Debian Codegraph @

extensions/VisualEditor/lib/ve/src/ce/ve.ce.Surface.js

raw symbols SCIP
1 /*!
2 * VisualEditor ContentEditable Surface class.
3 *
4 * @copyright See AUTHORS.txt
5 */
6
7 /**
8 * ContentEditable surface.
9 *
10 * @class
11 * @extends OO.ui.Element
12 * @mixes OO.EventEmitter
13 *
14 * @constructor
15 * @param {ve.dm.Surface} model Surface model to observe
16 * @param {ve.ui.Surface} ui Surface user interface
17 * @param {Object} [config] Configuration options
18 */
19 ve.ce.Surface = function VeCeSurface( model, ui, config ) {
20 // Parent constructor
21 ve.ce.Surface.super.call( this, config );
22
23 // Mixin constructors
24 OO.EventEmitter.call( this );
25
26 // Properties
27 this.surface = ui;
28 this.model = model;
29 this.documentView = new ve.ce.Document( model.getDocument(), this );
30 this.attachedRoot = this.getDocument().getDocumentNode().getNodeFromOffset(
31 model.getDocument().getAttachedRoot().getOffset() + ( model.getDocument().getAttachedRoot().isWrapped() ? 1 : 0 )
32 );
33 this.selection = null;
34 this.readOnly = false;
35 this.reviewMode = false;
36 this.surfaceObserver = new ve.ce.SurfaceObserver( this );
37 this.$window = $( this.getElementWindow() );
38 this.$document = $( this.getElementDocument() );
39 this.$attachedRootNode = this.attachedRoot.$element.addClass( 've-ce-attachedRootNode' );
40 // Deprecated aliases
41 this.$documentNode = this.$attachedRootNode;
42 this.root = this.attachedRoot;
43 // Window.getSelection returns a live singleton representing the document's selection
44 this.nativeSelection = this.getElementWindow().getSelection();
45 ve.fixSelectionNodes( this.nativeSelection );
46 this.eventSequencer = new ve.EventSequencer( [
47 'keydown', 'keypress', 'keyup',
48 'compositionstart', 'compositionend',
49 'beforeinput', 'input', 'mousedown'
50 ] );
51 this.clipboard = null;
52 this.clipboardId = Math.random().toString();
53 this.clipboardIndex = 0;
54 // The last non-collapsed selection in this VE surface. This will be a NullSelection
55 // if there has never had a non-collapsed selection, or if the cursor is moved out of
56 // the surface and a selection is made elsewhere.
57 this.lastNonCollapsedDocumentSelection = new ve.dm.NullSelection();
58 this.middleClickPasting = false;
59 this.middleClickTargetOffset = false;
60 this.renderLocks = 0;
61 this.dragging = false;
62 this.relocatingSelection = null;
63 this.relocatingNode = null;
64 this.allowedFile = null;
65 this.resizing = false;
66 this.focused = false;
67 this.deactivated = false;
68 this.showAsActivated = false;
69 this.hideSelection = false;
70 this.$deactivatedSelection = $( '<div>' );
71 this.userSelectionDeactivate = {};
72 this.drawnSelections = {};
73 this.drawnSelectionCache = {};
74 this.activeNode = null;
75 this.contentBranchNodeChanged = false;
76 this.selectionLink = null;
77 this.delayedSequences = [];
78 this.$highlightsFocused = $( '<div>' );
79 this.$highlightsBlurred = $( '<div>' );
80 this.$highlights = $( '<div>' ).append(
81 this.$highlightsFocused, this.$highlightsBlurred
82 );
83 this.$findResults = $( '<div>' );
84 this.$dropMarker = $( '<div>' ).addClass( 've-ce-surface-dropMarker oo-ui-element-hidden' );
85 this.$lastDropTarget = null;
86 this.lastDropPosition = null;
87 this.$pasteTarget = $( '<div>' );
88 this.pasting = false;
89 this.beforePasteAnnotationsAtFocus = [];
90 this.copying = false;
91 this.pasteSpecial = false;
92 this.pointerEvents = null;
93 this.focusedBlockSlug = null;
94 this.focusedNode = null;
95 this.activeAnnotations = [];
96 this.contexedAnnotations = [];
97 this.previousActiveAnnotations = [];
98 // This is set on entering changeModel, then unset when leaving.
99 // It is used to test whether a reflected change event is emitted.
100 this.newModelSelection = null;
101
102 // Snapshot updated at keyDown. See storeKeyDownState.
103 this.keyDownState = {
104 event: null,
105 selectionState: null
106 };
107
108 this.cursorDirectionality = null;
109 this.unicorningNode = null;
110 this.setUnicorningRecursionGuard = false;
111 this.cursorHolderBefore = null;
112 this.cursorHolderAfter = null;
113
114 // Events
115 // Debounce to prevent trying to draw every cursor position in history.
116 this.onPositionDebounced = ve.debounce( this.onPosition.bind( this ) );
117 this.connect( this, { position: this.onPositionDebounced } );
118 this.model.connect( this, {
119 select: 'onModelSelect',
120 documentUpdate: 'onModelDocumentUpdate',
121 insertionAnnotationsChange: 'onInsertionAnnotationsChange'
122 } );
123
124 if ( this.model.synchronizer ) {
125 this.model.synchronizer.connect( this, {
126 authorSelect: 'onSynchronizerAuthorUpdate',
127 authorChange: 'onSynchronizerAuthorUpdate',
128 authorDisconnect: 'onSynchronizerAuthorDisconnect',
129 wrongDoc: 'onSynchronizerWrongDoc',
130 pause: 'onSynchronizerPause'
131 } );
132 }
133
134 this.onDocumentMouseUpHandler = this.onDocumentMouseUp.bind( this );
135 this.$attachedRootNode.on( {
136 // Mouse events shouldn't be sequenced as the event sequencer
137 // is detached on blur
138 mousedown: this.onDocumentMouseDown.bind( this ),
139 // mouseup is bound to the whole document on mousedown
140 cut: this.onCut.bind( this ),
141 copy: this.onCopy.bind( this )
142 } );
143
144 this.onWindowResizeHandler = ve.debounce( this.onWindowResize.bind( this ), 50 );
145 this.$window.on( 'resize', this.onWindowResizeHandler );
146
147 this.onDocumentFocusInOutHandler = this.onDocumentFocusInOut.bind( this );
148 this.$document.on( 'focusin focusout', this.onDocumentFocusInOutHandler );
149
150 this.debounceFocusChange = ve.debounce( this.onFocusChange.bind( this ) );
151 // If the document is blurred (but still has a selection) it is
152 // possible to clear the selection by clicking elsewhere without
153 // triggering a focus or blur event, so listen to mousedown globally.
154 this.$document.on( 'mousedown', this.debounceFocusChange );
155 // It is possible that when focusin fires, the selection is not yet inside
156 // the document. This happens if the selection is being moved inside itself,
157 // e.g. the whole html page was previously selected, including the attachedRootNode
158 // In this case the selection is not moved until mouseup. T157499
159 this.$attachedRootNode.on( 'mouseup', this.debounceFocusChange );
160
161 this.$pasteTarget.add( this.$highlights ).on( {
162 cut: this.onCut.bind( this ),
163 copy: this.onCopy.bind( this ),
164 paste: this.onPaste.bind( this )
165 } );
166
167 this.$attachedRootNode
168 .on( 'paste', this.onPaste.bind( this ) )
169 .on( 'focus', 'a', () => {
170 // Opera <= 12 triggers 'blur' on document node before any link is
171 // focused and we don't want that
172 this.$attachedRootNode[ 0 ].focus();
173 } );
174
175 this.onDocumentSelectionChangeHandler = this.onDocumentSelectionChange.bind( this );
176 this.$document.on( 'selectionchange', this.onDocumentSelectionChangeHandler );
177
178 this.$element.on( {
179 dragstart: this.onDocumentDragStart.bind( this ),
180 dragover: this.onDocumentDragOver.bind( this ),
181 dragleave: this.onDocumentDragLeave.bind( this ),
182 drop: this.onDocumentDrop.bind( this )
183 } );
184
185 // Add listeners to the eventSequencer. They won't get called until
186 // eventSequencer.attach(node) has been called.
187 this.eventSequencer.on( {
188 keydown: this.onDocumentKeyDown.bind( this ),
189 keyup: this.onDocumentKeyUp.bind( this ),
190 keypress: this.onDocumentKeyPress.bind( this ),
191 beforeinput: this.onDocumentBeforeInput.bind( this ),
192 input: this.onDocumentInput.bind( this ),
193 compositionstart: this.onDocumentCompositionStart.bind( this )
194 } ).after( {
195 keydown: this.afterDocumentKeyDown.bind( this )
196 } );
197
198 this.mutationObserver = new MutationObserver( this.afterMutations.bind( this ) );
199 this.mutationObserver.observe(
200 this.$attachedRootNode[ 0 ],
201 { childList: true, subtree: true }
202 );
203
204 // Initialization
205 // Support: Chrome
206 // Add 'notranslate' class to prevent Chrome's translate feature from
207 // completely messing up the CE DOM (T59124)
208 this.$element.addClass( 've-ce-surface notranslate' );
209 // Support: Edge
210 // Add translate="no" attribute to prevent Chromium Edge's translate feature from
211 // translating our editable surface, and leaving junk behind... (T267747)
212 // Some documentation out there says it respects class="notranslate", but it doesn't.
213 this.$element.attr( 'translate', 'no' );
214 this.$highlights.addClass( 've-ce-surface-highlights' );
215 this.$highlightsFocused.addClass( 've-ce-surface-highlights-focused' );
216 this.$highlightsBlurred.addClass( 've-ce-surface-highlights-blurred' );
217 this.$deactivatedSelection.addClass( 've-ce-surface-deactivatedSelection' );
218 this.$pasteTarget
219 .addClass( 've-ce-surface-paste' )
220 // T283853
221 .attr( 'aria-hidden', true )
222 .prop( {
223 tabIndex: -1,
224 contentEditable: 'true'
225 } );
226
227 // Add elements to the DOM
228 this.$highlights.append( this.$dropMarker );
229 this.$element.append( this.$attachedRootNode, this.$pasteTarget );
230 this.surface.$blockers.append( this.$highlights );
231 this.surface.$selections.append( this.$deactivatedSelection );
232 };
233
234 /* Inheritance */
235
236 OO.inheritClass( ve.ce.Surface, OO.ui.Element );
237
238 OO.mixinClass( ve.ce.Surface, OO.EventEmitter );
239
240 /* Events */
241
242 /**
243 * @event ve.ce.Surface#relocationStart
244 */
245
246 /**
247 * @event ve.ce.Surface#relocationEnd
248 */
249
250 /**
251 * @event ve.ce.Surface#keyup
252 */
253
254 /**
255 * When the surface or its contents changes position
256 * (only after initialize has already been called).
257 *
258 * @event ve.ce.Surface#position
259 * @param {boolean} [wasSynchronizing] The surface was positioned due to
260 * synchronization (ve.dm.SurfaceSynchronizer)
261 */
262
263 /**
264 * Note that it's possible for a focus event to occur immediately after a blur event, if the focus
265 * moves to or from a FocusableNode. In this case the surface doesn't lose focus conceptually, but
266 * a pair of blur-focus events is emitted anyway.
267 *
268 * @event ve.ce.Surface#focus
269 */
270
271 /**
272 * Note that it's possible for a focus event to occur immediately after a blur event, if the focus
273 * moves to or from a FocusableNode. In this case the surface doesn't lose focus conceptually, but
274 * a pair of blur-focus events is emitted anyway.
275 *
276 * @event ve.ce.Surface#blur
277 */
278
279 /**
280 * Surface activation state has changed (i.e. on activate or deactivate)
281 *
282 * @event ve.ce.Surface#activation
283 */
284
285 /* Static properties */
286
287 /**
288 * Attributes considered 'unsafe' for copy/paste
289 *
290 * These attributes may be dropped by the browser during copy/paste, so
291 * any element containing these attributes will have them JSON encoded into
292 * data-ve-attributes on copy.
293 *
294 * @type {string[]}
295 */
296 ve.ce.Surface.static.unsafeAttributes = [
297 // Support: Firefox
298 // RDFa: Firefox ignores these
299 'about',
300 'content',
301 'datatype',
302 'property',
303 'rel',
304 'resource',
305 'rev',
306 'typeof',
307 // CSS: Values are often added or modified
308 'style'
309 ];
310
311 /**
312 * Values of InputEvent.inputType which map to a command
313 *
314 * Currently these are triggered when the user selects
315 * undo/redo from the context menu in Chrome, or uses the
316 * selection formatting tools on iOS.
317 *
318 * See https://w3c.github.io/input-events/
319 *
320 * commands like { collapsed: 'foo', uncollapsed: 'bar' }
321 * act conditionally depending whether the selection is
322 * collapsed
323 *
324 * A value of `null` will perform no action and
325 * preventDefault. A value of `undefined` will do nothing
326 * and let the event continue.
327 *
328 * @type {Object.<string,string|null|Object>}
329 */
330 ve.ce.Surface.static.inputTypeCommands = {
331 historyUndo: 'undo',
332 historyRedo: 'redo',
333 formatBold: 'bold',
334 formatItalic: 'italic',
335 formatUnderline: 'underline',
336 formatStrikeThrough: 'strikethrough',
337 formatSuperscript: 'superscript',
338 formatSubscript: 'subscript',
339 formatJustifyFull: null,
340 formatJustifyCenter: null,
341 formatJustifyRight: null,
342 formatJustifyLeft: null,
343 formatIndent: 'indent',
344 formatOutdent: 'outdent',
345 formatRemove: 'clear',
346 formatSetBlockTextDirection: null,
347 formatSetInlineTextDirection: null,
348 formatBackColor: null,
349 formatFontColor: null,
350 formatFontName: null,
351 // Support: Firefox
352 // Delete content via context menu in Firefox. (T220629)
353 // If there is a non-collapsed selection, a delete content event can only ever just remove
354 // the selected content. The only time we know this event is fired is in Firefox, where
355 // no other change events are fired.
356 // If any other browsers fire this event with a selection this is harmless, as removing
357 // the content without moving the cursor is always the correct thing to do.
358 deleteContentBackward: { uncollapsed: 'backspace' }
359 };
360
361 /**
362 * Cursor holder template
363 *
364 * @static
365 * @property {HTMLElement}
366 */
367 ve.ce.Surface.static.cursorHolderTemplate =
368 $( '<div>' )
369 .addClass( 've-ce-cursorHolder' )
370 .prop( 'contentEditable', 'true' )
371 .append(
372 // The image does not need a src for Firefox in spite of cursoring
373 // bug https://bugzilla.mozilla.org/show_bug.cgi?id=989012 , because
374 // you can cursor to ce=false blocks in Firefox (see bug
375 // https://bugzilla.mozilla.org/show_bug.cgi?id=1155031 )
376 $( '<img>' )
377 .addClass( 've-ce-cursorHolder-img' )
378 .attr( {
379 role: 'none',
380 alt: ''
381 } )
382 )
383 .get( 0 );
384
385 /* Static methods */
386
387 /**
388 * When pasting, browsers normalize HTML to varying degrees.
389 * This hash creates a comparable string for validating clipboard contents.
390 *
391 * @param {jQuery} $elements Clipboard HTML
392 * @param {Object} [beforePasteData] Paste information, including leftText and rightText to strip
393 * @return {string} Hash
394 */
395 ve.ce.Surface.static.getClipboardHash = function ( $elements, beforePasteData ) {
396 beforePasteData = beforePasteData || {};
397 return $elements.text()
398 .slice(
399 beforePasteData.leftText ? beforePasteData.leftText.length : 0,
400 beforePasteData.rightText ? -beforePasteData.rightText.length : undefined
401 )
402 // Whitespace may be modified (e.g. ' ' to '&nbsp;'), so strip it all
403 .replace( /\s/gm, '' );
404 };
405
406 /* Methods */
407
408 /**
409 * Destroy the surface, removing all DOM elements.
410 */
411 ve.ce.Surface.prototype.destroy = function () {
412 const attachedRoot = this.attachedRoot;
413
414 // Support: Firefox, iOS
415 // FIXME T126041: Blur to make selection/cursor disappear (needed in Firefox
416 // in some cases, and in iOS to hide the keyboard)
417 if ( this.isFocused() ) {
418 this.blur();
419 }
420
421 // Detach observer and event sequencer
422 this.surfaceObserver.stopTimerLoop();
423 this.surfaceObserver.detach();
424 this.eventSequencer.detach();
425
426 // Make document node not live
427 attachedRoot.setLive( false );
428
429 // Disconnect events
430 this.model.disconnect( this );
431
432 // Disconnect DOM events on the document
433 this.$document.off( 'focusin focusout', this.onDocumentFocusInOutHandler );
434 this.$document.off( 'mousedown', this.debounceFocusChange );
435 this.$document.off( 'selectionchange', this.onDocumentSelectionChangeHandler );
436
437 if ( this.model.synchronizer ) {
438 // TODO: Move destroy to ve.dm.Surface#destroy
439 this.model.synchronizer.destroy();
440 this.model.synchronizer.disconnect( this );
441 }
442
443 // Disconnect DOM events on the window
444 this.$window.off( 'resize', this.onWindowResizeHandler );
445
446 // Remove DOM elements (also disconnects their events)
447 this.$element.remove();
448 this.$highlights.remove();
449 };
450
451 /**
452 * Get linear model offest from a mouse event
453 *
454 * @param {Event} e
455 * @return {number} Linear model offset, or -1 if coordinates are out of bounds
456 */
457 ve.ce.Surface.prototype.getOffsetFromEventCoords = function ( e ) {
458 return this.getOffsetFromCoords(
459 e.pageX - this.surface.$scrollContainer.scrollLeft(),
460 e.pageY - this.surface.$scrollContainer.scrollTop()
461 );
462 };
463
464 /**
465 * Get linear model offset from absolute coords
466 *
467 * @param {number} x X offset
468 * @param {number} y Y offset
469 * @return {number} Linear model offset, or -1 if coordinates are out of bounds
470 */
471 ve.ce.Surface.prototype.getOffsetFromCoords = function ( x, y ) {
472 const doc = this.getElementDocument();
473
474 try {
475 let offset;
476 if ( doc.caretPositionFromPoint ) {
477 // Gecko
478 // http://dev.w3.org/csswg/cssom-view/#extensions-to-the-document-interface
479 const caretPosition = document.caretPositionFromPoint( x, y );
480 offset = ve.ce.getOffset( caretPosition.offsetNode, caretPosition.offset );
481 } else if ( doc.caretRangeFromPoint ) {
482 // Webkit
483 // http://www.w3.org/TR/2009/WD-cssom-view-20090804/
484 const range = document.caretRangeFromPoint( x, y );
485 offset = ve.ce.getOffset( range.startContainer, range.startOffset );
486 } else if ( document.body.createTextRange ) {
487 // Trident
488 // http://msdn.microsoft.com/en-gb/library/ie/ms536632(v=vs.85).aspx
489 const textRange = document.body.createTextRange();
490 textRange.moveToPoint( x, y );
491 textRange.pasteHTML( '<span class="ve-ce-textRange-drop-marker">&nbsp;</span>' );
492 // eslint-disable-next-line no-jquery/no-global-selector
493 const $marker = $( '.ve-ce-textRange-drop-marker' );
494 offset = ve.ce.getOffset( $marker.get( 0 ), 0 );
495 $marker.remove();
496 }
497 return offset;
498 } catch ( e ) {
499 // Both ve.ce.getOffset and TextRange.moveToPoint can throw out of bounds exceptions
500 return -1;
501 }
502 };
503
504 /**
505 * Get selection view object
506 *
507 * @param {ve.dm.Selection} [selection] Optional selection model, defaults to current selection
508 * @return {ve.ce.Selection} Selection view
509 */
510 ve.ce.Surface.prototype.getSelection = function ( selection ) {
511 if ( selection ) {
512 // Specific selection requested, bypass cache
513 return ve.ce.Selection.static.newFromModel( selection, this );
514 } else if ( !this.selection ) {
515 this.selection = ve.ce.Selection.static.newFromModel( this.getModel().getSelection(), this );
516 }
517 return this.selection;
518 };
519
520 /**
521 * Get block directionality at selection
522 *
523 * @return {string} 'rtl' or 'ltr'
524 */
525 ve.ce.Surface.prototype.getSelectionDirectionality = function () {
526 return this.getSelection().getDirectionality( this.getDocument() );
527 };
528
529 /* Initialization */
530
531 /**
532 * Initialize surface.
533 *
534 * This should be called after the surface has been attached to the DOM.
535 *
536 * @fires ve.ce.Surface#position
537 */
538 ve.ce.Surface.prototype.initialize = function () {
539 this.attachedRoot.setLive( true );
540 if ( $.client.profile().layout === 'gecko' ) {
541 // Support: Firefox < 64
542 // Turn off native object editing. This must be tried after the surface has been added to DOM.
543 // This is only needed in Gecko. In other engines, these properties are off by default,
544 // and turning them off again is expensive; see https://phabricator.wikimedia.org/T89928
545 // These are disabled by default since Firefox 64.
546 try {
547 this.$document[ 0 ].execCommand( 'enableObjectResizing', false, false );
548 this.$document[ 0 ].execCommand( 'enableInlineTableEditing', false, false );
549 } catch ( e ) { /* Silently ignore */ }
550 }
551 this.emit( 'position' );
552 };
553
554 /**
555 * Set the read-only state of the surface
556 *
557 * @param {boolean} readOnly Make surface read-only
558 */
559 ve.ce.Surface.prototype.setReadOnly = function ( readOnly ) {
560 this.readOnly = !!readOnly;
561 this.$element.toggleClass( 've-ce-surface-readOnly', this.readOnly );
562 };
563
564 /**
565 * Check if the surface is read-only
566 *
567 * @return {boolean}
568 */
569 ve.ce.Surface.prototype.isReadOnly = function () {
570 return this.readOnly;
571 };
572
573 /**
574 * Set the review mode state of the surface
575 *
576 * In review mode the surface can't be interacted with by the user
577 * (unlike the read-only mode where the user can select text and
578 * inspect nodes).
579 *
580 * Review mode does not restrict changes to the model by other means,
581 * so programmatic changes can still be made from other tools.
582 *
583 * @param {boolean} reviewMode Set surface to review mode
584 * @param {ve.ce.Node[]} highlightNodes Nodes to highlight while in review mode
585 */
586 ve.ce.Surface.prototype.setReviewMode = function ( reviewMode, highlightNodes ) {
587 this.reviewMode = !!reviewMode;
588 this.$element.toggleClass( 've-ce-surface-reviewMode', this.reviewMode );
589 this.$element.toggleClass( 've-ce-surface-reviewMode-highlightNodes', this.reviewMode && !!highlightNodes );
590 if ( reviewMode && highlightNodes ) {
591 highlightNodes.forEach( ( node ) => {
592 node.$element
593 .addClass( 've-ce-surface-reviewMode-highlightNode' )
594 .parentsUntil( '.ve-ce-attachedRootNode' )
595 .addClass( 've-ce-surface-reviewMode-highlightNode' );
596
597 } );
598 } else {
599 this.$element.find( '.ve-ce-surface-reviewMode-highlightNode' )
600 .removeClass( 've-ce-surface-reviewMode-highlightNode' );
601 }
602 };
603
604 /**
605 * Give focus to the surface, reapplying the model selection, or selecting the first visible offset
606 * if the model selection is null.
607 *
608 * This is used when switching between surfaces, e.g. when closing a dialog window. Calling this
609 * function will also reapply the selection, even if the surface is already focused.
610 */
611 ve.ce.Surface.prototype.focus = function () {
612 if ( !this.attachedRoot.isLive() ) {
613 OO.ui.warnDeprecation( 'Tried to focus an un-initialized surface view. Wait for the ve.ui.Surface `ready` event to fire.' );
614 return;
615 }
616
617 let selection = this.getSelection();
618 if ( selection.getModel().isNull() ) {
619 this.selectFirstVisibleStartContentOffset();
620 selection = this.getSelection();
621 }
622
623 // Focus the contentEditable for text selections, or the pasteTarget for focusedNode selections
624 if ( selection.isFocusedNode() ) {
625 this.$pasteTarget[ 0 ].focus();
626 } else if ( selection.isNativeCursor() ) {
627 let nodeAndOffset;
628 try {
629 nodeAndOffset = this.getDocument().getNodeAndOffset( selection.getModel().getRange().start );
630 } catch ( e ) {
631 // Unexplained failures causing log spam: T262487
632 nodeAndOffset = null;
633 }
634 if ( nodeAndOffset ) {
635 $( nodeAndOffset.node ).closest( '[contenteditable=true]' )[ 0 ].focus();
636 }
637 }
638
639 // If we are calling focus after replacing a node the selection may be gone
640 // but onDocumentFocus won't fire so restore the selection here too.
641 this.onModelSelect();
642 // setTimeout: postpone until onDocumentFocus has been called
643 setTimeout( () => {
644 // Support: Chrome
645 // In some browsers (e.g. Chrome) giving the document node focus doesn't
646 // necessarily give you a selection (e.g. if the first child is a <figure>)
647 // so if the surface isn't 'focused' (has no selection) give it a selection
648 // manually
649 // TODO: rename isFocused and other methods to something which reflects
650 // the fact they actually mean "has a native selection"
651 if ( !this.isFocused() ) {
652 this.selectFirstVisibleStartContentOffset();
653 }
654 } );
655 // onDocumentFocus takes care of the rest
656 };
657
658 /**
659 * Blur the surface
660 */
661 ve.ce.Surface.prototype.blur = function () {
662 if ( this.deactivated ) {
663 // Clear the model selection, so activate doesn't trigger another de-activate
664 this.getModel().setNullSelection();
665 this.activate();
666 }
667 this.removeRangesAndBlur();
668 // This won't trigger focusin/focusout events, so trigger focus change manually
669 this.onFocusChange();
670 if ( OO.ui.isMobile() ) {
671 this.updateActiveAnnotations();
672 this.contexedAnnotations = [];
673 }
674 };
675
676 /**
677 * Remove all native selection ranges, and blur any active element
678 *
679 * This should hide all virtual keyboards when present.
680 */
681 ve.ce.Surface.prototype.removeRangesAndBlur = function () {
682 this.nativeSelection.removeAllRanges();
683 if ( this.getElementDocument().activeElement === this.$attachedRootNode[ 0 ] ) {
684 // Blurring the activeElement ensures the keyboard is hidden on iOS
685 this.getElementDocument().activeElement.blur();
686 }
687 };
688
689 /**
690 * Handler for focusin and focusout events. Filters events and debounces to #onFocusChange.
691 *
692 * @param {jQuery.Event} e focusin/out event
693 */
694 ve.ce.Surface.prototype.onDocumentFocusInOut = function () {
695 this.debounceFocusChange();
696 };
697
698 /**
699 * Handle global focus change.
700 */
701 ve.ce.Surface.prototype.onFocusChange = function () {
702 const surfaceNodes = [
703 this.$attachedRootNode[ 0 ],
704 this.$pasteTarget[ 0 ],
705 this.$highlights[ 0 ]
706 ];
707
708 const hasFocus = OO.ui.contains(
709 surfaceNodes,
710 this.nativeSelection.anchorNode,
711 true
712 ) && OO.ui.contains(
713 surfaceNodes,
714 document.activeElement,
715 true
716 );
717
718 if ( this.deactivated ) {
719 if ( OO.ui.contains( this.$attachedRootNode[ 0 ], this.nativeSelection.anchorNode, true ) ) {
720 this.onDocumentFocus();
721 }
722 } else {
723 if ( hasFocus && !this.isFocused() ) {
724 this.onDocumentFocus();
725 } else if ( !hasFocus && this.isFocused() ) {
726 this.onDocumentBlur();
727 } else if ( hasFocus && OO.ui.contains( this.$highlights[ 0 ], document.activeElement, true ) ) {
728 // Focus ended up in the higlight, e.g. by click on an already visible highlight.
729 // Move the cursor back to pasteTarget as we do when focusableNode initially selected.
730 // Without this, arrow key navigation from the focusable node would stop working.
731 this.preparePasteTargetForCopy();
732 }
733 }
734 };
735
736 /**
737 * Check if the surface is deactivated.
738 *
739 * @return {boolean} Surface is deactivated
740 */
741 ve.ce.Surface.prototype.isDeactivated = function () {
742 return this.deactivated;
743 };
744
745 /**
746 * Check if the surface is visibly deactivated.
747 *
748 * Only true if the surface was decativated by the user
749 * in a way that is expected to change the rendering.
750 *
751 * @return {boolean} Surface is visibly deactivated
752 */
753 ve.ce.Surface.prototype.isShownAsDeactivated = function () {
754 return this.deactivated && !this.showAsActivated;
755 };
756
757 /**
758 * Deactivate the surface, stopping the surface observer and replacing the native
759 * range with a fake rendered one.
760 *
761 * Used by dialogs so they can take focus without losing the original document selection.
762 *
763 * @param {boolean} [showAsActivated=true] Surface should still show as activated
764 * @param {boolean} [noSelectionChange] Don't change the native selection.
765 * @param {boolean} [hideSelection] Completely hide the selection
766 * @fires ve.ce.Surface#activation
767 */
768 ve.ce.Surface.prototype.deactivate = function ( showAsActivated, noSelectionChange, hideSelection ) {
769 this.showAsActivated = showAsActivated === undefined || !!showAsActivated;
770 this.hideSelection = hideSelection;
771 if ( !this.deactivated ) {
772 // Disable the surface observer, there can be no observable changes
773 // until the surface is activated
774 this.surfaceObserver.disable();
775 this.deactivated = true;
776 this.previousActiveAnnotations = this.activeAnnotations;
777 this.findAndExecuteDelayedSequences();
778 this.$element.addClass( 've-ce-surface-deactivated' );
779 // Remove ranges so the user can't accidentally type into the document,
780 // and so virtual keyboards are hidden.
781 if ( !noSelectionChange ) {
782 this.removeRangesAndBlur();
783 // iOS Safari will sometimes restore the selection immediately (T293661)
784 setTimeout( () => {
785 if (
786 // Surface may have been immediately re-activated deliberately
787 this.deactivated &&
788 OO.ui.contains( this.$attachedRootNode[ 0 ], this.nativeSelection.anchorNode, true )
789 ) {
790 this.removeRangesAndBlur();
791 }
792 } );
793 }
794 this.updateDeactivatedSelection();
795 this.clearKeyDownState();
796 this.emit( 'activation' );
797 }
798 };
799
800 /**
801 * Reactivate the surface and restore the native selection
802 *
803 * @fires ve.ce.Surface#activation
804 * @fires ve.dm.Surface#contextChange
805 */
806 ve.ce.Surface.prototype.activate = function () {
807 if ( this.deactivated ) {
808 this.deactivated = false;
809 this.showAsActivated = false;
810 this.hideSelection = false;
811 this.updateDeactivatedSelection();
812 this.surfaceObserver.enable();
813 this.$element.removeClass( 've-ce-surface-deactivated' );
814 if ( OO.ui.isMobile() ) {
815 // Activating triggers a context hide on mobile
816 this.model.emit( 'contextChange' );
817 }
818
819 const previousSelection = this.getModel().getSelection();
820
821 if ( OO.ui.contains( this.$attachedRootNode[ 0 ], this.nativeSelection.anchorNode, true ) ) {
822 // The selection has been placed back in the document, either by the user clicking
823 // or by the closing window updating the model. Poll in case it was the user clicking.
824 this.surfaceObserver.clear();
825 this.surfaceObserver.pollOnce();
826 } else {
827 // Clear focused node so onModelSelect re-selects it if necessary
828 this.focusedNode = null;
829 this.onModelSelect();
830 }
831
832 const newSelection = this.getModel().getSelection();
833
834 if (
835 previousSelection.getCoveringRange() &&
836 newSelection.getCoveringRange() &&
837 previousSelection.getCoveringRange().containsRange(
838 newSelection.getCoveringRange()
839 )
840 ) {
841 // If the user reactivates by clicking on their previous selection, use that selection.
842 this.getModel().setSelection( previousSelection );
843 // Restore active annotations
844 if ( this.previousActiveAnnotations.length ) {
845 const annotationClasses = this.previousActiveAnnotations.map( ( ann ) => ann.constructor );
846 this.selectAnnotation( ( view ) => ve.isInstanceOfAny( view, annotationClasses ) );
847 }
848 }
849
850 this.emit( 'activation' );
851 }
852 };
853
854 /**
855 * Update the fake selection while the surface is deactivated.
856 *
857 * While the surface is deactivated, all calls to showModelSelection will get redirected here.
858 */
859 ve.ce.Surface.prototype.updateDeactivatedSelection = function () {
860 const selection = this.getSelection();
861
862 // Check we have a deactivated surface and a native selection
863 if ( this.deactivated && selection.isNativeCursor() && !this.hideSelection ) {
864 let textColor;
865 // For collapsed selections, work out the text color to use for the cursor
866 const isCollapsed = selection.getModel().isCollapsed();
867 if ( isCollapsed ) {
868 const currentNode = this.getDocument().getBranchNodeFromOffset(
869 selection.getModel().getCoveringRange().start
870 );
871 if ( currentNode ) {
872 // This isn't perfect as it doesn't take into account annotations.
873 textColor = currentNode.$element.css( 'color' );
874 }
875 }
876 const classes = [];
877 if ( this.isShownAsDeactivated() ) {
878 classes.push( 've-ce-surface-selections-deactivated-showAsDeactivated' );
879 }
880 if ( isCollapsed ) {
881 classes.push( 've-ce-surface-selections-deactivated-collapsed' );
882 }
883 // Generates ve-ce-surface-selections-deactivated CSS class
884 this.drawSelections( 'deactivated', [ selection ], {
885 color: textColor,
886 wrapperClass: classes.join( ' ' )
887 } );
888 } else {
889 // Generates ve-ce-surface-selections-deactivated CSS class
890 this.drawSelections( 'deactivated', [] );
891 }
892 };
893
894 /**
895 * Check if the surface has a native cursor selection
896 *
897 * On mobile platforms, this means it is likely the virtual
898 * keyboard is visible.
899 *
900 * @return {boolean} Surface has a native cursor selection
901 */
902 ve.ce.Surface.prototype.hasNativeCursorSelection = function () {
903 return !this.isDeactivated() && this.getSelection().isNativeCursor();
904 };
905
906 /**
907 * Draw selections.
908 *
909 * @param {string} name Unique name for the selection being drawn
910 * @param {ve.ce.Selection[]} selections Selections to draw
911 * @param {Object} [options]
912 * @param {string} options.color CSS color for the selection. Should usually
913 * be set in a stylesheet using the generated class name.
914 * @param {string} options.wrapperClass Additional CSS class string to add to the $selections wrapper.
915 * mapped to the same index.
916 * @param {string} options.label Label shown above each selection
917 */
918 ve.ce.Surface.prototype.drawSelections = function ( name, selections, options ) {
919 options = options || {};
920
921 if ( !Object.prototype.hasOwnProperty.call( this.drawnSelections, name ) ) {
922 this.drawnSelections[ name ] = {};
923 }
924 const drawnSelection = this.drawnSelections[ name ];
925
926 drawnSelection.$selections = drawnSelection.$selections ||
927 // The following classes are used here:
928 // * ve-ce-surface-selections-deactived
929 // * ve-ce-surface-selections-<name>
930 $( '<div>' ).addClass( 've-ce-surface-selections ve-ce-surface-selections-' + name ).appendTo( this.surface.$selections );
931
932 const oldSelections = drawnSelection.selections || [];
933 const oldOptions = drawnSelection.options || {};
934
935 drawnSelection.selections = selections;
936 drawnSelection.options = options;
937
938 // Always set the 'class' attribute to ensure previously-set classes are cleared.
939 drawnSelection.$selections.attr(
940 'class',
941 've-ce-surface-selections ve-ce-surface-selections-' + name + ' ' +
942 ( options.wrapperClass || '' )
943 );
944
945 const selectionsJustShown = {};
946 selections.forEach( ( selection ) => {
947 let $selection = this.getDrawnSelection( name, selection.getModel(), options );
948 if ( !$selection ) {
949 let rects = selection.getSelectionRects();
950 if ( !rects ) {
951 return;
952 }
953 rects = ve.minimizeRects( rects );
954 $selection = $( '<div>' ).addClass( 've-ce-surface-selection' );
955 rects.forEach( ( rect ) => {
956 const $rect = $( '<div>' ).css( {
957 top: rect.top,
958 left: rect.left,
959 // Collapsed selections can have a width of 0, so expand
960 width: Math.max( rect.width, 1 ),
961 height: rect.height
962 } );
963 $selection.append( $rect );
964 if ( options.color ) {
965 $rect.css( 'background-color', options.color );
966 }
967 } );
968
969 if ( options.label ) {
970 const boundingRect = selection.getSelectionBoundingRect();
971 $selection.append(
972 $( '<div>' )
973 .addClass( 've-ce-surface-selection-label' )
974 .text( options.label )
975 .css( {
976 top: boundingRect.top,
977 left: boundingRect.left,
978 'background-color': options.color || ''
979 } )
980 );
981 }
982 }
983 if ( !$selection.parent().length ) {
984 drawnSelection.$selections.append( $selection );
985 }
986 const cacheKey = this.storeDrawnSelection( $selection, name, selection.getModel(), options );
987 selectionsJustShown[ cacheKey ] = true;
988 } );
989
990 // Remove any selections that were not in the latest list of selections
991 oldSelections.forEach( ( oldSelection ) => {
992 const cacheKey = this.getDrawnSelectionCacheKey( name, oldSelection.getModel(), oldOptions );
993 if ( !selectionsJustShown[ cacheKey ] ) {
994 const $oldSelection = this.getDrawnSelection( name, oldSelection.getModel(), oldOptions );
995 if ( $oldSelection ) {
996 $oldSelection.detach();
997 }
998 }
999 } );
1000 };
1001
1002 /**
1003 * Get a cache key for a drawn selection
1004 *
1005 * @param {string} name Name of selection group
1006 * @param {ve.dm.Selection} selection Selection model
1007 * @param {Object} [options] Selection options
1008 * @return {string} Cache key
1009 */
1010 ve.ce.Surface.prototype.getDrawnSelectionCacheKey = function ( name, selection, options ) {
1011 options = options || {};
1012 return name + '-' + JSON.stringify( selection ) + '-' + ( options.color || '' ) + '-' + ( options.label || '' );
1013 };
1014
1015 /**
1016 * Get an already drawn selection from the cache
1017 *
1018 * @param {string} name Name of selection group
1019 * @param {ve.dm.Selection} selection Selection model
1020 * @param {Object} [options] Selection options
1021 * @return {jQuery} Drawn selection
1022 */
1023 ve.ce.Surface.prototype.getDrawnSelection = function ( name, selection, options ) {
1024 const cacheKey = this.getDrawnSelectionCacheKey( name, selection, options );
1025 return Object.prototype.hasOwnProperty.call( this.drawnSelectionCache, cacheKey ) ? this.drawnSelectionCache[ cacheKey ] : null;
1026 };
1027
1028 /**
1029 * Store an already drawn selection in the cache
1030 *
1031 * @param {jQuery} $selection Drawn selection
1032 * @param {string} name Name of selection group
1033 * @param {ve.dm.Selection} selection Selection model
1034 * @param {Object} [options] Selection options
1035 * @return {string} Cache key
1036 */
1037 ve.ce.Surface.prototype.storeDrawnSelection = function ( $selection, name, selection, options ) {
1038 const cacheKey = this.getDrawnSelectionCacheKey( name, selection, options );
1039 this.drawnSelectionCache[ cacheKey ] = $selection;
1040 return cacheKey;
1041 };
1042
1043 /**
1044 * Redraw selections
1045 *
1046 * This is triggered by a surface 'position' event, which fires when the surface
1047 * changes size, or when the document is modified. The drawnSelectionCache is
1048 * cleared as these two things will cause any previously calculated rectangles
1049 * to be incorrect.
1050 */
1051 ve.ce.Surface.prototype.redrawSelections = function () {
1052 Object.keys( this.drawnSelections ).forEach( ( name ) => {
1053 const drawnSelection = this.drawnSelections[ name ];
1054 drawnSelection.$selections.empty();
1055 } );
1056
1057 this.drawnSelectionCache = {};
1058 Object.keys( this.drawnSelections ).forEach( ( name ) => {
1059 const drawnSelection = this.drawnSelections[ name ];
1060 this.drawSelections( name, drawnSelection.selections, drawnSelection.options );
1061 } );
1062 };
1063
1064 /**
1065 * Handle document focus events.
1066 *
1067 * This is triggered by a global focusin/focusout event noticing a selection on the document.
1068 *
1069 * @fires ve.ce.Surface#focus
1070 */
1071 ve.ce.Surface.prototype.onDocumentFocus = function () {
1072 if ( this.getModel().getSelection().isNull() ) {
1073 // If the document is being focused by a non-mouse/non-touch user event,
1074 // find the first content offset and place the cursor there.
1075 this.selectFirstVisibleStartContentOffset();
1076 }
1077 this.eventSequencer.attach( this.$element );
1078 this.surfaceObserver.startTimerLoop();
1079 this.focused = true;
1080 this.activate();
1081 this.$element.addClass( 've-ce-surface-focused' );
1082 this.emit( 'focus' );
1083 };
1084
1085 /**
1086 * Handle document blur events.
1087 *
1088 * This is triggered by a global focusin/focusout event noticing no selection on the document.
1089 *
1090 * @fires ve.ce.Surface#blur
1091 */
1092 ve.ce.Surface.prototype.onDocumentBlur = function () {
1093 const nullSelectionOnBlur = this.surface.nullSelectionOnBlur;
1094 if ( !nullSelectionOnBlur ) {
1095 // Set noSelectionChange as we already know the selection has left
1096 // the document and we don't want #deactivate to move it again.
1097 this.deactivate( false, true );
1098 }
1099 this.eventSequencer.detach();
1100 this.surfaceObserver.stopTimerLoop();
1101 this.surfaceObserver.pollOnce();
1102 this.surfaceObserver.clear();
1103 // Setting focused to false blocks selection change handler, so fire one last time here
1104 this.onDocumentSelectionChange();
1105 this.setDragging( false );
1106 this.focused = false;
1107 if ( nullSelectionOnBlur ) {
1108 if ( this.focusedNode ) {
1109 this.focusedNode.setFocused( false );
1110 this.focusedNode = null;
1111 }
1112 this.getModel().setNullSelection();
1113 }
1114 this.$element.removeClass( 've-ce-surface-focused' );
1115 this.emit( 'blur' );
1116 };
1117
1118 /**
1119 * Check if surface is focused.
1120 *
1121 * @return {boolean} Surface is focused
1122 */
1123 ve.ce.Surface.prototype.isFocused = function () {
1124 return this.focused;
1125 };
1126
1127 /**
1128 * Handle document mouse down events.
1129 *
1130 * @param {jQuery.Event} e Mouse down event
1131 */
1132 ve.ce.Surface.prototype.onDocumentMouseDown = function ( e ) {
1133 if ( e.which !== OO.ui.MouseButtons.LEFT ) {
1134 if ( e.which === OO.ui.MouseButtons.MIDDLE ) {
1135 // When middle click is also focusig the document, the selection may not end up
1136 // where you clicked, so record the offset from the click coordinates. (T311733)
1137 let targetOffset = -1;
1138 if ( this.getModel().getSelection().isNull() ) {
1139 targetOffset = this.getOffsetFromEventCoords( e );
1140 }
1141 this.middleClickTargetOffset = targetOffset !== -1 ? targetOffset : null;
1142 this.middleClickPasting = true;
1143 this.$document.one( 'mouseup', () => {
1144 // Stay true until other events have run, e.g. paste
1145 setTimeout( () => {
1146 this.middleClickPasting = false;
1147 } );
1148 } );
1149 }
1150 return;
1151 }
1152
1153 const offset = this.getOffsetFromEventCoords( e );
1154 if ( offset !== -1 ) {
1155 const contexedAnnotations = this.annotationsAtNode(
1156 e.target,
1157 ( view ) => this.surface.context.getRelatedSourcesFromModels( [ view.model ] ).length
1158 );
1159 if (
1160 OO.ui.isMobile() &&
1161 // The user has clicked on contexed annotations and ...
1162 contexedAnnotations.length && (
1163 // ... was previously on a focusable node or ...
1164 this.focusedNode ||
1165 // ... previously had different annotations selected ...
1166 !(
1167 // Shallow strict equality check
1168 this.contexedAnnotations.length === contexedAnnotations.length &&
1169 this.contexedAnnotations.every( ( ann, i ) => ann === contexedAnnotations[ i ] )
1170 )
1171 )
1172 ) {
1173 const node = e.target;
1174 setTimeout( () => {
1175 this.getModel().setLinearSelection( new ve.Range( offset ) );
1176 // HACK: Re-activate flag so selection is repositioned
1177 this.activate();
1178 this.deactivate( false, false, true );
1179 this.updateActiveAnnotations( node );
1180 } );
1181 this.contexedAnnotations = contexedAnnotations;
1182 e.preventDefault();
1183 return;
1184 }
1185 this.contexedAnnotations = contexedAnnotations;
1186 }
1187
1188 // Remember the mouse is down
1189 this.setDragging( true );
1190
1191 // Bind mouseup to the whole document in case of dragging out of the surface
1192 this.$document.on( 'mouseup', this.onDocumentMouseUpHandler );
1193
1194 this.surfaceObserver.stopTimerLoop();
1195 // setTimeout: In some browsers the selection doesn't change until after the event
1196 // so poll in the 'after' function.
1197 // TODO: rewrite to use EventSequencer
1198 setTimeout( this.afterDocumentMouseDown.bind( this, e, this.getSelection() ) );
1199
1200 // Handle triple click
1201 if ( e.originalEvent.detail >= 3 ) {
1202 // Browser default behaviour for triple click won't behave as we want
1203 e.preventDefault();
1204
1205 const newFragment = this.getModel().getFragment()
1206 // After double-clicking in an inline slug, we'll get a selection like
1207 // <p><span><img />|</span></p><p>|Foo</p>. This selection spans a CBN boundary,
1208 // so we can't expand to the nearest CBN. To handle this case and other possible
1209 // cases where the selection spans a CBN boundary, collapse the selection before
1210 // expanding it. If the selection is entirely within the same CBN as it should be,
1211 // this won't change the result.
1212 .collapseToStart()
1213 // Cover the CBN we're in
1214 .expandLinearSelection( 'closest', ve.dm.ContentBranchNode )
1215 // …but that covered the entire CBN, we only want the contents
1216 .adjustLinearSelection( 1, -1 );
1217 // If something weird happened (e.g. no CBN found), newFragment will be null.
1218 // Don't select it in that case, because that'll blur the surface.
1219 if ( !newFragment.isNull() ) {
1220 newFragment.select();
1221 }
1222 }
1223 };
1224
1225 /**
1226 * Deferred until after document mouse down
1227 *
1228 * @param {jQuery.Event} e Mouse down event
1229 * @param {ve.ce.Selection} selectionBefore Selection before the mouse event
1230 */
1231 ve.ce.Surface.prototype.afterDocumentMouseDown = function ( e, selectionBefore ) {
1232 // TODO: guard with incRenderLock?
1233 this.surfaceObserver.pollOnce();
1234 if ( e.shiftKey ) {
1235 this.fixShiftClickSelect( selectionBefore );
1236 }
1237 };
1238
1239 /**
1240 * Handle document mouse up events.
1241 *
1242 * @param {jQuery.Event} e Mouse up event
1243 */
1244 ve.ce.Surface.prototype.onDocumentMouseUp = function ( e ) {
1245 this.$document.off( 'mouseup', this.onDocumentMouseUpHandler );
1246 this.surfaceObserver.startTimerLoop();
1247 // setTimeout: In some browsers the selection doesn't change until after the event
1248 // so poll in the 'after' function
1249 // TODO: rewrite to use EventSequencer
1250 setTimeout( this.afterDocumentMouseUp.bind( this, e, this.getSelection() ) );
1251 };
1252
1253 /**
1254 * Deferred until after document mouse up
1255 *
1256 * @param {jQuery.Event} e Mouse up event
1257 * @param {ve.ce.Selection} selectionBefore Selection before the mouse event
1258 */
1259 ve.ce.Surface.prototype.afterDocumentMouseUp = function ( e, selectionBefore ) {
1260 // TODO: guard with incRenderLock?
1261 this.surfaceObserver.pollOnce();
1262 if ( e.shiftKey ) {
1263 this.fixShiftClickSelect( selectionBefore );
1264 }
1265 this.setDragging( false );
1266 };
1267
1268 /**
1269 * Fix shift-click selection
1270 *
1271 * Support: Chrome
1272 * When shift-clicking on links Chrome tries to collapse the selection
1273 * so check for this and fix manually.
1274 *
1275 * This can occur on mousedown or, if the existing selection covers the
1276 * link, on mouseup.
1277 *
1278 * https://code.google.com/p/chromium/issues/detail?id=345745
1279 *
1280 * @param {ve.ce.Selection} selectionBefore Selection before the mouse event
1281 */
1282 ve.ce.Surface.prototype.fixShiftClickSelect = function ( selectionBefore ) {
1283 if ( !selectionBefore.isNativeCursor() ) {
1284 return;
1285 }
1286 const newSelection = this.getSelection();
1287 if ( newSelection.getModel().isCollapsed() && !newSelection.equals( selectionBefore ) ) {
1288 this.getModel().setLinearSelection(
1289 new ve.Range(
1290 selectionBefore.getModel().getRange().from,
1291 newSelection.getModel().getRange().to
1292 )
1293 );
1294 }
1295 };
1296
1297 /**
1298 * Set a flag when the user is dragging a selection
1299 *
1300 * @param {boolean} dragging Dragging (mouse is down)
1301 */
1302 ve.ce.Surface.prototype.setDragging = function ( dragging ) {
1303 this.dragging = !!dragging;
1304 // Class can be used to suppress hover states, such as branch slugs.
1305 this.$element.toggleClass( 've-ce-surface-dragging', this.dragging );
1306 };
1307
1308 /**
1309 * Handle document selection change events.
1310 *
1311 * @param {jQuery.Event} e Selection change event
1312 */
1313 ve.ce.Surface.prototype.onDocumentSelectionChange = function () {
1314 const selection = this.getModel().getSelection();
1315 if (
1316 // There is a non-empty selection in the VE surface. Use this if middle-click-to-paste is triggered later.
1317 !selection.isCollapsed() ||
1318 // There is no surface selection, and a native selection has been made elsewhere.
1319 // Null the lastNonCollapsedDocumentSelection so native middle-click-to-paste happens instead.
1320 ( selection.isNull() && this.nativeSelection.rangeCount && !this.nativeSelection.getRangeAt( 0 ).collapsed )
1321 ) {
1322 this.lastNonCollapsedDocumentSelection = selection;
1323 }
1324
1325 // selectionChange events are only emitted from window.document, so ignore
1326 // any events which are fired when the document is blurred or deactivated.
1327 if ( !this.focused || this.deactivated ) {
1328 return;
1329 }
1330 this.fixupCursorPosition( 0, this.dragging );
1331 this.updateActiveAnnotations();
1332 this.surfaceObserver.pollOnceSelection();
1333 };
1334
1335 /**
1336 * Handle document drag start events.
1337 *
1338 * @param {jQuery.Event} e Drag start event
1339 * @fires ve.ce.Surface#relocationStart
1340 */
1341 ve.ce.Surface.prototype.onDocumentDragStart = function ( e ) {
1342 this.onCopy( e );
1343 this.startRelocation();
1344 };
1345
1346 /**
1347 * Handle document drag over events.
1348 *
1349 * @param {jQuery.Event} e Drag over event
1350 */
1351 ve.ce.Surface.prototype.onDocumentDragOver = function ( e ) {
1352 const dataTransferHandlerFactory = this.getSurface().dataTransferHandlerFactory,
1353 dataTransfer = e.originalEvent.dataTransfer;
1354 let isContent = true;
1355
1356 if ( this.readOnly ) {
1357 return;
1358 }
1359
1360 let nodeType;
1361 if ( this.relocatingNode ) {
1362 isContent = this.relocatingNode.isContent();
1363 nodeType = this.relocatingNode.getType();
1364 } else {
1365 if ( this.allowedFile === null ) {
1366 this.allowedFile = false;
1367 // If we can get file metadata, check if there is a DataTransferHandler registered
1368 // to handle it.
1369 if ( dataTransfer.items ) {
1370 for ( let i = 0, l = dataTransfer.items.length; i < l; i++ ) {
1371 const item = dataTransfer.items[ i ];
1372 if ( item.kind !== 'string' ) {
1373 const fakeItem = new ve.ui.DataTransferItem( item.kind, item.type );
1374 if ( dataTransferHandlerFactory.getHandlerNameForItem( fakeItem ) ) {
1375 this.allowedFile = true;
1376 break;
1377 }
1378 }
1379 }
1380 } else if ( dataTransfer.files ) {
1381 for ( let i = 0, l = dataTransfer.files.length; i < l; i++ ) {
1382 const item = dataTransfer.items[ i ];
1383 const fakeItem = new ve.ui.DataTransferItem( item.kind, item.type );
1384 if ( dataTransferHandlerFactory.getHandlerNameForItem( fakeItem ) ) {
1385 this.allowedFile = true;
1386 break;
1387 }
1388 }
1389 } else if ( Array.prototype.indexOf.call( dataTransfer.types || [], 'Files' ) !== -1 ) {
1390 // Support: Firefox
1391 // If we have no metadata (e.g. in Firefox) assume it is droppable
1392 this.allowedFile = true;
1393 }
1394 }
1395 // this.allowedFile is cached until the next dragleave event
1396 if ( this.allowedFile ) {
1397 isContent = false;
1398 nodeType = 'alienBlock';
1399 }
1400 }
1401
1402 function getNearestDropTarget( node ) {
1403 while ( node.parent && !node.parent.isAllowedChildNodeType( nodeType ) ) {
1404 node = node.parent;
1405 }
1406 if ( node.parent ) {
1407 node.parent.traverseUpstream( ( n ) => {
1408 if ( n.shouldIgnoreChildren() ) {
1409 node = null;
1410 return false;
1411 }
1412 } );
1413 return node;
1414 }
1415 }
1416
1417 if ( !isContent ) {
1418 e.preventDefault();
1419 const $target = $( e.target ).closest( '.ve-ce-branchNode, .ve-ce-leafNode' );
1420 let $dropTarget;
1421 let dropPosition;
1422 if ( $target.length ) {
1423 // Find the nearest node which will accept this node type
1424 let dropTargetNode = getNearestDropTarget( $target.data( 'view' ) );
1425 if ( dropTargetNode ) {
1426 $dropTarget = dropTargetNode.$element;
1427 dropPosition = e.originalEvent.pageY - $dropTarget.offset().top > $dropTarget.outerHeight() / 2 ? 'bottom' : 'top';
1428 } else {
1429 const targetOffset = this.getOffsetFromEventCoords( e.originalEvent );
1430 if ( targetOffset !== -1 ) {
1431 dropTargetNode = getNearestDropTarget( this.getDocument().getBranchNodeFromOffset( targetOffset ) );
1432 if ( dropTargetNode ) {
1433 $dropTarget = dropTargetNode.$element;
1434 dropPosition = 'top';
1435 }
1436 }
1437 if ( !$dropTarget ) {
1438 $dropTarget = this.$lastDropTarget;
1439 dropPosition = this.lastDropPosition;
1440 }
1441 }
1442 }
1443 if ( this.$lastDropTarget && (
1444 !this.$lastDropTarget.is( $dropTarget ) || dropPosition !== this.lastDropPosition
1445 ) ) {
1446 this.$dropMarker.addClass( 'oo-ui-element-hidden' );
1447 $dropTarget = null;
1448 }
1449 if ( $dropTarget && (
1450 !$dropTarget.is( this.$lastDropTarget ) || dropPosition !== this.lastDropPosition
1451 ) ) {
1452 const targetPosition = $dropTarget.position();
1453 // Go beyond margins as they can overlap
1454 let top = targetPosition.top + parseFloat( $dropTarget.css( 'margin-top' ) );
1455 const left = targetPosition.left + parseFloat( $dropTarget.css( 'margin-left' ) );
1456 if ( dropPosition === 'bottom' ) {
1457 top += $dropTarget.outerHeight();
1458 }
1459 this.$dropMarker
1460 .css( {
1461 top: top,
1462 left: left
1463 } )
1464 .width( $dropTarget.outerWidth() )
1465 .removeClass( 'oo-ui-element-hidden' );
1466 }
1467 if ( $dropTarget !== undefined ) {
1468 this.$lastDropTarget = $dropTarget;
1469 this.lastDropPosition = dropPosition;
1470 }
1471 }
1472 };
1473
1474 /**
1475 * Handle document drag leave events.
1476 *
1477 * @param {jQuery.Event} e Drag leave event
1478 */
1479 ve.ce.Surface.prototype.onDocumentDragLeave = function () {
1480 this.allowedFile = null;
1481 if ( this.$lastDropTarget ) {
1482 this.$dropMarker.addClass( 'oo-ui-element-hidden' );
1483 this.$lastDropTarget = null;
1484 this.lastDropPosition = null;
1485 }
1486 };
1487
1488 /**
1489 * Handle document drop events.
1490 *
1491 * Limits native drag and drop behaviour.
1492 *
1493 * @param {jQuery.Event} e Drop event
1494 * @fires ve.ce.Surface#relocationEnd
1495 */
1496 ve.ce.Surface.prototype.onDocumentDrop = function ( e ) {
1497 // Properties may be nullified by other events, so cache before setTimeout
1498 const surfaceModel = this.getModel(),
1499 dataTransfer = e.originalEvent.dataTransfer,
1500 $dropTarget = this.$lastDropTarget,
1501 dropPosition = this.lastDropPosition,
1502 platformKey = ve.getSystemPlatform() === 'mac' ? 'mac' : 'pc';
1503
1504 // Prevent native drop event from modifying view
1505 e.preventDefault();
1506
1507 if ( this.readOnly ) {
1508 return;
1509 }
1510
1511 let targetOffset;
1512 // Determine drop position
1513 if ( $dropTarget ) {
1514 // Block level drag and drop: use the lastDropTarget to get the targetOffset
1515 if ( $dropTarget ) {
1516 const targetRange = $dropTarget.data( 'view' ).getModel().getOuterRange();
1517 if ( dropPosition === 'top' ) {
1518 targetOffset = targetRange.start;
1519 } else {
1520 targetOffset = targetRange.end;
1521 }
1522 } else {
1523 return;
1524 }
1525 } else {
1526 targetOffset = this.getOffsetFromEventCoords( e.originalEvent );
1527 if ( targetOffset === -1 ) {
1528 return;
1529 }
1530 }
1531 const targetFragment = surfaceModel.getLinearFragment( new ve.Range( targetOffset ) );
1532
1533 const targetViewNode = this.getDocument().getBranchNodeFromOffset(
1534 targetFragment.getSelection().getCoveringRange().from
1535 );
1536 // TODO: Support sanitized drop on a single line node (removing line breaks)
1537 const isMultiline = targetViewNode.isMultiline();
1538
1539 // Internal drop
1540 if ( this.relocatingSelection ) {
1541 // Get a fragment and data of the node being dragged
1542 const originFragment = surfaceModel.getFragment( this.relocatingSelection );
1543 let originData;
1544 if ( !isMultiline ) {
1545 // Data needs to be balanced to be sanitized
1546 const slice = this.model.documentModel.shallowCloneFromRange( originFragment.getSelection().getCoveringRange() );
1547 const linearData = new ve.dm.ElementLinearData(
1548 originFragment.getDocument().getStore(),
1549 slice.getBalancedData()
1550 );
1551 linearData.sanitize( { singleLine: true } );
1552 originData = linearData.data;
1553 // Unwrap CBN
1554 if ( originData[ 0 ].type && ve.dm.nodeFactory.canNodeContainContent( originData[ 0 ].type ) ) {
1555 originData = originData.slice( 1, originData.length - 1 );
1556 }
1557 } else {
1558 originData = originFragment.getData();
1559 }
1560
1561 // Start staging so we can abort in the catch later
1562 surfaceModel.pushStaging();
1563
1564 // Dragging performs cut-and-paste by default (remove content from old location).
1565 // If Ctrl on PC, or Opt (alt) on Mac, is held, it performs copy-and-paste instead.
1566 if ( ( platformKey === 'pc' && !e.ctrlKey ) || ( platformKey === 'mac' && !e.altKey ) ) {
1567 originFragment.removeContent();
1568 }
1569
1570 try {
1571 // Re-insert data at new location
1572 targetFragment.insertContent( originData );
1573 surfaceModel.applyStaging();
1574 } catch ( error ) {
1575 // Insert content may throw an exception if it can't find a way
1576 // to fixup the insertion sensibly
1577 surfaceModel.popStaging();
1578 }
1579
1580 } else {
1581 // External drop
1582 // TODO: Support sanitized external drop into single line contexts
1583 if ( isMultiline ) {
1584 this.handleDataTransfer( dataTransfer, false, targetFragment );
1585 }
1586 }
1587 this.endRelocation();
1588 };
1589
1590 /**
1591 * Handle document key down events.
1592 *
1593 * @param {jQuery.Event} e Key down event
1594 */
1595 ve.ce.Surface.prototype.onDocumentKeyDown = function ( e ) {
1596 const selection = this.getModel().getSelection();
1597 let updateFromModel = false;
1598
1599 if ( selection.isNull() ) {
1600 return;
1601 }
1602
1603 if ( e.which === 229 ) {
1604 // Support: Chrome
1605 // Ignore fake IME events (emitted in Chrome)
1606 return;
1607 }
1608
1609 this.surfaceObserver.stopTimerLoop();
1610 this.incRenderLock();
1611 try {
1612 // TODO: is this correct?
1613 this.surfaceObserver.pollOnce();
1614 } finally {
1615 this.decRenderLock();
1616 }
1617
1618 this.storeKeyDownState( e );
1619
1620 if ( ve.ce.keyDownHandlerFactory.executeHandlersForKey( e.keyCode, selection.getName(), this, e ) ) {
1621 updateFromModel = true;
1622 } else {
1623 const trigger = new ve.ui.Trigger( e );
1624 if ( trigger.isComplete() ) {
1625 const executed = this.surface.executeWithSource( trigger, false, 'trigger' );
1626 if ( executed || this.isBlockedTrigger( trigger ) ) {
1627 e.preventDefault();
1628 e.stopPropagation();
1629 updateFromModel = true;
1630 }
1631 }
1632 }
1633
1634 if (
1635 !e.isDefaultPrevented() &&
1636 e.keyCode === OO.ui.Keys.TAB &&
1637 // Not modified (excluding shift)
1638 !( e.metaKey || e.ctrlKey || e.altKey )
1639 ) {
1640 // Manually move focus to the next/previous focusable element (T341687)
1641 const surfaceNode = this.$element[ 0 ];
1642 const treeWalker = document.createTreeWalker(
1643 document.body,
1644 NodeFilter.SHOW_ELEMENT,
1645 ( n ) => {
1646 if ( surfaceNode.contains( n ) ) {
1647 return NodeFilter.FILTER_REJECT;
1648 }
1649 if ( OO.ui.isFocusableElement( $( n ) ) ) {
1650 return NodeFilter.FILTER_ACCEPT;
1651 }
1652 return NodeFilter.FILTER_SKIP;
1653 }
1654 );
1655 treeWalker.currentNode = surfaceNode;
1656 if ( e.shiftKey ) {
1657 treeWalker.previousNode();
1658 } else {
1659 treeWalker.nextNode();
1660 }
1661 if ( treeWalker.currentNode ) {
1662 treeWalker.currentNode.focus();
1663 e.preventDefault();
1664 e.stopPropagation();
1665 return;
1666 }
1667 }
1668
1669 if (
1670 this.readOnly && !(
1671 // Allowed keystrokes in readonly mode:
1672 // Arrows, simple navigation
1673 ve.ce.LinearArrowKeyDownHandler.static.keys.indexOf( e.keyCode ) !== -1 ||
1674 // Potential commands:
1675 // Function keys...
1676 ( e.keyCode >= 112 && e.keyCode <= 123 ) ||
1677 // ... or anything modified (e.g. copy / select-all), excluding shift
1678 e.metaKey || e.ctrlKey || e.altKey
1679 // Keys already handled in keyDownHandlers above do not need to be exempt here
1680 )
1681 ) {
1682 e.preventDefault();
1683 e.stopPropagation();
1684 return;
1685 }
1686
1687 if ( !updateFromModel ) {
1688 this.incRenderLock();
1689 }
1690 try {
1691 this.surfaceObserver.pollOnce();
1692 } finally {
1693 if ( !updateFromModel ) {
1694 this.decRenderLock();
1695 }
1696 }
1697 this.surfaceObserver.startTimerLoop();
1698 };
1699
1700 /**
1701 * Check if a trigger event is blocked from performing its default behaviour
1702 *
1703 * If any of these triggers can't execute on the surface, (e.g. the underline
1704 * command has been disabled), we should still preventDefault so ContentEditable
1705 * native commands don't occur, leaving the view out of sync with the model.
1706 *
1707 * @param {ve.ui.Trigger} trigger Trigger to check
1708 * @return {boolean} Trigger should preventDefault
1709 */
1710 ve.ce.Surface.prototype.isBlockedTrigger = function ( trigger ) {
1711 const triggerString = trigger.toString(),
1712 platformKey = ve.getSystemPlatform() === 'mac' ? 'mac' : 'pc',
1713 blockedIfRegisteredTriggers = [ 'tab', 'shift+tab' ],
1714 blockedTriggers = {
1715 mac: [ 'cmd+b', 'cmd+i', 'cmd+u', 'cmd+z', 'cmd+y', 'cmd+shift+z', 'cmd+[', 'cmd+]' ],
1716 pc: [ 'ctrl+b', 'ctrl+i', 'ctrl+u', 'ctrl+z', 'ctrl+y', 'ctrl+shift+z' ]
1717 };
1718
1719 // Special case: only block Tab/Shift+Tab if indentation commands are enabled on this surface,
1720 // otherwise allow them to change focus
1721 if ( blockedIfRegisteredTriggers.indexOf( triggerString ) !== -1 ) {
1722 return !!this.surface.triggerListener.getCommandByTrigger( triggerString );
1723 }
1724
1725 return blockedTriggers[ platformKey ].indexOf( triggerString ) !== -1;
1726 };
1727
1728 /**
1729 * Handle document key press events.
1730 *
1731 * @param {jQuery.Event} e Key press event
1732 */
1733 ve.ce.Surface.prototype.onDocumentKeyPress = function ( e ) {
1734 let selection;
1735
1736 // Handle the case where keyPress Enter is fired without a matching keyDown. This can
1737 // happen with OS X Romanising Korean IMEs on Firefox, when pressing Enter with
1738 // uncommitted candidate text; see T120156. Behave as though keyDown Enter has been
1739 // fired.
1740 if (
1741 e.keyCode === OO.ui.Keys.ENTER &&
1742 !this.keyDownState.event &&
1743 // We're only aware of cases of this happening with uncommitted candidate text,
1744 // which implies a native selection. But we instead perform a weaker test - for
1745 // a non-null selection - to match that same test in onDocumentKeyDown
1746 !( ( selection = this.getModel().getSelection() ).isNull() )
1747 ) {
1748 this.surfaceObserver.stopTimerLoop();
1749 if ( ve.ce.keyDownHandlerFactory.executeHandlersForKey( e.keyCode, selection.getName(), this, e ) ) {
1750 this.surfaceObserver.pollOnce();
1751 }
1752 this.surfaceObserver.startTimerLoop();
1753 return;
1754 }
1755
1756 // Filter out non-character keys. Doing this prevents:
1757 // * Unexpected content deletion when selection is not collapsed and the user presses, for
1758 // example, the Home key (Firefox fires 'keypress' for it)
1759 // TODO: Should be covered with Selenium tests.
1760 if (
1761 // Catches most keys that don't produce output (charCode === 0, thus no character)
1762 e.which === 0 || e.charCode === 0 ||
1763 // Opera 12 doesn't always adhere to that convention
1764 e.keyCode === OO.ui.Keys.TAB || e.keyCode === OO.ui.Keys.ESCAPE ||
1765 // Ignore all keypresses with Ctrl / Cmd modifier keys
1766 ve.ce.isShortcutKey( e )
1767 ) {
1768 return;
1769 }
1770
1771 this.handleInsertion();
1772 };
1773
1774 /**
1775 * Deferred until after document key down event
1776 *
1777 * @param {jQuery.Event} e keydown event
1778 */
1779 ve.ce.Surface.prototype.afterDocumentKeyDown = function ( e ) {
1780 const documentModel = this.getModel().getDocument(),
1781 isArrow = (
1782 e.keyCode === OO.ui.Keys.UP ||
1783 e.keyCode === OO.ui.Keys.DOWN ||
1784 e.keyCode === OO.ui.Keys.LEFT ||
1785 e.keyCode === OO.ui.Keys.RIGHT
1786 );
1787 let keyDownSelectionState = null;
1788
1789 /**
1790 * Determine whether a position is editable, and if so which focusable node it is in
1791 *
1792 * We can land inside ce=false in many browsers:
1793 * - Firefox has normal cursor positions at most node boundaries inside ce=false
1794 * - Chromium has superfluous cursor positions around a ce=false img
1795 * - IE hardly restricts editing at all inside ce=false
1796 * If ce=false then we have landed inside the focusable node.
1797 * If we land in a non-text position, assume we should have hit the node
1798 * immediately after the position we hit (in the direction of motion)
1799 * If we land inside a sequence of grouped nodes, assume we should treat them as a
1800 * unit instead of letting the cursor slip inside them.
1801 *
1802 * @private
1803 * @param {Node} node DOM node of cursor position
1804 * @param {number} offset Offset of cursor position
1805 * @param {number} dir Cursor motion direction (1=forward, -1=backward)
1806 * @return {ve.ce.Node|null} node, or null if not in a focusable node
1807 */
1808 const getSurroundingFocusableNode = ( node, offset, dir ) => {
1809 let focusNode;
1810 if ( node.nodeType === Node.TEXT_NODE ) {
1811 focusNode = node;
1812 } else if ( dir > 0 && offset < node.childNodes.length ) {
1813 focusNode = node.childNodes[ offset ];
1814 } else if ( dir < 0 && offset > 0 ) {
1815 focusNode = node.childNodes[ offset - 1 ];
1816 } else {
1817 focusNode = node;
1818 }
1819
1820 if ( ve.isContentEditable( focusNode ) ) {
1821 // We are allowed to be inside this focusable node (e.g. editing a
1822 // table cell or caption).
1823 return null;
1824 }
1825 return $( focusNode ).closest( '.ve-ce-focusableNode, .ve-ce-tableNode' ).data( 'view' ) || null;
1826 };
1827
1828 /**
1829 * Compute the direction of cursor movement, if any
1830 *
1831 * Even if the user pressed a cursor key in the interior of the document, there may not
1832 * be any movement: browser BIDI and ce=false handling can be quite quirky.
1833 *
1834 * Furthermore, the keydown selection nodes may have become detached since keydown (e.g.
1835 * if ve.ce.ContentBranchNode#renderContents has run).
1836 *
1837 * @return {number|null} negative for startwards, positive for endwards, null for none
1838 */
1839 const getDirection = () => (
1840 isArrow &&
1841 keyDownSelectionState &&
1842 ve.compareDocumentOrder(
1843 this.nativeSelection.focusNode,
1844 this.nativeSelection.focusOffset,
1845 keyDownSelectionState.focusNode,
1846 keyDownSelectionState.focusOffset
1847 )
1848 ) || null;
1849
1850 if ( e !== this.keyDownState.event ) {
1851 return;
1852 }
1853 keyDownSelectionState = this.keyDownState.selectionState;
1854 this.clearKeyDownState();
1855
1856 if (
1857 ( e.keyCode === OO.ui.Keys.BACKSPACE || e.keyCode === OO.ui.Keys.DELETE ) &&
1858 this.nativeSelection.focusNode
1859 ) {
1860 const inNonSlug = this.nativeSelection.focusNode.nodeType === Node.ELEMENT_NODE &&
1861 !this.nativeSelection.focusNode.classList.contains( 've-ce-branchNode-inlineSlug' );
1862 if ( inNonSlug ) {
1863 // In a non-slug element. Sync the DM, then see if we need a slug.
1864 this.incRenderLock();
1865 try {
1866 this.surfaceObserver.pollOnce();
1867 } finally {
1868 this.decRenderLock();
1869 }
1870
1871 const dmSelection = this.model.getSelection();
1872 if ( dmSelection instanceof ve.dm.LinearSelection ) {
1873 const dmFocus = dmSelection.getRange().end;
1874 const ceNode = this.documentView.getBranchNodeFromOffset( dmFocus );
1875 if ( ceNode && ceNode.getModel().hasSlugAtOffset( dmFocus ) ) {
1876 ceNode.setupBlockSlugs();
1877 }
1878 }
1879 }
1880
1881 // Remove then re-set the selection, to clear any browser-native preannotations.
1882 // This should be IME-safe because delete/backspace key events should only happen
1883 // when there is no IME candidate window open.
1884 //
1885 // Note that if an IME removes text otherwise than by delete/backspace, then
1886 // browser-native preannotations might still get applied. This can happen: see
1887 // https://phabricator.wikimedia.org/T116275 .
1888 // That's nasty, but it's not a reason to leave the delete/backspace case broken.
1889 const ceSelection = new ve.SelectionState( this.nativeSelection );
1890 this.nativeSelection.removeAllRanges();
1891 this.showSelectionState( ceSelection );
1892
1893 if ( inNonSlug ) {
1894 return;
1895 }
1896 }
1897
1898 // Only fixup cursoring on linear selections.
1899 if ( isArrow && !( this.model.getSelection() instanceof ve.dm.LinearSelection ) ) {
1900 return;
1901 }
1902
1903 // Restore the selection and stop, if we cursored out of a table edit cell.
1904 // Assumption: if we cursored out of a table cell, then none of the fixups below this point
1905 // would have got the selection back inside the cell. Therefore it's OK to check here.
1906 if ( isArrow && this.restoreActiveNodeSelection() ) {
1907 return;
1908 }
1909
1910 // If we landed in a cursor holder, select the corresponding focusable node instead
1911 // (which, for a table, will select the first cell). Else if we arrowed a collapsed
1912 // cursor across a focusable node, select the node instead.
1913 const $focusNode = $( this.nativeSelection.focusNode );
1914 let direction;
1915 let focusableNode;
1916 let range;
1917 // eslint-disable-next-line no-jquery/no-class-state
1918 if ( $focusNode.hasClass( 've-ce-cursorHolder' ) ) {
1919 // eslint-disable-next-line no-jquery/no-class-state
1920 if ( $focusNode.hasClass( 've-ce-cursorHolder-after' ) ) {
1921 direction = -1;
1922 focusableNode = $focusNode.prev().data( 'view' );
1923 } else {
1924 direction = 1;
1925 focusableNode = $focusNode.next().data( 'view' );
1926 }
1927 this.removeCursorHolders();
1928 } else if (
1929 // If we arrowed a collapsed cursor into/across a focusable node, select the node instead
1930 isArrow &&
1931 !e.ctrlKey &&
1932 !e.altKey &&
1933 !e.metaKey &&
1934 keyDownSelectionState &&
1935 keyDownSelectionState.isCollapsed &&
1936 this.nativeSelection.isCollapsed &&
1937 ( direction = getDirection() ) !== null
1938 ) {
1939 focusableNode = getSurroundingFocusableNode(
1940 this.nativeSelection.focusNode,
1941 this.nativeSelection.focusOffset,
1942 direction
1943 );
1944
1945 if ( !focusableNode ) {
1946 let startOffset, endOffset, offsetDiff;
1947 // Calculate the DM offsets of our motion
1948 try {
1949 startOffset = ve.ce.getOffset(
1950 keyDownSelectionState.focusNode,
1951 keyDownSelectionState.focusOffset
1952 );
1953 endOffset = ve.ce.getOffset(
1954 this.nativeSelection.focusNode,
1955 this.nativeSelection.focusOffset
1956 );
1957 offsetDiff = endOffset - startOffset;
1958 } catch ( ex ) {
1959 startOffset = endOffset = offsetDiff = undefined;
1960 }
1961
1962 if ( Math.abs( offsetDiff ) === 2 ) {
1963 // Test whether we crossed a focusable node
1964 // (this applies even if we cursored up/down)
1965 focusableNode = documentModel.documentNode
1966 .getNodeFromOffset( ( startOffset + endOffset ) / 2 );
1967
1968 if ( focusableNode.isFocusable() ) {
1969 range = new ve.Range( startOffset, endOffset );
1970 } else {
1971 focusableNode = undefined;
1972 }
1973 }
1974 }
1975 }
1976
1977 if (
1978 isArrow &&
1979 direction > 0 &&
1980 this.getActiveNode() instanceof ve.ce.TableCaptionNode &&
1981 this.getActiveNode() !== $focusNode.closest( '.ve-ce-tableCaptionNode' ).data( 'view' )
1982 ) {
1983 // We cursored down out of the table caption; move to the first table cell
1984 const tableNode = this.getActiveNode().getParent();
1985 this.model.setSelection( new ve.dm.TableSelection( tableNode.getOuterRange(), 0, 0 ) );
1986 }
1987
1988 if ( focusableNode ) {
1989 if ( !range ) {
1990 range = focusableNode.getOuterRange();
1991 if ( direction < 0 ) {
1992 range = range.flip();
1993 }
1994 }
1995 if ( focusableNode instanceof ve.ce.TableNode ) {
1996 if ( direction > 0 ) {
1997 let captionNode;
1998 if ( ( captionNode = focusableNode.getModel().getCaptionNode() ) ) {
1999 this.model.setLinearSelection(
2000 documentModel.getRelativeRange( new ve.Range( captionNode.getRange().start ), 1 )
2001 );
2002 } else {
2003 this.model.setSelection( new ve.dm.TableSelection(
2004 range, 0, 0
2005 ) );
2006 }
2007 } else {
2008 const matrix = focusableNode.getModel().getMatrix();
2009 const row = matrix.getRowCount() - 1;
2010 const col = matrix.getColCount( row ) - 1;
2011 this.model.setSelection( new ve.dm.TableSelection(
2012 range, col, row
2013 ) );
2014 }
2015 } else {
2016 this.model.setLinearSelection( range );
2017 }
2018 if ( e.keyCode === OO.ui.Keys.LEFT ) {
2019 this.cursorDirectionality = direction > 0 ? 'rtl' : 'ltr';
2020 } else if ( e.keyCode === OO.ui.Keys.RIGHT ) {
2021 this.cursorDirectionality = direction < 0 ? 'rtl' : 'ltr';
2022 }
2023 // else up/down pressed; leave this.cursorDirectionality as null
2024 // (it was set by setLinearSelection calling onModelSelect)
2025 }
2026
2027 if ( direction === undefined ) {
2028 direction = getDirection();
2029 }
2030
2031 const fixupCursorForUnicorn = (
2032 !e.shiftKey &&
2033 ( e.keyCode === OO.ui.Keys.LEFT || e.keyCode === OO.ui.Keys.RIGHT )
2034 );
2035 const removedUnicorns = this.cleanupUnicorns( fixupCursorForUnicorn );
2036 if ( removedUnicorns ) {
2037 this.surfaceObserver.pollOnceNoCallback();
2038 } else {
2039 this.incRenderLock();
2040 try {
2041 this.surfaceObserver.pollOnce();
2042 } finally {
2043 this.decRenderLock();
2044 }
2045 }
2046 this.fixupCursorPosition( direction, e.shiftKey );
2047 };
2048
2049 /**
2050 * Check whether the DOM selection has moved out of the unicorned area (i.e. is not currently
2051 * between two unicorns) and if so, set the model selection from the DOM selection, destroy the
2052 * unicorns and return true. If there are no active unicorns, this function does nothing and
2053 * returns false.
2054 *
2055 * If the unicorns are destroyed as a consequence of the user moving the cursor across a unicorn
2056 * with the left/rightarrow keys, the cursor will have to be moved again to produce the cursor
2057 * movement the user expected. Set the fixupCursor parameter to true to enable this behavior.
2058 *
2059 * @param {boolean} fixupCursor If destroying unicorns, fix up left/rightarrow cursor position
2060 * @return {boolean} Whether unicorns have been destroyed
2061 */
2062 ve.ce.Surface.prototype.cleanupUnicorns = function ( fixupCursor ) {
2063 if ( !this.unicorningNode || !this.unicorningNode.unicorns ) {
2064 return false;
2065 }
2066 const preUnicorn = this.unicorningNode.unicorns[ 0 ];
2067 if ( !this.$attachedRootNode[ 0 ].contains( preUnicorn ) ) {
2068 return false;
2069 }
2070
2071 if ( this.nativeSelection.rangeCount === 0 ) {
2072 // XXX do we want to clear unicorns in this case?
2073 return false;
2074 }
2075 const range = this.nativeSelection.getRangeAt( 0 );
2076
2077 // Test whether the selection endpoint is between unicorns. If so, do nothing.
2078 // Unicorns can only contain text, so just move backwards until we hit a non-text node.
2079 let node = range.endContainer;
2080 if ( node.nodeType === Node.ELEMENT_NODE ) {
2081 node = range.endOffset > 0 ? node.childNodes[ range.endOffset - 1 ] : null;
2082 }
2083 while ( node !== null && node.nodeType === Node.TEXT_NODE ) {
2084 node = node.previousSibling;
2085 }
2086 if ( node === preUnicorn ) {
2087 return false;
2088 }
2089
2090 // Selection endpoint is not between unicorns.
2091 // Test whether it is before or after the pre-unicorn (i.e. before/after both unicorns)
2092 let fixup;
2093 if ( ve.compareDocumentOrder(
2094 range.endContainer,
2095 range.endOffset,
2096 preUnicorn.parentNode,
2097 ve.parentIndex( preUnicorn )
2098 ) <= 0 ) {
2099 // Before the pre-unicorn (including in the equality case, because the selection
2100 // endpoint is an offset between sibling positions)
2101 fixup = -1;
2102 } else {
2103 // At or after the pre-unicorn (actually must be after the post-unicorn)
2104 fixup = 1;
2105 }
2106
2107 const contentBranchNodeBefore = this.getSelectedContentBranchNode();
2108 if ( this.unicorningNode !== contentBranchNodeBefore ) {
2109 this.setNotUnicorningAll();
2110 return true;
2111 }
2112
2113 // Apply the DOM selection to the model
2114 const veRange = ve.ce.veRangeFromSelection( this.nativeSelection );
2115 if ( veRange ) {
2116 this.incRenderLock();
2117 try {
2118 // The most likely reason for this condition to not-pass is if we
2119 // try to cleanup unicorns while the native selection is outside
2120 // the model momentarily, as sometimes happens during paste.
2121 this.changeModel( null, new ve.dm.LinearSelection( veRange ) );
2122 if ( fixupCursor ) {
2123 this.moveModelCursor( fixup );
2124 }
2125 } finally {
2126 this.decRenderLock();
2127 }
2128 }
2129
2130 const contentBranchNodeAfter = this.getSelectedContentBranchNode();
2131 if ( contentBranchNodeAfter ) {
2132 contentBranchNodeAfter.renderContents();
2133 }
2134 if ( contentBranchNodeBefore && contentBranchNodeBefore !== contentBranchNodeAfter ) {
2135 contentBranchNodeBefore.renderContents();
2136 }
2137
2138 this.showModelSelection();
2139 return true;
2140 };
2141
2142 /**
2143 * Handle document key up events.
2144 *
2145 * @param {jQuery.Event} e Key up event
2146 * @fires ve.ce.Surface#keyup
2147 */
2148 ve.ce.Surface.prototype.onDocumentKeyUp = function () {
2149 this.emit( 'keyup' );
2150 };
2151
2152 /**
2153 * Handle cut events.
2154 *
2155 * @param {jQuery.Event} e Cut event
2156 */
2157 ve.ce.Surface.prototype.onCut = function ( e ) {
2158 const selection = this.getModel().getSelection();
2159
2160 if ( selection.isCollapsed() ) {
2161 return;
2162 }
2163
2164 this.onCopy( e );
2165 // setTimeout: postpone until after the setTimeout in onCopy
2166 setTimeout( () => {
2167 // Trigger a fake backspace to remove the content: this behaves differently based on the selection,
2168 // e.g. in a TableSelection.
2169 ve.ce.keyDownHandlerFactory.executeHandlersForKey( OO.ui.Keys.BACKSPACE, selection.getName(), this, e );
2170 } );
2171 };
2172
2173 /**
2174 * Handle copy (including cut) and dragstart events.
2175 *
2176 * @param {jQuery.Event} e Copy event
2177 * @param {ve.dm.Selection} selection Optional selection to simulate a copy on
2178 */
2179 ve.ce.Surface.prototype.onCopy = function ( e, selection ) {
2180 // Copy or cut, but not dragstart
2181 const isClipboard = e.type === 'copy' || e.type === 'cut',
2182 htmlDoc = this.getModel().getDocument().getHtmlDocument(),
2183 clipboardData = isClipboard ? e.originalEvent.clipboardData : e.originalEvent.dataTransfer;
2184
2185 selection = selection || this.getModel().getSelection();
2186
2187 this.$pasteTarget.empty();
2188
2189 if ( selection.isCollapsed() ) {
2190 return;
2191 }
2192
2193 const slice = this.model.documentModel.shallowCloneFromSelection( selection );
2194
2195 // Clone the elements in the slice
2196 slice.data.cloneElements( true );
2197
2198 ve.dm.converter.getDomSubtreeFromModel( slice, this.$pasteTarget[ 0 ], ve.dm.Converter.static.CLIPBOARD_MODE );
2199
2200 // Some browsers strip out spans when they match the styling of the
2201 // paste target (e.g. plain spans) so we must protect against this
2202 // by adding a dummy class, which we can remove after paste.
2203 this.$pasteTarget.find( 'span' ).addClass( 've-pasteProtect' );
2204
2205 // When paste has no text content browsers do extreme normalization…
2206 if ( this.$pasteTarget.text() === '' ) {
2207 // …so put nbsp's in empty leaves
2208 // eslint-disable-next-line no-jquery/no-sizzle
2209 this.$pasteTarget.find( '*:not( :has( * ) )' ).text( '\u00a0' );
2210 }
2211
2212 // Resolve attributes (in particular, expand 'href' and 'src' using the right base)
2213 ve.resolveAttributes(
2214 this.$pasteTarget[ 0 ],
2215 htmlDoc,
2216 ve.dm.Converter.static.computedAttributes
2217 );
2218
2219 // Support: Firefox
2220 // Some attributes (e.g RDFa attributes in Firefox) aren't preserved by copy
2221 const unsafeSelector = '[' + ve.ce.Surface.static.unsafeAttributes.join( '],[' ) + ']';
2222 this.$pasteTarget.find( unsafeSelector ).each( ( n, element ) => {
2223 const attrs = {},
2224 ua = ve.ce.Surface.static.unsafeAttributes;
2225
2226 let i = ua.length;
2227 while ( i-- ) {
2228 const val = element.getAttribute( ua[ i ] );
2229 if ( val !== null ) {
2230 attrs[ ua[ i ] ] = val;
2231 }
2232 }
2233 element.setAttribute( 'data-ve-attributes', JSON.stringify( attrs ) );
2234 } );
2235
2236 this.clipboardIndex++;
2237 const clipboardKey = this.clipboardId + '-' + this.clipboardIndex;
2238 this.clipboard = { slice: slice, hash: null };
2239 // Support: Firefox<48
2240 // Writing the key to text/xcustom won't work in Firefox<48, so write
2241 // it to the HTML instead
2242 if ( isClipboard && !ve.isClipboardDataFormatsSupported( e ) ) {
2243 this.$pasteTarget.prepend(
2244 $( '<span>' ).attr( 'data-ve-clipboard-key', clipboardKey ).text( '\u00a0' )
2245 );
2246 // To ensure the contents with the clipboardKey isn't modified in an external editor,
2247 // store a hash of the contents for later validation.
2248 this.clipboard.hash = this.constructor.static.getClipboardHash( this.$pasteTarget.contents() );
2249 }
2250
2251 if ( isClipboard ) {
2252 // Disable the default event so we can override the data
2253 e.preventDefault();
2254 }
2255
2256 // Only write a custom mime type if we think the browser supports it, otherwise
2257 // we will have already written a key to the HTML above.
2258 if ( isClipboard && ve.isClipboardDataFormatsSupported( e, true ) ) {
2259 clipboardData.setData( 'text/xcustom', clipboardKey );
2260 }
2261 clipboardData.setData( 'text/html', this.$pasteTarget.html() );
2262 // innerText "approximates the text the user would get if they highlighted the
2263 // contents of the element with the cursor and then copied to the clipboard." - MDN
2264 // Use $.text as a fallback for Firefox <= 44
2265 clipboardData.setData( 'text/plain', this.$pasteTarget[ 0 ].innerText || this.$pasteTarget.text() || ' ' );
2266
2267 ve.track( 'activity.clipboard', { action: e.type } );
2268 };
2269
2270 /**
2271 * Get the annotation set that was a the user focus before a paste started
2272 *
2273 * @return {ve.dm.AnnotationSet} Annotation set
2274 */
2275 ve.ce.Surface.prototype.getBeforePasteAnnotationSet = function () {
2276 const store = this.getModel().getDocument().getStore();
2277 const dmAnnotations = this.beforePasteAnnotationsAtFocus.map( ( view ) => view.getModel() );
2278 return new ve.dm.AnnotationSet( store, store.hashAll( dmAnnotations ) );
2279 };
2280
2281 /**
2282 * Handle native paste event
2283 *
2284 * @param {jQuery.Event} e Paste event
2285 * @return {boolean|undefined} False if the event is cancelled
2286 */
2287 ve.ce.Surface.prototype.onPaste = function ( e ) {
2288 // Prevent pasting until after we are done
2289 if ( this.pasting || this.readOnly ) {
2290 return false;
2291 }
2292 this.beforePaste( e );
2293 this.surfaceObserver.disable();
2294 this.pasting = true;
2295 // setTimeout: postpone until after the default paste action
2296 setTimeout( () => {
2297 let afterPastePromise = ve.createDeferred().resolve().promise();
2298 try {
2299 if ( !e.isDefaultPrevented() ) {
2300 afterPastePromise = this.afterPaste( e );
2301 }
2302 } finally {
2303 afterPastePromise.always( () => {
2304 this.surfaceObserver.clear();
2305 this.surfaceObserver.enable();
2306
2307 // Allow pasting again
2308 this.pasting = false;
2309 this.pasteSpecial = false;
2310 this.beforePasteData = null;
2311
2312 // Restore original clipboard metadata if requred (was overridden by middle-click
2313 // paste logic in beforePaste)
2314 if ( this.originalClipboardMetdata ) {
2315 this.clipboardIndex = this.originalClipboardMetdata.clipboardIndex;
2316 this.clipboard = this.originalClipboardMetdata.clipboard;
2317 }
2318
2319 ve.track( 'activity.clipboard', { action: 'paste' } );
2320 } );
2321 }
2322 } );
2323 };
2324
2325 /**
2326 * Handle pre-paste events.
2327 *
2328 * @param {jQuery.Event} e Paste event
2329 */
2330 ve.ce.Surface.prototype.beforePaste = function ( e ) {
2331 const selection = this.getModel().getSelection(),
2332 clipboardData = e.originalEvent.clipboardData,
2333 surfaceModel = this.getModel(),
2334 fragment = surfaceModel.getFragment(),
2335 documentModel = surfaceModel.getDocument();
2336
2337 let range;
2338 if ( selection instanceof ve.dm.LinearSelection ) {
2339 range = fragment.getSelection().getRange();
2340 } else if ( selection instanceof ve.dm.TableSelection ) {
2341 range = new ve.Range( selection.getRanges( documentModel )[ 0 ].start );
2342 } else {
2343 e.preventDefault();
2344 return;
2345 }
2346
2347 this.beforePasteAnnotationsAtFocus = this.annotationsAtFocus();
2348 this.beforePasteData = {};
2349 this.originalClipboardMetdata = null;
2350 if ( this.middleClickPasting && !this.lastNonCollapsedDocumentSelection.isNull() ) {
2351 // Paste was triggered by middle click, and the last non-collapsed document selection was in
2352 // this VE surface. Simulate a fake copy to load DM data into the clipboard. If we let the
2353 // native middle-click paste happen, it would load CE data into the clipboard.
2354 // Store original clipboard metadata so it can be restored after paste,
2355 // and we can continue to use internal paste.
2356 this.originalClipboardMetdata = {
2357 clipboardIndex: this.clipboardIndex,
2358 clipboard: this.clipboard
2359 };
2360 // Use a fake clipboard index for middle click, will be restored in afterPaste
2361 this.clipboardIndex = -1;
2362 this.clipboard = {
2363 slice: this.model.documentModel.shallowCloneFromSelection( this.lastNonCollapsedDocumentSelection ),
2364 hash: null
2365 };
2366 this.beforePasteData.custom = this.clipboardId + '-' + this.clipboardIndex;
2367 } else if ( clipboardData ) {
2368 if ( this.handleDataTransfer( clipboardData, true ) ) {
2369 e.preventDefault();
2370 return;
2371 }
2372 this.beforePasteData.custom = clipboardData.getData( 'text/xcustom' );
2373 this.beforePasteData.html = clipboardData.getData( 'text/html' );
2374 if ( this.beforePasteData.html ) {
2375 // http://msdn.microsoft.com/en-US/en-%20us/library/ms649015(VS.85).aspx
2376 this.beforePasteData.html = this.beforePasteData.html
2377 .replace( /^[\s\S]*<!-- *StartFragment *-->/, '' )
2378 .replace( /<!-- *EndFragment *-->[\s\S]*$/, '' );
2379 }
2380 }
2381
2382 // Save scroll position before changing focus to "offscreen" paste target
2383 this.beforePasteData.scrollTop = this.surface.$scrollContainer.scrollTop();
2384
2385 this.$pasteTarget.empty();
2386
2387 // Get node from cursor position
2388 const startNode = documentModel.getBranchNodeFromOffset( range.start );
2389 if ( startNode.canContainContent() ) {
2390 // If this is a content branch node, then add its DM HTML
2391 // to the paste target to give CE some context.
2392 let textStart = 0, textEnd = 0;
2393 const contextElement = startNode.getClonedElement();
2394 // Make sure that context doesn't have any attributes that might confuse
2395 // the importantElement check in afterPaste.
2396 $( documentModel.getStore().value( contextElement.originalDomElementsHash ) ).removeAttr( 'id typeof rel' );
2397 const context = [ contextElement ];
2398 // If there is content to the left of the cursor, put a placeholder
2399 // character to the left of the cursor
2400 let leftText, rightText;
2401 if ( range.start > startNode.getRange().start ) {
2402 leftText = '☀';
2403 context.push( leftText );
2404 textStart = textEnd = 1;
2405 }
2406 // If there is content to the right of the cursor, put a placeholder
2407 // character to the right of the cursor
2408 const endNode = documentModel.getBranchNodeFromOffset( range.end );
2409 if ( range.end < endNode.getRange().end ) {
2410 rightText = '☂';
2411 context.push( rightText );
2412 }
2413 // If there is no text context, select some text to be replaced
2414 if ( !leftText && !rightText ) {
2415 context.push( '☁' );
2416 textEnd = 1;
2417 // If we are middle click pasting we can't change the native selection, so
2418 // just make the text a placeholder to the left. (T311723)
2419 if ( this.middleClickPasting ) {
2420 leftText = '☁';
2421 textStart = 1;
2422 }
2423 }
2424 context.push( { type: '/' + context[ 0 ].type } );
2425
2426 // Throw away 'internal', specifically inner whitespace,
2427 // before conversion as it can affect textStart/End offsets.
2428 delete contextElement.internal;
2429 ve.dm.converter.getDomSubtreeFromModel(
2430 documentModel.cloneWithData( context, true ),
2431 this.$pasteTarget[ 0 ]
2432 );
2433
2434 // Giving the paste target focus too late can cause problems in FF (!?)
2435 // so do it up here.
2436 this.$pasteTarget[ 0 ].focus();
2437
2438 const nativeRange = this.getElementDocument().createRange();
2439 // Assume that the DM node only generated one child
2440 const textNode = this.$pasteTarget.children().contents()[ 0 ];
2441 // Place the cursor between the placeholder characters
2442 nativeRange.setStart( textNode, textStart );
2443 nativeRange.setEnd( textNode, textEnd );
2444 this.nativeSelection.removeAllRanges();
2445 this.nativeSelection.addRange( nativeRange );
2446
2447 this.beforePasteData.context = context;
2448 this.beforePasteData.leftText = leftText;
2449 this.beforePasteData.rightText = rightText;
2450 } else {
2451 // If we're not in a content branch node, don't bother trying to do
2452 // anything clever with paste context
2453 this.$pasteTarget[ 0 ].focus();
2454 }
2455
2456 // Restore scroll position after focusing the paste target
2457 this.surface.$scrollContainer.scrollTop( this.beforePasteData.scrollTop );
2458
2459 };
2460
2461 /**
2462 * Handle post-paste events.
2463 *
2464 * @param {jQuery.Event} e Paste event
2465 * @return {jQuery.Promise} Promise which resolves when the content has been pasted
2466 */
2467 ve.ce.Surface.prototype.afterPaste = function () {
2468 const surfaceModel = this.getModel(),
2469 documentModel = surfaceModel.getDocument(),
2470 fragment = surfaceModel.getFragment(),
2471 beforePasteData = this.beforePasteData || {},
2472 done = ve.createDeferred().resolve().promise();
2473 let targetFragment = surfaceModel.getFragment( null, true );
2474
2475 // If the selection doesn't collapse after paste then nothing was inserted
2476 if ( !this.nativeSelection.isCollapsed ) {
2477 return done;
2478 }
2479
2480 if ( this.getModel().getFragment().isNull() ) {
2481 return done;
2482 }
2483
2484 if ( this.middleClickTargetOffset ) {
2485 targetFragment = targetFragment.clone( new ve.dm.LinearSelection( new ve.Range( this.middleClickTargetOffset ) ) );
2486 } else if ( this.middleClickPasting ) {
2487 // Middle click pasting should always collapse the selection before pasting
2488 targetFragment = targetFragment.collapseToEnd();
2489 }
2490
2491 // Immedately remove any <style> tags from the pasteTarget that might
2492 // be changing the rendering of the whole page (T235068)
2493 this.$pasteTarget.find( 'style' ).remove();
2494
2495 const pasteData = this.afterPasteExtractClipboardData();
2496
2497 // Handle pastes into a table
2498 if ( fragment.getSelection() instanceof ve.dm.TableSelection ) {
2499 // Internal table-into-table paste can be shortcut
2500 if ( fragment.getSelection() instanceof ve.dm.TableSelection && pasteData.slice instanceof ve.dm.TableSlice ) {
2501 const tableAction = new ve.ui.TableAction( this.getSurface() );
2502 tableAction.importTable( pasteData.slice.getTableNode( documentModel ) );
2503 return ve.createDeferred().resolve().promise();
2504 }
2505
2506 // For table selections the target is the first cell
2507 targetFragment = surfaceModel.getLinearFragment( fragment.getSelection().getRanges( documentModel )[ 0 ], true );
2508 }
2509
2510 // Are we pasting into a multiline context?
2511 const isMultiline = this.getDocument().getBranchNodeFromOffset(
2512 targetFragment.getSelection().getCoveringRange().from
2513 ).isMultiline();
2514
2515 let pending;
2516 if ( pasteData.slice ) {
2517 pending = this.afterPasteAddToFragmentFromInternal( pasteData.slice, fragment, targetFragment, isMultiline );
2518 } else {
2519 pending = this.afterPasteAddToFragmentFromExternal( pasteData.clipboardKey, pasteData.$clipboardHtml, fragment, targetFragment, isMultiline );
2520 }
2521 return pending.then( () => {
2522 if ( this.getSelection().isNativeCursor() ) {
2523 // Restore focus and scroll position
2524 this.$attachedRootNode[ 0 ].focus();
2525 this.surface.$scrollContainer.scrollTop( beforePasteData.scrollTop );
2526 // setTimeout: Firefox sometimes doesn't change scrollTop immediately when pasting
2527 // line breaks at the end of a line so do it again later.
2528 setTimeout( () => {
2529 this.surface.$scrollContainer.scrollTop( beforePasteData.scrollTop );
2530 } );
2531 }
2532
2533 // If original selection was linear, switch to end of pasted text
2534 if ( fragment.getSelection() instanceof ve.dm.LinearSelection ) {
2535 targetFragment.collapseToEnd().select();
2536 this.findAndExecuteSequences( /* isPaste */ true );
2537 }
2538 } );
2539 };
2540
2541 /**
2542 * @typedef {Object} ClipboardData
2543 * @memberof ve.ce
2544 * @property {string|undefined} clipboardKey Clipboard key, if present
2545 * @property {jQuery|undefined} $clipboardHtml Clipboard html, if used to extract the clipboard key
2546 * @property {ve.dm.DocumentSlice|undefined} slice Relevant slice of this document, if the key points to it
2547 */
2548
2549 /**
2550 * Extract the clipboard key and other relevant data from beforePasteData / the paste target
2551 *
2552 * @return {ve.ce.ClipboardData} Data
2553 */
2554 ve.ce.Surface.prototype.afterPasteExtractClipboardData = function () {
2555 const beforePasteData = this.beforePasteData || {};
2556
2557 let clipboardKey, clipboardHash, $clipboardHtml;
2558 // Find the clipboard key
2559 if ( beforePasteData.custom ) {
2560 // text/xcustom was present, and requires no further processing
2561 clipboardKey = beforePasteData.custom;
2562 } else {
2563 if ( beforePasteData.html ) {
2564 // text/html was present, so we can check if a key was hidden in it
2565 $clipboardHtml = $( ve.sanitizeHtml( beforePasteData.html ) ).filter( ( i, element ) => {
2566 const val = element.getAttribute && element.getAttribute( 'data-ve-clipboard-key' );
2567 if ( val ) {
2568 clipboardKey = val;
2569 // Remove the clipboard key span once read
2570 return false;
2571 }
2572 return true;
2573 } );
2574 clipboardHash = this.constructor.static.getClipboardHash( $clipboardHtml );
2575 } else {
2576 // fall back on checking the pasteTarget
2577
2578 // HTML in pasteTarget may get wrapped, so use the recursive $.find to look for the clipboard key
2579 clipboardKey = this.$pasteTarget.find( 'span[data-ve-clipboard-key]' ).data( 've-clipboard-key' );
2580 // Pass beforePasteData so context gets stripped
2581 clipboardHash = this.constructor.static.getClipboardHash( this.$pasteTarget, beforePasteData );
2582 }
2583 }
2584
2585 let slice;
2586 // If we have a clipboard key, validate it and fetch data
2587 if ( clipboardKey === this.clipboardId + '-' + this.clipboardIndex ) {
2588 // Hash validation: either text/xcustom was used or the hash must be
2589 // equal to the hash of the pasted HTML to assert that the HTML
2590 // hasn't been modified in another editor before being pasted back.
2591 if ( beforePasteData.custom || clipboardHash === this.clipboard.hash ) {
2592 slice = this.clipboard.slice;
2593 // Clone again. The elements were cloned on copy, but we need to clone
2594 // on paste too in case the same thing is pasted multiple times.
2595 slice.data.cloneElements( true );
2596 }
2597 }
2598
2599 if ( !slice && !$clipboardHtml && beforePasteData.html ) {
2600 $clipboardHtml = $( ve.sanitizeHtml( beforePasteData.html ) );
2601 }
2602
2603 return {
2604 clipboardKey: clipboardKey,
2605 $clipboardHtml: $clipboardHtml,
2606 slice: slice
2607 };
2608 };
2609
2610 /**
2611 * LinearData sanitize helper, for pasted data
2612 *
2613 * @param {ve.dm.LinearData} linearData Data to sanitize
2614 * @param {boolean} isMultiline Sanitize for a multiline context
2615 * @param {boolean} isExternal Treat as external content
2616 */
2617 ve.ce.Surface.prototype.afterPasteSanitize = function ( linearData, isMultiline, isExternal ) {
2618 const importRules = this.afterPasteImportRules( isMultiline );
2619 if ( isExternal ) {
2620 linearData.sanitize( importRules.external || {} );
2621 }
2622 linearData.sanitize( importRules.all || {} );
2623 };
2624
2625 /**
2626 * Helper to build import rules for pasted data
2627 *
2628 * @param {boolean} isMultiline Get rules for a multiline context
2629 * @return {Object.<string,Object>} Import rules
2630 */
2631 ve.ce.Surface.prototype.afterPasteImportRules = function ( isMultiline ) {
2632 let importRules = !this.pasteSpecial ? this.getSurface().getImportRules() : { all: { plainText: true, keepEmptyContentBranches: true } };
2633 if ( !isMultiline ) {
2634 importRules = {
2635 all: ve.extendObject( {}, importRules.all, { singleLine: true } ),
2636 external: ve.extendObject( {}, importRules.external, { singleLine: true } )
2637 };
2638 }
2639 return importRules;
2640 };
2641
2642 /**
2643 * After paste handler for pastes from the same document
2644 *
2645 * @param {ve.dm.DocumentSlice} slice Slice of document to paste
2646 * @param {ve.dm.SurfaceFragment} fragment Current fragment
2647 * @param {ve.dm.SurfaceFragment} targetFragment Fragment to insert into
2648 * @param {boolean} isMultiline Pasting to a multiline context
2649 * @return {jQuery.Promise} Promise which resolves when the content has been inserted
2650 */
2651 ve.ce.Surface.prototype.afterPasteAddToFragmentFromInternal = function ( slice, fragment, targetFragment, isMultiline ) {
2652 // Pasting non-table content into table: just replace the first cell with the pasted content
2653 if ( fragment.getSelection() instanceof ve.dm.TableSelection ) {
2654 // Cell was not deleted in beforePaste to prevent flicker when table-into-table paste is
2655 // about to be triggered.
2656 targetFragment.removeContent();
2657 }
2658
2659 // Temporary tracking for T362358
2660 const pastedRefs = slice.getNodesByType( 'mwReference' );
2661 if ( pastedRefs.length > 0 ) {
2662 const documentRefKeys = fragment.getDocument().getNodesByType( 'mwReference' ).map(
2663 ( ref ) => ref.registeredListGroup + '\n' + ref.registeredListKey
2664 );
2665 if ( pastedRefs.some(
2666 ( ref ) => documentRefKeys.indexOf( ref.registeredListGroup + '\n' + ref.registeredListKey ) !== -1
2667 ) ) {
2668 ve.track( 'activity.clipboard', { action: 'paste-ref-internal-reuse' } );
2669 } else {
2670 ve.track( 'activity.clipboard', { action: 'paste-ref-internal-new' } );
2671 }
2672 }
2673
2674 // Only try original data in multiline contexts, for single line we must use balanced data
2675
2676 let linearData, insertionPromise;
2677 // Original data + fixupInsertion
2678 if ( isMultiline ) {
2679 // Take a copy to prevent the data being annotated a second time in the balanced data path
2680 // and to prevent actions in the data model affecting view.clipboard
2681 linearData = new ve.dm.ElementLinearData(
2682 slice.getStore(),
2683 ve.copy( slice.getOriginalData() )
2684 );
2685
2686 if ( this.pasteSpecial ) {
2687 this.afterPasteSanitize( linearData, isMultiline );
2688 }
2689
2690 // ve.dm.Document#fixupInsertion may fail, in which case we fall back to balanced data
2691 try {
2692 insertionPromise = this.afterPasteInsertInternalData( targetFragment, linearData.getData() );
2693 } catch ( e ) {}
2694 }
2695
2696 // Balanaced data
2697 if ( !insertionPromise ) {
2698 // Take a copy to prevent actions in the data model affecting view.clipboard
2699 linearData = new ve.dm.ElementLinearData(
2700 slice.getStore(),
2701 ve.copy( slice.getBalancedData() )
2702 );
2703
2704 if ( this.pasteSpecial || !isMultiline ) {
2705 this.afterPasteSanitize( linearData, isMultiline );
2706 }
2707
2708 let data = linearData.getData();
2709
2710 if ( !isMultiline ) {
2711 // Unwrap single CBN
2712 if ( data[ 0 ].type ) {
2713 data = data.slice( 1, data.length - 1 );
2714 }
2715 }
2716
2717 insertionPromise = this.afterPasteInsertInternalData( targetFragment, data );
2718 }
2719
2720 return insertionPromise;
2721 };
2722
2723 /**
2724 * Insert some pasted data from an internal source
2725 *
2726 * @param {ve.dm.SurfaceFragment} targetFragment Fragment to insert into
2727 * @param {Array} data Data to insert
2728 * @return {jQuery.Promise} Promise which resolves when the content has been inserted
2729 */
2730 ve.ce.Surface.prototype.afterPasteInsertInternalData = function ( targetFragment, data ) {
2731 targetFragment.insertContent( data, this.getBeforePasteAnnotationSet() );
2732 return targetFragment.getPending();
2733 };
2734
2735 /**
2736 * After paste handler for pastes from the another document
2737 *
2738 * @param {string|undefined} clipboardKey Clipboard key for pasted data
2739 * @param {jQuery|undefined} $clipboardHtml Clipboard HTML, if used to find the key
2740 * @param {ve.dm.SurfaceFragment} fragment Current fragment
2741 * @param {ve.dm.SurfaceFragment} targetFragment Fragment to insert into
2742 * @param {boolean} [isMultiline] Pasting to a multiline context
2743 * @param {boolean} [forceClipboardData] Ignore the paste target, and use only clipboard html
2744 * @return {jQuery.Promise} Promise which resolves when the content has been inserted
2745 */
2746 ve.ce.Surface.prototype.afterPasteAddToFragmentFromExternal = function ( clipboardKey, $clipboardHtml, fragment, targetFragment, isMultiline, forceClipboardData ) {
2747 const importantElement = '[id],[typeof],[rel],figure',
2748 items = [],
2749 surfaceModel = this.getModel(),
2750 documentModel = surfaceModel.getDocument(),
2751 beforePasteData = this.beforePasteData || {};
2752
2753 let htmlDoc;
2754 // There are two potential sources of HTML to choose from:
2755 // * this.$pasteTarget where we we let the past happen in a context similar to the surface
2756 // * beforePasteData.html which is read from the clipboard API
2757 //
2758 // If clipboard API data is available, then make sure important elements haven't been dropped.
2759 //
2760 // The only reason we don't use clipboard API data unconditionally is that for simpler pastes,
2761 // the $pasteTarget method does a good job of merging content, e.g. paragraps into paragraphs.
2762 //
2763 // If we could do a better job of mimicking how browsers merge content, the clipboard API data
2764 // would produce much more consistent results, as the pasteTarget approach can also re-order
2765 // and destroy nodes.
2766 if (
2767 $clipboardHtml && (
2768 forceClipboardData ||
2769 // FIXME T126045: Allow the test runner to force the use of clipboardData
2770 clipboardKey === 'useClipboardData-0' ||
2771 $clipboardHtml.find( importantElement ).addBack( importantElement ).length > this.$pasteTarget.find( importantElement ).length
2772 )
2773 ) {
2774 // CE destroyed an important element, so revert to using clipboard data
2775 htmlDoc = ve.sanitizeHtmlToDocument( beforePasteData.html );
2776 $( htmlDoc )
2777 // Remove the pasteProtect class. See #onCopy.
2778 .find( 'span' ).removeClass( 've-pasteProtect' ).end()
2779 // Remove the clipboard key
2780 .find( 'span[data-ve-clipboard-key]' ).remove().end()
2781 // Remove ve-attributes, we trust that clipboard data preserved these attributes
2782 .find( '[data-ve-attributes]' ).removeAttr( 'data-ve-attributes' );
2783 beforePasteData.context = null;
2784 }
2785 if ( !htmlDoc ) {
2786 // If we're using $pasteTarget, let CE do its sanitizing as it may
2787 // contain disruptive metadata (head tags etc.)
2788 htmlDoc = ve.sanitizeHtmlToDocument( this.$pasteTarget.html() );
2789 }
2790
2791 // Some browsers don't provide pasted image data through the clipboardData API and
2792 // instead create img tags with data URLs, so detect those here
2793 const $body = $( htmlDoc.body );
2794 const $images = $body.children( 'img[src^=data\\:]' );
2795 // Check the body contained just images.
2796 // TODO: In the future this may want to trigger image uploads *and* paste the HTML.
2797 if ( $images.length && $images.length === $body.children().length ) {
2798 for ( let i = 0; i < $images.length; i++ ) {
2799 items.push( ve.ui.DataTransferItem.static.newFromDataUri(
2800 $images.eq( i ).attr( 'src' ),
2801 $images[ i ].outerHTML
2802 ) );
2803 }
2804 if ( this.handleDataTransferItems( items, true ) ) {
2805 return ve.createDeferred().resolve().promise();
2806 }
2807 }
2808
2809 this.afterPasteSanitizeExternal( $( htmlDoc.body ) );
2810
2811 // HACK: Fix invalid HTML from Google Docs nested lists (T98100).
2812 // Converts
2813 // <ul><li>A</li><ul><li>B</li></ul></ul>
2814 // to
2815 // <ul><li>A<ul><li>B</li></ul></li></ul>
2816 $( htmlDoc.body ).find( 'ul > ul, ul > ol, ol > ul, ol > ol' ).each( ( n, element ) => {
2817 if ( element.previousElementSibling ) {
2818 element.previousElementSibling.appendChild( element );
2819 } else {
2820 // List starts double indented. This is invalid and a semantic nightmare.
2821 // Just wrap with an extra list item
2822 $( element ).wrap( '<li>' );
2823 }
2824 } );
2825
2826 // HACK: Fix invalid HTML from copy-pasting `display: inline` lists (T239550).
2827 $( htmlDoc.body ).find( 'li, dd, dt' ).each( ( n, element ) => {
2828 const listType = { li: 'ul', dd: 'dl', dt: 'dl' },
2829 tag = element.tagName.toLowerCase(),
2830 // Parent node always exists because we're searching inside <body>
2831 parentTag = element.parentNode.tagName.toLowerCase();
2832
2833 let list;
2834 if (
2835 ( tag === 'li' && ( parentTag !== 'ul' && parentTag !== 'ol' ) ) ||
2836 ( ( tag === 'dd' || tag === 'dt' ) && parentTag !== 'dl' )
2837 ) {
2838 // This list item's parent node is not a list. This breaks expectations in DM code.
2839 // Wrap this node and its list item siblings in a list node.
2840 list = htmlDoc.createElement( listType[ tag ] );
2841 element.parentNode.insertBefore( list, element );
2842
2843 while (
2844 list.nextElementSibling &&
2845 listType[ list.nextElementSibling.tagName.toLowerCase() ] === listType[ tag ]
2846 ) {
2847 list.appendChild( list.nextElementSibling );
2848 }
2849 }
2850 } );
2851
2852 // HTML sanitization
2853 const htmlBlacklist = ve.getProp( this.afterPasteImportRules( isMultiline ), 'external', 'htmlBlacklist' );
2854 if ( htmlBlacklist && !clipboardKey ) {
2855 if ( htmlBlacklist.remove ) {
2856 Object.keys( htmlBlacklist.remove ).forEach( ( selector ) => {
2857 if ( htmlBlacklist.remove[ selector ] ) {
2858 $( htmlDoc.body ).find( selector ).remove();
2859 }
2860 } );
2861 }
2862 if ( htmlBlacklist.unwrap ) {
2863 Object.keys( htmlBlacklist.unwrap ).forEach( ( selector ) => {
2864 if ( htmlBlacklist.unwrap[ selector ] ) {
2865 $( htmlDoc.body ).find( selector ).contents().unwrap();
2866 }
2867 } );
2868 }
2869 }
2870
2871 // External paste
2872 const pastedDocumentModel = ve.dm.converter.getModelFromDom( htmlDoc, {
2873 targetDoc: documentModel.getHtmlDocument(),
2874 fromClipboard: true
2875 } );
2876 const data = pastedDocumentModel.data;
2877 // Clone again
2878 data.cloneElements( true );
2879
2880 // Sanitize
2881 this.afterPasteSanitize( data, isMultiline, !clipboardKey );
2882
2883 data.remapInternalListKeys( documentModel.getInternalList() );
2884
2885 // Initialize node tree
2886 pastedDocumentModel.buildNodeTree();
2887
2888 if ( fragment.getSelection() instanceof ve.dm.TableSelection ) {
2889 // External table-into-table paste
2890 if (
2891 pastedDocumentModel.documentNode.children.length === 2 &&
2892 pastedDocumentModel.documentNode.children[ 0 ] instanceof ve.dm.TableNode
2893 ) {
2894 const tableAction = new ve.ui.TableAction( this.getSurface() );
2895 tableAction.importTable( pastedDocumentModel.documentNode.children[ 0 ], true );
2896 return ve.createDeferred().resolve().promise();
2897 }
2898
2899 // Pasting non-table content into table: just replace the first cell with the pasted content
2900 // Cell was not deleted in beforePaste to prevent flicker when table-into-table paste is about to be triggered.
2901 targetFragment.removeContent();
2902 }
2903
2904 let contextRange;
2905 if ( beforePasteData.context ) {
2906 // If the paste was given context, calculate the range of the inserted data
2907 contextRange = this.afterPasteFromExternalContextRange( pastedDocumentModel, isMultiline, forceClipboardData );
2908 if ( !contextRange ) {
2909 return this.afterPasteAddToFragmentFromExternal( clipboardKey, $clipboardHtml, fragment, targetFragment, isMultiline, true );
2910 }
2911 } else {
2912 contextRange = pastedDocumentModel.getDocumentRange();
2913 }
2914 const pastedNodes = pastedDocumentModel.selectNodes( contextRange, 'siblings' )
2915 // Ignore nodes where nothing is selected
2916 .filter( ( node ) => !( node.range && node.range.isCollapsed() ) );
2917
2918 // Unwrap single content branch nodes to match internal copy/paste behaviour
2919 // (which wouldn't put the open and close tags in the clipboard to begin with).
2920 if (
2921 pastedNodes.length === 1 &&
2922 pastedNodes[ 0 ].node.canContainContent()
2923 ) {
2924 if ( contextRange.containsRange( pastedNodes[ 0 ].nodeRange ) ) {
2925 contextRange = pastedNodes[ 0 ].nodeRange;
2926 }
2927 }
2928
2929 return this.afterPasteInsertExternalData( targetFragment, pastedDocumentModel, contextRange );
2930 };
2931
2932 /**
2933 * Insert some pasted data from an external source
2934 *
2935 * @param {ve.dm.SurfaceFragment} targetFragment Fragment to insert into
2936 * @param {ve.dm.Document} pastedDocumentModel Model generated from pasted data
2937 * @param {ve.Range} contextRange Range of data in generated model to consider
2938 * @return {jQuery.Promise} Promise which resolves when the content has been inserted
2939 */
2940 ve.ce.Surface.prototype.afterPasteInsertExternalData = function ( targetFragment, pastedDocumentModel, contextRange ) {
2941 // Temporary tracking for T362358
2942 if ( pastedDocumentModel.getInternalList().getItemNodeCount() > 0 ) {
2943 ve.track( 'activity.clipboard', { action: 'paste-ref-external' } );
2944 }
2945
2946 let handled;
2947 // If the external HTML turned out to be plain text after sanitization
2948 // then run it as a plain text transfer item. In core this will never
2949 // do anything, but implementations can provide their own handler for
2950 // conversion actions here.
2951 if ( pastedDocumentModel.data.isPlainText( contextRange, true, undefined, true ) ) {
2952 const pastedText = pastedDocumentModel.data.getText( true, contextRange );
2953 if ( pastedText ) {
2954 handled = this.handleDataTransferItems(
2955 [ ve.ui.DataTransferItem.static.newFromString( pastedText ) ],
2956 true,
2957 targetFragment
2958 );
2959 }
2960 }
2961 if ( !handled ) {
2962 targetFragment.insertDocument( pastedDocumentModel, contextRange, this.getBeforePasteAnnotationSet() );
2963 }
2964 return targetFragment.getPending();
2965 };
2966
2967 /**
2968 * Helper to work out the context range for an external paste
2969 *
2970 * @param {ve.dm.Document} pastedDocumentModel Model for pasted data
2971 * @param {boolean} isMultiline Whether pasting to a multiline context
2972 * @param {boolean} forceClipboardData Whether the current attempted paste is the result of forcing use of clipboard data
2973 * @return {ve.Range|boolean} Context range, or false if data appeared corrupted
2974 */
2975 ve.ce.Surface.prototype.afterPasteFromExternalContextRange = function ( pastedDocumentModel, isMultiline, forceClipboardData ) {
2976 const data = pastedDocumentModel.data,
2977 documentRange = pastedDocumentModel.getDocumentRange(),
2978 beforePasteData = this.beforePasteData || {},
2979 context = new ve.dm.ElementLinearData(
2980 pastedDocumentModel.getStore(),
2981 ve.copy( beforePasteData.context )
2982 );
2983 // Sanitize context to match data
2984 this.afterPasteSanitize( context, isMultiline );
2985
2986 let leftText = beforePasteData.leftText;
2987 let rightText = beforePasteData.rightText;
2988
2989 // Remove matching context from the left
2990 let left = 0;
2991 while (
2992 context.getLength() &&
2993 ve.dm.ElementLinearData.static.compareElementsUnannotated(
2994 data.getData( left ),
2995 data.isElementData( left ) ? context.getData( 0 ) : leftText
2996 )
2997 ) {
2998 if ( !data.isElementData( left ) ) {
2999 // Text context is removed
3000 leftText = '';
3001 }
3002 left++;
3003 context.splice( 0, 1 );
3004 }
3005
3006 // Remove matching context from the right
3007 let right = documentRange.end;
3008 while (
3009 right > 0 &&
3010 context.getLength() &&
3011 ve.dm.ElementLinearData.static.compareElementsUnannotated(
3012 data.getData( right - 1 ),
3013 data.isElementData( right - 1 ) ? context.getData( context.getLength() - 1 ) : rightText
3014 )
3015 ) {
3016 if ( !data.isElementData( right - 1 ) ) {
3017 // Text context is removed
3018 rightText = '';
3019 }
3020 right--;
3021 context.splice( context.getLength() - 1, 1 );
3022 }
3023 if ( ( leftText || rightText ) && !forceClipboardData ) {
3024 // If any text context is left over, assume the paste target got corrupted
3025 // so we should start again and try to use clipboardData instead. T193110
3026 return false;
3027 }
3028 // Support: Chrome
3029 // FIXME T126046: Strip trailing linebreaks probably introduced by Chrome bug
3030 while ( right > 0 && data.getType( right - 1 ) === 'break' ) {
3031 right--;
3032 }
3033 return new ve.Range( left, right );
3034 };
3035
3036 /**
3037 * Helper to clean up externally pasted HTML (via pasteTarget).
3038 *
3039 * @param {jQuery} $element Root element containing pasted stuff to sanitize
3040 */
3041 ve.ce.Surface.prototype.afterPasteSanitizeExternal = function ( $element ) {
3042 const metadataIdRegExp = ve.init.platform.getMetadataIdRegExp();
3043
3044 // Remove the clipboard key
3045 $element.find( 'span[data-ve-clipboard-key]' ).remove();
3046 // Remove style tags (T185532)
3047 $element.find( 'style' ).remove();
3048 // If this is from external, run extra sanitization:
3049
3050 // Do some simple transforms to catch content that is using
3051 // spans+styles instead of regular tags. This is very much targeted at
3052 // the output of Google Docs, but should work with anything fairly-
3053 // similar. This is *fragile*, but more in the sense that small
3054 // deviations will stop it from working, rather than it being terribly
3055 // likely to incorrectly over-format things.
3056 // TODO: This might be cleaner if we could move the sanitization into
3057 // dm.converter entirely.
3058 $element.find( 'span' ).each( ( i, node ) => {
3059 // Later sanitization will replace completely-empty spans with
3060 // their contents, so we can lazily-wrap here without cleaning
3061 // up.
3062 if ( !node.style ) {
3063 return;
3064 }
3065 const $node = $( node );
3066 if ( +node.style.fontWeight >= 700 || node.style.fontWeight === 'bold' ) {
3067 $node.wrap( '<b>' );
3068 }
3069 if ( node.style.fontStyle === 'italic' ) {
3070 $node.wrap( '<i>' );
3071 }
3072 if ( node.style.textDecorationLine === 'underline' ) {
3073 $node.wrap( '<u>' );
3074 }
3075 if ( node.style.textDecorationLine === 'line-through' ) {
3076 $node.wrap( '<s>' );
3077 }
3078 if ( node.style.verticalAlign === 'super' ) {
3079 $node.wrap( '<sup>' );
3080 }
3081 if ( node.style.verticalAlign === 'sub' ) {
3082 $node.wrap( '<sub>' );
3083 }
3084 } );
3085
3086 // Remove style attributes. Any valid styles will be restored by data-ve-attributes.
3087 $element.find( '[style]' ).removeAttr( 'style' );
3088
3089 if ( metadataIdRegExp ) {
3090 $element.find( '[id]' ).each( ( i, el ) => {
3091 const $el = $( el );
3092 if ( metadataIdRegExp.test( $el.attr( 'id' ) ) ) {
3093 $el.removeAttr( 'id' );
3094 }
3095 } );
3096 }
3097
3098 // Remove the pasteProtect class (see #onCopy) and unwrap empty spans.
3099 $element.find( 'span' ).each( ( i, el ) => {
3100 const $el = $( el );
3101 $el.removeClass( 've-pasteProtect' );
3102 if ( $el.attr( 'class' ) === '' ) {
3103 $el.removeAttr( 'class' );
3104 }
3105 // Unwrap empty spans
3106 if ( !el.attributes.length ) {
3107 // childNodes is a NodeList
3108 // eslint-disable-next-line no-jquery/no-append-html
3109 $el.replaceWith( el.childNodes );
3110 }
3111 } );
3112
3113 // Restore attributes. See #onCopy.
3114 $element.find( '[data-ve-attributes]' ).each( ( i, el ) => {
3115 const attrsJSON = el.getAttribute( 'data-ve-attributes' );
3116
3117 // Always remove the attribute, even if the JSON has been corrupted
3118 el.removeAttribute( 'data-ve-attributes' );
3119
3120 let attrs;
3121 try {
3122 attrs = JSON.parse( attrsJSON );
3123 } catch ( err ) {
3124 // Invalid JSON
3125 return;
3126 }
3127 Object.keys( attrs ).forEach( ( attr ) => {
3128 ve.setAttributeSafe( el, attr, attrs[ attr ] );
3129 } );
3130 } );
3131 };
3132
3133 /**
3134 * Handle the insertion of a data transfer object
3135 *
3136 * @param {DataTransfer} dataTransfer Data transfer
3137 * @param {boolean} isPaste Handlers being used for paste
3138 * @param {ve.dm.SurfaceFragment} [targetFragment] Fragment to insert data items at, defaults to current selection
3139 * @return {boolean} One more items was handled
3140 */
3141 ve.ce.Surface.prototype.handleDataTransfer = function ( dataTransfer, isPaste, targetFragment ) {
3142 const items = [],
3143 htmlStringData = dataTransfer.getData( 'text/html' );
3144
3145 // Rules for clipboard content selection:
3146 // 1. If the clipboard has only HTML, proceed parsing such HTML.
3147 // 2. If the clipboard has only files, process them as-is.
3148 // 3. If the clipboard has both:
3149 // a. If the HTML in the clipboard contains only images and other elements with no text, process the image files.
3150 // b. Otherwise, ignore the files and process the HTML.
3151 //
3152 // Notes:
3153 // - If a file is pasted/dropped, it may have HTML fallback, such as an IMG node with alt text, for example.
3154 // - HTML generated from some clients has an image fallback(!) that is a screenshot of the HTML snippet (e.g. LibreOffice Calc)
3155 if ( !htmlStringData ) {
3156 if ( dataTransfer.items ) {
3157 for ( let i = 0, l = dataTransfer.items.length; i < l; i++ ) {
3158 if ( dataTransfer.items[ i ].kind !== 'string' ) {
3159 items.push( ve.ui.DataTransferItem.static.newFromItem( dataTransfer.items[ i ], htmlStringData ) );
3160 }
3161 }
3162 } else if ( dataTransfer.files ) {
3163 for ( let i = 0, l = dataTransfer.files.length; i < l; i++ ) {
3164 items.push( ve.ui.DataTransferItem.static.newFromBlob( dataTransfer.files[ i ], htmlStringData ) );
3165 }
3166 }
3167 } else if ( dataTransfer.files ) {
3168 const htmlPreParse = $.parseHTML( htmlStringData );
3169
3170 let imgCount = 0;
3171 let hasContent = false;
3172 for ( let i = 0; i < htmlPreParse.length; i++ ) {
3173 // Count images in root nodes
3174 if ( htmlPreParse[ i ].nodeName === 'IMG' ) {
3175 imgCount++;
3176 } else if (
3177 ( htmlPreParse[ i ].nodeType === 1 || htmlPreParse[ i ].nodeType === 3 ) &&
3178 htmlPreParse[ i ].textContent &&
3179 htmlPreParse[ i ].textContent.trim() !== ''
3180 ) {
3181 // Only count element nodes (type 1) or text nodes (type 3)
3182 // that have non empty text content.
3183 hasContent = true;
3184 }
3185
3186 // Count images in children
3187 if ( typeof htmlPreParse[ i ].querySelectorAll === 'function' ) {
3188 imgCount += htmlPreParse[ i ].querySelectorAll( 'img' ).length;
3189 }
3190 }
3191
3192 if ( !hasContent && imgCount === dataTransfer.files.length ) {
3193 for ( let i = 0, l = dataTransfer.files.length; i < l; i++ ) {
3194 // TODO: should we use image node outerHTML instead of htmlStringData?
3195 items.push( ve.ui.DataTransferItem.static.newFromBlob( dataTransfer.files[ i ], htmlStringData ) );
3196 }
3197 }
3198 }
3199
3200 if ( dataTransfer.items ) {
3201 // Extract "string" types.
3202 for ( let i = 0, l = dataTransfer.items.length; i < l; i++ ) {
3203 if (
3204 dataTransfer.items[ i ].kind === 'string' &&
3205 dataTransfer.items[ i ].type.slice( 0, 5 ) === 'text/'
3206 ) {
3207 items.push( ve.ui.DataTransferItem.static.newFromString(
3208 dataTransfer.getData( dataTransfer.items[ i ].type ),
3209 dataTransfer.items[ i ].type,
3210 htmlStringData
3211 ) );
3212 }
3213 }
3214 }
3215
3216 // We care a little bit about the order of items, as the first one matched
3217 // is going to be the one we handle, and don't trust dataTransfer.items to
3218 // be in the fallback order we'd prefer. In practice, this just means that
3219 // we want to text/html and text/plain to be at the end of the list, as
3220 // they tend to show up as common fallbacks.
3221 const pushItemToBack = function ( array, type ) {
3222 for ( let j = 0, jlen = array.length; j < jlen; j++ ) {
3223 if ( array[ j ].type === type ) {
3224 return array.push( array.splice( j, 1 )[ 0 ] );
3225 }
3226 }
3227 };
3228 pushItemToBack( items, 'text/html' );
3229 pushItemToBack( items, 'text/plain' );
3230
3231 return this.handleDataTransferItems( items, isPaste, targetFragment );
3232 };
3233
3234 /**
3235 * Handle the insertion of data transfer items
3236 *
3237 * @param {ve.ui.DataTransferItem[]} items Data transfer items
3238 * @param {boolean} isPaste Handlers being used for paste
3239 * @param {ve.dm.SurfaceFragment} [targetFragment] Fragment to insert data items at, defaults to current selection
3240 * @return {boolean} One more items was handled
3241 */
3242 ve.ce.Surface.prototype.handleDataTransferItems = function ( items, isPaste, targetFragment ) {
3243 targetFragment = targetFragment || this.getModel().getFragment();
3244
3245 function insert( docOrData ) {
3246 // For non-paste transfers, don't overwrite the selection
3247 const resultFragment = !isPaste ? targetFragment.collapseToEnd() : targetFragment;
3248 if ( docOrData instanceof ve.dm.Document ) {
3249 const rootChildren = docOrData.getDocumentNode().children;
3250 if (
3251 rootChildren[ 0 ] &&
3252 rootChildren[ 0 ].type === 'paragraph' &&
3253 ( !rootChildren[ 1 ] || rootChildren[ 1 ].type === 'internalList' )
3254 ) {
3255 resultFragment.insertDocument(
3256 docOrData,
3257 rootChildren[ 0 ].getRange()
3258 );
3259 } else {
3260 resultFragment.insertDocument( docOrData );
3261 }
3262 } else {
3263 resultFragment.insertContent( docOrData );
3264 }
3265 // The resultFragment's selection now covers the inserted content;
3266 // adjust selection to end of inserted content.
3267 resultFragment.collapseToEnd().select();
3268 }
3269
3270 const dataTransferHandlerFactory = this.getSurface().dataTransferHandlerFactory;
3271 let handled = false;
3272 for ( let i = 0, l = items.length; i < l; i++ ) {
3273 const item = items[ i ];
3274 const name = dataTransferHandlerFactory.getHandlerNameForItem( item, isPaste, this.pasteSpecial );
3275 if ( name ) {
3276 dataTransferHandlerFactory.create( name, this.surface, item )
3277 .getInsertableData().done( insert );
3278 handled = true;
3279 break;
3280 } else if ( isPaste && item.type === 'text/html' ) {
3281 // Don't handle anything else if text/html is available, as it is handled specially in #afterPaste
3282 break;
3283 }
3284 }
3285 return handled;
3286 };
3287
3288 /**
3289 * Select all the contents within the current context
3290 */
3291 ve.ce.Surface.prototype.selectAll = function () {
3292 const selection = this.getModel().getSelection(),
3293 dmDoc = this.getModel().getDocument();
3294
3295 if ( selection instanceof ve.dm.LinearSelection ) {
3296 const activeNode = this.getActiveNode();
3297 let range;
3298 if ( activeNode ) {
3299 range = activeNode.getRange();
3300 range = new ve.Range( range.from + 1, range.to - 1 );
3301 } else {
3302 const documentRange = this.getModel().getDocument().getDocumentRange();
3303 range = new ve.Range(
3304 dmDoc.getNearestCursorOffset( 0, 1 ),
3305 dmDoc.getNearestCursorOffset( documentRange.end, -1 )
3306 );
3307 }
3308 this.getModel().setLinearSelection( range );
3309 } else if ( selection instanceof ve.dm.TableSelection ) {
3310 const matrix = selection.getTableNode( dmDoc ).getMatrix();
3311 this.getModel().setSelection(
3312 new ve.dm.TableSelection(
3313 selection.tableRange,
3314 0, 0, matrix.getMaxColCount() - 1, matrix.getRowCount() - 1
3315 )
3316 );
3317 }
3318 };
3319
3320 /**
3321 * Handle beforeinput events.
3322 *
3323 * @param {jQuery.Event} e The input event
3324 */
3325 ve.ce.Surface.prototype.onDocumentBeforeInput = function ( e ) {
3326 if ( this.getSelection().isNativeCursor() ) {
3327 const inputType = e.originalEvent ? e.originalEvent.inputType : null;
3328
3329 // Support: Chrome (Android, Gboard)
3330 // Handle IMEs that emit text fragments with a trailing newline on Enter keypress (T312558)
3331 if (
3332 ( inputType === 'insertText' || inputType === 'insertCompositionText' ) &&
3333 e.originalEvent.data && e.originalEvent.data.slice( -1 ) === '\n'
3334 ) {
3335 // The event will have inserted a newline into the CE view,
3336 // so fix up the DM accordingly depending on the context.
3337 this.eventSequencer.afterOne( {
3338 beforeinput: this.fixupChromiumNativeEnter.bind( this )
3339 } );
3340 }
3341 }
3342 };
3343
3344 /**
3345 * Remove unwanted DOM elements from the CE view, inserted by Chromium's native Enter handling.
3346 * We preventDefault an Enter keydown event, but the native handling can still happen with some
3347 * IME combinations, e.g. Gboard on Android Chromium in many languages including English when
3348 * there is candidate text (T312558).
3349 */
3350 ve.ce.Surface.prototype.fixupChromiumNativeEnter = function () {
3351 const setCursorToEnd = ( element ) => {
3352 if ( !element ) {
3353 return;
3354 }
3355 const range = this.getElementDocument().createRange();
3356 range.setStart( element, element.childNodes.length );
3357 range.setEnd( element, element.childNodes.length );
3358 this.nativeSelection.removeAllRanges();
3359 this.nativeSelection.addRange( range );
3360 };
3361
3362 let fixedUp = false;
3363 // Test for Chromium native Enter inside a <li class="foo"><p class="bar">...</p></li>
3364 // creating unwanted trailing <li class="foo"><p class="bar"><br></p></li>,
3365 // assuming it (initially) leaves the selection in the original list item.
3366 const listItemNode = $( this.nativeSelection.focusNode ).closest( 'li.ve-ce-branchNode' )[ 0 ];
3367 if ( listItemNode ) {
3368 const nextNode = listItemNode.nextElementSibling;
3369 if ( nextNode && !$.data( nextNode, 'view' ) ) {
3370 // We infer the native Enter action added a spurious DOM node that does
3371 // not exist in the view. Remove it and flag that we need to perform a
3372 // VE Enter action.
3373 nextNode.parentNode.removeChild( nextNode );
3374 fixedUp = true;
3375 }
3376 }
3377 // Test for Chromium native Enter inside a <p class="foo"></p>, while there is
3378 // candidate text, creating a spurious trailing <div><br></div>, and (immediately)
3379 // putting the cursor inside it.
3380 //
3381 // Note if the paragraph is a grandchild of the list item, it's not clear under what
3382 // circumstances Chromium creates a div vs a list item, so perform this check even if
3383 // a fixup already happened in the lines of code above.
3384 const div = $( this.nativeSelection.focusNode ).closest( 'div' )[ 0 ];
3385 if ( div && this.$documentNode[ 0 ].contains( div ) && !$.data( div, 'view' ) ) {
3386 // The div is inside a branch node, but has no view. We infer the native Enter
3387 // action added a spurious DOM node that does not exist in the view. Remove it and
3388 // flag that we need to perform a VE enter action.
3389 setCursorToEnd( div.previousElementSibling );
3390 div.parentNode.removeChild( div );
3391 fixedUp = true;
3392 }
3393 // If we found nodes to fixup, that means the VE Enter handler never ran (since it would
3394 // have prevented the Enter event), so execute it now to perform the context-appropriate
3395 // operation.
3396 if ( fixedUp ) {
3397 // First, poll current node for content changes, because any autocorrect change
3398 // will not have reached the model. The logic above ensures the cursor will be
3399 // inside the ContentBranchNode where the user was typing in either case.
3400 this.surfaceObserver.pollOnce();
3401 ve.ce.keyDownHandlerFactory.lookup( 'linearEnter' ).static.execute( this, new Event( 'dummy' ) );
3402 }
3403 };
3404
3405 /**
3406 * Handle input events.
3407 *
3408 * @param {jQuery.Event} e The input event
3409 */
3410 ve.ce.Surface.prototype.onDocumentInput = function ( e ) {
3411 // Synthetic events don't have the originalEvent property (T176104)
3412 const inputType = e.originalEvent ? e.originalEvent.inputType : null;
3413
3414 // Special handling of NBSP insertions. T53045
3415 // NBSPs are converted to normal spaces in ve.ce.TextState as they can be
3416 // inserted by ContentEditable in unexpected places, or accidentally imported
3417 // by copy-paste. Usually they are not intended, but if we detect an NBSP in
3418 // an insertion event that means it was probably intentional, e.g. inserted
3419 // by a specific keyboard shortcut, or IME sequence.
3420 if (
3421 this.getSelection().isNativeCursor() &&
3422 ( inputType === 'insertText' || inputType === 'insertCompositionText' ) &&
3423 e.originalEvent.data === '\u00a0'
3424 ) {
3425 // Wait for the insertion to happen
3426 setTimeout( () => {
3427 const fragment = this.getModel().getFragment().adjustLinearSelection( -1 );
3428 let nbspContent = '&nbsp;';
3429 if ( this.getSurface().getMode() === 'visual' ) {
3430 nbspContent = ve.init.platform.decodeEntities( nbspContent );
3431 }
3432 // Check a plain space was inserted and replace it with an NBSP.
3433 if ( fragment.getText() === ' ' ) {
3434 fragment.insertContent( nbspContent ).collapseToEnd().select();
3435 }
3436 } );
3437 }
3438
3439 let command;
3440 const inputTypeCommands = this.constructor.static.inputTypeCommands;
3441 if ( inputType && Object.prototype.hasOwnProperty.call( inputTypeCommands, inputType ) ) {
3442 command = inputTypeCommands[ inputType ];
3443 }
3444 if ( command !== undefined ) {
3445 // Conditionally descend into commands like { collapsed: 'foo', uncollapsed: 'bar' }
3446 if ( command !== null && typeof command === 'object' ) {
3447 if ( this.getSelection().getModel().isCollapsed() ) {
3448 command = command.collapsed;
3449 } else {
3450 command = command.uncollapsed;
3451 }
3452 }
3453
3454 // command might be undefined again now
3455 if ( command !== undefined ) {
3456 if ( command === null ) {
3457 e.preventDefault();
3458 } else {
3459 this.getSurface().executeCommand( command );
3460 e.preventDefault();
3461 }
3462 return;
3463 }
3464 }
3465 this.incRenderLock();
3466 try {
3467 this.surfaceObserver.pollOnce();
3468 } finally {
3469 this.decRenderLock();
3470 }
3471 };
3472
3473 /**
3474 * Handle compositionstart events.
3475 * Note that their meaning varies between browser/OS/IME combinations
3476 *
3477 * @param {jQuery.Event} e The compositionstart event
3478 */
3479 ve.ce.Surface.prototype.onDocumentCompositionStart = function () {
3480 // Eagerly trigger emulated deletion on certain selections, to ensure a ContentEditable
3481 // native node merge never happens. See https://phabricator.wikimedia.org/T123716 .
3482 if (
3483 this.model.selection instanceof ve.dm.TableSelection &&
3484 $.client.profile().layout === 'gecko'
3485 ) {
3486 // Support: Firefox <= ~51
3487 // Work around a segfault on blur+focus in Firefox compositionstart handlers.
3488 // It would get triggered by handleInsertion emptying the table cell then putting
3489 // a linear selection inside it. See:
3490 // https://phabricator.wikimedia.org/T86589
3491 // https://bugzilla.mozilla.org/show_bug.cgi?id=1230473
3492 return;
3493 }
3494 this.handleInsertion();
3495 };
3496
3497 /* Custom Events */
3498
3499 /**
3500 * Handle model select events.
3501 *
3502 * @see ve.dm.Surface#method-change
3503 */
3504 ve.ce.Surface.prototype.onModelSelect = function () {
3505 const selection = this.getModel().getSelection();
3506
3507 setTimeout( this.findAndExecuteDelayedSequences.bind( this ) );
3508
3509 this.cursorDirectionality = null;
3510 this.contentBranchNodeChanged = false;
3511 this.selection = null;
3512
3513 if ( selection.isNull() ) {
3514 this.removeCursorHolders();
3515 }
3516
3517 if ( selection instanceof ve.dm.LinearSelection ) {
3518 const blockSlug = this.findBlockSlug( selection.getRange() );
3519 if ( blockSlug !== this.focusedBlockSlug ) {
3520 if ( this.focusedBlockSlug ) {
3521 this.focusedBlockSlug.classList.remove(
3522 've-ce-branchNode-blockSlug-focused'
3523 );
3524 this.focusedBlockSlug = null;
3525 }
3526
3527 if ( blockSlug ) {
3528 blockSlug.classList.add( 've-ce-branchNode-blockSlug-focused' );
3529 this.focusedBlockSlug = blockSlug;
3530 this.preparePasteTargetForCopy();
3531 }
3532 }
3533
3534 const focusedNode = this.findFocusedNode( selection.getRange() );
3535
3536 if ( this.isDeactivated() && !this.isShownAsDeactivated() && !blockSlug && !focusedNode ) {
3537 // If deactivated without showing (e.g. by preparePasteTargetForCopy),
3538 // reactivate when changing selection (T221291)
3539 // TODO: It is really messy that the surface can get reactivated based on the state of
3540 // a flag that should just be used for rendering (isShownAsDeactivated). This led to
3541 // T236400 so should be fixed.
3542 this.activate();
3543 }
3544
3545 // If focus has changed, update nodes and this.focusedNode
3546 if ( focusedNode !== this.focusedNode ) {
3547 if ( this.focusedNode ) {
3548 this.focusedNode.setFocused( false );
3549 this.focusedNode = null;
3550 }
3551 if ( focusedNode ) {
3552 focusedNode.setFocused( true );
3553 this.focusedNode = focusedNode;
3554
3555 // If dragging, we already have a native selection, so don't mess with it
3556 if ( !this.dragging ) {
3557 this.preparePasteTargetForCopy();
3558 // Since the selection is no longer in the root, clear the SurfaceObserver's
3559 // selection state. Otherwise, if the user places the selection back into the root
3560 // in exactly the same place where it was before, the observer won't consider that a change.
3561 this.surfaceObserver.clear();
3562 }
3563 }
3564 }
3565 } else {
3566 if ( selection instanceof ve.dm.TableSelection ) {
3567 this.preparePasteTargetForCopy();
3568 }
3569 if ( this.focusedNode ) {
3570 this.focusedNode.setFocused( false );
3571 }
3572 this.focusedNode = null;
3573 }
3574
3575 // Deactivate immediately if mobile and read-only to avoid showing keyboard (T281771)
3576 if ( this.isReadOnly() && OO.ui.isMobile() ) {
3577 this.deactivate( false, false, true );
3578 }
3579
3580 // Ignore the selection if changeModelSelection is currently being
3581 // called with the same (object-identical) selection object
3582 // (i.e. if the model is calling us back)
3583 if ( !this.isRenderingLocked() && selection !== this.newModelSelection ) {
3584 this.showModelSelection();
3585 this.cleanupUnicorns( false );
3586 }
3587 // Update the selection state in the SurfaceObserver
3588 this.surfaceObserver.pollOnceNoCallback();
3589 };
3590
3591 /**
3592 * Prepare the paste target for a copy event by selecting some text
3593 *
3594 * @param {boolean} force Force a native selection, even on mobile (used for click-to-copy)
3595 */
3596 ve.ce.Surface.prototype.preparePasteTargetForCopy = function ( force ) {
3597 // As FF won't fire a copy event with nothing selected, create a native selection.
3598 // If there is a focusedNode available, use its text content so that context menu
3599 // items such as "Search for [SELECTED TEXT]" make sense. If the text is empty or
3600 // whitespace, use a single unicode character as this is required for programmatic
3601 // selection to work correctly in all browsers (e.g. Safari won't select a single space).
3602 // #onCopy will ignore this native selection and use the DM selection
3603 if ( force || !OO.ui.isMobile() ) {
3604 this.$pasteTarget.text( ( this.focusedNode && this.focusedNode.$element.text().trim() ) || '☢' );
3605 ve.selectElement( this.$pasteTarget[ 0 ] );
3606 this.$pasteTarget[ 0 ].focus();
3607 } else {
3608 // Selecting the paste target fails on mobile:
3609 // * On iOS The selection stays visible and causes scrolling
3610 // * The user is unlikely to be able to trigger a keyboard copy anyway
3611 // Instead just deactivate the surface so the native cursor doesn't
3612 // get in the way and the on screen keyboard doesn't show.
3613 // TODO: Provide a copy tool in the context menu (T202278)
3614 this.deactivate( true );
3615 }
3616 };
3617
3618 /**
3619 * Get the focused node (optionally at a specified range), or null if one is not present
3620 *
3621 * @param {ve.Range} [range] Optional range to check for focused node, defaults to current selection's range
3622 * @return {ve.ce.Node|null} Focused node
3623 */
3624 ve.ce.Surface.prototype.getFocusedNode = function ( range ) {
3625 if ( !range ) {
3626 return this.focusedNode;
3627 }
3628 const selection = this.getModel().getSelection();
3629 if (
3630 selection instanceof ve.dm.LinearSelection &&
3631 range.equalsSelection( selection.getRange() )
3632 ) {
3633 return this.focusedNode;
3634 }
3635 return this.findFocusedNode( range );
3636 };
3637
3638 /**
3639 * Find the block slug a given range is in.
3640 *
3641 * @param {ve.Range} range Range to check
3642 * @return {HTMLElement|null} Slug, or null if no slug or if range is not collapsed
3643 * @throws {Error} If range is inside internal list
3644 */
3645 ve.ce.Surface.prototype.findBlockSlug = function ( range ) {
3646 if ( !range.isCollapsed() ) {
3647 return null;
3648 }
3649 const node = this.documentView.getBranchNodeFromOffset( range.end );
3650 if ( !node || !node.canHaveChildrenNotContent() ) {
3651 // Node can not have block slugs (only inline slugs)
3652 return null;
3653 }
3654 return node.getSlugAtOffset( range.end );
3655 };
3656
3657 /**
3658 * Find the focusedNode at a specified range
3659 *
3660 * @param {ve.Range} range Range to search at for a focusable node
3661 * @return {ve.ce.Node|null} Focused node
3662 */
3663 ve.ce.Surface.prototype.findFocusedNode = function ( range ) {
3664 const documentNode = this.getDocument().getDocumentNode();
3665 // Detect when only a single focusable element is selected
3666 let startNode;
3667 if ( !range.isCollapsed() ) {
3668 startNode = documentNode.getNodeFromOffset( range.start + 1 );
3669 if ( startNode && startNode.isFocusable() ) {
3670 const endNode = documentNode.getNodeFromOffset( range.end - 1 );
3671 if ( startNode === endNode ) {
3672 return startNode;
3673 }
3674 }
3675 } else {
3676 // Check if the range is inside a focusable node with a collapsed selection
3677 startNode = documentNode.getNodeFromOffset( range.start );
3678 if ( startNode && startNode.isFocusable() ) {
3679 return startNode;
3680 }
3681 }
3682 return null;
3683 };
3684
3685 /**
3686 * Handle documentUpdate events on the surface model.
3687 *
3688 * @fires ve.ce.Surface#position
3689 */
3690 ve.ce.Surface.prototype.onModelDocumentUpdate = function () {
3691 if ( this.contentBranchNodeChanged ) {
3692 // Update the selection state from model
3693 this.onModelSelect();
3694 }
3695 // Update the state of the SurfaceObserver
3696 this.surfaceObserver.pollOnceNoCallback();
3697 const wasSynchronizing = !!( this.getModel().synchronizer && this.getModel().synchronizer.applying );
3698 // setTimeout: Wait for other documentUpdate listeners to run before emitting
3699 setTimeout( () => {
3700 this.emit( 'position', wasSynchronizing );
3701 } );
3702 };
3703
3704 /**
3705 * Handle insertionAnnotationsChange events on the surface model.
3706 *
3707 * @param {ve.dm.AnnotationSet} insertionAnnotations
3708 */
3709 ve.ce.Surface.prototype.onInsertionAnnotationsChange = function () {
3710 const changed = this.renderSelectedContentBranchNode();
3711 if ( !changed ) {
3712 return;
3713 }
3714 // Must re-apply the selection after re-rendering
3715 this.forceShowModelSelection();
3716 this.surfaceObserver.pollOnceNoCallback();
3717 };
3718
3719 /**
3720 * Get the ContentBranchNode containing the selection focus, if any
3721 *
3722 * @return {ve.ce.ContentBranchNode|null} ContentBranchNode containing selection focus, or null
3723 */
3724 ve.ce.Surface.prototype.getSelectedContentBranchNode = function () {
3725 const selection = this.model.getSelection();
3726
3727 if ( !( selection instanceof ve.dm.LinearSelection ) ) {
3728 return null;
3729 }
3730 const node = this.documentView.getBranchNodeFromOffset( selection.getRange().to );
3731 if ( !node || !( node instanceof ve.ce.ContentBranchNode ) ) {
3732 return null;
3733 }
3734 return node;
3735 };
3736
3737 /**
3738 * Re-render the ContentBranchNode containing the selection focus, if any
3739 *
3740 * @return {boolean} Whether a re-render actually happened
3741 */
3742 ve.ce.Surface.prototype.renderSelectedContentBranchNode = function () {
3743 const node = this.getSelectedContentBranchNode();
3744 if ( !node ) {
3745 return false;
3746 }
3747 return node.renderContents();
3748 };
3749
3750 /**
3751 * Handle changes observed from the DOM
3752 *
3753 * These are normally caused by the user interacting directly with the contenteditable.
3754 *
3755 * @param {ve.ce.RangeState|null} oldState The prior range state, if any
3756 * @param {ve.ce.RangeState} newState The changed range state
3757 */
3758 ve.ce.Surface.prototype.handleObservedChanges = function ( oldState, newState ) {
3759 const dmDoc = this.getModel().getDocument();
3760
3761 let insertedText = false,
3762 removedText = false;
3763 if ( newState.contentChanged ) {
3764 if ( this.readOnly ) {
3765 newState.node.renderContents();
3766 this.showModelSelection();
3767 return;
3768 } else {
3769 const transaction = newState.textState.getChangeTransaction(
3770 oldState.textState,
3771 dmDoc,
3772 newState.node.getOffset(),
3773 newState.node.unicornAnnotations
3774 );
3775 if ( transaction ) {
3776 this.incRenderLock();
3777 try {
3778 this.changeModel( transaction );
3779 } finally {
3780 this.decRenderLock();
3781 }
3782 insertedText = transaction.operations.some( ( op ) => op.type === 'replace' && op.insert.length );
3783 removedText = transaction.operations.some( ( op ) => op.type === 'replace' && op.remove.length );
3784 }
3785 }
3786 }
3787
3788 if (
3789 !this.readOnly &&
3790 newState.branchNodeChanged &&
3791 oldState &&
3792 oldState.node &&
3793 oldState.node.root &&
3794 oldState.node instanceof ve.ce.ContentBranchNode
3795 ) {
3796 oldState.node.renderContents();
3797 }
3798
3799 if ( newState.selectionChanged && !(
3800 // Ignore when the newRange is just a flipped oldRange
3801 oldState &&
3802 oldState.veRange &&
3803 newState.veRange &&
3804 !newState.veRange.isCollapsed() &&
3805 oldState.veRange.equalsSelection( newState.veRange )
3806 ) ) {
3807 let newSelection;
3808 if ( newState.veRange ) {
3809 if ( newState.veRange.isCollapsed() ) {
3810 const offset = dmDoc.getNearestCursorOffset( newState.veRange.from, 0 );
3811 if ( offset === -1 ) {
3812 // First, if we're in a document which outright doesn't
3813 // have any content to select, don't try to set one. These
3814 // would be niche documents, since slugs normally exist
3815 // and catch those cases.
3816 newSelection = new ve.dm.NullSelection();
3817 // TODO: Unset whatever native selection got us here, to match
3818 // the model state (assuming it is in the CE document)
3819 } else {
3820 // If we're placing the cursor, make sure it winds up in a
3821 // cursorable location. Failure to do this can result in
3822 // strange behavior when inserting content immediately after
3823 // clicking on the surface.
3824 newSelection = new ve.dm.LinearSelection( new ve.Range( offset ) );
3825 }
3826 } else {
3827 newSelection = new ve.dm.LinearSelection( newState.veRange );
3828 }
3829 } else {
3830 newSelection = new ve.dm.NullSelection();
3831 }
3832 this.incRenderLock();
3833 try {
3834 this.changeModel( null, newSelection );
3835 if ( newSelection instanceof ve.dm.LinearSelection && newSelection.isCollapsed() ) {
3836 const blockSlug = this.findBlockSlug( newSelection.getRange() );
3837 if ( blockSlug ) {
3838 // Set the DOM selection, in case the model selection did not change but
3839 // the DOM selection did (T201599).
3840 this.preparePasteTargetForCopy();
3841 this.surfaceObserver.pollOnceNoCallback();
3842 }
3843 }
3844 } finally {
3845 this.decRenderLock();
3846 }
3847 const removedUnicorns = this.cleanupUnicorns( false );
3848 if ( removedUnicorns ) {
3849 this.surfaceObserver.pollOnceNoCallback();
3850 }
3851
3852 // Ensure we don't observe a selection that breaks out of the active node
3853 const activeNode = this.getActiveNode();
3854 const coveringRange = newSelection.getCoveringRange();
3855 if ( activeNode && coveringRange ) {
3856 const nodeRange = activeNode.getRange();
3857 const containsStart = nodeRange.containsRange( new ve.Range( coveringRange.start ) );
3858 const containsEnd = nodeRange.containsRange( new ve.Range( coveringRange.end ) );
3859 // If the range starts xor ends in the active node, but not both, then it must
3860 // span an active node boundary, so fixup.
3861 if ( containsStart !== containsEnd ) {
3862 newSelection = oldState && oldState.veRange ?
3863 new ve.dm.LinearSelection( oldState.veRange ) :
3864 new ve.dm.NullSelection();
3865 // TODO: setTimeout: document purpose
3866 setTimeout( () => {
3867 this.changeModel( null, newSelection );
3868 this.showModelSelection();
3869 } );
3870 }
3871 }
3872
3873 // Support: Firefox
3874 // Firefox lets you create multiple selections within a single paragraph
3875 // which our model doesn't support, so detect and prevent these.
3876 // This shouldn't create problems with IME candidates as only an explicit user
3877 // action can create a multiple selection (CTRL+click), and we remove it
3878 // immediately, so there can never be a multiple selection while the user is
3879 // typing text; therefore the selection change will never commit IME candidates
3880 // prematurely.
3881 while ( this.nativeSelection.rangeCount > 1 ) {
3882 // The current range is the last range, so remove ranges from the front
3883 this.nativeSelection.removeRange( this.nativeSelection.getRangeAt( 0 ) );
3884 }
3885 }
3886
3887 if ( insertedText ) {
3888 this.afterRenderLock( () => {
3889 this.findAndExecuteSequences();
3890 this.maybeSetBreakpoint();
3891 } );
3892 } else if ( removedText ) {
3893 this.afterRenderLock( () => {
3894 this.findAndExecuteSequences( false, true );
3895 this.maybeSetBreakpoint();
3896 } );
3897 }
3898 if ( newState.branchNodeChanged && newState.node ) {
3899 this.updateCursorHolders();
3900 this.showModelSelection();
3901 }
3902 if ( !insertedText ) {
3903 // Two likely cases here:
3904 // 1. The cursor moved. If so, fire off a breakpoint to catch any transactions
3905 // that were pending, in case a word was being typed.
3906 // 2. Text was deleted. If so, make a breakpoint. A future enhancement could be
3907 // to make this only break after a sequence of deletes. (Maybe combine new
3908 // breakpoints with the former breakpoint based on the new transactions?)
3909 this.getModel().breakpoint();
3910 }
3911 };
3912
3913 /**
3914 * Create a slug out of a DOM element
3915 *
3916 * @param {HTMLElement} element Slug element
3917 * @fires ve.ce.Surface#position
3918 */
3919 ve.ce.Surface.prototype.createSlug = function ( element ) {
3920 const offset = ve.ce.getOffsetOfSlug( element ),
3921 documentModel = this.getModel().getDocument(),
3922 slugHeight = element.scrollHeight;
3923
3924 this.changeModel( ve.dm.TransactionBuilder.static.newFromInsertion(
3925 documentModel, offset, [
3926 { type: 'paragraph', internal: { generated: 'slug' } },
3927 { type: '/paragraph' }
3928 ]
3929 ), new ve.dm.LinearSelection( new ve.Range( offset + 1 ) ) );
3930
3931 // Animate the slug open
3932 const $slug = this.getDocument().getDocumentNode().getNodeFromOffset( offset + 1 ).$element;
3933 const verticalPadding = $slug.innerHeight() - $slug.height();
3934 const targetMargin = $slug.css( 'margin' );
3935 const targetPadding = $slug.css( 'padding' );
3936 $slug.addClass( 've-ce-branchNode-newSlug' ).css( 'min-height', slugHeight - verticalPadding );
3937 requestAnimationFrame( () => {
3938 $slug.addClass( 've-ce-branchNode-newSlug-open' ).css( {
3939 margin: targetMargin,
3940 padding: targetPadding,
3941 'min-height': $slug.css( 'line-height' )
3942 } );
3943 $slug.one( 'transitionend', () => {
3944 this.emit( 'position' );
3945 // Animation finished, cleanup
3946 $slug
3947 .removeClass( 've-ce-branchNode-newSlug ve-ce-branchNode-newSlug-open' )
3948 .css( { margin: '', padding: '', 'min-height': '' } );
3949 } );
3950 } );
3951
3952 this.onModelSelect();
3953 };
3954
3955 /**
3956 * Move cursor if it is between annotation nails
3957 *
3958 * @param {number} direction Direction of travel, 1=forwards, -1=backwards, 0=unknown
3959 * @param {boolean} extend Whether the anchor should stay where it is
3960 *
3961 * TODO: Improve name
3962 */
3963 ve.ce.Surface.prototype.fixupCursorPosition = function ( direction, extend ) {
3964 // Default to moving start-wards, to mimic typical Chromium behaviour
3965 direction = direction > 0 ? 1 : -1;
3966
3967 if ( this.nativeSelection.rangeCount === 0 ) {
3968 return;
3969 }
3970 let node = this.nativeSelection.focusNode;
3971 let offset = this.nativeSelection.focusOffset;
3972 if ( node.nodeType !== Node.ELEMENT_NODE ) {
3973 return;
3974 }
3975 const previousNode = node.childNodes[ offset - 1 ];
3976 const nextNode = node.childNodes[ offset ];
3977
3978 if (
3979 !(
3980 previousNode &&
3981 previousNode.nodeType === Node.ELEMENT_NODE && (
3982 previousNode.classList.contains( 've-ce-nail-pre-open' ) ||
3983 previousNode.classList.contains( 've-ce-nail-pre-close' )
3984 )
3985 ) && !(
3986 nextNode &&
3987 nextNode.nodeType === Node.ELEMENT_NODE && (
3988 nextNode.classList.contains( 've-ce-nail-post-open' ) ||
3989 nextNode.classList.contains( 've-ce-nail-post-close' )
3990 )
3991 )
3992 ) {
3993 return;
3994 }
3995 // Between nails: cross the one in the specified direction
3996 let fixedPosition = ve.adjacentDomPosition(
3997 { node: node, offset: offset },
3998 direction,
3999 { stop: ve.isHardCursorStep }
4000 );
4001 node = fixedPosition.node;
4002 offset = fixedPosition.offset;
4003 if ( direction === -1 ) {
4004 // Support: Firefox
4005 // Moving startwards: left-bias the fixed position
4006 // Avoids Firefox bug "cursor disappears at left of img inside link":
4007 // https://bugzilla.mozilla.org/show_bug.cgi?id=1175495
4008 fixedPosition = ve.adjacentDomPosition(
4009 fixedPosition,
4010 direction,
4011 { stop: ve.isHardCursorStep }
4012 );
4013 if ( fixedPosition.node.nodeType === Node.TEXT_NODE ) {
4014 // Have crossed into a text node; go back to its end
4015 node = fixedPosition.node;
4016 offset = fixedPosition.node.length;
4017 }
4018 }
4019
4020 this.showSelectionState( new ve.SelectionState( {
4021 anchorNode: extend ? this.nativeSelection.anchorNode : node,
4022 anchorOffset: extend ? this.nativeSelection.anchorOffset : offset,
4023 focusNode: node,
4024 focusOffset: offset
4025 } ) );
4026 };
4027
4028 /**
4029 * Find sequence matches at the current surface offset
4030 *
4031 * @param {boolean} [isPaste] Whether this in the context of a paste
4032 * @param {boolean} [isDelete] Whether this is after content being deleted
4033 * @return {ve.ui.SequenceRegistry.Match[]}
4034 */
4035 ve.ce.Surface.prototype.findMatchingSequences = function ( isPaste, isDelete ) {
4036 const selection = this.getSelection();
4037
4038 if ( !selection.isNativeCursor() ) {
4039 return [];
4040 }
4041
4042 return this.getSurface().sequenceRegistry.findMatching(
4043 this.getModel().getDocument().data,
4044 selection.getModel().getCoveringRange().end,
4045 isPaste,
4046 isDelete
4047 );
4048 };
4049
4050 /**
4051 * Find sequence matches at the current surface offset and execute them
4052 *
4053 * @param {boolean} [isPaste] Whether this in the context of a paste
4054 * @param {boolean} [isDelete] Whether this is after content being deleted
4055 */
4056 ve.ce.Surface.prototype.findAndExecuteSequences = function ( isPaste, isDelete ) {
4057 this.executeSequences( this.findMatchingSequences( isPaste, isDelete ) );
4058 };
4059
4060 // Deprecated alias
4061 ve.ce.Surface.prototype.checkSequences = ve.ce.Surface.prototype.findAndExecuteSequences;
4062
4063 /**
4064 * Check if any of the previously delayed sequences no longer match with current offset,
4065 * and therefore should be executed.
4066 */
4067 ve.ce.Surface.prototype.findAndExecuteDelayedSequences = function () {
4068 const sequences = [],
4069 selection = this.getSelection();
4070
4071 let matchingSequences;
4072 if ( this.deactivated || !selection.isNativeCursor() ) {
4073 matchingSequences = [];
4074 } else {
4075 matchingSequences = this.findMatchingSequences();
4076 }
4077 const matchingByName = {};
4078 let i;
4079 for ( i = 0; i < matchingSequences.length; i++ ) {
4080 matchingByName[ matchingSequences[ i ].sequence.getName() ] = matchingSequences[ i ];
4081 }
4082
4083 for ( i = 0; i < this.delayedSequences.length; i++ ) {
4084 const matchingSeq = matchingByName[ this.delayedSequences[ i ].sequence.getName() ];
4085 if (
4086 !matchingSeq ||
4087 matchingSeq.range.start !== this.delayedSequences[ i ].range.start
4088 ) {
4089 // This sequence stopped matching; execute it with the previously saved range
4090 this.delayedSequences[ i ].wasDelayed = true;
4091 sequences.push( this.delayedSequences[ i ] );
4092 }
4093 }
4094 // Discard any delayed sequences; they will be checked for again when the user starts typing
4095 this.delayedSequences = [];
4096
4097 this.executeSequences( sequences );
4098 };
4099
4100 // Deprecated alias
4101 ve.ce.Surface.prototype.checkDelayedSequences = ve.ce.Surface.prototype.findAndExecuteDelayedSequences;
4102
4103 /**
4104 * Execute matched sequences
4105 *
4106 * @param {ve.ui.SequenceRegistry.Match[]} sequences
4107 */
4108 ve.ce.Surface.prototype.executeSequences = function ( sequences ) {
4109 let executed = false;
4110
4111 // sequences.length will likely be 0 or 1 so don't cache
4112 for ( let i = 0; i < sequences.length; i++ ) {
4113 if ( sequences[ i ].sequence.delayed && !sequences[ i ].wasDelayed ) {
4114 // Save the sequence and match range for execution later
4115 this.delayedSequences.push( sequences[ i ] );
4116 } else {
4117 executed = sequences[ i ].sequence.execute( this.surface, sequences[ i ].range ) || executed;
4118 }
4119 }
4120 if ( executed ) {
4121 this.delayedSequences = [];
4122 this.showModelSelection();
4123 }
4124 };
4125
4126 /**
4127 * See if the just-entered content fits our criteria for setting a history breakpoint
4128 */
4129 ve.ce.Surface.prototype.maybeSetBreakpoint = function () {
4130 const selection = this.getSelection();
4131
4132 if ( !selection.isNativeCursor() ) {
4133 return;
4134 }
4135
4136 // We have just entered text, probably. We want to know whether we just
4137 // created a word break. We can't check the current offset, since the
4138 // common case is that being at the end of the string, which is inherently
4139 // a word break. So, we check whether the previous offset is a word break,
4140 // which should catch cases where we have hit space or added punctuation.
4141 // We use getWordRange because it handles the unicode cases, and accounts
4142 // for single-character words where a space back is a word break because
4143 // it's the *start* of a word.
4144
4145 // Note: Text input which isn't using word breaks, for whatever reason,
4146 // will get breakpoints set by the fallback timer anyway. This is the
4147 // main reason to not debounce that timer here, as then a reasonable
4148 // typist with such text would never get a breakpoint set. The compromise
4149 // position here will occasionally get a breakpoint set in the middle of
4150 // the first word typed.
4151
4152 const offset = selection.getModel().getCoveringRange().end - 1;
4153 const data = this.getModel().getDocument().data;
4154 if ( data.getWordRange( offset ).end === offset ) {
4155 this.getModel().breakpoint();
4156 }
4157 };
4158
4159 /**
4160 * Handle window resize event.
4161 *
4162 * @param {jQuery.Event} e Window resize event
4163 * @fires ve.ce.Surface#position
4164 */
4165 ve.ce.Surface.prototype.onWindowResize = function () {
4166 this.emit( 'position' );
4167 if ( OO.ui.isMobile() && !ve.init.platform.constructor.static.isIos() ) {
4168 // A resize event on mobile is probably a keyboard open/close (or rotate).
4169 // Either way, ensure the cursor is still visible (T204388).
4170 // On iOS, window is resized whenever you start scrolling down and the "address bar" is
4171 // minimized. So don't scroll back up…
4172 this.getSurface().scrollSelectionIntoView();
4173 }
4174 };
4175
4176 /* Relocation */
4177
4178 /**
4179 * Start a relocation action.
4180 *
4181 * @fires ve.ce.Surface#relocationStart
4182 */
4183 ve.ce.Surface.prototype.startRelocation = function () {
4184 // Cache the selection and selectedNode when the drag starts, to
4185 // avoid having to recompute them while dragging.
4186 this.relocatingSelection = this.getModel().getSelection();
4187 this.relocatingNode = this.getModel().getSelectedNode();
4188 this.emit( 'relocationStart' );
4189 };
4190
4191 /**
4192 * Complete a relocation action.
4193 *
4194 * @fires ve.ce.Surface#relocationEnd
4195 */
4196 ve.ce.Surface.prototype.endRelocation = function () {
4197 this.relocatingSelection = null;
4198 this.relocatingNode = null;
4199 // Trigger a drag leave event to clear markers
4200 this.onDocumentDragLeave();
4201 this.emit( 'relocationEnd' );
4202 };
4203
4204 /**
4205 * Set the active node
4206 *
4207 * @param {ve.ce.Node|null} node Active node
4208 */
4209 ve.ce.Surface.prototype.setActiveNode = function ( node ) {
4210 this.activeNode = node;
4211 };
4212
4213 /**
4214 * Get the active node
4215 *
4216 * @return {ve.ce.Node|null} Active node
4217 */
4218 ve.ce.Surface.prototype.getActiveNode = function () {
4219 return this.activeNode;
4220 };
4221
4222 /* Utilities */
4223
4224 /**
4225 * Store a state snapshot at a keydown event, to be used in an after-keydown handler
4226 *
4227 * A ve.SelectionState object is stored, but only when the key event is a cursor key.
4228 * (It would be misleading to save selection properties for key events where the DOM might get
4229 * modified, because anchorNode/focusNode are live and mutable, and so the offsets may come to
4230 * point confusingly to different places than they did when the selection was saved).
4231 *
4232 * @param {jQuery.Event|null} e Key down event; must be active when this call is made
4233 */
4234 ve.ce.Surface.prototype.storeKeyDownState = function ( e ) {
4235 this.keyDownState.event = e;
4236 this.keyDownState.selectionState = null;
4237
4238 if ( this.nativeSelection.rangeCount > 0 && e && (
4239 e.keyCode === OO.ui.Keys.UP ||
4240 e.keyCode === OO.ui.Keys.DOWN ||
4241 e.keyCode === OO.ui.Keys.LEFT ||
4242 e.keyCode === OO.ui.Keys.RIGHT
4243 ) ) {
4244 this.keyDownState.selectionState = new ve.SelectionState( this.nativeSelection );
4245 }
4246 };
4247
4248 /**
4249 * Clear a stored state snapshot from a key down event
4250 */
4251 ve.ce.Surface.prototype.clearKeyDownState = function () {
4252 this.keyDownState.event = null;
4253 this.keyDownState.selectionState = null;
4254 };
4255
4256 /**
4257 * Move the DM surface cursor
4258 *
4259 * @param {number} offset Distance to move (negative = toward document start)
4260 */
4261 ve.ce.Surface.prototype.moveModelCursor = function ( offset ) {
4262 const selection = this.model.getSelection();
4263 if ( selection instanceof ve.dm.LinearSelection ) {
4264 this.model.setLinearSelection( this.model.getDocument().getRelativeRange(
4265 selection.getRange(),
4266 offset,
4267 'character',
4268 false
4269 ) );
4270 }
4271 };
4272
4273 /**
4274 * Get the directionality at the current focused node
4275 *
4276 * @return {string} 'ltr' or 'rtl'
4277 */
4278 ve.ce.Surface.prototype.getFocusedNodeDirectionality = function () {
4279 // Use stored directionality if we have one.
4280 if ( this.cursorDirectionality ) {
4281 return this.cursorDirectionality;
4282 }
4283
4284 // Else fall back on the CSS directionality of the focused node at the DM selection focus,
4285 // which is less reliable because it does not take plaintext bidi into account.
4286 // (range.to will actually be at the edge of the focused node, but the
4287 // CSS directionality will be the same).
4288 const range = this.model.getSelection().getRange();
4289 let cursorNode = this.getDocument().getNodeAndOffset( range.to ).node;
4290 if ( cursorNode.nodeType === Node.TEXT_NODE ) {
4291 cursorNode = cursorNode.parentNode;
4292 }
4293 return $( cursorNode ).css( 'direction' );
4294 };
4295
4296 /**
4297 * Restore the selection from the model if expands outside the active node
4298 *
4299 * This is only useful if the DOM selection and the model selection are out of sync.
4300 *
4301 * @return {boolean} Whether the selection was restored
4302 */
4303 ve.ce.Surface.prototype.restoreActiveNodeSelection = function () {
4304 const activeNode = this.getActiveNode(),
4305 activeRange = activeNode && activeNode.getRange();
4306
4307 let currentRange;
4308 if (
4309 activeRange &&
4310 ( currentRange = ve.ce.veRangeFromSelection( this.nativeSelection ) ) &&
4311 ( !currentRange.isCollapsed() || activeNode.trapsCursor() ) &&
4312 !activeRange.containsRange( currentRange )
4313 ) {
4314 this.showModelSelection();
4315 return true;
4316 } else {
4317 return false;
4318 }
4319 };
4320
4321 /**
4322 * Find a ce=false branch node that a native cursor movement from here *might* skip
4323 *
4324 * If a node is returned, then it might get skipped by a single native cursor
4325 * movement in the specified direction from the closest branch node at the
4326 * current cursor focus. However, if null is returned, then any single such
4327 * movement is guaranteed *not* to skip an uneditable branch node.
4328 *
4329 * Note we cannot predict precisely where/with which cursor key we might step out
4330 * of the current closest branch node, because it is difficult to predict the
4331 * behaviour of left/rightarrow (because of bidi visual cursoring) and
4332 * up/downarrow (because of wrapping).
4333 *
4334 * @param {number} direction -1 for before the cursor, +1 for after
4335 * @return {Node|null} Potentially cursor-adjacent uneditable branch node, or null
4336 */
4337 ve.ce.Surface.prototype.findAdjacentUneditableBranchNode = function ( direction ) {
4338 const activeNode = this.getActiveNode(),
4339 forward = direction > 0;
4340
4341 let node = $( this.nativeSelection.focusNode ).closest(
4342 '.ve-ce-branchNode,.ve-ce-leafNode,.ve-ce-surface-paste'
4343 )[ 0 ];
4344 if ( !node || node.classList.contains( 've-ce-surface-paste' ) ) {
4345 return null;
4346 }
4347
4348 // Walk in document order till we find a ContentBranchNode (in which case
4349 // return null) or a FocusableNode/TableNode (in which case return the node)
4350 // or run out of nodes (in which case return null)
4351 while ( true ) {
4352 // Step up until we find a sibling
4353 while ( !( forward ? node.nextSibling : node.previousSibling ) ) {
4354 node = node.parentNode;
4355 if ( node === null ) {
4356 // Reached the document start/end
4357 return null;
4358 }
4359 }
4360 // Step back
4361 node = forward ? node.nextSibling : node.previousSibling;
4362 // Check and step down
4363 while ( true ) {
4364 if (
4365 $.data( node, 'view' ) instanceof ve.ce.ContentBranchNode ||
4366 // We shouldn't ever hit a raw text node, because they
4367 // should all be wrapped in CBNs or focusable nodes, but
4368 // just in case…
4369 node.nodeType === Node.TEXT_NODE
4370 ) {
4371 // This is cursorable (must have content or slugs)
4372 return null;
4373 }
4374 if ( $( node ).is( '.ve-ce-focusableNode,.ve-ce-tableNode' ) ) {
4375 if ( activeNode ) {
4376 const viewNode = $( node ).data( 'view' );
4377 if ( !activeNode.getRange().containsRange( viewNode.getRange() ) ) {
4378 // Node is outside the active node
4379 return null;
4380 }
4381 }
4382 return node;
4383 }
4384 if ( !node.childNodes || node.childNodes.length === 0 ) {
4385 break;
4386 }
4387 node = forward ? node.firstChild : node.lastChild;
4388 }
4389 }
4390 };
4391
4392 /**
4393 * Insert cursor holders, if they might be required as a cursor target
4394 */
4395 ve.ce.Surface.prototype.updateCursorHolders = function () {
4396 this.updateCursorHolderBefore();
4397 this.updateCursorHolderAfter();
4398 };
4399
4400 /**
4401 * Insert cursor holder between selection focus and subsequent ce=false node, if required as a cursor target
4402 */
4403 ve.ce.Surface.prototype.updateCursorHolderBefore = function () {
4404 const doc = this.getElementDocument(),
4405 nodeBelow = this.findAdjacentUneditableBranchNode( 1 );
4406 if (
4407 !( nodeBelow === null && this.cursorHolderBefore === null ) &&
4408 !( nodeBelow && this.cursorHolderBefore && nodeBelow.nextSibling === this.cursorHolderBefore )
4409 ) {
4410 // cursorHolderBefore is not correct for nodeBelow; update it
4411 this.removeCursorHolderBefore();
4412 if ( nodeBelow ) {
4413 this.cursorHolderBefore = doc.importNode( this.constructor.static.cursorHolderTemplate, true );
4414 this.cursorHolderBefore.classList.add( 've-ce-cursorHolder-before' );
4415 if ( ve.inputDebug ) {
4416 this.cursorHolderBefore.classList.add( 've-ce-cursorHolder-debug' );
4417 }
4418 // this.cursorHolderBefore is a Node
4419 // eslint-disable-next-line no-jquery/no-append-html
4420 $( nodeBelow ).before( this.cursorHolderBefore );
4421 }
4422 }
4423 };
4424
4425 /**
4426 * Insert cursor holder between selection focus and preceding ce=false node, if required as a cursor target
4427 */
4428 ve.ce.Surface.prototype.updateCursorHolderAfter = function () {
4429 const doc = this.getElementDocument(),
4430 nodeAbove = this.findAdjacentUneditableBranchNode( -1 );
4431 if (
4432 !( nodeAbove === null && this.cursorHolderAfter === null ) &&
4433 !( nodeAbove && this.cursorHolderAfter && nodeAbove.nextSibling === this.cursorHolderAfter )
4434 ) {
4435 // cursorHolderAfter is not correct for nodeAbove; update it
4436 this.removeCursorHolderAfter();
4437 if ( nodeAbove ) {
4438 this.cursorHolderAfter = doc.importNode( this.constructor.static.cursorHolderTemplate, true );
4439 this.cursorHolderAfter.classList.add( 've-ce-cursorHolder-after' );
4440 if ( ve.inputDebug ) {
4441 this.cursorHolderAfter.classList.add( 've-ce-cursorHolder-debug' );
4442 }
4443 // this.cursorHolderAfter is a Node
4444 // eslint-disable-next-line no-jquery/no-append-html
4445 $( nodeAbove ).after( this.cursorHolderAfter );
4446 }
4447 }
4448 };
4449
4450 /**
4451 * Remove cursor holders, if they exist
4452 */
4453 ve.ce.Surface.prototype.removeCursorHolders = function () {
4454 this.removeCursorHolderBefore();
4455 this.removeCursorHolderAfter();
4456 };
4457
4458 /**
4459 * Remove cursorHolderBefore, if it exists
4460 */
4461 ve.ce.Surface.prototype.removeCursorHolderBefore = function () {
4462 if ( this.cursorHolderBefore ) {
4463 if ( this.cursorHolderBefore.parentNode ) {
4464 this.cursorHolderBefore.parentNode.removeChild( this.cursorHolderBefore );
4465 }
4466 this.cursorHolderBefore = null;
4467 }
4468 };
4469
4470 /**
4471 * Remove cursorHolderAfter, if it exists
4472 */
4473 ve.ce.Surface.prototype.removeCursorHolderAfter = function () {
4474 if ( this.cursorHolderAfter ) {
4475 if ( this.cursorHolderAfter.parentNode ) {
4476 this.cursorHolderAfter.parentNode.removeChild( this.cursorHolderAfter );
4477 }
4478 this.cursorHolderAfter = null;
4479 }
4480 };
4481
4482 /**
4483 * Handle insertion of content.
4484 */
4485 ve.ce.Surface.prototype.handleInsertion = function () {
4486 const surfaceModel = this.getModel(),
4487 fragment = surfaceModel.getFragment();
4488
4489 let selection = this.getSelection();
4490 if ( selection instanceof ve.ce.TableSelection ) {
4491 // Collapse table selection to anchor cell
4492 surfaceModel.setSelection( selection.getModel().collapseToFrom() );
4493 // Delete the current contents
4494 ve.ce.keyDownHandlerFactory.lookup( 'tableDelete' ).static.execute( this );
4495 // Place selection inside the cell
4496 this.documentView.getBranchNodeFromOffset( selection.getModel().tableRange.start + 1 ).setEditing( true );
4497 // Selection has changed, update
4498 selection = this.getSelection();
4499 } else if ( selection.isFocusedNode() ) {
4500 // Don't allow a user to delete a non-table focusable node just by typing
4501 return;
4502 }
4503
4504 if ( !( selection instanceof ve.ce.LinearSelection ) ) {
4505 return;
4506 }
4507
4508 const range = selection.getModel().getRange();
4509
4510 // Handles removing expanded selection before inserting new text
4511 if (
4512 this.selectionSplitsNailedAnnotation() ||
4513 ( !range.isCollapsed() && !this.documentView.rangeInsideOneLeafNode( range ) )
4514 ) {
4515 // Remove the selection to force its re-application from the DM (even if the
4516 // DM is too granular to detect the selection change)
4517 surfaceModel.setNullSelection();
4518 fragment.removeContent().collapseToStart().select();
4519 this.surfaceObserver.clear();
4520 this.storeKeyDownState( this.keyDownState.event );
4521 this.surfaceObserver.stopTimerLoop();
4522 this.surfaceObserver.pollOnce();
4523 }
4524 };
4525
4526 /**
4527 * Place the selection at the next content offset which is selectable.
4528 *
4529 * For the purposes of this method, offsets within ve.ce.ActiveNode's
4530 * are not considered selectable when they are not active.
4531 *
4532 * @param {number} startOffset Offset to start from
4533 * @param {number} direction Search direction, -1 for left and 1 for right
4534 * @param {number} [endOffset] End offset to stop searching at
4535 * @return {number} Content offset, or -1 of not found
4536 */
4537 ve.ce.Surface.prototype.getRelativeSelectableContentOffset = function ( startOffset, direction, endOffset ) {
4538 const documentView = this.getDocument(),
4539 linearData = this.getModel().getDocument().data;
4540
4541 let nextOffset = linearData.getRelativeOffset(
4542 startOffset,
4543 direction,
4544 ( offset ) => {
4545 // Check we are at a content offset, according to the model
4546 if ( !linearData.isContentOffset( offset ) ) {
4547 return false;
4548 }
4549 const branchNode = documentView.getBranchNodeFromOffset( offset );
4550 if ( !branchNode ) {
4551 // This shouldn't happen in a content offset
4552 return false;
4553 }
4554 // traverseUpstream stops on a false return
4555 const noAutoFocusContainer = branchNode.traverseUpstream( ( node ) => node.autoFocus() );
4556 if ( noAutoFocusContainer ) {
4557 // Don't try to place the cursor in a node which has a container with autoFocus set to false
4558 return false;
4559 }
4560 return true;
4561 }
4562 );
4563
4564 if (
4565 endOffset !== undefined && (
4566 ( direction > 0 && nextOffset > endOffset ) ||
4567 ( direction < 0 && nextOffset < endOffset )
4568 )
4569 ) {
4570 nextOffset = -1;
4571 }
4572
4573 return nextOffset;
4574 };
4575
4576 /**
4577 * Select the offset returned by #getRelativeSelectableContentOffset
4578 *
4579 * @param {number} startOffset
4580 * @param {number} direction
4581 * @param {number} [endOffset]
4582 */
4583 ve.ce.Surface.prototype.selectRelativeSelectableContentOffset = function ( startOffset, direction, endOffset ) {
4584 const offset = this.getRelativeSelectableContentOffset( startOffset, direction, endOffset );
4585 if ( offset !== -1 ) {
4586 // Found an offset
4587 this.getModel().setLinearSelection( new ve.Range( offset ) );
4588 } else {
4589 // Nowhere sensible to put the cursor
4590 this.getModel().setNullSelection();
4591 }
4592 };
4593
4594 /**
4595 * Select the first content offset which is selectable.
4596 *
4597 * See #selectRelativeSelectableContentOffset for the definition of selectable.
4598 */
4599 ve.ce.Surface.prototype.selectFirstSelectableContentOffset = function () {
4600 this.selectRelativeSelectableContentOffset(
4601 this.getModel().getDocument().getAttachedRoot().getOffset(),
4602 1
4603 );
4604 };
4605
4606 /**
4607 * Select the last content offset which is selectable.
4608 *
4609 * See #selectRelativeSelectableContentOffset for the definition of selectable.
4610 */
4611 ve.ce.Surface.prototype.selectLastSelectableContentOffset = function () {
4612 this.selectRelativeSelectableContentOffset(
4613 this.getModel().getDocument().getDocumentRange().end,
4614 -1
4615 );
4616 };
4617
4618 /**
4619 * Get an approximate range covering data visible in the viewport
4620 *
4621 * It is assumed that vertical offset increases as you progress through the DM.
4622 * Items with custom positioning may throw off results given by this method, so
4623 * it should only be treated as an approximation.
4624 *
4625 * If the document doesn't contain any content offsets (e.g. it only contains
4626 * a transclusion), the returned range will cover the entire document. If the
4627 * single element is particularly large this might be very distinct from the
4628 * visible content.
4629 *
4630 * @param {boolean} [covering] Get a range which fully covers the viewport, otherwise
4631 * get a range which is full contained within the viewport.
4632 * @param {number} [padding=0] Increase computed size of viewport by this amount at the top and bottom
4633 * @return {ve.Range|null} Range covering data visible in the viewport, null if the surface is not attached
4634 */
4635 ve.ce.Surface.prototype.getViewportRange = function ( covering, padding ) {
4636 const documentModel = this.getModel().getDocument(),
4637 data = documentModel.data,
4638 dimensions = this.surface.getViewportDimensions();
4639
4640 if ( !dimensions ) {
4641 // Surface is not attached
4642 return null;
4643 }
4644
4645 padding = padding || 0;
4646 const top = Math.max( 0, dimensions.top - padding );
4647 const bottom = dimensions.bottom + ( padding * 2 );
4648 const documentRange = this.attachedRoot === this.getDocument().getDocumentNode() ?
4649 this.getModel().getDocument().getDocumentRange() :
4650 this.attachedRoot.getRange();
4651
4652 const highestIgnoreChildrenNode = ( childNode ) => {
4653 let ignoreChildrenNode = null;
4654 childNode.traverseUpstream( ( node ) => {
4655 if ( node.shouldIgnoreChildren() ) {
4656 ignoreChildrenNode = node;
4657 }
4658 } );
4659 return ignoreChildrenNode;
4660 };
4661
4662 /**
4663 * @param {number} offset Vertical offset to find
4664 * @param {ve.Range} range Document range
4665 * @param {string} side Side of the viewport align with, 'bottom' or 'top'
4666 * @param {boolean} isStart Find the start of the range, otherwise the end
4667 * @return {number} DM offset
4668 */
4669 const binarySearch = ( offset, range, side, isStart ) => {
4670 let start = range.start,
4671 end = range.end,
4672 lastLength = Infinity;
4673
4674 while ( range.getLength() < lastLength ) {
4675 lastLength = range.getLength();
4676 let mid = Math.round( ( range.start + range.end ) / 2 );
4677 let midNode = documentModel.documentNode.getNodeFromOffset( mid );
4678 const ignoreChildrenNode = highestIgnoreChildrenNode( midNode );
4679
4680 if ( ignoreChildrenNode ) {
4681 const nodeRange = ignoreChildrenNode.getOuterRange();
4682 mid = side === 'top' ? nodeRange.end : nodeRange.start;
4683 } else {
4684 mid = data.getNearestContentOffset( mid );
4685 if ( mid === -1 ) {
4686 // There is no content offset available in this document.
4687 // Return early, with a range that'll be covering the entire document.
4688 return isStart ? start : end;
4689 }
4690 // Never search outisde the original range
4691 mid = Math.max( Math.min( mid, range.end ), range.start );
4692 }
4693
4694 let rect = null;
4695 while ( !rect ) {
4696 // Try to create a selection of one character for more reliable
4697 // behaviour when text wraps.
4698 let contentRange;
4699 if ( data.isContentOffset( mid + 1 ) ) {
4700 contentRange = new ve.Range( mid, mid + 1 );
4701 } else if ( data.isContentOffset( mid - 1 ) ) {
4702 contentRange = new ve.Range( mid - 1, mid );
4703 } else {
4704 contentRange = new ve.Range( mid );
4705 }
4706 rect = this.getSelection( new ve.dm.LinearSelection( contentRange ) ).getSelectionBoundingRect();
4707
4708 // Node at contentRange is not rendered, find rendered parent
4709 if ( !rect ) {
4710 if ( !midNode ) {
4711 throw new Error( 'Offset has no rendered node container' );
4712 }
4713 const midNodeRange = midNode.getOuterRange();
4714 // Find the nearest content offset outside the invisible node
4715 mid = side === 'top' ?
4716 data.getRelativeContentOffset( midNodeRange.end, 1 ) :
4717 data.getRelativeContentOffset( midNodeRange.start, -1 );
4718
4719 // Never search outisde the original range
4720 mid = Math.max( Math.min( mid, range.end ), range.start );
4721
4722 // Check we didn't end up inside the invisible node again
4723 if ( midNodeRange.containsRange( new ve.Range( mid ) ) ) {
4724 return isStart ? start : end;
4725 }
4726 // Ensure we check parent in next iteration
4727 midNode = midNode.parent;
4728 }
4729 }
4730 if ( rect[ side ] >= offset ) {
4731 end = mid;
4732 range = new ve.Range( range.start, end );
4733 } else {
4734 start = mid;
4735 range = new ve.Range( start, range.end );
4736 }
4737 }
4738 return side === 'bottom' ? start : end;
4739 };
4740
4741 return new ve.Range(
4742 binarySearch( top, documentRange, covering ? 'bottom' : 'top', true ),
4743 binarySearch( bottom, documentRange, covering ? 'top' : 'bottom', false )
4744 );
4745 };
4746
4747 /**
4748 * Move the selection to the first visible "start content offset" in the viewport
4749 *
4750 * Where "start content offset" is the first offset within a content branch node.
4751 *
4752 * The following are used as fallbacks when such offsets can't be found:
4753 * - The first visible content offset (at any position in the CBN)
4754 * - The first selectable content offset in the doc (if fallbackToFirst is set)
4755 *
4756 * @param {boolean} [fallbackToFirst] Whether to select the first content offset if a visible offset can't be found
4757 */
4758 ve.ce.Surface.prototype.selectFirstVisibleStartContentOffset = function ( fallbackToFirst ) {
4759 // When scrolled. add about one line height of padding so the browser doesn't try to scroll the line above the cursor into view
4760 const dimensions = this.surface.getViewportDimensions();
4761 const offset = dimensions && dimensions.top ? -20 : 0;
4762 const visibleRange = this.getViewportRange( false, offset );
4763 if ( visibleRange ) {
4764 const model = this.getModel();
4765 let startNodeOffset = -1;
4766 const contentOffset = this.getRelativeSelectableContentOffset( Math.max( visibleRange.start - 1, 0 ), 1, visibleRange.end );
4767 if ( contentOffset !== -1 ) {
4768 const branchNodeRange = model.getDocument().getBranchNodeFromOffset( contentOffset ).getRange();
4769 if ( contentOffset === branchNodeRange.start ) {
4770 // We luckily landed and the start of a branch node
4771 startNodeOffset = contentOffset;
4772 } else {
4773 // We are in the middle of a branch node, move to the end, then find the next
4774 // content offset, which should be the start of the next CBN
4775 const nextContentOffset = this.getRelativeSelectableContentOffset( branchNodeRange.end, 1, visibleRange.end );
4776 // If there isn't a content offset after the end of the current node, fallback to the mid-node contentOffset
4777 startNodeOffset = nextContentOffset !== -1 ? nextContentOffset : contentOffset;
4778 }
4779 }
4780 if ( startNodeOffset !== -1 ) {
4781 // Found an offset
4782 model.setLinearSelection( new ve.Range( startNodeOffset ) );
4783 } else {
4784 // Nowhere sensible to put the cursor
4785 model.setNullSelection();
4786 }
4787 }
4788
4789 if ( fallbackToFirst && this.getSelection().getModel().isNull() ) {
4790 // If a visible range couldn't be determined, or a selection couldn't
4791 // be made for some reason, fall back to the actual first content offset.
4792 this.selectFirstSelectableContentOffset();
4793 }
4794 };
4795
4796 /**
4797 * Apply a DM selection to the DOM, even if the old DOM selection is different but DM-equivalent
4798 *
4799 * @return {boolean} Whether the selection actually changed
4800 */
4801 ve.ce.Surface.prototype.forceShowModelSelection = function () {
4802 return this.showModelSelection( true );
4803 };
4804
4805 /**
4806 * Apply a DM selection to the DOM
4807 *
4808 * @param {boolean} [force] Replace the DOM selection if it is different but DM-equivalent
4809 * @return {boolean} Whether the selection actually changed
4810 */
4811 ve.ce.Surface.prototype.showModelSelection = function ( force ) {
4812 if ( this.deactivated ) {
4813 // setTimeout: Defer until view has updated
4814 setTimeout( this.updateDeactivatedSelection.bind( this ) );
4815 return false;
4816 }
4817
4818 const selection = this.getSelection();
4819 let modelRange;
4820 if ( selection.getModel().isNull() ) {
4821 if (
4822 !this.nativeSelection.focusNode ||
4823 !this.$element[ 0 ].contains( this.nativeSelection.focusNode )
4824 ) {
4825 // Native selection is already null, or outside the document
4826 return false;
4827 }
4828 modelRange = null;
4829 } else {
4830 if ( !selection.isNativeCursor() || this.focusedBlockSlug ) {
4831 // Model selection is an emulated selection (e.g. table). The view is certain to
4832 // match it already, because there is no way to change the view selection when
4833 // an emulated selection is showing.
4834 return false;
4835 }
4836 modelRange = selection.getModel().getRange();
4837 if ( !force && this.$attachedRootNode.get( 0 ).contains(
4838 this.nativeSelection.focusNode
4839 ) ) {
4840 // See whether the model range implied by the DOM selection is already equal to
4841 // the actual model range. This is necessary because one model selection can
4842 // correspond to many DOM selections, and we don't want to change a DOM
4843 // selection that is already valid to an arbitrary different DOM selection.
4844 let impliedModelRange;
4845 try {
4846 impliedModelRange = new ve.Range(
4847 ve.ce.getOffset(
4848 this.nativeSelection.anchorNode,
4849 this.nativeSelection.anchorOffset
4850 ),
4851 ve.ce.getOffset(
4852 this.nativeSelection.focusNode,
4853 this.nativeSelection.focusOffset
4854 )
4855 );
4856 } catch ( e ) {
4857 // The nativeSelection appears to end up outside the documentNode
4858 // sometimes, e.g. when deleting in Safari (T306218)
4859 impliedModelRange = null;
4860 }
4861 if ( modelRange.equals( impliedModelRange ) ) {
4862 // Current native selection fits model range; don't change
4863 return false;
4864 }
4865 }
4866 }
4867 const changed = this.showSelectionState( this.getSelectionState( modelRange ) );
4868 // Support: Chrome
4869 // Fixes T131674, which is only triggered with Chromium-style ce=false cursoring
4870 // restrictions (but other cases of non-updated cursor holders can probably occur
4871 // in other browsers).
4872 if ( changed ) {
4873 this.updateCursorHolders();
4874 return true;
4875 }
4876 return false;
4877 };
4878
4879 /**
4880 * Apply a selection state to the DOM
4881 *
4882 * If the browser cannot show a backward selection, fall back to the forward equivalent
4883 *
4884 * @param {ve.SelectionState} selection The selection state to show
4885 * @return {boolean} Whether the selection actually changed
4886 */
4887 ve.ce.Surface.prototype.showSelectionState = function ( selection ) {
4888 const sel = this.nativeSelection;
4889
4890 let extendedBackwards = false,
4891 newSel = selection;
4892
4893 if ( newSel.equalsSelection( sel ) ) {
4894 this.updateActiveAnnotations();
4895 return false;
4896 }
4897
4898 if ( !newSel.getNativeRange( this.getElementDocument() ) ) {
4899 // You can still set a linear selection if the document doesn't have any cursorable positions.
4900 // That's when you end up here.
4901 sel.removeAllRanges();
4902 return true;
4903 }
4904
4905 if ( newSel.isBackwards ) {
4906 if ( ve.supportsSelectionExtend ) {
4907 // Set the range at the anchor, and extend backwards to the focus
4908 const range = this.getElementDocument().createRange();
4909 range.setStart( newSel.anchorNode, newSel.anchorOffset );
4910 sel.removeAllRanges();
4911 sel.addRange( range );
4912 try {
4913 sel.extend( newSel.focusNode, newSel.focusOffset );
4914 extendedBackwards = true;
4915 } catch ( e ) {
4916 // Support: Firefox
4917 // Firefox sometimes fails when nodes are different
4918 // see https://bugzilla.mozilla.org/show_bug.cgi?id=921444
4919 }
4920 }
4921 if ( !extendedBackwards ) {
4922 // Fallback: Apply the corresponding forward selection
4923 newSel = newSel.flip();
4924 if ( newSel.equalsSelection( sel ) ) {
4925 this.updateActiveAnnotations();
4926 return false;
4927 }
4928 }
4929 }
4930
4931 if ( !extendedBackwards ) {
4932 // Forward selection
4933 sel.removeAllRanges();
4934 sel.addRange( newSel.getNativeRange( this.getElementDocument() ) );
4935 }
4936
4937 // Setting a range doesn't give focus in all browsers so make sure this happens
4938 // Also set focus after range to prevent scrolling to top
4939 const $focusTarget = $( newSel.focusNode ).closest( '[contenteditable=true]' );
4940 if ( $focusTarget.get( 0 ) === this.getElementDocument().activeElement ) {
4941 // Already focused, do nothing.
4942 } else if ( $focusTarget.length && !OO.ui.contains( $focusTarget.get( 0 ), this.getElementDocument().activeElement ) ) {
4943 // Check $focusTarget is non-empty (T259531)
4944 // Note: contains *doesn't* include === here. This is desired, as the
4945 // common case for getting here is when pressing backspace when the
4946 // cursor is in the middle of a block of text (thus both are a <div>),
4947 // and we don't want to scroll away from the caret.
4948 const scrollTop = this.surface.$scrollContainer.scrollTop();
4949 $focusTarget.trigger( 'focus' );
4950 // Support: Safari
4951 // Safari tries to scroll the CE surface into view when focusing,
4952 // causing unwanted page jumps (T258847)
4953 this.surface.$scrollContainer.scrollTop( scrollTop );
4954 } else {
4955 // Scroll the node into view
4956 ve.scrollIntoView(
4957 $( newSel.focusNode ).closest( '*' ).get( 0 )
4958 );
4959 }
4960 this.updateActiveAnnotations();
4961 return true;
4962 };
4963
4964 /**
4965 * Update the activeAnnotations property and apply CSS classes accordingly
4966 *
4967 * An active annotation is one containing the DOM cursor, which may not be well
4968 * defined at annotation boundaries, except for links which use nails.
4969 *
4970 * Also the order of .activeAnnotations may not be well defined.
4971 *
4972 * @param {boolean|Node} [fromModelOrNode] If `true`, gather annotations from the model,
4973 * instead of the cusor focus point. If a Node is passed, gather annotations from that node.
4974 * @fires ve.dm.Surface#contextChange
4975 */
4976 ve.ce.Surface.prototype.updateActiveAnnotations = function ( fromModelOrNode ) {
4977 const canBeActive = function ( view ) {
4978 return view.canBeActive();
4979 };
4980
4981 let activeAnnotations;
4982 if ( fromModelOrNode === true ) {
4983 activeAnnotations = this.annotationsAtModelSelection( canBeActive );
4984 } else if ( fromModelOrNode instanceof Node ) {
4985 activeAnnotations = this.annotationsAtNode( fromModelOrNode, canBeActive );
4986 } else {
4987 activeAnnotations = this.annotationsAtFocus( canBeActive );
4988 }
4989
4990 let changed = false;
4991 // Iterate over previously active annotations
4992 this.activeAnnotations.forEach( ( annotation ) => {
4993 // If not in the new list, turn off
4994 if ( activeAnnotations.indexOf( annotation ) === -1 ) {
4995 annotation.$element.removeClass( 've-ce-annotation-active' );
4996 changed = true;
4997 }
4998 } );
4999
5000 // Iterate over newly active annotations
5001 activeAnnotations.forEach( ( annotation ) => {
5002 // If not in the old list, turn on
5003 if ( this.activeAnnotations.indexOf( annotation ) === -1 ) {
5004 annotation.$element.addClass( 've-ce-annotation-active' );
5005 changed = true;
5006 }
5007 } );
5008
5009 if ( changed ) {
5010 this.activeAnnotations = activeAnnotations;
5011 this.model.emit( 'contextChange' );
5012 }
5013 };
5014
5015 /**
5016 * Update the selection to contain the contents of a node
5017 *
5018 * @param {HTMLElement} node
5019 * @param {string} [collapse] Collaspse to 'start' or 'end'
5020 * @return {boolean} Whether the selection changed
5021 */
5022 ve.ce.Surface.prototype.selectNodeContents = function ( node, collapse ) {
5023 if ( !node ) {
5024 return false;
5025 }
5026 let anchor = ve.ce.nextCursorOffset( node.childNodes[ 0 ] );
5027 let focus = ve.ce.previousCursorOffset( node.childNodes[ node.childNodes.length - 1 ] );
5028 if ( collapse === 'start' ) {
5029 focus = anchor;
5030 } else if ( collapse === 'end' ) {
5031 anchor = focus;
5032 }
5033 return this.showSelectionState( new ve.SelectionState( {
5034 anchorNode: anchor.node,
5035 anchorOffset: anchor.offset, // Past the nail
5036 focusNode: focus.node,
5037 focusOffset: focus.offset, // Before the nail
5038 isCollapsed: false
5039 } ) );
5040 };
5041
5042 /**
5043 * Select the inner contents of the closest annotation
5044 *
5045 * @param {Function} [filter] Function to filter view nodes by.
5046 */
5047 ve.ce.Surface.prototype.selectAnnotation = function ( filter ) {
5048 const annotations = this.annotationsAtModelSelection( filter );
5049
5050 if ( annotations.length ) {
5051 this.selectNodeContents( annotations[ 0 ].$element[ 0 ] );
5052 }
5053 };
5054
5055 /**
5056 * Get the annotation views at the current model selection
5057 *
5058 * TODO: This doesn't work for annotations that span fewer
5059 * than one character, as getNodeAndOffset will never return
5060 * an offset inside that annotation.
5061 *
5062 * @param {Function} [filter] Function to filter view nodes by.
5063 * @param {number} [offset] Model offset. Defaults to start of current selection.
5064 * @return {ve.ce.Annotation[]} Annotation views
5065 */
5066 ve.ce.Surface.prototype.annotationsAtModelSelection = function ( filter, offset ) {
5067 const documentRange = this.getModel().getDocument().getDocumentRange();
5068
5069 if ( offset === undefined ) {
5070 offset = this.getModel().getSelection().getCoveringRange().start;
5071 }
5072
5073 // getNodeAndOffset can throw when offset is out of bounds (T262354)
5074 // and other undiagnosed situations (T136780, T262487, T259154, T262303)
5075
5076 // TODO: For annotation boundaries we have to search one place left and right
5077 // to find the text inside the annotation. This will give too many results for
5078 // adjancent annotations, and will fail for one character annotations. (T221967)
5079 let nodeAndOffset;
5080 let annotations = [];
5081 if ( offset > documentRange.start ) {
5082 try {
5083 nodeAndOffset = this.getDocument().getNodeAndOffset( offset - 1 );
5084 } catch ( e ) {
5085 nodeAndOffset = null;
5086 }
5087 annotations = nodeAndOffset ? this.annotationsAtNode( nodeAndOffset.node, filter ) : [];
5088 }
5089
5090 if ( offset < documentRange.end ) {
5091 try {
5092 nodeAndOffset = this.getDocument().getNodeAndOffset( offset + 1 );
5093 } catch ( e ) {
5094 nodeAndOffset = null;
5095 }
5096 annotations = OO.unique( annotations.concat( nodeAndOffset ? this.annotationsAtNode( nodeAndOffset.node, filter ) : [] ) );
5097 }
5098
5099 return annotations;
5100 };
5101
5102 /**
5103 * Get the annotation views containing the cursor focus
5104 *
5105 * @param {Function} [filter] Function to filter view nodes by.
5106 * @return {ve.ce.Annotation[]} Annotation views
5107 */
5108 ve.ce.Surface.prototype.annotationsAtFocus = function ( filter ) {
5109 return this.annotationsAtNode( this.nativeSelection.focusNode, filter );
5110 };
5111
5112 /**
5113 * Get the annotation views containing the cursor focus
5114 *
5115 * Only returns annotations which can be active.
5116 *
5117 * @param {Node} node Node at which to search for annotations
5118 * @param {Function} [filter] Function to filter view nodes by. Takes one argument which
5119 * is the view node and returns a boolean.
5120 * @return {ve.ce.Annotation[]} Annotation views
5121 */
5122 ve.ce.Surface.prototype.annotationsAtNode = function ( node, filter ) {
5123 const annotations = [];
5124 $( node ).parents( '.ve-ce-annotation' ).addBack( '.ve-ce-annotation' ).each( ( i, element ) => {
5125 const view = $( element ).data( 'view' );
5126 if ( view && ( !filter || filter( view ) ) ) {
5127 annotations.push( view );
5128 }
5129 } );
5130 return annotations;
5131 };
5132
5133 /**
5134 * Get a SelectionState corresponding to a ve.Range.
5135 *
5136 * If either endpoint of the ve.Range is not a cursor offset, adjust the SelectionState
5137 * endpoints to be at cursor offsets. For a collapsed selection, the adjustment preserves
5138 * collapsedness; for a non-collapsed selection, the adjustment is in the direction that
5139 * grows the selection (thereby avoiding collapsing or reversing the selection).
5140 *
5141 * @param {ve.Range|null} range Range to get selection for
5142 * @return {ve.SelectionState} The selection
5143 */
5144 ve.ce.Surface.prototype.getSelectionState = function ( range ) {
5145 const dmDoc = this.getModel().getDocument();
5146
5147 if ( !range ) {
5148 return ve.SelectionState.static.newNullSelection();
5149 }
5150
5151 // Anchor/focus at the nearest correct position in the direction that
5152 // grows the selection.
5153 const from = dmDoc.getNearestCursorOffset( range.from, range.isBackwards() ? 1 : -1 );
5154 if ( from === -1 ) {
5155 return ve.SelectionState.static.newNullSelection();
5156 }
5157 let anchor;
5158 try {
5159 anchor = this.documentView.getNodeAndOffset( from );
5160 } catch ( e ) {
5161 return ve.SelectionState.static.newNullSelection();
5162 }
5163 let focus;
5164 if ( range.isCollapsed() ) {
5165 focus = anchor;
5166 } else {
5167 const to = dmDoc.getNearestCursorOffset( range.to, range.isBackwards() ? -1 : 1 );
5168 if ( to === -1 ) {
5169 return ve.SelectionState.static.newNullSelection();
5170 }
5171 try {
5172 focus = this.documentView.getNodeAndOffset( to );
5173 } catch ( e ) {
5174 return ve.SelectionState.static.newNullSelection();
5175 }
5176 }
5177 return new ve.SelectionState( {
5178 anchorNode: anchor.node,
5179 anchorOffset: anchor.offset,
5180 focusNode: focus.node,
5181 focusOffset: focus.offset,
5182 isBackwards: range.isBackwards()
5183 } );
5184 };
5185
5186 /**
5187 * Get a native range object for a specified ve.Range
5188 *
5189 * Native ranges are only used by linear selections. They don't show whether the selection
5190 * is backwards, so they should be used for measurement only.
5191 *
5192 * @param {ve.Range} [range] Optional range to get the native range for, defaults to current selection's range
5193 * @return {Range|null} Native range object, or null if there is no suitable selection
5194 */
5195 ve.ce.Surface.prototype.getNativeRange = function ( range ) {
5196 let selectionState;
5197
5198 if ( !range ) {
5199 // If no range specified, or range is equivalent to current native selection,
5200 // then use the current native selection
5201 selectionState = new ve.SelectionState( this.nativeSelection );
5202 } else {
5203 selectionState = this.getSelectionState( range );
5204 }
5205 return selectionState.getNativeRange( this.getElementDocument() );
5206 };
5207
5208 /**
5209 * Append passed highlights to highlight container.
5210 *
5211 * @param {jQuery} $highlights Highlights to append
5212 * @param {boolean} focused Highlights are currently focused
5213 */
5214 ve.ce.Surface.prototype.appendHighlights = function ( $highlights, focused ) {
5215 // Only one item can be blurred-highlighted at a time, so remove the others.
5216 // Remove by detaching so they don't lose their event handlers, in case they
5217 // are attached again.
5218 this.$highlightsBlurred.children().detach();
5219 if ( focused ) {
5220 this.$highlightsFocused.append( $highlights );
5221 } else {
5222 this.$highlightsBlurred.append( $highlights );
5223 }
5224 };
5225
5226 /* Getters */
5227
5228 /**
5229 * Get the top-level surface.
5230 *
5231 * @return {ve.ui.Surface}
5232 */
5233 ve.ce.Surface.prototype.getSurface = function () {
5234 return this.surface;
5235 };
5236
5237 /**
5238 * Get the surface model.
5239 *
5240 * @return {ve.dm.Surface} Surface model
5241 */
5242 ve.ce.Surface.prototype.getModel = function () {
5243 return this.model;
5244 };
5245
5246 /**
5247 * Get the document view.
5248 *
5249 * @return {ve.ce.Document} Document view
5250 */
5251 ve.ce.Surface.prototype.getDocument = function () {
5252 return this.documentView;
5253 };
5254
5255 /**
5256 * Check whether there are any render locks
5257 *
5258 * @return {boolean} Render is locked
5259 */
5260 ve.ce.Surface.prototype.isRenderingLocked = function () {
5261 return this.renderLocks > 0 && !this.readOnly;
5262 };
5263
5264 /**
5265 * Add a single render lock (to disable rendering)
5266 */
5267 ve.ce.Surface.prototype.incRenderLock = function () {
5268 this.renderLocks++;
5269 };
5270
5271 /**
5272 * Remove a single render lock
5273 */
5274 ve.ce.Surface.prototype.decRenderLock = function () {
5275 this.renderLocks--;
5276 };
5277
5278 /**
5279 * Escape the current render lock
5280 *
5281 * @param {Function} callback Function to run after render lock
5282 */
5283 ve.ce.Surface.prototype.afterRenderLock = function ( callback ) {
5284 // TODO: implement an actual tracking system that makes sure renderlock is
5285 // 0 when this is done.
5286 // setTimeout: postpone until there is definitely no render lock
5287 setTimeout( callback );
5288 };
5289
5290 /**
5291 * Change the model only, not the CE surface
5292 *
5293 * This avoids event storms when the CE surface is already correct
5294 *
5295 * @param {ve.dm.Transaction|ve.dm.Transaction[]|null} transactions One or more transactions to
5296 * process, or null to process none
5297 * @param {ve.dm.Selection} selection New selection
5298 * @throws {Error} If calls to this method are nested
5299 */
5300 ve.ce.Surface.prototype.changeModel = function ( transactions, selection ) {
5301 if ( this.newModelSelection !== null ) {
5302 throw new Error( 'Nested change of newModelSelection' );
5303 }
5304 this.newModelSelection = selection;
5305 try {
5306 this.model.change( transactions, selection );
5307 } finally {
5308 this.newModelSelection = null;
5309 }
5310 };
5311
5312 /**
5313 * Inform the surface that one of its ContentBranchNodes' rendering has changed.
5314 *
5315 * @see ve.ce.ContentBranchNode#renderContents
5316 */
5317 ve.ce.Surface.prototype.setContentBranchNodeChanged = function () {
5318 this.contentBranchNodeChanged = true;
5319 this.clearKeyDownState();
5320 };
5321
5322 /**
5323 * Set the node that has the current unicorn.
5324 *
5325 * If another node currently has a unicorn, it will be rerendered, which will
5326 * cause it to release its unicorn.
5327 *
5328 * @param {ve.ce.ContentBranchNode|null} node The node claiming the unicorn, null to release (by rerendering) without claiming
5329 */
5330 ve.ce.Surface.prototype.setUnicorning = function ( node ) {
5331 if ( this.setUnicorningRecursionGuard ) {
5332 throw new Error( 'setUnicorning recursing' );
5333 }
5334 if ( this.unicorningNode && this.unicorningNode !== node ) {
5335 this.setUnicorningRecursionGuard = true;
5336 try {
5337 this.unicorningNode.renderContents();
5338 } finally {
5339 this.setUnicorningRecursionGuard = false;
5340 }
5341 }
5342 this.unicorningNode = node;
5343 };
5344
5345 /**
5346 * Release the current unicorn held by a given node, without rerendering
5347 *
5348 * If the node doesn't hold the current unicorn, nothing happens.
5349 *
5350 * @param {ve.ce.ContentBranchNode} node The node releasing the unicorn
5351 */
5352 ve.ce.Surface.prototype.setNotUnicorning = function ( node ) {
5353 if ( this.unicorningNode === node ) {
5354 this.unicorningNode = null;
5355 }
5356 };
5357
5358 /**
5359 * Ensure that no node has a unicorn.
5360 *
5361 * If the given node currently has the unicorn, it will be released and
5362 * no rerender will happen. If another node has the unicorn, that node
5363 * will be rerendered to get rid of the unicorn.
5364 *
5365 * @param {ve.ce.ContentBranchNode} node The node releasing the unicorn
5366 */
5367 ve.ce.Surface.prototype.setNotUnicorningAll = function ( node ) {
5368 if ( this.unicorningNode === node ) {
5369 // Don't call back node.renderContents()
5370 this.unicorningNode = null;
5371 }
5372 this.setUnicorning( null );
5373 };
5374
5375 /**
5376 * Get list of selected nodes and annotations.
5377 *
5378 * Exclude active annotations unless the CE focus is inside a link
5379 *
5380 * @param {boolean} [all] Include nodes and annotations which only cover some of the fragment
5381 * @return {ve.dm.Model[]} Selected models
5382 */
5383 ve.ce.Surface.prototype.getSelectedModels = function () {
5384 if ( !( this.model.selection instanceof ve.dm.LinearSelection ) ) {
5385 return [];
5386 }
5387 let models = this.model.getFragment().getSelectedModels();
5388
5389 if ( this.model.selection.isCollapsed() ) {
5390 const fragmentAfter = this.model.getFragment( new ve.dm.LinearSelection(
5391 new ve.Range(
5392 this.model.selection.range.start,
5393 this.model.selection.range.start + 1
5394 )
5395 ) );
5396 models = OO.unique( [].concat(
5397 models,
5398 fragmentAfter.getSelectedModels()
5399 ) );
5400 }
5401
5402 const activeModels = this.activeAnnotations.map( ( view ) => view.getModel() );
5403
5404 if ( this.model.sourceMode ) {
5405 return models;
5406 } else {
5407 return models.filter( ( annModel ) => {
5408 // If the model is an annotation that can be active, only show it if it *is* active
5409 if ( annModel instanceof ve.dm.Annotation && ve.ce.annotationFactory.canAnnotationBeActive( annModel.getType() ) ) {
5410 return activeModels.indexOf( annModel ) !== -1;
5411 }
5412 return true;
5413 } );
5414 }
5415 };
5416
5417 /**
5418 * Tests whether the selection covers part but not all of a nailed annotation
5419 *
5420 * @return {boolean} True if a nailed annotation is split either at the focus or at the anchor (or both)
5421 */
5422 ve.ce.Surface.prototype.selectionSplitsNailedAnnotation = function () {
5423 return ve.ce.nailedAnnotationAt( this.nativeSelection.anchorNode ) !==
5424 ve.ce.nailedAnnotationAt( this.nativeSelection.focusNode );
5425 };
5426
5427 /**
5428 * Called when the synchronizer receives a remote author selection or name change
5429 *
5430 * @param {number} authorId The author ID
5431 */
5432 ve.ce.Surface.prototype.onSynchronizerAuthorUpdate = function ( authorId ) {
5433 this.paintAuthor( authorId );
5434 };
5435
5436 /**
5437 * Called when the synchronizer receives a remote author disconnect
5438 *
5439 * @param {number} authorId The author ID
5440 */
5441 ve.ce.Surface.prototype.onSynchronizerAuthorDisconnect = function ( authorId ) {
5442 this.drawSelections( 'otherUserSelection-' + authorId, [] );
5443 this.drawSelections( 'otherUserCursor-' + authorId, [] );
5444 };
5445
5446 /**
5447 * Called when the synchronizer reconnects and their is a server doc ID mismatch
5448 */
5449 ve.ce.Surface.prototype.onSynchronizerWrongDoc = function () {
5450 OO.ui.alert(
5451 ve.msg( 'visualeditor-rebase-missing-document-error' ),
5452 { title: ve.msg( 'visualeditor-rebase-missing-document-title' ) }
5453 );
5454 };
5455
5456 /**
5457 * Handle pause events from the synchronizer
5458 *
5459 * Drops the opacity of the surface to indicate that no updates are
5460 * being received from other users.
5461 */
5462 ve.ce.Surface.prototype.onSynchronizerPause = function () {
5463 this.$element.toggleClass( 've-ce-surface-paused', !!this.model.synchronizer.paused );
5464 };
5465
5466 /**
5467 * Paint a remote author's current selection, as stored in the synchronizer
5468 *
5469 * @param {number} authorId The author ID
5470 */
5471 ve.ce.Surface.prototype.paintAuthor = function ( authorId ) {
5472 const synchronizer = this.model.synchronizer,
5473 authorData = synchronizer.getAuthorData( authorId ),
5474 selection = synchronizer.authorSelections[ authorId ];
5475
5476 if ( !authorData || !selection || authorId === synchronizer.getAuthorId() ) {
5477 return;
5478 }
5479
5480 const color = '#' + authorData.color;
5481
5482 if ( !Object.prototype.hasOwnProperty.call( this.userSelectionDeactivate, authorId ) ) {
5483 this.userSelectionDeactivate[ authorId ] = ve.debounce( () => {
5484 // TODO: Transition away the user label when inactive, maybe dim selection
5485 if ( Object.prototype.hasOwnProperty.call( this.drawnSelections, 'otherUserSelection-' + authorId ) ) {
5486 this.drawnSelections[ 'otherUserSelection-' + authorId ].$selections.addClass( 've-ce-surface-selections-otherUserSelection-inactive' );
5487 }
5488 if ( Object.prototype.hasOwnProperty.call( this.drawnSelections, 'otherUserCursor-' + authorId ) ) {
5489 this.drawnSelections[ 'otherUserCursor-' + authorId ].$selections.addClass( 've-ce-surface-selections-otherUserCursor-inactive' );
5490 }
5491 }, 5000 );
5492 }
5493 this.userSelectionDeactivate[ authorId ]();
5494
5495 if ( !selection || selection.isNull() ) {
5496 this.drawSelections( 'otherUserSelection-' + authorId, [] );
5497 this.drawSelections( 'otherUserCursor-' + authorId, [] );
5498 return;
5499 }
5500
5501 this.drawSelections(
5502 'otherUserSelection-' + authorId,
5503 [ ve.ce.Selection.static.newFromModel( selection, this ) ],
5504 {
5505 wrapperClass: 've-ce-surface-selections-otherUserSelection',
5506 color: color
5507 }
5508 );
5509
5510 const cursorSelection = selection instanceof ve.dm.LinearSelection && this.getFocusedNode( selection.getRange() ) ?
5511 selection : selection.collapseToTo();
5512
5513 this.drawSelections(
5514 'otherUserCursor-' + authorId,
5515 [ ve.ce.Selection.static.newFromModel( cursorSelection, this ) ],
5516 {
5517 wrapperClass: 've-ce-surface-selections-otherUserCursor',
5518 color: color,
5519 // Label is attached to cursor for 100% opacity, but it should probably be attached
5520 // to the selection, so the cursor can be selectively rendered just for LinearSelection's.
5521 label: authorData.name
5522 }
5523 );
5524 };
5525
5526 /**
5527 * Respond to a position event on this surface
5528 */
5529 ve.ce.Surface.prototype.onPosition = function () {
5530 this.redrawSelections();
5531
5532 if ( this.model.synchronizer ) {
5533 // Defer to allow surface synchronizer to adjust for transactions
5534 setTimeout( () => {
5535 const authorSelections = this.model.synchronizer.authorSelections;
5536 for ( const authorId in authorSelections ) {
5537 this.onSynchronizerAuthorUpdate( +authorId );
5538 }
5539 } );
5540 }
5541 };
5542
5543 /**
5544 * Handler for mutation observer
5545 *
5546 * Identifies deleted DOM nodes, and finds and deletes corresponding model structural nodes.
5547 * Mutation observers run asynchronously (on the microtask queue) so the current document state
5548 * may differ from when the mutations happened. Therefore this handler rechecks node attachment,
5549 * document ranges etc.
5550 *
5551 * @param {MutationRecord[]} mutationRecords Records of the mutations observed
5552 */
5553 ve.ce.Surface.prototype.afterMutations = function ( mutationRecords ) {
5554 const removedNodes = [];
5555 mutationRecords.forEach( ( mutationRecord ) => {
5556 if ( !mutationRecord.removedNodes ) {
5557 return;
5558 }
5559 mutationRecord.removedNodes.forEach( ( removedNode ) => {
5560 const view = $.data( removedNode, 'view' );
5561 if ( view && view.isContent && !view.isContent() ) {
5562 removedNodes.push( view );
5563 }
5564 } );
5565 mutationRecord.addedNodes.forEach( ( addedNode ) => {
5566 const view = $.data( addedNode, 'view' );
5567 if ( view && view.isContent && !view.isContent() ) {
5568 const idx = removedNodes.indexOf( view );
5569 if ( idx !== -1 ) {
5570 // This is a move, not a removal. See T365052#9811638
5571 removedNodes.splice( idx, 1 );
5572 }
5573 }
5574 } );
5575 } );
5576 const removals = removedNodes.map( ( node ) => ( { node: node, range: node.getOuterRange() } ) );
5577 removals.sort( ( x, y ) => x.range.start - y.range.start );
5578 for ( let i = 0, iLen = removals.length; i < iLen; i++ ) {
5579 // Remove any overlapped range (which in a tree must be a nested range)
5580 if ( i > 0 && removals[ i ].range.start < removals[ i - 1 ].range.end ) {
5581 removals.splice( i, 1 );
5582 i--;
5583 continue;
5584 }
5585 }
5586 removals.forEach( ( removal ) => {
5587 const tx = ve.dm.TransactionBuilder.static.newFromRemoval(
5588 this.getModel().getDocument(),
5589 removal.node.getOuterRange()
5590 );
5591 this.getModel().change( tx );
5592 } );
5593 };