kibana/packages/kbn-eslint-plugin-i18n/helpers/utils.ts
Luke Elmers b6287708f6
Adds AGPL 3.0 license (#192025)
Updates files outside of x-pack to be triple-licensed under Elastic
License 2.0, AGPL 3.0, or SSPL 1.0.
2024-09-06 19:02:41 -06:00

60 lines
1.7 KiB
TypeScript

/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the "Elastic License
* 2.0", the "GNU Affero General Public License v3.0 only", and the "Server Side
* Public License v 1"; you may not use this file except in compliance with, at
* your election, the "Elastic License 2.0", the "GNU Affero General Public
* License v3.0 only", or the "Server Side Public License, v 1".
*/
export function lowerCaseFirstLetter(str: string) {
if (isUpperCase(str)) return str.toLowerCase();
return str.charAt(0).toLowerCase() + str.slice(1);
}
export function upperCaseFirstLetter(str: string) {
return str.charAt(0).toUpperCase() + str.slice(1);
}
export function isTruthy<T>(value: T): value is NonNullable<T> {
return value != null;
}
function isUpperCase(val: string) {
return /^[A-Z]+$/.test(val);
}
export function geti18nIdentifierFromString(str: string) {
return str
.trim()
.replace(/```\w*```/g, '')
.replace(/[\'\"]+/g, '')
.replace(/\s+/g, ' ')
.split(' ')
.filter((_, i) => i <= 3)
.map(upperCaseFirstLetter)
.map((word, index) => (index === 0 ? word.toLowerCase() : word))
.join('')
.replace(/[^a-zA-Z\s]*/g, '');
}
export function getTranslatableValueFromString(str: string) {
const strTrimmed = str.trim();
if (strTrimmed.length === 1) {
return '';
}
// Markdown
if (strTrimmed.replace(/```\w*```/g, '').length === 0) {
return '';
}
// Special characters, numbers, and white spaces
if (strTrimmed.replace(/[!\@\#\$\%\^\&\*\(\)\_\+\{\}\|]|[0-9]|\s+/g, '').length === 0) {
return '';
}
return strTrimmed.replace(/'/g, "\\'");
}