@mapomodule/form 2.0.0-beta.8 → 2.0.0-experimental.1

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 (145) hide show
  1. package/README.md +38 -119
  2. package/dist/index.d.mts +2 -1
  3. package/dist/index.d.ts +3 -1
  4. package/dist/index.d.ts.map +1 -1
  5. package/dist/index.mjs +1 -0
  6. package/dist/module.d.mts +1 -0
  7. package/dist/module.d.ts.map +1 -1
  8. package/dist/module.json +1 -1
  9. package/dist/module.mjs +9 -0
  10. package/dist/runtime/components/MapoFocusPortal.vue +9 -2
  11. package/dist/runtime/components/MapoFocusPortal.vue.d.ts.map +1 -1
  12. package/dist/runtime/components/MapoForm.vue +28 -6
  13. package/dist/runtime/components/MapoForm.vue.d.ts +13 -1
  14. package/dist/runtime/components/MapoForm.vue.d.ts.map +1 -1
  15. package/dist/runtime/components/MapoFormAnnotation.vue +79 -0
  16. package/dist/runtime/components/MapoFormAnnotation.vue.d.ts +27 -0
  17. package/dist/runtime/components/MapoFormAnnotation.vue.d.ts.map +1 -0
  18. package/dist/runtime/components/MapoFormAnnotationBadges.vue +28 -0
  19. package/dist/runtime/components/MapoFormAnnotationBadges.vue.d.ts +13 -0
  20. package/dist/runtime/components/MapoFormAnnotationBadges.vue.d.ts.map +1 -0
  21. package/dist/runtime/components/MapoFormField.vue +47 -11
  22. package/dist/runtime/components/MapoFormField.vue.d.ts +15 -9
  23. package/dist/runtime/components/MapoFormField.vue.d.ts.map +1 -1
  24. package/dist/runtime/components/MapoFormGroup.vue +18 -2
  25. package/dist/runtime/components/MapoFormGroup.vue.d.ts.map +1 -1
  26. package/dist/runtime/components/MapoFormTabs.vue +50 -8
  27. package/dist/runtime/components/MapoFormTabs.vue.d.ts.map +1 -1
  28. package/dist/runtime/components/fields/MapoMediaField.vue +5 -3
  29. package/dist/runtime/components/fields/MapoMediaField.vue.d.ts.map +1 -1
  30. package/dist/runtime/components/fields/MapoMediaM2mField.vue +3 -2
  31. package/dist/runtime/components/fields/MapoMediaM2mField.vue.d.ts.map +1 -1
  32. package/dist/runtime/components/fields/MapoRepeater.vue +73 -14
  33. package/dist/runtime/components/fields/MapoRepeater.vue.d.ts.map +1 -1
  34. package/dist/runtime/components/fields/MapoRepeaterBlockPicker.vue +167 -0
  35. package/dist/runtime/components/fields/MapoRepeaterBlockPicker.vue.d.ts +20 -0
  36. package/dist/runtime/components/fields/MapoRepeaterBlockPicker.vue.d.ts.map +1 -0
  37. package/dist/runtime/components/fields/MapoRepeaterItem.vue +46 -10
  38. package/dist/runtime/components/fields/MapoRepeaterItem.vue.d.ts +6 -2
  39. package/dist/runtime/components/fields/MapoRepeaterItem.vue.d.ts.map +1 -1
  40. package/dist/runtime/components/fields/MapoWygEditor.vue +19 -13
  41. package/dist/runtime/components/fields/MapoWygEditor.vue.d.ts.map +1 -1
  42. package/dist/runtime/composables/useFieldAnnotation.d.ts +18 -0
  43. package/dist/runtime/composables/useFieldAnnotation.d.ts.map +1 -0
  44. package/dist/runtime/composables/useFieldAnnotation.js +16 -0
  45. package/dist/runtime/composables/useFocusMode.d.ts +3 -1
  46. package/dist/runtime/composables/useFocusMode.d.ts.map +1 -1
  47. package/dist/runtime/composables/useFormFromSchema.d.ts +23 -1
  48. package/dist/runtime/composables/useFormFromSchema.d.ts.map +1 -1
  49. package/dist/runtime/composables/useFormFromSchema.js +173 -32
  50. package/dist/runtime/composables/useMapoForm.d.ts +21 -3
  51. package/dist/runtime/composables/useMapoForm.d.ts.map +1 -1
  52. package/dist/runtime/composables/useMapoForm.js +49 -15
  53. package/dist/runtime/types/annotation.d.ts +43 -0
  54. package/dist/runtime/types/annotation.d.ts.map +1 -0
  55. package/dist/runtime/types/annotation.js +0 -0
  56. package/dist/runtime/types/descriptor.d.ts +81 -4
  57. package/dist/runtime/types/descriptor.d.ts.map +1 -1
  58. package/dist/runtime/types/index.d.ts +2 -1
  59. package/dist/runtime/types/index.d.ts.map +1 -1
  60. package/dist/runtime/utils/annotations.d.ts +40 -0
  61. package/dist/runtime/utils/annotations.d.ts.map +1 -0
  62. package/dist/runtime/utils/annotations.js +78 -0
  63. package/dist/runtime/utils/draft.d.ts +21 -0
  64. package/dist/runtime/utils/draft.d.ts.map +1 -0
  65. package/dist/runtime/utils/draft.js +108 -0
  66. package/dist/runtime/utils/fieldComponent.d.ts +9 -0
  67. package/dist/runtime/utils/fieldComponent.d.ts.map +1 -0
  68. package/dist/runtime/utils/fieldComponent.js +12 -0
  69. package/dist/runtime/utils/fieldFocus.d.ts +24 -0
  70. package/dist/runtime/utils/fieldFocus.d.ts.map +1 -0
  71. package/dist/runtime/utils/fieldFocus.js +41 -0
  72. package/dist/runtime/utils/fieldsToJsonSchema.d.ts +38 -0
  73. package/dist/runtime/utils/fieldsToJsonSchema.d.ts.map +1 -0
  74. package/dist/runtime/utils/fieldsToJsonSchema.js +248 -0
  75. package/dist/runtime/utils/repeaterTemplates.d.ts +26 -0
  76. package/dist/runtime/utils/repeaterTemplates.d.ts.map +1 -0
  77. package/dist/runtime/utils/repeaterTemplates.js +51 -0
  78. package/dist/runtime/utils/reveal.d.ts +34 -0
  79. package/dist/runtime/utils/reveal.d.ts.map +1 -0
  80. package/dist/runtime/utils/reveal.js +29 -0
  81. package/dist/runtime/utils/tabVisibility.d.ts +18 -0
  82. package/dist/runtime/utils/tabVisibility.d.ts.map +1 -0
  83. package/dist/runtime/utils/tabVisibility.js +18 -0
  84. package/package.json +5 -5
  85. package/src/__tests__/MapoFocusPortal.component.test.ts +97 -0
  86. package/src/__tests__/MapoForm.component.test.ts +79 -0
  87. package/src/__tests__/MapoFormAnnotation.component.test.ts +244 -0
  88. package/src/__tests__/MapoFormField.component.test.ts +508 -0
  89. package/src/__tests__/MapoFormGroup.component.test.ts +141 -0
  90. package/src/__tests__/MapoFormTabs.component.test.ts +254 -0
  91. package/src/__tests__/MapoRepeaterItem.component.test.ts +286 -0
  92. package/src/__tests__/MapoWygEditor.component.test.ts +95 -0
  93. package/src/__tests__/annotations.test.ts +227 -0
  94. package/src/__tests__/article.schema.json +193 -0
  95. package/src/__tests__/camomillaRoundTrip.test.ts +73 -0
  96. package/src/__tests__/draft.test.ts +221 -0
  97. package/src/__tests__/fieldComponent.test.ts +31 -0
  98. package/src/__tests__/fieldExtensions.test.ts +63 -0
  99. package/src/__tests__/fieldFocus.test.ts +178 -0
  100. package/src/__tests__/fieldsToJsonSchema.test.ts +630 -0
  101. package/src/__tests__/headlessRenderer.ts +85 -0
  102. package/src/__tests__/repeaterTemplates.test.ts +154 -0
  103. package/src/__tests__/reveal.test.ts +89 -0
  104. package/src/__tests__/schemaSources.test.ts +132 -0
  105. package/src/__tests__/tabVisibility.test.ts +102 -0
  106. package/src/__tests__/useFormFromSchema.test.ts +387 -0
  107. package/src/__tests__/useMapoForm.test.ts +213 -2
  108. package/src/index.ts +9 -0
  109. package/src/module.ts +9 -0
  110. package/src/runtime/components/MapoFocusPortal.vue +15 -2
  111. package/src/runtime/components/MapoForm.vue +47 -4
  112. package/src/runtime/components/MapoFormAnnotation.vue +113 -0
  113. package/src/runtime/components/MapoFormAnnotationBadges.vue +41 -0
  114. package/src/runtime/components/MapoFormField.vue +72 -11
  115. package/src/runtime/components/MapoFormGroup.vue +20 -2
  116. package/src/runtime/components/MapoFormTabs.vue +64 -8
  117. package/src/runtime/components/fields/MapoMediaField.vue +5 -3
  118. package/src/runtime/components/fields/MapoMediaM2mField.vue +3 -2
  119. package/src/runtime/components/fields/MapoRepeater.vue +82 -14
  120. package/src/runtime/components/fields/MapoRepeaterBlockPicker.vue +188 -0
  121. package/src/runtime/components/fields/MapoRepeaterItem.vue +56 -8
  122. package/src/runtime/components/fields/MapoWygEditor.vue +22 -14
  123. package/src/runtime/composables/useFieldAnnotation.ts +38 -0
  124. package/src/runtime/composables/useFocusMode.ts +7 -1
  125. package/src/runtime/composables/useFormFromSchema.ts +306 -42
  126. package/src/runtime/composables/useMapoForm.ts +103 -23
  127. package/src/runtime/types/annotation.ts +53 -0
  128. package/src/runtime/types/descriptor.ts +94 -4
  129. package/src/runtime/types/index.ts +10 -0
  130. package/src/runtime/utils/annotations.ts +169 -0
  131. package/src/runtime/utils/draft.ts +158 -0
  132. package/src/runtime/utils/fieldComponent.ts +34 -0
  133. package/src/runtime/utils/fieldFocus.ts +73 -0
  134. package/src/runtime/utils/fieldsToJsonSchema.ts +405 -0
  135. package/src/runtime/utils/repeaterTemplates.ts +103 -0
  136. package/src/runtime/utils/reveal.ts +68 -0
  137. package/src/runtime/utils/tabVisibility.ts +44 -0
  138. package/dist/__tests__/__mocks__/nuxt-imports.d.ts +0 -4
  139. package/dist/__tests__/__mocks__/nuxt-imports.d.ts.map +0 -1
  140. package/dist/__tests__/registry.test.d.ts +0 -2
  141. package/dist/__tests__/registry.test.d.ts.map +0 -1
  142. package/dist/__tests__/useFormFromSchema.test.d.ts +0 -2
  143. package/dist/__tests__/useFormFromSchema.test.d.ts.map +0 -1
  144. package/dist/__tests__/useMapoForm.test.d.ts +0 -2
  145. package/dist/__tests__/useMapoForm.test.d.ts.map +0 -1
