1 | import uniq from "lodash/uniq";
|
2 |
|
3 | import { Dict, LocaleResolver } from "./typing";
|
4 | import { I18n } from "./I18n";
|
5 |
|
6 |
|
7 |
|
8 |
|
9 |
|
10 |
|
11 |
|
12 |
|
13 |
|
14 |
|
15 |
|
16 |
|
17 |
|
18 |
|
19 |
|
20 |
|
21 |
|
22 |
|
23 |
|
24 |
|
25 |
|
26 |
|
27 | export const defaultLocaleResolver: LocaleResolver = (
|
28 | i18n: I18n,
|
29 | locale: string,
|
30 | ): string[] => {
|
31 | const locales = [];
|
32 | const list: string[] = [];
|
33 |
|
34 |
|
35 |
|
36 | locales.push(locale);
|
37 |
|
38 |
|
39 | if (!locale) {
|
40 | locales.push(i18n.locale);
|
41 | }
|
42 |
|
43 |
|
44 | if (i18n.enableFallback) {
|
45 | locales.push(i18n.defaultLocale);
|
46 | }
|
47 |
|
48 |
|
49 |
|
50 |
|
51 |
|
52 |
|
53 |
|
54 | locales
|
55 | .filter(Boolean)
|
56 | .map((entry) => entry.toString())
|
57 | .forEach(function (currentLocale: string) {
|
58 | if (!list.includes(currentLocale)) {
|
59 | list.push(currentLocale);
|
60 | }
|
61 |
|
62 | if (!i18n.enableFallback) {
|
63 | return;
|
64 | }
|
65 |
|
66 | const codes = currentLocale.split("-");
|
67 |
|
68 | if (codes.length === 3) {
|
69 | list.push(`${codes[0]}-${codes[1]}`);
|
70 | }
|
71 |
|
72 | list.push(codes[0]);
|
73 | });
|
74 |
|
75 | return uniq(list);
|
76 | };
|
77 |
|
78 | export class Locales {
|
79 | private i18n: I18n;
|
80 | private registry: Dict;
|
81 |
|
82 | constructor(i18n: I18n) {
|
83 | this.i18n = i18n;
|
84 | this.registry = {};
|
85 |
|
86 | this.register("default", defaultLocaleResolver);
|
87 | }
|
88 |
|
89 | |
90 |
|
91 |
|
92 |
|
93 |
|
94 |
|
95 |
|
96 |
|
97 |
|
98 |
|
99 |
|
100 |
|
101 |
|
102 |
|
103 |
|
104 |
|
105 |
|
106 |
|
107 | public register(
|
108 | locale: string,
|
109 | localeResolver: LocaleResolver | string | string[],
|
110 | ): void {
|
111 | if (typeof localeResolver !== "function") {
|
112 | const result = localeResolver;
|
113 | localeResolver = (() => result) as LocaleResolver;
|
114 | }
|
115 |
|
116 | this.registry[locale] = localeResolver;
|
117 | }
|
118 |
|
119 | /**
|
120 | * Return a list of all locales that must be tried before returning the
|
121 | * missing translation message. By default, this will consider the inline
|
122 | * option, current locale and fallback locale.
|
123 | *
|
124 | * ```js
|
125 | * i18n.locales.get("de-DE");
|
126 | * // ["de-DE", "de", "en"]
|
127 | * ```
|
128 | *
|
129 | * @param {string} locale The locale query.
|
130 | *
|
131 | * @returns {string[]} The list of locales.
|
132 | */
|
133 | public get(locale: string): string[] {
|
134 | let locales =
|
135 | this.registry[locale] ||
|
136 | this.registry[this.i18n.locale] ||
|
137 | this.registry.default;
|
138 |
|
139 | if (typeof locales === "function") {
|
140 | locales = locales(this.i18n, locale);
|
141 | }
|
142 |
|
143 | if (!(locales instanceof Array)) {
|
144 | locales = [locales];
|
145 | }
|
146 | return locales;
|
147 | }
|
148 | }
|
149 |
|
\ | No newline at end of file |