svelte-rtf-editor 1.10.0 → 1.11.0

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.
package/README.md CHANGED
@@ -137,6 +137,8 @@ Pass an HTML string as `content`. If the content is already RTF, convert it firs
137
137
  | `fontFamily` | `string` | `'Segoe UI'` | Document font, on screen and in the RTF. See [Fonts](#fonts) |
138
138
  | `fontSize` | `number` | `12` | Body text size in points, on screen and in the RTF |
139
139
  | `fontSizes` | `number[]` | `[8, 9, 10, 11, 12, 14, 16, 18, 20, 24, 28, 36]` | The sizes, in points, the toolbar's size list offers for selected text. The body size is always among them; `[]` takes the list off the toolbar. See [Size of selected text](#size-of-selected-text) |
140
+ | `keepAttributes` | `string[]` | `[]` | `data-` attributes of your own that stay on HTML you set or the user pastes. See [HTML from outside](#html-from-outside) |
141
+ | `keepClasses` | `string[]` | `[]` | Class names of your own that stay the same way |
140
142
 
141
143
  #### Callback props
142
144
 
@@ -185,6 +187,14 @@ Whatever HTML reaches the editor is made safe before it is shown: the `content`
185
187
  | Style text the browser did not read as a property (`width: expression(…)`, a property named twice) | It does nothing here, but it would still be in the HTML for whatever shows it next. Where there is any, the attribute is written again from the properties that were read and kept. An attribute that is all read and kept stays exactly as it was written, `border: 1px solid black` included |
186
188
  | `class`; an `id` that names something on `document` or `window`; the `id` of a link; in the editor, an `id` the page already uses for an element outside an editor | They would take on the page's own styles, or answer to a name or an `id` the page's scripts look up. A document's own ids are kept, also when it is shown again while its first showing is still in the editor. They are still names on `window`, as every `id` in a page is: a page whose scripts read settings from `window` by a name they do not define should not show documents from strangers |
187
189
 
190
+ **Marks of your own.** An application that marks elements in its documents and reads the marks back (`<p data-section="2">`), or styles one by a class (`<pre class="summary">`), names them in `keepAttributes` and `keepClasses`, and they stay on HTML it sets and on what the user pastes:
191
+
192
+ ```svelte
193
+ <InkEditor content={html} keepAttributes={['data-section', 'data-row']} keepClasses={['summary']} />
194
+ ```
195
+
196
+ Only attribute names that start with `data-` are kept, and after it only letters, digits, `-`, `_` and `.`; anything else in the list (`onclick`, `style`, `src`) is ignored, so the list cannot let in what the table above takes out. Any class name can be named, `md:flex` and `w-1/2` included. A kept class is kept by name alone: how it looks is your stylesheet's doing, and a paste that happens to use the same name gets it too. A kept attribute comes in with a paste the same way, with whatever value the pasted page gave it, so read a mark back as you would read anything a user typed; and a marked paragraph copied and pasted is two paragraphs with the same mark. Neither changes the RTF. `sanitizeHtml(html, { keepAttributes, keepClasses })` does the same for HTML you show yourself. Without the settings both are taken off, as since 1.10.0: an application that upgraded from an earlier version and relies on one has to name it.
197
+
188
198
  The editing area also clips what it holds: nothing in a document is drawn outside it, whatever its styles, and a table wider than the area scrolls inside it. The frame around a selected picture stays inside it too. Text that Word marked hidden (`mso-hide: all`) is hidden on screen as it is left out of the RTF, and in a paste it is not pasted. A closed `<details>` is shown open, since what is in it is written to the RTF either way.
189
199
 
190
200
  `getHTML()` returns what is in the editor, which has been through this. HTML from `rtfToHtml` is safe by construction (see [What `rtfToHtml` may return](#what-rtftohtml-may-return)).
@@ -208,7 +218,7 @@ import {
208
218
  | `isSafeLinkUrl(url: string): boolean` | Whether a link address is a web, mail or phone address; `htmlToRtf` and `htmlToMarkdown` write any other link as its text alone, and `rtfToHtml` reads any other as text |
209
219
  | `readRtfFile(file: File, options?: { fontSize?, maxBytes? }): Promise<string>` | Read a `.rtf` File object and return HTML. Rejects, without reading it, for a file larger than `maxBytes` |
210
220
  | `htmlToMarkdown(el: HTMLElement): string` | Convert a DOM element's content to Markdown. See [Markdown export](#markdown-export) |
211
- | `sanitizeHtml(html: string): string` | HTML made safe to show and edit. See [HTML from outside](#html-from-outside). Needs a DOM (`DOMParser`); without one it returns `''` |
221
+ | `sanitizeHtml(html: string, options?: { keepAttributes?: string[]; keepClasses?: string[] }): string` | HTML made safe to show and edit. See [HTML from outside](#html-from-outside). Needs a DOM (`DOMParser`); without one it returns `''` |
212
222
  | `downloadFile(name, content, mime): void` | Trigger a file download in the browser |
213
223
 
214
224
  ---
@@ -37,6 +37,15 @@
37
37
  * selected text. The body size is always among them. An empty
38
38
  * list takes the size list off the toolbar.
39
39
  * Default: 8, 9, 10, 11, 12, 14, 16, 18, 20, 24, 28, 36.
40
+ * keepAttributes — `data-` attributes the application's documents carry, which
41
+ * the editor leaves on their elements: a mark on a paragraph that
42
+ * the application reads back (`data-section="2"`). Every other
43
+ * attribute the editor does not know is taken off HTML as it comes
44
+ * in, set or pasted. Names that do not start with `data-` are not
45
+ * kept. Default: none.
46
+ * keepClasses — Class names of the application's own that stay in an element's
47
+ * class list the same way (`<pre class="summary">`). Every other
48
+ * class is taken off. Default: none.
40
49
  *
41
50
  * Events (callback props):
42
51
  * onchange — Fires on content change with
@@ -62,7 +71,7 @@
62
71
  import Modal from './Modal.svelte';
63
72
  import ImageOverlay from './ImageOverlay.svelte';
64
73
  import { htmlToMarkdown, downloadFile } from '../utils.js';
65
- import { pasteNotes, removeWordHidden, sanitizedNodes, sanitizeTree, type PasteNotes } from '../sanitize.js';
74
+ import { keptMarks, pasteNotes, removeWordHidden, sanitizedNodes, sanitizeTree, type PasteNotes } from '../sanitize.js';
66
75
  import { readRtfFile, DEFAULT_MAX_RTF_BYTES } from '../rtf-parser.js';
67
76
  import {
68
77
  htmlToRtf,
@@ -120,6 +129,10 @@
120
129
  fontFamily?: string;
121
130
  fontSize?: number;
122
131
  fontSizes?: number[];
132
+ /** `data-` attributes of the application's own, kept on HTML that is set or pasted. */
133
+ keepAttributes?: string[];
134
+ /** Class names of the application's own, kept the same way. */
135
+ keepClasses?: string[];
123
136
  onchange?: (payload: ChangePayload) => void;
124
137
  onsave?: (payload: { html: string }) => void;
125
138
  onimport?: (payload: { html: string }) => void;
@@ -134,6 +147,7 @@
134
147
 
135
148
  /** The sizes, in points, the toolbar's size list offers unless `fontSizes` says otherwise. */
136
149
  const DEFAULT_FONT_SIZES = [8, 9, 10, 11, 12, 14, 16, 18, 20, 24, 28, 36];
150
+ const NO_KEPT_ATTRIBUTES: string[] = [];
137
151
 
138
152
  // ── Props ──
139
153
  let {
@@ -153,11 +167,15 @@
153
167
  fontFamily = DEFAULT_FONT_FAMILY,
154
168
  fontSize = DEFAULT_FONT_SIZE,
155
169
  fontSizes = DEFAULT_FONT_SIZES,
170
+ keepAttributes = NO_KEPT_ATTRIBUTES,
171
+ keepClasses = NO_KEPT_ATTRIBUTES,
156
172
  onchange,
157
173
  onsave,
158
174
  onimport
159
175
  }: Props = $props();
160
176
 
177
+ const keptNames = $derived(keptMarks({ keepAttributes, keepClasses }));
178
+
161
179
  // The same font and size go to the screen and to the RTF, so the editor
162
180
  // shows what the receiving system will show.
163
181
  const rtfOptions = $derived({ fontFamily, fontSize });
@@ -236,7 +254,7 @@
236
254
  const owner = document.getElementById(id);
237
255
  return owner !== null && owner.closest('.ink-content') === null;
238
256
  };
239
- editorEl.replaceChildren(...sanitizedNodes(html, document, idTaken));
257
+ editorEl.replaceChildren(...sanitizedNodes(html, document, idTaken, keptNames));
240
258
  for (const p of Array.from(editorEl.querySelectorAll('p'))) {
241
259
  if (p.childNodes.length === 0) p.appendChild(document.createElement('br'));
242
260
  }
@@ -1914,7 +1932,7 @@
1914
1932
  // What the paste brought is made safe as HTML from anywhere else is: a browser takes the
1915
1933
  // scripts out of a paste itself, but leaves a form, an <iframe>, or a block with
1916
1934
  // position: fixed that covers the page.
1917
- sanitizeTree(editorEl, (el) => !before.has(el));
1935
+ sanitizeTree(editorEl, (el) => !before.has(el), undefined, keptNames);
1918
1936
  for (const el of Array.from(editorEl.querySelectorAll<HTMLElement>('*'))) {
1919
1937
  if (before.has(el)) continue;
1920
1938
  el.removeAttribute('id');
@@ -33,6 +33,10 @@ interface Props {
33
33
  fontFamily?: string;
34
34
  fontSize?: number;
35
35
  fontSizes?: number[];
36
+ /** `data-` attributes of the application's own, kept on HTML that is set or pasted. */
37
+ keepAttributes?: string[];
38
+ /** Class names of the application's own, kept the same way. */
39
+ keepClasses?: string[];
36
40
  onchange?: (payload: ChangePayload) => void;
37
41
  onsave?: (payload: {
38
42
  html: string;
package/dist/index.d.ts CHANGED
@@ -6,3 +6,4 @@ export type { RtfWriteOptions } from './rtf-writer.js';
6
6
  export type { RtfReadOptions } from './rtf-parser.js';
7
7
  export { htmlToMarkdown, downloadFile } from './utils.js';
8
8
  export { sanitizeHtml } from './sanitize.js';
9
+ export type { KeepOptions } from './sanitize.js';
@@ -24,27 +24,49 @@
24
24
  * sight (a margin below zero, a padding of thousands of pixels, a first line that starts left
25
25
  * of its paragraph, text of no size).
26
26
  */
27
+ /** What an application asked to have kept on its own documents. */
28
+ export interface KeepOptions {
29
+ /** `data-` attributes that stay on any element. */
30
+ keepAttributes?: readonly string[];
31
+ /** Class names that stay in an element's class list. */
32
+ keepClasses?: readonly string[];
33
+ }
34
+ /** The same, as the sets the sanitizer reads. */
35
+ export interface Kept {
36
+ attributes: ReadonlySet<string>;
37
+ classes: ReadonlySet<string>;
38
+ }
39
+ /**
40
+ * What an application asked to have kept (the editor's `keepAttributes` and `keepClasses`), as
41
+ * the sets the sanitizer reads. Only `data-` attributes can be asked for: they mark an element
42
+ * and do nothing else, where `onclick`, `src` or `style` asked for here would undo what this
43
+ * file is for. A class is kept by its name alone; what it looks like is the page's stylesheet,
44
+ * which is why none is kept unless the application names it. A name that is neither is left out.
45
+ */
46
+ export declare function keptMarks(options: KeepOptions | undefined): Kept;
27
47
  /**
28
48
  * Make the elements under `root` safe, in place. With `only`, just the elements it accepts (the
29
49
  * ones a paste brought in) are looked at; the rest of the document is left as it is. With
30
- * `idTaken`, an id it says the page already uses is taken off.
50
+ * `idTaken`, an id it says the page already uses is taken off. With `keep` (see keptMarks),
51
+ * the application's own `data-` attributes and classes stay.
31
52
  * Returns whether anything was taken out or changed.
32
53
  */
33
- export declare function sanitizeTree(root: Element, only?: (el: Element) => boolean, idTaken?: (id: string) => boolean): boolean;
54
+ export declare function sanitizeTree(root: Element, only?: (el: Element) => boolean, idTaken?: (id: string) => boolean, keep?: Kept): boolean;
34
55
  /**
35
56
  * HTML made safe to show and edit: see the top of this file for what is kept. It is parsed in a
36
57
  * document of its own, where nothing in it runs or loads, before any of it reaches the page.
37
58
  * Where there is no DOM to parse it with (on a server), nothing is returned: HTML that could
38
- * not be checked is not passed on.
59
+ * not be checked is not passed on. `keepAttributes` and `keepClasses` name marks of the
60
+ * application's own to leave on (see keptMarks).
39
61
  */
40
- export declare function sanitizeHtml(html: string): string;
62
+ export declare function sanitizeHtml(html: string, options?: KeepOptions): string;
41
63
  /**
42
64
  * The same, as nodes for `into` to hold. The editor puts these in the page as they are: what was
43
65
  * checked is what is shown. Written out as text and read in again, a second reading has to
44
66
  * agree with the first for the check to mean anything, and that is where a sanitizer is got
45
67
  * round; it is also a third pass over a document that may hold megabytes of pictures.
46
68
  */
47
- export declare function sanitizedNodes(html: string, into: Document, idTaken?: (id: string) => boolean): Node[];
69
+ export declare function sanitizedNodes(html: string, into: Document, idTaken?: (id: string) => boolean, keep?: Kept): Node[];
48
70
  /** A run of a paste's text. */
49
71
  interface PastePiece {
50
72
  text: string;
package/dist/sanitize.js CHANGED
@@ -135,6 +135,37 @@ function shownText(el, tag) {
135
135
  }
136
136
  /** Attributes any element may keep. */
137
137
  const GLOBAL_ATTRIBUTES = new Set(['style', 'dir', 'lang', 'title', 'hidden', 'align', 'data-rtf-tab-stops']);
138
+ /**
139
+ * What an application asked to have kept (the editor's `keepAttributes` and `keepClasses`), as
140
+ * the sets the sanitizer reads. Only `data-` attributes can be asked for: they mark an element
141
+ * and do nothing else, where `onclick`, `src` or `style` asked for here would undo what this
142
+ * file is for. A class is kept by its name alone; what it looks like is the page's stylesheet,
143
+ * which is why none is kept unless the application names it. A name that is neither is left out.
144
+ */
145
+ export function keptMarks(options) {
146
+ const attributes = new Set();
147
+ for (const name of namesIn(options?.keepAttributes)) {
148
+ const lower = name.toLowerCase();
149
+ if (/^data-[a-z0-9_.-]+$/.test(lower))
150
+ attributes.add(lower);
151
+ }
152
+ // Every class name given is taken as it is. A rule for what a name may look like refused
153
+ // `md:flex`, `w-1/2` and `résumé` without saying so, and kept nothing out: a name is only
154
+ // ever compared with the classes an element has, and one with a space in it is none of them.
155
+ const classes = new Set(namesIn(options?.keepClasses));
156
+ return { attributes, classes };
157
+ }
158
+ /**
159
+ * The names in one of the two settings. A caller without types can pass one name where a list
160
+ * is meant (`keepClasses="summary"`): read as a list it is its letters, which kept classes named
161
+ * "s" and "u" and not "summary". It is taken as a list of that one name. What is not a list is
162
+ * no names, and what is not text is not a name, so a `null` in a list keeps no class "null".
163
+ */
164
+ function namesIn(given) {
165
+ // Array.from gives no items for what is neither a list nor like one (a number, an object).
166
+ const list = typeof given === 'string' ? [given] : given == null ? [] : Array.from(given);
167
+ return list.filter((name) => typeof name === 'string').map((name) => name.trim());
168
+ }
138
169
  /** Attributes only some elements may keep. */
139
170
  const TAG_ATTRIBUTES = {
140
171
  a: ['href', 'target', 'rel'],
@@ -468,13 +499,14 @@ function namesAGlobal(id) {
468
499
  }
469
500
  return true;
470
501
  }
471
- function sanitizeAttributes(el, tag, fonts, idTaken) {
502
+ function sanitizeAttributes(el, tag, fonts, idTaken, keep) {
472
503
  const own = TAG_ATTRIBUTES[tag];
473
504
  for (const attr of Array.from(el.attributes)) {
474
505
  const name = attr.name.toLowerCase();
475
506
  if (name === 'class') {
476
- if (el.classList.contains(KEPT_CLASS))
477
- el.setAttribute('class', KEPT_CLASS);
507
+ const stay = Array.from(el.classList).filter((token) => token === KEPT_CLASS || keep?.classes.has(token));
508
+ if (stay.length > 0)
509
+ el.setAttribute('class', stay.join(' '));
478
510
  else
479
511
  el.removeAttribute(attr.name);
480
512
  continue;
@@ -491,7 +523,7 @@ function sanitizeAttributes(el, tag, fonts, idTaken) {
491
523
  }
492
524
  continue;
493
525
  }
494
- if (!GLOBAL_ATTRIBUTES.has(name) && !own?.includes(name))
526
+ if (!GLOBAL_ATTRIBUTES.has(name) && !own?.includes(name) && !keep?.attributes.has(name))
495
527
  el.removeAttribute(attr.name);
496
528
  // width="100000" is a table a hundred thousand pixels wide.
497
529
  else if ((name === 'width' || name === 'height') && !sizeAttributeAllowed(attr.value))
@@ -527,10 +559,11 @@ function isReadAloudCopy(el) {
527
559
  /**
528
560
  * Make the elements under `root` safe, in place. With `only`, just the elements it accepts (the
529
561
  * ones a paste brought in) are looked at; the rest of the document is left as it is. With
530
- * `idTaken`, an id it says the page already uses is taken off.
562
+ * `idTaken`, an id it says the page already uses is taken off. With `keep` (see keptMarks),
563
+ * the application's own `data-` attributes and classes stay.
531
564
  * Returns whether anything was taken out or changed.
532
565
  */
533
- export function sanitizeTree(root, only, idTaken) {
566
+ export function sanitizeTree(root, only, idTaken, keep) {
534
567
  let changed = false;
535
568
  const fonts = new Map();
536
569
  /** The words of the last element that left its words, where they are still in the document. */
@@ -572,7 +605,7 @@ export function sanitizeTree(root, only, idTaken) {
572
605
  continue;
573
606
  }
574
607
  const before = el.attributes.length + (el.getAttribute('style') ?? '') + (el.getAttribute('href') ?? '') + (el.getAttribute('width') ?? '') + (el.getAttribute('height') ?? '');
575
- sanitizeAttributes(el, tag, fonts, idTaken);
608
+ sanitizeAttributes(el, tag, fonts, idTaken, keep);
576
609
  if (before !== el.attributes.length + (el.getAttribute('style') ?? '') + (el.getAttribute('href') ?? '') + (el.getAttribute('width') ?? '') + (el.getAttribute('height') ?? ''))
577
610
  changed = true;
578
611
  }
@@ -582,17 +615,18 @@ export function sanitizeTree(root, only, idTaken) {
582
615
  * HTML made safe to show and edit: see the top of this file for what is kept. It is parsed in a
583
616
  * document of its own, where nothing in it runs or loads, before any of it reaches the page.
584
617
  * Where there is no DOM to parse it with (on a server), nothing is returned: HTML that could
585
- * not be checked is not passed on.
618
+ * not be checked is not passed on. `keepAttributes` and `keepClasses` name marks of the
619
+ * application's own to leave on (see keptMarks).
586
620
  */
587
- export function sanitizeHtml(html) {
588
- return safeBody(html)?.innerHTML ?? '';
621
+ export function sanitizeHtml(html, options) {
622
+ return safeBody(html, undefined, keptMarks(options))?.innerHTML ?? '';
589
623
  }
590
624
  /** The HTML, read in a document of its own and made safe there; null where it cannot be. */
591
- function safeBody(html, idTaken) {
625
+ function safeBody(html, idTaken, keep) {
592
626
  if (!html || typeof DOMParser === 'undefined')
593
627
  return null;
594
628
  const doc = new DOMParser().parseFromString(`<!DOCTYPE html><html><body>${html}</body></html>`, 'text/html');
595
- sanitizeTree(doc.body, undefined, idTaken);
629
+ sanitizeTree(doc.body, undefined, idTaken, keep);
596
630
  return doc.body;
597
631
  }
598
632
  /**
@@ -601,8 +635,8 @@ function safeBody(html, idTaken) {
601
635
  * agree with the first for the check to mean anything, and that is where a sanitizer is got
602
636
  * round; it is also a third pass over a document that may hold megabytes of pictures.
603
637
  */
604
- export function sanitizedNodes(html, into, idTaken) {
605
- const body = safeBody(html, idTaken);
638
+ export function sanitizedNodes(html, into, idTaken, keep) {
639
+ const body = safeBody(html, idTaken, keep);
606
640
  if (!body)
607
641
  return [];
608
642
  return Array.from(body.childNodes).map((node) => into.importNode(node, true));
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "svelte-rtf-editor",
3
- "version": "1.10.0",
3
+ "version": "1.11.0",
4
4
  "description": "RTF viewer and rich-text editor components for Svelte 5",
5
5
  "license": "MIT",
6
6
  "homepage": "https://github.com/jcelano/svelte-rtf-editor#readme",