Skip to content

Commit 18589f4

Browse files
author
Mikhail Bashkirov
committed
fix(localize): observe <html lang> attribute
1 parent 3115c50 commit 18589f4

File tree

4 files changed

+141
-52
lines changed

4 files changed

+141
-52
lines changed

packages/localize/src/LocalizeManager.js

Lines changed: 32 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -11,15 +11,22 @@ export class LocalizeManager extends LionSingleton {
1111
super(params);
1212
this._fakeExtendsEventTarget();
1313

14-
if (!this.locale) {
15-
this.locale = 'en-GB';
14+
if (!document.documentElement.lang) {
15+
document.documentElement.lang = 'en-GB';
1616
}
17+
1718
this._autoLoadOnLocaleChange = !!params.autoLoadOnLocaleChange;
1819
this.__storage = {};
1920
this.__namespacePatternsMap = new Map();
2021
this.__namespaceLoadersCache = {};
2122
this.__namespaceLoaderPromisesCache = {};
2223
this.formatNumberOptions = { returnIfNaN: '' };
24+
25+
this._setupHtmlLangAttributeObserver();
26+
}
27+
28+
teardown() {
29+
this._teardownHtmlLangAttributeObserver();
2330
}
2431

2532
// eslint-disable-next-line class-methods-use-this
@@ -29,7 +36,11 @@ export class LocalizeManager extends LionSingleton {
2936

3037
set locale(value) {
3138
const oldLocale = document.documentElement.lang;
39+
40+
this._teardownHtmlLangAttributeObserver();
3241
document.documentElement.lang = value;
42+
this._setupHtmlLangAttributeObserver();
43+
3344
this._onLocaleChanged(value, oldLocale);
3445
}
3546

@@ -90,6 +101,25 @@ export class LocalizeManager extends LionSingleton {
90101
return formatter.format(vars);
91102
}
92103

104+
_setupHtmlLangAttributeObserver() {
105+
if (!this._htmlLangAttributeObserver) {
106+
this._htmlLangAttributeObserver = new MutationObserver(mutations => {
107+
mutations.forEach(mutation => {
108+
this._onLocaleChanged(document.documentElement.lang, mutation.oldValue);
109+
});
110+
});
111+
}
112+
this._htmlLangAttributeObserver.observe(document.documentElement, {
113+
attributes: true,
114+
attributeFilter: ['lang'],
115+
attributeOldValue: true,
116+
});
117+
}
118+
119+
_teardownHtmlLangAttributeObserver() {
120+
this._htmlLangAttributeObserver.disconnect();
121+
}
122+
93123
_isNamespaceInCache(locale, namespace) {
94124
return !!(this.__storage[locale] && this.__storage[locale][namespace]);
95125
}

packages/localize/src/localize.js

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,5 +6,6 @@ export let localize = LocalizeManager.getInstance({
66
});
77

88
export function setLocalize(newLocalize) {
9+
localize.teardown();
910
localize = newLocalize;
1011
}

0 commit comments

Comments
 (0)