Primeiro commit do projeto Angular
This commit is contained in:
+21
@@ -0,0 +1,21 @@
|
||||
The MIT License
|
||||
|
||||
Copyright (c) 2010-2026 Google LLC. https://angular.dev/license
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in
|
||||
all copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
THE SOFTWARE.
|
||||
+7
@@ -0,0 +1,7 @@
|
||||
# Angular
|
||||
|
||||
The sources for this package are in the main [Angular](https://github.com/angular/angular) repo. Please file issues and pull requests against that repo.
|
||||
|
||||
Usage information and reference details can be found in [Angular documentation](https://angular.dev/overview).
|
||||
|
||||
License: MIT
|
||||
+1729
File diff suppressed because it is too large
Load Diff
+1
File diff suppressed because one or more lines are too long
+5365
File diff suppressed because it is too large
Load Diff
+1
File diff suppressed because one or more lines are too long
+659
@@ -0,0 +1,659 @@
|
||||
/**
|
||||
* @license Angular v21.2.1
|
||||
* (c) 2010-2026 Google LLC. https://angular.dev/
|
||||
* License: MIT
|
||||
*/
|
||||
|
||||
import { FieldNode, getInjectorFromOptions, FieldNodeState, FieldNodeStructure, calculateValidationSelfStatus, extractNestedReactiveErrors, BasicFieldAdapter, form, normalizeFormArgs, signalErrorsToValidationErrors } from './_validation_errors-chunk.mjs';
|
||||
export { CompatValidationError } from './_validation_errors-chunk.mjs';
|
||||
import { linkedSignal, untracked, runInInjectionContext, computed, signal, ɵRuntimeError as _RuntimeError, EventEmitter, inject, Injector, effect } from '@angular/core';
|
||||
import { AbstractControl, ValueChangeEvent, StatusChangeEvent, TouchedChangeEvent, PristineChangeEvent, FormResetEvent } from '@angular/forms';
|
||||
import { toSignal } from '@angular/core/rxjs-interop';
|
||||
import { ReplaySubject } from 'rxjs';
|
||||
import { map, takeUntil } from 'rxjs/operators';
|
||||
import '@angular/core/primitives/signals';
|
||||
|
||||
class CompatFieldNode extends FieldNode {
|
||||
options;
|
||||
control;
|
||||
constructor(options) {
|
||||
super(options);
|
||||
this.options = options;
|
||||
this.control = this.options.control;
|
||||
}
|
||||
}
|
||||
function makeCreateDestroySubject() {
|
||||
let destroy$ = new ReplaySubject(1);
|
||||
return () => {
|
||||
destroy$.next();
|
||||
destroy$.complete();
|
||||
return destroy$ = new ReplaySubject(1);
|
||||
};
|
||||
}
|
||||
function extractControlPropToSignal(options, makeSignal) {
|
||||
const injector = getInjectorFromOptions(options);
|
||||
const createDestroySubject = makeCreateDestroySubject();
|
||||
const signalOfControlSignal = linkedSignal({
|
||||
...(ngDevMode ? {
|
||||
debugName: "signalOfControlSignal"
|
||||
} : {}),
|
||||
source: options.control,
|
||||
computation: control => {
|
||||
return untracked(() => {
|
||||
return runInInjectionContext(injector, () => makeSignal(control, createDestroySubject()));
|
||||
});
|
||||
}
|
||||
});
|
||||
return computed(() => signalOfControlSignal()());
|
||||
}
|
||||
const getControlStatusSignal = (options, getValue) => {
|
||||
return extractControlPropToSignal(options, (c, destroy$) => toSignal(c.statusChanges.pipe(map(() => getValue(c)), takeUntil(destroy$)), {
|
||||
initialValue: getValue(c)
|
||||
}));
|
||||
};
|
||||
const getControlEventsSignal = (options, getValue) => {
|
||||
return extractControlPropToSignal(options, (c, destroy$) => toSignal(c.events.pipe(map(() => {
|
||||
return getValue(c);
|
||||
}), takeUntil(destroy$)), {
|
||||
initialValue: getValue(c)
|
||||
}));
|
||||
};
|
||||
|
||||
class CompatNodeState extends FieldNodeState {
|
||||
compatNode;
|
||||
touched;
|
||||
dirty;
|
||||
disabled;
|
||||
control;
|
||||
constructor(compatNode, options) {
|
||||
super(compatNode);
|
||||
this.compatNode = compatNode;
|
||||
this.control = options.control;
|
||||
this.touched = getControlEventsSignal(options, c => c.touched);
|
||||
this.dirty = getControlEventsSignal(options, c => c.dirty);
|
||||
const controlDisabled = getControlStatusSignal(options, c => c.disabled);
|
||||
this.disabled = computed(() => {
|
||||
return controlDisabled() || this.disabledReasons().length > 0;
|
||||
}, ...(ngDevMode ? [{
|
||||
debugName: "disabled"
|
||||
}] : []));
|
||||
}
|
||||
markAsDirty() {
|
||||
this.control().markAsDirty();
|
||||
}
|
||||
markAsTouched() {
|
||||
this.control().markAsTouched();
|
||||
}
|
||||
markAsPristine() {
|
||||
this.control().markAsPristine();
|
||||
}
|
||||
markAsUntouched() {
|
||||
this.control().markAsUntouched();
|
||||
}
|
||||
}
|
||||
|
||||
function getParentFromOptions(options) {
|
||||
if (options.kind === 'root') {
|
||||
return undefined;
|
||||
}
|
||||
return options.parent;
|
||||
}
|
||||
function getFieldManagerFromOptions(options) {
|
||||
if (options.kind === 'root') {
|
||||
return options.fieldManager;
|
||||
}
|
||||
return options.parent.structure.root.structure.fieldManager;
|
||||
}
|
||||
function getControlValueSignal(options) {
|
||||
const value = extractControlPropToSignal(options, (control, destroy$) => {
|
||||
return toSignal(control.valueChanges.pipe(map(() => control.getRawValue()), takeUntil(destroy$)), {
|
||||
initialValue: control.getRawValue()
|
||||
});
|
||||
});
|
||||
value.set = value => {
|
||||
options.control().setValue(value);
|
||||
};
|
||||
value.update = fn => {
|
||||
value.set(fn(value()));
|
||||
};
|
||||
return value;
|
||||
}
|
||||
class CompatStructure extends FieldNodeStructure {
|
||||
value;
|
||||
keyInParent;
|
||||
root;
|
||||
pathKeys;
|
||||
children = signal([], ...(ngDevMode ? [{
|
||||
debugName: "children"
|
||||
}] : []));
|
||||
childrenMap = computed(() => undefined, ...(ngDevMode ? [{
|
||||
debugName: "childrenMap"
|
||||
}] : []));
|
||||
parent;
|
||||
fieldManager;
|
||||
constructor(node, options) {
|
||||
super(options.logic, node, () => {
|
||||
throw new _RuntimeError(1911, ngDevMode && `Compat nodes don't have children.`);
|
||||
});
|
||||
this.value = getControlValueSignal(options);
|
||||
this.parent = getParentFromOptions(options);
|
||||
this.root = this.parent?.structure.root ?? node;
|
||||
this.fieldManager = getFieldManagerFromOptions(options);
|
||||
const identityInParent = options.kind === 'child' ? options.identityInParent : undefined;
|
||||
const initialKeyInParent = options.kind === 'child' ? options.initialKeyInParent : undefined;
|
||||
this.keyInParent = this.createKeyInParent(options, identityInParent, initialKeyInParent);
|
||||
this.pathKeys = computed(() => this.parent ? [...this.parent.structure.pathKeys(), this.keyInParent()] : [], ...(ngDevMode ? [{
|
||||
debugName: "pathKeys"
|
||||
}] : []));
|
||||
}
|
||||
getChild() {
|
||||
return undefined;
|
||||
}
|
||||
}
|
||||
|
||||
const EMPTY_ARRAY_SIGNAL = computed(() => [], ...(ngDevMode ? [{
|
||||
debugName: "EMPTY_ARRAY_SIGNAL"
|
||||
}] : []));
|
||||
const TRUE_SIGNAL = computed(() => true, ...(ngDevMode ? [{
|
||||
debugName: "TRUE_SIGNAL"
|
||||
}] : []));
|
||||
class CompatValidationState {
|
||||
syncValid;
|
||||
errors;
|
||||
pending;
|
||||
invalid;
|
||||
valid;
|
||||
parseErrors = computed(() => [], ...(ngDevMode ? [{
|
||||
debugName: "parseErrors"
|
||||
}] : []));
|
||||
constructor(options) {
|
||||
this.syncValid = getControlStatusSignal(options, c => c.status === 'VALID');
|
||||
this.errors = getControlStatusSignal(options, extractNestedReactiveErrors);
|
||||
this.pending = getControlStatusSignal(options, c => c.pending);
|
||||
this.valid = getControlStatusSignal(options, c => {
|
||||
return c.valid;
|
||||
});
|
||||
this.invalid = getControlStatusSignal(options, c => {
|
||||
return c.invalid;
|
||||
});
|
||||
}
|
||||
asyncErrors = EMPTY_ARRAY_SIGNAL;
|
||||
errorSummary = EMPTY_ARRAY_SIGNAL;
|
||||
rawSyncTreeErrors = EMPTY_ARRAY_SIGNAL;
|
||||
syncErrors = EMPTY_ARRAY_SIGNAL;
|
||||
rawAsyncErrors = EMPTY_ARRAY_SIGNAL;
|
||||
shouldSkipValidation = TRUE_SIGNAL;
|
||||
status = computed(() => {
|
||||
return calculateValidationSelfStatus(this);
|
||||
}, ...(ngDevMode ? [{
|
||||
debugName: "status"
|
||||
}] : []));
|
||||
}
|
||||
|
||||
class CompatFieldAdapter {
|
||||
basicAdapter = new BasicFieldAdapter();
|
||||
newRoot(fieldManager, value, pathNode, adapter) {
|
||||
if (value() instanceof AbstractControl) {
|
||||
return createCompatNode({
|
||||
kind: 'root',
|
||||
fieldManager,
|
||||
value,
|
||||
pathNode,
|
||||
logic: pathNode.builder.build(),
|
||||
fieldAdapter: adapter
|
||||
});
|
||||
}
|
||||
return this.basicAdapter.newRoot(fieldManager, value, pathNode, adapter);
|
||||
}
|
||||
createNodeState(node, options) {
|
||||
if (!options.control) {
|
||||
return this.basicAdapter.createNodeState(node);
|
||||
}
|
||||
return new CompatNodeState(node, options);
|
||||
}
|
||||
createStructure(node, options) {
|
||||
if (!options.control) {
|
||||
return this.basicAdapter.createStructure(node, options);
|
||||
}
|
||||
return new CompatStructure(node, options);
|
||||
}
|
||||
createValidationState(node, options) {
|
||||
if (!options.control) {
|
||||
return this.basicAdapter.createValidationState(node);
|
||||
}
|
||||
return new CompatValidationState(options);
|
||||
}
|
||||
newChild(options) {
|
||||
const value = options.parent.value()[options.initialKeyInParent];
|
||||
if (value instanceof AbstractControl) {
|
||||
return createCompatNode(options);
|
||||
}
|
||||
return new FieldNode(options);
|
||||
}
|
||||
}
|
||||
function createCompatNode(options) {
|
||||
const control = options.kind === 'root' ? options.value : computed(() => {
|
||||
return options.parent.value()[options.initialKeyInParent];
|
||||
});
|
||||
return new CompatFieldNode({
|
||||
...options,
|
||||
control
|
||||
});
|
||||
}
|
||||
|
||||
function compatForm(...args) {
|
||||
const [model, maybeSchema, maybeOptions] = normalizeFormArgs(args);
|
||||
const options = {
|
||||
...maybeOptions,
|
||||
adapter: new CompatFieldAdapter()
|
||||
};
|
||||
const schema = maybeSchema || (() => {});
|
||||
return form(model, schema, options);
|
||||
}
|
||||
|
||||
const NG_STATUS_CLASSES = {
|
||||
'ng-touched': ({
|
||||
state
|
||||
}) => state().touched(),
|
||||
'ng-untouched': ({
|
||||
state
|
||||
}) => !state().touched(),
|
||||
'ng-dirty': ({
|
||||
state
|
||||
}) => state().dirty(),
|
||||
'ng-pristine': ({
|
||||
state
|
||||
}) => !state().dirty(),
|
||||
'ng-valid': ({
|
||||
state
|
||||
}) => state().valid(),
|
||||
'ng-invalid': ({
|
||||
state
|
||||
}) => state().invalid(),
|
||||
'ng-pending': ({
|
||||
state
|
||||
}) => state().pending()
|
||||
};
|
||||
|
||||
class SignalFormControl extends AbstractControl {
|
||||
fieldTree;
|
||||
sourceValue;
|
||||
fieldState;
|
||||
initialValue;
|
||||
pendingParentNotifications = 0;
|
||||
onChangeCallbacks = [];
|
||||
onDisabledChangeCallbacks = [];
|
||||
valueChanges = new EventEmitter();
|
||||
statusChanges = new EventEmitter();
|
||||
constructor(value, schemaOrOptions, options) {
|
||||
super(null, null);
|
||||
const [model, schema, opts] = normalizeFormArgs([signal(value), schemaOrOptions, options]);
|
||||
this.sourceValue = model;
|
||||
this.initialValue = value;
|
||||
const injector = opts?.injector ?? inject(Injector);
|
||||
const rawTree = schema ? compatForm(this.sourceValue, schema, {
|
||||
injector
|
||||
}) : compatForm(this.sourceValue, {
|
||||
injector
|
||||
});
|
||||
this.fieldTree = wrapFieldTreeForSyncUpdates(rawTree, () => this.parent?.updateValueAndValidity({
|
||||
sourceControl: this
|
||||
}));
|
||||
this.fieldState = this.fieldTree();
|
||||
this.defineCompatProperties();
|
||||
effect(() => {
|
||||
const value = this.sourceValue();
|
||||
untracked(() => {
|
||||
this.notifyParentUnlessPending();
|
||||
this.valueChanges.emit(value);
|
||||
this.emitControlEvent(new ValueChangeEvent(value, this));
|
||||
});
|
||||
}, {
|
||||
injector
|
||||
});
|
||||
effect(() => {
|
||||
const status = this.status;
|
||||
untracked(() => {
|
||||
this.statusChanges.emit(status);
|
||||
});
|
||||
this.emitControlEvent(new StatusChangeEvent(status, this));
|
||||
}, {
|
||||
injector
|
||||
});
|
||||
effect(() => {
|
||||
const isDisabled = this.disabled;
|
||||
untracked(() => {
|
||||
for (const fn of this.onDisabledChangeCallbacks) {
|
||||
fn(isDisabled);
|
||||
}
|
||||
});
|
||||
}, {
|
||||
injector
|
||||
});
|
||||
effect(() => {
|
||||
const isTouched = this.fieldState.touched();
|
||||
this.emitControlEvent(new TouchedChangeEvent(isTouched, this));
|
||||
const parent = this.parent;
|
||||
if (!parent) {
|
||||
return;
|
||||
}
|
||||
if (!isTouched) {
|
||||
parent.markAsUntouched();
|
||||
} else {
|
||||
parent.markAsTouched();
|
||||
}
|
||||
}, {
|
||||
injector
|
||||
});
|
||||
effect(() => {
|
||||
const isDirty = this.fieldState.dirty();
|
||||
this.emitControlEvent(new PristineChangeEvent(!isDirty, this));
|
||||
const parent = this.parent;
|
||||
if (!parent) {
|
||||
return;
|
||||
}
|
||||
if (isDirty) {
|
||||
parent.markAsDirty();
|
||||
} else {
|
||||
parent.markAsPristine();
|
||||
}
|
||||
}, {
|
||||
injector
|
||||
});
|
||||
}
|
||||
defineCompatProperties() {
|
||||
const valueProp = getClosureSafeProperty({
|
||||
value: getClosureSafeProperty
|
||||
});
|
||||
Object.defineProperty(this, valueProp, {
|
||||
get: () => this.sourceValue()
|
||||
});
|
||||
const errorsProp = getClosureSafeProperty({
|
||||
errors: getClosureSafeProperty
|
||||
});
|
||||
Object.defineProperty(this, errorsProp, {
|
||||
get: () => signalErrorsToValidationErrors(this.fieldState.errors())
|
||||
});
|
||||
}
|
||||
emitControlEvent(event) {
|
||||
untracked(() => {
|
||||
this._events.next(event);
|
||||
});
|
||||
}
|
||||
setValue(value, options) {
|
||||
this.updateValue(value, options);
|
||||
}
|
||||
patchValue(value, options) {
|
||||
this.updateValue(value, options);
|
||||
}
|
||||
updateValue(value, options) {
|
||||
const parent = this.scheduleParentUpdate(options);
|
||||
this.sourceValue.set(value);
|
||||
if (parent) {
|
||||
this.updateParentValueAndValidity(parent, options?.emitEvent);
|
||||
}
|
||||
if (options?.emitModelToViewChange !== false) {
|
||||
for (const fn of this.onChangeCallbacks) {
|
||||
fn(value, true);
|
||||
}
|
||||
}
|
||||
}
|
||||
registerOnChange(fn) {
|
||||
this.onChangeCallbacks.push(fn);
|
||||
}
|
||||
_unregisterOnChange(fn) {
|
||||
removeListItem(this.onChangeCallbacks, fn);
|
||||
}
|
||||
registerOnDisabledChange(fn) {
|
||||
this.onDisabledChangeCallbacks.push(fn);
|
||||
}
|
||||
_unregisterOnDisabledChange(fn) {
|
||||
removeListItem(this.onDisabledChangeCallbacks, fn);
|
||||
}
|
||||
getRawValue() {
|
||||
return this.value;
|
||||
}
|
||||
reset(value, options) {
|
||||
if (isFormControlState(value)) {
|
||||
throw unsupportedDisableEnableError();
|
||||
}
|
||||
const resetValue = value ?? this.initialValue;
|
||||
this.fieldState.reset(resetValue);
|
||||
if (value !== undefined) {
|
||||
this.updateValue(value, options);
|
||||
} else if (!options?.onlySelf) {
|
||||
const parent = this.parent;
|
||||
if (parent) {
|
||||
this.updateParentValueAndValidity(parent, options?.emitEvent);
|
||||
}
|
||||
}
|
||||
if (options?.emitEvent !== false) {
|
||||
this.emitControlEvent(new FormResetEvent(this));
|
||||
}
|
||||
}
|
||||
scheduleParentUpdate(options) {
|
||||
const parent = options?.onlySelf ? null : this.parent;
|
||||
if (options?.onlySelf || parent) {
|
||||
this.pendingParentNotifications++;
|
||||
}
|
||||
return parent;
|
||||
}
|
||||
notifyParentUnlessPending() {
|
||||
if (this.pendingParentNotifications > 0) {
|
||||
this.pendingParentNotifications--;
|
||||
return;
|
||||
}
|
||||
const parent = this.parent;
|
||||
if (parent) {
|
||||
this.updateParentValueAndValidity(parent);
|
||||
}
|
||||
}
|
||||
updateParentValueAndValidity(parent, emitEvent) {
|
||||
parent.updateValueAndValidity({
|
||||
emitEvent,
|
||||
sourceControl: this
|
||||
});
|
||||
}
|
||||
propagateToParent(opts, fn) {
|
||||
const parent = this.parent;
|
||||
if (parent && !opts?.onlySelf) {
|
||||
fn(parent);
|
||||
}
|
||||
}
|
||||
get status() {
|
||||
if (this.fieldState.disabled()) {
|
||||
return 'DISABLED';
|
||||
}
|
||||
if (this.fieldState.valid()) {
|
||||
return 'VALID';
|
||||
}
|
||||
if (this.fieldState.invalid()) {
|
||||
return 'INVALID';
|
||||
}
|
||||
return 'PENDING';
|
||||
}
|
||||
get valid() {
|
||||
return this.fieldState.valid();
|
||||
}
|
||||
get invalid() {
|
||||
return this.fieldState.invalid();
|
||||
}
|
||||
get pending() {
|
||||
return this.fieldState.pending();
|
||||
}
|
||||
get disabled() {
|
||||
return this.fieldState.disabled();
|
||||
}
|
||||
get enabled() {
|
||||
return !this.disabled;
|
||||
}
|
||||
get dirty() {
|
||||
return this.fieldState.dirty();
|
||||
}
|
||||
set dirty(_) {
|
||||
throw unsupportedFeatureError(ngDevMode && 'Setting dirty directly is not supported. Instead use markAsDirty().');
|
||||
}
|
||||
get pristine() {
|
||||
return !this.dirty;
|
||||
}
|
||||
set pristine(_) {
|
||||
throw unsupportedFeatureError(ngDevMode && 'Setting pristine directly is not supported. Instead use reset().');
|
||||
}
|
||||
get touched() {
|
||||
return this.fieldState.touched();
|
||||
}
|
||||
set touched(_) {
|
||||
throw unsupportedFeatureError(ngDevMode && 'Setting touched directly is not supported. Instead use markAsTouched() or reset().');
|
||||
}
|
||||
get untouched() {
|
||||
return !this.touched;
|
||||
}
|
||||
set untouched(_) {
|
||||
throw unsupportedFeatureError(ngDevMode && 'Setting untouched directly is not supported. Instead use reset().');
|
||||
}
|
||||
markAsTouched(opts) {
|
||||
this.fieldState.markAsTouched();
|
||||
this.propagateToParent(opts, parent => parent.markAsTouched(opts));
|
||||
}
|
||||
markAsDirty(opts) {
|
||||
this.fieldState.markAsDirty();
|
||||
this.propagateToParent(opts, parent => parent.markAsDirty(opts));
|
||||
}
|
||||
markAsPristine(opts) {
|
||||
this.fieldState.markAsPristine();
|
||||
this.propagateToParent(opts, parent => parent.markAsPristine(opts));
|
||||
}
|
||||
markAsUntouched(opts) {
|
||||
this.fieldState.markAsUntouched();
|
||||
this.propagateToParent(opts, parent => parent.markAsUntouched(opts));
|
||||
}
|
||||
updateValueAndValidity(_opts) {}
|
||||
_updateValue() {}
|
||||
_forEachChild(_cb) {}
|
||||
_anyControls(_condition) {
|
||||
return false;
|
||||
}
|
||||
_allControlsDisabled() {
|
||||
return this.disabled;
|
||||
}
|
||||
_syncPendingControls() {
|
||||
return false;
|
||||
}
|
||||
disable(_opts) {
|
||||
throw unsupportedDisableEnableError();
|
||||
}
|
||||
enable(_opts) {
|
||||
throw unsupportedDisableEnableError();
|
||||
}
|
||||
setValidators(_validators) {
|
||||
throw unsupportedValidatorsError();
|
||||
}
|
||||
setAsyncValidators(_validators) {
|
||||
throw unsupportedValidatorsError();
|
||||
}
|
||||
addValidators(_validators) {
|
||||
throw unsupportedValidatorsError();
|
||||
}
|
||||
addAsyncValidators(_validators) {
|
||||
throw unsupportedValidatorsError();
|
||||
}
|
||||
removeValidators(_validators) {
|
||||
throw unsupportedValidatorsError();
|
||||
}
|
||||
removeAsyncValidators(_validators) {
|
||||
throw unsupportedValidatorsError();
|
||||
}
|
||||
clearValidators() {
|
||||
throw unsupportedValidatorsError();
|
||||
}
|
||||
clearAsyncValidators() {
|
||||
throw unsupportedValidatorsError();
|
||||
}
|
||||
setErrors(_errors, _opts) {
|
||||
throw unsupportedFeatureError(ngDevMode && 'Imperatively setting errors is not supported in signal forms. Errors are derived from validation rules.');
|
||||
}
|
||||
markAsPending(_opts) {
|
||||
throw unsupportedFeatureError(ngDevMode && 'Imperatively marking as pending is not supported in signal forms. Pending state is derived from async validation status.');
|
||||
}
|
||||
}
|
||||
class CachingWeakMap {
|
||||
map = new WeakMap();
|
||||
getOrCreate(key, create) {
|
||||
const cached = this.map.get(key);
|
||||
if (cached) {
|
||||
return cached;
|
||||
}
|
||||
const value = create();
|
||||
this.map.set(key, value);
|
||||
return value;
|
||||
}
|
||||
}
|
||||
function wrapFieldTreeForSyncUpdates(tree, onUpdate) {
|
||||
const treeCache = new CachingWeakMap();
|
||||
const stateCache = new CachingWeakMap();
|
||||
const wrapState = state => {
|
||||
const {
|
||||
value
|
||||
} = state;
|
||||
const wrappedValue = Object.assign((...a) => value(...a), {
|
||||
set: v => {
|
||||
value.set(v);
|
||||
onUpdate();
|
||||
},
|
||||
update: fn => {
|
||||
value.update(fn);
|
||||
onUpdate();
|
||||
}
|
||||
});
|
||||
return Object.create(state, {
|
||||
value: {
|
||||
get: () => wrappedValue
|
||||
}
|
||||
});
|
||||
};
|
||||
const wrapTree = t => {
|
||||
return treeCache.getOrCreate(t, () => {
|
||||
return new Proxy(t, {
|
||||
get(target, prop, receiver) {
|
||||
const val = Reflect.get(target, prop, receiver);
|
||||
if (typeof val === 'function' && typeof prop === 'string') {
|
||||
return wrapTree(val);
|
||||
}
|
||||
return val;
|
||||
},
|
||||
apply(target, _, args) {
|
||||
const state = target(...args);
|
||||
return stateCache.getOrCreate(state, () => wrapState(state));
|
||||
}
|
||||
});
|
||||
});
|
||||
};
|
||||
return wrapTree(tree);
|
||||
}
|
||||
function isFormControlState(formState) {
|
||||
return typeof formState === 'object' && formState !== null && Object.keys(formState).length === 2 && 'value' in formState && 'disabled' in formState;
|
||||
}
|
||||
function unsupportedFeatureError(message) {
|
||||
return new _RuntimeError(1920, message ?? false);
|
||||
}
|
||||
function unsupportedDisableEnableError() {
|
||||
return unsupportedFeatureError(ngDevMode && 'Imperatively changing enabled/disabled status in form control is not supported in signal forms. Instead use a "disabled" rule to derive the disabled status from a signal.');
|
||||
}
|
||||
function unsupportedValidatorsError() {
|
||||
return unsupportedFeatureError(ngDevMode && 'Dynamically adding and removing validators is not supported in signal forms. Instead use the "applyWhen" rule to conditionally apply validators based on a signal.');
|
||||
}
|
||||
function removeListItem(list, el) {
|
||||
const index = list.indexOf(el);
|
||||
if (index > -1) list.splice(index, 1);
|
||||
}
|
||||
function getClosureSafeProperty(objWithPropertyToExtract) {
|
||||
for (let key in objWithPropertyToExtract) {
|
||||
if (objWithPropertyToExtract[key] === getClosureSafeProperty) {
|
||||
return key;
|
||||
}
|
||||
}
|
||||
throw Error(typeof ngDevMode === 'undefined' || ngDevMode ? 'Could not find renamed property on target object.' : '');
|
||||
}
|
||||
|
||||
export { NG_STATUS_CLASSES, SignalFormControl, compatForm };
|
||||
//# sourceMappingURL=signals-compat.mjs.map
|
||||
+1
File diff suppressed because one or more lines are too long
+1178
File diff suppressed because it is too large
Load Diff
+1
File diff suppressed because one or more lines are too long
+72
@@ -0,0 +1,72 @@
|
||||
{
|
||||
"name": "@angular/forms",
|
||||
"version": "21.2.1",
|
||||
"description": "Angular - directives and services for creating forms",
|
||||
"author": "angular",
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": "^20.19.0 || ^22.12.0 || >=24.0.0"
|
||||
},
|
||||
"dependencies": {
|
||||
"tslib": "^2.3.0",
|
||||
"@standard-schema/spec": "^1.0.0"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"@angular/core": "21.2.1",
|
||||
"@angular/common": "21.2.1",
|
||||
"@angular/platform-browser": "21.2.1",
|
||||
"rxjs": "^6.5.3 || ^7.4.0"
|
||||
},
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "https://github.com/angular/angular.git",
|
||||
"directory": "packages/forms"
|
||||
},
|
||||
"angular": {
|
||||
"examples": {
|
||||
"format": "sqlite",
|
||||
"path": "./resources/code-examples.db"
|
||||
}
|
||||
},
|
||||
"ng-update": {
|
||||
"packageGroup": [
|
||||
"@angular/core",
|
||||
"@angular/bazel",
|
||||
"@angular/common",
|
||||
"@angular/compiler",
|
||||
"@angular/compiler-cli",
|
||||
"@angular/animations",
|
||||
"@angular/elements",
|
||||
"@angular/platform-browser",
|
||||
"@angular/platform-browser-dynamic",
|
||||
"@angular/forms",
|
||||
"@angular/platform-server",
|
||||
"@angular/upgrade",
|
||||
"@angular/router",
|
||||
"@angular/language-service",
|
||||
"@angular/localize",
|
||||
"@angular/service-worker"
|
||||
]
|
||||
},
|
||||
"sideEffects": false,
|
||||
"module": "./fesm2022/forms.mjs",
|
||||
"typings": "./types/forms.d.ts",
|
||||
"type": "module",
|
||||
"exports": {
|
||||
"./package.json": {
|
||||
"default": "./package.json"
|
||||
},
|
||||
".": {
|
||||
"types": "./types/forms.d.ts",
|
||||
"default": "./fesm2022/forms.mjs"
|
||||
},
|
||||
"./signals": {
|
||||
"types": "./types/signals.d.ts",
|
||||
"default": "./fesm2022/signals.mjs"
|
||||
},
|
||||
"./signals/compat": {
|
||||
"types": "./types/signals-compat.d.ts",
|
||||
"default": "./fesm2022/signals-compat.mjs"
|
||||
}
|
||||
}
|
||||
}
|
||||
BIN
Binary file not shown.
+1670
File diff suppressed because it is too large
Load Diff
+5393
File diff suppressed because it is too large
Load Diff
+266
@@ -0,0 +1,266 @@
|
||||
/**
|
||||
* @license Angular v21.2.1
|
||||
* (c) 2010-2026 Google LLC. https://angular.dev/
|
||||
* License: MIT
|
||||
*/
|
||||
|
||||
import { WritableSignal, EventEmitter } from '@angular/core';
|
||||
import { FormOptions, FieldTree, SchemaOrSchemaFn, ValidationError, SignalFormsConfig, SchemaFn } from './_structure-chunk.js';
|
||||
import { AbstractControl, FormControlStatus, FormControlState } from '@angular/forms';
|
||||
import '@standard-schema/spec';
|
||||
|
||||
/**
|
||||
* Options that may be specified when creating a compat form.
|
||||
*
|
||||
* @category interop
|
||||
* @experimental 21.0.0
|
||||
*/
|
||||
type CompatFormOptions<TModel> = Omit<FormOptions<TModel>, 'adapter'>;
|
||||
/**
|
||||
* Creates a compatibility form wrapped around the given model data.
|
||||
*
|
||||
* `compatForm` is a version of the `form` function that is designed for backwards
|
||||
* compatibility with Reactive forms by accepting Reactive controls as a part of the data.
|
||||
*
|
||||
* @example
|
||||
* ```ts
|
||||
* const lastName = new FormControl('lastName');
|
||||
*
|
||||
* const nameModel = signal({
|
||||
* first: '',
|
||||
* last: lastName
|
||||
* });
|
||||
*
|
||||
* const nameForm = compatForm(nameModel, (name) => {
|
||||
* required(name.first);
|
||||
* });
|
||||
*
|
||||
* nameForm.last().value(); // lastName, not FormControl
|
||||
* ```
|
||||
*
|
||||
* @param model A writable signal that contains the model data for the form. The resulting field
|
||||
* structure will match the shape of the model and any changes to the form data will be written to
|
||||
* the model.
|
||||
*
|
||||
* @category interop
|
||||
* @experimental 21.0.0
|
||||
*/
|
||||
declare function compatForm<TModel>(model: WritableSignal<TModel>): FieldTree<TModel>;
|
||||
/**
|
||||
* Creates a compatibility form wrapped around the given model data.
|
||||
*
|
||||
* `compatForm` is a version of the `form` function that is designed for backwards
|
||||
* compatibility with Reactive forms by accepting Reactive controls as a part of the data.
|
||||
*
|
||||
* @example
|
||||
* ```ts
|
||||
* const lastName = new FormControl('lastName');
|
||||
*
|
||||
* const nameModel = signal({
|
||||
* first: '',
|
||||
* last: lastName
|
||||
* });
|
||||
*
|
||||
* const nameForm = compatForm(nameModel, (name) => {
|
||||
* required(name.first);
|
||||
* });
|
||||
*
|
||||
* nameForm.last().value(); // lastName, not FormControl
|
||||
*
|
||||
* @param model A writable signal that contains the model data for the form. The resulting field
|
||||
* structure will match the shape of the model and any changes to the form data will be written to
|
||||
* the model.
|
||||
* @param schemaOrOptions The second argument can be either
|
||||
* 1. A schema or a function used to specify logic for the form (e.g. validation, disabled fields, etc.).
|
||||
* When passing a schema, the form options can be passed as a third argument if needed.
|
||||
* 2. The form options (excluding adapter, since it's provided).
|
||||
*
|
||||
* @category interop
|
||||
* @experimental 21.0.0
|
||||
*/
|
||||
declare function compatForm<TModel>(model: WritableSignal<TModel>, schemaOrOptions: SchemaOrSchemaFn<TModel> | CompatFormOptions<TModel>): FieldTree<TModel>;
|
||||
/**
|
||||
* Creates a compatibility form wrapped around the given model data.
|
||||
*
|
||||
* `compatForm` is a version of the `form` function that is designed for backwards
|
||||
* compatibility with Reactive forms by accepting Reactive controls as a part of the data.
|
||||
*
|
||||
* @example
|
||||
* ```ts
|
||||
* const lastName = new FormControl('lastName');
|
||||
*
|
||||
* const nameModel = signal({
|
||||
* first: '',
|
||||
* last: lastName
|
||||
* });
|
||||
*
|
||||
* const nameForm = compatForm(nameModel, (name) => {
|
||||
* required(name.first);
|
||||
* });
|
||||
*
|
||||
* nameForm.last().value(); // lastName, not FormControl
|
||||
*
|
||||
* @param model A writable signal that contains the model data for the form. The resulting field
|
||||
* structure will match the shape of the model and any changes to the form data will be written to
|
||||
* the model.
|
||||
* @param schemaOrOptions A schema or a function used to specify logic for the form (e.g. validation, disabled fields, etc.).
|
||||
* When passing a schema, the form options can be passed as a third argument if needed.
|
||||
* @param options The form options (excluding adapter, since it's provided).
|
||||
*
|
||||
* @category interop
|
||||
* @experimental 21.0.0
|
||||
*/
|
||||
declare function compatForm<TModel>(model: WritableSignal<TModel>, schema: SchemaOrSchemaFn<TModel>, options: CompatFormOptions<TModel>): FieldTree<TModel>;
|
||||
|
||||
/**
|
||||
* An error used for compat errors.
|
||||
*
|
||||
* @experimental 21.0.0
|
||||
* @category interop
|
||||
*/
|
||||
declare class CompatValidationError<T = unknown> implements ValidationError {
|
||||
readonly kind: string;
|
||||
readonly control: AbstractControl;
|
||||
readonly fieldTree: FieldTree<unknown>;
|
||||
readonly context: T;
|
||||
readonly message?: string;
|
||||
constructor({ context, kind, control }: {
|
||||
context: T;
|
||||
kind: string;
|
||||
control: AbstractControl;
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* A value that can be used for `SignalFormsConfig.classes` to automatically add
|
||||
* the `ng-*` status classes from reactive forms.
|
||||
*
|
||||
* @experimental 21.0.1
|
||||
*/
|
||||
declare const NG_STATUS_CLASSES: SignalFormsConfig['classes'];
|
||||
|
||||
/** Options used to update the control value. */
|
||||
type ValueUpdateOptions = {
|
||||
onlySelf?: boolean;
|
||||
emitEvent?: boolean;
|
||||
emitModelToViewChange?: boolean;
|
||||
emitViewToModelChange?: boolean;
|
||||
};
|
||||
/**
|
||||
* A `FormControl` that is backed by signal forms rules.
|
||||
*
|
||||
* This class provides a bridge between Signal Forms and Reactive Forms, allowing
|
||||
* signal-based controls to be used within a standard `FormGroup` or `FormArray`.
|
||||
*
|
||||
* A control could be created using signal forms, and integrated with an existing FormGroup
|
||||
* propagating all the statuses and validity.
|
||||
*
|
||||
* @usageNotes
|
||||
*
|
||||
* ### Basic usage
|
||||
*
|
||||
* ```angular-ts
|
||||
* const form = new FormGroup({
|
||||
* // You can create SignalFormControl with signal form rules, and add it to a FormGroup.
|
||||
* name: new SignalFormControl('Alice', p => {
|
||||
* required(p);
|
||||
* }),
|
||||
* age: new FormControl(25),
|
||||
* });
|
||||
* ```
|
||||
* In the template you can get the underlying `fieldTree` and bind it:
|
||||
*
|
||||
* ```angular-html
|
||||
* <form [formGroup]="form">
|
||||
* <input [formField]="nameControl.fieldTree" />
|
||||
* <input formControlName="age" />
|
||||
* </form>
|
||||
* ```
|
||||
*
|
||||
* @experimental
|
||||
*/
|
||||
declare class SignalFormControl<T> extends AbstractControl {
|
||||
/** Source FieldTree. */
|
||||
readonly fieldTree: FieldTree<T>;
|
||||
/** The raw signal driving the control value. */
|
||||
readonly sourceValue: WritableSignal<T>;
|
||||
private readonly fieldState;
|
||||
private readonly initialValue;
|
||||
private pendingParentNotifications;
|
||||
private readonly onChangeCallbacks;
|
||||
private readonly onDisabledChangeCallbacks;
|
||||
readonly valueChanges: EventEmitter<T>;
|
||||
readonly statusChanges: EventEmitter<FormControlStatus>;
|
||||
constructor(value: T, schemaOrOptions?: SchemaFn<T> | FormOptions<T>, options?: FormOptions<T>);
|
||||
/**
|
||||
* Defines properties using closure-safe names to prevent issues with property renaming optimizations.
|
||||
*
|
||||
* AbstractControl have `value` and `errors` as readonly prop, which doesn't allow getters.
|
||||
**/
|
||||
private defineCompatProperties;
|
||||
private emitControlEvent;
|
||||
setValue(value: any, options?: ValueUpdateOptions): void;
|
||||
patchValue(value: any, options?: ValueUpdateOptions): void;
|
||||
private updateValue;
|
||||
registerOnChange(fn: (value?: any, emitModelEvent?: boolean) => void): void;
|
||||
registerOnDisabledChange(fn: (isDisabled: boolean) => void): void;
|
||||
getRawValue(): T;
|
||||
reset(value?: T | FormControlState<T>, options?: ValueUpdateOptions): void;
|
||||
private scheduleParentUpdate;
|
||||
private notifyParentUnlessPending;
|
||||
private updateParentValueAndValidity;
|
||||
private propagateToParent;
|
||||
get status(): FormControlStatus;
|
||||
get valid(): boolean;
|
||||
get invalid(): boolean;
|
||||
get pending(): boolean;
|
||||
get disabled(): boolean;
|
||||
get enabled(): boolean;
|
||||
get dirty(): boolean;
|
||||
set dirty(_: boolean);
|
||||
get pristine(): boolean;
|
||||
set pristine(_: boolean);
|
||||
get touched(): boolean;
|
||||
set touched(_: boolean);
|
||||
get untouched(): boolean;
|
||||
set untouched(_: boolean);
|
||||
markAsTouched(opts?: {
|
||||
onlySelf?: boolean;
|
||||
}): void;
|
||||
markAsDirty(opts?: {
|
||||
onlySelf?: boolean;
|
||||
}): void;
|
||||
markAsPristine(opts?: {
|
||||
onlySelf?: boolean;
|
||||
}): void;
|
||||
markAsUntouched(opts?: {
|
||||
onlySelf?: boolean;
|
||||
}): void;
|
||||
updateValueAndValidity(_opts?: Object): void;
|
||||
disable(_opts?: {
|
||||
onlySelf?: boolean;
|
||||
emitEvent?: boolean;
|
||||
}): void;
|
||||
enable(_opts?: {
|
||||
onlySelf?: boolean;
|
||||
emitEvent?: boolean;
|
||||
}): void;
|
||||
setValidators(_validators: any): void;
|
||||
setAsyncValidators(_validators: any): void;
|
||||
addValidators(_validators: any): void;
|
||||
addAsyncValidators(_validators: any): void;
|
||||
removeValidators(_validators: any): void;
|
||||
removeAsyncValidators(_validators: any): void;
|
||||
clearValidators(): void;
|
||||
clearAsyncValidators(): void;
|
||||
setErrors(_errors: any, _opts?: {
|
||||
emitEvent?: boolean;
|
||||
}): void;
|
||||
markAsPending(_opts?: {
|
||||
onlySelf?: boolean;
|
||||
emitEvent?: boolean;
|
||||
}): void;
|
||||
}
|
||||
|
||||
export { CompatValidationError, NG_STATUS_CLASSES, SignalFormControl, compatForm };
|
||||
export type { CompatFormOptions };
|
||||
+664
@@ -0,0 +1,664 @@
|
||||
/**
|
||||
* @license Angular v21.2.1
|
||||
* (c) 2010-2026 Google LLC. https://angular.dev/
|
||||
* License: MIT
|
||||
*/
|
||||
|
||||
import * as i0 from '@angular/core';
|
||||
import { Signal, ResourceRef, InputSignal, InputSignalWithTransform, ModelSignal, OutputRef, WritableSignal } from '@angular/core';
|
||||
import { PathKind, SchemaPath, SchemaPathRules, LogicFn, OneOrMany, ValidationError, FieldValidator, FieldContext, TreeValidationResult, TreeValidator, WithOptionalFieldTree, DisabledReason, Debouncer, FieldTree } from './_structure-chunk.js';
|
||||
export { AsyncValidationResult, BaseNgValidationError, ChildFieldContext, CompatFieldState, CompatSchemaPath, EmailValidationError, FORM_FIELD, Field, FieldState, FormField, FormFieldBindingOptions, FormOptions, FormSubmitOptions, IgnoreUnknownProperties, ItemFieldContext, ItemType, MAX, MAX_LENGTH, MIN, MIN_LENGTH, MaxLengthValidationError, MaxValidationError, MaybeFieldTree, MaybeSchemaPathTree, MetadataKey, MetadataReducer, MetadataSetterType, MinLengthValidationError, MinValidationError, NativeInputParseError, NgValidationError, PATTERN, PatternValidationError, REQUIRED, ReadonlyArrayLike, RemoveStringIndexUnknownKey, RequiredValidationError, RootFieldContext, Schema, SchemaFn, SchemaOrSchemaFn, SchemaPathTree, SignalFormsConfig, StandardSchemaValidationError, Subfields, ValidationErrorOptions, ValidationResult, ValidationSuccess, Validator, WithField, WithFieldTree, WithOptionalField, WithoutField, WithoutFieldTree, apply, applyEach, applyWhen, applyWhenValue, createManagedMetadataKey, createMetadataKey, emailError, form, maxError, maxLengthError, metadata, minError, minLengthError, patternError, provideSignalFormsConfig, requiredError, schema, standardSchemaError, submit, validateStandardSchema, ɵNgFieldDirective } from './_structure-chunk.js';
|
||||
import { HttpResourceRequest, HttpResourceOptions } from '@angular/common/http';
|
||||
import '@angular/forms';
|
||||
import '@standard-schema/spec';
|
||||
|
||||
/**
|
||||
* Adds logic to a field to conditionally disable it. A disabled field does not contribute to the
|
||||
* validation, touched/dirty, or other state of its parent field.
|
||||
*
|
||||
* @param path The target path to add the disabled logic to.
|
||||
* @param logic A reactive function that returns `true` (or a string reason) when the field is disabled,
|
||||
* and `false` when it is not disabled.
|
||||
* @template TValue The type of value stored in the field the logic is bound to.
|
||||
* @template TPathKind The kind of path the logic is bound to (a root path, child path, or item of an array)
|
||||
*
|
||||
* @category logic
|
||||
* @experimental 21.0.0
|
||||
*/
|
||||
declare function disabled<TValue, TPathKind extends PathKind = PathKind.Root>(path: SchemaPath<TValue, SchemaPathRules.Supported, TPathKind>, logic?: string | NoInfer<LogicFn<TValue, boolean | string, TPathKind>>): void;
|
||||
|
||||
/**
|
||||
* Adds logic to a field to conditionally hide it. A hidden field does not contribute to the
|
||||
* validation, touched/dirty, or other state of its parent field.
|
||||
*
|
||||
* If a field may be hidden it is recommended to guard it with an `@if` in the template:
|
||||
* ```
|
||||
* @if (!email().hidden()) {
|
||||
* <label for="email">Email</label>
|
||||
* <input id="email" type="email" [control]="email" />
|
||||
* }
|
||||
* ```
|
||||
*
|
||||
* @param path The target path to add the hidden logic to.
|
||||
* @param logic A reactive function that returns `true` when the field is hidden.
|
||||
* @template TValue The type of value stored in the field the logic is bound to.
|
||||
* @template TPathKind The kind of path the logic is bound to (a root path, child path, or item of an array)
|
||||
*
|
||||
* @category logic
|
||||
* @experimental 21.0.0
|
||||
*/
|
||||
declare function hidden<TValue, TPathKind extends PathKind = PathKind.Root>(path: SchemaPath<TValue, SchemaPathRules.Supported, TPathKind>, logic: NoInfer<LogicFn<TValue, boolean, TPathKind>>): void;
|
||||
|
||||
/**
|
||||
* Adds logic to a field to conditionally make it readonly. A readonly field does not contribute to
|
||||
* the validation, touched/dirty, or other state of its parent field.
|
||||
*
|
||||
* @param path The target path to make readonly.
|
||||
* @param logic A reactive function that returns `true` when the field is readonly.
|
||||
* @template TValue The type of value stored in the field the logic is bound to.
|
||||
* @template TPathKind The kind of path the logic is bound to (a root path, child path, or item of an array)
|
||||
*
|
||||
* @category logic
|
||||
* @experimental 21.0.0
|
||||
*/
|
||||
declare function readonly<TValue, TPathKind extends PathKind = PathKind.Root>(path: SchemaPath<TValue, SchemaPathRules.Supported, TPathKind>, logic?: NoInfer<LogicFn<TValue, boolean, TPathKind>>): void;
|
||||
|
||||
/** Represents a value that has a length or size, such as an array or string, or set. */
|
||||
type ValueWithLengthOrSize = {
|
||||
length: number;
|
||||
} | {
|
||||
size: number;
|
||||
};
|
||||
/** Common options available on the standard validators. */
|
||||
type BaseValidatorConfig<TValue, TPathKind extends PathKind = PathKind.Root> = {
|
||||
/** A user-facing error message to include with the error. */
|
||||
message?: string | LogicFn<TValue, string, TPathKind>;
|
||||
error?: never;
|
||||
} | {
|
||||
/**
|
||||
* Custom validation error(s) to report instead of the default,
|
||||
* or a function that receives the `FieldContext` and returns custom validation error(s).
|
||||
*/
|
||||
error?: OneOrMany<ValidationError> | LogicFn<TValue, OneOrMany<ValidationError>, TPathKind>;
|
||||
message?: never;
|
||||
};
|
||||
|
||||
/**
|
||||
* Binds a validator to the given path that requires the value to match the standard email format.
|
||||
* This function can only be called on string paths.
|
||||
*
|
||||
* @param path Path of the field to validate
|
||||
* @param config Optional, allows providing any of the following options:
|
||||
* - `error`: Custom validation error(s) to be used instead of the default `ValidationError.email()`
|
||||
* or a function that receives the `FieldContext` and returns custom validation error(s).
|
||||
* @template TPathKind The kind of path the logic is bound to (a root path, child path, or item of an array)
|
||||
*
|
||||
* @see [Signal Form Email Validation](guide/forms/signals/validation#email)
|
||||
* @category validation
|
||||
* @experimental 21.0.0
|
||||
*/
|
||||
declare function email<TPathKind extends PathKind = PathKind.Root>(path: SchemaPath<string, SchemaPathRules.Supported, TPathKind>, config?: BaseValidatorConfig<string, TPathKind>): void;
|
||||
|
||||
/**
|
||||
* Binds a validator to the given path that requires the value to be less than or equal to the
|
||||
* given `maxValue`.
|
||||
* This function can only be called on number paths.
|
||||
* In addition to binding a validator, this function adds `MAX` property to the field.
|
||||
*
|
||||
* @param path Path of the field to validate
|
||||
* @param maxValue The maximum value, or a LogicFn that returns the maximum value.
|
||||
* @param config Optional, allows providing any of the following options:
|
||||
* - `error`: Custom validation error(s) to be used instead of the default `ValidationError.max(maxValue)`
|
||||
* or a function that receives the `FieldContext` and returns custom validation error(s).
|
||||
* @template TPathKind The kind of path the logic is bound to (a root path, child path, or item of an array)
|
||||
*
|
||||
* @see [Signal Form Max Validation](guide/forms/signals/validation#min-and-max)
|
||||
* @category validation
|
||||
* @experimental 21.0.0
|
||||
*/
|
||||
declare function max<TPathKind extends PathKind = PathKind.Root>(path: SchemaPath<number | string | null, SchemaPathRules.Supported, TPathKind>, maxValue: number | LogicFn<number | string | null, number | undefined, TPathKind>, config?: BaseValidatorConfig<number | string | null, TPathKind>): void;
|
||||
|
||||
/**
|
||||
* Binds a validator to the given path that requires the length of the value to be less than or
|
||||
* equal to the given `maxLength`.
|
||||
* This function can only be called on string or array paths.
|
||||
* In addition to binding a validator, this function adds `MAX_LENGTH` property to the field.
|
||||
*
|
||||
* @param path Path of the field to validate
|
||||
* @param maxLength The maximum length, or a LogicFn that returns the maximum length.
|
||||
* @param config Optional, allows providing any of the following options:
|
||||
* - `error`: Custom validation error(s) to be used instead of the default `ValidationError.maxLength(maxLength)`
|
||||
* or a function that receives the `FieldContext` and returns custom validation error(s).
|
||||
* @template TValue The type of value stored in the field the logic is bound to.
|
||||
* @template TPathKind The kind of path the logic is bound to (a root path, child path, or item of an array)
|
||||
*
|
||||
* @see [Signal Form Max Length Validation](guide/forms/signals/validation#minlength-and-maxlength)
|
||||
* @category validation
|
||||
* @experimental 21.0.0
|
||||
*/
|
||||
declare function maxLength<TValue extends ValueWithLengthOrSize, TPathKind extends PathKind = PathKind.Root>(path: SchemaPath<TValue, SchemaPathRules.Supported, TPathKind>, maxLength: number | LogicFn<TValue, number | undefined, TPathKind>, config?: BaseValidatorConfig<TValue, TPathKind>): void;
|
||||
|
||||
/**
|
||||
* Binds a validator to the given path that requires the value to be greater than or equal to
|
||||
* the given `minValue`.
|
||||
* This function can only be called on number paths.
|
||||
* In addition to binding a validator, this function adds `MIN` property to the field.
|
||||
*
|
||||
* @param path Path of the field to validate
|
||||
* @param minValue The minimum value, or a LogicFn that returns the minimum value.
|
||||
* @param config Optional, allows providing any of the following options:
|
||||
* - `error`: Custom validation error(s) to be used instead of the default `ValidationError.min(minValue)`
|
||||
* or a function that receives the `FieldContext` and returns custom validation error(s).
|
||||
* @template TPathKind The kind of path the logic is bound to (a root path, child path, or item of an array)
|
||||
*
|
||||
* @see [Signal Form Min Validation](guide/forms/signals/validation#min-and-max)
|
||||
* @category validation
|
||||
* @experimental 21.0.0
|
||||
*/
|
||||
declare function min<TValue extends number | string | null, TPathKind extends PathKind = PathKind.Root>(path: SchemaPath<TValue, SchemaPathRules.Supported, TPathKind>, minValue: number | LogicFn<TValue, number | undefined, TPathKind>, config?: BaseValidatorConfig<TValue, TPathKind>): void;
|
||||
|
||||
/**
|
||||
* Binds a validator to the given path that requires the length of the value to be greater than or
|
||||
* equal to the given `minLength`.
|
||||
* This function can only be called on string or array paths.
|
||||
* In addition to binding a validator, this function adds `MIN_LENGTH` property to the field.
|
||||
*
|
||||
* @param path Path of the field to validate
|
||||
* @param minLength The minimum length, or a LogicFn that returns the minimum length.
|
||||
* @param config Optional, allows providing any of the following options:
|
||||
* - `error`: Custom validation error(s) to be used instead of the default `ValidationError.minLength(minLength)`
|
||||
* or a function that receives the `FieldContext` and returns custom validation error(s).
|
||||
* @template TValue The type of value stored in the field the logic is bound to.
|
||||
* @template TPathKind The kind of path the logic is bound to (a root path, child path, or item of an array)
|
||||
*
|
||||
* @see [Signal Form Min Length Validation](guide/forms/signals/validation#minlength-and-maxlength)
|
||||
* @category validation
|
||||
* @experimental 21.0.0
|
||||
*/
|
||||
declare function minLength<TValue extends ValueWithLengthOrSize, TPathKind extends PathKind = PathKind.Root>(path: SchemaPath<TValue, SchemaPathRules.Supported, TPathKind>, minLength: number | LogicFn<TValue, number | undefined, TPathKind>, config?: BaseValidatorConfig<TValue, TPathKind>): void;
|
||||
|
||||
/**
|
||||
* Binds a validator to the given path that requires the value to match a specific regex pattern.
|
||||
* This function can only be called on string paths.
|
||||
* In addition to binding a validator, this function adds `PATTERN` property to the field.
|
||||
*
|
||||
* @param path Path of the field to validate
|
||||
* @param pattern The RegExp pattern to match, or a LogicFn that returns the RegExp pattern.
|
||||
* @param config Optional, allows providing any of the following options:
|
||||
* - `error`: Custom validation error(s) to be used instead of the default `ValidationError.pattern(pattern)`
|
||||
* or a function that receives the `FieldContext` and returns custom validation error(s).
|
||||
* @template TPathKind The kind of path the logic is bound to (a root path, child path, or item of an array)
|
||||
*
|
||||
* @see [Signal Form Pattern Validation](guide/forms/signals/validation#pattern)
|
||||
* @category validation
|
||||
* @experimental 21.0.0
|
||||
*/
|
||||
declare function pattern<TPathKind extends PathKind = PathKind.Root>(path: SchemaPath<string, SchemaPathRules.Supported, TPathKind>, pattern: RegExp | LogicFn<string | undefined, RegExp | undefined, TPathKind>, config?: BaseValidatorConfig<string, TPathKind>): void;
|
||||
|
||||
/**
|
||||
* Binds a validator to the given path that requires the value to be non-empty.
|
||||
* This function can only be called on any type of path.
|
||||
* In addition to binding a validator, this function adds `REQUIRED` property to the field.
|
||||
*
|
||||
* @param path Path of the field to validate
|
||||
* @param config Optional, allows providing any of the following options:
|
||||
* - `message`: A user-facing message for the error.
|
||||
* - `error`: Custom validation error(s) to be used instead of the default `ValidationError.required()`
|
||||
* or a function that receives the `FieldContext` and returns custom validation error(s).
|
||||
* - `when`: A function that receives the `FieldContext` and returns true if the field is required
|
||||
* @template TValue The type of value stored in the field the logic is bound to.
|
||||
* @template TPathKind The kind of path the logic is bound to (a root path, child path, or item of an array)
|
||||
*
|
||||
* @see [Signal Form Required Validation](guide/forms/signals/validation#required)
|
||||
* @category validation
|
||||
* @experimental 21.0.0
|
||||
*/
|
||||
declare function required<TValue, TPathKind extends PathKind = PathKind.Root>(path: SchemaPath<TValue, SchemaPathRules.Supported, TPathKind>, config?: BaseValidatorConfig<TValue, TPathKind> & {
|
||||
when?: NoInfer<LogicFn<TValue, boolean, TPathKind>>;
|
||||
}): void;
|
||||
|
||||
/**
|
||||
* Adds logic to a field to determine if the field has validation errors.
|
||||
*
|
||||
* @param path The target path to add the validation logic to.
|
||||
* @param logic A `Validator` that returns the current validation errors.
|
||||
* @template TValue The type of value stored in the field the logic is bound to.
|
||||
* @template TPathKind The kind of path the logic is bound to (a root path, child path, or item of an array)
|
||||
*
|
||||
* @category logic
|
||||
* @experimental 21.0.0
|
||||
*/
|
||||
declare function validate<TValue, TPathKind extends PathKind = PathKind.Root>(path: SchemaPath<TValue, SchemaPathRules.Supported, TPathKind>, logic: NoInfer<FieldValidator<TValue, TPathKind>>): void;
|
||||
|
||||
/**
|
||||
* A function that takes the result of an async operation and the current field context, and maps it
|
||||
* to a list of validation errors.
|
||||
*
|
||||
* @param result The result of the async operation.
|
||||
* @param ctx The context for the field the validator is attached to.
|
||||
* @return A validation error, or list of validation errors to report based on the result of the async operation.
|
||||
* The returned errors can optionally specify a field that the error should be targeted to.
|
||||
* A targeted error will show up as an error on its target field rather than the field being validated.
|
||||
* If a field is not given, the error is assumed to apply to the field being validated.
|
||||
* @template TValue The type of value stored in the field being validated.
|
||||
* @template TResult The type of result returned by the async operation
|
||||
* @template TPathKind The kind of path being validated (a root path, child path, or item of an array)
|
||||
*
|
||||
* @experimental 21.0.0
|
||||
*/
|
||||
type MapToErrorsFn<TValue, TResult, TPathKind extends PathKind = PathKind.Root> = (result: TResult, ctx: FieldContext<TValue, TPathKind>) => TreeValidationResult;
|
||||
/**
|
||||
* Options that indicate how to create a resource for async validation for a field,
|
||||
* and map its result to validation errors.
|
||||
*
|
||||
* @template TValue The type of value stored in the field being validated.
|
||||
* @template TParams The type of parameters to the resource.
|
||||
* @template TResult The type of result returned by the resource
|
||||
* @template TPathKind The kind of path being validated (a root path, child path, or item of an array)
|
||||
* @see [Signal Form Async Validation](guide/forms/signals/validation#async-validation)
|
||||
* @category validation
|
||||
* @experimental 21.0.0
|
||||
*/
|
||||
interface AsyncValidatorOptions<TValue, TParams, TResult, TPathKind extends PathKind = PathKind.Root> {
|
||||
/**
|
||||
* A function that receives the field context and returns the params for the resource.
|
||||
*
|
||||
* @param ctx The field context for the field being validated.
|
||||
* @returns The params for the resource.
|
||||
*/
|
||||
readonly params: (ctx: FieldContext<TValue, TPathKind>) => TParams;
|
||||
/**
|
||||
* A function that receives the resource params and returns a resource of the given params.
|
||||
* The given params should be used as is to create the resource.
|
||||
* The forms system will report the params as `undefined` when this validation doesn't need to be run.
|
||||
*
|
||||
* @param params The params to use for constructing the resource
|
||||
* @returns A reference to the constructed resource.
|
||||
*/
|
||||
readonly factory: (params: Signal<TParams | undefined>) => ResourceRef<TResult | undefined>;
|
||||
/**
|
||||
* A function to handle errors thrown by httpResource (HTTP errors, network errors, etc.).
|
||||
* Receives the error and the field context, returns a list of validation errors.
|
||||
*/
|
||||
readonly onError: (error: unknown, ctx: FieldContext<TValue, TPathKind>) => TreeValidationResult;
|
||||
/**
|
||||
* A function that takes the resource result, and the current field context and maps it to a list
|
||||
* of validation errors.
|
||||
*
|
||||
* @param result The resource result.
|
||||
* @param ctx The context for the field the validator is attached to.
|
||||
* @return A validation error, or list of validation errors to report based on the resource result.
|
||||
* The returned errors can optionally specify a field that the error should be targeted to.
|
||||
* A targeted error will show up as an error on its target field rather than the field being validated.
|
||||
* If a field is not given, the error is assumed to apply to the field being validated.
|
||||
*/
|
||||
readonly onSuccess: MapToErrorsFn<TValue, TResult, TPathKind>;
|
||||
}
|
||||
/**
|
||||
* Adds async validation to the field corresponding to the given path based on a resource.
|
||||
* Async validation for a field only runs once all synchronous validation is passing.
|
||||
*
|
||||
* @param path A path indicating the field to bind the async validation logic to.
|
||||
* @param opts The async validation options.
|
||||
* @template TValue The type of value stored in the field being validated.
|
||||
* @template TParams The type of parameters to the resource.
|
||||
* @template TResult The type of result returned by the resource
|
||||
* @template TPathKind The kind of path being validated (a root path, child path, or item of an array)
|
||||
*
|
||||
* @see [Signal Form Async Validation](guide/forms/signals/validation#async-validation)
|
||||
* @category validation
|
||||
* @experimental 21.0.0
|
||||
*/
|
||||
declare function validateAsync<TValue, TParams, TResult, TPathKind extends PathKind = PathKind.Root>(path: SchemaPath<TValue, SchemaPathRules.Supported, TPathKind>, opts: AsyncValidatorOptions<TValue, TParams, TResult, TPathKind>): void;
|
||||
|
||||
/**
|
||||
* Options that indicate how to create an httpResource for async validation for a field,
|
||||
* and map its result to validation errors.
|
||||
*
|
||||
* @template TValue The type of value stored in the field being validated.
|
||||
* @template TResult The type of result returned by the httpResource
|
||||
* @template TPathKind The kind of path being validated (a root path, child path, or item of an array)
|
||||
*
|
||||
* @category validation
|
||||
* @experimental 21.0.0
|
||||
*/
|
||||
interface HttpValidatorOptions<TValue, TResult, TPathKind extends PathKind = PathKind.Root> {
|
||||
/**
|
||||
* A function that receives the field context and returns the url or request for the httpResource.
|
||||
* If given a URL, the underlying httpResource will perform an HTTP GET on it.
|
||||
*
|
||||
* @param ctx The field context for the field being validated.
|
||||
* @returns The URL or request for creating the httpResource.
|
||||
*/
|
||||
readonly request: ((ctx: FieldContext<TValue, TPathKind>) => string | undefined) | ((ctx: FieldContext<TValue, TPathKind>) => HttpResourceRequest | undefined);
|
||||
/**
|
||||
* A function that takes the httpResource result, and the current field context and maps it to a
|
||||
* list of validation errors.
|
||||
*
|
||||
* @param result The httpResource result.
|
||||
* @param ctx The context for the field the validator is attached to.
|
||||
* @return A validation error, or list of validation errors to report based on the httpResource result.
|
||||
* The returned errors can optionally specify a field that the error should be targeted to.
|
||||
* A targeted error will show up as an error on its target field rather than the field being validated.
|
||||
* If a field is not given, the error is assumed to apply to the field being validated.
|
||||
*/
|
||||
readonly onSuccess: MapToErrorsFn<TValue, TResult, TPathKind>;
|
||||
/**
|
||||
* A function to handle errors thrown by httpResource (HTTP errors, network errors, etc.).
|
||||
* Receives the error and the field context, returns a list of validation errors.
|
||||
*/
|
||||
readonly onError: (error: unknown, ctx: FieldContext<TValue, TPathKind>) => TreeValidationResult;
|
||||
/**
|
||||
* The options to use when creating the httpResource.
|
||||
*/
|
||||
readonly options?: HttpResourceOptions<TResult, unknown>;
|
||||
}
|
||||
/**
|
||||
* Adds async validation to the field corresponding to the given path based on an httpResource.
|
||||
* Async validation for a field only runs once all synchronous validation is passing.
|
||||
*
|
||||
* @param path A path indicating the field to bind the async validation logic to.
|
||||
* @param opts The http validation options.
|
||||
* @template TValue The type of value stored in the field being validated.
|
||||
* @template TResult The type of result returned by the httpResource
|
||||
* @template TPathKind The kind of path being validated (a root path, child path, or item of an array)
|
||||
*
|
||||
* @see [Signal Form Async Validation](guide/forms/signals/validation#async-validation)
|
||||
* @category validation
|
||||
* @experimental 21.0.0
|
||||
*/
|
||||
declare function validateHttp<TValue, TResult = unknown, TPathKind extends PathKind = PathKind.Root>(path: SchemaPath<TValue, SchemaPathRules.Supported, TPathKind>, opts: HttpValidatorOptions<TValue, TResult, TPathKind>): void;
|
||||
|
||||
/**
|
||||
* Adds logic to a field to determine if the field or any of its child fields has validation errors.
|
||||
*
|
||||
* @param path The target path to add the validation logic to.
|
||||
* @param logic A `TreeValidator` that returns the current validation errors.
|
||||
* Errors returned by the validator may specify a target field to indicate an error on a child field.
|
||||
* @template TValue The type of value stored in the field the logic is bound to.
|
||||
* @template TPathKind The kind of path the logic is bound to (a root path, child path, or item of an array)
|
||||
*
|
||||
* @category logic
|
||||
* @experimental 21.0.0
|
||||
*/
|
||||
declare function validateTree<TValue, TPathKind extends PathKind = PathKind.Root>(path: SchemaPath<TValue, SchemaPathRules.Supported, TPathKind>, logic: NoInfer<TreeValidator<TValue, TPathKind>>): void;
|
||||
|
||||
/**
|
||||
* The base set of properties shared by all form control contracts.
|
||||
*
|
||||
* @category control
|
||||
* @experimental 21.0.0
|
||||
*/
|
||||
interface FormUiControl {
|
||||
/**
|
||||
* An input to receive the errors for the field. If implemented, the `Field` directive will
|
||||
* automatically bind errors from the bound field to this input.
|
||||
*/
|
||||
readonly errors?: InputSignal<readonly ValidationError.WithOptionalFieldTree[]> | InputSignalWithTransform<readonly ValidationError.WithOptionalFieldTree[], unknown>;
|
||||
/**
|
||||
* An input to receive the disabled status for the field. If implemented, the `Field` directive
|
||||
* will automatically bind the disabled status from the bound field to this input.
|
||||
*/
|
||||
readonly disabled?: InputSignal<boolean> | InputSignalWithTransform<boolean, unknown>;
|
||||
/**
|
||||
* An input to receive the reasons for the disablement of the field. If implemented, the `Field`
|
||||
* directive will automatically bind the disabled reason from the bound field to this input.
|
||||
*/
|
||||
readonly disabledReasons?: InputSignal<readonly WithOptionalFieldTree<DisabledReason>[]> | InputSignalWithTransform<readonly WithOptionalFieldTree<DisabledReason>[], unknown>;
|
||||
/**
|
||||
* An input to receive the readonly status for the field. If implemented, the `Field` directive
|
||||
* will automatically bind the readonly status from the bound field to this input.
|
||||
*/
|
||||
readonly readonly?: InputSignal<boolean> | InputSignalWithTransform<boolean, unknown>;
|
||||
/**
|
||||
* An input to receive the hidden status for the field. If implemented, the `Field` directive
|
||||
* will automatically bind the hidden status from the bound field to this input.
|
||||
*/
|
||||
readonly hidden?: InputSignal<boolean> | InputSignalWithTransform<boolean, unknown>;
|
||||
/**
|
||||
* An input to receive the invalid status for the field. If implemented, the `Field` directive
|
||||
* will automatically bind the invalid status from the bound field to this input.
|
||||
*/
|
||||
readonly invalid?: InputSignal<boolean> | InputSignalWithTransform<boolean, unknown>;
|
||||
/**
|
||||
* An input to receive the pending status for the field. If implemented, the `Field` directive
|
||||
* will automatically bind the pending status from the bound field to this input.
|
||||
*/
|
||||
readonly pending?: InputSignal<boolean> | InputSignalWithTransform<boolean, unknown>;
|
||||
/**
|
||||
* An input to receive the touched status for the field. If implemented, the `Field` directive
|
||||
* will automatically bind the touched status from the bound field to this input.
|
||||
*/
|
||||
readonly touched?: ModelSignal<boolean> | InputSignal<boolean> | InputSignalWithTransform<boolean, unknown> | OutputRef<boolean>;
|
||||
/**
|
||||
* An input to receive the dirty status for the field. If implemented, the `Field` directive
|
||||
* will automatically bind the dirty status from the bound field to this input.
|
||||
*/
|
||||
readonly dirty?: InputSignal<boolean> | InputSignalWithTransform<boolean, unknown>;
|
||||
/**
|
||||
* An input to receive the name for the field. If implemented, the `Field` directive will
|
||||
* automatically bind the name from the bound field to this input.
|
||||
*/
|
||||
readonly name?: InputSignal<string> | InputSignalWithTransform<string, unknown>;
|
||||
/**
|
||||
* An input to receive the required status for the field. If implemented, the `Field` directive
|
||||
* will automatically bind the required status from the bound field to this input.
|
||||
*/
|
||||
readonly required?: InputSignal<boolean> | InputSignalWithTransform<boolean, unknown>;
|
||||
/**
|
||||
* An input to receive the min value for the field. If implemented, the `Field` directive will
|
||||
* automatically bind the min value from the bound field to this input.
|
||||
*/
|
||||
readonly min?: InputSignal<number | undefined> | InputSignalWithTransform<number | undefined, unknown>;
|
||||
/**
|
||||
* An input to receive the min length for the field. If implemented, the `Field` directive will
|
||||
* automatically bind the min length from the bound field to this input.
|
||||
*/
|
||||
readonly minLength?: InputSignal<number | undefined> | InputSignalWithTransform<number | undefined, unknown>;
|
||||
/**
|
||||
* An input to receive the max value for the field. If implemented, the `Field` directive will
|
||||
* automatically bind the max value from the bound field to this input.
|
||||
*/
|
||||
readonly max?: InputSignal<number | undefined> | InputSignalWithTransform<number | undefined, unknown>;
|
||||
/**
|
||||
* An input to receive the max length for the field. If implemented, the `Field` directive will
|
||||
* automatically bind the max length from the bound field to this input.
|
||||
*/
|
||||
readonly maxLength?: InputSignal<number | undefined> | InputSignalWithTransform<number | undefined, unknown>;
|
||||
/**
|
||||
* An input to receive the value patterns for the field. If implemented, the `Field` directive
|
||||
* will automatically bind the value patterns from the bound field to this input.
|
||||
*/
|
||||
readonly pattern?: InputSignal<readonly RegExp[]> | InputSignalWithTransform<readonly RegExp[], unknown>;
|
||||
/**
|
||||
* Focuses the UI control.
|
||||
*
|
||||
* If the focus method is not implemented, Signal Forms will attempt to focus the host element
|
||||
* when asked to focus this control.
|
||||
*/
|
||||
focus?(options?: FocusOptions): void;
|
||||
}
|
||||
/**
|
||||
* A contract for a form control that edits a `FieldTree` of type `TValue`. Any component that
|
||||
* implements this contract can be used with the `Field` directive.
|
||||
*
|
||||
* Many of the properties declared on this contract are optional. They do not need to be
|
||||
* implemented, but if they are will be kept in sync with the field state of the field bound to the
|
||||
* `Field` directive.
|
||||
*
|
||||
* @template TValue The type of `FieldTree` that the implementing component can edit.
|
||||
*
|
||||
* @category control
|
||||
* @experimental 21.0.0
|
||||
*/
|
||||
interface FormValueControl<TValue> extends FormUiControl {
|
||||
/**
|
||||
* The value is the only required property in this contract. A component that wants to integrate
|
||||
* with the `Field` directive via this contract, *must* provide a `model()` that will be kept in
|
||||
* sync with the value of the bound `FieldTree`.
|
||||
*/
|
||||
readonly value: ModelSignal<TValue>;
|
||||
/**
|
||||
* The implementing component *must not* define a `checked` property. This is reserved for
|
||||
* components that want to integrate with the `Field` directive as a checkbox.
|
||||
*/
|
||||
readonly checked?: undefined;
|
||||
}
|
||||
/**
|
||||
* A contract for a form control that edits a boolean checkbox `FieldTree`. Any component that
|
||||
* implements this contract can be used with the `Field` directive.
|
||||
*
|
||||
* Many of the properties declared on this contract are optional. They do not need to be
|
||||
* implemented, but if they are will be kept in sync with the field state of the field bound to the
|
||||
* `Field` directive.
|
||||
*
|
||||
* @category control
|
||||
* @experimental 21.0.0
|
||||
*/
|
||||
interface FormCheckboxControl extends FormUiControl {
|
||||
/**
|
||||
* The checked is the only required property in this contract. A component that wants to integrate
|
||||
* with the `Field` directive, *must* provide a `model()` that will be kept in sync with the
|
||||
* value of the bound `FieldTree`.
|
||||
*/
|
||||
readonly checked: ModelSignal<boolean>;
|
||||
/**
|
||||
* The implementing component *must not* define a `value` property. This is reserved for
|
||||
* components that want to integrate with the `Field` directive as a standard input.
|
||||
*/
|
||||
readonly value?: undefined;
|
||||
}
|
||||
|
||||
/**
|
||||
* Configures the frequency at which a form field is updated by UI events.
|
||||
*
|
||||
* When this rule is applied, updates from the UI to the form model will be delayed until either
|
||||
* the field is touched, or the most recently debounced update resolves.
|
||||
*
|
||||
* @param path The target path to debounce.
|
||||
* @param durationOrDebouncer Either a debounce duration in milliseconds, or a custom
|
||||
* {@link Debouncer} function.
|
||||
*
|
||||
* @experimental 21.0.0
|
||||
*/
|
||||
declare function debounce<TValue, TPathKind extends PathKind = PathKind.Root>(path: SchemaPath<TValue, SchemaPathRules.Supported, TPathKind>, durationOrDebouncer: number | Debouncer<TValue, TPathKind>): void;
|
||||
|
||||
/**
|
||||
* Result of parsing a raw value into a model value.
|
||||
*/
|
||||
interface ParseResult<TValue> {
|
||||
/**
|
||||
* The parsed value. If omitted, the model is not updated.
|
||||
*/
|
||||
readonly value?: TValue;
|
||||
/**
|
||||
* Errors encountered during parsing, if any.
|
||||
*/
|
||||
readonly error?: OneOrMany<ValidationError.WithoutFieldTree>;
|
||||
}
|
||||
/**
|
||||
* Options for `transformedValue`.
|
||||
*
|
||||
* @experimental 21.2.0
|
||||
*/
|
||||
interface TransformedValueOptions<TValue, TRaw> {
|
||||
/**
|
||||
* Parse the raw value into the model value.
|
||||
*
|
||||
* Should return an object containing the parsed result, which may contain:
|
||||
* - `value`: The parsed model value. If `undefined`, the model will not be updated.
|
||||
* - `error`: Any parse errors encountered. If `undefined`, no errors are reported.
|
||||
*/
|
||||
parse: (rawValue: TRaw) => ParseResult<TValue>;
|
||||
/**
|
||||
* Format the model value into the raw value.
|
||||
*/
|
||||
format: (value: TValue) => TRaw;
|
||||
}
|
||||
/**
|
||||
* A writable signal representing a "raw" UI value that is synchronized with a model signal
|
||||
* via parse/format transformations.
|
||||
*
|
||||
* @category control
|
||||
* @experimental 21.2.0
|
||||
*/
|
||||
interface TransformedValueSignal<TRaw> extends WritableSignal<TRaw> {
|
||||
/**
|
||||
* The current parse errors resulting from the last transformation.
|
||||
*/
|
||||
readonly parseErrors: Signal<readonly ValidationError.WithoutFieldTree[]>;
|
||||
}
|
||||
/**
|
||||
* Creates a writable signal representing a "raw" UI value that is transformed to/from a model
|
||||
* value via `parse` and `format` functions.
|
||||
*
|
||||
* This utility simplifies the creation of custom form controls that parse a user-facing value
|
||||
* representation into an underlying model value. For example, a numeric input that displays and
|
||||
* accepts string values but stores a number.
|
||||
*
|
||||
* Parse errors are exposed via the returned signal’s `parseErrors()` property.
|
||||
* When `transformedValue` is used within a Signal Forms field context, parse errors are also
|
||||
* reported to the nearest field automatically. When no field context is present, no automatic
|
||||
* reporting occurs and `parseErrors` can be consumed directly.
|
||||
*
|
||||
* Note: `parse` may return both a `value` and an `error`. Returning `value` updates the model;
|
||||
* omitting it leaves the model unchanged.
|
||||
*
|
||||
* @param value The model signal to synchronize with.
|
||||
* @param options Configuration including `parse` and `format` functions.
|
||||
* @returns A `TransformedValueSignal` representing the raw value with parse error tracking.
|
||||
* @experimental 21.2.0
|
||||
*
|
||||
* @example
|
||||
* ```ts
|
||||
* @Component({
|
||||
* selector: 'number-input',
|
||||
* template: `<input [value]="rawValue()" (input)="rawValue.set($event.target.value)" />`,
|
||||
* })
|
||||
* export class NumberInput implements FormValueControl<number | null> {
|
||||
* readonly value = model.required<number | null>();
|
||||
*
|
||||
* protected readonly rawValue = transformedValue(this.value, {
|
||||
* parse: (val) => {
|
||||
* if (val === '') return {value: null};
|
||||
* const num = Number(val);
|
||||
* if (Number.isNaN(num)) {
|
||||
* return {error: {kind: 'parse', message: `${val} is not numeric`}};
|
||||
* }
|
||||
* return {value: num};
|
||||
* },
|
||||
* format: (val) => val?.toString() ?? '',
|
||||
* });
|
||||
* }
|
||||
* ```
|
||||
*/
|
||||
declare function transformedValue<TValue, TRaw>(value: ModelSignal<TValue>, options: TransformedValueOptions<TValue, TRaw>): TransformedValueSignal<TRaw>;
|
||||
|
||||
/**
|
||||
* A directive that binds a `FieldTree` to a `<form>` element.
|
||||
*
|
||||
* It automatically:
|
||||
* 1. Sets `novalidate` on the form element to disable browser validation.
|
||||
* 2. Listens for the `submit` event, prevents the default behavior, and calls `submit()` on the
|
||||
* `FieldTree`.
|
||||
*
|
||||
* @usageNotes
|
||||
*
|
||||
* ```html
|
||||
* <form [formRoot]="myFieldTree">
|
||||
* ...
|
||||
* </form>
|
||||
* ```
|
||||
*
|
||||
* @publicApi
|
||||
* @experimental 21.0.0
|
||||
*/
|
||||
declare class FormRoot<T> {
|
||||
readonly fieldTree: i0.InputSignal<FieldTree<T>>;
|
||||
protected onSubmit(event: Event): void;
|
||||
static ɵfac: i0.ɵɵFactoryDeclaration<FormRoot<any>, never>;
|
||||
static ɵdir: i0.ɵɵDirectiveDeclaration<FormRoot<any>, "form[formRoot]", never, { "fieldTree": { "alias": "formRoot"; "required": true; "isSignal": true; }; }, {}, never, never, true, never>;
|
||||
}
|
||||
|
||||
export { Debouncer, DisabledReason, FieldContext, FieldTree, FieldValidator, FormRoot, LogicFn, OneOrMany, PathKind, SchemaPath, SchemaPathRules, TreeValidationResult, TreeValidator, ValidationError, WithOptionalFieldTree, debounce, disabled, email, hidden, max, maxLength, min, minLength, pattern, readonly, required, transformedValue, validate, validateAsync, validateHttp, validateTree };
|
||||
export type { AsyncValidatorOptions, FormCheckboxControl, FormUiControl, FormValueControl, HttpValidatorOptions, MapToErrorsFn, ParseResult, TransformedValueOptions, TransformedValueSignal };
|
||||
Reference in New Issue
Block a user