@form-eng/core 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md ADDED
@@ -0,0 +1,499 @@
1
+ # @form-eng/core
2
+
3
+ UI-library agnostic business rules engine and form orchestration for configuration-driven React forms. Built for React -- works with any component library (Fluent UI, MUI, Ant Design, or your own). Define forms as JSON -- field definitions, dependency rules, dropdown options, ordering -- and the library handles rendering, validation, auto-save, and field interactions automatically.
4
+
5
+ ## Install
6
+
7
+ ```bash
8
+ npm install @form-eng/core
9
+ ```
10
+
11
+ Peer dependencies: `react` (18 or 19), `react-hook-form` (v7)
12
+
13
+ ## Quick Start
14
+
15
+ ```tsx
16
+ import {
17
+ RulesEngineProvider,
18
+ InjectedFieldProvider,
19
+ FormEngine,
20
+ } from "@form-eng/core";
21
+
22
+ const fieldConfigs = {
23
+ name: { type: "Textbox", label: "Name", required: true },
24
+ status: {
25
+ type: "Dropdown",
26
+ label: "Status",
27
+ options: [
28
+ { value: "Active", label: "Active" },
29
+ { value: "Inactive", label: "Inactive" },
30
+ ],
31
+ },
32
+ };
33
+
34
+ function App() {
35
+ return (
36
+ <RulesEngineProvider>
37
+ <InjectedFieldProvider>
38
+ <FormEngine
39
+ configName="myForm"
40
+ programName="myApp"
41
+ fieldConfigs={fieldConfigs}
42
+ defaultValues={{ name: "", status: "Active" }}
43
+ saveData={async (data) => {
44
+ console.log("Saving:", data);
45
+ return data;
46
+ }}
47
+ />
48
+ </InjectedFieldProvider>
49
+ </RulesEngineProvider>
50
+ );
51
+ }
52
+ ```
53
+
54
+ You'll also need a UI adapter to provide field components. See:
55
+ - [`@form-eng/fluent`](https://www.npmjs.com/package/@form-eng/fluent) -- Fluent UI v9
56
+ - [`@form-eng/mui`](https://www.npmjs.com/package/@form-eng/mui) -- Material UI
57
+ - [`@form-eng/headless`](https://www.npmjs.com/package/@form-eng/headless) -- Unstyled semantic HTML (Tailwind-friendly)
58
+
59
+ ## Business Rules Engine
60
+
61
+ Rules are **declarative** -- defined as data in `IFieldConfig.rules`, not imperative code.
62
+
63
+ When a field value changes, the engine:
64
+
65
+ 1. Reverts previously applied rules on dependent fields
66
+ 2. Re-evaluates which rules match the new value
67
+ 3. Applies new rules (required, hidden, readOnly, component swap, validations, etc.)
68
+ 4. Processes combo (AND) rules across multiple fields
69
+ 5. Updates dropdown options based on dependency rules
70
+ 6. Reorders fields if order dependencies are defined
71
+
72
+ Includes **circular dependency detection** via Kahn's algorithm and **config validation** for catching misconfigurations early.
73
+
74
+ ## Validation
75
+
76
+ ### 15 Built-in Sync Validators
77
+
78
+ `EmailValidation`, `PhoneNumberValidation`, `YearValidation`, `Max150KbValidation`, `Max32KbValidation`, `isValidUrl`, `NoSpecialCharactersValidation`, `CurrencyValidation`, `UniqueInArrayValidation`
79
+
80
+ ### Factory Validators
81
+
82
+ ```tsx
83
+ import {
84
+ createMinLengthValidation,
85
+ createMaxLengthValidation,
86
+ createNumericRangeValidation,
87
+ createPatternValidation,
88
+ createRequiredIfValidation,
89
+ } from "@form-eng/core";
90
+
91
+ registerValidators({
92
+ MinLength3: createMinLengthValidation(3),
93
+ Max100Chars: createMaxLengthValidation(100),
94
+ Score1to10: createNumericRangeValidation(1, 10),
95
+ AlphaOnly: createPatternValidation(/^[a-zA-Z]+$/, "Letters only"),
96
+ RequiredIfActive: createRequiredIfValidation("status", ["Active"]),
97
+ });
98
+ ```
99
+
100
+ ### Async Validators
101
+
102
+ ```tsx
103
+ import { registerValidators } from "@form-eng/core";
104
+
105
+ registerValidators({
106
+ CheckUniqueEmail: async (value, entityData, signal) => {
107
+ const res = await fetch(`/api/check?email=${value}`, { signal });
108
+ const { exists } = await res.json();
109
+ return exists ? "Already in use" : undefined;
110
+ },
111
+ });
112
+ ```
113
+
114
+ Reference in field configs via `validate: [{ validator: "CheckUniqueEmail", async: true }]`.
115
+
116
+ ### Config Validation
117
+
118
+ ```tsx
119
+ import { validateFieldConfigs } from "@form-eng/core";
120
+
121
+ const errors = validateFieldConfigs(fieldConfigs, registeredComponentTypes);
122
+ // Checks: missing dep targets, unregistered components/validators, circular deps
123
+ ```
124
+
125
+ ## Multi-Step Wizard
126
+
127
+ ```tsx
128
+ import { WizardForm } from "@form-eng/core";
129
+
130
+ <WizardForm
131
+ wizardConfig={{
132
+ steps: [
133
+ { id: "basics", title: "Basics", fields: ["name", "type"] },
134
+ { id: "details", title: "Details", fields: ["description"],
135
+ visibleWhen: { field: "type", is: ["bug"] } },
136
+ ],
137
+ validateOnStepChange: true,
138
+ }}
139
+ entityData={formValues}
140
+ renderStepContent={(fields) => <FieldRenderer fields={fields} />}
141
+ renderStepNavigation={({ goNext, goPrev, canGoNext, canGoPrev }) => (
142
+ <nav>
143
+ <button onClick={goPrev} disabled={!canGoPrev}>Back</button>
144
+ <button onClick={goNext} disabled={!canGoNext}>Next</button>
145
+ </nav>
146
+ )}
147
+ />
148
+ ```
149
+
150
+ All fields stay in a single `react-hook-form` context. Steps just control which fields are visible. Cross-step business rules work automatically.
151
+
152
+ ## Field Arrays
153
+
154
+ ```tsx
155
+ import { FieldArray } from "@form-eng/core";
156
+
157
+ <FieldArray
158
+ fieldName="contacts"
159
+ config={{
160
+ items: { name: { type: "Textbox", label: "Name" } },
161
+ minItems: 1,
162
+ maxItems: 5,
163
+ }}
164
+ renderItem={(fieldNames, index, remove) => (
165
+ <div>
166
+ <FieldRenderer fields={fieldNames} />
167
+ <button onClick={remove}>Remove</button>
168
+ </div>
169
+ )}
170
+ renderAddButton={(append, canAdd) => (
171
+ <button onClick={append} disabled={!canAdd}>Add</button>
172
+ )}
173
+ />
174
+ ```
175
+
176
+ ## i18n / Localization
177
+
178
+ ```tsx
179
+ import { registerLocale } from "@form-eng/core";
180
+
181
+ registerLocale({
182
+ required: "Obligatoire",
183
+ save: "Sauvegarder",
184
+ invalidEmail: "Adresse e-mail invalide",
185
+ // Partial -- unspecified keys fall back to English
186
+ });
187
+ ```
188
+
189
+ All strings in `FormStrings` and validation error messages resolve through the locale registry.
190
+
191
+ ## Manual Save vs Auto-Save
192
+
193
+ ```tsx
194
+ // Auto-save (default) -- saves on every field change with debounce
195
+ <FormEngine saveData={async (data) => data} />
196
+
197
+ // Manual save -- shows Save/Cancel buttons, no auto-save
198
+ <FormEngine isManualSave={true} saveData={async (data) => data} />
199
+
200
+ // Manual save with custom buttons
201
+ <FormEngine
202
+ isManualSave={true}
203
+ renderSaveButton={({ onSave, isDirty, isSubmitting }) => (
204
+ <button onClick={onSave} disabled={!isDirty || isSubmitting}>Submit</button>
205
+ )}
206
+ />
207
+ ```
208
+
209
+ ## Error Boundary
210
+
211
+ Each field is individually wrapped in `FormErrorBoundary` so one crashing field does not take down the entire form:
212
+
213
+ ```tsx
214
+ import { FormErrorBoundary } from "@form-eng/core";
215
+
216
+ <FormErrorBoundary
217
+ fallback={(error, resetErrorBoundary) => (
218
+ <div>
219
+ <p>Field crashed: {error.message}</p>
220
+ <button onClick={resetErrorBoundary}>Retry</button>
221
+ </div>
222
+ )}
223
+ onError={(error, errorInfo) => logError(error)}
224
+ >
225
+ <MyField />
226
+ </FormErrorBoundary>
227
+ ```
228
+
229
+ Built into the core rendering pipeline automatically.
230
+
231
+ ## Save Reliability
232
+
233
+ FormEngine includes robust save handling:
234
+
235
+ - **AbortController** cancels previous in-flight saves when a new save triggers
236
+ - **Configurable timeout** via `saveTimeoutMs` prop (default 30 seconds)
237
+ - **Retry with exponential backoff** via `maxSaveRetries` prop (default 3 retries)
238
+
239
+ ```tsx
240
+ <FormEngine
241
+ saveTimeoutMs={15000}
242
+ maxSaveRetries={5}
243
+ saveData={async (data) => { /* ... */ }}
244
+ />
245
+ ```
246
+
247
+ ## Accessibility
248
+
249
+ Built-in accessibility features:
250
+
251
+ - **Focus trap** in `ConfirmInputsModal` (Tab wraps, Escape closes, focus restored on close)
252
+ - **Focus-to-first-error** on validation failure
253
+ - **ARIA live regions** -- `<div role="status" aria-live="polite">` announces saving/saved/error
254
+ - **aria-label** on filter inputs, **aria-busy** on fields during save
255
+ - **Wizard step announcements** for screen readers ("Step 2 of 4: Details")
256
+
257
+ ## Draft Persistence
258
+
259
+ Auto-save form state to localStorage and recover after page refresh:
260
+
261
+ ```tsx
262
+ import { useDraftPersistence, useBeforeUnload } from "@form-eng/core";
263
+
264
+ const { hasDraft, clearDraft } = useDraftPersistence({
265
+ formId: "my-form-123",
266
+ data: formValues,
267
+ saveIntervalMs: 5000,
268
+ enabled: isDirty,
269
+ storageKeyPrefix: "myApp",
270
+ });
271
+
272
+ // Browser warning on page leave
273
+ useBeforeUnload(isDirty, "You have unsaved changes.");
274
+ ```
275
+
276
+ Includes `serializeFormState` / `deserializeFormState` utilities for Date-safe JSON round-trips.
277
+
278
+ ## Theming & Customization
279
+
280
+ ### Render Props
281
+
282
+ Customize field chrome via render props on `FieldWrapper`:
283
+
284
+ ```tsx
285
+ <FieldWrapper
286
+ renderLabel={(label, required) => <CustomLabel text={label} required={required} />}
287
+ renderError={(error) => <CustomError message={error} />}
288
+ renderStatus={(status) => <CustomStatus type={status} />}
289
+ />
290
+ ```
291
+
292
+ ### CSS Custom Properties
293
+
294
+ Import the optional `styles.css` and override CSS custom properties:
295
+
296
+ ```css
297
+ :root {
298
+ --fe-error-color: #d32f2f;
299
+ --fe-warning-color: #ed6c02;
300
+ --fe-saving-color: #0288d1;
301
+ --fe-label-color: #333;
302
+ --fe-required-color: #d32f2f;
303
+ --fe-border-radius: 4px;
304
+ --fe-field-gap: 12px;
305
+ --fe-font-size: 14px;
306
+ }
307
+ ```
308
+
309
+ ### Form-Level Errors
310
+
311
+ Display a form-level error banner for cross-field validation:
312
+
313
+ ```tsx
314
+ <FormEngine
315
+ formErrors={["End date must be after start date"]}
316
+ /* ... */
317
+ />
318
+ ```
319
+
320
+ ## Analytics & Telemetry
321
+
322
+ Opt-in form lifecycle tracking via `IAnalyticsCallbacks` in form settings:
323
+
324
+ ```tsx
325
+ const formConfig: IFormConfig = {
326
+ version: 2,
327
+ fields: { /* ... */ },
328
+ settings: {
329
+ analytics: {
330
+ onFieldFocus: (fieldName) => telemetry.track("focus", { fieldName }),
331
+ onFieldBlur: (fieldName, timeSpentMs) => telemetry.track("blur", { fieldName, timeSpentMs }),
332
+ onFieldChange: (fieldName, oldValue, newValue) => telemetry.track("change", { fieldName }),
333
+ onValidationError: (fieldName, errors) => telemetry.track("validation_error", { fieldName, errors }),
334
+ onFormSubmit: (values, durationMs) => telemetry.track("submit", { durationMs }),
335
+ onFormAbandonment: (filledFields, emptyRequired) => telemetry.track("abandoned", { filledFields }),
336
+ onWizardStepChange: (fromStep, toStep) => telemetry.track("step", { fromStep, toStep }),
337
+ onRuleTriggered: (event) => telemetry.track("rule", event),
338
+ },
339
+ },
340
+ };
341
+ ```
342
+
343
+ All callbacks are optional. Zero overhead when not provided. See [docs/analytics-telemetry.md](https://github.com/bghcore/form-engine/blob/main/docs/analytics-telemetry.md).
344
+
345
+ ## DevTools
346
+
347
+ Collapsible dev-only panel with 7 tabs: **Rules**, **Values**, **Errors**, **Graph**, **Perf**, **Deps**, **Timeline**.
348
+
349
+ ```tsx
350
+ import { FormDevTools } from "@form-eng/core";
351
+
352
+ <FormDevTools
353
+ configName="myForm"
354
+ formState={rulesState}
355
+ formValues={formValues}
356
+ formErrors={formErrors}
357
+ dirtyFields={dirtyFields}
358
+ enabled={process.env.NODE_ENV === "development"}
359
+ />
360
+ ```
361
+
362
+ | Tab | Shows |
363
+ |-----|-------|
364
+ | Rules | Per-field runtime state (type, required, hidden, readOnly, active rules) |
365
+ | Values | Live form values as JSON |
366
+ | Errors | Current validation errors |
367
+ | Graph | Dependency graph as text |
368
+ | Perf | Per-field render counts, hot field detection via `RenderTracker` |
369
+ | Deps | Dependency adjacency table, color-coded by effect type, cycle detection |
370
+ | Timeline | Chronological event log via `EventTimeline`, filterable by field name |
371
+
372
+ See [docs/performance-debugging.md](https://github.com/bghcore/form-engine/blob/main/docs/performance-debugging.md).
373
+
374
+ ## JSON Schema Import
375
+
376
+ Convert JSON Schema to field configs:
377
+
378
+ ```tsx
379
+ import { jsonSchemaToFieldConfig } from "@form-eng/core";
380
+
381
+ const fieldConfigs = jsonSchemaToFieldConfig({
382
+ type: "object",
383
+ properties: {
384
+ name: { type: "string", minLength: 1 },
385
+ age: { type: "number", minimum: 0 },
386
+ role: { type: "string", enum: ["admin", "user"] },
387
+ },
388
+ required: ["name"],
389
+ });
390
+ ```
391
+
392
+ Maps JSON Schema types, enums, formats, and required fields to `Dictionary<IFieldConfig>`.
393
+
394
+ ## Zod Schema Import
395
+
396
+ Convert Zod object schemas to field configs without adding zod as a dependency. The adapter inspects Zod's internal type structure at runtime.
397
+
398
+ ```tsx
399
+ import { zodSchemaToFieldConfig } from "@form-eng/core";
400
+ import { z } from "zod";
401
+
402
+ const UserSchema = z.object({
403
+ name: z.string().min(1),
404
+ age: z.number().min(0),
405
+ active: z.boolean(),
406
+ role: z.enum(["admin", "user", "guest"]),
407
+ email: z.string().email(),
408
+ startDate: z.date(),
409
+ tags: z.array(z.string()),
410
+ });
411
+
412
+ const fieldConfigs = zodSchemaToFieldConfig(UserSchema);
413
+ // Maps: ZodString->Textbox, ZodNumber->Number, ZodBoolean->Toggle,
414
+ // ZodEnum->Dropdown, ZodDate->DateControl, ZodArray->Multiselect
415
+ // Detects .email() and .url() checks for automatic validation
416
+ ```
417
+
418
+ No `zod` peer dependency is required. If you do not use Zod, this function is tree-shaken out of your bundle.
419
+
420
+ ## Type-Safe Field Configs
421
+
422
+ Use `defineFieldConfigs()` to get compile-time verification that dependency targets reference real field names:
423
+
424
+ ```tsx
425
+ import { defineFieldConfigs } from "@form-eng/core";
426
+
427
+ const configs = defineFieldConfigs({
428
+ name: { type: "Textbox", label: "Name", required: true },
429
+ status: {
430
+ type: "Dropdown",
431
+ label: "Status",
432
+ options: [
433
+ { value: "Active", label: "Active" },
434
+ { value: "Inactive", label: "Inactive" },
435
+ ],
436
+ rules: [
437
+ {
438
+ when: { field: "status", is: "Active" },
439
+ then: {
440
+ name: { required: true }, // TypeScript verifies "name" exists
441
+ // typo: { required: true }, // ERROR: "typo" is not a field name
442
+ },
443
+ },
444
+ ],
445
+ },
446
+ });
447
+ ```
448
+
449
+ This is a zero-cost utility -- at runtime it just returns the input object unchanged. The value is purely at compile time.
450
+
451
+ ## JSON Schema for IDE Autocompletion
452
+
453
+ The package ships JSON Schema files for `IFieldConfig` and `IWizardConfig` at `schemas/field-config.schema.json` and `schemas/wizard-config.schema.json`. Reference them in your JSON config files for IDE autocompletion:
454
+
455
+ ```json
456
+ {
457
+ "$schema": "node_modules/@form-eng/core/schemas/field-config.schema.json"
458
+ }
459
+ ```
460
+
461
+ ## Lazy Field Registry
462
+
463
+ Load field components on demand using `React.lazy()` for smaller initial bundles:
464
+
465
+ ```tsx
466
+ import { createLazyFieldRegistry } from "@form-eng/core";
467
+
468
+ const lazyFields = createLazyFieldRegistry({
469
+ Textbox: () => import("./fields/HookTextbox"),
470
+ Dropdown: () => import("./fields/HookDropdown"),
471
+ });
472
+
473
+ setInjectedFields(lazyFields);
474
+ ```
475
+
476
+ ## Architecture
477
+
478
+ ```
479
+ <RulesEngineProvider> -- Owns rule state via useReducer (memoized)
480
+ <InjectedFieldProvider> -- Component injection registry (memoized)
481
+ <FormEngine> -- Form state (react-hook-form), auto-save with retry, business rules
482
+ <FormFields> -- Renders ordered field list
483
+ <FormErrorBoundary> -- Per-field error boundary (crash isolation)
484
+ <RenderField> -- Per-field: Controller + component lookup (useMemo)
485
+ <FieldWrapper> -- Label, error, saving status (React.memo, render props)
486
+ <InjectedField /> -- Your UI component via cloneElement
487
+ ```
488
+
489
+ ## SSR / Next.js
490
+
491
+ All core components are SSR-safe with proper `typeof window` guards. See [docs/ssr-guide.md](https://github.com/bghcore/form-engine/blob/main/docs/ssr-guide.md) for Next.js App Router and Pages Router integration guides.
492
+
493
+ ## Building a Custom UI Adapter
494
+
495
+ See [docs/creating-an-adapter.md](https://github.com/bghcore/form-engine/blob/main/docs/creating-an-adapter.md) for a complete guide.
496
+
497
+ ## License
498
+
499
+ MIT