forked from nuxt/content
/
editor.vue
75 lines (73 loc) · 1.93 KB
/
editor.vue
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
<template>
<textarea
ref="textarea"
v-model="file"
@keydown.tab.exact.prevent="onTabRight"
@keydown.tab.shift.prevent="onTabLeft"
@compositionstart.prevent="isInComposition = true"
@compositionend.prevent="isInComposition = false"
@blur="$emit('endEdit')"
/>
</template>
<script>
export default {
props: {
value: String,
isEditing: Boolean
},
data () {
return {
file: '',
isInComposition: false
}
},
watch: {
value () {
this.file = this.value
},
isEditing () {
this.onType()
this.$refs.textarea.focus()
},
file () {
this.onType()
this.$emit('input', this.file)
}
},
methods: {
onType () {
const el = this.$refs.textarea
el.style.height = 'auto'
this.$nextTick(() => {
el.style.height = el.scrollHeight + 'px'
})
},
onTabRight(event) {
if (this.isInComposition) {
return
}
const text = this.file
const originalSelectionStart = event.target.selectionStart
const textStart = text.slice(0, originalSelectionStart)
const textEnd = text.slice(originalSelectionStart)
this.file = `${textStart}\t${textEnd}`
event.target.value = this.file // required to make the cursor stay in place.
event.target.selectionEnd = event.target.selectionStart =
originalSelectionStart + 1
},
onTabLeft(event) {
if (this.isInComposition) {
return
}
const text = this.file
const originalSelectionStart = event.target.selectionStart
const textStart = text.slice(0, originalSelectionStart)
const textEnd = text.slice(originalSelectionStart)
this.file = `${textStart.replace(/\t$/, '')}${textEnd}`
event.target.value = this.file // required to make the cursor stay in place.
event.target.selectionEnd = event.target.selectionStart =
originalSelectionStart - 1
}
}
}
</script>