react-form-step-manager 0.0.0-stage → 0.1.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 +202 -0
- package/NOTICE +5 -0
- package/README.md +208 -3
- package/ai/AGENTS.md +17 -0
- package/ai/skills/react-form-step-manager/SKILL.md +34 -0
- package/ai/skills/react-form-step-manager/references/api.md +49 -0
- package/ai/skills/react-form-step-manager/references/claims.md +16 -0
- package/ai/skills/react-form-step-manager/references/recipes.md +16 -0
- package/ai/skills/react-form-step-manager/references/strategy.md +47 -0
- package/ai/skills/react-form-step-manager/references/testing.md +31 -0
- package/bin/install-skill.mjs +61 -0
- package/dist/index.cjs +547 -0
- package/dist/index.cjs.map +1 -0
- package/dist/index.d.cts +217 -0
- package/dist/index.d.ts +217 -0
- package/dist/index.js +523 -0
- package/dist/index.js.map +1 -0
- package/llms.txt +14 -0
- package/package.json +87 -6
package/LICENSE
ADDED
|
@@ -0,0 +1,202 @@
|
|
|
1
|
+
|
|
2
|
+
Apache License
|
|
3
|
+
Version 2.0, January 2004
|
|
4
|
+
http://www.apache.org/licenses/
|
|
5
|
+
|
|
6
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
7
|
+
|
|
8
|
+
1. Definitions.
|
|
9
|
+
|
|
10
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
11
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
12
|
+
|
|
13
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
14
|
+
the copyright owner that is granting the License.
|
|
15
|
+
|
|
16
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
17
|
+
other entities that control, are controlled by, or are under common
|
|
18
|
+
control with that entity. For the purposes of this definition,
|
|
19
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
20
|
+
direction or management of such entity, whether by contract or
|
|
21
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
22
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
23
|
+
|
|
24
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
25
|
+
exercising permissions granted by this License.
|
|
26
|
+
|
|
27
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
28
|
+
including but not limited to software source code, documentation
|
|
29
|
+
source, and configuration files.
|
|
30
|
+
|
|
31
|
+
"Object" form shall mean any form resulting from mechanical
|
|
32
|
+
transformation or translation of a Source form, including but
|
|
33
|
+
not limited to compiled object code, generated documentation,
|
|
34
|
+
and conversions to other media types.
|
|
35
|
+
|
|
36
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
37
|
+
Object form, made available under the License, as indicated by a
|
|
38
|
+
copyright notice that is included in or attached to the work
|
|
39
|
+
(an example is provided in the Appendix below).
|
|
40
|
+
|
|
41
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
42
|
+
form, that is based on (or derived from) the Work and for which the
|
|
43
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
44
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
45
|
+
of this License, Derivative Works shall not include works that remain
|
|
46
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
47
|
+
the Work and Derivative Works thereof.
|
|
48
|
+
|
|
49
|
+
"Contribution" shall mean any work of authorship, including
|
|
50
|
+
the original version of the Work and any modifications or additions
|
|
51
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
52
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
53
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
54
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
55
|
+
means any form of electronic, verbal, or written communication sent
|
|
56
|
+
to the Licensor or its representatives, including but not limited to
|
|
57
|
+
communication on electronic mailing lists, source code control systems,
|
|
58
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
59
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
60
|
+
excluding communication that is conspicuously marked or otherwise
|
|
61
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
62
|
+
|
|
63
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
64
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
65
|
+
subsequently incorporated within the Work.
|
|
66
|
+
|
|
67
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
68
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
69
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
70
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
71
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
72
|
+
Work and such Derivative Works in Source or Object form.
|
|
73
|
+
|
|
74
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
75
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
76
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
77
|
+
(except as stated in this section) patent license to make, have made,
|
|
78
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
79
|
+
where such license applies only to those patent claims licensable
|
|
80
|
+
by such Contributor that are necessarily infringed by their
|
|
81
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
82
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
83
|
+
institute patent litigation against any entity (including a
|
|
84
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
85
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
86
|
+
or contributory patent infringement, then any patent licenses
|
|
87
|
+
granted to You under this License for that Work shall terminate
|
|
88
|
+
as of the date such litigation is filed.
|
|
89
|
+
|
|
90
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
91
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
92
|
+
modifications, and in Source or Object form, provided that You
|
|
93
|
+
meet the following conditions:
|
|
94
|
+
|
|
95
|
+
(a) You must give any other recipients of the Work or
|
|
96
|
+
Derivative Works a copy of this License; and
|
|
97
|
+
|
|
98
|
+
(b) You must cause any modified files to carry prominent notices
|
|
99
|
+
stating that You changed the files; and
|
|
100
|
+
|
|
101
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
102
|
+
that You distribute, all copyright, patent, trademark, and
|
|
103
|
+
attribution notices from the Source form of the Work,
|
|
104
|
+
excluding those notices that do not pertain to any part of
|
|
105
|
+
the Derivative Works; and
|
|
106
|
+
|
|
107
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
108
|
+
distribution, then any Derivative Works that You distribute must
|
|
109
|
+
include a readable copy of the attribution notices contained
|
|
110
|
+
within such NOTICE file, excluding those notices that do not
|
|
111
|
+
pertain to any part of the Derivative Works, in at least one
|
|
112
|
+
of the following places: within a NOTICE text file distributed
|
|
113
|
+
as part of the Derivative Works; within the Source form or
|
|
114
|
+
documentation, if provided along with the Derivative Works; or,
|
|
115
|
+
within a display generated by the Derivative Works, if and
|
|
116
|
+
wherever such third-party notices normally appear. The contents
|
|
117
|
+
of the NOTICE file are for informational purposes only and
|
|
118
|
+
do not modify the License. You may add Your own attribution
|
|
119
|
+
notices within Derivative Works that You distribute, alongside
|
|
120
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
121
|
+
that such additional attribution notices cannot be construed
|
|
122
|
+
as modifying the License.
|
|
123
|
+
|
|
124
|
+
You may add Your own copyright statement to Your modifications and
|
|
125
|
+
may provide additional or different license terms and conditions
|
|
126
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
127
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
128
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
129
|
+
the conditions stated in this License.
|
|
130
|
+
|
|
131
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
132
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
133
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
134
|
+
this License, without any additional terms or conditions.
|
|
135
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
136
|
+
the terms of any separate license agreement you may have executed
|
|
137
|
+
with Licensor regarding such Contributions.
|
|
138
|
+
|
|
139
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
140
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
141
|
+
except as required for reasonable and customary use in describing the
|
|
142
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
143
|
+
|
|
144
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
145
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
146
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
147
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
148
|
+
implied, including, without limitation, any warranties or conditions
|
|
149
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
150
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
151
|
+
appropriateness of using or redistributing the Work and assume any
|
|
152
|
+
risks associated with Your exercise of permissions under this License.
|
|
153
|
+
|
|
154
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
155
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
156
|
+
unless required by applicable law (such as deliberate and grossly
|
|
157
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
158
|
+
liable to You for damages, including any direct, indirect, special,
|
|
159
|
+
incidental, or consequential damages of any character arising as a
|
|
160
|
+
result of this License or out of the use or inability to use the
|
|
161
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
162
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
163
|
+
other commercial damages or losses), even if such Contributor
|
|
164
|
+
has been advised of the possibility of such damages.
|
|
165
|
+
|
|
166
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
167
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
168
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
169
|
+
or other liability obligations and/or rights consistent with this
|
|
170
|
+
License. However, in accepting such obligations, You may act only
|
|
171
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
172
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
173
|
+
defend, and hold each Contributor harmless for any liability
|
|
174
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
175
|
+
of your accepting any such warranty or additional liability.
|
|
176
|
+
|
|
177
|
+
END OF TERMS AND CONDITIONS
|
|
178
|
+
|
|
179
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
180
|
+
|
|
181
|
+
To apply the Apache License to your work, attach the following
|
|
182
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
183
|
+
replaced with your own identifying information. (Don't include
|
|
184
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
185
|
+
comment syntax for the file format. We also recommend that a
|
|
186
|
+
file or class name and description of purpose be included on the
|
|
187
|
+
same "printed page" as the copyright notice for easier
|
|
188
|
+
identification within third-party archives.
|
|
189
|
+
|
|
190
|
+
Copyright [yyyy] [name of copyright owner]
|
|
191
|
+
|
|
192
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
193
|
+
you may not use this file except in compliance with the License.
|
|
194
|
+
You may obtain a copy of the License at
|
|
195
|
+
|
|
196
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
197
|
+
|
|
198
|
+
Unless required by applicable law or agreed to in writing, software
|
|
199
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
200
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
201
|
+
See the License for the specific language governing permissions and
|
|
202
|
+
limitations under the License.
|
package/NOTICE
ADDED
package/README.md
CHANGED
|
@@ -1,3 +1,208 @@
|
|
|
1
|
-
#
|
|
2
|
-
|
|
3
|
-
|
|
1
|
+
# react-form-step-manager
|
|
2
|
+
|
|
3
|
+
Multi-step form manager for React built on [React Hook Form](https://react-hook-form.com) and [Zod](https://zod.dev), with per-step **claims**. One `FormManager` instance per form, a strategy class that declares steps, schema and submit, and hooks that read the instance from context.
|
|
4
|
+
|
|
5
|
+
## Install
|
|
6
|
+
|
|
7
|
+
```bash
|
|
8
|
+
npm install react-form-step-manager react react-hook-form zod @hookform/resolvers
|
|
9
|
+
```
|
|
10
|
+
|
|
11
|
+
Peer dependencies: `react ^18.3 || ^19`, `react-hook-form ^7.62`, `zod ^4`, `@hookform/resolvers ^5`.
|
|
12
|
+
|
|
13
|
+
## Quick start
|
|
14
|
+
|
|
15
|
+
```tsx
|
|
16
|
+
import { z } from "zod";
|
|
17
|
+
import { useController } from "react-hook-form";
|
|
18
|
+
import {
|
|
19
|
+
AbstractStrategy, FormManager, FormManagerProvider, StepForm,
|
|
20
|
+
useFormControl, useFormManager, useFormSteps, type Step,
|
|
21
|
+
} from "react-form-step-manager";
|
|
22
|
+
|
|
23
|
+
const schema = z.object({
|
|
24
|
+
customer: z.object({ name: z.string().min(1) }),
|
|
25
|
+
review: z.object({ confirmed: z.boolean() }),
|
|
26
|
+
});
|
|
27
|
+
type Values = z.infer<typeof schema>;
|
|
28
|
+
|
|
29
|
+
class OrderStrategy extends AbstractStrategy<typeof schema, Values> {
|
|
30
|
+
protected readonly steps: readonly Step<typeof schema>[] = [
|
|
31
|
+
{ name: "customer", id: "order.customer" },
|
|
32
|
+
{ name: "review", id: "order.review" },
|
|
33
|
+
];
|
|
34
|
+
protected readonly schema = schema;
|
|
35
|
+
protected readonly metadata = {};
|
|
36
|
+
async submit(data: Values) { await save(data); }
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
const manager = new FormManager<OrderStrategy>().bootstrap({
|
|
40
|
+
strategy: new OrderStrategy(),
|
|
41
|
+
defaultValues: { customer: { name: "" }, review: { confirmed: false } },
|
|
42
|
+
});
|
|
43
|
+
|
|
44
|
+
function Wizard() {
|
|
45
|
+
const manager = useFormManager<OrderStrategy>();
|
|
46
|
+
const { currentStep } = useFormSteps();
|
|
47
|
+
const { control } = useFormControl();
|
|
48
|
+
const { field } = useController({ control, name: "customer.name" });
|
|
49
|
+
return (
|
|
50
|
+
<StepForm name={currentStep.name} id={currentStep.id} onSubmit={() => manager.submit()}>
|
|
51
|
+
{currentStep.name === "customer" && <input {...field} />}
|
|
52
|
+
{manager.isLastStep() ? <button type="submit">Submit</button> : <button type="button" onClick={() => manager.goNext()}>Next</button>}
|
|
53
|
+
</StepForm>
|
|
54
|
+
);
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
export const App = () => (
|
|
58
|
+
<FormManagerProvider manager={manager}><Wizard /></FormManagerProvider>
|
|
59
|
+
);
|
|
60
|
+
```
|
|
61
|
+
|
|
62
|
+
Bootstrap the manager **before** rendering the provider.
|
|
63
|
+
|
|
64
|
+
## API summary
|
|
65
|
+
|
|
66
|
+
| Export | Purpose |
|
|
67
|
+
|---|---|
|
|
68
|
+
| `FormManager<TStrategy>` | Owns one form: RHF control, current step, claims, listeners. `new FormManager()`; no singleton. |
|
|
69
|
+
| `AbstractStrategy<TSchema, TSubmitData, TMetadata, TSubmitResult, TClaim, TAction>` | Declares `steps`, `schema`, `metadata`, `submit`, hooks `onReset`/`onDispose`. |
|
|
70
|
+
| `FormManagerProvider` | `manager={...}` (multi-step) or `methods={useForm(...)}` (single page). |
|
|
71
|
+
| `useFormManager()` | The manager from context; throws outside a provider. |
|
|
72
|
+
| `useFormSteps()` | `{ steps, currentStep, formStatus }` with a stable snapshot. |
|
|
73
|
+
| `useFormClaims(id)` | Actions granted on a claim. |
|
|
74
|
+
| `useFormControl()` | `{ control, setValue, setError, trigger }`. |
|
|
75
|
+
| `StepForm` | `<form noValidate>` that prevents the default submit. |
|
|
76
|
+
| `Step`, `StrategyClass`, `BootstrapOptions`, `ClaimsResolver` | Types. |
|
|
77
|
+
|
|
78
|
+
Key behaviours:
|
|
79
|
+
|
|
80
|
+
- **Claims**: a step with `claim` (and `action`, default `view`) exists only if `bootstrap({ claims })` grants it. A denied step is absent from `steps` and its schema is neutralized so its default values survive submit.
|
|
81
|
+
- **Navigation**: `goNext()`/`goPrev()` return `null` at the edges; `goToStep(name)` returns `true`/`null`/`false` (moved / already there / unknown).
|
|
82
|
+
- **Submit**: validates first; the strategy may call `report` many times.
|
|
83
|
+
- **Scope**: `ensureScope(id, factory, revision)` is idempotent; `clearScope(id)` clears only the active scope.
|
|
84
|
+
- The schema root must be a `ZodObject`; each top-level key is a step.
|
|
85
|
+
|
|
86
|
+
Full reference: [`ai/skills/react-form-step-manager/references/api.md`](ai/skills/react-form-step-manager/references/api.md).
|
|
87
|
+
|
|
88
|
+
## Bootstrap id
|
|
89
|
+
|
|
90
|
+
`manager.getBootstrapId()` returns an id (UUID, with a fallback for non-secure contexts) regenerated on every `bootstrap()` and every `resetFormManager()`, and `null` after `clearAll()`. It identifies one *generation* of the form: same id means same RHF control and same strategy instance state.
|
|
91
|
+
|
|
92
|
+
Use it as a React `key` to remount the provider (and everything below) when the form is rebuilt, and to discard stale async work started for a previous generation.
|
|
93
|
+
|
|
94
|
+
```tsx
|
|
95
|
+
<FormManagerProvider key={manager.getBootstrapId()} manager={manager}>...</FormManagerProvider>
|
|
96
|
+
```
|
|
97
|
+
|
|
98
|
+
## When an input change must change the strategy
|
|
99
|
+
|
|
100
|
+
Pick the lightest option that fits.
|
|
101
|
+
|
|
102
|
+
| Input change affects | Do | Control / id | Current step |
|
|
103
|
+
|---|---|---|---|
|
|
104
|
+
| Only values | `manager.mergeFormValues(partial)` or `form.setValue` | kept / kept | kept |
|
|
105
|
+
| Metadata the strategy reads (and some values) | `manager.updateMetadataAndResetFormFields(metadata, { values })` | kept / kept | kept |
|
|
106
|
+
| Everything back to defaults | `manager.resetFormManager()` | kept / **new id** | back to first step |
|
|
107
|
+
| Steps, schema or claims, **keeping typed values and current step** | `manager.replaceStrategy(new OtherStrategy(), { claims?, defaultValues? })` | kept / kept | kept by name |
|
|
108
|
+
| Steps, schema or claims, from scratch (different strategy) | `manager.bootstrap({ strategy: new OtherStrategy(), defaultValues, claims })` | **new** / **new id** | back to first step |
|
|
109
|
+
| A claim decision (permissions changed) | `ensureScope(id, factory, newRevision)` | **new** / **new id** | back to first step |
|
|
110
|
+
|
|
111
|
+
`replaceStrategy` details:
|
|
112
|
+
|
|
113
|
+
- Keeps the RHF control (values, dirty, touched), step listeners, provider and `bootstrapId`: no remount needed.
|
|
114
|
+
- The old strategy gets `onDispose()`. Claims: `options.claims` replaces the resolver; if omitted the current one is reused and granted actions are recomputed for the new strategy's claims.
|
|
115
|
+
- Current step is matched by `name`; if it no longer exists it falls back to the closest previous surviving step, else the first.
|
|
116
|
+
- `options.defaultValues` only fills top-level keys still `undefined` (steps new to the schema); it never overwrites user input.
|
|
117
|
+
- The whole form is revalidated (`trigger()`) against the new schema, so new steps may show errors immediately. Keys removed from the schema stay in RHF but are stripped at submit.
|
|
118
|
+
|
|
119
|
+
Notes on rebuilding (`bootstrap`, `ensureScope` with a new revision):
|
|
120
|
+
|
|
121
|
+
- The previous strategy gets `onDispose()` and the step listeners are dropped, so remount the provider with `key={manager.getBootstrapId()}` (see `examples/11-strategy-change.tsx`).
|
|
122
|
+
- Carry over what the user already typed by passing it in `defaultValues` (e.g. `manager.getFormValues()`); keys of steps that no longer exist stay in the form values only if you pass them.
|
|
123
|
+
- `resetFormManager()` calls `onReset()` on the same strategy; `bootstrap()` calls `onDispose()` on the old one.
|
|
124
|
+
|
|
125
|
+
## Step validation
|
|
126
|
+
|
|
127
|
+
Each step is validated against its own slice of the schema: `schema.shape[step.name]` parsed with the current value of that key.
|
|
128
|
+
|
|
129
|
+
- `manager.steps[i].error` / `useFormSteps().steps[i].error` is `true` when the step has issues; `currentStep.error` is the same for the current step. Use it for steppers and to disable "Next".
|
|
130
|
+
- `manager.validateStep(step)` returns a boolean; `manager.getStepIssues(step)` returns the Zod issues.
|
|
131
|
+
- The current step is re-evaluated on every form change and on navigation; listeners are notified only when its validity (or the current step) actually changes, so `useFormSteps` does not re-render on every keystroke.
|
|
132
|
+
- `goNext`/`goPrev`/`goToStep` do **not** block on invalid steps: gate them yourself with `currentStep.error`.
|
|
133
|
+
- `validationMode` (`"onChange"` default, or `"onSubmit"`) controls when RHF populates field errors (`fieldState.error`). The step `error` flag is always computed from the schema.
|
|
134
|
+
- `submit()` validates the **whole** form through the resolver (all steps) before calling `strategy.submit`; if invalid it does nothing and RHF fills the field errors.
|
|
135
|
+
- Steps denied by claims are not validated and are absent from `steps`; their values still reach `strategy.submit`.
|
|
136
|
+
- The schema must be a `ZodObject` whose top-level keys are the step names; cross-step rules (`superRefine` on the root) are enforced at submit, not in per-step `error`.
|
|
137
|
+
|
|
138
|
+
## Scenarios
|
|
139
|
+
|
|
140
|
+
Every scenario is a type-checked file in [`examples/`](examples) (`npm run typecheck`).
|
|
141
|
+
|
|
142
|
+
### 1. Basic 3-step wizard — `examples/01-basic-wizard.tsx`
|
|
143
|
+
Strategy with three steps, `useFormSteps` for the stepper, `isLastStep()` to switch Next/Submit.
|
|
144
|
+
|
|
145
|
+
### 2. Submit with multiple reports — `examples/02-submit-reports.ts`
|
|
146
|
+
```ts
|
|
147
|
+
await manager.submit((result) => statuses.push(result.status)); // pending, then success
|
|
148
|
+
```
|
|
149
|
+
|
|
150
|
+
### 3. Steps gated by claims — `examples/03-claims.ts`
|
|
151
|
+
```ts
|
|
152
|
+
const claims: ClaimsResolver<"orders.details", "view" | "update"> = { claim: () => ({ view: true }) };
|
|
153
|
+
manager.bootstrap({ strategy, defaultValues, claims });
|
|
154
|
+
```
|
|
155
|
+
|
|
156
|
+
### 4. Several forms on one page — `examples/04-multiple-forms.tsx`
|
|
157
|
+
One manager and one provider per form; state is isolated.
|
|
158
|
+
|
|
159
|
+
### 5. Single page form, no steps — `examples/05-single-page.tsx`
|
|
160
|
+
```tsx
|
|
161
|
+
<FormManagerProvider methods={useForm({ defaultValues })}>...</FormManagerProvider>
|
|
162
|
+
```
|
|
163
|
+
|
|
164
|
+
### 6. Strategy with static methods — `examples/06-strategy-statics.ts`
|
|
165
|
+
```ts
|
|
166
|
+
const strategyClass = manager.getStrategyClass<{ createPayload(values: Values): Payload }>();
|
|
167
|
+
```
|
|
168
|
+
|
|
169
|
+
### 7. Testing without React — `examples/07-testing.ts`
|
|
170
|
+
Bootstrap a manager and call `goNext`, `submit`, `steps` directly.
|
|
171
|
+
|
|
172
|
+
### 8. Scoping across routes — `examples/08-scopes.ts`
|
|
173
|
+
`ensureScope` in the loader, `clearScope` on leave.
|
|
174
|
+
|
|
175
|
+
### 9. `switch`/`case` rendering — `examples/09-switch-rendering.tsx`
|
|
176
|
+
```tsx
|
|
177
|
+
switch (currentStep.name) { case "customer": return <CustomerStep />; ... }
|
|
178
|
+
```
|
|
179
|
+
|
|
180
|
+
### 10. TanStack Router file-based routes — `examples/10-tanstack-router.tsx`
|
|
181
|
+
One route per step (`/form/$step`); URL → `goToStep`, manager → `navigate`.
|
|
182
|
+
|
|
183
|
+
### 11. Changing strategy from an input — `examples/11-strategy-change.tsx`
|
|
184
|
+
Metadata/values change vs. full re-bootstrap, remounting the provider with the bootstrap id.
|
|
185
|
+
|
|
186
|
+
## AI assistants
|
|
187
|
+
|
|
188
|
+
```bash
|
|
189
|
+
npx react-form-step-manager install-skill # ./.agents/skills
|
|
190
|
+
npx react-form-step-manager install-skill --target claude # ./.claude/skills
|
|
191
|
+
npx react-form-step-manager install-skill --target <path> --force
|
|
192
|
+
```
|
|
193
|
+
|
|
194
|
+
Also shipped: `ai/AGENTS.md` (snippet for your `AGENTS.md`/`CLAUDE.md`) and `llms.txt`.
|
|
195
|
+
|
|
196
|
+
## Development
|
|
197
|
+
|
|
198
|
+
```bash
|
|
199
|
+
npm run typecheck
|
|
200
|
+
npm test # vitest, in band
|
|
201
|
+
npm run build
|
|
202
|
+
```
|
|
203
|
+
|
|
204
|
+
## Attribution
|
|
205
|
+
|
|
206
|
+
Licensed under the Apache License 2.0 (see `LICENSE` and `NOTICE`). Copyright 2026 PieroProcessing. If you use this library in a product, a credit is appreciated, for example:
|
|
207
|
+
|
|
208
|
+
> Multi-step forms powered by react-form-step-manager by PieroProcessing.
|
package/ai/AGENTS.md
ADDED
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
# react-form-step-manager — agent instructions
|
|
2
|
+
|
|
3
|
+
Add this snippet to your `AGENTS.md` / `CLAUDE.md`:
|
|
4
|
+
|
|
5
|
+
```md
|
|
6
|
+
## Forms
|
|
7
|
+
|
|
8
|
+
Multi-step forms use `react-form-step-manager` (React Hook Form + Zod).
|
|
9
|
+
|
|
10
|
+
- One `FormManager` instance per form; no shared singleton. Bootstrap it before rendering `<FormManagerProvider manager={manager}>`.
|
|
11
|
+
- Steps, schema, claims and `submit` live in an `AbstractStrategy` subclass. The schema root is a `z.object`; each top-level key is a step.
|
|
12
|
+
- Gate steps with `claim`/`action` and inject decisions through `bootstrap({ claims })`.
|
|
13
|
+
- Use `useFormSteps`, `useFormClaims`, `useFormControl`, `useFormManager`; render steps with `<StepForm>`.
|
|
14
|
+
- Keep `TClaim`/`TAction` unions narrow on the strategy.
|
|
15
|
+
- Run tests in band: `npx vitest run --no-file-parallelism --maxWorkers=1`.
|
|
16
|
+
- Full skill: `npx react-form-step-manager install-skill`.
|
|
17
|
+
```
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
---
|
|
2
|
+
name: react-form-step-manager
|
|
3
|
+
description: Build multi-step React forms with react-form-step-manager (React Hook Form + Zod). Use when creating or changing a FormManager, AbstractStrategy, FormManagerProvider, useFormSteps/useFormClaims/useFormControl hooks, claim-gated steps, or tests of a form strategy.
|
|
4
|
+
---
|
|
5
|
+
|
|
6
|
+
# react-form-step-manager
|
|
7
|
+
|
|
8
|
+
Library for multi-step forms: one `FormManager` instance per form, a user `AbstractStrategy` subclass that declares steps, schema, claims and `submit`, and React hooks reading the instance from context.
|
|
9
|
+
|
|
10
|
+
## Workflow
|
|
11
|
+
|
|
12
|
+
1. Define a root `z.object` schema. Each top-level key is one step.
|
|
13
|
+
2. Subclass `AbstractStrategy` (see `references/strategy.md`): `steps`, `schema`, `metadata`, `submit`, optional `onReset`/`onDispose`.
|
|
14
|
+
3. Create `new FormManager<MyStrategy>()` (never a module singleton shared between forms) and call `bootstrap({ strategy, defaultValues, claims })` **before** rendering the provider. Use `ensureScope`/`clearScope` for route-driven lifecycles.
|
|
15
|
+
4. Wrap the UI in `<FormManagerProvider manager={manager}>`; read state with `useFormSteps`, `useFormClaims`, `useFormControl`, `useFormManager`.
|
|
16
|
+
5. Render each step with `<StepForm name id>`; navigate with `manager.goNext/goPrev/goToStep`; submit with `manager.submit(onResult)`.
|
|
17
|
+
|
|
18
|
+
## Rules
|
|
19
|
+
|
|
20
|
+
- Schema root must be a `ZodObject`; `Step.name` is one of its keys.
|
|
21
|
+
- A step with `claim` exists only if `claims.claim(step.claim)[step.action ?? "view"] === true`. Denied steps are absent from `steps`, but their values survive submit.
|
|
22
|
+
- `goNext`/`goPrev` return `null` at the edges; `goToStep` returns `false` (unknown), `null` (already there), `true` (moved).
|
|
23
|
+
- `submit` validates first; the strategy may call `report` many times (pending, then final).
|
|
24
|
+
- Single page forms: `useForm` + `<FormManagerProvider methods={methods}>`; `useFormManager` throws there.
|
|
25
|
+
- Keep types narrow: declare `TClaim`/`TAction` unions on the strategy instead of `string`.
|
|
26
|
+
- Test strategies without React (`references/testing.md`). Run tests in band.
|
|
27
|
+
|
|
28
|
+
## References
|
|
29
|
+
|
|
30
|
+
- `references/api.md` — full public API
|
|
31
|
+
- `references/strategy.md` — writing strategies, statics via `StrategyClass`
|
|
32
|
+
- `references/claims.md` — claims and gating
|
|
33
|
+
- `references/testing.md` — testing without React and with hooks
|
|
34
|
+
- `references/recipes.md` — wizard, multi-form page, switch/case rendering, TanStack Router
|
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
# API
|
|
2
|
+
|
|
3
|
+
```ts
|
|
4
|
+
import {
|
|
5
|
+
FormManager, AbstractStrategy, FormManagerProvider, StepForm,
|
|
6
|
+
useFormManager, useFormSteps, useFormClaims, useFormControl,
|
|
7
|
+
type Step, type StrategyClass, type BootstrapOptions, type ClaimsResolver,
|
|
8
|
+
} from "react-form-step-manager";
|
|
9
|
+
```
|
|
10
|
+
|
|
11
|
+
## FormManager<TStrategy>
|
|
12
|
+
|
|
13
|
+
`new FormManager<TStrategy>()` — one instance per form.
|
|
14
|
+
|
|
15
|
+
| Member | Notes |
|
|
16
|
+
|---|---|
|
|
17
|
+
| `bootstrap(options)` | `{ strategy, defaultValues, disabled?, validationMode?: "onChange" \| "onSubmit", claims? }`. Clears previous state, returns `this`. |
|
|
18
|
+
| `replaceStrategy(strategy, { claims?, defaultValues? })` | Swaps the strategy keeping RHF values, listeners, bootstrap id and current step (by name); revalidates. |
|
|
19
|
+
| `ensureScope(id, factory, revision?)` | Bootstraps unless `id` and `revision` are already active. |
|
|
20
|
+
| `clearScope(id)` | Clears only if `id` is the active scope. |
|
|
21
|
+
| `clearAll(removeListeners = true)` / `resetFormManager()` | Fire `onDispose` / `onReset` on the strategy. |
|
|
22
|
+
| `steps` | Granted steps, each with `error: boolean`. |
|
|
23
|
+
| `goNext()` / `goPrev()` | New step or `null` at the edges. |
|
|
24
|
+
| `goToStep(name)` | `true` moved, `null` same step, `false` unknown. |
|
|
25
|
+
| `isLastStep()`, `getNextStep()`, `getPrevStep()`, `getStepIndexByName(name)` | |
|
|
26
|
+
| `submit(onResult?)` | Validates, then `strategy.submit(data, report)`; `report` forwards to `onResult`. |
|
|
27
|
+
| `mergeFormValues(partial, shouldTrigger?)` | Shallow-merges per top-level key. |
|
|
28
|
+
| `setFieldError(name, error)`, `getFormValues()`, `getStepFormData(step)` | |
|
|
29
|
+
| `getStrategy()`, `getStrategyClass<TStatics>()`, `getStrategyMetadata()`, `patchMetadata()`, `updateMetadataAndResetFormFields()` | |
|
|
30
|
+
| `getClaim(id)`, `subscribeClaims(listener)` | Decision for a claim; `{}` when unknown. |
|
|
31
|
+
| `getCurrentStepInfo()`, `subscribeCurrentStepData(listener)`, `getFormStatus()`, `getBootstrapId()`, `hasCompletedBootstrap()` | |
|
|
32
|
+
| `form` | Namespace for everything delegated to react-hook-form: `setValue, getValues, resetField, trigger, unregister, reset, setError, clearErrors, handleSubmit, control, options`. Throws before `bootstrap`. |
|
|
33
|
+
|
|
34
|
+
## Provider and hooks
|
|
35
|
+
|
|
36
|
+
- `<FormManagerProvider manager={manager}>` (multi-step) or `<FormManagerProvider methods={useFormReturn}>` (single page).
|
|
37
|
+
- `useFormManager<TStrategy>()` — the manager. Throws outside a provider or in `methods` mode.
|
|
38
|
+
- `useFormSteps<TStep>()` — `{ steps, currentStep: { ...step, index, error }, formStatus }`, stable snapshot.
|
|
39
|
+
- `useFormClaims<TStrategy>(claimId)` — granted actions of the claim.
|
|
40
|
+
- `useFormControl<TValues>()` — `{ control, setValue, setError, trigger }` for `useController`/`useFormState`.
|
|
41
|
+
- `<StepForm name id? style? onSubmit?>` — `<form noValidate>` that prevents the default submit.
|
|
42
|
+
|
|
43
|
+
## Types
|
|
44
|
+
|
|
45
|
+
- `Step<TSchema, TClaim, TAction>` = `{ name, id, claim?, action? }`.
|
|
46
|
+
- `ClaimsResolver<TClaim, TAction>` = `{ claim(id: TClaim): Partial<Record<TAction, boolean>> }`.
|
|
47
|
+
- `AbstractStrategy<TSchema, TSubmitData, TMetadata, TSubmitResult, TClaim, TAction>`.
|
|
48
|
+
- `StrategyClass<TStrategy, TStatics>` = strategy constructor + statics.
|
|
49
|
+
- `SubmitResultOf<S>`, `ClaimOf<S>`, `ActionOf<S>` extract strategy generics.
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
# Claims
|
|
2
|
+
|
|
3
|
+
A claim is an opaque id (e.g. `"orders.details"`); an action is a verb (`"view"`, `"update"`, ...). The library has no auth dependency: you inject decisions.
|
|
4
|
+
|
|
5
|
+
```ts
|
|
6
|
+
const claims: ClaimsResolver<"orders.details", "view" | "update"> = {
|
|
7
|
+
claim: (id) => permissions.for(id), // Partial<Record<"view" | "update", boolean>>
|
|
8
|
+
};
|
|
9
|
+
manager.bootstrap({ strategy, defaultValues, claims });
|
|
10
|
+
```
|
|
11
|
+
|
|
12
|
+
- No `claims` option: no claim is granted, every step with a `claim` is hidden.
|
|
13
|
+
- `Step.action` defaults to `view`.
|
|
14
|
+
- Denied step: absent from `manager.steps`; its schema becomes `z.any()` in the resolver, so its default values are neither validated nor dropped at submit.
|
|
15
|
+
- Decisions are fixed at bootstrap. To change them, bootstrap again (`ensureScope(id, factory, revision)` with a new `revision`).
|
|
16
|
+
- In React: `const { update } = useFormClaims<MyStrategy>("orders.details")`. Unknown claim or no form: `{}`.
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
# Recipes
|
|
2
|
+
|
|
3
|
+
Runnable versions live in the repository `examples/` folder (type-checked in CI).
|
|
4
|
+
|
|
5
|
+
1. **Wizard**: `examples/01-basic-wizard.tsx`
|
|
6
|
+
2. **Multiple reports on submit**: `examples/02-submit-reports.ts`
|
|
7
|
+
3. **Claim-gated steps**: `examples/03-claims.ts`
|
|
8
|
+
4. **Several forms on one page**: one `FormManager` + one `FormManagerProvider` each: `examples/04-multiple-forms.tsx`
|
|
9
|
+
5. **Single page form**: `examples/05-single-page.tsx`
|
|
10
|
+
6. **Strategy statics**: `examples/06-strategy-statics.ts`
|
|
11
|
+
7. **Testing without React**: `examples/07-testing.ts`
|
|
12
|
+
8. **Scopes across routes**: `ensureScope` on enter, `clearScope` on leave: `examples/08-scopes.ts`
|
|
13
|
+
9. **switch/case rendering**: `examples/09-switch-rendering.tsx`
|
|
14
|
+
10. **TanStack Router, one route per step** (`/form/$step`), `goToStep` synced with `navigate`: `examples/10-tanstack-router.tsx`
|
|
15
|
+
|
|
16
|
+
Pattern for step components: read the current step with `useFormSteps`, render the matching component inside `<StepForm name={currentStep.name} id={currentStep.id}>`, and bind inputs with `useController({ control, name })` using `control` from `useFormControl`.
|
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
# Writing a strategy
|
|
2
|
+
|
|
3
|
+
```ts
|
|
4
|
+
import { z } from "zod";
|
|
5
|
+
import { AbstractStrategy, type Step } from "react-form-step-manager";
|
|
6
|
+
|
|
7
|
+
const schema = z.object({
|
|
8
|
+
info: z.object({ name: z.string().min(1) }),
|
|
9
|
+
review: z.object({ confirmed: z.boolean() }),
|
|
10
|
+
});
|
|
11
|
+
type Values = z.infer<typeof schema>;
|
|
12
|
+
type SubmitStatus = { status: "pending" | "success" | "error" };
|
|
13
|
+
|
|
14
|
+
class OnboardingStrategy extends AbstractStrategy<
|
|
15
|
+
typeof schema, Values, { identity: string }, SubmitStatus, "onboarding.review", "view" | "update"
|
|
16
|
+
> {
|
|
17
|
+
protected readonly steps: readonly Step<typeof schema, "onboarding.review", "view" | "update">[] = [
|
|
18
|
+
{ name: "info", id: "onboarding.info" },
|
|
19
|
+
{ name: "review", id: "onboarding.review", claim: "onboarding.review", action: "update" },
|
|
20
|
+
];
|
|
21
|
+
protected readonly schema = schema;
|
|
22
|
+
protected readonly metadata = { identity: "onboarding" };
|
|
23
|
+
|
|
24
|
+
async submit(data: Values, report: (result: SubmitStatus) => void) {
|
|
25
|
+
report({ status: "pending" });
|
|
26
|
+
await save(data);
|
|
27
|
+
report({ status: "success" });
|
|
28
|
+
}
|
|
29
|
+
override onReset() { /* release in-flight work */ }
|
|
30
|
+
override onDispose() { /* release subscriptions */ }
|
|
31
|
+
}
|
|
32
|
+
```
|
|
33
|
+
|
|
34
|
+
Generics: `TSchema` (root `ZodObject`), `TSubmitData` (validated data), `TMetadata`, `TSubmitResult` (what `report` receives), `TClaim`, `TAction`.
|
|
35
|
+
|
|
36
|
+
- `protected claims` lists claims used outside steps (e.g. sections inside a step); `getClaims()` merges them with the step claims.
|
|
37
|
+
- `getStepSchema(step)` returns `schema.shape[step.name]`.
|
|
38
|
+
|
|
39
|
+
## Statics with StrategyClass
|
|
40
|
+
|
|
41
|
+
```ts
|
|
42
|
+
type OnboardingStatics = { createPayload(values: Values): Payload };
|
|
43
|
+
const strategyClass = manager.getStrategyClass<OnboardingStatics>();
|
|
44
|
+
strategyClass.createPayload(manager.getFormValues());
|
|
45
|
+
```
|
|
46
|
+
|
|
47
|
+
Declare the statics on the class (`static createPayload(...)`); `StrategyClass` only types them. No throwing stubs.
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
# Testing
|
|
2
|
+
|
|
3
|
+
Run in band: `npx vitest run --no-file-parallelism --maxWorkers=1`.
|
|
4
|
+
|
|
5
|
+
## Without React
|
|
6
|
+
|
|
7
|
+
```ts
|
|
8
|
+
const manager = new FormManager<MyStrategy>().bootstrap({ strategy: new MyStrategy(), defaultValues, claims });
|
|
9
|
+
expect(manager.steps.map((step) => step.name)).toEqual(["info", "review"]);
|
|
10
|
+
const results: unknown[] = [];
|
|
11
|
+
await manager.submit((result) => results.push(result));
|
|
12
|
+
expect(manager.getStrategy().submitted).toEqual([defaultValues]);
|
|
13
|
+
```
|
|
14
|
+
|
|
15
|
+
- Each test creates its own manager: no shared state to reset.
|
|
16
|
+
- An invalid form never reaches `strategy.submit`.
|
|
17
|
+
- `goNext()` / `goPrev()` return `null` at the edges.
|
|
18
|
+
|
|
19
|
+
## With hooks
|
|
20
|
+
|
|
21
|
+
```tsx
|
|
22
|
+
const wrapper = ({ children }) => <FormManagerProvider manager={manager}>{children}</FormManagerProvider>;
|
|
23
|
+
const { result } = renderHook(() => useFormSteps(), { wrapper });
|
|
24
|
+
act(() => { manager.goNext(); });
|
|
25
|
+
```
|
|
26
|
+
|
|
27
|
+
Bootstrap before rendering the provider. Wrap manager mutations in `act`.
|
|
28
|
+
|
|
29
|
+
## Types
|
|
30
|
+
|
|
31
|
+
`expectTypeOf<NonNullable<BootstrapOptions<MyStrategy>["claims"]>>().toEqualTypeOf<ClaimsResolver<MyClaim, MyAction>>()`.
|