@mapomodule/form 2.0.0-beta.9 → 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 +171 -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__/draft.test.ts +221 -0
  95. package/src/__tests__/fieldComponent.test.ts +31 -0
  96. package/src/__tests__/fieldExtensions.test.ts +63 -0
  97. package/src/__tests__/fieldFocus.test.ts +178 -0
  98. package/src/__tests__/fieldsToJsonSchema.test.ts +630 -0
  99. package/src/__tests__/headlessRenderer.ts +85 -0
  100. package/src/__tests__/repeaterTemplates.test.ts +154 -0
  101. package/src/__tests__/reveal.test.ts +89 -0
  102. package/src/__tests__/schemaSources.test.ts +132 -0
  103. package/src/__tests__/tabVisibility.test.ts +102 -0
  104. package/src/__tests__/useFormFromSchema.test.ts +387 -0
  105. package/src/__tests__/useMapoForm.test.ts +213 -2
  106. package/src/index.ts +9 -0
  107. package/src/module.ts +9 -0
  108. package/src/runtime/components/MapoFocusPortal.vue +15 -2
  109. package/src/runtime/components/MapoForm.vue +47 -4
  110. package/src/runtime/components/MapoFormAnnotation.vue +113 -0
  111. package/src/runtime/components/MapoFormAnnotationBadges.vue +41 -0
  112. package/src/runtime/components/MapoFormField.vue +72 -11
  113. package/src/runtime/components/MapoFormGroup.vue +20 -2
  114. package/src/runtime/components/MapoFormTabs.vue +64 -8
  115. package/src/runtime/components/fields/MapoMediaField.vue +5 -3
  116. package/src/runtime/components/fields/MapoMediaM2mField.vue +3 -2
  117. package/src/runtime/components/fields/MapoRepeater.vue +82 -14
  118. package/src/runtime/components/fields/MapoRepeaterBlockPicker.vue +188 -0
  119. package/src/runtime/components/fields/MapoRepeaterItem.vue +56 -8
  120. package/src/runtime/components/fields/MapoWygEditor.vue +22 -14
  121. package/src/runtime/composables/useFieldAnnotation.ts +38 -0
  122. package/src/runtime/composables/useFocusMode.ts +7 -1
  123. package/src/runtime/composables/useFormFromSchema.ts +303 -41
  124. package/src/runtime/composables/useMapoForm.ts +103 -23
  125. package/src/runtime/types/annotation.ts +53 -0
  126. package/src/runtime/types/descriptor.ts +94 -4
  127. package/src/runtime/types/index.ts +10 -0
  128. package/src/runtime/utils/annotations.ts +169 -0
  129. package/src/runtime/utils/draft.ts +158 -0
  130. package/src/runtime/utils/fieldComponent.ts +34 -0
  131. package/src/runtime/utils/fieldFocus.ts +73 -0
  132. package/src/runtime/utils/fieldsToJsonSchema.ts +405 -0
  133. package/src/runtime/utils/repeaterTemplates.ts +103 -0
  134. package/src/runtime/utils/reveal.ts +68 -0
  135. package/src/runtime/utils/tabVisibility.ts +44 -0
  136. package/dist/__tests__/__mocks__/nuxt-imports.d.ts +0 -4
  137. package/dist/__tests__/__mocks__/nuxt-imports.d.ts.map +0 -1
  138. package/dist/__tests__/camomillaRoundTrip.test.d.ts +0 -2
  139. package/dist/__tests__/camomillaRoundTrip.test.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,53 @@
