@keislamoglu/react-conditional
Version:
Reduce the complexity of conditional rendering.
112 lines (99 loc) • 3.21 kB
JavaScript
;
Object.defineProperty(exports, '__esModule', { value: true });
var react = require('react');
const useConditional = conditions => {
const [actions, _setActions] = react.useState(new Set());
const verifyAndPerformConditions = react.useCallback(() => {
const _actions = Array.from(actions);
conditions.forEach(condition => {
condition.verifyAndPerform(_actions);
});
}, [actions, conditions]);
const doAction = react.useCallback(action => {
_setActions(actions => {
if (actions.has(action)) {
return actions;
}
actions.add(action);
return new Set(actions);
});
}, []);
const undoAction = react.useCallback(action => {
_setActions(actions => {
if (!actions.has(action)) {
return actions;
}
actions.delete(action);
return new Set(actions);
});
}, []);
const clearActions = react.useCallback(() => {
_setActions(actions => {
if (actions.size === 0) {
return actions;
}
actions.clear();
return new Set(actions);
});
}, []);
const setActions = react.useCallback(_actions => {
_setActions(actions => {
if (_actions.length === actions.size && _actions.every(action => actions.has(action))) {
return actions;
}
actions.clear();
_actions.forEach(action => actions.add(action));
return new Set(actions);
});
}, []);
const verifyCondition = react.useCallback(when => {
return when == null || [!when.done || when.done.every(actionShouldDone => actions.has(actionShouldDone)), !when.undone || !when.undone.some(actionShouldUndone => actions.has(actionShouldUndone))].every(Boolean);
}, [actions]);
react.useEffect(() => {
verifyAndPerformConditions();
}, [verifyAndPerformConditions]);
return {
doAction,
undoAction,
clearActions,
setActions,
verifyCondition
};
};
const useCondition = (when, handler) => {
const performed = react.useRef(false);
const teardownFn = react.useRef();
const handlerRef = react.useRef(handler);
const verify = react.useCallback(actions => {
return when == null || [!when.done || when.done.every(actionShouldDone => actions.includes(actionShouldDone)), !when.undone || !when.undone.some(actionShouldUndone => actions.includes(actionShouldUndone))].every(Boolean);
}, [when]);
const perform = react.useCallback(() => {
if (performed.current) return;
performed.current = true;
return teardownFn.current = handler();
}, [handler]);
const revoke = react.useCallback(() => {
if (!performed.current) return;
performed.current = false;
teardownFn.current && teardownFn.current();
}, []);
const verifyAndPerform = react.useCallback(actions => {
if (verify(actions)) {
perform();
} else {
revoke();
}
}, [verify, perform, revoke]);
react.useEffect(() => {
if (handler !== handlerRef.current) {
revoke();
handlerRef.current = handler;
}
}, [handler, revoke]);
return {
verifyAndPerform
};
};
exports.useCondition = useCondition;
exports.useConditional = useConditional;
//# sourceMappingURL=react-conditional.cjs.development.js.map