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

94.52% Statements 138/146
91.14% Branches 72/79
93.33% Functions 14/15
94.52% Lines 138/146
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                                        3457×     3457×     3457× 3457×     3457×     3457×                                                                                                                                   3459×   3459×                           441×     441×                                   2370×                         3616×               3616×       3616× 11808×     3616× 3138× 4576×           4573× 4573×         3616× 3616× 190×   190× 190× 190× 190×   190×   3616× 3138× 3138× 4576× 4576× 2927×     3138×   1885× 1885×         3138× 4576× 262×           3616× 3616×             3512× 1993×               5113× 3123×             4885×   4885× 472× 155×   472×                     5116×     5116×       5116×   5116×   5116× 1993× 3123×     3123×     5116× 774×     774× 115×   115×   659×   774× 774× 220×         220×                                     90×     90× 33×   57× 74× 74× 57×                     6456×   6456×   6456× 8137×             99× 99×       99×                         1892×       1892× 1892× 1895× 1895×   1837×   58×   53×                                                          
/*!
 * VisualEditor ContentEditable BranchNode class.
 *
 * @copyright 2011-2019 VisualEditor Team and others; see http://ve.mit-license.org
 */
 
/**
 * ContentEditable branch node.
 *
 * Branch nodes can have branch or leaf nodes as children.
 *
 * @class
 * @abstract
 * @extends ve.ce.Node
 * @mixins 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.apply( this, [ 0, 0 ].concat( 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 () {
	var profile = $.client.profile(),
		// The following classes can be used here:
		// * ve-ce-chimera-gecko
		// * ve-ce-chimera-konqueror
		// * ve-ce-chimera-msie
		// * ve-ce-chimera-trident
		// * ve-ce-chimera-edge
		// * ve-ce-chimera-opera
		// * ve-ce-chimera-webkit
		$img = $( '<img>' )
			.addClass( 've-ce-chimera ve-ce-chimera-' + profile.layout ),
		$span = $( '<span>' )
			.addClass( 've-ce-branchNode-slug ve-ce-branchNode-inlineSlug' )
			.append( $img );
 
	// Support: Firefox
	// Firefox <=37 misbehaves if we don't set an src: https://bugzilla.mozilla.org/show_bug.cgi?id=989012
	// Firefox 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 ( profile.layout === 'gecko' ) {
		$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>' )
			.prop( 'src', ve.ce.chimeraImgDataUri )
			.addClass( 've-ce-chimera ve-ce-chimera-debug' )
	)
	.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 teardown
 * @fires setup
 */
