import { watch } from 'vue' /** * Minimal store contract for style watcher sync. * Kept free of @/ imports so Pro can bundle these helpers from Lite. */ export interface FormBuilderStore { styleSettings: object updateStyleSettings: (path: string, value: unknown) => void } export type StyleSyncRef = { value: unknown } export interface StyleWatcherConfig { ref: StyleSyncRef storePath: string syncPaths?: string[] formBuilderStore: FormBuilderStore isSyncingFromStore: StyleSyncRef } export type StoreStyleWatcherEntry = { ref: StyleSyncRef storePath: string syncPaths: string[] } export function resolveSyncStringValue(storeValue?: string, defaultValue?: string): string { return storeValue || defaultValue || '' } export function getNestedValue(obj: object, path: string): unknown { return path.split('.').reduce((current, key) => { if (current && typeof current === 'object' && key in (current as Record)) { return (current as Record)[key] } return undefined }, obj) } export function updateStylePaths( formBuilderStore: FormBuilderStore, paths: string[], value: unknown, ): void { paths.forEach((path) => { formBuilderStore.updateStyleSettings(path, value) }) } export function createStyleWatcher(config: StyleWatcherConfig): () => void { const { ref: watchRef, storePath, syncPaths, formBuilderStore, isSyncingFromStore } = config let timeoutId: ReturnType | undefined const stop = watch( () => watchRef.value, (newValue) => { if (timeoutId) { clearTimeout(timeoutId) } if (isSyncingFromStore.value) return timeoutId = setTimeout(() => { const currentValue = getNestedValue(formBuilderStore.styleSettings, storePath) if (newValue !== currentValue) { if (syncPaths && syncPaths.length > 0) { updateStylePaths(formBuilderStore, syncPaths, newValue) } else { formBuilderStore.updateStyleSettings(storePath, newValue) } } timeoutId = undefined }, 0) }, ) return () => { if (timeoutId) { clearTimeout(timeoutId) timeoutId = undefined } stop() } } export function registerStoreStyleWatchers( entries: StoreStyleWatcherEntry[], formBuilderStore: FormBuilderStore, isSyncingFromStore: StyleSyncRef, ): void { entries.forEach((entry) => { createStyleWatcher({ ref: entry.ref, storePath: entry.storePath, syncPaths: entry.syncPaths, formBuilderStore, isSyncingFromStore, }) }) }