all files / src/ce/ ve.ce.ContentBranchNode.js

91.09% Statements 184/202
82.69% Branches 86/104
88.24% Functions 15/17
91.09% Lines 184/202
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 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514                                    1404×   1404× 1404× 1404×     1404×   1404×     1404×     1404× 1404×     1404×                                                   1968× 1968× 2355× 2355× 67× 2288× 358×           1610× 1610× 1844×                   1365×     1365×                                                           664×       664×             1626×             1626×       222×       1626×                 1632×       113×     1519×                 3236×       113×     3123×                         1818×                                     1818×                   493× 493× 493× 208×     208×   208×     493× 493× 493× 493× 493× 493×     493× 493× 493× 210×     210×   210×     493× 493× 493×       1818× 1665×         1818× 1818× 391× 391× 391× 391×   114×           1818× 1723×   95× 95× 95× 278× 278× 278× 47×       47× 47×   231×     95× 48×       48×         1818× 4897× 1248× 1248×   3649× 3649×       4897× 4897×         4897× 4723× 174× 95× 19×       19× 19× 19× 19× 19× 19× 19×           19× 19×   19× 19× 19× 19×   76× 76×     79× 51× 51×     79×   78×   78× 78×       1818× 1433× 1433×   1818× 247×   1818× 1818×       49× 49×                 2377×     2377×       582×     1795× 391×     1795× 1795×             1795× 391× 391×     391×           391× 391× 688×   391× 391× 391× 185×   206×   1610×   1610× 1610×     1610× 1610× 1610× 679×         1610×     1610× 206× 173× 33× 11×   22×         1610×     1610×             1610×           49×       49×       49×           52×     52×    
/*!
 * VisualEditor ContentEditable ContentBranchNode class.
 *
 * @copyright 2011-2019 VisualEditor Team and others; see http://ve.mit-license.org
 */
 
/**
 * ContentEditable content branch node.
 *
 * Content branch nodes can only have content nodes as children.
 *
 * @abstract
 * @extends ve.ce.BranchNode
 * @constructor
 * @param {ve.dm.BranchNode} model Model to observe
 * @param {Object} [config] Configuration options
 */
ve.ce.ContentBranchNode = function VeCeContentBranchNode() {
	// Properties
	this.lastTransaction = null;
	// Parent constructor calls renderContents, so this must be set first
	this.rendered = this.rendered;
	this.unicornAnnotations = null;
	this.unicorns = null;
 
	// Parent constructor
	ve.ce.ContentBranchNode.super.apply( this, arguments );
 
	this.onClickHandler = this.onClick.bind( this );
 
	// DOM changes (keep in sync with #onSetup)
	this.$element.addClass( 've-ce-contentBranchNode' );
 
	// Events
	this.connect( this, { childUpdate: 'onChildUpdate' } );
	this.model.connect( this, { detach: 'onModelDetach' } );
	// Some browsers allow clicking links inside contenteditable, such as in iOS Safari when the
	// keyboard is closed
	this.$element.on( 'click', this.onClickHandler );
};
 
/* Inheritance */
 
OO.inheritClass( ve.ce.ContentBranchNode, ve.ce.BranchNode );
 
/* Static Members */
 
/**
 * Whether Enter splits this node type. Must be true for ContentBranchNodes.
 *
 * Warning: overriding this to false in a subclass will cause crashes on Enter key handling.
 *
 * @static
 * @property
 * @inheritable
 */
ve.ce.ContentBranchNode.static.splitOnEnter = true;
 
/* Static Methods */
 
/**
 * Append the return value of #getRenderedContents to a DOM element.
 *
 * @param {HTMLElement} container DOM element
 * @param {HTMLElement} wrapper Wrapper returned by #getRenderedContents
 */
