From 4ba80ca7f5472dbdbccc1afa9ebf3549700f2778 Mon Sep 17 00:00:00 2001 From: Derk-Jan Hartman Date: Sun, 18 Nov 2018 01:48:56 +0100 Subject: [PATCH] textSelection: Use execcommand to replace text This preserves the undo history. Should be supported by all browsers but Firefox. Bug: T33780 Change-Id: I857965141e8e3aeabacf505d6cfce798f88a9711 --- resources/src/jquery/jquery.textSelection.js | 27 ++++++++++++-------- 1 file changed, 16 insertions(+), 11 deletions(-) diff --git a/resources/src/jquery/jquery.textSelection.js b/resources/src/jquery/jquery.textSelection.js index 6b4ab979a1..cbbed995a6 100644 --- a/resources/src/jquery/jquery.textSelection.js +++ b/resources/src/jquery/jquery.textSelection.js @@ -71,7 +71,10 @@ setContents: function ( content ) { return this.each( function () { var scrollTop = this.scrollTop; - $( this ).val( content ); + this.select(); + if ( !document.execCommand( 'insertText', false, content ) ) { + $( this ).val( content ); + } // Setting this.value may scroll the textarea, restore the scroll position this.scrollTop = scrollTop; } ); @@ -108,17 +111,19 @@ return this.each( function () { var allText, currSelection, startPos, endPos; - allText = $( this ).textSelection( 'getContents' ); - currSelection = $( this ).textSelection( 'getCaretPosition', { startAndEnd: true } ); - startPos = currSelection[ 0 ]; - endPos = currSelection[ 1 ]; + if ( !document.execCommand( 'insertText', false, value ) ) { + allText = $( this ).textSelection( 'getContents' ); + currSelection = $( this ).textSelection( 'getCaretPosition', { startAndEnd: true } ); + startPos = currSelection[ 0 ]; + endPos = currSelection[ 1 ]; - $( this ).textSelection( 'setContents', allText.slice( 0, startPos ) + value + - allText.slice( endPos ) ); - $( this ).textSelection( 'setSelection', { - start: startPos, - end: startPos + value.length - } ); + $( this ).textSelection( 'setContents', allText.slice( 0, startPos ) + value + + allText.slice( endPos ) ); + $( this ).textSelection( 'setSelection', { + start: startPos, + end: startPos + value.length + } ); + } } ); }, -- 2.20.1