@softwarity/livewire 0.1.1 → 0.2.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 CHANGED
@@ -23,7 +23,6 @@ readonly source = new LiveWindowDataSource<MessageRow>(
23
23
  (total) => this.total.set(total),
24
24
  () => this.messages.resync(),
25
25
  100,
26
- inject(ChangeDetectorRef), // what repaints a zoneless screen - see rule 1
27
26
  );
28
27
 
29
28
  constructor() {
@@ -50,19 +49,15 @@ constructor() {
50
49
 
51
50
  Each of these cost a debugging session in the application this came from.
52
51
 
53
- **1. Say that something arrived.** A row arriving from a socket callback
54
- schedules no change detection at all in a zoneless application: the field is
55
- right and the screen is wrong. Two ways to say it, and either is enough.
56
-
57
- - **Hand the data source a `ChangeDetectorRef`** (above). It calls
58
- `markForCheck()` on every publication, which marks the view dirty *and*
59
- notifies the zoneless scheduler. The template then says only what it shows.
60
- - **Or read `revision()` in the template** — `[attr.data-revision]="source.revision()"`
61
- on the viewport is enough. Use this when the source is built outside an
62
- injection context, where there is no `ChangeDetectorRef` to inject.
63
-
64
- `ApplicationRef.tick()` is the third way and the wrong one: it throws when it
65
- lands inside a cycle already in progress.
52
+ **1. Build the data source in the component that shows the list.** A row
53
+ arriving from a socket callback schedules no change detection at all in a
54
+ zoneless application: the field is right and the screen is wrong. Built in a
55
+ component field, the data source injects that view's `ChangeDetectorRef` and
56
+ calls `markForCheck()` on every publication — which marks the view dirty *and*
57
+ notifies the zoneless scheduler. Built outside an injection context it throws,
58
+ and that is the intended answer: a data source with no view to repaint has
59
+ nobody to answer. (`ApplicationRef.tick()` is the other way and the wrong one:
60
+ it throws when it lands inside a cycle already in progress.)
66
61
 
67
62
  **2. The window size is a constant per screen, never derived from the
68
63
  viewport.** Deriving it loops: publish → the viewport re-measures → a new window
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@softwarity/livewire",
3
- "version": "0.1.1",
3
+ "version": "0.2.0",
4
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
5
  "keywords": [
6
6
  "angular",
@@ -38,7 +38,7 @@
38
38
  "rxjs": "^7.5.0"
39
39
  },
40
40
  "dependencies": {
41
- "@softwarity/livewire-protocol": "0.1.1",
41
+ "@softwarity/livewire-protocol": "0.2.0",
42
42
  "tslib": "^2.6.2"
43
43
  },
44
44
  "devDependencies": {
@@ -56,6 +56,6 @@
56
56
  "rxjs": "^7.8.1",
57
57
  "typescript": "~5.6.0",
58
58
  "zone.js": "^0.15.0",
59
- "@softwarity/livewire-mock": "0.1.1"
59
+ "@softwarity/livewire-mock": "0.2.0"
60
60
  }
61
61
  }
@@ -1,8 +1,7 @@
1
1
  import { DataSource } from '@angular/cdk/collections';
2
- import { signal } from '@angular/core';
2
+ import { ChangeDetectorRef, inject } from '@angular/core';
3
3
  import { BehaviorSubject, Observable, Subscription } from 'rxjs';
4
4
  import { LiveList } from './live-list';
5
- import type { ChangeDetectorRef } from '@angular/core';
6
5
  import type { CollectionViewer, ListRange } from '@angular/cdk/collections';
7
6
  import type { LiveRow, UpdateFrame } from '@softwarity/livewire-protocol';
8
7
 
@@ -64,22 +63,25 @@ const FRESH_MS = 1000;
64
63
  export class LiveWindowDataSource<Row extends LiveRow> extends DataSource<Row | undefined> {
65
64
  private readonly published = new BehaviorSubject<(Row | undefined)[]>([]);
66
65
  private readonly viewing = new Subscription();
67
- private readonly stamp = signal(0);
68
66
 
69
67
  /**
70
- * Bumped on every publication, and meant to be read in the template.
68
+ * The view to repaint, taken from wherever this was built.
71
69
  *
72
70
  * Zoneless applications schedule nothing when a row arrives from a socket
73
71
  * callback: the table is told its data changed but no pass is ever run, and
74
72
  * the screen holds stale rows until something unrelated wakes Angular up.
73
+ * `markForCheck()` marks the view dirty *and* notifies the zoneless
74
+ * scheduler, which is exactly the missing half.
75
75
  *
76
- * Two ways to say it properly, and this is the one that needs nothing from
77
- * the caller: a signal the view reads. Hand a `ChangeDetectorRef` to the
78
- * constructor instead and the repaint is asked for here, leaving the template
79
- * to say only what it shows. (`ApplicationRef.tick()` is the third way and the
80
- * wrong one - it throws when it lands inside a cycle already in progress.)
76
+ * Injected rather than asked for, because there is nothing to decide: build
77
+ * this in a component field, as one does, and the injection context is right
78
+ * there. Built outside one it throws, and that is the point - a data source
79
+ * with no view to repaint has nobody to answer.
80
+ *
81
+ * (`ApplicationRef.tick()` is the other way and the wrong one: it throws when
82
+ * it lands inside a cycle already in progress.)
81
83
  */
82
- readonly revision = this.stamp.asReadonly();
84
+ private readonly repaint = inject(ChangeDetectorRef);
83
85
 
84
86
  private list = new LiveList<Row>();
85
87
  private watching: Subscription | null = null;
@@ -99,24 +101,6 @@ export class LiveWindowDataSource<Row extends LiveRow> extends DataSource<Row |
99
101
  private readonly onDrift: () => void = () => undefined,
100
102
  /** Rows per window - see `DEFAULT_WINDOW` for how to choose one. */
101
103
  private readonly window: number = DEFAULT_WINDOW,
102
- /**
103
- * The view to repaint when something arrives. Optional, and the difference
104
- * it makes is on the screen's side, not here.
105
- *
106
- * `markForCheck()` marks the view dirty *and* notifies the zoneless
107
- * scheduler, so a frame landing in a socket callback gets a pass run for it.
108
- * Given one, a template needs no `revision()`; given none, it does.
109
- *
110
- * ```ts
111
- * readonly source = new LiveWindowDataSource<Row>(
112
- * (total) => this.total.set(total),
113
- * () => this.topic.resync(),
114
- * 100,
115
- * inject(ChangeDetectorRef),
116
- * );
117
- * ```
118
- */
119
- private readonly repaint?: ChangeDetectorRef,
120
104
  ) {
121
105
  super();
122
106
  }
@@ -206,10 +190,7 @@ export class LiveWindowDataSource<Row extends LiveRow> extends DataSource<Row |
206
190
  // asking any more, and the snapshot lands a moment later. Emptying it
207
191
  // without saying so leaves the previous answer on display in between.
208
192
  //
209
- // `markForCheck` and not `touched`: a screen calls this from an `effect`,
210
- // and Angular 18 - which this package still supports - refuses a signal
211
- // write from inside one.
212
- this.repaint?.markForCheck();
193
+ this.repaint.markForCheck();
213
194
  this.follow();
214
195
  }
