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

[Translator] Add Symfony UX Translator package #616

Merged
merged 1 commit into from
Apr 24, 2023
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
17 changes: 17 additions & 0 deletions .github/workflows/test.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -164,6 +164,15 @@ jobs:
working-directory: src/Autocomplete
run: php vendor/bin/simple-phpunit

- name: Translator Dependencies
uses: ramsey/composer-install@v2
with:
working-directory: src/Translator
dependency-versions: lowest
- name: Translator Tests
run: php vendor/bin/simple-phpunit
working-directory: src/Translator

tests-php-high-deps:
runs-on: ubuntu-latest
steps:
Expand Down Expand Up @@ -261,6 +270,14 @@ jobs:
- name: Notify Tests
working-directory: src/Notify
run: php vendor/bin/simple-phpunit

- name: Translator Dependencies
uses: ramsey/composer-install@v2
with:
working-directory: src/Translator
- name: Translator Tests
working-directory: src/Translator
run: php vendor/bin/simple-phpunit

tests-js:
runs-on: ubuntu-latest
Expand Down
8 changes: 8 additions & 0 deletions src/Translator/.gitattributes
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
/.gitattributes export-ignore
/.gitignore export-ignore
/.symfony.bundle.yaml export-ignore
/phpunit.xml.dist export-ignore
/assets/src export-ignore
/assets/test export-ignore
/assets/jest.config.js export-ignore
/tests export-ignore
4 changes: 4 additions & 0 deletions src/Translator/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
vendor
composer.lock
.php_cs.cache
.phpunit.result.cache
3 changes: 3 additions & 0 deletions src/Translator/.symfony.bundle.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
branches: ["2.x"]
maintained_branches: ["2.x"]
doc_dir: "doc"
5 changes: 5 additions & 0 deletions src/Translator/CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
# CHANGELOG

## Unreleased

- Component added
19 changes: 19 additions & 0 deletions src/Translator/LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
Copyright (c) 2023-present Fabien Potencier

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is furnished
to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
16 changes: 16 additions & 0 deletions src/Translator/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
# Symfony UX Translator

**EXPERIMENTAL** This component is currently experimental and is
likely to change, or even change drastically.

