async-states
Version:
Core of async-states
73 lines (70 loc) • 2.48 kB
JavaScript
import { emptyArray, isFunction, __DEV__ } from '../utils.js';
import { pending } from '../enums.js';
import { startEmitting, stopEmitting, replaceInstanceState, isAlteringState } from './StateUpdate.js';
function createProps(instance, indicators, payload, runProps) {
let getState = instance.actions.getState;
let args = (runProps?.args || emptyArray);
let controller = new AbortController();
let producerProps = {
emit,
args,
abort,
getState,
payload: payload,
signal: controller.signal,
onAbort(callback) {
if (isFunction(callback)) {
controller.signal.addEventListener("abort", () => {
callback(controller.signal.reason);
});
}
},
isAborted() {
return indicators.aborted;
},
get lastSuccess() {
return instance.lastSuccess;
},
};
return producerProps;
function emit(value, status) {
if (indicators.cleared) {
return;
}
if (!indicators.done) {
if (__DEV__) {
console.error("Called props.emit before the producer resolves. This is" +
" not supported in the library and will have no effect");
}
return;
}
let prevIsEmitting = startEmitting();
let newValue = value;
let newStatus = status;
instance.actions.setState(newValue, newStatus, runProps);
stopEmitting(prevIsEmitting);
}
function abort(reason) {
if (indicators.aborted || indicators.cleared) {
return;
}
if (!indicators.done) {
indicators.aborted = true;
let currentState = instance.state;
if (currentState.status === pending) {
currentState = currentState.prev;
}
// revert back to previous state when aborting only if we won't be updating
// the state right next.
let isCurrentlyAlteringState = isAlteringState();
if (!isCurrentlyAlteringState) {
replaceInstanceState(instance, currentState, true, runProps);
}
}
indicators.cleared = true; // before calling user land onAbort that may emit
controller.abort(reason);
instance.currentAbort = undefined;
}
}
export { createProps };
//# sourceMappingURL=StateProps.js.map