-
Notifications
You must be signed in to change notification settings - Fork 3
/
section.js
438 lines (375 loc) · 12.1 KB
/
section.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
import {
DEFAULT_TAG_NAME,
VALID_MARKUP_SECTION_TAGNAMES
} from 'mobiledoc-kit/models/markup-section';
import {
VALID_LIST_SECTION_TAGNAMES
} from 'mobiledoc-kit/models/list-section';
import {
VALID_LIST_ITEM_TAGNAMES
} from 'mobiledoc-kit/models/list-item';
import {
LIST_SECTION_TYPE,
LIST_ITEM_TYPE,
MARKUP_SECTION_TYPE
} from 'mobiledoc-kit/models/types';
import {
VALID_MARKUP_TAGNAMES
} from 'mobiledoc-kit/models/markup';
import {
getAttributes,
normalizeTagName,
isTextNode,
isCommentNode,
NODE_TYPES
} from 'mobiledoc-kit/utils/dom-utils';
import {
any,
forEach,
contains
} from 'mobiledoc-kit/utils/array-utils';
import {
transformHTMLText,
trimSectionText
} from '../parsers/dom';
import assert from '../utils/assert';
const SKIPPABLE_ELEMENT_TAG_NAMES = [
'style', 'head', 'title', 'meta'
].map(normalizeTagName);
const NEWLINES = /\n/g;
function sanitize(text) {
return text.replace(NEWLINES, ' ');
}
/**
* parses an element into a section, ignoring any non-markup
* elements contained within
* @private
*/
class SectionParser {
constructor(builder, options={}) {
this.builder = builder;
this.plugins = options.plugins || [];
}
parse(element) {
if (this._isSkippable(element)) {
return [];
}
this.sections = [];
this.state = {};
this._updateStateFromElement(element);
let finished = false;
// top-level text nodes will be run through parseNode later so avoid running
// the node through parserPlugins twice
if (!isTextNode(element)) {
finished = this.runPlugins(element);
}
if (!finished) {
let childNodes = isTextNode(element) ? [element] : element.childNodes;
forEach(childNodes, el => {
this.parseNode(el);
});
}
this._closeCurrentSection();
return this.sections;
}
runPlugins(node) {
let isNodeFinished = false;
let env = {
addSection: (section) => {
// avoid creating empty paragraphs due to wrapper elements around
// parser-plugin-handled elements
if (this.state.section && this.state.section.isMarkerable && !this.state.text) {
this.state.section = null;
} else {
this._closeCurrentSection();
}
this.sections.push(section);
},
addMarkerable: (marker) => {
let { state } = this;
let { section } = state;
// if the first element doesn't create it's own state and it's plugin
// handler uses `addMarkerable` we won't have a section yet
if (!section) {
state.text = '';
state.section = this.builder.createMarkupSection(normalizeTagName('p'));
section = state.section;
}
assert(
'Markerables can only be appended to markup sections and list item sections',
section && section.isMarkerable
);
if (state.text) {
this._createMarker();
}
section.markers.append(marker);
},
nodeFinished() {
isNodeFinished = true;
}
};
for (let i=0; i<this.plugins.length; i++) {
let plugin = this.plugins[i];
plugin(node, this.builder, env);
if (isNodeFinished) {
return true;
}
}
return false;
}
/* eslint-disable complexity */
parseNode(node) {
if (!this.state.section) {
this._updateStateFromElement(node);
}
let nodeFinished = this.runPlugins(node);
if (nodeFinished) {
return;
}
// handle closing the current section and starting a new one if we hit a
// new-section-creating element.
if (this.state.section && !isTextNode(node) && node.tagName) {
let tagName = normalizeTagName(node.tagName);
let isListSection = contains(VALID_LIST_SECTION_TAGNAMES, tagName);
let isListItem = contains(VALID_LIST_ITEM_TAGNAMES, tagName);
let isMarkupSection = contains(VALID_MARKUP_SECTION_TAGNAMES, tagName);
let isNestedListSection = isListSection && this.state.section.isListItem;
let lastSection = this.sections[this.sections.length - 1];
// we can hit a list item after parsing a nested list, when that happens
// and the lists are of different types we need to make sure we switch
// the list type back
if (isListItem && lastSection && lastSection.isListSection) {
let parentElement = node.parentElement;
let parentElementTagName = normalizeTagName(parentElement.tagName);
if (parentElementTagName !== lastSection.tagName) {
this._closeCurrentSection();
this._updateStateFromElement(parentElement);
}
}
// if we've broken out of a list due to nested section-level elements we
// can hit the next list item without having a list section in the current
// state. In this instance we find the parent list node and use it to
// re-initialize the state with a new list section
if (
isListItem &&
!(this.state.section.isListItem || this.state.section.isListSection) &&
!lastSection.isListSection
) {
this._closeCurrentSection();
this._updateStateFromElement(node.parentElement);
}
// if we have consecutive list sections of different types (ul, ol) then
// ensure we close the current section and start a new one
let isNewListSection = lastSection
&& lastSection.isListSection
&& this.state.section.isListItem
&& isListSection
&& tagName !== lastSection.tagName;
if (
isNewListSection ||
(isListSection && !isNestedListSection) ||
isMarkupSection ||
isListItem
) {
// don't break out of the list for list items that contain a single <p>.
// deals with typical case of <li><p>Text</p></li><li><p>Text</p></li>
if (
this.state.section.isListItem &&
tagName === 'p' &&
!node.nextSibling &&
contains(VALID_LIST_ITEM_TAGNAMES, normalizeTagName(node.parentElement.tagName))
) {
this.parseElementNode(node);
return;
}
// avoid creating empty paragraphs due to wrapper elements around
// section-creating elements
if (this.state.section.isMarkerable && !this.state.text && this.state.section.markers.length === 0) {
this.state.section = null;
} else {
this._closeCurrentSection();
}
this._updateStateFromElement(node);
}
if (this.state.section.isListSection) {
// ensure the list section is closed and added to the sections list.
// _closeCurrentSection handles pushing list items onto the list section
this._closeCurrentSection();
forEach(node.childNodes, (node) => {
this.parseNode(node);
});
return;
}
}
switch (node.nodeType) {
case NODE_TYPES.TEXT:
this.parseTextNode(node);
break;
case NODE_TYPES.ELEMENT:
this.parseElementNode(node);
break;
}
}
parseElementNode(element) {
let { state } = this;
const markups = this._markupsFromElement(element);
if (markups.length && state.text.length && state.section.isMarkerable) {
this._createMarker();
}
state.markups.push(...markups);
forEach(element.childNodes, (node) => {
this.parseNode(node);
});
if (markups.length && state.text.length && state.section.isMarkerable) {
// create the marker started for this node
this._createMarker();
}
// pop the current markups from the stack
state.markups.splice(-markups.length, markups.length);
}
parseTextNode(textNode) {
let { state } = this;
state.text += sanitize(textNode.textContent);
}
_updateStateFromElement(element) {
if (isCommentNode(element)) {
return;
}
let { state } = this;
state.section = this._createSectionFromElement(element);
state.markups = this._markupsFromElement(element);
state.text = '';
}
_closeCurrentSection() {
let { sections, state } = this;
let lastSection = sections[sections.length - 1];
if (!state.section) {
return;
}
// close a trailing text node if it exists
if (state.text.length && state.section.isMarkerable) {
this._createMarker();
}
// push listItems onto the listSection or add a new section
if (state.section.isListItem && lastSection && lastSection.isListSection) {
trimSectionText(state.section);
lastSection.items.append(state.section);
} else {
// avoid creating empty markup sections, especially useful for indented source
if (
state.section.isMarkerable &&
!state.section.text.trim() &&
!any(state.section.markers, marker => marker.isAtom)
) {
state.section = null;
state.text = '';
return;
}
// remove empty list sections before creating a new section
if (lastSection && lastSection.isListSection && lastSection.items.length === 0) {
sections.pop();
}
sections.push(state.section);
}
state.section = null;
state.text = '';
}
_markupsFromElement(element) {
let { builder } = this;
let markups = [];
if (isTextNode(element)) {
return markups;
}
const tagName = normalizeTagName(element.tagName);
if (this._isValidMarkupForElement(tagName, element)) {
markups.push(builder.createMarkup(tagName, getAttributes(element)));
}
this._markupsFromElementStyle(element).forEach(
markup => markups.push(markup)
);
return markups;
}
_isValidMarkupForElement(tagName, element) {
if (VALID_MARKUP_TAGNAMES.indexOf(tagName) === -1) {
return false;
} else if (tagName === 'b') {
// google docs add a <b style="font-weight: normal;"> that should not
// create a "b" markup
return element.style.fontWeight !== 'normal';
}
return true;
}
_markupsFromElementStyle(element) {
let { builder } = this;
let markups = [];
let { fontStyle, fontWeight } = element.style;
if (fontStyle === 'italic') {
markups.push(builder.createMarkup('em'));
}
if (fontWeight === 'bold' || fontWeight === '700') {
markups.push(builder.createMarkup('strong'));
}
return markups;
}
_createMarker() {
let { state } = this;
let text = transformHTMLText(state.text);
let marker = this.builder.createMarker(text, state.markups);
state.section.markers.append(marker);
state.text = '';
}
_getSectionDetails(element) {
let sectionType,
tagName,
inferredTagName = false;
if (isTextNode(element)) {
tagName = DEFAULT_TAG_NAME;
sectionType = MARKUP_SECTION_TYPE;
inferredTagName = true;
} else {
tagName = normalizeTagName(element.tagName);
if (contains(VALID_LIST_SECTION_TAGNAMES, tagName)) {
sectionType = LIST_SECTION_TYPE;
} else if (contains(VALID_LIST_ITEM_TAGNAMES, tagName)) {
sectionType = LIST_ITEM_TYPE;
} else if (contains(VALID_MARKUP_SECTION_TAGNAMES, tagName)) {
sectionType = MARKUP_SECTION_TYPE;
} else {
sectionType = MARKUP_SECTION_TYPE;
tagName = DEFAULT_TAG_NAME;
inferredTagName = true;
}
}
return {sectionType, tagName, inferredTagName};
}
_createSectionFromElement(element) {
if (isCommentNode(element)) {
return;
}
let { builder } = this;
let section;
let {tagName, sectionType, inferredTagName} =
this._getSectionDetails(element);
switch (sectionType) {
case LIST_SECTION_TYPE:
section = builder.createListSection(tagName);
break;
case LIST_ITEM_TYPE:
section = builder.createListItem();
break;
case MARKUP_SECTION_TYPE:
section = builder.createMarkupSection(tagName);
section._inferredTagName = inferredTagName;
break;
default:
assert('Cannot parse section from element', false);
}
return section;
}
_isSkippable(element) {
return element.nodeType === NODE_TYPES.ELEMENT &&
contains(SKIPPABLE_ELEMENT_TAG_NAMES,
normalizeTagName(element.tagName));
}
}
export default SectionParser;