-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathCurrentLocale.ts
39 lines (31 loc) · 1.18 KB
/
CurrentLocale.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
import type { LocalizedUnit } from './LocalizedUnit.ts';
/**
This default implementation may be sufficient for most use cases, but it can be overridden by the consuming app, if necessary.
FIXME: how?
*/
export const getCurrentLocale = <Locales extends string>(
localizedUnit: LocalizedUnit<Locales>,
): keyof LocalizedUnit<Locales> & string =>
{
const FALLBACK_LOCALE = 'en';
// Check if we're in a browser environment and can access document properties. If so, use the document's locale as specified in the <html> tag.
const locale = (typeof globalThis !== 'undefined' && 'document' in globalThis
// deno-lint-ignore no-explicit-any
&& (globalThis as unknown as { document: any }).document?.documentElement?.lang) || FALLBACK_LOCALE; // 🤖🤮
if (!localizedUnit)
{
return locale as Locales;
}
const value = localizedUnit[locale as Locales];
if (!value)
{
// FIXME: invoke the failure handler here
// Let's try to find a fallback locale. We'll just use the first locale we find in the object
const firstLocale = Object.keys(localizedUnit)[0];
if (firstLocale)
{
return firstLocale as Locales;
}
}
return locale as Locales;
};