|
| 1 | +import { useCallback, useRef, useState } from "react" |
| 2 | + |
| 3 | +export default function useStateWithHistory( |
| 4 | + defaultValue, |
| 5 | + { capacity = 10 } = {} |
| 6 | +) { |
| 7 | + const [value, setValue] = useState(defaultValue) |
| 8 | + const historyRef = useRef([value]) |
| 9 | + const pointerRef = useRef(0) |
| 10 | + |
| 11 | + const set = useCallback( |
| 12 | + v => { |
| 13 | + const resolvedValue = typeof v === "function" ? v(value) : v |
| 14 | + if (historyRef.current[pointerRef.current] !== resolvedValue) { |
| 15 | + if (pointerRef.current < historyRef.current.length - 1) { |
| 16 | + historyRef.current.splice(pointerRef.current + 1) |
| 17 | + } |
| 18 | + historyRef.current.push(resolvedValue) |
| 19 | + |
| 20 | + while (historyRef.current.length > capacity) { |
| 21 | + historyRef.current.shift() |
| 22 | + } |
| 23 | + pointerRef.current = historyRef.current.length - 1 |
| 24 | + } |
| 25 | + setValue(resolvedValue) |
| 26 | + }, |
| 27 | + [capacity, value] |
| 28 | + ) |
| 29 | + |
| 30 | + const back = useCallback(() => { |
| 31 | + if (pointerRef.current <= 0) return |
| 32 | + pointerRef.current-- |
| 33 | + setValue(historyRef.current[pointerRef.current]) |
| 34 | + }, []) |
| 35 | + |
| 36 | + const forward = useCallback(() => { |
| 37 | + if (pointerRef.current >= historyRef.current.length - 1) return |
| 38 | + pointerRef.current++ |
| 39 | + setValue(historyRef.current[pointerRef.current]) |
| 40 | + }, []) |
| 41 | + |
| 42 | + const go = useCallback(index => { |
| 43 | + if (index < 0 || index >= historyRef.current.length - 1) return |
| 44 | + pointerRef.current = index |
| 45 | + setValue(historyRef.current[pointerRef.current]) |
| 46 | + }, []) |
| 47 | + |
| 48 | + return [ |
| 49 | + value, |
| 50 | + set, |
| 51 | + { |
| 52 | + history: historyRef.current, |
| 53 | + pointer: pointerRef.current, |
| 54 | + back, |
| 55 | + forward, |
| 56 | + go, |
| 57 | + }, |
| 58 | + ] |
| 59 | +} |
0 commit comments