MCPcopy Index your code
hub / github.com/charkour/zundo

github.com/charkour/zundo @v2.3.0

Chat with this repo
repository ↗ · DeepWiki ↗ · release v2.3.0 ↗ · + Follow
81 symbols 184 edges 26 files 1 documented · 1% 8 cross-repo links updated 5mo agov2.3.0 · 2024-11-17★ 87616 open issues
What it actually does AI analysis from the code graph — generated when you open this
loading…
README

🍜 Zundo

enable time-travel in your apps. undo/redo middleware for zustand. built with zustand. <700 B

gif displaying undo feature

Build Size Version Downloads

Try a live demo

Install

npm i zustand zundo

zustand v4.2.0+ or v5 is required for TS usage. v4.0.0 or higher is required for JS usage. Node 16 or higher is required.

Background

  • Solves the issue of managing state in complex user applications
  • "It Just Works" mentality
  • Small and fast
  • Provides simple middleware to add undo/redo capabilities
  • Leverages zustand for state management
  • Works with multiple stores in the same app
  • Has an unopinionated and extensible API

Bear wearing a button up shirt textured with blue recycle symbols eating a bowl of noodles with chopsticks.

First create a vanilla store with temporal middleware

This returns the familiar store accessible by a hook! But now your store also tracks past states.

import { create } from 'zustand';
import { temporal } from 'zundo';

// Define the type of your store state (typescript)
interface StoreState {
  bears: number;
  increasePopulation: () => void;
  removeAllBears: () => void;
}

// Use `temporal` middleware to create a store with undo/redo capabilities
const useStoreWithUndo = create<StoreState>()(
  temporal((set) => ({
    bears: 0,
    increasePopulation: () => set((state) => ({ bears: state.bears + 1 })),
    removeAllBears: () => set({ bears: 0 }),
  })),
);

Then access temporal functions and properties of your store

Your zustand store will now have an attached temporal object that provides access to useful time-travel utilities, including undo, redo, and clear!

const App = () => {
  const { bears, increasePopulation, removeAllBears } = useStoreWithUndo();
  // See API section for temporal.getState() for all functions and
  // properties provided by `temporal`, but note that properties, such as `pastStates` and `futureStates`, are not reactive when accessed directly from the store.
  const { undo, redo, clear } = useStoreWithUndo.temporal.getState();

  return (
    <>
      bears: {bears}
      <button onClick={() => increasePopulation}>increase</button>
      <button onClick={() => removeAllBears}>remove</button>
      <button onClick={() => undo()}>undo</button>
      <button onClick={() => redo()}>redo</button>
      <button onClick={() => clear()}>clear</button>
    </>
  );
};

For reactive changes to member properties of the temporal object, optionally convert to a React store hook

In React, to subscribe components or custom hooks to member properties of the temporal object (like the array of pastStates or currentStates), you can create a useTemporalStore hook.

import { useStoreWithEqualityFn } from 'zustand/traditional';
import type { TemporalState } from 'zundo';

function useTemporalStore(): TemporalState<MyState>;
function useTemporalStore<T>(selector: (state: TemporalState<MyState>) => T): T;
function useTemporalStore<T>(
  selector: (state: TemporalState<MyState>) => T,
  equality: (a: T, b: T) => boolean,
): T;
function useTemporalStore<T>(
  selector?: (state: TemporalState<MyState>) => T,
  equality?: (a: T, b: T) => boolean,
) {
  return useStoreWithEqualityFn(useStoreWithUndo.temporal, selector!, equality);
}

const App = () => {
  const { bears, increasePopulation, removeAllBears } = useStoreWithUndo();
  // changes to pastStates and futureStates will now trigger a reactive component rerender
  const { undo, redo, clear, pastStates, futureStates } = useTemporalStore(
    (state) => state,
  );

  return (
    <>


 bears: {bears}




 pastStates: {JSON.stringify(pastStates)}




 futureStates: {JSON.stringify(futureStates)}


      <button onClick={() => increasePopulation}>increase</button>
      <button onClick={() => removeAllBears}>remove</button>
      <button onClick={() => undo()}>undo</button>
      <button onClick={() => redo()}>redo</button>
      <button onClick={() => clear()}>clear</button>
    </>
  );
};

API

