forked from quasarframework/quasar
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathUndoRedo.vue
More file actions
117 lines (102 loc) · 2.89 KB
/
UndoRedo.vue
File metadata and controls
117 lines (102 loc) · 2.89 KB
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
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
<template>
<div class="q-pa-md">
<div class="row justify-start items-center q-mb-md">
Max Stack Depth: {{ maxStack }}
</div>
<div class="row justify-around items-center">
<div class="row items-center q-px-md q-gutter-sm">
<q-btn label="Undo" color="primary" :disable="undoStack.length === 0" @click="undo" />
<div>Stack Depth: {{ undoStack.length }}</div>
</div>
<div class="row items-center q-px-md q-gutter-sm">
<q-btn label="Redo" color="accent" :disable="redoStack.length === 0" @click="redo" />
<div>Stack Depth: {{ redoStack.length }}</div>
</div>
</div>
<div class="row justify-around items-center q-mt-md">
<div
ref="editorRef"
v-mutation="handler"
contentEditable="true"
class="editable rounded-borders q-pa-sm overflow-auto"
>Type here</div>
</div>
</div>
</template>
<script>
import { ref } from 'vue'
export default {
setup () {
const maxStack = ref(100)
const undoStack = ref([])
const redoStack = ref([])
const undoBlocked = ref(false)
const editorRef = ref(null)
function checkStack (stack) {
if (stack.length > maxStack.value) {
stack.splice(maxStack.value)
}
}
function clearStack (stack) {
stack.splice(0)
}
return {
maxStack,
undoStack,
redoStack,
undoBlocked,
editorRef,
undo () {
// shift the stack
const data = undoStack.value.shift()
if (data !== void 0) {
// block undo from receiving its own data
undoBlocked.value = true
editorRef.value.innerText = data
}
},
redo () {
// shift the stack
const data = redoStack.value.shift()
if (data !== void 0) {
// unblock undo from receiving redo data
undoBlocked.value = false
editorRef.value.innerText = data
}
},
handler (mutationRecords) {
mutationRecords.forEach(record => {
if (record.type === 'characterData') {
undoStack.value.unshift(record.oldValue)
checkStack(undoStack.value)
clearStack(redoStack.value)
}
else if (record.type === 'childList') {
record.removedNodes.forEach(node => {
if (undoBlocked.value === false) {
// comes from redo
undoStack.value.unshift(node.textContent)
}
else {
// comes from undo
redoStack.value.unshift(node.textContent)
}
})
// check stacks
checkStack(undoStack.value)
checkStack(redoStack.value)
undoBlocked.value = false
}
})
}
}
}
}
</script>
<style scoped lang="sass">
.editable
width: 100%
height: 100px
border: 1px solid #aaa
outline: 0
</style>