@whatsaaaa/form-builder-react 0.1.0 → 0.3.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/README.md +142 -4
- package/dist/index.d.ts +88 -9
- package/dist/index.js +371 -35
- package/dist/index.js.map +1 -1
- package/package.json +3 -2
package/README.md
CHANGED
|
@@ -49,12 +49,13 @@ export function DefinitionForm({ definition }: { definition: JsonForm }) {
|
|
|
49
49
|
useJsonForm(definition, {
|
|
50
50
|
builder: createSchemaBuilder({ fieldTypes: { money } }), // your own types, rules and messages
|
|
51
51
|
components, // your component per field type, see below
|
|
52
|
+
layoutComponents, // your component per layout type, see Layout
|
|
52
53
|
validate: 'blur', // when a field is validated the first time, as in Formisch
|
|
53
54
|
revalidate: 'input', // when it is validated again
|
|
54
55
|
})
|
|
55
56
|
```
|
|
56
57
|
|
|
57
|
-
`builder`, `validate` and `revalidate` are read on the first render, with the definition. `components`
|
|
58
|
+
`builder`, `validate` and `revalidate` are read on the first render, with the definition. `components` and `layoutComponents` are read on every render.
|
|
58
59
|
|
|
59
60
|
## Components
|
|
60
61
|
|
|
@@ -208,9 +209,146 @@ export function Heading({ field }: DisplayFieldProps) {
|
|
|
208
209
|
}
|
|
209
210
|
```
|
|
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` | the steps on show, each with its `step` as written (`id`, `label`, `description`, `ui`), `children` and `fields`: a step that [conditions](#conditions) hide is left out, unless the user is on it |
|
|
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
|
+
## Conditions
|
|
326
|
+
|
|
327
|
+
With the [affects package](https://github.com/whatsaaaa/form-builder/tree/main/packages/affects), fields, sections and steps show and hide by the values of other fields. Pass `useJsonForm` a builder with the extension:
|
|
328
|
+
|
|
329
|
+
```tsx
|
|
330
|
+
import { affects } from '@whatsaaaa/form-builder-affects'
|
|
331
|
+
|
|
332
|
+
const builder = createSchemaBuilder({ extensions: [affects()] })
|
|
333
|
+
|
|
334
|
+
function DefinitionForm({ definition }: { definition: JsonForm }) {
|
|
335
|
+
const jsonForm = useJsonForm(definition, { builder, components, layoutComponents })
|
|
336
|
+
// ...
|
|
337
|
+
}
|
|
338
|
+
```
|
|
339
|
+
|
|
340
|
+
- **`<JsonFields>` and `<JsonField>` leave out what the conditions hide**: a hidden field, a hidden section, and a group, section or row whose fields are all hidden. A field hidden in a row drops out of it, and the others keep their spans.
|
|
341
|
+
- **Steps skip the hidden ones.** `steps.list` holds the steps on show, so a step whose fields are all hidden is left out, and Next and Back go past it. The step the user is on stays, until they leave it.
|
|
342
|
+
- **`useJsonForm` clears what `hideAndClear` clears**, with Formisch's `setInput`, as soon as it is cleared, wherever the field renders: in `<JsonFields>`, with `<JsonField>`, or by your own code. A field that starts hidden this way starts blank.
|
|
343
|
+
- **The schema skips hidden fields**, so they never block the form, and submits what the affects package says.
|
|
344
|
+
- **The form renders again only when what is hidden changes**, not on every keystroke: `useJsonForm` watches the input outside React, through `@formisch/react/internals`.
|
|
345
|
+
- **`jsonForm.visibility`** is the state for the form's input now, for your own renderers: `isHidden(node, indexes)`, `isStepHidden(step)`, `shownNodes(nodes, indexes)`. It is a new object only when what is hidden changes.
|
|
346
|
+
|
|
347
|
+
Without conditions, nothing is hidden, nothing is watched, and nothing changes.
|
|
348
|
+
|
|
211
349
|
## Placing fields yourself
|
|
212
350
|
|
|
213
|
-
`<JsonFields>` renders every field in the order of the definition. To put some of them somewhere else, place them with `<JsonField>` and leave them out of `<JsonFields>` with `except`:
|
|
351
|
+
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`:
|
|
214
352
|
|
|
215
353
|
```tsx
|
|
216
354
|
<Form of={jsonForm.form} onSubmit={save}>
|
|
@@ -227,7 +365,7 @@ export function Heading({ field }: DisplayFieldProps) {
|
|
|
227
365
|
|
|
228
366
|
- 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.
|
|
229
367
|
- 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']}`.
|
|
230
|
-
- `only` renders just the fields it names, in the order of the definition: `<JsonFields of={jsonForm} only={['name', 'email']} />`. Display elements have no name, so `only` leaves them out.
|
|
368
|
+
- `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.
|
|
231
369
|
- 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.
|
|
232
370
|
|
|
233
371
|
## Typing the form
|
|
@@ -257,4 +395,4 @@ useFieldArray(jsonForm.form, { path: ['lines'] })
|
|
|
257
395
|
|
|
258
396
|
- 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.
|
|
259
397
|
- `ui.widget` doesn't pick a component. A component can read `field.ui` itself, e.g. to show a multiselect as checkboxes.
|
|
260
|
-
- Showing and hiding fields, or making one required because of another, belongs to a future affects package.
|
|
398
|
+
- 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.
|
package/dist/index.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { FieldNode, FieldNode as FieldNode$1, FieldPath, FieldPath as FieldPath$1, FieldRole, JsonField as JsonField$1, JsonForm, JsonFormSchema, JsonFormSchema as JsonFormSchema$1, SchemaBuilder, TypedJsonFormSchema, TypedJsonFormSchema as TypedJsonFormSchema$1, ValueKind } from "@whatsaaaa/form-builder-schema";
|
|
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, VisibilityState, VisibilityState as VisibilityState$1 } from "@whatsaaaa/form-builder-schema";
|
|
2
2
|
import { FieldElementProps, FormSchema, FormStore, ValidationMode } from "@formisch/react";
|
|
3
3
|
import { ComponentType, ReactElement, ReactNode } from "react";
|
|
4
4
|
/**
|
|
@@ -49,11 +49,64 @@ interface ArrayFieldProps {
|
|
|
49
49
|
/** Renders the fields of the item at `index`. */
|
|
50
50
|
children: (index: number) => ReactNode;
|
|
51
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
|
+
/**
|
|
79
|
+
* The steps on show, in order. A step whose fields are all hidden by conditions, or that is
|
|
80
|
+
* hidden itself, is left out, unless it is the current one: Next and Back skip it.
|
|
81
|
+
*/
|
|
82
|
+
readonly list: readonly LayoutStep$1[];
|
|
83
|
+
/** The index of the current step in `list`. */
|
|
84
|
+
readonly index: number;
|
|
85
|
+
/** The step `<JsonFields>` renders. */
|
|
86
|
+
readonly current: LayoutStep$1;
|
|
87
|
+
readonly isFirst: boolean;
|
|
88
|
+
readonly isLast: boolean;
|
|
89
|
+
/**
|
|
90
|
+
* Validates the whole form, and moves to the next step when the fields of this one have no
|
|
91
|
+
* issues. Otherwise it stays, and focuses the first field with an issue, in layout order.
|
|
92
|
+
* Resolves to whether it moved.
|
|
93
|
+
*/
|
|
94
|
+
next(): Promise<boolean>;
|
|
95
|
+
/** Moves to the step before, without validating. */
|
|
96
|
+
back(): void;
|
|
97
|
+
/**
|
|
98
|
+
* Moves to the step at `index`. Back is free, and forward validates every step on the way, like
|
|
99
|
+
* `next()`, and stops at the first with issues. Resolves to whether it got there.
|
|
100
|
+
*/
|
|
101
|
+
goTo(index: number): Promise<boolean>;
|
|
102
|
+
}
|
|
52
103
|
interface UseJsonFormOptions {
|
|
53
104
|
/** Builds the schema and knows your own types and rules. Defaults to `createSchemaBuilder()`. */
|
|
54
105
|
builder?: SchemaBuilder;
|
|
55
106
|
/** Your component for each field type, so `<JsonFields>` and `<JsonField>` don't need them. */
|
|
56
107
|
components?: FieldComponents;
|
|
108
|
+
/** Your component for each layout type the definition's `layout` uses, like `section`. */
|
|
109
|
+
layoutComponents?: LayoutComponents;
|
|
57
110
|
/** When a field is validated the first time, as in Formisch. */
|
|
58
111
|
validate?: ValidationMode;
|
|
59
112
|
/** When a field is validated again after that, as in Formisch. */
|
|
@@ -67,8 +120,21 @@ interface JsonFormInstance<TSchema extends FormSchema = JsonFormSchema$1> {
|
|
|
67
120
|
readonly builder: SchemaBuilder;
|
|
68
121
|
/** The components from the options, if any. */
|
|
69
122
|
readonly components: FieldComponents | undefined;
|
|
70
|
-
/** The
|
|
123
|
+
/** The layout components from the options, if any. */
|
|
124
|
+
readonly layoutComponents: LayoutComponents | undefined;
|
|
125
|
+
/** The definition's fields as a tree, for `<JsonFields only>` and `<JsonField>`. */
|
|
71
126
|
readonly fields: readonly FieldNode$1[];
|
|
127
|
+
/** The definition's layout, the way `<JsonFields>` renders it. */
|
|
128
|
+
readonly layout: FormLayout$1;
|
|
129
|
+
/** The layout's steps: the current one, and Next, Back and Go to. A form without steps has one. */
|
|
130
|
+
readonly steps: JsonFormSteps;
|
|
131
|
+
/**
|
|
132
|
+
* What the conditions of the builder's extensions hide for the form's input now, like the
|
|
133
|
+
* `affects` of `@whatsaaaa/form-builder-affects`: `<JsonFields>` and `<JsonField>` leave it out.
|
|
134
|
+
* Read it in your own renderers. A new object only when what is hidden changes, so the form
|
|
135
|
+
* re-renders for that, not for every keystroke. Without conditions, it hides nothing.
|
|
136
|
+
*/
|
|
137
|
+
readonly visibility: VisibilityState$1;
|
|
72
138
|
}
|
|
73
139
|
/** Any form `useJsonForm` returns, typed or not: what the components take. */
|
|
74
140
|
type AnyJsonFormInstance = JsonFormInstance<FormSchema>;
|
|
@@ -77,7 +143,9 @@ type AnyJsonFormInstance = JsonFormInstance<FormSchema>;
|
|
|
77
143
|
* definition with issues throws the builder's `DefinitionError`, so run `validate()` first when it
|
|
78
144
|
* comes from outside your code. Like Formisch's `useForm`, it reads the definition, the builder and
|
|
79
145
|
* the validation modes on the first render: give the component a new `key` to use another
|
|
80
|
-
* definition. The components are read on every render.
|
|
146
|
+
* definition. The components and layout components are read on every render. With conditions, it
|
|
147
|
+
* clears the fields they clear as soon as they do, with Formisch's `setInput`, wherever the fields
|
|
148
|
+
* are rendered.
|
|
81
149
|
*/
|
|
82
150
|
export declare function useJsonForm(definition: JsonForm, options?: UseJsonFormOptions): JsonFormInstance;
|
|
83
151
|
/**
|
|
@@ -96,22 +164,33 @@ interface JsonFieldProps {
|
|
|
96
164
|
/**
|
|
97
165
|
* Renders one field of a `useJsonForm` form, wherever you put it inside Formisch's `<Form>`. A
|
|
98
166
|
* group or an array comes with its fields. Leave the field out of `<JsonFields>` with `except`.
|
|
167
|
+
* It renders nothing while conditions hide the field.
|
|
99
168
|
*/
|
|
100
|
-
export declare function JsonField({ of, path, components }: JsonFieldProps): ReactElement;
|
|
169
|
+
export declare function JsonField({ of, path, components }: JsonFieldProps): ReactElement | null;
|
|
101
170
|
interface JsonFieldsProps {
|
|
102
171
|
/** What `useJsonForm` returned. */
|
|
103
172
|
of: AnyJsonFormInstance;
|
|
104
173
|
/** Defaults to the components `useJsonForm` got. */
|
|
105
174
|
components?: FieldComponents | undefined;
|
|
106
|
-
/**
|
|
175
|
+
/** Defaults to the layout components `useJsonForm` got. */
|
|
176
|
+
layoutComponents?: LayoutComponents | undefined;
|
|
177
|
+
/** The content of the layout's slots, by name: `{ submit: <button type="submit">Save</button> }`. */
|
|
178
|
+
slots?: Readonly<Record<string, ReactNode>> | undefined;
|
|
179
|
+
/** Renders only these fields, by path, in the order of the definition, without the layout. */
|
|
107
180
|
only?: readonly string[] | undefined;
|
|
108
|
-
/**
|
|
181
|
+
/**
|
|
182
|
+
* Leaves out these fields, by path, e.g. the ones you place with `<JsonField>`. A section or a
|
|
183
|
+
* row left without fields drops out too.
|
|
184
|
+
*/
|
|
109
185
|
except?: readonly string[] | undefined;
|
|
186
|
+
/** Renders the step at this index instead of the current one, e.g. on a review page. */
|
|
187
|
+
step?: number | undefined;
|
|
110
188
|
}
|
|
111
189
|
/**
|
|
112
|
-
* Renders the fields of a `useJsonForm` form with your components, one per field type
|
|
190
|
+
* Renders the fields of a `useJsonForm` form with your components, one per field type, where the
|
|
191
|
+
* definition's `layout` puts them: the current step, with its sections, rows and slots. It renders
|
|
113
192
|
* nothing of its own, so put it inside Formisch's `<Form>` with your own submit button.
|
|
114
193
|
*/
|
|
115
|
-
export declare function JsonFields(
|
|
116
|
-
export type { AnyJsonFormInstance, ArrayFieldProps, DisplayFieldProps, FieldComponents, FieldNode, FieldPath, FieldRole, GroupFieldProps, JsonFieldProps, JsonFieldsProps, JsonFormInstance, JsonFormSchema, TypedJsonFormSchema, UseJsonFormOptions, ValueFieldProps };
|
|
194
|
+
export declare function JsonFields(props: JsonFieldsProps): ReactElement;
|
|
195
|
+
export type { AnyJsonFormInstance, ArrayFieldProps, DisplayFieldProps, FieldComponents, FieldNode, FieldPath, FieldRole, FormLayout, GroupFieldProps, JsonFieldProps, JsonFieldsProps, JsonFormInstance, JsonFormSchema, JsonFormSteps, LayoutComponents, LayoutNode, LayoutStep, RowProps, SectionProps, TypedJsonFormSchema, UseJsonFormOptions, ValueFieldProps, VisibilityState };
|
|
117
196
|
//# sourceMappingURL=index.d.ts.map
|
package/dist/index.js
CHANGED
|
@@ -1,7 +1,185 @@
|
|
|
1
|
-
import { checkComponents, coerceInput, createSchemaBuilder, dotPathOf, findField, isRequired, selectFields, toFieldPath } from "@whatsaaaa/form-builder-schema";
|
|
2
|
-
import { insert, move, remove, useField, useFieldArray, useForm } from "@formisch/react";
|
|
3
|
-
import { useCallback, useMemo, useState } from "react";
|
|
4
|
-
import { Fragment, jsx } from "react/jsx-runtime";
|
|
1
|
+
import { checkComponents, checkLayoutComponents, coerceInput, createSchemaBuilder, dotPathOf, fieldPathsOf, findField, isRequired, issuesOfStep, selectFields, toFieldPath } from "@whatsaaaa/form-builder-schema";
|
|
2
|
+
import { focus, getErrors, getInput, insert, move, remove, setErrors, setInput, useField, useFieldArray, useForm, validate } from "@formisch/react";
|
|
3
|
+
import { Fragment, useCallback, useEffect, useMemo, useRef, useState, useSyncExternalStore } from "react";
|
|
4
|
+
import { Fragment as Fragment$1, jsx } from "react/jsx-runtime";
|
|
5
|
+
import { INTERNAL, getFieldInput, setListener, untrack } from "@formisch/react/internals";
|
|
6
|
+
// src/json-form-steps.ts
|
|
7
|
+
const fieldEvents = /* @__PURE__ */ new WeakMap();
|
|
8
|
+
/** What a field of `form` calls on each event, for a form with steps. Undefined with one step. */
|
|
9
|
+
const fieldEventsOf = (form) => fieldEvents.get(form);
|
|
10
|
+
/**
|
|
11
|
+
* The steps of `layout`, for `useJsonForm`. With more than one, a step shows the errors it had
|
|
12
|
+
* when the user left it, and none the first time they get to it, a step that failed Next
|
|
13
|
+
* revalidates as the user fixes it, a submit before the last step moves on like Next, and a submit
|
|
14
|
+
* that fails because of an earlier step goes back to it. The steps `visibility` hides are skipped.
|
|
15
|
+
* Like Formisch's `useForm`, it reads the validation modes on the first render.
|
|
16
|
+
*/
|
|
17
|
+
function useJsonFormSteps(form, layout, modes, visibility) {
|
|
18
|
+
const all = layout.steps;
|
|
19
|
+
const [index, setIndex] = useState(0);
|
|
20
|
+
const state = useRef({
|
|
21
|
+
index: 0,
|
|
22
|
+
left: /* @__PURE__ */ new Map(),
|
|
23
|
+
failed: /* @__PURE__ */ new Set(),
|
|
24
|
+
focus: void 0,
|
|
25
|
+
submitting: false,
|
|
26
|
+
modes
|
|
27
|
+
});
|
|
28
|
+
const methods = useMemo(() => {
|
|
29
|
+
const at = state.current;
|
|
30
|
+
const shown = () => all.filter((step, i) => i === at.index || !visibility.isStepHidden(step));
|
|
31
|
+
const position = (list) => list.indexOf(all[at.index]);
|
|
32
|
+
async function goTo(target) {
|
|
33
|
+
const list = shown();
|
|
34
|
+
if (!Number.isInteger(target) || target < 0 || target >= list.length) throw new RangeError(`No step ${target}. The form has ${list.length}.`);
|
|
35
|
+
const to = all.indexOf(list[target]);
|
|
36
|
+
if (target <= position(list)) {
|
|
37
|
+
move(to);
|
|
38
|
+
return true;
|
|
39
|
+
}
|
|
40
|
+
await afterTask();
|
|
41
|
+
const { issues } = await validate(form);
|
|
42
|
+
for (const step of list.slice(position(list), target)) {
|
|
43
|
+
const found = issuesOfStep(step, issues);
|
|
44
|
+
if (found.length) {
|
|
45
|
+
stop(all.indexOf(step), found);
|
|
46
|
+
return false;
|
|
47
|
+
}
|
|
48
|
+
at.failed.delete(all.indexOf(step));
|
|
49
|
+
}
|
|
50
|
+
move(to);
|
|
51
|
+
return true;
|
|
52
|
+
}
|
|
53
|
+
/**
|
|
54
|
+
* Moves to a step as the user left it: with the errors it had then, and none the first time, and
|
|
55
|
+
* revalidating if it failed Next. Validating the steps before set errors on its fields, which
|
|
56
|
+
* the user never saw.
|
|
57
|
+
*/
|
|
58
|
+
function move(target) {
|
|
59
|
+
leave();
|
|
60
|
+
const errors = at.left.get(target);
|
|
61
|
+
for (const path of fieldPathsOf(all[target], getInput(form))) setErrors(form, {
|
|
62
|
+
path,
|
|
63
|
+
errors: errors?.get(JSON.stringify(path)) ?? null
|
|
64
|
+
});
|
|
65
|
+
at.index = target;
|
|
66
|
+
setIndex(target);
|
|
67
|
+
}
|
|
68
|
+
/** Keeps the errors of the current step, for when the user comes back to it. */
|
|
69
|
+
function leave() {
|
|
70
|
+
const errors = fieldPathsOf(all[at.index], getInput(form)).map((path) => [JSON.stringify(path), getErrors(form, { path })]);
|
|
71
|
+
at.left.set(at.index, new Map(errors));
|
|
72
|
+
}
|
|
73
|
+
/** Stays on, or goes to, the step at `target`, with its issues shown. */
|
|
74
|
+
function stop(target, found) {
|
|
75
|
+
at.failed.add(target);
|
|
76
|
+
const path = found.find((issue) => issue.field.role === "value")?.path;
|
|
77
|
+
if (target === at.index) {
|
|
78
|
+
if (path) focus(form, { path });
|
|
79
|
+
return;
|
|
80
|
+
}
|
|
81
|
+
leave();
|
|
82
|
+
at.focus = path;
|
|
83
|
+
at.index = target;
|
|
84
|
+
setIndex(target);
|
|
85
|
+
}
|
|
86
|
+
const events = (event) => {
|
|
87
|
+
const validateMode = at.modes.validate ?? "submit";
|
|
88
|
+
if (!at.failed.has(at.index) || validateMode !== "submit" || form.isSubmitted) return;
|
|
89
|
+
if (event === (at.modes.revalidate ?? "input")) validate(form);
|
|
90
|
+
};
|
|
91
|
+
/** After a failed submit: back to the first step before this one with issues, if any. */
|
|
92
|
+
async function afterSubmit() {
|
|
93
|
+
const { issues } = await validate(form);
|
|
94
|
+
const list = shown();
|
|
95
|
+
const step = list.find((each) => issuesOfStep(each, issues).length);
|
|
96
|
+
if (step && list.indexOf(step) < position(list)) stop(all.indexOf(step), issuesOfStep(step, issues));
|
|
97
|
+
}
|
|
98
|
+
const isLast = () => {
|
|
99
|
+
const list = shown();
|
|
100
|
+
return position(list) === list.length - 1;
|
|
101
|
+
};
|
|
102
|
+
const next = () => isLast() ? Promise.resolve(false) : goTo(position(shown()) + 1);
|
|
103
|
+
const back = () => {
|
|
104
|
+
const list = shown();
|
|
105
|
+
const before = list[position(list) - 1];
|
|
106
|
+
if (before) move(all.indexOf(before));
|
|
107
|
+
};
|
|
108
|
+
return {
|
|
109
|
+
goTo,
|
|
110
|
+
next,
|
|
111
|
+
back,
|
|
112
|
+
isLast,
|
|
113
|
+
events,
|
|
114
|
+
afterSubmit
|
|
115
|
+
};
|
|
116
|
+
}, [
|
|
117
|
+
form,
|
|
118
|
+
all,
|
|
119
|
+
visibility
|
|
120
|
+
]);
|
|
121
|
+
useEffect(() => {
|
|
122
|
+
const path = state.current.focus;
|
|
123
|
+
state.current.focus = void 0;
|
|
124
|
+
if (path) focus(form, { path });
|
|
125
|
+
}, [form, index]);
|
|
126
|
+
const stepped = all.length > 1;
|
|
127
|
+
useEffect(() => {
|
|
128
|
+
if (!stepped) return;
|
|
129
|
+
fieldEvents.set(form, methods.events);
|
|
130
|
+
const onSubmit = (event) => {
|
|
131
|
+
if (event.target !== formElementOf(form)) return;
|
|
132
|
+
if (methods.isLast()) {
|
|
133
|
+
state.current.submitting = true;
|
|
134
|
+
return;
|
|
135
|
+
}
|
|
136
|
+
event.preventDefault();
|
|
137
|
+
event.stopImmediatePropagation();
|
|
138
|
+
methods.next();
|
|
139
|
+
};
|
|
140
|
+
document.addEventListener("submit", onSubmit, { capture: true });
|
|
141
|
+
return () => {
|
|
142
|
+
fieldEvents.delete(form);
|
|
143
|
+
document.removeEventListener("submit", onSubmit, { capture: true });
|
|
144
|
+
};
|
|
145
|
+
}, [
|
|
146
|
+
form,
|
|
147
|
+
methods,
|
|
148
|
+
stepped
|
|
149
|
+
]);
|
|
150
|
+
const submitting = form.isSubmitting;
|
|
151
|
+
useEffect(() => {
|
|
152
|
+
if (!state.current.submitting || submitting) return;
|
|
153
|
+
state.current.submitting = false;
|
|
154
|
+
if (!form.isValid) methods.afterSubmit();
|
|
155
|
+
});
|
|
156
|
+
return useMemo(() => {
|
|
157
|
+
const list = all.filter((step, i) => i === index || !visibility.isStepHidden(step));
|
|
158
|
+
const current = all[index];
|
|
159
|
+
const at = list.indexOf(current);
|
|
160
|
+
return {
|
|
161
|
+
list,
|
|
162
|
+
index: at,
|
|
163
|
+
current,
|
|
164
|
+
isFirst: at === 0,
|
|
165
|
+
isLast: at === list.length - 1,
|
|
166
|
+
next: methods.next,
|
|
167
|
+
back: methods.back,
|
|
168
|
+
goTo: methods.goTo
|
|
169
|
+
};
|
|
170
|
+
}, [
|
|
171
|
+
all,
|
|
172
|
+
index,
|
|
173
|
+
visibility,
|
|
174
|
+
methods
|
|
175
|
+
]);
|
|
176
|
+
}
|
|
177
|
+
/** Resolves once the task that called it is over, and the browser is done with its event. */
|
|
178
|
+
const afterTask = () => new Promise((resolve) => setTimeout(resolve));
|
|
179
|
+
/** The `<form>` Formisch's `<Form>` renders, which it keeps on the store for its `submit()`. */
|
|
180
|
+
function formElementOf(form) {
|
|
181
|
+
return form["~internal"]?.element;
|
|
182
|
+
}
|
|
5
183
|
// src/array-field.tsx
|
|
6
184
|
/** Connects a container of kind `array` to Formisch, and renders your component for it. */
|
|
7
185
|
function ArrayField({ of, node, path, component: Component, renderItem }) {
|
|
@@ -10,19 +188,28 @@ function ArrayField({ of, node, path, component: Component, renderItem }) {
|
|
|
10
188
|
const { field } = node;
|
|
11
189
|
const at = array.path;
|
|
12
190
|
const methods = useMemo(() => ({
|
|
13
|
-
add: () =>
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
191
|
+
add: () => {
|
|
192
|
+
insert(form, {
|
|
193
|
+
path: at,
|
|
194
|
+
initialInput: builder.getItemInput(field)
|
|
195
|
+
});
|
|
196
|
+
fieldEventsOf(form)?.("input");
|
|
197
|
+
},
|
|
198
|
+
remove: (index) => {
|
|
199
|
+
remove(form, {
|
|
200
|
+
path: at,
|
|
201
|
+
at: index
|
|
202
|
+
});
|
|
203
|
+
fieldEventsOf(form)?.("input");
|
|
204
|
+
},
|
|
205
|
+
move: (from, to) => {
|
|
206
|
+
move(form, {
|
|
207
|
+
path: at,
|
|
208
|
+
from,
|
|
209
|
+
to
|
|
210
|
+
});
|
|
211
|
+
fieldEventsOf(form)?.("input");
|
|
212
|
+
}
|
|
26
213
|
}), [
|
|
27
214
|
form,
|
|
28
215
|
builder,
|
|
@@ -42,7 +229,31 @@ function ArrayField({ of, node, path, component: Component, renderItem }) {
|
|
|
42
229
|
/** Connects a field with a value to Formisch, and renders your component for it. */
|
|
43
230
|
function ValueField({ of, node, path, component: Component }) {
|
|
44
231
|
const field = useField(of.form, { path });
|
|
45
|
-
const
|
|
232
|
+
const { form } = of;
|
|
233
|
+
const setInput = useCallback((input) => {
|
|
234
|
+
field.onChange(coerceInput(input, node));
|
|
235
|
+
fieldEventsOf(form)?.("input");
|
|
236
|
+
}, [
|
|
237
|
+
field,
|
|
238
|
+
node,
|
|
239
|
+
form
|
|
240
|
+
]);
|
|
241
|
+
const inputProps = of.steps.list.length > 1 ? {
|
|
242
|
+
...field.props,
|
|
243
|
+
onFocus: () => {
|
|
244
|
+
field.props.onFocus();
|
|
245
|
+
fieldEventsOf(form)?.("touch");
|
|
246
|
+
},
|
|
247
|
+
onChange: (event) => {
|
|
248
|
+
field.props.onChange(event);
|
|
249
|
+
fieldEventsOf(form)?.("input");
|
|
250
|
+
fieldEventsOf(form)?.("change");
|
|
251
|
+
},
|
|
252
|
+
onBlur: () => {
|
|
253
|
+
field.props.onBlur();
|
|
254
|
+
fieldEventsOf(form)?.("blur");
|
|
255
|
+
}
|
|
256
|
+
} : field.props;
|
|
46
257
|
return /* @__PURE__ */ jsx(Component, {
|
|
47
258
|
field: node.field,
|
|
48
259
|
path,
|
|
@@ -50,7 +261,7 @@ function ValueField({ of, node, path, component: Component }) {
|
|
|
50
261
|
required: isRequired(node.field),
|
|
51
262
|
input: field.input,
|
|
52
263
|
errors: field.errors,
|
|
53
|
-
inputProps
|
|
264
|
+
inputProps,
|
|
54
265
|
setInput
|
|
55
266
|
});
|
|
56
267
|
}
|
|
@@ -61,27 +272,34 @@ function resolveComponents(components, of) {
|
|
|
61
272
|
if (!resolved) throw new TypeError("No field components. Pass them to useJsonForm, or to the component.");
|
|
62
273
|
return resolved;
|
|
63
274
|
}
|
|
64
|
-
/**
|
|
275
|
+
/**
|
|
276
|
+
* Renders the fields that conditions don't hide. `indexes` are the indexes of the array items the
|
|
277
|
+
* fields are in, outermost first.
|
|
278
|
+
*/
|
|
65
279
|
function renderFields(ctx, nodes, indexes) {
|
|
66
|
-
|
|
280
|
+
const { visibility } = ctx.of;
|
|
281
|
+
return nodes.flatMap((node, position) => visibility.isHidden(node, indexes) ? [] : [renderField(ctx, node, indexes, dotPathOf(node) ?? `#${position}`, (inner) => renderFields(ctx, node.children, inner))]);
|
|
67
282
|
}
|
|
68
|
-
|
|
283
|
+
/**
|
|
284
|
+
* Renders one field with its component. `children` renders the fields inside a group, or inside
|
|
285
|
+
* the item of an array, with the indexes of the items they are in.
|
|
286
|
+
*/
|
|
287
|
+
function renderField(ctx, node, indexes, key, children) {
|
|
69
288
|
const component = ctx.components[node.type];
|
|
70
289
|
const path = toFieldPath(node.dataPath, indexes);
|
|
71
|
-
const key = dotPathOf(node) ?? `#${position}`;
|
|
72
290
|
switch (node.role) {
|
|
73
291
|
case "display": return /* @__PURE__ */ jsx(component, { field: node.field }, key);
|
|
74
292
|
case "group": return /* @__PURE__ */ jsx(component, {
|
|
75
293
|
field: node.field,
|
|
76
294
|
path,
|
|
77
|
-
children:
|
|
295
|
+
children: children(indexes)
|
|
78
296
|
}, key);
|
|
79
297
|
case "array": return /* @__PURE__ */ jsx(ArrayField, {
|
|
80
298
|
of: ctx.of,
|
|
81
299
|
node,
|
|
82
300
|
path,
|
|
83
301
|
component,
|
|
84
|
-
renderItem: (index) =>
|
|
302
|
+
renderItem: (index) => children([...indexes, index])
|
|
85
303
|
}, key);
|
|
86
304
|
case "value": return /* @__PURE__ */ jsx(ValueField, {
|
|
87
305
|
of: ctx.of,
|
|
@@ -95,6 +313,7 @@ function renderField(ctx, node, indexes, position) {
|
|
|
95
313
|
/**
|
|
96
314
|
* Renders one field of a `useJsonForm` form, wherever you put it inside Formisch's `<Form>`. A
|
|
97
315
|
* group or an array comes with its fields. Leave the field out of `<JsonFields>` with `except`.
|
|
316
|
+
* It renders nothing while conditions hide the field.
|
|
98
317
|
*/
|
|
99
318
|
function JsonField({ of, path, components }) {
|
|
100
319
|
const node = findField(of.fields, path, { placed: true });
|
|
@@ -103,24 +322,123 @@ function JsonField({ of, path, components }) {
|
|
|
103
322
|
components: resolveComponents(components, of)
|
|
104
323
|
};
|
|
105
324
|
checkComponents([node], ctx.components);
|
|
106
|
-
|
|
325
|
+
if (of.visibility.isHidden(node, [])) return null;
|
|
326
|
+
return renderField(ctx, node, [], dotPathOf(node) ?? "#0", (indexes) => renderFields(ctx, node.children, indexes));
|
|
327
|
+
}
|
|
328
|
+
// src/render-layout.tsx
|
|
329
|
+
/**
|
|
330
|
+
* Renders layout nodes. A field left out or hidden by conditions drops out, and so does a section
|
|
331
|
+
* hidden by them, and a section or a row left without fields. `indexes` are the indexes of the
|
|
332
|
+
* array items the nodes are in, outermost first.
|
|
333
|
+
*/
|
|
334
|
+
function renderLayout(ctx, nodes, indexes) {
|
|
335
|
+
return ctx.of.visibility.shownNodes(nodes, indexes, ctx.isShown).map((node) => renderNode(ctx, node, indexes));
|
|
336
|
+
}
|
|
337
|
+
function renderNode(ctx, node, indexes) {
|
|
338
|
+
const { key } = node;
|
|
339
|
+
switch (node.type) {
|
|
340
|
+
case "field": return renderField(ctx, node.node, indexes, key, (inner) => renderLayout(ctx, node.children, inner));
|
|
341
|
+
case "section": {
|
|
342
|
+
const Section = ctx.layoutComponents.section;
|
|
343
|
+
return /* @__PURE__ */ jsx(Section, {
|
|
344
|
+
section: node.section,
|
|
345
|
+
children: renderLayout(ctx, node.children, indexes)
|
|
346
|
+
}, key);
|
|
347
|
+
}
|
|
348
|
+
case "row": {
|
|
349
|
+
const Row = ctx.layoutComponents.row;
|
|
350
|
+
return /* @__PURE__ */ jsx(Row, {
|
|
351
|
+
row: node.row,
|
|
352
|
+
spans: node.children.map((cell) => cell.span),
|
|
353
|
+
children: (index) => renderNode(ctx, node.children[index], indexes)
|
|
354
|
+
}, key);
|
|
355
|
+
}
|
|
356
|
+
case "slot": return /* @__PURE__ */ jsx(Fragment, { children: ctx.slots[node.name] }, key);
|
|
357
|
+
}
|
|
107
358
|
}
|
|
108
359
|
// src/json-fields.tsx
|
|
109
360
|
/**
|
|
110
|
-
* Renders the fields of a `useJsonForm` form with your components, one per field type
|
|
361
|
+
* Renders the fields of a `useJsonForm` form with your components, one per field type, where the
|
|
362
|
+
* definition's `layout` puts them: the current step, with its sections, rows and slots. It renders
|
|
111
363
|
* nothing of its own, so put it inside Formisch's `<Form>` with your own submit button.
|
|
112
364
|
*/
|
|
113
|
-
function JsonFields(
|
|
365
|
+
function JsonFields(props) {
|
|
366
|
+
const { of, only, except } = props;
|
|
114
367
|
const ctx = {
|
|
115
368
|
of,
|
|
116
|
-
components: resolveComponents(components, of)
|
|
369
|
+
components: resolveComponents(props.components, of)
|
|
117
370
|
};
|
|
118
371
|
const nodes = selectFields(of.fields, {
|
|
119
372
|
only,
|
|
120
373
|
except
|
|
121
374
|
});
|
|
122
|
-
|
|
123
|
-
|
|
375
|
+
if (only || !of.definition.layout) {
|
|
376
|
+
checkComponents(nodes, ctx.components);
|
|
377
|
+
return /* @__PURE__ */ jsx(Fragment$1, { children: renderFields(ctx, nodes, []) });
|
|
378
|
+
}
|
|
379
|
+
const { layout, steps } = of;
|
|
380
|
+
const left = new Set(except);
|
|
381
|
+
const layoutCtx = {
|
|
382
|
+
...ctx,
|
|
383
|
+
layoutComponents: props.layoutComponents ?? of.layoutComponents ?? {},
|
|
384
|
+
slots: props.slots ?? {},
|
|
385
|
+
isShown: (node) => !left.has(dotPathOf(node) ?? "")
|
|
386
|
+
};
|
|
387
|
+
checkComponents(layout.steps.flatMap((step) => fieldsOf(step.children)), ctx.components);
|
|
388
|
+
checkLayoutComponents(layout, layoutCtx.layoutComponents, layoutCtx.slots);
|
|
389
|
+
const index = props.step ?? steps.index;
|
|
390
|
+
const step = steps.list[index];
|
|
391
|
+
if (!step) throw new RangeError(`No step ${props.step}. The form has ${steps.list.length}.`);
|
|
392
|
+
return /* @__PURE__ */ jsx(Fragment, { children: renderLayout(layoutCtx, step.children, []) }, index);
|
|
393
|
+
}
|
|
394
|
+
/** Every field of the nodes, display elements written in the layout included. */
|
|
395
|
+
function fieldsOf(nodes) {
|
|
396
|
+
return nodes.flatMap((node) => {
|
|
397
|
+
if (node.type === "slot") return [];
|
|
398
|
+
const inner = fieldsOf(node.children);
|
|
399
|
+
return node.type === "field" ? [node.node, ...inner] : inner;
|
|
400
|
+
});
|
|
401
|
+
}
|
|
402
|
+
// src/use-visibility.ts
|
|
403
|
+
/**
|
|
404
|
+
* What the conditions of the definition hide for the form's input, as it changes. Formisch
|
|
405
|
+
* re-renders a component for each signal it reads, so reading the whole input in `useJsonForm`
|
|
406
|
+
* would re-render the form on every keystroke. This watches the input outside React instead, and
|
|
407
|
+
* re-renders only when the state changes: `of()` gives the same object until then. Without
|
|
408
|
+
* conditions, it watches nothing.
|
|
409
|
+
*/
|
|
410
|
+
function useVisibility(form, visibility) {
|
|
411
|
+
const subscribe = useCallback((onChange) => visibility.conditional ? watchInput(form, onChange) : () => {}, [form, visibility]);
|
|
412
|
+
const getSnapshot = () => visibility.of(visibility.conditional ? untrack(() => getFieldInput(form[INTERNAL])) : void 0);
|
|
413
|
+
return useSyncExternalStore(subscribe, getSnapshot, getSnapshot);
|
|
414
|
+
}
|
|
415
|
+
/**
|
|
416
|
+
* Calls `onChange` after each change of the form's input, until the function it returns is called.
|
|
417
|
+
* It reads the input as Formisch's own components do, with a listener: a signal that changes calls
|
|
418
|
+
* it once, so it reads the input again each time, the items of new array items too.
|
|
419
|
+
*/
|
|
420
|
+
function watchInput(form, onChange) {
|
|
421
|
+
const listener = [() => {
|
|
422
|
+
read();
|
|
423
|
+
onChange();
|
|
424
|
+
}, /* @__PURE__ */ new Set()];
|
|
425
|
+
const stop = () => {
|
|
426
|
+
for (const subscribers of listener[1]) subscribers.delete(listener);
|
|
427
|
+
listener[1].clear();
|
|
428
|
+
};
|
|
429
|
+
function read() {
|
|
430
|
+
stop();
|
|
431
|
+
untrack(() => {
|
|
432
|
+
setListener(listener);
|
|
433
|
+
try {
|
|
434
|
+
getFieldInput(form[INTERNAL]);
|
|
435
|
+
} finally {
|
|
436
|
+
setListener(void 0);
|
|
437
|
+
}
|
|
438
|
+
});
|
|
439
|
+
}
|
|
440
|
+
read();
|
|
441
|
+
return stop;
|
|
124
442
|
}
|
|
125
443
|
// src/use-json-form.ts
|
|
126
444
|
function useJsonForm(definition, options = {}) {
|
|
@@ -131,7 +449,9 @@ function useJsonForm(definition, options = {}) {
|
|
|
131
449
|
builder,
|
|
132
450
|
schema: builder.build(definition),
|
|
133
451
|
initialInput: builder.getInitialInput(definition),
|
|
134
|
-
fields: builder.getFieldTree(definition)
|
|
452
|
+
fields: builder.getFieldTree(definition),
|
|
453
|
+
layout: builder.getLayout(definition),
|
|
454
|
+
visibility: builder.getVisibility(definition)
|
|
135
455
|
};
|
|
136
456
|
});
|
|
137
457
|
const form = useForm({
|
|
@@ -140,17 +460,33 @@ function useJsonForm(definition, options = {}) {
|
|
|
140
460
|
validate: options.validate,
|
|
141
461
|
revalidate: options.revalidate
|
|
142
462
|
});
|
|
143
|
-
const
|
|
463
|
+
const visibility = useVisibility(form, built.visibility);
|
|
464
|
+
const { toClear } = visibility;
|
|
465
|
+
useEffect(() => {
|
|
466
|
+
for (const { path, input } of toClear) setInput(form, {
|
|
467
|
+
path,
|
|
468
|
+
input
|
|
469
|
+
});
|
|
470
|
+
}, [form, toClear]);
|
|
471
|
+
const steps = useJsonFormSteps(form, built.layout, options, visibility);
|
|
472
|
+
const { components, layoutComponents } = options;
|
|
144
473
|
return useMemo(() => ({
|
|
145
474
|
form,
|
|
146
475
|
definition: built.definition,
|
|
147
476
|
builder: built.builder,
|
|
148
477
|
components,
|
|
149
|
-
|
|
478
|
+
layoutComponents,
|
|
479
|
+
fields: built.fields,
|
|
480
|
+
layout: built.layout,
|
|
481
|
+
steps,
|
|
482
|
+
visibility
|
|
150
483
|
}), [
|
|
151
484
|
form,
|
|
152
485
|
built,
|
|
153
|
-
components
|
|
486
|
+
components,
|
|
487
|
+
layoutComponents,
|
|
488
|
+
steps,
|
|
489
|
+
visibility
|
|
154
490
|
]);
|
|
155
491
|
}
|
|
156
492
|
export { JsonField, JsonFields, useJsonForm };
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","names":["Display","Group"],"sources":["../src/array-field.tsx","../src/value-field.tsx","../src/render-fields.tsx","../src/json-field.tsx","../src/json-fields.tsx","../src/use-json-form.ts"],"sourcesContent":["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 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 const methods = useMemo(\n () => ({\n // A new item starts with the defaults of its fields, like the items of a new form.\n add: () => insert(form, { path: at, initialInput: builder.getItemInput(field) as never }),\n remove: (index: number) => remove(form, { path: at, at: index }),\n move: (from: number, to: number) => move(form, { path: at, from, to }),\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 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 setInput = useCallback(\n (input: unknown) => field.onChange(coerceInput(input, node) as never),\n [field, node],\n )\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={field.props}\n setInput={setInput}\n />\n )\n}\n","import { dotPathOf, type FieldNode, toFieldPath } from '@whatsaaaa/form-builder-schema'\nimport type { ComponentType, ReactElement } 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) => renderField(ctx, node, indexes, position))\n}\n\nexport function renderField(\n ctx: RenderContext,\n node: FieldNode,\n indexes: readonly number[],\n position: number,\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 const key = dotPathOf(node) ?? `#${position}`\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 {renderFields(ctx, node.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) => renderFields(ctx, node.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, findField } from '@whatsaaaa/form-builder-schema'\nimport type { ReactElement } from 'react'\nimport type { FieldComponents } from './field-components'\nimport { type RenderContext, renderField, 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, [], 0)\n}\n","import { checkComponents, selectFields } from '@whatsaaaa/form-builder-schema'\nimport type { ReactElement } from 'react'\nimport type { FieldComponents } from './field-components'\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 /** Renders only these fields, by path, in the order of the definition. */\n only?: readonly string[] | undefined\n /** Leaves out these fields, by path, e.g. the ones you place with `<JsonField>`. */\n except?: readonly string[] | undefined\n}\n\n/**\n * Renders the fields of a `useJsonForm` form with your components, one per field type. It renders\n * nothing of its own, so put it inside Formisch's `<Form>` with your own submit button.\n */\nexport function JsonFields({ of, components, only, except }: JsonFieldsProps): ReactElement {\n const ctx: RenderContext = { of, components: resolveComponents(components, of) }\n const nodes = selectFields(of.fields, { only, except })\n checkComponents(nodes, ctx.components)\n\n return <>{renderFields(ctx, nodes, [])}</>\n}\n","import { type FormSchema, type FormStore, useForm, type ValidationMode } from '@formisch/react'\nimport {\n createSchemaBuilder,\n type FieldNode,\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 } from './field-components'\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 /** 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 definition's fields as a tree, the way `<JsonFields>` renders them. */\n readonly fields: readonly FieldNode[]\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 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 }\n })\n const form = useForm({\n schema: built.schema,\n initialInput: built.initialInput,\n validate: options.validate,\n revalidate: options.revalidate,\n })\n const { components } = options\n return useMemo(\n () => ({\n form,\n definition: built.definition,\n builder: built.builder,\n components,\n fields: built.fields,\n }),\n [form, built, components],\n )\n}\n"],"mappings":";;;;;;AAgBA,SAAgB,WAAW,EACzB,IACA,MACA,MACA,WAAW,WACX,cAC0C;CAE1C,MAAM,QAAQ,cAAc,GAAG,MAAM,EAAQ,KAAc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AAO;GACL;GACA;GACA,QAAQ,QAAQ,MAAM,UAAU;GAChC,cAAc,QAAQ,gBAAgB,UAAU;GAChD,QAAQ,QAAQ,aAAa,UAAU;EACzC;CACF,CAAC;CACD,MAAM,OAAO,QAAQ;EACnB,QAAQ,MAAM;EACd,cAAc,MAAM;EACpB,UAAU,QAAQ;EAClB,YAAY,QAAQ;CACtB,CAAC;CACD,MAAM,EAAE,eAAe;CACvB,OAAO,eACE;EACL;EACA,YAAY,MAAM;EAClB,SAAS,MAAM;EACf;EACA,QAAQ,MAAM;CAChB,IACA;EAAC;EAAM;EAAO;CAAU,CAC1B;AACF"}
|
|
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-visibility.ts","../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 type VisibilityState,\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 /**\n * The steps on show, in order. A step whose fields are all hidden by conditions, or that is\n * hidden itself, is left out, unless it is the current one: Next and Back skip it.\n */\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\n * revalidates as the user fixes it, a submit before the last step moves on like Next, and a submit\n * that fails because of an earlier step goes back to it. The steps `visibility` hides are skipped.\n * Like Formisch's `useForm`, it reads the validation modes on the first render.\n */\nexport function useJsonFormSteps(\n form: FormStore,\n layout: FormLayout,\n modes: Modes,\n visibility: VisibilityState,\n): JsonFormSteps {\n const all = layout.steps\n // The current step, by its index in `all`, as are the steps in `state` below.\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 // The current step stays on show, so it never goes from under the user.\n const shown = () => all.filter((step, i) => i === at.index || !visibility.isStepHidden(step))\n const position = (list: readonly LayoutStep[]) => list.indexOf(all[at.index] as LayoutStep)\n\n async function goTo(target: number): Promise<boolean> {\n const list = shown()\n if (!Number.isInteger(target) || target < 0 || target >= list.length) {\n throw new RangeError(`No step ${target}. The form has ${list.length}.`)\n }\n const to = all.indexOf(list[target] as LayoutStep)\n if (target <= position(list)) {\n move(to)\n return true\n }\n // Next goes on once the task that called it is over. A click runs its default action after its\n // handlers, and React can render in between: a Next button that turns into the submit button on\n // the last step would then submit the form as the user gets there.\n await afterTask()\n const { issues } = await validate(form)\n for (const step of list.slice(position(list), target)) {\n const found = issuesOfStep(step, issues)\n if (found.length) {\n stop(all.indexOf(step), found)\n return false\n }\n at.failed.delete(all.indexOf(step))\n }\n move(to)\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(all[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(all[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 list = shown()\n const step = list.find((each) => issuesOfStep(each, issues).length)\n if (step && list.indexOf(step) < position(list)) {\n stop(all.indexOf(step), issuesOfStep(step, issues))\n }\n }\n\n const isLast = () => {\n const list = shown()\n return position(list) === list.length - 1\n }\n const next = () => (isLast() ? Promise.resolve(false) : goTo(position(shown()) + 1))\n const back = () => {\n const list = shown()\n const before = list[position(list) - 1]\n if (before) move(all.indexOf(before))\n }\n return { goTo, next, back, isLast, events, afterSubmit }\n }, [form, all, visibility])\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 = all.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 (methods.isLast()) {\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, 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 const list = all.filter((step, i) => i === index || !visibility.isStepHidden(step))\n const current = all[index] as LayoutStep\n const at = list.indexOf(current)\n return {\n list,\n index: at,\n current,\n isFirst: at === 0,\n isLast: at === list.length - 1,\n next: methods.next,\n back: methods.back,\n goTo: methods.goTo,\n }\n }, [all, index, visibility, methods])\n}\n\n/** Resolves once the task that called it is over, and the browser is done with its event. */\nconst afterTask = () => new Promise<void>((resolve) => setTimeout(resolve))\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/**\n * Renders the fields that conditions don't hide. `indexes` are the indexes of the array items the\n * fields are in, outermost first.\n */\nexport function renderFields(\n ctx: RenderContext,\n nodes: readonly FieldNode[],\n indexes: readonly number[],\n): ReactElement[] {\n const { visibility } = ctx.of\n // A display element is keyed by its position among all the nodes, which stays the same.\n return nodes.flatMap((node, position) =>\n visibility.isHidden(node, indexes)\n ? []\n : [\n renderField(ctx, node, indexes, dotPathOf(node) ?? `#${position}`, (inner) =>\n renderFields(ctx, node.children, inner),\n ),\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 * It renders nothing while conditions hide the field.\n */\nexport function JsonField({ of, path, components }: JsonFieldProps): ReactElement | null {\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 if (of.visibility.isHidden(node, [])) return null\n return renderField(ctx, node, [], dotPathOf(node) ?? '#0', (indexes) =>\n renderFields(ctx, node.children, indexes),\n )\n}\n","import type { IsFieldShown, LayoutNode } 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 or hidden by conditions drops out, and so does a section\n * hidden by them, and a section or a row left without fields. `indexes` are the indexes of the\n * 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 ctx.of.visibility\n .shownNodes(nodes, indexes, ctx.isShown)\n .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 { FormStore } from '@formisch/react'\nimport {\n getFieldInput,\n INTERNAL,\n type Listener,\n setListener,\n untrack,\n} from '@formisch/react/internals'\nimport type { Visibility, VisibilityState } from '@whatsaaaa/form-builder-schema'\nimport { useCallback, useSyncExternalStore } from 'react'\n\n/**\n * What the conditions of the definition hide for the form's input, as it changes. Formisch\n * re-renders a component for each signal it reads, so reading the whole input in `useJsonForm`\n * would re-render the form on every keystroke. This watches the input outside React instead, and\n * re-renders only when the state changes: `of()` gives the same object until then. Without\n * conditions, it watches nothing.\n */\nexport function useVisibility(form: FormStore, visibility: Visibility): VisibilityState {\n const subscribe = useCallback(\n (onChange: () => void) => (visibility.conditional ? watchInput(form, onChange) : () => {}),\n [form, visibility],\n )\n const getSnapshot = () =>\n visibility.of(visibility.conditional ? untrack(() => getFieldInput(form[INTERNAL])) : undefined)\n return useSyncExternalStore(subscribe, getSnapshot, getSnapshot)\n}\n\n/**\n * Calls `onChange` after each change of the form's input, until the function it returns is called.\n * It reads the input as Formisch's own components do, with a listener: a signal that changes calls\n * it once, so it reads the input again each time, the items of new array items too.\n */\nfunction watchInput(form: FormStore, onChange: () => void): () => void {\n const listener: Listener = [\n () => {\n read()\n onChange()\n },\n new Set(),\n ]\n const stop = () => {\n for (const subscribers of listener[1]) subscribers.delete(listener)\n listener[1].clear()\n }\n function read() {\n stop()\n // untrack() sets back the listener of a component that may be rendering now.\n untrack(() => {\n setListener(listener)\n try {\n getFieldInput(form[INTERNAL])\n } finally {\n setListener(undefined)\n }\n })\n }\n read()\n return stop\n}\n","import {\n type FormSchema,\n type FormStore,\n setInput,\n useForm,\n type ValidationMode,\n} 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 type VisibilityState,\n} from '@whatsaaaa/form-builder-schema'\nimport { useEffect, useMemo, useState } from 'react'\nimport type { FieldComponents, LayoutComponents } from './field-components'\nimport { type JsonFormSteps, useJsonFormSteps } from './json-form-steps'\nimport { useVisibility } from './use-visibility'\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 * What the conditions of the builder's extensions hide for the form's input now, like the\n * `affects` of `@whatsaaaa/form-builder-affects`: `<JsonFields>` and `<JsonField>` leave it out.\n * Read it in your own renderers. A new object only when what is hidden changes, so the form\n * re-renders for that, not for every keystroke. Without conditions, it hides nothing.\n */\n readonly visibility: VisibilityState\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. With conditions, it\n * clears the fields they clear as soon as they do, with Formisch's `setInput`, wherever the fields\n * are rendered.\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 visibility: builder.getVisibility(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 visibility = useVisibility(form, built.visibility)\n // A new state means something to clear may have come. It is empty once the fields are blank.\n const { toClear } = visibility\n useEffect(() => {\n // The paths come from the definition at runtime, so the schema's types can't check them.\n for (const { path, input } of toClear) setInput(form, { path, input } as never)\n }, [form, toClear])\n const steps = useJsonFormSteps(form, built.layout, options, visibility)\n const { components, layoutComponents } = options\n return useMemo(\n () => ({\n form,\n definition: built.definition,\n builder: built.builder,\n components,\n layoutComponents,\n fields: built.fields,\n layout: built.layout,\n steps,\n visibility,\n }),\n [form, built, components, layoutComponents, steps, visibility],\n )\n}\n"],"mappings":";;;;;;AAyDA,MAAM,8BAAc,IAAI,QAAgC;;AAGxD,MAAa,iBAAiB,SAA6C,YAAY,IAAI,IAAI;;;;;;;;AAc/F,SAAgB,iBACd,MACA,QACA,OACA,YACe;CACf,MAAM,MAAM,OAAO;CAEnB,MAAM,CAAC,OAAO,YAAY,SAAS,CAAC;CAEpC,MAAM,QAAQ,OAAO;EACnB,OAAO;EAEP,sBAAM,IAAI,IAAiC;EAE3C,wBAAQ,IAAI,IAAY;EAExB,OAAO,KAAA;EAEP,YAAY;EACZ;CACF,CAAC;CAED,MAAM,UAAU,cAAc;EAC5B,MAAM,KAAK,MAAM;EAEjB,MAAM,cAAc,IAAI,QAAQ,MAAM,MAAM,MAAM,GAAG,SAAS,CAAC,WAAW,aAAa,IAAI,CAAC;EAC5F,MAAM,YAAY,SAAgC,KAAK,QAAQ,IAAI,GAAG,MAAoB;EAE1F,eAAe,KAAK,QAAkC;GACpD,MAAM,OAAO,MAAM;GACnB,IAAI,CAAC,OAAO,UAAU,MAAM,KAAK,SAAS,KAAK,UA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OAAO,CAAC;CAClB,MAAM,QAAQ,iBAAiB,MAAM,MAAM,QAAQ,SAAS,UAAU;CACtE,MAAM,EAAE,YAAY,qBAAqB;CACzC,OAAO,eACE;EACL;EACA,YAAY,MAAM;EAClB,SAAS,MAAM;EACf;EACA;EACA,QAAQ,MAAM;EACd,QAAQ,MAAM;EACd;EACA;CACF,IACA;EAAC;EAAM;EAAO;EAAY;EAAkB;EAAO;CAAU,CAC/D;AACF"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@whatsaaaa/form-builder-react",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.3.0",
|
|
4
4
|
"description": "Render JSON form definitions with Formisch and your own React components.",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"form",
|
|
@@ -33,7 +33,7 @@
|
|
|
33
33
|
"access": "public"
|
|
34
34
|
},
|
|
35
35
|
"dependencies": {
|
|
36
|
-
"@whatsaaaa/form-builder-schema": "^0.
|
|
36
|
+
"@whatsaaaa/form-builder-schema": "^0.15.0"
|
|
37
37
|
},
|
|
38
38
|
"devDependencies": {
|
|
39
39
|
"@arethetypeswrong/cli": "^0.18.5",
|
|
@@ -42,6 +42,7 @@
|
|
|
42
42
|
"@types/react": "^19.3.0",
|
|
43
43
|
"@types/react-dom": "^19.3.0",
|
|
44
44
|
"@vitest/coverage-v8": "^5.0.5",
|
|
45
|
+
"@whatsaaaa/form-builder-affects": "^0.1.0",
|
|
45
46
|
"happy-dom": "^20.0.0",
|
|
46
47
|
"publint": "^0.3.25",
|
|
47
48
|
"react": "^19.3.1",
|