Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

adjusts to translate api #25709

Merged
merged 1 commit into from
Apr 6, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
76 changes: 49 additions & 27 deletions generators/angular/support/translate-angular.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import { extname } from 'node:path';
import { passthrough } from '@yeoman/transform';
import { Minimatch } from 'minimatch';

Expand All @@ -24,7 +25,8 @@ import {
createJhiTransformTranslateReplacer,
createJhiTransformTranslateStringifyReplacer,
createJhiTranslateReplacer,
escapeTranslationValue,
escapeHtmlTranslationValue,
escapeTsTranslationValue,
} from '../../languages/support/index.js';

const PLACEHOLDER_REGEX = /(?:placeholder|title)=['|"](\{\{\s?['|"]([a-zA-Z0-9.\-_]+)['|"]\s?\|\s?translate\s?\}\})['|"]/.source;
Expand Down Expand Up @@ -132,7 +134,7 @@ const tagTranslation = (
const translatedValueInterpolate = parsedInterpolate
? Object.fromEntries(Object.entries(parsedInterpolate).map(([key, value]) => [key, `{{ ${value} }}`]))
: undefined;
const translatedValue = escapeTranslationValue(getTranslationValue(getWebappTranslation, key, translatedValueInterpolate));
const translatedValue = escapeHtmlTranslationValue(getTranslationValue(getWebappTranslation, key, translatedValueInterpolate));

if (enableTranslation) {
const translateValuesAttr = parsedInterpolate
Expand All @@ -158,7 +160,7 @@ const validationTagTranslation = (
if (!parsedInterpolate || Object.keys(parsedInterpolate).length === 0) {
throw new Error(`No interpolation values found for translation key ${key}, use __jhiTranslateTag__ instead.`);
}
const translatedValue = escapeTranslationValue(getTranslationValue(getWebappTranslation, key, parsedInterpolate));
const translatedValue = escapeHtmlTranslationValue(getTranslationValue(getWebappTranslation, key, parsedInterpolate));

if (enableTranslation) {
const translateValuesAttr = parsedInterpolate
Expand Down Expand Up @@ -187,7 +189,7 @@ const tagPipeTranslation = (
const translatedValueInterpolate = Object.fromEntries(
Object.entries(parsedInterpolate).map(([key, value]) => [key, getWebappTranslation(value)]),
);
const translatedValue = escapeTranslationValue(getTranslationValue(getWebappTranslation, key, translatedValueInterpolate));
const translatedValue = escapeHtmlTranslationValue(getTranslationValue(getWebappTranslation, key, translatedValueInterpolate));
if (enableTranslation) {
const translateValuesAttr = ` [translateValues]="{ ${Object.entries(parsedInterpolate)
.map(([key, value]) => `${key}: ('${value}' | translate)`)
Expand Down Expand Up @@ -232,7 +234,25 @@ const pipeTranslation = (
return `${prefix}{{ '${key}' | translate }}${suffix}`;
}

return `${prefix}${escapeTranslationValue(getTranslationValue(getWebappTranslation, key))}${suffix}`;
return `${prefix}${escapeHtmlTranslationValue(getTranslationValue(getWebappTranslation, key))}${suffix}`;
};

/**
* Get translation value.
*/
const valueTranslation = (
getWebappTranslation: any,
_replacerOptions: ReplacerOptions,
{ filePath, key, prefix, suffix }: JHITranslateConverterOptions,
) => {
let translationValue = getTranslationValue(getWebappTranslation, key);
const fileExtension = extname(filePath);
if (fileExtension === '.html') {
translationValue = escapeHtmlTranslationValue(translationValue);
} else if (fileExtension === '.ts') {
translationValue = escapeTsTranslationValue(translationValue);
}
return `${prefix}${translationValue}${suffix}`;
};

/**
Expand All @@ -256,6 +276,19 @@ const pipeEnumTranslation = (
return `${prefix}${translatedValue}${suffix}`;
};

const replaceImplementations: Record<
string,
(getWebappTranslation: any, replacerOpts: ReplacerOptions, translateOpts: JHITranslateConverterOptions) => string
> = {
Tag: tagTranslation,
TagPipe: tagPipeTranslation,
TagEnum: tagEnumTranslation,
ValidationTag: validationTagTranslation,
Pipe: pipeTranslation,
PipeEnum: pipeEnumTranslation,
Value: valueTranslation,
};

/**
* Replace and cleanup translations.
*
Expand All @@ -265,30 +298,17 @@ const pipeEnumTranslation = (
export const createTranslationReplacer = (getWebappTranslation, opts: ReplacerOptions | boolean) => {
const htmlJhiTranslateReplacer = createJhiTransformTranslateReplacer(getWebappTranslation, { escapeHtml: true });
const htmlJhiTranslateStringifyReplacer = createJhiTransformTranslateStringifyReplacer(getWebappTranslation);
let translationReplacer: ((content: string) => string) | undefined;
let translationReplacer: ((content: string, filePath: string) => string) | undefined;
const enableTranslation = typeof opts === 'boolean' ? opts : opts.enableTranslation;
if (typeof opts !== 'boolean') {
translationReplacer = createJhiTranslateReplacer(
optsReplacer => {
if (optsReplacer.type === 'Tag') {
return tagTranslation(getWebappTranslation, opts, optsReplacer);
}
if (optsReplacer.type === 'TagPipe') {
return tagPipeTranslation(getWebappTranslation, opts, optsReplacer);
}
if (optsReplacer.type === 'TagEnum') {
return tagEnumTranslation(getWebappTranslation, opts, optsReplacer);
}
if (optsReplacer.type === 'ValidationTag') {
return validationTagTranslation(getWebappTranslation, opts, optsReplacer);
}
if (optsReplacer.type === 'Pipe') {
return pipeTranslation(getWebappTranslation, opts, optsReplacer);
}
if (optsReplacer.type === 'PipeEnum') {
return pipeEnumTranslation(getWebappTranslation, opts, optsReplacer);
}
throw new Error(`Translation type not supported ${optsReplacer.type}`);
const replacer =
replaceImplementations[optsReplacer.type] ??
(() => {
throw new Error(`Translation type not supported ${optsReplacer.type}`);
});
return replacer(getWebappTranslation, opts, optsReplacer);
},
{ prefixPattern: '>\\s*', suffixPattern: '\\s*<' },
);
Expand All @@ -304,7 +324,9 @@ export const createTranslationReplacer = (getWebappTranslation, opts: ReplacerOp
if (/(:?\.html|component\.ts)$/.test(filePath)) {
content = htmlJhiTranslateReplacer(content);
content = htmlJhiTranslateStringifyReplacer(content);
content = translationReplacer?.(content);
}
if (/(:?\.html|.ts)$/.test(filePath)) {
content = translationReplacer?.(content, filePath);
}
if (!enableTranslation) {
if (/(:?route|module)\.ts$/.test(filePath)) {
Expand All @@ -318,7 +340,7 @@ export const createTranslationReplacer = (getWebappTranslation, opts: ReplacerOp
};
};

const minimatch = new Minimatch('**/*{.html,.component.ts,.route.ts,.module.ts}');
const minimatch = new Minimatch('**/*{.html,.ts}');
export const isTranslatedAngularFile = file => minimatch.match(file.path);

export const translateAngularFilesTransform = (getWebappTranslation, opts: ReplacerOptions | boolean) => {
Expand Down
14 changes: 9 additions & 5 deletions generators/languages/support/translate.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,9 +19,11 @@

const TRANSLATE_FUNCTION_ARGS = /\(\s*'(?<key>[^']+)'(?:,\s*(?<interpolate>\{(?:(?!\}\))[\s\S])*\}))?\)/gs.source;

export const escapeTranslationValue = (translation: string) =>
export const escapeHtmlTranslationValue = (translation: string) =>
translation.replace(/'/g, '&apos;').replace(/"/g, '&quot;').replace(/@/g, '&#64;');

export const escapeTsTranslationValue = (translation: string) => translation.replace(/'/g, "\\'").replace(/\\/g, '\\\\');

function getTranslationValue(getWebappTranslation, key, data) {
return getWebappTranslation(key, data) || undefined;
}
Expand Down Expand Up @@ -84,7 +86,7 @@ export const replaceTranslationKeysWithText = (
replacement = `${wrapTranslation[0]}${translation}${wrapTranslation[1]}`;
} else if (escapeHtml) {
// Escape specific chars
replacement = escapeTranslationValue(replacement);
replacement = escapeHtmlTranslationValue(replacement);
} else if (stringify) {
replacement = JSON.stringify(replacement);
}
Expand All @@ -102,6 +104,7 @@ export const createJhiTransformTranslateStringifyReplacer = getWebappTranslation
});

export type JHITranslateConverterOptions = {
filePath: string;
/** Translation type */
type: string;
/** Translation key */
Expand All @@ -118,7 +121,7 @@ export type JHITranslateConverterOptions = {

export type JHITranslateConverter = (opts: JHITranslateConverterOptions) => string;

export const replaceTranslateContents = (body: string, regexp: string, converter: JHITranslateConverter) => {
export const replaceTranslateContents = (body: string, filePath: string, regexp: string, converter: JHITranslateConverter) => {
const matches = [...body.matchAll(new RegExp(regexp, 'g'))].reverse();
for (const match of matches) {
const target = match[0];
Expand All @@ -141,7 +144,7 @@ export const replaceTranslateContents = (body: string, regexp: string, converter
}
}

body = `${body.slice(0, match.index!)}${converter({ key, interpolate, parsedInterpolate, type, prefix, suffix })}${body.slice(match.index! + target.length)}`;
body = `${body.slice(0, match.index!)}${converter({ filePath, key, interpolate, parsedInterpolate, type, prefix, suffix })}${body.slice(match.index! + target.length)}`;
}
return body;
};
Expand All @@ -155,9 +158,10 @@ export type JHITranslateReplacerOptions = {

export const createJhiTranslateReplacer =
(converter: JHITranslateConverter, { prefixPattern = '', suffixPattern = '' }: JHITranslateReplacerOptions = {}) =>
(body: string) =>
(body: string, filePath: string) =>
replaceTranslateContents(
body,
filePath,
`${prefixPattern ? `(?<prefix>(${prefixPattern}))?` : ''}__jhiTranslate(?<type>(\\w+))__${TRANSLATE_FUNCTION_ARGS}${suffixPattern ? `(?<suffix>(${suffixPattern}))?` : ''}`,
converter,
);
Loading