@whatsaaaa/form-builder-react 0.0.0 → 0.2.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 Whatsaaaa
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 ADDED
@@ -0,0 +1,374 @@
1
+ # @whatsaaaa/form-builder-react
2
+
3
+ [![npm](https://img.shields.io/npm/v/@whatsaaaa/form-builder-react)](https://www.npmjs.com/package/@whatsaaaa/form-builder-react)
4
+
5
+ Render JSON form definitions with [Formisch](https://formisch.dev) and your own React components.
6
+
7
+ It's headless: it reads the definition, connects every field to Formisch and turns input into the values the schema expects, but it renders nothing of its own. You give it a component per field type, so it works with plain HTML, shadcn/ui or any other UI library.
8
+
9
+ ## Install
10
+
11
+ ```sh
12
+ pnpm add @whatsaaaa/form-builder-react @formisch/react valibot
13
+ ```
14
+
15
+ React 18 or 19, `@formisch/react` 1.2 and Valibot 1.4.1 or later are required. `@whatsaaaa/form-builder-schema` comes with it.
16
+
17
+ ## Usage
18
+
19
+ ```tsx
20
+ import { Form } from '@formisch/react'
21
+ import type { JsonForm } from '@whatsaaaa/form-builder-schema'
22
+ import { JsonFields, useJsonForm } from '@whatsaaaa/form-builder-react'
23
+ import { components } from './fields'
24
+
25
+ export function DefinitionForm({ definition }: { definition: JsonForm }) {
26
+ const jsonForm = useJsonForm(definition, { components })
27
+
28
+ function save(output: unknown) {
29
+ // The output of the schema: trimmed, numbers as numbers, empty optional fields left out.
30
+ }
31
+
32
+ return (
33
+ <Form of={jsonForm.form} onSubmit={save}>
34
+ <JsonFields of={jsonForm} />
35
+ <button type="submit">Save</button>
36
+ </Form>
37
+ )
38
+ }
39
+ ```
40
+
41
+ - `useJsonForm(definition, options?)` builds the schema and the initial input, and creates the Formisch form. `jsonForm.form` is a normal Formisch form, so every Formisch method works on it.
42
+ - `<JsonFields>` renders the fields inside your `<Form>`. The form element, the submit button and anything around them are yours.
43
+ - A definition with issues throws the builder's `DefinitionError` while rendering, so an error boundary can catch it. Run `validate()` first when the definition comes from outside your code.
44
+ - Like Formisch's `useForm`, `useJsonForm` reads the definition on the first render. To show another one, give the component that calls `useJsonForm` a new `key`: `<DefinitionForm key={id} definition={definition} />`.
45
+
46
+ ### Options
47
+
48
+ ```ts
49
+ useJsonForm(definition, {
50
+ builder: createSchemaBuilder({ fieldTypes: { money } }), // your own types, rules and messages
51
+ components, // your component per field type, see below
52
+ layoutComponents, // your component per layout type, see Layout
53
+ validate: 'blur', // when a field is validated the first time, as in Formisch
54
+ revalidate: 'input', // when it is validated again
55
+ })
56
+ ```
57
+
58
+ `builder`, `validate` and `revalidate` are read on the first render, with the definition. `components` and `layoutComponents` are read on every render.
59
+
60
+ ## Components
61
+
62
+ `components` has one component per field type, by type name. Pass it to `useJsonForm`, or to `<JsonFields>` and `<JsonField>` as a prop, which wins. Several types can share one:
63
+
64
+ ```ts
65
+ import type { FieldComponents } from '@whatsaaaa/form-builder-react'
66
+
67
+ export const components: FieldComponents = {
68
+ text: TextInput,
69
+ email: TextInput,
70
+ number: TextInput,
71
+ select: SelectInput,
72
+ group: Fieldset,
73
+ array: Repeater,
74
+ heading: Heading,
75
+ // …one for every type your definitions use
76
+ }
77
+ ```
78
+
79
+ A type that a definition uses but `components` doesn't have throws a `TypeError` that names every missing type, when `<JsonFields>` or `<JsonField>` renders. Only the fields it renders count.
80
+
81
+ What a component gets depends on the field's role:
82
+
83
+ | Role | Which fields | Props |
84
+ | ------- | ------------------------------ | -------------------------------------------------------------------------------- |
85
+ | value | every field with a value | `field`, `path`, `kind`, `required`, `input`, `errors`, `inputProps`, `setInput` |
86
+ | group | a container of kind `object` | `field`, `path`, `children`: the group's fields |
87
+ | array | a container of kind `array` | `field`, `path`, `items`, `errors`, `add`, `remove`, `move`, `children(index)` |
88
+ | display | a display element, kind `none` | `field` |
89
+
90
+ The props are typed as `ValueFieldProps`, `GroupFieldProps`, `ArrayFieldProps` and `DisplayFieldProps`.
91
+
92
+ Your own container types render through the group or array role too, by their kind.
93
+
94
+ ### A value field
95
+
96
+ ```tsx
97
+ import type { ValueFieldProps } from '@whatsaaaa/form-builder-react'
98
+
99
+ export function TextInput({ field, kind, input, errors, inputProps, ...props }: ValueFieldProps) {
100
+ return (
101
+ <label>
102
+ {field.label}
103
+ <input
104
+ {...inputProps}
105
+ type={kind === 'number' ? 'number' : 'text'}
106
+ value={String(input ?? '')}
107
+ required={props.required}
108
+ onChange={(e) => props.setInput(e.target.value)}
109
+ />
110
+ {errors && <small>{errors[0]}</small>}
111
+ </label>
112
+ )
113
+ }
114
+ ```
115
+
116
+ - `field` is the field from the definition, with its `label`, `placeholder`, `options` and `ui`.
117
+ - `path` is its Formisch path with real indexes, like `['lines', 0, 'quantity']`.
118
+ - `inputProps` are Formisch's element props: the field's name, a ref, and focus, change and blur handlers. Spread them on the input element, so Formisch knows when the field is touched and can focus it after a failed submit. Your own `onChange` after the spread replaces Formisch's, and calls `setInput` instead.
119
+ - `required` is true when the definition makes the field required.
120
+
121
+ ### setInput
122
+
123
+ `setInput` sets the field's input after turning what an input element gives into what the schema expects, by the field's kind:
124
+
125
+ | Kind | Input | Value set |
126
+ | ------------------- | ----------------------- | ------------------------------ |
127
+ | `number` | `''` or only spaces | `undefined` |
128
+ | `number` | a numeric string, `'5'` | `5` |
129
+ | `file` | a `FileList` | its first file, or `undefined` |
130
+ | `array` of `file` | a `FileList` | an array of its files |
131
+ | `array` of `number` | numeric strings | numbers |
132
+
133
+ Anything else is set as it is, and the schema reports it. For a choice, like a radio or a select, set the option's value from `field.options` rather than the element's value: that keeps `2` a number and `true` a boolean.
134
+
135
+ ```tsx
136
+ const options = field.options as { value: string | number | boolean; label: string }[]
137
+
138
+ <select
139
+ {...inputProps}
140
+ value={options.findIndex((option) => option.value === input)}
141
+ onChange={(e) => setInput(options[Number(e.target.value)]?.value)}
142
+ >
143
+ <option value={-1}>Choose…</option>
144
+ {options.map((option, i) => (
145
+ <option key={i} value={i}>
146
+ {option.label}
147
+ </option>
148
+ ))}
149
+ </select>
150
+ ```
151
+
152
+ For a file input, pass the element's `files` with `onChange={(e) => setInput(e.target.files)}`, and never set its `value`.
153
+
154
+ `setInput` stays the same function while the field is the same, so it is safe in an effect's or a memo's dependencies.
155
+
156
+ ### A group
157
+
158
+ ```tsx
159
+ import type { GroupFieldProps } from '@whatsaaaa/form-builder-react'
160
+
161
+ export function Fieldset({ field, children }: GroupFieldProps) {
162
+ return (
163
+ <fieldset>
164
+ <legend>{field.label}</legend>
165
+ {children}
166
+ </fieldset>
167
+ )
168
+ }
169
+ ```
170
+
171
+ ### An array
172
+
173
+ ```tsx
174
+ import type { ArrayFieldProps } from '@whatsaaaa/form-builder-react'
175
+
176
+ export function Repeater({ field, items, errors, add, remove, children }: ArrayFieldProps) {
177
+ return (
178
+ <fieldset>
179
+ <legend>{field.label}</legend>
180
+ {items.map((item, index) => (
181
+ <div key={item}>
182
+ {children(index)}
183
+ <button type="button" onClick={() => remove(index)}>
184
+ Remove
185
+ </button>
186
+ </div>
187
+ ))}
188
+ <button type="button" onClick={add}>
189
+ Add
190
+ </button>
191
+ {errors && <small>{errors[0]}</small>}
192
+ </fieldset>
193
+ )
194
+ }
195
+ ```
196
+
197
+ - `children(index)` renders the fields of the item at `index`.
198
+ - `items` has one id per item. Use it as the `key`, so each item keeps its inputs when one is removed or moved.
199
+ - `add()` adds an item at the end, with the defaults its fields have in the definition.
200
+ - `errors` are the array's own messages, like a required array's or `maxLength`'s. Its items' fields show their own.
201
+
202
+ ### A display element
203
+
204
+ ```tsx
205
+ import type { DisplayFieldProps } from '@whatsaaaa/form-builder-react'
206
+
207
+ export function Heading({ field }: DisplayFieldProps) {
208
+ return <h2>{String(field.text ?? '')}</h2>
209
+ }
210
+ ```
211
+
212
+ ## Layout
213
+
214
+ A definition's [`layout`](https://github.com/whatsaaaa/form-builder/tree/main/packages/schema#layout) puts its fields in sections, rows of a 12-column grid and steps, and leaves slots for content of yours. `<JsonFields>` renders the current step of it. Give `useJsonForm` a component for each layout type the definition uses, and `<JsonFields>` the content of its slots:
215
+
216
+ ```tsx
217
+ import type { LayoutComponents, RowProps, SectionProps } from '@whatsaaaa/form-builder-react'
218
+
219
+ function Section({ section, children }: SectionProps) {
220
+ return (
221
+ <fieldset>
222
+ <legend>{section.label}</legend>
223
+ {children}
224
+ </fieldset>
225
+ )
226
+ }
227
+
228
+ // One line of a 12-column grid. On a narrow screen, give each cell the whole row.
229
+ function Row({ spans, children }: RowProps) {
230
+ return (
231
+ <div className="row">
232
+ {spans.map((span, index) => (
233
+ <div key={index} style={{ gridColumn: `span ${span}` }}>
234
+ {children(index)}
235
+ </div>
236
+ ))}
237
+ </div>
238
+ )
239
+ }
240
+
241
+ const layoutComponents: LayoutComponents = { section: Section, row: Row }
242
+
243
+ function Checkout({ definition }: { definition: JsonForm }) {
244
+ const jsonForm = useJsonForm(definition, { components, layoutComponents })
245
+ return (
246
+ <Form of={jsonForm.form} onSubmit={save}>
247
+ <JsonFields of={jsonForm} slots={{ submit: <button type="submit">Place order</button> }} />
248
+ </Form>
249
+ )
250
+ }
251
+ ```
252
+
253
+ ```css
254
+ .row {
255
+ display: grid;
256
+ grid-template-columns: repeat(12, 1fr);
257
+ gap: 1rem;
258
+ }
259
+ ```
260
+
261
+ | Layout type | Props |
262
+ | ----------- | ------------------------------------------------------------------------------------------------------------------------ |
263
+ | `section` | `section`, as written, with its `id`, `label`, `description` and `ui`; `children` |
264
+ | `row` | `row`, as written, with its `id` and `ui`; `spans`, the span of each cell; `children(index)` renders the cell at `index` |
265
+
266
+ - `layoutComponents` goes to `useJsonForm`, or to `<JsonFields>` as a prop, which wins. A definition without sections or rows needs none, and one without a `layout` renders as it always did.
267
+ - A layout type the layout uses without a component, or a slot without content in `slots`, throws a `TypeError` naming each one, on every step.
268
+ - Display elements written in the layout render with your field components, like the ones in `fields`.
269
+ - `except` leaves fields out of the layout too, and a section or a row left without fields drops out. The other cells of a row keep their spans. `only` renders the fields it names without the layout.
270
+ - The spans are for a wide screen: the layout says nothing about narrow ones, so your row component decides, e.g. with a media query.
271
+
272
+ ### Steps
273
+
274
+ `jsonForm.steps` is where the form is, and how to move:
275
+
276
+ ```tsx
277
+ function Signup({ definition }: { definition: JsonForm }) {
278
+ const jsonForm = useJsonForm(definition, { components, layoutComponents })
279
+ const { steps } = jsonForm
280
+ return (
281
+ <Form of={jsonForm.form} onSubmit={save}>
282
+ <ol>
283
+ {steps.list.map((step, i) => (
284
+ <li key={step.step.id ?? i} aria-current={i === steps.index ? 'step' : undefined}>
285
+ {step.step.label}
286
+ </li>
287
+ ))}
288
+ </ol>
289
+ <JsonFields of={jsonForm} />
290
+ {!steps.isFirst && (
291
+ <button type="button" onClick={steps.back}>
292
+ Back
293
+ </button>
294
+ )}
295
+ {steps.isLast ? (
296
+ <button type="submit">Sign up</button>
297
+ ) : (
298
+ <button type="button" onClick={() => void steps.next()}>
299
+ Next
300
+ </button>
301
+ )}
302
+ </Form>
303
+ )
304
+ }
305
+ ```
306
+
307
+ | Member | |
308
+ | ------------------- | ---------------------------------------------------------------------------------------------------- |
309
+ | `list` | every step, with its `step` as written (`id`, `label`, `description`, `ui`), `children` and `fields` |
310
+ | `index`, `current` | the step `<JsonFields>` renders |
311
+ | `isFirst`, `isLast` | |
312
+ | `next()` | validates, and moves on when the step's fields have no issues. Resolves to whether it moved |
313
+ | `back()` | moves back, without validating |
314
+ | `goTo(index)` | back freely; forward through each step on the way, stopping at the first with issues |
315
+
316
+ The form is one Formisch form, so Formisch validates all of it at once. The steps make that work:
317
+
318
+ - **Next** validates the whole form, and only the issues on the current step's fields keep the user there. It focuses the first one, in layout order.
319
+ - **A step shows what the user left**: the errors it had when they left it, and none the first time they get to it, so the issues of steps nobody saw yet stay out of sight.
320
+ - **A step that failed Next revalidates** as the user fixes it, on the `revalidate` event, like a form after a failed submit.
321
+ - **A submit before the last step is a Next**, so Enter in a step with a single text input doesn't submit the form early. On the last step, Formisch submits as usual.
322
+ - **A submit that fails because of an earlier step**, like a form rule that reads fields of two steps, goes back to that step.
323
+ - `<JsonFields step={2} />` renders a given step instead of the current one, e.g. on a review page. A form without steps has one, and nothing changes for it.
324
+
325
+ ## Placing fields yourself
326
+
327
+ Without a `layout`, `<JsonFields>` renders every field in the order of the definition. To put some of them somewhere else, in code rather than in the definition, place them with `<JsonField>` and leave them out of `<JsonFields>` with `except`:
328
+
329
+ ```tsx
330
+ <Form of={jsonForm.form} onSubmit={save}>
331
+ <main>
332
+ <JsonFields of={jsonForm} except={['coupon', 'acceptTerms']} />
333
+ </main>
334
+ <aside>
335
+ <JsonField of={jsonForm} path="coupon" />
336
+ <JsonField of={jsonForm} path="acceptTerms" />
337
+ <button type="submit">Place order</button>
338
+ </aside>
339
+ </Form>
340
+ ```
341
+
342
+ - A path is the field's names joined with dots: `'email'`, or `'address.city'` for a field of a group. A placed field validates, focuses and submits like any other, because it is still part of the one Formisch form.
343
+ - A group or an array comes with all its fields. A field of an array's items can't be placed on its own, because it has no index outside its item, so place the array. To leave such a field out of every item, use `'*'` for the index: `except={['lines.*.note']}`.
344
+ - `only` renders just the fields it names, in the order of the definition: `<JsonFields of={jsonForm} only={['name', 'email']} />`. Display elements have no dot path, even with a name, so `only` leaves them out.
345
+ - A path that names no field throws a `TypeError`, so a typo shows up at once. `only` and `except` are read on every render, so they can change, and a field keeps what was typed while it is hidden.
346
+
347
+ ## Typing the form
348
+
349
+ The definition is data, so TypeScript doesn't know its fields, and `jsonForm.form` is typed loosely: Formisch's own functions accept only top-level paths on it. Give `useJsonForm` your input type, and your output type when it differs, and they check paths and values as in any Formisch form:
350
+
351
+ ```ts
352
+ import { getInput, useFieldArray } from '@formisch/react'
353
+
354
+ interface CheckoutInput {
355
+ name: string
356
+ address: { city: string }
357
+ lines: { product: string; quantity: number }[]
358
+ }
359
+
360
+ const jsonForm = useJsonForm<CheckoutInput>(definition, { components })
361
+
362
+ getInput(jsonForm.form, { path: ['address', 'city'] }) // string | undefined
363
+ useFieldArray(jsonForm.form, { path: ['lines'] })
364
+ ```
365
+
366
+ - Formisch's `<Field>`, `<FieldArray>`, `useField`, `getInput` and `setInput` work on `jsonForm.form` either way. With a type, nested paths type-check, their values are typed, and so is the output your submit handler gets.
367
+ - The type is a promise you make: nothing checks it against the definition. Keep the two in step.
368
+ - A field you render with Formisch's `<Field>` gets none of the adapter's help, like `setInput` turning `'5'` into `5`, or the defaults of a new array item. Leave it out of `<JsonFields>` with `except`.
369
+
370
+ ## Not included
371
+
372
+ - Labels and display text reach your components as written in the definition. The builder's `resolveMessage` only changes what goes into the schema, so translate `field.label` in your components.
373
+ - `ui.widget` doesn't pick a component. A component can read `field.ui` itself, e.g. to show a multiselect as checkboxes.
374
+ - Showing and hiding fields, or making one required because of another, belongs to a future affects package. The layout already hides a section, a row or a step whose fields are all hidden, through `shownNodes` in the schema package.
@@ -0,0 +1,183 @@
1
+ import { FieldNode, FieldNode as FieldNode$1, FieldPath, FieldPath as FieldPath$1, FieldRole, FormLayout, FormLayout as FormLayout$1, JsonField as JsonField$1, JsonForm, JsonFormSchema, JsonFormSchema as JsonFormSchema$1, JsonLayoutRow, JsonLayoutSection, LayoutNode, LayoutStep, LayoutStep as LayoutStep$1, SchemaBuilder, TypedJsonFormSchema, TypedJsonFormSchema as TypedJsonFormSchema$1, ValueKind } from "@whatsaaaa/form-builder-schema";
2
+ import { FieldElementProps, FormSchema, FormStore, ValidationMode } from "@formisch/react";
3
+ import { ComponentType, ReactElement, ReactNode } from "react";
4
+ /**
5
+ * Your component for each field type, by type name: `{ text: TextInput, group: Fieldset }`. Each
6
+ * one takes the props of the role its type has.
7
+ */
8
+ type FieldComponents = Record<string, ComponentType<ValueFieldProps> | ComponentType<GroupFieldProps> | ComponentType<ArrayFieldProps> | ComponentType<DisplayFieldProps>>;
9
+ /** The props of a component for a display element, like a heading. */
10
+ interface DisplayFieldProps {
11
+ field: JsonField$1;
12
+ }
13
+ /** The props of a component for a field with a value. */
14
+ interface ValueFieldProps {
15
+ field: JsonField$1;
16
+ path: FieldPath$1;
17
+ /** The kind of the value, e.g. `'number'`. */
18
+ kind: ValueKind;
19
+ /** True when the definition makes the field required. */
20
+ required: boolean;
21
+ /** The field's current input. */
22
+ input: unknown;
23
+ /** The field's error messages, or null when it has none. */
24
+ errors: [string, ...string[]] | null;
25
+ /** Spread these on the input element: its name, ref, and focus, change and blur handlers. */
26
+ inputProps: FieldElementProps;
27
+ /** Sets the input, after turning `'5'` into `5` for a number, or a `FileList` into files. */
28
+ setInput: (input: unknown) => void;
29
+ }
30
+ /** The props of a component for a container of kind `object`, like the built-in group. */
31
+ interface GroupFieldProps {
32
+ field: JsonField$1;
33
+ path: FieldPath$1;
34
+ /** The group's fields. */
35
+ children: ReactNode;
36
+ }
37
+ /** The props of a component for a container of kind `array`, like the built-in array. */
38
+ interface ArrayFieldProps {
39
+ field: JsonField$1;
40
+ path: FieldPath$1;
41
+ /** One id per item, to use as its `key`. */
42
+ items: string[];
43
+ /** The array's own error messages, e.g. from `maxLength`, or null. */
44
+ errors: [string, ...string[]] | null;
45
+ /** Adds an item at the end. */
46
+ add: () => void;
47
+ remove: (index: number) => void;
48
+ move: (from: number, to: number) => void;
49
+ /** Renders the fields of the item at `index`. */
50
+ children: (index: number) => ReactNode;
51
+ }
52
+ /**
53
+ * Your component for each layout type a definition's `layout` uses: `{ section: Card, row: Grid }`.
54
+ * A definition without sections or rows needs none.
55
+ */
56
+ interface LayoutComponents {
57
+ section?: ComponentType<SectionProps>;
58
+ row?: ComponentType<RowProps>;
59
+ }
60
+ /** The props of a component for a section of the layout. */
61
+ interface SectionProps {
62
+ /** The section as written, with its `id`, `label`, `description` and `ui`. */
63
+ section: JsonLayoutSection;
64
+ /** The section's items. */
65
+ children: ReactNode;
66
+ }
67
+ /** The props of a component for a row of the layout: one line of a 12-column grid. */
68
+ interface RowProps {
69
+ /** The row as written, with its `id` and `ui`. */
70
+ row: JsonLayoutRow;
71
+ /** How many of the 12 columns each cell takes, in order. They add up to 12 at most. */
72
+ spans: number[];
73
+ /** Renders the cell at `index`. */
74
+ children: (index: number) => ReactNode;
75
+ }
76
+ /** The steps of a form, from its layout. A form without `steps` in its layout has one. */
77
+ interface JsonFormSteps {
78
+ /** Every step, in order. */
79
+ readonly list: readonly LayoutStep$1[];
80
+ /** The index of the current step in `list`. */
81
+ readonly index: number;
82
+ /** The step `<JsonFields>` renders. */
83
+ readonly current: LayoutStep$1;
84
+ readonly isFirst: boolean;
85
+ readonly isLast: boolean;
86
+ /**
87
+ * Validates the whole form, and moves to the next step when the fields of this one have no
88
+ * issues. Otherwise it stays, and focuses the first field with an issue, in layout order.
89
+ * Resolves to whether it moved.
90
+ */
91
+ next(): Promise<boolean>;
92
+ /** Moves to the step before, without validating. */
93
+ back(): void;
94
+ /**
95
+ * Moves to the step at `index`. Back is free, and forward validates every step on the way, like
96
+ * `next()`, and stops at the first with issues. Resolves to whether it got there.
97
+ */
98
+ goTo(index: number): Promise<boolean>;
99
+ }
100
+ interface UseJsonFormOptions {
101
+ /** Builds the schema and knows your own types and rules. Defaults to `createSchemaBuilder()`. */
102
+ builder?: SchemaBuilder;
103
+ /** Your component for each field type, so `<JsonFields>` and `<JsonField>` don't need them. */
104
+ components?: FieldComponents;
105
+ /** Your component for each layout type the definition's `layout` uses, like `section`. */
106
+ layoutComponents?: LayoutComponents;
107
+ /** When a field is validated the first time, as in Formisch. */
108
+ validate?: ValidationMode;
109
+ /** When a field is validated again after that, as in Formisch. */
110
+ revalidate?: Exclude<ValidationMode, 'initial'>;
111
+ }
112
+ /** What `useJsonForm` returns. Pass it to `<JsonFields>`. */
113
+ interface JsonFormInstance<TSchema extends FormSchema = JsonFormSchema$1> {
114
+ /** The Formisch form: pass it to Formisch's `<Form of>`, or to any of its methods. */
115
+ readonly form: FormStore<TSchema>;
116
+ readonly definition: JsonForm;
117
+ readonly builder: SchemaBuilder;
118
+ /** The components from the options, if any. */
119
+ readonly components: FieldComponents | undefined;
120
+ /** The layout components from the options, if any. */
121
+ readonly layoutComponents: LayoutComponents | undefined;
122
+ /** The definition's fields as a tree, for `<JsonFields only>` and `<JsonField>`. */
123
+ readonly fields: readonly FieldNode$1[];
124
+ /** The definition's layout, the way `<JsonFields>` renders it. */
125
+ readonly layout: FormLayout$1;
126
+ /** The layout's steps: the current one, and Next, Back and Go to. A form without steps has one. */
127
+ readonly steps: JsonFormSteps;
128
+ }
129
+ /** Any form `useJsonForm` returns, typed or not: what the components take. */
130
+ type AnyJsonFormInstance = JsonFormInstance<FormSchema>;
131
+ /**
132
+ * A Formisch form for a definition, with its schema and initial input from the builder. A
133
+ * definition with issues throws the builder's `DefinitionError`, so run `validate()` first when it
134
+ * comes from outside your code. Like Formisch's `useForm`, it reads the definition, the builder and
135
+ * the validation modes on the first render: give the component a new `key` to use another
136
+ * definition. The components and layout components are read on every render.
137
+ */
138
+ export declare function useJsonForm(definition: JsonForm, options?: UseJsonFormOptions): JsonFormInstance;
139
+ /**
140
+ * The same, with the form typed by your input type, and output type when it differs, so Formisch's
141
+ * paths and values are checked. The types are yours to keep in step with the definition.
142
+ */
143
+ export declare function useJsonForm<TInput extends object, TOutput extends object = TInput>(definition: JsonForm, options?: UseJsonFormOptions): JsonFormInstance<TypedJsonFormSchema$1<TInput, TOutput>>;
144
+ interface JsonFieldProps {
145
+ /** What `useJsonForm` returned. */
146
+ of: AnyJsonFormInstance;
147
+ /** The field's path: `'email'`, or `'address.city'` for a field of a group. */
148
+ path: string;
149
+ /** Defaults to the components `useJsonForm` got. */
150
+ components?: FieldComponents | undefined;
151
+ }
152
+ /**
153
+ * Renders one field of a `useJsonForm` form, wherever you put it inside Formisch's `<Form>`. A
154
+ * group or an array comes with its fields. Leave the field out of `<JsonFields>` with `except`.
155
+ */
156
+ export declare function JsonField({ of, path, components }: JsonFieldProps): ReactElement;
157
+ interface JsonFieldsProps {
158
+ /** What `useJsonForm` returned. */
159
+ of: AnyJsonFormInstance;
160
+ /** Defaults to the components `useJsonForm` got. */
161
+ components?: FieldComponents | undefined;
162
+ /** Defaults to the layout components `useJsonForm` got. */
163
+ layoutComponents?: LayoutComponents | undefined;
164
+ /** The content of the layout's slots, by name: `{ submit: <button type="submit">Save</button> }`. */
165
+ slots?: Readonly<Record<string, ReactNode>> | undefined;
166
+ /** Renders only these fields, by path, in the order of the definition, without the layout. */
167
+ only?: readonly string[] | undefined;
168
+ /**
169
+ * Leaves out these fields, by path, e.g. the ones you place with `<JsonField>`. A section or a
170
+ * row left without fields drops out too.
171
+ */
172
+ except?: readonly string[] | undefined;
173
+ /** Renders the step at this index instead of the current one, e.g. on a review page. */
174
+ step?: number | undefined;
175
+ }
176
+ /**
177
+ * Renders the fields of a `useJsonForm` form with your components, one per field type, where the
178
+ * definition's `layout` puts them: the current step, with its sections, rows and slots. It renders
179
+ * nothing of its own, so put it inside Formisch's `<Form>` with your own submit button.
180
+ */
181
+ export declare function JsonFields(props: JsonFieldsProps): ReactElement;
182
+ export type { AnyJsonFormInstance, ArrayFieldProps, DisplayFieldProps, FieldComponents, FieldNode, FieldPath, FieldRole, FormLayout, GroupFieldProps, JsonFieldProps, JsonFieldsProps, JsonFormInstance, JsonFormSchema, JsonFormSteps, LayoutComponents, LayoutNode, LayoutStep, RowProps, SectionProps, TypedJsonFormSchema, UseJsonFormOptions, ValueFieldProps };
183
+ //# sourceMappingURL=index.d.ts.map
package/dist/index.js ADDED
@@ -0,0 +1,409 @@
1
+ import { checkComponents, checkLayoutComponents, coerceInput, createSchemaBuilder, dotPathOf, fieldPathsOf, findField, isRequired, issuesOfStep, selectFields, shownNodes, toFieldPath } from "@whatsaaaa/form-builder-schema";
2
+ import { focus, getErrors, getInput, insert, move, remove, setErrors, useField, useFieldArray, useForm, validate } from "@formisch/react";
3
+ import { Fragment, useCallback, useEffect, useMemo, useRef, useState } from "react";
4
+ import { Fragment as Fragment$1, jsx } from "react/jsx-runtime";
5
+ // src/json-form-steps.ts
6
+ const fieldEvents = /* @__PURE__ */ new WeakMap();
7
+ /** What a field of `form` calls on each event, for a form with steps. Undefined with one step. */
8
+ const fieldEventsOf = (form) => fieldEvents.get(form);
9
+ /**
10
+ * The steps of `layout`, for `useJsonForm`. With more than one, a step shows the errors it had
11
+ * when the user left it, and none the first time they get to it, a step that failed Next revalidates as the user fixes it, a submit
12
+ * before the last step moves on like Next, and a submit that fails because of an earlier step
13
+ * goes back to it. Like Formisch's `useForm`, it reads the validation modes on the first render.
14
+ */
15
+ function useJsonFormSteps(form, layout, modes) {
16
+ const list = layout.steps;
17
+ const [index, setIndex] = useState(0);
18
+ const state = useRef({
19
+ index: 0,
20
+ left: /* @__PURE__ */ new Map(),
21
+ failed: /* @__PURE__ */ new Set(),
22
+ focus: void 0,
23
+ submitting: false,
24
+ modes
25
+ });
26
+ const methods = useMemo(() => {
27
+ const at = state.current;
28
+ async function goTo(target) {
29
+ if (!Number.isInteger(target) || target < 0 || target >= list.length) throw new RangeError(`No step ${target}. The form has ${list.length}.`);
30
+ if (target <= at.index) {
31
+ move(target);
32
+ return true;
33
+ }
34
+ const { issues } = await validate(form);
35
+ for (let step = at.index; step < target; step++) {
36
+ const found = issuesOfStep(list[step], issues);
37
+ if (found.length) {
38
+ stop(step, found);
39
+ return false;
40
+ }
41
+ at.failed.delete(step);
42
+ }
43
+ move(target);
44
+ return true;
45
+ }
46
+ /**
47
+ * Moves to a step as the user left it: with the errors it had then, and none the first time, and
48
+ * revalidating if it failed Next. Validating the steps before set errors on its fields, which
49
+ * the user never saw.
50
+ */
51
+ function move(target) {
52
+ leave();
53
+ const errors = at.left.get(target);
54
+ for (const path of fieldPathsOf(list[target], getInput(form))) setErrors(form, {
55
+ path,
56
+ errors: errors?.get(JSON.stringify(path)) ?? null
57
+ });
58
+ at.index = target;
59
+ setIndex(target);
60
+ }
61
+ /** Keeps the errors of the current step, for when the user comes back to it. */
62
+ function leave() {
63
+ const errors = fieldPathsOf(list[at.index], getInput(form)).map((path) => [JSON.stringify(path), getErrors(form, { path })]);
64
+ at.left.set(at.index, new Map(errors));
65
+ }
66
+ /** Stays on, or goes to, the step at `target`, with its issues shown. */
67
+ function stop(target, found) {
68
+ at.failed.add(target);
69
+ const path = found.find((issue) => issue.field.role === "value")?.path;
70
+ if (target === at.index) {
71
+ if (path) focus(form, { path });
72
+ return;
73
+ }
74
+ leave();
75
+ at.focus = path;
76
+ at.index = target;
77
+ setIndex(target);
78
+ }
79
+ const events = (event) => {
80
+ const validateMode = at.modes.validate ?? "submit";
81
+ if (!at.failed.has(at.index) || validateMode !== "submit" || form.isSubmitted) return;
82
+ if (event === (at.modes.revalidate ?? "input")) validate(form);
83
+ };
84
+ /** After a failed submit: back to the first step before this one with issues, if any. */
85
+ async function afterSubmit() {
86
+ const { issues } = await validate(form);
87
+ const step = list.findIndex((each) => issuesOfStep(each, issues).length);
88
+ if (step !== -1 && step < at.index) stop(step, issuesOfStep(list[step], issues));
89
+ }
90
+ const next = () => at.index === list.length - 1 ? Promise.resolve(false) : goTo(at.index + 1);
91
+ const back = () => {
92
+ if (at.index > 0) move(at.index - 1);
93
+ };
94
+ return {
95
+ goTo,
96
+ next,
97
+ back,
98
+ events,
99
+ afterSubmit
100
+ };
101
+ }, [form, list]);
102
+ useEffect(() => {
103
+ const path = state.current.focus;
104
+ state.current.focus = void 0;
105
+ if (path) focus(form, { path });
106
+ }, [form, index]);
107
+ const stepped = list.length > 1;
108
+ useEffect(() => {
109
+ if (!stepped) return;
110
+ fieldEvents.set(form, methods.events);
111
+ const onSubmit = (event) => {
112
+ if (event.target !== formElementOf(form)) return;
113
+ if (state.current.index === list.length - 1) {
114
+ state.current.submitting = true;
115
+ return;
116
+ }
117
+ event.preventDefault();
118
+ event.stopImmediatePropagation();
119
+ methods.next();
120
+ };
121
+ document.addEventListener("submit", onSubmit, { capture: true });
122
+ return () => {
123
+ fieldEvents.delete(form);
124
+ document.removeEventListener("submit", onSubmit, { capture: true });
125
+ };
126
+ }, [
127
+ form,
128
+ list,
129
+ methods,
130
+ stepped
131
+ ]);
132
+ const submitting = form.isSubmitting;
133
+ useEffect(() => {
134
+ if (!state.current.submitting || submitting) return;
135
+ state.current.submitting = false;
136
+ if (!form.isValid) methods.afterSubmit();
137
+ });
138
+ return useMemo(() => ({
139
+ list,
140
+ index,
141
+ current: list[index],
142
+ isFirst: index === 0,
143
+ isLast: index === list.length - 1,
144
+ next: methods.next,
145
+ back: methods.back,
146
+ goTo: methods.goTo
147
+ }), [
148
+ list,
149
+ index,
150
+ methods
151
+ ]);
152
+ }
153
+ /** The `<form>` Formisch's `<Form>` renders, which it keeps on the store for its `submit()`. */
154
+ function formElementOf(form) {
155
+ return form["~internal"]?.element;
156
+ }
157
+ // src/array-field.tsx
158
+ /** Connects a container of kind `array` to Formisch, and renders your component for it. */
159
+ function ArrayField({ of, node, path, component: Component, renderItem }) {
160
+ const array = useFieldArray(of.form, { path });
161
+ const { form, builder } = of;
162
+ const { field } = node;
163
+ const at = array.path;
164
+ const methods = useMemo(() => ({
165
+ add: () => {
166
+ insert(form, {
167
+ path: at,
168
+ initialInput: builder.getItemInput(field)
169
+ });
170
+ fieldEventsOf(form)?.("input");
171
+ },
172
+ remove: (index) => {
173
+ remove(form, {
174
+ path: at,
175
+ at: index
176
+ });
177
+ fieldEventsOf(form)?.("input");
178
+ },
179
+ move: (from, to) => {
180
+ move(form, {
181
+ path: at,
182
+ from,
183
+ to
184
+ });
185
+ fieldEventsOf(form)?.("input");
186
+ }
187
+ }), [
188
+ form,
189
+ builder,
190
+ field,
191
+ at
192
+ ]);
193
+ return /* @__PURE__ */ jsx(Component, {
194
+ field,
195
+ path,
196
+ items: array.items,
197
+ errors: array.errors,
198
+ ...methods,
199
+ children: renderItem
200
+ });
201
+ }
202
+ // src/value-field.tsx
203
+ /** Connects a field with a value to Formisch, and renders your component for it. */
204
+ function ValueField({ of, node, path, component: Component }) {
205
+ const field = useField(of.form, { path });
206
+ const { form } = of;
207
+ const setInput = useCallback((input) => {
208
+ field.onChange(coerceInput(input, node));
209
+ fieldEventsOf(form)?.("input");
210
+ }, [
211
+ field,
212
+ node,
213
+ form
214
+ ]);
215
+ const inputProps = of.steps.list.length > 1 ? {
216
+ ...field.props,
217
+ onFocus: () => {
218
+ field.props.onFocus();
219
+ fieldEventsOf(form)?.("touch");
220
+ },
221
+ onChange: (event) => {
222
+ field.props.onChange(event);
223
+ fieldEventsOf(form)?.("input");
224
+ fieldEventsOf(form)?.("change");
225
+ },
226
+ onBlur: () => {
227
+ field.props.onBlur();
228
+ fieldEventsOf(form)?.("blur");
229
+ }
230
+ } : field.props;
231
+ return /* @__PURE__ */ jsx(Component, {
232
+ field: node.field,
233
+ path,
234
+ kind: node.kind,
235
+ required: isRequired(node.field),
236
+ input: field.input,
237
+ errors: field.errors,
238
+ inputProps,
239
+ setInput
240
+ });
241
+ }
242
+ // src/render-fields.tsx
243
+ /** The components from the props, or else the ones `useJsonForm` got. */
244
+ function resolveComponents(components, of) {
245
+ const resolved = components ?? of.components;
246
+ if (!resolved) throw new TypeError("No field components. Pass them to useJsonForm, or to the component.");
247
+ return resolved;
248
+ }
249
+ /** `indexes` are the indexes of the array items the fields are in, outermost first. */
250
+ function renderFields(ctx, nodes, indexes) {
251
+ return nodes.map((node, position) => renderField(ctx, node, indexes, dotPathOf(node) ?? `#${position}`, (inner) => renderFields(ctx, node.children, inner)));
252
+ }
253
+ /**
254
+ * Renders one field with its component. `children` renders the fields inside a group, or inside
255
+ * the item of an array, with the indexes of the items they are in.
256
+ */
257
+ function renderField(ctx, node, indexes, key, children) {
258
+ const component = ctx.components[node.type];
259
+ const path = toFieldPath(node.dataPath, indexes);
260
+ switch (node.role) {
261
+ case "display": return /* @__PURE__ */ jsx(component, { field: node.field }, key);
262
+ case "group": return /* @__PURE__ */ jsx(component, {
263
+ field: node.field,
264
+ path,
265
+ children: children(indexes)
266
+ }, key);
267
+ case "array": return /* @__PURE__ */ jsx(ArrayField, {
268
+ of: ctx.of,
269
+ node,
270
+ path,
271
+ component,
272
+ renderItem: (index) => children([...indexes, index])
273
+ }, key);
274
+ case "value": return /* @__PURE__ */ jsx(ValueField, {
275
+ of: ctx.of,
276
+ node,
277
+ path,
278
+ component
279
+ }, key);
280
+ }
281
+ }
282
+ // src/json-field.tsx
283
+ /**
284
+ * Renders one field of a `useJsonForm` form, wherever you put it inside Formisch's `<Form>`. A
285
+ * group or an array comes with its fields. Leave the field out of `<JsonFields>` with `except`.
286
+ */
287
+ function JsonField({ of, path, components }) {
288
+ const node = findField(of.fields, path, { placed: true });
289
+ const ctx = {
290
+ of,
291
+ components: resolveComponents(components, of)
292
+ };
293
+ checkComponents([node], ctx.components);
294
+ return renderField(ctx, node, [], dotPathOf(node) ?? "#0", (indexes) => renderFields(ctx, node.children, indexes));
295
+ }
296
+ // src/render-layout.tsx
297
+ /**
298
+ * Renders layout nodes. A field left out drops out, and so does a section or a row left without
299
+ * fields. `indexes` are the indexes of the array items the nodes are in, outermost first.
300
+ */
301
+ function renderLayout(ctx, nodes, indexes) {
302
+ return shownNodes(nodes, indexes, ctx.isShown).map((node) => renderNode(ctx, node, indexes));
303
+ }
304
+ function renderNode(ctx, node, indexes) {
305
+ const { key } = node;
306
+ switch (node.type) {
307
+ case "field": return renderField(ctx, node.node, indexes, key, (inner) => renderLayout(ctx, node.children, inner));
308
+ case "section": {
309
+ const Section = ctx.layoutComponents.section;
310
+ return /* @__PURE__ */ jsx(Section, {
311
+ section: node.section,
312
+ children: renderLayout(ctx, node.children, indexes)
313
+ }, key);
314
+ }
315
+ case "row": {
316
+ const Row = ctx.layoutComponents.row;
317
+ return /* @__PURE__ */ jsx(Row, {
318
+ row: node.row,
319
+ spans: node.children.map((cell) => cell.span),
320
+ children: (index) => renderNode(ctx, node.children[index], indexes)
321
+ }, key);
322
+ }
323
+ case "slot": return /* @__PURE__ */ jsx(Fragment, { children: ctx.slots[node.name] }, key);
324
+ }
325
+ }
326
+ // src/json-fields.tsx
327
+ /**
328
+ * Renders the fields of a `useJsonForm` form with your components, one per field type, where the
329
+ * definition's `layout` puts them: the current step, with its sections, rows and slots. It renders
330
+ * nothing of its own, so put it inside Formisch's `<Form>` with your own submit button.
331
+ */
332
+ function JsonFields(props) {
333
+ const { of, only, except } = props;
334
+ const ctx = {
335
+ of,
336
+ components: resolveComponents(props.components, of)
337
+ };
338
+ const nodes = selectFields(of.fields, {
339
+ only,
340
+ except
341
+ });
342
+ if (only || !of.definition.layout) {
343
+ checkComponents(nodes, ctx.components);
344
+ return /* @__PURE__ */ jsx(Fragment$1, { children: renderFields(ctx, nodes, []) });
345
+ }
346
+ const { layout, steps } = of;
347
+ const left = new Set(except);
348
+ const layoutCtx = {
349
+ ...ctx,
350
+ layoutComponents: props.layoutComponents ?? of.layoutComponents ?? {},
351
+ slots: props.slots ?? {},
352
+ isShown: (node) => !left.has(dotPathOf(node) ?? "")
353
+ };
354
+ checkComponents(layout.steps.flatMap((step) => fieldsOf(step.children)), ctx.components);
355
+ checkLayoutComponents(layout, layoutCtx.layoutComponents, layoutCtx.slots);
356
+ const index = props.step ?? steps.index;
357
+ const step = steps.list[index];
358
+ if (!step) throw new RangeError(`No step ${props.step}. The form has ${steps.list.length}.`);
359
+ return /* @__PURE__ */ jsx(Fragment, { children: renderLayout(layoutCtx, step.children, []) }, index);
360
+ }
361
+ /** Every field of the nodes, display elements written in the layout included. */
362
+ function fieldsOf(nodes) {
363
+ return nodes.flatMap((node) => {
364
+ if (node.type === "slot") return [];
365
+ const inner = fieldsOf(node.children);
366
+ return node.type === "field" ? [node.node, ...inner] : inner;
367
+ });
368
+ }
369
+ // src/use-json-form.ts
370
+ function useJsonForm(definition, options = {}) {
371
+ const [built] = useState(() => {
372
+ const builder = options.builder ?? createSchemaBuilder();
373
+ return {
374
+ definition,
375
+ builder,
376
+ schema: builder.build(definition),
377
+ initialInput: builder.getInitialInput(definition),
378
+ fields: builder.getFieldTree(definition),
379
+ layout: builder.getLayout(definition)
380
+ };
381
+ });
382
+ const form = useForm({
383
+ schema: built.schema,
384
+ initialInput: built.initialInput,
385
+ validate: options.validate,
386
+ revalidate: options.revalidate
387
+ });
388
+ const steps = useJsonFormSteps(form, built.layout, options);
389
+ const { components, layoutComponents } = options;
390
+ return useMemo(() => ({
391
+ form,
392
+ definition: built.definition,
393
+ builder: built.builder,
394
+ components,
395
+ layoutComponents,
396
+ fields: built.fields,
397
+ layout: built.layout,
398
+ steps
399
+ }), [
400
+ form,
401
+ built,
402
+ components,
403
+ layoutComponents,
404
+ steps
405
+ ]);
406
+ }
407
+ export { JsonField, JsonFields, useJsonForm };
408
+
409
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","names":["Display","Group"],"sources":["../src/json-form-steps.ts","../src/array-field.tsx","../src/value-field.tsx","../src/render-fields.tsx","../src/json-field.tsx","../src/render-layout.tsx","../src/json-fields.tsx","../src/use-json-form.ts"],"sourcesContent":["import {\n focus,\n type FormStore,\n getErrors,\n getInput,\n setErrors,\n validate,\n type ValidationMode,\n} from '@formisch/react'\nimport {\n type FieldPath,\n fieldPathsOf,\n type FormLayout,\n issuesOfStep,\n type LayoutStep,\n type StepIssue,\n} from '@whatsaaaa/form-builder-schema'\nimport { useEffect, useMemo, useRef, useState } from 'react'\n\n/** The steps of a form, from its layout. A form without `steps` in its layout has one. */\nexport interface JsonFormSteps {\n /** Every step, in order. */\n readonly list: readonly LayoutStep[]\n /** The index of the current step in `list`. */\n readonly index: number\n /** The step `<JsonFields>` renders. */\n readonly current: LayoutStep\n readonly isFirst: boolean\n readonly isLast: boolean\n /**\n * Validates the whole form, and moves to the next step when the fields of this one have no\n * issues. Otherwise it stays, and focuses the first field with an issue, in layout order.\n * Resolves to whether it moved.\n */\n next(): Promise<boolean>\n /** Moves to the step before, without validating. */\n back(): void\n /**\n * Moves to the step at `index`. Back is free, and forward validates every step on the way, like\n * `next()`, and stops at the first with issues. Resolves to whether it got there.\n */\n goTo(index: number): Promise<boolean>\n}\n\n/** A field's error messages in Formisch, or null. */\ntype Errors = [string, ...string[]] | null\n\n/** What a field tells the steps it was through, by Formisch's name for the validation mode. */\nexport type FieldEvent = Exclude<ValidationMode, 'initial' | 'submit'>\n\n/** Revalidates a step that failed Next on each field event, like a form after a failed submit. */\ntype FieldEvents = (event: FieldEvent) => void\n\nconst fieldEvents = new WeakMap<FormStore, FieldEvents>()\n\n/** What a field of `form` calls on each event, for a form with steps. Undefined with one step. */\nexport const fieldEventsOf = (form: FormStore): FieldEvents | undefined => fieldEvents.get(form)\n\ninterface Modes {\n validate?: ValidationMode | undefined\n revalidate?: Exclude<ValidationMode, 'initial'> | undefined\n}\n\n/**\n * The steps of `layout`, for `useJsonForm`. With more than one, a step shows the errors it had\n * when the user left it, and none the first time they get to it, a step that failed Next revalidates as the user fixes it, a submit\n * before the last step moves on like Next, and a submit that fails because of an earlier step\n * goes back to it. Like Formisch's `useForm`, it reads the validation modes on the first render.\n */\nexport function useJsonFormSteps(form: FormStore, layout: FormLayout, modes: Modes): JsonFormSteps {\n const list = layout.steps\n const [index, setIndex] = useState(0)\n // What the async methods and the event handlers read: always the latest.\n const state = useRef({\n index: 0,\n // The errors each step had when the user left it, by the JSON of each field's path.\n left: new Map<number, Map<string, Errors>>(),\n // The steps that failed Next, and haven't passed since.\n failed: new Set<number>(),\n // The field to focus once the step it is on has rendered.\n focus: undefined as FieldPath | undefined,\n // Whether a submit on the last step is on its way through Formisch.\n submitting: false,\n modes,\n })\n\n const methods = useMemo(() => {\n const at = state.current\n\n async function goTo(target: number): Promise<boolean> {\n if (!Number.isInteger(target) || target < 0 || target >= list.length) {\n throw new RangeError(`No step ${target}. The form has ${list.length}.`)\n }\n if (target <= at.index) {\n move(target)\n return true\n }\n const { issues } = await validate(form)\n for (let step = at.index; step < target; step++) {\n const found = issuesOfStep(list[step] as LayoutStep, issues)\n if (found.length) {\n stop(step, found)\n return false\n }\n at.failed.delete(step)\n }\n move(target)\n return true\n }\n\n /**\n * Moves to a step as the user left it: with the errors it had then, and none the first time, and\n * revalidating if it failed Next. Validating the steps before set errors on its fields, which\n * the user never saw.\n */\n function move(target: number) {\n leave()\n const errors = at.left.get(target)\n for (const path of fieldPathsOf(list[target] as LayoutStep, getInput(form))) {\n setErrors(form, { path, errors: errors?.get(JSON.stringify(path)) ?? null } as never)\n }\n at.index = target\n setIndex(target)\n }\n\n /** Keeps the errors of the current step, for when the user comes back to it. */\n function leave() {\n const paths = fieldPathsOf(list[at.index] as LayoutStep, getInput(form))\n const errors = paths.map((path): [string, Errors] => [\n JSON.stringify(path),\n getErrors(form, { path } as never),\n ])\n at.left.set(at.index, new Map(errors))\n }\n\n /** Stays on, or goes to, the step at `target`, with its issues shown. */\n function stop(target: number, found: readonly StepIssue[]) {\n at.failed.add(target)\n // A group or an array has no element: the first field that has one gets the focus.\n const path = found.find((issue) => issue.field.role === 'value')?.path\n if (target === at.index) {\n if (path) focus(form, { path: path as never })\n return\n }\n leave()\n at.focus = path\n at.index = target\n setIndex(target)\n }\n\n const events: FieldEvents = (event) => {\n // In the other modes, Formisch revalidates a field with errors itself.\n const validateMode = at.modes.validate ?? 'submit'\n if (!at.failed.has(at.index) || validateMode !== 'submit' || form.isSubmitted) return\n if (event === (at.modes.revalidate ?? 'input')) void validate(form)\n }\n\n /** After a failed submit: back to the first step before this one with issues, if any. */\n async function afterSubmit() {\n const { issues } = await validate(form)\n const step = list.findIndex((each) => issuesOfStep(each, issues).length)\n if (step !== -1 && step < at.index) stop(step, issuesOfStep(list[step] as LayoutStep, issues))\n }\n\n const next = () => (at.index === list.length - 1 ? Promise.resolve(false) : goTo(at.index + 1))\n const back = () => {\n if (at.index > 0) move(at.index - 1)\n }\n return { goTo, next, back, events, afterSubmit }\n }, [form, list])\n\n // The field a step was stopped on, once the step has rendered.\n useEffect(() => {\n const path = state.current.focus\n state.current.focus = undefined\n if (path) focus(form, { path: path as never })\n }, [form, index])\n\n const stepped = list.length > 1\n useEffect(() => {\n if (!stepped) return\n fieldEvents.set(form, methods.events)\n // Before the last step, a submit, like Enter in a step with a single text input, is a Next.\n // It is caught on its way down to the form, before Formisch's own handler sees it.\n const onSubmit = (event: Event) => {\n if (event.target !== formElementOf(form)) return\n if (state.current.index === list.length - 1) {\n state.current.submitting = true\n return\n }\n event.preventDefault()\n event.stopImmediatePropagation()\n void methods.next()\n }\n document.addEventListener('submit', onSubmit, { capture: true })\n return () => {\n fieldEvents.delete(form)\n document.removeEventListener('submit', onSubmit, { capture: true })\n }\n }, [form, list, methods, stepped])\n\n // A submit that fails because of a step before the last, e.g. on a form rule, goes back to it.\n // React can batch the start and the end of a submit into one render, so the submit is marked\n // as it starts, and each render checks whether Formisch has finished it.\n const submitting = form.isSubmitting\n useEffect(() => {\n if (!state.current.submitting || submitting) return\n state.current.submitting = false\n if (!form.isValid) void methods.afterSubmit()\n })\n\n return useMemo(\n () => ({\n list,\n index,\n current: list[index] as LayoutStep,\n isFirst: index === 0,\n isLast: index === list.length - 1,\n next: methods.next,\n back: methods.back,\n goTo: methods.goTo,\n }),\n [list, index, methods],\n )\n}\n\n/** The `<form>` Formisch's `<Form>` renders, which it keeps on the store for its `submit()`. */\nfunction formElementOf(form: FormStore): HTMLFormElement | undefined {\n return (form as unknown as { '~internal'?: { element?: HTMLFormElement } })['~internal']?.element\n}\n","import { insert, move, remove, useFieldArray } from '@formisch/react'\nimport type { FieldNode, FieldPath } from '@whatsaaaa/form-builder-schema'\nimport { type ComponentType, type ReactElement, type ReactNode, useMemo } from 'react'\nimport type { ArrayFieldProps } from './field-components'\nimport { fieldEventsOf } from './json-form-steps'\nimport type { AnyJsonFormInstance } from './use-json-form'\n\ninterface ArrayFieldConnectionProps {\n of: AnyJsonFormInstance\n node: FieldNode\n path: FieldPath\n component: ComponentType<ArrayFieldProps>\n /** Renders the fields of the item at `index`. */\n renderItem: (index: number) => ReactNode\n}\n\n/** Connects a container of kind `array` to Formisch, and renders your component for it. */\nexport function ArrayField({\n of,\n node,\n path,\n component: Component,\n renderItem,\n}: ArrayFieldConnectionProps): ReactElement {\n // The path comes from the definition at runtime, so the schema's types can't check it.\n const array = useFieldArray(of.form, { path: path as never })\n\n // Formisch keeps the path it got while the array is the same, so the methods stay the same too.\n const { form, builder } = of\n const { field } = node\n const at = array.path\n // In a form with steps, a step that failed Next revalidates on a change of its items too.\n const methods = useMemo(\n () => ({\n // A new item starts with the defaults of its fields, like the items of a new form.\n add: () => {\n insert(form, { path: at, initialInput: builder.getItemInput(field) as never })\n fieldEventsOf(form)?.('input')\n },\n remove: (index: number) => {\n remove(form, { path: at, at: index })\n fieldEventsOf(form)?.('input')\n },\n move: (from: number, to: number) => {\n move(form, { path: at, from, to })\n fieldEventsOf(form)?.('input')\n },\n }),\n [form, builder, field, at],\n )\n\n return (\n <Component field={field} path={path} items={array.items} errors={array.errors} {...methods}>\n {renderItem}\n </Component>\n )\n}\n","import { useField } from '@formisch/react'\nimport {\n coerceInput,\n type FieldNode,\n type FieldPath,\n isRequired,\n} from '@whatsaaaa/form-builder-schema'\nimport { type ComponentType, type ReactElement, useCallback } from 'react'\nimport type { ValueFieldProps } from './field-components'\nimport { fieldEventsOf } from './json-form-steps'\nimport type { AnyJsonFormInstance } from './use-json-form'\n\ninterface ValueFieldConnectionProps {\n of: AnyJsonFormInstance\n node: FieldNode\n path: FieldPath\n component: ComponentType<ValueFieldProps>\n}\n\n/** Connects a field with a value to Formisch, and renders your component for it. */\nexport function ValueField({\n of,\n node,\n path,\n component: Component,\n}: ValueFieldConnectionProps): ReactElement {\n // The path comes from the definition at runtime, so the schema's types can't check it.\n const field = useField(of.form, { path: path as never })\n const { form } = of\n const setInput = useCallback(\n (input: unknown) => {\n field.onChange(coerceInput(input, node) as never)\n fieldEventsOf(form)?.('input')\n },\n [field, node, form],\n )\n // In a form with steps, a step that failed Next revalidates on these events too.\n const inputProps =\n of.steps.list.length > 1\n ? {\n ...field.props,\n onFocus: () => {\n field.props.onFocus()\n fieldEventsOf(form)?.('touch')\n },\n onChange: (event: Parameters<typeof field.props.onChange>[0]) => {\n field.props.onChange(event)\n fieldEventsOf(form)?.('input')\n fieldEventsOf(form)?.('change')\n },\n onBlur: () => {\n field.props.onBlur()\n fieldEventsOf(form)?.('blur')\n },\n }\n : field.props\n\n return (\n <Component\n field={node.field}\n path={path}\n kind={node.kind}\n required={isRequired(node.field)}\n input={field.input}\n errors={field.errors}\n inputProps={inputProps}\n setInput={setInput}\n />\n )\n}\n","import { dotPathOf, type FieldNode, toFieldPath } from '@whatsaaaa/form-builder-schema'\nimport type { ComponentType, ReactElement, ReactNode } from 'react'\nimport { ArrayField } from './array-field'\nimport type {\n ArrayFieldProps,\n DisplayFieldProps,\n FieldComponents,\n GroupFieldProps,\n ValueFieldProps,\n} from './field-components'\nimport type { AnyJsonFormInstance } from './use-json-form'\nimport { ValueField } from './value-field'\n\n/** What `<JsonFields>` and `<JsonField>` render with. */\nexport interface RenderContext {\n of: AnyJsonFormInstance\n components: FieldComponents\n}\n\n/** The components from the props, or else the ones `useJsonForm` got. */\nexport function resolveComponents(\n components: FieldComponents | undefined,\n of: AnyJsonFormInstance,\n): FieldComponents {\n const resolved = components ?? of.components\n if (!resolved) {\n throw new TypeError('No field components. Pass them to useJsonForm, or to the component.')\n }\n return resolved\n}\n\n/** `indexes` are the indexes of the array items the fields are in, outermost first. */\nexport function renderFields(\n ctx: RenderContext,\n nodes: readonly FieldNode[],\n indexes: readonly number[],\n): ReactElement[] {\n return nodes.map((node, position) =>\n renderField(ctx, node, indexes, dotPathOf(node) ?? `#${position}`, (inner) =>\n renderFields(ctx, node.children, inner),\n ),\n )\n}\n\n/**\n * Renders one field with its component. `children` renders the fields inside a group, or inside\n * the item of an array, with the indexes of the items they are in.\n */\nexport function renderField(\n ctx: RenderContext,\n node: FieldNode,\n indexes: readonly number[],\n key: string,\n children: (indexes: readonly number[]) => ReactNode,\n): ReactElement {\n // The fields were checked for components, and the role tells which props the component takes.\n const component = ctx.components[node.type]\n const path = toFieldPath(node.dataPath, indexes)\n switch (node.role) {\n case 'display': {\n const Display = component as ComponentType<DisplayFieldProps>\n return <Display key={key} field={node.field} />\n }\n case 'group': {\n const Group = component as ComponentType<GroupFieldProps>\n return (\n <Group key={key} field={node.field} path={path}>\n {children(indexes)}\n </Group>\n )\n }\n case 'array':\n return (\n <ArrayField\n key={key}\n of={ctx.of}\n node={node}\n path={path}\n component={component as ComponentType<ArrayFieldProps>}\n renderItem={(index) => children([...indexes, index])}\n />\n )\n case 'value':\n return (\n <ValueField\n key={key}\n of={ctx.of}\n node={node}\n path={path}\n component={component as ComponentType<ValueFieldProps>}\n />\n )\n }\n}\n","import { checkComponents, dotPathOf, findField } from '@whatsaaaa/form-builder-schema'\nimport type { ReactElement } from 'react'\nimport type { FieldComponents } from './field-components'\nimport { type RenderContext, renderField, renderFields, resolveComponents } from './render-fields'\nimport type { AnyJsonFormInstance } from './use-json-form'\n\nexport interface JsonFieldProps {\n /** What `useJsonForm` returned. */\n of: AnyJsonFormInstance\n /** The field's path: `'email'`, or `'address.city'` for a field of a group. */\n path: string\n /** Defaults to the components `useJsonForm` got. */\n components?: FieldComponents | undefined\n}\n\n/**\n * Renders one field of a `useJsonForm` form, wherever you put it inside Formisch's `<Form>`. A\n * group or an array comes with its fields. Leave the field out of `<JsonFields>` with `except`.\n */\nexport function JsonField({ of, path, components }: JsonFieldProps): ReactElement {\n const node = findField(of.fields, path, { placed: true })\n const ctx: RenderContext = { of, components: resolveComponents(components, of) }\n checkComponents([node], ctx.components)\n\n return renderField(ctx, node, [], dotPathOf(node) ?? '#0', (indexes) =>\n renderFields(ctx, node.children, indexes),\n )\n}\n","import { type IsFieldShown, type LayoutNode, shownNodes } from '@whatsaaaa/form-builder-schema'\nimport { type ComponentType, Fragment, type ReactElement, type ReactNode } from 'react'\nimport type { LayoutComponents, RowProps, SectionProps } from './field-components'\nimport { type RenderContext, renderField } from './render-fields'\n\n/** What `<JsonFields>` renders a layout with. */\nexport interface LayoutContext extends RenderContext {\n layoutComponents: LayoutComponents\n /** The content of the layout's slots, by name. */\n slots: Readonly<Record<string, ReactNode>>\n /** False for a field left out with `except`. */\n isShown: IsFieldShown\n}\n\n/**\n * Renders layout nodes. A field left out drops out, and so does a section or a row left without\n * fields. `indexes` are the indexes of the array items the nodes are in, outermost first.\n */\nexport function renderLayout(\n ctx: LayoutContext,\n nodes: readonly LayoutNode[],\n indexes: readonly number[],\n): ReactElement[] {\n return shownNodes(nodes, indexes, ctx.isShown).map((node) => renderNode(ctx, node, indexes))\n}\n\nfunction renderNode(\n ctx: LayoutContext,\n node: LayoutNode,\n indexes: readonly number[],\n): ReactElement {\n const { key } = node\n switch (node.type) {\n case 'field':\n return renderField(ctx, node.node, indexes, key, (inner) =>\n renderLayout(ctx, node.children, inner),\n )\n case 'section': {\n // The layout was checked for components.\n const Section = ctx.layoutComponents.section as ComponentType<SectionProps>\n return (\n <Section key={key} section={node.section}>\n {renderLayout(ctx, node.children, indexes)}\n </Section>\n )\n }\n case 'row': {\n const Row = ctx.layoutComponents.row as ComponentType<RowProps>\n return (\n <Row key={key} row={node.row} spans={node.children.map((cell) => cell.span)}>\n {(index) => renderNode(ctx, node.children[index] as LayoutNode, indexes)}\n </Row>\n )\n }\n case 'slot':\n return <Fragment key={key}>{ctx.slots[node.name]}</Fragment>\n }\n}\n","import {\n checkComponents,\n checkLayoutComponents,\n dotPathOf,\n type FieldNode,\n type LayoutNode,\n selectFields,\n} from '@whatsaaaa/form-builder-schema'\nimport { Fragment, type ReactElement, type ReactNode } from 'react'\nimport type { FieldComponents, LayoutComponents } from './field-components'\nimport { type LayoutContext, renderLayout } from './render-layout'\nimport { type RenderContext, renderFields, resolveComponents } from './render-fields'\nimport type { AnyJsonFormInstance } from './use-json-form'\n\nexport interface JsonFieldsProps {\n /** What `useJsonForm` returned. */\n of: AnyJsonFormInstance\n /** Defaults to the components `useJsonForm` got. */\n components?: FieldComponents | undefined\n /** Defaults to the layout components `useJsonForm` got. */\n layoutComponents?: LayoutComponents | undefined\n /** The content of the layout's slots, by name: `{ submit: <button type=\"submit\">Save</button> }`. */\n slots?: Readonly<Record<string, ReactNode>> | undefined\n /** Renders only these fields, by path, in the order of the definition, without the layout. */\n only?: readonly string[] | undefined\n /**\n * Leaves out these fields, by path, e.g. the ones you place with `<JsonField>`. A section or a\n * row left without fields drops out too.\n */\n except?: readonly string[] | undefined\n /** Renders the step at this index instead of the current one, e.g. on a review page. */\n step?: number | undefined\n}\n\n/**\n * Renders the fields of a `useJsonForm` form with your components, one per field type, where the\n * definition's `layout` puts them: the current step, with its sections, rows and slots. It renders\n * nothing of its own, so put it inside Formisch's `<Form>` with your own submit button.\n */\nexport function JsonFields(props: JsonFieldsProps): ReactElement {\n const { of, only, except } = props\n const ctx: RenderContext = { of, components: resolveComponents(props.components, of) }\n const nodes = selectFields(of.fields, { only, except })\n // Without a layout, it renders the fields the way it always did, and so with `only`.\n if (only || !of.definition.layout) {\n checkComponents(nodes, ctx.components)\n return <>{renderFields(ctx, nodes, [])}</>\n }\n\n const { layout, steps } = of\n const left = new Set(except)\n const layoutCtx: LayoutContext = {\n ...ctx,\n layoutComponents: props.layoutComponents ?? of.layoutComponents ?? {},\n slots: props.slots ?? {},\n isShown: (node) => !left.has(dotPathOf(node) ?? ''),\n }\n checkComponents(\n layout.steps.flatMap((step) => fieldsOf(step.children)),\n ctx.components,\n )\n checkLayoutComponents(layout, layoutCtx.layoutComponents, layoutCtx.slots)\n\n const index = props.step ?? steps.index\n const step = steps.list[index]\n if (!step) throw new RangeError(`No step ${props.step}. The form has ${steps.list.length}.`)\n // Keyed by the step, so another step's fields don't take over this one's components.\n return <Fragment key={index}>{renderLayout(layoutCtx, step.children, [])}</Fragment>\n}\n\n/** Every field of the nodes, display elements written in the layout included. */\nfunction fieldsOf(nodes: readonly LayoutNode[]): FieldNode[] {\n return nodes.flatMap((node) => {\n if (node.type === 'slot') return []\n const inner = fieldsOf(node.children)\n return node.type === 'field' ? [node.node, ...inner] : inner\n })\n}\n","import { type FormSchema, type FormStore, useForm, type ValidationMode } from '@formisch/react'\nimport {\n createSchemaBuilder,\n type FieldNode,\n type FormLayout,\n type JsonForm,\n type JsonFormSchema,\n type SchemaBuilder,\n type TypedJsonFormSchema,\n} from '@whatsaaaa/form-builder-schema'\nimport { useMemo, useState } from 'react'\nimport type { FieldComponents, LayoutComponents } from './field-components'\nimport { type JsonFormSteps, useJsonFormSteps } from './json-form-steps'\n\nexport interface UseJsonFormOptions {\n /** Builds the schema and knows your own types and rules. Defaults to `createSchemaBuilder()`. */\n builder?: SchemaBuilder\n /** Your component for each field type, so `<JsonFields>` and `<JsonField>` don't need them. */\n components?: FieldComponents\n /** Your component for each layout type the definition's `layout` uses, like `section`. */\n layoutComponents?: LayoutComponents\n /** When a field is validated the first time, as in Formisch. */\n validate?: ValidationMode\n /** When a field is validated again after that, as in Formisch. */\n revalidate?: Exclude<ValidationMode, 'initial'>\n}\n\n/** What `useJsonForm` returns. Pass it to `<JsonFields>`. */\nexport interface JsonFormInstance<TSchema extends FormSchema = JsonFormSchema> {\n /** The Formisch form: pass it to Formisch's `<Form of>`, or to any of its methods. */\n readonly form: FormStore<TSchema>\n readonly definition: JsonForm\n readonly builder: SchemaBuilder\n /** The components from the options, if any. */\n readonly components: FieldComponents | undefined\n /** The layout components from the options, if any. */\n readonly layoutComponents: LayoutComponents | undefined\n /** The definition's fields as a tree, for `<JsonFields only>` and `<JsonField>`. */\n readonly fields: readonly FieldNode[]\n /** The definition's layout, the way `<JsonFields>` renders it. */\n readonly layout: FormLayout\n /** The layout's steps: the current one, and Next, Back and Go to. A form without steps has one. */\n readonly steps: JsonFormSteps\n}\n\n/** Any form `useJsonForm` returns, typed or not: what the components take. */\nexport type AnyJsonFormInstance = JsonFormInstance<FormSchema>\n\n/**\n * A Formisch form for a definition, with its schema and initial input from the builder. A\n * definition with issues throws the builder's `DefinitionError`, so run `validate()` first when it\n * comes from outside your code. Like Formisch's `useForm`, it reads the definition, the builder and\n * the validation modes on the first render: give the component a new `key` to use another\n * definition. The components and layout components are read on every render.\n */\nexport function useJsonForm(definition: JsonForm, options?: UseJsonFormOptions): JsonFormInstance\n/**\n * The same, with the form typed by your input type, and output type when it differs, so Formisch's\n * paths and values are checked. The types are yours to keep in step with the definition.\n */\nexport function useJsonForm<TInput extends object, TOutput extends object = TInput>(\n definition: JsonForm,\n options?: UseJsonFormOptions,\n): JsonFormInstance<TypedJsonFormSchema<TInput, TOutput>>\nexport function useJsonForm(\n definition: JsonForm,\n options: UseJsonFormOptions = {},\n): JsonFormInstance {\n // Formisch reads its config on the first render only, so the schema is built once too.\n const [built] = useState(() => {\n const builder = options.builder ?? createSchemaBuilder()\n return {\n definition,\n builder,\n schema: builder.build(definition),\n initialInput: builder.getInitialInput(definition),\n fields: builder.getFieldTree(definition),\n layout: builder.getLayout(definition),\n }\n })\n const form = useForm({\n schema: built.schema,\n initialInput: built.initialInput,\n validate: options.validate,\n revalidate: options.revalidate,\n })\n const steps = useJsonFormSteps(form, built.layout, options)\n const { components, layoutComponents } = options\n return useMemo(\n () => ({\n form,\n definition: built.definition,\n builder: built.builder,\n components,\n layo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;GAChD,QAAQ,QAAQ,aAAa,UAAU;GACvC,QAAQ,QAAQ,UAAU,UAAU;EACtC;CACF,CAAC;CACD,MAAM,OAAO,QAAQ;EACnB,QAAQ,MAAM;EACd,cAAc,MAAM;EACpB,UAAU,QAAQ;EAClB,YAAY,QAAQ;CACtB,CAAC;CACD,MAAM,QAAQ,iBAAiB,MAAM,MAAM,QAAQ,OAAO;CAC1D,MAAM,EAAE,YAAY,qBAAqB;CACzC,OAAO,eACE;EACL;EACA,YAAY,MAAM;EAClB,SAAS,MAAM;EACf;EACA;EACA,QAAQ,MAAM;EACd,QAAQ,MAAM;EACd;CACF,IACA;EAAC;EAAM;EAAO;EAAY;EAAkB;CAAK,CACnD;AACF"}
package/package.json CHANGED
@@ -1,7 +1,68 @@
1
1
  {
2
2
  "name": "@whatsaaaa/form-builder-react",
3
- "version": "0.0.0",
4
- "description": "Placeholder - first real release is published from CI.",
3
+ "version": "0.2.0",
4
+ "description": "Render JSON form definitions with Formisch and your own React components.",
5
+ "keywords": [
6
+ "form",
7
+ "formisch",
8
+ "headless",
9
+ "json",
10
+ "react"
11
+ ],
12
+ "homepage": "https://github.com/whatsaaaa/form-builder",
13
+ "bugs": "https://github.com/whatsaaaa/form-builder/issues",
5
14
  "license": "MIT",
6
- "repository": { "type": "git", "url": "git+https://github.com/whatsaaaa/form-builder.git", "directory": "frameworks/react" }
7
- }
15
+ "author": "Whatsaaaa",
16
+ "repository": {
17
+ "type": "git",
18
+ "url": "git+https://github.com/whatsaaaa/form-builder.git",
19
+ "directory": "frameworks/react"
20
+ },
21
+ "files": [
22
+ "dist"
23
+ ],
24
+ "type": "module",
25
+ "sideEffects": false,
26
+ "exports": {
27
+ ".": {
28
+ "types": "./dist/index.d.ts",
29
+ "default": "./dist/index.js"
30
+ }
31
+ },
32
+ "publishConfig": {
33
+ "access": "public"
34
+ },
35
+ "dependencies": {
36
+ "@whatsaaaa/form-builder-schema": "^0.14.0"
37
+ },
38
+ "devDependencies": {
39
+ "@arethetypeswrong/cli": "^0.18.5",
40
+ "@formisch/react": "^1.2.0",
41
+ "@size-limit/preset-small-lib": "^14.3.0",
42
+ "@types/react": "^19.3.0",
43
+ "@types/react-dom": "^19.3.0",
44
+ "@vitest/coverage-v8": "^5.0.5",
45
+ "happy-dom": "^20.0.0",
46
+ "publint": "^0.3.25",
47
+ "react": "^19.3.1",
48
+ "react-dom": "^19.3.1",
49
+ "size-limit": "^14.3.0",
50
+ "tsdown": "^0.23.2",
51
+ "typescript": "~6.0.3",
52
+ "valibot": "^1.5.0",
53
+ "vitest": "^5.0.5"
54
+ },
55
+ "peerDependencies": {
56
+ "@formisch/react": "^1.2.0",
57
+ "react": "^18.0.0 || ^19.0.0",
58
+ "valibot": "^1.4.1"
59
+ },
60
+ "scripts": {
61
+ "build": "tsdown",
62
+ "test": "vitest run",
63
+ "test:coverage": "vitest run --coverage",
64
+ "type-check": "tsc --noEmit",
65
+ "lint:pkg": "publint && pnpm pack --pack-destination .attw && attw .attw/*.tgz --profile esm-only",
66
+ "size": "size-limit"
67
+ }
68
+ }