feat(settings): respect settings from server (#1013)

This commit is contained in:
三咲智子 Kevin Deng 2023-01-13 01:52:52 +08:00 committed by GitHub
parent 32aa47e701
commit 9a41b9b7d7
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
27 changed files with 230 additions and 167 deletions

View file

@ -4,6 +4,8 @@ import type { mastodon } from 'masto'
defineProps<{ defineProps<{
account: mastodon.v1.Account account: mastodon.v1.Account
}>() }>()
const userSettings = useUserSettings()
</script> </script>
<template> <template>
@ -38,7 +40,7 @@ defineProps<{
</template> </template>
</NuxtLink> </NuxtLink>
<NuxtLink <NuxtLink
v-if="!getWellnessSetting('hideFollowerCount')" v-if="!getWellnessSetting(userSettings, 'hideFollowerCount')"
:to="getAccountFollowersRoute(account)" :to="getAccountFollowersRoute(account)"
replace text-secondary replace text-secondary
exact-active-class="text-primary" exact-active-class="text-primary"

View file

@ -4,6 +4,8 @@ let { modelValue } = $defineModel<{
}>() }>()
const colorMode = useColorMode() const colorMode = useColorMode()
const userSettings = useUserSettings()
function toggleVisible() { function toggleVisible() {
modelValue = !modelValue modelValue = !modelValue
} }

View file

@ -2,6 +2,8 @@
const buildInfo = useRuntimeConfig().public.buildInfo const buildInfo = useRuntimeConfig().public.buildInfo
const timeAgoOptions = useTimeAgoOptions() const timeAgoOptions = useTimeAgoOptions()
const userSettings = useUserSettings()
const buildTimeDate = new Date(buildInfo.time) const buildTimeDate = new Date(buildInfo.time)
const buildTimeAgo = useTimeAgo(buildTimeDate, timeAgoOptions) const buildTimeAgo = useTimeAgo(buildTimeDate, timeAgoOptions)

View file

@ -1,5 +1,5 @@
<script setup lang="ts"> <script setup lang="ts">
import type { ColorMode } from '~/types' import type { ColorMode } from '~/composables/settings'
const colorMode = useColorMode() const colorMode = useColorMode()

View file

@ -1,14 +1,15 @@
<script lang="ts" setup> <script lang="ts" setup>
import { DEFAULT_FONT_SIZE } from '~/constants' import { DEFAULT_FONT_SIZE } from '~/constants'
import type { FontSize } from '~/types' import type { FontSize } from '~/composables/settings'
const userSettings = useUserSettings()
const sizes = ['xs', 'sm', 'md', 'lg', 'xl'] as FontSize[] const sizes = ['xs', 'sm', 'md', 'lg', 'xl'] as FontSize[]
const fontSize = useFontSizeRef()
</script> </script>
<template> <template>
<select v-model="fontSize"> <select v-model="userSettings.fontSize">
<option v-for="size in sizes" :key="size" :value="size" :selected="fontSize === size"> <option v-for="size in sizes" :key="size" :value="size" :selected="userSettings.fontSize === size">
{{ `${$t(`settings.interface.size_label.${size}`)}${size === DEFAULT_FONT_SIZE ? $t('settings.interface.default') : ''}` }} {{ `${$t(`settings.interface.size_label.${size}`)}${size === DEFAULT_FONT_SIZE ? $t('settings.interface.default') : ''}` }}
</option> </option>
</select> </select>

View file

@ -2,13 +2,14 @@
import type { ComputedRef } from 'vue' import type { ComputedRef } from 'vue'
import type { LocaleObject } from '#i18n' import type { LocaleObject } from '#i18n'
const { locale, setLocale } = useI18n() const userSettings = useUserSettings()
const { locales } = useI18n() as { locales: ComputedRef<LocaleObject[]> } const { locales } = useI18n() as { locales: ComputedRef<LocaleObject[]> }
</script> </script>
<template> <template>
<select :value="locale" @input="e => setLocale((e.target as any).value)"> <select v-model="userSettings.language">
<option v-for="item in locales" :key="item.code" :value="item.code" :selected="locale === item.code"> <option v-for="item in locales" :key="item.code" :value="item.code" :selected="userSettings.language === item.code">
{{ item.name }} {{ item.name }}
</option> </option>
</select> </select>

View file

@ -11,6 +11,8 @@ const focusEditor = inject<typeof noop>('focus-editor', noop)
const { details, command } = $(props) const { details, command } = $(props)
const userSettings = useUserSettings()
const { const {
status, status,
isLoading, isLoading,
@ -53,7 +55,7 @@ const reply = () => {
<div flex-1> <div flex-1>
<StatusActionButton <StatusActionButton
:content="$t('action.boost')" :content="$t('action.boost')"
:text="!getWellnessSetting('hideBoostCount') && status.reblogsCount ? status.reblogsCount : ''" :text="!getWellnessSetting(userSettings, 'hideBoostCount') && status.reblogsCount ? status.reblogsCount : ''"
color="text-green" hover="text-green" group-hover="bg-green/10" color="text-green" hover="text-green" group-hover="bg-green/10"
icon="i-ri:repeat-line" icon="i-ri:repeat-line"
active-icon="i-ri:repeat-fill" active-icon="i-ri:repeat-fill"
@ -62,7 +64,7 @@ const reply = () => {
:command="command" :command="command"
@click="toggleReblog()" @click="toggleReblog()"
> >
<template v-if="status.reblogsCount && !getWellnessSetting('hideBoostCount')" #text> <template v-if="status.reblogsCount && !getWellnessSetting(userSettings, 'hideBoostCount')" #text>
<CommonLocalizedNumber <CommonLocalizedNumber
keypath="action.boost_count" keypath="action.boost_count"
:count="status.reblogsCount" :count="status.reblogsCount"
@ -74,7 +76,7 @@ const reply = () => {
<div flex-1> <div flex-1>
<StatusActionButton <StatusActionButton
:content="$t('action.favourite')" :content="$t('action.favourite')"
:text="!getWellnessSetting('hideFavoriteCount') && status.favouritesCount ? status.favouritesCount : ''" :text="!getWellnessSetting(userSettings, 'hideFavoriteCount') && status.favouritesCount ? status.favouritesCount : ''"
color="text-rose" hover="text-rose" group-hover="bg-rose/10" color="text-rose" hover="text-rose" group-hover="bg-rose/10"
icon="i-ri:heart-3-line" icon="i-ri:heart-3-line"
active-icon="i-ri:heart-3-fill" active-icon="i-ri:heart-3-fill"
@ -83,7 +85,7 @@ const reply = () => {
:command="command" :command="command"
@click="toggleFavourite()" @click="toggleFavourite()"
> >
<template v-if="status.favouritesCount && !getWellnessSetting('hideFavoriteCount')" #text> <template v-if="status.favouritesCount && !getWellnessSetting(userSettings, 'hideFavoriteCount')" #text>
<CommonLocalizedNumber <CommonLocalizedNumber
keypath="action.favourite_count" keypath="action.favourite_count"
:count="status.favouritesCount" :count="status.favouritesCount"

View file

@ -23,6 +23,7 @@ const clipboard = useClipboard()
const router = useRouter() const router = useRouter()
const route = useRoute() const route = useRoute()
const { t } = useI18n() const { t } = useI18n()
const userSettings = useUserSettings()
const isAuthor = $computed(() => status.account.id === currentUser.value?.account.id) const isAuthor = $computed(() => status.account.id === currentUser.value?.account.id)

View file

@ -22,6 +22,7 @@ const props = withDefaults(
}>(), }>(),
{ actions: true }, { actions: true },
) )
const userSettings = useUserSettings()
const status = $computed(() => { const status = $computed(() => {
if (props.status.reblog && !props.status.content) if (props.status.reblog && !props.status.content)

View file

@ -244,6 +244,7 @@ export const provideGlobalCommands = () => {
const users = useUsers() const users = useUsers()
const masto = useMasto() const masto = useMasto()
const colorMode = useColorMode() const colorMode = useColorMode()
const userSettings = useUserSettings()
useCommand({ useCommand({
scope: 'Navigation', scope: 'Navigation',

View file

@ -1,8 +1,4 @@
import { InjectionKeyDropdownContext, InjectionKeyFontSize } from '~/constants/symbols' import { InjectionKeyDropdownContext } from '~/constants/symbols'
export function useFontSizeRef() {
return inject(InjectionKeyFontSize)!
}
export function useDropdownContext() { export function useDropdownContext() {
return inject(InjectionKeyDropdownContext, undefined) return inject(InjectionKeyDropdownContext, undefined)

View file

@ -0,0 +1,46 @@
import { DEFAULT_FONT_SIZE, DEFAULT_LANGUAGE } from '~/constants'
export type FontSize = 'xs' | 'sm' | 'md' | 'lg' | 'xl'
export type ColorMode = 'light' | 'dark'
export interface FeatureFlags {
experimentalVirtualScroller: boolean
experimentalGitHubCards: boolean
experimentalUserPicker: boolean
}
export interface WellnessSettings {
hideBoostCount: boolean
hideFavoriteCount: boolean
hideFollowerCount: boolean
}
export interface UserSettings {
featureFlags: Partial<FeatureFlags>
wellnessSettings: Partial<WellnessSettings>
colorMode?: ColorMode
fontSize: FontSize
language: string
zenMode?: boolean
}
export function getDefaultUserSettings(): UserSettings {
return {
language: DEFAULT_LANGUAGE,
fontSize: DEFAULT_FONT_SIZE,
featureFlags: {},
wellnessSettings: {},
}
}
export const DEFAULT_WELLNESS_SETTINGS: WellnessSettings = {
hideBoostCount: false,
hideFavoriteCount: false,
hideFollowerCount: false,
}
export const DEFAULT_FEATURE_FLAGS: FeatureFlags = {
experimentalVirtualScroller: true,
experimentalGitHubCards: true,
experimentalUserPicker: true,
}

View file

@ -1,36 +0,0 @@
import type { Ref } from 'vue'
import { userSettings } from '.'
export interface FeatureFlags {
experimentalVirtualScroller: boolean
experimentalGitHubCards: boolean
experimentalUserPicker: boolean
}
export type FeatureFlagsMap = Record<string, FeatureFlags>
const DEFAULT_FEATURE_FLAGS: FeatureFlags = {
experimentalVirtualScroller: true,
experimentalGitHubCards: true,
experimentalUserPicker: true,
}
export function useFeatureFlag<T extends keyof FeatureFlags>(name: T): Ref<FeatureFlags[T]> {
return computed({
get() {
return getFeatureFlag(name)
},
set(value) {
if (userSettings.value)
userSettings.value.featureFlags[name] = value
},
})
}
export function getFeatureFlag<T extends keyof FeatureFlags>(name: T): FeatureFlags[T] {
return userSettings.value?.featureFlags?.[name] ?? DEFAULT_FEATURE_FLAGS[name]
}
export function toggleFeatureFlag(key: keyof FeatureFlags) {
const flag = useFeatureFlag(key)
flag.value = !flag.value
}

View file

@ -1,24 +1,2 @@
import type { FeatureFlags } from './featureFlags' export * from './definition'
import type { WellnessSettings } from './wellness' export * from './storage'
import type { ColorMode, FontSize } from '~/types'
import { STORAGE_KEY_SETTINGS } from '~/constants'
export interface UserSettings {
featureFlags: Partial<FeatureFlags>
wellnessSettings: Partial<WellnessSettings>
colorMode?: ColorMode
fontSize?: FontSize
lang?: string
zenMode?: boolean
}
export function getDefaultUserSettings(): UserSettings {
return {
featureFlags: {},
wellnessSettings: {},
}
}
export const userSettings = process.server
? computed(getDefaultUserSettings)
: useUserLocalStorage(STORAGE_KEY_SETTINGS, getDefaultUserSettings)

View file

@ -0,0 +1,53 @@
import type { Ref } from 'vue'
import type { FeatureFlags, UserSettings, WellnessSettings } from './definition'
import { STORAGE_KEY_SETTINGS } from '~/constants'
export const useUserSettings = () => {
if (process.server)
return useState('user-settings', getDefaultUserSettings)
return useUserLocalStorage(STORAGE_KEY_SETTINGS, getDefaultUserSettings)
}
// TODO: refactor & simplify this
export function useWellnessSetting<T extends keyof WellnessSettings>(name: T): Ref<WellnessSettings[T]> {
const userSettings = useUserSettings()
return computed({
get() {
return getWellnessSetting(userSettings.value, name)
},
set(value) {
userSettings.value.wellnessSettings[name] = value
},
})
}
export function getWellnessSetting<T extends keyof WellnessSettings>(userSettings: UserSettings, name: T): WellnessSettings[T] {
return userSettings?.wellnessSettings?.[name] ?? DEFAULT_WELLNESS_SETTINGS[name]
}
export function toggleWellnessSetting(key: keyof WellnessSettings) {
const flag = useWellnessSetting(key)
flag.value = !flag.value
}
export function useFeatureFlag<T extends keyof FeatureFlags>(name: T): Ref<FeatureFlags[T]> {
const userSettings = useUserSettings()
return computed({
get() {
return getFeatureFlag(userSettings.value, name)
},
set(value) {
userSettings.value.featureFlags[name] = value
},
})
}
export function getFeatureFlag<T extends keyof FeatureFlags>(userSettings: UserSettings, name: T): FeatureFlags[T] {
return userSettings?.featureFlags?.[name] ?? DEFAULT_FEATURE_FLAGS[name]
}
export function toggleFeatureFlag(key: keyof FeatureFlags) {
const flag = useFeatureFlag(key)
flag.value = !flag.value
}

View file

@ -1,36 +0,0 @@
import type { Ref } from 'vue'
import { userSettings } from '.'
export interface WellnessSettings {
hideBoostCount: boolean
hideFavoriteCount: boolean
hideFollowerCount: boolean
}
export type WellnessSettingsMap = Record<string, WellnessSettings>
const DEFAULT_WELLNESS_SETTINGS: WellnessSettings = {
hideBoostCount: false,
hideFavoriteCount: false,
hideFollowerCount: false,
}
export function useWellnessSetting<T extends keyof WellnessSettings>(name: T): Ref<WellnessSettings[T]> {
return computed({
get() {
return getWellnessSetting(name)
},
set(value) {
if (userSettings.value)
userSettings.value.wellnessSettings[name] = value
},
})
}
export function getWellnessSetting<T extends keyof WellnessSettings>(name: T): WellnessSettings[T] {
return userSettings.value?.wellnessSettings?.[name] ?? DEFAULT_WELLNESS_SETTINGS[name]
}
export function toggleWellnessSetting(key: keyof WellnessSettings) {
const flag = useWellnessSetting(key)
flag.value = !flag.value
}

View file

@ -271,13 +271,7 @@ export function checkLogin() {
* Create reactive storage for the current user * Create reactive storage for the current user
*/ */
export function useUserLocalStorage<T extends object>(key: string, initial: () => T) { export function useUserLocalStorage<T extends object>(key: string, initial: () => T) {
// @ts-expect-error bind value to the function const all = useLocalStorage<Record<string, T>>(key, {}, { deep: true })
const storages = useUserLocalStorage._ = useUserLocalStorage._ || new Map<string, Ref<Record<string, any>>>()
if (!storages.has(key))
storages.set(key, useLocalStorage(key, {}, { deep: true }))
const all = storages.get(key) as Ref<Record<string, T>>
return computed(() => { return computed(() => {
const id = currentUser.value?.account.id const id = currentUser.value?.account.id
? currentUser.value.account.acct ? currentUser.value.account.acct

View file

@ -2,6 +2,7 @@ export const APP_NAME = 'Elk'
export const DEFAULT_POST_CHARS_LIMIT = 500 export const DEFAULT_POST_CHARS_LIMIT = 500
export const DEFAULT_FONT_SIZE = 'md' export const DEFAULT_FONT_SIZE = 'md'
export const DEFAULT_LANGUAGE = 'en-US'
export const STORAGE_KEY_DRAFTS = 'elk-drafts' export const STORAGE_KEY_DRAFTS = 'elk-drafts'
export const STORAGE_KEY_USERS = 'elk-users' export const STORAGE_KEY_USERS = 'elk-users'
@ -20,7 +21,6 @@ export const STORAGE_KEY_NOTIFICATION_POLICY = 'elk-notification-policy'
export const COOKIE_MAX_AGE = 10 * 365 * 24 * 60 * 60 * 1000 export const COOKIE_MAX_AGE = 10 * 365 * 24 * 60 * 60 * 1000
export const COOKIE_KEY_FONT_SIZE = 'elk-font-size' export const COOKIE_KEY_FONT_SIZE = 'elk-font-size'
export const COOKIE_KEY_COLOR_MODE = 'elk-color-mode'
export const COOKIE_KEY_LOCALE = 'elk-lang' export const COOKIE_KEY_LOCALE = 'elk-lang'
export const HANDLED_MASTO_URLS = /^(https?:\/\/)?([\w\d-]+\.)+\w+\/(@[@\w\d-\.]+)(\/objects)?(\/\d+)?$/ export const HANDLED_MASTO_URLS = /^(https?:\/\/)?([\w\d-]+\.)+\w+\/(@[@\w\d-\.]+)(\/objects)?(\/\d+)?$/

View file

@ -1,7 +1,4 @@
import type { InjectionKey, Ref } from 'vue' import type { InjectionKey } from 'vue'
import type { FontSize } from '~/types'
export const InjectionKeyFontSize: InjectionKey<Ref<FontSize>> = Symbol('font-size')
export const InjectionKeyDropdownContext: InjectionKey<{ export const InjectionKeyDropdownContext: InjectionKey<{
hide: () => void hide: () => void

View file

@ -1,7 +1,8 @@
<script lang="ts" setup> <script lang="ts" setup>
import { useFeatureFlag } from '~~/composables/settings/featureFlags' import { useFeatureFlag } from '~/composables/settings'
const route = useRoute() const route = useRoute()
const userSettings = useUserSettings()
const wideLayout = computed(() => route.meta.wideLayout ?? false) const wideLayout = computed(() => route.meta.wideLayout ?? false)

View file

@ -4,6 +4,8 @@ const { t } = useI18n()
useHeadFixed({ useHeadFixed({
title: () => `${t('settings.preferences.label')} | ${t('nav.settings')}`, title: () => `${t('settings.preferences.label')} | ${t('nav.settings')}`,
}) })
const userSettings = useUserSettings()
</script> </script>
<template> <template>
@ -18,19 +20,19 @@ useHeadFixed({
{{ $t('settings.feature_flags.title') }} {{ $t('settings.feature_flags.title') }}
</h3> </h3>
<SettingsToggleItem <SettingsToggleItem
:checked="getFeatureFlag('experimentalVirtualScroller')" :checked="getFeatureFlag(userSettings, 'experimentalVirtualScroller')"
@click="toggleFeatureFlag('experimentalVirtualScroller')" @click="toggleFeatureFlag('experimentalVirtualScroller')"
> >
{{ $t('settings.feature_flags.virtual_scroll') }} {{ $t('settings.feature_flags.virtual_scroll') }}
</SettingsToggleItem> </SettingsToggleItem>
<SettingsToggleItem <SettingsToggleItem
:checked="getFeatureFlag('experimentalGitHubCards')" :checked="getFeatureFlag(userSettings, 'experimentalGitHubCards')"
@click="toggleFeatureFlag('experimentalGitHubCards')" @click="toggleFeatureFlag('experimentalGitHubCards')"
> >
{{ $t('settings.feature_flags.github_cards') }} {{ $t('settings.feature_flags.github_cards') }}
</SettingsToggleItem> </SettingsToggleItem>
<SettingsToggleItem <SettingsToggleItem
:checked="getFeatureFlag('experimentalUserPicker')" :checked="getFeatureFlag(userSettings, 'experimentalUserPicker')"
@click="toggleFeatureFlag('experimentalUserPicker')" @click="toggleFeatureFlag('experimentalUserPicker')"
> >
{{ $t('settings.feature_flags.user_picker') }} {{ $t('settings.feature_flags.user_picker') }}

View file

@ -4,6 +4,8 @@ const { t } = useI18n()
useHeadFixed({ useHeadFixed({
title: () => `${t('settings.wellness.label')} | ${t('nav.settings')}`, title: () => `${t('settings.wellness.label')} | ${t('nav.settings')}`,
}) })
const userSettings = useUserSettings()
</script> </script>
<template> <template>
@ -14,19 +16,19 @@ useHeadFixed({
</div> </div>
</template> </template>
<SettingsToggleItem <SettingsToggleItem
:checked="getWellnessSetting('hideBoostCount')" :checked="getWellnessSetting(userSettings, 'hideBoostCount')"
@click="toggleWellnessSetting('hideBoostCount')" @click="toggleWellnessSetting('hideBoostCount')"
> >
{{ $t('settings.wellness.feature.hide_boost_count') }} {{ $t('settings.wellness.feature.hide_boost_count') }}
</SettingsToggleItem> </SettingsToggleItem>
<SettingsToggleItem <SettingsToggleItem
:checked="getWellnessSetting('hideFavoriteCount')" :checked="getWellnessSetting(userSettings, 'hideFavoriteCount')"
@click="toggleWellnessSetting('hideFavoriteCount')" @click="toggleWellnessSetting('hideFavoriteCount')"
> >
{{ $t('settings.wellness.feature.hide_favorite_count') }} {{ $t('settings.wellness.feature.hide_favorite_count') }}
</SettingsToggleItem> </SettingsToggleItem>
<SettingsToggleItem <SettingsToggleItem
:checked="getWellnessSetting('hideFollowerCount')" :checked="getWellnessSetting(userSettings, 'hideFollowerCount')"
@click="toggleWellnessSetting('hideFollowerCount')" @click="toggleWellnessSetting('hideFollowerCount')"
> >
{{ $t('settings.wellness.feature.hide_follower_count') }} {{ $t('settings.wellness.feature.hide_follower_count') }}

View file

@ -1,24 +1,26 @@
import type { FontSize } from '~/types' import type { FontSize } from '~/composables/settings'
import { InjectionKeyFontSize } from '~/constants/symbols'
import { COOKIE_KEY_FONT_SIZE, COOKIE_MAX_AGE, DEFAULT_FONT_SIZE } from '~/constants' import { COOKIE_KEY_FONT_SIZE, COOKIE_MAX_AGE, DEFAULT_FONT_SIZE } from '~/constants'
import { fontSizeMap } from '~/constants/options' import { fontSizeMap } from '~/constants/options'
export default defineNuxtPlugin((nuxt) => { export default defineNuxtPlugin(() => {
const userSettings = useUserSettings()
const cookieFontSize = useCookie<FontSize>(COOKIE_KEY_FONT_SIZE, { default: () => DEFAULT_FONT_SIZE, maxAge: COOKIE_MAX_AGE }) const cookieFontSize = useCookie<FontSize>(COOKIE_KEY_FONT_SIZE, { default: () => DEFAULT_FONT_SIZE, maxAge: COOKIE_MAX_AGE })
nuxt.vueApp.provide(InjectionKeyFontSize, cookieFontSize) if (!cookieFontSize.value || !fontSizeMap[cookieFontSize.value])
cookieFontSize.value = DEFAULT_FONT_SIZE
if (!process.server) { if (process.server) {
watchEffect(() => { userSettings.value.fontSize = cookieFontSize.value
document.documentElement.style.setProperty('--font-size', fontSizeMap[cookieFontSize.value || DEFAULT_FONT_SIZE])
})
}
else {
useHead({ useHead({
style: [ style: [
{ { innerHTML: `:root { --font-size: ${fontSizeMap[cookieFontSize.value]}; }` },
innerHTML: `:root { --font-size: ${fontSizeMap[cookieFontSize.value || DEFAULT_FONT_SIZE]}; }`,
},
], ],
}) })
return
} }
userSettings.value.fontSize = cookieFontSize.value
watch(() => userSettings.value.fontSize, (size) => {
document.documentElement.style.setProperty('--font-size', fontSizeMap[size])
cookieFontSize.value = size
}, { immediate: true })
}) })

View file

@ -1,26 +1,46 @@
import { COOKIE_KEY_LOCALE, COOKIE_MAX_AGE } from '~/constants' import type { VueI18n } from 'vue-i18n'
import type { LocaleObject } from 'vue-i18n-routing'
import { COOKIE_KEY_LOCALE, COOKIE_MAX_AGE, DEFAULT_LANGUAGE } from '~/constants'
export default defineNuxtPlugin(async (nuxt) => { export default defineNuxtPlugin(async (nuxt) => {
const i18n = nuxt.vueApp.config.globalProperties.$i18n const i18n = nuxt.vueApp.config.globalProperties.$i18n as VueI18n
const { setLocale, locales } = nuxt.vueApp.config.globalProperties.$i18n const { setLocale, locales } = i18n
const supportLanguages = (locales as LocaleObject[]).map(locale => locale.code)
const cookieLocale = useCookie(COOKIE_KEY_LOCALE, { maxAge: COOKIE_MAX_AGE }) const cookieLocale = useCookie(COOKIE_KEY_LOCALE, { maxAge: COOKIE_MAX_AGE })
const isFirstVisit = cookieLocale.value == null const userSettings = useUserSettings()
if (process.client && isFirstVisit) { if (process.server) {
const userLang = (navigator.language || 'en-US').toLowerCase() const headers = useRequestHeaders()
// cause vue-i18n not explicit export LocaleObject type
const supportLocales = unref(locales) as { code: string }[] let lang = cookieLocale.value
const lang = supportLocales.find(locale => userLang.startsWith(locale.code.toLowerCase()))?.code if (!lang || !supportLanguages.includes(lang)) {
|| supportLocales.find(locale => userLang.startsWith(locale.code.split('-')[0]))?.code // first visit
cookieLocale.value = lang || 'en-US' if (headers['accept-language']) {
// detect language from header
const userLanguages = headers['accept-language'].split(',').map(lang => lang.split(';')[0].toLowerCase())
lang = matchLanguages(supportLanguages, userLanguages) || DEFAULT_LANGUAGE
} }
else {
lang = DEFAULT_LANGUAGE
}
}
userSettings.value.language = cookieLocale.value = lang
if (cookieLocale.value && cookieLocale.value !== i18n.locale) if (lang !== i18n.locale)
await setLocale(cookieLocale.value) await setLocale(cookieLocale.value)
if (process.client) { return
watchEffect(() => {
cookieLocale.value = i18n.locale
})
} }
// could be null if browser don't accept cookie
if (!cookieLocale.value || !supportLanguages.includes(cookieLocale.value))
cookieLocale.value = DEFAULT_LANGUAGE
userSettings.value.language = cookieLocale.value
watch(() => userSettings.value.language, (lang) => {
if (lang !== cookieLocale.value)
cookieLocale.value = lang
if (lang !== i18n.locale)
setLocale(lang)
}, { immediate: true })
}) })

18
tests/language.test.ts Normal file
View file

@ -0,0 +1,18 @@
import { describe, expect, it } from 'vitest'
import { matchLanguages } from '../utils/language'
describe('language', () => {
it('match language', () => {
expect(matchLanguages(['zh-CN', 'zh-TW'], ['zh'])).toMatchInlineSnapshot('"zh-CN"')
expect(matchLanguages(['zh-CN', 'zh-TW'], ['en'])).toMatchInlineSnapshot('null')
expect(matchLanguages(['zh-CN', 'zh-TW', 'en-US'], ['zh', 'en'])).toMatchInlineSnapshot('"zh-CN"')
expect(matchLanguages(['zh-CN', 'zh-TW', 'en-US'], ['en', 'zh-CN'])).toMatchInlineSnapshot('"en-US"')
expect(matchLanguages(['zh-CN', 'zh-TW', 'en-US'], ['zh-TW', 'en'])).toMatchInlineSnapshot('"zh-TW"')
expect(matchLanguages(['zh-TW', 'en-US'], ['zh-CN', 'en-GB'])).toMatchInlineSnapshot('"zh-TW"')
expect(matchLanguages(['zh-TW', 'en-GB'], ['ja-JP', 'zh-CN'])).toMatchInlineSnapshot('"zh-TW"')
expect(matchLanguages(['zh-TW'], ['zh-tw'])).toMatchInlineSnapshot('"zh-TW"')
})
})

View file

@ -74,6 +74,3 @@ export interface BuildInfo {
branch: string branch: string
env: 'preview' | 'canary' | 'dev' | 'release' env: 'preview' | 'canary' | 'dev' | 'release'
} }
export type FontSize = 'xs' | 'sm' | 'md' | 'lg' | 'xl'
export type ColorMode = 'light' | 'dark'

16
utils/language.ts Normal file
View file

@ -0,0 +1,16 @@
export function matchLanguages(languages: string[], acceptLanguages: string[]): string | null {
{
const lang = acceptLanguages.map(userLang => languages.find(lang => lang.startsWith(userLang))).filter(v => !!v)[0]
if (lang)
return lang
}
const lang = acceptLanguages.map((userLang) => {
userLang = userLang.split('-')[0]!
return languages.find(lang => lang.startsWith(userLang))
}).filter(v => !!v)[0]
if (lang)
return lang
return null
}