element-vir
Version:
Heroic. Reactive. Declarative. Type safe. Web components without compromise.
103 lines (102 loc) • 3.25 kB
JavaScript
import { CallbackObservable } from 'observavir';
/**
* The current state of an {@link AsyncProp}'s value.
*
* @category Internal
*/
export var AsyncValueState;
(function (AsyncValueState) {
/** The `.value` Promise has been rejected. */
AsyncValueState["Rejected"] = "rejected";
/** The `.value` Promise has not settled yet. */
AsyncValueState["Waiting"] = "waiting";
/** The `.value` Promise has been resolved into an awaited value. */
AsyncValueState["Resolved"] = "resolved";
})(AsyncValueState || (AsyncValueState = {}));
/**
* Class for constructing async props. Do not use this directly as its internal types won't be
* inferred correctly. Instead use {@link asyncProp} an async prop or {@link AsyncProp} for types.
*
* @category Internal
*/
export class InternalAsyncPropClass extends CallbackObservable {
/**
* The current `.value` if it has settled (into either a resolved value or an Error), or
* `undefined` if it has not.
*/
get settledValue() {
if (this.isSettled()) {
return this.value;
}
else {
return undefined;
}
}
/** The current `.value` as a promise or resolved value. If `.value` is an error, it'll throw. */
get promiseValue() {
if (this.isError()) {
return Promise.reject(this.value);
}
else if (this.isWaiting()) {
return this.value;
}
else {
return Promise.resolve(this.value);
}
}
/** The state of the current `.value`. */
get state() {
if (this.isResolved()) {
return AsyncValueState.Resolved;
}
else if (this.isError()) {
return AsyncValueState.Rejected;
}
else {
return AsyncValueState.Waiting;
}
}
/**
* Checks if the current `.value` has resolved (meaning the Promise has settled and it was not
* rejected). This type guards the current instance's `.value` property.
*/
isResolved() {
return !(this.value instanceof Promise);
}
/**
* Checks if the current `.value` has settled (meaning it is either a rejection error or a
* resolved value). This type guards the current instance's `.value` property.
*/
isSettled() {
return !(this.value instanceof Promise);
}
/**
* Checks if the current `.value` has not settled yet settled (meaning it is still an unsettled
* Promise). This type guards the current instance's `.value` property.
*/
isWaiting() {
return this.value instanceof Promise;
}
/**
* Checks if the current `.value` is a rejection error. This type guards the current instance's
* `.value` property.
*/
isError() {
return this.value instanceof Error;
}
/**
* Checks if the current `.value` is resolved (and not an error) or still waiting. This type
* guards the current instance's `.value` property.
*/
isNotError() {
return !(this.value instanceof Error);
}
}
/**
* Create an async prop for a declarative element's state.
*
* @category Async
*/
export function asyncProp(init) {
return new InternalAsyncPropClass(init);
}