|
| 1 | +import { temporal, type TemporalState } from 'zundo'; |
| 2 | +import { useStore, createStore } from 'zustand'; |
| 3 | +import { shallow } from 'zustand/shallow'; |
| 4 | + |
| 5 | +interface MyState { |
| 6 | + fontSize: number; |
| 7 | + changeFontSize: (fontSize: number) => void; |
| 8 | +} |
| 9 | + |
| 10 | +const withZundo = temporal<MyState>((set) => ({ |
| 11 | + fontSize: 16, |
| 12 | + changeFontSize: (fontSize) => set({ fontSize }), |
| 13 | +})); |
| 14 | + |
| 15 | +const originalStore = createStore(withZundo); |
| 16 | + |
| 17 | +const useBaseStore = <T extends unknown>( |
| 18 | + selector: (state: MyState) => T, |
| 19 | + equality?: (a: T, b: T) => boolean, |
| 20 | +) => useStore(originalStore, selector, equality); |
| 21 | +const useTemporalStore = <T extends unknown>( |
| 22 | + selector: (state: TemporalState<MyState>) => T, |
| 23 | + equality?: (a: T, b: T) => boolean, |
| 24 | +) => useStore(originalStore.temporal, selector, equality); |
| 25 | + |
| 26 | +export default function App() { |
| 27 | + const { fontSize, changeFontSize } = useBaseStore((state) => state); |
| 28 | + const { futureStates, pastStates, undo, resume, pause } = useTemporalStore( |
| 29 | + (state) => state, |
| 30 | + shallow, |
| 31 | + ); |
| 32 | + |
| 33 | + return ( |
| 34 | + <div> |
| 35 | + <h1>Web</h1> |
| 36 | + <div> |
| 37 | + <input |
| 38 | + type="number" |
| 39 | + value={fontSize} |
| 40 | + onFocus={() => { |
| 41 | + changeFontSize(fontSize); |
| 42 | + pause(); |
| 43 | + }} |
| 44 | + onChange={(e) => changeFontSize(e.target.valueAsNumber)} |
| 45 | + onBlur={(e) => { |
| 46 | + resume(); |
| 47 | + changeFontSize(e.target.valueAsNumber); |
| 48 | + }} |
| 49 | + /> |
| 50 | + <span>{fontSize}</span> |
| 51 | + <div> |
| 52 | + <h2>Future States</h2> |
| 53 | + <div>{JSON.stringify(futureStates)}</div> |
| 54 | + <h2>Previous States</h2> |
| 55 | + <div>{JSON.stringify(pastStates)}</div> |
| 56 | + <button onClick={() => undo()}>Undo</button> |
| 57 | + </div> |
| 58 | + </div> |
| 59 | + </div> |
| 60 | + ); |
| 61 | +} |
0 commit comments