@codeinkit/dom-trigger 0.0.0-stage → 0.2.0-alpha.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/CHANGELOG.md ADDED
@@ -0,0 +1,35 @@
1
+ # Changelog
2
+
3
+ ## 0.2.0-alpha.0
4
+
5
+ Additive, nothing that worked in 0.1.0-alpha.0 changes.
6
+
7
+ - Page-scoped flows: flows that are registered but only listen while a scope holds them.
8
+ - `register(flowId, triggers, { scoped: true })` and `registerModules(modules, { scoped })`, where `scoped` is
9
+ `true` (every flow of the glob) or a selector (only the flows it selects). Scoped flows have `scoped: true`
10
+ in the result of `registerModules`.
11
+ - `trigger.scope(selector)`: the selector is a flow id prefix, an array of flow ids or a predicate. Returns an
12
+ idempotent release function. Scopes are reference-counted per flow; the last release removes the listeners and
13
+ aborts the running and queued runs (status `cancelled`, reason "flow scope released").
14
+ - `stop()` keeps the counts, `start()` attaches only the scoped flows that are held. A scoped flow registered
15
+ while a matching scope is held joins it. `unregister` removes scoped flows too.
16
+ - `resolveFlowModules(modules, base?)` is exported (with the `ResolvedFlowModule` type): the `{ flowId, module }`
17
+ entries of an eager `import.meta.glob` record, the helper `registerModules` already used.
18
+ - `createEmitter`, `createDomPort`, `Emitter` and `DomPort` accept an `interface` as the event map, not only a
19
+ type alias. New type `EventMapLike`; `EventMap` is unchanged.
20
+ - New types: `FlowSelector`, `EventMapLike`, `ResolvedFlowModule`.
21
+
22
+ ## 0.1.0-alpha.0
23
+
24
+ First alpha. The client twin of `@codeinkit/http-trigger`, for `@codeinkit/flows` `^4.0.0-alpha.1`.
25
+
26
+ - `DomTrigger`: one delegated listener per `flows:<domain>.<verb>` event type on the document, runs the
27
+ matching UI flow with an `AbortSignal` and a `runId`.
28
+ - `register`, `registerModules` (same flow ids as `flows.registerModules`, optional `registerFlows`), `unregister`.
29
+ - `start` / `stop` (idempotent, restartable, a no-op without a document), `isRunning`, `getTarget`, `onStatus`.
30
+ - Concurrency per (flow, event): `drop` (default), `latest`, `queue`, `parallel`.
31
+ - Optional `input` schema (`safeParse` or `parse`) validates the event's `detail` before the flow runs.
32
+ - `createEmitter`: typed `emit`, `emitOnDocument` and `listen`.
33
+ - `createDomPort`: a port for flows so UI actions can announce events.
34
+ - `isEventName`, `EVENT_NAME_RE`, `DEFAULT_PREFIX`, and the `DomEventMap` type to augment `DocumentEventMap`.
35
+ - CommonJS and ES module builds, no runtime dependencies, safe to import on the server.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) codeinkit dev team
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,401 @@
1
- # Temporary Holding Version
1
+ # @codeinkit/dom-trigger
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ DOM CustomEvent trigger for [@codeinkit/flows](https://github.com/CodeInKit/flows): components dispatch
4
+ `flows:domain.verb` events, and a UI flow runs.
5
+
6
+ It is the client twin of `@codeinkit/http-trigger`. On the server an HTTP request starts a flow; in the
7
+ browser a DOM event does:
8
+
9
+ ```
10
+ <button> ── dispatches "flows:booking.submit" ──▶ bubbles to document ──▶ DomTrigger ──▶ flows.execute('booking/submit', …)
11
+ ```
12
+
13
+ - Components know nothing about flows. They dispatch an event from their own element and are done.
14
+ - One delegated listener per event type on `document`, however many components there are.
15
+ - Every run gets an `AbortSignal` and a `runId`, so searches can be cancelled and runs can be traced.
16
+ - Framework-agnostic (no React), safe to import on the server, no runtime dependencies.
17
+
18
+ > Alpha. The API may still change before `0.1.0`.
19
+
20
+ ## Install
21
+
22
+ ```sh
23
+ npm i @codeinkit/dom-trigger@next @codeinkit/flows@next
24
+ ```
25
+
26
+ `@codeinkit/flows` `^4.0.0-alpha.1` is a peer dependency.
27
+
28
+ ## Quick start
29
+
30
+ ```ts
31
+ // main.tsx
32
+ import { Flows } from '@codeinkit/flows/core'; // the browser entry
33
+ import { DomTrigger, createDomPort } from '@codeinkit/dom-trigger';
34
+
35
+ const flows = new Flows({ ports: { dom: createDomPort(), api } });
36
+ const trigger = new DomTrigger(flows);
37
+
38
+ // registers the flows and their dom triggers in one go
39
+ trigger.registerModules(import.meta.glob('./flows/**/*.ts', { eager: true }), {
40
+ base: './flows',
41
+ registerFlows: true,
42
+ });
43
+
44
+ const stop = trigger.start();
45
+
46
+ import.meta.hot?.dispose(stop); // HMR: no listener of the old module is left behind
47
+ ```
48
+
49
+ ```ts
50
+ // flows/booking/submit.ts -> flow id "booking/submit"
51
+ import { z } from 'zod';
52
+
53
+ export const triggers = [{ type: 'dom', event: 'booking.submit' }];
54
+
55
+ export const input = z.object({ slot: z.number() }); // optional, validates event.detail
56
+
57
+ export default [
58
+ async (data, unsafe, ctx) => {
59
+ const booking = await unsafe.api.createBooking(data.detail, { signal: ctx.signal });
60
+ return { booking };
61
+ },
62
+ (data, unsafe) => {
63
+ unsafe.dom.emit('booking.created', { id: data.booking.id });
64
+ return {};
65
+ },
66
+ ];
67
+ ```
68
+
69
+ ```tsx
70
+ // any component, any framework
71
+ import { emit } from './events';
72
+
73
+ <button onClick={(e) => emit(e.currentTarget, 'booking.submit', { slot: 3 })}>Book</button>;
74
+ ```
75
+
76
+ ## Event naming
77
+
78
+ The contract between components and flows is the event name:
79
+
80
+ - A name is `domain.verb`: lowercase segments (`a-z`, `0-9`, `-`, starting with a letter) separated by dots,
81
+ at least two of them. `booking.submit`, `search-box.query` and `booking.slot.pick` are valid;
82
+ `submit` and `Booking.Submit` are not. `isEventName(name)` and `EVENT_NAME_RE` check it.
83
+ - The DOM event type is the prefix plus the name: `flows:booking.submit`. The prefix is an option (default `'flows:'`).
84
+ - Invalid names throw when a trigger is registered and when an event is emitted.
85
+ - By convention (not validated), **commands** are in the present tense and ask for something
86
+ (`booking.submit`), and **announcements** are in the past tense and say that something happened
87
+ (`booking.created`). Components dispatch commands; flows dispatch announcements.
88
+
89
+ ## Flow files
90
+
91
+ A flow module exports its actions as `default`, and optionally `triggers` and `input`, the same shape
92
+ the http trigger reads:
93
+
94
+ ```ts
95
+ export const triggers = [
96
+ { type: 'http', method: 'post', path: '/search' }, // ignored by DomTrigger
97
+ { type: 'dom', event: 'search.query', concurrency: 'latest' },
98
+ ];
99
+ export const input = schema; // anything with safeParse(v) => { success, data?, error? }, or with parse(v)
100
+ export default [/* actions */];
101
+ ```
102
+
103
+ The first action receives:
104
+
105
+ ```ts
106
+ {
107
+ event: 'search.query',
108
+ detail: /* event.detail, or the parsed data of `input` */,
109
+ runId: '…',
110
+ source: { flowId: 'search/query', route: '/rooms' }, // route: location.pathname
111
+ }
112
+ ```
113
+
114
+ `detail` must be JSON-serializable, flows clones it between actions. There are no DOM nodes in the data;
115
+ when something outside of the flow needs the element, `trigger.getTarget(runId)` returns the event's
116
+ original target while the run is active.
117
+
118
+ When `input` fails, the flow does not run: the status is `invalid` and `onError` is called.
119
+
120
+ Without a glob, register by hand:
121
+
122
+ ```ts
123
+ flows.register('booking/submit', actions);
124
+ trigger.register('booking/submit', [{ type: 'dom', event: 'booking.submit' }], { input: schema });
125
+ ```
126
+
127
+ Several flows may listen to the same event, each of them runs. Registering the same flow twice for one
128
+ event throws.
129
+
130
+ ## Page-scoped flows
131
+
132
+ Some flows should listen only while their page is mounted. Register them as *scoped*: the trigger knows
133
+ them, but they do not listen until somebody holds a scope that selects them.
134
+
135
+ ```ts
136
+ // main.tsx: flows under booking/ are scoped, every other flow listens from start() on
137
+ trigger.registerModules(import.meta.glob('./flows/**/*.ts', { eager: true }), {
138
+ base: './flows',
139
+ registerFlows: true,
140
+ scoped: 'booking/', // true (all of them) | a flow id prefix | an array of flow ids | (flowId) => boolean
141
+ });
142
+ trigger.start();
143
+ ```
144
+
145
+ ```ts
146
+ // when the booking page mounts
147
+ const release = trigger.scope('booking/'); // a flow id prefix | an array of flow ids | (flowId) => boolean
148
+
149
+ // when it unmounts
150
+ release();
151
+ ```
152
+
153
+ - `scope(selector)` only ever touches scoped flows. A flow that is not scoped listens from `start()`
154
+ to `stop()` whatever scopes come and go.
155
+ - Scopes are counted per flow. With two overlapping holders (two components, or StrictMode's mount,
156
+ unmount, mount) the listeners stay until the last one releases. The selectors do not have to be equal:
157
+ `scope('booking/')` and `scope(['booking/submit'])` both hold `booking/submit`.
158
+ - The last release removes the listeners of those flows and aborts their running and queued runs:
159
+ status `cancelled`, reason `AbortError` "flow scope released", exactly like `unregister`. The flows
160
+ stay registered and can be acquired again.
161
+ - `release` is idempotent, calling it again does nothing.
162
+ - `stop()` aborts the runs but keeps the counts: `start()` attaches the scoped flows that are held at
163
+ that moment, and only those. Acquiring and releasing while stopped (or before the first `start()`) works.
164
+ - A scoped flow that is registered while a scope that selects it is held (a lazy chunk) joins that scope
165
+ and listens right away.
166
+ - `unregister(flowId)` removes a scoped flow for good, held or not.
167
+ - Concurrency, `input`, `onStatus`, `isRunning` and `getTarget` work as for any other flow.
168
+
169
+ By hand, without a glob:
170
+
171
+ ```ts
172
+ trigger.register('booking/submit', [{ type: 'dom', event: 'booking.submit' }], { input: schema, scoped: true });
173
+ ```
174
+
175
+ In React the whole integration is one effect, see [React StrictMode](#react-strictmode).
176
+
177
+ > `trigger.scope(selector)` is not the `scope` *option* of the constructor, which is the unsafe scope
178
+ > object each run receives.
179
+
180
+ ### `resolveFlowModules`
181
+
182
+ The helper `registerModules` uses to turn an eager `import.meta.glob` record into flow ids is exported,
183
+ for code that needs the same ids (its own grouping, lazy registration, tooling):
184
+
185
+ ```ts
186
+ import { resolveFlowModules } from '@codeinkit/dom-trigger';
187
+
188
+ const entries = resolveFlowModules(import.meta.glob('./flows/**/*.ts', { eager: true }), './flows');
189
+ // [{ flowId: 'booking/submit', module: { default, triggers?, input? } }, …]
190
+
191
+ for (const { flowId, module } of entries) {
192
+ if (Array.isArray(module.triggers)) trigger.register(flowId, module.triggers, { input: module.input, scoped: isPage(flowId) });
193
+ }
194
+ ```
195
+
196
+ It computes the ids exactly like `flows.registerModules` (without `base`: relative to the longest directory
197
+ common to all keys), skips modules without an array `default`, and throws for a lazy (not eager) glob.
198
+
199
+ ## Concurrency
200
+
201
+ What happens to an event that arrives while a run of the same flow for the same event is active:
202
+
203
+ | `concurrency` | behaviour | use for |
204
+ | ------------------ | ---------------------------------------------------------------------- | ----------------------------- |
205
+ | `'drop'` (default) | the new event is ignored, status `dropped` | commands: a double click |
206
+ | `'latest'` | the previous run is aborted (status `cancelled`), the new one starts | searches, autocomplete |
207
+ | `'queue'` | runs one after another, in order | ordered writes |
208
+ | `'parallel'` | every event runs at once | independent work, analytics |
209
+
210
+ Concurrency is per (flow, event) pair: other events of the same flow, and other flows on the same event,
211
+ are not affected.
212
+
213
+ ## Cancellation
214
+
215
+ Every run has its own `AbortController`. Its signal is `ctx.signal` in every action, and flows checks it
216
+ before every action, so a cancelled flow never continues with its next action.
217
+
218
+ A run is cancelled when a newer event replaces it (`latest`), when its flow is unregistered, when the
219
+ last scope of a [scoped flow](#page-scoped-flows) is released, and on `stop()`. The abort reason is an `Error` named `AbortError` with the code `ABORT_ERR`. A cancelled run
220
+ gets the status `cancelled` at once and never reaches `onError`; whatever its flow still returns is ignored.
221
+
222
+ To stop the work that is already under way, pass the signal on:
223
+
224
+ ```ts
225
+ export default [
226
+ async (data, unsafe, ctx) => {
227
+ const res = await fetch(`/api/search?q=${encodeURIComponent(data.detail)}`, { signal: ctx.signal });
228
+ return { results: await res.json() };
229
+ },
230
+ ];
231
+ ```
232
+
233
+ `withTimeout` and `withRetry` of [`@codeinkit/flows-hoa`](https://github.com/amitmtrn/flows-hoa) honour
234
+ `ctx.signal`: the wrapped action gets a signal that aborts on timeout and when the trigger cancels the
235
+ run, and a retry does not start another attempt after an abort.
236
+
237
+ ```ts
238
+ import { withTimeout } from '@codeinkit/flows-hoa';
239
+
240
+ export default [withTimeout(search, { ms: 5000 })];
241
+ ```
242
+
243
+ ## Status
244
+
245
+ `onStatus` tells you about every run, which is all a store needs to show spinners and errors:
246
+
247
+ ```ts
248
+ const unsubscribe = trigger.onStatus(({ status, flowId, event, runId, output, error }) => {
249
+ store.setState((s) => ({ runs: { ...s.runs, [event]: { status, error } } }));
250
+ });
251
+ ```
252
+
253
+ | status | meaning | extra |
254
+ | ----------- | ----------------------------------------------------- | -------- |
255
+ | `running` | the flow started | |
256
+ | `done` | the flow resolved | `output` |
257
+ | `error` | the flow rejected. `onError` is called too | `error` |
258
+ | `cancelled` | the run was aborted (also runs still waiting in a queue) | `error`: the abort reason |
259
+ | `dropped` | ignored because of `concurrency: 'drop'` | |
260
+ | `invalid` | `input` rejected the detail. `onError` is called too | `error` |
261
+
262
+ A listener that throws never breaks the trigger. `trigger.isRunning(flowId?, event?)` answers without a subscription.
263
+
264
+ ## Options
265
+
266
+ ```ts
267
+ new DomTrigger(flows, {
268
+ target, // where to listen. Default: document, resolved in start()
269
+ prefix, // default 'flows:'
270
+ scope, // () => the unsafe scope of each run, default {}. Never put ports here, they belong to new Flows({ ports })
271
+ onError, // (error, { status, flowId, event, runId }) => void, for 'error' and 'invalid'. Default: console.error
272
+ route, // () => string | undefined, default: location.pathname
273
+ runId, // () => string, default: crypto.randomUUID() when available
274
+ });
275
+ ```
276
+
277
+ `flows` is anything with `execute(name, input, scope, { signal, runId })`: the `@codeinkit/flows/core`
278
+ entry, the Node entry, or a test double.
279
+
280
+ | method | |
281
+ | --- | --- |
282
+ | `register(flowId, triggers, { input, scoped }?)` | add the dom triggers of a registered flow. Returns its event names. `scoped: true`: it listens only while a scope holds it |
283
+ | `registerModules(modules, { base, registerFlows, scoped }?)` | the same for an eager glob, with the flow ids of `flows.registerModules`. Returns `[{ flowId, events }]`, with `scoped: true` on the scoped ones. `scoped`: `true` or a selector |
284
+ | `scope(selector)` | hold the scoped flows of a prefix, an array of flow ids or a predicate. Returns the idempotent release function, see [Page-scoped flows](#page-scoped-flows) |
285
+ | `unregister(flowId)` | remove its triggers (scoped ones too), abort its runs |
286
+ | `start()` | start listening. Returns `stop`. Calling it twice does not subscribe twice |
287
+ | `stop()` | remove the listeners, abort every run. `start()` works again afterwards |
288
+ | `isRunning(flowId?, event?)` | is a run active? |
289
+ | `getTarget(runId)` | the event's original target while the run is active, else `null` |
290
+ | `onStatus(listener)` | subscribe to run statuses. Returns the unsubscribe function |
291
+
292
+ ## Dispatching events
293
+
294
+ `createEmitter` is a typed wrapper around `dispatchEvent(new CustomEvent(...))`:
295
+
296
+ ```ts
297
+ // events.ts
298
+ import { createEmitter } from '@codeinkit/dom-trigger';
299
+
300
+ export type AppEvents = {
301
+ 'booking.submit': { slot: number };
302
+ 'booking.created': { id: string };
303
+ 'search.query': string;
304
+ };
305
+
306
+ export const { emit, emitOnDocument, listen } = createEmitter<AppEvents>();
307
+ ```
308
+
309
+ ```ts
310
+ emit(button, 'booking.submit', { slot: 3 }); // from an element, bubbles to the document
311
+ emitOnDocument('search.query', 'sea view'); // when there is no element at hand
312
+ emit(button, 'booking.submit', { slot: '3' }); // type error
313
+ emit(button, 'booking.sumbit', { slot: 3 }); // type error
314
+
315
+ const off = listen(document, 'booking.created', ({ id }) => navigate(`/bookings/${id}`));
316
+ ```
317
+
318
+ The event map may be a type alias or an `interface`.
319
+
320
+ Events are `bubbles: true, composed: true, cancelable: true`, so they cross shadow roots. A DomTrigger
321
+ that handles an event calls `preventDefault()` on it, which is how `emit` knows: it returns `true` when
322
+ a trigger handled the event and `false` when nobody did (a typo, or a trigger that is not started).
323
+
324
+ You do not need the helper. This is the whole protocol:
325
+
326
+ ```ts
327
+ el.dispatchEvent(new CustomEvent('flows:booking.submit', { detail: { slot: 3 }, bubbles: true, composed: true, cancelable: true }));
328
+ ```
329
+
330
+ ### The DomTrigger port
331
+
332
+ Flows announce what happened through a port, so actions stay free of globals:
333
+
334
+ ```ts
335
+ import { createDomPort } from '@codeinkit/dom-trigger';
336
+
337
+ const flows = new Flows({ ports: { dom: createDomPort<AppEvents>() } });
338
+
339
+ // in an action
340
+ unsafe.dom.emit('booking.created', { id: booking.id });
341
+ ```
342
+
343
+ It dispatches on the document (or on `createDomPort({ target })`). Components hear it with `listen`, and
344
+ an announcement is an event like any other, so another flow can have a trigger for it.
345
+
346
+ ### Typing `addEventListener`
347
+
348
+ `DomEventMap` turns an event map into DOM event types, to augment `DocumentEventMap`:
349
+
350
+ ```ts
351
+ import type { DomEventMap } from '@codeinkit/dom-trigger';
352
+ import type { AppEvents } from './events';
353
+
354
+ declare global {
355
+ interface DocumentEventMap extends DomEventMap<AppEvents> {}
356
+ // the same as writing each of them:
357
+ // interface DocumentEventMap { 'flows:booking.created': CustomEvent<{ id: string }> }
358
+ }
359
+
360
+ document.addEventListener('flows:booking.created', (e) => e.detail.id); // typed
361
+ ```
362
+
363
+ ## SSR
364
+
365
+ Importing the package touches no browser global, and nothing happens until you call something:
366
+
367
+ - `start()` without a document does nothing and returns a no-op teardown.
368
+ - `emitOnDocument()` and `createDomPort().emit()` return `false` without a document.
369
+ - `register`, `registerModules`, `scope` and `resolveFlowModules` work anywhere.
370
+
371
+ So the same `main` module can run on the server and in the browser.
372
+
373
+ ## React StrictMode
374
+
375
+ Start the trigger outside of React, once, next to `createRoot` (see the quick start). In development
376
+ StrictMode mounts, unmounts and mounts every component again, and a trigger started in an effect would
377
+ abort its running flows on that first unmount.
378
+
379
+ If it has to live in a component, return the teardown and it stays correct, `start()` works again after `stop()`:
380
+
381
+ ```ts
382
+ useEffect(() => trigger.start(), []);
383
+ ```
384
+
385
+ [Page-scoped flows](#page-scoped-flows) are safe in an effect as they are: scopes are counted and the
386
+ release is idempotent, so a page-level wrapper is three lines.
387
+
388
+ ```tsx
389
+ export function FlowScope({ prefix, children }: { prefix: string; children: ReactNode }) {
390
+ useEffect(() => trigger.scope(prefix), [prefix]);
391
+ return <>{children}</>;
392
+ }
393
+ ```
394
+
395
+ In StrictMode the effect runs, is cleaned up and runs again, synchronously: the scope is released and
396
+ taken again before any event can arrive. A flow that was already running at that moment (only possible
397
+ when no other holder exists) is cancelled by that release, as it would be by a real unmount.
398
+
399
+ ## License
400
+
401
+ MIT