Skip to content

Commit 226276b

Browse files
committed
Fix insertText
- Correctly position cursor after operation if extra newline was inserted - Correctly replace existing selection
1 parent 52cb260 commit 226276b

1 file changed

Lines changed: 8 additions & 7 deletions

File tree

src/text.js

Lines changed: 8 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,14 +1,15 @@
11
/* @flow strict */
22

33
export function insertText(textarea: HTMLInputElement | HTMLTextAreaElement, text: string): void {
4-
const point = textarea.selectionEnd
5-
const beginning = textarea.value.substring(0, point)
6-
const remaining = textarea.value.substring(point)
7-
const newline = textarea.value === '' || beginning.match(/\n$/) ? '' : '\n'
4+
const beginning = textarea.value.substring(0, textarea.selectionStart)
5+
const remaining = textarea.value.substring(textarea.selectionEnd)
86

9-
textarea.value = beginning + newline + text + remaining
10-
textarea.selectionStart = point + text.length
11-
textarea.selectionEnd = point + text.length
7+
const newline = beginning.length === 0 || beginning.match(/\n$/) ? '' : '\n'
8+
const textBeforeCursor = beginning + newline + text
9+
10+
textarea.value = textBeforeCursor + remaining
11+
textarea.selectionStart = textBeforeCursor.length
12+
textarea.selectionEnd = textarea.selectionStart
1213

1314
textarea.dispatchEvent(
1415
new CustomEvent('change', {

0 commit comments

Comments
 (0)