@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
@@ -12,6 +12,7 @@ const { $mapoFormRegistry } = useNuxtApp() as unknown as {
12
12
  const config = useRuntimeConfig().public.mapoForm as {
13
13
  groups?: { expanded?: boolean };
14
14
  debounce?: number;
15
+ editor?: { source?: boolean; textAlign?: boolean };
15
16
  };
16
17
 
17
18
  /** Sorted list of all registered field types currently available in the runtime registry. */
@@ -48,6 +49,10 @@ const userMappings = computed(() =>
48
49
 
49
50
  const globalDebounce = computed(() => config?.debounce || 300);
50
51
  const globalExpanded = computed(() => config?.groups?.expanded !== false);
52
+ const globalEditorSource = computed(() => config?.editor?.source !== false);
53
+ const globalEditorTextAlign = computed(
54
+ () => config?.editor?.textAlign === true,
55
+ );
51
56
 
52
57
  function componentLabel(type: string): string {
53
58
  const v = $mapoFormRegistry?.mapping?.[type];
@@ -111,6 +116,24 @@ function isUserType(type: string): boolean {
111
116
  {{ globalExpanded }}
112
117
  </span>
113
118
  </div>
119
+ <div>
120
+ <span class="text-gray-500">editor.source</span>
121
+ <span
122
+ class="ml-2"
123
+ :class="globalEditorSource ? 'text-green-400' : 'text-red-400'"
124
+ >
125
+ {{ globalEditorSource }}
126
+ </span>
127
+ </div>
128
+ <div>
129
+ <span class="text-gray-500">editor.textAlign</span>
130
+ <span
131
+ class="ml-2"
132
+ :class="globalEditorTextAlign ? 'text-green-400' : 'text-red-400'"
133
+ >
134
+ {{ globalEditorTextAlign }}
135
+ </span>
136
+ </div>
114
137
  <div>
115
138
  <span class="text-gray-500">custom types</span>
116
139
  <span class="ml-2 text-blue-400">{{ userMappings.length }}</span>
@@ -284,12 +284,83 @@ export interface FileDescriptor<
284
284
  attrs?: { accept?: string; maxSize?: number };
285
285
  }
286
286
 
287
+ /**
288
+ * The Tiptap editor a toolbar button acts on, described by the members a button
289
+ * needs so that the descriptor types do not depend on Tiptap. At runtime it is
290
+ * the field's Tiptap `Editor`: cast it for the rest of its API. The command
291
+ * builders are untyped because the commands available depend on the extensions
292
+ * the field loads (`attrs.extensions`).
293
+ */
294
+ export interface EditorToolbarEditor {
295
+ /** Starts a command chain, as in `editor.chain().focus().toggleBold().run()`. */
296
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
297
+ chain(): any;
298
+ /** Dry-runs commands: `editor.can().addRowAfter()` is `true` when the command would apply. */
299
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
300
+ can(): any;
301
+ /** Runs one command, as in `editor.commands.setHorizontalRule()`. */
302
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
303
+ readonly commands: any;
304
+ /** Whether a mark or a node is active at the selection, as in `editor.isActive('table')`. */
305
+ isActive(name: string, attributes?: Record<string, unknown>): boolean;
306
+ }
307
+
308
+ /**
309
+ * A button that `attrs.toolbar` adds to an editor field, after the built-in
310
+ * buttons. Methods, not function properties: a function typed with Tiptap's own
311
+ * `Editor` fits them too.
312
+ */
313
+ export interface EditorToolbarItem {
314
+ /** Identifies the button among the custom ones; unique within the toolbar. */
315
+ key: string;
316
+ /** Tooltip and accessible name of the button; its text when it has no `icon`. */
317
+ label: string;
318
+ /** Icon name, as `UButton` takes it (e.g. `i-lucide-table`). */
319
+ icon?: string;
320
+ /** Runs on click, as in `(editor) => editor.chain().focus().insertTable().run()`. */
321
+ action(editor: EditorToolbarEditor): void;
322
+ /** Shows the button as active, like the built-in ones on bold text or a heading. */
323
+ isActive?(editor: EditorToolbarEditor): boolean;
324
+ /**
325
+ * Disables the button, as in `(editor) => !editor.can().addRowAfter()`. The
326
+ * button is also disabled when the field is read-only and in the source view.
327
+ */
328
+ isDisabled?(editor: EditorToolbarEditor): boolean;
329
+ }
330
+
287
331
  /** Descriptor for a Tiptap rich-text editor. */
288
332
  export interface EditorDescriptor<
289
333
  T = Record<string, unknown>,
290
334
  > extends FieldBase<T> {
291
335
  type: `${KnownFieldType.Editor}`;
292
- attrs?: { extensions?: unknown[] };
336
+ attrs?: {
337
+ /** Tiptap v2 extensions loaded after the built-in ones (StarterKit, Link, Underline, Image). */
338
+ extensions?: unknown[];
339
+ /**
340
+ * Adds an HTML source toggle at the end of the toolbar. The source view
341
+ * edits the HTML in a textarea; what it saves goes through the editor, so it
342
+ * is sanitized, and the tags and attributes no extension supports are
343
+ * dropped. A read-only field shows the source without letting it change.
344
+ * Default: the module option `editor.source` (`mapoForm.editor.source` in
345
+ * `nuxt.config`), which is `true`; `false` hides the toggle on this field.
346
+ */
347
+ source?: boolean;
348
+ /**
349
+ * Adds left, centre and right alignment buttons for paragraphs and
350
+ * headings, and loads Tiptap's TextAlign extension, which writes
351
+ * `style="text-align: center"` (left writes no style). A field without it
352
+ * drops the alignment of pasted text. Default: the module option
353
+ * `editor.textAlign` (`mapoForm.editor.textAlign`), which is `false`.
354
+ */
355
+ textAlign?: boolean;
356
+ /**
357
+ * Buttons added after the built-in ones, past a separator: typically the
358
+ * commands of the `extensions` the field loads. Each item is
359
+ * `{ key, label, icon?, action(editor), isActive?(editor), isDisabled?(editor) }`.
360
+ * Disabled when the field is read-only and in the source view.
361
+ */
362
+ toolbar?: EditorToolbarItem[];
363
+ };
293
364
  }
294
365
 
295
366
  /** Descriptor for the SEO preview field (title + description + live SERP preview). */
@@ -18,6 +18,8 @@ export type {
18
18
  ColorDescriptor,
19
19
  FileDescriptor,
20
20
  EditorDescriptor,
21
+ EditorToolbarItem,
22
+ EditorToolbarEditor,
21
23
  SeoDescriptor,
22
24
  MapDescriptor,
23
25
  RepeaterDescriptor,
@@ -89,10 +89,12 @@ export function resolveFieldAccessor(
89
89
 
90
90
  /**
91
91
  * Shape of `runtimeConfig.public.mapoForm` as written by the module setup.
92
- * `groups` and `debounce` are guaranteed by the module `defaults`.
92
+ * `groups`, `debounce` and `editor` are guaranteed by the module `defaults`.
93
93
  */
94
94
  export interface MapoFormRuntimeConfig {
95
95
  groups: { expanded: boolean };
96
96
  debounce: number;
97
+ /** Defaults for every `editor` field (module option `editor`). */
98
+ editor: { source: boolean; textAlign: boolean };
97
99
  fields: { attrs: Record<string, Record<string, unknown>> };
98
100
  }
@@ -0,0 +1,198 @@
1
+ /**
2
+ * Block-level tags: each one starts a line of its own, and a block that holds
3
+ * other blocks closes on a line of its own, one indent step out.
4
+ */
5
+ const BLOCK_TAGS = new Set([
6
+ "p",
7
+ "h1",
8
+ "h2",
9
+ "h3",
10
+ "h4",
11
+ "h5",
12
+ "h6",
13
+ "ul",
14
+ "ol",
15
+ "li",
16
+ "table",
17
+ "colgroup",
18
+ "col",
19
+ "thead",
20
+ "tbody",
21
+ "tfoot",
22
+ "tr",
23
+ "th",
24
+ "td",
25
+ "blockquote",
26
+ "pre",
27
+ "hr",
28
+ "img",
29
+ "div",
30
+ "figure",
31
+ "figcaption",
32
+ ]);
33
+
34
+ /** Blocks that hold a line of text: an `<img>` inside one is part of the text. */
35
+ const TEXTBLOCK_TAGS = new Set([
36
+ "p",
37
+ "h1",
38
+ "h2",
39
+ "h3",
40
+ "h4",
41
+ "h5",
42
+ "h6",
43
+ "figcaption",
44
+ ]);
45
+
46
+ /** Tags with no closing tag: they never open a level. */
47
+ const VOID_TAGS = new Set([
48
+ "area",
49
+ "base",
50
+ "br",
51
+ "col",
52
+ "embed",
53
+ "hr",
54
+ "img",
55
+ "input",
56
+ "link",
57
+ "meta",
58
+ "source",
59
+ "track",
60
+ "wbr",
61
+ ]);
62
+
63
+ /** Tags whose content is copied as it is: whitespace is part of the content there. */
64
+ const VERBATIM_TAGS = new Set(["pre", "code"]);
65
+
66
+ /**
67
+ * A comment, a tag (quoted attribute values may hold `>`), a run of text, or a
68
+ * `<` that starts none of them.
69
+ */
70
+ const TOKEN =
71
+ /<!--[\s\S]*?-->|<\/?[a-zA-Z][^\s/>]*(?:"[^"]*"|'[^']*'|[^'">])*>|[^<]+|</g;
72
+ const TAG_NAME = /^<\/?([a-zA-Z][a-zA-Z0-9-]*)/;
73
+ /** HTML whitespace only: a no-break space is content. */
74
+ const BLANK = /^[ \t\n\f\r]*$/;
75
+ const LEADING_BLANK = /^[ \t\n\f\r]+/;
76
+ const TRAILING_BLANK = /[ \t\n\f\r]+$/;
77
+
78
+ interface OpenBlock {
79
+ name: string;
80
+ /** Whether a block opened inside it, so its closing tag needs a line of its own. */
81
+ holdsBlocks: boolean;
82
+ }
83
+
84
+ /** What came last: a block's opening tag, the end of a block, or inline content. */
85
+ type LastToken = "block-open" | "block-end" | "inline";
86
+
87
+ /**
88
+ * Lays out an HTML fragment for reading: a line per block-level tag (paragraphs,
89
+ * headings, lists, tables, quotes, `pre`, `hr`, `img`), indented by nesting, with
90
+ * inline content kept on its block's line.
91
+ *
92
+ * The result parses back to the same document: only whitespace between blocks
93
+ * and at the edges of a block is added or dropped, which an HTML parser that
94
+ * collapses whitespace (Tiptap's) ignores. The content of `<pre>` and `<code>`
95
+ * is copied as it is, and an `<img>` inside a line of text stays on that line.
96
+ *
97
+ * @param html The fragment to lay out, typically Tiptap's `editor.getHTML()`.
98
+ * @param indent The string one nesting level adds. Default: two spaces.
99
+ * @returns The fragment over several lines, with no trailing newline.
100
+ */
101
+ export function formatHtml(html: string, indent = " "): string {
102
+ const lines: string[] = [];
103
+ const open: OpenBlock[] = [];
104
+ let line = "";
105
+ let last: LastToken = "block-open";
106
+ let verbatim: { name: string; depth: number } | null = null;
107
+
108
+ const startLine = () => {
109
+ const isBlankLine = BLANK.test(line);
110
+ if (!isBlankLine) lines.push(line.replace(TRAILING_BLANK, ""));
111
+ line = indent.repeat(open.length);
112
+ };
113
+
114
+ /**
115
+ * Closes the innermost open block named `name`; a block that held other
116
+ * blocks closes on a line of its own. A closing tag with no opening one
117
+ * stays where it is.
118
+ */
119
+ const closeBlock = (name: string, token: string) => {
120
+ let at = open.length - 1;
121
+ while (at >= 0 && open[at]!.name !== name) at -= 1;
122
+ const isStray = at < 0;
123
+ if (isStray) {
124
+ line += token;
125
+ last = "block-end";
126
+ return;
127
+ }
128
+ const holdsBlocks = open[at]!.holdsBlocks;
129
+ open.length = at;
130
+ if (holdsBlocks) startLine();
131
+ line += token;
132
+ last = "block-end";
133
+ };
134
+
135
+ for (const [token] of html.matchAll(TOKEN)) {
136
+ const name = TAG_NAME.exec(token)?.[1]?.toLowerCase();
137
+ const isClosing = token.startsWith("</");
138
+
139
+ if (verbatim) {
140
+ const isVerbatimTag = name === verbatim.name;
141
+ if (isVerbatimTag && isClosing) verbatim.depth -= 1;
142
+ else if (isVerbatimTag) verbatim.depth += 1;
143
+ const verbatimEnds = verbatim.depth === 0;
144
+ if (!verbatimEnds) {
145
+ line += token;
146
+ continue;
147
+ }
148
+ verbatim = null;
149
+ // `</pre>` closes a block, `</code>` an inline element.
150
+ if (name === "pre") closeBlock(name, token);
151
+ else line += token;
152
+ continue;
153
+ }
154
+
155
+ const isBlock = name !== undefined && BLOCK_TAGS.has(name);
156
+ const parent = open.at(-1);
157
+ const isInsideText =
158
+ last === "inline" ||
159
+ (parent !== undefined && TEXTBLOCK_TAGS.has(parent.name));
160
+ const isInlineImage = name === "img" && isInsideText;
161
+
162
+ if (!isBlock || isInlineImage) {
163
+ const isText = name === undefined;
164
+ const isBlankBetweenBlocks =
165
+ isText && last !== "inline" && BLANK.test(token);
166
+ if (isBlankBetweenBlocks) continue;
167
+ if (last === "block-end") startLine();
168
+ // Whitespace at the start of a block's text is not content.
169
+ const startsText = isText && last !== "inline";
170
+ line += startsText ? token.replace(LEADING_BLANK, "") : token;
171
+ last = "inline";
172
+ const opensVerbatim =
173
+ name !== undefined && VERBATIM_TAGS.has(name) && !isClosing;
174
+ if (opensVerbatim) verbatim = { name, depth: 1 };
175
+ continue;
176
+ }
177
+
178
+ if (isClosing) {
179
+ closeBlock(name, token);
180
+ continue;
181
+ }
182
+
183
+ if (parent) parent.holdsBlocks = true;
184
+ startLine();
185
+ line += token;
186
+ const isVoid = VOID_TAGS.has(name) || token.endsWith("/>");
187
+ if (isVoid) {
188
+ last = "block-end";
189
+ continue;
190
+ }
191
+ open.push({ name, holdsBlocks: false });
192
+ last = "block-open";
193
+ if (name === "pre") verbatim = { name, depth: 1 };
194
+ }
195
+
196
+ startLine();
197
+ return lines.join("\n");
198
+ }
@@ -0,0 +1,60 @@
1
+ // Protocol allowlist for user-entered links. Without this,
2
+ // `<a href="javascript:...">` would be accepted, leading to XSS when content is
3
+ // rendered elsewhere (preview, server-side, other editors).
4
+ export const ALLOWED_LINK_PROTOCOLS = ["http", "https", "mailto", "tel"];
5
+
6
+ /**
7
+ * Whether a link or image URL is safe to keep: relative, or with a protocol in
8
+ * {@link ALLOWED_LINK_PROTOCOLS}.
9
+ */
10
+ export function isSafeUrl(url: string): boolean {
11
+ try {
12
+ // URL relativi (es. "/page") non hanno protocol — li accettiamo.
13
+ if (!/^[a-z][a-z0-9+.-]*:/i.test(url)) return true;
14
+ const proto = new URL(url, "https://placeholder.local").protocol
15
+ .replace(":", "")
16
+ .toLowerCase();
17
+ return ALLOWED_LINK_PROTOCOLS.includes(proto);
18
+ } catch {
19
+ return false;
20
+ }
21
+ }
22
+
23
+ /**
24
+ * Sanitise incoming HTML from external sources (initial set, server sync, the
25
+ * source view) by removing <script>, inline handlers (on*), and href:
26
+ * javascript:. This is intentionally minimal (no DOMPurify) to avoid a heavy
27
+ * dependency: it covers the most common vectors; for truly untrusted HTML the
28
+ * consumer should use DOMPurify at the app level. Without a DOM (SSR) the HTML
29
+ * is returned as it is.
30
+ */
31
+ export function sanitizeHtml(html: string): string {
32
+ if (typeof window === "undefined" || !html) return html;
33
+ const tpl = document.createElement("template");
34
+ tpl.innerHTML = html;
35
+ const walker = document.createTreeWalker(
36
+ tpl.content,
37
+ NodeFilter.SHOW_ELEMENT,
38
+ );
39
+ const toRemove: Element[] = [];
40
+ let node = walker.nextNode() as Element | null;
41
+ while (node) {
42
+ if (node.tagName === "SCRIPT" || node.tagName === "STYLE") {
43
+ toRemove.push(node);
44
+ } else {
45
+ for (const attr of Array.from(node.attributes)) {
46
+ const name = attr.name.toLowerCase();
47
+ if (name.startsWith("on")) node.removeAttribute(attr.name);
48
+ if (
49
+ (name === "href" || name === "src" || name === "xlink:href") &&
50
+ !isSafeUrl(attr.value)
51
+ ) {
52
+ node.removeAttribute(attr.name);
53
+ }
54
+ }
55
+ }
56
+ node = walker.nextNode() as Element | null;
57
+ }
58
+ toRemove.forEach((el) => el.remove());
59
+ return tpl.innerHTML;
60
+ }