1
+ /**
2
+ * A Nuxt UI color: one of the built-in semantic colors, or a color the app
3
+ * registers in its theme (`ui.theme.colors`).
4
+ */
5
+ export type FieldAnnotationColor =
6
+ | "primary"
7
+ | "secondary"
8
+ | "success"
9
+ | "info"
10
+ | "warning"
11
+ | "error"
12
+ | "neutral"
13
+ | (string & {});
14
+
15
+ /** A button in the popover of a field annotation. */
16
+ export interface FieldAnnotationAction {
17
+ /** Button text. */
18
+ label: string;
19
+ /** Iconify name shown before the text, e.g. `i-lucide-check`. */
20
+ icon?: string;
21
+ /** Button color. Default: `neutral`. */
22
+ color?: FieldAnnotationColor;
23
+ /** Runs when the button is clicked. */
24
+ onClick: () => void;
25
+ }
26
+
27
+ /**
28
+ * A mark that decorates a field from outside its descriptor: an icon next to the
29
+ * label that opens a popover, and a count on the tab that holds the field.
30
+ */
31
+ export interface FieldAnnotation {
32
+ /**
33
+ * Short text: the accessible name of the mark and the title of its popover,
34
+ * e.g. "Suggested by AI".
35
+ */
36
+ label: string;
37
+ /** Iconify name of the mark. Default: `i-lucide-info`. */
38
+ icon?: string;
39
+ /** Color of the mark and of its tab count. Default: `neutral`. */
40
+ color?: FieldAnnotationColor;
41
+ /** Adds a dot to the mark, to ask for attention without another icon. */
42
+ dot?: boolean;
43
+ /** Longer text in the popover, under the title. */
44
+ description?: string;
45
+ /** Buttons at the bottom of the popover. */
46
+ actions?: readonly FieldAnnotationAction[];
47
+ }
48
+
49
+ /**
50
+ * Annotations keyed by the path of the field's value, the same paths as the
51
+ * server errors: `title`, `translations.it.title`, `blocks.0.title`.
52
+ */
53
+ export type FieldAnnotations = Record<string, FieldAnnotation>;
@@ -69,11 +69,36 @@ export interface FieldAccessor<TValue = unknown, TModel = unknown> {
69
69
  set?: (ctx: { model: TModel; val: TValue; lang?: string }) => TValue;
70
70
  }
71
71
 
72
+ /**
73
+ * Properties that packages and apps add to every field descriptor, with type
74
+ * checking. The form engine never reads them: whoever declares a property reads
75
+ * it, for example a custom field or the `property` option of
76
+ * `fieldsToJsonSchema()`.
77
+ *
78
+ * Declare a property by augmenting this interface. Keep it optional, and give it
79
+ * a name of your own so it cannot clash with a descriptor property.
80
+ *
81
+ * @example
82
+ * // In an app: a .d.ts file the app's tsconfig includes
83
+ * declare module "mapomodule/types" {
84
+ * interface FieldExtensions {
85
+ * help?: string;
86
+ * }
87
+ * }
88
+ *
89
+ * // Makes the file a module, so the block above adds to Mapo's types
90
+ * // instead of replacing them.
91
+ * export {};
92
+ */
93
+ // Empty on purpose: it exists to be augmented.
94
+ // eslint-disable-next-line @typescript-eslint/no-empty-object-type
95
+ export interface FieldExtensions {}
96
+
72
97
  /**
73
98
  * Common properties shared by every field descriptor.
74
99
  * All concrete descriptor types extend this interface.
75
100
  */
76
- interface FieldBase<T> {
101
+ interface FieldBase<T> extends FieldExtensions {
77
102
  /** Model key. Accepts a direct `keyof T` or a dotted path up to 4 levels deep (e.g. `"data.hero.title"`). */
78
103
  key: DeepKeyOf<T>;
79
104
  /** Human-readable label displayed above the field. */
@@ -164,8 +189,11 @@ interface FieldBase<T> {
164
189
  /** Direct component override. Takes priority over `registry.mapping[type]`. */
165
190
  is?: Component;
166
191
  /**
167
- * When `true`, this field's value is excluded from draft snapshots saved to localStorage.
192
+ * When `true`, this field's value is excluded from draft snapshots saved to localStorage,
193
+ * wherever it is: at its key (a dotted key included), in every language for a
194
+ * translatable or `synci18n` field, and in each item of a repeater that declares it.
168
195
  * Use for sensitive fields (passwords, API keys, tokens) that should never be persisted client-side.
196
+ * A value that an `accessor` writes at another path is not reached: mark that field too.
169
197
  */
170
198
  noDraft?: boolean;
171
199
  }
@@ -303,6 +331,53 @@ export interface MapDescriptor<
303
331
  };
304
332
  }
