This repository has been archived by the owner on Feb 6, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 2.6k
/
convertFromHTMLToContentBlocks.js
669 lines (589 loc) · 16.3 KB
/
convertFromHTMLToContentBlocks.js
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
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
/**
* Copyright (c) 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule convertFromHTMLToContentBlocks
* @typechecks
* @flow
*/
'use strict';
const CharacterMetadata = require('CharacterMetadata');
const ContentBlock = require('ContentBlock');
const DefaultDraftBlockRenderMap = require('DefaultDraftBlockRenderMap');
const DraftEntity = require('DraftEntity');
const Immutable = require('immutable');
const URI = require('URI');
const generateRandomKey = require('generateRandomKey');
const getSafeBodyFromHTML = require('getSafeBodyFromHTML');
const invariant = require('invariant');
const nullthrows = require('nullthrows');
const sanitizeDraftText = require('sanitizeDraftText');
const {Set} = require('immutable');
import type {DraftBlockRenderMap} from 'DraftBlockRenderMap';
import type {DraftBlockRenderConfig} from 'DraftBlockRenderConfig';
import type {DraftBlockType} from 'DraftBlockType';
import type {DraftInlineStyle} from 'DraftInlineStyle';
import type {EntityMap} from 'EntityMap';
var {
List,
OrderedSet,
} = Immutable;
var NBSP = ' ';
var SPACE = ' ';
// Arbitrary max indent
var MAX_DEPTH = 4;
// used for replacing characters in HTML
var REGEX_CR = new RegExp('\r', 'g');
var REGEX_LF = new RegExp('\n', 'g');
var REGEX_NBSP = new RegExp(NBSP, 'g');
var REGEX_CARRIAGE = new RegExp(' ?', 'g');
var REGEX_ZWS = new RegExp('​?', 'g');
// https://developer.mozilla.org/en-US/docs/Web/CSS/font-weight
const boldValues = ['bold', 'bolder', '500', '600', '700', '800', '900'];
const notBoldValues = ['light', 'lighter', '100', '200', '300', '400'];
// Block tag flow is different because LIs do not have
// a deterministic style ;_;
var inlineTags = {
b: 'BOLD',
code: 'CODE',
del: 'STRIKETHROUGH',
em: 'ITALIC',
i: 'ITALIC',
s: 'STRIKETHROUGH',
strike: 'STRIKETHROUGH',
strong: 'BOLD',
u: 'UNDERLINE',
};
var anchorAttr = [
'className',
'href',
'rel',
'target',
'title',
];
const imgAttr = [
'alt',
'className',
'height',
'src',
'width',
];
var lastBlock;
type Block = {
type: DraftBlockType,
depth: number,
};
type Chunk = {
text: string,
inlines: Array<DraftInlineStyle>,
entities: Array<string>,
blocks: Array<Block>,
};
function getEmptyChunk(): Chunk {
return {
text: '',
inlines: [],
entities: [],
blocks: [],
};
}
function getWhitespaceChunk(inEntity: ?string): Chunk {
var entities = new Array(1);
if (inEntity) {
entities[0] = inEntity;
}
return {
text: SPACE,
inlines: [OrderedSet()],
entities,
blocks: [],
};
}
function getSoftNewlineChunk(): Chunk {
return {
text: '\n',
inlines: [OrderedSet()],
entities: new Array(1),
blocks: [],
};
}
function getBlockDividerChunk(block: DraftBlockType, depth: number): Chunk {
return {
text: '\r',
inlines: [OrderedSet()],
entities: new Array(1),
blocks: [{
type: block,
depth: Math.max(0, Math.min(MAX_DEPTH, depth)),
}],
};
}
function getListBlockType(
tag: string,
lastList: ?string,
): ?DraftBlockType {
if (tag === 'li') {
return lastList === 'ol' ? 'ordered-list-item' : 'unordered-list-item';
}
return null;
}
function getBlockMapSupportedTags(
blockRenderMap: DraftBlockRenderMap,
): Array<string> {
const unstyledElement = blockRenderMap.get('unstyled').element;
let tags = new Set([]);
blockRenderMap.forEach((draftBlock: DraftBlockRenderConfig) => {
if (draftBlock.aliasedElements) {
draftBlock.aliasedElements.forEach((tag) => {
tags = tags.add(tag);
});
}
tags = tags.add(draftBlock.element);
});
return tags
.filter((tag) => tag && tag !== unstyledElement)
.toArray()
.sort();
}
// custom element conversions
function getMultiMatchedType(
tag: string,
lastList: ?string,
multiMatchExtractor: Array<Function>,
): ?DraftBlockType {
for (let ii = 0; ii < multiMatchExtractor.length; ii++) {
const matchType = multiMatchExtractor[ii](tag, lastList);
if (matchType) {
return matchType;
}
}
return null;
}
function getBlockTypeForTag(
tag: string,
lastList: ?string,
blockRenderMap: DraftBlockRenderMap,
): DraftBlockType {
const matchedTypes = blockRenderMap
.filter((draftBlock: DraftBlockRenderConfig) => (
draftBlock.element === tag ||
draftBlock.wrapper === tag ||
(
draftBlock.aliasedElements &&
draftBlock.aliasedElements.some(alias => alias === tag)
)
))
.keySeq()
.toSet()
.toArray()
.sort();
// if we dont have any matched type, return unstyled
// if we have one matched type return it
// if we have multi matched types use the multi-match function to gather type
switch (matchedTypes.length) {
case 0:
return 'unstyled';
case 1:
return matchedTypes[0];
default:
return (
getMultiMatchedType(tag, lastList, [getListBlockType]) ||
'unstyled'
);
}
}
function processInlineTag(
tag: string,
node: Node,
currentStyle: DraftInlineStyle,
): DraftInlineStyle {
var styleToCheck = inlineTags[tag];
if (styleToCheck) {
currentStyle = currentStyle.add(styleToCheck).toOrderedSet();
} else if (node instanceof HTMLElement) {
const htmlElement = node;
currentStyle = currentStyle.withMutations(style => {
const fontWeight = htmlElement.style.fontWeight;
const fontStyle = htmlElement.style.fontStyle;
const textDecoration = htmlElement.style.textDecoration;
if (boldValues.indexOf(fontWeight) >= 0) {
style.add('BOLD');
} else if (notBoldValues.indexOf(fontWeight) >= 0) {
style.remove('BOLD');
}
if (fontStyle === 'italic') {
style.add('ITALIC');
} else if (fontStyle === 'normal') {
style.remove('ITALIC');
}
if (textDecoration === 'underline') {
style.add('UNDERLINE');
}
if (textDecoration === 'line-through') {
style.add('STRIKETHROUGH');
}
if (textDecoration === 'none') {
style.remove('UNDERLINE');
style.remove('STRIKETHROUGH');
}
}).toOrderedSet();
}
return currentStyle;
}
function joinChunks(A: Chunk, B: Chunk): Chunk {
// Sometimes two blocks will touch in the DOM and we need to strip the
// extra delimiter to preserve niceness.
var lastInA = A.text.slice(-1);
var firstInB = B.text.slice(0, 1);
if (
lastInA === '\r' &&
firstInB === '\r'
) {
A.text = A.text.slice(0, -1);
A.inlines.pop();
A.entities.pop();
A.blocks.pop();
}
// Kill whitespace after blocks
if (
lastInA === '\r'
) {
if (B.text === SPACE || B.text === '\n') {
return A;
} else if (firstInB === SPACE || firstInB === '\n') {
B.text = B.text.slice(1);
B.inlines.shift();
B.entities.shift();
}
}
return {
text: A.text + B.text,
inlines: A.inlines.concat(B.inlines),
entities: A.entities.concat(B.entities),
blocks: A.blocks.concat(B.blocks),
};
}
/**
* Check to see if we have anything like <p> <blockquote> <h1>... to create
* block tags from. If we do, we can use those and ignore <div> tags. If we
* don't, we can treat <div> tags as meaningful (unstyled) blocks.
*/
function containsSemanticBlockMarkup(
html: string,
blockTags: Array<string>,
): boolean {
return blockTags.some(tag => html.indexOf('<' + tag) !== -1);
}
function hasValidLinkText(link: Node): boolean {
invariant(
link instanceof HTMLAnchorElement,
'Link must be an HTMLAnchorElement.',
);
var protocol = link.protocol;
return (
protocol === 'http:' ||
protocol === 'https:' ||
protocol === 'mailto:'
);
}
function genFragment(
entityMap: EntityMap,
node: Node,
inlineStyle: DraftInlineStyle,
lastList: string,
inBlock: ?string,
blockTags: Array<string>,
depth: number,
blockRenderMap: DraftBlockRenderMap,
inEntity?: string,
): {chunk: Chunk, entityMap: EntityMap} {
var nodeName = node.nodeName.toLowerCase();
var newBlock = false;
var nextBlockType = 'unstyled';
var lastLastBlock = lastBlock;
let newEntityMap = entityMap;
// Base Case
if (nodeName === '#text') {
var text = node.textContent;
if (text.trim() === '' && inBlock !== 'pre') {
return {chunk: getWhitespaceChunk(inEntity), entityMap};
}
if (inBlock !== 'pre') {
// Can't use empty string because MSWord
text = text.replace(REGEX_LF, SPACE);
}
// save the last block so we can use it later
lastBlock = nodeName;
return {
chunk: {
text,
inlines: Array(text.length).fill(inlineStyle),
entities: Array(text.length).fill(inEntity),
blocks: [],
},
entityMap,
};
}
// save the last block so we can use it later
lastBlock = nodeName;
// BR tags
if (nodeName === 'br') {
if (
lastLastBlock === 'br' &&
(
!inBlock ||
getBlockTypeForTag(inBlock, lastList, blockRenderMap) === 'unstyled'
)
) {
return {chunk: getBlockDividerChunk('unstyled', depth), entityMap};
}
return {chunk: getSoftNewlineChunk(), entityMap};
}
// IMG tags
if (
nodeName === 'img' &&
node instanceof HTMLImageElement &&
node.attributes.getNamedItem('src') &&
node.attributes.getNamedItem('src').value
) {
const image: HTMLImageElement = node;
const entityConfig = {};
imgAttr.forEach((attr) => {
const imageAttribute = image.getAttribute(attr);
if (imageAttribute) {
entityConfig[attr] = imageAttribute;
}
});
const imageURI = new URI(entityConfig.src).toString();
node.textContent = imageURI; // Output src if no decorator
// TODO: update this when we remove DraftEntity entirely
inEntity = DraftEntity.__create(
'IMAGE',
'MUTABLE',
entityConfig || {},
);
}
var chunk = getEmptyChunk();
var newChunk: ?Chunk = null;
// Inline tags
inlineStyle = processInlineTag(nodeName, node, inlineStyle);
// Handle lists
if (nodeName === 'ul' || nodeName === 'ol') {
if (lastList) {
depth += 1;
}
lastList = nodeName;
}
// Block Tags
if (!inBlock && blockTags.indexOf(nodeName) !== -1) {
chunk = getBlockDividerChunk(
getBlockTypeForTag(nodeName, lastList, blockRenderMap),
depth,
);
inBlock = nodeName;
newBlock = true;
} else if (lastList && inBlock === 'li' && nodeName === 'li') {
chunk = getBlockDividerChunk(
getBlockTypeForTag(nodeName, lastList, blockRenderMap),
depth,
);
inBlock = nodeName;
newBlock = true;
nextBlockType = lastList === 'ul' ?
'unordered-list-item' :
'ordered-list-item';
}
// Recurse through children
var child: ?Node = node.firstChild;
if (child != null) {
nodeName = child.nodeName.toLowerCase();
}
var entityId: ?string = null;
while (child) {
if (
child instanceof HTMLAnchorElement &&
child.href &&
hasValidLinkText(child)
) {
const anchor: HTMLAnchorElement = child;
const entityConfig = {};
anchorAttr.forEach((attr) => {
const anchorAttribute = anchor.getAttribute(attr);
if (anchorAttribute) {
entityConfig[attr] = anchorAttribute;
}
});
entityConfig.url = new URI(anchor.href).toString();
// TODO: update this when we remove DraftEntity completely
entityId = DraftEntity.__create(
'LINK',
'MUTABLE',
entityConfig || {},
);
} else {
entityId = undefined;
}
const {
chunk: generatedChunk,
entityMap: maybeUpdatedEntityMap,
} = genFragment(
newEntityMap,
child,
inlineStyle,
lastList,
inBlock,
blockTags,
depth,
blockRenderMap,
entityId || inEntity,
);
newChunk = generatedChunk;
newEntityMap = maybeUpdatedEntityMap;
chunk = joinChunks(chunk, newChunk);
var sibling: ?Node = child.nextSibling;
// Put in a newline to break up blocks inside blocks
if (
sibling &&
blockTags.indexOf(nodeName) >= 0 &&
inBlock
) {
chunk = joinChunks(chunk, getSoftNewlineChunk());
}
if (sibling) {
nodeName = sibling.nodeName.toLowerCase();
}
child = sibling;
}
if (newBlock) {
chunk = joinChunks(
chunk,
getBlockDividerChunk(nextBlockType, depth),
);
}
return {chunk, entityMap: newEntityMap};
}
function getChunkForHTML(
html: string,
DOMBuilder: Function,
blockRenderMap: DraftBlockRenderMap,
entityMap: EntityMap,
): ?{chunk: Chunk, entityMap: EntityMap} {
html = html
.trim()
.replace(REGEX_CR, '')
.replace(REGEX_NBSP, SPACE)
.replace(REGEX_CARRIAGE, '')
.replace(REGEX_ZWS, '');
const supportedBlockTags = getBlockMapSupportedTags(blockRenderMap);
var safeBody = DOMBuilder(html);
if (!safeBody) {
return null;
}
lastBlock = null;
// Sometimes we aren't dealing with content that contains nice semantic
// tags. In this case, use divs to separate everything out into paragraphs
// and hope for the best.
var workingBlocks = containsSemanticBlockMarkup(html, supportedBlockTags) ?
supportedBlockTags :
['div'];
// Start with -1 block depth to offset the fact that we are passing in a fake
// UL block to start with.
var {
chunk,
entityMap: newEntityMap,
} = genFragment(
entityMap,
safeBody,
OrderedSet(),
'ul',
null,
workingBlocks,
-1,
blockRenderMap,
);
// join with previous block to prevent weirdness on paste
if (chunk.text.indexOf('\r') === 0) {
chunk = {
text: chunk.text.slice(1),
inlines: chunk.inlines.slice(1),
entities: chunk.entities.slice(1),
blocks: chunk.blocks,
};
}
// Kill block delimiter at the end
if (chunk.text.slice(-1) === '\r') {
chunk.text = chunk.text.slice(0, -1);
chunk.inlines = chunk.inlines.slice(0, -1);
chunk.entities = chunk.entities.slice(0, -1);
chunk.blocks.pop();
}
// If we saw no block tags, put an unstyled one in
if (chunk.blocks.length === 0) {
chunk.blocks.push({type: 'unstyled', depth: 0});
}
// Sometimes we start with text that isn't in a block, which is then
// followed by blocks. Need to fix up the blocks to add in
// an unstyled block for this content
if (chunk.text.split('\r').length === chunk.blocks.length + 1) {
chunk.blocks.unshift({type: 'unstyled', depth: 0});
}
return {chunk, entityMap: newEntityMap};
}
function convertFromHTMLtoContentBlocks(
html: string,
DOMBuilder: Function = getSafeBodyFromHTML,
blockRenderMap?: DraftBlockRenderMap = DefaultDraftBlockRenderMap,
): ?{contentBlocks: ?Array<ContentBlock>, entityMap: EntityMap} {
// Be ABSOLUTELY SURE that the dom builder you pass here won't execute
// arbitrary code in whatever environment you're running this in. For an
// example of how we try to do this in-browser, see getSafeBodyFromHTML.
// TODO: replace DraftEntity with an OrderedMap here
var chunkData = getChunkForHTML(
html,
DOMBuilder,
blockRenderMap,
DraftEntity,
);
if (chunkData == null) {
return null;
}
const {
chunk,
entityMap: newEntityMap,
} = chunkData;
var start = 0;
return {
contentBlocks: chunk.text.split('\r').map(
(textBlock, ii) => {
// Make absolutely certain that our text is acceptable.
textBlock = sanitizeDraftText(textBlock);
var end = start + textBlock.length;
var inlines = nullthrows(chunk).inlines.slice(start, end);
var entities = nullthrows(chunk).entities.slice(start, end);
var characterList = List(
inlines.map((style, ii) => {
var data = {style, entity: (null: ?string)};
if (entities[ii]) {
data.entity = entities[ii];
}
return CharacterMetadata.create(data);
}),
);
start = end + 1;
return new ContentBlock({
key: generateRandomKey(),
type: nullthrows(chunk).blocks[ii].type,
depth: nullthrows(chunk).blocks[ii].depth,
text: textBlock,
characterList,
});
},
),
entityMap: newEntityMap,
};
}
module.exports = convertFromHTMLtoContentBlocks;