@spooky-sync/client-solid 0.0.1-canary.355 → 0.0.1-canary.357

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.
@@ -0,0 +1,105 @@
1
+ import { createEffect, createSignal, onCleanup, untrack, useContext } from 'solid-js';
2
+ import type { ChannelPeer, ChannelTableNames, SchemaStructure } from '@spooky-sync/query-builder';
3
+ import type { ChannelQuery, ChannelState, ChannelStatus, Sp00kyChannel } from '@spooky-sync/core';
4
+ import type { SyncedDb } from '..';
5
+ import { Sp00kyContext } from './context';
6
+
7
+ /** Who a channel connects to: a list, or an accessor of one (re-read when it changes). */
8
+ export type ChannelPeers = Iterable<ChannelPeer> | (() => Iterable<ChannelPeer> | null | undefined);
9
+
10
+ /** What a channel carries: the rows a query (or several) matches. */
11
+ export type ChannelQueries<S extends SchemaStructure, T extends ChannelTableNames<S>> =
12
+ | ChannelQuery<S, T>
13
+ | ReadonlyArray<ChannelQuery<S, T>>;
14
+
15
+ /** An open channel, for as long as the component lives. */
16
+ export interface UseChannel<S extends SchemaStructure, T extends string> {
17
+ /** `idle` | `connecting` | `connected` | `failed` | `unsupported`. */
18
+ status: () => ChannelStatus;
19
+ /** Users with a tab connected. */
20
+ peers: () => ReadonlyArray<string>;
21
+ /** Writes that go to THIS channel's peers only (when the row matches its query), plus the database as always. */
22
+ update: Sp00kyChannel<S, T>['update'];
23
+ create: Sp00kyChannel<S, T>['create'];
24
+ delete: Sp00kyChannel<S, T>['delete'];
25
+ }
26
+
27
+ const IDLE: ChannelState = { status: 'idle', peers: [] };
28
+
29
+ /**
30
+ * Open a peer to peer channel to `peers` for the rows `query` matches, for
31
+ * the lifetime of the component. The query must be on a `-- @channel` table
32
+ * and only its `where` counts; it is checked against each row, never
33
+ * registered. Writes to matching rows (`db.update` / `db.create` /
34
+ * `db.delete`, or the channel's own) reach the peers over WebRTC in tens of
35
+ * ms; `-- @ephemeral` fields travel only this way. A connection forms when
36
+ * both sides list each other; your own id is skipped.
37
+ *
38
+ * ```ts
39
+ * const ch = useChannel(
40
+ * () => db.query('message').where({ conversation: convoId() }),
41
+ * () => [me(), other()]
42
+ * );
43
+ * ```
44
+ *
45
+ * `query` may be an accessor (re-read when it changes; `null` closes the
46
+ * channel until it returns a query again) or a list of queries.
47
+ */
48
+ export function useChannel<S extends SchemaStructure, T extends ChannelTableNames<S>>(
49
+ query: ChannelQueries<S, T> | (() => ChannelQueries<S, T> | null | undefined),
50
+ peers: ChannelPeers
51
+ ): UseChannel<S, T> {
52
+ const db = useContext(Sp00kyContext);
53
+ if (!db) throw new Error('useChannel must be used within a <Sp00kyProvider>.');
54
+ const queries = query as ChannelQueries<any, any> | (() => ChannelQueries<any, any> | null | undefined);
55
+ const readQueries = () => (typeof queries === 'function' ? queries() : queries);
56
+ const readPeers = () => (typeof peers === 'function' ? (peers() ?? []) : peers);
57
+ const [state, setState] = createSignal<ChannelState>(IDLE);
58
+
59
+ let channel: Sp00kyChannel<any, any> | null = null;
60
+ let stop = () => {};
61
+ const close = () => {
62
+ stop();
63
+ channel?.close();
64
+ channel = null;
65
+ setState(IDLE);
66
+ };
67
+ const sync = (q: ChannelQueries<any, any> | null | undefined) => {
68
+ if (!q) return close();
69
+ if (channel) return channel.setQueries(q);
70
+ channel = (db as SyncedDb<any>).channel(q, untrack(readPeers));
71
+ stop = channel.subscribe(setState);
72
+ };
73
+ sync(untrack(readQueries));
74
+
75
+ if (typeof queries === 'function') {
76
+ let first = true;
77
+ createEffect(() => {
78
+ const q = queries();
79
+ if (first) return void (first = false);
80
+ sync(q);
81
+ });
82
+ }
83
+ if (typeof peers === 'function') {
84
+ let first = true;
85
+ createEffect(() => {
86
+ const next = [...readPeers()];
87
+ if (first) return void (first = false);
88
+ channel?.setPeers(next);
89
+ });
90
+ }
91
+
92
+ onCleanup(close);
93
+
94
+ const open = () => {
95
+ if (!channel) throw new Error('This channel is closed (its query accessor returned nothing).');
96
+ return channel;
97
+ };
98
+ return {
99
+ status: () => state().status,
100
+ peers: () => state().peers,
101
+ update: ((...args: Parameters<Sp00kyChannel<any, any>['update']>) => open().update(...args)) as UseChannel<S, T>['update'],
102
+ create: ((...args: Parameters<Sp00kyChannel<any, any>['create']>) => open().create(...args)) as UseChannel<S, T>['create'],
103
+ delete: ((...args: Parameters<Sp00kyChannel<any, any>['delete']>) => open().delete(...args)) as UseChannel<S, T>['delete'],
104
+ };
105
+ }