@mapomodule/form 2.0.0-beta.15 → 2.0.0-beta.17

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 (43) hide show
  1. package/dist/__tests__/MapoWygEditor.component.test.d.ts +2 -0
  2. package/dist/__tests__/MapoWygEditor.component.test.d.ts.map +1 -0
  3. package/dist/__tests__/formatHtml.test.d.ts +2 -0
  4. package/dist/__tests__/formatHtml.test.d.ts.map +1 -0
  5. package/dist/__tests__/sanitizeHtml.test.d.ts +2 -0
  6. package/dist/__tests__/sanitizeHtml.test.d.ts.map +1 -0
  7. package/dist/index.d.mts +1 -1
  8. package/dist/index.d.ts +1 -1
  9. package/dist/index.d.ts.map +1 -1
  10. package/dist/module.d.mts +13 -0
  11. package/dist/module.d.ts +13 -0
  12. package/dist/module.d.ts.map +1 -1
  13. package/dist/module.json +1 -1
  14. package/dist/module.mjs +6 -1
  15. package/dist/runtime/components/fields/MapoWygEditor.vue +351 -51
  16. package/dist/runtime/components/fields/MapoWygEditor.vue.d.ts.map +1 -1
  17. package/dist/runtime/devtools/DevtoolsFormsPage.vue +22 -0
  18. package/dist/runtime/devtools/DevtoolsFormsPage.vue.d.ts.map +1 -1
  19. package/dist/runtime/types/descriptor.d.ts +64 -0
  20. package/dist/runtime/types/descriptor.d.ts.map +1 -1
  21. package/dist/runtime/types/index.d.ts +1 -1
  22. package/dist/runtime/types/index.d.ts.map +1 -1
  23. package/dist/runtime/types/registry.d.ts +6 -1
  24. package/dist/runtime/types/registry.d.ts.map +1 -1
  25. package/dist/runtime/utils/formatHtml.d.ts +16 -0
  26. package/dist/runtime/utils/formatHtml.d.ts.map +1 -0
  27. package/dist/runtime/utils/formatHtml.js +137 -0
  28. package/dist/runtime/utils/sanitizeHtml.d.ts +16 -0
  29. package/dist/runtime/utils/sanitizeHtml.d.ts.map +1 -0
  30. package/dist/runtime/utils/sanitizeHtml.js +37 -0
  31. package/package.json +3 -2
  32. package/src/__tests__/MapoWygEditor.component.test.ts +886 -0
  33. package/src/__tests__/formatHtml.test.ts +145 -0
  34. package/src/__tests__/sanitizeHtml.test.ts +40 -0
  35. package/src/index.ts +2 -0
  36. package/src/module.ts +20 -2
  37. package/src/runtime/components/fields/MapoWygEditor.vue +532 -69
  38. package/src/runtime/devtools/DevtoolsFormsPage.vue +23 -0
  39. package/src/runtime/types/descriptor.ts +72 -1
  40. package/src/runtime/types/index.ts +2 -0
  41. package/src/runtime/types/registry.ts +3 -1
  42. package/src/runtime/utils/formatHtml.ts +198 -0
  43. package/src/runtime/utils/sanitizeHtml.ts +60 -0
