svelte-rtf-editor 1.11.0 → 1.13.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.
@@ -30,11 +30,27 @@ export interface KeepOptions {
30
30
  keepAttributes?: readonly string[];
31
31
  /** Class names that stay in an element's class list. */
32
32
  keepClasses?: readonly string[];
33
+ /**
34
+ * The fonts text may be set in, beside the document's own (the editor's `fonts`): a font
35
+ * name, or a CSS list whose first family is the name. Where this is given, a font that is
36
+ * not among them is taken off the text; given as an empty list, every font but the
37
+ * document's is. Where it is not given, fonts are left as they come. (The editor always
38
+ * gives its list, so an editor that offers no fonts lets none in.)
39
+ */
40
+ fonts?: readonly string[];
41
+ /** The document's own font (the editor's `fontFamily`), which text may always name. Only read where `fonts` is given. */
42
+ fontFamily?: string;
33
43
  }
34
44
  /** The same, as the sets the sanitizer reads. */
35
45
  export interface Kept {
36
46
  attributes: ReadonlySet<string>;
37
47
  classes: ReadonlySet<string>;
48
+ /**
49
+ * The fonts text may name, by the name each is looked up by, with what is written for it:
50
+ * the fonts offered, and the document's own. Not there where no list of fonts was given
51
+ * at all: then fonts are left as they come.
52
+ */
53
+ fonts?: ReadonlyMap<string, string>;
38
54
  }
39
55
  /**
40
56
  * What an application asked to have kept (the editor's `keepAttributes` and `keepClasses`), as
@@ -48,10 +64,14 @@ export declare function keptMarks(options: KeepOptions | undefined): Kept;
48
64
  * Make the elements under `root` safe, in place. With `only`, just the elements it accepts (the
49
65
  * ones a paste brought in) are looked at; the rest of the document is left as it is. With
50
66
  * `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.
67
+ * the application's own `data-` attributes and classes stay. `wordsLeft` is told of each element
68
+ * taken out with its words left in its place (a button, a text box), and of the text that holds
69
+ * them: an editor whose Redo puts the element back needs to know those words are there already.
70
+ * `leftOut` is told of each element that could not be checked, and so was taken out with what
71
+ * was in it: whoever shows the rest can say that a part is missing.
52
72
  * Returns whether anything was taken out or changed.
53
73
  */
54
- export declare function sanitizeTree(root: Element, only?: (el: Element) => boolean, idTaken?: (id: string) => boolean, keep?: Kept): boolean;
74
+ export declare function sanitizeTree(root: Element, only?: (el: Element) => boolean, idTaken?: (id: string) => boolean, keep?: Kept, wordsLeft?: (el: Element, words: Text) => void, leftOut?: (el: Element) => void): boolean;
55
75
  /**
56
76
  * HTML made safe to show and edit: see the top of this file for what is kept. It is parsed in a
57
77
  * document of its own, where nothing in it runs or loads, before any of it reaches the page.
@@ -65,8 +85,9 @@ export declare function sanitizeHtml(html: string, options?: KeepOptions): strin
65
85
  * checked is what is shown. Written out as text and read in again, a second reading has to
66
86
  * agree with the first for the check to mean anything, and that is where a sanitizer is got
67
87
  * round; it is also a third pass over a document that may hold megabytes of pictures.
88
+ * `leftOut` is told of each element that could not be checked (see sanitizeTree).
68
89
  */
69
- export declare function sanitizedNodes(html: string, into: Document, idTaken?: (id: string) => boolean, keep?: Kept): Node[];
90
+ export declare function sanitizedNodes(html: string, into: Document, idTaken?: (id: string) => boolean, keep?: Kept, leftOut?: (el: Element) => void): Node[];
70
91
  /** A run of a paste's text. */
