svelte-rtf-editor 1.13.0 → 1.16.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.
@@ -73,10 +73,13 @@ export declare const LINK_COLOR: {
73
73
  readonly g: 0;
74
74
  readonly b: 255;
75
75
  };
76
+ export declare function parseColor(colorStr: string): RGB | null;
76
77
  /** The contrast of two colors as WCAG counts it: 1 for the same color, 21 for black on white. */
77
78
  export declare function colorContrast(a: RGB, b: RGB): number;
78
79
  /** Whether words in a color are hard to read on a white page. */
79
80
  export declare function hardToReadOnWhite(color: RGB): boolean;
81
+ /** A background that shows nothing: none, or one with no opacity. */
82
+ export declare const NO_BACKGROUND: RegExp;
80
83
  /**
81
84
  * Size htmlToRtf would produce, without doing the conversion.
82
85
  *
@@ -158,4 +161,11 @@ export declare function cssFontFamily(name: string | undefined): string;
158
161
  */
159
162
  export declare function normalizeFontSize(fontSize: number | undefined): number;
160
163
  export declare function htmlToRtf(editorEl: HTMLElement, options?: RtfWriteOptions): string;
164
+ /**
165
+ * The least a line is spaced by, as a share of the height of its text. Lines closer than this
166
+ * are printed over each other: two lines of a diagnosis, there to be selected and not to be
167
+ * read. A line height below it is no spacing a document has, and is not written (nor read, nor
168
+ * kept by the sanitizer, nor set by the editor).
169
+ */
170
+ export declare const LEAST_LINES = 0.8;
161
171
  export {};
@@ -16,7 +16,8 @@
16
16
  * lostWithoutItsBackground.
17
17
  */
18
18
  import { tableModel, columnShares, tableRowsInOrder, rowCells } from './table-model.js';
19
- import { itemNumber, listStart, markerText, numberStyleOf } from './list-markers.js';
19
+ import { gappedRowWidths } from './picture-rows.js';
20
+ import { itemNumber, listStart, markerGapTwips, markerText, numberStyleOf } from './list-markers.js';
20
21
  /**
21
22
  * Font used when no fontFamily is given: what the editor and the viewer show, and what the RTF
22
23
  * names. This is the one place the default is named; the size estimate, the components and the
@@ -66,7 +67,7 @@ const MAX_TWIPS = 31680;
66
67
  */
67
68
  const MAX_ELEMENT_DEPTH = 600;
68
69
  // ── Color helpers ──
