@20minutes/draft-convert 3.0.0 → 3.0.1

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.
Files changed (42) hide show
  1. package/README.md +29 -0
  2. package/dist/draft-convert.js +440 -0
  3. package/dist/draft-convert.min.js +1 -0
  4. package/esm/blockEntities.js +67 -0
  5. package/esm/blockInlineStyles.js +98 -0
  6. package/esm/convertFromHTML.js +537 -0
  7. package/esm/convertToHTML.js +107 -0
  8. package/esm/default/defaultBlockHTML.js +31 -0
  9. package/esm/default/defaultInlineHTML.js +18 -0
  10. package/esm/encodeBlock.js +44 -0
  11. package/esm/index.js +4 -0
  12. package/esm/util/accumulateFunction.js +9 -0
  13. package/esm/util/blockTypeObjectFunction.js +9 -0
  14. package/esm/util/getBlockTags.js +27 -0
  15. package/esm/util/getElementHTML.js +36 -0
  16. package/esm/util/getElementTagLength.js +20 -0
  17. package/esm/util/getNestedBlockTags.js +29 -0
  18. package/esm/util/parseHTML.js +18 -0
  19. package/esm/util/rangeSort.js +6 -0
  20. package/esm/util/splitReactElement.js +18 -0
  21. package/esm/util/styleObjectFunction.js +8 -0
  22. package/esm/util/updateMutation.js +48 -0
  23. package/lib/blockEntities.js +74 -0
  24. package/lib/blockInlineStyles.js +105 -0
  25. package/lib/convertFromHTML.js +544 -0
  26. package/lib/convertToHTML.js +114 -0
  27. package/lib/default/defaultBlockHTML.js +37 -0
  28. package/lib/default/defaultInlineHTML.js +25 -0
  29. package/lib/encodeBlock.js +51 -0
  30. package/lib/index.js +27 -0
  31. package/lib/util/accumulateFunction.js +15 -0
  32. package/lib/util/blockTypeObjectFunction.js +15 -0
  33. package/lib/util/getBlockTags.js +34 -0
  34. package/lib/util/getElementHTML.js +43 -0
  35. package/lib/util/getElementTagLength.js +27 -0
  36. package/lib/util/getNestedBlockTags.js +36 -0
  37. package/lib/util/parseHTML.js +24 -0
  38. package/lib/util/rangeSort.js +12 -0
  39. package/lib/util/splitReactElement.js +24 -0
  40. package/lib/util/styleObjectFunction.js +14 -0
  41. package/lib/util/updateMutation.js +55 -0
  42. package/package.json +1 -1
