undora
v0.1.2
Published
A lightweight TypeScript library for seamless undo/redo functionality.
Readme
undora
Undora is a lightweight undo/redo state management library for TypeScript/JavaScript applications. It provides a simple API to track state changes, undo/redo operations, and manage state history with configurable capacity.
Installation
pnpm add undoraFeatures
- Undo/Redo functionality: Track and navigate through state history
- Transaction support: Batch multiple changes as a single undo/redo step
- Configurable comparison: Customize how state changes are detected
- Capacity control: Limit history size to prevent memory issues
- Change callbacks: Get notified when state changes occur
- Type-safe: Built with TypeScript for excellent type support
Usage
import { Undora } from 'undora'
// Initialize with optional configuration
const undora = new Undora<number>({
capacity: 100, // Maximum number of states to keep
compare: (a, b) => a === b, // Custom comparison function
clone: x => x, // Custom clone function
onChange: (from, to) => console.log(`State changed from ${from} to ${to}`)
})
// Push initial state
undora.pushState(1)
// Update state
undora.pushState(2)
// Undo the last change
undora.undo()
// Redo the undone change
undora.redo()
// Get current state
const current = undora.getCurrent()Constructor
new Undora<T>(options?: Options<T>)Options:
capacity: Maximum number of states to keep (0 = unlimited)compare: Function to compare states (default: deep equality via JSON.stringify)clone: Function to clone states (default: deep clone via JSON.parse/stringify)onChange: Callback when state changes
Core Methods
pushState(newState: T, options?: { silent?: boolean })Add a new state to history (skipped if identical to current state)undo()Revert to previous stateredo()Reapply next statetransaction(callback: () => void)Batch multiple state changes as a single undo/redo step
State Access
getCurrent(): T | undefinedGet current stategetIndex(): numberGet current state indexgetStates(): T[]Get all stored states
Control Methods
canUndo(): booleanCheck if undo is possiblecanRedo(): booleanCheck if redo is possiblesetCapacity(newCapacity: number)Change maximum history sizepause()Temporarily stop recording state changesresume()Resume recording state changesclear()Reset all history
Advanced Usage
Transactions
undora.transaction(() => {
undora.pushState(1)
undora.pushState(2)
undora.pushState(3)
// All pushes are recorded as a single undo step
})Custom Comparison
const undora = new Undora<{ id: number }>({
compare: (a, b) => a.id === b.id // Only compare by ID
})Custom Clone Function
const undora = new Undora<MyState>({
clone: x => structuredClone(x) // For example, using structuredClone
})License
MIT License © jinghaihan
