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.
@@ -12,8 +12,11 @@
12
12
  *
13
13
  * Background color is intentionally not written — RTF highlight support
14
14
  * is inconsistent across viewers (TextEdit uses \AppleHighlight, not \highlight).
15
+ * So a text color that can be read only on its background is not written either: see
16
+ * lostWithoutItsBackground.
15
17
  */
16
18
  import { tableModel, columnShares, tableRowsInOrder, rowCells } from './table-model.js';
19
+ import { itemNumber, listStart, markerText, numberStyleOf } from './list-markers.js';
17
20
  /**
18
21
  * Font used when no fontFamily is given: what the editor and the viewer show, and what the RTF
19
22
  * names. This is the one place the default is named; the size estimate, the components and the
@@ -88,23 +91,102 @@ function parseColor(colorStr) {
88
91
  };
89
92
  }
90
93
  // Basic named colors
91
- const named = {
92
- black: { r: 0, g: 0, b: 0 },
93
- white: { r: 255, g: 255, b: 255 },
94
- red: { r: 255, g: 0, b: 0 },
95
- green: { r: 0, g: 128, b: 0 },
96
- blue: { r: 0, g: 0, b: 255 },
97
- yellow: { r: 255, g: 255, b: 0 },
98
- orange: { r: 255, g: 165, b: 0 },
99
- purple: { r: 128, g: 0, b: 128 },
100
- gray: { r: 128, g: 128, b: 128 },
101
- grey: { r: 128, g: 128, b: 128 }
102
- };
103
- return named[s] || null;
94
+ return NAMED_COLORS.get(s) ?? null;
104
95
  }
96
+ /**
97
+ * The colors known by name. A Map, like every table here that is asked for a name out of the
98
+ * document (a color, a tag): an object also answers to the names every object has, so
99
+ * <font color="constructor"> was a color, and went into the color table as
100
+ * "\redundefined\greenundefined\blueundefined".
101
+ */
102
+ const NAMED_COLORS = new Map(Object.entries({
103
+ black: { r: 0, g: 0, b: 0 },
104
+ white: { r: 255, g: 255, b: 255 },
105
+ red: { r: 255, g: 0, b: 0 },
106
+ green: { r: 0, g: 128, b: 0 },
107
+ blue: { r: 0, g: 0, b: 255 },
108
+ yellow: { r: 255, g: 255, b: 0 },
109
+ orange: { r: 255, g: 165, b: 0 },
110
+ purple: { r: 128, g: 0, b: 128 },
111
+ gray: { r: 128, g: 128, b: 128 },
112
+ grey: { r: 128, g: 128, b: 128 }
113
+ }));
105
114
  function colorKey(c) {
106
115
  return `${c.r},${c.g},${c.b}`;
107
116
  }