The Middleware

(config: StateCreator, options?: ZundoOptions) => StateCreator

zundo has one export: temporal. It is used as middleware for create from zustand. The config parameter is your store created by zustand. The second options param is optional and has the following API.

Bear's eye view

export interface ZundoOptions<TState, PartialTState = TState> {
  partialize?: (state: TState) => PartialTState;
  limit?: number;
  equality?: (pastState: PartialTState, currentState: PartialTState) => boolean;
  diff?: (
    pastState: Partial<PartialTState>,
    currentState: Partial<PartialTState>,
  ) => Partial<PartialTState> | null;
  onSave?: (pastState: TState, currentState: TState) => void;
  handleSet?: (
    handleSet: StoreApi<TState>['setState'],
  ) => StoreApi<TState>['setState'];
  pastStates?: Partial<PartialTState>[];
  futureStates?: Partial<PartialTState>[];
  wrapTemporal?: (
    storeInitializer: StateCreator<
      _TemporalState<TState>,
      [StoreMutatorIdentifier, unknown][],
      []
    >,
  ) => StateCreator<
    _TemporalState<TState>,
    [StoreMutatorIdentifier, unknown][],
    [StoreMutatorIdentifier, unknown][]
  >;
}

Exclude fields from being tracked in history

partialize?: (state: TState) => PartialTState

Use the partialize option to omit or include specific fields. Pass a callback that returns the desired fields. This can also be used to exclude fields. By default, the entire state object is tracked.

// Only field1 and field2 will be tracked
const useStoreWithUndoA = create<StoreState>()(
  temporal(
    (set) => ({
      // your store fields
    }),
    {
      partialize: (state) => {
        const { field1, field2, ...rest } = state;
        return { field1, field2 };
      },
    },
  ),
);

// Everything besides field1 and field2 will be tracked
const useStoreWithUndoB = create<StoreState>()(
  temporal(
    (set) => ({
      // your store fields
    }),
    {
      partialize: (state) => {
        const { field1, field2, ...rest } = state;
        return rest;
      },
    },
  ),
);

useTemporalStore with partialize

If converting temporal store to a React Store Hook with typescript, be sure to define the type of your partialized state

interface StoreState {
  bears: number;
  untrackedStateField: number;
}

type PartializedStoreState = Pick<StoreState, 'bears'>;

const useStoreWithUndo = create<StoreState>()(
  temporal(
    (set) => ({
      bears: 0,
      untrackedStateField: 0,
    }),
    {
      partialize: (state) => {
        const { bears } = state;
        return { bears };
      },
    },
  ),
);

const useTemporalStore = <T,>(
  // Use partalized StoreState type as the generic here
  selector: (state: TemporalState<PartializedStoreState>) => T,
) => useStore(useStoreWithUndo.temporal, selector);

Limit number of historical states stored

limit?: number

For performance reasons, you may want to limit the number of previous and future states stored in history. Setting limit will limit the number of previous and future states stored in the temporal store. When the limit is reached, the oldest state is dropped. By default, no limit is set.

const useStoreWithUndo = create<StoreState>()(
  temporal(
    (set) => ({
      // your store fields
    }),
    { limit: 100 },
  ),
);

Prevent unchanged states from getting stored in history

equality?: (pastState: PartialTState, currentState: PartialTState) => boolean

By default, a state snapshot is stored in temporal history when any zustand state setter is called—even if no value in your zustand store has changed.

If all of your zustand state setters modify state in a way that you want tracked in history, this default is sufficient.

However, for more precise control over when a state snapshot is stored in zundo history, you can provide an equality function.

You can write your own equality function or use something like fast-equals, fast-deep-equal, zustand/shallow, lodash.isequal, or underscore.isEqual.

Example with deep equality

import isDeepEqual from 'fast-deep-equal';

// Use a deep equality function to only store history when currentState has changed
const useStoreWithUndo = create<StoreState>()(
  temporal(
    (set) => ({
      // your store fields
    }),
    // a state snapshot will only be stored in history when currentState is not deep-equal to pastState
    // Note: this can also be more concisely written as {equality: isDeepEqual}
    {
      equality: (pastState, currentState) =>
        isDeepEqual(pastState, currentState),
    },
  ),
);

Example with shallow equality

