UNPKG

3.62 kBJavaScriptView Raw
1System.register(['xstate', 'jotai'], (function (exports) {
2 'use strict';
3 var interpret, atom;
4 return {
5 setters: [function (module) {
6 interpret = module.interpret;
7 }, function (module) {
8 atom = module.atom;
9 }],
10 execute: (function () {
11
12 exports('atomWithMachine', atomWithMachine);
13
14 const RESTART = exports('RESTART', Symbol());
15 function atomWithMachine(getMachine, getOptions) {
16 const cachedMachineAtom = atom(null);
17 const machineAtom = atom((get) => {
18 const cachedMachine = get(cachedMachineAtom);
19 if (cachedMachine) {
20 return cachedMachine;
21 }
22 let initializing = true;
23 const safeGet = (a) => {
24 if (initializing) {
25 return get(a);
26 }
27 throw new Error("get not allowed after initialization");
28 };
29 const machine = isGetter(getMachine) ? getMachine(safeGet) : getMachine;
30 const options = isGetter(getOptions) ? getOptions(safeGet) : getOptions;
31 initializing = false;
32 const {
33 guards,
34 actions,
35 services,
36 delays,
37 context,
38 ...interpreterOptions
39 } = options || {};
40 const machineConfig = {
41 ...guards && { guards },
42 ...actions && { actions },
43 ...services && { services },
44 ...delays && { delays }
45 };
46 const machineWithConfig = machine.withConfig(machineConfig, () => ({
47 ...machine.context,
48 ...context
49 }));
50 const service = interpret(machineWithConfig, interpreterOptions);
51 return { machine: machineWithConfig, service };
52 }, (get, set, _arg) => {
53 set(cachedMachineAtom, get(machineAtom));
54 });
55 machineAtom.onMount = (commit) => {
56 commit();
57 };
58 const cachedMachineStateAtom = atom(null);
59 const machineStateAtom = atom((get) => {
60 var _a;
61 return (_a = get(cachedMachineStateAtom)) != null ? _a : get(machineAtom).machine.initialState;
62 }, (get, set, registerCleanup) => {
63 const { service } = get(machineAtom);
64 service.onTransition((nextState) => {
65 set(cachedMachineStateAtom, nextState);
66 });
67 service.start();
68 registerCleanup(() => {
69 const { service: service2 } = get(machineAtom);
70 service2.stop();
71 });
72 });
73 machineStateAtom.onMount = (initialize) => {
74 let unsub;
75 initialize((cleanup) => {
76 if (unsub === false) {
77 cleanup();
78 } else {
79 unsub = cleanup;
80 }
81 });
82 return () => {
83 if (unsub) {
84 unsub();
85 }
86 unsub = false;
87 };
88 };
89 const machineStateWithServiceAtom = atom((get) => get(machineStateAtom), (get, set, event) => {
90 const { service } = get(machineAtom);
91 if (event === RESTART) {
92 service.stop();
93 set(cachedMachineAtom, null);
94 set(machineAtom, null);
95 const { service: newService } = get(machineAtom);
96 newService.onTransition((nextState) => {
97 set(cachedMachineStateAtom, nextState);
98 });
99 newService.start();
100 } else {
101 service.send(event);
102 }
103 });
104 return machineStateWithServiceAtom;
105 }
106 const isGetter = (v) => typeof v === "function";
107
108 })
109 };
110}));