All files / webview-app/src/hooks useUndoRedo.ts

94.87% Statements 37/39
88.88% Branches 24/27
100% Functions 9/9
94.87% Lines 37/39

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158                                                                        43x   43x           43x         23x 23x   23x 23x   23x 4x       4x             19x 2x       2x 2x                   17x 1x     16x 16x                         43x 8x 8x 1x     7x 7x               43x 5x 5x 1x     4x 4x               43x 1x     43x 43x   43x 33x             43x                      
import { useCallback, useMemo, useState } from "react";
 
export interface UndoRedoOptions {
  historyLimit?: number;
}
 
interface HistoryState<T> {
  past: T[];
  present: T;
  future: T[];
}
 
export interface UseUndoRedoResult<T> {
  state: T;
  set: (
    next: T | ((current: T) => T),
    options?: {
      mode?: "push" | "replace" | "pushFrom";
      from?: T;
    },
  ) => void;
  undo: () => void;
  redo: () => void;
  reset: (nextState: T) => void;
  canUndo: boolean;
  canRedo: boolean;
  history: {
    past: T[];
    future: T[];
  };
}
 
export function useUndoRedo<T>(
  initialState: T,
  options: UndoRedoOptions = {},
): UseUndoRedoResult<T> {
  const { historyLimit = 100 } = options;
 
  const [historyState, setHistoryState] = useState<HistoryState<T>>({
    past: [],
    present: initialState,
    future: [],
  });
 
  const set = useCallback(
    (
      next: T | ((current: T) => T),
      options: { mode?: "push" | "replace" | "pushFrom"; from?: T } = {},
    ) => {
      const mode = options.mode ?? "push";
      setHistoryState((currentState) => {
        const nextValue =
          typeof next === "function" ? (next as (current: T) => T)(currentState.present) : next;
        const historyFrom = options.from ?? currentState.present;
 
        if (mode === "replace") {
          Iif (Object.is(currentState.present, nextValue)) {
            return currentState;
          }
 
          return {
            past: currentState.past,
            present: nextValue,
            future: [],
          };
        }
 
        if (mode === "pushFrom") {
          Iif (Object.is(historyFrom, nextValue)) {
            return currentState;
          }
 
          const nextPast = [...currentState.past, historyFrom];
          return {
            past:
              nextPast.length > historyLimit
                ? nextPast.slice(nextPast.length - historyLimit)
                : nextPast,
            present: nextValue,
            future: [],
          };
        }
 
        if (Object.is(currentState.present, nextValue)) {
          return currentState;
        }
 
        const nextPast = [...currentState.past, currentState.present];
        return {
          past:
            nextPast.length > historyLimit
              ? nextPast.slice(nextPast.length - historyLimit)
              : nextPast,
          present: nextValue,
          future: [],
        };
      });
    },
    [historyLimit],
  );
 
  const undo = useCallback(() => {
    setHistoryState((currentState) => {
      if (currentState.past.length === 0) {
        return currentState;
      }
 
      const previous = currentState.past[currentState.past.length - 1];
      return {
        past: currentState.past.slice(0, -1),
        present: previous,
        future: [currentState.present, ...currentState.future],
      };
    });
  }, []);
 
  const redo = useCallback(() => {
    setHistoryState((currentState) => {
      if (currentState.future.length === 0) {
        return currentState;
      }
 
      const [nextPresent, ...remainingFuture] = currentState.future;
      return {
        past: [...currentState.past, currentState.present],
        present: nextPresent,
        future: remainingFuture,
      };
    });
  }, []);
 
  const reset = useCallback((nextState: T) => {
    setHistoryState({ past: [], present: nextState, future: [] });
  }, []);
 
  const canUndo = historyState.past.length > 0;
  const canRedo = historyState.future.length > 0;
 
  const history = useMemo(
    () => ({
      past: historyState.past,
      future: historyState.future,
    }),
    [historyState.future, historyState.past],
  );
 
  return {
    state: historyState.present,
    set,
    undo,
    redo,
    reset,
    canUndo,
    canRedo,
    history,
  };
}