use-history-snapshot.ts 1.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041
  1. import { useCallback } from 'react';
  2. import { useSnapshotStore } from '@/lib/store/snapshot';
  3. /**
  4. * Hook for managing history snapshots (undo/redo)
  5. *
  6. * Usage:
  7. * ```tsx
  8. * const { addHistorySnapshot, canUndo, canRedo, undo, redo } = useHistorySnapshot();
  9. *
  10. * // After making changes
  11. * await addHistorySnapshot();
  12. *
  13. * // Undo/Redo
  14. * if (canUndo) await undo();
  15. * if (canRedo) await redo();
  16. * ```
  17. */
  18. export function useHistorySnapshot() {
  19. const addSnapshot = useSnapshotStore((state) => state.addSnapshot);
  20. const undo = useSnapshotStore((state) => state.undo);
  21. const redo = useSnapshotStore((state) => state.redo);
  22. const canUndo = useSnapshotStore((state) => state.canUndo);
  23. const canRedo = useSnapshotStore((state) => state.canRedo);
  24. /**
  25. * Add a snapshot to the history
  26. * Call this after any significant state change that should be undoable
  27. */
  28. const addHistorySnapshot = useCallback(async () => {
  29. await addSnapshot();
  30. }, [addSnapshot]);
  31. return {
  32. addHistorySnapshot,
  33. undo,
  34. redo,
  35. canUndo: canUndo(),
  36. canRedo: canRedo(),
  37. };
  38. }