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.
@@ -11,8 +11,22 @@
11
11
  *
12
12
  * \cb (character background) is silently ignored on import.
13
13
  */
14
- import { HEADING_SCALE, PRE_SCALE, LINK_COLOR, DEFAULT_FONT_FAMILY, fontChoices, fontKey, isMonospaceFontName, linkTarget, normalizeFontSize, hardToReadOnWhite } from './rtf-writer.js';
15
- import { letterReadings, listTypeAttribute } from './list-markers.js';
14
+ import { HEADING_SCALE, PRE_SCALE, LINK_COLOR, DEFAULT_FONT_FAMILY, fontChoices, fontKey, isMonospaceFontName, linkTarget, normalizeFontSize, hardToReadOnWhite, LEAST_LINES } from './rtf-writer.js';
15
+ import { LEAST_MARKER_GAP, MOST_MARKER_GAP, letterReadings, listTypeAttribute } from './list-markers.js';
16
+ /** The lines RTF names that CSS has too; any other is a plain line. */
17
+ const BORDER_LINE_CSS = new Map(Object.entries({ brdrdb: 'double', brdrdot: 'dotted', brdrdash: 'dashed', brdrdashsm: 'dashed', brdrdashd: 'dashed', brdrdashdd: 'dashed' }));
18
+ /**
19
+ * A cell's borders as CSS, which the writer reads back as the same: "border:1px solid;" where
20
+ * all four are one, else each side that has one. A width is given in px, 15 twips each, as
21
+ * the writer counts them.
22
+ */
23
+ function bordersStyle(borders) {
24
+ const css = (b) => b ? `${Math.round((Math.max(1, Math.min(b.twips, 75)) / 15) * 100) / 100}px ${b.line}${b.color ? ` ${b.color}` : ''}` : '';
25
+ const sides = [css(borders.t), css(borders.r), css(borders.b), css(borders.l)];
26
+ if (sides[0] && sides.every((side) => side === sides[0]))
27
+ return `border:${sides[0]};`;
28
+ return ['top', 'right', 'bottom', 'left'].map((name, i) => (sides[i] ? `border-${name}:${sides[i]};` : '')).join('');
29
+ }
16
30
  // ── Highlight palette (RTF \highlight 1-16) ──
