@koordinates/xstate-tree
Version:
Build UIs with Actors using xstate and React
59 lines (58 loc) • 2.21 kB
JavaScript
;
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.lazy = void 0;
const react_1 = __importDefault(require("react"));
const xstate_1 = require("xstate");
const builders_1 = require("./builders");
const slots_1 = require("./slots");
/**
* @public
*
* Wraps an xstate-tree returning Promise (generated by `import()` in an xstate-tree machine responsible for
* booting up the machine upon resolution
*
* @param factory - the factory function that returns the promise that resolves to the machine
* @param options - configure loading component and context to invoke machine with
* @returns an xstate-tree machine that wraps the promise, invoking the resulting machine when it resolves
*/
function lazy(factory, { Loader = () => null, input } = {}) {
const loadedMachineSlot = (0, slots_1.singleSlot)("loadedMachine");
const slots = [loadedMachineSlot];
const machine = (0, xstate_1.setup)({}).createMachine({
initial: "loading",
context: {},
states: {
loading: {
invoke: {
src: (0, xstate_1.fromPromise)(factory),
onDone: {
target: "rendering",
actions: (0, xstate_1.assign)({
loadedMachine: ({ spawn, event }) => spawn(event.output, {
id: loadedMachineSlot.getId(),
input,
}),
}),
},
},
},
rendering: {},
},
});
return (0, builders_1.createXStateTreeMachine)(machine, {
slots,
selectors({ inState }) {
return { loading: inState("loading") };
},
View({ selectors, slots }) {
if (selectors.loading) {
return react_1.default.createElement(Loader, null);
}
return react_1.default.createElement(slots.loadedMachine, null);
},
});
}
exports.lazy = lazy;