Line data Source code
1 : import { toRaw } from 'vue'
2 : import { fromZodError } from 'zod-validation-error'
3 :
4 : import {
5 : BUILT_IN_THEME_PRESETS,
6 : DEFAULT_THEME_PRESET
7 : } from '@comfyorg/theme-core/builtInThemePresets'
8 : import { resolveTheme } from '@comfyorg/theme-core/resolveTheme'
9 : import { themePresetSchema } from '@comfyorg/theme-core/themePresetSchema'
10 : import type {
11 : ThemePreset,
12 : ThemePresets
13 : } from '@comfyorg/theme-core/themePresetSchema'
14 :
15 : import { downloadBlob } from '@/base/common/downloadUtil'
16 : import { useErrorHandling } from '@/composables/useErrorHandling'
17 : import { useSettingStore } from '@/platform/settings/settingStore'
18 : import { useApp } from '@/scripts/appInstance'
19 : import { uploadFile } from '@/scripts/utils'
20 : import { useNodeDefStore } from '@/stores/nodeDefStore'
21 :
22 : import { applyTheme } from './applyTheme'
23 : import { useThemeStore } from './themeStore'
24 :
25 2356 : let latestThemeSwitch = 0
26 :
27 0 : function availableCustomPresetId(id: string, presets: ThemePresets) {
28 0 : let candidate = `${id}-custom`
29 0 : let suffix = 2
30 0 : while (
31 : Object.hasOwn(presets, candidate) ||
32 : Object.hasOwn(BUILT_IN_THEME_PRESETS, candidate)
33 : ) {
34 0 : candidate = `${id}-custom-${suffix++}`
35 : }
36 0 : return candidate
37 : }
38 :
39 2383 : function persistSplashColors() {
40 2383 : try {
41 2383 : const body = getComputedStyle(document.body)
42 2383 : localStorage.setItem('comfy-splash-bg', body.backgroundColor)
43 2383 : localStorage.setItem('comfy-splash-fg', body.color)
44 : } catch {
45 0 : return
46 : }
47 : }
48 :
49 2356 : export const useThemeService = () => {
50 6811 : const themeStore = useThemeStore()
51 6811 : const settingStore = useSettingStore()
52 6811 : const nodeDefStore = useNodeDefStore()
53 6811 : const {
54 : toastErrorHandler,
55 : wrapWithErrorHandling,
56 : wrapWithErrorHandlingAsync
57 : } = useErrorHandling()
58 :
59 1 : async function persistCustomThemePresets() {
60 1 : await settingStore.set(
61 : 'Comfy.CustomColorPalettes',
62 : themeStore.customPresets
63 : )
64 : }
65 :
66 2355 : async function loadCustomThemePresets() {
67 2355 : const presets = settingStore.exists('Comfy.CustomColorPalettes')
68 : ? settingStore.get('Comfy.CustomColorPalettes')
69 : : {}
70 2355 : const conflicts = Object.keys(presets).filter((id) =>
71 : Object.hasOwn(BUILT_IN_THEME_PRESETS, id)
72 : )
73 2355 : const migrated = { ...presets }
74 2355 : const previousId = settingStore.exists('Comfy.ColorPalette')
75 : ? settingStore.get('Comfy.ColorPalette')
76 : : DEFAULT_THEME_PRESET.id
77 2355 : let activeId = previousId
78 2355 : for (const id of conflicts) {
79 0 : const newId = availableCustomPresetId(id, migrated)
80 0 : migrated[newId] = { ...migrated[id], id: newId }
81 0 : delete migrated[id]
82 0 : if (activeId === id) activeId = newId
83 : }
84 2355 : themeStore.customPresets = migrated
85 2355 : if (!Object.hasOwn(themeStore.presetsLookup, activeId)) {
86 0 : activeId = DEFAULT_THEME_PRESET.id
87 : }
88 2355 : if (!conflicts.length && activeId === previousId) return
89 :
90 2355 : await settingStore.setMany({
91 : 'Comfy.CustomColorPalettes': migrated,
92 : ...(activeId !== previousId ? { 'Comfy.ColorPalette': activeId } : {})
93 : })
94 : }
95 :
96 0 : async function deleteCustomThemePreset(id: string) {
97 0 : if (!themeStore.deleteCustomPreset(id)) {
98 0 : toastErrorHandler(new Error(`Palette with id ${id} does not exist`))
99 0 : return
100 : }
101 0 : await persistCustomThemePresets()
102 : }
103 :
104 1 : function validateThemePreset(data: unknown): data is ThemePreset {
105 1 : const result = themePresetSchema.safeParse(data)
106 1 : if (!result.success) {
107 0 : toastErrorHandler(fromZodError(result.error))
108 0 : return false
109 : }
110 1 : return true
111 : }
112 :
113 1 : async function addCustomThemePreset(data: unknown) {
114 1 : if (!validateThemePreset(data)) return
115 1 : if (!themeStore.addCustomPreset(data)) {
116 0 : toastErrorHandler(new Error(`Palette with id ${data.id} already exists`))
117 0 : return
118 : }
119 1 : await persistCustomThemePresets()
120 1 : return data
121 : }
122 :
123 2385 : async function setActiveTheme(id: string) {
124 2385 : const preset = themeStore.presetsLookup[id]
125 2385 : if (!preset) {
126 0 : toastErrorHandler(new Error(`Color palette ${id} not found`))
127 0 : return
128 : }
129 2385 : const theme = resolveTheme(preset)
130 2385 : const root = document.documentElement
131 2385 : const themeSwitch = ++latestThemeSwitch
132 2385 : root.dataset.paletteSwitching = ''
133 2385 : try {
134 2385 : applyTheme(theme, {
135 : style: root.style,
136 : canvas: useApp().canvas,
137 : dataTypes: nodeDefStore.nodeDataTypes,
138 : backgroundImage: settingStore.get('Comfy.Canvas.BackgroundImage')
139 : })
140 2385 : themeStore.activePresetId = id
141 : } finally {
142 2385 : requestAnimationFrame(() =>
143 : requestAnimationFrame(() => {
144 2385 : if (themeSwitch !== latestThemeSwitch) return
145 2383 : delete root.dataset.paletteSwitching
146 2383 : persistSplashColors()
147 : })
148 : )
149 : }
150 : }
151 :
152 0 : function exportThemePreset(id: string) {
153 0 : const preset = themeStore.presetsLookup[id]
154 0 : if (!preset) {
155 0 : toastErrorHandler(new Error(`Color palette ${id} not found`))
156 0 : return
157 : }
158 0 : downloadBlob(
159 : preset.id + '.json',
160 : new Blob([JSON.stringify(toRaw(preset), null, 2)], {
161 : type: 'application/json'
162 : })
163 : )
164 : }
165 :
166 0 : async function importThemePreset(): Promise<ThemePreset | undefined> {
167 : const file = await uploadFile('application/json')
168 0 : const text = await file.text()
169 : const data: unknown = JSON.parse(text)
170 0 : return addCustomThemePreset(data)
171 : }
172 :
173 6811 : return {
174 : getActiveTheme: () => themeStore.activeTheme,
175 : loadCustomThemePresets: wrapWithErrorHandlingAsync(loadCustomThemePresets),
176 : addCustomThemePreset: wrapWithErrorHandlingAsync(addCustomThemePreset),
177 : deleteCustomThemePreset: wrapWithErrorHandlingAsync(
178 : deleteCustomThemePreset
179 : ),
180 : setActiveTheme: wrapWithErrorHandlingAsync(setActiveTheme),
181 : exportThemePreset: wrapWithErrorHandling(exportThemePreset),
182 : importThemePreset: wrapWithErrorHandlingAsync(importThemePreset)
183 : }
184 : }
185 :
186 2355 : export function useLegacyColorPaletteService() {
187 2355 : const service = useThemeService()
188 2355 : return {
189 : getActiveColorPalette: () => service.getActiveTheme().preset,
190 : addCustomColorPalette: service.addCustomThemePreset,
191 : deleteCustomColorPalette: service.deleteCustomThemePreset,
192 : loadColorPalette: service.setActiveTheme,
193 : exportColorPalette: service.exportThemePreset,
194 : importColorPalette: service.importThemePreset
195 : }
196 : }
|