@angular/forms 21.0.0-rc.2 → 21.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,714 +1,16 @@
1
1
  /**
2
- * @license Angular v21.0.0-rc.2
2
+ * @license Angular v21.0.0
3
3
  * (c) 2010-2025 Google LLC. https://angular.dev/
4
4
  * License: MIT
5
5
  */
6
6
 
7
7
  import { httpResource } from '@angular/common/http';
8
8
  import * as i0 from '@angular/core';
9
- import { computed, untracked, InjectionToken, inject, Injector, input, ɵCONTROL as _CONTROL, effect, Directive, runInInjectionContext, linkedSignal, signal, APP_ID, ɵisPromise as _isPromise, resource } from '@angular/core';
10
- import { Validators, NG_VALUE_ACCESSOR, NgControl, AbstractControl } from '@angular/forms';
11
- import { SIGNAL } from '@angular/core/primitives/signals';
12
-
13
- function isArray(value) {
14
- return Array.isArray(value);
15
- }
16
- function isObject(value) {
17
- return (typeof value === 'object' || typeof value === 'function') && value != null;
18
- }
19
-
20
- function reduceChildren(node, initialValue, fn, shortCircuit) {
21
- const childrenMap = node.structure.childrenMap();
22
- if (!childrenMap) {
23
- return initialValue;
24
- }
25
- let value = initialValue;
26
- for (const child of childrenMap.values()) {
27
- if (shortCircuit?.(value)) {
28
- break;
29
- }
30
- value = fn(child, value);
31
- }
32
- return value;
33
- }
34
- function shortCircuitFalse(value) {
35
- return !value;
36
- }
37
- function shortCircuitTrue(value) {
38
- return value;
39
- }
40
-
41
- function calculateValidationSelfStatus(state) {
42
- if (state.errors().length > 0) {
43
- return 'invalid';
44
- }
45
- if (state.pending()) {
46
- return 'unknown';
47
- }
48
- return 'valid';
49
- }
50
- class FieldValidationState {
51
- node;
52
- constructor(node) {
53
- this.node = node;
54
- }
55
- rawSyncTreeErrors = computed(() => {
56
- if (this.shouldSkipValidation()) {
57
- return [];
58
- }
59
- return [...this.node.logicNode.logic.syncTreeErrors.compute(this.node.context), ...(this.node.structure.parent?.validationState.rawSyncTreeErrors() ?? [])];
60
- }, ...(ngDevMode ? [{
61
- debugName: "rawSyncTreeErrors"
62
- }] : []));
63
- syncErrors = computed(() => {
64
- if (this.shouldSkipValidation()) {
65
- return [];
66
- }
67
- return [...this.node.logicNode.logic.syncErrors.compute(this.node.context), ...this.syncTreeErrors(), ...normalizeErrors(this.node.submitState.serverErrors())];
68
- }, ...(ngDevMode ? [{
69
- debugName: "syncErrors"
70
- }] : []));
71
- syncValid = computed(() => {
72
- if (this.shouldSkipValidation()) {
73
- return true;
74
- }
75
- return reduceChildren(this.node, this.syncErrors().length === 0, (child, value) => value && child.validationState.syncValid(), shortCircuitFalse);
76
- }, ...(ngDevMode ? [{
77
- debugName: "syncValid"
78
- }] : []));
79
- syncTreeErrors = computed(() => this.rawSyncTreeErrors().filter(err => err.field === this.node.fieldProxy), ...(ngDevMode ? [{
80
- debugName: "syncTreeErrors"
81
- }] : []));
82
- rawAsyncErrors = computed(() => {
83
- if (this.shouldSkipValidation()) {
84
- return [];
85
- }
86
- return [...this.node.logicNode.logic.asyncErrors.compute(this.node.context), ...(this.node.structure.parent?.validationState.rawAsyncErrors() ?? [])];
87
- }, ...(ngDevMode ? [{
88
- debugName: "rawAsyncErrors"
89
- }] : []));
90
- asyncErrors = computed(() => {
91
- if (this.shouldSkipValidation()) {
92
- return [];
93
- }
94
- return this.rawAsyncErrors().filter(err => err === 'pending' || err.field === this.node.fieldProxy);
95
- }, ...(ngDevMode ? [{
96
- debugName: "asyncErrors"
97
- }] : []));
98
- errors = computed(() => [...this.syncErrors(), ...this.asyncErrors().filter(err => err !== 'pending')], ...(ngDevMode ? [{
99
- debugName: "errors"
100
- }] : []));
101
- errorSummary = computed(() => reduceChildren(this.node, this.errors(), (child, result) => [...result, ...child.errorSummary()]), ...(ngDevMode ? [{
102
- debugName: "errorSummary"
103
- }] : []));
104
- pending = computed(() => reduceChildren(this.node, this.asyncErrors().includes('pending'), (child, value) => value || child.validationState.asyncErrors().includes('pending')), ...(ngDevMode ? [{
105
- debugName: "pending"
106
- }] : []));
107
- status = computed(() => {
108
- if (this.shouldSkipValidation()) {
109
- return 'valid';
110
- }
111
- let ownStatus = calculateValidationSelfStatus(this);
112
- return reduceChildren(this.node, ownStatus, (child, value) => {
113
- if (value === 'invalid' || child.validationState.status() === 'invalid') {
114
- return 'invalid';
115
- } else if (value === 'unknown' || child.validationState.status() === 'unknown') {
116
- return 'unknown';
117
- }
118
- return 'valid';
119
- }, v => v === 'invalid');
120
- }, ...(ngDevMode ? [{
121
- debugName: "status"
122
- }] : []));
123
- valid = computed(() => this.status() === 'valid', ...(ngDevMode ? [{
124
- debugName: "valid"
125
- }] : []));
126
- invalid = computed(() => this.status() === 'invalid', ...(ngDevMode ? [{
127
- debugName: "invalid"
128
- }] : []));
129
- shouldSkipValidation = computed(() => this.node.hidden() || this.node.disabled() || this.node.readonly(), ...(ngDevMode ? [{
130
- debugName: "shouldSkipValidation"
131
- }] : []));
132
- }
133
- function normalizeErrors(error) {
134
- if (error === undefined) {
135
- return [];
136
- }
137
- if (isArray(error)) {
138
- return error;
139
- }
140
- return [error];
141
- }
142
- function addDefaultField(errors, field) {
143
- if (isArray(errors)) {
144
- for (const error of errors) {
145
- error.field ??= field;
146
- }
147
- } else if (errors) {
148
- errors.field ??= field;
149
- }
150
- return errors;
151
- }
152
-
153
- let boundPathDepth = 0;
154
- function getBoundPathDepth() {
155
- return boundPathDepth;
156
- }
157
- function setBoundPathDepthForResolution(fn, depth) {
158
- return (...args) => {
159
- try {
160
- boundPathDepth = depth;
161
- return fn(...args);
162
- } finally {
163
- boundPathDepth = 0;
164
- }
165
- };
166
- }
167
-
168
- const DYNAMIC = Symbol();
169
- const IGNORED = Symbol();
170
- class AbstractLogic {
171
- predicates;
172
- fns = [];
173
- constructor(predicates) {
174
- this.predicates = predicates;
175
- }
176
- push(logicFn) {
177
- this.fns.push(wrapWithPredicates(this.predicates, logicFn));
178
- }
179
- mergeIn(other) {
180
- const fns = this.predicates ? other.fns.map(fn => wrapWithPredicates(this.predicates, fn)) : other.fns;
181
- this.fns.push(...fns);
182
- }
183
- }
184
- class BooleanOrLogic extends AbstractLogic {
185
- get defaultValue() {
186
- return false;
187
- }
188
- compute(arg) {
189
- return this.fns.some(f => {
190
- const result = f(arg);
191
- return result && result !== IGNORED;
192
- });
193
- }
194
- }
195
- class ArrayMergeIgnoreLogic extends AbstractLogic {
196
- ignore;
197
- static ignoreNull(predicates) {
198
- return new ArrayMergeIgnoreLogic(predicates, e => e === null);
199
- }
200
- constructor(predicates, ignore) {
201
- super(predicates);
202
- this.ignore = ignore;
203
- }
204
- get defaultValue() {
205
- return [];
206
- }
207
- compute(arg) {
208
- return this.fns.reduce((prev, f) => {
209
- const value = f(arg);
210
- if (value === undefined || value === IGNORED) {
211
- return prev;
212
- } else if (isArray(value)) {
213
- return [...prev, ...(this.ignore ? value.filter(e => !this.ignore(e)) : value)];
214
- } else {
215
- if (this.ignore && this.ignore(value)) {
216
- return prev;
217
- }
218
- return [...prev, value];
219
- }
220
- }, []);
221
- }
222
- }
223
- class ArrayMergeLogic extends ArrayMergeIgnoreLogic {
224
- constructor(predicates) {
225
- super(predicates, undefined);
226
- }
227
- }
228
- class AggregateMetadataMergeLogic extends AbstractLogic {
229
- key;
230
- get defaultValue() {
231
- return this.key.getInitial();
232
- }
233
- constructor(predicates, key) {
234
- super(predicates);
235
- this.key = key;
236
- }
237
- compute(ctx) {
238
- if (this.fns.length === 0) {
239
- return this.key.getInitial();
240
- }
241
- let acc = this.key.getInitial();
242
- for (let i = 0; i < this.fns.length; i++) {
243
- const item = this.fns[i](ctx);
244
- if (item !== IGNORED) {
245
- acc = this.key.reduce(acc, item);
246
- }
247
- }
248
- return acc;
249
- }
250
- }
251
- function wrapWithPredicates(predicates, logicFn) {
252
- if (predicates.length === 0) {
253
- return logicFn;
254
- }
255
- return arg => {
256
- for (const predicate of predicates) {
257
- let predicateField = arg.stateOf(predicate.path);
258
- const depthDiff = untracked(predicateField.structure.pathKeys).length - predicate.depth;
259
- for (let i = 0; i < depthDiff; i++) {
260
- predicateField = predicateField.structure.parent;
261
- }
262
- if (!predicate.fn(predicateField.context)) {
263
- return IGNORED;
264
- }
265
- }
266
- return logicFn(arg);
267
- };
268
- }
269
- class LogicContainer {
270
- predicates;
271
- hidden;
272
- disabledReasons;
273
- readonly;
274
- syncErrors;
275
- syncTreeErrors;
276
- asyncErrors;
277
- aggregateMetadataKeys = new Map();
278
- metadataFactories = new Map();
279
- constructor(predicates) {
280
- this.predicates = predicates;
281
- this.hidden = new BooleanOrLogic(predicates);
282
- this.disabledReasons = new ArrayMergeLogic(predicates);
283
- this.readonly = new BooleanOrLogic(predicates);
284
- this.syncErrors = ArrayMergeIgnoreLogic.ignoreNull(predicates);
285
- this.syncTreeErrors = ArrayMergeIgnoreLogic.ignoreNull(predicates);
286
- this.asyncErrors = ArrayMergeIgnoreLogic.ignoreNull(predicates);
287
- }
288
- hasAggregateMetadata(key) {
289
- return this.aggregateMetadataKeys.has(key);
290
- }
291
- getAggregateMetadataEntries() {
292
- return this.aggregateMetadataKeys.entries();
293
- }
294
- getMetadataFactoryEntries() {
295
- return this.metadataFactories.entries();
296
- }
297
- getAggregateMetadata(key) {
298
- if (!this.aggregateMetadataKeys.has(key)) {
299
- this.aggregateMetadataKeys.set(key, new AggregateMetadataMergeLogic(this.predicates, key));
300
- }
301
- return this.aggregateMetadataKeys.get(key);
302
- }
303
- addMetadataFactory(key, factory) {
304
- if (this.metadataFactories.has(key)) {
305
- throw new Error(`Can't define value twice for the same MetadataKey`);
306
- }
307
- this.metadataFactories.set(key, factory);
308
- }
309
- mergeIn(other) {
310
- this.hidden.mergeIn(other.hidden);
311
- this.disabledReasons.mergeIn(other.disabledReasons);
312
- this.readonly.mergeIn(other.readonly);
313
- this.syncErrors.mergeIn(other.syncErrors);
314
- this.syncTreeErrors.mergeIn(other.syncTreeErrors);
315
- this.asyncErrors.mergeIn(other.asyncErrors);
316
- for (const [key, metadataLogic] of other.getAggregateMetadataEntries()) {
317
- this.getAggregateMetadata(key).mergeIn(metadataLogic);
318
- }
319
- for (const [key, metadataFactory] of other.getMetadataFactoryEntries()) {
320
- this.addMetadataFactory(key, metadataFactory);
321
- }
322
- }
323
- }
324
-
325
- class AbstractLogicNodeBuilder {
326
- depth;
327
- constructor(depth) {
328
- this.depth = depth;
329
- }
330
- build() {
331
- return new LeafLogicNode(this, [], 0);
332
- }
333
- }
334
- class LogicNodeBuilder extends AbstractLogicNodeBuilder {
335
- constructor(depth) {
336
- super(depth);
337
- }
338
- current;
339
- all = [];
340
- addHiddenRule(logic) {
341
- this.getCurrent().addHiddenRule(logic);
342
- }
343
- addDisabledReasonRule(logic) {
344
- this.getCurrent().addDisabledReasonRule(logic);
345
- }
346
- addReadonlyRule(logic) {
347
- this.getCurrent().addReadonlyRule(logic);
348
- }
349
- addSyncErrorRule(logic) {
350
- this.getCurrent().addSyncErrorRule(logic);
351
- }
352
- addSyncTreeErrorRule(logic) {
353
- this.getCurrent().addSyncTreeErrorRule(logic);
354
- }
355
- addAsyncErrorRule(logic) {
356
- this.getCurrent().addAsyncErrorRule(logic);
357
- }
358
- addAggregateMetadataRule(key, logic) {
359
- this.getCurrent().addAggregateMetadataRule(key, logic);
360
- }
361
- addMetadataFactory(key, factory) {
362
- this.getCurrent().addMetadataFactory(key, factory);
363
- }
364
- getChild(key) {
365
- if (key === DYNAMIC) {
366
- const children = this.getCurrent().children;
367
- if (children.size > (children.has(DYNAMIC) ? 1 : 0)) {
368
- this.current = undefined;
369
- }
370
- }
371
- return this.getCurrent().getChild(key);
372
- }
373
- hasLogic(builder) {
374
- if (this === builder) {
375
- return true;
376
- }
377
- return this.all.some(({
378
- builder: subBuilder
379
- }) => subBuilder.hasLogic(builder));
380
- }
381
- mergeIn(other, predicate) {
382
- if (predicate) {
383
- this.all.push({
384
- builder: other,
385
- predicate: {
386
- fn: setBoundPathDepthForResolution(predicate.fn, this.depth),
387
- path: predicate.path
388
- }
389
- });
390
- } else {
391
- this.all.push({
392
- builder: other
393
- });
394
- }
395
- this.current = undefined;
396
- }
397
- getCurrent() {
398
- if (this.current === undefined) {
399
- this.current = new NonMergeableLogicNodeBuilder(this.depth);
400
- this.all.push({
401
- builder: this.current
402
- });
403
- }
404
- return this.current;
405
- }
406
- static newRoot() {
407
- return new LogicNodeBuilder(0);
408
- }
409
- }
410
- class NonMergeableLogicNodeBuilder extends AbstractLogicNodeBuilder {
411
- logic = new LogicContainer([]);
412
- children = new Map();
413
- constructor(depth) {
414
- super(depth);
415
- }
416
- addHiddenRule(logic) {
417
- this.logic.hidden.push(setBoundPathDepthForResolution(logic, this.depth));
418
- }
419
- addDisabledReasonRule(logic) {
420
- this.logic.disabledReasons.push(setBoundPathDepthForResolution(logic, this.depth));
421
- }
422
- addReadonlyRule(logic) {
423
- this.logic.readonly.push(setBoundPathDepthForResolution(logic, this.depth));
424
- }
425
- addSyncErrorRule(logic) {
426
- this.logic.syncErrors.push(setBoundPathDepthForResolution(logic, this.depth));
427
- }
428
- addSyncTreeErrorRule(logic) {
429
- this.logic.syncTreeErrors.push(setBoundPathDepthForResolution(logic, this.depth));
430
- }
431
- addAsyncErrorRule(logic) {
432
- this.logic.asyncErrors.push(setBoundPathDepthForResolution(logic, this.depth));
433
- }
434
- addAggregateMetadataRule(key, logic) {
435
- this.logic.getAggregateMetadata(key).push(setBoundPathDepthForResolution(logic, this.depth));
436
- }
437
- addMetadataFactory(key, factory) {
438
- this.logic.addMetadataFactory(key, setBoundPathDepthForResolution(factory, this.depth));
439
- }
440
- getChild(key) {
441
- if (!this.children.has(key)) {
442
- this.children.set(key, new LogicNodeBuilder(this.depth + 1));
443
- }
444
- return this.children.get(key);
445
- }
446
- hasLogic(builder) {
447
- return this === builder;
448
- }
449
- }
450
- class LeafLogicNode {
451
- builder;
452
- predicates;
453
- depth;
454
- logic;
455
- constructor(builder, predicates, depth) {
456
- this.builder = builder;
457
- this.predicates = predicates;
458
- this.depth = depth;
459
- this.logic = builder ? createLogic(builder, predicates, depth) : new LogicContainer([]);
460
- }
461
- getChild(key) {
462
- const childBuilders = this.builder ? getAllChildBuilders(this.builder, key) : [];
463
- if (childBuilders.length === 0) {
464
- return new LeafLogicNode(undefined, [], this.depth + 1);
465
- } else if (childBuilders.length === 1) {
466
- const {
467
- builder,
468
- predicates
469
- } = childBuilders[0];
470
- return new LeafLogicNode(builder, [...this.predicates, ...predicates.map(p => bindLevel(p, this.depth))], this.depth + 1);
471
- } else {
472
- const builtNodes = childBuilders.map(({
473
- builder,
474
- predicates
475
- }) => new LeafLogicNode(builder, [...this.predicates, ...predicates.map(p => bindLevel(p, this.depth))], this.depth + 1));
476
- return new CompositeLogicNode(builtNodes);
477
- }
478
- }
479
- hasLogic(builder) {
480
- return this.builder?.hasLogic(builder) ?? false;
481
- }
482
- }
483
- class CompositeLogicNode {
484
- all;
485
- logic;
486
- constructor(all) {
487
- this.all = all;
488
- this.logic = new LogicContainer([]);
489
- for (const node of all) {
490
- this.logic.mergeIn(node.logic);
491
- }
492
- }
493
- getChild(key) {
494
- return new CompositeLogicNode(this.all.flatMap(child => child.getChild(key)));
495
- }
496
- hasLogic(builder) {
497
- return this.all.some(node => node.hasLogic(builder));
498
- }
499
- }
500
- function getAllChildBuilders(builder, key) {
501
- if (builder instanceof LogicNodeBuilder) {
502
- return builder.all.flatMap(({
503
- builder,
504
- predicate
505
- }) => {
506
- const children = getAllChildBuilders(builder, key);
507
- if (predicate) {
508
- return children.map(({
509
- builder,
510
- predicates
511
- }) => ({
512
- builder,
513
- predicates: [...predicates, predicate]
514
- }));
515
- }
516
- return children;
517
- });
518
- } else if (builder instanceof NonMergeableLogicNodeBuilder) {
519
- return [...(key !== DYNAMIC && builder.children.has(DYNAMIC) ? [{
520
- builder: builder.getChild(DYNAMIC),
521
- predicates: []
522
- }] : []), ...(builder.children.has(key) ? [{
523
- builder: builder.getChild(key),
524
- predicates: []
525
- }] : [])];
526
- } else {
527
- throw new Error('Unknown LogicNodeBuilder type');
528
- }
529
- }
530
- function createLogic(builder, predicates, depth) {
531
- const logic = new LogicContainer(predicates);
532
- if (builder instanceof LogicNodeBuilder) {
533
- const builtNodes = builder.all.map(({
534
- builder,
535
- predicate
536
- }) => new LeafLogicNode(builder, predicate ? [...predicates, bindLevel(predicate, depth)] : predicates, depth));
537
- for (const node of builtNodes) {
538
- logic.mergeIn(node.logic);
539
- }
540
- } else if (builder instanceof NonMergeableLogicNodeBuilder) {
541
- logic.mergeIn(builder.logic);
542
- } else {
543
- throw new Error('Unknown LogicNodeBuilder type');
544
- }
545
- return logic;
546
- }
547
- function bindLevel(predicate, depth) {
548
- return {
549
- ...predicate,
550
- depth: depth
551
- };
552
- }
553
-
554
- const PATH = Symbol('PATH');
555
- class FieldPathNode {
556
- keys;
557
- parent;
558
- keyInParent;
559
- root;
560
- children = new Map();
561
- fieldPathProxy = new Proxy(this, FIELD_PATH_PROXY_HANDLER);
562
- logicBuilder;
563
- constructor(keys, root, parent, keyInParent) {
564
- this.keys = keys;
565
- this.parent = parent;
566
- this.keyInParent = keyInParent;
567
- this.root = root ?? this;
568
- if (!parent) {
569
- this.logicBuilder = LogicNodeBuilder.newRoot();
570
- }
571
- }
572
- get builder() {
573
- if (this.logicBuilder) {
574
- return this.logicBuilder;
575
- }
576
- return this.parent.builder.getChild(this.keyInParent);
577
- }
578
- getChild(key) {
579
- if (!this.children.has(key)) {
580
- this.children.set(key, new FieldPathNode([...this.keys, key], this.root, this, key));
581
- }
582
- return this.children.get(key);
583
- }
584
- mergeIn(other, predicate) {
585
- const path = other.compile();
586
- this.builder.mergeIn(path.builder, predicate);
587
- }
588
- static unwrapFieldPath(formPath) {
589
- return formPath[PATH];
590
- }
591
- static newRoot() {
592
- return new FieldPathNode([], undefined, undefined, undefined);
593
- }
594
- }
595
- const FIELD_PATH_PROXY_HANDLER = {
596
- get(node, property) {
597
- if (property === PATH) {
598
- return node;
599
- }
600
- return node.getChild(property).fieldPathProxy;
601
- }
602
- };
603
-
604
- let currentCompilingNode = undefined;
605
- const compiledSchemas = new Map();
606
- class SchemaImpl {
607
- schemaFn;
608
- constructor(schemaFn) {
609
- this.schemaFn = schemaFn;
610
- }
611
- compile() {
612
- if (compiledSchemas.has(this)) {
613
- return compiledSchemas.get(this);
614
- }
615
- const path = FieldPathNode.newRoot();
616
- compiledSchemas.set(this, path);
617
- let prevCompilingNode = currentCompilingNode;
618
- try {
619
- currentCompilingNode = path;
620
- this.schemaFn(path.fieldPathProxy);
621
- } finally {
622
- currentCompilingNode = prevCompilingNode;
623
- }
624
- return path;
625
- }
626
- static create(schema) {
627
- if (schema instanceof SchemaImpl) {
628
- return schema;
629
- }
630
- return new SchemaImpl(schema);
631
- }
632
- static rootCompile(schema) {
633
- try {
634
- compiledSchemas.clear();
635
- if (schema === undefined) {
636
- return FieldPathNode.newRoot();
637
- }
638
- if (schema instanceof SchemaImpl) {
639
- return schema.compile();
640
- }
641
- return new SchemaImpl(schema).compile();
642
- } finally {
643
- compiledSchemas.clear();
644
- }
645
- }
646
- }
647
- function isSchemaOrSchemaFn(value) {
648
- return value instanceof SchemaImpl || typeof value === 'function';
649
- }
650
- function assertPathIsCurrent(path) {
651
- if (currentCompilingNode !== FieldPathNode.unwrapFieldPath(path).root) {
652
- 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.`);
653
- }
654
- }
655
-
656
- class MetadataKey {
657
- brand;
658
- constructor() {}
659
- }
660
- function createMetadataKey() {
661
- return new MetadataKey();
662
- }
663
- class AggregateMetadataKey {
664
- reduce;
665
- getInitial;
666
- brand;
667
- constructor(reduce, getInitial) {
668
- this.reduce = reduce;
669
- this.getInitial = getInitial;
670
- }
671
- }
672
- function reducedMetadataKey(reduce, getInitial) {
673
- return new AggregateMetadataKey(reduce, getInitial);
674
- }
675
- function listMetadataKey() {
676
- return reducedMetadataKey((acc, item) => item === undefined ? acc : [...acc, item], () => []);
677
- }
678
- function minMetadataKey() {
679
- return reducedMetadataKey((prev, next) => {
680
- if (prev === undefined) {
681
- return next;
682
- }
683
- if (next === undefined) {
684
- return prev;
685
- }
686
- return Math.min(prev, next);
687
- }, () => undefined);
688
- }
689
- function maxMetadataKey() {
690
- return reducedMetadataKey((prev, next) => {
691
- if (prev === undefined) {
692
- return next;
693
- }
694
- if (next === undefined) {
695
- return prev;
696
- }
697
- return Math.max(prev, next);
698
- }, () => undefined);
699
- }
700
- function orMetadataKey() {
701
- return reducedMetadataKey((prev, next) => prev || next, () => false);
702
- }
703
- function andMetadataKey() {
704
- return reducedMetadataKey((prev, next) => prev && next, () => true);
705
- }
706
- const REQUIRED = orMetadataKey();
707
- const MIN = maxMetadataKey();
708
- const MAX = minMetadataKey();
709
- const MIN_LENGTH = maxMetadataKey();
710
- const MAX_LENGTH = minMetadataKey();
711
- const PATTERN = listMetadataKey();
9
+ import { computed, InjectionToken, inject, Injector, input, ɵCONTROL as _CONTROL, effect, Directive, ɵisPromise as _isPromise, resource } from '@angular/core';
10
+ import { isArray, assertPathIsCurrent, addDefaultField, FieldPathNode, createMetadataKey, DEBOUNCER, REQUIRED, MAX, MAX_LENGTH, MIN, MIN_LENGTH, PATTERN } from './_structure-chunk.mjs';
11
+ export { AggregateMetadataKey, MetadataKey, andMetadataKey, apply, applyEach, applyWhen, applyWhenValue, form, listMetadataKey, maxMetadataKey, minMetadataKey, orMetadataKey, reducedMetadataKey, schema, submit } from './_structure-chunk.mjs';
12
+ import { Validators, NG_VALUE_ACCESSOR, NgControl } from '@angular/forms';
13
+ import '@angular/core/primitives/signals';
712
14
 
713
15
  function requiredError(options) {
714
16
  return new RequiredValidationError(options);
@@ -957,8 +259,6 @@ function validateHttp(path, opts) {
957
259
  });
958
260
  }
959
261
 
960
- const DEBOUNCER = reducedMetadataKey((_, item) => item, () => undefined);
961
-
962
262
  function debounce(path, durationOrDebouncer) {
963
263
  assertPathIsCurrent(path);
964
264
  const pathNode = FieldPathNode.unwrapFieldPath(path);
@@ -966,8 +266,11 @@ function debounce(path, durationOrDebouncer) {
966
266
  pathNode.builder.addAggregateMetadataRule(DEBOUNCER, () => debouncer);
967
267
  }
968
268
  function debounceForDuration(durationInMilliseconds) {
969
- return () => {
970
- return new Promise(resolve => setTimeout(resolve, durationInMilliseconds));
269
+ return (_context, abortSignal) => {
270
+ return new Promise(resolve => {
271
+ const timeoutId = setTimeout(resolve, durationInMilliseconds);
272
+ abortSignal.addEventListener('abort', () => clearTimeout(timeoutId));
273
+ });
971
274
  };
972
275
  }
973
276
  function immediate() {}
@@ -1078,7 +381,7 @@ class Field {
1078
381
  }
1079
382
  static ɵfac = i0.ɵɵngDeclareFactory({
1080
383
  minVersion: "12.0.0",
1081
- version: "21.0.0-rc.2",
384
+ version: "21.0.0",
1082
385
  ngImport: i0,
1083
386
  type: Field,
1084
387
  deps: [],
@@ -1086,7 +389,7 @@ class Field {
1086
389
  });
1087
390
  static ɵdir = i0.ɵɵngDeclareDirective({
1088
391
  minVersion: "17.1.0",
1089
- version: "21.0.0-rc.2",
392
+ version: "21.0.0",
1090
393
  type: Field,
1091
394
  isStandalone: true,
1092
395
  selector: "[field]",
@@ -1111,7 +414,7 @@ class Field {
1111
414
  }
1112
415
  i0.ɵɵngDeclareClassMetadata({
1113
416
  minVersion: "12.0.0",
1114
- version: "21.0.0-rc.2",
417
+ version: "21.0.0",
1115
418
  ngImport: i0,
1116
419
  type: Field,
1117
420
  decorators: [{
@@ -1139,784 +442,6 @@ i0.ɵɵngDeclareClassMetadata({
1139
442
  }
1140
443
  });
1141
444
 
1142
- class FieldNodeContext {
1143
- node;
1144
- cache = new WeakMap();
1145
- constructor(node) {
1146
- this.node = node;
1147
- }
1148
- resolve(target) {
1149
- if (!this.cache.has(target)) {
1150
- const resolver = computed(() => {
1151
- const targetPathNode = FieldPathNode.unwrapFieldPath(target);
1152
- let field = this.node;
1153
- let stepsRemaining = getBoundPathDepth();
1154
- while (stepsRemaining > 0 || !field.structure.logic.hasLogic(targetPathNode.root.builder)) {
1155
- stepsRemaining--;
1156
- field = field.structure.parent;
1157
- if (field === undefined) {
1158
- throw new Error('Path is not part of this field tree.');
1159
- }
1160
- }
1161
- for (let key of targetPathNode.keys) {
1162
- field = field.structure.getChild(key);
1163
- if (field === undefined) {
1164
- throw new Error(`Cannot resolve path .${targetPathNode.keys.join('.')} relative to field ${['<root>', ...this.node.structure.pathKeys()].join('.')}.`);
1165
- }
1166
- }
1167
- return field.fieldProxy;
1168
- }, ...(ngDevMode ? [{
1169
- debugName: "resolver"
1170
- }] : []));
1171
- this.cache.set(target, resolver);
1172
- }
1173
- return this.cache.get(target)();
1174
- }
1175
- get field() {
1176
- return this.node.fieldProxy;
1177
- }
1178
- get state() {
1179
- return this.node;
1180
- }
1181
- get value() {
1182
- return this.node.structure.value;
1183
- }
1184
- get key() {
1185
- return this.node.structure.keyInParent;
1186
- }
1187
- get pathKeys() {
1188
- return this.node.structure.pathKeys;
1189
- }
1190
- index = computed(() => {
1191
- const key = this.key();
1192
- if (!isArray(untracked(this.node.structure.parent.value))) {
1193
- throw new Error(`RuntimeError: cannot access index, parent field is not an array`);
1194
- }
1195
- return Number(key);
1196
- }, ...(ngDevMode ? [{
1197
- debugName: "index"
1198
- }] : []));
1199
- fieldTreeOf = p => this.resolve(p);
1200
- stateOf = p => this.resolve(p)();
1201
- valueOf = p => {
1202
- const result = this.resolve(p)().value();
1203
- if (result instanceof AbstractControl) {
1204
- throw new Error(`Tried to read an 'AbstractControl' value form a 'form()'. Did you mean to use 'compatForm()' instead?`);
1205
- }
1206
- return result;
1207
- };
1208
- }
1209
-
1210
- class FieldMetadataState {
1211
- node;
1212
- metadata = new Map();
1213
- constructor(node) {
1214
- this.node = node;
1215
- untracked(() => runInInjectionContext(this.node.structure.injector, () => {
1216
- for (const [key, factory] of this.node.logicNode.logic.getMetadataFactoryEntries()) {
1217
- this.metadata.set(key, factory(this.node.context));
1218
- }
1219
- }));
1220
- }
1221
- get(key) {
1222
- if (key instanceof MetadataKey) {
1223
- return this.metadata.get(key);
1224
- }
1225
- if (!this.metadata.has(key)) {
1226
- const logic = this.node.logicNode.logic.getAggregateMetadata(key);
1227
- const result = computed(() => logic.compute(this.node.context), ...(ngDevMode ? [{
1228
- debugName: "result"
1229
- }] : []));
1230
- this.metadata.set(key, result);
1231
- }
1232
- return this.metadata.get(key);
1233
- }
1234
- has(key) {
1235
- if (key instanceof AggregateMetadataKey) {
1236
- return this.node.logicNode.logic.hasAggregateMetadata(key);
1237
- } else {
1238
- return this.metadata.has(key);
1239
- }
1240
- }
1241
- }
1242
-
1243
- const FIELD_PROXY_HANDLER = {
1244
- get(getTgt, p, receiver) {
1245
- const tgt = getTgt();
1246
- const child = tgt.structure.getChild(p);
1247
- if (child !== undefined) {
1248
- return child.fieldProxy;
1249
- }
1250
- const value = untracked(tgt.value);
1251
- if (isArray(value)) {
1252
- if (p === 'length') {
1253
- return tgt.value().length;
1254
- }
1255
- if (p === Symbol.iterator) {
1256
- return Array.prototype[p];
1257
- }
1258
- }
1259
- if (isObject(value)) {
1260
- if (p === Symbol.iterator) {
1261
- return function* () {
1262
- for (const key in receiver) {
1263
- yield [key, receiver[key]];
1264
- }
1265
- };
1266
- }
1267
- }
1268
- return undefined;
1269
- },
1270
- getOwnPropertyDescriptor(getTgt, prop) {
1271
- const value = untracked(getTgt().value);
1272
- const desc = Reflect.getOwnPropertyDescriptor(value, prop);
1273
- if (desc && !desc.configurable) {
1274
- desc.configurable = true;
1275
- }
1276
- return desc;
1277
- },
1278
- ownKeys(getTgt) {
1279
- const value = untracked(getTgt().value);
1280
- return typeof value === 'object' && value !== null ? Reflect.ownKeys(value) : [];
1281
- }
1282
- };
1283
-
1284
- function deepSignal(source, prop) {
1285
- const read = computed(() => source()[prop()]);
1286
- read[SIGNAL] = source[SIGNAL];
1287
- read.set = value => {
1288
- source.update(current => valueForWrite(current, value, prop()));
1289
- };
1290
- read.update = fn => {
1291
- read.set(fn(untracked(read)));
1292
- };
1293
- read.asReadonly = () => read;
1294
- return read;
1295
- }
1296
- function valueForWrite(sourceValue, newPropValue, prop) {
1297
- if (isArray(sourceValue)) {
1298
- const newValue = [...sourceValue];
1299
- newValue[prop] = newPropValue;
1300
- return newValue;
1301
- } else {
1302
- return {
1303
- ...sourceValue,
1304
- [prop]: newPropValue
1305
- };
1306
- }
1307
- }
1308
-
1309
- class FieldNodeStructure {
1310
- logic;
1311
- identitySymbol = Symbol();
1312
- _injector = undefined;
1313
- get injector() {
1314
- this._injector ??= Injector.create({
1315
- providers: [],
1316
- parent: this.fieldManager.injector
1317
- });
1318
- return this._injector;
1319
- }
1320
- constructor(logic) {
1321
- this.logic = logic;
1322
- }
1323
- children() {
1324
- return this.childrenMap()?.values() ?? [];
1325
- }
1326
- getChild(key) {
1327
- const map = this.childrenMap();
1328
- const value = this.value();
1329
- if (!map || !isObject(value)) {
1330
- return undefined;
1331
- }
1332
- if (isArray(value)) {
1333
- const childValue = value[key];
1334
- if (isObject(childValue) && childValue.hasOwnProperty(this.identitySymbol)) {
1335
- key = childValue[this.identitySymbol];
1336
- }
1337
- }
1338
- return map.get(typeof key === 'number' ? key.toString() : key);
1339
- }
1340
- destroy() {
1341
- this.injector.destroy();
1342
- }
1343
- }
1344
- class RootFieldNodeStructure extends FieldNodeStructure {
1345
- node;
1346
- fieldManager;
1347
- value;
1348
- get parent() {
1349
- return undefined;
1350
- }
1351
- get root() {
1352
- return this.node;
1353
- }
1354
- get pathKeys() {
1355
- return ROOT_PATH_KEYS;
1356
- }
1357
- get keyInParent() {
1358
- return ROOT_KEY_IN_PARENT;
1359
- }
1360
- childrenMap;
1361
- constructor(node, pathNode, logic, fieldManager, value, adapter, createChildNode) {
1362
- super(logic);
1363
- this.node = node;
1364
- this.fieldManager = fieldManager;
1365
- this.value = value;
1366
- this.childrenMap = makeChildrenMapSignal(node, value, this.identitySymbol, pathNode, logic, adapter, createChildNode);
1367
- }
1368
- }
1369
- class ChildFieldNodeStructure extends FieldNodeStructure {
1370
- parent;
1371
- root;
1372
- pathKeys;
1373
- keyInParent;
1374
- value;
1375
- childrenMap;
1376
- get fieldManager() {
1377
- return this.root.structure.fieldManager;
1378
- }
1379
- constructor(node, pathNode, logic, parent, identityInParent, initialKeyInParent, adapter, createChildNode) {
1380
- super(logic);
1381
- this.parent = parent;
1382
- this.root = this.parent.structure.root;
1383
- this.pathKeys = computed(() => [...parent.structure.pathKeys(), this.keyInParent()], ...(ngDevMode ? [{
1384
- debugName: "pathKeys"
1385
- }] : []));
1386
- if (identityInParent === undefined) {
1387
- const key = initialKeyInParent;
1388
- this.keyInParent = computed(() => {
1389
- if (parent.structure.childrenMap()?.get(key) !== node) {
1390
- throw new Error(`RuntimeError: orphan field, looking for property '${key}' of ${getDebugName(parent)}`);
1391
- }
1392
- return key;
1393
- }, ...(ngDevMode ? [{
1394
- debugName: "keyInParent"
1395
- }] : []));
1396
- } else {
1397
- let lastKnownKey = initialKeyInParent;
1398
- this.keyInParent = computed(() => {
1399
- const parentValue = parent.structure.value();
1400
- if (!isArray(parentValue)) {
1401
- throw new Error(`RuntimeError: orphan field, expected ${getDebugName(parent)} to be an array`);
1402
- }
1403
- const data = parentValue[lastKnownKey];
1404
- if (isObject(data) && data.hasOwnProperty(parent.structure.identitySymbol) && data[parent.structure.identitySymbol] === identityInParent) {
1405
- return lastKnownKey;
1406
- }
1407
- for (let i = 0; i < parentValue.length; i++) {
1408
- const data = parentValue[i];
1409
- if (isObject(data) && data.hasOwnProperty(parent.structure.identitySymbol) && data[parent.structure.identitySymbol] === identityInParent) {
1410
- return lastKnownKey = i.toString();
1411
- }
1412
- }
1413
- throw new Error(`RuntimeError: orphan field, can't find element in array ${getDebugName(parent)}`);
1414
- }, ...(ngDevMode ? [{
1415
- debugName: "keyInParent"
1416
- }] : []));
1417
- }
1418
- this.value = deepSignal(this.parent.structure.value, this.keyInParent);
1419
- this.childrenMap = makeChildrenMapSignal(node, this.value, this.identitySymbol, pathNode, logic, adapter, createChildNode);
1420
- this.fieldManager.structures.add(this);
1421
- }
1422
- }
1423
- let globalId = 0;
1424
- const ROOT_PATH_KEYS = computed(() => [], ...(ngDevMode ? [{
1425
- debugName: "ROOT_PATH_KEYS"
1426
- }] : []));
1427
- const ROOT_KEY_IN_PARENT = computed(() => {
1428
- throw new Error(`RuntimeError: the top-level field in the form has no parent`);
1429
- }, ...(ngDevMode ? [{
1430
- debugName: "ROOT_KEY_IN_PARENT"
1431
- }] : []));
1432
- function makeChildrenMapSignal(node, valueSignal, identitySymbol, pathNode, logic, adapter, createChildNode) {
1433
- return linkedSignal({
1434
- source: valueSignal,
1435
- computation: (value, previous) => {
1436
- let childrenMap = previous?.value;
1437
- if (!isObject(value)) {
1438
- return undefined;
1439
- }
1440
- const isValueArray = isArray(value);
1441
- if (childrenMap !== undefined) {
1442
- let oldKeys = undefined;
1443
- if (isValueArray) {
1444
- oldKeys = new Set(childrenMap.keys());
1445
- for (let i = 0; i < value.length; i++) {
1446
- const childValue = value[i];
1447
- if (isObject(childValue) && childValue.hasOwnProperty(identitySymbol)) {
1448
- oldKeys.delete(childValue[identitySymbol]);
1449
- } else {
1450
- oldKeys.delete(i.toString());
1451
- }
1452
- }
1453
- for (const key of oldKeys) {
1454
- childrenMap.delete(key);
1455
- }
1456
- } else {
1457
- for (let key of childrenMap.keys()) {
1458
- if (!value.hasOwnProperty(key)) {
1459
- childrenMap.delete(key);
1460
- }
1461
- }
1462
- }
1463
- }
1464
- for (let key of Object.keys(value)) {
1465
- let trackingId = undefined;
1466
- const childValue = value[key];
1467
- if (childValue === undefined) {
1468
- childrenMap?.delete(key);
1469
- continue;
1470
- }
1471
- if (isValueArray && isObject(childValue) && !isArray(childValue)) {
1472
- trackingId = childValue[identitySymbol] ??= Symbol(ngDevMode ? `id:${globalId++}` : '');
1473
- }
1474
- const identity = trackingId ?? key;
1475
- if (childrenMap?.has(identity)) {
1476
- continue;
1477
- }
1478
- let childPath;
1479
- let childLogic;
1480
- if (isValueArray) {
1481
- childPath = pathNode.getChild(DYNAMIC);
1482
- childLogic = logic.getChild(DYNAMIC);
1483
- } else {
1484
- childPath = pathNode.getChild(key);
1485
- childLogic = logic.getChild(key);
1486
- }
1487
- childrenMap ??= new Map();
1488
- childrenMap.set(identity, createChildNode({
1489
- kind: 'child',
1490
- parent: node,
1491
- pathNode: childPath,
1492
- logic: childLogic,
1493
- initialKeyInParent: key,
1494
- identityInParent: trackingId,
1495
- fieldAdapter: adapter
1496
- }));
1497
- }
1498
- return childrenMap;
1499
- },
1500
- equal: () => false
1501
- });
1502
- }
1503
- function getDebugName(node) {
1504
- return `<root>.${node.structure.pathKeys().join('.')}`;
1505
- }
1506
-
1507
- class FieldSubmitState {
1508
- node;
1509
- selfSubmitting = signal(false, ...(ngDevMode ? [{
1510
- debugName: "selfSubmitting"
1511
- }] : []));
1512
- serverErrors;
1513
- constructor(node) {
1514
- this.node = node;
1515
- this.serverErrors = linkedSignal(...(ngDevMode ? [{
1516
- debugName: "serverErrors",
1517
- source: this.node.structure.value,
1518
- computation: () => []
1519
- }] : [{
1520
- source: this.node.structure.value,
1521
- computation: () => []
1522
- }]));
1523
- }
1524
- submitting = computed(() => {
1525
- return this.selfSubmitting() || (this.node.structure.parent?.submitting() ?? false);
1526
- }, ...(ngDevMode ? [{
1527
- debugName: "submitting"
1528
- }] : []));
1529
- }
1530
-
1531
- class FieldNode {
1532
- structure;
1533
- validationState;
1534
- metadataState;
1535
- nodeState;
1536
- submitState;
1537
- fieldAdapter;
1538
- _context = undefined;
1539
- get context() {
1540
- return this._context ??= new FieldNodeContext(this);
1541
- }
1542
- fieldProxy = new Proxy(() => this, FIELD_PROXY_HANDLER);
1543
- constructor(options) {
1544
- this.fieldAdapter = options.fieldAdapter;
1545
- this.structure = this.fieldAdapter.createStructure(this, options);
1546
- this.validationState = this.fieldAdapter.createValidationState(this, options);
1547
- this.nodeState = this.fieldAdapter.createNodeState(this, options);
1548
- this.metadataState = new FieldMetadataState(this);
1549
- this.submitState = new FieldSubmitState(this);
1550
- }
1551
- pendingSync = linkedSignal(...(ngDevMode ? [{
1552
- debugName: "pendingSync",
1553
- source: () => this.value(),
1554
- computation: () => undefined
1555
- }] : [{
1556
- source: () => this.value(),
1557
- computation: () => undefined
1558
- }]));
1559
- get logicNode() {
1560
- return this.structure.logic;
1561
- }
1562
- get value() {
1563
- return this.structure.value;
1564
- }
1565
- _controlValue = linkedSignal(() => this.value(), ...(ngDevMode ? [{
1566
- debugName: "_controlValue"
1567
- }] : []));
1568
- get controlValue() {
1569
- return this._controlValue.asReadonly();
1570
- }
1571
- get keyInParent() {
1572
- return this.structure.keyInParent;
1573
- }
1574
- get errors() {
1575
- return this.validationState.errors;
1576
- }
1577
- get errorSummary() {
1578
- return this.validationState.errorSummary;
1579
- }
1580
- get pending() {
1581
- return this.validationState.pending;
1582
- }
1583
- get valid() {
1584
- return this.validationState.valid;
1585
- }
1586
- get invalid() {
1587
- return this.validationState.invalid;
1588
- }
1589
- get dirty() {
1590
- return this.nodeState.dirty;
1591
- }
1592
- get touched() {
1593
- return this.nodeState.touched;
1594
- }
1595
- get disabled() {
1596
- return this.nodeState.disabled;
1597
- }
1598
- get disabledReasons() {
1599
- return this.nodeState.disabledReasons;
1600
- }
1601
- get hidden() {
1602
- return this.nodeState.hidden;
1603
- }
1604
- get readonly() {
1605
- return this.nodeState.readonly;
1606
- }
1607
- get fieldBindings() {
1608
- return this.nodeState.fieldBindings;
1609
- }
1610
- get submitting() {
1611
- return this.submitState.submitting;
1612
- }
1613
- get name() {
1614
- return this.nodeState.name;
1615
- }
1616
- metadataOrUndefined(key) {
1617
- return this.hasMetadata(key) ? this.metadata(key) : undefined;
1618
- }
1619
- get max() {
1620
- return this.metadataOrUndefined(MAX);
1621
- }
1622
- get maxLength() {
1623
- return this.metadataOrUndefined(MAX_LENGTH);
1624
- }
1625
- get min() {
1626
- return this.metadataOrUndefined(MIN);
1627
- }
1628
- get minLength() {
1629
- return this.metadataOrUndefined(MIN_LENGTH);
1630
- }
1631
- get pattern() {
1632
- return this.metadataOrUndefined(PATTERN) ?? EMPTY;
1633
- }
1634
- get required() {
1635
- return this.metadataOrUndefined(REQUIRED) ?? FALSE;
1636
- }
1637
- metadata(key) {
1638
- return this.metadataState.get(key);
1639
- }
1640
- hasMetadata(key) {
1641
- return this.metadataState.has(key);
1642
- }
1643
- markAsTouched() {
1644
- this.nodeState.markAsTouched();
1645
- this.sync();
1646
- }
1647
- markAsDirty() {
1648
- this.nodeState.markAsDirty();
1649
- }
1650
- reset() {
1651
- this.nodeState.markAsUntouched();
1652
- this.nodeState.markAsPristine();
1653
- for (const child of this.structure.children()) {
1654
- child.reset();
1655
- }
1656
- }
1657
- setControlValue(newValue) {
1658
- this._controlValue.set(newValue);
1659
- this.markAsDirty();
1660
- this.debounceSync();
1661
- }
1662
- sync() {
1663
- this.value.set(this.controlValue());
1664
- this.pendingSync.set(undefined);
1665
- }
1666
- debounceSync() {
1667
- const promise = this.nodeState.debouncer();
1668
- if (promise) {
1669
- promise.then(() => {
1670
- if (promise === this.pendingSync()) {
1671
- this.sync();
1672
- }
1673
- });
1674
- this.pendingSync.set(promise);
1675
- } else {
1676
- this.sync();
1677
- }
1678
- }
1679
- static newRoot(fieldManager, value, pathNode, adapter) {
1680
- return adapter.newRoot(fieldManager, value, pathNode, adapter);
1681
- }
1682
- static newChild(options) {
1683
- return options.fieldAdapter.newChild(options);
1684
- }
1685
- createStructure(options) {
1686
- 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);
1687
- }
1688
- }
1689
- const EMPTY = computed(() => [], ...(ngDevMode ? [{
1690
- debugName: "EMPTY"
1691
- }] : []));
1692
- const FALSE = computed(() => false, ...(ngDevMode ? [{
1693
- debugName: "FALSE"
1694
- }] : []));
1695
-
1696
- class FieldNodeState {
1697
- node;
1698
- selfTouched = signal(false, ...(ngDevMode ? [{
1699
- debugName: "selfTouched"
1700
- }] : []));
1701
- selfDirty = signal(false, ...(ngDevMode ? [{
1702
- debugName: "selfDirty"
1703
- }] : []));
1704
- markAsTouched() {
1705
- this.selfTouched.set(true);
1706
- }
1707
- markAsDirty() {
1708
- this.selfDirty.set(true);
1709
- }
1710
- markAsPristine() {
1711
- this.selfDirty.set(false);
1712
- }
1713
- markAsUntouched() {
1714
- this.selfTouched.set(false);
1715
- }
1716
- fieldBindings = signal([], ...(ngDevMode ? [{
1717
- debugName: "fieldBindings"
1718
- }] : []));
1719
- constructor(node) {
1720
- this.node = node;
1721
- }
1722
- dirty = computed(() => {
1723
- const selfDirtyValue = this.selfDirty() && !this.isNonInteractive();
1724
- return reduceChildren(this.node, selfDirtyValue, (child, value) => value || child.nodeState.dirty(), shortCircuitTrue);
1725
- }, ...(ngDevMode ? [{
1726
- debugName: "dirty"
1727
- }] : []));
1728
- touched = computed(() => {
1729
- const selfTouchedValue = this.selfTouched() && !this.isNonInteractive();
1730
- return reduceChildren(this.node, selfTouchedValue, (child, value) => value || child.nodeState.touched(), shortCircuitTrue);
1731
- }, ...(ngDevMode ? [{
1732
- debugName: "touched"
1733
- }] : []));
1734
- disabledReasons = computed(() => [...(this.node.structure.parent?.nodeState.disabledReasons() ?? []), ...this.node.logicNode.logic.disabledReasons.compute(this.node.context)], ...(ngDevMode ? [{
1735
- debugName: "disabledReasons"
1736
- }] : []));
1737
- disabled = computed(() => !!this.disabledReasons().length, ...(ngDevMode ? [{
1738
- debugName: "disabled"
1739
- }] : []));
1740
- readonly = computed(() => (this.node.structure.parent?.nodeState.readonly() || this.node.logicNode.logic.readonly.compute(this.node.context)) ?? false, ...(ngDevMode ? [{
1741
- debugName: "readonly"
1742
- }] : []));
1743
- hidden = computed(() => (this.node.structure.parent?.nodeState.hidden() || this.node.logicNode.logic.hidden.compute(this.node.context)) ?? false, ...(ngDevMode ? [{
1744
- debugName: "hidden"
1745
- }] : []));
1746
- name = computed(() => {
1747
- const parent = this.node.structure.parent;
1748
- if (!parent) {
1749
- return this.node.structure.fieldManager.rootName;
1750
- }
1751
- return `${parent.name()}.${this.node.structure.keyInParent()}`;
1752
- }, ...(ngDevMode ? [{
1753
- debugName: "name"
1754
- }] : []));
1755
- debouncer() {
1756
- if (this.node.logicNode.logic.hasAggregateMetadata(DEBOUNCER)) {
1757
- const debouncerLogic = this.node.logicNode.logic.getAggregateMetadata(DEBOUNCER);
1758
- const debouncer = debouncerLogic.compute(this.node.context);
1759
- if (debouncer) {
1760
- return debouncer(this.node.context);
1761
- }
1762
- }
1763
- return this.node.structure.parent?.nodeState.debouncer();
1764
- }
1765
- isNonInteractive = computed(() => this.hidden() || this.disabled() || this.readonly(), ...(ngDevMode ? [{
1766
- debugName: "isNonInteractive"
1767
- }] : []));
1768
- }
1769
-
1770
- class BasicFieldAdapter {
1771
- newRoot(fieldManager, value, pathNode, adapter) {
1772
- return new FieldNode({
1773
- kind: 'root',
1774
- fieldManager,
1775
- value,
1776
- pathNode,
1777
- logic: pathNode.builder.build(),
1778
- fieldAdapter: adapter
1779
- });
1780
- }
1781
- newChild(options) {
1782
- return new FieldNode(options);
1783
- }
1784
- createNodeState(node) {
1785
- return new FieldNodeState(node);
1786
- }
1787
- createValidationState(node) {
1788
- return new FieldValidationState(node);
1789
- }
1790
- createStructure(node, options) {
1791
- return node.createStructure(options);
1792
- }
1793
- }
1794
-
1795
- class FormFieldManager {
1796
- injector;
1797
- rootName;
1798
- constructor(injector, rootName) {
1799
- this.injector = injector;
1800
- this.rootName = rootName ?? `${this.injector.get(APP_ID)}.form${nextFormId++}`;
1801
- }
1802
- structures = new Set();
1803
- createFieldManagementEffect(root) {
1804
- effect(() => {
1805
- const liveStructures = new Set();
1806
- this.markStructuresLive(root, liveStructures);
1807
- for (const structure of this.structures) {
1808
- if (!liveStructures.has(structure)) {
1809
- this.structures.delete(structure);
1810
- untracked(() => structure.destroy());
1811
- }
1812
- }
1813
- }, {
1814
- injector: this.injector
1815
- });
1816
- }
1817
- markStructuresLive(structure, liveStructures) {
1818
- liveStructures.add(structure);
1819
- for (const child of structure.children()) {
1820
- this.markStructuresLive(child.structure, liveStructures);
1821
- }
1822
- }
1823
- }
1824
- let nextFormId = 0;
1825
-
1826
- function normalizeFormArgs(args) {
1827
- let model;
1828
- let schema;
1829
- let options;
1830
- if (args.length === 3) {
1831
- [model, schema, options] = args;
1832
- } else if (args.length === 2) {
1833
- if (isSchemaOrSchemaFn(args[1])) {
1834
- [model, schema] = args;
1835
- } else {
1836
- [model, options] = args;
1837
- }
1838
- } else {
1839
- [model] = args;
1840
- }
1841
- return [model, schema, options];
1842
- }
1843
-
1844
- function form(...args) {
1845
- const [model, schema, options] = normalizeFormArgs(args);
1846
- const injector = options?.injector ?? inject(Injector);
1847
- const pathNode = runInInjectionContext(injector, () => SchemaImpl.rootCompile(schema));
1848
- const fieldManager = new FormFieldManager(injector, options?.name);
1849
- const adapter = options?.adapter ?? new BasicFieldAdapter();
1850
- const fieldRoot = FieldNode.newRoot(fieldManager, model, pathNode, adapter);
1851
- fieldManager.createFieldManagementEffect(fieldRoot.structure);
1852
- return fieldRoot.fieldProxy;
1853
- }
1854
- function applyEach(path, schema) {
1855
- assertPathIsCurrent(path);
1856
- const elementPath = FieldPathNode.unwrapFieldPath(path).getChild(DYNAMIC).fieldPathProxy;
1857
- apply(elementPath, schema);
1858
- }
1859
- function apply(path, schema) {
1860
- assertPathIsCurrent(path);
1861
- const pathNode = FieldPathNode.unwrapFieldPath(path);
1862
- pathNode.mergeIn(SchemaImpl.create(schema));
1863
- }
1864
- function applyWhen(path, logic, schema) {
1865
- assertPathIsCurrent(path);
1866
- const pathNode = FieldPathNode.unwrapFieldPath(path);
1867
- pathNode.mergeIn(SchemaImpl.create(schema), {
1868
- fn: logic,
1869
- path
1870
- });
1871
- }
1872
- function applyWhenValue(path, predicate, schema) {
1873
- applyWhen(path, ({
1874
- value
1875
- }) => predicate(value()), schema);
1876
- }
1877
- async function submit(form, action) {
1878
- const node = form();
1879
- markAllAsTouched(node);
1880
- if (node.invalid()) {
1881
- return;
1882
- }
1883
- node.submitState.selfSubmitting.set(true);
1884
- try {
1885
- const errors = await action(form);
1886
- errors && setServerErrors(node, errors);
1887
- } finally {
1888
- node.submitState.selfSubmitting.set(false);
1889
- }
1890
- }
1891
- function setServerErrors(submittedField, errors) {
1892
- if (!isArray(errors)) {
1893
- errors = [errors];
1894
- }
1895
- const errorsByField = new Map();
1896
- for (const error of errors) {
1897
- const errorWithField = addDefaultField(error, submittedField.fieldProxy);
1898
- const field = errorWithField.field();
1899
- let fieldErrors = errorsByField.get(field);
1900
- if (!fieldErrors) {
1901
- fieldErrors = [];
1902
- errorsByField.set(field, fieldErrors);
1903
- }
1904
- fieldErrors.push(errorWithField);
1905
- }
1906
- for (const [field, fieldErrors] of errorsByField) {
1907
- field.submitState.serverErrors.set(fieldErrors);
1908
- }
1909
- }
1910
- function schema(fn) {
1911
- return SchemaImpl.create(fn);
1912
- }
1913
- function markAllAsTouched(node) {
1914
- node.markAsTouched();
1915
- for (const child of node.structure.children()) {
1916
- markAllAsTouched(child);
1917
- }
1918
- }
1919
-
1920
445
  const EMAIL_REGEXP = /^(?=.{1,254}$)(?=.{1,64}@)[a-zA-Z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-zA-Z0-9!#$%&'*+/=?^_`{|}~-]+)*@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/;
1921
446
  function email(path, config) {
1922
447
  validate(path, ctx => {
@@ -1949,7 +474,9 @@ function max(path, maxValue, config) {
1949
474
  if (max === undefined || Number.isNaN(max)) {
1950
475
  return undefined;
1951
476
  }
1952
- if (ctx.value() > max) {
477
+ const value = ctx.value();
478
+ const numValue = !value && value !== 0 ? NaN : Number(value);
479
+ if (numValue > max) {
1953
480
  if (config?.error) {
1954
481
  return getOption(config.error, ctx);
1955
482
  } else {
@@ -2001,7 +528,9 @@ function min(path, minValue, config) {
2001
528
  if (min === undefined || Number.isNaN(min)) {
2002
529
  return undefined;
2003
530
  }
2004
- if (ctx.value() < min) {
531
+ const value = ctx.value();
532
+ const numValue = !value && value !== 0 ? NaN : Number(value);
533
+ if (numValue < min) {
2005
534
  if (config?.error) {
2006
535
  return getOption(config.error, ctx);
2007
536
  } else {
@@ -2130,8 +659,10 @@ function standardIssueToFormTreeError(field, issue) {
2130
659
  const pathKey = typeof pathPart === 'object' ? pathPart.key : pathPart;
2131
660
  target = target[pathKey];
2132
661
  }
2133
- return addDefaultField(standardSchemaError(issue), target);
662
+ return addDefaultField(standardSchemaError(issue, {
663
+ message: issue.message
664
+ }), target);
2134
665
  }
2135
666
 
2136
- export { AggregateMetadataKey, CustomValidationError, EmailValidationError, FIELD, Field, MAX, MAX_LENGTH, MIN, MIN_LENGTH, MaxLengthValidationError, MaxValidationError, MetadataKey, MinLengthValidationError, MinValidationError, NgValidationError, PATTERN, PatternValidationError, REQUIRED, RequiredValidationError, StandardSchemaValidationError, aggregateMetadata, andMetadataKey, apply, applyEach, applyWhen, applyWhenValue, createMetadataKey, customError, debounce, disabled, email, emailError, form, hidden, listMetadataKey, max, maxError, maxLength, maxLengthError, maxMetadataKey, metadata, min, minError, minLength, minLengthError, minMetadataKey, orMetadataKey, pattern, patternError, readonly, reducedMetadataKey, required, requiredError, schema, standardSchemaError, submit, validate, validateAsync, validateHttp, validateStandardSchema, validateTree };
667
+ export { CustomValidationError, EmailValidationError, FIELD, Field, MAX, MAX_LENGTH, MIN, MIN_LENGTH, MaxLengthValidationError, MaxValidationError, MinLengthValidationError, MinValidationError, NgValidationError, PATTERN, PatternValidationError, REQUIRED, RequiredValidationError, StandardSchemaValidationError, aggregateMetadata, createMetadataKey, customError, debounce, disabled, email, emailError, hidden, max, maxError, maxLength, maxLengthError, metadata, min, minError, minLength, minLengthError, pattern, patternError, readonly, required, requiredError, standardSchemaError, validate, validateAsync, validateHttp, validateStandardSchema, validateTree };
2137
668
  //# sourceMappingURL=signals.mjs.map