@sv-use/core
Version:
A collection of Svelte 5 utilities.
55 lines (54 loc) • 1.64 kB
JavaScript
import { trackHistory } from '../track-history/index.svelte.js';
/**
* A reactive state that allows for undo and redo operations by tracking the change history.
* @param initial The initial value of the state.
* @see https://svelte-librarian.github.io/sv-use/docs/core/history-state
*/
export function historyState(initial, options = {}) {
const { includeCurrent = false } = options;
const _state = $state({ current: initial });
const _history = trackHistory(() => $state.snapshot(_state.current), (v) => (_state.current = v), { includeCurrent });
const handler = {
get(target, key) {
if (target &&
typeof target === 'object' &&
typeof target[key] === 'object' &&
target[key] !== null) {
return new Proxy(target[key], handler);
}
else {
return target[key];
}
},
set(target, key, value) {
target[key] = value;
return true;
}
};
return {
get current() {
return new Proxy(_state, handler).current;
},
set current(v) {
_state.current = v;
},
get canUndo() {
return _history.canUndo;
},
get canRedo() {
return _history.canRedo;
},
get history() {
return _history.history;
},
get redoHistory() {
return _history.redoHistory;
},
undo() {
return _history.undo();
},
redo() {
return _history.redo();
}
};
}