-
-
Notifications
You must be signed in to change notification settings - Fork 120
/
textarea.ts
55 lines (45 loc) · 1.75 KB
/
textarea.ts
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
import EditorPlug from './_plug'
import type PlugKit from './_kit'
import $t from '@/i18n'
export default class Textarea extends EditorPlug {
constructor(kit: PlugKit) {
super(kit)
const onKeydown = (e: KeyboardEvent) => this.onKeydown(e)
const onInput = () => this.onInput()
this.kit.useMounted(() => {
// 占位符
this.kit.useUI().$textarea.placeholder = this.kit.useConf().placeholder || $t('placeholder')
// bind the event
this.kit.useUI().$textarea.addEventListener('keydown', onKeydown)
this.kit.useUI().$textarea.addEventListener('input', onInput)
})
this.kit.useUnmounted(() => {
// unmount the event
this.kit.useUI().$textarea.removeEventListener('keydown', onKeydown)
this.kit.useUI().$textarea.removeEventListener('input', onInput)
})
this.kit.useEvents().on('content-updated', () => {
// delay 80ms to prevent invalid execution
window.setTimeout(() => {
this.adaptiveHeightByContent()
}, 80)
})
}
// 按下 Tab 输入内容,而不是失去焦距
private onKeydown(e: KeyboardEvent) {
const keyCode = e.keyCode || e.which
if (keyCode === 9) {
e.preventDefault()
this.kit.useEditor().insertContent('\t')
}
}
private onInput() {
this.kit.useEvents().trigger('content-updated', this.kit.useEditor().getContentRaw())
}
// Resize the textarea height by content
public adaptiveHeightByContent() {
const diff = this.kit.useUI().$textarea.offsetHeight - this.kit.useUI().$textarea.clientHeight
this.kit.useUI().$textarea.style.height = '0px' // it's a magic. 若不加此行,内容减少,高度回不去
this.kit.useUI().$textarea.style.height = `${this.kit.useUI().$textarea.scrollHeight + diff}px`
}
}