All files / src/ce/keydownhandlers ve.ce.LinearDeleteKeyDownHandler.js

88.42% Statements 107/121
86.51% Branches 77/89
100% Functions 1/1
88.33% Lines 106/120

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                                            1x       1x   1x   1x                           1x 61x 61x 61x 61x 61x 61x 61x 61x   61x         61x     1x     60x 7x 7x                   60x 47x             47x               47x 47x 13x     13x             34x         3x         3x 3x 3x 3x 3x 3x 3x         31x                                     1x 1x       1x   1x 1x 1x   1x 1x 1x 1x 1x           30x         2x         2x 2x 2x 2x 2x 2x 2x     28x 28x                       41x 30x   30x 30x         30x 30x 45x 45x 45x 45x   4x 2x       2x 2x 2x 2x       41x   9x   45x   13x 13x 13x   4x   13x 13x 13x       17x             7x 7x 7x 5x 9x     7x 7x 7x                 2x 2x     5x     5x 5x 5x                       21x     21x 21x   21x 21x 21x         1x  
/*!
 * VisualEditor ContentEditable linear delete key down handler
 *
 * @copyright See AUTHORS.txt
 */
 
/* istanbul ignore next */
/**
 * Delete key down handler for linear selections.
 *
 * @class
 * @extends ve.ce.KeyDownHandler
 *
 * @constructor
 */
ve.ce.LinearDeleteKeyDownHandler = function VeCeLinearDeleteKeyDownHandler() {
	// Parent constructor - never called because class is fully static
	// ve.ui.LinearDeleteKeyDownHandler.super.apply( this, arguments );
};
 
/* Inheritance */
 
OO.inheritClass( ve.ce.LinearDeleteKeyDownHandler, ve.ce.KeyDownHandler );
 
/* Static properties */
 
ve.ce.LinearDeleteKeyDownHandler.static.name = 'linearDelete';
 
ve.ce.LinearDeleteKeyDownHandler.static.keys = [ OO.ui.Keys.BACKSPACE, OO.ui.Keys.DELETE ];
 
ve.ce.LinearDeleteKeyDownHandler.static.supportedSelections = [ 'linear' ];
 
/* Static methods */
 
/**
 * @inheritdoc
 *
 * The handler just schedules a poll to observe the native content removal, unless
 * one of the following is true:
 * - The ctrlKey is down; or
 * - The selection is expanded; or
 * - We are directly adjacent to an element node in the deletion direction.
 * In these cases, it will perform the content removal itself.
 */
