46 lines
1.3 KiB
TypeScript
46 lines
1.3 KiB
TypeScript
import type {CookieRef} from "nuxt/app"
|
|
|
|
export function useContentPreference() {
|
|
const config = useAppConfig()
|
|
|
|
const locales = config.content.matrix.locale.list.map(l => l.code)
|
|
const variants = config.content.matrix.variant.list.map(v => v.code)
|
|
|
|
const localeCookie = useCookie<string>('locale', {
|
|
sameSite: 'lax',
|
|
maxAge: config.content.matrix.locale.cookieMaxAge
|
|
})
|
|
|
|
const variantCookie = useCookie<string>('variant', {
|
|
sameSite: 'lax',
|
|
maxAge: config.content.matrix.variant.cookieMaxAge
|
|
})
|
|
|
|
function prefer(list: string[], cookie: CookieRef<string>) {
|
|
return (item: string) => {
|
|
if (list.includes(item)) {
|
|
cookie.value = item
|
|
}
|
|
}
|
|
}
|
|
|
|
function preferred(list: string[], cookie: CookieRef<string | undefined>, fallback: string) {
|
|
return computed(() => {
|
|
if (cookie.value!==undefined && list.includes(cookie.value)) {
|
|
return cookie.value
|
|
} else if (cookie.value !== undefined) {
|
|
cookie.value = undefined
|
|
}
|
|
|
|
return fallback
|
|
})
|
|
}
|
|
|
|
return {
|
|
preferredLocale: preferred(locales, localeCookie, config.content.matrix.locale.default),
|
|
preferLocale: prefer(locales, localeCookie),
|
|
preferredVariant: preferred(variants, variantCookie, config.content.matrix.variant.default),
|
|
preferVariant: prefer(variants, variantCookie)
|
|
}
|
|
}
|