@reformer/core 9.0.0 → 9.1.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.
Files changed (105) hide show
  1. package/README.md +52 -57
  2. package/dist/behaviors-node-BMOI2JJF.js +26 -0
  3. package/dist/behaviors-value-lCpqicfa.js +148 -0
  4. package/dist/behaviors.d.ts +2 -133
  5. package/dist/behaviors.js +148 -147
  6. package/dist/{core/utils → form}/aggregate-signals.d.ts +2 -2
  7. package/dist/form/behaviors-node.d.ts +55 -0
  8. package/dist/form/behaviors.d.ts +133 -0
  9. package/dist/{core/utils → form}/create-form.d.ts +5 -4
  10. package/dist/{core/utils → form}/error-handler.d.ts +1 -1
  11. package/dist/{core → form}/factories/node-factory.d.ts +1 -1
  12. package/dist/{core/utils → form}/form-proxy-builder.d.ts +2 -2
  13. package/dist/{core/utils → form}/form-submitter.d.ts +6 -1
  14. package/dist/{hooks → form/hooks}/types.d.ts +31 -1
  15. package/dist/{hooks → form/hooks}/useArrayLength.d.ts +1 -1
  16. package/dist/{hooks → form/hooks}/useFormControl.d.ts +3 -3
  17. package/dist/{hooks → form/hooks}/useFormControlValue.d.ts +2 -2
  18. package/dist/{hooks → form/hooks}/useSignalSubscription.d.ts +8 -1
  19. package/dist/form/index.d.ts +36 -0
  20. package/dist/{core → form}/nodes/array-node.d.ts +1 -1
  21. package/dist/{core → form}/nodes/field-node.d.ts +1 -1
  22. package/dist/{core → form}/nodes/form-node.d.ts +1 -1
  23. package/dist/{core → form}/nodes/group-node.d.ts +34 -4
  24. package/dist/{core → form}/nodes/model-array-node.d.ts +10 -3
  25. package/dist/{core/utils → form}/signal-node-registry.d.ts +1 -1
  26. package/dist/{core/utils → form}/status-machine.d.ts +1 -1
  27. package/dist/{core/utils → form}/type-guards.d.ts +5 -5
  28. package/dist/{core/types/index.d.ts → form/types/contracts.d.ts} +11 -90
  29. package/dist/{core → form}/types/deep-schema.d.ts +23 -1
  30. package/dist/{core → form}/types/form-proxy.d.ts +26 -1
  31. package/dist/form/types/index.d.ts +91 -0
  32. package/dist/{core → form}/types/schema-node.d.ts +1 -1
  33. package/dist/{core → form}/types/validation-schema.d.ts +19 -9
  34. package/dist/{core/model/validate-model.d.ts → form/validate-model-core.d.ts} +25 -25
  35. package/dist/form/validate-model.d.ts +27 -0
  36. package/dist/{core → form}/validation/validators/required.d.ts +2 -1
  37. package/dist/form/validators.d.ts +6 -0
  38. package/dist/form-model-C8Fi83k4.js +439 -0
  39. package/dist/index.d.ts +11 -16
  40. package/dist/index.js +666 -1011
  41. package/dist/{core/model/behaviors.d.ts → state/behaviors-value.d.ts} +0 -38
  42. package/dist/{core/utils → state}/derived-registry.d.ts +29 -0
  43. package/dist/state/form-model.d.ts +26 -0
  44. package/dist/state/index.d.ts +31 -0
  45. package/dist/state/safe-effect.d.ts +93 -0
  46. package/dist/{core/model → state}/types.d.ts +14 -11
  47. package/dist/state.d.ts +2 -0
  48. package/dist/state.js +19 -0
  49. package/dist/validators/email.d.ts +1 -1
  50. package/dist/validators/future-date.d.ts +1 -1
  51. package/dist/validators/integer.d.ts +1 -1
  52. package/dist/validators/is-date.d.ts +1 -1
  53. package/dist/validators/is-number.d.ts +1 -1
  54. package/dist/validators/max-age.d.ts +1 -1
  55. package/dist/validators/max-date.d.ts +1 -1
  56. package/dist/validators/max-length.d.ts +1 -1
  57. package/dist/validators/max.d.ts +1 -1
  58. package/dist/validators/min-age.d.ts +1 -1
  59. package/dist/validators/min-date.d.ts +1 -1
  60. package/dist/validators/min-length.d.ts +1 -1
  61. package/dist/validators/min.d.ts +1 -1
  62. package/dist/validators/multiple-of.d.ts +1 -1
  63. package/dist/validators/non-negative.d.ts +1 -1
  64. package/dist/validators/non-zero.d.ts +1 -1
  65. package/dist/validators/past-date.d.ts +1 -1
  66. package/dist/validators/pattern.d.ts +1 -1
  67. package/dist/validators/pattern.js +7 -6
  68. package/dist/validators/phone.d.ts +1 -1
  69. package/dist/validators/required.d.ts +1 -1
  70. package/dist/validators/required.js +5 -9
  71. package/dist/validators/url.d.ts +1 -1
  72. package/dist/validators.d.ts +6 -6
  73. package/llms.txt +307 -166
  74. package/package.json +5 -1
  75. package/dist/behaviors-O9a1Djj9.js +0 -147
  76. package/dist/core/model/form-model.d.ts +0 -18
  77. package/dist/core/model/index.d.ts +0 -12
  78. package/dist/core/utils/index.d.ts +0 -18
  79. package/dist/core/utils/safe-effect.d.ts +0 -73
  80. /package/dist/{core → form}/factories/index.d.ts +0 -0
  81. /package/dist/{core/utils → form}/unique-id.d.ts +0 -0
  82. /package/dist/{core → form}/validation/index.d.ts +0 -0
  83. /package/dist/{core → form}/validation/validators/date-utils.d.ts +0 -0
  84. /package/dist/{core → form}/validation/validators/email.d.ts +0 -0
  85. /package/dist/{core → form}/validation/validators/future-date.d.ts +0 -0
  86. /package/dist/{core → form}/validation/validators/index.d.ts +0 -0
  87. /package/dist/{core → form}/validation/validators/integer.d.ts +0 -0
  88. /package/dist/{core → form}/validation/validators/is-date.d.ts +0 -0
  89. /package/dist/{core → form}/validation/validators/is-number.d.ts +0 -0
  90. /package/dist/{core → form}/validation/validators/max-age.d.ts +0 -0
  91. /package/dist/{core → form}/validation/validators/max-date.d.ts +0 -0
  92. /package/dist/{core → form}/validation/validators/max-length.d.ts +0 -0
  93. /package/dist/{core → form}/validation/validators/max.d.ts +0 -0
  94. /package/dist/{core → form}/validation/validators/min-age.d.ts +0 -0
  95. /package/dist/{core → form}/validation/validators/min-date.d.ts +0 -0
  96. /package/dist/{core → form}/validation/validators/min-length.d.ts +0 -0
  97. /package/dist/{core → form}/validation/validators/min.d.ts +0 -0
  98. /package/dist/{core → form}/validation/validators/multiple-of.d.ts +0 -0
  99. /package/dist/{core → form}/validation/validators/non-negative.d.ts +0 -0
  100. /package/dist/{core → form}/validation/validators/non-zero.d.ts +0 -0
  101. /package/dist/{core → form}/validation/validators/past-date.d.ts +0 -0
  102. /package/dist/{core → form}/validation/validators/pattern.d.ts +0 -0
  103. /package/dist/{core → form}/validation/validators/phone.d.ts +0 -0
  104. /package/dist/{core → form}/validation/validators/url.d.ts +0 -0
  105. /package/dist/{core/utils → state}/subscription-manager.d.ts +0 -0
