@opentf/afw-form 1.27.0 → 1.29.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 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,37 +1,27 @@
1
- # @opentf/afw-form
1
+ <div align="center">
2
2
 
3
- A high-performance, **path-based reactive forms engine** for [AFW](https://github.com/Open-Tech-Foundation/afw).
3
+ # @opentf/afw-form
4
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.
5
+ ***Path-based reactive forms for AFW***
8
6
 
9
- ## Features
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)
10
8
 
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.
9
+ </div>
17
10
 
18
- ## Installation
11
+ <div align="right">
19
12
 
20
- ```bash
21
- npm install @opentf/afw-form
22
- # or
23
- pnpm add @opentf/afw-form
24
- ```
13
+ *An [Open Tech Foundation](https://opentechf.org/) project*
25
14
 
26
- ## Basic usage
15
+ </div>
27
16
 
28
- `createForm` returns a stable form object. Spread `register(path)` onto an input
29
- to bind it, and wrap your submit handler with `handleSubmit`.
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.
30
20
 
31
21
  ```jsx
32
22
  import { createForm } from "@opentf/afw-form";
33
23
 
34
- export function SignupForm() {
24
+ export default function SignupForm() {
35
25
  const form = createForm({
36
26
  initialValues: { username: "", email: "" },
37
27
  validate: (values) => {
@@ -42,104 +32,72 @@ export function SignupForm() {
42
32
  },
43
33
  });
44
34
 
45
- const onSubmit = (values) => console.log("Submitted:", values);
46
-
47
35
  return (
48
- <form onsubmit={form.handleSubmit(onSubmit)}>
49
- <label for="username">Username</label>
50
- <input {...form.register("username")} id="username" />
36
+ <form onsubmit={form.handleSubmit((values) => console.log(values))}>
37
+ <input {...form.register("username")} placeholder="Username" />
51
38
  {form.errors.username && <span class="error">{form.errors.username}</span>}
52
39
 
53
- <label for="email">Email</label>
54
- <input {...form.register("email")} id="email" />
40
+ <input {...form.register("email")} placeholder="Email" />
55
41
  {form.errors.email && <span class="error">{form.errors.email}</span>}
56
42
 
57
- <button type="submit">Sign up</button>
43
+ <button type="submit" disabled={form.isSubmitting}>Sign up</button>
58
44
  </form>
59
45
  );
60
46
  }
61
47
  ```
62
48
 
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.
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.
72
52
 
73
- ```jsx
74
- <p>Hello, {form.values.username || "stranger"}</p>
75
- ```
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).
76
56
 
77
- ## Nested state & arrays
57
+ ## Why afw-form
78
58
 
79
- Address objects and arrays by dot-path; arrays use the index as a segment.
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 |
80
66
 
81
- ```jsx
82
- const form = createForm({
83
- initialValues: {
84
- user: {
85
- profile: { firstName: "John" },
86
- settings: { notifications: true },
87
- },
88
- },
89
- });
67
+ ## Install
90
68
 
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>}
69
+ ```sh
70
+ pnpm add @opentf/afw-form
100
71
  ```
101
72
 
102
- ### Dynamic arrays
73
+ `@opentf/afw` is a peer dependency.
103
74
 
104
- The values store is a real reactive object — mutate it directly:
75
+ ## Nested state and arrays
105
76
 
106
77
  ```jsx
107
- const form = createForm({ initialValues: { skills: ["JavaScript"] } });
78
+ const form = createForm({
79
+ initialValues: { user: { name: "Ada" }, skills: ["JavaScript"] },
80
+ });
108
81
 
109
- // Add / remove
110
- const addSkill = () => form.values.skills.push("");
111
- const removeSkill = (i) => form.values.skills.splice(i, 1);
82
+ <input {...form.register("user.name")} />
112
83
 
113
- // Render a row per item; editing one input never re-renders the others
114
84
  {form.values.skills.map((skill, i) => (
115
85
  <input {...form.register(`skills.${i}`)} />
116
86
  ))}
117
- ```
118
87
 
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
- });
88
+ <button type="button" onclick={() => form.values.skills.push("")}>Add skill</button>
135
89
  ```
136
90
 
137
- ### Schema validation (Zod)
91
+ Editing one row never re-renders the others; `push` and `splice` on
92
+ `form.values.skills` update the list in place.
138
93
 
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`:
94
+ ## Validation
141
95
 
142
- ```jsx
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
143
101
  import { z } from "zod";
