|
| 1 | +import { walkAndSerialize } from './utils'; |
| 2 | +import { runInAction } from 'mobx'; |
| 3 | + |
| 4 | +const recordStates: { [key: string]: object } = {}; |
| 5 | +const stacks: typeof recordStates[] = []; |
| 6 | +let cursor = 0; |
| 7 | + |
| 8 | +(window as any).stacks = stacks; |
| 9 | +(window as any).undo = undo; |
| 10 | +(window as any).redo = redo; |
| 11 | + |
| 12 | +export function undo() { |
| 13 | + if (stacks.length <= 1 || cursor === 0) { |
| 14 | + return; |
| 15 | + } |
| 16 | + const snapshot = stacks[--cursor]; |
| 17 | + return restoreSnapshot(snapshot); |
| 18 | +} |
| 19 | + |
| 20 | +export function redo() { |
| 21 | + if (stacks.length <= 1 || cursor === stacks.length) { |
| 22 | + return; |
| 23 | + } |
| 24 | + const snapshot = stacks[++cursor]; |
| 25 | + return restoreSnapshot(snapshot); |
| 26 | +} |
| 27 | + |
| 28 | +function restoreSnapshot(snapshot: typeof recordStates) { |
| 29 | + return runInAction(() => { |
| 30 | + Object.entries(snapshot).forEach(([key, v]) => { |
| 31 | + Object.assign(recordStates[key], v); |
| 32 | + }); |
| 33 | + }); |
| 34 | +} |
| 35 | + |
| 36 | +export function recordHistory(states: typeof recordStates) { |
| 37 | + Object.assign(recordStates, states); |
| 38 | + updateSnapshots(true); |
| 39 | +} |
| 40 | + |
| 41 | +let inReaction = false; |
| 42 | +export const withHistory = ( |
| 43 | + target: { [key: string]: any }, |
| 44 | + propertyKey: string, |
| 45 | + descriptor?: PropertyDescriptor, |
| 46 | +): void => { |
| 47 | + const { initializer } = descriptor as any; |
| 48 | + descriptor!.value = function(...args: Parameters<ReturnType<typeof initializer>>) { |
| 49 | + const reaction = inReaction; |
| 50 | + if (!reaction) { |
| 51 | + inReaction = true; |
| 52 | + } |
| 53 | + const result = initializer.apply(this).apply(this, args); |
| 54 | + if (!reaction) { |
| 55 | + setTimeout(async () => { |
| 56 | + if (result instanceof Promise) { |
| 57 | + await result; |
| 58 | + } |
| 59 | + updateSnapshots(); |
| 60 | + inReaction = false; |
| 61 | + }, 0); |
| 62 | + } |
| 63 | + return result; |
| 64 | + }; |
| 65 | +}; |
| 66 | + |
| 67 | +function updateSnapshots(assign = false) { |
| 68 | + const snapshot = Object.entries(recordStates).reduce<{ [key: string]: object }>((accu, [k, v]) => { |
| 69 | + accu[k] = walkAndSerialize(v); |
| 70 | + return accu; |
| 71 | + }, {}); |
| 72 | + if (assign && stacks.length) { |
| 73 | + Object.assign(stacks[stacks.length - 1], snapshot); |
| 74 | + } else { |
| 75 | + stacks.push(snapshot); |
| 76 | + } |
| 77 | + cursor = stacks.length - 1; |
| 78 | +} |
0 commit comments