69
- function parseColor(colorStr) {
70
+ export function parseColor(colorStr) {
70
71
  if (!colorStr)
71
72
  return null;
72
73
  const s = colorStr.trim().toLowerCase();
@@ -140,7 +141,7 @@ export function hardToReadOnWhite(color) {
140
141
  return colorContrast(color, WHITE) < READABLE_ON_WHITE;
141
142
  }
142
143
  /** A background that shows nothing: none, or one with no opacity. */
143
- const NO_BACKGROUND = /^(|transparent|none|initial|inherit|unset|revert|currentcolor|rgba\([^)]*,\s*0(\.0+)?\s*\)|#[0-9a-f]{3}0|#[0-9a-f]{6}00)$/;
144
+ export const NO_BACKGROUND = /^(|transparent|none|initial|inherit|unset|revert|currentcolor|rgba\([^)]*,\s*0(\.0+)?\s*\)|#[0-9a-f]{3}0|#[0-9a-f]{6}00)$/;
144
145
  /**
145
146
  * The background an element sets by itself: its color, 'some' for one that is set and not read
146
147
  * (a color by a name this file does not know, a picture), or null. From its style, and from the
@@ -770,6 +771,19 @@ export function estimateRtfBytes(editorEl, options = {}) {
770
771
  // (Its own, or the one a block around the table hands down.)
771
772
  if (el.closest('center, [style*="text-align"], [align]'))
772
773
  total += 3;
774
+ // Its borders, in each row it is written in, with a color numbered as high as any,
775
+ // and the mark of a header cell that has borders ("{\*\inkth}", 10).
776
+ const borders = cellBordersRtf(el, () => 999).length;
777
+ if (borders > 0) {
778
+ const down = Math.max(1, parseInt(el.getAttribute('rowspan') ?? '', 10) || 1);
779
+ const rowCount = el.closest('table')?.querySelectorAll('tr').length ?? 1;
780
+ total += borders * Math.min(rowCount, el.getAttribute('rowspan') === '0' ? rowCount : down) + 10;
781
+ // And each color a border has is in the color table, the first time (at most 25
782
+ // bytes, "\red255\green255\blue255;"): a cell may have four.
783
+ for (const [side] of BORDER_SIDES)
784
+ if (cellBorder(el, side)?.color)
785
+ total += 25;
786
+ }
773
787
  const rows = parseInt(el.getAttribute('rowspan') ?? '', 10);
774
788
  if (rows !== 1 && Number.isFinite(rows) && !el.parentElement?.closest('td, th')) {
775
789
  // rowspan="0" reaches the last row; no span reaches past the table.
@@ -807,6 +821,10 @@ export function estimateRtfBytes(editorEl, options = {}) {
807
821
  total += 27;
808
822
  }
809
823
  }
824
+ // A list with a gap of its own hangs its items by it: "\fi-2880" and a wider "\liN" are
825
+ // up to four more on each of their paragraphs than the quarter inch counted for them.
826
+ if ((tag === 'ul' || tag === 'ol') && markerGapTwips(el) !== null)
827
+ total += 4 * (1 + el.querySelectorAll(':scope > li, :scope > li :is(p, div, br)').length);
810
828
  // A paragraph inside a list item is written at the item's indent (\liN, up to 7).
811
829
  if ((tag === 'p' || tag === 'div') && el.parentElement?.tagName === 'LI')
812
830
  total += 8;
@@ -822,6 +840,22 @@ export function estimateRtfBytes(editorEl, options = {}) {
822
840
  counter++;
823
841
  }
824
842
  }
843
+ // A heading's spacing, and a picture's (before the picture, after its caption).
844
+ if (HEADING_TAGS.has(tag) || (tag === 'figure' && !el.closest('td, th')))
845
+ total += spacingControls(el).length;
846
+ // A list item's: the line spacing on each of its paragraphs (one more for each block
847
+ // or line break in it), the space before and after once.
848
+ if (tag === 'li') {
849
+ const lines = spacingControls(el, 'lines').length;
850
+ if (lines || el.style?.marginTop || el.style?.marginBottom)
851
+ total += spacingControls(el).length + lines * el.querySelectorAll(`${blockSelector}, br`).length;
852
+ }
853
+ // A paragraph's in a table cell, which then restates "\\pard\\intbl " (11).
854
+ if ((tag === 'p' || tag === 'div') && el.closest('td, th')) {
855
+ const spacing = spacingControls(el).length;
856
+ if (spacing)
857
+ total += spacing + 11;
858
+ }
825
859
  // A figure with no picture is a paragraph of what it holds: "\pard\intbl\qc\liN " and
826
860
  // "\par " (at most 30).
827
861
  if (tag === 'figure' && !el.querySelector('img'))
@@ -1112,8 +1146,79 @@ function collectColors(root, colorMap) {
1112
1146
  // <font color="..."> is produced by execCommand('foreColor')
1113
1147
  if (el.tagName?.toLowerCase() === 'font')
1114
1148
  addColor(el.getAttribute('color'), colorMap, el, root);
1149
+ // The color of a table cell's borders.
1150
+ if (el.tagName === 'TD' || el.tagName === 'TH') {
1151
+ for (const [side] of BORDER_SIDES) {
1152
+ const color = cellBorder(el, side)?.color;
1153
+ if (color)
1154
+ colorMap.set(colorKey(color), color);
1155
+ }
1156
+ }
1115
1157
  }
1116
1158
  }
1159
+ // ── Table cell borders ──
1160
+ const BORDER_SIDES = [['top', 't'], ['left', 'l'], ['bottom', 'b'], ['right', 'r']];
1161
+ /** The line of a border, as RTF names it; any other that draws one is a plain line. */
1162
+ const BORDER_LINES = new Map(Object.entries({ solid: 'brdrs', double: 'brdrdb', dotted: 'brdrdot', dashed: 'brdrdash' }));
1163
+ const BORDER_WIDTHS = new Map(Object.entries({ thin: 15, medium: 45, thick: 75 }));
1164
+ /** The widest border RTF has (\brdrw75, 3.75 pt). */
1165
+ const MAX_BORDER_TWIPS = 75;
1166
+ /**
1167
+ * One border of a table cell as its own style sets it, or null where it sets none: the line,
1168
+ * its width in twips, and its color where that is not the text's own (black, or one this file
1169
+ * cannot read, is left to the reader). Read from the side's own properties, and from
1170
+ * `border-top` and `border` where a DOM does not spread those over them.
1171
+ */
1172
+ function cellBorder(el, side) {
1173
+ const style = el.style;
1174
+ if (!style)
1175
+ return null;
1176
+ const value = (name) => (style.getPropertyValue(name) || '').trim().toLowerCase();
1177
+ let line = value(`border-${side}-style`);
1178
+ let width = value(`border-${side}-width`);
1179
+ let color = value(`border-${side}-color`);
1180
+ if (!line) {
1181
+ for (const short of [`border-${side}`, 'border']) {
1182
+ const words = value(short).split(/\s+(?![^(]*\))/).filter(Boolean);
1183
+ if (words.length === 0)
1184
+ continue;
1185
+ for (const word of words) {
1186
+ if (BORDER_STYLE_WORDS.has(word))
1187
+ line = word;
1188
+ else if (BORDER_WIDTHS.has(word) || /^[\d.]/.test(word))
1189
+ width = word;
1190
+ else
1191
+ color = word;
1192
+ }
1193
+ break;
1194
+ }
1195
+ line ||= value('border-style');
1196
+ width ||= value('border-width');
1197
+ color ||= value('border-color');
1198
+ }
1199
+ if (!BORDER_STYLE_WORDS.has(line) || line === 'none' || line === 'hidden')
1200
+ return null;
1201
+ const twips = width === '' ? BORDER_WIDTHS.get('medium') : (BORDER_WIDTHS.get(width) ?? lengthTwips(width));
1202
+ if (!twips)
1203
+ return null;
1204
+ const rgb = parseColor(color);
1205
+ return { line: BORDER_LINES.get(line) ?? 'brdrs', twips: Math.min(MAX_BORDER_TWIPS, twips), color: rgb && colorKey(rgb) !== '0,0,0' ? rgb : null };
1206
+ }
1207
+ const BORDER_STYLE_WORDS = new Set(['none', 'hidden', 'solid', 'double', 'dotted', 'dashed', 'groove', 'ridge', 'inset', 'outset']);
1208
+ /** A cell's borders for its row's definition: "\clbrdrt\brdrs\brdrw15" for each side that has one. */
1209
+ function cellBordersRtf(el, colorIndex) {
1210
+ let rtf = '';
1211
+ for (const [side, letter] of BORDER_SIDES) {
1212
+ const border = cellBorder(el, side);
1213
+ if (!border)
1214
+ continue;
1215
+ const index = border.color ? colorIndex(border.color) : undefined;
1216
+ rtf += `\\clbrdr${letter}\\${border.line}\\brdrw${border.twips}${index ? `\\brdrcf${index}` : ''}`;
1217
+ }
1218
+ return rtf;
1219
+ }
1220
+ /** The one border the reader gives a header cell: see tableRtf. */
1221
+ const HEADER_MARK_BORDER = '\\clbrdrb\\brdrs\\brdrw15';
1117
1222
  /** How many elements deep the walker is (see MAX_ELEMENT_DEPTH). */
1118
1223
  let walkDepth = 0;
1119
1224
  /** The text an element shows, read without a call per level of nesting. */
@@ -1248,8 +1353,8 @@ function walkNodeAt(node, ctx, restate, endLooseText) {
1248
1353
  break;
1249
1354
  }
1250
1355
  if (ctx.inTableCell) {
1251
- // Alignment or an indent needs a paragraph of its own, even as the cell's first.
1252
- const layout = paragraphLayout(el, ctx);
1356
+ // Alignment, an indent or spacing needs a paragraph of its own, even as the cell's first.
1357
+ const layout = cellParagraphLayout(el, ctx);
1253
1358
  const restate = afterLooseText
1254
1359
  ? `\\par \\pard\\intbl${layout} `
1255
1360
  : el.previousElementSibling || layout ? `\\pard\\intbl${layout} ` : '';
@@ -1365,8 +1470,11 @@ function walkNodeAt(node, ctx, restate, endLooseText) {
1365
1470
  const captionEl = img ? anyCaption : Array.from(el.children).find((c) => c.tagName === 'FIGCAPTION' && !isHidden(c));
1366
1471
  const caption = (captionEl ? shownText(captionEl) : '').trim();
1367
1472
  const align = `${ownAlign(el) ?? (cellAlign(ctx) || '\\ql')}${liControl(ctx.indent + leftMarginTwips(el))}`;
1473
+ // The space before a picture is before the picture, and the space after it is after
1474
+ // its caption, where it has one. (Not in a table cell, as for any paragraph there.)
1475
+ const spaced = (part) => (ctx.inTableCell ? '' : spacingControls(el, part));
1368
1476
  if (img) {
1369
- rtf += `\\pard${inCell(ctx)}${align} ${imageBody(img)}\\par `;
1477
+ rtf += `\\pard${inCell(ctx)}${align}${spaced('before')}${caption ? '' : spaced('after')} ${imageBody(img)}\\par `;
1370
1478
  }
1371
1479
  else {
1372
1480
  // A figure with no picture is a block of what it holds: its lines end with \par, as a
@@ -1375,7 +1483,7 @@ function walkNodeAt(node, ctx, restate, endLooseText) {
1375
1483
  rtf += flowRtf(held, ctx, null, `\\pard${inCell(ctx)}${align} `);
1376
1484
  }
1377
1485
  if (caption) {
1378
- rtf += `{\\*\\inkcap}\\pard${inCell(ctx)}${align}\\i ${escapeRtf(caption)}${ctx.italic ? '' : '\\i0'}\\par `;
1486
+ rtf += `{\\*\\inkcap}\\pard${inCell(ctx)}${align}${img ? spaced('after') : ''}\\i ${escapeRtf(caption)}${ctx.italic ? '' : '\\i0'}\\par `;
1379
1487
  }
1380
1488
  break;
1381
1489
  }
@@ -1555,7 +1663,10 @@ function listRtfAt(list, ctx) {
1555
1663
  // A list read back from RTF carries the indent beyond its level's own as a margin, which
1556
1664
  // is negative for a list nested by less than half an inch.
1557
1665
  const margin = lengthTwips(list.style?.marginLeft, true) ?? 0;
1558
- const left = Math.max(LIST_HANG, ctx.indent + margin + LIST_STEP);
1666
+ // The marker stands where it always has, a quarter inch into the level; the text is the
1667
+ // list's gap after it (see markerGapTwips), a quarter inch where it sets none.
1668
+ const hang = markerGapTwips(list) ?? LIST_HANG;
1669
+ const left = Math.max(hang, ctx.indent + margin + LIST_STEP - LIST_HANG + hang);
1559
1670
  let counter = ordered ? listStart(list) : 1;
1560
1671
  const itemCtx = { ...ctx, indent: left, cellAlign: listAlign(ctx) };
1561
1672
  const paragraph = `\\pard${inCell(ctx)}${listAlign(ctx)}${liControl(left)}`;
@@ -1579,7 +1690,7 @@ function listRtfAt(list, ctx) {
1579
1690
  const marker = ordered ? ` ${markerText(counter, numberStyleOf(list, child))}.\\tab ` : '\\bullet\\tab ';
1580
1691
  // The item's own color and the like; its marker takes them too, as on screen.
1581
1692
  const own = charFormat(child, tag, itemCtx, true);
1582
- rtf += `${own.on}${flowRtf(Array.from(child.childNodes), own.ctx, `${paragraph}\\fi-${LIST_HANG}${marker}`, `${paragraph} `)}${own.off}`;
1693
+ rtf += `${own.on}${itemRtf(child, own.ctx, paragraph, `\\fi-${hang}${marker}`)}${own.off}`;
1583
1694
  counter++;
1584
1695
  }
1585
1696
  else if (tag === 'ul' || tag === 'ol') {
@@ -1596,6 +1707,26 @@ function listRtfAt(list, ctx) {
1596
1707
  flushLoose();
1597
1708
  return rtf;
1598
1709
  }
1710
+ /**
1711
+ * A list item's paragraphs, opening with `paragraph` (its indent), the first with its hang and marker,
1712
+ * and its spacing: the space before on the first paragraph, the space after on the last, and
1713
+ * the line spacing on each, as an item of more than one paragraph is shown.
1714
+ */
1715
+ function itemRtf(item, ctx, paragraph, marker) {
1716
+ const before = spacingControls(item, 'before');
1717
+ const after = spacingControls(item, 'after');
1718
+ const lines = spacingControls(item, 'lines', tallestText(item, ctx.size));
1719
+ if (!before && !after && !lines)
1720
+ return flowRtf(Array.from(item.childNodes), ctx, `${paragraph}${marker}`, `${paragraph} `);
1721
+ // (Where the item's last paragraph begins is known once it is written: each begins with
1722
+ // ITEM_PARAGRAPH, which is the space after on the last and nothing on the others. The
1723
+ // character is never in what is written: text is escaped, and a control character with it.)
1724
+ const written = flowRtf(Array.from(item.childNodes), ctx, `${paragraph}${before}${lines}${ITEM_PARAGRAPH}${marker}`, `${paragraph}${lines}${ITEM_PARAGRAPH} `);
1725
+ const last = written.lastIndexOf(ITEM_PARAGRAPH);
1726
+ return `${written.slice(0, last)}${after}${written.slice(last + 1)}`.replaceAll(ITEM_PARAGRAPH, '');
1727
+ }
1728
+ /** Where a paragraph of a list item begins, while the item is written (see itemRtf). */
1729
+ const ITEM_PARAGRAPH = '\u0001';
1599
1730
  /**
1600
1731
  * The alignment a list's items are written with: the table cell's, inside one. Anywhere else a
1601
1732
  * list is written left-aligned, whatever a <div> around it says, because only a left-aligned
@@ -1700,11 +1831,19 @@ function tableRtf(table, ctx) {
1700
1831
  if (model.columns === 0)
1701
1832
  return rtf;
1702
1833
  let cumulative = 0;
1703
- const edges = columnShares(model, table).map((share) => {
1704
- cumulative += share;
1705
- return Math.round(cumulative * PAGE_WIDTH);
1706
- });
1707
- edges[edges.length - 1] = PAGE_WIDTH; // snap last edge to avoid rounding drift
1834
+ // Pictures side by side with a set gap between them are written at their own widths, the
1835
+ // gap an empty cell, with no space inside a cell: the picture fills its cell, and nothing
1836
+ // is stretched to the page (see picture-rows.ts).
1837
+ const gapped = gappedRowWidths(table);
1838
+ const edges = gapped
1839
+ ? gapped.map((twips) => Math.round((cumulative += twips)))
1840
+ : columnShares(model, table).map((share) => {
1841
+ cumulative += share;
1842
+ return Math.round(cumulative * PAGE_WIDTH);
1843
+ });
1844
+ if (!gapped)
1845
+ edges[edges.length - 1] = PAGE_WIDTH; // snap last edge to avoid rounding drift
1846
+ const gaph = gapped ? 0 : 120;
1708
1847
  const started = new Set();
1709
1848
  for (let r = 0; r < model.rows.length; r++) {
1710
1849
  const row = model.rows[r];
@@ -1723,8 +1862,16 @@ function tableRtf(table, ctx) {
1723
1862
  const merged = cell !== null && cell.rowspan > 1;
1724
1863
  if (merged)
1725
1864
  definition += origin ? '\\clvmgf' : '\\clvmrg';
1726
- if (cell?.el.tagName.toLowerCase() === 'th')
1727
- definition += '\\clbrdrb\\brdrs';
1865
+ // A cell's own borders. A header cell with none (or with the line under it alone,
1866
+ // which is how one is read back) is marked as it always was, by a bare line under
1867
+ // it. One with borders of its own has those, and is marked in what it holds:
1868
+ // Word and TextEdit put borders on every cell of a gridded table, so a border
1869
+ // cannot say which cells are headers there.
1870
+ const borders = cell ? cellBordersRtf(cell.el, (color) => ctx.colorIndex.get(colorKey(color))) : '';
1871
+ const header = cell?.el.tagName.toLowerCase() === 'th';
1872
+ const plainHeader = header && (borders === '' || borders === HEADER_MARK_BORDER);
1873
+ definition += plainHeader ? '\\clbrdrb\\brdrs' : borders;
1874
+ const headerMark = header && !plainHeader && origin ? '{\\*\\inkth}' : '';
1728
1875
  definition += `\\cellx${edges[last]}`;
1729
1876
  // A cell with no alignment of its own takes that of what the table is in.
1730
1877
  const align = cell && origin ? alignOf(cell.el, ctx) : '';
@@ -1735,11 +1882,11 @@ function tableRtf(table, ctx) {
1735
1882
  const own = charFormat(cell.el, 'td', { ...ctx, inTableCell: true, cellAlign: align }, true);
1736
1883
  content = `${own.on}${withoutTrailingPar(walkChildren(cell.el, own.ctx))}`;
1737
1884
  }
1738
- bodies += `{\\pard\\intbl${align} \\f${ctx.font} \\sa0 \\li0 \\fi0 ${content}\\cell}`;
1885
+ bodies += `{\\pard\\intbl${align} \\f${ctx.font} \\sa0 \\li0 \\fi0 ${headerMark}${content}\\cell}`;
1739
1886
  c = last + 1;
1740
1887
  }
1741
1888
  const lastRow = r === model.rows.length - 1 ? '\\lastrow' : '';
1742
- rtf += `{\\trowd\\trgaph120${definition}\\trkeep\\intbl{${bodies}}\\intbl${lastRow}\\row}`;
1889
+ rtf += `{\\trowd\\trgaph${gaph}${definition}\\trkeep\\intbl{${bodies}}\\intbl${lastRow}\\row}`;
1743
1890
  }
1744
1891
  return rtf;
1745
1892
  }
@@ -1955,7 +2102,7 @@ function restateAfterBlock(node, ctx) {
1955
2102
  const tag = tagOf(block);
1956
2103
  const formatted = FORMATTED_BLOCK_TAGS.has(tag) ||
1957
2104
  // (A container's own alignment or indent is its blocks': what is inside it had them.)
1958
- (['p', 'div'].includes(tag) && ((ctx.inTableCell ? paragraphLayout(block, ctx) : paragraphFormat(block, ctx)) !== '' || Array.from(block.children).some(isBlock))) ||
2105
+ (['p', 'div'].includes(tag) && ((ctx.inTableCell ? cellParagraphLayout(block, ctx) : paragraphFormat(block, ctx)) !== '' || Array.from(block.children).some(isBlock))) ||
1959
2106
  (HEADING_TAGS.has(tag) && headingLayout(block, ctx) !== '') ||
1960
2107
  (tag === 'pre' && ctx.indent + leftMarginTwips(block) > 0);
1961
2108
  return formatted ? `\\pard${inCell(ctx)}${cellAlign(ctx)}${liControl(ctx.indent)} ` : '';
@@ -2029,10 +2176,93 @@ function paragraphLayout(el, ctx) {
2029
2176
  }
2030
2177
  /**
2031
2178
  * A heading's layout: its alignment and left indent, and outside a table cell its right and
2032
- * first-line indents too, so a heading read from RTF with a hanging number goes back as it came.
2179
+ * first-line indents too, so a heading read from RTF with a hanging number goes back as it came,
2180
+ * and its spacing.
2033
2181
  */
2034
2182
  function headingLayout(el, ctx) {
2035
- return `${paragraphLayout(el, ctx)}${ctx.inTableCell ? '' : edgeIndents(el)}`;
2183
+ const spacing = spacingControls(el, 'all', tallestText(el, scaled(ctx, ALL_HEADING_SCALES[el.tagName.toLowerCase()] ?? 1)));
2184
+ return `${paragraphLayout(el, ctx)}${ctx.inTableCell ? spacing : `${edgeIndents(el)}${spacing}`}`;
2185
+ }
2186
+ /** A paragraph's layout in a table cell: its alignment, left indent and spacing. */
2187
+ function cellParagraphLayout(el, ctx) {
2188
+ return `${paragraphLayout(el, ctx)}${spacingControls(el, 'all', tallestText(el, ctx.size))}`;
2189
+ }
2190
+ /** The most a line is spaced by: ten lines, as the sanitizer lets through. */
2191
+ const MOST_LINES = 10;
2192
+ /**
2193
+ * The least a line is spaced by, as a share of the height of its text. Lines closer than this
2194
+ * are printed over each other: two lines of a diagnosis, there to be selected and not to be
2195
+ * read. A line height below it is no spacing a document has, and is not written (nor read, nor
2196
+ * kept by the sanitizer, nor set by the editor).
2197
+ */
2198
+ export const LEAST_LINES = 0.8;
2199
+ /**
2200
+ * The size of the tallest text an element holds, in half-points: its own under text of `base`,
2201
+ * and every size set on what is inside it.
2202
+ */
2203
+ function tallestText(el, base) {
2204
+ let tallest = sizeOf(el) ?? base;
2205
+ for (const inside of Array.from(el.querySelectorAll('[style*="font-size"], font[size]')))
2206
+ tallest = Math.max(tallest, sizeOf(inside) ?? 0);
2207
+ return tallest;
2208
+ }
2209
+ /**
2210
+ * The space before and after a paragraph, and between its lines, or nothing where the element
2211
+ * sets none:
2212
+ *
2213
+ * - `margin-top` and `margin-bottom` as \sbN and \saN. Zero writes nothing, which is what \pard
2214
+ * sets.
2215
+ * - `line-height` as a number or a percentage ("1.5", "150%") as \slN\slmult1, a multiple of a
2216
+ * line (240 to a line), and "1" too: it is what was chosen, and is read back as that. As a
2217
+ * length ("14pt") as \sl-N\slmult0, which is exactly that height.
2218
+ *
2219
+ * A height in RTF is not what it is in CSS. A line of exactly 14pt is cut off at 14pt by Word
2220
+ * and by every reader that does as it does: a picture in the line shows as a strip 14pt high,
2221
+ * and text taller than the line loses its top. In a browser the line grows around a picture,
2222
+ * and tall text is drawn over the line above. Words copied from a web page come with the line
2223
+ * height of that page ("line-height: 14px"), and a picture pasted with them was whole in the
2224
+ * editor and a strip in the RTF. So `tallest` is the size of the tallest text of the paragraph,
2225
+ * in half-points, and:
2226
+ *
2227
+ * - a paragraph that holds a picture has a height its lines have at least (\slN\slmult0, N
2228
+ * above zero), which is what the browser shows;
2229
+ * - lines closer than LEAST_LINES of the tallest text are not written at all, as a multiple or
2230
+ * as a height: they are printed over each other.
2231
+ *
2232
+ * With no `tallest` (the estimate, which knows no sizes) the longest form is given.
2233
+ *
2234
+ * `part` leaves out what is written on another paragraph: a picture's caption has the space
2235
+ * after it, the picture the space before. `lines` is the line spacing alone: a list item of
2236
+ * more than one paragraph has it on each, the space before on its first and after on its last.
2237
+ */
2238
+ function spacingControls(el, part = 'all', tallest) {
2239
+ const style = el.style;
2240
+ if (!style)
2241
+ return '';
2242
+ let out = '';
2243
+ const sb = part === 'after' || part === 'lines' ? null : lengthTwips(style.marginTop);
2244
+ if (sb)
2245
+ out += `\\sb${sb}`;
2246
+ const sa = part === 'before' || part === 'lines' ? null : lengthTwips(style.marginBottom);
2247
+ if (sa)
2248
+ out += `\\sa${sa}`;
2249
+ if (part !== 'all' && part !== 'lines')
2250
+ return out;
2251
+ const line = (style.lineHeight ?? '').trim().toLowerCase();
2252
+ const multiple = line.match(/^(\d+(?:\.\d+)?|\.\d+)(%?)$/);
2253
+ if (multiple) {
2254
+ const lines = parseFloat(multiple[1]) / (multiple[2] ? 100 : 1);
2255
+ if (lines >= LEAST_LINES && lines <= MOST_LINES)
2256
+ out += `\\sl${Math.round(lines * 240)}\\slmult1`;
2257
+ }
2258
+ else {
2259
+ const exact = lengthTwips(line);
2260
+ // (A half-point is ten twips.)
2261
+ if (!exact || (tallest !== undefined && exact < LEAST_LINES * tallest * 10))
2262
+ return out;
2263
+ out += tallest !== undefined && el.querySelector('img') ? `\\sl${exact}\\slmult0` : `\\sl-${exact}\\slmult0`;
2264
+ }
2265
+ return out;
2036
2266
  }
2037
2267
  /** \\riN for margin-right and \\fiN for text-indent, or nothing where the element sets none. */
2038
2268
  function edgeIndents(el) {
@@ -2045,7 +2275,7 @@ function edgeIndents(el) {
2045
2275
  * indent of the blocks around it plus its own margin.
2046
2276
  */
2047
2277
  function paragraphFormat(el, ctx) {
2048
- return `${alignOf(el, ctx)}${paragraphControls(el, ctx.indent + leftMarginTwips(el))}`;
2278
+ return `${alignOf(el, ctx)}${paragraphControls(el, ctx.indent + leftMarginTwips(el), tallestText(el, ctx.size))}`;
2049
2279
  }
2050
2280
  /** The alignment a container hands to the blocks inside it: its own, or the one it was handed. */
2051
2281
  function inheritedAlign(el, ctx) {
@@ -2064,13 +2294,14 @@ function inheritedAlign(el, ctx) {
2064
2294
  * | margin-right: 0.5in | \ri720 |
2065
2295
  * | text-indent: -1.75in | \fi-2520 |
2066
2296
  * | margin-top: 5pt / margin-bottom: 5pt | \sb100 / \sa100 |
2297
+ * | line-height: 1.5 (or 150%) / line-height: 14pt | \sl360\slmult1 / \sl-280\slmult0 |
2067
2298
  * | break-after: avoid, or page-break-after: avoid | \keepn |
2068
2299
  *
2069
2300
  * CSS has no absolute tab stop, hence the data- attribute. A value that cannot be read writes
2070
2301
  * nothing, and so does zero, which is what \pard already sets. Not written inside a table cell,
2071
2302
  * where the cell declares its own paragraph.
2072
2303
  */
2073
- function paragraphControls(el, leftTwips) {
2304
+ function paragraphControls(el, leftTwips, tallest) {
2074
2305
  let out = '';
2075
2306
  const stops = (el.getAttribute('data-rtf-tab-stops') ?? '')
2076
2307
  .split(',')
@@ -2083,12 +2314,7 @@ function paragraphControls(el, leftTwips) {
2083
2314
  if (!style)
2084
2315
  return out;
2085
2316
  out += edgeIndents(el);
2086
- const sb = lengthTwips(style.marginTop);
2087
- if (sb)
2088
- out += `\\sb${sb}`;
2089
- const sa = lengthTwips(style.marginBottom);
2090
- if (sa)
2091
- out += `\\sa${sa}`;
2317
+ out += spacingControls(el, 'all', tallest);
2092
2318
  const keep = (prop) => style.getPropertyValue(prop).trim() === 'avoid';
2093
2319
  if (keep('break-after') || keep('page-break-after'))
2094
2320
  out += '\\keepn';
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 { cssFontFamily, fontChoices, fontKey, linkTarget, sameFontList } from './rtf-writer.js';
27
+ import { cssFontFamily, fontChoices, fontKey, hardToReadOnWhite, LEAST_LINES, linkTarget, NO_BACKGROUND, parseColor, 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([
@@ -373,6 +373,23 @@ function fontPxAround(el, known) {
373
373
  }
374
374
  return px;
375
375
  }
376
+ /**
377
+ * Whether a line height puts the lines of a paragraph on top of each other: less than
378
+ * LEAST_LINES of the height of its text, as a number ("0.2"), a percentage, or a length
379
+ * ("1px", which pages and mail put on what holds a picture). Two lines so close are one line
380
+ * of ink, with the paragraph after them printed over both; the words are in the document, and
381
+ * in the RTF, and nobody can read them.
382
+ */
383
+ function linesOverlap(value, fontPx) {
384
+ const match = /^\s*(\d*\.?\d+(?:e[+-]?\d+)?)([a-z%]*)\s*$/i.exec(value);
385
+ if (!match)
386
+ return false;
387
+ const unit = match[2].toLowerCase();
388
+ if (unit === '' || unit === '%')
389
+ return Number(match[1]) / (unit ? 100 : 1) < LEAST_LINES;
390
+ const px = lengthPx(match[1], unit, fontPx);
391
+ return px !== null && px < LEAST_LINES * fontPx;
392
+ }
376
393
  /** Whether a property that places or sizes an element has a value a document would give it. */
377
394
  function sizeAllowed(name, value, tag, fontPx) {
378
395
  if (name === 'margin-left' && (tag === 'ul' || tag === 'ol'))
@@ -390,7 +407,7 @@ function sizeAllowed(name, value, tag, fontPx) {
390
407
  if (name === 'display')
391
408
  return DISPLAY_VALUES.has(value.trim().toLowerCase());
392
409
  if (name === 'line-height')
393
- return within(value, { most: 400, mostPercent: 1000, mostNumber: 10 }, fontPx);
410
+ return within(value, { most: 400, mostPercent: 1000, mostNumber: 10 }, fontPx) && !linesOverlap(value, fontPx);
394
411
  if (/^border.*width$/.test(name) || name === 'border-spacing' || name === 'text-decoration-thickness')
395
412
  return within(value, { most: 100 }, fontPx);
396
413
  if (name.endsWith('tab-size'))
@@ -606,6 +623,68 @@ function sanitizeAttributes(el, tag, fonts, idTaken, keep) {
606
623
  }
607
624
  sanitizeStyle(el, tag, fonts, keep);
608
625
  }
626
+ /** A picture as a background, in a style: one that is loaded, or one that is drawn (a gradient). */
627
+ const BACKGROUND_PICTURE = /(gradient|url|image|image-set|cross-fade|element|paint)\s*\(/i;
628
+ /**
629
+ * Whether an element is given a picture or a gradient to stand on: by its style, or by the
630
+ * `background` older pages and mail put on a table and its cells. Asked before the element is
631
+ * made safe, which takes that away: no picture is loaded for a document, and a gradient is not
632
+ * a thing an RTF has.
633
+ */
634
+ function hasBackgroundPicture(el) {
635
+ if ((el.getAttribute('background') ?? '').trim() !== '')
636
+ return true;
637
+ // From the attribute as it is written: a browser that does not read a gradient the way it
638
+ // is spelled there ("-webkit-gradient(…)") lists nothing for it.
639
+ return declarations(el.getAttribute('style') ?? '').some((declaration) => (declaration.name === 'background' || declaration.name === 'background-image') && BACKGROUND_PICTURE.test(declaration.text));
640
+ }
641
+ /** Whether an element has a background color of its own. */
642
+ function hasShade(el) {
643
+ const color = (el.style?.backgroundColor ?? '').trim().toLowerCase();
644
+ return color !== '' && !NO_BACKGROUND.test(color);
645
+ }
646
+ /**
647
+ * Words left on the white of the page are left readable. `bare` holds the elements whose
648
+ * picture or gradient was taken away, with no color behind them: light words on one of those
649
+ * (white on a dark gradient) would be white on white, in the editor and in the RTF, there for
650
+ * a reader to select and for nobody to see. Their color is taken off with the background it
651
+ * was chosen for. A color with a background color behind it stays: that is kept, and the
652
+ * writer knows what to do with the two. Called for an element once it is made safe, the
653
+ * elements it is in before it.
654
+ */
655
+ function leaveReadable(el, pictured, bare, root) {
656
+ /** What the words of an element stand on now: a color, a background that is gone, or the page. */
657
+ const behind = (from) => {
658
+ for (let at = from; at; at = at.parentElement) {
659
+ if (hasShade(at))
660
+ return 'shade';
661
+ if (bare.has(at))
662
+ return 'bare';
663
+ if (at === root)
664
+ break;
665
+ }
666
+ return null;
667
+ };
668
+ if (pictured && behind(el) !== 'shade')
669
+ bare.add(el);
670
+ const light = (color) => {
671
+ const read = color ? (parseColor(color) ?? parseColor(`#${color.trim()}`)) : null;
672
+ return read !== null && hardToReadOnWhite(read);
673
+ };
674
+ const styled = light(el.style?.color);
675
+ const attribute = el.tagName === 'FONT' && light(el.getAttribute('color'));
676
+ if ((!styled && !attribute) || behind(el) !== 'bare')
677
+ return;
678
+ if (attribute)
679
+ el.removeAttribute('color');
680
+ if (styled) {
681
+ el.style.removeProperty('color');
682
+ if (el.style.cssText)
683
+ el.setAttribute('style', el.style.cssText);
684
+ else
685
+ el.removeAttribute('style');
686
+ }
687
+ }
609
688
  /**
610
689
  * Whether an element is a formula's copy for a screen reader, beside the same formula written
611
690
  * as text: KaTeX writes both, and its stylesheet hides this one. Kept, "30%" read "30%30%".
@@ -628,6 +707,8 @@ function isReadAloudCopy(el) {
628
707
  export function sanitizeTree(root, only, idTaken, keep, wordsLeft, leftOut) {
629
708
  let changed = false;
630
709
  const fonts = new Map();
710
+ /** The elements whose background picture was taken away: see leaveReadable. */
711
+ const bare = new Set();
631
712
  /** The words of the last element that left its words, where they are still in the document. */
632
713
  let lastKept = null;
633
714
  /** One element made safe; returns whether it was taken out or changed. */
@@ -661,7 +742,9 @@ export function sanitizeTree(root, only, idTaken, keep, wordsLeft, leftOut) {
661
742
  return true;
662
743
  }
663
744
  const before = el.attributes.length + (el.getAttribute('style') ?? '') + (el.getAttribute('href') ?? '') + (el.getAttribute('width') ?? '') + (el.getAttribute('height') ?? '');
745
+ const pictured = hasBackgroundPicture(el);
664
746
  sanitizeAttributes(el, tag, fonts, idTaken, keep);
747
+ leaveReadable(el, pictured, bare, root);
665
748
  return before !== el.attributes.length + (el.getAttribute('style') ?? '') + (el.getAttribute('href') ?? '') + (el.getAttribute('width') ?? '') + (el.getAttribute('height') ?? '');
666
749
  };
667
750
  for (const el of Array.from(root.querySelectorAll('*'))) {
package/dist/utils.js CHANGED
@@ -559,10 +559,26 @@ function listToMarkdown(list, ordered, ctx, out) {
559
559
  let shownNumber = listStart(list);
560
560
  let items = [];
561
561
  let loose = [];
562
+ /**
563
+ * The mark after a number: "1." or "1)". Markdown takes a list's first number and counts on
564
+ * from it, whatever the items after it say: "1. 7. 8." is shown as 1, 2, 3, and a list of
565
+ * its own that follows another is counted on with it. The other mark is what starts a new
566
+ * list, from the number it is written with: "1. 7) 8)" is shown as 1, 7, 8.
567
+ */
568
+ let mark = '.';
569
+ /** Whether a number has been written with this mark, in the run of items being written. */
570
+ let counting = false;
571
+ const otherMark = () => {
572
+ mark = mark === '.' ? ')' : '.';
573
+ };
562
574
  const endItems = () => {
563
- if (items.length)
575
+ if (items.length) {
564
576
  out.blocks.push(items.map((item) => listItem(item.marker, item.blocks.join('\n\n'))).join('\n'));
577
+ if (counting)
578
+ out.numbered = { at: out.blocks.length - 1, mark };
579
+ }
565
580
  items = [];
581
+ counting = false;
566
582
  };
567
583
  const endLoose = () => {
568
584
  const blocks = blocksOf(loose, ctx);
@@ -593,8 +609,30 @@ function listToMarkdown(list, ordered, ctx, out) {
593
609
  blocks.unshift(label);
594
610
  }
595
611
  // An item whose text is hidden shows no marker either.
596
- if (blocks.length || !inside.unseen)
597
- items.push({ marker: ordered && !label ? `${number++}. ` : '- ', blocks });
612
+ if (blocks.length || !inside.unseen) {
613
+ if (ordered && !label) {
614
+ // An item with a number of its own (`value`) has it here too, and those
615
+ // after it count on from it, as the screen and the RTF have them. (It was
616
+ // written by its place in the list: "7." in the RTF, and "2." here.)
617
+ const own = Math.max(0, Math.min(itemNumber(node, number), 999_999_999));
618
+ if (counting && own !== number)
619
+ otherMark();
620
+ // And a list that follows another starts at its own number.
621
+ else if (!counting && items.length === 0 && out.numbered?.at === out.blocks.length - 1 && out.numbered.mark === mark)
622
+ otherMark();
623
+ number = own;
624
+ counting = true;
625
+ items.push({ marker: `${number++}${mark} `, blocks });
626
+ }
627
+ else {
628
+ // (A bullet between numbers ends their list: the next number starts one, at
629
+ // the number the screen has for it, which counts the bullet too.)
630
+ counting = false;
631
+ if (label)
632
+ number = Math.max(0, Math.min(shownNumber, 999_999_999));
633
+ items.push({ marker: '- ', blocks });
634
+ }
635
+ }
598
636
  else if (label)
599
637
  blocks.shift();
600
638
  }