144
102
 
145
103
  const schema = z.object({
@@ -151,72 +109,40 @@ const zodResolver = (schema) => (values) => {
151
109
  const result = schema.safeParse(values);
152
110
  if (result.success) return { errors: {} };
153
111
  const errors = {};
154
- for (const issue of result.error.issues) {
155
- errors[issue.path.join(".")] = issue.message;
156
- }
112
+ for (const issue of result.error.issues) errors[issue.path.join(".")] = issue.message;
157
113
  return { errors };
158
114
  };
159
115
 
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" });
116
+ const form = createForm({ initialValues: { username: "", email: "" }, validator: zodResolver(schema) });
178
117
  ```
179
118
 
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
- ```
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. When the same component instance
127
+ remounts, each `createForm` call gets its form back, matched by `key` or else by call
128
+ order in the component body. Several forms in one component stay independent.
129
+
130
+ | Option | Purpose |
131
+ | --- | --- |
132
+ | `initialValues` | Starting values; also the baseline for `isChanged` |
133
+ | `validate` / `validator` | Validation function, as above |
134
+ | `mode` / `reValidateMode` | Validation timing, as above |
135
+ | `key` | Names the form within its component, instead of its call order |
136
+
137
+ | Member | Purpose |
138
+ | --- | --- |
139
+ | `register(path)` | Props to spread onto an input |
140
+ | `handleSubmit(fn)` | Submit handler: validates, then calls `fn(values)` when valid |
141
+ | `reset(values?)` | Restore `initialValues`, or reset to new baseline values |
142
+ | `values`, `errors`, `touched`, `changed` | Reactive stores, read by path |
143
+ | `isValid`, `isChanged`, `isTouched` | Form-wide status |
144
+ | `isSubmitting`, `isValidating`, `isSubmitted`, `submitCount` | Submission status |
219
145
 
220
146
  ## License
221
147
 
222
- MIT © [Open Tech Foundation](https://github.com/Open-Tech-Foundation)
148
+ MIT — see [LICENSE](https://github.com/Open-Tech-Foundation/afw/blob/main/LICENSE).
package/index.js CHANGED
@@ -33,10 +33,24 @@ export function createForm(options = {}) {
33
33
  const inst = getCurrentInstance();
34
34
  if (!inst) return _createForm(options);
35
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 });
36
+ let entry = INST_FORMS_REGISTRY.get(inst);
37
+ if (!entry) INST_FORMS_REGISTRY.set(inst, (entry = { forms: new Map(), calls: 0, counting: false }));
38
+ const { forms } = entry;
39
+
40
+ // Without a `key`, a form is identified by its call position in the component
41
+ // body: the first `createForm` is `#0`, the next `#1`, … The count restarts once
42
+ // the body finishes (a microtask later), so a remount of the same host gets the
43
+ // same forms back, while two forms in one body never share state — even with
44
+ // identical (or no) initial values.
45
+ if (!entry.counting) {
46
+ entry.counting = true;
47
+ queueMicrotask(() => {
48
+ entry.calls = 0;
49
+ entry.counting = false;
50
+ });
51
+ }
52
+ const position = entry.calls++;
53
+ const key = options.key != null ? `key:${options.key}` : `#${position}`;
40
54
  if (forms.has(key)) {
41
55
  const form = forms.get(key);
42
56
  form._updateConfig?.(options.mode, options.reValidateMode);
@@ -193,8 +207,9 @@ function _createForm(options = {}) {
193
207
 
194
208
  const register = (path) => ({
195
209
  name: path,
196
- value: readPath(valuesStore, path),
197
- checked: readPath(valuesStore, path),
210
+ // A field with no initial value renders empty, not the text "undefined".
211
+ value: readPath(valuesStore, path) ?? "",
212
+ checked: readPath(valuesStore, path) ?? false,
198
213
  error: computed(() => readPath(errorsStore, path)),
199
214
  isTouched: computed(() => readPath(touchedStore, path) ?? false),
200
215
  oninput: (e) => {
@@ -220,15 +235,15 @@ function _createForm(options = {}) {
220
235
  syncStore(touchedStore, mirrorLeaves(snapshot(valuesStore), true));
221
236
  isSubmittingSig.value = true;
222
237
  submitCountSig.value++;
223
- await runValidation();
224
- if (!hasTruthy(toRawValue(errorsStore))) {
225
- try {
238
+ // `finally` covers a validator that throws or rejects as well as `fn`, so a
239
+ // failed submit never leaves the form stuck in `isSubmitting`.
240
+ try {
241
+ await runValidation();
242
+ if (!hasTruthy(toRawValue(errorsStore))) {
226
243
  await fn(snapshot(valuesStore));
227
244
  isSubmittedSig.value = true;
228
- } finally {
229
- isSubmittingSig.value = false;
230
245
  }
231
- } else {
246
+ } finally {
232
247
  isSubmittingSig.value = false;
233
248
  }
234
249
  };
package/package.json CHANGED
@@ -1,24 +1,46 @@
1
1
  {
2
2
  "name": "@opentf/afw-form",
3
- "version": "1.27.0",
4
- "description": "A high-performance, path-based reactive forms engine for the native-first AFW.",
3
+ "version": "1.29.0",
4
+ "description": "Path-based reactive forms for AFW.",
5
5
  "main": "index.js",
6
6
  "module": "index.js",
7
7
  "type": "module",
8
+ "scripts": {
9
+ "build": "cp ../../LICENSE LICENSE"
10
+ },
8
11
  "exports": {
9
12
  ".": "./index.js"
10
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",
11
33
  "dependencies": {
12
34
  "@opentf/std": "^0.19.0"
13
35
  },
14
36
  "peerDependencies": {
15
- "@opentf/afw": "0.32.0"
37
+ "@opentf/afw": "0.34.0"
16
38
  },
17
39
  "publishConfig": {
18
40
  "access": "public"
19
41
  },
20
42
  "devDependencies": {
21
- "@opentf/afw": "0.32.0",
22
- "@opentf/afw-test": "1.27.0"
43
+ "@opentf/afw": "0.34.0",
44
+ "@opentf/afw-test": "1.29.0"
23
45
  }
24
- }
46
+ }
package/CHANGELOG.md DELETED
@@ -1,136 +0,0 @@
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
@@ -1,36 +0,0 @@
1
- import { expect, test, describe } from "runtime:test";
2
- import { mount, type, clear, click } from "./dom.js";
3
- import BasicForm from "./BasicForm.jsx";
4
-
5
- describe("Basic Form", () => {
6
- test("initializes and handles submission", async () => {
7
- let submittedValues = null;
8
- const { getByTestId, queryByTestId } = mount(BasicForm, {
9
- onSubmit: (v) => submittedValues = v
10
- });
11
-
12
- const username = getByTestId("username");
13
- const email = getByTestId("email");
14
- const submit = getByTestId("submit");
15
-
16
- expect(username.value).toBe("alice");
17
- expect(email.value).toBe("");
18
-
19
- // Try to submit with invalid email
20
- await click(submit);
21
- expect(submittedValues).toBeNull();
22
- expect(getByTestId("email-error").textContent).toBe("Invalid email");
23
-
24
- // Correct the email
25
- await type(email, "alice@example.com");
26
- expect(queryByTestId("email-error")).toBeNull();
27
-
28
- // Change username
29
- await clear(username);
30
- await type(username, "bob");
31
-
32
- // Submit
33
- await click(submit);
34
- expect(submittedValues).toEqual({ username: "bob", email: "alice@example.com" });
35
- });
36
- });
@@ -1,29 +0,0 @@
1
- import { createForm } from "../index.js";
2
-
3
- export default function BasicForm({ onSubmit }) {
4
- const form = createForm({
5
- initialValues: { username: "alice", email: "" },
6
- validate: (values) => {
7
- const errs = {};
8
- if (!values.username) errs.username = "Username required";
9
- if (!values.email.includes("@")) errs.email = "Invalid email";
10
- return errs;
11
- }
12
- });
13
-
14
- return (
15
- <form onsubmit={form.handleSubmit(onSubmit)}>
16
- <div>
17
- <label for="username">Username</label>
18
- <input {...form.register("username")} id="username" data-testid="username" />
19
- {form.errors.username && <span data-testid="username-error">{form.errors.username}</span>}
20
- </div>
21
- <div>
22
- <label for="email">Email</label>
23
- <input {...form.register("email")} id="email" data-testid="email" />
24
- {form.errors.email && <span data-testid="email-error">{form.errors.email}</span>}
25
- </div>
26
- <button type="submit" data-testid="submit">Submit</button>
27
- </form>
28
- );
29
- }