svelte-rtf-editor 1.12.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.
- package/README.md +104 -11
- package/dist/RtfViewer.svelte +9 -4
- package/dist/RtfViewer.svelte.d.ts +1 -0
- package/dist/components/InkEditor.svelte +552 -44
- package/dist/components/InkEditor.svelte.d.ts +4 -0
- package/dist/components/Modal.svelte +9 -13
- package/dist/components/Toolbar.svelte +71 -16
- package/dist/components/Toolbar.svelte.d.ts +11 -0
- package/dist/list-markers.d.ts +38 -0
- package/dist/list-markers.js +129 -0
- package/dist/paste-pictures.d.ts +22 -0
- package/dist/paste-pictures.js +57 -0
- package/dist/rtf-parser.d.ts +23 -0
- package/dist/rtf-parser.js +186 -17
- package/dist/rtf-writer.d.ts +55 -3
- package/dist/rtf-writer.js +257 -32
- package/dist/sanitize.d.ts +36 -0
- package/dist/sanitize.js +78 -5
- package/dist/utils.js +22 -1
- package/package.json +1 -1
package/dist/rtf-writer.js
CHANGED
|
@@ -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
|
|
@@ -111,6 +114,79 @@ const NAMED_COLORS = new Map(Object.entries({
|
|
|
111
114
|
function colorKey(c) {
|
|
112
115
|
return `${c.r},${c.g},${c.b}`;
|
|
113
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
|
+
}
|
|
114
190
|
// ── RTF text escaping ──
|
|
115
191
|
function escapeRtf(text) {
|
|
116
192
|
// RTF readers ignore raw CR/LF, so a newline inside text content rendered as
|
|
@@ -549,6 +625,8 @@ export function estimateRtfBytes(editorEl, options = {}) {
|
|
|
549
625
|
// heading's, twice the body.
|
|
550
626
|
const sizeDigits = Math.max(0, String(bodyHalfPoints(options.fontSize) * 2).length - 2);
|
|
551
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();
|
|
552
630
|
for (const img of Array.from(editorEl.querySelectorAll('img'))) {
|
|
553
631
|
const src = img.getAttribute('src') || '';
|
|
554
632
|
const comma = src.indexOf(',');
|
|
@@ -640,6 +718,21 @@ export function estimateRtfBytes(editorEl, options = {}) {
|
|
|
640
718
|
if (target)
|
|
641
719
|
total += LINK_OVERHEAD_BYTES + escapeRtf(target).length;
|
|
642
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
|
+
}
|
|
643
736
|
// Each line break in a code block is written as "\line " (6). It is counted as 1 with
|
|
644
737
|
// the text, or as nothing where it follows another: a run of them is counted there as
|
|
645
738
|
// one space.
|
|
@@ -717,10 +810,17 @@ export function estimateRtfBytes(editorEl, options = {}) {
|
|
|
717
810
|
// A paragraph inside a list item is written at the item's indent (\liN, up to 7).
|
|
718
811
|
if ((tag === 'p' || tag === 'div') && el.parentElement?.tagName === 'LI')
|
|
719
812
|
total += 8;
|
|
720
|
-
// A numbered item's number is counted as one
|
|
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.").
|
|
721
815
|
if (tag === 'ol') {
|
|
722
|
-
|
|
723
|
-
|
|
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
|
+
}
|
|
724
824
|
}
|
|
725
825
|
// A figure with no picture is a paragraph of what it holds: "\pard\intbl\qc\liN " and
|
|
726
826
|
// "\par " (at most 30).
|
|
@@ -785,6 +885,86 @@ function cleanFontName(name) {
|
|
|
785
885
|
const cleaned = first.replace(/[\\{};]/g, '').trim();
|
|
786
886
|
return cleaned || DEFAULT_FONT_FAMILY;
|
|
787
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
|
+
}
|
|
788
968
|
/**
|
|
789
969
|
* Whether a font name is a monospace font's: Courier New, Consolas, Menlo, a "… Mono" family
|
|
790
970
|
* (Roboto Mono, DejaVu Sans Mono), and their PostScript names (CourierNewPSMT, SFMono-Regular).
|
|
@@ -805,13 +985,29 @@ function fontFamilyClass(name) {
|
|
|
805
985
|
return 'swiss';
|
|
806
986
|
}
|
|
807
987
|
/**
|
|
808
|
-
* CSS font-family value for
|
|
809
|
-
*
|
|
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.
|
|
810
996
|
*/
|
|
811
997
|
export function cssFontFamily(name) {
|
|
812
998
|
const font = cleanFontName(name);
|
|
813
|
-
const
|
|
814
|
-
|
|
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)];
|
|
815
1011
|
}
|
|
816
1012
|
/**
|
|
817
1013
|
* A body size in points, as the RTF will carry it: rounded to the half-point
|
|
@@ -852,14 +1048,14 @@ export function htmlToRtf(editorEl, options = {}) {
|
|
|
852
1048
|
colorTable += `\\red${c.r}\\green${c.g}\\blue${c.b};`;
|
|
853
1049
|
}
|
|
854
1050
|
colorTable += '}';
|
|
855
|
-
|
|
856
|
-
|
|
857
|
-
|
|
858
|
-
|
|
859
|
-
|
|
860
|
-
'}';
|
|
1051
|
+
const fonts = {
|
|
1052
|
+
document: fontName.toLowerCase(),
|
|
1053
|
+
offered: new Map(fontChoices(options.fonts).map((choice) => [choice.key, choice])),
|
|
1054
|
+
used: new Map()
|
|
1055
|
+
};
|
|
861
1056
|
const body = walkChildren(editorEl, {
|
|
862
1057
|
colorIndex,
|
|
1058
|
+
colorAt: new Map(colors.map((c, i) => [i + 1, c])),
|
|
863
1059
|
bodySize,
|
|
864
1060
|
inPre: false,
|
|
865
1061
|
listCounter: 0,
|
|
@@ -874,9 +1070,19 @@ export function htmlToRtf(editorEl, options = {}) {
|
|
|
874
1070
|
color: 0,
|
|
875
1071
|
script: null,
|
|
876
1072
|
mono: false,
|
|
1073
|
+
font: 0,
|
|
1074
|
+
fonts,
|
|
877
1075
|
indent: 0,
|
|
878
1076
|
cellAlign: ''
|
|
879
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 += '}';
|
|
880
1086
|
const rtf = '{\\rtf1\\ansi\\ansicpg1252\\deff0' +
|
|
881
1087
|
fontTable +
|
|
882
1088
|
colorTable +
|
|
@@ -890,21 +1096,22 @@ export function htmlToRtf(editorEl, options = {}) {
|
|
|
890
1096
|
// and no newline carries meaning in the output.
|
|
891
1097
|
return rtf.replace(/[\r\n]+/g, ' ');
|
|
892
1098
|
}
|
|
893
|
-
function addColor(colorStr, colorMap) {
|
|
1099
|
+
function addColor(colorStr, colorMap, el, root) {
|
|
894
1100
|
if (!colorStr)
|
|
895
1101
|
return;
|
|
896
1102
|
const c = parseColor(colorStr);
|
|
897
|
-
|
|
1103
|
+
// (A color that is not written is not in the table either.)
|
|
1104
|
+
if (c && !lostWithoutItsBackground(c, el, root))
|
|
898
1105
|
colorMap.set(colorKey(c), c);
|
|
899
1106
|
}
|
|
900
1107
|
function collectColors(root, colorMap) {
|
|
901
1108
|
// (In document order, as the color table has always been written, and without a call per
|
|
902
1109
|
// level of nesting.)
|
|
903
1110
|
for (const el of [root, ...Array.from(root.querySelectorAll('*'))]) {
|
|
904
|
-
addColor(el.style?.color, colorMap);
|
|
1111
|
+
addColor(el.style?.color, colorMap, el, root);
|
|
905
1112
|
// <font color="..."> is produced by execCommand('foreColor')
|
|
906
1113
|
if (el.tagName?.toLowerCase() === 'font')
|
|
907
|
-
addColor(el.getAttribute('color'), colorMap);
|
|
1114
|
+
addColor(el.getAttribute('color'), colorMap, el, root);
|
|
908
1115
|
}
|
|
909
1116
|
}
|
|
910
1117
|
/** How many elements deep the walker is (see MAX_ELEMENT_DEPTH). */
|
|
@@ -1009,7 +1216,7 @@ function walkNodeAt(node, ctx, restate, endLooseText) {
|
|
|
1009
1216
|
rtf += `\\fs${size}${ctx.bold ? '' : '\\b'} ${own.on}${walkChildren(el, own.ctx)}${own.off}${ctx.bold ? '' : '\\b0'}\\fs${ctx.size} `;
|
|
1010
1217
|
break;
|
|
1011
1218
|
}
|
|
1012
|
-
rtf += `\\pard${inCell(ctx)}${headingLayout(el, ctx)}\\
|
|
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 `;
|
|
1013
1220
|
break;
|
|
1014
1221
|
}
|
|
1015
1222
|
case 'p':
|
|
@@ -1089,7 +1296,7 @@ function walkNodeAt(node, ctx, restate, endLooseText) {
|
|
|
1089
1296
|
}
|
|
1090
1297
|
case 'pre': {
|
|
1091
1298
|
const size = scaled(ctx, PRE_SCALE);
|
|
1092
|
-
rtf += `\\pard${inCell(ctx)}${cellAlign(ctx)}${liControl(ctx.indent + leftMarginTwips(el))}\\f1\\fs${size} ${walkChildren(el, { ...ctx, inPre: true, size })}\\
|
|
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 `;
|
|
1093
1300
|
break;
|
|
1094
1301
|
}
|
|
1095
1302
|
case 'hr':
|
|
@@ -1115,7 +1322,7 @@ function walkNodeAt(node, ctx, restate, endLooseText) {
|
|
|
1115
1322
|
case 'code': {
|
|
1116
1323
|
const own = charFormat(el, tag, ctx);
|
|
1117
1324
|
if (!ctx.inPre && !ctx.mono) {
|
|
1118
|
-
rtf += `${own.on}\\f1 ${walkChildren(el, { ...own.ctx, mono: true })}\\
|
|
1325
|
+
rtf += `${own.on}\\f1 ${walkChildren(el, { ...own.ctx, mono: true })}\\f${own.ctx.font} ${own.off}`;
|
|
1119
1326
|
}
|
|
1120
1327
|
else {
|
|
1121
1328
|
rtf += `${own.on}${walkChildren(el, own.ctx)}${own.off}`;
|
|
@@ -1255,12 +1462,19 @@ function charFormat(el, rawTag, ctx, block = false) {
|
|
|
1255
1462
|
const script = vertical === 'super' ? 'super' : vertical === 'sub' ? 'sub' : vertical === 'baseline' ? null : (tagFormat.script ?? ctx.script);
|
|
1256
1463
|
const color = colorIndexOf(el, ctx);
|
|
1257
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;
|
|
1258
1468
|
let on = '';
|
|
1259
1469
|
let off = '';
|
|
1260
1470
|
if (color != null) {
|
|
1261
1471
|
on += `\\cf${color} `;
|
|
1262
1472
|
off = `\\cf${ctx.color} `;
|
|
1263
1473
|
}
|
|
1474
|
+
if (font != null) {
|
|
1475
|
+
on += `\\f${font} `;
|
|
1476
|
+
off = `\\f${ctx.font} ${off}`;
|
|
1477
|
+
}
|
|
1264
1478
|
if (size != null) {
|
|
1265
1479
|
on += `\\fs${size} `;
|
|
1266
1480
|
off = `\\fs${ctx.size} ${off}`;
|
|
@@ -1287,7 +1501,7 @@ function charFormat(el, rawTag, ctx, block = false) {
|
|
|
1287
1501
|
}
|
|
1288
1502
|
if (!on)
|
|
1289
1503
|
return { on, off, ctx };
|
|
1290
|
-
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 } };
|
|
1291
1505
|
}
|
|
1292
1506
|
/** Whether an element is shown and holds text or a picture: an empty <form> or a hidden <input> does not. */
|
|
1293
1507
|
function holdsSomething(el) {
|
|
@@ -1320,7 +1534,8 @@ const LIST_HANG = 360;
|
|
|
1320
1534
|
/**
|
|
1321
1535
|
* A <ul> or <ol>: one hanging paragraph per item, opened by a bullet or the item's number and a
|
|
1322
1536
|
* tab. A list inside an item, or straight inside the list (<ul><ul>, as some editors nest), is
|
|
1323
|
-
* 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.
|
|
1324
1539
|
*/
|
|
1325
1540
|
function listRtf(list, ctx) {
|
|
1326
1541
|
// A list straight inside a list is written from here, not through walkNode, so the depth is
|
|
@@ -1341,8 +1556,7 @@ function listRtfAt(list, ctx) {
|
|
|
1341
1556
|
// is negative for a list nested by less than half an inch.
|
|
1342
1557
|
const margin = lengthTwips(list.style?.marginLeft, true) ?? 0;
|
|
1343
1558
|
const left = Math.max(LIST_HANG, ctx.indent + margin + LIST_STEP);
|
|
1344
|
-
|
|
1345
|
-
let counter = ordered && Number.isFinite(start) ? start : 1;
|
|
1559
|
+
let counter = ordered ? listStart(list) : 1;
|
|
1346
1560
|
const itemCtx = { ...ctx, indent: left, cellAlign: listAlign(ctx) };
|
|
1347
1561
|
const paragraph = `\\pard${inCell(ctx)}${listAlign(ctx)}${liControl(left)}`;
|
|
1348
1562
|
let rtf = '';
|
|
@@ -1359,7 +1573,10 @@ function listRtfAt(list, ctx) {
|
|
|
1359
1573
|
continue;
|
|
1360
1574
|
if (tag === 'li') {
|
|
1361
1575
|
flushLoose();
|
|
1362
|
-
|
|
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 ';
|
|
1363
1580
|
// The item's own color and the like; its marker takes them too, as on screen.
|
|
1364
1581
|
const own = charFormat(child, tag, itemCtx, true);
|
|
1365
1582
|
rtf += `${own.on}${flowRtf(Array.from(child.childNodes), own.ctx, `${paragraph}\\fi-${LIST_HANG}${marker}`, `${paragraph} `)}${own.off}`;
|
|
@@ -1518,7 +1735,7 @@ function tableRtf(table, ctx) {
|
|
|
1518
1735
|
const own = charFormat(cell.el, 'td', { ...ctx, inTableCell: true, cellAlign: align }, true);
|
|
1519
1736
|
content = `${own.on}${withoutTrailingPar(walkChildren(cell.el, own.ctx))}`;
|
|
1520
1737
|
}
|
|
1521
|
-
bodies += `{\\pard\\intbl${align} \\
|
|
1738
|
+
bodies += `{\\pard\\intbl${align} \\f${ctx.font} \\sa0 \\li0 \\fi0 ${content}\\cell}`;
|
|
1522
1739
|
c = last + 1;
|
|
1523
1740
|
}
|
|
1524
1741
|
const lastRow = r === model.rows.length - 1 ? '\\lastrow' : '';
|
|
@@ -1919,16 +2136,24 @@ function isPageBreak(el) {
|
|
|
1919
2136
|
const value = (prop) => el.style?.getPropertyValue(prop).trim();
|
|
1920
2137
|
return value('break-after') === 'page' || value('page-break-after') === 'always';
|
|
1921
2138
|
}
|
|
1922
|
-
/**
|
|
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
|
+
*/
|
|
1923
2144
|
function colorIndexOf(el, ctx) {
|
|
1924
2145
|
// Support both inline style.color (spans) and the color attribute (<font>)
|
|
1925
2146
|
const color = el.style?.color ||
|
|
1926
2147
|
(el.tagName.toLowerCase() === 'font' ? (el.getAttribute('color') ?? '') : '');
|
|
1927
|
-
|
|
1928
|
-
|
|
1929
|
-
|
|
1930
|
-
|
|
1931
|
-
|
|
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;
|
|
1932
2157
|
return ctx.colorIndex.get(colorKey(c)) ?? null;
|
|
1933
2158
|
}
|
|
1934
2159
|
/**
|
package/dist/sanitize.d.ts
CHANGED
|
@@ -30,11 +30,27 @@ export interface KeepOptions {
|
|
|
30
30
|
keepAttributes?: readonly string[];
|
|
31
31
|
/** Class names that stay in an element's class list. */
|
|
32
32
|
keepClasses?: readonly string[];
|
|
33
|
+
/**
|
|
34
|
+
* The fonts text may be set in, beside the document's own (the editor's `fonts`): a font
|
|
35
|
+
* name, or a CSS list whose first family is the name. Where this is given, a font that is
|
|
36
|
+
* not among them is taken off the text; given as an empty list, every font but the
|
|
37
|
+
* document's is. Where it is not given, fonts are left as they come. (The editor always
|
|
38
|
+
* gives its list, so an editor that offers no fonts lets none in.)
|
|
39
|
+
*/
|
|
40
|
+
fonts?: readonly string[];
|
|
41
|
+
/** The document's own font (the editor's `fontFamily`), which text may always name. Only read where `fonts` is given. */
|
|
42
|
+
fontFamily?: string;
|
|
33
43
|
}
|
|
34
44
|
/** The same, as the sets the sanitizer reads. */
|
|
35
45
|
export interface Kept {
|
|
36
46
|
attributes: ReadonlySet<string>;
|
|
37
47
|
classes: ReadonlySet<string>;
|
|
48
|
+
/**
|
|
49
|
+
* The fonts text may name, by the name each is looked up by, with what is written for it:
|
|
50
|
+
* the fonts offered, and the document's own. Not there where no list of fonts was given
|
|
51
|
+
* at all: then fonts are left as they come.
|
|
52
|
+
*/
|
|
53
|
+
fonts?: ReadonlyMap<string, string>;
|
|
38
54
|
}
|
|
39
55
|
/**
|
|
40
56
|
* What an application asked to have kept (the editor's `keepAttributes` and `keepClasses`), as
|
|
@@ -93,6 +109,26 @@ export interface PasteNotes {
|
|
|
93
109
|
* words. So a paste that has both is words where its HTML has any, and a picture where not.
|
|
94
110
|
*/
|
|
95
111
|
export declare function pasteHasWords(html: string): boolean;
|
|
112
|
+
/**
|
|
113
|
+
* The HTML of a paste that holds a frame, made safe and without the frame; or null where it
|
|
114
|
+
* holds none, which is nearly every paste.
|
|
115
|
+
*
|
|
116
|
+
* A frame is not kept in a document, and until 1.12.0 it was taken out after the browser had
|
|
117
|
+
* pasted it, with all else that is not safe. But a frame put in a page is a page being loaded,
|
|
118
|
+
* and Safari forgets every step it could undo when one is taken out again: after a paste that
|
|
119
|
+
* held a frame (a part of a web page with a video or an advertisement in it) nothing done
|
|
120
|
+
* before the paste could be undone, and after Undo and Redo of it, not the paste either. So a
|
|
121
|
+
* paste that holds a frame is put in by the editor, without it.
|
|
122
|
+
*
|
|
123
|
+
* What the editor puts in itself has to be safe before it is in the page, all of it. A
|
|
124
|
+
* browser's own paste takes the scripts and the handlers out of what it pastes; the command
|
|
125
|
+
* the editor inserts with does not, and a handler runs as soon as its element is in the page
|
|
126
|
+
* (`<video onerror>`, `<svg><image onerror>`), whatever is taken out a moment later. So the
|
|
127
|
+
* whole of it is made safe here, in a document of its own where nothing is loaded and no script
|
|
128
|
+
* is run, as HTML from anywhere else is. (For a time only the frames were taken out, and a
|
|
129
|
+
* page one copied from could run script in the application by having a frame in the copy.)
|
|
130
|
+
*/
|
|
131
|
+
export declare function pasteWithoutFrames(html: string, keep?: Kept): string | null;
|
|
96
132
|
/**
|
|
97
133
|
* Read from a paste's HTML what the browser's own paste may lose: null where it holds neither
|
|
98
134
|
* Word's hidden text nor a text box, which is nearly every paste.
|
package/dist/sanitize.js
CHANGED
|
@@ -24,7 +24,7 @@
|
|
|
24
24
|
* sight (a margin below zero, a padding of thousands of pixels, a first line that starts left
|
|
25
25
|
* of its paragraph, text of no size).
|
|
26
26
|
*/
|
|
27
|
-
import { linkTarget } from './rtf-writer.js';
|
|
27
|
+
import { cssFontFamily, fontChoices, fontKey, linkTarget, sameFontList } from './rtf-writer.js';
|
|
28
28
|
import { isSafeImageUrl } from './images.js';
|
|
29
29
|
/** Elements taken out with everything in them. */
|
|
30
30
|
const REMOVED_TAGS = new Set([
|
|
@@ -153,7 +153,20 @@ export function keptMarks(options) {
|
|
|
153
153
|
// `md:flex`, `w-1/2` and `résumé` without saying so, and kept nothing out: a name is only
|
|
154
154
|
// ever compared with the classes an element has, and one with a space in it is none of them.
|
|
155
155
|
const classes = new Set(namesIn(options?.keepClasses));
|
|
156
|
-
|
|
156
|
+
if (options?.fonts == null)
|
|
157
|
+
return { attributes, classes };
|
|
158
|
+
// The document font last: a list that names it too does not make it a font of the text's own.
|
|
159
|
+
const fonts = new Map(fontChoices(options.fonts).map((choice) => [choice.key, choice.css]));
|
|
160
|
+
const own = cssFontFamily(options?.fontFamily);
|
|
161
|
+
fonts.set(fontKey(own), own);
|
|
162
|
+
return { attributes, classes, fonts };
|
|
163
|
+
}
|
|
164
|
+
/**
|
|
165
|
+
* A font value as it may stay: what the application wrote for that font. Null where the font is
|
|
166
|
+
* not one it offers.
|
|
167
|
+
*/
|
|
168
|
+
function offeredFont(value, keep) {
|
|
169
|
+
return keep.fonts?.get(fontKey(value)) ?? null;
|
|
157
170
|
}
|
|
158
171
|
/**
|
|
159
172
|
* The names in one of the two settings. A caller without types can pass one name where a list
|
|
@@ -190,6 +203,8 @@ const TAG_ATTRIBUTES = table({
|
|
|
190
203
|
font: ['color', 'size', 'face'],
|
|
191
204
|
details: ['open']
|
|
192
205
|
});
|
|
206
|
+
/** A color as `bgcolor` gives one: hex digits with or without "#", a name, rgb(). Nothing else is made a style of. */
|
|
207
|
+
const BGCOLOR = /^(#?[0-9a-f]{3,8}|[a-z]{3,30}|rgba?\([\d\s,.%]+\))$/i;
|
|
193
208
|
/**
|
|
194
209
|
* The one class that means something here: Safari's wrapper around a typed tab. Any other class
|
|
195
210
|
* would take on whatever the page's own stylesheet gives that name.
|
|
@@ -410,7 +425,7 @@ function unreadAlone(text, el) {
|
|
|
410
425
|
probe.setAttribute('style', text);
|
|
411
426
|
return !probe.style || probe.style.length === 0;
|
|
412
427
|
}
|
|
413
|
-
function sanitizeStyle(el, tag, fonts) {
|
|
428
|
+
function sanitizeStyle(el, tag, fonts, keep) {
|
|
414
429
|
const raw = el.getAttribute('style');
|
|
415
430
|
if (raw === null)
|
|
416
431
|
return;
|
|
@@ -421,6 +436,8 @@ function sanitizeStyle(el, tag, fonts) {
|
|
|
421
436
|
}
|
|
422
437
|
const wordHidden = WORD_HIDDEN.test(raw);
|
|
423
438
|
const drop = [];
|
|
439
|
+
/** The font to write in place of the one named, where it is offered under another spelling. */
|
|
440
|
+
let font = null;
|
|
424
441
|
// The size of this element's text first: its other lengths may be counted in it.
|
|
425
442
|
let fontPx = fontPxAround(el, fonts);
|
|
426
443
|
const fontSize = style.getPropertyValue('font-size');
|
|
@@ -437,6 +454,16 @@ function sanitizeStyle(el, tag, fonts) {
|
|
|
437
454
|
const value = style.getPropertyValue(name);
|
|
438
455
|
if (name === 'font-size')
|
|
439
456
|
continue;
|
|
457
|
+
if (name === 'font-family' && keep?.fonts) {
|
|
458
|
+
// Only a font the application offers, and written as it wrote it: the name and
|
|
459
|
+
// what to show where the font is missing.
|
|
460
|
+
font = offeredFont(value, keep);
|
|
461
|
+
if (font === null)
|
|
462
|
+
drop.push(name);
|
|
463
|
+
else if (sameFontList(font, value))
|
|
464
|
+
font = null;
|
|
465
|
+
continue;
|
|
466
|
+
}
|
|
440
467
|
const noPicture = NO_BORDER_IMAGE.get(name);
|
|
441
468
|
if (noPicture !== undefined) {
|
|
442
469
|
// `border: 1px solid` also says "no border picture", and a browser lists that with
|
|
@@ -478,10 +505,12 @@ function sanitizeStyle(el, tag, fonts) {
|
|
|
478
505
|
new Set(names).size !== names.length ||
|
|
479
506
|
names.some((name) => !STYLE_PROPERTY.test(name) || !read.some((property) => property === name || property.startsWith(`${name}-`))) ||
|
|
480
507
|
(shortAndPart && declared.some((declaration) => unreadAlone(declaration.text, el)));
|
|
481
|
-
if (drop.length === 0 && !unread)
|
|
508
|
+
if (drop.length === 0 && !unread && font === null)
|
|
482
509
|
return;
|
|
483
510
|
for (const name of drop)
|
|
484
511
|
style.removeProperty(name);
|
|
512
|
+
if (font !== null)
|
|
513
|
+
style.setProperty('font-family', font);
|
|
485
514
|
// What Word hid stays hidden, in a way the browser keeps: mso-hide is not a property it
|
|
486
515
|
// reads, so the text showed on screen while the RTF left it out.
|
|
487
516
|
if (wordHidden)
|
|
@@ -515,6 +544,13 @@ function namesAGlobal(id) {
|
|
|
515
544
|
}
|
|
516
545
|
function sanitizeAttributes(el, tag, fonts, idTaken, keep) {
|
|
517
546
|
const own = TAG_ATTRIBUTES.get(tag);
|
|
547
|
+
// `bgcolor`, as older pages and mail shade a table and its cells, is not kept. The shading
|
|
548
|
+
// is, as the style it stands for: without it, words set in white to stand on it were white
|
|
549
|
+
// on the white of the page, and the writer could not tell that they had had a background.
|
|
550
|
+
const shade = (el.getAttribute('bgcolor') ?? '').trim();
|
|
551
|
+
if (BGCOLOR.test(shade) && el.style && !el.style.backgroundColor) {
|
|
552
|
+
el.style.backgroundColor = /^[0-9a-f]{6}$/i.test(shade) ? `#${shade}` : shade;
|
|
553
|
+
}
|
|
518
554
|
for (const attr of Array.from(el.attributes)) {
|
|
519
555
|
const name = attr.name.toLowerCase();
|
|
520
556
|
if (name === 'class') {
|
|
@@ -560,7 +596,15 @@ function sanitizeAttributes(el, tag, fonts, idTaken, keep) {
|
|
|
560
596
|
if (tag === 'img' && el.hasAttribute('src') && !isSafeImageUrl(el.getAttribute('src') || '')) {
|
|
561
597
|
el.removeAttribute('src');
|
|
562
598
|
}
|
|
563
|
-
|
|
599
|
+
if (tag === 'font' && keep?.fonts && el.hasAttribute('face')) {
|
|
600
|
+
const face = el.getAttribute('face');
|
|
601
|
+
const font = offeredFont(face, keep);
|
|
602
|
+
if (font === null)
|
|
603
|
+
el.removeAttribute('face');
|
|
604
|
+
else if (!sameFontList(font, face))
|
|
605
|
+
el.setAttribute('face', font);
|
|
606
|
+
}
|
|
607
|
+
sanitizeStyle(el, tag, fonts, keep);
|
|
564
608
|
}
|
|
565
609
|
/**
|
|
566
610
|
* Whether an element is a formula's copy for a screen reader, beside the same formula written
|
|
@@ -738,6 +782,35 @@ export function pasteHasWords(html) {
|
|
|
738
782
|
el.remove();
|
|
739
783
|
return (body.textContent ?? '').trim() !== '';
|
|
740
784
|
}
|
|
785
|
+
/** A frame in a paste's HTML: `<iframe>`, and the `<frame>` of an older page. */
|
|
786
|
+
const FRAME = /<i?frame[\s>/]/i;
|
|
787
|
+
/**
|
|
788
|
+
* The HTML of a paste that holds a frame, made safe and without the frame; or null where it
|
|
789
|
+
* holds none, which is nearly every paste.
|
|
790
|
+
*
|
|
791
|
+
* A frame is not kept in a document, and until 1.12.0 it was taken out after the browser had
|
|
792
|
+
* pasted it, with all else that is not safe. But a frame put in a page is a page being loaded,
|
|
793
|
+
* and Safari forgets every step it could undo when one is taken out again: after a paste that
|
|
794
|
+
* held a frame (a part of a web page with a video or an advertisement in it) nothing done
|
|
795
|
+
* before the paste could be undone, and after Undo and Redo of it, not the paste either. So a
|
|
796
|
+
* paste that holds a frame is put in by the editor, without it.
|
|
797
|
+
*
|
|
798
|
+
* What the editor puts in itself has to be safe before it is in the page, all of it. A
|
|
799
|
+
* browser's own paste takes the scripts and the handlers out of what it pastes; the command
|
|
800
|
+
* the editor inserts with does not, and a handler runs as soon as its element is in the page
|
|
801
|
+
* (`<video onerror>`, `<svg><image onerror>`), whatever is taken out a moment later. So the
|
|
802
|
+
* whole of it is made safe here, in a document of its own where nothing is loaded and no script
|
|
803
|
+
* is run, as HTML from anywhere else is. (For a time only the frames were taken out, and a
|
|
804
|
+
* page one copied from could run script in the application by having a frame in the copy.)
|
|
805
|
+
*/
|
|
806
|
+
export function pasteWithoutFrames(html, keep) {
|
|
807
|
+
if (!FRAME.test(html) || typeof DOMParser === 'undefined')
|
|
808
|
+
return null;
|
|
809
|
+
// (None after all: the letters were text, in a line of code or in a comment.)
|
|
810
|
+
if (new DOMParser().parseFromString(html, 'text/html').querySelector('iframe, frame, frameset') === null)
|
|
811
|
+
return null;
|
|
812
|
+
return safeBody(html, undefined, keep)?.innerHTML ?? '';
|
|
813
|
+
}
|
|
741
814
|
/**
|
|
742
815
|
* Read from a paste's HTML what the browser's own paste may lose: null where it holds neither
|
|
743
816
|
* Word's hidden text nor a text box, which is nearly every paste.
|