File size: 1,870 Bytes
4bbfe8b | 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 67 68 69 70 71 | import { createEffect } from "solid-js"
import { getRequestEvent } from "solid-js/web"
import { createStore } from "solid-js/store"
import { createSimpleContext } from "@opencode-ai/ui/context"
import {
LOCALES,
cookie,
detectFromLanguages,
dir,
fromPathname,
label,
localeFromCookieHeader,
localeFromRequest,
parseLocale,
route,
tag,
type Locale,
} from "../lib/language"
function initial() {
const event = getRequestEvent()
if (event) return localeFromRequest(event.request)
if (typeof window === "object") {
const fromPath = fromPathname(window.location.pathname)
if (fromPath) return fromPath
}
if (typeof document === "object") {
const fromCookie = localeFromCookieHeader(document.cookie)
if (fromCookie) return fromCookie
const fromDom = parseLocale(document.documentElement.dataset.locale)
if (fromDom) return fromDom
}
if (typeof navigator !== "object") return "en" satisfies Locale
const languages = navigator.languages?.length ? navigator.languages : [navigator.language]
return detectFromLanguages(languages)
}
export const { use: useLanguage, provider: LanguageProvider } = createSimpleContext({
name: "StatsLanguage",
init: () => {
const [store, setStore] = createStore({
locale: initial(),
})
createEffect(() => {
document.documentElement.lang = tag(store.locale)
document.documentElement.dir = dir(store.locale)
document.documentElement.dataset.locale = store.locale
})
return {
locale: () => store.locale,
locales: LOCALES,
label,
tag,
dir,
route(pathname: string) {
return route(store.locale, pathname)
},
setLocale(next: Locale) {
setStore("locale", next)
if (typeof document !== "object") return
document.cookie = cookie(next)
},
}
},
})
|