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