ve.ce.BranchNode.prototype.updateTagName = function () {
	var wrapper,
		tagName = this.getTagName();
 
	if ( tagName !== this.tagName ) {
		this.emit( 'teardown' );
		wrapper = document.createElement( tagName );
		// Copy classes
		wrapper.className = this.$element[ 0 ].className;
		// Copy contentEditable
		wrapper.contentEditable = this.$element[ 0 ].contentEditable;
		// Move contents
		while ( this.$element[ 0 ].firstChild ) {
			wrapper.appendChild( this.$element[ 0 ].firstChild );
		}
		// Swap elements
		if ( this.$element[ 0 ].parentNode ) {
			this.$element[ 0 ].parentNode.replaceChild( wrapper, 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' );
	}
};
 
/**
 * 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} howmany Number of nodes to remove
 * @param {...ve.dm.BranchNode} [nodes] Variadic list of nodes to insert
 */
ve.ce.BranchNode.prototype.onSplice = function ( index ) {
	var i, length, removals, position, j, fragment,
		inAttachedRoot, upstreamOfAttachedRoot,
		// attachedRoot and doc can be undefined in tests
		dmDoc = this.getModel().getDocument(),
		attachedRoot = dmDoc && dmDoc.attachedRoot,
		isAllAttached = !attachedRoot || attachedRoot instanceof ve.dm.DocumentNode,
		args = [];
 
	if ( !isAllAttached ) {
		// Optimization: Skip traversal when whole doc is attached
		inAttachedRoot = this.getModel().isDownstreamOf( attachedRoot );
		upstreamOfAttachedRoot = attachedRoot.collectUpstream();
	}
 
	for ( i = 0, length = arguments.length; i < length; i++ ) {
		args.push( arguments[ i ] );
	}
	// Convert models to views and attach them to this node
	if ( args.length >= 3 ) {
		for ( i = 2, length = args.length; i < length; i++ ) {
			if (
				isAllAttached || inAttachedRoot || upstreamOfAttachedRoot.indexOf( args[ i ] ) !== -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.
				args[ i ].findParent( ve.dm.InternalItemNode )
			) {
				args[ i ] = ve.ce.nodeFactory.createFromModel( args[ i ] );
				args[ i ].model.connect( this, { update: 'onModelUpdate' } );
			} else {
				args[ i ] = new ve.ce.UnrenderedNode( args[ i ] );
			}
		}
	}
	removals = this.children.splice.apply( this.children, args );
	for ( i = 0, length = removals.length; i < length; i++ ) {
		removals[ i ].model.disconnect( this, { update: 'onModelUpdate' } );
		// Stop child listening to its model (e.g. for splice event)
		removals[ i ].model.disconnect( removals[ i ] );
		removals[ i ].setLive( false );
		removals[ i ].detach();
		removals[ i ].$element.detach();
		// And fare thee weel a while
		removals[ i ].destroy();
	}
	if ( args.length >= 3 ) {
		fragment = document.createDocumentFragment();
		for ( i = args.length - 1; i >= 2; i-- ) {
			args[ i ].attach( this );
			for ( j = args[ i ].$element.length - 1; j >= 0; j-- ) {
				fragment.insertBefore( args[ i ].$element[ j ], fragment.childNodes[ 0 ] || null );
			}
		}
		if ( fragment.childNodes.length ) {
			// Only calculate this if it's needed, this function looks expensive
			position = this.getDomPosition( index );
			position.node.insertBefore(
				fragment,
				position.node.children[ position.offset ] || null
			);
		}
		for ( i = args.length - 1; i >= 2; i-- ) {
			if ( this.live !== args[ i ].isLive() ) {
				args[ 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 () {
	var i;
	// Remove all slugs in this branch
	for ( 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 ) {
	var i, slugTemplate, slugNode, child, slugButton, doc;
 
	// Source mode optimization
	Iif ( this.getModel().getDocument() && this.getModel().getDocument().sourceMode && isBlock ) {
		return;
	}
 
	doc = this.getElementDocument();
 
	this.removeSlugs();
 
	if ( isBlock ) {
		slugTemplate = ve.ce.BranchNode.blockSlugTemplate;
	} else Iif ( ve.inputDebug ) {
		slugTemplate = ve.ce.BranchNode.inputDebugInlineSlugTemplate;
	} else {
		slugTemplate = ve.ce.BranchNode.inlineSlugTemplate;
	}
 
	for ( i in this.getModel().slugPositions ) {
		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 ] ) {
			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 ) {
			slugButton = new ve.ui.NoFocusButtonWidget( {
				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 ) {
	var i,
		startOffset = this.model.getOffset() + ( this.isWrapped() ? 1 : 0 );
 
	if ( offset === startOffset ) {
		return this.slugNodes[ 0 ] || null;
	}
	for ( 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 ) {
	var i;
	// Parent method
	ve.ce.BranchNode.super.prototype.setLive.apply( this, arguments );
 
	for ( i = 0; i < this.children.length; i++ ) {
		this.children[ i ].setLive( live );
	}
};
 
/**
 * Release all memory.
 */
ve.ce.BranchNode.prototype.destroy = function () {
	var i, len;
	for ( i = 0, len = this.children.length; i < len; i++ ) {
		this.children[ i ].destroy();
	}
 
	// Parent method
	ve.ce.BranchNode.super.prototype.destroy.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 {Object|null} The DOM position
 * @return {Node} return.node DOM node; guaranteed to be this node's final DOM node
 * @return {number} return.offset DOM offset
 */
ve.ce.BranchNode.prototype.getDomPosition = function ( offset ) {
	var i, ceNode,
		domNode = this.$element.last()[ 0 ];
 
	// Step backwards past empty nodes
	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' );
};