import { useEffect } from "react"; import { editingCellContext } from "../context/EditorContext"; import { usePropsRef } from "../context/PropsContext"; export const useUndo = () => { const propsRef = usePropsRef(); const setEditingCell = editingCellContext.useSetter(); useEffect(() => { const listener = (e: KeyboardEvent) => { // Can't find any better way to do this. On macOS, users expect CMD+Z to // undo. On Windows and Linux, users expect CTRL+Z to undo const isModifierDown = window.navigator.platform.match(/mac/i) ? e.metaKey : e.ctrlKey; if (e.key.toLowerCase() === "z" && isModifierDown) { setEditingCell(null); if (e.shiftKey) { propsRef.current.onRedo(); } else { propsRef.current.onUndo(); } } }; document.addEventListener("keydown", listener); return () => document.removeEventListener("keydown", listener); }, []); };