17
31
  const HIGHLIGHT_COLORS = {
18
32
  1: '#000000', // Black
@@ -73,6 +87,14 @@ const ONLY_SPACES = /^[ \t\r\n\f]*$/;
73
87
  const RULE_DASHES = '\u2014'.repeat(20);
74
88
  /** A hanging indent of this many twips is the one the writer gives a list item (\fi-360). */
75
89
  const LIST_HANG = 360;
90
+ /**
91
+ * Whether a paragraph hangs as a list item does: its first line out by a gap a list can have
92
+ * (see markerGapTwips), and no further than the page. A list hung by any such gap is read as a
93
+ * list with that gap, which is written back the same.
94
+ */
95
+ function hangsAsItem(first, left) {
96
+ return -first >= LEAST_MARKER_GAP && -first <= MOST_MARKER_GAP && left >= -first;
97
+ }
76
98
  /** The longest number a numbered list item is read with. */
77
99
  const MAX_LIST_NUMBER_DIGITS = 9;
78
100
  /** Each level of a list is indented this much further (\li720). */
@@ -721,6 +743,49 @@ function resetIndents(state) {
721
743
  state.leftIndent = 0;
722
744
  state.rightIndent = 0;
723
745
  state.firstLineIndent = 0;
746
+ state.spaceBefore = 0;
747
+ state.spaceAfter = 0;
748
+ state.lineSpacing = 0;
749
+ state.lineMultiple = false;
750
+ }
751
+ /** The most space before or after a paragraph that is read: a page's height. More is a mistake in the file. */
752
+ const MOST_SPACE_TWIPS = 15840;
753
+ /**
754
+ * A paragraph's spacing as CSS, which the writer reads back as the same \sb, \sa and \sl:
755
+ * "margin-top:6pt;margin-bottom:6pt;line-height:1.5". A height the lines have at least (\sl
756
+ * above zero with no \slmult1) is not a thing CSS has, and is left to the screen.
757
+ */
758
+ function spacingStyle(block, part = 'all') {
759
+ const parts = [];
760
+ const space = (twips) => twipsToPt(Math.min(twips, MOST_SPACE_TWIPS));
761
+ if (part !== 'after' && block.before > 0)
762
+ parts.push(`margin-top:${space(block.before)}`);
763
+ if (part !== 'before' && block.after > 0)
764
+ parts.push(`margin-bottom:${space(block.after)}`);
765
+ if (part === 'all') {
766
+ // Lines closer than LEAST_LINES of their text are printed over each other, and are
767
+ // not read: "\sl-20" put two lines of a diagnosis on top of each other, and the
768
+ // paragraph after them on both. (A half-point is ten twips.)
769
+ const tallest = block.runs.reduce((most, run) => Math.max(most, run.fmt.fontSize || 0), 0);
770
+ if (block.lineMultiple && block.line >= LEAST_LINES * 240 && block.line <= 2400)
771
+ parts.push(`line-height:${Math.round((block.line / 240) * 100) / 100}`);
772
+ else if (!block.lineMultiple && block.line < 0 && block.line >= -MOST_SPACE_TWIPS && -block.line >= LEAST_LINES * tallest * 10)
773
+ parts.push(`line-height:${twipsToPt(-block.line)}`);
774
+ }
775
+ return parts.join(';');
776
+ }
777
+ /** A style added to the element an HTML string opens with: `<figure>` or `<figure style="…">`. */
778
+ function withStyle(html, style) {
779
+ if (!style)
780
+ return html;
781
+ const open = html.match(/^<[a-z0-9]+( style="([^"]*)")?/);
782
+ if (!open)
783
+ return html;
784
+ const tag = open[0].slice(0, open[0].length - (open[1]?.length ?? 0));
785
+ // (What it sets replaces what the element had of the same name.)
786
+ const named = new Set(style.split(';').map((declaration) => declaration.split(':')[0]));
787
+ const kept = (open[2] ?? '').split(';').filter((declaration) => declaration && !named.has(declaration.split(':')[0]));
788
+ return `${tag} style="${[...kept, style].join(';')}"${html.slice(open[0].length)}`;
724
789
  }
725
790
  /**
726
791
  * A paragraph's indents as CSS, in points (20 twips), which the writer reads back as the same
@@ -849,6 +914,9 @@ export function rtfToHtml(rtfString, options = {}) {
849
914
  let currentRowDefs = [];
850
915
  /** The definition of the row before, which a row with no \trowd of its own repeats. */
851
916
  let lastRowDefs = [];
917
+ /** The row's \trgaph, and the row before's, which a row with no \trowd of its own repeats. */
918
+ let rowGaph = null;
919
+ let lastRowGaph = null;
852
920
  let pendingDef = newCellDef();
853
921
  /** The side a \clbrdrX just named, until a border type (\brdrs...) confirms or \brdrnone clears it. */
854
922
  let pendingSide = null;
@@ -859,15 +927,21 @@ export function rtfToHtml(rtfString, options = {}) {
859
927
  let cellBorders = { b: false, other: false, bare: false };
860
928
  /** The side whose border type was read last, which a \brdrw or \brdrcf after it belongs to. */
861
929
  let borderSide = null;
930
+ /** {\*\inkth} was read in the cell being read: it is a header cell. */
931
+ let cellMarkedHeader = false;
932
+ /** How much of the cell had been read when {\*\inkcap} marked what follows as a caption. */
933
+ let captionAt = null;
862
934
  let inTableCell = false;
863
935
  /** \par seen in a table cell since its last text: line breaks owed if more text follows. */
864
936
  let cellBreaks = 0;
937
+ /** The spacing of the paragraph each of those paragraph marks ended; null for a line that is no paragraph's (a row of a table in the cell). */
938
+ let cellBreakSpacing = [];
865
939
  /** \lastrow seen in the definition of the row being read: its \row ends the table. */
866
940
  let lastRow = false;
867
941
  /** \nestcell seen: a tab is owed if more text follows on the line. */
868
942
  let nestTabPending = false;
869
943
  function newCellDef() {
870
- return { right: 0, header: false, vmgf: false, vmrg: false, hmgf: false, hmrg: false, shade: '' };
944
+ return { right: 0, header: false, vmgf: false, vmrg: false, hmgf: false, hmrg: false, shade: '', borders: {}, edge: null, drawn: null };
871
945
  }
872
946
  // The document is the first group. A byte-order mark or blank lines before it (a file saved
873
947
  // by a tool that adds them) do not make it something else: with those the color and font
@@ -948,6 +1022,10 @@ export function rtfToHtml(rtfString, options = {}) {
948
1022
  leftIndent: 0,
949
1023
  rightIndent: 0,
950
1024
  firstLineIndent: 0,
1025
+ spaceBefore: 0,
1026
+ spaceAfter: 0,
1027
+ lineSpacing: 0,
1028
+ lineMultiple: false,
951
1029
  };
952
1030
  }
953
1031
  const stateStack = [defaultState()];
@@ -1091,6 +1169,7 @@ export function rtfToHtml(rtfString, options = {}) {
1091
1169
  /** An empty paragraph to read into. */
1092
1170
  function newRuns() {
1093
1171
  runs = [];
1172
+ captionAt = null;
1094
1173
  onlyText = true;
1095
1174
  contentAlign = 'left';
1096
1175
  marker = null;
@@ -1137,11 +1216,15 @@ export function rtfToHtml(rtfString, options = {}) {
1137
1216
  }
1138
1217
  if (cellBreaks > 0) {
1139
1218
  const count = cellBreaks;
1219
+ const spacings = cellBreakSpacing;
1140
1220
  cellBreaks = 0;
1221
+ cellBreakSpacing = [];
1141
1222
  if (inTableCell) {
1142
1223
  // A paragraph mark inside a cell: the cell's text goes on, on a new line.
1143
- for (let k = 0; k < count; k++)
1224
+ for (let k = 0; k < count; k++) {
1144
1225
  pushHtml('br', '<br>', state);
1226
+ runs[runs.length - 1].spacing = spacings[k] ?? null;
1227
+ }
1145
1228
  }
1146
1229
  else {
1147
1230
  // \pard has left the table without a \cell: what was read is a paragraph.
@@ -1175,15 +1258,43 @@ export function rtfToHtml(rtfString, options = {}) {
1175
1258
  beforeContent(state);
1176
1259
  pushHtml(kind, html, state);
1177
1260
  }
1261
+ /** The spacing the paragraph being read has. */
1262
+ function spacingHere(state) {
1263
+ return { before: state.spaceBefore, after: state.spaceAfter, line: state.lineSpacing, lineMultiple: state.lineMultiple };
1264
+ }
1265
+ /**
1266
+ * What a table cell holds, as HTML. Its paragraphs are lines of the cell, a <br> apart; where
1267
+ * one of them is spaced (\sa, \sb, \sl, as Word writes a cell's paragraphs), each is a
1268
+ * paragraph of its own with its spacing. `last` is the spacing of the last one.
1269
+ */
1270
+ function cellHtml(last) {
1271
+ const paragraphs = [];
1272
+ let from = 0;
1273
+ runs.forEach((run, i) => {
1274
+ if (run.type !== 'html' || !run.spacing)
1275
+ return;
1276
+ paragraphs.push({ runs: runs.slice(from, i), spacing: run.spacing });
1277
+ from = i + 1;
1278
+ });
1279
+ paragraphs.push({ runs: runs.slice(from), spacing: last });
1280
+ const styles = paragraphs.map((paragraph) => spacingStyle({ ...paragraph.spacing, runs: paragraph.runs }));
1281
+ if (styles.every((style) => !style))
1282
+ return trimSpaces(renderRuns(runs));
1283
+ return paragraphs
1284
+ .map((paragraph, k) => `<p${styles[k] ? ` style="${styles[k]}"` : ''}>${trimSpaces(renderRuns(paragraph.runs)) || '<br>'}</p>`)
1285
+ .join('');
1286
+ }
1178
1287
  /** \par, where it ends a paragraph and where, in a table cell, it starts a new line. */
1179
1288
  function paragraphMark(state) {
1180
1289
  if (inTableCell) {
1181
1290
  cellBreaks++;
1291
+ cellBreakSpacing.push(spacingHere(state));
1182
1292
  }
1183
1293
  else {
1184
1294
  // Paragraph marks from a cell that \pard has since left end paragraphs too.
1185
1295
  for (; cellBreaks > 0; cellBreaks--)
1186
1296
  flushParagraph();
1297
+ cellBreakSpacing = [];
1187
1298
  flushParagraph();
1188
1299
  }
1189
1300
  }
@@ -1215,7 +1326,25 @@ export function rtfToHtml(rtfString, options = {}) {
1215
1326
  }
1216
1327
  appendText(text.slice(from), state);
1217
1328
  }
1218
- /** The text of the line being read, back to the last line break, if text is all it holds. */
1329
+ /**
1330
+ * The cell being read as the figure it is, where it holds one picture and then the caption
1331
+ * the writer marked ({\*\inkcap}): pictures side by side are a row of such cells, each
1332
+ * picture with its own caption. Null for any other cell, which is read as its lines.
1333
+ */
1334
+ function cellFigure() {
1335
+ if (captionAt == null || captionAt < 1)
1336
+ return null;
1337
+ const before = runs.slice(0, captionAt).filter((run) => !(run.type === 'text' && ONLY_SPACES.test(run.text)));
1338
+ if (before.length !== 1 || before[0].type !== 'html' || before[0].kind !== 'img')
1339
+ return null;
1340
+ let from = captionAt;
1341
+ while (from < runs.length && runs[from].type === 'html' && runs[from].kind === 'br')
1342
+ from++;
1343
+ const caption = stripWrappingEm(trimSpaces(renderRuns(runs.slice(from))));
1344
+ if (!caption)
1345
+ return null;
1346
+ return `<figure>${trimSpaces(renderRuns(before))}<figcaption>${caption}</figcaption></figure>`;
1347
+ }
1219
1348
  /** The cell being read, with the colors left out that cannot be read on white; undefined where it has none. */
1220
1349
  function cellOnWhite() {
1221
1350
  if (!runs.some((run) => run.fmt.color && !run.fmt.background && !readsOnWhite(run.fmt.color)))
@@ -1262,8 +1391,7 @@ export function rtfToHtml(rtfString, options = {}) {
1262
1391
  // the tab after it stays a tab.
1263
1392
  const lettered = opensParagraph && lead != null ? lead.match(LETTER_MARKER) : null;
1264
1393
  if (lettered &&
1265
- state.firstLineIndent === -LIST_HANG &&
1266
- state.leftIndent >= LIST_HANG &&
1394
+ hangsAsItem(state.firstLineIndent, state.leftIndent) &&
1267
1395
  state.rightIndent === 0 &&
1268
1396
  (state.align || 'left') === 'left' &&
1269
1397
  letterReadings(lettered[1]).length > 0) {
@@ -1302,7 +1430,7 @@ export function rtfToHtml(rtfString, options = {}) {
1302
1430
  }
1303
1431
  else {
1304
1432
  placed.push({
1305
- html: cellHtml, align: cell.align, def,
1433
+ html: cellHtml, align: cell.align, header: def.header || cell.header === true, def,
1306
1434
  left: prevRight, right: Math.max(def.right, prevRight),
1307
1435
  start: 0, end: 0, rowspan: 1, merged: false
1308
1436
  });
@@ -1366,6 +1494,26 @@ export function rtfToHtml(rtfString, options = {}) {
1366
1494
  }
1367
1495
  }
1368
1496
  }
1497
+ // Pictures side by side with a set gap: one row, a picture in each cell and an empty
1498
+ // cell between each two, written with no space inside a cell (\trgaph0) and nothing
1499
+ // drawn or shaded. It is read at its own widths, as it was written, and not stretched
1500
+ // across the page: what was set is the distance between the pictures. (See
1501
+ // picture-rows.ts.) A table that only looks like one, with borders, shading, or the
1502
+ // space a reader puts inside its cells, is read as the table it is.
1503
+ const plain = rows.length === 1 && rows[0].gaph === 0 && rows[0].defs.every((def) => !def.shade && Object.keys(def.borders).length === 0);
1504
+ const only = plain && placedRows.length === 1 ? placedRows[0] : null;
1505
+ const onePicture = (html) => /^<(figure|img)\b/.test(html) && html.split('<img').length === 2;
1506
+ if (only &&
1507
+ only.length >= 3 &&
1508
+ only.length % 2 === 1 &&
1509
+ only.every((cell, i) => !cell.merged && !cell.header && cell.rowspan === 1 && cell.end === cell.start && cell.right > cell.left && (i % 2 === 0 ? onePicture(cell.html) : cell.html === ''))) {
1510
+ const cells = only.map((cell) => `<td style="padding:0;width:${(cell.right - cell.left) / 20}pt">${cell.html}</td>`).join('');
1511
+ blocks.push({ kind: 'table', html: `<table style="border-collapse:collapse;margin:4px 0"><tr>${cells}</tr></table>` });
1512
+ for (const aside of tableAsides)
1513
+ blocks.push(aside);
1514
+ tableAsides = [];
1515
+ return;
1516
+ }
1369
1517
  const total = edges[edges.length - 1] || 1;
1370
1518
  // A cell's width is the difference of where it ends and where it starts, each as a
1371
1519
  // share of the table rounded to a hundredth of a percent. Written that way the widths
@@ -1378,12 +1526,15 @@ export function rtfToHtml(rtfString, options = {}) {
1378
1526
  for (const cell of row) {
1379
1527
  if (cell.merged)
1380
1528
  continue;
1381
- const tag = cell.def.header ? 'th' : 'td';
1529
+ const tag = cell.header ? 'th' : 'td';
1382
1530
  const pct = (shareAt(cell.right) - shareAt(cell.left)).toFixed(2).replace(/0$/, '');
1383
1531
  const alignStyle = cell.align !== 'left' ? `;text-align:${cell.align}` : '';
1532
+ // (A header cell says how it is aligned, left too: a browser centers one that does not.)
1384
1533
  const style = cell.def.header
1385
1534
  ? `border-bottom:1px solid;padding:2px 6px;text-align:${cell.align};width:${pct}%`
1386
- : `padding:2px 6px;width:${pct}%${alignStyle}`;
1535
+ : cell.header
1536
+ ? `${bordersStyle(cell.def.borders)}padding:2px 6px;text-align:${cell.align};width:${pct}%`
1537
+ : `${bordersStyle(cell.def.borders)}padding:2px 6px;width:${pct}%${alignStyle}`;
1387
1538
  const colspan = cell.end > cell.start ? ` colspan="${cell.end - cell.start + 1}"` : '';
1388
1539
  const rowspan = cell.rowspan > 1 ? ` rowspan="${cell.rowspan}"` : '';
1389
1540
  html += `<${tag}${colspan}${rowspan} style="${style}">${cell.html}</${tag}>`;
@@ -1412,6 +1563,10 @@ export function rtfToHtml(rtfString, options = {}) {
1412
1563
  left: state.leftIndent,
1413
1564
  right: state.rightIndent,
1414
1565
  first: state.firstLineIndent,
1566
+ before: state.spaceBefore,
1567
+ after: state.spaceAfter,
1568
+ line: state.lineSpacing,
1569
+ lineMultiple: state.lineMultiple,
1415
1570
  caption: paragraphIsCaption,
1416
1571
  marker,
1417
1572
  inTable: inTableCell
@@ -1474,14 +1629,14 @@ export function rtfToHtml(rtfString, options = {}) {
1474
1629
  const saved = {
1475
1630
  blocks, runs, onlyText, marker, paragraphHasListMarker, paragraphIsCaption, paragraphAsides,
1476
1631
  tableAsides, tableRows, currentRowCells, currentRowDefs, lastRowDefs, pendingDef, pendingSide,
1477
- cellBorders, borderSide, inTableCell, cellBreaks, contentAlign, lastRow, nestTabPending,
1632
+ cellBorders, borderSide, cellMarkedHeader, captionAt, inTableCell, cellBreaks, cellBreakSpacing, contentAlign, lastRow, nestTabPending,
1478
1633
  pendingHighSurrogate, pendingUnicodeSkip, noteNumber, unshown, stateBase
1479
1634
  };
1480
1635
  restore = () => {
1481
1636
  ({
1482
1637
  blocks, runs, onlyText, marker, paragraphHasListMarker, paragraphIsCaption, paragraphAsides,
1483
1638
  tableAsides, tableRows, currentRowCells, currentRowDefs, lastRowDefs, pendingDef, pendingSide,
1484
- cellBorders, borderSide, inTableCell, cellBreaks, contentAlign, lastRow, nestTabPending,
1639
+ cellBorders, borderSide, cellMarkedHeader, captionAt, inTableCell, cellBreaks, cellBreakSpacing, contentAlign, lastRow, nestTabPending,
1485
1640
  pendingHighSurrogate, pendingUnicodeSkip, noteNumber, unshown, stateBase
1486
1641
  } = saved);
1487
1642
  };
@@ -1499,8 +1654,10 @@ export function rtfToHtml(rtfString, options = {}) {
1499
1654
  pendingSide = null;
1500
1655
  cellBorders = { b: false, other: false, bare: false };
1501
1656
  borderSide = null;
1657
+ cellMarkedHeader = false;
1502
1658
  inTableCell = false;
1503
1659
  cellBreaks = 0;
1660
+ cellBreakSpacing = [];
1504
1661
  lastRow = false;
1505
1662
  nestTabPending = false;
1506
1663
  pendingHighSurrogate = 0;
@@ -1626,12 +1783,18 @@ export function rtfToHtml(rtfString, options = {}) {
1626
1783
  else if (dest?.word === 'inkcap') {
1627
1784
  // Marks the paragraph that follows as a picture caption.
1628
1785
  paragraphIsCaption = true;
1786
+ captionAt = runs.length;
1787
+ }
1788
+ else if (dest?.word === 'inkth') {
1789
+ // Marks the cell it is in as a header cell.
1790
+ cellMarkedHeader = true;
1629
1791
  }
1630
1792
  else if (dest?.word === 'nesttableprops') {
1631
1793
  // Word ends each row of a table inside a cell with this group, which holds
1632
1794
  // the row's definition and its \nestrow.
1633
1795
  nestTabPending = false;
1634
1796
  cellBreaks++;
1797
+ cellBreakSpacing.push(null);
1635
1798
  }
1636
1799
  continue;
1637
1800
  }
@@ -1738,6 +1901,18 @@ export function rtfToHtml(rtfString, options = {}) {
1738
1901
  case 'fi':
1739
1902
  state.firstLineIndent = p ?? 0;
1740
1903
  break;
1904
+ case 'sb':
1905
+ state.spaceBefore = Math.max(0, p ?? 0);
1906
+ break;
1907
+ case 'sa':
1908
+ state.spaceAfter = Math.max(0, p ?? 0);
1909
+ break;
1910
+ case 'sl':
1911
+ state.lineSpacing = p ?? 0;
1912
+ break;
1913
+ case 'slmult':
1914
+ state.lineMultiple = p === 1;
1915
+ break;
1741
1916
  case 'par':
1742
1917
  case 'sect':
1743
1918
  // \sect ends a section, and with it the paragraph: "A\sect B" is two lines.
@@ -1747,6 +1922,7 @@ export function rtfToHtml(rtfString, options = {}) {
1747
1922
  // A row's definition, not its start: Word writes the definition before the
1748
1923
  // cells and again before \row, so the cells read so far are kept.
1749
1924
  currentRowDefs = [];
1925
+ rowGaph = null;
1750
1926
  pendingDef = newCellDef();
1751
1927
  pendingSide = null;
1752
1928
  borderSide = null;
@@ -1757,25 +1933,37 @@ export function rtfToHtml(rtfString, options = {}) {
1757
1933
  lastRow = true;
1758
1934
  break;
1759
1935
  case 'trgaph':
1936
+ rowGaph = p ?? null;
1937
+ pendingSide = null;
1938
+ pendingDef.edge = null;
1939
+ break;
1760
1940
  case 'trkeep':
1761
1941
  case 'trleft':
1762
1942
  case 'trhdr':
1763
1943
  pendingSide = null;
1944
+ pendingDef.edge = null;
1764
1945
  break; // table formatting, ignored
1765
1946
  case 'clbrdrr':
1766
1947
  case 'clbrdrl':
1767
1948
  case 'clbrdrt':
1768
1949
  pendingSide = 'other';
1769
1950
  borderSide = null;
1951
+ pendingDef.edge = w === 'clbrdrr' ? 'r' : w === 'clbrdrl' ? 'l' : 't';
1952
+ pendingDef.drawn = null;
1770
1953
  break;
1771
1954
  case 'clbrdrb':
1772
1955
  pendingSide = 'b';
1773
1956
  borderSide = null;
1957
+ pendingDef.edge = 'b';
1958
+ pendingDef.drawn = null;
1774
1959
  break;
1775
1960
  case 'brdrnone':
1776
1961
  case 'brdrnil':
1962
+ case 'brdrtbl':
1777
1963
  pendingSide = null;
1778
1964
  borderSide = null;
1965
+ pendingDef.edge = null;
1966
+ pendingDef.drawn = null;
1779
1967
  break;
1780
1968
  case 'brdrw':
1781
1969
  case 'brdrcf':
@@ -1784,6 +1972,20 @@ export function rtfToHtml(rtfString, options = {}) {
1784
1972
  // without one. The writer's header mark is the bare \clbrdrb\brdrs.
1785
1973
  if (borderSide === 'b')
1786
1974
  cellBorders.bare = false;
1975
+ if (pendingDef.drawn && p != null) {
1976
+ const border = pendingDef.borders[pendingDef.drawn];
1977
+ if (w === 'brdrw') {
1978
+ // (No width is no line: Word writes \brdrw0 for a border that is off.)
1979
+ if (p > 0)
1980
+ border.twips = p;
1981
+ else
1982
+ delete pendingDef.borders[pendingDef.drawn];
1983
+ }
1984
+ else {
1985
+ const color = p > 0 && p < colorTable.length ? colorTable[p] : '';
1986
+ border.color = color === 'rgb(0,0,0)' ? '' : color;
1987
+ }
1988
+ }
1787
1989
  break;
1788
1990
  // Every border style RTF names: any of them makes the side a border.
1789
1991
  case 'brdrs':
@@ -1820,6 +2022,11 @@ export function rtfToHtml(rtfString, options = {}) {
1820
2022
  }
1821
2023
  borderSide = pendingSide;
1822
2024
  pendingSide = null;
2025
+ if (pendingDef.edge) {
2026
+ pendingDef.borders[pendingDef.edge] = { line: BORDER_LINE_CSS.get(w) ?? 'solid', twips: 15, color: '' };
2027
+ pendingDef.drawn = pendingDef.edge;
2028
+ pendingDef.edge = null;
2029
+ }
1823
2030
  break;
1824
2031
  case 'clvmgf':
1825
2032
  pendingDef.vmgf = true;
@@ -1852,17 +2059,23 @@ export function rtfToHtml(rtfString, options = {}) {
1852
2059
  pendingHighSurrogate = 0;
1853
2060
  pushText('\ufffd', state);
1854
2061
  }
2062
+ // (A caption in a cell is the cell's; it is not the paragraph's after the table.)
2063
+ paragraphIsCaption = false;
2064
+ const figure = cellFigure();
1855
2065
  currentRowCells.push({
1856
- html: trimSpaces(renderRuns(runs)),
1857
- onWhite: cellOnWhite(),
2066
+ html: figure ?? cellHtml(spacingHere(state)),
2067
+ onWhite: figure ? undefined : cellOnWhite(),
1858
2068
  // The alignment of the cell's last paragraph, also where that paragraph
1859
2069
  // was ended inside a group ({\pard\intbl\qr 1.0\par}\cell, as this writer
1860
2070
  // wrote cells up to 1.9.0).
1861
- align: alignHere(state)
2071
+ align: alignHere(state),
2072
+ header: cellMarkedHeader
1862
2073
  });
2074
+ cellMarkedHeader = false;
1863
2075
  newRuns();
1864
2076
  // The paragraph mark that ends a cell's last paragraph adds no line.
1865
2077
  cellBreaks = 0;
2078
+ cellBreakSpacing = [];
1866
2079
  nestTabPending = false;
1867
2080
  break;
1868
2081
  case 'nestcell':
@@ -1873,6 +2086,7 @@ export function rtfToHtml(rtfString, options = {}) {
1873
2086
  case 'nestrow':
1874
2087
  nestTabPending = false;
1875
2088
  cellBreaks++;
2089
+ cellBreakSpacing.push(null);
1876
2090
  break;
1877
2091
  case 'row': {
1878
2092
  // Text after the row's last \cell is a cell that was not closed, not the
@@ -1883,13 +2097,16 @@ export function rtfToHtml(rtfString, options = {}) {
1883
2097
  }
1884
2098
  // A row with no definition of its own repeats the one before it.
1885
2099
  const defs = currentRowDefs.length > 0 ? currentRowDefs : lastRowDefs;
1886
- tableRows.push({ cells: currentRowCells, defs });
2100
+ const gaph = currentRowDefs.length > 0 ? rowGaph : lastRowGaph;
2101
+ tableRows.push({ cells: currentRowCells, defs, gaph });
1887
2102
  lastRowDefs = defs;
2103
+ lastRowGaph = gaph;
1888
2104
  currentRowCells = [];
1889
2105
  currentRowDefs = [];
1890
2106
  pendingDef = newCellDef();
1891
2107
  inTableCell = false;
1892
2108
  cellBreaks = 0;
2109
+ cellBreakSpacing = [];
1893
2110
  nestTabPending = false;
1894
2111
  // The cell's indents and alignment end with the row, in whichever group
1895
2112
  // set them: \row may sit in a group of its own ({\row}). Not in the text a
@@ -2008,10 +2225,12 @@ export function rtfToHtml(rtfString, options = {}) {
2008
2225
  // A page break. On screen it is a rule; the writer sends it back as \page.
2009
2226
  if (inTableCell) {
2010
2227
  cellBreaks++;
2228
+ cellBreakSpacing.push(null);
2011
2229
  break;
2012
2230
  }
2013
2231
  for (; cellBreaks > 0; cellBreaks--)
2014
2232
  flushParagraph();
2233
+ cellBreakSpacing = [];
2015
2234
  if (runs.length > 0)
2016
2235
  flushParagraph();
2017
2236
  flushTable();
@@ -2077,20 +2296,26 @@ export function rtfToHtml(rtfString, options = {}) {
2077
2296
  const items = blocks.map((b) => {
2078
2297
  if (b.kind !== 'paragraph' || !b.marker || b.inTable || b.caption)
2079
2298
  return null;
2080
- if (b.first !== -LIST_HANG || b.left < LIST_HANG || b.right !== 0 || b.align !== 'left')
2299
+ if (!hangsAsItem(b.first, b.left) || b.right !== 0 || b.align !== 'left')
2081
2300
  return null;
2082
2301
  return {
2083
2302
  kind: b.marker.kind,
2084
2303
  number: b.marker.number,
2085
2304
  letters: b.marker.letters,
2086
2305
  left: b.left,
2087
- html: trimSpaces(renderRuns(b.runs.slice(b.marker.end)))
2306
+ hang: -b.first,
2307
+ html: trimSpaces(renderRuns(b.runs.slice(b.marker.end))),
2308
+ spacing: spacingStyle(b)
2088
2309
  };
2089
2310
  });
2311
+ /** Where an item's marker stands, in twips: its text's indent less its hang. */
2312
+ const markAt = (item) => item.left - item.hang;
2090
2313
  /** Consecutive list items as nested <ul> and <ol>, one string per list at the top level. */
2091
2314
  function renderLists(list) {
2092
2315
  const out = [];
2093
2316
  let html = '';
2317
+ // (A level is where its markers stand, as Word has it: lists with other gaps after the
2318
+ // marker are at one level where their markers are at one place.)
2094
2319
  const open = [];
2095
2320
  /**
2096
2321
  * The number an item has and the way its list counts. Letters can be read two ways: "C"
@@ -2099,26 +2324,49 @@ export function rtfToHtml(rtfString, options = {}) {
2099
2324
  * ("D." or "CI."); and with neither to go by, a Roman numeral for "I" and for several
2100
2325
  * letters, a letter for any other.
2101
2326
  */
2327
+ /**
2328
+ * For each item, the next one at its level in the same run of items: the one after it
2329
+ * with the same indent, with none of a smaller indent between; -1 where there is none.
2330
+ * Found for all of them in one pass from the end. (Looked for from each item in turn,
2331
+ * a list in which every item is one level deeper than the last was read through once
2332
+ * for each of its items: a second for 20,000 of them, four for 40,000.)
2333
+ */
2334
+ const nextAtLevel = new Array(list.length).fill(-1);
2335
+ {
2336
+ /** The items after this one that one before it may still go on to: the nearest at each indent, the smallest indent first. */
2337
+ const ahead = [];
2338
+ for (let i = list.length - 1; i >= 0; i--) {
2339
+ const mark = markAt(list[i]);
2340
+ while (ahead.length > 0 && ahead[ahead.length - 1].mark > mark)
2341
+ ahead.pop();
2342
+ const same = ahead[ahead.length - 1];
2343
+ if (same && same.mark === mark) {
2344
+ nextAtLevel[i] = same.at;
2345
+ same.at = i;
2346
+ }
2347
+ else {
2348
+ ahead.push({ mark, at: i });
2349
+ }
2350
+ }
2351
+ }
2102
2352
  const readingOf = (at, top) => {
2103
2353
  const item = list[at];
2104
2354
  if (!item.letters)
2105
2355
  return { style: 'decimal', number: item.number };
2106
2356
  const readings = letterReadings(item.letters);
2107
- if (top && top.kind === 'ol' && item.left === top.left) {
2357
+ if (top && top.kind === 'ol' && markAt(item) === top.at) {
2108
2358
  const goesOn = readings.find((r) => r.style === top.style && r.number === top.next);
2109
2359
  if (goesOn)
2110
2360
  return goesOn;
2111
2361
  }
2112
2362
  if (readings.length === 1)
2113
2363
  return readings[0];
2114
- for (let i = at + 1; i < list.length && list[i].left >= item.left; i++) {
2115
- if (list[i].left > item.left)
2116
- continue;
2117
- const after = list[i].letters ? letterReadings(list[i].letters) : [];
2364
+ const next = nextAtLevel[at];
2365
+ if (next !== -1) {
2366
+ const after = list[next].letters ? letterReadings(list[next].letters) : [];
2118
2367
  const led = readings.find((r) => after.some((a) => a.style === r.style && a.number === r.number + 1));
2119
2368
  if (led)
2120
2369
  return led;
2121
- break;
2122
2370
  }
2123
2371
  const roman = item.letters.length > 1 || /^[Ii]$/.test(item.letters);
2124
2372
  return readings.find((r) => r.style.endsWith(roman ? 'roman' : 'alpha')) ?? readings[0];
@@ -2133,26 +2381,29 @@ export function rtfToHtml(rtfString, options = {}) {
2133
2381
  };
2134
2382
  for (const [at, item] of list.entries()) {
2135
2383
  // A smaller indent ends the lists nested deeper than it.
2136
- while (open.length > 0 && item.left < open[open.length - 1].left)
2384
+ while (open.length > 0 && markAt(item) < open[open.length - 1].at)
2137
2385
  closeList();
2138
2386
  const top = open[open.length - 1];
2139
2387
  const { style, number } = readingOf(at, top);
2140
- if (top && item.left === top.left && item.kind === top.kind && (item.kind === 'ul' || (number === top.next && style === top.style))) {
2141
- html += '</li><li>';
2388
+ if (top && markAt(item) === top.at && item.hang === top.hang && item.kind === top.kind && (item.kind === 'ul' || (number === top.next && style === top.style))) {
2389
+ html += `</li><li${item.spacing ? ` style="${item.spacing}"` : ''}>`;
2142
2390
  top.next = number + 1;
2143
2391
  }
2144
2392
  else {
2145
- // A change from bullets to numbers, or a number out of sequence, is a new list
2146
- // in the same place.
2147
- if (top && item.left === top.left)
2393
+ // A change from bullets to numbers, a number out of sequence or another gap after
2394
+ // the marker is a new list in the same place.
2395
+ if (top && markAt(item) === top.at)
2148
2396
  closeList();
2149
2397
  const parent = open[open.length - 1];
2150
- // What the indent adds to the half inch a list level has by itself.
2151
- const margin = item.left - (parent ? parent.left : 0) - LIST_STEP;
2398
+ // What the indent adds to the half inch a list level has by itself: the marker
2399
+ // stands a quarter inch into the level, and the text the list's gap after it.
2400
+ const margin = item.left - item.hang - (parent ? parent.left : 0) - (LIST_STEP - LIST_HANG);
2152
2401
  const start = item.kind === 'ol' && number !== 1 ? ` start="${number}"` : '';
2153
2402
  const type = item.kind === 'ol' && style !== 'decimal' ? ` type="${listTypeAttribute(style)}"` : '';
2154
- html += `<${item.kind}${type}${start}${margin !== 0 ? ` style="margin-left:${twipsToPt(margin)}"` : ''}><li>`;
2155
- open.push({ kind: item.kind, left: item.left, next: number + 1, style });
2403
+ // (A gap other than the quarter inch is the list's padding: see markerGapTwips.)
2404
+ const listStyle = [margin !== 0 ? `margin-left:${twipsToPt(margin)}` : '', item.hang !== LIST_HANG ? `padding-left:${twipsToPt(item.hang)}` : ''].filter(Boolean).join(';');
2405
+ html += `<${item.kind}${type}${start}${listStyle ? ` style="${listStyle}"` : ''}><li${item.spacing ? ` style="${item.spacing}"` : ''}>`;
2406
+ open.push({ kind: item.kind, left: item.left, at: markAt(item), hang: item.hang, next: number + 1, style });
2156
2407
  }
2157
2408
  html += item.html || '<br>';
2158
2409
  }
@@ -2212,8 +2463,8 @@ export function rtfToHtml(rtfString, options = {}) {
2212
2463
  continue;
2213
2464
  }
2214
2465
  const align = block.align;
2215
- // The paragraph's style attribute: its alignment, then its indents.
2216
- const blockStyle = [align !== 'left' ? `text-align:${align}` : '', block.inTable ? '' : indentStyle(block)]
2466
+ // The paragraph's style attribute: its alignment, then its indents and its spacing.
2467
+ const blockStyle = [align !== 'left' ? `text-align:${align}` : '', block.inTable ? '' : indentStyle(block), block.inTable ? '' : spacingStyle(block)]
2217
2468
  .filter(Boolean)
2218
2469
  .join(';');
2219
2470
  const styleAttr = blockStyle ? ` style="${blockStyle}"` : '';
@@ -2244,14 +2495,15 @@ export function rtfToHtml(rtfString, options = {}) {
2244
2495
  // The caption is given by a function: as a replacement string, a "$&" or a "$`"
2245
2496
  // in the caption's own text would be read as the match or as the figure before it.
2246
2497
  const caption = `<figcaption>${stripWrappingEm(trimmed)}</figcaption></figure>`;
2247
- rendered[last] = rendered[last].replace('</figure>', () => caption);
2498
+ // (The space after a picture is written after its caption.)
2499
+ rendered[last] = withStyle(rendered[last].replace('</figure>', () => caption), block.inTable ? '' : spacingStyle(block, 'after'));
2248
2500
  continue;
2249
2501
  }
2250
2502
  }
2251
2503
  // A paragraph holding nothing but pictures becomes a figure, so it can carry
2252
2504
  // a caption and be aligned/resized as a unit in the editor.
2253
2505
  if (IMAGE_ONLY_PARAGRAPH.test(trimmed)) {
2254
- const figureStyle = [align !== 'left' ? `text-align:${align}` : '', block.inTable ? '' : figureIndentStyle(block)]
2506
+ const figureStyle = [align !== 'left' ? `text-align:${align}` : '', block.inTable ? '' : figureIndentStyle(block), block.inTable ? '' : spacingStyle(block, 'before'), block.inTable ? '' : spacingStyle(block, 'after')]
2255
2507
  .filter(Boolean)
2256
2508
  .join(';');
2257
2509
  rendered.push(`<figure${figureStyle ? ` style="${figureStyle}"` : ''}>${trimmed}</figure>`);