ve.ce.ContentBranchNode.static.appendRenderedContents = function ( container, wrapper ) {
	function resolveOriginals( domElement ) {
		var i, len, child;
		for ( i = 0, len = domElement.childNodes.length; i < len; i++ ) {
			child = domElement.childNodes[ i ];
			if ( child.veOrigNode ) {
				domElement.replaceChild( child.veOrigNode, child );
			} else if ( child.childNodes && child.childNodes.length ) {
				resolveOriginals( child );
			}
		}
	}
 
	/* Resolve references to the original nodes. */
	resolveOriginals( wrapper );
	while ( wrapper.firstChild ) {
		container.appendChild( wrapper.firstChild );
	}
};
 
/* Methods */
 
/**
 * @inheritdoc
 */
ve.ce.ContentBranchNode.prototype.onSetup = function () {
	// Parent method
	ve.ce.ContentBranchNode.super.prototype.onSetup.apply( this, arguments );
 
	// DOM changes (duplicated from constructor in case this.$element is replaced)
	this.$element.addClass( 've-ce-contentBranchNode' );
};
 
/**
 * Handle click events.
 *
 * @param {jQuery.Event} e Click event
 */
ve.ce.ContentBranchNode.prototype.onClick = function ( e ) {
	if (
		// Only block clicks on links
		( e.target !== this.$element[ 0 ] && e.target.nodeName.toUpperCase() === 'A' ) &&
		// Don't prevent a modified click, which in some browsers deliberately opens the link
		( !e.altKey && !e.ctrlKey && !e.metaKey && !e.shiftKey )
	) {
		e.preventDefault();
	}
};
 
/**
 * Handle childUpdate events.
 *
 * Rendering is only done once per transaction. If a paragraph has multiple nodes in it then it's
 * possible to receive multiple `childUpdate` events for a single transaction such as annotating
 * across them. State is tracked by storing and comparing the length of the surface model's complete
 * history.
 *
 * This is used to automatically render contents.
 *
 * @param {ve.dm.Transaction} transaction Transaction
 */
ve.ce.ContentBranchNode.prototype.onChildUpdate = function ( transaction ) {
	Iif ( transaction === null || transaction === this.lastTransaction ) {
		this.lastTransaction = transaction;
		return;
	}
	this.renderContents();
};
 
/**
 * @inheritdoc
 */
ve.ce.ContentBranchNode.prototype.onSplice = function ( index, howmany ) {
	// Parent method
	ve.ce.ContentBranchNode.super.prototype.onSplice.apply( this, arguments );
 
	// FIXME T126025: adjust slugNodes indexes if isRenderingLocked. This should be
	// sufficient to keep this.slugNodes valid - only text changes can occur, which
	// cannot create a requirement for a new slug (it can make an existing slug
	// redundant, but it is harmless to leave it there).
	// TODO fix the use of ve.ce.DocumentNode and getSurface
	if (
		this.root instanceof ve.ce.DocumentNode &&
		this.root.getSurface().isRenderingLocked
	) {
		this.slugNodes.splice.apply( this.slugNodes, [ index, howmany ].concat( new Array( arguments.length - 2 ) ) );
	}
 
	// Rerender to make sure annotations are applied correctly
	this.renderContents();
};
 
/**
 * @inheritdoc
 */
ve.ce.ContentBranchNode.prototype.setupBlockSlugs = function () {
	// Respect render lock
	// TODO: Can this check be moved into the parent method?
	// TODO fix the use of ve.ce.DocumentNode and getSurface
	if (
		this.root instanceof ve.ce.DocumentNode &&
		this.root.getSurface().isRenderingLocked()
	) {
		return;
	}
	// Parent method
	ve.ce.ContentBranchNode.super.prototype.setupBlockSlugs.apply( this, arguments );
};
 
/**
 * @inheritdoc
 */
ve.ce.ContentBranchNode.prototype.setupInlineSlugs = function () {
	// Respect render lock
	// TODO: Can this check be moved into the parent method?
	// TODO fix the use of ve.ce.DocumentNode and getSurface
	if (
		this.root instanceof ve.ce.DocumentNode &&
		this.root.getSurface().isRenderingLocked()
	) {
		return;
	}
	// Parent method
	ve.ce.ContentBranchNode.super.prototype.setupInlineSlugs.apply( this, arguments );
};
 
