-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathinsert.js
47 lines (40 loc) · 1.08 KB
/
insert.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
/* global Node, getSelection */
export default function insert (text) {
let ae = document.activeElement
if (ae.tagName === 'INPUT' || ae.tagName === 'TEXTAREA') {
return insertToTextarea(text, ae)
} else {
return insertToEditable(text)
}
}
function insertToEditable (text) {
let r = getRange()
let node = r.endContainer
r.deleteContents()
if (node.nodeType === Node.TEXT_NODE) {
let cut = r.endOffset
node.data = node.data.slice(0, cut) +
text + node.data.slice(cut)
r.setEnd(node, cut + text.length)
} else {
let t = document.createTextNode(text)
r.insertNode(t)
r.setEndAfter(t)
}
r.collapse(false) // arg is required in IE
}
function insertToTextarea (text, ta) {
let start = ta.selectionStart
let end = ta.selectionEnd
ta.value = ta.value.slice(0, start) +
text + ta.value.slice(end)
let newEnd = start + text.length
ta.selectionStart = newEnd
ta.selectionEnd = newEnd
}
function getRange () {
let selection = getSelection()
if (selection && selection.rangeCount > 0) {
return selection.getRangeAt(0)
}
}