formo-react 0.0.0-stage → 0.2.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,60 @@
1
+ import { type ModelField, type ModelItem, type ModelRule, type RuntimeRule, type WarningHandler } from './ir';
2
+ import type { FieldSpec, SpecOption, SpecRule } from './spec';
3
+ /**
4
+ * How model fields become Formo fields: the driver for each type, the rules
5
+ * derived from constraints, options, attributes. Every decision can be
6
+ * changed per field (`formFromModel(model, { fields })`, `ui` in the model) or
7
+ * app-wide (`policy`).
8
+ */
9
+ /**
10
+ * - `derived` (default): Formo rules derived from the constraints — messages,
11
+ * checklists, live locale switching and Laravel lang files all work. Schema
12
+ * refinements Formo can't express (Zod `.refine()` / `.superRefine()`) still
13
+ * run through the schema, after Formo's rules.
14
+ * - `schema`: the schema validates everything (needs a schema-backed model: `fromZod`)
15
+ * - `none`: no client-side validation (the server's 422 errors still map onto fields)
16
+ */
17
+ export type ValidationMode = 'derived' | 'schema' | 'none';
18
+ export interface ModelPolicy {
19
+ /** Strings whose `maxLength` is above this become textareas (default 255) */
20
+ textareaAbove: number;
21
+ /** Enums with this many options or fewer become radios instead of a select (default 0: always a select) */
22
+ radiosUpTo: number;
23
+ /** Last word on the driver of every field: return another driver name, or `proposed` */
24
+ driverFor?: (field: ModelField | ModelItem, proposed: string | undefined, path: string) => string | undefined;
25
+ }
26
+ export declare const defaultPolicy: ModelPolicy;
27
+ /** Options supplied by the app (relations, labelled enums): `{ role_id: roles }` */
28
+ export type OptionsInput = SpecOption[] | Array<string | number> | Record<string, string>;
29
+ export interface PolicyContext {
30
+ /** Dotted path, without row indexes (`phones.number`) */
31
+ path: string;
32
+ policy: ModelPolicy;
33
+ validation: ValidationMode;
34
+ warn: WarningHandler;
35
+ options: Record<string, OptionsInput>;
36
+ }
37
+ /** The driver a field gets (`undefined`: Formo can't render this type on its own) */
38
+ export declare function proposeDriver(field: ModelField | ModelItem, policy: ModelPolicy): string | undefined;
39
+ /** A model rule → a Formo rule */
40
+ export declare function toSpecRule(rule: ModelRule): SpecRule;
41
+ /** A JSON Schema pattern → RegExp (unicode-aware when it can be) */
42
+ export declare function patternToRegExp(pattern: string): RegExp | undefined;
43
+ /**
44
+ * Merge definition keys over a generated spec: plain objects (`attr`, `props`,
45
+ * `errorMessages`, `classes`, `config`) merge one level, everything else —
46
+ * `rules`, `opts`, `val` included — is replaced. `options` / `value` are read
47
+ * as `opts` / `val`.
48
+ */
49
+ export declare function mergeSpec(base: FieldSpec, over: Record<string, unknown>): FieldSpec;
50
+ /** A function rule named for Formo (a rule's name is its function's name) */
51
+ export declare function namedRule(fn: RuntimeRule, name: string): RuntimeRule;
52
+ /**
53
+ * A leaf field (anything but an object / repeatable rows) → its Formo definition.
54
+ * `undefined` when Formo can't render it (warned).
55
+ */
56
+ export declare function leafSpec(field: ModelField | ModelItem, ctx: PolicyContext): FieldSpec | undefined;
57
+ /** An object → a subform */
58
+ export declare function groupSpec(field: ModelField | ModelItem, children: Record<string, FieldSpec>, ctx: PolicyContext): FieldSpec;
59
+ /** An array of objects → repeatable rows */
60
+ export declare function blueprintSpec(field: ModelField | ModelItem, children: Record<string, FieldSpec>, ctx: PolicyContext): FieldSpec;
@@ -0,0 +1,315 @@
1
+ import { humanize, isPlainObject } from '../core/utils';
2
+ import { RUNTIME } from './ir';
3
+ export const defaultPolicy = { textareaAbove: 255, radiosUpTo: 0 };
4
+ const FORMAT_DRIVERS = {
5
+ email: 'email',
6
+ url: 'url',
7
+ uri: 'url',
8
+ password: 'password',
9
+ tel: 'tel',
10
+ color: 'color',
11
+ search: 'search',
12
+ };
13
+ const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
14
+ /** Rules implied by a string format (the driver's input type may add the same ones — Formo dedupes by name) */
15
+ const FORMAT_RULES = {
16
+ email: 'email',
17
+ url: 'url',
18
+ uri: 'url',
19
+ color: 'color',
20
+ ip: 'ip',
21
+ uuid: { rule: 'regex', params: [UUID] },
22
+ };
23
+ const isMany = (field) => field.relation?.kind === 'belongsToMany' || field.relation?.kind === 'hasMany';
24
+ /** The driver a field gets (`undefined`: Formo can't render this type on its own) */
25
+ export function proposeDriver(field, policy) {
26
+ const c = field.constraints ?? {};
27
+ switch (field.type) {
28
+ case 'string':
29
+ if (field.format && FORMAT_DRIVERS[field.format])
30
+ return FORMAT_DRIVERS[field.format];
31
+ if (field.format === 'textarea' || (c.maxLength ?? 0) > policy.textareaAbove)
32
+ return 'textarea';
33
+ return 'text';
34
+ case 'text':
35
+ return 'textarea';
36
+ case 'integer':
37
+ case 'number':
38
+ return 'number';
39
+ case 'boolean':
40
+ return 'checkbox';
41
+ case 'date':
42
+ return 'date';
43
+ case 'datetime':
44
+ return 'datetime-local';
45
+ case 'time':
46
+ return 'time';
47
+ case 'enum':
48
+ return (field.options?.length ?? 0) <= policy.radiosUpTo ? 'radios' : 'select';
49
+ case 'file':
50
+ return 'file';
51
+ case 'relation':
52
+ return isMany(field) ? 'checkboxes' : 'select';
53
+ case 'array': {
54
+ const item = field.items;
55
+ if (!item)
56
+ return undefined;
57
+ if (item.type === 'enum' || item.type === 'relation')
58
+ return 'checkboxes';
59
+ if (item.type === 'file')
60
+ return 'file';
61
+ return undefined;
62
+ }
63
+ default:
64
+ return undefined;
65
+ }
66
+ }
67
+ /** A model rule → a Formo rule */
68
+ export function toSpecRule(rule) {
69
+ if (typeof rule === 'string')
70
+ return rule;
71
+ const out = { rule: rule.rule };
72
+ if (rule.params)
73
+ out.params = [...rule.params];
74
+ if (rule.message)
75
+ out.message = rule.message;
76
+ return out;
77
+ }
78
+ /** A JSON Schema pattern → RegExp (unicode-aware when it can be) */
79
+ export function patternToRegExp(pattern) {
80
+ try {
81
+ return new RegExp(pattern, 'u');
82
+ }
83
+ catch {
84
+ try {
85
+ return new RegExp(pattern);
86
+ }
87
+ catch {
88
+ return undefined;
89
+ }
90
+ }
91
+ }
92
+ function optionLabel(value) {
93
+ if (typeof value === 'string')
94
+ return humanize(value);
95
+ return String(value);
96
+ }
97
+ function toOptions(options) {
98
+ return options.map((o) => {
99
+ const option = { value: o.value, label: o.label ?? optionLabel(o.value) };
100
+ if (o.disabled)
101
+ option.disabled = true;
102
+ return option;
103
+ });
104
+ }
105
+ /** Keys whose value replaces the generated one wholesale (the rest merge one level deep) */
106
+ const REPLACED = new Set(['rules', 'opts', 'filters', 'callbacks', 'val', 'fields']);
107
+ /**
108
+ * Merge definition keys over a generated spec: plain objects (`attr`, `props`,
109
+ * `errorMessages`, `classes`, `config`) merge one level, everything else —
110
+ * `rules`, `opts`, `val` included — is replaced. `options` / `value` are read
111
+ * as `opts` / `val`.
112
+ */
113
+ export function mergeSpec(base, over) {
114
+ const out = { ...base };
115
+ for (const [rawKey, value] of Object.entries(over)) {
116
+ if (value === undefined)
117
+ continue;
118
+ const key = rawKey === 'options' ? 'opts' : rawKey === 'value' ? 'val' : rawKey;
119
+ if (!REPLACED.has(key) && isPlainObject(value) && isPlainObject(out[key]))
120
+ out[key] = { ...out[key], ...value };
121
+ else
122
+ out[key] = value;
123
+ }
124
+ return out;
125
+ }
126
+ /** A function rule named for Formo (a rule's name is its function's name) */
127
+ export function namedRule(fn, name) {
128
+ const rule = (value, params, ctx) => fn(value, params, ctx);
129
+ Object.defineProperty(rule, 'name', { value: name });
130
+ return rule;
131
+ }
132
+ function derivedRules(field, ctx) {
133
+ const c = field.constraints ?? {};
134
+ const rules = [];
135
+ const isArray = field.type === 'array';
136
+ const item = isArray ? field.items : undefined;
137
+ const kind = item?.type === 'file' ? 'file' : field.type;
138
+ if (field.type === 'string' || field.type === 'text') {
139
+ if (field.format && FORMAT_RULES[field.format])
140
+ rules.push(FORMAT_RULES[field.format]);
141
+ if (c.minLength !== undefined)
142
+ rules.push(`min:${c.minLength}`);
143
+ if (c.maxLength !== undefined)
144
+ rules.push(`max:${c.maxLength}`);
145
+ if (c.pattern !== undefined) {
146
+ const regex = patternToRegExp(c.pattern);
147
+ if (regex)
148
+ rules.push({ rule: 'regex', params: [regex] });
149
+ else
150
+ ctx.warn({ path: ctx.path, code: 'invalid-pattern', message: `pattern ${JSON.stringify(c.pattern)} isn't a valid JavaScript regular expression — skipped` });
151
+ }
152
+ }
153
+ if (field.type === 'integer' || field.type === 'number') {
154
+ if (field.type === 'integer')
155
+ rules.push('integer');
156
+ if (c.min !== undefined)
157
+ rules.push(`min_value:${c.min}`);
158
+ if (c.max !== undefined)
159
+ rules.push(`max_value:${c.max}`);
160
+ if (c.exclusiveMin !== undefined)
161
+ rules.push(`gt:${c.exclusiveMin}`);
162
+ if (c.exclusiveMax !== undefined)
163
+ rules.push(`lt:${c.exclusiveMax}`);
164
+ }
165
+ if (field.type === 'boolean' && c.accepted)
166
+ rules.push('accepted');
167
+ if (kind === 'file') {
168
+ const fc = { ...(item?.constraints ?? {}), ...(isArray ? {} : c) };
169
+ if (fc.maxSize !== undefined)
170
+ rules.push(`size:${fc.maxSize}`);
171
+ if (fc.extensions?.length)
172
+ rules.push({ rule: 'ext', params: [...fc.extensions] });
173
+ if (fc.mimeTypes?.length)
174
+ rules.push({ rule: 'mimes', params: [...fc.mimeTypes] });
175
+ }
176
+ if (isArray) {
177
+ if (c.minItems !== undefined)
178
+ rules.push(`min_items:${c.minItems}`);
179
+ if (c.maxItems !== undefined)
180
+ rules.push(`max_items:${c.maxItems}`);
181
+ }
182
+ return rules;
183
+ }
184
+ function attrsFor(field) {
185
+ const attr = {};
186
+ const c = field.constraints ?? {};
187
+ if (field.placeholder)
188
+ attr.placeholder = field.placeholder;
189
+ if ((field.type === 'string' || field.type === 'text') && c.maxLength !== undefined)
190
+ attr.maxlength = c.maxLength;
191
+ if ((field.type === 'integer' || field.type === 'number') && c.step !== undefined)
192
+ attr.step = c.step;
193
+ const fileField = field.type === 'file' ? field : field.type === 'array' && field.items?.type === 'file' ? field.items : undefined;
194
+ if (fileField) {
195
+ const fc = fileField.constraints ?? {};
196
+ const accept = [...(fc.mimeTypes ?? []), ...(fc.extensions ?? []).map((e) => `.${e.replace(/^\./, '')}`)];
197
+ if (accept.length)
198
+ attr.accept = accept.join(',');
199
+ if (field.type === 'array')
200
+ attr.multiple = true;
201
+ }
202
+ return attr;
203
+ }
204
+ /** What every spec carries: label, help text, placeholder, default, messages */
205
+ function baseSpec(field) {
206
+ const spec = {};
207
+ if (field.label !== undefined)
208
+ spec.label = field.label;
209
+ if (field.description)
210
+ spec.message = field.description;
211
+ if (field.default !== undefined && !field.writeOnly)
212
+ spec.val = field.default;
213
+ if (field.messages && Object.keys(field.messages).length)
214
+ spec.errorMessages = { ...field.messages };
215
+ return spec;
216
+ }
217
+ /**
218
+ * A leaf field (anything but an object / repeatable rows) → its Formo definition.
219
+ * `undefined` when Formo can't render it (warned).
220
+ */
221
+ export function leafSpec(field, ctx) {
222
+ const ui = field.ui ?? {};
223
+ const proposed = proposeDriver(field, ctx.policy);
224
+ const driver = ctx.policy.driverFor ? ctx.policy.driverFor(field, proposed, ctx.path) : proposed;
225
+ if (!driver && !ui.driver && !ui.component) {
226
+ const what = field.type === 'array' ? `a list of ${field.items?.type ?? 'unknown'} values` : `type "${field.type}"`;
227
+ ctx.warn({
228
+ path: ctx.path,
229
+ code: 'unsupported-type',
230
+ message: `Formo has no control for ${what} — skipped. Give it one with \`fields: { '${ctx.path}': { driver | component } }\``,
231
+ });
232
+ return undefined;
233
+ }
234
+ const spec = baseSpec(field);
235
+ if (driver)
236
+ spec.driver = driver;
237
+ // Options: the app's (relations, labelled enums), else the model's
238
+ const optionSource = field.type === 'array' ? field.items : field;
239
+ const supplied = ctx.options[ctx.path];
240
+ if (supplied)
241
+ spec.opts = supplied;
242
+ else if (optionSource?.options)
243
+ spec.opts = toOptions(optionSource.options);
244
+ else if (field.type === 'relation' || optionSource?.type === 'relation') {
245
+ ctx.warn({ path: ctx.path, code: 'missing-options', message: `relation without options — pass them: \`options: { '${ctx.path}': [...] }\`` });
246
+ spec.opts = [];
247
+ }
248
+ if (driver === 'select' && spec.val === undefined)
249
+ spec.blank = true;
250
+ const attr = attrsFor(field);
251
+ if (Object.keys(attr).length)
252
+ spec.attr = attr;
253
+ // A required checkbox only has to be present — Laravel's `accepted` is "must be checked"
254
+ if (field.required && field.type !== 'boolean' && ctx.validation !== 'none')
255
+ spec.required = true;
256
+ if (field.nullable && ['string', 'text', 'date', 'datetime', 'time'].includes(field.type))
257
+ spec.filters = ['null_if_empty'];
258
+ // A list of files: its element's rules (`image`, `ext`…) check every file
259
+ const itemRules = field.type === 'array' && field.items?.type === 'file' ? (field.items.rules ?? []) : [];
260
+ const extra = [...itemRules, ...(field.rules ?? [])].map(toSpecRule);
261
+ const runtime = field[RUNTIME];
262
+ let rules = [];
263
+ if (ctx.validation === 'derived') {
264
+ rules = [...derivedRules(field, ctx), ...extra];
265
+ if (runtime?.refine)
266
+ rules.push(namedRule(runtime.refine, 'refine'));
267
+ }
268
+ else if (ctx.validation === 'schema') {
269
+ if (runtime?.validate) {
270
+ // Named `required` when the field is: Formo shows the marker, runs it first, and keeps it out of checklists
271
+ rules = [namedRule(runtime.validate, field.required ? 'required' : 'schema'), ...extra];
272
+ delete spec.required;
273
+ }
274
+ else {
275
+ rules = [...derivedRules(field, ctx), ...extra];
276
+ }
277
+ }
278
+ if (rules.length)
279
+ spec.rules = rules;
280
+ // A list's element can carry hints too (`accept` for files): the list's own win
281
+ const itemUi = field.type === 'array' ? field.items?.ui : undefined;
282
+ const withItemUi = itemUi && Object.keys(itemUi).length ? mergeSpec(spec, itemUi) : spec;
283
+ return Object.keys(ui).length ? mergeSpec(withItemUi, ui) : withItemUi;
284
+ }
285
+ /** An object → a subform */
286
+ export function groupSpec(field, children, ctx) {
287
+ const spec = baseSpec(field);
288
+ delete spec.val;
289
+ if (field.default !== undefined && isPlainObject(field.default))
290
+ spec.val = field.default;
291
+ spec.fields = children;
292
+ if (ctx.validation !== 'none' && field.rules?.length)
293
+ spec.rules = field.rules.map(toSpecRule);
294
+ const ui = field.ui ?? {};
295
+ return Object.keys(ui).length ? mergeSpec(spec, ui) : spec;
296
+ }
297
+ /** An array of objects → repeatable rows */
298
+ export function blueprintSpec(field, children, ctx) {
299
+ const spec = baseSpec(field);
300
+ delete spec.val;
301
+ if (Array.isArray(field.default))
302
+ spec.val = field.default;
303
+ spec.blueprint = true;
304
+ spec.fields = children;
305
+ const c = field.constraints ?? {};
306
+ const min = c.minItems ?? (field.required ? 1 : undefined);
307
+ if (min !== undefined)
308
+ spec.min = min;
309
+ if (c.maxItems !== undefined)
310
+ spec.max = c.maxItems;
311
+ if (ctx.validation !== 'none' && field.rules?.length)
312
+ spec.rules = field.rules.map(toSpecRule);
313
+ const ui = field.ui ?? {};
314
+ return Object.keys(ui).length ? mergeSpec(spec, ui) : spec;
315
+ }
@@ -0,0 +1,75 @@
1
+ import type { RuntimeCallback, RuntimeRule } from './ir';
2
+ /**
3
+ * What `formFromModel()` produces: a Formo form definition, framework-neutral.
4
+ *
5
+ * The subset of formo-vue's `FieldDef` that doesn't involve Vue: components and
6
+ * views are referenced by name, rules are strings / objects / functions. It is
7
+ * assignable to `FieldDef`, so it goes straight into `useFormo()`, `<FormoForm>`
8
+ * or the `Formo` builder — and a future React Native renderer can read it too.
9
+ */
10
+ /** A Standard Schema (zod, valibot, arktype…) */
11
+ export interface StandardSchemaLike {
12
+ readonly '~standard': {
13
+ readonly version: 1;
14
+ readonly vendor: string;
15
+ readonly validate: (value: unknown) => unknown;
16
+ };
17
+ }
18
+ export type SpecRule = string | RuntimeRule | {
19
+ rule: string | RuntimeRule;
20
+ params?: unknown[];
21
+ message?: string;
22
+ label?: string;
23
+ } | StandardSchemaLike;
24
+ export type SpecOption = {
25
+ value: unknown;
26
+ label: string;
27
+ disabled?: boolean;
28
+ };
29
+ export type SpecCondition = boolean | {
30
+ when: string;
31
+ is?: unknown;
32
+ not?: unknown;
33
+ filled?: boolean;
34
+ };
35
+ export interface FieldSpec {
36
+ alias?: string | number;
37
+ driver?: string;
38
+ val?: unknown;
39
+ label?: string | false | null;
40
+ message?: string;
41
+ /** `[{ value, label }]`, `['a', 'b']` or `{ value: label }` */
42
+ opts?: SpecOption[] | Array<string | number> | Record<string, string>;
43
+ blank?: boolean | string;
44
+ attr?: Record<string, unknown>;
45
+ rules?: SpecRule[];
46
+ required?: boolean;
47
+ errorMessages?: Record<string, string>;
48
+ editable?: boolean;
49
+ exclude?: SpecCondition;
50
+ filters?: string[];
51
+ callbacks?: {
52
+ pass?: RuntimeCallback[];
53
+ fail?: RuntimeCallback[];
54
+ };
55
+ config?: {
56
+ messages?: Record<string, string>;
57
+ inputRules?: Record<string, never[]>;
58
+ htmlConstraintRules?: boolean;
59
+ /** What input names start with — `false`: bare names (`email`, `address[street]`) */
60
+ namePrefix?: string | false;
61
+ request?: {
62
+ rootKey?: string;
63
+ };
64
+ };
65
+ /** A component registered by name (`createFormo({ components })`) */
66
+ component?: string;
67
+ /** A view name from the theme (`'floating'`), or `false` for the bare control */
68
+ view?: string | false;
69
+ /** Children, keyed by alias */
70
+ fields?: Record<string, FieldSpec>;
71
+ blueprint?: boolean;
72
+ min?: number;
73
+ max?: number;
74
+ [key: string]: unknown;
75
+ }
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,35 @@
1
+ import { type FormoModel, type WarningHandler } from './ir';
2
+ import type { FieldSpec } from './spec';
3
+ export interface ToFormValuesOptions {
4
+ /**
5
+ * Keep only the values the form has fields for — the result of `formFromModel()`,
6
+ * or a builder (`Formo.fromModel()`). Without it, every model field's value
7
+ * is kept, and values of fields the form leaves out would be submitted too.
8
+ */
9
+ form?: FieldSpec | {
10
+ toSchema(): unknown;
11
+ };
12
+ onWarning?: WarningHandler;
13
+ }
14
+ /**
15
+ * A record from your API → the form's values:
16
+ *
17
+ * - dates / datetimes / times in the shape their inputs need
18
+ * (`2024-05-01T09:30:00.000000Z` → `2024-05-01`, or `2024-05-01T11:30` in local time)
19
+ * - relations → their keys (`{ role: { id: 3 } }` → `role_id: 3`, `tags: [{ id: 1 }]` → `[1]`)
20
+ * - numbers from decimal strings, booleans from `0` / `1`
21
+ * - write-only fields (passwords) and files are never pre-filled; keys the model doesn't have are dropped
22
+ * - with `form`, only the values of the fields that form has (so `except` / `only` hold on submit)
23
+ *
24
+ * const def = formFromModel(model, { mode: 'update', except: ['role'] })
25
+ * useFormo(def, { initialValues: toFormValues(model, props.user, { form: def }) })
26
+ *
27
+ * (`formFromModel(model, { values: props.user })` does both at once.)
28
+ */
29
+ export declare function toFormValues(model: FormoModel | string, record: Record<string, any> | null | undefined, options?: ToFormValuesOptions): Record<string, any>;
30
+ type Children = Record<string, FieldSpec> | Array<FieldSpec & {
31
+ alias?: string | number;
32
+ }>;
33
+ /** Values restricted to the fields a form definition has (keyed or list `fields`, subforms, rows) */
34
+ export declare function pickFormValues(values: Record<string, any>, fields: Children): Record<string, any>;
35
+ export {};
@@ -0,0 +1,151 @@
1
+ import { isPlainObject } from '../core/utils';
2
+ import { parseModel } from './ir';
3
+ /**
4
+ * A record from your API → the form's values:
5
+ *
6
+ * - dates / datetimes / times in the shape their inputs need
7
+ * (`2024-05-01T09:30:00.000000Z` → `2024-05-01`, or `2024-05-01T11:30` in local time)
8
+ * - relations → their keys (`{ role: { id: 3 } }` → `role_id: 3`, `tags: [{ id: 1 }]` → `[1]`)
9
+ * - numbers from decimal strings, booleans from `0` / `1`
10
+ * - write-only fields (passwords) and files are never pre-filled; keys the model doesn't have are dropped
11
+ * - with `form`, only the values of the fields that form has (so `except` / `only` hold on submit)
12
+ *
13
+ * const def = formFromModel(model, { mode: 'update', except: ['role'] })
14
+ * useFormo(def, { initialValues: toFormValues(model, props.user, { form: def }) })
15
+ *
16
+ * (`formFromModel(model, { values: props.user })` does both at once.)
17
+ */
18
+ export function toFormValues(model, record, options = {}) {
19
+ const parsed = parseModel(model, options.onWarning);
20
+ if (!record)
21
+ return {};
22
+ const values = readFields(parsed.fields, record);
23
+ if (!options.form)
24
+ return values;
25
+ const form = 'toSchema' in options.form && typeof options.form.toSchema === 'function' ? options.form.toSchema() : options.form;
26
+ return pickFormValues(values, form.fields ?? {});
27
+ }
28
+ /** Values restricted to the fields a form definition has (keyed or list `fields`, subforms, rows) */
29
+ export function pickFormValues(values, fields) {
30
+ const out = {};
31
+ const entries = Array.isArray(fields)
32
+ ? fields.filter((f) => f.alias !== undefined).map((f) => [String(f.alias), f])
33
+ : Object.entries(fields);
34
+ for (const [alias, spec] of entries) {
35
+ if (!(alias in values))
36
+ continue;
37
+ const value = values[alias];
38
+ const children = spec.fields;
39
+ if (spec.blueprint && children && Array.isArray(value)) {
40
+ out[alias] = value.map((row) => (isPlainObject(row) ? pickFormValues(row, children) : row));
41
+ }
42
+ else if (children && isPlainObject(value)) {
43
+ out[alias] = pickFormValues(value, children);
44
+ }
45
+ else
46
+ out[alias] = value;
47
+ }
48
+ return out;
49
+ }
50
+ const pad = (n) => String(n).padStart(2, '0');
51
+ function toDate(value) {
52
+ if (typeof value === 'string') {
53
+ const m = value.match(/^(\d{4}-\d{2}-\d{2})/);
54
+ if (m)
55
+ return m[1];
56
+ }
57
+ const date = value instanceof Date ? value : new Date(String(value));
58
+ if (Number.isNaN(date.getTime()))
59
+ return undefined;
60
+ return `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())}`;
61
+ }
62
+ /** `<input type="datetime-local">` wants local time without seconds' fraction or zone */
63
+ function toDateTime(value) {
64
+ if (typeof value === 'string' && /^\d{4}-\d{2}-\d{2}[T ]\d{2}:\d{2}(:\d{2})?$/.test(value)) {
65
+ // No zone: already local
66
+ return value.replace(' ', 'T').slice(0, 16);
67
+ }
68
+ const date = value instanceof Date ? value : new Date(String(value));
69
+ if (Number.isNaN(date.getTime()))
70
+ return undefined;
71
+ return `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())}T${pad(date.getHours())}:${pad(date.getMinutes())}`;
72
+ }
73
+ function toTime(value) {
74
+ const m = String(value).match(/(?:^|T|\s)(\d{2}:\d{2})(?::\d{2})?/);
75
+ return m ? m[1] : undefined;
76
+ }
77
+ function toNumber(value) {
78
+ if (typeof value === 'string' && value.trim() !== '' && !Number.isNaN(Number(value)))
79
+ return Number(value);
80
+ return value;
81
+ }
82
+ function toBoolean(value) {
83
+ if (value === 1 || value === '1' || value === 'true')
84
+ return true;
85
+ if (value === 0 || value === '0' || value === 'false' || value === '')
86
+ return false;
87
+ return value;
88
+ }
89
+ const keyOf = (field) => field.relation?.key ?? 'id';
90
+ function relationValue(field, value) {
91
+ if (Array.isArray(value))
92
+ return value.map((v) => (isPlainObject(v) ? v[keyOf(field)] : v));
93
+ return isPlainObject(value) ? value[keyOf(field)] : value;
94
+ }
95
+ function readValue(field, value) {
96
+ if (value === null || value === undefined)
97
+ return undefined;
98
+ switch (field.type) {
99
+ case 'date':
100
+ return toDate(value);
101
+ case 'datetime':
102
+ return toDateTime(value);
103
+ case 'time':
104
+ return toTime(value);
105
+ case 'integer':
106
+ case 'number':
107
+ return toNumber(value);
108
+ case 'boolean':
109
+ return toBoolean(value);
110
+ case 'relation':
111
+ return relationValue(field, value);
112
+ case 'file':
113
+ return undefined;
114
+ case 'object':
115
+ return isPlainObject(value) ? readFields(field.fields ?? [], value) : undefined;
116
+ case 'array': {
117
+ if (!Array.isArray(value) || !field.items)
118
+ return undefined;
119
+ const item = field.items;
120
+ if (item.type === 'file')
121
+ return undefined;
122
+ return value.map((v) => readValue(item, v)).filter((v) => v !== undefined);
123
+ }
124
+ case 'enum':
125
+ // A number column behind string options (or the reverse): keep the option's type
126
+ if (field.options?.length && !field.options.some((o) => o.value === value)) {
127
+ const match = field.options.find((o) => String(o.value) === String(value));
128
+ if (match)
129
+ return match.value;
130
+ }
131
+ return value;
132
+ default:
133
+ return value;
134
+ }
135
+ }
136
+ function readFields(fields, record) {
137
+ const out = {};
138
+ for (const field of fields) {
139
+ if (field.writeOnly)
140
+ continue;
141
+ let raw = record[field.name];
142
+ // `role_id` missing, but the relation was loaded: `role: { id: 3 }`
143
+ if (raw === undefined && field.name.endsWith('_id') && isPlainObject(record[field.name.slice(0, -3)])) {
144
+ raw = record[field.name.slice(0, -3)][keyOf(field)];
145
+ }
146
+ const value = readValue(field, raw);
147
+ if (value !== undefined)
148
+ out[field.name] = value;
149
+ }
150
+ return out;
151
+ }