Line data Source code
1 : import { debounce } from 'es-toolkit/compat'
2 :
3 : import { getStorageValue, setStorageValue } from '@/scripts/utils'
4 : import type { Brush } from '@comfyorg/mask-editor/types'
5 : import { useMaskEditorStore } from '@comfyorg/mask-editor/maskEditorStore'
6 :
7 29 : const STORAGE_KEY = 'maskeditor_brush_settings'
8 :
9 : type StoredBrush = Omit<Brush, 'stepSize'> & { stepSize?: number }
10 :
11 30 : function loadBrushFromStorage(): StoredBrush | null {
12 30 : try {
13 30 : const brushString = getStorageValue(STORAGE_KEY)
14 30 : if (brushString) {
15 0 : return JSON.parse(brushString) as StoredBrush
16 : }
17 30 : return null
18 : } catch (error) {
19 0 : console.error('Failed to load brush from cache:', error)
20 0 : return null
21 : }
22 : }
23 :
24 29 : const debouncedWrite = debounce((serialized: string): void => {
25 0 : try {
26 0 : setStorageValue(STORAGE_KEY, serialized)
27 : } catch (error) {
28 0 : console.error('Failed to save brush to cache:', error)
29 : }
30 : }, 300)
31 :
32 30 : export function useBrushPersistence() {
33 30 : const store = useMaskEditorStore()
34 :
35 7 : function save(): void {
36 7 : debouncedWrite(JSON.stringify(store.brushSettings))
37 : }
38 :
39 30 : function loadAndApply(): void {
40 30 : const cached = loadBrushFromStorage()
41 30 : if (!cached) return
42 0 : store.setBrushSize(cached.size)
43 0 : store.setBrushOpacity(cached.opacity)
44 0 : store.setBrushHardness(cached.hardness)
45 0 : store.brushSettings.type = cached.type
46 30 : store.setBrushStepSize(cached.stepSize ?? 5)
47 : }
48 :
49 30 : return { loadAndApply, save }
50 : }
|