Symfony UX Translator integrates [Symfony Translation](https://symfony.com/doc/current/translation.html) for JavaScript.

**This repository is a READ-ONLY sub-tree split**. See
https://github.com/symfony/ux to create issues or submit pull requests.

## Resources

- [Documentation](https://symfony.com/bundles/ux-translator/current/index.html)
- [Report issues](https://github.com/symfony/ux/issues) and
[send Pull Requests](https://github.com/symfony/ux/pulls)
in the [main Symfony UX repository](https://github.com/symfony/ux)
1 change: 1 addition & 0 deletions src/Translator/assets/dist/formatters/formatter.d.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export declare function format(id: string, parameters: Record<string, string | number> | undefined, locale: string): string;
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export declare function formatIntl(id: string, parameters: Record<string, string | number> | undefined, locale: string): string;
26 changes: 26 additions & 0 deletions src/Translator/assets/dist/translator.d.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
export type DomainType = string;
export type LocaleType = string;
export type TranslationsType = Record<DomainType, {
parameters: ParametersType;
}>;
export type NoParametersType = Record<string, never>;
export type ParametersType = Record<string, string | number> | NoParametersType;
export type RemoveIntlIcuSuffix<T> = T extends `${infer U}+intl-icu` ? U : T;
export type DomainsOf<M> = M extends Message<infer Translations, LocaleType> ? keyof Translations : never;
export type LocaleOf<M> = M extends Message<TranslationsType, infer Locale> ? Locale : never;
export type ParametersOf<M, D extends DomainType> = M extends Message<infer Translations, LocaleType> ? Translations[D] extends {
parameters: infer Parameters;
} ? Parameters : never : never;
export interface Message<Translations extends TranslationsType, Locale extends LocaleType> {
id: string;
translations: {
[domain in DomainType]: {
[locale in Locale]: string;
};
};
}
export declare function setLocale(locale: LocaleType | null): void;
export declare function getLocale(): LocaleType;
export declare function setLocaleFallbacks(localeFallbacks: Record<LocaleType, LocaleType>): void;
export declare function getLocaleFallbacks(): Record<LocaleType, LocaleType>;
export declare function trans<M extends Message<TranslationsType, LocaleType>, D extends DomainsOf<M>, P extends ParametersOf<M, D>>(...args: P extends NoParametersType ? [message: M, parameters?: P, domain?: RemoveIntlIcuSuffix<D>, locale?: LocaleOf<M>] : [message: M, parameters: P, domain?: RemoveIntlIcuSuffix<D>, locale?: LocaleOf<M>]): string;
1 change: 1 addition & 0 deletions src/Translator/assets/dist/translator_controller.d.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export * from './translator';
253 changes: 253 additions & 0 deletions src/Translator/assets/dist/translator_controller.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,253 @@
import { IntlMessageFormat } from 'intl-messageformat';

function formatIntl(id, parameters = {}, locale) {
if (id === '') {
return '';
}
const intlMessage = new IntlMessageFormat(id, [locale.replace('_', '-')], undefined, { ignoreTag: true });
parameters = Object.assign({}, parameters);
Object.entries(parameters).forEach(([key, value]) => {
if (key.includes('%') || key.includes('{')) {
delete parameters[key];
parameters[key.replace(/[%{} ]/g, '').trim()] = value;
}
});
return intlMessage.format(parameters);
}

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This function has two drawbacks that you may want to solve:

  1. it is updating the parent object "parameters" without making a proper copy
  2. it's unclear from your regex what is the expected behavior for cleaning { and } because here you're only looking for open brackets to trigger the clean
  3. (also the if is not really needed if you use a regex)

I'm suggesting below a different approach (you may use the test scenarios for the unit tests too):

function sample(parameters = {}) {
  Object.entries(parameters).forEach(([key, value]) => {
    if (key.includes('%') || key.includes('{')) {
      delete parameters[key];
      parameters[key.replace(/[%{} ]/g, '').trim()] = value;
    }
  });
  return parameters
}

function rework(parameters = {}) {
  return Object.entries(parameters).reduce((acc, [key, value]) => {
    return {
      ...acc,
      [key.replace(/[%{} ]/g, '').trim()]: value
    }
  }, {});
}

const parameters = {
  'example1': 'content1',
  'example2%': 'content2',
  '{example3}': 'content3',
  '%{ example4 }%': 'content4',
  'example5 }': 'content5',
  'example6% }': 'content6'
}

console.log('params', parameters);

console.log('rework', rework(parameters));
console.log('params', parameters);

console.log('sample', sample(parameters));
console.log('params', parameters);

I made a quick JSFiddle to show the result: https://jsfiddle.net/p6qnzs7t/18/

Copy link
Member Author

@Kocal Kocal Dec 18, 2022

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

  1. Fixed, thanks
  2. As said on Discord (:eyes:), the logic is taken from the Symfony Translator in its PHP version (https://github.com/symfony/symfony/blob/6.3/src/Symfony/Component/Translation/Formatter/IntlFormatter.php#L45), so I prefer keep the same logic instead.
  3. Usually you want to quickly check if one of the concerned character can be found before using the regex, to prevent performances loss if you directly use (parse + run) the regex. However I don't know how its behave with JavaScript.


function strtr(string, replacePairs) {
const regex = Object.entries(replacePairs).map(([from]) => {
return from.replace(/([-[\]{}()*+?.\\^$|#,])/g, '\\$1');
});
if (regex.length === 0) {
return string;
}
return string.replace(new RegExp(regex.join('|'), 'g'), (matched) => replacePairs[matched].toString());
}

function format(id, parameters = {}, locale) {
if (null === id || '' === id) {
return '';
}
if (typeof parameters['%count%'] === 'undefined' || Number.isNaN(parameters['%count%'])) {
return strtr(id, parameters);
}
const number = Number(parameters['%count%']);
let parts = [];
if (/^\|+$/.test(id)) {
parts = id.split('|');
}
else {
const matches = id.match(/(?:\|\||[^|])+/g);
if (matches !== null) {
parts = matches;
}
}
const intervalRegex = /^(?<interval>({\s*(-?\d+(\.\d+)?[\s*,\s*\-?\d+(.\d+)?]*)\s*})|(?<left_delimiter>[[\]])\s*(?<left>-Inf|-?\d+(\.\d+)?)\s*,\s*(?<right>\+?Inf|-?\d+(\.\d+)?)\s*(?<right_delimiter>[[\]]))\s*(?<message>.*?)$/s;
const standardRules = [];
for (let part of parts) {
part = part.trim().replace(/\|\|/g, '|');
let matches = part.match(intervalRegex);
if (matches !== null) {
if (matches[2]) {
for (const n of matches[3].split(',')) {
if (number === Number(n)) {
return strtr(matches.groups['message'], parameters);
}
}
}
else {
const leftNumber = '-Inf' === matches.groups['left'] ? Number.NEGATIVE_INFINITY : Number(matches.groups['left']);
const rightNumber = ['Inf', '+Inf'].includes(matches.groups['right']) ? Number.POSITIVE_INFINITY : Number(matches.groups['right']);
if (('[' === matches.groups['left_delimiter'] ? number >= leftNumber : number > leftNumber)
&& (']' === matches.groups['right_delimiter'] ? number <= rightNumber : number < rightNumber)) {
return strtr(matches.groups['message'], parameters);
}
}
}
else {
matches = part.match(/^\w+:\s*(.*?)$/);
if (matches !== null) {
standardRules.push(matches[1]);
}
else {
standardRules.push(part);
}
}
}
const position = getPluralizationRule(number, locale);
if (typeof standardRules[position] === 'undefined') {
if (1 === parts.length && typeof standardRules[0] !== 'undefined') {
return strtr(standardRules[0], parameters);
}
throw new Error(`Unable to choose a translation for "${id}" with locale "${locale}" for value "${number}". Double check that this translation has the correct plural options (e.g. "There is one apple|There are %count% apples").`);
}
return strtr(standardRules[position], parameters);
}
function getPluralizationRule(number, locale) {
number = Math.abs(number);
let _locale = locale;
if (locale === 'pt_BR' || locale === 'en_US_POSIX') {
return 0;
}
_locale = _locale.length > 3 ? _locale.substring(0, _locale.indexOf('_')) : _locale;
switch (_locale) {
case 'af':
case 'bn':
case 'bg':
case 'ca':
case 'da':
case 'de':
case 'el':
case 'en':
case 'en_US_POSIX':
case 'eo':
case 'es':
case 'et':
case 'eu':
case 'fa':
case 'fi':
case 'fo':
case 'fur':
case 'fy':
case 'gl':
case 'gu':
case 'ha':
case 'he':
case 'hu':
case 'is':
case 'it':
case 'ku':
case 'lb':
case 'ml':
case 'mn':
case 'mr':
case 'nah':
case 'nb':
case 'ne':
case 'nl':
case 'nn':
case 'no':
case 'oc':
case 'om':
case 'or':
case 'pa':
case 'pap':
case 'ps':
case 'pt':
case 'so':
case 'sq':
case 'sv':
case 'sw':
case 'ta':
case 'te':
case 'tk':
case 'ur':
case 'zu':
return (1 == number) ? 0 : 1;
case 'am':
case 'bh':
case 'fil':
case 'fr':
case 'gun':
case 'hi':
case 'hy':
case 'ln':
case 'mg':
case 'nso':
case 'pt_BR':
case 'ti':
case 'wa':
return (number < 2) ? 0 : 1;
case 'be':
case 'bs':
case 'hr':
case 'ru':
case 'sh':
case 'sr':
case 'uk':
return ((1 == number % 10) && (11 != number % 100)) ? 0 : (((number % 10 >= 2) && (number % 10 <= 4) && ((number % 100 < 10) || (number % 100 >= 20))) ? 1 : 2);
case 'cs':
case 'sk':
return (1 == number) ? 0 : (((number >= 2) && (number <= 4)) ? 1 : 2);
case 'ga':
return (1 == number) ? 0 : ((2 == number) ? 1 : 2);
case 'lt':
return ((1 == number % 10) && (11 != number % 100)) ? 0 : (((number % 10 >= 2) && ((number % 100 < 10) || (number % 100 >= 20))) ? 1 : 2);
case 'sl':
return (1 == number % 100) ? 0 : ((2 == number % 100) ? 1 : (((3 == number % 100) || (4 == number % 100)) ? 2 : 3));
case 'mk':
return (1 == number % 10) ? 0 : 1;
case 'mt':
return (1 == number) ? 0 : (((0 == number) || ((number % 100 > 1) && (number % 100 < 11))) ? 1 : (((number % 100 > 10) && (number % 100 < 20)) ? 2 : 3));
case 'lv':
return (0 == number) ? 0 : (((1 == number % 10) && (11 != number % 100)) ? 1 : 2);
case 'pl':
return (1 == number) ? 0 : (((number % 10 >= 2) && (number % 10 <= 4) && ((number % 100 < 12) || (number % 100 > 14))) ? 1 : 2);
case 'cy':
return (1 == number) ? 0 : ((2 == number) ? 1 : (((8 == number) || (11 == number)) ? 2 : 3));
case 'ro':
return (1 == number) ? 0 : (((0 == number) || ((number % 100 > 0) && (number % 100 < 20))) ? 1 : 2);
case 'ar':
return (0 == number) ? 0 : ((1 == number) ? 1 : ((2 == number) ? 2 : (((number % 100 >= 3) && (number % 100 <= 10)) ? 3 : (((number % 100 >= 11) && (number % 100 <= 99)) ? 4 : 5))));
default:
return 0;
}
}

let _locale = null;
let _localeFallbacks = {};
function setLocale(locale) {
_locale = locale;
}
function getLocale() {
return (_locale ||
document.documentElement.getAttribute('data-symfony-ux-translator-locale') ||
document.documentElement.lang ||
'en');
}
function setLocaleFallbacks(localeFallbacks) {
_localeFallbacks = localeFallbacks;
}
function getLocaleFallbacks() {
return _localeFallbacks;
}
function trans(message, parameters = {}, domain = 'messages', locale = null) {
if (typeof domain === 'undefined') {
domain = 'messages';
}
if (typeof locale === 'undefined' || null === locale) {
locale = getLocale();
}
if (typeof message.translations === 'undefined') {
return message.id;
}
const localesFallbacks = getLocaleFallbacks();
const translationsIntl = message.translations[`${domain}+intl-icu`];
if (typeof translationsIntl !== 'undefined') {
while (typeof translationsIntl[locale] === 'undefined') {
locale = localesFallbacks[locale];
if (!locale) {
break;
}
}
if (locale) {
return formatIntl(translationsIntl[locale], parameters, locale);
}
}
const translations = message.translations[domain];
if (typeof translations !== 'undefined') {
while (typeof translations[locale] === 'undefined') {
locale = localesFallbacks[locale];
if (!locale) {
break;
}
}
if (locale) {
return format(translations[locale], parameters, locale);
}
}
return message.id;
}

export { getLocale, getLocaleFallbacks, setLocale, setLocaleFallbacks, trans };
1 change: 1 addition & 0 deletions src/Translator/assets/dist/utils.d.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export declare function strtr(string: string, replacePairs: Record<string, string | number>): string;
1 change: 1 addition & 0 deletions src/Translator/assets/jest.config.js
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
module.exports = require('../../../jest.config.js');
Loading