@cntyclub/ui-react 0.1.0 → 0.1.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/form.js CHANGED
@@ -1,8 +1,9 @@
1
- import { require_with_selector, Field, FieldLabel, CheckboxGroup, Checkbox, FieldError, FieldDescription, Popover, PopoverTrigger, Calendar, format, Button, cn, PopoverPopup, Calendar2, FieldControl, NumberField, NumberFieldGroup, NumberFieldDecrement, NumberFieldInput, NumberFieldIncrement, Select, SelectTrigger, SelectValue, SelectPopup, SelectItem, SpinnerOnDemand, InputGroup, InputGroupAddon, InputGroupInput, Input } from './chunk-HDGMSYQS.js';
2
- import { __toESM } from './chunk-PR4QN5HX.js';
3
- import { jsxs, jsx, Fragment } from 'react/jsx-runtime';
4
- import * as React from 'react';
5
- import { createContext, useState, useContext, useMemo, useRef, useLayoutEffect, useEffect, useCallback } from 'react';
1
+ import { Button, SpinnerOnDemand, Field, FieldLabel, FieldControl, NumberField, NumberFieldGroup, NumberFieldDecrement, NumberFieldInput, NumberFieldIncrement, FieldError, Popover, PopoverTrigger, cn, PopoverPopup, Calendar, Select, SelectTrigger, SelectValue, SelectPopup, SelectItem, CheckboxGroup, Checkbox, FieldDescription, InputGroup, InputGroupAddon, InputGroupInput, Input } from './chunk-2HQPCV2L.js';
2
+ import { jsx, jsxs, Fragment } from 'react/jsx-runtime';
3
+ import { format } from 'date-fns';
4
+ import { CalendarIcon } from 'lucide-react';
5
+ import { useState } from 'react';
6
+ import { createFormHookContexts, createFormHook, formOptions, revalidateLogic } from '@tanstack/react-form';
6
7
 
7
8
  function CheckboxGroupField({
8
9
  field,
@@ -82,13 +83,13 @@ function DateField({
82
83
  }
83
84
  ),
84
85
  children: [
85
- /* @__PURE__ */ jsx(Calendar, { "aria-hidden": "true" }),
86
+ /* @__PURE__ */ jsx(CalendarIcon, { "aria-hidden": "true" }),
86
87
  value ? format(value, "LLL dd, y") : /* @__PURE__ */ jsx("span", { children: placeholder ?? "Pick a date" })
87
88
  ]
88
89
  }
89
90
  ),
