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
2022-07-25 08:35:15 +00:00
} as Record<ThemeableProperty, string | undefined>,
2022-07-04 17:47:46 +00:00
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
},
2024-01-24 22:39:47 +00:00
getThemeById (id: Theme['id']) {
2022-04-15 14:24:30 +00:00
return this.state.themes.find(theme => theme.id === id)
},
2024-07-05 12:20:30 +00:00
getDefaultTheme () {
2022-04-15 14:24:30 +00:00
return this.getThemeById('classic')!
},
2024-07-05 12:20:30 +00:00
applyThemeFromPreference () {
2022-04-15 14:24:30 +00:00
const theme = preferences.theme
? (this.getThemeById(preferences.theme) ?? this.getDefaultTheme())
: this.getDefaultTheme()
this.setTheme(theme)
}
}