koel/resources/assets/js/stores/preferenceStore.ts

80 lines
2 KiB
TypeScript
Raw Normal View History

2022-04-15 14:24:30 +00:00
import { userStore } from '.'
2022-04-24 08:50:45 +00:00
import { localStorageService } from '@/services'
2022-04-20 15:57:53 +00:00
import { reactive } from 'vue'
2022-04-15 14:24:30 +00:00
interface Preferences extends Record<string, any> {
volume: number
notify: boolean
repeatMode: RepeatMode
showExtraPanel: boolean
confirmClosing: boolean
equalizer: EqualizerPreset,
artistsViewMode: ArtistAlbumViewMode | null,
albumsViewMode: ArtistAlbumViewMode | null,
selectedPreset: number
transcodeOnMobile: boolean
supportBarNoBugging: boolean
showAlbumArtOverlay: boolean
theme: Theme['id'] | null
}
const preferenceStore = {
storeKey: '',
2022-04-20 15:57:53 +00:00
state: reactive<Preferences>({
2022-04-15 14:24:30 +00:00
volume: 7,
notify: true,
repeatMode: 'NO_REPEAT',
showExtraPanel: true,
confirmClosing: false,
equalizer: {
preamp: 0,
gains: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
},
artistsViewMode: null,
albumsViewMode: null,
selectedPreset: -1,
transcodeOnMobile: false,
supportBarNoBugging: false,
showAlbumArtOverlay: true,
theme: null
2022-04-20 15:57:53 +00:00
}),
2022-04-15 14:24:30 +00:00
init (user?: User): void {
const initUser = user || userStore.current
this.storeKey = `preferences_${initUser.id}`
2022-04-24 08:50:45 +00:00
Object.assign(this.state, localStorageService.get(this.storeKey, this.state))
2022-04-15 14:24:30 +00:00
this.setupProxy()
},
/**
* Proxy the state properties, so that each can be directly accessed using the key.
*/
2022-04-20 15:57:53 +00:00
setupProxy () {
2022-04-15 14:24:30 +00:00
Object.keys(this.state).forEach(key => {
Object.defineProperty(this, key, {
get: (): any => this.get(key),
set: (value: any): void => this.set(key, value),
configurable: true
})
})
},
2022-04-20 15:57:53 +00:00
set (key: keyof Preferences, val: any) {
2022-04-15 14:24:30 +00:00
this.state[key] = val
this.save()
},
2022-04-20 15:57:53 +00:00
get (key: string) {
2022-04-15 14:24:30 +00:00
return key in this.state ? this.state[key] : null
},
2022-04-20 15:57:53 +00:00
save () {
2022-04-24 08:50:45 +00:00
localStorageService.set(this.storeKey, this.state)
2022-04-15 14:24:30 +00:00
}
}
const exportedPreferenceStore = preferenceStore as unknown as Omit<typeof preferenceStore, 'setupProxy'> & Preferences
export { exportedPreferenceStore as preferenceStore }