forked from opentiny/tiny-engine
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathuseHistory.js
More file actions
124 lines (105 loc) · 2.62 KB
/
Copy pathuseHistory.js
File metadata and controls
124 lines (105 loc) · 2.62 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
118
119
120
121
122
123
124
/**
* Copyright (c) 2023 - present TinyEngine Authors.
* Copyright (c) 2023 - present Huawei Cloud Computing Technologies Co., Ltd.
*
* Use of this source code is governed by an MIT-style license.
*
* THE OPEN SOURCE SOFTWARE IN THIS PRODUCT IS DISTRIBUTED IN THE HOPE THAT IT WILL BE USEFUL,
* BUT WITHOUT ANY WARRANTY, WITHOUT EVEN THE IMPLIED WARRANTY OF MERCHANTABILITY OR FITNESS FOR
* A PARTICULAR PURPOSE. SEE THE APPLICABLE LICENSES FOR MORE DETAILS.
*
*/
import { reactive, isProxy, toRaw, watch } from 'vue'
import useCanvas from './useCanvas'
import { setSchema, getSchema } from '@opentiny/tiny-engine-canvas'
const schema2String = (schema) => {
if (isProxy(schema)) {
schema = toRaw(schema)
}
return JSON.stringify(schema)
}
const string2Schema = (string) => {
let schema
try {
schema = JSON.parse(string)
} catch (error) {
schema = {}
}
return schema
}
const list = []
const maxLength = 5
const historyState = reactive({
index: 0,
back: false,
forward: false
})
const push = (schema) => {
let length = list.length
// 处于撤销中,又修改了 schema ,需要将后面的历史记录清除
if (historyState.index < length - 1) {
list.splice(historyState.index + 1)
length = list.length
}
// 历史记录超过限制,删除前面的记录
if (length >= maxLength) {
list.splice(0, length - maxLength + 1)
}
list.push(schema2String(schema))
historyState.index = list.length - 1
}
const go = (addend, valid) => {
historyState.index = historyState.index + addend
setSchema(string2Schema(list[historyState.index]))
// 不是锁定状态,撤销操作后,传递第二个标识位,将 list 的长度减一,置灰 undoredo 操作按钮
if (typeof valid === 'boolean') {
list.splice(1, 1)
}
}
const back = () => {
if (historyState.back) {
go(-1)
useCanvas().setSaved(false)
}
}
const forward = () => {
if (historyState.forward) {
go(1)
useCanvas().setSaved(historyState.index === list.length - 1)
}
}
const addHistory = (schema) => {
if (!schema) {
useCanvas().setSaved(false)
push(getSchema())
} else {
clear()
// 初始 schema 需要设置为第一条历史记录
push(schema)
}
}
const clear = () => {
list.splice(0)
Object.assign(historyState, {
index: 0,
back: false,
forward: false
})
}
// 监控下标,判断是否允许前进后退标志
watch(
() => historyState.index,
(value) => {
historyState.back = value > 0
historyState.forward = value < list.length - 1
}
)
export default () => {
return {
historyState,
back,
forward,
go,
addHistory
}
}