@rs-x/state-manager 0.4.22 → 1.0.2

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
@@ -1,1930 +1,13 @@
1
- # State-manager
1
+ # @rs-x/state-manager
2
2
 
3
- The **State Manager** provides an efficient way to observe and synchronize state changes across your application.
3
+ Reactive state management for RS-X — provides an efficient way to observe, update, and synchronize state changes across your application. Supports fine-grained change detection and automatic reactive updates.
4
4
 
5
- A state item is defined by a **context** and an **index**.
6
- A context can be an object, and an index can be a property name — but it is not limited to that. It can be **any value**. The context is used as an identifier to group a set of state indexes.
7
-
8
- Examples of state indexes:
9
-
10
- - Object property or field → index = property or field name
11
- - Array item → index = numeric position
12
- - Map item → index = map key
13
-
14
- The State Manager does **not** automatically know how to detect changes for every state value data type, nor how to patch the corresponding state setter. Therefore, it relies on two services:
15
-
16
- - A service implementing `IObjectPropertyObserverProxyPairManager`
17
- Responsible for creating observers and proxying values when needed.
18
-
19
- - A service implementing `IIndexValueAccessor`
20
- Responsible for retrieving the current value.
21
-
22
- The **State Manager** has the followng interface:
23
-
24
- ```ts
25
- export interface IStateManager {
26
- readonly changed: Observable<IStateChange>;
27
- readonly contextChanged: Observable<IContextChanged>;
28
- readonly startChangeCycle: Observable<void>;
29
- readonly endChangeCycle: Observable<void>;
30
-
31
- isWatched(
32
- context: unknown,
33
- index: unknown,
34
- mustProxify: MustProxify,
35
- ): boolean;
36
-
37
- watchState(
38
- context: unknown,
39
- index: unknown,
40
- mustProxify?: MustProxify,
41
- ): unknown;
42
-
43
- releaseState(
44
- oontext: unknown,
45
- index: unknown,
46
- mustProxify?: MustProxify,
47
- ): void;
48
-
49
- getState<T>(context: unknown, index: unknown): T;
50
-
51
- setState<T>(context: unknown, index: unknown, value: T): void;
52
-
53
- clear(): void;
54
- }
55
- ```
56
-
57
- ---
58
-
59
- ## Members
60
-
61
- ### **changed**
62
-
63
- **Type:** `Observable<IStateChange>`
64
- Emits whenever a state item value changes.
65
-
66
- ---
67
-
68
- ### **contextChanged**
69
-
70
- **Type:** `Observable<IContextChanged>`
71
- Emits whenever an entire context is replaced.
72
- This happens, for example, when a nested object is replaced.
5
+ **Docs:** [rsxjs.com](https://rsxjs.com)
73
6
 
74
7
  ---
75
8
 
76
- ### **startChangeCycle**
77
-
78
- **Type:** `Observable<void>`
79
- Emits at the start of processing a state item change.
80
-
81
- ---
82
-
83
- ### **endChangeCycle**
84
-
85
- **Type:** `Observable<void>`
86
- Emits at the end of processing a state item change.
87
-
88
- ---
89
-
90
- ### **isWatched(context, index, mustProxify)**
91
-
92
- Returns whether the state item identified by the `(context, index, mustProxify)` triplet is currently being watched.
93
-
94
- | Parameter | Type | Description |
95
- | --------------- | -------------------------- | -------------------------------------------------------------------------------------------------------------------------------------- |
96
- | **context** | `unknown` | The context to which the state index belongs. |
97
- | **index** | `unknown` | The index identifying the state on the given context. |
98
- | **mustProxify** | `MustProxify` _(optional)_ | Predicate determining whether a nested state value must be proxified. It should be the same predicate that was passed to `watchState`. |
99
-
100
- **Returns:** `boolean`
101
-
102
- ---
103
-
104
- ### **watchState(context, index, mustProxify?)**
105
-
106
- Watches a state item identified by the `(context, index, mustProxify)` triplet so that its value is proxified and tracked.
107
-
108
- | Parameter | Type | Description |
109
- | --------------- | -------------------------- | --------------------------------------------------------------------- |
110
- | **context** | `unknown` | The state context. |
111
- | **index** | `unknown` | The index identifying the state on the given context. |
112
- | **mustProxify** | `MustProxify` _(optional)_ | Predicate determining whether a nested state value must be proxified. |
113
-
114
- **Returns:**
115
- `unknown` — the state item value if it was already being watched; otherwise `undefined`.
116
-
117
- ---
118
-
119
- ### **releaseState(context, index, mustProxify?)**
120
-
121
- Releases the state item identified by the `(context, index, mustProxify)` triplet.
122
- Each call to `watchState` should have a corresponding `releaseState` call to ensure the state item is released when it is no longer needed.
123
-
124
- | Parameter | Type | Description |
125
- | --------------- | -------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------- |
126
- | **context** | `unknown` | The state context. |
127
- | **index** | `unknown` | The index identifying the state on the given context. |
128
- | **mustProxify** | `MustProxify` _(optional)_ | Predicate determining whether a nested state value must be proxified. It should be the same predicate that was passed to `watchState`. . |
129
-
130
- **Returns:** `void`
131
-
132
- ---
133
-
134
- ### **getState(context, index)**
135
-
136
- Retrieves the current state item value identified by the `(context, index)` pair.
137
-
138
- | Parameter | Type | Description |
139
- | ----------- | --------- | ----------------------------------------------------- |
140
- | **context** | `unknown` | The state context. |
141
- | **index** | `unknown` | The index identifying the state on the given context. |
142
-
143
- **Returns:** `unknown`
144
-
145
- ---
146
-
147
- ### **setState(context, index, value)**
148
-
149
- Sets the value of the state item identified by the `(context, index)` pair.
150
-
151
- Unlike `watchState`, `setState` does **not** track changes. It does not patch setters or proxify values.
152
- A change event is emitted on the first `setState` call and again whenever the value changes in subsequent calls.
153
-
154
- | Parameter | Type | Description |
155
- | ----------- | --------- | ----------------------------------------------------- |
156
- | **context** | `unknown` | The state context. |
157
- | **index** | `unknown` | The index identifying the state on the given context. |
158
- | **value** | `unknown` | The state value. |
159
-
160
- ---
161
-
162
- ### **clear()**
163
-
164
- Releases all registered state items.
165
-
166
- **Returns:** `void`
167
-
168
- ---
169
-
170
- ## Get an instance of the State Manager
171
-
172
- The state manager is registered as a **singleton service**.
173
- You must load the module into the injection container if you went
174
- to use it.
175
-
176
- ```ts
177
- import { InjectionContainer } from '@rs-x/core';
178
- import { RsXStateManagerModule } from '@rs-x/state-manager';
179
-
180
- InjectionContainer.load(RsXStateManagerModule);
181
- ```
182
-
183
- There are two ways to get an instance:
184
-
185
- ### 1. Using the injection container
186
-
187
- ```ts
188
- import { InjectionContainer } from '@rs-x/core';
189
- import {
190
- IIStateManager,
191
- RsXStateManagerInjectionTokens,
192
- } from '@rs-x/state-manager';
193
-
194
- const stateManager: IIStateManager = InjectionContainer.get(
195
- RsXStateManagerInjectionTokens.IStateManager,
196
- );
197
- ```
198
-
199
- ### 2. Using the `@Inject` decorator
200
-
201
- ```ts
202
- import { Inject } from '@rs-x/core';
203
- import {
204
- IIStateManager,
205
- RsXStateManagerInjectionTokens,
206
- } from '@rs-x/state-manager';
207
-
208
- export class MyClass {
209
- constructor(
210
- @Inject(RsXStateManagerInjectionTokens.IStateManager)
211
- private readonly _stateManager: IIStateManager,
212
- ) {}
213
- }
214
- ```
215
-
216
- ---
217
-
218
- ## Register state
219
-
220
- There are two variants:
221
-
222
- ### Non-recursive
223
-
224
- Monitors only assignment of a **new value** to the index.
225
-
226
- ```ts
227
- import { InjectionContainer, printValue } from '@rs-x/core';
228
- import {
229
- type IStateChange,
230
- type IStateManager,
231
- RsXStateManagerInjectionTokens,
232
- RsXStateManagerModule,
233
- } from '@rs-x/state-manager';
234
-
235
- // Load the state manager module into the injection container
236
- InjectionContainer.load(RsXStateManagerModule);
237
-
238
- export const run = (() => {
239
- const stateManager: IStateManager = InjectionContainer.get(
240
- RsXStateManagerInjectionTokens.IStateManager,
241
- );
242
-
243
- const model = {
244
- x: { y: 10 },
245
- };
246
-
247
- // This will emit a change event with the initial (current) value.
248
- console.log('Initial value:');
249
- const changedSubsription = stateManager.changed.subscribe(
250
- (change: IStateChange) => {
251
- printValue(change.newValue);
252
- },
253
- );
254
-
255
- try {
256
- // This will emit the new value { y: 10 }
257
- stateManager.watchState(model, 'x');
258
-
259
- console.log('Changed value:');
260
- // This will emit the new value { y: 10 }
261
- model.x = {
262
- y: 20,
263
- };
264
-
265
- console.log(`Latest value:`);
266
- printValue(stateManager.getState(model, 'x'));
267
-
268
- // This will emit no change because the state is not recursive.
269
- console.log('\nmodel.x.y = 30 will not emit any change:\n---\n');
270
- model.x.y = 30;
271
- } finally {
272
- changedSubsription.unsubscribe();
273
- // Always release the state when it is no longer needed.
274
- stateManager.releaseState(model, 'x');
275
- }
276
- })();
277
- ```
278
-
279
- **Output:**
280
-
281
- ```console
282
- Running demo: demo/src/rs-x-state-manager/register-non-recursive-state.ts
283
- Initial value:
284
- {
285
- y: 10
286
- }
287
- Changed value:
288
- {
289
- y: 20
290
- }
291
- Latest value:
292
- {
293
- y: 20
294
- }
295
-
296
- stateContext.x.y = 30 will not emit any change:
297
- ---
298
- ```
299
-
300
- ---
301
-
302
- ### Recursive
303
-
304
- Monitors assignments **and** changes _inside_ the value.
305
- Example: if the value is an object, internal object changes are also observed. You can make a state item recursive by passing in a **mustProxify** predicate to a **watchState** call. The mustProxify will be called for every nested index. If you return true it will watch the index otherwise not.
306
-
307
- ```ts
308
- import { InjectionContainer, printValue } from '@rs-x/core';
309
- import {
310
- type IStateChange,
311
- type IStateManager,
312
- RsXStateManagerInjectionTokens,
313
- RsXStateManagerModule,
314
- watchIndexRecursiveRule,
315
- } from '@rs-x/state-manager';
316
-
317
- // Load the state manager module into the injection container
318
- InjectionContainer.load(RsXStateManagerModule);
319
-
320
- export const run = (() => {
321
- const stateManager: IStateManager = InjectionContainer.get(
322
- RsXStateManagerInjectionTokens.IStateManager,
323
- );
324
- const model = {
325
- x: { y: 10 },
326
- };
327
- const changedSubscription = stateManager.changed.subscribe(
328
- (change: IStateChange) => {
329
- printValue(change.newValue);
330
- },
331
- );
332
-
333
- try {
334
- // We register recursive state by passing
335
- // a predicate as the third argument.
336
- // In this case, we want to watch the entire value,
337
- // so we pass a predicate that always returns true.
338
- // This will emit an initial value { y: 10 }
339
- console.log('Initial value:');
340
- stateManager.watchState(model, 'x', watchIndexRecursiveRule);
341
-
342
- console.log('Changed value:');
343
- // This will emit the new value { y: 10 }
344
- model.x = {
345
- y: 20,
346
- };
347
-
348
- console.log('Changed (recursive) value:');
349
- // This will emit the new value { y: 30 } because x
350
- // is registered as a recursive state.
351
- model.x.y = 30;
352
-
353
- console.log(`Latest value:`);
354
- printValue(stateManager.getState(model, 'x'));
355
- } finally {
356
- changedSubscription.unsubscribe();
357
- // Always release the state when it is no longer needed.
358
- stateManager.releaseState(model, 'x', watchIndexRecursiveRule);
359
- }
360
- })();
361
- ```
362
-
363
- **Output:**
364
-
365
- ```console
366
- Initial value:
367
- { y: 10 }
368
-
369
- Changed value:
370
- { y: 20 }
371
-
372
- Changed (recursive) value:
373
- { y: 30 }
374
- ```
375
-
376
- ---
377
-
378
- ### Manually setting state
379
-
380
- Besides that you can register a watched stated (calling `watchedState`) you can register an unwatched state using `setState`. An example for using `setState` might be an readonly property:
381
-
382
- ```ts
383
- import { InjectionContainer, printValue } from '@rs-x/core';
384
- import {
385
- type IStateChange,
386
- type IStateManager,
387
- RsXStateManagerInjectionTokens,
388
- RsXStateManagerModule,
389
- } from '@rs-x/state-manager';
390
-
391
- // Load the state manager module into the injection container
392
- InjectionContainer.load(RsXStateManagerModule);
393
-
394
- export const run = (() => {
395
- const stateManager: IStateManager = InjectionContainer.get(
396
- RsXStateManagerInjectionTokens.IStateManager,
397
- );
398
-
399
- class MyModel {
400
- private readonly _aPlusBId = 'a+b';
401
- private _a = 10;
402
- private _b = 20;
403
-
404
- constructor() {
405
- this.setAPlusB();
406
- }
407
-
408
- public dispose(): void {
409
- return stateManager.releaseState(this, this._aPlusBId);
410
- }
411
-
412
- public get aPlusB(): number {
413
- return stateManager.getState(this, this._aPlusBId);
414
- }
415
-
416
- public get a(): number {
417
- return this._a;
418
- }
419
-
420
- public set a(value: number) {
421
- this._a = value;
422
- this.setAPlusB();
423
- }
424
-
425
- public get b(): number {
426
- return this._b;
427
- }
428
-
429
- public set b(value: number) {
430
- this._b = value;
431
- this.setAPlusB();
432
- }
433
-
434
- private setAPlusB(): void {
435
- stateManager.setState(this, this._aPlusBId, this._a + this._b);
436
- }
437
- }
438
-
439
- const model = new MyModel();
440
- const changeSubscription = stateManager.changed.subscribe(
441
- (change: IStateChange) => {
442
- printValue(change.newValue);
443
- },
444
- );
445
-
446
- try {
447
- console.log(`Initial value for readonly property 'aPlusB':`);
448
- console.log(model.aPlusB);
449
-
450
- console.log(
451
- `set 'model.a' to '100' will emit a change event for readonly property 'aPlusB'`,
452
- );
453
- console.log(`Changed value for readonly property 'aPlusB':`);
454
- model.a = 100;
455
-
456
- console.log(
457
- `set 'model.b' to '200' will emit a change event for readonly property 'aPlusB'`,
458
- );
459
- console.log(`Changed value for readonly property 'aPlusB':`);
460
- model.b = 200;
461
- } finally {
462
- changeSubscription.unsubscribe();
463
- // Always release the state when it is no longer needed.
464
- model.dispose();
465
- }
466
- })();
467
- ```
468
-
469
- **Output:**
470
-
471
- ```console
472
- Running demo: demo/src/rs-x-state-manager/register-readonly-property.ts
473
- Initial value for readonly property 'aPlusB':
474
- 30
475
- set 'stateContext.a' to '100' will emit a change event for readonly property 'aPlusB'
476
- Changed value for readonly property 'aPlusB':
477
- 120
478
- set 'stateContext.b' to '200' will emit a change event for readonly property 'aPlusB'
479
- Changed value for readonly property 'aPlusB':
480
- 300
481
- ```
482
-
483
- ---
484
-
485
- ### State registration is idempotent
486
-
487
- You can register the same state item multiple times.
488
- Never assume a state is already registered. Always register it if you depend on it.
489
- Otherwise the state may disappear when another part of the system unregisters it. The state manager keeps track of a reference count and will release the state when it goes to zero.
490
-
491
- When done, release the state:
492
-
493
- ```ts
494
- import { InjectionContainer, printValue } from '@rs-x/core';
495
- import {
496
- type IStateChange,
497
- type IStateManager,
498
- RsXStateManagerInjectionTokens,
499
- RsXStateManagerModule,
500
- } from '@rs-x/state-manager';
501
-
502
- // Load the state manager module into the injection container
503
- InjectionContainer.load(RsXStateManagerModule);
504
-
505
- export const run = (() => {
506
- const stateManager: IStateManager = InjectionContainer.get(
507
- RsXStateManagerInjectionTokens.IStateManager,
508
- );
509
- const model = {
510
- x: { y: 10 },
511
- };
512
- const changedSubscription = stateManager.changed.subscribe(
513
- (change: IStateChange) => {
514
- printValue(change.newValue);
515
- },
516
- );
517
-
518
- try {
519
- // Register is idempotent: you can register the same state multiple times.
520
- // For every register call, make sure you call unregister when you're done.
521
- console.log('Initial value:');
522
- stateManager.watchState(model, 'x');
523
- stateManager.watchState(model, 'x');
524
-
525
- console.log('Changed value:');
526
- model.x = { y: 20 };
527
-
528
- stateManager.releaseState(model, 'x');
529
-
530
- console.log(
531
- 'Changed event is still emitted after unregister because one observer remains.',
532
- );
533
- console.log('Changed value:');
534
- model.x = { y: 30 };
535
-
536
- stateManager.releaseState(model, 'x');
537
-
538
- console.log(
539
- 'Changed event is no longer emitted after the last observer unregisters.',
540
- );
541
- console.log('Changed value:');
542
- console.log('---');
543
- model.x = { y: 30 };
544
- } finally {
545
- changedSubscription.unsubscribe();
546
- }
547
- })();
548
- ```
549
-
550
- **Output:**
551
-
552
- ```console
553
- Initial value:
554
- { y: 10 }
555
-
556
- Changed value:
557
- { y: 20 }
558
-
559
- Changed event is still emitted after unregister because one observer remains.
560
- Changed value:
561
- { y: 30 }
562
- ```
563
-
564
- ---
565
-
566
- ## Support data types
567
-
568
- The state manager works by creating **observers** based on the data type of the registered state.
569
- It uses a chain of **observer factories**, each capable of determining whether it supports a particular type.
570
- The **first factory** that returns `true` is used.
571
-
572
- You can override this factory list by providing your own custom provider service.
573
-
574
- | Type | Index | Implementation | example |
575
- | ----------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------- | -------------------------------- |
576
- | Object | any field/property | Patching | [example](#object-propertyfield) |
577
- | Date | - year, utcYear<br>- month, utcMonth<br>- date, utcDate<br>- hours, utcHours<br>- minutes, utcMinutes<br>- seconds, utcSeconds<br>- milliseconds, utcMilliseconds<br>- times | Proxy | [example](#date) |
578
- | Array | number | Proxy | [example](#array) |
579
- | Map | any | Proxy | [example](#map) |
580
- | Set | Not indexable | Proxy | [example](#set) |
581
- | Promise | Not indexable | Attach `.then` handler | [example](#promise) |
582
- | Observable | Not indexable | Subscribe | [example](#observable) |
583
- | Custom type | user defined | user defined | [example](#customtype) |
584
-
585
- State item is identified by a **context**, **index** and **mustProxify** predicate for a recursive state item
586
- The manager checks each observer factory to determine support based on the **context** and **index**.
587
-
588
- Behavior:
589
-
590
- - Both recursive and non-recursive observers monitor **assignment** of a new value.
591
- - Recursive observers additionally monitor **internal changes** of the value. The nested values you want to monitor are determine by the **mustProxify** predicate.
592
-
593
- The following example illustrates the different state types:
594
-
595
- ### Object property/field
596
-
597
- **Example**
598
-
599
- ```ts
600
- import { InjectionContainer, printValue, Type } from '@rs-x/core';
601
- import {
602
- type IStateChange,
603
- type IStateManager,
604
- RsXStateManagerInjectionTokens,
605
- RsXStateManagerModule,
606
- watchIndexRecursiveRule,
607
- } from '@rs-x/state-manager';
608
-
609
- // Load the state manager module into the injection container
610
- InjectionContainer.load(RsXStateManagerModule);
611
-
612
- interface INestStateConext {
613
- a: number;
614
- nested?: INestStateConext;
615
- }
616
-
617
- class MyModel {
618
- private _b: INestStateConext = {
619
- a: 10,
620
- nested: {
621
- a: 20,
622
- nested: {
623
- a: 30,
624
- nested: {
625
- a: 40,
626
- },
627
- },
628
- },
629
- };
630
-
631
- public get b(): INestStateConext {
632
- return this._b;
633
- }
634
-
635
- public set b(value: INestStateConext) {
636
- this._b = value;
637
- }
638
- }
639
-
640
- export const run = (() => {
641
- const stateManager: IStateManager = InjectionContainer.get(
642
- RsXStateManagerInjectionTokens.IStateManager,
643
- );
644
-
645
- const model = new MyModel();
646
-
647
- const changeSubscription = stateManager.changed.subscribe(
648
- (change: IStateChange) => {
649
- printValue(change.newValue);
650
- },
651
- );
652
-
653
- try {
654
- // Observe property `b` recursively.
655
- // Otherwise, only assigning a new value to model.b would emit a change event.
656
- // This will emit a change event with the initial (current) value.
657
- console.log('Initial value:');
658
- stateManager.watchState(model, 'b', watchIndexRecursiveRule);
659
-
660
- console.log('\nReplacing model.b.nested.nested will emit a change event');
661
- console.log('Changed value:');
662
-
663
- (Type.toObject(model.b.nested) ?? {}).nested = {
664
- a: -30,
665
- nested: {
666
- a: -40,
667
- },
668
- };
9
+ ## Build
669
10
 
670
- console.log(`Latest value:`);
671
- printValue(stateManager.getState(model, 'b'));
672
- } finally {
673
- changeSubscription.unsubscribe();
674
- // Always release the state when it is no longer needed.
675
- stateManager.releaseState(model, 'b', watchIndexRecursiveRule);
676
- }
677
- })();
678
- ```
679
-
680
- **Output:**
681
-
682
- ```console
683
- Running demo: /Users/robertsanders/projects/rs-x/demo/src/rs-x-state-manager/register-property.ts
684
- Initial value:
685
- {
686
- a: 10,
687
- nested: {
688
- a: 20,
689
- nested: {
690
- a: 30,
691
- nested: {
692
- a: 40
693
- }
694
- }
695
- }
696
- }
697
-
698
- Replacing stateContext.b.nested.nested will emit a change event
699
- Changed value:
700
- {
701
- a: 10,
702
- nested: {
703
- a: 20,
704
- nested: {
705
- a: -30,
706
- nested: {
707
- a: -40
708
- }
709
- }
710
- }
711
- }
712
- Latest value:
713
- {
714
- a: 10,
715
- nested: {
716
- a: 20,
717
- nested: {
718
- a: -30,
719
- nested: {
720
- a: -40
721
- }
722
- }
723
- }
724
- }
725
- ```
726
-
727
- ### Date
728
-
729
- **Example**
730
-
731
- ```ts
732
- import { InjectionContainer, utCDate } from '@rs-x/core';
733
- import {
734
- type IProxyRegistry,
735
- type IStateChange,
736
- type IStateManager,
737
- RsXStateManagerInjectionTokens,
738
- RsXStateManagerModule,
739
- watchIndexRecursiveRule,
740
- } from '@rs-x/state-manager';
741
-
742
- // Load the state manager module into the injection container
743
- InjectionContainer.load(RsXStateManagerModule);
744
-
745
- function watchDate(stateManager: IStateManager) {
746
- console.log('\n******************************************');
747
- console.log('* Watching date');
748
- console.log('******************************************\n');
749
-
750
- const model = {
751
- date: utCDate(2021, 2, 5),
752
- };
753
- const changeSubscription = stateManager.changed.subscribe(
754
- (change: IStateChange) => {
755
- console.log(
756
- `${change.index}: ${(change.newValue as Date).toUTCString()}`,
757
- );
758
- },
759
- );
760
- try {
761
- console.log('Initial value:');
762
- stateManager.watchState(model, 'date', watchIndexRecursiveRule);
763
-
764
- console.log('Changed value:');
765
- model.date.setFullYear(2023);
766
-
767
- console.log('Set value:');
768
- model.date = new Date(2024, 5, 6);
769
-
770
- console.log('Latest value:');
771
- console.log(stateManager.getState<Date>(model, 'date').toUTCString());
772
- } finally {
773
- changeSubscription.unsubscribe();
774
- // Always release the state when it is no longer needed.
775
- stateManager.releaseState(model, 'date', watchIndexRecursiveRule);
776
- }
777
- }
778
-
779
- function watchDateProperty(stateManager: IStateManager) {
780
- console.log('\n******************************************');
781
- console.log('* Watching year');
782
- console.log('******************************************\n');
783
- const date = utCDate(2021, 2, 5);
784
- const changeSubscription = stateManager.changed.subscribe(
785
- (change: IStateChange) => {
786
- console.log(change.newValue);
787
- },
788
- );
789
- try {
790
- // This will emit a change event with the initial (current) value.
791
- console.log('Initial value:');
792
- stateManager.watchState(date, 'year');
793
-
794
- const proxyRegister: IProxyRegistry = InjectionContainer.get(
795
- RsXStateManagerInjectionTokens.IProxyRegistry,
796
- );
797
- const dateProxy = proxyRegister.getProxy<Date>(date);
798
- console.log('Changed value:');
799
- dateProxy.setFullYear(2023);
800
-
801
- console.log('Latest value:');
802
- console.log(stateManager.getState(date, 'year'));
803
- } finally {
804
- changeSubscription.unsubscribe();
805
- stateManager.releaseState(date, 'year');
806
- }
807
- }
808
-
809
- export const run = (() => {
810
- const stateManager: IStateManager = InjectionContainer.get(
811
- RsXStateManagerInjectionTokens.IStateManager,
812
- );
813
- watchDate(stateManager);
814
- watchDateProperty(stateManager);
815
- })();
816
- ```
817
-
818
- **Output:**
819
-
820
- ```console
821
- Running demo: demo/src/rs-x-state-manager/register-date.ts
822
-
823
- ******************************************
824
- * Watching date
825
- ******************************************
826
-
827
- Initial value:
828
- date: Fri, 05 Mar 2021 00:00:00 GMT
829
- Changed value:
830
- date: Sun, 05 Mar 2023 00:00:00 GMT
831
- Set value:
832
- date: Thu, 06 Jun 2024 00:00:00 GMT
833
- Latest value:
834
- Thu, 06 Jun 2024 00:00:00 GMT
835
-
836
- ******************************************
837
- * Watching year
838
- ******************************************
839
-
840
- Initial value:
841
- 2021
842
- Changed value:
843
- 2023
844
- Latest value:
845
- 2023
846
- ```
847
-
848
- ### Array
849
-
850
- **Example**
851
-
852
- ```ts
853
- import { InjectionContainer, printValue } from '@rs-x/core';
854
- import {
855
- type IStateChange,
856
- type IStateManager,
857
- RsXStateManagerInjectionTokens,
858
- RsXStateManagerModule,
859
- watchIndexRecursiveRule,
860
- } from '@rs-x/state-manager';
861
-
862
- // Load the state manager module into the injection container
863
- InjectionContainer.load(RsXStateManagerModule);
864
-
865
- export const run = (() => {
866
- const stateManager: IStateManager = InjectionContainer.get(
867
- RsXStateManagerInjectionTokens.IStateManager,
868
- );
869
-
870
- const model = {
871
- array: [
872
- [1, 2],
873
- [3, 4],
874
- ],
875
- };
876
-
877
- const changeSubscription = stateManager.changed.subscribe(
878
- (change: IStateChange) => {
879
- printValue(change.newValue);
880
- },
881
- );
882
-
883
- try {
884
- // This will emit a change event with the initial (current) value.
885
- console.log('Initial value:');
886
- stateManager.watchState(model, 'array', watchIndexRecursiveRule);
887
-
888
- console.log('Changed value:');
889
- model.array[1].push(5);
890
-
891
- console.log('Latest value:');
892
- printValue(stateManager.getState(model, 'array'));
893
- } finally {
894
- changeSubscription.unsubscribe();
895
- // Always release the state when it is no longer needed.
896
- stateManager.releaseState(model, 'array', watchIndexRecursiveRule);
897
- }
898
- })();
899
- ```
900
-
901
- **Output:**
902
-
903
- ```console
904
- Running demo: /Users/robertsanders/projects/rs-x/demo/src/rs-x-state-manager/register-array.ts
905
- Initial value:
906
- [
907
- [
908
- 1,
909
- 2
910
- ],
911
- [
912
- 3,
913
- 4
914
- ]
915
- ]
916
- Changed value:
917
- [
918
- [
919
- 1,
920
- 2
921
- ],
922
- [
923
- 3,
924
- 4,
925
- 5
926
- ]
927
- ]
928
- Latest value:
929
- [
930
- [
931
- 1,
932
- 2
933
- ],
934
- [
935
- 3,
936
- 4,
937
- 5
938
- ]
939
- ]
940
- ```
941
-
942
- ### Map
943
-
944
- **Example**
945
-
946
- ```ts
947
- import { InjectionContainer, printValue } from '@rs-x/core';
948
- import {
949
- type IStateChange,
950
- type IStateManager,
951
- RsXStateManagerInjectionTokens,
952
- RsXStateManagerModule,
953
- watchIndexRecursiveRule,
954
- } from '@rs-x/state-manager';
955
-
956
- // Load the state manager module into the injection container
957
- InjectionContainer.load(RsXStateManagerModule);
958
-
959
- const stateManager: IStateManager = InjectionContainer.get(
960
- RsXStateManagerInjectionTokens.IStateManager,
961
- );
962
-
963
- export const run = (() => {
964
- const model = {
965
- map: new Map([
966
- ['a', [1, 2]],
967
- ['b', [3, 4]],
968
- ]),
969
- };
970
-
971
- const changeSubscription = stateManager.changed.subscribe(
972
- (change: IStateChange) => {
973
- printValue(change.newValue);
974
- },
975
- );
976
-
977
- try {
978
- // This will emit a change event with the initial (current) value.
979
- console.log('Initial value:');
980
- stateManager.watchState(model, 'map', watchIndexRecursiveRule);
981
-
982
- console.log('Changed value:');
983
- model.map.get('b')?.push(5);
984
-
985
- console.log('Latest value:');
986
- printValue(stateManager.getState(model, 'map'));
987
- } finally {
988
- changeSubscription.unsubscribe();
989
- // Always release the state when it is no longer needed.
990
- stateManager.releaseState(model, 'array', watchIndexRecursiveRule);
991
- }
992
- })();
993
- ```
994
-
995
- **Output:**
996
-
997
- ```console
998
- Running demo: /Users/robertsanders/projects/rs-x/demo/src/rs-x-state-manager/register-map.ts
999
- Initial value:
1000
- [
1001
- [
1002
- a,
1003
- [
1004
- 1,
1005
- 2
1006
- ]
1007
- ],
1008
- [
1009
- b,
1010
- [
1011
- 3,
1012
- 4
1013
- ]
1014
- ]
1015
- ]
1016
- Changed value:
1017
- [
1018
- [
1019
- a,
1020
- [
1021
- 1,
1022
- 2
1023
- ]
1024
- ],
1025
- [
1026
- b,
1027
- [
1028
- 3,
1029
- 4,
1030
- 5
1031
- ]
1032
- ]
1033
- ]
1034
- Latest value:
1035
- [
1036
- [
1037
- a,
1038
- [
1039
- 1,
1040
- 2
1041
- ]
1042
- ],
1043
- [
1044
- b,
1045
- [
1046
- 3,
1047
- 4,
1048
- 5
1049
- ]
1050
- ]
1051
- ]
1052
- ```
1053
-
1054
- ### Set
1055
-
1056
- **Example**
1057
-
1058
- ```ts
1059
- import { InjectionContainer, printValue } from '@rs-x/core';
1060
- import {
1061
- type IProxyRegistry,
1062
- type IStateChange,
1063
- type IStateManager,
1064
- RsXStateManagerInjectionTokens,
1065
- RsXStateManagerModule,
1066
- watchIndexRecursiveRule,
1067
- } from '@rs-x/state-manager';
1068
-
1069
- // Load the state manager module into the injection container
1070
- InjectionContainer.load(RsXStateManagerModule);
1071
-
1072
- export const run = (() => {
1073
- const stateManager: IStateManager = InjectionContainer.get(
1074
- RsXStateManagerInjectionTokens.IStateManager,
1075
- );
1076
- const item1 = [1, 2];
1077
- const item2 = [3, 4];
1078
- const model = {
1079
- set: new Set([item1, item2]),
1080
- };
1081
- const changeSubscription = stateManager.changed.subscribe(
1082
- (change: IStateChange) => {
1083
- printValue(change.newValue);
1084
- },
1085
- );
1086
-
1087
- try {
1088
- // This will emit a change event with the initial (current) value.
1089
- console.log('Initial value:');
1090
- stateManager.watchState(model, 'set', watchIndexRecursiveRule);
1091
-
1092
- console.log('Changed value:');
1093
- const proxyRegister: IProxyRegistry = InjectionContainer.get(
1094
- RsXStateManagerInjectionTokens.IProxyRegistry,
1095
- );
1096
- proxyRegister.getProxy<number[]>(item2).push(5);
1097
-
1098
- console.log('Latest value:');
1099
- printValue(stateManager.getState(model, 'set'));
1100
- } finally {
1101
- changeSubscription.unsubscribe();
1102
- // Always release the state when it is no longer needed.
1103
- stateManager.releaseState(model, 'set', watchIndexRecursiveRule);
1104
- }
1105
- })();
1106
- ```
1107
-
1108
- **Output:**
1109
-
1110
- ```console
1111
- Running demo: /Users/robertsanders/projects/rs-x/demo/src/rs-x-state-manager/register-set.ts
1112
- Initial value:
1113
- [
1114
- [
1115
- 1,
1116
- 2
1117
- ],
1118
- [
1119
- 3,
1120
- 4
1121
- ]
1122
- ]
1123
- Changed value:
1124
- [
1125
- [
1126
- 1,
1127
- 2
1128
- ],
1129
- [
1130
- 3,
1131
- 4,
1132
- 5
1133
- ]
1134
- ]
1135
- Latest value:
1136
- [
1137
- [
1138
- 1,
1139
- 2
1140
- ],
1141
- [
1142
- 3,
1143
- 4,
1144
- 5
1145
- ]
1146
- ]
1147
- ```
1148
-
1149
- ### Promise
1150
-
1151
- **Example**
1152
-
1153
- ```ts
1154
- import { InjectionContainer, WaitForEvent } from '@rs-x/core';
1155
- import {
1156
- type IStateChange,
1157
- type IStateManager,
1158
- RsXStateManagerInjectionTokens,
1159
- RsXStateManagerModule,
1160
- } from '@rs-x/state-manager';
1161
-
1162
- // Load the state manager module into the injection container
1163
- InjectionContainer.load(RsXStateManagerModule);
1164
-
1165
- export const run = (async () => {
1166
- const stateManager: IStateManager = InjectionContainer.get(
1167
- RsXStateManagerInjectionTokens.IStateManager,
1168
- );
1169
-
1170
- const model = {
1171
- promise: Promise.resolve(10),
1172
- };
1173
- const changeSubscription = stateManager.changed.subscribe(
1174
- (change: IStateChange) => {
1175
- console.log(change.newValue);
1176
- },
1177
- );
1178
-
1179
- try {
1180
- await new WaitForEvent(stateManager, 'changed').wait(() => {
1181
- // This will emit a change event with the initial (current) value.
1182
- console.log('Initial value:');
1183
- stateManager.watchState(model, 'promise');
1184
- });
1185
-
1186
- await new WaitForEvent(stateManager, 'changed').wait(() => {
1187
- console.log('Changed value:');
1188
- let resolveHandler!: (value: number) => void;
1189
-
1190
- model.promise = new Promise<number>((resolve) => {
1191
- resolveHandler = resolve;
1192
- });
1193
-
1194
- resolveHandler(30);
1195
- });
1196
-
1197
- console.log(`Latest value: ${stateManager.getState(model, 'promise')}`);
1198
- } finally {
1199
- changeSubscription.unsubscribe();
1200
- // Always release the state when it is no longer needed.
1201
- stateManager.releaseState(model, 'promise');
1202
- }
1203
- })();
1204
- ```
1205
-
1206
- **Output:**
1207
-
1208
- ```console
1209
- Running demo: /Users/robertsanders/projects/rs-x/demo/src/rs-x-state-manager/register-promise.ts
1210
- Initial value:
1211
- 10
1212
- Changed value:
1213
- 30
1214
- Latest value: 30
1215
- ```
1216
-
1217
- ### Observable
1218
-
1219
- **Example**
1220
-
1221
- ```ts
1222
- import { of, Subject } from 'rxjs';
1223
-
1224
- import { InjectionContainer, WaitForEvent } from '@rs-x/core';
1225
- import {
1226
- type IStateChange,
1227
- type IStateManager,
1228
- RsXStateManagerInjectionTokens,
1229
- RsXStateManagerModule,
1230
- } from '@rs-x/state-manager';
1231
-
1232
- // Load the state manager module into the injection container
1233
- InjectionContainer.load(RsXStateManagerModule);
1234
-
1235
- export const run = (async () => {
1236
- const stateManager: IStateManager = InjectionContainer.get(
1237
- RsXStateManagerInjectionTokens.IStateManager,
1238
- );
1239
-
1240
- const model = {
1241
- observable: of(10),
1242
- };
1243
-
1244
- const changeSubscription = stateManager.changed.subscribe(
1245
- (change: IStateChange) => {
1246
- console.log(change.newValue);
1247
- },
1248
- );
1249
-
1250
- try {
1251
- // We need to wait here until the event is emitted,
1252
- // otherwise the demo will exit before the change event occurs.
1253
- await new WaitForEvent(stateManager, 'changed').wait(() => {
1254
- // This will emit a change event with the initial (current) value.
1255
- console.log('Initial value:');
1256
- stateManager.watchState(model, 'observable');
1257
- });
1258
-
1259
- await new WaitForEvent(stateManager, 'changed').wait(() => {
1260
- console.log('Changed value:');
1261
- const subject = new Subject<number>();
1262
- model.observable = subject;
1263
- subject.next(30);
1264
- });
1265
-
1266
- console.log(`Latest value: ${stateManager.getState(model, 'observable')}`);
1267
- } finally {
1268
- changeSubscription.unsubscribe();
1269
- // Always release the state when it is no longer needed.
1270
- stateManager.releaseState(model, 'observable');
1271
- }
1272
- })();
1273
- ```
1274
-
1275
- **Output:**
1276
-
1277
- ```console
1278
- Running demo: /Users/robertsanders/projects/rs-x/demo/src/rs-x-state-manager/register-observable.ts
1279
- Initial value:
1280
- 10
1281
- Changed value:
1282
- 30
1283
- Latest value: 30
1284
- ```
1285
-
1286
- ### Custom type
1287
-
1288
- 1. Create an accessor to retrieve index values on your type.
1289
- 2. Create a factory to create an observer for your data type.
1290
- 3. Create a factory to create an observer for an index on your data instance.
1291
-
1292
- The following example demonstrates adding support for a custom `TextDocument` class:
1293
-
1294
- **Example**
1295
-
1296
- ````ts
1297
- import { ReplaySubject, Subscription } from 'rxjs';
1298
-
1299
- import {
1300
- ContainerModule,
1301
- defaultIndexValueAccessorList,
1302
- type IDisposableOwner,
1303
- type IErrorLog,
1304
- type IGuidFactory,
1305
- type IIndexValueAccessor,
1306
- Inject,
1307
- Injectable,
1308
- InjectionContainer,
1309
- type IPropertyChange,
1310
- type IValueMetadata,
1311
- overrideMultiInjectServices,
1312
- RsXCoreInjectionTokens,
1313
- SingletonFactory,
1314
- Type,
1315
- } from '@rs-x/core';
1316
- import {
1317
- AbstractObserver,
1318
- defaultObjectObserverProxyPairFactoryList,
1319
- defaultPropertyObserverProxyPairFactoryList,
1320
- type IIndexObserverInfo,
1321
- IndexObserverProxyPairFactory,
1322
- type IObjectObserverProxyPairFactory,
1323
- type IObjectObserverProxyPairManager,
1324
- type IObserverProxyPair,
1325
- type IPropertyInfo,
1326
- type IProxyRegistry,
1327
- type IProxyTarget,
1328
- type IStateChange,
1329
- type IStateManager,
1330
- RsXStateManagerInjectionTokens,
1331
- RsXStateManagerModule,
1332
- watchIndexRecursiveRule,
1333
- } from '@rs-x/state-manager';
1334
-
1335
- const MyInjectTokens = {
1336
- TextDocumentObserverManager: Symbol('TextDocumentObserverManager'),
1337
- TextDocumenIndexObserverManager: Symbol('TextDocumenIndexObserverManager'),
1338
- TextDocumentIndexAccessor: Symbol('TextDocumentIndexAccessor'),
1339
- TextDocumentObserverProxyPairFactory: Symbol(
1340
- 'TextDocumentObserverProxyPairFactory',
1341
- ),
1342
- TextDocumentInxdexObserverProxyPairFactory: Symbol(
1343
- 'TextDocumentInxdexObserverProxyPairFactory',
1344
- ),
1345
- };
1346
-
1347
- class IndexForTextDocumentxObserverManager extends SingletonFactory<
1348
- number,
1349
- IIndexObserverInfo<ITextDocumentIndex>,
1350
- TextDocumentIndexObserver
1351
- > {
1352
- constructor(
1353
- private readonly _textDocument: TextDocument,
1354
- private readonly _textDocumentObserverManager: TextDocumentObserverManager,
1355
- private readonly releaseOwner: () => void,
1356
- ) {
1357
- super();
1358
- }
1359
-
1360
- public override getId(
1361
- indexObserverInfo: IIndexObserverInfo<ITextDocumentIndex>,
1362
- ): number {
1363
- return this.createId(indexObserverInfo);
1364
- }
1365
-
1366
- protected override createInstance(
1367
- indexObserverInfo: IIndexObserverInfo<ITextDocumentIndex>,
1368
- id: number,
1369
- ): TextDocumentIndexObserver {
1370
- const textDocumentObserver = this._textDocumentObserverManager.create(
1371
- this._textDocument,
1372
- ).instance;
1373
- return new TextDocumentIndexObserver(
1374
- {
1375
- canDispose: () => this.getReferenceCount(id) === 1,
1376
- release: () => {
1377
- textDocumentObserver.dispose();
1378
- this.release(id);
1379
- },
1380
- },
1381
- textDocumentObserver,
1382
- indexObserverInfo.index,
1383
- );
1384
- }
1385
-
1386
- protected override createId(
1387
- indexObserverInfo: IIndexObserverInfo<ITextDocumentIndex>,
1388
- ): number {
1389
- // Using Cantor pairing to create a unique id from page and line index
1390
- const { pageIndex, lineIndex } = indexObserverInfo.index;
1391
- return (
1392
- ((pageIndex + lineIndex) * (pageIndex + lineIndex + 1)) / 2 + lineIndex
1393
- );
1394
- }
1395
-
1396
- protected override onReleased(): void {
1397
- if (this.isEmpty) {
1398
- this.releaseOwner();
1399
- }
1400
- }
1401
- }
1402
-
1403
- // We want to ensure that for the same TextDocument we always have the same observer
1404
- @Injectable()
1405
- class TextDocumentObserverManager extends SingletonFactory<
1406
- TextDocument,
1407
- TextDocument,
1408
- TextDocumentObserver
1409
- > {
1410
- constructor(
1411
- @Inject(RsXStateManagerInjectionTokens.IProxyRegistry)
1412
- private readonly _proxyRegister: IProxyRegistry,
1413
- ) {
1414
- super();
1415
- }
1416
-
1417
- public override getId(textDocument: TextDocument): TextDocument {
1418
- return textDocument;
1419
- }
1420
-
1421
- protected override createInstance(
1422
- textDocument: TextDocument,
1423
- id: TextDocument,
1424
- ): TextDocumentObserver {
1425
- return new TextDocumentObserver(textDocument, this._proxyRegister, {
1426
- canDispose: () => this.getReferenceCount(id) === 1,
1427
- release: () => this.release(id),
1428
- });
1429
- }
1430
-
1431
- protected override createId(textDocument: TextDocument): TextDocument {
1432
- return textDocument;
1433
- }
1434
- }
1435
-
1436
- // We want to ensure we create only one index-manager per TextDocument
1437
- @Injectable()
1438
- export class TextDocumenIndexObserverManager extends SingletonFactory<
1439
- TextDocument,
1440
- TextDocument,
1441
- IndexForTextDocumentxObserverManager
1442
- > {
1443
- constructor(
1444
- @Inject(MyInjectTokens.TextDocumentObserverManager)
1445
- private readonly _textDocumentObserverManager: TextDocumentObserverManager,
1446
- ) {
1447
- super();
1448
- }
1449
-
1450
- public override getId(textDocument: TextDocument): TextDocument {
1451
- return textDocument;
1452
- }
1453
-
1454
- protected override createId(textDocument: TextDocument): TextDocument {
1455
- return textDocument;
1456
- }
1457
-
1458
- protected override createInstance(
1459
- textDocument: TextDocument,
1460
- ): IndexForTextDocumentxObserverManager {
1461
- return new IndexForTextDocumentxObserverManager(
1462
- textDocument,
1463
- this._textDocumentObserverManager,
1464
- () => this.release(textDocument),
1465
- );
1466
- }
1467
-
1468
- protected override releaseInstance(
1469
- indexForTextDocumentxObserverManager: IndexForTextDocumentxObserverManager,
1470
- ): void {
1471
- indexForTextDocumentxObserverManager.dispose();
1472
- }
1473
- }
1474
-
1475
- @Injectable()
1476
- export class TextDocumentIndexAccessor implements IIndexValueAccessor<
1477
- TextDocument,
1478
- ITextDocumentIndex
1479
- > {
1480
- public readonly priority!: 200;
1481
-
1482
- public hasValue(
1483
- textDocument: TextDocument,
1484
- index: ITextDocumentIndex,
1485
- ): boolean {
1486
- return textDocument.getLine(index) !== undefined;
1487
- }
1488
-
1489
- // We don’t have any properties that can be iterated through.
1490
- public getIndexes(): IterableIterator<ITextDocumentIndex> {
1491
- return [].values();
1492
- }
1493
-
1494
- // Here it is the same as getValue.
1495
- // For example, for a Promise accessor getValue returns the promise
1496
- // and getResolvedValue returns the resolved promise value
1497
- public getResolvedValue(
1498
- textDocument: TextDocument,
1499
- index: ITextDocumentIndex,
1500
- ): string | undefined {
1501
- return this.getValue(textDocument, index);
1502
- }
1503
-
1504
- public getValue(
1505
- textDocument: TextDocument,
1506
- index: ITextDocumentIndex,
1507
- ): string | undefined {
1508
- return textDocument.getLine(index);
1509
- }
1510
-
1511
- public setValue(
1512
- textDocument: TextDocument,
1513
- index: ITextDocumentIndex,
1514
- value: string,
1515
- ): void {
1516
- textDocument.setLine(index, value);
1517
- }
1518
-
1519
- public applies(textDocument: unknown, _index: ITextDocumentIndex): boolean {
1520
- return textDocument instanceof TextDocument;
1521
- }
1522
- }
1523
-
1524
- @Injectable()
1525
- export class TextDocumentInxdexObserverProxyPairFactory extends IndexObserverProxyPairFactory<
1526
- TextDocument,
1527
- unknown
1528
- > {
1529
- constructor(
1530
- @Inject(RsXStateManagerInjectionTokens.IObjectObserverProxyPairManager)
1531
- objectObserverManager: IObjectObserverProxyPairManager,
1532
- @Inject(MyInjectTokens.TextDocumenIndexObserverManager)
1533
- textDocumenIndexObserverManager: TextDocumenIndexObserverManager,
1534
- @Inject(RsXCoreInjectionTokens.IErrorLog)
1535
- errorLog: IErrorLog,
1536
- @Inject(RsXCoreInjectionTokens.IGuidFactory)
1537
- guidFactory: IGuidFactory,
1538
- @Inject(RsXCoreInjectionTokens.IIndexValueAccessor)
1539
- indexValueAccessor: IIndexValueAccessor,
1540
- @Inject(RsXStateManagerInjectionTokens.IProxyRegistry)
1541
- proxyRegister: IProxyRegistry,
1542
- @Inject(RsXCoreInjectionTokens.IValueMetadata)
1543
- valueMetadata: IValueMetadata,
1544
- ) {
1545
- super(
1546
- objectObserverManager,
1547
- Type.cast(textDocumenIndexObserverManager),
1548
- errorLog,
1549
- guidFactory,
1550
- indexValueAccessor,
1551
- proxyRegister,
1552
- valueMetadata,
1553
- );
1554
- }
1555
-
1556
- public applies(object: unknown, propertyInfo: IPropertyInfo): boolean {
1557
- const documentKey = propertyInfo.index as ITextDocumentIndex;
1558
- return (
1559
- object instanceof TextDocument &&
1560
- documentKey?.lineIndex >= 0 &&
1561
- documentKey?.pageIndex >= 0
1562
- );
1563
- }
1564
- }
1565
-
1566
- @Injectable()
1567
- export class TextDocumentObserverProxyPairFactory implements IObjectObserverProxyPairFactory {
1568
- public readonly priority = 100;
1569
-
1570
- constructor(
1571
- @Inject(MyInjectTokens.TextDocumentObserverManager)
1572
- private readonly _textDocumentObserverManager: TextDocumentObserverManager,
1573
- ) {}
1574
-
1575
- public create(
1576
- _: IDisposableOwner,
1577
- proxyTarget: IProxyTarget<TextDocument>,
1578
- ): IObserverProxyPair<TextDocument> {
1579
- const observer = this._textDocumentObserverManager.create(
1580
- proxyTarget.target,
1581
- ).instance;
1582
- return {
1583
- observer,
1584
- proxy: observer.target as TextDocument,
1585
- proxyTarget: proxyTarget.target,
1586
- };
1587
- }
1588
-
1589
- public applies(object: unknown): boolean {
1590
- return object instanceof TextDocument;
1591
- }
1592
- }
1593
-
1594
- interface ITextDocumentIndex {
1595
- pageIndex: number;
1596
- lineIndex: number;
1597
- }
1598
-
1599
- class TextDocument {
1600
- private readonly _pages = new Map<number, Map<number, string>>();
1601
- constructor(pages?: string[][]) {
1602
- pages?.forEach((page, pageIndex) => {
1603
- const pageText = new Map<number, string>();
1604
-
1605
- this._pages.set(pageIndex, pageText);
1606
- page.forEach((lineText, lineIndex) => {
1607
- pageText.set(lineIndex, lineText);
1608
- });
1609
- });
1610
- }
1611
-
1612
- public toString(): string {
1613
- const pages: string[] = [];
1614
-
1615
- // Sort pages by pageIndex
1616
- const sortedPageIndexes = Array.from(this._pages.keys()).sort(
1617
- (a, b) => a - b,
1618
- );
1619
-
1620
- for (const pageIndex of sortedPageIndexes) {
1621
- const page = this._pages.get(pageIndex);
1622
- if (!page) {
1623
- continue;
1624
- }
1625
-
1626
- // Sort lines by lineIndex
1627
- const sortedLineIndexes = Array.from(page.keys()).sort((a, b) => a - b);
1628
-
1629
- const lines = sortedLineIndexes.map(
1630
- (lineIndex) => ` ${lineIndex}: ${page.get(lineIndex)}`,
1631
- );
1632
- pages.push(`Page ${pageIndex}:\n${lines.join('\n')}`);
1633
- }
1634
-
1635
- return pages.join('\n\n');
1636
- }
1637
-
1638
- public setLine(index: ITextDocumentIndex, text: string): void {
1639
- const { pageIndex, lineIndex } = index;
1640
- let page = this._pages.get(pageIndex);
1641
- if (!page) {
1642
- page = new Map();
1643
- this._pages.set(pageIndex, page);
1644
- }
1645
-
1646
- page.set(lineIndex, text);
1647
- }
1648
-
1649
- public getLine(index: ITextDocumentIndex): string | undefined {
1650
- const { pageIndex, lineIndex } = index;
1651
- return this._pages.get(pageIndex)?.get(lineIndex);
1652
- }
1653
- }
1654
-
1655
- class TextDocumentIndexObserver extends AbstractObserver<
1656
- TextDocument,
1657
- string,
1658
- ITextDocumentIndex
1659
- > {
1660
- private readonly _changeSubscription: Subscription;
1661
-
1662
- constructor(
1663
- owner: IDisposableOwner,
1664
- private readonly _observer: TextDocumentObserver,
1665
- index: ITextDocumentIndex,
1666
- ) {
1667
- super(
1668
- owner,
1669
- _observer.target,
1670
- _observer.target.getLine(index),
1671
- new ReplaySubject(),
1672
- index,
1673
- );
1674
- this._changeSubscription = _observer.changed.subscribe(this.onChange);
1675
- }
1676
-
1677
- protected override disposeInternal(): void {
1678
- this._changeSubscription.unsubscribe();
1679
- this._observer.dispose();
1680
- }
1681
-
1682
- private readonly onChange = (change: IPropertyChange) => {
1683
- const changeIndex = change.index as ITextDocumentIndex;
1684
- if (
1685
- changeIndex.lineIndex === this.id?.lineIndex &&
1686
- changeIndex.pageIndex === this.id?.pageIndex
1687
- ) {
1688
- this.emitChange(change);
1689
- }
1690
- };
1691
- }
1692
-
1693
- class TextDocumentObserver extends AbstractObserver<TextDocument> {
1694
- constructor(
1695
- textDocument: TextDocument,
1696
- private readonly _proxyRegister: IProxyRegistry,
1697
- owner?: IDisposableOwner,
1698
- ) {
1699
- super(owner, Type.cast(undefined), textDocument);
1700
-
1701
- this.target = new Proxy(textDocument, this);
1702
-
1703
- // Always register a proxy at the proxy registry
1704
- // so we can determine if an instance is a proxy or not.
1705
- this._proxyRegister.register(textDocument, this.target);
1706
- }
1707
-
1708
- protected override disposeInternal(): void {
1709
- this._proxyRegister.unregister(this.value);
1710
- }
1711
-
1712
- public get(
1713
- textDocument: TextDocument,
1714
- property: PropertyKey,
1715
- receiver: unknown,
1716
- ): unknown {
1717
- if (property == 'setLine') {
1718
- return (index: ITextDocumentIndex, text: string) => {
1719
- textDocument.setLine(index, text);
1720
- this.emitChange({
1721
- arguments: [],
1722
- index: index,
1723
- target: textDocument,
1724
- newValue: text,
1725
- });
1726
- };
1727
- } else {
1728
- return Reflect.get(textDocument, property, receiver);
1729
- }
1730
- }
1731
- }
1732
-
1733
- // Load the state manager module into the injection container
1734
- InjectionContainer.load(RsXStateManagerModule);
1735
-
1736
- const MyModule = new ContainerModule((options) => {
1737
- options
1738
- .bind<TextDocumentObserverManager>(
1739
- MyInjectTokens.TextDocumentObserverManager,
1740
- )
1741
- .to(TextDocumentObserverManager)
1742
- .inSingletonScope();
1743
-
1744
- options
1745
- .bind<TextDocumenIndexObserverManager>(
1746
- MyInjectTokens.TextDocumenIndexObserverManager,
1747
- )
1748
- .to(TextDocumenIndexObserverManager)
1749
- .inSingletonScope();
1750
-
1751
- overrideMultiInjectServices(
1752
- options,
1753
- RsXCoreInjectionTokens.IIndexValueAccessorList,
1754
- [
1755
- {
1756
- target: TextDocumentIndexAccessor,
1757
- token: MyInjectTokens.TextDocumentIndexAccessor,
1758
- },
1759
- ...defaultIndexValueAccessorList,
1760
- ],
1761
- );
1762
-
1763
- overrideMultiInjectServices(
1764
- options,
1765
- RsXStateManagerInjectionTokens.IObjectObserverProxyPairFactoryList,
1766
- [
1767
- {
1768
- target: TextDocumentObserverProxyPairFactory,
1769
- token: MyInjectTokens.TextDocumentObserverProxyPairFactory,
1770
- },
1771
- ...defaultObjectObserverProxyPairFactoryList,
1772
- ],
1773
- );
1774
-
1775
- overrideMultiInjectServices(
1776
- options,
1777
- RsXStateManagerInjectionTokens.IPropertyObserverProxyPairFactoryList,
1778
- [
1779
- {
1780
- target: TextDocumentInxdexObserverProxyPairFactory,
1781
- token: MyInjectTokens.TextDocumentInxdexObserverProxyPairFactory,
1782
- },
1783
- ...defaultPropertyObserverProxyPairFactoryList,
1784
- ],
1785
- );
1786
- });
1787
-
1788
- InjectionContainer.load(MyModule);
1789
-
1790
- function testMonitorTextDocument(
1791
- stateManager: IStateManager,
1792
- model: { myBook: TextDocument },
1793
- ): void {
1794
- const bookSubscription = stateManager.changed.subscribe(() => {
1795
- console.log(model.myBook.toString());
1796
- });
1797
-
1798
- // We observe the whole book
1799
- // This will use TextDocumentObserverProxyPairFactory
1800
- try {
1801
- console.log('\n***********************************************');
1802
- console.log('Start watching the whole book\n');
1803
- console.log('My initial book:\n');
1804
- stateManager.watchState(model, 'myBook', watchIndexRecursiveRule);
1805
-
1806
- console.log('\nUpdate second line on the first page:\n');
1807
- console.log('My book after change:\n');
1808
- model.myBook.setLine(
1809
- { pageIndex: 0, lineIndex: 1 },
1810
- 'In a far far away land',
1811
- );
1812
- } finally {
1813
- // Stop monitoring the whole book
1814
- stateManager.releaseState(model, 'myBook', watchIndexRecursiveRule);
1815
- bookSubscription.unsubscribe();
1816
- }
1817
- }
1818
-
1819
- function testMonitoreSpecificLineInDocument(
1820
- stateManager: IStateManager,
1821
- model: { myBook: TextDocument },
1822
- ): void {
1823
- const line3OnPage1Index = { pageIndex: 0, lineIndex: 2 };
1824
- const lineSubscription = stateManager.changed.subscribe(
1825
- (change: IStateChange) => {
1826
- const documentIndex = change.index as ITextDocumentIndex;
1827
- console.log(
1828
- `Line ${documentIndex.lineIndex + 1} on page ${documentIndex.pageIndex + 1} has changed to '${change.newValue}'`,
1829
- );
1830
- console.log('My book after change:\n');
1831
- console.log(model.myBook.toString());
1832
- },
1833
- );
1834
-
1835
- try {
1836
- // Here we only watch line 3 on page 1.
1837
- // Notice that the line does not have to exist yet.
1838
- // The initial book does not have a line 3 on page 1.
1839
- //
1840
- // TextDocumentInxdexObserverProxyPairFactory is used here
1841
-
1842
- console.log('\n***********************************************');
1843
- console.log('Start watching line 3 on page 1\n');
1844
- stateManager.watchState(model.myBook, line3OnPage1Index);
1845
-
1846
- const proxRegistry: IProxyRegistry = InjectionContainer.get(
1847
- RsXStateManagerInjectionTokens.IProxyRegistry,
1848
- );
1849
- const bookProxy: TextDocument = proxRegistry.getProxy(model.myBook);
1850
-
1851
- bookProxy.setLine(line3OnPage1Index, 'a prince was born');
1852
-
1853
- console.log('\nChanging line 1 on page 1 does not emit change:');
1854
- console.log('---');
1855
- bookProxy.setLine({ pageIndex: 0, lineIndex: 0 }, 'a troll was born');
1856
- } finally {
1857
- // Stop monitoring line 3 on page 1.
1858
- stateManager.releaseState(model.myBook, line3OnPage1Index);
1859
- lineSubscription.unsubscribe();
1860
- }
1861
- }
1862
-
1863
- export const run = (() => {
1864
- const stateManager: IStateManager = InjectionContainer.get(
1865
- RsXStateManagerInjectionTokens.IStateManager,
1866
- );
1867
- const model = {
1868
- myBook: new TextDocument([
1869
- ['Once upon a time', 'bla bla'],
1870
- ['bla bla', 'They lived happily ever after.', 'The end'],
1871
- ]),
1872
- };
1873
- testMonitorTextDocument(stateManager, model);
1874
- testMonitoreSpecificLineInDocument(stateManager, model);
1875
- })();
1876
-
1877
- ```nclude_relative ../demo/src/rs-x-state-manager/register-set.ts %}
1878
- ````
1879
-
1880
- **Output:**
1881
-
1882
- ```console
1883
- Running demo: /Users/robertsanders/projects/rs-x/demo/src/rs-x-state-manager/state-manager-customize.ts
1884
-
1885
- ***********************************************
1886
- Start watching the whole book
1887
-
1888
- My initial book:
1889
-
1890
- Page 0:
1891
- 0: Once upon a time
1892
- 1: bla bla
1893
-
1894
- Page 1:
1895
- 0: bla bla
1896
- 1: They lived happily ever after.
1897
- 2: The end
1898
-
1899
- Update second line on the first page:
1900
-
1901
- My book after change:
1902
-
1903
- Page 0:
1904
- 0: Once upon a time
1905
- 1: In a far far away land
1906
-
1907
- Page 1:
1908
- 0: bla bla
1909
- 1: They lived happily ever after.
1910
- 2: The end
1911
-
1912
- ***********************************************
1913
- Start watching line 3 on page 1
1914
-
1915
- Line 3 on page 1 has changed to 'a prince was born'
1916
- My book after change:
1917
-
1918
- Page 0:
1919
- 0: Once upon a time
1920
- 1: In a far far away land
1921
- 2: a prince was born
1922
-
1923
- Page 1:
1924
- 0: bla bla
1925
- 1: They lived happily ever after.
1926
- 2: The end
1927
-
1928
- Changing line 1 on page 1 does not emit change:
1929
- ---
11
+ ```bash
12
+ pnpm run build:state-manager
1930
13
  ```