Skip to content
Open
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
15 changes: 14 additions & 1 deletion _includes/2020/templates/Head.php
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,9 @@ static function render($fields = []) {
if(!isset($fields->js)) {
$fields->js = [];
}
if(!isset($fields->js_i18n_domains)) {
$fields->js_i18n_domains = [];
}
?><!DOCTYPE html>
<?php
if (!empty($fields->language)) {
Expand Down Expand Up @@ -60,6 +63,16 @@ static function render($fields = []) {
<link href='https://fonts.googleapis.com/css?family=Cabin:400,400italic,500,600,700,700italic|Source+Sans+Pro:400,700,900,600,300|Noto+Serif:400' rel='stylesheet' type='text/css'>

<?php
/* Embed json i18n strings for each domain */
foreach($fields->js_i18n_domains as $domain => $locales) {
$localization = '';
foreach($locales as $locale) {
if($localization != '') $localization .= ",\n";
$localization .= "{ \"locale\": \"$locale\", \"strings\": " . file_get_contents(__DIR__ . "/../../locale/strings/$domain/$locale.json") . "}";
Copy link
Contributor

Choose a reason for hiding this comment

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

Just wanted to confirm the folder structure for all the localized strings will be:

PHP (existing)

.../locale/strings/keyboards/ (for the main keyboards/ page)

.../locale/strings/keyboards/details/
.../locale/strings/keyboards/install/
.../locale/strings/keyboards/share/

JS (so far)

.../locale/strings/keyboard-search/

So we don't want to have the JS strings somewhere in /locale/strings/keyboards/?

Copy link
Contributor

Choose a reason for hiding this comment

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

The JS paths in crowdin.yml would need to be updated.
I can do here or back on my base PR

  # JS files
  - source: /_includes/locale/strings/keyboard-search/en.json
    dest: /js/search/en.json
    translation: /_includes/locale/strings/keyboard-search/%locale%.json
    languages_mapping:
      locale:

Copy link
Contributor

Choose a reason for hiding this comment

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

There's a lot of munging on the "embed json i18n strings" for loop.
Would it be cleaner to wrap it in a Util.php function?

}
echo "<script id='i18n_$domain' type='application/json'>[\n$localization\n]</script>\n";
}

array_unshift($fields->js,
Util::cdn('js/jquery1-11-1.min.js'),
Util::cdn('js/bowser.es5.2.9.0.min.js'),
Expand All @@ -68,7 +81,7 @@ static function render($fields = []) {

foreach($fields->js as $jsFile) {
$jsFileType = str_ends_with($jsFile, '.mjs') ? "type='module'" : "";
echo "<script src='$jsFile' $jsFileType></script>";
echo "<script src='$jsFile' $jsFileType></script>\n";
}
?>
</head>
Expand Down
34 changes: 26 additions & 8 deletions _includes/locale/Locale.php
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@
class Locale {
public const DEFAULT_LOCALE = 'en';

// array of the support locales
// array of the support locales
// xx-YY locale as specified in crowdin %locale%
private static $currentLocales = [];

Expand All @@ -36,14 +36,16 @@ public static function currentLocales() {
*/
public static function setLocale($locale) {
// Clear current locales
self::$currentLocales == [];
self::$currentLocales = [];

if (!empty($locale)) {
self::$currentLocales = self::calculateFallbackLocales($locale);
}

// Push default fallback locale to the end
array_push(self::$currentLocales, Locale::DEFAULT_LOCALE);
if(!in_array(Locale::DEFAULT_LOCALE, self::$currentLocales)) {
// Push default fallback locale to the end
array_push(self::$currentLocales, Locale::DEFAULT_LOCALE);
}
}

/**
Expand Down Expand Up @@ -88,10 +90,26 @@ public static function loadStrings($domain, $locale) {
}
}

/**
* Return an array of javascript locales available for the given domain, in
* priority order.
*/
public static function domain_js($domain) {
$root = __DIR__ . "/strings/$domain";
$locales = [];
foreach (self::currentLocales() as $locale) {
if(file_exists("$root/$locale.json")) {
array_push($locales, $locale);
}
}

return $locales;
}

/**
* Defines a global variable for page locale strings and also
* tells locale system that current page uses locales
* @param $define -
* @param $define -
* @param $id - folder containing locale strings, relative to /_includes/locale/strings
*/
public static function definePageLocale($define, $id) {
Expand Down Expand Up @@ -156,21 +174,21 @@ private static function getString($domain, $id) {
}
}

// String not found in any localization -
// String not found in any localization -
if(KeymanHosts::Instance()->Tier() == KeymanHosts::TIER_DEVELOPMENT) {
die('string ' . $id . ' is missing in all the l10ns');
}
return $id;
}

/**
* Wrapper to lookup localized string for webpage domain.
* Wrapper to lookup localized string for webpage domain.
* Formatted string using optional variable args for placeholders
* should escape like %1\$s
* @param $domain - the PHP file using the localized strings
* @param $id - the id for the string
* @param $args - optional remaining args to the format string
*/
*/
public static function m($domain, $id, ...$args) {
$str = self::getString($domain, $id);
if (count($args) == 0) {
Expand Down
125 changes: 125 additions & 0 deletions cdn/dev/js/i18n.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,125 @@
/**
* 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
*
* Domains are loaded by Head::render() with the js_i18n_domains property, e.g.
*
* 'js_i18n_domains' => [
* 'keyboard-search' => Locale::domain_js('keyboard-search'),
* ],
*
*/

export class I18n {
// domains member has the following structure:
// [
// { "locale": "fr", "strings": { "key": "value", ... } },
// { "locale": "en", "strings": { "key": "value", ... } },
// ...
// ]
static domains = [];

/**
* Load the strings for the given domain
* @param {string} domain
*/
Comment on lines +26 to +27
Copy link
Contributor

Choose a reason for hiding this comment

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

Suggested change
* @param {string} domain
*/
* @param {string} domain
* @return {boolean} Status if domain was successfully loaded
*/

static loadDomain(domain) {

// avoid reporting domain-load errors more than once
I18n.domains[domain] = { locales: [] };

const json = document.getElementById('i18n_'+domain)?.text;
if(!json) {
console.error(`i18n domain '${domain}' was not loaded`);
return false;
}

try {
I18n.domains[domain] = {
locales: JSON.parse(json)
};
} catch(e) {
// Handle JSON parse errors so we get a functioning page, even if it has
// no localized strings visible
console.error(e);
return false;
}

return true;
}

/**
* 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){
if(!obj) return undefined;
var aPath = path.split('.');
try {
return aPath.reduce((a, v) => a[v], obj);
} catch {
return undefined;
}
};

/**
* 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 t(domain, key, interpolations) {
if (!I18n.domains[domain]) {
if(!I18n.loadDomain(domain)) {
return key;
}
}

// Find best matching string in the available locales
for(const locale of I18n.domains[domain].locales) {
const value = I18n.objNavigate(locale.strings, key);
if(value) {
return I18n.strObjInterpolation(value, interpolations);
}
}

console.warn(`Missing localization string in '${domain}' for '${key}' in all loaded locales`);
// TODO: log to sentry?
return key;
}
}
Loading