305
333
 
334
+ /**
335
+ * How a template's preview `image` fits its picker card: the CSS `object-fit` values.
336
+ * `contain` shows the whole image, `cover` fills the card and crops the edges.
337
+ */
338
+ export type RepeaterImageFit =
339
+ | "contain"
340
+ | "cover"
341
+ | "fill"
342
+ | "none"
343
+ | "scale-down";
344
+
345
+ /**
346
+ * A repeater block template with presentation metadata.
347
+ * Use it instead of a bare field array to describe the block in the picker.
348
+ */
349
+ export interface RepeaterTemplate {
350
+ /** Field descriptors of the block. */
351
+ fields: AnyFieldDescriptor[];
352
+ /** Human-readable name. Defaults to the template key. */
353
+ label?: string;
354
+ /** Short explanation of what the block is for. */
355
+ description?: string;
356
+ /** Iconify name (e.g. `i-lucide-image`). Used as the preview fallback and in the item header. */
357
+ icon?: string;
358
+ /** Preview image URL, shown in the picker card. Takes precedence over `wireframe` and `icon`. */
359
+ image?: string;
360
+ /**
361
+ * How `image` fits the picker card (CSS `object-fit`). Default: the repeater's
362
+ * `attrs.templateImageFit`, else `contain`, which shows the whole image.
363
+ */
364
+ imageFit?: RepeaterImageFit;
365
+ /** Draw a schematic preview generated from the template fields (used when there is no `image`). */
366
+ wireframe?: boolean;
367
+ /** Group name: the picker shows one filter chip per category. */
368
+ category?: string;
369
+ }
370
+
371
+ /** A {@link RepeaterTemplate} normalized for display, with its key and defaults applied. @internal */
372
+ export interface NormalizedRepeaterTemplate extends Omit<
373
+ RepeaterTemplate,
374
+ "label" | "imageFit"
375
+ > {
376
+ key: string;
377
+ label: string;
378
+ imageFit: RepeaterImageFit;
379
+ }
380
+
306
381
  /** Descriptor for a drag-and-drop repeater with nested field descriptors. */
307
382
  export interface RepeaterDescriptor<
308
383
  T = Record<string, unknown>,
@@ -314,8 +389,23 @@ export interface RepeaterDescriptor<
314
389
  */
315
390
  fields?: AnyFieldDescriptor[];
