-
Notifications
You must be signed in to change notification settings - Fork 1
/
dy-textarea.js
88 lines (73 loc) · 2.16 KB
/
dy-textarea.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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
class DYTextArea extends HTMLElement {
constructor(){
super()
const initialValue = this.textContent || this.getAttribute('value')
this.replaceContents(
this.$editor = html`<span contenteditable></span>`,
this.$input = html`<textarea class="input" tabindex="-1"></textarea>`
)
const {$editor, $input} = this
for(const {name, value} of this.attributes){
if(name === 'class' || name === 'id') continue
if(name !== 'name') this.$editor.setAttribute(name, value)
this.$input.setAttribute(name, value)
}
if(initialValue) this.value = initialValue
try { $editor.contentEditable = 'plaintext-only' }catch(e){}
$editor.on({
paste: e => {
e.preventDefault()
// const text = e.clipboardData.getData('Text')
// document.execCommand('inserttext', false, text)
const text = e.clipboardData.getData('text/plain')
document.execCommand('insertHTML', false, text)
},
// https://stackoverflow.com/questions/48517637/ie11-drop-plain-text-into-contenteditable-div
drop: e => {
e.preventDefault()
const text = e.dataTransfer.getData('Text')
const range = document.caretRangeFromPoint(e.clientX, e.clientY)
range.deleteContents()
const textNode = document.createTextNode(text)
range.insertNode(textNode)
range.selectNodeContents(textNode)
range.collapse(false)
const selection = window.getSelection()
selection.removeAllRanges()
selection.addRange(range)
},
copy: e => {
if (e.clipboardData) {
const text = window.getSelection().toString()
e.clipboardData.setData('text/plain', text)
e.preventDefault()
}
},
input: e => {
this.value = $editor.textContent
},
blur: e => {
this.value = this.value.trim()
}
})
$input.on({
input: () => {
this.value = $input.value
},
focus: () => {
this.$editor.focus()
}
})
}
get value(){
return this.$input.value
}
set value(value){
if(value !== this.$input.value) this.$input.value = value
if(value !== this.$editor.textContent) this.$editor.textContent = value
}
addEventListener(){
this.$editor.addEventListener(...arguments)
}
}
customElements.define('dy-textarea', DYTextArea)