-
-
Notifications
You must be signed in to change notification settings - Fork 341
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
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,4 @@ | ||
vendor | ||
composer.lock | ||
.php_cs.cache | ||
.phpunit.result.cache |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,3 @@ | ||
branches: ["2.x"] | ||
maintained_branches: ["2.x"] | ||
doc_dir: "doc" |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,5 @@ | ||
# CHANGELOG | ||
|
||
## Unreleased | ||
|
||
- Component added |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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. |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1 @@ | ||
export * from './translator'; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); | ||
} | ||
|
||
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()); | ||
} | ||
Kocal marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
||
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 }; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1 @@ | ||
module.exports = require('../../../jest.config.js'); |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
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:
{
and}
because here you're only looking for open brackets to trigger the cleanI'm suggesting below a different approach (you may use the test scenarios for the unit tests too):
I made a quick JSFiddle to show the result: https://jsfiddle.net/p6qnzs7t/18/
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.