@isoloop/preact 0.1.1 → 0.2.0-next.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/dist/index.d.ts CHANGED
@@ -55,15 +55,18 @@ type UseTopicOptions = {
55
55
  from?: StartPosition;
56
56
  };
57
57
  /**
58
- * The latest value on `topic`. It subscribes on mount and unsubscribes on unmount;
59
- * a different `topic` or `from` subscribes again.
58
+ * The latest value on `topic`. It reads on mount and stops on unmount; a different `topic`
59
+ * or `from` reads again.
60
60
  *
61
- * An isolate has one subscription per topic. A second `useTopic` on the same topic, in
62
- * another component or another call in the same one, replaces the first with no error: only
63
- * the last one subscribed gets records, and the first stops updating. When the last one
64
- * unmounts, the topic has no subscription, and the first doesn't get it back. Call
65
- * `useTopic` once per topic, and pass the value down as props or share it through context.
66
- * With the kernel's `dev: true`, the bus warns in the console when this happens.
61
+ * Any number of components can read the same topic. Every `useTopic` on a topic in one
62
+ * isolate shares one bus subscription: the first to mount subscribes, the last to unmount
63
+ * unsubscribes, and each gets the same latest value, so one that mounts later sees the
64
+ * current value at once. The first one's `from` sets where the shared subscription starts; a
65
+ * later `useTopic` with a different `from` gets the shared value and a console warning.
66
+ *
67
+ * Every record still reaches the isolate, including the ones no render shows. To show the
68
+ * current value per key with only those sent, use `useWatch`; the watchers guide
69
+ * compares the two.
67
70
  *
68
71
  * @param topic - The topic to read. The isolate needs a subscribe grant for it.
69
72
  * @param opts - Where reading starts ({@link UseTopicOptions}).
@@ -87,6 +90,47 @@ export declare function useTopic<Out>(topic: TopicRef<any, Out, any, any>, opts?
87
90
  export declare function usePublish<In>(topic: TopicRef<In, any, any, any>): (value: In, opts?: {
88
91
  key?: string;
89
92
  }) => Promise<void>;
93
+ /** Options for {@link useWatch}: the one key to read. @experimental */
94
+ type UseWatchOptions = {
95
+ /** The key to read; `null` reads the records with no key. */
96
+ key: string | null;
97
+ };
98
+ /**
99
+ * A watcher skips values; use `subscribe` to get every record.
100
+ *
101
+ * The current value per key of `topic`, as a map from key to value. Records with no key
102
+ * share the key `null`. It starts with the newest retained value of each key, then follows
103
+ * the keys that change; when several values arrive for a key between two renders, only the
104
+ * newest is shown. A key leaves the map when retention removes its newest record. Treat the
105
+ * map and its values as read-only.
106
+ *
107
+ * Any number of components can watch the same topic, and one that mounts later shows the
108
+ * current map at once. The bus sends the next view only once the render showing this one
109
+ * has committed, so a component never gets values faster than it draws them.
110
+ *
111
+ * @param topic - The topic to watch. The isolate needs a subscribe grant for it.
112
+ * @returns The current value per key: empty until the first view arrives. A bus restart
113
+ * that lost a memory topic empties it.
114
+ * @throws `Error` outside a component that `defineIsolate` rendered.
115
+ * @experimental
116
+ */
117
+ export declare function useWatch<Out>(topic: TopicRef<any, Out, any, any>): ReadonlyMap<string | null, Out>;
118
+ /**
119
+ * A watcher skips values; use `subscribe` to get every record.
120
+ *
121
+ * The current value of one key of `topic`. It starts with the newest retained value of the
122
+ * key, then follows it; when several values arrive between two renders, only the newest is
123
+ * shown. Treat the value as read-only.
124
+ *
125
+ * @param topic - The topic to watch. The isolate needs a subscribe grant for it.
126
+ * @param opts - The key to read ({@link UseWatchOptions}); `{ key: null }` reads the records
127
+ * with no key.
128
+ * @returns The key's current value, or `undefined` while it has none: before the first view,
129
+ * after retention removed its newest record, or after a bus restart lost a memory topic.
130
+ * @throws `Error` outside a component that `defineIsolate` rendered.
131
+ * @experimental
132
+ */
133
+ export declare function useWatch<Out>(topic: TopicRef<any, Out, any, any>, opts: UseWatchOptions): Out | undefined;
90
134
  /**
91
135
  * A function that sends a request on `topic` and resolves with the first valid reply.
92
136
  * The function is stable while `topic` is the same.
@@ -118,4 +162,4 @@ export declare function useHost(): HostApi$1;
118
162
  * @throws `Error` outside a component that `defineIsolate` rendered.
119
163
  */
