8
8
import $ from "jquery" ;
9
9
import ko from "knockout" ;
10
10
import keyCodes from "Magento_Ui/js/lib/key-codes" ;
11
+ import _ from "underscore" ;
11
12
12
13
/**
13
14
* Add or remove the placeholder-text class from the element based on its content
@@ -37,7 +38,6 @@ ko.bindingHandlers.liveEdit = {
37
38
init ( element , valueAccessor , allBindings , viewModel , bindingContext ) {
38
39
const { field, placeholder} = valueAccessor ( ) ;
39
40
let focusedValue = element . innerHTML ;
40
-
41
41
/**
42
42
* Strip HTML and return text
43
43
*
@@ -81,6 +81,7 @@ ko.bindingHandlers.liveEdit = {
81
81
*
82
82
* Prevent styling such as bold, italic, and underline using keyboard commands
83
83
* Prevent multi-line entries
84
+ * Debounce the saving of the state to 1 second to ensure that on save without first unfocus will succeed
84
85
*
85
86
* @param {any } event
86
87
*/
@@ -100,6 +101,32 @@ ko.bindingHandlers.liveEdit = {
100
101
if ( key === "pageLeftKey" || key === "pageRightKey" ) {
101
102
event . stopPropagation ( ) ;
102
103
}
104
+
105
+ _ . debounce ( ( ) => {
106
+ const selection = window . getSelection ( ) ;
107
+ const range = document . createRange ( ) ;
108
+ const getCharPosition = ( editableDiv : HTMLElement ) => {
109
+ let charPosition = 0 ;
110
+
111
+ if ( window . getSelection ) {
112
+ if ( selection . rangeCount ) {
113
+ if ( selection . getRangeAt ( 0 ) . commonAncestorContainer . parentNode === editableDiv ) {
114
+ charPosition = selection . getRangeAt ( 0 ) . endOffset ;
115
+ }
116
+ }
117
+ }
118
+ return charPosition ;
119
+ } ;
120
+ const pos : number = getCharPosition ( element ) ;
121
+
122
+ if ( focusedValue !== stripHtml ( element . innerHTML ) ) {
123
+ viewModel . updateData ( field , stripHtml ( element . innerHTML ) ) ;
124
+ }
125
+ range . setStart ( element . childNodes [ 0 ] , pos ) ;
126
+ range . collapse ( true ) ;
127
+ selection . removeAllRanges ( ) ;
128
+ selection . addRange ( range ) ;
129
+ } , 1000 ) . call ( this ) ;
103
130
} ;
104
131
105
132
/**
0 commit comments