All files / src/ce ve.ce.BranchNode.js

95.12% Statements 156/164
88.5% Branches 77/87
94.44% Functions 17/18
94.83% Lines 147/155

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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                                      1x   5492x     5492x     5492x 5492x     5492x     5492x         1x   1x                   1x 1x 1x 1x           1x       1x     1x               1x     1x                 1x                                     1x                 1x   5501x   5501x                           1x 1476x   1476x 9x 9x     9x   9x       9x 8x   9x 9x   9x 8x       9x   9x   9x 9x     9x 8x                   1x 4952x                         1x   6181x 6181x 6181x     6181x   3x 3x       6181x   7305x           7302x 7302x   3x   7305x   6181x 6181x 556x   556x 556x 556x 556x   556x   6181x 5116x 5116x 7305x 7305x 4817x     5116x   3143x 3143x         5116x 7305x 519x           6181x 6181x           1x   6079x 3614x             1x   8633x 5024x             1x   8099x 790x 323x   790x                     1x   8638x       8638x   8638x     8638x 3614x 5024x     5024x     8638x 1425x     1425x 217x   217x   1208x   1425x 1425x 548x           548x                   1x                   1x 95x   95x 38x   57x 76x 76x 57x                     1x   9190x   9190x 11189x             1x 403x 78x       403x           1x 401x 76x       401x                     1x 3150x       3150x 3150x 3153x 3153x   2997x   156x   151x               5x 2x         2x 2x 2x 2x   1x   1x   1x                              
/*!
 * VisualEditor ContentEditable BranchNode class.
 *
 * @copyright See AUTHORS.txt
 */
 
/**
 * ContentEditable branch node.
 *
 * Branch nodes can have branch or leaf nodes as children.
 *
 * @class
 * @abstract
 * @extends ve.ce.Node
 * @mixes ve.BranchNode
 * @constructor
 * @param {ve.dm.BranchNode} model Model to observe
 * @param {Object} [config] Configuration options
 */
ve.ce.BranchNode = function VeCeBranchNode( model ) {
	// Mixin constructor
	ve.BranchNode.call( this );
 
	// Parent constructor
	ve.ce.BranchNode.super.apply( this, arguments );
 
	// Properties
	this.tagName = this.$element.get( 0 ).nodeName.toLowerCase();
	this.slugNodes = [];
 
	// Events
	this.model.connect( this, { splice: 'onSplice' } );
 
	// Initialization
	this.onSplice( 0, 0, ...model.getChildren() );
};
 
/* Inheritance */
 
OO.inheritClass( ve.ce.BranchNode, ve.ce.Node );
 
OO.mixinClass( ve.ce.BranchNode, ve.BranchNode );
 
/* Static Properties */
 
/**
 * Inline slug template.
 *
 * @static
 * @property {HTMLElement}
 */
ve.ce.BranchNode.inlineSlugTemplate = ( function () {
	const profile = $.client.profile();
	const layout = profile.layout;
	const $img = $( '<img>' )
		.attr( {
			role: 'none',
			alt: ''
		} )
		.addClass( 've-ce-chimera' );
	Eif ( layout === 'webkit' || layout === 'gecko' ) {
		// The following classes are used here:
		// * ve-ce-chimera-gecko
		// * ve-ce-chimera-webkit
		$img.addClass( 've-ce-chimera-' + layout );
	}
 
	const $span = $( '<span>' )
		.addClass( 've-ce-branchNode-slug ve-ce-branchNode-inlineSlug' )
		.append( $img );
 
	// Support: Firefox <69
	// Firefox <=37 misbehaves if we don't set an src: https://bugzilla.mozilla.org/show_bug.cgi?id=989012
	// Firefox <69 misbehaves if we don't set an src and there is no sizing at node creation time: https://bugzilla.mozilla.org/show_bug.cgi?id=1267906
	// Setting an src in Chrome is slow, so only set it in affected versions of Firefox
	Iif ( layout === 'gecko' && profile.versionNumber < 69 ) {
		$img.prop( 'src', ve.ce.minImgDataUri );
	}
	return $span.get( 0 );
}() );
 
/**
 * Inline slug template for input debugging.
 *
 * @static
 * @property {HTMLElement}
 */