120
164
  export declare function useRoute(): RouteValue$1 | undefined;
121
- export { BusError, type HostApi, HostCallError, type IsolateContext, type IsolateProps, type RequestOptions, type RouteValue, type UseTopicOptions };
165
+ export { BusError, type HostApi, HostCallError, type IsolateContext, type IsolateProps, type RequestOptions, type RouteValue, type UseTopicOptions, type UseWatchOptions };
package/dist/index.js CHANGED
@@ -1,6 +1,6 @@
1
1
  import { BusError, HostCallError, REQUIRES } from "@isoloop/runtime";
2
2
  import { Component, createContext, h, options, render } from "preact";
3
- import { useCallback, useContext, useLayoutEffect, useState } from "preact/hooks";
3
+ import { useCallback, useContext, useLayoutEffect, useMemo, useState } from "preact/hooks";
4
4
  import { routeTopic } from "@isoloop/protocol";
5
5
  // src/isolate/context.ts
6
6
  const IsolateCtx = createContext(null);
@@ -124,17 +124,137 @@ function defineIsolate(Component) {
124
124
  }
125
125
  };
126
126
  }
127
+ // src/hooks/shared-topic.ts
128
+ const byBus = /* @__PURE__ */ new WeakMap();
129
+ /** `topic`'s latest value in `bus`'s shared subscription, or `undefined` with no readers yet. */
130
+ function latest(bus, topic) {
131
+ return byBus.get(bus)?.get(topic.name)?.latest;
132
+ }
133
+ /**
134
+ * Adds a reader of `topic`, called after every new value or reset. The first
135
+ * reader subscribes from `from`; a later one with another `from` shares that
136
+ * subscription, and the first such reader gets a console warning. Returns the
137
+ * function that removes the reader; the last one out unsubscribes.
138
+ */
139
+ function addReader(bus, topic, from, notify) {
140
+ const topics = byBus.get(bus) ?? /* @__PURE__ */ new Map();
141
+ byBus.set(bus, topics);
142
+ let e = topics.get(topic.name);
143
+ if (!e) {
144
+ const entry = {
145
+ from,
146
+ latest: void 0,
147
+ readers: /* @__PURE__ */ new Set(),
148
+ unsubscribe: () => {}
149
+ };
150
+ const set = (v) => {
151
+ entry.latest = v;
152
+ for (const r of entry.readers) r.notify();
153
+ };
154
+ entry.unsubscribe = bus.subscribe(topic, (r) => set({ v: r.value }), {
155
+ from,
156
+ onReset: () => set(void 0)
157
+ });
158
+ topics.set(topic.name, e = entry);
159
+ } else if (from !== e.from && !e.warned) {
160
+ e.warned = true;
161
+ console.warn(`[isoloop] useTopic("${topic.name}"): from '${from}' shares from '${e.from}'`);
162
+ }
163
+ const shared = e;
164
+ const reader = { notify };
165
+ shared.readers.add(reader);
166
+ return () => {
167
+ if (!shared.readers.delete(reader) || shared.readers.size > 0) return;
168
+ shared.unsubscribe();
169
+ if (topics.get(topic.name) === shared) topics.delete(topic.name);
170
+ };
171
+ }
172
+ const watchesByBus = /* @__PURE__ */ new WeakMap();
173
+ const entryName = (topic, spec) => spec === void 0 ? `${topic}\u0000*` : `${topic}\u0000${JSON.stringify(spec.key)}`;
174
+ function watchEntry(bus, topic, spec) {
175
+ return watchesByBus.get(bus)?.get(entryName(topic, spec));
176
+ }
177
+ /** Resolves the pending view once every reader has committed it, or none is left. */
178
+ function settleIfCommitted(e) {
179
+ const p = e.pending;
180
+ if (!p) return;
181
+ for (const r of e.readers) if (r.committed < p.gen) return;
182
+ e.pending = void 0;
183
+ p.resolve();
184
+ }
185
+ /** The current view of `topic` for `spec`, or `undefined` before the first one. */
186
+ function watchSnapshot(bus, topic, spec) {
187
+ return watchEntry(bus, topic.name, spec)?.snap;
188
+ }
189
+ /**
190
+ * Adds a reader of `topic` for `spec`, notified after every view. The first
191
+ * reader watches; the last one out unwatches. Returns the function that
192
+ * removes the reader.
193
+ */
194
+ function addWatchReader(bus, topic, spec, reader) {
195
+ const entries = watchesByBus.get(bus) ?? /* @__PURE__ */ new Map();
196
+ watchesByBus.set(bus, entries);
197
+ const name = entryName(topic.name, spec);
198
+ let e = entries.get(name);
199
+ if (!e) {
200
+ const entry = {
201
+ snap: void 0,
202
+ readers: /* @__PURE__ */ new Set(),
203
+ pending: void 0,
204
+ unwatch: () => {}
205
+ };
206
+ entry.unwatch = bus.watch(topic, (view) => {
207
+ entry.snap = {
208
+ gen: (entry.snap?.gen ?? 0) + 1,
209
+ view
210
+ };
211
+ const gen = entry.snap.gen;
212
+ const settled = new Promise((resolve) => {
213
+ entry.pending = {
214
+ gen,
215
+ resolve
216
+ };
217
+ });
218
+ for (const r of entry.readers) r.notify();
219
+ settleIfCommitted(entry);
220
+ return settled;
221
+ }, spec === void 0 ? {} : { keys: [spec.key] });
222
+ entries.set(name, e = entry);
223
+ }
224
+ const shared = e;
225
+ shared.readers.add(reader);
226
+ return () => {
227
+ if (!shared.readers.delete(reader)) return;
228
+ if (shared.readers.size > 0) {
229
+ settleIfCommitted(shared);
230
+ return;
231
+ }
232
+ shared.pending?.resolve();
233
+ shared.pending = void 0;
234
+ shared.unwatch();
235
+ if (entries.get(name) === shared) entries.delete(name);
236
+ };
237
+ }
238
+ /** A reader committed a render showing `gen`: the pending view may now be settled. */
239
+ function commitWatch(bus, topic, spec, reader, gen) {
240
+ reader.committed = Math.max(reader.committed, gen);
241
+ const e = watchEntry(bus, topic.name, spec);
242
+ if (e?.readers.has(reader)) settleIfCommitted(e);
243
+ }
127
244
  // src/hooks/topic.ts
