formo-react 0.0.0-stage → 0.3.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.
Files changed (87) hide show
  1. package/LICENSE +201 -0
  2. package/README.md +21 -2
  3. package/dist/components/FormoBlueprint.d.ts +5 -0
  4. package/dist/components/FormoBlueprint.js +30 -0
  5. package/dist/components/FormoButton.d.ts +6 -0
  6. package/dist/components/FormoButton.js +23 -0
  7. package/dist/components/FormoCheckbox.d.ts +7 -0
  8. package/dist/components/FormoCheckbox.js +10 -0
  9. package/dist/components/FormoChecklist.d.ts +5 -0
  10. package/dist/components/FormoChecklist.js +15 -0
  11. package/dist/components/FormoChoices.d.ts +8 -0
  12. package/dist/components/FormoChoices.js +33 -0
  13. package/dist/components/FormoContext.d.ts +27 -0
  14. package/dist/components/FormoContext.js +69 -0
  15. package/dist/components/FormoErrors.d.ts +5 -0
  16. package/dist/components/FormoErrors.js +14 -0
  17. package/dist/components/FormoField.d.ts +17 -0
  18. package/dist/components/FormoField.js +148 -0
  19. package/dist/components/FormoForm.d.ts +15 -0
  20. package/dist/components/FormoForm.js +76 -0
  21. package/dist/components/FormoGroup.d.ts +5 -0
  22. package/dist/components/FormoGroup.js +15 -0
  23. package/dist/components/FormoHelp.d.ts +6 -0
  24. package/dist/components/FormoHelp.js +9 -0
  25. package/dist/components/FormoInput.d.ts +6 -0
  26. package/dist/components/FormoInput.js +24 -0
  27. package/dist/components/FormoLabel.d.ts +6 -0
  28. package/dist/components/FormoLabel.js +9 -0
  29. package/dist/components/FormoProvider.d.ts +11 -0
  30. package/dist/components/FormoProvider.js +13 -0
  31. package/dist/components/FormoRest.d.ts +6 -0
  32. package/dist/components/FormoRest.js +23 -0
  33. package/dist/components/FormoSelect.d.ts +6 -0
  34. package/dist/components/FormoSelect.js +36 -0
  35. package/dist/components/FormoUneditable.d.ts +6 -0
  36. package/dist/components/FormoUneditable.js +12 -0
  37. package/dist/core/builder.d.ts +42 -0
  38. package/dist/core/builder.js +166 -0
  39. package/dist/core/controls.d.ts +27 -0
  40. package/dist/core/controls.js +24 -0
  41. package/dist/core/fields.d.ts +63 -0
  42. package/dist/core/fields.js +177 -0
  43. package/dist/core/messages.d.ts +35 -0
  44. package/dist/core/messages.js +69 -0
  45. package/dist/core/normalize.d.ts +35 -0
  46. package/dist/core/normalize.js +234 -0
  47. package/dist/core/options.d.ts +44 -0
  48. package/dist/core/options.js +146 -0
  49. package/dist/core/rules.d.ts +41 -0
  50. package/dist/core/rules.js +230 -0
  51. package/dist/core/store.d.ts +155 -0
  52. package/dist/core/store.js +830 -0
  53. package/dist/core/theme.d.ts +20 -0
  54. package/dist/core/theme.js +21 -0
  55. package/dist/core/tree.d.ts +74 -0
  56. package/dist/core/tree.js +119 -0
  57. package/dist/core/utils.d.ts +35 -0
  58. package/dist/core/utils.js +206 -0
  59. package/dist/hooks/subscriptions.d.ts +38 -0
  60. package/dist/hooks/subscriptions.js +65 -0
  61. package/dist/hooks/useFormo.d.ts +18 -0
  62. package/dist/hooks/useFormo.js +25 -0
  63. package/dist/index.d.ts +28 -0
  64. package/dist/index.js +27 -0
  65. package/dist/schema/form.d.ts +92 -0
  66. package/dist/schema/form.js +304 -0
  67. package/dist/schema/index.d.ts +22 -0
  68. package/dist/schema/index.js +21 -0
  69. package/dist/schema/ir.d.ts +189 -0
  70. package/dist/schema/ir.js +130 -0
  71. package/dist/schema/json-schema.d.ts +25 -0
  72. package/dist/schema/json-schema.js +351 -0
  73. package/dist/schema/laravel.d.ts +57 -0
  74. package/dist/schema/laravel.js +555 -0
  75. package/dist/schema/openapi.d.ts +24 -0
  76. package/dist/schema/openapi.js +67 -0
  77. package/dist/schema/policy.d.ts +60 -0
  78. package/dist/schema/policy.js +315 -0
  79. package/dist/schema/spec.d.ts +75 -0
  80. package/dist/schema/spec.js +1 -0
  81. package/dist/schema/values.d.ts +35 -0
  82. package/dist/schema/values.js +151 -0
  83. package/dist/schema/zod.d.ts +79 -0
  84. package/dist/schema/zod.js +236 -0
  85. package/dist/types.d.ts +400 -0
  86. package/dist/types.js +1 -0
  87. package/package.json +70 -4