@@ -0,0 +1,405 @@
1
+ import { ATTRS_KEYWORD, FIELD_KEYWORD } from "@mapomodule/utils";
2
+ import type { JSONSchema } from "@mapomodule/utils";
3
+ import {
4
+ KEYWORD_ATTRS,
5
+ TEMPLATE_PROPERTY,
6
+ isUnsafeAttr,
7
+ schemaFieldType,
8
+ } from "../composables/useFormFromSchema.js";
9
+ import type { AnyFieldDescriptor, RepeaterTemplate } from "../types/index.js";
10
+
11
+ // `any` accepts descriptors typed against any model: the schema reads only
12
+ // what a descriptor says about its field, never the model type.
13
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
14
+ type Field = AnyFieldDescriptor<any>;
15
+
16
+ /** Options of {@link fieldsToJsonSchema}. */
17
+ export interface FieldsToJsonSchemaOptions {
18
+ /**
19
+ * Called for every field, those of repeaters and templates included, with the
20
+ * schema written for it. Return the schema to use, or `undefined` to leave
21
+ * the field out. This is how a property declared with `FieldExtensions`
22
+ * reaches the schema. `x-mapo-field` is decided afterwards, on the schema
23
+ * returned.
24
+ *
25
+ * @example
26
+ * property: (schema, field) =>
27
+ * field.help ? { ...schema, description: field.help } : schema
28
+ */
29
+ property?: (
30
+ schema: JSONSchema,
31
+ // The full name, rather than `Field`, is what editors and the MCP show.
32
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
33
+ field: AnyFieldDescriptor<any>,
34
+ ) => JSONSchema | undefined;
35
+ }
36
+
37
+ /** What every step of the writing needs. */
38
+ interface WriteContext {
39
+ options: FieldsToJsonSchemaOptions;
40
+ /** The repeaters being written, outermost first: one that contains itself stops. */
41
+ path: ReadonlySet<Field>;
42
+ }
43
+
44
+ /** The value of each built-in type that has a fixed shape. */
45
+ const VALUE_SCHEMAS: Readonly<Record<string, JSONSchema>> = {
46
+ text: { type: "string" },
47
+ textarea: { type: "string", format: "textarea" },
48
+ email: { type: "string", format: "email" },
49
+ url: { type: "string", format: "uri" },
50
+ number: { type: "number" },
51
+ slider: { type: "number" },
52
+ boolean: { type: "boolean" },
53
+ switch: { type: "boolean" },
54
+ color: { type: "string", format: "color" },
55
+ file: { type: "string", format: "binary" },
56
+ date: { type: "string", format: "date" },
57
+ time: { type: "string", format: "time" },
58
+ datetime: { type: "string", format: "date-time" },
59
+ editor: { type: "string", contentMediaType: "text/html" },
60
+ // What the seo accessor stores.
61
+ seo: {
62
+ type: "object",
63
+ properties: {
64
+ title: { type: "string" },
65
+ description: { type: "string" },
66
+ permalink: { type: "string" },
67
+ },
68
+ },
69
+ map: {
70
+ type: "object",
71
+ properties: { lat: { type: "number" }, lng: { type: "number" } },
72
+ },
73
+ media: { type: "object" },
74
+ "media-m2m": { type: "array", items: { type: "object" } },
75
+ "enhanced-media": {
76
+ type: "object",
77
+ properties: {
78
+ media: { type: "object" },
79
+ alt: { type: "string" },
80
+ caption: { type: "string" },
81
+ },
82
+ },
83
+ };
84
+
85
+ /** Marks a value JSON cannot hold. */
86
+ const SKIP = Symbol("skip");
87
+
88
+ /**
89
+ * A copy of `value` made of JSON only, or {@link SKIP} when it holds a
90
+ * function, a component, a class instance, a cycle or another value JSON
91
+ * cannot hold. Object entries set to `undefined` are dropped, as
92
+ * `JSON.stringify` does.
93
+ */
94
+ function toPlain(value: unknown, ancestors: Set<object> = new Set()): unknown {
95
+ if (value === null) return null;
96
+ switch (typeof value) {
97
+ case "string":
98
+ case "boolean":
99
+ return value;
100
+ case "number":
101
+ return Number.isFinite(value) ? value : SKIP;
102
+ case "object": {
103
+ if (ancestors.has(value)) return SKIP;
104
+ ancestors.add(value);
105
+ const plain = toPlainObject(value, ancestors);
106
+ ancestors.delete(value);
107
+ return plain;
108
+ }
109
+ default:
110
+ return SKIP;
111
+ }
112
+ }
113
+
114
+ function toPlainObject(value: object, ancestors: Set<object>): unknown {
115
+ if (Array.isArray(value)) {
116
+ const items = value.map((item) => toPlain(item, ancestors));
117
+ return items.includes(SKIP) ? SKIP : items;
118
+ }
119
+ const proto = Object.getPrototypeOf(value);
120
+ if (proto !== Object.prototype && proto !== null) return SKIP;
121
+ const entries: [string, unknown][] = [];
122
+ for (const [key, entry] of Object.entries(value)) {
123
+ if (entry === undefined) continue;
124
+ const plain = toPlain(entry, ancestors);
125
+ if (plain === SKIP) return SKIP;
126
+ entries.push([key, plain]);
127
+ }
128
+ return Object.fromEntries(entries);
129
+ }
130
+
131
+ /**
132
+ * The entries of `record` that JSON can hold, each copied with {@link toPlain};
133
+ * the others, and the names {@link isUnsafeAttr} rejects, are left out one by
134
+ * one. `undefined` when none is left.
135
+ */
136
+ function plainEntries(
137
+ record: Record<string, unknown>,
138
+ ): Record<string, unknown> | undefined {
139
+ const entries = Object.entries(record)
140
+ .filter(([key]) => !isUnsafeAttr(key))
141
+ .map(([key, value]): [string, unknown] => [key, toPlain(value)])
142
+ .filter(([, value]) => value !== SKIP);
143
+ return entries.length ? Object.fromEntries(entries) : undefined;
144
+ }
145
+
146
+ /** Removes `name` from `attrs` and returns its value. */
147
+ function take(attrs: Record<string, unknown>, name: string): unknown {
148
+ const value = attrs[name];
149
+ delete attrs[name];
150
+ return value;
151
+ }
152
+
153
+ /** The JSON type every choice value shares, if any. */
154
+ function sharedType(values: unknown[]): string | undefined {
155
+ const types = new Set(
156
+ values.map((value) => (value === null ? "null" : typeof value)),
157
+ );
158
+ const [only] = [...types];
159
+ const isShared = types.size === 1;
160
+ if (!isShared) return undefined;
161
+ return only === "string" || only === "number" || only === "boolean"
162
+ ? only
163
+ : undefined;
164
+ }
165
+
166
+ interface Choice {
167
+ value: unknown;
168
+ label: string;
169
+ /** The other properties of the choice, such as `icon` or `disabled`. */
170
+ extras?: Record<string, unknown>;
171
+ }
172
+
173
+ /** One choice of a select, read as the select reads it: `text` before `label`. */
174
+ function toChoice(item: unknown): Choice {
175
+ if (typeof item !== "object" || item === null)
176
+ return { value: item, label: String(item) };
177
+ const { text, label, value, ...rest } = item as Record<string, unknown>;
178
+ return {
179
+ value: toPlain(value),
180
+ label: String(text ?? label ?? value),
181
+ extras: plainEntries(rest),
182
+ };
183
+ }
184
+
185
+ /**
186
+ * The choices of a select, from `attrs.items` (strings or `{ label, value }`)
187
+ * or `attrs.options` (`{ text, value }`): an `enum`, or `oneOf` of
188
+ * `{ const, title }` when a label differs from its value or a choice has other
189
+ * properties. A choice whose value JSON cannot hold is left out.
190
+ */
191
+ function choicesSchema(list: unknown): JSONSchema {
192
+ if (!Array.isArray(list)) return {};
193
+ const choices = list.map(toChoice).filter((choice) => choice.value !== SKIP);
194
+ if (choices.length === 0) return {};
195
+ const values = choices.map((choice) => choice.value);
196
+ const type = sharedType(values);
197
+ const isLabeled = choices.some(
198
+ (choice) => choice.label !== String(choice.value) || choice.extras,
199
+ );
200
+ return {
201
+ ...(type ? { type } : {}),
202
+ ...(isLabeled
203
+ ? {
204
+ oneOf: choices.map((choice) => ({
205
+ const: choice.value,
206
+ title: choice.label,
207
+ ...(choice.extras ? { [ATTRS_KEYWORD]: choice.extras } : {}),
208
+ })),
209
+ }
210
+ : { enum: values }),
211
+ };
212
+ }
213
+
214
+ function selectSchema(attrs: Record<string, unknown>): JSONSchema {
215
+ // The select shows `items` when it has both.
216
+ const items = take(attrs, "items");
217
+ const options = take(attrs, "options");
218
+ const choices = choicesSchema(items ?? options);
219
+ const isMultiple = take(attrs, "multiple") === true;
220
+ return isMultiple
221
+ ? { type: "array", items: choices, uniqueItems: true }
222
+ : choices;
223
+ }
224
+
225
+ function relationSchema(
226
+ type: string,
227
+ attrs: Record<string, unknown>,
228
+ ): JSONSchema {
229
+ const endpoint = take(attrs, "endpoint");
230
+ const isMultiple = take(attrs, "multiple") === true || type === "m2m";
231
+ return {
232
+ type: "relation",
233
+ ...(typeof endpoint === "string" ? { endpoint } : {}),
234
+ ...(isMultiple ? { multiple: true } : {}),
235
+ };
236
+ }
237
+
238
+ function templateSchema(
239
+ key: string,
240
+ template: AnyFieldDescriptor[] | RepeaterTemplate,
241
+ ctx: WriteContext,
242
+ ): JSONSchema {
243
+ const normalized: RepeaterTemplate = Array.isArray(template)
244
+ ? { fields: template }
245
+ : template;
246
+ const { fields, label, description, ...presentation } = normalized;
247
+ const body = objectSchema(fields, ctx);
248
+ // Icon, image, wireframe and category: no keyword expresses them.
249
+ const own = plainEntries(presentation);
250
+ return {
251
+ type: "object",
252
+ ...(label ? { title: label } : {}),
253
+ ...(description ? { description } : {}),
254
+ properties: {
255
+ [TEMPLATE_PROPERTY]: { const: key },
256
+ ...body.properties,
257
+ },
258
+ required: [TEMPLATE_PROPERTY, ...(body.required ?? [])],
259
+ ...(own ? { [ATTRS_KEYWORD]: own } : {}),
260
+ };
261
+ }
262
+
263
+ function repeaterSchema(
264
+ field: Field,
265
+ attrs: Record<string, unknown>,
266
+ ctx: WriteContext,
267
+ ): JSONSchema {
268
+ const templates = take(attrs, "templates") as
269
+ | Record<string, AnyFieldDescriptor[] | RepeaterTemplate>
270
+ | undefined;
271
+ // A repeater that contains itself is written once: inside, its items are empty.
272
+ if (ctx.path.has(field)) {
273
+ return { type: "array", items: { type: "object", properties: {} } };
274
+ }
275
+ const inner: WriteContext = { ...ctx, path: new Set([...ctx.path, field]) };
276
+ const hasTemplates = !!templates && Object.keys(templates).length > 0;
277
+ if (!hasTemplates) {
278
+ const fields = (field as { fields?: Field[] }).fields ?? [];
279
+ return { type: "array", items: objectSchema(fields, inner) };
280
+ }
281
+ return {
282
+ type: "array",
283
+ items: {
284
+ oneOf: Object.entries(templates).map(([key, template]) =>
285
+ templateSchema(key, template, inner),
286
+ ),
287
+ discriminator: { propertyName: TEMPLATE_PROPERTY },
288
+ },
289
+ };
290
+ }
291
+
292
+ /** The keywords of the value, removing from `attrs` those they express. */
293
+ function valueSchema(
294
+ field: Field,
295
+ attrs: Record<string, unknown>,
296
+ ctx: WriteContext,
297
+ ): JSONSchema {
298
+ const type = String(field.type);
299
+ const keywords: JSONSchema = {};
300
+ for (const [attr, keyword] of Object.entries(KEYWORD_ATTRS[type] ?? {})) {
301
+ const value = toPlain(take(attrs, attr));
302
+ if (value !== SKIP) keywords[keyword] = value;
303
+ }
304
+
305
+ let schema: JSONSchema;
306
+ if (type === "select") schema = selectSchema(attrs);
307
+ else if (type === "fks" || type === "m2m")
308
+ schema = relationSchema(type, attrs);
309
+ else if (type === "repeater") schema = repeaterSchema(field, attrs, ctx);
310
+ else if (VALUE_SCHEMAS[type]) schema = structuredClone(VALUE_SCHEMAS[type]);
311
+ // A generic object read from a schema keeps its shape.
312
+ else if (type.startsWith("object:")) schema = { type: "object" };
313
+ // A custom type: Mapo does not know its value.
314
+ else schema = {};
315
+
316
+ return { ...schema, ...keywords };
317
+ }
318
+
319
+ function fieldSchema(field: Field, ctx: WriteContext): JSONSchema {
320
+ // A copy: `valueSchema` removes the attrs it turns into keywords.
321
+ const attrs = {
322
+ ...((field as { attrs?: Record<string, unknown> }).attrs ?? {}),
323
+ };
324
+
325
+ const schema: JSONSchema = {
326
+ ...(field.label ? { title: field.label } : {}),
327
+ ...valueSchema(field, attrs, ctx),
328
+ ...(field.readonly ? { readOnly: true } : {}),
329
+ // A field kept out of drafts holds a secret, such as a password: JSON
330
+ // Schema marks a value the backend never sends back as writeOnly.
331
+ ...(field.noDraft ? { writeOnly: true } : {}),
332
+ ...(field.translatable ? { translatable: true } : {}),
333
+ };
334
+
335
+ const rest = plainEntries(attrs);
336
+ if (rest) schema[ATTRS_KEYWORD] = rest;
337
+ return schema;
338
+ }
339
+
340
+ /**
341
+ * Names the type with `x-mapo-field` when the other keywords would read back
342
+ * as another one, unless the schema already names one.
343
+ */
344
+ function markType(schema: JSONSchema, field: Field): JSONSchema {
345
+ const type = String(field.type);
346
+ const isMarked = schema[FIELD_KEYWORD] !== undefined;
347
+ if (isMarked) return schema;
348
+ const readsBackAs = schemaFieldType(schema, String(field.key));
349
+ return readsBackAs === type ? schema : { ...schema, [FIELD_KEYWORD]: type };
350
+ }
351
+
352
+ function objectSchema(fields: readonly Field[], ctx: WriteContext): JSONSchema {
353
+ const properties: [string, JSONSchema][] = [];
354
+ const required: string[] = [];
355
+ const written = new Set<string>();
356
+
357
+ for (const field of fields) {
358
+ const key = String(field.key);
359
+ // One property per key: the first field written with that key wins.
360
+ if (written.has(key)) continue;
361
+
362
+ const schema = fieldSchema(field, ctx);
363
+ const final = ctx.options.property
364
+ ? ctx.options.property(schema, field)
365
+ : schema;
366
+ if (!final) continue;
367
+
368
+ written.add(key);
369
+ properties.push([key, markType(final, field)]);
370
+ if (field.required) required.push(key);
371
+ }
372
+
373
+ return {
374
+ type: "object",
375
+ properties: Object.fromEntries(properties),
376
+ ...(required.length ? { required } : {}),
377
+ };
378
+ }
379
+
380
+ /**
381
+ * Describes a form as a JSON Schema: one property per field, named by the
382
+ * field key, in the dialect `useFormFromSchema()` reads. The schema reads back
383
+ * into equivalent descriptors.
384
+ *
385
+ * Each property carries the field's type, label, required, readonly,
386
+ * translatable and `noDraft` flags, and its `attrs`: as standard keywords
387
+ * (`minimum`, `maxLength`, `enum`…) where one exists, in `x-mapo-attrs`
388
+ * otherwise. Layout (`tab`, `group`, `cols`…), functions (`visible`,
389
+ * `validate`…) and components (`is`) are not written.
390
+ *
391
+ * @param fields The descriptors, as passed to `MapoForm`.
392
+ * @param options `property` customises the schema of each field.
393
+ * @returns A JSON Schema of type `object`.
394
+ *
395
+ * @example
396
+ * const schema = fieldsToJsonSchema(fields);
397
+ * const same = useFormFromSchema(schema); // equivalent descriptors
398
+ */
399
+ export function fieldsToJsonSchema(
400
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
401
+ fields: readonly AnyFieldDescriptor<any>[],
402
+ options: FieldsToJsonSchemaOptions = {},
403
+ ): JSONSchema {
404
+ return objectSchema(fields, { options, path: new Set() });
405
+ }
@@ -0,0 +1,103 @@
1
+ import type {
2
+ AnyFieldDescriptor,
3
+ NormalizedRepeaterTemplate,
4
+ RepeaterDescriptor,
5
+ RepeaterImageFit,
6
+ RepeaterTemplate,
7
+ } from "../types/descriptor.js";
8
+
9
+ /** Above this many templates, `picker: "auto"` switches from the dropdown to the modal. */
10
+ export const MODAL_PICKER_THRESHOLD = 3;
11
+
12
+ /**
13
+ * Turns `attrs.templates` into a list with defaults applied. A bare field array
14
+ * becomes a template whose label is its key. `imageFit` falls back to the
15
+ * repeater's `templateImageFit`, then to `contain`, so a preview is never cropped
16
+ * unless someone asks for it.
17
+ */
18
+ export function normalizeTemplates(
19
+ templates: NonNullable<RepeaterDescriptor["attrs"]>["templates"],
20
+ defaultImageFit: RepeaterImageFit = "contain",
21
+ ): NormalizedRepeaterTemplate[] {
22
+ return Object.entries(templates ?? {}).map(([key, tpl]) => {
23
+ const meta: Partial<RepeaterTemplate> = Array.isArray(tpl) ? {} : tpl;
24
+ return {
25
+ key,
26
+ label: meta.label ?? key,
27
+ description: meta.description,
28
+ icon: meta.icon,
29
+ image: meta.image,
30
+ imageFit: meta.imageFit ?? defaultImageFit,
31
+ wireframe: meta.wireframe,
32
+ category: meta.category,
33
+ fields: Array.isArray(tpl) ? tpl : (tpl.fields ?? []),
34
+ };
35
+ });
36
+ }
37
+
38
+ /** Whether the block picker modal replaces the dropdown for this many templates. */
39
+ export function shouldUseModalPicker(
40
+ picker: "auto" | "select" | "modal" | undefined,
41
+ templateCount: number,
42
+ ): boolean {
43
+ if (templateCount === 0) return false;
44
+ const mode = picker ?? "auto";
45
+ return (
46
+ mode === "modal" ||
47
+ (mode === "auto" && templateCount > MODAL_PICKER_THRESHOLD)
48
+ );
49
+ }
50
+
51
+ /** Filters templates by category and by a case-insensitive text query. */
52
+ export function filterTemplates(
53
+ templates: NormalizedRepeaterTemplate[],
54
+ query: string,
55
+ category: string,
56
+ ): NormalizedRepeaterTemplate[] {
57
+ const q = query.trim().toLowerCase();
58
+ return templates.filter((tpl) => {
59
+ if (category && tpl.category !== category) return false;
60
+ if (!q) return true;
61
+ return [tpl.label, tpl.description, tpl.category].some((v) =>
62
+ v?.toLowerCase().includes(q),
63
+ );
64
+ });
65
+ }
66
+
67
+ export type WireframeShape = "line" | "lines" | "box" | "check";
68
+
69
+ /** One schematic shape per field type, capped at 5 so it fits a picker card. */
70
+ export function wireframeShapes(
71
+ fields: AnyFieldDescriptor[],
72
+ ): WireframeShape[] {
73
+ return fields.slice(0, 5).map((f) => {
74
+ const type = String(f.type);
75
+ if (type === "textarea" || type === "editor") return "lines";
76
+ if (type.includes("media") || type === "file") return "box";
77
+ if (type === "boolean") return "check";
78
+ return "line";
79
+ });
80
+ }
81
+
82
+ /** True when adding one more item reaches `maxItems`. */
83
+ export function reachesMax(current: number, maxItems?: number): boolean {
84
+ return !!maxItems && current + 1 >= maxItems;
85
+ }
86
+
87
+ /**
88
+ * The fields an item renders: those of its template, picked by `item._template`
89
+ * or, for an item without one, by `fallbackKey`; the repeater's own `fields`
90
+ * when it has no templates or the key matches none.
91
+ */
92
+ export function repeaterItemFields(
93
+ descriptor: RepeaterDescriptor,
94
+ templates: NormalizedRepeaterTemplate[],
95
+ item: Record<string, unknown>,
96
+ fallbackKey: string | undefined,
97
+ ): AnyFieldDescriptor[] {
98
+ const ownFields = descriptor.fields ?? [];
99
+ const hasTemplates = templates.length > 0;
100
+ if (!hasTemplates) return ownFields;
101
+ const key = (item._template as string | undefined) ?? fallbackKey;
102
+ return templates.find((tpl) => tpl.key === key)?.fields ?? ownFields;
103
+ }
@@ -0,0 +1,68 @@
1
+ import type { AnyFieldDescriptor } from "../types/index.js";
2
+ import type { TabEntry } from "../types/layout.js";
3
+ import { valuePath } from "./annotations.js";
4
+
5
+ /**
6
+ * A request of `revealField()`, which the parts of a form act on: the tab,
7
+ * the group and the repeater item that hold the field open, and the field
8
+ * puts the focus on its control.
9
+ */
10
+ export interface FieldRevealRequest {
11
+ /** The path asked, in the form that holds the field: `title`, `translations.it.title`, `blocks.0.title`. */
12
+ readonly path: string;
13
+ /** The key of the form's field the path names, or holds a value of. */
14
+ readonly key: string;
15
+ /** The rest of the path inside that field's value: empty for the field itself, `0.title` in `blocks`. */
16
+ readonly rest: string;
17
+ /** Ends the request: `true` once the control has the focus. A second call does nothing. */
18
+ readonly settle: (focused: boolean) => void;
19
+ }
20
+
21
+ /** The field a path names, and what of the path is inside its value. */
22
+ export interface FieldAtPath {
23
+ field: AnyFieldDescriptor;
24
+ /** Empty for the field itself; `2.author` for `blocks.2.author` in the field `blocks`. */
25
+ rest: string;
26
+ }
27
+
28
+ /**
29
+ * The field of `fields` whose value `path` is, or is inside: the longest key
30
+ * that matches, so `seo.title` wins over `seo`. A translatable field answers
31
+ * to the path of its value in `lang` and to its bare key, as its mark does.
32
+ */
33
+ export function fieldAtPath(
34
+ fields: readonly AnyFieldDescriptor[],
35
+ path: string,
36
+ lang: string,
37
+ ): FieldAtPath | undefined {
38
+ let found: FieldAtPath | undefined;
39
+ let longest = -1;
40
+ for (const field of fields) {
41
+ const key = field.key as string;
42
+ for (const candidate of new Set([valuePath(field, lang), key])) {
43
+ const isField = path === candidate;
44
+ const isInside = path.startsWith(`${candidate}.`);
45
+ if (!isField && !isInside) continue;
46
+ if (candidate.length <= longest) continue;
47
+ longest = candidate.length;
48
+ found = { field, rest: isField ? "" : path.slice(candidate.length + 1) };
49
+ }
50
+ }
51
+ return found;
52
+ }
53
+
54
+ /** The fields of tabs: their groups, the groups' sub-tabs, and their child tabs. */
55
+ export function fieldsOfTabs(tabs: readonly TabEntry[]): AnyFieldDescriptor[] {
56
+ return tabs.flatMap((tab) => [
57
+ ...[...tab.groups.values()].flatMap((group) => [
58
+ ...group.fields,
59
+ ...[...group.subtabs.values()].flat(),
60
+ ]),
61
+ ...fieldsOfTabs([...tab.children.values()]),
62
+ ]);
63
+ }
64
+
65
+ /** Whether a tab, or one of its child tabs, holds the field of `key`. */
66
+ export function tabHoldsField(tab: TabEntry, key: string): boolean {
67
+ return fieldsOfTabs([tab]).some((field) => field.key === key);
68
+ }
@@ -0,0 +1,44 @@
1
+ import type { AnyFieldDescriptor } from "../types/index.js";
2
+ import type { TabEntry } from "../types/layout.js";
3
+
4
+ /**
5
+ * Whether a field shows for this model: neither its `visible` predicate, which
6
+ * removes it, nor its `show` predicate, which hides it, keeps it out.
7
+ */
8
+ export function isFieldShown(
9
+ field: AnyFieldDescriptor,
10
+ model: Record<string, unknown>,
11
+ ): boolean {
12
+ const removed = field.visible ? !field.visible({ model }) : false;
13
+ const hidden = field.show ? !field.show({ model }) : false;
14
+ return !removed && !hidden;
15
+ }
16
+
17
+ /**
18
+ * Whether a tab has a field to show for this model, in one of its groups (sub-tabs
19
+ * included) or in one of its child tabs.
20
+ */
21
+ export function tabHasShownFields(
22
+ tab: TabEntry,
23
+ model: Record<string, unknown>,
24
+ ): boolean {
25
+ for (const group of tab.groups.values()) {
26
+ const fields = [...group.fields, ...[...group.subtabs.values()].flat()];
27
+ if (fields.some((field) => isFieldShown(field, model))) return true;
28
+ }
29
+ return [...tab.children.values()].some((child) =>
30
+ tabHasShownFields(child, model),
31
+ );
32
+ }
33
+
34
+ /**
35
+ * The tab to open among the ones shown: the tab the user picked, while it is
36
+ * shown; otherwise the first one. Empty when no tab is shown.
37
+ */
38
+ export function pickActiveTab(
39
+ shownTabs: TabEntry[],
40
+ picked: string | null,
41
+ ): string {
42
+ const pickedTab = shownTabs.find((tab) => tab.name === picked);
43
+ return (pickedTab ?? shownTabs[0])?.name ?? "";
44
+ }
@@ -1,4 +0,0 @@
1
- export declare const useSnackStore: import("vitest").Mock<() => {
2
- show: import("vitest").Mock<(...args: any[]) => any>;
3
- }>;
4
- //# sourceMappingURL=nuxt-imports.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"nuxt-imports.d.ts","sourceRoot":"","sources":["../../../src/__tests__/__mocks__/nuxt-imports.ts"],"names":[],"mappings":"AAEA,eAAO,MAAM,aAAa;;EAEvB,CAAC"}
@@ -1,2 +0,0 @@
1
- export {};
2
- //# sourceMappingURL=registry.test.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"registry.test.d.ts","sourceRoot":"","sources":["../../src/__tests__/registry.test.ts"],"names":[],"mappings":""}
@@ -1,2 +0,0 @@
1
- export {};
2
- //# sourceMappingURL=useFormFromSchema.test.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"useFormFromSchema.test.d.ts","sourceRoot":"","sources":["../../src/__tests__/useFormFromSchema.test.ts"],"names":[],"mappings":""}
@@ -1,2 +0,0 @@
1
- export {};
2
- //# sourceMappingURL=useMapoForm.test.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"useMapoForm.test.d.ts","sourceRoot":"","sources":["../../src/__tests__/useMapoForm.test.ts"],"names":[],"mappings":""}