|
1 |
| -export function insertText( |
2 |
| - textarea: HTMLInputElement | HTMLTextAreaElement, |
3 |
| - text: string, |
4 |
| - options = {addNewline: true} |
5 |
| -): void { |
6 |
| - const beginning = textarea.value.substring(0, textarea.selectionStart || 0) |
7 |
| - const remaining = textarea.value.substring(textarea.selectionEnd || 0) |
| 1 | +export function insertText(textarea: HTMLInputElement | HTMLTextAreaElement, text: string): void { |
| 2 | + const before = textarea.value.slice(0, textarea.selectionStart ?? undefined) |
| 3 | + const after = textarea.value.slice(textarea.selectionEnd ?? undefined) |
8 | 4 |
|
9 |
| - const newline = !options.addNewline || beginning.length === 0 || beginning.match(/\n$/) ? '' : '\n' |
10 |
| - const textBeforeCursor = beginning + newline + text |
| 5 | + let canInsertText = true |
11 | 6 |
|
12 |
| - textarea.value = textBeforeCursor + remaining |
13 |
| - textarea.selectionStart = textBeforeCursor.length |
14 |
| - textarea.selectionEnd = textarea.selectionStart |
| 7 | + textarea.contentEditable = 'true' |
| 8 | + try { |
| 9 | + canInsertText = document.execCommand('insertText', false, text) |
| 10 | + } catch (error) { |
| 11 | + canInsertText = false |
| 12 | + } |
| 13 | + textarea.contentEditable = 'false' |
15 | 14 |
|
16 |
| - textarea.dispatchEvent( |
17 |
| - new CustomEvent('change', { |
18 |
| - bubbles: true, |
19 |
| - cancelable: false |
20 |
| - }) |
21 |
| - ) |
| 15 | + if (canInsertText && !textarea.value.slice(0, textarea.selectionStart ?? undefined).endsWith(text)) { |
| 16 | + canInsertText = false |
| 17 | + } |
22 | 18 |
|
23 |
| - textarea.focus() |
| 19 | + if (!canInsertText) { |
| 20 | + try { |
| 21 | + document.execCommand('ms-beginUndoUnit') |
| 22 | + } catch (e) { |
| 23 | + // Do nothing. |
| 24 | + } |
| 25 | + textarea.value = before + text + after |
| 26 | + try { |
| 27 | + document.execCommand('ms-endUndoUnit') |
| 28 | + } catch (e) { |
| 29 | + // Do nothing. |
| 30 | + } |
| 31 | + textarea.dispatchEvent(new CustomEvent('change', {bubbles: true, cancelable: true})) |
| 32 | + } |
24 | 33 | }
|
0 commit comments