|
| 1 | +/** |
| 2 | + * @license |
| 3 | + * Copyright Google LLC All Rights Reserved. |
| 4 | + * |
| 5 | + * Use of this source code is governed by an MIT-style license that can be |
| 6 | + * found in the LICENSE file at https://angular.dev/license |
| 7 | + */ |
| 8 | + |
| 9 | +import {FieldPathNode} from '../../schema/path_node'; |
| 10 | +import {assertPathIsCurrent} from '../../schema/schema'; |
| 11 | +import type {FieldContext, SchemaPath, LogicFn, PathKind, SchemaPathRules} from '../types'; |
| 12 | + |
| 13 | +/** |
| 14 | + * Adds logic to a field to conditionally disable it. A disabled field does not contribute to the |
| 15 | + * validation, touched/dirty, or other state of its parent field. |
| 16 | + * |
| 17 | + * @param path The target path to add the disabled logic to. |
| 18 | + * @param logic A reactive function that returns `true` (or a string reason) when the field is disabled, |
| 19 | + * and `false` when it is not disabled. |
| 20 | + * @template TValue The type of value stored in the field the logic is bound to. |
| 21 | + * @template TPathKind The kind of path the logic is bound to (a root path, child path, or item of an array) |
| 22 | + * |
| 23 | + * @category logic |
| 24 | + * @experimental 21.0.0 |
| 25 | + */ |
| 26 | +export function disabled<TValue, TPathKind extends PathKind = PathKind.Root>( |
| 27 | + path: SchemaPath<TValue, SchemaPathRules.Supported, TPathKind>, |
| 28 | + logic?: string | NoInfer<LogicFn<TValue, boolean | string, TPathKind>>, |
| 29 | +): void { |
| 30 | + assertPathIsCurrent(path); |
| 31 | + |
| 32 | + const pathNode = FieldPathNode.unwrapFieldPath(path); |
| 33 | + pathNode.builder.addDisabledReasonRule((ctx) => { |
| 34 | + let result: boolean | string = true; |
| 35 | + if (typeof logic === 'string') { |
| 36 | + result = logic; |
| 37 | + } else if (logic) { |
| 38 | + result = logic(ctx as FieldContext<TValue, TPathKind>); |
| 39 | + } |
| 40 | + if (typeof result === 'string') { |
| 41 | + return {field: ctx.field, message: result}; |
| 42 | + } |
| 43 | + return result ? {field: ctx.field} : undefined; |
| 44 | + }); |
| 45 | +} |
0 commit comments