|
1 |
| -import type { Locale } from '~/models/i18n.model'; |
| 1 | +import type { Locale, Locales } from '~/models/i18n.model'; |
2 | 2 |
|
3 | 3 | import { useI18nStore } from '~/stores/i18n.store';
|
4 | 4 | import { useRouterStore } from '~/stores/router.store';
|
5 | 5 | import { useI18nTranslate } from '~/utils/browser/browser-i18n.utils';
|
6 | 6 | import { chromeI18n } from '~/utils/browser/browser.utils';
|
7 | 7 |
|
| 8 | +export const initLocalI18n = () => { |
| 9 | + const store = useI18nStore(); |
| 10 | + const router = useRouterStore(); |
| 11 | + let promise: Promise<Locales | void> | undefined; |
| 12 | + if (import.meta.hot) { |
| 13 | + console.info('Listening to i18n HMR changes'); |
| 14 | + import.meta.hot.send('fetch:i18n'); |
| 15 | + import.meta.hot.on('update:i18n', (data: { lang: string; locale: Locale }[]) => { |
| 16 | + data?.forEach(({ lang, locale }) => store.addLocale(locale, lang)); |
| 17 | + }); |
| 18 | + } else if (!store.locales?.[store.lang]) { |
| 19 | + promise = fetch(new URL(`${router.baseUrl ?? './'}_locales/${store.lang}/messages.json`, new URL(import.meta.url).origin)) |
| 20 | + .then(r => r.json()) |
| 21 | + .then((locale: Locale) => store.addLocale(locale)) |
| 22 | + .catch(err => console.error(`Failed to fetch locale '${store.lang}'`, err)); |
| 23 | + } |
| 24 | + |
| 25 | + return { store, router, promise }; |
| 26 | +}; |
| 27 | + |
8 | 28 | /**
|
9 | 29 | * Setup i18n function to either use chrome i18n resolver or a local store (for web use).
|
10 | 30 | * @param roots modules names
|
11 | 31 | * @see chrome.i18n.getMessage
|
12 | 32 | */
|
13 | 33 | export const useI18n = (...roots: string[]): ReturnType<typeof useI18nTranslate> => {
|
14 | 34 | if (!chromeI18n) {
|
15 |
| - const store = useI18nStore(); |
16 |
| - const router = useRouterStore(); |
17 |
| - |
18 |
| - if (import.meta.hot) { |
19 |
| - console.info('Listening to i18n HMR changes'); |
20 |
| - import.meta.hot.send('fetch:i18n'); |
21 |
| - import.meta.hot.on('update:i18n', (data: { lang: string; locale: Locale }[]) => { |
22 |
| - data?.forEach(({ lang, locale }) => store.addLocale(locale, lang)); |
23 |
| - }); |
24 |
| - } else if (!store.locales?.[store.lang]) { |
25 |
| - fetch(new URL(`${router.baseUrl ?? './'}_locales/${store.lang}/messages.json`, new URL(import.meta.url).origin)) |
26 |
| - .then(r => r.json()) |
27 |
| - .then((locale: Locale) => store.addLocale(locale)) |
28 |
| - .catch(err => console.error(`Failed to fetch locale '${store.lang}'`, err)); |
29 |
| - } |
30 |
| - |
| 35 | + const { store } = initLocalI18n(); |
31 | 36 | return (value, ...modules) => store.i18n(value, ...(modules?.length ? modules : roots));
|
32 | 37 | }
|
33 | 38 |
|
|
0 commit comments