2023-01-12 20:52:52 +03:00
|
|
|
import type { Ref } from 'vue'
|
2024-02-24 19:46:14 +03:00
|
|
|
import type { LocaleObject } from '@nuxtjs/i18n'
|
2023-01-22 23:18:03 +03:00
|
|
|
import type { FontSize, OldFontSize, PreferencesSettings, UserSettings } from './definition'
|
2023-01-12 20:52:52 +03:00
|
|
|
import { STORAGE_KEY_SETTINGS } from '~/constants'
|
2023-01-22 23:18:03 +03:00
|
|
|
import { oldFontSizeMap } from '~~/constants/options'
|
2023-01-12 20:52:52 +03:00
|
|
|
|
2023-01-14 13:09:17 +03:00
|
|
|
export function useUserSettings() {
|
2024-02-24 19:46:14 +03:00
|
|
|
const { locales } = useNuxtApp().$i18n
|
|
|
|
const supportLanguages = (unref(locales) as LocaleObject[]).map(locale => locale.code)
|
2023-01-22 23:18:03 +03:00
|
|
|
const settingsStorage = useUserLocalStorage<UserSettings>(STORAGE_KEY_SETTINGS, () => getDefaultUserSettings(supportLanguages))
|
|
|
|
|
|
|
|
// Backward compatibility, font size was xs, sm, md, lg, xl before
|
|
|
|
if (settingsStorage.value.fontSize && !settingsStorage.value.fontSize.includes('px'))
|
|
|
|
settingsStorage.value.fontSize = oldFontSizeMap[settingsStorage.value.fontSize as OldFontSize] as FontSize
|
|
|
|
|
|
|
|
return settingsStorage
|
2023-01-12 20:52:52 +03:00
|
|
|
}
|
|
|
|
|
|
|
|
// TODO: refactor & simplify this
|
|
|
|
|
2023-01-15 17:19:22 +03:00
|
|
|
export function usePreferences<T extends keyof PreferencesSettings>(name: T): Ref<PreferencesSettings[T]> {
|
2023-01-12 20:52:52 +03:00
|
|
|
const userSettings = useUserSettings()
|
|
|
|
return computed({
|
|
|
|
get() {
|
2023-01-15 17:19:22 +03:00
|
|
|
return getPreferences(userSettings.value, name)
|
2023-01-12 20:52:52 +03:00
|
|
|
},
|
|
|
|
set(value) {
|
2023-01-15 17:19:22 +03:00
|
|
|
userSettings.value.preferences[name] = value
|
2023-01-12 20:52:52 +03:00
|
|
|
},
|
|
|
|
})
|
|
|
|
}
|
|
|
|
|
2023-01-15 17:19:22 +03:00
|
|
|
export function getPreferences<T extends keyof PreferencesSettings>(userSettings: UserSettings, name: T): PreferencesSettings[T] {
|
2023-02-15 13:34:23 +03:00
|
|
|
const preference = userSettings?.preferences?.[name] ?? DEFAULT__PREFERENCES_SETTINGS[name]
|
|
|
|
|
|
|
|
if (name === 'enableAutoplay')
|
|
|
|
return getPreferences(userSettings, 'enableDataSaving') ? false : preference
|
|
|
|
|
|
|
|
return preference
|
2023-01-12 20:52:52 +03:00
|
|
|
}
|
|
|
|
|
2023-01-15 17:19:22 +03:00
|
|
|
export function togglePreferences(key: keyof PreferencesSettings) {
|
|
|
|
const flag = usePreferences(key)
|
2023-01-12 20:52:52 +03:00
|
|
|
flag.value = !flag.value
|
|
|
|
}
|