@modern-kit/react
Version:
91 lines (87 loc) • 2.57 kB
JavaScript
;
var utils = require('@modern-kit/utils');
var React = require('react');
function useHistoryState(initialValue, capacity = 10) {
const initialValueToUse = utils.isFunction(initialValue) ? initialValue() : initialValue;
const [state, innerSetState] = React.useState({
history: [initialValueToUse],
current: initialValueToUse,
pointer: 0
});
const canForward = React.useMemo(
() => state.pointer < state.history.length - 1,
[state.pointer, state.history.length]
);
const canBack = React.useMemo(() => state.pointer > 0, [state.pointer]);
const setState = React.useCallback(
(newState) => {
innerSetState((prev) => {
const history = [...prev.history];
const newStateToUse = utils.isFunction(newState) ? newState(history[prev.pointer]) : newState;
if (history.length === capacity) {
history.shift();
}
history.push(newStateToUse);
const pointer = history.length - 1;
return { history, current: newStateToUse, pointer };
});
},
[capacity]
);
const replaceState = React.useCallback((newState) => {
innerSetState((prev) => {
const history = [...prev.history];
const newStateToUse = utils.isFunction(newState) ? newState(history[prev.pointer]) : newState;
history[prev.pointer] = newStateToUse;
return { ...prev, history, current: newStateToUse };
});
}, []);
const back = React.useCallback(() => {
innerSetState((prev) => {
if (prev.pointer < 1) {
return prev;
}
const pointer = prev.pointer - 1;
return {
...prev,
current: prev.history[pointer],
pointer
};
});
}, []);
const forward = React.useCallback(() => {
innerSetState((prev) => {
if (prev.pointer >= prev.history.length - 1) {
return prev;
}
const pointer = prev.pointer + 1;
return {
...prev,
current: prev.history[pointer],
pointer
};
});
}, []);
const go = React.useCallback((index) => {
innerSetState((prev) => {
const element = utils.at(prev.history, index);
if (element == null) {
return prev;
}
const pointer = index < 0 ? prev.history.length + index : index;
return { ...prev, current: element, pointer };
});
}, []);
return {
state: state.current,
canForward,
canBack,
setState,
replaceState,
forward,
back,
go
};
}
exports.useHistoryState = useHistoryState;
//# sourceMappingURL=index.cjs.map