@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,508 @@
1
+ import { afterEach, describe, expect, it, vi } from "vitest";
2
+ import { h, onMounted, onUnmounted, provide, ref, shallowRef } from "vue";
3
+ import type { App, Component, Ref, SetupContext, ShallowRef } from "vue";
4
+
5
+ import MapoFormField from "../runtime/components/MapoFormField.vue";
6
+ import { FORM_KEY } from "../runtime/composables/useMapoForm.js";
7
+ import { useFieldAnnotation } from "../runtime/composables/useFieldAnnotation.js";
8
+ import type { MapoFormContext } from "../runtime/composables/useMapoForm.js";
9
+ import type {
10
+ AnyFieldDescriptor,
11
+ FieldAnnotation,
12
+ FieldAnnotations,
13
+ FieldRegistry,
14
+ } from "../runtime/types/index.js";
15
+ import type { FieldRevealRequest } from "../runtime/utils/reveal.js";
16
+ import { createApp, headlessNode } from "./headlessRenderer.js";
17
+ import type { HeadlessNode } from "./headlessRenderer.js";
18
+
19
+ // `useMapoForm.ts` pulls in `nuxt/app` through `useMapoT`, which cannot resolve
20
+ // outside a Nuxt build. The field only injects the form context.
21
+ vi.mock("@mapomodule/i18n/runtime/composables/useMapoT", () => ({
22
+ useMapoT: () => (key: string) => key,
23
+ }));
24
+ // Headless nodes cannot take the focus: a test says whether the control did.
25
+ const focus = vi.hoisted(() => ({
26
+ control: vi.fn((_field: unknown, _id: string) => true),
27
+ }));
28
+ vi.mock(import("../runtime/utils/fieldFocus.js"), async (original) => ({
29
+ ...(await original()),
30
+ focusFieldControl: focus.control,
31
+ }));
32
+
33
+ /** What a test observes of a field component: its lifecycle and what it renders. */
34
+ interface FieldProbe {
35
+ mounted: number;
36
+ unmounted: number;
37
+ /** The element the field renders: the browser keeps the focus on it while it stays. */
38
+ element: HeadlessNode | null;
39
+ /** The descriptor of the last render. */
40
+ descriptor: unknown;
41
+ }
42
+
43
+ /**
44
+ * A field type as the registry holds it, a lazy loader, plus a probe on the
45
+ * component the loader resolves to.
46
+ */
47
+ function fieldType(name: string) {
48
+ const probe: FieldProbe = {
49
+ mounted: 0,
50
+ unmounted: 0,
51
+ element: null,
52
+ descriptor: undefined,
53
+ };
54
+ const component: Component = {
55
+ name,
56
+ props: { descriptor: { type: Object, required: true } },
57
+ setup(props: { descriptor?: unknown }) {
58
+ const element = ref<HeadlessNode | null>(null);
59
+ onMounted(() => {
60
+ probe.mounted++;
61
+ probe.element = element.value;
62
+ });
63
+ onUnmounted(() => {
64
+ probe.unmounted++;
65
+ });
66
+ return () => {
67
+ probe.descriptor = props.descriptor;
68
+ return h("input", { ref: element });
69
+ };
70
+ },
71
+ };
72
+ // `import()` resolves to a module namespace; `__esModule` makes the async
73
+ // component take `default` from this object in the same way.
74
+ const module = { __esModule: true, default: component };
75
+ return { probe, loader: () => Promise.resolve(module) };
76
+ }
77
+
78
+ const registryOf = (mapping: FieldRegistry["mapping"]): FieldRegistry => ({
79
+ mapping,
80
+ attrs: {},
81
+ accessor: {},
82
+ });
83
+
84
+ interface FormOptions {
85
+ annotations?: Ref<FieldAnnotations>;
86
+ currentLang?: string;
87
+ reveal?: Ref<FieldRevealRequest | undefined>;
88
+ }
89
+
90
+ function formContext(
91
+ registry: FieldRegistry,
92
+ options: FormOptions,
93
+ ): MapoFormContext<Record<string, unknown>> {
94
+ return {
95
+ model: ref<Record<string, unknown>>({ title: "Chi siamo" }),
96
+ fields: [],
97
+ errors: ref({}),
98
+ languages: [],
99
+ currentLang: ref(options.currentLang ?? ""),
100
+ readonly: ref(false),
101
+ immediate: true,
102
+ debounce: 0,
103
+ registry,
104
+ setFieldValue: vi.fn(),
105
+ getClientError: () => null,
106
+ markTouched: vi.fn(),
107
+ isTouched: () => false,
108
+ submitted: ref(false),
109
+ annotations: options.annotations ?? ref({}),
110
+ ...(options.reveal ? { reveal: options.reveal } : {}),
111
+ };
112
+ }
113
+
114
+ // The label renders `UIcon` only for async validation or expandable fields, but
115
+ // the template resolves it on every render.
116
+ const UIcon: Component = { render: () => h("i") };
117
+
118
+ // `UPopover` renders its trigger and, as if open, its content.
119
+ const UPopover: Component = {
120
+ name: "UPopover",
121
+ setup(_props: unknown, { slots }: SetupContext) {
122
+ return () =>
123
+ h("div", null, [slots.default?.({ open: true }), slots.content?.()]);
124
+ },
125
+ };
126
+
127
+ // `UButton` declares what the mark binds: `icon` and `color` as props, the
128
+ // accessible name as an attribute.
129
+ interface ButtonStub {
130
+ readonly icon: unknown;
131
+ readonly color: unknown;
132
+ readonly ariaLabel: unknown;
133
+ }
134
+ const buttons: ButtonStub[] = [];
135
+
136
+ const UButton: Component = {
137
+ name: "UButton",
138
+ inheritAttrs: false,
139
+ props: { icon: String, color: String, label: String },
140
+ setup(
141
+ props: { icon?: string; color?: string },
142
+ { attrs, slots }: SetupContext,
143
+ ) {
144
+ const stub: ButtonStub = {
145
+ get icon() {
146
+ return props.icon;
147
+ },
148
+ get color() {
149
+ return props.color;
150
+ },
151
+ get ariaLabel() {
152
+ return attrs["aria-label"];
153
+ },
154
+ };
155
+ buttons.push(stub);
156
+ onUnmounted(() => {
157
+ buttons.splice(buttons.indexOf(stub), 1);
158
+ });
159
+ return () => h("button", null, slots.default?.());
160
+ },
161
+ };
162
+
163
+ /** The marks next to the labels: the buttons with an accessible name. */
164
+ const marks = () => buttons.filter((button) => button.ariaLabel);
165
+
166
+ let apps: App<HeadlessNode>[] = [];
167
+
168
+ /**
169
+ * Mounts one field in a form of its own. Setting `descriptor.value` re-renders
170
+ * the field with that object, as a recomputed `fields` array does.
171
+ */
172
+ function mountField(
173
+ registry: FieldRegistry,
174
+ descriptor: ShallowRef<AnyFieldDescriptor>,
175
+ options: FormOptions = {},
176
+ slots: Record<string, (bindings: never) => unknown> = {},
177
+ ) {
178
+ const context = formContext(registry, options);
179
+ const host: Component = {
180
+ setup() {
181
+ provide(FORM_KEY, context);
182
+ return () => h(MapoFormField, { descriptor: descriptor.value }, slots);
183
+ },
184
+ };
185
+ const app = createApp(host);
186
+ app.component("UIcon", UIcon);
187
+ app.component("UPopover", UPopover);
188
+ app.component("UButton", UButton);
189
+ app.mount(headlessNode());
190
+ apps.push(app);
191
+ }
192
+
193
+ // An async component resolves its loader over a few promise jobs; a timer runs
194
+ // after all of them.
195
+ const settle = () => new Promise((resolve) => setTimeout(resolve, 0));
196
+
197
+ afterEach(() => {
198
+ for (const app of apps) app.unmount();
199
+ apps = [];
200
+ });
201
+
202
+ describe("MapoFormField component", () => {
203
+ it("keeps the field mounted when a new descriptor object has the same type", async () => {
204
+ const text = fieldType("TextField");
205
+ const descriptor = shallowRef<AnyFieldDescriptor>({
206
+ key: "title",
207
+ type: "text",
208
+ label: "Title",
209
+ });
210
+ mountField(registryOf({ text: text.loader }), descriptor);
211
+ await settle();
212
+ const element = text.probe.element;
213
+
214
+ const next: AnyFieldDescriptor = {
215
+ key: "title",
216
+ type: "text",
217
+ label: "Page title",
218
+ };
219
+ descriptor.value = next;
220
+ await settle();
221
+
222
+ expect(text.probe.unmounted).toBe(0);
223
+ expect(text.probe.mounted).toBe(1);
224
+ expect(element).not.toBeNull();
225
+ expect(text.probe.element).toBe(element);
226
+ expect(text.probe.descriptor).toBe(next);
227
+ });
228
+
229
+ it("mounts the new type's component when the type changes", async () => {
230
+ const text = fieldType("TextField");
231
+ const textarea = fieldType("TextareaField");
232
+ const descriptor = shallowRef<AnyFieldDescriptor>({
233
+ key: "title",
234
+ type: "text",
235
+ });
236
+ mountField(
237
+ registryOf({ text: text.loader, textarea: textarea.loader }),
238
+ descriptor,
239
+ );
240
+ await settle();
241
+
242
+ descriptor.value = { key: "title", type: "textarea" };
243
+ await settle();
244
+
245
+ expect(text.probe.unmounted).toBe(1);
246
+ expect(textarea.probe.mounted).toBe(1);
247
+ });
248
+
249
+ it("shows a field of a type already loaded at once, in any form", async () => {
250
+ const text = fieldType("TextField");
251
+ const registry = registryOf({ text: text.loader });
252
+ mountField(registry, shallowRef({ key: "title", type: "text" }));
253
+ await settle();
254
+
255
+ mountField(registry, shallowRef({ key: "subtitle", type: "text" }));
256
+
257
+ expect(text.probe.mounted).toBe(2);
258
+ });
259
+ });
260
+
261
+ describe("MapoFormField annotations", () => {
262
+ const ai: FieldAnnotation = {
263
+ label: "Suggested by AI",
264
+ icon: "i-lucide-sparkles",
265
+ color: "info",
266
+ };
267
+ const toCheck: FieldAnnotation = { ...ai, label: "To check", dot: true };
268
+
269
+ it("follows the annotation map and keeps the field mounted", async () => {
270
+ const text = fieldType("TextField");
271
+ const annotations = ref<FieldAnnotations>({ title: ai });
272
+ mountField(
273
+ registryOf({ text: text.loader }),
274
+ shallowRef({ key: "title", type: "text" }),
275
+ { annotations },
276
+ );
277
+ await settle();
278
+ expect(marks()).toEqual([
279
+ {
280
+ icon: "i-lucide-sparkles",
281
+ color: "info",
282
+ ariaLabel: "Suggested by AI",
283
+ },
284
+ ]);
285
+
286
+ annotations.value = { title: toCheck };
287
+ await settle();
288
+ expect(marks().map((mark) => mark.ariaLabel)).toEqual(["To check"]);
289
+
290
+ annotations.value = {};
291
+ await settle();
292
+ expect(marks()).toEqual([]);
293
+ expect(text.probe.mounted).toBe(1);
294
+ expect(text.probe.unmounted).toBe(0);
295
+ });
296
+
297
+ it("marks a translatable field in the current language, or by its bare key", async () => {
298
+ const text = fieldType("TextField");
299
+ const annotations = ref<FieldAnnotations>({
300
+ "translations.it.title": toCheck,
301
+ });
302
+ mountField(
303
+ registryOf({ text: text.loader }),
304
+ shallowRef({ key: "title", type: "text", translatable: true }),
305
+ { annotations, currentLang: "it" },
306
+ );
307
+ await settle();
308
+ expect(marks().map((mark) => mark.ariaLabel)).toEqual(["To check"]);
309
+
310
+ annotations.value = { title: ai };
311
+ await settle();
312
+ expect(marks().map((mark) => mark.ariaLabel)).toEqual(["Suggested by AI"]);
313
+
314
+ annotations.value = { "translations.en.title": ai };
315
+ await settle();
316
+ expect(marks()).toEqual([]);
317
+ });
318
+
319
+ it("gives the annotation to the label slot and the popover body slot", async () => {
320
+ const text = fieldType("TextField");
321
+ const labelSlot = vi.fn(() => []);
322
+ const bodySlot = vi.fn(() => []);
323
+ mountField(
324
+ registryOf({ text: text.loader }),
325
+ shallowRef({ key: "title", type: "text" }),
326
+ { annotations: ref({ title: ai }) },
327
+ { "field.title.annotation": bodySlot },
328
+ );
329
+ await settle();
330
+ expect(bodySlot).toHaveBeenLastCalledWith(
331
+ expect.objectContaining({ annotation: ai }),
332
+ );
333
+
334
+ mountField(
335
+ registryOf({ text: text.loader }),
336
+ shallowRef({ key: "title", type: "text" }),
337
+ { annotations: ref({ title: ai }) },
338
+ { "field.title.label": labelSlot },
339
+ );
340
+ await settle();
341
+ expect(labelSlot).toHaveBeenLastCalledWith(
342
+ expect.objectContaining({ annotation: ai }),
343
+ );
344
+ });
345
+ });
346
+
347
+ describe("useFieldAnnotation", () => {
348
+ const ai: FieldAnnotation = { label: "Suggested by AI", color: "info" };
349
+ const toCheck: FieldAnnotation = { label: "To check", dot: true };
350
+
351
+ /** A custom field that keeps the annotation it reads at every render. */
352
+ function annotatedFieldType() {
353
+ const seen: { annotation: FieldAnnotation | undefined } = {
354
+ annotation: undefined,
355
+ };
356
+ const component: Component = {
357
+ name: "AnnotatedField",
358
+ props: { descriptor: { type: Object, required: true } },
359
+ setup(props: { descriptor?: AnyFieldDescriptor }) {
360
+ const annotation = useFieldAnnotation(
361
+ () => props.descriptor as AnyFieldDescriptor,
362
+ );
363
+ return () => {
364
+ seen.annotation = annotation.value;
365
+ return h("input");
366
+ };
367
+ },
368
+ };
369
+ const module = { __esModule: true, default: component };
370
+ return { seen, loader: () => Promise.resolve(module) };
371
+ }
372
+
373
+ it("lets a custom field read the annotation its mark shows", async () => {
374
+ const field = annotatedFieldType();
375
+ const annotations = ref<FieldAnnotations>({ title: ai });
376
+ mountField(
377
+ registryOf({ custom: field.loader }),
378
+ shallowRef({ key: "title", type: "custom" }),
379
+ { annotations },
380
+ );
381
+ await settle();
382
+ expect(field.seen.annotation).toEqual(ai);
383
+ expect(marks().map((mark) => mark.ariaLabel)).toEqual(["Suggested by AI"]);
384
+
385
+ annotations.value = { title: toCheck };
386
+ await settle();
387
+ expect(field.seen.annotation).toEqual(toCheck);
388
+
389
+ annotations.value = {};
390
+ await settle();
391
+ expect(field.seen.annotation).toBeUndefined();
392
+ });
393
+
394
+ it("applies the current language and the bare key, as the mark does", async () => {
395
+ const field = annotatedFieldType();
396
+ mountField(
397
+ registryOf({ custom: field.loader }),
398
+ shallowRef({ key: "title", type: "custom", translatable: true }),
399
+ { annotations: ref({ title: ai }), currentLang: "it" },
400
+ );
401
+ await settle();
402
+
403
+ expect(field.seen.annotation).toEqual(ai);
404
+ });
405
+
406
+ it("is undefined outside a form", () => {
407
+ let read: FieldAnnotation | undefined = ai;
408
+ const standalone: Component = {
409
+ setup() {
410
+ const annotation = useFieldAnnotation({ key: "title", type: "text" });
411
+ return () => {
412
+ read = annotation.value;
413
+ return h("input");
414
+ };
415
+ },
416
+ };
417
+ const app = createApp(standalone);
418
+ app.mount(headlessNode());
419
+ apps.push(app);
420
+
421
+ expect(read).toBeUndefined();
422
+ });
423
+ });
424
+
425
+ describe("MapoFormField reveal", () => {
426
+ /** A request of `revealField()` for the field of `key`, its end recorded. */
427
+ function request(key: string, rest = ""): FieldRevealRequest {
428
+ const path = rest ? `${key}.${rest}` : key;
429
+ return { path, key, rest, settle: vi.fn() };
430
+ }
431
+
432
+ const wait = (ms: number) =>
433
+ new Promise((resolve) => setTimeout(resolve, ms));
434
+
435
+ afterEach(() => {
436
+ focus.control.mockReset();
437
+ focus.control.mockImplementation(() => true);
438
+ });
439
+
440
+ it("focuses its control when the form reveals it, and ends the request", async () => {
441
+ const text = fieldType("TextField");
442
+ const asked = request("title");
443
+ mountField(
444
+ registryOf({ text: text.loader }),
445
+ shallowRef<AnyFieldDescriptor>({ key: "title", type: "text" }),
446
+ { reveal: shallowRef<FieldRevealRequest | undefined>(asked) },
447
+ );
448
+
449
+ await vi.waitFor(() => expect(asked.settle).toHaveBeenCalledWith(true));
450
+ const [element, id] = focus.control.mock.calls[0] ?? [];
451
+ expect(id).toBe("field-title");
452
+ expect(String((element as HeadlessNode).props.class)).toContain(
453
+ "mapo-form-field",
454
+ );
455
+ });
456
+
457
+ it("looks again until its control renders, as a field loaded lazily does", async () => {
458
+ focus.control.mockReturnValueOnce(false).mockReturnValueOnce(false);
459
+ const text = fieldType("TextField");
460
+ const asked = request("title");
461
+ mountField(
462
+ registryOf({ text: text.loader }),
463
+ shallowRef<AnyFieldDescriptor>({ key: "title", type: "text" }),
464
+ { reveal: shallowRef<FieldRevealRequest | undefined>(asked) },
465
+ );
466
+
467
+ await vi.waitFor(() => expect(asked.settle).toHaveBeenCalledWith(true));
468
+ expect(focus.control).toHaveBeenCalledTimes(3);
469
+ });
470
+
471
+ it("leaves a request for another field, or for a value inside its own", async () => {
472
+ const text = fieldType("TextField");
473
+ const reveal = shallowRef<FieldRevealRequest | undefined>(
474
+ request("subtitle"),
475
+ );
476
+ mountField(
477
+ registryOf({ text: text.loader }),
478
+ shallowRef<AnyFieldDescriptor>({ key: "title", type: "text" }),
479
+ { reveal },
480
+ );
481
+ await wait(60);
482
+ reveal.value = request("title", "0.name");
483
+ await wait(60);
484
+
485
+ expect(focus.control).not.toHaveBeenCalled();
486
+ });
487
+
488
+ it("stops looking once the request ends", async () => {
489
+ focus.control.mockImplementation(() => false);
490
+ const text = fieldType("TextField");
491
+ const asked = request("title");
492
+ const reveal = shallowRef<FieldRevealRequest | undefined>(asked);
493
+ mountField(
494
+ registryOf({ text: text.loader }),
495
+ shallowRef<AnyFieldDescriptor>({ key: "title", type: "text" }),
496
+ { reveal },
497
+ );
498
+ await wait(120);
499
+
500
+ reveal.value = undefined;
501
+ const looks = focus.control.mock.calls.length;
502
+ await wait(120);
503
+
504
+ expect(looks).toBeGreaterThan(1);
505
+ expect(focus.control).toHaveBeenCalledTimes(looks);
506
+ expect(asked.settle).not.toHaveBeenCalled();
507
+ });
508
+ });
@@ -0,0 +1,141 @@
1
+ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
2
+ import { h, nextTick, provide, ref } from "vue";
3
+ import type { App, Component, Ref } from "vue";
4
+
5
+ import MapoFormGroup from "../runtime/components/MapoFormGroup.vue";
6
+ import { FORM_KEY } from "../runtime/composables/useMapoForm.js";
7
+ import type { MapoFormContext } from "../runtime/composables/useMapoForm.js";
8
+ import type { AnyFieldDescriptor } from "../runtime/types/index.js";
9
+ import type { FieldRevealRequest } from "../runtime/utils/reveal.js";
10
+ import { createApp, findAll, headlessNode } from "./headlessRenderer.js";
11
+ import type { HeadlessNode } from "./headlessRenderer.js";
12
+
13
+ // `useMapoForm.ts` pulls in `nuxt/app` through `useMapoT`, which cannot resolve
14
+ // outside a Nuxt build. The group only injects the form context.
15
+ vi.mock("@mapomodule/i18n/runtime/composables/useMapoT", () => ({
16
+ useMapoT: () => (key: string) => key,
17
+ }));
18
+ // The group reads whether groups start open from the app's config.
19
+ vi.mock("#app", () => ({ useRuntimeConfig: () => ({ public: {} }) }));
20
+ // The fields are out of scope: each renders its key, so a test sees which
21
+ // ones the group shows.
22
+ vi.mock("../runtime/components/MapoFormField.vue", async () => {
23
+ const { h: render } = await import("vue");
24
+ return {
25
+ default: {
26
+ name: "MapoFormField",
27
+ props: { descriptor: { type: Object, required: true } },
28
+ setup: (props: { descriptor: AnyFieldDescriptor }) => () =>
29
+ render("div", { "data-field": props.descriptor.key }),
30
+ },
31
+ };
32
+ });
33
+
34
+ const UIcon: Component = { render: () => h("i") };
35
+
36
+ let app: App<HeadlessNode> | undefined;
37
+
38
+ interface GroupProps {
39
+ fields: AnyFieldDescriptor[];
40
+ subtabs?: Map<string, AnyFieldDescriptor[]>;
41
+ }
42
+
43
+ /** Mounts a closed group in a form whose `reveal` the test sets. */
44
+ function mountGroup(
45
+ reveal: Ref<FieldRevealRequest | undefined>,
46
+ props: GroupProps,
47
+ ) {
48
+ const context = {
49
+ model: ref({}),
50
+ currentLang: ref(""),
51
+ reveal,
52
+ } as unknown as MapoFormContext<Record<string, unknown>>;
53
+ const host: Component = {
54
+ setup() {
55
+ provide(FORM_KEY, context);
56
+ return () =>
57
+ h(MapoFormGroup, { name: "details", initialExpanded: false, ...props });
58
+ },
59
+ };
60
+ app = createApp(host);
61
+ app.component("UIcon", UIcon);
62
+ const root = headlessNode();
63
+ app.mount(root);
64
+ return root;
65
+ }
66
+
67
+ /** Whether a node shows: no element around it is hidden by `v-show`. */
68
+ function isShown(node: HeadlessNode | null): boolean {
69
+ if (!node) return true;
70
+ return node.style.display !== "none" && isShown(node.parent);
71
+ }
72
+
73
+ /** The keys of the fields the group shows. */
74
+ const shownFields = (root: HeadlessNode) =>
75
+ findAll(root, (node) => node.props["data-field"] !== undefined)
76
+ .filter(isShown)
77
+ .map((node) => node.props["data-field"]);
78
+
79
+ /** A request of `revealField()` for the field of `key`. */
80
+ const request = (key: string): FieldRevealRequest => ({
81
+ path: key,
82
+ key,
83
+ rest: "",
84
+ settle: vi.fn(),
85
+ });
86
+
87
+ const field = (key: string): AnyFieldDescriptor => ({ key, type: "text" });
88
+
89
+ // The group listens for Escape on the page, which the headless renderer has not.
90
+ beforeEach(() => {
91
+ vi.stubGlobal("document", {
92
+ addEventListener: vi.fn(),
93
+ removeEventListener: vi.fn(),
94
+ body: { style: {} },
95
+ });
96
+ });
97
+
98
+ afterEach(() => {
99
+ app?.unmount();
100
+ app = undefined;
101
+ vi.unstubAllGlobals();
102
+ });
103
+
104
+ describe("MapoFormGroup reveal", () => {
105
+ it("opens when the form reveals one of its fields", async () => {
106
+ const reveal = ref<FieldRevealRequest | undefined>();
107
+ const root = mountGroup(reveal, {
108
+ fields: [field("title"), field("slug")],
109
+ });
110
+ expect(shownFields(root)).toEqual([]);
111
+
112
+ reveal.value = request("slug");
113
+ await nextTick();
114
+
115
+ expect(shownFields(root)).toEqual(["title", "slug"]);
116
+ });
117
+
118
+ it("opens the sub-tab that holds the field", async () => {
119
+ const reveal = ref<FieldRevealRequest | undefined>();
120
+ const subtabs = new Map([
121
+ ["Basics", [field("name")]],
122
+ ["More", [field("notes")]],
123
+ ]);
124
+ const root = mountGroup(reveal, { fields: [], subtabs });
125
+
126
+ reveal.value = request("notes");
127
+ await nextTick();
128
+
129
+ expect(shownFields(root)).toEqual(["notes"]);
130
+ });
131
+
132
+ it("stays closed for a field of another group", async () => {
133
+ const reveal = ref<FieldRevealRequest | undefined>();
134
+ const root = mountGroup(reveal, { fields: [field("title")] });
135
+
136
+ reveal.value = request("seo_title");
137
+ await nextTick();
138
+
139
+ expect(shownFields(root)).toEqual([]);
140
+ });
141
+ });