attaform 0.30.0 → 0.30.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/abstract.d.mts +15 -21
- package/dist/abstract.mjs +2 -2
- package/dist/dev/abstract.mjs +4 -4
- package/dist/dev/chunks/devtools.mjs +2 -2
- package/dist/dev/directive.mjs +1 -1
- package/dist/dev/history.mjs +1 -1
- package/dist/dev/index.mjs +5 -5
- package/dist/dev/runtime/plugins/attaform.mjs +1 -1
- package/dist/dev/shared/{attaform-dev.BK6Ge2qR.mjs → attaform-dev.BJK1kqHY.mjs} +14 -14
- package/dist/dev/shared/{attaform-dev.D6CLvaQT.mjs → attaform-dev.BMQ3GcgD.mjs} +46 -59
- package/dist/dev/shared/{attaform-dev.BisFstxh.mjs → attaform-dev.BUIFcTYf.mjs} +6 -6
- package/dist/dev/shared/{attaform-dev.DTrHonpc.mjs → attaform-dev.CT7MDjPy.mjs} +27 -36
- package/dist/dev/shared/{attaform-dev.BcYT6tFh.mjs → attaform-dev.CZz4GYZ6.mjs} +21 -9
- package/dist/dev/shared/{attaform-dev.DUZckyV8.mjs → attaform-dev.Chm4D6SJ.mjs} +2 -2
- package/dist/dev/shared/{attaform-dev.BcNtyOmf.mjs → attaform-dev.DuEE4GU1.mjs} +4 -4
- package/dist/dev/shared/{attaform-dev.CQ2rJiAX.mjs → attaform-dev.DxHdkkPG.mjs} +126 -115
- package/dist/dev/shared/{attaform-dev.BQc5QV3Y.mjs → attaform-dev.zlvDr0WB.mjs} +2 -2
- package/dist/dev/zod-v3.mjs +6 -6
- package/dist/dev/zod-v4.mjs +6 -6
- package/dist/dev/zod.mjs +5 -5
- package/dist/directive.d.mts +4 -4
- package/dist/directive.mjs +1 -1
- package/dist/esbuild.d.mts +11 -0
- package/dist/esbuild.mjs +1 -1
- package/dist/history.d.mts +3 -32
- package/dist/history.mjs +1 -1
- package/dist/index.d.mts +67 -70
- package/dist/index.mjs +3 -3
- package/dist/nuxt.d.mts +4 -3
- package/dist/nuxt.mjs +3 -6
- package/dist/rollup.d.mts +11 -0
- package/dist/rollup.mjs +1 -1
- package/dist/rspack.d.mts +19 -11
- package/dist/rspack.mjs +1 -1
- package/dist/runtime/components/AttaformDevtoolsPanel.vue +12 -12
- package/dist/runtime/components/DevtoolsValueTree.vue +2 -2
- package/dist/shared/{attaform.Rc9u4Vfw.d.mts → attaform.2FslhB9R.d.mts} +83 -95
- package/dist/shared/{attaform.BRDDQeHV.mjs → attaform.8mfKZCwH.mjs} +2 -2
- package/dist/shared/{attaform.DRUT703x.d.mts → attaform.B-Tb62qV.d.mts} +12 -12
- package/dist/shared/{attaform.v0fQtWyA.mjs → attaform.B1rH9ht6.mjs} +1 -1
- package/dist/shared/{attaform.ByWP6kSx.mjs → attaform.B2iebkPA.mjs} +3 -3
- package/dist/shared/{attaform.DhnPb6nK.mjs → attaform.BAf3UNn4.mjs} +1 -1
- package/dist/shared/{attaform.DNJOWjQw.mjs → attaform.BIWicztt.mjs} +102 -100
- package/dist/shared/attaform.BcQwgWaq.d.mts +2153 -0
- package/dist/shared/attaform.Br8EBn5B.d.mts +4553 -0
- package/dist/shared/{attaform.BXneBxEj.mjs → attaform.CO918TdU.mjs} +13 -13
- package/dist/shared/{attaform.CUfrMK7t.mjs → attaform.DRsANMok.mjs} +5 -5
- package/dist/shared/{attaform.B3resMQ1.mjs → attaform.D_f1WgYf.mjs} +40 -53
- package/dist/shared/{attaform.CJ8DpRGj.mjs → attaform.D_pt1gOj.mjs} +26 -33
- package/dist/shared/attaform.L0kUn3vL.d.mts +42 -0
- package/dist/shared/{attaform.BK0cgu2K.mjs → attaform.ZYn2ahzJ.mjs} +3 -3
- package/dist/transforms.d.mts +153 -26
- package/dist/transforms.mjs +1 -1
- package/dist/vite.d.mts +29 -52
- package/dist/vite.mjs +3 -3
- package/dist/webpack.d.mts +20 -12
- package/dist/webpack.mjs +1 -1
- package/dist/zod-v3.d.mts +90 -96
- package/dist/zod-v3.mjs +4 -4
- package/dist/zod-v4.d.mts +118 -118
- package/dist/zod-v4.mjs +4 -4
- package/dist/zod.d.mts +5 -5
- package/dist/zod.mjs +3 -3
- package/package.json +7 -6
- package/dist/shared/attaform.Clz0ArIi.d.mts +0 -44
- package/dist/shared/attaform.UGyOK83T.d.mts +0 -2366
- package/dist/shared/attaform.bKLzMU0o.d.mts +0 -4761
|
@@ -1,2366 +0,0 @@
|
|
|
1
|
-
import { G as GenericForm, F as FormKey, a as UseFormReturnType, _ as RegisterValue, v as Path, w as PathKey, ar as DisplayCtx, as as GetDisplayState, at as DisplayMachine, au as FieldRecord, av as ErrorCell, ad as ValidationError, aw as OriginalsRecord, A as AbstractSchema, ah as WriteMeta, d as DeepPartial, ai as WriteShape, ax as AttaformDomBinding, ay as TransformAbortHolder } from './attaform.bKLzMU0o.mjs';
|
|
2
|
-
import { Ref, ComputedRef, ShallowRef, App, InjectionKey, Plugin } from 'vue';
|
|
3
|
-
|
|
4
|
-
/**
|
|
5
|
-
* Options accepted by `injectForm` when passing an object instead of
|
|
6
|
-
* a bare key string. `__ssrAccessed: true` is set by the Phase 3
|
|
7
|
-
* `attaform-vite` transform on descendant calls whose template reads
|
|
8
|
-
* the injected form's reactive state — it tells the runtime to
|
|
9
|
-
* enqueue the form for SSR prefetch and register the descendant's
|
|
10
|
-
* `onServerPrefetch` hook. Consumers may set it manually as the
|
|
11
|
-
* escape hatch when the transform isn't installed or doesn't see
|
|
12
|
-
* the reference.
|
|
13
|
-
*/
|
|
14
|
-
type InjectFormInput = {
|
|
15
|
-
readonly key?: FormKey;
|
|
16
|
-
/**
|
|
17
|
-
* Set by the Vite transform when this `injectForm` call site sits in
|
|
18
|
-
* a component whose template / script reads the form's reactive
|
|
19
|
-
* state. On the server, this enqueues the form for SSR prefetch and
|
|
20
|
-
* wires `onServerPrefetch` so the descendant awaits the activation
|
|
21
|
-
* promise before its render emits HTML.
|
|
22
|
-
*
|
|
23
|
-
* @internal Transform-emitted. Manual use is the documented escape
|
|
24
|
-
* hatch when the transform can't reach the reference (dynamic
|
|
25
|
-
* property access, untransformed bundlers).
|
|
26
|
-
*/
|
|
27
|
-
readonly __ssrAccessed?: boolean;
|
|
28
|
-
};
|
|
29
|
-
/**
|
|
30
|
-
* Access an existing form from a descendant component without passing
|
|
31
|
-
* it through props. Counterpart to `useForm` — `useForm` creates and
|
|
32
|
-
* provides; `injectForm` looks up via Vue's inject mechanism.
|
|
33
|
-
*
|
|
34
|
-
* Three ways to call it:
|
|
35
|
-
*
|
|
36
|
-
* ```ts
|
|
37
|
-
* // Reach the nearest ancestor's anonymous useForm() call.
|
|
38
|
-
* const form = injectForm<SignupShape>()
|
|
39
|
-
*
|
|
40
|
-
* // Reach a specific form by its key — works from anywhere in the app.
|
|
41
|
-
* const cart = injectForm<CartShape>('cart')
|
|
42
|
-
*
|
|
43
|
-
* // Options form. The Vite transform emits this with `__ssrAccessed: true`
|
|
44
|
-
* // when the descendant's template / script reads the form's reactive
|
|
45
|
-
* // state, so the descendant participates in SSR prefetch coordination.
|
|
46
|
-
* const cart = injectForm<CartShape>({ key: 'cart', __ssrAccessed: true })
|
|
47
|
-
* ```
|
|
48
|
-
*
|
|
49
|
-
* Resolution rules (no-key form):
|
|
50
|
-
* - Closest ambient ancestor wins.
|
|
51
|
-
* - Only anonymous `useForm()` (no `key`) fills the ambient slot;
|
|
52
|
-
* keyed forms are reachable only via `injectForm(key)`.
|
|
53
|
-
* - Inherits the resolved ancestor's `formInstanceId`.
|
|
54
|
-
*
|
|
55
|
-
* Resolution rules (keyed form): registry lookup by string key,
|
|
56
|
-
* independent of component-tree position.
|
|
57
|
-
*
|
|
58
|
-
* Returns `null` when no matching form exists (no ambient ancestor, or
|
|
59
|
-
* the named key isn't registered yet). A dev-mode warning points at the
|
|
60
|
-
* call site, lists the registered keys, and flags the mount-timing case
|
|
61
|
-
* (a form created by a child or sibling isn't registered until its own
|
|
62
|
-
* setup runs). Always narrow before using:
|
|
63
|
-
*
|
|
64
|
-
* ```ts
|
|
65
|
-
* const form = injectForm<Shape>('signup')
|
|
66
|
-
* if (!form) return
|
|
67
|
-
* form.register('email')
|
|
68
|
-
* ```
|
|
69
|
-
*
|
|
70
|
-
* Pass the `Form` generic explicitly — Vue's provide/inject erases
|
|
71
|
-
* generics, so the library can't recover the shape automatically.
|
|
72
|
-
*
|
|
73
|
-
* The form is kept alive for this component's lifetime; once every
|
|
74
|
-
* consumer unmounts, the form is cleaned up automatically.
|
|
75
|
-
*/
|
|
76
|
-
declare function injectForm<Form extends GenericForm, GetValueFormType extends GenericForm = Form>(input?: FormKey | InjectFormInput): UseFormReturnType<Form, GetValueFormType> | null;
|
|
77
|
-
|
|
78
|
-
/**
|
|
79
|
-
* Re-bind a parent's `v-register` onto an inner native element. Use
|
|
80
|
-
* inside a component that wraps a single form field whose root is
|
|
81
|
-
* NOT the input itself (e.g. a labelled-row that renders `<label>`
|
|
82
|
-
* around the input).
|
|
83
|
-
*
|
|
84
|
-
* ```vue
|
|
85
|
-
* <!-- Parent -->
|
|
86
|
-
* <MyInput v-register="form.register('email')" />
|
|
87
|
-
*
|
|
88
|
-
* <!-- MyInput.vue -->
|
|
89
|
-
* <script setup lang="ts">
|
|
90
|
-
* import { useRegister } from 'attaform'
|
|
91
|
-
* const rv = useRegister()
|
|
92
|
-
* // rv.path / rv.segments / rv.formKey / rv.formInstanceId / rv.innerRef
|
|
93
|
-
* // are all reachable directly — no `.value` unwrap.
|
|
94
|
-
* </script>
|
|
95
|
-
*
|
|
96
|
-
* <template>
|
|
97
|
-
* <label class="field">
|
|
98
|
-
* <span>Email</span>
|
|
99
|
-
* <input v-register="rv" />
|
|
100
|
-
* </label>
|
|
101
|
-
* </template>
|
|
102
|
-
* ```
|
|
103
|
-
*
|
|
104
|
-
* Returns a hybrid Proxy: it answers `__v_isRef` / `.value` like a
|
|
105
|
-
* Vue `Ref<RegisterValue | undefined>` (so templates auto-unwrap
|
|
106
|
-
* correctly and `v-register="rv"` feeds the underlying RV to the
|
|
107
|
-
* directive — preserving the directive's path-migration diff across
|
|
108
|
-
* renders), AND every other property read pierces to the captured
|
|
109
|
-
* RV's field (so `rv.path` works directly in script setup). Reads
|
|
110
|
-
* inside reactive scopes (`computed` / `watchEffect`) track the
|
|
111
|
-
* underlying `shallowRef`, so `rv.path` re-runs when the parent
|
|
112
|
-
* rebinds to a different path.
|
|
113
|
-
*
|
|
114
|
-
* Unbound state: when the parent didn't pass `v-register`, every
|
|
115
|
-
* piercing read returns `undefined` at runtime, and the return type
|
|
116
|
-
* surfaces this honestly as `UseRegisterReturn<V> | undefined`.
|
|
117
|
-
* Consumers defend with optional chaining (`rv?.formKey`,
|
|
118
|
-
* `rv?.segments`); the directive accepts `undefined` peacefully (its
|
|
119
|
-
* binding value type is already `RegisterValue<V> | undefined`), so
|
|
120
|
-
* `v-register="rv"` works whether or not a parent has bound. The
|
|
121
|
-
* composable's `onMounted` warn fires once per instance to surface
|
|
122
|
-
* the misuse case at runtime.
|
|
123
|
-
*
|
|
124
|
-
* A wrapper meant to work both ways says so with
|
|
125
|
-
* `useRegister({ optional: true })`, which silences the unbound
|
|
126
|
-
* diagnostic and changes nothing else. Without it the diagnostic still
|
|
127
|
-
* earns its keep: a single-mode wrapper whose parent forgot
|
|
128
|
-
* `v-register` renders a field that looks fine and stores nothing.
|
|
129
|
-
*
|
|
130
|
-
* `rv?.isBound` is the test for "did a parent bind me", and it is the
|
|
131
|
-
* one to reach for: script-setup code holds the Proxy, which is an
|
|
132
|
-
* object and so always truthy, while a template holds the unwrapped
|
|
133
|
-
* ref, which is `undefined` when unbound. Those two disagree, and
|
|
134
|
-
* `isBound` reads the same on both. A dual-mode wrapper (one used
|
|
135
|
-
* both `v-register`-bound and plain `v-model`-bound) branches on it,
|
|
136
|
-
* and does not need to duplicate its element to do so: the
|
|
137
|
-
* compile-time value injection keeps an author-written `:value` /
|
|
138
|
-
* `:checked` as its unbound leg, so one element serves both (#620).
|
|
139
|
-
*
|
|
140
|
-
* Diagnostic: in dev mode, a single `console.warn` fires per instance
|
|
141
|
-
* at `onMounted` if the captured value is still `undefined` — by then
|
|
142
|
-
* the parent has had its full mount lifecycle to bind, so a missing
|
|
143
|
-
* binding is conclusive misuse. The warn does NOT fire on every read
|
|
144
|
-
* of the proxy, and is intentionally silent under SSR
|
|
145
|
-
* (`renderToString` skips `onMounted`); the CSR hydration pass
|
|
146
|
-
* surfaces the same diagnostic without double-counting through Nuxt's
|
|
147
|
-
* `dev:ssr-logs` channel.
|
|
148
|
-
*
|
|
149
|
-
* When the wrapper's root IS the input itself, Vue's attribute
|
|
150
|
-
* fallthrough handles the binding and `useRegister` is unnecessary.
|
|
151
|
-
* For wrappers that bind multiple fields (compound forms), use
|
|
152
|
-
* `injectForm<Form>(key?)` and call `ctx.register(...)` directly.
|
|
153
|
-
*/
|
|
154
|
-
|
|
155
|
-
/**
|
|
156
|
-
* Return type of `useRegister()`. Hybrid of `RegisterValue<V>` (so
|
|
157
|
-
* `rv.path` / `rv.segments` / `rv.formKey` etc. work directly in
|
|
158
|
-
* script setup) and `Ref<RegisterValue<V> | undefined>` (so Vue's
|
|
159
|
-
* template auto-unwrap surfaces the underlying RV to `v-register`
|
|
160
|
-
* and the directive's path-migration diff sees the real RV across
|
|
161
|
-
* renders).
|
|
162
|
-
*
|
|
163
|
-
* The two surfaces don't clash at the type level: `RegisterValue`
|
|
164
|
-
* doesn't carry a `value` field, and `Ref<T>`'s `value: T` becomes
|
|
165
|
-
* the hybrid's only `.value`. Older code that read `rv.value?.path`
|
|
166
|
-
* keeps working; new code can write `rv.path` directly.
|
|
167
|
-
*/
|
|
168
|
-
type UseRegisterReturn<V = unknown> = RegisterValue<V> & Ref<RegisterValue<V> | undefined> & {
|
|
169
|
-
/**
|
|
170
|
-
* Whether a parent has actually bound this wrapper. `false` until a
|
|
171
|
-
* `RegisterValue` lands, `true` once one has, and reactive in both
|
|
172
|
-
* directions: a parent that binds on a later render flips it, and
|
|
173
|
-
* so does one that stops binding.
|
|
174
|
-
*
|
|
175
|
-
* This is the test a dual-mode wrapper reaches for, and the reason
|
|
176
|
-
* it exists as a field rather than a truthiness check on the
|
|
177
|
-
* return: the composable cannot answer "is this bound" at setup
|
|
178
|
-
* time. A parent is free to bind on a later render
|
|
179
|
-
* (`v-register="ready ? form.register('x') : undefined"`), and
|
|
180
|
-
* `useRegister` has to keep serving that, so it can never return a
|
|
181
|
-
* plain `undefined` for "unbound right now". Script-setup code
|
|
182
|
-
* reading `rv` directly sees the hybrid Proxy, which is an object
|
|
183
|
-
* and therefore always truthy; a template sees the unwrapped ref,
|
|
184
|
-
* which IS `undefined` when unbound. `rv?.isBound` reads the same
|
|
185
|
-
* on both sides (#620).
|
|
186
|
-
*/
|
|
187
|
-
readonly isBound: boolean;
|
|
188
|
-
};
|
|
189
|
-
/**
|
|
190
|
-
* Options for `useRegister`.
|
|
191
|
-
*/
|
|
192
|
-
type UseRegisterOptions = {
|
|
193
|
-
/**
|
|
194
|
-
* Declares that this wrapper is used both with and without a form, so
|
|
195
|
-
* a render with no parent binding is intended rather than a mistake.
|
|
196
|
-
* Silences the unbound diagnostic; nothing else changes.
|
|
197
|
-
*
|
|
198
|
-
* The diagnostic exists because a single-mode wrapper whose parent
|
|
199
|
-
* forgot `v-register` renders a field that looks fine and stores
|
|
200
|
-
* nothing, which is an expensive afternoon. Once a wrapper is
|
|
201
|
-
* deliberately dual-mode, the same signal fires on correct code and
|
|
202
|
-
* tells the author to do something wrong, so this is the one fact
|
|
203
|
-
* that separates the two cases and only the author has it (#620).
|
|
204
|
-
*
|
|
205
|
-
* Pair it with `rv?.isBound` to branch on what actually happened.
|
|
206
|
-
*/
|
|
207
|
-
readonly optional?: boolean;
|
|
208
|
-
};
|
|
209
|
-
declare function useRegister<V = unknown>(options?: UseRegisterOptions): UseRegisterReturn<V> | undefined;
|
|
210
|
-
|
|
211
|
-
type DynamicPathSweep = {
|
|
212
|
-
/**
|
|
213
|
-
* Note that a cache has just stored an entry for `segments` under
|
|
214
|
-
* `key`. Paths a schema shape bounds are ignored, so only the
|
|
215
|
-
* candidates the sweep could ever drop are walked.
|
|
216
|
-
*/
|
|
217
|
-
readonly track: (segments: Path, key: PathKey) => void;
|
|
218
|
-
/**
|
|
219
|
-
* Register a cache's own eviction. It receives the canonical
|
|
220
|
-
* `PathKey` of a path the form no longer has, and deletes whatever it
|
|
221
|
-
* files under that path. A cache keying by more than the path (a
|
|
222
|
-
* shape sigil, say) deletes every variant; a key it never held is a
|
|
223
|
-
* no-op.
|
|
224
|
-
*/
|
|
225
|
-
readonly onEvict: (evict: (key: PathKey) => void) => void;
|
|
226
|
-
};
|
|
227
|
-
|
|
228
|
-
/**
|
|
229
|
-
* Per-form display engine: owns the clock and the timers the display
|
|
230
|
-
* reducer's timing policy needs, so the reducer itself stays a
|
|
231
|
-
* deterministic `(prev, ctx) => next` function.
|
|
232
|
-
*
|
|
233
|
-
* It keeps a `Map` of the machines that are still *active* (a spinner is
|
|
234
|
-
* showing, a verdict is being held, or a `reviewAt` deadline is pending),
|
|
235
|
-
* a single reactive `tick` ref, and a single `setTimeout` aimed at the
|
|
236
|
-
* nearest `reviewAt` across every active field. When a field-state
|
|
237
|
-
* computed reads `resolve`, it subscribes to `tick`; when the timer
|
|
238
|
-
* fires, `tick` bumps and every dependent computed re-runs the reducer,
|
|
239
|
-
* so a field whose deadline elapsed transitions (verdict → spinner, or
|
|
240
|
-
* spinner → settled verdict) without any per-field watcher.
|
|
241
|
-
*
|
|
242
|
-
* Eviction: a machine is dropped once it reaches a terminal *idle* state
|
|
243
|
-
* with no pending review. Error / success / pending machines are retained
|
|
244
|
-
* so the reducer can hold the prior verdict under the show-delay window of
|
|
245
|
-
* the *next* validation streak (no success → idle → success flicker). The
|
|
246
|
-
* retained set is bounded by the rendered non-idle fields; none of them
|
|
247
|
-
* arm a timer, so retention costs memory, never CPU.
|
|
248
|
-
*
|
|
249
|
-
* `setTimeout` invariants on the returned `reviewAt`, enforced here rather
|
|
250
|
-
* than trusted from the reducer. A non-finite deadline is ignored rather
|
|
251
|
-
* than handed to `setTimeout`, where it coerces to 0 and spins; an over-large
|
|
252
|
-
* finite deadline is clamped below the 32-bit `setTimeout` overflow; and the
|
|
253
|
-
* timer refuses to re-arm for a deadline it just fired that has also already
|
|
254
|
-
* passed. The last of those is not belt-and-braces: the library reducer's own
|
|
255
|
-
* min-visible hold re-emits ONE fixed instant for the length of the window,
|
|
256
|
-
* which is exactly the shape that stranded a field on `'pending'` forever (see
|
|
257
|
-
* `rearm`).
|
|
258
|
-
*
|
|
259
|
-
* Background tabs: `setTimeout` is throttled to >= 1s while a tab is hidden,
|
|
260
|
-
* so a min-visible hold can overshoot. A `visibilitychange` listener bumps
|
|
261
|
-
* the clock on return to the foreground, so any overdue deadline resolves at
|
|
262
|
-
* once instead of lingering.
|
|
263
|
-
*
|
|
264
|
-
* SSR: no clock, no timers, no listener. With `now` frozen and nothing
|
|
265
|
-
* validating at render, the reducer returns the plain verdict (never
|
|
266
|
-
* pending) and the engine stores nothing, so the server HTML and the
|
|
267
|
-
* client's first render agree — no hydration mismatch on the display
|
|
268
|
-
* projection.
|
|
269
|
-
*/
|
|
270
|
-
type DisplayEngine = {
|
|
271
|
-
/**
|
|
272
|
-
* Resolve a path's next `DisplayMachine`. Subscribes the calling
|
|
273
|
-
* computed to the engine clock, threads the path's previous machine
|
|
274
|
-
* through `reducer`, persists or evicts the result, and re-arms the
|
|
275
|
-
* single timer to the nearest deadline.
|
|
276
|
-
*/
|
|
277
|
-
resolve(key: PathKey, ctx: DisplayCtx, reducer: GetDisplayState): DisplayMachine;
|
|
278
|
-
/** Drop every retained machine and cancel the timer (used by `reset()`). */
|
|
279
|
-
clear(): void;
|
|
280
|
-
/** Tear down for good: `clear()` plus detaching the visibility listener. */
|
|
281
|
-
dispose(): void;
|
|
282
|
-
/** Introspection for tests: count of retained machines. Dev builds only. */
|
|
283
|
-
size?(): number;
|
|
284
|
-
/** Introspection for tests: whether a path has a retained machine. Dev builds only. */
|
|
285
|
-
has?(key: PathKey): boolean;
|
|
286
|
-
/** Introspection for tests: whether a deadline timer is armed. Dev builds only. */
|
|
287
|
-
hasTimer?(): boolean;
|
|
288
|
-
};
|
|
289
|
-
|
|
290
|
-
/**
|
|
291
|
-
* The error stores, indexed by path prefix.
|
|
292
|
-
*
|
|
293
|
-
* `aggregateErrorsAt(state, prefix)` answers "every active error at or
|
|
294
|
-
* under this path", and it used to answer it by walking every entry in
|
|
295
|
-
* all three error stores, resolving each key back to segments and
|
|
296
|
-
* testing the prefix. That is fine for one call. A table asks for one
|
|
297
|
-
* per row: `form.list('rows')` on 400 rows with 800 errors did 320,000
|
|
298
|
-
* of those tests, and a keystroke in any single row re-did all of them,
|
|
299
|
-
* costing a quarter of a second per character typed.
|
|
300
|
-
*
|
|
301
|
-
* The cost is structural, not incidental: the work is O(rows x errors)
|
|
302
|
-
* where the answer is O(errors). So the keys are collected ONCE per
|
|
303
|
-
* change to the stores, resolved to segments once, and sorted, and a
|
|
304
|
-
* query binary-searches its own window instead of scanning.
|
|
305
|
-
*
|
|
306
|
-
* ## Why a sorted key array is the right index
|
|
307
|
-
*
|
|
308
|
-
* A `PathKey` is `JSON.stringify(segments)`, so a path's descendants
|
|
309
|
-
* all begin with the parent's key minus its closing bracket, plus a
|
|
310
|
-
* comma: every key under `["rows",0]` begins `["rows",0,`. Call that
|
|
311
|
-
* the marker. Two facts make a sorted array enough:
|
|
312
|
-
*
|
|
313
|
-
* - every descendant key is >= the marker, since it begins with it;
|
|
314
|
-
* - every descendant key is <= the parent's own key, since the two
|
|
315
|
-
* agree up to the last character, where `,` (0x2C) sorts before
|
|
316
|
-
* `]` (0x5D).
|
|
317
|
-
*
|
|
318
|
-
* So `[marker, parentKey]` is a contiguous window containing every
|
|
319
|
-
* descendant and the parent itself. It is a SUPERSET, not an exact
|
|
320
|
-
* answer, and the caller still applies `isPathPrefix` to what comes
|
|
321
|
-
* back: the window narrows the scan, it does not decide membership.
|
|
322
|
-
* That split is deliberate. Membership stays where it already was, so
|
|
323
|
-
* the encoding argument above cannot quietly become the definition of
|
|
324
|
-
* a prefix.
|
|
325
|
-
*
|
|
326
|
-
* The root prefix has no marker (`[]` minus its bracket plus a comma is
|
|
327
|
-
* `[,`, which nothing begins with), and the root matches everything
|
|
328
|
-
* anyway, so it is answered by handing back the whole index.
|
|
329
|
-
*/
|
|
330
|
-
|
|
331
|
-
/** One indexed path: its key, and the segments that key decodes to. */
|
|
332
|
-
type ErrorPathEntry = {
|
|
333
|
-
readonly key: PathKey;
|
|
334
|
-
readonly segments: Path;
|
|
335
|
-
};
|
|
336
|
-
|
|
337
|
-
type FormStore<F extends GenericForm, G extends GenericForm = F> = {
|
|
338
|
-
/**
|
|
339
|
-
* The form's single liveness sweep over every per-path cache. Owned by
|
|
340
|
-
* the store rather than by `buildFormApi` because the store's own
|
|
341
|
-
* per-path maps (`fields`, `originals`, `authoredPaths`,
|
|
342
|
-
* `fieldValidationState`) are the largest thing it evicts, and they
|
|
343
|
-
* exist whether or not a form API was ever built around them. Read
|
|
344
|
-
* surfaces register their own evictions into it, so one subscription
|
|
345
|
-
* and one liveness walk serve all of them. See
|
|
346
|
-
* `dynamic-path-sweep.ts`.
|
|
347
|
-
*/
|
|
348
|
-
readonly pathSweep: DynamicPathSweep;
|
|
349
|
-
readonly formKey: FormKey;
|
|
350
|
-
readonly form: Ref<F>;
|
|
351
|
-
readonly fields: Map<PathKey, FieldRecord>;
|
|
352
|
-
/**
|
|
353
|
-
* The tagged error store: one cell per error-bearing path, each cell
|
|
354
|
-
* segregating its two sources. The `schema` side is written ONLY by
|
|
355
|
-
* the validation pipeline (`scheduleFieldValidation`, `handleSubmit`,
|
|
356
|
-
* the construction-time seed, history restore, hydration) and cleared
|
|
357
|
-
* by `reset` / `resetField` and a successful submit; the `user` side
|
|
358
|
-
* is written ONLY by the `setErrors` / `clearErrors` API surface (and
|
|
359
|
-
* history / hydration replay) and survives schema revalidation and
|
|
360
|
-
* successful submits — the consumer owns its lifetime explicitly.
|
|
361
|
-
* A key exists iff a side is non-empty; cells are replaced, never
|
|
362
|
-
* mutated, so Vue's per-key Map tracking fires for either side's
|
|
363
|
-
* change. Derived blank entries are NOT stored here — they synthesize
|
|
364
|
-
* at read (`derivedBlankErrors`).
|
|
365
|
-
*/
|
|
366
|
-
readonly errorCells: Map<PathKey, ErrorCell>;
|
|
367
|
-
/**
|
|
368
|
-
* Reactively-derived "No value supplied" errors. Pure function of
|
|
369
|
-
* `(blankPaths, schema.isRequiredAtPath)` — no writers, no clears.
|
|
370
|
-
* Membership tracks `blankPaths` automatically: typing a value into
|
|
371
|
-
* a blank required numeric field removes the path from `blankPaths`
|
|
372
|
-
* and the derived error vanishes; clearing the numeric input re-adds
|
|
373
|
-
* the path and the error reappears. The `errors` proxy and
|
|
374
|
-
* `getErrorsForPath` merge this map in alongside `schemaErrors` and
|
|
375
|
-
* `userErrors`, so consumers see the "this required field is empty"
|
|
376
|
-
* error the moment it's true — no `validate()` / `handleSubmit`
|
|
377
|
-
* call required. Honors the founding principle that
|
|
378
|
-
* `errors = f(schema, state)`.
|
|
379
|
-
*
|
|
380
|
-
* Most entries flow through this map for `number` / `bigint` leaves
|
|
381
|
-
* (where the side-channel is needed to distinguish "user typed 0"
|
|
382
|
-
* from "user supplied nothing"). String / boolean leaves only land
|
|
383
|
-
* here when the consumer explicitly opted in via the `unset`
|
|
384
|
-
* sentinel — see `docs/validation/blank.md`.
|
|
385
|
-
*/
|
|
386
|
-
readonly derivedBlankErrors: ComputedRef<ReadonlyMap<PathKey, ValidationError[]>>;
|
|
387
|
-
/**
|
|
388
|
-
* Every path carrying an error at or under `prefix`, sorted by key.
|
|
389
|
-
* `aggregateErrorsAt` takes its candidates from here instead of
|
|
390
|
-
* re-scanning all three error stores per call, which is what turns a
|
|
391
|
-
* table of N rows from O(N x errors) back into O(errors). See
|
|
392
|
-
* `error-path-index.ts`.
|
|
393
|
-
*
|
|
394
|
-
* Reading this rather than the form-global index is also what keeps
|
|
395
|
-
* containers isolated from each other. The index is one value for the
|
|
396
|
-
* whole form, so any path gaining or losing an error gives it a new
|
|
397
|
-
* identity; a container reading it directly woke on every other
|
|
398
|
-
* container's errors. Each prefix gets its own memoised `computed`
|
|
399
|
-
* that holds its previous array when its own window is unchanged, so
|
|
400
|
-
* the global change stops there. See `errorWindowAt` in the store.
|
|
401
|
-
*/
|
|
402
|
-
readonly errorWindowAt: (prefix: Path, prefixKey: PathKey) => readonly ErrorPathEntry[];
|
|
403
|
-
readonly originals: Map<PathKey, OriginalsRecord>;
|
|
404
|
-
/**
|
|
405
|
-
* Reactive set of paths whose displayed state should be EMPTY even
|
|
406
|
-
* though storage holds a real, schema-conformant value (the slim
|
|
407
|
-
* default). It exists exclusively to record **storage / display
|
|
408
|
-
* divergence** — the case where the runtime can't tell "user typed
|
|
409
|
-
* 0" from "user supplied nothing" by looking at storage alone.
|
|
410
|
-
*
|
|
411
|
-
* The mechanism shines for `number` / `bigint`: storage holds the
|
|
412
|
-
* slim default (`0` / `0n`) but the DOM input shows `''`, so the
|
|
413
|
-
* directive's input listener marks the path here on clear. Strings
|
|
414
|
-
* and booleans don't need it — `''` storage equals `''` display,
|
|
415
|
-
* `false` storage equals unchecked display — so they're never
|
|
416
|
-
* auto-marked. Consumers can still mark any primitive leaf
|
|
417
|
-
* explicitly via the `unset` sentinel (`defaultValues: { x: unset }`,
|
|
418
|
-
* `setValue('x', unset)`, `reset({ x: unset })`); the mark is then
|
|
419
|
-
* a documented signal of consumer intent rather than runtime
|
|
420
|
-
* inference.
|
|
421
|
-
*
|
|
422
|
-
* Reads (`displayValue` computed, `fields.<path>.blank`,
|
|
423
|
-
* `derivedBlankErrors` computed) track via Vue 3.5's reactive Set
|
|
424
|
-
* handlers. Writes happen inside `setValueAtPath` (gate-hook
|
|
425
|
-
* bookkeeping: `blank: true` meta adds the path; any other write
|
|
426
|
-
* removes it) and `reset`.
|
|
427
|
-
*
|
|
428
|
-
* Storage NEVER reflects this set — calculations and reads against
|
|
429
|
-
* `form.value` see the slim default. The set is purely a UI/intent
|
|
430
|
-
* channel that `derivedBlankErrors` consults to surface
|
|
431
|
-
* "No value supplied" errors for required schemas.
|
|
432
|
-
*
|
|
433
|
-
* See `docs/validation/blank.md` for the conceptual model.
|
|
434
|
-
*/
|
|
435
|
-
readonly blankPaths: Set<PathKey>;
|
|
436
|
-
/**
|
|
437
|
-
* Snapshot of `blankPaths` captured at construction (and
|
|
438
|
-
* re-captured on `reset(args)`). Used by dirty calculation: a path
|
|
439
|
-
* whose membership differs from the snapshot is dirty even if
|
|
440
|
-
* storage matches the original. Eagerly populated to avoid a "dirty
|
|
441
|
-
* on first read" race after construction.
|
|
442
|
-
*/
|
|
443
|
-
readonly originalBlankPaths: Set<PathKey>;
|
|
444
|
-
readonly schema: AbstractSchema<F, G>;
|
|
445
|
-
/**
|
|
446
|
-
* Server-side flag, plumbed in from `registry.ssr`. The
|
|
447
|
-
* `register()`-returned `markConnectedOptimistically()` reads this
|
|
448
|
-
* before flipping `connected: true`; on the client it's a no-op so
|
|
449
|
-
* the eventual directive lifecycle remains the source of truth.
|
|
450
|
-
*/
|
|
451
|
-
readonly ssr: boolean;
|
|
452
|
-
/**
|
|
453
|
-
* Per-form display engine: owns the clock and the single timer the timed
|
|
454
|
-
* display-reducer policy needs, keeping the reducer itself a
|
|
455
|
-
* pure `(prev, ctx) => next` function. The field-state computeds route
|
|
456
|
-
* every `displayState` read through `displayEngine.resolve(...)`, which
|
|
457
|
-
* threads the path's previous machine, persists or evicts the result, and
|
|
458
|
-
* re-arms the nearest-deadline timer. Constructed once at form
|
|
459
|
-
* construction; torn down via `registerCleanup` on store eviction.
|
|
460
|
-
*/
|
|
461
|
-
readonly displayEngine: DisplayEngine;
|
|
462
|
-
readonly submitting: Ref<boolean>;
|
|
463
|
-
readonly activeSubmissions: Ref<number>;
|
|
464
|
-
readonly submissionAttempts: Ref<number>;
|
|
465
|
-
/**
|
|
466
|
-
* `true` once a `handleSubmit` callback resolved without throwing.
|
|
467
|
-
* Independent of `submissionAttempts` — a failed submit increments
|
|
468
|
-
* attempts but leaves `submitted` at `false`. Cleared by `reset()`
|
|
469
|
-
* alongside the rest of the submission surface.
|
|
470
|
-
*/
|
|
471
|
-
readonly submitted: Ref<boolean>;
|
|
472
|
-
readonly submitError: Ref<Error | null>;
|
|
473
|
-
readonly departAttempts: Ref<number>;
|
|
474
|
-
/**
|
|
475
|
-
* Effective data-freeze state: `true` when either the form's own
|
|
476
|
-
* `disabled` config resolves truthy or `externalLock` is set. Read at
|
|
477
|
-
* the write chokepoint (`setValueAtPath`), the register value's
|
|
478
|
-
* `disabled`, and the field display predicate.
|
|
479
|
-
*/
|
|
480
|
-
readonly effectiveDisabled: ComputedRef<boolean>;
|
|
481
|
-
/**
|
|
482
|
-
* Wizard-driven freeze channel. `useWizard` sets this `true` for a
|
|
483
|
-
* locked step's member form; ORed into `effectiveDisabled` so the
|
|
484
|
-
* wizard lock is authoritative and a member form cannot escape it by
|
|
485
|
-
* passing `disabled: false`. Default `false`.
|
|
486
|
-
*/
|
|
487
|
-
readonly externalLock: Ref<boolean>;
|
|
488
|
-
/**
|
|
489
|
-
* `true` while a function-form `defaultValues` factory is in flight.
|
|
490
|
-
* Stays `false` for plain-value `defaultValues`. Shared across every
|
|
491
|
-
* `useForm({ key })` call that resolves to this store — the second
|
|
492
|
-
* caller sees the first caller's hydration state.
|
|
493
|
-
*/
|
|
494
|
-
readonly hydrating: Ref<boolean>;
|
|
495
|
-
/**
|
|
496
|
-
* Error from the most recent function-form `defaultValues` factory.
|
|
497
|
-
* Normalized to a `ValidationError` (code `atta:hydration-failed`) so the
|
|
498
|
-
* shape matches `form.errors` / `form.meta.errors` entries. `null` when
|
|
499
|
-
* no factory has fired or the last one succeeded.
|
|
500
|
-
*/
|
|
501
|
-
readonly hydrateError: Ref<ValidationError | null>;
|
|
502
|
-
/**
|
|
503
|
-
* The function-form `defaultValues` factory, captured at the first
|
|
504
|
-
* `useForm({ key })` call that wired this store. `undefined` for
|
|
505
|
-
* plain-value forms. Read by `form.rehydrate()`.
|
|
506
|
-
*/
|
|
507
|
-
readonly defaultValuesFactory: Ref<(() => unknown | Promise<unknown>) | undefined>;
|
|
508
|
-
/**
|
|
509
|
-
* `true` when this store carries an SSR prefetch queue (server path
|
|
510
|
-
* where `state.activate()` must enqueue intent before deciding
|
|
511
|
-
* whether to fire). The flag lets `buildFormApi` skip the lazy
|
|
512
|
-
* activation gate for forms with no factory AND no SSR prefetch —
|
|
513
|
-
* the common client-side case where `gated()` is otherwise pure
|
|
514
|
-
* reactive overhead on every public method call.
|
|
515
|
-
*/
|
|
516
|
-
readonly hasSsrPrefetch: boolean;
|
|
517
|
-
/**
|
|
518
|
-
* `true` once the form's effective defaults have been applied —
|
|
519
|
-
* sync `defaultValues` at construction, or async factory whose
|
|
520
|
-
* settle completed. Stays `false` for dormant lazy forms until they
|
|
521
|
-
* activate. Read by `useWizard` to decide whether seed status or
|
|
522
|
-
* live meta should surface.
|
|
523
|
-
*/
|
|
524
|
-
readonly defaultsResolved: Ref<boolean>;
|
|
525
|
-
/**
|
|
526
|
-
* `true` once the captured async factory has been kicked off (set
|
|
527
|
-
* synchronously by `activate()`, before the factory itself resolves).
|
|
528
|
-
* Distinct from `defaultsResolved`, which only flips after the factory
|
|
529
|
-
* settles. The pair lets the API surface tell "we've started" apart
|
|
530
|
-
* from "we're done."
|
|
531
|
-
*/
|
|
532
|
-
readonly activated: Ref<boolean>;
|
|
533
|
-
/**
|
|
534
|
-
* In-flight activation promise. Concurrent callers (cross-component
|
|
535
|
-
* SSR consumers, recursive factory reads, parallel `activate()`
|
|
536
|
-
* calls) receive the same promise, ensuring the factory runs once
|
|
537
|
-
* even under contention.
|
|
538
|
-
*/
|
|
539
|
-
readonly activationPromise: Ref<Promise<void> | undefined>;
|
|
540
|
-
/**
|
|
541
|
-
* Idempotent activation entrypoint. Fires the captured function-form
|
|
542
|
-
* `defaultValues` factory on first call and stores the in-flight
|
|
543
|
-
* promise. Subsequent calls return the same promise until the factory
|
|
544
|
-
* settles; thereafter calls return `Promise.resolve()`. Plain-value
|
|
545
|
-
* forms (no factory captured) always return a resolved promise. The
|
|
546
|
-
* public API surface routes all reactive interactions (getters and
|
|
547
|
-
* methods, except `key`) through this entrypoint so the form
|
|
548
|
-
* activates on first use.
|
|
549
|
-
*/
|
|
550
|
-
activate(): Promise<void>;
|
|
551
|
-
/**
|
|
552
|
-
* Re-fire the captured function-form `defaultValues` factory. Throws
|
|
553
|
-
* synchronously when no factory was captured (plain-value form).
|
|
554
|
-
* Resolves after `hydrating` flips back to `false`; consumers can
|
|
555
|
-
* `await form.rehydrate()` to gate UI on the fresh load.
|
|
556
|
-
*
|
|
557
|
-
* Does NOT touch touched / submit state; chain `form.reset()` if you
|
|
558
|
-
* want a clean surface. It DOES re-seat the defaults (see
|
|
559
|
-
* `adoptResolvedDefaults`), so dirty afterwards means "differs from
|
|
560
|
-
* what the factory just returned", and `form.reset()` lands on the
|
|
561
|
-
* fresh values rather than throwing them away.
|
|
562
|
-
*/
|
|
563
|
-
rehydrate(): Promise<void>;
|
|
564
|
-
/**
|
|
565
|
-
* Adopt a resolved async-defaults value as the form's durable
|
|
566
|
-
* defaults and re-seed the dirty baseline from it. Called by the
|
|
567
|
-
* activate / rehydrate orchestrator once its factory settles.
|
|
568
|
-
* Exposed on the store (rather than imported) because
|
|
569
|
-
* `form-activation` is imported BY this module; a value import back
|
|
570
|
-
* the other way would close a cycle.
|
|
571
|
-
*/
|
|
572
|
-
adoptResolvedDefaults(value: unknown): void;
|
|
573
|
-
/**
|
|
574
|
-
* Incremented by every `reset()` call. The submit wrapper captures
|
|
575
|
-
* this at entry and skips writing `submitError` from a catch that
|
|
576
|
-
* fires *after* a reset — otherwise a reset-during-submit would
|
|
577
|
-
* visibly clear `submitError` and then have it reappear when the
|
|
578
|
-
* in-flight promise rejects.
|
|
579
|
-
*/
|
|
580
|
-
readonly submissionGeneration: Ref<number>;
|
|
581
|
-
/**
|
|
582
|
-
* Counts in-flight validation calls across every `validate()` ref and
|
|
583
|
-
* every committing `parse(...)` / `handleSubmit` pre-check. `validating`
|
|
584
|
-
* on the public API mirrors `activeValidations.value > 0`. Tracked
|
|
585
|
-
* separately from submissions because a validate-while-submitting
|
|
586
|
-
* (e.g. a debounced field check overlapping a submit) needs to show
|
|
587
|
-
* the union of both surfaces.
|
|
588
|
-
*/
|
|
589
|
-
readonly activeValidations: Ref<number>;
|
|
590
|
-
/**
|
|
591
|
-
* `true` once the form has completed at least one validation pass
|
|
592
|
-
* — flips when `activeValidations` returns to 0 from any positive
|
|
593
|
-
* value. Until that happens, `meta.valid` and `field.valid` report
|
|
594
|
-
* `false` even when `schemaErrors.size === 0`, because the absence
|
|
595
|
-
* of errors at frame 1 is just "we haven't checked yet," not "we
|
|
596
|
-
* checked and it's clean."
|
|
597
|
-
*
|
|
598
|
-
* This closes the brief flash window for schemas where the slim
|
|
599
|
-
* default-derivation parse strips refinements (`.refine`,
|
|
600
|
-
* `.superRefine`, async validators): the slim parse passes, no
|
|
601
|
-
* construction-time errors land, and the queued microtask hasn't
|
|
602
|
-
* run yet — so without the gate, frame 1 paints the form as
|
|
603
|
-
* "valid" before the real verdict arrives a tick later.
|
|
604
|
-
*
|
|
605
|
-
* Reset is left untouched — the post-reset validation flips it
|
|
606
|
-
* back true on completion, same as the construction-time path.
|
|
607
|
-
*/
|
|
608
|
-
readonly firstValidationDone: Ref<boolean>;
|
|
609
|
-
/**
|
|
610
|
-
* Precomputed-key shortcut for `pathHasAsyncValidation`. The
|
|
611
|
-
* canonical key is required and must correspond to `segments`; the
|
|
612
|
-
* helper skips the `canonicalizePath` round-trip so descendant-walk
|
|
613
|
-
* loops (whose Map iteration already yields the canonical key) can
|
|
614
|
-
* read the async-gate verdict without a per-leaf canonicalize.
|
|
615
|
-
*/
|
|
616
|
-
pathHasAsyncValidationByKey(key: PathKey, segments: Path): boolean;
|
|
617
|
-
/**
|
|
618
|
-
* Per-path counter of in-flight field-level validation runs.
|
|
619
|
-
* `field.validating` on `FieldState` mirrors
|
|
620
|
-
* `(fieldValidationCounts.get(key) ?? 0) > 0`.
|
|
621
|
-
*
|
|
622
|
-
* Incremented at the same point as `activeValidations` inside
|
|
623
|
-
* `scheduleFieldValidation`'s `run` closure (right before the schema
|
|
624
|
-
* call) and decremented in the matching `.finally` — so the per-path
|
|
625
|
-
* bookkeeping is exactly co-extensive with the form-wide counter for
|
|
626
|
-
* the field-scheduled branch. Whole-form `validate()` /
|
|
627
|
-
* `parse()` runs touch `activeValidations` only; they don't
|
|
628
|
-
* have a single field path and so don't contribute here.
|
|
629
|
-
*
|
|
630
|
-
* Counter (not Set) because two runs for the same path can briefly
|
|
631
|
-
* overlap: when an in-flight run is aborted and a new run starts,
|
|
632
|
-
* the new run increments before the aborted run's `.finally`
|
|
633
|
-
* decrements. With `> 0` semantics the field stays "validating"
|
|
634
|
-
* across the abort/restart boundary.
|
|
635
|
-
*
|
|
636
|
-
* Reactive Map: Vue 3's `reactive(new Map())` proxy makes `.get()`,
|
|
637
|
-
* `.has()`, and `.size` track per-key, so the FieldState
|
|
638
|
-
* computed only re-runs when the count for ITS key changes.
|
|
639
|
-
*/
|
|
640
|
-
readonly fieldValidationCounts: Map<PathKey, number>;
|
|
641
|
-
/**
|
|
642
|
-
* Per-path `Date.now()` stamp marking when the field's LATEST validation
|
|
643
|
-
* run started, re-anchored on every run start (every increment), deleted
|
|
644
|
-
* on the `→ 0` edge. The display reducer reads it as `ctx.validatingSince`
|
|
645
|
-
* to time the anti-flash spinner, which measures `now - validatingSince`:
|
|
646
|
-
* re-anchoring on each run means a burst of keystrokes (each aborting the
|
|
647
|
-
* prior run and starting a new one) keeps pushing the stamp forward, so the
|
|
648
|
-
* spinner stays suppressed until the user pauses rather than surfacing
|
|
649
|
-
* mid-typing. Anchoring only at the streak start would pin it to the first
|
|
650
|
-
* keystroke, because with `debounceMs: 0` the aborted run's decrement lands
|
|
651
|
-
* after the next run's increment and the count never returns to 0 between
|
|
652
|
-
* fast keystrokes. The field-state container walk takes the descendant-min
|
|
653
|
-
* so a row spinner anchors at its earliest still-active leaf. Runtime-only,
|
|
654
|
-
* never hydrated, like the counts. REACTIVE: the display computed reads this
|
|
655
|
-
* (as `ctx.validatingSince`) but not the `validating` flag, and a long
|
|
656
|
-
* validation that settles with an unchanged verdict (same error, still
|
|
657
|
-
* invalid) leaves `errors` / `valid` untouched — so a non-reactive map would
|
|
658
|
-
* leave a held `pending` spinner stranded after the run ends, until some
|
|
659
|
-
* unrelated reactive change happened to re-run the computed. Reactivity ties
|
|
660
|
-
* the computed to both the streak start (set) and end (delete).
|
|
661
|
-
*/
|
|
662
|
-
readonly fieldValidatingSince: Map<PathKey, number>;
|
|
663
|
-
/**
|
|
664
|
-
* Per-path counter of in-flight async-transform runs (the async
|
|
665
|
-
* branch of the `register({ transforms })` pipeline). `> 0` drives
|
|
666
|
-
* `field.transforming` / `field.busy`. Counter, not flag, for the
|
|
667
|
-
* same overlap reason as `fieldValidationCounts`, except a superseding
|
|
668
|
-
* input releases the prior run synchronously before incrementing the
|
|
669
|
-
* new one — so the count is the live in-flight depth at the path
|
|
670
|
-
* (effectively 0 or 1). Reactive Map, like the validation counters.
|
|
671
|
-
*/
|
|
672
|
-
readonly fieldTransformCounts: Map<PathKey, number>;
|
|
673
|
-
/**
|
|
674
|
-
* Per-path `ssr ? 0 : Date.now()` stamp marking when the path's latest
|
|
675
|
-
* async transform opened; the display reducer reads it (as
|
|
676
|
-
* `ctx.transformingSince`) to time the gated busy spinner. Mirrors
|
|
677
|
-
* `fieldValidatingSince` exactly: re-anchored on each run start,
|
|
678
|
-
* deleted on the `→ 0` edge, reactive for the held-spinner reason.
|
|
679
|
-
*/
|
|
680
|
-
readonly fieldTransformingSince: Map<PathKey, number>;
|
|
681
|
-
/**
|
|
682
|
-
* Per-path latest async-transform failure (a rejected transform, or a
|
|
683
|
-
* resolved value the write gate refused), surfaced as
|
|
684
|
-
* `field.transformError`. Cleared when a fresh run opens at the path
|
|
685
|
-
* and on `reset()`. A channel separate from validation `errors`.
|
|
686
|
-
*/
|
|
687
|
-
readonly transformErrors: Map<PathKey, Error | null>;
|
|
688
|
-
/**
|
|
689
|
-
* Form-wide count of in-flight async-transform runs. Drives the
|
|
690
|
-
* `settleTransforms` quiescence guard and the `handleSubmit` drain
|
|
691
|
-
* barrier. `Math.max(0, …)`-clamped on release so a doubled decrement
|
|
692
|
-
* (a run's own `endTransform` after a synchronous cancel release)
|
|
693
|
-
* can't drive it negative.
|
|
694
|
-
*/
|
|
695
|
-
readonly activeTransforms: Ref<number>;
|
|
696
|
-
/**
|
|
697
|
-
* Replace the form value wholesale. Optional `meta` is forwarded to
|
|
698
|
-
* every `onFormChange` listener so they can decide whether THIS write
|
|
699
|
-
* is one they care about (e.g. history tagging a hydration replay).
|
|
700
|
-
*/
|
|
701
|
-
applyFormReplacement(next: F, meta?: WriteMeta): void;
|
|
702
|
-
/**
|
|
703
|
-
* Set a single path's value. `meta` is forwarded to listeners via
|
|
704
|
-
* `applyFormReplacement` (see above). Public `form.setValue` passes no
|
|
705
|
-
* meta.
|
|
706
|
-
*
|
|
707
|
-
* Returns `false` when the slim-primitive gate rejects the write
|
|
708
|
-
* (the value's primitive shape doesn't match the schema's slim
|
|
709
|
-
* shape at the path). The store is unchanged in that case.
|
|
710
|
-
*/
|
|
711
|
-
setValueAtPath(path: Path, value: unknown, meta?: WriteMeta): boolean;
|
|
712
|
-
getValueAtPath(path: Path): unknown;
|
|
713
|
-
/**
|
|
714
|
-
* Stable identity for the array element at `path`. An array element
|
|
715
|
-
* (numeric last segment) carries its allocated identity token,
|
|
716
|
-
* maintained by the arrays engine across structural mutations.
|
|
717
|
-
* Empty for any non-array-element path: a record entry, a
|
|
718
|
-
* fixed-object field, a container, or the root. Backs `FieldState.key`.
|
|
719
|
-
*/
|
|
720
|
-
arrayElementKey(path: Path): string;
|
|
721
|
-
reset(nextDefaultValues?: DeepPartial<WriteShape<F>>): void;
|
|
722
|
-
resetField(path: Path): void;
|
|
723
|
-
setSchemaErrorsForPath(path: Path, errors: ValidationError[]): void;
|
|
724
|
-
setAllSchemaErrors(errors: readonly ValidationError[]): void;
|
|
725
|
-
clearSchemaErrors(path?: Path): void;
|
|
726
|
-
/**
|
|
727
|
-
* Replace `schemaErrors` under `path` with `errors`, keying each
|
|
728
|
-
* error by its OWN absolute path. Used by validation pipelines
|
|
729
|
-
* (scheduleFieldValidation, the committing parse, handleSubmit, reset)
|
|
730
|
-
* to commit a parse result wholesale — entries not in the new
|
|
731
|
-
* pass get dropped from the subtree, surviving keys update in
|
|
732
|
-
* place to preserve insertion order. Pass `path === []` for the
|
|
733
|
-
* whole-form scope.
|
|
734
|
-
*/
|
|
735
|
-
applySchemaErrorsForSubtree(path: Path, errors: ValidationError[]): void;
|
|
736
|
-
setAllUserErrors(errors: readonly ValidationError[]): void;
|
|
737
|
-
setUserErrorsForPath(path: Path, errors: readonly ValidationError[]): void;
|
|
738
|
-
clearUserErrors(path?: Path): void;
|
|
739
|
-
/**
|
|
740
|
-
* Rebuild the whole tagged store from a snapshot's `[key, cell]`
|
|
741
|
-
* entries — the history ring buffer's restore road. Entry arrays are
|
|
742
|
-
* cloned in, so the snapshot stays detached from the live store;
|
|
743
|
-
* cells with both sides empty are skipped.
|
|
744
|
-
*/
|
|
745
|
-
restoreErrorCells(entries: ReadonlyArray<readonly [PathKey, ErrorCell]>): void;
|
|
746
|
-
/**
|
|
747
|
-
* Merged read — the cell at `path` in schema -> blank -> user order.
|
|
748
|
-
* Schema errors come first (structural validation before business
|
|
749
|
-
* logic), the derived blank entry synthesizes between, and user
|
|
750
|
-
* entries close, matching the iteration order for
|
|
751
|
-
* `getFirstErrorElement` and the top-level `errors` drillable Proxy.
|
|
752
|
-
*/
|
|
753
|
-
getErrorsForPath(path: Path): ValidationError[];
|
|
754
|
-
/**
|
|
755
|
-
* Returns a stable schema-declaration ordinal for `key`, assigning a
|
|
756
|
-
* fresh one if the path hasn't been seen before. Drives
|
|
757
|
-
* `form.meta.errors` sort order so the aggregate is a function of the
|
|
758
|
-
* SET of errors currently present (not the temporal order their
|
|
759
|
-
* Map keys were last `set`). Construction-time seed walks every leaf
|
|
760
|
-
* in the schema's slim default; runtime callers (DU variant 2, dynamic
|
|
761
|
-
* array indices, refines targeting cross-field paths) pick up
|
|
762
|
-
* first-encounter ordinals and keep them for the form's lifetime.
|
|
763
|
-
*/
|
|
764
|
-
ensurePathOrdinal(key: PathKey): number;
|
|
765
|
-
/**
|
|
766
|
-
* The store's DOM slice, `null` until the directive cluster or
|
|
767
|
-
* `useRegister` arms it via `RegisterValue.ensureDomBinding`. Element
|
|
768
|
-
* registration, host anchors, and first-error focus resolution all
|
|
769
|
-
* live behind it; eager readers treat `null` as an empty registry.
|
|
770
|
-
*/
|
|
771
|
-
readonly domBinding: ShallowRef<AttaformDomBinding | null>;
|
|
772
|
-
/**
|
|
773
|
-
* Field-record connect transition, driven by the DOM binding on
|
|
774
|
-
* element attach / host connect (and by the SSR-only
|
|
775
|
-
* `markConnectedOptimistically`): `connected: true`, with
|
|
776
|
-
* `focused` / `blurred` lifted from `null` to optimistic booleans
|
|
777
|
-
* only when currently null — an existing boolean from an early focus
|
|
778
|
-
* event is never clobbered.
|
|
779
|
-
*/
|
|
780
|
-
noteDomConnected(path: Path): void;
|
|
781
|
-
/**
|
|
782
|
-
* Field-record disconnect transition, driven by the DOM binding when
|
|
783
|
-
* a path's last element detaches or its host disconnects:
|
|
784
|
-
* `connected: false`, `focused` / `blurred` back to `null` (DOM-state
|
|
785
|
-
* properties are meaningless with nothing attached; interaction
|
|
786
|
-
* history stays).
|
|
787
|
-
*/
|
|
788
|
-
noteDomDisconnected(path: Path): void;
|
|
789
|
-
/**
|
|
790
|
-
* Optional `meta.instance` carries per-`useForm()`-instance overrides
|
|
791
|
-
* for `validateOn` / `debounceMs` so the blur-trigger respects the
|
|
792
|
-
* caller's config when sibling instances share a FormStore.
|
|
793
|
-
*/
|
|
794
|
-
markFocused(path: Path, focused: boolean, meta?: {
|
|
795
|
-
readonly instance?: WriteMeta['instance'];
|
|
796
|
-
}): void;
|
|
797
|
-
/**
|
|
798
|
-
* Flip `interacted: true` on a leaf — the sticky value-mutation flag.
|
|
799
|
-
* Driven by the directive's input listeners (via the RegisterValue's
|
|
800
|
-
* `markInteracted`); idempotent, never set by programmatic writes.
|
|
801
|
-
*/
|
|
802
|
-
markInteracted(path: Path): void;
|
|
803
|
-
/**
|
|
804
|
-
* Walk every active-variant leaf under `segments` and flip
|
|
805
|
-
* `touched: true`. Powers `form.touch(path?)`. Idempotent;
|
|
806
|
-
* does not mutate value / focused / blurred or trigger validation.
|
|
807
|
-
*/
|
|
808
|
-
touchAtPath(segments: Path): void;
|
|
809
|
-
/**
|
|
810
|
-
* Walk every active-variant leaf under `segments` and flip the full
|
|
811
|
-
* interaction ladder (`touched` / `interacted` /
|
|
812
|
-
* `blurredAfterInteraction`), as though the user had focused,
|
|
813
|
-
* edited, and left each one. Powers `form.interact(path?)`.
|
|
814
|
-
* Idempotent; does not mutate value / focused / blurred. Returns
|
|
815
|
-
* whether any leaf resolved, so the caller can skip validation and
|
|
816
|
-
* dev-warn on an empty path.
|
|
817
|
-
*/
|
|
818
|
-
interactAtPath(segments: Path): boolean;
|
|
819
|
-
/**
|
|
820
|
-
* SSR-only optimistic mark: flip `connected: true` on the field
|
|
821
|
-
* record without an actual DOM element. Called by the `vRegisterHint`
|
|
822
|
-
* compile-time transform via `RegisterValue.markConnectedOptimistically()`
|
|
823
|
-
* for every element rendered with `v-register`. Idempotent + no-op on
|
|
824
|
-
* the client (the directive's `created` hook is the authoritative
|
|
825
|
-
* source there).
|
|
826
|
-
*/
|
|
827
|
-
markConnectedOptimistically(path: Path): void;
|
|
828
|
-
/**
|
|
829
|
-
* Precomputed-key shortcut for `isPristineAtPath`. The canonical
|
|
830
|
-
* key is required and must correspond to `segments`; the helper
|
|
831
|
-
* skips the `canonicalizePath` round-trip so descendant-walk loops
|
|
832
|
-
* (whose Map iteration already yields the canonical key) can read
|
|
833
|
-
* the pristine verdict without a per-leaf canonicalize.
|
|
834
|
-
*/
|
|
835
|
-
isPristineAtPathByKey(key: PathKey, segments: Path): boolean;
|
|
836
|
-
/**
|
|
837
|
-
* Whether any tracked array under `path` has changed shape — a reorder,
|
|
838
|
-
* insert, or removal — relative to its construction/reset baseline. The
|
|
839
|
-
* structural half of `dirty`: per-element baselines travel with their
|
|
840
|
-
* element across a mutation, so a positional value comparison alone can
|
|
841
|
-
* no longer see the shape change.
|
|
842
|
-
*/
|
|
843
|
-
hasStructuralChangeUnder(path: Path): boolean;
|
|
844
|
-
/**
|
|
845
|
-
* Whether a baseline-present container under `path` was replaced wholesale by
|
|
846
|
-
* a non-container (e.g. `setValue('profile', undefined)`) and is still absent.
|
|
847
|
-
* The other half of removal-driven `dirty`: such a subtree's leaves vanish
|
|
848
|
-
* from the live value, so neither the present-leaf walk nor the array tracker
|
|
849
|
-
* can see the loss. Self-filters by current liveness, so a refilled path stops
|
|
850
|
-
* counting.
|
|
851
|
-
*/
|
|
852
|
-
hasRemovedSubtreeUnder(path: Path): boolean;
|
|
853
|
-
getFieldRecord(path: Path): FieldRecord | undefined;
|
|
854
|
-
/**
|
|
855
|
-
* Cancel every in-flight field-level validation run — clears timers
|
|
856
|
-
* for debounced 'change' runs that haven't fired, latches `aborted`
|
|
857
|
-
* for runs whose async parse is in flight. Called by `handleSubmit`
|
|
858
|
-
* at entry (submit validation is authoritative) and by `reset()`.
|
|
859
|
-
*/
|
|
860
|
-
cancelFieldValidation(): void;
|
|
861
|
-
/**
|
|
862
|
-
* Open an async-transform run at `key` — bump the run token, increment
|
|
863
|
-
* the in-flight counters, stamp `transformingSince`, clear any prior
|
|
864
|
-
* `transformError`, register `holder` for later abort. Returns the run
|
|
865
|
-
* token. See `InternalRegisterValue.beginTransform`.
|
|
866
|
-
*/
|
|
867
|
-
beginTransform(key: PathKey, holder: TransformAbortHolder): number;
|
|
868
|
-
/** `true` while `token` is the live async-transform run at `key`. */
|
|
869
|
-
isCurrentTransform(key: PathKey, token: number): boolean;
|
|
870
|
-
/**
|
|
871
|
-
* Close the run `token` at `key`: release the counters (no-op if the
|
|
872
|
-
* run was already released by a supersede / cancel) and flush settled
|
|
873
|
-
* `settleTransforms` waiters.
|
|
874
|
-
*/
|
|
875
|
-
endTransform(key: PathKey, token: number): void;
|
|
876
|
-
/** Record a per-field normalization failure at `key` (`field.transformError`). */
|
|
877
|
-
setTransformError(key: PathKey, err: Error): void;
|
|
878
|
-
/**
|
|
879
|
-
* Path-scoped counterpart to `cancelTransforms`: abort + release only
|
|
880
|
-
* the runs at-or-under `prefix`, clearing their `transformError`.
|
|
881
|
-
* Called by `resetField`.
|
|
882
|
-
*/
|
|
883
|
-
cancelTransformsUnder(prefix: Path): void;
|
|
884
|
-
/**
|
|
885
|
-
* Resolve once async transforms are quiescent — globally (`path`
|
|
886
|
-
* omitted) or at-or-under `path`. Resolve-never-reject. See
|
|
887
|
-
* `UseFormReturnType.settleTransforms`.
|
|
888
|
-
*/
|
|
889
|
-
settleTransforms(path?: string | Path): Promise<void>;
|
|
890
|
-
/**
|
|
891
|
-
* Kick off (or schedule) a field-level validation run for `path`. Pass
|
|
892
|
-
* `path = []` to cover the whole form; `applySchemaErrorsForSubtree`
|
|
893
|
-
* then wipes every `schemaErrors` entry and replaces them with the
|
|
894
|
-
* adapter's full async response. Used by persistence's post-hydration
|
|
895
|
-
* revalidation and by the construction-time async-refine seed.
|
|
896
|
-
*
|
|
897
|
-
* `immediate: true` skips the debounce window — the runtime kicks off
|
|
898
|
-
* the adapter call on the next microtask. Internal callsites use this
|
|
899
|
-
* for one-shot triggers; the per-keystroke writers pass `false` to
|
|
900
|
-
* coalesce rapid mutations under the configured debounceMs.
|
|
901
|
-
*
|
|
902
|
-
* `override` carries per-`useForm()`-instance values: when provided,
|
|
903
|
-
* the scheduler honors `override.mode` instead of the store's
|
|
904
|
-
* captured `validateOn`, and `override.debounceMs` instead of the
|
|
905
|
-
* store's captured `debounceMs`. Used so sibling instances sharing a
|
|
906
|
-
* FormStore can each validate on their own cadence.
|
|
907
|
-
*/
|
|
908
|
-
scheduleFieldValidation(path: Path, immediate: boolean, instance?: WriteMeta['instance']): void;
|
|
909
|
-
/**
|
|
910
|
-
* Subscribe to every `applyFormReplacement`. Fires synchronously
|
|
911
|
-
* after `form.value` has been swapped to `next` and all field /
|
|
912
|
-
* originals bookkeeping has run. Used by undo/redo to hook the single
|
|
913
|
-
* mutation funnel. The optional `meta` carries the originating call
|
|
914
|
-
* site's intent; subscribers that don't care about meta can ignore the
|
|
915
|
-
* parameter. Returns an unsubscribe function.
|
|
916
|
-
*/
|
|
917
|
-
onFormChange(listener: (next: F, meta?: WriteMeta) => void): () => void;
|
|
918
|
-
/**
|
|
919
|
-
* Subscribe to successful submissions. Fires after the consumer's
|
|
920
|
-
* `onSubmit` callback has resolved — not on validation failure,
|
|
921
|
-
* not on callback throw. The DevTools panel rides this to surface a
|
|
922
|
-
* submit event. Returns an unsubscribe function.
|
|
923
|
-
*/
|
|
924
|
-
onSubmitSuccess(listener: () => void): () => void;
|
|
925
|
-
/**
|
|
926
|
-
* Subscribe to `reset()` calls. Fires AFTER reset has replaced
|
|
927
|
-
* the form and cleared errors + lifecycle, so listeners see the
|
|
928
|
-
* fresh post-reset state. Used by the history module to drop the
|
|
929
|
-
* undo/redo stack on reset. Returns an unsubscribe function.
|
|
930
|
-
*/
|
|
931
|
-
onReset(listener: () => void): () => void;
|
|
932
|
-
/**
|
|
933
|
-
* Internal: notify submit-success subscribers. Called by
|
|
934
|
-
* `handleSubmit` in `process-form.ts` once the user callback has
|
|
935
|
-
* resolved. Consumers shouldn't call this directly.
|
|
936
|
-
*/
|
|
937
|
-
emitSubmitSuccess(): void;
|
|
938
|
-
/**
|
|
939
|
-
* Register a teardown function whose lifetime is bound to the
|
|
940
|
-
* FormStore itself (not a consumer's Vue effect scope). Called by
|
|
941
|
-
* `dispose()` when the last consumer unmounts. Used by persistence /
|
|
942
|
-
* history wiring so their subscribers aren't detached prematurely
|
|
943
|
-
* when only the first consumer unmounts but others remain.
|
|
944
|
-
*/
|
|
945
|
-
registerCleanup(fn: () => void): void;
|
|
946
|
-
/**
|
|
947
|
-
* Cache for per-state modules (chiefly history) that must
|
|
948
|
-
* outlive any single consumer. Subsequent `useForm` / `injectForm`
|
|
949
|
-
* calls for the same key read from this map so the public API shape
|
|
950
|
-
* is identical regardless of mount order. Keyed by a string identifier
|
|
951
|
-
* owned by the caller (e.g. `'history'`).
|
|
952
|
-
*/
|
|
953
|
-
readonly modules: Map<string, unknown>;
|
|
954
|
-
/**
|
|
955
|
-
* Whether schema-driven coercion runs for this form — `false` only
|
|
956
|
-
* when the consumer passed `useForm({ coerce: false })`. Read at
|
|
957
|
-
* `register()` time by `buildCoerceFn` to bake the per-path coerce
|
|
958
|
-
* closure on `RegisterValue.coerce`.
|
|
959
|
-
*/
|
|
960
|
-
readonly coerceEnabled: boolean;
|
|
961
|
-
/**
|
|
962
|
-
* Tear down non-reactive resources owned by this FormStore. Invoked
|
|
963
|
-
* by the registry when the last consumer unmounts. Cancels pending
|
|
964
|
-
* field-validation timers, drops every subscriber, and fires each
|
|
965
|
-
* cleanup hook registered via `registerCleanup`.
|
|
966
|
-
*/
|
|
967
|
-
dispose(): void;
|
|
968
|
-
};
|
|
969
|
-
|
|
970
|
-
/**
|
|
971
|
-
* Public types for `useWizard` — the multistep-form orchestrator.
|
|
972
|
-
*
|
|
973
|
-
* The wizard is built around an ordered list of step slots. Each slot
|
|
974
|
-
* resolves to a participating form: an existing `useForm` reference, a
|
|
975
|
-
* bare string key (desugared to a noop form so affordance steps
|
|
976
|
-
* participate uniformly), an eagerly-evaluated function slot for
|
|
977
|
-
* runtime branching, or a `lazy()`-wrapped function slot that caches
|
|
978
|
-
* its resolution and re-fires only on its own tracked deps.
|
|
979
|
-
*
|
|
980
|
-
* The wizard surface is loosely keyed (`Record<FormKey, …>`).
|
|
981
|
-
* Cross-component flows threaded through `injectWizard` lose lexical
|
|
982
|
-
* key knowledge anyway, so the public read surface is a string-keyed
|
|
983
|
-
* record. Typed per-form access flows back through the original form
|
|
984
|
-
* refs and through `wizard.handleSubmit`'s `ctx.get(formRef)` accessor.
|
|
985
|
-
*/
|
|
986
|
-
|
|
987
|
-
/**
|
|
988
|
-
* Minimum structural shape the wizard requires from a participating
|
|
989
|
-
* form. Constraining to the full `UseFormReturnType` would force
|
|
990
|
-
* contravariant unification of the storage / read shapes across all
|
|
991
|
-
* steps; the wizard does not care about those — it routes by `key` at
|
|
992
|
-
* runtime and exposes the original form objects untouched.
|
|
993
|
-
*/
|
|
994
|
-
type AnyForm = {
|
|
995
|
-
readonly key: FormKey;
|
|
996
|
-
};
|
|
997
|
-
/**
|
|
998
|
-
* Per-form summary surface — what `wizard.statuses[key]` exposes (and
|
|
999
|
-
* what `defaultStatuses` seeds). Distinct from `form.meta`: `FormStatus`
|
|
1000
|
-
* is the cross-step rollup optimized for template ergonomics
|
|
1001
|
-
* (`{{ wizard.statuses.cargo.valid }}`), while `form.meta` carries the
|
|
1002
|
-
* full per-form lifecycle surface.
|
|
1003
|
-
*
|
|
1004
|
-
* Field semantics:
|
|
1005
|
-
* - `valid` — `form.meta.valid`. `false` while errors exist or while
|
|
1006
|
-
* the first-validation-done gate has not flipped.
|
|
1007
|
-
* - `dirty` — `form.meta.dirty`. `true` once any value differs from
|
|
1008
|
-
* the original defaults.
|
|
1009
|
-
* - `submitted` — `form.meta.submitted`. `true` once a `handleSubmit`
|
|
1010
|
-
* callback has resolved without throwing. A failed submit
|
|
1011
|
-
* (validation or callback rejection) leaves this `false`;
|
|
1012
|
-
* `submissionAttempts > 0` is the "user has tried" signal.
|
|
1013
|
-
* - `errorCount` — `form.meta.errorCount`. Count of active validation
|
|
1014
|
-
* errors (zero when valid).
|
|
1015
|
-
* - `locked`: `true` when this step sits after an uncleared gate. Its
|
|
1016
|
-
* member form is frozen (data writes no-op) and navigation to it is
|
|
1017
|
-
* refused, so a stepper can render it as an unreachable step. `false`
|
|
1018
|
-
* when no gate seals it. Orthogonal to `gate`: the first uncleared
|
|
1019
|
-
* gate reads `locked: false` (you must reach it to clear it), while a
|
|
1020
|
-
* later gate sealed behind it reads both `gate: 'uncleared'` and
|
|
1021
|
-
* `locked: true`.
|
|
1022
|
-
* - `gate`: this step's own role as a hard prerequisite. `null` when the
|
|
1023
|
-
* step is not a `gate()`; `'uncleared'` while its member form is
|
|
1024
|
-
* unconfirmed (so it seals every later step); `'cleared'` once
|
|
1025
|
-
* confirmed by a clean member submit or seeded cleared via
|
|
1026
|
-
* `defaultStatuses`. Reflects the live compiled shape, so a conditional
|
|
1027
|
-
* `gate()` that a function slot drops resolves to `null`.
|
|
1028
|
-
*
|
|
1029
|
-
* Noop forms generated for string slots surface as default-valid
|
|
1030
|
-
* (`{ valid: true, dirty: false, submitted: false, errorCount: 0, locked: false, gate: null }`),
|
|
1031
|
-
* unless the string slot is a `gate('...')`, whose `gate` tracks the
|
|
1032
|
-
* in-session acknowledgment.
|
|
1033
|
-
*/
|
|
1034
|
-
type FormStatus = {
|
|
1035
|
-
readonly valid: boolean;
|
|
1036
|
-
readonly dirty: boolean;
|
|
1037
|
-
readonly submitted: boolean;
|
|
1038
|
-
readonly errorCount: number;
|
|
1039
|
-
readonly locked: boolean;
|
|
1040
|
-
readonly gate: 'cleared' | 'uncleared' | null;
|
|
1041
|
-
};
|
|
1042
|
-
/**
|
|
1043
|
-
* Seed shape accepted by `useWizard({ defaultStatuses })`. Every field is
|
|
1044
|
-
* optional; an omitted meta field falls back to the pending sentinel on
|
|
1045
|
-
* read.
|
|
1046
|
-
*
|
|
1047
|
-
* `locked` is never accepted: it is purely live-derived (sealed behind an
|
|
1048
|
-
* earlier uncleared gate) and overlaid on every status read, so a seeded
|
|
1049
|
-
* value would be ignored.
|
|
1050
|
-
*
|
|
1051
|
-
* `gate` is a WRITE-only seed, not a status field echoed back on read. A
|
|
1052
|
-
* seed of `'cleared'` latches the gate's cleared state once at construction
|
|
1053
|
-
* (an SSR restore of a confirmed prerequisite); the live `gate` overlay
|
|
1054
|
-
* then owns the read. `'uncleared'` is the default and seeds nothing. Only
|
|
1055
|
-
* a step that compiles to a `gate()` honors it — other keys ignore it.
|
|
1056
|
-
*/
|
|
1057
|
-
type FormStatusSeed = {
|
|
1058
|
-
readonly valid?: boolean;
|
|
1059
|
-
readonly dirty?: boolean;
|
|
1060
|
-
readonly submitted?: boolean;
|
|
1061
|
-
readonly errorCount?: number;
|
|
1062
|
-
readonly gate?: 'cleared' | 'uncleared';
|
|
1063
|
-
};
|
|
1064
|
-
/**
|
|
1065
|
-
* Flat error shape returned per form by `wizard.allErrors[key]`. Each
|
|
1066
|
-
* entry carries the formKey + path tuple so consumers can route to the
|
|
1067
|
-
* offending field from a wizard-wide error summary.
|
|
1068
|
-
*/
|
|
1069
|
-
type WizardAggregateError = {
|
|
1070
|
-
readonly formKey: FormKey;
|
|
1071
|
-
readonly path: ReadonlyArray<string | number>;
|
|
1072
|
-
readonly message: string;
|
|
1073
|
-
readonly code?: string;
|
|
1074
|
-
};
|
|
1075
|
-
/**
|
|
1076
|
-
* Mirror of `form.values`' call-or-read pattern, one level deep.
|
|
1077
|
-
* Drillable as `wizard.statuses.cargo.valid` (readable), as
|
|
1078
|
-
* `wizard.statuses('cargo')` (callable single-key), or as
|
|
1079
|
-
* `wizard.statuses()` (callable no-arg returns the whole record).
|
|
1080
|
-
*/
|
|
1081
|
-
type WizardStatusesProxy<S extends Record<string, FormStatus>> = ((key?: keyof S) => FormStatus | S) & Readonly<S>;
|
|
1082
|
-
/**
|
|
1083
|
-
* One compiled position in the wizard's flow. The wizard surface
|
|
1084
|
-
* exposes an ordered array of these as `wizard.steps`, plus a
|
|
1085
|
-
* `wizard.forms` record keyed by `step.key` for direct lookup.
|
|
1086
|
-
*
|
|
1087
|
-
* String slots in the source `steps` array desugar to noop forms
|
|
1088
|
-
* before compilation, so every compiled step carries a `form`
|
|
1089
|
-
* regardless of source kind.
|
|
1090
|
-
*/
|
|
1091
|
-
type CompiledStep = {
|
|
1092
|
-
readonly key: FormKey;
|
|
1093
|
-
readonly form: AnyForm;
|
|
1094
|
-
};
|
|
1095
|
-
/**
|
|
1096
|
-
* Shape of a participating form as seen from inside a function slot's
|
|
1097
|
-
* `ctx.forms[key]` lookup. Adds `values` to the structural `AnyForm`
|
|
1098
|
-
* minimum so routing decisions can read live form state.
|
|
1099
|
-
*
|
|
1100
|
-
* Values are typed loose because the wizard does not generically thread
|
|
1101
|
-
* each step's schema through `ctx.forms`. For typed access inside slot
|
|
1102
|
-
* bodies, close over the original form ref instead of routing through
|
|
1103
|
-
* `ctx.forms`.
|
|
1104
|
-
*/
|
|
1105
|
-
type WizardCtxForm = AnyForm & {
|
|
1106
|
-
readonly values: Readonly<Record<string, unknown>>;
|
|
1107
|
-
};
|
|
1108
|
-
/**
|
|
1109
|
-
* Context object passed to function slots in the `steps` array. The
|
|
1110
|
-
* `forms` record exposes the wizard's statically-known forms (every
|
|
1111
|
-
* top-level `AnyForm` slot plus every noop form synthesized for a
|
|
1112
|
-
* top-level string slot). `currentKey` mirrors the live wizard step.
|
|
1113
|
-
*
|
|
1114
|
-
* Function slots re-evaluate reactively when the values they read
|
|
1115
|
-
* mutate (typically `ctx.forms.<key>.values.<path>`). The `forms`
|
|
1116
|
-
* accumulator itself is stable across re-evaluations so the slot's
|
|
1117
|
-
* lookup identity stays referentially equal. Effectful slot bodies
|
|
1118
|
-
* should be avoided; routing decisions live here.
|
|
1119
|
-
*/
|
|
1120
|
-
type WizardCtx = {
|
|
1121
|
-
readonly forms: Readonly<Record<FormKey, WizardCtxForm>>;
|
|
1122
|
-
readonly currentKey: FormKey | undefined;
|
|
1123
|
-
};
|
|
1124
|
-
/**
|
|
1125
|
-
* What a function slot or a `lazy()` / `gate()` resolver may yield: a
|
|
1126
|
-
* participating form, a bare affordance key, a nested `lazy()` / `gate()`
|
|
1127
|
-
* wrapper (so the two compose in either order), or `null` / `undefined`
|
|
1128
|
-
* to drop the position from the compiled list.
|
|
1129
|
-
*/
|
|
1130
|
-
type SlotResolution<Ctx = WizardCtx> = AnyForm | string | null | undefined | LazyMarker<Ctx> | GateMarker;
|
|
1131
|
-
/**
|
|
1132
|
-
* Internal phantom brand for `LazyMarker`. The runtime brand symbol
|
|
1133
|
-
* lives in `core/wizard-lazy.ts`; this declaration keeps the marker
|
|
1134
|
-
* type unforgeable without circular module imports.
|
|
1135
|
-
*/
|
|
1136
|
-
declare const _lazyBrand: unique symbol;
|
|
1137
|
-
/**
|
|
1138
|
-
* Brand-typed marker returned by `lazy((ctx) => …)`. Wrapping a
|
|
1139
|
-
* function slot in `lazy()` gives that slot its own memoization cache:
|
|
1140
|
-
* the resolver fires once on the first compile pass, and the result
|
|
1141
|
-
* stays cached until one of the resolver's own tracked reactive reads
|
|
1142
|
-
* changes (or `wizard.reset()` invalidates the cache). Heavy or
|
|
1143
|
-
* one-shot lookups (network-backed factories, expensive derivations)
|
|
1144
|
-
* do not re-fire because an unrelated slot's deps changed.
|
|
1145
|
-
*
|
|
1146
|
-
* Construct via the `lazy()` helper exported from the same entry as
|
|
1147
|
-
* `useWizard`. The marker is opaque at the type level; consumers do
|
|
1148
|
-
* not assemble it directly.
|
|
1149
|
-
*/
|
|
1150
|
-
type LazyMarker<Ctx = WizardCtx> = {
|
|
1151
|
-
readonly [_lazyBrand]: true;
|
|
1152
|
-
readonly resolve: (ctx: Ctx) => SlotResolution<Ctx>;
|
|
1153
|
-
};
|
|
1154
|
-
/**
|
|
1155
|
-
* Internal phantom brand for `GateMarker`. The runtime brand symbol
|
|
1156
|
-
* lives in `core/wizard-gate.ts`; this declaration keeps the marker
|
|
1157
|
-
* type unforgeable without circular module imports.
|
|
1158
|
-
*/
|
|
1159
|
-
declare const _gateBrand: unique symbol;
|
|
1160
|
-
/**
|
|
1161
|
-
* Brand-typed marker returned by `gate(step)`. Wrapping a slot in
|
|
1162
|
-
* `gate()` makes it a hard prerequisite: an uncleared gate seals every
|
|
1163
|
-
* step positioned after it, and the gate's own form is the only way
|
|
1164
|
-
* past. A gate clears on a member form's clean submit (confirmation),
|
|
1165
|
-
* never on a value merely going valid (intent), and its form freezes
|
|
1166
|
-
* once cleared so a back-navigation is a read-only review.
|
|
1167
|
-
*
|
|
1168
|
-
* `Inner` carries the wrapped slot's static type so `gate` stays
|
|
1169
|
-
* transparent to the type machinery: `gate(form)` still contributes the
|
|
1170
|
-
* form's key to `wizard.forms` and still counts as a guaranteed step,
|
|
1171
|
-
* while `gate(lazy(fn))` stays maybe-absent exactly like the lazy slot
|
|
1172
|
-
* it wraps. See {@link UnwrapGate}.
|
|
1173
|
-
*
|
|
1174
|
-
* Construct via the `gate()` helper exported from the same entry as
|
|
1175
|
-
* `useWizard`. The marker is opaque at the type level; consumers do not
|
|
1176
|
-
* assemble it directly.
|
|
1177
|
-
*/
|
|
1178
|
-
type GateMarker<Inner = unknown> = {
|
|
1179
|
-
readonly [_gateBrand]: true;
|
|
1180
|
-
readonly inner: Inner;
|
|
1181
|
-
};
|
|
1182
|
-
/**
|
|
1183
|
-
* Strip every `gate()` wrapper off a slot type, exposing the inner
|
|
1184
|
-
* slot's static shape. A gate is identity-on-shape — it changes runtime
|
|
1185
|
-
* reachability, never the compiled type — so the forms map and the
|
|
1186
|
-
* non-empty-tuple predicate both unwrap it before inspecting a slot.
|
|
1187
|
-
* Recursive, so a doubly-wrapped `gate(gate(form))` still resolves to
|
|
1188
|
-
* `form`. This is what makes `gate(lazy(s))` and `lazy((ctx) => gate(s))`
|
|
1189
|
-
* agree at the type level as well as at runtime.
|
|
1190
|
-
*/
|
|
1191
|
-
type UnwrapGate<T> = T extends GateMarker<infer Inner> ? UnwrapGate<Inner> : T;
|
|
1192
|
-
/**
|
|
1193
|
-
* One position in the source `useWizard({ steps })` array. Each slot
|
|
1194
|
-
* resolves to a compiled `{ key, form }` step, or drops out:
|
|
1195
|
-
*
|
|
1196
|
-
* - `AnyForm` — a form declared via `useForm`. Surfaced as-is.
|
|
1197
|
-
* - `string` — bare key. The wizard generates a noop form
|
|
1198
|
-
* under the hood so the external surface stays
|
|
1199
|
-
* uniform across affordance positions (intro,
|
|
1200
|
-
* terms, congratulations, review surfaces).
|
|
1201
|
-
* - `null` / `undefined` — a literal absence, dropped from the compiled
|
|
1202
|
-
* list. Lets a conditional step read inline as
|
|
1203
|
-
* `cond ? form : null` without pre-filtering the
|
|
1204
|
-
* array.
|
|
1205
|
-
* - function — eager slot, re-evaluates reactively. Returns a
|
|
1206
|
-
* `SlotResolution`, or `null` / `undefined` to
|
|
1207
|
-
* drop the slot from the compiled list.
|
|
1208
|
-
* - `LazyMarker` — memoized function slot (see `lazy`).
|
|
1209
|
-
* - `GateMarker` — hard-prerequisite wrapper (see `gate`). Wraps
|
|
1210
|
-
* any of the above; transparent to the compiled
|
|
1211
|
-
* step's type, opaque to reachability.
|
|
1212
|
-
*/
|
|
1213
|
-
type StepSlot<Ctx = WizardCtx> = AnyForm | string | null | undefined | ((ctx: Ctx) => SlotResolution<Ctx>) | LazyMarker<Ctx> | GateMarker;
|
|
1214
|
-
/**
|
|
1215
|
-
* Shape returned by the `restore` callback. Carries the active step's
|
|
1216
|
-
* key; intentionally open-ended (object form) so future additions land
|
|
1217
|
-
* without a callback-signature break.
|
|
1218
|
-
*/
|
|
1219
|
-
type WizardRestoreState = {
|
|
1220
|
-
readonly step?: FormKey;
|
|
1221
|
-
};
|
|
1222
|
-
/**
|
|
1223
|
-
* `restore` callback signature. Invoked at construction and watched
|
|
1224
|
-
* reactively via `watchEffect` so external state changes (browser
|
|
1225
|
-
* back/forward, cross-tab events, route changes) re-apply through the
|
|
1226
|
-
* wizard. Returning `undefined` falls through to the first step.
|
|
1227
|
-
*/
|
|
1228
|
-
type WizardRestoreFn = () => WizardRestoreState | undefined;
|
|
1229
|
-
/**
|
|
1230
|
-
* `persist` callback signature. Invoked whenever `wizard.currentStep`
|
|
1231
|
-
* changes; the wizard diffs against the last persisted value to break
|
|
1232
|
-
* the restore-persist loop, so the callback only fires when the active
|
|
1233
|
-
* step actually moves.
|
|
1234
|
-
*/
|
|
1235
|
-
type WizardPersistFn = (state: WizardRestoreState) => void;
|
|
1236
|
-
/**
|
|
1237
|
-
* Submit context passed to the `onSubmit` callback registered via
|
|
1238
|
-
* `wizard.handleSubmit(onSubmit, onError?)`. `handleSubmit` always
|
|
1239
|
-
* processes the whole step list, so `values` carries every form's
|
|
1240
|
-
* parsed output regardless of which step fired the submit.
|
|
1241
|
-
*
|
|
1242
|
-
* - `values` — namespaced aggregate keyed by form key, mirroring
|
|
1243
|
-
* `wizard.allValues`. Reflects parsed output for every
|
|
1244
|
-
* form whose validation has settled; noops contribute an
|
|
1245
|
-
* empty record.
|
|
1246
|
-
* - `get(form)` — typed accessor that reads the parsed output for a
|
|
1247
|
-
* specific form ref. Works across cross-component graphs
|
|
1248
|
-
* because the form ref carries its schema info.
|
|
1249
|
-
* - `currentKey` — key of the step that fired this submission.
|
|
1250
|
-
* - `isFinal` — `true` when `currentKey` is the last position in
|
|
1251
|
-
* `wizard.steps`. Positional only: it reports where the
|
|
1252
|
-
* submit fired, never what got validated. A user who steps
|
|
1253
|
-
* back, edits, and submits from the middle sees
|
|
1254
|
-
* `isFinal === false`, yet the whole list is still
|
|
1255
|
-
* processed and `done` still latches on success.
|
|
1256
|
-
*/
|
|
1257
|
-
type WizardSubmitContext = {
|
|
1258
|
-
readonly values: Readonly<Record<FormKey, unknown>>;
|
|
1259
|
-
readonly get: <F extends AnyForm>(form: F) => F extends {
|
|
1260
|
-
readonly values: infer V;
|
|
1261
|
-
} ? V : unknown;
|
|
1262
|
-
readonly currentKey: FormKey;
|
|
1263
|
-
readonly isFinal: boolean;
|
|
1264
|
-
};
|
|
1265
|
-
/**
|
|
1266
|
-
* `onSubmit` callback registered via `wizard.handleSubmit`. Sync or
|
|
1267
|
-
* async; the returned promise gates `wizard.submitting`.
|
|
1268
|
-
*/
|
|
1269
|
-
type WizardOnSubmit = (ctx: WizardSubmitContext) => void | Promise<void>;
|
|
1270
|
-
/**
|
|
1271
|
-
* Optional `onError` callback registered via `wizard.handleSubmit`.
|
|
1272
|
-
* Receives the aggregate error list spanning EVERY step (handleSubmit
|
|
1273
|
-
* validates the whole wizard), so a failed submit surfaces every form's
|
|
1274
|
-
* errors at once, not just the active step's. Entries originate from
|
|
1275
|
-
* per-form validation, activation failures (`atta:activation-failed`),
|
|
1276
|
-
* and a submit callback that left errors on a processed step (the
|
|
1277
|
-
* `setErrors(...); return` server-rejection path). Sync or async; the
|
|
1278
|
-
* returned promise gates `wizard.submitting`.
|
|
1279
|
-
*/
|
|
1280
|
-
type WizardOnError = (errors: readonly WizardAggregateError[]) => void | Promise<void>;
|
|
1281
|
-
/**
|
|
1282
|
-
* Options for `useWizard({ steps, … })`. `steps` is the only required
|
|
1283
|
-
* field; the rest are optional and default sensibly for the common
|
|
1284
|
-
* URL-synchronized wizard case.
|
|
1285
|
-
*/
|
|
1286
|
-
type WizardOptions = {
|
|
1287
|
-
/**
|
|
1288
|
-
* Ordered list of slots that compile into the wizard's positional
|
|
1289
|
-
* step list. See `StepSlot` for the per-slot shape contract.
|
|
1290
|
-
*/
|
|
1291
|
-
readonly steps: ReadonlyArray<StepSlot>;
|
|
1292
|
-
/**
|
|
1293
|
-
* Identifier used to register the wizard handle in the per-app
|
|
1294
|
-
* registry. Descendant components call `injectWizard(key)` to reach
|
|
1295
|
-
* the same wizard without prop-threading. Anonymous wizards (option
|
|
1296
|
-
* omitted) get a synthetic `__atta:anon-wizard:<id>` key resolved
|
|
1297
|
-
* via `useId()` so SSR-rendered and client-hydrated trees agree on
|
|
1298
|
-
* the same registry entry; the synthetic key is opaque and
|
|
1299
|
-
* descendants reach an anonymous wizard via ambient `injectWizard()`
|
|
1300
|
-
* rather than by key.
|
|
1301
|
-
*
|
|
1302
|
-
* Duplicate-key registration is first-wins-silently (dev-warn on the
|
|
1303
|
-
* second registration) to mirror `useForm`'s shared-key behavior.
|
|
1304
|
-
* The dev-warn fires only for explicit keys — two anonymous wizards
|
|
1305
|
-
* are guaranteed distinct synthetic keys, so the warning never
|
|
1306
|
-
* misfires on independent anonymous wizards on the same page.
|
|
1307
|
-
*/
|
|
1308
|
-
readonly key?: string;
|
|
1309
|
-
/**
|
|
1310
|
-
* Seed status payload used while a form is pre-resolved (async
|
|
1311
|
-
* `defaultValues` in flight, or wizard-deferred non-current).
|
|
1312
|
-
* Mirrors `defaultValues`' trichotomy: plain object, sync factory,
|
|
1313
|
-
* or async factory.
|
|
1314
|
-
*
|
|
1315
|
-
* Status resolution priority per form:
|
|
1316
|
-
* 1. `store.defaultsResolved === true` → derive from `form.meta`
|
|
1317
|
-
* 2. else noop form → built-in always-valid status
|
|
1318
|
-
* 3. else seed value for this key → seed over the pending sentinel
|
|
1319
|
-
* 4. else → pending sentinel
|
|
1320
|
-
*
|
|
1321
|
-
* `locked` is never seeded: it is computed live from the wizard's gates
|
|
1322
|
-
* and overlaid on every status read. `gate: 'cleared'` IS honored, but as
|
|
1323
|
-
* a one-shot seed of the gate's cleared latch at construction (an SSR
|
|
1324
|
-
* restore of a confirmed prerequisite), not as a status field echoed on
|
|
1325
|
-
* read — the live `gate` overlay owns the read. Only a step that compiles
|
|
1326
|
-
* to a `gate()` honors it. See `FormStatusSeed`.
|
|
1327
|
-
*
|
|
1328
|
-
* SSR note: the async factory resolves after hydration (client-only), so
|
|
1329
|
-
* a gate seeded through it clears post-hydration. For a gate that must
|
|
1330
|
-
* render open on the first server byte, use the plain or sync-factory
|
|
1331
|
-
* form (resolve server truth in the page's `setup` await).
|
|
1332
|
-
*
|
|
1333
|
-
* Unknown keys in the seed object dev-warn so a stale resume payload
|
|
1334
|
-
* surfaces at construction.
|
|
1335
|
-
*/
|
|
1336
|
-
readonly defaultStatuses?: Record<string, FormStatusSeed> | (() => Record<string, FormStatusSeed>) | (() => Promise<Record<string, FormStatusSeed>>);
|
|
1337
|
-
/**
|
|
1338
|
-
* Optional progress override. When omitted, the wizard exposes
|
|
1339
|
-
* `progress` as `valid_step_count / count` (normalised to `[0, 1]`).
|
|
1340
|
-
* When provided, the returned number is used as-is — the consumer is
|
|
1341
|
-
* responsible for any normalisation.
|
|
1342
|
-
*
|
|
1343
|
-
* The override is invoked inside a Vue `computed` so it must be
|
|
1344
|
-
* synchronous and may only read reactive sources.
|
|
1345
|
-
*/
|
|
1346
|
-
readonly progress?: (steps: ReadonlyArray<CompiledStep>) => number;
|
|
1347
|
-
/**
|
|
1348
|
-
* When `wizard.handleSubmit` finds errors, automatically focus the
|
|
1349
|
-
* first failing form: jump to its step and invoke its
|
|
1350
|
-
* `applyInvalidSubmitPolicy()` (which honors that form's own
|
|
1351
|
-
* `focusOnInvalidSubmit` choice). Default `true`; pass `false` to
|
|
1352
|
-
* keep the active step where the user left it and handle navigation
|
|
1353
|
-
* manually in the `onError` callback.
|
|
1354
|
-
*/
|
|
1355
|
-
readonly focusFirstError?: boolean;
|
|
1356
|
-
/**
|
|
1357
|
-
* Source of truth for the active step. Invoked at construction and
|
|
1358
|
-
* re-evaluated reactively via `watchEffect`. Default callback reads
|
|
1359
|
-
* `?step=<key>` from the URL via `wizard-history.ts`; pass `false`
|
|
1360
|
-
* to disable URL sync, or provide a custom callback for non-router
|
|
1361
|
-
* persistence (localStorage, broadcast channel, etc.).
|
|
1362
|
-
*/
|
|
1363
|
-
readonly restore?: WizardRestoreFn | false;
|
|
1364
|
-
/**
|
|
1365
|
-
* Destination for the active step. Invoked whenever `currentStep`
|
|
1366
|
-
* changes, with a diff check to break the restore-persist loop.
|
|
1367
|
-
* Default callback writes `?step=<key>` via `wizard-history.ts`;
|
|
1368
|
-
* pass `false` to disable persistence, or provide a custom callback
|
|
1369
|
-
* to scope the param name or write to alternate storage.
|
|
1370
|
-
*/
|
|
1371
|
-
readonly persist?: WizardPersistFn | false;
|
|
1372
|
-
};
|
|
1373
|
-
/**
|
|
1374
|
-
* True when a single slot is guaranteed to contribute exactly one
|
|
1375
|
-
* compiled step: a bare form or affordance string that is neither
|
|
1376
|
-
* nullish nor a (maybe-absent) function / `lazy()` slot. One of these
|
|
1377
|
-
* anywhere in the tuple proves the compiled list is non-empty.
|
|
1378
|
-
*/
|
|
1379
|
-
type IsGuaranteedStep<T, U = UnwrapGate<T>> = [null] extends [U] ? false : [undefined] extends [U] ? false : U extends LazyMarker | ((...args: unknown[]) => unknown) ? false : U extends string ? true : U extends {
|
|
1380
|
-
readonly key: string;
|
|
1381
|
-
} ? true : false;
|
|
1382
|
-
/**
|
|
1383
|
-
* Predicate: is the steps tuple statically guaranteed to compile to a
|
|
1384
|
-
* non-empty list? True when at least one element is a guaranteed step
|
|
1385
|
-
* (see `IsGuaranteedStep`). Function / `lazy()` slots may resolve to
|
|
1386
|
-
* nothing, and `null` / `undefined` (a literal absence or a
|
|
1387
|
-
* `cond ? form : null` union) is an explicit drop, so none of those
|
|
1388
|
-
* prove non-emptiness; a tuple of only maybe-absent slots stays
|
|
1389
|
-
* honestly `| undefined`.
|
|
1390
|
-
*
|
|
1391
|
-
* Used to narrow `currentStep` / `activeForm` to their non-`undefined`
|
|
1392
|
-
* shapes in the common-case wizard, while keeping the honest union
|
|
1393
|
-
* everywhere a runtime drop is reachable.
|
|
1394
|
-
*/
|
|
1395
|
-
type StaticallyNonEmpty<S> = S extends readonly [infer First, ...infer Rest] ? IsGuaranteedStep<First> extends true ? true : StaticallyNonEmpty<Rest> : false;
|
|
1396
|
-
/** Active step's key, narrowed to `string` when `S` is statically safe. */
|
|
1397
|
-
type CurrentStepOf<S> = StaticallyNonEmpty<S> extends true ? FormKey : FormKey | undefined;
|
|
1398
|
-
/**
|
|
1399
|
-
* Active step's form handle, schema-erased to `UseFormReturnType<GenericForm>`
|
|
1400
|
-
* and narrowed to non-`undefined` when `S` is statically safe. The runtime
|
|
1401
|
-
* value is a live facade over the active step, so reads (`.values`, `.meta`,
|
|
1402
|
-
* `.history`) and `.handleSubmit` always target the current step. Values are
|
|
1403
|
-
* loose here because the active step's schema is not statically known; reach
|
|
1404
|
-
* for the original form ref or `ctx.get(ref)` when you need typed per-step
|
|
1405
|
-
* values.
|
|
1406
|
-
*/
|
|
1407
|
-
type ActiveFormOf<S> = StaticallyNonEmpty<S> extends true ? UseFormReturnType<GenericForm> : UseFormReturnType<GenericForm> | undefined;
|
|
1408
|
-
/**
|
|
1409
|
-
* Per-slot contribution to {@link FormsRecordOf}. Unwraps a `gate()`
|
|
1410
|
-
* wrapper (transparent to the compiled type) and strips a `null` /
|
|
1411
|
-
* `undefined` (a literal absence or a `cond ? form : null` union) off the
|
|
1412
|
-
* slot first, so both a conditionally-present form and a `gate(form)`
|
|
1413
|
-
* still map to their key and stay concretely typed on `wizard.forms`; a
|
|
1414
|
-
* purely nullish slot contributes nothing.
|
|
1415
|
-
*/
|
|
1416
|
-
type SlotRecord<First, U = UnwrapGate<First>, F = Exclude<U, null | undefined>> = [F] extends [
|
|
1417
|
-
never
|
|
1418
|
-
] ? unknown : F extends string ? {
|
|
1419
|
-
readonly [P in F]: AnyForm;
|
|
1420
|
-
} : F extends {
|
|
1421
|
-
readonly key: infer K extends string;
|
|
1422
|
-
} ? {
|
|
1423
|
-
readonly [P in K]: F;
|
|
1424
|
-
} : unknown;
|
|
1425
|
-
/**
|
|
1426
|
-
* Recursive tuple walk that builds the static portion of
|
|
1427
|
-
* `wizard.forms`. Each step slot contributes to the record:
|
|
1428
|
-
*
|
|
1429
|
-
* - **String slot** (`'review'`): the literal becomes the record key
|
|
1430
|
-
* and the value is `AnyForm` (the noop form synthesized for the
|
|
1431
|
-
* affordance position is opaque at the type level).
|
|
1432
|
-
* - **Form slot** (a `useForm` reference with a literal `key` field):
|
|
1433
|
-
* the form's own `key` becomes the record key, and the value is
|
|
1434
|
-
* the concrete form handle type — so drilling
|
|
1435
|
-
* `wizard.forms.shipping.values.address` carries the schema-derived
|
|
1436
|
-
* field types through. A form kept behind a `cond ? form : null`
|
|
1437
|
-
* conditional still maps to its key.
|
|
1438
|
-
* - **`null` / `undefined` slot**: contributes nothing.
|
|
1439
|
-
* - **Function / `lazy()` slot**: contributes nothing to the static
|
|
1440
|
-
* map. Runtime-resolved forms are still reachable via the
|
|
1441
|
-
* catch-all index signature on `WizardForms` (typed as `AnyForm`).
|
|
1442
|
-
* - **`gate()` slot**: transparent — unwrapped to the slot it wraps, so
|
|
1443
|
-
* `gate(form)` contributes the form's key and `gate(lazy(fn))`
|
|
1444
|
-
* contributes nothing, exactly like the wrapped slot on its own.
|
|
1445
|
-
*
|
|
1446
|
-
* Recursion is bounded by the tuple length; real-world wizards land
|
|
1447
|
-
* well below the TS instantiation budget.
|
|
1448
|
-
*/
|
|
1449
|
-
type FormsRecordOf<S> = S extends readonly [
|
|
1450
|
-
infer First,
|
|
1451
|
-
...infer Rest extends ReadonlyArray<StepSlot>
|
|
1452
|
-
] ? SlotRecord<First> & FormsRecordOf<Rest> : unknown;
|
|
1453
|
-
/**
|
|
1454
|
-
* `wizard.forms` typed view. Combines the static per-step type map
|
|
1455
|
-
* with a catch-all `Record<FormKey, AnyForm>` fallback so:
|
|
1456
|
-
*
|
|
1457
|
-
* - Statically known slot keys → concrete form type via `FormsRecordOf`
|
|
1458
|
-
* - Any other string key → `AnyForm` via the index signature
|
|
1459
|
-
*
|
|
1460
|
-
* The intersection collapses to the concrete form for statically
|
|
1461
|
-
* known keys (because the concrete form type extends `AnyForm`) and
|
|
1462
|
-
* to `AnyForm` for unknown keys.
|
|
1463
|
-
*/
|
|
1464
|
-
type WizardForms<S> = FormsRecordOf<S> & Readonly<Record<FormKey, AnyForm>>;
|
|
1465
|
-
/**
|
|
1466
|
-
* Return shape of `useWizard({ steps, … })`. Every reactive read is a
|
|
1467
|
-
* plain getter (no `.value`) — `wizard.currentStep`, `wizard.progress`,
|
|
1468
|
-
* `wizard.allValues` track inside `computed` / template effects
|
|
1469
|
-
* directly.
|
|
1470
|
-
*
|
|
1471
|
-
* Parameterized by the steps tuple `S` so active-position fields
|
|
1472
|
-
* (`currentStep`, `activeForm`) narrow to non-undefined for the common
|
|
1473
|
-
* case (all positional Form / string slots) and stay as honest unions
|
|
1474
|
-
* when a function or `lazy()` slot can drop the compiled position at
|
|
1475
|
-
* runtime. The `const` type parameter on `useWizard` preserves literal
|
|
1476
|
-
* tuple types without consumer-side `as const`, so the narrowing
|
|
1477
|
-
* happens automatically from the call site.
|
|
1478
|
-
*
|
|
1479
|
-
* - `currentStep` — key of the active step. Narrows to `string` when
|
|
1480
|
-
* the steps tuple is statically guaranteed to
|
|
1481
|
-
* compile to a non-empty list (all positional
|
|
1482
|
-
* Form / string slots, no function or `lazy()`
|
|
1483
|
-
* slots). Otherwise reads as `string | undefined`
|
|
1484
|
-
* so the degenerate case (empty list at runtime)
|
|
1485
|
-
* surfaces honestly.
|
|
1486
|
-
* - `activeForm` — a LIVE view of the active step's form. Operating
|
|
1487
|
-
* through it always targets the current step, so a
|
|
1488
|
-
* handler captured once at setup
|
|
1489
|
-
* (`wizard.activeForm.handleSubmit(() =>
|
|
1490
|
-
* wizard.next())`) retargets as the wizard advances.
|
|
1491
|
-
* No longer `===` the raw per-step handle; reach for
|
|
1492
|
-
* `wizard.forms[key]` when you need raw identity.
|
|
1493
|
-
* Same `undefined` narrowing as `currentStep`. Noop
|
|
1494
|
-
* forms cover string slots in the normal path.
|
|
1495
|
-
* - `activeIndex` — 0-based position of the active step.
|
|
1496
|
-
* - `isFinalStep` — `true` when `currentStep === steps[count - 1].key`.
|
|
1497
|
-
* - `steps` — ordered list of compiled `{ key, form }` slots.
|
|
1498
|
-
* - `forms` — record indexable by step key; the value is the
|
|
1499
|
-
* full form handle resolved for that slot.
|
|
1500
|
-
* - `count` — `steps.length`.
|
|
1501
|
-
* - `statuses` — callable readonly proxy over the per-key
|
|
1502
|
-
* `FormStatus` record. Noop-form keys always read
|
|
1503
|
-
* as default-valid.
|
|
1504
|
-
* - `allValues` — namespaced aggregate of each form's values, keyed
|
|
1505
|
-
* by step key.
|
|
1506
|
-
* - `allErrors` — namespaced aggregate of each form's validation
|
|
1507
|
-
* errors, keyed by step key. Noop forms map to an
|
|
1508
|
-
* empty list.
|
|
1509
|
-
* - `progress` — normalised step-validity ratio (or the consumer's
|
|
1510
|
-
* `progress` override). Forward-looking: noops count
|
|
1511
|
-
* as always-valid.
|
|
1512
|
-
* - `canAdvance` — `true` when `activeIndex < count - 1`. Pure
|
|
1513
|
-
* positional check; navigation never gates on
|
|
1514
|
-
* validity.
|
|
1515
|
-
* - `canGoBack` — `true` when `activeIndex > 0`.
|
|
1516
|
-
* - `complete` — `isFinalStep && every step's form is valid`.
|
|
1517
|
-
* Forward-looking; reactive to current form
|
|
1518
|
-
* validity. Gates "Finish button enable" style UI.
|
|
1519
|
-
* - `done` — monotonic latch: flips `true` the first time a
|
|
1520
|
-
* `handleSubmit` resolves without throwing AND leaves
|
|
1521
|
-
* no errors set on any step, and stays `true` through
|
|
1522
|
-
* subsequent edits or invalidations. A callback that
|
|
1523
|
-
* calls `setErrors` and returns (the documented
|
|
1524
|
-
* server-rejection path) is a failed submit, so it
|
|
1525
|
-
* does not flip `done`. Only `reset()` flips it back.
|
|
1526
|
-
* Gates "show success card" style UI that should
|
|
1527
|
-
* reflect submission history rather than current
|
|
1528
|
-
* validity.
|
|
1529
|
-
* - `submitting` — `true` while a `wizard.handleSubmit` call is in
|
|
1530
|
-
* flight. Global re-entrance guard: every
|
|
1531
|
-
* navigation method also refuses while this is on.
|
|
1532
|
-
* - `submissionAttempts` — count of `wizard.handleSubmit` invocations
|
|
1533
|
-
* (success or failure). Always bumps, including on
|
|
1534
|
-
* noop-form steps.
|
|
1535
|
-
* - `submitError` — the error THROWN by the most recent
|
|
1536
|
-
* `wizard.handleSubmit` callback (or its `onError`),
|
|
1537
|
-
* coerced to a real `Error`. Mirrors
|
|
1538
|
-
* `form.meta.submitError`: this is the unexpected-throw
|
|
1539
|
-
* channel, so an expected rejection handled via
|
|
1540
|
-
* `setErrors` (no throw) surfaces through the error
|
|
1541
|
-
* surface and `onError` instead, leaving this `null`.
|
|
1542
|
-
* Cleared at submit entry and by `reset()`, parked here
|
|
1543
|
-
* rather than re-thrown, so the handler resolves and
|
|
1544
|
-
* never manufactures a `window` unhandledrejection.
|
|
1545
|
-
* `null` on success.
|
|
1546
|
-
* - `visited` — append-only breadcrumb of navigated step keys.
|
|
1547
|
-
* `back()` does not pop; the trail is the audit
|
|
1548
|
-
* log, not the back-stack.
|
|
1549
|
-
* - `next/back/goTo` — pure navigation. Refuses while `submitting`.
|
|
1550
|
-
* The one exception is `next()` on an UNCLEARED
|
|
1551
|
-
* `gate()` step, which behaves as `tryNext()` so
|
|
1552
|
-
* wiring Next straight to it can never skip the
|
|
1553
|
-
* gate's confirmation. Once that gate clears, `next()`
|
|
1554
|
-
* is plain navigation again and does not re-submit to
|
|
1555
|
-
* re-confirm.
|
|
1556
|
-
* - `tryNext()` — submit the active step, and once that submit
|
|
1557
|
-
* resolves clean, advance; invalid input keeps the pin
|
|
1558
|
-
* put under the form's standard error reveal (first
|
|
1559
|
-
* error focused, display state advanced). The advance
|
|
1560
|
-
* runs after the submit settles, so a `gate()` on the
|
|
1561
|
-
* active step clears in a single call. Inline-bindable
|
|
1562
|
-
* (`@click="wizard.tryNext()"`); resolves to whether
|
|
1563
|
-
* the pin moved. No-ops to `false` on a degenerate or
|
|
1564
|
-
* final-step wizard (finish via `handleSubmit`).
|
|
1565
|
-
* Called while the active step's form already has a
|
|
1566
|
-
* submit in flight (the usual case being from inside
|
|
1567
|
-
* that form's own callback), it rides that submit
|
|
1568
|
-
* rather than starting a second one, so one action
|
|
1569
|
-
* costs one submission. The pin has not moved by the
|
|
1570
|
-
* time it resolves, so the answer is `false`; the
|
|
1571
|
-
* advance lands with the in-flight submit.
|
|
1572
|
-
* - `handleSubmit(onSubmit, onError?)` — always validates the entire
|
|
1573
|
-
* step list, from any step, and never advances the
|
|
1574
|
-
* pin: on success it latches `done`; on any error it
|
|
1575
|
-
* focuses the first failing step and fires `onError`
|
|
1576
|
-
* with errors spanning every step. To gate advancing
|
|
1577
|
-
* a step on its own validity, compose with the active
|
|
1578
|
-
* form's submit: `activeForm.handleSubmit(() =>
|
|
1579
|
-
* wizard.next())`. Returns an event handler suitable
|
|
1580
|
-
* for `<form @submit>` or imperative use.
|
|
1581
|
-
* - `reset()` — zeros wizard lifecycle (`submissionAttempts`,
|
|
1582
|
-
* `visited`), resets every form, returns
|
|
1583
|
-
* `currentStep` to `steps[0].key`, and invokes
|
|
1584
|
-
* `persist` with the cleared state. Re-applies the
|
|
1585
|
-
* `defaultStatuses` gate seed, so a reboot returns to
|
|
1586
|
-
* the seeded initial clearance, not fully sealed.
|
|
1587
|
-
* - `relock(key, commit)` — re-seal a cleared gate, contingent on
|
|
1588
|
-
* `commit`. Awaits `commit` (a server-side revoke) and
|
|
1589
|
-
* re-seals only if it resolves clean, so the gate reflects
|
|
1590
|
-
* server-confirmed truth the same way a clearing submit
|
|
1591
|
-
* does; a thrown `commit` leaves it as-is. Seal-only (never
|
|
1592
|
-
* opens a gate), so it cannot become the leading-signal
|
|
1593
|
-
* foot-gun `gate()` exists to prevent. `commit` is required
|
|
1594
|
-
* (pass `() => {}` for a deliberate client-only re-seal).
|
|
1595
|
-
* Resolves whether the gate ended up sealed; never rejects.
|
|
1596
|
-
* Resolves `false` (dev-warn) on a non-gate key.
|
|
1597
|
-
*/
|
|
1598
|
-
type UseWizardReturnType<S extends ReadonlyArray<StepSlot> = ReadonlyArray<StepSlot>> = {
|
|
1599
|
-
readonly key: string;
|
|
1600
|
-
readonly currentStep: CurrentStepOf<S>;
|
|
1601
|
-
readonly activeForm: ActiveFormOf<S>;
|
|
1602
|
-
readonly activeIndex: number;
|
|
1603
|
-
readonly isFinalStep: boolean;
|
|
1604
|
-
readonly steps: ReadonlyArray<CompiledStep>;
|
|
1605
|
-
readonly forms: WizardForms<S>;
|
|
1606
|
-
readonly count: number;
|
|
1607
|
-
readonly statuses: WizardStatusesProxy<Record<string, FormStatus>>;
|
|
1608
|
-
readonly allValues: Readonly<Record<FormKey, unknown>>;
|
|
1609
|
-
readonly allErrors: Readonly<Record<FormKey, readonly WizardAggregateError[]>>;
|
|
1610
|
-
readonly progress: number;
|
|
1611
|
-
readonly canAdvance: boolean;
|
|
1612
|
-
readonly canGoBack: boolean;
|
|
1613
|
-
readonly complete: boolean;
|
|
1614
|
-
readonly done: boolean;
|
|
1615
|
-
readonly submitting: boolean;
|
|
1616
|
-
readonly submissionAttempts: number;
|
|
1617
|
-
readonly submitError: Error | null;
|
|
1618
|
-
readonly visited: readonly FormKey[];
|
|
1619
|
-
readonly next: () => Promise<void>;
|
|
1620
|
-
readonly back: () => void;
|
|
1621
|
-
readonly goTo: (key: string) => void;
|
|
1622
|
-
readonly tryNext: () => Promise<boolean>;
|
|
1623
|
-
readonly handleSubmit: (onSubmit: WizardOnSubmit, onError?: WizardOnError) => (event?: Event) => Promise<void>;
|
|
1624
|
-
readonly reset: () => void;
|
|
1625
|
-
readonly relock: (key: FormKey, commit: () => void | Promise<void>) => Promise<boolean>;
|
|
1626
|
-
};
|
|
1627
|
-
|
|
1628
|
-
/**
|
|
1629
|
-
* Portable SSR detection. The plugin captures this value at install time and
|
|
1630
|
-
* exposes it via the registry so every runtime branch reads a single source
|
|
1631
|
-
* of truth instead of sniffing `import.meta.*` (bundler-specific) at each
|
|
1632
|
-
* call site.
|
|
1633
|
-
*
|
|
1634
|
-
* Consumers can override the heuristic explicitly via
|
|
1635
|
-
* `createAttaform({ ssr: true })`; the default handles the common
|
|
1636
|
-
* Node-vs-browser split without relying on any bundler-injected flag.
|
|
1637
|
-
*/
|
|
1638
|
-
interface SSRDetectOptions {
|
|
1639
|
-
/**
|
|
1640
|
-
* Force SSR-vs-client mode, bypassing the `typeof window` heuristic.
|
|
1641
|
-
* `true` activates the SSR code paths (no devtools, no persistence
|
|
1642
|
-
* wiring, payload serialisation enabled); `false` forces client mode.
|
|
1643
|
-
* The Nuxt plugin sets this from `import.meta.server` so SSR detection
|
|
1644
|
-
* never depends on whether `window` is polyfilled. Tests that need to
|
|
1645
|
-
* exercise the SSR code paths under jsdom pass `ssr: true`.
|
|
1646
|
-
*/
|
|
1647
|
-
ssr?: boolean;
|
|
1648
|
-
}
|
|
1649
|
-
|
|
1650
|
-
/**
|
|
1651
|
-
* Per-Vue-app container for all form state instances. Each
|
|
1652
|
-
* `app.use(createAttaform())` call gets its own registry,
|
|
1653
|
-
* so the library runs under bare Vue 3 + SSR (via
|
|
1654
|
-
* `@vue/server-renderer`) and Nuxt with the same code path.
|
|
1655
|
-
*
|
|
1656
|
-
* Each form's state lives in `forms: Map<FormKey, FormStore<GenericForm>>`.
|
|
1657
|
-
* The type relaxation at storage time is necessary because different
|
|
1658
|
-
* forms in the same app have different `Form` generics; callers recover
|
|
1659
|
-
* the specific form type via `useForm`'s overloads.
|
|
1660
|
-
*/
|
|
1661
|
-
/**
|
|
1662
|
-
* Serialised snapshot of one form's state, captured by
|
|
1663
|
-
* `renderAttaformState` for SSR and replayed by
|
|
1664
|
-
* `hydrateAttaformState` on the client. Round-trips through
|
|
1665
|
-
* JSON-safe tuples; field references are intentionally omitted
|
|
1666
|
-
* (DOM nodes don't survive serialisation).
|
|
1667
|
-
*/
|
|
1668
|
-
type SerializedFormData = {
|
|
1669
|
-
/** The form's value at snapshot time. */
|
|
1670
|
-
readonly form: unknown;
|
|
1671
|
-
/**
|
|
1672
|
-
* Errors produced by the schema at snapshot time. Replayed into
|
|
1673
|
-
* the client form's error state at hydration; cleared on
|
|
1674
|
-
* successful re-validation client-side.
|
|
1675
|
-
*/
|
|
1676
|
-
readonly schemaErrors: ReadonlyArray<readonly [string, unknown]>;
|
|
1677
|
-
/**
|
|
1678
|
-
* Errors set explicitly via `setErrors` (typically a server
|
|
1679
|
-
* response) at snapshot time. Replayed at hydration; persists across
|
|
1680
|
-
* client-side re-validation.
|
|
1681
|
-
*/
|
|
1682
|
-
readonly userErrors: ReadonlyArray<readonly [string, unknown]>;
|
|
1683
|
-
/** Per-field metadata (timestamps, raw values, connection flags) captured at snapshot time. */
|
|
1684
|
-
readonly fields: ReadonlyArray<readonly [string, unknown]>;
|
|
1685
|
-
/**
|
|
1686
|
-
* Path keys that were in the form's `blankPaths` set at
|
|
1687
|
-
* snapshot time. Round-trips the "displayed empty" UI state across
|
|
1688
|
-
* the SSR boundary — without it, the client briefly renders
|
|
1689
|
-
* `String(slim-default)` (e.g. `'0'`) for fields the server
|
|
1690
|
-
* rendered as blank. Optional in the wire format so older payload
|
|
1691
|
-
* shapes deserialise cleanly.
|
|
1692
|
-
*/
|
|
1693
|
-
readonly blankPaths?: ReadonlyArray<string>;
|
|
1694
|
-
};
|
|
1695
|
-
type PendingHydration = Map<FormKey, SerializedFormData>;
|
|
1696
|
-
/**
|
|
1697
|
-
* The library's per-Vue-app container. One `AttaformRegistry` is
|
|
1698
|
-
* created per `app.use(createAttaform())` call.
|
|
1699
|
-
*
|
|
1700
|
-
* Most consumers never touch this directly — `useForm` and
|
|
1701
|
-
* `injectForm` reach the registry on your behalf. Access it
|
|
1702
|
-
* explicitly only when wiring SSR or a custom plugin integration.
|
|
1703
|
-
*/
|
|
1704
|
-
type AttaformRegistry = {
|
|
1705
|
-
/**
|
|
1706
|
-
* Live forms keyed by `FormKey`.
|
|
1707
|
-
* @internal
|
|
1708
|
-
*/
|
|
1709
|
-
readonly forms: Map<FormKey, FormStore<GenericForm>>;
|
|
1710
|
-
/**
|
|
1711
|
-
* Live wizards keyed by the consumer-supplied `key` option. Populated
|
|
1712
|
-
* by `useWizard(entryForm, { key })`; consulted by `injectWizard(key)` to
|
|
1713
|
-
* resolve cross-component wizard handles. Anonymous wizards (no
|
|
1714
|
-
* `key`) do NOT register here — they're reachable only via ambient
|
|
1715
|
-
* provide/inject.
|
|
1716
|
-
* @internal
|
|
1717
|
-
*/
|
|
1718
|
-
readonly wizards: Map<string, UseWizardReturnType>;
|
|
1719
|
-
/**
|
|
1720
|
-
* Snapshots staged by `hydrateAttaformState` waiting to be consumed by the next `useForm` call.
|
|
1721
|
-
* @internal
|
|
1722
|
-
*/
|
|
1723
|
-
readonly pendingHydration: PendingHydration;
|
|
1724
|
-
/** `true` while running on the server during SSR; `false` on the client. */
|
|
1725
|
-
readonly ssr: boolean;
|
|
1726
|
-
/**
|
|
1727
|
-
* Track a consumer of `key`. Returns a dispose function — call it
|
|
1728
|
-
* when the consumer unmounts. The form is evicted automatically
|
|
1729
|
-
* when the last consumer disposes, so long-running SPAs don't
|
|
1730
|
-
* leak detached state across navigations.
|
|
1731
|
-
* @internal
|
|
1732
|
-
*/
|
|
1733
|
-
readonly trackConsumer: (key: FormKey) => () => void;
|
|
1734
|
-
/**
|
|
1735
|
-
* Track a consumer of wizard `key`. Returns a dispose function — call
|
|
1736
|
-
* it when the consumer unmounts. The wizard handle is evicted from
|
|
1737
|
-
* `wizards` once the last consumer disposes, mirroring the form
|
|
1738
|
-
* consumer-counting mechanics. Anonymous wizards never enter this
|
|
1739
|
-
* counter (they have no key to count under).
|
|
1740
|
-
* @internal
|
|
1741
|
-
*/
|
|
1742
|
-
readonly trackWizardConsumer: (key: string) => () => void;
|
|
1743
|
-
/**
|
|
1744
|
-
* Mark a form as eligible for SSR prefetch. The form's
|
|
1745
|
-
* `onServerPrefetch` hook consults `shouldPrefetch(key)` and runs the
|
|
1746
|
-
* captured `defaultValues` factory only when this set contains the
|
|
1747
|
-
* key (and the skip set does not). Set by `form.activate()`,
|
|
1748
|
-
* `useWizard`'s current-step auto-mark, and the future Vite transform.
|
|
1749
|
-
* @internal
|
|
1750
|
-
*/
|
|
1751
|
-
readonly enqueuePrefetch: (key: FormKey) => void;
|
|
1752
|
-
/**
|
|
1753
|
-
* Mark a form as ineligible for SSR prefetch. Overrides `enqueuePrefetch`.
|
|
1754
|
-
* Used by `useWizard` to keep non-current steps dormant on the
|
|
1755
|
-
* server even when a transform mark or stray `activate()` would
|
|
1756
|
-
* otherwise enqueue them — the wizard's "user isn't on this step"
|
|
1757
|
-
* signal wins.
|
|
1758
|
-
* @internal
|
|
1759
|
-
*/
|
|
1760
|
-
readonly skipPrefetch: (key: FormKey) => void;
|
|
1761
|
-
/**
|
|
1762
|
-
* Whether `key`'s SSR prefetch should run. Returns `true` iff the key
|
|
1763
|
-
* is enqueued AND not skipped.
|
|
1764
|
-
* @internal
|
|
1765
|
-
*/
|
|
1766
|
-
readonly shouldPrefetch: (key: FormKey) => boolean;
|
|
1767
|
-
};
|
|
1768
|
-
/**
|
|
1769
|
-
* The Vue `InjectionKey` under which the registry is provided on the
|
|
1770
|
-
* app. Most consumers never need this — `useForm` and
|
|
1771
|
-
* `injectForm` resolve the registry automatically.
|
|
1772
|
-
*/
|
|
1773
|
-
declare const kAttaformRegistry: InjectionKey<AttaformRegistry>;
|
|
1774
|
-
declare module 'vue' {
|
|
1775
|
-
interface App {
|
|
1776
|
-
/** @internal */
|
|
1777
|
-
_attaform?: AttaformRegistry;
|
|
1778
|
-
}
|
|
1779
|
-
}
|
|
1780
|
-
/** Options for `createRegistry`. */
|
|
1781
|
-
type CreateRegistryOptions = SSRDetectOptions;
|
|
1782
|
-
/**
|
|
1783
|
-
* Create a fresh `AttaformRegistry`. `createAttaform()` calls
|
|
1784
|
-
* this internally — most consumers never need to call it directly.
|
|
1785
|
-
* Use it when building a custom plugin that doesn't want the
|
|
1786
|
-
* `createAttaform` plugin's auto-install behaviour (e.g. test
|
|
1787
|
-
* harnesses, embedded apps).
|
|
1788
|
-
*/
|
|
1789
|
-
declare function createRegistry(options?: CreateRegistryOptions): AttaformRegistry;
|
|
1790
|
-
/**
|
|
1791
|
-
* Look up the current app's registry from inside a component's
|
|
1792
|
-
* `setup()` (or any synchronous code on the setup call stack).
|
|
1793
|
-
*
|
|
1794
|
-
* Most consumers don't need this — `useForm` and `injectForm`
|
|
1795
|
-
* call it on your behalf. Reach for it directly when building
|
|
1796
|
-
* custom integrations that need the raw registry.
|
|
1797
|
-
*
|
|
1798
|
-
* Throws:
|
|
1799
|
-
* - `OutsideSetupError` when called outside a Vue setup context
|
|
1800
|
-
* (e.g. from an event handler or async callback). Move the call
|
|
1801
|
-
* into setup, or trigger it from a child component.
|
|
1802
|
-
* - `RegistryNotInstalledError` when called inside setup but the
|
|
1803
|
-
* plugin wasn't installed. Add
|
|
1804
|
-
* `app.use(createAttaform())` to your app entry.
|
|
1805
|
-
*/
|
|
1806
|
-
declare function useRegistry(): AttaformRegistry;
|
|
1807
|
-
/**
|
|
1808
|
-
* Look up a Vue app's registry by `App` reference. Used by
|
|
1809
|
-
* SSR helpers (`renderAttaformState`, `hydrateAttaformState`) that
|
|
1810
|
-
* run outside a component setup context.
|
|
1811
|
-
*
|
|
1812
|
-
* Throws `RegistryNotInstalledError` when the app hasn't been wired
|
|
1813
|
-
* with `createAttaform()`.
|
|
1814
|
-
*/
|
|
1815
|
-
declare function getRegistryFromApp(app: App): AttaformRegistry;
|
|
1816
|
-
|
|
1817
|
-
/**
|
|
1818
|
-
* Multistep-form orchestrator built around an ordered list of step slots.
|
|
1819
|
-
* Each slot resolves to a participating form: an existing `useForm`
|
|
1820
|
-
* reference, a bare string key (desugared to a noop form so affordance
|
|
1821
|
-
* steps participate uniformly), an eagerly-evaluated function slot for
|
|
1822
|
-
* runtime branching, or a `lazy()`-wrapped function slot that caches
|
|
1823
|
-
* its resolution and re-fires only on its own tracked deps.
|
|
1824
|
-
*
|
|
1825
|
-
* The wizard's surface is read-only from the consumer's side:
|
|
1826
|
-
* navigation (`next` / `back` / `goTo`) walks positional indices,
|
|
1827
|
-
* `handleSubmit` validates the whole step list from any step and never
|
|
1828
|
-
* advances (gate advance with `activeForm.handleSubmit(() =>
|
|
1829
|
-
* wizard.next())`), and URL synchronization rides on `restore` /
|
|
1830
|
-
* `persist` callbacks that default to `?step=<key>`.
|
|
1831
|
-
*/
|
|
1832
|
-
declare function useWizard<const S extends ReadonlyArray<StepSlot>>(options: WizardOptions & {
|
|
1833
|
-
readonly steps: S;
|
|
1834
|
-
}): UseWizardReturnType<S>;
|
|
1835
|
-
|
|
1836
|
-
/**
|
|
1837
|
-
* Options accepted by `injectWizard` when passing an object instead of
|
|
1838
|
-
* a bare key string. Mirrors `injectForm`'s `InjectFormInput` shape so
|
|
1839
|
-
* the two composables present an identical call surface.
|
|
1840
|
-
*/
|
|
1841
|
-
type InjectWizardInput = {
|
|
1842
|
-
readonly key?: string | undefined;
|
|
1843
|
-
};
|
|
1844
|
-
/**
|
|
1845
|
-
* Access an existing wizard handle from a descendant component without
|
|
1846
|
-
* passing it through props. Counterpart to `useWizard` — `useWizard`
|
|
1847
|
-
* creates and provides; `injectWizard` looks up via Vue's inject
|
|
1848
|
-
* mechanism or the per-app registry.
|
|
1849
|
-
*
|
|
1850
|
-
* Three ways to call it:
|
|
1851
|
-
*
|
|
1852
|
-
* ```ts
|
|
1853
|
-
* // Reach the nearest ancestor's useWizard call (ambient).
|
|
1854
|
-
* const wizard = injectWizard()
|
|
1855
|
-
*
|
|
1856
|
-
* // Reach a specific wizard by its key — works from anywhere in the app.
|
|
1857
|
-
* const signup = injectWizard('signup-wizard')
|
|
1858
|
-
*
|
|
1859
|
-
* // Object form (equivalent; convenient for spread).
|
|
1860
|
-
* const signup = injectWizard({ key: 'signup-wizard' })
|
|
1861
|
-
* ```
|
|
1862
|
-
*
|
|
1863
|
-
* Resolution rules (no-key form):
|
|
1864
|
-
* - Closest ambient ancestor wins via `provide(kAttaformAncestorWizard)`.
|
|
1865
|
-
* - Only anonymous (no-`key`) `useWizard()` calls fill the ambient
|
|
1866
|
-
* slot. Descendants of a keyed wizard must address it explicitly
|
|
1867
|
-
* via `injectWizard('the-key')`. Mirrors `useForm`'s ambient gate.
|
|
1868
|
-
*
|
|
1869
|
-
* Resolution rules (keyed form): registry lookup by string key,
|
|
1870
|
-
* independent of component-tree position. The wizard must have been
|
|
1871
|
-
* constructed with `useWizard({ steps, key })` to be reachable.
|
|
1872
|
-
*
|
|
1873
|
-
* Returns `null` when no matching wizard exists (no ambient ancestor,
|
|
1874
|
-
* or the named key isn't registered yet). A dev-mode warning points at
|
|
1875
|
-
* the call site, lists the registered keys, and flags the mount-timing
|
|
1876
|
-
* case (a wizard created by a child or sibling isn't registered until
|
|
1877
|
-
* its own setup runs). Always narrow before using:
|
|
1878
|
-
*
|
|
1879
|
-
* ```ts
|
|
1880
|
-
* const wizard = injectWizard('signup')
|
|
1881
|
-
* if (!wizard) return
|
|
1882
|
-
* wizard.next()
|
|
1883
|
-
* ```
|
|
1884
|
-
*
|
|
1885
|
-
* Consumer ref-counting: keyed lookups pin the wizard handle in the
|
|
1886
|
-
* registry for this component's lifetime, so the handle survives even
|
|
1887
|
-
* if the parent `useWizard` component unmounts before the child does.
|
|
1888
|
-
* Once every consumer disposes, the registry evicts the entry on the
|
|
1889
|
-
* next microtask. Ambient lookups don't ref-count — the parent
|
|
1890
|
-
* `useWizard`'s scope owns the lifetime.
|
|
1891
|
-
*/
|
|
1892
|
-
declare function injectWizard(input?: string | InjectWizardInput): UseWizardReturnType | null;
|
|
1893
|
-
|
|
1894
|
-
/**
|
|
1895
|
-
* Wrap a function slot in `lazy()` to give that slot its own memoized
|
|
1896
|
-
* cache, distinct from the wizard-wide step compiler.
|
|
1897
|
-
*
|
|
1898
|
-
* Default function slots in `useWizard({ steps })` re-evaluate whenever
|
|
1899
|
-
* the compiled step list re-evaluates, including when an unrelated
|
|
1900
|
-
* slot's reactive deps change. That keeps the rail correct but can
|
|
1901
|
-
* trigger spurious work in a resolver that is expensive (a network
|
|
1902
|
-
* lookup, a heavy schema derivation, an async-derived factory).
|
|
1903
|
-
*
|
|
1904
|
-
* `lazy()` isolates each wrapped slot behind its own cache. The
|
|
1905
|
-
* resolver runs eagerly on the first compile pass; subsequent reads
|
|
1906
|
-
* reuse the cached form. The cache invalidates only when one of the
|
|
1907
|
-
* resolver's own tracked reactive dependencies changes (Vue's
|
|
1908
|
-
* `computed` semantics applied to a slot), or when `wizard.reset()`
|
|
1909
|
-
* triggers a global re-compile:
|
|
1910
|
-
*
|
|
1911
|
-
* const wizard = useWizard({
|
|
1912
|
-
* steps: [
|
|
1913
|
-
* account,
|
|
1914
|
-
* lazy((ctx) => loadShippingForm(ctx.forms.account.values.region)),
|
|
1915
|
-
* confirm,
|
|
1916
|
-
* ],
|
|
1917
|
-
* })
|
|
1918
|
-
*
|
|
1919
|
-
* Resolution semantics:
|
|
1920
|
-
* - Eager at construction so `wizard.steps` and SSR markup are honest
|
|
1921
|
-
* from t=0.
|
|
1922
|
-
* - Memoized: the resolver re-fires only when one of its own tracked
|
|
1923
|
-
* reads changes. An unrelated slot re-evaluating does not re-fire
|
|
1924
|
-
* this one.
|
|
1925
|
-
* - `wizard.reset()` clears every lazy slot's cache so a reboot truly
|
|
1926
|
-
* resolves from scratch.
|
|
1927
|
-
* - Resolving to `null` or `undefined` drops the slot from the compiled
|
|
1928
|
-
* list until the resolver next re-fires.
|
|
1929
|
-
* - The resolver may return a `gate()` wrapper, so a lazy slot can gate
|
|
1930
|
-
* what it resolves to; `lazy((ctx) => gate(s))` and `gate(lazy(s))`
|
|
1931
|
-
* resolve identically.
|
|
1932
|
-
*
|
|
1933
|
-
* The runtime brand returned by `lazy()` is opaque. Use
|
|
1934
|
-
* {@link isLazyMarker} to detect it.
|
|
1935
|
-
*/
|
|
1936
|
-
declare function lazy<Ctx = WizardCtx>(resolve: (ctx: Ctx) => SlotResolution<Ctx>): LazyMarker<Ctx>;
|
|
1937
|
-
|
|
1938
|
-
/**
|
|
1939
|
-
* Wrap a step slot in `gate()` to make it a hard prerequisite: while the
|
|
1940
|
-
* gate is uncleared, every step positioned after it is inaccessible, and
|
|
1941
|
-
* the gate's own form is the only way past.
|
|
1942
|
-
*
|
|
1943
|
-
* A gate is safe by construction. It does not hand the consumer a
|
|
1944
|
-
* predicate to key on; it bakes the correct semantics in:
|
|
1945
|
-
*
|
|
1946
|
-
* - **Confirmation, not intent.** The gate clears only when a member
|
|
1947
|
-
* form submits clean, never when a value merely goes valid. Checking
|
|
1948
|
-
* the box does nothing; submitting the consent step is what opens the
|
|
1949
|
-
* rail. This is the whole reason `gate()` exists: a leading value
|
|
1950
|
-
* signal lets a downstream step collect data before the prerequisite
|
|
1951
|
-
* is confirmed.
|
|
1952
|
-
* - **Linear-forward.** An uncleared gate seals every step after it.
|
|
1953
|
-
* Order places it: put `gate(step)` immediately before what it
|
|
1954
|
-
* guards. Everything downstream is both un-navigable and, through the
|
|
1955
|
-
* `disabled` data freeze, un-fillable, so a deep link, the browser
|
|
1956
|
-
* back button, or a stray `goTo` all redirect to the gate.
|
|
1957
|
-
* - **Freeze-after-clear.** A cleared gate's own form freezes, so
|
|
1958
|
-
* navigating back to it is a read-only review with no withdrawal
|
|
1959
|
-
* path. There is no re-lock dance.
|
|
1960
|
-
*
|
|
1961
|
-
* Wrap any slot kind:
|
|
1962
|
-
*
|
|
1963
|
-
* const wizard = useWizard({ steps: [gate(consent), shipping, payment] })
|
|
1964
|
-
*
|
|
1965
|
-
* A **form** gate (`gate(consentForm)`) clears when its form submits
|
|
1966
|
-
* clean, and is treated as pre-cleared on reload when its member form
|
|
1967
|
-
* rehydrates already valid (a persisted consent), so a seeded-valid gate
|
|
1968
|
-
* SSR-renders open. A bare-string **affordance** gate (`gate('terms')`)
|
|
1969
|
-
* clears on acknowledgment (advancing past it), and re-prompts each
|
|
1970
|
-
* session because that acknowledgment is ephemeral.
|
|
1971
|
-
*
|
|
1972
|
-
* Conditional gates come from composition, not an options bag:
|
|
1973
|
-
*
|
|
1974
|
-
* () => (transfer.values.amount > 10_000 ? gate(kyc) : kyc)
|
|
1975
|
-
*
|
|
1976
|
-
* `gate()` composes with `lazy()` in either order:
|
|
1977
|
-
* `gate(lazy(fn))` and `lazy((ctx) => gate(fn(ctx)))` resolve
|
|
1978
|
-
* identically.
|
|
1979
|
-
*
|
|
1980
|
-
* The runtime brand returned by `gate()` is opaque. Use
|
|
1981
|
-
* {@link isGateMarker} to detect it.
|
|
1982
|
-
*/
|
|
1983
|
-
declare function gate<const Inner extends StepSlot>(step: Inner): GateMarker<Inner>;
|
|
1984
|
-
|
|
1985
|
-
/**
|
|
1986
|
-
* Stable identifiers for library-emitted `ValidationError` codes.
|
|
1987
|
-
*
|
|
1988
|
-
* Convention: `<scope>:<kebab-case-identifier>`. Three scopes are
|
|
1989
|
-
* recognised by the library:
|
|
1990
|
-
*
|
|
1991
|
-
* - `atta:` — emitted by the framework-agnostic core (this map).
|
|
1992
|
-
* - `zod:` — emitted by the Zod adapter; computed inline from
|
|
1993
|
-
* `issue.code` (e.g. `zod:too_small`). No enum here because
|
|
1994
|
-
* Zod's code list evolves.
|
|
1995
|
-
* - consumer-defined — anything the consumer's backend / app stamps
|
|
1996
|
-
* onto a `ValidationError` (a server response handed to `setErrors`,
|
|
1997
|
-
* or a code passed inline). Pick a scope (`api:`, `auth:`, etc.) and
|
|
1998
|
-
* stay consistent.
|
|
1999
|
-
*
|
|
2000
|
-
* Use these constants in tests and error-routing UI:
|
|
2001
|
-
*
|
|
2002
|
-
* ```ts
|
|
2003
|
-
* if (error.code === AttaformErrorCode.NoValueSupplied) {
|
|
2004
|
-
* // user hasn't filled this field
|
|
2005
|
-
* }
|
|
2006
|
-
* ```
|
|
2007
|
-
*/
|
|
2008
|
-
declare const AttaformErrorCode: {
|
|
2009
|
-
/** A required field is in the blank set — user hasn't supplied a value. */
|
|
2010
|
-
readonly NoValueSupplied: "atta:no-value-supplied";
|
|
2011
|
-
/** The schema adapter's `validateAtPath` threw synchronously. */
|
|
2012
|
-
readonly AdapterThrew: "atta:adapter-threw";
|
|
2013
|
-
/**
|
|
2014
|
-
* User code inside a `z.preprocess`, `.refine`, or `.transform`
|
|
2015
|
-
* threw (sync or async). The adapter caught the throw and surfaced
|
|
2016
|
-
* it as a `ValidationError` at the field path so the form's normal
|
|
2017
|
-
* error pipeline handles it instead of leaking as an unhandled
|
|
2018
|
-
* rejection or routing through `submitError`.
|
|
2019
|
-
*/
|
|
2020
|
-
readonly ValidatorThrew: "atta:validator-threw";
|
|
2021
|
-
/**
|
|
2022
|
-
* A function-form `defaultValues` factory threw or its promise
|
|
2023
|
-
* rejected. The runtime captures the raw error on `form.hydrateError`
|
|
2024
|
-
* and ALSO surfaces a form-level `ValidationError` (path `[]`) so
|
|
2025
|
-
* the standard error pipeline carries the signal. Critical for the
|
|
2026
|
-
* SSR round-trip: `hydrateError` itself does not ride the wire
|
|
2027
|
-
* payload, but `schemaErrors` does, so the client sees the failure
|
|
2028
|
-
* after rehydration without an extra channel.
|
|
2029
|
-
*/
|
|
2030
|
-
readonly HydrationFailed: "atta:hydration-failed";
|
|
2031
|
-
/** The supplied path didn't resolve to any node in the schema. */
|
|
2032
|
-
readonly PathNotFound: "atta:path-not-found";
|
|
2033
|
-
/**
|
|
2034
|
-
* A walked form's `activate()` (async `defaultValues` factory) threw
|
|
2035
|
-
* during `wizard.handleSubmit`'s path walk. Surfaced as a synthetic
|
|
2036
|
-
* `ValidationError` at the form-level path (`[]`) so the wizard's
|
|
2037
|
-
* aggregate error pipeline can carry the failure alongside ordinary
|
|
2038
|
-
* validation errors. The raw factory error remains on
|
|
2039
|
-
* `form.hydrateError` for retry UX.
|
|
2040
|
-
*/
|
|
2041
|
-
readonly ActivationFailed: "atta:activation-failed";
|
|
2042
|
-
/**
|
|
2043
|
-
* Default code stamped on a manual error set through `form.setErrors`
|
|
2044
|
-
* when the caller omits an explicit `code`. The `setErrors` input is
|
|
2045
|
-
* lenient (`code` optional), so this is the fallback that keeps every
|
|
2046
|
-
* produced `ValidationError` carrying a stable, branchable identifier.
|
|
2047
|
-
* Override it per error by passing your own `code` (`api:…`, `auth:…`).
|
|
2048
|
-
*/
|
|
2049
|
-
readonly UserError: "atta:user-error";
|
|
2050
|
-
/**
|
|
2051
|
-
* Stamped on a `ValidationError` synthesized from a throw or rejection
|
|
2052
|
-
* out of a `handleSubmit` `onSubmit` callback. The raw error also lands
|
|
2053
|
-
* on `form.meta.submitError` (a raw-`Error` inspection channel); this
|
|
2054
|
-
* code marks the copy piped into the user-error layer so the failure
|
|
2055
|
-
* also surfaces on `form.errors` / `meta.ownErrors` / `firstOwnError`
|
|
2056
|
-
* where the UI already reads. A throw carrying its own `path` / `code`
|
|
2057
|
-
* keeps them; a bare `Error` or a non-Error throw defaults here at the
|
|
2058
|
-
* form-level path `[]`.
|
|
2059
|
-
*/
|
|
2060
|
-
readonly SubmitError: "atta:submit-error";
|
|
2061
|
-
/**
|
|
2062
|
-
* Synthesized by `wizard.handleSubmit` when the whole-wizard submit
|
|
2063
|
-
* would otherwise succeed but a `gate()` step is still uncleared. A
|
|
2064
|
-
* gate clears only on its member form's clean submit (confirmation), so
|
|
2065
|
-
* a downstream step that happens to be valid-by-default must not let the
|
|
2066
|
-
* wizard finish past an unconfirmed prerequisite. Emitted at the gate
|
|
2067
|
-
* form's key (path `[]`) so the aggregate error pipeline routes focus to
|
|
2068
|
-
* the gate, and `done` never latches.
|
|
2069
|
-
*/
|
|
2070
|
-
readonly GateNotCleared: "atta:gate-not-cleared";
|
|
2071
|
-
};
|
|
2072
|
-
type AttaformErrorCode = (typeof AttaformErrorCode)[keyof typeof AttaformErrorCode];
|
|
2073
|
-
|
|
2074
|
-
/**
|
|
2075
|
-
* Options for `createAttaform()`.
|
|
2076
|
-
*/
|
|
2077
|
-
type AttaformPluginOptions = SSRDetectOptions & {
|
|
2078
|
-
/**
|
|
2079
|
-
* Whether to install the Vue DevTools integration. Default `true`.
|
|
2080
|
-
* The integration is dev-only: the `import('./devtools')` sits behind
|
|
2081
|
-
* the `__DEV__` flag, so a consumer's production build folds it out
|
|
2082
|
-
* entirely (no devtools chunk shipped, no fetch attempted). In
|
|
2083
|
-
* development the DevTools peer is loaded lazily and a missing peer
|
|
2084
|
-
* fails silently. Pass `false` to skip the integration even in dev.
|
|
2085
|
-
*/
|
|
2086
|
-
devtools?: boolean;
|
|
2087
|
-
};
|
|
2088
|
-
/**
|
|
2089
|
-
* Create the Vue plugin that installs the form library on a Vue
|
|
2090
|
-
* application. Required only when you want app-wide options
|
|
2091
|
-
* (`devtools: false`, `ssr: true`) — for the default setup,
|
|
2092
|
-
* `useForm` / `injectForm` / `useRegister` lazy-install the registry
|
|
2093
|
-
* on first use.
|
|
2094
|
-
*
|
|
2095
|
-
* ```ts
|
|
2096
|
-
* import { createApp } from 'vue'
|
|
2097
|
-
* import { createAttaform } from 'attaform'
|
|
2098
|
-
*
|
|
2099
|
-
* createApp(App)
|
|
2100
|
-
* .use(createAttaform({ devtools: false }))
|
|
2101
|
-
* .mount('#app')
|
|
2102
|
-
* ```
|
|
2103
|
-
*
|
|
2104
|
-
* Under SSR with bare Vue 3, install explicitly with `{ ssr: true }`
|
|
2105
|
-
* from your server entry — the SSR serialization helpers
|
|
2106
|
-
* (`renderAttaformState` / `hydrateAttaformState`) require an
|
|
2107
|
-
* already-attached registry and don't trigger lazy install. Under
|
|
2108
|
-
* Nuxt, install via `attaform/nuxt` instead — the Nuxt module wires
|
|
2109
|
-
* both server and client automatically.
|
|
2110
|
-
*
|
|
2111
|
-
* Installing more than once on the same app is a no-op (the second
|
|
2112
|
-
* call logs a dev-mode warning).
|
|
2113
|
-
*/
|
|
2114
|
-
declare function createAttaform(options?: AttaformPluginOptions): Plugin;
|
|
2115
|
-
|
|
2116
|
-
/**
|
|
2117
|
-
* Serialised snapshot of every form in a Vue app, produced by
|
|
2118
|
-
* `renderAttaformState` and consumed by `hydrateAttaformState`.
|
|
2119
|
-
*
|
|
2120
|
-
* JSON-safe — pass to `JSON.stringify`, `devalue`, or any other
|
|
2121
|
-
* serialiser before embedding in your SSR payload.
|
|
2122
|
-
*/
|
|
2123
|
-
type SerializedAttaformState = {
|
|
2124
|
-
/** Envelope version — see {@link ATTAFORM_STATE_VERSION}. */
|
|
2125
|
-
readonly v: number;
|
|
2126
|
-
/** Tuples of `[formKey, snapshot]` for every form in the app. */
|
|
2127
|
-
readonly forms: ReadonlyArray<readonly [FormKey, SerializedFormData]>;
|
|
2128
|
-
};
|
|
2129
|
-
/**
|
|
2130
|
-
* Snapshot every form on a Vue app for SSR. Call from your server
|
|
2131
|
-
* entry after rendering the app:
|
|
2132
|
-
*
|
|
2133
|
-
* ```ts
|
|
2134
|
-
* import { renderToString } from '@vue/server-renderer'
|
|
2135
|
-
* import { renderAttaformState, escapeForInlineScript } from 'attaform'
|
|
2136
|
-
*
|
|
2137
|
-
* const html = await renderToString(app)
|
|
2138
|
-
* const state = renderAttaformState(app)
|
|
2139
|
-
* const payload = escapeForInlineScript(JSON.stringify(state))
|
|
2140
|
-
*
|
|
2141
|
-
* return `
|
|
2142
|
-
* ${html}
|
|
2143
|
-
* <script>window.__ATTAFORM_STATE__ = ${payload}</script>
|
|
2144
|
-
* `
|
|
2145
|
-
* ```
|
|
2146
|
-
*
|
|
2147
|
-
* Pair with `hydrateAttaformState` on the client to restore the
|
|
2148
|
-
* forms in their server-rendered state. Nuxt users don't need this —
|
|
2149
|
-
* `attaform/nuxt` wires SSR automatically.
|
|
2150
|
-
*/
|
|
2151
|
-
declare function renderAttaformState(app: App): SerializedAttaformState;
|
|
2152
|
-
/**
|
|
2153
|
-
* Restore forms from a server-rendered snapshot on the client. Call
|
|
2154
|
-
* from your client entry before mounting:
|
|
2155
|
-
*
|
|
2156
|
-
* ```ts
|
|
2157
|
-
* import { createApp } from 'vue'
|
|
2158
|
-
* import { createAttaform, hydrateAttaformState } from 'attaform'
|
|
2159
|
-
*
|
|
2160
|
-
* const app = createApp(App).use(createAttaform())
|
|
2161
|
-
* hydrateAttaformState(app, window.__ATTAFORM_STATE__)
|
|
2162
|
-
* app.mount('#app')
|
|
2163
|
-
* ```
|
|
2164
|
-
*
|
|
2165
|
-
* Accepts `unknown` because the payload crosses the wire untyped
|
|
2166
|
-
* (an inline `<script>` tag, `JSON.parse`): the envelope is
|
|
2167
|
-
* validated at runtime, and anything that isn't a version-matched
|
|
2168
|
-
* `renderAttaformState` snapshot is skipped wholesale, so forms
|
|
2169
|
-
* construct fresh from their schemas instead.
|
|
2170
|
-
*
|
|
2171
|
-
* The next `useForm({ key })` call for each serialised form picks up
|
|
2172
|
-
* the snapshot transparently — no further action is required.
|
|
2173
|
-
*/
|
|
2174
|
-
declare function hydrateAttaformState(app: App, payload: unknown): void;
|
|
2175
|
-
|
|
2176
|
-
/**
|
|
2177
|
-
* Escape a JSON string so it's safe to embed inside an inline
|
|
2178
|
-
* `<script>` tag during SSR. Plain `JSON.stringify` is not safe — a
|
|
2179
|
-
* form value containing the literal substring `</script>` would
|
|
2180
|
-
* break out of the script tag.
|
|
2181
|
-
*
|
|
2182
|
-
* ```ts
|
|
2183
|
-
* const payload = escapeForInlineScript(JSON.stringify(renderAttaformState(app)))
|
|
2184
|
-
* // `<script>window.__ATTAFORM_STATE__ = ${payload}</script>` is safe.
|
|
2185
|
-
* ```
|
|
2186
|
-
*
|
|
2187
|
-
* Output remains valid JSON — `JSON.parse` round-trips back to the
|
|
2188
|
-
* original value on the client.
|
|
2189
|
-
*/
|
|
2190
|
-
declare function escapeForInlineScript(json: string): string;
|
|
2191
|
-
|
|
2192
|
-
/**
|
|
2193
|
-
* Symbol slot used by custom directive integrations to install an
|
|
2194
|
-
* assigner on the bound element. Read by the v-register directive
|
|
2195
|
-
* when a DOM event fires:
|
|
2196
|
-
*
|
|
2197
|
-
* ```ts
|
|
2198
|
-
* import { assignKey } from 'attaform'
|
|
2199
|
-
* el[assignKey] = (value) => myCustomWriter(value)
|
|
2200
|
-
* ```
|
|
2201
|
-
*
|
|
2202
|
-
* Most consumers never need this — the built-in directives wire
|
|
2203
|
-
* default assigners for text inputs, checkboxes, radios, and selects.
|
|
2204
|
-
*/
|
|
2205
|
-
declare const assignKey: unique symbol;
|
|
2206
|
-
|
|
2207
|
-
/**
|
|
2208
|
-
* Type guard for a `RegisterValue`. Returns `true` when `val` looks
|
|
2209
|
-
* like the object returned from `form.register(path)`.
|
|
2210
|
-
*
|
|
2211
|
-
* ```ts
|
|
2212
|
-
* if (isRegisterValue(slotValue)) {
|
|
2213
|
-
* // slotValue.innerRef is now a Ref<unknown>
|
|
2214
|
-
* }
|
|
2215
|
-
* ```
|
|
2216
|
-
*
|
|
2217
|
-
* Useful when building wrapper components that accept either a
|
|
2218
|
-
* `RegisterValue` or a plain ref via the same prop.
|
|
2219
|
-
*/
|
|
2220
|
-
declare function isRegisterValue<Value = unknown>(val: unknown): val is RegisterValue<Value>;
|
|
2221
|
-
|
|
2222
|
-
/**
|
|
2223
|
-
* Shared building blocks for Attaform's two devtools surfaces — the Vue
|
|
2224
|
-
* DevTools (Chrome-extension) inspector wired up in `./devtools.ts`, and
|
|
2225
|
-
* the Nuxt DevTools (overlay) panel wired up via `../../nuxt.ts` +
|
|
2226
|
-
* `../pages/_attaform_devtools.vue`.
|
|
2227
|
-
*
|
|
2228
|
-
* Houses the window-bridge contract both surfaces consume so a new
|
|
2229
|
-
* bridge field lands in one file. Both surfaces render RAW form values
|
|
2230
|
-
* by design — DevTools is a dev-only surface, and redaction across every
|
|
2231
|
-
* place a value surfaces is impractical security theater rather than a
|
|
2232
|
-
* real safeguard.
|
|
2233
|
-
*/
|
|
2234
|
-
|
|
2235
|
-
/**
|
|
2236
|
-
* Property key on `window` that the Nuxt-side dev plugin attaches the
|
|
2237
|
-
* bridge object to. The iframe-mounted overlay panel reads
|
|
2238
|
-
* `window.parent[DEVTOOLS_WINDOW_KEY]` to reach the host app's registry.
|
|
2239
|
-
*
|
|
2240
|
-
* Underscored + namespaced to make accidental collision with consumer
|
|
2241
|
-
* globals vanishingly unlikely. Stable across versions — bumping it
|
|
2242
|
-
* would silently disconnect older library builds from newer overlay
|
|
2243
|
-
* panels in the same browser tab during a library upgrade.
|
|
2244
|
-
*/
|
|
2245
|
-
declare const DEVTOOLS_WINDOW_KEY = "__attaform_devtools__";
|
|
2246
|
-
/**
|
|
2247
|
-
* Shape of the object the host plugin attaches to `window` in dev mode.
|
|
2248
|
-
* The iframe overlay panel reads this to discover the live registry and
|
|
2249
|
-
* render its forms.
|
|
2250
|
-
*
|
|
2251
|
-
* Single-registry assumption: the latest `createAttaform()` install
|
|
2252
|
-
* wins. Multi-app pages (rare; typically only seen in micro-frontend
|
|
2253
|
-
* setups) will only see one app's forms in the panel. Documented but
|
|
2254
|
-
* not actively supported — the alternative (a Set of registries with
|
|
2255
|
-
* union-rendering) is a future call if a real consumer hits it.
|
|
2256
|
-
*/
|
|
2257
|
-
interface AttaformDevtoolsBridge {
|
|
2258
|
-
registry: AttaformRegistry;
|
|
2259
|
-
/**
|
|
2260
|
-
* The library version, surfaced in the panel's footer for support /
|
|
2261
|
-
* bug-report context. Read from `package.json` at host-plugin init.
|
|
2262
|
-
*/
|
|
2263
|
-
version: string;
|
|
2264
|
-
}
|
|
2265
|
-
declare global {
|
|
2266
|
-
interface Window {
|
|
2267
|
-
[DEVTOOLS_WINDOW_KEY]?: AttaformDevtoolsBridge;
|
|
2268
|
-
}
|
|
2269
|
-
}
|
|
2270
|
-
|
|
2271
|
-
/**
|
|
2272
|
-
* Typed error classes thrown by the form library. Each one signals a
|
|
2273
|
-
* distinct misuse so calling code can branch on `instanceof` instead
|
|
2274
|
-
* of pattern-matching error messages.
|
|
2275
|
-
*
|
|
2276
|
-
* Every class extends `AttaformError`, so consumers can write a single
|
|
2277
|
-
* polymorphic catch (`catch (e) { if (e instanceof AttaformError) ... }`)
|
|
2278
|
-
* instead of OR-chaining checks for each subclass. `AttaformError` itself
|
|
2279
|
-
* extends the standard `Error`, so existing `instanceof Error` usage
|
|
2280
|
-
* keeps working.
|
|
2281
|
-
*/
|
|
2282
|
-
|
|
2283
|
-
/**
|
|
2284
|
-
* Base for every error class thrown by `attaform`. Sets
|
|
2285
|
-
* `this.name` from the constructor's `new.target.name`, so subclasses
|
|
2286
|
-
* don't have to redeclare their own name override.
|
|
2287
|
-
*/
|
|
2288
|
-
declare class AttaformError extends Error {
|
|
2289
|
-
constructor(message: string, options?: ErrorOptions);
|
|
2290
|
-
}
|
|
2291
|
-
/**
|
|
2292
|
-
* Thrown when a path string is malformed — typically a dotted path
|
|
2293
|
-
* with empty segments (e.g. `'a..b'`, leading or trailing dots).
|
|
2294
|
-
* Use array form (`['a', 'b']`) for keys that contain literal dots.
|
|
2295
|
-
*/
|
|
2296
|
-
declare class InvalidPathError extends AttaformError {
|
|
2297
|
-
}
|
|
2298
|
-
/**
|
|
2299
|
-
* Thrown when `useForm` receives an invalid configuration — most often
|
|
2300
|
-
* a schema passed directly as the first argument, or no argument at
|
|
2301
|
-
* all. The configuration is an options bag; the schema is one of
|
|
2302
|
-
* several fields, even when it's the only one in use.
|
|
2303
|
-
*
|
|
2304
|
-
* ```ts
|
|
2305
|
-
* // ✗ Crashes deep inside the validator with an opaque message:
|
|
2306
|
-
* const form = useForm(z.object({ ... }))
|
|
2307
|
-
* // ✗ Same:
|
|
2308
|
-
* const form = useForm()
|
|
2309
|
-
* // ✓ Pass the schema as the `schema` field:
|
|
2310
|
-
* const form = useForm({ schema: z.object({ ... }) })
|
|
2311
|
-
* ```
|
|
2312
|
-
*
|
|
2313
|
-
* The same shape applies to every entry point: `attaform/zod`,
|
|
2314
|
-
* `attaform/zod-v3`, `attaform/zod-v4`, and the schema-agnostic
|
|
2315
|
-
* `attaform` root.
|
|
2316
|
-
*/
|
|
2317
|
-
declare class InvalidUseFormConfigError extends AttaformError {
|
|
2318
|
-
constructor();
|
|
2319
|
-
}
|
|
2320
|
-
/**
|
|
2321
|
-
* Thrown when a `handleSubmit`-supplied `onError` callback itself
|
|
2322
|
-
* throws or rejects. Wraps the inner failure so both the original
|
|
2323
|
-
* cause (via `error.cause`) and the propagation site are visible.
|
|
2324
|
-
*/
|
|
2325
|
-
declare class SubmitErrorHandlerError extends AttaformError {
|
|
2326
|
-
}
|
|
2327
|
-
/**
|
|
2328
|
-
* Thrown when an `attaform` API needs the registry attached to a Vue
|
|
2329
|
-
* app but it isn't there yet. Component-level entry points (`useForm`,
|
|
2330
|
-
* `injectForm`, `useRegister`) lazy-install the registry on first use,
|
|
2331
|
-
* so this error is mostly reached by SSR helpers — `renderAttaformState`
|
|
2332
|
-
* and `hydrateAttaformState` — which run outside a setup context and
|
|
2333
|
-
* have no current instance to install against.
|
|
2334
|
-
*
|
|
2335
|
-
* Fix: add `app.use(createAttaform())` (or `app.use(createAttaform({
|
|
2336
|
-
* ssr: true }))` on the server) to your SSR entry, before
|
|
2337
|
-
* `renderToString` / hydration. Under Nuxt, `attaform/nuxt` already
|
|
2338
|
-
* does this; the error usually points at a non-Nuxt SSR setup that
|
|
2339
|
-
* hasn't installed explicitly.
|
|
2340
|
-
*/
|
|
2341
|
-
declare class RegistryNotInstalledError extends AttaformError {
|
|
2342
|
-
constructor();
|
|
2343
|
-
}
|
|
2344
|
-
/**
|
|
2345
|
-
* Thrown when `useForm` / `injectForm` is called outside of a
|
|
2346
|
-
* Vue `setup()` function — typically from an event handler, watcher,
|
|
2347
|
-
* or async callback that runs after mount.
|
|
2348
|
-
*
|
|
2349
|
-
* Fix: move the call into `setup()`, or trigger it from a child
|
|
2350
|
-
* component whose `setup()` runs the composable.
|
|
2351
|
-
*/
|
|
2352
|
-
declare class OutsideSetupError extends AttaformError {
|
|
2353
|
-
constructor();
|
|
2354
|
-
}
|
|
2355
|
-
/**
|
|
2356
|
-
* Thrown when a `useForm({ key })` call uses a key starting with
|
|
2357
|
-
* `__atta:`. That prefix is reserved for keys the library generates
|
|
2358
|
-
* internally (e.g. for anonymous `useForm()` calls without an
|
|
2359
|
-
* explicit key). Pick a different prefix for your form.
|
|
2360
|
-
*/
|
|
2361
|
-
declare class ReservedFormKeyError extends AttaformError {
|
|
2362
|
-
constructor(key: string);
|
|
2363
|
-
}
|
|
2364
|
-
|
|
2365
|
-
export { createRegistry as B, DEVTOOLS_WINDOW_KEY as D, escapeForInlineScript as E, gate as H, getRegistryFromApp as J, hydrateAttaformState as K, injectForm as M, injectWizard as N, OutsideSetupError as O, isRegisterValue as P, kAttaformRegistry as Q, RegistryNotInstalledError as R, lazy as T, renderAttaformState as V, useRegister as X, useRegistry as Y, useWizard as Z, AttaformError as c, AttaformErrorCode as d, InvalidPathError as g, InvalidUseFormConfigError as h, ReservedFormKeyError as i, SubmitErrorHandlerError as l, assignKey as y, createAttaform as z };
|
|
2366
|
-
export type { AttaformRegistry as A, CompiledStep as C, FormStatus as F, GateMarker as G, InjectWizardInput as I, LazyMarker as L, SerializedAttaformState as S, UseRegisterOptions as U, WizardAggregateError as W, AnyForm as a, AttaformDevtoolsBridge as b, AttaformPluginOptions as e, FormStatusSeed as f, SerializedFormData as j, StepSlot as k, UseRegisterReturn as m, UseWizardReturnType as n, WizardCtx as o, WizardCtxForm as p, WizardOnError as q, WizardOnSubmit as r, WizardOptions as s, WizardPersistFn as t, WizardRestoreFn as u, WizardRestoreState as v, WizardStatusesProxy as w, WizardSubmitContext as x };
|