ny
23 小时以前 282fbc6488f4e8ceb5fda759f963ee88fbf7b999
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
import { computed, ref, unref } from 'vue';
 
import { cloneDeep, isFunction, isString } from '@jnpf/utils';
 
export function useRedo() {
  const recordList = ref<any[]>([]);
  const currentRecordIndex = ref(-1);
  const recordLimit = ref(500);
 
  const getCanUndo = computed(() => currentRecordIndex.value > 0);
  const getCanRedo = computed(
    () => recordList.value.length > currentRecordIndex.value + 1,
  );
 
  const initRedo = (limit = 500) => {
    recordList.value = [];
    currentRecordIndex.value = -1;
    recordLimit.value = limit;
  };
  // 新增一条历史纪录
  const addRecord = (json, fullName = '修改') => {
    if (currentRecordIndex.value + 1 < recordList.value.length) {
      recordList.value.splice(currentRecordIndex.value + 1);
    }
    const item = {
      fullName,
      id: currentRecordIndex.value + 1,
      json: isString(json) ? json : cloneDeep(json),
    };
    recordList.value.push(item);
    currentRecordIndex.value++;
    // 限制undo纪录步数
    if (recordList.value.length > recordLimit.value) {
      recordList.value.shift();
      currentRecordIndex.value--;
    }
  };
  // 撤销
  const handleUndo = (callback?) => {
    if (!unref(getCanUndo)) return;
    currentRecordIndex.value--;
    const currRecord = recordList.value[currentRecordIndex.value];
    callback && isFunction(callback) && callback(currRecord.json);
  };
  // 重做
  const handleRedo = (callback?) => {
    if (!unref(getCanRedo)) return;
    currentRecordIndex.value++;
    const currRecord = recordList.value[currentRecordIndex.value];
    callback && isFunction(callback) && callback(currRecord.json);
  };
  // 跳转到指定历史纪录
  const jumpToRecord = (index, callback?) => {
    if (index < 0 || index >= recordList.value.length) return;
    currentRecordIndex.value = index;
    const currRecord = recordList.value[currentRecordIndex.value];
    callback && isFunction(callback) && callback(currRecord.json);
  };
 
  return {
    addRecord,
    currentRecordIndex,
    getCanRedo,
    getCanUndo,
    handleRedo,
    handleUndo,
    initRedo,
    jumpToRecord,
    recordList,
  };
}