react-konva-grid
Version:
Declarative React Canvas Grid primitive for Data table, Pivot table, Excel Worksheets
73 lines • 2.33 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.createPatches = void 0;
const react_1 = require("react");
const types_1 = require("../types");
/**
* Create patches
* @param path
* @param value
* @param previousValue
* @param op
*/
function createPatches(path, value, previousValue, op = "replace") {
const patches = { op, value, path };
const inversePatches = { op, value: previousValue, path };
return { patches, inversePatches };
}
exports.createPatches = createPatches;
/**
* Undo/Redo hook
* @param
*/
const useUndo = (props = {}) => {
const { onRedo, onUndo } = props;
const undoStack = react_1.useRef([]);
const undoStackPointer = react_1.useRef(-1);
const [_, forceRender] = react_1.useReducer((s) => s + 1, 0);
const handleKeyDown = react_1.useCallback((e) => {
const isMeta = e.metaKey || e.ctrlKey;
const isUndo = isMeta && e.which === types_1.KeyCodes.Z;
const isRedo = e.shiftKey && isUndo;
if (!isRedo && !isUndo)
return;
if (isRedo) {
handleRedo();
}
else {
handleUndo();
}
}, []);
const handleUndo = () => {
if (undoStackPointer.current < 0)
return;
const patches = undoStack.current[undoStackPointer.current].inversePatches;
undoStackPointer.current--;
onUndo && onUndo(patches);
forceRender();
};
const handleRedo = () => {
if (undoStackPointer.current === undoStack.current.length - 1)
return;
undoStackPointer.current++;
const patches = undoStack.current[undoStackPointer.current].patches;
onRedo && onRedo(patches);
forceRender();
};
const addUndoable = ({ patches, inversePatches }) => {
const pointer = ++undoStackPointer.current;
undoStack.current.length = pointer;
undoStack.current[pointer] = { patches, inversePatches };
forceRender();
};
return {
undo: handleUndo,
redo: handleRedo,
add: addUndoable,
canUndo: !(undoStackPointer.current < 0),
canRedo: !(undoStackPointer.current === undoStack.current.length - 1),
onKeyDown: handleKeyDown,
};
};
exports.default = useUndo;
//# sourceMappingURL=useUndo.js.map