-
Notifications
You must be signed in to change notification settings - Fork 406
/
Clean.ts
395 lines (368 loc) · 12.2 KB
/
Clean.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
import { notWS } from './Constants';
import { TreeIterator, SHOW_ELEMENT_OR_TEXT } from './node/TreeIterator';
import { createElement, empty, detach, replaceWith } from './node/Node';
import { isInline, isLeaf } from './node/Category';
import { fixContainer } from './node/MergeSplit';
import { isLineBreak } from './node/Whitespace';
import type { SquireConfig } from './Editor';
// ---
type StyleRewriter = (
node: HTMLElement,
parent: Node,
config: SquireConfig,
) => HTMLElement;
// ---
const styleToSemantic: Record<
string,
{ regexp: RegExp; replace: (x: any, y: string) => HTMLElement }
> = {
'font-weight': {
regexp: /^bold|^700/i,
replace(): HTMLElement {
return createElement('B');
},
},
'font-style': {
regexp: /^italic/i,
replace(): HTMLElement {
return createElement('I');
},
},
'font-family': {
regexp: notWS,
replace(
classNames: { fontFamily: string },
family: string,
): HTMLElement {
return createElement('SPAN', {
class: classNames.fontFamily,
style: 'font-family:' + family,
});
},
},
'font-size': {
regexp: notWS,
replace(classNames: { fontSize: string }, size: string): HTMLElement {
return createElement('SPAN', {
class: classNames.fontSize,
style: 'font-size:' + size,
});
},
},
'text-decoration': {
regexp: /^underline/i,
replace(): HTMLElement {
return createElement('U');
},
},
};
const replaceStyles = (
node: HTMLElement,
_: Node,
config: SquireConfig,
): HTMLElement => {
const style = node.style;
let newTreeBottom: HTMLElement | undefined;
let newTreeTop: HTMLElement | undefined;
for (const attr in styleToSemantic) {
const converter = styleToSemantic[attr];
const css = style.getPropertyValue(attr);
if (css && converter.regexp.test(css)) {
const el = converter.replace(config.classNames, css);
if (
el.nodeName === node.nodeName &&
el.className === node.className
) {
continue;
}
if (!newTreeTop) {
newTreeTop = el;
}
if (newTreeBottom) {
newTreeBottom.appendChild(el);
}
newTreeBottom = el;
node.style.removeProperty(attr);
}
}
if (newTreeTop && newTreeBottom) {
newTreeBottom.appendChild(empty(node));
if (node.style.cssText) {
node.appendChild(newTreeTop);
} else {
replaceWith(node, newTreeTop);
}
}
return newTreeBottom || node;
};
const replaceWithTag = (tag: string) => {
return (node: HTMLElement, parent: Node) => {
const el = createElement(tag);
const attributes = node.attributes;
for (let i = 0, l = attributes.length; i < l; i += 1) {
const attribute = attributes[i];
el.setAttribute(attribute.name, attribute.value);
}
parent.replaceChild(el, node);
el.appendChild(empty(node));
return el;
};
};
const fontSizes: Record<string, string> = {
'1': '10',
'2': '13',
'3': '16',
'4': '18',
'5': '24',
'6': '32',
'7': '48',
};
const stylesRewriters: Record<string, StyleRewriter> = {
STRONG: replaceWithTag('B'),
EM: replaceWithTag('I'),
INS: replaceWithTag('U'),
STRIKE: replaceWithTag('S'),
SPAN: replaceStyles,
FONT: (
node: HTMLElement,
parent: Node,
config: SquireConfig,
): HTMLElement => {
const font = node as HTMLFontElement;
const face = font.face;
const size = font.size;
let color = font.color;
const classNames = config.classNames;
let fontSpan: HTMLElement;
let sizeSpan: HTMLElement;
let colorSpan: HTMLElement;
let newTreeBottom: HTMLElement | undefined;
let newTreeTop: HTMLElement | undefined;
if (face) {
fontSpan = createElement('SPAN', {
class: classNames.fontFamily,
style: 'font-family:' + face,
});
newTreeTop = fontSpan;
newTreeBottom = fontSpan;
}
if (size) {
sizeSpan = createElement('SPAN', {
class: classNames.fontSize,
style: 'font-size:' + fontSizes[size] + 'px',
});
if (!newTreeTop) {
newTreeTop = sizeSpan;
}
if (newTreeBottom) {
newTreeBottom.appendChild(sizeSpan);
}
newTreeBottom = sizeSpan;
}
if (color && /^#?([\dA-F]{3}){1,2}$/i.test(color)) {
if (color.charAt(0) !== '#') {
color = '#' + color;
}
colorSpan = createElement('SPAN', {
class: classNames.color,
style: 'color:' + color,
});
if (!newTreeTop) {
newTreeTop = colorSpan;
}
if (newTreeBottom) {
newTreeBottom.appendChild(colorSpan);
}
newTreeBottom = colorSpan;
}
if (!newTreeTop || !newTreeBottom) {
newTreeTop = newTreeBottom = createElement('SPAN');
}
parent.replaceChild(newTreeTop, font);
newTreeBottom.appendChild(empty(font));
return newTreeBottom;
},
TT: (node: Node, parent: Node, config: SquireConfig): HTMLElement => {
const el = createElement('SPAN', {
class: config.classNames.fontFamily,
style: 'font-family:menlo,consolas,"courier new",monospace',
});
parent.replaceChild(el, node);
el.appendChild(empty(node));
return el;
},
};
const allowedBlock =
/^(?:A(?:DDRESS|RTICLE|SIDE|UDIO)|BLOCKQUOTE|CAPTION|D(?:[DLT]|IV)|F(?:IGURE|IGCAPTION|OOTER)|H[1-6]|HEADER|L(?:ABEL|EGEND|I)|O(?:L|UTPUT)|P(?:RE)?|SECTION|T(?:ABLE|BODY|D|FOOT|H|HEAD|R)|COL(?:GROUP)?|UL)$/;
const blacklist = /^(?:HEAD|META|STYLE)/;
/*
Two purposes:
1. Remove nodes we don't want, such as weird <o:p> tags, comment nodes
and whitespace nodes.
2. Convert inline tags into our preferred format.
*/
const cleanTree = (
node: Node,
config: SquireConfig,
preserveWS?: boolean,
): Node => {
const children = node.childNodes;
let nonInlineParent = node;
while (isInline(nonInlineParent)) {
nonInlineParent = nonInlineParent.parentNode!;
}
const walker = new TreeIterator<Element | Text>(
nonInlineParent,
SHOW_ELEMENT_OR_TEXT,
);
for (let i = 0, l = children.length; i < l; i += 1) {
let child = children[i];
const nodeName = child.nodeName;
const rewriter = stylesRewriters[nodeName];
if (child instanceof HTMLElement) {
const childLength = child.childNodes.length;
if (rewriter) {
child = rewriter(child, node, config);
} else if (blacklist.test(nodeName)) {
node.removeChild(child);
i -= 1;
l -= 1;
continue;
} else if (!allowedBlock.test(nodeName) && !isInline(child)) {
i -= 1;
l += childLength - 1;
node.replaceChild(empty(child), child);
continue;
}
if (childLength) {
cleanTree(child, config, preserveWS || nodeName === 'PRE');
}
} else {
if (child instanceof Text) {
let data = child.data;
const startsWithWS = !notWS.test(data.charAt(0));
const endsWithWS = !notWS.test(data.charAt(data.length - 1));
if (preserveWS || (!startsWithWS && !endsWithWS)) {
continue;
}
// Iterate through the nodes; if we hit some other content
// before the start of a new block we don't trim
if (startsWithWS) {
walker.currentNode = child;
let sibling;
while ((sibling = walker.previousPONode())) {
if (
sibling.nodeName === 'IMG' ||
(sibling instanceof Text &&
notWS.test(sibling.data))
) {
break;
}
if (!isInline(sibling)) {
sibling = null;
break;
}
}
data = data.replace(/^[ \t\r\n]+/g, sibling ? ' ' : '');
}
if (endsWithWS) {
walker.currentNode = child;
let sibling;
while ((sibling = walker.nextNode())) {
if (
sibling.nodeName === 'IMG' ||
(sibling instanceof Text &&
notWS.test(sibling.data))
) {
break;
}
if (!isInline(sibling)) {
sibling = null;
break;
}
}
data = data.replace(/[ \t\r\n]+$/g, sibling ? ' ' : '');
}
if (data) {
child.data = data;
continue;
}
}
node.removeChild(child);
i -= 1;
l -= 1;
}
}
return node;
};
// ---
const removeEmptyInlines = (node: Node): void => {
const children = node.childNodes;
let l = children.length;
while (l--) {
const child = children[l];
if (child instanceof Element && !isLeaf(child)) {
removeEmptyInlines(child);
if (isInline(child) && !child.firstChild) {
node.removeChild(child);
}
} else if (child instanceof Text && !child.data) {
node.removeChild(child);
}
}
};
// ---
// <br> elements are treated specially, and differently depending on the
// browser, when in rich text editor mode. When adding HTML from external
// sources, we must remove them, replacing the ones that actually affect
// line breaks by wrapping the inline text in a <div>. Browsers that want <br>
// elements at the end of each block will then have them added back in a later
// fixCursor method call.
const cleanupBRs = (
node: Element | DocumentFragment,
root: Element,
keepForBlankLine: boolean,
): void => {
const brs: NodeListOf<HTMLBRElement> = node.querySelectorAll('BR');
const brBreaksLine: boolean[] = [];
let l = brs.length;
// Must calculate whether the <br> breaks a line first, because if we
// have two <br>s next to each other, after the first one is converted
// to a block split, the second will be at the end of a block and
// therefore seem to not be a line break. But in its original context it
// was, so we should also convert it to a block split.
for (let i = 0; i < l; i += 1) {
brBreaksLine[i] = isLineBreak(brs[i], keepForBlankLine);
}
while (l--) {
const br = brs[l];
// Cleanup may have removed it
const parent = br.parentNode;
if (!parent) {
continue;
}
// If it doesn't break a line, just remove it; it's not doing
// anything useful. We'll add it back later if required by the
// browser. If it breaks a line, wrap the content in div tags
// and replace the brs.
if (!brBreaksLine[l]) {
detach(br);
} else if (!isInline(parent)) {
fixContainer(parent, root);
}
}
};
// ---
const escapeHTML = (text: string): string => {
return text
.split('&')
.join('&')
.split('<')
.join('<')
.split('>')
.join('>')
.split('"')
.join('"');
};
// ---
export { cleanTree, cleanupBRs, isLineBreak, removeEmptyInlines, escapeHTML };