@opentf/afw-form 0.0.0-stage → 1.27.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/CHANGELOG.md +136 -0
- package/README.md +221 -2
- package/index.js +350 -0
- package/package.json +21 -3
- package/tests/Basic.test.js +36 -0
- package/tests/BasicForm.jsx +29 -0
- package/tests/Component.test.js +44 -0
- package/tests/DynamicArrayForm.jsx +32 -0
- package/tests/DynamicArrays.test.js +32 -0
- package/tests/DynamicListForm.jsx +20 -0
- package/tests/Logic.test.js +153 -0
- package/tests/NestedFields.test.js +27 -0
- package/tests/NestedForm.jsx +32 -0
- package/tests/ProfileForm.jsx +34 -0
- package/tests/Reactivity.test.js +25 -0
- package/tests/RegisterMetadata.test.js +83 -0
- package/tests/State.test.js +93 -0
- package/tests/StateComponent.test.js +57 -0
- package/tests/StateForm.jsx +29 -0
- package/tests/ValidationModes.test.js +84 -0
- package/tests/dom.js +93 -0
package/CHANGELOG.md
ADDED
|
@@ -0,0 +1,136 @@
|
|
|
1
|
+
@opentf/afw
|
|
2
|
+
|
|
3
|
+
## [Unreleased]
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
### Changed
|
|
7
|
+
|
|
8
|
+
- Project renamed **OTF Web → AFW — App Framework for the Web**. All package,
|
|
9
|
+
binary and crate names move with it (no compatibility aliases): `@opentf/web*` →
|
|
10
|
+
`@opentf/afw*`, `esdev-plugin-web` → `esdev-plugin-afw`, the `otfw`/`otfwc`
|
|
11
|
+
binaries → `afw`/`afwc` (crate `otfw_cli` → `afw_cli`), `web.opentechf.org` →
|
|
12
|
+
`afw.opentechf.org`, and the repo → `Open-Tech-Foundation/afw`.
|
|
13
|
+
- Test suite titles say "AFW Forms Library" instead of "Web App Framework".
|
|
14
|
+
|
|
15
|
+
## [1.27.0] - 2026-10-07
|
|
16
|
+
|
|
17
|
+
_Dependency updates._
|
|
18
|
+
|
|
19
|
+
## [1.26.0] - 2026-10-06
|
|
20
|
+
|
|
21
|
+
_Dependency updates._
|
|
22
|
+
|
|
23
|
+
## [1.25.0] - 2026-10-03
|
|
24
|
+
|
|
25
|
+
_Dependency updates._
|
|
26
|
+
|
|
27
|
+
## [1.24.0] - 2026-10-01
|
|
28
|
+
|
|
29
|
+
### Changed
|
|
30
|
+
|
|
31
|
+
- Use stable `@opentf/std` `^0.19.0` instead of `^1.0.0-beta.2`.
|
|
32
|
+
- Track the workspace framework peer dependency and migrate form and component
|
|
33
|
+
tests to esdev, replacing the Bun and happy-dom configuration.
|
|
34
|
+
|
|
35
|
+
## [1.23.0] - 2026-08-12
|
|
36
|
+
|
|
37
|
+
_Dependency updates._
|
|
38
|
+
|
|
39
|
+
## [1.22.0] - 2026-07-31
|
|
40
|
+
|
|
41
|
+
_Dependency updates._
|
|
42
|
+
|
|
43
|
+
## [1.21.0] - 2026-07-30
|
|
44
|
+
|
|
45
|
+
_Dependency updates._
|
|
46
|
+
|
|
47
|
+
## [1.20.0] - 2026-07-29
|
|
48
|
+
|
|
49
|
+
_Dependency updates._
|
|
50
|
+
|
|
51
|
+
## [1.19.0] - 2026-07-25
|
|
52
|
+
|
|
53
|
+
_Dependency updates._
|
|
54
|
+
|
|
55
|
+
## [1.18.0] - 2026-07-25
|
|
56
|
+
|
|
57
|
+
_Dependency updates._
|
|
58
|
+
|
|
59
|
+
## [1.17.0] - 2026-07-25
|
|
60
|
+
|
|
61
|
+
_Dependency updates._
|
|
62
|
+
|
|
63
|
+
## [1.16.0] - 2026-07-24
|
|
64
|
+
|
|
65
|
+
_Dependency updates._
|
|
66
|
+
|
|
67
|
+
## [1.15.0] - 2026-07-18
|
|
68
|
+
|
|
69
|
+
_Dependency updates._
|
|
70
|
+
|
|
71
|
+
## [1.14.0] - 2026-07-18
|
|
72
|
+
|
|
73
|
+
_Dependency updates._
|
|
74
|
+
|
|
75
|
+
## [1.13.0] - 2026-07-08
|
|
76
|
+
|
|
77
|
+
_Dependency updates._
|
|
78
|
+
|
|
79
|
+
## [1.12.0] - 2026-07-08
|
|
80
|
+
|
|
81
|
+
_Dependency updates._
|
|
82
|
+
|
|
83
|
+
## [1.11.0] - 2026-07-07
|
|
84
|
+
|
|
85
|
+
_Dependency updates._
|
|
86
|
+
|
|
87
|
+
## [1.10.0] - 2026-07-07
|
|
88
|
+
|
|
89
|
+
_Dependency updates._
|
|
90
|
+
|
|
91
|
+
## [1.9.0] - 2026-07-07
|
|
92
|
+
|
|
93
|
+
_Dependency updates._
|
|
94
|
+
|
|
95
|
+
## [1.8.0] - 2026-07-07
|
|
96
|
+
|
|
97
|
+
_Dependency updates._
|
|
98
|
+
|
|
99
|
+
## [1.7.0] - 2026-07-06
|
|
100
|
+
|
|
101
|
+
_Dependency updates._
|
|
102
|
+
|
|
103
|
+
## [1.6.0] - 2026-07-06
|
|
104
|
+
|
|
105
|
+
_Dependency updates._
|
|
106
|
+
|
|
107
|
+
## [1.5.0] - 2026-07-05
|
|
108
|
+
|
|
109
|
+
_Dependency updates._
|
|
110
|
+
|
|
111
|
+
## [1.4.0] - 2026-07-05
|
|
112
|
+
|
|
113
|
+
_Dependency updates._
|
|
114
|
+
|
|
115
|
+
## [1.3.0] - 2026-07-05
|
|
116
|
+
|
|
117
|
+
_Dependency updates._
|
|
118
|
+
|
|
119
|
+
## [1.2.0] - 2026-07-03
|
|
120
|
+
|
|
121
|
+
_Dependency updates._
|
|
122
|
+
|
|
123
|
+
## [1.1.0] - 2026-07-01
|
|
124
|
+
|
|
125
|
+
- **Engine Rebuild:** Rebuilt the form engine on the `reactive()` store primitive.
|
|
126
|
+
- **Dependency Fix:** Normalized the peer dependency range for `@opentf/web` to `*` to improve compatibility.
|
|
127
|
+
- **Documentation:** Updated the forms documentation to reflect the new `reactive()` engine, including working examples.
|
|
128
|
+
- **Testing:** Restructured the test suite to adopt a fixture-per-component convention.
|
|
129
|
+
|
|
130
|
+
|
|
131
|
+
## 1.0.0
|
|
132
|
+
|
|
133
|
+
### Patch Changes
|
|
134
|
+
|
|
135
|
+
- Updated dependencies [bb1c71b]
|
|
136
|
+
- @opentf/web@0.5.0
|
package/README.md
CHANGED
|
@@ -1,3 +1,222 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @opentf/afw-form
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
A high-performance, **path-based reactive forms engine** for [AFW](https://github.com/Open-Tech-Foundation/afw).
|
|
4
|
+
|
|
5
|
+
Fields bind directly to a `reactive()` store, so updates are surgical — typing in
|
|
6
|
+
one field only re-runs the effects that read that field. No virtual DOM, no
|
|
7
|
+
re-render, no memoization.
|
|
8
|
+
|
|
9
|
+
## Features
|
|
10
|
+
|
|
11
|
+
- 🌿 **Reactive values** — read `form.values.user.name` / `form.errors.email`
|
|
12
|
+
straight in your JSX; they update fine-grained.
|
|
13
|
+
- 🌲 **Nested state & arrays** — address any depth by dot-path (`"user.profile.firstName"`, `"tags.0"`).
|
|
14
|
+
- 🛡️ **Validation** — a plain function or a schema library (Zod, Valibot, …), with `onChange` / `onBlur` / `onSubmit` modes.
|
|
15
|
+
- 🚀 **Fine-grained** — per-keystroke work is `O(path)`, not `O(fields)`.
|
|
16
|
+
- 🛠️ **`register` pattern** — spread one call onto an input to wire it up.
|
|
17
|
+
|
|
18
|
+
## Installation
|
|
19
|
+
|
|
20
|
+
```bash
|
|
21
|
+
npm install @opentf/afw-form
|
|
22
|
+
# or
|
|
23
|
+
pnpm add @opentf/afw-form
|
|
24
|
+
```
|
|
25
|
+
|
|
26
|
+
## Basic usage
|
|
27
|
+
|
|
28
|
+
`createForm` returns a stable form object. Spread `register(path)` onto an input
|
|
29
|
+
to bind it, and wrap your submit handler with `handleSubmit`.
|
|
30
|
+
|
|
31
|
+
```jsx
|
|
32
|
+
import { createForm } from "@opentf/afw-form";
|
|
33
|
+
|
|
34
|
+
export function SignupForm() {
|
|
35
|
+
const form = createForm({
|
|
36
|
+
initialValues: { username: "", email: "" },
|
|
37
|
+
validate: (values) => {
|
|
38
|
+
const errors = {};
|
|
39
|
+
if (!values.username) errors.username = "Username required";
|
|
40
|
+
if (!values.email.includes("@")) errors.email = "Invalid email";
|
|
41
|
+
return errors;
|
|
42
|
+
},
|
|
43
|
+
});
|
|
44
|
+
|
|
45
|
+
const onSubmit = (values) => console.log("Submitted:", values);
|
|
46
|
+
|
|
47
|
+
return (
|
|
48
|
+
<form onsubmit={form.handleSubmit(onSubmit)}>
|
|
49
|
+
<label for="username">Username</label>
|
|
50
|
+
<input {...form.register("username")} id="username" />
|
|
51
|
+
{form.errors.username && <span class="error">{form.errors.username}</span>}
|
|
52
|
+
|
|
53
|
+
<label for="email">Email</label>
|
|
54
|
+
<input {...form.register("email")} id="email" />
|
|
55
|
+
{form.errors.email && <span class="error">{form.errors.email}</span>}
|
|
56
|
+
|
|
57
|
+
<button type="submit">Sign up</button>
|
|
58
|
+
</form>
|
|
59
|
+
);
|
|
60
|
+
}
|
|
61
|
+
```
|
|
62
|
+
|
|
63
|
+
`register(path)` returns everything a field needs — `name`, `value`, `checked`
|
|
64
|
+
(for checkboxes/radios), `error`, `isTouched`, `oninput`, and `onblur` — so a
|
|
65
|
+
controlled input is one line.
|
|
66
|
+
|
|
67
|
+
## Reactive values
|
|
68
|
+
|
|
69
|
+
`form.values`, `form.errors`, `form.touched`, and `form.changed` are reactive
|
|
70
|
+
stores — read them directly in your template and only the nodes that read a
|
|
71
|
+
changed path update. There is no provider to thread through.
|
|
72
|
+
|
|
73
|
+
```jsx
|
|
74
|
+
<p>Hello, {form.values.username || "stranger"}</p>
|
|
75
|
+
```
|
|
76
|
+
|
|
77
|
+
## Nested state & arrays
|
|
78
|
+
|
|
79
|
+
Address objects and arrays by dot-path; arrays use the index as a segment.
|
|
80
|
+
|
|
81
|
+
```jsx
|
|
82
|
+
const form = createForm({
|
|
83
|
+
initialValues: {
|
|
84
|
+
user: {
|
|
85
|
+
profile: { firstName: "John" },
|
|
86
|
+
settings: { notifications: true },
|
|
87
|
+
},
|
|
88
|
+
},
|
|
89
|
+
});
|
|
90
|
+
|
|
91
|
+
<input {...form.register("user.profile.firstName")} />
|
|
92
|
+
<input {...form.register("user.settings.notifications")} type="checkbox" />
|
|
93
|
+
```
|
|
94
|
+
|
|
95
|
+
Read nested values and errors with ordinary property access:
|
|
96
|
+
|
|
97
|
+
```jsx
|
|
98
|
+
<p>{form.values.user.profile.firstName}</p>
|
|
99
|
+
{form.errors.user?.firstName && <span class="error">{form.errors.user.firstName}</span>}
|
|
100
|
+
```
|
|
101
|
+
|
|
102
|
+
### Dynamic arrays
|
|
103
|
+
|
|
104
|
+
The values store is a real reactive object — mutate it directly:
|
|
105
|
+
|
|
106
|
+
```jsx
|
|
107
|
+
const form = createForm({ initialValues: { skills: ["JavaScript"] } });
|
|
108
|
+
|
|
109
|
+
// Add / remove
|
|
110
|
+
const addSkill = () => form.values.skills.push("");
|
|
111
|
+
const removeSkill = (i) => form.values.skills.splice(i, 1);
|
|
112
|
+
|
|
113
|
+
// Render a row per item; editing one input never re-renders the others
|
|
114
|
+
{form.values.skills.map((skill, i) => (
|
|
115
|
+
<input {...form.register(`skills.${i}`)} />
|
|
116
|
+
))}
|
|
117
|
+
```
|
|
118
|
+
|
|
119
|
+
## Validation
|
|
120
|
+
|
|
121
|
+
A validator receives the current `values` and returns an errors object keyed by
|
|
122
|
+
field path. Use `validate` to return the errors object directly, or `validator`
|
|
123
|
+
to return `{ errors }` (handy for schema resolvers).
|
|
124
|
+
|
|
125
|
+
```jsx
|
|
126
|
+
const form = createForm({
|
|
127
|
+
mode: "onChange",
|
|
128
|
+
initialValues: { age: 0 },
|
|
129
|
+
validate: (values) => {
|
|
130
|
+
const errors = {};
|
|
131
|
+
if (values.age < 18) errors.age = "Too young";
|
|
132
|
+
return errors;
|
|
133
|
+
},
|
|
134
|
+
});
|
|
135
|
+
```
|
|
136
|
+
|
|
137
|
+
### Schema validation (Zod)
|
|
138
|
+
|
|
139
|
+
Wrap a schema in a resolver that maps issues to the path-keyed shape. The
|
|
140
|
+
resolver closes over the schema and takes the form `values`:
|
|
141
|
+
|
|
142
|
+
```jsx
|
|
143
|
+
import { z } from "zod";
|
|
144
|
+
|
|
145
|
+
const schema = z.object({
|
|
146
|
+
username: z.string().min(3, "Too short"),
|
|
147
|
+
email: z.string().email("Invalid email"),
|
|
148
|
+
});
|
|
149
|
+
|
|
150
|
+
const zodResolver = (schema) => (values) => {
|
|
151
|
+
const result = schema.safeParse(values);
|
|
152
|
+
if (result.success) return { errors: {} };
|
|
153
|
+
const errors = {};
|
|
154
|
+
for (const issue of result.error.issues) {
|
|
155
|
+
errors[issue.path.join(".")] = issue.message;
|
|
156
|
+
}
|
|
157
|
+
return { errors };
|
|
158
|
+
};
|
|
159
|
+
|
|
160
|
+
const form = createForm({
|
|
161
|
+
initialValues: { username: "", email: "" },
|
|
162
|
+
validator: zodResolver(schema),
|
|
163
|
+
});
|
|
164
|
+
```
|
|
165
|
+
|
|
166
|
+
A validator may be **async** (return a Promise); `form.isValidating` is `true`
|
|
167
|
+
while it resolves — useful for server-side uniqueness checks.
|
|
168
|
+
|
|
169
|
+
### Validation modes
|
|
170
|
+
|
|
171
|
+
| Option | Values | Default | When it validates |
|
|
172
|
+
| :--- | :--- | :--- | :--- |
|
|
173
|
+
| `mode` | `"onChange"` `"onBlur"` `"onSubmit"` | `"onBlur"` | `onChange`: every edit + on mount · `onBlur`: on blur · `onSubmit`: only on submit |
|
|
174
|
+
| `reValidateMode` | `"onChange"` `"onBlur"` | `"onChange"` | After the first error exists, when to re-validate |
|
|
175
|
+
|
|
176
|
+
```js
|
|
177
|
+
createForm({ mode: "onChange", reValidateMode: "onBlur" });
|
|
178
|
+
```
|
|
179
|
+
|
|
180
|
+
`handleSubmit` always runs the validator first and only calls your handler when
|
|
181
|
+
the form is valid, so a final check is guaranteed regardless of `mode`.
|
|
182
|
+
|
|
183
|
+
## Status flags
|
|
184
|
+
|
|
185
|
+
`createForm` exposes derived flags — read them directly (they are reactive in JSX):
|
|
186
|
+
|
|
187
|
+
| Flag | Description |
|
|
188
|
+
| :--- | :--- |
|
|
189
|
+
| `isValid` | `true` when there are no errors. |
|
|
190
|
+
| `isChanged` | `true` when values differ from `initialValues`. |
|
|
191
|
+
| `isTouched` | `true` when any field has been blurred. |
|
|
192
|
+
| `isSubmitting` | `true` while an async `onSubmit` handler is running. |
|
|
193
|
+
| `isValidating` | `true` while an async validator is running. |
|
|
194
|
+
| `isSubmitted` | `true` after a successful submit. |
|
|
195
|
+
| `submitCount` | Number of submit attempts. |
|
|
196
|
+
|
|
197
|
+
```jsx
|
|
198
|
+
<button type="submit" disabled={form.isSubmitting || !form.isValid}>
|
|
199
|
+
{form.isSubmitting ? "Saving…" : "Save"}
|
|
200
|
+
</button>
|
|
201
|
+
```
|
|
202
|
+
|
|
203
|
+
Per-field `touched` and `changed` state is on the matching store:
|
|
204
|
+
`form.touched.email`, `form.changed.user`.
|
|
205
|
+
|
|
206
|
+
## Resetting
|
|
207
|
+
|
|
208
|
+
`reset()` restores `initialValues` and clears status. Pass an object to reset to
|
|
209
|
+
new baseline values (which become the new "initial" for `isChanged`).
|
|
210
|
+
|
|
211
|
+
```jsx
|
|
212
|
+
<button type="button" onclick={() => form.reset()}>Reset</button>
|
|
213
|
+
```
|
|
214
|
+
|
|
215
|
+
```js
|
|
216
|
+
form.reset(); // back to initial
|
|
217
|
+
form.reset({ username: "" }); // new baseline
|
|
218
|
+
```
|
|
219
|
+
|
|
220
|
+
## License
|
|
221
|
+
|
|
222
|
+
MIT © [Open Tech Foundation](https://github.com/Open-Tech-Foundation)
|
package/index.js
ADDED
|
@@ -0,0 +1,350 @@
|
|
|
1
|
+
import {
|
|
2
|
+
signal,
|
|
3
|
+
computed,
|
|
4
|
+
effect,
|
|
5
|
+
batch,
|
|
6
|
+
untracked,
|
|
7
|
+
getCurrentInstance,
|
|
8
|
+
reactive,
|
|
9
|
+
toRawValue,
|
|
10
|
+
snapshot,
|
|
11
|
+
} from "@opentf/afw";
|
|
12
|
+
|
|
13
|
+
export { signal, computed, batch, effect, untracked, reactive, getCurrentInstance };
|
|
14
|
+
|
|
15
|
+
import { clone, isEql } from "@opentf/std";
|
|
16
|
+
|
|
17
|
+
/**
|
|
18
|
+
* Path-based reactive forms engine for AFW.
|
|
19
|
+
*
|
|
20
|
+
* The form's values/errors/touched/changed trees are `reactive()` stores
|
|
21
|
+
* (@opentf/afw), so `form.values.user.name` and `form.errors.email` are read
|
|
22
|
+
* directly in JSX with fine-grained reactivity — no provider object, no bespoke
|
|
23
|
+
* proxy. The engine layers field registration, validation modes, and submit
|
|
24
|
+
* orchestration on top.
|
|
25
|
+
*/
|
|
26
|
+
|
|
27
|
+
const INST_FORMS_REGISTRY = new WeakMap();
|
|
28
|
+
|
|
29
|
+
export function createForm(options = {}) {
|
|
30
|
+
// Scope the form to the mounting component so re-entrant `createForm` calls
|
|
31
|
+
// (e.g. the component body running again) return the same instance. Outside a
|
|
32
|
+
// component (module scope, tests) there is no instance — just build one.
|
|
33
|
+
const inst = getCurrentInstance();
|
|
34
|
+
if (!inst) return _createForm(options);
|
|
35
|
+
|
|
36
|
+
let forms = INST_FORMS_REGISTRY.get(inst);
|
|
37
|
+
if (!forms) INST_FORMS_REGISTRY.set(inst, (forms = new Map()));
|
|
38
|
+
|
|
39
|
+
const key = options.key || JSON.stringify({ initialValues: options.initialValues });
|
|
40
|
+
if (forms.has(key)) {
|
|
41
|
+
const form = forms.get(key);
|
|
42
|
+
form._updateConfig?.(options.mode, options.reValidateMode);
|
|
43
|
+
return form;
|
|
44
|
+
}
|
|
45
|
+
const form = _createForm(options);
|
|
46
|
+
forms.set(key, form);
|
|
47
|
+
return form;
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
function _createForm(options = {}) {
|
|
51
|
+
let initialValues = clone(options.initialValues || {});
|
|
52
|
+
|
|
53
|
+
const valuesStore = reactive(clone(initialValues));
|
|
54
|
+
const errorsStore = reactive({});
|
|
55
|
+
// touched mirrors the value tree with `false` leaves, so a field reads `false`
|
|
56
|
+
// (not undefined) before it is ever blurred. `changed` is filled by the
|
|
57
|
+
// creation effect below (top-level booleans vs. initial values).
|
|
58
|
+
const touchedStore = reactive(mirrorLeaves(initialValues, false));
|
|
59
|
+
const changedStore = reactive({});
|
|
60
|
+
|
|
61
|
+
const modeSig = signal(options.mode);
|
|
62
|
+
const reValidateModeSig = signal(options.reValidateMode);
|
|
63
|
+
const isSubmittingSig = signal(false);
|
|
64
|
+
const isValidatingSig = signal(false);
|
|
65
|
+
const isSubmittedSig = signal(false);
|
|
66
|
+
const submitCountSig = signal(0);
|
|
67
|
+
|
|
68
|
+
const normMode = (m) =>
|
|
69
|
+
((m && typeof m === "object" && "value" in m ? m.value : m) || "onBlur");
|
|
70
|
+
const normReValidate = (m) =>
|
|
71
|
+
((m && typeof m === "object" && "value" in m ? m.value : m) || "onChange");
|
|
72
|
+
|
|
73
|
+
const activeValidator = options.validator || options.validate;
|
|
74
|
+
|
|
75
|
+
// --- path helpers: walk the reactive store so reads subscribe & writes notify
|
|
76
|
+
function readPath(store, path) {
|
|
77
|
+
if (!path) return store;
|
|
78
|
+
let node = store;
|
|
79
|
+
for (const p of path.split(".")) {
|
|
80
|
+
if (node == null) return undefined;
|
|
81
|
+
node = node[p];
|
|
82
|
+
}
|
|
83
|
+
return node;
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
function writePath(store, path, value) {
|
|
87
|
+
const parts = path.split(".");
|
|
88
|
+
let node = store;
|
|
89
|
+
for (let i = 0; i < parts.length - 1; i++) {
|
|
90
|
+
const p = parts[i];
|
|
91
|
+
let next = node[p];
|
|
92
|
+
if (next == null || typeof next !== "object") {
|
|
93
|
+
node[p] = {};
|
|
94
|
+
next = node[p];
|
|
95
|
+
}
|
|
96
|
+
node = next;
|
|
97
|
+
}
|
|
98
|
+
node[parts[parts.length - 1]] = value;
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
function deletePath(store, path) {
|
|
102
|
+
const parts = path.split(".");
|
|
103
|
+
let node = store;
|
|
104
|
+
for (let i = 0; i < parts.length - 1; i++) {
|
|
105
|
+
node = node[parts[i]];
|
|
106
|
+
if (node == null || typeof node !== "object") return;
|
|
107
|
+
}
|
|
108
|
+
delete node[parts[parts.length - 1]];
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
// Reconcile a reactive store in place to match a plain object, touching only
|
|
112
|
+
// the leaves that actually differ (fine-grained — no wholesale replace).
|
|
113
|
+
function syncStore(store, next) {
|
|
114
|
+
next = next || {};
|
|
115
|
+
const raw = toRawValue(store);
|
|
116
|
+
for (const k of Object.keys(raw)) {
|
|
117
|
+
if (!(k in next)) delete store[k];
|
|
118
|
+
}
|
|
119
|
+
for (const k of Object.keys(next)) {
|
|
120
|
+
const nv = next[k];
|
|
121
|
+
const cur = raw[k];
|
|
122
|
+
if (nv && typeof nv === "object" && cur && typeof cur === "object") {
|
|
123
|
+
syncStore(store[k], nv);
|
|
124
|
+
} else if (!isEql(cur, nv)) {
|
|
125
|
+
store[k] = nv;
|
|
126
|
+
}
|
|
127
|
+
}
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
// --- validation
|
|
131
|
+
const normalizeErrors = (r) => (r && r.errors !== undefined ? r.errors : r) || {};
|
|
132
|
+
|
|
133
|
+
function applyErrors(errorsObj, fieldPath) {
|
|
134
|
+
if (fieldPath) {
|
|
135
|
+
const fieldErr = readRaw(errorsObj, fieldPath);
|
|
136
|
+
if (fieldErr) writePath(errorsStore, fieldPath, fieldErr);
|
|
137
|
+
else deletePath(errorsStore, fieldPath);
|
|
138
|
+
} else {
|
|
139
|
+
syncStore(errorsStore, errorsObj);
|
|
140
|
+
}
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
let validationToken = 0;
|
|
144
|
+
function runValidation(fieldPath) {
|
|
145
|
+
if (!activeValidator) return;
|
|
146
|
+
const token = ++validationToken;
|
|
147
|
+
const result = activeValidator(snapshot(valuesStore));
|
|
148
|
+
if (result instanceof Promise) {
|
|
149
|
+
isValidatingSig.value = true;
|
|
150
|
+
return result
|
|
151
|
+
.then((r) => {
|
|
152
|
+
if (token === validationToken) applyErrors(normalizeErrors(r), fieldPath);
|
|
153
|
+
})
|
|
154
|
+
.finally(() => {
|
|
155
|
+
if (token === validationToken) isValidatingSig.value = false;
|
|
156
|
+
});
|
|
157
|
+
}
|
|
158
|
+
applyErrors(normalizeErrors(result), fieldPath);
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
// --- changed tracking: per top-level key, deep-compared to initial values.
|
|
162
|
+
function recomputeChanged() {
|
|
163
|
+
const v = toRawValue(valuesStore);
|
|
164
|
+
const keys = new Set([...Object.keys(v), ...Object.keys(initialValues)]);
|
|
165
|
+
for (const k of keys) {
|
|
166
|
+
const ch = !isEql(v[k], initialValues[k]);
|
|
167
|
+
if (toRawValue(changedStore)[k] !== ch) changedStore[k] = ch;
|
|
168
|
+
}
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
// One effect observes every value change and (a) recomputes `changed`, and
|
|
172
|
+
// (b) in onChange mode, revalidates — covering inputs, direct assignment, and
|
|
173
|
+
// array mutation alike. Writes are untracked so it never depends on its own
|
|
174
|
+
// output. Validates once on creation, satisfying onChange's "validate on init".
|
|
175
|
+
effect(() => {
|
|
176
|
+
deepTrack(valuesStore);
|
|
177
|
+
const mode = normMode(modeSig.value);
|
|
178
|
+
untracked(() => {
|
|
179
|
+
recomputeChanged();
|
|
180
|
+
if (mode === "onChange") runValidation();
|
|
181
|
+
});
|
|
182
|
+
});
|
|
183
|
+
|
|
184
|
+
// --- field registration
|
|
185
|
+
function updateValue(path, val) {
|
|
186
|
+
writePath(valuesStore, path, val);
|
|
187
|
+
const mode = normMode(modeSig.peek());
|
|
188
|
+
if (mode === "onChange") return; // the effect above revalidates
|
|
189
|
+
if (hasTruthy(toRawValue(errorsStore)) && normReValidate(reValidateModeSig.peek()) === "onChange") {
|
|
190
|
+
runValidation(path);
|
|
191
|
+
}
|
|
192
|
+
}
|
|
193
|
+
|
|
194
|
+
const register = (path) => ({
|
|
195
|
+
name: path,
|
|
196
|
+
value: readPath(valuesStore, path),
|
|
197
|
+
checked: readPath(valuesStore, path),
|
|
198
|
+
error: computed(() => readPath(errorsStore, path)),
|
|
199
|
+
isTouched: computed(() => readPath(touchedStore, path) ?? false),
|
|
200
|
+
oninput: (e) => {
|
|
201
|
+
const t = e.target;
|
|
202
|
+
updateValue(path, t.type === "checkbox" ? t.checked : t.value);
|
|
203
|
+
},
|
|
204
|
+
onblur: () => {
|
|
205
|
+
writePath(touchedStore, path, true);
|
|
206
|
+
const mode = normMode(modeSig.peek());
|
|
207
|
+
if (mode === "onBlur") runValidation(path);
|
|
208
|
+
else if (
|
|
209
|
+
hasTruthy(toRawValue(errorsStore)) &&
|
|
210
|
+
normReValidate(reValidateModeSig.peek()) === "onBlur"
|
|
211
|
+
) {
|
|
212
|
+
runValidation(path);
|
|
213
|
+
}
|
|
214
|
+
},
|
|
215
|
+
});
|
|
216
|
+
|
|
217
|
+
// --- submit / reset
|
|
218
|
+
const handleSubmit = (fn) => async (e) => {
|
|
219
|
+
if (e && e.preventDefault) e.preventDefault();
|
|
220
|
+
syncStore(touchedStore, mirrorLeaves(snapshot(valuesStore), true));
|
|
221
|
+
isSubmittingSig.value = true;
|
|
222
|
+
submitCountSig.value++;
|
|
223
|
+
await runValidation();
|
|
224
|
+
if (!hasTruthy(toRawValue(errorsStore))) {
|
|
225
|
+
try {
|
|
226
|
+
await fn(snapshot(valuesStore));
|
|
227
|
+
isSubmittedSig.value = true;
|
|
228
|
+
} finally {
|
|
229
|
+
isSubmittingSig.value = false;
|
|
230
|
+
}
|
|
231
|
+
} else {
|
|
232
|
+
isSubmittingSig.value = false;
|
|
233
|
+
}
|
|
234
|
+
};
|
|
235
|
+
|
|
236
|
+
const reset = (newValues) => {
|
|
237
|
+
batch(() => {
|
|
238
|
+
if (newValues !== undefined) initialValues = clone(newValues);
|
|
239
|
+
syncStore(valuesStore, clone(initialValues));
|
|
240
|
+
syncStore(errorsStore, {});
|
|
241
|
+
syncStore(touchedStore, mirrorLeaves(initialValues, false));
|
|
242
|
+
syncStore(changedStore, {});
|
|
243
|
+
isSubmittedSig.value = false;
|
|
244
|
+
});
|
|
245
|
+
};
|
|
246
|
+
|
|
247
|
+
// --- derived flags
|
|
248
|
+
const isValidSig = computed(() => !hasTruthy(errorsStore));
|
|
249
|
+
const isTouchedSig = computed(() => hasTruthy(touchedStore));
|
|
250
|
+
const isChangedSig = computed(() => hasTruthy(changedStore));
|
|
251
|
+
|
|
252
|
+
const form = {
|
|
253
|
+
register,
|
|
254
|
+
handleSubmit,
|
|
255
|
+
reset,
|
|
256
|
+
_updateConfig(newMode, newReValidateMode) {
|
|
257
|
+
batch(() => {
|
|
258
|
+
modeSig.value = newMode;
|
|
259
|
+
reValidateModeSig.value = newReValidateMode;
|
|
260
|
+
});
|
|
261
|
+
},
|
|
262
|
+
_notifySignals() {}, // legacy no-op: reactive stores notify on write
|
|
263
|
+
get values() { return valuesStore; },
|
|
264
|
+
get errors() { return errorsStore; },
|
|
265
|
+
get touched() { return touchedStore; },
|
|
266
|
+
get changed() { return changedStore; },
|
|
267
|
+
_signals: {
|
|
268
|
+
values: storeSignal(valuesStore),
|
|
269
|
+
errors: storeSignal(errorsStore),
|
|
270
|
+
touched: storeSignal(touchedStore),
|
|
271
|
+
changed: storeSignal(changedStore),
|
|
272
|
+
},
|
|
273
|
+
};
|
|
274
|
+
|
|
275
|
+
Object.defineProperties(form, {
|
|
276
|
+
isValid: { get: () => isValidSig.value, enumerable: true },
|
|
277
|
+
isChanged: { get: () => isChangedSig.value, enumerable: true },
|
|
278
|
+
isTouched: { get: () => isTouchedSig.value, enumerable: true },
|
|
279
|
+
isSubmitting: { get: () => isSubmittingSig.value, enumerable: true },
|
|
280
|
+
isValidating: { get: () => isValidatingSig.value, enumerable: true },
|
|
281
|
+
isSubmitted: { get: () => isSubmittedSig.value, enumerable: true },
|
|
282
|
+
submitCount: { get: () => submitCountSig.value, enumerable: true },
|
|
283
|
+
});
|
|
284
|
+
|
|
285
|
+
return form;
|
|
286
|
+
}
|
|
287
|
+
|
|
288
|
+
// --- shared helpers (no per-form state)
|
|
289
|
+
|
|
290
|
+
/** Raw (non-reactive) deep read by dot-path. */
|
|
291
|
+
function readRaw(obj, path) {
|
|
292
|
+
let node = obj;
|
|
293
|
+
for (const p of path.split(".")) {
|
|
294
|
+
if (node == null) return undefined;
|
|
295
|
+
node = node[p];
|
|
296
|
+
}
|
|
297
|
+
return node;
|
|
298
|
+
}
|
|
299
|
+
|
|
300
|
+
/** Whether any leaf is truthy — the basis of isValid/isTouched/isChanged. */
|
|
301
|
+
function hasTruthy(obj) {
|
|
302
|
+
if (obj == null || typeof obj !== "object") return !!obj;
|
|
303
|
+
return Object.values(obj).some(hasTruthy);
|
|
304
|
+
}
|
|
305
|
+
|
|
306
|
+
/** Mirror a tree's structure, replacing every leaf with `leaf`. */
|
|
307
|
+
function mirrorLeaves(obj, leaf) {
|
|
308
|
+
if (obj == null || typeof obj !== "object") return leaf;
|
|
309
|
+
const res = Array.isArray(obj) ? [] : {};
|
|
310
|
+
for (const k of Object.keys(obj)) res[k] = mirrorLeaves(obj[k], leaf);
|
|
311
|
+
return res;
|
|
312
|
+
}
|
|
313
|
+
|
|
314
|
+
/** Subscribe the active consumer to every path in a store (deep). */
|
|
315
|
+
function deepTrack(store) {
|
|
316
|
+
const raw = toRawValue(store);
|
|
317
|
+
if (raw == null || typeof raw !== "object") return;
|
|
318
|
+
for (const k of Object.keys(store)) {
|
|
319
|
+
const v = store[k];
|
|
320
|
+
if (v && typeof v === "object") deepTrack(v);
|
|
321
|
+
}
|
|
322
|
+
}
|
|
323
|
+
|
|
324
|
+
/**
|
|
325
|
+
* A preact-style signal facade over a reactive store for the advanced `_signals`
|
|
326
|
+
* API: `.value` snapshots/replaces the whole tree, `.subscribe(cb)` fires
|
|
327
|
+
* immediately then once per change.
|
|
328
|
+
*/
|
|
329
|
+
function storeSignal(store) {
|
|
330
|
+
return {
|
|
331
|
+
get value() {
|
|
332
|
+
return snapshot(store);
|
|
333
|
+
},
|
|
334
|
+
set value(v) {
|
|
335
|
+
const next = v || {};
|
|
336
|
+
const raw = toRawValue(store);
|
|
337
|
+
for (const k of Object.keys(raw)) if (!(k in next)) delete store[k];
|
|
338
|
+
for (const k of Object.keys(next)) store[k] = next[k];
|
|
339
|
+
},
|
|
340
|
+
peek() {
|
|
341
|
+
return toRawValue(store);
|
|
342
|
+
},
|
|
343
|
+
subscribe(cb) {
|
|
344
|
+
return effect(() => {
|
|
345
|
+
deepTrack(store);
|
|
346
|
+
cb(snapshot(store));
|
|
347
|
+
});
|
|
348
|
+
},
|
|
349
|
+
};
|
|
350
|
+
}
|