@opentf/afw-form 1.27.0 → 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 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.
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.
66
52
 
67
- ## Reactive values
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).
68
56
 
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.
57
+ ## Why afw-form
72
58
 
73
- ```jsx
74
- <p>Hello, {form.values.username || "stranger"}</p>
75
- ```
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 |
76
66
 
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
- });
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
-
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
87
 
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,39 @@ 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
- });
116
+ const form = createForm({ initialValues: { username: "", email: "" }, validator: zodResolver(schema) });
164
117
  ```
165
118
 
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
- ```
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 |
179
123
 
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`.
124
+ ## API
182
125
 
183
- ## Status flags
126
+ `createForm(options)` returns a stable form object; called again from the same
127
+ component, it returns the same instance.
184
128
 
185
- `createForm` exposes derived flags — read them directly (they are reactive in JSX):
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 |
186
135
 
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
- ```
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 |
219
144
 
220
145
  ## License
221
146
 
222
- MIT © [Open Tech Foundation](https://github.com/Open-Tech-Foundation)
147
+ MIT — see [LICENSE](https://github.com/Open-Tech-Foundation/afw/blob/main/LICENSE).
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.28.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.33.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.33.0",
44
+ "@opentf/afw-test": "1.28.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
- }
@@ -1,44 +0,0 @@
1
- import { expect, test, describe } from "runtime:test";
2
- import { mount, type, clear, click, tab } from "./dom.js";
3
- import ProfileForm from "./ProfileForm.jsx";
4
-
5
- describe("Web Form Component Integration", () => {
6
- test("updates nested values and validation state in UI", async () => {
7
- const { getByTestId } = mount(ProfileForm);
8
-
9
- const input = getByTestId("name-input");
10
- const error = getByTestId("name-error");
11
- const status = getByTestId("status");
12
- const title = getByTestId("title");
13
-
14
- expect(title.textContent).toBe("John");
15
- expect(status.textContent).toBe("Valid");
16
-
17
- await clear(input);
18
- await type(input, "Jo");
19
- // Mode is onBlur by default, so we need to blur
20
- await tab();
21
-
22
- expect(title.textContent).toBe("Jo");
23
- expect(error.textContent).toBe("Too short");
24
- expect(status.textContent).toBe("Invalid");
25
-
26
- await type(input, "hnny");
27
- await tab();
28
- expect(error.textContent).toBe("");
29
- expect(status.textContent).toBe("Valid");
30
- });
31
-
32
- test("handles dynamic array mutations in UI", async () => {
33
- const { getByTestId, getAllByRole } = mount(ProfileForm);
34
-
35
- const list = getByTestId("tag-list");
36
- const addBtn = getByTestId("add-tag");
37
-
38
- expect(list.children.length).toBe(1);
39
-
40
- await click(addBtn);
41
- expect(list.children.length).toBe(2);
42
- expect(getByTestId("tag-1").textContent).toBe("tag-1");
43
- });
44
- });
@@ -1,32 +0,0 @@
1
- import { createForm } from "../index.js";
2
-
3
- export default function DynamicArrayForm() {
4
- const form = createForm({
5
- initialValues: { items: ["Item 1"] }
6
- });
7
-
8
- const addItem = () => {
9
- const items = form.values.items;
10
- form.values.items = [...items, `Item ${items.length + 1}`];
11
- };
12
-
13
- const removeItem = (index) => {
14
- const newItems = [...form.values.items];
15
- newItems.splice(index, 1);
16
- form.values.items = newItems;
17
- };
18
-
19
- return (
20
- <div>
21
- <button onclick={addItem} data-testid="add-item">Add Item</button>
22
- <ul data-testid="item-list">
23
- {form.values.items.map((item, index) => (
24
- <li data-testid={`item-${index}`}>
25
- {item}
26
- <button onclick={() => removeItem(index)} data-testid={`remove-${index}`}>Remove</button>
27
- </li>
28
- ))}
29
- </ul>
30
- </div>
31
- );
32
- }
@@ -1,32 +0,0 @@
1
- import { expect, test, describe } from "runtime:test";
2
- import { mount, click } from "./dom.js";
3
- import DynamicArrayForm from "./DynamicArrayForm.jsx";
4
-
5
- describe("Dynamic Arrays", () => {
6
- test("adds and removes items", async () => {
7
- const { getByTestId, getAllByRole, queryByTestId } = mount(DynamicArrayForm);
8
-
9
- const addBtn = getByTestId("add-item");
10
- const list = getByTestId("item-list");
11
-
12
- expect(getAllByRole("listitem").length).toBe(1);
13
- expect(getByTestId("item-0").textContent).toContain("Item 1");
14
-
15
- // Add item
16
- await click(addBtn);
17
- expect(getAllByRole("listitem").length).toBe(2);
18
- expect(getByTestId("item-1").textContent).toContain("Item 2");
19
-
20
- // Add another
21
- await click(addBtn);
22
- expect(getAllByRole("listitem").length).toBe(3);
23
-
24
- // Remove middle item (Item 2 at index 1)
25
- await click(getByTestId("remove-1"));
26
- expect(getAllByRole("listitem").length).toBe(2);
27
-
28
- // Check remaining items
29
- expect(getByTestId("item-0").textContent).toContain("Item 1");
30
- expect(getByTestId("item-1").textContent).toContain("Item 3"); // Item 3 moved to index 1
31
- });
32
- });