@zedux/machines
Version:
Simple native state machine implementation for Zedux atoms
96 lines (95 loc) • 3.34 kB
JavaScript
import { Store as E, injectSelf as M, injectMemo as f, injectRef as m, injectEffect as w, zeduxTypes as y } from "@zedux/atoms";
class _ extends E {
constructor(S, e, v, p) {
super(null, {
context: v,
value: S
}), this.states = e, this.guard = p, this.getContext = () => this.getState().context, this.getValue = () => this.getState().value, this.is = (t) => this.getState().value === t, this.send = (t, s) => this.setState((r) => {
const i = this.states[r.value][t];
return !i || i.guard && !i.guard(r.context) || this.guard && !this.guard(r, i.name) ? r : { context: r.context, value: i.name };
}, s), this.setContext = (t, s) => this.setState(
(r) => ({
context: typeof t == "function" ? t(r.context) : t,
value: r.value
}),
s
), this.setContextDeep = (t, s) => this.setStateDeep(
(r) => ({
context: typeof t == "function" ? t(r.context) : t
}),
s
);
}
}
const R = (...[j, S, e]) => {
const v = M(), { enterHooks: p, leaveHooks: t, store: s } = f(() => {
var k;
const h = {}, c = {}, n = {}, l = (a) => {
const x = {
on: (d, b, T) => (n[a] || (n[a] = {}), n[b] || (n[b] = {}), n[a][d] = {
name: b,
guard: T
}, x),
onEnter: (d) => (h[a] || (h[a] = []), h[a].push(d), x),
onLeave: (d) => (c[a] || (c[a] = []), c[a].push(d), x),
stateName: a
};
return x;
}, [u] = j(l), o = (e == null ? void 0 : e.hydrate) && ((k = v.ecosystem.hydration) == null ? void 0 : k[v.id]), H = new _(
(o == null ? void 0 : o.value) ?? u.stateName,
n,
(o == null ? void 0 : o.context) ?? S,
e == null ? void 0 : e.guard
);
return { enterHooks: h, leaveHooks: c, store: H };
}, []), r = m();
r.current = e == null ? void 0 : e.subscribe, w(
() => {
const h = s.subscribe({
effects: (c) => {
const { action: n, newState: l, oldState: u } = c;
l.value !== (u == null ? void 0 : u.value) && (u && t[u.value] && t[u.value].forEach(
(o) => o(s, c)
), p[l.value] && p[l.value].forEach(
(o) => o(s, c)
), e != null && e.onTransition && e.onTransition(s, c), !(!r.current || l === u || v._isEvaluating || (n == null ? void 0 : n.meta) === y.ignore) && (v._scheduleEvaluation(
{
newState: l,
oldState: u,
operation: "injectMachineStore",
reasons: [
{
action: n,
newState: l,
oldState: u,
operation: "dispatch",
sourceType: "Store",
type: "state changed"
}
],
sourceType: "Injector",
type: "state changed"
},
!1
), (n == null ? void 0 : n.meta) !== y.batch && v.ecosystem._scheduler.flush()));
}
});
return () => h.unsubscribe();
},
[],
{ synchronous: !0 }
);
const i = s.getState();
return p[i.value] && p[i.value].forEach(
(h) => h(s, {
action: { type: y.prime },
newState: i,
store: s
})
), s;
};
export {
_ as MachineStore,
R as injectMachineStore
};
//# sourceMappingURL=zedux-machines.es.min.js.map