117
+ // ── Text that needs its background ──
118
+ // A background is not written (see the top of this file), so the reader shows every word on
119
+ // white. White words on a dark table header, or a sentence copied from a page with a dark
120
+ // theme, were written white all the same: the header of a results table, or "Margins are
121
+ // positive for carcinoma.", was in the report and could not be seen. A color that can be read
122
+ // on its background and not on white is left out, and the words are in the reader's own color.
123
+ const WHITE = { r: 255, g: 255, b: 255 };
124
+ /** Below this contrast with white (WCAG's measure, 1 to 21) words are hard to read: its floor for large text. */
125
+ const READABLE_ON_WHITE = 3;
126
+ function luminance(c) {
127
+ const part = (value) => {
128
+ const s = value / 255;
129
+ return s <= 0.03928 ? s / 12.92 : ((s + 0.055) / 1.055) ** 2.4;
130
+ };
131
+ return 0.2126 * part(c.r) + 0.7152 * part(c.g) + 0.0722 * part(c.b);
132
+ }
133
+ /** The contrast of two colors as WCAG counts it: 1 for the same color, 21 for black on white. */
134
+ export function colorContrast(a, b) {
135
+ const [light, dark] = [luminance(a), luminance(b)].sort((x, y) => y - x);
136
+ return (light + 0.05) / (dark + 0.05);
137
+ }
138
+ /** Whether words in a color are hard to read on a white page. */
139
+ export function hardToReadOnWhite(color) {
140
+ return colorContrast(color, WHITE) < READABLE_ON_WHITE;
141
+ }
142
+ /** 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
+ /**
145
+ * The background an element sets by itself: its color, 'some' for one that is set and not read
146
+ * (a color by a name this file does not know, a picture), or null. From its style, and from the
147
+ * `bgcolor` older pages and mail put on a table and its cells.
148
+ */
149
+ function ownBackground(el) {
150
+ const style = el.style;
151
+ const color = (style?.backgroundColor || '').trim().toLowerCase();
152
+ if (color && !NO_BACKGROUND.test(color))
153
+ return parseColor(color) ?? 'some';
154
+ const image = (style?.backgroundImage || '').trim().toLowerCase();
155
+ if (image && image !== 'none' && image !== 'initial')
156
+ return 'some';
157
+ // (Not every DOM spreads `background` over the properties it stands for.)
158
+ const short = color ? '' : (style?.getPropertyValue?.('background') || '').trim().toLowerCase();
159
+ if (short && !NO_BACKGROUND.test(short))
160
+ return parseColor(short.split(/\s+(?![^(]*\))/)[0]) ?? 'some';
161
+ const attribute = (el.getAttribute('bgcolor') ?? '').trim().toLowerCase();
162
+ if (attribute && !NO_BACKGROUND.test(attribute))
163
+ return parseColor(attribute) ?? parseColor(`#${attribute}`) ?? 'some';
164
+ return null;
165
+ }
166
+ /** The background the words of an element stand on: its own, or the nearest one around it in the document. */
167
+ function backgroundBehind(el, root) {
168
+ for (let at = el; at; at = at.parentElement) {
169
+ const own = ownBackground(at);
170
+ if (own)
171
+ return own;
172
+ if (at === root)
173
+ break;
174
+ }
175
+ return null;
176
+ }
177
+ /**
178
+ * Whether a text color is one that only its background makes readable: hard to read on white,
179
+ * and on a background in the document that it reads better on. A color with no background
180
+ * behind it is the writer's own choice, as the screen shows it, and is written whatever it is.
181
+ */
182
+ function lostWithoutItsBackground(color, el, root) {
183
+ const onWhite = colorContrast(color, WHITE);
184
+ if (onWhite >= READABLE_ON_WHITE)
185
+ return false;
186
+ const behind = backgroundBehind(el, root);
187
+ // (Better by more than a shade: white on ivory is as hard to read as white on white.)
188
+ return behind === 'some' || (behind !== null && colorContrast(color, behind) > onWhite + 0.5);
189
+ }
108
190
  // ── RTF text escaping ──