ve.ce.BranchNode.inputDebugInlineSlugTemplate = $( '<span>' )
	.addClass( 've-ce-branchNode-slug ve-ce-branchNode-inlineSlug' )
	.append(
		$( '<img>' )
			.addClass( 've-ce-chimera ve-ce-chimera-debug' )
			.attr( {
				src: ve.ce.chimeraImgDataUri,
				role: 'none',
				alt: ''
			} )
	)
	.get( 0 );
 
/**
 * Block slug template.
 *
 * @static
 * @property {HTMLElement}
 */
ve.ce.BranchNode.blockSlugTemplate = $( '<div>' )
	.addClass( 've-ce-branchNode-slug ve-ce-branchNode-blockSlug' )
	.get( 0 );
 
/* Methods */
 
/**
 * @inheritdoc
 */
ve.ce.BranchNode.prototype.initialize = function () {
	// Parent method
	ve.ce.BranchNode.super.prototype.initialize.call( this );
 
	this.$element.addClass( 've-ce-branchNode' );
};
 
/**
 * Update the DOM wrapper.
 *
 * WARNING: The contents, .data( 'view' ), the contentEditable property and any classes the wrapper
 * already has will be moved to  the new wrapper, but other attributes and any other information
 * added using $.data() will be lost upon updating the wrapper. To retain information added to the
 * wrapper, subscribe to the 'teardown' and 'setup' events, or override #initialize.
 *
 * @fires ve.ce.View#teardown
 * @fires ve.ce.View#setup
 */
ve.ce.BranchNode.prototype.updateTagName = function () {
	const tagName = this.getTagName();
 
	if ( tagName !== this.tagName ) {
		this.emit( 'teardown' );
		const wrapper = document.createElement( tagName );
		// Copy classes
		// eslint-disable-next-line mediawiki/class-doc
		wrapper.className = this.$element[ 0 ].className;
		// Copy contentEditable
		wrapper.contentEditable = this.$element[ 0 ].contentEditable;
 
		// Insert new node, then move contents, then remove old node
		// This lets ve.ce.Surface#afterMutations see that this is a move
		if ( this.$element[ 0 ].parentNode ) {
			this.$element[ 0 ].parentNode.insertBefore( wrapper, this.$element[ 0 ] );
		}
		while ( this.$element[ 0 ].firstChild ) {
			wrapper.appendChild( this.$element[ 0 ].firstChild );
		}
		if ( this.$element[ 0 ].parentNode ) {
			this.$element[ 0 ].parentNode.removeChild( this.$element[ 0 ] );
		}
 
		// Use new element from now on
		this.$element = $( wrapper );
		// Remember which tag name we are using now
		this.tagName = tagName;
		// Give subclasses the opportunity to touch the new element
		this.initialize();
		this.emit( 'setup' );
 
		// TODO fix the use of ve.ce.DocumentNode and getSurface
		if ( this.root instanceof ve.ce.DocumentNode ) {
			this.root.getSurface().setContentBranchNodeChanged();
		}
	}
};
 
/**
 * Handles model update events.
 *
 * @param {ve.dm.Transaction} transaction
 */
ve.ce.BranchNode.prototype.onModelUpdate = function ( transaction ) {
	this.emit( 'childUpdate', transaction );
};
 
/**
 * Handle splice events.
 *
 * ve.ce.Node objects are generated from the inserted ve.dm.Node objects, producing a view that's a
 * mirror of its model.
 *
 * @param {number} index Index to remove and or insert nodes at
 * @param {number} deleteCount Number of nodes to remove
 * @param {...ve.dm.BranchNode} [modelNodes] Variadic list of nodes to insert
 */
