@fluixi/forms-core 0.2.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.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Fluixi
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,4 @@
1
+ import type { ArrayControl, ArrayOptions, Control } from './types.js';
2
+ /** Stable key for a control (for keyed list rendering). */
3
+ export declare const keyOf: (control: object) => number;
4
+ export declare function createFormArray<TItem, TCtrl extends Control<TItem> = Control<TItem>>(initial?: TCtrl[], options?: ArrayOptions<TItem>): ArrayControl<TItem, TCtrl>;
package/dist/array.js ADDED
@@ -0,0 +1,117 @@
1
+ /**
2
+ * createFormArray — a dynamic, ordered list of controls with STABLE identity.
3
+ *
4
+ * The list is a signal of controls; push/insert/remove/move replace it immutably so
5
+ * fine-grained list diffing (the framework's keyed `<For>`) reuses DOM for moved rows
6
+ * instead of re-rendering. Identity is the control object itself (stable across reorders),
7
+ * exposed via `keyOf` for keyed rendering. Aggregate state is derived with memos.
8
+ */
9
+ import { createSignal, createMemo, untrack, batch } from '@fluixi/reactive/signal';
10
+ let _key = 0;
11
+ const keys = new WeakMap();
12
+ /** Stable key for a control (for keyed list rendering). */
13
+ export const keyOf = (control) => {
14
+ let k = keys.get(control);
15
+ if (k === undefined)
16
+ keys.set(control, (k = ++_key));
17
+ return k;
18
+ };
19
+ export function createFormArray(initial = [], options = {}) {
20
+ const [list, setList] = createSignal([...initial]);
21
+ const [disabled, setDisabledSig] = createSignal(!!options.disabled);
22
+ const [submitCount] = createSignal(0);
23
+ const syncValidators = options.validators ?? [];
24
+ let parent = null;
25
+ let self;
26
+ const wire = (c) => c._setParent(self, null);
27
+ const value = createMemo(() => list().map((c) => c.value()));
28
+ const initialValue = createMemo(() => list().map((c) => c.initialValue()));
29
+ const ctx = {
30
+ get control() {
31
+ return self;
32
+ },
33
+ get root() {
34
+ return self._root();
35
+ },
36
+ get: (path) => self._ctxGet(path),
37
+ };
38
+ const ownErrors = createMemo(() => {
39
+ if (disabled())
40
+ return [];
41
+ const v = value();
42
+ const out = [];
43
+ for (const validator of syncValidators) {
44
+ const e = validator(v, ctx);
45
+ if (e)
46
+ out.push(e);
47
+ }
48
+ return out;
49
+ });
50
+ const errors = createMemo(() => {
51
+ if (disabled())
52
+ return [];
53
+ const out = [...ownErrors()];
54
+ for (const c of list())
55
+ out.push(...c.errors());
56
+ return out;
57
+ });
58
+ const valid = createMemo(() => !disabled() && ownErrors().length === 0 && list().every((c) => c.valid()));
59
+ const mutate = (fn) => setList((prev) => fn([...prev]));
60
+ self = {
61
+ kind: 'array',
62
+ controls: list,
63
+ length: createMemo(() => list().length),
64
+ value,
65
+ initialValue,
66
+ errors,
67
+ error: createMemo(() => errors()[0]),
68
+ valid,
69
+ invalid: createMemo(() => !valid()),
70
+ pending: createMemo(() => list().some((c) => c.pending())),
71
+ touched: createMemo(() => list().some((c) => c.touched())),
72
+ untouched: createMemo(() => !list().some((c) => c.touched())),
73
+ dirty: createMemo(() => list().some((c) => c.dirty())),
74
+ pristine: createMemo(() => !list().some((c) => c.dirty())),
75
+ disabled,
76
+ enabled: createMemo(() => !disabled()),
77
+ submitCount,
78
+ at: (i) => untrack(list)[i],
79
+ push: (c) => {
80
+ wire(c);
81
+ mutate((arr) => (arr.push(c), arr));
82
+ },
83
+ insert: (i, c) => {
84
+ wire(c);
85
+ mutate((arr) => (arr.splice(i, 0, c), arr));
86
+ },
87
+ removeAt: (i) => mutate((arr) => (arr.splice(i, 1), arr)),
88
+ move: (from, to) => mutate((arr) => {
89
+ const [c] = arr.splice(from, 1);
90
+ arr.splice(to, 0, c);
91
+ return arr;
92
+ }),
93
+ clear: () => setList([]),
94
+ setValue: (v, opts) => batch(() => untrack(list).forEach((c, i) => c.setValue(v[i], opts))),
95
+ patch: (v, opts) => batch(() => untrack(list).forEach((c, i) => v[i] != null && c.patch(v[i], opts))),
96
+ reset: (v) => batch(() => untrack(list).forEach((c, i) => c.reset(v ? v[i] : undefined))),
97
+ markTouched: (t = true) => batch(() => untrack(list).forEach((c) => c.markTouched(t))),
98
+ markDirty: (d = true) => batch(() => untrack(list).forEach((c) => c.markDirty(d))),
99
+ setDisabled: (d) => {
100
+ setDisabledSig(d);
101
+ batch(() => untrack(list).forEach((c) => c.setDisabled(d)));
102
+ },
103
+ validate: async () => {
104
+ const r = await Promise.all(untrack(list).map((c) => c.validate()));
105
+ return r.every(Boolean) && untrack(valid);
106
+ },
107
+ dispose: () => untrack(list).forEach((c) => c.dispose()),
108
+ _setParent: (p) => {
109
+ parent = p;
110
+ },
111
+ _root: () => (parent ? parent._root() : self),
112
+ _ctxGet: (path) => parent ? parent._ctxGet(path) : undefined,
113
+ _bumpSubmit: () => batch(() => untrack(list).forEach((c) => c._bumpSubmit(submitCount))),
114
+ };
115
+ initial.forEach(wire);
116
+ return self;
117
+ }
@@ -0,0 +1,9 @@
1
+ import type { Accessor, FieldControl, FieldOptions, AnyControl, Widen } from './types.js';
2
+ /** Internal hooks the parent group/array uses to wire context + propagation. */
3
+ export interface InternalControl {
4
+ _setParent(parent: AnyControl | null, key: string | number | null): void;
5
+ _root(): AnyControl;
6
+ _ctxGet(path: string): unknown;
7
+ _bumpSubmit(n: Accessor<number>): void;
8
+ }
9
+ export declare function createField<T>(initial: T, options?: FieldOptions<T>): FieldControl<Widen<T>>;
package/dist/field.js ADDED
@@ -0,0 +1,182 @@
1
+ /**
2
+ * createField — the FormControl equivalent.
3
+ *
4
+ * Reactivity model (fine-grained, no central store):
5
+ * value → a signal
6
+ * touched → a signal
7
+ * disabled → a signal
8
+ * syncErrors → a memo over (value, sibling deps via ctx) — LAZY, recomputed only when
9
+ * an input changes, and only if something reads it.
10
+ * asyncErrors→ a signal, written by a debounced effect (AbortController-cancelled)
11
+ * errors → memo merging sync + async
12
+ * valid/dirty/… → memos derived from the above
13
+ *
14
+ * No field re-runs because another field changed, unless it explicitly reads that field
15
+ * through `ctx.get(path)` (a cross-field dependency) — that read subscribes it precisely.
16
+ */
17
+ import { createSignal, createMemo, createEffect, untrack, onCleanup, batch, } from '@fluixi/reactive/signal';
18
+ export function createField(initial, options = {}) {
19
+ const equals = options.equals ?? Object.is;
20
+ const debounce = options.debounce ?? 250;
21
+ const syncValidators = options.validators ?? [];
22
+ const asyncValidators = options.asyncValidators ?? [];
23
+ const [value, setValueSig] = createSignal(initial);
24
+ const [initialValue, setInitial] = createSignal(initial);
25
+ const [touched, setTouchedSig] = createSignal(false);
26
+ const [disabled, setDisabledSig] = createSignal(!!options.disabled);
27
+ const [asyncErrors, setAsyncErrors] = createSignal([]);
28
+ const [pending, setPending] = createSignal(false);
29
+ const [submitCount, setSubmitCount] = createSignal(0);
30
+ // Parent wiring (set when this field is placed into a group/array).
31
+ let parent = null;
32
+ let self;
33
+ const ctx = {
34
+ get control() {
35
+ return self;
36
+ },
37
+ get root() {
38
+ return self._root();
39
+ },
40
+ get: (path) => self._ctxGet(path),
41
+ };
42
+ // Sync validation — a memo. Reading `value()` subscribes it to value; any `ctx.get(p)`
43
+ // inside a validator subscribes it to that sibling. Disabled fields are always valid.
44
+ const syncErrors = createMemo(() => {
45
+ if (disabled())
46
+ return [];
47
+ const v = value();
48
+ const out = [];
49
+ for (const validator of syncValidators) {
50
+ const e = validator(v, ctx);
51
+ if (e)
52
+ out.push(e);
53
+ }
54
+ return out;
55
+ });
56
+ const errors = createMemo(() => disabled() ? [] : [...syncErrors(), ...asyncErrors()]);
57
+ const error = createMemo(() => errors()[0]);
58
+ const valid = createMemo(() => !disabled() && errors().length === 0 && !pending());
59
+ const invalid = createMemo(() => !valid());
60
+ const dirty = createMemo(() => !equals(value(), initialValue()));
61
+ const pristine = createMemo(() => !dirty());
62
+ // ── Async validation engine ──────────────────────────────────────────────────
63
+ // A single debounced effect tracks `value`. On each change it cancels the in-flight run
64
+ // (AbortController), waits `debounce`, runs all async validators in parallel, and writes
65
+ // the result — but only if it's still the latest run (stale guard). pending() reflects it.
66
+ if (asyncValidators.length > 0) {
67
+ let runId = 0;
68
+ let controller = null;
69
+ let timer = null;
70
+ createEffect(() => {
71
+ const v = value(); // track
72
+ if (untrack(disabled)) {
73
+ setPending(false);
74
+ setAsyncErrors([]);
75
+ return;
76
+ }
77
+ const id = ++runId;
78
+ controller?.abort();
79
+ if (timer)
80
+ clearTimeout(timer);
81
+ setPending(true);
82
+ timer = setTimeout(async () => {
83
+ controller = new AbortController();
84
+ try {
85
+ const results = await Promise.all(asyncValidators.map((av) => av(v, ctx, controller.signal)));
86
+ if (id !== runId)
87
+ return; // a newer change superseded this run
88
+ batch(() => {
89
+ setAsyncErrors(results.filter((e) => e != null));
90
+ setPending(false);
91
+ });
92
+ }
93
+ catch (e) {
94
+ if (id !== runId)
95
+ return;
96
+ setPending(false);
97
+ }
98
+ }, debounce);
99
+ });
100
+ onCleanup(() => {
101
+ controller?.abort();
102
+ if (timer)
103
+ clearTimeout(timer);
104
+ });
105
+ }
106
+ // ── Mutations ────────────────────────────────────────────────────────────────
107
+ const setValue = (v, opts = {}) => {
108
+ batch(() => {
109
+ setValueSig(() => v);
110
+ if (!opts.pristine)
111
+ setTouchedSig(true);
112
+ });
113
+ };
114
+ const reset = (v) => {
115
+ batch(() => {
116
+ const next = v === undefined ? untrack(initialValue) : v;
117
+ if (v !== undefined)
118
+ setInitial(() => v);
119
+ setValueSig(() => next);
120
+ setTouchedSig(false);
121
+ setAsyncErrors([]);
122
+ setPending(false);
123
+ });
124
+ };
125
+ const validate = async () => {
126
+ setTouchedSig(true);
127
+ if (asyncValidators.length === 0)
128
+ return untrack(valid);
129
+ const v = untrack(value);
130
+ const c = new AbortController();
131
+ setPending(true);
132
+ try {
133
+ const results = await Promise.all(asyncValidators.map((av) => av(v, ctx, c.signal)));
134
+ batch(() => {
135
+ setAsyncErrors(results.filter((e) => e != null));
136
+ setPending(false);
137
+ });
138
+ }
139
+ catch {
140
+ setPending(false);
141
+ }
142
+ return untrack(valid);
143
+ };
144
+ self = {
145
+ kind: 'field',
146
+ value,
147
+ initialValue,
148
+ errors,
149
+ error,
150
+ valid,
151
+ invalid,
152
+ pending,
153
+ touched,
154
+ untouched: createMemo(() => !touched()),
155
+ dirty,
156
+ pristine,
157
+ disabled,
158
+ enabled: createMemo(() => !disabled()),
159
+ submitCount,
160
+ setValue,
161
+ patch: (v) => setValue(v),
162
+ reset,
163
+ markTouched: (t = true) => setTouchedSig(t),
164
+ markDirty: (d = true) => {
165
+ if (!d)
166
+ setInitial(() => untrack(value)); // "not dirty" ⇒ make current the baseline
167
+ },
168
+ setDisabled: (d) => setDisabledSig(d),
169
+ validate,
170
+ dispose: () => {
171
+ /* effects are torn down by the owning reactive root; explicit hook for manual use */
172
+ },
173
+ // internal
174
+ _setParent: (p) => {
175
+ parent = p;
176
+ },
177
+ _root: () => (parent ? parent._root() : self),
178
+ _ctxGet: (path) => (parent ? parent._ctxGet(path) : undefined),
179
+ _bumpSubmit: (n) => setSubmitCount(untrack(n)),
180
+ };
181
+ return self;
182
+ }
@@ -0,0 +1,4 @@
1
+ import type { ControlsRecord, FormControl, GroupControl, GroupOptions } from './types.js';
2
+ export declare function createGroup<C extends ControlsRecord>(initialControls: C, options?: GroupOptions<C>): GroupControl<C>;
3
+ /** Root form: a group plus submission state + `submit()`. */
4
+ export declare function createForm<C extends ControlsRecord>(controls: C, options?: GroupOptions<C>): FormControl<C>;
package/dist/group.js ADDED
@@ -0,0 +1,189 @@
1
+ /**
2
+ * createGroup — the FormGroup equivalent; createForm — a root group with submission.
3
+ *
4
+ * A group derives its aggregate state from its children with memos, so the aggregate is
5
+ * lazy and granular: `group.valid()` recomputes only when a child's `valid()` flips, and
6
+ * reading it subscribes the caller to exactly that. Structure is itself a signal, so
7
+ * dynamic add/remove of controls is reactive.
8
+ */
9
+ import { createSignal, createMemo, untrack, batch } from '@fluixi/reactive/signal';
10
+ export function createGroup(initialControls, options = {}) {
11
+ const [controlsSig, setControls] = createSignal({ ...initialControls });
12
+ const [disabled, setDisabledSig] = createSignal(!!options.disabled);
13
+ const [submitCount, setSubmitCount] = createSignal(0);
14
+ const syncValidators = options.validators ?? [];
15
+ const asyncValidators = options.asyncValidators ?? [];
16
+ let parent = null;
17
+ let self;
18
+ const children = createMemo(() => Object.values(controlsSig()));
19
+ // Wire each child to this group (parent link) so cross-field ctx.get + root resolution work.
20
+ const wire = (record) => {
21
+ for (const c of Object.values(record))
22
+ c._setParent(self, null);
23
+ };
24
+ const value = createMemo(() => {
25
+ const record = controlsSig();
26
+ const out = {};
27
+ for (const key in record)
28
+ out[key] = record[key].value();
29
+ return out;
30
+ });
31
+ const initialValue = createMemo(() => {
32
+ const record = controlsSig();
33
+ const out = {};
34
+ for (const key in record)
35
+ out[key] = record[key].initialValue();
36
+ return out;
37
+ });
38
+ const ctx = {
39
+ get control() {
40
+ return self;
41
+ },
42
+ get root() {
43
+ return self._root();
44
+ },
45
+ get: (path) => self._ctxGet(path),
46
+ };
47
+ const ownErrors = createMemo(() => {
48
+ if (disabled())
49
+ return [];
50
+ const v = value();
51
+ const out = [];
52
+ for (const validator of syncValidators) {
53
+ const e = validator(v, ctx);
54
+ if (e)
55
+ out.push(e);
56
+ }
57
+ return out;
58
+ });
59
+ // Aggregate: own group-level errors + every descendant's errors.
60
+ const errors = createMemo(() => {
61
+ if (disabled())
62
+ return [];
63
+ const out = [...ownErrors()];
64
+ for (const c of children())
65
+ out.push(...c.errors());
66
+ return out;
67
+ });
68
+ const valid = createMemo(() => !disabled() && ownErrors().length === 0 && children().every((c) => c.valid()));
69
+ const pending = createMemo(() => children().some((c) => c.pending()));
70
+ const touched = createMemo(() => children().some((c) => c.touched()));
71
+ const dirty = createMemo(() => children().some((c) => c.dirty()));
72
+ // ── mutations ──────────────────────────────────────────────────────────────
73
+ const patch = (partial, opts) => {
74
+ batch(() => {
75
+ const record = untrack(controlsSig);
76
+ for (const key in partial) {
77
+ const c = record[key];
78
+ if (c)
79
+ c.patch(partial[key], opts);
80
+ }
81
+ });
82
+ };
83
+ const setValue = (v, opts) => {
84
+ batch(() => {
85
+ const record = untrack(controlsSig);
86
+ for (const key in record)
87
+ record[key].setValue(v[key], opts);
88
+ });
89
+ };
90
+ const reset = (v) => {
91
+ batch(() => {
92
+ const record = untrack(controlsSig);
93
+ for (const key in record)
94
+ record[key].reset(v ? v[key] : undefined);
95
+ });
96
+ };
97
+ const eachChild = (fn) => batch(() => untrack(children).forEach(fn));
98
+ // Resolve an absolute (root-relative) dotted path to a leaf control's reactive value.
99
+ const ctxGet = (path) => {
100
+ const [head, ...rest] = path.split('.');
101
+ const record = controlsSig();
102
+ const child = record[head];
103
+ if (!child)
104
+ return undefined;
105
+ if (rest.length === 0)
106
+ return child.value();
107
+ return child._ctxGet(rest.join('.'));
108
+ };
109
+ self = {
110
+ kind: 'group',
111
+ get controls() {
112
+ return untrack(controlsSig);
113
+ },
114
+ value,
115
+ initialValue,
116
+ errors,
117
+ error: createMemo(() => errors()[0]),
118
+ valid,
119
+ invalid: createMemo(() => !valid()),
120
+ pending,
121
+ touched,
122
+ untouched: createMemo(() => !touched()),
123
+ dirty,
124
+ pristine: createMemo(() => !dirty()),
125
+ disabled,
126
+ enabled: createMemo(() => !disabled()),
127
+ submitCount,
128
+ get: (key) => untrack(controlsSig)[key],
129
+ addControl: (key, control) => {
130
+ control._setParent(self, null);
131
+ setControls((prev) => ({ ...prev, [key]: control }));
132
+ },
133
+ removeControl: (key) => setControls((prev) => {
134
+ const next = { ...prev };
135
+ delete next[key];
136
+ return next;
137
+ }),
138
+ setValue,
139
+ patch,
140
+ reset,
141
+ markTouched: (t = true) => eachChild((c) => c.markTouched(t)),
142
+ markDirty: (d = true) => eachChild((c) => c.markDirty(d)),
143
+ setDisabled: (d) => {
144
+ setDisabledSig(d);
145
+ eachChild((c) => c.setDisabled(d));
146
+ },
147
+ validate: async () => {
148
+ const results = await Promise.all([
149
+ ...untrack(children).map((c) => c.validate()),
150
+ ]);
151
+ return results.every(Boolean) && untrack(valid);
152
+ },
153
+ dispose: () => eachChild((c) => c.dispose()),
154
+ _setParent: (p) => {
155
+ parent = p;
156
+ },
157
+ _root: () => (parent ? parent._root() : self),
158
+ _ctxGet: (path) => parent ? parent._ctxGet(path) : ctxGet(path),
159
+ _bumpSubmit: () => {
160
+ setSubmitCount((n) => n + 1);
161
+ eachChild((c) => c._bumpSubmit(submitCount));
162
+ },
163
+ };
164
+ wire(untrack(controlsSig));
165
+ return self;
166
+ }
167
+ /** Root form: a group plus submission state + `submit()`. */
168
+ export function createForm(controls, options = {}) {
169
+ const group = createGroup(controls, options);
170
+ const [submitting, setSubmitting] = createSignal(false);
171
+ const [submitted, setSubmitted] = createSignal(false);
172
+ const submit = async (onValid) => {
173
+ setSubmitted(true);
174
+ group.markTouched(true);
175
+ group._bumpSubmit(group.submitCount);
176
+ const ok = await group.validate();
177
+ if (!ok)
178
+ return false;
179
+ setSubmitting(true);
180
+ try {
181
+ await onValid(untrack(group.value));
182
+ return true;
183
+ }
184
+ finally {
185
+ setSubmitting(false);
186
+ }
187
+ };
188
+ return Object.assign(group, { submitting, submitted, submit });
189
+ }
@@ -0,0 +1,14 @@
1
+ /**
2
+ * @fluixi/forms-core — reactive forms for fine-grained signal frameworks.
3
+ *
4
+ * Primitives:
5
+ * createField — a single control (value + validation + touched/dirty/async)
6
+ * createGroup — a nested record of controls (aggregate state)
7
+ * createForm — a root group + submission
8
+ * createFormArray — a dynamic, keyed list of controls
9
+ */
10
+ export { createField } from './field.js';
11
+ export { createGroup, createForm } from './group.js';
12
+ export { createFormArray, keyOf } from './array.js';
13
+ export * from './validators.js';
14
+ export type { Accessor, ValidationError, ValidatorContext, Validator, AsyncValidator, UpdateOptions, ControlKind, Control, AnyControl, FieldOptions, FieldControl, ControlsRecord, GroupValue, GroupOptions, GroupControl, ArrayOptions, ArrayControl, FormControl, PartialDeep, Path, } from './types.js';
package/dist/index.js ADDED
@@ -0,0 +1,13 @@
1
+ /**
2
+ * @fluixi/forms-core — reactive forms for fine-grained signal frameworks.
3
+ *
4
+ * Primitives:
5
+ * createField — a single control (value + validation + touched/dirty/async)
6
+ * createGroup — a nested record of controls (aggregate state)
7
+ * createForm — a root group + submission
8
+ * createFormArray — a dynamic, keyed list of controls
9
+ */
10
+ export { createField } from './field.js';
11
+ export { createGroup, createForm } from './group.js';
12
+ export { createFormArray, keyOf } from './array.js';
13
+ export * from './validators.js';
@@ -0,0 +1,159 @@
1
+ /**
2
+ * @fluixi/forms-core — public types.
3
+ *
4
+ * The model is signal-native: every reactive read is an `Accessor<T>` (a zero-arg getter
5
+ * that subscribes the caller fine-grainedly), never a snapshot object. Reading
6
+ * `field.valid()` subscribes ONLY to that field's validity memo, so an unrelated field
7
+ * changing never re-runs your computation.
8
+ */
9
+ import type { Accessor } from '@fluixi/reactive/signal';
10
+ export type { Accessor };
11
+ /** A single validation failure. `type` is a stable machine key; `message` is for humans. */
12
+ export interface ValidationError {
13
+ type: string;
14
+ message?: string;
15
+ /** validator-specific payload (e.g. `{ requiredLength: 5, actualLength: 3 }`). */
16
+ meta?: Record<string, unknown>;
17
+ }
18
+ /** Context passed to validators — lets a validator read sibling fields, the root, etc. */
19
+ export interface ValidatorContext {
20
+ /** The control being validated. */
21
+ control: AnyControl;
22
+ /** Walk up to a named ancestor value (e.g. the password for a confirm-password check). */
23
+ get<T = unknown>(path: string): T | undefined;
24
+ /** The root form control. */
25
+ root: AnyControl;
26
+ }
27
+ /** Synchronous validator: pure, returns an error or `null`. Runs inside a memo. */
28
+ export type Validator<T = unknown> = (value: T, ctx: ValidatorContext) => ValidationError | null;
29
+ /**
30
+ * Async validator: returns a Promise of an error or `null`. Runs debounced, off the sync
31
+ * path, and toggles `pending`. `signal` aborts a stale run when the value changes again.
32
+ */
33
+ export type AsyncValidator<T = unknown> = (value: T, ctx: ValidatorContext, signal: AbortSignal) => Promise<ValidationError | null>;
34
+ export type UpdateOptions = {
35
+ /** Skip marking the control dirty (e.g. programmatic patch). Default false. */
36
+ pristine?: boolean;
37
+ /** Skip running validators for this update (rare). Default false. */
38
+ novalidate?: boolean;
39
+ /** Don't propagate to dependents/parents this tick. Default false. */
40
+ silent?: boolean;
41
+ };
42
+ export type ControlKind = 'field' | 'group' | 'array';
43
+ /** State common to every control kind (field / group / array). */
44
+ export interface ControlState<T> {
45
+ readonly kind: ControlKind;
46
+ /** Current value (deep for groups/arrays). */
47
+ value: Accessor<T>;
48
+ /** The value the control was constructed/last-reset with. */
49
+ initialValue: Accessor<T>;
50
+ /** All errors for this control (own + async; groups/arrays aggregate descendants). */
51
+ errors: Accessor<ValidationError[]>;
52
+ /** First error, or undefined. */
53
+ error: Accessor<ValidationError | undefined>;
54
+ valid: Accessor<boolean>;
55
+ invalid: Accessor<boolean>;
56
+ /** An async validator is currently running somewhere in this control's subtree. */
57
+ pending: Accessor<boolean>;
58
+ touched: Accessor<boolean>;
59
+ untouched: Accessor<boolean>;
60
+ /** value !== initialValue (by the configured equality). */
61
+ dirty: Accessor<boolean>;
62
+ pristine: Accessor<boolean>;
63
+ disabled: Accessor<boolean>;
64
+ enabled: Accessor<boolean>;
65
+ /** How many times the enclosing form was submitted (propagated from the root). */
66
+ submitCount: Accessor<number>;
67
+ }
68
+ /** Mutations + lifecycle common to every control. */
69
+ export interface ControlApi<T> {
70
+ setValue(value: T, opts?: UpdateOptions): void;
71
+ /** Shallow/partial update — merges for groups, replaces for fields. */
72
+ patch(value: PartialDeep<T>, opts?: UpdateOptions): void;
73
+ /** Reset to `value` (or the initial value) and clear touched/dirty. */
74
+ reset(value?: T): void;
75
+ markTouched(touched?: boolean): void;
76
+ markDirty(dirty?: boolean): void;
77
+ setDisabled(disabled: boolean): void;
78
+ /** Force-run sync + async validators now; resolves to the resulting validity. */
79
+ validate(): Promise<boolean>;
80
+ /** Tear down effects/subscriptions (called automatically when owned by a reactive root). */
81
+ dispose(): void;
82
+ }
83
+ export type Control<T> = ControlState<T> & ControlApi<T>;
84
+ export type AnyControl = Control<any>;
85
+ export interface FieldOptions<T> {
86
+ validators?: Validator<T>[];
87
+ asyncValidators?: AsyncValidator<T>[];
88
+ /** Debounce (ms) before async validators run. Default 250. */
89
+ debounce?: number;
90
+ disabled?: boolean;
91
+ /** Equality used for dirty tracking. Default `Object.is`. */
92
+ equals?: (a: T, b: T) => boolean;
93
+ }
94
+ export interface FieldControl<T> extends Control<T> {
95
+ readonly kind: 'field';
96
+ }
97
+ /** A map of child controls. */
98
+ export type ControlsRecord = Record<string, AnyControl>;
99
+ /** Infer the aggregated value type of a controls record. */
100
+ export type GroupValue<C extends ControlsRecord> = {
101
+ [K in keyof C]: C[K] extends Control<infer V> ? V : never;
102
+ };
103
+ export interface GroupOptions<C extends ControlsRecord> {
104
+ validators?: Validator<GroupValue<C>>[];
105
+ asyncValidators?: AsyncValidator<GroupValue<C>>[];
106
+ disabled?: boolean;
107
+ }
108
+ export interface GroupControl<C extends ControlsRecord> extends Control<GroupValue<C>> {
109
+ readonly kind: 'group';
110
+ readonly controls: C;
111
+ /** Typed access to a child by key. */
112
+ get<K extends keyof C>(key: K): C[K];
113
+ /** Add a control at runtime (dynamic forms). */
114
+ addControl<K extends string, V>(key: K, control: Control<V>): void;
115
+ /** Remove a control at runtime. */
116
+ removeControl(key: keyof C): void;
117
+ }
118
+ export interface ArrayOptions<T> {
119
+ validators?: Validator<T[]>[];
120
+ asyncValidators?: AsyncValidator<T[]>[];
121
+ disabled?: boolean;
122
+ }
123
+ export interface ArrayControl<TItem, TCtrl extends Control<TItem> = Control<TItem>> extends Control<TItem[]> {
124
+ readonly kind: 'array';
125
+ /** Reactive list of child controls (keyed by stable identity). */
126
+ controls: Accessor<TCtrl[]>;
127
+ length: Accessor<number>;
128
+ at(index: number): TCtrl | undefined;
129
+ push(control: TCtrl): void;
130
+ insert(index: number, control: TCtrl): void;
131
+ removeAt(index: number): void;
132
+ move(from: number, to: number): void;
133
+ clear(): void;
134
+ }
135
+ export interface FormControl<C extends ControlsRecord> extends GroupControl<C> {
136
+ /** Submission state. */
137
+ submitting: Accessor<boolean>;
138
+ submitted: Accessor<boolean>;
139
+ /**
140
+ * Run validation (incl. async), and if valid call `onValid(values)`. Marks all fields
141
+ * touched, increments submitCount, and tracks `submitting`.
142
+ */
143
+ submit(onValid: (values: GroupValue<C>) => unknown | Promise<unknown>): Promise<boolean>;
144
+ }
145
+ /**
146
+ * Widen a fresh literal to its primitive base, so `createField('')` is `FieldControl<string>`
147
+ * (not `FieldControl<''>`). TS normally widens a bare type-parameter inferred from a literal,
148
+ * but `T` also appears contravariantly in `FieldOptions<T>` (the validator param), which
149
+ * suppresses that widening — so we widen explicitly at the boundary. Non-primitives pass
150
+ * through unchanged; pass an explicit type arg to keep a literal union (e.g. a select).
151
+ */
152
+ export type Widen<T> = T extends string ? string : T extends number ? number : T extends boolean ? boolean : T extends bigint ? bigint : T;
153
+ export type PartialDeep<T> = T extends (infer U)[] ? PartialDeep<U>[] : T extends object ? {
154
+ [K in keyof T]?: PartialDeep<T[K]>;
155
+ } : T;
156
+ /** Dotted/bracketed paths into a value (typed). */
157
+ export type Path<T> = T extends object ? {
158
+ [K in keyof T & (string | number)]: `${K}` | (T[K] extends object ? `${K}.${Path<T[K]>}` : never);
159
+ }[keyof T & (string | number)] : never;
package/dist/types.js ADDED
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,27 @@
1
+ /**
2
+ * Built-in validators + composition. Validators are pure `(value, ctx) => error | null`.
3
+ * They run inside a memo, so they're lazy (only re-run when their inputs change) and
4
+ * fine-grained (reading a sibling via `ctx.get(path)` subscribes to just that sibling).
5
+ */
6
+ import type { Validator, AsyncValidator, ValidationError } from './types.js';
7
+ export declare const required: (message?: string) => Validator;
8
+ export declare const requiredTrue: (message?: string) => Validator<boolean>;
9
+ export declare const minLength: (min: number, message?: string) => Validator<string | unknown[]>;
10
+ export declare const maxLength: (max: number, message?: string) => Validator<string | unknown[]>;
11
+ export declare const min: (m: number, message?: string) => Validator<number>;
12
+ export declare const max: (m: number, message?: string) => Validator<number>;
13
+ export declare const email: (message?: string) => Validator<string>;
14
+ export declare const pattern: (re: RegExp, message?: string) => Validator<string>;
15
+ /** Cross-field: the value must equal another field's value (e.g. confirm password). */
16
+ export declare const sameAs: (path: string, message?: string) => Validator;
17
+ /** Run a validator only when `predicate` (typically reads sibling fields) is true. */
18
+ export declare const when: <T>(predicate: (ctx: Parameters<Validator<T>>[1]) => boolean, validator: Validator<T>) => Validator<T>;
19
+ /** Compose validators into one — returns the FIRST failure (short-circuits). */
20
+ export declare const compose: <T>(...validators: Validator<T>[]) => Validator<T>;
21
+ /** Run all validators and collect EVERY failure (no short-circuit). */
22
+ export declare const all: <T>(...validators: Validator<T>[]) => (value: T, ctx: Parameters<Validator<T>>[1]) => ValidationError[];
23
+ /**
24
+ * Wrap a plain async check (returns boolean) as an AsyncValidator. The `signal` aborts a
25
+ * stale run; pass it to your fetch.
26
+ */
27
+ export declare const asyncCheck: <T>(check: (value: T, signal: AbortSignal) => Promise<boolean>, type: string, message: string) => AsyncValidator<T>;
@@ -0,0 +1,46 @@
1
+ const err = (type, message, meta) => ({
2
+ type,
3
+ message,
4
+ meta,
5
+ });
6
+ const isEmpty = (v) => v == null || v === '' || (Array.isArray(v) && v.length === 0);
7
+ export const required = (message = 'This field is required') => (value) => (isEmpty(value) ? err('required', message) : null);
8
+ export const requiredTrue = (message = 'Must be checked') => (value) => (value === true ? null : err('requiredTrue', message));
9
+ export const minLength = (min, message) => (value) => value != null && value.length < min
10
+ ? err('minLength', message ?? `Must be at least ${min} characters`, {
11
+ requiredLength: min,
12
+ actualLength: value.length,
13
+ })
14
+ : null;
15
+ export const maxLength = (max, message) => (value) => value != null && value.length > max
16
+ ? err('maxLength', message ?? `Must be at most ${max} characters`, {
17
+ requiredLength: max,
18
+ actualLength: value.length,
19
+ })
20
+ : null;
21
+ export const min = (m, message) => (value) => (value != null && value < m ? err('min', message ?? `Must be ≥ ${m}`, { min: m }) : null);
22
+ export const max = (m, message) => (value) => (value != null && value > m ? err('max', message ?? `Must be ≤ ${m}`, { max: m }) : null);
23
+ const EMAIL_RE = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
24
+ export const email = (message = 'Invalid email address') => (value) => (isEmpty(value) || EMAIL_RE.test(value) ? null : err('email', message));
25
+ export const pattern = (re, message = 'Invalid format') => (value) => (isEmpty(value) || re.test(value) ? null : err('pattern', message, { pattern: re.source }));
26
+ /** Cross-field: the value must equal another field's value (e.g. confirm password). */
27
+ export const sameAs = (path, message = 'Values must match') => (value, ctx) => (value === ctx.get(path) ? null : err('sameAs', message, { path }));
28
+ /** Run a validator only when `predicate` (typically reads sibling fields) is true. */
29
+ export const when = (predicate, validator) => (value, ctx) => (predicate(ctx) ? validator(value, ctx) : null);
30
+ /** Compose validators into one — returns the FIRST failure (short-circuits). */
31
+ export const compose = (...validators) => (value, ctx) => {
32
+ for (const v of validators) {
33
+ const e = v(value, ctx);
34
+ if (e)
35
+ return e;
36
+ }
37
+ return null;
38
+ };
39
+ /** Run all validators and collect EVERY failure (no short-circuit). */
40
+ export const all = (...validators) => (value, ctx) => validators.map((v) => v(value, ctx)).filter((e) => e != null);
41
+ // ── async helpers ──────────────────────────────────────────────────────────────
42
+ /**
43
+ * Wrap a plain async check (returns boolean) as an AsyncValidator. The `signal` aborts a
44
+ * stale run; pass it to your fetch.
45
+ */
46
+ export const asyncCheck = (check, type, message) => async (value, _ctx, signal) => ((await check(value, signal)) ? null : err(type, message));
package/package.json ADDED
@@ -0,0 +1,39 @@
1
+ {
2
+ "name": "@fluixi/forms-core",
3
+ "version": "0.2.0",
4
+ "license": "MIT",
5
+ "description": "Reactive forms core (FormControl/FormGroup/FormArray) for fine-grained signal frameworks.",
6
+ "type": "module",
7
+ "main": "./dist/index.js",
8
+ "types": "./dist/index.d.ts",
9
+ "exports": {
10
+ ".": {
11
+ "types": "./dist/index.d.ts",
12
+ "import": "./dist/index.js"
13
+ }
14
+ },
15
+ "files": [
16
+ "dist",
17
+ "LICENSE"
18
+ ],
19
+ "dependencies": {},
20
+ "publishConfig": {
21
+ "registry": "https://registry.npmjs.org/",
22
+ "access": "public"
23
+ },
24
+ "repository": {
25
+ "type": "git",
26
+ "url": "git+https://github.com/fluixi/forms.git",
27
+ "directory": "packages/forms-core"
28
+ },
29
+ "peerDependencies": {
30
+ "@fluixi/reactive": "*"
31
+ },
32
+ "devDependencies": {
33
+ "@fluixi/reactive": "alpha"
34
+ },
35
+ "scripts": {
36
+ "build": "tsc -p tsconfig.json",
37
+ "test": "vitest run --passWithNoTests"
38
+ }
39
+ }