File
Blob: ui/shared/editor.svelte.ts
| 1 | import { onDestroy, untrack } from 'svelte'; |
| 2 | import { createQuery } from '@tanstack/svelte-query'; |
| 3 | import { createForm } from '@tanstack/svelte-form'; |
| 4 | import { RequestError, errorMessage } from './http'; |
| 5 | import { queryClient } from './query'; |
| 6 | |
| 7 | export type SaveOutcome<S> = { kind: 'saved'; snapshot: S } |
| 8 | | { kind: 'conflict' | 'unknown' | 'rejected'; error: RequestError }; |
| 9 | |
| 10 | // Query owns the observed snapshot, Form owns the draft, and the version belongs |
| 11 | // to the snapshot explicitly accepted as that draft's base. |
| 12 | export function createEditor<S extends { version: string }, D>(options: { |
| 13 | key: () => string; |
| 14 | defaults: D; |
| 15 | load: (signal: AbortSignal, after?: string) => Promise<S>; |
| 16 | save: (value: D, version: string, signal: AbortSignal) => Promise<S>; |
| 17 | draft: (snapshot: S) => D; |
| 18 | editable?: (snapshot: S) => boolean; |
| 19 | }) { |
| 20 | let base = $state<{ key: string; version: string } | null>(null); |
| 21 | let outcome = $state<SaveOutcome<S> | null>(null); |
| 22 | const lifetime = new AbortController(); |
| 23 | const key = $derived(options.key()); |
| 24 | const query = createQuery(() => ({ |
| 25 | queryKey: [key], enabled: key !== '', staleTime: 0, |
| 26 | queryFn: ({ signal, queryKey }) => options.load(signal, queryClient.getQueryData<S>(queryKey)?.version), |
| 27 | refetchOnMount: 'always', |
| 28 | })); |
| 29 | const form = createForm(() => ({ |
| 30 | defaultValues: options.defaults, |
| 31 | onSubmit: async ({ value }) => { |
| 32 | if (!base || base.key !== key || stale || readOnly || lifetime.signal.aborted) return; |
| 33 | const submitted = base; |
| 34 | outcome = null; |
| 35 | await queryClient.cancelQueries({ queryKey: [submitted.key] }); |
| 36 | try { |
| 37 | const saved = await options.save(value, submitted.version, lifetime.signal); |
| 38 | if (lifetime.signal.aborted || submitted.key !== key) return; |
| 39 | queryClient.setQueryData([submitted.key], saved); |
| 40 | accept(saved); |
| 41 | outcome = { kind: 'saved', snapshot: saved }; |
| 42 | } catch (cause) { |
| 43 | if (lifetime.signal.aborted || submitted.key !== key) return; |
| 44 | const error = cause instanceof RequestError ? cause : new RequestError(errorMessage(cause), 'outcome_unknown'); |
| 45 | outcome = { kind: error.status === 409 || error.code === 'version_conflict' ? 'conflict' |
| 46 | : error.code === 'outcome_unknown' ? 'unknown' : 'rejected', error }; |
| 47 | if (outcome.kind === 'conflict') await query.refetch(); |
| 48 | throw error; |
| 49 | } |
| 50 | }, |
| 51 | })); |
| 52 | const state = form.useSelector(s => ({ values: s.values, dirty: !s.isDefaultValue, saving: s.isSubmitting })); |
| 53 | const readOnly = $derived(Boolean(query.data && options.editable && !options.editable(query.data))); |
| 54 | const stale = $derived(base?.key === key && (outcome?.kind === 'conflict' || (query.data !== undefined && base.version !== query.data.version))); |
| 55 | const dirty = $derived(base?.key === key && state.current.dirty); |
| 56 | const canSave = $derived(dirty && !state.current.saving && !query.isFetching && !readOnly && !stale); |
| 57 | |
| 58 | function accept(snapshot = query.data) { |
| 59 | if (!snapshot || (options.editable && !options.editable(snapshot))) return; |
| 60 | form.reset(options.draft(snapshot)); |
| 61 | base = { key, version: snapshot.version }; |
| 62 | outcome = null; |
| 63 | } |
| 64 | |
| 65 | $effect(() => { |
| 66 | const currentKey = key; |
| 67 | const snapshot = query.data; |
| 68 | untrack(() => { |
| 69 | if (base?.key !== currentKey) { |
| 70 | base = null; |
| 71 | outcome = null; |
| 72 | form.reset(options.defaults); |
| 73 | } |
| 74 | if (snapshot && (!base || (!dirty && outcome?.kind !== 'conflict' && outcome?.kind !== 'unknown' && base.version !== snapshot.version))) accept(snapshot); |
| 75 | }); |
| 76 | }); |
| 77 | onDestroy(() => lifetime.abort()); |
| 78 | |
| 79 | return { |
| 80 | form, query, accept, |
| 81 | get values() { return state.current.values; }, |
| 82 | get initialized() { return base?.key === key; }, |
| 83 | get outcome() { return outcome; }, |
| 84 | get dirty() { return dirty; }, |
| 85 | get stale() { return stale; }, |
| 86 | get readOnly() { return readOnly; }, |
| 87 | get saving() { return state.current.saving; }, |
| 88 | get canSave() { return canSave; }, |
| 89 | get fields() { return outcome?.kind === 'rejected' ? outcome.error.fields : {}; }, |
| 90 | edited() { if (outcome?.kind === 'saved' || outcome?.kind === 'rejected') outcome = null; }, |
| 91 | async refresh() { if (!form.state.isSubmitting) await query.refetch(); }, |
| 92 | async submit(event: SubmitEvent) { |
| 93 | event.preventDefault(); |
| 94 | if (canSave && !form.state.isSubmitting) await form.handleSubmit().catch(() => {}); |
| 95 | }, |
| 96 | }; |
| 97 | } |