package/README.md CHANGED
@@ -30,33 +30,35 @@ npm install @reformer/core@beta # Active development is underway, so you can try
30
30
 
31
31
  ## Quick Start
32
32
 
33
+ ReFormer is built around the **M1 architecture**: a reactive `FormModel` owns the values, a single
34
+ schema binds field config (component / validators) to the model's signals, and `createForm({ model, schema })`
35
+ wires them into a typed form.
36
+
33
37
  ```tsx
34
38
  import { useMemo } from 'react';
35
39
  import {
40
+ createModel,
36
41
  createForm,
42
+ validateFormModel,
37
43
  useFormControl,
38
- required,
39
- email,
40
- validate,
41
- watchField,
42
- FieldNode,
43
- type ValidationSchemaFn,
44
- type BehaviorSchemaFn,
44
+ type FieldNode,
45
45
  } from '@reformer/core';
46
+ import { required, email, minLength } from '@reformer/core/validators';
47
+ import { defineFormBehavior, onChange } from '@reformer/core/behaviors';
46
48
 
47
49
  // 0. Simple FormField component
48
50
  function FormField({ label, control }: { label: string; control: FieldNode<string> }) {
49
- const { value, errors } = useFormControl(control);
51
+ const { value, errors, shouldShowError } = useFormControl(control);
50
52
 
51
53
  return (
52
54
  <div>
53
55
  <label>{label}</label>
54
56
  <input
55
- value={value}
57
+ value={value ?? ''}
56
58
  onChange={(e) => control.setValue(e.target.value)}
57
59
  onBlur={() => control.markAsTouched()}
58
60
  />
59
- {errors.length > 0 && <span className="error">{errors[0].message}</span>}
61
+ {shouldShowError && <span className="error">{errors[0].message}</span>}
60
62
  </div>
61
63
  );
62
64
  }
@@ -69,62 +71,55 @@ interface RegistrationForm {
69
71
  confirmPassword: string;
70
72
  }
71
73
 
72
- // 2. Form schema
73
- const formSchema = {
74
- username: { value: '' },
75
- email: { value: '' },
76
- password: { value: '' },
77
- confirmPassword: { value: '' },
74
+ // 2. Reactive model — the source of truth for values
75
+ const model = createModel<RegistrationForm>({
76
+ username: '',
77
+ email: '',
78
+ password: '',
79
+ confirmPassword: '',
80
+ });
81
+
82
+ // 3. Single schema — binds field config to model signals (`model.$.<field>`).
83
+ // Validators are inline factories from `@reformer/core/validators`.
84
+ // Cross-field validation is a ModelValidator `(value, model) => error | null`.
85
+ const schema = {
86
+ children: [
87
+ { value: model.$.username, component: Input, validators: [required(), minLength(2)] },
88
+ { value: model.$.email, component: Input, validators: [required(), email()] },
89
+ { value: model.$.password, component: Input, validators: [required(), minLength(8)] },
90
+ {
91
+ value: model.$.confirmPassword,
92
+ component: Input,
93
+ validators: [
94
+ required(),
95
+ (value, m) =>
96
+ value && m.password && value !== m.password
97
+ ? { code: 'mismatch', message: 'Passwords do not match' }
98
+ : null,
99
+ ],
100
+ },
101
+ ],
78
102
  };
79
103
 
80
- // 3. Validation schema
81
- const validationSchema: ValidationSchemaFn<RegistrationForm> = (path) => {
82
- required(path.username);
83
-
84
- required(path.email);
85
- email(path.email);
86
-
87
- required(path.password);
88
- required(path.confirmPassword);
89
-
90
- // Cross-field validation: вешается на поле-носитель ошибки, соседнее поле читается через `root`
91
- validate(path.confirmPassword, (value, _control, root) => {
92
- const password = root.password.value.value;
93
- if (value && password && value !== password) {
94
- return { code: 'mismatch', message: 'Passwords do not match' };
95
- }
96
- return null;
104
+ // 4. Behavior — declarative reactive logic, run by `createForm({ behavior })`.
105
+ // Clear confirmPassword whenever password changes.
106
+ const behavior = defineFormBehavior<RegistrationForm>(({ model }) => {
107
+ onChange(model.$.password, () => {
108
+ if (model.confirmPassword) model.confirmPassword = '';
97
109
  });
98
- };
99
-
100
- // 4. Behavior schema
101
- const behaviorSchema: BehaviorSchemaFn<RegistrationForm> = (path) => {
102
- // Clear confirmPassword when password changes (if not empty)
103
- watchField(path.password, (_, ctx) => {
104
- const confirmValue = ctx.form.confirmPassword.value.value;
105
- if (confirmValue) {
106
- ctx.form.confirmPassword.setValue('', { emitEvent: false });
107
- }
108
- });
109
- };
110
+ });
110
111
 
111
112
  // 5. Registration form component
112
113
  function RegistrationFormExample() {
113
- const form = useMemo(
114
- () =>
115
- createForm<RegistrationForm>({
116
- form: formSchema,
117
- validation: validationSchema,
118
- behavior: behaviorSchema,
119
- }),
120
- []
121
- );
114
+ const form = useMemo(() => createForm<RegistrationForm>({ model, schema, behavior }), []);
122
115
 
123
116
  const handleSubmit = async (e: React.FormEvent) => {
124
117
  e.preventDefault();
125
- await form.validate();
126
- if (form.valid.value) {
127
- console.log('Form data:', form.value.value);
118
+ form.touchAll();
119
+ // Validate the whole model against the schema (sync + async); errors route into the form.
120
+ const { valid } = await validateFormModel(model, schema);
121
+ if (valid) {
122
+ console.log('Form data:', model.get());
128
123
  }
129
124
  };
130
125
 
@@ -0,0 +1,26 @@
1
+ import { effect as o } from "@preact/signals-core";
2
+ import { d as a } from "./behaviors-value-lCpqicfa.js";
3
+ const s = /* @__PURE__ */ new WeakMap();
4
+ function l(e, n) {
5
+ s.set(e, n);
6
+ }
7
+ function f(e) {
8
+ return s.get(e);
9
+ }
10
+ function u(e, n, r) {
11
+ return o(() => {
12
+ const i = n(), t = f(e);
13
+ t && a(() => {
14
+ i ? t.enable() : (t.disable(), r?.resetOnDisable && t.reset());
15
+ });
16
+ });
17
+ }
18
+ function g(e, n, r) {
19
+ return u(e, () => !n(), r);
20
+ }
21
+ export {
22
+ g as d,
23
+ u as e,
24
+ f as g,
25
+ l as r
26
+ };
@@ -0,0 +1,148 @@
1
+ import { effect as f } from "@preact/signals-core";
2
+ const a = /* @__PURE__ */ new WeakMap();
3
+ function h(e) {
4
+ a.set(e, (a.get(e) ?? 0) + 1);
5
+ }
6
+ function y(e) {
7
+ const n = a.get(e);
8
+ n !== void 0 && (n <= 1 ? a.delete(e) : a.set(e, n - 1));
9
+ }
10
+ function E(e) {
11
+ return a.has(e);
12
+ }
13
+ const m = "runOutsideEffect";
14
+ function v(e, n) {
15
+ process.env.NODE_ENV !== "production" && console.error(`[${n}]`, e);
16
+ }
17
+ function p(e) {
18
+ return typeof e == "object" && e !== null && typeof e.then == "function";
19
+ }
20
+ function d(e, n) {
21
+ try {
22
+ const t = e();
23
+ p(t) && t.then(void 0, (r) => v(r, n));
24
+ } catch (t) {
25
+ v(t, n);
26
+ }
27
+ }
28
+ function D(e) {
29
+ return (...n) => {
30
+ s(() => e(...n));
31
+ };
32
+ }
33
+ function s(e) {
34
+ let n = !1;
35
+ return queueMicrotask(() => {
36
+ n || d(e, m);
37
+ }), () => {
38
+ n = !0;
39
+ };
40
+ }
41
+ function w(e, n) {
42
+ return () => {
43
+ n(() => d(e, "safeDebouncedCallback"));
44
+ };
45
+ }
46
+ function b(e, n, t, r) {
47
+ return f(() => {
48
+ const u = e.map((c) => c.value);
49
+ if (r?.when && !r.when(...u)) return;
50
+ const o = t(...u);
51
+ n.peek() !== o && (n.value = o);
52
+ });
53
+ }
54
+ function F(e, n, t) {
55
+ return f(() => {
56
+ const r = e.value;
57
+ if (t?.when && !t.when()) return;
58
+ const u = t?.transform ? t.transform(r) : r;
59
+ n.peek() !== u && (n.value = u);
60
+ });
61
+ }
62
+ function x(e, n, t) {
63
+ let r = !0;
64
+ return f(() => {
65
+ const u = e.value;
66
+ r && (r = !1, !t?.immediate) || n(u);
67
+ });
68
+ }
69
+ function C(e, n) {
70
+ let t = !1;
71
+ return f(() => {
72
+ const r = e.value;
73
+ t || s(() => {
74
+ const u = n(r);
75
+ if (e.peek() !== u) {
76
+ t = !0;
77
+ try {
78
+ e.value = u;
79
+ } finally {
80
+ t = !1;
81
+ }
82
+ }
83
+ });
84
+ });
85
+ }
86
+ function O(e, n, t) {
87
+ const r = t?.resetValue ?? null;
88
+ return f(() => {
89
+ const u = n();
90
+ s(() => {
91
+ u && e.peek() !== r && (e.value = r);
92
+ });
93
+ });
94
+ }
95
+ function V(e, n, t) {
96
+ const r = t?.transform;
97
+ let u = !1;
98
+ const o = f(() => {
99
+ const i = e.value;
100
+ u || s(() => {
101
+ u = !0;
102
+ try {
103
+ const l = r ? r(i) : i;
104
+ n.peek() !== l && (n.value = l);
105
+ } finally {
106
+ u = !1;
107
+ }
108
+ });
109
+ }), c = f(() => {
110
+ const i = n.value;
111
+ u || s(() => {
112
+ u = !0;
113
+ try {
114
+ e.peek() !== i && (e.value = i);
115
+ } finally {
116
+ u = !1;
117
+ }
118
+ });
119
+ });
120
+ return () => {
121
+ o(), c();
122
+ };
123
+ }
124
+ function N(e, n) {
125
+ let t = !0;
126
+ return f(() => {
127
+ if (e.forEach((r) => r.value), t) {
128
+ t = !1;
129
+ return;
130
+ }
131
+ s(() => n());
132
+ });
133
+ }
134
+ export {
135
+ F as a,
136
+ N as b,
137
+ b as c,
138
+ s as d,
139
+ D as e,
140
+ w as f,
141
+ E as i,
142
+ h as m,
143
+ O as r,
144
+ V as s,
145
+ C as t,
146
+ y as u,
147
+ x as w
148
+ };
@@ -1,133 +1,2 @@
1
- import { Signal, ReadonlySignal } from '@preact/signals-core';
2
- import { BehaviorCleanup, FormModel, FormProxy } from './index';
3
- /** Контекст схемы поведения: модель (значения/сигналы) + форма (ноды). */
4
- export type BehaviorScope<T> = {
5
- model: FormModel<T>;
6
- form: FormProxy<T>;
7
- };
8
- /** Результат {@link defineFormBehavior}; передаётся в `createForm({ behavior })`. */
9
- export interface FormBehavior<T> {
10
- /** @internal Запускается `createForm` после построения нод и заполнения реестра сигнал→нода. */
11
- __run(model: FormModel<T>, form: FormProxy<T>): BehaviorCleanup;
12
- }
13
- export type { Signal, ReadonlySignal, BehaviorCleanup };
14
- /** Зарегистрировать произвольную отписку в активной схеме. */
15
- export declare function onDispose(cleanup: BehaviorCleanup): void;
16
- /** Текущий scope ({ model, form }) активной схемы (escape hatch для кросс-операторов). */
17
- export declare function getScope<T>(): BehaviorScope<T>;
18
- /**
19
- * Описать поведение формы декларативно. Возвращает {@link FormBehavior} для `createForm({ behavior })`.
20
- *
21
- * @example
22
- * ```ts
23
- * export const myBehavior = defineFormBehavior<MyForm>(({ model, form }) => {
24
- * compute(model.$.total, () => model.price * model.qty);
25
- * enableWhen([model.$.city], () => Boolean(model.country));
26
- * onChange(model.$.country, async (c) => form.city.updateComponentProps({ options: await load(c) }));
27
- * });
28
- * ```
29
- */
30
- export declare function defineFormBehavior<T>(setup: (scope: BehaviorScope<T>) => void): FormBehavior<T>;
31
- /** Реактивный эффект (авто-dispose). Колбэк может вернуть собственный cleanup. */
32
- export declare function effect(fn: () => void | (() => void)): void;
33
- /** Отложенная запись вне effect-контекста (микротаск) — защита от «Cycle detected». */
34
- export declare function defer(fn: () => void): void;
35
- /** Вычисляемое поле с auto-tracking: `target = read()` при изменении прочитанных сигналов. */
36
- export declare function compute<R>(target: Signal<R>, read: () => R, options?: {
37
- when?: () => boolean;
38
- }): void;
39
- /** Вычисляемое поле с явным списком зависимостей (escape hatch). */
40
- export declare function computeFrom<R>(sources: ReadonlySignal<unknown>[], target: Signal<R>, fn: (...values: any[]) => R, options?: {
41
- when?: (...values: any[]) => boolean;
42
- }): void;
43
- /** Копирование `source → target` — скаляр или группа (объект целиком). */
44
- export declare function copyFrom<T>(source: ReadonlySignal<T> | object, target: Signal<T> | object, options?: {
45
- when?: () => boolean;
46
- transform?: (value: T) => T;
47
- }): void;
48
- /** Контекст async-реакции: `signal` аннулируется, когда поле меняется снова до завершения колбэка. */
49
- export interface ChangeContext {
50
- signal: AbortSignal;
51
- }
52
- /**
53
- * Реакция на изменение поля; `{ debounce, immediate }`.
54
- *
55
- * Колбэк выполняется ВНЕ effect-контекста (микротаск/таймер) — можно безопасно писать сигналы и ноды
56
- * (`updateComponentProps`/`reset`/`clear`) без ручного `defer` и без «Cycle detected».
57
- *
58
- * Для async-колбэков 2-м аргументом приходит `{ signal }` (AbortSignal): при следующей смене значения
59
- * предыдущий `signal` аннулируется. Передавай его в `fetch` (сетевая отмена) или проверяй
60
- * `signal.aborted` перед применением результата — это убирает гонки устаревших ответов (F2).
61
- */
62
- export declare function onChange<T>(source: ReadonlySignal<T>, cb: (value: T, ctx: ChangeContext) => void, options?: {
63
- immediate?: boolean;
64
- debounce?: number;
65
- }): void;
66
- type EnableTarget = ReadonlySignal<unknown> | object;
67
- /** Условное включение поля(ей) — скаляр, массив целей или группа. `resetOnDisable=false` по умолчанию. */
68
- export declare function enableWhen(target: EnableTarget | EnableTarget[], condition: () => boolean, options?: {
69
- resetOnDisable?: boolean;
70
- }): void;
71
- /** Условное выключение поля(ей) (инверсия {@link enableWhen}). */
72
- export declare function disableWhen(target: EnableTarget | EnableTarget[], condition: () => boolean, options?: {
73
- resetOnDisable?: boolean;
74
- }): void;
75
- /** Трансформация значения поля (идемпотентная). */
76
- export declare function transformValue<T>(target: Signal<T>, transformer: (value: T) => T): void;
77
- /** Сброс значения по условию. */
78
- export declare function resetWhen<T>(target: Signal<T>, condition: () => boolean, options?: {
79
- resetValue?: T;
80
- }): void;
81
- /** Двусторонняя синхронизация двух полей. */
82
- export declare function syncFields<T>(a: Signal<T>, b: Signal<T>, options?: {
83
- transform?: (value: T) => T;
84
- }): void;
85
- /** Ревалидация при изменении зависимостей. */
86
- export declare function revalidateWhen(deps: ReadonlySignal<unknown>[], revalidate: () => void): void;
87
- /**
88
- * Применить под-схему к КАЖДОМУ элементу динамического массива (per-item поведение).
89
- * Реагирует на добавление/удаление строк: новым строкам поведение применяется, удалённым — отписывается.
90
- *
91
- * Под-схема получает scope строки: `model` (под-модель строки — `row.$.field`) и `form` (нода строки).
92
- * - Value-операции (`compute`/`copyFrom`/`transformValue` на `row.$.*`) работают всегда.
93
- * - Node-операции (`enableWhen`/`updateComponentProps`/`reset` через `form.*`) требуют, чтобы массив был
94
- * МАТЕРИАЛИЗОВАН в форме (узел `{ array, item }` в схеме) — тогда `form` строки = та же нода, что
95
- * рендерится, а её сигналы зарегистрированы (`enableWhen` резолвит ноду). Без материализации доступ
96
- * к `form.*` бросит понятную ошибку (см. {@link unmaterializedRowForm}).
97
- *
98
- * @example
99
- * applyEach(model.$.items, defineFormBehavior<Item>(({ model: row, form }) => {
100
- * compute(row.$.lineTotal, () => row.qty * row.price); // value-op — всегда
101
- * enableWhen(row.$.discount, () => row.qty > 10); // node-op — нужна материализация массива
102
- * }));
103
- */
104
- export declare function applyEach<TItem>(array: object, itemSchema: FormBehavior<TItem>): void;
105
- /**
106
- * Взаимное исключение булева флага среди строк массива (single-selection — «единственный primary»).
107
- * Когда флаг строки становится true, у остальных строк он сбрасывается в false. Не хрупок к push:
108
- * новые строки с флагом false исключения не запускают.
109
- *
110
- * @example
111
- * exclusiveFlag(model.$.contacts, (row) => row.$.primary);
112
- */
113
- export declare function exclusiveFlag<TItem>(array: object, getFlag: (row: FormModel<TItem>) => Signal<boolean>): void;
114
- /**
115
- * Агрегатная запись в строки массива. `derive(snapshot)` получает СНИМОК строк и возвращает список
116
- * `{ index, patch }`, который применяется к строкам. Записи КОАЛЕСИРУЮТСЯ в один отложенный проход на
117
- * финальном состоянии — поэтому массовые синхронные мутации (push в цикле) не вызывают каскад на
118
- * промежуточных состояниях. `derive` должна сходиться (на фикспоинте возвращать те же значения).
119
- *
120
- * @example
121
- * // последняя строка = 100 − Σ(остальные)
122
- * aggregateInto(model.$.rows, (rows) => {
123
- * const n = rows.length; if (n === 0) return [];
124
- * const others = rows.slice(0, n - 1).reduce((s, r) => s + r.percent, 0);
125
- * return [{ index: n - 1, patch: { percent: 100 - others } }];
126
- * });
127
- */
128
- export declare function aggregateInto<TItem>(array: object, derive: (rows: TItem[]) => Array<{
129
- index: number;
130
- patch: Partial<TItem>;
131
- }>): void;
132
- /** Применить под-схему к одному или нескольким полям-группам (переиспользование). */
133
- export declare function apply<TField>(targets: object | object[], subSchema: FormBehavior<TField>): void;
1
+ export * from './form/behaviors'
2
+ export {}