fix(admin): 按 Art Design Pro 源码校准明暗主题与默认设置

This commit is contained in:
2026-12-01 16:40:54 +08:00
parent 9024e4b287
commit e1681f8d13
15 changed files with 547 additions and 363 deletions
+129 -76
View File
@@ -1,21 +1,34 @@
import { isObject } from '@vue/shared'
import { createSharedComposable, useDark, useStorage } from '@vueuse/core'
import { defineStore } from 'pinia'
import { computed, ref, watch } from 'vue'
import defaultSetting, {
SETTING_SCHEMA_MIGRATIONS,
SETTING_SCHEMA_VERSION
} from '@/config/setting'
import defaultSetting, { SETTING_SCHEMA_MIGRATIONS, SETTING_SCHEMA_VERSION } from '@/config/setting'
import { SETTING_KEY } from '@/enums/cacheEnums'
import cache from '@/utils/cache'
import { setTheme } from '@/utils/theme'
const storageSetting = cache.get(SETTING_KEY)
type AdminUi = 'legacy' | 'v2'
type ColorMode = 'auto' | 'dark' | 'light'
const APPEARANCE_KEY = 'admin_ui'
const ART_SETTING_KEY = 'admin_ui_v2_setting'
// Art Design Pro f3aaf58: config/index.ts and config/setting.ts.
export const artMainColors = ['#5D87FF', '#B48DF3', '#1D84FF', '#60C041', '#38C0FC', '#F9901F', '#FF80C8']
const artDefaults = {
...defaultSetting,
theme: artMainColors[0],
sideTheme: 'design',
sideDarkColor: '#191A23',
sideWidth: 230,
showLogo: true,
successTheme: '#13deb9',
warningTheme: '#ffae1f',
dangerTheme: '#ff4d4f',
errorTheme: '#fa896b',
colorMode: 'auto' as ColorMode
}
// A preview can seed <html data-admin-ui="v2"> before the first store is created.
// Its switch is local to that document; it never overwrites the normal entry's preference.
function initialAppearance() {
const root = document.documentElement
const preview = root.dataset.adminUi === 'v2'
@@ -24,7 +37,6 @@ function initialAppearance() {
return { preview, mode }
}
// Keep the new preference separate from the existing, versioned settings object.
export const useAdminAppearanceStore = defineStore('adminAppearance', {
state: initialAppearance,
actions: {
@@ -36,97 +48,138 @@ export const useAdminAppearanceStore = defineStore('adminAppearance', {
}
})
function applySettingSchemaMigrations(
state: Record<string, any>,
storedVersion: number
) {
if (storedVersion >= SETTING_SCHEMA_VERSION) return
for (let ver = storedVersion + 1; ver <= SETTING_SCHEMA_VERSION; ver++) {
const keys = SETTING_SCHEMA_MIGRATIONS[ver]
if (!keys) continue
for (const key of keys) {
state[key] = defaultSetting[key]
function loadLegacy(preview: boolean): Record<string, any> {
const stored = cache.get(SETTING_KEY)
const state: Record<string, any> = { ...defaultSetting, ...stored }
if (isObject(stored)) {
const version = Number(stored._settingSchemaVersion) || 0
for (let i = version + 1; i <= SETTING_SCHEMA_VERSION; i++) {
for (const key of SETTING_SCHEMA_MIGRATIONS[i] || []) state[key] = defaultSetting[key]
}
if (!preview && version < SETTING_SCHEMA_VERSION) {
cache.set(SETTING_KEY, { ...state, _settingSchemaVersion: SETTING_SCHEMA_VERSION })
}
}
state._settingSchemaVersion = SETTING_SCHEMA_VERSION
const { showDrawer, ...persist } = state
cache.set(SETTING_KEY, persist)
return { ...state, _settingSchemaVersion: SETTING_SCHEMA_VERSION }
}
function isHex(value: unknown): value is string {
return typeof value === 'string' && /^#[\da-f]{6}$/i.test(value)
}
function loadArt(legacy: Record<string, any>) {
const stored = cache.get(ART_SETTING_KEY)
// Only inherit an actual, non-default accent. The old dark menu / 183px width
// are classic preferences, not a selected Art menu style or sidebar size.
const inherited = isHex(legacy.theme) && legacy.theme.toLowerCase() !== defaultSetting.theme.toLowerCase()
? legacy.theme : artDefaults.theme
return { ...artDefaults, theme: inherited, ...(isObject(stored) ? stored : {}) }
}
function persistProfile(mode: AdminUi, state: Record<string, any>) {
// Only profile settings enter localStorage, never the drawer or the other profile.
const defaults = mode === 'v2' ? artDefaults : defaultSetting
const settings = Object.fromEntries(Object.keys(defaults).map(key => [key, state[key]]))
if (mode === 'legacy') settings._settingSchemaVersion = SETTING_SCHEMA_VERSION
cache.set(mode === 'v2' ? ART_SETTING_KEY : SETTING_KEY, settings)
}
// Upstream utils/ui/colors.ts floors each RGB channel. CSS color-mix and the
// classic theme helper round differently (notably light-9 and the dark ramp).
function artPalette(primary: string, isDark: boolean) {
const rgb = [1, 3, 5].map(i => parseInt(primary.slice(i, i + 2), 16))
const colorAt = (level: number, dark: boolean) => '#' + rgb.map(channel =>
Math.floor(dark ? channel * (1 - level) : (255 - channel) * level + channel)
.toString(16).padStart(2, '0')
).join('')
const vars: Record<string, string> = { '--el-color-primary': primary, '--el-color-primary-rgb': rgb.join(', ') }
for (let i = 1; i <= 9; i++) {
vars[`--el-color-primary-light-${i}`] = colorAt(i / 10, isDark)
vars[`--el-color-primary-dark-${i}`] = colorAt(i / 10, true)
}
// Preserve the upstream white on blue; avoid white-on-white for a custom near-white accent.
const luma = rgb[0] * .2126 + rgb[1] * .7152 + rgb[2] * .0722
vars['--zyt-on-primary'] = luma > 200 ? '#29343D' : '#fff'
vars['--zyt-selected-ink'] = !isDark && luma > 220 ? '#29343D' : primary
return vars
}
export const useSettingStore = defineStore({
id: 'setting',
state: () => {
const state: Record<string, any> = {
showDrawer: false,
...defaultSetting
const appearance = useAdminAppearanceStore()
const legacy = loadLegacy(appearance.preview)
const profiles: Record<AdminUi, Record<string, any>> = { legacy, v2: loadArt(legacy) }
return {
profiles, showDrawer: false, ...defaultSetting, colorMode: 'auto' as ColorMode,
...profiles[appearance.mode]
}
let storedVersion = SETTING_SCHEMA_VERSION
if (isObject(storageSetting)) {
storedVersion =
typeof (storageSetting as any)._settingSchemaVersion === 'number'
? (storageSetting as any)._settingSchemaVersion
: 0
Object.assign(state, storageSetting)
if (storedVersion < SETTING_SCHEMA_VERSION) {
applySettingSchemaMigrations(state, storedVersion)
}
}
state._settingSchemaVersion = SETTING_SCHEMA_VERSION
return state
},
getters: {
adminUi(): AdminUi {
return useAdminAppearanceStore().mode
}
adminUi(): AdminUi { return useAdminAppearanceStore().mode }
},
actions: {
toggleAdminUi() {
useAdminAppearanceStore().select(this.adminUi === 'v2' ? 'legacy' : 'v2')
const keys = Object.keys(this.adminUi === 'v2' ? artDefaults : defaultSetting) as (keyof typeof artDefaults)[]
this.profiles[this.adminUi] = Object.fromEntries(keys.map(key => [key, this.$state[key]]))
const mode = this.adminUi === 'v2' ? 'legacy' : 'v2'
this.$patch(this.profiles[mode])
useAdminAppearanceStore().select(mode)
},
// 设置布局设置
setSetting(data: Record<string, any>) {
const { key, value } = data
if (this.hasOwnProperty(key)) {
//@ts-ignore
this[key] = value
setSetting({ key, value }: { key: string; value: any }) {
if (!(key in this.$state) || key === 'profiles') return
this.$patch({ [key]: value })
if (key !== 'showDrawer' && !useAdminAppearanceStore().preview) {
persistProfile(this.adminUi, this.$state)
}
const settings: any = Object.assign({}, this.$state)
delete settings.showDrawer
settings._settingSchemaVersion = SETTING_SCHEMA_VERSION
cache.set(SETTING_KEY, settings)
},
// 设置主题色
setTheme(isDark: boolean) {
// An explicitly chosen accent is shared; the legacy default stays blue,
// while the v2 default is jade. Neither switch rewrites the color picker.
const rootStyle = document.documentElement.style
if (this.theme && this.theme !== defaultSetting.theme) {
rootStyle.setProperty('--zyt-user-primary', this.theme)
if (this.adminUi === 'v2') {
const vars = artPalette(isHex(this.theme) ? this.theme : artDefaults.theme, isDark)
// Separate, scoped sheet so leaving v2 instantly restores classic including poppers.
let style = document.getElementById('art-theme-vars')
if (!style) {
style = document.createElement('style')
style.id = 'art-theme-vars'
document.head.appendChild(style)
}
style.textContent = "html:root[data-admin-ui='v2']{" +
Object.entries(vars).map(([k,v]) => k + ':' + v).join(';') + '}'
} else {
rootStyle.removeProperty('--zyt-user-primary')
setTheme({
primary: this.theme, success: this.successTheme, warning: this.warningTheme,
danger: this.dangerTheme, error: this.errorTheme, info: this.infoTheme
}, isDark)
}
setTheme(
{
primary: this.theme,
success: this.successTheme,
warning: this.warningTheme,
danger: this.dangerTheme,
error: this.errorTheme,
info: this.infoTheme
},
isDark
)
},
resetTheme() {
for (const key in defaultSetting) {
//@ts-ignore
this[key] = defaultSetting[key]
if (this.adminUi === 'v2') {
this.$patch({ ...artDefaults })
if (!useAdminAppearanceStore().preview) persistProfile('v2', artDefaults)
} else {
this.$patch({ ...defaultSetting })
if (!useAdminAppearanceStore().preview) cache.remove(SETTING_KEY)
}
this._settingSchemaVersion = SETTING_SCHEMA_VERSION
cache.remove(SETTING_KEY)
useAdminAppearanceStore().select('legacy')
}
}
})
// A single system-dark listener / palette writer shared by the root and drawer.
// The old vueuse-color-scheme key remains the owner of the classic preference.
export const useAdminDark = createSharedComposable(() => {
const settings = useSettingStore()
const normalMode = useStorage<ColorMode>('vueuse-color-scheme', 'auto', undefined, { writeDefaults: false })
const classicMode = useAdminAppearanceStore().preview ? ref(normalMode.value) : normalMode
const storageRef = computed<ColorMode>({
get: () => settings.adminUi === 'v2' ? settings.colorMode : classicMode.value,
set(value) {
if (settings.adminUi === 'v2') settings.setSetting({ key: 'colorMode', value })
else classicMode.value = value
}
})
const dark = useDark({ storageRef })
watch([dark, () => settings.adminUi, () => settings.theme], () => settings.setTheme(dark.value), { immediate: true })
return dark
})
export default useSettingStore