2023-01-12 17:52:52 +00:00
|
|
|
import type { Ref } from 'vue'
|
2023-01-15 12:23:47 +00:00
|
|
|
import type { VueI18n } from 'vue-i18n'
|
|
|
|
import type { LocaleObject } from 'vue-i18n-routing'
|
2023-01-15 14:19:22 +00:00
|
|
|
import type { PreferencesSettings, UserSettings } from './definition'
|
2023-01-12 17:52:52 +00:00
|
|
|
import { STORAGE_KEY_SETTINGS } from '~/constants'
|
|
|
|
|
2023-01-14 10:09:17 +00:00
|
|
|
export function useUserSettings() {
|
2023-01-15 12:23:47 +00:00
|
|
|
const i18n = useNuxtApp().vueApp.config.globalProperties.$i18n as VueI18n
|
|
|
|
const { locales } = i18n
|
|
|
|
const supportLanguages = (locales as LocaleObject[]).map(locale => locale.code)
|
|
|
|
return useUserLocalStorage<UserSettings>(STORAGE_KEY_SETTINGS, () => getDefaultUserSettings(supportLanguages))
|
2023-01-12 17:52:52 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
// TODO: refactor & simplify this
|
|
|
|
|
2023-01-15 14:19:22 +00:00
|
|
|
export function usePreferences<T extends keyof PreferencesSettings>(name: T): Ref<PreferencesSettings[T]> {
|
2023-01-12 17:52:52 +00:00
|
|
|
const userSettings = useUserSettings()
|
|
|
|
return computed({
|
|
|
|
get() {
|
2023-01-15 14:19:22 +00:00
|
|
|
return getPreferences(userSettings.value, name)
|
2023-01-12 17:52:52 +00:00
|
|
|
},
|
|
|
|
set(value) {
|
2023-01-15 14:19:22 +00:00
|
|
|
userSettings.value.preferences[name] = value
|
2023-01-12 17:52:52 +00:00
|
|
|
},
|
|
|
|
})
|
|
|
|
}
|
|
|
|
|
2023-01-15 14:19:22 +00:00
|
|
|
export function getPreferences<T extends keyof PreferencesSettings>(userSettings: UserSettings, name: T): PreferencesSettings[T] {
|
|
|
|
return userSettings?.preferences?.[name] ?? DEFAULT__PREFERENCES_SETTINGS[name]
|
2023-01-12 17:52:52 +00:00
|
|
|
}
|
|
|
|
|
2023-01-15 14:19:22 +00:00
|
|
|
export function togglePreferences(key: keyof PreferencesSettings) {
|
|
|
|
const flag = usePreferences(key)
|
2023-01-12 17:52:52 +00:00
|
|
|
flag.value = !flag.value
|
|
|
|
}
|