71
92
  interface PastePiece {
72
93
  text: string;
@@ -82,6 +103,32 @@ export interface PasteNotes {
82
103
  /** What each of its text boxes held. */
83
104
  textareas: string[];
84
105
  }
106
+ /**
107
+ * Whether a paste's HTML holds words. Word and Excel copy their text as HTML and put a picture
108
+ * of the same text beside it; a browser copies a picture as the picture and an `<img>` with no
109
+ * words. So a paste that has both is words where its HTML has any, and a picture where not.
110
+ */
111
+ export declare function pasteHasWords(html: string): boolean;
112
+ /**
113
+ * The HTML of a paste that holds a frame, made safe and without the frame; or null where it
114
+ * holds none, which is nearly every paste.
115
+ *
116
+ * A frame is not kept in a document, and until 1.12.0 it was taken out after the browser had
117
+ * pasted it, with all else that is not safe. But a frame put in a page is a page being loaded,
118
+ * and Safari forgets every step it could undo when one is taken out again: after a paste that
119
+ * held a frame (a part of a web page with a video or an advertisement in it) nothing done
120
+ * before the paste could be undone, and after Undo and Redo of it, not the paste either. So a
121
+ * paste that holds a frame is put in by the editor, without it.
122
+ *
123
+ * What the editor puts in itself has to be safe before it is in the page, all of it. A
124
+ * browser's own paste takes the scripts and the handlers out of what it pastes; the command
125
+ * the editor inserts with does not, and a handler runs as soon as its element is in the page
126
+ * (`<video onerror>`, `<svg><image onerror>`), whatever is taken out a moment later. So the
127
+ * whole of it is made safe here, in a document of its own where nothing is loaded and no script
128
+ * is run, as HTML from anywhere else is. (For a time only the frames were taken out, and a
129
+ * page one copied from could run script in the application by having a frame in the copy.)
130
+ */
131
+ export declare function pasteWithoutFrames(html: string, keep?: Kept): string | null;
85
132
  /**
86
133
  * Read from a paste's HTML what the browser's own paste may lose: null where it holds neither
87
134
  * Word's hidden text nor a text box, which is nearly every paste.
@@ -94,6 +141,10 @@ export declare function pasteNotes(html: string): PasteNotes | null;
94
141
  * characters were the hidden ones. An element left with nothing in it goes too, where
95
142
  * `mayRemove` allows (a paragraph that was hidden whole would stay as an empty line in the
96
143
  * RTF). Returns whether anything was taken out.
144
+ *
145
+ * With null for `to`, the paste is one that Redo has put back, after its hidden text was taken
146
+ * out once. A browser then brings back some of that text and not the rest, so each hidden
147
+ * piece may be there or not; all the other text of the paste has to be, from `from` on.
97
148
  */
98
- export declare function removeWordHidden(root: Element, from: number, to: number, notes: PasteNotes, mayRemove?: (el: Element) => boolean): boolean;
149
+ export declare function removeWordHidden(root: Element, from: number, to: number | null, notes: PasteNotes, mayRemove?: (el: Element) => boolean): boolean;
99
150
  export {};
package/dist/sanitize.js CHANGED
@@ -24,7 +24,7 @@
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
- import { linkTarget } from './rtf-writer.js';
27
+ import { cssFontFamily, fontChoices, fontKey, linkTarget, sameFontList } from './rtf-writer.js';
28
28
  import { isSafeImageUrl } from './images.js';
29
29
  /** Elements taken out with everything in them. */
30
30
  const REMOVED_TAGS = new Set([
@@ -153,7 +153,20 @@ export function keptMarks(options) {
153
153
  // `md:flex`, `w-1/2` and `résumé` without saying so, and kept nothing out: a name is only
154
154
  // ever compared with the classes an element has, and one with a space in it is none of them.
155
155
  const classes = new Set(namesIn(options?.keepClasses));
156
- return { attributes, classes };
156
+ if (options?.fonts == null)
157
+ return { attributes, classes };
158
+ // The document font last: a list that names it too does not make it a font of the text's own.
159
+ const fonts = new Map(fontChoices(options.fonts).map((choice) => [choice.key, choice.css]));
160
+ const own = cssFontFamily(options?.fontFamily);
161
+ fonts.set(fontKey(own), own);
162
+ return { attributes, classes, fonts };
163
+ }
164
+ /**
165
+ * A font value as it may stay: what the application wrote for that font. Null where the font is
166
+ * not one it offers.
167
+ */
168
+ function offeredFont(value, keep) {
169
+ return keep.fonts?.get(fontKey(value)) ?? null;
157
170
  }
158
171
  /**
159
172
  * The names in one of the two settings. A caller without types can pass one name where a list
@@ -166,8 +179,18 @@ function namesIn(given) {
166
179
  const list = typeof given === 'string' ? [given] : given == null ? [] : Array.from(given);
167
180
  return list.filter((name) => typeof name === 'string').map((name) => name.trim());
168
181
  }
182
+ /**
183
+ * A table to look names up in that come from the document: a tag, a unit, the name of a size.
184
+ * Written as an object, such a table also answers to the names every object has (`constructor`,
185
+ * `toString`, `__proto__`), with a function where a list or a number was meant: an element
186
+ * named <constructor> with an attribute of its own stopped the sanitizer where it stood. A Map
187
+ * holds what was put in it and nothing else.
188
+ */
189
+ function table(entries) {
190
+ return new Map(Object.entries(entries));
191
+ }
169
192
  /** Attributes only some elements may keep. */
170
- const TAG_ATTRIBUTES = {
193
+ const TAG_ATTRIBUTES = table({
171
194
  a: ['href', 'target', 'rel'],
172
195
  img: ['src', 'alt', 'width', 'height'],
173
196
  td: ['colspan', 'rowspan', 'width'],
@@ -179,7 +202,9 @@ const TAG_ATTRIBUTES = {
179
202
  li: ['value'],
180
203
  font: ['color', 'size', 'face'],
181
204
  details: ['open']
182
- };
205
+ });
206
+ /** A color as `bgcolor` gives one: hex digits with or without "#", a name, rgb(). Nothing else is made a style of. */
207
+ const BGCOLOR = /^(#?[0-9a-f]{3,8}|[a-z]{3,30}|rgba?\([\d\s,.%]+\))$/i;
183
208
  /**
184
209
  * The one class that means something here: Safari's wrapper around a typed tab. Any other class
185
210
  * would take on whatever the page's own stylesheet gives that name.
@@ -200,9 +225,9 @@ const UNSAFE_STYLE_VALUE = /url\s*\(|expression\s*\(|javascript:|@import|behavio
200
225
  // the editing area cuts it off, or text of no size. They would be in the RTF and not on the
201
226
  // screen, so those values go too.
202
227
  /** Lengths in px, for the limits below. The units that follow the font are in FONT_UNITS. */
203
- const PX_PER_UNIT = { px: 1, pt: 4 / 3, pc: 16, in: 96, cm: 96 / 2.54, mm: 96 / 25.4, q: 96 / 101.6, rem: 16 };
228
+ const PX_PER_UNIT = table({ px: 1, pt: 4 / 3, pc: 16, in: 96, cm: 96 / 2.54, mm: 96 / 25.4, q: 96 / 101.6, rem: 16 });
204
229
  /** Lengths counted in the element's font size: how many of them make one. */
205
- const FONT_UNITS = { em: 1, ex: 2, ch: 2 };
230
+ const FONT_UNITS = table({ em: 1, ex: 2, ch: 2 });
206
231
  /** The font size where nothing above sets one. */
207
232
  const BASE_FONT_PX = 16;
208
233
  /**
@@ -211,10 +236,10 @@ const BASE_FONT_PX = 16;
211
236
  */
212
237
  const LEAST_FONT_PX = 0.5;
213
238
  /** The font sizes that have names, in px. */
214
- const NAMED_FONT_PX = {
239
+ const NAMED_FONT_PX = table({
215
240
  'xx-small': 9, 'x-small': 10, small: 13, medium: 16, large: 18, 'x-large': 24, 'xx-large': 32, 'xxx-large': 48,
216
241
  '-webkit-xxx-large': 48
217
- };
242
+ });
218
243
  /** A step up or down in size (`larger`, `smaller`): the factor a browser uses. */
219
244
  const FONT_STEP = 1.2;
220
245
  /**
@@ -232,13 +257,13 @@ const INLINE_TAGS = new Set([
232
257
  'small', 'big', 'abbr', 'cite', 'q', 'label', 'kbd', 'samp', 'var', 'tt', 'bdi', 'bdo', 'time', 'dfn'
233
258
  ]);
234
259
  /** What each part of a border picture is when there is none: what `border: …` sets them to. */
235
- const NO_BORDER_IMAGE = {
260
+ const NO_BORDER_IMAGE = table({
236
261
  'border-image-source': ['none', 'initial'],
237
262
  'border-image-slice': ['100%', 'initial'],
238
263
  'border-image-width': ['1', 'initial'],
239
264
  'border-image-outset': ['0', '0px', 'initial'],
240
265
  'border-image-repeat': ['stretch', 'initial']
241
- };
266
+ });
242
267
  /** A little over the widest page there is, 22 inches (2112 px). */
243
268
  const MOST_PX = 2200;
244
269
  /** The elements that have a width or a height of their own in a document. */
@@ -250,10 +275,12 @@ const DISPLAY_VALUES = new Set([
250
275
  ]);
251
276
  /** One number of a style value with its unit, as px; null for a percentage, a bare number or a unit not known. */
252
277
  function lengthPx(digits, unit, fontPx) {
253
- if (unit in PX_PER_UNIT)
254
- return Number(digits) * PX_PER_UNIT[unit];
255
- if (unit in FONT_UNITS)
256
- return (Number(digits) * fontPx) / FONT_UNITS[unit];
278
+ const px = PX_PER_UNIT.get(unit);
279
+ if (px !== undefined)
280
+ return Number(digits) * px;
281
+ const perFont = FONT_UNITS.get(unit);
282
+ if (perFont !== undefined)
283
+ return (Number(digits) * fontPx) / perFont;
257
284
  return null;
258
285
  }
259
286
  const NUMBER_AND_UNIT = /(-?\d*\.?\d+(?:e[+-]?\d+)?)([a-z%]*)/g;
@@ -303,8 +330,9 @@ function oneLengthPx(value, fontPx) {
303
330
  */
304
331
  function fontSizePx(value, parentPx) {
305
332
  const text = value.trim().toLowerCase();
306
- if (text in NAMED_FONT_PX)
307
- return NAMED_FONT_PX[text];
333
+ const named = NAMED_FONT_PX.get(text);
334
+ if (named !== undefined)
335
+ return named;
308
336
  if (text === 'larger')
309
337
  return parentPx * FONT_STEP;
310
338
  if (text === 'smaller')
@@ -397,7 +425,7 @@ function unreadAlone(text, el) {
397
425
  probe.setAttribute('style', text);
398
426
  return !probe.style || probe.style.length === 0;
399
427
  }
400
- function sanitizeStyle(el, tag, fonts) {
428
+ function sanitizeStyle(el, tag, fonts, keep) {
401
429
  const raw = el.getAttribute('style');
402
430
  if (raw === null)
403
431
  return;
@@ -408,6 +436,8 @@ function sanitizeStyle(el, tag, fonts) {
408
436
  }
409
437
  const wordHidden = WORD_HIDDEN.test(raw);
410
438
  const drop = [];
439
+ /** The font to write in place of the one named, where it is offered under another spelling. */
440
+ let font = null;
411
441
  // The size of this element's text first: its other lengths may be counted in it.
412
442
  let fontPx = fontPxAround(el, fonts);
413
443
  const fontSize = style.getPropertyValue('font-size');
@@ -424,12 +454,23 @@ function sanitizeStyle(el, tag, fonts) {
424
454
  const value = style.getPropertyValue(name);
425
455
  if (name === 'font-size')
426
456
  continue;
427
- if (name in NO_BORDER_IMAGE) {
457
+ if (name === 'font-family' && keep?.fonts) {
458
+ // Only a font the application offers, and written as it wrote it: the name and
459
+ // what to show where the font is missing.
460
+ font = offeredFont(value, keep);
461
+ if (font === null)
462
+ drop.push(name);
463
+ else if (sameFontList(font, value))
464
+ font = null;
465
+ continue;
466
+ }
467
+ const noPicture = NO_BORDER_IMAGE.get(name);
468
+ if (noPicture !== undefined) {
428
469
  // `border: 1px solid` also says "no border picture", and a browser lists that with
429
470
  // the properties it read. That much is no reason to write the attribute again; a
430
471
  // border picture itself is drawn outside its element, and a document has none.
431
- if (!NO_BORDER_IMAGE[name].includes(value.trim().toLowerCase()))
432
- drop.push(...Object.keys(NO_BORDER_IMAGE));
472
+ if (!noPicture.includes(value.trim().toLowerCase()))
473
+ drop.push(...NO_BORDER_IMAGE.keys());
433
474
  continue;
434
475
  }
435
476
  if (!STYLE_PROPERTY.test(name) || UNSAFE_STYLE_VALUE.test(value) || !sizeAllowed(name, value, tag, fontPx))
@@ -464,10 +505,12 @@ function sanitizeStyle(el, tag, fonts) {
464
505
  new Set(names).size !== names.length ||
465
506
  names.some((name) => !STYLE_PROPERTY.test(name) || !read.some((property) => property === name || property.startsWith(`${name}-`))) ||
466
507
  (shortAndPart && declared.some((declaration) => unreadAlone(declaration.text, el)));
467
- if (drop.length === 0 && !unread)
508
+ if (drop.length === 0 && !unread && font === null)
468
509
  return;
469
510
  for (const name of drop)
470
511
  style.removeProperty(name);
512
+ if (font !== null)
513
+ style.setProperty('font-family', font);
471
514
  // What Word hid stays hidden, in a way the browser keeps: mso-hide is not a property it
472
515
  // reads, so the text showed on screen while the RTF left it out.
473
516
  if (wordHidden)
@@ -500,7 +543,14 @@ function namesAGlobal(id) {
500
543
  return true;
501
544
  }
502
545
  function sanitizeAttributes(el, tag, fonts, idTaken, keep) {
503
- const own = TAG_ATTRIBUTES[tag];
546
+ const own = TAG_ATTRIBUTES.get(tag);
547
+ // `bgcolor`, as older pages and mail shade a table and its cells, is not kept. The shading
548
+ // is, as the style it stands for: without it, words set in white to stand on it were white
549
+ // on the white of the page, and the writer could not tell that they had had a background.
550
+ const shade = (el.getAttribute('bgcolor') ?? '').trim();
551
+ if (BGCOLOR.test(shade) && el.style && !el.style.backgroundColor) {
552
+ el.style.backgroundColor = /^[0-9a-f]{6}$/i.test(shade) ? `#${shade}` : shade;
553
+ }
504
554
  for (const attr of Array.from(el.attributes)) {
505
555
  const name = attr.name.toLowerCase();
506
556
  if (name === 'class') {
@@ -546,7 +596,15 @@ function sanitizeAttributes(el, tag, fonts, idTaken, keep) {
546
596
  if (tag === 'img' && el.hasAttribute('src') && !isSafeImageUrl(el.getAttribute('src') || '')) {
547
597
  el.removeAttribute('src');
548
598
  }
549
- sanitizeStyle(el, tag, fonts);
599
+ if (tag === 'font' && keep?.fonts && el.hasAttribute('face')) {
600
+ const face = el.getAttribute('face');
601
+ const font = offeredFont(face, keep);
602
+ if (font === null)
603
+ el.removeAttribute('face');
604
+ else if (!sameFontList(font, face))
605
+ el.setAttribute('face', font);
606
+ }
607
+ sanitizeStyle(el, tag, fonts, keep);
550
608
  }
551
609
  /**
552
610
  * Whether an element is a formula's copy for a screen reader, beside the same formula written
@@ -560,25 +618,24 @@ function isReadAloudCopy(el) {
560
618
  * Make the elements under `root` safe, in place. With `only`, just the elements it accepts (the
561
619
  * ones a paste brought in) are looked at; the rest of the document is left as it is. With
562
620
  * `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.
621
+ * the application's own `data-` attributes and classes stay. `wordsLeft` is told of each element
622
+ * taken out with its words left in its place (a button, a text box), and of the text that holds
623
+ * them: an editor whose Redo puts the element back needs to know those words are there already.
624
+ * `leftOut` is told of each element that could not be checked, and so was taken out with what
625
+ * was in it: whoever shows the rest can say that a part is missing.
564
626
  * Returns whether anything was taken out or changed.
565
627
  */
566
- export function sanitizeTree(root, only, idTaken, keep) {
628
+ export function sanitizeTree(root, only, idTaken, keep, wordsLeft, leftOut) {
567
629
  let changed = false;
568
630
  const fonts = new Map();
569
631
  /** The words of the last element that left its words, where they are still in the document. */
570
632
  let lastKept = null;
571
- for (const el of Array.from(root.querySelectorAll('*'))) {
572
- // Gone already, with something it was in.
573
- if (!root.contains(el))
574
- continue;
575
- if (only && !only(el))
576
- continue;
633
+ /** One element made safe; returns whether it was taken out or changed. */
634
+ const check = (el) => {
577
635
  const tag = el.tagName.toLowerCase();
578
636
  if (REMOVED_TAGS.has(tag) || isReadAloudCopy(el)) {
579
637
  el.remove();
580
- changed = true;
581
- continue;
638
+ return true;
582
639
  }
583
640
  if (TEXT_KEPT_TAGS.has(tag)) {
584
641
  const text = shownText(el, tag);
@@ -587,12 +644,12 @@ export function sanitizeTree(root, only, idTaken, keep) {
587
644
  const kept = el.ownerDocument.createTextNode(lastKept !== null && el.previousSibling === lastKept ? ` ${text}` : text);
588
645
  el.replaceWith(kept);
589
646
  lastKept = kept;
647
+ wordsLeft?.(el, kept);
590
648
  }
591
649
  else {
592
650
  el.remove();
593
651
  }
594
- changed = true;
595
- continue;
652
+ return true;
596
653
  }
597
654
  // A custom element would be given its behaviour by the page: only what it holds is kept,
598
655
  // and nothing of one that was hidden, which would show once the element is gone.
@@ -601,13 +658,31 @@ export function sanitizeTree(root, only, idTaken, keep) {
601
658
  el.remove();
602
659
  else
603
660
  el.replaceWith(...Array.from(el.childNodes));
604
- changed = true;
605
- continue;
661
+ return true;
606
662
  }
607
663
  const before = el.attributes.length + (el.getAttribute('style') ?? '') + (el.getAttribute('href') ?? '') + (el.getAttribute('width') ?? '') + (el.getAttribute('height') ?? '');
608
664
  sanitizeAttributes(el, tag, fonts, idTaken, keep);
609
- if (before !== el.attributes.length + (el.getAttribute('style') ?? '') + (el.getAttribute('href') ?? '') + (el.getAttribute('width') ?? '') + (el.getAttribute('height') ?? ''))
665
+ return before !== el.attributes.length + (el.getAttribute('style') ?? '') + (el.getAttribute('href') ?? '') + (el.getAttribute('width') ?? '') + (el.getAttribute('height') ?? '');
666
+ };
667
+ for (const el of Array.from(root.querySelectorAll('*'))) {
668
+ // Gone already, with something it was in.
669
+ if (!root.contains(el))
670
+ continue;
671
+ if (only && !only(el))
672
+ continue;
673
+ try {
674
+ if (check(el))
675
+ changed = true;
676
+ }
677
+ catch {
678
+ // An element that cannot be checked, for a reason nobody thought of, is not kept: it
679
+ // goes, with what is in it, and the elements after it are still looked at. Stopping
680
+ // here left the rest of a paste in the document as it came in, and whoever called
681
+ // with nothing to say which half had been made safe.
682
+ el.remove();
610
683
  changed = true;
684
+ leftOut?.(el);
685
+ }
611
686
  }
612
687
  return changed;
613
688
  }
@@ -622,11 +697,11 @@ export function sanitizeHtml(html, options) {
622
697
  return safeBody(html, undefined, keptMarks(options))?.innerHTML ?? '';
623
698
  }
624
699
  /** The HTML, read in a document of its own and made safe there; null where it cannot be. */
625
- function safeBody(html, idTaken, keep) {
700
+ function safeBody(html, idTaken, keep, leftOut) {
626
701
  if (!html || typeof DOMParser === 'undefined')
627
702
  return null;
628
703
  const doc = new DOMParser().parseFromString(`<!DOCTYPE html><html><body>${html}</body></html>`, 'text/html');
629
- sanitizeTree(doc.body, undefined, idTaken, keep);
704
+ sanitizeTree(doc.body, undefined, idTaken, keep, undefined, leftOut);
630
705
  return doc.body;
631
706
  }
632
707
  /**
@@ -634,16 +709,108 @@ function safeBody(html, idTaken, keep) {
634
709
  * checked is what is shown. Written out as text and read in again, a second reading has to
635
710
  * agree with the first for the check to mean anything, and that is where a sanitizer is got
636
711
  * round; it is also a third pass over a document that may hold megabytes of pictures.
712
+ * `leftOut` is told of each element that could not be checked (see sanitizeTree).
637
713
  */
638
- export function sanitizedNodes(html, into, idTaken, keep) {
639
- const body = safeBody(html, idTaken, keep);
714
+ export function sanitizedNodes(html, into, idTaken, keep, leftOut) {
715
+ const body = safeBody(html, idTaken, keep, leftOut);
640
716
  if (!body)
641
717
  return [];
642
718
  return Array.from(body.childNodes).map((node) => into.importNode(node, true));
643
719
  }
720
+ /** Where each part of a paste begins, when they are all there one after the other from `from`. */
721
+ function partsInARow(from, parts) {
722
+ let at = from;
723
+ return parts.map((part) => {
724
+ const start = at;
725
+ at += part.text.length;
726
+ return start;
727
+ });
728
+ }
729
+ /**
730
+ * Where each part of a paste begins in `shown`, from `from` on, when a hidden part may be
731
+ * missing (null for one that is): the first reading that fits, taking each hidden part as there
732
+ * where it can be. Null where there is no reading: this text is not that paste.
733
+ */
734
+ function partsPutBack(shown, from, parts) {
735
+ const starts = [];
736
+ /** Where the reading stood before each part, to go back to. */
737
+ const stood = [];
738
+ let at = from;
739
+ let i = 0;
740
+ // (A reading is given up and taken again from an earlier part; a text made to be read in
741
+ // very many ways is not read at all.)
742
+ for (let steps = 0; i < parts.length; steps++) {
743
+ if (steps > 200_000)
744
+ return null;
745
+ stood[i] = at;
746
+ if (shown.startsWith(parts[i].text, at)) {
747
+ starts[i] = at;
748
+ at += parts[i].text.length;
749
+ i++;
750
+ }
751
+ else if (parts[i].hidden) {
752
+ starts[i] = null;
753
+ i++;
754
+ }
755
+ else {
756
+ // The last hidden part taken as there is taken as missing, and read on from it.
757
+ let back = i - 1;
758
+ while (back >= 0 && !(parts[back].hidden && starts[back] !== null))
759
+ back--;
760
+ if (back < 0)
761
+ return null;
762
+ starts[back] = null;
763
+ at = stood[back];
764
+ i = back + 1;
765
+ }
766
+ }
767
+ return starts;
768
+ }
644
769
  /** Elements whose text is not text of the page. */
645
770
  const NOT_PAGE_TEXT = new Set(['script', 'style', 'title', 'template', 'noscript', 'textarea']);
646
771
  const withoutSpace = (text) => text.replace(/\s/g, '');
772
+ /**
773
+ * Whether a paste's HTML holds words. Word and Excel copy their text as HTML and put a picture
774
+ * of the same text beside it; a browser copies a picture as the picture and an `<img>` with no
775
+ * words. So a paste that has both is words where its HTML has any, and a picture where not.
776
+ */
777
+ export function pasteHasWords(html) {
778
+ if (!html || typeof DOMParser === 'undefined')
779
+ return false;
780
+ const body = new DOMParser().parseFromString(html, 'text/html').body;
781
+ for (const el of Array.from(body.querySelectorAll(Array.from(NOT_PAGE_TEXT).join(','))))
782
+ el.remove();
783
+ return (body.textContent ?? '').trim() !== '';
784
+ }
785
+ /** A frame in a paste's HTML: `<iframe>`, and the `<frame>` of an older page. */
786
+ const FRAME = /<i?frame[\s>/]/i;
787
+ /**
788
+ * The HTML of a paste that holds a frame, made safe and without the frame; or null where it
789
+ * holds none, which is nearly every paste.
790
+ *
791
+ * A frame is not kept in a document, and until 1.12.0 it was taken out after the browser had
792
+ * pasted it, with all else that is not safe. But a frame put in a page is a page being loaded,
793
+ * and Safari forgets every step it could undo when one is taken out again: after a paste that
794
+ * held a frame (a part of a web page with a video or an advertisement in it) nothing done
795
+ * before the paste could be undone, and after Undo and Redo of it, not the paste either. So a
796
+ * paste that holds a frame is put in by the editor, without it.
797
+ *
798
+ * What the editor puts in itself has to be safe before it is in the page, all of it. A
799
+ * browser's own paste takes the scripts and the handlers out of what it pastes; the command
800
+ * the editor inserts with does not, and a handler runs as soon as its element is in the page
801
+ * (`<video onerror>`, `<svg><image onerror>`), whatever is taken out a moment later. So the
802
+ * whole of it is made safe here, in a document of its own where nothing is loaded and no script
803
+ * is run, as HTML from anywhere else is. (For a time only the frames were taken out, and a
804
+ * page one copied from could run script in the application by having a frame in the copy.)
805
+ */
806
+ export function pasteWithoutFrames(html, keep) {
807
+ if (!FRAME.test(html) || typeof DOMParser === 'undefined')
808
+ return null;
809
+ // (None after all: the letters were text, in a line of code or in a comment.)
810
+ if (new DOMParser().parseFromString(html, 'text/html').querySelector('iframe, frame, frameset') === null)
811
+ return null;
812
+ return safeBody(html, undefined, keep)?.innerHTML ?? '';
813
+ }
647
814
  /**
648
815
  * Read from a paste's HTML what the browser's own paste may lose: null where it holds neither
649
816
  * Word's hidden text nor a text box, which is nearly every paste.
@@ -697,6 +864,10 @@ export function pasteNotes(html) {
697
864
  * characters were the hidden ones. An element left with nothing in it goes too, where
698
865
  * `mayRemove` allows (a paragraph that was hidden whole would stay as an empty line in the
699
866
  * RTF). Returns whether anything was taken out.
867
+ *
868
+ * With null for `to`, the paste is one that Redo has put back, after its hidden text was taken
869
+ * out once. A browser then brings back some of that text and not the rest, so each hidden
870
+ * piece may be there or not; all the other text of the paste has to be, from `from` on.
700
871
  */
701
872
  export function removeWordHidden(root, from, to, notes, mayRemove) {
702
873
  const texts = [];
@@ -709,25 +880,26 @@ export function removeWordHidden(root, from, to, notes, mayRemove) {
709
880
  for (let i = children.length - 1; i >= 0; i--)
710
881
  todo.push(children[i]);
711
882
  }
712
- const pasted = withoutSpace(texts.map((text) => text.data).join('')).slice(from, to);
883
+ const shown = withoutSpace(texts.map((text) => text.data).join(''));
713
884
  // A browser may leave what is not displayed out of a paste, or bring it along.
714
885
  for (const pieces of [notes.pieces, notes.pieces.filter((piece) => !piece.undisplayed)]) {
715
- if (withoutSpace(pieces.map((piece) => piece.text).join('')) !== pasted)
886
+ const parts = pieces.map((piece) => ({ text: withoutSpace(piece.text), hidden: piece.hidden })).filter((part) => part.text !== '');
887
+ if (to !== null && parts.map((part) => part.text).join('') !== shown.slice(from, to))
888
+ continue;
889
+ const starts = to === null ? partsPutBack(shown, from, parts) : partsInARow(from, parts);
890
+ if (starts === null)
716
891
  continue;
717
892
  /** The hidden runs, as [first, after last] among the characters that are not white space. */
718
893
  const runs = [];
719
- let at = from;
720
- for (const piece of pieces) {
721
- const length = withoutSpace(piece.text).length;
722
- if (piece.hidden && length > 0) {
723
- const last = runs[runs.length - 1];
724
- if (last && last[1] === at)
725
- last[1] = at + length;
726
- else
727
- runs.push([at, at + length]);
728
- }
729
- at += length;
730
- }
894
+ parts.forEach((part, i) => {
895
+ if (!part.hidden || starts[i] === null)
896
+ return;
897
+ const last = runs[runs.length - 1];
898
+ if (last && last[1] === starts[i])
899
+ last[1] = starts[i] + part.text.length;
900
+ else
901
+ runs.push([starts[i], starts[i] + part.text.length]);
902
+ });
731
903
  if (runs.length === 0)
732
904
  return false;
733
905
  let index = 0;
package/dist/utils.js CHANGED
@@ -1,5 +1,6 @@
1
1
  import { linkTarget } from './rtf-writer.js';
2
2
  import { tableModel } from './table-model.js';
3
+ import { itemNumber, listStart, markerText, numberStyleOf } from './list-markers.js';
3
4
  /** Elements whose text is never shown. */
4
5
  const UNSHOWN_TAGS = new Set(['style', 'script', 'template', 'noscript', 'title', 'head']);
5
6
  /** Elements that are a line of their own and nothing more, as a <div> is. */
@@ -75,6 +76,8 @@ function imageToMarkdown(alt, src, ctx) {
75
76
  * A list item's Markdown under its marker: later lines are indented to the item's text, so a
76
77
  * table, a code block or a list inside the item stays in it.
77
78
  */
79
+ /** A block of Markdown that is not a paragraph of words: a list, a quotation, a heading, code, a table, a rule. */
80
+ const BLOCK_START = /^(?:```|~~~|>|#{1,6}(?: |$)|[-+*](?: |$)|\d{1,9}[.)](?: |$)|\||(?:-{3,}|\*{3,}|_{3,})\s*$| {4})/;
78
81
  function listItem(marker, body) {
79
82
  // (Spaces and line breaks only are taken off its ends: other white space is the document's.)
80
83
  return `${marker}${body.replace(/^[ \n]+|[ \n]+$/g, '').replace(/\n(?=[^\n])/g, `\n${' '.repeat(marker.length)}`)}`;
@@ -550,6 +553,10 @@ function listToMarkdown(list, ordered, ctx, out) {
550
553
  // block: the list starts as near to its own number as Markdown can count from.
551
554
  const itemCount = Array.from(list.children).filter((child) => child.tagName === 'LI').length;
552
555
  let number = Number.isFinite(start) ? Math.max(0, Math.min(start, 1_000_000_000 - Math.max(itemCount, 1))) : 1;
556
+ // The number the screen shows, for an item numbered in letters or Roman numerals. Markdown
557
+ // numbers a list in digits only, and "see part B" has to find an item that says "B.": such
558
+ // an item is written as a bullet with its marker as the first words, "- B. Left breast".
559
+ let shownNumber = listStart(list);
553
560
  let items = [];
554
561
  let loose = [];
555
562
  const endItems = () => {
@@ -573,9 +580,23 @@ function listToMarkdown(list, ordered, ctx, out) {
573
580
  if (!inside)
574
581
  return;
575
582
  const blocks = blocksOf(node.childNodes, inside);
583
+ const style = ordered ? numberStyleOf(list, node) : 'decimal';
584
+ shownNumber = itemNumber(node, shownNumber);
585
+ const label = style === 'decimal' ? '' : `${markerText(shownNumber, style)}.`;
586
+ shownNumber++;
587
+ if (label) {
588
+ // Before the words of the item; on a line of its own before a block that is not
589
+ // words (a list, a code block, a table, a quotation).
590
+ if (blocks.length && !BLOCK_START.test(blocks[0]))
591
+ blocks[0] = `${label} ${blocks[0]}`;
592
+ else
593
+ blocks.unshift(label);
594
+ }
576
595
  // An item whose text is hidden shows no marker either.
577
596
  if (blocks.length || !inside.unseen)
578
- items.push({ marker: ordered ? `${number++}. ` : '- ', blocks });
597
+ items.push({ marker: ordered && !label ? `${number++}. ` : '- ', blocks });
598
+ else if (label)
599
+ blocks.shift();
579
600
  }
580
601
  else if (['ul', 'ol', 'menu', 'dir'].includes(tag)) {
581
602
  endLoose();
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "svelte-rtf-editor",
3
- "version": "1.11.0",
3
+ "version": "1.13.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",