diff --git a/src/core/form-store.ts b/src/core/form-store.ts new file mode 100644 index 0000000..d065a2e --- /dev/null +++ b/src/core/form-store.ts @@ -0,0 +1,73 @@ +import { FormDefinition, FormfireSettings } from '../types'; + +/** + * Manages CRUD operations on FormDefinitions within plugin settings. + * Does NOT persist --- the caller (plugin) calls saveSettings() after mutations. + */ +export class FormStore { + constructor(private settings: FormfireSettings) {} + + getAll(): FormDefinition[] { + return this.settings.forms; + } + + getById(id: string): FormDefinition | undefined { + return this.settings.forms.find(f => f.id === id); + } + + getByName(name: string): FormDefinition | undefined { + return this.settings.forms.find( + f => f.name.toLowerCase() === name.toLowerCase(), + ); + } + + add(form: FormDefinition): void { + this.settings.forms.push(form); + } + + update(id: string, patch: Partial): void { + const idx = this.settings.forms.findIndex(f => f.id === id); + if (idx === -1) return; + this.settings.forms[idx] = { ...this.settings.forms[idx], ...patch }; + } + + remove(id: string): void { + this.settings.forms = this.settings.forms.filter(f => f.id !== id); + } + + duplicate(id: string): FormDefinition | undefined { + const original = this.getById(id); + if (!original) return undefined; + const copy: FormDefinition = { + ...structuredClone(original), + id: crypto.randomUUID(), + name: `${original.name} (Copy)`, + }; + this.settings.forms.push(copy); + return copy; + } + + /** Move a form up or down in the list. */ + reorder(id: string, direction: 'up' | 'down'): void { + const idx = this.settings.forms.findIndex(f => f.id === id); + if (idx === -1) return; + const swap = direction === 'up' ? idx - 1 : idx + 1; + if (swap < 0 || swap >= this.settings.forms.length) return; + [this.settings.forms[idx], this.settings.forms[swap]] = + [this.settings.forms[swap], this.settings.forms[idx]]; + } + + /** Create a blank FormDefinition with sensible defaults. */ + createBlank(): FormDefinition { + return { + id: crypto.randomUUID(), + name: 'New Form', + icon: 'file-input', + mode: 'create', + targetFolder: '/', + fileNameTemplate: '{{date}}-{{title}}', + bodyTemplate: '', + fields: [], + }; + } +}