UNPKG

@jbrowse/core

Version:

JBrowse 2 core libraries used by plugins

91 lines (90 loc) 2.86 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); const mobx_state_tree_1 = require("mobx-state-tree"); const MAX_HISTORY_LENGTH = 20; function debounce(func, timeout = 300) { let timer; return (...args) => { clearTimeout(timer); timer = setTimeout(() => { func(...args); }, timeout); }; } const TimeTraveller = mobx_state_tree_1.types .model('TimeTraveller', { undoIdx: -1, targetPath: '', }) .volatile(() => ({ history: [], notTrackingUndo: false, })) .views(self => ({ get canUndo() { return self.undoIdx > 0 && !self.notTrackingUndo; }, get canRedo() { return self.undoIdx < self.history.length - 1 && !self.notTrackingUndo; }, })) .actions(self => { let targetStore; let snapshotDisposer; let skipNextUndoState = false; return { stopTrackingUndo() { self.notTrackingUndo = true; }, resumeTrackingUndo() { self.notTrackingUndo = false; }, addUndoState(todos) { if (self.notTrackingUndo) { return; } if (skipNextUndoState) { skipNextUndoState = false; return; } self.history.splice(self.undoIdx + 1); self.history.push(todos); if (self.history.length > MAX_HISTORY_LENGTH) { self.history.shift(); } self.undoIdx = self.history.length - 1; }, beforeDestroy() { snapshotDisposer(); }, initialize() { targetStore = self.targetPath ? (0, mobx_state_tree_1.resolvePath)(self, self.targetPath) : (0, mobx_state_tree_1.getEnv)(self).targetStore; if (!targetStore) { throw new Error('Failed to find target store for TimeTraveller. Please provide `targetPath` property, or a `targetStore` in the environment'); } snapshotDisposer = (0, mobx_state_tree_1.onSnapshot)(targetStore, debounce((snapshot) => { this.addUndoState(snapshot); }, 300)); if (self.history.length === 0) { this.addUndoState((0, mobx_state_tree_1.getSnapshot)(targetStore)); } }, undo() { self.undoIdx--; skipNextUndoState = true; if (targetStore) { (0, mobx_state_tree_1.applySnapshot)(targetStore, self.history[self.undoIdx]); } }, redo() { self.undoIdx++; skipNextUndoState = true; if (targetStore) { (0, mobx_state_tree_1.applySnapshot)(targetStore, self.history[self.undoIdx]); } }, }; }); exports.default = TimeTraveller;