@schema-engine/forms-react 0.0.0-stage → 0.5.1
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 +87 -2
- package/dist/chunk-5XCNXEJB.js +19 -0
- package/dist/chunk-5XCNXEJB.js.map +7 -0
- package/dist/chunk-6RI4LMM6.js +19 -0
- package/dist/chunk-6RI4LMM6.js.map +7 -0
- package/dist/chunk-7QNWPTT7.js +20 -0
- package/dist/chunk-7QNWPTT7.js.map +7 -0
- package/dist/chunk-7RUFT6EJ.js +39 -0
- package/dist/chunk-7RUFT6EJ.js.map +7 -0
- package/dist/chunk-AALIXTCD.js +56 -0
- package/dist/chunk-AALIXTCD.js.map +7 -0
- package/dist/chunk-CPJMN2IH.js +128 -0
- package/dist/chunk-CPJMN2IH.js.map +7 -0
- package/dist/chunk-DTJ64NZQ.js +142 -0
- package/dist/chunk-DTJ64NZQ.js.map +7 -0
- package/dist/chunk-EYDB6NR6.js +9 -0
- package/dist/chunk-EYDB6NR6.js.map +7 -0
- package/dist/chunk-GH2QO3WC.js +11 -0
- package/dist/chunk-GH2QO3WC.js.map +7 -0
- package/dist/chunk-H25SUEJE.js +8 -0
- package/dist/chunk-H25SUEJE.js.map +7 -0
- package/dist/chunk-HT43MPKW.js +0 -0
- package/dist/chunk-HT43MPKW.js.map +7 -0
- package/dist/chunk-IHX6VMAQ.js +0 -0
- package/dist/chunk-IHX6VMAQ.js.map +7 -0
- package/dist/chunk-ISDPSORR.js +265 -0
- package/dist/chunk-ISDPSORR.js.map +7 -0
- package/dist/chunk-IXRV3YCF.js +36 -0
- package/dist/chunk-IXRV3YCF.js.map +7 -0
- package/dist/chunk-K3LLWGXU.js +30 -0
- package/dist/chunk-K3LLWGXU.js.map +7 -0
- package/dist/chunk-K66J2V73.js +108 -0
- package/dist/chunk-K66J2V73.js.map +7 -0
- package/dist/chunk-KG6Q7MNI.js +51 -0
- package/dist/chunk-KG6Q7MNI.js.map +7 -0
- package/dist/chunk-MBN4WIAC.js +41 -0
- package/dist/chunk-MBN4WIAC.js.map +7 -0
- package/dist/chunk-NDFV5AQW.js +39 -0
- package/dist/chunk-NDFV5AQW.js.map +7 -0
- package/dist/chunk-QUZN42PL.js +128 -0
- package/dist/chunk-QUZN42PL.js.map +7 -0
- package/dist/chunk-SED35QJC.js +78 -0
- package/dist/chunk-SED35QJC.js.map +7 -0
- package/dist/chunk-ULKJHK3P.js +6 -0
- package/dist/chunk-ULKJHK3P.js.map +7 -0
- package/dist/chunk-USRF3EEE.js +122 -0
- package/dist/chunk-USRF3EEE.js.map +7 -0
- package/dist/chunk-WFRWVH4X.js +44 -0
- package/dist/chunk-WFRWVH4X.js.map +7 -0
- package/dist/chunk-WOTW7A2I.js +7 -0
- package/dist/chunk-WOTW7A2I.js.map +7 -0
- package/dist/chunk-WRJWSEL7.js +98 -0
- package/dist/chunk-WRJWSEL7.js.map +7 -0
- package/dist/chunk-XWHP2AGG.js +7 -0
- package/dist/chunk-XWHP2AGG.js.map +7 -0
- package/dist/chunk-ZWEYALBG.js +25 -0
- package/dist/chunk-ZWEYALBG.js.map +7 -0
- package/dist/components/form-debugger/form-debugger.css +374 -0
- package/dist/components/form-debugger/form-debugger.css.map +7 -0
- package/dist/components/form-debugger/form-debugger.d.ts +23 -0
- package/dist/components/form-debugger/form-debugger.js +17 -0
- package/dist/components/form-debugger/form-debugger.js.map +7 -0
- package/dist/components/form-debugger/index.css +374 -0
- package/dist/components/form-debugger/index.css.map +7 -0
- package/dist/components/form-debugger/index.d.ts +2 -0
- package/dist/components/form-debugger/index.js +17 -0
- package/dist/components/form-debugger/index.js.map +7 -0
- package/dist/components/form-engine-provider.d.ts +7 -0
- package/dist/components/form-engine-provider.js +7 -0
- package/dist/components/form-engine-provider.js.map +7 -0
- package/dist/components/form-provider.d.ts +23 -0
- package/dist/components/form-provider.js +13 -0
- package/dist/components/form-provider.js.map +7 -0
- package/dist/components/index.d.ts +4 -0
- package/dist/components/index.js +43 -0
- package/dist/components/index.js.map +7 -0
- package/dist/components/internals/element-error.d.ts +9 -0
- package/dist/components/internals/element-error.js +6 -0
- package/dist/components/internals/element-error.js.map +7 -0
- package/dist/components/internals/field-renderer.d.ts +26 -0
- package/dist/components/internals/field-renderer.js +24 -0
- package/dist/components/internals/field-renderer.js.map +7 -0
- package/dist/components/internals/form-elements.d.ts +20 -0
- package/dist/components/internals/form-elements.js +25 -0
- package/dist/components/internals/form-elements.js.map +7 -0
- package/dist/components/internals/form-renderer.d.ts +28 -0
- package/dist/components/internals/form-renderer.js +31 -0
- package/dist/components/internals/form-renderer.js.map +7 -0
- package/dist/components/internals/recipe-renderer.d.ts +10 -0
- package/dist/components/internals/recipe-renderer.js +17 -0
- package/dist/components/internals/recipe-renderer.js.map +7 -0
- package/dist/components/provider.d.ts +18 -0
- package/dist/components/provider.js +8 -0
- package/dist/components/provider.js.map +7 -0
- package/dist/contexts/field-constraint-context.d.ts +15 -0
- package/dist/contexts/field-constraint-context.js +6 -0
- package/dist/contexts/field-constraint-context.js.map +7 -0
- package/dist/contexts/index.d.ts +2 -0
- package/dist/contexts/index.js +6 -0
- package/dist/contexts/index.js.map +7 -0
- package/dist/contexts/view-context.d.ts +14 -0
- package/dist/contexts/view-context.js +16 -0
- package/dist/contexts/view-context.js.map +7 -0
- package/dist/global.css +8 -0
- package/dist/hooks/field-text.d.ts +6 -0
- package/dist/hooks/field-text.js +6 -0
- package/dist/hooks/field-text.js.map +7 -0
- package/dist/hooks/form-state/context.d.ts +27 -0
- package/dist/hooks/form-state/context.js +10 -0
- package/dist/hooks/form-state/context.js.map +7 -0
- package/dist/hooks/form-state/field-registry.d.ts +60 -0
- package/dist/hooks/form-state/field-registry.js +9 -0
- package/dist/hooks/form-state/field-registry.js.map +7 -0
- package/dist/hooks/form-state/index.d.ts +8 -0
- package/dist/hooks/form-state/index.js +27 -0
- package/dist/hooks/form-state/index.js.map +7 -0
- package/dist/hooks/form-state/native-control.d.ts +39 -0
- package/dist/hooks/form-state/native-control.js +17 -0
- package/dist/hooks/form-state/native-control.js.map +7 -0
- package/dist/hooks/form-state/types.d.ts +191 -0
- package/dist/hooks/form-state/types.js +0 -0
- package/dist/hooks/form-state/types.js.map +7 -0
- package/dist/hooks/form-state/use-field-array.d.ts +12 -0
- package/dist/hooks/form-state/use-field-array.js +7 -0
- package/dist/hooks/form-state/use-field-array.js.map +7 -0
- package/dist/hooks/form-state/use-form-context.d.ts +10 -0
- package/dist/hooks/form-state/use-form-context.js +7 -0
- package/dist/hooks/form-state/use-form-context.js.map +7 -0
- package/dist/hooks/form-state/use-form-field.d.ts +24 -0
- package/dist/hooks/form-state/use-form-field.js +11 -0
- package/dist/hooks/form-state/use-form-field.js.map +7 -0
- package/dist/hooks/form-state/use-watch.d.ts +12 -0
- package/dist/hooks/form-state/use-watch.js +7 -0
- package/dist/hooks/form-state/use-watch.js.map +7 -0
- package/dist/hooks/index.d.ts +7 -0
- package/dist/hooks/index.js +78 -0
- package/dist/hooks/index.js.map +7 -0
- package/dist/hooks/is-element-required.d.ts +5 -0
- package/dist/hooks/is-element-required.js +6 -0
- package/dist/hooks/is-element-required.js.map +7 -0
- package/dist/hooks/use-debounce.d.ts +14 -0
- package/dist/hooks/use-debounce.js +8 -0
- package/dist/hooks/use-debounce.js.map +7 -0
- package/dist/hooks/use-field.d.ts +44 -0
- package/dist/hooks/use-field.js +16 -0
- package/dist/hooks/use-field.js.map +7 -0
- package/dist/hooks/use-form-context.d.ts +63 -0
- package/dist/hooks/use-form-context.js +18 -0
- package/dist/hooks/use-form-context.js.map +7 -0
- package/dist/hooks/use-mobile.d.ts +9 -0
- package/dist/hooks/use-mobile.js +6 -0
- package/dist/hooks/use-mobile.js.map +7 -0
- package/dist/index.d.ts +2 -0
- package/dist/index.js +43 -0
- package/dist/index.js.map +7 -0
- package/dist/lib/logger.d.ts +2 -0
- package/dist/lib/object-identity.d.ts +6 -0
- package/dist/primitives.d.ts +28 -0
- package/dist/primitives.js +37 -0
- package/dist/primitives.js.map +7 -0
- package/package.json +139 -3
- package/skill/SKILL.md +79 -0
- package/skill/reference/forms-react-widgets.md +222 -0
- package/skill/reference/forms-react.md +92 -0
|
@@ -0,0 +1,222 @@
|
|
|
1
|
+
# Writing a React widget
|
|
2
|
+
|
|
3
|
+
Task: add or change a field widget for the React renderer, and test it. A widget is the render function of an element registration; the engine owns the state, so a widget only reads the field's status and hands the user's changes back. Registering it (`defineInput`) is in `forms.md`; the config shape and the container are there too.
|
|
4
|
+
|
|
5
|
+
Call `useFormField` with the config the widget receives. It returns the field's status (`error`, `warning`, `invalid`, `issue`, `isTouched`, `isDirty`, `isValidating`), `required` and `disabled` (a `require` constraint counts), and the props of the label, the error and the control: `labelProps`, `errorProps` (`null` while there is no text to show), `containerStyles` and `fieldProps`. Give every element an `id`: the label and the error are tied to the control by it.
|
|
6
|
+
|
|
7
|
+
## Uncontrolled or controlled
|
|
8
|
+
|
|
9
|
+
| The widget renders | Call | The field re-renders |
|
|
10
|
+
| -------------------------------------------------------------------------------------------- | -------------------------------------------- | ---------------------------------------------------- |
|
|
11
|
+
| A real `input`, `select` or `textarea` (or a native checkbox, radio, file) | `useFormField(config)` | For an error, warning or flag; never for a keystroke |
|
|
12
|
+
| A component that takes only `value` and `onChange` (Radix, Base UI, a date picker, your own) | `useFormField(config, { controlled: true })` | Whenever the value changes |
|
|
13
|
+
|
|
14
|
+
**Uncontrolled is the default.** The control keeps its own text. Spread `fieldProps` on it (`ref`, `id`, `name`, `required`, `disabled`, `readOnly`, `aria-invalid`, `aria-describedby`, `onChange`, `onBlur`) and give it `defaultValue`, frozen when the field mounts and the server's value while the form hydrates. A checkbox takes `defaultChecked={Boolean(defaultValue)}`, and each radio of a group takes `defaultChecked={defaultValue === option}` with `fieldProps` first and its own `id` after. `fieldText(defaultValue)` makes a string of any default. The form reads what the user did from the control (text from `.value`, a checkbox from `.checked`, a number from `valueAsNumber`, a `select multiple` from its selected options, a file input from its files) and, when the container changes (a reset, `setValue`, a row update), writes it back into the control only if it differs, so the cursor and an IME composition are left alone.
|
|
15
|
+
|
|
16
|
+
```tsx title="react/text-field.tsx"
|
|
17
|
+
import * as z from 'zod/mini';
|
|
18
|
+
import { defineInput, BaseFieldSchema } from '@schema-engine/forms';
|
|
19
|
+
import { fieldText, useFormField } from '@schema-engine/forms-react/hooks';
|
|
20
|
+
|
|
21
|
+
const TextFieldSchema = z.extend(BaseFieldSchema, {
|
|
22
|
+
$type: z.literal('text'),
|
|
23
|
+
inputType: z._default(z.enum(['text', 'email']), 'text'),
|
|
24
|
+
});
|
|
25
|
+
|
|
26
|
+
function TextField(config: z.output<typeof TextFieldSchema>) {
|
|
27
|
+
const { defaultValue, error, fieldProps, labelProps, errorProps } = useFormField(config);
|
|
28
|
+
return (
|
|
29
|
+
<div>
|
|
30
|
+
<label {...labelProps}>{config.label}</label>
|
|
31
|
+
<input {...fieldProps} type={config.inputType} defaultValue={fieldText(defaultValue)} />
|
|
32
|
+
{errorProps && <p {...errorProps}>{error}</p>}
|
|
33
|
+
</div>
|
|
34
|
+
);
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
export const textFieldRegistration = defineInput({
|
|
38
|
+
$type: 'text',
|
|
39
|
+
schema: TextFieldSchema,
|
|
40
|
+
metadata: { name: 'Text', category: 'input' },
|
|
41
|
+
value: () => z.string(),
|
|
42
|
+
render: TextField,
|
|
43
|
+
});
|
|
44
|
+
```
|
|
45
|
+
|
|
46
|
+
**Controlled** adds `value`, `onChange(value)` and `onBlur()`. `fieldProps` has no change handler, and its `ref` still serves focus. A controlled widget that is not a native control puts `ref` where focus should land and nothing else.
|
|
47
|
+
|
|
48
|
+
```tsx title="react/rating-field.tsx"
|
|
49
|
+
import * as z from 'zod/mini';
|
|
50
|
+
import { defineInput, BaseFieldSchema } from '@schema-engine/forms';
|
|
51
|
+
import { useFormField } from '@schema-engine/forms-react/hooks';
|
|
52
|
+
|
|
53
|
+
const RatingFieldSchema = z.extend(BaseFieldSchema, {
|
|
54
|
+
$type: z.literal('rating'),
|
|
55
|
+
max: z._default(z.number().check(z.int(), z.positive()), 5),
|
|
56
|
+
});
|
|
57
|
+
|
|
58
|
+
function StarRating(props: { value: number; max: number; onChange: (value: number) => void; onBlur: () => void }) {
|
|
59
|
+
return Array.from({ length: props.max }, (_, index) => (
|
|
60
|
+
<button
|
|
61
|
+
key={index}
|
|
62
|
+
type="button"
|
|
63
|
+
aria-pressed={props.value === index + 1}
|
|
64
|
+
aria-label={`${index + 1} stars`}
|
|
65
|
+
onClick={() => props.onChange(index + 1)}
|
|
66
|
+
onBlur={props.onBlur}
|
|
67
|
+
/>
|
|
68
|
+
));
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
function RatingField(config: z.output<typeof RatingFieldSchema>) {
|
|
72
|
+
const { value, onChange, onBlur, fieldProps, labelProps } = useFormField(config, { controlled: true });
|
|
73
|
+
const { ref, 'aria-invalid': invalid } = fieldProps;
|
|
74
|
+
return (
|
|
75
|
+
<fieldset ref={ref} aria-invalid={invalid}>
|
|
76
|
+
<legend id={labelProps.htmlFor}>{config.label}</legend>
|
|
77
|
+
<StarRating value={Number(value) || 0} max={config.max} onChange={onChange} onBlur={onBlur} />
|
|
78
|
+
</fieldset>
|
|
79
|
+
);
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
export const ratingFieldRegistration = defineInput({
|
|
83
|
+
$type: 'rating',
|
|
84
|
+
schema: RatingFieldSchema,
|
|
85
|
+
metadata: { name: 'Rating', category: 'input' },
|
|
86
|
+
value: (config) => z.number().check(z.int(), z.gte(1), z.lte(config.max)),
|
|
87
|
+
render: RatingField,
|
|
88
|
+
});
|
|
89
|
+
```
|
|
90
|
+
|
|
91
|
+
## Native facts
|
|
92
|
+
|
|
93
|
+
What a control says about its own value reaches the container as a native fact, and it counts in `validate` and `checkValidity`. A native `input`, `select` or `textarea` contributes one by default: its `validity` (`valueMissing`, `typeMismatch`, `tooShort`, ...), reported from the element `fieldProps.ref` lands on, after each change, on blur and after each render, in both modes. To contribute none, put `ref` on a wrapper that is not a native control (focus still works, as in the rating above), or leave the constraint attributes (`required`, `min`, `pattern`, a typed `type`) off the control. A fact follows the form's validation timing, and the rule's error wins the display when both fail.
|
|
94
|
+
|
|
95
|
+
## Registering the widget
|
|
96
|
+
|
|
97
|
+
Register the widget with `defineInput` (`forms.md`) and pass it to `createFormEngine({ elements })`. The engine of this package is the one the profile form below renders with; replacing a packaged widget is the same registration under the same `$type`, listed after it, because the last one wins.
|
|
98
|
+
|
|
99
|
+
## Testing a widget
|
|
100
|
+
|
|
101
|
+
Test a widget through the real renderer and the form's own container, not a copy of them. A widget test covers four things: an uncontrolled widget renders zero times per keystroke once dirty, `reset` and `setValue` write back into the control, the error is shown and announced (`aria-invalid`, `aria-describedby` and the alert), and a native control's fact blocks the check. It runs under Testing Library in a browser project.
|
|
102
|
+
|
|
103
|
+
```tsx title="react/text-field.test.tsx"
|
|
104
|
+
import { Profiler, useEffect, type ReactNode } from 'react';
|
|
105
|
+
import { act, render, screen } from '@testing-library/react';
|
|
106
|
+
import { expect, test, vi } from 'vitest';
|
|
107
|
+
import { userEvent } from 'vitest/browser';
|
|
108
|
+
import { FormRenderer } from '@schema-engine/forms-react';
|
|
109
|
+
import { useFormContext, useFormField } from '@schema-engine/forms-react/hooks';
|
|
110
|
+
import { engine } from './engine';
|
|
111
|
+
import { EmailPreview, ResetButton } from './hooks';
|
|
112
|
+
import { profile, ProfileForm } from './profile-form';
|
|
113
|
+
|
|
114
|
+
let form: ReturnType<typeof useFormContext>;
|
|
115
|
+
let emailIssue: ReturnType<typeof useFormField>['issue'];
|
|
116
|
+
|
|
117
|
+
function Probe() {
|
|
118
|
+
const context = useFormContext();
|
|
119
|
+
const email = useFormField('email');
|
|
120
|
+
useEffect(() => {
|
|
121
|
+
form = context;
|
|
122
|
+
emailIssue = email.issue;
|
|
123
|
+
});
|
|
124
|
+
return null;
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
function mount(defaultValues: Record<string, unknown> = {}, extras: ReactNode = null) {
|
|
128
|
+
const onRender = vi.fn();
|
|
129
|
+
render(
|
|
130
|
+
<Profiler id="form" onRender={onRender}>
|
|
131
|
+
<FormRenderer engine={engine} config={profile} defaultValues={defaultValues}>
|
|
132
|
+
<Probe />
|
|
133
|
+
{extras}
|
|
134
|
+
</FormRenderer>
|
|
135
|
+
</Profiler>,
|
|
136
|
+
);
|
|
137
|
+
return { onRender, input: screen.getByRole('textbox', { name: 'Email' }) };
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
test('typing renders the field zero times once it is dirty', async () => {
|
|
141
|
+
const { onRender, input } = mount();
|
|
142
|
+
|
|
143
|
+
await userEvent.type(input, 'a');
|
|
144
|
+
const afterFirst = onRender.mock.calls.length;
|
|
145
|
+
await userEvent.type(input, 'bc');
|
|
146
|
+
|
|
147
|
+
expect(onRender).toHaveBeenCalledTimes(afterFirst);
|
|
148
|
+
expect(form.getValues().email).toBe('abc');
|
|
149
|
+
});
|
|
150
|
+
|
|
151
|
+
test('reset and setValue in code write back into the control', async () => {
|
|
152
|
+
const { input } = mount({ email: 'start@example.com' });
|
|
153
|
+
|
|
154
|
+
await userEvent.type(input, 'x');
|
|
155
|
+
act(() => form.reset());
|
|
156
|
+
expect(input).toHaveValue('start@example.com');
|
|
157
|
+
|
|
158
|
+
act(() => form.setValue('email', 'code@example.com'));
|
|
159
|
+
expect(input).toHaveValue('code@example.com');
|
|
160
|
+
});
|
|
161
|
+
|
|
162
|
+
test('the error is shown, announced, and gone once the value is fixed', async () => {
|
|
163
|
+
const { input } = mount();
|
|
164
|
+
|
|
165
|
+
await act(() => form.validate());
|
|
166
|
+
const alert = screen.getByRole('alert');
|
|
167
|
+
expect(alert).toHaveTextContent('Email is required');
|
|
168
|
+
expect(input).toHaveAttribute('aria-invalid', 'true');
|
|
169
|
+
expect(input).toHaveAttribute('aria-describedby', alert.id);
|
|
170
|
+
|
|
171
|
+
await userEvent.type(input, 'ada@example.com');
|
|
172
|
+
expect(screen.queryByRole('alert')).toBeNull();
|
|
173
|
+
});
|
|
174
|
+
|
|
175
|
+
test('a native control reports what the browser says about its value', async () => {
|
|
176
|
+
const { input } = mount();
|
|
177
|
+
|
|
178
|
+
await userEvent.type(input, 'not an email');
|
|
179
|
+
const result = await act(() => form.validate(['email']));
|
|
180
|
+
|
|
181
|
+
expect(result).toEqual({ outcome: 'invalid' });
|
|
182
|
+
expect(screen.getByRole('alert')).toBeInTheDocument();
|
|
183
|
+
expect(emailIssue?.all).toContainEqual(expect.objectContaining({ type: 'typeMismatch', source: 'native' }));
|
|
184
|
+
});
|
|
185
|
+
|
|
186
|
+
test('a controlled component writes through onChange and follows setValue', async () => {
|
|
187
|
+
mount();
|
|
188
|
+
|
|
189
|
+
await userEvent.click(screen.getByRole('button', { name: '3 stars' }));
|
|
190
|
+
expect(form.getValues().stars).toBe(3);
|
|
191
|
+
|
|
192
|
+
act(() => form.setValue('stars', 5));
|
|
193
|
+
expect(screen.getByRole('button', { name: '5 stars' })).toHaveAttribute('aria-pressed', 'true');
|
|
194
|
+
});
|
|
195
|
+
|
|
196
|
+
test('useWatch follows a value and useFormContext resets the form', async () => {
|
|
197
|
+
const { input } = mount(
|
|
198
|
+
{},
|
|
199
|
+
<>
|
|
200
|
+
<EmailPreview />
|
|
201
|
+
<ResetButton />
|
|
202
|
+
</>,
|
|
203
|
+
);
|
|
204
|
+
|
|
205
|
+
await userEvent.type(input, 'ada@example.com');
|
|
206
|
+
expect(screen.getByRole('status')).toHaveTextContent('ada@example.com');
|
|
207
|
+
|
|
208
|
+
await userEvent.click(screen.getByRole('button', { name: 'Reset' }));
|
|
209
|
+
expect(input).toHaveValue('');
|
|
210
|
+
expect(screen.getByRole('status')).toHaveTextContent('');
|
|
211
|
+
});
|
|
212
|
+
|
|
213
|
+
test('the form renders its fields and the children it is given', () => {
|
|
214
|
+
render(<ProfileForm />);
|
|
215
|
+
|
|
216
|
+
expect(screen.getByRole('textbox', { name: 'Email' })).toBeInTheDocument();
|
|
217
|
+
expect(screen.getByRole('group')).toBeInTheDocument();
|
|
218
|
+
expect(screen.getByRole('button', { name: 'Reset' })).toBeInTheDocument();
|
|
219
|
+
});
|
|
220
|
+
```
|
|
221
|
+
|
|
222
|
+
Save your copy as `text-field.test.tsx`.
|
|
@@ -0,0 +1,92 @@
|
|
|
1
|
+
# @schema-engine/forms-react
|
|
2
|
+
|
|
3
|
+
The React renderer and its hooks. The package renders a normalized form; the field widgets are your code, written by you (`forms-react-widgets.md`) or optionally copied from the shadcn registry.
|
|
4
|
+
|
|
5
|
+
## Setup
|
|
6
|
+
|
|
7
|
+
Install `@schema-engine/forms-react`, `@schema-engine/forms`, `@schema-engine/layout`, `react`, `react-dom` and `zod`. Write your widgets with `useFormField` (`forms-react-widgets.md`) and pass them as `elements`. Build the engine once and reuse it. Optionally, a project that uses shadcn can copy ready-made widgets and recipes with `pnpm dlx shadcn@latest add schema-engine/schema-engine/schema-form schema-engine/schema-engine/schema-engine-form-recipes`: its generated `registrations` barrel is then the list to pass as `elements`, and `recipes/recipes.css` is imported once after Tailwind.
|
|
8
|
+
|
|
9
|
+
```ts title="react/engine.ts"
|
|
10
|
+
import { createFormEngine } from '@schema-engine/forms';
|
|
11
|
+
import { ratingFieldRegistration } from './rating-field';
|
|
12
|
+
import { textFieldRegistration } from './text-field';
|
|
13
|
+
|
|
14
|
+
export const engine = createFormEngine({ elements: [textFieldRegistration, ratingFieldRegistration] });
|
|
15
|
+
```
|
|
16
|
+
|
|
17
|
+
## Rendering
|
|
18
|
+
|
|
19
|
+
`FormRenderer` takes the form and renders it. A plain config is validated at that boundary; pass `engine.defineForm(...)` when you want the typed, normalized one. The engine comes from the `engine` prop or from an enclosing `FormEngineProvider`. Its other props are `defaultValues`, `onSubmit(values, helpers)`, `onChange(values)`, `onAction`, `onActionResults`, `navigate` (where a submit action's `redirectUrl` takes the page, `location.assign` by default), `formatIssue`, `className`, `style` and `children`, which render inside the form so they can use the hooks.
|
|
20
|
+
|
|
21
|
+
```tsx title="react/profile-form.tsx"
|
|
22
|
+
import type { FormSubmitHelpers, FormValues } from '@schema-engine/forms';
|
|
23
|
+
import { FormRenderer } from '@schema-engine/forms-react';
|
|
24
|
+
import { engine } from './engine';
|
|
25
|
+
import { ResetButton } from './hooks';
|
|
26
|
+
|
|
27
|
+
export const profile = engine.defineForm({
|
|
28
|
+
id: 'profile',
|
|
29
|
+
steps: [
|
|
30
|
+
{
|
|
31
|
+
id: 'main',
|
|
32
|
+
title: 'Profile',
|
|
33
|
+
elements: [
|
|
34
|
+
{
|
|
35
|
+
$type: 'text',
|
|
36
|
+
id: 'email',
|
|
37
|
+
name: 'email',
|
|
38
|
+
label: 'Email',
|
|
39
|
+
inputType: 'email',
|
|
40
|
+
rules: [{ $type: 'required', message: 'Email is required' }],
|
|
41
|
+
},
|
|
42
|
+
{ $type: 'rating', id: 'stars', name: 'stars', label: 'Stars' },
|
|
43
|
+
],
|
|
44
|
+
},
|
|
45
|
+
],
|
|
46
|
+
});
|
|
47
|
+
|
|
48
|
+
async function save(values: FormValues, { fetch }: FormSubmitHelpers) {
|
|
49
|
+
await fetch('/api/profile', { method: 'POST', body: JSON.stringify(values) });
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
export function ProfileForm() {
|
|
53
|
+
return (
|
|
54
|
+
<FormRenderer engine={engine} config={profile} onSubmit={save}>
|
|
55
|
+
<ResetButton />
|
|
56
|
+
</FormRenderer>
|
|
57
|
+
);
|
|
58
|
+
}
|
|
59
|
+
```
|
|
60
|
+
|
|
61
|
+
The form's runtime and container are created once per form instance, and their lifetime follows the identity of the config passed in: a new config starts a fresh form with its defaults and step state. The hooks read the container through its selectors, so a field re-renders only for its own value, error or flags, and a parent render alone calls neither `onChange` nor a `form_change` action. Import every hook from `@schema-engine/forms-react/hooks`.
|
|
62
|
+
|
|
63
|
+
## The four hooks
|
|
64
|
+
|
|
65
|
+
- `useFormField(config)` binds a widget to one field. It is uncontrolled by default; `useFormField(config, { controlled: true })` is for a component that takes only `value` and `onChange`; `useFormField(path)` is the state of a path with no value. How to choose, and what each returns, is in `forms-react-widgets.md`.
|
|
66
|
+
- `useFormContext()` returns the commands over the form: `getValues()`, `setValue(name, value)`, `validate(name?)` (a path or several, resolving `{ outcome }`), `reset(values?)`, `setFocus(name)`, `formatIssue(issue, { path })` and `clearSubmission()`. Its `formState` is lazy: `errors`, `isValid` (the recorded errors, validating nothing) and `submission` (`status`, `failures`, `submitCount`). A component re-renders only for the keys it reads.
|
|
67
|
+
- `useWatch()` reads every value, `useWatch(path)` one and `useWatch([paths])` a list, and re-renders only when what it reads changes.
|
|
68
|
+
- `useFieldArray(name)` returns `fields` (one `{ id }` per row, stable through reordering) and `append`, `prepend`, `insert`, `swap`, `move`, `update`, `replace` and `remove`. Rows keep their errors, touched state and ids through every operation, and an operation that adds a row focuses its first control.
|
|
69
|
+
|
|
70
|
+
```tsx title="react/hooks.tsx"
|
|
71
|
+
import { isSubmissionBusy } from '@schema-engine/forms';
|
|
72
|
+
import { useFormContext, useWatch } from '@schema-engine/forms-react/hooks';
|
|
73
|
+
|
|
74
|
+
export function EmailPreview() {
|
|
75
|
+
const email = useWatch('email');
|
|
76
|
+
return <output>{typeof email === 'string' ? email : ''}</output>;
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
export function ResetButton() {
|
|
80
|
+
const { reset, formState } = useFormContext();
|
|
81
|
+
const busy = isSubmissionBusy(formState.submission.status);
|
|
82
|
+
return (
|
|
83
|
+
<button type="button" onClick={() => reset()} disabled={busy}>
|
|
84
|
+
Reset
|
|
85
|
+
</button>
|
|
86
|
+
);
|
|
87
|
+
}
|
|
88
|
+
```
|
|
89
|
+
|
|
90
|
+
For a wizard, `useFormInstanceActions()` exposes `current` (the step id), `steps`, `navigating` and `next()`, `back()` and `goTo(id)`. `useFormEngine()` reads the engine the provider supplied. Recipe blocks read the active view with `useViewContext`, `useActiveStep`, `useFormNavigation` and `useViewConfig`.
|
|
91
|
+
|
|
92
|
+
`useFormRuntime()` gives the runtime of the form the component sits in, which `registerFormAgentTool` takes (`forms.md`).
|