ve.ce.LinearDeleteKeyDownHandler.static.execute = function ( surface, e ) {
	const direction = e.keyCode === OO.ui.Keys.DELETE ? 1 : -1,
		unit = ( e.altKey === true || e.ctrlKey === true ) ? 'word' : 'character',
		documentModel = surface.getModel().getDocument(),
		focusedNode = surface.getFocusedNode(),
		uiSurface = surface.getSurface(),
		data = documentModel.data;
	let offset = 0,
		rangeToRemove = surface.getModel().getSelection().getRange();
 
	Iif ( surface.isReadOnly() ) {
		e.preventDefault();
		return true;
	}
 
	if ( direction === 1 && e.shiftKey && ve.getSystemPlatform() !== 'mac' ) {
		// Shift+Del on non-Mac platforms performs 'cut', so
		// don't handle it here.
		return false;
	}
 
	if ( focusedNode ) {
		const command = uiSurface.commandRegistry.getDeleteCommandForNode( focusedNode );
		Iif ( command ) {
			command.execute( uiSurface );
			e.preventDefault();
			return true;
		}
	}
 
	// Use native behaviour then poll if collapsed, unless we are adjacent to some hard tag
	// (or CTRL is down, in which case we can't reliably predict whether the native behaviour
	// would delete far enough to remove some element)
	if ( rangeToRemove.isCollapsed() && !e.ctrlKey ) {
		Iif ( surface.nativeSelection.focusNode === null ) {
			// Unexplained failures causing log spam: T262303
			// How can it be null when this method should only be called for linear selections?
			e.preventDefault();
			return true;
		}
 
		let position = ve.adjacentDomPosition(
			{
				node: surface.nativeSelection.focusNode,
				offset: surface.nativeSelection.focusOffset
			},
			direction,
			{ stop: ve.isHardCursorStep }
		);
		const skipNode = position.steps[ position.steps.length - 1 ].node;
		if ( skipNode.nodeType === Node.TEXT_NODE ) {
			surface.eventSequencer.afterOne( {
				keydown: surface.surfaceObserver.pollOnce.bind( surface.surfaceObserver )
			} );
			return true;
		}
 
		let range;
		// If the native action would delete an outside nail, move *two* cursor positions
		// in the deletion direction, to get inside the link just past the inside nail,
		// then preventDefault
		if (
			direction > 0 ?
				skipNode.classList.contains( 've-ce-nail-pre-open' ) :
				skipNode.classList.contains( 've-ce-nail-post-close' )
		) {
			position = ve.adjacentDomPosition(
				position,
				direction,
				{ stop: ve.isHardCursorStep }
			);
			range = document.createRange();
			range.setStart( position.node, position.offset );
			surface.nativeSelection.removeAllRanges();
			surface.nativeSelection.addRange( range );
			surface.updateActiveAnnotations();
			e.preventDefault();
			return true;
		}
 
		let pairNode;
		// If inside an empty link, delete it and preventDefault
		if (
			skipNode.classList &&
			skipNode.classList.contains(
				direction > 0 ?
					've-ce-nail-pre-close' :
					've-ce-nail-post-open'
			) &&
			( pairNode = (
				direction > 0 ?
					skipNode.previousSibling :
					skipNode.nextSibling
			) ) &&
			pairNode.classList &&
			pairNode.classList.contains(
				direction > 0 ?
					've-ce-nail-post-open' :
					've-ce-nail-pre-close'
			)
		) {
			const linkNode = skipNode.parentNode;
			range = document.createRange();
			// Set start to link's offset, minus 1 to allow for outer nail deletion
			// (browsers actually tend to adjust range offsets automatically
			// for previous sibling deletion, but just in case …)
			range.setStart( linkNode.parentNode, ve.parentIndex( linkNode ) - 1 );
			// Remove the outer nails, then the link itself
			linkNode.parentNode.removeChild( linkNode.previousSibling );
			linkNode.parentNode.removeChild( linkNode.nextSibling );
			linkNode.parentNode.removeChild( linkNode );
 
			surface.nativeSelection.removeAllRanges();
			surface.nativeSelection.addRange( range );
			surface.updateActiveAnnotations();
			e.preventDefault();
			return true;
		}
 
		// If the native action would delete an inside nail, move *two* cursor positions
		// in the deletion direction, to get outside the link just past the outside nail,
		// then preventDefault
		if (
			direction > 0 ?
				skipNode.classList.contains( 've-ce-nail-pre-close' ) :
				skipNode.classList.contains( 've-ce-nail-post-open' )
		) {
			position = ve.adjacentDomPosition(
				position,
				direction,
				{ stop: ve.isHardCursorStep }
			);
			range = document.createRange();
			range.setStart( position.node, position.offset );
			surface.nativeSelection.removeAllRanges();
			surface.nativeSelection.addRange( range );
			surface.updateActiveAnnotations();
			e.preventDefault();
			return true;
		}
 
		offset = rangeToRemove.start;
		Iif ( !e.ctrlKey && (
			( direction < 0 && !data.isElementData( offset - 1 ) ) ||
			( direction > 0 && !data.isElementData( offset ) )
		) ) {
			surface.eventSequencer.afterOne( {
				keydown: surface.surfaceObserver.pollOnce.bind( surface.surfaceObserver )
			} );
			return true;
		}
	}
 
	// Else range is uncollapsed or is adjacent to a non-nail element.
	if ( rangeToRemove.isCollapsed() ) {
		const originalRange = new ve.Range( rangeToRemove.from, rangeToRemove.to );
		// Expand rangeToRemove
		rangeToRemove = documentModel.getRelativeRange( rangeToRemove, direction, unit, true );
		Iif ( surface.getActiveNode() && !surface.getActiveNode().getRange().containsRange( rangeToRemove ) ) {
			e.preventDefault();
			return true;
		}
 
		const documentModelSelectedNodes = documentModel.selectNodes( rangeToRemove, 'siblings' );
		for ( let i = 0; i < documentModelSelectedNodes.length; i++ ) {
			const node = documentModelSelectedNodes[ i ].node;
			const nodeOuterRange = documentModelSelectedNodes[ i ].nodeOuterRange;
			let adjacentBlockSelection = null;
			if ( node instanceof ve.dm.TableNode ) {
				// Prevent backspacing/deleting over table cells
				if ( rangeToRemove.containsOffset( nodeOuterRange.start ) ) {
					adjacentBlockSelection = new ve.dm.TableSelection(
						nodeOuterRange, 0, 0
					);
				} else {
					const matrix = node.getMatrix();
					const row = matrix.getRowCount() - 1;
					const col = matrix.getColCount( row ) - 1;
					adjacentBlockSelection = new ve.dm.TableSelection(
						nodeOuterRange, col, row
					);
				}
			} else if ( node.isFocusable() ) {
				// Prevent backspacing/deleting over focusable nodes
				adjacentBlockSelection = new ve.dm.LinearSelection( node.getOuterRange() );
			}
			if ( adjacentBlockSelection ) {
				// Create a fragment from the selection as we might delete first
				const adjacentFragment = surface.getModel().getFragment( adjacentBlockSelection, true );
				const currentNode = documentModel.getDocumentNode().getNodeFromOffset( originalRange.start );
				if ( currentNode.canContainContent() && !currentNode.getLength() ) {
					// If starting in an empty CBN, delete the CBN instead (T338622)
					surface.getModel().getLinearFragment( currentNode.getOuterRange(), true ).delete( direction );
				}
				adjacentFragment.select();
				e.preventDefault();
				return true;
			}
		}
 
		if ( rangeToRemove.isCollapsed() ) {
			// For some reason (most likely: we're at the beginning or end of the document) we can't
			// expand the range. So, should we delete something or not?
			// The rules are:
			// * if we're literally at the start or end, and are in a content node, don't do anything
			// * if we're in a plain paragraph, don't do anything
			// * if we're in a list item and it's empty get rid of the item
			offset = rangeToRemove.start;
			const docLength = documentModel.getDocumentRange().getLength();
			if ( offset < docLength - 1 ) {
				while ( offset < docLength - 1 && data.isCloseElementData( offset ) ) {
					offset++;
				}
			}
			const startNode = documentModel.getDocumentNode().getNodeFromOffset( offset - 1 );
			const nodeRange = startNode.getOuterRange();
			if (
				// The node is not unwrappable (e.g. table cells, text nodes)
				!startNode.isUnwrappable() ||
				// Content item at the start / end?
				(
					( startNode.canContainContent() || surface.attachedRoot === startNode ) &&
					( nodeRange.start === 0 || nodeRange.end === docLength )
				)
			) {
				e.preventDefault();
				return true;
			} else {
				// Expand our removal to reflect what we actually need to remove
				switch ( startNode.getType() ) {
					case 'list':
					case 'listItem':
						uiSurface.execute( 'indentation', 'decrease' );
						e.preventDefault();
						return;
					default:
						if ( direction > 0 ) {
							rangeToRemove = new ve.Range( rangeToRemove.start, nodeRange.end );
						} else {
							rangeToRemove = new ve.Range( nodeRange.start, rangeToRemove.start - 1 );
						}
				}
			}
		}
	}
 
	surface.getModel().getLinearFragment( rangeToRemove, true ).delete( direction ).select();
	// Rerender selection even if it didn't change
	// TODO: is any of this necessary?
	surface.focus();
	surface.surfaceObserver.clear();
	// Check delete sequences
	surface.findAndExecuteSequences( false, true );
	e.preventDefault();
	return true;
};
 
/* Registration */
 
ve.ce.keyDownHandlerFactory.register( ve.ce.LinearDeleteKeyDownHandler );