Skip to content

Commit 808c3d8

Browse files
authored
Merge pull request #28 from steffen/add-undo-support
Add "undo" support
2 parents 194a0a2 + 918ef92 commit 808c3d8

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
@@ -26,7 +26,7 @@ function onPaste(event: ClipboardEvent) {
2626
event.stopPropagation()
2727
event.preventDefault()
2828

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

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

0 commit comments

Comments
 (0)