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 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/index.ts","../src/form-manager.ts","../src/models.ts","../src/utils.ts","../src/strategy.ts","../src/context.tsx","../src/StepForm.tsx"],"sourcesContent":["export { FormManager, type FormControlFacade, type ReplaceStrategyOptions } from \"./form-manager\";\r\nexport { AbstractStrategy } from \"./strategy\";\r\nexport {\r\n FormManagerProvider,\r\n useFormManager,\r\n useFormSteps,\r\n useFormClaims,\r\n useFormControl,\r\n} from \"./context\";\r\nexport { StepForm } from \"./StepForm\";\r\nexport type {\r\n Step,\r\n StrategyClass,\r\n BootstrapOptions,\r\n ClaimsResolver,\r\n FormManagerMetadata,\r\n FormManagerSteps,\r\n FormStatus,\r\n SubmitResultOf,\r\n ClaimOf,\r\n ActionOf,\r\n} from \"./models\";\r\nexport type { FormControlContext, FormManagerProviderProps } from \"./context\";\r\nexport type { StepFormProps } from \"./StepForm\";\r\n","import { zodResolver } from \"@hookform/resolvers/zod\";\r\nimport {\r\n createFormControl,\r\n type DeepPartial,\r\n type DefaultValues,\r\n type ErrorOption,\r\n type FieldPath,\r\n type FieldValues,\r\n type KeepStateOptions,\r\n type Resolver,\r\n} from \"react-hook-form\";\r\nimport { z, type ZodObject, type ZodType } from \"zod\";\r\nimport {\r\n DEFAULT_ACTION,\r\n type ActionOf,\r\n type BootstrapOptions,\r\n type ClaimOf,\r\n type FormManagerMetadata,\r\n type FormManagerStepListener,\r\n type FormManagerSteps,\r\n type FormStatus,\r\n type HeadlessFormControl,\r\n type Step,\r\n type StepState,\r\n type StrategyClass,\r\n type SubmitResultOf,\r\n} from \"./models\";\r\nimport type { AnyStrategy } from \"./strategy\";\r\nimport { createBootstrapId, shallowMerge } from \"./utils\";\r\n\r\ntype SchemaOf<TStrategy extends AnyStrategy> = ReturnType<TStrategy[\"getFormSchema\"]>;\r\ntype ValuesOf<TStrategy extends AnyStrategy> = z.infer<SchemaOf<TStrategy>>;\r\ntype StepOf<TStrategy extends AnyStrategy> = ReturnType<TStrategy[\"getSteps\"]>[number];\r\ntype ClaimDecision<TStrategy extends AnyStrategy> = Partial<Record<ActionOf<TStrategy>, boolean>>;\r\n\r\n/** Frozen so that `getClaim` returns the same reference for every unknown claim. */\r\nconst NO_CLAIM: Readonly<Record<string, boolean>> = Object.freeze({});\r\n\r\ntype RhfMember = \"setValue\" | \"getValues\" | \"resetField\" | \"trigger\" | \"unregister\" | \"reset\" | \"setError\" | \"clearErrors\" | \"handleSubmit\";\r\n\r\nexport type FormControlFacade = Pick<HeadlessFormControl<FieldValues>, RhfMember> & {\r\n control: HeadlessFormControl<FieldValues>[\"formControl\"];\r\n options: { mode: \"onChange\" | \"onSubmit\"; resolver: Resolver<FieldValues> };\r\n};\r\n\r\nexport type ReplaceStrategyOptions<TStrategy extends AnyStrategy> = {\r\n claims?: BootstrapOptions<TStrategy>[\"claims\"];\r\n defaultValues?: DeepPartial<z.infer<ReturnType<TStrategy[\"getFormSchema\"]>>>;\r\n};\r\n\r\n/** Owns one form: its react-hook-form control, current step, claims and listeners. One instance per form. */\r\nexport class FormManager<TStrategy extends AnyStrategy = AnyStrategy> {\r\n private strategy: TStrategy | null = null;\r\n private bootstrapId: string | null = null;\r\n private scopeId: string | null = null;\r\n private revision = \"\";\r\n private grants: Record<string, ClaimDecision<TStrategy>> = {};\r\n private claimsResolver: BootstrapOptions<TStrategy>[\"claims\"];\r\n private readonly claimsListeners = new Set<() => void>();\r\n private formStatus: FormStatus | null = null;\r\n private currentStepIndex = 0;\r\n private currentStepValid = false;\r\n private readonly stepsListeners = new Set<FormManagerStepListener<any>>();\r\n private unsubscribeForm: (() => void) | null = null;\r\n private headlessForm: HeadlessFormControl<FieldValues> | null = null;\r\n private resolverOptions: { mode: \"onChange\" | \"onSubmit\"; resolver: Resolver<FieldValues> } | null =\r\n null;\r\n\r\n /** Neutralizes (`z.any()`) the schema of denied steps so their default values survive submit. */\r\n protected getResolverSchema(): ZodObject {\r\n const schema = this.getFormSchema() as ZodObject;\r\n const denied = this.requireStrategy()\r\n .getDeclaredSteps()\r\n .filter((step) => !this.isGranted(step));\r\n if (denied.length === 0) return schema;\r\n const neutralized = Object.fromEntries(denied.map((step) => [step.name, z.any()]));\r\n return schema.extend(neutralized);\r\n }\r\n\r\n private isGranted(step: Step<any, any, any>): boolean {\r\n if (!step.claim) return true;\r\n const decision = this.grants[step.claim] as Record<string, boolean> | undefined;\r\n return decision?.[step.action ?? DEFAULT_ACTION] === true;\r\n }\r\n\r\n /** Decision taken at bootstrap, stable until the form is rebuilt. Unknown claim or no form = no action. */\r\n getClaim = (id: ClaimOf<TStrategy>): ClaimDecision<TStrategy> =>\r\n this.grants[id] ?? (NO_CLAIM as ClaimDecision<TStrategy>);\r\n\r\n subscribeClaims = (listener: () => void): (() => void) => {\r\n this.claimsListeners.add(listener);\r\n return () => {\r\n this.claimsListeners.delete(listener);\r\n };\r\n };\r\n\r\n private notifyClaims(): void {\r\n this.claimsListeners.forEach((listener) => listener());\r\n }\r\n\r\n private requireStrategy(): TStrategy {\r\n if (!this.strategy) throw new Error(\"Strategy not set\");\r\n return this.strategy;\r\n }\r\n\r\n private requireForm(): HeadlessFormControl<FieldValues> {\r\n if (!this.headlessForm) throw new Error(\"Form is not valid\");\r\n return this.headlessForm;\r\n }\r\n\r\n private isCurrentStepValid(): boolean {\r\n this.requireForm();\r\n const currentStep = this.getVisibleSteps()[this.currentStepIndex];\r\n if (!currentStep) return true;\r\n return this.validateStep(currentStep);\r\n }\r\n\r\n private getVisibleSteps(): StepOf<TStrategy>[] {\r\n return (this.requireStrategy().getSteps() as StepOf<TStrategy>[]).filter((step) =>\r\n this.isGranted(step),\r\n );\r\n }\r\n\r\n private buildCurrentStepInfo<TStep extends Step<any, any, any> = StepOf<TStrategy>>(): FormManagerSteps<TStep> {\r\n if (!this.strategy) {\r\n return {\r\n steps: [],\r\n currentStep: { name: \"\", id: \"\", index: 0, error: true } as FormManagerSteps<TStep>[\"currentStep\"],\r\n formStatus: null,\r\n };\r\n }\r\n const steps = this.steps as StepState<TStep>[];\r\n const currentStep = steps[this.currentStepIndex];\r\n return {\r\n steps,\r\n currentStep: { ...currentStep, index: this.currentStepIndex } as FormManagerSteps<TStep>[\"currentStep\"],\r\n formStatus: this.formStatus,\r\n };\r\n }\r\n\r\n get steps(): StepState<StepOf<TStrategy>>[] {\r\n return this.getVisibleSteps().map((step) => ({\r\n ...step,\r\n error: !this.validateStep(step),\r\n }));\r\n }\r\n\r\n /**\r\n * Thin access to the react-hook-form control. Everything here delegates to RHF;\r\n * the rest of the class is the step logic. Throws before `bootstrap`.\r\n */\r\n get form(): FormControlFacade {\r\n const { setValue, getValues, resetField, trigger, unregister, reset, setError, clearErrors, handleSubmit, formControl } =\r\n this.requireForm();\r\n return {\r\n setValue,\r\n getValues,\r\n resetField,\r\n trigger,\r\n unregister,\r\n reset,\r\n setError,\r\n clearErrors,\r\n handleSubmit,\r\n control: formControl,\r\n // `useForm({ formControl })` overrides the control options with its own props: pass these again.\r\n options: this.resolverOptions as NonNullable<typeof this.resolverOptions>,\r\n };\r\n }\r\n getBootstrapId(): string | null {\r\n return this.bootstrapId;\r\n }\r\n\r\n /** The constructor of the strategy in use, typed with the statics declared via `StrategyClass`. */\r\n getStrategyClass<TStatics = {}>(): StrategyClass<TStrategy, TStatics> {\r\n return this.requireStrategy().constructor as StrategyClass<TStrategy, TStatics>;\r\n }\r\n\r\n validateStep(step: Step<any, any, any>): boolean {\r\n return this.getStepIssues(step).length === 0;\r\n }\r\n\r\n getStepIssues(step: Step<any, any, any>) {\r\n const values = this.requireForm().getValues(step.name as FieldPath<FieldValues>);\r\n const stepSchema = this.requireStrategy().getStepSchema(step);\r\n const validationResult = stepSchema.safeParse(values);\r\n return validationResult.success ? [] : validationResult.error.issues;\r\n }\r\n\r\n clearAll(removeListeners = true): void {\r\n this.strategy?.onDispose();\r\n this.headlessForm = null;\r\n this.strategy = null;\r\n this.bootstrapId = null;\r\n this.scopeId = null;\r\n this.revision = \"\";\r\n this.grants = {};\r\n this.claimsResolver = undefined;\r\n this.currentStepIndex = 0;\r\n this.currentStepValid = false;\r\n this.formStatus = null;\r\n this.notifyClaims();\r\n if (removeListeners) {\r\n this.unsubscribeForm?.();\r\n this.unsubscribeForm = null;\r\n this.stepsListeners.clear();\r\n }\r\n }\r\n\r\n /** Bootstraps the scope unless it is already the active one with the same `revision`: safe to call repeatedly. */\r\n ensureScope(id: string, factory: () => BootstrapOptions<TStrategy>, revision = \"\"): void {\r\n if (this.scopeId === id && this.revision === revision && this.hasCompletedBootstrap()) return;\r\n this.bootstrap(factory());\r\n this.scopeId = id;\r\n this.revision = revision;\r\n }\r\n\r\n /** Clears only if the active scope is `id`: leaving a page must not wipe the form of the one just opened. */\r\n clearScope(id: string): void {\r\n if (this.scopeId === id) this.clearAll();\r\n }\r\n\r\n resetFormManager(): void {\r\n this.strategy?.onReset();\r\n this.bootstrapId = createBootstrapId();\r\n this.currentStepIndex = 0;\r\n this.currentStepValid = false;\r\n this.requireForm().reset();\r\n this.recomputeCurrentStepValid();\r\n }\r\n\r\n bootstrap({ strategy, ...options }: BootstrapOptions<TStrategy>): this {\r\n this.clearAll();\r\n\r\n this.strategy = strategy;\r\n this.claimsResolver = options.claims;\r\n this.grants = this.resolveGrants(strategy);\r\n this.bootstrapId = createBootstrapId();\r\n\r\n const resolver: Resolver<FieldValues> = (...resolverArguments) => {\r\n const resolve = zodResolver(this.getResolverSchema() as ZodType<FieldValues, FieldValues>);\r\n return resolve(...(resolverArguments as Parameters<typeof resolve>)) as ReturnType<\r\n Resolver<FieldValues>\r\n >;\r\n };\r\n this.resolverOptions = { mode: options.validationMode ?? \"onChange\", resolver };\r\n this.headlessForm = createFormControl<FieldValues>({\r\n ...this.resolverOptions,\r\n defaultValues: options.defaultValues as DefaultValues<FieldValues>,\r\n disabled: options.disabled,\r\n });\r\n this.currentStepIndex = 0;\r\n this.currentStepValid = this.isCurrentStepValid();\r\n\r\n this.unsubscribeForm = this.headlessForm.subscribe({\r\n formState: { dirtyFields: true, touchedFields: true, values: true },\r\n callback: (data) => {\r\n this.formStatus = data as FormStatus;\r\n this.recomputeCurrentStepValid();\r\n },\r\n });\r\n this.notifyClaims();\r\n return this;\r\n }\r\n\r\n private resolveGrants(strategy: TStrategy): Record<string, ClaimDecision<TStrategy>> {\r\n return Object.fromEntries(\r\n strategy\r\n .getClaims()\r\n .map((id: string) => [id, this.claimsResolver?.claim(id as ClaimOf<TStrategy>) ?? NO_CLAIM]),\r\n );\r\n }\r\n\r\n /**\r\n * Swaps the strategy keeping the RHF control (values, dirty, touched), the listeners, the bootstrap id\r\n * and the current step (matched by name). If that step no longer exists, falls back to the closest\r\n * previous step that still exists, otherwise to the first one. Then revalidates the whole form.\r\n * Claims: `options.claims` replaces the resolver; without it the current one is reused.\r\n * `options.defaultValues` only fills top-level keys that are still `undefined` (e.g. steps new to the schema).\r\n */\r\n replaceStrategy(strategy: TStrategy, options: ReplaceStrategyOptions<TStrategy> = {}): this {\r\n const form = this.requireForm();\r\n const previousVisibleNames = this.getVisibleSteps().map((step) => step.name);\r\n const previousIndex = this.currentStepIndex;\r\n\r\n for (const [key, value] of Object.entries(options.defaultValues ?? {})) {\r\n if (form.getValues(key as FieldPath<FieldValues>) === undefined) {\r\n form.setValue(key as FieldPath<FieldValues>, value);\r\n }\r\n }\r\n\r\n this.strategy?.onDispose();\r\n this.strategy = strategy;\r\n if (options.claims) this.claimsResolver = options.claims;\r\n this.grants = this.resolveGrants(strategy);\r\n\r\n const visibleNames = this.getVisibleSteps().map((step) => step.name as string);\r\n const candidates = previousVisibleNames.slice(0, previousIndex + 1).reverse();\r\n const keptName = candidates.find((name) => visibleNames.includes(name as string));\r\n this.currentStepIndex = keptName === undefined ? 0 : visibleNames.indexOf(keptName as string);\r\n this.currentStepValid = this.isCurrentStepValid();\r\n\r\n void form.trigger();\r\n this.notifyClaims();\r\n this.callStepListeners();\r\n return this;\r\n }\r\n\r\n getFormSchema(): SchemaOf<TStrategy> {\r\n return this.requireStrategy().getFormSchema();\r\n }\r\n\r\n getFormStatus(): FormStatus | null {\r\n return this.formStatus;\r\n }\r\n\r\n getCurrentStepInfo = <TStep extends Step<any, any, any> = StepOf<TStrategy>>() =>\r\n this.buildCurrentStepInfo<TStep>();\r\n\r\n recomputeCurrentStepValid(): boolean {\r\n const nextValid = this.isCurrentStepValid();\r\n if (nextValid !== this.currentStepValid) {\r\n this.currentStepValid = nextValid;\r\n this.callStepListeners();\r\n }\r\n return nextValid;\r\n }\r\n\r\n private callStepListeners(): void {\r\n const currentStepData = this.buildCurrentStepInfo();\r\n this.stepsListeners.forEach((listener) => listener(currentStepData));\r\n }\r\n\r\n subscribeCurrentStepData = (listener: FormManagerStepListener<any>): (() => void) => {\r\n this.stepsListeners.add(listener);\r\n return () => {\r\n this.stepsListeners.delete(listener);\r\n };\r\n };\r\n\r\n isLastStep(): boolean {\r\n return this.currentStepIndex >= this.steps.length - 1;\r\n }\r\n\r\n getNextStep(): StepState<StepOf<TStrategy>> | null {\r\n this.requireForm();\r\n if (this.isLastStep()) return null;\r\n return this.steps[this.currentStepIndex + 1] ?? null;\r\n }\r\n\r\n getPrevStep(): StepState<StepOf<TStrategy>> | null {\r\n if (this.currentStepIndex <= 0) return null;\r\n return this.steps[this.currentStepIndex - 1] ?? null;\r\n }\r\n\r\n /** `false`: unknown step. `null`: already on that step. `true`: moved. */\r\n goToStep(stepName: StepOf<TStrategy>[\"name\"]): boolean | null {\r\n this.requireForm();\r\n const steps = this.getVisibleSteps();\r\n const index = steps.findIndex((step) => step.name === stepName);\r\n if (index < 0) return false;\r\n if (index === this.currentStepIndex) return null;\r\n this.moveToStep(index);\r\n return true;\r\n }\r\n\r\n /** Returns the new current step, or `null` when already on the last one. */\r\n goNext(): StepState<StepOf<TStrategy>> | null {\r\n this.requireForm();\r\n if (this.isLastStep()) return null;\r\n this.moveToStep(this.currentStepIndex + 1);\r\n return this.steps[this.currentStepIndex] ?? null;\r\n }\r\n\r\n /** Returns the new current step, or `null` when already on the first one. */\r\n goPrev(): StepState<StepOf<TStrategy>> | null {\r\n this.requireForm();\r\n if (this.currentStepIndex <= 0) return null;\r\n this.moveToStep(this.currentStepIndex - 1);\r\n return this.steps[this.currentStepIndex] ?? null;\r\n }\r\n\r\n private moveToStep(index: number): void {\r\n this.currentStepIndex = index;\r\n this.currentStepValid = this.isCurrentStepValid();\r\n this.callStepListeners();\r\n }\r\n\r\n getStepIndexByName(stepName: StepOf<TStrategy>[\"name\"]): number {\r\n return this.getVisibleSteps().findIndex((step) => step.name === stepName);\r\n }\r\n\r\n /** The manager does not interpret results: it forwards them to `onResult` each time the strategy reports. */\r\n async submit<TResult = SubmitResultOf<TStrategy>>(onResult?: (result: TResult) => void): Promise<void> {\r\n const form = this.requireForm();\r\n const strategy = this.requireStrategy();\r\n // handleSubmit returns the handler: invoke it. It validates before calling the strategy.\r\n await form.handleSubmit(async (data) => {\r\n await strategy.submit(data, (result: unknown) => onResult?.(result as TResult));\r\n })();\r\n }\r\n\r\n mergeFormValues(data: DeepPartial<ValuesOf<TStrategy>>, shouldTrigger = false): void {\r\n const form = this.requireForm();\r\n for (const key of Object.keys(data)) {\r\n const incoming = (data as Record<string, unknown>)[key];\r\n if (incoming === undefined || incoming === null) continue;\r\n const fieldKey = key as FieldPath<FieldValues>;\r\n form.setValue(fieldKey, shallowMerge(form.getValues(fieldKey), incoming), {\r\n shouldDirty: shouldTrigger,\r\n shouldValidate: shouldTrigger,\r\n });\r\n }\r\n }\r\n\r\n setFieldError(fieldName: string, error: ErrorOption): void {\r\n this.requireForm().setError(fieldName as FieldPath<FieldValues>, error);\r\n }\r\n\r\n getFormValues(): ValuesOf<TStrategy> {\r\n return this.requireForm().getValues() as ValuesOf<TStrategy>;\r\n }\r\n\r\n getStepFormData<T>(stepName: string): T {\r\n return this.requireForm().getValues(stepName as FieldPath<FieldValues>) as T;\r\n }\r\n\r\n getStrategyMetadata<T extends object>(): T {\r\n return { ...this.requireStrategy().getMetadata<T>() };\r\n }\r\n\r\n getStrategy(): TStrategy {\r\n return this.requireStrategy();\r\n }\r\n\r\n patchMetadata<T extends FormManagerMetadata>(metadata: T): void {\r\n const strategy = this.requireStrategy();\r\n strategy.updateMetadata({ ...strategy.getMetadata<T>(), ...metadata });\r\n }\r\n\r\n updateMetadataAndResetFormFields<T extends FormManagerMetadata>(\r\n metadata: T,\r\n data?: { values: DeepPartial<ValuesOf<TStrategy>>; options?: KeepStateOptions },\r\n ): void {\r\n const form = this.requireForm();\r\n this.patchMetadata(metadata);\r\n const mergedValues = { ...form.getValues(), ...data?.values };\r\n const { keepValues: _keepValues, ...resetOptions } = data?.options ?? {};\r\n form.reset(mergedValues, resetOptions);\r\n }\r\n\r\n hasCompletedBootstrap(): boolean {\r\n return this.strategy !== null;\r\n }\r\n}\r\n","import type { createFormControl, FieldValues, FormState } from \"react-hook-form\";\r\nimport type { z, ZodObject } from \"zod\";\r\nimport type { AbstractStrategy } from \"./strategy\";\r\n\r\n/** Action checked on a step whose `claim` is set but `action` is not. */\r\nexport const DEFAULT_ACTION = \"view\";\r\n\r\nexport type Step<\r\n TSchema extends ZodObject = ZodObject,\r\n TClaim extends string = string,\r\n TAction extends string = string,\r\n> = {\r\n /** Top-level key of the schema. */\r\n name: keyof z.infer<TSchema> & string;\r\n id: string;\r\n /** Claim that governs the step: without the granted action the step does not exist. */\r\n claim?: TClaim;\r\n /** Action required on the claim; defaults to `view`. */\r\n action?: TAction;\r\n};\r\n\r\n/** Decisions injected at bootstrap telling which claim/action pairs are granted. */\r\nexport type ClaimsResolver<TClaim extends string = string, TAction extends string = string> = {\r\n claim(id: TClaim): Partial<Record<TAction, boolean>>;\r\n};\r\n\r\n/** Result type declared by strategy `S` (fourth generic of `AbstractStrategy`). */\r\nexport type SubmitResultOf<S> = S extends AbstractStrategy<any, any, any, infer TResult, any, any>\r\n ? TResult\r\n : never;\r\n\r\nexport type ClaimOf<S> = S extends AbstractStrategy<any, any, any, any, infer TClaim, any>\r\n ? TClaim\r\n : never;\r\n\r\nexport type ActionOf<S> = S extends AbstractStrategy<any, any, any, any, any, infer TAction>\r\n ? TAction\r\n : never;\r\n\r\nexport type FormManagerMetadata = Record<string, unknown>;\r\n\r\nexport type StepState<TStep extends Step<any, any, any> = Step> = TStep & { error: boolean };\r\n\r\n/** Subset of the react-hook-form state tracked by the manager. */\r\nexport type FormStatus = Pick<FormState<FieldValues>, \"dirtyFields\" | \"touchedFields\"> & {\r\n values: FieldValues;\r\n};\r\n\r\nexport type FormManagerSteps<TStep extends Step<any, any, any> = Step> = {\r\n steps: StepState<TStep>[];\r\n currentStep: StepState<TStep> & { index: number };\r\n formStatus: FormStatus | null;\r\n};\r\n\r\nexport type FormManagerStepListener<TStep extends Step<any, any, any> = Step> = (\r\n stepsData: FormManagerSteps<TStep>,\r\n) => void;\r\n\r\nexport type HeadlessFormControl<TValues extends FieldValues = FieldValues> = ReturnType<\r\n typeof createFormControl<TValues>\r\n>;\r\n\r\nexport interface BootstrapOptions<TStrategy extends AbstractStrategy<any, any, any, any, any, any>> {\r\n strategy: TStrategy;\r\n defaultValues: z.infer<ReturnType<TStrategy[\"getFormSchema\"]>>;\r\n disabled?: boolean;\r\n validationMode?: \"onChange\" | \"onSubmit\";\r\n /** Granted claims. Without it no claim is granted. */\r\n claims?: ClaimsResolver<ClaimOf<TStrategy>, ActionOf<TStrategy>>;\r\n}\r\n\r\n/** Strategy constructor carrying user-defined static methods. */\r\nexport type StrategyClass<TStrategy, TStatics = {}> = (new (...args: any[]) => TStrategy) & TStatics;\r\n","import type { FormManagerSteps } from \"./models\";\r\n\r\nexport function shallowMerge(current: unknown, incoming: unknown): unknown {\r\n const isPlainObject = (value: unknown): value is Record<string, unknown> =>\r\n value !== null && typeof value === \"object\" && !Array.isArray(value);\r\n if (isPlainObject(incoming) && isPlainObject(current)) {\r\n return { ...current, ...incoming };\r\n }\r\n return incoming;\r\n}\r\n\r\nexport function isSameCurrentStepData(\r\n currentState: FormManagerSteps<any>,\r\n nextState: FormManagerSteps<any>,\r\n): boolean {\r\n const isCurrentSame =\r\n currentState.currentStep.index === nextState.currentStep.index &&\r\n currentState.currentStep.name === nextState.currentStep.name &&\r\n currentState.currentStep.error === nextState.currentStep.error;\r\n if (!isCurrentSame) return false;\r\n if (currentState.steps.length !== nextState.steps.length) return false;\r\n return !currentState.steps.some(\r\n (step) => step.error !== nextState.steps.find((next) => next.name === step.name)?.error,\r\n );\r\n}\r\n\r\nexport function createBootstrapId(): string {\r\n if (typeof crypto !== \"undefined\" && typeof crypto.randomUUID === \"function\") {\r\n return crypto.randomUUID();\r\n }\r\n return `bootstrap-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 10)}`;\r\n}\r\n","import type { z, ZodObject } from \"zod\";\r\nimport type { FormManagerMetadata, Step } from \"./models\";\r\n\r\nexport abstract class AbstractStrategy<\r\n TSchema extends ZodObject = ZodObject,\r\n TSubmitData = z.infer<TSchema>,\r\n TMetadata extends object = FormManagerMetadata,\r\n TSubmitResult = unknown,\r\n TClaim extends string = string,\r\n TAction extends string = string,\r\n> {\r\n protected abstract steps: readonly Step<TSchema, TClaim, TAction>[];\r\n protected abstract schema: TSchema;\r\n protected abstract metadata?: TMetadata;\r\n /** Claims used by the form besides the ones of its steps (e.g. sections inside a step). */\r\n protected claims: readonly TClaim[] = [];\r\n\r\n /** `report` may be called many times (e.g. pending, then the final status). */\r\n abstract submit(\r\n data: TSubmitData,\r\n report: (result: TSubmitResult) => void,\r\n ): void | Promise<void>;\r\n\r\n /** Hook: the form is reset (`resetFormManager`). Release in-flight work here. */\r\n onReset(): void {}\r\n\r\n /** Hook: the strategy is retired (`clearAll`, `clearScope`, a new `bootstrap`). */\r\n onDispose(): void {}\r\n\r\n getSteps(): readonly Step<TSchema, TClaim, TAction>[] {\r\n return this.steps;\r\n }\r\n\r\n /** All declared steps, before claims: needed to know which schemas to neutralize. */\r\n getDeclaredSteps(): readonly Step<TSchema, TClaim, TAction>[] {\r\n return this.steps;\r\n }\r\n\r\n /** Form claims: the declared ones plus the ones of the steps. */\r\n getClaims(): TClaim[] {\r\n const ids = new Set<TClaim>(this.claims);\r\n for (const step of this.steps) if (step.claim) ids.add(step.claim);\r\n return [...ids];\r\n }\r\n\r\n getFormSchema(): TSchema {\r\n return this.schema;\r\n }\r\n\r\n /** The schema root must be a `ZodObject`: each step maps to one of its keys. */\r\n getStepSchema(step: Step<TSchema, TClaim, TAction>): z.ZodType {\r\n return this.schema.shape[step.name as string] as z.ZodType;\r\n }\r\n\r\n getMetadata<T>(): T {\r\n return this.metadata as T;\r\n }\r\n\r\n updateMetadata(metadata: Partial<TMetadata>): void {\r\n this.metadata = { ...this.metadata, ...metadata } as TMetadata;\r\n }\r\n}\r\n\r\nexport type AnyStrategy = AbstractStrategy<any, any, any, any, any, any>;\r\n","import {\r\n createContext,\r\n useContext,\r\n useMemo,\r\n useRef,\r\n useSyncExternalStore,\r\n type ReactNode,\r\n} from \"react\";\r\nimport {\r\n useForm,\r\n type Control,\r\n type FieldValues,\r\n type UseFormReturn,\r\n type UseFormSetError,\r\n type UseFormSetValue,\r\n type UseFormTrigger,\r\n} from \"react-hook-form\";\r\nimport type { FormManager } from \"./form-manager\";\r\nimport type { ActionOf, ClaimOf, FormManagerSteps, Step } from \"./models\";\r\nimport type { AnyStrategy } from \"./strategy\";\r\nimport { isSameCurrentStepData } from \"./utils\";\r\n\r\nexport interface FormControlContext<TValues extends FieldValues = FieldValues> {\r\n setValue: UseFormSetValue<TValues>;\r\n setError: UseFormSetError<TValues>;\r\n trigger: UseFormTrigger<TValues>;\r\n control: Control<TValues, unknown, TValues>;\r\n}\r\n\r\ninterface FormManagerContextValue {\r\n manager: FormManager<any> | null;\r\n controls: FormControlContext<any>;\r\n}\r\n\r\nconst FormManagerContext = createContext<FormManagerContextValue | null>(null);\r\n\r\ntype ControlSource = Pick<UseFormReturn<any>, \"control\" | \"setValue\" | \"setError\" | \"trigger\">;\r\n\r\nfunction ContextBridge({\r\n manager,\r\n source,\r\n children,\r\n}: Readonly<{ manager: FormManager<any> | null; source: ControlSource; children: ReactNode }>) {\r\n const { control, setValue, setError, trigger } = source;\r\n const value = useMemo<FormManagerContextValue>(\r\n () => ({ manager, controls: { control, setValue, setError, trigger } }),\r\n [manager, control, setValue, setError, trigger],\r\n );\r\n return <FormManagerContext.Provider value={value}>{children}</FormManagerContext.Provider>;\r\n}\r\n\r\nfunction ManagerProvider({\r\n manager,\r\n children,\r\n}: Readonly<{ manager: FormManager<any>; children: ReactNode }>) {\r\n const methods = useForm({ formControl: manager.form.control, ...manager.form.options });\r\n return (\r\n <ContextBridge manager={manager} source={methods}>\r\n {children}\r\n </ContextBridge>\r\n );\r\n}\r\n\r\nexport type FormManagerProviderProps =\r\n | Readonly<{ manager: FormManager<any>; methods?: never; children: ReactNode }>\r\n | Readonly<{ methods: UseFormReturn<any>; manager?: never; children: ReactNode }>;\r\n\r\n/**\r\n * Provides a form to the tree. `manager` (multi-step, must be bootstrapped) or `methods` (single page, from `useForm`).\r\n */\r\nexport function FormManagerProvider(props: FormManagerProviderProps) {\r\n if (props.manager) {\r\n return <ManagerProvider manager={props.manager}>{props.children}</ManagerProvider>;\r\n }\r\n return (\r\n <ContextBridge manager={null} source={props.methods}>\r\n {props.children}\r\n </ContextBridge>\r\n );\r\n}\r\n\r\nfunction useFormManagerContext(hookName: string): FormManagerContextValue {\r\n const context = useContext(FormManagerContext);\r\n if (!context) throw new Error(`${hookName} must be used within a FormManagerProvider`);\r\n return context;\r\n}\r\n\r\nfunction useRequiredManager<TStrategy extends AnyStrategy>(hookName: string): FormManager<TStrategy> {\r\n const { manager } = useFormManagerContext(hookName);\r\n if (!manager) {\r\n throw new Error(`${hookName} needs a FormManagerProvider created with \\`manager\\`, not \\`methods\\``);\r\n }\r\n return manager as FormManager<TStrategy>;\r\n}\r\n\r\n/** The manager of the closest provider. Throws outside a provider or in single page mode. */\r\nexport function useFormManager<TStrategy extends AnyStrategy = AnyStrategy>(): FormManager<TStrategy> {\r\n return useRequiredManager<TStrategy>(\"useFormManager\");\r\n}\r\n\r\nexport function useFormControl<TValues extends FieldValues = FieldValues>(): FormControlContext<TValues> {\r\n return useFormManagerContext(\"useFormControl\").controls as FormControlContext<TValues>;\r\n}\r\n\r\n/** Steps and current step of the manager, with a stable snapshot while nothing relevant changes. */\r\nexport function useFormSteps<TStep extends Step<any, any, any> = Step>(): FormManagerSteps<TStep> {\r\n const manager = useRequiredManager<AnyStrategy>(\"useFormSteps\");\r\n const snapshotRef = useRef<FormManagerSteps<TStep> | null>(null);\r\n const getSnapshot = () => {\r\n const nextSnapshot = manager.getCurrentStepInfo<TStep>();\r\n const currentSnapshot = snapshotRef.current;\r\n if (currentSnapshot && isSameCurrentStepData(currentSnapshot, nextSnapshot)) {\r\n return currentSnapshot;\r\n }\r\n snapshotRef.current = nextSnapshot;\r\n return nextSnapshot;\r\n };\r\n return useSyncExternalStore(manager.subscribeCurrentStepData, getSnapshot, getSnapshot);\r\n}\r\n\r\n/** Actions granted on a claim, as decided at bootstrap. Without a bootstrapped form nothing is granted. */\r\nexport function useFormClaims<TStrategy extends AnyStrategy = AnyStrategy>(\r\n id: ClaimOf<TStrategy>,\r\n): Partial<Record<ActionOf<TStrategy>, boolean>> {\r\n const manager = useRequiredManager<TStrategy>(\"useFormClaims\");\r\n return useSyncExternalStore(\r\n manager.subscribeClaims,\r\n () => manager.getClaim(id),\r\n () => manager.getClaim(id),\r\n );\r\n}\r\n","import type { CSSProperties, ReactNode } from \"react\";\r\n\r\nexport interface StepFormProps {\r\n name: string;\r\n id?: string;\r\n children: ReactNode;\r\n style?: CSSProperties;\r\n onSubmit?: () => void;\r\n}\r\n\r\nexport function StepForm({ name, id, children, style, onSubmit }: Readonly<StepFormProps>) {\r\n return (\r\n <form\r\n id={id}\r\n name={name}\r\n data-testid={`${name}-form`}\r\n style={style}\r\n noValidate\r\n onSubmit={(event) => {\r\n event.preventDefault();\r\n onSubmit?.();\r\n }}\r\n >\r\n {children}\r\n </form>\r\n );\r\n}\r\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACAA,iBAA4B;AAC5B,6BASO;AACP,IAAAA,cAAgD;;;ACNzC,IAAM,iBAAiB;;;ACHvB,SAAS,aAAa,SAAkB,UAA4B;AACzE,QAAM,gBAAgB,CAAC,UACrB,UAAU,QAAQ,OAAO,UAAU,YAAY,CAAC,MAAM,QAAQ,KAAK;AACrE,MAAI,cAAc,QAAQ,KAAK,cAAc,OAAO,GAAG;AACrD,WAAO,EAAE,GAAG,SAAS,GAAG,SAAS;AAAA,EACnC;AACA,SAAO;AACT;AAEO,SAAS,sBACd,cACA,WACS;AACT,QAAM,gBACJ,aAAa,YAAY,UAAU,UAAU,YAAY,SACzD,aAAa,YAAY,SAAS,UAAU,YAAY,QACxD,aAAa,YAAY,UAAU,UAAU,YAAY;AAC3D,MAAI,CAAC,cAAe,QAAO;AAC3B,MAAI,aAAa,MAAM,WAAW,UAAU,MAAM,OAAQ,QAAO;AACjE,SAAO,CAAC,aAA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G;AACA,SAAO;AACT;AAGO,SAAS,iBAAsF;AACpG,SAAO,mBAA8B,gBAAgB;AACvD;AAEO,SAAS,iBAAyF;AACvG,SAAO,sBAAsB,gBAAgB,EAAE;AACjD;AAGO,SAAS,eAAkF;AAChG,QAAM,UAAU,mBAAgC,cAAc;AAC9D,QAAM,kBAAc,qBAAuC,IAAI;AAC/D,QAAM,cAAc,MAAM;AACxB,UAAM,eAAe,QAAQ,mBAA0B;AACvD,UAAM,kBAAkB,YAAY;AACpC,QAAI,mBAAmB,sBAAsB,iBAAiB,YAAY,GAAG;AAC3E,aAAO;AAAA,IACT;AACA,gBAAY,UAAU;AACtB,WAAO;AAAA,EACT;AACA,aAAO,mCAAqB,QAAQ,0BAA0B,aAAa,WAAW;AACxF;AAGO,SAAS,cACd,IAC+C;AAC/C,QAAM,UAAU,mBAA8B,eAAe;AAC7D,aAAO;AAAA,IACL,QAAQ;AAAA,IACR,MAAM,QAAQ,SAAS,EAAE;AAAA,IACzB,MAAM,QAAQ,SAAS,EAAE;AAAA,EAC3B;AACF;;;ACtHI,IAAAC,sBAAA;AAFG,SAAS,SAAS,EAAE,MAAM,IAAI,UAAU,OAAO,SAAS,GAA4B;AACzF,SACE;AAAA,IAAC;AAAA;AAAA,MACC;AAAA,MACA;AAAA,MACA,eAAa,GAAG,IAAI;AAAA,MACpB;AAAA,MACA,YAAU;AAAA,MACV,UAAU,CAAC,UAAU;AACnB,cAAM,eAAe;AACrB,mBAAW;AAAA,MACb;AAAA,MAEC;AAAA;AAAA,EACH;AAEJ;","names":["import_zod","import_react_hook_form","import_jsx_runtime"]}
|
package/dist/index.d.cts
ADDED
|
@@ -0,0 +1,217 @@
|
|
|
1
|
+
import { FieldValues, createFormControl, FormState, Resolver, DeepPartial, ErrorOption, KeepStateOptions, UseFormSetValue, UseFormSetError, UseFormTrigger, Control, UseFormReturn } from 'react-hook-form';
|
|
2
|
+
import { ZodObject, z } from 'zod';
|
|
3
|
+
import * as react from 'react';
|
|
4
|
+
import { ReactNode, CSSProperties } from 'react';
|
|
5
|
+
|
|
6
|
+
declare abstract class AbstractStrategy<TSchema extends ZodObject = ZodObject, TSubmitData = z.infer<TSchema>, TMetadata extends object = FormManagerMetadata, TSubmitResult = unknown, TClaim extends string = string, TAction extends string = string> {
|
|
7
|
+
protected abstract steps: readonly Step<TSchema, TClaim, TAction>[];
|
|
8
|
+
protected abstract schema: TSchema;
|
|
9
|
+
protected abstract metadata?: TMetadata;
|
|
10
|
+
/** Claims used by the form besides the ones of its steps (e.g. sections inside a step). */
|
|
11
|
+
protected claims: readonly TClaim[];
|
|
12
|
+
/** `report` may be called many times (e.g. pending, then the final status). */
|
|
13
|
+
abstract submit(data: TSubmitData, report: (result: TSubmitResult) => void): void | Promise<void>;
|
|
14
|
+
/** Hook: the form is reset (`resetFormManager`). Release in-flight work here. */
|
|
15
|
+
onReset(): void;
|
|
16
|
+
/** Hook: the strategy is retired (`clearAll`, `clearScope`, a new `bootstrap`). */
|
|
17
|
+
onDispose(): void;
|
|
18
|
+
getSteps(): readonly Step<TSchema, TClaim, TAction>[];
|
|
19
|
+
/** All declared steps, before claims: needed to know which schemas to neutralize. */
|
|
20
|
+
getDeclaredSteps(): readonly Step<TSchema, TClaim, TAction>[];
|
|
21
|
+
/** Form claims: the declared ones plus the ones of the steps. */
|
|
22
|
+
getClaims(): TClaim[];
|
|
23
|
+
getFormSchema(): TSchema;
|
|
24
|
+
/** The schema root must be a `ZodObject`: each step maps to one of its keys. */
|
|
25
|
+
getStepSchema(step: Step<TSchema, TClaim, TAction>): z.ZodType;
|
|
26
|
+
getMetadata<T>(): T;
|
|
27
|
+
updateMetadata(metadata: Partial<TMetadata>): void;
|
|
28
|
+
}
|
|
29
|
+
type AnyStrategy = AbstractStrategy<any, any, any, any, any, any>;
|
|
30
|
+
|
|
31
|
+
type Step<TSchema extends ZodObject = ZodObject, TClaim extends string = string, TAction extends string = string> = {
|
|
32
|
+
/** Top-level key of the schema. */
|
|
33
|
+
name: keyof z.infer<TSchema> & string;
|
|
34
|
+
id: string;
|
|
35
|
+
/** Claim that governs the step: without the granted action the step does not exist. */
|
|
36
|
+
claim?: TClaim;
|
|
37
|
+
/** Action required on the claim; defaults to `view`. */
|
|
38
|
+
action?: TAction;
|
|
39
|
+
};
|
|
40
|
+
/** Decisions injected at bootstrap telling which claim/action pairs are granted. */
|
|
41
|
+
type ClaimsResolver<TClaim extends string = string, TAction extends string = string> = {
|
|
42
|
+
claim(id: TClaim): Partial<Record<TAction, boolean>>;
|
|
43
|
+
};
|
|
44
|
+
/** Result type declared by strategy `S` (fourth generic of `AbstractStrategy`). */
|
|
45
|
+
type SubmitResultOf<S> = S extends AbstractStrategy<any, any, any, infer TResult, any, any> ? TResult : never;
|
|
46
|
+
type ClaimOf<S> = S extends AbstractStrategy<any, any, any, any, infer TClaim, any> ? TClaim : never;
|
|
47
|
+
type ActionOf<S> = S extends AbstractStrategy<any, any, any, any, any, infer TAction> ? TAction : never;
|
|
48
|
+
type FormManagerMetadata = Record<string, unknown>;
|
|
49
|
+
type StepState<TStep extends Step<any, any, any> = Step> = TStep & {
|
|
50
|
+
error: boolean;
|
|
51
|
+
};
|
|
52
|
+
/** Subset of the react-hook-form state tracked by the manager. */
|
|
53
|
+
type FormStatus = Pick<FormState<FieldValues>, "dirtyFields" | "touchedFields"> & {
|
|
54
|
+
values: FieldValues;
|
|
55
|
+
};
|
|
56
|
+
type FormManagerSteps<TStep extends Step<any, any, any> = Step> = {
|
|
57
|
+
steps: StepState<TStep>[];
|
|
58
|
+
currentStep: StepState<TStep> & {
|
|
59
|
+
index: number;
|
|
60
|
+
};
|
|
61
|
+
formStatus: FormStatus | null;
|
|
62
|
+
};
|
|
63
|
+
type FormManagerStepListener<TStep extends Step<any, any, any> = Step> = (stepsData: FormManagerSteps<TStep>) => void;
|
|
64
|
+
type HeadlessFormControl<TValues extends FieldValues = FieldValues> = ReturnType<typeof createFormControl<TValues>>;
|
|
65
|
+
interface BootstrapOptions<TStrategy extends AbstractStrategy<any, any, any, any, any, any>> {
|
|
66
|
+
strategy: TStrategy;
|
|
67
|
+
defaultValues: z.infer<ReturnType<TStrategy["getFormSchema"]>>;
|
|
68
|
+
disabled?: boolean;
|
|
69
|
+
validationMode?: "onChange" | "onSubmit";
|
|
70
|
+
/** Granted claims. Without it no claim is granted. */
|
|
71
|
+
claims?: ClaimsResolver<ClaimOf<TStrategy>, ActionOf<TStrategy>>;
|
|
72
|
+
}
|
|
73
|
+
/** Strategy constructor carrying user-defined static methods. */
|
|
74
|
+
type StrategyClass<TStrategy, TStatics = {}> = (new (...args: any[]) => TStrategy) & TStatics;
|
|
75
|
+
|
|
76
|
+
type SchemaOf<TStrategy extends AnyStrategy> = ReturnType<TStrategy["getFormSchema"]>;
|
|
77
|
+
type ValuesOf<TStrategy extends AnyStrategy> = z.infer<SchemaOf<TStrategy>>;
|
|
78
|
+
type StepOf<TStrategy extends AnyStrategy> = ReturnType<TStrategy["getSteps"]>[number];
|
|
79
|
+
type ClaimDecision<TStrategy extends AnyStrategy> = Partial<Record<ActionOf<TStrategy>, boolean>>;
|
|
80
|
+
type RhfMember = "setValue" | "getValues" | "resetField" | "trigger" | "unregister" | "reset" | "setError" | "clearErrors" | "handleSubmit";
|
|
81
|
+
type FormControlFacade = Pick<HeadlessFormControl<FieldValues>, RhfMember> & {
|
|
82
|
+
control: HeadlessFormControl<FieldValues>["formControl"];
|
|
83
|
+
options: {
|
|
84
|
+
mode: "onChange" | "onSubmit";
|
|
85
|
+
resolver: Resolver<FieldValues>;
|
|
86
|
+
};
|
|
87
|
+
};
|
|
88
|
+
type ReplaceStrategyOptions<TStrategy extends AnyStrategy> = {
|
|
89
|
+
claims?: BootstrapOptions<TStrategy>["claims"];
|
|
90
|
+
defaultValues?: DeepPartial<z.infer<ReturnType<TStrategy["getFormSchema"]>>>;
|
|
91
|
+
};
|
|
92
|
+
/** Owns one form: its react-hook-form control, current step, claims and listeners. One instance per form. */
|
|
93
|
+
declare class FormManager<TStrategy extends AnyStrategy = AnyStrategy> {
|
|
94
|
+
private strategy;
|
|
95
|
+
private bootstrapId;
|
|
96
|
+
private scopeId;
|
|
97
|
+
private revision;
|
|
98
|
+
private grants;
|
|
99
|
+
private claimsResolver;
|
|
100
|
+
private readonly claimsListeners;
|
|
101
|
+
private formStatus;
|
|
102
|
+
private currentStepIndex;
|
|
103
|
+
private currentStepValid;
|
|
104
|
+
private readonly stepsListeners;
|
|
105
|
+
private unsubscribeForm;
|
|
106
|
+
private headlessForm;
|
|
107
|
+
private resolverOptions;
|
|
108
|
+
/** Neutralizes (`z.any()`) the schema of denied steps so their default values survive submit. */
|
|
109
|
+
protected getResolverSchema(): ZodObject;
|
|
110
|
+
private isGranted;
|
|
111
|
+
/** Decision taken at bootstrap, stable until the form is rebuilt. Unknown claim or no form = no action. */
|
|
112
|
+
getClaim: (id: ClaimOf<TStrategy>) => ClaimDecision<TStrategy>;
|
|
113
|
+
subscribeClaims: (listener: () => void) => (() => void);
|
|
114
|
+
private notifyClaims;
|
|
115
|
+
private requireStrategy;
|
|
116
|
+
private requireForm;
|
|
117
|
+
private isCurrentStepValid;
|
|
118
|
+
private getVisibleSteps;
|
|
119
|
+
private buildCurrentStepInfo;
|
|
120
|
+
get steps(): StepState<StepOf<TStrategy>>[];
|
|
121
|
+
/**
|
|
122
|
+
* Thin access to the react-hook-form control. Everything here delegates to RHF;
|
|
123
|
+
* the rest of the class is the step logic. Throws before `bootstrap`.
|
|
124
|
+
*/
|
|
125
|
+
get form(): FormControlFacade;
|
|
126
|
+
getBootstrapId(): string | null;
|
|
127
|
+
/** The constructor of the strategy in use, typed with the statics declared via `StrategyClass`. */
|
|
128
|
+
getStrategyClass<TStatics = {}>(): StrategyClass<TStrategy, TStatics>;
|
|
129
|
+
validateStep(step: Step<any, any, any>): boolean;
|
|
130
|
+
getStepIssues(step: Step<any, any, any>): z.core.$ZodIssue[];
|
|
131
|
+
clearAll(removeListeners?: boolean): void;
|
|
132
|
+
/** Bootstraps the scope unless it is already the active one with the same `revision`: safe to call repeatedly. */
|
|
133
|
+
ensureScope(id: string, factory: () => BootstrapOptions<TStrategy>, revision?: string): void;
|
|
134
|
+
/** Clears only if the active scope is `id`: leaving a page must not wipe the form of the one just opened. */
|
|
135
|
+
clearScope(id: string): void;
|
|
136
|
+
resetFormManager(): void;
|
|
137
|
+
bootstrap({ strategy, ...options }: BootstrapOptions<TStrategy>): this;
|
|
138
|
+
private resolveGrants;
|
|
139
|
+
/**
|
|
140
|
+
* Swaps the strategy keeping the RHF control (values, dirty, touched), the listeners, the bootstrap id
|
|
141
|
+
* and the current step (matched by name). If that step no longer exists, falls back to the closest
|
|
142
|
+
* previous step that still exists, otherwise to the first one. Then revalidates the whole form.
|
|
143
|
+
* Claims: `options.claims` replaces the resolver; without it the current one is reused.
|
|
144
|
+
* `options.defaultValues` only fills top-level keys that are still `undefined` (e.g. steps new to the schema).
|
|
145
|
+
*/
|
|
146
|
+
replaceStrategy(strategy: TStrategy, options?: ReplaceStrategyOptions<TStrategy>): this;
|
|
147
|
+
getFormSchema(): SchemaOf<TStrategy>;
|
|
148
|
+
getFormStatus(): FormStatus | null;
|
|
149
|
+
getCurrentStepInfo: <TStep extends Step<any, any, any> = StepOf<TStrategy>>() => FormManagerSteps<TStep>;
|
|
150
|
+
recomputeCurrentStepValid(): boolean;
|
|
151
|
+
private callStepListeners;
|
|
152
|
+
subscribeCurrentStepData: (listener: FormManagerStepListener<any>) => (() => void);
|
|
153
|
+
isLastStep(): boolean;
|
|
154
|
+
getNextStep(): StepState<StepOf<TStrategy>> | null;
|
|
155
|
+
getPrevStep(): StepState<StepOf<TStrategy>> | null;
|
|
156
|
+
/** `false`: unknown step. `null`: already on that step. `true`: moved. */
|
|
157
|
+
goToStep(stepName: StepOf<TStrategy>["name"]): boolean | null;
|
|
158
|
+
/** Returns the new current step, or `null` when already on the last one. */
|
|
159
|
+
goNext(): StepState<StepOf<TStrategy>> | null;
|
|
160
|
+
/** Returns the new current step, or `null` when already on the first one. */
|
|
161
|
+
goPrev(): StepState<StepOf<TStrategy>> | null;
|
|
162
|
+
private moveToStep;
|
|
163
|
+
getStepIndexByName(stepName: StepOf<TStrategy>["name"]): number;
|
|
164
|
+
/** The manager does not interpret results: it forwards them to `onResult` each time the strategy reports. */
|
|
165
|
+
submit<TResult = SubmitResultOf<TStrategy>>(onResult?: (result: TResult) => void): Promise<void>;
|
|
166
|
+
mergeFormValues(data: DeepPartial<ValuesOf<TStrategy>>, shouldTrigger?: boolean): void;
|
|
167
|
+
setFieldError(fieldName: string, error: ErrorOption): void;
|
|
168
|
+
getFormValues(): ValuesOf<TStrategy>;
|
|
169
|
+
getStepFormData<T>(stepName: string): T;
|
|
170
|
+
getStrategyMetadata<T extends object>(): T;
|
|
171
|
+
getStrategy(): TStrategy;
|
|
172
|
+
patchMetadata<T extends FormManagerMetadata>(metadata: T): void;
|
|
173
|
+
updateMetadataAndResetFormFields<T extends FormManagerMetadata>(metadata: T, data?: {
|
|
174
|
+
values: DeepPartial<ValuesOf<TStrategy>>;
|
|
175
|
+
options?: KeepStateOptions;
|
|
176
|
+
}): void;
|
|
177
|
+
hasCompletedBootstrap(): boolean;
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
interface FormControlContext<TValues extends FieldValues = FieldValues> {
|
|
181
|
+
setValue: UseFormSetValue<TValues>;
|
|
182
|
+
setError: UseFormSetError<TValues>;
|
|
183
|
+
trigger: UseFormTrigger<TValues>;
|
|
184
|
+
control: Control<TValues, unknown, TValues>;
|
|
185
|
+
}
|
|
186
|
+
type FormManagerProviderProps = Readonly<{
|
|
187
|
+
manager: FormManager<any>;
|
|
188
|
+
methods?: never;
|
|
189
|
+
children: ReactNode;
|
|
190
|
+
}> | Readonly<{
|
|
191
|
+
methods: UseFormReturn<any>;
|
|
192
|
+
manager?: never;
|
|
193
|
+
children: ReactNode;
|
|
194
|
+
}>;
|
|
195
|
+
/**
|
|
196
|
+
* Provides a form to the tree. `manager` (multi-step, must be bootstrapped) or `methods` (single page, from `useForm`).
|
|
197
|
+
*/
|
|
198
|
+
declare function FormManagerProvider(props: FormManagerProviderProps): react.JSX.Element;
|
|
199
|
+
/** The manager of the closest provider. Throws outside a provider or in single page mode. */
|
|
200
|
+
declare function useFormManager<TStrategy extends AnyStrategy = AnyStrategy>(): FormManager<TStrategy>;
|
|
201
|
+
declare function useFormControl<TValues extends FieldValues = FieldValues>(): FormControlContext<TValues>;
|
|
202
|
+
/** Steps and current step of the manager, with a stable snapshot while nothing relevant changes. */
|
|
203
|
+
declare function useFormSteps<TStep extends Step<any, any, any> = Step>(): FormManagerSteps<TStep>;
|
|
204
|
+
/** Actions granted on a claim, as decided at bootstrap. Without a bootstrapped form nothing is granted. */
|
|
205
|
+
declare function useFormClaims<TStrategy extends AnyStrategy = AnyStrategy>(id: ClaimOf<TStrategy>): Partial<Record<ActionOf<TStrategy>, boolean>>;
|
|
206
|
+
|
|
207
|
+
interface StepFormProps {
|
|
208
|
+
name: string;
|
|
209
|
+
id?: string;
|
|
210
|
+
children: ReactNode;
|
|
211
|
+
style?: CSSProperties;
|
|
212
|
+
onSubmit?: () => void;
|
|
213
|
+
}
|
|
214
|
+
declare function StepForm({ name, id, children, style, onSubmit }: Readonly<StepFormProps>): react.JSX.Element;
|
|
215
|
+
|
|
216
|
+
export { AbstractStrategy, FormManager, FormManagerProvider, StepForm, useFormClaims, useFormControl, useFormManager, useFormSteps };
|
|
217
|
+
export type { ActionOf, BootstrapOptions, ClaimOf, ClaimsResolver, FormControlContext, FormControlFacade, FormManagerMetadata, FormManagerProviderProps, FormManagerSteps, FormStatus, ReplaceStrategyOptions, Step, StepFormProps, StrategyClass, SubmitResultOf };
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,217 @@
|
|
|
1
|
+
import { FieldValues, createFormControl, FormState, Resolver, DeepPartial, ErrorOption, KeepStateOptions, UseFormSetValue, UseFormSetError, UseFormTrigger, Control, UseFormReturn } from 'react-hook-form';
|
|
2
|
+
import { ZodObject, z } from 'zod';
|
|
3
|
+
import * as react from 'react';
|
|
4
|
+
import { ReactNode, CSSProperties } from 'react';
|
|
5
|
+
|
|
6
|
+
declare abstract class AbstractStrategy<TSchema extends ZodObject = ZodObject, TSubmitData = z.infer<TSchema>, TMetadata extends object = FormManagerMetadata, TSubmitResult = unknown, TClaim extends string = string, TAction extends string = string> {
|
|
7
|
+
protected abstract steps: readonly Step<TSchema, TClaim, TAction>[];
|
|
8
|
+
protected abstract schema: TSchema;
|
|
9
|
+
protected abstract metadata?: TMetadata;
|
|
10
|
+
/** Claims used by the form besides the ones of its steps (e.g. sections inside a step). */
|
|
11
|
+
protected claims: readonly TClaim[];
|
|
12
|
+
/** `report` may be called many times (e.g. pending, then the final status). */
|
|
13
|
+
abstract submit(data: TSubmitData, report: (result: TSubmitResult) => void): void | Promise<void>;
|
|
14
|
+
/** Hook: the form is reset (`resetFormManager`). Release in-flight work here. */
|
|
15
|
+
onReset(): void;
|
|
16
|
+
/** Hook: the strategy is retired (`clearAll`, `clearScope`, a new `bootstrap`). */
|
|
17
|
+
onDispose(): void;
|
|
18
|
+
getSteps(): readonly Step<TSchema, TClaim, TAction>[];
|
|
19
|
+
/** All declared steps, before claims: needed to know which schemas to neutralize. */
|
|
20
|
+
getDeclaredSteps(): readonly Step<TSchema, TClaim, TAction>[];
|
|
21
|
+
/** Form claims: the declared ones plus the ones of the steps. */
|
|
22
|
+
getClaims(): TClaim[];
|
|
23
|
+
getFormSchema(): TSchema;
|
|
24
|
+
/** The schema root must be a `ZodObject`: each step maps to one of its keys. */
|
|
25
|
+
getStepSchema(step: Step<TSchema, TClaim, TAction>): z.ZodType;
|
|
26
|
+
getMetadata<T>(): T;
|
|
27
|
+
updateMetadata(metadata: Partial<TMetadata>): void;
|
|
28
|
+
}
|
|
29
|
+
type AnyStrategy = AbstractStrategy<any, any, any, any, any, any>;
|
|
30
|
+
|
|
31
|
+
type Step<TSchema extends ZodObject = ZodObject, TClaim extends string = string, TAction extends string = string> = {
|
|
32
|
+
/** Top-level key of the schema. */
|
|
33
|
+
name: keyof z.infer<TSchema> & string;
|
|
34
|
+
id: string;
|
|
35
|
+
/** Claim that governs the step: without the granted action the step does not exist. */
|
|
36
|
+
claim?: TClaim;
|
|
37
|
+
/** Action required on the claim; defaults to `view`. */
|
|
38
|
+
action?: TAction;
|
|
39
|
+
};
|
|
40
|
+
/** Decisions injected at bootstrap telling which claim/action pairs are granted. */
|
|
41
|
+
type ClaimsResolver<TClaim extends string = string, TAction extends string = string> = {
|
|
42
|
+
claim(id: TClaim): Partial<Record<TAction, boolean>>;
|
|
43
|
+
};
|
|
44
|
+
/** Result type declared by strategy `S` (fourth generic of `AbstractStrategy`). */
|
|
45
|
+
type SubmitResultOf<S> = S extends AbstractStrategy<any, any, any, infer TResult, any, any> ? TResult : never;
|
|
46
|
+
type ClaimOf<S> = S extends AbstractStrategy<any, any, any, any, infer TClaim, any> ? TClaim : never;
|
|
47
|
+
type ActionOf<S> = S extends AbstractStrategy<any, any, any, any, any, infer TAction> ? TAction : never;
|
|
48
|
+
type FormManagerMetadata = Record<string, unknown>;
|
|
49
|
+
type StepState<TStep extends Step<any, any, any> = Step> = TStep & {
|
|
50
|
+
error: boolean;
|
|
51
|
+
};
|
|
52
|
+
/** Subset of the react-hook-form state tracked by the manager. */
|
|
53
|
+
type FormStatus = Pick<FormState<FieldValues>, "dirtyFields" | "touchedFields"> & {
|
|
54
|
+
values: FieldValues;
|
|
55
|
+
};
|
|
56
|
+
type FormManagerSteps<TStep extends Step<any, any, any> = Step> = {
|
|
57
|
+
steps: StepState<TStep>[];
|
|
58
|
+
currentStep: StepState<TStep> & {
|
|
59
|
+
index: number;
|
|
60
|
+
};
|
|
61
|
+
formStatus: FormStatus | null;
|
|
62
|
+
};
|
|
63
|
+
type FormManagerStepListener<TStep extends Step<any, any, any> = Step> = (stepsData: FormManagerSteps<TStep>) => void;
|
|
64
|
+
type HeadlessFormControl<TValues extends FieldValues = FieldValues> = ReturnType<typeof createFormControl<TValues>>;
|
|
65
|
+
interface BootstrapOptions<TStrategy extends AbstractStrategy<any, any, any, any, any, any>> {
|
|
66
|
+
strategy: TStrategy;
|
|
67
|
+
defaultValues: z.infer<ReturnType<TStrategy["getFormSchema"]>>;
|
|
68
|
+
disabled?: boolean;
|
|
69
|
+
validationMode?: "onChange" | "onSubmit";
|
|
70
|
+
/** Granted claims. Without it no claim is granted. */
|
|
71
|
+
claims?: ClaimsResolver<ClaimOf<TStrategy>, ActionOf<TStrategy>>;
|
|
72
|
+
}
|
|
73
|
+
/** Strategy constructor carrying user-defined static methods. */
|
|
74
|
+
type StrategyClass<TStrategy, TStatics = {}> = (new (...args: any[]) => TStrategy) & TStatics;
|
|
75
|
+
|
|
76
|
+
type SchemaOf<TStrategy extends AnyStrategy> = ReturnType<TStrategy["getFormSchema"]>;
|
|
77
|
+
type ValuesOf<TStrategy extends AnyStrategy> = z.infer<SchemaOf<TStrategy>>;
|
|
78
|
+
type StepOf<TStrategy extends AnyStrategy> = ReturnType<TStrategy["getSteps"]>[number];
|
|
79
|
+
type ClaimDecision<TStrategy extends AnyStrategy> = Partial<Record<ActionOf<TStrategy>, boolean>>;
|
|
80
|
+
type RhfMember = "setValue" | "getValues" | "resetField" | "trigger" | "unregister" | "reset" | "setError" | "clearErrors" | "handleSubmit";
|
|
81
|
+
type FormControlFacade = Pick<HeadlessFormControl<FieldValues>, RhfMember> & {
|
|
82
|
+
control: HeadlessFormControl<FieldValues>["formControl"];
|
|
83
|
+
options: {
|
|
84
|
+
mode: "onChange" | "onSubmit";
|
|
85
|
+
resolver: Resolver<FieldValues>;
|
|
86
|
+
};
|
|
87
|
+
};
|
|
88
|
+
type ReplaceStrategyOptions<TStrategy extends AnyStrategy> = {
|
|
89
|
+
claims?: BootstrapOptions<TStrategy>["claims"];
|
|
90
|
+
defaultValues?: DeepPartial<z.infer<ReturnType<TStrategy["getFormSchema"]>>>;
|
|
91
|
+
};
|
|
92
|
+
/** Owns one form: its react-hook-form control, current step, claims and listeners. One instance per form. */
|
|
93
|
+
declare class FormManager<TStrategy extends AnyStrategy = AnyStrategy> {
|
|
94
|
+
private strategy;
|
|
95
|
+
private bootstrapId;
|
|
96
|
+
private scopeId;
|
|
97
|
+
private revision;
|
|
98
|
+
private grants;
|
|
99
|
+
private claimsResolver;
|
|
100
|
+
private readonly claimsListeners;
|
|
101
|
+
private formStatus;
|
|
102
|
+
private currentStepIndex;
|
|
103
|
+
private currentStepValid;
|
|
104
|
+
private readonly stepsListeners;
|
|
105
|
+
private unsubscribeForm;
|
|
106
|
+
private headlessForm;
|
|
107
|
+
private resolverOptions;
|
|
108
|
+
/** Neutralizes (`z.any()`) the schema of denied steps so their default values survive submit. */
|
|
109
|
+
protected getResolverSchema(): ZodObject;
|
|
110
|
+
private isGranted;
|
|
111
|
+
/** Decision taken at bootstrap, stable until the form is rebuilt. Unknown claim or no form = no action. */
|
|
112
|
+
getClaim: (id: ClaimOf<TStrategy>) => ClaimDecision<TStrategy>;
|
|
113
|
+
subscribeClaims: (listener: () => void) => (() => void);
|
|
114
|
+
private notifyClaims;
|
|
115
|
+
private requireStrategy;
|
|
116
|
+
private requireForm;
|
|
117
|
+
private isCurrentStepValid;
|
|
118
|
+
private getVisibleSteps;
|
|
119
|
+
private buildCurrentStepInfo;
|
|
120
|
+
get steps(): StepState<StepOf<TStrategy>>[];
|
|
121
|
+
/**
|
|
122
|
+
* Thin access to the react-hook-form control. Everything here delegates to RHF;
|
|
123
|
+
* the rest of the class is the step logic. Throws before `bootstrap`.
|
|
124
|
+
*/
|
|
125
|
+
get form(): FormControlFacade;
|
|
126
|
+
getBootstrapId(): string | null;
|
|
127
|
+
/** The constructor of the strategy in use, typed with the statics declared via `StrategyClass`. */
|
|
128
|
+
getStrategyClass<TStatics = {}>(): StrategyClass<TStrategy, TStatics>;
|
|
129
|
+
validateStep(step: Step<any, any, any>): boolean;
|
|
130
|
+
getStepIssues(step: Step<any, any, any>): z.core.$ZodIssue[];
|
|
131
|
+
clearAll(removeListeners?: boolean): void;
|
|
132
|
+
/** Bootstraps the scope unless it is already the active one with the same `revision`: safe to call repeatedly. */
|
|
133
|
+
ensureScope(id: string, factory: () => BootstrapOptions<TStrategy>, revision?: string): void;
|
|
134
|
+
/** Clears only if the active scope is `id`: leaving a page must not wipe the form of the one just opened. */
|
|
135
|
+
clearScope(id: string): void;
|
|
136
|
+
resetFormManager(): void;
|
|
137
|
+
bootstrap({ strategy, ...options }: BootstrapOptions<TStrategy>): this;
|
|
138
|
+
private resolveGrants;
|
|
139
|
+
/**
|
|
140
|
+
* Swaps the strategy keeping the RHF control (values, dirty, touched), the listeners, the bootstrap id
|
|
141
|
+
* and the current step (matched by name). If that step no longer exists, falls back to the closest
|
|
142
|
+
* previous step that still exists, otherwise to the first one. Then revalidates the whole form.
|
|
143
|
+
* Claims: `options.claims` replaces the resolver; without it the current one is reused.
|
|
144
|
+
* `options.defaultValues` only fills top-level keys that are still `undefined` (e.g. steps new to the schema).
|
|
145
|
+
*/
|
|
146
|
+
replaceStrategy(strategy: TStrategy, options?: ReplaceStrategyOptions<TStrategy>): this;
|
|
147
|
+
getFormSchema(): SchemaOf<TStrategy>;
|
|
148
|
+
getFormStatus(): FormStatus | null;
|
|
149
|
+
getCurrentStepInfo: <TStep extends Step<any, any, any> = StepOf<TStrategy>>() => FormManagerSteps<TStep>;
|
|
150
|
+
recomputeCurrentStepValid(): boolean;
|
|
151
|
+
private callStepListeners;
|
|
152
|
+
subscribeCurrentStepData: (listener: FormManagerStepListener<any>) => (() => void);
|
|
153
|
+
isLastStep(): boolean;
|
|
154
|
+
getNextStep(): StepState<StepOf<TStrategy>> | null;
|
|
155
|
+
getPrevStep(): StepState<StepOf<TStrategy>> | null;
|
|
156
|
+
/** `false`: unknown step. `null`: already on that step. `true`: moved. */
|
|
157
|
+
goToStep(stepName: StepOf<TStrategy>["name"]): boolean | null;
|
|
158
|
+
/** Returns the new current step, or `null` when already on the last one. */
|
|
159
|
+
goNext(): StepState<StepOf<TStrategy>> | null;
|
|
160
|
+
/** Returns the new current step, or `null` when already on the first one. */
|
|
161
|
+
goPrev(): StepState<StepOf<TStrategy>> | null;
|
|
162
|
+
private moveToStep;
|
|
163
|
+
getStepIndexByName(stepName: StepOf<TStrategy>["name"]): number;
|
|
164
|
+
/** The manager does not interpret results: it forwards them to `onResult` each time the strategy reports. */
|
|
165
|
+
submit<TResult = SubmitResultOf<TStrategy>>(onResult?: (result: TResult) => void): Promise<void>;
|
|
166
|
+
mergeFormValues(data: DeepPartial<ValuesOf<TStrategy>>, shouldTrigger?: boolean): void;
|
|
167
|
+
setFieldError(fieldName: string, error: ErrorOption): void;
|
|
168
|
+
getFormValues(): ValuesOf<TStrategy>;
|
|
169
|
+
getStepFormData<T>(stepName: string): T;
|
|
170
|
+
getStrategyMetadata<T extends object>(): T;
|
|
171
|
+
getStrategy(): TStrategy;
|
|
172
|
+
patchMetadata<T extends FormManagerMetadata>(metadata: T): void;
|
|
173
|
+
updateMetadataAndResetFormFields<T extends FormManagerMetadata>(metadata: T, data?: {
|
|
174
|
+
values: DeepPartial<ValuesOf<TStrategy>>;
|
|
175
|
+
options?: KeepStateOptions;
|
|
176
|
+
}): void;
|
|
177
|
+
hasCompletedBootstrap(): boolean;
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
interface FormControlContext<TValues extends FieldValues = FieldValues> {
|
|
181
|
+
setValue: UseFormSetValue<TValues>;
|
|
182
|
+
setError: UseFormSetError<TValues>;
|
|
183
|
+
trigger: UseFormTrigger<TValues>;
|
|
184
|
+
control: Control<TValues, unknown, TValues>;
|
|
185
|
+
}
|
|
186
|
+
type FormManagerProviderProps = Readonly<{
|
|
187
|
+
manager: FormManager<any>;
|
|
188
|
+
methods?: never;
|
|
189
|
+
children: ReactNode;
|
|
190
|
+
}> | Readonly<{
|
|
191
|
+
methods: UseFormReturn<any>;
|
|
192
|
+
manager?: never;
|
|
193
|
+
children: ReactNode;
|
|
194
|
+
}>;
|
|
195
|
+
/**
|
|
196
|
+
* Provides a form to the tree. `manager` (multi-step, must be bootstrapped) or `methods` (single page, from `useForm`).
|
|
197
|
+
*/
|
|
198
|
+
declare function FormManagerProvider(props: FormManagerProviderProps): react.JSX.Element;
|
|
199
|
+
/** The manager of the closest provider. Throws outside a provider or in single page mode. */
|
|
200
|
+
declare function useFormManager<TStrategy extends AnyStrategy = AnyStrategy>(): FormManager<TStrategy>;
|
|
201
|
+
declare function useFormControl<TValues extends FieldValues = FieldValues>(): FormControlContext<TValues>;
|
|
202
|
+
/** Steps and current step of the manager, with a stable snapshot while nothing relevant changes. */
|
|
203
|
+
declare function useFormSteps<TStep extends Step<any, any, any> = Step>(): FormManagerSteps<TStep>;
|
|
204
|
+
/** Actions granted on a claim, as decided at bootstrap. Without a bootstrapped form nothing is granted. */
|
|
205
|
+
declare function useFormClaims<TStrategy extends AnyStrategy = AnyStrategy>(id: ClaimOf<TStrategy>): Partial<Record<ActionOf<TStrategy>, boolean>>;
|
|
206
|
+
|
|
207
|
+
interface StepFormProps {
|
|
208
|
+
name: string;
|
|
209
|
+
id?: string;
|
|
210
|
+
children: ReactNode;
|
|
211
|
+
style?: CSSProperties;
|
|
212
|
+
onSubmit?: () => void;
|
|
213
|
+
}
|
|
214
|
+
declare function StepForm({ name, id, children, style, onSubmit }: Readonly<StepFormProps>): react.JSX.Element;
|
|
215
|
+
|
|
216
|
+
export { AbstractStrategy, FormManager, FormManagerProvider, StepForm, useFormClaims, useFormControl, useFormManager, useFormSteps };
|
|
217
|
+
export type { ActionOf, BootstrapOptions, ClaimOf, ClaimsResolver, FormControlContext, FormControlFacade, FormManagerMetadata, FormManagerProviderProps, FormManagerSteps, FormStatus, ReplaceStrategyOptions, Step, StepFormProps, StrategyClass, SubmitResultOf };
|