316
391
  attrs?: {
317
- /** Multiple templates for heterogeneous items (`oneOf` discriminated union). */
318
- templates?: Record<string, AnyFieldDescriptor[]>;
392
+ /**
393
+ * Multiple templates for heterogeneous items (`oneOf` discriminated union).
394
+ * A value is either a bare field array or a {@link RepeaterTemplate} with label,
395
+ * description, icon, preview image and category.
396
+ */
397
+ templates?: Record<string, AnyFieldDescriptor[] | RepeaterTemplate>;
398
+ /**
399
+ * How the user chooses a template when adding an item: `select` (dropdown),
400
+ * `modal` (card gallery with search) or `auto`. Default: `auto`, which uses the
401
+ * modal when there are more than 3 templates.
402
+ */
403
+ picker?: "auto" | "select" | "modal";
404
+ /**
405
+ * How the templates' preview images fit the picker cards (CSS `object-fit`).
406
+ * A template's own `imageFit` wins. Default: `contain`.
407
+ */
408
+ templateImageFit?: RepeaterImageFit;
319
409
  /** Label shown when an item is collapsed. Receives the item and its index. */
320
410
  previewLabel?: (item: unknown, index: number) => string;
321
411
  confirmDelete?: boolean;
@@ -9,6 +9,7 @@ export type {
9
9
  FieldAccessor,
10
10
  FieldDescriptor,
11
11
  AnyFieldDescriptor,
12
+ FieldExtensions,
12
13
  TextDescriptor,
13
14
  NumberDescriptor,
14
15
  BooleanDescriptor,
@@ -21,6 +22,8 @@ export type {
21
22
  SeoDescriptor,
22
23
  MapDescriptor,
23
24
  RepeaterDescriptor,
25
+ RepeaterTemplate,
26
+ RepeaterImageFit,
24
27
  MediaDescriptor,
25
28
  MediaM2mDescriptor,
26
29
  EnhancedMediaDescriptor,
@@ -29,6 +32,13 @@ export type {
29
32
 
30
33
  export type { MediaLink, MediaItem, EnhancedMediaValue } from "./media.js";
31
34
 
35
+ export type {
36
+ FieldAnnotation,
37
+ FieldAnnotationAction,
38
+ FieldAnnotationColor,
39
+ FieldAnnotations,
40
+ } from "./annotation.js";
41
+
32
42
  export type {
33
43
  FieldComponentEntry,
34
44
  FieldRegistry,
@@ -0,0 +1,169 @@
1
+ import { getNestedValue } from "@mapomodule/utils";
2
+ import type {
3
+ AnyFieldDescriptor,
4
+ FieldAnnotation,
5
+ FieldAnnotationColor,
6
+ FieldAnnotations,
7
+ RepeaterDescriptor,
8
+ } from "../types/index.js";
9
+ import type { TabEntry } from "../types/layout.js";
10
+ import { isFieldShown } from "./tabVisibility.js";
11
+ import { normalizeTemplates, repeaterItemFields } from "./repeaterTemplates.js";
12
+
13
+ /** Icon of a mark that does not choose one. */
14
+ export const DEFAULT_ANNOTATION_ICON = "i-lucide-info";
15
+
16
+ /** Color of a mark that does not choose one. */
17
+ export const DEFAULT_ANNOTATION_COLOR: FieldAnnotationColor = "neutral";
18
+
19
+ /**
20
+ * The path of a field's value in the model: its key, or its translation in the
21
+ * current language for a translatable field.
22
+ */
23
+ export function valuePath(field: AnyFieldDescriptor, lang: string): string {
24
+ const key = field.key as string;
25
+ const isTranslated = Boolean(field.translatable) && Boolean(lang);
26
+ return isTranslated ? `translations.${lang}.${key}` : key;
27
+ }
28
+
29
+ /**
30
+ * The annotation of a field: the one at the path of its value; for a
31
+ * translatable field, otherwise the one at its bare key, which holds in every
32
+ * language.
33
+ */
34
+ export function annotationFor(
35
+ annotations: FieldAnnotations,
36
+ key: string,
37
+ path: string,
38
+ ): FieldAnnotation | undefined {
39
+ const atPath = annotations[path];
40
+ if (atPath) return atPath;
41
+ const isTranslatedPath = path !== key;
42
+ if (!isTranslatedPath) return undefined;
43
+ return annotations[key];
44
+ }
45
+
46
+ /**
47
+ * The entries under `prefix`, keyed relative to it: with prefix `blocks.0`,
48
+ * `blocks.0.title` becomes `title`. A repeater item reads its errors and its
49
+ * annotations from the parent form this way.
50
+ */
51
+ export function entriesUnder<V>(
52
+ record: Record<string, V>,
53
+ prefix: string,
54
+ ): Record<string, V> {
55
+ const start = `${prefix}.`;
56
+ const result: Record<string, V> = {};
57
+ for (const [path, value] of Object.entries(record)) {
58
+ if (path.startsWith(start)) result[path.slice(start.length)] = value;
59
+ }
60
+ return result;
61
+ }
62
+
63
+ /** The annotations of one icon and one color: one badge with their count. */
64
+ export interface AnnotationGroup {
65
+ icon: string;
66
+ color: FieldAnnotationColor;
67
+ count: number;
68
+ /** The distinct labels, for the accessible name of the badge. */
69
+ labels: string[];
70
+ }
71
+
72
+ /** The fields of a tab: its groups, their sub-tabs and its child tabs. */
73
+ function tabFields(tab: TabEntry): AnyFieldDescriptor[] {
74
+ const own = [...tab.groups.values()].flatMap((group) => [
75
+ ...group.fields,
76
+ ...[...group.subtabs.values()].flat(),
77
+ ]);
78
+ const nested = [...tab.children.values()].flatMap(tabFields);
79
+ return [...own, ...nested];
80
+ }
81
+
82
+ /**
83
+ * The marks the shown fields display, the marks inside their repeater items
84
+ * included.
85
+ */
86
+ function shownAnnotations(
87
+ fields: AnyFieldDescriptor[],
88
+ annotations: FieldAnnotations,
89
+ model: Record<string, unknown>,
90
+ lang: string,
91
+ ): FieldAnnotation[] {
92
+ return fields
93
+ .filter((field) => isFieldShown(field, model))
94
+ .flatMap((field) => fieldAnnotations(field, annotations, model, lang));
95
+ }
96
+
97
+ /**
98
+ * The marks a field displays: its own and, for a repeater, those of each item,
99
+ * found the way `MapoRepeater` hands them out: under `<key>.<index>`, for the
100
+ * fields the item renders, shown for the item's model.
101
+ */
102
+ function fieldAnnotations(
103
+ field: AnyFieldDescriptor,
104
+ annotations: FieldAnnotations,
105
+ model: Record<string, unknown>,
106
+ lang: string,
107
+ ): FieldAnnotation[] {
108
+ const key = field.key as string;
109
+ const path = valuePath(field, lang);
110
+ const own = annotationFor(annotations, key, path);
111
+ const marks = own ? [own] : [];
112
+
113
+ const isRepeater = field.type === "repeater";
114
+ if (!isRepeater) return marks;
115
+ const items = getNestedValue(model, path);
116
+ if (!Array.isArray(items)) return marks;
117
+
118
+ const repeater = field as RepeaterDescriptor;
119
+ const templates = normalizeTemplates(repeater.attrs?.templates);
120
+ const firstTemplate = templates[0]?.key;
121
+ items.forEach((item: Record<string, unknown>, index) => {
122
+ const itemFields = repeaterItemFields(
123
+ repeater,
124
+ templates,
125
+ item,
126
+ firstTemplate,
127
+ );
128
+ const itemAnnotations = entriesUnder(annotations, `${key}.${index}`);
129
+ marks.push(...shownAnnotations(itemFields, itemAnnotations, item, lang));
130
+ });
131
+ return marks;
132
+ }
133
+
134
+ /**
135
+ * The badges for a list of fields: the marks of the shown fields, those inside
136
+ * repeater items included, grouped by icon and color in the order they first
137
+ * appear.
138
+ */
139
+ export function annotationGroups(
140
+ fields: AnyFieldDescriptor[],
141
+ annotations: FieldAnnotations,
142
+ model: Record<string, unknown>,
143
+ lang: string,
144
+ ): AnnotationGroup[] {
145
+ const hasAnnotations = Object.keys(annotations).length > 0;
146
+ if (!hasAnnotations) return [];
147
+
148
+ const groups = new Map<string, AnnotationGroup>();
149
+ for (const mark of shownAnnotations(fields, annotations, model, lang)) {
150
+ const icon = mark.icon ?? DEFAULT_ANNOTATION_ICON;
151
+ const color = mark.color ?? DEFAULT_ANNOTATION_COLOR;
152
+ const groupKey = `${icon}|${color}`;
153
+ const group = groups.get(groupKey) ?? { icon, color, count: 0, labels: [] };
154
+ group.count++;
155
+ if (!group.labels.includes(mark.label)) group.labels.push(mark.label);
156
+ groups.set(groupKey, group);
157
+ }
158
+ return [...groups.values()];
159
+ }
160
+
161
+ /** The badges of a tab: those of its fields, sub-tabs and child tabs included. */
162
+ export function tabAnnotationGroups(
163
+ tab: TabEntry,
164
+ annotations: FieldAnnotations,
165
+ model: Record<string, unknown>,
166
+ lang: string,
167
+ ): AnnotationGroup[] {
168
+ return annotationGroups(tabFields(tab), annotations, model, lang);
169
+ }
@@ -0,0 +1,158 @@
1
+ import type { AnyFieldDescriptor, RepeaterDescriptor } from "../types/index.js";
2
+ import { normalizeTemplates, repeaterItemFields } from "./repeaterTemplates.js";
3
+
4
+ /** Path segments that lead to an object's prototype instead of a value. */
5
+ const UNSAFE_SEGMENTS: ReadonlySet<string> = new Set([
6
+ "__proto__",
7
+ "constructor",
8
+ "prototype",
9
+ ]);
10
+
11
+ type Values = Record<string, unknown>;
12
+
13
+ // `any` accepts descriptors typed against any model: the draft reads only
14
+ // what a descriptor says about its field, never the model type.
15
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
16
+ type Field = AnyFieldDescriptor<any>;
17
+
18
+ function isValues(value: unknown): value is Values {
19
+ return typeof value === "object" && value !== null && !Array.isArray(value);
20
+ }
21
+
22
+ /** An object of keys and values: not a file, a date, a map or a class's instance. */
23
+ function isPlainObject(value: unknown): value is Values {
24
+ if (!isValues(value)) return false;
25
+ const prototype: unknown = Object.getPrototypeOf(value);
26
+ const isLiteral = prototype === Object.prototype;
27
+ const isBare = prototype === null;
28
+ return isLiteral || isBare;
29
+ }
30
+
31
+ /**
32
+ * The model as a draft keeps it: a copy of what JSON writes and reads back
33
+ * as it was (texts, finite numbers, booleans, `null`, and lists and plain
34
+ * objects of them), in which the fields marked `noDraft` hold nothing.
35
+ * Anything else stays out, so a restore never writes it back changed: a
36
+ * file not uploaded yet, a date, a map; and so does a value met again
37
+ * inside itself. A field's value is removed at its key (`password`,
38
+ * `api.key`), and for a translatable or `synci18n` field in every language
39
+ * of `translations` too; inside a repeater, at the same paths of each item,
40
+ * by the fields the item renders. A field whose accessor writes its value
41
+ * somewhere else keeps it there.
42
+ *
43
+ * @param model The form's values.
44
+ * @param fields The form's fields, the sidebar's included.
45
+ * @returns The copy to store.
46
+ */
47
+ export function modelForDraft<T extends object>(
48
+ model: T,
49
+ fields: readonly Field[],
50
+ ): T {
51
+ const copy = plainCopy(model, new Set());
52
+ const values: Values = isPlainObject(copy) ? copy : {};
53
+ removeNoDraft(values, fields);
54
+ // The copy holds the model's own keys, those JSON can carry.
55
+ return values as T;
56
+ }
57
+
58
+ /**
59
+ * The plain data of a value, copied; `undefined` when it has none. A list
60
+ * keeps the items that have some, an object the keys. `inside` holds the
61
+ * objects the value is in, so a cycle ends.
62
+ */
63
+ function plainCopy(value: unknown, inside: Set<object>): unknown {
64
+ if (value === null) return null;
65
+ if (typeof value === "string") return value;
66
+ if (typeof value === "boolean") return value;
67
+ if (typeof value === "number") {
68
+ return Number.isFinite(value) ? value : undefined;
69
+ }
70
+ const isList = Array.isArray(value);
71
+ if (!isList && !isPlainObject(value)) return undefined;
72
+ if (inside.has(value)) return undefined;
73
+ inside.add(value);
74
+ let copy: unknown;
75
+ if (isList) {
76
+ copy = value.flatMap((item) => {
77
+ const kept = plainCopy(item, inside);
78
+ return kept === undefined ? [] : [kept];
79
+ });
80
+ } else {
81
+ const kept: Values = {};
82
+ for (const [key, item] of Object.entries(value)) {
83
+ const one = plainCopy(item, inside);
84
+ if (one === undefined) continue;
85
+ // A key such as `__proto__` stays a key, as JSON reads it.
86
+ Object.defineProperty(kept, key, {
87
+ value: one,
88
+ enumerable: true,
89
+ writable: true,
90
+ configurable: true,
91
+ });
92
+ }
93
+ copy = kept;
94
+ }
95
+ inside.delete(value);
96
+ return copy;
97
+ }
98
+
99
+ /** Removes the values of the `noDraft` fields from one record of values: the model, or an item. */
100
+ function removeNoDraft(values: Values, fields: readonly Field[]): void {
101
+ const languages = isValues(values.translations)
102
+ ? Object.values(values.translations).filter(isValues)
103
+ : [];
104
+ for (const field of fields) {
105
+ const key = String(field.key);
106
+ const isTranslated = Boolean(field.translatable) || Boolean(field.synci18n);
107
+ const holders = isTranslated ? [values, ...languages] : [values];
108
+ if (field.noDraft) {
109
+ for (const holder of holders) removeAt(holder, key);
110
+ continue;
111
+ }
112
+ if (field.type !== "repeater") continue;
113
+ const repeater = field as RepeaterDescriptor;
114
+ const templates = normalizeTemplates(repeater.attrs?.templates);
115
+ // An item without a template renders the first one, as the repeater does.
116
+ const fallback = templates[0]?.key;
117
+ for (const holder of holders) {
118
+ const items = readAt(holder, key);
119
+ if (!Array.isArray(items)) continue;
120
+ for (const item of items) {
121
+ if (!isValues(item)) continue;
122
+ const itemFields = repeaterItemFields(
123
+ repeater,
124
+ templates,
125
+ item,
126
+ fallback,
127
+ );
128
+ removeNoDraft(item, itemFields);
129
+ }
130
+ }
131
+ }
132
+ }
133
+
134
+ /** The value at a dotted path, through own properties only. */
135
+ function readAt(values: Values, path: string): unknown {
136
+ const segments = path.split(".");
137
+ if (segments.some((segment) => UNSAFE_SEGMENTS.has(segment))) {
138
+ return undefined;
139
+ }
140
+ let current: unknown = values;
141
+ for (const segment of segments) {
142
+ const isOwn = isValues(current) && Object.hasOwn(current, segment);
143
+ if (!isOwn) return undefined;
144
+ current = (current as Values)[segment];
145
+ }
146
+ return current;
147
+ }
148
+
149
+ /** Removes the key at a dotted path, through own properties only. */
150
+ function removeAt(values: Values, path: string): void {
151
+ const segments = path.split(".");
152
+ const last = segments.pop();
153
+ if (last === undefined) return;
154
+ if (UNSAFE_SEGMENTS.has(last)) return;
155
+ const parent = segments.length ? readAt(values, segments.join(".")) : values;
156
+ const isOwn = isValues(parent) && Object.hasOwn(parent, last);
157
+ if (isOwn) delete (parent as Values)[last];
158
+ }
@@ -0,0 +1,34 @@
1
+ import { defineAsyncComponent } from "vue";
2
+ import type { Component } from "vue";
3
+ import type { FieldComponentEntry } from "../types/index.js";
4
+
5
+ type FieldLoader = () => Promise<{ default: Component }>;
6
+
7
+ // `<component :is>` tells components apart by identity. An async wrapper created
8
+ // at every render would be a new component for every new descriptor object: Vue
9
+ // would unmount the field and mount another one, losing the focus and the
10
+ // field's state. One wrapper per loader, shared by every form, keeps the field
11
+ // mounted; it also keeps the loaded component, so later fields of that type
12
+ // render without waiting for the import. Weak keys let a loader created by a
13
+ // page be collected with it.
14
+ const asyncFields = new WeakMap<FieldLoader, Component>();
15
+
16
+ /**
17
+ * Returns the component that `<component :is>` renders for a registry entry.
18
+ * A lazy loader becomes an async component, created once per loader and reused;
19
+ * a component name or a component is returned as it is.
20
+ */
21
+ export function toFieldComponent(
22
+ entry: FieldComponentEntry,
23
+ ): string | Component {
24
+ const isLoader = typeof entry === "function";
25
+ if (!isLoader) return entry;
26
+
27
+ const loader = entry as FieldLoader;
28
+ const cached = asyncFields.get(loader);
29
+ if (cached) return cached;
30
+
31
+ const component = defineAsyncComponent(loader);
32
+ asyncFields.set(loader, component);
33
+ return component;
34
+ }
@@ -0,0 +1,73 @@
1
+ /** What can take the focus inside a field's control. */
2
+ const FOCUSABLE = [
3
+ 'input:not([type="hidden"])',
4
+ "textarea",
5
+ "select",
6
+ "button",
7
+ '[contenteditable="true"]',
8
+ '[tabindex]:not([tabindex="-1"])',
9
+ ].join(", ");
10
+
11
+ /**
12
+ * Puts the focus back on a field's control when nothing holds it. An action
13
+ * in a field's mark can take the mark away, or replace the button pressed,
14
+ * and the browser then drops the focus on the page: the field is where the
15
+ * operator was. A focus held elsewhere, as by a dialog the action opened,
16
+ * stays where it is.
17
+ *
18
+ * @param id The id of the field's control, as `MapoFormField` gives it: `field-<key>`.
19
+ * @returns Whether the focus went to the field.
20
+ */
21
+ export function refocusField(id: string): boolean {
22
+ if (typeof document === "undefined") return false;
23
+ const active = document.activeElement;
24
+ const isLost = active === null || active === document.body;
25
+ if (!isLost) return false;
26
+ const root = document.getElementById(id);
27
+ if (!root) return false;
28
+ const control = root.matches(FOCUSABLE)
29
+ ? root
30
+ : root.querySelector<HTMLElement>(FOCUSABLE);
31
+ if (!control) return false;
32
+ control.focus();
33
+ return true;
34
+ }
35
+
36
+ /**
37
+ * Puts the focus on a field's control and scrolls the field into view, its
38
+ * label and mark included: what `revealField()` ends with. The control is
39
+ * the element with the field's id inside the field's own element: an id
40
+ * alone could name the same field of another repeater item.
41
+ *
42
+ * @param field The field's element, as `MapoFormField` renders it.
43
+ * @param id The id of the field's control: `field-<key>`.
44
+ * @returns Whether the control took the focus. Not while it cannot have it,
45
+ * as when it is disabled or not rendered yet.
46
+ */
47
+ export function focusFieldControl(field: unknown, id: string): boolean {
48
+ if (!isElement(field)) return false;
49
+ const escaped = id.replace(/["\\]/g, "\\$&");
50
+ const root = field.querySelector<HTMLElement>(`[id="${escaped}"]`);
51
+ if (!root) return false;
52
+ const control = root.matches(FOCUSABLE)
53
+ ? root
54
+ : root.querySelector<HTMLElement>(FOCUSABLE);
55
+ if (!control) return false;
56
+ // A scroll the operator asked to keep still is not animated.
57
+ const behavior: ScrollBehavior = prefersReducedMotion() ? "auto" : "smooth";
58
+ field.scrollIntoView?.({ block: "center", behavior });
59
+ control.focus({ preventScroll: true });
60
+ return field.ownerDocument.activeElement === control;
61
+ }
62
+
63
+ /** An element of the page: the headless renderer of the tests gives plain objects. */
64
+ function isElement(value: unknown): value is HTMLElement {
65
+ const isObject = typeof value === "object" && value !== null;
66
+ return isObject && typeof (value as Element).querySelector === "function";
67
+ }
68
+
69
+ function prefersReducedMotion(): boolean {
70
+ if (typeof window === "undefined") return false;
71
+ if (typeof window.matchMedia !== "function") return false;
72
+ return window.matchMedia("(prefers-reduced-motion: reduce)").matches;
73
+ }