Skip to content

Commit 6daef3b

Browse files
authored
Add "undo" support
1 parent e2b975b commit 6daef3b

File tree

2 files changed

+29
-20
lines changed

2 files changed

+29
-20
lines changed

src/paste-markdown-link.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -25,7 +25,7 @@ function onPaste(event: ClipboardEvent) {
2525

2626
const selectedText = field.value.substring(field.selectionStart, field.selectionEnd)
2727

28-
insertText(field, linkify(selectedText, text), {addNewline: false})
28+
insertText(field, linkify(selectedText, text))
2929
}
3030

3131
function hasPlainText(transfer: DataTransfer): boolean {

src/text.ts

Lines changed: 28 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -1,24 +1,33 @@
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)
84

9-
const newline = !options.addNewline || beginning.length === 0 || beginning.match(/\n$/) ? '' : '\n'
10-
const textBeforeCursor = beginning + newline + text
5+
let canInsertText = true
116

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'
1514

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+
}
2218

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('input', {bubbles: true, cancelable: true}))
32+
}
2433
}

0 commit comments

Comments
 (0)