-
Notifications
You must be signed in to change notification settings - Fork 0
/
locale.js
46 lines (39 loc) · 1.19 KB
/
locale.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
import { writable } from "svelte/store";
import { locales } from "./data.js";
const getInitialLocale = () => {
if (navigator.languages && navigator.languages.length) {
return navigator.languages[0];
} else {
return (
navigator.userLanguage ||
navigator.language ||
navigator.browserLanguage ||
Object.keys(locales)[0]
);
}
};
let currentLocaleCode = getInitialLocale().substr(0, 2);
if (!(currentLocaleCode in locales)) currentLocaleCode = "en";
let currentLocale = locales[currentLocaleCode];
console.log(`Initial locale ${currentLocaleCode}`);
const { subscribe, set } = writable(locales[currentLocaleCode]),
setLocale = (newLocaleCode) => {
if (currentLocaleCode === newLocaleCode) return;
const newLocale = locales[newLocaleCode];
if (newLocale) {
currentLocaleCode = newLocaleCode;
currentLocale = newLocale;
set(newLocale);
}
},
getAvailableLocales = () =>
Object.entries(locales).map(([k, v]) => [k, v.name]),
getCurrentLocaleCode = () => currentLocaleCode,
getCurrentLocale = () => currentLocale;
export const locale = {
subscribe,
setLocale,
getAvailableLocales,
getCurrentLocaleCode,
getCurrentLocale
};