@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
@@ -1,23 +1,189 @@
1
- import { resolveSchema, extractDefs, matchesSchema } from "@mapomodule/utils";
1
+ import {
2
+ ATTRS_KEYWORD,
3
+ FIELD_KEYWORD,
4
+ resolveSchema,
5
+ extractDefs,
6
+ matchesSchema,
7
+ } from "@mapomodule/utils";
2
8
  import type { JSONSchema } from "@mapomodule/utils";
3
- import type { AnyFieldDescriptor, FieldType } from "../types/index.js";
9
+ import type {
10
+ AnyFieldDescriptor,
11
+ FieldType,
12
+ RepeaterTemplate,
13
+ } from "../types/index.js";
14
+
15
+ // ─── Mapo keywords ───────────────────────────────────────────────────────────
16
+ // `x-mapo-field` and `x-mapo-attrs` come from `@mapomodule/utils`, shared with
17
+ // the DRF and OpenAPI normalizers. `fieldsToJsonSchema()` writes them, so that
18
+ // its schema reads back into the same descriptors.
19
+
20
+ /** The property where a repeater item keeps its template key. @internal */
21
+ export const TEMPLATE_PROPERTY = "_template";
22
+
23
+ /**
24
+ * Attrs that a JSON Schema keyword with the same meaning expresses, by field
25
+ * type. The reader maps the keyword to the attr, and `fieldsToJsonSchema()`
26
+ * the attr to the keyword. @internal
27
+ */
28
+ export const KEYWORD_ATTRS: Readonly<
29
+ Record<string, Readonly<Record<string, string>>>
30
+ > = {
31
+ number: { min: "minimum", max: "maximum" },
32
+ slider: { min: "minimum", max: "maximum" },
33
+ text: { minLength: "minLength", maxLength: "maxLength" },
34
+ textarea: { minLength: "minLength", maxLength: "maxLength" },
35
+ email: { minLength: "minLength", maxLength: "maxLength" },
36
+ url: { minLength: "minLength", maxLength: "maxLength" },
37
+ repeater: { minItems: "minItems", maxItems: "maxItems" },
38
+ "media-m2m": { minItems: "minItems", maxItems: "maxItems" },
39
+ };
40
+
41
+ /**
42
+ * Attr names never read from a schema nor written to one. Attrs reach the
43
+ * field component through `v-bind`: an event handler (`onFocus`, `onclick`) or
44
+ * a DOM property such as `innerHTML` would let a schema run script.
45
+ * @internal
46
+ */
47
+ export function isUnsafeAttr(name: string): boolean {
48
+ return (
49
+ /^on/i.test(name) ||
50
+ /^(innerhtml|outerhtml|innertext|textcontent|srcdoc|formaction)$/i.test(
51
+ name,
52
+ )
53
+ );
54
+ }
55
+
56
+ /** Labels of the `enum` values, kept aside when choices are read. */
57
+ const ENUM_LABELS = "_enumLabels";
58
+ /** Other properties of each choice (`icon`, `disabled`…), kept aside too. */
59
+ const ENUM_EXTRAS = "_enumExtras";
60
+
61
+ function isRecord(value: unknown): value is Record<string, unknown> {
62
+ return typeof value === "object" && value !== null && !Array.isArray(value);
63
+ }
64
+
65
+ /** The entries of `record` whose name is not {@link isUnsafeAttr}. */
66
+ function safeEntries(record: Record<string, unknown>): Record<string, unknown> {
67
+ return Object.fromEntries(
68
+ Object.entries(record).filter(([name]) => !isUnsafeAttr(name)),
69
+ );
70
+ }
71
+
72
+ /** The JSON type of a schema, ignoring `"null"` in a type list. */
73
+ function jsonType(schema: JSONSchema): string | undefined {
74
+ return Array.isArray(schema.type)
75
+ ? schema.type.find((v) => v !== "null")
76
+ : schema.type;
77
+ }
78
+
79
+ // ─── Choices with labels ─────────────────────────────────────────────────────
80
+
81
+ /**
82
+ * Turns choices written as `oneOf` (or `anyOf`) of `{ const, title }`, the JSON
83
+ * Schema way to label enum values, into an `enum` with its labels kept aside.
84
+ * `resolveSchema()` would otherwise keep the first choice only.
85
+ */
86
+ function withLabeledChoices(schema: JSONSchema): JSONSchema {
87
+ const union = schema.oneOf ?? schema.anyOf;
88
+ if (!union) return schema;
89
+ const choices = union.filter(
90
+ (branch) => isRecord(branch) && branch.type !== "null",
91
+ );
92
+ const isChoiceList =
93
+ choices.length > 0 && choices.every((branch) => "const" in branch);
94
+ if (!isChoiceList) return schema;
95
+ const { oneOf: _oneOf, anyOf: _anyOf, ...rest } = schema;
96
+ const nullable = choices.length < union.length;
97
+ return {
98
+ ...rest,
99
+ enum: choices.map((branch) => branch.const),
100
+ [ENUM_LABELS]: choices.map(
101
+ (branch) => branch.title ?? String(branch.const),
102
+ ),
103
+ [ENUM_EXTRAS]: choices.map((branch) => branch[ATTRS_KEYWORD]),
104
+ ...(nullable ? { _nullable: true } : {}),
105
+ };
106
+ }
107
+
108
+ // ─── Resolve a property ──────────────────────────────────────────────────────
109
+
110
+ /** `#/$defs/Item` → `Item`, the key `resolveSchema()` looks up. */
111
+ function defName(ref: string): string {
112
+ return ref.replace(/^#\/\$defs\//, "").replace(/^#\/definitions\//, "");
113
+ }
114
+
115
+ /** The `$defs` a schema points to: its own `$ref` and those of its union branches. */
116
+ function refsOf(schema: unknown): string[] {
117
+ if (!isRecord(schema)) return [];
118
+ const branches = [
119
+ schema,
120
+ ...(Array.isArray(schema.anyOf) ? schema.anyOf : []),
121
+ ...(Array.isArray(schema.oneOf) ? schema.oneOf : []),
122
+ ];
123
+ return branches.flatMap((branch) =>
124
+ isRecord(branch) && typeof branch.$ref === "string"
125
+ ? [defName(branch.$ref)]
126
+ : [],
127
+ );
128
+ }
129
+
130
+ interface ResolvedProperty {
131
+ schema: JSONSchema;
132
+ /** The `$defs` followed to resolve the property and its items. */
133
+ refs: string[];
134
+ }
135
+
136
+ /**
137
+ * Resolves a property for mapping: labeled choices, `$ref`, nullable unions,
138
+ * and the same for its array items, so a list of models maps to a repeater.
139
+ */
140
+ function resolveProperty(
141
+ raw: unknown,
142
+ defs: Record<string, JSONSchema>,
143
+ ): ResolvedProperty {
144
+ // A boolean schema (`true` accepts any value) has no keyword to map.
145
+ if (!isRecord(raw)) return { schema: {}, refs: [] };
146
+ const schema = resolveSchema(withLabeledChoices(raw), defs);
147
+ const items: unknown = schema.items;
148
+ if (!isRecord(items)) return { schema, refs: refsOf(raw) };
149
+ return {
150
+ schema: {
151
+ ...schema,
152
+ items: resolveSchema(withLabeledChoices(items), defs),
153
+ },
154
+ refs: [...refsOf(raw), ...refsOf(items)],
155
+ };
156
+ }
4
157
 
5
158
  // ─── Map JSON Schema types to FieldType ──────────────────────────────────────
6
159
 
160
+ /** Items of different shapes, told apart by the property that holds the template key. */
161
+ function isTemplateItems(items: JSONSchema | undefined): boolean {
162
+ return (
163
+ !!items?.oneOf && items.discriminator?.propertyName === TEMPLATE_PROPERTY
164
+ );
165
+ }
166
+
7
167
  function mapType(schema: JSONSchema, key: string): FieldType {
168
+ const marked = schema[FIELD_KEYWORD];
169
+ if (typeof marked === "string" && marked) return marked;
170
+
8
171
  // Enum on any scalar type maps to a select field.
9
172
  if (schema.enum) return "select";
10
173
 
11
- const t = Array.isArray(schema.type)
12
- ? schema.type.find((v) => v !== "null")
13
- : schema.type;
14
- const fmt = schema.format as string | undefined;
174
+ const t = jsonType(schema);
175
+ const fmt = schema.format;
15
176
 
16
177
  if (t === "string") {
178
+ if (fmt === "textarea") return "textarea";
17
179
  if (fmt === "date") return "date";
18
180
  if (fmt === "date-time") return "datetime";
19
181
  if (fmt === "time") return "time";
20
182
  if (fmt === "color") return "color";
183
+ if (fmt === "email") return "email";
184
+ if (fmt === "uri" || fmt === "url") return "url";
185
+ if (fmt === "binary") return "file";
186
+ if (schema.contentMediaType === "text/html") return "editor";
21
187
  if (typeof schema.maxLength === "number" && schema.maxLength > 255)
22
188
  return "textarea";
23
189
  return "text";
@@ -37,19 +203,22 @@ function mapType(schema: JSONSchema, key: string): FieldType {
37
203
  const items = schema.items;
38
204
  // Array of relations maps to m2m.
39
205
  if (items?.type === "relation") return "m2m";
40
- // Array of objects maps to a repeater.
206
+ // Array of objects maps to a repeater, with templates when the items vary.
207
+ if (isTemplateItems(items)) return "repeater";
41
208
  if (items?.type === "object" || items?.properties) return "repeater";
42
- // Flat arrays of strings/numbers map to multi-select.
209
+ // Arrays of plain values map to a multiple select.
43
210
  return "select";
44
211
  }
45
212
 
46
213
  if (t === "object") {
47
- // Heuristic: title + description + url/slug looks like an SEO object.
214
+ // Heuristic: title + description + url/slug/permalink looks like an SEO object.
48
215
  const props = Object.keys(schema.properties ?? {});
49
216
  if (
50
217
  props.includes("title") &&
51
218
  props.includes("description") &&
52
- (props.includes("url") || props.includes("slug"))
219
+ (props.includes("url") ||
220
+ props.includes("slug") ||
221
+ props.includes("permalink"))
53
222
  )
54
223
  return "seo";
55
224
  // Otherwise treat it as a generic object through a custom type.
@@ -59,38 +228,61 @@ function mapType(schema: JSONSchema, key: string): FieldType {
59
228
  return "text";
60
229
  }
61
230
 
231
+ /**
232
+ * The field type `useFormFromSchema()` gives a property. `fieldsToJsonSchema()`
233
+ * uses it to write `x-mapo-field` only when the other keywords are not enough.
234
+ * @internal
235
+ */
236
+ export function schemaFieldType(schema: JSONSchema, key: string): FieldType {
237
+ return mapType(resolveProperty(schema, {}).schema, key);
238
+ }
239
+
62
240
  // ─── Build extra attrs from the schema ───────────────────────────────────────
63
241
 
242
+ function selectAttrs(schema: JSONSchema): Record<string, unknown> {
243
+ const isArray = jsonType(schema) === "array";
244
+ // A multiple select keeps its choices on the items.
245
+ const choices = isArray ? schema.items : schema;
246
+ const values = isRecord(choices) ? choices.enum : undefined;
247
+ const labels = choices?.[ENUM_LABELS] as string[] | undefined;
248
+ const extras = choices?.[ENUM_EXTRAS] as unknown[] | undefined;
249
+ return {
250
+ ...(values
251
+ ? {
252
+ options: values.map((value, index) => {
253
+ const extra = extras?.[index];
254
+ return {
255
+ ...(isRecord(extra) ? safeEntries(extra) : {}),
256
+ text: labels?.[index] ?? String(value),
257
+ value,
258
+ };
259
+ }),
260
+ }
261
+ : {}),
262
+ ...(isArray ? { multiple: true } : {}),
263
+ };
264
+ }
265
+
64
266
  function buildAttrs(
65
267
  schema: JSONSchema,
66
268
  type: FieldType,
67
269
  ): Record<string, unknown> {
68
- const attrs: Record<string, unknown> = {};
69
-
70
- if (type === "select") {
71
- if (schema.enum) {
72
- attrs.options = (schema.enum as unknown[]).map((v) => ({
73
- text: String(v),
74
- value: v,
75
- }));
76
- }
77
- }
78
-
79
- if (type === "number") {
80
- if (schema.minimum !== undefined) attrs.min = schema.minimum;
81
- if (schema.maximum !== undefined) attrs.max = schema.maximum;
82
- }
270
+ const attrs: Record<string, unknown> =
271
+ type === "select" ? selectAttrs(schema) : {};
83
272
 
84
- if (type === "text" || type === "textarea") {
85
- if (schema.maxLength !== undefined) attrs.maxLength = schema.maxLength;
86
- if (schema.minLength !== undefined) attrs.minLength = schema.minLength;
273
+ for (const [attr, keyword] of Object.entries(KEYWORD_ATTRS[type] ?? {})) {
274
+ if (schema[keyword] !== undefined) attrs[attr] = schema[keyword];
87
275
  }
88
276
 
89
277
  if (type === "fks" || type === "m2m") {
90
- const ext = schema as JSONSchema & { endpoint?: string; relation?: string };
278
+ const ext = schema as JSONSchema & {
279
+ endpoint?: string;
280
+ relation?: string;
281
+ multiple?: boolean;
282
+ };
91
283
  attrs.endpoint = ext.endpoint ?? ext.relation ?? "";
92
284
  attrs.returnObject = true;
93
- if (type === "m2m") attrs.multiple = true;
285
+ if (type === "m2m" || ext.multiple === true) attrs.multiple = true;
94
286
  }
95
287
 
96
288
  if (type === "date" || type === "datetime") {
@@ -98,6 +290,10 @@ function buildAttrs(
98
290
  if (schema.maximum) attrs.max = schema.maximum;
99
291
  }
100
292
 
293
+ // Mapo's own attrs come last: they are the field's, so they win.
294
+ const own = schema[ATTRS_KEYWORD];
295
+ if (isRecord(own)) Object.assign(attrs, safeEntries(own));
296
+
101
297
  return attrs;
102
298
  }
103
299
 
@@ -146,16 +342,72 @@ function makeVisible(
146
342
  };
147
343
  }
148
344
 
345
+ // ─── Objects, repeater items and templates ───────────────────────────────────
346
+ // `chain` holds the `$defs` expanded on the way down. A model that contains
347
+ // itself (a menu whose items have children, two models that list each other)
348
+ // expands once: the list that would repeat it gets no fields.
349
+
350
+ /** One descriptor per property of an object schema, except `skip`. */
351
+ function objectDescriptors(
352
+ schema: JSONSchema,
353
+ defs: Record<string, JSONSchema>,
354
+ chain: ReadonlySet<string>,
355
+ skip?: string,
356
+ ): AnyFieldDescriptor[] {
357
+ const required = new Set<string>(schema.required ?? []);
358
+ const rules = collectRules(schema);
359
+ return Object.entries(schema.properties ?? {})
360
+ .filter(([key]) => key !== skip)
361
+ .map(([key, value]) =>
362
+ propertyToDescriptor(key, value, defs, required, rules, chain),
363
+ );
364
+ }
365
+
366
+ /**
367
+ * Repeater templates from items written as `oneOf` with a `discriminator` on
368
+ * `_template`: one template per branch, keyed by the `const` of that property.
369
+ * A branch without that `const` cannot be reached and is skipped.
370
+ */
371
+ function templatesOf(
372
+ items: JSONSchema,
373
+ defs: Record<string, JSONSchema>,
374
+ chain: ReadonlySet<string>,
375
+ ): Record<string, AnyFieldDescriptor[] | RepeaterTemplate> {
376
+ const templates: Record<string, AnyFieldDescriptor[] | RepeaterTemplate> = {};
377
+ for (const raw of items.oneOf ?? []) {
378
+ if (!isRecord(raw)) continue;
379
+ const branch = resolveSchema(raw, defs);
380
+ const key = branch.properties?.[TEMPLATE_PROPERTY]?.const;
381
+ if (typeof key !== "string") continue;
382
+ const inner = new Set([...chain, ...refsOf(raw)]);
383
+ const fields = objectDescriptors(branch, defs, inner, TEMPLATE_PROPERTY);
384
+ // Icon, image, wireframe and category of the template.
385
+ const own = branch[ATTRS_KEYWORD];
386
+ const presentation = isRecord(own) ? safeEntries(own) : {};
387
+ const meta = {
388
+ ...(branch.title ? { label: branch.title } : {}),
389
+ ...(typeof branch.description === "string"
390
+ ? { description: branch.description }
391
+ : {}),
392
+ ...presentation,
393
+ };
394
+ // A template with nothing but fields stays a bare field array.
395
+ templates[key] = Object.keys(meta).length ? { ...meta, fields } : fields;
396
+ }
397
+ return templates;
398
+ }
399
+
149
400
  // ─── Single property → AnyFieldDescriptor ──────────────────────────────────────
150
401
 
151
402
  function propertyToDescriptor(
152
403
  key: string,
153
- rawSchema: JSONSchema,
404
+ rawSchema: unknown,
154
405
  defs: Record<string, JSONSchema>,
155
406
  requiredKeys: Set<string>,
156
407
  rules: ConditionalRule[],
408
+ chain: ReadonlySet<string>,
157
409
  ): AnyFieldDescriptor {
158
- const schema = resolveSchema(rawSchema, defs);
410
+ const { schema, refs } = resolveProperty(rawSchema, defs);
159
411
  const type = mapType(schema, key);
160
412
  const attrs = buildAttrs(schema, type);
161
413
 
@@ -173,24 +425,28 @@ function propertyToDescriptor(
173
425
  }
174
426
  }
175
427
 
176
- // Repeater: build child descriptors recursively.
428
+ // Repeater: build child descriptors recursively, or one set per template.
429
+ const items = type === "repeater" ? schema.items : undefined;
430
+ const isCycle = refs.some((name) => chain.has(name));
431
+ const inner = new Set([...chain, ...refs]);
432
+ const hasTemplates = !!items && isTemplateItems(items) && !isCycle;
433
+ if (hasTemplates) attrs.templates = templatesOf(items, defs, inner);
434
+
177
435
  const base: Record<string, unknown> = {
178
436
  key,
179
437
  type,
180
438
  label: schema.title ?? undefined,
181
439
  required: requiredKeys.has(key),
440
+ ...(schema.readOnly ? { readonly: true } : {}),
441
+ // A value the backend never returns, such as a password: keep it out of drafts.
442
+ ...(schema.writeOnly ? { noDraft: true } : {}),
443
+ ...(schema.translatable ? { translatable: true } : {}),
182
444
  ...(visible ? { visible } : {}),
183
445
  ...(Object.keys(attrs).length ? { attrs } : {}),
184
446
  };
185
447
 
186
- if (type === "repeater" && schema.items) {
187
- const itemSchema = resolveSchema(schema.items, defs);
188
- const childRequired = new Set<string>(itemSchema.required ?? []);
189
- const childProps = itemSchema.properties ?? {};
190
- const childRules = collectRules(itemSchema);
191
- base.fields = Object.entries(childProps).map(([k, v]) =>
192
- propertyToDescriptor(k, v, defs, childRequired, childRules),
193
- );
448
+ if (items && !hasTemplates) {
449
+ base.fields = isCycle ? [] : objectDescriptors(items, defs, inner);
194
450
  }
195
451
 
196
452
  return base as unknown as AnyFieldDescriptor;
@@ -209,6 +465,7 @@ export interface UseFormFromSchemaOptions {
209
465
  /**
210
466
  * Builds a `AnyFieldDescriptor[]` array from a JSON Schema.
211
467
  * Supports Pydantic v2 (`$defs`, nullable `anyOf`), DRF Spectacular, and `if/then/else` conditionals.
468
+ * Reads back the schemas `fieldsToJsonSchema()` writes.
212
469
  *
213
470
  * @example
214
471
  * const fields = useFormFromSchema(myApiSchema, {
@@ -221,7 +478,13 @@ export function useFormFromSchema(
221
478
  options: UseFormFromSchemaOptions = {},
222
479
  ): AnyFieldDescriptor[] {
223
480
  const { exclude = [], overrides = {} } = options;
224
- const defs = extractDefs(schema);
481
+ // Labeled choices behind a `$ref` are read like inline ones.
482
+ const defs = Object.fromEntries(
483
+ Object.entries(extractDefs(schema)).map(([name, def]) => [
484
+ name,
485
+ isRecord(def) ? withLabeledChoices(def) : def,
486
+ ]),
487
+ );
225
488
 
226
489
  const properties = schema.properties ?? {};
227
490
  const requiredKeys = new Set<string>(schema.required ?? []);
@@ -238,6 +501,7 @@ export function useFormFromSchema(
238
501
  defs,
239
502
  requiredKeys,
240
503
  rules,
504
+ new Set(),
241
505
  );
242
506
 
243
507
  // Apply consumer overrides with a shallow merge.
@@ -1,9 +1,12 @@
1
1
  import {
2
2
  ref,
3
+ shallowRef,
3
4
  computed,
4
5
  toRaw,
5
6
  toValue,
6
7
  watch,
8
+ getCurrentScope,
9
+ onScopeDispose,
7
10
  type Ref,
8
11
  type MaybeRef,
9
12
  provide,
@@ -15,8 +18,17 @@ import {
15
18
  objectDiff,
16
19
  debounce,
17
20
  } from "@mapomodule/utils";
18
- import type { AnyFieldDescriptor, FieldRegistry } from "../types/index.js";
21
+ import type {
22
+ AnyFieldDescriptor,
23
+ FieldAnnotations,
24
+ FieldRegistry,
25
+ } from "../types/index.js";
19
26
  import { resolveFieldAccessor } from "../types/index.js";
27
+ import { valuePath } from "../utils/annotations.js";
28
+ import { modelForDraft } from "../utils/draft.js";
29
+ import { fieldAtPath } from "../utils/reveal.js";
30
+ import type { FieldRevealRequest } from "../utils/reveal.js";
31
+ import { isFieldShown } from "../utils/tabVisibility.js";
20
32
  import { useCurrentLang } from "./useCurrentLang.js";
21
33
  import { useSnackStore } from "@mapomodule/store/runtime/stores/snack";
22
34
  import { useMapoT } from "@mapomodule/i18n/runtime/composables/useMapoT";
@@ -41,11 +53,19 @@ export interface UseMapoFormOptions<T extends object> {
41
53
  registry: FieldRegistry;
42
54
  /**
43
55
  * When set, enables automatic draft persistence to localStorage.
44
- * Key is prefixed with `mapo:draft:`. Drafts expire after 24 h.
56
+ * Key is prefixed with `mapo:draft:` and the signed-in user's id, so
57
+ * accounts on one browser never share a draft. Drafts expire after 24 h,
58
+ * and the fields marked `noDraft` are left out of them.
45
59
  * Call the returned `checkDraft()` after the model is populated to offer restore.
46
- * Example: `"article:42"` → `mapo:draft:article:42`.
60
+ * Example: `"article:42"` → `mapo:draft:1:article:42` for the user with id `1`.
47
61
  */
48
62
  draftKey?: MaybeRef<string | undefined>;
63
+ /**
64
+ * Marks shown next to the labels of the fields, keyed by the path of the
65
+ * value (`title`, `translations.it.title`, `blocks.0.title`). Changing the
66
+ * map updates the marks without remounting the fields.
67
+ */
68
+ annotations?: MaybeRef<FieldAnnotations | undefined>;
49
69
  }
50
70
 
51
71
  /** State exposed when a pending draft is found in localStorage. */
@@ -71,6 +91,14 @@ export interface MapoFormContext<T extends object> {
71
91
  markTouched: (key: string) => void;
72
92
  isTouched: (key: string) => boolean;
73
93
  submitted: Ref<boolean>;
94
+ /** Optional, so a context built by hand without marks keeps working. */
95
+ annotations?: Readonly<Ref<FieldAnnotations>>;
96
+ /**
97
+ * The field `revealField()` brings into view, while it does: the tab, the
98
+ * group and the repeater item that hold it open, and the field focuses
99
+ * its control. Optional, as `annotations`.
100
+ */
101
+ reveal?: Readonly<Ref<FieldRevealRequest | undefined>>;
74
102
  }
75
103
 
76
104
  function safeClone<X>(v: X): X {
@@ -90,6 +118,13 @@ function safeClone<X>(v: X): X {
90
118
  /** Injection key for the current Mapo form context. */
91
119
  export const FORM_KEY = Symbol("mapoForm");
92
120
 
121
+ /**
122
+ * How long `revealField()` waits for the field to focus its control: a
123
+ * field type the registry loads lazily renders it a moment after its tab,
124
+ * group or item opens.
125
+ */
126
+ const REVEAL_TIMEOUT_MS = 3000;
127
+
93
128
  /**
94
129
  * Provides the current form context to descendant field components.
95
130
  * Internal: `useMapoForm` calls it automatically; consumers use `injectMapoForm`.
@@ -140,7 +175,12 @@ export function useMapoForm<T extends object>(options: UseMapoFormOptions<T>) {
140
175
  const entries = Object.entries(val);
141
176
  if (!entries.length) return;
142
177
  const lines = entries
143
- .map(([field, msgs]) => `${field}: ${(msgs as string[]).join(", ")}`)
178
+ .map(([field, msgs]) => {
179
+ const label =
180
+ toValue(fields).find((descriptor) => descriptor.key === field)
181
+ ?.label || field;
182
+ return `${label}: ${(msgs as string[]).join(", ")}`;
183
+ })
144
184
  .join("\n");
145
185
  snack.show(lines, "error");
146
186
  },
@@ -209,24 +249,15 @@ export function useMapoForm<T extends object>(options: UseMapoFormOptions<T>) {
209
249
  const key = _draftStorageKey();
210
250
  if (!key || !isDirty.value || typeof localStorage === "undefined") return;
211
251
  try {
212
- const noDraftKeys = new Set(
213
- toValue(fields)
214
- .filter((f) => f.noDraft)
215
- .map((f) => f.key as string),
216
- );
217
- const snapshot = toRaw(model.value) as Record<string, unknown>;
218
- const filtered =
219
- noDraftKeys.size > 0
220
- ? Object.fromEntries(
221
- Object.entries(snapshot).filter(([k]) => !noDraftKeys.has(k)),
222
- )
223
- : snapshot;
252
+ // The fields marked `noDraft` hold nothing in the draft, at any
253
+ // path: in every language, under a dotted key, in a repeater's items.
254
+ const values = modelForDraft(toRaw(model.value), toValue(fields));
224
255
  localStorage.setItem(
225
256
  key,
226
- JSON.stringify({ model: filtered, savedAt: Date.now() }),
257
+ JSON.stringify({ model: values, savedAt: Date.now() }),
227
258
  );
228
259
  } catch {
229
- /* quota exceeded — ignore */
260
+ /* quota exceeded, or a value with no JSON form — ignore */
230
261
  }
231
262
  }, 2000);
232
263
  watch(model, saveDraft, { deep: true });
@@ -251,11 +282,7 @@ export function useMapoForm<T extends object>(options: UseMapoFormOptions<T>) {
251
282
  });
252
283
 
253
284
  function resolvePath(descriptor: AnyFieldDescriptor<T>): string {
254
- const lang = currentLang.value;
255
- if (descriptor.translatable && lang) {
256
- return `translations.${lang}.${descriptor.key}`;
257
- }
258
- return descriptor.key as string;
285
+ return valuePath(descriptor as AnyFieldDescriptor, currentLang.value);
259
286
  }
260
287
 
261
288
  function initLang(lang: string) {
@@ -406,6 +433,56 @@ export function useMapoForm<T extends object>(options: UseMapoFormOptions<T>) {
406
433
  });
407
434
  const findDescriptor = (key: string) => fieldIndex.value.get(key);
408
435
 
436
+ // ─── Bringing a field into view ─────────────────────────────────────────────
437
+
438
+ const reveal = shallowRef<FieldRevealRequest>();
439
+
440
+ /**
441
+ * Brings a field into view: opens the tab, the group or sub-tab and the
442
+ * repeater item that hold it, puts the focus on its control and scrolls
443
+ * it to the middle of the screen. The last call wins: one under way ends
444
+ * with `false`.
445
+ *
446
+ * @param path The path of the field's value, as its mark and its server
447
+ * errors name it: `title`, `translations.it.title`, `blocks.0.title`.
448
+ * @returns Whether the field's control took the focus: `false` at once
449
+ * for a field this form does not have or does not show, and after a few
450
+ * seconds for one that never rendered a control to focus.
451
+ */
452
+ function revealField(path: string): Promise<boolean> {
453
+ reveal.value?.settle(false);
454
+ const located = fieldAtPath(
455
+ toValue(fields) as AnyFieldDescriptor[],
456
+ path,
457
+ currentLang.value,
458
+ );
459
+ const isShown = located
460
+ ? isFieldShown(located.field, model.value as Record<string, unknown>)
461
+ : false;
462
+ if (!located || !isShown) return Promise.resolve(false);
463
+ return new Promise((resolve) => {
464
+ let isSettled = false;
465
+ const request: FieldRevealRequest = {
466
+ path,
467
+ key: located.field.key as string,
468
+ rest: located.rest,
469
+ // Called only once the request is out, after the timer below.
470
+ settle: (focused) => {
471
+ if (isSettled) return;
472
+ isSettled = true;
473
+ clearTimeout(timer);
474
+ if (reveal.value === request) reveal.value = undefined;
475
+ resolve(focused);
476
+ },
477
+ };
478
+ const timer = setTimeout(() => request.settle(false), REVEAL_TIMEOUT_MS);
479
+ reveal.value = request;
480
+ });
481
+ }
482
+
483
+ // A form that goes away ends what it was bringing into view.
484
+ if (getCurrentScope()) onScopeDispose(() => reveal.value?.settle(false));
485
+
409
486
  const ctx: MapoFormContext<T> = {
410
487
  model,
411
488
  fields,
@@ -427,6 +504,8 @@ export function useMapoForm<T extends object>(options: UseMapoFormOptions<T>) {
427
504
  markTouched,
428
505
  isTouched,
429
506
  submitted,
507
+ annotations: computed(() => toValue(options.annotations) ?? {}),
508
+ reveal,
430
509
  };
431
510
 
432
511
  // Public API: accepts either a string key or a full descriptor, making it ergonomic
@@ -478,6 +557,7 @@ export function useMapoForm<T extends object>(options: UseMapoFormOptions<T>) {
478
557
  resetDirty,
479
558
  getPatch,
480
559
  submit,
560
+ revealField,
481
561
  ctx,
482
562
  draftBanner,
483
563
  checkDraft,