128
245
  /**
129
- * The latest value on `topic`. It subscribes on mount and unsubscribes on unmount;
130
- * a different `topic` or `from` subscribes again.
246
+ * The latest value on `topic`. It reads on mount and stops on unmount; a different `topic`
247
+ * or `from` reads again.
131
248
  *
132
- * An isolate has one subscription per topic. A second `useTopic` on the same topic, in
133
- * another component or another call in the same one, replaces the first with no error: only
134
- * the last one subscribed gets records, and the first stops updating. When the last one
135
- * unmounts, the topic has no subscription, and the first doesn't get it back. Call
136
- * `useTopic` once per topic, and pass the value down as props or share it through context.
137
- * With the kernel's `dev: true`, the bus warns in the console when this happens.
249
+ * Any number of components can read the same topic. Every `useTopic` on a topic in one
250
+ * isolate shares one bus subscription: the first to mount subscribes, the last to unmount
251
+ * unsubscribes, and each gets the same latest value, so one that mounts later sees the
252
+ * current value at once. The first one's `from` sets where the shared subscription starts; a
253
+ * later `useTopic` with a different `from` gets the shared value and a console warning.
254
+ *
255
+ * Every record still reaches the isolate, including the ones no render shows. To show the
256
+ * current value per key with only those sent, use `useWatch`; the watchers guide
257
+ * compares the two.
138
258
  *
139
259
  * @param topic - The topic to read. The isolate needs a subscribe grant for it.
140
260
  * @param opts - Where reading starts ({@link UseTopicOptions}).
@@ -144,14 +264,12 @@ function defineIsolate(Component) {
144
264
  */