@@ -0,0 +1,537 @@
1
+ /**
2
+ * Copyright (c) 2013-present, Facebook, Inc.
3
+ * All rights reserved.
4
+ *
5
+ * Copyright (c) 2013-present, Facebook, Inc.
6
+ * All rights reserved.
7
+ *
8
+ * This source code is licensed under the BSD-style license found in the
9
+ * LICENSE file in the /src directory of this source tree. An additional grant
10
+ * of patent rights can be found in the PATENTS file in the same directory.
11
+ */
12
+
13
+ import { List, Map, OrderedSet } from 'immutable';
14
+ import { BlockMapBuilder, CharacterMetadata, ContentBlock, ContentState, Entity, SelectionState, genKey } from 'draft-js';
15
+ import getSafeBodyFromHTML from './util/parseHTML';
16
+ import rangeSort from './util/rangeSort';
17
+ var SPACE = ' ';
18
+
19
+ // Arbitrary max indent
20
+ var MAX_DEPTH = 4;
21
+
22
+ // used for replacing characters in HTML
23
+ var REGEX_CR = /\r/g;
24
+ var REGEX_LF = /\n/g;
25
+ var REGEX_NBSP = / /g;
26
+ var REGEX_BLOCK_DELIMITER = /\r/g;
27
+
28
+ // Block tag flow is different because LIs do not have
29
+ // a deterministic style ;_;
30
+ var blockTags = ['p', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'li', 'blockquote', 'pre'];
31
+ var inlineTags = {
32
+ b: 'BOLD',
33
+ code: 'CODE',
34
+ del: 'STRIKETHROUGH',
35
+ em: 'ITALIC',
36
+ i: 'ITALIC',
37
+ s: 'STRIKETHROUGH',
38
+ strike: 'STRIKETHROUGH',
39
+ strong: 'BOLD',
40
+ u: 'UNDERLINE'
41
+ };
42
+ var handleMiddleware = function handleMiddleware(maybeMiddleware, base) {
43
+ if (maybeMiddleware && maybeMiddleware.__isMiddleware === true) {
44
+ return maybeMiddleware(base);
45
+ }
46
+ return maybeMiddleware;
47
+ };
48
+ var defaultHTMLToBlock = function defaultHTMLToBlock(nodeName, node, lastList) {
49
+ return undefined;
50
+ };
51
+ var defaultHTMLToStyle = function defaultHTMLToStyle(nodeName, node, currentStyle) {
52
+ return currentStyle;
53
+ };
54
+ var defaultHTMLToEntity = function defaultHTMLToEntity(nodeName, node) {
55
+ return undefined;
56
+ };
57
+ var defaultTextToEntity = function defaultTextToEntity(text) {
58
+ return [];
59
+ };
60
+ var nullthrows = function nullthrows(x) {
61
+ if (x != null) {
62
+ return x;
63
+ }
64
+ throw new Error('Got unexpected null or undefined');
65
+ };
66
+ var sanitizeDraftText = function sanitizeDraftText(input) {
67
+ return input.replace(REGEX_BLOCK_DELIMITER, '');
68
+ };
69
+ function getEmptyChunk() {
70
+ return {
71
+ text: '',
72
+ inlines: [],
73
+ entities: [],
74
+ blocks: []
75
+ };
76
+ }
77
+ function getWhitespaceChunk(inEntity) {
78
+ var entities = new Array(1);
79
+ if (inEntity) {
80
+ entities[0] = inEntity;
81
+ }
82
+ return {
83
+ text: SPACE,
84
+ inlines: [OrderedSet()],
85
+ entities: entities,
86
+ blocks: []
87
+ };
88
+ }
89
+ function getSoftNewlineChunk(block, depth) {
90
+ var flat = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false;
91
+ var data = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : Map();
92
+ if (flat === true) {
93
+ return {
94
+ text: '\r',
95
+ inlines: [OrderedSet()],
96
+ entities: new Array(1),
97
+ blocks: [{
98
+ type: block,
99
+ data: data,
100
+ depth: Math.max(0, Math.min(MAX_DEPTH, depth))
101
+ }],
102
+ isNewline: true
103
+ };
104
+ }
105
+ return {
106
+ text: '\n',
107
+ inlines: [OrderedSet()],
108
+ entities: new Array(1),
109
+ blocks: []
110
+ };
111
+ }
112
+ function getBlockDividerChunk(block, depth) {
113
+ var data = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : Map();
114
+ return {
115
+ text: '\r',
116
+ inlines: [OrderedSet()],
117
+ entities: new Array(1),
118
+ blocks: [{
119
+ type: block,
120
+ data: data,
121
+ depth: Math.max(0, Math.min(MAX_DEPTH, depth))
122
+ }]
123
+ };
124
+ }
125
+ function getBlockTypeForTag(tag, lastList) {
126
+ switch (tag) {
127
+ case 'h1':
128
+ return 'header-one';
129
+ case 'h2':
130
+ return 'header-two';
131
+ case 'h3':
132
+ return 'header-three';
133
+ case 'h4':
134
+ return 'header-four';
135
+ case 'h5':
136
+ return 'header-five';
137
+ case 'h6':
138
+ return 'header-six';
139
+ case 'li':
140
+ if (lastList === 'ol') {
141
+ return 'ordered-list-item';
142
+ }
143
+ return 'unordered-list-item';
144
+ case 'blockquote':
145
+ return 'blockquote';
146
+ case 'pre':
147
+ return 'code-block';
148
+ case 'div':
149
+ case 'p':
150
+ return 'unstyled';
151
+ default:
152
+ return null;
153
+ }
154
+ }
155
+ function baseCheckBlockType(nodeName, node, lastList) {
156
+ return getBlockTypeForTag(nodeName, lastList);
157
+ }
158
+ function processInlineTag(tag, node, currentStyle) {
159
+ var styleToCheck = inlineTags[tag];
160
+ if (styleToCheck) {
161
+ currentStyle = currentStyle.add(styleToCheck).toOrderedSet();
162
+ } else if (node instanceof HTMLElement) {
163
+ var htmlElement = node;
164
+ currentStyle = currentStyle.withMutations(function (style) {
165
+ if (htmlElement.style.fontWeight === 'bold') {
166
+ style.add('BOLD');
167
+ }
168
+ if (htmlElement.style.fontStyle === 'italic') {
169
+ style.add('ITALIC');
170
+ }
171
+ if (htmlElement.style.textDecoration === 'underline') {
172
+ style.add('UNDERLINE');
173
+ }
174
+ if (htmlElement.style.textDecoration === 'line-through') {
175
+ style.add('STRIKETHROUGH');
176
+ }
177
+ }).toOrderedSet();
178
+ }
179
+ return currentStyle;
180
+ }
181
+ function baseProcessInlineTag(tag, node) {
182
+ var inlineStyles = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : OrderedSet();
183
+ return processInlineTag(tag, node, inlineStyles);
184
+ }
185
+ function joinChunks(A, B) {
186
+ var flat = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false;
187
+ // Sometimes two blocks will touch in the DOM and we need to strip the
188
+ // extra delimiter to preserve niceness.
189
+ var firstInB = B.text.slice(0, 1);
190
+ var lastInA = A.text.slice(-1);
191
+ var adjacentDividers = lastInA === '\r' && firstInB === '\r';
192
+ var isJoiningBlocks = A.text !== '\r' && B.text !== '\r'; // when joining two full blocks like this we want to pop one divider
193
+ var addingNewlineToEmptyBlock = A.text === '\r' && !A.isNewline && B.isNewline; // when joining a newline to an empty block we want to remove the newline
194
+
195
+ if (adjacentDividers && (isJoiningBlocks || addingNewlineToEmptyBlock)) {
196
+ A.text = A.text.slice(0, -1);
197
+ A.inlines.pop();
198
+ A.entities.pop();
199
+ A.blocks.pop();
200
+ }
201
+
202
+ // Kill whitespace after blocks if flat mode is on
203
+ if (A.text.slice(-1) === '\r' && flat === true) {
204
+ if (B.text === SPACE || B.text === '\n') {
205
+ return A;
206
+ }
207
+ if (firstInB === SPACE || firstInB === '\n') {
208
+ B.text = B.text.slice(1);
209
+ B.inlines.shift();
210
+ B.entities.shift();
211
+ }
212
+ }
213
+ var isNewline = A.text.length === 0 && B.isNewline;
214
+ return {
215
+ text: A.text + B.text,
216
+ inlines: A.inlines.concat(B.inlines),
217
+ entities: A.entities.concat(B.entities),
218
+ blocks: A.blocks.concat(B.blocks),
219
+ isNewline: isNewline
220
+ };
221
+ }
222
+
223
+ /*
224
+ * Check to see if we have anything like <p> <blockquote> <h1>... to create
225
+ * block tags from. If we do, we can use those and ignore <div> tags. If we
226
+ * don't, we can treat <div> tags as meaningful (unstyled) blocks.
227
+ */
228
+ function containsSemanticBlockMarkup(html) {
229
+ return blockTags.some(function (tag) {
230
+ return html.indexOf("<".concat(tag)) !== -1;
231
+ });
232
+ }
233
+ function genFragment(node, inlineStyle, lastList, inBlock, fragmentBlockTags, depth, processCustomInlineStyles, checkEntityNode, checkEntityText, checkBlockType, createEntity, getEntity, mergeEntityData, replaceEntityData, options, inEntity) {
234
+ var nodeName = node.nodeName.toLowerCase();
235
+ var newBlock = false;
236
+ var nextBlockType = 'unstyled';
237
+
238
+ // Base Case
239
+ if (nodeName === '#text') {
240
+ var text = node.textContent;
241
+ if (text.trim() === '' && inBlock === null) {
242
+ return getEmptyChunk();
243
+ }
244
+ if (text.trim() === '' && inBlock !== 'code-block') {
245
+ return getWhitespaceChunk(inEntity);
246
+ }
247
+ if (inBlock !== 'code-block') {
248
+ // Can't use empty string because MSWord
249
+ text = text.replace(REGEX_LF, SPACE);
250
+ }
251
+ var entities = Array(text.length).fill(inEntity);
252
+ var offsetChange = 0;
253
+ var textEntities = checkEntityText(text, createEntity, getEntity, mergeEntityData, replaceEntityData).sort(rangeSort);
254
+ textEntities.forEach(function (_ref) {
255
+ var entity = _ref.entity,
256
+ offset = _ref.offset,
257
+ length = _ref.length,
258
+ result = _ref.result;
259
+ var adjustedOffset = offset + offsetChange;
260
+ if (result === null || result === undefined) {
261
+ result = text.substr(adjustedOffset, length);
262
+ }
263
+ var textArray = text.split('');
264
+ textArray.splice.bind(textArray, adjustedOffset, length).apply(textArray, result.split(''));
265
+ text = textArray.join('');
266
+ entities.splice.bind(entities, adjustedOffset, length).apply(entities, Array(result.length).fill(entity));
267
+ offsetChange += result.length - length;
268
+ });
269
+ return {
270
+ text: text,
271
+ inlines: Array(text.length).fill(inlineStyle),
272
+ entities: entities,
273
+ blocks: []
274
+ };
275
+ }
276
+
277
+ // BR tags
278
+ if (nodeName === 'br') {
279
+ var _blockType = inBlock;
280
+ if (_blockType === null) {
281
+ // BR tag is at top level, treat it as an unstyled block
282
+ return getSoftNewlineChunk('unstyled', depth, true);
283
+ }
284
+ return getSoftNewlineChunk(_blockType || 'unstyled', depth, options.flat);
285
+ }
286
+ var chunk = getEmptyChunk();
287
+ var newChunk = null;
288
+
289
+ // Inline tags
290
+ inlineStyle = processInlineTag(nodeName, node, inlineStyle);
291
+ inlineStyle = processCustomInlineStyles(nodeName, node, inlineStyle);
292
+
293
+ // Handle lists
294
+ if (nodeName === 'ul' || nodeName === 'ol') {
295
+ if (lastList) {
296
+ depth += 1;
297
+ }
298
+ lastList = nodeName;
299
+ inBlock = null;
300
+ }
301
+
302
+ // Block Tags
303
+ var blockInfo = checkBlockType(nodeName, node, lastList, inBlock);
304
+ var blockType;
305
+ var blockDataMap;
306
+ if (blockInfo === false) {
307
+ return getEmptyChunk();
308
+ }
309
+ blockInfo = blockInfo || {};
310
+ if (typeof blockInfo === 'string') {
311
+ blockType = blockInfo;
312
+ blockDataMap = Map();
313
+ } else {
314
+ blockType = typeof blockInfo === 'string' ? blockInfo : blockInfo.type;
315
+ blockDataMap = blockInfo.data ? Map(blockInfo.data) : Map();
316
+ }
317
+ if (!inBlock && (fragmentBlockTags.indexOf(nodeName) !== -1 || blockType)) {
318
+ chunk = getBlockDividerChunk(blockType || getBlockTypeForTag(nodeName, lastList), depth, blockDataMap);
319
+ inBlock = blockType || getBlockTypeForTag(nodeName, lastList);
320
+ newBlock = true;
321
+ } else if (lastList && (inBlock === 'ordered-list-item' || inBlock === 'unordered-list-item') && nodeName === 'li') {
322
+ var listItemBlockType = getBlockTypeForTag(nodeName, lastList);
323
+ chunk = getBlockDividerChunk(listItemBlockType, depth);
324
+ inBlock = listItemBlockType;
325
+ newBlock = true;
326
+ nextBlockType = lastList === 'ul' ? 'unordered-list-item' : 'ordered-list-item';
327
+ } else if (inBlock && inBlock !== 'atomic' && blockType === 'atomic') {
328
+ inBlock = blockType;
329
+ newBlock = true;
330
+ chunk = getSoftNewlineChunk(blockType, depth, true,
331
+ // atomic blocks within non-atomic blocks must always be split out
332
+ blockDataMap);
333
+ }
334
+
335
+ // Recurse through children
336
+ var child = node.firstChild;
337
+
338
+ // hack to allow conversion of atomic blocks from HTML (e.g. <figure><img
339
+ // src="..." /></figure>). since metadata must be stored on an entity text
340
+ // must exist for the entity to apply to. the way chunks are joined strips
341
+ // whitespace at the end so it cannot be a space character.
342
+
343
+ if (child == null && inEntity && (blockType === 'atomic' || inBlock === 'atomic')) {
344
+ child = document.createTextNode('a');
345
+ }
346
+ if (child != null) {
347
+ nodeName = child.nodeName.toLowerCase();
348
+ }
349
+ var entityId = null;
350
+ while (child) {
351
+ entityId = checkEntityNode(nodeName, child, createEntity, getEntity, mergeEntityData, replaceEntityData);
352
+ newChunk = genFragment(child, inlineStyle, lastList, inBlock, fragmentBlockTags, depth, processCustomInlineStyles, checkEntityNode, checkEntityText, checkBlockType, createEntity, getEntity, mergeEntityData, replaceEntityData, options, entityId || inEntity);
353
+ chunk = joinChunks(chunk, newChunk, options.flat);
354
+ var sibling = child.nextSibling;
355
+
356
+ // Put in a newline to break up blocks inside blocks
357
+ if (sibling && fragmentBlockTags.indexOf(nodeName) >= 0 && inBlock) {
358
+ var newBlockInfo = checkBlockType(nodeName, child, lastList, inBlock);
359
+ var newBlockType = void 0;
360
+ var newBlockData = void 0;
361
+ if (newBlockInfo !== false) {
362
+ newBlockInfo = newBlockInfo || {};
363
+ if (typeof newBlockInfo === 'string') {
364
+ newBlockType = newBlockInfo;
365
+ newBlockData = Map();
366
+ } else {
367
+ newBlockType = newBlockInfo.type || getBlockTypeForTag(nodeName, lastList);
368
+ newBlockData = newBlockInfo.data ? Map(newBlockInfo.data) : Map();
369
+ }
370
+ chunk = joinChunks(chunk, getSoftNewlineChunk(newBlockType, depth, options.flat, newBlockData), options.flat);
371
+ }
372
+ }
373
+ if (sibling) {
374
+ nodeName = sibling.nodeName.toLowerCase();
375
+ }
376
+ child = sibling;
377
+ }
378
+ if (newBlock) {
379
+ chunk = joinChunks(chunk, getBlockDividerChunk(nextBlockType, depth, Map()), options.flat);
380
+ }
381
+ return chunk;
382
+ }
383
+ function getChunkForHTML(html, processCustomInlineStyles, checkEntityNode, checkEntityText, checkBlockType, createEntity, getEntity, mergeEntityData, replaceEntityData, options, DOMBuilder) {
384
+ html = html.trim().replace(REGEX_CR, '').replace(REGEX_NBSP, SPACE);
385
+ var safeBody = DOMBuilder(html);
386
+ if (!safeBody) {
387
+ return null;
388
+ }
389
+
390
+ // Sometimes we aren't dealing with content that contains nice semantic
391
+ // tags. In this case, use divs to separate everything out into paragraphs
392
+ // and hope for the best.
393
+ var workingBlocks = containsSemanticBlockMarkup(html) ? blockTags.concat(['div']) : ['div'];
394
+
395
+ // Start with -1 block depth to offset the fact that we are passing in a fake
396
+ // UL block to sta rt with.
397
+ var chunk = genFragment(safeBody, OrderedSet(), 'ul', null, workingBlocks, -1, processCustomInlineStyles, checkEntityNode, checkEntityText, checkBlockType, createEntity, getEntity, mergeEntityData, replaceEntityData, options);
398
+
399
+ // join with previous block to prevent weirdness on paste
400
+ if (chunk.text.indexOf('\r') === 0) {
401
+ chunk = {
402
+ text: chunk.text.slice(1),
403
+ inlines: chunk.inlines.slice(1),
404
+ entities: chunk.entities.slice(1),
405
+ blocks: chunk.blocks
406
+ };
407
+ }
408
+
409
+ // Kill block delimiter at the end
410
+ if (chunk.text.slice(-1) === '\r') {
411
+ chunk.text = chunk.text.slice(0, -1);
412
+ chunk.inlines = chunk.inlines.slice(0, -1);
413
+ chunk.entities = chunk.entities.slice(0, -1);
414
+ chunk.blocks.pop();
415
+ }
416
+
417
+ // If we saw no block tags, put an unstyled one in
418
+ if (chunk.blocks.length === 0) {
419
+ chunk.blocks.push({
420
+ type: 'unstyled',
421
+ data: Map(),
422
+ depth: 0
423
+ });
424
+ }
425
+
426
+ // Sometimes we start with text that isn't in a block, which is then
427
+ // followed by blocks. Need to fix up the blocks to add in
428
+ // an unstyled block for this content
429
+ if (chunk.text.split('\r').length === chunk.blocks.length + 1) {
430
+ chunk.blocks.unshift({
431
+ type: 'unstyled',
432
+ data: Map(),
433
+ depth: 0
434
+ });
435
+ }
436
+ return chunk;
437
+ }
438
+ function convertFromHTMLtoContentBlocks(html, processCustomInlineStyles, checkEntityNode, checkEntityText, checkBlockType, createEntity, getEntity, mergeEntityData, replaceEntityData, options, DOMBuilder, generateKey) {
439
+ // Be ABSOLUTELY SURE that the dom builder you pass hare won't execute
440
+ // arbitrary code in whatever environment you're running this in. For an
441
+ // example of how we try to do this in-browser, see getSafeBodyFromHTML.
442
+
443
+ var chunk = getChunkForHTML(html, processCustomInlineStyles, checkEntityNode, checkEntityText, checkBlockType, createEntity, getEntity, mergeEntityData, replaceEntityData, options, DOMBuilder, generateKey);
444
+ if (chunk == null) {
445
+ return [];
446
+ }
447
+ var start = 0;
448
+ return chunk.text.split('\r').map(function (textBlock, blockIndex) {
449
+ // Make absolutely certain that our text is acceptable.
450
+ textBlock = sanitizeDraftText(textBlock);
451
+ var end = start + textBlock.length;
452
+ var inlines = nullthrows(chunk).inlines.slice(start, end);
453
+ var entities = nullthrows(chunk).entities.slice(start, end);
454
+ var characterList = List(inlines.map(function (style, entityIndex) {
455
+ var data = {
456
+ style: style,
457
+ entity: null
458
+ };
459
+ if (entities[entityIndex]) {
460
+ data.entity = entities[entityIndex];
461
+ }
462
+ return CharacterMetadata.create(data);
463
+ }));
464
+ start = end + 1;
465
+ return new ContentBlock({
466
+ key: generateKey(),
467
+ type: nullthrows(chunk).blocks[blockIndex].type,
468
+ data: nullthrows(chunk).blocks[blockIndex].data,
469
+ depth: nullthrows(chunk).blocks[blockIndex].depth,
470
+ text: textBlock,
471
+ characterList: characterList
472
+ });
473
+ });
474
+ }
475
+ var convertFromHTML = function convertFromHTML(_ref2) {
476
+ var _ref2$htmlToStyle = _ref2.htmlToStyle,
477
+ htmlToStyle = _ref2$htmlToStyle === void 0 ? defaultHTMLToStyle : _ref2$htmlToStyle,
478
+ _ref2$htmlToEntity = _ref2.htmlToEntity,
479
+ htmlToEntity = _ref2$htmlToEntity === void 0 ? defaultHTMLToEntity : _ref2$htmlToEntity,
480
+ _ref2$textToEntity = _ref2.textToEntity,
481
+ textToEntity = _ref2$textToEntity === void 0 ? defaultTextToEntity : _ref2$textToEntity,
482
+ _ref2$htmlToBlock = _ref2.htmlToBlock,
483
+ htmlToBlock = _ref2$htmlToBlock === void 0 ? defaultHTMLToBlock : _ref2$htmlToBlock;
484
+ return function (html) {
485
+ var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {
486
+ flat: false
487
+ };
488
+ var DOMBuilder = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : getSafeBodyFromHTML;
489
+ var generateKey = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : genKey;
490
+ var contentState = ContentState.createFromText('');
491
+ var createEntityWithContentState = function createEntityWithContentState() {
492
+ if (contentState.createEntity) {
493
+ var _contentState;
494
+ contentState = (_contentState = contentState).createEntity.apply(_contentState, arguments);
495
+ return contentState.getLastCreatedEntityKey();
496
+ }
497
+ return Entity.create.apply(Entity, arguments);
498
+ };
499
+ var getEntityWithContentState = function getEntityWithContentState() {
500
+ if (contentState.getEntity) {
501
+ var _contentState2;
502
+ return (_contentState2 = contentState).getEntity.apply(_contentState2, arguments);
503
+ }
504
+ return Entity.get.apply(Entity, arguments);
505
+ };
506
+ var mergeEntityDataWithContentState = function mergeEntityDataWithContentState() {
507
+ if (contentState.mergeEntityData) {
508
+ var _contentState3;
509
+ contentState = (_contentState3 = contentState).mergeEntityData.apply(_contentState3, arguments);
510
+ return;
511
+ }
512
+ Entity.mergeData.apply(Entity, arguments);
513
+ };
514
+ var replaceEntityDataWithContentState = function replaceEntityDataWithContentState() {
515
+ if (contentState.replaceEntityData) {
516
+ var _contentState4;
517
+ contentState = (_contentState4 = contentState).replaceEntityData.apply(_contentState4, arguments);
518
+ return;
519
+ }
520
+ Entity.replaceData.apply(Entity, arguments);
521
+ };
522
+ var contentBlocks = convertFromHTMLtoContentBlocks(html, handleMiddleware(htmlToStyle, baseProcessInlineTag), handleMiddleware(htmlToEntity, defaultHTMLToEntity), handleMiddleware(textToEntity, defaultTextToEntity), handleMiddleware(htmlToBlock, baseCheckBlockType), createEntityWithContentState, getEntityWithContentState, mergeEntityDataWithContentState, replaceEntityDataWithContentState, options, DOMBuilder, generateKey);
523
+ var blockMap = BlockMapBuilder.createFromArray(contentBlocks);
524
+ var firstBlockKey = contentBlocks[0].getKey();
525
+ return contentState.merge({
526
+ blockMap: blockMap,
527
+ selectionBefore: SelectionState.createEmpty(firstBlockKey),
528
+ selectionAfter: SelectionState.createEmpty(firstBlockKey)
529
+ });
530
+ };
531
+ };
532
+ export default (function () {
533
+ if (arguments.length >= 1 && typeof (arguments.length <= 0 ? undefined : arguments[0]) === 'string') {
534
+ return convertFromHTML({}).apply(void 0, arguments);
535
+ }
536
+ return convertFromHTML.apply(void 0, arguments);
537
+ });
@@ -0,0 +1,107 @@
1
+ import invariant from 'invariant';
2
+ import React from 'react';
3
+ import ReactDOMServer from 'react-dom/server';
4
+ import { convertToRaw } from 'draft-js';
5
+ import encodeBlock from './encodeBlock';
6
+ import blockEntities from './blockEntities';
7
+ import blockInlineStyles from './blockInlineStyles';
8
+ import accumulateFunction from './util/accumulateFunction';
9
+ import blockTypeObjectFunction from './util/blockTypeObjectFunction';
10
+ import getBlockTags from './util/getBlockTags';
11
+ import getNestedBlockTags from './util/getNestedBlockTags';
12
+ import defaultBlockHTML from './default/defaultBlockHTML';
13
+ var defaultEntityToHTML = function defaultEntityToHTML(entity, originalText) {
14
+ return originalText;
15
+ };
16
+ var defaultValidateHTML = function defaultValidateHTML(html) {
17
+ return true;
18
+ };
19
+ var convertToHTML = function convertToHTML(_ref) {
20
+ var _ref$styleToHTML = _ref.styleToHTML,
21
+ styleToHTML = _ref$styleToHTML === void 0 ? {} : _ref$styleToHTML,
22
+ _ref$blockToHTML = _ref.blockToHTML,
23
+ blockToHTML = _ref$blockToHTML === void 0 ? {} : _ref$blockToHTML,
24
+ _ref$entityToHTML = _ref.entityToHTML,
25
+ entityToHTML = _ref$entityToHTML === void 0 ? defaultEntityToHTML : _ref$entityToHTML,
26
+ _ref$validateHTML = _ref.validateHTML,
27
+ validateHTML = _ref$validateHTML === void 0 ? defaultValidateHTML : _ref$validateHTML;
28
+ return function (contentState) {
29
+ invariant(contentState !== null && contentState !== undefined, 'Expected contentState to be non-null');
30
+ var getBlockHTML;
31
+ if (blockToHTML.__isMiddleware === true) {
32
+ getBlockHTML = blockToHTML(blockTypeObjectFunction(defaultBlockHTML));
33
+ } else {
34
+ getBlockHTML = accumulateFunction(blockTypeObjectFunction(blockToHTML), blockTypeObjectFunction(defaultBlockHTML));
35
+ }
36
+ var rawState = convertToRaw(contentState);
37
+ var listStack = [];
38
+ var result = rawState.blocks.map(function (block) {
39
+ var type = block.type,
40
+ depth = block.depth;
41
+ var closeNestTags = '';
42
+ var openNestTags = '';
43
+ var blockHTMLResult = getBlockHTML(block);
44
+ if (!blockHTMLResult) {
45
+ throw new Error("convertToHTML: missing HTML definition for block with type ".concat(block.type));
46
+ }
47
+ if (!blockHTMLResult.nest) {
48
+ // this block can't be nested, so reset all nesting if necessary
49
+ closeNestTags = listStack.reduceRight(function (string, nestedBlock) {
50
+ return string + getNestedBlockTags(getBlockHTML(nestedBlock), depth).nestEnd;
51
+ }, '');
52
+ listStack = [];
53
+ } else {
54
+ while (depth + 1 !== listStack.length || type !== listStack[depth].type) {
55
+ if (depth + 1 === listStack.length) {
56
+ // depth is right but doesn't match type
57
+ var blockToClose = listStack[depth];
58
+ closeNestTags += getNestedBlockTags(getBlockHTML(blockToClose), depth).nestEnd;
59
+ openNestTags += getNestedBlockTags(getBlockHTML(block), depth).nestStart;
60
+ listStack[depth] = block;
61
+ } else if (depth + 1 < listStack.length) {
62
+ var _blockToClose = listStack[listStack.length - 1];
63
+ closeNestTags += getNestedBlockTags(getBlockHTML(_blockToClose), depth).nestEnd;
64
+ listStack = listStack.slice(0, -1);
65
+ } else {
66
+ openNestTags += getNestedBlockTags(getBlockHTML(block), depth).nestStart;
67
+ listStack.push(block);
68
+ }
69
+ }
70
+ }
71
+ var innerHTML = blockInlineStyles(blockEntities(encodeBlock(block), rawState.entityMap, entityToHTML), styleToHTML);
72
+ var blockHTML = getBlockTags(getBlockHTML(block));
73
+ var html;
74
+ if (typeof blockHTML === 'string') {
75
+ html = blockHTML;
76
+ } else {
77
+ html = blockHTML.start + innerHTML + blockHTML.end;
78
+ }
79
+ if (innerHTML.length === 0 && Object.prototype.hasOwnProperty.call(blockHTML, 'empty')) {
80
+ if ( /*#__PURE__*/React.isValidElement(blockHTML.empty)) {
81
+ html = ReactDOMServer.renderToStaticMarkup(blockHTML.empty);
82
+ } else {
83
+ html = blockHTML.empty;
84
+ }
85
+ }
86
+ var finalHtml = closeNestTags + openNestTags + html;
87
+ if (!validateHTML(finalHtml)) {
88
+ return '';
89
+ }
90
+ return finalHtml;
91
+ }).join('');
92
+ result = listStack.reduce(function (res, nestBlock) {
93
+ return res + getNestedBlockTags(getBlockHTML(nestBlock), nestBlock.depth).nestEnd;
94
+ }, result);
95
+ return result;
96
+ };
97
+ };
98
+ export default (function () {
99
+ for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
100
+ args[_key] = arguments[_key];
101
+ }
102
+ if (args.length === 1 && Object.prototype.hasOwnProperty.call(args[0], '_map') && args[0].getBlockMap != null) {
103
+ // skip higher-order function and use defaults
104
+ return convertToHTML({}).apply(void 0, args);
105
+ }
106
+ return convertToHTML.apply(void 0, args);
107
+ });
@@ -0,0 +1,31 @@
1
+ import React from 'react';
2
+
3
+ // based on Draft.js' custom list depth styling
4
+ var ORDERED_LIST_TYPES = ['1', 'a', 'i'];
5
+ export default {
6
+ unstyled: /*#__PURE__*/React.createElement("p", null),
7
+ paragraph: /*#__PURE__*/React.createElement("p", null),
8
+ 'header-one': /*#__PURE__*/React.createElement("h1", null),
9
+ 'header-two': /*#__PURE__*/React.createElement("h2", null),
10
+ 'header-three': /*#__PURE__*/React.createElement("h3", null),
11
+ 'header-four': /*#__PURE__*/React.createElement("h4", null),
12
+ 'header-five': /*#__PURE__*/React.createElement("h5", null),
13
+ 'header-six': /*#__PURE__*/React.createElement("h6", null),
14
+ 'code-block': /*#__PURE__*/React.createElement("pre", null),
15
+ blockquote: /*#__PURE__*/React.createElement("blockquote", null),
16
+ 'unordered-list-item': {
17
+ element: /*#__PURE__*/React.createElement("li", null),
18
+ nest: /*#__PURE__*/React.createElement("ul", null)
19
+ },
20
+ 'ordered-list-item': {
21
+ element: /*#__PURE__*/React.createElement("li", null),
22
+ nest: function nest(depth) {
23
+ var type = ORDERED_LIST_TYPES[depth % 3];
24
+ return /*#__PURE__*/React.createElement("ol", {
25
+ type: type
26
+ });
27
+ }
28
+ },
29
+ media: /*#__PURE__*/React.createElement("figure", null),
30
+ atomic: /*#__PURE__*/React.createElement("figure", null)
31
+ };
@@ -0,0 +1,18 @@
1
+ import React from 'react';
2
+ export default function defaultInlineHTML(style) {
3
+ switch (style) {
4
+ case 'BOLD':
5
+ return /*#__PURE__*/React.createElement("strong", null);
6
+ case 'ITALIC':
7
+ return /*#__PURE__*/React.createElement("em", null);
8
+ case 'UNDERLINE':
9
+ return /*#__PURE__*/React.createElement("u", null);
10
+ case 'CODE':
11
+ return /*#__PURE__*/React.createElement("code", null);
12
+ default:
13
+ return {
14
+ start: '',
15
+ end: ''
16
+ };
17
+ }
18
+ }