Debian Codegraph @

extensions/VisualEditor/lib/ve/src/dm/ve.dm.Converter.js

raw symbols SCIP
1 /*!
2 * VisualEditor DataModel Converter class.
3 *
4 * @copyright See AUTHORS.txt
5 */
6
7 /**
8 * DataModel converter.
9 *
10 * Converts between HTML DOM and VisualEditor linear data.
11 *
12 * @class
13 * @constructor
14 * @param {ve.dm.ModelRegistry} modelRegistry
15 * @param {ve.dm.NodeFactory} nodeFactory
16 * @param {ve.dm.AnnotationFactory} annotationFactory
17 */
18 ve.dm.Converter = function VeDmConverter( modelRegistry, nodeFactory, annotationFactory ) {
19 // Properties
20 this.modelRegistry = modelRegistry;
21 this.nodeFactory = nodeFactory;
22 this.annotationFactory = annotationFactory;
23 this.doc = null;
24 this.documentData = null;
25 this.store = null;
26 this.internalList = null;
27 this.mode = null;
28 this.fromClipboard = null;
29 this.contextStack = null;
30
31 // Whitespace regexes
32 const whitespaceList = this.constructor.static.whitespaceList;
33
34 this.leadingWhitespaceRegex = new RegExp( '^[' + whitespaceList + ']' );
35 this.leadingWhitespacesRegex = new RegExp( '^[' + whitespaceList + ']+' );
36 this.trailingWhitespaceRegex = new RegExp( '[' + whitespaceList + ']$' );
37 this.trailingWhitespacesRegex = new RegExp( '[' + whitespaceList + ']+$' );
38 this.onlyWhitespaceRegex = new RegExp( '^[' + whitespaceList + ']+$' );
39 this.trimWhitespaceRegex = new RegExp( '^([' + whitespaceList + ']*)([\\s\\S]*?)([' + whitespaceList + ']*)$' );
40
41 };
42
43 /* Inheritance */
44
45 OO.initClass( ve.dm.Converter );
46
47 /* Static Properties */
48
49 /**
50 * List of HTML attribute names that {#renderHtmlAttributeList} should use computed values for.
51 *
52 * @type {string[]}
53 */
54 ve.dm.Converter.static.computedAttributes = [ 'href', 'src' ];
55
56 /**
57 * Pattern matching 'white space characters' as defined by the HTML spec only.
58 *
59 * All other whitespace should be treated as text, e.g. non-breaking spaces.
60 *
61 * See https://www.w3.org/TR/html4/struct/text.html#h-9.1
62 *
63 * @type {RegExp}
64 */
65 ve.dm.Converter.static.whitespaceList = ' \\t\\f\\u200b\\r\\n';
66
67 ve.dm.Converter.static.PARSER_MODE = 0;
68 ve.dm.Converter.static.CLIPBOARD_MODE = 1;
69 ve.dm.Converter.static.PREVIEW_MODE = 2;
70
71 /* Static Methods */
72
73 /**
74 * Get linear model data from a string optionally applying annotations
75 *
76 * @static
77 * @param {string} text Plain text to convert
78 * @param {ve.dm.AnnotationSet} [annotations] Annotations to apply
79 * @return {Array} Linear model data, one element per character
80 */
81 ve.dm.Converter.static.getDataContentFromText = function ( text, annotations ) {
82 const characters = text.split( '' );
83
84 if ( !annotations || annotations.isEmpty() ) {
85 return characters;
86 }
87 // Apply annotations to characters
88 for ( let i = 0, len = characters.length; i < len; i++ ) {
89 // Just store the annotations' hashes from the hash-value store
90 characters[ i ] = [ characters[ i ], annotations.getHashes().slice() ];
91 }
92 return characters;
93 };
94
95 /**
96 * Utility function for annotation rendering. Transforms one set of annotations into another
97 * by opening and closing annotations. Each time an annotation is opened or closed, the associated
98 * callback is called with the annotation passed as a parameter.
99 *
100 * Note that currentSet will be modified, and will be equal to targetSet once this function returns.
101 *
102 * @static
103 * @param {ve.dm.AnnotationSet} currentSet The set of annotations currently opened. Will be modified.
104 * @param {ve.dm.AnnotationSet} targetSet The set of annotations we want to have.
105 * @param {Function} open Callback called when an annotation is opened. Passed a ve.dm.Annotation.
106 * @param {Function} close Callback called when an annotation is closed. Passed a ve.dm.Annotation.
107 */
108 ve.dm.Converter.static.openAndCloseAnnotations = function ( currentSet, targetSet, open, close ) {
109 let hash, i, len;
110 // Close annotations as needed
111 // Go through annotationStack from bottom to top (low to high),
112 // and find the first annotation that's not in annotations.
113 if ( currentSet.getLength() ) {
114 const targetSetOpen = targetSet.clone();
115 let startClosingAt;
116 for ( i = 0, len = currentSet.getLength(); i < len; i++ ) {
117 hash = currentSet.getHash( i );
118 // containsComparableForSerialization is expensive,
119 // so do a simple contains check first
120 if (
121 targetSetOpen.containsHash( hash ) ||
122 targetSetOpen.containsComparableForSerialization( currentSet.get( i ) )
123 ) {
124 targetSetOpen.removeHash( hash );
125 } else {
126 startClosingAt = i;
127 break;
128 }
129 }
130 if ( startClosingAt !== undefined ) {
131 // Close all annotations from top to bottom (high to low)
132 // until we reach startClosingAt
133 for ( i = currentSet.getLength() - 1; i >= startClosingAt; i-- ) {
134 close( currentSet.get( i ) );
135 // Remove from currentClone
136 currentSet.removeAt( i );
137 }
138 }
139 }
140
141 if ( targetSet.getLength() ) {
142 const currentSetOpen = currentSet.clone();
143 // Open annotations as needed
144 for ( i = 0, len = targetSet.getLength(); i < len; i++ ) {
145 hash = targetSet.getHash( i );
146 // containsComparableForSerialization is expensive,
147 // so do a simple contains check first
148 if (
149 currentSetOpen.containsHash( hash ) ||
150 currentSetOpen.containsComparableForSerialization( targetSet.get( i ) )
151 ) {
152 // If an annotation is already open remove it from the currentSetOpen list
153 // as it may exist multiple times in the targetSet, and so may need to be
154 // opened again
155 currentSetOpen.removeHash( hash );
156 } else {
157 open( targetSet.get( i ) );
158 // Add to currentClone
159 currentSet.pushHash( hash );
160 }
161 }
162 }
163 };
164
165 /**
166 * Copy attributes from one set of DOM elements to another.
167 *
168 * @static
169 * @param {HTMLElement[]} originalDomElements Array of DOM elements to render from
170 * @param {HTMLElement[]} targetDomElements Array of DOM elements to render onto
171 * @param {boolean|Function} [filter=true] Attribute filter
172 * @param {boolean} [computed=false] If true, use the computed values of attributes where available
173 * @param {boolean} [deep=false] Recurse into child nodes
174 */
175 ve.dm.Converter.static.renderHtmlAttributeList = function ( originalDomElements, targetDomElements, filter, computed, deep ) {
176 if ( filter === undefined ) {
177 filter = true;
178 }
179 if ( filter === false ) {
180 return;
181 }
182
183 for ( let i = 0, ilen = originalDomElements.length; i < ilen; i++ ) {
184 if ( !targetDomElements[ i ] ) {
185 continue;
186 }
187 const attrs = originalDomElements[ i ].attributes;
188 if ( !attrs ) {
189 continue;
190 }
191 for ( let j = 0, jlen = attrs.length; j < jlen; j++ ) {
192 if (
193 targetDomElements[ i ].nodeType === Node.ELEMENT_NODE &&
194 !targetDomElements[ i ].hasAttribute( attrs[ j ].name ) &&
195 ( filter === true || filter( attrs[ j ].name ) )
196 ) {
197 let value;
198 if ( computed && this.computedAttributes.indexOf( attrs[ j ].name ) !== -1 ) {
199 value = originalDomElements[ i ][ attrs[ j ].name ];
200 } else {
201 value = attrs[ j ].value;
202 }
203 targetDomElements[ i ].setAttribute( attrs[ j ].name, value );
204 }
205 }
206
207 // Descend into element children only (skipping text nodes, comment nodes and nodes we just created)
208 if ( deep && !targetDomElements[ i ].veFromDataElement && originalDomElements[ i ].children.length > 0 ) {
209 this.renderHtmlAttributeList(
210 originalDomElements[ i ].children,
211 targetDomElements[ i ].children,
212 filter,
213 computed,
214 true
215 );
216 }
217 }
218 };
219
220 /**
221 * Modify linear model data in-place to move inline meta items out of content context
222 *
223 * All branch node start items must have item.internal.metaItems = []
224 * All inline meta items must have item.internal.isInlineMeta set to true
225 *
226 * After the method completes, each inline meta item will be moved downward to the nearest legal
227 * block position (i.e. just after the close meta parent item), and has these properties:
228 * item.internal.loadMetaParentHash - corresponding meta parent's item.originalDomElementsHash
229 * item.internal.loadMetaParentOffset - offset at load time within the meta parent (0 for start).
230 * Each meta item is appended to the corresponding meta parent's item.internal.metaItems .
231 *
232 * @param {Array} data Linear model data to modify in place
233 */
234 ve.dm.Converter.static.moveInlineMetaItems = function ( data ) {
235 const ancestors = [],
236 pendingMetaItems = [];
237
238 function closestMetaParent() {
239 for ( let n = ancestors.length - 1; n >= 0; n-- ) {
240 const ancestor = ancestors[ n ];
241 if ( ancestor.isMetaParent ) {
242 return ancestor;
243 }
244 }
245 return null;
246 }
247
248 let metaParent;
249 for ( let i = 0; i < data.length; i++ ) {
250 let item = data[ i ];
251 if ( Array.isArray( item ) ) {
252 // Ignore annotations
253 item = item[ 0 ];
254 }
255 if ( !item.type ) {
256 // Item is not a node
257 continue;
258 }
259 if ( item.type[ 0 ] !== '/' ) {
260 // Item is a node start
261 if ( ve.getProp( item, 'internal', 'isInlineMeta' ) ) {
262 // This is an inline meta item: move it
263 delete item.internal.isInlineMeta;
264 metaParent = closestMetaParent();
265 if ( metaParent ) {
266 metaParent.item.internal.metaItems.push( item );
267 pendingMetaItems.push( {
268 item: item,
269 closeItem: data[ i + 1 ],
270 metaParent: metaParent,
271 offset: i - metaParent.offset - 1
272 } );
273 // Remove this item and the immediately following close item
274 data.splice( i, 2 );
275 // Prepare to rescan this index
276 i--;
277 } else {
278 // Inline meta outside meta parent. This can happen if, say,
279 // the document starts with a comment then a meta item.
280 // Skip this item and the immediately following close item
281 i++;
282 }
283 } else {
284 ancestors.push( {
285 item: item,
286 offset: i,
287 isMetaParent: !!ve.getProp( item, 'internal', 'metaItems' )
288 } );
289 }
290 } else {
291 // Item is a node end
292 metaParent = ancestors.pop();
293 if ( metaParent.isMetaParent ) {
294 for ( let j = 0; j < pendingMetaItems.length; j++ ) {
295 const pending = pendingMetaItems[ j ];
296 if ( pending.metaParent.item !== metaParent.item ) {
297 continue;
298 }
299 pending.item.internal.loadMetaParentHash = metaParent.item.originalDomElementsHash;
300 pending.item.internal.loadMetaParentOffset = pending.offset;
301 pendingMetaItems.splice( j, 1 );
302 j--;
303 // This will drop annotations on meta items; fine
304 data.splice( i + 1, 0, pending.item, pending.closeItem );
305 i += 2;
306 }
307 }
308 }
309 }
310 };
311
312 /* Methods */
313
314 /**
315 * Check whether this converter instance is currently inside a getModelFromDom() conversion.
316 *
317 * @return {boolean} Whether we're converting
318 */
319 ve.dm.Converter.prototype.isConverting = function () {
320 return this.contextStack !== null;
321 };
322
323 /**
324 * Get the HashValueStore used for the current conversion.
325 *
326 * @return {ve.dm.HashValueStore|null} Current store, or null if not converting
327 */
328 ve.dm.Converter.prototype.getStore = function () {
329 return this.store;
330 };
331
332 /**
333 * Get the HTML document currently being converted
334 *
335 * @return {HTMLDocument|null} HTML document being converted, or null if not converting
336 */
337 ve.dm.Converter.prototype.getHtmlDocument = function () {
338 return this.doc;
339 };
340
341 /**
342 * Get the HTML document we are converting data for
343 *
344 * @return {HTMLDocument|null} HTML document being converted for, or null if not converting
345 */
346 ve.dm.Converter.prototype.getTargetHtmlDocument = function () {
347 return this.targetDoc;
348 };
349
350 /**
351 * Get the converter mode, one of PARSER_MODE, CLIPBOARD_MODE or PREVIEW_MODE
352 *
353 * @return {number} Converter mode
354 */
355 ve.dm.Converter.prototype.getMode = function () {
356 return this.mode;
357 };
358
359 /**
360 * Checks if the current mode needs a full view rendering in the HTML
361 *
362 * @return {boolean} Mode needs a rendering
363 */
364 ve.dm.Converter.prototype.doesModeNeedRendering = function () {
365 return this.getMode() !== this.constructor.static.PARSER_MODE;
366 };
367
368 /**
369 * Is the current conversion for the parser
370 *
371 * @return {boolean} The conversion is for the paser
372 */
373 ve.dm.Converter.prototype.isForParser = function () {
374 return this.getMode() === this.constructor.static.PARSER_MODE;
375 };
376
377 /**
378 * Is the current conversion for the clipboard
379 *
380 * @return {boolean} The conversion is for the clipboard
381 */
382 ve.dm.Converter.prototype.isForClipboard = function () {
383 return this.getMode() === this.constructor.static.CLIPBOARD_MODE;
384 };
385
386 /**
387 * Is the current conversion for the preview
388 *
389 * @return {boolean} The conversion is for the preview
390 */
391 ve.dm.Converter.prototype.isForPreview = function () {
392 return this.getMode() === this.constructor.static.PREVIEW_MODE;
393 };
394
395 /**
396 * Is the current conversion from the clipboard
397 *
398 * @return {boolean|null} The conversion is from the clipboard, or null if not converting
399 */
400 ve.dm.Converter.prototype.isFromClipboard = function () {
401 return this.fromClipboard;
402 };
403
404 /**
405 * Get the current conversion context. This is the recursion state of getDataFromDomSubtree().
406 *
407 * @return {Object|null} Context object, or null if not converting
408 */
409 ve.dm.Converter.prototype.getCurrentContext = function () {
410 return this.contextStack === null ? null : this.contextStack[ this.contextStack.length - 1 ];
411 };
412
413 /**
414 * Get the annotations currently being applied by the converter. Note that this is specific to
415 * the current recursion level.
416 *
417 * @return {ve.dm.AnnotationSet|null} Annotation set, or null if not converting
418 */
419 ve.dm.Converter.prototype.getActiveAnnotations = function () {
420 const context = this.getCurrentContext();
421 return context ? context.annotations : null;
422 };
423
424 /**
425 * Whether the converter is currently expecting content. Note that this is specific to the current
426 * recursion level.
427 *
428 * @return {boolean|null} Boolean indicating whether content is expected, or null if not converting
429 */
430 ve.dm.Converter.prototype.isExpectingContent = function () {
431 const context = this.getCurrentContext();
432 return context ? context.expectingContent : null;
433 };
434
435 /**
436 * Whether the converter can currently accept a child node with the given type.
437 *
438 * @param {string} nodeType
439 * @return {boolean|null} Whether the node type is valid, or null if not converting
440 */
441 ve.dm.Converter.prototype.isValidChildNodeType = function ( nodeType ) {
442 const context = this.getCurrentContext();
443 if ( !context ) {
444 return null;
445 }
446 const childTypes = this.nodeFactory.getChildNodeTypes( context.branchType );
447 return ( childTypes === null || childTypes.indexOf( nodeType ) !== -1 );
448 };
449
450 /**
451 * Whether the conversion is currently inside a wrapper paragraph generated by the converter.
452 * Note that this is specific to the current recursion level.
453 *
454 * @return {boolean|null} Boolean indicating whether we're wrapping, or null if not converting
455 */
456 ve.dm.Converter.prototype.isInWrapper = function () {
457 const context = this.getCurrentContext();
458 return context ? context.inWrapper : null;
459 };
460
461 /**
462 * Whether the active wrapper can be closed. Note that this is specific to the current recursion
463 * level. If there is no active wrapper, this returns false.
464 *
465 * @return {boolean|null} Boolean indicating whether the wrapper can be closed, or null if not converting
466 */
467 ve.dm.Converter.prototype.canCloseWrapper = function () {
468 const context = this.getCurrentContext();
469 return context ? context.canCloseWrapper : null;
470 };
471
472 /**
473 * Get the DOM element for a given linear model element.
474 *
475 * This invokes the toDomElements function registered for the element type.
476 *
477 * @param {Object|Array} dataElements Linear model element or data slice
478 * @param {HTMLDocument} doc Document to create DOM elements in
479 * @param {Node[]} [childDomElements] Array of child DOM elements to pass in (annotations only)
480 * @return {Node[]|boolean} DOM elements, or false if the element cannot be converted.
481 * If the first DOMelement has a 'handledOwnChildren' property set, the converter treats it as if it
482 * were a handlesOwnChildren node.
483 */
484 ve.dm.Converter.prototype.getDomElementsFromDataElement = function ( dataElements, doc, childDomElements ) {
485 const dataElement = Array.isArray( dataElements ) ? dataElements[ 0 ] : dataElements,
486 nodeClass = this.modelRegistry.lookup( dataElement.type );
487
488 if ( !nodeClass ) {
489 throw new Error( 'Attempting to convert unknown data element type ' + dataElement.type );
490 }
491 if ( nodeClass.static.isInternal ) {
492 return false;
493 }
494 const domElements = nodeClass.static.toDomElements( dataElements, doc, this, childDomElements );
495 if ( !Array.isArray( domElements ) && !( nodeClass.prototype instanceof ve.dm.Annotation ) ) {
496 throw new Error( 'toDomElements() failed to return an array when converting element of type ' + dataElement.type );
497 }
498 const originalDomElements = this.store.value( dataElement.originalDomElementsHash );
499 // Optimization: don't call renderHtmlAttributeList if returned domElements are equal to the originals
500 if ( originalDomElements && !ve.isEqualDomElements( domElements, originalDomElements ) ) {
501 this.constructor.static.renderHtmlAttributeList(
502 originalDomElements,
503 domElements,
504 nodeClass.static.preserveHtmlAttributes,
505 // computed
506 false,
507 // deep
508 (
509 !this.nodeFactory.lookup( dataElement.type ) ||
510 !this.nodeFactory.canNodeHaveChildren( dataElement.type ) ||
511 this.nodeFactory.doesNodeHandleOwnChildren( dataElement.type )
512 )
513 );
514 }
515 // TODO: This is only for the diff. Eventually should make a DiffConverter subclass
516 if ( dataElement.internal && dataElement.internal.diff ) {
517 Array.prototype.forEach.call( domElements, ( domElement ) => {
518 for ( const key in dataElement.internal.diff ) {
519 // toDomElements is a misnomer, it can actually return other nodes,
520 // such as comment nodes or text nodes.
521 if ( domElement.setAttribute ) {
522 domElement.setAttribute( key, dataElement.internal.diff[ key ] );
523 }
524 }
525 } );
526 }
527 // Mark branch nodes as generated from dataElement, so we don't try and descend into them in a deep renderHtmlAttributeList call
528 if ( this.nodeFactory.lookup( dataElement.type ) && this.nodeFactory.canNodeHaveChildren( dataElement.type ) ) {
529 const hasSignificantWhitespace = this.nodeFactory.doesNodeHaveSignificantWhitespace( dataElement.type );
530 domElements.forEach( ( domElement ) => {
531 domElement.veFromDataElement = true;
532 if ( hasSignificantWhitespace ) {
533 domElement.veHasSignificantWhitespace = true;
534 }
535 } );
536 }
537 return domElements;
538 };
539
540 /**
541 * Create a data element from a DOM element.
542 *
543 * @param {ve.dm.Model} modelClass Model class to use for conversion
544 * @param {Node[]} domElements DOM elements to convert
545 * @return {Object|Array|null} Data element or array of linear model data, or null to alienate
546 */
547 ve.dm.Converter.prototype.createDataElements = function ( modelClass, domElements ) {
548 let dataElements = modelClass.static.toDataElement( domElements, this );
549
550 if ( !dataElements ) {
551 return null;
552 }
553 if ( !Array.isArray( dataElements ) ) {
554 dataElements = [ dataElements ];
555 }
556 if ( dataElements.length ) {
557 let serializer;
558 if ( modelClass.prototype instanceof ve.dm.Annotation ) {
559 serializer = function ( node ) {
560 // Do not include childNodes; see T160839
561 return node.cloneNode( false ).outerHTML;
562 };
563 } else {
564 serializer = ve.getNodeHtml;
565 }
566 dataElements[ 0 ].originalDomElementsHash = this.store.hash(
567 domElements,
568 domElements.map( serializer ).join( '' )
569 );
570 if ( modelClass.prototype instanceof ve.dm.BranchNode && modelClass.static.childNodeTypes === null ) {
571 // Set this item up as a meta parent
572 ve.setProp( dataElements[ 0 ], 'internal', 'metaItems', [] );
573 ve.setProp( dataElements[ 0 ], 'internal', 'changesSinceLoad', 0 );
574 }
575 }
576 return dataElements;
577 };
578
579 /**
580 * Build an HTML DOM node for a linear model annotation.
581 *
582 * @param {Object} dataAnnotation
583 * @param {HTMLDocument} doc HTML document to create element with
584 * @return {HTMLElement} HTML DOM node
585 */
586 ve.dm.Converter.prototype.getDomElementFromDataAnnotation = function ( dataAnnotation, doc ) {
587 const htmlData = dataAnnotation.toHtml(),
588 domElement = doc.createElement( htmlData.tag );
589
590 ve.setDomAttributes( domElement, htmlData.attributes );
591 return domElement;
592 };
593
594 /**
595 * Convert an HTML document to a document model.
596 *
597 * @param {HTMLDocument} doc HTML document to convert
598 * @param {Object} [options] Conversion options
599 * @param {HTMLDocument} [options.targetDoc=doc] Target HTML document we are converting for, if different from doc
600 * @param {boolean} [options.fromClipboard=false] Conversion is from clipboard
601 * @param {string} [options.lang] Document language code
602 * @param {string} [options.dir] Document directionality (ltr/rtl)
603 * @param {ve.dm.HashValueStore} [store] Hash value store
604 * @return {ve.dm.Document} Document model
605 */
606 ve.dm.Converter.prototype.getModelFromDom = function ( doc, options, store ) {
607 const tmpDoc = new ve.dm.Document();
608 const internalList = new ve.dm.InternalList( tmpDoc );
609
610 store = store || new ve.dm.HashValueStore();
611 options = options || {};
612
613 // Set up the converter state
614 this.doc = doc;
615 this.targetDoc = options.targetDoc || doc;
616 this.fromClipboard = options.fromClipboard;
617 this.store = store;
618 this.internalList = internalList;
619 this.contextStack = [];
620 // Possibly do things with doc and the head in the future
621
622 // Generate data
623 const data = this.getDataFromDomSubtree( doc.body );
624 this.constructor.static.moveInlineMetaItems( data );
625
626 const linearData = new ve.dm.ElementLinearData( store, data );
627 const refData = this.internalList.convertToData( this, doc );
628 linearData.batchSplice( linearData.getLength(), 0, refData );
629 const innerWhitespace = this.getInnerWhitespace( linearData );
630
631 // Clear the state
632 this.doc = null;
633 this.targetDoc = null;
634 this.fromClipboard = null;
635 this.store = null;
636 this.internalList = null;
637 this.contextStack = null;
638
639 return new ve.dm.Document( linearData, doc, undefined, internalList, innerWhitespace, options.lang, options.dir, null, null, tmpDoc.getStorage() );
640 };
641
642 /**
643 * Wrapper for getDataFromDom which resets contextStack before the call
644 * and then set it back after the call.
645 *
646 * TODO: This is kind of a hack, better implementation would be more appropriate in near future.
647 *
648 * @param {HTMLElement} domElement HTML element to convert
649 * @param {Object} [wrapperElement] Data element to wrap the returned data in
650 * @param {ve.dm.AnnotationSet} [annotationSet] Override the set of annotations to use
651 * @return {Array} Linear model data
652 */
653 ve.dm.Converter.prototype.getDataFromDomClean = function ( domElement, wrapperElement, annotationSet ) {
654 const contextStack = this.contextStack;
655 this.contextStack = [];
656 const result = this.getDataFromDomSubtree( domElement, wrapperElement, annotationSet );
657 this.contextStack = contextStack;
658 return result;
659 };
660
661 /**
662 * Get linear model data from a DOM node. Called recursively. For internal use
663 * and ve.dm.Model.static.toDataElement() implementations.
664 *
665 * @param {HTMLElement} domElement HTML element to convert
666 * @param {Object} [wrapperElement] Data element to wrap the returned data in
667 * @param {ve.dm.AnnotationSet} [annotationSet] Override the set of annotations to use
668 * @return {Array} Linear model data
669 */
670 ve.dm.Converter.prototype.getDataFromDomSubtree = function ( domElement, wrapperElement, annotationSet ) {
671 const modelRegistry = this.modelRegistry,
672 data = [],
673 context = {},
674 prevContext = this.contextStack.length ?
675 this.contextStack[ this.contextStack.length - 1 ] : null;
676 let wrappingParagraph,
677 nextWhitespace = '',
678 wrappedWhitespace = '',
679 wrappedWhitespaceIndex,
680 wrappedMetaItems = [];
681
682 /**
683 * Add whitespace to an element at a specific offset.
684 *
685 * @private
686 * @param {Array} element Data element
687 * @param {number} index Whitespace index, 0-3
688 * @param {string} whitespace Whitespace content
689 */
690 const addWhitespace = ( element, index, whitespace ) => {
691 if ( !whitespace ) {
692 return;
693 }
694 if ( !element.internal ) {
695 element.internal = {};
696 }
697 // whitespace = [ outerPre, innerPre, innerPost, outerPost ]
698 // <tag> text </tag> <nextTag>
699 // ^^^^^^^^ ^^^^^^^^ ^^^^^^^^^ ^^^^^^^^^
700 // outerPre innerPre innerPost outerPost
701 if ( !element.internal.whitespace ) {
702 element.internal.whitespace = [];
703 }
704 element.internal.whitespace[ index ] = whitespace;
705 };
706 const processNextWhitespace = ( element ) => {
707 // This function uses and changes nextWhitespace in the outer function's scope,
708 // which means it's not really a function but more of a shortcut.
709 if ( nextWhitespace !== '' ) {
710 addWhitespace( element, 0, nextWhitespace );
711 nextWhitespace = '';
712 }
713 };
714 // FIXME rewrite this horrible meta item / whitespace queueing/wrapping business
715 const outputWrappedMetaItems = ( whitespaceTreatment ) => {
716 const toInsert = [];
717 let prev = wrappingParagraph;
718
719 for ( let j = 0, len = wrappedMetaItems.length; j < len; j++ ) {
720 if ( wrappedMetaItems[ j ].type && wrappedMetaItems[ j ].type.charAt( 0 ) !== '/' ) {
721 if ( wrappedMetaItems[ j ].internal && wrappedMetaItems[ j ].internal.whitespace ) {
722 if ( whitespaceTreatment === 'restore' ) {
723 ve.batchPush( toInsert, this.constructor.static.getDataContentFromText(
724 wrappedMetaItems[ j ].internal.whitespace[ 0 ], context.annotations
725 ) );
726 delete wrappedMetaItems[ j ].internal;
727 } else if ( whitespaceTreatment === 'fixup' ) {
728 addWhitespace( prev, 3, wrappedMetaItems[ j ].internal.whitespace[ 0 ] );
729 }
730 }
731 prev = wrappedMetaItems[ j ];
732 }
733 toInsert.push( wrappedMetaItems[ j ] );
734 }
735 if ( wrappedWhitespace !== '' && whitespaceTreatment === 'restore' ) {
736 // If we have wrapped whitespace, insert the wrapped meta items before it
737 // This is horrible and this whole system desperately needs to be rewritten
738 ve.batchSplice( data, wrappedWhitespaceIndex, 0, toInsert );
739 } else {
740 ve.batchPush( data, toInsert );
741 }
742 wrappedMetaItems = [];
743 };
744 const startWrapping = () => {
745 // Mark this paragraph as having been generated by
746 // us, so we can strip it on the way out
747 wrappingParagraph = {
748 type: 'paragraph',
749 internal: { generated: 'wrapper', metaItems: [] }
750 };
751 data.push( wrappingParagraph );
752 context.inWrapper = true;
753 context.canCloseWrapper = true;
754 context.expectingContent = true;
755 processNextWhitespace( wrappingParagraph );
756 };
757 const stopWrapping = () => {
758 if ( wrappedWhitespace !== '' ) {
759 // Remove wrappedWhitespace from data
760 data.splice( wrappedWhitespaceIndex, wrappedWhitespace.length );
761 // Add whitespace to the last sibling: either the last meta item or the wrapper paragraph
762 addWhitespace( wrappedMetaItems.length > 0 ? wrappedMetaItems[ wrappedMetaItems.length - 2 ] : wrappingParagraph, 3, wrappedWhitespace );
763 nextWhitespace = wrappedWhitespace;
764 }
765 data.push( { type: '/paragraph' } );
766 outputWrappedMetaItems( 'fixup' );
767 wrappingParagraph = undefined;
768 context.inWrapper = false;
769 context.canCloseWrapper = false;
770 context.expectingContent = context.originallyExpectingContent;
771 };
772 const getAboutGroup = ( node ) => {
773 const group = [ node ];
774
775 if ( node.nodeType !== Node.ELEMENT_NODE || node.getAttribute( 'about' ) === null ) {
776 return group;
777 }
778 const about = node.getAttribute( 'about' );
779 while ( ( node = node.nextSibling ) !== null ) {
780 if ( node.nodeType === Node.ELEMENT_NODE && node.getAttribute( 'about' ) === about ) {
781 group.push( node );
782 } else {
783 break;
784 }
785 }
786 return group;
787 };
788 const isAllInstanceOf = ( linearData, targetClass ) => {
789 for ( let j = linearData.length - 1; j >= 0; j-- ) {
790 const type = ve.dm.LinearData.static.getType( linearData[ j ] );
791 if ( type ) {
792 const itemClass = modelRegistry.lookup( type ) || ve.dm.AlienNode;
793 if ( !( itemClass === targetClass || itemClass.prototype instanceof targetClass ) ) {
794 return false;
795 }
796 } else {
797 return false;
798 }
799 }
800 return true;
801 };
802
803 context.annotations = annotationSet || (
804 prevContext ? prevContext.annotations.clone() : new ve.dm.AnnotationSet( this.store )
805 );
806 context.branchType = wrapperElement ? wrapperElement.type : (
807 prevContext ? prevContext.branchType : 'document'
808 );
809 context.branchHasContent = this.nodeFactory.canNodeContainContent( context.branchType );
810 context.originallyExpectingContent = context.branchHasContent || !context.annotations.isEmpty();
811 context.expectingContent = context.originallyExpectingContent;
812 context.inWrapper = prevContext ? prevContext.inWrapper : false;
813 context.canCloseWrapper = false;
814 this.contextStack.push( context );
815
816 // Open element
817 if ( wrapperElement ) {
818 data.push( wrapperElement );
819 }
820 // Add contents
821 function setInlineMeta( element ) {
822 ve.setProp( element, 'internal', 'isInlineMeta', true );
823 }
824
825 let prevElement;
826 for ( let i = 0; i < domElement.childNodes.length; i++ ) {
827 const childNode = domElement.childNodes[ i ];
828 switch ( childNode.nodeType ) {
829 case Node.ELEMENT_NODE:
830 case Node.COMMENT_NODE: {
831 if (
832 childNode.getAttribute &&
833 childNode.getAttribute( 'data-ve-ignore' )
834 ) {
835 continue;
836 }
837 const aboutGroup = getAboutGroup( childNode );
838 const modelName = this.modelRegistry.matchElement( childNode, aboutGroup.length > 1 );
839 let modelClass = this.modelRegistry.lookup( modelName ) || ve.dm.AlienNode;
840 let childNodes;
841 if ( modelClass.prototype instanceof ve.dm.Annotation ) {
842 childNodes = [ childNode ];
843 } else {
844 // Node or meta item
845 childNodes = modelClass.static.enableAboutGrouping ?
846 aboutGroup : [ childNode ];
847 }
848 let childDataElements = this.createDataElements( modelClass, childNodes );
849
850 if ( !childDataElements ) {
851 // Alienate
852 modelClass = ve.dm.AlienNode;
853 childNodes = modelClass.static.enableAboutGrouping ?
854 aboutGroup : [ childNode ];
855 childDataElements = this.createDataElements( modelClass, childNodes );
856 } else if ( childDataElements.length ) {
857 // Update modelClass to reflect the type we got back
858 modelClass = this.modelRegistry.lookup( childDataElements[ 0 ].type );
859 } else {
860 continue;
861 }
862
863 // If we're about to start wrapping for an annotation,
864 // check paragraphs are actually allowed here.
865 if (
866 !context.inWrapper && !context.expectingContent &&
867 modelClass.prototype instanceof ve.dm.Annotation &&
868 !this.isValidChildNodeType( 'paragraph' )
869 ) {
870 // Alienate (force block mode as we are replacing a wrapper)
871 modelClass = ve.dm.AlienBlockNode;
872 childNodes = modelClass.static.enableAboutGrouping ?
873 aboutGroup : [ childNode ];
874 childDataElements = this.createDataElements( modelClass, childNodes );
875 }
876
877 // Now take the appropriate action based on that
878 if ( modelClass.prototype instanceof ve.dm.Annotation ) {
879 const annotation = this.annotationFactory.createFromElement( childDataElements[ 0 ], this.store );
880 // Start wrapping if needed
881 if ( !context.inWrapper && !context.expectingContent ) {
882 startWrapping();
883 prevElement = wrappingParagraph;
884 }
885 // Append child element data
886 const childAnnotations = context.annotations.clone();
887 childAnnotations.push( annotation );
888
889 childDataElements = this.getDataFromDomSubtree( childNode, undefined, childAnnotations );
890 if ( !childDataElements.length || isAllInstanceOf( childDataElements, ve.dm.AlienMetaItem ) ) {
891 // Empty annotation, create a meta item
892 if ( !childDataElements.length || isAllInstanceOf( childDataElements, ve.dm.RemovableAlienMetaItem ) ) {
893 childDataElements = this.createDataElements( ve.dm.RemovableAlienMetaItem, childNodes );
894 } else {
895 childDataElements = this.createDataElements( ve.dm.AlienMetaItem, childNodes );
896 }
897 childDataElements.push( { type: '/' + childDataElements[ 0 ].type } );
898 // Annotate meta item
899 if ( !context.annotations.isEmpty() ) {
900 childDataElements[ 0 ].annotations = context.annotations.getHashes().slice();
901 }
902 // Mark meta items to be moved outside of content context, as we can't handle them here
903 // (context.expectingContent is always true at this point)
904 setInlineMeta( childDataElements[ 0 ] );
905 }
906 outputWrappedMetaItems( 'restore' );
907 ve.batchPush( data, childDataElements );
908 // Clear wrapped whitespace
909 wrappedWhitespace = '';
910 } else {
911 // Node or meta item
912 if ( modelClass.prototype instanceof ve.dm.MetaItem ) {
913 if ( context.expectingContent ) {
914 // Mark meta items to be moved outside of content context, as we can't handle them here
915 childDataElements.forEach( setInlineMeta );
916 }
917
918 // No additional processing needed
919 // Write to data and continue
920 if ( childDataElements.length === 1 ) {
921 childDataElements.push( { type: '/' + childDataElements[ 0 ].type } );
922 }
923 // Annotate meta item
924 if ( !context.annotations.isEmpty() ) {
925 childDataElements[ 0 ].annotations = context.annotations.getHashes().slice();
926 }
927 // Queue wrapped meta items only if it's actually possible for us to move them out
928 // of the wrapper
929 if ( context.inWrapper && context.canCloseWrapper ) {
930 ve.batchPush( wrappedMetaItems, childDataElements );
931 if ( wrappedWhitespace !== '' ) {
932 data.splice( wrappedWhitespaceIndex, wrappedWhitespace.length );
933 addWhitespace( childDataElements[ 0 ], 0, wrappedWhitespace );
934 nextWhitespace = wrappedWhitespace;
935 wrappedWhitespace = '';
936 }
937 } else {
938 outputWrappedMetaItems( 'restore' );
939 ve.batchPush( data, childDataElements );
940 processNextWhitespace( childDataElements[ 0 ] );
941 prevElement = childDataElements[ 0 ];
942 }
943 // In case we consumed multiple childNodes, adjust i accordingly
944 i += childNodes.length - 1;
945 break;
946 }
947
948 let childIsContent = this.nodeFactory.canNodeSerializeAsContent( childDataElements[ 0 ].type );
949
950 // If childIsContent isn't what we expect, adjust
951 if ( !context.expectingContent && childIsContent ) {
952 startWrapping();
953 prevElement = wrappingParagraph;
954 } else if ( context.expectingContent && !childIsContent ) {
955 if ( context.inWrapper && context.canCloseWrapper ) {
956 stopWrapping();
957 } else {
958 // Alienate
959 modelClass = ve.dm.AlienNode;
960 childNodes = modelClass.static.enableAboutGrouping ?
961 aboutGroup : [ childNode ];
962 childDataElements = this.createDataElements( modelClass, childNodes );
963 childIsContent = this.nodeFactory.canNodeSerializeAsContent( childDataElements[ 0 ].type );
964 }
965 }
966
967 // If we're inserting content into a wrapper, any wrapped whitespace and meta
968 // items up until this point are here to stay
969 if ( context.inWrapper && childIsContent ) {
970 outputWrappedMetaItems( 'restore' );
971 wrappedWhitespace = '';
972 // Don't record the wrapped whitespace as the child node's outer whitespace
973 nextWhitespace = '';
974 }
975
976 // Annotate child
977 if ( childIsContent && !context.annotations.isEmpty() ) {
978 childDataElements[ 0 ].annotations = context.annotations.getHashes().slice();
979 }
980
981 // Output child and process children if needed
982 if (
983 childDataElements.length === 1 &&
984 childNodes.length === 1 &&
985 this.nodeFactory.canNodeHaveChildren( childDataElements[ 0 ].type ) &&
986 !this.nodeFactory.doesNodeHandleOwnChildren( childDataElements[ 0 ].type )
987 ) {
988 // Recursion
989 // Opening and closing elements are added by the recursion too
990 outputWrappedMetaItems( 'restore' );
991 ve.batchPush( data,
992 this.getDataFromDomSubtree( childNode, childDataElements[ 0 ],
993 new ve.dm.AnnotationSet( this.store )
994 )
995 );
996 } else {
997 if ( childDataElements.length === 1 ) {
998 childDataElements.push( { type: '/' + childDataElements[ 0 ].type } );
999 }
1000 // Write childDataElements directly
1001 outputWrappedMetaItems( 'restore' );
1002 ve.batchPush( data, childDataElements );
1003 }
1004 processNextWhitespace( childDataElements[ 0 ] );
1005 prevElement = childDataElements[ 0 ];
1006
1007 // In case we consumed multiple childNodes, adjust i accordingly
1008 i += childNodes.length - 1;
1009 }
1010 break;
1011 }
1012 case Node.TEXT_NODE: {
1013 let text = childNode.data;
1014 if ( text === '' ) {
1015 // Empty text node?!?
1016 break;
1017 }
1018 if ( !context.originallyExpectingContent ) {
1019 // Strip and store outer whitespace
1020 if ( this.onlyWhitespaceRegex.test( text ) ) {
1021 // This text node is whitespace only
1022 if ( context.inWrapper ) {
1023 // We're already wrapping, so output this whitespace
1024 // and store it in wrappedWhitespace (see
1025 // comment about wrappedWhitespace below)
1026 wrappedWhitespace = text;
1027 wrappedWhitespaceIndex = data.length;
1028 ve.batchPush( data,
1029 this.constructor.static.getDataContentFromText( wrappedWhitespace, context.annotations )
1030 );
1031 } else {
1032 // We're not in wrapping mode, store this whitespace
1033 if ( !prevElement ) {
1034 if ( wrapperElement ) {
1035 // First child, store as inner
1036 // whitespace in the parent
1037 addWhitespace( wrapperElement, 1, text );
1038 }
1039 // Else, WTF?!? This is not supposed to
1040 // happen, but it's not worth
1041 // throwing an exception over.
1042 } else {
1043 addWhitespace( prevElement, 3, text );
1044 }
1045 nextWhitespace = text;
1046 wrappedWhitespace = '';
1047 outputWrappedMetaItems( 'restore' );
1048 }
1049 // We're done, no actual text left to process
1050 break;
1051 } else {
1052 // This text node contains actual text
1053 // Separate the real text from the whitespace
1054 // HACK: '.' doesn't match newlines in JS, so use
1055 // [\s\S] to match any character
1056 const matches = text.match( this.trimWhitespaceRegex );
1057 if ( !context.inWrapper ) {
1058 // Wrap the text in a paragraph and output it
1059 startWrapping();
1060
1061 // Only store leading whitespace if we just
1062 // started wrapping
1063 if ( matches[ 1 ] !== '' ) {
1064 if ( !prevElement ) {
1065 if ( wrapperElement ) {
1066 // First child, store as inner
1067 // whitespace in the parent
1068 addWhitespace( wrapperElement, 1, matches[ 1 ] );
1069 }
1070 // Else, WTF?!? This is not supposed to
1071 // happen, but it's not worth
1072 // throwing an exception over.
1073 } else {
1074 addWhitespace( prevElement, 3, matches[ 1 ] );
1075 }
1076 addWhitespace( wrappingParagraph, 0, matches[ 1 ] );
1077 }
1078 } else {
1079 outputWrappedMetaItems( 'restore' );
1080 // We were already wrapping in a paragraph,
1081 // so the leading whitespace must be output
1082 ve.batchPush( data,
1083 this.constructor.static.getDataContentFromText( matches[ 1 ], context.annotations )
1084 );
1085 }
1086 // Output the text sans whitespace
1087 ve.batchPush( data,
1088 this.constructor.static.getDataContentFromText( matches[ 2 ], context.annotations )
1089 );
1090
1091 // Don't store this in wrappingParagraph.internal.whitespace[3]
1092 // and nextWhitespace just yet. Instead, store it
1093 // in wrappedWhitespace. There might be more text
1094 // nodes after this one, so we output wrappedWhitespace
1095 // for now and undo that if it turns out this was
1096 // the last text node. We can't output it later
1097 // because we have to apply the correct annotations.
1098 wrappedWhitespace = matches[ 3 ];
1099 wrappedWhitespaceIndex = data.length;
1100 ve.batchPush( data,
1101 this.constructor.static.getDataContentFromText( wrappedWhitespace, context.annotations )
1102 );
1103 prevElement = wrappingParagraph;
1104 break;
1105 }
1106 }
1107
1108 // Strip leading and trailing inner whitespace
1109 // (but only in non-annotation nodes)
1110 // and store it so it can be restored later.
1111 if (
1112 context.annotations.isEmpty() && i === 0 && wrapperElement &&
1113 !this.nodeFactory.doesNodeHaveSignificantWhitespace( wrapperElement.type )
1114 ) {
1115 // Strip leading whitespace from the first child
1116 const matches = text.match( this.leadingWhitespacesRegex );
1117 if ( matches && matches[ 0 ] !== '' ) {
1118 addWhitespace( wrapperElement, 1, matches[ 0 ] );
1119 text = text.slice( matches[ 0 ].length );
1120 }
1121 }
1122 if (
1123 context.annotations.isEmpty() &&
1124 i === domElement.childNodes.length - 1 &&
1125 wrapperElement &&
1126 !this.nodeFactory.doesNodeHaveSignificantWhitespace( wrapperElement.type )
1127 ) {
1128 // Strip trailing whitespace from the last child
1129 const matches = text.match( this.trailingWhitespacesRegex );
1130 if ( matches && matches[ 0 ] !== '' ) {
1131 addWhitespace( wrapperElement, 2, matches[ 0 ] );
1132 text = text.slice( 0, text.length - matches[ 0 ].length );
1133 }
1134 }
1135
1136 // Annotate the text and output it
1137 ve.batchPush( data,
1138 this.constructor.static.getDataContentFromText( text, context.annotations )
1139 );
1140 break;
1141 }
1142 }
1143 }
1144 // End auto-wrapping of bare content
1145 if ( context.inWrapper && context.canCloseWrapper ) {
1146 stopWrapping();
1147 // HACK: don't set context.inWrapper = false here because it's checked below
1148 context.inWrapper = true;
1149 }
1150
1151 // If we're closing a node that doesn't have any children, but could contain a paragraph,
1152 // add a paragraph. This prevents things like empty list items
1153 if ( context.branchType !== 'paragraph' && wrapperElement && data[ data.length - 1 ] === wrapperElement &&
1154 !context.inWrapper && !this.nodeFactory.canNodeContainContent( context.branchType ) &&
1155 !this.nodeFactory.isNodeContent( context.branchType ) &&
1156 this.isValidChildNodeType( 'paragraph' )
1157 ) {
1158 const wrapperParagraph = { type: 'paragraph', internal: { generated: 'wrapper' } };
1159 processNextWhitespace( wrapperParagraph );
1160 data.push( wrapperParagraph );
1161 data.push( { type: '/paragraph' } );
1162 }
1163
1164 // Close element
1165 if ( wrapperElement ) {
1166 // Add the whitespace after the last child to the parent as innerPost
1167 // But don't do this if the parent is empty, because in that case we've already put that
1168 // whitespace in innerPre
1169 if ( nextWhitespace !== '' && data[ data.length - 1 ] !== wrapperElement ) {
1170 addWhitespace( wrapperElement, 2, nextWhitespace );
1171 nextWhitespace = '';
1172 }
1173 data.push( { type: '/' + wrapperElement.type } );
1174 }
1175 // Don't return an empty document
1176 if ( context.branchType === 'document' && isAllInstanceOf( data, ve.dm.MetaItem ) && !annotationSet ) {
1177 const emptyParagraph = { type: 'paragraph', internal: { generated: 'empty' } };
1178 processNextWhitespace( emptyParagraph );
1179 data.push( emptyParagraph );
1180 data.push( { type: '/paragraph' } );
1181 }
1182
1183 this.contextStack.pop();
1184 return data;
1185 };
1186
1187 /**
1188 * Get inner whitespace from linear data
1189 *
1190 * @param {ve.dm.ElementLinearData} data Linear model data
1191 * @return {Array.<string|undefined>} Sparse array of whitespace strings: [ innerLeft, innerRight ]
1192 */
1193 ve.dm.Converter.prototype.getInnerWhitespace = function ( data ) {
1194 const innerWhitespace = new Array( 2 );
1195 let stack = 0,
1196 last = data.getLength() - 1;
1197
1198 let whitespace;
1199 if ( data.isOpenElementData( 0 ) ) {
1200 whitespace = ve.getProp( data.getData( 0 ), 'internal', 'whitespace' );
1201 innerWhitespace[ 0 ] = whitespace ? whitespace[ 0 ] : undefined;
1202 }
1203 if ( data.isCloseElementData( last ) ) {
1204 // Find matching opening tag of the last close tag
1205 stack++;
1206 while ( --last ) {
1207 if ( data.isCloseElementData( last ) ) {
1208 stack++;
1209 } else if ( data.isOpenElementData( last ) ) {
1210 stack--;
1211 if ( stack === 0 && data.getType( last ) !== 'internalList' ) {
1212 break;
1213 }
1214 }
1215 }
1216 whitespace = ve.getProp( data.getData( last ), 'internal', 'whitespace' );
1217 innerWhitespace[ 1 ] = whitespace ? whitespace[ 3 ] : undefined;
1218 }
1219 return innerWhitespace;
1220 };
1221
1222 /**
1223 * Convert document model to an HTML DOM
1224 *
1225 * @param {ve.dm.Document} model Document model
1226 * @param {number} [mode=PARSER_MODE] Conversion mode, defaults to PARSER_MODE
1227 * @return {HTMLDocument} Document containing the resulting HTML
1228 */
1229 ve.dm.Converter.prototype.getDomFromModel = function ( model, mode ) {
1230 // Backwards compatibility with 'forClipboard' argument
1231 if ( typeof mode === 'boolean' ) {
1232 mode = mode ? this.constructor.static.CLIPBOARD_MODE : this.constructor.static.PARSER_MODE;
1233 }
1234 mode = mode || this.constructor.static.PARSER_MODE;
1235
1236 const doc = ve.createDocumentFromHtml( '' );
1237 this.getDomSubtreeFromModel( model, doc.body, mode );
1238
1239 return doc;
1240 };
1241
1242 /**
1243 * Convert model node to an HTML DOM
1244 *
1245 * @param {ve.dm.Node} node Model node
1246 * @param {number} [mode=PARSER_MODE] Conversion mode, defaults to PARSER_MODE
1247 * @return {HTMLDocument} Document containing the resulting HTML
1248 */
1249 ve.dm.Converter.prototype.getDomFromNode = function ( node, mode ) {
1250 // Backwards compatibility with 'forClipboard' argument
1251 if ( typeof mode === 'boolean' ) {
1252 mode = mode ? this.constructor.static.CLIPBOARD_MODE : this.constructor.static.PARSER_MODE;
1253 }
1254 mode = mode || this.constructor.static.PARSER_MODE;
1255 return this.getDomFromModel(
1256 node.getDocument().shallowCloneFromRange( node.isInternal() ? node.getRange() : node.getOuterRange() ),
1257 mode
1258 );
1259 };
1260
1261 /**
1262 * Convert document model to an HTML DOM subtree and add it to a container element.
1263 *
1264 * @param {ve.dm.Document} model Document model
1265 * @param {HTMLElement} container DOM element to add the generated elements to. Should be empty.
1266 * @param {number} [mode=PARSER_MODE] Conversion mode, defaults to PARSER_MODE
1267 */
1268 ve.dm.Converter.prototype.getDomSubtreeFromModel = function ( model, container, mode ) {
1269 if ( typeof mode === 'boolean' ) {
1270 mode = mode ? this.constructor.static.CLIPBOARD_MODE : this.constructor.static.PARSER_MODE;
1271 }
1272 mode = mode || this.constructor.static.PARSER_MODE;
1273 // Set up the converter state
1274 this.documentData = model.getFullData( undefined, 'roundTrip' );
1275 this.store = model.getStore();
1276 this.internalList = model.getInternalList();
1277 // Internal list of the doc this was cloned from, or itself if not cloned
1278 this.originalDocInternalList = model.getOriginalDocument() ? model.getOriginalDocument().getInternalList() : this.internalList;
1279 this.mode = mode;
1280
1281 this.getDomSubtreeFromData( this.documentData, container, model.getInnerWhitespace() );
1282
1283 // Clear the state
1284 this.documentData = null;
1285 this.store = null;
1286 this.internalList = null;
1287 this.originalDocInternalList = null;
1288 this.mode = null;
1289 };
1290
1291 /**
1292 * Convert linear model data to an HTML DOM subtree and add it to a container element.
1293 *
1294 * @param {Array} data Linear model data
1295 * @param {HTMLElement} container DOM element to add the generated elements to. Should be empty.
1296 * @param {Array.<string|undefined>} [innerWhitespace] Inner whitespace if the container is the body
1297 * @throws Unbalanced data: looking for closing /type
1298 */
1299 ve.dm.Converter.prototype.getDomSubtreeFromData = function ( data, container, innerWhitespace ) {
1300 const whitespaceHtmlChars = ve.visibleWhitespaceCharacters,
1301 isForPreview = this.isForPreview(),
1302 dataLen = data.length,
1303 doc = container.ownerDocument;
1304 let text, annotatedDomElements, annotatedDomElementStack,
1305 domElement = container;
1306
1307 // TODO this whole function should be rewritten with a domElementStack and ascend() and
1308 // descend() functions, to build the whole DOM bottom-up rather than top-down. That would make
1309 // unwrapping easier and will hopefully result in fewer DOM operations.
1310
1311 const openAnnotation = () => {
1312 // Add text if needed
1313 if ( text.length > 0 ) {
1314 annotatedDomElements.push( doc.createTextNode( text ) );
1315 text = '';
1316 }
1317 annotatedDomElements = [];
1318 annotatedDomElementStack.push( annotatedDomElements );
1319 };
1320
1321 const closeAnnotation = ( annotation ) => {
1322 const originalDomElements = annotation.getOriginalDomElements( this.store ),
1323 origElementText = originalDomElements[ 0 ] &&
1324 originalDomElements[ 0 ].textContent ||
1325 '';
1326 let leading = '',
1327 trailing = '';
1328
1329 // Add text if needed
1330 if ( text.length > 0 ) {
1331 annotatedDomElements.push( doc.createTextNode( text ) );
1332 text = '';
1333 }
1334
1335 const annotatedChildDomElements = annotatedDomElementStack.pop();
1336 annotatedDomElements = annotatedDomElementStack[ annotatedDomElementStack.length - 1 ];
1337
1338 // HACK: Move any leading and trailing whitespace out of the annotation, but only if the
1339 // annotation didn't originally have leading/trailing whitespace
1340 if ( annotation.constructor.static.trimWhitespace ) {
1341 let matches;
1342 let first = annotatedChildDomElements[ 0 ];
1343 while (
1344 first &&
1345 first.nodeType === Node.TEXT_NODE &&
1346 ( matches = first.data.match( this.leadingWhitespacesRegex ) ) &&
1347 !this.leadingWhitespaceRegex.test( origElementText )
1348 ) {
1349 leading += matches[ 0 ];
1350 first.deleteData( 0, matches[ 0 ].length );
1351 if ( first.data.length !== 0 ) {
1352 break;
1353 }
1354 // Remove empty text node
1355 annotatedChildDomElements.shift();
1356 // Process next text node to see if it also has whitespace
1357 first = annotatedChildDomElements[ 0 ];
1358 }
1359 let last = annotatedChildDomElements[ annotatedChildDomElements.length - 1 ];
1360 while (
1361 last &&
1362 last.nodeType === Node.TEXT_NODE &&
1363 ( matches = last.data.match( this.trailingWhitespacesRegex ) ) &&
1364 !this.trailingWhitespaceRegex.test( origElementText )
1365 ) {
1366 trailing = matches[ 0 ] + trailing;
1367 last.deleteData( last.data.length - matches[ 0 ].length, matches[ 0 ].length );
1368 if ( last.data.length !== 0 ) {
1369 break;
1370 }
1371 // Remove empty text node
1372 annotatedChildDomElements.pop();
1373 // Process next text node to see if it also has whitespace
1374 last = annotatedChildDomElements[ annotatedChildDomElements.length - 1 ];
1375 }
1376 }
1377
1378 let annotationElement;
1379 if ( annotatedChildDomElements.length ) {
1380 annotationElement = this.getDomElementsFromDataElement(
1381 annotation.getElement(), doc, annotatedChildDomElements
1382 )[ 0 ];
1383 }
1384
1385 if ( leading ) {
1386 annotatedDomElements.push( doc.createTextNode( leading ) );
1387 }
1388 let n, len;
1389 if ( annotationElement ) {
1390 for ( n = 0, len = annotatedChildDomElements.length; n < len; n++ ) {
1391 annotationElement.appendChild( annotatedChildDomElements[ n ] );
1392 }
1393 annotatedDomElements.push( annotationElement );
1394 } else {
1395 for ( n = 0, len = annotatedChildDomElements.length; n < len; n++ ) {
1396 annotatedDomElements.push( annotatedChildDomElements[ n ] );
1397 }
1398 }
1399 if ( trailing ) {
1400 annotatedDomElements.push( doc.createTextNode( trailing ) );
1401 }
1402 };
1403
1404 const findEndOfNode = ( k ) => {
1405 let n, depth;
1406 for ( n = k + 1, depth = 1; n < dataLen && depth > 0; n++ ) {
1407 if ( data[ n ].type ) {
1408 depth += data[ n ].type.charAt( 0 ) === '/' ? -1 : 1;
1409 }
1410 }
1411 if ( depth !== 0 ) {
1412 throw new Error( 'Unbalanced data: ' + depth + ' element(s) left open.' );
1413 }
1414 return n;
1415 };
1416
1417 const getDataElementOrSlice = ( i ) => {
1418 let dataSlice;
1419 if (
1420 ve.dm.nodeFactory.lookup( data[ i ].type ) &&
1421 ve.dm.nodeFactory.doesNodeHandleOwnChildren( data[ i ].type )
1422 ) {
1423 dataSlice = data.slice( i, findEndOfNode( i ) );
1424 } else {
1425 dataSlice = data[ i ];
1426 }
1427 return dataSlice;
1428 };
1429
1430 const getChar = ( char ) => {
1431 if (
1432 isForPreview &&
1433 !domElement.veHasSignificantWhitespace &&
1434 Object.prototype.hasOwnProperty.call( whitespaceHtmlChars, char )
1435 ) {
1436 char = whitespaceHtmlChars[ char ];
1437 }
1438 return char;
1439 };
1440
1441 const annotationStack = new ve.dm.AnnotationSet( this.store );
1442
1443 for ( let i = 0; i < dataLen; i++ ) {
1444 if ( typeof data[ i ] === 'string' ) {
1445 // Text
1446 text = '';
1447 let isStart = i > 0 &&
1448 ve.dm.LinearData.static.isOpenElementData( data[ i - 1 ] ) &&
1449 !ve.dm.nodeFactory.doesNodeHaveSignificantWhitespace(
1450 ve.dm.LinearData.static.getType( data[ i - 1 ] )
1451 );
1452 // Continue forward as far as the plain text goes
1453 while ( typeof data[ i ] === 'string' ) {
1454 // HACK: Skip over leading whitespace (T53462/T142132) in non-whitespace-preserving tags
1455 // This should possibly be handled by Parsoid or in the UI.
1456 if ( !( isStart && this.onlyWhitespaceRegex.test( data[ i ] ) && this.isForParser() ) ) {
1457 text += getChar( data[ i ] );
1458 isStart = false;
1459 }
1460 i++;
1461 }
1462 // i points to the first non-text thing, go back one so we don't skip this later
1463 i--;
1464 // Add text
1465 if ( text.length > 0 ) {
1466 domElement.appendChild( doc.createTextNode( text ) );
1467 }
1468 } else if (
1469 Array.isArray( data[ i ] ) ||
1470 (
1471 data[ i ].annotations !== undefined &&
1472 this.nodeFactory.canNodeSerializeAsContent( data[ i ].type )
1473 )
1474 ) {
1475 // Annotated text, nodes or meta
1476 text = '';
1477 annotatedDomElements = [];
1478 annotatedDomElementStack = [ annotatedDomElements ];
1479 while (
1480 data[ i ] !== undefined && (
1481 Array.isArray( data[ i ] ) ||
1482 (
1483 data[ i ].annotations !== undefined &&
1484 this.nodeFactory.canNodeSerializeAsContent( data[ i ].type )
1485 )
1486 )
1487 ) {
1488 const annotations = new ve.dm.AnnotationSet(
1489 this.store, data[ i ].annotations || data[ i ][ 1 ]
1490 );
1491 this.constructor.static.openAndCloseAnnotations( annotationStack, annotations,
1492 openAnnotation, closeAnnotation
1493 );
1494
1495 if ( data[ i ].annotations === undefined ) {
1496 // Annotated text
1497 text += getChar( data[ i ][ 0 ] );
1498 } else {
1499 // Annotated node
1500 // Add text if needed
1501 if ( text.length > 0 ) {
1502 annotatedDomElements.push( doc.createTextNode( text ) );
1503 text = '';
1504 }
1505 // Insert the elements
1506 const dataElementOrSlice = getDataElementOrSlice( i );
1507 const childDomElements = this.getDomElementsFromDataElement( dataElementOrSlice, doc );
1508 for ( let j = 0; j < childDomElements.length; j++ ) {
1509 annotatedDomElements.push( childDomElements[ j ] );
1510 }
1511 if ( Array.isArray( dataElementOrSlice ) ) {
1512 i += dataElementOrSlice.length - 1;
1513 } else {
1514 i++; // Skip the closing
1515 }
1516 }
1517 i++;
1518 }
1519 // We're now at the first non-annotated thing, go back one so we don't skip this later
1520 i--;
1521
1522 // Add any gathered text
1523 if ( text.length > 0 ) {
1524 annotatedDomElements.push( doc.createTextNode( text ) );
1525 text = '';
1526 }
1527 // Close any remaining annotations
1528 this.constructor.static.openAndCloseAnnotations( annotationStack, new ve.dm.AnnotationSet( this.store ),
1529 openAnnotation, closeAnnotation
1530 );
1531 // Put the annotated nodes in the DOM
1532 for ( let j = 0; j < annotatedDomElements.length; j++ ) {
1533 domElement.appendChild( annotatedDomElements[ j ] );
1534 }
1535 } else if ( data[ i ].type !== undefined ) {
1536 const dataElement = data[ i ];
1537 // Element
1538 if ( dataElement.type.charAt( 0 ) === '/' ) {
1539 // Close element
1540 const parentDomElement = domElement.parentNode;
1541 const type = data[ i ].type.slice( 1 );
1542 const isContentNode = this.nodeFactory.isNodeContent( type );
1543 // Process whitespace
1544 // whitespace = [ outerPre, innerPre, innerPost, outerPost ]
1545 const oldLastOuterPost = parentDomElement.lastOuterPost;
1546 if (
1547 !isContentNode &&
1548 domElement.veInternal &&
1549 domElement.veInternal.whitespace
1550 ) {
1551 // Process inner whitespace. innerPre is for sure legitimate
1552 // whitespace that should be inserted; if it was a duplicate
1553 // of our child's outerPre, we would have cleared it.
1554 const pre = domElement.veInternal.whitespace[ 1 ];
1555 if ( pre ) {
1556 if (
1557 domElement.firstChild &&
1558 domElement.firstChild.nodeType === Node.TEXT_NODE
1559 ) {
1560 // First child is a TextNode, prepend to it
1561 domElement.firstChild.insertData( 0, pre );
1562 } else {
1563 // Prepend a TextNode
1564 const textNode = doc.createTextNode( pre );
1565 textNode.veIsWhitespace = true;
1566 domElement.insertBefore(
1567 textNode,
1568 domElement.firstChild
1569 );
1570 }
1571 }
1572 const lastChild = domElement.veInternal.childDomElements ?
1573 domElement.veInternal
1574 .childDomElements[ domElement.veInternal.childDomElements.length - 1 ]
1575 .lastChild :
1576 domElement.lastChild;
1577 const ours = domElement.veInternal.whitespace[ 2 ];
1578 let theirs;
1579 if ( domElement.lastOuterPost === undefined ) {
1580 // This node didn't have any structural children
1581 // (i.e. it's a content-containing node), so there's
1582 // nothing to check innerPost against
1583 theirs = ours;
1584 } else {
1585 theirs = domElement.lastOuterPost;
1586 }
1587 if ( ours && ours === theirs ) {
1588 if ( lastChild && lastChild.nodeType === Node.TEXT_NODE ) {
1589 // Last child is a TextNode, append to it
1590 domElement.lastChild.appendData( ours );
1591 } else {
1592 // Append a TextNode
1593 const textNode = doc.createTextNode( ours );
1594 textNode.veIsWhitespace = true;
1595 domElement.appendChild(
1596 textNode
1597 );
1598 }
1599 }
1600 // Tell the parent about our outerPost
1601 parentDomElement.lastOuterPost = domElement.veInternal.whitespace[ 3 ] || '';
1602 } else if ( !isContentNode ) {
1603 // Use empty string, because undefined means there were no
1604 // structural children
1605 parentDomElement.lastOuterPost = '';
1606 }
1607 // else don't touch lastOuterPost
1608
1609 // Logic to unwrap empty & wrapper nodes.
1610 // It would be nicer if we could avoid generating in the first
1611 // place, but then remembering where we have to skip ascending
1612 // to the parent would be tricky.
1613 let doUnwrap = false;
1614 if ( domElement.veInternal ) {
1615 switch ( domElement.veInternal.generated ) {
1616 case 'slug':
1617 // 'slug' elements - remove if they are still empty
1618 if ( domElement.childNodes.length === 0 ) {
1619 doUnwrap = true;
1620 }
1621 break;
1622 case 'empty':
1623 // 'empty' elements - first ensure they are actually empty
1624 if (
1625 domElement.childNodes.length === 0 &&
1626 (
1627 // then check that we are the last child
1628 // before unwrapping (and therefore destroying)
1629 data[ i + 1 ] === undefined ||
1630 data[ i + 1 ].type.charAt( 0 ) === '/' ||
1631 // Document ends when we encounter the internal list
1632 (
1633 data[ i + 1 ].type &&
1634 this.nodeFactory.isNodeInternal( data[ i + 1 ].type )
1635 )
1636 )
1637 ) {
1638 doUnwrap = true;
1639 }
1640 break;
1641 case 'wrapper': {
1642 // 'wrapper' elements - ensure there is a block level
1643 // element between this element and the previous sibling
1644 // wrapper or parent node
1645 doUnwrap = true;
1646 const previousSiblings = domElement.parentNode.childNodes;
1647 // Note: previousSiblings includes the current element
1648 // so we only go up to length - 2
1649 for ( let j = previousSiblings.length - 2; j >= 0; j-- ) {
1650 const sibling = previousSiblings[ j ];
1651 if ( ve.isBlockElement( sibling ) ) {
1652 // Stop searching early when we get to a block element.
1653 break;
1654 }
1655 // If we find content, don't unwrap.
1656 if (
1657 // Text node content (non-whitespace)
1658 ( sibling.nodeType === Node.TEXT_NODE && !sibling.veIsWhitespace ) ||
1659 // Inline content tag
1660 ( sibling.nodeType === Node.ELEMENT_NODE && sibling.tagName !== 'META' && sibling.tagName !== 'LINK' )
1661 ) {
1662 // we've found unwrapped content so don't unwrap
1663 doUnwrap = false;
1664 break;
1665 }
1666 }
1667 break;
1668 }
1669 }
1670 }
1671 if ( doUnwrap ) {
1672 if ( domElement.childNodes.length ) {
1673 // If domElement has children, append them to parentDomElement
1674 while ( domElement.firstChild ) {
1675 parentDomElement.insertBefore(
1676 domElement.firstChild,
1677 domElement
1678 );
1679 }
1680 } else {
1681 // If domElement has no children, it's as if it was never there at all,
1682 // so set lastOuterPost back to what it was, except that we need to
1683 // change undefined to '' , since undefined means there were no children.
1684 parentDomElement.lastOuterPost = oldLastOuterPost || '';
1685 }
1686 parentDomElement.removeChild( domElement );
1687 }
1688
1689 delete domElement.veInternal;
1690 delete domElement.lastOuterPost;
1691 // Ascend to parent node, except if this is an internal node
1692 // TODO: It's not covered with unit tests.
1693 if ( !ve.dm.nodeFactory.lookup( type ) || !ve.dm.nodeFactory.isNodeInternal( type ) ) {
1694 domElement = parentDomElement;
1695 }
1696 } else {
1697 // Create node from data
1698 if ( this.nodeFactory.isNodeInternal( data[ i ].type ) ) {
1699 // Reached the internal list, finish
1700 break;
1701 }
1702 const isContentNode = this.nodeFactory.isNodeContent( data[ i ].type );
1703
1704 const dataElementOrSlice = getDataElementOrSlice( i );
1705 const childDomElements = this.getDomElementsFromDataElement( dataElementOrSlice, doc );
1706 if ( childDomElements && !childDomElements.length ) {
1707 // Support toDomElements returning an empty array
1708 i = findEndOfNode( i ) - 1;
1709 continue;
1710 } else if ( childDomElements ) {
1711 // Add clone of internal data; we use a clone rather than a reference because
1712 // we modify .veInternal.whitespace[1] in some cases
1713 childDomElements[ 0 ].veInternal = ve.extendObject(
1714 { childDomElements: childDomElements },
1715 dataElement.internal ? ve.copy( dataElement.internal ) : {}
1716 );
1717 // Add elements
1718 for ( let j = 0; j < childDomElements.length; j++ ) {
1719 domElement.appendChild( childDomElements[ j ] );
1720 }
1721 // Descend into the first child node
1722 const parentDomElement = domElement;
1723 domElement = childDomElements[ 0 ];
1724
1725 // Process outer whitespace
1726 // Every piece of outer whitespace is duplicated somewhere:
1727 // each node's outerPost is duplicated as the next node's
1728 // outerPre, the first node's outerPre is the parent's
1729 // innerPre, and the last node's outerPost is the parent's
1730 // innerPost. For each piece of whitespace, we verify that
1731 // the duplicate matches. If it doesn't, we take that to
1732 // mean the user has messed with it and don't output any
1733 // whitespace.
1734 if ( domElement.veInternal && domElement.veInternal.whitespace ) {
1735 // Process this node's outerPre
1736 const ours = domElement.veInternal.whitespace[ 0 ];
1737 let theirs;
1738 if ( domElement.previousSibling ) {
1739 // Get previous sibling's outerPost
1740 theirs = parentDomElement.lastOuterPost;
1741 } else if ( parentDomElement === container ) {
1742 // outerPre of the very first node in the document, check against body innerWhitespace
1743 theirs = innerWhitespace ? innerWhitespace[ 0 ] : ours;
1744 } else {
1745 // First child, get parent's innerPre
1746 if (
1747 parentDomElement.veInternal &&
1748 parentDomElement.veInternal.whitespace
1749 ) {
1750 theirs = parentDomElement.veInternal.whitespace[ 1 ];
1751 // Clear parent's innerPre so it's not used again
1752 parentDomElement.veInternal.whitespace[ 1 ] = undefined;
1753 }
1754 // else theirs=undefined
1755 }
1756 if ( ours && ours === theirs ) {
1757 // Matches the duplicate, insert a TextNode
1758 const textNode = doc.createTextNode( ours );
1759 textNode.veIsWhitespace = true;
1760 parentDomElement.insertBefore(
1761 textNode,
1762 domElement
1763 );
1764 }
1765 } else if (
1766 !isContentNode &&
1767 !domElement.previousSibling &&
1768 parentDomElement.veInternal &&
1769 parentDomElement.veInternal.whitespace
1770 ) {
1771 // The parent's innerPre should not be used, because it doesn't match
1772 // outerPre (since we didn't have any whitespace set at all).
1773 // Except if this is a content node, because content nodes
1774 // don't have whitespace annotated on them *sigh*
1775 parentDomElement.veInternal.whitespace[ 1 ] = undefined;
1776 }
1777 }
1778
1779 if ( Array.isArray( dataElementOrSlice ) ) {
1780 i += dataElementOrSlice.length - 2;
1781 } else if ( childDomElements && childDomElements.length && childDomElements[ 0 ].handledOwnChildren ) {
1782 i = findEndOfNode( i ) - 2;
1783 }
1784 }
1785 }
1786 }
1787 // Check outerPost whitespace of the very last node against body innerWhitespace
1788 if (
1789 container.lastOuterPost !== undefined &&
1790 ( !innerWhitespace || container.lastOuterPost === innerWhitespace[ 1 ] )
1791 ) {
1792 if ( container.lastChild && container.lastChild.nodeType === Node.TEXT_NODE ) {
1793 // Last child is a TextNode, append to it
1794 container.lastChild.appendData( container.lastOuterPost );
1795 } else if ( container.lastOuterPost.length > 0 ) {
1796 // Append a TextNode
1797 container.appendChild( doc.createTextNode( container.lastOuterPost ) );
1798 }
1799 delete container.lastOuterPost;
1800 }
1801 // Get rid of excess text nodes
1802 container.normalize();
1803 };
1804
1805 /* Initialization */
1806
1807 ve.dm.converter = new ve.dm.Converter( ve.dm.modelRegistry, ve.dm.nodeFactory, ve.dm.annotationFactory );