@cosmicdrift/kumiko-headless 0.327.0 → 0.328.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/apex/css.d.ts +3 -0
- package/{src/apex/css.ts → dist/apex/css.js} +11 -24
- package/dist/apex/index.d.ts +229 -0
- package/dist/apex/index.js +360 -0
- package/dist/apex/lightbox.d.ts +4 -0
- package/{src/apex/lightbox.ts → dist/apex/lightbox.js} +0 -4
- package/dist/contracts/asset.d.ts +15 -0
- package/dist/contracts/asset.js +17 -0
- package/dist/contracts/index.d.ts +3 -0
- package/dist/contracts/index.js +1 -0
- package/dist/contracts/locale.d.ts +7 -0
- package/dist/contracts/locale.js +11 -0
- package/dist/contracts/primitives.d.ts +93 -0
- package/dist/contracts/primitives.js +21 -0
- package/dist/dispatcher/index.d.ts +2 -0
- package/dist/dispatcher/index.js +1 -0
- package/dist/dispatcher/types.d.ts +86 -0
- package/dist/dispatcher/types.js +34 -0
- package/dist/form/form-controller.d.ts +2 -0
- package/dist/form/form-controller.js +404 -0
- package/dist/form/index.d.ts +3 -0
- package/dist/form/index.js +2 -0
- package/dist/form/types.d.ts +71 -0
- package/dist/form/types.js +1 -0
- package/dist/form/zod-bridge.d.ts +5 -0
- package/{src/form/zod-bridge.ts → dist/form/zod-bridge.js} +52 -58
- package/dist/format/escape.d.ts +5 -0
- package/{src/format/escape.ts → dist/format/escape.js} +43 -47
- package/dist/format/html-template.d.ts +9 -0
- package/dist/format/html-template.js +39 -0
- package/dist/format/index.d.ts +10 -0
- package/dist/format/index.js +192 -0
- package/dist/format/money.d.ts +1 -0
- package/{src/format/money.ts → dist/format/money.js} +6 -5
- package/dist/index.d.ts +14 -0
- package/dist/index.js +9 -0
- package/dist/locale-routing/index.d.ts +39 -0
- package/dist/locale-routing/index.js +143 -0
- package/dist/nav/index.d.ts +2 -0
- package/dist/nav/index.js +1 -0
- package/dist/nav/resolve.d.ts +2 -0
- package/dist/nav/resolve.js +58 -0
- package/dist/nav/types.d.ts +26 -0
- package/dist/nav/types.js +1 -0
- package/dist/store/create-store.d.ts +2 -0
- package/{src/store/create-store.ts → dist/store/create-store.js} +21 -23
- package/dist/store/equality.d.ts +1 -0
- package/{src/store/equality.ts → dist/store/equality.js} +19 -17
- package/dist/store/index.d.ts +3 -0
- package/dist/store/index.js +2 -0
- package/dist/store/types.d.ts +7 -0
- package/dist/store/types.js +10 -0
- package/dist/view-model/edit.d.ts +10 -0
- package/dist/view-model/edit.js +392 -0
- package/dist/view-model/embedded-list.d.ts +27 -0
- package/dist/view-model/embedded-list.js +63 -0
- package/dist/view-model/index.d.ts +7 -0
- package/dist/view-model/index.js +3 -0
- package/dist/view-model/list.d.ts +16 -0
- package/dist/view-model/list.js +201 -0
- package/dist/view-model/types.d.ts +300 -0
- package/dist/view-model/types.js +1 -0
- package/package.json +31 -12
- package/src/changes.json +7 -0
- package/src/apex/__tests__/lightbox.test.ts +0 -20
- package/src/apex/__tests__/page-head.test.ts +0 -63
- package/src/apex/__tests__/render.test.ts +0 -401
- package/src/apex/index.ts +0 -667
- package/src/contracts/__tests__/contracts.test.ts +0 -123
- package/src/contracts/__tests__/field-issue-compat.test.ts +0 -19
- package/src/contracts/asset.ts +0 -48
- package/src/contracts/index.ts +0 -23
- package/src/contracts/locale.ts +0 -33
- package/src/contracts/primitives.ts +0 -158
- package/src/dispatcher/__tests__/contract.test.ts +0 -163
- package/src/dispatcher/index.ts +0 -16
- package/src/dispatcher/types.ts +0 -217
- package/src/form/__tests__/conditional-fields.test.ts +0 -177
- package/src/form/__tests__/form-controller.test.ts +0 -231
- package/src/form/__tests__/submit.test.ts +0 -575
- package/src/form/__tests__/validation.test.ts +0 -274
- package/src/form/form-controller.ts +0 -458
- package/src/form/index.ts +0 -15
- package/src/form/types.ts +0 -297
- package/src/format/__tests__/escape.test.ts +0 -79
- package/src/format/__tests__/format.test.ts +0 -281
- package/src/format/__tests__/html-template.test.ts +0 -47
- package/src/format/html-template.ts +0 -49
- package/src/format/index.ts +0 -219
- package/src/index.ts +0 -118
- package/src/locale-routing/__tests__/locale-routing.test.ts +0 -276
- package/src/locale-routing/index.ts +0 -218
- package/src/nav/__tests__/resolve.test.ts +0 -279
- package/src/nav/index.ts +0 -8
- package/src/nav/resolve.ts +0 -60
- package/src/nav/types.ts +0 -70
- package/src/store/__tests__/create-store.test.ts +0 -139
- package/src/store/__tests__/equality.test.ts +0 -66
- package/src/store/index.ts +0 -3
- package/src/store/types.ts +0 -27
- package/src/view-model/__tests__/edit.test.ts +0 -1072
- package/src/view-model/__tests__/embedded-list.test.ts +0 -96
- package/src/view-model/__tests__/field-labels.test.ts +0 -62
- package/src/view-model/__tests__/list.test.ts +0 -428
- package/src/view-model/edit.ts +0 -641
- package/src/view-model/embedded-list.ts +0 -89
- package/src/view-model/index.ts +0 -43
- package/src/view-model/list.ts +0 -277
- package/src/view-model/types.ts +0 -392
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
// Dispatcher Contract — the interface every client-side Dispatcher implements.
|
|
2
|
+
// Two implementations ship with Kumiko:
|
|
3
|
+
//
|
|
4
|
+
// - dispatcher-live: HTTP-only, always online. Writes go straight to
|
|
5
|
+
// /api/write or /api/batch; a failed network call is a failed write.
|
|
6
|
+
// Used on the web by default and on mobile when the app is "cockpit"-
|
|
7
|
+
// style (admin dashboards, back-office UIs).
|
|
8
|
+
//
|
|
9
|
+
// - dispatcher-savable: Local-first with an outbound queue. Writes land
|
|
10
|
+
// in a local store, the queue syncs when the network is back. Used on
|
|
11
|
+
// mobile and for PWA-style web apps.
|
|
12
|
+
//
|
|
13
|
+
// The UI code never reaches for either implementation directly — it takes
|
|
14
|
+
// a `Dispatcher` through a provider/context and calls `write` / `query` /
|
|
15
|
+
// `batch`. A feature-module can therefore be rendered identically on a
|
|
16
|
+
// live-online admin screen and on a mobile app that edits offline; the
|
|
17
|
+
// dispatcher choice is an app-level concern, not a feature-level one.
|
|
18
|
+
//
|
|
19
|
+
// Result shape: `{ isSuccess: true, data } | { isSuccess: false, error }`.
|
|
20
|
+
// Pattern matches the server's WriteResult but does not import it — this
|
|
21
|
+
// package stays free of @cosmicdrift/kumiko-framework so it runs in any JS runtime
|
|
22
|
+
// (browser, Expo/React Native, Web Worker). The HTTP dispatcher adapts
|
|
23
|
+
// the server response to this shape; the savable dispatcher synthesizes
|
|
24
|
+
// it from its own state machine. The shape is the boundary, not the
|
|
25
|
+
// internal detail.
|
|
26
|
+
// SSE frame event names for POST /api/stream — shared across the server route,
|
|
27
|
+
// the live-dispatcher wire parser, and their tests so a typo on one side
|
|
28
|
+
// fails the type-checker instead of the integration test.
|
|
29
|
+
export const StreamFrame = {
|
|
30
|
+
chunk: "chunk",
|
|
31
|
+
ping: "ping",
|
|
32
|
+
done: "done",
|
|
33
|
+
error: "error",
|
|
34
|
+
};
|
|
@@ -0,0 +1,404 @@
|
|
|
1
|
+
import { createStore } from "../store/index.js";
|
|
2
|
+
import { groupIssuesByPath, zodErrorToFieldIssues } from "./zod-bridge.js";
|
|
3
|
+
// Paths without the prefix (hook-level errors, "(root)") pass through unchanged.
|
|
4
|
+
function stripServerFieldPathPrefix(issues, prefix) {
|
|
5
|
+
return issues.map((issue) => issue.path.startsWith(prefix) ? { ...issue, path: issue.path.slice(prefix.length) } : issue);
|
|
6
|
+
}
|
|
7
|
+
// Resolve one condition-value (boolean | predicate) against current values + ctx.
|
|
8
|
+
// `undefined` means "condition not declared"; the caller substitutes the
|
|
9
|
+
// field-default (visible:true, readonly:false, required:false).
|
|
10
|
+
function evalCondition(condition, fallback, values, ctx) {
|
|
11
|
+
if (condition === undefined)
|
|
12
|
+
return fallback;
|
|
13
|
+
if (typeof condition === "boolean")
|
|
14
|
+
return condition;
|
|
15
|
+
return condition(values, ctx);
|
|
16
|
+
}
|
|
17
|
+
function computeFieldStates(rules, values, ctx) {
|
|
18
|
+
if (!rules)
|
|
19
|
+
return {};
|
|
20
|
+
const out = {};
|
|
21
|
+
for (const [fieldKey, rule] of Object.entries(rules)) {
|
|
22
|
+
out[fieldKey] = {
|
|
23
|
+
visible: evalCondition(rule.visible, true, values, ctx),
|
|
24
|
+
readonly: evalCondition(rule.readonly, false, values, ctx),
|
|
25
|
+
required: evalCondition(rule.required, false, values, ctx),
|
|
26
|
+
};
|
|
27
|
+
}
|
|
28
|
+
return out;
|
|
29
|
+
}
|
|
30
|
+
// Reference equality only. For primitive-valued fields this is exact; for
|
|
31
|
+
// object/array fields it treats "same reference" as "unchanged" — callers
|
|
32
|
+
// who mutate in place instead of swapping references (which is bad form
|
|
33
|
+
// anyway, but common in ad-hoc tests) would miss a change. Kumiko's
|
|
34
|
+
// form-controller contract is that mutators build new references.
|
|
35
|
+
// Object.is is chosen over === so NaN !== NaN doesn't mark a field dirty
|
|
36
|
+
// after you re-type the same number back in.
|
|
37
|
+
function valuesDiff(current, initial) {
|
|
38
|
+
const out = {};
|
|
39
|
+
// Iterate over BOTH sides — a field that existed on initial but was
|
|
40
|
+
// deleted from current (via `setValues({ foo: undefined })`) still
|
|
41
|
+
// counts as a change.
|
|
42
|
+
// FormValues<T> erlaubt kein keyof-T-Iteration (T ist generic). Cast
|
|
43
|
+
// zu Record<string, unknown> für dynamic-key-Inspection.
|
|
44
|
+
const cur = current; // @cast-boundary form-values
|
|
45
|
+
const ini = initial; // @cast-boundary form-values
|
|
46
|
+
const o = out; // @cast-boundary form-values
|
|
47
|
+
const keys = new Set([...Object.keys(cur), ...Object.keys(ini)]);
|
|
48
|
+
for (const key of keys) {
|
|
49
|
+
const a = cur[key];
|
|
50
|
+
const b = ini[key];
|
|
51
|
+
if (!Object.is(a, b)) {
|
|
52
|
+
o[key] = a;
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
return out;
|
|
56
|
+
}
|
|
57
|
+
// buildInitialValues seeds untouched optional fields with "" for controlled
|
|
58
|
+
// inputs; a `.optional()` server schema accepts undefined but not "".
|
|
59
|
+
// String-only: number/money seed to 0 and boolean seeds to false, and an
|
|
60
|
+
// untouched optional field of those types still submits that seed instead
|
|
61
|
+
// of being omitted — no validation error surfaces it, unlike the "" case.
|
|
62
|
+
// Fixing that needs real per-field seed-tracking (which value was actually
|
|
63
|
+
// user-set vs. defaulted), not just a wider strip predicate here.
|
|
64
|
+
function stripUntouchedEmptyStrings(values, initial, forceIncludeEmpty) {
|
|
65
|
+
const v = values; // @cast-boundary form-values
|
|
66
|
+
const ini = initial; // @cast-boundary form-values
|
|
67
|
+
let out;
|
|
68
|
+
for (const key of Object.keys(v)) {
|
|
69
|
+
// Value-based seed strip, except keys previously submitted as "" after a
|
|
70
|
+
// real clear — those must survive post-rebase submits (#1858).
|
|
71
|
+
if (!forceIncludeEmpty.has(key) && v[key] === "" && ini[key] === "") {
|
|
72
|
+
out ??= { ...v };
|
|
73
|
+
delete out[key];
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
return (out ?? v);
|
|
77
|
+
}
|
|
78
|
+
// Shallow-freeze so accidental mutations on the snapshot (e.g. a test
|
|
79
|
+
// writing `snapshot.values.title = "x"`) throw in strict mode instead of
|
|
80
|
+
// silently diverging from the controller's internal state. Deep-freeze
|
|
81
|
+
// would be safer but expensive — keeping it shallow matches React's own
|
|
82
|
+
// immutability expectations and leaves room for sub-controllers to manage
|
|
83
|
+
// their own sub-trees without double-frozen parents blocking them.
|
|
84
|
+
function freezeSnapshot(snapshot) {
|
|
85
|
+
return Object.freeze(snapshot);
|
|
86
|
+
}
|
|
87
|
+
export function createFormController(options) {
|
|
88
|
+
// Shallow copy so mutating the input after creation doesn't bleed into
|
|
89
|
+
// the controller's internal state. `initial` stays fixed across the
|
|
90
|
+
// controller's lifetime unless rebase() replaces it.
|
|
91
|
+
let values = { ...options.initial };
|
|
92
|
+
let initial = { ...options.initial };
|
|
93
|
+
let errors = Object.freeze({});
|
|
94
|
+
// Keys last submitted as "" (intentional clear). Survives rebase so a later
|
|
95
|
+
// submit of other fields does not drop them (#1858).
|
|
96
|
+
const forceIncludeEmpty = new Set();
|
|
97
|
+
// ctx is cast-held as TCtx; `undefined` is valid when callers don't
|
|
98
|
+
// declare conditional predicates that depend on it.
|
|
99
|
+
let ctx = options.ctx ?? undefined;
|
|
100
|
+
// Snapshot lives in a Store — same reference across getSnapshot() calls
|
|
101
|
+
// until a mutator invalidates it via setState. React's useSyncExternalStore
|
|
102
|
+
// compares snapshot identity to decide on a re-render; the Store holds the
|
|
103
|
+
// identity stable until invalidate() swaps it for a fresh build.
|
|
104
|
+
const snapshotStore = createStore(buildSnapshot());
|
|
105
|
+
// In-flight submit tracker. When a submit() is pending, a second call
|
|
106
|
+
// awaits the same promise instead of firing a parallel write — avoids
|
|
107
|
+
// double-submission on double-click and keeps the rebase semantics
|
|
108
|
+
// coherent (rebasing twice in quick succession would mis-align the
|
|
109
|
+
// baseline with what the server actually saw).
|
|
110
|
+
let submitInFlight = null;
|
|
111
|
+
function buildSnapshot() {
|
|
112
|
+
const changes = valuesDiff(values, initial);
|
|
113
|
+
const isDirty = Object.keys(changes).length > 0;
|
|
114
|
+
const fields = Object.freeze(computeFieldStates(options.fields, values, ctx));
|
|
115
|
+
return freezeSnapshot({
|
|
116
|
+
values,
|
|
117
|
+
initial,
|
|
118
|
+
changes,
|
|
119
|
+
isDirty,
|
|
120
|
+
isUnchanged: !isDirty,
|
|
121
|
+
errors,
|
|
122
|
+
fields,
|
|
123
|
+
});
|
|
124
|
+
}
|
|
125
|
+
function invalidate() {
|
|
126
|
+
snapshotStore.setState(buildSnapshot());
|
|
127
|
+
}
|
|
128
|
+
// Local shared implementations so submit() can call validate/rebase
|
|
129
|
+
// without the this-in-object-literal dance. Both also expose themselves
|
|
130
|
+
// as methods on the returned controller.
|
|
131
|
+
// Clears/replaces errors for a scoped run without touching fields outside
|
|
132
|
+
// the scope — a step-2 validate() that comes back clean must not wipe
|
|
133
|
+
// step-1's still-unresolved errors from an earlier submit() (or vice
|
|
134
|
+
// versa when step-2 newly has issues).
|
|
135
|
+
function replaceScopedErrors(scopeSet, grouped) {
|
|
136
|
+
if (scopeSet === undefined) {
|
|
137
|
+
errors = Object.freeze(grouped);
|
|
138
|
+
// skip: unscoped replace — wholesale overwrite, nothing left to merge
|
|
139
|
+
return;
|
|
140
|
+
}
|
|
141
|
+
const merged = {};
|
|
142
|
+
for (const [path, issues] of Object.entries(errors)) {
|
|
143
|
+
if (!scopeSet.has(path))
|
|
144
|
+
merged[path] = issues;
|
|
145
|
+
}
|
|
146
|
+
Object.assign(merged, grouped);
|
|
147
|
+
errors = Object.freeze(merged);
|
|
148
|
+
}
|
|
149
|
+
function runValidate(scope, opts) {
|
|
150
|
+
// See the validate() doc comment in types.ts for the scope contract.
|
|
151
|
+
// Normalize nested scope entries (`address.city` → `address`) so wizard
|
|
152
|
+
// callers that pass dotted paths still match issue root segments (#1898).
|
|
153
|
+
const scopeSet = scope === undefined ? undefined : new Set(scope.map((s) => s.split(".")[0] ?? s));
|
|
154
|
+
const includeRoot = opts?.includeRoot === true;
|
|
155
|
+
if (!options.schema) {
|
|
156
|
+
if (Object.keys(errors).length > 0) {
|
|
157
|
+
replaceScopedErrors(scopeSet, {});
|
|
158
|
+
invalidate();
|
|
159
|
+
}
|
|
160
|
+
return true;
|
|
161
|
+
}
|
|
162
|
+
const fieldStates = computeFieldStates(options.fields, values, ctx);
|
|
163
|
+
const parsed = options.schema.safeParse(values);
|
|
164
|
+
if (parsed.success) {
|
|
165
|
+
if (Object.keys(errors).length > 0) {
|
|
166
|
+
replaceScopedErrors(scopeSet, {});
|
|
167
|
+
invalidate();
|
|
168
|
+
}
|
|
169
|
+
return true;
|
|
170
|
+
}
|
|
171
|
+
const hiddenFields = new Set();
|
|
172
|
+
for (const [fieldKey, state] of Object.entries(fieldStates)) {
|
|
173
|
+
if (!state.visible)
|
|
174
|
+
hiddenFields.add(fieldKey);
|
|
175
|
+
}
|
|
176
|
+
const allIssues = zodErrorToFieldIssues(parsed.error);
|
|
177
|
+
const relevantIssues = allIssues.filter((issue) => {
|
|
178
|
+
const rootField = issue.path.split(".")[0] ?? "";
|
|
179
|
+
if (hiddenFields.has(rootField))
|
|
180
|
+
return false;
|
|
181
|
+
// Root-level .refine() issues use path "(root)". Wizard step validate()
|
|
182
|
+
// still drops them (#1885); submit() passes includeRoot so RenderEdit
|
|
183
|
+
// fields={…} cannot silently skip cross-field rules (#1907).
|
|
184
|
+
const isRootIssue = issue.path === "(root)";
|
|
185
|
+
if (scopeSet && !(includeRoot && isRootIssue) && !scopeSet.has(rootField)) {
|
|
186
|
+
return false;
|
|
187
|
+
}
|
|
188
|
+
return true;
|
|
189
|
+
});
|
|
190
|
+
if (relevantIssues.length === 0) {
|
|
191
|
+
if (Object.keys(errors).length > 0) {
|
|
192
|
+
replaceScopedErrors(scopeSet, {});
|
|
193
|
+
invalidate();
|
|
194
|
+
}
|
|
195
|
+
return true;
|
|
196
|
+
}
|
|
197
|
+
replaceScopedErrors(scopeSet, groupIssuesByPath(relevantIssues));
|
|
198
|
+
invalidate();
|
|
199
|
+
return false;
|
|
200
|
+
}
|
|
201
|
+
function runRebase() {
|
|
202
|
+
initial = { ...values };
|
|
203
|
+
if (Object.keys(errors).length > 0)
|
|
204
|
+
errors = Object.freeze({});
|
|
205
|
+
invalidate();
|
|
206
|
+
}
|
|
207
|
+
// Stale-submit-safe rebase. Difference to runRebase: the baseline is
|
|
208
|
+
// taken from the values that were actually SENT to the server, not
|
|
209
|
+
// from `values` at the moment the server replied. If the user typed
|
|
210
|
+
// into a field while the submit was in flight, those edits stay as
|
|
211
|
+
// dirty changes after the call — they never made it to the server, so
|
|
212
|
+
// pretending they did (via `initial = { ...values }`) would mask unsaved
|
|
213
|
+
// input. The race shows up as "user edits a field during a 2s save, sees
|
|
214
|
+
// it as saved, closes the tab — the edit is lost". This path keeps
|
|
215
|
+
// `values` untouched; only `initial` shifts to the submitted snapshot.
|
|
216
|
+
function runRebaseToSnapshot(snapped) {
|
|
217
|
+
initial = { ...snapped };
|
|
218
|
+
if (Object.keys(errors).length > 0)
|
|
219
|
+
errors = Object.freeze({});
|
|
220
|
+
invalidate();
|
|
221
|
+
}
|
|
222
|
+
return {
|
|
223
|
+
getSnapshot: snapshotStore.getSnapshot,
|
|
224
|
+
subscribe: snapshotStore.subscribe,
|
|
225
|
+
setField(key, value) {
|
|
226
|
+
// skip: value unchanged, avoid notify/re-render on identical set
|
|
227
|
+
// avoids a notify + re-render for "setField with same value" which
|
|
228
|
+
// happens a lot in controlled inputs on every keystroke of an
|
|
229
|
+
// untouched field.
|
|
230
|
+
if (Object.is(values[key], value))
|
|
231
|
+
return;
|
|
232
|
+
values = { ...values, [key]: value };
|
|
233
|
+
invalidate();
|
|
234
|
+
},
|
|
235
|
+
setValues(partial) {
|
|
236
|
+
// skip: partial matches current values, avoid no-op notify
|
|
237
|
+
// partial that matches current values shouldn't fire listeners.
|
|
238
|
+
let changed = false;
|
|
239
|
+
const v = values; // @cast-boundary form-values
|
|
240
|
+
const p = partial; // @cast-boundary form-values
|
|
241
|
+
for (const k of Object.keys(p)) {
|
|
242
|
+
if (!Object.is(v[k], p[k])) {
|
|
243
|
+
changed = true;
|
|
244
|
+
break;
|
|
245
|
+
}
|
|
246
|
+
}
|
|
247
|
+
// skip: no key in partial actually changed, avoid no-op notify
|
|
248
|
+
if (!changed)
|
|
249
|
+
return;
|
|
250
|
+
values = { ...values, ...partial };
|
|
251
|
+
invalidate();
|
|
252
|
+
},
|
|
253
|
+
clearErrors(path) {
|
|
254
|
+
if (path === undefined) {
|
|
255
|
+
// skip: no errors present, avoid no-op notify
|
|
256
|
+
if (Object.keys(errors).length === 0)
|
|
257
|
+
return;
|
|
258
|
+
errors = Object.freeze({});
|
|
259
|
+
}
|
|
260
|
+
else {
|
|
261
|
+
// skip: path has no error entry, avoid no-op notify
|
|
262
|
+
if (!(path in errors))
|
|
263
|
+
return;
|
|
264
|
+
const next = { ...errors };
|
|
265
|
+
delete next[path];
|
|
266
|
+
errors = Object.freeze(next);
|
|
267
|
+
}
|
|
268
|
+
invalidate();
|
|
269
|
+
},
|
|
270
|
+
setErrors(nextErrors) {
|
|
271
|
+
errors = Object.freeze({ ...nextErrors });
|
|
272
|
+
invalidate();
|
|
273
|
+
},
|
|
274
|
+
validate: runValidate,
|
|
275
|
+
reset() {
|
|
276
|
+
const alreadyClean = !snapshotStore.getSnapshot().isDirty && Object.keys(errors).length === 0;
|
|
277
|
+
// skip: already at baseline with no errors, no-op reset
|
|
278
|
+
if (alreadyClean)
|
|
279
|
+
return;
|
|
280
|
+
values = { ...initial };
|
|
281
|
+
errors = Object.freeze({});
|
|
282
|
+
forceIncludeEmpty.clear();
|
|
283
|
+
invalidate();
|
|
284
|
+
},
|
|
285
|
+
rebase: runRebase,
|
|
286
|
+
setCtx(nextCtx) {
|
|
287
|
+
// Cast back to TCtx: setCtx's public signature takes unknown so
|
|
288
|
+
// callers don't need to plumb generics. If conditions depend on ctx
|
|
289
|
+
// and callers pass the wrong shape, the predicate throws at
|
|
290
|
+
// evaluation time — which is the same fail mode as any other
|
|
291
|
+
// callback contract violation.
|
|
292
|
+
ctx = nextCtx;
|
|
293
|
+
invalidate();
|
|
294
|
+
},
|
|
295
|
+
async submit() {
|
|
296
|
+
const submitCfg = options.submit;
|
|
297
|
+
if (!submitCfg) {
|
|
298
|
+
throw new Error("createFormController: submit() called without a `submit` config. Configure `{ dispatcher, type }` on the controller or drive dispatching manually.");
|
|
299
|
+
}
|
|
300
|
+
// Concurrent-submit guard: a double-click (two invocations before
|
|
301
|
+
// the first network call returned) would otherwise fire two writes
|
|
302
|
+
// AND rebase twice — compounding with the stale-submit race below.
|
|
303
|
+
// Serialize: subsequent calls await the in-flight promise. Same
|
|
304
|
+
// pattern the server-side event-dispatcher uses (inFlightTurns).
|
|
305
|
+
if (submitInFlight)
|
|
306
|
+
return submitInFlight;
|
|
307
|
+
if (!runValidate(submitCfg.validateScope, { includeRoot: true })) {
|
|
308
|
+
return { validationBlocked: true, isSuccess: false };
|
|
309
|
+
}
|
|
310
|
+
const payloadMode = submitCfg.payloadMode ?? "values";
|
|
311
|
+
// Capture the whole snapshot AT submit-time. The user may keep
|
|
312
|
+
// typing while the network call is in flight; on success we rebase
|
|
313
|
+
// ONLY to the values that were actually sent, leaving any
|
|
314
|
+
// subsequent edits as a fresh dirty delta. Without this, an edit
|
|
315
|
+
// during the await would be swallowed into the new baseline and
|
|
316
|
+
// the user would see it as "saved" despite the server never seeing
|
|
317
|
+
// it. Same snapshot is fed to buildPayload — a custom transformer
|
|
318
|
+
// (nested-write case) sees exactly what submit() sees.
|
|
319
|
+
const submittedSnapshot = snapshotStore.getSnapshot();
|
|
320
|
+
const submittedValues = submittedSnapshot.values;
|
|
321
|
+
// buildPayload wins over payloadMode when both are set.
|
|
322
|
+
let payload;
|
|
323
|
+
if (submitCfg.buildPayload) {
|
|
324
|
+
payload = submitCfg.buildPayload(submittedSnapshot);
|
|
325
|
+
}
|
|
326
|
+
else if (payloadMode === "changes") {
|
|
327
|
+
if (submittedSnapshot.isUnchanged) {
|
|
328
|
+
return {
|
|
329
|
+
validationBlocked: false,
|
|
330
|
+
isSuccess: true,
|
|
331
|
+
isNoOp: true,
|
|
332
|
+
data: submittedValues,
|
|
333
|
+
};
|
|
334
|
+
}
|
|
335
|
+
payload = submittedSnapshot.changes;
|
|
336
|
+
}
|
|
337
|
+
else if (submitCfg.stripEmptySeeds === false) {
|
|
338
|
+
payload = submittedValues;
|
|
339
|
+
}
|
|
340
|
+
else {
|
|
341
|
+
payload = stripUntouchedEmptyStrings(submittedValues, submittedSnapshot.initial, forceIncludeEmpty);
|
|
342
|
+
}
|
|
343
|
+
// Only enforced here, right before the write actually happens — a
|
|
344
|
+
// form that never reaches this point (blocked by validation, or a
|
|
345
|
+
// clean payloadMode "changes" no-op) must not throw just because no
|
|
346
|
+
// dispatcher was ever wired up.
|
|
347
|
+
const dispatcher = submitCfg.dispatcher;
|
|
348
|
+
if (!dispatcher) {
|
|
349
|
+
// Return SubmitResult (not throw) so RenderEdit's banner path shows
|
|
350
|
+
// the misconfiguration instead of an unhandled rejection on save.
|
|
351
|
+
return {
|
|
352
|
+
validationBlocked: false,
|
|
353
|
+
isSuccess: false,
|
|
354
|
+
isNoOp: false,
|
|
355
|
+
error: {
|
|
356
|
+
code: "misconfigured",
|
|
357
|
+
httpStatus: 500,
|
|
358
|
+
i18nKey: "errors.internal",
|
|
359
|
+
message: "createFormController: submit() called without a dispatcher (dispatcher was absent when the form mounted). Pass `submit.dispatcher` explicitly, or mount a <DispatcherProvider> above this form.",
|
|
360
|
+
},
|
|
361
|
+
};
|
|
362
|
+
}
|
|
363
|
+
const runWrite = async () => {
|
|
364
|
+
const result = await dispatcher.write(submitCfg.type, payload);
|
|
365
|
+
if (result.isSuccess) {
|
|
366
|
+
// Remember intentional empty clears so post-rebase submits keep them (#1858).
|
|
367
|
+
if (payload && typeof payload === "object" && !Array.isArray(payload)) {
|
|
368
|
+
for (const [k, v] of Object.entries(payload)) {
|
|
369
|
+
if (v === "")
|
|
370
|
+
forceIncludeEmpty.add(k);
|
|
371
|
+
else
|
|
372
|
+
forceIncludeEmpty.delete(k);
|
|
373
|
+
}
|
|
374
|
+
}
|
|
375
|
+
// Rebase to the SNAPSHOT, not to the current values — see
|
|
376
|
+
// runRebaseToSnapshot comment for why.
|
|
377
|
+
runRebaseToSnapshot(submittedValues);
|
|
378
|
+
return { validationBlocked: false, isSuccess: true, isNoOp: false, data: result.data };
|
|
379
|
+
}
|
|
380
|
+
const serverFields = result.error.details?.fields;
|
|
381
|
+
if (serverFields && serverFields.length > 0) {
|
|
382
|
+
const prefix = submitCfg.serverFieldPathPrefix;
|
|
383
|
+
const mappedFields = prefix
|
|
384
|
+
? stripServerFieldPathPrefix(serverFields, prefix)
|
|
385
|
+
: serverFields;
|
|
386
|
+
errors = Object.freeze(groupIssuesByPath(mappedFields));
|
|
387
|
+
invalidate();
|
|
388
|
+
const error = prefix
|
|
389
|
+
? { ...result.error, details: { ...result.error.details, fields: mappedFields } }
|
|
390
|
+
: result.error;
|
|
391
|
+
return { validationBlocked: false, isSuccess: false, isNoOp: false, error };
|
|
392
|
+
}
|
|
393
|
+
return { validationBlocked: false, isSuccess: false, isNoOp: false, error: result.error };
|
|
394
|
+
};
|
|
395
|
+
submitInFlight = runWrite();
|
|
396
|
+
try {
|
|
397
|
+
return await submitInFlight;
|
|
398
|
+
}
|
|
399
|
+
finally {
|
|
400
|
+
submitInFlight = null;
|
|
401
|
+
}
|
|
402
|
+
},
|
|
403
|
+
};
|
|
404
|
+
}
|
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
export { createFormController } from "./form-controller.js";
|
|
2
|
+
export type { FieldConditionPredicate, FieldConditions, FieldConditionValue, FieldState, FormController, FormControllerOptions, FormSnapshot, FormValues, SubmitConfig, SubmitPayloadMode, SubmitResult, } from "./types.js";
|
|
3
|
+
export { groupIssuesByPath, I18N_KEY_PARAM, zodErrorToFieldIssues } from "./zod-bridge.js";
|
|
@@ -0,0 +1,71 @@
|
|
|
1
|
+
import type { ZodType } from "zod";
|
|
2
|
+
import type { Dispatcher, FieldIssue, WriteResult } from "../dispatcher/index.js";
|
|
3
|
+
export type FormValues = Record<string, unknown>;
|
|
4
|
+
export type FieldConditionPredicate<TValues extends FormValues, TCtx> = (values: TValues, ctx: TCtx) => boolean;
|
|
5
|
+
export type FieldConditionValue<TValues extends FormValues, TCtx> = boolean | FieldConditionPredicate<TValues, TCtx>;
|
|
6
|
+
export type FieldConditions<TValues extends FormValues, TCtx = unknown> = {
|
|
7
|
+
readonly visible?: FieldConditionValue<TValues, TCtx>;
|
|
8
|
+
readonly readonly?: FieldConditionValue<TValues, TCtx>;
|
|
9
|
+
readonly required?: FieldConditionValue<TValues, TCtx>;
|
|
10
|
+
};
|
|
11
|
+
export type FieldState = {
|
|
12
|
+
readonly visible: boolean;
|
|
13
|
+
readonly readonly: boolean;
|
|
14
|
+
readonly required: boolean;
|
|
15
|
+
};
|
|
16
|
+
export type FormSnapshot<TValues extends FormValues> = {
|
|
17
|
+
readonly values: TValues;
|
|
18
|
+
readonly initial: TValues;
|
|
19
|
+
readonly changes: Partial<TValues>;
|
|
20
|
+
readonly isDirty: boolean;
|
|
21
|
+
readonly isUnchanged: boolean;
|
|
22
|
+
readonly errors: Readonly<Record<string, readonly FieldIssue[]>>;
|
|
23
|
+
readonly fields: Readonly<Record<string, FieldState>>;
|
|
24
|
+
};
|
|
25
|
+
export type FormController<TValues extends FormValues> = {
|
|
26
|
+
getSnapshot(): FormSnapshot<TValues>;
|
|
27
|
+
subscribe(listener: () => void): () => void;
|
|
28
|
+
setField<K extends keyof TValues>(key: K, value: TValues[K]): void;
|
|
29
|
+
setValues(partial: Partial<TValues>): void;
|
|
30
|
+
clearErrors(path?: string): void;
|
|
31
|
+
setErrors(errors: Readonly<Record<string, readonly FieldIssue[]>>): void;
|
|
32
|
+
validate(scope?: readonly string[]): boolean;
|
|
33
|
+
reset(): void;
|
|
34
|
+
rebase(): void;
|
|
35
|
+
setCtx(ctx: unknown): void;
|
|
36
|
+
submit<TData = unknown>(): Promise<SubmitResult<TData>>;
|
|
37
|
+
};
|
|
38
|
+
export type FormControllerOptions<TValues extends FormValues, TCtx = unknown> = {
|
|
39
|
+
readonly initial: TValues;
|
|
40
|
+
readonly schema?: ZodType;
|
|
41
|
+
readonly fields?: Readonly<Record<string, FieldConditions<TValues, TCtx>>>;
|
|
42
|
+
readonly ctx?: TCtx;
|
|
43
|
+
readonly submit?: SubmitConfig<TValues>;
|
|
44
|
+
};
|
|
45
|
+
export type SubmitPayloadMode = "values" | "changes";
|
|
46
|
+
export type SubmitConfig<TValues extends FormValues = FormValues> = {
|
|
47
|
+
readonly dispatcher?: Dispatcher;
|
|
48
|
+
readonly type: string;
|
|
49
|
+
readonly payloadMode?: SubmitPayloadMode;
|
|
50
|
+
/** Only applies to payloadMode "values". Controls whether untouched
|
|
51
|
+
* empty-string fields (still equal to their initial "" seed) are
|
|
52
|
+
* stripped from the payload before dispatch — see SubmitPayloadMode's
|
|
53
|
+
* "values" doc for why the stripping exists. Default `true` (current
|
|
54
|
+
* behavior). Set `false` to send those fields as `""` unchanged. */
|
|
55
|
+
readonly stripEmptySeeds?: boolean;
|
|
56
|
+
readonly buildPayload?: (snapshot: FormSnapshot<TValues>) => unknown;
|
|
57
|
+
readonly serverFieldPathPrefix?: string;
|
|
58
|
+
/** Restricts submit()'s internal validate() call to these field names —
|
|
59
|
+
* same contract as validate()'s `scope` param. Set by RenderEdit when the
|
|
60
|
+
* caller's `fields` prop narrows which fields are rendered, so an
|
|
61
|
+
* unrendered required field can't block a submit the user can't fix.
|
|
62
|
+
* Omitted = unscoped (existing behavior, validates everything). */
|
|
63
|
+
readonly validateScope?: readonly string[];
|
|
64
|
+
};
|
|
65
|
+
export type SubmitResult<TData = unknown> = ({
|
|
66
|
+
readonly validationBlocked: false;
|
|
67
|
+
readonly isNoOp?: boolean;
|
|
68
|
+
} & WriteResult<TData>) | {
|
|
69
|
+
readonly validationBlocked: true;
|
|
70
|
+
readonly isSuccess: false;
|
|
71
|
+
};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export {};
|
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
import type { ZodError } from "zod";
|
|
2
|
+
import type { FieldIssue } from "../dispatcher/index.js";
|
|
3
|
+
export declare function zodErrorToFieldIssues(error: ZodError): FieldIssue[];
|
|
4
|
+
export declare const I18N_KEY_PARAM = "i18nKey";
|
|
5
|
+
export declare function groupIssuesByPath(issues: readonly FieldIssue[]): Record<string, readonly FieldIssue[]>;
|