-
Notifications
You must be signed in to change notification settings - Fork 9
Expand file tree
/
Copy pathTranslation.ts
More file actions
66 lines (52 loc) · 1.78 KB
/
Translation.ts
File metadata and controls
66 lines (52 loc) · 1.78 KB
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
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
import { loadLanguageMapFrom, parseCookie, TranslationMap, TranslationModel } from 'mobx-i18n';
import { DataObject } from 'mobx-restful';
import { NextPageContext } from 'next';
import { createContext } from 'react';
import zhCN from '../translation/zh-CN';
const i18nData = {
'zh-CN': zhCN,
'zh-TW': () => import('../translation/zh-TW'),
'en-US': () => import('../translation/en-US'),
};
export type LanguageCode = keyof typeof i18nData;
export interface I18nProps {
language: LanguageCode;
languageMap: typeof zhCN;
}
export const createI18nStore = <N extends LanguageCode, K extends string>(
language?: N,
data?: TranslationMap<K>,
) => {
const store = new TranslationModel({
...i18nData,
...(language && { [language]: data }),
});
if (language) store.currentLanguage = language;
if (data) store.currentMap = data as TranslationMap<keyof (typeof i18nData)['zh-CN']>;
return store;
};
export const i18n = createI18nStore();
export const LanguageName: Record<LanguageCode, string> = {
'zh-CN': '简体中文',
'zh-TW': '繁體中文',
'en-US': 'English',
};
export const I18nContext = createContext(i18n);
export const parseSSRContext = <T extends DataObject = DataObject>(
{ req, query }: NextPageContext,
queryKeys: (keyof T)[] = [],
) => {
const cookie = parseCookie(req?.headers.cookie || '') as T;
for (const key of queryKeys)
cookie[key] = (query[key as string]?.toString().split(',')[0] as T[keyof T]) || cookie[key];
return cookie;
};
export const loadSSRLanguage = (context: NextPageContext) => {
const { headers } = context.req || {},
{ language } = parseSSRContext(context, ['language']);
const header = {
...headers,
...(language ? { cookie: `language=${language}` } : {}),
};
return loadLanguageMapFrom(i18nData, header);
};