145
265
  function useTopic(topic, opts = {}) {
146
266
  const { bus } = useIsolate();
147
- const [value, setValue] = useState(void 0);
267
+ const [value, setValue] = useState(() => latest(bus, topic));
148
268
  const from = opts.from ?? "latest";
149
269
  useLayoutEffect(() => {
150
- setValue(void 0);
151
- return bus.subscribe(topic, (r) => setValue({ v: r.value }), {
152
- from,
153
- onReset: () => setValue(void 0)
154
- });
270
+ const off = addReader(bus, topic, from, () => setValue(latest(bus, topic)));
271
+ setValue(latest(bus, topic));
272
+ return off;
155
273
  }, [
156
274
  bus,
157
275
  topic.name,
@@ -173,10 +291,40 @@ function useTopic(topic, opts = {}) {
173
291
  */
174
292
  function usePublish(topic) {
175
293
  const { bus } = useIsolate();
176
- return useCallback((value, o = {}) => bus.publish(topic, o.key === void 0 ? { value } : {
177
- key: o.key,
178
- value
179
- }), [bus, topic.name]);
294
+ return useCallback((value, o = {}) => bus.publish(topic, value, o), [bus, topic.name]);
295
+ }
296
+ // src/hooks/watch.ts
297
+ const EMPTY = /* @__PURE__ */ new Map();
298
+ function useWatch(topic, opts) {
299
+ const { bus } = useIsolate();
300
+ const keyed = opts !== void 0;
301
+ const key = opts?.key ?? null;
302
+ const store = useMemo(() => {
303
+ return {
304
+ spec: keyed ? { key } : void 0,
305
+ reader: {
306
+ notify: () => {},
307
+ committed: 0
308
+ }
309
+ };
310
+ }, [
311
+ bus,
312
+ topic.name,
313
+ keyed,
314
+ key
315
+ ]);
316
+ const [snap, setSnap] = useState(() => watchSnapshot(bus, topic, store.spec));
317
+ useLayoutEffect(() => {
318
+ store.reader.notify = () => setSnap(watchSnapshot(bus, topic, store.spec));
319
+ const off = addWatchReader(bus, topic, store.spec, store.reader);
320
+ setSnap(watchSnapshot(bus, topic, store.spec));
321
+ return off;
322
+ }, [store]);
323
+ useLayoutEffect(() => {
324
+ commitWatch(bus, topic, store.spec, store.reader, snap?.gen ?? 0);
325
+ }, [store, snap]);
326
+ const view = snap?.view ?? EMPTY;
327
+ return keyed ? view.get(key) : view;
180
328
  }
181
329
  // src/hooks/request.ts
182
330
  /**
@@ -219,4 +367,4 @@ function useHost() {
219
367
  function useRoute() {
220
368
  return useTopic(routeTopic, { from: "earliest" });
221
369
  }
222
- export { BusError, HostCallError, defineIsolate, useHost, useIsolate, usePortalRoot, usePublish, useRequest, useRoute, useTopic };
370
+ export { BusError, HostCallError, defineIsolate, useHost, useIsolate, usePortalRoot, usePublish, useRequest, useRoute, useTopic, useWatch };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@isoloop/preact",
3
- "version": "0.1.1",
3
+ "version": "0.2.0-next.0",
4
4
  "description": "Preact for Isoloop: run a component as an isolate in a worker, with hooks for the message bus and the host.",
5
5
  "keywords": [
6
6
  "isoloop",
@@ -32,11 +32,11 @@
32
32
  "preact": "^10 || ^11"
33
33
  },
34
34
  "dependencies": {
35
- "@isoloop/protocol": "0.1.1",
36
- "@isoloop/runtime": "0.1.1"
35
+ "@isoloop/protocol": "0.2.0-next.0",
36
+ "@isoloop/runtime": "0.2.0-next.0"
37
37
  },
38
38
  "devDependencies": {
39
- "@isoloop/dom": "0.1.1",
39
+ "@isoloop/dom": "0.2.0-next.0",
40
40
  "preact10": "npm:preact@10.29.8",
41
41
  "preact11": "npm:preact@11.1.1",
42
42
  "typescript": "7.0.2"