profileShare

rasmusjy / splitapp-frontend-vue

Read-only snapshot

No repository description.

main default branch 96 files Expires Sep 13, 2026, 9:06 AM
lang.ts 1,410 bytes
1 import { ref, watch } from 'vue'
2 import { defineStore } from 'pinia'
3 import i18n, { DEFAULT_LOCALE, SUPPORTED_LOCALES, type AppLocale } from '@/i18n'
4
5 function readCookieCulture(): AppLocale | null {
6 const match = document.cookie.match(/(?:^|;\s*)\.AspNetCore\.Culture=([^;]+)/)
7 if (!match) return null
8 const decoded = decodeURIComponent(match[1]!)
9 const m = decoded.match(/c=([a-zA-Z-]+)/)
10 const code = m?.[1]?.toLowerCase()
11 if (code === 'en' || code === 'et') return code
12 return null
13 }
14
15 function writeCookieCulture(locale: AppLocale) {
16 const value = `c=${locale}|uic=${locale}`
17 const oneYear = 60 * 60 * 24 * 365
18 document.cookie = `.AspNetCore.Culture=${encodeURIComponent(value)}; path=/; max-age=${oneYear}; samesite=lax`
19 }
20
21 export const useLangStore = defineStore('lang', () => {
22 const stored = (localStorage.getItem('locale') as AppLocale | null) ?? readCookieCulture() ?? DEFAULT_LOCALE
23 const currentLocale = ref<AppLocale>(stored)
24
25 function apply(locale: AppLocale) {
26 i18n.global.locale.value = locale
27 document.documentElement.lang = locale
28 localStorage.setItem('locale', locale)
29 writeCookieCulture(locale)
30 }
31
32 apply(currentLocale.value)
33
34 watch(currentLocale, (val) => apply(val))
35
36 function setLocale(locale: AppLocale) {
37 if (!SUPPORTED_LOCALES.includes(locale)) return
38 currentLocale.value = locale
39 }
40
41 return { currentLocale, setLocale }
42 })
43