@softwarity/livewire 0.1.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.
@@ -0,0 +1,322 @@
1
+ import { DataSource } from '@angular/cdk/collections';
2
+ import { signal } from '@angular/core';
3
+ import { BehaviorSubject, Observable, Subscription } from 'rxjs';
4
+ import { LiveList } from './live-list';
5
+ import type { CollectionViewer, ListRange } from '@angular/cdk/collections';
6
+ import type { LiveRow, UpdateFrame } from '@softwarity/livewire-protocol';
7
+
8
+ /**
9
+ * How many rows a window holds when the caller does not say.
10
+ *
11
+ * Fixed per screen, never derived from the viewport: a window sized from the
12
+ * rendered range would change with it - 58 rows here, 59 there - and every
13
+ * change is a new question, whose answer republishes, which makes the viewport
14
+ * emit again. That loop freezes the renderer outright. Only the offset moves.
15
+ *
16
+ * The number is a transport budget, not a display choice. Some proxies silently
17
+ * drop a WebSocket frame past ~64 kB and close the connection rather than the
18
+ * frame, leaving the screen empty with no error anywhere. The rule is
19
+ * `rows x bytes-per-row < the ceiling you tested`, and the bytes differ per
20
+ * screen. Measure before raising it: the failure gives no clue at all.
21
+ */
22
+ const DEFAULT_WINDOW = 100;
23
+
24
+ /**
25
+ * How far the offset is rounded.
26
+ *
27
+ * Without it every scrolled pixel is a new question. Rounding means the
28
+ * subscription only moves when the view has genuinely left what it was reading.
29
+ */
30
+ const BLOCK = 50;
31
+
32
+ /**
33
+ * How close the view may come to an edge before the window is moved.
34
+ *
35
+ * The hysteresis is what keeps this from running away: every publication makes
36
+ * the list longer, the viewport recalculates and emits a range, and recentring
37
+ * on each of those re-subscribes - which republishes, which emits again.
38
+ */
39
+ const MARGIN = 10;
40
+
41
+ /**
42
+ * How long a row that just changed stays marked.
43
+ *
44
+ * The `.fresh` styling on the consuming screen should run for exactly this
45
+ * long. Shorter here cuts the animation off mid-way; longer leaves the row
46
+ * plain while it is still marked.
47
+ */
48
+ const FRESH_MS = 1000;
49
+
50
+ /**
51
+ * One live window of a long list, as a CDK data source.
52
+ *
53
+ * The screen watches one thing: the rows around what it is showing. Scroll and
54
+ * the window moves; something changes and the server pushes what that window
55
+ * now holds. There is no page cache and no second question in flight - the
56
+ * window *is* the question, which is what lets a paged list be pushed at all.
57
+ *
58
+ * The array handed to the viewport is the full length the server reports, with
59
+ * a hole wherever the window does not reach. That is what makes the scrollbar
60
+ * tell the truth from the first frame: its height is the whole list, not the
61
+ * part being watched.
62
+ */
63
+ export class LiveWindowDataSource<Row extends LiveRow> extends DataSource<Row | undefined> {
64
+ private readonly published = new BehaviorSubject<(Row | undefined)[]>([]);
65
+ private readonly viewing = new Subscription();
66
+ private readonly stamp = signal(0);
67
+
68
+ /**
69
+ * Bumped on every publication, and meant to be read in the template.
70
+ *
71
+ * Zoneless applications schedule nothing when a row arrives from a socket
72
+ * callback: the table is told its data changed but no pass is ever run, and
73
+ * the screen holds stale rows until something unrelated wakes Angular up. A
74
+ * signal the view reads is how that is said properly - `ApplicationRef.tick()`
75
+ * from the callback is the other way, and it throws when it lands inside a
76
+ * cycle already in progress.
77
+ */
78
+ readonly revision = this.stamp.asReadonly();
79
+
80
+ private list = new LiveList<Row>();
81
+ private watching: Subscription | null = null;
82
+
83
+ /** The rows a patch touched a moment ago - see `fresh`. */
84
+ private readonly recent = new Set<string>();
85
+
86
+ /** Where the current subscription starts. Its length is always `window`. */
87
+ private offset = 0;
88
+
89
+ private open: ((offset: number, limit: number) => Observable<UpdateFrame<Row>>) | null = null;
90
+ private range = { start: 0, end: 0 };
91
+
92
+ constructor(
93
+ private readonly onTotal: (total: number) => void = () => undefined,
94
+ /** Told when a patch cannot be applied, so the caller can ask again. */
95
+ private readonly onDrift: () => void = () => undefined,
96
+ /** Rows per window - see `DEFAULT_WINDOW` for how to choose one. */
97
+ private readonly window: number = DEFAULT_WINDOW,
98
+ ) {
99
+ super();
100
+ }
101
+
102
+ connect(viewer: CollectionViewer): Observable<(Row | undefined)[]> {
103
+ // Kept because a data source is asked for it, but not relied on: inside a
104
+ // `mat-table` the viewer is the table, whose `viewChange` stays silent
105
+ // while the CDK viewport does the scrolling. `track` is what actually
106
+ // reports where the eye is.
107
+ this.viewing.add(viewer.viewChange.subscribe((range) => this.moveTo(range)));
108
+ return this.published;
109
+ }
110
+
111
+ /**
112
+ * Follows a viewport's rendered range.
113
+ *
114
+ * The screen hands this over explicitly because the `CollectionViewer` a
115
+ * table passes to `connect` does not carry it. Without this the window stays
116
+ * where it started and everything below the first screen is a placeholder
117
+ * that never fills.
118
+ */
119
+ track(ranges: Observable<ListRange>): void {
120
+ this.viewing.add(ranges.subscribe((range) => this.moveTo(range)));
121
+ }
122
+
123
+ disconnect(): void {
124
+ this.viewing.unsubscribe();
125
+ this.watching?.unsubscribe();
126
+ }
127
+
128
+ /** How long the list is, as the server last reported it. */
129
+ get length(): number {
130
+ return this.list.total();
131
+ }
132
+
133
+ /**
134
+ * The index the server pointed at, in the whole list rather than in the page.
135
+ *
136
+ * Whatever it means is the screen's business. It survives the window moving,
137
+ * which is the point: a boundary the reader has scrolled away from is still
138
+ * where it was.
139
+ */
140
+ get pivot(): number | null {
141
+ return this.list.pivot();
142
+ }
143
+
144
+ /** Every republication, for a caller waiting on one row rather than on the viewport. */
145
+ get changes(): Observable<(Row | undefined)[]> {
146
+ return this.published.asObservable();
147
+ }
148
+
149
+ /** The row at that index, when the window reaches it. */
150
+ at(index: number): Row | undefined {
151
+ return this.published.value[index];
152
+ }
153
+
154
+ /**
155
+ * Whether this row arrived, or changed, a moment ago.
156
+ *
157
+ * Only patches mark anything: a snapshot is the answer to "what does this
158
+ * window hold", which is what arriving on the screen and what scrolling both
159
+ * ask, and lighting up a whole page every time the window moves says nothing.
160
+ *
161
+ * A patch's `upserted` is exactly the rows whose version changed, so a row
162
+ * that merely shifted because three arrived above it is not marked. The one
163
+ * approximation: for a window part-way down the list, a row pushed into it
164
+ * from just outside is new to this client without being new to the list.
165
+ */
166
+ fresh(id: string | undefined): boolean {
167
+ return id !== undefined && this.recent.has(id);
168
+ }
169
+
170
+ /**
171
+ * Starts again on a new question.
172
+ *
173
+ * A different question has a different answer, and a row kept from the
174
+ * previous one would be an answer to neither.
175
+ */
176
+ reset(open: (offset: number, limit: number) => Observable<UpdateFrame<Row>>): void {
177
+ this.open = open;
178
+ this.range = { start: 0, end: BLOCK };
179
+ this.offset = -1;
180
+ this.list = new LiveList<Row>();
181
+ this.recent.clear();
182
+ this.published.next([]);
183
+ this.follow();
184
+ }
185
+
186
+ /**
187
+ * Makes sure the window covers one row, wherever the viewport currently is.
188
+ *
189
+ * Stepping through a detail panel walks past the edge of what is loaded, and
190
+ * the scroll that follows only reports where it lands - too late for the row
191
+ * the panel is already opening on.
192
+ */
193
+ ensure(index: number): void {
194
+ if (index >= this.offset && index < this.offset + this.window) {
195
+ return;
196
+ }
197
+ // The offset is computed here rather than through `range`: that field is
198
+ // where the viewport is, and writing a made-up position into it means the
199
+ // next real range disagrees, moves the window back, and the two take turns
200
+ // until the renderer gives up.
201
+ //
202
+ // Clamped the way `follow` clamps, and for the same reason: rounding to a
203
+ // block can land beside the very row that was asked for.
204
+ const centred = Math.round((index - this.window / 2) / BLOCK) * BLOCK;
205
+ const wanted = Math.max(0, Math.min(index, Math.max(centred, index - this.window + 1)));
206
+ if (wanted === this.offset) {
207
+ return;
208
+ }
209
+ this.offset = wanted;
210
+ this.subscribe();
211
+ }
212
+
213
+ private moveTo(range: ListRange): void {
214
+ // An empty range says nothing about where the eye is, and taking it at face
215
+ // value moves the window to the top of the list. A viewport emits one every
216
+ // time it is hidden or resized to nothing - which is what opening a drawer
217
+ // over it does, and why the list behind came back blank.
218
+ if (range.end <= range.start) {
219
+ return;
220
+ }
221
+ this.range = range;
222
+ this.follow();
223
+ }
224
+
225
+ /** Moves the window if the view has walked out of what it covers. */
226
+ private follow(): void {
227
+ if (!this.open) {
228
+ return;
229
+ }
230
+ const { start, end } = this.range;
231
+
232
+ // What is left once the rendered rows are covered, and therefore how much
233
+ // of it can be spent as hysteresis on each side. Asking for the full MARGIN
234
+ // regardless leaves a band of rows loaded by nothing: a window barely wider
235
+ // than the viewport cannot both cover it and keep ten rows in hand.
236
+ const spare = Math.max(0, this.window - (end - start));
237
+ const margin = Math.min(MARGIN, Math.floor(spare / 2));
238
+ if (this.offset >= 0 && start >= this.offset + margin && end <= this.offset + this.window - margin) {
239
+ return;
240
+ }
241
+
242
+ // Centred on the view and rounded to a block - then pulled back until it
243
+ // covers the rendered rows. Covering them is the requirement; the block is
244
+ // only a way of not moving on every scrolled pixel, and rounding to one is
245
+ // exactly how a window settles beside the rows it was meant to hold:
246
+ // rendered [90, 120) rounded to [100, 150), leaving 90 to 99 in no window
247
+ // at all - and, the offset being unchanged, leaving them there.
248
+ const middle = (start + end) / 2;
249
+ const centred = Math.round((middle - this.window / 2) / BLOCK) * BLOCK;
250
+ // Never past the first rendered row, never so far back that the last one
251
+ // falls out. When the viewport renders more rows than the window holds
252
+ // there is no such position: the first row wins, which keeps the hole below
253
+ // the fold rather than above it.
254
+ const wanted = Math.max(0, Math.min(start, Math.max(centred, end - this.window)));
255
+ if (wanted === this.offset) {
256
+ return;
257
+ }
258
+ this.offset = wanted;
259
+ this.subscribe();
260
+ }
261
+
262
+ private subscribe(): void {
263
+ if (!this.open) {
264
+ return;
265
+ }
266
+ this.watching?.unsubscribe();
267
+ // A fresh list per subscription: the server answers a new window with a
268
+ // snapshot, and rows from the previous one are at different offsets. The
269
+ // marks go with them - they belonged to the window being left.
270
+ this.list = new LiveList<Row>();
271
+ this.recent.clear();
272
+ this.watching = this.open(this.offset, this.window).subscribe({
273
+ next: (update) => {
274
+ if (!this.list.apply(update)) {
275
+ this.onDrift();
276
+ return;
277
+ }
278
+ if (update.type === 'patch') {
279
+ this.mark(update.upserted.map((row) => row.id));
280
+ }
281
+ this.onTotal(this.list.total());
282
+ this.publish();
283
+ },
284
+ error: (error: unknown) => console.error('[livewire] window failed', error),
285
+ });
286
+ }
287
+
288
+ private mark(ids: string[]): void {
289
+ if (ids.length === 0) {
290
+ return;
291
+ }
292
+ for (const id of ids) {
293
+ this.recent.add(id);
294
+ }
295
+ // One timer per wave, clearing its own ids: a single shared timer would be
296
+ // pushed back by every new arrival, so under a busy feed nothing would ever
297
+ // stop being marked. The repaint is explicit because a zoneless application
298
+ // schedules nothing for a set mutated outside the view.
299
+ setTimeout(() => {
300
+ for (const id of ids) {
301
+ this.recent.delete(id);
302
+ }
303
+ this.stamp.update((count) => count + 1);
304
+ }, FRESH_MS);
305
+ }
306
+
307
+ /**
308
+ * The whole length, holes and all.
309
+ *
310
+ * A new array each time: the viewport compares references to know something
311
+ * changed, and the rows themselves are shared rather than copied.
312
+ */
313
+ private publish(): void {
314
+ const rows = new Array<Row | undefined>(this.list.total());
315
+ const held = this.list.rows();
316
+ for (let index = 0; index < held.length; index += 1) {
317
+ rows[this.offset + index] = held[index];
318
+ }
319
+ this.published.next(rows);
320
+ this.stamp.update((count) => count + 1);
321
+ }
322
+ }
@@ -0,0 +1,215 @@
1
+ import { DOCUMENT } from '@angular/common';
2
+ import { Inject, Injectable, InjectionToken, Optional, signal } from '@angular/core';
3
+ import { Observable, Subject } from 'rxjs';
4
+ import { filter } from 'rxjs/operators';
5
+ import { SUBSCRIBE_EVENT, UNSUBSCRIBE_EVENT, UPDATE_EVENT } from '@softwarity/livewire-protocol';
6
+ import type { Envelope, JsonValue, LiveRow, UpdateFrame } from '@softwarity/livewire-protocol';
7
+
8
+ export interface LivewireConfig {
9
+ /** Where the socket answers. Root-relative, so a gateway can route it. */
10
+ path: string;
11
+
12
+ /** How long a dropped socket waits before trying again. */
13
+ reconnectMs?: number;
14
+
15
+ /**
16
+ * How to open the connection.
17
+ *
18
+ * Absent, a real `WebSocket` against `path` on the page's own host. Supplied,
19
+ * anything of that shape - which is how the in-memory server is dropped in
20
+ * for a demo or a test with no backend at all.
21
+ */
22
+ connect?: () => LivewireSocket;
23
+ }
24
+
25
+ /** The little of a `WebSocket` this client uses. */
26
+ export interface LivewireSocket {
27
+ send(frame: string): void;
28
+ close(code?: number, reason?: string): void;
29
+ onmessage?: ((frame: string) => void) | null;
30
+ onclose?: ((code: number, reason: string) => void) | null;
31
+ onopen?: (() => void) | null;
32
+ }
33
+
34
+ export const LIVEWIRE_CONFIG = new InjectionToken<LivewireConfig>('LIVEWIRE_CONFIG');
35
+
36
+ const DEFAULT_RECONNECT_MS = 3000;
37
+
38
+ /**
39
+ * The one socket, shared by every live list.
40
+ *
41
+ * One connection per tab, not one per screen: one handshake, one place where
42
+ * authorisation happens, one reconnection to get right. Subscriptions are told
43
+ * apart by an id the caller picks, so several lists can be open at once.
44
+ */
45
+ @Injectable({ providedIn: 'root' })
46
+ export class LivewireClient {
47
+ /** Whether the socket is currently carrying anything. */
48
+ readonly live = signal(false);
49
+
50
+ private socket: LivewireSocket | null = null;
51
+
52
+ /** The wait before the next attempt, held so `retry` can cut it short. */
53
+ private retrying: ReturnType<typeof setTimeout> | null = null;
54
+
55
+ /**
56
+ * Everything the socket delivers, for the watchers to filter.
57
+ *
58
+ * A plain Subject between the socket and the screens, and that indirection is
59
+ * the whole point. `rxjs/webSocket` ties the connection to its subscriber
60
+ * count: it closes when the last one leaves and reopens on the next, so a
61
+ * list scrolling out of view took the connection down with it and the next
62
+ * one opened another - nine sockets for one list, each losing the snapshot
63
+ * sent to the one before.
64
+ */
65
+ private readonly incoming = new Subject<Envelope<unknown>>();
66
+
67
+ /**
68
+ * What to re-send when a socket comes back.
69
+ *
70
+ * A reconnected socket knows nothing about what the screens were watching a
71
+ * second ago, and the screens have no reason to find out that it dropped.
72
+ */
73
+ private readonly open = new Map<string, unknown>();
74
+
75
+ constructor(
76
+ @Inject(LIVEWIRE_CONFIG) private readonly config: LivewireConfig,
77
+ @Optional() @Inject(DOCUMENT) private readonly document: Document | null,
78
+ ) {}
79
+
80
+ /**
81
+ * Watches one topic, and keeps watching it across reconnections.
82
+ *
83
+ * The returned stream starts with a snapshot and continues with patches -
84
+ * applying them is `LiveList`'s job. Unsubscribing closes the subscription
85
+ * server-side; the socket itself stays up for the other lists.
86
+ */
87
+ watch<Row extends LiveRow>(id: string, topic: string, query: JsonValue | null): Observable<UpdateFrame<Row>> {
88
+ return new Observable<UpdateFrame<Row>>((subscriber) => {
89
+ this.connect();
90
+ const asked = { id, topic, query: query ?? undefined };
91
+ this.open.set(id, asked);
92
+ this.send(SUBSCRIBE_EVENT, asked);
93
+
94
+ const frames = this.incoming
95
+ .pipe(
96
+ filter((envelope): envelope is Envelope<UpdateFrame<Row>> => {
97
+ return envelope.event === UPDATE_EVENT && (envelope.data as UpdateFrame<Row>)?.id === id;
98
+ }),
99
+ )
100
+ .subscribe((envelope) => subscriber.next(envelope.data));
101
+
102
+ return () => {
103
+ frames.unsubscribe();
104
+ // The socket stays up for the other lists; only this window closes.
105
+ this.open.delete(id);
106
+ this.send(UNSUBSCRIBE_EVENT, { id });
107
+ };
108
+ });
109
+ }
110
+
111
+ /**
112
+ * Asks for a window again, and gets a snapshot back.
113
+ *
114
+ * A gap in the sequence means the two sides disagree about what was sent.
115
+ * Asking again is cheap; carrying on would show a list nobody can trust.
116
+ */
117
+ resync(id: string): void {
118
+ const asked = this.open.get(id);
119
+ if (asked) {
120
+ this.send(SUBSCRIBE_EVENT, asked);
121
+ }
122
+ }
123
+
124
+ /**
125
+ * What a reader can do about it when something looks off.
126
+ *
127
+ * Two situations, one gesture, because from their side they are the same
128
+ * complaint - the screen may not be showing what is true. Down: the
129
+ * reconnection delay is skipped and the socket is opened now. Up: every open
130
+ * window is asked for again, and each answers with a snapshot.
131
+ */
132
+ retry(): void {
133
+ if (this.socket) {
134
+ for (const asked of this.open.values()) {
135
+ this.send(SUBSCRIBE_EVENT, asked);
136
+ }
137
+ return;
138
+ }
139
+ if (this.retrying !== null) {
140
+ clearTimeout(this.retrying);
141
+ this.retrying = null;
142
+ }
143
+ this.connect();
144
+ }
145
+
146
+ /**
147
+ * Opens the one socket, once, and keeps it open.
148
+ *
149
+ * A plain `WebSocket` rather than `rxjs/webSocket`, deliberately - see the
150
+ * note on `incoming`. What this needs is one socket for as long as the tab
151
+ * lives, which is easier to write outright than to talk an operator chain
152
+ * into.
153
+ */
154
+ private connect(): void {
155
+ if (this.socket) {
156
+ return;
157
+ }
158
+ const socket = this.config.connect ? this.config.connect() : this.openWebSocket();
159
+ this.socket = socket;
160
+
161
+ socket.onopen = (): void => {
162
+ this.live.set(true);
163
+ // Whatever the screens were watching, asked for again. A reconnected
164
+ // socket knows nothing about them, and on the first open this is what
165
+ // sends the subscriptions queued before it came up.
166
+ for (const asked of this.open.values()) {
167
+ this.send(SUBSCRIBE_EVENT, asked);
168
+ }
169
+ };
170
+
171
+ socket.onmessage = (frame: string): void => {
172
+ try {
173
+ this.incoming.next(JSON.parse(frame) as Envelope<unknown>);
174
+ } catch (error) {
175
+ console.error('[livewire] unreadable frame', error);
176
+ }
177
+ };
178
+
179
+ // A dropped socket is the normal case, not a fault: a gateway restart, a
180
+ // laptop that slept. Reconnecting is this client's job so no screen has to
181
+ // know it happened.
182
+ socket.onclose = (): void => {
183
+ this.live.set(false);
184
+ this.socket = null;
185
+ this.retrying = setTimeout(() => {
186
+ this.retrying = null;
187
+ this.connect();
188
+ }, this.config.reconnectMs ?? DEFAULT_RECONNECT_MS);
189
+ };
190
+ }
191
+
192
+ private openWebSocket(): LivewireSocket {
193
+ const location = this.document?.location;
194
+ const scheme = location?.protocol === 'https:' ? 'wss:' : 'ws:';
195
+ const native = new WebSocket(`${scheme}//${location?.host ?? ''}${this.config.path}`);
196
+ // Adapted rather than used directly: a `MessageEvent` is the browser's
197
+ // shape, and everything else here - the in-memory server, the tests -
198
+ // speaks in frames.
199
+ const socket: LivewireSocket = {
200
+ send: (frame) => native.send(frame),
201
+ close: (code, reason) => native.close(code, reason),
202
+ };
203
+ native.onopen = () => socket.onopen?.();
204
+ native.onmessage = (event: MessageEvent) => socket.onmessage?.(String(event.data));
205
+ native.onclose = (event: CloseEvent) => socket.onclose?.(event.code, event.reason);
206
+ native.onerror = () => console.error('[livewire] socket error');
207
+ return socket;
208
+ }
209
+
210
+ private send(event: string, data: unknown): void {
211
+ // Anything sent before the socket is up is not queued here: `onopen` sends
212
+ // every open subscription, which is the same set and a shorter path.
213
+ this.socket?.send(JSON.stringify({ event, data }));
214
+ }
215
+ }
@@ -0,0 +1,21 @@
1
+ import { LIVEWIRE_CONFIG } from './livewire.client';
2
+ import type { EnvironmentProviders, Provider } from '@angular/core';
3
+ import type { LivewireConfig } from './livewire.client';
4
+
5
+ /**
6
+ * Wires the one socket into an application.
7
+ *
8
+ * ```ts
9
+ * providers: [provideLivewire({ path: '/my-service/ws' })]
10
+ * ```
11
+ *
12
+ * For a demo or a test with no backend, hand it a connection instead:
13
+ *
14
+ * ```ts
15
+ * const server = new MockServer().register('rows', { windowFor: () => window });
16
+ * provideLivewire({ path: '', connect: () => server.connect() });
17
+ * ```
18
+ */
19
+ export function provideLivewire(config: LivewireConfig): (Provider | EnvironmentProviders)[] {
20
+ return [{ provide: LIVEWIRE_CONFIG, useValue: config }];
21
+ }
@@ -0,0 +1,20 @@
1
+ export { LivewireClient, LIVEWIRE_CONFIG } from './lib/livewire.client';
2
+ export type { LivewireConfig, LivewireSocket } from './lib/livewire.client';
3
+ export { provideLivewire } from './lib/provide-livewire';
4
+ export { LiveList } from './lib/live-list';
5
+ export { LiveTopic, liveLabels } from './lib/live-topic';
6
+ export { LiveWindowDataSource } from './lib/live-window.datasource';
7
+ export { LiveIndicatorComponent } from './lib/live-indicator.component';
8
+
9
+ // The wire contract, re-exported so a screen needs one import for the types its
10
+ // rows are made of.
11
+ export type {
12
+ JsonValue,
13
+ JsonObject,
14
+ LiveRow,
15
+ LiveWindow,
16
+ SnapshotFrame,
17
+ PatchFrame,
18
+ ErrorFrame,
19
+ UpdateFrame,
20
+ } from '@softwarity/livewire-protocol';