@xemahq/ui-kernel 0.6.1 → 0.7.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/dist/index.d.ts +1 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +1 -0
- package/dist/index.js.map +1 -1
- package/dist/ui/capture/document-preview.d.ts +12 -0
- package/dist/ui/capture/document-preview.d.ts.map +1 -0
- package/dist/ui/capture/document-preview.js +31 -0
- package/dist/ui/capture/document-preview.js.map +1 -0
- package/dist/ui/capture/field-spec-to-zod.d.ts +5 -0
- package/dist/ui/capture/field-spec-to-zod.d.ts.map +1 -0
- package/dist/ui/capture/field-spec-to-zod.js +71 -0
- package/dist/ui/capture/field-spec-to-zod.js.map +1 -0
- package/dist/ui/capture/field-spec.d.ts +49 -0
- package/dist/ui/capture/field-spec.d.ts.map +1 -0
- package/dist/ui/capture/field-spec.js +59 -0
- package/dist/ui/capture/field-spec.js.map +1 -0
- package/dist/ui/capture/index.d.ts +11 -0
- package/dist/ui/capture/index.d.ts.map +1 -0
- package/dist/ui/capture/index.js +31 -0
- package/dist/ui/capture/index.js.map +1 -0
- package/dist/ui/capture/schema-field-input.d.ts +20 -0
- package/dist/ui/capture/schema-field-input.d.ts.map +1 -0
- package/dist/ui/capture/schema-field-input.js +64 -0
- package/dist/ui/capture/schema-field-input.js.map +1 -0
- package/dist/ui/capture/schema-form.d.ts +18 -0
- package/dist/ui/capture/schema-form.d.ts.map +1 -0
- package/dist/ui/capture/schema-form.js +26 -0
- package/dist/ui/capture/schema-form.js.map +1 -0
- package/dist/ui/capture/use-prefill.d.ts +18 -0
- package/dist/ui/capture/use-prefill.d.ts.map +1 -0
- package/dist/ui/capture/use-prefill.js +94 -0
- package/dist/ui/capture/use-prefill.js.map +1 -0
- package/dist/ui/capture/use-schema-validation.d.ts +11 -0
- package/dist/ui/capture/use-schema-validation.d.ts.map +1 -0
- package/dist/ui/capture/use-schema-validation.js +69 -0
- package/dist/ui/capture/use-schema-validation.js.map +1 -0
- package/dist/ui/capture/use-wizard.d.ts +28 -0
- package/dist/ui/capture/use-wizard.d.ts.map +1 -0
- package/dist/ui/capture/use-wizard.js +63 -0
- package/dist/ui/capture/use-wizard.js.map +1 -0
- package/dist/ui/capture/value-format.d.ts +4 -0
- package/dist/ui/capture/value-format.d.ts.map +1 -0
- package/dist/ui/capture/value-format.js +23 -0
- package/dist/ui/capture/value-format.js.map +1 -0
- package/dist/ui/capture/wizard.d.ts +19 -0
- package/dist/ui/capture/wizard.d.ts.map +1 -0
- package/dist/ui/capture/wizard.js +34 -0
- package/dist/ui/capture/wizard.js.map +1 -0
- package/dist/ui/index.d.ts +1 -0
- package/dist/ui/index.d.ts.map +1 -1
- package/dist/ui/index.js +1 -0
- package/dist/ui/index.js.map +1 -1
- package/dist/ui/primitives/badge.d.ts +1 -1
- package/dist/ui/primitives/button.d.ts +1 -1
- package/dist/ui/primitives/sheet.d.ts +1 -1
- package/package.json +4 -3
- package/src/index.ts +5 -0
- package/src/ui/capture/document-preview.tsx +101 -0
- package/src/ui/capture/field-spec-to-zod.test.ts +59 -0
- package/src/ui/capture/field-spec-to-zod.ts +93 -0
- package/src/ui/capture/field-spec.test.ts +49 -0
- package/src/ui/capture/field-spec.ts +160 -0
- package/src/ui/capture/index.ts +43 -0
- package/src/ui/capture/schema-field-input.tsx +186 -0
- package/src/ui/capture/schema-form.tsx +108 -0
- package/src/ui/capture/use-prefill.ts +150 -0
- package/src/ui/capture/use-schema-validation.ts +113 -0
- package/src/ui/capture/use-wizard.ts +134 -0
- package/src/ui/capture/value-format.ts +22 -0
- package/src/ui/capture/wizard.tsx +100 -0
- package/src/ui/index.ts +3 -0
|
@@ -0,0 +1,108 @@
|
|
|
1
|
+
// ═══════════════════════════════════════════════════════════════════════════
|
|
2
|
+
// <SchemaForm> — the ONE kernel schema→form renderer
|
|
3
|
+
//
|
|
4
|
+
// Consolidates the three parallel schema→form implementations (app-forge-web's
|
|
5
|
+
// RecordForm/FieldInput, the pipelines with-schema-form, the rjsf install
|
|
6
|
+
// wizard) into a single reusable primitive. Give it a flat `fields` list OR
|
|
7
|
+
// titled `sections`; it renders one typed input per field (10 scalar types +
|
|
8
|
+
// nested `object` + repeatable `list`), inline per-field errors, and an "AI
|
|
9
|
+
// suggested" badge for machine-prefilled fields.
|
|
10
|
+
//
|
|
11
|
+
// Controlled: owns no value state — `values` in, `onChange` out. Pair it with
|
|
12
|
+
// `useSchemaValidation` for live errors and `usePrefill` for suggestions.
|
|
13
|
+
// ═══════════════════════════════════════════════════════════════════════════
|
|
14
|
+
import { Sparkles } from 'lucide-react';
|
|
15
|
+
import { type ReactNode } from 'react';
|
|
16
|
+
|
|
17
|
+
import { cn } from '../cn';
|
|
18
|
+
import { Badge } from '../primitives/badge';
|
|
19
|
+
import { Label } from '../primitives/label';
|
|
20
|
+
|
|
21
|
+
import { type CaptureFieldSpec, type CaptureSchema, type CaptureSection, type CaptureValues, toSections } from './field-spec';
|
|
22
|
+
import { SchemaFieldInput, type RenderReference } from './schema-field-input';
|
|
23
|
+
|
|
24
|
+
export interface SchemaFormProps {
|
|
25
|
+
/** Flat schema. Mutually exclusive with `sections`. */
|
|
26
|
+
readonly fields?: readonly CaptureFieldSpec[];
|
|
27
|
+
/** Sectioned schema. Mutually exclusive with `fields`. */
|
|
28
|
+
readonly sections?: readonly CaptureSection[];
|
|
29
|
+
/** Pre-built schema object (either face). Lowest precedence. */
|
|
30
|
+
readonly schema?: CaptureSchema;
|
|
31
|
+
readonly values: CaptureValues;
|
|
32
|
+
readonly onChange: (values: CaptureValues) => void;
|
|
33
|
+
/** Per-field errors keyed by dot-path (from `useSchemaValidation` / server). */
|
|
34
|
+
readonly errors?: Readonly<Record<string, string>>;
|
|
35
|
+
/** Field keys to badge as machine-suggested (from `usePrefill`). */
|
|
36
|
+
readonly suggestedKeys?: ReadonlySet<string> | readonly string[];
|
|
37
|
+
readonly disabled?: boolean;
|
|
38
|
+
/** Inject a record-backed picker for `reference` fields. */
|
|
39
|
+
readonly renderReference?: RenderReference;
|
|
40
|
+
/** Show section titles (default true when a section has a title). */
|
|
41
|
+
readonly className?: string;
|
|
42
|
+
/** Optional slot rendered after the fields (e.g. a submit bar). */
|
|
43
|
+
readonly footer?: ReactNode;
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
function toSet(keys: SchemaFormProps['suggestedKeys']): ReadonlySet<string> {
|
|
47
|
+
if (!keys) return new Set();
|
|
48
|
+
return keys instanceof Set ? keys : new Set(keys as readonly string[]);
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
/**
|
|
52
|
+
* @example
|
|
53
|
+
* const [values, setValues] = useState({});
|
|
54
|
+
* const { errors } = useSchemaValidation(fields, values);
|
|
55
|
+
* <SchemaForm fields={fields} values={values} onChange={setValues} errors={errors} />
|
|
56
|
+
*/
|
|
57
|
+
export function SchemaForm({ fields, sections, schema, values, onChange, errors, suggestedKeys, disabled, renderReference, className, footer }: SchemaFormProps) {
|
|
58
|
+
const resolved: readonly CaptureSection[] = toSections(sections ?? (fields ? fields : schema) ?? []);
|
|
59
|
+
const suggested = toSet(suggestedKeys);
|
|
60
|
+
|
|
61
|
+
const setField = (key: string, value: unknown) => onChange({ ...values, [key]: value });
|
|
62
|
+
|
|
63
|
+
return (
|
|
64
|
+
<div className={cn('space-y-6', className)}>
|
|
65
|
+
{resolved.map((section) => (
|
|
66
|
+
<fieldset key={section.key} className="space-y-3 border-0 p-0" disabled={disabled}>
|
|
67
|
+
{section.title ? (
|
|
68
|
+
<legend className="mb-1 text-subtitle font-semibold text-ink">
|
|
69
|
+
{section.title}
|
|
70
|
+
{section.description ? <span className="mt-0.5 block text-caption font-normal text-ink-3">{section.description}</span> : null}
|
|
71
|
+
</legend>
|
|
72
|
+
) : null}
|
|
73
|
+
{section.fields.map((field) => {
|
|
74
|
+
const error = errors?.[field.key];
|
|
75
|
+
const isSuggested = suggested.has(field.key);
|
|
76
|
+
return (
|
|
77
|
+
<div key={field.key}>
|
|
78
|
+
<div className="flex items-center gap-2">
|
|
79
|
+
<Label htmlFor={`field-${field.key}`}>
|
|
80
|
+
{field.label}
|
|
81
|
+
{field.required ? <span className="text-destructive"> *</span> : null}
|
|
82
|
+
</Label>
|
|
83
|
+
{isSuggested ? (
|
|
84
|
+
<Badge variant="outline" className="gap-1 border-primary/30 bg-primary/10 px-1.5 py-0 text-caption text-primary">
|
|
85
|
+
<Sparkles className="h-3 w-3" /> AI suggested
|
|
86
|
+
</Badge>
|
|
87
|
+
) : null}
|
|
88
|
+
</div>
|
|
89
|
+
{field.description ? <p className="mb-1 text-caption text-ink-3">{field.description}</p> : null}
|
|
90
|
+
<SchemaFieldInput
|
|
91
|
+
field={field}
|
|
92
|
+
value={values[field.key]}
|
|
93
|
+
onChange={(v) => setField(field.key, v)}
|
|
94
|
+
disabled={disabled}
|
|
95
|
+
path={field.key}
|
|
96
|
+
errors={errors}
|
|
97
|
+
renderReference={renderReference}
|
|
98
|
+
/>
|
|
99
|
+
{error ? <p className="mt-1 text-caption text-destructive">{error}</p> : null}
|
|
100
|
+
</div>
|
|
101
|
+
);
|
|
102
|
+
})}
|
|
103
|
+
</fieldset>
|
|
104
|
+
))}
|
|
105
|
+
{footer}
|
|
106
|
+
</div>
|
|
107
|
+
);
|
|
108
|
+
}
|
|
@@ -0,0 +1,150 @@
|
|
|
1
|
+
// ═══════════════════════════════════════════════════════════════════════════
|
|
2
|
+
// usePrefill — field-level pre-fill from an async, source-agnostic default
|
|
3
|
+
// source (AI, prior-context, a template service — the caller supplies it).
|
|
4
|
+
//
|
|
5
|
+
// It populates initial field values WITHOUT clobbering user edits, and tracks
|
|
6
|
+
// which fields were machine-suggested so the UI can badge them. A field the
|
|
7
|
+
// user has touched is never overwritten by a (re)load, and reading a field back
|
|
8
|
+
// after the user edits it clears its "suggested" mark.
|
|
9
|
+
// ═══════════════════════════════════════════════════════════════════════════
|
|
10
|
+
import { useCallback, useEffect, useRef, useState } from 'react';
|
|
11
|
+
|
|
12
|
+
import type { CaptureValues } from './field-spec';
|
|
13
|
+
|
|
14
|
+
export interface UsePrefillOptions<T extends CaptureValues = CaptureValues> {
|
|
15
|
+
/**
|
|
16
|
+
* Async source of default values keyed by field key. Called on mount (unless
|
|
17
|
+
* `enabled` is false) and on `reload()`. May return a partial record — only
|
|
18
|
+
* the keys it returns are considered suggestions.
|
|
19
|
+
*/
|
|
20
|
+
readonly fetchDefaults: () => Promise<Partial<T>>;
|
|
21
|
+
/** Seed values (e.g. an edit form's existing record). Never treated as suggested. */
|
|
22
|
+
readonly initialValues?: T;
|
|
23
|
+
/** Gate the initial fetch (default true). */
|
|
24
|
+
readonly enabled?: boolean;
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
export interface UsePrefillResult<T extends CaptureValues = CaptureValues> {
|
|
28
|
+
readonly values: T;
|
|
29
|
+
/** Set one field (a user edit) — clears its suggested mark. */
|
|
30
|
+
readonly setValue: (key: string, value: unknown) => void;
|
|
31
|
+
/** Replace/patch values (a user edit) — clears suggested marks for changed keys. */
|
|
32
|
+
readonly setValues: (updater: Partial<T> | ((prev: T) => T)) => void;
|
|
33
|
+
/** Keys populated by the default source and NOT yet edited by the user. */
|
|
34
|
+
readonly suggestedKeys: ReadonlySet<string>;
|
|
35
|
+
readonly isSuggested: (key: string) => boolean;
|
|
36
|
+
readonly loading: boolean;
|
|
37
|
+
readonly error: unknown;
|
|
38
|
+
/** Re-run `fetchDefaults`; still respects user-touched keys. */
|
|
39
|
+
readonly reload: () => void;
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
/**
|
|
43
|
+
* @example
|
|
44
|
+
* const prefill = usePrefill({
|
|
45
|
+
* fetchDefaults: () => api.suggestDefaults(contextId), // → { title: 'Draft', owner: 'me' }
|
|
46
|
+
* initialValues: { title: '', owner: '' },
|
|
47
|
+
* });
|
|
48
|
+
* <SchemaForm
|
|
49
|
+
* fields={fields}
|
|
50
|
+
* values={prefill.values}
|
|
51
|
+
* onChange={prefill.setValues}
|
|
52
|
+
* suggestedKeys={prefill.suggestedKeys} // renders an "AI suggested" badge
|
|
53
|
+
* />
|
|
54
|
+
*/
|
|
55
|
+
export function usePrefill<T extends CaptureValues = CaptureValues>(
|
|
56
|
+
options: UsePrefillOptions<T>,
|
|
57
|
+
): UsePrefillResult<T> {
|
|
58
|
+
const { fetchDefaults, initialValues, enabled = true } = options;
|
|
59
|
+
|
|
60
|
+
const [values, setValuesState] = useState<T>(() => ({ ...(initialValues ?? ({} as T)) }));
|
|
61
|
+
const [suggested, setSuggested] = useState<ReadonlySet<string>>(() => new Set());
|
|
62
|
+
const [loading, setLoading] = useState(false);
|
|
63
|
+
const [error, setError] = useState<unknown>(null);
|
|
64
|
+
|
|
65
|
+
// Keys the user has explicitly touched — a (re)load must never clobber these.
|
|
66
|
+
const touched = useRef<Set<string>>(new Set());
|
|
67
|
+
// Monotonic request id guards against a stale fetch resolving after a newer
|
|
68
|
+
// one (or after user edits) — no timeout-based races.
|
|
69
|
+
const requestId = useRef(0);
|
|
70
|
+
|
|
71
|
+
const setValue = useCallback((key: string, value: unknown) => {
|
|
72
|
+
touched.current.add(key);
|
|
73
|
+
setValuesState((prev) => ({ ...prev, [key]: value }));
|
|
74
|
+
setSuggested((prev) => {
|
|
75
|
+
if (!prev.has(key)) return prev;
|
|
76
|
+
const next = new Set(prev);
|
|
77
|
+
next.delete(key);
|
|
78
|
+
return next;
|
|
79
|
+
});
|
|
80
|
+
}, []);
|
|
81
|
+
|
|
82
|
+
const setValues = useCallback((updater: Partial<T> | ((prev: T) => T)) => {
|
|
83
|
+
setValuesState((prev) => {
|
|
84
|
+
const next = typeof updater === 'function' ? (updater as (p: T) => T)(prev) : { ...prev, ...updater };
|
|
85
|
+
const changed = new Set<string>();
|
|
86
|
+
for (const k of Object.keys(next)) {
|
|
87
|
+
if (next[k] !== prev[k]) {
|
|
88
|
+
touched.current.add(k);
|
|
89
|
+
changed.add(k);
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
if (changed.size > 0) {
|
|
93
|
+
setSuggested((prevSug) => {
|
|
94
|
+
if (![...changed].some((k) => prevSug.has(k))) return prevSug;
|
|
95
|
+
const n = new Set(prevSug);
|
|
96
|
+
for (const k of changed) n.delete(k);
|
|
97
|
+
return n;
|
|
98
|
+
});
|
|
99
|
+
}
|
|
100
|
+
return next;
|
|
101
|
+
});
|
|
102
|
+
}, []);
|
|
103
|
+
|
|
104
|
+
const run = useCallback(() => {
|
|
105
|
+
const id = ++requestId.current;
|
|
106
|
+
setLoading(true);
|
|
107
|
+
setError(null);
|
|
108
|
+
void fetchDefaults()
|
|
109
|
+
.then((defaults) => {
|
|
110
|
+
if (id !== requestId.current) return; // superseded — drop
|
|
111
|
+
const applied: string[] = [];
|
|
112
|
+
setValuesState((prev) => {
|
|
113
|
+
const next = { ...prev };
|
|
114
|
+
for (const [key, value] of Object.entries(defaults)) {
|
|
115
|
+
// Only fill keys the user hasn't touched and that are still empty.
|
|
116
|
+
const current = prev[key];
|
|
117
|
+
const isEmpty = current === undefined || current === null || current === '';
|
|
118
|
+
if (!touched.current.has(key) && isEmpty && value !== undefined) {
|
|
119
|
+
(next as CaptureValues)[key] = value;
|
|
120
|
+
applied.push(key);
|
|
121
|
+
}
|
|
122
|
+
}
|
|
123
|
+
return next;
|
|
124
|
+
});
|
|
125
|
+
setSuggested((prev) => {
|
|
126
|
+
if (applied.length === 0) return prev;
|
|
127
|
+
const n = new Set(prev);
|
|
128
|
+
for (const k of applied) n.add(k);
|
|
129
|
+
return n;
|
|
130
|
+
});
|
|
131
|
+
})
|
|
132
|
+
.catch((e: unknown) => {
|
|
133
|
+
if (id !== requestId.current) return;
|
|
134
|
+
setError(e);
|
|
135
|
+
})
|
|
136
|
+
.finally(() => {
|
|
137
|
+
if (id === requestId.current) setLoading(false);
|
|
138
|
+
});
|
|
139
|
+
}, [fetchDefaults]);
|
|
140
|
+
|
|
141
|
+
useEffect(() => {
|
|
142
|
+
if (enabled) run();
|
|
143
|
+
// Run once on mount / when re-enabled; `reload()` is the explicit re-fetch.
|
|
144
|
+
// eslint-disable-next-line react-hooks/exhaustive-deps
|
|
145
|
+
}, [enabled]);
|
|
146
|
+
|
|
147
|
+
const isSuggested = useCallback((key: string) => suggested.has(key), [suggested]);
|
|
148
|
+
|
|
149
|
+
return { values, setValue, setValues, suggestedKeys: suggested, isSuggested, loading, error, reload: run };
|
|
150
|
+
}
|
|
@@ -0,0 +1,113 @@
|
|
|
1
|
+
// ═══════════════════════════════════════════════════════════════════════════
|
|
2
|
+
// useSchemaValidation — client-side validation + "missing info" sweep
|
|
3
|
+
//
|
|
4
|
+
// Runs BEFORE any server round-trip, on every change/blur. Accepts either a
|
|
5
|
+
// hand-written `zod` schema OR a `CaptureFieldSpec[]` / `CaptureSection[]` /
|
|
6
|
+
// `CaptureSchema` (auto-adapted via `fieldSpecToZod`). Returns per-field errors
|
|
7
|
+
// keyed by dot-path plus a deterministic `missingRequired` list so a guided UX
|
|
8
|
+
// can nudge "you still need to fill X" without waiting for a 422.
|
|
9
|
+
// ═══════════════════════════════════════════════════════════════════════════
|
|
10
|
+
import { useMemo } from 'react';
|
|
11
|
+
import { z } from 'zod';
|
|
12
|
+
|
|
13
|
+
import { CaptureFieldType, type CaptureFieldSpec, type CaptureSchema, type CaptureSection, type CaptureValues, toFieldList } from './field-spec';
|
|
14
|
+
import { fieldSpecToZod, isEmptyValue } from './field-spec-to-zod';
|
|
15
|
+
|
|
16
|
+
export interface SchemaValidationResult {
|
|
17
|
+
/** First error per field, keyed by dot-path (`tags.0.name`, `address.city`). */
|
|
18
|
+
readonly errors: Readonly<Record<string, string>>;
|
|
19
|
+
/** Dot-paths of required fields still empty — the "missing info" sweep. */
|
|
20
|
+
readonly missingRequired: readonly string[];
|
|
21
|
+
/** True when there are no errors AND nothing required is missing. */
|
|
22
|
+
readonly isValid: boolean;
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
type ValidationInput =
|
|
26
|
+
| z.ZodType
|
|
27
|
+
| CaptureSchema
|
|
28
|
+
| readonly CaptureFieldSpec[]
|
|
29
|
+
| readonly CaptureSection[];
|
|
30
|
+
|
|
31
|
+
function isZodSchema(input: ValidationInput): input is z.ZodType {
|
|
32
|
+
return typeof (input as z.ZodType)?.safeParse === 'function';
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
/** Deterministic required sweep over the flat spec list (nested-aware). */
|
|
36
|
+
function sweepMissing(fields: readonly CaptureFieldSpec[], values: CaptureValues, prefix = ''): string[] {
|
|
37
|
+
const missing: string[] = [];
|
|
38
|
+
for (const field of fields) {
|
|
39
|
+
const path = prefix ? `${prefix}.${field.key}` : field.key;
|
|
40
|
+
const value = values?.[field.key];
|
|
41
|
+
if (field.type === CaptureFieldType.Object) {
|
|
42
|
+
if (field.required && isEmptyValue(value)) missing.push(path);
|
|
43
|
+
if (value && typeof value === 'object' && !Array.isArray(value)) {
|
|
44
|
+
missing.push(...sweepMissing(field.fields ?? [], value as CaptureValues, path));
|
|
45
|
+
}
|
|
46
|
+
continue;
|
|
47
|
+
}
|
|
48
|
+
if (field.type === CaptureFieldType.List) {
|
|
49
|
+
if (field.required && isEmptyValue(value)) missing.push(path);
|
|
50
|
+
if (Array.isArray(value)) {
|
|
51
|
+
value.forEach((item, i) => {
|
|
52
|
+
if (item && typeof item === 'object') {
|
|
53
|
+
missing.push(...sweepMissing(field.fields ?? [], item as CaptureValues, `${path}.${i}`));
|
|
54
|
+
}
|
|
55
|
+
});
|
|
56
|
+
}
|
|
57
|
+
continue;
|
|
58
|
+
}
|
|
59
|
+
if (field.required && isEmptyValue(value)) missing.push(path);
|
|
60
|
+
}
|
|
61
|
+
return missing;
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
/**
|
|
65
|
+
* @example
|
|
66
|
+
* const { errors, missingRequired, isValid } = useSchemaValidation(fields, values);
|
|
67
|
+
* // live under each input:
|
|
68
|
+
* errors['email'] // → 'Email must be a valid address' | undefined
|
|
69
|
+
* missingRequired // → ['email', 'address.city']
|
|
70
|
+
* // gate a wizard step / submit button:
|
|
71
|
+
* <Button disabled={!isValid}>Continue</Button>
|
|
72
|
+
*/
|
|
73
|
+
export function useSchemaValidation(input: ValidationInput, values: CaptureValues): SchemaValidationResult {
|
|
74
|
+
// Field specs (when supplied) drive the deterministic required sweep and the
|
|
75
|
+
// auto-adapted zod schema; a raw zod schema is used as-is.
|
|
76
|
+
const fields = useMemo<readonly CaptureFieldSpec[] | null>(
|
|
77
|
+
() => (isZodSchema(input) ? null : toFieldList(input)),
|
|
78
|
+
[input],
|
|
79
|
+
);
|
|
80
|
+
const schema = useMemo<z.ZodType>(
|
|
81
|
+
() => (isZodSchema(input) ? input : fieldSpecToZod(input)),
|
|
82
|
+
[input],
|
|
83
|
+
);
|
|
84
|
+
|
|
85
|
+
return useMemo<SchemaValidationResult>(() => {
|
|
86
|
+
const errors: Record<string, string> = {};
|
|
87
|
+
const result = schema.safeParse(values);
|
|
88
|
+
if (!result.success) {
|
|
89
|
+
for (const issue of result.error.issues) {
|
|
90
|
+
const path = issue.path.map(String).join('.');
|
|
91
|
+
// First error per path wins (deterministic, matches display order).
|
|
92
|
+
if (!(path in errors)) errors[path] = issue.message;
|
|
93
|
+
}
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
// Deterministic sweep when we have specs; otherwise derive "missing" from
|
|
97
|
+
// zod issues that fired on an empty value (so a bare zod schema still works).
|
|
98
|
+
const missingRequired = fields
|
|
99
|
+
? sweepMissing(fields, values)
|
|
100
|
+
: Object.keys(errors).filter((path) => {
|
|
101
|
+
const segments = path.split('.');
|
|
102
|
+
let cur: unknown = values;
|
|
103
|
+
for (const seg of segments) cur = (cur as CaptureValues | undefined)?.[seg];
|
|
104
|
+
return isEmptyValue(cur);
|
|
105
|
+
});
|
|
106
|
+
|
|
107
|
+
return {
|
|
108
|
+
errors,
|
|
109
|
+
missingRequired,
|
|
110
|
+
isValid: Object.keys(errors).length === 0 && missingRequired.length === 0,
|
|
111
|
+
};
|
|
112
|
+
}, [schema, fields, values]);
|
|
113
|
+
}
|
|
@@ -0,0 +1,134 @@
|
|
|
1
|
+
// ═══════════════════════════════════════════════════════════════════════════
|
|
2
|
+
// useWizard — headless multi-step engine
|
|
3
|
+
//
|
|
4
|
+
// The state machine the hand-rolled wizards lack: step index, next/prev, goTo,
|
|
5
|
+
// isFirst/isLast, per-step advance gating, and a `status(i)` that maps 1:1 onto
|
|
6
|
+
// the presentational `FormStepper`'s `FormStepStatus`. Controlled (pass `step`)
|
|
7
|
+
// and uncontrolled (pass `initialStep`) modes. No timers, no side effects.
|
|
8
|
+
// ═══════════════════════════════════════════════════════════════════════════
|
|
9
|
+
import { useCallback, useMemo, useState } from 'react';
|
|
10
|
+
|
|
11
|
+
import { FormStepStatus } from '../primitives/form-stepper';
|
|
12
|
+
|
|
13
|
+
export interface WizardStepDef {
|
|
14
|
+
readonly key: string;
|
|
15
|
+
readonly label: string;
|
|
16
|
+
readonly hint?: string;
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
export interface UseWizardOptions {
|
|
20
|
+
readonly steps: readonly WizardStepDef[];
|
|
21
|
+
/**
|
|
22
|
+
* Per-step forward gate. `canAdvance(i)` must return true before the wizard
|
|
23
|
+
* will move PAST step `i`. Backward navigation is always allowed. Defaults to
|
|
24
|
+
* always-advanceable.
|
|
25
|
+
*/
|
|
26
|
+
readonly canAdvance?: (index: number) => boolean;
|
|
27
|
+
/** Uncontrolled initial index (default 0). Ignored when `step` is provided. */
|
|
28
|
+
readonly initialStep?: number;
|
|
29
|
+
/** Controlled active index. When set, the hook is controlled. */
|
|
30
|
+
readonly step?: number;
|
|
31
|
+
/** Fired on every requested index change (both modes). */
|
|
32
|
+
readonly onStepChange?: (index: number) => void;
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
export interface WizardApi {
|
|
36
|
+
readonly steps: readonly WizardStepDef[];
|
|
37
|
+
readonly activeIndex: number;
|
|
38
|
+
readonly activeStep: WizardStepDef;
|
|
39
|
+
readonly isFirst: boolean;
|
|
40
|
+
readonly isLast: boolean;
|
|
41
|
+
/** Whether the CURRENT step's forward gate is satisfied. */
|
|
42
|
+
readonly canAdvance: boolean;
|
|
43
|
+
/** 0..1 progress across the steps. */
|
|
44
|
+
readonly progress: number;
|
|
45
|
+
readonly next: () => void;
|
|
46
|
+
readonly prev: () => void;
|
|
47
|
+
/** Jump to `index`. Backward is free; forward requires every intervening gate. */
|
|
48
|
+
readonly goTo: (index: number) => void;
|
|
49
|
+
/** {@link FormStepStatus} for step `index` — feeds `<FormStepper>`. */
|
|
50
|
+
readonly status: (index: number) => FormStepStatus;
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
/**
|
|
54
|
+
* @example
|
|
55
|
+
* const wizard = useWizard({
|
|
56
|
+
* steps: [{ key: 'details', label: 'Details' }, { key: 'review', label: 'Review' }],
|
|
57
|
+
* canAdvance: (i) => (i === 0 ? isValid : true),
|
|
58
|
+
* });
|
|
59
|
+
* <Wizard api={wizard} onFinish={submit}>
|
|
60
|
+
* <WizardStep stepKey="details"><SchemaForm … /></WizardStep>
|
|
61
|
+
* <WizardStep stepKey="review"><DocumentPreview … /></WizardStep>
|
|
62
|
+
* </Wizard>
|
|
63
|
+
*/
|
|
64
|
+
export function useWizard(options: UseWizardOptions): WizardApi {
|
|
65
|
+
const { steps, canAdvance, initialStep = 0, step, onStepChange } = options;
|
|
66
|
+
const count = steps.length;
|
|
67
|
+
const clamp = useCallback((i: number) => Math.max(0, Math.min(count - 1, i)), [count]);
|
|
68
|
+
|
|
69
|
+
const isControlled = step !== undefined;
|
|
70
|
+
const [internal, setInternal] = useState(() => clamp(initialStep));
|
|
71
|
+
const activeIndex = clamp(isControlled ? (step as number) : internal);
|
|
72
|
+
|
|
73
|
+
const gate = useCallback((i: number) => (canAdvance ? canAdvance(i) : true), [canAdvance]);
|
|
74
|
+
|
|
75
|
+
const request = useCallback(
|
|
76
|
+
(target: number) => {
|
|
77
|
+
const next = clamp(target);
|
|
78
|
+
if (next === activeIndex) return;
|
|
79
|
+
onStepChange?.(next);
|
|
80
|
+
if (!isControlled) setInternal(next);
|
|
81
|
+
},
|
|
82
|
+
[activeIndex, clamp, isControlled, onStepChange],
|
|
83
|
+
);
|
|
84
|
+
|
|
85
|
+
const goTo = useCallback(
|
|
86
|
+
(index: number) => {
|
|
87
|
+
const target = clamp(index);
|
|
88
|
+
if (target <= activeIndex) {
|
|
89
|
+
request(target); // backward is always allowed
|
|
90
|
+
return;
|
|
91
|
+
}
|
|
92
|
+
// Forward: every step from active..target-1 must pass its gate.
|
|
93
|
+
for (let i = activeIndex; i < target; i += 1) {
|
|
94
|
+
if (!gate(i)) return;
|
|
95
|
+
}
|
|
96
|
+
request(target);
|
|
97
|
+
},
|
|
98
|
+
[activeIndex, clamp, gate, request],
|
|
99
|
+
);
|
|
100
|
+
|
|
101
|
+
const next = useCallback(() => {
|
|
102
|
+
if (activeIndex >= count - 1) return;
|
|
103
|
+
if (!gate(activeIndex)) return;
|
|
104
|
+
request(activeIndex + 1);
|
|
105
|
+
}, [activeIndex, count, gate, request]);
|
|
106
|
+
|
|
107
|
+
const prev = useCallback(() => request(activeIndex - 1), [activeIndex, request]);
|
|
108
|
+
|
|
109
|
+
const status = useCallback(
|
|
110
|
+
(index: number): FormStepStatus => {
|
|
111
|
+
if (index < activeIndex) return FormStepStatus.DONE;
|
|
112
|
+
if (index === activeIndex) return FormStepStatus.ACTIVE;
|
|
113
|
+
return FormStepStatus.PENDING;
|
|
114
|
+
},
|
|
115
|
+
[activeIndex],
|
|
116
|
+
);
|
|
117
|
+
|
|
118
|
+
return useMemo<WizardApi>(
|
|
119
|
+
() => ({
|
|
120
|
+
steps,
|
|
121
|
+
activeIndex,
|
|
122
|
+
activeStep: steps[activeIndex],
|
|
123
|
+
isFirst: activeIndex === 0,
|
|
124
|
+
isLast: activeIndex === count - 1,
|
|
125
|
+
canAdvance: gate(activeIndex),
|
|
126
|
+
progress: count <= 1 ? 1 : activeIndex / (count - 1),
|
|
127
|
+
next,
|
|
128
|
+
prev,
|
|
129
|
+
goTo,
|
|
130
|
+
status,
|
|
131
|
+
}),
|
|
132
|
+
[steps, activeIndex, count, gate, next, prev, goTo, status],
|
|
133
|
+
);
|
|
134
|
+
}
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
// Shared value coercion/formatting for the capture kit — used by the input
|
|
2
|
+
// boundary (SchemaForm) and the read-only view (DocumentPreview) so the two
|
|
3
|
+
// never disagree on how a stored value maps to its display/edit string.
|
|
4
|
+
import { CaptureFieldType, type CaptureFieldSpec } from './field-spec';
|
|
5
|
+
|
|
6
|
+
/** Coerce any stored value to a display/edit string (empty for absent). */
|
|
7
|
+
export function asString(value: unknown): string {
|
|
8
|
+
if (typeof value === 'string') return value;
|
|
9
|
+
if (value === undefined || value === null) return '';
|
|
10
|
+
return String(value);
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
/** Human-readable rendering of a scalar field value for the read-only preview. */
|
|
14
|
+
export function formatScalar(field: CaptureFieldSpec, value: unknown, emptyText: string): string {
|
|
15
|
+
if (value === undefined || value === null || value === '') return emptyText;
|
|
16
|
+
switch (field.type) {
|
|
17
|
+
case CaptureFieldType.Boolean:
|
|
18
|
+
return value === true ? 'Yes' : 'No';
|
|
19
|
+
default:
|
|
20
|
+
return asString(value);
|
|
21
|
+
}
|
|
22
|
+
}
|
|
@@ -0,0 +1,100 @@
|
|
|
1
|
+
// ═══════════════════════════════════════════════════════════════════════════
|
|
2
|
+
// <Wizard> / <WizardStep> — thin presentational shell over useWizard
|
|
3
|
+
//
|
|
4
|
+
// Composes the existing `<FormStepper>` for the numbered rail (with the ACTIVE
|
|
5
|
+
// step's body rendered inline, guided-style — pending steps stay empty) and
|
|
6
|
+
// renders a Back / Next / Finish nav bar. All state lives in the `useWizard`
|
|
7
|
+
// engine you pass via `api`; this component is presentation only.
|
|
8
|
+
// ═══════════════════════════════════════════════════════════════════════════
|
|
9
|
+
import { Children, isValidElement, type ReactElement, type ReactNode } from 'react';
|
|
10
|
+
|
|
11
|
+
import { cn } from '../cn';
|
|
12
|
+
import { Button } from '../primitives/button';
|
|
13
|
+
import { FormStepper, type FormStep } from '../primitives/form-stepper';
|
|
14
|
+
|
|
15
|
+
import type { WizardApi } from './use-wizard';
|
|
16
|
+
|
|
17
|
+
export interface WizardStepProps {
|
|
18
|
+
/** Must match a `useWizard` step `key`. */
|
|
19
|
+
readonly stepKey: string;
|
|
20
|
+
readonly children: ReactNode;
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
/**
|
|
24
|
+
* Declarative wrapper for one wizard step's body. Rendered by `<Wizard>` only
|
|
25
|
+
* when its `stepKey` is the active step.
|
|
26
|
+
*/
|
|
27
|
+
export function WizardStep(_props: WizardStepProps): null {
|
|
28
|
+
// Rendering is orchestrated by <Wizard>; this component only carries props.
|
|
29
|
+
return null;
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
export interface WizardProps {
|
|
33
|
+
readonly api: WizardApi;
|
|
34
|
+
readonly children: ReactNode;
|
|
35
|
+
/** Called when Finish is pressed on the last step (gate already satisfied). */
|
|
36
|
+
readonly onFinish?: () => void;
|
|
37
|
+
readonly nextLabel?: string;
|
|
38
|
+
readonly backLabel?: string;
|
|
39
|
+
readonly finishLabel?: string;
|
|
40
|
+
/** Hide the built-in nav bar (caller renders its own using `api`). */
|
|
41
|
+
readonly hideNav?: boolean;
|
|
42
|
+
readonly className?: string;
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
function stepBodies(children: ReactNode): Map<string, ReactNode> {
|
|
46
|
+
const map = new Map<string, ReactNode>();
|
|
47
|
+
Children.forEach(children, (child) => {
|
|
48
|
+
if (isValidElement(child) && (child as ReactElement<WizardStepProps>).props?.stepKey) {
|
|
49
|
+
const p = (child as ReactElement<WizardStepProps>).props;
|
|
50
|
+
map.set(p.stepKey, p.children);
|
|
51
|
+
}
|
|
52
|
+
});
|
|
53
|
+
return map;
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
export function Wizard({
|
|
57
|
+
api,
|
|
58
|
+
children,
|
|
59
|
+
onFinish,
|
|
60
|
+
nextLabel = 'Continue',
|
|
61
|
+
backLabel = 'Back',
|
|
62
|
+
finishLabel = 'Finish',
|
|
63
|
+
hideNav = false,
|
|
64
|
+
className,
|
|
65
|
+
}: WizardProps) {
|
|
66
|
+
const bodies = stepBodies(children);
|
|
67
|
+
|
|
68
|
+
const formSteps: FormStep[] = api.steps.map((step, index) => ({
|
|
69
|
+
key: step.key,
|
|
70
|
+
label: step.label,
|
|
71
|
+
hint: step.hint,
|
|
72
|
+
status: api.status(index),
|
|
73
|
+
// Render the active step's body inline; pending/done steps stay empty so
|
|
74
|
+
// the rail reads as a guided one-step-at-a-time flow.
|
|
75
|
+
children: index === api.activeIndex ? bodies.get(step.key) ?? null : null,
|
|
76
|
+
}));
|
|
77
|
+
|
|
78
|
+
return (
|
|
79
|
+
<div className={cn('space-y-5', className)}>
|
|
80
|
+
<FormStepper steps={formSteps} />
|
|
81
|
+
|
|
82
|
+
{!hideNav && (
|
|
83
|
+
<div className="flex items-center justify-between gap-2 border-t border-rule pt-4">
|
|
84
|
+
<Button variant="ghost" onClick={api.prev} disabled={api.isFirst}>
|
|
85
|
+
{backLabel}
|
|
86
|
+
</Button>
|
|
87
|
+
{api.isLast ? (
|
|
88
|
+
<Button onClick={onFinish} disabled={!api.canAdvance}>
|
|
89
|
+
{finishLabel}
|
|
90
|
+
</Button>
|
|
91
|
+
) : (
|
|
92
|
+
<Button onClick={api.next} disabled={!api.canAdvance}>
|
|
93
|
+
{nextLabel}
|
|
94
|
+
</Button>
|
|
95
|
+
)}
|
|
96
|
+
</div>
|
|
97
|
+
)}
|
|
98
|
+
</div>
|
|
99
|
+
);
|
|
100
|
+
}
|
package/src/ui/index.ts
CHANGED
|
@@ -88,3 +88,6 @@ export { default as LoadingState, type LoadingStateVariant } from './chrome/Load
|
|
|
88
88
|
export { default as AsyncBoundary } from './chrome/AsyncBoundary';
|
|
89
89
|
|
|
90
90
|
export { PdfPreview, type PdfPreviewProps } from './pdf/pdf-preview';
|
|
91
|
+
|
|
92
|
+
// ── guided-capture UX kit (B5 — wizard, validation, prefill, schema form) ──
|
|
93
|
+
export * from './capture';
|