forked from Mirrors/elk
feat(settings): respect settings from server (#1013)
This commit is contained in:
parent
32aa47e701
commit
9a41b9b7d7
27 changed files with 230 additions and 167 deletions
|
@ -4,6 +4,8 @@ import type { mastodon } from 'masto'
|
|||
defineProps<{
|
||||
account: mastodon.v1.Account
|
||||
}>()
|
||||
|
||||
const userSettings = useUserSettings()
|
||||
</script>
|
||||
|
||||
<template>
|
||||
|
@ -38,7 +40,7 @@ defineProps<{
|
|||
</template>
|
||||
</NuxtLink>
|
||||
<NuxtLink
|
||||
v-if="!getWellnessSetting('hideFollowerCount')"
|
||||
v-if="!getWellnessSetting(userSettings, 'hideFollowerCount')"
|
||||
:to="getAccountFollowersRoute(account)"
|
||||
replace text-secondary
|
||||
exact-active-class="text-primary"
|
||||
|
|
|
@ -4,6 +4,8 @@ let { modelValue } = $defineModel<{
|
|||
}>()
|
||||
const colorMode = useColorMode()
|
||||
|
||||
const userSettings = useUserSettings()
|
||||
|
||||
function toggleVisible() {
|
||||
modelValue = !modelValue
|
||||
}
|
||||
|
|
|
@ -2,6 +2,8 @@
|
|||
const buildInfo = useRuntimeConfig().public.buildInfo
|
||||
const timeAgoOptions = useTimeAgoOptions()
|
||||
|
||||
const userSettings = useUserSettings()
|
||||
|
||||
const buildTimeDate = new Date(buildInfo.time)
|
||||
const buildTimeAgo = useTimeAgo(buildTimeDate, timeAgoOptions)
|
||||
|
||||
|
|
|
@ -1,5 +1,5 @@
|
|||
<script setup lang="ts">
|
||||
import type { ColorMode } from '~/types'
|
||||
import type { ColorMode } from '~/composables/settings'
|
||||
|
||||
const colorMode = useColorMode()
|
||||
|
||||
|
|
|
@ -1,14 +1,15 @@
|
|||
<script lang="ts" setup>
|
||||
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 fontSize = useFontSizeRef()
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<select v-model="fontSize">
|
||||
<option v-for="size in sizes" :key="size" :value="size" :selected="fontSize === size">
|
||||
<select v-model="userSettings.fontSize">
|
||||
<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') : ''}` }}
|
||||
</option>
|
||||
</select>
|
||||
|
|
|
@ -2,13 +2,14 @@
|
|||
import type { ComputedRef } from 'vue'
|
||||
import type { LocaleObject } from '#i18n'
|
||||
|
||||
const { locale, setLocale } = useI18n()
|
||||
const userSettings = useUserSettings()
|
||||
|
||||
const { locales } = useI18n() as { locales: ComputedRef<LocaleObject[]> }
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<select :value="locale" @input="e => setLocale((e.target as any).value)">
|
||||
<option v-for="item in locales" :key="item.code" :value="item.code" :selected="locale === item.code">
|
||||
<select v-model="userSettings.language">
|
||||
<option v-for="item in locales" :key="item.code" :value="item.code" :selected="userSettings.language === item.code">
|
||||
{{ item.name }}
|
||||
</option>
|
||||
</select>
|
||||
|
|
|
@ -11,6 +11,8 @@ const focusEditor = inject<typeof noop>('focus-editor', noop)
|
|||
|
||||
const { details, command } = $(props)
|
||||
|
||||
const userSettings = useUserSettings()
|
||||
|
||||
const {
|
||||
status,
|
||||
isLoading,
|
||||
|
@ -53,7 +55,7 @@ const reply = () => {
|
|||
<div flex-1>
|
||||
<StatusActionButton
|
||||
: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"
|
||||
icon="i-ri:repeat-line"
|
||||
active-icon="i-ri:repeat-fill"
|
||||
|
@ -62,7 +64,7 @@ const reply = () => {
|
|||
:command="command"
|
||||
@click="toggleReblog()"
|
||||
>
|
||||
<template v-if="status.reblogsCount && !getWellnessSetting('hideBoostCount')" #text>
|
||||
<template v-if="status.reblogsCount && !getWellnessSetting(userSettings, 'hideBoostCount')" #text>
|
||||
<CommonLocalizedNumber
|
||||
keypath="action.boost_count"
|
||||
:count="status.reblogsCount"
|
||||
|
@ -74,7 +76,7 @@ const reply = () => {
|
|||
<div flex-1>
|
||||
<StatusActionButton
|
||||
: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"
|
||||
icon="i-ri:heart-3-line"
|
||||
active-icon="i-ri:heart-3-fill"
|
||||
|
@ -83,7 +85,7 @@ const reply = () => {
|
|||
:command="command"
|
||||
@click="toggleFavourite()"
|
||||
>
|
||||
<template v-if="status.favouritesCount && !getWellnessSetting('hideFavoriteCount')" #text>
|
||||
<template v-if="status.favouritesCount && !getWellnessSetting(userSettings, 'hideFavoriteCount')" #text>
|
||||
<CommonLocalizedNumber
|
||||
keypath="action.favourite_count"
|
||||
:count="status.favouritesCount"
|
||||
|
|
|
@ -23,6 +23,7 @@ const clipboard = useClipboard()
|
|||
const router = useRouter()
|
||||
const route = useRoute()
|
||||
const { t } = useI18n()
|
||||
const userSettings = useUserSettings()
|
||||
|
||||
const isAuthor = $computed(() => status.account.id === currentUser.value?.account.id)
|
||||
|
||||
|
|
|
@ -22,6 +22,7 @@ const props = withDefaults(
|
|||
}>(),
|
||||
{ actions: true },
|
||||
)
|
||||
const userSettings = useUserSettings()
|
||||
|
||||
const status = $computed(() => {
|
||||
if (props.status.reblog && !props.status.content)
|
||||
|
|
|
@ -244,6 +244,7 @@ export const provideGlobalCommands = () => {
|
|||
const users = useUsers()
|
||||
const masto = useMasto()
|
||||
const colorMode = useColorMode()
|
||||
const userSettings = useUserSettings()
|
||||
|
||||
useCommand({
|
||||
scope: 'Navigation',
|
||||
|
|
|
@ -1,8 +1,4 @@
|
|||
import { InjectionKeyDropdownContext, InjectionKeyFontSize } from '~/constants/symbols'
|
||||
|
||||
export function useFontSizeRef() {
|
||||
return inject(InjectionKeyFontSize)!
|
||||
}
|
||||
import { InjectionKeyDropdownContext } from '~/constants/symbols'
|
||||
|
||||
export function useDropdownContext() {
|
||||
return inject(InjectionKeyDropdownContext, undefined)
|
||||
|
|
46
composables/settings/definition.ts
Normal file
46
composables/settings/definition.ts
Normal 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,
|
||||
}
|
|
@ -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
|
||||
}
|
|
@ -1,24 +1,2 @@
|
|||
import type { FeatureFlags } from './featureFlags'
|
||||
import type { WellnessSettings } from './wellness'
|
||||
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)
|
||||
export * from './definition'
|
||||
export * from './storage'
|
||||
|
|
53
composables/settings/storage.ts
Normal file
53
composables/settings/storage.ts
Normal 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
|
||||
}
|
|
@ -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
|
||||
}
|
|
@ -271,13 +271,7 @@ export function checkLogin() {
|
|||
* Create reactive storage for the current user
|
||||
*/
|
||||
export function useUserLocalStorage<T extends object>(key: string, initial: () => T) {
|
||||
// @ts-expect-error bind value to the function
|
||||
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>>
|
||||
|
||||
const all = useLocalStorage<Record<string, T>>(key, {}, { deep: true })
|
||||
return computed(() => {
|
||||
const id = currentUser.value?.account.id
|
||||
? currentUser.value.account.acct
|
||||
|
|
|
@ -2,6 +2,7 @@ export const APP_NAME = 'Elk'
|
|||
|
||||
export const DEFAULT_POST_CHARS_LIMIT = 500
|
||||
export const DEFAULT_FONT_SIZE = 'md'
|
||||
export const DEFAULT_LANGUAGE = 'en-US'
|
||||
|
||||
export const STORAGE_KEY_DRAFTS = 'elk-drafts'
|
||||
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_KEY_FONT_SIZE = 'elk-font-size'
|
||||
export const COOKIE_KEY_COLOR_MODE = 'elk-color-mode'
|
||||
export const COOKIE_KEY_LOCALE = 'elk-lang'
|
||||
|
||||
export const HANDLED_MASTO_URLS = /^(https?:\/\/)?([\w\d-]+\.)+\w+\/(@[@\w\d-\.]+)(\/objects)?(\/\d+)?$/
|
||||
|
|
|
@ -1,7 +1,4 @@
|
|||
import type { InjectionKey, Ref } from 'vue'
|
||||
import type { FontSize } from '~/types'
|
||||
|
||||
export const InjectionKeyFontSize: InjectionKey<Ref<FontSize>> = Symbol('font-size')
|
||||
import type { InjectionKey } from 'vue'
|
||||
|
||||
export const InjectionKeyDropdownContext: InjectionKey<{
|
||||
hide: () => void
|
||||
|
|
|
@ -1,7 +1,8 @@
|
|||
<script lang="ts" setup>
|
||||
import { useFeatureFlag } from '~~/composables/settings/featureFlags'
|
||||
import { useFeatureFlag } from '~/composables/settings'
|
||||
|
||||
const route = useRoute()
|
||||
const userSettings = useUserSettings()
|
||||
|
||||
const wideLayout = computed(() => route.meta.wideLayout ?? false)
|
||||
|
||||
|
|
|
@ -4,6 +4,8 @@ const { t } = useI18n()
|
|||
useHeadFixed({
|
||||
title: () => `${t('settings.preferences.label')} | ${t('nav.settings')}`,
|
||||
})
|
||||
|
||||
const userSettings = useUserSettings()
|
||||
</script>
|
||||
|
||||
<template>
|
||||
|
@ -18,19 +20,19 @@ useHeadFixed({
|
|||
{{ $t('settings.feature_flags.title') }}
|
||||
</h3>
|
||||
<SettingsToggleItem
|
||||
:checked="getFeatureFlag('experimentalVirtualScroller')"
|
||||
:checked="getFeatureFlag(userSettings, 'experimentalVirtualScroller')"
|
||||
@click="toggleFeatureFlag('experimentalVirtualScroller')"
|
||||
>
|
||||
{{ $t('settings.feature_flags.virtual_scroll') }}
|
||||
</SettingsToggleItem>
|
||||
<SettingsToggleItem
|
||||
:checked="getFeatureFlag('experimentalGitHubCards')"
|
||||
:checked="getFeatureFlag(userSettings, 'experimentalGitHubCards')"
|
||||
@click="toggleFeatureFlag('experimentalGitHubCards')"
|
||||
>
|
||||
{{ $t('settings.feature_flags.github_cards') }}
|
||||
</SettingsToggleItem>
|
||||
<SettingsToggleItem
|
||||
:checked="getFeatureFlag('experimentalUserPicker')"
|
||||
:checked="getFeatureFlag(userSettings, 'experimentalUserPicker')"
|
||||
@click="toggleFeatureFlag('experimentalUserPicker')"
|
||||
>
|
||||
{{ $t('settings.feature_flags.user_picker') }}
|
||||
|
|
|
@ -4,6 +4,8 @@ const { t } = useI18n()
|
|||
useHeadFixed({
|
||||
title: () => `${t('settings.wellness.label')} | ${t('nav.settings')}`,
|
||||
})
|
||||
|
||||
const userSettings = useUserSettings()
|
||||
</script>
|
||||
|
||||
<template>
|
||||
|
@ -14,19 +16,19 @@ useHeadFixed({
|
|||
</div>
|
||||
</template>
|
||||
<SettingsToggleItem
|
||||
:checked="getWellnessSetting('hideBoostCount')"
|
||||
:checked="getWellnessSetting(userSettings, 'hideBoostCount')"
|
||||
@click="toggleWellnessSetting('hideBoostCount')"
|
||||
>
|
||||
{{ $t('settings.wellness.feature.hide_boost_count') }}
|
||||
</SettingsToggleItem>
|
||||
<SettingsToggleItem
|
||||
:checked="getWellnessSetting('hideFavoriteCount')"
|
||||
:checked="getWellnessSetting(userSettings, 'hideFavoriteCount')"
|
||||
@click="toggleWellnessSetting('hideFavoriteCount')"
|
||||
>
|
||||
{{ $t('settings.wellness.feature.hide_favorite_count') }}
|
||||
</SettingsToggleItem>
|
||||
<SettingsToggleItem
|
||||
:checked="getWellnessSetting('hideFollowerCount')"
|
||||
:checked="getWellnessSetting(userSettings, 'hideFollowerCount')"
|
||||
@click="toggleWellnessSetting('hideFollowerCount')"
|
||||
>
|
||||
{{ $t('settings.wellness.feature.hide_follower_count') }}
|
||||
|
|
|
@ -1,24 +1,26 @@
|
|||
import type { FontSize } from '~/types'
|
||||
import { InjectionKeyFontSize } from '~/constants/symbols'
|
||||
import type { FontSize } from '~/composables/settings'
|
||||
import { COOKIE_KEY_FONT_SIZE, COOKIE_MAX_AGE, DEFAULT_FONT_SIZE } from '~/constants'
|
||||
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 })
|
||||
nuxt.vueApp.provide(InjectionKeyFontSize, cookieFontSize)
|
||||
if (!cookieFontSize.value || !fontSizeMap[cookieFontSize.value])
|
||||
cookieFontSize.value = DEFAULT_FONT_SIZE
|
||||
|
||||
if (!process.server) {
|
||||
watchEffect(() => {
|
||||
document.documentElement.style.setProperty('--font-size', fontSizeMap[cookieFontSize.value || DEFAULT_FONT_SIZE])
|
||||
})
|
||||
}
|
||||
else {
|
||||
if (process.server) {
|
||||
userSettings.value.fontSize = cookieFontSize.value
|
||||
useHead({
|
||||
style: [
|
||||
{
|
||||
innerHTML: `:root { --font-size: ${fontSizeMap[cookieFontSize.value || DEFAULT_FONT_SIZE]}; }`,
|
||||
},
|
||||
{ innerHTML: `:root { --font-size: ${fontSizeMap[cookieFontSize.value]}; }` },
|
||||
],
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
userSettings.value.fontSize = cookieFontSize.value
|
||||
watch(() => userSettings.value.fontSize, (size) => {
|
||||
document.documentElement.style.setProperty('--font-size', fontSizeMap[size])
|
||||
cookieFontSize.value = size
|
||||
}, { immediate: true })
|
||||
})
|
||||
|
|
|
@ -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) => {
|
||||
const i18n = nuxt.vueApp.config.globalProperties.$i18n
|
||||
const { setLocale, locales } = nuxt.vueApp.config.globalProperties.$i18n
|
||||
const i18n = nuxt.vueApp.config.globalProperties.$i18n as VueI18n
|
||||
const { setLocale, locales } = i18n
|
||||
const supportLanguages = (locales as LocaleObject[]).map(locale => locale.code)
|
||||
const cookieLocale = useCookie(COOKIE_KEY_LOCALE, { maxAge: COOKIE_MAX_AGE })
|
||||
const isFirstVisit = cookieLocale.value == null
|
||||
const userSettings = useUserSettings()
|
||||
|
||||
if (process.client && isFirstVisit) {
|
||||
const userLang = (navigator.language || 'en-US').toLowerCase()
|
||||
// cause vue-i18n not explicit export LocaleObject type
|
||||
const supportLocales = unref(locales) as { code: string }[]
|
||||
const lang = supportLocales.find(locale => userLang.startsWith(locale.code.toLowerCase()))?.code
|
||||
|| supportLocales.find(locale => userLang.startsWith(locale.code.split('-')[0]))?.code
|
||||
cookieLocale.value = lang || 'en-US'
|
||||
if (process.server) {
|
||||
const headers = useRequestHeaders()
|
||||
|
||||
let lang = cookieLocale.value
|
||||
if (!lang || !supportLanguages.includes(lang)) {
|
||||
// first visit
|
||||
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)
|
||||
|
||||
if (process.client) {
|
||||
watchEffect(() => {
|
||||
cookieLocale.value = i18n.locale
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
// 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
18
tests/language.test.ts
Normal 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"')
|
||||
})
|
||||
})
|
|
@ -74,6 +74,3 @@ export interface BuildInfo {
|
|||
branch: string
|
||||
env: 'preview' | 'canary' | 'dev' | 'release'
|
||||
}
|
||||
|
||||
export type FontSize = 'xs' | 'sm' | 'md' | 'lg' | 'xl'
|
||||
export type ColorMode = 'light' | 'dark'
|
||||
|
|
16
utils/language.ts
Normal file
16
utils/language.ts
Normal 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
|
||||
}
|
Loading…
Reference in a new issue