@cssints/machine 0.0.0-stage → 0.28.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +196 -2
- package/dist/index-C5d0wRMO.d.mts +262 -0
- package/dist/index.d.mts +2 -0
- package/dist/index.mjs +466 -0
- package/dist/solid.d.mts +41 -0
- package/dist/solid.mjs +80 -0
- package/package.json +39 -4
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Alexei Accio
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,197 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @cssints/machine
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
A minimal, dependency-free, type-safe state machine for UI protocols: an animated disclosure, a menu that opens on
|
|
4
|
+
hover and closes on a debounced leave, a toast that reverses mid-flight.
|
|
5
|
+
|
|
6
|
+
A signal holds state, not a protocol. The moment a component animates, the protocol appears: a `closing` and an
|
|
7
|
+
`opening` in the same frame race; a cancelled animation still fires its completion; an interrupted close must reverse
|
|
8
|
+
from where the box is; a burst of `pointerenter`/`pointerleave` must not produce five effects; a debounce must not
|
|
9
|
+
swallow the last intent. None of those is expressible as a signal. This package is the runtime half: the smallest
|
|
10
|
+
machine that can drive those protocols, and a harness that makes them provable without a browser.
|
|
11
|
+
|
|
12
|
+
No dependencies. The core is plain TypeScript (it runs through node's type stripping: no enums, no namespaces, no
|
|
13
|
+
parameter properties); `@cssints/machine/solid` is the only file that imports anything, and `solid-js` is its optional
|
|
14
|
+
peer.
|
|
15
|
+
|
|
16
|
+
## An animated disclosure
|
|
17
|
+
|
|
18
|
+
```ts
|
|
19
|
+
import { createMachine, defineMachine } from "@cssints/machine";
|
|
20
|
+
|
|
21
|
+
type Events = { open: undefined; close: undefined; finish: { id: number } };
|
|
22
|
+
|
|
23
|
+
const disclosure = defineMachine<Events>()({
|
|
24
|
+
start: "closed",
|
|
25
|
+
initial: { progress: 0 },
|
|
26
|
+
states: {
|
|
27
|
+
closed: {
|
|
28
|
+
on: { open: { target: "opening", effect: { type: "animate", to: "open" } } },
|
|
29
|
+
},
|
|
30
|
+
opening: {
|
|
31
|
+
on: {
|
|
32
|
+
finish: "open",
|
|
33
|
+
close: { target: "closing", effect: { type: "animate", to: "closed" } },
|
|
34
|
+
},
|
|
35
|
+
after: { 400: "open" }, // an animation that never reports back still ends: no state is a trap
|
|
36
|
+
},
|
|
37
|
+
open: {
|
|
38
|
+
on: {
|
|
39
|
+
close: { target: "closing", effect: { type: "animate", to: "closed" } },
|
|
40
|
+
tick: {
|
|
41
|
+
target: "open",
|
|
42
|
+
assign: (context, event) => ({
|
|
43
|
+
progress: event.type === "tick" ? event.value : context.progress,
|
|
44
|
+
}),
|
|
45
|
+
},
|
|
46
|
+
},
|
|
47
|
+
},
|
|
48
|
+
closing: {
|
|
49
|
+
on: {
|
|
50
|
+
finish: "closed",
|
|
51
|
+
open: { target: "opening", effect: { type: "animate", to: "open" } },
|
|
52
|
+
},
|
|
53
|
+
after: { 400: "closed" },
|
|
54
|
+
},
|
|
55
|
+
},
|
|
56
|
+
});
|
|
57
|
+
|
|
58
|
+
const machine = createMachine(disclosure);
|
|
59
|
+
|
|
60
|
+
// The host runs the effects; the machine holds one handle per effect and cancels it when the state is left.
|
|
61
|
+
machine.onEffect((handle) => {
|
|
62
|
+
const animation = box.animate(keyframes[handle.spec.to], { duration: 200 });
|
|
63
|
+
animation.finished.then(() => machine.send({ type: "finish", id: handle.id }));
|
|
64
|
+
});
|
|
65
|
+
|
|
66
|
+
button.addEventListener("click", () => {
|
|
67
|
+
machine.send(machine.getState().state === "closed" ? { type: "open" } : { type: "close" });
|
|
68
|
+
});
|
|
69
|
+
```
|
|
70
|
+
|
|
71
|
+
## The five properties it buys
|
|
72
|
+
|
|
73
|
+
1. **A close interrupted by an open reverses and ends open.** A transition out of a transient state is a transition like
|
|
74
|
+
any other; the reverse's effect supersedes the close's effect.
|
|
75
|
+
2. **A cancelled animation's completion is ignored.** A `finish` carries the handle id the host was given. Leaving the
|
|
76
|
+
state cancels the handle, so a completion that arrives late is stale and dropped, not applied to the new state.
|
|
77
|
+
3. **Two events in one frame produce at most one effect per state.** Each transition cancels the handles of the state it
|
|
78
|
+
leaves; the host runs the last intent only.
|
|
79
|
+
4. **A debounced burst produces one effect carrying the last intent.** `send(event, { debounce })` (or a machine-level
|
|
80
|
+
`debounce` map) coalesces by event type; `flush()` delivers the final intent, `cancel()` drops a superseded one.
|
|
81
|
+
5. **Nothing is ever stuck.** Every state has an exit; `after` is the fallback for an effect that never reports back.
|
|
82
|
+
|
|
83
|
+
## API
|
|
84
|
+
|
|
85
|
+
| Member | What it does |
|
|
86
|
+
| ------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
|
87
|
+
| `defineMachine(config)` | A definition: `{ initial, states, start?, debounce? }`. Events are a union of the `on` keys, the context is inferred from `initial`; an event no state accepts is a type error. |
|
|
88
|
+
| `defineMachine<Payloads>()(config)` | The same with typed payloads: `{ close: undefined; finish: { id: number } }`. A guard or an `assign` narrows on `event.type`. |
|
|
89
|
+
| `createMachine(definition, options?)` | An instance. Options: `clock`, `autoStart`, `onEffect`, `onCancel`, `onTransition`. |
|
|
90
|
+
| `machine.getState()` | `{ state, context }`; a new object per transition, the old one stays readable. |
|
|
91
|
+
| `machine.subscribe(listener)` | Every transition and every debounce flush. |
|
|
92
|
+
| `machine.subscribe(selector, listener)` | Only a change of `selector`'s value (`Object.is`), the store bridge a host reads one slice with. |
|
|
93
|
+
| `machine.send(event, { debounce? })` | Deliver now, or schedule a coalesced delivery. |
|
|
94
|
+
| `machine.flush()` / `machine.cancel(type?)` | Deliver the pending intent now / drop it. |
|
|
95
|
+
| `machine.effects()` | The live handles: issued, not completed, not cancelled. |
|
|
96
|
+
| `machine.onEffect` / `onCancel` / `onTransition` | The host's side: run an effect, stop it, observe a delivery. |
|
|
97
|
+
| `machine.start()` / `machine.destroy()` | Enter the start state (idempotent) / clear every timer, cancel every handle, drop every listener. |
|
|
98
|
+
| `harness(definition)` | The machine on a fake clock: `advance(ms)`, a queue (`enqueue`, `deliver`, `deliverAll`), `race`, `interleave`, `flushEffects`, the live `cancelled()` ids and the `log`. |
|
|
99
|
+
|
|
100
|
+
A transition is a target string (`open: "opening"`) or `{ target, guard?, effect?, assign? }`; a state's `on` value is one
|
|
101
|
+
transition or a list, the first whose guard passes. `after` maps ms to a transition; leaving the state clears the timer.
|
|
102
|
+
`assign` is a `Partial<context>` or `(context, event) => Partial<context>`.
|
|
103
|
+
|
|
104
|
+
## Effects and handles
|
|
105
|
+
|
|
106
|
+
Effects are data, not callbacks: `{ type: "animate", to: "open", duration: 200 }`. The machine issues a **handle**
|
|
107
|
+
(`{ id, type, spec, state }`) for every effect a state entry or a transition declares, and cancels it when the state is
|
|
108
|
+
left or a transition supersedes it. A completion event is any event with a numeric `id`: a stale id is dropped (and
|
|
109
|
+
logged as `cancelled`), a live one completes its handle without a cancellation. `effects()` is what the host should be
|
|
110
|
+
running now.
|
|
111
|
+
|
|
112
|
+
An effect that takes longer than the state lives is cancelled; the host stops it (`onCancel`) and its late completion
|
|
113
|
+
cannot move the machine.
|
|
114
|
+
|
|
115
|
+
## The clock
|
|
116
|
+
|
|
117
|
+
`createMachine(definition, { clock })` takes `{ now(), setTimeout(callback, ms), clearTimeout(handle) }`; the default is
|
|
118
|
+
`systemClock`. The same clock drives `after`, the debounce and a transition's timestamp, so a test drives time with
|
|
119
|
+
`advance(ms)` and a host uses real time.
|
|
120
|
+
|
|
121
|
+
## The harness
|
|
122
|
+
|
|
123
|
+
```ts
|
|
124
|
+
import { harness } from "@cssints/machine";
|
|
125
|
+
|
|
126
|
+
const h = harness(disclosure);
|
|
127
|
+
h.send({ type: "open" });
|
|
128
|
+
const animation = h.machine.effects().at(-1);
|
|
129
|
+
|
|
130
|
+
h.send({ type: "close" }); // the open's animation is cancelled, the close's is issued
|
|
131
|
+
h.send({ type: "finish", id: animation.id }); // stale: ignored
|
|
132
|
+
assert.equal(h.machine.getState().state, "closing");
|
|
133
|
+
|
|
134
|
+
h.advance(400); // the `after` fallback settles it
|
|
135
|
+
assert.equal(h.machine.getState().state, "closed");
|
|
136
|
+
```
|
|
137
|
+
|
|
138
|
+
`h.log` has one row per delivery (and one per effect it issued): `{ at, event, from, to, effect, context, cancelled }`.
|
|
139
|
+
`h.race(...events)` delivers a frame's events at one instant; `h.interleave(...sequences)` round-robins several orders.
|
|
140
|
+
`h.flushEffects()` returns the handles the host should run now, not the ones already cancelled in the same frame.
|
|
141
|
+
|
|
142
|
+
## The Solid bridge
|
|
143
|
+
|
|
144
|
+
`@cssints/machine/solid` (solid-js is a peer) exposes the machine as Solid's store layer:
|
|
145
|
+
|
|
146
|
+
```ts
|
|
147
|
+
import { createMachineStore } from "@cssints/machine/solid";
|
|
148
|
+
|
|
149
|
+
const store = createMachineStore(machine, {
|
|
150
|
+
settled: (phase) => phase === "open" || phase === "closed",
|
|
151
|
+
intent: (event) =>
|
|
152
|
+
event.type === "close" ? "closed" : event.type === "open" ? "open" : undefined,
|
|
153
|
+
});
|
|
154
|
+
const view = store.projection(
|
|
155
|
+
(draft, from) => {
|
|
156
|
+
draft.visible = from.phase !== "closed";
|
|
157
|
+
},
|
|
158
|
+
{ visible: false },
|
|
159
|
+
);
|
|
160
|
+
```
|
|
161
|
+
|
|
162
|
+
- `store.state` is a `createStore` of `{ ...context, phase }`, one setter call per transition, writing only the fields
|
|
163
|
+
that changed: a reader of `state.phase` does not re-run when only `progress` changes.
|
|
164
|
+
- `store.optimistic` is a derived `createOptimisticStore`: its value follows `state`, and an intent writes the phase it
|
|
165
|
+
is heading to inside a Solid `action`. The action stays open until the machine settles, then the override reverts to
|
|
166
|
+
the committed snapshot — an intent that is superseded before the finish rolls back instead of sticking.
|
|
167
|
+
- `store.projection(compute, seed)` is a `createProjection` over `state`: only a changed field notifies, so a reader of
|
|
168
|
+
`view.visible` does not re-run when `progress` changes. A projection reads the committed frame, not an optimistic
|
|
169
|
+
override (Solid holds the override whole), so the visual phase is read off `optimistic` directly.
|
|
170
|
+
- `store.send(event)` is the machine's send with the optimistic lead; sending on the machine directly skips it.
|
|
171
|
+
|
|
172
|
+
One `setState` per transition is the same atomicity the reactive runtime gets from its one flush
|
|
173
|
+
(`packages/reactive/src/runtime.ts`, `packages/apg-specs/specs/patterns/reactive.qnt`): a reader never sees a phase from
|
|
174
|
+
one transition with a progress from another.
|
|
175
|
+
|
|
176
|
+
## Limits
|
|
177
|
+
|
|
178
|
+
- One state at a time: no parallel states, no history states, no nested machines. A protocol with two independent
|
|
179
|
+
regions is two machines and a host that sends to both.
|
|
180
|
+
- Effects are data and the host runs them; the machine does not await a promise, own an animation or call a callback.
|
|
181
|
+
A completion that never arrives is covered by `after` (or by a host that cancels).
|
|
182
|
+
- A numeric `id` on an event is reserved for an effect handle: an event with a stale id is dropped.
|
|
183
|
+
- The debounce coalesces by event type; two different sources of the same event type share one pending intent.
|
|
184
|
+
- The store bridge's optimistic lead is taken only from a settled phase (the coordinator's `settled`); a new intent in
|
|
185
|
+
the middle of a transition rolls the previous lead back rather than stacking a second one.
|
|
186
|
+
- There is no Quint spec for this runtime yet; the harness's five properties are the oracle (`test/machine.mjs`).
|
|
187
|
+
|
|
188
|
+
## Tests
|
|
189
|
+
|
|
190
|
+
```bash
|
|
191
|
+
cd packages/machine && bun run test # node test/machine.mjs, then node test/store.mjs (Solid's client build)
|
|
192
|
+
cd packages/machine && bun run typecheck # src and test/types (the @ts-expect-error cases)
|
|
193
|
+
```
|
|
194
|
+
|
|
195
|
+
The store test runs in plain node with `--conditions=browser --conditions=development`: Solid's store layer needs no DOM,
|
|
196
|
+
but the node default is the SSR build, where an action's optimistic override has no client transaction to live in. The
|
|
197
|
+
package's `test` script carries the flags.
|
|
@@ -0,0 +1,262 @@
|
|
|
1
|
+
/** A fake clock: time moves only when `advance` is called. */
|
|
2
|
+
interface FakeClock extends Clock {
|
|
3
|
+
/** The current time in ms. */
|
|
4
|
+
readonly time: number;
|
|
5
|
+
/** Move time forward by `ms`, running every timer that falls due, in order. */
|
|
6
|
+
advance(ms: number): void;
|
|
7
|
+
/** How many timers are scheduled. */
|
|
8
|
+
pending(): number;
|
|
9
|
+
}
|
|
10
|
+
/** A deterministic clock: `now` starts at 0 and only `advance` moves it. */
|
|
11
|
+
declare const createFakeClock: () => FakeClock;
|
|
12
|
+
/** One entry of the harness log: a delivery, one row per effect it issued (or one row with no effect). */
|
|
13
|
+
interface LogEntry<C extends object> {
|
|
14
|
+
/** When it happened on the fake clock. */
|
|
15
|
+
readonly at: number;
|
|
16
|
+
/** The event's `type` (`"after"` for a timer). */
|
|
17
|
+
readonly event: string;
|
|
18
|
+
/** The state when the event arrived. */
|
|
19
|
+
readonly from: string;
|
|
20
|
+
/** The state after it, or `undefined` when no transition was taken. */
|
|
21
|
+
readonly to: string | undefined;
|
|
22
|
+
/** The handle this row is about. */
|
|
23
|
+
readonly effect: number | undefined;
|
|
24
|
+
/** The context after the delivery. */
|
|
25
|
+
readonly context: C;
|
|
26
|
+
/** The event was dropped (a stale handle id) or this effect was cancelled by leaving its state. */
|
|
27
|
+
cancelled: boolean;
|
|
28
|
+
}
|
|
29
|
+
/** A machine on a fake clock, with the host's side recorded. */
|
|
30
|
+
interface Harness<C extends object, S extends string, E extends {
|
|
31
|
+
readonly type: string;
|
|
32
|
+
}> {
|
|
33
|
+
/** The machine. Send through the harness to keep the queue and the log together, or directly. */
|
|
34
|
+
readonly machine: Machine<C, S, E>;
|
|
35
|
+
/** The fake clock; `advance(ms)` is the harness's shortcut. */
|
|
36
|
+
readonly clock: FakeClock;
|
|
37
|
+
/** Every delivery, and every effect a delivery issued. */
|
|
38
|
+
readonly log: LogEntry<C>[];
|
|
39
|
+
/** Send now (an effect's completion, a user event). */
|
|
40
|
+
send(event: E, options?: SendOptions): void;
|
|
41
|
+
/** Queue events for a later, chosen order. */
|
|
42
|
+
enqueue(...events: E[]): void;
|
|
43
|
+
/** The queued events, in order. */
|
|
44
|
+
queued(): readonly E[];
|
|
45
|
+
/** Deliver the first queued event now. */
|
|
46
|
+
deliver(): void;
|
|
47
|
+
/** Deliver every queued event now, in queue order. */
|
|
48
|
+
deliverAll(): void;
|
|
49
|
+
/** Move the fake clock forward. */
|
|
50
|
+
advance(ms: number): void;
|
|
51
|
+
/** The handles issued since the last flush: what the host would run now. */
|
|
52
|
+
pendingEffects(): readonly EffectHandle[];
|
|
53
|
+
/** The handles issued since the last flush; clears the queue. */
|
|
54
|
+
flushEffects(): readonly EffectHandle[];
|
|
55
|
+
/** Deliver every event at the current instant, in order, without advancing time. */
|
|
56
|
+
race(...events: E[]): readonly MachineState<C, S>[];
|
|
57
|
+
/** Deliver several sequences round-robin at the current instant. */
|
|
58
|
+
interleave(...sequences: readonly (readonly E[])[]): readonly MachineState<C, S>[];
|
|
59
|
+
/** The ids of the effects cancelled so far. */
|
|
60
|
+
cancelled(): readonly number[];
|
|
61
|
+
}
|
|
62
|
+
/**
|
|
63
|
+
* Put a definition on a fake clock: the machine starts (so its entry effects are issued before the harness returns) and
|
|
64
|
+
* every delivery, issued effect and cancellation is recorded.
|
|
65
|
+
*/
|
|
66
|
+
declare function harness<C extends object, St, P extends PayloadMap = Record<never, never>>(definition: MachineDefinition<C, St, P>, options?: Omit<MachineOptions, "autoStart" | "clock" | "onEffect" | "onCancel" | "onTransition">): Harness<C, keyof St & string, EventOf<St, P>>;
|
|
67
|
+
/** A map from event name to its payload: `undefined` for an event with no payload. */
|
|
68
|
+
type PayloadMap = {
|
|
69
|
+
readonly [type: string]: object | undefined;
|
|
70
|
+
};
|
|
71
|
+
/** An effect is data, not a callback: `type` names it and every other field is the host's. */
|
|
72
|
+
type EffectSpec = {
|
|
73
|
+
readonly type: string;
|
|
74
|
+
readonly [field: string]: unknown;
|
|
75
|
+
};
|
|
76
|
+
/** Any event: a `type` and, when it carries one, a payload. */
|
|
77
|
+
type BaseEvent = {
|
|
78
|
+
readonly type: string;
|
|
79
|
+
readonly [field: string]: unknown;
|
|
80
|
+
};
|
|
81
|
+
/** A timer handle: `number` in a fake clock, a `Timeout` from the system one. */
|
|
82
|
+
type TimerHandle = unknown;
|
|
83
|
+
/** The clock the machine reads; a host passes the system one, a harness a fake one. */
|
|
84
|
+
interface Clock {
|
|
85
|
+
/** The current time in ms. */
|
|
86
|
+
now(): number;
|
|
87
|
+
/** Run `callback` after `ms`; the handle is opaque to the machine. */
|
|
88
|
+
setTimeout(callback: () => void, ms: number): TimerHandle;
|
|
89
|
+
/** Cancel a pending callback. */
|
|
90
|
+
clearTimeout(handle: TimerHandle): void;
|
|
91
|
+
}
|
|
92
|
+
/** The host's clock: `Date.now` and the global timers. */
|
|
93
|
+
declare const systemClock: Clock;
|
|
94
|
+
/** A transition: a target state, a guard, an effect for the host and a write to the context. */
|
|
95
|
+
interface Transition<C extends object, E> {
|
|
96
|
+
/** The state the transition enters. */
|
|
97
|
+
readonly target: string;
|
|
98
|
+
/** Whether this transition applies, given the context and the event. */
|
|
99
|
+
readonly guard?: ((context: C, event: E) => boolean) | undefined;
|
|
100
|
+
/** The effect(s) the host runs; the machine issues a handle for each, owned by the target state. */
|
|
101
|
+
readonly effect?: EffectSpec | readonly EffectSpec[] | undefined;
|
|
102
|
+
/** The context fields to write, or a function of the context and the event. */
|
|
103
|
+
readonly assign?: Partial<C> | ((context: C, event: E) => Partial<C>) | undefined;
|
|
104
|
+
}
|
|
105
|
+
/** A target as a string (a transition with no guard, effect or assign), or the full transition. */
|
|
106
|
+
type TransitionLike<C extends object, E> = string | Transition<C, E>;
|
|
107
|
+
/** One transition or a list of them; the first whose guard passes is taken. */
|
|
108
|
+
type TransitionList<C extends object, E> = TransitionLike<C, E> | readonly TransitionLike<C, E>[];
|
|
109
|
+
/** The definition of one state. */
|
|
110
|
+
interface StateDef<C extends object, E> {
|
|
111
|
+
/** On an event: one transition, or the first of a list whose guard passes. */
|
|
112
|
+
readonly on?: {
|
|
113
|
+
readonly [type: string]: TransitionList<C, E>;
|
|
114
|
+
} | undefined;
|
|
115
|
+
/** After `ms` in this state: a transition. Leaving the state clears the timer. */
|
|
116
|
+
readonly after?: {
|
|
117
|
+
readonly [ms: string]: TransitionList<C, E>;
|
|
118
|
+
} | undefined;
|
|
119
|
+
/** The effects of being in this state; cancelled when the state is left. */
|
|
120
|
+
readonly effect?: readonly EffectSpec[] | undefined;
|
|
121
|
+
}
|
|
122
|
+
/** The event union a machine accepts, plus its payloads, given its states and a payload map. */
|
|
123
|
+
type EventName<St, K extends keyof St> = St[K] extends {
|
|
124
|
+
readonly on?: infer On;
|
|
125
|
+
} ? keyof On & string : never;
|
|
126
|
+
/** Every event name some state accepts. */
|
|
127
|
+
type EventNames<St> = { [K in keyof St]: EventName<St, K>; }[keyof St];
|
|
128
|
+
/** The payload of one event: its declared payload, or none. */
|
|
129
|
+
type PayloadOf<K extends string, P extends PayloadMap> = K extends keyof P ? P[K] extends object ? P[K] : Record<never, never> : Record<never, never>;
|
|
130
|
+
/** The event union of a machine, derived from its states and its payload map. */
|
|
131
|
+
type EventOf<St, P extends PayloadMap> = { [K in EventNames<St>]: {
|
|
132
|
+
readonly type: K;
|
|
133
|
+
} & PayloadOf<K, P>; }[EventNames<St>];
|
|
134
|
+
/** What a guard or an `assign` sees in the definition: the declared payload union, or any event. */
|
|
135
|
+
type ConfigEvent<P extends PayloadMap> = [keyof P] extends [never] ? BaseEvent : { [K in keyof P & string]: {
|
|
136
|
+
readonly type: K;
|
|
137
|
+
} & PayloadOf<K, P>; }[keyof P & string];
|
|
138
|
+
/** A machine's definition: states, the initial context, the start state and the debounce map. */
|
|
139
|
+
interface MachineDefinition<C extends object, St, P extends PayloadMap> {
|
|
140
|
+
/** The initial context. */
|
|
141
|
+
readonly initial: C;
|
|
142
|
+
/** The states, in declaration order. */
|
|
143
|
+
readonly states: St;
|
|
144
|
+
/** The state the machine starts in: `start`, else the first key of `states`. */
|
|
145
|
+
readonly start: keyof St & string;
|
|
146
|
+
/** Event name → debounce in ms, applied by `send` when it passes no `debounce`. */
|
|
147
|
+
readonly debounce: Readonly<Record<string, number>>;
|
|
148
|
+
/** The payload map, so `createMachine` can recover the event union. */
|
|
149
|
+
readonly payloads?: P | undefined;
|
|
150
|
+
}
|
|
151
|
+
/** The state a machine exposes: the state's name and the context. */
|
|
152
|
+
interface MachineState<C extends object, S extends string> {
|
|
153
|
+
/** The current state's name. */
|
|
154
|
+
readonly state: S;
|
|
155
|
+
/** The context. Replace-per-write, so an old snapshot stays readable. */
|
|
156
|
+
readonly context: C;
|
|
157
|
+
}
|
|
158
|
+
/** One running effect: the machine's handle for it. */
|
|
159
|
+
interface EffectHandle {
|
|
160
|
+
/** Unique per machine; a completion event carries it as `id`. */
|
|
161
|
+
readonly id: number;
|
|
162
|
+
/** The effect's `type`. */
|
|
163
|
+
readonly type: string;
|
|
164
|
+
/** The effect as declared. */
|
|
165
|
+
readonly spec: EffectSpec;
|
|
166
|
+
/** The state that owns the handle; leaving the state cancels it. */
|
|
167
|
+
readonly state: string;
|
|
168
|
+
}
|
|
169
|
+
/** What happened to one delivered event. */
|
|
170
|
+
interface TransitionRecord {
|
|
171
|
+
/** `clock.now()` when the event was delivered. */
|
|
172
|
+
readonly at: number;
|
|
173
|
+
/** The event's `type`. */
|
|
174
|
+
readonly event: string;
|
|
175
|
+
/** The state when the event arrived. */
|
|
176
|
+
readonly from: string;
|
|
177
|
+
/** The state after the event (`from` when no transition was taken). */
|
|
178
|
+
readonly to: string;
|
|
179
|
+
/** Whether a transition was taken. */
|
|
180
|
+
readonly taken: boolean;
|
|
181
|
+
/** The handles the transition issued, in order. */
|
|
182
|
+
readonly effects: readonly number[];
|
|
183
|
+
/** The event was dropped because the handle id it carried was already cancelled. */
|
|
184
|
+
readonly cancelled: boolean;
|
|
185
|
+
}
|
|
186
|
+
/** Options for `send`. */
|
|
187
|
+
interface SendOptions {
|
|
188
|
+
/** Coalesce a burst of this event type into the last one, delivered after `ms` unless flushed. */
|
|
189
|
+
readonly debounce?: number | undefined;
|
|
190
|
+
}
|
|
191
|
+
/** Options for `createMachine`. */
|
|
192
|
+
interface MachineOptions {
|
|
193
|
+
/** The clock; the system one by default. */
|
|
194
|
+
readonly clock?: Clock | undefined;
|
|
195
|
+
/** Start on creation (the default); a harness starts after wiring its listeners. */
|
|
196
|
+
readonly autoStart?: boolean | undefined;
|
|
197
|
+
/** A handle was issued. */
|
|
198
|
+
readonly onEffect?: ((handle: EffectHandle) => void) | undefined;
|
|
199
|
+
/** A handle was cancelled by leaving its state or by a transition that superseded it. */
|
|
200
|
+
readonly onCancel?: ((handle: EffectHandle) => void) | undefined;
|
|
201
|
+
/** An event was delivered. */
|
|
202
|
+
readonly onTransition?: ((record: TransitionRecord) => void) | undefined;
|
|
203
|
+
}
|
|
204
|
+
/** A machine instance. */
|
|
205
|
+
interface Machine<C extends object, S extends string, E extends {
|
|
206
|
+
readonly type: string;
|
|
207
|
+
}> {
|
|
208
|
+
/** The current state and context; a new object per transition. */
|
|
209
|
+
getState(): MachineState<C, S>;
|
|
210
|
+
/** Every transition and every debounce flush. */
|
|
211
|
+
subscribe(listener: (state: MachineState<C, S>) => void): () => void;
|
|
212
|
+
/** Only a change of `selector`'s value (compared with `Object.is`). */
|
|
213
|
+
subscribe<T>(selector: (state: MachineState<C, S>) => T, listener: (value: T, previous: T) => void): () => void;
|
|
214
|
+
/** Deliver an event now, or after a debounce when one applies. */
|
|
215
|
+
send(event: E, options?: SendOptions): void;
|
|
216
|
+
/** Deliver every pending debounced event now: the final intent is never lost. */
|
|
217
|
+
flush(): void;
|
|
218
|
+
/** Drop the pending debounced event of `type`, or every pending one. */
|
|
219
|
+
cancel(type?: E["type"]): void;
|
|
220
|
+
/** The handles that are live: issued and not yet completed or cancelled. */
|
|
221
|
+
effects(): readonly EffectHandle[];
|
|
222
|
+
/** A handle was issued. */
|
|
223
|
+
onEffect(listener: (handle: EffectHandle) => void): () => void;
|
|
224
|
+
/** A handle was cancelled. */
|
|
225
|
+
onCancel(listener: (handle: EffectHandle) => void): () => void;
|
|
226
|
+
/** An event was delivered (or dropped). */
|
|
227
|
+
onTransition(listener: (record: TransitionRecord) => void): () => void;
|
|
228
|
+
/** Enter the start state: issue its effects and schedule its `after` timers. Idempotent. */
|
|
229
|
+
start(): void;
|
|
230
|
+
/** Clear every timer and pending event, cancel every handle, drop every listener. */
|
|
231
|
+
destroy(): void;
|
|
232
|
+
}
|
|
233
|
+
/** What `defineMachine` takes: the initial context, the states, an optional start state and a debounce map. */
|
|
234
|
+
interface MachineConfig<C extends object, St, P extends PayloadMap> {
|
|
235
|
+
/** The initial context; its shape is the machine's context. */
|
|
236
|
+
readonly initial: C;
|
|
237
|
+
/** The states, in declaration order; the first is the start state unless `start` says otherwise. */
|
|
238
|
+
readonly states: St;
|
|
239
|
+
/** The state the machine starts in. */
|
|
240
|
+
readonly start?: (keyof St & string) | undefined;
|
|
241
|
+
/** Event name → debounce in ms, applied by `send` when it passes no `debounce`. */
|
|
242
|
+
readonly debounce?: Readonly<Record<string, number>> | undefined;
|
|
243
|
+
/** Keeps the payload map in the definition's type. */
|
|
244
|
+
readonly payloads?: P | undefined;
|
|
245
|
+
}
|
|
246
|
+
/**
|
|
247
|
+
* Define a machine: its initial context, its states, the start state (the first key of `states` by default) and an
|
|
248
|
+
* optional debounce map. The state names, the event union and the context are all inferred, and a transition to a state
|
|
249
|
+
* that does not exist is a build error.
|
|
250
|
+
*
|
|
251
|
+
* Events with no payload need nothing more. To type payloads, declare them once, curried:
|
|
252
|
+
* `defineMachine<{ close: undefined; finish: { id: number } }>()({ ... })`; a guard or an `assign` then narrows on
|
|
253
|
+
* `event.type`. Without the map they see `{ type: string; [field: string]: unknown }`.
|
|
254
|
+
*/
|
|
255
|
+
declare function defineMachine<P extends PayloadMap = Record<never, never>>(): <C extends object, const St extends Record<string, StateDef<C, ConfigEvent<P>>>>(config: MachineConfig<C, St, P>) => MachineDefinition<C, St, P>;
|
|
256
|
+
declare function defineMachine<C extends object, const St extends Record<string, StateDef<C, BaseEvent>>>(config: MachineConfig<C, St, Record<never, never>>): MachineDefinition<C, St, Record<never, never>>;
|
|
257
|
+
/**
|
|
258
|
+
* Create a machine and start it (unless `autoStart: false`). The start state's effects are issued right away, so a host
|
|
259
|
+
* reads them through `effects()` or an `onEffect` option.
|
|
260
|
+
*/
|
|
261
|
+
declare function createMachine<C extends object, St, P extends PayloadMap = Record<never, never>>(definition: MachineDefinition<C, St, P>, options?: MachineOptions): Machine<C, keyof St & string, EventOf<St, P>>;
|
|
262
|
+
export { systemClock as C, createFakeClock as D, LogEntry as E, harness as O, defineMachine as S, Harness as T, Transition as _, EffectSpec as a, TransitionRecord as b, Machine as c, MachineOptions as d, MachineState as f, TimerHandle as g, StateDef as h, EffectHandle as i, MachineConfig as l, SendOptions as m, Clock as n, EventNames as o, PayloadMap as p, ConfigEvent as r, EventOf as s, BaseEvent as t, MachineDefinition as u, TransitionLike as v, FakeClock as w, createMachine as x, TransitionList as y };
|
package/dist/index.d.mts
ADDED
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import { C as systemClock, D as createFakeClock, E as LogEntry, O as harness, S as defineMachine, T as Harness, _ as Transition, a as EffectSpec, b as TransitionRecord, c as Machine, d as MachineOptions, f as MachineState, g as TimerHandle, h as StateDef, i as EffectHandle, l as MachineConfig, m as SendOptions, n as Clock, o as EventNames, p as PayloadMap, r as ConfigEvent, s as EventOf, t as BaseEvent, u as MachineDefinition, v as TransitionLike, w as FakeClock, x as createMachine, y as TransitionList } from "./index-C5d0wRMO.mjs";
|
|
2
|
+
export { BaseEvent, Clock, ConfigEvent, EffectHandle, EffectSpec, EventNames, EventOf, type FakeClock, type Harness, type LogEntry, Machine, MachineConfig, MachineDefinition, MachineOptions, MachineState, PayloadMap, SendOptions, StateDef, TimerHandle, Transition, TransitionLike, TransitionList, TransitionRecord, createFakeClock, createMachine, defineMachine, harness, systemClock };
|
package/dist/index.mjs
ADDED
|
@@ -0,0 +1,466 @@
|
|
|
1
|
+
// src/harness.ts
|
|
2
|
+
/** A deterministic clock: `now` starts at 0 and only `advance` moves it. */
|
|
3
|
+
const createFakeClock = () => {
|
|
4
|
+
let now = 0;
|
|
5
|
+
let nextTimer = 1;
|
|
6
|
+
const timers = /* @__PURE__ */ new Map();
|
|
7
|
+
const advance = (ms) => {
|
|
8
|
+
const target = now + ms;
|
|
9
|
+
let steps = 0;
|
|
10
|
+
for (;;) {
|
|
11
|
+
let dueId;
|
|
12
|
+
let dueAt = Number.POSITIVE_INFINITY;
|
|
13
|
+
for (const [id, timer] of timers) if (timer.at <= target && (timer.at < dueAt || timer.at === dueAt && dueId !== void 0 && id < dueId)) {
|
|
14
|
+
dueId = id;
|
|
15
|
+
dueAt = timer.at;
|
|
16
|
+
}
|
|
17
|
+
const timer = dueId === void 0 ? void 0 : timers.get(dueId);
|
|
18
|
+
if (dueId === void 0 || timer === void 0) break;
|
|
19
|
+
timers.delete(dueId);
|
|
20
|
+
now = timer.at;
|
|
21
|
+
timer.callback();
|
|
22
|
+
steps += 1;
|
|
23
|
+
if (steps > 1e5) throw new Error("@cssints/machine: the fake clock ran 100000 timers without reaching its target");
|
|
24
|
+
}
|
|
25
|
+
now = target;
|
|
26
|
+
};
|
|
27
|
+
return {
|
|
28
|
+
get time() {
|
|
29
|
+
return now;
|
|
30
|
+
},
|
|
31
|
+
now: () => now,
|
|
32
|
+
setTimeout: (callback, ms) => {
|
|
33
|
+
const id = nextTimer++;
|
|
34
|
+
timers.set(id, {
|
|
35
|
+
at: now + Math.max(0, ms),
|
|
36
|
+
callback
|
|
37
|
+
});
|
|
38
|
+
return id;
|
|
39
|
+
},
|
|
40
|
+
clearTimeout: (handle) => {
|
|
41
|
+
timers.delete(handle);
|
|
42
|
+
},
|
|
43
|
+
advance,
|
|
44
|
+
pending: () => timers.size
|
|
45
|
+
};
|
|
46
|
+
};
|
|
47
|
+
/**
|
|
48
|
+
* Put a definition on a fake clock: the machine starts (so its entry effects are issued before the harness returns) and
|
|
49
|
+
* every delivery, issued effect and cancellation is recorded.
|
|
50
|
+
*/
|
|
51
|
+
function harness(definition, options = {}) {
|
|
52
|
+
const clock = createFakeClock();
|
|
53
|
+
const log = [];
|
|
54
|
+
const entries = /* @__PURE__ */ new Map();
|
|
55
|
+
const pending = [];
|
|
56
|
+
const queue = [];
|
|
57
|
+
const cancelledIds = [];
|
|
58
|
+
const onTransition = (record) => {
|
|
59
|
+
const context = machine.getState().context;
|
|
60
|
+
if (!record.taken) {
|
|
61
|
+
log.push({
|
|
62
|
+
at: record.at,
|
|
63
|
+
event: record.event,
|
|
64
|
+
from: record.from,
|
|
65
|
+
to: void 0,
|
|
66
|
+
effect: void 0,
|
|
67
|
+
context,
|
|
68
|
+
cancelled: record.cancelled
|
|
69
|
+
});
|
|
70
|
+
return;
|
|
71
|
+
}
|
|
72
|
+
if (record.effects.length === 0) {
|
|
73
|
+
log.push({
|
|
74
|
+
at: record.at,
|
|
75
|
+
event: record.event,
|
|
76
|
+
from: record.from,
|
|
77
|
+
to: record.to,
|
|
78
|
+
effect: void 0,
|
|
79
|
+
context,
|
|
80
|
+
cancelled: false
|
|
81
|
+
});
|
|
82
|
+
return;
|
|
83
|
+
}
|
|
84
|
+
for (const id of record.effects) {
|
|
85
|
+
const entry = {
|
|
86
|
+
at: record.at,
|
|
87
|
+
event: record.event,
|
|
88
|
+
from: record.from,
|
|
89
|
+
to: record.to,
|
|
90
|
+
effect: id,
|
|
91
|
+
context,
|
|
92
|
+
cancelled: false
|
|
93
|
+
};
|
|
94
|
+
entries.set(id, entry);
|
|
95
|
+
log.push(entry);
|
|
96
|
+
}
|
|
97
|
+
};
|
|
98
|
+
const machine = createMachine(definition, {
|
|
99
|
+
...options,
|
|
100
|
+
clock,
|
|
101
|
+
autoStart: false,
|
|
102
|
+
onEffect: (handle) => {
|
|
103
|
+
pending.push(handle);
|
|
104
|
+
},
|
|
105
|
+
onCancel: (handle) => {
|
|
106
|
+
cancelledIds.push(handle.id);
|
|
107
|
+
const entry = entries.get(handle.id);
|
|
108
|
+
if (entry !== void 0) entry.cancelled = true;
|
|
109
|
+
},
|
|
110
|
+
onTransition
|
|
111
|
+
});
|
|
112
|
+
machine.start();
|
|
113
|
+
const deliverAll = () => {
|
|
114
|
+
while (queue.length > 0) {
|
|
115
|
+
const event = queue.shift();
|
|
116
|
+
if (event !== void 0) machine.send(event);
|
|
117
|
+
}
|
|
118
|
+
};
|
|
119
|
+
const step = (event) => {
|
|
120
|
+
machine.send(event);
|
|
121
|
+
return machine.getState();
|
|
122
|
+
};
|
|
123
|
+
return {
|
|
124
|
+
machine,
|
|
125
|
+
clock,
|
|
126
|
+
log,
|
|
127
|
+
send: (event, sendOptions) => {
|
|
128
|
+
machine.send(event, sendOptions);
|
|
129
|
+
},
|
|
130
|
+
enqueue: (...events) => {
|
|
131
|
+
queue.push(...events);
|
|
132
|
+
},
|
|
133
|
+
queued: () => [...queue],
|
|
134
|
+
deliver: () => {
|
|
135
|
+
const event = queue.shift();
|
|
136
|
+
if (event !== void 0) machine.send(event);
|
|
137
|
+
},
|
|
138
|
+
deliverAll,
|
|
139
|
+
advance: (ms) => {
|
|
140
|
+
clock.advance(ms);
|
|
141
|
+
},
|
|
142
|
+
pendingEffects: () => {
|
|
143
|
+
const live = new Set(machine.effects().map((handle) => handle.id));
|
|
144
|
+
return pending.filter((handle) => live.has(handle.id));
|
|
145
|
+
},
|
|
146
|
+
flushEffects: () => {
|
|
147
|
+
const live = new Set(machine.effects().map((handle) => handle.id));
|
|
148
|
+
const issued = pending.filter((handle) => live.has(handle.id));
|
|
149
|
+
pending.length = 0;
|
|
150
|
+
return issued;
|
|
151
|
+
},
|
|
152
|
+
race: (...events) => events.map(step),
|
|
153
|
+
interleave: (...sequences) => {
|
|
154
|
+
const states = [];
|
|
155
|
+
const longest = Math.max(0, ...sequences.map((sequence) => sequence.length));
|
|
156
|
+
for (let index = 0; index < longest; index += 1) for (const sequence of sequences) {
|
|
157
|
+
const event = sequence[index];
|
|
158
|
+
if (event !== void 0) states.push(step(event));
|
|
159
|
+
}
|
|
160
|
+
return states;
|
|
161
|
+
},
|
|
162
|
+
cancelled: () => [...cancelledIds]
|
|
163
|
+
};
|
|
164
|
+
}
|
|
165
|
+
// src/index.ts
|
|
166
|
+
/** The host's clock: `Date.now` and the global timers. */
|
|
167
|
+
const systemClock = {
|
|
168
|
+
now: () => Date.now(),
|
|
169
|
+
setTimeout: (callback, ms) => setTimeout(callback, ms),
|
|
170
|
+
clearTimeout: (handle) => clearTimeout(handle)
|
|
171
|
+
};
|
|
172
|
+
const toTransition = (value) => typeof value === "string" ? { target: value } : value;
|
|
173
|
+
const listOf = (value) => Array.isArray(value) ? value.map(toTransition) : [toTransition(value)];
|
|
174
|
+
const effectsOf = (value) => {
|
|
175
|
+
if (value === void 0) return [];
|
|
176
|
+
return Array.isArray(value) ? value : [value];
|
|
177
|
+
};
|
|
178
|
+
const targetsOf = (value) => value === void 0 ? [] : listOf(value).map((transition) => transition.target);
|
|
179
|
+
const build = (config) => {
|
|
180
|
+
const states = config.states;
|
|
181
|
+
const names = Object.keys(states);
|
|
182
|
+
if (names.length === 0) throw new Error("@cssints/machine: a machine needs at least one state");
|
|
183
|
+
const start = config.start ?? names[0];
|
|
184
|
+
if (!Object.hasOwn(states, start)) throw new Error(`@cssints/machine: the start state "${start}" is not a state`);
|
|
185
|
+
const known = new Set(names);
|
|
186
|
+
for (const [name, state] of Object.entries(states)) for (const [kind, map] of [["on", state.on], ["after", state.after]]) for (const [key, value] of Object.entries(map ?? {})) {
|
|
187
|
+
if (kind === "after" && Number.isNaN(Number(key))) throw new Error(`@cssints/machine: ${name}.after.${key} is not a number of ms`);
|
|
188
|
+
for (const target of targetsOf(value)) if (!known.has(target)) throw new Error(`@cssints/machine: ${name}.${kind}.${key} targets "${target}", which is not a state`);
|
|
189
|
+
}
|
|
190
|
+
return {
|
|
191
|
+
initial: config.initial,
|
|
192
|
+
states: config.states,
|
|
193
|
+
start,
|
|
194
|
+
debounce: config.debounce ?? {}
|
|
195
|
+
};
|
|
196
|
+
};
|
|
197
|
+
function defineMachine(...args) {
|
|
198
|
+
if (args.length === 0) return (config) => build(config);
|
|
199
|
+
return build(args[0]);
|
|
200
|
+
}
|
|
201
|
+
const choose = (value, context, event) => {
|
|
202
|
+
if (value === void 0) return;
|
|
203
|
+
for (const transition of listOf(value)) if (transition.guard === void 0 || transition.guard(context, event)) return transition;
|
|
204
|
+
};
|
|
205
|
+
/** The id a completion event carries, if it carries one. */
|
|
206
|
+
const handleIdOf = (event) => {
|
|
207
|
+
const id = event.id;
|
|
208
|
+
return typeof id === "number" ? id : void 0;
|
|
209
|
+
};
|
|
210
|
+
/**
|
|
211
|
+
* Create a machine and start it (unless `autoStart: false`). The start state's effects are issued right away, so a host
|
|
212
|
+
* reads them through `effects()` or an `onEffect` option.
|
|
213
|
+
*/
|
|
214
|
+
function createMachine(definition, options = {}) {
|
|
215
|
+
const states = definition.states;
|
|
216
|
+
const clock = options.clock ?? systemClock;
|
|
217
|
+
const debounceMap = definition.debounce;
|
|
218
|
+
let current = definition.start;
|
|
219
|
+
let context = definition.initial;
|
|
220
|
+
let started = false;
|
|
221
|
+
let destroyed = false;
|
|
222
|
+
let nextId = 1;
|
|
223
|
+
const handles = /* @__PURE__ */ new Map();
|
|
224
|
+
const afterTimers = /* @__PURE__ */ new Set();
|
|
225
|
+
const pending = /* @__PURE__ */ new Map();
|
|
226
|
+
const stateListeners = /* @__PURE__ */ new Set();
|
|
227
|
+
const selectors = /* @__PURE__ */ new Set();
|
|
228
|
+
const effectListeners = /* @__PURE__ */ new Set();
|
|
229
|
+
const cancelListeners = /* @__PURE__ */ new Set();
|
|
230
|
+
const transitionListeners = /* @__PURE__ */ new Set();
|
|
231
|
+
const snapshot = () => ({
|
|
232
|
+
state: current,
|
|
233
|
+
context
|
|
234
|
+
});
|
|
235
|
+
const notify = () => {
|
|
236
|
+
const state = snapshot();
|
|
237
|
+
for (const listener of stateListeners) listener(state);
|
|
238
|
+
for (const entry of selectors) {
|
|
239
|
+
const value = entry.selector(state);
|
|
240
|
+
if (!Object.is(value, entry.value)) {
|
|
241
|
+
const previous = entry.value;
|
|
242
|
+
entry.value = value;
|
|
243
|
+
entry.listener(value, previous);
|
|
244
|
+
}
|
|
245
|
+
}
|
|
246
|
+
};
|
|
247
|
+
const record = (entry) => {
|
|
248
|
+
for (const listener of transitionListeners) listener(entry);
|
|
249
|
+
};
|
|
250
|
+
const announce = (issued) => {
|
|
251
|
+
for (const handle of issued) for (const listener of effectListeners) listener(handle);
|
|
252
|
+
};
|
|
253
|
+
const clearAfter = () => {
|
|
254
|
+
for (const timer of afterTimers) clock.clearTimeout(timer);
|
|
255
|
+
afterTimers.clear();
|
|
256
|
+
};
|
|
257
|
+
const cancelHandles = (except) => {
|
|
258
|
+
for (const handle of handles.values()) {
|
|
259
|
+
if (handle.id === except) continue;
|
|
260
|
+
handles.delete(handle.id);
|
|
261
|
+
for (const listener of cancelListeners) listener(handle);
|
|
262
|
+
}
|
|
263
|
+
if (except !== void 0) handles.delete(except);
|
|
264
|
+
};
|
|
265
|
+
const issue = (specs, state) => {
|
|
266
|
+
const issued = [];
|
|
267
|
+
for (const spec of specs) {
|
|
268
|
+
const handle = {
|
|
269
|
+
id: nextId++,
|
|
270
|
+
type: spec.type,
|
|
271
|
+
spec,
|
|
272
|
+
state
|
|
273
|
+
};
|
|
274
|
+
handles.set(handle.id, handle);
|
|
275
|
+
issued.push(handle);
|
|
276
|
+
}
|
|
277
|
+
return issued;
|
|
278
|
+
};
|
|
279
|
+
const scheduleAfter = (state) => {
|
|
280
|
+
for (const [ms, value] of Object.entries(states[state].after ?? {})) {
|
|
281
|
+
const delay = Number(ms);
|
|
282
|
+
const timer = clock.setTimeout(() => {
|
|
283
|
+
afterTimers.delete(timer);
|
|
284
|
+
const transition = choose(value, context, { type: "after" });
|
|
285
|
+
if (transition !== void 0) take(transition, { type: "after" });
|
|
286
|
+
}, delay);
|
|
287
|
+
afterTimers.add(timer);
|
|
288
|
+
}
|
|
289
|
+
};
|
|
290
|
+
const take = (transition, event, completedId) => {
|
|
291
|
+
const from = current;
|
|
292
|
+
const target = transition.target;
|
|
293
|
+
const assigned = transition.assign === void 0 ? void 0 : typeof transition.assign === "function" ? transition.assign(context, event) : transition.assign;
|
|
294
|
+
const nextContext = assigned === void 0 ? context : {
|
|
295
|
+
...context,
|
|
296
|
+
...assigned
|
|
297
|
+
};
|
|
298
|
+
clearAfter();
|
|
299
|
+
cancelHandles(completedId);
|
|
300
|
+
current = target;
|
|
301
|
+
context = nextContext;
|
|
302
|
+
const issued = [...issue(states[target].effect ?? [], target), ...issue(effectsOf(transition.effect), target)];
|
|
303
|
+
scheduleAfter(target);
|
|
304
|
+
record({
|
|
305
|
+
at: clock.now(),
|
|
306
|
+
event: event.type,
|
|
307
|
+
from,
|
|
308
|
+
to: target,
|
|
309
|
+
taken: true,
|
|
310
|
+
effects: issued.map((handle) => handle.id),
|
|
311
|
+
cancelled: false
|
|
312
|
+
});
|
|
313
|
+
notify();
|
|
314
|
+
announce(issued);
|
|
315
|
+
};
|
|
316
|
+
const deliver = (event) => {
|
|
317
|
+
if (destroyed) return;
|
|
318
|
+
const from = current;
|
|
319
|
+
const id = handleIdOf(event);
|
|
320
|
+
if (id !== void 0 && !handles.has(id)) {
|
|
321
|
+
record({
|
|
322
|
+
at: clock.now(),
|
|
323
|
+
event: event.type,
|
|
324
|
+
from,
|
|
325
|
+
to: from,
|
|
326
|
+
taken: false,
|
|
327
|
+
effects: [],
|
|
328
|
+
cancelled: true
|
|
329
|
+
});
|
|
330
|
+
return;
|
|
331
|
+
}
|
|
332
|
+
const transition = choose(states[from].on?.[event.type], context, event);
|
|
333
|
+
if (transition === void 0) {
|
|
334
|
+
record({
|
|
335
|
+
at: clock.now(),
|
|
336
|
+
event: event.type,
|
|
337
|
+
from,
|
|
338
|
+
to: from,
|
|
339
|
+
taken: false,
|
|
340
|
+
effects: [],
|
|
341
|
+
cancelled: false
|
|
342
|
+
});
|
|
343
|
+
return;
|
|
344
|
+
}
|
|
345
|
+
take(transition, event, id);
|
|
346
|
+
};
|
|
347
|
+
const dropPending = (type) => {
|
|
348
|
+
if (type === void 0) {
|
|
349
|
+
for (const entry of pending.values()) clock.clearTimeout(entry.timer);
|
|
350
|
+
pending.clear();
|
|
351
|
+
return;
|
|
352
|
+
}
|
|
353
|
+
const entry = pending.get(type);
|
|
354
|
+
if (entry !== void 0) {
|
|
355
|
+
clock.clearTimeout(entry.timer);
|
|
356
|
+
pending.delete(type);
|
|
357
|
+
}
|
|
358
|
+
};
|
|
359
|
+
const send = (event, sendOptions) => {
|
|
360
|
+
if (destroyed) return;
|
|
361
|
+
const debounce = sendOptions?.debounce ?? debounceMap[event.type];
|
|
362
|
+
if (debounce === void 0) {
|
|
363
|
+
deliver(event);
|
|
364
|
+
return;
|
|
365
|
+
}
|
|
366
|
+
const type = event.type;
|
|
367
|
+
const previous = pending.get(type);
|
|
368
|
+
if (previous !== void 0) clock.clearTimeout(previous.timer);
|
|
369
|
+
const timer = clock.setTimeout(() => {
|
|
370
|
+
const entry = pending.get(type);
|
|
371
|
+
if (entry === void 0 || entry.timer !== timer) return;
|
|
372
|
+
pending.delete(type);
|
|
373
|
+
deliver(entry.event);
|
|
374
|
+
}, debounce);
|
|
375
|
+
pending.set(type, {
|
|
376
|
+
event,
|
|
377
|
+
timer
|
|
378
|
+
});
|
|
379
|
+
};
|
|
380
|
+
const flush = () => {
|
|
381
|
+
const entries = [...pending.values()];
|
|
382
|
+
pending.clear();
|
|
383
|
+
for (const entry of entries) {
|
|
384
|
+
clock.clearTimeout(entry.timer);
|
|
385
|
+
deliver(entry.event);
|
|
386
|
+
}
|
|
387
|
+
};
|
|
388
|
+
const start = () => {
|
|
389
|
+
if (started || destroyed) return;
|
|
390
|
+
started = true;
|
|
391
|
+
const issued = issue(states[current].effect ?? [], current);
|
|
392
|
+
scheduleAfter(current);
|
|
393
|
+
announce(issued);
|
|
394
|
+
};
|
|
395
|
+
const destroy = () => {
|
|
396
|
+
if (destroyed) return;
|
|
397
|
+
destroyed = true;
|
|
398
|
+
started = false;
|
|
399
|
+
clearAfter();
|
|
400
|
+
dropPending();
|
|
401
|
+
cancelHandles();
|
|
402
|
+
for (const set of [
|
|
403
|
+
stateListeners,
|
|
404
|
+
selectors,
|
|
405
|
+
effectListeners,
|
|
406
|
+
cancelListeners,
|
|
407
|
+
transitionListeners
|
|
408
|
+
]) set.clear();
|
|
409
|
+
};
|
|
410
|
+
const subscribe = ((first, second) => {
|
|
411
|
+
if (second === void 0) {
|
|
412
|
+
stateListeners.add(first);
|
|
413
|
+
return () => {
|
|
414
|
+
stateListeners.delete(first);
|
|
415
|
+
};
|
|
416
|
+
}
|
|
417
|
+
const entry = {
|
|
418
|
+
selector: first,
|
|
419
|
+
listener: second,
|
|
420
|
+
value: first(snapshot())
|
|
421
|
+
};
|
|
422
|
+
selectors.add(entry);
|
|
423
|
+
return () => {
|
|
424
|
+
selectors.delete(entry);
|
|
425
|
+
};
|
|
426
|
+
});
|
|
427
|
+
const onEffect = (listener) => {
|
|
428
|
+
effectListeners.add(listener);
|
|
429
|
+
return () => {
|
|
430
|
+
effectListeners.delete(listener);
|
|
431
|
+
};
|
|
432
|
+
};
|
|
433
|
+
const onCancel = (listener) => {
|
|
434
|
+
cancelListeners.add(listener);
|
|
435
|
+
return () => {
|
|
436
|
+
cancelListeners.delete(listener);
|
|
437
|
+
};
|
|
438
|
+
};
|
|
439
|
+
const onTransition = (listener) => {
|
|
440
|
+
transitionListeners.add(listener);
|
|
441
|
+
return () => {
|
|
442
|
+
transitionListeners.delete(listener);
|
|
443
|
+
};
|
|
444
|
+
};
|
|
445
|
+
if (options.onEffect !== void 0) effectListeners.add(options.onEffect);
|
|
446
|
+
if (options.onCancel !== void 0) cancelListeners.add(options.onCancel);
|
|
447
|
+
if (options.onTransition !== void 0) transitionListeners.add(options.onTransition);
|
|
448
|
+
const machine = {
|
|
449
|
+
getState: snapshot,
|
|
450
|
+
subscribe,
|
|
451
|
+
send,
|
|
452
|
+
flush,
|
|
453
|
+
cancel: (type) => {
|
|
454
|
+
dropPending(type);
|
|
455
|
+
},
|
|
456
|
+
effects: () => [...handles.values()],
|
|
457
|
+
onEffect,
|
|
458
|
+
onCancel,
|
|
459
|
+
onTransition,
|
|
460
|
+
start,
|
|
461
|
+
destroy
|
|
462
|
+
};
|
|
463
|
+
if (options.autoStart !== false) start();
|
|
464
|
+
return machine;
|
|
465
|
+
}
|
|
466
|
+
export { createFakeClock, createMachine, defineMachine, harness, systemClock };
|
package/dist/solid.d.mts
ADDED
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
import { c as Machine, f as MachineState, m as SendOptions, t as BaseEvent } from "./index-C5d0wRMO.mjs";
|
|
2
|
+
import { Store } from "solid-js";
|
|
3
|
+
/** The machine's context plus the state's name, which is the store's shape. */
|
|
4
|
+
export type MachineFields<C extends object, S extends string> = C & {
|
|
5
|
+
phase: S;
|
|
6
|
+
};
|
|
7
|
+
/** What the bridge needs to know about a machine beyond its type: which phases are settled, and where an event leads. */
|
|
8
|
+
export interface MachineStoreOptions<C extends object, S extends string, E extends BaseEvent> {
|
|
9
|
+
/**
|
|
10
|
+
* Whether a phase is settled (the committed logical state). The optimistic lead is taken only from a settled phase,
|
|
11
|
+
* and an in-flight intent reconciles as soon as a transition reaches one. Every phase is settled by default, which
|
|
12
|
+
* makes the optimistic view equal the committed one.
|
|
13
|
+
*/
|
|
14
|
+
readonly settled?: ((phase: S) => boolean) | undefined;
|
|
15
|
+
/**
|
|
16
|
+
* The phase an event's visual state leads to, or `undefined` for no lead (`close` → `closed`, `open` → `open`).
|
|
17
|
+
* Read before the machine transitions; a lead that the machine then does not take is rolled back at once.
|
|
18
|
+
*/
|
|
19
|
+
readonly intent?: ((event: E, state: MachineState<C, S>) => S | undefined) | undefined;
|
|
20
|
+
}
|
|
21
|
+
/** The machine as Solid reads it. */
|
|
22
|
+
export interface MachineStore<C extends object, S extends string, E extends BaseEvent> {
|
|
23
|
+
/** The committed snapshot: `{ ...context, phase }`, one `setStore` per transition, only the changed fields. */
|
|
24
|
+
readonly state: Store<MachineFields<C, S>>;
|
|
25
|
+
/** The visual snapshot: the committed one, plus the current intent's lead while a transition is in flight. */
|
|
26
|
+
readonly optimistic: Store<MachineFields<C, S>>;
|
|
27
|
+
/**
|
|
28
|
+
* A `createProjection` over the committed snapshot (call it in a component body). The draft is the caller's object;
|
|
29
|
+
* only the fields that change notify, so a reader of `view.visible` does not re-run when `progress` changes. A
|
|
30
|
+
* projection reads the committed frame, not an optimistic override (Solid holds it whole), so the visual phase is
|
|
31
|
+
* read off `optimistic` directly.
|
|
32
|
+
*/
|
|
33
|
+
readonly projection: <T extends object>(compute: (draft: T, state: Store<MachineFields<C, S>>) => void, seed: T) => Store<T>;
|
|
34
|
+
/** Send through the store, so an intent gets its optimistic lead. */
|
|
35
|
+
readonly send: (event: E, options?: SendOptions) => void;
|
|
36
|
+
}
|
|
37
|
+
/**
|
|
38
|
+
* Expose a machine as a Solid store. Call it in a component body: the projections it makes belong to the component, and
|
|
39
|
+
* disposing the component unsubscribes it and settles a pending intent.
|
|
40
|
+
*/
|
|
41
|
+
export declare const createMachineStore: <C extends object, S extends string, E extends BaseEvent>(machine: Machine<C, S, E>, options?: MachineStoreOptions<C, NoInfer<S>, NoInfer<E>>) => MachineStore<C, S, E>;
|
package/dist/solid.mjs
ADDED
|
@@ -0,0 +1,80 @@
|
|
|
1
|
+
import { action, createOptimisticStore, createProjection, createStore, getOwner, onCleanup } from "solid-js";
|
|
2
|
+
// src/solid.ts
|
|
3
|
+
const fieldsOf = (state) => ({
|
|
4
|
+
...state.context,
|
|
5
|
+
phase: state.state
|
|
6
|
+
});
|
|
7
|
+
/** Copy `source` onto `draft`, reading every field of a store so the projection tracks each one, writing only changes. */
|
|
8
|
+
const copyInto = (draft, source) => {
|
|
9
|
+
const target = draft;
|
|
10
|
+
const from = source;
|
|
11
|
+
for (const key of Object.keys(from)) {
|
|
12
|
+
const value = from[key];
|
|
13
|
+
if (!Object.is(target[key], value)) target[key] = value;
|
|
14
|
+
}
|
|
15
|
+
for (const key of Object.keys(target)) if (!Object.hasOwn(from, key)) delete target[key];
|
|
16
|
+
};
|
|
17
|
+
/** Write only the fields that changed: a store replaces nothing, so only the readers of a changed field re-run. */
|
|
18
|
+
const writeFields = (setter, next) => {
|
|
19
|
+
setter((draft) => {
|
|
20
|
+
const target = draft;
|
|
21
|
+
const source = next;
|
|
22
|
+
for (const key of Object.keys(source)) if (!Object.is(target[key], source[key])) target[key] = source[key];
|
|
23
|
+
for (const key of Object.keys(target)) if (!Object.hasOwn(source, key)) delete target[key];
|
|
24
|
+
});
|
|
25
|
+
};
|
|
26
|
+
/**
|
|
27
|
+
* Expose a machine as a Solid store. Call it in a component body: the projections it makes belong to the component, and
|
|
28
|
+
* disposing the component unsubscribes it and settles a pending intent.
|
|
29
|
+
*/
|
|
30
|
+
const createMachineStore = (machine, options = {}) => {
|
|
31
|
+
const initial = machine.getState();
|
|
32
|
+
const [state, setState] = createStore(fieldsOf(initial));
|
|
33
|
+
const [optimistic, setOptimistic] = createOptimisticStore((draft) => {
|
|
34
|
+
copyInto(draft, state);
|
|
35
|
+
}, fieldsOf(initial));
|
|
36
|
+
const settled = options.settled ?? (() => true);
|
|
37
|
+
let end;
|
|
38
|
+
const endIntent = () => {
|
|
39
|
+
const resolve = end;
|
|
40
|
+
end = void 0;
|
|
41
|
+
resolve?.();
|
|
42
|
+
};
|
|
43
|
+
const startIntent = (phase) => {
|
|
44
|
+
const gate = new Promise((resolve) => {
|
|
45
|
+
end = resolve;
|
|
46
|
+
});
|
|
47
|
+
action(async function* () {
|
|
48
|
+
setOptimistic((draft) => {
|
|
49
|
+
draft.phase = phase;
|
|
50
|
+
});
|
|
51
|
+
yield gate;
|
|
52
|
+
})();
|
|
53
|
+
};
|
|
54
|
+
const off = machine.subscribe((snapshot) => {
|
|
55
|
+
writeFields(setState, fieldsOf(snapshot));
|
|
56
|
+
if (settled(snapshot.state)) endIntent();
|
|
57
|
+
});
|
|
58
|
+
if (getOwner() !== null) onCleanup(() => {
|
|
59
|
+
endIntent();
|
|
60
|
+
off();
|
|
61
|
+
});
|
|
62
|
+
const send = (event, sendOptions) => {
|
|
63
|
+
const before = machine.getState();
|
|
64
|
+
endIntent();
|
|
65
|
+
const lead = sendOptions?.debounce === void 0 && settled(before.state) && options.intent !== void 0 ? options.intent(event, before) : void 0;
|
|
66
|
+
machine.send(event, sendOptions);
|
|
67
|
+
const after = machine.getState();
|
|
68
|
+
if (lead === void 0 || after.state === before.state || lead === after.state) return;
|
|
69
|
+
startIntent(lead);
|
|
70
|
+
};
|
|
71
|
+
return {
|
|
72
|
+
state,
|
|
73
|
+
optimistic,
|
|
74
|
+
projection: (compute, seed) => createProjection((draft) => {
|
|
75
|
+
compute(draft, state);
|
|
76
|
+
}, seed),
|
|
77
|
+
send
|
|
78
|
+
};
|
|
79
|
+
};
|
|
80
|
+
export { createMachineStore };
|
package/package.json
CHANGED
|
@@ -1,6 +1,41 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@cssints/machine",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.28.0",
|
|
4
|
+
"description": "A minimal, dependency-free, type-safe state machine for UI protocols: effects as data, a stale effect cannot complete, debounce with a flush, an injectable clock and a harness that proves it without a browser",
|
|
5
|
+
"license": "MIT",
|
|
6
|
+
"repository": {
|
|
7
|
+
"type": "git",
|
|
8
|
+
"url": "git+https://github.com/alexeiaccio/css-in-ts-compiler.git",
|
|
9
|
+
"directory": "packages/machine"
|
|
10
|
+
},
|
|
11
|
+
"homepage": "https://cssints.dev",
|
|
12
|
+
"files": [
|
|
13
|
+
"dist"
|
|
14
|
+
],
|
|
15
|
+
"type": "module",
|
|
16
|
+
"sideEffects": false,
|
|
17
|
+
"exports": {
|
|
18
|
+
".": {
|
|
19
|
+
"types": "./dist/index.d.mts",
|
|
20
|
+
"default": "./dist/index.mjs"
|
|
21
|
+
},
|
|
22
|
+
"./solid": {
|
|
23
|
+
"types": "./dist/solid.d.mts",
|
|
24
|
+
"default": "./dist/solid.mjs"
|
|
25
|
+
}
|
|
26
|
+
},
|
|
27
|
+
"peerDependencies": {
|
|
28
|
+
"solid-js": "^2.0.0-rc.13"
|
|
29
|
+
},
|
|
30
|
+
"peerDependenciesMeta": {
|
|
31
|
+
"solid-js": {
|
|
32
|
+
"optional": true
|
|
33
|
+
}
|
|
34
|
+
},
|
|
35
|
+
"engines": {
|
|
36
|
+
"node": ">=22"
|
|
37
|
+
},
|
|
38
|
+
"publishConfig": {
|
|
39
|
+
"access": "public"
|
|
40
|
+
}
|
|
41
|
+
}
|