90
91
  /* @__PURE__ */ jsx(PopoverPopup, { children: /* @__PURE__ */ jsx(
91
- Calendar2,
92
+ Calendar,
92
93
  {
93
94
  mode: "single",
94
95
  defaultMonth: value,
@@ -136,7 +137,7 @@ function DateRangeField({
136
137
  }
137
138
  ),
138
139
  children: [
139
- /* @__PURE__ */ jsx(Calendar, { "aria-hidden": "true" }),
140
+ /* @__PURE__ */ jsx(CalendarIcon, { "aria-hidden": "true" }),
140
141
  value.from ? value.to ? /* @__PURE__ */ jsxs(Fragment, { children: [
141
142
  format(value.from, "LLL dd, y"),
142
143
  " -",
@@ -147,7 +148,7 @@ function DateRangeField({
147
148
  }
148
149
  ),
149
150
  /* @__PURE__ */ jsx(PopoverPopup, { children: /* @__PURE__ */ jsx(
150
- Calendar2,
151
+ Calendar,
151
152
  {
152
153
  mode: "range",
153
154
  defaultMonth: value.from,
@@ -172,4858 +173,6 @@ function DateRangeField({
172
173
  /* @__PURE__ */ jsx(FieldError, { match: !!errors.length, children: errors.join(", ") })
173
174
  ] });
174
175
  }
175
-
176
- // ../../node_modules/.pnpm/@tanstack+store@0.11.0/node_modules/@tanstack/store/dist/alien.js
177
- var ReactiveFlags = /* @__PURE__ */ (function(ReactiveFlags2) {
178
- ReactiveFlags2[ReactiveFlags2["None"] = 0] = "None";
179
- ReactiveFlags2[ReactiveFlags2["Mutable"] = 1] = "Mutable";
180
- ReactiveFlags2[ReactiveFlags2["Watching"] = 2] = "Watching";
181
- ReactiveFlags2[ReactiveFlags2["RecursedCheck"] = 4] = "RecursedCheck";
182
- ReactiveFlags2[ReactiveFlags2["Recursed"] = 8] = "Recursed";
183
- ReactiveFlags2[ReactiveFlags2["Dirty"] = 16] = "Dirty";
184
- ReactiveFlags2[ReactiveFlags2["Pending"] = 32] = "Pending";
185
- return ReactiveFlags2;
186
- })({});
187
- // @__NO_SIDE_EFFECTS__
188
- function createReactiveSystem({ update, notify, unwatched }) {
189
- return {
190
- link: link2,
191
- unlink: unlink2,
192
- propagate: propagate2,
193
- checkDirty: checkDirty2,
194
- shallowPropagate: shallowPropagate2
195
- };
196
- function link2(dep, sub, version2) {
197
- const prevDep = sub.depsTail;
198
- if (prevDep !== void 0 && prevDep.dep === dep) return;
199
- const nextDep = prevDep !== void 0 ? prevDep.nextDep : sub.deps;
200
- if (nextDep !== void 0 && nextDep.dep === dep) {
201
- nextDep.version = version2;
202
- sub.depsTail = nextDep;
203
- return;
204
- }
205
- const prevSub = dep.subsTail;
206
- if (prevSub !== void 0 && prevSub.version === version2 && prevSub.sub === sub) return;
207
- const newLink = sub.depsTail = dep.subsTail = {
208
- version: version2,
209
- dep,
210
- sub,
211
- prevDep,
212
- nextDep,
213
- prevSub,
214
- nextSub: void 0
215
- };
216
- if (nextDep !== void 0) nextDep.prevDep = newLink;
217
- if (prevDep !== void 0) prevDep.nextDep = newLink;
218
- else sub.deps = newLink;
219
- if (prevSub !== void 0) prevSub.nextSub = newLink;
220
- else dep.subs = newLink;
221
- }
222
- function unlink2(link3, sub = link3.sub) {
223
- const dep = link3.dep;
224
- const prevDep = link3.prevDep;
225
- const nextDep = link3.nextDep;
226
- const nextSub = link3.nextSub;
227
- const prevSub = link3.prevSub;
228
- if (nextDep !== void 0) nextDep.prevDep = prevDep;
229
- else sub.depsTail = prevDep;
230
- if (prevDep !== void 0) prevDep.nextDep = nextDep;
231
- else sub.deps = nextDep;
232
- if (nextSub !== void 0) nextSub.prevSub = prevSub;
233
- else dep.subsTail = prevSub;
234
- if (prevSub !== void 0) prevSub.nextSub = nextSub;
235
- else if ((dep.subs = nextSub) === void 0) unwatched(dep);
236
- return nextDep;
237
- }
238
- function propagate2(link3) {
239
- let next = link3.nextSub;
240
- let stack;
241
- top: do {
242
- const sub = link3.sub;
243
- let flags = sub.flags;
244
- if (!(flags & (ReactiveFlags.RecursedCheck | ReactiveFlags.Recursed | ReactiveFlags.Dirty | ReactiveFlags.Pending))) sub.flags = flags | ReactiveFlags.Pending;
245
- else if (!(flags & (ReactiveFlags.RecursedCheck | ReactiveFlags.Recursed))) flags = ReactiveFlags.None;
246
- else if (!(flags & ReactiveFlags.RecursedCheck)) sub.flags = flags & ~ReactiveFlags.Recursed | ReactiveFlags.Pending;
247
- else if (!(flags & (ReactiveFlags.Dirty | ReactiveFlags.Pending)) && isValidLink(link3, sub)) {
248
- sub.flags = flags | (ReactiveFlags.Recursed | ReactiveFlags.Pending);
249
- flags &= ReactiveFlags.Mutable;
250
- } else flags = ReactiveFlags.None;
251
- if (flags & ReactiveFlags.Watching) notify(sub);
252
- if (flags & ReactiveFlags.Mutable) {
253
- const subSubs = sub.subs;
254
- if (subSubs !== void 0) {
255
- const nextSub = (link3 = subSubs).nextSub;
256
- if (nextSub !== void 0) {
257
- stack = {
258
- value: next,
259
- prev: stack
260
- };
261
- next = nextSub;
262
- }
263
- continue;
264
- }
265
- }
266
- if ((link3 = next) !== void 0) {
267
- next = link3.nextSub;
268
- continue;
269
- }
270
- while (stack !== void 0) {
271
- link3 = stack.value;
272
- stack = stack.prev;
273
- if (link3 !== void 0) {
274
- next = link3.nextSub;
275
- continue top;
276
- }
277
- }
278
- break;
279
- } while (true);
280
- }
281
- function checkDirty2(link3, sub) {
282
- let stack;
283
- let checkDepth = 0;
284
- let dirty = false;
285
- top: do {
286
- const dep = link3.dep;
287
- const flags = dep.flags;
288
- if (sub.flags & ReactiveFlags.Dirty) dirty = true;
289
- else if ((flags & (ReactiveFlags.Mutable | ReactiveFlags.Dirty)) === (ReactiveFlags.Mutable | ReactiveFlags.Dirty)) {
290
- if (update(dep)) {
291
- const subs = dep.subs;
292
- if (subs.nextSub !== void 0) shallowPropagate2(subs);
293
- dirty = true;
294
- }
295
- } else if ((flags & (ReactiveFlags.Mutable | ReactiveFlags.Pending)) === (ReactiveFlags.Mutable | ReactiveFlags.Pending)) {
296
- if (link3.nextSub !== void 0 || link3.prevSub !== void 0) stack = {
297
- value: link3,
298
- prev: stack
299
- };
300
- link3 = dep.deps;
301
- sub = dep;
302
- ++checkDepth;
303
- continue;
304
- }
305
- if (!dirty) {
306
- const nextDep = link3.nextDep;
307
- if (nextDep !== void 0) {
308
- link3 = nextDep;
309
- continue;
310
- }
311
- }
312
- while (checkDepth--) {
313
- const firstSub = sub.subs;
314
- const hasMultipleSubs = firstSub.nextSub !== void 0;
315
- if (hasMultipleSubs) {
316
- link3 = stack.value;
317
- stack = stack.prev;
318
- } else link3 = firstSub;
319
- if (dirty) {
320
- if (update(sub)) {
321
- if (hasMultipleSubs) shallowPropagate2(firstSub);
322
- sub = link3.sub;
323
- continue;
324
- }
325
- dirty = false;
326
- } else sub.flags &= ~ReactiveFlags.Pending;
327
- sub = link3.sub;
328
- const nextDep = link3.nextDep;
329
- if (nextDep !== void 0) {
330
- link3 = nextDep;
331
- continue top;
332
- }
333
- }
334
- return dirty;
335
- } while (true);
336
- }
337
- function shallowPropagate2(link3) {
338
- do {
339
- const sub = link3.sub;
340
- const flags = sub.flags;
341
- if ((flags & (ReactiveFlags.Pending | ReactiveFlags.Dirty)) === ReactiveFlags.Pending) {
342
- sub.flags = flags | ReactiveFlags.Dirty;
343
- if ((flags & (ReactiveFlags.Watching | ReactiveFlags.RecursedCheck)) === ReactiveFlags.Watching) notify(sub);
344
- }
345
- } while ((link3 = link3.nextSub) !== void 0);
346
- }
347
- function isValidLink(checkLink, sub) {
348
- let link3 = sub.depsTail;
349
- while (link3 !== void 0) {
350
- if (link3 === checkLink) return true;
351
- link3 = link3.prevDep;
352
- }
353
- return false;
354
- }
355
- }
356
-
357
- // ../../node_modules/.pnpm/@tanstack+store@0.11.0/node_modules/@tanstack/store/dist/atom.js
358
- function toObserver(nextHandler, errorHandler, completionHandler) {
359
- const isObserver = typeof nextHandler === "object";
360
- const self = isObserver ? nextHandler : void 0;
361
- return {
362
- next: (isObserver ? nextHandler.next : nextHandler)?.bind(self),
363
- error: (isObserver ? nextHandler.error : errorHandler)?.bind(self),
364
- complete: (isObserver ? nextHandler.complete : completionHandler)?.bind(self)
365
- };
366
- }
367
- var queuedEffects = [];
368
- var cycle = 0;
369
- var { link, unlink, propagate, checkDirty, shallowPropagate } = /* @__PURE__ */ createReactiveSystem({
370
- update(atom) {
371
- return atom._update();
372
- },
373
- notify(effect2) {
374
- queuedEffects[queuedEffectsLength++] = effect2;
375
- effect2.flags &= ~ReactiveFlags.Watching;
376
- },
377
- unwatched(atom) {
378
- if (atom.depsTail !== void 0) {
379
- atom.depsTail = void 0;
380
- atom.flags = ReactiveFlags.Mutable | ReactiveFlags.Dirty;
381
- purgeDeps(atom);
382
- }
383
- }
384
- });
385
- var notifyIndex = 0;
386
- var queuedEffectsLength = 0;
387
- var activeSub;
388
- var batchDepth = 0;
389
- function batch(fn) {
390
- try {
391
- ++batchDepth;
392
- fn();
393
- } finally {
394
- if (!--batchDepth) flush();
395
- }
396
- }
397
- function purgeDeps(sub) {
398
- const depsTail = sub.depsTail;
399
- let dep = depsTail !== void 0 ? depsTail.nextDep : sub.deps;
400
- while (dep !== void 0) dep = unlink(dep, sub);
401
- }
402
- function flush() {
403
- if (batchDepth > 0) return;
404
- while (notifyIndex < queuedEffectsLength) {
405
- const effect2 = queuedEffects[notifyIndex];
406
- queuedEffects[notifyIndex++] = void 0;
407
- effect2.notify();
408
- }
409
- notifyIndex = 0;
410
- queuedEffectsLength = 0;
411
- }
412
- function createAtom(valueOrFn, options) {
413
- const isComputed = typeof valueOrFn === "function";
414
- const getter = valueOrFn;
415
- const atom = {
416
- _snapshot: isComputed ? void 0 : valueOrFn,
417
- subs: void 0,
418
- subsTail: void 0,
419
- deps: void 0,
420
- depsTail: void 0,
421
- flags: isComputed ? ReactiveFlags.None : ReactiveFlags.Mutable,
422
- get() {
423
- if (activeSub !== void 0) link(atom, activeSub, cycle);
424
- return atom._snapshot;
425
- },
426
- subscribe(observerOrFn) {
427
- const obs = toObserver(observerOrFn);
428
- const observed = { current: false };
429
- const e = effect(() => {
430
- atom.get();
431
- if (!observed.current) observed.current = true;
432
- else obs.next?.(atom._snapshot);
433
- });
434
- return { unsubscribe: () => {
435
- e.stop();
436
- } };
437
- },
438
- _update(getValue) {
439
- const prevSub = activeSub;
440
- const compare = Object.is;
441
- if (isComputed) {
442
- activeSub = atom;
443
- ++cycle;
444
- atom.depsTail = void 0;
445
- } else if (getValue === void 0) return false;
446
- if (isComputed) atom.flags = ReactiveFlags.Mutable | ReactiveFlags.RecursedCheck;
447
- try {
448
- const oldValue = atom._snapshot;
449
- const newValue = typeof getValue === "function" ? getValue(oldValue) : getValue === void 0 && isComputed ? getter(oldValue) : getValue;
450
- if (oldValue === void 0 || !compare(oldValue, newValue)) {
451
- atom._snapshot = newValue;
452
- return true;
453
- }
454
- return false;
455
- } finally {
456
- activeSub = prevSub;
457
- if (isComputed) atom.flags &= ~ReactiveFlags.RecursedCheck;
458
- purgeDeps(atom);
459
- }
460
- }
461
- };
462
- if (isComputed) {
463
- atom.flags = ReactiveFlags.Mutable | ReactiveFlags.Dirty;
464
- atom.get = function() {
465
- const flags = atom.flags;
466
- if (flags & ReactiveFlags.Dirty || flags & ReactiveFlags.Pending && checkDirty(atom.deps, atom)) {
467
- if (atom._update()) {
468
- const subs = atom.subs;
469
- if (subs !== void 0) shallowPropagate(subs);
470
- }
471
- } else if (flags & ReactiveFlags.Pending) atom.flags = flags & ~ReactiveFlags.Pending;
472
- if (activeSub !== void 0) link(atom, activeSub, cycle);
473
- return atom._snapshot;
474
- };
475
- } else atom.set = function(valueOrFn2) {
476
- if (atom._update(valueOrFn2)) {
477
- const subs = atom.subs;
478
- if (subs !== void 0) {
479
- propagate(subs);
480
- shallowPropagate(subs);
481
- flush();
482
- }
483
- }
484
- };
485
- return atom;
486
- }
487
- function effect(fn) {
488
- const run = () => {
489
- const prevSub = activeSub;
490
- activeSub = effectObj;
491
- ++cycle;
492
- effectObj.depsTail = void 0;
493
- effectObj.flags = ReactiveFlags.Watching | ReactiveFlags.RecursedCheck;
494
- try {
495
- return fn();
496
- } finally {
497
- activeSub = prevSub;
498
- effectObj.flags &= ~ReactiveFlags.RecursedCheck;
499
- purgeDeps(effectObj);
500
- }
501
- };
502
- const effectObj = {
503
- deps: void 0,
504
- depsTail: void 0,
505
- subs: void 0,
506
- subsTail: void 0,
507
- flags: ReactiveFlags.Watching | ReactiveFlags.RecursedCheck,
508
- notify() {
509
- const flags = this.flags;
510
- if (flags & ReactiveFlags.Dirty || flags & ReactiveFlags.Pending && checkDirty(this.deps, this)) run();
511
- else this.flags = ReactiveFlags.Watching;
512
- },
513
- stop() {
514
- this.flags = ReactiveFlags.None;
515
- this.depsTail = void 0;
516
- purgeDeps(this);
517
- }
518
- };
519
- run();
520
- return effectObj;
521
- }
522
-
523
- // ../../node_modules/.pnpm/@tanstack+store@0.11.0/node_modules/@tanstack/store/dist/store.js
524
- var Store = class {
525
- constructor(valueOrFn, actionsFactory) {
526
- this.atom = createAtom(valueOrFn);
527
- this.get = this.get.bind(this);
528
- this.setState = this.setState.bind(this);
529
- this.subscribe = this.subscribe.bind(this);
530
- if (actionsFactory) this.actions = actionsFactory(this);
531
- }
532
- setState(updater) {
533
- this.atom.set(updater);
534
- }
535
- get state() {
536
- return this.atom.get();
537
- }
538
- get() {
539
- return this.state;
540
- }
541
- subscribe(observerOrFn) {
542
- return this.atom.subscribe(toObserver(observerOrFn));
543
- }
544
- };
545
- var ReadonlyStore = class {
546
- constructor(valueOrFn) {
547
- this.atom = createAtom(valueOrFn);
548
- }
549
- get state() {
550
- return this.atom.get();
551
- }
552
- get() {
553
- return this.state;
554
- }
555
- subscribe(observerOrFn) {
556
- return this.atom.subscribe(toObserver(observerOrFn));
557
- }
558
- };
559
- function createStore(valueOrFn, actions) {
560
- if (typeof valueOrFn === "function") return new ReadonlyStore(valueOrFn);
561
- return new Store(valueOrFn);
562
- }
563
-
564
- // ../../node_modules/.pnpm/@tanstack+pacer-lite@0.1.1/node_modules/@tanstack/pacer-lite/dist/lite-throttler.js
565
- var LiteThrottler = class {
566
- constructor(fn, options) {
567
- this.fn = fn;
568
- this.options = options;
569
- this.lastExecutionTime = 0;
570
- this.isPending = false;
571
- this.maybeExecute = (...args) => {
572
- const timeSinceLastExecution = Date.now() - this.lastExecutionTime;
573
- if (this.options.leading && timeSinceLastExecution >= this.options.wait) this.execute(...args);
574
- else {
575
- this.lastArgs = args;
576
- if (!this.timeoutId && this.options.trailing) {
577
- const timeoutDuration = this.options.wait - timeSinceLastExecution;
578
- this.isPending = true;
579
- this.timeoutId = setTimeout(() => {
580
- if (this.lastArgs !== void 0) this.execute(...this.lastArgs);
581
- }, timeoutDuration);
582
- }
583
- }
584
- };
585
- this.execute = (...args) => {
586
- this.fn(...args);
587
- this.options.onExecute?.(args, this);
588
- this.lastExecutionTime = Date.now();
589
- this.clearTimeout();
590
- this.lastArgs = void 0;
591
- this.isPending = false;
592
- };
593
- this.flush = () => {
594
- if (this.isPending && this.lastArgs) this.execute(...this.lastArgs);
595
- };
596
- this.cancel = () => {
597
- this.clearTimeout();
598
- this.lastArgs = void 0;
599
- this.isPending = false;
600
- };
601
- this.clearTimeout = () => {
602
- if (this.timeoutId) {
603
- clearTimeout(this.timeoutId);
604
- this.timeoutId = void 0;
605
- }
606
- };
607
- if (this.options.leading === void 0 && this.options.trailing === void 0) {
608
- this.options.leading = true;
609
- this.options.trailing = true;
610
- }
611
- }
612
- };
613
- function liteThrottle(fn, options) {
614
- return new LiteThrottler(fn, options).maybeExecute;
615
- }
616
-
617
- // ../../node_modules/.pnpm/@tanstack+devtools-event-client@0.4.3/node_modules/@tanstack/devtools-event-client/dist/esm/plugin.js
618
- var EventClient = class {
619
- #enabled = true;
620
- #pluginId;
621
- #eventTarget;
622
- #debug;
623
- #queuedEvents;
624
- #connected;
625
- #connectIntervalId;
626
- #connectEveryMs;
627
- #retryCount = 0;
628
- #maxRetries = 5;
629
- #connecting = false;
630
- #failedToConnect = false;
631
- #internalEventTarget = null;
632
- #onConnected = () => {
633
- this.debugLog("Connected to event bus");
634
- this.#connected = true;
635
- this.#connecting = false;
636
- this.debugLog("Emitting queued events", this.#queuedEvents);
637
- this.#queuedEvents.forEach((event) => this.emitEventToBus(event));
638
- this.#queuedEvents = [];
639
- this.stopConnectLoop();
640
- this.#eventTarget().removeEventListener(
641
- "tanstack-connect-success",
642
- this.#onConnected
643
- );
644
- };
645
- // fired off right away and then at intervals
646
- #retryConnection = () => {
647
- if (this.#retryCount < this.#maxRetries) {
648
- this.#retryCount++;
649
- this.dispatchCustomEvent("tanstack-connect", {});
650
- return;
651
- }
652
- this.#eventTarget().removeEventListener(
653
- "tanstack-connect",
654
- this.#retryConnection
655
- );
656
- this.#failedToConnect = true;
657
- this.debugLog("Max retries reached, giving up on connection");
658
- this.stopConnectLoop();
659
- };
660
- // This is run to register connection handlers on first emit attempt
661
- #connectFunction = () => {
662
- if (this.#connecting) return;
663
- this.#connecting = true;
664
- this.#eventTarget().addEventListener(
665
- "tanstack-connect-success",
666
- this.#onConnected
667
- );
668
- this.#retryConnection();
669
- };
670
- constructor({
671
- pluginId,
672
- debug = false,
673
- enabled = true,
674
- reconnectEveryMs = 300
675
- }) {
676
- this.#pluginId = pluginId;
677
- this.#enabled = enabled;
678
- this.#eventTarget = this.getGlobalTarget;
679
- this.#debug = debug;
680
- this.debugLog(" Initializing event subscription for plugin", this.#pluginId);
681
- this.#queuedEvents = [];
682
- this.#connected = false;
683
- this.#failedToConnect = false;
684
- this.#connectIntervalId = null;
685
- this.#connectEveryMs = reconnectEveryMs;
686
- }
687
- startConnectLoop() {
688
- if (this.#connectIntervalId !== null || this.#connected) return;
689
- this.debugLog(`Starting connect loop (every ${this.#connectEveryMs}ms)`);
690
- this.#connectIntervalId = setInterval(
691
- this.#retryConnection,
692
- this.#connectEveryMs
693
- );
694
- }
695
- stopConnectLoop() {
696
- this.#connecting = false;
697
- if (this.#connectIntervalId === null) {
698
- return;
699
- }
700
- clearInterval(this.#connectIntervalId);
701
- this.#connectIntervalId = null;
702
- this.#queuedEvents = [];
703
- this.debugLog("Stopped connect loop");
704
- }
705
- debugLog(...args) {
706
- if (this.#debug) {
707
- console.log(`\u{1F334} [tanstack-devtools:${this.#pluginId}-plugin]`, ...args);
708
- }
709
- }
710
- getGlobalTarget() {
711
- if (typeof globalThis !== "undefined" && globalThis.__TANSTACK_EVENT_TARGET__) {
712
- this.debugLog("Using global event target");
713
- return globalThis.__TANSTACK_EVENT_TARGET__;
714
- }
715
- if (typeof window !== "undefined" && typeof window.addEventListener !== "undefined") {
716
- this.debugLog("Using window as event target");
717
- return window;
718
- }
719
- const eventTarget = typeof EventTarget !== "undefined" ? new EventTarget() : void 0;
720
- if (typeof eventTarget === "undefined" || typeof eventTarget.addEventListener === "undefined") {
721
- this.debugLog(
722
- "No event mechanism available, running in non-web environment"
723
- );
724
- return {
725
- addEventListener: () => {
726
- },
727
- removeEventListener: () => {
728
- },
729
- dispatchEvent: () => false
730
- };
731
- }
732
- this.debugLog("Using new EventTarget as fallback");
733
- return eventTarget;
734
- }
735
- getPluginId() {
736
- return this.#pluginId;
737
- }
738
- dispatchCustomEventShim(eventName, detail) {
739
- try {
740
- const event = new Event(eventName, {
741
- detail
742
- });
743
- this.#eventTarget().dispatchEvent(event);
744
- } catch (e) {
745
- this.debugLog("Failed to dispatch shim event");
746
- }
747
- }
748
- dispatchCustomEvent(eventName, detail) {
749
- try {
750
- this.#eventTarget().dispatchEvent(new CustomEvent(eventName, { detail }));
751
- } catch (e) {
752
- this.dispatchCustomEventShim(eventName, detail);
753
- }
754
- }
755
- emitEventToBus(event) {
756
- this.debugLog("Emitting event to client bus", event);
757
- this.dispatchCustomEvent("tanstack-dispatch-event", event);
758
- }
759
- createEventPayload(eventSuffix, payload) {
760
- return {
761
- type: `${this.#pluginId}:${eventSuffix}`,
762
- payload,
763
- pluginId: this.#pluginId
764
- };
765
- }
766
- emit(eventSuffix, payload) {
767
- if (!this.#enabled) {
768
- this.debugLog(
769
- "Event bus client is disabled, not emitting event",
770
- eventSuffix,
771
- payload
772
- );
773
- return;
774
- }
775
- if (this.#internalEventTarget) {
776
- this.debugLog(
777
- "Emitting event to internal event target",
778
- eventSuffix,
779
- payload
780
- );
781
- this.#internalEventTarget.dispatchEvent(
782
- new CustomEvent(`${this.#pluginId}:${eventSuffix}`, {
783
- detail: this.createEventPayload(eventSuffix, payload)
784
- })
785
- );
786
- }
787
- if (this.#failedToConnect) {
788
- this.debugLog("Previously failed to connect, not emitting to bus");
789
- return;
790
- }
791
- if (!this.#connected) {
792
- this.debugLog("Bus not available, will be pushed as soon as connected");
793
- this.#queuedEvents.push(this.createEventPayload(eventSuffix, payload));
794
- if (typeof CustomEvent !== "undefined" && !this.#connecting) {
795
- this.#connectFunction();
796
- this.startConnectLoop();
797
- }
798
- return;
799
- }
800
- return this.emitEventToBus(this.createEventPayload(eventSuffix, payload));
801
- }
802
- on(eventSuffix, cb, options) {
803
- const withEventTarget = options?.withEventTarget ?? false;
804
- const eventName = `${this.#pluginId}:${eventSuffix}`;
805
- if (withEventTarget) {
806
- if (!this.#internalEventTarget) {
807
- this.#internalEventTarget = new EventTarget();
808
- }
809
- this.#internalEventTarget.addEventListener(eventName, (e) => {
810
- cb(e.detail);
811
- });
812
- }
813
- if (!this.#enabled) {
814
- this.debugLog(
815
- "Event bus client is disabled, not registering event",
816
- eventName
817
- );
818
- return () => {
819
- };
820
- }
821
- const handler = (e) => {
822
- this.debugLog("Received event from bus", e.detail);
823
- cb(e.detail);
824
- };
825
- this.#eventTarget().addEventListener(eventName, handler);
826
- this.debugLog("Registered event to bus", eventName);
827
- return () => {
828
- if (withEventTarget) {
829
- this.#internalEventTarget?.removeEventListener(eventName, handler);
830
- }
831
- this.#eventTarget().removeEventListener(eventName, handler);
832
- };
833
- }
834
- onAll(cb) {
835
- if (!this.#enabled) {
836
- this.debugLog("Event bus client is disabled, not registering event");
837
- return () => {
838
- };
839
- }
840
- const handler = (e) => {
841
- const event = e.detail;
842
- cb(event);
843
- };
844
- this.#eventTarget().addEventListener("tanstack-devtools-global", handler);
845
- return () => this.#eventTarget().removeEventListener(
846
- "tanstack-devtools-global",
847
- handler
848
- );
849
- }
850
- onAllPluginEvents(cb) {
851
- if (!this.#enabled) {
852
- this.debugLog("Event bus client is disabled, not registering event");
853
- return () => {
854
- };
855
- }
856
- const handler = (e) => {
857
- const event = e.detail;
858
- if (this.#pluginId && event.pluginId !== this.#pluginId) {
859
- return;
860
- }
861
- cb(event);
862
- };
863
- this.#eventTarget().addEventListener("tanstack-devtools-global", handler);
864
- return () => this.#eventTarget().removeEventListener(
865
- "tanstack-devtools-global",
866
- handler
867
- );
868
- }
869
- };
870
-
871
- // ../../node_modules/.pnpm/@tanstack+form-core@1.33.0/node_modules/@tanstack/form-core/dist/esm/EventClient.js
872
- var FormEventClient = class extends EventClient {
873
- constructor() {
874
- super({
875
- pluginId: "form-devtools",
876
- reconnectEveryMs: 1e3
877
- });
878
- }
879
- };
880
- var formEventClient = new FormEventClient();
881
-
882
- // ../../node_modules/.pnpm/@tanstack+form-core@1.33.0/node_modules/@tanstack/form-core/dist/esm/utils.js
883
- function functionalUpdate(updater, input) {
884
- return typeof updater === "function" ? updater(input) : updater;
885
- }
886
- function getBy(obj, path) {
887
- const pathObj = makePathArray(path);
888
- return pathObj.reduce((current, pathPart) => {
889
- if (current === null) return null;
890
- if (typeof current !== "undefined") {
891
- return current[pathPart];
892
- }
893
- return void 0;
894
- }, obj);
895
- }
896
- function setBy(obj, _path, updater) {
897
- const path = makePathArray(_path);
898
- function doSet(parent) {
899
- if (!path.length) {
900
- return functionalUpdate(updater, parent);
901
- }
902
- const key = path.shift();
903
- if (typeof key === "string" || typeof key === "number" && !Array.isArray(parent)) {
904
- if (typeof parent === "object") {
905
- if (parent === null) {
906
- parent = {};
907
- }
908
- return {
909
- ...parent,
910
- [key]: doSet(parent[key])
911
- };
912
- }
913
- return {
914
- [key]: doSet()
915
- };
916
- }
917
- if (Array.isArray(parent) && typeof key === "number") {
918
- const prefix = parent.slice(0, key);
919
- return [
920
- ...prefix.length ? prefix : new Array(key),
921
- doSet(parent[key]),
922
- ...parent.slice(key + 1)
923
- ];
924
- }
925
- return [...new Array(key), doSet()];
926
- }
927
- return doSet(obj);
928
- }
929
- function deleteBy(obj, _path) {
930
- const path = makePathArray(_path);
931
- function doDelete(parent) {
932
- if (!parent) return;
933
- if (path.length === 1) {
934
- const finalPath = path[0];
935
- if (Array.isArray(parent) && typeof finalPath === "number") {
936
- return parent.filter((_, i) => i !== finalPath);
937
- }
938
- const { [finalPath]: remove, ...rest } = parent;
939
- return rest;
940
- }
941
- const key = path.shift();
942
- if (typeof key === "string" || typeof key === "number" && !Array.isArray(parent)) {
943
- if (typeof parent === "object") {
944
- return {
945
- ...parent,
946
- [key]: doDelete(parent[key])
947
- };
948
- }
949
- }
950
- if (typeof key === "number") {
951
- if (Array.isArray(parent)) {
952
- if (key >= parent.length) {
953
- return parent;
954
- }
955
- const prefix = parent.slice(0, key);
956
- return [
957
- ...prefix.length ? prefix : new Array(key),
958
- doDelete(parent[key]),
959
- ...parent.slice(key + 1)
960
- ];
961
- }
962
- }
963
- throw new Error("It seems we have created an infinite loop in deleteBy. ");
964
- }
965
- return doDelete(obj);
966
- }
967
- var CC_DOT = 46;
968
- var CC_OPEN = 91;
969
- var CC_CLOSE = 93;
970
- var CC_ZERO = 48;
971
- var CC_NINE = 57;
972
- function makePathArray(str) {
973
- if (Array.isArray(str)) {
974
- return [...str];
975
- }
976
- if (typeof str !== "string") {
977
- throw new Error("Path must be a string.");
978
- }
979
- const len = str.length;
980
- const result = [];
981
- let segStart = len > 0 && str.charCodeAt(0) === CC_OPEN ? 1 : 0;
982
- let allDigits = true;
983
- let prev = -1;
984
- for (let i = segStart; i <= len; i++) {
985
- const char = i < len ? str.charCodeAt(i) : -1;
986
- if (i === len || char === CC_DOT || char === CC_OPEN || char === CC_CLOSE) {
987
- const segLen = i - segStart;
988
- if (segLen > 0) {
989
- const treatAsNumber = (
990
- // ...it must contain only digits...
991
- allDigits && // ...and either be a single '0' or not start with '0'.
992
- (segLen === 1 || str.charCodeAt(segStart) !== CC_ZERO)
993
- );
994
- const seg = str.slice(segStart, i);
995
- if (treatAsNumber) {
996
- const num = parseInt(seg, 10);
997
- if (segLen <= 15 || String(num) === seg) {
998
- result.push(num);
999
- } else {
1000
- result.push(seg);
1001
- }
1002
- } else {
1003
- result.push(seg);
1004
- }
1005
- } else if (
1006
- // This branch, which handles empty segments, only exists to preserve
1007
- // the old behavior for malformed input.
1008
- // Push the empty segment unless this is a "phantom boundary" the
1009
- // old regex impl would have absorbed:
1010
- // 1. `]` was always stripped — `prev === ']'` means the real
1011
- // boundary already happened on the previous iteration.
1012
- // 2. A leading `]` was stripped too (the leading `[` strip
1013
- // above handles its counterpart for `[`).
1014
- // 3. `..` and `[[` collapse to a single boundary.
1015
- prev !== CC_CLOSE && !(prev === -1 && char === CC_CLOSE) && !(prev === char && (char === CC_DOT || char === CC_OPEN))
1016
- ) {
1017
- result.push("");
1018
- }
1019
- segStart = i + 1;
1020
- allDigits = true;
1021
- } else if (char < CC_ZERO || char > CC_NINE) {
1022
- allDigits = false;
1023
- }
1024
- prev = char;
1025
- }
1026
- if (!result.length) result.push("");
1027
- return result;
1028
- }
1029
- function concatenatePaths(path1, path2) {
1030
- if (path1.length === 0) return path2;
1031
- if (path2.length === 0) return path1;
1032
- if (path2.startsWith("[")) {
1033
- return path1 + path2;
1034
- }
1035
- if (path2.startsWith(".")) {
1036
- return path1 + path2;
1037
- }
1038
- return `${path1}.${path2}`;
1039
- }
1040
- function isNonEmptyArray(obj) {
1041
- return !(Array.isArray(obj) && obj.length === 0);
1042
- }
1043
- function getSyncValidatorArray(cause, options) {
1044
- const runValidation = (props) => {
1045
- return props.validators.filter(Boolean).map((validator) => {
1046
- return {
1047
- cause: validator.cause,
1048
- validate: validator.fn
1049
- };
1050
- });
1051
- };
1052
- return options.validationLogic({
1053
- form: options.form,
1054
- group: options.group,
1055
- validators: options.validators,
1056
- event: { type: cause, fieldName: options.fieldName, async: false },
1057
- runValidation
1058
- });
1059
- }
1060
- function getAsyncValidatorArray(cause, options) {
1061
- const { asyncDebounceMs } = options;
1062
- const {
1063
- onBlurAsyncDebounceMs,
1064
- onChangeAsyncDebounceMs,
1065
- onDynamicAsyncDebounceMs
1066
- } = options.validators || {};
1067
- const defaultDebounceMs = asyncDebounceMs ?? 0;
1068
- const runValidation = (props) => {
1069
- return props.validators.filter(Boolean).map((validator) => {
1070
- const validatorCause = validator?.cause || cause;
1071
- let debounceMs = defaultDebounceMs;
1072
- switch (validatorCause) {
1073
- case "change":
1074
- debounceMs = onChangeAsyncDebounceMs ?? defaultDebounceMs;
1075
- break;
1076
- case "blur":
1077
- debounceMs = onBlurAsyncDebounceMs ?? defaultDebounceMs;
1078
- break;
1079
- case "dynamic":
1080
- debounceMs = onDynamicAsyncDebounceMs ?? defaultDebounceMs;
1081
- break;
1082
- case "submit":
1083
- debounceMs = 0;
1084
- break;
1085
- }
1086
- if (cause === "submit") {
1087
- debounceMs = 0;
1088
- }
1089
- return {
1090
- cause: validatorCause,
1091
- validate: validator.fn,
1092
- debounceMs
1093
- };
1094
- });
1095
- };
1096
- return options.validationLogic({
1097
- form: options.form,
1098
- group: options.group,
1099
- validators: options.validators,
1100
- event: { type: cause, fieldName: options.fieldName, async: true },
1101
- runValidation
1102
- });
1103
- }
1104
- var isGlobalFormValidationError = (error) => {
1105
- return !!error && typeof error === "object" && "fields" in error;
1106
- };
1107
- function evaluate(objA, objB) {
1108
- if (Object.is(objA, objB)) {
1109
- return true;
1110
- }
1111
- if (typeof objA !== "object" || objA === null || typeof objB !== "object" || objB === null) {
1112
- return false;
1113
- }
1114
- if (objA instanceof Date && objB instanceof Date) {
1115
- return objA.getTime() === objB.getTime();
1116
- }
1117
- if (objA instanceof Map && objB instanceof Map) {
1118
- if (objA.size !== objB.size) return false;
1119
- for (const [k, v] of objA) {
1120
- if (!objB.has(k) || !Object.is(v, objB.get(k))) return false;
1121
- }
1122
- return true;
1123
- }
1124
- if (objA instanceof Set && objB instanceof Set) {
1125
- if (objA.size !== objB.size) return false;
1126
- for (const v of objA) {
1127
- if (!objB.has(v)) return false;
1128
- }
1129
- return true;
1130
- }
1131
- const keysA = Object.keys(objA);
1132
- const keysB = Object.keys(objB);
1133
- if (keysA.length !== keysB.length) {
1134
- return false;
1135
- }
1136
- if (keysA.length === 0 && !Array.isArray(objA) && !Array.isArray(objB) && (Object.getPrototypeOf(objA) !== Object.prototype || Object.getPrototypeOf(objB) !== Object.prototype)) {
1137
- return false;
1138
- }
1139
- for (const key of keysA) {
1140
- if (!keysB.includes(key) || !evaluate(objA[key], objB[key])) {
1141
- return false;
1142
- }
1143
- }
1144
- return true;
1145
- }
1146
- var determineFormLevelErrorSourceAndValue = ({
1147
- newFormValidatorError,
1148
- isPreviousErrorFromFormValidator,
1149
- previousErrorValue
1150
- }) => {
1151
- if (newFormValidatorError) {
1152
- return { newErrorValue: newFormValidatorError, newSource: "form" };
1153
- }
1154
- if (isPreviousErrorFromFormValidator) {
1155
- return { newErrorValue: void 0, newSource: void 0 };
1156
- }
1157
- if (previousErrorValue) {
1158
- return { newErrorValue: previousErrorValue, newSource: "field" };
1159
- }
1160
- return { newErrorValue: void 0, newSource: void 0 };
1161
- };
1162
- var determineFieldLevelErrorSourceAndValue = ({
1163
- formLevelError,
1164
- fieldLevelError
1165
- }) => {
1166
- if (fieldLevelError) {
1167
- return { newErrorValue: fieldLevelError, newSource: "field" };
1168
- }
1169
- if (formLevelError) {
1170
- return { newErrorValue: formLevelError, newSource: "form" };
1171
- }
1172
- return { newErrorValue: void 0, newSource: void 0 };
1173
- };
1174
- function mergeOpts(originalOpts, overrides) {
1175
- if (originalOpts === void 0 || originalOpts === null) {
1176
- return overrides;
1177
- }
1178
- return { ...originalOpts, ...overrides };
1179
- }
1180
- var IDX = 256;
1181
- var HEX = [];
1182
- var BUFFER;
1183
- while (IDX--) {
1184
- HEX[IDX] = (IDX + 256).toString(16).substring(1);
1185
- }
1186
- function uuid() {
1187
- let i = 0;
1188
- let num;
1189
- let out = "";
1190
- if (!BUFFER || IDX + 16 > 256) {
1191
- BUFFER = new Array(256);
1192
- i = 256;
1193
- while (i--) {
1194
- BUFFER[i] = 256 * Math.random() | 0;
1195
- }
1196
- i = 0;
1197
- IDX = 0;
1198
- }
1199
- for (; i < 16; i++) {
1200
- num = BUFFER[IDX + i];
1201
- if (i === 6) out += HEX[num & 15 | 64];
1202
- else if (i === 8) out += HEX[num & 63 | 128];
1203
- else out += HEX[num];
1204
- if (i & 1 && i > 1 && i < 11) out += "-";
1205
- }
1206
- IDX++;
1207
- return out;
1208
- }
1209
- var throttleFormState = liteThrottle(
1210
- (form) => formEventClient.emit("form-state", {
1211
- id: form.formId,
1212
- state: form.store.state
1213
- }),
1214
- {
1215
- wait: 300
1216
- }
1217
- );
1218
- function deepCopy(obj) {
1219
- if (obj === null || typeof obj !== "object") {
1220
- return obj;
1221
- }
1222
- if (obj instanceof Date) {
1223
- return new Date(obj.getTime());
1224
- }
1225
- if (Array.isArray(obj)) {
1226
- const arrCopy = [];
1227
- for (let i = 0; i < obj.length; i++) {
1228
- arrCopy[i] = deepCopy(obj[i]);
1229
- }
1230
- return arrCopy;
1231
- }
1232
- if (obj instanceof Map) {
1233
- const mapCopy = /* @__PURE__ */ new Map();
1234
- obj.forEach((value, key) => {
1235
- mapCopy.set(key, deepCopy(value));
1236
- });
1237
- return mapCopy;
1238
- }
1239
- if (obj instanceof Set) {
1240
- const setCopy = /* @__PURE__ */ new Set();
1241
- obj.forEach((value) => {
1242
- setCopy.add(deepCopy(value));
1243
- });
1244
- return setCopy;
1245
- }
1246
- const copy = {};
1247
- for (const key in obj) {
1248
- if (Object.prototype.hasOwnProperty.call(obj, key)) {
1249
- copy[key] = deepCopy(obj[key]);
1250
- }
1251
- }
1252
- return copy;
1253
- }
1254
- function isFieldInGroup(groupName, fieldName) {
1255
- return fieldName === groupName || fieldName.startsWith(`${groupName}.`) || fieldName.startsWith(`${groupName}[`);
1256
- }
1257
-
1258
- // ../../node_modules/.pnpm/@tanstack+form-core@1.33.0/node_modules/@tanstack/form-core/dist/esm/ValidationLogic.js
1259
- var revalidateLogic = ({
1260
- mode = "submit",
1261
- modeAfterSubmission = "change"
1262
- } = {}) => (props) => {
1263
- const validatorNames = Object.keys(props.validators ?? {});
1264
- if (validatorNames.length === 0) {
1265
- return props.runValidation({
1266
- validators: [],
1267
- form: props.form
1268
- });
1269
- }
1270
- const dynamicValidator = {
1271
- fn: props.event.async ? props.validators["onDynamicAsync"] : props.validators["onDynamic"],
1272
- cause: "dynamic"
1273
- };
1274
- const validatorsToAdd = [];
1275
- const submissionAttempts = props.group ? props.group.state.meta.submissionAttempts : props.form.state.submissionAttempts;
1276
- const modeToWatch = submissionAttempts === 0 ? mode : modeAfterSubmission;
1277
- if ([modeToWatch, "submit"].includes(props.event.type)) {
1278
- validatorsToAdd.push(dynamicValidator);
1279
- }
1280
- let defaultValidators = [];
1281
- defaultValidationLogic({
1282
- ...props,
1283
- runValidation: (vProps) => {
1284
- defaultValidators = vProps.validators;
1285
- }
1286
- });
1287
- if (validatorsToAdd.length === 0) {
1288
- return props.runValidation({
1289
- validators: defaultValidators,
1290
- form: props.form
1291
- });
1292
- }
1293
- return props.runValidation({
1294
- validators: [...defaultValidators, ...validatorsToAdd],
1295
- form: props.form
1296
- });
1297
- };
1298
- var defaultValidationLogic = (props) => {
1299
- if (!props.validators) {
1300
- return props.runValidation({
1301
- validators: [],
1302
- form: props.form
1303
- });
1304
- }
1305
- const isAsync = props.event.async;
1306
- const onMountValidator = isAsync ? void 0 : { fn: props.validators.onMount, cause: "mount" };
1307
- const onChangeValidator = {
1308
- fn: isAsync ? props.validators.onChangeAsync : props.validators.onChange,
1309
- cause: "change"
1310
- };
1311
- const onBlurValidator = {
1312
- fn: isAsync ? props.validators.onBlurAsync : props.validators.onBlur,
1313
- cause: "blur"
1314
- };
1315
- const onSubmitValidator = {
1316
- fn: isAsync ? props.validators.onSubmitAsync : props.validators.onSubmit,
1317
- cause: "submit"
1318
- };
1319
- const onServerValidator = isAsync ? void 0 : { fn: () => void 0, cause: "server" };
1320
- switch (props.event.type) {
1321
- case "mount": {
1322
- return props.runValidation({
1323
- validators: [onMountValidator],
1324
- form: props.form
1325
- });
1326
- }
1327
- case "submit": {
1328
- return props.runValidation({
1329
- validators: [
1330
- onChangeValidator,
1331
- onBlurValidator,
1332
- onSubmitValidator,
1333
- onServerValidator
1334
- ],
1335
- form: props.form
1336
- });
1337
- }
1338
- case "server": {
1339
- return props.runValidation({
1340
- validators: [],
1341
- form: props.form
1342
- });
1343
- }
1344
- case "blur": {
1345
- return props.runValidation({
1346
- validators: [onBlurValidator, onServerValidator],
1347
- form: props.form
1348
- });
1349
- }
1350
- case "change": {
1351
- return props.runValidation({
1352
- validators: [onChangeValidator, onServerValidator],
1353
- form: props.form
1354
- });
1355
- }
1356
- default: {
1357
- throw new Error(`Unknown validation event type: ${props.event.type}`);
1358
- }
1359
- }
1360
- };
1361
-
1362
- // ../../node_modules/.pnpm/@tanstack+form-core@1.33.0/node_modules/@tanstack/form-core/dist/esm/standardSchemaValidator.js
1363
- function prefixSchemaToErrors(issues, formValue) {
1364
- const schema = /* @__PURE__ */ new Map();
1365
- for (const issue of issues) {
1366
- const issuePath = issue.path ?? [];
1367
- let currentFormValue = formValue;
1368
- let path = "";
1369
- for (let i = 0; i < issuePath.length; i++) {
1370
- const pathSegment = issuePath[i];
1371
- if (pathSegment === void 0) continue;
1372
- const segment = typeof pathSegment === "object" ? pathSegment.key : pathSegment;
1373
- const segmentAsNumber = Number(segment);
1374
- if (Array.isArray(currentFormValue) && !Number.isNaN(segmentAsNumber)) {
1375
- path += `[${segmentAsNumber}]`;
1376
- } else {
1377
- path += (i > 0 ? "." : "") + String(segment);
1378
- }
1379
- if (typeof currentFormValue === "object" && currentFormValue !== null) {
1380
- currentFormValue = currentFormValue[segment];
1381
- } else {
1382
- currentFormValue = void 0;
1383
- }
1384
- }
1385
- schema.set(path, (schema.get(path) ?? []).concat(issue));
1386
- }
1387
- return Object.fromEntries(schema);
1388
- }
1389
- var transformFormIssues = (issues, formValue) => {
1390
- const schemaErrors = prefixSchemaToErrors(issues, formValue);
1391
- return {
1392
- form: schemaErrors,
1393
- fields: schemaErrors
1394
- };
1395
- };
1396
- var standardSchemaValidators = {
1397
- validate({
1398
- value,
1399
- validationSource
1400
- }, schema) {
1401
- const result = schema["~standard"].validate(value);
1402
- if (result instanceof Promise) {
1403
- throw new Error("async function passed to sync validator");
1404
- }
1405
- if (!result.issues) return;
1406
- if (validationSource === "field") {
1407
- return result.issues;
1408
- }
1409
- return transformFormIssues(result.issues, value);
1410
- },
1411
- async validateAsync({
1412
- value,
1413
- validationSource
1414
- }, schema) {
1415
- const result = await schema["~standard"].validate(value);
1416
- if (!result.issues) return;
1417
- if (validationSource === "field") {
1418
- return result.issues;
1419
- }
1420
- return transformFormIssues(result.issues, value);
1421
- }
1422
- };
1423
- var isStandardSchemaValidator = (validator) => !!validator && "~standard" in validator;
1424
-
1425
- // ../../node_modules/.pnpm/@tanstack+form-core@1.33.0/node_modules/@tanstack/form-core/dist/esm/metaHelper.js
1426
- var defaultFieldMeta = {
1427
- isValidating: false,
1428
- isTouched: false,
1429
- isBlurred: false,
1430
- isDirty: false,
1431
- isPristine: true,
1432
- isValid: true,
1433
- isDefaultValue: true,
1434
- errors: [],
1435
- errorMap: {},
1436
- errorSourceMap: {},
1437
- _arrayVersion: 0
1438
- };
1439
- function metaHelper(formApi) {
1440
- function bumpArrayVersion(field) {
1441
- const currentMeta = formApi.getFieldMeta(field) ?? defaultFieldMeta;
1442
- formApi.setFieldMeta(field, {
1443
- ...currentMeta,
1444
- _arrayVersion: (currentMeta._arrayVersion || 0) + 1
1445
- });
1446
- }
1447
- function handleArrayMove(field, fromIndex, toIndex) {
1448
- bumpArrayVersion(field);
1449
- const affectedFields = getAffectedFields(field, fromIndex, "move", toIndex);
1450
- const startIndex = Math.min(fromIndex, toIndex);
1451
- const endIndex = Math.max(fromIndex, toIndex);
1452
- for (let i = startIndex; i <= endIndex; i++) {
1453
- affectedFields.push(getFieldPath(field, i));
1454
- }
1455
- const fromFields = Object.keys(formApi.fieldInfo).reduce(
1456
- (fieldMap, fieldKey) => {
1457
- if (fieldKey.startsWith(getFieldPath(field, fromIndex))) {
1458
- fieldMap.set(
1459
- fieldKey,
1460
- formApi.getFieldMeta(fieldKey)
1461
- );
1462
- }
1463
- return fieldMap;
1464
- },
1465
- /* @__PURE__ */ new Map()
1466
- );
1467
- shiftMeta(affectedFields, fromIndex < toIndex ? "up" : "down");
1468
- Object.keys(formApi.fieldInfo).filter((fieldKey) => fieldKey.startsWith(getFieldPath(field, toIndex))).forEach((fieldKey) => {
1469
- const fromKey = fieldKey.replace(
1470
- getFieldPath(field, toIndex),
1471
- getFieldPath(field, fromIndex)
1472
- );
1473
- const fromMeta = fromFields.get(fromKey);
1474
- if (fromMeta) {
1475
- formApi.setFieldMeta(fieldKey, fromMeta);
1476
- }
1477
- });
1478
- }
1479
- function handleArrayRemove(field, index) {
1480
- bumpArrayVersion(field);
1481
- const affectedFields = getAffectedFields(field, index, "remove");
1482
- shiftMeta(affectedFields, "up");
1483
- }
1484
- function handleArraySwap(field, index, secondIndex) {
1485
- bumpArrayVersion(field);
1486
- const affectedFields = getAffectedFields(field, index, "swap", secondIndex);
1487
- affectedFields.forEach((fieldKey) => {
1488
- if (!fieldKey.toString().startsWith(getFieldPath(field, index))) {
1489
- return;
1490
- }
1491
- const swappedKey = fieldKey.toString().replace(
1492
- getFieldPath(field, index),
1493
- getFieldPath(field, secondIndex)
1494
- );
1495
- const [meta1, meta2] = [
1496
- formApi.getFieldMeta(fieldKey),
1497
- formApi.getFieldMeta(swappedKey)
1498
- ];
1499
- if (meta1) formApi.setFieldMeta(swappedKey, meta1);
1500
- if (meta2) formApi.setFieldMeta(fieldKey, meta2);
1501
- });
1502
- }
1503
- function handleArrayInsert(field, insertIndex) {
1504
- bumpArrayVersion(field);
1505
- const affectedFields = getAffectedFields(field, insertIndex, "insert");
1506
- shiftMeta(affectedFields, "down");
1507
- affectedFields.forEach((fieldKey) => {
1508
- if (fieldKey.toString().startsWith(getFieldPath(field, insertIndex))) {
1509
- formApi.setFieldMeta(fieldKey, getEmptyFieldMeta());
1510
- }
1511
- });
1512
- }
1513
- function getFieldPath(field, index) {
1514
- return `${field}[${index}]`;
1515
- }
1516
- function getAffectedFields(field, index, mode, secondIndex) {
1517
- const affectedFieldKeys = [getFieldPath(field, index)];
1518
- switch (mode) {
1519
- case "swap":
1520
- affectedFieldKeys.push(getFieldPath(field, secondIndex));
1521
- break;
1522
- case "move": {
1523
- const [startIndex, endIndex] = [
1524
- Math.min(index, secondIndex),
1525
- Math.max(index, secondIndex)
1526
- ];
1527
- for (let i = startIndex; i <= endIndex; i++) {
1528
- affectedFieldKeys.push(getFieldPath(field, i));
1529
- }
1530
- break;
1531
- }
1532
- default: {
1533
- const currentValue = formApi.getFieldValue(field);
1534
- const fieldItems = Array.isArray(currentValue) ? currentValue.length : 0;
1535
- for (let i = index + 1; i < fieldItems; i++) {
1536
- affectedFieldKeys.push(getFieldPath(field, i));
1537
- }
1538
- break;
1539
- }
1540
- }
1541
- return Object.keys(formApi.fieldInfo).filter(
1542
- (fieldKey) => affectedFieldKeys.some((key) => fieldKey.startsWith(key))
1543
- );
1544
- }
1545
- function updateIndex(fieldKey, direction) {
1546
- return fieldKey.replace(/\[(\d+)\]/, (_, num) => {
1547
- const currIndex = parseInt(num, 10);
1548
- const newIndex = direction === "up" ? currIndex + 1 : Math.max(0, currIndex - 1);
1549
- return `[${newIndex}]`;
1550
- });
1551
- }
1552
- function shiftMeta(fields, direction) {
1553
- const sortedFields = direction === "up" ? fields : [...fields].reverse();
1554
- sortedFields.forEach((fieldKey) => {
1555
- const nextFieldKey = updateIndex(fieldKey.toString(), direction);
1556
- const nextFieldMeta = formApi.getFieldMeta(nextFieldKey);
1557
- if (nextFieldMeta) {
1558
- formApi.setFieldMeta(fieldKey, nextFieldMeta);
1559
- } else {
1560
- formApi.setFieldMeta(fieldKey, getEmptyFieldMeta());
1561
- }
1562
- });
1563
- }
1564
- const getEmptyFieldMeta = () => defaultFieldMeta;
1565
- return {
1566
- bumpArrayVersion,
1567
- handleArrayMove,
1568
- handleArrayRemove,
1569
- handleArraySwap,
1570
- handleArrayInsert
1571
- };
1572
- }
1573
-
1574
- // ../../node_modules/.pnpm/@tanstack+form-core@1.33.0/node_modules/@tanstack/form-core/dist/esm/FormApi.js
1575
- function getDefaultFormState(defaultState) {
1576
- return {
1577
- values: defaultState.values ?? {},
1578
- errorMap: defaultState.errorMap ?? {},
1579
- fieldMetaBase: defaultState.fieldMetaBase ?? {},
1580
- formGroupStateBase: defaultState.formGroupStateBase ?? {},
1581
- isSubmitted: defaultState.isSubmitted ?? false,
1582
- isSubmitting: defaultState.isSubmitting ?? false,
1583
- isValidating: defaultState.isValidating ?? false,
1584
- submissionAttempts: defaultState.submissionAttempts ?? 0,
1585
- isSubmitSuccessful: defaultState.isSubmitSuccessful ?? false,
1586
- validationMetaMap: defaultState.validationMetaMap ?? {
1587
- onChange: void 0,
1588
- onBlur: void 0,
1589
- onSubmit: void 0,
1590
- onMount: void 0,
1591
- onServer: void 0,
1592
- onDynamic: void 0
1593
- }
1594
- };
1595
- }
1596
- var FormApi = class {
1597
- /**
1598
- * Constructs a new `FormApi` instance with the given form options.
1599
- */
1600
- constructor(opts) {
1601
- this.options = {};
1602
- this.fieldInfo = {};
1603
- this.formGroupApis = /* @__PURE__ */ new Set();
1604
- this.mount = () => {
1605
- const cleanupDevtoolBroadcast = this.store.subscribe(() => {
1606
- throttleFormState(this);
1607
- });
1608
- const cleanupFormStateListener = formEventClient.on(
1609
- "request-form-state",
1610
- (e) => {
1611
- if (e.payload.id === this._formId) {
1612
- formEventClient.emit("form-api", {
1613
- id: this._formId,
1614
- state: this.store.state,
1615
- options: this.options
1616
- });
1617
- }
1618
- }
1619
- );
1620
- const cleanupFormResetListener = formEventClient.on(
1621
- "request-form-reset",
1622
- (e) => {
1623
- if (e.payload.id === this._formId) {
1624
- this.reset();
1625
- }
1626
- }
1627
- );
1628
- const cleanupFormForceSubmitListener = formEventClient.on(
1629
- "request-form-force-submit",
1630
- (e) => {
1631
- if (e.payload.id === this._formId) {
1632
- this._devtoolsSubmissionOverride = true;
1633
- this.handleSubmit();
1634
- this._devtoolsSubmissionOverride = false;
1635
- }
1636
- }
1637
- );
1638
- const cleanup = () => {
1639
- cleanupFormForceSubmitListener();
1640
- cleanupFormResetListener();
1641
- cleanupFormStateListener();
1642
- cleanupDevtoolBroadcast.unsubscribe();
1643
- formEventClient.emit("form-unmounted", {
1644
- id: this._formId
1645
- });
1646
- };
1647
- this.options.listeners?.onMount?.({ formApi: this });
1648
- const { onMount } = this.options.validators || {};
1649
- formEventClient.emit("form-api", {
1650
- id: this._formId,
1651
- state: this.store.state,
1652
- options: this.options
1653
- });
1654
- if (!onMount) return cleanup;
1655
- this.validateSync("mount");
1656
- return cleanup;
1657
- };
1658
- this.update = (options) => {
1659
- if (!options) return;
1660
- const oldOptions = this.options;
1661
- this.options = options;
1662
- const shouldUpdateValues = options.defaultValues && !evaluate(options.defaultValues, oldOptions.defaultValues) && !this.state.isTouched;
1663
- const shouldUpdateState = !evaluate(options.defaultState, oldOptions.defaultState) && !this.state.isTouched;
1664
- if (!shouldUpdateValues && !shouldUpdateState) return;
1665
- batch(() => {
1666
- this.baseStore.setState(
1667
- () => getDefaultFormState(
1668
- Object.assign(
1669
- {},
1670
- this.state,
1671
- shouldUpdateState ? options.defaultState : {},
1672
- shouldUpdateValues ? {
1673
- values: options.defaultValues
1674
- } : {}
1675
- )
1676
- )
1677
- );
1678
- });
1679
- if (shouldUpdateValues) {
1680
- const helper = metaHelper(this);
1681
- for (const fieldKey of Object.keys(
1682
- this.fieldInfo
1683
- )) {
1684
- if (Array.isArray(this.getFieldValue(fieldKey))) {
1685
- helper.bumpArrayVersion(fieldKey);
1686
- }
1687
- }
1688
- }
1689
- formEventClient.emit("form-api", {
1690
- id: this._formId,
1691
- state: this.store.state,
1692
- options: this.options
1693
- });
1694
- };
1695
- this.reset = (values, opts2) => {
1696
- const { fieldMeta: currentFieldMeta } = this.state;
1697
- const fieldMetaBase = this.resetFieldMeta(currentFieldMeta);
1698
- if (values && !opts2?.keepDefaultValues) {
1699
- this.options = {
1700
- ...this.options,
1701
- defaultValues: values
1702
- };
1703
- }
1704
- this.baseStore.setState(() => {
1705
- let nextValues = values ?? this.options.defaultValues ?? this.options.defaultState?.values;
1706
- if (!values) {
1707
- Object.values(this.fieldInfo).forEach(
1708
- (fieldInfo) => {
1709
- if (fieldInfo.instance && fieldInfo.instance.options.defaultValue !== void 0) {
1710
- nextValues = setBy(
1711
- nextValues,
1712
- fieldInfo.instance.name,
1713
- fieldInfo.instance.options.defaultValue
1714
- );
1715
- }
1716
- }
1717
- );
1718
- }
1719
- return getDefaultFormState({
1720
- ...this.options.defaultState,
1721
- values: nextValues,
1722
- fieldMetaBase
1723
- });
1724
- });
1725
- };
1726
- this.validateAllFields = async (cause) => {
1727
- const fieldValidationPromises = [];
1728
- batch(() => {
1729
- void Object.values(this.fieldInfo).forEach(
1730
- (field) => {
1731
- if (!field.instance) return;
1732
- const fieldInstance = field.instance;
1733
- fieldValidationPromises.push(
1734
- // Remember, `validate` is either a sync operation or a promise
1735
- Promise.resolve().then(
1736
- () => fieldInstance.validate(cause, {
1737
- skipFormValidation: true,
1738
- skipGroupValidation: true
1739
- })
1740
- )
1741
- );
1742
- if (!field.instance.store.state.meta.isTouched) {
1743
- field.instance.setMeta((prev) => ({ ...prev, isTouched: true }));
1744
- }
1745
- }
1746
- );
1747
- });
1748
- const fieldErrorMapMap = await Promise.all(fieldValidationPromises);
1749
- return fieldErrorMapMap.flat();
1750
- };
1751
- this.validateArrayFieldsStartingFrom = async (field, index, cause) => {
1752
- const currentValue = this.getFieldValue(field);
1753
- const lastIndex = Array.isArray(currentValue) ? Math.max(currentValue.length - 1, 0) : null;
1754
- const fieldKeysToValidate = [`${field}[${index}]`];
1755
- for (let i = index + 1; i <= (lastIndex ?? 0); i++) {
1756
- fieldKeysToValidate.push(`${field}[${i}]`);
1757
- }
1758
- const fieldsToValidate = Object.keys(this.fieldInfo).filter(
1759
- (fieldKey) => fieldKeysToValidate.some((key) => fieldKey.startsWith(key))
1760
- );
1761
- const fieldValidationPromises = [];
1762
- batch(() => {
1763
- fieldsToValidate.forEach((nestedField) => {
1764
- fieldValidationPromises.push(
1765
- Promise.resolve().then(() => this.validateField(nestedField, cause))
1766
- );
1767
- });
1768
- });
1769
- const fieldErrorMapMap = await Promise.all(fieldValidationPromises);
1770
- return fieldErrorMapMap.flat();
1771
- };
1772
- this.validateField = (field, cause) => {
1773
- const fieldInstance = this.fieldInfo[field]?.instance;
1774
- if (!fieldInstance) {
1775
- const { hasErrored } = this.validateSync(cause);
1776
- if (hasErrored && !this.options.asyncAlways) {
1777
- return this.getFieldMeta(field)?.errors ?? [];
1778
- }
1779
- return this.validateAsync(cause).then(() => {
1780
- return this.getFieldMeta(field)?.errors ?? [];
1781
- });
1782
- }
1783
- if (!fieldInstance.store.state.meta.isTouched) {
1784
- fieldInstance.setMeta((prev) => ({ ...prev, isTouched: true }));
1785
- }
1786
- return fieldInstance.validate(cause);
1787
- };
1788
- this.validateSync = (cause, validateOpts) => {
1789
- const validates = getSyncValidatorArray(cause, {
1790
- ...this.options,
1791
- form: this,
1792
- group: validateOpts?.group,
1793
- validationLogic: this.options.validationLogic || defaultValidationLogic
1794
- });
1795
- let hasErrored = false;
1796
- const currentValidationErrorMap = {};
1797
- batch(() => {
1798
- for (const validateObj of validates) {
1799
- if (!validateObj.validate) continue;
1800
- const rawError = this.runValidator({
1801
- validate: validateObj.validate,
1802
- value: {
1803
- value: this.state.values,
1804
- formApi: this,
1805
- validationSource: "form"
1806
- },
1807
- type: "validate"
1808
- });
1809
- const { formError, fieldErrors } = normalizeError(rawError);
1810
- const errorMapKey = getErrorMapKey(validateObj.cause);
1811
- let allFieldsToProcess = /* @__PURE__ */ new Set([
1812
- ...Object.keys(this.state.fieldMeta),
1813
- ...Object.keys(fieldErrors || {})
1814
- ]);
1815
- if (validateOpts?.filterFieldNames) {
1816
- allFieldsToProcess = new Set(
1817
- [...allFieldsToProcess].filter(validateOpts.filterFieldNames)
1818
- );
1819
- }
1820
- for (const field of allFieldsToProcess) {
1821
- if (this.baseStore.state.fieldMetaBase[field] === void 0 && !fieldErrors?.[field]) {
1822
- continue;
1823
- }
1824
- const fieldMeta = this.getFieldMeta(field) ?? defaultFieldMeta;
1825
- const {
1826
- errorMap: currentErrorMap,
1827
- errorSourceMap: currentErrorMapSource
1828
- } = fieldMeta;
1829
- const newFormValidatorError = fieldErrors?.[field];
1830
- const { newErrorValue, newSource } = determineFormLevelErrorSourceAndValue({
1831
- newFormValidatorError,
1832
- isPreviousErrorFromFormValidator: (
1833
- // These conditional checks are required, otherwise we get runtime errors.
1834
- // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
1835
- currentErrorMapSource?.[errorMapKey] === "form"
1836
- ),
1837
- // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
1838
- previousErrorValue: currentErrorMap?.[errorMapKey]
1839
- });
1840
- if (newSource === "form") {
1841
- currentValidationErrorMap[field] = {
1842
- ...currentValidationErrorMap[field],
1843
- [errorMapKey]: newFormValidatorError
1844
- };
1845
- }
1846
- if (currentErrorMap?.[errorMapKey] !== newErrorValue) {
1847
- this.setFieldMeta(field, (prev = defaultFieldMeta) => ({
1848
- ...prev,
1849
- errorMap: {
1850
- ...prev.errorMap,
1851
- [errorMapKey]: newErrorValue
1852
- },
1853
- errorSourceMap: {
1854
- ...prev.errorSourceMap,
1855
- [errorMapKey]: newSource
1856
- }
1857
- }));
1858
- }
1859
- }
1860
- if (!validateOpts?.dontUpdateFormErrorMap) {
1861
- if (this.state.errorMap?.[errorMapKey] !== formError) {
1862
- this.baseStore.setState((prev) => ({
1863
- ...prev,
1864
- errorMap: {
1865
- ...prev.errorMap,
1866
- [errorMapKey]: formError
1867
- }
1868
- }));
1869
- }
1870
- }
1871
- if (formError || fieldErrors) {
1872
- hasErrored = true;
1873
- }
1874
- }
1875
- if (validateOpts?.dontUpdateFormErrorMap) {
1876
- return;
1877
- }
1878
- const submitErrKey = getErrorMapKey("submit");
1879
- if (
1880
- // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
1881
- this.state.errorMap?.[submitErrKey] && cause !== "submit" && !hasErrored
1882
- ) {
1883
- this.baseStore.setState((prev) => ({
1884
- ...prev,
1885
- errorMap: {
1886
- ...prev.errorMap,
1887
- [submitErrKey]: void 0
1888
- }
1889
- }));
1890
- }
1891
- const serverErrKey = getErrorMapKey("server");
1892
- if (
1893
- // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
1894
- this.state.errorMap?.[serverErrKey] && cause !== "server" && !hasErrored
1895
- ) {
1896
- this.baseStore.setState((prev) => ({
1897
- ...prev,
1898
- errorMap: {
1899
- ...prev.errorMap,
1900
- [serverErrKey]: void 0
1901
- }
1902
- }));
1903
- }
1904
- });
1905
- return { hasErrored, fieldsErrorMap: currentValidationErrorMap };
1906
- };
1907
- this.validateAsync = async (cause, validateOpts) => {
1908
- const validates = getAsyncValidatorArray(cause, {
1909
- ...this.options,
1910
- form: this,
1911
- group: validateOpts?.group,
1912
- validationLogic: this.options.validationLogic || defaultValidationLogic
1913
- });
1914
- if (!this.state.isFormValidating) {
1915
- this.baseStore.setState((prev) => ({ ...prev, isFormValidating: true }));
1916
- }
1917
- const promises = [];
1918
- let fieldErrorsFromFormValidators;
1919
- for (const validateObj of validates) {
1920
- if (!validateObj.validate) continue;
1921
- const key = getErrorMapKey(validateObj.cause);
1922
- const fieldValidatorMeta = this.state.validationMetaMap[key];
1923
- fieldValidatorMeta?.lastAbortController.abort();
1924
- const controller = new AbortController();
1925
- this.state.validationMetaMap[key] = {
1926
- lastAbortController: controller
1927
- };
1928
- promises.push(
1929
- new Promise(async (resolve) => {
1930
- let rawError;
1931
- try {
1932
- rawError = await new Promise((rawResolve, rawReject) => {
1933
- setTimeout(async () => {
1934
- if (controller.signal.aborted) return rawResolve(void 0);
1935
- try {
1936
- rawResolve(
1937
- await this.runValidator({
1938
- validate: validateObj.validate,
1939
- value: {
1940
- value: this.state.values,
1941
- formApi: this,
1942
- validationSource: "form",
1943
- signal: controller.signal
1944
- },
1945
- type: "validateAsync"
1946
- })
1947
- );
1948
- } catch (e) {
1949
- rawReject(e);
1950
- }
1951
- }, validateObj.debounceMs);
1952
- });
1953
- } catch (e) {
1954
- rawError = e;
1955
- }
1956
- const { formError, fieldErrors: fieldErrorsFromNormalizeError } = normalizeError(rawError);
1957
- if (fieldErrorsFromNormalizeError) {
1958
- fieldErrorsFromFormValidators = fieldErrorsFromFormValidators ? {
1959
- ...fieldErrorsFromFormValidators,
1960
- ...fieldErrorsFromNormalizeError
1961
- } : fieldErrorsFromNormalizeError;
1962
- }
1963
- const errorMapKey = getErrorMapKey(validateObj.cause);
1964
- let fields = Object.keys(this.state.fieldMeta);
1965
- if (validateOpts?.filterFieldNames) {
1966
- fields = fields.filter(validateOpts.filterFieldNames);
1967
- }
1968
- for (const field of fields) {
1969
- if (this.baseStore.state.fieldMetaBase[field] === void 0) {
1970
- continue;
1971
- }
1972
- const fieldMeta = this.getFieldMeta(field);
1973
- if (!fieldMeta) continue;
1974
- const {
1975
- errorMap: currentErrorMap,
1976
- errorSourceMap: currentErrorMapSource
1977
- } = fieldMeta;
1978
- const newFormValidatorError = fieldErrorsFromFormValidators?.[field];
1979
- const { newErrorValue, newSource } = determineFormLevelErrorSourceAndValue({
1980
- newFormValidatorError,
1981
- isPreviousErrorFromFormValidator: (
1982
- // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
1983
- currentErrorMapSource?.[errorMapKey] === "form"
1984
- ),
1985
- // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
1986
- previousErrorValue: currentErrorMap?.[errorMapKey]
1987
- });
1988
- if (currentErrorMap?.[errorMapKey] !== newErrorValue) {
1989
- this.setFieldMeta(field, (prev) => ({
1990
- ...prev,
1991
- errorMap: {
1992
- ...prev.errorMap,
1993
- [errorMapKey]: newErrorValue
1994
- },
1995
- errorSourceMap: {
1996
- ...prev.errorSourceMap,
1997
- [errorMapKey]: newSource
1998
- }
1999
- }));
2000
- }
2001
- }
2002
- if (!validateOpts?.dontUpdateFormErrorMap) {
2003
- this.baseStore.setState((prev) => ({
2004
- ...prev,
2005
- errorMap: {
2006
- ...prev.errorMap,
2007
- [errorMapKey]: formError
2008
- }
2009
- }));
2010
- }
2011
- resolve(
2012
- fieldErrorsFromFormValidators ? { fieldErrors: fieldErrorsFromFormValidators, errorMapKey } : void 0
2013
- );
2014
- })
2015
- );
2016
- }
2017
- let results = [];
2018
- const fieldsErrorMap = {};
2019
- if (promises.length) {
2020
- results = await Promise.all(promises);
2021
- for (const fieldValidationResult of results) {
2022
- if (fieldValidationResult?.fieldErrors) {
2023
- const { errorMapKey } = fieldValidationResult;
2024
- for (const [field, fieldError] of Object.entries(
2025
- fieldValidationResult.fieldErrors
2026
- )) {
2027
- const oldErrorMap = fieldsErrorMap[field] || {};
2028
- const newErrorMap = {
2029
- ...oldErrorMap,
2030
- [errorMapKey]: fieldError
2031
- };
2032
- fieldsErrorMap[field] = newErrorMap;
2033
- }
2034
- }
2035
- }
2036
- }
2037
- this.baseStore.setState((prev) => ({
2038
- ...prev,
2039
- isFormValidating: false
2040
- }));
2041
- return fieldsErrorMap;
2042
- };
2043
- this.validate = (cause, validateOpts) => {
2044
- const { hasErrored, fieldsErrorMap } = this.validateSync(
2045
- cause,
2046
- validateOpts
2047
- );
2048
- if (hasErrored && !this.options.asyncAlways) {
2049
- return fieldsErrorMap;
2050
- }
2051
- return this.validateAsync(cause, validateOpts);
2052
- };
2053
- this._handleSubmit = async (submitMeta) => {
2054
- this.baseStore.setState((old) => ({
2055
- ...old,
2056
- // Submission attempts mark the form as not submitted
2057
- isSubmitted: false,
2058
- // Count submission attempts
2059
- submissionAttempts: old.submissionAttempts + 1,
2060
- isSubmitSuccessful: false
2061
- // Reset isSubmitSuccessful at the start of submission
2062
- }));
2063
- batch(() => {
2064
- void Object.values(this.fieldInfo).forEach(
2065
- (field) => {
2066
- if (!field.instance) return;
2067
- if (!field.instance.store.state.meta.isTouched) {
2068
- field.instance.setMeta((prev) => ({ ...prev, isTouched: true }));
2069
- }
2070
- }
2071
- );
2072
- });
2073
- const submitMetaArg = submitMeta ?? this.options.onSubmitMeta;
2074
- if (!this.state.canSubmit && !this._devtoolsSubmissionOverride) {
2075
- this.options.onSubmitInvalid?.({
2076
- value: this.state.values,
2077
- formApi: this,
2078
- meta: submitMetaArg
2079
- });
2080
- return;
2081
- }
2082
- this.baseStore.setState((d) => ({ ...d, isSubmitting: true }));
2083
- const done = () => {
2084
- this.baseStore.setState((prev) => ({ ...prev, isSubmitting: false }));
2085
- };
2086
- await this.validateAllFields("submit");
2087
- if (!this.state.isFieldsValid) {
2088
- done();
2089
- this.options.onSubmitInvalid?.({
2090
- value: this.state.values,
2091
- formApi: this,
2092
- meta: submitMetaArg
2093
- });
2094
- formEventClient.emit("form-submission", {
2095
- id: this._formId,
2096
- submissionAttempt: this.state.submissionAttempts,
2097
- successful: false,
2098
- stage: "validateAllFields",
2099
- errors: Object.values(this.state.fieldMeta).map((meta) => meta.errors).flat()
2100
- });
2101
- return;
2102
- }
2103
- await this.validate("submit");
2104
- if (!this.state.isValid) {
2105
- done();
2106
- this.options.onSubmitInvalid?.({
2107
- value: this.state.values,
2108
- formApi: this,
2109
- meta: submitMetaArg
2110
- });
2111
- formEventClient.emit("form-submission", {
2112
- id: this._formId,
2113
- submissionAttempt: this.state.submissionAttempts,
2114
- successful: false,
2115
- stage: "validate",
2116
- errors: this.state.errors
2117
- });
2118
- return;
2119
- }
2120
- batch(() => {
2121
- void Object.values(this.fieldInfo).forEach(
2122
- (field) => {
2123
- field.instance?.triggerOnSubmitListener();
2124
- }
2125
- );
2126
- });
2127
- this.options.listeners?.onSubmit?.({ formApi: this, meta: submitMetaArg });
2128
- try {
2129
- await this.options.onSubmit?.({
2130
- value: this.state.values,
2131
- formApi: this,
2132
- meta: submitMetaArg
2133
- });
2134
- batch(() => {
2135
- this.baseStore.setState((prev) => ({
2136
- ...prev,
2137
- isSubmitted: true,
2138
- isSubmitSuccessful: true
2139
- // Set isSubmitSuccessful to true on successful submission
2140
- }));
2141
- formEventClient.emit("form-submission", {
2142
- id: this._formId,
2143
- submissionAttempt: this.state.submissionAttempts,
2144
- successful: true
2145
- });
2146
- done();
2147
- });
2148
- } catch (err) {
2149
- this.baseStore.setState((prev) => ({
2150
- ...prev,
2151
- isSubmitSuccessful: false
2152
- // Ensure isSubmitSuccessful is false if an error occurs
2153
- }));
2154
- formEventClient.emit("form-submission", {
2155
- id: this._formId,
2156
- submissionAttempt: this.state.submissionAttempts,
2157
- successful: false,
2158
- stage: "inflight",
2159
- onError: err
2160
- });
2161
- done();
2162
- throw err;
2163
- }
2164
- };
2165
- this.getFieldValue = (field) => getBy(this.state.values, field);
2166
- this.getFieldMeta = (field) => {
2167
- return this.state.fieldMeta[field];
2168
- };
2169
- this.getFormGroupMeta = (name) => {
2170
- return this.formGroupMetaDerived.state[name];
2171
- };
2172
- this.getFieldInfo = (field) => {
2173
- return this.fieldInfo[field] ||= {
2174
- instance: null,
2175
- validationMetaMap: {
2176
- onChange: void 0,
2177
- onBlur: void 0,
2178
- onSubmit: void 0,
2179
- onMount: void 0,
2180
- onServer: void 0,
2181
- onDynamic: void 0
2182
- }
2183
- };
2184
- };
2185
- this.setFieldMeta = (field, updater) => {
2186
- this.baseStore.setState((prev) => {
2187
- return {
2188
- ...prev,
2189
- fieldMetaBase: {
2190
- ...prev.fieldMetaBase,
2191
- [field]: functionalUpdate(
2192
- updater,
2193
- prev.fieldMetaBase[field]
2194
- )
2195
- }
2196
- };
2197
- });
2198
- };
2199
- this.resetFieldMeta = (fieldMeta) => {
2200
- return Object.keys(fieldMeta).reduce(
2201
- (acc, key) => {
2202
- const fieldKey = key;
2203
- acc[fieldKey] = defaultFieldMeta;
2204
- return acc;
2205
- },
2206
- {}
2207
- );
2208
- };
2209
- this.setFieldValue = (field, updater, opts2) => {
2210
- const dontUpdateMeta = opts2?.dontUpdateMeta ?? false;
2211
- const dontRunListeners = opts2?.dontRunListeners ?? false;
2212
- const dontValidate = opts2?.dontValidate ?? false;
2213
- batch(() => {
2214
- if (!dontUpdateMeta) {
2215
- this.setFieldMeta(field, (prev) => ({
2216
- ...prev,
2217
- isTouched: true,
2218
- isDirty: true,
2219
- errorMap: {
2220
- // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
2221
- ...prev?.errorMap,
2222
- onMount: void 0
2223
- }
2224
- }));
2225
- }
2226
- this.baseStore.setState((prev) => {
2227
- return {
2228
- ...prev,
2229
- values: setBy(prev.values, field, updater)
2230
- };
2231
- });
2232
- });
2233
- if (!dontRunListeners) {
2234
- this.getFieldInfo(field).instance?.triggerOnChangeListener();
2235
- }
2236
- if (!dontValidate) {
2237
- this.validateField(field, "change");
2238
- }
2239
- };
2240
- this.deleteField = (field) => {
2241
- const subFieldsToDelete = Object.keys(this.fieldInfo).filter((f) => {
2242
- const fieldStr = field.toString();
2243
- return f !== fieldStr && f.startsWith(fieldStr);
2244
- });
2245
- const fieldsToDelete = [...subFieldsToDelete, field];
2246
- this.baseStore.setState((prev) => {
2247
- const newState = { ...prev };
2248
- fieldsToDelete.forEach((f) => {
2249
- newState.values = deleteBy(newState.values, f);
2250
- delete this.fieldInfo[f];
2251
- delete newState.fieldMetaBase[f];
2252
- });
2253
- return newState;
2254
- });
2255
- };
2256
- this.pushFieldValue = (field, value, options) => {
2257
- this.setFieldValue(
2258
- field,
2259
- (prev) => [...Array.isArray(prev) ? prev : [], value],
2260
- options
2261
- );
2262
- metaHelper(this).bumpArrayVersion(field);
2263
- };
2264
- this.insertFieldValue = async (field, index, value, options) => {
2265
- this.setFieldValue(
2266
- field,
2267
- (prev) => {
2268
- return [
2269
- ...prev.slice(0, index),
2270
- value,
2271
- ...prev.slice(index)
2272
- ];
2273
- },
2274
- mergeOpts(options, { dontValidate: true })
2275
- );
2276
- const dontValidate = options?.dontValidate ?? false;
2277
- if (!dontValidate) {
2278
- await this.validateField(field, "change");
2279
- }
2280
- metaHelper(this).handleArrayInsert(field, index);
2281
- if (!dontValidate) {
2282
- await this.validateArrayFieldsStartingFrom(field, index, "change");
2283
- }
2284
- };
2285
- this.replaceFieldValue = async (field, index, value, options) => {
2286
- this.setFieldValue(
2287
- field,
2288
- (prev) => {
2289
- return prev.map(
2290
- (d, i) => i === index ? value : d
2291
- );
2292
- },
2293
- mergeOpts(options, { dontValidate: true })
2294
- );
2295
- metaHelper(this).bumpArrayVersion(field);
2296
- const dontValidate = options?.dontValidate ?? false;
2297
- if (!dontValidate) {
2298
- await this.validateField(field, "change");
2299
- await this.validateArrayFieldsStartingFrom(field, index, "change");
2300
- }
2301
- };
2302
- this.removeFieldValue = async (field, index, options) => {
2303
- const fieldValue = this.getFieldValue(field);
2304
- const lastIndex = Array.isArray(fieldValue) ? Math.max(fieldValue.length - 1, 0) : null;
2305
- this.setFieldValue(
2306
- field,
2307
- (prev) => {
2308
- return prev.filter(
2309
- (_d, i) => i !== index
2310
- );
2311
- },
2312
- mergeOpts(options, { dontValidate: true })
2313
- );
2314
- metaHelper(this).handleArrayRemove(field, index);
2315
- if (lastIndex !== null) {
2316
- const start = `${field}[${lastIndex}]`;
2317
- this.deleteField(start);
2318
- }
2319
- const dontValidate = options?.dontValidate ?? false;
2320
- if (!dontValidate) {
2321
- await this.validateField(field, "change");
2322
- await this.validateArrayFieldsStartingFrom(field, index, "change");
2323
- }
2324
- };
2325
- this.swapFieldValues = (field, index1, index2, options) => {
2326
- this.setFieldValue(
2327
- field,
2328
- (prev) => {
2329
- const prev1 = prev[index1];
2330
- const prev2 = prev[index2];
2331
- return setBy(setBy(prev, `${index1}`, prev2), `${index2}`, prev1);
2332
- },
2333
- mergeOpts(options, { dontValidate: true })
2334
- );
2335
- metaHelper(this).handleArraySwap(field, index1, index2);
2336
- const dontValidate = options?.dontValidate ?? false;
2337
- if (!dontValidate) {
2338
- this.validateField(field, "change");
2339
- this.validateField(`${field}[${index1}]`, "change");
2340
- this.validateField(`${field}[${index2}]`, "change");
2341
- }
2342
- };
2343
- this.moveFieldValues = (field, index1, index2, options) => {
2344
- this.setFieldValue(
2345
- field,
2346
- (prev) => {
2347
- const next = [...prev];
2348
- next.splice(index2, 0, next.splice(index1, 1)[0]);
2349
- return next;
2350
- },
2351
- mergeOpts(options, { dontValidate: true })
2352
- );
2353
- metaHelper(this).handleArrayMove(field, index1, index2);
2354
- const dontValidate = options?.dontValidate ?? false;
2355
- if (!dontValidate) {
2356
- this.validateField(field, "change");
2357
- this.validateField(`${field}[${index1}]`, "change");
2358
- this.validateField(`${field}[${index2}]`, "change");
2359
- }
2360
- };
2361
- this.clearFieldValues = (field, options) => {
2362
- const fieldValue = this.getFieldValue(field);
2363
- const lastIndex = Array.isArray(fieldValue) ? Math.max(fieldValue.length - 1, 0) : null;
2364
- this.setFieldValue(
2365
- field,
2366
- [],
2367
- mergeOpts(options, { dontValidate: true })
2368
- );
2369
- metaHelper(this).bumpArrayVersion(field);
2370
- if (lastIndex !== null) {
2371
- for (let i = 0; i <= lastIndex; i++) {
2372
- const fieldKey = `${field}[${i}]`;
2373
- this.deleteField(fieldKey);
2374
- }
2375
- }
2376
- const dontValidate = options?.dontValidate ?? false;
2377
- if (!dontValidate) {
2378
- this.validateField(field, "change");
2379
- }
2380
- };
2381
- this.resetField = (field) => {
2382
- this.baseStore.setState((prev) => {
2383
- const fieldDefault = this.getFieldInfo(field).instance?.options.defaultValue;
2384
- const formDefault = getBy(this.options.defaultValues, field);
2385
- const targetValue = fieldDefault ?? formDefault;
2386
- return {
2387
- ...prev,
2388
- fieldMetaBase: {
2389
- ...prev.fieldMetaBase,
2390
- [field]: defaultFieldMeta
2391
- },
2392
- values: targetValue !== void 0 ? setBy(prev.values, field, targetValue) : prev.values
2393
- };
2394
- });
2395
- };
2396
- this.setErrorMap = (errorMap) => {
2397
- batch(() => {
2398
- Object.entries(errorMap).forEach(([key, value]) => {
2399
- const errorMapKey = key;
2400
- if (isGlobalFormValidationError(value)) {
2401
- const { formError, fieldErrors } = normalizeError(value);
2402
- for (const fieldName of Object.keys(
2403
- this.fieldInfo
2404
- )) {
2405
- const fieldMeta = this.getFieldMeta(fieldName);
2406
- if (!fieldMeta) continue;
2407
- this.setFieldMeta(fieldName, (prev) => ({
2408
- ...prev,
2409
- errorMap: {
2410
- ...prev.errorMap,
2411
- [errorMapKey]: fieldErrors?.[fieldName]
2412
- },
2413
- errorSourceMap: {
2414
- ...prev.errorSourceMap,
2415
- [errorMapKey]: "form"
2416
- }
2417
- }));
2418
- }
2419
- this.baseStore.setState((prev) => ({
2420
- ...prev,
2421
- errorMap: {
2422
- ...prev.errorMap,
2423
- [errorMapKey]: formError
2424
- }
2425
- }));
2426
- } else {
2427
- this.baseStore.setState((prev) => ({
2428
- ...prev,
2429
- errorMap: {
2430
- ...prev.errorMap,
2431
- [errorMapKey]: value
2432
- }
2433
- }));
2434
- }
2435
- });
2436
- });
2437
- };
2438
- this.getAllErrors = () => {
2439
- return {
2440
- form: {
2441
- errors: this.state.errors,
2442
- errorMap: this.state.errorMap
2443
- },
2444
- fields: Object.entries(this.state.fieldMeta).reduce(
2445
- (acc, [fieldName, fieldMeta]) => {
2446
- if (Object.keys(fieldMeta).length && fieldMeta.errors.length) {
2447
- acc[fieldName] = {
2448
- errors: fieldMeta.errors,
2449
- errorMap: fieldMeta.errorMap
2450
- };
2451
- }
2452
- return acc;
2453
- },
2454
- {}
2455
- )
2456
- };
2457
- };
2458
- this.parseValuesWithSchema = (schema) => {
2459
- return standardSchemaValidators.validate(
2460
- { value: this.state.values, validationSource: "form" },
2461
- schema
2462
- );
2463
- };
2464
- this.parseValuesWithSchemaAsync = (schema) => {
2465
- return standardSchemaValidators.validateAsync(
2466
- { value: this.state.values, validationSource: "form" },
2467
- schema
2468
- );
2469
- };
2470
- this.timeoutIds = {
2471
- validations: {},
2472
- listeners: {},
2473
- formListeners: {}
2474
- };
2475
- this._formId = opts?.formId ?? uuid();
2476
- this._devtoolsSubmissionOverride = false;
2477
- let baseStoreVal = getDefaultFormState({
2478
- ...opts?.defaultState,
2479
- values: opts?.defaultValues ?? opts?.defaultState?.values
2480
- });
2481
- if (opts?.transform) {
2482
- baseStoreVal = opts.transform({ state: baseStoreVal }).state;
2483
- for (const errKey of Object.keys(baseStoreVal.errorMap)) {
2484
- const errKeyMap = baseStoreVal.errorMap[errKey];
2485
- if (errKeyMap === void 0 || !isGlobalFormValidationError(errKeyMap)) {
2486
- continue;
2487
- }
2488
- for (const fieldName of Object.keys(errKeyMap.fields)) {
2489
- const fieldErr = errKeyMap.fields[fieldName];
2490
- if (fieldErr === void 0) {
2491
- continue;
2492
- }
2493
- const existingFieldMeta = baseStoreVal.fieldMetaBase[fieldName];
2494
- baseStoreVal.fieldMetaBase[fieldName] = {
2495
- isTouched: false,
2496
- isValidating: false,
2497
- isBlurred: false,
2498
- isDirty: false,
2499
- _arrayVersion: 0,
2500
- ...existingFieldMeta ?? {},
2501
- errorSourceMap: {
2502
- ...existingFieldMeta?.["errorSourceMap"] ?? {},
2503
- onChange: "form"
2504
- },
2505
- errorMap: {
2506
- ...existingFieldMeta?.["errorMap"] ?? {},
2507
- [errKey]: fieldErr
2508
- }
2509
- };
2510
- }
2511
- }
2512
- }
2513
- this.baseStore = createStore(baseStoreVal);
2514
- let prevBaseStore = void 0;
2515
- this.fieldMetaDerived = createStore(
2516
- (prevVal) => {
2517
- const currBaseStore = this.baseStore.get();
2518
- let originalMetaCount = 0;
2519
- const fieldMeta = {};
2520
- for (const fieldName of Object.keys(
2521
- currBaseStore.fieldMetaBase
2522
- )) {
2523
- const currBaseMeta = currBaseStore.fieldMetaBase[fieldName];
2524
- const prevBaseMeta = prevBaseStore?.fieldMetaBase[fieldName];
2525
- const prevFieldInfo = prevVal?.[fieldName];
2526
- const curFieldVal = getBy(currBaseStore.values, fieldName);
2527
- let fieldErrors = prevFieldInfo?.errors;
2528
- if (!prevBaseMeta || currBaseMeta.errorMap !== prevBaseMeta.errorMap) {
2529
- fieldErrors = Object.values(currBaseMeta.errorMap ?? {}).filter(
2530
- (val) => val !== void 0
2531
- );
2532
- const fieldInstance = this.getFieldInfo(fieldName)?.instance;
2533
- if (!fieldInstance || !fieldInstance.options.disableErrorFlat) {
2534
- fieldErrors = fieldErrors.flat(1);
2535
- }
2536
- }
2537
- const isFieldValid = !isNonEmptyArray(fieldErrors);
2538
- const isFieldPristine = !currBaseMeta.isDirty;
2539
- const isDefaultValue = evaluate(
2540
- curFieldVal,
2541
- // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
2542
- this.getFieldInfo(fieldName)?.instance?.options.defaultValue ?? getBy(this.options.defaultValues, fieldName)
2543
- );
2544
- if (prevFieldInfo && prevFieldInfo.isPristine === isFieldPristine && prevFieldInfo.isValid === isFieldValid && prevFieldInfo.isDefaultValue === isDefaultValue && prevFieldInfo.errors === fieldErrors && currBaseMeta === prevBaseMeta) {
2545
- fieldMeta[fieldName] = prevFieldInfo;
2546
- originalMetaCount++;
2547
- continue;
2548
- }
2549
- fieldMeta[fieldName] = {
2550
- ...currBaseMeta,
2551
- errors: fieldErrors ?? [],
2552
- isPristine: isFieldPristine,
2553
- isValid: isFieldValid,
2554
- isDefaultValue
2555
- };
2556
- }
2557
- if (!Object.keys(currBaseStore.fieldMetaBase).length) return fieldMeta;
2558
- if (prevVal && originalMetaCount === Object.keys(currBaseStore.fieldMetaBase).length) {
2559
- return prevVal;
2560
- }
2561
- prevBaseStore = this.baseStore.get();
2562
- return fieldMeta;
2563
- }
2564
- );
2565
- this.formGroupMetaDerived = createStore(
2566
- (prevVal) => {
2567
- const currBaseStore = this.baseStore.get();
2568
- const currFieldMeta = this.fieldMetaDerived.get();
2569
- const result = {};
2570
- for (const group of this.formGroupApis) {
2571
- const groupName = group.name;
2572
- const lifecycle = currBaseStore.formGroupStateBase[groupName] ?? {
2573
- isSubmitted: false,
2574
- isSubmitting: false,
2575
- isValidating: false,
2576
- submissionAttempts: 0,
2577
- isSubmitSuccessful: false
2578
- };
2579
- const ownFieldMeta = currFieldMeta[groupName];
2580
- let isFieldsValidating = false;
2581
- let isFieldsValid = true;
2582
- let aggIsTouched = false;
2583
- let aggIsBlurred = false;
2584
- let aggIsDefaultValue = true;
2585
- let aggIsDirty = false;
2586
- for (const fieldName in currFieldMeta) {
2587
- if (fieldName === groupName) continue;
2588
- if (!isFieldInGroup(groupName, fieldName)) continue;
2589
- const m = currFieldMeta[fieldName];
2590
- if (!m) continue;
2591
- if (m.isValidating) isFieldsValidating = true;
2592
- if (!m.isValid) isFieldsValid = false;
2593
- if (m.isTouched) aggIsTouched = true;
2594
- if (m.isBlurred) aggIsBlurred = true;
2595
- if (!m.isDefaultValue) aggIsDefaultValue = false;
2596
- if (m.isDirty) aggIsDirty = true;
2597
- }
2598
- const isPristine = !aggIsDirty;
2599
- const isValidating = !!isFieldsValidating || lifecycle.isValidating;
2600
- const errorMap = ownFieldMeta?.errorMap ?? {};
2601
- const errorSourceMap = ownFieldMeta?.errorSourceMap ?? {};
2602
- const hasOnMountError = Boolean(
2603
- errorMap.onMount || Object.entries(currFieldMeta).some(
2604
- ([fieldName, field]) => field && fieldName !== groupName && isFieldInGroup(groupName, fieldName) && field.errorMap.onMount
2605
- )
2606
- );
2607
- const prevGroupMeta = prevVal?.[groupName];
2608
- let errors = prevGroupMeta?.errors ?? [];
2609
- if (!prevGroupMeta || prevGroupMeta.__srcErrorMap !== errorMap) {
2610
- errors = Object.values(errorMap).reduce((acc, curr) => {
2611
- if (curr === void 0) return acc;
2612
- if (curr && typeof curr === "object" && "fields" in curr) {
2613
- const groupErr = curr.group;
2614
- if (groupErr !== void 0) acc.push(groupErr);
2615
- return acc;
2616
- }
2617
- acc.push(curr);
2618
- return acc;
2619
- }, []);
2620
- }
2621
- const isGroupValid = errors.length === 0;
2622
- const isValid = isFieldsValid && isGroupValid;
2623
- const submitInvalid = group.options.canSubmitWhenInvalid ?? false;
2624
- const canSubmit = lifecycle.submissionAttempts === 0 && !aggIsTouched && !hasOnMountError || !isValidating && !lifecycle.isSubmitting && isValid || submitInvalid;
2625
- if (prevGroupMeta && prevGroupMeta.errorMap === errorMap && prevGroupMeta.errorSourceMap === errorSourceMap && prevGroupMeta.errors === errors && prevGroupMeta.isFieldsValidating === isFieldsValidating && prevGroupMeta.isFieldsValid === isFieldsValid && prevGroupMeta.isGroupValid === isGroupValid && prevGroupMeta.isValid === isValid && prevGroupMeta.canSubmit === canSubmit && prevGroupMeta.isTouched === aggIsTouched && prevGroupMeta.isBlurred === aggIsBlurred && prevGroupMeta.isPristine === isPristine && prevGroupMeta.isDefaultValue === aggIsDefaultValue && prevGroupMeta.isDirty === aggIsDirty && prevGroupMeta.isValidating === isValidating && prevGroupMeta.isSubmitting === lifecycle.isSubmitting && prevGroupMeta.isSubmitted === lifecycle.isSubmitted && prevGroupMeta.submissionAttempts === lifecycle.submissionAttempts && prevGroupMeta.isSubmitSuccessful === lifecycle.isSubmitSuccessful) {
2626
- result[groupName] = prevGroupMeta;
2627
- continue;
2628
- }
2629
- const meta = {
2630
- // Submission lifecycle (spread first; `isValidating` below
2631
- // intentionally overrides `lifecycle.isValidating` with the
2632
- // OR of group-level + descendant-field validating).
2633
- ...lifecycle,
2634
- // Field-meta-base fields (so `setMeta` updates can roundtrip
2635
- // through `state.meta`).
2636
- errorMap,
2637
- errorSourceMap,
2638
- _arrayVersion: ownFieldMeta?._arrayVersion ?? 0,
2639
- // Aggregated descendant booleans (override field-level meaning
2640
- // for groups — a group's "field" itself never receives input).
2641
- isTouched: aggIsTouched,
2642
- isBlurred: aggIsBlurred,
2643
- isDirty: aggIsDirty,
2644
- isPristine,
2645
- isDefaultValue: aggIsDefaultValue,
2646
- // Aggregated validity
2647
- isValid,
2648
- errors,
2649
- isValidating,
2650
- // Group-only flags
2651
- isFieldsValidating,
2652
- isFieldsValid,
2653
- isGroupValid,
2654
- canSubmit
2655
- };
2656
- Object.defineProperty(meta, "__srcErrorMap", {
2657
- value: errorMap,
2658
- enumerable: false,
2659
- configurable: true
2660
- });
2661
- result[groupName] = meta;
2662
- }
2663
- return result;
2664
- }
2665
- );
2666
- let prevBaseStoreForStore = void 0;
2667
- this.store = createStore((prevVal) => {
2668
- const currBaseStore = this.baseStore.get();
2669
- const currFieldMeta = this.fieldMetaDerived.get();
2670
- const fieldMetaValues = Object.values(currFieldMeta).filter(
2671
- Boolean
2672
- );
2673
- const isFieldsValidating = fieldMetaValues.some(
2674
- (field) => field.isValidating
2675
- );
2676
- const isFieldsValid = fieldMetaValues.every((field) => field.isValid);
2677
- const isTouched = fieldMetaValues.some((field) => field.isTouched);
2678
- const isBlurred = fieldMetaValues.some((field) => field.isBlurred);
2679
- const isDefaultValue = fieldMetaValues.every(
2680
- (field) => field.isDefaultValue
2681
- );
2682
- const shouldInvalidateOnMount = (
2683
- // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
2684
- isTouched && currBaseStore.errorMap?.onMount
2685
- );
2686
- const isDirty = fieldMetaValues.some((field) => field.isDirty);
2687
- const isPristine = !isDirty;
2688
- const hasOnMountError = Boolean(
2689
- // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
2690
- currBaseStore.errorMap?.onMount || // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
2691
- fieldMetaValues.some((f) => f?.errorMap?.onMount)
2692
- );
2693
- const isValidating = !!isFieldsValidating;
2694
- let errors = prevVal?.errors ?? [];
2695
- if (!prevBaseStoreForStore || currBaseStore.errorMap !== prevBaseStoreForStore.errorMap) {
2696
- errors = Object.values(currBaseStore.errorMap).reduce((prev, curr) => {
2697
- if (curr === void 0) return prev;
2698
- if (curr && isGlobalFormValidationError(curr)) {
2699
- prev.push(curr.form);
2700
- return prev;
2701
- }
2702
- prev.push(curr);
2703
- return prev;
2704
- }, []);
2705
- }
2706
- const isFormValid = errors.length === 0;
2707
- const isValid = isFieldsValid && isFormValid;
2708
- const submitInvalid = this.options.canSubmitWhenInvalid ?? false;
2709
- const canSubmit = currBaseStore.submissionAttempts === 0 && !isTouched && !hasOnMountError || !isValidating && !currBaseStore.isSubmitting && isValid || submitInvalid;
2710
- let errorMap = currBaseStore.errorMap;
2711
- if (shouldInvalidateOnMount) {
2712
- errors = errors.filter((err) => err !== currBaseStore.errorMap.onMount);
2713
- errorMap = Object.assign(errorMap, { onMount: void 0 });
2714
- }
2715
- if (prevVal && prevBaseStoreForStore && prevVal.errorMap === errorMap && prevVal.fieldMeta === this.fieldMetaDerived.state && prevVal.errors === errors && prevVal.isFieldsValidating === isFieldsValidating && prevVal.isFieldsValid === isFieldsValid && prevVal.isFormValid === isFormValid && prevVal.isValid === isValid && prevVal.canSubmit === canSubmit && prevVal.isTouched === isTouched && prevVal.isBlurred === isBlurred && prevVal.isPristine === isPristine && prevVal.isDefaultValue === isDefaultValue && prevVal.isDirty === isDirty && evaluate(prevBaseStoreForStore, currBaseStore)) {
2716
- return prevVal;
2717
- }
2718
- const state = {
2719
- ...currBaseStore,
2720
- errorMap,
2721
- fieldMeta: this.fieldMetaDerived.state,
2722
- errors,
2723
- isFieldsValidating,
2724
- isFieldsValid,
2725
- isFormValid,
2726
- isValid,
2727
- canSubmit,
2728
- isTouched,
2729
- isBlurred,
2730
- isPristine,
2731
- isDefaultValue,
2732
- isDirty
2733
- };
2734
- prevBaseStoreForStore = this.baseStore.get();
2735
- return state;
2736
- });
2737
- this.handleSubmit = this.handleSubmit.bind(this);
2738
- this.update(opts || {});
2739
- }
2740
- get state() {
2741
- return this.store.state;
2742
- }
2743
- get formId() {
2744
- return this._formId;
2745
- }
2746
- /**
2747
- * @private
2748
- */
2749
- runValidator(props) {
2750
- if (isStandardSchemaValidator(props.validate)) {
2751
- return standardSchemaValidators[props.type](
2752
- props.value,
2753
- props.validate
2754
- );
2755
- }
2756
- return props.validate(props.value);
2757
- }
2758
- handleSubmit(submitMeta) {
2759
- return this._handleSubmit(submitMeta);
2760
- }
2761
- };
2762
- function normalizeError(rawError) {
2763
- if (rawError) {
2764
- if (isGlobalFormValidationError(rawError)) {
2765
- const formError = normalizeError(rawError.form).formError;
2766
- const fieldErrors = rawError.fields;
2767
- return { formError, fieldErrors };
2768
- }
2769
- return { formError: rawError };
2770
- }
2771
- return { formError: void 0 };
2772
- }
2773
- function getErrorMapKey(cause) {
2774
- switch (cause) {
2775
- case "submit":
2776
- return "onSubmit";
2777
- case "blur":
2778
- return "onBlur";
2779
- case "mount":
2780
- return "onMount";
2781
- case "server":
2782
- return "onServer";
2783
- case "dynamic":
2784
- return "onDynamic";
2785
- case "change":
2786
- default:
2787
- return "onChange";
2788
- }
2789
- }
2790
-
2791
- // ../../node_modules/.pnpm/@tanstack+form-core@1.33.0/node_modules/@tanstack/form-core/dist/esm/FieldApi.js
2792
- var FieldApi = class _FieldApi {
2793
- /**
2794
- * Initializes a new `FieldApi` instance.
2795
- */
2796
- constructor(opts) {
2797
- this.options = {};
2798
- this.mount = () => {
2799
- if (this.options.defaultValue !== void 0 && !this.getMeta().isTouched) {
2800
- this.form.setFieldValue(this.name, this.options.defaultValue, {
2801
- dontUpdateMeta: true
2802
- });
2803
- }
2804
- const info = this.getInfo();
2805
- info.instance = this;
2806
- this.update(this.options);
2807
- const { onMount } = this.options.validators || {};
2808
- if (onMount) {
2809
- const error = this.runValidator({
2810
- validate: onMount,
2811
- value: {
2812
- value: this.state.value,
2813
- fieldApi: this,
2814
- validationSource: "field"
2815
- },
2816
- type: "validate"
2817
- });
2818
- if (error) {
2819
- this.setMeta(
2820
- (prev) => ({
2821
- ...prev,
2822
- // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
2823
- errorMap: { ...prev?.errorMap, onMount: error },
2824
- errorSourceMap: {
2825
- // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
2826
- ...prev?.errorSourceMap,
2827
- onMount: "field"
2828
- }
2829
- })
2830
- );
2831
- }
2832
- }
2833
- this.options.listeners?.onMount?.({
2834
- value: this.state.value,
2835
- fieldApi: this
2836
- });
2837
- return () => {
2838
- for (const [key, timeout] of Object.entries(
2839
- this.timeoutIds.validations
2840
- )) {
2841
- if (timeout) {
2842
- clearTimeout(timeout);
2843
- this.timeoutIds.validations[key] = null;
2844
- }
2845
- }
2846
- for (const [key, timeout] of Object.entries(this.timeoutIds.listeners)) {
2847
- if (timeout) {
2848
- clearTimeout(timeout);
2849
- this.timeoutIds.listeners[key] = null;
2850
- }
2851
- }
2852
- for (const [key, timeout] of Object.entries(
2853
- this.timeoutIds.formListeners
2854
- )) {
2855
- if (timeout) {
2856
- clearTimeout(timeout);
2857
- this.timeoutIds.formListeners[key] = null;
2858
- }
2859
- }
2860
- const fieldInfo = this.form.fieldInfo[this.name];
2861
- if (!fieldInfo) return;
2862
- if (fieldInfo.instance !== this) return;
2863
- for (const [key, validationMeta] of Object.entries(
2864
- fieldInfo.validationMetaMap
2865
- )) {
2866
- validationMeta?.lastAbortController.abort();
2867
- fieldInfo.validationMetaMap[key] = void 0;
2868
- }
2869
- this.form.baseStore.setState((prev) => ({
2870
- // Preserve interaction flags so field-level defaultValue does not
2871
- // reseed user-entered values on remount.
2872
- ...prev,
2873
- fieldMetaBase: {
2874
- ...prev.fieldMetaBase,
2875
- [this.name]: {
2876
- ...defaultFieldMeta,
2877
- isTouched: prev.fieldMetaBase[this.name]?.isTouched ?? defaultFieldMeta.isTouched,
2878
- isBlurred: prev.fieldMetaBase[this.name]?.isBlurred ?? defaultFieldMeta.isBlurred,
2879
- isDirty: prev.fieldMetaBase[this.name]?.isDirty ?? defaultFieldMeta.isDirty
2880
- }
2881
- }
2882
- }));
2883
- fieldInfo.instance = null;
2884
- this.options.listeners?.onUnmount?.({
2885
- value: this.state.value,
2886
- fieldApi: this
2887
- });
2888
- this.form.options.listeners?.onFieldUnmount?.({
2889
- formApi: this.form,
2890
- fieldApi: this
2891
- });
2892
- };
2893
- };
2894
- this.update = (opts2) => {
2895
- this.options = opts2;
2896
- this.name = opts2.name;
2897
- if (!this.state.meta.isTouched && this.options.defaultValue !== void 0) {
2898
- const formField = this.form.getFieldValue(this.name);
2899
- if (!evaluate(formField, opts2.defaultValue)) {
2900
- this.form.setFieldValue(this.name, opts2.defaultValue, {
2901
- dontUpdateMeta: true,
2902
- dontValidate: true,
2903
- dontRunListeners: true
2904
- });
2905
- }
2906
- }
2907
- if (!this.form.getFieldMeta(this.name)) {
2908
- this.form.setFieldMeta(this.name, this.state.meta);
2909
- }
2910
- };
2911
- this.getValue = () => {
2912
- return this.form.getFieldValue(this.name);
2913
- };
2914
- this.setValue = (updater, options) => {
2915
- this.form.setFieldValue(
2916
- this.name,
2917
- updater,
2918
- mergeOpts(options, { dontRunListeners: true, dontValidate: true })
2919
- );
2920
- if (!options?.dontRunListeners) {
2921
- this.triggerOnChangeListener();
2922
- }
2923
- if (!options?.dontValidate) {
2924
- this.validate("change");
2925
- }
2926
- };
2927
- this.getMeta = () => this.store.state.meta;
2928
- this.setMeta = (updater) => this.form.setFieldMeta(this.name, updater);
2929
- this.getInfo = () => this.form.getFieldInfo(this.name);
2930
- this.pushValue = (value, options) => {
2931
- this.form.pushFieldValue(
2932
- this.name,
2933
- value,
2934
- mergeOpts(options, { dontRunListeners: true })
2935
- );
2936
- if (!options?.dontRunListeners) {
2937
- this.triggerOnChangeListener();
2938
- }
2939
- };
2940
- this.insertValue = (index, value, options) => {
2941
- this.form.insertFieldValue(
2942
- this.name,
2943
- index,
2944
- value,
2945
- mergeOpts(options, { dontRunListeners: true })
2946
- );
2947
- if (!options?.dontRunListeners) {
2948
- this.triggerOnChangeListener();
2949
- }
2950
- };
2951
- this.replaceValue = (index, value, options) => {
2952
- this.form.replaceFieldValue(
2953
- this.name,
2954
- index,
2955
- value,
2956
- mergeOpts(options, { dontRunListeners: true })
2957
- );
2958
- if (!options?.dontRunListeners) {
2959
- this.triggerOnChangeListener();
2960
- }
2961
- };
2962
- this.removeValue = (index, options) => {
2963
- this.form.removeFieldValue(
2964
- this.name,
2965
- index,
2966
- mergeOpts(options, { dontRunListeners: true })
2967
- );
2968
- if (!options?.dontRunListeners) {
2969
- this.triggerOnChangeListener();
2970
- }
2971
- };
2972
- this.swapValues = (aIndex, bIndex, options) => {
2973
- this.form.swapFieldValues(
2974
- this.name,
2975
- aIndex,
2976
- bIndex,
2977
- mergeOpts(options, { dontRunListeners: true })
2978
- );
2979
- if (!options?.dontRunListeners) {
2980
- this.triggerOnChangeListener();
2981
- }
2982
- };
2983
- this.moveValue = (aIndex, bIndex, options) => {
2984
- this.form.moveFieldValues(
2985
- this.name,
2986
- aIndex,
2987
- bIndex,
2988
- mergeOpts(options, { dontRunListeners: true })
2989
- );
2990
- if (!options?.dontRunListeners) {
2991
- this.triggerOnChangeListener();
2992
- }
2993
- };
2994
- this.clearValues = (options) => {
2995
- this.form.clearFieldValues(
2996
- this.name,
2997
- mergeOpts(options, { dontRunListeners: true })
2998
- );
2999
- if (!options?.dontRunListeners) {
3000
- this.triggerOnChangeListener();
3001
- }
3002
- };
3003
- this.getLinkedFields = (cause) => {
3004
- const fields = Object.values(this.form.fieldInfo);
3005
- const linkedFields = [];
3006
- for (const field of fields) {
3007
- if (!field.instance) continue;
3008
- if (!(field.instance instanceof _FieldApi)) {
3009
- continue;
3010
- }
3011
- const { onChangeListenTo, onBlurListenTo } = field.instance.options.validators || {};
3012
- if (cause === "change" && onChangeListenTo?.includes(this.name)) {
3013
- linkedFields.push(field.instance);
3014
- }
3015
- if (cause === "blur" && onBlurListenTo?.includes(this.name)) {
3016
- linkedFields.push(field.instance);
3017
- }
3018
- }
3019
- return linkedFields;
3020
- };
3021
- this.validateSync = (cause, errorFromForm) => {
3022
- const validates = getSyncValidatorArray(cause, {
3023
- ...this.options,
3024
- form: this.form,
3025
- fieldName: this.name,
3026
- validationLogic: this.form.options.validationLogic || defaultValidationLogic
3027
- });
3028
- const linkedFields = this.getLinkedFields(cause);
3029
- const linkedFieldValidates = linkedFields.reduce(
3030
- (acc, field) => {
3031
- const fieldValidates = getSyncValidatorArray(cause, {
3032
- ...field.options,
3033
- form: field.form,
3034
- fieldName: field.name,
3035
- validationLogic: field.form.options.validationLogic || defaultValidationLogic
3036
- });
3037
- fieldValidates.forEach((validate) => {
3038
- validate.field = field;
3039
- });
3040
- return acc.concat(fieldValidates);
3041
- },
3042
- []
3043
- );
3044
- let hasErrored = false;
3045
- batch(() => {
3046
- const validateFieldFn = (field, validateObj) => {
3047
- const errorMapKey = getErrorMapKey2(validateObj.cause);
3048
- const fieldLevelError = validateObj.validate ? normalizeError2(
3049
- field.runValidator({
3050
- validate: validateObj.validate,
3051
- value: {
3052
- value: field.store.state.value,
3053
- validationSource: "field",
3054
- fieldApi: field
3055
- },
3056
- type: "validate"
3057
- })
3058
- ) : void 0;
3059
- const formLevelError = errorFromForm[errorMapKey];
3060
- const { newErrorValue, newSource } = determineFieldLevelErrorSourceAndValue({
3061
- formLevelError,
3062
- fieldLevelError
3063
- });
3064
- if (field.state.meta.errorMap?.[errorMapKey] !== newErrorValue) {
3065
- field.setMeta((prev) => ({
3066
- ...prev,
3067
- errorMap: {
3068
- ...prev.errorMap,
3069
- [errorMapKey]: newErrorValue
3070
- },
3071
- errorSourceMap: {
3072
- ...prev.errorSourceMap,
3073
- [errorMapKey]: newSource
3074
- }
3075
- }));
3076
- }
3077
- if (newErrorValue) {
3078
- hasErrored = true;
3079
- }
3080
- };
3081
- for (const validateObj of validates) {
3082
- validateFieldFn(this, validateObj);
3083
- }
3084
- for (const fieldValitateObj of linkedFieldValidates) {
3085
- if (!fieldValitateObj.validate) continue;
3086
- validateFieldFn(fieldValitateObj.field, fieldValitateObj);
3087
- }
3088
- });
3089
- const submitErrKey = getErrorMapKey2("submit");
3090
- if (
3091
- // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
3092
- this.state.meta.errorMap?.[submitErrKey] && cause !== "submit" && !hasErrored
3093
- ) {
3094
- this.setMeta((prev) => ({
3095
- ...prev,
3096
- errorMap: {
3097
- ...prev.errorMap,
3098
- [submitErrKey]: void 0
3099
- },
3100
- errorSourceMap: {
3101
- ...prev.errorSourceMap,
3102
- [submitErrKey]: void 0
3103
- }
3104
- }));
3105
- }
3106
- return { hasErrored };
3107
- };
3108
- this.validateAsync = async (cause, formValidationResultPromise) => {
3109
- const validates = getAsyncValidatorArray(cause, {
3110
- ...this.options,
3111
- form: this.form,
3112
- fieldName: this.name,
3113
- validationLogic: this.form.options.validationLogic || defaultValidationLogic
3114
- });
3115
- const asyncFormValidationResults = await formValidationResultPromise;
3116
- const linkedFields = this.getLinkedFields(cause);
3117
- const linkedFieldValidates = linkedFields.reduce(
3118
- (acc, field) => {
3119
- const fieldValidates = getAsyncValidatorArray(cause, {
3120
- ...field.options,
3121
- form: field.form,
3122
- fieldName: field.name,
3123
- validationLogic: field.form.options.validationLogic || defaultValidationLogic
3124
- });
3125
- fieldValidates.forEach((validate) => {
3126
- validate.field = field;
3127
- });
3128
- return acc.concat(fieldValidates);
3129
- },
3130
- []
3131
- );
3132
- const validatesPromises = [];
3133
- const linkedPromises = [];
3134
- const hasAsyncValidators = validates.some((v) => v.validate) || linkedFieldValidates.some((v) => v.validate);
3135
- if (hasAsyncValidators) {
3136
- if (!this.state.meta.isValidating) {
3137
- this.setMeta((prev) => ({ ...prev, isValidating: true }));
3138
- }
3139
- for (const linkedField of linkedFields) {
3140
- linkedField.setMeta((prev) => ({ ...prev, isValidating: true }));
3141
- }
3142
- }
3143
- const validateFieldAsyncFn = (field, validateObj, promises) => {
3144
- const errorMapKey = getErrorMapKey2(validateObj.cause);
3145
- const fieldInfo = field.getInfo();
3146
- const fieldValidatorMeta = fieldInfo.validationMetaMap[errorMapKey];
3147
- fieldValidatorMeta?.lastAbortController.abort();
3148
- const controller = new AbortController();
3149
- fieldInfo.validationMetaMap[errorMapKey] = {
3150
- lastAbortController: controller
3151
- };
3152
- promises.push(
3153
- new Promise(async (resolve) => {
3154
- let rawError;
3155
- try {
3156
- rawError = await new Promise((rawResolve, rawReject) => {
3157
- if (field.timeoutIds.validations[validateObj.cause]) {
3158
- clearTimeout(field.timeoutIds.validations[validateObj.cause]);
3159
- }
3160
- field.timeoutIds.validations[validateObj.cause] = setTimeout(
3161
- async () => {
3162
- if (controller.signal.aborted) return rawResolve(void 0);
3163
- try {
3164
- rawResolve(
3165
- await this.runValidator({
3166
- validate: validateObj.validate,
3167
- value: {
3168
- value: field.store.state.value,
3169
- fieldApi: field,
3170
- signal: controller.signal,
3171
- validationSource: "field"
3172
- },
3173
- type: "validateAsync"
3174
- })
3175
- );
3176
- } catch (e) {
3177
- rawReject(e);
3178
- }
3179
- },
3180
- validateObj.debounceMs
3181
- );
3182
- });
3183
- } catch (e) {
3184
- rawError = e;
3185
- }
3186
- if (controller.signal.aborted) return resolve(void 0);
3187
- const fieldLevelError = normalizeError2(rawError);
3188
- const formLevelError = asyncFormValidationResults[field.name]?.[errorMapKey];
3189
- const { newErrorValue, newSource } = determineFieldLevelErrorSourceAndValue({
3190
- formLevelError,
3191
- fieldLevelError
3192
- });
3193
- if (field.getInfo().instance !== field) {
3194
- return resolve(void 0);
3195
- }
3196
- field.setMeta((prev) => {
3197
- return {
3198
- ...prev,
3199
- errorMap: {
3200
- // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
3201
- ...prev?.errorMap,
3202
- [errorMapKey]: newErrorValue
3203
- },
3204
- errorSourceMap: {
3205
- ...prev.errorSourceMap,
3206
- [errorMapKey]: newSource
3207
- }
3208
- };
3209
- });
3210
- resolve(newErrorValue);
3211
- })
3212
- );
3213
- };
3214
- for (const validateObj of validates) {
3215
- if (!validateObj.validate) continue;
3216
- validateFieldAsyncFn(this, validateObj, validatesPromises);
3217
- }
3218
- for (const fieldValitateObj of linkedFieldValidates) {
3219
- if (!fieldValitateObj.validate) continue;
3220
- validateFieldAsyncFn(
3221
- fieldValitateObj.field,
3222
- fieldValitateObj,
3223
- linkedPromises
3224
- );
3225
- }
3226
- let results = [];
3227
- if (validatesPromises.length || linkedPromises.length) {
3228
- results = await Promise.all(validatesPromises);
3229
- await Promise.all(linkedPromises);
3230
- }
3231
- if (hasAsyncValidators) {
3232
- this.setMeta((prev) => ({ ...prev, isValidating: false }));
3233
- for (const linkedField of linkedFields) {
3234
- linkedField.setMeta((prev) => ({ ...prev, isValidating: false }));
3235
- }
3236
- }
3237
- return results.filter(Boolean);
3238
- };
3239
- this.validate = (cause, opts2) => {
3240
- if (!this.state.meta.isTouched) return [];
3241
- const encompassingGroups = opts2?.skipGroupValidation ? [] : Array.from(this.form.formGroupApis).filter(
3242
- (group) => this.name.startsWith(group.name)
3243
- );
3244
- const formSyncResult = opts2?.skipFormValidation ? { fieldsErrorMap: {} } : this.form.validateSync(cause);
3245
- let fieldsErrorMap = formSyncResult.fieldsErrorMap[this.name] ?? {};
3246
- if (!opts2?.skipFormValidation) {
3247
- for (const group of encompassingGroups) {
3248
- if (group.state.meta.submissionAttempts === 0) continue;
3249
- const { fieldsErrorMap: groupFormErrors } = this.form.validateSync(
3250
- cause,
3251
- {
3252
- group,
3253
- dontUpdateFormErrorMap: true,
3254
- filterFieldNames: (fieldName) => isFieldInGroup(group.name, fieldName)
3255
- }
3256
- );
3257
- fieldsErrorMap = {
3258
- ...fieldsErrorMap,
3259
- ...groupFormErrors[this.name] ?? {}
3260
- };
3261
- }
3262
- }
3263
- const { hasErrored } = this.validateSync(cause, fieldsErrorMap);
3264
- const groupHasErroredWeakMap = /* @__PURE__ */ new WeakMap();
3265
- for (const group of encompassingGroups) {
3266
- const { hasErrored: groupHasErrored } = group.validateSync(
3267
- cause,
3268
- {},
3269
- { skipRelatedFieldValidation: true }
3270
- );
3271
- groupHasErroredWeakMap.set(group, groupHasErrored);
3272
- }
3273
- if (hasErrored && !this.options.asyncAlways) {
3274
- this.getInfo().validationMetaMap[getErrorMapKey2(cause)]?.lastAbortController.abort();
3275
- const groupErrors = [];
3276
- for (const group of encompassingGroups) {
3277
- group.getInfo().validationMetaMap[getErrorMapKey2(cause)]?.lastAbortController.abort();
3278
- groupErrors.push(group.state.meta.errors);
3279
- }
3280
- return [...this.state.meta.errors, ...groupErrors.flat()];
3281
- }
3282
- const formValidationResultPromise = opts2?.skipFormValidation ? Promise.resolve({}) : this.form.validateAsync(cause);
3283
- const fieldAsyncResults = this.validateAsync(
3284
- cause,
3285
- formValidationResultPromise
3286
- );
3287
- const groupAsyncResults = [];
3288
- for (const group of encompassingGroups) {
3289
- if (groupHasErroredWeakMap.get(group) && !group.options.asyncAlways) {
3290
- continue;
3291
- }
3292
- groupAsyncResults.push(
3293
- group.validateAsync(cause, formValidationResultPromise, {
3294
- skipRelatedFieldValidation: true
3295
- })
3296
- );
3297
- }
3298
- if (groupAsyncResults.length === 0) {
3299
- return fieldAsyncResults;
3300
- }
3301
- return Promise.all([fieldAsyncResults, ...groupAsyncResults]).then(
3302
- (results) => results.flat()
3303
- );
3304
- };
3305
- this.handleChange = (updater) => {
3306
- this.setValue(updater);
3307
- };
3308
- this.handleBlur = () => {
3309
- const prevTouched = this.state.meta.isTouched;
3310
- if (!prevTouched) {
3311
- this.setMeta((prev) => ({ ...prev, isTouched: true }));
3312
- }
3313
- if (!this.state.meta.isBlurred) {
3314
- this.setMeta((prev) => ({ ...prev, isBlurred: true }));
3315
- }
3316
- this.validate("blur");
3317
- this.triggerOnBlurListener();
3318
- };
3319
- this.setErrorMap = (errorMap) => {
3320
- this.setMeta((prev) => ({
3321
- ...prev,
3322
- errorMap: {
3323
- ...prev.errorMap,
3324
- ...errorMap
3325
- }
3326
- }));
3327
- };
3328
- this.parseValueWithSchema = (schema) => {
3329
- return standardSchemaValidators.validate(
3330
- { value: this.state.value, validationSource: "field" },
3331
- schema
3332
- );
3333
- };
3334
- this.parseValueWithSchemaAsync = (schema) => {
3335
- return standardSchemaValidators.validateAsync(
3336
- { value: this.state.value, validationSource: "field" },
3337
- schema
3338
- );
3339
- };
3340
- this.triggerOnBlurListener = () => {
3341
- const formDebounceMs = this.form.options.listeners?.onBlurDebounceMs;
3342
- if (formDebounceMs && formDebounceMs > 0) {
3343
- if (this.timeoutIds.formListeners.blur) {
3344
- clearTimeout(this.timeoutIds.formListeners.blur);
3345
- }
3346
- this.timeoutIds.formListeners.blur = setTimeout(() => {
3347
- this.form.options.listeners?.onBlur?.({
3348
- formApi: this.form,
3349
- fieldApi: this
3350
- });
3351
- }, formDebounceMs);
3352
- } else {
3353
- this.form.options.listeners?.onBlur?.({
3354
- formApi: this.form,
3355
- fieldApi: this
3356
- });
3357
- }
3358
- const fieldDebounceMs = this.options.listeners?.onBlurDebounceMs;
3359
- if (fieldDebounceMs && fieldDebounceMs > 0) {
3360
- if (this.timeoutIds.listeners.blur) {
3361
- clearTimeout(this.timeoutIds.listeners.blur);
3362
- }
3363
- this.timeoutIds.listeners.blur = setTimeout(() => {
3364
- this.options.listeners?.onBlur?.({
3365
- value: this.state.value,
3366
- fieldApi: this
3367
- });
3368
- }, fieldDebounceMs);
3369
- } else {
3370
- this.options.listeners?.onBlur?.({
3371
- value: this.state.value,
3372
- fieldApi: this
3373
- });
3374
- }
3375
- };
3376
- this.triggerOnChangeListener = () => {
3377
- const formDebounceMs = this.form.options.listeners?.onChangeDebounceMs;
3378
- if (formDebounceMs && formDebounceMs > 0) {
3379
- if (this.timeoutIds.formListeners.change) {
3380
- clearTimeout(this.timeoutIds.formListeners.change);
3381
- }
3382
- this.timeoutIds.formListeners.change = setTimeout(() => {
3383
- this.form.options.listeners?.onChange?.({
3384
- formApi: this.form,
3385
- fieldApi: this
3386
- });
3387
- }, formDebounceMs);
3388
- } else {
3389
- this.form.options.listeners?.onChange?.({
3390
- formApi: this.form,
3391
- fieldApi: this
3392
- });
3393
- }
3394
- const fieldDebounceMs = this.options.listeners?.onChangeDebounceMs;
3395
- if (fieldDebounceMs && fieldDebounceMs > 0) {
3396
- if (this.timeoutIds.listeners.change) {
3397
- clearTimeout(this.timeoutIds.listeners.change);
3398
- }
3399
- this.timeoutIds.listeners.change = setTimeout(() => {
3400
- this.options.listeners?.onChange?.({
3401
- value: this.state.value,
3402
- fieldApi: this
3403
- });
3404
- }, fieldDebounceMs);
3405
- } else {
3406
- this.options.listeners?.onChange?.({
3407
- value: this.state.value,
3408
- fieldApi: this
3409
- });
3410
- }
3411
- for (const group of this.form.formGroupApis) {
3412
- if (isFieldInGroup(group.name, this.name)) {
3413
- group.triggerOnChangeListener();
3414
- }
3415
- }
3416
- };
3417
- this.triggerOnSubmitListener = () => {
3418
- this.options.listeners?.onSubmit?.({
3419
- value: this.state.value,
3420
- fieldApi: this
3421
- });
3422
- };
3423
- this.form = opts.form;
3424
- this.name = opts.name;
3425
- this.options = opts;
3426
- this.timeoutIds = {
3427
- validations: {},
3428
- listeners: {},
3429
- formListeners: {}
3430
- };
3431
- this.store = createStore(
3432
- (prevVal) => {
3433
- this.form.store.get();
3434
- const meta = this.form.getFieldMeta(this.name) ?? {
3435
- ...defaultFieldMeta,
3436
- ...opts.defaultMeta
3437
- };
3438
- let value = this.form.getFieldValue(this.name);
3439
- if (!meta.isTouched && value === void 0 && this.options.defaultValue !== void 0 && !evaluate(value, this.options.defaultValue)) {
3440
- value = this.options.defaultValue;
3441
- }
3442
- if (prevVal && prevVal.value === value && prevVal.meta === meta) {
3443
- return prevVal;
3444
- }
3445
- return {
3446
- value,
3447
- meta
3448
- };
3449
- }
3450
- );
3451
- }
3452
- /**
3453
- * The current field state.
3454
- */
3455
- get state() {
3456
- return this.store.state;
3457
- }
3458
- /**
3459
- * @private
3460
- */
3461
- runValidator(props) {
3462
- if (isStandardSchemaValidator(props.validate)) {
3463
- return standardSchemaValidators[props.type](
3464
- props.value,
3465
- props.validate
3466
- );
3467
- }
3468
- return props.validate(props.value);
3469
- }
3470
- };
3471
- function normalizeError2(rawError) {
3472
- if (rawError) {
3473
- return rawError;
3474
- }
3475
- return void 0;
3476
- }
3477
- function getErrorMapKey2(cause) {
3478
- switch (cause) {
3479
- case "submit":
3480
- return "onSubmit";
3481
- case "blur":
3482
- return "onBlur";
3483
- case "mount":
3484
- return "onMount";
3485
- case "server":
3486
- return "onServer";
3487
- case "dynamic":
3488
- return "onDynamic";
3489
- case "change":
3490
- default:
3491
- return "onChange";
3492
- }
3493
- }
3494
-
3495
- // ../../node_modules/.pnpm/@tanstack+form-core@1.33.0/node_modules/@tanstack/form-core/dist/esm/FormGroupApi.js
3496
- function getDefaultFormGroupState(defaultState) {
3497
- return {
3498
- isSubmitted: defaultState.isSubmitted ?? false,
3499
- isSubmitting: defaultState.isSubmitting ?? false,
3500
- isValidating: defaultState.isValidating ?? false,
3501
- submissionAttempts: defaultState.submissionAttempts ?? 0,
3502
- isSubmitSuccessful: defaultState.isSubmitSuccessful ?? false
3503
- };
3504
- }
3505
- function getDefaultFormGroupMeta(defaultMeta) {
3506
- return {
3507
- ...defaultFieldMeta,
3508
- ...defaultMeta,
3509
- errors: [],
3510
- isPristine: true,
3511
- isValid: true,
3512
- isDefaultValue: true,
3513
- isFieldsValidating: false,
3514
- isFieldsValid: true,
3515
- isGroupValid: true,
3516
- canSubmit: true,
3517
- isSubmitting: false,
3518
- isSubmitted: false,
3519
- isValidating: false,
3520
- submissionAttempts: 0,
3521
- isSubmitSuccessful: false
3522
- };
3523
- }
3524
- var FormGroupApi = class _FormGroupApi {
3525
- constructor(opts) {
3526
- this.options = {};
3527
- this.setFormGroupState = (updater) => {
3528
- this.form.baseStore.setState((prev) => {
3529
- const prevGroupState = prev.formGroupStateBase[this.name] ?? getDefaultFormGroupState({});
3530
- return {
3531
- ...prev,
3532
- formGroupStateBase: {
3533
- ...prev.formGroupStateBase,
3534
- [this.name]: updater(prevGroupState)
3535
- }
3536
- };
3537
- });
3538
- };
3539
- this._lastDistributedFieldNames = {};
3540
- this.update = (opts2) => {
3541
- this.options = opts2;
3542
- this.name = opts2.name;
3543
- if (!this.state.meta.isTouched && this.options.defaultValue !== void 0) {
3544
- const formField = this.form.getFieldValue(this.name);
3545
- if (!evaluate(formField, opts2.defaultValue)) {
3546
- this.form.setFieldValue(this.name, opts2.defaultValue, {
3547
- dontUpdateMeta: true,
3548
- dontValidate: true,
3549
- dontRunListeners: true
3550
- });
3551
- }
3552
- }
3553
- if (!this.form.getFieldMeta(this.name)) {
3554
- this.form.setFieldMeta(this.name, {
3555
- ...defaultFieldMeta,
3556
- ...this.options.defaultMeta
3557
- });
3558
- }
3559
- };
3560
- this.mount = () => {
3561
- this.update(this.options);
3562
- this.form.formGroupApis.add(this);
3563
- this.fieldInfo.instance = this;
3564
- this.form.baseStore.setState((prev) => ({
3565
- ...prev,
3566
- formGroupStateBase: {
3567
- ...prev.formGroupStateBase,
3568
- [this.name]: prev.formGroupStateBase[this.name] ?? getDefaultFormGroupState({
3569
- ...this.options.defaultState
3570
- })
3571
- }
3572
- }));
3573
- const { onMount } = this.options.validators || {};
3574
- if (onMount) {
3575
- const rawError = this.runValidator({
3576
- validate: onMount,
3577
- value: {
3578
- value: this.state.value,
3579
- groupApi: this,
3580
- validationSource: "form"
3581
- },
3582
- type: "validate"
3583
- });
3584
- let groupOwnRawError = rawError;
3585
- let groupFieldErrors = void 0;
3586
- if (isGlobalGroupValidationError(rawError)) {
3587
- groupOwnRawError = rawError.group;
3588
- groupFieldErrors = rawError.fields;
3589
- }
3590
- const error = normalizeError3(groupOwnRawError);
3591
- if (error) {
3592
- this.setMeta(
3593
- (prev) => ({
3594
- ...prev,
3595
- errorMap: {
3596
- ...prev.errorMap,
3597
- onMount: error
3598
- },
3599
- errorSourceMap: {
3600
- ...prev.errorSourceMap,
3601
- onMount: "field"
3602
- }
3603
- })
3604
- );
3605
- }
3606
- this.distributeFieldErrors("onMount", groupFieldErrors);
3607
- }
3608
- this.options.listeners?.onMount?.({
3609
- value: this.state.value,
3610
- groupApi: this
3611
- });
3612
- return () => {
3613
- for (const [key, timeout] of Object.entries(
3614
- this.timeoutIds.validations
3615
- )) {
3616
- if (timeout) {
3617
- clearTimeout(timeout);
3618
- this.timeoutIds.validations[key] = null;
3619
- }
3620
- }
3621
- for (const [key, timeout] of Object.entries(this.timeoutIds.listeners)) {
3622
- if (timeout) {
3623
- clearTimeout(timeout);
3624
- this.timeoutIds.listeners[key] = null;
3625
- }
3626
- }
3627
- for (const [key, timeout] of Object.entries(
3628
- this.timeoutIds.formListeners
3629
- )) {
3630
- if (timeout) {
3631
- clearTimeout(timeout);
3632
- this.timeoutIds.formListeners[key] = null;
3633
- }
3634
- }
3635
- if (this.fieldInfo.instance !== this) return;
3636
- for (const [key, validationMeta] of Object.entries(
3637
- this.fieldInfo.validationMetaMap
3638
- )) {
3639
- validationMeta?.lastAbortController.abort();
3640
- this.fieldInfo.validationMetaMap[key] = void 0;
3641
- }
3642
- this.form.formGroupApis.delete(this);
3643
- this.form.baseStore.setState((prev) => ({
3644
- ...prev,
3645
- formGroupStateBase: {
3646
- ...prev.formGroupStateBase,
3647
- [this.name]: getDefaultFormGroupState({})
3648
- }
3649
- }));
3650
- this.fieldInfo.instance = null;
3651
- this.options.listeners?.onUnmount?.({
3652
- value: this.state.value,
3653
- groupApi: this
3654
- });
3655
- };
3656
- };
3657
- this.setValue = (updater, options) => {
3658
- this.form.setFieldValue(
3659
- this.name,
3660
- updater,
3661
- mergeOpts(options, { dontRunListeners: true, dontValidate: true })
3662
- );
3663
- if (!options?.dontRunListeners) {
3664
- this.triggerOnChangeListener();
3665
- }
3666
- if (!options?.dontValidate) {
3667
- this.validate("change");
3668
- }
3669
- };
3670
- this.getMeta = () => this.store.state.meta;
3671
- this.setMeta = (updater) => this.form.setFieldMeta(this.name, updater);
3672
- this.getInfo = () => this.fieldInfo;
3673
- this.getRelatedFields = () => {
3674
- const fields = Object.values(this.form.fieldInfo);
3675
- const relatedFields = [];
3676
- for (const field of fields) {
3677
- if (!field.instance) continue;
3678
- if (!(field.instance instanceof FieldApi)) continue;
3679
- if (field.instance.name.startsWith(this.name)) {
3680
- relatedFields.push(field.instance);
3681
- }
3682
- }
3683
- return relatedFields;
3684
- };
3685
- this.getRelatedFieldMetasDerived = () => {
3686
- const fields = Object.entries(this.form.fieldMetaDerived.state);
3687
- const relatedFieldMetas = [];
3688
- for (const [fieldName, fieldMeta] of fields) {
3689
- if (fieldName === this.name) continue;
3690
- if (isFieldInGroup(this.name, fieldName)) {
3691
- relatedFieldMetas.push({ ...fieldMeta, name: fieldName });
3692
- }
3693
- }
3694
- return relatedFieldMetas;
3695
- };
3696
- this.buildChildFieldName = (relativeName) => {
3697
- if (relativeName === "") return this.name;
3698
- if (relativeName.startsWith("[")) return `${this.name}${relativeName}`;
3699
- return `${this.name}.${relativeName}`;
3700
- };
3701
- this.distributeFieldErrors = (errorMapKey, fieldErrors) => {
3702
- const previousNames = this._lastDistributedFieldNames[errorMapKey] ?? /* @__PURE__ */ new Set();
3703
- const currentNames = /* @__PURE__ */ new Set();
3704
- if (fieldErrors) {
3705
- for (const [relativeName, err] of Object.entries(fieldErrors)) {
3706
- if (err === void 0 || err === null || err === false) continue;
3707
- currentNames.add(this.buildChildFieldName(relativeName));
3708
- }
3709
- }
3710
- const allNames = /* @__PURE__ */ new Set([...previousNames, ...currentNames]);
3711
- let hasErrored = false;
3712
- for (const fullName of allNames) {
3713
- const relativeName = fullName.startsWith(this.name + "[") ? fullName.slice(this.name.length) : fullName.slice(this.name.length + 1);
3714
- const newFormValidatorError = fieldErrors?.[relativeName];
3715
- const fieldMeta = this.form.getFieldMeta(fullName);
3716
- if (!fieldMeta && !newFormValidatorError) continue;
3717
- const previousErrorValue = fieldMeta?.errorMap[errorMapKey];
3718
- const isPreviousErrorFromFormValidator = fieldMeta?.errorSourceMap[errorMapKey] === "form";
3719
- const { newErrorValue, newSource } = determineFormLevelErrorSourceAndValue({
3720
- newFormValidatorError,
3721
- isPreviousErrorFromFormValidator,
3722
- previousErrorValue
3723
- });
3724
- if (newErrorValue) hasErrored = true;
3725
- if (previousErrorValue === newErrorValue && fieldMeta?.errorSourceMap[errorMapKey] === newSource) {
3726
- continue;
3727
- }
3728
- this.form.setFieldMeta(fullName, (prev) => ({
3729
- ...prev,
3730
- errorMap: {
3731
- ...prev.errorMap,
3732
- [errorMapKey]: newErrorValue
3733
- },
3734
- errorSourceMap: {
3735
- ...prev.errorSourceMap,
3736
- [errorMapKey]: newSource
3737
- }
3738
- }));
3739
- }
3740
- this._lastDistributedFieldNames[errorMapKey] = currentNames;
3741
- return hasErrored;
3742
- };
3743
- this.validateSync = (cause, errorFromForm, opts2 = {}) => {
3744
- const validates = getSyncValidatorArray(cause, {
3745
- ...this.options,
3746
- form: this.form,
3747
- group: this,
3748
- validationLogic: this.options.validationLogic || this.form.options.validationLogic || defaultValidationLogic
3749
- });
3750
- const relatedFields = opts2.skipRelatedFieldValidation ? [] : this.getRelatedFields();
3751
- const relatedFieldValidates = relatedFields.reduce(
3752
- (acc, field) => {
3753
- const fieldValidates = getSyncValidatorArray(cause, {
3754
- ...field.options,
3755
- form: field.form,
3756
- validationLogic: field.form.options.validationLogic || defaultValidationLogic
3757
- });
3758
- fieldValidates.forEach((validate) => {
3759
- validate.field = field;
3760
- });
3761
- return acc.concat(fieldValidates);
3762
- },
3763
- []
3764
- );
3765
- let hasErrored = false;
3766
- batch(() => {
3767
- const validateFieldOrGroupFn = (fieldOrGroup, validateObj) => {
3768
- const errorMapKey = getErrorMapKey3(validateObj.cause);
3769
- const isGroup = fieldOrGroup === this;
3770
- let rawError = void 0;
3771
- if (validateObj.validate) {
3772
- rawError = fieldOrGroup.runValidator({
3773
- validate: validateObj.validate,
3774
- value: {
3775
- value: fieldOrGroup.store.state.value,
3776
- // For the group's own validators we want standard schemas to
3777
- // produce a `{ form, fields }` shape (with relative keys) so
3778
- // we can fan errors out to children. Field-level validators on
3779
- // related fields keep the regular field source.
3780
- validationSource: isGroup ? "form" : "field",
3781
- ...fieldOrGroup instanceof _FormGroupApi ? {
3782
- groupApi: fieldOrGroup
3783
- } : { fieldApi: fieldOrGroup }
3784
- },
3785
- type: "validate"
3786
- });
3787
- }
3788
- let groupOwnRawError = rawError;
3789
- let groupFieldErrors = void 0;
3790
- if (isGroup && isGlobalGroupValidationError(rawError)) {
3791
- groupOwnRawError = rawError.group;
3792
- groupFieldErrors = rawError.fields;
3793
- }
3794
- const fieldLevelError = normalizeError3(
3795
- groupOwnRawError
3796
- );
3797
- const formLevelError = errorFromForm[errorMapKey];
3798
- const { newErrorValue, newSource } = determineFieldLevelErrorSourceAndValue({
3799
- formLevelError,
3800
- fieldLevelError
3801
- });
3802
- if (fieldOrGroup.state.meta.errorMap?.[errorMapKey] !== newErrorValue) {
3803
- fieldOrGroup.setMeta((prev) => ({
3804
- ...prev,
3805
- errorMap: {
3806
- ...prev.errorMap,
3807
- [errorMapKey]: newErrorValue
3808
- },
3809
- errorSourceMap: {
3810
- ...prev.errorSourceMap,
3811
- [errorMapKey]: newSource
3812
- }
3813
- }));
3814
- }
3815
- if (newErrorValue) {
3816
- hasErrored = true;
3817
- }
3818
- if (isGroup) {
3819
- const distributedHasErrored = this.distributeFieldErrors(
3820
- errorMapKey,
3821
- groupFieldErrors
3822
- );
3823
- if (distributedHasErrored) {
3824
- hasErrored = true;
3825
- }
3826
- }
3827
- };
3828
- for (const validateObj of validates) {
3829
- validateFieldOrGroupFn(this, validateObj);
3830
- }
3831
- for (const fieldValidateObj of relatedFieldValidates) {
3832
- if (!fieldValidateObj.validate) continue;
3833
- validateFieldOrGroupFn(fieldValidateObj.field, fieldValidateObj);
3834
- }
3835
- });
3836
- const submitErrKey = getErrorMapKey3("submit");
3837
- if (
3838
- // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
3839
- this.state.meta.errorMap?.[submitErrKey] && cause !== "submit" && !hasErrored
3840
- ) {
3841
- this.setMeta((prev) => ({
3842
- ...prev,
3843
- errorMap: {
3844
- ...prev.errorMap,
3845
- [submitErrKey]: void 0
3846
- },
3847
- errorSourceMap: {
3848
- ...prev.errorSourceMap,
3849
- [submitErrKey]: void 0
3850
- }
3851
- }));
3852
- }
3853
- return { hasErrored };
3854
- };
3855
- this.validateAsync = async (cause, formValidationResultPromise, opts2 = {}) => {
3856
- const validates = getAsyncValidatorArray(cause, {
3857
- ...this.options,
3858
- form: this.form,
3859
- group: this,
3860
- validationLogic: this.options.validationLogic || this.form.options.validationLogic || defaultValidationLogic
3861
- });
3862
- const asyncFormValidationResults = await formValidationResultPromise;
3863
- const relatedFields = opts2.skipRelatedFieldValidation ? [] : this.getRelatedFields();
3864
- const relatedFieldValidates = relatedFields.reduce(
3865
- (acc, field) => {
3866
- const fieldValidates = getAsyncValidatorArray(cause, {
3867
- ...field.options,
3868
- form: field.form,
3869
- validationLogic: field.form.options.validationLogic || defaultValidationLogic
3870
- });
3871
- fieldValidates.forEach((validate) => {
3872
- validate.field = field;
3873
- });
3874
- return acc.concat(fieldValidates);
3875
- },
3876
- []
3877
- );
3878
- const validatesPromises = [];
3879
- const linkedPromises = [];
3880
- const hasAsyncValidators = validates.some((v) => v.validate) || relatedFieldValidates.some((v) => v.validate);
3881
- if (hasAsyncValidators) {
3882
- if (!this.state.meta.isValidating) {
3883
- this.setMeta((prev) => ({ ...prev, isValidating: true }));
3884
- }
3885
- for (const linkedField of relatedFields) {
3886
- linkedField.setMeta((prev) => ({ ...prev, isValidating: true }));
3887
- }
3888
- }
3889
- const validateFieldOrGroupAsyncFn = (fieldOrGroup, validateObj, promises) => {
3890
- const errorMapKey = getErrorMapKey3(validateObj.cause);
3891
- const fieldInfo = fieldOrGroup.getInfo();
3892
- const fieldValidatorMeta = fieldInfo.validationMetaMap[errorMapKey];
3893
- fieldValidatorMeta?.lastAbortController.abort();
3894
- const controller = new AbortController();
3895
- fieldInfo.validationMetaMap[errorMapKey] = {
3896
- lastAbortController: controller
3897
- };
3898
- const isGroup = fieldOrGroup === this;
3899
- promises.push(
3900
- new Promise(async (resolve) => {
3901
- let rawError;
3902
- try {
3903
- rawError = await new Promise((rawResolve, rawReject) => {
3904
- if (fieldOrGroup.timeoutIds.validations[validateObj.cause]) {
3905
- clearTimeout(
3906
- fieldOrGroup.timeoutIds.validations[validateObj.cause]
3907
- );
3908
- }
3909
- fieldOrGroup.timeoutIds.validations[validateObj.cause] = setTimeout(async () => {
3910
- if (controller.signal.aborted) return rawResolve(void 0);
3911
- try {
3912
- rawResolve(
3913
- await this.runValidator({
3914
- validate: validateObj.validate,
3915
- value: {
3916
- value: fieldOrGroup.store.state.value,
3917
- signal: controller.signal,
3918
- // See sync counterpart: produce `{ form, fields }`
3919
- // from standard schemas attached to the group so we
3920
- // can fan errors out to children.
3921
- validationSource: isGroup ? "form" : "field",
3922
- ...fieldOrGroup instanceof _FormGroupApi ? {
3923
- groupApi: fieldOrGroup
3924
- } : { fieldApi: fieldOrGroup }
3925
- },
3926
- type: "validateAsync"
3927
- })
3928
- );
3929
- } catch (e) {
3930
- rawReject(e);
3931
- }
3932
- }, validateObj.debounceMs);
3933
- });
3934
- } catch (e) {
3935
- rawError = e;
3936
- }
3937
- if (controller.signal.aborted) return resolve(void 0);
3938
- let groupOwnRawError = rawError;
3939
- let groupFieldErrors = void 0;
3940
- if (isGroup && isGlobalGroupValidationError(rawError)) {
3941
- groupOwnRawError = rawError.group;
3942
- groupFieldErrors = rawError.fields;
3943
- }
3944
- const fieldLevelError = normalizeError3(groupOwnRawError);
3945
- const formLevelError = asyncFormValidationResults[fieldOrGroup.name]?.[errorMapKey];
3946
- const { newErrorValue, newSource } = determineFieldLevelErrorSourceAndValue({
3947
- formLevelError,
3948
- fieldLevelError
3949
- });
3950
- if (fieldOrGroup.getInfo().instance !== fieldOrGroup) {
3951
- return resolve(void 0);
3952
- }
3953
- fieldOrGroup.setMeta((prev) => {
3954
- return {
3955
- ...prev,
3956
- errorMap: {
3957
- // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
3958
- ...prev?.errorMap,
3959
- [errorMapKey]: newErrorValue
3960
- },
3961
- errorSourceMap: {
3962
- ...prev.errorSourceMap,
3963
- [errorMapKey]: newSource
3964
- }
3965
- };
3966
- });
3967
- if (isGroup) {
3968
- this.distributeFieldErrors(errorMapKey, groupFieldErrors);
3969
- }
3970
- resolve(newErrorValue);
3971
- })
3972
- );
3973
- };
3974
- for (const validateObj of validates) {
3975
- if (!validateObj.validate) continue;
3976
- validateFieldOrGroupAsyncFn(this, validateObj, validatesPromises);
3977
- }
3978
- for (const fieldValitateObj of relatedFieldValidates) {
3979
- if (!fieldValitateObj.validate) continue;
3980
- validateFieldOrGroupAsyncFn(
3981
- fieldValitateObj.field,
3982
- fieldValitateObj,
3983
- linkedPromises
3984
- );
3985
- }
3986
- let results = [];
3987
- if (validatesPromises.length || linkedPromises.length) {
3988
- results = await Promise.all(validatesPromises);
3989
- await Promise.all(linkedPromises);
3990
- }
3991
- if (hasAsyncValidators) {
3992
- this.setMeta((prev) => ({ ...prev, isValidating: false }));
3993
- for (const linkedField of relatedFields) {
3994
- linkedField.setMeta((prev) => ({ ...prev, isValidating: false }));
3995
- }
3996
- }
3997
- return results.filter(Boolean);
3998
- };
3999
- this.validateAllFields = async (cause) => {
4000
- const fieldValidationPromises = [];
4001
- batch(() => {
4002
- void Object.values(this.getRelatedFields()).forEach((fieldInstance) => {
4003
- fieldValidationPromises.push(
4004
- // Remember, `validate` is either a sync operation or a promise
4005
- Promise.resolve().then(
4006
- () => fieldInstance.validate(cause, {
4007
- skipFormValidation: true,
4008
- skipGroupValidation: true
4009
- })
4010
- )
4011
- );
4012
- if (!fieldInstance.store.state.meta.isTouched) {
4013
- fieldInstance.setMeta((prev) => ({ ...prev, isTouched: true }));
4014
- }
4015
- });
4016
- });
4017
- const fieldErrorMapMap = await Promise.all(fieldValidationPromises);
4018
- return fieldErrorMapMap.flat();
4019
- };
4020
- this.validateArrayFieldsStartingFrom = (field, index, cause) => {
4021
- return this.form.validateArrayFieldsStartingFrom(field, index, cause);
4022
- };
4023
- this.validateField = (field, cause) => {
4024
- return this.form.validateField(field, cause);
4025
- };
4026
- this.getFieldValue = (field) => {
4027
- return this.form.getFieldValue(field);
4028
- };
4029
- this.getFieldMeta = (field) => {
4030
- return this.form.getFieldMeta(field);
4031
- };
4032
- this.setFieldMeta = (field, updater) => {
4033
- return this.form.setFieldMeta(field, updater);
4034
- };
4035
- this.setFieldValue = (field, value) => {
4036
- return this.form.setFieldValue(field, value);
4037
- };
4038
- this.deleteField = (field) => {
4039
- return this.form.deleteField(field);
4040
- };
4041
- this.pushFieldValue = (field, value) => {
4042
- return this.form.pushFieldValue(field, value);
4043
- };
4044
- this.insertFieldValue = (field, index, value) => {
4045
- return this.form.insertFieldValue(field, index, value);
4046
- };
4047
- this.replaceFieldValue = (field, index, value) => {
4048
- return this.form.replaceFieldValue(field, index, value);
4049
- };
4050
- this.swapFieldValues = (field, index1, index2) => {
4051
- return this.form.swapFieldValues(field, index1, index2);
4052
- };
4053
- this.moveFieldValues = (field, fromIndex, toIndex) => {
4054
- return this.form.moveFieldValues(field, fromIndex, toIndex);
4055
- };
4056
- this.clearFieldValues = (field) => {
4057
- return this.form.clearFieldValues(field);
4058
- };
4059
- this.resetField = (field) => {
4060
- return this.form.resetField(field);
4061
- };
4062
- this.removeFieldValue = (field, index) => {
4063
- return this.form.removeFieldValue(field, index);
4064
- };
4065
- this.areRelatedFieldsValid = () => {
4066
- return Object.values(this.getRelatedFields()).every(
4067
- (field) => field.state.meta.isValid
4068
- );
4069
- };
4070
- this.validate = (cause, opts2) => {
4071
- const { fieldsErrorMap } = opts2?.skipFormValidation ? { fieldsErrorMap: {} } : this.form.validateSync(cause, {
4072
- dontUpdateFormErrorMap: true,
4073
- filterFieldNames: (fieldName) => isFieldInGroup(this.name, fieldName)
4074
- });
4075
- const { hasErrored } = this.validateSync(
4076
- cause,
4077
- fieldsErrorMap[this.name] ?? {},
4078
- { skipRelatedFieldValidation: opts2?.skipRelatedFieldValidation }
4079
- );
4080
- if (hasErrored && !this.options.asyncAlways) {
4081
- this.getInfo().validationMetaMap[getErrorMapKey3(cause)]?.lastAbortController.abort();
4082
- return this.state.meta.errors;
4083
- }
4084
- const formValidationResultPromise = opts2?.skipFormValidation ? Promise.resolve({}) : this.form.validateAsync(cause, {
4085
- dontUpdateFormErrorMap: true,
4086
- filterFieldNames: (fieldName) => isFieldInGroup(this.name, fieldName)
4087
- });
4088
- return this.validateAsync(cause, formValidationResultPromise, {
4089
- skipRelatedFieldValidation: opts2?.skipRelatedFieldValidation
4090
- });
4091
- };
4092
- this.triggerOnChangeListener = () => {
4093
- const formDebounceMs = this.form.options.listeners?.onChangeGroupDebounceMs;
4094
- if (formDebounceMs && formDebounceMs > 0) {
4095
- if (this.timeoutIds.formListeners.change) {
4096
- clearTimeout(this.timeoutIds.formListeners.change);
4097
- }
4098
- this.timeoutIds.formListeners.change = setTimeout(() => {
4099
- this.form.options.listeners?.onChangeGroup?.({
4100
- formApi: this.form,
4101
- groupApi: this
4102
- });
4103
- }, formDebounceMs);
4104
- } else {
4105
- this.form.options.listeners?.onChangeGroup?.({
4106
- formApi: this.form,
4107
- groupApi: this
4108
- });
4109
- }
4110
- const fieldDebounceMs = this.options.listeners?.onChangeDebounceMs;
4111
- if (fieldDebounceMs && fieldDebounceMs > 0) {
4112
- if (this.timeoutIds.listeners.change) {
4113
- clearTimeout(this.timeoutIds.listeners.change);
4114
- }
4115
- this.timeoutIds.listeners.change = setTimeout(() => {
4116
- this.options.listeners?.onChange?.({
4117
- value: this.state.value,
4118
- groupApi: this
4119
- });
4120
- }, fieldDebounceMs);
4121
- } else {
4122
- this.options.listeners?.onChange?.({
4123
- value: this.state.value,
4124
- groupApi: this
4125
- });
4126
- }
4127
- };
4128
- this.triggerOnSubmitListener = () => {
4129
- this.options.listeners?.onSubmit?.({
4130
- value: this.state.value,
4131
- groupApi: this
4132
- });
4133
- };
4134
- this._handleSubmit = async (submitMeta) => {
4135
- this.setFormGroupState((old) => ({
4136
- ...old,
4137
- // Submission attempts mark the form as not submitted
4138
- isSubmitted: false,
4139
- // Count submission attempts
4140
- submissionAttempts: old.submissionAttempts + 1,
4141
- isSubmitSuccessful: false
4142
- // Reset isSubmitSuccessful at the start of submission
4143
- }));
4144
- batch(() => {
4145
- void Object.values(this.getRelatedFields()).forEach((field) => {
4146
- if (!field.state.meta.isTouched) {
4147
- field.setMeta((prev) => ({ ...prev, isTouched: true }));
4148
- }
4149
- });
4150
- });
4151
- const submitMetaArg = submitMeta ?? this.options.onSubmitMeta;
4152
- this.setFormGroupState((d) => ({ ...d, isSubmitting: true }));
4153
- const done = () => {
4154
- this.setFormGroupState((prev) => ({ ...prev, isSubmitting: false }));
4155
- };
4156
- await this.validateAllFields("submit");
4157
- if (!this.areRelatedFieldsValid()) {
4158
- done();
4159
- this.options.onGroupSubmitInvalid?.({
4160
- value: this.state.value,
4161
- groupApi: this,
4162
- meta: submitMetaArg
4163
- });
4164
- return;
4165
- }
4166
- await this.validate("submit", {
4167
- // This has already happened in the previous step
4168
- skipRelatedFieldValidation: true
4169
- });
4170
- if (!this.areRelatedFieldsValid() || !this.state.meta.isValid) {
4171
- done();
4172
- this.options.onGroupSubmitInvalid?.({
4173
- value: this.state.value,
4174
- groupApi: this,
4175
- meta: submitMetaArg
4176
- });
4177
- return;
4178
- }
4179
- batch(() => {
4180
- void Object.values(this.getRelatedFields()).forEach((field) => {
4181
- field.options.listeners?.onGroupSubmit?.({
4182
- value: field.state.value,
4183
- fieldApi: field
4184
- });
4185
- });
4186
- });
4187
- this.options.listeners?.onSubmit?.({
4188
- groupApi: this,
4189
- value: this.state.value
4190
- });
4191
- try {
4192
- await this.options.onGroupSubmit?.({
4193
- value: this.state.value,
4194
- groupApi: this,
4195
- meta: submitMetaArg
4196
- });
4197
- batch(() => {
4198
- this.setFormGroupState((prev) => ({
4199
- ...prev,
4200
- isSubmitted: true,
4201
- isSubmitSuccessful: true
4202
- // Set isSubmitSuccessful to true on successful submission
4203
- }));
4204
- done();
4205
- });
4206
- } catch (err) {
4207
- this.setFormGroupState((prev) => ({
4208
- ...prev,
4209
- isSubmitSuccessful: false
4210
- // Ensure isSubmitSuccessful is false if an error occurs
4211
- }));
4212
- done();
4213
- throw err;
4214
- }
4215
- };
4216
- this.form = opts.form;
4217
- this.name = opts.name;
4218
- this.options = opts;
4219
- this.timeoutIds = {
4220
- validations: {},
4221
- listeners: {},
4222
- formListeners: {}
4223
- };
4224
- this.fieldInfo = {
4225
- instance: null,
4226
- validationMetaMap: {
4227
- onChange: void 0,
4228
- onBlur: void 0,
4229
- onSubmit: void 0,
4230
- onMount: void 0,
4231
- onServer: void 0,
4232
- onDynamic: void 0
4233
- }
4234
- };
4235
- this.store = createStore(
4236
- (prevVal) => {
4237
- this.form.formGroupMetaDerived.get();
4238
- this.form.baseStore.get();
4239
- const meta = this.form.getFormGroupMeta(this.name) ?? getDefaultFormGroupMeta(opts.defaultMeta);
4240
- let value = this.form.getFieldValue(this.name);
4241
- if (!meta.isTouched && value === void 0 && this.options.defaultValue !== void 0 && !evaluate(value, this.options.defaultValue)) {
4242
- value = this.options.defaultValue;
4243
- }
4244
- if (prevVal && prevVal.value === value && prevVal.meta === meta) {
4245
- return prevVal;
4246
- }
4247
- return {
4248
- value,
4249
- meta
4250
- };
4251
- }
4252
- );
4253
- this.handleSubmit = this.handleSubmit.bind(this);
4254
- }
4255
- /**
4256
- * The current field state.
4257
- */
4258
- get state() {
4259
- return this.store.state;
4260
- }
4261
- /**
4262
- * @private
4263
- */
4264
- runValidator(props) {
4265
- if (isStandardSchemaValidator(props.validate)) {
4266
- const result = standardSchemaValidators[props.type](
4267
- props.value,
4268
- props.validate
4269
- );
4270
- if (props.type === "validate") {
4271
- return remapStandardSchemaResultForGroup(result);
4272
- }
4273
- return result.then(
4274
- remapStandardSchemaResultForGroup
4275
- );
4276
- }
4277
- return props.validate(
4278
- props.value
4279
- );
4280
- }
4281
- handleSubmit(submitMeta) {
4282
- return this._handleSubmit(submitMeta);
4283
- }
4284
- };
4285
- function normalizeError3(rawError) {
4286
- if (rawError) {
4287
- return rawError;
4288
- }
4289
- return void 0;
4290
- }
4291
- function isGlobalGroupValidationError(error) {
4292
- return !!error && typeof error === "object" && "fields" in error;
4293
- }
4294
- function remapStandardSchemaResultForGroup(result) {
4295
- if (!result || typeof result !== "object") return result;
4296
- if (!("form" in result) && !("fields" in result)) return result;
4297
- const { form, fields, ...rest } = result;
4298
- return { ...rest, group: form, fields };
4299
- }
4300
- function getErrorMapKey3(cause) {
4301
- switch (cause) {
4302
- case "submit":
4303
- return "onSubmit";
4304
- case "blur":
4305
- return "onBlur";
4306
- case "mount":
4307
- return "onMount";
4308
- case "server":
4309
- return "onServer";
4310
- case "dynamic":
4311
- return "onDynamic";
4312
- case "change":
4313
- default:
4314
- return "onChange";
4315
- }
4316
- }
4317
-
4318
- // ../../node_modules/.pnpm/@tanstack+form-core@1.33.0/node_modules/@tanstack/form-core/dist/esm/formOptions.js
4319
- function formOptions(defaultOpts) {
4320
- return defaultOpts;
4321
- }
4322
-
4323
- // ../../node_modules/.pnpm/@tanstack+form-core@1.33.0/node_modules/@tanstack/form-core/dist/esm/FieldGroupApi.js
4324
- var FieldGroupApi = class _FieldGroupApi {
4325
- /**
4326
- * Constructs a new `FieldGroupApi` instance with the given form options.
4327
- */
4328
- constructor(opts) {
4329
- this.getFormFieldName = (subfield) => {
4330
- if (typeof this.fieldsMap === "string") {
4331
- return concatenatePaths(this.fieldsMap, subfield);
4332
- }
4333
- const firstAccessor = makePathArray(subfield)[0];
4334
- if (typeof firstAccessor !== "string") {
4335
- return "";
4336
- }
4337
- const restOfPath = subfield.slice(firstAccessor.length);
4338
- const formMappedPath = (
4339
- // TFields is either a string or this. See guard above.
4340
- this.fieldsMap[firstAccessor]
4341
- );
4342
- return concatenatePaths(formMappedPath, restOfPath);
4343
- };
4344
- this.getFormFieldOptions = (props) => {
4345
- const newProps = { ...props };
4346
- const validators = newProps.validators;
4347
- newProps.name = this.getFormFieldName(props.name);
4348
- if (validators && (validators.onChangeListenTo || validators.onBlurListenTo)) {
4349
- const newValidators = { ...validators };
4350
- const remapListenTo = (listenTo) => {
4351
- if (!listenTo) return void 0;
4352
- return listenTo.map(
4353
- (localFieldName) => this.getFormFieldName(localFieldName)
4354
- );
4355
- };
4356
- newValidators.onChangeListenTo = remapListenTo(
4357
- validators.onChangeListenTo
4358
- );
4359
- newValidators.onBlurListenTo = remapListenTo(validators.onBlurListenTo);
4360
- newProps.validators = newValidators;
4361
- }
4362
- return newProps;
4363
- };
4364
- this.mount = () => {
4365
- return () => {
4366
- };
4367
- };
4368
- this.validateArrayFieldsStartingFrom = async (field, index, cause) => {
4369
- return this.form.validateArrayFieldsStartingFrom(
4370
- this.getFormFieldName(field),
4371
- index,
4372
- cause
4373
- );
4374
- };
4375
- this.validateField = (field, cause) => {
4376
- return this.form.validateField(this.getFormFieldName(field), cause);
4377
- };
4378
- this.getFieldValue = (field) => {
4379
- return this.form.getFieldValue(this.getFormFieldName(field));
4380
- };
4381
- this.getFieldMeta = (field) => {
4382
- return this.form.getFieldMeta(this.getFormFieldName(field));
4383
- };
4384
- this.setFieldMeta = (field, updater) => {
4385
- return this.form.setFieldMeta(this.getFormFieldName(field), updater);
4386
- };
4387
- this.setFieldValue = (field, updater, opts2) => {
4388
- return this.form.setFieldValue(
4389
- this.getFormFieldName(field),
4390
- updater,
4391
- opts2
4392
- );
4393
- };
4394
- this.deleteField = (field) => {
4395
- return this.form.deleteField(this.getFormFieldName(field));
4396
- };
4397
- this.pushFieldValue = (field, value, opts2) => {
4398
- return this.form.pushFieldValue(
4399
- this.getFormFieldName(field),
4400
- // since unknown doesn't extend an array, it types `value` as never.
4401
- value,
4402
- opts2
4403
- );
4404
- };
4405
- this.insertFieldValue = async (field, index, value, opts2) => {
4406
- return this.form.insertFieldValue(
4407
- this.getFormFieldName(field),
4408
- index,
4409
- // since unknown doesn't extend an array, it types `value` as never.
4410
- value,
4411
- opts2
4412
- );
4413
- };
4414
- this.replaceFieldValue = async (field, index, value, opts2) => {
4415
- return this.form.replaceFieldValue(
4416
- this.getFormFieldName(field),
4417
- index,
4418
- // since unknown doesn't extend an array, it types `value` as never.
4419
- value,
4420
- opts2
4421
- );
4422
- };
4423
- this.removeFieldValue = async (field, index, opts2) => {
4424
- return this.form.removeFieldValue(this.getFormFieldName(field), index, opts2);
4425
- };
4426
- this.swapFieldValues = (field, index1, index2, opts2) => {
4427
- return this.form.swapFieldValues(
4428
- this.getFormFieldName(field),
4429
- index1,
4430
- index2,
4431
- opts2
4432
- );
4433
- };
4434
- this.moveFieldValues = (field, index1, index2, opts2) => {
4435
- return this.form.moveFieldValues(
4436
- this.getFormFieldName(field),
4437
- index1,
4438
- index2,
4439
- opts2
4440
- );
4441
- };
4442
- this.clearFieldValues = (field, opts2) => {
4443
- return this.form.clearFieldValues(this.getFormFieldName(field), opts2);
4444
- };
4445
- this.resetField = (field) => {
4446
- return this.form.resetField(this.getFormFieldName(field));
4447
- };
4448
- this.validateAllFields = (cause) => this.form.validateAllFields(cause);
4449
- if (opts.form instanceof _FieldGroupApi) {
4450
- const group = opts.form;
4451
- this.form = group.form;
4452
- if (typeof opts.fields === "string") {
4453
- this.fieldsMap = group.getFormFieldName(opts.fields);
4454
- } else {
4455
- const fields = {
4456
- ...opts.fields
4457
- };
4458
- for (const key in fields) {
4459
- fields[key] = group.getFormFieldName(fields[key]);
4460
- }
4461
- this.fieldsMap = fields;
4462
- }
4463
- } else {
4464
- this.form = opts.form;
4465
- this.fieldsMap = opts.fields;
4466
- }
4467
- this.store = createStore(() => {
4468
- const currFormStore = this.form.store.get();
4469
- let values;
4470
- if (typeof this.fieldsMap === "string") {
4471
- values = getBy(currFormStore.values, this.fieldsMap);
4472
- } else {
4473
- values = {};
4474
- const fields = this.fieldsMap;
4475
- for (const key in fields) {
4476
- values[key] = getBy(currFormStore.values, fields[key]);
4477
- }
4478
- }
4479
- return {
4480
- values
4481
- };
4482
- });
4483
- }
4484
- get state() {
4485
- return this.store.state;
4486
- }
4487
- async handleSubmit(submitMeta) {
4488
- return this.form.handleSubmit(submitMeta);
4489
- }
4490
- };
4491
-
4492
- // ../../node_modules/.pnpm/@tanstack+form-core@1.33.0/node_modules/@tanstack/form-core/dist/esm/transform.js
4493
- function mergeAndUpdate(form, fn) {
4494
- if (!fn) return;
4495
- const newObj = Object.assign({}, form, {
4496
- state: deepCopy(form.state)
4497
- });
4498
- fn(newObj);
4499
- if (newObj.fieldInfo !== form.fieldInfo) {
4500
- form.fieldInfo = newObj.fieldInfo;
4501
- }
4502
- if (newObj.options !== form.options) {
4503
- form.options = newObj.options;
4504
- }
4505
- const baseFormKeys = Object.keys({
4506
- values: null,
4507
- validationMetaMap: null,
4508
- fieldMetaBase: null,
4509
- formGroupStateBase: null,
4510
- isSubmitting: null,
4511
- isSubmitted: null,
4512
- isValidating: null,
4513
- submissionAttempts: null,
4514
- isSubmitSuccessful: null,
4515
- _force_re_eval: null
4516
- // Do not remove this, it ensures that we have all the keys in `BaseFormState`
4517
- });
4518
- const diffedObject = baseFormKeys.reduce((prev, key) => {
4519
- if (form.state[key] !== newObj.state[key]) {
4520
- prev[key] = newObj.state[key];
4521
- }
4522
- return prev;
4523
- }, {});
4524
- batch(() => {
4525
- if (Object.keys(diffedObject).length) {
4526
- form.baseStore.setState((prev) => ({ ...prev, ...diffedObject }));
4527
- }
4528
- if (newObj.state.errorMap !== form.state.errorMap) {
4529
- form.setErrorMap(newObj.state.errorMap);
4530
- }
4531
- });
4532
- return newObj;
4533
- }
4534
-
4535
- // ../../node_modules/.pnpm/@tanstack+react-store@0.11.0_react-dom@19.2.7_react@19.2.7__react@19.2.7/node_modules/@tanstack/react-store/dist/useSelector.js
4536
- var import_with_selector = __toESM(require_with_selector(), 1);
4537
- function defaultCompare(a, b) {
4538
- return a === b;
4539
- }
4540
- function useSelector(source, selector = (s) => s, options) {
4541
- const compare = defaultCompare;
4542
- const subscribe = useCallback((handleStoreChange) => {
4543
- const { unsubscribe } = source.subscribe(handleStoreChange);
4544
- return unsubscribe;
4545
- }, [source]);
4546
- const getSnapshot = useCallback(() => source.get(), [source]);
4547
- return (0, import_with_selector.useSyncExternalStoreWithSelector)(subscribe, getSnapshot, getSnapshot, selector, compare);
4548
- }
4549
-
4550
- // ../../node_modules/.pnpm/@tanstack+react-store@0.11.0_react-dom@19.2.7_react@19.2.7__react@19.2.7/node_modules/@tanstack/react-store/dist/useStore.js
4551
- var useStore = (source, selector = (s) => s, compare) => useSelector(source, selector);
4552
- var useIsomorphicLayoutEffect = typeof window !== "undefined" ? useLayoutEffect : useEffect;
4553
-
4554
- // ../../node_modules/.pnpm/@tanstack+react-form@1.33.0_react-dom@19.2.7_react@19.2.7__react@19.2.7/node_modules/@tanstack/react-form/dist/esm/useField.js
4555
- function useField(opts) {
4556
- const [prevOptions, setPrevOptions] = useState(() => ({
4557
- form: opts.form,
4558
- name: opts.name
4559
- }));
4560
- const [fieldApi, setFieldApi] = useState(() => {
4561
- return new FieldApi({
4562
- ...opts
4563
- });
4564
- });
4565
- if (prevOptions.form !== opts.form || prevOptions.name !== opts.name) {
4566
- setFieldApi(
4567
- new FieldApi({
4568
- ...opts
4569
- })
4570
- );
4571
- setPrevOptions({ form: opts.form, name: opts.name });
4572
- }
4573
- const reactiveStateValue = useStore(
4574
- fieldApi.store,
4575
- opts.mode === "array" ? (state) => state.meta._arrayVersion || 0 : (state) => state.value
4576
- );
4577
- const reactiveMetaIsTouched = useStore(
4578
- fieldApi.store,
4579
- (state) => state.meta.isTouched
4580
- );
4581
- const reactiveMetaIsBlurred = useStore(
4582
- fieldApi.store,
4583
- (state) => state.meta.isBlurred
4584
- );
4585
- const reactiveMetaIsDirty = useStore(
4586
- fieldApi.store,
4587
- (state) => state.meta.isDirty
4588
- );
4589
- const reactiveMetaErrorMap = useStore(
4590
- fieldApi.store,
4591
- (state) => state.meta.errorMap
4592
- );
4593
- const reactiveMetaErrorSourceMap = useStore(
4594
- fieldApi.store,
4595
- (state) => state.meta.errorSourceMap
4596
- );
4597
- const reactiveMetaIsValidating = useStore(
4598
- fieldApi.store,
4599
- (state) => state.meta.isValidating
4600
- );
4601
- const extendedFieldApi = useMemo(() => {
4602
- const reactiveFieldApi = {
4603
- ...fieldApi,
4604
- get state() {
4605
- return {
4606
- // For array mode, reactiveStateValue is the length (for reactivity tracking),
4607
- // so we need to get the actual value from fieldApi
4608
- value: opts.mode === "array" ? fieldApi.state.value : reactiveStateValue,
4609
- get meta() {
4610
- return {
4611
- ...fieldApi.state.meta,
4612
- isTouched: reactiveMetaIsTouched,
4613
- isBlurred: reactiveMetaIsBlurred,
4614
- isDirty: reactiveMetaIsDirty,
4615
- errorMap: reactiveMetaErrorMap,
4616
- errorSourceMap: reactiveMetaErrorSourceMap,
4617
- isValidating: reactiveMetaIsValidating
4618
- };
4619
- }
4620
- };
4621
- }
4622
- };
4623
- const extendedApi = reactiveFieldApi;
4624
- return extendedApi;
4625
- }, [
4626
- fieldApi,
4627
- opts.mode,
4628
- reactiveStateValue,
4629
- reactiveMetaIsTouched,
4630
- reactiveMetaIsBlurred,
4631
- reactiveMetaIsDirty,
4632
- reactiveMetaErrorMap,
4633
- reactiveMetaErrorSourceMap,
4634
- reactiveMetaIsValidating
4635
- ]);
4636
- useIsomorphicLayoutEffect(fieldApi.mount, [fieldApi]);
4637
- useIsomorphicLayoutEffect(() => {
4638
- fieldApi.update(opts);
4639
- });
4640
- return extendedFieldApi;
4641
- }
4642
- var Field2 = (({
4643
- children,
4644
- ...fieldOptions
4645
- }) => {
4646
- const fieldApi = useField(fieldOptions);
4647
- const jsxToDisplay = useMemo(
4648
- () => functionalUpdate(children, fieldApi),
4649
- [children, fieldApi]
4650
- );
4651
- return /* @__PURE__ */ jsx(Fragment, { children: jsxToDisplay });
4652
- });
4653
- function useUUID() {
4654
- return useState(() => uuid())[0];
4655
- }
4656
-
4657
- // ../../node_modules/.pnpm/@tanstack+react-form@1.33.0_react-dom@19.2.7_react@19.2.7__react@19.2.7/node_modules/@tanstack/react-form/dist/esm/useFormId.js
4658
- var _React = React;
4659
- var useFormId = React.version.split(".")[0] === "17" ? useUUID : _React.useId;
4660
- function useFormGroup(opts) {
4661
- const [prevOptions, setPrevOptions] = useState(() => ({
4662
- form: opts.form,
4663
- name: opts.name
4664
- }));
4665
- const [formGroupApi, setFormGroupApi] = useState(() => {
4666
- return new FormGroupApi({
4667
- ...opts
4668
- });
4669
- });
4670
- if (prevOptions.form !== opts.form || prevOptions.name !== opts.name) {
4671
- setFormGroupApi(
4672
- new FormGroupApi({
4673
- ...opts
4674
- })
4675
- );
4676
- setPrevOptions({ form: opts.form, name: opts.name });
4677
- }
4678
- const reactiveStateValue = useStore(
4679
- formGroupApi.store,
4680
- (state) => state.value
4681
- );
4682
- const reactiveMetaIsTouched = useStore(
4683
- formGroupApi.store,
4684
- (state) => state.meta.isTouched
4685
- );
4686
- const reactiveMetaIsBlurred = useStore(
4687
- formGroupApi.store,
4688
- (state) => state.meta.isBlurred
4689
- );
4690
- const reactiveMetaIsDirty = useStore(
4691
- formGroupApi.store,
4692
- (state) => state.meta.isDirty
4693
- );
4694
- const reactiveMetaErrorMap = useStore(
4695
- formGroupApi.store,
4696
- (state) => state.meta.errorMap
4697
- );
4698
- const reactiveMetaErrorSourceMap = useStore(
4699
- formGroupApi.store,
4700
- (state) => state.meta.errorSourceMap
4701
- );
4702
- const reactiveMetaIsValidating = useStore(
4703
- formGroupApi.store,
4704
- (state) => state.meta.isValidating
4705
- );
4706
- const reactiveMetaIsSubmitting = useStore(
4707
- formGroupApi.store,
4708
- (state) => state.meta.isSubmitting
4709
- );
4710
- const reactiveMetaIsSubmitted = useStore(
4711
- formGroupApi.store,
4712
- (state) => state.meta.isSubmitted
4713
- );
4714
- const reactiveMetaSubmissionAttempts = useStore(
4715
- formGroupApi.store,
4716
- (state) => state.meta.submissionAttempts
4717
- );
4718
- const reactiveMetaIsSubmitSuccessful = useStore(
4719
- formGroupApi.store,
4720
- (state) => state.meta.isSubmitSuccessful
4721
- );
4722
- const reactiveMetaCanSubmit = useStore(
4723
- formGroupApi.store,
4724
- (state) => state.meta.canSubmit
4725
- );
4726
- const reactiveMetaIsValid = useStore(
4727
- formGroupApi.store,
4728
- (state) => state.meta.isValid
4729
- );
4730
- const reactiveMetaIsFieldsValid = useStore(
4731
- formGroupApi.store,
4732
- (state) => state.meta.isFieldsValid
4733
- );
4734
- const reactiveMetaIsFieldsValidating = useStore(
4735
- formGroupApi.store,
4736
- (state) => state.meta.isFieldsValidating
4737
- );
4738
- const reactiveMetaIsGroupValid = useStore(
4739
- formGroupApi.store,
4740
- (state) => state.meta.isGroupValid
4741
- );
4742
- const extendedFieldApi = useMemo(() => {
4743
- const reactiveFieldApi = {
4744
- ...formGroupApi,
4745
- handleSubmit: ((...props) => {
4746
- return formGroupApi._handleSubmit(...props);
4747
- }),
4748
- get state() {
4749
- return {
4750
- ...formGroupApi.state,
4751
- value: reactiveStateValue,
4752
- get meta() {
4753
- return {
4754
- ...formGroupApi.state.meta,
4755
- isTouched: reactiveMetaIsTouched,
4756
- isBlurred: reactiveMetaIsBlurred,
4757
- isDirty: reactiveMetaIsDirty,
4758
- errorMap: reactiveMetaErrorMap,
4759
- errorSourceMap: reactiveMetaErrorSourceMap,
4760
- isValidating: reactiveMetaIsValidating,
4761
- isSubmitting: reactiveMetaIsSubmitting,
4762
- isSubmitted: reactiveMetaIsSubmitted,
4763
- submissionAttempts: reactiveMetaSubmissionAttempts,
4764
- isSubmitSuccessful: reactiveMetaIsSubmitSuccessful,
4765
- canSubmit: reactiveMetaCanSubmit,
4766
- isValid: reactiveMetaIsValid,
4767
- isFieldsValid: reactiveMetaIsFieldsValid,
4768
- isFieldsValidating: reactiveMetaIsFieldsValidating,
4769
- isGroupValid: reactiveMetaIsGroupValid
4770
- };
4771
- }
4772
- };
4773
- }
4774
- };
4775
- const extendedApi = reactiveFieldApi;
4776
- return extendedApi;
4777
- }, [
4778
- formGroupApi,
4779
- reactiveStateValue,
4780
- reactiveMetaIsTouched,
4781
- reactiveMetaIsBlurred,
4782
- reactiveMetaIsDirty,
4783
- reactiveMetaErrorMap,
4784
- reactiveMetaErrorSourceMap,
4785
- reactiveMetaIsValidating,
4786
- reactiveMetaIsSubmitting,
4787
- reactiveMetaIsSubmitted,
4788
- reactiveMetaSubmissionAttempts,
4789
- reactiveMetaIsSubmitSuccessful,
4790
- reactiveMetaCanSubmit,
4791
- reactiveMetaIsValid,
4792
- reactiveMetaIsFieldsValid,
4793
- reactiveMetaIsFieldsValidating,
4794
- reactiveMetaIsGroupValid
4795
- ]);
4796
- useIsomorphicLayoutEffect(formGroupApi.mount, [formGroupApi]);
4797
- useIsomorphicLayoutEffect(() => {
4798
- formGroupApi.update(opts);
4799
- });
4800
- return extendedFieldApi;
4801
- }
4802
- var FormGroup = (({
4803
- children,
4804
- ...formGroupOptions
4805
- }) => {
4806
- const formGroupApi = useFormGroup(formGroupOptions);
4807
- const jsxToDisplay = useMemo(
4808
- () => functionalUpdate(children, formGroupApi),
4809
- [children, formGroupApi]
4810
- );
4811
- return /* @__PURE__ */ jsx(Fragment, { children: jsxToDisplay });
4812
- });
4813
-
4814
- // ../../node_modules/.pnpm/@tanstack+react-form@1.33.0_react-dom@19.2.7_react@19.2.7__react@19.2.7/node_modules/@tanstack/react-form/dist/esm/useForm.js
4815
- function LocalSubscribe({
4816
- form,
4817
- selector = (state) => state,
4818
- children
4819
- }) {
4820
- const data = useStore(form.store, selector);
4821
- return /* @__PURE__ */ jsx(Fragment, { children: functionalUpdate(children, data) });
4822
- }
4823
- function useForm(opts) {
4824
- const fallbackFormId = useFormId();
4825
- const [prevFormId, setPrevFormId] = useState(opts?.formId);
4826
- const [formApi, setFormApi] = useState(() => {
4827
- return new FormApi({ ...opts, formId: opts?.formId ?? fallbackFormId });
4828
- });
4829
- if (prevFormId !== opts?.formId) {
4830
- const formId = opts?.formId ?? fallbackFormId;
4831
- setFormApi(new FormApi({ ...opts, formId }));
4832
- setPrevFormId(formId);
4833
- }
4834
- const extendedFormApi = useMemo(() => {
4835
- const extendedApi = {
4836
- ...formApi,
4837
- handleSubmit: ((...props) => {
4838
- return formApi._handleSubmit(...props);
4839
- }),
4840
- // We must add all `get`ters from `core`'s `FormApi` here, as otherwise the spread operator won't catch those
4841
- get formId() {
4842
- return formApi._formId;
4843
- },
4844
- get state() {
4845
- return formApi.store.state;
4846
- }
4847
- };
4848
- extendedApi.Field = function APIField(props) {
4849
- return /* @__PURE__ */ jsx(Field2, { ...props, form: formApi });
4850
- };
4851
- extendedApi.FormGroup = function APIFormGroup(props) {
4852
- return /* @__PURE__ */ jsx(FormGroup, { ...props, form: formApi });
4853
- };
4854
- extendedApi.Subscribe = function Subscribe(props) {
4855
- return /* @__PURE__ */ jsx(
4856
- LocalSubscribe,
4857
- {
4858
- form: formApi,
4859
- selector: props.selector,
4860
- children: props.children
4861
- }
4862
- );
4863
- };
4864
- return extendedApi;
4865
- }, [formApi]);
4866
- useIsomorphicLayoutEffect(formApi.mount, []);
4867
- useIsomorphicLayoutEffect(() => {
4868
- formApi.update(opts);
4869
- });
4870
- const hasRan = useRef(false);
4871
- useIsomorphicLayoutEffect(() => {
4872
- if (!hasRan.current) return;
4873
- if (!opts?.transform) return;
4874
- mergeAndUpdate(formApi, opts.transform);
4875
- }, [formApi, opts?.transform]);
4876
- useIsomorphicLayoutEffect(() => {
4877
- hasRan.current = true;
4878
- });
4879
- return extendedFormApi;
4880
- }
4881
- function LocalSubscribe2({
4882
- lens,
4883
- selector = (state) => state,
4884
- children
4885
- }) {
4886
- const data = useStore(lens.store, selector);
4887
- return /* @__PURE__ */ jsx(Fragment, { children: functionalUpdate(children, data) });
4888
- }
4889
- function useFieldGroup(opts) {
4890
- const [formLensApi] = useState(() => {
4891
- const api = new FieldGroupApi(opts);
4892
- const form = opts.form instanceof FieldGroupApi ? opts.form.form : opts.form;
4893
- const extendedApi = api;
4894
- extendedApi.AppForm = function AppForm(appFormProps) {
4895
- return /* @__PURE__ */ jsx(form.AppForm, { ...appFormProps });
4896
- };
4897
- extendedApi.AppField = function AppField(props) {
4898
- return /* @__PURE__ */ jsx(form.AppField, { ...formLensApi.getFormFieldOptions(props) });
4899
- };
4900
- extendedApi.Field = function Field3(props) {
4901
- return /* @__PURE__ */ jsx(form.Field, { ...formLensApi.getFormFieldOptions(props) });
4902
- };
4903
- extendedApi.Subscribe = function Subscribe(props) {
4904
- return /* @__PURE__ */ jsx(
4905
- LocalSubscribe2,
4906
- {
4907
- lens: formLensApi,
4908
- selector: props.selector,
4909
- children: props.children
4910
- }
4911
- );
4912
- };
4913
- return Object.assign(extendedApi, {
4914
- ...opts.formComponents
4915
- });
4916
- });
4917
- useIsomorphicLayoutEffect(formLensApi.mount, [formLensApi]);
4918
- return formLensApi;
4919
- }
4920
-
4921
- // ../../node_modules/.pnpm/@tanstack+react-form@1.33.0_react-dom@19.2.7_react@19.2.7__react@19.2.7/node_modules/@tanstack/react-form/dist/esm/createFormHook.js
4922
- var fieldContext = createContext(null);
4923
- var formContext = createContext(null);
4924
- function useFormContext() {
4925
- const form = useContext(formContext);
4926
- if (!form) {
4927
- throw new Error(
4928
- "`formContext` only works when within a `formComponent` passed to `createFormHook`"
4929
- );
4930
- }
4931
- return form;
4932
- }
4933
- function createFormHookContexts() {
4934
- function useFieldContext() {
4935
- const field = useContext(fieldContext);
4936
- if (!field) {
4937
- throw new Error(
4938
- "`fieldContext` only works when within a `fieldComponent` passed to `createFormHook`"
4939
- );
4940
- }
4941
- return field;
4942
- }
4943
- return { fieldContext, useFieldContext, useFormContext, formContext };
4944
- }
4945
- function createFormHook({
4946
- fieldComponents,
4947
- fieldContext: fieldContext2,
4948
- formContext: formContext2,
4949
- formComponents
4950
- }) {
4951
- function useAppForm2(props) {
4952
- const form = useForm(props);
4953
- const AppForm = useMemo(() => {
4954
- return ({ children }) => {
4955
- return /* @__PURE__ */ jsx(formContext2.Provider, { value: form, children });
4956
- };
4957
- }, [form]);
4958
- const AppField = useMemo(() => {
4959
- const AppField2 = (({ children, ...props2 }) => {
4960
- return /* @__PURE__ */ jsx(form.Field, { ...props2, children: (field) => /* @__PURE__ */ jsx(fieldContext2.Provider, { value: field, children: children(Object.assign(field, fieldComponents)) }) });
4961
- });
4962
- return AppField2;
4963
- }, [form]);
4964
- const extendedForm = useMemo(() => {
4965
- return Object.assign(form, {
4966
- AppField,
4967
- AppForm,
4968
- ...formComponents
4969
- });
4970
- }, [form, AppField, AppForm]);
4971
- return extendedForm;
4972
- }
4973
- function withForm({
4974
- render,
4975
- props
4976
- }) {
4977
- return function Render(innerProps) {
4978
- return render({ ...props, ...innerProps });
4979
- };
4980
- }
4981
- function withFieldGroup({
4982
- render,
4983
- props,
4984
- defaultValues
4985
- }) {
4986
- return function Render(innerProps) {
4987
- const fieldGroupProps = useMemo(() => {
4988
- return {
4989
- form: innerProps.form,
4990
- fields: innerProps.fields,
4991
- defaultValues,
4992
- formComponents
4993
- };
4994
- }, [innerProps.form, innerProps.fields]);
4995
- const fieldGroupApi = useFieldGroup(fieldGroupProps);
4996
- return render({ ...props, ...innerProps, group: fieldGroupApi });
4997
- };
4998
- }
4999
- function useTypedAppFormContext(_props) {
5000
- const form = useFormContext();
5001
- return form;
5002
- }
5003
- function extendForm(extension) {
5004
- return createFormHook({
5005
- fieldContext: fieldContext2,
5006
- formContext: formContext2,
5007
- fieldComponents: {
5008
- ...fieldComponents,
5009
- ...extension.fieldComponents
5010
- },
5011
- formComponents: {
5012
- ...formComponents,
5013
- ...extension.formComponents
5014
- }
5015
- });
5016
- }
5017
- return {
5018
- useAppForm: useAppForm2,
5019
- withForm,
5020
- withFieldGroup,
5021
- useTypedAppFormContext,
5022
- extendForm
5023
- };
5024
- }
5025
-
5026
- // src/components/form/form-context.ts
5027
176
  var {
5028
177
  fieldContext: appFieldContext,
5029
178
  formContext: appFormContext,