/*! * VisualEditor ContentEditable Surface class. * * @copyright See AUTHORS.txt */ /** * ContentEditable surface. * * @class * @extends OO.ui.Element * @mixes OO.EventEmitter * * @constructor * @param {ve.dm.Surface} model Surface model to observe * @param {ve.ui.Surface} ui Surface user interface * @param {Object} [config] Configuration options */ ve.ce.Surface = function VeCeSurface( model, ui, config ) { // Parent constructor ve.ce.Surface.super.call( this, config ); // Mixin constructors OO.EventEmitter.call( this ); // Properties this.surface = ui; this.model = model; this.documentView = new ve.ce.Document( model.getDocument(), this ); this.attachedRoot = this.getDocument().getDocumentNode().getNodeFromOffset( model.getDocument().getAttachedRoot().getOffset() + ( model.getDocument().getAttachedRoot().isWrapped() ? 1 : 0 ) ); this.selection = null; this.readOnly = false; this.reviewMode = false; this.surfaceObserver = new ve.ce.SurfaceObserver( this ); this.$window = $( this.getElementWindow() ); this.$document = $( this.getElementDocument() ); this.$attachedRootNode = this.attachedRoot.$element.addClass( 've-ce-attachedRootNode' ); // Deprecated aliases this.$documentNode = this.$attachedRootNode; this.root = this.attachedRoot; // Window.getSelection returns a live singleton representing the document's selection this.nativeSelection = this.getElementWindow().getSelection(); ve.fixSelectionNodes( this.nativeSelection ); this.eventSequencer = new ve.EventSequencer( [ 'keydown', 'keypress', 'keyup', 'compositionstart', 'compositionend', 'beforeinput', 'input', 'mousedown' ] ); this.clipboard = null; this.clipboardId = Math.random().toString(); this.clipboardIndex = 0; // The last non-collapsed selection in this VE surface. This will be a NullSelection // if there has never had a non-collapsed selection, or if the cursor is moved out of // the surface and a selection is made elsewhere. this.lastNonCollapsedDocumentSelection = new ve.dm.NullSelection(); this.middleClickPasting = false; this.middleClickTargetOffset = false; this.renderLocks = 0; this.dragging = false; this.relocatingSelection = null; this.relocatingNode = null; this.allowedFile = null; this.resizing = false; this.focused = false; this.deactivated = false; this.showAsActivated = false; this.hideSelection = false; this.$deactivatedSelection = $( '
' ); this.userSelectionDeactivate = {}; this.drawnSelections = {}; this.drawnSelectionCache = {}; this.activeNode = null; this.contentBranchNodeChanged = false; this.selectionLink = null; this.delayedSequences = []; this.$highlightsFocused = $( '
' ); this.$highlightsBlurred = $( '
' ); this.$highlights = $( '
' ).append( this.$highlightsFocused, this.$highlightsBlurred ); this.$findResults = $( '
' ); this.$dropMarker = $( '
' ).addClass( 've-ce-surface-dropMarker oo-ui-element-hidden' ); this.$lastDropTarget = null; this.lastDropPosition = null; this.$pasteTarget = $( '
' ); this.pasting = false; this.beforePasteAnnotationsAtFocus = []; this.copying = false; this.pasteSpecial = false; this.pointerEvents = null; this.focusedBlockSlug = null; this.focusedNode = null; this.activeAnnotations = []; this.contexedAnnotations = []; this.previousActiveAnnotations = []; // This is set on entering changeModel, then unset when leaving. // It is used to test whether a reflected change event is emitted. this.newModelSelection = null; // Snapshot updated at keyDown. See storeKeyDownState. this.keyDownState = { event: null, selectionState: null }; this.cursorDirectionality = null; this.unicorningNode = null; this.setUnicorningRecursionGuard = false; this.cursorHolderBefore = null; this.cursorHolderAfter = null; // Events // Debounce to prevent trying to draw every cursor position in history. this.onPositionDebounced = ve.debounce( this.onPosition.bind( this ) ); this.connect( this, { position: this.onPositionDebounced } ); this.model.connect( this, { select: 'onModelSelect', documentUpdate: 'onModelDocumentUpdate', insertionAnnotationsChange: 'onInsertionAnnotationsChange' } ); if ( this.model.synchronizer ) { this.model.synchronizer.connect( this, { authorSelect: 'onSynchronizerAuthorUpdate', authorChange: 'onSynchronizerAuthorUpdate', authorDisconnect: 'onSynchronizerAuthorDisconnect', wrongDoc: 'onSynchronizerWrongDoc', pause: 'onSynchronizerPause' } ); } this.onDocumentMouseUpHandler = this.onDocumentMouseUp.bind( this ); this.$attachedRootNode.on( { // Mouse events shouldn't be sequenced as the event sequencer // is detached on blur mousedown: this.onDocumentMouseDown.bind( this ), // mouseup is bound to the whole document on mousedown cut: this.onCut.bind( this ), copy: this.onCopy.bind( this ) } ); this.onWindowResizeHandler = ve.debounce( this.onWindowResize.bind( this ), 50 ); this.$window.on( 'resize', this.onWindowResizeHandler ); this.onDocumentFocusInOutHandler = this.onDocumentFocusInOut.bind( this ); this.$document.on( 'focusin focusout', this.onDocumentFocusInOutHandler ); this.debounceFocusChange = ve.debounce( this.onFocusChange.bind( this ) ); // If the document is blurred (but still has a selection) it is // possible to clear the selection by clicking elsewhere without // triggering a focus or blur event, so listen to mousedown globally. this.$document.on( 'mousedown', this.debounceFocusChange ); // It is possible that when focusin fires, the selection is not yet inside // the document. This happens if the selection is being moved inside itself, // e.g. the whole html page was previously selected, including the attachedRootNode // In this case the selection is not moved until mouseup. T157499 this.$attachedRootNode.on( 'mouseup', this.debounceFocusChange ); this.$pasteTarget.add( this.$highlights ).on( { cut: this.onCut.bind( this ), copy: this.onCopy.bind( this ), paste: this.onPaste.bind( this ) } ); this.$attachedRootNode .on( 'paste', this.onPaste.bind( this ) ) .on( 'focus', 'a', () => { // Opera <= 12 triggers 'blur' on document node before any link is // focused and we don't want that this.$attachedRootNode[ 0 ].focus(); } ); this.onDocumentSelectionChangeHandler = this.onDocumentSelectionChange.bind( this ); this.$document.on( 'selectionchange', this.onDocumentSelectionChangeHandler ); this.$element.on( { dragstart: this.onDocumentDragStart.bind( this ), dragover: this.onDocumentDragOver.bind( this ), dragleave: this.onDocumentDragLeave.bind( this ), drop: this.onDocumentDrop.bind( this ) } ); // Add listeners to the eventSequencer. They won't get called until // eventSequencer.attach(node) has been called. this.eventSequencer.on( { keydown: this.onDocumentKeyDown.bind( this ), keyup: this.onDocumentKeyUp.bind( this ), keypress: this.onDocumentKeyPress.bind( this ), beforeinput: this.onDocumentBeforeInput.bind( this ), input: this.onDocumentInput.bind( this ), compositionstart: this.onDocumentCompositionStart.bind( this ) } ).after( { keydown: this.afterDocumentKeyDown.bind( this ) } ); this.mutationObserver = new MutationObserver( this.afterMutations.bind( this ) ); this.mutationObserver.observe( this.$attachedRootNode[ 0 ], { childList: true, subtree: true } ); // Initialization // Support: Chrome // Add 'notranslate' class to prevent Chrome's translate feature from // completely messing up the CE DOM (T59124) this.$element.addClass( 've-ce-surface notranslate' ); // Support: Edge // Add translate="no" attribute to prevent Chromium Edge's translate feature from // translating our editable surface, and leaving junk behind... (T267747) // Some documentation out there says it respects class="notranslate", but it doesn't. this.$element.attr( 'translate', 'no' ); this.$highlights.addClass( 've-ce-surface-highlights' ); this.$highlightsFocused.addClass( 've-ce-surface-highlights-focused' ); this.$highlightsBlurred.addClass( 've-ce-surface-highlights-blurred' ); this.$deactivatedSelection.addClass( 've-ce-surface-deactivatedSelection' ); this.$pasteTarget .addClass( 've-ce-surface-paste' ) // T283853 .attr( 'aria-hidden', true ) .prop( { tabIndex: -1, contentEditable: 'true' } ); // Add elements to the DOM this.$highlights.append( this.$dropMarker ); this.$element.append( this.$attachedRootNode, this.$pasteTarget ); this.surface.$blockers.append( this.$highlights ); this.surface.$selections.append( this.$deactivatedSelection ); }; /* Inheritance */ OO.inheritClass( ve.ce.Surface, OO.ui.Element ); OO.mixinClass( ve.ce.Surface, OO.EventEmitter ); /* Events */ /** * @event ve.ce.Surface#relocationStart */ /** * @event ve.ce.Surface#relocationEnd */ /** * @event ve.ce.Surface#keyup */ /** * When the surface or its contents changes position * (only after initialize has already been called). * * @event ve.ce.Surface#position * @param {boolean} [wasSynchronizing] The surface was positioned due to * synchronization (ve.dm.SurfaceSynchronizer) */ /** * Note that it's possible for a focus event to occur immediately after a blur event, if the focus * moves to or from a FocusableNode. In this case the surface doesn't lose focus conceptually, but * a pair of blur-focus events is emitted anyway. * * @event ve.ce.Surface#focus */ /** * Note that it's possible for a focus event to occur immediately after a blur event, if the focus * moves to or from a FocusableNode. In this case the surface doesn't lose focus conceptually, but * a pair of blur-focus events is emitted anyway. * * @event ve.ce.Surface#blur */ /** * Surface activation state has changed (i.e. on activate or deactivate) * * @event ve.ce.Surface#activation */ /* Static properties */ /** * Attributes considered 'unsafe' for copy/paste * * These attributes may be dropped by the browser during copy/paste, so * any element containing these attributes will have them JSON encoded into * data-ve-attributes on copy. * * @type {string[]} */ ve.ce.Surface.static.unsafeAttributes = [ // Support: Firefox // RDFa: Firefox ignores these 'about', 'content', 'datatype', 'property', 'rel', 'resource', 'rev', 'typeof', // CSS: Values are often added or modified 'style' ]; /** * Values of InputEvent.inputType which map to a command * * Currently these are triggered when the user selects * undo/redo from the context menu in Chrome, or uses the * selection formatting tools on iOS. * * See https://w3c.github.io/input-events/ * * commands like { collapsed: 'foo', uncollapsed: 'bar' } * act conditionally depending whether the selection is * collapsed * * A value of `null` will perform no action and * preventDefault. A value of `undefined` will do nothing * and let the event continue. * * @type {Object.} */ ve.ce.Surface.static.inputTypeCommands = { historyUndo: 'undo', historyRedo: 'redo', formatBold: 'bold', formatItalic: 'italic', formatUnderline: 'underline', formatStrikeThrough: 'strikethrough', formatSuperscript: 'superscript', formatSubscript: 'subscript', formatJustifyFull: null, formatJustifyCenter: null, formatJustifyRight: null, formatJustifyLeft: null, formatIndent: 'indent', formatOutdent: 'outdent', formatRemove: 'clear', formatSetBlockTextDirection: null, formatSetInlineTextDirection: null, formatBackColor: null, formatFontColor: null, formatFontName: null, // Support: Firefox // Delete content via context menu in Firefox. (T220629) // If there is a non-collapsed selection, a delete content event can only ever just remove // the selected content. The only time we know this event is fired is in Firefox, where // no other change events are fired. // If any other browsers fire this event with a selection this is harmless, as removing // the content without moving the cursor is always the correct thing to do. deleteContentBackward: { uncollapsed: 'backspace' } }; /** * Cursor holder template * * @static * @property {HTMLElement} */ ve.ce.Surface.static.cursorHolderTemplate = $( '
' ) .addClass( 've-ce-cursorHolder' ) .prop( 'contentEditable', 'true' ) .append( // The image does not need a src for Firefox in spite of cursoring // bug https://bugzilla.mozilla.org/show_bug.cgi?id=989012 , because // you can cursor to ce=false blocks in Firefox (see bug // https://bugzilla.mozilla.org/show_bug.cgi?id=1155031 ) $( '' ) .addClass( 've-ce-cursorHolder-img' ) .attr( { role: 'none', alt: '' } ) ) .get( 0 ); /* Static methods */ /** * When pasting, browsers normalize HTML to varying degrees. * This hash creates a comparable string for validating clipboard contents. * * @param {jQuery} $elements Clipboard HTML * @param {Object} [beforePasteData] Paste information, including leftText and rightText to strip * @return {string} Hash */ ve.ce.Surface.static.getClipboardHash = function ( $elements, beforePasteData ) { beforePasteData = beforePasteData || {}; return $elements.text() .slice( beforePasteData.leftText ? beforePasteData.leftText.length : 0, beforePasteData.rightText ? -beforePasteData.rightText.length : undefined ) // Whitespace may be modified (e.g. ' ' to ' '), so strip it all .replace( /\s/gm, '' ); }; /* Methods */ /** * Destroy the surface, removing all DOM elements. */ ve.ce.Surface.prototype.destroy = function () { const attachedRoot = this.attachedRoot; // Support: Firefox, iOS // FIXME T126041: Blur to make selection/cursor disappear (needed in Firefox // in some cases, and in iOS to hide the keyboard) if ( this.isFocused() ) { this.blur(); } // Detach observer and event sequencer this.surfaceObserver.stopTimerLoop(); this.surfaceObserver.detach(); this.eventSequencer.detach(); // Make document node not live attachedRoot.setLive( false ); // Disconnect events this.model.disconnect( this ); // Disconnect DOM events on the document this.$document.off( 'focusin focusout', this.onDocumentFocusInOutHandler ); this.$document.off( 'mousedown', this.debounceFocusChange ); this.$document.off( 'selectionchange', this.onDocumentSelectionChangeHandler ); if ( this.model.synchronizer ) { // TODO: Move destroy to ve.dm.Surface#destroy this.model.synchronizer.destroy(); this.model.synchronizer.disconnect( this ); } // Disconnect DOM events on the window this.$window.off( 'resize', this.onWindowResizeHandler ); // Remove DOM elements (also disconnects their events) this.$element.remove(); this.$highlights.remove(); }; /** * Get linear model offest from a mouse event * * @param {Event} e * @return {number} Linear model offset, or -1 if coordinates are out of bounds */ ve.ce.Surface.prototype.getOffsetFromEventCoords = function ( e ) { return this.getOffsetFromCoords( e.pageX - this.surface.$scrollContainer.scrollLeft(), e.pageY - this.surface.$scrollContainer.scrollTop() ); }; /** * Get linear model offset from absolute coords * * @param {number} x X offset * @param {number} y Y offset * @return {number} Linear model offset, or -1 if coordinates are out of bounds */ ve.ce.Surface.prototype.getOffsetFromCoords = function ( x, y ) { const doc = this.getElementDocument(); try { let offset; if ( doc.caretPositionFromPoint ) { // Gecko // http://dev.w3.org/csswg/cssom-view/#extensions-to-the-document-interface const caretPosition = document.caretPositionFromPoint( x, y ); offset = ve.ce.getOffset( caretPosition.offsetNode, caretPosition.offset ); } else if ( doc.caretRangeFromPoint ) { // Webkit // http://www.w3.org/TR/2009/WD-cssom-view-20090804/ const range = document.caretRangeFromPoint( x, y ); offset = ve.ce.getOffset( range.startContainer, range.startOffset ); } else if ( document.body.createTextRange ) { // Trident // http://msdn.microsoft.com/en-gb/library/ie/ms536632(v=vs.85).aspx const textRange = document.body.createTextRange(); textRange.moveToPoint( x, y ); textRange.pasteHTML( ' ' ); // eslint-disable-next-line no-jquery/no-global-selector const $marker = $( '.ve-ce-textRange-drop-marker' ); offset = ve.ce.getOffset( $marker.get( 0 ), 0 ); $marker.remove(); } return offset; } catch ( e ) { // Both ve.ce.getOffset and TextRange.moveToPoint can throw out of bounds exceptions return -1; } }; /** * Get selection view object * * @param {ve.dm.Selection} [selection] Optional selection model, defaults to current selection * @return {ve.ce.Selection} Selection view */ ve.ce.Surface.prototype.getSelection = function ( selection ) { if ( selection ) { // Specific selection requested, bypass cache return ve.ce.Selection.static.newFromModel( selection, this ); } else if ( !this.selection ) { this.selection = ve.ce.Selection.static.newFromModel( this.getModel().getSelection(), this ); } return this.selection; }; /** * Get block directionality at selection * * @return {string} 'rtl' or 'ltr' */ ve.ce.Surface.prototype.getSelectionDirectionality = function () { return this.getSelection().getDirectionality( this.getDocument() ); }; /* Initialization */ /** * Initialize surface. * * This should be called after the surface has been attached to the DOM. * * @fires ve.ce.Surface#position */ ve.ce.Surface.prototype.initialize = function () { this.attachedRoot.setLive( true ); if ( $.client.profile().layout === 'gecko' ) { // Support: Firefox < 64 // Turn off native object editing. This must be tried after the surface has been added to DOM. // This is only needed in Gecko. In other engines, these properties are off by default, // and turning them off again is expensive; see https://phabricator.wikimedia.org/T89928 // These are disabled by default since Firefox 64. try { this.$document[ 0 ].execCommand( 'enableObjectResizing', false, false ); this.$document[ 0 ].execCommand( 'enableInlineTableEditing', false, false ); } catch ( e ) { /* Silently ignore */ } } this.emit( 'position' ); }; /** * Set the read-only state of the surface * * @param {boolean} readOnly Make surface read-only */ ve.ce.Surface.prototype.setReadOnly = function ( readOnly ) { this.readOnly = !!readOnly; this.$element.toggleClass( 've-ce-surface-readOnly', this.readOnly ); }; /** * Check if the surface is read-only * * @return {boolean} */ ve.ce.Surface.prototype.isReadOnly = function () { return this.readOnly; }; /** * Set the review mode state of the surface * * In review mode the surface can't be interacted with by the user * (unlike the read-only mode where the user can select text and * inspect nodes). * * Review mode does not restrict changes to the model by other means, * so programmatic changes can still be made from other tools. * * @param {boolean} reviewMode Set surface to review mode * @param {ve.ce.Node[]} highlightNodes Nodes to highlight while in review mode */ ve.ce.Surface.prototype.setReviewMode = function ( reviewMode, highlightNodes ) { this.reviewMode = !!reviewMode; this.$element.toggleClass( 've-ce-surface-reviewMode', this.reviewMode ); this.$element.toggleClass( 've-ce-surface-reviewMode-highlightNodes', this.reviewMode && !!highlightNodes ); if ( reviewMode && highlightNodes ) { highlightNodes.forEach( ( node ) => { node.$element .addClass( 've-ce-surface-reviewMode-highlightNode' ) .parentsUntil( '.ve-ce-attachedRootNode' ) .addClass( 've-ce-surface-reviewMode-highlightNode' ); } ); } else { this.$element.find( '.ve-ce-surface-reviewMode-highlightNode' ) .removeClass( 've-ce-surface-reviewMode-highlightNode' ); } }; /** * Give focus to the surface, reapplying the model selection, or selecting the first visible offset * if the model selection is null. * * This is used when switching between surfaces, e.g. when closing a dialog window. Calling this * function will also reapply the selection, even if the surface is already focused. */ ve.ce.Surface.prototype.focus = function () { if ( !this.attachedRoot.isLive() ) { OO.ui.warnDeprecation( 'Tried to focus an un-initialized surface view. Wait for the ve.ui.Surface `ready` event to fire.' ); return; } let selection = this.getSelection(); if ( selection.getModel().isNull() ) { this.selectFirstVisibleStartContentOffset(); selection = this.getSelection(); } // Focus the contentEditable for text selections, or the pasteTarget for focusedNode selections if ( selection.isFocusedNode() ) { this.$pasteTarget[ 0 ].focus(); } else if ( selection.isNativeCursor() ) { let nodeAndOffset; try { nodeAndOffset = this.getDocument().getNodeAndOffset( selection.getModel().getRange().start ); } catch ( e ) { // Unexplained failures causing log spam: T262487 nodeAndOffset = null; } if ( nodeAndOffset ) { $( nodeAndOffset.node ).closest( '[contenteditable=true]' )[ 0 ].focus(); } } // If we are calling focus after replacing a node the selection may be gone // but onDocumentFocus won't fire so restore the selection here too. this.onModelSelect(); // setTimeout: postpone until onDocumentFocus has been called setTimeout( () => { // Support: Chrome // In some browsers (e.g. Chrome) giving the document node focus doesn't // necessarily give you a selection (e.g. if the first child is a
) // so if the surface isn't 'focused' (has no selection) give it a selection // manually // TODO: rename isFocused and other methods to something which reflects // the fact they actually mean "has a native selection" if ( !this.isFocused() ) { this.selectFirstVisibleStartContentOffset(); } } ); // onDocumentFocus takes care of the rest }; /** * Blur the surface */ ve.ce.Surface.prototype.blur = function () { if ( this.deactivated ) { // Clear the model selection, so activate doesn't trigger another de-activate this.getModel().setNullSelection(); this.activate(); } this.removeRangesAndBlur(); // This won't trigger focusin/focusout events, so trigger focus change manually this.onFocusChange(); if ( OO.ui.isMobile() ) { this.updateActiveAnnotations(); this.contexedAnnotations = []; } }; /** * Remove all native selection ranges, and blur any active element * * This should hide all virtual keyboards when present. */ ve.ce.Surface.prototype.removeRangesAndBlur = function () { this.nativeSelection.removeAllRanges(); if ( this.getElementDocument().activeElement === this.$attachedRootNode[ 0 ] ) { // Blurring the activeElement ensures the keyboard is hidden on iOS this.getElementDocument().activeElement.blur(); } }; /** * Handler for focusin and focusout events. Filters events and debounces to #onFocusChange. * * @param {jQuery.Event} e focusin/out event */ ve.ce.Surface.prototype.onDocumentFocusInOut = function () { this.debounceFocusChange(); }; /** * Handle global focus change. */ ve.ce.Surface.prototype.onFocusChange = function () { const surfaceNodes = [ this.$attachedRootNode[ 0 ], this.$pasteTarget[ 0 ], this.$highlights[ 0 ] ]; const hasFocus = OO.ui.contains( surfaceNodes, this.nativeSelection.anchorNode, true ) && OO.ui.contains( surfaceNodes, document.activeElement, true ); if ( this.deactivated ) { if ( OO.ui.contains( this.$attachedRootNode[ 0 ], this.nativeSelection.anchorNode, true ) ) { this.onDocumentFocus(); } } else { if ( hasFocus && !this.isFocused() ) { this.onDocumentFocus(); } else if ( !hasFocus && this.isFocused() ) { this.onDocumentBlur(); } else if ( hasFocus && OO.ui.contains( this.$highlights[ 0 ], document.activeElement, true ) ) { // Focus ended up in the higlight, e.g. by click on an already visible highlight. // Move the cursor back to pasteTarget as we do when focusableNode initially selected. // Without this, arrow key navigation from the focusable node would stop working. this.preparePasteTargetForCopy(); } } }; /** * Check if the surface is deactivated. * * @return {boolean} Surface is deactivated */ ve.ce.Surface.prototype.isDeactivated = function () { return this.deactivated; }; /** * Check if the surface is visibly deactivated. * * Only true if the surface was decativated by the user * in a way that is expected to change the rendering. * * @return {boolean} Surface is visibly deactivated */ ve.ce.Surface.prototype.isShownAsDeactivated = function () { return this.deactivated && !this.showAsActivated; }; /** * Deactivate the surface, stopping the surface observer and replacing the native * range with a fake rendered one. * * Used by dialogs so they can take focus without losing the original document selection. * * @param {boolean} [showAsActivated=true] Surface should still show as activated * @param {boolean} [noSelectionChange] Don't change the native selection. * @param {boolean} [hideSelection] Completely hide the selection * @fires ve.ce.Surface#activation */ ve.ce.Surface.prototype.deactivate = function ( showAsActivated, noSelectionChange, hideSelection ) { this.showAsActivated = showAsActivated === undefined || !!showAsActivated; this.hideSelection = hideSelection; if ( !this.deactivated ) { // Disable the surface observer, there can be no observable changes // until the surface is activated this.surfaceObserver.disable(); this.deactivated = true; this.previousActiveAnnotations = this.activeAnnotations; this.findAndExecuteDelayedSequences(); this.$element.addClass( 've-ce-surface-deactivated' ); // Remove ranges so the user can't accidentally type into the document, // and so virtual keyboards are hidden. if ( !noSelectionChange ) { this.removeRangesAndBlur(); // iOS Safari will sometimes restore the selection immediately (T293661) setTimeout( () => { if ( // Surface may have been immediately re-activated deliberately this.deactivated && OO.ui.contains( this.$attachedRootNode[ 0 ], this.nativeSelection.anchorNode, true ) ) { this.removeRangesAndBlur(); } } ); } this.updateDeactivatedSelection(); this.clearKeyDownState(); this.emit( 'activation' ); } }; /** * Reactivate the surface and restore the native selection * * @fires ve.ce.Surface#activation * @fires ve.dm.Surface#contextChange */ ve.ce.Surface.prototype.activate = function () { if ( this.deactivated ) { this.deactivated = false; this.showAsActivated = false; this.hideSelection = false; this.updateDeactivatedSelection(); this.surfaceObserver.enable(); this.$element.removeClass( 've-ce-surface-deactivated' ); if ( OO.ui.isMobile() ) { // Activating triggers a context hide on mobile this.model.emit( 'contextChange' ); } const previousSelection = this.getModel().getSelection(); if ( OO.ui.contains( this.$attachedRootNode[ 0 ], this.nativeSelection.anchorNode, true ) ) { // The selection has been placed back in the document, either by the user clicking // or by the closing window updating the model. Poll in case it was the user clicking. this.surfaceObserver.clear(); this.surfaceObserver.pollOnce(); } else { // Clear focused node so onModelSelect re-selects it if necessary this.focusedNode = null; this.onModelSelect(); } const newSelection = this.getModel().getSelection(); if ( previousSelection.getCoveringRange() && newSelection.getCoveringRange() && previousSelection.getCoveringRange().containsRange( newSelection.getCoveringRange() ) ) { // If the user reactivates by clicking on their previous selection, use that selection. this.getModel().setSelection( previousSelection ); // Restore active annotations if ( this.previousActiveAnnotations.length ) { const annotationClasses = this.previousActiveAnnotations.map( ( ann ) => ann.constructor ); this.selectAnnotation( ( view ) => ve.isInstanceOfAny( view, annotationClasses ) ); } } this.emit( 'activation' ); } }; /** * Update the fake selection while the surface is deactivated. * * While the surface is deactivated, all calls to showModelSelection will get redirected here. */ ve.ce.Surface.prototype.updateDeactivatedSelection = function () { const selection = this.getSelection(); // Check we have a deactivated surface and a native selection if ( this.deactivated && selection.isNativeCursor() && !this.hideSelection ) { let textColor; // For collapsed selections, work out the text color to use for the cursor const isCollapsed = selection.getModel().isCollapsed(); if ( isCollapsed ) { const currentNode = this.getDocument().getBranchNodeFromOffset( selection.getModel().getCoveringRange().start ); if ( currentNode ) { // This isn't perfect as it doesn't take into account annotations. textColor = currentNode.$element.css( 'color' ); } } const classes = []; if ( this.isShownAsDeactivated() ) { classes.push( 've-ce-surface-selections-deactivated-showAsDeactivated' ); } if ( isCollapsed ) { classes.push( 've-ce-surface-selections-deactivated-collapsed' ); } // Generates ve-ce-surface-selections-deactivated CSS class this.drawSelections( 'deactivated', [ selection ], { color: textColor, wrapperClass: classes.join( ' ' ) } ); } else { // Generates ve-ce-surface-selections-deactivated CSS class this.drawSelections( 'deactivated', [] ); } }; /** * Check if the surface has a native cursor selection * * On mobile platforms, this means it is likely the virtual * keyboard is visible. * * @return {boolean} Surface has a native cursor selection */ ve.ce.Surface.prototype.hasNativeCursorSelection = function () { return !this.isDeactivated() && this.getSelection().isNativeCursor(); }; /** * Draw selections. * * @param {string} name Unique name for the selection being drawn * @param {ve.ce.Selection[]} selections Selections to draw * @param {Object} [options] * @param {string} options.color CSS color for the selection. Should usually * be set in a stylesheet using the generated class name. * @param {string} options.wrapperClass Additional CSS class string to add to the $selections wrapper. * mapped to the same index. * @param {string} options.label Label shown above each selection */ ve.ce.Surface.prototype.drawSelections = function ( name, selections, options ) { options = options || {}; if ( !Object.prototype.hasOwnProperty.call( this.drawnSelections, name ) ) { this.drawnSelections[ name ] = {}; } const drawnSelection = this.drawnSelections[ name ]; drawnSelection.$selections = drawnSelection.$selections || // The following classes are used here: // * ve-ce-surface-selections-deactived // * ve-ce-surface-selections- $( '
' ).addClass( 've-ce-surface-selections ve-ce-surface-selections-' + name ).appendTo( this.surface.$selections ); const oldSelections = drawnSelection.selections || []; const oldOptions = drawnSelection.options || {}; drawnSelection.selections = selections; drawnSelection.options = options; // Always set the 'class' attribute to ensure previously-set classes are cleared. drawnSelection.$selections.attr( 'class', 've-ce-surface-selections ve-ce-surface-selections-' + name + ' ' + ( options.wrapperClass || '' ) ); const selectionsJustShown = {}; selections.forEach( ( selection ) => { let $selection = this.getDrawnSelection( name, selection.getModel(), options ); if ( !$selection ) { let rects = selection.getSelectionRects(); if ( !rects ) { return; } rects = ve.minimizeRects( rects ); $selection = $( '
' ).addClass( 've-ce-surface-selection' ); rects.forEach( ( rect ) => { const $rect = $( '
' ).css( { top: rect.top, left: rect.left, // Collapsed selections can have a width of 0, so expand width: Math.max( rect.width, 1 ), height: rect.height } ); $selection.append( $rect ); if ( options.color ) { $rect.css( 'background-color', options.color ); } } ); if ( options.label ) { const boundingRect = selection.getSelectionBoundingRect(); $selection.append( $( '
' ) .addClass( 've-ce-surface-selection-label' ) .text( options.label ) .css( { top: boundingRect.top, left: boundingRect.left, 'background-color': options.color || '' } ) ); } } if ( !$selection.parent().length ) { drawnSelection.$selections.append( $selection ); } const cacheKey = this.storeDrawnSelection( $selection, name, selection.getModel(), options ); selectionsJustShown[ cacheKey ] = true; } ); // Remove any selections that were not in the latest list of selections oldSelections.forEach( ( oldSelection ) => { const cacheKey = this.getDrawnSelectionCacheKey( name, oldSelection.getModel(), oldOptions ); if ( !selectionsJustShown[ cacheKey ] ) { const $oldSelection = this.getDrawnSelection( name, oldSelection.getModel(), oldOptions ); if ( $oldSelection ) { $oldSelection.detach(); } } } ); }; /** * Get a cache key for a drawn selection * * @param {string} name Name of selection group * @param {ve.dm.Selection} selection Selection model * @param {Object} [options] Selection options * @return {string} Cache key */ ve.ce.Surface.prototype.getDrawnSelectionCacheKey = function ( name, selection, options ) { options = options || {}; return name + '-' + JSON.stringify( selection ) + '-' + ( options.color || '' ) + '-' + ( options.label || '' ); }; /** * Get an already drawn selection from the cache * * @param {string} name Name of selection group * @param {ve.dm.Selection} selection Selection model * @param {Object} [options] Selection options * @return {jQuery} Drawn selection */ ve.ce.Surface.prototype.getDrawnSelection = function ( name, selection, options ) { const cacheKey = this.getDrawnSelectionCacheKey( name, selection, options ); return Object.prototype.hasOwnProperty.call( this.drawnSelectionCache, cacheKey ) ? this.drawnSelectionCache[ cacheKey ] : null; }; /** * Store an already drawn selection in the cache * * @param {jQuery} $selection Drawn selection * @param {string} name Name of selection group * @param {ve.dm.Selection} selection Selection model * @param {Object} [options] Selection options * @return {string} Cache key */ ve.ce.Surface.prototype.storeDrawnSelection = function ( $selection, name, selection, options ) { const cacheKey = this.getDrawnSelectionCacheKey( name, selection, options ); this.drawnSelectionCache[ cacheKey ] = $selection; return cacheKey; }; /** * Redraw selections * * This is triggered by a surface 'position' event, which fires when the surface * changes size, or when the document is modified. The drawnSelectionCache is * cleared as these two things will cause any previously calculated rectangles * to be incorrect. */ ve.ce.Surface.prototype.redrawSelections = function () { Object.keys( this.drawnSelections ).forEach( ( name ) => { const drawnSelection = this.drawnSelections[ name ]; drawnSelection.$selections.empty(); } ); this.drawnSelectionCache = {}; Object.keys( this.drawnSelections ).forEach( ( name ) => { const drawnSelection = this.drawnSelections[ name ]; this.drawSelections( name, drawnSelection.selections, drawnSelection.options ); } ); }; /** * Handle document focus events. * * This is triggered by a global focusin/focusout event noticing a selection on the document. * * @fires ve.ce.Surface#focus */ ve.ce.Surface.prototype.onDocumentFocus = function () { if ( this.getModel().getSelection().isNull() ) { // If the document is being focused by a non-mouse/non-touch user event, // find the first content offset and place the cursor there. this.selectFirstVisibleStartContentOffset(); } this.eventSequencer.attach( this.$element ); this.surfaceObserver.startTimerLoop(); this.focused = true; this.activate(); this.$element.addClass( 've-ce-surface-focused' ); this.emit( 'focus' ); }; /** * Handle document blur events. * * This is triggered by a global focusin/focusout event noticing no selection on the document. * * @fires ve.ce.Surface#blur */ ve.ce.Surface.prototype.onDocumentBlur = function () { const nullSelectionOnBlur = this.surface.nullSelectionOnBlur; if ( !nullSelectionOnBlur ) { // Set noSelectionChange as we already know the selection has left // the document and we don't want #deactivate to move it again. this.deactivate( false, true ); } this.eventSequencer.detach(); this.surfaceObserver.stopTimerLoop(); this.surfaceObserver.pollOnce(); this.surfaceObserver.clear(); // Setting focused to false blocks selection change handler, so fire one last time here this.onDocumentSelectionChange(); this.setDragging( false ); this.focused = false; if ( nullSelectionOnBlur ) { if ( this.focusedNode ) { this.focusedNode.setFocused( false ); this.focusedNode = null; } this.getModel().setNullSelection(); } this.$element.removeClass( 've-ce-surface-focused' ); this.emit( 'blur' ); }; /** * Check if surface is focused. * * @return {boolean} Surface is focused */ ve.ce.Surface.prototype.isFocused = function () { return this.focused; }; /** * Handle document mouse down events. * * @param {jQuery.Event} e Mouse down event */ ve.ce.Surface.prototype.onDocumentMouseDown = function ( e ) { if ( e.which !== OO.ui.MouseButtons.LEFT ) { if ( e.which === OO.ui.MouseButtons.MIDDLE ) { // When middle click is also focusig the document, the selection may not end up // where you clicked, so record the offset from the click coordinates. (T311733) let targetOffset = -1; if ( this.getModel().getSelection().isNull() ) { targetOffset = this.getOffsetFromEventCoords( e ); } this.middleClickTargetOffset = targetOffset !== -1 ? targetOffset : null; this.middleClickPasting = true; this.$document.one( 'mouseup', () => { // Stay true until other events have run, e.g. paste setTimeout( () => { this.middleClickPasting = false; } ); } ); } return; } const offset = this.getOffsetFromEventCoords( e ); if ( offset !== -1 ) { const contexedAnnotations = this.annotationsAtNode( e.target, ( view ) => this.surface.context.getRelatedSourcesFromModels( [ view.model ] ).length ); if ( OO.ui.isMobile() && // The user has clicked on contexed annotations and ... contexedAnnotations.length && ( // ... was previously on a focusable node or ... this.focusedNode || // ... previously had different annotations selected ... !( // Shallow strict equality check this.contexedAnnotations.length === contexedAnnotations.length && this.contexedAnnotations.every( ( ann, i ) => ann === contexedAnnotations[ i ] ) ) ) ) { const node = e.target; setTimeout( () => { this.getModel().setLinearSelection( new ve.Range( offset ) ); // HACK: Re-activate flag so selection is repositioned this.activate(); this.deactivate( false, false, true ); this.updateActiveAnnotations( node ); } ); this.contexedAnnotations = contexedAnnotations; e.preventDefault(); return; } this.contexedAnnotations = contexedAnnotations; } // Remember the mouse is down this.setDragging( true ); // Bind mouseup to the whole document in case of dragging out of the surface this.$document.on( 'mouseup', this.onDocumentMouseUpHandler ); this.surfaceObserver.stopTimerLoop(); // setTimeout: In some browsers the selection doesn't change until after the event // so poll in the 'after' function. // TODO: rewrite to use EventSequencer setTimeout( this.afterDocumentMouseDown.bind( this, e, this.getSelection() ) ); // Handle triple click if ( e.originalEvent.detail >= 3 ) { // Browser default behaviour for triple click won't behave as we want e.preventDefault(); const newFragment = this.getModel().getFragment() // After double-clicking in an inline slug, we'll get a selection like //

|

|Foo

. This selection spans a CBN boundary, // so we can't expand to the nearest CBN. To handle this case and other possible // cases where the selection spans a CBN boundary, collapse the selection before // expanding it. If the selection is entirely within the same CBN as it should be, // this won't change the result. .collapseToStart() // Cover the CBN we're in .expandLinearSelection( 'closest', ve.dm.ContentBranchNode ) // …but that covered the entire CBN, we only want the contents .adjustLinearSelection( 1, -1 ); // If something weird happened (e.g. no CBN found), newFragment will be null. // Don't select it in that case, because that'll blur the surface. if ( !newFragment.isNull() ) { newFragment.select(); } } }; /** * Deferred until after document mouse down * * @param {jQuery.Event} e Mouse down event * @param {ve.ce.Selection} selectionBefore Selection before the mouse event */ ve.ce.Surface.prototype.afterDocumentMouseDown = function ( e, selectionBefore ) { // TODO: guard with incRenderLock? this.surfaceObserver.pollOnce(); if ( e.shiftKey ) { this.fixShiftClickSelect( selectionBefore ); } }; /** * Handle document mouse up events. * * @param {jQuery.Event} e Mouse up event */ ve.ce.Surface.prototype.onDocumentMouseUp = function ( e ) { this.$document.off( 'mouseup', this.onDocumentMouseUpHandler ); this.surfaceObserver.startTimerLoop(); // setTimeout: In some browsers the selection doesn't change until after the event // so poll in the 'after' function // TODO: rewrite to use EventSequencer setTimeout( this.afterDocumentMouseUp.bind( this, e, this.getSelection() ) ); }; /** * Deferred until after document mouse up * * @param {jQuery.Event} e Mouse up event * @param {ve.ce.Selection} selectionBefore Selection before the mouse event */ ve.ce.Surface.prototype.afterDocumentMouseUp = function ( e, selectionBefore ) { // TODO: guard with incRenderLock? this.surfaceObserver.pollOnce(); if ( e.shiftKey ) { this.fixShiftClickSelect( selectionBefore ); } this.setDragging( false ); }; /** * Fix shift-click selection * * Support: Chrome * When shift-clicking on links Chrome tries to collapse the selection * so check for this and fix manually. * * This can occur on mousedown or, if the existing selection covers the * link, on mouseup. * * https://code.google.com/p/chromium/issues/detail?id=345745 * * @param {ve.ce.Selection} selectionBefore Selection before the mouse event */ ve.ce.Surface.prototype.fixShiftClickSelect = function ( selectionBefore ) { if ( !selectionBefore.isNativeCursor() ) { return; } const newSelection = this.getSelection(); if ( newSelection.getModel().isCollapsed() && !newSelection.equals( selectionBefore ) ) { this.getModel().setLinearSelection( new ve.Range( selectionBefore.getModel().getRange().from, newSelection.getModel().getRange().to ) ); } }; /** * Set a flag when the user is dragging a selection * * @param {boolean} dragging Dragging (mouse is down) */ ve.ce.Surface.prototype.setDragging = function ( dragging ) { this.dragging = !!dragging; // Class can be used to suppress hover states, such as branch slugs. this.$element.toggleClass( 've-ce-surface-dragging', this.dragging ); }; /** * Handle document selection change events. * * @param {jQuery.Event} e Selection change event */ ve.ce.Surface.prototype.onDocumentSelectionChange = function () { const selection = this.getModel().getSelection(); if ( // There is a non-empty selection in the VE surface. Use this if middle-click-to-paste is triggered later. !selection.isCollapsed() || // There is no surface selection, and a native selection has been made elsewhere. // Null the lastNonCollapsedDocumentSelection so native middle-click-to-paste happens instead. ( selection.isNull() && this.nativeSelection.rangeCount && !this.nativeSelection.getRangeAt( 0 ).collapsed ) ) { this.lastNonCollapsedDocumentSelection = selection; } // selectionChange events are only emitted from window.document, so ignore // any events which are fired when the document is blurred or deactivated. if ( !this.focused || this.deactivated ) { return; } this.fixupCursorPosition( 0, this.dragging ); this.updateActiveAnnotations(); this.surfaceObserver.pollOnceSelection(); }; /** * Handle document drag start events. * * @param {jQuery.Event} e Drag start event * @fires ve.ce.Surface#relocationStart */ ve.ce.Surface.prototype.onDocumentDragStart = function ( e ) { this.onCopy( e ); this.startRelocation(); }; /** * Handle document drag over events. * * @param {jQuery.Event} e Drag over event */ ve.ce.Surface.prototype.onDocumentDragOver = function ( e ) { const dataTransferHandlerFactory = this.getSurface().dataTransferHandlerFactory, dataTransfer = e.originalEvent.dataTransfer; let isContent = true; if ( this.readOnly ) { return; } let nodeType; if ( this.relocatingNode ) { isContent = this.relocatingNode.isContent(); nodeType = this.relocatingNode.getType(); } else { if ( this.allowedFile === null ) { this.allowedFile = false; // If we can get file metadata, check if there is a DataTransferHandler registered // to handle it. if ( dataTransfer.items ) { for ( let i = 0, l = dataTransfer.items.length; i < l; i++ ) { const item = dataTransfer.items[ i ]; if ( item.kind !== 'string' ) { const fakeItem = new ve.ui.DataTransferItem( item.kind, item.type ); if ( dataTransferHandlerFactory.getHandlerNameForItem( fakeItem ) ) { this.allowedFile = true; break; } } } } else if ( dataTransfer.files ) { for ( let i = 0, l = dataTransfer.files.length; i < l; i++ ) { const item = dataTransfer.items[ i ]; const fakeItem = new ve.ui.DataTransferItem( item.kind, item.type ); if ( dataTransferHandlerFactory.getHandlerNameForItem( fakeItem ) ) { this.allowedFile = true; break; } } } else if ( Array.prototype.indexOf.call( dataTransfer.types || [], 'Files' ) !== -1 ) { // Support: Firefox // If we have no metadata (e.g. in Firefox) assume it is droppable this.allowedFile = true; } } // this.allowedFile is cached until the next dragleave event if ( this.allowedFile ) { isContent = false; nodeType = 'alienBlock'; } } function getNearestDropTarget( node ) { while ( node.parent && !node.parent.isAllowedChildNodeType( nodeType ) ) { node = node.parent; } if ( node.parent ) { node.parent.traverseUpstream( ( n ) => { if ( n.shouldIgnoreChildren() ) { node = null; return false; } } ); return node; } } if ( !isContent ) { e.preventDefault(); const $target = $( e.target ).closest( '.ve-ce-branchNode, .ve-ce-leafNode' ); let $dropTarget; let dropPosition; if ( $target.length ) { // Find the nearest node which will accept this node type let dropTargetNode = getNearestDropTarget( $target.data( 'view' ) ); if ( dropTargetNode ) { $dropTarget = dropTargetNode.$element; dropPosition = e.originalEvent.pageY - $dropTarget.offset().top > $dropTarget.outerHeight() / 2 ? 'bottom' : 'top'; } else { const targetOffset = this.getOffsetFromEventCoords( e.originalEvent ); if ( targetOffset !== -1 ) { dropTargetNode = getNearestDropTarget( this.getDocument().getBranchNodeFromOffset( targetOffset ) ); if ( dropTargetNode ) { $dropTarget = dropTargetNode.$element; dropPosition = 'top'; } } if ( !$dropTarget ) { $dropTarget = this.$lastDropTarget; dropPosition = this.lastDropPosition; } } } if ( this.$lastDropTarget && ( !this.$lastDropTarget.is( $dropTarget ) || dropPosition !== this.lastDropPosition ) ) { this.$dropMarker.addClass( 'oo-ui-element-hidden' ); $dropTarget = null; } if ( $dropTarget && ( !$dropTarget.is( this.$lastDropTarget ) || dropPosition !== this.lastDropPosition ) ) { const targetPosition = $dropTarget.position(); // Go beyond margins as they can overlap let top = targetPosition.top + parseFloat( $dropTarget.css( 'margin-top' ) ); const left = targetPosition.left + parseFloat( $dropTarget.css( 'margin-left' ) ); if ( dropPosition === 'bottom' ) { top += $dropTarget.outerHeight(); } this.$dropMarker .css( { top: top, left: left } ) .width( $dropTarget.outerWidth() ) .removeClass( 'oo-ui-element-hidden' ); } if ( $dropTarget !== undefined ) { this.$lastDropTarget = $dropTarget; this.lastDropPosition = dropPosition; } } }; /** * Handle document drag leave events. * * @param {jQuery.Event} e Drag leave event */ ve.ce.Surface.prototype.onDocumentDragLeave = function () { this.allowedFile = null; if ( this.$lastDropTarget ) { this.$dropMarker.addClass( 'oo-ui-element-hidden' ); this.$lastDropTarget = null; this.lastDropPosition = null; } }; /** * Handle document drop events. * * Limits native drag and drop behaviour. * * @param {jQuery.Event} e Drop event * @fires ve.ce.Surface#relocationEnd */ ve.ce.Surface.prototype.onDocumentDrop = function ( e ) { // Properties may be nullified by other events, so cache before setTimeout const surfaceModel = this.getModel(), dataTransfer = e.originalEvent.dataTransfer, $dropTarget = this.$lastDropTarget, dropPosition = this.lastDropPosition, platformKey = ve.getSystemPlatform() === 'mac' ? 'mac' : 'pc'; // Prevent native drop event from modifying view e.preventDefault(); if ( this.readOnly ) { return; } let targetOffset; // Determine drop position if ( $dropTarget ) { // Block level drag and drop: use the lastDropTarget to get the targetOffset if ( $dropTarget ) { const targetRange = $dropTarget.data( 'view' ).getModel().getOuterRange(); if ( dropPosition === 'top' ) { targetOffset = targetRange.start; } else { targetOffset = targetRange.end; } } else { return; } } else { targetOffset = this.getOffsetFromEventCoords( e.originalEvent ); if ( targetOffset === -1 ) { return; } } const targetFragment = surfaceModel.getLinearFragment( new ve.Range( targetOffset ) ); const targetViewNode = this.getDocument().getBranchNodeFromOffset( targetFragment.getSelection().getCoveringRange().from ); // TODO: Support sanitized drop on a single line node (removing line breaks) const isMultiline = targetViewNode.isMultiline(); // Internal drop if ( this.relocatingSelection ) { // Get a fragment and data of the node being dragged const originFragment = surfaceModel.getFragment( this.relocatingSelection ); let originData; if ( !isMultiline ) { // Data needs to be balanced to be sanitized const slice = this.model.documentModel.shallowCloneFromRange( originFragment.getSelection().getCoveringRange() ); const linearData = new ve.dm.ElementLinearData( originFragment.getDocument().getStore(), slice.getBalancedData() ); linearData.sanitize( { singleLine: true } ); originData = linearData.data; // Unwrap CBN if ( originData[ 0 ].type && ve.dm.nodeFactory.canNodeContainContent( originData[ 0 ].type ) ) { originData = originData.slice( 1, originData.length - 1 ); } } else { originData = originFragment.getData(); } // Start staging so we can abort in the catch later surfaceModel.pushStaging(); // Dragging performs cut-and-paste by default (remove content from old location). // If Ctrl on PC, or Opt (alt) on Mac, is held, it performs copy-and-paste instead. if ( ( platformKey === 'pc' && !e.ctrlKey ) || ( platformKey === 'mac' && !e.altKey ) ) { originFragment.removeContent(); } try { // Re-insert data at new location targetFragment.insertContent( originData ); surfaceModel.applyStaging(); } catch ( error ) { // Insert content may throw an exception if it can't find a way // to fixup the insertion sensibly surfaceModel.popStaging(); } } else { // External drop // TODO: Support sanitized external drop into single line contexts if ( isMultiline ) { this.handleDataTransfer( dataTransfer, false, targetFragment ); } } this.endRelocation(); }; /** * Handle document key down events. * * @param {jQuery.Event} e Key down event */ ve.ce.Surface.prototype.onDocumentKeyDown = function ( e ) { const selection = this.getModel().getSelection(); let updateFromModel = false; if ( selection.isNull() ) { return; } if ( e.which === 229 ) { // Support: Chrome // Ignore fake IME events (emitted in Chrome) return; } this.surfaceObserver.stopTimerLoop(); this.incRenderLock(); try { // TODO: is this correct? this.surfaceObserver.pollOnce(); } finally { this.decRenderLock(); } this.storeKeyDownState( e ); if ( ve.ce.keyDownHandlerFactory.executeHandlersForKey( e.keyCode, selection.getName(), this, e ) ) { updateFromModel = true; } else { const trigger = new ve.ui.Trigger( e ); if ( trigger.isComplete() ) { const executed = this.surface.executeWithSource( trigger, false, 'trigger' ); if ( executed || this.isBlockedTrigger( trigger ) ) { e.preventDefault(); e.stopPropagation(); updateFromModel = true; } } } if ( !e.isDefaultPrevented() && e.keyCode === OO.ui.Keys.TAB && // Not modified (excluding shift) !( e.metaKey || e.ctrlKey || e.altKey ) ) { // Manually move focus to the next/previous focusable element (T341687) const surfaceNode = this.$element[ 0 ]; const treeWalker = document.createTreeWalker( document.body, NodeFilter.SHOW_ELEMENT, ( n ) => { if ( surfaceNode.contains( n ) ) { return NodeFilter.FILTER_REJECT; } if ( OO.ui.isFocusableElement( $( n ) ) ) { return NodeFilter.FILTER_ACCEPT; } return NodeFilter.FILTER_SKIP; } ); treeWalker.currentNode = surfaceNode; if ( e.shiftKey ) { treeWalker.previousNode(); } else { treeWalker.nextNode(); } if ( treeWalker.currentNode ) { treeWalker.currentNode.focus(); e.preventDefault(); e.stopPropagation(); return; } } if ( this.readOnly && !( // Allowed keystrokes in readonly mode: // Arrows, simple navigation ve.ce.LinearArrowKeyDownHandler.static.keys.indexOf( e.keyCode ) !== -1 || // Potential commands: // Function keys... ( e.keyCode >= 112 && e.keyCode <= 123 ) || // ... or anything modified (e.g. copy / select-all), excluding shift e.metaKey || e.ctrlKey || e.altKey // Keys already handled in keyDownHandlers above do not need to be exempt here ) ) { e.preventDefault(); e.stopPropagation(); return; } if ( !updateFromModel ) { this.incRenderLock(); } try { this.surfaceObserver.pollOnce(); } finally { if ( !updateFromModel ) { this.decRenderLock(); } } this.surfaceObserver.startTimerLoop(); }; /** * Check if a trigger event is blocked from performing its default behaviour * * If any of these triggers can't execute on the surface, (e.g. the underline * command has been disabled), we should still preventDefault so ContentEditable * native commands don't occur, leaving the view out of sync with the model. * * @param {ve.ui.Trigger} trigger Trigger to check * @return {boolean} Trigger should preventDefault */ ve.ce.Surface.prototype.isBlockedTrigger = function ( trigger ) { const triggerString = trigger.toString(), platformKey = ve.getSystemPlatform() === 'mac' ? 'mac' : 'pc', blockedIfRegisteredTriggers = [ 'tab', 'shift+tab' ], blockedTriggers = { mac: [ 'cmd+b', 'cmd+i', 'cmd+u', 'cmd+z', 'cmd+y', 'cmd+shift+z', 'cmd+[', 'cmd+]' ], pc: [ 'ctrl+b', 'ctrl+i', 'ctrl+u', 'ctrl+z', 'ctrl+y', 'ctrl+shift+z' ] }; // Special case: only block Tab/Shift+Tab if indentation commands are enabled on this surface, // otherwise allow them to change focus if ( blockedIfRegisteredTriggers.indexOf( triggerString ) !== -1 ) { return !!this.surface.triggerListener.getCommandByTrigger( triggerString ); } return blockedTriggers[ platformKey ].indexOf( triggerString ) !== -1; }; /** * Handle document key press events. * * @param {jQuery.Event} e Key press event */ ve.ce.Surface.prototype.onDocumentKeyPress = function ( e ) { let selection; // Handle the case where keyPress Enter is fired without a matching keyDown. This can // happen with OS X Romanising Korean IMEs on Firefox, when pressing Enter with // uncommitted candidate text; see T120156. Behave as though keyDown Enter has been // fired. if ( e.keyCode === OO.ui.Keys.ENTER && !this.keyDownState.event && // We're only aware of cases of this happening with uncommitted candidate text, // which implies a native selection. But we instead perform a weaker test - for // a non-null selection - to match that same test in onDocumentKeyDown !( ( selection = this.getModel().getSelection() ).isNull() ) ) { this.surfaceObserver.stopTimerLoop(); if ( ve.ce.keyDownHandlerFactory.executeHandlersForKey( e.keyCode, selection.getName(), this, e ) ) { this.surfaceObserver.pollOnce(); } this.surfaceObserver.startTimerLoop(); return; } // Filter out non-character keys. Doing this prevents: // * Unexpected content deletion when selection is not collapsed and the user presses, for // example, the Home key (Firefox fires 'keypress' for it) // TODO: Should be covered with Selenium tests. if ( // Catches most keys that don't produce output (charCode === 0, thus no character) e.which === 0 || e.charCode === 0 || // Opera 12 doesn't always adhere to that convention e.keyCode === OO.ui.Keys.TAB || e.keyCode === OO.ui.Keys.ESCAPE || // Ignore all keypresses with Ctrl / Cmd modifier keys ve.ce.isShortcutKey( e ) ) { return; } this.handleInsertion(); }; /** * Deferred until after document key down event * * @param {jQuery.Event} e keydown event */ ve.ce.Surface.prototype.afterDocumentKeyDown = function ( e ) { const documentModel = this.getModel().getDocument(), isArrow = ( e.keyCode === OO.ui.Keys.UP || e.keyCode === OO.ui.Keys.DOWN || e.keyCode === OO.ui.Keys.LEFT || e.keyCode === OO.ui.Keys.RIGHT ); let keyDownSelectionState = null; /** * Determine whether a position is editable, and if so which focusable node it is in * * We can land inside ce=false in many browsers: * - Firefox has normal cursor positions at most node boundaries inside ce=false * - Chromium has superfluous cursor positions around a ce=false img * - IE hardly restricts editing at all inside ce=false * If ce=false then we have landed inside the focusable node. * If we land in a non-text position, assume we should have hit the node * immediately after the position we hit (in the direction of motion) * If we land inside a sequence of grouped nodes, assume we should treat them as a * unit instead of letting the cursor slip inside them. * * @private * @param {Node} node DOM node of cursor position * @param {number} offset Offset of cursor position * @param {number} dir Cursor motion direction (1=forward, -1=backward) * @return {ve.ce.Node|null} node, or null if not in a focusable node */ const getSurroundingFocusableNode = ( node, offset, dir ) => { let focusNode; if ( node.nodeType === Node.TEXT_NODE ) { focusNode = node; } else if ( dir > 0 && offset < node.childNodes.length ) { focusNode = node.childNodes[ offset ]; } else if ( dir < 0 && offset > 0 ) { focusNode = node.childNodes[ offset - 1 ]; } else { focusNode = node; } if ( ve.isContentEditable( focusNode ) ) { // We are allowed to be inside this focusable node (e.g. editing a // table cell or caption). return null; } return $( focusNode ).closest( '.ve-ce-focusableNode, .ve-ce-tableNode' ).data( 'view' ) || null; }; /** * Compute the direction of cursor movement, if any * * Even if the user pressed a cursor key in the interior of the document, there may not * be any movement: browser BIDI and ce=false handling can be quite quirky. * * Furthermore, the keydown selection nodes may have become detached since keydown (e.g. * if ve.ce.ContentBranchNode#renderContents has run). * * @return {number|null} negative for startwards, positive for endwards, null for none */ const getDirection = () => ( isArrow && keyDownSelectionState && ve.compareDocumentOrder( this.nativeSelection.focusNode, this.nativeSelection.focusOffset, keyDownSelectionState.focusNode, keyDownSelectionState.focusOffset ) ) || null; if ( e !== this.keyDownState.event ) { return; } keyDownSelectionState = this.keyDownState.selectionState; this.clearKeyDownState(); if ( ( e.keyCode === OO.ui.Keys.BACKSPACE || e.keyCode === OO.ui.Keys.DELETE ) && this.nativeSelection.focusNode ) { const inNonSlug = this.nativeSelection.focusNode.nodeType === Node.ELEMENT_NODE && !this.nativeSelection.focusNode.classList.contains( 've-ce-branchNode-inlineSlug' ); if ( inNonSlug ) { // In a non-slug element. Sync the DM, then see if we need a slug. this.incRenderLock(); try { this.surfaceObserver.pollOnce(); } finally { this.decRenderLock(); } const dmSelection = this.model.getSelection(); if ( dmSelection instanceof ve.dm.LinearSelection ) { const dmFocus = dmSelection.getRange().end; const ceNode = this.documentView.getBranchNodeFromOffset( dmFocus ); if ( ceNode && ceNode.getModel().hasSlugAtOffset( dmFocus ) ) { ceNode.setupBlockSlugs(); } } } // Remove then re-set the selection, to clear any browser-native preannotations. // This should be IME-safe because delete/backspace key events should only happen // when there is no IME candidate window open. // // Note that if an IME removes text otherwise than by delete/backspace, then // browser-native preannotations might still get applied. This can happen: see // https://phabricator.wikimedia.org/T116275 . // That's nasty, but it's not a reason to leave the delete/backspace case broken. const ceSelection = new ve.SelectionState( this.nativeSelection ); this.nativeSelection.removeAllRanges(); this.showSelectionState( ceSelection ); if ( inNonSlug ) { return; } } // Only fixup cursoring on linear selections. if ( isArrow && !( this.model.getSelection() instanceof ve.dm.LinearSelection ) ) { return; } // Restore the selection and stop, if we cursored out of a table edit cell. // Assumption: if we cursored out of a table cell, then none of the fixups below this point // would have got the selection back inside the cell. Therefore it's OK to check here. if ( isArrow && this.restoreActiveNodeSelection() ) { return; } // If we landed in a cursor holder, select the corresponding focusable node instead // (which, for a table, will select the first cell). Else if we arrowed a collapsed // cursor across a focusable node, select the node instead. const $focusNode = $( this.nativeSelection.focusNode ); let direction; let focusableNode; let range; // eslint-disable-next-line no-jquery/no-class-state if ( $focusNode.hasClass( 've-ce-cursorHolder' ) ) { // eslint-disable-next-line no-jquery/no-class-state if ( $focusNode.hasClass( 've-ce-cursorHolder-after' ) ) { direction = -1; focusableNode = $focusNode.prev().data( 'view' ); } else { direction = 1; focusableNode = $focusNode.next().data( 'view' ); } this.removeCursorHolders(); } else if ( // If we arrowed a collapsed cursor into/across a focusable node, select the node instead isArrow && !e.ctrlKey && !e.altKey && !e.metaKey && keyDownSelectionState && keyDownSelectionState.isCollapsed && this.nativeSelection.isCollapsed && ( direction = getDirection() ) !== null ) { focusableNode = getSurroundingFocusableNode( this.nativeSelection.focusNode, this.nativeSelection.focusOffset, direction ); if ( !focusableNode ) { let startOffset, endOffset, offsetDiff; // Calculate the DM offsets of our motion try { startOffset = ve.ce.getOffset( keyDownSelectionState.focusNode, keyDownSelectionState.focusOffset ); endOffset = ve.ce.getOffset( this.nativeSelection.focusNode, this.nativeSelection.focusOffset ); offsetDiff = endOffset - startOffset; } catch ( ex ) { startOffset = endOffset = offsetDiff = undefined; } if ( Math.abs( offsetDiff ) === 2 ) { // Test whether we crossed a focusable node // (this applies even if we cursored up/down) focusableNode = documentModel.documentNode .getNodeFromOffset( ( startOffset + endOffset ) / 2 ); if ( focusableNode.isFocusable() ) { range = new ve.Range( startOffset, endOffset ); } else { focusableNode = undefined; } } } } if ( isArrow && direction > 0 && this.getActiveNode() instanceof ve.ce.TableCaptionNode && this.getActiveNode() !== $focusNode.closest( '.ve-ce-tableCaptionNode' ).data( 'view' ) ) { // We cursored down out of the table caption; move to the first table cell const tableNode = this.getActiveNode().getParent(); this.model.setSelection( new ve.dm.TableSelection( tableNode.getOuterRange(), 0, 0 ) ); } if ( focusableNode ) { if ( !range ) { range = focusableNode.getOuterRange(); if ( direction < 0 ) { range = range.flip(); } } if ( focusableNode instanceof ve.ce.TableNode ) { if ( direction > 0 ) { let captionNode; if ( ( captionNode = focusableNode.getModel().getCaptionNode() ) ) { this.model.setLinearSelection( documentModel.getRelativeRange( new ve.Range( captionNode.getRange().start ), 1 ) ); } else { this.model.setSelection( new ve.dm.TableSelection( range, 0, 0 ) ); } } else { const matrix = focusableNode.getModel().getMatrix(); const row = matrix.getRowCount() - 1; const col = matrix.getColCount( row ) - 1; this.model.setSelection( new ve.dm.TableSelection( range, col, row ) ); } } else { this.model.setLinearSelection( range ); } if ( e.keyCode === OO.ui.Keys.LEFT ) { this.cursorDirectionality = direction > 0 ? 'rtl' : 'ltr'; } else if ( e.keyCode === OO.ui.Keys.RIGHT ) { this.cursorDirectionality = direction < 0 ? 'rtl' : 'ltr'; } // else up/down pressed; leave this.cursorDirectionality as null // (it was set by setLinearSelection calling onModelSelect) } if ( direction === undefined ) { direction = getDirection(); } const fixupCursorForUnicorn = ( !e.shiftKey && ( e.keyCode === OO.ui.Keys.LEFT || e.keyCode === OO.ui.Keys.RIGHT ) ); const removedUnicorns = this.cleanupUnicorns( fixupCursorForUnicorn ); if ( removedUnicorns ) { this.surfaceObserver.pollOnceNoCallback(); } else { this.incRenderLock(); try { this.surfaceObserver.pollOnce(); } finally { this.decRenderLock(); } } this.fixupCursorPosition( direction, e.shiftKey ); }; /** * Check whether the DOM selection has moved out of the unicorned area (i.e. is not currently * between two unicorns) and if so, set the model selection from the DOM selection, destroy the * unicorns and return true. If there are no active unicorns, this function does nothing and * returns false. * * If the unicorns are destroyed as a consequence of the user moving the cursor across a unicorn * with the left/rightarrow keys, the cursor will have to be moved again to produce the cursor * movement the user expected. Set the fixupCursor parameter to true to enable this behavior. * * @param {boolean} fixupCursor If destroying unicorns, fix up left/rightarrow cursor position * @return {boolean} Whether unicorns have been destroyed */ ve.ce.Surface.prototype.cleanupUnicorns = function ( fixupCursor ) { if ( !this.unicorningNode || !this.unicorningNode.unicorns ) { return false; } const preUnicorn = this.unicorningNode.unicorns[ 0 ]; if ( !this.$attachedRootNode[ 0 ].contains( preUnicorn ) ) { return false; } if ( this.nativeSelection.rangeCount === 0 ) { // XXX do we want to clear unicorns in this case? return false; } const range = this.nativeSelection.getRangeAt( 0 ); // Test whether the selection endpoint is between unicorns. If so, do nothing. // Unicorns can only contain text, so just move backwards until we hit a non-text node. let node = range.endContainer; if ( node.nodeType === Node.ELEMENT_NODE ) { node = range.endOffset > 0 ? node.childNodes[ range.endOffset - 1 ] : null; } while ( node !== null && node.nodeType === Node.TEXT_NODE ) { node = node.previousSibling; } if ( node === preUnicorn ) { return false; } // Selection endpoint is not between unicorns. // Test whether it is before or after the pre-unicorn (i.e. before/after both unicorns) let fixup; if ( ve.compareDocumentOrder( range.endContainer, range.endOffset, preUnicorn.parentNode, ve.parentIndex( preUnicorn ) ) <= 0 ) { // Before the pre-unicorn (including in the equality case, because the selection // endpoint is an offset between sibling positions) fixup = -1; } else { // At or after the pre-unicorn (actually must be after the post-unicorn) fixup = 1; } const contentBranchNodeBefore = this.getSelectedContentBranchNode(); if ( this.unicorningNode !== contentBranchNodeBefore ) { this.setNotUnicorningAll(); return true; } // Apply the DOM selection to the model const veRange = ve.ce.veRangeFromSelection( this.nativeSelection ); if ( veRange ) { this.incRenderLock(); try { // The most likely reason for this condition to not-pass is if we // try to cleanup unicorns while the native selection is outside // the model momentarily, as sometimes happens during paste. this.changeModel( null, new ve.dm.LinearSelection( veRange ) ); if ( fixupCursor ) { this.moveModelCursor( fixup ); } } finally { this.decRenderLock(); } } const contentBranchNodeAfter = this.getSelectedContentBranchNode(); if ( contentBranchNodeAfter ) { contentBranchNodeAfter.renderContents(); } if ( contentBranchNodeBefore && contentBranchNodeBefore !== contentBranchNodeAfter ) { contentBranchNodeBefore.renderContents(); } this.showModelSelection(); return true; }; /** * Handle document key up events. * * @param {jQuery.Event} e Key up event * @fires ve.ce.Surface#keyup */ ve.ce.Surface.prototype.onDocumentKeyUp = function () { this.emit( 'keyup' ); }; /** * Handle cut events. * * @param {jQuery.Event} e Cut event */ ve.ce.Surface.prototype.onCut = function ( e ) { const selection = this.getModel().getSelection(); if ( selection.isCollapsed() ) { return; } this.onCopy( e ); // setTimeout: postpone until after the setTimeout in onCopy setTimeout( () => { // Trigger a fake backspace to remove the content: this behaves differently based on the selection, // e.g. in a TableSelection. ve.ce.keyDownHandlerFactory.executeHandlersForKey( OO.ui.Keys.BACKSPACE, selection.getName(), this, e ); } ); }; /** * Handle copy (including cut) and dragstart events. * * @param {jQuery.Event} e Copy event * @param {ve.dm.Selection} selection Optional selection to simulate a copy on */ ve.ce.Surface.prototype.onCopy = function ( e, selection ) { // Copy or cut, but not dragstart const isClipboard = e.type === 'copy' || e.type === 'cut', htmlDoc = this.getModel().getDocument().getHtmlDocument(), clipboardData = isClipboard ? e.originalEvent.clipboardData : e.originalEvent.dataTransfer; selection = selection || this.getModel().getSelection(); this.$pasteTarget.empty(); if ( selection.isCollapsed() ) { return; } const slice = this.model.documentModel.shallowCloneFromSelection( selection ); // Clone the elements in the slice slice.data.cloneElements( true ); ve.dm.converter.getDomSubtreeFromModel( slice, this.$pasteTarget[ 0 ], ve.dm.Converter.static.CLIPBOARD_MODE ); // Some browsers strip out spans when they match the styling of the // paste target (e.g. plain spans) so we must protect against this // by adding a dummy class, which we can remove after paste. this.$pasteTarget.find( 'span' ).addClass( 've-pasteProtect' ); // When paste has no text content browsers do extreme normalization… if ( this.$pasteTarget.text() === '' ) { // …so put nbsp's in empty leaves // eslint-disable-next-line no-jquery/no-sizzle this.$pasteTarget.find( '*:not( :has( * ) )' ).text( '\u00a0' ); } // Resolve attributes (in particular, expand 'href' and 'src' using the right base) ve.resolveAttributes( this.$pasteTarget[ 0 ], htmlDoc, ve.dm.Converter.static.computedAttributes ); // Support: Firefox // Some attributes (e.g RDFa attributes in Firefox) aren't preserved by copy const unsafeSelector = '[' + ve.ce.Surface.static.unsafeAttributes.join( '],[' ) + ']'; this.$pasteTarget.find( unsafeSelector ).each( ( n, element ) => { const attrs = {}, ua = ve.ce.Surface.static.unsafeAttributes; let i = ua.length; while ( i-- ) { const val = element.getAttribute( ua[ i ] ); if ( val !== null ) { attrs[ ua[ i ] ] = val; } } element.setAttribute( 'data-ve-attributes', JSON.stringify( attrs ) ); } ); this.clipboardIndex++; const clipboardKey = this.clipboardId + '-' + this.clipboardIndex; this.clipboard = { slice: slice, hash: null }; // Support: Firefox<48 // Writing the key to text/xcustom won't work in Firefox<48, so write // it to the HTML instead if ( isClipboard && !ve.isClipboardDataFormatsSupported( e ) ) { this.$pasteTarget.prepend( $( '' ).attr( 'data-ve-clipboard-key', clipboardKey ).text( '\u00a0' ) ); // To ensure the contents with the clipboardKey isn't modified in an external editor, // store a hash of the contents for later validation. this.clipboard.hash = this.constructor.static.getClipboardHash( this.$pasteTarget.contents() ); } if ( isClipboard ) { // Disable the default event so we can override the data e.preventDefault(); } // Only write a custom mime type if we think the browser supports it, otherwise // we will have already written a key to the HTML above. if ( isClipboard && ve.isClipboardDataFormatsSupported( e, true ) ) { clipboardData.setData( 'text/xcustom', clipboardKey ); } clipboardData.setData( 'text/html', this.$pasteTarget.html() ); // innerText "approximates the text the user would get if they highlighted the // contents of the element with the cursor and then copied to the clipboard." - MDN // Use $.text as a fallback for Firefox <= 44 clipboardData.setData( 'text/plain', this.$pasteTarget[ 0 ].innerText || this.$pasteTarget.text() || ' ' ); ve.track( 'activity.clipboard', { action: e.type } ); }; /** * Get the annotation set that was a the user focus before a paste started * * @return {ve.dm.AnnotationSet} Annotation set */ ve.ce.Surface.prototype.getBeforePasteAnnotationSet = function () { const store = this.getModel().getDocument().getStore(); const dmAnnotations = this.beforePasteAnnotationsAtFocus.map( ( view ) => view.getModel() ); return new ve.dm.AnnotationSet( store, store.hashAll( dmAnnotations ) ); }; /** * Handle native paste event * * @param {jQuery.Event} e Paste event * @return {boolean|undefined} False if the event is cancelled */ ve.ce.Surface.prototype.onPaste = function ( e ) { // Prevent pasting until after we are done if ( this.pasting || this.readOnly ) { return false; } this.beforePaste( e ); this.surfaceObserver.disable(); this.pasting = true; // setTimeout: postpone until after the default paste action setTimeout( () => { let afterPastePromise = ve.createDeferred().resolve().promise(); try { if ( !e.isDefaultPrevented() ) { afterPastePromise = this.afterPaste( e ); } } finally { afterPastePromise.always( () => { this.surfaceObserver.clear(); this.surfaceObserver.enable(); // Allow pasting again this.pasting = false; this.pasteSpecial = false; this.beforePasteData = null; // Restore original clipboard metadata if requred (was overridden by middle-click // paste logic in beforePaste) if ( this.originalClipboardMetdata ) { this.clipboardIndex = this.originalClipboardMetdata.clipboardIndex; this.clipboard = this.originalClipboardMetdata.clipboard; } ve.track( 'activity.clipboard', { action: 'paste' } ); } ); } } ); }; /** * Handle pre-paste events. * * @param {jQuery.Event} e Paste event */ ve.ce.Surface.prototype.beforePaste = function ( e ) { const selection = this.getModel().getSelection(), clipboardData = e.originalEvent.clipboardData, surfaceModel = this.getModel(), fragment = surfaceModel.getFragment(), documentModel = surfaceModel.getDocument(); let range; if ( selection instanceof ve.dm.LinearSelection ) { range = fragment.getSelection().getRange(); } else if ( selection instanceof ve.dm.TableSelection ) { range = new ve.Range( selection.getRanges( documentModel )[ 0 ].start ); } else { e.preventDefault(); return; } this.beforePasteAnnotationsAtFocus = this.annotationsAtFocus(); this.beforePasteData = {}; this.originalClipboardMetdata = null; if ( this.middleClickPasting && !this.lastNonCollapsedDocumentSelection.isNull() ) { // Paste was triggered by middle click, and the last non-collapsed document selection was in // this VE surface. Simulate a fake copy to load DM data into the clipboard. If we let the // native middle-click paste happen, it would load CE data into the clipboard. // Store original clipboard metadata so it can be restored after paste, // and we can continue to use internal paste. this.originalClipboardMetdata = { clipboardIndex: this.clipboardIndex, clipboard: this.clipboard }; // Use a fake clipboard index for middle click, will be restored in afterPaste this.clipboardIndex = -1; this.clipboard = { slice: this.model.documentModel.shallowCloneFromSelection( this.lastNonCollapsedDocumentSelection ), hash: null }; this.beforePasteData.custom = this.clipboardId + '-' + this.clipboardIndex; } else if ( clipboardData ) { if ( this.handleDataTransfer( clipboardData, true ) ) { e.preventDefault(); return; } this.beforePasteData.custom = clipboardData.getData( 'text/xcustom' ); this.beforePasteData.html = clipboardData.getData( 'text/html' ); if ( this.beforePasteData.html ) { // http://msdn.microsoft.com/en-US/en-%20us/library/ms649015(VS.85).aspx this.beforePasteData.html = this.beforePasteData.html .replace( /^[\s\S]*/, '' ) .replace( /[\s\S]*$/, '' ); } } // Save scroll position before changing focus to "offscreen" paste target this.beforePasteData.scrollTop = this.surface.$scrollContainer.scrollTop(); this.$pasteTarget.empty(); // Get node from cursor position const startNode = documentModel.getBranchNodeFromOffset( range.start ); if ( startNode.canContainContent() ) { // If this is a content branch node, then add its DM HTML // to the paste target to give CE some context. let textStart = 0, textEnd = 0; const contextElement = startNode.getClonedElement(); // Make sure that context doesn't have any attributes that might confuse // the importantElement check in afterPaste. $( documentModel.getStore().value( contextElement.originalDomElementsHash ) ).removeAttr( 'id typeof rel' ); const context = [ contextElement ]; // If there is content to the left of the cursor, put a placeholder // character to the left of the cursor let leftText, rightText; if ( range.start > startNode.getRange().start ) { leftText = '☀'; context.push( leftText ); textStart = textEnd = 1; } // If there is content to the right of the cursor, put a placeholder // character to the right of the cursor const endNode = documentModel.getBranchNodeFromOffset( range.end ); if ( range.end < endNode.getRange().end ) { rightText = '☂'; context.push( rightText ); } // If there is no text context, select some text to be replaced if ( !leftText && !rightText ) { context.push( '☁' ); textEnd = 1; // If we are middle click pasting we can't change the native selection, so // just make the text a placeholder to the left. (T311723) if ( this.middleClickPasting ) { leftText = '☁'; textStart = 1; } } context.push( { type: '/' + context[ 0 ].type } ); // Throw away 'internal', specifically inner whitespace, // before conversion as it can affect textStart/End offsets. delete contextElement.internal; ve.dm.converter.getDomSubtreeFromModel( documentModel.cloneWithData( context, true ), this.$pasteTarget[ 0 ] ); // Giving the paste target focus too late can cause problems in FF (!?) // so do it up here. this.$pasteTarget[ 0 ].focus(); const nativeRange = this.getElementDocument().createRange(); // Assume that the DM node only generated one child const textNode = this.$pasteTarget.children().contents()[ 0 ]; // Place the cursor between the placeholder characters nativeRange.setStart( textNode, textStart ); nativeRange.setEnd( textNode, textEnd ); this.nativeSelection.removeAllRanges(); this.nativeSelection.addRange( nativeRange ); this.beforePasteData.context = context; this.beforePasteData.leftText = leftText; this.beforePasteData.rightText = rightText; } else { // If we're not in a content branch node, don't bother trying to do // anything clever with paste context this.$pasteTarget[ 0 ].focus(); } // Restore scroll position after focusing the paste target this.surface.$scrollContainer.scrollTop( this.beforePasteData.scrollTop ); }; /** * Handle post-paste events. * * @param {jQuery.Event} e Paste event * @return {jQuery.Promise} Promise which resolves when the content has been pasted */ ve.ce.Surface.prototype.afterPaste = function () { const surfaceModel = this.getModel(), documentModel = surfaceModel.getDocument(), fragment = surfaceModel.getFragment(), beforePasteData = this.beforePasteData || {}, done = ve.createDeferred().resolve().promise(); let targetFragment = surfaceModel.getFragment( null, true ); // If the selection doesn't collapse after paste then nothing was inserted if ( !this.nativeSelection.isCollapsed ) { return done; } if ( this.getModel().getFragment().isNull() ) { return done; } if ( this.middleClickTargetOffset ) { targetFragment = targetFragment.clone( new ve.dm.LinearSelection( new ve.Range( this.middleClickTargetOffset ) ) ); } else if ( this.middleClickPasting ) { // Middle click pasting should always collapse the selection before pasting targetFragment = targetFragment.collapseToEnd(); } // Immedately remove any