215
196
 
@@ -330,7 +311,7 @@ export class LiveWindowDataSource<Row extends LiveRow> extends DataSource<Row |
330
311
  for (const id of ids) {
331
312
  this.recent.delete(id);
332
313
  }
333
- this.touched();
314
+ this.repaint.markForCheck();
334
315
  }, FRESH_MS);
335
316
  }
336
317
 
@@ -347,18 +328,6 @@ export class LiveWindowDataSource<Row extends LiveRow> extends DataSource<Row |
347
328
  rows[this.offset + index] = held[index];
348
329
  }
349
330
  this.published.next(rows);
350
- this.touched();
351
- }
352
-
353
- /**
354
- * Says that the screen has something new to show.
355
- *
356
- * Both ways at once, and they do not overlap: the signal serves a template
357
- * that reads `revision()`, and `markForCheck()` serves one that does not.
358
- * Whichever the screen uses, the other costs a counter.
359
- */
360
- private touched(): void {
361
- this.stamp.update((count) => count + 1);
362
- this.repaint?.markForCheck();
331
+ this.repaint.markForCheck();
363
332
  }
364
333
  }
@@ -1,3 +1,4 @@
1
+ import { ChangeDetectorRef } from '@angular/core';
1
2
  import { TestBed } from '@angular/core/testing';