ve.ce.BranchNode.prototype.onSplice = function ( index, deleteCount, ...modelNodes ) {
	// attachedRoot and doc can be undefined in tests
	const dmDoc = this.getModel().getDocument(),
		attachedRoot = dmDoc && dmDoc.attachedRoot,
		isAllAttached = !attachedRoot || attachedRoot instanceof ve.dm.DocumentNode;
 
	let inAttachedRoot, upstreamOfAttachedRoot;
	if ( !isAllAttached ) {
		// Optimization: Skip traversal when whole doc is attached
		inAttachedRoot = this.getModel().isDownstreamOf( attachedRoot );
		upstreamOfAttachedRoot = attachedRoot.collectUpstream();
	}
 
	// Convert models to views and attach them to this node
	const viewNodes = modelNodes.map( ( model ) => {
		let view;
		if (
			isAllAttached || inAttachedRoot || upstreamOfAttachedRoot.indexOf( model ) !== -1 ||
			// HACK: An internal item node was requested directly, e.g. for preview (T228070)
			// TODO: Come up with a more explict way to skip the UnrenderedNode optimisation.
			model.findParent( ve.dm.InternalItemNode )
		) {
			view = ve.ce.nodeFactory.createFromModel( model );
			view.model.connect( this, { update: 'onModelUpdate' } );
		} else {
			view = new ve.ce.UnrenderedNode( model );
		}
		return view;
	} );
	const removals = this.children.splice( index, deleteCount, ...viewNodes );
	removals.forEach( ( view ) => {
		view.model.disconnect( this, { update: 'onModelUpdate' } );
		// Stop child listening to its model (e.g. for splice event)
		view.model.disconnect( view );
		view.setLive( false );
		view.detach();
		view.$element.detach();
		// And fare thee weel a while
		view.destroy();
	} );
	if ( viewNodes.length ) {
		const fragment = document.createDocumentFragment();
		for ( let i = viewNodes.length - 1; i >= 0; i-- ) {
			viewNodes[ i ].attach( this );
			for ( let j = viewNodes[ i ].$element.length - 1; j >= 0; j-- ) {
				fragment.insertBefore( viewNodes[ i ].$element[ j ], fragment.childNodes[ 0 ] || null );
			}
		}
		if ( fragment.childNodes.length ) {
			// Only calculate this if it's needed, this function looks expensive
			const position = this.getDomPosition( index );
			position.node.insertBefore(
				fragment,
				position.node.children[ position.offset ] || null
			);
		}
		for ( let i = viewNodes.length - 1; i >= 0; i-- ) {
			if ( this.live !== viewNodes[ i ].isLive() ) {
				viewNodes[ i ].setLive( this.live );
			}
		}
	}
 
	// TODO: restructure to clarify the logic (exactly one of these is a no-op)
	this.setupBlockSlugs();
	this.setupInlineSlugs();
};
 
/**
 * Setup block slugs
 */
ve.ce.BranchNode.prototype.setupBlockSlugs = function () {
	// Only proceed if we are in a non-content node
	if ( this.canHaveChildrenNotContent() ) {
		this.setupSlugs( true );
	}
};
 
/**
 * Setup inline slugs
 */
ve.ce.BranchNode.prototype.setupInlineSlugs = function () {
	// Only proceed if we are in a content node
	if ( !this.canHaveChildrenNotContent() ) {
		this.setupSlugs( false );
	}
};
 
/**
 * Remove all slugs in this branch
 */
ve.ce.BranchNode.prototype.removeSlugs = function () {
	// Remove all slugs in this branch
	for ( const i in this.slugNodes ) {
		if ( this.slugNodes[ i ] !== undefined && this.slugNodes[ i ].parentNode ) {
			this.slugNodes[ i ].parentNode.removeChild( this.slugNodes[ i ] );
		}
		delete this.slugNodes[ i ];
	}
};
 
/**
 * Setup slugs where needed.
 *
 * Existing slugs will be removed before new ones are added.
 *
 * @param {boolean} isBlock Set up block slugs, otherwise setup inline slugs
 */
ve.ce.BranchNode.prototype.setupSlugs = function ( isBlock ) {
	// Source mode optimization
	Iif ( this.getModel().getDocument() && this.getModel().getDocument().sourceMode && isBlock ) {
		return;
	}
 
	const doc = this.getElementDocument();
 
	this.removeSlugs();
 
	let slugTemplate;
	if ( isBlock ) {
		slugTemplate = ve.ce.BranchNode.blockSlugTemplate;
	} else Iif ( ve.inputDebug ) {
		slugTemplate = ve.ce.BranchNode.inputDebugInlineSlugTemplate;
	} else {
		slugTemplate = ve.ce.BranchNode.inlineSlugTemplate;
	}
 
	for ( const i in this.getModel().slugPositions ) {
		const slugNode = doc.importNode( slugTemplate, true );
		// FIXME T126019: InternalListNode has an empty $element, so we assume that the slug goes
		// at the end instead. This is a hack and the internal list needs to die in a fire.
		if ( this.children[ i ] && this.children[ i ].$element[ 0 ] ) {
			const child = this.children[ i ].$element[ 0 ];
			// child.parentNode might not be equal to this.$element[ 0 ]: e.g. annotated inline nodes
			child.parentNode.insertBefore( slugNode, child );
		} else {
			this.$element[ 0 ].appendChild( slugNode );
		}
		this.slugNodes[ i ] = slugNode;
		if ( isBlock ) {
			const slugButton = new ve.ui.NoFocusButtonWidget( {
				tabIndex: -1,
				label: ve.msg( 'visualeditor-slug-insert' ),
				icon: 'add',
				framed: false
			} ).on( 'click', this.onSlugClick.bind( this, slugNode ) );
			$( slugNode ).append( slugButton.$element );
		}
	}
};
 
