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