@angular/forms 21.0.0-rc.2 → 21.0.0-rc.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,1509 @@
1
+ /**
2
+ * @license Angular v21.0.0-rc.3
3
+ * (c) 2010-2025 Google LLC. https://angular.dev/
4
+ * License: MIT
5
+ */
6
+
7
+ import { computed, untracked, runInInjectionContext, linkedSignal, Injector, signal, APP_ID, effect, inject } from '@angular/core';
8
+ import { AbstractControl } from '@angular/forms';
9
+ import { SIGNAL } from '@angular/core/primitives/signals';
10
+
11
+ function isArray(value) {
12
+ return Array.isArray(value);
13
+ }
14
+ function isObject(value) {
15
+ return (typeof value === 'object' || typeof value === 'function') && value != null;
16
+ }
17
+
18
+ function reduceChildren(node, initialValue, fn, shortCircuit) {
19
+ const childrenMap = node.structure.childrenMap();
20
+ if (!childrenMap) {
21
+ return initialValue;
22
+ }
23
+ let value = initialValue;
24
+ for (const child of childrenMap.values()) {
25
+ if (shortCircuit?.(value)) {
26
+ break;
27
+ }
28
+ value = fn(child, value);
29
+ }
30
+ return value;
31
+ }
32
+ function shortCircuitFalse(value) {
33
+ return !value;
34
+ }
35
+ function shortCircuitTrue(value) {
36
+ return value;
37
+ }
38
+ function getInjectorFromOptions(options) {
39
+ if (options.kind === 'root') {
40
+ return options.fieldManager.injector;
41
+ }
42
+ return options.parent.structure.root.structure.injector;
43
+ }
44
+
45
+ function calculateValidationSelfStatus(state) {
46
+ if (state.errors().length > 0) {
47
+ return 'invalid';
48
+ }
49
+ if (state.pending()) {
50
+ return 'unknown';
51
+ }
52
+ return 'valid';
53
+ }
54
+ class FieldValidationState {
55
+ node;
56
+ constructor(node) {
57
+ this.node = node;
58
+ }
59
+ rawSyncTreeErrors = computed(() => {
60
+ if (this.shouldSkipValidation()) {
61
+ return [];
62
+ }
63
+ return [...this.node.logicNode.logic.syncTreeErrors.compute(this.node.context), ...(this.node.structure.parent?.validationState.rawSyncTreeErrors() ?? [])];
64
+ }, ...(ngDevMode ? [{
65
+ debugName: "rawSyncTreeErrors"
66
+ }] : []));
67
+ syncErrors = computed(() => {
68
+ if (this.shouldSkipValidation()) {
69
+ return [];
70
+ }
71
+ return [...this.node.logicNode.logic.syncErrors.compute(this.node.context), ...this.syncTreeErrors(), ...normalizeErrors(this.node.submitState.serverErrors())];
72
+ }, ...(ngDevMode ? [{
73
+ debugName: "syncErrors"
74
+ }] : []));
75
+ syncValid = computed(() => {
76
+ if (this.shouldSkipValidation()) {
77
+ return true;
78
+ }
79
+ return reduceChildren(this.node, this.syncErrors().length === 0, (child, value) => value && child.validationState.syncValid(), shortCircuitFalse);
80
+ }, ...(ngDevMode ? [{
81
+ debugName: "syncValid"
82
+ }] : []));
83
+ syncTreeErrors = computed(() => this.rawSyncTreeErrors().filter(err => err.field === this.node.fieldProxy), ...(ngDevMode ? [{
84
+ debugName: "syncTreeErrors"
85
+ }] : []));
86
+ rawAsyncErrors = computed(() => {
87
+ if (this.shouldSkipValidation()) {
88
+ return [];
89
+ }
90
+ return [...this.node.logicNode.logic.asyncErrors.compute(this.node.context), ...(this.node.structure.parent?.validationState.rawAsyncErrors() ?? [])];
91
+ }, ...(ngDevMode ? [{
92
+ debugName: "rawAsyncErrors"
93
+ }] : []));
94
+ asyncErrors = computed(() => {
95
+ if (this.shouldSkipValidation()) {
96
+ return [];
97
+ }
98
+ return this.rawAsyncErrors().filter(err => err === 'pending' || err.field === this.node.fieldProxy);
99
+ }, ...(ngDevMode ? [{
100
+ debugName: "asyncErrors"
101
+ }] : []));
102
+ errors = computed(() => [...this.syncErrors(), ...this.asyncErrors().filter(err => err !== 'pending')], ...(ngDevMode ? [{
103
+ debugName: "errors"
104
+ }] : []));
105
+ errorSummary = computed(() => reduceChildren(this.node, this.errors(), (child, result) => [...result, ...child.errorSummary()]), ...(ngDevMode ? [{
106
+ debugName: "errorSummary"
107
+ }] : []));
108
+ pending = computed(() => reduceChildren(this.node, this.asyncErrors().includes('pending'), (child, value) => value || child.validationState.asyncErrors().includes('pending')), ...(ngDevMode ? [{
109
+ debugName: "pending"
110
+ }] : []));
111
+ status = computed(() => {
112
+ if (this.shouldSkipValidation()) {
113
+ return 'valid';
114
+ }
115
+ let ownStatus = calculateValidationSelfStatus(this);
116
+ return reduceChildren(this.node, ownStatus, (child, value) => {
117
+ if (value === 'invalid' || child.validationState.status() === 'invalid') {
118
+ return 'invalid';
119
+ } else if (value === 'unknown' || child.validationState.status() === 'unknown') {
120
+ return 'unknown';
121
+ }
122
+ return 'valid';
123
+ }, v => v === 'invalid');
124
+ }, ...(ngDevMode ? [{
125
+ debugName: "status"
126
+ }] : []));
127
+ valid = computed(() => this.status() === 'valid', ...(ngDevMode ? [{
128
+ debugName: "valid"
129
+ }] : []));
130
+ invalid = computed(() => this.status() === 'invalid', ...(ngDevMode ? [{
131
+ debugName: "invalid"
132
+ }] : []));
133
+ shouldSkipValidation = computed(() => this.node.hidden() || this.node.disabled() || this.node.readonly(), ...(ngDevMode ? [{
134
+ debugName: "shouldSkipValidation"
135
+ }] : []));
136
+ }
137
+ function normalizeErrors(error) {
138
+ if (error === undefined) {
139
+ return [];
140
+ }
141
+ if (isArray(error)) {
142
+ return error;
143
+ }
144
+ return [error];
145
+ }
146
+ function addDefaultField(errors, field) {
147
+ if (isArray(errors)) {
148
+ for (const error of errors) {
149
+ error.field ??= field;
150
+ }
151
+ } else if (errors) {
152
+ errors.field ??= field;
153
+ }
154
+ return errors;
155
+ }
156
+
157
+ let boundPathDepth = 0;
158
+ function getBoundPathDepth() {
159
+ return boundPathDepth;
160
+ }
161
+ function setBoundPathDepthForResolution(fn, depth) {
162
+ return (...args) => {
163
+ try {
164
+ boundPathDepth = depth;
165
+ return fn(...args);
166
+ } finally {
167
+ boundPathDepth = 0;
168
+ }
169
+ };
170
+ }
171
+
172
+ const DYNAMIC = Symbol();
173
+ const IGNORED = Symbol();
174
+ class AbstractLogic {
175
+ predicates;
176
+ fns = [];
177
+ constructor(predicates) {
178
+ this.predicates = predicates;
179
+ }
180
+ push(logicFn) {
181
+ this.fns.push(wrapWithPredicates(this.predicates, logicFn));
182
+ }
183
+ mergeIn(other) {
184
+ const fns = this.predicates ? other.fns.map(fn => wrapWithPredicates(this.predicates, fn)) : other.fns;
185
+ this.fns.push(...fns);
186
+ }
187
+ }
188
+ class BooleanOrLogic extends AbstractLogic {
189
+ get defaultValue() {
190
+ return false;
191
+ }
192
+ compute(arg) {
193
+ return this.fns.some(f => {
194
+ const result = f(arg);
195
+ return result && result !== IGNORED;
196
+ });
197
+ }
198
+ }
199
+ class ArrayMergeIgnoreLogic extends AbstractLogic {
200
+ ignore;
201
+ static ignoreNull(predicates) {
202
+ return new ArrayMergeIgnoreLogic(predicates, e => e === null);
203
+ }
204
+ constructor(predicates, ignore) {
205
+ super(predicates);
206
+ this.ignore = ignore;
207
+ }
208
+ get defaultValue() {
209
+ return [];
210
+ }
211
+ compute(arg) {
212
+ return this.fns.reduce((prev, f) => {
213
+ const value = f(arg);
214
+ if (value === undefined || value === IGNORED) {
215
+ return prev;
216
+ } else if (isArray(value)) {
217
+ return [...prev, ...(this.ignore ? value.filter(e => !this.ignore(e)) : value)];
218
+ } else {
219
+ if (this.ignore && this.ignore(value)) {
220
+ return prev;
221
+ }
222
+ return [...prev, value];
223
+ }
224
+ }, []);
225
+ }
226
+ }
227
+ class ArrayMergeLogic extends ArrayMergeIgnoreLogic {
228
+ constructor(predicates) {
229
+ super(predicates, undefined);
230
+ }
231
+ }
232
+ class AggregateMetadataMergeLogic extends AbstractLogic {
233
+ key;
234
+ get defaultValue() {
235
+ return this.key.getInitial();
236
+ }
237
+ constructor(predicates, key) {
238
+ super(predicates);
239
+ this.key = key;
240
+ }
241
+ compute(ctx) {
242
+ if (this.fns.length === 0) {
243
+ return this.key.getInitial();
244
+ }
245
+ let acc = this.key.getInitial();
246
+ for (let i = 0; i < this.fns.length; i++) {
247
+ const item = this.fns[i](ctx);
248
+ if (item !== IGNORED) {
249
+ acc = this.key.reduce(acc, item);
250
+ }
251
+ }
252
+ return acc;
253
+ }
254
+ }
255
+ function wrapWithPredicates(predicates, logicFn) {
256
+ if (predicates.length === 0) {
257
+ return logicFn;
258
+ }
259
+ return arg => {
260
+ for (const predicate of predicates) {
261
+ let predicateField = arg.stateOf(predicate.path);
262
+ const depthDiff = untracked(predicateField.structure.pathKeys).length - predicate.depth;
263
+ for (let i = 0; i < depthDiff; i++) {
264
+ predicateField = predicateField.structure.parent;
265
+ }
266
+ if (!predicate.fn(predicateField.context)) {
267
+ return IGNORED;
268
+ }
269
+ }
270
+ return logicFn(arg);
271
+ };
272
+ }
273
+ class LogicContainer {
274
+ predicates;
275
+ hidden;
276
+ disabledReasons;
277
+ readonly;
278
+ syncErrors;
279
+ syncTreeErrors;
280
+ asyncErrors;
281
+ aggregateMetadataKeys = new Map();
282
+ metadataFactories = new Map();
283
+ constructor(predicates) {
284
+ this.predicates = predicates;
285
+ this.hidden = new BooleanOrLogic(predicates);
286
+ this.disabledReasons = new ArrayMergeLogic(predicates);
287
+ this.readonly = new BooleanOrLogic(predicates);
288
+ this.syncErrors = ArrayMergeIgnoreLogic.ignoreNull(predicates);
289
+ this.syncTreeErrors = ArrayMergeIgnoreLogic.ignoreNull(predicates);
290
+ this.asyncErrors = ArrayMergeIgnoreLogic.ignoreNull(predicates);
291
+ }
292
+ hasAggregateMetadata(key) {
293
+ return this.aggregateMetadataKeys.has(key);
294
+ }
295
+ getAggregateMetadataEntries() {
296
+ return this.aggregateMetadataKeys.entries();
297
+ }
298
+ getMetadataFactoryEntries() {
299
+ return this.metadataFactories.entries();
300
+ }
301
+ getAggregateMetadata(key) {
302
+ if (!this.aggregateMetadataKeys.has(key)) {
303
+ this.aggregateMetadataKeys.set(key, new AggregateMetadataMergeLogic(this.predicates, key));
304
+ }
305
+ return this.aggregateMetadataKeys.get(key);
306
+ }
307
+ addMetadataFactory(key, factory) {
308
+ if (this.metadataFactories.has(key)) {
309
+ throw new Error(`Can't define value twice for the same MetadataKey`);
310
+ }
311
+ this.metadataFactories.set(key, factory);
312
+ }
313
+ mergeIn(other) {
314
+ this.hidden.mergeIn(other.hidden);
315
+ this.disabledReasons.mergeIn(other.disabledReasons);
316
+ this.readonly.mergeIn(other.readonly);
317
+ this.syncErrors.mergeIn(other.syncErrors);
318
+ this.syncTreeErrors.mergeIn(other.syncTreeErrors);
319
+ this.asyncErrors.mergeIn(other.asyncErrors);
320
+ for (const [key, metadataLogic] of other.getAggregateMetadataEntries()) {
321
+ this.getAggregateMetadata(key).mergeIn(metadataLogic);
322
+ }
323
+ for (const [key, metadataFactory] of other.getMetadataFactoryEntries()) {
324
+ this.addMetadataFactory(key, metadataFactory);
325
+ }
326
+ }
327
+ }
328
+
329
+ class AbstractLogicNodeBuilder {
330
+ depth;
331
+ constructor(depth) {
332
+ this.depth = depth;
333
+ }
334
+ build() {
335
+ return new LeafLogicNode(this, [], 0);
336
+ }
337
+ }
338
+ class LogicNodeBuilder extends AbstractLogicNodeBuilder {
339
+ constructor(depth) {
340
+ super(depth);
341
+ }
342
+ current;
343
+ all = [];
344
+ addHiddenRule(logic) {
345
+ this.getCurrent().addHiddenRule(logic);
346
+ }
347
+ addDisabledReasonRule(logic) {
348
+ this.getCurrent().addDisabledReasonRule(logic);
349
+ }
350
+ addReadonlyRule(logic) {
351
+ this.getCurrent().addReadonlyRule(logic);
352
+ }
353
+ addSyncErrorRule(logic) {
354
+ this.getCurrent().addSyncErrorRule(logic);
355
+ }
356
+ addSyncTreeErrorRule(logic) {
357
+ this.getCurrent().addSyncTreeErrorRule(logic);
358
+ }
359
+ addAsyncErrorRule(logic) {
360
+ this.getCurrent().addAsyncErrorRule(logic);
361
+ }
362
+ addAggregateMetadataRule(key, logic) {
363
+ this.getCurrent().addAggregateMetadataRule(key, logic);
364
+ }
365
+ addMetadataFactory(key, factory) {
366
+ this.getCurrent().addMetadataFactory(key, factory);
367
+ }
368
+ getChild(key) {
369
+ if (key === DYNAMIC) {
370
+ const children = this.getCurrent().children;
371
+ if (children.size > (children.has(DYNAMIC) ? 1 : 0)) {
372
+ this.current = undefined;
373
+ }
374
+ }
375
+ return this.getCurrent().getChild(key);
376
+ }
377
+ hasLogic(builder) {
378
+ if (this === builder) {
379
+ return true;
380
+ }
381
+ return this.all.some(({
382
+ builder: subBuilder
383
+ }) => subBuilder.hasLogic(builder));
384
+ }
385
+ mergeIn(other, predicate) {
386
+ if (predicate) {
387
+ this.all.push({
388
+ builder: other,
389
+ predicate: {
390
+ fn: setBoundPathDepthForResolution(predicate.fn, this.depth),
391
+ path: predicate.path
392
+ }
393
+ });
394
+ } else {
395
+ this.all.push({
396
+ builder: other
397
+ });
398
+ }
399
+ this.current = undefined;
400
+ }
401
+ getCurrent() {
402
+ if (this.current === undefined) {
403
+ this.current = new NonMergeableLogicNodeBuilder(this.depth);
404
+ this.all.push({
405
+ builder: this.current
406
+ });
407
+ }
408
+ return this.current;
409
+ }
410
+ static newRoot() {
411
+ return new LogicNodeBuilder(0);
412
+ }
413
+ }
414
+ class NonMergeableLogicNodeBuilder extends AbstractLogicNodeBuilder {
415
+ logic = new LogicContainer([]);
416
+ children = new Map();
417
+ constructor(depth) {
418
+ super(depth);
419
+ }
420
+ addHiddenRule(logic) {
421
+ this.logic.hidden.push(setBoundPathDepthForResolution(logic, this.depth));
422
+ }
423
+ addDisabledReasonRule(logic) {
424
+ this.logic.disabledReasons.push(setBoundPathDepthForResolution(logic, this.depth));
425
+ }
426
+ addReadonlyRule(logic) {
427
+ this.logic.readonly.push(setBoundPathDepthForResolution(logic, this.depth));
428
+ }
429
+ addSyncErrorRule(logic) {
430
+ this.logic.syncErrors.push(setBoundPathDepthForResolution(logic, this.depth));
431
+ }
432
+ addSyncTreeErrorRule(logic) {
433
+ this.logic.syncTreeErrors.push(setBoundPathDepthForResolution(logic, this.depth));
434
+ }
435
+ addAsyncErrorRule(logic) {
436
+ this.logic.asyncErrors.push(setBoundPathDepthForResolution(logic, this.depth));
437
+ }
438
+ addAggregateMetadataRule(key, logic) {
439
+ this.logic.getAggregateMetadata(key).push(setBoundPathDepthForResolution(logic, this.depth));
440
+ }
441
+ addMetadataFactory(key, factory) {
442
+ this.logic.addMetadataFactory(key, setBoundPathDepthForResolution(factory, this.depth));
443
+ }
444
+ getChild(key) {
445
+ if (!this.children.has(key)) {
446
+ this.children.set(key, new LogicNodeBuilder(this.depth + 1));
447
+ }
448
+ return this.children.get(key);
449
+ }
450
+ hasLogic(builder) {
451
+ return this === builder;
452
+ }
453
+ }
454
+ class LeafLogicNode {
455
+ builder;
456
+ predicates;
457
+ depth;
458
+ logic;
459
+ constructor(builder, predicates, depth) {
460
+ this.builder = builder;
461
+ this.predicates = predicates;
462
+ this.depth = depth;
463
+ this.logic = builder ? createLogic(builder, predicates, depth) : new LogicContainer([]);
464
+ }
465
+ getChild(key) {
466
+ const childBuilders = this.builder ? getAllChildBuilders(this.builder, key) : [];
467
+ if (childBuilders.length === 0) {
468
+ return new LeafLogicNode(undefined, [], this.depth + 1);
469
+ } else if (childBuilders.length === 1) {
470
+ const {
471
+ builder,
472
+ predicates
473
+ } = childBuilders[0];
474
+ return new LeafLogicNode(builder, [...this.predicates, ...predicates.map(p => bindLevel(p, this.depth))], this.depth + 1);
475
+ } else {
476
+ const builtNodes = childBuilders.map(({
477
+ builder,
478
+ predicates
479
+ }) => new LeafLogicNode(builder, [...this.predicates, ...predicates.map(p => bindLevel(p, this.depth))], this.depth + 1));
480
+ return new CompositeLogicNode(builtNodes);
481
+ }
482
+ }
483
+ hasLogic(builder) {
484
+ return this.builder?.hasLogic(builder) ?? false;
485
+ }
486
+ }
487
+ class CompositeLogicNode {
488
+ all;
489
+ logic;
490
+ constructor(all) {
491
+ this.all = all;
492
+ this.logic = new LogicContainer([]);
493
+ for (const node of all) {
494
+ this.logic.mergeIn(node.logic);
495
+ }
496
+ }
497
+ getChild(key) {
498
+ return new CompositeLogicNode(this.all.flatMap(child => child.getChild(key)));
499
+ }
500
+ hasLogic(builder) {
501
+ return this.all.some(node => node.hasLogic(builder));
502
+ }
503
+ }
504
+ function getAllChildBuilders(builder, key) {
505
+ if (builder instanceof LogicNodeBuilder) {
506
+ return builder.all.flatMap(({
507
+ builder,
508
+ predicate
509
+ }) => {
510
+ const children = getAllChildBuilders(builder, key);
511
+ if (predicate) {
512
+ return children.map(({
513
+ builder,
514
+ predicates
515
+ }) => ({
516
+ builder,
517
+ predicates: [...predicates, predicate]
518
+ }));
519
+ }
520
+ return children;
521
+ });
522
+ } else if (builder instanceof NonMergeableLogicNodeBuilder) {
523
+ return [...(key !== DYNAMIC && builder.children.has(DYNAMIC) ? [{
524
+ builder: builder.getChild(DYNAMIC),
525
+ predicates: []
526
+ }] : []), ...(builder.children.has(key) ? [{
527
+ builder: builder.getChild(key),
528
+ predicates: []
529
+ }] : [])];
530
+ } else {
531
+ throw new Error('Unknown LogicNodeBuilder type');
532
+ }
533
+ }
534
+ function createLogic(builder, predicates, depth) {
535
+ const logic = new LogicContainer(predicates);
536
+ if (builder instanceof LogicNodeBuilder) {
537
+ const builtNodes = builder.all.map(({
538
+ builder,
539
+ predicate
540
+ }) => new LeafLogicNode(builder, predicate ? [...predicates, bindLevel(predicate, depth)] : predicates, depth));
541
+ for (const node of builtNodes) {
542
+ logic.mergeIn(node.logic);
543
+ }
544
+ } else if (builder instanceof NonMergeableLogicNodeBuilder) {
545
+ logic.mergeIn(builder.logic);
546
+ } else {
547
+ throw new Error('Unknown LogicNodeBuilder type');
548
+ }
549
+ return logic;
550
+ }
551
+ function bindLevel(predicate, depth) {
552
+ return {
553
+ ...predicate,
554
+ depth: depth
555
+ };
556
+ }
557
+
558
+ const PATH = Symbol('PATH');
559
+ class FieldPathNode {
560
+ keys;
561
+ parent;
562
+ keyInParent;
563
+ root;
564
+ children = new Map();
565
+ fieldPathProxy = new Proxy(this, FIELD_PATH_PROXY_HANDLER);
566
+ logicBuilder;
567
+ constructor(keys, root, parent, keyInParent) {
568
+ this.keys = keys;
569
+ this.parent = parent;
570
+ this.keyInParent = keyInParent;
571
+ this.root = root ?? this;
572
+ if (!parent) {
573
+ this.logicBuilder = LogicNodeBuilder.newRoot();
574
+ }
575
+ }
576
+ get builder() {
577
+ if (this.logicBuilder) {
578
+ return this.logicBuilder;
579
+ }
580
+ return this.parent.builder.getChild(this.keyInParent);
581
+ }
582
+ getChild(key) {
583
+ if (!this.children.has(key)) {
584
+ this.children.set(key, new FieldPathNode([...this.keys, key], this.root, this, key));
585
+ }
586
+ return this.children.get(key);
587
+ }
588
+ mergeIn(other, predicate) {
589
+ const path = other.compile();
590
+ this.builder.mergeIn(path.builder, predicate);
591
+ }
592
+ static unwrapFieldPath(formPath) {
593
+ return formPath[PATH];
594
+ }
595
+ static newRoot() {
596
+ return new FieldPathNode([], undefined, undefined, undefined);
597
+ }
598
+ }
599
+ const FIELD_PATH_PROXY_HANDLER = {
600
+ get(node, property) {
601
+ if (property === PATH) {
602
+ return node;
603
+ }
604
+ return node.getChild(property).fieldPathProxy;
605
+ }
606
+ };
607
+
608
+ let currentCompilingNode = undefined;
609
+ const compiledSchemas = new Map();
610
+ class SchemaImpl {
611
+ schemaFn;
612
+ constructor(schemaFn) {
613
+ this.schemaFn = schemaFn;
614
+ }
615
+ compile() {
616
+ if (compiledSchemas.has(this)) {
617
+ return compiledSchemas.get(this);
618
+ }
619
+ const path = FieldPathNode.newRoot();
620
+ compiledSchemas.set(this, path);
621
+ let prevCompilingNode = currentCompilingNode;
622
+ try {
623
+ currentCompilingNode = path;
624
+ this.schemaFn(path.fieldPathProxy);
625
+ } finally {
626
+ currentCompilingNode = prevCompilingNode;
627
+ }
628
+ return path;
629
+ }
630
+ static create(schema) {
631
+ if (schema instanceof SchemaImpl) {
632
+ return schema;
633
+ }
634
+ return new SchemaImpl(schema);
635
+ }
636
+ static rootCompile(schema) {
637
+ try {
638
+ compiledSchemas.clear();
639
+ if (schema === undefined) {
640
+ return FieldPathNode.newRoot();
641
+ }
642
+ if (schema instanceof SchemaImpl) {
643
+ return schema.compile();
644
+ }
645
+ return new SchemaImpl(schema).compile();
646
+ } finally {
647
+ compiledSchemas.clear();
648
+ }
649
+ }
650
+ }
651
+ function isSchemaOrSchemaFn(value) {
652
+ return value instanceof SchemaImpl || typeof value === 'function';
653
+ }
654
+ function assertPathIsCurrent(path) {
655
+ if (currentCompilingNode !== FieldPathNode.unwrapFieldPath(path).root) {
656
+ throw new Error(`A FieldPath can only be used directly within the Schema that owns it,` + ` **not** outside of it or within a sub-schema.`);
657
+ }
658
+ }
659
+
660
+ class MetadataKey {
661
+ brand;
662
+ constructor() {}
663
+ }
664
+ function createMetadataKey() {
665
+ return new MetadataKey();
666
+ }
667
+ class AggregateMetadataKey {
668
+ reduce;
669
+ getInitial;
670
+ brand;
671
+ constructor(reduce, getInitial) {
672
+ this.reduce = reduce;
673
+ this.getInitial = getInitial;
674
+ }
675
+ }
676
+ function reducedMetadataKey(reduce, getInitial) {
677
+ return new AggregateMetadataKey(reduce, getInitial);
678
+ }
679
+ function listMetadataKey() {
680
+ return reducedMetadataKey((acc, item) => item === undefined ? acc : [...acc, item], () => []);
681
+ }
682
+ function minMetadataKey() {
683
+ return reducedMetadataKey((prev, next) => {
684
+ if (prev === undefined) {
685
+ return next;
686
+ }
687
+ if (next === undefined) {
688
+ return prev;
689
+ }
690
+ return Math.min(prev, next);
691
+ }, () => undefined);
692
+ }
693
+ function maxMetadataKey() {
694
+ return reducedMetadataKey((prev, next) => {
695
+ if (prev === undefined) {
696
+ return next;
697
+ }
698
+ if (next === undefined) {
699
+ return prev;
700
+ }
701
+ return Math.max(prev, next);
702
+ }, () => undefined);
703
+ }
704
+ function orMetadataKey() {
705
+ return reducedMetadataKey((prev, next) => prev || next, () => false);
706
+ }
707
+ function andMetadataKey() {
708
+ return reducedMetadataKey((prev, next) => prev && next, () => true);
709
+ }
710
+ const REQUIRED = orMetadataKey();
711
+ const MIN = maxMetadataKey();
712
+ const MAX = minMetadataKey();
713
+ const MIN_LENGTH = maxMetadataKey();
714
+ const MAX_LENGTH = minMetadataKey();
715
+ const PATTERN = listMetadataKey();
716
+
717
+ const DEBOUNCER = reducedMetadataKey((_, item) => item, () => undefined);
718
+
719
+ class FieldNodeContext {
720
+ node;
721
+ cache = new WeakMap();
722
+ constructor(node) {
723
+ this.node = node;
724
+ }
725
+ resolve(target) {
726
+ if (!this.cache.has(target)) {
727
+ const resolver = computed(() => {
728
+ const targetPathNode = FieldPathNode.unwrapFieldPath(target);
729
+ let field = this.node;
730
+ let stepsRemaining = getBoundPathDepth();
731
+ while (stepsRemaining > 0 || !field.structure.logic.hasLogic(targetPathNode.root.builder)) {
732
+ stepsRemaining--;
733
+ field = field.structure.parent;
734
+ if (field === undefined) {
735
+ throw new Error('Path is not part of this field tree.');
736
+ }
737
+ }
738
+ for (let key of targetPathNode.keys) {
739
+ field = field.structure.getChild(key);
740
+ if (field === undefined) {
741
+ throw new Error(`Cannot resolve path .${targetPathNode.keys.join('.')} relative to field ${['<root>', ...this.node.structure.pathKeys()].join('.')}.`);
742
+ }
743
+ }
744
+ return field.fieldProxy;
745
+ }, ...(ngDevMode ? [{
746
+ debugName: "resolver"
747
+ }] : []));
748
+ this.cache.set(target, resolver);
749
+ }
750
+ return this.cache.get(target)();
751
+ }
752
+ get field() {
753
+ return this.node.fieldProxy;
754
+ }
755
+ get state() {
756
+ return this.node;
757
+ }
758
+ get value() {
759
+ return this.node.structure.value;
760
+ }
761
+ get key() {
762
+ return this.node.structure.keyInParent;
763
+ }
764
+ get pathKeys() {
765
+ return this.node.structure.pathKeys;
766
+ }
767
+ index = computed(() => {
768
+ const key = this.key();
769
+ if (!isArray(untracked(this.node.structure.parent.value))) {
770
+ throw new Error(`RuntimeError: cannot access index, parent field is not an array`);
771
+ }
772
+ return Number(key);
773
+ }, ...(ngDevMode ? [{
774
+ debugName: "index"
775
+ }] : []));
776
+ fieldTreeOf = p => this.resolve(p);
777
+ stateOf = p => this.resolve(p)();
778
+ valueOf = p => {
779
+ const result = this.resolve(p)().value();
780
+ if (result instanceof AbstractControl) {
781
+ throw new Error(`Tried to read an 'AbstractControl' value form a 'form()'. Did you mean to use 'compatForm()' instead?`);
782
+ }
783
+ return result;
784
+ };
785
+ }
786
+
787
+ class FieldMetadataState {
788
+ node;
789
+ metadata = new Map();
790
+ constructor(node) {
791
+ this.node = node;
792
+ untracked(() => runInInjectionContext(this.node.structure.injector, () => {
793
+ for (const [key, factory] of this.node.logicNode.logic.getMetadataFactoryEntries()) {
794
+ this.metadata.set(key, factory(this.node.context));
795
+ }
796
+ }));
797
+ }
798
+ get(key) {
799
+ if (key instanceof MetadataKey) {
800
+ return this.metadata.get(key);
801
+ }
802
+ if (!this.metadata.has(key)) {
803
+ const logic = this.node.logicNode.logic.getAggregateMetadata(key);
804
+ const result = computed(() => logic.compute(this.node.context), ...(ngDevMode ? [{
805
+ debugName: "result"
806
+ }] : []));
807
+ this.metadata.set(key, result);
808
+ }
809
+ return this.metadata.get(key);
810
+ }
811
+ has(key) {
812
+ if (key instanceof AggregateMetadataKey) {
813
+ return this.node.logicNode.logic.hasAggregateMetadata(key);
814
+ } else {
815
+ return this.metadata.has(key);
816
+ }
817
+ }
818
+ }
819
+
820
+ const FIELD_PROXY_HANDLER = {
821
+ get(getTgt, p, receiver) {
822
+ const tgt = getTgt();
823
+ const child = tgt.structure.getChild(p);
824
+ if (child !== undefined) {
825
+ return child.fieldProxy;
826
+ }
827
+ const value = untracked(tgt.value);
828
+ if (isArray(value)) {
829
+ if (p === 'length') {
830
+ return tgt.value().length;
831
+ }
832
+ if (p === Symbol.iterator) {
833
+ return Array.prototype[p];
834
+ }
835
+ }
836
+ if (isObject(value)) {
837
+ if (p === Symbol.iterator) {
838
+ return function* () {
839
+ for (const key in receiver) {
840
+ yield [key, receiver[key]];
841
+ }
842
+ };
843
+ }
844
+ }
845
+ return undefined;
846
+ },
847
+ getOwnPropertyDescriptor(getTgt, prop) {
848
+ const value = untracked(getTgt().value);
849
+ const desc = Reflect.getOwnPropertyDescriptor(value, prop);
850
+ if (desc && !desc.configurable) {
851
+ desc.configurable = true;
852
+ }
853
+ return desc;
854
+ },
855
+ ownKeys(getTgt) {
856
+ const value = untracked(getTgt().value);
857
+ return typeof value === 'object' && value !== null ? Reflect.ownKeys(value) : [];
858
+ }
859
+ };
860
+
861
+ function deepSignal(source, prop) {
862
+ const read = computed(() => source()[prop()]);
863
+ read[SIGNAL] = source[SIGNAL];
864
+ read.set = value => {
865
+ source.update(current => valueForWrite(current, value, prop()));
866
+ };
867
+ read.update = fn => {
868
+ read.set(fn(untracked(read)));
869
+ };
870
+ read.asReadonly = () => read;
871
+ return read;
872
+ }
873
+ function valueForWrite(sourceValue, newPropValue, prop) {
874
+ if (isArray(sourceValue)) {
875
+ const newValue = [...sourceValue];
876
+ newValue[prop] = newPropValue;
877
+ return newValue;
878
+ } else {
879
+ return {
880
+ ...sourceValue,
881
+ [prop]: newPropValue
882
+ };
883
+ }
884
+ }
885
+
886
+ class FieldNodeStructure {
887
+ logic;
888
+ identitySymbol = Symbol();
889
+ _injector = undefined;
890
+ get injector() {
891
+ this._injector ??= Injector.create({
892
+ providers: [],
893
+ parent: this.fieldManager.injector
894
+ });
895
+ return this._injector;
896
+ }
897
+ constructor(logic) {
898
+ this.logic = logic;
899
+ }
900
+ children() {
901
+ return this.childrenMap()?.values() ?? [];
902
+ }
903
+ getChild(key) {
904
+ const map = this.childrenMap();
905
+ const value = this.value();
906
+ if (!map || !isObject(value)) {
907
+ return undefined;
908
+ }
909
+ if (isArray(value)) {
910
+ const childValue = value[key];
911
+ if (isObject(childValue) && childValue.hasOwnProperty(this.identitySymbol)) {
912
+ key = childValue[this.identitySymbol];
913
+ }
914
+ }
915
+ return map.get(typeof key === 'number' ? key.toString() : key);
916
+ }
917
+ destroy() {
918
+ this.injector.destroy();
919
+ }
920
+ }
921
+ class RootFieldNodeStructure extends FieldNodeStructure {
922
+ node;
923
+ fieldManager;
924
+ value;
925
+ get parent() {
926
+ return undefined;
927
+ }
928
+ get root() {
929
+ return this.node;
930
+ }
931
+ get pathKeys() {
932
+ return ROOT_PATH_KEYS;
933
+ }
934
+ get keyInParent() {
935
+ return ROOT_KEY_IN_PARENT;
936
+ }
937
+ childrenMap;
938
+ constructor(node, pathNode, logic, fieldManager, value, adapter, createChildNode) {
939
+ super(logic);
940
+ this.node = node;
941
+ this.fieldManager = fieldManager;
942
+ this.value = value;
943
+ this.childrenMap = makeChildrenMapSignal(node, value, this.identitySymbol, pathNode, logic, adapter, createChildNode);
944
+ }
945
+ }
946
+ class ChildFieldNodeStructure extends FieldNodeStructure {
947
+ parent;
948
+ root;
949
+ pathKeys;
950
+ keyInParent;
951
+ value;
952
+ childrenMap;
953
+ get fieldManager() {
954
+ return this.root.structure.fieldManager;
955
+ }
956
+ constructor(node, pathNode, logic, parent, identityInParent, initialKeyInParent, adapter, createChildNode) {
957
+ super(logic);
958
+ this.parent = parent;
959
+ this.root = this.parent.structure.root;
960
+ this.pathKeys = computed(() => [...parent.structure.pathKeys(), this.keyInParent()], ...(ngDevMode ? [{
961
+ debugName: "pathKeys"
962
+ }] : []));
963
+ if (identityInParent === undefined) {
964
+ const key = initialKeyInParent;
965
+ this.keyInParent = computed(() => {
966
+ if (parent.structure.childrenMap()?.get(key) !== node) {
967
+ throw new Error(`RuntimeError: orphan field, looking for property '${key}' of ${getDebugName(parent)}`);
968
+ }
969
+ return key;
970
+ }, ...(ngDevMode ? [{
971
+ debugName: "keyInParent"
972
+ }] : []));
973
+ } else {
974
+ let lastKnownKey = initialKeyInParent;
975
+ this.keyInParent = computed(() => {
976
+ const parentValue = parent.structure.value();
977
+ if (!isArray(parentValue)) {
978
+ throw new Error(`RuntimeError: orphan field, expected ${getDebugName(parent)} to be an array`);
979
+ }
980
+ const data = parentValue[lastKnownKey];
981
+ if (isObject(data) && data.hasOwnProperty(parent.structure.identitySymbol) && data[parent.structure.identitySymbol] === identityInParent) {
982
+ return lastKnownKey;
983
+ }
984
+ for (let i = 0; i < parentValue.length; i++) {
985
+ const data = parentValue[i];
986
+ if (isObject(data) && data.hasOwnProperty(parent.structure.identitySymbol) && data[parent.structure.identitySymbol] === identityInParent) {
987
+ return lastKnownKey = i.toString();
988
+ }
989
+ }
990
+ throw new Error(`RuntimeError: orphan field, can't find element in array ${getDebugName(parent)}`);
991
+ }, ...(ngDevMode ? [{
992
+ debugName: "keyInParent"
993
+ }] : []));
994
+ }
995
+ this.value = deepSignal(this.parent.structure.value, this.keyInParent);
996
+ this.childrenMap = makeChildrenMapSignal(node, this.value, this.identitySymbol, pathNode, logic, adapter, createChildNode);
997
+ this.fieldManager.structures.add(this);
998
+ }
999
+ }
1000
+ let globalId = 0;
1001
+ const ROOT_PATH_KEYS = computed(() => [], ...(ngDevMode ? [{
1002
+ debugName: "ROOT_PATH_KEYS"
1003
+ }] : []));
1004
+ const ROOT_KEY_IN_PARENT = computed(() => {
1005
+ throw new Error(`RuntimeError: the top-level field in the form has no parent`);
1006
+ }, ...(ngDevMode ? [{
1007
+ debugName: "ROOT_KEY_IN_PARENT"
1008
+ }] : []));
1009
+ function makeChildrenMapSignal(node, valueSignal, identitySymbol, pathNode, logic, adapter, createChildNode) {
1010
+ return linkedSignal({
1011
+ source: valueSignal,
1012
+ computation: (value, previous) => {
1013
+ let childrenMap = previous?.value;
1014
+ if (!isObject(value)) {
1015
+ return undefined;
1016
+ }
1017
+ const isValueArray = isArray(value);
1018
+ if (childrenMap !== undefined) {
1019
+ let oldKeys = undefined;
1020
+ if (isValueArray) {
1021
+ oldKeys = new Set(childrenMap.keys());
1022
+ for (let i = 0; i < value.length; i++) {
1023
+ const childValue = value[i];
1024
+ if (isObject(childValue) && childValue.hasOwnProperty(identitySymbol)) {
1025
+ oldKeys.delete(childValue[identitySymbol]);
1026
+ } else {
1027
+ oldKeys.delete(i.toString());
1028
+ }
1029
+ }
1030
+ for (const key of oldKeys) {
1031
+ childrenMap.delete(key);
1032
+ }
1033
+ } else {
1034
+ for (let key of childrenMap.keys()) {
1035
+ if (!value.hasOwnProperty(key)) {
1036
+ childrenMap.delete(key);
1037
+ }
1038
+ }
1039
+ }
1040
+ }
1041
+ for (let key of Object.keys(value)) {
1042
+ let trackingId = undefined;
1043
+ const childValue = value[key];
1044
+ if (childValue === undefined) {
1045
+ childrenMap?.delete(key);
1046
+ continue;
1047
+ }
1048
+ if (isValueArray && isObject(childValue) && !isArray(childValue)) {
1049
+ trackingId = childValue[identitySymbol] ??= Symbol(ngDevMode ? `id:${globalId++}` : '');
1050
+ }
1051
+ const identity = trackingId ?? key;
1052
+ if (childrenMap?.has(identity)) {
1053
+ continue;
1054
+ }
1055
+ let childPath;
1056
+ let childLogic;
1057
+ if (isValueArray) {
1058
+ childPath = pathNode.getChild(DYNAMIC);
1059
+ childLogic = logic.getChild(DYNAMIC);
1060
+ } else {
1061
+ childPath = pathNode.getChild(key);
1062
+ childLogic = logic.getChild(key);
1063
+ }
1064
+ childrenMap ??= new Map();
1065
+ childrenMap.set(identity, createChildNode({
1066
+ kind: 'child',
1067
+ parent: node,
1068
+ pathNode: childPath,
1069
+ logic: childLogic,
1070
+ initialKeyInParent: key,
1071
+ identityInParent: trackingId,
1072
+ fieldAdapter: adapter
1073
+ }));
1074
+ }
1075
+ return childrenMap;
1076
+ },
1077
+ equal: () => false
1078
+ });
1079
+ }
1080
+ function getDebugName(node) {
1081
+ return `<root>.${node.structure.pathKeys().join('.')}`;
1082
+ }
1083
+
1084
+ class FieldSubmitState {
1085
+ node;
1086
+ selfSubmitting = signal(false, ...(ngDevMode ? [{
1087
+ debugName: "selfSubmitting"
1088
+ }] : []));
1089
+ serverErrors;
1090
+ constructor(node) {
1091
+ this.node = node;
1092
+ this.serverErrors = linkedSignal(...(ngDevMode ? [{
1093
+ debugName: "serverErrors",
1094
+ source: this.node.structure.value,
1095
+ computation: () => []
1096
+ }] : [{
1097
+ source: this.node.structure.value,
1098
+ computation: () => []
1099
+ }]));
1100
+ }
1101
+ submitting = computed(() => {
1102
+ return this.selfSubmitting() || (this.node.structure.parent?.submitting() ?? false);
1103
+ }, ...(ngDevMode ? [{
1104
+ debugName: "submitting"
1105
+ }] : []));
1106
+ }
1107
+
1108
+ class FieldNode {
1109
+ structure;
1110
+ validationState;
1111
+ metadataState;
1112
+ nodeState;
1113
+ submitState;
1114
+ fieldAdapter;
1115
+ _context = undefined;
1116
+ get context() {
1117
+ return this._context ??= new FieldNodeContext(this);
1118
+ }
1119
+ fieldProxy = new Proxy(() => this, FIELD_PROXY_HANDLER);
1120
+ constructor(options) {
1121
+ this.fieldAdapter = options.fieldAdapter;
1122
+ this.structure = this.fieldAdapter.createStructure(this, options);
1123
+ this.validationState = this.fieldAdapter.createValidationState(this, options);
1124
+ this.nodeState = this.fieldAdapter.createNodeState(this, options);
1125
+ this.metadataState = new FieldMetadataState(this);
1126
+ this.submitState = new FieldSubmitState(this);
1127
+ }
1128
+ pendingSync = linkedSignal(...(ngDevMode ? [{
1129
+ debugName: "pendingSync",
1130
+ source: () => this.value(),
1131
+ computation: (_source, previous) => {
1132
+ previous?.value?.abort();
1133
+ return undefined;
1134
+ }
1135
+ }] : [{
1136
+ source: () => this.value(),
1137
+ computation: (_source, previous) => {
1138
+ previous?.value?.abort();
1139
+ return undefined;
1140
+ }
1141
+ }]));
1142
+ get logicNode() {
1143
+ return this.structure.logic;
1144
+ }
1145
+ get value() {
1146
+ return this.structure.value;
1147
+ }
1148
+ _controlValue = linkedSignal(() => this.value(), ...(ngDevMode ? [{
1149
+ debugName: "_controlValue"
1150
+ }] : []));
1151
+ get controlValue() {
1152
+ return this._controlValue.asReadonly();
1153
+ }
1154
+ get keyInParent() {
1155
+ return this.structure.keyInParent;
1156
+ }
1157
+ get errors() {
1158
+ return this.validationState.errors;
1159
+ }
1160
+ get errorSummary() {
1161
+ return this.validationState.errorSummary;
1162
+ }
1163
+ get pending() {
1164
+ return this.validationState.pending;
1165
+ }
1166
+ get valid() {
1167
+ return this.validationState.valid;
1168
+ }
1169
+ get invalid() {
1170
+ return this.validationState.invalid;
1171
+ }
1172
+ get dirty() {
1173
+ return this.nodeState.dirty;
1174
+ }
1175
+ get touched() {
1176
+ return this.nodeState.touched;
1177
+ }
1178
+ get disabled() {
1179
+ return this.nodeState.disabled;
1180
+ }
1181
+ get disabledReasons() {
1182
+ return this.nodeState.disabledReasons;
1183
+ }
1184
+ get hidden() {
1185
+ return this.nodeState.hidden;
1186
+ }
1187
+ get readonly() {
1188
+ return this.nodeState.readonly;
1189
+ }
1190
+ get fieldBindings() {
1191
+ return this.nodeState.fieldBindings;
1192
+ }
1193
+ get submitting() {
1194
+ return this.submitState.submitting;
1195
+ }
1196
+ get name() {
1197
+ return this.nodeState.name;
1198
+ }
1199
+ metadataOrUndefined(key) {
1200
+ return this.hasMetadata(key) ? this.metadata(key) : undefined;
1201
+ }
1202
+ get max() {
1203
+ return this.metadataOrUndefined(MAX);
1204
+ }
1205
+ get maxLength() {
1206
+ return this.metadataOrUndefined(MAX_LENGTH);
1207
+ }
1208
+ get min() {
1209
+ return this.metadataOrUndefined(MIN);
1210
+ }
1211
+ get minLength() {
1212
+ return this.metadataOrUndefined(MIN_LENGTH);
1213
+ }
1214
+ get pattern() {
1215
+ return this.metadataOrUndefined(PATTERN) ?? EMPTY;
1216
+ }
1217
+ get required() {
1218
+ return this.metadataOrUndefined(REQUIRED) ?? FALSE;
1219
+ }
1220
+ metadata(key) {
1221
+ return this.metadataState.get(key);
1222
+ }
1223
+ hasMetadata(key) {
1224
+ return this.metadataState.has(key);
1225
+ }
1226
+ markAsTouched() {
1227
+ this.nodeState.markAsTouched();
1228
+ this.pendingSync()?.abort();
1229
+ this.sync();
1230
+ }
1231
+ markAsDirty() {
1232
+ this.nodeState.markAsDirty();
1233
+ }
1234
+ reset() {
1235
+ this.nodeState.markAsUntouched();
1236
+ this.nodeState.markAsPristine();
1237
+ for (const child of this.structure.children()) {
1238
+ child.reset();
1239
+ }
1240
+ }
1241
+ setControlValue(newValue) {
1242
+ this._controlValue.set(newValue);
1243
+ this.markAsDirty();
1244
+ this.debounceSync();
1245
+ }
1246
+ sync() {
1247
+ this.value.set(this.controlValue());
1248
+ }
1249
+ async debounceSync() {
1250
+ this.pendingSync()?.abort();
1251
+ const debouncer = this.nodeState.debouncer();
1252
+ if (debouncer) {
1253
+ const controller = new AbortController();
1254
+ const promise = debouncer(controller.signal);
1255
+ if (promise) {
1256
+ this.pendingSync.set(controller);
1257
+ await promise;
1258
+ if (controller.signal.aborted) {
1259
+ return;
1260
+ }
1261
+ }
1262
+ }
1263
+ this.sync();
1264
+ }
1265
+ static newRoot(fieldManager, value, pathNode, adapter) {
1266
+ return adapter.newRoot(fieldManager, value, pathNode, adapter);
1267
+ }
1268
+ static newChild(options) {
1269
+ return options.fieldAdapter.newChild(options);
1270
+ }
1271
+ createStructure(options) {
1272
+ return options.kind === 'root' ? new RootFieldNodeStructure(this, options.pathNode, options.logic, options.fieldManager, options.value, options.fieldAdapter, FieldNode.newChild) : new ChildFieldNodeStructure(this, options.pathNode, options.logic, options.parent, options.identityInParent, options.initialKeyInParent, options.fieldAdapter, FieldNode.newChild);
1273
+ }
1274
+ }
1275
+ const EMPTY = computed(() => [], ...(ngDevMode ? [{
1276
+ debugName: "EMPTY"
1277
+ }] : []));
1278
+ const FALSE = computed(() => false, ...(ngDevMode ? [{
1279
+ debugName: "FALSE"
1280
+ }] : []));
1281
+
1282
+ class FieldNodeState {
1283
+ node;
1284
+ selfTouched = signal(false, ...(ngDevMode ? [{
1285
+ debugName: "selfTouched"
1286
+ }] : []));
1287
+ selfDirty = signal(false, ...(ngDevMode ? [{
1288
+ debugName: "selfDirty"
1289
+ }] : []));
1290
+ markAsTouched() {
1291
+ this.selfTouched.set(true);
1292
+ }
1293
+ markAsDirty() {
1294
+ this.selfDirty.set(true);
1295
+ }
1296
+ markAsPristine() {
1297
+ this.selfDirty.set(false);
1298
+ }
1299
+ markAsUntouched() {
1300
+ this.selfTouched.set(false);
1301
+ }
1302
+ fieldBindings = signal([], ...(ngDevMode ? [{
1303
+ debugName: "fieldBindings"
1304
+ }] : []));
1305
+ constructor(node) {
1306
+ this.node = node;
1307
+ }
1308
+ dirty = computed(() => {
1309
+ const selfDirtyValue = this.selfDirty() && !this.isNonInteractive();
1310
+ return reduceChildren(this.node, selfDirtyValue, (child, value) => value || child.nodeState.dirty(), shortCircuitTrue);
1311
+ }, ...(ngDevMode ? [{
1312
+ debugName: "dirty"
1313
+ }] : []));
1314
+ touched = computed(() => {
1315
+ const selfTouchedValue = this.selfTouched() && !this.isNonInteractive();
1316
+ return reduceChildren(this.node, selfTouchedValue, (child, value) => value || child.nodeState.touched(), shortCircuitTrue);
1317
+ }, ...(ngDevMode ? [{
1318
+ debugName: "touched"
1319
+ }] : []));
1320
+ disabledReasons = computed(() => [...(this.node.structure.parent?.nodeState.disabledReasons() ?? []), ...this.node.logicNode.logic.disabledReasons.compute(this.node.context)], ...(ngDevMode ? [{
1321
+ debugName: "disabledReasons"
1322
+ }] : []));
1323
+ disabled = computed(() => !!this.disabledReasons().length, ...(ngDevMode ? [{
1324
+ debugName: "disabled"
1325
+ }] : []));
1326
+ readonly = computed(() => (this.node.structure.parent?.nodeState.readonly() || this.node.logicNode.logic.readonly.compute(this.node.context)) ?? false, ...(ngDevMode ? [{
1327
+ debugName: "readonly"
1328
+ }] : []));
1329
+ hidden = computed(() => (this.node.structure.parent?.nodeState.hidden() || this.node.logicNode.logic.hidden.compute(this.node.context)) ?? false, ...(ngDevMode ? [{
1330
+ debugName: "hidden"
1331
+ }] : []));
1332
+ name = computed(() => {
1333
+ const parent = this.node.structure.parent;
1334
+ if (!parent) {
1335
+ return this.node.structure.fieldManager.rootName;
1336
+ }
1337
+ return `${parent.name()}.${this.node.structure.keyInParent()}`;
1338
+ }, ...(ngDevMode ? [{
1339
+ debugName: "name"
1340
+ }] : []));
1341
+ debouncer = computed(() => {
1342
+ if (this.node.logicNode.logic.hasAggregateMetadata(DEBOUNCER)) {
1343
+ const debouncerLogic = this.node.logicNode.logic.getAggregateMetadata(DEBOUNCER);
1344
+ const debouncer = debouncerLogic.compute(this.node.context);
1345
+ if (debouncer) {
1346
+ return signal => debouncer(this.node.context, signal);
1347
+ }
1348
+ }
1349
+ return this.node.structure.parent?.nodeState.debouncer?.();
1350
+ }, ...(ngDevMode ? [{
1351
+ debugName: "debouncer"
1352
+ }] : []));
1353
+ isNonInteractive = computed(() => this.hidden() || this.disabled() || this.readonly(), ...(ngDevMode ? [{
1354
+ debugName: "isNonInteractive"
1355
+ }] : []));
1356
+ }
1357
+
1358
+ class BasicFieldAdapter {
1359
+ newRoot(fieldManager, value, pathNode, adapter) {
1360
+ return new FieldNode({
1361
+ kind: 'root',
1362
+ fieldManager,
1363
+ value,
1364
+ pathNode,
1365
+ logic: pathNode.builder.build(),
1366
+ fieldAdapter: adapter
1367
+ });
1368
+ }
1369
+ newChild(options) {
1370
+ return new FieldNode(options);
1371
+ }
1372
+ createNodeState(node) {
1373
+ return new FieldNodeState(node);
1374
+ }
1375
+ createValidationState(node) {
1376
+ return new FieldValidationState(node);
1377
+ }
1378
+ createStructure(node, options) {
1379
+ return node.createStructure(options);
1380
+ }
1381
+ }
1382
+
1383
+ class FormFieldManager {
1384
+ injector;
1385
+ rootName;
1386
+ constructor(injector, rootName) {
1387
+ this.injector = injector;
1388
+ this.rootName = rootName ?? `${this.injector.get(APP_ID)}.form${nextFormId++}`;
1389
+ }
1390
+ structures = new Set();
1391
+ createFieldManagementEffect(root) {
1392
+ effect(() => {
1393
+ const liveStructures = new Set();
1394
+ this.markStructuresLive(root, liveStructures);
1395
+ for (const structure of this.structures) {
1396
+ if (!liveStructures.has(structure)) {
1397
+ this.structures.delete(structure);
1398
+ untracked(() => structure.destroy());
1399
+ }
1400
+ }
1401
+ }, {
1402
+ injector: this.injector
1403
+ });
1404
+ }
1405
+ markStructuresLive(structure, liveStructures) {
1406
+ liveStructures.add(structure);
1407
+ for (const child of structure.children()) {
1408
+ this.markStructuresLive(child.structure, liveStructures);
1409
+ }
1410
+ }
1411
+ }
1412
+ let nextFormId = 0;
1413
+
1414
+ function normalizeFormArgs(args) {
1415
+ let model;
1416
+ let schema;
1417
+ let options;
1418
+ if (args.length === 3) {
1419
+ [model, schema, options] = args;
1420
+ } else if (args.length === 2) {
1421
+ if (isSchemaOrSchemaFn(args[1])) {
1422
+ [model, schema] = args;
1423
+ } else {
1424
+ [model, options] = args;
1425
+ }
1426
+ } else {
1427
+ [model] = args;
1428
+ }
1429
+ return [model, schema, options];
1430
+ }
1431
+
1432
+ function form(...args) {
1433
+ const [model, schema, options] = normalizeFormArgs(args);
1434
+ const injector = options?.injector ?? inject(Injector);
1435
+ const pathNode = runInInjectionContext(injector, () => SchemaImpl.rootCompile(schema));
1436
+ const fieldManager = new FormFieldManager(injector, options?.name);
1437
+ const adapter = options?.adapter ?? new BasicFieldAdapter();
1438
+ const fieldRoot = FieldNode.newRoot(fieldManager, model, pathNode, adapter);
1439
+ fieldManager.createFieldManagementEffect(fieldRoot.structure);
1440
+ return fieldRoot.fieldProxy;
1441
+ }
1442
+ function applyEach(path, schema) {
1443
+ assertPathIsCurrent(path);
1444
+ const elementPath = FieldPathNode.unwrapFieldPath(path).getChild(DYNAMIC).fieldPathProxy;
1445
+ apply(elementPath, schema);
1446
+ }
1447
+ function apply(path, schema) {
1448
+ assertPathIsCurrent(path);
1449
+ const pathNode = FieldPathNode.unwrapFieldPath(path);
1450
+ pathNode.mergeIn(SchemaImpl.create(schema));
1451
+ }
1452
+ function applyWhen(path, logic, schema) {
1453
+ assertPathIsCurrent(path);
1454
+ const pathNode = FieldPathNode.unwrapFieldPath(path);
1455
+ pathNode.mergeIn(SchemaImpl.create(schema), {
1456
+ fn: logic,
1457
+ path
1458
+ });
1459
+ }
1460
+ function applyWhenValue(path, predicate, schema) {
1461
+ applyWhen(path, ({
1462
+ value
1463
+ }) => predicate(value()), schema);
1464
+ }
1465
+ async function submit(form, action) {
1466
+ const node = form();
1467
+ markAllAsTouched(node);
1468
+ if (node.invalid()) {
1469
+ return;
1470
+ }
1471
+ node.submitState.selfSubmitting.set(true);
1472
+ try {
1473
+ const errors = await action(form);
1474
+ errors && setServerErrors(node, errors);
1475
+ } finally {
1476
+ node.submitState.selfSubmitting.set(false);
1477
+ }
1478
+ }
1479
+ function setServerErrors(submittedField, errors) {
1480
+ if (!isArray(errors)) {
1481
+ errors = [errors];
1482
+ }
1483
+ const errorsByField = new Map();
1484
+ for (const error of errors) {
1485
+ const errorWithField = addDefaultField(error, submittedField.fieldProxy);
1486
+ const field = errorWithField.field();
1487
+ let fieldErrors = errorsByField.get(field);
1488
+ if (!fieldErrors) {
1489
+ fieldErrors = [];
1490
+ errorsByField.set(field, fieldErrors);
1491
+ }
1492
+ fieldErrors.push(errorWithField);
1493
+ }
1494
+ for (const [field, fieldErrors] of errorsByField) {
1495
+ field.submitState.serverErrors.set(fieldErrors);
1496
+ }
1497
+ }
1498
+ function schema(fn) {
1499
+ return SchemaImpl.create(fn);
1500
+ }
1501
+ function markAllAsTouched(node) {
1502
+ node.markAsTouched();
1503
+ for (const child of node.structure.children()) {
1504
+ markAllAsTouched(child);
1505
+ }
1506
+ }
1507
+
1508
+ export { AggregateMetadataKey, BasicFieldAdapter, DEBOUNCER, FieldNode, FieldNodeState, FieldNodeStructure, FieldPathNode, MAX, MAX_LENGTH, MIN, MIN_LENGTH, MetadataKey, PATTERN, REQUIRED, addDefaultField, andMetadataKey, apply, applyEach, applyWhen, applyWhenValue, assertPathIsCurrent, calculateValidationSelfStatus, createMetadataKey, form, getInjectorFromOptions, isArray, listMetadataKey, maxMetadataKey, minMetadataKey, normalizeFormArgs, orMetadataKey, reducedMetadataKey, schema, submit };
1509
+ //# sourceMappingURL=_structure-chunk.mjs.map