/**
 * Handle slug click events
 *
 * @param {HTMLElement} slugNode Slug node clicked
 */
ve.ce.BranchNode.prototype.onSlugClick = function ( slugNode ) {
	this.getRoot().getSurface().createSlug( slugNode );
};
 
/**
 * Get a slug at an offset.
 *
 * @param {number} offset Offset to get slug at
 * @return {HTMLElement|null}
 */
ve.ce.BranchNode.prototype.getSlugAtOffset = function ( offset ) {
	let startOffset = this.model.getOffset() + ( this.isWrapped() ? 1 : 0 );
 
	if ( offset === startOffset ) {
		return this.slugNodes[ 0 ] || null;
	}
	for ( let i = 0; i < this.children.length; i++ ) {
		startOffset += this.children[ i ].model.getOuterLength();
		if ( offset === startOffset ) {
			return this.slugNodes[ i + 1 ] || null;
		}
	}
	return null;
};
 
/**
 * Set live state on child nodes.
 *
 * @param {boolean} live New live state
 */
ve.ce.BranchNode.prototype.setLive = function ( live ) {
	// Parent method
	ve.ce.BranchNode.super.prototype.setLive.apply( this, arguments );
 
	for ( let i = 0; i < this.children.length; i++ ) {
		this.children[ i ].setLive( live );
	}
};
 
/**
 * Release all memory.
 */
ve.ce.BranchNode.prototype.destroy = function () {
	for ( let i = 0, len = this.children.length; i < len; i++ ) {
		this.children[ i ].destroy();
	}
 
	// Parent method
	ve.ce.BranchNode.super.prototype.destroy.call( this );
};
 
/**
 * @inheritdoc
 */
ve.ce.BranchNode.prototype.detach = function () {
	for ( let i = 0, len = this.children.length; i < len; i++ ) {
		this.children[ i ].detach();
	}
 
	// Parent method
	ve.ce.BranchNode.super.prototype.detach.call( this );
};
 
/**
 * Get the DOM position (node and offset) corresponding to a position in this node
 *
 * The node/offset have the same semantics as a DOM Selection focusNode/focusOffset
 *
 * @param {number} offset The offset inside this node of the required position
 * @return {ve.ce.NodeAndOffset} The DOM position; guaranteed to be this node's final DOM node
 */
ve.ce.BranchNode.prototype.getDomPosition = function ( offset ) {
	const domNode = this.$element.last()[ 0 ];
 
	// Step backwards past empty nodes
	let ceNode;
	let i = offset - 1;
	while ( true ) {
		ceNode = this.children[ i-- ];
		if ( !ceNode ) {
			// No preceding children with DOM nodes
			return { node: domNode, offset: 0 };
		}
		if ( ceNode.$element && ceNode.$element.length > 0 ) {
			// Preceding child with a DOM node
			return {
				node: domNode,
				offset: Array.prototype.indexOf.call(
					domNode.childNodes,
					ceNode.$element.last()[ 0 ]
				) + 1
			};
		}
		if ( ceNode.getType() === 'text' ) {
			break;
		}
	}
	// Darn, we hit a text node. CE text nodes can contain varying annotations and so it is
	// difficult to calculate how many childNodes to skip. Let's try stepping forward instead.
	i = offset;
	while ( true ) {
		ceNode = this.children[ i++ ];
		if ( !ceNode ) {
			// No following children with DOM nodes
			return { node: domNode, offset: domNode.childNodes.length };
		}
		Eif ( ceNode.$element && ceNode.$element.length > 0 ) {
			// Following child with a DOM node
			return {
				node: domNode,
				offset: Array.prototype.indexOf.call(
					domNode.childNodes,
					ceNode.$element.first()[ 0 ]
				)
			};
		}
		if ( ceNode.getType() === 'text' ) {
			break;
		}
	}
	// Oh no, there's a text node in both directions
	throw new Error( 'Cannot calculate DOM position: adjacent text nodes' );
};