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

92.86% Statements 130/140
92.31% Branches 96/104
84.62% Functions 11/13
92.86% Lines 130/140
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                                  295×   295× 295×   295× 295×     295×                                         295× 295× 295×               295× 295× 295×                                                                               914×                                             914×   913× 913×   913×     31× 48× 48× 28×   20×     20× 20×               30× 30×     30×     25×                     882×   523×       882× 2258× 301×   1957×         1957×     1957× 1957× 1957× 1107×   265×           842×   577× 577×     265× 265× 265×       850×           815×     35×               35×   35×     10× 10×   25× 25×     21× 21×                         882× 882×               882× 2474× 2474× 1235×     1239×       324× 324×   323× 323×   915×   882× 882×   1592× 10433×     1592× 1592× 1592× 1592× 1592× 1592× 1592× 1592×         882× 14×   868×       868×     52×   816×     80×   736× 387× 222×     165×   349×                                                    
/*!
 * VisualEditor ContentEditable Document class.
 *
 * @copyright 2011-2019 VisualEditor Team and others; see http://ve.mit-license.org
 */
 
/**
 * ContentEditable document.
 *
 * @class
 * @extends ve.Document
 *
 * @constructor
 * @param {ve.dm.Document} model Model to observe
 * @param {ve.ce.Surface} surface Surface document is part of
 */
ve.ce.Document = function VeCeDocument( model, surface ) {
	// Parent constructor
	ve.ce.Document.super.call( this, new ve.ce.DocumentNode( model.getDocumentNode(), surface ) );
 
	this.lang = null;
	this.dir = null;
 
	this.setLang( model.getLang() );
	this.setDir( model.getDir() );
 
	// Properties
	this.model = model;
};
 
/* Inheritance */
 
OO.inheritClass( ve.ce.Document, ve.Document );
 
/* Events */
 
/**
 * Language or direction changed
 *
 * @event langChange
 */
 
/* Methods */
 
/**
 * Set the document view language
 *
 * @param {string} lang Language code
 */
ve.ce.Document.prototype.setLang = function ( lang ) {
	this.getDocumentNode().$element.prop( 'lang', lang );
	this.lang = lang;
	this.emit( 'langChange' );
};
 
/**
 * Set the document view directionality
 *
 * @param {string} dir Directionality (ltr/rtl)
 */
ve.ce.Document.prototype.setDir = function ( dir ) {
	this.getDocumentNode().$element.prop( 'dir', dir );
	this.dir = dir;
	this.emit( 'langChange' );
};
 
/**
 * Get the document view language
 *
 * @return {string} Language code
 */
ve.ce.Document.prototype.getLang = function () {
	return this.lang;
};
 
/**
 * Get the document view directionality
 *
 * @return {string} Directionality (ltr/rtl)
 */
ve.ce.Document.prototype.getDir = function () {
	return this.dir;
};
 
/**
 * Get a slug at an offset.
 *
 * @param {number} offset Offset to get slug at
 * @return {HTMLElement} Slug at offset
 */
ve.ce.Document.prototype.getSlugAtOffset = function ( offset ) {
	var node = this.getBranchNodeFromOffset( offset );
	return node ? node.getSlugAtOffset( offset ) : null;
};
 
/**
 * Calculate the DOM position corresponding to a DM offset
 *
 * If there are multiple DOM locations, heuristically pick the best one for cursor placement
 *
 * @private
 * @param {number} offset Linear model offset
 * @return {Object} position
 * @return {Node} return.node position node
 * @return {number} return.offset position offset within the node
 * @throws {Error} Offset could not be translated to a DOM element and offset
 */
