@opentf/afw-form 0.0.0-stage → 1.28.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 +21 -0
- package/README.md +146 -2
- package/index.js +350 -0
- package/package.json +44 -4
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Open Tech Foundation and contributors
|
|
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.
|
package/README.md
CHANGED
|
@@ -1,3 +1,147 @@
|
|
|
1
|
-
|
|
1
|
+
<div align="center">
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
# @opentf/afw-form
|
|
4
|
+
|
|
5
|
+
***Path-based reactive forms for AFW***
|
|
6
|
+
|
|
7
|
+
[Docs](https://afw.opentechf.org/packages/afw-form) | [API](https://afw.opentechf.org/api/afw-form) | [Changelog](https://github.com/Open-Tech-Foundation/afw/blob/main/packages/afw-form/CHANGELOG.md) | [GitHub](https://github.com/Open-Tech-Foundation/afw)
|
|
8
|
+
|
|
9
|
+
</div>
|
|
10
|
+
|
|
11
|
+
<div align="right">
|
|
12
|
+
|
|
13
|
+
*An [Open Tech Foundation](https://opentechf.org/) project*
|
|
14
|
+
|
|
15
|
+
</div>
|
|
16
|
+
|
|
17
|
+
> Fields bind straight to reactive stores, addressed by dot-path. Typing in one
|
|
18
|
+
> field re-runs only the bindings that read that field: per-keystroke work grows
|
|
19
|
+
> with the path, not with the number of fields.
|
|
20
|
+
|
|
21
|
+
```jsx
|
|
22
|
+
import { createForm } from "@opentf/afw-form";
|
|
23
|
+
|
|
24
|
+
export default function SignupForm() {
|
|
25
|
+
const form = createForm({
|
|
26
|
+
initialValues: { username: "", email: "" },
|
|
27
|
+
validate: (values) => {
|
|
28
|
+
const errors = {};
|
|
29
|
+
if (!values.username) errors.username = "Username required";
|
|
30
|
+
if (!values.email.includes("@")) errors.email = "Invalid email";
|
|
31
|
+
return errors;
|
|
32
|
+
},
|
|
33
|
+
});
|
|
34
|
+
|
|
35
|
+
return (
|
|
36
|
+
<form onsubmit={form.handleSubmit((values) => console.log(values))}>
|
|
37
|
+
<input {...form.register("username")} placeholder="Username" />
|
|
38
|
+
{form.errors.username && <span class="error">{form.errors.username}</span>}
|
|
39
|
+
|
|
40
|
+
<input {...form.register("email")} placeholder="Email" />
|
|
41
|
+
{form.errors.email && <span class="error">{form.errors.email}</span>}
|
|
42
|
+
|
|
43
|
+
<button type="submit" disabled={form.isSubmitting}>Sign up</button>
|
|
44
|
+
</form>
|
|
45
|
+
);
|
|
46
|
+
}
|
|
47
|
+
```
|
|
48
|
+
|
|
49
|
+
`register(path)` returns everything an input needs: `name`, `value`, `checked`,
|
|
50
|
+
`oninput` and `onblur`, plus the field's `error` and `isTouched` state. `handleSubmit` validates first and calls your handler only
|
|
51
|
+
when the form is valid.
|
|
52
|
+
|
|
53
|
+
> [!NOTE]
|
|
54
|
+
> **Alpha.** The API can change between minor versions; see the
|
|
55
|
+
> [changelog](https://github.com/Open-Tech-Foundation/afw/blob/main/packages/afw-form/CHANGELOG.md).
|
|
56
|
+
|
|
57
|
+
## Why afw-form
|
|
58
|
+
|
|
59
|
+
| Need | How afw-form meets it |
|
|
60
|
+
| --- | --- |
|
|
61
|
+
| 🎯 **Fine-grained** | `form.values`, `form.errors`, `form.touched` and `form.changed` are reactive stores; only the nodes that read a changed path update |
|
|
62
|
+
| 🌲 **Nested state and arrays** | Any depth by dot-path (`"user.profile.firstName"`, `"tags.0"`); arrays are mutated directly |
|
|
63
|
+
| 🛡️ **Validation your way** | A plain function, an async check, or a schema library such as Zod or Valibot |
|
|
64
|
+
| ⏱️ **Validation timing** | `onChange`, `onBlur` or `onSubmit`, with a separate mode for re-validation |
|
|
65
|
+
| 🔌 **No provider** | The form is a plain object; pass it down or read it where it was created |
|
|
66
|
+
|
|
67
|
+
## Install
|
|
68
|
+
|
|
69
|
+
```sh
|
|
70
|
+
pnpm add @opentf/afw-form
|
|
71
|
+
```
|
|
72
|
+
|
|
73
|
+
`@opentf/afw` is a peer dependency.
|
|
74
|
+
|
|
75
|
+
## Nested state and arrays
|
|
76
|
+
|
|
77
|
+
```jsx
|
|
78
|
+
const form = createForm({
|
|
79
|
+
initialValues: { user: { name: "Ada" }, skills: ["JavaScript"] },
|
|
80
|
+
});
|
|
81
|
+
|
|
82
|
+
<input {...form.register("user.name")} />
|
|
83
|
+
|
|
84
|
+
{form.values.skills.map((skill, i) => (
|
|
85
|
+
<input {...form.register(`skills.${i}`)} />
|
|
86
|
+
))}
|
|
87
|
+
|
|
88
|
+
<button type="button" onclick={() => form.values.skills.push("")}>Add skill</button>
|
|
89
|
+
```
|
|
90
|
+
|
|
91
|
+
Editing one row never re-renders the others; `push` and `splice` on
|
|
92
|
+
`form.values.skills` update the list in place.
|
|
93
|
+
|
|
94
|
+
## Validation
|
|
95
|
+
|
|
96
|
+
`validate(values)` returns an errors object keyed by field path. `validator(values)`
|
|
97
|
+
returns `{ errors }` instead, which suits schema resolvers. Either may be async;
|
|
98
|
+
`form.isValidating` is `true` while it runs.
|
|
99
|
+
|
|
100
|
+
```js
|
|
101
|
+
import { z } from "zod";
|
|
102
|
+
|
|
103
|
+
const schema = z.object({
|
|
104
|
+
username: z.string().min(3, "Too short"),
|
|
105
|
+
email: z.string().email("Invalid email"),
|
|
106
|
+
});
|
|
107
|
+
|
|
108
|
+
const zodResolver = (schema) => (values) => {
|
|
109
|
+
const result = schema.safeParse(values);
|
|
110
|
+
if (result.success) return { errors: {} };
|
|
111
|
+
const errors = {};
|
|
112
|
+
for (const issue of result.error.issues) errors[issue.path.join(".")] = issue.message;
|
|
113
|
+
return { errors };
|
|
114
|
+
};
|
|
115
|
+
|
|
116
|
+
const form = createForm({ initialValues: { username: "", email: "" }, validator: zodResolver(schema) });
|
|
117
|
+
```
|
|
118
|
+
|
|
119
|
+
| Option | Values | Default | Validates |
|
|
120
|
+
| --- | --- | --- | --- |
|
|
121
|
+
| `mode` | `"onChange"`, `"onBlur"`, `"onSubmit"` | `"onBlur"` | On every edit (and on mount), on blur, or only on submit |
|
|
122
|
+
| `reValidateMode` | `"onChange"`, `"onBlur"` | `"onChange"` | Once an error exists, when to check again |
|
|
123
|
+
|
|
124
|
+
## API
|
|
125
|
+
|
|
126
|
+
`createForm(options)` returns a stable form object; called again from the same
|
|
127
|
+
component, it returns the same instance.
|
|
128
|
+
|
|
129
|
+
| Option | Purpose |
|
|
130
|
+
| --- | --- |
|
|
131
|
+
| `initialValues` | Starting values; also the baseline for `isChanged` |
|
|
132
|
+
| `validate` / `validator` | Validation function, as above |
|
|
133
|
+
| `mode` / `reValidateMode` | Validation timing, as above |
|
|
134
|
+
| `key` | Distinguishes several forms created in one component |
|
|
135
|
+
|
|
136
|
+
| Member | Purpose |
|
|
137
|
+
| --- | --- |
|
|
138
|
+
| `register(path)` | Props to spread onto an input |
|
|
139
|
+
| `handleSubmit(fn)` | Submit handler: validates, then calls `fn(values)` when valid |
|
|
140
|
+
| `reset(values?)` | Restore `initialValues`, or reset to new baseline values |
|
|
141
|
+
| `values`, `errors`, `touched`, `changed` | Reactive stores, read by path |
|
|
142
|
+
| `isValid`, `isChanged`, `isTouched` | Form-wide status |
|
|
143
|
+
| `isSubmitting`, `isValidating`, `isSubmitted`, `submitCount` | Submission status |
|
|
144
|
+
|
|
145
|
+
## License
|
|
146
|
+
|
|
147
|
+
MIT — see [LICENSE](https://github.com/Open-Tech-Foundation/afw/blob/main/LICENSE).
|
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
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,46 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@opentf/afw-form",
|
|
3
|
-
"version": "
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "1.28.0",
|
|
4
|
+
"description": "Path-based reactive forms for AFW.",
|
|
5
|
+
"main": "index.js",
|
|
6
|
+
"module": "index.js",
|
|
7
|
+
"type": "module",
|
|
8
|
+
"scripts": {
|
|
9
|
+
"build": "cp ../../LICENSE LICENSE"
|
|
10
|
+
},
|
|
11
|
+
"exports": {
|
|
12
|
+
".": "./index.js"
|
|
13
|
+
},
|
|
14
|
+
"files": [
|
|
15
|
+
"index.js"
|
|
16
|
+
],
|
|
17
|
+
"keywords": [
|
|
18
|
+
"afw",
|
|
19
|
+
"opentf",
|
|
20
|
+
"forms",
|
|
21
|
+
"validation",
|
|
22
|
+
"reactive",
|
|
23
|
+
"signals"
|
|
24
|
+
],
|
|
25
|
+
"repository": {
|
|
26
|
+
"type": "git",
|
|
27
|
+
"url": "https://github.com/Open-Tech-Foundation/afw.git",
|
|
28
|
+
"directory": "packages/afw-form"
|
|
29
|
+
},
|
|
30
|
+
"homepage": "https://afw.opentechf.org/packages/afw-form",
|
|
31
|
+
"bugs": "https://github.com/Open-Tech-Foundation/afw/issues",
|
|
32
|
+
"license": "MIT",
|
|
33
|
+
"dependencies": {
|
|
34
|
+
"@opentf/std": "^0.19.0"
|
|
35
|
+
},
|
|
36
|
+
"peerDependencies": {
|
|
37
|
+
"@opentf/afw": "0.33.0"
|
|
38
|
+
},
|
|
39
|
+
"publishConfig": {
|
|
40
|
+
"access": "public"
|
|
41
|
+
},
|
|
42
|
+
"devDependencies": {
|
|
43
|
+
"@opentf/afw": "0.33.0",
|
|
44
|
+
"@opentf/afw-test": "1.28.0"
|
|
45
|
+
}
|
|
46
|
+
}
|