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

59 lines
1.5 KiB
TypeScript
Raw Normal View History

2022-07-04 17:57:32 +00:00
import { clone } from 'lodash'
2022-04-21 22:51:48 +00:00
import { reactive } from 'vue'
2022-04-24 08:50:45 +00:00
import { preferenceStore as preferences } from '@/stores'
2022-07-04 17:57:32 +00:00
import themes from '@/themes'
2022-04-20 09:34:15 +00:00
2022-04-15 14:24:30 +00:00
export const themeStore = {
2022-07-04 17:47:46 +00:00
defaultProperties: {
'--color-text-primary': undefined,
'--color-text-secondary': undefined,
'--color-bg-primary': undefined,
'--color-bg-secondary': undefined,
'--color-highlight': undefined,
'--bg-image': undefined,
'--bg-position': undefined,
'--bg-attachment': undefined,
'--bg-size': undefined
} as Record<ThemeableProperty, string>,
2022-04-21 22:51:48 +00:00
state: reactive({
2022-07-04 17:57:32 +00:00
themes
2022-04-21 22:51:48 +00:00
}),
2022-04-15 14:24:30 +00:00
init () {
2022-07-04 17:47:46 +00:00
for (let key in this.defaultProperties) {
this.defaultProperties[key] = document.documentElement.style.getPropertyValue(key)
}
2022-04-15 14:24:30 +00:00
this.applyThemeFromPreference()
},
setTheme (theme: Theme) {
document.documentElement.setAttribute('data-theme', theme.id)
2022-07-04 17:47:46 +00:00
let properties = Object.assign(clone(this.defaultProperties), theme.properties ?? {})
2022-04-15 14:24:30 +00:00
2022-07-04 17:47:46 +00:00
for (let key in properties) {
document.documentElement.style.setProperty(key, properties[key])
}
preferences.theme = theme.id
2022-04-21 22:51:48 +00:00
this.state.themes.forEach(t => (t.selected = t.id === theme.id))
2022-04-15 14:24:30 +00:00
},
2022-04-21 22:51:48 +00:00
getThemeById (id: string) {
2022-04-15 14:24:30 +00:00
return this.state.themes.find(theme => theme.id === id)
},
getDefaultTheme (): Theme {
return this.getThemeById('classic')!
},
applyThemeFromPreference (): void {
const theme = preferences.theme
? (this.getThemeById(preferences.theme) ?? this.getDefaultTheme())
: this.getDefaultTheme()
this.setTheme(theme)
}
}