@@ -0,0 +1,20 @@
1
+ import type { ComponentRef, FormoTheme, FormoViews } from '../types';
2
+ export interface ThemeInput {
3
+ views?: FormoViews;
4
+ components?: Record<string, ComponentRef>;
5
+ classes?: Record<string, string>;
6
+ }
7
+ /**
8
+ * Bundle custom view components, control overrides, and optional CSS class names
9
+ * into a reusable theme:
10
+ *
11
+ * ```tsx
12
+ * const cardTheme = defineTheme({
13
+ * views: { field: CardFieldView },
14
+ * components: { input: ShadcnInput },
15
+ * })
16
+ *
17
+ * <FormoForm form={form} theme={cardTheme} />
18
+ * ```
19
+ */
20
+ export declare function defineTheme(input: ThemeInput): FormoTheme;
@@ -0,0 +1,21 @@
1
+ /**
2
+ * Bundle custom view components, control overrides, and optional CSS class names
3
+ * into a reusable theme:
4
+ *
5
+ * ```tsx
6
+ * const cardTheme = defineTheme({
7
+ * views: { field: CardFieldView },
8
+ * components: { input: ShadcnInput },
9
+ * })
10
+ *
11
+ * <FormoForm form={form} theme={cardTheme} />
12
+ * ```
13
+ */
14
+ export function defineTheme(input) {
15
+ return {
16
+ views: input.views ?? {},
17
+ components: input.components ?? {},
18
+ classes: input.classes ?? {},
19
+ __formoTheme: true,
20
+ };
21
+ }
@@ -0,0 +1,74 @@
1
+ import type { ErrorDisplay, FieldNode, FormoConfig } from '../types';
2
+ /**
3
+ * The rendered shape of a form — pure TypeScript, no React. Like formo-vue's
4
+ * `locate.ts` walk: paths follow namespaces (`address.street`), `namespaces: false`
5
+ * groups (their fields at the parent's level) and blueprint rows (`phones[0].number`),
6
+ * whose number comes from the values.
7
+ */
8
+ interface TreeBase {
9
+ node: FieldNode;
10
+ /** Path of the node (`address.street`, `phones[0].number`) — handles, errors */
11
+ path: string;
12
+ /** Value path of the group its value lives in (`''` at the root, `phones[0]` in a row) */
13
+ parentPath: string;
14
+ /** `config` it inherits, its own layered in */
15
+ config: FormoConfig;
16
+ /** `exclude: true` on it or on a group around it */
17
+ excluded: boolean;
18
+ /** Nesting depth (groups and rows count) */
19
+ depth: number;
20
+ }
21
+ export interface TreeField extends TreeBase {
22
+ kind: 'field';
23
+ /** The field's `errorDisplay`, else the nearest `config.errorDisplay` above it, else `first` */
24
+ errorDisplay: ErrorDisplay;
25
+ }
26
+ export interface TreeGroup extends TreeBase {
27
+ kind: 'group';
28
+ /** Where its fields' values live: its own path, or its parent's (`namespaces: false`) */
29
+ childPrefix: string;
30
+ children: TreeItem[];
31
+ }
32
+ export interface TreeRow {
33
+ index: number;
34
+ /** `phones[0]` */
35
+ path: string;
36
+ children: TreeItem[];
37
+ }
38
+ export interface TreeBlueprint extends TreeBase {
39
+ kind: 'blueprint';
40
+ rows: TreeRow[];
41
+ }
42
+ export type TreeItem = TreeField | TreeGroup | TreeBlueprint;
43
+ /** A field with a value (not a form / group / blueprint) */
44
+ export type FormoLeaf = TreeField;
45
+ /** The form's fields, subforms and blueprint rows, for these values */
46
+ export declare function buildTree(root: FieldNode, values: Record<string, any>, config?: FormoConfig): TreeItem[];
47
+ /** Every item of a tree, depth first (rows' items included) */
48
+ export declare function flattenTree(items: TreeItem[], out?: TreeItem[]): TreeItem[];
49
+ /** Every field of a tree */
50
+ export declare function leavesOf(items: TreeItem[]): FormoLeaf[];
51
+ /** Every subform and blueprint of a tree */
52
+ export declare function groupsOf(items: TreeItem[]): Array<TreeGroup | TreeBlueprint>;
53
+ /** Where a group's value lives: a blueprint's array, a subform's object (its parent's for `namespaces: false`) */
54
+ export declare function valuePathOf(item: TreeGroup | TreeBlueprint): string;
55
+ /** `path` is `parent` or inside it (`address.zip`, `phones[0].number`) */
56
+ export declare function isUnder(path: string, parent: string): boolean;
57
+ /** The row of `blueprintPath` that `path` is in (`phones[2].number` → 2), if it's in one */
58
+ export declare function rowIndexIn(path: string, blueprintPath: string): number | undefined;
59
+ /**
60
+ * After removing row `index` of a blueprint, move what's stored by path for
61
+ * the later rows up one (`phones[2].number` → `phones[1].number`) and drop the
62
+ * removed row's entries. Returns a new record (the same one when nothing moved).
63
+ */
64
+ export declare function shiftRowPaths<T>(record: Record<string, T>, blueprintPath: string, index: number): Record<string, T>;
65
+ /**
66
+ * A server's error key → the form path: Laravel / Inertia / Rails send
67
+ * `phones.0.number`, Formo's paths are `phones[0].number`. `':self'` is the
68
+ * group's own error (`address.:self` → `address`, `:self` → `''`).
69
+ * A path the form has, as written, always wins.
70
+ */
71
+ export declare function toFormPath(key: string, known?: (path: string) => boolean): string;
72
+ /** Flatten nested errors (`{ address: { street: '…', ':self': '…' } }`) into `{ path: messages }` */
73
+ export declare function flattenErrors(input: Record<string, unknown>, known?: (path: string) => boolean, prefix?: string, out?: Record<string, string[]>): Record<string, string[]>;
74
+ export {};
@@ -0,0 +1,119 @@
1
+ import { groupNamespaces, isGroupNode, nodeConfig } from './normalize';
2
+ import { getPath, isPlainObject, joinPath, toSegments } from './utils';
3
+ function walk(group, prefix, config, excluded, depth, values) {
4
+ const cfg = nodeConfig(group, config);
5
+ return group.fields.map((child) => {
6
+ const path = joinPath(prefix, child.alias);
7
+ const childCfg = nodeConfig(child, cfg);
8
+ const childExcluded = excluded || child.exclude === true;
9
+ const base = { node: child, path, parentPath: prefix, config: childCfg, excluded: childExcluded, depth };
10
+ if (!isGroupNode(child)) {
11
+ return { ...base, kind: 'field', errorDisplay: child.errorDisplay ?? childCfg.errorDisplay ?? 'first' };
12
+ }
13
+ if (child.blueprint) {
14
+ const value = getPath(values, path);
15
+ const count = Array.isArray(value) ? value.length : 0;
16
+ const rows = Array.from({ length: count }, (_, index) => {
17
+ const rowPath = `${path}[${index}]`;
18
+ return { index, path: rowPath, children: walk(child, rowPath, cfg, childExcluded, depth + 2, values) };
19
+ });
20
+ return { ...base, kind: 'blueprint', rows };
21
+ }
22
+ const childPrefix = groupNamespaces(child, cfg) ? path : prefix;
23
+ return { ...base, kind: 'group', childPrefix, children: walk(child, childPrefix, cfg, childExcluded, depth + 1, values) };
24
+ });
25
+ }
26
+ /** The form's fields, subforms and blueprint rows, for these values */
27
+ export function buildTree(root, values, config = {}) {
28
+ return walk(root, '', config, false, 0, values);
29
+ }
30
+ /** Every item of a tree, depth first (rows' items included) */
31
+ export function flattenTree(items, out = []) {
32
+ for (const item of items) {
33
+ out.push(item);
34
+ if (item.kind === 'group')
35
+ flattenTree(item.children, out);
36
+ else if (item.kind === 'blueprint')
37
+ for (const row of item.rows)
38
+ flattenTree(row.children, out);
39
+ }
40
+ return out;
41
+ }
42
+ /** Every field of a tree */
43
+ export function leavesOf(items) {
44
+ return flattenTree(items).filter((item) => item.kind === 'field');
45
+ }
46
+ /** Every subform and blueprint of a tree */
47
+ export function groupsOf(items) {
48
+ return flattenTree(items).filter((item) => item.kind !== 'field');
49
+ }
50
+ /** Where a group's value lives: a blueprint's array, a subform's object (its parent's for `namespaces: false`) */
51
+ export function valuePathOf(item) {
52
+ return item.kind === 'blueprint' ? item.path : item.childPrefix;
53
+ }
54
+ /* -------------------------------------------------------------------------- */
55
+ /* Paths */
56
+ /* -------------------------------------------------------------------------- */
57
+ /** `path` is `parent` or inside it (`address.zip`, `phones[0].number`) */
58
+ export function isUnder(path, parent) {
59
+ if (parent === '')
60
+ return true;
61
+ return path === parent || path.startsWith(`${parent}.`) || path.startsWith(`${parent}[`);
62
+ }
63
+ /** The row of `blueprintPath` that `path` is in (`phones[2].number` → 2), if it's in one */
64
+ export function rowIndexIn(path, blueprintPath) {
65
+ const m = path.match(ROW(blueprintPath));
66
+ if (!m || (m[2] !== '' && !/^[.[]/.test(m[2])))
67
+ return undefined;
68
+ return Number(m[1]);
69
+ }
70
+ const ROW = (blueprintPath) => new RegExp(`^${blueprintPath.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}\\[(\\d+)\\](.*)$`);
71
+ /**
72
+ * After removing row `index` of a blueprint, move what's stored by path for
73
+ * the later rows up one (`phones[2].number` → `phones[1].number`) and drop the
74
+ * removed row's entries. Returns a new record (the same one when nothing moved).
75
+ */
76
+ export function shiftRowPaths(record, blueprintPath, index) {
77
+ const re = ROW(blueprintPath);
78
+ let changed = false;
79
+ const out = {};
80
+ for (const [key, value] of Object.entries(record)) {
81
+ const m = key.match(re);
82
+ if (!m || (m[2] !== '' && !/^[.[]/.test(m[2]))) {
83
+ out[key] = value;
84
+ continue;
85
+ }
86
+ const row = Number(m[1]);
87
+ changed = true;
88
+ if (row === index)
89
+ continue;
90
+ out[row > index ? `${blueprintPath}[${row - 1}]${m[2]}` : key] = value;
91
+ }
92
+ return changed ? out : record;
93
+ }
94
+ /**
95
+ * A server's error key → the form path: Laravel / Inertia / Rails send
96
+ * `phones.0.number`, Formo's paths are `phones[0].number`. `':self'` is the
97
+ * group's own error (`address.:self` → `address`, `:self` → `''`).
98
+ * A path the form has, as written, always wins.
99
+ */
100
+ export function toFormPath(key, known = () => false) {
101
+ const p = key === ':self' ? '' : key.replace(/\.?:self$/, '');
102
+ if (p === '' || known(p))
103
+ return p;
104
+ return toSegments(p).reduce((acc, segment) => joinPath(acc, segment), '');
105
+ }
106
+ /** Flatten nested errors (`{ address: { street: '…', ':self': '…' } }`) into `{ path: messages }` */
107
+ export function flattenErrors(input, known = () => false, prefix = '', out = {}) {
108
+ for (const [key, value] of Object.entries(input)) {
109
+ const raw = key === ':self' ? prefix : prefix ? `${prefix}.${key}` : key;
110
+ if (isPlainObject(value)) {
111
+ flattenErrors(value, known, raw, out);
112
+ continue;
113
+ }
114
+ const list = (Array.isArray(value) ? value : [value]).filter((m) => typeof m === 'string' && m !== '');
115
+ if (list.length)
116
+ out[toFormPath(raw, known)] = list;
117
+ }
118
+ return out;
119
+ }
@@ -0,0 +1,35 @@
1
+ export declare function isPlainObject(value: unknown): value is Record<string, any>;
2
+ export declare function isEmptyValue(value: unknown): boolean;
3
+ /** `first_name` → `First name` */
4
+ export declare function humanize(alias: string | number): string;
5
+ /** Formo: "aliases always replace spaces with underscores" */
6
+ export declare function cleanAlias(alias: string | number): string | number;
7
+ /** Split a path like `a.b[0].c` or `a[b][0][c]` into segments */
8
+ export declare function toSegments(path: string | Array<string | number>): Array<string | number>;
9
+ export declare function getPath(obj: any, path: string | Array<string | number>, fallback?: any): any;
10
+ export declare function setPath(obj: Record<string, any>, path: string | Array<string | number>, value: unknown): void;
11
+ /** Delete a path from an object (array items are removed) */
12
+ export declare function unsetPath(obj: Record<string, any>, path: string | Array<string | number>): void;
13
+ /** Join a group path and a child alias the way vee-validate expects */
14
+ export declare function joinPath(parent: string, alias: string | number): string;
15
+ /** Build the HTML `name` attribute Formo style: `form[group][field]` */
16
+ export declare function toName(prefix: string | number | undefined, path: string): string;
17
+ /** A DOM-safe id from a form alias and a path */
18
+ export declare function toId(prefix: string | number | undefined, path: string): string;
19
+ export declare function deepClone<T>(value: T): T;
20
+ export declare function deepEqual(a: unknown, b: unknown): boolean;
21
+ /** Deep merge plain objects. Arrays and other values from `source` replace the target's */
22
+ export declare function deepMerge<T extends Record<string, any>>(target: T, ...sources: Array<Record<string, any> | undefined>): T;
23
+ export declare function toArray<T>(value: T | T[] | undefined | null): T[];
24
+ /** Replace `:field` / `{field}` style placeholders */
25
+ export declare function interpolate(message: string, values: Record<string, unknown>): string;
26
+ /**
27
+ * Immutable write: a copy of `obj` with `value` at `path`. Only the objects /
28
+ * arrays along the path are copied — everything else keeps its identity, so
29
+ * snapshots of untouched fields stay equal.
30
+ */
31
+ export declare function setIn<T>(obj: T, path: string | Array<string | number>, value: unknown): T;
32
+ /** Equal for re-render purposes: the same value, or arrays with the same items (checkbox lists) */
33
+ export declare function sameLeafValue(a: unknown, b: unknown): boolean;
34
+ /** `a.b[2].c` → `['a.b[2]', 'a.b', 'a', '']` — every group above a path, nearest first */
35
+ export declare function ancestorPaths(path: string): string[];
@@ -0,0 +1,206 @@
1
+ export function isPlainObject(value) {
2
+ if (value === null || typeof value !== 'object')
3
+ return false;
4
+ const proto = Object.getPrototypeOf(value);
5
+ return proto === Object.prototype || proto === null;
6
+ }
7
+ export function isEmptyValue(value) {
8
+ return (value === undefined ||
9
+ value === null ||
10
+ value === '' ||
11
+ (Array.isArray(value) && value.length === 0));
12
+ }
13
+ /** `first_name` → `First name` */
14
+ export function humanize(alias) {
15
+ const str = String(alias)
16
+ .replace(/[_-]+/g, ' ')
17
+ .replace(/([a-z\d])([A-Z])/g, '$1 $2')
18
+ .trim()
19
+ .toLowerCase();
20
+ return str.charAt(0).toUpperCase() + str.slice(1);
21
+ }
22
+ /** Formo: "aliases always replace spaces with underscores" */
23
+ export function cleanAlias(alias) {
24
+ if (typeof alias === 'number')
25
+ return alias;
26
+ return String(alias).trim().replace(/\s+/g, '_').replace(/\./g, '_');
27
+ }
28
+ /** Split a path like `a.b[0].c` or `a[b][0][c]` into segments */
29
+ export function toSegments(path) {
30
+ if (Array.isArray(path))
31
+ return path;
32
+ if (path === '')
33
+ return [];
34
+ return path
35
+ .replace(/\[(\w+)\]/g, '.$1')
36
+ .split('.')
37
+ .filter((s) => s !== '')
38
+ .map((s) => (/^\d+$/.test(s) ? Number(s) : s));
39
+ }
40
+ export function getPath(obj, path, fallback) {
41
+ const segments = toSegments(path);
42
+ let cur = obj;
43
+ for (const seg of segments) {
44
+ if (cur === null || cur === undefined)
45
+ return fallback;
46
+ cur = cur[seg];
47
+ }
48
+ return cur === undefined ? fallback : cur;
49
+ }
50
+ export function setPath(obj, path, value) {
51
+ const segments = toSegments(path);
52
+ let cur = obj;
53
+ segments.forEach((seg, i) => {
54
+ if (i === segments.length - 1) {
55
+ cur[seg] = value;
56
+ return;
57
+ }
58
+ if (cur[seg] === null || typeof cur[seg] !== 'object') {
59
+ cur[seg] = typeof segments[i + 1] === 'number' ? [] : {};
60
+ }
61
+ cur = cur[seg];
62
+ });
63
+ }
64
+ /** Delete a path from an object (array items are removed) */
65
+ export function unsetPath(obj, path) {
66
+ const segments = toSegments(path);
67
+ const last = segments.pop();
68
+ if (last === undefined)
69
+ return;
70
+ const parent = segments.length ? getPath(obj, segments) : obj;
71
+ if (parent === null || typeof parent !== 'object')
72
+ return;
73
+ if (Array.isArray(parent) && typeof last === 'number')
74
+ parent.splice(last, 1);
75
+ else
76
+ delete parent[last];
77
+ }
78
+ /** Join a group path and a child alias the way vee-validate expects */
79
+ export function joinPath(parent, alias) {
80
+ if (typeof alias === 'number')
81
+ return `${parent}[${alias}]`;
82
+ return parent ? `${parent}.${alias}` : String(alias);
83
+ }
84
+ /** Build the HTML `name` attribute Formo style: `form[group][field]` */
85
+ export function toName(prefix, path) {
86
+ const segments = toSegments(path);
87
+ if (prefix === undefined || prefix === '') {
88
+ const [first, ...rest] = segments;
89
+ return String(first ?? '') + rest.map((s) => `[${s}]`).join('');
90
+ }
91
+ return String(prefix) + segments.map((s) => `[${s}]`).join('');
92
+ }
93
+ /** A DOM-safe id from a form alias and a path */
94
+ export function toId(prefix, path) {
95
+ const body = toSegments(path).join('-');
96
+ const raw = prefix !== undefined && prefix !== '' ? `${prefix}-${body}` : body;
97
+ return raw.replace(/[^\w-]/g, '-');
98
+ }
99
+ export function deepClone(value) {
100
+ if (Array.isArray(value))
101
+ return value.map((v) => deepClone(v));
102
+ if (isPlainObject(value)) {
103
+ const out = {};
104
+ for (const key of Object.keys(value))
105
+ out[key] = deepClone(value[key]);
106
+ return out;
107
+ }
108
+ return value;
109
+ }
110
+ export function deepEqual(a, b) {
111
+ if (a === b)
112
+ return true;
113
+ if (Array.isArray(a) && Array.isArray(b)) {
114
+ return a.length === b.length && a.every((v, i) => deepEqual(v, b[i]));
115
+ }
116
+ if (isPlainObject(a) && isPlainObject(b)) {
117
+ const ka = Object.keys(a);
118
+ const kb = Object.keys(b);
119
+ return ka.length === kb.length && ka.every((k) => deepEqual(a[k], b[k]));
120
+ }
121
+ // Rules often carry regexes: the same pattern and flags are equal
122
+ if (a instanceof RegExp && b instanceof RegExp)
123
+ return String(a) === String(b);
124
+ return false;
125
+ }
126
+ /** Deep merge plain objects. Arrays and other values from `source` replace the target's */
127
+ export function deepMerge(target, ...sources) {
128
+ const out = { ...target };
129
+ for (const source of sources) {
130
+ if (!source)
131
+ continue;
132
+ for (const key of Object.keys(source)) {
133
+ const value = source[key];
134
+ if (value === undefined)
135
+ continue;
136
+ out[key] = isPlainObject(value) && isPlainObject(out[key]) ? deepMerge(out[key], value) : value;
137
+ }
138
+ }
139
+ return out;
140
+ }
141
+ export function toArray(value) {
142
+ if (value === undefined || value === null)
143
+ return [];
144
+ return Array.isArray(value) ? value : [value];
145
+ }
146
+ /** Replace `:field` / `{field}` style placeholders */
147
+ export function interpolate(message, values) {
148
+ // Longest keys first so `:param10` wins over `:param1`
149
+ const keys = Object.keys(values).sort((a, b) => b.length - a.length);
150
+ let out = message;
151
+ for (const key of keys) {
152
+ const replacement = formatParam(values[key]);
153
+ out = out.split(`:${key}`).join(replacement).split(`{${key}}`).join(replacement);
154
+ }
155
+ return out;
156
+ }
157
+ function formatParam(value) {
158
+ if (Array.isArray(value))
159
+ return value.map(formatParam).join(', ');
160
+ if (value instanceof RegExp)
161
+ return value.toString();
162
+ if (value === null || value === undefined)
163
+ return '';
164
+ if (typeof value === 'object')
165
+ return '';
166
+ return String(value);
167
+ }
168
+ /**
169
+ * Immutable write: a copy of `obj` with `value` at `path`. Only the objects /
170
+ * arrays along the path are copied — everything else keeps its identity, so
171
+ * snapshots of untouched fields stay equal.
172
+ */
173
+ export function setIn(obj, path, value) {
174
+ const segments = toSegments(path);
175
+ if (!segments.length)
176
+ return value;
177
+ const write = (current, i) => {
178
+ const seg = segments[i];
179
+ const copy = Array.isArray(current) ? current.slice() : isPlainObject(current) ? { ...current } : typeof seg === 'number' ? [] : {};
180
+ copy[seg] = i === segments.length - 1 ? value : write(current?.[seg], i + 1);
181
+ return copy;
182
+ };
183
+ return write(obj, 0);
184
+ }
185
+ /** Equal for re-render purposes: the same value, or arrays with the same items (checkbox lists) */
186
+ export function sameLeafValue(a, b) {
187
+ if (Object.is(a, b))
188
+ return true;
189
+ return Array.isArray(a) && Array.isArray(b) && a.length === b.length && a.every((v, i) => Object.is(v, b[i]));
190
+ }
191
+ /** `a.b[2].c` → `['a.b[2]', 'a.b', 'a', '']` — every group above a path, nearest first */
192
+ export function ancestorPaths(path) {
193
+ const segments = toSegments(path);
194
+ const out = [];
195
+ let acc = '';
196
+ const prefixes = [];
197
+ for (const seg of segments.slice(0, -1)) {
198
+ acc = joinPath(acc, seg);
199
+ prefixes.push(acc);
200
+ }
201
+ for (let i = prefixes.length - 1; i >= 0; i--)
202
+ out.push(prefixes[i]);
203
+ if (path !== '')
204
+ out.push('');
205
+ return out;
206
+ }
@@ -0,0 +1,38 @@
1
+ import type { FormoController, FormoFields, FormoHandle } from '../types';
2
+ import type { FormoState } from '../core/store';
3
+ /**
4
+ * Subscribe to form-wide state with a selector — the component re-renders only
5
+ * when the selected value changes (`isEqual`, default `Object.is`):
6
+ *
7
+ * ```tsx
8
+ * const dirty = useFormoState(form, (s) => s.dirty)
9
+ * const submitting = useFormoState(form, (s) => s.submitting)
10
+ * const errorCount = useFormoState(form, (s) => Object.keys(s.errors).length)
11
+ * ```
12
+ *
13
+ * Selecting `s.values` (or `(s) => s`) re-renders on every change — fine for a
14
+ * debug panel, not for a screen: select what you show.
15
+ */
16
+ export declare function useFormoState<T>(form: FormoController, selector: (state: FormoState) => T, isEqual?: (a: T, b: T) => boolean): T;
17
+ /**
18
+ * Subscribe to one value by path (`'email'`, `'address'`, `'phones[0].number'`) —
19
+ * re-renders when that value changes (groups: when anything inside changes).
20
+ */
21
+ export declare function useFormoValue<T = unknown>(form: FormoController, path: string): T;
22
+ export interface UseFormoFieldOptions {
23
+ /**
24
+ * Include the value (default: fields yes, subforms / blueprints no — a group's
25
+ * values object changes with every keystroke inside it, and its frame doesn't show it)
26
+ */
27
+ withValue?: boolean;
28
+ }
29
+ /**
30
+ * A handle's current state, re-rendering only when something it shows changes:
31
+ * its value, error(s), touched state, `editable`, checklist — for subforms their
32
+ * fields, for blueprints their rows / `canAdd` / `canRemove`. Accepts a live
33
+ * handle (`form.fields.email`) or a snapshot; returns a snapshot (a plain object,
34
+ * the same one while nothing changed). Every built-in component renders through it.
35
+ */
36
+ export declare function useFormoField(handle: FormoHandle, { withValue }?: UseFormoFieldOptions): FormoHandle;
37
+ /** The handles of the form's top level (`''`) or of a subform / row — re-renders when they change (structure only) */
38
+ export declare function useFormoFields(form: FormoController, containerPath?: string): FormoFields;
@@ -0,0 +1,65 @@
1
+ import { useCallback, useRef, useSyncExternalStore } from 'react';
2
+ /**
3
+ * Subscribe to form-wide state with a selector — the component re-renders only
4
+ * when the selected value changes (`isEqual`, default `Object.is`):
5
+ *
6
+ * ```tsx
7
+ * const dirty = useFormoState(form, (s) => s.dirty)
8
+ * const submitting = useFormoState(form, (s) => s.submitting)
9
+ * const errorCount = useFormoState(form, (s) => Object.keys(s.errors).length)
10
+ * ```
11
+ *
12
+ * Selecting `s.values` (or `(s) => s`) re-renders on every change — fine for a
13
+ * debug panel, not for a screen: select what you show.
14
+ */
15
+ export function useFormoState(form, selector, isEqual = Object.is) {
16
+ const { store } = form;
17
+ const cache = useRef({ has: false });
18
+ const getSnapshot = () => {
19
+ const state = store.getState();
20
+ const c = cache.current;
21
+ if (c.has && c.state === state && c.selector === selector)
22
+ return c.value;
23
+ const next = selector(state);
24
+ c.state = state;
25
+ c.selector = selector;
26
+ if (c.has && isEqual(c.value, next))
27
+ return c.value;
28
+ c.value = next;
29
+ c.has = true;
30
+ return next;
31
+ };
32
+ return useSyncExternalStore(store.subscribeAll, getSnapshot, getSnapshot);
33
+ }
34
+ /**
35
+ * Subscribe to one value by path (`'email'`, `'address'`, `'phones[0].number'`) —
36
+ * re-renders when that value changes (groups: when anything inside changes).
37
+ */
38
+ export function useFormoValue(form, path) {
39
+ const { store } = form;
40
+ const subscribe = useCallback((listener) => store.subscribe(path, listener), [store, path]);
41
+ const getSnapshot = () => store.getValue(path);
42
+ return useSyncExternalStore(subscribe, getSnapshot, getSnapshot);
43
+ }
44
+ /**
45
+ * A handle's current state, re-rendering only when something it shows changes:
46
+ * its value, error(s), touched state, `editable`, checklist — for subforms their
47
+ * fields, for blueprints their rows / `canAdd` / `canRemove`. Accepts a live
48
+ * handle (`form.fields.email`) or a snapshot; returns a snapshot (a plain object,
49
+ * the same one while nothing changed). Every built-in component renders through it.
50
+ */
51
+ export function useFormoField(handle, { withValue } = {}) {
52
+ const { store } = handle.form;
53
+ const { path } = handle;
54
+ const include = withValue ?? handle.kind === 'field';
55
+ const subscribe = useCallback((listener) => store.subscribe(path, listener), [store, path]);
56
+ const getSnapshot = () => store.snapshot(path, include);
57
+ return useSyncExternalStore(subscribe, getSnapshot, getSnapshot);
58
+ }
59
+ /** The handles of the form's top level (`''`) or of a subform / row — re-renders when they change (structure only) */
60
+ export function useFormoFields(form, containerPath = '') {
61
+ const { store } = form;
62
+ const subscribe = useCallback((listener) => store.subscribe(containerPath, listener), [store, containerPath]);
63
+ const getSnapshot = () => store.fieldsOf(containerPath);
64
+ return useSyncExternalStore(subscribe, getSnapshot, getSnapshot);
65
+ }
@@ -0,0 +1,18 @@
1
+ import type { FormoController, FormoDefinition } from '../types';
2
+ import { type FormoStoreOptions } from '../core/store';
3
+ export type UseFormoOptions = FormoStoreOptions;
4
+ /**
5
+ * Create a form controller. The form's state lives in a store outside React:
6
+ * the component calling `useFormo` does NOT re-render when the form changes —
7
+ * each field subscribes to its own path, so a keystroke re-renders that field only.
8
+ *
9
+ * ```tsx
10
+ * const form = useFormo(definition, { onSubmit })
11
+ * form.values // the current values (in handlers, effects…)
12
+ * const dirty = useFormoState(form, (s) => s.dirty) // to render form state: subscribe
13
+ * ```
14
+ *
15
+ * Memoize the definition (`useMemo`, or define it outside the component): a new
16
+ * definition object rebuilds the form (what's been typed is kept).
17
+ */
18
+ export declare function useFormo(definition: FormoDefinition, options?: UseFormoOptions): FormoController;
@@ -0,0 +1,25 @@
1
+ import { useEffect, useLayoutEffect, useState } from 'react';
2
+ import { FormoStore } from '../core/store';
3
+ /** Layout effects where they exist (React Native, the browser); plain effects when rendering on a server */
4
+ const useIsomorphicLayoutEffect = typeof window === 'undefined' ? useEffect : useLayoutEffect;
5
+ /**
6
+ * Create a form controller. The form's state lives in a store outside React:
7
+ * the component calling `useFormo` does NOT re-render when the form changes —
8
+ * each field subscribes to its own path, so a keystroke re-renders that field only.
9
+ *
10
+ * ```tsx
11
+ * const form = useFormo(definition, { onSubmit })
12
+ * form.values // the current values (in handlers, effects…)
13
+ * const dirty = useFormoState(form, (s) => s.dirty) // to render form state: subscribe
14
+ * ```
15
+ *
16
+ * Memoize the definition (`useMemo`, or define it outside the component): a new
17
+ * definition object rebuilds the form (what's been typed is kept).
18
+ */
19
+ export function useFormo(definition, options = {}) {
20
+ const [store] = useState(() => new FormoStore(definition, options));
21
+ // A new definition / config / initialValues: applied now, notified after commit (no updates during render)
22
+ store.sync(definition, options);
23
+ useIsomorphicLayoutEffect(() => store.flush());
24
+ return store.controller;
25
+ }
@@ -0,0 +1,28 @@
1
+ export { Formo } from './core/builder';
2
+ export { normalize, buildInitialValues, isHidden } from './core/normalize';
3
+ export { validateField, evaluateChecklist, parseRules } from './core/rules';
4
+ export { normalizeOptions, flattenOptions, isOptionGroup } from './core/options';
5
+ export { FormoStore, type FormoState, type FormoStoreOptions } from './core/store';
6
+ export { useFormo, type UseFormoOptions } from './hooks/useFormo';
7
+ export { useFormoState, useFormoValue, useFormoField, useFormoFields, } from './hooks/subscriptions';
8
+ export { FormoContext, useFormoContext, useFormoOptions } from './components/FormoContext';
9
+ export { FormoProvider, type FormoProviderProps } from './components/FormoProvider';
10
+ export { defineControl, isControl, type ControlInput } from './core/controls';
11
+ export { defineTheme, type ThemeInput } from './core/theme';
12
+ export { FormoForm, type FormoFormProps } from './components/FormoForm';
13
+ export { FormoField, FormoFieldControl, FormoReadOnly, type FormoFieldProps } from './components/FormoField';
14
+ export { FormoLabel, type FormoLabelProps } from './components/FormoLabel';
15
+ export { FormoHelp, type FormoHelpProps } from './components/FormoHelp';
16
+ export { FormoRest, type FormoRestProps } from './components/FormoRest';
17
+ export { FormoInput, type FormoInputProps } from './components/FormoInput';
18
+ export { FormoSelect, type FormoSelectProps } from './components/FormoSelect';
19
+ export { FormoCheckbox, type FormoCheckboxProps } from './components/FormoCheckbox';
20
+ export { FormoRadios, FormoCheckboxes } from './components/FormoChoices';
21
+ export { FormoButton, type FormoButtonProps } from './components/FormoButton';
22
+ export { FormoErrors } from './components/FormoErrors';
23
+ export { FormoChecklist } from './components/FormoChecklist';
24
+ export { FormoUneditable, readOnlyText } from './components/FormoUneditable';
25
+ export { FormoGroup } from './components/FormoGroup';
26
+ export { FormoBlueprint } from './components/FormoBlueprint';
27
+ export * from './schema';
28
+ export type * from './types';