109
191
  function escapeRtf(text) {
110
192
  // RTF readers ignore raw CR/LF, so a newline inside text content rendered as
@@ -451,7 +533,7 @@ const PICTURE_OVERHEAD_BYTES = 80;
451
533
  * and closing runs measured from walkChildren. Anything not listed costs
452
534
  * nothing of its own beyond the text it contains.
453
535
  */
454
- const BLOCK_OVERHEAD_BYTES = {
536
+ const BLOCK_OVERHEAD_BYTES = new Map(Object.entries({
455
537
  p: 14,
456
538
  div: 14,
457
539
  h1: 29,
@@ -490,7 +572,16 @@ const BLOCK_OVERHEAD_BYTES = {
490
572
  hr: 154, // "\pard\qc " + 20 x "\emdash" + "\par "
491
573
  ul: 0,
492
574
  ol: 0
493
- };
575
+ }));
576
+ /**
577
+ * What an element of this tag costs, or nothing for one not listed. (Looked up in a Map: asked
578
+ * of an object, an element named <constructor> cost a function, and the estimate, added to
579
+ * that, was a piece of text. An application comparing it with a size limit then let every
580
+ * document through.)
581
+ */
582
+ function overheadBytes(tag) {
583
+ return BLOCK_OVERHEAD_BYTES.get(tag) ?? 0;
584
+ }
494
585
  /**
495
586
  * Blocks that are written as a <div> is: a paragraph when they hold text, a container when they
496
587
  * hold blocks. Pasted pages are made of them, and each one not known as a block had its lines
@@ -534,6 +625,8 @@ export function estimateRtfBytes(editorEl, options = {}) {
534
625
  // heading's, twice the body.
535
626
  const sizeDigits = Math.max(0, String(bodyHalfPoints(options.fontSize) * 2).length - 2);
536
627
  let total = RTF_PREAMBLE_BYTES + fontName.length + fontClass + sizeDigits;
628
+ const offered = new Map(fontChoices(options.fonts).map((choice) => [choice.key, choice]));
629
+ const fontsCounted = new Set();
537
630
  for (const img of Array.from(editorEl.querySelectorAll('img'))) {
538
631
  const src = img.getAttribute('src') || '';
539
632
  const comma = src.indexOf(',');
@@ -599,7 +692,7 @@ export function estimateRtfBytes(editorEl, options = {}) {
599
692
  // A <div> that only holds blocks writes nothing of its own: its blocks are counted.
600
693
  const container = tag === 'div' && Array.from(el.children).some(isBlock) && !startsWithInline(el) && !endsWithInline(el);
601
694
  if (!container)
602
- total += BLOCK_OVERHEAD_BYTES[tag] ?? 0;
695
+ total += overheadBytes(tag);
603
696
  // A heading and a code block each write their size and the size around them.
604
697
  if (HEADING_TAGS.has(tag) || tag === 'pre')
605
698
  total += 2 * sizeDigits;
@@ -625,6 +718,21 @@ export function estimateRtfBytes(editorEl, options = {}) {
625
718
  if (target)
626
719
  total += LINK_OVERHEAD_BYTES + escapeRtf(target).length;
627
720
  }
721
+ if (offered.size > 0) {
722
+ // Text in a font of its own turns it on and off again ("\f12 " twice), and the first
723
+ // text in a font adds the font to the table ("{\f12\fmodern\fcharset0 Name;}").
724
+ const key = fontKey(style?.fontFamily || (tag === 'font' ? el.getAttribute('face') : ''));
725
+ const choice = offered.get(key);
726
+ if (choice || (key && key === font.toLowerCase()))
727
+ total += 12;
728
+ if (choice && !fontsCounted.has(key)) {
729
+ fontsCounted.add(key);
730
+ total += 28 + escapeRtf(choice.name).length;
731
+ }
732
+ // What puts the font back after code, a heading or a table cell may now have two digits.
733
+ if (tag === 'code' || tag === 'pre' || tag === 'td' || tag === 'th' || HEADING_TAGS.has(tag))
734
+ total += 2;
735
+ }
628
736
  // Each line break in a code block is written as "\line " (6). It is counted as 1 with
629
737
  // the text, or as nothing where it follows another: a run of them is counted there as
630
738
  // one space.
@@ -667,14 +775,14 @@ export function estimateRtfBytes(editorEl, options = {}) {
667
775
  // rowspan="0" reaches the last row; no span reaches past the table.
668
776
  const rowCount = el.closest('table')?.querySelectorAll('tr').length ?? 1;
669
777
  const spanned = Math.min(rowCount, rows > 0 ? rows : rowCount);
670
- total += 7 + (spanned - 1) * ((BLOCK_OVERHEAD_BYTES[tag] ?? 0) + 7);
778
+ total += 7 + (spanned - 1) * (overheadBytes(tag) + 7);
671
779
  }
672
780
  }
673
781
  // A row with fewer cells than the table has columns is filled with empty ones.
674
782
  if (tag === 'table' && !el.parentElement?.closest('td, th')) {
675
783
  const model = tableModel(el);
676
784
  for (const row of model.rows)
677
- total += row.filter((slot) => slot === null).length * BLOCK_OVERHEAD_BYTES.td;
785
+ total += row.filter((slot) => slot === null).length * overheadBytes('td');
678
786
  }
679
787
  // Anything in a table that is in no cell is written before it, each run a paragraph
680
788
  // ("\pard\intbl\qc\liN " and "\par ", at most 27).
@@ -702,10 +810,17 @@ export function estimateRtfBytes(editorEl, options = {}) {
702
810
  // A paragraph inside a list item is written at the item's indent (\liN, up to 7).
703
811
  if ((tag === 'p' || tag === 'div') && el.parentElement?.tagName === 'LI')
704
812
  total += 8;
705
- // A numbered item's number is counted as one digit; a list that starts high has more.
813
+ // A numbered item's number is counted as one character; a list that starts high has
814
+ // more, and so has one in Roman numerals ("xviii.").
706
815
  if (tag === 'ol') {
707
- const last = (parseInt(el.getAttribute('start') ?? '', 10) || 1) + el.children.length;
708
- total += el.children.length * Math.max(0, String(last).length - 1);
816
+ let counter = listStart(el);
817
+ for (const item of Array.from(el.children)) {
818
+ if (item.tagName !== 'LI')
819
+ continue;
820
+ counter = itemNumber(item, counter);
821
+ total += Math.max(0, markerText(counter, numberStyleOf(el, item)).length - 1);
822
+ counter++;
823
+ }
709
824
  }
710
825
  // A figure with no picture is a paragraph of what it holds: "\pard\intbl\qc\liN " and
711
826
  // "\par " (at most 30).
@@ -770,6 +885,86 @@ function cleanFontName(name) {
770
885
  const cleaned = first.replace(/[\\{};]/g, '').trim();
771
886
  return cleaned || DEFAULT_FONT_FAMILY;
772
887
  }
888
+ /** The generic families of CSS, which are written without quotes. */
889
+ const GENERIC_FAMILY = new Set(['serif', 'sans-serif', 'monospace', 'cursive', 'fantasy', 'system-ui', 'ui-serif', 'ui-sans-serif', 'ui-monospace', 'ui-rounded', 'math', 'emoji', 'fangsong']);
890
+ /** What a font name is made of: letters, digits, spaces and a few marks. */
891
+ const FONT_NAME = /^[\p{L}\p{N} ._-]+$/u;
892
+ /** Words that mean something else to CSS where a family is named: such a name is quoted. */
893
+ const CSS_WIDE = /^(inherit|initial|unset|revert|revert-layer|default)$/i;
894
+ /** Whether two font values name the same families in the same order, however they are written. */
895
+ export function sameFontList(a, b) {
896
+ return familiesOf(a).join(',').toLowerCase() === familiesOf(b).join(',').toLowerCase();
897
+ }
898
+ /** The families of a CSS font list or a `face` attribute, without their quotes. */
899
+ function familiesOf(value) {
900
+ if (typeof value !== 'string')
901
+ return [];
902
+ return value
903
+ .split(',')
904
+ .map((family) => family.replace(/["']/g, '').replace(/\s+/g, ' ').trim())
905
+ .filter((family) => family !== '');
906
+ }
907
+ /**
908
+ * The name a font value is looked up by: its first family, without quotes and without regard to
909
+ * capitals. '' where there is none.
910
+ */
911
+ export function fontKey(value) {
912
+ return (familiesOf(value)[0] ?? '').toLowerCase();
913
+ }
914
+ /** One family as CSS: quoted wherever a bare name could be read as something else. */
915
+ function cssFamily(family) {
916
+ if (GENERIC_FAMILY.has(family.toLowerCase()))
917
+ return family.toLowerCase();
918
+ const words = family.split(' ');
919
+ const bare = words.every((word) => /^[A-Za-z][A-Za-z0-9-]*$/.test(word) && !CSS_WIDE.test(word) && !GENERIC_FAMILY.has(word.toLowerCase()));
920
+ return bare ? family : `"${family}"`;
921
+ }
922
+ /**
923
+ * The fonts an application offers, as the editor, the sanitizer, the writer and the reader use
924
+ * them. Each is given as a name ("Calibri") or as a CSS list whose first family is the name
925
+ * ("Calibri, Carlito, sans-serif"): the rest of the list is what a screen without that font
926
+ * shows the text in. A name alone is given the generic family that suits it, so that such a
927
+ * screen does not fall back to the browser's own font. A name that could not be written in a
928
+ * font table or a style (it has a brace, a semicolon, a bracket) is left out, and so is a
929
+ * generic family by itself and a name given twice.
930
+ */
931
+ export function fontChoices(fonts) {
932
+ const given = typeof fonts === 'string' ? [fonts] : fonts == null ? [] : Array.from(fonts);
933
+ const choices = new Map();
934
+ for (const entry of given) {
935
+ const families = familiesOf(entry);
936
+ if (families.length === 0 || families.some((family) => !FONT_NAME.test(family) || family.length > 100))
937
+ continue;
938
+ const name = families[0];
939
+ const key = name.toLowerCase();
940
+ if (GENERIC_FAMILY.has(key) || choices.has(key))
941
+ continue;
942
+ const css = families.length > 1 ? families.map(cssFamily).join(', ') : `${cssFamily(name)}, ${genericFor(name)}`;
943
+ choices.set(key, { name, css, key });
944
+ }
945
+ return Array.from(choices.values());
946
+ }
947
+ /**
948
+ * The font-table index of the font an element sets its text in: 0 for the document font, 2 and
949
+ * up for a font the application offers. Null where it names none, or one that is not offered.
950
+ */
951
+ function fontOf(el, fonts) {
952
+ if (fonts.offered.size === 0)
953
+ return null;
954
+ const key = fontKey(el.style?.fontFamily || (el.tagName === 'FONT' ? el.getAttribute('face') : ''));
955
+ if (!key)
956
+ return null;
957
+ if (key === fonts.document)
958
+ return 0;
959
+ if (!fonts.offered.has(key))
960
+ return null;
961
+ let index = fonts.used.get(key);
962
+ if (index === undefined) {
963
+ index = fonts.used.size + 2;
964
+ fonts.used.set(key, index);
965
+ }
966
+ return index;
967
+ }
773
968
  /**
774
969
  * Whether a font name is a monospace font's: Courier New, Consolas, Menlo, a "… Mono" family
775
970
  * (Roboto Mono, DejaVu Sans Mono), and their PostScript names (CourierNewPSMT, SFMono-Regular).
@@ -790,13 +985,29 @@ function fontFamilyClass(name) {
790
985
  return 'swiss';
791
986
  }
792
987
  /**
793
- * CSS font-family value for a font name, with the generic fallback that
794
- * matches it, e.g. "Arial", sans-serif.
988
+ * CSS font-family value for the document font: the name, with the generic fallback that matches
989
+ * it, e.g. "Arial", sans-serif.
990
+ *
991
+ * Given a CSS list, the first family is the font (the one the RTF names) and the rest is what a
992
+ * screen without that font shows the document in, in that order: "Segoe UI, Selawik, sans-serif"
993
+ * is Segoe UI where it is installed and Selawik where the page has loaded that. A list that does
994
+ * not end in a generic family is given the one that matches the font. A family that is no font
995
+ * name (it has a brace, a semicolon, a bracket) is left out.
795
996
  */
796
997
  export function cssFontFamily(name) {
797
998
  const font = cleanFontName(name);
798
- const generic = { roman: 'serif', modern: 'monospace', swiss: 'sans-serif' }[fontFamilyClass(font)];
799
- return `"${font}", ${generic}`;
999
+ const others = familiesOf(name)
1000
+ .slice(1)
1001
+ .filter((family) => FONT_NAME.test(family) && family.length <= 100)
1002
+ .map((family) => (GENERIC_FAMILY.has(family.toLowerCase()) ? family.toLowerCase() : `"${family}"`));
1003
+ const last = others[others.length - 1];
1004
+ if (last === undefined || last.startsWith('"'))
1005
+ others.push(genericFor(font));
1006
+ return [`"${font}"`, ...others].join(', ');
1007
+ }
1008
+ /** The generic CSS family that suits a font name: what a screen without the font shows instead. */
1009
+ function genericFor(name) {
1010
+ return { roman: 'serif', modern: 'monospace', swiss: 'sans-serif' }[fontFamilyClass(name)];
800
1011
  }
801
1012
  /**
802
1013
  * A body size in points, as the RTF will carry it: rounded to the half-point
@@ -837,14 +1048,14 @@ export function htmlToRtf(editorEl, options = {}) {
837
1048
  colorTable += `\\red${c.r}\\green${c.g}\\blue${c.b};`;
838
1049
  }
839
1050
  colorTable += '}';
840
- // \f0 is the document font, used for everything except code; \f1 is the
841
- // monospace font for code.
842
- const fontTable = '{\\fonttbl' +
843
- `{\\f0\\f${fontFamilyClass(fontName)}\\fcharset0 ${escapeRtf(fontName)};}` +
844
- '{\\f1\\fmodern\\fcharset0 Courier New;}' +
845
- '}';
1051
+ const fonts = {
1052
+ document: fontName.toLowerCase(),
1053
+ offered: new Map(fontChoices(options.fonts).map((choice) => [choice.key, choice])),
1054
+ used: new Map()
1055
+ };
846
1056
  const body = walkChildren(editorEl, {
847
1057
  colorIndex,
1058
+ colorAt: new Map(colors.map((c, i) => [i + 1, c])),
848
1059
  bodySize,
849
1060
  inPre: false,
850
1061
  listCounter: 0,
@@ -859,9 +1070,19 @@ export function htmlToRtf(editorEl, options = {}) {
859
1070
  color: 0,
860
1071
  script: null,
861
1072
  mono: false,
1073
+ font: 0,
1074
+ fonts,
862
1075
  indent: 0,
863
1076
  cellAlign: ''
864
1077
  });
1078
+ // \f0 is the document font, used for everything except code; \f1 is the monospace font
1079
+ // for code. After them, the fonts the application offers that the document has text in.
1080
+ let fontTable = `{\\fonttbl{\\f0\\f${fontFamilyClass(fontName)}\\fcharset0 ${escapeRtf(fontName)};}{\\f1\\fmodern\\fcharset0 Courier New;}`;
1081
+ for (const [key, index] of fonts.used) {
1082
+ const name = fonts.offered.get(key).name;
1083
+ fontTable += `{\\f${index}\\f${fontFamilyClass(name)}\\fcharset0 ${escapeRtf(name)};}`;
1084
+ }
1085
+ fontTable += '}';
865
1086
  const rtf = '{\\rtf1\\ansi\\ansicpg1252\\deff0' +
866
1087
  fontTable +
867
1088
  colorTable +
@@ -875,21 +1096,22 @@ export function htmlToRtf(editorEl, options = {}) {
875
1096
  // and no newline carries meaning in the output.
876
1097
  return rtf.replace(/[\r\n]+/g, ' ');
877
1098
  }
878
- function addColor(colorStr, colorMap) {
1099
+ function addColor(colorStr, colorMap, el, root) {
879
1100
  if (!colorStr)
880
1101
  return;
881
1102
  const c = parseColor(colorStr);
882
- if (c)
1103
+ // (A color that is not written is not in the table either.)
1104
+ if (c && !lostWithoutItsBackground(c, el, root))
883
1105
  colorMap.set(colorKey(c), c);
884
1106
  }
885
1107
  function collectColors(root, colorMap) {
886
1108
  // (In document order, as the color table has always been written, and without a call per
887
1109
  // level of nesting.)
888
1110
  for (const el of [root, ...Array.from(root.querySelectorAll('*'))]) {
889
- addColor(el.style?.color, colorMap);
1111
+ addColor(el.style?.color, colorMap, el, root);
890
1112
  // <font color="..."> is produced by execCommand('foreColor')
891
1113
  if (el.tagName?.toLowerCase() === 'font')
892
- addColor(el.getAttribute('color'), colorMap);
1114
+ addColor(el.getAttribute('color'), colorMap, el, root);
893
1115
  }
894
1116
  }
895
1117
  /** How many elements deep the walker is (see MAX_ELEMENT_DEPTH). */
@@ -994,7 +1216,7 @@ function walkNodeAt(node, ctx, restate, endLooseText) {
994
1216
  rtf += `\\fs${size}${ctx.bold ? '' : '\\b'} ${own.on}${walkChildren(el, own.ctx)}${own.off}${ctx.bold ? '' : '\\b0'}\\fs${ctx.size} `;
995
1217
  break;
996
1218
  }
997
- rtf += `\\pard${inCell(ctx)}${headingLayout(el, ctx)}\\f0\\fs${size}\\b ${own.on}${walkChildren(el, own.ctx)}${own.off}${ctx.bold ? '' : '\\b0'}\\fs${ctx.size}\\par `;
1219
+ rtf += `\\pard${inCell(ctx)}${headingLayout(el, ctx)}\\f${ctx.font}\\fs${size}\\b ${own.on}${walkChildren(el, own.ctx)}${own.off}${ctx.bold ? '' : '\\b0'}\\fs${ctx.size}\\par `;
998
1220
  break;
999
1221
  }
1000
1222
  case 'p':
@@ -1074,7 +1296,7 @@ function walkNodeAt(node, ctx, restate, endLooseText) {
1074
1296
  }
1075
1297
  case 'pre': {
1076
1298
  const size = scaled(ctx, PRE_SCALE);
1077
- rtf += `\\pard${inCell(ctx)}${cellAlign(ctx)}${liControl(ctx.indent + leftMarginTwips(el))}\\f1\\fs${size} ${walkChildren(el, { ...ctx, inPre: true, size })}\\f0\\fs${ctx.size}\\par `;
1299
+ rtf += `\\pard${inCell(ctx)}${cellAlign(ctx)}${liControl(ctx.indent + leftMarginTwips(el))}\\f1\\fs${size} ${walkChildren(el, { ...ctx, inPre: true, size })}\\f${ctx.font}\\fs${ctx.size}\\par `;
1078
1300
  break;
1079
1301
  }
1080
1302
  case 'hr':
@@ -1100,7 +1322,7 @@ function walkNodeAt(node, ctx, restate, endLooseText) {
1100
1322
  case 'code': {
1101
1323
  const own = charFormat(el, tag, ctx);
1102
1324
  if (!ctx.inPre && !ctx.mono) {
1103
- rtf += `${own.on}\\f1 ${walkChildren(el, { ...own.ctx, mono: true })}\\f0 ${own.off}`;
1325
+ rtf += `${own.on}\\f1 ${walkChildren(el, { ...own.ctx, mono: true })}\\f${own.ctx.font} ${own.off}`;
1104
1326
  }
1105
1327
  else {
1106
1328
  rtf += `${own.on}${walkChildren(el, own.ctx)}${own.off}`;
@@ -1185,7 +1407,7 @@ function walkNodeAt(node, ctx, restate, endLooseText) {
1185
1407
  }
1186
1408
  // ── Character formatting ──
1187
1409
  /** What a tag by itself does to its text. */
1188
- const TAG_FORMAT = {
1410
+ const TAG_FORMAT = new Map(Object.entries({
1189
1411
  b: { bold: true },
1190
1412
  strong: { bold: true },
1191
1413
  i: { italic: true },
@@ -1200,7 +1422,7 @@ const TAG_FORMAT = {
1200
1422
  del: { strike: true },
1201
1423
  sup: { script: 'super' },
1202
1424
  sub: { script: 'sub' }
1203
- };
1425
+ }));
1204
1426
  /** Whether a font-weight is bold; null when it does not say. */
1205
1427
  function cssBold(weight) {
1206
1428
  if (!weight)
@@ -1225,7 +1447,7 @@ function cssBold(weight) {
1225
1447
  */
1226
1448
  function charFormat(el, rawTag, ctx, block = false) {
1227
1449
  const style = el.style;
1228
- const tagFormat = TAG_FORMAT[rawTag] ?? {};
1450
+ const tagFormat = TAG_FORMAT.get(rawTag) ?? {};
1229
1451
  const weight = cssBold(style?.fontWeight);
1230
1452
  const bold = weight ?? (tagFormat.bold || ctx.bold);
1231
1453
  const fontStyle = style?.fontStyle ?? '';
@@ -1240,12 +1462,19 @@ function charFormat(el, rawTag, ctx, block = false) {
1240
1462
  const script = vertical === 'super' ? 'super' : vertical === 'sub' ? 'sub' : vertical === 'baseline' ? null : (tagFormat.script ?? ctx.script);
1241
1463
  const color = colorIndexOf(el, ctx);
1242
1464
  const size = block ? null : sizeOf(el);
1465
+ // Code is in the code font, whatever font is named in it or around it.
1466
+ const named = ctx.mono || ctx.inPre || rawTag === 'pre' ? null : fontOf(el, ctx.fonts);
1467
+ const font = named === ctx.font ? null : named;
1243
1468
  let on = '';
1244
1469
  let off = '';
1245
1470
  if (color != null) {
1246
1471
  on += `\\cf${color} `;
1247
1472
  off = `\\cf${ctx.color} `;
1248
1473
  }
1474
+ if (font != null) {
1475
+ on += `\\f${font} `;
1476
+ off = `\\f${ctx.font} ${off}`;
1477
+ }
1249
1478
  if (size != null) {
1250
1479
  on += `\\fs${size} `;
1251
1480
  off = `\\fs${ctx.size} ${off}`;
@@ -1272,7 +1501,7 @@ function charFormat(el, rawTag, ctx, block = false) {
1272
1501
  }
1273
1502
  if (!on)
1274
1503
  return { on, off, ctx };
1275
- return { on, off, ctx: { ...ctx, bold, italic, underline, strike, script, color: color ?? ctx.color, size: size ?? ctx.size } };
1504
+ return { on, off, ctx: { ...ctx, bold, italic, underline, strike, script, color: color ?? ctx.color, size: size ?? ctx.size, font: font ?? ctx.font } };
1276
1505
  }
1277
1506
  /** Whether an element is shown and holds text or a picture: an empty <form> or a hidden <input> does not. */
1278
1507
  function holdsSomething(el) {
@@ -1305,7 +1534,8 @@ const LIST_HANG = 360;
1305
1534
  /**
1306
1535
  * A <ul> or <ol>: one hanging paragraph per item, opened by a bullet or the item's number and a
1307
1536
  * tab. A list inside an item, or straight inside the list (<ul><ul>, as some editors nest), is
1308
- * indented one level further. Numbers start at the list's `start`.
1537
+ * indented one level further. Numbers start at the list's `start` and are written as the list
1538
+ * shows them: in digits, in letters, in Roman numerals.
1309
1539
  */
1310
1540
  function listRtf(list, ctx) {
1311
1541
  // A list straight inside a list is written from here, not through walkNode, so the depth is
@@ -1326,8 +1556,7 @@ function listRtfAt(list, ctx) {
1326
1556
  // is negative for a list nested by less than half an inch.
1327
1557
  const margin = lengthTwips(list.style?.marginLeft, true) ?? 0;
1328
1558
  const left = Math.max(LIST_HANG, ctx.indent + margin + LIST_STEP);
1329
- const start = parseInt(list.getAttribute('start') ?? '', 10);
1330
- let counter = ordered && Number.isFinite(start) ? start : 1;
1559
+ let counter = ordered ? listStart(list) : 1;
1331
1560
  const itemCtx = { ...ctx, indent: left, cellAlign: listAlign(ctx) };
1332
1561
  const paragraph = `\\pard${inCell(ctx)}${listAlign(ctx)}${liControl(left)}`;
1333
1562
  let rtf = '';
@@ -1344,7 +1573,10 @@ function listRtfAt(list, ctx) {
1344
1573
  continue;
1345
1574
  if (tag === 'li') {
1346
1575
  flushLoose();
1347
- const marker = ordered ? ` ${counter}.\\tab ` : '\\bullet\\tab ';
1576
+ // The number as the list shows it: "3.", "C.", "iii." (see list-markers.ts).
1577
+ if (ordered)
1578
+ counter = itemNumber(child, counter);
1579
+ const marker = ordered ? ` ${markerText(counter, numberStyleOf(list, child))}.\\tab ` : '\\bullet\\tab ';
1348
1580
  // The item's own color and the like; its marker takes them too, as on screen.
1349
1581
  const own = charFormat(child, tag, itemCtx, true);
1350
1582
  rtf += `${own.on}${flowRtf(Array.from(child.childNodes), own.ctx, `${paragraph}\\fi-${LIST_HANG}${marker}`, `${paragraph} `)}${own.off}`;
@@ -1503,7 +1735,7 @@ function tableRtf(table, ctx) {
1503
1735
  const own = charFormat(cell.el, 'td', { ...ctx, inTableCell: true, cellAlign: align }, true);
1504
1736
  content = `${own.on}${withoutTrailingPar(walkChildren(cell.el, own.ctx))}`;
1505
1737
  }
1506
- bodies += `{\\pard\\intbl${align} \\f0 \\sa0 \\li0 \\fi0 ${content}\\cell}`;
1738
+ bodies += `{\\pard\\intbl${align} \\f${ctx.font} \\sa0 \\li0 \\fi0 ${content}\\cell}`;
1507
1739
  c = last + 1;
1508
1740
  }
1509
1741
  const lastRow = r === model.rows.length - 1 ? '\\lastrow' : '';
@@ -1904,16 +2136,24 @@ function isPageBreak(el) {
1904
2136
  const value = (prop) => el.style?.getPropertyValue(prop).trim();
1905
2137
  return value('break-after') === 'page' || value('page-break-after') === 'always';
1906
2138
  }
1907
- /** Color-table index of the element's own color, or null when it sets none. */
2139
+ /**
2140
+ * Color-table index of the color an element's text is written in, or null where that is the
2141
+ * color around it. An element's own color; or the reader's own (0) where the color it has, its
2142
+ * own or the one around it, is one only its background made readable (lostWithoutItsBackground).
2143
+ */
1908
2144
  function colorIndexOf(el, ctx) {
1909
2145
  // Support both inline style.color (spans) and the color attribute (<font>)
1910
2146
  const color = el.style?.color ||
1911
2147
  (el.tagName.toLowerCase() === 'font' ? (el.getAttribute('color') ?? '') : '');
1912
- if (!color)
1913
- return null;
1914
- const c = parseColor(color);
1915
- if (!c)
1916
- return null;
2148
+ const c = color ? parseColor(color) : null;
2149
+ if (!c) {
2150
+ // No color of its own: the one around it, on a background this element or one
2151
+ // between them sets (<div style="color:white"><p style="background:navy">).
2152
+ const around = ctx.color === 0 ? undefined : ctx.colorAt.get(ctx.color);
2153
+ return around && lostWithoutItsBackground(around, el, ctx.root) ? 0 : null;
2154
+ }
2155
+ if (lostWithoutItsBackground(c, el, ctx.root))
2156
+ return ctx.color === 0 ? null : 0;
1917
2157
  return ctx.colorIndex.get(colorKey(c)) ?? null;
1918
2158
  }
1919
2159
  /**