/**
 * Get an HTML rendering of the contents.
 *
 * If you are actually going to append the result to a DOM, you need to
 * do this with #appendRenderedContents, which resolves the cloned
 * nodes returned by this function back to their originals.
 *
 * @return {HTMLElement} Wrapper containing rendered contents
 * @return {Object} return.unicornInfo Unicorn information
 */
ve.ce.ContentBranchNode.prototype.getRenderedContents = function () {
	var i, ilen, j, jlen, item, itemAnnotations, clone, dmSurface, dmSelection, relCursor,
		unicorn, preUnicorn, postUnicorn, annotationsChanged, childLength, offset, htmlItem, ceSurface,
		store = this.model.doc.getStore(),
		annotationSet = new ve.dm.AnnotationSet( store ),
		annotatedHtml = [],
		doc = this.getElementDocument(),
		wrapper = doc.createElement( 'div' ),
		current = wrapper,
		annotationStack = [],
		nodeStack = [],
		unicornInfo = {
			hasCursor: false,
			annotations: null,
			unicorns: null
		},
		buffer = '',
		node = this;
 
	// Source mode optimization
	Iif ( this.getModel().getDocument().sourceMode ) {
		wrapper.appendChild(
			document.createTextNode(
				this.getModel().getDocument().getDataFromNode( this.getModel() ).join( '' )
			)
		);
		wrapper.unicornInfo = unicornInfo;
		return wrapper;
	}
 
	function openAnnotation( annotation ) {
		var ann;
		annotationsChanged = true;
		if ( buffer !== '' ) {
			Iif ( current.nodeType === Node.TEXT_NODE ) {
				current.textContent += buffer;
			} else {
				current.appendChild( doc.createTextNode( buffer ) );
			}
			buffer = '';
		}
		// Create a new DOM node and descend into it
		annotation.store = store;
		ann = ve.ce.annotationFactory.create( annotation.getType(), annotation, node );
		ann.appendTo( current );
		annotationStack.push( ann );
		nodeStack.push( current );
		current = ann.getContentContainer();
	}
 
	function closeAnnotation() {
		var ann;
		annotationsChanged = true;
		if ( buffer !== '' ) {
			Iif ( current.nodeType === Node.TEXT_NODE ) {
				current.textContent += buffer;
			} else {
				current.appendChild( doc.createTextNode( buffer ) );
			}
			buffer = '';
		}
		// Traverse up
		ann = annotationStack.pop();
		ann.attachContents();
		current = nodeStack.pop();
	}
 
	// Gather annotated HTML from the child nodes
	for ( i = 0, ilen = this.children.length; i < ilen; i++ ) {
		annotatedHtml = annotatedHtml.concat( this.children[ i ].getAnnotatedHtml() );
	}
 
	// Set relCursor to collapsed selection offset, or -1 if none
	// (in which case we don't need to worry about preannotation)
	relCursor = -1;
	if ( this.getRoot() ) {
		ceSurface = this.getRoot().getSurface();
		dmSurface = ceSurface.getModel();
		dmSelection = dmSurface.getTranslatedSelection();
		if ( dmSelection instanceof ve.dm.LinearSelection && dmSelection.isCollapsed() ) {
			// Subtract 1 for CBN opening tag
			relCursor = dmSelection.getRange().start - this.getOffset() - 1;
		}
	}
 
	// Set cursor status for renderContents. If hasCursor, splice unicorn marker at the
	// collapsed selection offset. It will be rendered later if it is needed, else ignored
	if ( relCursor < 0 || relCursor > this.getLength() ) {
		unicornInfo.hasCursor = false;
	} else {
		unicornInfo.hasCursor = true;
		offset = 0;
		for ( i = 0, ilen = annotatedHtml.length; i < ilen; i++ ) {
			htmlItem = annotatedHtml[ i ][ 0 ];
			childLength = ( typeof htmlItem === 'string' ) ? 1 : 2;
			if ( offset <= relCursor && relCursor < offset + childLength ) {
				unicorn = [
					{}, // Unique object, for testing object equality later
					dmSurface.getInsertionAnnotations().storeHashes
				];
				annotatedHtml.splice( i, 0, unicorn );
				break;
			}
			offset += childLength;
		}
		// Special case for final position
		if ( i === ilen && offset === relCursor ) {
			unicorn = [
				{}, // Unique object, for testing object equality later
				dmSurface.getInsertionAnnotations().storeHashes
			];
			annotatedHtml.push( unicorn );
		}
	}
 
	// Render HTML with annotations
	for ( i = 0, ilen = annotatedHtml.length; i < ilen; i++ ) {
		if ( Array.isArray( annotatedHtml[ i ] ) ) {
			item = annotatedHtml[ i ][ 0 ];
			itemAnnotations = new ve.dm.AnnotationSet( store, annotatedHtml[ i ][ 1 ] );
		} else {
			item = annotatedHtml[ i ];
			itemAnnotations = new ve.dm.AnnotationSet( store );
		}
 
		// annotationsChanged gets set to true by openAnnotation and closeAnnotation
		annotationsChanged = false;
		ve.dm.Converter.static.openAndCloseAnnotations( annotationSet, itemAnnotations,
			openAnnotation, closeAnnotation
		);
 
		// Handle the actual item
		if ( typeof item === 'string' ) {
			buffer += item;
		} else if ( unicorn && item === unicorn[ 0 ] ) {
			if ( annotationsChanged ) {
				Iif ( buffer !== '' ) {
					current.appendChild( doc.createTextNode( buffer ) );
					buffer = '';
				}
				preUnicorn = doc.createElement( 'img' );
				postUnicorn = doc.createElement( 'img' );
				preUnicorn.className = 've-ce-unicorn ve-ce-pre-unicorn';
				postUnicorn.className = 've-ce-unicorn ve-ce-post-unicorn';
				$( preUnicorn ).data( 'modelOffset', ( this.getOffset() + 1 + i ) );
				$( postUnicorn ).data( 'modelOffset', ( this.getOffset() + 1 + i ) );
				Iif ( ve.inputDebug ) {
					preUnicorn.setAttribute( 'src', ve.ce.unicornImgDataUri );
					postUnicorn.setAttribute( 'src', ve.ce.unicornImgDataUri );
					preUnicorn.className += ' ve-ce-unicorn-debug';
					postUnicorn.className += ' ve-ce-unicorn-debug';
				} else {
					preUnicorn.setAttribute( 'src', ve.ce.minImgDataUri );
					postUnicorn.setAttribute( 'src', ve.ce.minImgDataUri );
				}
				current.appendChild( preUnicorn );
				current.appendChild( postUnicorn );
				unicornInfo.annotations = dmSurface.getInsertionAnnotations();
				unicornInfo.unicorns = [ preUnicorn, postUnicorn ];
			} else {
				unicornInfo.annotations = null;
				unicornInfo.unicorns = null;
			}
		} else {
			if ( buffer !== '' ) {
				current.appendChild( doc.createTextNode( buffer ) );
				buffer = '';
			}
			// DOM equivalent of $( current ).append( item.clone() );
			for ( j = 0, jlen = item.length; j < jlen; j++ ) {
				// Append a clone so as to not relocate the original node
				clone = item[ j ].cloneNode( true );
				// Store a reference to the original node in a property
				clone.veOrigNode = item[ j ];
				current.appendChild( clone );
			}
		}
	}
	if ( buffer !== '' ) {
		current.appendChild( doc.createTextNode( buffer ) );
		buffer = '';
	}
	while ( annotationStack.length > 0 ) {
		closeAnnotation();
	}
	wrapper.unicornInfo = unicornInfo;
	return wrapper;
};
 
