@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.
package/README.md ADDED
@@ -0,0 +1,89 @@
1
+ # @softwarity/livewire
2
+
3
+ Live query synchronisation for Angular. A screen subscribes to a query over one
4
+ WebSocket; it gets the answer, then every answer after it.
5
+
6
+ ```ts
7
+ // app.config.ts
8
+ providers: [provideLivewire({ path: '/my-service/ws' })];
9
+ ```
10
+
11
+ ```ts
12
+ @Injectable()
13
+ export class MessagesService {
14
+ private readonly topic = new LiveTopic<MessageRow>(inject(LivewireClient), 'messages');
15
+
16
+ window = (query: object, offset: number, limit: number) => this.topic.window(query, offset, limit);
17
+ resync = () => this.topic.resync();
18
+ }
19
+ ```
20
+
21
+ ```ts
22
+ readonly source = new LiveWindowDataSource<MessageRow>(
23
+ (total) => this.total.set(total),
24
+ () => this.messages.resync(),
25
+ );
26
+ readonly revision = this.source.revision;
27
+
28
+ constructor() {
29
+ effect(() => {
30
+ const query = this.queryOf();
31
+ this.source.reset((offset, limit) => this.messages.window(query, offset, limit));
32
+ });
33
+ effect(() => {
34
+ const viewport = this.viewport();
35
+ if (viewport) this.source.track(viewport.renderedRangeStream);
36
+ });
37
+ }
38
+ ```
39
+
40
+ ```html
41
+ <cdk-virtual-scroll-viewport [attr.data-revision]="revision()" [itemSize]="44">
42
+ <table mat-table [dataSource]="source">…</table>
43
+ </cdk-virtual-scroll-viewport>
44
+
45
+ <lw-live-indicator />
46
+ ```
47
+
48
+ ## Three rules that are not obvious
49
+
50
+ Each of these cost a debugging session in the application this came from.
51
+
52
+ **1. Read `revision()` in the template.** A row arriving from a socket callback
53
+ schedules no change detection at all in a zoneless application, and the screen
54
+ holds stale rows. A signal read in the view is how a push is made to repaint.
55
+ `ApplicationRef.tick()` is the other way, and it throws when it lands inside a
56
+ cycle already in progress.
57
+
58
+ **2. The window size is a constant per screen, never derived from the
59
+ viewport.** Deriving it loops: publish → the viewport re-measures → a new window
60
+ → publish. It is a *transport* budget anyway — some proxies silently drop a
61
+ frame past ~64 kB — so it is `rows × bytes-per-row < the ceiling you tested`.
62
+ Measure before raising it: the failure gives no clue, just an empty screen.
63
+
64
+ **3. Viewport buffers have to fit inside the window**, with room to spare. The
65
+ rendered range is what the window must cover; a viewport rendering nearly as
66
+ many rows as the window holds leaves no hysteresis, and it moves on every
67
+ scrolled pixel.
68
+
69
+ ## No backend yet?
70
+
71
+ `@softwarity/livewire-mock` speaks the same protocol in memory:
72
+
73
+ ```ts
74
+ const server = new MockServer().register('messages', { windowFor: () => ({ rows, total: rows.length }) });
75
+ provideLivewire({ path: '', connect: () => server.connect() });
76
+ ```
77
+
78
+ Same for a demo, and for tests.
79
+
80
+ ## Theming the indicator
81
+
82
+ ```css
83
+ lw-live-indicator {
84
+ --lw-live: #1b7f3b;
85
+ --lw-down: #b26a00;
86
+ }
87
+ ```
88
+
89
+ See [SPEC.md](../protocol/SPEC.md) for the contract this speaks.
package/jest.config.js ADDED
@@ -0,0 +1,11 @@
1
+ module.exports = {
2
+ preset: 'jest-preset-angular',
3
+ testEnvironment: 'jsdom',
4
+ rootDir: '.',
5
+ setupFilesAfterEnv: ['<rootDir>/test/setup.ts'],
6
+ testRegex: '(/test/.*|(\\.|/)(test|spec))\\.tsx?$',
7
+ moduleFileExtensions: ['ts', 'js', 'json', 'mjs'],
8
+ testPathIgnorePatterns: ['/node_modules/', '/dist/', '<rootDir>/test/setup.ts'],
9
+ transformIgnorePatterns: ['node_modules/(?!.*\\.mjs$)'],
10
+ globals: { 'ts-jest': { tsconfig: '<rootDir>/tsconfig.spec.json' } },
11
+ };
@@ -0,0 +1,6 @@
1
+ {
2
+ "$schema": "../../node_modules/ng-packagr/ng-package.schema.json",
3
+ "dest": "dist",
4
+ "lib": { "entryFile": "src/public-api.ts" },
5
+ "allowedNonPeerDependencies": ["@softwarity/livewire-protocol"]
6
+ }
package/package.json ADDED
@@ -0,0 +1,61 @@
1
+ {
2
+ "name": "@softwarity/livewire",
3
+ "version": "0.1.0",
4
+ "description": "Live query synchronisation for Angular: subscribe to a query over one WebSocket, get its answer and every answer after it. Virtual-scroll data source included.",
5
+ "keywords": [
6
+ "angular",
7
+ "websocket",
8
+ "live-query",
9
+ "realtime",
10
+ "signals",
11
+ "virtual-scroll",
12
+ "cdk",
13
+ "livewire"
14
+ ],
15
+ "homepage": "https://github.com/softwarity/livewire#readme",
16
+ "bugs": {
17
+ "url": "https://github.com/softwarity/livewire/issues"
18
+ },
19
+ "repository": {
20
+ "type": "git",
21
+ "url": "git+https://github.com/softwarity/livewire.git",
22
+ "directory": "packages/angular"
23
+ },
24
+ "license": "Apache-2.0",
25
+ "author": "François ACHACHE <francois.achache@gmail.com>",
26
+ "publishConfig": {
27
+ "access": "public"
28
+ },
29
+ "scripts": {
30
+ "build": "rm -rf dist && ng-packagr -p ng-package.json",
31
+ "check": "tsc -p tsconfig.spec.json --noEmit",
32
+ "test": "jest"
33
+ },
34
+ "peerDependencies": {
35
+ "@angular/cdk": ">=18.0.0",
36
+ "@angular/common": ">=18.0.0",
37
+ "@angular/core": ">=18.0.0",
38
+ "rxjs": "^7.5.0"
39
+ },
40
+ "dependencies": {
41
+ "@softwarity/livewire-protocol": "0.1.0",
42
+ "tslib": "^2.6.2"
43
+ },
44
+ "devDependencies": {
45
+ "@angular/cdk": "^19.0.0",
46
+ "@angular/common": "^19.0.0",
47
+ "@angular/compiler": "^19.0.0",
48
+ "@angular/compiler-cli": "^19.0.0",
49
+ "@angular/core": "^19.0.0",
50
+ "@angular/platform-browser": "^19.0.0",
51
+ "@angular/platform-browser-dynamic": "^19.0.0",
52
+ "@types/jest": "^29.5.14",
53
+ "jest": "^29.7.0",
54
+ "jest-preset-angular": "^14.4.2",
55
+ "ng-packagr": "^19.0.0",
56
+ "rxjs": "^7.8.1",
57
+ "typescript": "~5.6.0",
58
+ "zone.js": "^0.15.0",
59
+ "@softwarity/livewire-mock": "0.1.0"
60
+ }
61
+ }
@@ -0,0 +1,118 @@
1
+ import { ChangeDetectionStrategy, Component, computed, inject, signal } from '@angular/core';
2
+ import { LivewireClient } from './livewire.client';
3
+
4
+ /** How long the indicator acknowledges a click before going back to its state. */
5
+ const ACKNOWLEDGE_MS = 700;
6
+
7
+ /**
8
+ * Whether the socket is up, and the one thing to do about it when it is not.
9
+ *
10
+ * That and nothing else - not whether anything is arriving on it, which is a
11
+ * different question and one this would answer badly: a quiet feed at three in
12
+ * the morning is not a fault.
13
+ *
14
+ * Clicking it retries. Down, that opens the socket now instead of waiting out
15
+ * the reconnection delay; up, it asks every open window for a fresh snapshot.
16
+ * It is deliberately not a refresh button on the list: on a live screen a
17
+ * control offering to fetch it again implies that the rest of the time you are
18
+ * looking at something stale.
19
+ *
20
+ * Colours come from CSS custom properties, so a host theme dresses it without
21
+ * this package knowing anything about the theme:
22
+ *
23
+ * ```css
24
+ * lw-live-indicator { --lw-live: #1b7f3b; --lw-down: #b26a00; }
25
+ * ```
26
+ */
27
+ @Component({
28
+ selector: 'lw-live-indicator',
29
+ changeDetection: ChangeDetectionStrategy.OnPush,
30
+ standalone: true,
31
+ template: `
32
+ <button type="button" class="lw-indicator" [class.lw-down]="!live()" [attr.aria-label]="label()" [title]="label()" (click)="retry()">
33
+ <span class="lw-dot" [class.lw-beat]="live() && !asked()" [class.lw-turn]="asked()"></span>
34
+ </button>
35
+ `,
36
+ styles: [
37
+ `
38
+ :host {
39
+ display: inline-flex;
40
+ }
41
+ .lw-indicator {
42
+ display: inline-flex;
43
+ align-items: center;
44
+ padding: 0;
45
+ border: none;
46
+ background: none;
47
+ cursor: pointer;
48
+ color: var(--lw-live, currentColor);
49
+ }
50
+ .lw-indicator.lw-down {
51
+ color: var(--lw-down, #b26a00);
52
+ }
53
+ .lw-indicator:focus-visible {
54
+ outline: 2px solid currentColor;
55
+ outline-offset: 2px;
56
+ border-radius: 50%;
57
+ }
58
+ .lw-dot {
59
+ display: block;
60
+ width: 0.6rem;
61
+ height: 0.6rem;
62
+ border-radius: 50%;
63
+ background: currentColor;
64
+ }
65
+ .lw-dot.lw-beat {
66
+ animation: lw-beat 1s ease-in-out infinite;
67
+ }
68
+ .lw-dot.lw-turn {
69
+ animation: lw-turn 0.5s ease-out;
70
+ }
71
+ @keyframes lw-beat {
72
+ 0%,
73
+ 90% {
74
+ transform: scale(1);
75
+ }
76
+ 45% {
77
+ transform: scale(1.35);
78
+ }
79
+ }
80
+ @keyframes lw-turn {
81
+ from {
82
+ transform: scale(1.6);
83
+ opacity: 0.4;
84
+ }
85
+ }
86
+ @media (prefers-reduced-motion: reduce) {
87
+ .lw-dot.lw-beat,
88
+ .lw-dot.lw-turn {
89
+ animation: none;
90
+ }
91
+ }
92
+ `,
93
+ ],
94
+ })
95
+ export class LiveIndicatorComponent {
96
+ private readonly client = inject(LivewireClient);
97
+
98
+ readonly live = this.client.live;
99
+
100
+ /**
101
+ * Set for a moment after a click, and read for nothing but the animation.
102
+ *
103
+ * A resync on a list that has not moved changes no pixel, so without this the
104
+ * gesture looks like it did nothing at all.
105
+ */
106
+ readonly asked = signal(false);
107
+
108
+ readonly label = computed(() => (this.live() ? LIVE : DOWN));
109
+
110
+ retry(): void {
111
+ this.client.retry();
112
+ this.asked.set(true);
113
+ setTimeout(() => this.asked.set(false), ACKNOWLEDGE_MS);
114
+ }
115
+ }
116
+
117
+ const LIVE = 'Live - click to ask for the data again';
118
+ const DOWN = 'Disconnected - reconnecting. Click to try now';
@@ -0,0 +1,94 @@
1
+ import { signal } from '@angular/core';
2
+ import type { Signal } from '@angular/core';
3
+ import type { LiveRow, PatchFrame, UpdateFrame } from '@softwarity/livewire-protocol';
4
+
5
+ /**
6
+ * A list kept in step with what the server pushes.
7
+ *
8
+ * Snapshot then patches, applied and nothing more: what belongs in the list and
9
+ * in what order is decided by the source's query, and a client that recomputed
10
+ * either from its own idea of the filters would be a second implementation free
11
+ * to disagree.
12
+ */
13
+ export class LiveList<Row extends LiveRow> {
14
+ private readonly held = signal<Row[]>([]);
15
+ private readonly length = signal(0);
16
+ private readonly marked = signal<number | null>(null);
17
+
18
+ /** The list as it stands. Ordered by the server, never re-sorted here. */
19
+ readonly rows: Signal<Row[]> = this.held.asReadonly();
20
+
21
+ /** What the list is a page of, for a paged topic. Its own length otherwise. */
22
+ readonly total: Signal<number> = this.length.asReadonly();
23
+
24
+ /**
25
+ * An index in the whole list the server pointed at, if it pointed at one.
26
+ *
27
+ * Meaningless here on purpose: the library carries the number and the screen
28
+ * decides what it means - a boundary, a cursor, the first unread row.
29
+ */
30
+ readonly pivot: Signal<number | null> = this.marked.asReadonly();
31
+
32
+ private sequence = 0;
33
+
34
+ /**
35
+ * Applies one frame. Answers false when the two sides have drifted, which is
36
+ * the caller's cue to ask for the window again.
37
+ */
38
+ apply(update: UpdateFrame<Row>): boolean {
39
+ if (update.type === 'error') {
40
+ console.error(`Livewire subscription '${update.id}' refused: ${update.reason}`);
41
+ return true;
42
+ }
43
+ if (update.type === 'snapshot') {
44
+ this.sequence = update.sequence;
45
+ this.held.set(update.rows);
46
+ this.length.set(update.total ?? update.rows.length);
47
+ this.marked.set(update.pivot ?? null);
48
+ return true;
49
+ }
50
+ // On one socket nothing is lost and nothing overtakes, so a gap means the
51
+ // two sides disagree about what was sent. Asking again is cheap; carrying
52
+ // on would show a list nobody can reproduce.
53
+ if (update.sequence !== this.sequence + 1) {
54
+ return false;
55
+ }
56
+ const rebuilt = this.rebuild(update);
57
+ if (!rebuilt) {
58
+ return false;
59
+ }
60
+ this.sequence = update.sequence;
61
+ this.held.set(rebuilt);
62
+ this.length.set(update.total ?? rebuilt.length);
63
+ this.marked.set(update.pivot ?? null);
64
+ return true;
65
+ }
66
+
67
+ /** Forgets what it holds - a fresh subscription answers with a snapshot. */
68
+ reset(): void {
69
+ this.sequence = 0;
70
+ this.held.set([]);
71
+ this.length.set(0);
72
+ this.marked.set(null);
73
+ }
74
+
75
+ /** Null when the patch names a row neither side holds - the caller resyncs. */
76
+ private rebuild(update: PatchFrame<Row>): Row[] | null {
77
+ const byId = new Map(this.held().map((row) => [row.id, row]));
78
+ for (const id of update.removed) {
79
+ byId.delete(id);
80
+ }
81
+ for (const row of update.upserted) {
82
+ byId.set(row.id, row);
83
+ }
84
+ const next: Row[] = [];
85
+ for (const id of update.order) {
86
+ const row = byId.get(id);
87
+ if (!row) {
88
+ return null;
89
+ }
90
+ next.push(row);
91
+ }
92
+ return next;
93
+ }
94
+ }
@@ -0,0 +1,83 @@
1
+ import { Observable } from 'rxjs';
2
+ import { filter, map } from 'rxjs/operators';
3
+ import { LiveList } from './live-list';
4
+ import { LivewireClient } from './livewire.client';
5
+ import type { JsonValue, LiveRow, UpdateFrame } from '@softwarity/livewire-protocol';
6
+
7
+ /**
8
+ * One screen's live window on one topic.
9
+ *
10
+ * The bookkeeping every feature service would otherwise repeat: the counter,
11
+ * the id it last opened, and the resync that has to name it. Small, and worth
12
+ * having once - the id rule below is the kind of thing that is right in one
13
+ * copy and wrong in the next.
14
+ */
15
+ export class LiveTopic<Row extends LiveRow> {
16
+ /** Counts subscriptions, so no two ever share an id. */
17
+ private opened = 0;
18
+
19
+ /** The id of the current window, for `resync`. */
20
+ private watching: string | null = null;
21
+
22
+ constructor(
23
+ private readonly client: LivewireClient,
24
+ private readonly topic: string,
25
+ ) {}
26
+
27
+ /**
28
+ * The rows the screen is showing, and again whenever they change.
29
+ *
30
+ * One subscription for the screen, not one per page: the window is part of
31
+ * the question, which is what makes a paged list pushable at all. The server
32
+ * does not send an insertion for the client to place - it sends what rows
33
+ * `[offset, offset+limit)` now hold, so three rows arriving at the top shift
34
+ * no index. The window simply holds something else than it did.
35
+ */
36
+ window(query: object, offset: number, limit: number): Observable<UpdateFrame<Row>> {
37
+ // Unique per subscription. Reusing an id means a patch still in flight from
38
+ // the window before lands on the new one, whose sequence starts over - it
39
+ // reads as a gap, resyncs, and nothing publishes in the meantime.
40
+ this.watching = `${this.topic}:${(this.opened += 1)}`;
41
+ return this.client.watch<Row>(this.watching, this.topic, { ...query, offset, limit } as JsonValue);
42
+ }
43
+
44
+ /**
45
+ * The same, for a list the server sends whole.
46
+ *
47
+ * A short list is bounded by its filters rather than by a scroll position, so
48
+ * there is no offset to send. Everything around it is unchanged: one live
49
+ * subscription at a time, a fresh id each time, and a resync that names it.
50
+ */
51
+ open(query: JsonValue | null): Observable<UpdateFrame<Row>> {
52
+ this.watching = `${this.topic}:${(this.opened += 1)}`;
53
+ return this.client.watch<Row>(this.watching, this.topic, query);
54
+ }
55
+
56
+ /** Asks the server for the window again - answered with a snapshot. */
57
+ resync(): void {
58
+ if (this.watching) {
59
+ this.client.resync(this.watching);
60
+ }
61
+ }
62
+ }
63
+
64
+ /**
65
+ * A short list, kept in step: the values that actually exist.
66
+ *
67
+ * Not a constant in the screen - offering a filter for something an
68
+ * installation has never seen answers nothing. These lists are small and
69
+ * unpaged, so there is one subscription per topic and its id is the topic.
70
+ */
71
+ export function liveLabels(
72
+ client: LivewireClient,
73
+ topic: string,
74
+ query: JsonValue | null = null,
75
+ ): Observable<{ id: string; label: string }[]> {
76
+ const list = new LiveList<LiveRow & { label?: string }>();
77
+ return client.watch<LiveRow & { label?: string }>(topic, topic, query).pipe(
78
+ filter((update) => list.apply(update)),
79
+ // A topic that sends no label is a list of bare values - the value is its
80
+ // own label.
81
+ map(() => list.rows().map((row) => ({ id: row.id, label: row.label ?? row.id }))),
82
+ );
83
+ }