@shikiform/react 0.0.0-stage → 0.1.0

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.
@@ -0,0 +1,1024 @@
1
+ import { createContext, memo, useContext, useMemo, useRef, useSyncExternalStore, useState, useEffect, useCallback, useId, forwardRef, useLayoutEffect } from 'react';
2
+ import { formatMessage, ShikiUsageError, showDraftPath, uiId, normalizeUiSpec, engineOf, emptySlot, createForm, deepEqual, joinPath, getAt, pathDomId, nearestName } from '@shikiform/core/internal';
3
+ import { jsx, Fragment } from 'react/jsx-runtime';
4
+ import { useVirtualizer } from '@tanstack/react-virtual';
5
+
6
+ // src/context.tsx
7
+ var FormContext = createContext(null);
8
+ var ScopeContext = createContext({ path: "", index: -1 });
9
+ var ArrayContext = createContext(null);
10
+ var RowWrapContext = createContext(null);
11
+ function useFormContext() {
12
+ return useRequiredForm("useFormContext()");
13
+ }
14
+ function useRequiredForm(caller) {
15
+ const form = useContext(FormContext);
16
+ if (!form) {
17
+ throw new Error(
18
+ `[shikiform] ${caller} has no form. Render it inside <Form form={form}> (useForm / createForm). A form instance is not provided until <Form> wraps the fields.`
19
+ );
20
+ }
21
+ return form;
22
+ }
23
+ function useScope() {
24
+ return useContext(ScopeContext);
25
+ }
26
+ function useFormMessage() {
27
+ const form = useContext(FormContext);
28
+ const overrides = form?.options.messages;
29
+ return (key, ...params) => formatMessage(overrides, key, ...params);
30
+ }
31
+ function useWatch(select) {
32
+ if (select === void 0) {
33
+ return ((next) => useWatch(next));
34
+ }
35
+ const form = useRequiredForm("useWatch()");
36
+ const selectRef = useRef(select);
37
+ selectRef.current = select;
38
+ const cache = useRef(null);
39
+ const read = () => {
40
+ const tracked = form.trackSelector(selectRef.current);
41
+ const value = tracked.value;
42
+ if (cache.current && (Object.is(cache.current.value, value) || deepEqual(cache.current.value, value))) {
43
+ return cache.current.value;
44
+ }
45
+ cache.current = { value };
46
+ return value;
47
+ };
48
+ return useSyncExternalStore(
49
+ (onStoreChange) => {
50
+ let stops = [];
51
+ let last = "";
52
+ const listen = () => {
53
+ const tracked = form.trackSelector(selectRef.current);
54
+ const key = tracked.deps.join("|");
55
+ if (key === last && stops.length) return;
56
+ for (const stop of stops) stop();
57
+ stops = tracked.deps.length > 0 ? tracked.deps.map(
58
+ (dep) => form.subscribeDep(dep, () => {
59
+ listen();
60
+ onStoreChange();
61
+ })
62
+ ) : [form.subscribeDebug(onStoreChange)];
63
+ last = key;
64
+ };
65
+ listen();
66
+ return () => {
67
+ for (const stop of stops) stop();
68
+ };
69
+ },
70
+ read,
71
+ read
72
+ );
73
+ }
74
+ var FieldGroupStore = class {
75
+ counts = /* @__PURE__ */ new Map();
76
+ listeners = /* @__PURE__ */ new Set();
77
+ ver = 0;
78
+ paths = () => [...this.counts.keys()];
79
+ version = () => this.ver;
80
+ subscribe = (listener) => {
81
+ this.listeners.add(listener);
82
+ return () => {
83
+ this.listeners.delete(listener);
84
+ };
85
+ };
86
+ /** Register `path` until the returned function runs. */
87
+ add(path) {
88
+ this.counts.set(path, (this.counts.get(path) ?? 0) + 1);
89
+ this.changed();
90
+ let done = false;
91
+ return () => {
92
+ if (done) return;
93
+ done = true;
94
+ const left = (this.counts.get(path) ?? 1) - 1;
95
+ if (left > 0) this.counts.set(path, left);
96
+ else this.counts.delete(path);
97
+ this.changed();
98
+ };
99
+ }
100
+ changed() {
101
+ this.ver++;
102
+ for (const listener of [...this.listeners]) listener();
103
+ }
104
+ };
105
+ var FieldGroupContext = createContext(null);
106
+ function useFieldGroup() {
107
+ const [group] = useState(() => new FieldGroupStore());
108
+ return group;
109
+ }
110
+ function FieldGroup({ value, children }) {
111
+ const parent = useContext(FieldGroupContext);
112
+ const registrar = useMemo(
113
+ () => ({
114
+ add(path) {
115
+ const own = value.add(path);
116
+ const up = parent?.add(path);
117
+ return () => {
118
+ own();
119
+ up?.();
120
+ };
121
+ }
122
+ }),
123
+ [value, parent]
124
+ );
125
+ return /* @__PURE__ */ jsx(FieldGroupContext.Provider, { value: registrar, children });
126
+ }
127
+ function useFieldGroupRegistration(path) {
128
+ const registrar = useContext(FieldGroupContext);
129
+ useEffect(() => registrar ? registrar.add(path) : void 0, [registrar, path]);
130
+ }
131
+ var ids = /* @__PURE__ */ new WeakMap();
132
+ var nextId = 0;
133
+ function groupId(group) {
134
+ let id = ids.get(group);
135
+ if (id === void 0) ids.set(group, id = ++nextId);
136
+ return id;
137
+ }
138
+ function inPaths(path, paths) {
139
+ for (const one of paths) if (path === one || path.startsWith(one + ".") || one === "") return true;
140
+ return false;
141
+ }
142
+ function useGroupsErrors(form, groups) {
143
+ const key = groups.map(groupId).join(",");
144
+ const subscribe = useCallback(
145
+ (onChange) => {
146
+ const stops = groups.map((group) => group.subscribe(onChange));
147
+ return () => {
148
+ for (const stop of stops) stop();
149
+ };
150
+ },
151
+ // eslint-disable-next-line react-hooks/exhaustive-deps
152
+ [key]
153
+ );
154
+ const snapshot = () => groups.map((group) => group.version()).join(",");
155
+ const versions = useSyncExternalStore(subscribe, snapshot, snapshot);
156
+ const select = useCallback(
157
+ (d) => {
158
+ void d.$errors;
159
+ const all = form.errors;
160
+ return groups.map((group) => {
161
+ const paths = group.paths();
162
+ return paths.length ? all.filter((error) => inPaths(error.path, paths)) : [];
163
+ });
164
+ },
165
+ // eslint-disable-next-line react-hooks/exhaustive-deps
166
+ [form, versions, key]
167
+ );
168
+ return useWatch(select);
169
+ }
170
+ function useFieldGroupErrors(group) {
171
+ const form = useRequiredForm("useFieldGroupErrors()");
172
+ return useGroupsErrors(form, [group])[0];
173
+ }
174
+ function resolveName(form, scope, name) {
175
+ const path = joinPath(scope.path, name);
176
+ if (process.env.NODE_ENV !== "production" && scope.path && name.startsWith(scope.path + ".")) {
177
+ const values = form.values;
178
+ if (getAt(values, path) === void 0 && getAt(values, name) !== void 0) {
179
+ const relative = name.slice(scope.path.length + 1);
180
+ throw new ShikiUsageError(
181
+ `Field name "${name}" is inside the "${scope.path}" scope, so it resolves to "${path}". Names are relative to the enclosing ObjectField / ArrayField / row: write name="${relative}" (typed: the row / object handles from typed(form), e.g. row.Field).`
182
+ );
183
+ }
184
+ }
185
+ return path;
186
+ }
187
+ function useDragProps(key, move, encode, decode) {
188
+ const decodePayload = (raw) => {
189
+ const sep = raw.indexOf("|");
190
+ if (sep < 0 || raw.slice(0, sep) !== key) return void 0;
191
+ return decode(raw.slice(sep + 1));
192
+ };
193
+ const fromRef = useRef(null);
194
+ const moveRef = useRef(move);
195
+ moveRef.current = move;
196
+ const codec = useRef({ encode, decode });
197
+ codec.current = { encode, decode };
198
+ return useCallback(
199
+ (at) => ({
200
+ draggable: true,
201
+ onDragStart: (event) => {
202
+ event.stopPropagation();
203
+ fromRef.current = at;
204
+ event.dataTransfer?.setData("text/plain", `${key}|${codec.current.encode(at)}`);
205
+ if (event.dataTransfer) event.dataTransfer.effectAllowed = "move";
206
+ },
207
+ onDragOver: (event) => {
208
+ event.preventDefault();
209
+ if (event.dataTransfer) event.dataTransfer.dropEffect = "move";
210
+ },
211
+ onDrop: (event) => {
212
+ event.preventDefault();
213
+ event.stopPropagation();
214
+ const raw = event.dataTransfer?.getData("text/plain");
215
+ const from = fromRef.current ?? (raw ? decodePayload(raw) : void 0);
216
+ fromRef.current = null;
217
+ if (from === void 0 || from === null) return;
218
+ if (codec.current.encode(from) === codec.current.encode(at)) return;
219
+ moveRef.current(from, at);
220
+ }
221
+ }),
222
+ [key]
223
+ );
224
+ }
225
+
226
+ // src/hooks/use-array.ts
227
+ function useArrayField(name, opts) {
228
+ const scope = useScope();
229
+ const form = useRequiredForm(`useArrayField('${name}') / <ArrayField name="${name}">`);
230
+ const path = resolveName(form, scope, name);
231
+ if (process.env.NODE_ENV !== "production") assertArrayValue(path, form.getValue(path));
232
+ useFieldGroupRegistration(path);
233
+ return useArrayAt(path, opts?.rowKey);
234
+ }
235
+ function useArray() {
236
+ const ctx = useContext(ArrayContext);
237
+ if (!ctx) {
238
+ if (process.env.NODE_ENV !== "production") {
239
+ throw new ShikiUsageError("useArray() must render inside <ArrayField> (a row or its container component: ArrayItems / ArrayCards / ArrayTable).");
240
+ }
241
+ throw new Error("useArray() must render inside <ArrayField>");
242
+ }
243
+ return useArrayAt(ctx.path, ctx.rowKey);
244
+ }
245
+ function assertArrayValue(path, value) {
246
+ if (value == null || Array.isArray(value)) return;
247
+ const shown = typeof value === "object" ? "an object" : `${typeof value} ${JSON.stringify(value)?.slice(0, 40)}`;
248
+ throw new ShikiUsageError(
249
+ `<ArrayField name="${path}"> / useArrayField('${path}'): ${showDraftPath(path)}.$value is ${shown}, not an array. Start it as an array in initialValues (\`${path.split(".").pop()}: []\`), or use <Field> / <ObjectField> for a non-array value.`
250
+ );
251
+ }
252
+ function useArrayAt(path, rowKey) {
253
+ const form = useRequiredForm(`the array '${path}'`);
254
+ useSyncExternalStore(
255
+ (onStoreChange) => form.subscribeStructure(path, onStoreChange),
256
+ () => form.getStructureVersion(path),
257
+ () => form.getStructureVersion(path)
258
+ );
259
+ form.registerArray(path, rowKey);
260
+ const dragProps = useDragProps(path, (from, to) => form.moveArray(path, from, to), String, toIndex);
261
+ return {
262
+ path,
263
+ keys: form.structureKeys(path, rowKey),
264
+ push: (row) => form.pushArray(path, row),
265
+ insert: (index, row) => form.insertArray(path, index, row),
266
+ remove: (index) => form.removeArray(path, index),
267
+ /** `to` is the final index. */
268
+ move: (from, to) => form.moveArray(path, from, to),
269
+ swap: (indexA, indexB) => form.swapArray(path, indexA, indexB),
270
+ replace: (index, row) => form.replaceArray(path, index, row),
271
+ dragProps
272
+ };
273
+ }
274
+ function toIndex(raw) {
275
+ const index = Number(raw);
276
+ return Number.isInteger(index) ? index : void 0;
277
+ }
278
+ var NO_MESSAGES = { errors: [], warnings: [] };
279
+ function useArrayErrors() {
280
+ const ctx = useContext(ArrayContext);
281
+ if (!ctx) {
282
+ if (process.env.NODE_ENV !== "production") {
283
+ throw new ShikiUsageError("useArrayErrors() must render inside an <ArrayField> (its container, or a row).");
284
+ }
285
+ throw new Error("useArrayErrors() must render inside an <ArrayField>");
286
+ }
287
+ const form = useRequiredForm("useArrayErrors()");
288
+ const path = ctx.path;
289
+ const cache = useRef(NO_MESSAGES);
290
+ const read = () => {
291
+ const binding = form.binding(path);
292
+ const prev = cache.current;
293
+ if (deepEqual(prev.errors, binding.errors) && deepEqual(prev.warnings, binding.warnings)) return prev;
294
+ const next = { errors: binding.errors, warnings: binding.warnings };
295
+ cache.current = next;
296
+ return next;
297
+ };
298
+ return useSyncExternalStore(
299
+ (onStoreChange) => form.subscribePath(path, onStoreChange),
300
+ read,
301
+ read
302
+ );
303
+ }
304
+ var IdPrefixContext = createContext("");
305
+ function IdPrefixProvider({ prefix, children }) {
306
+ return /* @__PURE__ */ jsx(IdPrefixContext.Provider, { value: prefix, children });
307
+ }
308
+ function useIdPrefix() {
309
+ return useContext(IdPrefixContext);
310
+ }
311
+ function useAutoIdPrefix(explicit) {
312
+ const auto = useId();
313
+ return explicit || auto;
314
+ }
315
+ function prefixDomId(prefix, id) {
316
+ return prefix ? `${prefix}-${id}` : id;
317
+ }
318
+ function focusFieldDomId(prefix, path) {
319
+ return prefixDomId(prefix, pathDomId(path));
320
+ }
321
+ function withDomId(binding, prefix) {
322
+ const id = prefixDomId(prefix, binding.id);
323
+ return id === binding.id ? binding : { ...binding, id };
324
+ }
325
+ var FieldKitContext = createContext(null);
326
+ function isComponent(value) {
327
+ return typeof value === "function" || !!value && typeof value === "object" && !Array.isArray(value);
328
+ }
329
+ function lookup(table, name, kind) {
330
+ const found = table[name];
331
+ if (found) return found;
332
+ const names = Object.keys(table);
333
+ const near = nearestName(name, names);
334
+ const slot = kind === "component" ? "components" : "decorators";
335
+ throw new ShikiUsageError(
336
+ `[shikiform] Unknown ${kind} "${name}".` + (near ? ` Did you mean "${near}"?` : "") + (names.length ? ` Registered: ${names.join(", ")}.` : " None are registered.") + ` Add it to <Form kit={{ ${slot}: { ${near ?? name} } }} /> or <FieldKit>, or pass the component instead of a string.`
337
+ );
338
+ }
339
+ function compileDecorator(spec, decorators) {
340
+ if (typeof spec === "string") return { component: lookup(decorators, spec, "decorator") };
341
+ if (Array.isArray(spec)) {
342
+ const head = spec[0];
343
+ const component = typeof head === "string" ? lookup(decorators, head, "decorator") : head;
344
+ if (!isComponent(component)) {
345
+ throw new ShikiUsageError("[shikiform] FieldKit `decorator` tuple has no component. Pass a component or a registered name.");
346
+ }
347
+ return { component, props: spec[1] };
348
+ }
349
+ return { component: spec };
350
+ }
351
+ function mergeKit(parent, spec) {
352
+ const components = { ...parent?.components, ...spec.components };
353
+ const decorators = { ...parent?.decorators, ...spec.decorators };
354
+ let decorator = parent?.decorator;
355
+ let decoratorProps = parent?.decoratorProps;
356
+ if (spec.decorator !== void 0) {
357
+ const resolved = compileDecorator(spec.decorator, decorators);
358
+ decorator = resolved.component;
359
+ decoratorProps = resolved.props;
360
+ }
361
+ return { components, decorators, decorator, decoratorProps };
362
+ }
363
+ function FieldKit({ children, ...spec }) {
364
+ const parent = useContext(FieldKitContext);
365
+ return /* @__PURE__ */ jsx(FieldKitContext.Provider, { value: mergeKit(parent, spec), children });
366
+ }
367
+ function useFieldKit() {
368
+ return useContext(FieldKitContext);
369
+ }
370
+ function resolveSlot(slot, table, kind) {
371
+ if (slot == null || slot === false) return void 0;
372
+ if (typeof slot === "string") return lookup(table ?? {}, slot, kind);
373
+ if (isComponent(slot)) return slot;
374
+ throw new ShikiUsageError(
375
+ `[shikiform] ${kind} must be a component, a [component, props] tuple, or a registered name. Received ${String(slot)}.`
376
+ );
377
+ }
378
+ function withResolvedSlots(field, kit, defaults) {
379
+ const component = resolveSlot(field.component, kit?.components, "component");
380
+ let decorator;
381
+ let decoratorProps = field.decoratorProps;
382
+ if (field.decorator === false) decorator = void 0;
383
+ else if (field.decorator != null) decorator = resolveSlot(field.decorator, kit?.decorators, "decorator");
384
+ else if (defaults && kit?.decorator) {
385
+ decorator = kit.decorator;
386
+ decoratorProps = { ...kit.decoratorProps, ...field.decoratorProps };
387
+ }
388
+ if (component === field.component && decorator === field.decorator && decoratorProps === field.decoratorProps) return field;
389
+ return { ...field, component, decorator, decoratorProps };
390
+ }
391
+
392
+ // src/hooks/field-lifecycle.ts
393
+ function applyJsxField(form, path, spec) {
394
+ if (spec.rules === void 0 && spec.required === void 0) {
395
+ form.registerField(path, { display: spec.display, pattern: spec.pattern });
396
+ return void 0;
397
+ }
398
+ const lease = form.mountJsxField(path, spec);
399
+ return () => form.releaseJsxField(path, lease);
400
+ }
401
+
402
+ // src/hooks/use-field.ts
403
+ var FieldContext = createContext(null);
404
+ function useField(name, options) {
405
+ const current = useContext(FieldContext);
406
+ if (name === void 0) {
407
+ if (!current) throw new ShikiUsageError(NO_FIELD);
408
+ return current;
409
+ }
410
+ const kit = useFieldKit();
411
+ const form = useRequiredForm(`useField('${String(name)}') / <Field name="${String(name)}">`);
412
+ const prefix = useIdPrefix();
413
+ const scope = useScope();
414
+ const path = resolveName(form, scope, String(name));
415
+ const ui = options?.ui;
416
+ if (ui && process.env.NODE_ENV !== "production") warnInstanceOptions(path, ui, options);
417
+ const spec = options && !ui ? { rules: options.rules, required: options.required, display: options.display, pattern: options.pattern } : void 0;
418
+ const ownsValidation = !!spec && (spec.rules !== void 0 || spec.required !== void 0);
419
+ const latestSpec = useRef(spec);
420
+ latestSpec.current = spec;
421
+ if (spec) applyJsxField(form, path, spec);
422
+ useEffect(() => {
423
+ const current2 = latestSpec.current;
424
+ return current2 ? applyJsxField(form, path, current2) : void 0;
425
+ }, [form, path, ownsValidation]);
426
+ useJsxEnum(form, path, ui ? void 0 : options?.enum);
427
+ useFieldGroupRegistration(path);
428
+ useSyncExternalStore(
429
+ (onStoreChange) => form.subscribePath(path, onStoreChange),
430
+ () => form.getPathVersion(path),
431
+ () => form.getPathVersion(path)
432
+ );
433
+ useUiNode(form, path, ui, "field");
434
+ form.registerField(path, {});
435
+ if (ui) {
436
+ return withResolvedSlots(withDomId(form.uiBinding(path, ui, uiJsx(options, path), "field"), prefix), kit, false);
437
+ }
438
+ return withResolvedSlots(withDomId(form.binding(path, options && uiLayer(options, path)), prefix), kit, true);
439
+ }
440
+ var NO_UI = () => () => {
441
+ };
442
+ var ZERO = () => 0;
443
+ function useUiNode(form, path, ui, kind) {
444
+ const id = ui ? uiId(path, ui) : "";
445
+ useSyncExternalStore(
446
+ ui ? (onStoreChange) => form.subscribePath(id, onStoreChange) : NO_UI,
447
+ ui ? () => form.getPathVersion(id) : ZERO,
448
+ ui ? () => form.getPathVersion(id) : ZERO
449
+ );
450
+ useEffect(() => {
451
+ form.markUiReady();
452
+ return ui ? form.claimUi(path, ui, kind) : void 0;
453
+ }, [form, path, ui, kind]);
454
+ }
455
+ var warnedInstance = /* @__PURE__ */ new Set();
456
+ function warnInstanceOptions(path, ui, options) {
457
+ const owned = ["rules", "required", "enum"].filter((key2) => options[key2] !== void 0);
458
+ const key = `${path}#${ui}`;
459
+ if (!owned.length || warnedInstance.has(key)) return;
460
+ warnedInstance.add(key);
461
+ console.warn(
462
+ `[shikiform] <Field name="${path}" ui="${ui}"> ignores ${owned.join(", ")}: a UI instance shares the field's value, rules and options. Put ${owned.join(" / ")} on the <Field name="${path}"> without ui (or in fields / a reaction).`
463
+ );
464
+ }
465
+ function useJsxEnum(form, path, input) {
466
+ const has = input !== void 0;
467
+ const lease = useRef(void 0);
468
+ const latest = useRef(input);
469
+ latest.current = input;
470
+ if (has) lease.current = form.applyJsxEnum(path, input, "render");
471
+ useEffect(() => {
472
+ if (latest.current !== void 0) lease.current = form.applyJsxEnum(path, latest.current, "commit");
473
+ });
474
+ useEffect(() => {
475
+ if (!has) return;
476
+ return () => form.releaseJsxEnum(path, lease.current);
477
+ }, [form, path, has]);
478
+ }
479
+ var NO_FIELD = `[shikiform] useField() without a name reads the surrounding <Field>, but this component is not inside one. Render it inside <Field name="\u2026"> (or as its component / decorator / children), or pass a name: useField('email').`;
480
+ function uiJsx(options, path) {
481
+ const display = options.display === "virtual" ? "visible" : options.display;
482
+ return { ...uiLayer(options, path), display, pattern: options.pattern };
483
+ }
484
+ function uiLayer(options, path) {
485
+ const { title, description, component, decorator } = options;
486
+ if (title === void 0 && description === void 0 && component === void 0 && decorator === void 0) return void 0;
487
+ return normalizeUiSpec({ title, description, component, decorator }, `<Field name="${path}"${options.ui ? ` ui="${options.ui}"` : ""}>`);
488
+ }
489
+ function useFieldContextOrNull() {
490
+ return useContext(FieldContext);
491
+ }
492
+ function useTreeField(name, opts) {
493
+ const form = useRequiredForm(`useTreeField('${name}') / <TreeField name="${name}">`);
494
+ const scope = useScope();
495
+ const path = resolveName(form, scope, name);
496
+ useFieldGroupRegistration(path);
497
+ form.registerTree(path, opts);
498
+ useSyncExternalStore(
499
+ (onStoreChange) => form.subscribeStructure(path, onStoreChange),
500
+ () => form.getStructureVersion(path),
501
+ () => form.getStructureVersion(path)
502
+ );
503
+ const value = form.getValue(path);
504
+ const dragProps = useDragProps(path, (from, to) => form.moveTree(path, from, to), (pos) => pos.join("."), toPos);
505
+ return {
506
+ path,
507
+ value: Array.isArray(value) ? value : [],
508
+ move: (from, to) => form.moveTree(path, from, to),
509
+ dragProps
510
+ };
511
+ }
512
+ function toPos(raw) {
513
+ const pos = raw.split(".").map(Number);
514
+ return pos.every(Number.isInteger) ? pos : void 0;
515
+ }
516
+ function VirtualRows({
517
+ count,
518
+ height,
519
+ rowHeight = 40,
520
+ overscan = 4,
521
+ children
522
+ }) {
523
+ const parentRef = useRef(null);
524
+ const virtualizer = useVirtualizer({
525
+ count,
526
+ getScrollElement: () => parentRef.current,
527
+ estimateSize: () => rowHeight,
528
+ overscan
529
+ });
530
+ const items = virtualizer.getVirtualItems();
531
+ return /* @__PURE__ */ jsx("div", { ref: parentRef, "data-virtual-scroll": "true", style: { height, overflow: "auto", position: "relative" }, children: /* @__PURE__ */ jsx("div", { style: { height: virtualizer.getTotalSize(), position: "relative" }, children: items.map((item) => /* @__PURE__ */ jsx(
532
+ "div",
533
+ {
534
+ "data-virtual-index": item.index,
535
+ style: { position: "absolute", top: 0, left: 0, width: "100%", transform: `translateY(${item.start}px)` },
536
+ children: children(item.index)
537
+ },
538
+ item.index
539
+ )) }) });
540
+ }
541
+ var ROOT_SCOPE = { path: "", index: -1 };
542
+ function handleFormSubmit(form, event, handlers) {
543
+ event.preventDefault();
544
+ event.stopPropagation();
545
+ runSubmit(form, handlers);
546
+ }
547
+ function runSubmit(form, handlers) {
548
+ void form.submit(handlers.onSubmit).then((result) => {
549
+ if (result.ok) return;
550
+ if (result.reason === "invalid") handlers.onInvalid?.(result.errors);
551
+ else if (result.reason === "error") {
552
+ if (handlers.onSubmitError) handlers.onSubmitError(result.error);
553
+ else console.error("[shikiform] onSubmit failed", result.error);
554
+ }
555
+ }).catch((err) => {
556
+ console.error("[shikiform] submit callback failed", err);
557
+ });
558
+ }
559
+ function Form({ form, children, onSubmit, onInvalid, onSubmitError, id, kit, ...rest }) {
560
+ const ref = useRef(null);
561
+ const prefix = useAutoIdPrefix(id);
562
+ useEffect(() => {
563
+ let timer;
564
+ const stop = form.subscribeValidateFailed((errors) => {
565
+ clearTimeout(timer);
566
+ let tries = 0;
567
+ const run = () => {
568
+ focusFirstError(ref.current, errors, prefix);
569
+ const focused = document.activeElement;
570
+ if (focused && focused !== document.body) return;
571
+ if (++tries >= 5) return;
572
+ timer = setTimeout(run, 0);
573
+ };
574
+ timer = setTimeout(run, 0);
575
+ });
576
+ return () => {
577
+ stop();
578
+ clearTimeout(timer);
579
+ };
580
+ }, [form, prefix]);
581
+ return /* @__PURE__ */ jsx(FormContext.Provider, { value: engineOf(form), children: /* @__PURE__ */ jsx(IdPrefixProvider, { prefix, children: /* @__PURE__ */ jsx(ScopeContext.Provider, { value: ROOT_SCOPE, children: /* @__PURE__ */ jsx("form", { ...rest, id, ref, onSubmit: (event) => handleFormSubmit(form, event, { onSubmit, onInvalid, onSubmitError }), children: kit ? /* @__PURE__ */ jsx(FieldKit, { ...kit, children }) : children }) }) }) });
582
+ }
583
+ function focusFirstError(root, errors, prefix) {
584
+ if (!root) return;
585
+ let first = null;
586
+ for (const { path } of errors) {
587
+ if (!path) continue;
588
+ const el = root.ownerDocument.getElementById(focusFieldDomId(prefix, path));
589
+ if (!el || !root.contains(el)) continue;
590
+ if (typeof el.checkVisibility === "function" && !el.checkVisibility()) continue;
591
+ if (!first || first.compareDocumentPosition(el) & Node.DOCUMENT_POSITION_PRECEDING) first = el;
592
+ }
593
+ if (!first) return;
594
+ first.focus();
595
+ if (root.ownerDocument.activeElement !== first) first.scrollIntoView?.({ block: "center" });
596
+ }
597
+ function Field({ name, children, ...options }) {
598
+ const field = useField(name, options);
599
+ if (field.display !== "visible" && field.display !== "virtual") return null;
600
+ const Component = field.component;
601
+ const Decorator = field.decorator;
602
+ const content = typeof children === "function" ? children(field) : children !== void 0 ? children : Component ? /* @__PURE__ */ jsx(Component, { ...field.componentProps }) : null;
603
+ return /* @__PURE__ */ jsx(FieldContext.Provider, { value: field, children: Decorator ? /* @__PURE__ */ jsx(Decorator, { ...field.decoratorProps, children: content }) : content });
604
+ }
605
+ function ObjectField({
606
+ name,
607
+ display,
608
+ children
609
+ }) {
610
+ const form = useRequiredForm(`<ObjectField name="${String(name)}">`);
611
+ const scope = useScope();
612
+ const path = resolveName(form, scope, String(name));
613
+ if (display !== void 0) form.registerField(path, { display });
614
+ const next = useMemo(() => ({ path, index: -1 }), [path]);
615
+ return /* @__PURE__ */ jsx(ScopeContext.Provider, { value: next, children });
616
+ }
617
+ function ArrayField({
618
+ name,
619
+ rowKey,
620
+ component,
621
+ virtualScroll,
622
+ children
623
+ }) {
624
+ const array = useArrayField(String(name), { rowKey });
625
+ const [Container, props] = Array.isArray(component) ? component : [component, void 0];
626
+ if (Array.isArray(component) && Container == null && process.env.NODE_ENV !== "production") {
627
+ throw emptySlot(`<ArrayField name="${String(name)}">`, "component", Container);
628
+ }
629
+ if (virtualScroll && Container) {
630
+ throw new ShikiUsageError(
631
+ `<ArrayField name="${String(name)}"> takes \`virtualScroll\` or a container \`component\`, not both: virtualScroll windows plain rows (\`<ArrayField name virtualScroll>{(row) => \u2026}</ArrayField>\`).`
632
+ );
633
+ }
634
+ const row = (index, key) => /* @__PURE__ */ jsx(ArrayRow, { path: `${array.path}.${index}`, index, itemKey: key, render: children }, key);
635
+ let rows = null;
636
+ if (children && virtualScroll) {
637
+ rows = /* @__PURE__ */ jsx(VirtualRows, { count: array.keys.length, height: virtualScroll.height, rowHeight: virtualScroll.rowHeight ?? 42, overscan: virtualScroll.overscan ?? 4, children: (index) => {
638
+ const at = array.keys[index];
639
+ return at ? row(index, at.key) : null;
640
+ } });
641
+ } else if (children) {
642
+ rows = array.keys.map((at) => row(at.index, at.key));
643
+ }
644
+ return /* @__PURE__ */ jsx(ArrayScope, { path: array.path, rowKey, children: Container ? /* @__PURE__ */ jsx(Container, { ...props, children: rows }) : rows });
645
+ }
646
+ var ArrayRow = memo(function ArrayRow2({ path, index, itemKey, render }) {
647
+ const wrap = useContext(RowWrapContext);
648
+ const content = render({ index, key: itemKey });
649
+ return /* @__PURE__ */ jsx(RowScope, { path, index, itemKey, children: wrap ? wrap(/* @__PURE__ */ jsx(RowWrapContext.Provider, { value: null, children: content })) : content });
650
+ });
651
+ function ArrayScope({ path, rowKey, children }) {
652
+ const value = useMemo(() => ({ path, rowKey }), [path, rowKey]);
653
+ return /* @__PURE__ */ jsx(ArrayContext.Provider, { value, children });
654
+ }
655
+ function RowScope({
656
+ path,
657
+ index,
658
+ itemKey,
659
+ pos,
660
+ children
661
+ }) {
662
+ const at = index ?? (pos ? pos[pos.length - 1] ?? -1 : -1);
663
+ const posKey = pos?.join(".");
664
+ const value = useMemo(() => ({ path, index: at, itemKey, pos }), [path, at, itemKey, posKey]);
665
+ return /* @__PURE__ */ jsx(ScopeContext.Provider, { value, children });
666
+ }
667
+ function TreeField({
668
+ name,
669
+ childrenKey,
670
+ rowKey,
671
+ children
672
+ }) {
673
+ const tree = useTreeField(String(name), { childrenKey, rowKey });
674
+ return children(tree);
675
+ }
676
+ function Watch({ select, children }) {
677
+ const value = useWatch(select);
678
+ return /* @__PURE__ */ jsx(Fragment, { children: children(value) });
679
+ }
680
+
681
+ // src/hooks/use-submit.ts
682
+ function useSubmit(options) {
683
+ const form = useRequiredForm("<Submit> / useSubmit()");
684
+ const meta = useWatch((d) => ({ can: d.$canSubmit === true, submitting: d.$submitting === true }));
685
+ const own = options?.onSubmit !== void 0;
686
+ const onClick = options?.onClick;
687
+ const onSubmit = options?.onSubmit;
688
+ const onInvalid = options?.onInvalid;
689
+ const onSubmitError = options?.onSubmitError;
690
+ return {
691
+ canSubmit: meta.can,
692
+ submitting: meta.submitting,
693
+ loading: meta.submitting,
694
+ disabled: options?.disabled ?? !meta.can,
695
+ type: own ? "button" : "submit",
696
+ "aria-busy": meta.submitting ? true : void 0,
697
+ "data-loading": meta.submitting ? "" : void 0,
698
+ onClick: (event) => {
699
+ onClick?.(event);
700
+ if (!own || event.defaultPrevented) return;
701
+ runSubmit(form, { onSubmit, onInvalid, onSubmitError });
702
+ }
703
+ };
704
+ }
705
+ function useReset(options) {
706
+ const form = useRequiredForm("<Reset> / useReset()");
707
+ const values = options?.values;
708
+ const afterReset = options?.afterReset;
709
+ const onClick = options?.onClick;
710
+ return {
711
+ type: "button",
712
+ disabled: options?.disabled ?? false,
713
+ onClick: (event) => {
714
+ onClick?.(event);
715
+ if (event.defaultPrevented) return;
716
+ form.reset(values);
717
+ afterReset?.(form.values);
718
+ }
719
+ };
720
+ }
721
+ var DEFAULT_TARGETS = {
722
+ value: "value",
723
+ onChange: "onChange",
724
+ onBlur: "onBlur",
725
+ disabled: "disabled",
726
+ readOnly: "readOnly",
727
+ // Ant Design only. A non-antd control would receive `status="error"` and may forward it to the DOM.
728
+ status: false,
729
+ id: "id",
730
+ options: false,
731
+ loading: false
732
+ };
733
+ var MAPPING_META = /* @__PURE__ */ new Set(["format", "parse", "blurOn"]);
734
+ function valueFromEvent(...args) {
735
+ const first = args[0];
736
+ if (first && typeof first === "object" && "target" in first && first.target && typeof first.target === "object") {
737
+ const target = first.target;
738
+ if (target.type === "checkbox") return target.checked;
739
+ if ("value" in target) return target.value;
740
+ if ("checked" in target) return target.checked;
741
+ }
742
+ return first;
743
+ }
744
+ function mapFieldProps(field, props, ...mappers) {
745
+ const mapping = {};
746
+ const transforms = [];
747
+ for (const mapper of mappers) {
748
+ if (typeof mapper === "function") transforms.push(mapper);
749
+ else Object.assign(mapping, mapper);
750
+ }
751
+ return applyMapping(field, { ...field.componentProps, ...props }, mapping, transforms, false);
752
+ }
753
+ function controlOptions(options) {
754
+ return options.map((option) => {
755
+ const out = { label: option.label, value: option.value, disabled: option.disabled };
756
+ if (option.children) out.children = controlOptions(option.children);
757
+ return out;
758
+ });
759
+ }
760
+ function readState(field, key) {
761
+ let current = field;
762
+ for (const part of key.split(".")) {
763
+ if (current == null || typeof current !== "object") return void 0;
764
+ current = current[part];
765
+ }
766
+ return current;
767
+ }
768
+ function blurSpec(blurOn, changeProp) {
769
+ if (blurOn === "onChange") {
770
+ if (!changeProp) return void 0;
771
+ return { prop: changeProp, when: () => true };
772
+ }
773
+ if (blurOn === "onOpenChange") return { prop: "onOpenChange", when: (open) => open === false };
774
+ return { prop: blurOn.prop, when: blurOn.when ?? (() => true) };
775
+ }
776
+ function withBlur(props, field, blurOn, changeProp) {
777
+ const spec = blurSpec(blurOn, changeProp);
778
+ if (!spec) return props;
779
+ const caller = props[spec.prop];
780
+ return {
781
+ ...props,
782
+ [spec.prop]: (...args) => {
783
+ caller?.(...args);
784
+ if (spec.when(...args)) field.onBlur();
785
+ }
786
+ };
787
+ }
788
+ function applyMapping(field, props, mapping, transforms, hasReadPretty) {
789
+ const target = (key) => mapping[key] === void 0 ? DEFAULT_TARGETS[key] : mapping[key];
790
+ const parseValue = mapping.parse ?? valueFromEvent;
791
+ const out = { ...props };
792
+ const value = target("value");
793
+ if (value) out[value] = field.value;
794
+ const id = target("id");
795
+ if (id) out[id] = props[id] ?? field.id;
796
+ const disabled = target("disabled");
797
+ if (disabled) out[disabled] = !!out[disabled] || field.disabled;
798
+ const readOnly = target("readOnly");
799
+ if (readOnly) out[readOnly] = !!out[readOnly] || field.readOnly || !hasReadPretty && field.pattern === "readPretty";
800
+ const status = target("status");
801
+ if (status) {
802
+ const derived = field.errors.length ? "error" : field.warnings.length ? "warning" : void 0;
803
+ out[status] = props[status] ?? derived;
804
+ }
805
+ const options = target("options");
806
+ if (options) {
807
+ out[options] = props[options] ?? controlOptions(field.options);
808
+ }
809
+ const loading = target("loading");
810
+ if (loading) out[loading] = props[loading] ?? field.loading;
811
+ const changeProp = target("onChange");
812
+ if (changeProp) {
813
+ const caller = props[changeProp];
814
+ out[changeProp] = (...args) => {
815
+ field.onChange(parseValue(...args));
816
+ caller?.(...args);
817
+ };
818
+ }
819
+ const onBlur = mapping.onBlur !== void 0 ? mapping.onBlur : mapping.blurOn ? false : target("onBlur");
820
+ if (onBlur) {
821
+ const caller = props[onBlur];
822
+ out[onBlur] = (...args) => {
823
+ field.onBlur();
824
+ caller?.(...args);
825
+ };
826
+ }
827
+ for (const [key, prop] of Object.entries(mapping)) {
828
+ if (MAPPING_META.has(key) || key in DEFAULT_TARGETS || typeof prop !== "string") continue;
829
+ if (props[prop] === void 0) out[prop] = readState(field, key);
830
+ }
831
+ let result = out;
832
+ for (const transform of transforms) result = transform(result, field) ?? result;
833
+ if (value && mapping.format) result = { ...result, [value]: mapping.format(field.value, result) };
834
+ if (mapping.blurOn) result = withBlur(result, field, mapping.blurOn, changeProp);
835
+ return result;
836
+ }
837
+ function mapProps(...args) {
838
+ const mapping = {};
839
+ const transforms = [];
840
+ for (const arg of args) {
841
+ if (typeof arg === "function") transforms.push(arg);
842
+ else Object.assign(mapping, arg);
843
+ }
844
+ let blur;
845
+ if (mapping.blurOn) blur = mapping.blurOn;
846
+ else if (mapping.onBlur === false) blur = "drop";
847
+ else if (typeof mapping.onBlur === "string") blur = "rename";
848
+ const enhancer = blur ? { kind: "props", mapping, transforms, blur } : { kind: "props", mapping, transforms };
849
+ return enhancer;
850
+ }
851
+ function mapBlur(on) {
852
+ return { kind: "props", mapping: { blurOn: on }, transforms: [], blur: on };
853
+ }
854
+ function mapReadPretty(component, props) {
855
+ return { kind: "readPretty", component, props };
856
+ }
857
+ var NOT_STATIC = /* @__PURE__ */ new Set([
858
+ // React component statics and function / class built-ins: never copied.
859
+ "displayName",
860
+ "propTypes",
861
+ "defaultProps",
862
+ "contextType",
863
+ "contextTypes",
864
+ "childContextTypes",
865
+ "getDefaultProps",
866
+ "getDerivedStateFromProps",
867
+ "getDerivedStateFromError",
868
+ "mixins",
869
+ "$$typeof",
870
+ "render",
871
+ "compare",
872
+ "type",
873
+ "length",
874
+ "name",
875
+ "prototype",
876
+ "caller",
877
+ "callee",
878
+ "arguments",
879
+ "arity"
880
+ ]);
881
+ var warned = /* @__PURE__ */ new Set();
882
+ function connect(target, ...enhancers) {
883
+ const mapping = {};
884
+ const transforms = [];
885
+ let readPretty;
886
+ for (const enhancer of enhancers) {
887
+ if (enhancer.kind === "props") {
888
+ Object.assign(mapping, enhancer.mapping);
889
+ transforms.push(...enhancer.transforms);
890
+ } else readPretty = enhancer;
891
+ }
892
+ const Target = target;
893
+ const displayName = `Connected(${Target.displayName ?? Target.name ?? "Component"})`;
894
+ const render = (field, callerProps, ref) => {
895
+ const props = { ...field.componentProps, ...callerProps };
896
+ if (readPretty && field.pattern === "readPretty") {
897
+ const Pretty = readPretty.component;
898
+ return /* @__PURE__ */ jsx(Pretty, { ...readPretty.props, ...props, value: field.value, options: props.options ?? field.options });
899
+ }
900
+ const mapped = applyMapping(field, props, mapping, transforms, !!readPretty);
901
+ return ref == null ? /* @__PURE__ */ jsx(Target, { ...mapped }) : /* @__PURE__ */ jsx(Target, { ...mapped, ref });
902
+ };
903
+ function WithField({ field, rest, forwarded }) {
904
+ return render(field, rest, forwarded);
905
+ }
906
+ function WithName({ name, rest, forwarded }) {
907
+ return render(useField(name), rest, forwarded);
908
+ }
909
+ function FromContext({ rest, forwarded }) {
910
+ const field = useFieldContextOrNull();
911
+ if (field) return render(field, rest, forwarded);
912
+ if (process.env.NODE_ENV !== "production" && !warned.has(displayName)) {
913
+ warned.add(displayName);
914
+ console.warn(
915
+ `[shikiform] ${displayName} is outside a <Field> and has no \`name\` / \`field\` prop: it renders as the plain control, bound to nothing. Put it in <Field name="\u2026" component={[\u2026]}>, or pass name="\u2026".`
916
+ );
917
+ }
918
+ return forwarded == null ? /* @__PURE__ */ jsx(Target, { ...rest }) : /* @__PURE__ */ jsx(Target, { ...rest, ref: forwarded });
919
+ }
920
+ const Connected = forwardRef(function Connected2(props, forwarded) {
921
+ const { name, field, ...rest } = props;
922
+ if (field) return /* @__PURE__ */ jsx(WithField, { field, rest, forwarded });
923
+ if (name !== void 0) return /* @__PURE__ */ jsx(WithName, { name, rest, forwarded });
924
+ return /* @__PURE__ */ jsx(FromContext, { rest, forwarded });
925
+ });
926
+ Connected.displayName = displayName;
927
+ for (const key of Object.getOwnPropertyNames(target)) {
928
+ if (NOT_STATIC.has(key) || key in Connected) continue;
929
+ const descriptor = Object.getOwnPropertyDescriptor(target, key);
930
+ if (descriptor) Object.defineProperty(Connected, key, descriptor);
931
+ }
932
+ return Connected;
933
+ }
934
+ var useIsoLayoutEffect = typeof window === "undefined" ? useEffect : useLayoutEffect;
935
+ function useForm(options) {
936
+ const ref = useRef(null);
937
+ const values = options?.values;
938
+ const last = useRef(values);
939
+ if (!ref.current) {
940
+ const { values: _values, ...rest } = options ?? {};
941
+ ref.current = createForm(values !== void 0 ? { ...rest, initialValues: values } : rest);
942
+ }
943
+ const form = ref.current;
944
+ useIsoLayoutEffect(() => {
945
+ if (values === last.current) return;
946
+ const changed = !deepEqual(values, last.current);
947
+ last.current = values;
948
+ if (changed && values !== void 0) form.reset(values);
949
+ }, [values, form]);
950
+ return form;
951
+ }
952
+ var UiNodeContext = createContext(null);
953
+ function useUiNodeOrNull() {
954
+ return useContext(UiNodeContext);
955
+ }
956
+ function UI({
957
+ name,
958
+ children,
959
+ display,
960
+ pattern,
961
+ ...slots
962
+ }) {
963
+ const form = useRequiredForm(`<UI name="${String(name)}">`);
964
+ const path = useScope().path;
965
+ const prefix = useIdPrefix();
966
+ useUiNode(form, path, name, "node");
967
+ const kit = useFieldKit();
968
+ const ui = withResolvedSlots(withDomId(form.uiBinding(path, name, { ...normalizeUiSpec(slots, `<UI name="${String(name)}">`), display, pattern }, "node"), prefix), kit, false);
969
+ if (ui.display !== "visible") return null;
970
+ const Component = ui.component;
971
+ const Decorator = ui.decorator;
972
+ const inner = typeof children === "function" ? children(ui) : children;
973
+ const content = Component ? /* @__PURE__ */ jsx(Component, { ...ui.componentProps, children: inner }) : inner;
974
+ if (!Decorator) return content;
975
+ return /* @__PURE__ */ jsx(UiNodeContext.Provider, { value: ui, children: /* @__PURE__ */ jsx(Decorator, { ...ui.decoratorProps, children: /* @__PURE__ */ jsx(UiNodeContext.Provider, { value: null, children: content }) }) });
976
+ }
977
+ function useIndex() {
978
+ const scope = useScope();
979
+ if (scope.index < 0) {
980
+ if (process.env.NODE_ENV !== "production") {
981
+ throw new ShikiUsageError("useIndex() must render inside an array row (<ArrayField> rows, ArrayTable cells included).");
982
+ }
983
+ throw new Error("useIndex() must render inside an array row");
984
+ }
985
+ return scope.index;
986
+ }
987
+ function useRecord() {
988
+ const form = useRequiredForm("useRecord() / useTreeNode()");
989
+ const scope = useScope();
990
+ if (scope.index < 0 && !scope.pos) {
991
+ if (process.env.NODE_ENV !== "production") {
992
+ throw new ShikiUsageError("useRecord() must render inside an array row (<ArrayField> rows, ArrayTable cells included) or a tree node (<RowScope path pos>).");
993
+ }
994
+ throw new Error("useRecord() must render inside an array row or tree node");
995
+ }
996
+ const path = scope.path;
997
+ const select = useCallback((_d) => form.query(path).$value, [form, path]);
998
+ return useWatch(select);
999
+ }
1000
+ function useTreeNode() {
1001
+ const scope = useScope();
1002
+ if (!scope.pos) {
1003
+ if (process.env.NODE_ENV !== "production") {
1004
+ throw new ShikiUsageError("useTreeNode() must render inside a tree node: wrap it in <RowScope path={\u2026} pos={\u2026}>.");
1005
+ }
1006
+ throw new Error("useTreeNode() must render inside a tree node (<RowScope path pos>)");
1007
+ }
1008
+ const form = useRequiredForm("useRecord() / useTreeNode()");
1009
+ const record = useRecord();
1010
+ const pos = scope.pos;
1011
+ const path = scope.path;
1012
+ const treePath = form.treeRoot(path) ?? path;
1013
+ const move = useCallback((from, to) => form.moveTree(treePath, from, to), [form, treePath]);
1014
+ const baseProps = useDragProps(treePath, move, (at) => at.join("."), (raw) => {
1015
+ const decoded = raw.split(".").map(Number);
1016
+ return decoded.every(Number.isInteger) ? decoded : void 0;
1017
+ });
1018
+ const dragProps = useCallback((at) => baseProps(at ?? pos), [baseProps, pos.join(".")]);
1019
+ return { path, pos, index: pos[pos.length - 1] ?? -1, record, move, dragProps };
1020
+ }
1021
+
1022
+ export { ArrayContext, ArrayField, ArrayScope, Field, FieldGroup, FieldGroupStore, FieldKit, Form, FormContext, IdPrefixProvider, ObjectField, RowScope, RowWrapContext, ScopeContext, TreeField, UI, VirtualRows, Watch, connect, mapBlur, mapFieldProps, mapProps, mapReadPretty, useArray, useArrayAt, useArrayErrors, useArrayField, useAutoIdPrefix, useField, useFieldContextOrNull, useFieldGroup, useFieldGroupErrors, useFieldGroupRegistration, useForm, useFormContext, useFormMessage, useGroupsErrors, useIndex, useRecord, useRequiredForm, useReset, useScope, useSubmit, useTreeField, useTreeNode, useUiNodeOrNull, useWatch, valueFromEvent };
1023
+ //# sourceMappingURL=chunk-EYDJ6I7P.js.map
1024
+ //# sourceMappingURL=chunk-EYDJ6I7P.js.map