2
3
  import { MockServer } from '@softwarity/livewire-mock';
3
4
  import { LiveList } from '../src/lib/live-list';
@@ -22,7 +23,12 @@ describe('the client, end to end', () => {
22
23
  function clientOf(): LivewireClient {
23
24
  TestBed.resetTestingModule();
24
25
  TestBed.configureTestingModule({
25
- providers: [provideLivewire({ path: '', connect: () => server.connect() })],
26
+ providers: [
27
+ provideLivewire({ path: '', connect: () => server.connect() }),
28
+ // The data source repaints a view; here there is none, so the ref is a
29
+ // stub. `repaint.spec.ts` is where the repainting itself is checked.
30
+ { provide: ChangeDetectorRef, useValue: { markForCheck: () => undefined } },
31
+ ],
26
32
  });
27
33
  return TestBed.inject(LivewireClient);
28
34
  }
@@ -128,7 +134,9 @@ describe('the client, end to end', () => {
128
134
  it('feeds a virtual-scroll source from end to end', async () => {
129
135
  const client = clientOf();
130
136
  const topic = new LiveTopic<LiveRow>(client, 'rows');
131
- const source = new LiveWindowDataSource<LiveRow>();
137
+ // Built in an injection context, as it is in a component field: the data
138
+ // source takes the view it repaints from there.
139
+ const source = TestBed.runInInjectionContext(() => new LiveWindowDataSource<LiveRow>());
132
140
  source.reset((offset, limit) => topic.window({}, offset, limit));
133
141
  await settle();
134
142
 
@@ -1,8 +1,25 @@
1
+ import { ChangeDetectorRef } from '@angular/core';
2
+ import { TestBed } from '@angular/core/testing';
1
3
  import { Subject } from 'rxjs';
2
4
  import { LiveWindowDataSource } from '../src/lib/live-window.datasource';
3
5
  import type { CollectionViewer } from '@angular/cdk/collections';
4
6
  import type { LiveRow, UpdateFrame } from '@softwarity/livewire-protocol';
5
7
 
8
+ /**
9
+ * The data source injects the view it repaints, so it is built in an injection
10
+ * context here as it is in a component field. Nothing in this file is about
11
+ * repainting - `repaint.spec.ts` covers that - so the ref is a stub.
12
+ */
13
+ function build<Row extends LiveRow>(...args: ConstructorParameters<typeof LiveWindowDataSource>): LiveWindowDataSource<Row> {
14
+ return TestBed.runInInjectionContext(() => new LiveWindowDataSource<Row>(...args));
15
+ }
16
+
17
+ beforeEach(() =>
18
+ TestBed.configureTestingModule({
19
+ providers: [{ provide: ChangeDetectorRef, useValue: { markForCheck: () => undefined } }],
20
+ }),
21
+ );
22
+
6
23
  function rows(from: number, count: number): LiveRow[] {
7
24
  return Array.from({ length: count }, (_, index) => ({ id: `r${from + index}`, updatedAt: 'v1' }));
8
25
  }
@@ -16,11 +33,7 @@ describe('LiveWindowDataSource', () => {
16
33
  function sourceOf(window?: number): void {
17
34
  opened = [];
18
35
  feed = new Subject<UpdateFrame<LiveRow>>();
19
- source = new LiveWindowDataSource<LiveRow>(
20
- () => undefined,
21
- () => undefined,
22
- window,
23
- );
36
+ source = build<LiveRow>(() => undefined, () => undefined, window);
24
37
  viewChange = new Subject<{ start: number; end: number }>();
25
38
  source.connect({ viewChange } as unknown as CollectionViewer);
26
39
  source.reset((offset, limit) => {
@@ -120,7 +133,7 @@ describe('LiveWindowDataSource', () => {
120
133
  let drifted = 0;
121
134
  opened = [];
122
135
  feed = new Subject<UpdateFrame<LiveRow>>();
123
- source = new LiveWindowDataSource<LiveRow>(
136
+ source = build<LiveRow>(
124
137
  () => undefined,
125
138
  () => (drifted += 1),
126
139
  );
@@ -1,4 +1,4 @@
1
- import { ChangeDetectorRef, Component, inject } from '@angular/core';
1
+ import { ChangeDetectorRef, Component } from '@angular/core';
2
2
  import { TestBed } from '@angular/core/testing';
3
3
  import { Subject } from 'rxjs';
4
4
  import { LiveWindowDataSource } from '../src/lib/live-window.datasource';
@@ -7,13 +7,14 @@ import type { LiveRow, UpdateFrame } from '@softwarity/livewire-protocol';
7
7
  /**
8
8
  * What repaints a zoneless screen when a frame lands in a socket callback.
9
9
  *
10
- * Two ways, and the point of this file is that the second one works: a signal
11
- * the template reads, or a `ChangeDetectorRef` handed to the data source.
10
+ * The data source injects the view's `ChangeDetectorRef` and calls
11
+ * `markForCheck()`, which marks the view dirty *and* notifies the zoneless
12
+ * scheduler. Nothing is asked of the screen.
12
13
  *
13
- * The templates here read **no signal at all** and use no async pipe - they
14
- * render a plain field, filled from a subscription. That is deliberate: it
15
- * strips out every other thing that could schedule a pass, so what the test
16
- * measures is the notification itself and nothing else.
14
+ * The component below reads **no signal at all** and uses no async pipe - it
15
+ * renders a plain field, filled from a subscription. That is deliberate: it
16
+ * strips out every other thing that could schedule a pass, so what is measured
17
+ * is the notification itself and nothing else.
17
18
  */
18
19
  describe('repainting a zoneless screen', () => {
19
20
  const feed = new Subject<UpdateFrame<LiveRow>>();
@@ -29,34 +30,15 @@ describe('repainting a zoneless screen', () => {
29
30
  }
30
31
 
31
32
  @Component({
32
- selector: 'test-told',
33
+ selector: 'test-screen',
33
34
  standalone: true,
34
35
  template: `<span class="ids">{{ ids }}</span>`,
35
36
  })
36
- class ToldComponent {
37
- ids = '';
38
-
39
- readonly source = new LiveWindowDataSource<LiveRow>(
40
- () => undefined,
41
- () => undefined,
42
- 100,
43
- inject(ChangeDetectorRef),
44
- );
45
-
46
- constructor() {
47
- this.source.changes.subscribe((rows) => (this.ids = rows.map((row) => row?.id ?? '-').join(',')));
48
- this.source.reset(() => feed);
49
- }
50
- }
51
-
52
- @Component({
53
- selector: 'test-silent',
54
- standalone: true,
55
- template: `<span class="ids">{{ ids }}</span>`,
56
- })
57
- class SilentComponent {
37
+ class ScreenComponent {
58
38
  ids = '';
59
39
 
40
+ // A component field, which is an injection context - the data source takes
41
+ // this view's ChangeDetectorRef from it.
60
42
  readonly source = new LiveWindowDataSource<LiveRow>();
61
43
 
62
44
  constructor() {
@@ -65,37 +47,19 @@ describe('repainting a zoneless screen', () => {
65
47
  }
66
48
  }
67
49
 
68
- it('repaints on its own when it was given a ChangeDetectorRef', async () => {
69
- const fixture = TestBed.createComponent(ToldComponent);
50
+ it('repaints on a frame arriving from outside a change-detection cycle', async () => {
51
+ const fixture = TestBed.createComponent(ScreenComponent);
70
52
  await fixture.whenStable();
71
53
 
72
- // Straight into the data source, as a socket callback would - nothing here
73
- // runs inside a change-detection cycle.
54
+ // Straight into the data source, as a socket callback would.
74
55
  feed.next(frame('a', 'b'));
75
56
  await fixture.whenStable();
76
57
 
77
58
  expect(fixture.nativeElement.querySelector('.ids').textContent).toBe('a,b');
78
59
  });
79
60
 
80
- /**
81
- * The other half of the claim, and the reason the rule exists: without either
82
- * notification the field is right and the screen is wrong. A test that only
83
- * checked the first case would pass just as well if something else in the
84
- * fixture were scheduling the pass.
85
- */
86
- it('does not, when it was given neither a ChangeDetectorRef nor a revision() read', async () => {
87
- const fixture = TestBed.createComponent(SilentComponent);
88
- await fixture.whenStable();
89
-
90
- feed.next(frame('a', 'b'));
91
- await fixture.whenStable();
92
-
93
- expect(fixture.componentInstance.ids).toBe('a,b');
94
- expect(fixture.nativeElement.querySelector('.ids').textContent).toBe('');
95
- });
96
-
97
61
  it('repaints again on every later frame, not only the first', async () => {
98
- const fixture = TestBed.createComponent(ToldComponent);
62
+ const fixture = TestBed.createComponent(ScreenComponent);
99
63
  await fixture.whenStable();
100
64
 
101
65
  for (const ids of [['a'], ['a', 'b'], ['a', 'b', 'c']]) {
@@ -104,6 +68,15 @@ describe('repainting a zoneless screen', () => {
104
68
  expect(fixture.nativeElement.querySelector('.ids').textContent).toBe(ids.join(','));
105
69
  }
106
70
  });
71
+
72
+ /**
73
+ * The rule made structural: there is no way to build one that cannot repaint.
74
+ * Left optional, the screens that forgot it would look right in development
75
+ * and hold stale rows in production.
76
+ */
77
+ it('refuses to be built where there is no view to repaint', () => {
78
+ expect(() => new LiveWindowDataSource<LiveRow>()).toThrow();
79
+ });
107
80
  });
108
81
 
109
82
  /**
@@ -116,7 +89,6 @@ describe('repainting a zoneless screen', () => {
116
89
  */
117
90
  describe('what asks for a repaint, and what does not', () => {
118
91
  let asked: number;
119
- let repaint: ChangeDetectorRef;
120
92
  let feed: Subject<UpdateFrame<LiveRow>>;
121
93
  let source: LiveWindowDataSource<LiveRow>;
122
94
 
@@ -127,16 +99,14 @@ describe('what asks for a repaint, and what does not', () => {
127
99
  beforeEach(() => {
128
100
  jest.useFakeTimers();
129
101
  asked = 0;
130
- // Only `markForCheck` is ever called; the rest of the interface is not
131
- // worth stubbing to count one thing.
132
- repaint = { markForCheck: () => (asked += 1) } as unknown as ChangeDetectorRef;
102
+ // `ChangeDetectorRef` is a token like any other: provided here, the data
103
+ // source injects this instead of a view's, and the calls can be counted.
104
+ // Only `markForCheck` is ever called.
105
+ TestBed.configureTestingModule({
106
+ providers: [{ provide: ChangeDetectorRef, useValue: { markForCheck: () => (asked += 1) } }],
107
+ });
133
108
  feed = new Subject<UpdateFrame<LiveRow>>();
134
- source = new LiveWindowDataSource<LiveRow>(
135
- () => undefined,
136
- () => undefined,
137
- 100,
138
- repaint,
139
- );
109
+ source = TestBed.runInInjectionContext(() => new LiveWindowDataSource<LiveRow>());
140
110
  });
141
111
 
142
112
  afterEach(() => jest.useRealTimers());
@@ -147,19 +117,6 @@ describe('what asks for a repaint, and what does not', () => {
147
117
  expect(asked).toBe(1);
148
118
  });
149
119
 
150
- /**
151
- * A screen calls `reset` from an `effect`, and Angular 18 refuses a signal
152
- * write from inside one. So emptying the list asks for a pass without
153
- * touching `revision` - which stays where the frames bump it.
154
- */
155
- it('empties the list without writing a signal', () => {
156
- const before = source.revision();
157
-
158
- source.reset(() => feed);
159
-
160
- expect(source.revision()).toBe(before);
161
- });
162
-
163
120
  it('asks once per frame it could apply, and no more', () => {
164
121
  source.reset(() => feed);
165
122
  asked = 0;
package/test/setup.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  // Zoneless, deliberately: this library is written for applications that do not
2
- // ship zone.js, and its one contract with change detection - read `revision()`
2
+ // ship zone.js, and its one contract with change detection - `markForCheck()`
3
3
  // in the template - only means anything there.
4
4
  import { setupZonelessTestEnv } from 'jest-preset-angular/setup-env/zoneless';
5
5