-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.ts
44 lines (37 loc) · 1.38 KB
/
index.ts
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
import rosetta from 'rosetta';
import type { SiteLocale, TranslationKey } from '@lib/i18n/types';
import messages from '@lib/i18n/messages.json';
import { locales as siteLocales } from '@lib/site.json';
export const locales = siteLocales as SiteLocale[];
export const defaultLocale = locales[0];
export const cookieName = 'HEAD_START_LOCALE';
const i18n = rosetta(messages);
if (typeof document !== 'undefined') {
setLocale(document.documentElement.lang as SiteLocale);
} else {
i18n.locale(defaultLocale);
}
export type T = typeof i18n.t & ((key: TranslationKey) => string);
// we use the 'any' type since this is used in the rosetta source-code
// eslint-disable-next-line @typescript-eslint/no-explicit-any
export const t: T = (key: TranslationKey, params?: any[] | Record<string, any>, lang?: string) => {
const translate = i18n.t.bind(i18n);
const translation = translate(key, params, lang);
if (!translation) console.warn(`\x1b[33mMissing translation for key: ${key}`);
return translation;
};
export function getLocale() {
return i18n.locale();
}
export function setLocale(locale?: SiteLocale) {
if (locale && locales.includes(locale)) {
return i18n.locale(locale);
}
return i18n.locale();
}
/**
* Returns locale name for a given code in its own language.
*/
export function getLocaleName(code: string) {
return new Intl.DisplayNames([code], { type: 'language' }).of(code);
}