@@ -259,15 +259,22 @@ function parseRangesToHTMLNodes(
259
259
return { dom : rootElement , tree : rootNode } ;
260
260
}
261
261
262
- function moveCursor ( isFocused : boolean , alwaysMoveCursorToTheEnd : boolean , cursorPosition : number | null , target : MarkdownTextInputElement , shouldScrollIntoView = false ) {
262
+ function moveCursor (
263
+ isFocused : boolean ,
264
+ alwaysMoveCursorToTheEnd : boolean ,
265
+ cursorPosition : number | null ,
266
+ target : MarkdownTextInputElement ,
267
+ selectionEnd : number | null = null ,
268
+ shouldScrollIntoView = false ,
269
+ ) {
263
270
if ( ! isFocused ) {
264
271
return ;
265
272
}
266
273
267
274
if ( alwaysMoveCursorToTheEnd || cursorPosition === null ) {
268
275
moveCursorToEnd ( target ) ;
269
276
} else if ( cursorPosition !== null ) {
270
- setCursorPosition ( target , cursorPosition , null , shouldScrollIntoView ) ;
277
+ setCursorPosition ( target , cursorPosition , selectionEnd , shouldScrollIntoView ) ;
271
278
}
272
279
}
273
280
@@ -281,15 +288,19 @@ function updateInputStructure(
281
288
shouldForceDOMUpdate = false ,
282
289
shouldScrollIntoView = false ,
283
290
inlineImagesProps : InlineImagesInputProps = { } ,
291
+ shouldPreserveSelection = false ,
284
292
) {
285
293
const targetElement = target ;
286
294
287
295
// in case the cursorPositionIndex is larger than text length, cursorPosition will be null, i.e: move the caret to the end
288
296
let cursorPosition : number | null = cursorPositionIndex !== null && cursorPositionIndex <= text . length ? cursorPositionIndex : null ;
297
+ let selectionEndPosition : number | null = null ;
289
298
const isFocused = document . activeElement === target ;
290
299
if ( isFocused && cursorPositionIndex === null ) {
291
300
const selection = getCurrentCursorPosition ( target ) ;
292
301
cursorPosition = selection ? selection . start : null ;
302
+ // in some cases like rerendering because style was changed we want to preserve selection
303
+ selectionEndPosition = shouldPreserveSelection && selection ? selection . end : null ;
293
304
}
294
305
const markdownRanges = global . parseExpensiMarkToRanges ( text ) ;
295
306
if ( ! text || targetElement . innerHTML === '<br>' || ( targetElement && targetElement . innerHTML === '\n' ) ) {
@@ -312,7 +323,7 @@ function updateInputStructure(
312
323
updateTreeElementRefs ( tree , targetElement ) ;
313
324
targetElement . tree = tree ;
314
325
315
- moveCursor ( isFocused , alwaysMoveCursorToTheEnd , cursorPosition , targetElement , shouldScrollIntoView ) ;
326
+ moveCursor ( isFocused , alwaysMoveCursorToTheEnd , cursorPosition , targetElement , selectionEndPosition , shouldScrollIntoView ) ;
316
327
} else {
317
328
targetElement . tree = createRootTreeNode ( targetElement ) ;
318
329
}
0 commit comments