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
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import { cpSync, existsSync, mkdirSync } from "node:fs";
|
|
3
|
+
import { dirname, join, resolve } from "node:path";
|
|
4
|
+
import { fileURLToPath } from "node:url";
|
|
5
|
+
|
|
6
|
+
const SKILL_NAME = "react-form-step-manager";
|
|
7
|
+
const TARGET_PRESETS = { agents: ".agents/skills", claude: ".claude/skills" };
|
|
8
|
+
const USAGE = `Usage: react-form-step-manager install-skill [--target claude|agents|<path>] [--force]
|
|
9
|
+
|
|
10
|
+
Copies the ${SKILL_NAME} AI skill into <target>/${SKILL_NAME}.
|
|
11
|
+
--target "agents" (default, ./.agents/skills), "claude" (./.claude/skills) or a directory path
|
|
12
|
+
--force overwrite an existing installation`;
|
|
13
|
+
|
|
14
|
+
function parseArguments(argumentList) {
|
|
15
|
+
const options = { target: "agents", force: false, help: false };
|
|
16
|
+
for (let index = 0; index < argumentList.length; index += 1) {
|
|
17
|
+
const argument = argumentList[index];
|
|
18
|
+
if (argument === "--force") options.force = true;
|
|
19
|
+
else if (argument === "--help" || argument === "-h") options.help = true;
|
|
20
|
+
else if (argument === "--target") {
|
|
21
|
+
const value = argumentList[index + 1];
|
|
22
|
+
if (!value || value.startsWith("--")) throw new Error("--target requires a value");
|
|
23
|
+
options.target = value;
|
|
24
|
+
index += 1;
|
|
25
|
+
} else throw new Error(`Unknown argument: ${argument}`);
|
|
26
|
+
}
|
|
27
|
+
return options;
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
function main() {
|
|
31
|
+
const [command, ...rest] = process.argv.slice(2);
|
|
32
|
+
if (command === "--help" || command === "-h" || command === undefined) {
|
|
33
|
+
console.log(USAGE);
|
|
34
|
+
return command === undefined ? 1 : 0;
|
|
35
|
+
}
|
|
36
|
+
if (command !== "install-skill") throw new Error(`Unknown command: ${command}\n${USAGE}`);
|
|
37
|
+
|
|
38
|
+
const options = parseArguments(rest);
|
|
39
|
+
if (options.help) {
|
|
40
|
+
console.log(USAGE);
|
|
41
|
+
return 0;
|
|
42
|
+
}
|
|
43
|
+
const sourceDirectory = join(dirname(fileURLToPath(import.meta.url)), "..", "ai", "skills", SKILL_NAME);
|
|
44
|
+
const targetRoot = resolve(process.cwd(), TARGET_PRESETS[options.target] ?? options.target);
|
|
45
|
+
const destination = join(targetRoot, SKILL_NAME);
|
|
46
|
+
|
|
47
|
+
if (existsSync(destination) && !options.force) {
|
|
48
|
+
throw new Error(`${destination} already exists. Use --force to overwrite.`);
|
|
49
|
+
}
|
|
50
|
+
mkdirSync(targetRoot, { recursive: true });
|
|
51
|
+
cpSync(sourceDirectory, destination, { recursive: true, force: true });
|
|
52
|
+
console.log(`Installed ${SKILL_NAME} skill to ${destination}`);
|
|
53
|
+
return 0;
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
try {
|
|
57
|
+
process.exitCode = main();
|
|
58
|
+
} catch (error) {
|
|
59
|
+
console.error(error instanceof Error ? error.message : error);
|
|
60
|
+
process.exitCode = 1;
|
|
61
|
+
}
|
package/dist/index.cjs
ADDED
|
@@ -0,0 +1,547 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __defProp = Object.defineProperty;
|
|
3
|
+
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
4
|
+
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
5
|
+
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
6
|
+
var __export = (target, all) => {
|
|
7
|
+
for (var name in all)
|
|
8
|
+
__defProp(target, name, { get: all[name], enumerable: true });
|
|
9
|
+
};
|
|
10
|
+
var __copyProps = (to, from, except, desc) => {
|
|
11
|
+
if (from && typeof from === "object" || typeof from === "function") {
|
|
12
|
+
for (let key of __getOwnPropNames(from))
|
|
13
|
+
if (!__hasOwnProp.call(to, key) && key !== except)
|
|
14
|
+
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
|
15
|
+
}
|
|
16
|
+
return to;
|
|
17
|
+
};
|
|
18
|
+
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
|
19
|
+
|
|
20
|
+
// src/index.ts
|
|
21
|
+
var index_exports = {};
|
|
22
|
+
__export(index_exports, {
|
|
23
|
+
AbstractStrategy: () => AbstractStrategy,
|
|
24
|
+
FormManager: () => FormManager,
|
|
25
|
+
FormManagerProvider: () => FormManagerProvider,
|
|
26
|
+
StepForm: () => StepForm,
|
|
27
|
+
useFormClaims: () => useFormClaims,
|
|
28
|
+
useFormControl: () => useFormControl,
|
|
29
|
+
useFormManager: () => useFormManager,
|
|
30
|
+
useFormSteps: () => useFormSteps
|
|
31
|
+
});
|
|
32
|
+
module.exports = __toCommonJS(index_exports);
|
|
33
|
+
|
|
34
|
+
// src/form-manager.ts
|
|
35
|
+
var import_zod = require("@hookform/resolvers/zod");
|
|
36
|
+
var import_react_hook_form = require("react-hook-form");
|
|
37
|
+
var import_zod2 = require("zod");
|
|
38
|
+
|
|
39
|
+
// src/models.ts
|
|
40
|
+
var DEFAULT_ACTION = "view";
|
|
41
|
+
|
|
42
|
+
// src/utils.ts
|
|
43
|
+
function shallowMerge(current, incoming) {
|
|
44
|
+
const isPlainObject = (value) => value !== null && typeof value === "object" && !Array.isArray(value);
|
|
45
|
+
if (isPlainObject(incoming) && isPlainObject(current)) {
|
|
46
|
+
return { ...current, ...incoming };
|
|
47
|
+
}
|
|
48
|
+
return incoming;
|
|
49
|
+
}
|
|
50
|
+
function isSameCurrentStepData(currentState, nextState) {
|
|
51
|
+
const isCurrentSame = currentState.currentStep.index === nextState.currentStep.index && currentState.currentStep.name === nextState.currentStep.name && currentState.currentStep.error === nextState.currentStep.error;
|
|
52
|
+
if (!isCurrentSame) return false;
|
|
53
|
+
if (currentState.steps.length !== nextState.steps.length) return false;
|
|
54
|
+
return !currentState.steps.some(
|
|
55
|
+
(step) => step.error !== nextState.steps.find((next) => next.name === step.name)?.error
|
|
56
|
+
);
|
|
57
|
+
}
|
|
58
|
+
function createBootstrapId() {
|
|
59
|
+
if (typeof crypto !== "undefined" && typeof crypto.randomUUID === "function") {
|
|
60
|
+
return crypto.randomUUID();
|
|
61
|
+
}
|
|
62
|
+
return `bootstrap-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 10)}`;
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
// src/form-manager.ts
|
|
66
|
+
var NO_CLAIM = Object.freeze({});
|
|
67
|
+
var FormManager = class {
|
|
68
|
+
constructor() {
|
|
69
|
+
this.strategy = null;
|
|
70
|
+
this.bootstrapId = null;
|
|
71
|
+
this.scopeId = null;
|
|
72
|
+
this.revision = "";
|
|
73
|
+
this.grants = {};
|
|
74
|
+
this.claimsListeners = /* @__PURE__ */ new Set();
|
|
75
|
+
this.formStatus = null;
|
|
76
|
+
this.currentStepIndex = 0;
|
|
77
|
+
this.currentStepValid = false;
|
|
78
|
+
this.stepsListeners = /* @__PURE__ */ new Set();
|
|
79
|
+
this.unsubscribeForm = null;
|
|
80
|
+
this.headlessForm = null;
|
|
81
|
+
this.resolverOptions = null;
|
|
82
|
+
/** Decision taken at bootstrap, stable until the form is rebuilt. Unknown claim or no form = no action. */
|
|
83
|
+
this.getClaim = (id) => this.grants[id] ?? NO_CLAIM;
|
|
84
|
+
this.subscribeClaims = (listener) => {
|
|
85
|
+
this.claimsListeners.add(listener);
|
|
86
|
+
return () => {
|
|
87
|
+
this.claimsListeners.delete(listener);
|
|
88
|
+
};
|
|
89
|
+
};
|
|
90
|
+
this.getCurrentStepInfo = () => this.buildCurrentStepInfo();
|
|
91
|
+
this.subscribeCurrentStepData = (listener) => {
|
|
92
|
+
this.stepsListeners.add(listener);
|
|
93
|
+
return () => {
|
|
94
|
+
this.stepsListeners.delete(listener);
|
|
95
|
+
};
|
|
96
|
+
};
|
|
97
|
+
}
|
|
98
|
+
/** Neutralizes (`z.any()`) the schema of denied steps so their default values survive submit. */
|
|
99
|
+
getResolverSchema() {
|
|
100
|
+
const schema = this.getFormSchema();
|
|
101
|
+
const denied = this.requireStrategy().getDeclaredSteps().filter((step) => !this.isGranted(step));
|
|
102
|
+
if (denied.length === 0) return schema;
|
|
103
|
+
const neutralized = Object.fromEntries(denied.map((step) => [step.name, import_zod2.z.any()]));
|
|
104
|
+
return schema.extend(neutralized);
|
|
105
|
+
}
|
|
106
|
+
isGranted(step) {
|
|
107
|
+
if (!step.claim) return true;
|
|
108
|
+
const decision = this.grants[step.claim];
|
|
109
|
+
return decision?.[step.action ?? DEFAULT_ACTION] === true;
|
|
110
|
+
}
|
|
111
|
+
notifyClaims() {
|
|
112
|
+
this.claimsListeners.forEach((listener) => listener());
|
|
113
|
+
}
|
|
114
|
+
requireStrategy() {
|
|
115
|
+
if (!this.strategy) throw new Error("Strategy not set");
|
|
116
|
+
return this.strategy;
|
|
117
|
+
}
|
|
118
|
+
requireForm() {
|
|
119
|
+
if (!this.headlessForm) throw new Error("Form is not valid");
|
|
120
|
+
return this.headlessForm;
|
|
121
|
+
}
|
|
122
|
+
isCurrentStepValid() {
|
|
123
|
+
this.requireForm();
|
|
124
|
+
const currentStep = this.getVisibleSteps()[this.currentStepIndex];
|
|
125
|
+
if (!currentStep) return true;
|
|
126
|
+
return this.validateStep(currentStep);
|
|
127
|
+
}
|
|
128
|
+
getVisibleSteps() {
|
|
129
|
+
return this.requireStrategy().getSteps().filter(
|
|
130
|
+
(step) => this.isGranted(step)
|
|
131
|
+
);
|
|
132
|
+
}
|
|
133
|
+
buildCurrentStepInfo() {
|
|
134
|
+
if (!this.strategy) {
|
|
135
|
+
return {
|
|
136
|
+
steps: [],
|
|
137
|
+
currentStep: { name: "", id: "", index: 0, error: true },
|
|
138
|
+
formStatus: null
|
|
139
|
+
};
|
|
140
|
+
}
|
|
141
|
+
const steps = this.steps;
|
|
142
|
+
const currentStep = steps[this.currentStepIndex];
|
|
143
|
+
return {
|
|
144
|
+
steps,
|
|
145
|
+
currentStep: { ...currentStep, index: this.currentStepIndex },
|
|
146
|
+
formStatus: this.formStatus
|
|
147
|
+
};
|
|
148
|
+
}
|
|
149
|
+
get steps() {
|
|
150
|
+
return this.getVisibleSteps().map((step) => ({
|
|
151
|
+
...step,
|
|
152
|
+
error: !this.validateStep(step)
|
|
153
|
+
}));
|
|
154
|
+
}
|
|
155
|
+
/**
|
|
156
|
+
* Thin access to the react-hook-form control. Everything here delegates to RHF;
|
|
157
|
+
* the rest of the class is the step logic. Throws before `bootstrap`.
|
|
158
|
+
*/
|
|
159
|
+
get form() {
|
|
160
|
+
const { setValue, getValues, resetField, trigger, unregister, reset, setError, clearErrors, handleSubmit, formControl } = this.requireForm();
|
|
161
|
+
return {
|
|
162
|
+
setValue,
|
|
163
|
+
getValues,
|
|
164
|
+
resetField,
|
|
165
|
+
trigger,
|
|
166
|
+
unregister,
|
|
167
|
+
reset,
|
|
168
|
+
setError,
|
|
169
|
+
clearErrors,
|
|
170
|
+
handleSubmit,
|
|
171
|
+
control: formControl,
|
|
172
|
+
// `useForm({ formControl })` overrides the control options with its own props: pass these again.
|
|
173
|
+
options: this.resolverOptions
|
|
174
|
+
};
|
|
175
|
+
}
|
|
176
|
+
getBootstrapId() {
|
|
177
|
+
return this.bootstrapId;
|
|
178
|
+
}
|
|
179
|
+
/** The constructor of the strategy in use, typed with the statics declared via `StrategyClass`. */
|
|
180
|
+
getStrategyClass() {
|
|
181
|
+
return this.requireStrategy().constructor;
|
|
182
|
+
}
|
|
183
|
+
validateStep(step) {
|
|
184
|
+
return this.getStepIssues(step).length === 0;
|
|
185
|
+
}
|
|
186
|
+
getStepIssues(step) {
|
|
187
|
+
const values = this.requireForm().getValues(step.name);
|
|
188
|
+
const stepSchema = this.requireStrategy().getStepSchema(step);
|
|
189
|
+
const validationResult = stepSchema.safeParse(values);
|
|
190
|
+
return validationResult.success ? [] : validationResult.error.issues;
|
|
191
|
+
}
|
|
192
|
+
clearAll(removeListeners = true) {
|
|
193
|
+
this.strategy?.onDispose();
|
|
194
|
+
this.headlessForm = null;
|
|
195
|
+
this.strategy = null;
|
|
196
|
+
this.bootstrapId = null;
|
|
197
|
+
this.scopeId = null;
|
|
198
|
+
this.revision = "";
|
|
199
|
+
this.grants = {};
|
|
200
|
+
this.claimsResolver = void 0;
|
|
201
|
+
this.currentStepIndex = 0;
|
|
202
|
+
this.currentStepValid = false;
|
|
203
|
+
this.formStatus = null;
|
|
204
|
+
this.notifyClaims();
|
|
205
|
+
if (removeListeners) {
|
|
206
|
+
this.unsubscribeForm?.();
|
|
207
|
+
this.unsubscribeForm = null;
|
|
208
|
+
this.stepsListeners.clear();
|
|
209
|
+
}
|
|
210
|
+
}
|
|
211
|
+
/** Bootstraps the scope unless it is already the active one with the same `revision`: safe to call repeatedly. */
|
|
212
|
+
ensureScope(id, factory, revision = "") {
|
|
213
|
+
if (this.scopeId === id && this.revision === revision && this.hasCompletedBootstrap()) return;
|
|
214
|
+
this.bootstrap(factory());
|
|
215
|
+
this.scopeId = id;
|
|
216
|
+
this.revision = revision;
|
|
217
|
+
}
|
|
218
|
+
/** Clears only if the active scope is `id`: leaving a page must not wipe the form of the one just opened. */
|
|
219
|
+
clearScope(id) {
|
|
220
|
+
if (this.scopeId === id) this.clearAll();
|
|
221
|
+
}
|
|
222
|
+
resetFormManager() {
|
|
223
|
+
this.strategy?.onReset();
|
|
224
|
+
this.bootstrapId = createBootstrapId();
|
|
225
|
+
this.currentStepIndex = 0;
|
|
226
|
+
this.currentStepValid = false;
|
|
227
|
+
this.requireForm().reset();
|
|
228
|
+
this.recomputeCurrentStepValid();
|
|
229
|
+
}
|
|
230
|
+
bootstrap({ strategy, ...options }) {
|
|
231
|
+
this.clearAll();
|
|
232
|
+
this.strategy = strategy;
|
|
233
|
+
this.claimsResolver = options.claims;
|
|
234
|
+
this.grants = this.resolveGrants(strategy);
|
|
235
|
+
this.bootstrapId = createBootstrapId();
|
|
236
|
+
const resolver = (...resolverArguments) => {
|
|
237
|
+
const resolve = (0, import_zod.zodResolver)(this.getResolverSchema());
|
|
238
|
+
return resolve(...resolverArguments);
|
|
239
|
+
};
|
|
240
|
+
this.resolverOptions = { mode: options.validationMode ?? "onChange", resolver };
|
|
241
|
+
this.headlessForm = (0, import_react_hook_form.createFormControl)({
|
|
242
|
+
...this.resolverOptions,
|
|
243
|
+
defaultValues: options.defaultValues,
|
|
244
|
+
disabled: options.disabled
|
|
245
|
+
});
|
|
246
|
+
this.currentStepIndex = 0;
|
|
247
|
+
this.currentStepValid = this.isCurrentStepValid();
|
|
248
|
+
this.unsubscribeForm = this.headlessForm.subscribe({
|
|
249
|
+
formState: { dirtyFields: true, touchedFields: true, values: true },
|
|
250
|
+
callback: (data) => {
|
|
251
|
+
this.formStatus = data;
|
|
252
|
+
this.recomputeCurrentStepValid();
|
|
253
|
+
}
|
|
254
|
+
});
|
|
255
|
+
this.notifyClaims();
|
|
256
|
+
return this;
|
|
257
|
+
}
|
|
258
|
+
resolveGrants(strategy) {
|
|
259
|
+
return Object.fromEntries(
|
|
260
|
+
strategy.getClaims().map((id) => [id, this.claimsResolver?.claim(id) ?? NO_CLAIM])
|
|
261
|
+
);
|
|
262
|
+
}
|
|
263
|
+
/**
|
|
264
|
+
* Swaps the strategy keeping the RHF control (values, dirty, touched), the listeners, the bootstrap id
|
|
265
|
+
* and the current step (matched by name). If that step no longer exists, falls back to the closest
|
|
266
|
+
* previous step that still exists, otherwise to the first one. Then revalidates the whole form.
|
|
267
|
+
* Claims: `options.claims` replaces the resolver; without it the current one is reused.
|
|
268
|
+
* `options.defaultValues` only fills top-level keys that are still `undefined` (e.g. steps new to the schema).
|
|
269
|
+
*/
|
|
270
|
+
replaceStrategy(strategy, options = {}) {
|
|
271
|
+
const form = this.requireForm();
|
|
272
|
+
const previousVisibleNames = this.getVisibleSteps().map((step) => step.name);
|
|
273
|
+
const previousIndex = this.currentStepIndex;
|
|
274
|
+
for (const [key, value] of Object.entries(options.defaultValues ?? {})) {
|
|
275
|
+
if (form.getValues(key) === void 0) {
|
|
276
|
+
form.setValue(key, value);
|
|
277
|
+
}
|
|
278
|
+
}
|
|
279
|
+
this.strategy?.onDispose();
|
|
280
|
+
this.strategy = strategy;
|
|
281
|
+
if (options.claims) this.claimsResolver = options.claims;
|
|
282
|
+
this.grants = this.resolveGrants(strategy);
|
|
283
|
+
const visibleNames = this.getVisibleSteps().map((step) => step.name);
|
|
284
|
+
const candidates = previousVisibleNames.slice(0, previousIndex + 1).reverse();
|
|
285
|
+
const keptName = candidates.find((name) => visibleNames.includes(name));
|
|
286
|
+
this.currentStepIndex = keptName === void 0 ? 0 : visibleNames.indexOf(keptName);
|
|
287
|
+
this.currentStepValid = this.isCurrentStepValid();
|
|
288
|
+
void form.trigger();
|
|
289
|
+
this.notifyClaims();
|
|
290
|
+
this.callStepListeners();
|
|
291
|
+
return this;
|
|
292
|
+
}
|
|
293
|
+
getFormSchema() {
|
|
294
|
+
return this.requireStrategy().getFormSchema();
|
|
295
|
+
}
|
|
296
|
+
getFormStatus() {
|
|
297
|
+
return this.formStatus;
|
|
298
|
+
}
|
|
299
|
+
recomputeCurrentStepValid() {
|
|
300
|
+
const nextValid = this.isCurrentStepValid();
|
|
301
|
+
if (nextValid !== this.currentStepValid) {
|
|
302
|
+
this.currentStepValid = nextValid;
|
|
303
|
+
this.callStepListeners();
|
|
304
|
+
}
|
|
305
|
+
return nextValid;
|
|
306
|
+
}
|
|
307
|
+
callStepListeners() {
|
|
308
|
+
const currentStepData = this.buildCurrentStepInfo();
|
|
309
|
+
this.stepsListeners.forEach((listener) => listener(currentStepData));
|
|
310
|
+
}
|
|
311
|
+
isLastStep() {
|
|
312
|
+
return this.currentStepIndex >= this.steps.length - 1;
|
|
313
|
+
}
|
|
314
|
+
getNextStep() {
|
|
315
|
+
this.requireForm();
|
|
316
|
+
if (this.isLastStep()) return null;
|
|
317
|
+
return this.steps[this.currentStepIndex + 1] ?? null;
|
|
318
|
+
}
|
|
319
|
+
getPrevStep() {
|
|
320
|
+
if (this.currentStepIndex <= 0) return null;
|
|
321
|
+
return this.steps[this.currentStepIndex - 1] ?? null;
|
|
322
|
+
}
|
|
323
|
+
/** `false`: unknown step. `null`: already on that step. `true`: moved. */
|
|
324
|
+
goToStep(stepName) {
|
|
325
|
+
this.requireForm();
|
|
326
|
+
const steps = this.getVisibleSteps();
|
|
327
|
+
const index = steps.findIndex((step) => step.name === stepName);
|
|
328
|
+
if (index < 0) return false;
|
|
329
|
+
if (index === this.currentStepIndex) return null;
|
|
330
|
+
this.moveToStep(index);
|
|
331
|
+
return true;
|
|
332
|
+
}
|
|
333
|
+
/** Returns the new current step, or `null` when already on the last one. */
|
|
334
|
+
goNext() {
|
|
335
|
+
this.requireForm();
|
|
336
|
+
if (this.isLastStep()) return null;
|
|
337
|
+
this.moveToStep(this.currentStepIndex + 1);
|
|
338
|
+
return this.steps[this.currentStepIndex] ?? null;
|
|
339
|
+
}
|
|
340
|
+
/** Returns the new current step, or `null` when already on the first one. */
|
|
341
|
+
goPrev() {
|
|
342
|
+
this.requireForm();
|
|
343
|
+
if (this.currentStepIndex <= 0) return null;
|
|
344
|
+
this.moveToStep(this.currentStepIndex - 1);
|
|
345
|
+
return this.steps[this.currentStepIndex] ?? null;
|
|
346
|
+
}
|
|
347
|
+
moveToStep(index) {
|
|
348
|
+
this.currentStepIndex = index;
|
|
349
|
+
this.currentStepValid = this.isCurrentStepValid();
|
|
350
|
+
this.callStepListeners();
|
|
351
|
+
}
|
|
352
|
+
getStepIndexByName(stepName) {
|
|
353
|
+
return this.getVisibleSteps().findIndex((step) => step.name === stepName);
|
|
354
|
+
}
|
|
355
|
+
/** The manager does not interpret results: it forwards them to `onResult` each time the strategy reports. */
|
|
356
|
+
async submit(onResult) {
|
|
357
|
+
const form = this.requireForm();
|
|
358
|
+
const strategy = this.requireStrategy();
|
|
359
|
+
await form.handleSubmit(async (data) => {
|
|
360
|
+
await strategy.submit(data, (result) => onResult?.(result));
|
|
361
|
+
})();
|
|
362
|
+
}
|
|
363
|
+
mergeFormValues(data, shouldTrigger = false) {
|
|
364
|
+
const form = this.requireForm();
|
|
365
|
+
for (const key of Object.keys(data)) {
|
|
366
|
+
const incoming = data[key];
|
|
367
|
+
if (incoming === void 0 || incoming === null) continue;
|
|
368
|
+
const fieldKey = key;
|
|
369
|
+
form.setValue(fieldKey, shallowMerge(form.getValues(fieldKey), incoming), {
|
|
370
|
+
shouldDirty: shouldTrigger,
|
|
371
|
+
shouldValidate: shouldTrigger
|
|
372
|
+
});
|
|
373
|
+
}
|
|
374
|
+
}
|
|
375
|
+
setFieldError(fieldName, error) {
|
|
376
|
+
this.requireForm().setError(fieldName, error);
|
|
377
|
+
}
|
|
378
|
+
getFormValues() {
|
|
379
|
+
return this.requireForm().getValues();
|
|
380
|
+
}
|
|
381
|
+
getStepFormData(stepName) {
|
|
382
|
+
return this.requireForm().getValues(stepName);
|
|
383
|
+
}
|
|
384
|
+
getStrategyMetadata() {
|
|
385
|
+
return { ...this.requireStrategy().getMetadata() };
|
|
386
|
+
}
|
|
387
|
+
getStrategy() {
|
|
388
|
+
return this.requireStrategy();
|
|
389
|
+
}
|
|
390
|
+
patchMetadata(metadata) {
|
|
391
|
+
const strategy = this.requireStrategy();
|
|
392
|
+
strategy.updateMetadata({ ...strategy.getMetadata(), ...metadata });
|
|
393
|
+
}
|
|
394
|
+
updateMetadataAndResetFormFields(metadata, data) {
|
|
395
|
+
const form = this.requireForm();
|
|
396
|
+
this.patchMetadata(metadata);
|
|
397
|
+
const mergedValues = { ...form.getValues(), ...data?.values };
|
|
398
|
+
const { keepValues: _keepValues, ...resetOptions } = data?.options ?? {};
|
|
399
|
+
form.reset(mergedValues, resetOptions);
|
|
400
|
+
}
|
|
401
|
+
hasCompletedBootstrap() {
|
|
402
|
+
return this.strategy !== null;
|
|
403
|
+
}
|
|
404
|
+
};
|
|
405
|
+
|
|
406
|
+
// src/strategy.ts
|
|
407
|
+
var AbstractStrategy = class {
|
|
408
|
+
constructor() {
|
|
409
|
+
/** Claims used by the form besides the ones of its steps (e.g. sections inside a step). */
|
|
410
|
+
this.claims = [];
|
|
411
|
+
}
|
|
412
|
+
/** Hook: the form is reset (`resetFormManager`). Release in-flight work here. */
|
|
413
|
+
onReset() {
|
|
414
|
+
}
|
|
415
|
+
/** Hook: the strategy is retired (`clearAll`, `clearScope`, a new `bootstrap`). */
|
|
416
|
+
onDispose() {
|
|
417
|
+
}
|
|
418
|
+
getSteps() {
|
|
419
|
+
return this.steps;
|
|
420
|
+
}
|
|
421
|
+
/** All declared steps, before claims: needed to know which schemas to neutralize. */
|
|
422
|
+
getDeclaredSteps() {
|
|
423
|
+
return this.steps;
|
|
424
|
+
}
|
|
425
|
+
/** Form claims: the declared ones plus the ones of the steps. */
|
|
426
|
+
getClaims() {
|
|
427
|
+
const ids = new Set(this.claims);
|
|
428
|
+
for (const step of this.steps) if (step.claim) ids.add(step.claim);
|
|
429
|
+
return [...ids];
|
|
430
|
+
}
|
|
431
|
+
getFormSchema() {
|
|
432
|
+
return this.schema;
|
|
433
|
+
}
|
|
434
|
+
/** The schema root must be a `ZodObject`: each step maps to one of its keys. */
|
|
435
|
+
getStepSchema(step) {
|
|
436
|
+
return this.schema.shape[step.name];
|
|
437
|
+
}
|
|
438
|
+
getMetadata() {
|
|
439
|
+
return this.metadata;
|
|
440
|
+
}
|
|
441
|
+
updateMetadata(metadata) {
|
|
442
|
+
this.metadata = { ...this.metadata, ...metadata };
|
|
443
|
+
}
|
|
444
|
+
};
|
|
445
|
+
|
|
446
|
+
// src/context.tsx
|
|
447
|
+
var import_react = require("react");
|
|
448
|
+
var import_react_hook_form2 = require("react-hook-form");
|
|
449
|
+
var import_jsx_runtime = require("react/jsx-runtime");
|
|
450
|
+
var FormManagerContext = (0, import_react.createContext)(null);
|
|
451
|
+
function ContextBridge({
|
|
452
|
+
manager,
|
|
453
|
+
source,
|
|
454
|
+
children
|
|
455
|
+
}) {
|
|
456
|
+
const { control, setValue, setError, trigger } = source;
|
|
457
|
+
const value = (0, import_react.useMemo)(
|
|
458
|
+
() => ({ manager, controls: { control, setValue, setError, trigger } }),
|
|
459
|
+
[manager, control, setValue, setError, trigger]
|
|
460
|
+
);
|
|
461
|
+
return /* @__PURE__ */ (0, import_jsx_runtime.jsx)(FormManagerContext.Provider, { value, children });
|
|
462
|
+
}
|
|
463
|
+
function ManagerProvider({
|
|
464
|
+
manager,
|
|
465
|
+
children
|
|
466
|
+
}) {
|
|
467
|
+
const methods = (0, import_react_hook_form2.useForm)({ formControl: manager.form.control, ...manager.form.options });
|
|
468
|
+
return /* @__PURE__ */ (0, import_jsx_runtime.jsx)(ContextBridge, { manager, source: methods, children });
|
|
469
|
+
}
|
|
470
|
+
function FormManagerProvider(props) {
|
|
471
|
+
if (props.manager) {
|
|
472
|
+
return /* @__PURE__ */ (0, import_jsx_runtime.jsx)(ManagerProvider, { manager: props.manager, children: props.children });
|
|
473
|
+
}
|
|
474
|
+
return /* @__PURE__ */ (0, import_jsx_runtime.jsx)(ContextBridge, { manager: null, source: props.methods, children: props.children });
|
|
475
|
+
}
|
|
476
|
+
function useFormManagerContext(hookName) {
|
|
477
|
+
const context = (0, import_react.useContext)(FormManagerContext);
|
|
478
|
+
if (!context) throw new Error(`${hookName} must be used within a FormManagerProvider`);
|
|
479
|
+
return context;
|
|
480
|
+
}
|
|
481
|
+
function useRequiredManager(hookName) {
|
|
482
|
+
const { manager } = useFormManagerContext(hookName);
|
|
483
|
+
if (!manager) {
|
|
484
|
+
throw new Error(`${hookName} needs a FormManagerProvider created with \`manager\`, not \`methods\``);
|
|
485
|
+
}
|
|
486
|
+
return manager;
|
|
487
|
+
}
|
|
488
|
+
function useFormManager() {
|
|
489
|
+
return useRequiredManager("useFormManager");
|
|
490
|
+
}
|
|
491
|
+
function useFormControl() {
|
|
492
|
+
return useFormManagerContext("useFormControl").controls;
|
|
493
|
+
}
|
|
494
|
+
function useFormSteps() {
|
|
495
|
+
const manager = useRequiredManager("useFormSteps");
|
|
496
|
+
const snapshotRef = (0, import_react.useRef)(null);
|
|
497
|
+
const getSnapshot = () => {
|
|
498
|
+
const nextSnapshot = manager.getCurrentStepInfo();
|
|
499
|
+
const currentSnapshot = snapshotRef.current;
|
|
500
|
+
if (currentSnapshot && isSameCurrentStepData(currentSnapshot, nextSnapshot)) {
|
|
501
|
+
return currentSnapshot;
|
|
502
|
+
}
|
|
503
|
+
snapshotRef.current = nextSnapshot;
|
|
504
|
+
return nextSnapshot;
|
|
505
|
+
};
|
|
506
|
+
return (0, import_react.useSyncExternalStore)(manager.subscribeCurrentStepData, getSnapshot, getSnapshot);
|
|
507
|
+
}
|
|
508
|
+
function useFormClaims(id) {
|
|
509
|
+
const manager = useRequiredManager("useFormClaims");
|
|
510
|
+
return (0, import_react.useSyncExternalStore)(
|
|
511
|
+
manager.subscribeClaims,
|
|
512
|
+
() => manager.getClaim(id),
|
|
513
|
+
() => manager.getClaim(id)
|
|
514
|
+
);
|
|
515
|
+
}
|
|
516
|
+
|
|
517
|
+
// src/StepForm.tsx
|
|
518
|
+
var import_jsx_runtime2 = require("react/jsx-runtime");
|
|
519
|
+
function StepForm({ name, id, children, style, onSubmit }) {
|
|
520
|
+
return /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(
|
|
521
|
+
"form",
|
|
522
|
+
{
|
|
523
|
+
id,
|
|
524
|
+
name,
|
|
525
|
+
"data-testid": `${name}-form`,
|
|
526
|
+
style,
|
|
527
|
+
noValidate: true,
|
|
528
|
+
onSubmit: (event) => {
|
|
529
|
+
event.preventDefault();
|
|
530
|
+
onSubmit?.();
|
|
531
|
+
},
|
|
532
|
+
children
|
|
533
|
+
}
|
|
534
|
+
);
|
|
535
|
+
}
|
|
536
|
+
// Annotate the CommonJS export names for ESM import in node:
|
|
537
|
+
0 && (module.exports = {
|
|
538
|
+
AbstractStrategy,
|
|
539
|
+
FormManager,
|
|
540
|
+
FormManagerProvider,
|
|
541
|
+
StepForm,
|
|
542
|
+
useFormClaims,
|
|
543
|
+
useFormControl,
|
|
544
|
+
useFormManager,
|
|
545
|
+
useFormSteps
|
|
546
|
+
});
|
|
547
|
+
//# sourceMappingURL=index.cjs.map
|