@codeinkit/dom-trigger 0.1.0-alpha.0 → 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 CHANGED
@@ -1,5 +1,24 @@
1
1
  # Changelog
2
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
+
3
22
  ## 0.1.0-alpha.0
4
23
 
5
24
  First alpha. The client twin of `@codeinkit/http-trigger`, for `@codeinkit/flows` `^4.0.0-alpha.1`.
package/README.md CHANGED
@@ -127,6 +127,75 @@ trigger.register('booking/submit', [{ type: 'dom', event: 'booking.submit' }], {
127
127
  Several flows may listen to the same event, each of them runs. Registering the same flow twice for one
128
128
  event throws.
129
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
+
130
199
  ## Concurrency
131
200
 
132
201
  What happens to an event that arrives while a run of the same flow for the same event is active:
@@ -146,8 +215,8 @@ are not affected.
146
215
  Every run has its own `AbortController`. Its signal is `ctx.signal` in every action, and flows checks it
147
216
  before every action, so a cancelled flow never continues with its next action.
148
217
 
149
- A run is cancelled when a newer event replaces it (`latest`), when its flow is unregistered, and on
150
- `stop()`. The abort reason is an `Error` named `AbortError` with the code `ABORT_ERR`. A cancelled run
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
151
220
  gets the status `cancelled` at once and never reaches `onError`; whatever its flow still returns is ignored.
152
221
 
153
222
  To stop the work that is already under way, pass the signal on:
@@ -210,9 +279,10 @@ entry, the Node entry, or a test double.
210
279
 
211
280
  | method | |
212
281
  | --- | --- |
213
- | `register(flowId, triggers, { input }?)` | add the dom triggers of a registered flow. Returns its event names |
214
- | `registerModules(modules, { base, registerFlows }?)` | the same for an eager glob, with the flow ids of `flows.registerModules`. Returns `[{ flowId, events }]` |
215
- | `unregister(flowId)` | remove its triggers, abort its runs |
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 |
216
286
  | `start()` | start listening. Returns `stop`. Calling it twice does not subscribe twice |
217
287
  | `stop()` | remove the listeners, abort every run. `start()` works again afterwards |
218
288
  | `isRunning(flowId?, event?)` | is a run active? |
@@ -245,6 +315,8 @@ emit(button, 'booking.sumbit', { slot: 3 }); // type error
245
315
  const off = listen(document, 'booking.created', ({ id }) => navigate(`/bookings/${id}`));
246
316
  ```
247
317
 
318
+ The event map may be a type alias or an `interface`.
319
+
248
320
  Events are `bubbles: true, composed: true, cancelable: true`, so they cross shadow roots. A DomTrigger
249
321
  that handles an event calls `preventDefault()` on it, which is how `emit` knows: it returns `true` when
250
322
  a trigger handled the event and `false` when nobody did (a typo, or a trigger that is not started).
@@ -294,7 +366,7 @@ Importing the package touches no browser global, and nothing happens until you c
294
366
 
295
367
  - `start()` without a document does nothing and returns a no-op teardown.
296
368
  - `emitOnDocument()` and `createDomPort().emit()` return `false` without a document.
297
- - `register` and `registerModules` work anywhere.
369
+ - `register`, `registerModules`, `scope` and `resolveFlowModules` work anywhere.
298
370
 
299
371
  So the same `main` module can run on the server and in the browser.
300
372
 
@@ -310,6 +382,20 @@ If it has to live in a component, return the teardown and it stays correct, `sta
310
382
  useEffect(() => trigger.start(), []);
311
383
  ```
312
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
+
313
399
  ## License
314
400
 
315
401
  MIT
@@ -4,6 +4,17 @@ exports.DomTrigger = void 0;
4
4
  const modules_js_1 = require("./modules.js");
5
5
  const names_js_1 = require("./names.js");
6
6
  const CONCURRENCY = ['drop', 'latest', 'queue', 'parallel'];
7
+ function toMatcher(selector, what) {
8
+ if (typeof selector === 'string')
9
+ return (flowId) => flowId.indexOf(selector) === 0;
10
+ if (typeof selector === 'function')
11
+ return (flowId) => !!selector(flowId);
12
+ if (Array.isArray(selector) && selector.every((id) => typeof id === 'string')) {
13
+ const ids = new Set(selector);
14
+ return (flowId) => ids.has(flowId);
15
+ }
16
+ throw new TypeError(`dom-trigger: ${what} must be a flow id prefix, an array of flow ids or a function`);
17
+ }
7
18
  function abortError(message) {
8
19
  return Object.assign(new Error(message), { name: 'AbortError', code: 'ABORT_ERR' });
9
20
  }
@@ -71,6 +82,10 @@ class DomTrigger {
71
82
  /** active runs by runId */
72
83
  this.runs = new Map();
73
84
  this.statusListeners = new Set();
85
+ /** flows registered with `scoped`, by flow id */
86
+ this.scopedFlows = new Map();
87
+ /** the scopes that are acquired right now */
88
+ this.holds = new Set();
74
89
  /**
75
90
  * start listening: one listener per event type on the target. Returns `stop`.
76
91
  * Without a target (SSR, no document) nothing happens. Calling it twice does not subscribe twice.
@@ -122,46 +137,73 @@ class DomTrigger {
122
137
  this.options = options;
123
138
  this.prefix = (_a = options.prefix) !== null && _a !== void 0 ? _a : names_js_1.DEFAULT_PREFIX;
124
139
  }
125
- /** add the dom triggers of an already registered flow. Returns the event names it now listens to */
140
+ /**
141
+ * add the dom triggers of an already registered flow. Returns the event names it now listens to.
142
+ * With `{ scoped: true }` it only listens while a `scope()` that selects it is held.
143
+ */
126
144
  register(flowId, triggers, opts = {}) {
127
145
  const parsed = parseTriggers(flowId, triggers, opts.input);
128
146
  this.assertNew(flowId, parsed);
129
- return this.add(flowId, parsed, opts.input);
147
+ if (!opts.scoped)
148
+ return this.add(flowId, parsed, opts.input);
149
+ return this.addScoped(flowId, parsed, opts.input, this.holdsOf(flowId));
130
150
  }
131
151
  /**
132
152
  * register the dom triggers of every flow module of an eager glob:
133
153
  * `registerModules(import.meta.glob('./flows/**\/*.ts', { eager: true }), { base: './flows', registerFlows: true })`.
134
154
  * Flow ids are computed exactly like `flows.registerModules` does. Nothing is registered when a module is invalid.
155
+ * `scoped: true` registers all of them as scoped, a selector (prefix, flow ids or predicate) only the flows
156
+ * it selects: those listen only while a `scope()` holds them, and have `scoped: true` in the result.
135
157
  */
136
158
  registerModules(modules, opts = {}) {
159
+ const { scoped } = opts;
160
+ const isScoped = scoped === undefined || typeof scoped === 'boolean' ? () => scoped === true : toMatcher(scoped, 'the scoped option');
137
161
  const seen = new Set();
138
162
  const plan = (0, modules_js_1.resolveFlowModules)(modules, opts.base).map(({ flowId, module }) => {
139
163
  const parsed = parseTriggers(flowId, module.triggers === undefined ? [] : module.triggers, module.input);
140
164
  this.assertNew(flowId, parsed, seen);
141
- return { flowId, parsed, input: parsed.length > 0 ? module.input : undefined };
165
+ return {
166
+ flowId,
167
+ parsed,
168
+ input: parsed.length > 0 ? module.input : undefined,
169
+ // user predicates run here, before anything is registered, so a throwing one registers nothing
170
+ holds: parsed.length > 0 && isScoped(flowId) ? this.holdsOf(flowId) : undefined,
171
+ };
142
172
  });
143
173
  if (opts.registerFlows && typeof this.flows.registerModules === 'function') {
144
174
  this.flows.registerModules(modules, opts.base === undefined ? {} : { base: opts.base });
145
175
  }
146
- return plan.map(({ flowId, parsed, input }) => ({ flowId, events: this.add(flowId, parsed, input) }));
176
+ return plan.map(({ flowId, parsed, input, holds }) => holds ? { flowId, events: this.addScoped(flowId, parsed, input, holds), scoped: true } : { flowId, events: this.add(flowId, parsed, input) });
147
177
  }
148
- /** remove the triggers of a flow, abort its running and queued runs, drop the listeners nobody needs any more */
178
+ /** remove the triggers of a flow (scoped ones too), abort its running and queued runs, drop the listeners nobody needs any more */
149
179
  unregister(flowId) {
150
- for (const [event, list] of [...this.entries]) {
151
- const removed = list.filter((entry) => entry.flowId === flowId);
152
- if (removed.length === 0)
153
- continue;
154
- const kept = list.filter((entry) => entry.flowId !== flowId);
155
- if (kept.length > 0) {
156
- this.entries.set(event, kept);
157
- }
158
- else {
159
- this.entries.delete(event);
160
- if (this.target)
161
- this.target.removeEventListener(this.prefix + event, this.onEvent);
162
- }
163
- removed.forEach((entry) => this.cancelRuns(entry, 'flow unregistered'));
180
+ this.scopedFlows.delete(flowId);
181
+ this.holds.forEach((hold) => hold.held.delete(flowId));
182
+ this.remove((entry) => entry.flowId === flowId, 'flow unregistered');
183
+ }
184
+ /**
185
+ * hold the scoped flows a selector picks: a flow id prefix (`'booking/'`), an array of flow ids, or a predicate.
186
+ * They listen while at least one scope holds them. Returns the release function (idempotent): the last release
187
+ * of a flow removes its listeners and aborts its running and queued runs (status `cancelled`).
188
+ * Flows that are not scoped are never affected. A scoped flow registered later joins the scopes that select it.
189
+ * Works while stopped too: `start()` attaches the scoped flows that are held at that moment.
190
+ */
191
+ scope(selector) {
192
+ const matches = toMatcher(selector, 'the scope selector');
193
+ const hold = { matches, held: new Set() };
194
+ for (const flowId of this.scopedFlows.keys()) {
195
+ if (matches(flowId))
196
+ hold.held.add(flowId);
164
197
  }
198
+ this.holds.add(hold);
199
+ hold.held.forEach((flowId) => this.acquire(flowId));
200
+ return () => {
201
+ if (!this.holds.delete(hold))
202
+ return;
203
+ const held = [...hold.held];
204
+ hold.held.clear();
205
+ held.forEach((flowId) => this.release(flowId));
206
+ };
165
207
  }
166
208
  /** is a run active (running or queued)? Optionally only of one flow, or of one flow's event */
167
209
  isRunning(flowId, event) {
@@ -186,7 +228,8 @@ class DomTrigger {
186
228
  assertNew(flowId, parsed, seen) {
187
229
  for (const { event } of parsed) {
188
230
  const key = `${flowId}\n${event}`;
189
- const registered = (this.entries.get(event) || []).some((entry) => entry.flowId === flowId);
231
+ const scoped = this.scopedFlows.get(flowId);
232
+ const registered = (this.entries.get(event) || []).some((entry) => entry.flowId === flowId) || (!!scoped && scoped.triggers.some((t) => t.event === event));
190
233
  if (registered || (seen && seen.has(key))) {
191
234
  throw new Error(`dom-trigger: flow "${flowId}" already listens to "${event}"`);
192
235
  }
@@ -194,9 +237,67 @@ class DomTrigger {
194
237
  seen.add(key);
195
238
  }
196
239
  }
197
- add(flowId, parsed, input) {
240
+ /** the acquired scopes a scoped flow that is about to be registered joins */
241
+ holdsOf(flowId) {
242
+ return [...this.holds].filter((hold) => hold.matches(flowId));
243
+ }
244
+ addScoped(flowId, parsed, input, holds) {
245
+ if (parsed.length === 0)
246
+ return [];
247
+ let flow = this.scopedFlows.get(flowId);
248
+ if (!flow) {
249
+ flow = { triggers: [], holders: 0 };
250
+ this.scopedFlows.set(flowId, flow);
251
+ // a known scoped flow is already held by every scope that selects it
252
+ for (const hold of holds) {
253
+ if (!this.holds.has(hold) || hold.held.has(flowId))
254
+ continue;
255
+ hold.held.add(flowId);
256
+ flow.holders += 1;
257
+ }
258
+ }
259
+ flow.triggers.push(...parsed.map((p) => ({ ...p, input })));
260
+ if (flow.holders > 0)
261
+ this.add(flowId, parsed, input, true);
262
+ return parsed.map((p) => p.event);
263
+ }
264
+ acquire(flowId) {
265
+ const flow = this.scopedFlows.get(flowId);
266
+ if (!flow)
267
+ return;
268
+ flow.holders += 1;
269
+ if (flow.holders === 1)
270
+ flow.triggers.forEach((t) => this.add(flowId, [t], t.input, true));
271
+ }
272
+ release(flowId) {
273
+ const flow = this.scopedFlows.get(flowId);
274
+ if (!flow)
275
+ return;
276
+ flow.holders -= 1;
277
+ if (flow.holders === 0)
278
+ this.remove((entry) => entry.scoped && entry.flowId === flowId, 'flow scope released');
279
+ }
280
+ /** drop the matching entries, the listeners nobody needs any more, and abort their runs */
281
+ remove(match, message) {
282
+ for (const [event, list] of [...this.entries]) {
283
+ const removed = list.filter(match);
284
+ if (removed.length === 0)
285
+ continue;
286
+ const kept = list.filter((entry) => !match(entry));
287
+ if (kept.length > 0) {
288
+ this.entries.set(event, kept);
289
+ }
290
+ else {
291
+ this.entries.delete(event);
292
+ if (this.target)
293
+ this.target.removeEventListener(this.prefix + event, this.onEvent);
294
+ }
295
+ removed.forEach((entry) => this.cancelRuns(entry, message));
296
+ }
297
+ }
298
+ add(flowId, parsed, input, scoped = false) {
198
299
  for (const { event, concurrency } of parsed) {
199
- const entry = { flowId, event, concurrency, input, runs: new Set(), queue: [] };
300
+ const entry = { flowId, event, concurrency, input, scoped, runs: new Set(), queue: [] };
200
301
  const list = this.entries.get(event);
201
302
  if (list) {
202
303
  list.push(entry);
package/dist/cjs/index.js CHANGED
@@ -1,11 +1,13 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.isEventName = exports.DEFAULT_PREFIX = exports.EVENT_NAME_RE = exports.createDomPort = exports.createEmitter = exports.DomTrigger = void 0;
3
+ exports.isEventName = exports.DEFAULT_PREFIX = exports.EVENT_NAME_RE = exports.resolveFlowModules = exports.createDomPort = exports.createEmitter = exports.DomTrigger = void 0;
4
4
  var dom_trigger_js_1 = require("./dom-trigger.js");
5
5
  Object.defineProperty(exports, "DomTrigger", { enumerable: true, get: function () { return dom_trigger_js_1.DomTrigger; } });
6
6
  var emitter_js_1 = require("./emitter.js");
7
7
  Object.defineProperty(exports, "createEmitter", { enumerable: true, get: function () { return emitter_js_1.createEmitter; } });
8
8
  Object.defineProperty(exports, "createDomPort", { enumerable: true, get: function () { return emitter_js_1.createDomPort; } });
9
+ var modules_js_1 = require("./modules.js");
10
+ Object.defineProperty(exports, "resolveFlowModules", { enumerable: true, get: function () { return modules_js_1.resolveFlowModules; } });
9
11
  var names_js_1 = require("./names.js");
10
12
  Object.defineProperty(exports, "EVENT_NAME_RE", { enumerable: true, get: function () { return names_js_1.EVENT_NAME_RE; } });
11
13
  Object.defineProperty(exports, "DEFAULT_PREFIX", { enumerable: true, get: function () { return names_js_1.DEFAULT_PREFIX; } });
@@ -1,6 +1,17 @@
1
1
  import { resolveFlowModules } from './modules.js';
2
2
  import { DEFAULT_PREFIX, assertEventName, getDocument } from './names.js';
3
3
  const CONCURRENCY = ['drop', 'latest', 'queue', 'parallel'];
4
+ function toMatcher(selector, what) {
5
+ if (typeof selector === 'string')
6
+ return (flowId) => flowId.indexOf(selector) === 0;
7
+ if (typeof selector === 'function')
8
+ return (flowId) => !!selector(flowId);
9
+ if (Array.isArray(selector) && selector.every((id) => typeof id === 'string')) {
10
+ const ids = new Set(selector);
11
+ return (flowId) => ids.has(flowId);
12
+ }
13
+ throw new TypeError(`dom-trigger: ${what} must be a flow id prefix, an array of flow ids or a function`);
14
+ }
4
15
  function abortError(message) {
5
16
  return Object.assign(new Error(message), { name: 'AbortError', code: 'ABORT_ERR' });
6
17
  }
@@ -68,6 +79,10 @@ export class DomTrigger {
68
79
  /** active runs by runId */
69
80
  this.runs = new Map();
70
81
  this.statusListeners = new Set();
82
+ /** flows registered with `scoped`, by flow id */
83
+ this.scopedFlows = new Map();
84
+ /** the scopes that are acquired right now */
85
+ this.holds = new Set();
71
86
  /**
72
87
  * start listening: one listener per event type on the target. Returns `stop`.
73
88
  * Without a target (SSR, no document) nothing happens. Calling it twice does not subscribe twice.
@@ -119,46 +134,73 @@ export class DomTrigger {
119
134
  this.options = options;
120
135
  this.prefix = (_a = options.prefix) !== null && _a !== void 0 ? _a : DEFAULT_PREFIX;
121
136
  }
122
- /** add the dom triggers of an already registered flow. Returns the event names it now listens to */
137
+ /**
138
+ * add the dom triggers of an already registered flow. Returns the event names it now listens to.
139
+ * With `{ scoped: true }` it only listens while a `scope()` that selects it is held.
140
+ */
123
141
  register(flowId, triggers, opts = {}) {
124
142
  const parsed = parseTriggers(flowId, triggers, opts.input);
125
143
  this.assertNew(flowId, parsed);
126
- return this.add(flowId, parsed, opts.input);
144
+ if (!opts.scoped)
145
+ return this.add(flowId, parsed, opts.input);
146
+ return this.addScoped(flowId, parsed, opts.input, this.holdsOf(flowId));
127
147
  }
128
148
  /**
129
149
  * register the dom triggers of every flow module of an eager glob:
130
150
  * `registerModules(import.meta.glob('./flows/**\/*.ts', { eager: true }), { base: './flows', registerFlows: true })`.
131
151
  * Flow ids are computed exactly like `flows.registerModules` does. Nothing is registered when a module is invalid.
152
+ * `scoped: true` registers all of them as scoped, a selector (prefix, flow ids or predicate) only the flows
153
+ * it selects: those listen only while a `scope()` holds them, and have `scoped: true` in the result.
132
154
  */
133
155
  registerModules(modules, opts = {}) {
156
+ const { scoped } = opts;
157
+ const isScoped = scoped === undefined || typeof scoped === 'boolean' ? () => scoped === true : toMatcher(scoped, 'the scoped option');
134
158
  const seen = new Set();
135
159
  const plan = resolveFlowModules(modules, opts.base).map(({ flowId, module }) => {
136
160
  const parsed = parseTriggers(flowId, module.triggers === undefined ? [] : module.triggers, module.input);
137
161
  this.assertNew(flowId, parsed, seen);
138
- return { flowId, parsed, input: parsed.length > 0 ? module.input : undefined };
162
+ return {
163
+ flowId,
164
+ parsed,
165
+ input: parsed.length > 0 ? module.input : undefined,
166
+ // user predicates run here, before anything is registered, so a throwing one registers nothing
167
+ holds: parsed.length > 0 && isScoped(flowId) ? this.holdsOf(flowId) : undefined,
168
+ };
139
169
  });
140
170
  if (opts.registerFlows && typeof this.flows.registerModules === 'function') {
141
171
  this.flows.registerModules(modules, opts.base === undefined ? {} : { base: opts.base });
142
172
  }
143
- return plan.map(({ flowId, parsed, input }) => ({ flowId, events: this.add(flowId, parsed, input) }));
173
+ return plan.map(({ flowId, parsed, input, holds }) => holds ? { flowId, events: this.addScoped(flowId, parsed, input, holds), scoped: true } : { flowId, events: this.add(flowId, parsed, input) });
144
174
  }
145
- /** remove the triggers of a flow, abort its running and queued runs, drop the listeners nobody needs any more */
175
+ /** remove the triggers of a flow (scoped ones too), abort its running and queued runs, drop the listeners nobody needs any more */
146
176
  unregister(flowId) {
147
- for (const [event, list] of [...this.entries]) {
148
- const removed = list.filter((entry) => entry.flowId === flowId);
149
- if (removed.length === 0)
150
- continue;
151
- const kept = list.filter((entry) => entry.flowId !== flowId);
152
- if (kept.length > 0) {
153
- this.entries.set(event, kept);
154
- }
155
- else {
156
- this.entries.delete(event);
157
- if (this.target)
158
- this.target.removeEventListener(this.prefix + event, this.onEvent);
159
- }
160
- removed.forEach((entry) => this.cancelRuns(entry, 'flow unregistered'));
177
+ this.scopedFlows.delete(flowId);
178
+ this.holds.forEach((hold) => hold.held.delete(flowId));
179
+ this.remove((entry) => entry.flowId === flowId, 'flow unregistered');
180
+ }
181
+ /**
182
+ * hold the scoped flows a selector picks: a flow id prefix (`'booking/'`), an array of flow ids, or a predicate.
183
+ * They listen while at least one scope holds them. Returns the release function (idempotent): the last release
184
+ * of a flow removes its listeners and aborts its running and queued runs (status `cancelled`).
185
+ * Flows that are not scoped are never affected. A scoped flow registered later joins the scopes that select it.
186
+ * Works while stopped too: `start()` attaches the scoped flows that are held at that moment.
187
+ */
188
+ scope(selector) {
189
+ const matches = toMatcher(selector, 'the scope selector');
190
+ const hold = { matches, held: new Set() };
191
+ for (const flowId of this.scopedFlows.keys()) {
192
+ if (matches(flowId))
193
+ hold.held.add(flowId);
161
194
  }
195
+ this.holds.add(hold);
196
+ hold.held.forEach((flowId) => this.acquire(flowId));
197
+ return () => {
198
+ if (!this.holds.delete(hold))
199
+ return;
200
+ const held = [...hold.held];
201
+ hold.held.clear();
202
+ held.forEach((flowId) => this.release(flowId));
203
+ };
162
204
  }
163
205
  /** is a run active (running or queued)? Optionally only of one flow, or of one flow's event */
164
206
  isRunning(flowId, event) {
@@ -183,7 +225,8 @@ export class DomTrigger {
183
225
  assertNew(flowId, parsed, seen) {
184
226
  for (const { event } of parsed) {
185
227
  const key = `${flowId}\n${event}`;
186
- const registered = (this.entries.get(event) || []).some((entry) => entry.flowId === flowId);
228
+ const scoped = this.scopedFlows.get(flowId);
229
+ const registered = (this.entries.get(event) || []).some((entry) => entry.flowId === flowId) || (!!scoped && scoped.triggers.some((t) => t.event === event));
187
230
  if (registered || (seen && seen.has(key))) {
188
231
  throw new Error(`dom-trigger: flow "${flowId}" already listens to "${event}"`);
189
232
  }
@@ -191,9 +234,67 @@ export class DomTrigger {
191
234
  seen.add(key);
192
235
  }
193
236
  }
194
- add(flowId, parsed, input) {
237
+ /** the acquired scopes a scoped flow that is about to be registered joins */
238
+ holdsOf(flowId) {
239
+ return [...this.holds].filter((hold) => hold.matches(flowId));
240
+ }
241
+ addScoped(flowId, parsed, input, holds) {
242
+ if (parsed.length === 0)
243
+ return [];
244
+ let flow = this.scopedFlows.get(flowId);
245
+ if (!flow) {
246
+ flow = { triggers: [], holders: 0 };
247
+ this.scopedFlows.set(flowId, flow);
248
+ // a known scoped flow is already held by every scope that selects it
249
+ for (const hold of holds) {
250
+ if (!this.holds.has(hold) || hold.held.has(flowId))
251
+ continue;
252
+ hold.held.add(flowId);
253
+ flow.holders += 1;
254
+ }
255
+ }
256
+ flow.triggers.push(...parsed.map((p) => ({ ...p, input })));
257
+ if (flow.holders > 0)
258
+ this.add(flowId, parsed, input, true);
259
+ return parsed.map((p) => p.event);
260
+ }
261
+ acquire(flowId) {
262
+ const flow = this.scopedFlows.get(flowId);
263
+ if (!flow)
264
+ return;
265
+ flow.holders += 1;
266
+ if (flow.holders === 1)
267
+ flow.triggers.forEach((t) => this.add(flowId, [t], t.input, true));
268
+ }
269
+ release(flowId) {
270
+ const flow = this.scopedFlows.get(flowId);
271
+ if (!flow)
272
+ return;
273
+ flow.holders -= 1;
274
+ if (flow.holders === 0)
275
+ this.remove((entry) => entry.scoped && entry.flowId === flowId, 'flow scope released');
276
+ }
277
+ /** drop the matching entries, the listeners nobody needs any more, and abort their runs */
278
+ remove(match, message) {
279
+ for (const [event, list] of [...this.entries]) {
280
+ const removed = list.filter(match);
281
+ if (removed.length === 0)
282
+ continue;
283
+ const kept = list.filter((entry) => !match(entry));
284
+ if (kept.length > 0) {
285
+ this.entries.set(event, kept);
286
+ }
287
+ else {
288
+ this.entries.delete(event);
289
+ if (this.target)
290
+ this.target.removeEventListener(this.prefix + event, this.onEvent);
291
+ }
292
+ removed.forEach((entry) => this.cancelRuns(entry, message));
293
+ }
294
+ }
295
+ add(flowId, parsed, input, scoped = false) {
195
296
  for (const { event, concurrency } of parsed) {
196
- const entry = { flowId, event, concurrency, input, runs: new Set(), queue: [] };
297
+ const entry = { flowId, event, concurrency, input, scoped, runs: new Set(), queue: [] };
197
298
  const list = this.entries.get(event);
198
299
  if (list) {
199
300
  list.push(entry);
package/dist/esm/index.js CHANGED
@@ -1,3 +1,4 @@
1
1
  export { DomTrigger } from './dom-trigger.js';
2
2
  export { createEmitter, createDomPort } from './emitter.js';
3
+ export { resolveFlowModules } from './modules.js';
3
4
  export { EVENT_NAME_RE, DEFAULT_PREFIX, isEventName } from './names.js';
@@ -1,4 +1,4 @@
1
- import type { DomTriggerOptions, FlowsLike, RegisterModulesOptions, RegisterOptions, RunStatus, TriggerDef } from './types.js';
1
+ import type { DomTriggerOptions, FlowSelector, FlowsLike, RegisterModulesOptions, RegisterOptions, RunStatus, TriggerDef } from './types.js';
2
2
  export declare class DomTrigger {
3
3
  private readonly flows;
4
4
  private readonly options;
@@ -8,23 +8,41 @@ export declare class DomTrigger {
8
8
  /** active runs by runId */
9
9
  private readonly runs;
10
10
  private readonly statusListeners;
11
+ /** flows registered with `scoped`, by flow id */
12
+ private readonly scopedFlows;
13
+ /** the scopes that are acquired right now */
14
+ private readonly holds;
11
15
  /** set while started */
12
16
  private target;
13
17
  private listeners;
14
18
  constructor(flows: FlowsLike, options?: DomTriggerOptions);
15
- /** add the dom triggers of an already registered flow. Returns the event names it now listens to */
19
+ /**
20
+ * add the dom triggers of an already registered flow. Returns the event names it now listens to.
21
+ * With `{ scoped: true }` it only listens while a `scope()` that selects it is held.
22
+ */
16
23
  register(flowId: string, triggers: ReadonlyArray<TriggerDef | unknown>, opts?: RegisterOptions): string[];
17
24
  /**
18
25
  * register the dom triggers of every flow module of an eager glob:
19
26
  * `registerModules(import.meta.glob('./flows/**\/*.ts', { eager: true }), { base: './flows', registerFlows: true })`.
20
27
  * Flow ids are computed exactly like `flows.registerModules` does. Nothing is registered when a module is invalid.
28
+ * `scoped: true` registers all of them as scoped, a selector (prefix, flow ids or predicate) only the flows
29
+ * it selects: those listen only while a `scope()` holds them, and have `scoped: true` in the result.
21
30
  */
22
31
  registerModules(modules: Record<string, unknown>, opts?: RegisterModulesOptions): Array<{
23
32
  flowId: string;
24
33
  events: string[];
34
+ scoped?: boolean;
25
35
  }>;
26
- /** remove the triggers of a flow, abort its running and queued runs, drop the listeners nobody needs any more */
36
+ /** remove the triggers of a flow (scoped ones too), abort its running and queued runs, drop the listeners nobody needs any more */
27
37
  unregister(flowId: string): void;
38
+ /**
39
+ * hold the scoped flows a selector picks: a flow id prefix (`'booking/'`), an array of flow ids, or a predicate.
40
+ * They listen while at least one scope holds them. Returns the release function (idempotent): the last release
41
+ * of a flow removes its listeners and aborts its running and queued runs (status `cancelled`).
42
+ * Flows that are not scoped are never affected. A scoped flow registered later joins the scopes that select it.
43
+ * Works while stopped too: `start()` attaches the scoped flows that are held at that moment.
44
+ */
45
+ scope(selector: FlowSelector): () => void;
28
46
  /**
29
47
  * start listening: one listener per event type on the target. Returns `stop`.
30
48
  * Without a target (SSR, no document) nothing happens. Calling it twice does not subscribe twice.
@@ -39,6 +57,13 @@ export declare class DomTrigger {
39
57
  /** subscribe to the status of every run. Returns the unsubscribe function */
40
58
  onStatus(listener: (status: RunStatus) => void): () => void;
41
59
  private assertNew;
60
+ /** the acquired scopes a scoped flow that is about to be registered joins */
61
+ private holdsOf;
62
+ private addScoped;
63
+ private acquire;
64
+ private release;
65
+ /** drop the matching entries, the listeners nobody needs any more, and abort their runs */
66
+ private remove;
42
67
  private add;
43
68
  private listen;
44
69
  private readonly onEvent;
@@ -1,5 +1,5 @@
1
- import type { EventMap } from './types.js';
2
- export interface Emitter<M extends EventMap> {
1
+ import type { EventMap, EventMapLike } from './types.js';
2
+ export interface Emitter<M extends EventMapLike> {
3
3
  /** dispatch `prefix + name` on `target`, bubbling up to the document. True when a DomTrigger handled it */
4
4
  emit<K extends keyof M & string>(target: EventTarget, name: K, detail: M[K]): boolean;
5
5
  /** same on the document. False, without throwing, when there is no document (SSR) */
@@ -7,10 +7,10 @@ export interface Emitter<M extends EventMap> {
7
7
  /** listen to an announcement on `target`. Returns the teardown */
8
8
  listen<K extends keyof M & string>(target: EventTarget, name: K, fn: (detail: M[K], event: CustomEvent<M[K]>) => void): () => void;
9
9
  }
10
- export declare function createEmitter<M extends EventMap = EventMap>(opts?: {
10
+ export declare function createEmitter<M extends EventMapLike = EventMap>(opts?: {
11
11
  prefix?: string;
12
12
  }): Emitter<M>;
13
- export interface DomPort<M extends EventMap> {
13
+ export interface DomPort<M extends EventMapLike> {
14
14
  emit<K extends keyof M & string>(name: K, detail: M[K]): boolean;
15
15
  }
16
16
  /**
@@ -18,7 +18,7 @@ export interface DomPort<M extends EventMap> {
18
18
  * happened: `unsafe.dom.emit('booking.created', { id })`. Dispatches on `target` (default: the
19
19
  * document, resolved on every emit). The target lives in the closure, so freezing the port is safe.
20
20
  */
21
- export declare function createDomPort<M extends EventMap = EventMap>(opts?: {
21
+ export declare function createDomPort<M extends EventMapLike = EventMap>(opts?: {
22
22
  target?: EventTarget;
23
23
  prefix?: string;
24
24
  }): DomPort<M>;
@@ -1,5 +1,7 @@
1
1
  export { DomTrigger } from './dom-trigger.js';
2
2
  export { createEmitter, createDomPort } from './emitter.js';
3
3
  export type { Emitter, DomPort } from './emitter.js';
4
+ export { resolveFlowModules } from './modules.js';
5
+ export type { ResolvedFlowModule } from './modules.js';
4
6
  export { EVENT_NAME_RE, DEFAULT_PREFIX, isEventName } from './names.js';
5
- export type { Concurrency, DomEventMap, DomTriggerData, DomTriggerOptions, EventMap, ExecuteOptions, FlowsLike, RegisterModulesOptions, RegisterOptions, RunInfo, RunStatus, RunStatusName, SchemaLike, TriggerDef, } from './types.js';
7
+ export type { Concurrency, DomEventMap, DomTriggerData, DomTriggerOptions, EventMap, EventMapLike, ExecuteOptions, FlowSelector, FlowsLike, RegisterModulesOptions, RegisterOptions, RunInfo, RunStatus, RunStatusName, SchemaLike, TriggerDef, } from './types.js';
@@ -68,17 +68,28 @@ export interface DomTriggerOptions {
68
68
  /** default: `crypto.randomUUID()` when available */
69
69
  runId?: () => string;
70
70
  }
71
+ /** picks flows: a flow id prefix (`'booking/'`), an array of flow ids, or a predicate */
72
+ export type FlowSelector = string | ReadonlyArray<string> | ((flowId: string) => boolean);
71
73
  export interface RegisterOptions {
72
74
  /** validates (and may transform) the event's `detail` before the flow runs */
73
75
  input?: SchemaLike;
76
+ /** only listen while a `trigger.scope(selector)` that selects this flow is held. Default `false` */
77
+ scoped?: boolean;
74
78
  }
75
79
  export interface RegisterModulesOptions {
76
80
  /** directory prefix removed from every key, e.g. './flows'. Default: the longest directory common to all keys */
77
81
  base?: string;
78
82
  /** also call `flows.registerModules(modules, { base })` */
79
83
  registerFlows?: boolean;
84
+ /**
85
+ * `true`: every flow of the glob only listens while a `trigger.scope(selector)` holds it.
86
+ * A selector: only the flows it selects are scoped, the others listen as usual. Default `false`
87
+ */
88
+ scoped?: boolean | FlowSelector;
80
89
  }
81
90
  export type EventMap = Record<string, unknown>;
91
+ /** an event map as a type alias or as an interface (an interface has no index signature, so it is not an `EventMap`) */
92
+ export type EventMapLike = object;
82
93
  /**
83
94
  * DOM event types of an event map, to augment `DocumentEventMap`:
84
95
  * `declare global { interface DocumentEventMap extends DomEventMap<AppEvents> {} }`
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@codeinkit/dom-trigger",
3
- "version": "0.1.0-alpha.0",
3
+ "version": "0.2.0-alpha.0",
4
4
  "description": "DOM CustomEvent trigger for @codeinkit/flows: run UI flows from `flows:domain.verb` events dispatched on the document.",
5
5
  "license": "MIT",
6
6
  "author": "codeinkit dev team",