-
-
Notifications
You must be signed in to change notification settings - Fork 7
feat: localize JS keyboard search 🗺️ #658
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
Open
darcywong00
wants to merge
20
commits into
master
Choose a base branch
from
feat/search-i18n
base: master
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+298
−27
Open
Changes from all commits
Commits
Show all changes
20 commits
Select commit
Hold shift + click to select a range
3ad32cf
diy for localizing JS search strings
darcywong00 6025c6a
refactor: make module to import json
darcywong00 ef90f13
refactor: Add crowdinContext to JSON files
darcywong00 71e1823
fix: Add string for no keyboard found
darcywong00 a35c18e
wrap i18n in a class
darcywong00 e869119
Apply suggestions from code review
darcywong00 e87862c
rename search.js --> search.mjs
darcywong00 c9a7bfb
revert api line
darcywong00 0b7dc5d
Fix objNavigate nesting
darcywong00 f525485
chore: cleanup TODO
darcywong00 2caf7cf
revert legacy/ keyboard search
darcywong00 78f81e7
Merge remote-tracking branch 'origin/master' into feat/search-i18n
darcywong00 8088ca2
start adding namespace to strings
darcywong00 33c7964
collapse json files
darcywong00 84a08d0
fix: Handle fallback to 'en' strings
darcywong00 1caf14e
fix: cleanup fallbacks
darcywong00 b5e93b2
fix monthly download strings
darcywong00 a88d5cb
Add reviewed Spanish strings
darcywong00 4821955
fix: Update crowdin.yml to handle *.json files
darcywong00 70ef033
fix paging strings again
darcywong00 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
Some comments aren't visible on the classic Files Changed page.
There are no files selected for viewing
This file contains hidden or 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 hidden or 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 hidden or 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,201 @@ | ||
| /** | ||
| * Keyman is copyright (c) SIL Global. MIT License | ||
| * | ||
| * Vanilla JS for localizing keyboard search strings without a framework | ||
| * Reference: https://medium.com/@mihura.ian/translations-in-vanilla-javascript-c942c2095170 | ||
| */ | ||
|
|
||
| export class I18n { | ||
|
|
||
| static DEFAULT_LOCALE = 'en'; | ||
|
|
||
| // Array of the supported locales | ||
| static currentLocales = []; | ||
|
|
||
| static currentDomain = ''; | ||
|
|
||
| // strings is an array of domains. | ||
| // Each domain is an array of locales | ||
| // Each locale is an object? with loaded flag and array of strings | ||
| static strings = []; | ||
|
|
||
|
|
||
| /** | ||
| * Set the current locales, with an array of fallbacks, ending in 'en' | ||
| * @param {locale} The new current locale | ||
| */ | ||
| static setLocale(locale) { | ||
| // Clean current locales | ||
| I18n.currentLocales = []; | ||
|
|
||
| if (!locale) { | ||
| I18n.currentLocales = I18n.calculateFallbackLocales(locale); | ||
| } | ||
|
|
||
| // Push default ballback locale to the end | ||
| I18n.currentLocales.push(I18n.DEFAULT_LOCALE); | ||
| } | ||
|
|
||
| /** | ||
| * Load the strings for the given domain | ||
| * @param {string} domain | ||
| */ | ||
| static loadDomain(domain) { | ||
| if (!I18n.strings[domain]) { | ||
| I18n.strings[domain] = []; | ||
| } | ||
| I18n.strings[domain][I18n.DEFAULT_LOCALE] = { | ||
| strings: [], | ||
| loaded: false | ||
| } | ||
| } | ||
|
|
||
| /** | ||
| * Defines a global variable for page locale strings and also | ||
| * tells locale system that current page uses locales | ||
| * @param $domain - | ||
| * @param $id - folder containing locale strings, relative to /cdn/dev/js/i18n | ||
| */ | ||
| static async definePageLocale(domain, id) { | ||
| I18n.currentDomain = domain; | ||
| if (!I18n.strings.hasOwnProperty(id)) { | ||
| I18n.strings[id] = []; | ||
| } | ||
| await I18n.loadStrings(domain, I18n.DEFAULT_LOCALE); | ||
| } | ||
|
|
||
| /** | ||
| * Given a locale, return an array of fallback locales | ||
| * For example: es-ES --> [es, es-ES] | ||
| * TODO: Use an existing fallback algorthim like | ||
| * https://cldr.unicode.org/development/development-process/design-proposals/language-distance-data | ||
| * @param $locale - the locale to determine fallback locales | ||
| * @return array of fallback locales | ||
| */ | ||
| static calculateFallbackLocales(locale) { | ||
| // Start with the given locale | ||
| var fallback = [locale]; | ||
|
|
||
| // Support other fallbacks such as es-419 -> es | ||
| var parts = locale.split('-'); | ||
| for (var i = parts.length-1; i > 0; i--) { | ||
| var lastPosition = locale.lastIndexOf(parts[i]) - 1; | ||
| // Insert language tag substring to head | ||
| fallback.unshift(locale.substr(0, lastPosition)); | ||
| } | ||
|
|
||
| return fallback; | ||
| } | ||
|
|
||
| /** | ||
| * Dynamically load translation for a language if not already added | ||
| * @param {String} lang | ||
| */ | ||
| static async loadStrings(domain, lang) { | ||
| var currentLocaleFilename = `./${domain}/${lang}.json`; | ||
| I18n.currentDomain = domain; | ||
|
|
||
| try { | ||
| const jsModule = await import(currentLocaleFilename, { | ||
| with: { type: 'json'} | ||
| }); | ||
| I18n.strings[I18n.currentDomain][lang] = { | ||
| strings: jsModule.default, | ||
| loaded: true | ||
| }; | ||
| } catch (ex) { | ||
| // JSON localization file doesn't exist. Log to sentry? | ||
| //console.warn(`${domain}/${lang}.json doesn't exist. Not loading...`); | ||
| } | ||
| } | ||
|
|
||
| /** | ||
| * Navigates inside `obj` with `path` string, | ||
| * | ||
| * Usage: | ||
| * objNavigate({a: {b: {c: 123}}}, "a.b.c") // returns 123 | ||
| * | ||
| * Fails silently. | ||
| * @param {obj} obj | ||
| * @param {String} path to navigate into obj | ||
| * @returns String or undefined if variable is not found. | ||
| */ | ||
| static objNavigate(obj, path){ | ||
| var aPath = path.split('.'); | ||
| try { | ||
| return aPath.reduce((a, v) => a[v], obj); | ||
| } catch { | ||
| return; | ||
| } | ||
| }; | ||
|
|
||
| /** | ||
| * Interpolates variables wrapped with `{}` in `str` with variables in `obj` | ||
| * It will replace what it can, and leave the rest untouched | ||
| * | ||
| * Usage: | ||
| * | ||
| * named variables: | ||
| * strObjInterpolation("I'm {age} years old!", { age: 29 }); | ||
| * | ||
| * ordered variables | ||
| * strObjInterpolation("The {0} says {1}, {1}, {1}!", ['cow', 'moo']); | ||
| */ | ||
| static strObjInterpolation(str, obj){ | ||
| obj = obj || []; | ||
| str = str ? str.toString() : ''; | ||
| return str.replace( | ||
| /{([^{}]*)}/g, | ||
| (a, b) => { | ||
| const r = obj[b]; | ||
| return typeof r === 'string' || typeof r === 'number' ? r : a; | ||
| }, | ||
| ); | ||
| }; | ||
|
|
||
| /** | ||
| * Determine the display UI language for the keyboard search | ||
| * Navigate the translation JSON | ||
| * @param {string} domain of the localized strings | ||
| * @param {string} key for the string | ||
| * @param {obj} interpolations for optional formatted parameters | ||
| * @returns localized string | ||
| */ | ||
| static async t(domain, key, interpolations) { | ||
| // Load the domain if it doesn't exist | ||
| if (!I18n.strings[domain]) { | ||
| loadDomain(domain); | ||
| } | ||
|
|
||
| // embed_lang set by session.php | ||
| var language = embed_lang ?? I18n.DEFAULT_LOCALE; | ||
| if (I18n.currentDomain) { | ||
| if (!I18n.strings[domain][language]) { | ||
| var obj = { | ||
| strings: {}, | ||
| loaded: false | ||
| }; | ||
| I18n.strings[domain][language] = obj; | ||
| } | ||
| if (!I18n.strings[domain][language].loaded) { | ||
| // Will set -> loaded = true | ||
| await I18n.loadStrings(domain, language); | ||
| } | ||
| } | ||
|
|
||
| if (!I18n.strings[I18n.currentDomain][language] || !I18n.strings[I18n.currentDomain][language].strings[key]) { | ||
| // Langage or key is missing, so fallback to "en" | ||
| // Log to Sentry? | ||
| // console.warn(`i18n for language: '${language}' for '${key}' missing, fallback to 'en'`); | ||
| language = I18n.DEFAULT_LOCALE; | ||
| } | ||
|
|
||
| const value = I18n.objNavigate(I18n.strings[I18n.currentDomain][language].strings, key); | ||
| if (!value) { | ||
| // Warn if string doesn't exist | ||
| console.log(`Missing '${I18n.currentDomain}/${language}.json' string for '${key}'`); | ||
| } | ||
| return I18n.strObjInterpolation(value, interpolations); | ||
| } | ||
|
|
||
| } | ||
This file contains hidden or 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,15 @@ | ||
| { | ||
| "resultOne": "result", | ||
| "resultMore": "results", | ||
| "pageNumberOfTotalPages": "page {pageNumber} of {totalPages}.", | ||
| "keyboardSearchTitle": "- Keyboard search", | ||
| "obsoleteKeyboards": "Obsolete keyboards", | ||
| "monthlyDownloadZero": "No recent downloads", | ||
| "monthlyDownloadOne": "monthly download", | ||
| "monthlyDownloadMore": "monthly downloads", | ||
| "notUnicode": "Note: Not a Unicode keyboard", | ||
| "designedForPlatform": "Designed for {platform}", | ||
| "noMatchesFoundForKeyboard": "No matches found for '{keyboard}'", | ||
| "previousPager": "< Previous", | ||
| "nextPager": "Next >" | ||
| } |
This file contains hidden or 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,15 @@ | ||
| { | ||
| "resultOne": "resultado", | ||
| "resultMore": "resultados", | ||
| "pageNumberOfTotalPages": "página {pageNumber} de {totalPages}.", | ||
| "keyboardSearchTitle": "- Búsqueda por teclado", | ||
| "obsoleteKeyboards": "Teclados obsoletos", | ||
| "monthlyDownloadZero": "No hay descargas recientes", | ||
| "monthlyDownloadOne": "descarga mensual", | ||
| "monthlyDownloadMore": "descargas mensuales", | ||
| "notUnicode": "Nota: No es un teclado Unicode", | ||
| "designedForPlatform": "Diseñado para {platform}", | ||
| "noMatchesFoundForKeyboard": "No se encontraron coincidencias para '{keyboard}'", | ||
| "previousPager": "< Anterior", | ||
| "nextPager": "Siguente >" | ||
| } |
This file contains hidden or 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,15 @@ | ||
| { | ||
| "resultOne": "résultat", | ||
| "resultMore": "résultats", | ||
| "pageNumberOfTotalPages": "page {pageNumber} sur {totalPages}.", | ||
| "keyboardSearchTitle": "- Recherche au clavier", | ||
| "obsoleteKeyboards": "Claviers obsolètes", | ||
| "monthlyDownloadZero": "Aucun téléchargement récent", | ||
| "monthlyDownloadOne": "téléchargement mensuel", | ||
| "monthlyDownloadMore": "téléchargements mensuels", | ||
| "notUnicode": "Remarque: Ce n'est pas un clavier Unicode.", | ||
| "designedForPlatform": "Conçu pour {platform}", | ||
| "noMatchesFoundForKeyboard": "Aucun résultat trouvé pour '{keyboard}'", | ||
| "previousPager": "< Précédentes", | ||
| "nextPager": "Plus >" | ||
| } |
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 was copied from Locale.php.
Unclear if still needed?