ve.ce.Document.prototype.getNodeAndOffset = function ( offset ) {
	var branchNode, count, i, ceChild, position, step, node, model, steps, found, prevNode,
		$viewNodes,
		countedNodes = [];
 
	// 1. Step with ve.adjacentDomPosition( …, { stop: function () { return true; } } )
	// until we hit a position at the correct offset (which is guaranteed to be the first
	// such position in document order).
	// 2. Use ve.adjacentDomPosition( …, { stop: … } ) once to return all
	// subsequent positions at the same offset.
	// 3. Look at the possible positions and pick as follows:
	//   - If there is a unicorn, return just inside it
	//   - Else if there is a nail, return just outside it
	//   - Else if there is a text node, return an offset in it
	//   - Else return the first matching offset
	//
	// Offsets of DOM nodes are counted to match their model equivalents.
	//
	// TODO: take the following into account:
	// Unfortunately, there is no way to avoid slugless block nodes with no DM length: an
	// IME can remove all the text from a node at a time when it is unsafe to fixup the node
	// contents. In this case, a maximally deep element gives better bounding rectangle
	// coordinates than any of its containers.
 
	if ( !this.model.getDocumentRange().containsRange( new ve.Range( offset ) ) ) {
		throw new Error( 'Offset is out of bounds' );
	}
	branchNode = this.getBranchNodeFromOffset( offset );
	count = branchNode.getOffset() + ( ( branchNode.isWrapped() ) ? 1 : 0 );
 
	if ( !( branchNode instanceof ve.ce.ContentBranchNode ) ) {
		// The cursor does not lie in a ContentBranchNode, so we can determine
		// everything from the DM tree
		for ( i = 0; ; i++ ) {
			ceChild = branchNode.children[ i ];
			if ( count === offset ) {
				break;
			}
			Iif ( !ceChild ) {
				throw new Error( 'Offset lies beyond branchNode' );
			}
			count += ceChild.getOuterLength();
			if ( count > offset ) {
				Iif ( ceChild.getOuterLength() !== 2 ) {
					throw new Error( 'Offset lies inside child of strange size' );
				}
				node = ceChild.$element[ 0 ];
				if ( node ) {
					return { node: node, offset: 0 };
				}
				// Else ceChild has no DOM representation; step forwards
				break;
			}
		}
		// Offset lies directly in branchNode, just before ceChild
		node = branchNode.$element[ 0 ];
		while ( ceChild && !ceChild.$element[ 0 ] ) {
			// Node does not have a DOM representation; move forwards past it
			i++;
			ceChild = branchNode.children[ i ];
		}
		if ( !ceChild || !ceChild.$element[ 0 ] ) {
			// Offset lies just at the end of branchNode
			return { node: node, offset: node.childNodes.length };
		}
		return {
			node: node,
			offset: Array.prototype.indexOf.call(
				node.childNodes,
				ceChild.$element[ 0 ]
			)
		};
	}
 
	// Else the cursor lies in a ContentBranchNode, so we must traverse the DOM, keeping
	// count of the corresponding DM position until it reaches offset.
	position = { node: branchNode.$element[ 0 ], offset: 0 };
 
	function noDescend() {
		return this.classList.contains( 've-ce-branchNode-blockSlug' ) ||
			ve.rejectsCursor( this );
	}
 
	while ( true ) {
		if ( count === offset ) {
			break;
		}
		position = ve.adjacentDomPosition(
			position,
			1,
			{
				noDescend: noDescend,
				stop: function () { return true; }
			}
		);
		step = position.steps[ 0 ];
		node = step.node;
		if ( node.nodeType === Node.TEXT_NODE ) {
			if ( step.type === 'leave' ) {
				// Skip without incrementing
				continue;
			}
			// else the code below always breaks or skips over the text node;
			// therefore it is guaranteed that step.type === 'enter' (we just
			// stepped in)
			// TODO: what about zero-length text nodes?
			if ( offset <= count + node.data.length ) {
				// Match the appropriate offset in the text node
				position = { node: node, offset: offset - count };
				break;
			} else {
				// Skip over the text node
				count += node.data.length;
				position = { node: node, offset: node.data.length };
				continue;
			}
		} // else it is an element node (TODO: handle comment etc)
 
		if ( !(
			node.classList.contains( 've-ce-branchNode' ) ||
			node.classList.contains( 've-ce-leafNode' )
		) ) {
			// Nodes like b, inline slug, browser-generated br that doesn't have
			// class ve-ce-leafNode: continue walk without incrementing
			continue;
		}
 
		Iif ( step.type === 'leave' ) {
			// Below we'll guarantee that .ve-ce-branchNode/.ve-ce-leafNode elements
			// are only entered if their open/close tags take up a model offset, so
			// we can increment unconditionally here
			count++;
			continue;
		} // else step.type === 'enter' || step.type === 'cross'
 
		model = $.data( node, 'view' ).model;
 
		if ( countedNodes.indexOf( model ) !== -1 ) {
			// This DM node is rendered as multiple DOM elements, and we have already
			// counted it as part of an earlier element. Skip past without incrementing
			position = { node: node.parentNode, offset: ve.parentIndex( node ) + 1 };
			continue;
		}
		countedNodes.push( model );
		if ( offset >= count + model.getOuterLength() ) {
			// Offset doesn't lie inside the node. Skip past and count length
			// skip past the whole node
			position = { node: node.parentNode, offset: ve.parentIndex( node ) + 1 };
			count += model.getOuterLength();
		} else Eif ( step.type === 'cross' ) {
			Eif ( offset === count + 1 ) {
				// The offset lies inside the crossed node
				position = { node: node, offset: 0 };
				break;
			}
			count += 2;
		} else {
			count += 1;
		}
	}
	// Now "position" is the first DOM position (in document order) at the correct
	// model offset.
 
	// If the position is exactly after the first of multiple view nodes sharing a model,
	// then jump to the position exactly after the final such view node.
	prevNode = position.node.childNodes[ position.offset - 1 ];
	if ( prevNode && prevNode.nodeType === Node.ELEMENT_NODE && (
		prevNode.classList.contains( 've-ce-branchNode' ) ||
		prevNode.classList.contains( 've-ce-leafNode' )
	) ) {
		$viewNodes = $.data( prevNode, 'view' ).$element;
		if ( $viewNodes.length > 1 ) {
			position.node = $viewNodes.get( -1 ).parentNode;
			position.offset = 1 + ve.parentIndex( $viewNodes.get( -1 ) );
		}
	}
 
	// Find all subsequent DOM positions at the same model offset
	found = {};
	function stop( step ) {
		var model;
		if ( step.node.nodeType === Node.TEXT_NODE ) {
			return step.type === 'internal';
		}
 
		if (
			step.node.classList.contains( 've-ce-branchNode' ) ||
			step.node.classList.contains( 've-ce-leafNode' )
		) {
			model = $.data( step.node, 'view' ).model;
			if ( countedNodes.indexOf( model ) !== -1 ) {
				return false;
			}
			countedNodes.push( model );
			return true;
		}
		return false;
	}
	steps = ve.adjacentDomPosition( position, 1, { stop: stop, noDescend: noDescend } ).steps;
	steps.slice( 0, -1 ).forEach( function ( step ) {
		// Step type cannot be "internal", else the offset would have incremented
		var hasClass = function ( className ) {
			return step.node.nodeType === Node.ELEMENT_NODE &&
				step.node.classList.contains( className );
		};
		found.preUnicorn = found.preUnicorn || ( hasClass( 've-ce-pre-unicorn' ) && step );
		found.postUnicorn = found.postUnicorn || ( hasClass( 've-ce-post-unicorn' ) && step );
		found.preOpenNail = found.preOpenNail || ( hasClass( 've-ce-nail-pre-open' ) && step );
		found.postOpenNail = found.postOpenNail || ( hasClass( 've-ce-nail-post-open' ) && step );
		found.preCloseNail = found.preCloseNail || ( hasClass( 've-ce-nail-pre-close' ) && step );
		found.postCloseNail = found.postCloseNail || ( hasClass( 've-ce-nail-post-close' ) && step );
		found.focusableNode = found.focusableNode || ( hasClass( 've-ce-focusableNode' ) && step );
		found.text = found.text || ( step.node.nodeType === Node.TEXT_NODE && step );
	} );
 
	// If there is a unicorn, it should be a unique pre/post-Unicorn pair containing text or
	// nothing return the position just inside.
	if ( found.preUnicorn ) {
		return ve.ce.nextCursorOffset( found.preUnicorn.node );
	}
	Iif ( found.postUnicorn ) {
		return ve.ce.previousCursorOffset( found.postUnicorn.node );
	}
 
	if ( found.preOpenNail ) {
		// This will also cover the case where there is a post-open nail, as there will
		// be no offset difference between them
		return ve.ce.previousCursorOffset( found.preOpenNail.node );
	}
	if ( found.postCloseNail ) {
		// This will also cover the case where there is a pre-close nail, as there will
		// be no offset difference between them
		return ve.ce.nextCursorOffset( found.postCloseNail.node );
	}
	if ( found.text ) {
		if ( position.node.nodeType === Node.TEXT_NODE ) {
			return position;
		}
		// We must either have entered or left the text node
		return { node: found.text.node, offset: 0 };
	}
	return position;
};
 
/**
 * Get the block directionality of some range
 *
 * Uses the computed CSS direction value of the current node
 *
 * @param {ve.Range} range Range
 * @return {string} 'rtl', 'ltr'
 */
ve.ce.Document.prototype.getDirectionalityFromRange = function ( range ) {
	var effectiveNode,
		selectedNodes = this.selectNodes( range, 'covered' );
 
	if ( selectedNodes.length > 1 ) {
		// Selection of multiple nodes
		// Get the common parent node
		effectiveNode = this.selectNodes( range, 'siblings' )[ 0 ].node.getParent();
	} else {
		// Selection of a single node
		effectiveNode = selectedNodes[ 0 ].node;
 
		while ( effectiveNode.isContent() ) {
			// This means that we're in a leaf node, like TextNode
			// those don't read the directionality properly, we will
			// have to climb up the parentage chain until we find a
			// wrapping node like paragraph or list item, etc.
			effectiveNode = effectiveNode.parent;
		}
	}
 
	return effectiveNode.$element.css( 'direction' );
};