UNPKG

jotai-history

Version:
39 lines • 1.31 kB
import { atom } from 'jotai/vanilla'; import { REDO, RESET, UNDO } from './actions'; import { withHistory } from './withHistory'; import { withUndo } from './withUndo'; export function withUndoableHistory(targetAtom, limit) { const historyAtom = withPrivate(withHistory(targetAtom, limit)); let undoAtom; if (isWritableAtom(targetAtom)) { // eslint-disable-next-line prefer-rest-params const getArgs = arguments[2] ?? Array.of; undoAtom = withPrivate(withUndo(historyAtom, targetAtom, limit, getArgs)); } return atom((get) => Object.assign(get(historyAtom), isWritableAtom(targetAtom) ? get(undoAtom) : {}), (_, set, ...args) => { const [action] = args; if (action === RESET) { set(historyAtom, action); if (undoAtom) { set(undoAtom, action); } } else if (!isWritableAtom(targetAtom)) { return; } else if (action === UNDO || action === REDO) { set(undoAtom, action); } else { return set(targetAtom, ...args); } }); } function isWritableAtom(atom) { return 'write' in atom; } function withPrivate(atom) { atom.debugPrivate = true; return atom; } //# sourceMappingURL=withUndoableHistory.js.map