@@ -0,0 +1,886 @@
1
+ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
2
+ import { createRenderer, h, nextTick, ref } from "vue";
3
+ import type { App, Component, Ref } from "vue";
4
+ import TextAlign from "@tiptap/extension-text-align";
5
+
6
+ import MapoWygEditor from "../runtime/components/fields/MapoWygEditor.vue";
7
+ import type { EditorDescriptor } from "../runtime/types/index.js";
8
+
9
+ // The editor field: its toolbar (links, alignment, custom buttons) and the
10
+ // HTML source view (`attrs.source`).
11
+ // Tiptap needs a DOM, which these tests do not have: `@tiptap/vue-3` is
12
+ // replaced by an editor that keeps its document as an HTML string and
13
+ // normalizes what it is given, the way a schema would.
14
+
15
+ interface FakeEditor {
16
+ getHTML: () => string;
17
+ commands: { setContent: ReturnType<typeof vi.fn> };
18
+ setEditable: ReturnType<typeof vi.fn>;
19
+ isActive: ReturnType<typeof vi.fn>;
20
+ getAttributes: ReturnType<typeof vi.fn>;
21
+ state: { selection: { empty: boolean } };
22
+ chain: () => unknown;
23
+ can: () => unknown;
24
+ destroy: ReturnType<typeof vi.fn>;
25
+ /** The commands run through `chain()`, in order, with their arguments. */
26
+ calls: [string, ...unknown[]][];
27
+ }
28
+
29
+ const tiptap = vi.hoisted(() => ({
30
+ editor: undefined as unknown,
31
+ options: undefined as { extensions: { name: string }[] } | undefined,
32
+ }));
33
+
34
+ /**
35
+ * What the fake schema does to HTML: whitespace between tags goes, a `<span>`
36
+ * (no extension supports it) is unwrapped, an empty document is one empty
37
+ * paragraph.
38
+ */
39
+ const normalize = (html: string) =>
40
+ html
41
+ .replace(/>[ \t\n\f\r]+</g, "><")
42
+ .replace(/<\/?span[^>]*>/g, "")
43
+ .trim() || "<p></p>";
44
+
45
+ function createFakeEditor(content: string): FakeEditor {
46
+ let html = normalize(content);
47
+ const calls: [string, ...unknown[]][] = [];
48
+ // A command chain: any command returns the chain and is recorded, `run()`
49
+ // applies nothing. `can()` answers through a chain that records nothing.
50
+ const chain: unknown = new Proxy(() => chain, {
51
+ get:
52
+ (_target, name) =>
53
+ (...args: unknown[]) => {
54
+ calls.push([String(name), ...args]);
55
+ return chain;
56
+ },
57
+ });
58
+ const dryRun: unknown = new Proxy(() => dryRun, {
59
+ get: () => () => dryRun,
60
+ });
61
+ return {
62
+ getHTML: () => html,
63
+ commands: {
64
+ setContent: vi.fn((value: string) => {
65
+ html = normalize(value);
66
+ }),
67
+ },
68
+ setEditable: vi.fn(),
69
+ isActive: vi.fn(() => false),
70
+ getAttributes: vi.fn(() => ({})),
71
+ state: { selection: { empty: false } },
72
+ chain: () => chain,
73
+ can: () => dryRun,
74
+ destroy: vi.fn(),
75
+ calls,
76
+ };
77
+ }
78
+
79
+ vi.mock("@tiptap/vue-3", async () => {
80
+ const { h, shallowRef } = await import("vue");
81
+ return {
82
+ useEditor: (options: {
83
+ content: string;
84
+ extensions: { name: string }[];
85
+ }) => {
86
+ tiptap.options = options;
87
+ tiptap.editor = createFakeEditor(options.content);
88
+ return shallowRef(tiptap.editor);
89
+ },
90
+ EditorContent: {
91
+ name: "EditorContent",
92
+ props: { editor: { type: Object, default: undefined } },
93
+ render: () => h("editor-content"),
94
+ },
95
+ };
96
+ });
97
+
98
+ // The DOM sanitizer returns its input without a DOM; this stand-in removes the
99
+ // vectors it targets, so the tests see whether the source goes through it.
100
+ vi.mock("../runtime/utils/sanitizeHtml.js", async (importOriginal) => ({
101
+ ...(await importOriginal<Record<string, unknown>>()),
102
+ sanitizeHtml: vi.fn((html: string) =>
103
+ html
104
+ .replace(/<script[\s\S]*?<\/script>/gi, "")
105
+ .replace(/\son\w+="[^"]*"/gi, "")
106
+ .replace(/\shref="javascript:[^"]*"/gi, ""),
107
+ ),
108
+ }));
109
+
110
+ vi.mock("vue-i18n", () => ({ useI18n: () => ({ t: (key: string) => key }) }));
111
+
112
+ // The module's runtime config; `beforeEach` restores what the module writes by default.
113
+ const runtimeConfig = vi.hoisted(() => ({
114
+ public: {
115
+ mapoForm: undefined as
116
+ | { editor: { source: boolean; textAlign?: boolean } }
117
+ | undefined,
118
+ },
119
+ }));
120
+ vi.mock("#app", () => ({ useRuntimeConfig: () => runtimeConfig }));
121
+
122
+ // Nodes are plain objects: each keeps its tag, its props (attributes and
123
+ // listeners included) and its text; `style` takes what `v-show` writes.
124
+ interface HeadlessNode {
125
+ type: string;
126
+ text: string;
127
+ parent: HeadlessNode | null;
128
+ children: HeadlessNode[];
129
+ props: Record<string, unknown>;
130
+ style: Record<string, string>;
131
+ }
132
+
133
+ const headlessNode = (type: string, text = ""): HeadlessNode => ({
134
+ type,
135
+ text,
136
+ parent: null,
137
+ children: [],
138
+ props: {},
139
+ style: {},
140
+ });
141
+
142
+ const { createApp } = createRenderer<HeadlessNode, HeadlessNode>({
143
+ createElement: (type) => headlessNode(type),
144
+ createText: (text) => headlessNode("#text", text),
145
+ createComment: (text) => headlessNode("#comment", text),
146
+ setText: (node, text) => {
147
+ node.text = text;
148
+ },
149
+ setElementText: (node, text) => {
150
+ node.children = [];
151
+ node.text = text;
152
+ },
153
+ patchProp(node, key, _previous, next) {
154
+ node.props[key] = next;
155
+ },
156
+ insert(child, parent, anchor) {
157
+ child.parent = parent;
158
+ const at = anchor ? parent.children.indexOf(anchor) : -1;
159
+ parent.children.splice(at < 0 ? parent.children.length : at, 0, child);
160
+ },
161
+ remove(child) {
162
+ child.parent?.children.splice(child.parent.children.indexOf(child), 1);
163
+ child.parent = null;
164
+ },
165
+ parentNode: (node) => node.parent,
166
+ nextSibling: (node) =>
167
+ node.parent?.children[node.parent.children.indexOf(node) + 1] ?? null,
168
+ });
169
+
170
+ // Nuxt UI stand-ins: the element each one renders keeps the attributes and
171
+ // listeners the editor passes.
172
+ const stubs: Record<string, Component> = {
173
+ UButton: {
174
+ setup:
175
+ (_, { slots }) =>
176
+ () =>
177
+ h("button", slots.default?.()),
178
+ },
179
+ UTooltip: {
180
+ props: { text: { type: String, default: "" } },
181
+ setup:
182
+ (props, { slots }) =>
183
+ () =>
184
+ h("tooltip", { text: props.text }, slots.default?.()),
185
+ },
186
+ USeparator: { render: () => h("separator") },
187
+ UInput: {
188
+ props: { modelValue: { type: String, default: "" } },
189
+ emits: ["update:modelValue"],
190
+ setup:
191
+ (props, { emit }) =>
192
+ () =>
193
+ h("input", {
194
+ value: props.modelValue,
195
+ onInput: (value: string) => emit("update:modelValue", value),
196
+ }),
197
+ },
198
+ UTextarea: {
199
+ props: { modelValue: { type: String, default: "" } },
200
+ emits: ["update:modelValue"],
201
+ setup:
202
+ (props, { emit }) =>
203
+ () =>
204
+ h("textarea", {
205
+ value: props.modelValue,
206
+ onInput: (value: string) => emit("update:modelValue", value),
207
+ }),
208
+ },
209
+ MapoMediaManagerDialog: { render: () => null },
210
+ };
211
+
212
+ const all = (node: HeadlessNode): HeadlessNode[] => [
213
+ node,
214
+ ...node.children.flatMap(all),
215
+ ];
216
+
217
+ let app: App<HeadlessNode> | undefined;
218
+ let root: HeadlessNode;
219
+ let modelValue: Ref<string>;
220
+ let emitted: string[];
221
+
222
+ const fakeEditor = () => tiptap.editor as FakeEditor;
223
+ const buttons = () => all(root).filter((node) => node.type === "button");
224
+ const sourceToggle = () =>
225
+ buttons().find((node) => node.props.icon === "i-lucide-code-xml");
226
+ const textarea = () => all(root).find((node) => node.type === "textarea");
227
+ const editorContent = () =>
228
+ all(root).find((node) => node.type === "editor-content")!;
229
+ const isHidden = (node: HeadlessNode) => node.style.display === "none";
230
+
231
+ function click(node: HeadlessNode | undefined) {
232
+ (node!.props.onClick as () => void)();
233
+ }
234
+
235
+ /** Types into the source textarea: the stub reports it as `update:modelValue`. */
236
+ function typeSource(html: string) {
237
+ (textarea()!.props.onInput as (value: string) => void)(html);
238
+ }
239
+
240
+ function mount(
241
+ attrs: EditorDescriptor["attrs"] = {},
242
+ state: { readonly?: boolean } = {},
243
+ ) {
244
+ root = headlessNode("root");
245
+ const descriptor: EditorDescriptor = { key: "body", type: "editor", attrs };
246
+ const host: Component = {
247
+ render: () =>
248
+ h(MapoWygEditor, {
249
+ modelValue: modelValue.value,
250
+ descriptor,
251
+ readonly: state.readonly,
252
+ disabled: state.readonly,
253
+ "onUpdate:modelValue": (value: string) => emitted.push(value),
254
+ }),
255
+ };
256
+ app = createApp(host);
257
+ for (const [name, stub] of Object.entries(stubs)) app.component(name, stub);
258
+ app.mount(root);
259
+ }
260
+
261
+ beforeEach(() => {
262
+ vi.useFakeTimers();
263
+ modelValue = ref("<p>Hello <strong>world</strong></p><h2>Title</h2>");
264
+ emitted = [];
265
+ runtimeConfig.public.mapoForm = { editor: { source: true } };
266
+ });
267
+
268
+ afterEach(() => {
269
+ app?.unmount();
270
+ app = undefined;
271
+ vi.useRealTimers();
272
+ });
273
+
274
+ describe("MapoWygEditor without attrs", () => {
275
+ it("renders the built-in toolbar and the source toggle, enabled, and the editor", () => {
276
+ mount();
277
+
278
+ expect(buttons()).toHaveLength(12);
279
+ expect(buttons().every((node) => !node.props.disabled)).toBe(true);
280
+ expect(sourceToggle()).toBeDefined();
281
+ expect(textarea()).toBeUndefined();
282
+ expect(isHidden(editorContent())).toBe(false);
283
+ });
284
+
285
+ it("renders the built-in toolbar only when the field turns the source view off", () => {
286
+ mount({ source: false });
287
+
288
+ expect(buttons()).toHaveLength(11);
289
+ expect(sourceToggle()).toBeUndefined();
290
+ });
291
+
292
+ it("disables the built-in toolbar when read-only, not the source toggle", () => {
293
+ mount({}, { readonly: true });
294
+
295
+ const builtIn = buttons().filter((node) => node !== sourceToggle());
296
+ expect(builtIn.every((node) => node.props.disabled)).toBe(true);
297
+ expect(sourceToggle()!.props.disabled).toBeFalsy();
298
+ });
299
+ });
300
+
301
+ describe("MapoWygEditor source toggle default", () => {
302
+ it("follows the module option when the field does not set attrs.source", () => {
303
+ runtimeConfig.public.mapoForm = { editor: { source: false } };
304
+ mount();
305
+
306
+ expect(sourceToggle()).toBeUndefined();
307
+ });
308
+
309
+ it("lets the field's attrs.source win over the module option, both ways", () => {
310
+ runtimeConfig.public.mapoForm = { editor: { source: false } };
311
+ mount({ source: true });
312
+ expect(sourceToggle()).toBeDefined();
313
+ app!.unmount();
314
+
315
+ runtimeConfig.public.mapoForm = { editor: { source: true } };
316
+ mount({ source: false });
317
+ expect(sourceToggle()).toBeUndefined();
318
+ });
319
+
320
+ it("shows the toggle when the app has no form runtime config", () => {
321
+ runtimeConfig.public.mapoForm = undefined;
322
+ mount();
323
+
324
+ expect(sourceToggle()).toBeDefined();
325
+ });
326
+ });
327
+
328
+ describe("MapoWygEditor source view", () => {
329
+ it("shows the editor's HTML laid out in a textarea, keeping the editor mounted", async () => {
330
+ mount({ source: true });
331
+
332
+ click(sourceToggle());
333
+ await nextTick();
334
+
335
+ expect(textarea()!.props.value).toBe(
336
+ "<p>Hello <strong>world</strong></p>\n<h2>Title</h2>",
337
+ );
338
+ expect(isHidden(editorContent())).toBe(true);
339
+ expect(sourceToggle()!.props["aria-pressed"]).toBe(true);
340
+ expect(fakeEditor().destroy).not.toHaveBeenCalled();
341
+ });
342
+
343
+ it("disables every other toolbar button and keeps the toggle active", async () => {
344
+ mount({ source: true });
345
+
346
+ click(sourceToggle());
347
+ await nextTick();
348
+
349
+ const others = buttons().filter((node) => node !== sourceToggle());
350
+ expect(others.every((node) => node.props.disabled)).toBe(true);
351
+ expect(sourceToggle()!.props.disabled).toBeFalsy();
352
+ });
353
+
354
+ it("writes the typing into the editor after a pause and emits the editor's HTML", async () => {
355
+ mount({ source: true });
356
+ click(sourceToggle());
357
+ await nextTick();
358
+
359
+ typeSource("<p>One</p>\n<p>Two <span>words</span></p>");
360
+ expect(fakeEditor().commands.setContent).not.toHaveBeenCalled();
361
+ vi.advanceTimersByTime(250);
362
+
363
+ expect(fakeEditor().commands.setContent).toHaveBeenCalledWith(
364
+ "<p>One</p>\n<p>Two <span>words</span></p>",
365
+ false,
366
+ );
367
+ // Normalized by the editor: the layout whitespace and the unsupported tag are gone.
368
+ expect(emitted).toEqual(["<p>One</p><p>Two words</p>"]);
369
+ });
370
+
371
+ it("passes the source through the sanitizer, so script, handlers and javascript: links never reach the value", async () => {
372
+ mount({ source: true });
373
+ click(sourceToggle());
374
+ await nextTick();
375
+
376
+ typeSource(
377
+ '<p onclick="steal()">Hi</p><script>alert(1)</script><p><a href="javascript:alert(1)">link</a></p>',
378
+ );
379
+ vi.advanceTimersByTime(250);
380
+
381
+ expect(fakeEditor().commands.setContent).toHaveBeenCalledWith(
382
+ "<p>Hi</p><p><a>link</a></p>",
383
+ false,
384
+ );
385
+ expect(emitted).toEqual(["<p>Hi</p><p><a>link</a></p>"]);
386
+ });
387
+
388
+ it("emits nothing when the typing leaves the document as it was", async () => {
389
+ mount({ source: true });
390
+ click(sourceToggle());
391
+ await nextTick();
392
+
393
+ typeSource("<p>Hello <strong>world</strong></p>\n\n<h2>Title</h2> ");
394
+ vi.advanceTimersByTime(250);
395
+
396
+ expect(emitted).toEqual([]);
397
+ });
398
+
399
+ it("goes back to the editor, already up to date, and round-trips again", async () => {
400
+ mount({ source: true });
401
+ click(sourceToggle());
402
+ await nextTick();
403
+ typeSource("<ul><li><p>Item</p></li></ul>");
404
+
405
+ // Leaving before the pause still applies the typing.
406
+ click(sourceToggle());
407
+ await nextTick();
408
+
409
+ expect(emitted).toEqual(["<ul><li><p>Item</p></li></ul>"]);
410
+ expect(textarea()).toBeUndefined();
411
+ expect(isHidden(editorContent())).toBe(false);
412
+ expect(fakeEditor().getHTML()).toBe("<ul><li><p>Item</p></li></ul>");
413
+
414
+ click(sourceToggle());
415
+ await nextTick();
416
+
417
+ expect(textarea()!.props.value).toBe(
418
+ "<ul>\n <li>\n <p>Item</p>\n </li>\n</ul>",
419
+ );
420
+ });
421
+
422
+ it("does not rewrite the textarea when the field's own value comes back", async () => {
423
+ mount({ source: true });
424
+ click(sourceToggle());
425
+ await nextTick();
426
+
427
+ typeSource("<p>Typed</p>\n");
428
+ vi.advanceTimersByTime(250);
429
+ modelValue.value = emitted[0]!;
430
+ await nextTick();
431
+
432
+ expect(textarea()!.props.value).toBe("<p>Typed</p>\n");
433
+ expect(fakeEditor().commands.setContent).toHaveBeenCalledTimes(1);
434
+ });
435
+
436
+ it("shows a value set from outside, dropping the typing it replaces", async () => {
437
+ mount({ source: true });
438
+ click(sourceToggle());
439
+ await nextTick();
440
+ typeSource("<p>Not saved</p>");
441
+
442
+ modelValue.value = "<p>Draft</p><p>restored</p>";
443
+ await nextTick();
444
+ vi.advanceTimersByTime(250);
445
+
446
+ expect(textarea()!.props.value).toBe("<p>Draft</p>\n<p>restored</p>");
447
+ expect(fakeEditor().getHTML()).toBe("<p>Draft</p><p>restored</p>");
448
+ expect(emitted).toEqual([]);
449
+ });
450
+
451
+ it("applies the typing at once when the textarea loses the focus", async () => {
452
+ mount({ source: true });
453
+ click(sourceToggle());
454
+ await nextTick();
455
+
456
+ typeSource("<p>Saved right away</p>");
457
+ (textarea()!.props.onBlur as () => void)();
458
+
459
+ expect(emitted).toEqual(["<p>Saved right away</p>"]);
460
+ vi.advanceTimersByTime(250);
461
+ expect(emitted).toHaveLength(1);
462
+ });
463
+
464
+ it("applies pending typing when the field unmounts", async () => {
465
+ mount({ source: true });
466
+ click(sourceToggle());
467
+ await nextTick();
468
+
469
+ typeSource("<p>Last words</p>");
470
+ app!.unmount();
471
+ app = undefined;
472
+
473
+ expect(emitted).toEqual(["<p>Last words</p>"]);
474
+ });
475
+
476
+ it("shows the source of a read-only field without letting it change", async () => {
477
+ mount({ source: true }, { readonly: true });
478
+
479
+ expect(sourceToggle()!.props.disabled).toBeFalsy();
480
+ click(sourceToggle());
481
+ await nextTick();
482
+
483
+ expect(textarea()!.props.readonly).toBe(true);
484
+ typeSource("<p>Changed</p>");
485
+ vi.advanceTimersByTime(250);
486
+
487
+ expect(textarea()!.props.value).toBe(
488
+ "<p>Hello <strong>world</strong></p>\n<h2>Title</h2>",
489
+ );
490
+ expect(fakeEditor().commands.setContent).not.toHaveBeenCalled();
491
+ expect(emitted).toEqual([]);
492
+ });
493
+ });
494
+
495
+ describe("MapoWygEditor custom toolbar buttons", () => {
496
+ /** The toolbar's elements in order, without the anchors of fragments. */
497
+ const toolbarRow = () =>
498
+ all(root)
499
+ .find((node) => node.children.some((child) => child.type === "tooltip"))!
500
+ .children.filter((node) => !node.type.startsWith("#"));
501
+ const tooltipOf = (label: string) =>
502
+ all(root).find(
503
+ (node) => node.type === "tooltip" && node.props.text === label,
504
+ );
505
+ const buttonOf = (label: string) =>
506
+ buttons().find((node) => node.props["aria-label"] === label);
507
+ const hasActiveClass = (node: HeadlessNode | undefined) =>
508
+ String(node!.props.class ?? "").includes("bg-gray-200");
509
+
510
+ it("renders the buttons after the built-in ones, past a separator", () => {
511
+ mount({
512
+ toolbar: [
513
+ {
514
+ key: "table",
515
+ icon: "i-lucide-table",
516
+ label: "Insert table",
517
+ action: () => {},
518
+ },
519
+ { key: "quote", label: "Quote", action: () => {} },
520
+ ],
521
+ });
522
+
523
+ const row = toolbarRow();
524
+ const table = row.indexOf(tooltipOf("Insert table")!);
525
+ expect(row[table - 1]!.type).toBe("separator");
526
+ expect(row[table - 2]).toBe(tooltipOf("mapo.wygEditor.insertImage"));
527
+ expect(row[table + 1]).toBe(tooltipOf("Quote"));
528
+ // 11 built-in, 2 custom, the source toggle.
529
+ expect(buttons()).toHaveLength(14);
530
+
531
+ expect(buttonOf("Insert table")!.props.icon).toBe("i-lucide-table");
532
+ // A button with no icon shows its label.
533
+ expect(buttonOf("Quote")!.props.label).toBe("Quote");
534
+ });
535
+
536
+ it("runs the action with the editor on click", () => {
537
+ const action = vi.fn();
538
+ mount({ toolbar: [{ key: "x", label: "X", action }] });
539
+
540
+ click(buttonOf("X"));
541
+
542
+ expect(action).toHaveBeenCalledWith(fakeEditor());
543
+ });
544
+
545
+ it("shows the active state and disables the button as its predicates say", () => {
546
+ mount({
547
+ toolbar: [
548
+ {
549
+ key: "on",
550
+ label: "On",
551
+ action: () => {},
552
+ isActive: () => true,
553
+ isDisabled: () => false,
554
+ },
555
+ { key: "off", label: "Off", action: () => {}, isDisabled: () => true },
556
+ ],
557
+ });
558
+
559
+ expect(hasActiveClass(buttonOf("On"))).toBe(true);
560
+ expect(buttonOf("On")!.props.disabled).toBe(false);
561
+ expect(hasActiveClass(buttonOf("Off"))).toBe(false);
562
+ expect(buttonOf("Off")!.props.disabled).toBe(true);
563
+ });
564
+
565
+ it("disables the buttons when read-only and in the source view", async () => {
566
+ const toolbar = [{ key: "x", label: "X", action: () => {} }];
567
+ mount({ toolbar }, { readonly: true });
568
+ expect(buttonOf("X")!.props.disabled).toBe(true);
569
+ app!.unmount();
570
+
571
+ mount({ toolbar, source: true });
572
+ expect(buttonOf("X")!.props.disabled).toBe(false);
573
+ click(sourceToggle());
574
+ await nextTick();
575
+ expect(buttonOf("X")!.props.disabled).toBe(true);
576
+ });
577
+
578
+ it("keeps the source toggle last, after the custom buttons", () => {
579
+ mount({
580
+ toolbar: [{ key: "x", label: "X", action: () => {} }],
581
+ source: true,
582
+ });
583
+
584
+ const row = toolbarRow();
585
+ expect(row.at(-1)).toBe(tooltipOf("mapo.wygEditor.source"));
586
+ expect(row.at(-2)!.type).toBe("separator");
587
+ expect(row.at(-3)).toBe(tooltipOf("X"));
588
+ });
589
+
590
+ it("treats a predicate that throws as inactive and disabled, without breaking the toolbar", () => {
591
+ const missingCommand = () => {
592
+ throw new TypeError("addRowAfter is not a function");
593
+ };
594
+ mount({
595
+ toolbar: [
596
+ {
597
+ key: "row",
598
+ label: "Add row",
599
+ action: () => {},
600
+ isActive: missingCommand,
601
+ isDisabled: missingCommand,
602
+ },
603
+ ],
604
+ });
605
+
606
+ expect(hasActiveClass(buttonOf("Add row"))).toBe(false);
607
+ expect(buttonOf("Add row")!.props.disabled).toBe(true);
608
+ // 11 built-in, 1 custom, the source toggle.
609
+ expect(buttons()).toHaveLength(13);
610
+ });
611
+ });
612
+
613
+ /** A button by its accessible name, or by its text when it has none. */
614
+ const byLabel = (label: string) =>
615
+ buttons().find(
616
+ (node) => node.props["aria-label"] === label || node.props.label === label,
617
+ );
618
+
619
+ describe("MapoWygEditor links", () => {
620
+ const linkButton = () => byLabel("mapo.wygEditor.link");
621
+ const linkInput = () => all(root).find((node) => node.type === "input");
622
+ const typeLink = (url: string) =>
623
+ (linkInput()!.props.onInput as (value: string) => void)(url);
624
+ const alert = () => all(root).find((node) => node.props.role === "alert");
625
+ /** Fires the input's keydown listeners, as `@keydown.<key>` binds them. */
626
+ function press(key: string) {
627
+ const event = { key, preventDefault: vi.fn() };
628
+ const handlers = [linkInput()!.props.onKeydown].flat() as Array<
629
+ (event: unknown) => void
630
+ >;
631
+ handlers.forEach((handler) => handler(event));
632
+ return event;
633
+ }
634
+ async function openLink(url?: string) {
635
+ click(linkButton());
636
+ await nextTick();
637
+ if (url !== undefined) {
638
+ typeLink(url);
639
+ await nextTick();
640
+ }
641
+ }
642
+
643
+ it("opens a bar with the address of the link at the selection, and closes it", async () => {
644
+ mount();
645
+ fakeEditor().getAttributes.mockReturnValue({ href: "/contatti/" });
646
+
647
+ await openLink();
648
+
649
+ expect(fakeEditor().getAttributes).toHaveBeenCalledWith("link");
650
+ expect(linkInput()!.props.value).toBe("/contatti/");
651
+ expect(linkButton()!.props["aria-expanded"]).toBe(true);
652
+
653
+ click(byLabel("mapo.wygEditor.linkCancel"));
654
+ await nextTick();
655
+ expect(linkInput()).toBeUndefined();
656
+ });
657
+
658
+ it("links the selection, extending the link already there", async () => {
659
+ mount();
660
+ await openLink("https://example.com");
661
+
662
+ click(byLabel("mapo.wygEditor.linkApply"));
663
+ await nextTick();
664
+
665
+ expect(fakeEditor().calls).toEqual([
666
+ ["focus"],
667
+ ["extendMarkRange", "link"],
668
+ ["setLink", { href: "https://example.com" }],
669
+ ["run"],
670
+ ]);
671
+ expect(linkInput()).toBeUndefined();
672
+ });
673
+
674
+ it("inserts the address as linked text when nothing is selected", async () => {
675
+ mount();
676
+ fakeEditor().state.selection.empty = true;
677
+ await openLink("/contatti/");
678
+
679
+ click(byLabel("mapo.wygEditor.linkApply"));
680
+
681
+ expect(fakeEditor().calls).toEqual([
682
+ ["focus"],
683
+ [
684
+ "insertContent",
685
+ {
686
+ type: "text",
687
+ text: "/contatti/",
688
+ marks: [{ type: "link", attrs: { href: "/contatti/" } }],
689
+ },
690
+ ],
691
+ ["run"],
692
+ ]);
693
+ });
694
+
695
+ it("adds https:// to an address that starts with www.", async () => {
696
+ mount();
697
+ await openLink("www.example.com");
698
+
699
+ click(byLabel("mapo.wygEditor.linkApply"));
700
+
701
+ expect(fakeEditor().calls).toContainEqual([
702
+ "setLink",
703
+ { href: "https://www.example.com" },
704
+ ]);
705
+ });
706
+
707
+ it("refuses an address outside the allowlist and keeps the bar open with an error", async () => {
708
+ mount();
709
+ await openLink("javascript:alert(1)");
710
+
711
+ click(byLabel("mapo.wygEditor.linkApply"));
712
+ await nextTick();
713
+
714
+ expect(fakeEditor().calls).toEqual([]);
715
+ expect(alert()!.text).toContain("mapo.wygEditor.linkInvalid");
716
+ expect(linkInput()!.props["aria-invalid"]).toBe(true);
717
+ });
718
+
719
+ it("removes the link with its button, or when the address is emptied", async () => {
720
+ mount();
721
+ fakeEditor().isActive.mockImplementation((name) => name === "link");
722
+ await openLink();
723
+
724
+ click(byLabel("mapo.wygEditor.linkRemove"));
725
+ await nextTick();
726
+ expect(fakeEditor().calls).toEqual([
727
+ ["focus"],
728
+ ["extendMarkRange", "link"],
729
+ ["unsetLink"],
730
+ ["run"],
731
+ ]);
732
+ expect(linkInput()).toBeUndefined();
733
+
734
+ fakeEditor().calls.length = 0;
735
+ await openLink(" ");
736
+ click(byLabel("mapo.wygEditor.linkApply"));
737
+ expect(fakeEditor().calls).toEqual([
738
+ ["focus"],
739
+ ["extendMarkRange", "link"],
740
+ ["unsetLink"],
741
+ ["run"],
742
+ ]);
743
+ });
744
+
745
+ it("applies with Enter and closes with Escape, keeping the keys from the page's form", async () => {
746
+ mount();
747
+ await openLink("/pagina/");
748
+
749
+ const enter = press("Enter");
750
+ expect(enter.preventDefault).toHaveBeenCalled();
751
+ expect(fakeEditor().calls).toContainEqual([
752
+ "setLink",
753
+ { href: "/pagina/" },
754
+ ]);
755
+ await nextTick();
756
+ expect(linkInput()).toBeUndefined();
757
+
758
+ await openLink();
759
+ const escape = press("Escape");
760
+ expect(escape.preventDefault).toHaveBeenCalled();
761
+ await nextTick();
762
+ expect(linkInput()).toBeUndefined();
763
+ });
764
+
765
+ it("closes the bar for the source view and disables the button on a read-only field", async () => {
766
+ mount();
767
+ await openLink();
768
+
769
+ click(sourceToggle());
770
+ await nextTick();
771
+ expect(linkInput()).toBeUndefined();
772
+ expect(linkButton()!.props.disabled).toBe(true);
773
+ app!.unmount();
774
+
775
+ mount({}, { readonly: true });
776
+ expect(linkButton()!.props.disabled).toBe(true);
777
+ });
778
+ });
779
+
780
+ describe("MapoWygEditor alignment", () => {
781
+ const alignButtons = () =>
782
+ ["alignLeft", "alignCenter", "alignRight"].map((key) =>
783
+ byLabel(`mapo.wygEditor.${key}`),
784
+ );
785
+ const loadedTextAlign = () =>
786
+ tiptap.options!.extensions.filter(
787
+ (extension) => extension.name === "textAlign",
788
+ ) as unknown as { options: { types: string[]; alignments: string[] } }[];
789
+
790
+ it("has no buttons and loads no TextAlign by default", () => {
791
+ mount();
792
+
793
+ expect(alignButtons().every((node) => node === undefined)).toBe(true);
794
+ expect(loadedTextAlign()).toHaveLength(0);
795
+ });
796
+
797
+ it("adds left, centre and right with attrs.textAlign, for paragraphs and headings", () => {
798
+ mount({ textAlign: true });
799
+
800
+ expect(alignButtons().map((node) => node?.props.icon)).toEqual([
801
+ "i-lucide-align-left",
802
+ "i-lucide-align-center",
803
+ "i-lucide-align-right",
804
+ ]);
805
+ expect(loadedTextAlign()).toHaveLength(1);
806
+ expect(loadedTextAlign()[0]!.options.types).toEqual([
807
+ "heading",
808
+ "paragraph",
809
+ ]);
810
+ expect(loadedTextAlign()[0]!.options.alignments).toEqual([
811
+ "left",
812
+ "center",
813
+ "right",
814
+ ]);
815
+ });
816
+
817
+ it("follows the module option, and the field's attrs.textAlign wins", () => {
818
+ runtimeConfig.public.mapoForm = {
819
+ editor: { source: true, textAlign: true },
820
+ };
821
+ mount();
822
+ expect(alignButtons().every((node) => node !== undefined)).toBe(true);
823
+ app!.unmount();
824
+
825
+ mount({ textAlign: false });
826
+ expect(alignButtons().every((node) => node === undefined)).toBe(true);
827
+ });
828
+
829
+ it("centres and right-aligns with setTextAlign; left removes the alignment", () => {
830
+ mount({ textAlign: true });
831
+ const [left, center, right] = alignButtons();
832
+
833
+ click(center);
834
+ click(right);
835
+ click(left);
836
+
837
+ expect(fakeEditor().calls).toEqual([
838
+ ["focus"],
839
+ ["setTextAlign", "center"],
840
+ ["run"],
841
+ ["focus"],
842
+ ["setTextAlign", "right"],
843
+ ["run"],
844
+ ["focus"],
845
+ ["unsetTextAlign"],
846
+ ["run"],
847
+ ]);
848
+ });
849
+
850
+ it("marks the selection's alignment as pressed, left when none is set", async () => {
851
+ mount({ textAlign: true });
852
+ expect(alignButtons().map((node) => node!.props["aria-pressed"])).toEqual([
853
+ true,
854
+ false,
855
+ false,
856
+ ]);
857
+
858
+ fakeEditor().isActive.mockImplementation(
859
+ (attributes) =>
860
+ typeof attributes === "object" &&
861
+ (attributes as { textAlign?: string }).textAlign === "center",
862
+ );
863
+ // Opening the link bar re-renders the toolbar with the new selection.
864
+ click(byLabel("mapo.wygEditor.link"));
865
+ await nextTick();
866
+
867
+ expect(alignButtons().map((node) => node!.props["aria-pressed"])).toEqual([
868
+ false,
869
+ true,
870
+ false,
871
+ ]);
872
+ });
873
+
874
+ it("keeps a TextAlign the field loads itself, instead of adding its own", () => {
875
+ const own = TextAlign.configure({ types: ["paragraph"] });
876
+ mount({ textAlign: true, extensions: [own] });
877
+
878
+ expect(loadedTextAlign()).toEqual([own]);
879
+ });
880
+
881
+ it("disables the buttons on a read-only field", () => {
882
+ mount({ textAlign: true }, { readonly: true });
883
+
884
+ expect(alignButtons().every((node) => node!.props.disabled)).toBe(true);
885
+ });
886
+ });