This repository has been archived by the owner on Apr 17, 2019. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 67
/
index.js
62 lines (52 loc) · 2.1 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
import 'fluent-intl-polyfill';
import './polyfill';
import { MessageContext } from 'fluent';
import negotiateLanguages from 'fluent-langneg';
import DOMLocalization from '../dom_localization';
import DocumentLocalization from '..//document_localization';
import { ResourceBundle } from './io';
import { documentReady, getResourceLinks, getMeta } from './util';
// This function is provided to the constructor of `Localization` object and is
// used to create new `MessageContext` objects for a given `lang` with selected
// builtin functions.
function createContext(lang) {
return new MessageContext(lang);
}
// Called for every named Localization declared via <link name=…> elements.
function createLocalization(defaultLocale, availableLangs, resIds, name) {
// This function is called by `Localization` class to retrieve an array of
// `ResourceBundle`s.
function requestBundles(requestedLangs = navigator.languages) {
const newLangs = negotiateLanguages(
requestedLangs, availableLangs, { defaultLocale }
);
const bundles = newLangs.map(
lang => new ResourceBundle(lang, resIds)
);
return Promise.resolve(bundles);
}
if (name === 'main') {
document.l10n = new DocumentLocalization(requestBundles, createContext);
document.l10n.ready = documentReady().then(() => {
document.l10n.connectRoot(document.documentElement);
return document.l10n.translateDocument();
}).then(() => {
window.addEventListener('languagechange', document.l10n);
});
} else {
// Pass the main Localization, `document.l10n`, as the observer.
const l10n = new DOMLocalization(
requestBundles, createContext, name, document.l10n
);
// Add this Localization as a delegate of the main one.
document.l10n.delegates.set(name, l10n);
}
}
const { defaultLang, availableLangs } = getMeta(document.head);
// Collect all l10n resource links and create `Localization` objects. The
// 'main' Localization must be declared as the first one.
getResourceLinks(document.head).forEach(
(resIds, name) => createLocalization(
defaultLang, availableLangs, resIds, name
)
);