2023-09-01 23:57:58 +08:00
|
|
|
import { I18nContext, createI18nContext, useI18n } from '@solid-primitives/i18n'
|
|
|
|
import { makePersisted } from '@solid-primitives/storage'
|
2023-09-04 18:48:39 +08:00
|
|
|
import dayjs from 'dayjs'
|
2023-09-01 23:57:58 +08:00
|
|
|
import { ParentComponent, createEffect, createSignal } from 'solid-js'
|
2023-09-03 03:26:29 +08:00
|
|
|
import { LANG } from '~/constants'
|
2023-09-02 13:50:24 +08:00
|
|
|
import dict from './dict'
|
2023-09-01 23:25:37 +08:00
|
|
|
|
2023-09-01 23:57:58 +08:00
|
|
|
const useLanguage = () => {
|
2023-09-02 00:09:41 +08:00
|
|
|
const [lang, setLang] = makePersisted(
|
|
|
|
createSignal(
|
2023-09-02 13:50:24 +08:00
|
|
|
Reflect.has(dict, navigator.language) ? navigator.language : LANG.EN,
|
2023-09-02 00:09:41 +08:00
|
|
|
),
|
|
|
|
{
|
|
|
|
name: 'lang',
|
|
|
|
storage: localStorage,
|
|
|
|
},
|
|
|
|
)
|
2023-09-01 23:57:58 +08:00
|
|
|
|
|
|
|
return { lang, setLang }
|
|
|
|
}
|
|
|
|
|
|
|
|
const I18nUpdator: ParentComponent = (props) => {
|
|
|
|
const { setLang } = useLanguage()
|
2023-09-03 15:30:56 +08:00
|
|
|
const [, { locale }] = useI18n()
|
2023-09-01 23:57:58 +08:00
|
|
|
|
|
|
|
createEffect(() => {
|
|
|
|
setLang(locale())
|
2023-09-04 18:48:39 +08:00
|
|
|
dayjs.locale(locale())
|
2023-09-01 23:57:58 +08:00
|
|
|
})
|
|
|
|
|
|
|
|
return props.children
|
|
|
|
}
|
|
|
|
|
2023-09-01 23:25:37 +08:00
|
|
|
export const I18nProvider: ParentComponent = (props) => {
|
|
|
|
const { lang } = useLanguage()
|
|
|
|
const value = createI18nContext(dict, lang())
|
|
|
|
|
|
|
|
return (
|
2023-09-01 23:57:58 +08:00
|
|
|
<I18nContext.Provider value={value}>
|
|
|
|
<I18nUpdator>{props.children}</I18nUpdator>
|
|
|
|
</I18nContext.Provider>
|
2023-09-01 23:25:37 +08:00
|
|
|
)
|
|
|
|
}
|