49 lines
1.3 KiB
JavaScript
49 lines
1.3 KiB
JavaScript
import {en} from "../lang/en"
|
|
import {fr} from "../lang/fr"
|
|
import {useContext, useEffect, useState} from "preact/hooks"
|
|
import {createContext} from "preact"
|
|
|
|
export const TranslateContext = createContext(null)
|
|
|
|
export const Text = ({text, count = null}) => {
|
|
|
|
const lang = useContext(TranslateContext)
|
|
const [translate, setTranslate] = useState()
|
|
|
|
useEffect(() => {
|
|
if (lang && lang[text]) {
|
|
if (count > 1 && lang[text].many) {
|
|
text = lang[text].many
|
|
} else if (count <= 1 && lang[text].one) {
|
|
text = lang[text].one
|
|
} else {
|
|
text = lang[text]
|
|
}
|
|
}
|
|
|
|
if (count && text.includes('{{count}}')) {
|
|
text = text.replace('{{count}}', count)
|
|
}
|
|
setTranslate(text)
|
|
}, [])
|
|
|
|
return <>{ translate }</>
|
|
}
|
|
|
|
export const TranslateProvider = ({children}) => {
|
|
|
|
let translate = null
|
|
if (typeof navigator !== "undefined") {
|
|
const userLang = navigator.language || navigator.userLanguage
|
|
if (userLang === "en") {
|
|
translate = en
|
|
} else if (userLang === "fr") {
|
|
translate = fr
|
|
}
|
|
}
|
|
|
|
return <TranslateContext.Provider value={translate}>
|
|
{ children }
|
|
</TranslateContext.Provider>
|
|
|
|
} |