ve.ce.ContentBranchNode.prototype.onModelDetach = function () {
	// TODO fix the use of ve.ce.DocumentNode and getSurface
	Eif ( this.root instanceof ve.ce.DocumentNode ) {
		this.root.getSurface().setContentBranchNodeChanged();
	}
};
 
/**
 * Render contents.
 *
 * @return {boolean} Whether the contents have changed
 */
ve.ce.ContentBranchNode.prototype.renderContents = function () {
	var i, len, element, rendered, unicornInfo, oldWrapper, newWrapper,
		node = this;
	// TODO fix the use of ve.ce.DocumentNode and getSurface
	if (
		this.root instanceof ve.ce.DocumentNode &&
		this.root.getSurface().isRenderingLocked()
	) {
		return false;
	}
 
	if ( this.root instanceof ve.ce.DocumentNode ) {
		this.root.getSurface().setContentBranchNodeChanged();
	}
 
	rendered = this.getRenderedContents();
	unicornInfo = rendered.unicornInfo;
 
	// Return if unchanged. Test by building the new version and checking DOM-equality.
	// However we have to normalize to cope with consecutive text nodes. We can't normalize
	// the attached version, because that would close IMEs. As an optimization, don't perform
	// this checking if this node has never rendered before.
 
	if ( this.rendered ) {
		oldWrapper = this.$element[ 0 ].cloneNode( true );
		$( oldWrapper )
			.find( '.ve-ce-annotation-active' )
			.removeClass( 've-ce-annotation-active' );
		$( oldWrapper )
			.find( '.ve-ce-branchNode-inlineSlug' )
			.children()
			.unwrap()
			.filter( '.ve-ce-chimera' )
			.remove();
		newWrapper = this.$element[ 0 ].cloneNode( false );
		while ( rendered.firstChild ) {
			newWrapper.appendChild( rendered.firstChild );
		}
		ve.normalizeNode( oldWrapper );
		ve.normalizeNode( newWrapper );
		if ( newWrapper.isEqualNode( oldWrapper ) ) {
			return false;
		}
		rendered = newWrapper;
	}
	this.rendered = true;
 
	this.unicornAnnotations = unicornInfo.annotations || null;
	this.unicorns = unicornInfo.unicorns || null;
 
	// Detach all child nodes from this.$element
	for ( i = 0, len = this.$element.length; i < len; i++ ) {
		element = this.$element[ i ];
		while ( element.firstChild ) {
			element.removeChild( element.firstChild );
		}
	}
 
	// Reattach nodes
	this.constructor.static.appendRenderedContents( this.$element[ 0 ], rendered );
 
	// Set unicorning status
	if ( this.getRoot() ) {
		if ( !unicornInfo.hasCursor ) {
			this.getRoot().getSurface().setNotUnicorning( this );
		} else if ( this.unicorns ) {
			this.getRoot().getSurface().setUnicorning( this );
		} else {
			this.getRoot().getSurface().setNotUnicorningAll( this );
		}
	}
 
	// Add slugs
	this.setupInlineSlugs();
 
	// Highlight the node in debug mode
	Iif ( ve.inputDebug ) {
		this.$element.css( 'backgroundColor', '#eee' );
		setTimeout( function () {
			node.$element.css( 'backgroundColor', '' );
		}, 300 );
	}
 
	return true;
};
 
/**
 * @inheritdoc
 */
ve.ce.ContentBranchNode.prototype.detach = function () {
	Eif ( this.getRoot() ) {
		// This should be true, as the root is removed in the parent detach
		// method which hasn't run yet. However, just in case a node gets
		// double-detached…
		this.getRoot().getSurface().setNotUnicorning( this );
	}
 
	// Parent method
	ve.ce.ContentBranchNode.super.prototype.detach.call( this );
};
 
/**
 * @inheritdoc
 */
ve.ce.ContentBranchNode.prototype.destroy = function () {
	this.$element.off( 'click', this.onClickHandler );
 
	// Parent method
	ve.ce.ContentBranchNode.super.prototype.destroy.call( this );
};