Skip to content

Commit

Permalink
Add input example and update types (#185)
Browse files Browse the repository at this point in the history
  • Loading branch information
charkour authored Oct 3, 2024
1 parent 6cced1c commit 6a58d84
Show file tree
Hide file tree
Showing 3 changed files with 64 additions and 4 deletions.
61 changes: 61 additions & 0 deletions examples/web/pages/input.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
import { temporal, type TemporalState } from 'zundo';
import { useStore, createStore } from 'zustand';
import { shallow } from 'zustand/shallow';

interface MyState {
fontSize: number;
changeFontSize: (fontSize: number) => void;
}

const withZundo = temporal<MyState>((set) => ({
fontSize: 16,
changeFontSize: (fontSize) => set({ fontSize }),
}));

const originalStore = createStore(withZundo);

const useBaseStore = <T extends unknown>(
selector: (state: MyState) => T,
equality?: (a: T, b: T) => boolean,
) => useStore(originalStore, selector, equality);
const useTemporalStore = <T extends unknown>(
selector: (state: TemporalState<MyState>) => T,
equality?: (a: T, b: T) => boolean,
) => useStore(originalStore.temporal, selector, equality);

export default function App() {
const { fontSize, changeFontSize } = useBaseStore((state) => state);
const { futureStates, pastStates, undo, resume, pause } = useTemporalStore(
(state) => state,
shallow,
);

return (
<div>
<h1>Web</h1>
<div>
<input
type="number"
value={fontSize}
onFocus={() => {
changeFontSize(fontSize);
pause();
}}
onChange={(e) => changeFontSize(e.target.valueAsNumber)}
onBlur={(e) => {
resume();
changeFontSize(e.target.valueAsNumber);
}}
/>
<span>{fontSize}</span>
<div>
<h2>Future States</h2>
<div>{JSON.stringify(futureStates)}</div>
<h2>Previous States</h2>
<div>{JSON.stringify(pastStates)}</div>
<button onClick={() => undo()}>Undo</button>
</div>
</div>
</div>
);
}
3 changes: 1 addition & 2 deletions examples/web/pages/persist.tsx
Original file line number Diff line number Diff line change
@@ -1,10 +1,9 @@
import { useMemo } from 'react';
import { create } from 'zustand';
import { temporal } from 'zundo';
import { persist } from 'zustand/middleware';
import { persist, type PersistOptions } from 'zustand/middleware';
import { immer } from 'zustand/middleware/immer';
import dynamic from 'next/dynamic';
import { PersistOptions } from 'zustand/middleware/persist';
import merge from 'lodash.merge';

interface Store {
Expand Down
4 changes: 2 additions & 2 deletions examples/web/pages/reactive.tsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { TemporalState, temporal } from 'zundo';
import { StoreApi, useStore, create } from 'zustand';
import { type TemporalState, temporal } from 'zundo';
import { type StoreApi, useStore, create } from 'zustand';

interface MyState {
bears: number;
Expand Down

0 comments on commit 6a58d84

Please sign in to comment.