add:基本实现撤销、恢复功能

This commit is contained in:
lhj
2024-11-10 20:37:55 +08:00
parent 1c14acf615
commit 9a365dd1a1
3 changed files with 59 additions and 12 deletions

View File

@ -1,5 +1,6 @@
import { defineStore } from 'pinia';
import { IPageComponent } from '@/type/IPageComponent';
import sha256 from 'js-sha256';
// 缓存对象
const idToObjectCache = new Map<string, IPageComponent>();
@ -24,18 +25,31 @@ function findObjectById(obj, targetId) {
return null; // 如果没有找到则返回null
}
const HISTORY_LENGTH = 20; // 默认队列长度
export const useSchemeStore = defineStore('scheme', {
state: () => ({
components: [],
previewScheme: [],
nowComponentsData: {}
nowComponentsData: {},
history: Array(HISTORY_LENGTH).fill(null), // 循环队列
currentIndex: -1, // 当前索引
currentLength: 0, // 当前队列中有效元素的数量
currentHash: '', // 当前状态的哈希值
}),
getters: {
canUndo: (state) => state.currentIndex >= 0,
canRedo: (state) => state.currentIndex < state.currentLength - 1,
},
actions: {
initPreviewScheme(value) {
this.previewScheme = value;
this.nowComponentsData = value[0];
// 清空缓存
idToObjectCache.clear();
this.history.fill(null); // 初始化队列
this.currentIndex = -1;
this.currentLength = 0;
this.currentHash = ''; // 初始化当前哈希值
},
initComponents(value) {
this.components = value;
@ -53,14 +67,46 @@ export const useSchemeStore = defineStore('scheme', {
return obj;
},
updateScheme(id, updates) {
console.log("更新数据",JSON.stringify(updates));
const obj = this.getSchemeObj(id);
console.log("更新目标",JSON.stringify(obj));
const currentStateHash = this.currentHash;
const newObj = this.getSchemeObj(id);
if (newObj) {
Object.assign(newObj, updates);
}
const newStateHash = sha256(JSON.stringify(this.previewScheme));
if (obj) {
// 更新对象属性
Object.assign(obj, updates);
console.log("更新后目标",JSON.stringify(obj));
// 如果新状态与当前状态不同,才保存到历史记录中
if (currentStateHash !== newStateHash) {
this.currentHash = newStateHash;
// 如果不是最新的状态,则清除之后的所有状态
if (this.currentIndex < this.currentLength - 1) {
this.history.fill(null, this.currentIndex + 1);
this.currentLength = this.currentIndex + 1;
}
this.currentIndex++;
this.currentLength = this.currentIndex + 1;
this.history[this.currentIndex % HISTORY_LENGTH] = JSON.parse(JSON.stringify(this.previewScheme));
}
},
undo() {
if (this.canUndo) {
this.currentIndex--;
const prevState = this.history[this.currentIndex % HISTORY_LENGTH];
if (prevState) {
this.previewScheme = prevState;
this.nowComponentsData = this.previewScheme[0];
this.currentHash = sha256(JSON.stringify(this.previewScheme));
}
}
},
redo() {
if (this.canRedo) {
this.currentIndex++;
const nextState = this.history[this.currentIndex % HISTORY_LENGTH];
if (nextState) {
this.previewScheme = nextState;
this.nowComponentsData = this.previewScheme[0];
this.currentHash = sha256(JSON.stringify(this.previewScheme));
}
}
}
}