Skip to content

Commit

Permalink
[Translator] Add Symfony UX Translator package
Browse files Browse the repository at this point in the history
  • Loading branch information
Kocal committed Dec 22, 2022
1 parent b6c86be commit 9ff2432
Show file tree
Hide file tree
Showing 41 changed files with 1,812 additions and 0 deletions.
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) 2020-2022 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.
13 changes: 13 additions & 0 deletions src/Translator/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
# Symfony UX Translator

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)
2 changes: 2 additions & 0 deletions src/Translator/assets/dist/formatters/formatter.d.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
import { Locale, MessageId } from '../types';
export declare function format(id: MessageId, parameters: Record<string, string | number> | undefined, domain: string | null | undefined, locale: Locale): string;
2 changes: 2 additions & 0 deletions src/Translator/assets/dist/formatters/icu-formatter.d.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
import { Domain, Locale, MessageId } from '../types';
export declare function formatIcu(id: MessageId, parameters: Record<string, string | number> | undefined, domain: Domain, locale: Locale): string;
2 changes: 2 additions & 0 deletions src/Translator/assets/dist/formatters/intl-formatter.d.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
import { Domain, Locale, MessageId } from '../types';
export declare function formatIntl(id: MessageId, parameters: Record<string, string | number> | undefined, domain: Domain, locale: Locale): string;
12 changes: 12 additions & 0 deletions src/Translator/assets/dist/translator.d.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
import { Domain, Locale, MessageId, MessageValue } from './types';
declare global {
interface Window {
__symfony_ux_translator?: {
locale: Locale;
translations: Record<Locale, Record<Domain, Record<MessageId, MessageValue>>>;
};
setTranslatorLocale(locale: Locale): void;
}
}
export declare function setLocale(locale: string): void;
export declare function trans(id: MessageId | null, parameters?: Record<string, string | number>, domain?: Domain, locale?: Locale | null): 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';
227 changes: 227 additions & 0 deletions src/Translator/assets/dist/translator_controller.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,227 @@
import { IntlMessageFormat } from 'intl-messageformat';

function formatIntl(id, parameters = {}, domain, 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);
}

function strtr(string, replacePairs) {
const regex = Object.entries(replacePairs).map(([from, to]) => {
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 = {}, domain = null, 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;
}
}

function setLocale(locale) {
window.__symfony_ux_translator.locale = locale;
}
function trans(id, parameters = {}, domain = 'messages', locale = null) {
var _a, _b, _c, _d;
if (null === id || '' === id) {
return '';
}
if (typeof window.__symfony_ux_translator === 'undefined') {
throw new Error('The Translator is not initialized. Did you forget to call the Twig function "initialize_js_translator()"?');
}
locale = locale || window.__symfony_ux_translator.locale;
if (!locale) {
throw new Error('No locale has been configured. Did you forget to call the Twig function "initialize_js_translator()"?');
}
if (typeof window.__symfony_ux_translator.translations[locale] === 'undefined') {
return id;
}
let translatedId = (_b = (_a = window.__symfony_ux_translator.translations[locale]) === null || _a === void 0 ? void 0 : _a[domain + '+intl-icu']) === null || _b === void 0 ? void 0 : _b[id];
if (typeof translatedId === 'string') {
return formatIntl(translatedId, parameters, domain, locale);
}
translatedId = (_d = (_c = window.__symfony_ux_translator.translations[locale]) === null || _c === void 0 ? void 0 : _c[domain]) === null || _d === void 0 ? void 0 : _d[id];
if (typeof translatedId === 'string') {
return format(translatedId, parameters, domain, locale);
}
return id;
}

export { setLocale, 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;
7 changes: 7 additions & 0 deletions src/Translator/assets/jest.config.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
const { defaults } = require('jest-config');
const jestConfig = require('../../../jest.config.js');

jestConfig.moduleFileExtensions = [...defaults.moduleFileExtensions, 'vue'];
jestConfig.transform['^.+\\.vue$'] = ['@vue/vue3-jest'];

module.exports = jestConfig;
15 changes: 15 additions & 0 deletions src/Translator/assets/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
{
"name": "@symfony/ux-translator",
"description": "Symfony Translator for JavaScript",
"license": "MIT",
"version": "1.0.0",
"main": "dist/translator_controller.js",
"types": "dist/translator_controller.d.ts",
"peerDependencies": {
"intl-messageformat": "^10.2.5"
},
"devDependencies": {
"intl-messageformat": "^10.2.5",
"ts-jest": "^27.1.5"
}
}
Loading

0 comments on commit 9ff2432

Please sign in to comment.