If your state or specific application does not require deep equality (for example, if you're only using non-nested primitives), you may for performance reasons choose to use a shallow equality fn that does not do deep comparison.

import shallow from 'zustand/shallow';

const useStoreWithUndo = create<StoreState>()(
  temporal(
    (set) => ({
      // your store fields
    }),
    // a state snapshot will only be stored in history when currentState is not deep-equal to pastState
    // Note: this can also be more concisely written as {equality: shallow}
    {
      equality: (pastState, currentState) => shallow(pastState, currentState),
    },
  ),
);

Example with custom equality

You can also just as easily use custom equality functions for your specific application

const useStoreWithUndo = create<StoreState>()(
  temporal(
    (set) => ({
      // your store fields
    }),
    {
      // Only track history when field1 AND field2 diverge from their pastState
      // Why would you do this? I don't know! But you can do it!
      equality: (pastState, currentState) =>
        pastState.field1 !== currentState.field1 &&
        pastState.field2 !== currentState.field2,
    },
  ),
);

Store state delta rather than full object

diff?: (pastState: Partial<PartialTState>, currentState: Partial<PartialTState>) => Partial<PartialTState> | null

For performance reasons, you may want to store the state delta rather than the complete (potentially partialized) state object. This can be done by passing a diff function. The diff function should return an object that represents the difference between the past and current state. By default, the full state object is stored.

If diff returns null, the state change will not be tracked. This is helpful for a conditionally storing past states or if you have a doNothing action that does not change the state.

You can write your own or use something like microdiff, just-diff, or deep-object-diff.

const useStoreWithUndo = create<StoreState>()(
  temporal(
    (set) => ({
      // your store fields
    }),
    {
      diff: (pastState, currentState) => {
        const myDiff = diff(currentState, pastState);
        const newStateFromDiff = myDiff.reduce(
          (acc, difference) => {
            type Key = keyof typeof currentState;
            if (difference.type === 'CHANGE') {
              const pathAsString = difference.path.join('.') as Key;
              acc[pathAsString] = difference.value;
            }
            return acc;
          },
          {} as Partial<typeof currentState>,
        );
        return isEmpty(newStateFromDiff) ? null : newStateFromDiff;
      },
    },
  ),
);

Callback when temporal store is updated

onSave?: (pastState: TState, currentState: TState) => void

Sometimes, you may need to call a function when the temporal store is updated. This can be configured using onSave in the options, or by programmatically setting the callback if you need lexical context (see the TemporalState API below for more information).

import { shallow } from 'zustand/shallow';

const useStoreWithUndo = create<StoreState>()(
  temporal(
    (set) => ({
      // your store fields
    }),
    { onSave: (state) => console.log('saved', state) },
  ),
);

Cool-off period

  handleSet?: (handleSet: StoreApi<TState>['setState']) => (
    pastState: Parameters<StoreApi<TState>['setState']>[0],
    // `replace` will likely be deprecated and removed in the future
    replace: Parameters<StoreApi<TState>['setState']>[1],
    currentState: PartialTState,
    deltaState?: Partial<PartialTState> | null,
) => void

Sometimes multiple state changes might happen in a short amount of time and you only want to store one change in history. To do so, we can utilize the handleSet callback to set a timeout to prevent new changes from being stored in history. This can be used with something like [throttle-debounce](https://github.com/nik

Extension points exported contracts — how you extend this code

Core symbols most depended-on inside this repo

Shape

Function 61
Interface 20

Languages

TypeScript100%

Modules by API surface

examples/web/pages/wrapped.tsx8 symbols
examples/web/pages/nested.tsx8 symbols
examples/web/pages/throttle.tsx7 symbols
tests/__tests__/react.test.tsx6 symbols
examples/web/pages/separate.tsx6 symbols
examples/web/pages/reactive.tsx6 symbols
examples/web/pages/diff.tsx5 symbols
tests/__tests__/options.test.ts4 symbols
examples/web/pages/input.tsx4 symbols
examples/web/pages/index.tsx4 symbols
src/index.ts3 symbols
examples/web/pages/setstate.tsx3 symbols

For agents

$ claude mcp add zundo \
  -- python -m otcore.mcp_server <graph>

⬇ download graph artifact

Ask about this repo answers extend the page