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