@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.
@@ -0,0 +1,57 @@
1
+ import { expect, test, describe } from "runtime:test";
2
+ import { mount, type, clear, click } from "./dom.js";
3
+ import { sleep } from "@opentf/std";
4
+ import StateForm from "./StateForm.jsx";
5
+
6
+ const waitFor = async (fn, timeout = 1000) => {
7
+ const start = Date.now();
8
+ while (Date.now() - start < timeout) {
9
+ try {
10
+ fn();
11
+ return;
12
+ } catch (e) {
13
+ await sleep(10);
14
+ }
15
+ }
16
+ fn();
17
+ };
18
+
19
+ describe("Form State UI Reactivity", () => {
20
+ test("updates UI based on state helpers", async () => {
21
+ let submitted = false;
22
+ const { getByTestId, queryByTestId } = mount(StateForm, { onSubmit: async () => {
23
+ submitted = true;
24
+ }});
25
+
26
+ const input = getByTestId("username");
27
+ const statusValid = getByTestId("status-valid");
28
+ const statusChanged = getByTestId("status-changed");
29
+ const statusTouched = getByTestId("status-touched");
30
+ const resetBtn = getByTestId("reset");
31
+ const submitBtn = getByTestId("submit");
32
+
33
+ // Initial state
34
+ expect(statusValid.textContent).toBe("Valid");
35
+
36
+ // Change value to invalid
37
+ await clear(input);
38
+ await type(input, "ab");
39
+ expect(statusValid.textContent).toBe("Invalid");
40
+ expect(statusChanged.textContent).toBe("Changed");
41
+ expect(getByTestId("error").textContent).toBe("Too short");
42
+
43
+ // Submit valid data
44
+ await clear(input);
45
+ await type(input, "bob");
46
+ await click(submitBtn);
47
+
48
+ await waitFor(() => expect(submitted).toBe(true));
49
+ await waitFor(() => expect(getByTestId("success")).toBeTruthy());
50
+
51
+ // Reset
52
+ await click(resetBtn);
53
+ expect(input.value).toBe("alice");
54
+ expect(statusChanged.textContent).toBe("Unchanged");
55
+ expect(queryByTestId("success")).toBeNull();
56
+ });
57
+ });
@@ -0,0 +1,29 @@
1
+ import { createForm } from "../index.js";
2
+
3
+ export default function StateForm({ onSubmit }) {
4
+ const form = createForm({
5
+ mode: "onChange", // Use onChange for easier testing of reactive text
6
+ initialValues: { username: "alice" },
7
+ validate: (v) => v.username.length < 3 ? { username: "Too short" } : {}
8
+ });
9
+
10
+ // Submit is driven via onclick rather than a native `type="submit"` (which, in
11
+ // the unit DOM, mangles the form subtree on submission regardless of
12
+ // preventDefault — a test-env quirk, not a real-browser behaviour).
13
+ return (
14
+ <div>
15
+ <input {...form.register("username")} data-testid="username" />
16
+
17
+ <div data-testid="status-valid">{form.isValid ? "Valid" : "Invalid"}</div>
18
+ <div data-testid="status-changed">{form.isChanged ? "Changed" : "Unchanged"}</div>
19
+ <div data-testid="status-touched">{form.isTouched ? "Touched" : "Untouched"}</div>
20
+
21
+ {form.errors.username && <span data-testid="error">{form.errors.username}</span>}
22
+
23
+ <button type="button" onclick={() => form.reset()} data-testid="reset">Reset</button>
24
+ <button type="button" onclick={form.handleSubmit(onSubmit)} data-testid="submit">Submit</button>
25
+
26
+ {form.isSubmitted && <div data-testid="success">Submitted!</div>}
27
+ </div>
28
+ );
29
+ }
@@ -0,0 +1,84 @@
1
+ import { expect, test, describe } from "runtime:test";
2
+ import { createForm } from "../index.js";
3
+
4
+ describe("AFW Forms Library - Validation Modes", () => {
5
+ test("mode: onBlur (default)", () => {
6
+ const form = createForm({
7
+ initialValues: { name: "" },
8
+ validate: (v) => v.name.length < 3 ? { name: "Short" } : {}
9
+ });
10
+
11
+ expect(form.errors.name).toBeUndefined();
12
+
13
+ // oninput should NOT trigger validation
14
+ form.register("name").oninput({ target: { value: "a" } });
15
+ expect(form.errors.name).toBeUndefined();
16
+
17
+ // onblur SHOULD trigger validation
18
+ form.register("name").onblur();
19
+ expect(form.errors.name).toBe("Short");
20
+ });
21
+
22
+ test("mode: onChange", () => {
23
+ const form = createForm({
24
+ mode: "onChange",
25
+ initialValues: { name: "" },
26
+ validate: (v) => v.name.length < 3 ? { name: "Short" } : {}
27
+ });
28
+
29
+ expect(form.errors.name).toBe("Short"); // Validates on init
30
+
31
+ form.register("name").oninput({ target: { value: "abc" } });
32
+ expect(form.errors.name).toBeUndefined();
33
+ });
34
+
35
+ test("mode: onSubmit", async () => {
36
+ const form = createForm({
37
+ mode: "onSubmit",
38
+ initialValues: { name: "" },
39
+ validate: (v) => v.name.length < 3 ? { name: "Short" } : {}
40
+ });
41
+
42
+ form.register("name").oninput({ target: { value: "a" } });
43
+ form.register("name").onblur();
44
+ expect(form.errors.name).toBeUndefined();
45
+
46
+ await form.handleSubmit(() => {})();
47
+ expect(form.errors.name).toBe("Short");
48
+ });
49
+
50
+ test("reValidateMode: onChange (default)", () => {
51
+ const form = createForm({
52
+ mode: "onBlur", // Validate on blur first
53
+ initialValues: { name: "" },
54
+ validate: (v) => v.name.length < 3 ? { name: "Short" } : {}
55
+ });
56
+
57
+ form.register("name").onblur();
58
+ expect(form.errors.name).toBe("Short");
59
+
60
+ // Once error exists, oninput SHOULD trigger re-validation
61
+ form.register("name").oninput({ target: { value: "abc" } });
62
+ expect(form.errors.name).toBeUndefined();
63
+ });
64
+
65
+ test("reValidateMode: onBlur", () => {
66
+ const form = createForm({
67
+ mode: "onBlur",
68
+ reValidateMode: "onBlur",
69
+ initialValues: { name: "" },
70
+ validate: (v) => v.name.length < 3 ? { name: "Short" } : {}
71
+ });
72
+
73
+ form.register("name").onblur();
74
+ expect(form.errors.name).toBe("Short");
75
+
76
+ // Should NOT re-validate on input
77
+ form.register("name").oninput({ target: { value: "abc" } });
78
+ expect(form.errors.name).toBe("Short");
79
+
80
+ // Should re-validate on blur
81
+ form.register("name").onblur();
82
+ expect(form.errors.name).toBeUndefined();
83
+ });
84
+ });
package/tests/dom.js ADDED
@@ -0,0 +1,93 @@
1
+ // Native-DOM test helpers for `esdev test --dom`.
2
+ //
3
+ // Replaces the happy-dom / testing-library based `@opentf/afw-test` render +
4
+ // user-event for suites that run under esdev. Interactions use real DOM APIs
5
+ // (verified against esdev's --dom realm): focusing + `input` events for typing,
6
+ // `.click()` for buttons and checkboxes (fires `input`/`change`), `blur()` for
7
+ // tabbing away. Mounted containers are removed after every test.
8
+ import { afterEach } from "runtime:test";
9
+
10
+ const mounted = new Set();
11
+
12
+ function instantiate(Component, props) {
13
+ if (typeof Component === "function" && Component.prototype instanceof HTMLElement) {
14
+ const tagName =
15
+ Component.tag ?? Component.prototype.tagName?.toLowerCase() ?? Component.name.toLowerCase();
16
+ const element = document.createElement(tagName);
17
+ Object.assign(element, props);
18
+ return element;
19
+ }
20
+ if (typeof Component === "function") {
21
+ const node = Component(props);
22
+ if (node instanceof Node) return node;
23
+ throw new Error("render(): component function did not return a DOM node");
24
+ }
25
+ if (typeof Component === "string") {
26
+ const element = document.createElement(Component);
27
+ Object.assign(element, props);
28
+ return element;
29
+ }
30
+ throw new Error("render(): invalid component type passed to mount()");
31
+ }
32
+
33
+ const ROLE_SELECTORS = {
34
+ listitem: 'li,[role="listitem"]',
35
+ button: 'button,[role="button"]',
36
+ textbox: 'input:not([type]),input[type="text"],[role="textbox"]',
37
+ };
38
+
39
+ export function mount(Component, props = {}) {
40
+ const container = document.createElement("div");
41
+ document.body.appendChild(container);
42
+ const element = instantiate(Component, props);
43
+ if (element.parentNode !== container) container.appendChild(element);
44
+ mounted.add(container);
45
+ const query = (id) => container.querySelector(`[data-testid="${id}"]`);
46
+ return {
47
+ container,
48
+ element,
49
+ getByTestId(id) {
50
+ const el = query(id);
51
+ if (!el) throw new Error(`getByTestId: no element with data-testid="${id}"`);
52
+ return el;
53
+ },
54
+ queryByTestId(id) {
55
+ return query(id);
56
+ },
57
+ getAllByRole(role) {
58
+ const selector = ROLE_SELECTORS[role];
59
+ if (!selector) throw new Error(`getAllByRole: unsupported role "${role}"`);
60
+ return [...container.querySelectorAll(selector)];
61
+ },
62
+ unmount() {
63
+ container.remove();
64
+ mounted.delete(container);
65
+ },
66
+ };
67
+ }
68
+
69
+ export async function type(input, text) {
70
+ input.focus();
71
+ input.value += text;
72
+ input.dispatchEvent(new Event("input", { bubbles: true }));
73
+ }
74
+
75
+ export async function clear(input) {
76
+ input.focus();
77
+ input.value = "";
78
+ input.dispatchEvent(new Event("input", { bubbles: true }));
79
+ }
80
+
81
+ export async function click(element) {
82
+ element.click();
83
+ }
84
+
85
+ export async function tab() {
86
+ const active = document.activeElement;
87
+ if (active && typeof active.blur === "function") active.blur();
88
+ }
89
+
90
+ afterEach(() => {
91
+ for (const container of mounted) container.remove();
92
+ mounted.clear();
93
+ });