async-reactivity 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,148 @@
1
+ import Dependency from "./dependency";
2
+ import Dependent from "./dependent";
3
+ import Tracker from "./tracker";
4
+
5
+ declare type TrackValue = <T>(dependency: Dependency<T>) => T;
6
+ export declare type ComputeFunc<T> = (value: TrackValue) => T;
7
+ export declare type ComputeFuncScoped<T1, T2> = (value: TrackValue, scope: T1) => T2;
8
+
9
+ enum ComputedState {
10
+ Invalid,
11
+ Valid,
12
+ Uncertain,
13
+ Computing
14
+ };
15
+
16
+ class CircularDependencyError extends Error { }
17
+
18
+ export default class Computed<T> extends Tracker<T> implements Dependent, Dependency<T> {
19
+ getter: ComputeFunc<T>;
20
+ private state = ComputedState.Invalid;
21
+ private dependencies = new Map<Dependency<any>, boolean>();
22
+ private computePromise?: T;
23
+ private computePromiseActions?: { resolve: Function, reject: Function };
24
+ private lastComputeAttemptPromise?: Promise<void>;
25
+
26
+ constructor(getter: ComputeFunc<T>) {
27
+ super();
28
+ this.getter = getter;
29
+ this.prepareComputePromise();
30
+ }
31
+
32
+ private prepareComputePromise() {
33
+ this.computePromise = new Promise((resolve, reject) => {
34
+ this.computePromiseActions = {
35
+ resolve,
36
+ reject
37
+ };
38
+ }) as unknown as T;
39
+ }
40
+
41
+ public get value(): T {
42
+ if (this.state === ComputedState.Invalid || this.state === ComputedState.Uncertain) {
43
+ return this.compute();
44
+ }
45
+
46
+ return this._value!;
47
+ }
48
+
49
+ private compute() {
50
+ if (this.state === ComputedState.Uncertain) {
51
+ for (const dependency of this.dependencies.keys()) {
52
+ this.dependencies.set(dependency, true);
53
+ }
54
+ if ([...this.dependencies.keys()].every(d => {
55
+ d.value;
56
+ return !this.dependencies.get(d);
57
+ })) {
58
+ this.finalizeComputing();
59
+ this.validateDependents();
60
+ return this._value!;
61
+ }
62
+ }
63
+
64
+ this.state = ComputedState.Computing;
65
+ this.clearDependencies();
66
+
67
+ const lastValue = this._value;
68
+ this._value = this.getter(this.trackDependency);
69
+ if (this._value instanceof Promise) {
70
+ const computeAttemptPromise = this._value
71
+ .then(result => this.handlePromiseThen(computeAttemptPromise, result))
72
+ .catch(error => this.handlePromiseCatch(computeAttemptPromise, error)) as Promise<void>;
73
+ this.lastComputeAttemptPromise = computeAttemptPromise;
74
+ this._value = this.computePromise!;
75
+ } else {
76
+ this.handlePromiseThen(this.lastComputeAttemptPromise!, this._value);
77
+ if (lastValue === this._value) {
78
+ this.validateDependents();
79
+ }
80
+ }
81
+ return this._value!;
82
+ }
83
+
84
+ private clearDependencies() {
85
+ for (const dependency of this.dependencies.keys()) {
86
+ dependency.removeDependent(this);
87
+ }
88
+ this.dependencies.clear();
89
+ }
90
+
91
+ private handlePromiseThen(computeAttemptPromise: Promise<void>, result: any) {
92
+ if (this.lastComputeAttemptPromise === computeAttemptPromise) {
93
+ this.computePromiseActions!.resolve(result);
94
+ this.finalizeComputing();
95
+ }
96
+ }
97
+
98
+ private handlePromiseCatch(computeAttemptPromise: Promise<void>, error: any) {
99
+ if (this.lastComputeAttemptPromise === computeAttemptPromise) {
100
+ this.computePromiseActions!.reject(error);
101
+ this.finalizeComputing();
102
+ }
103
+ }
104
+
105
+ private innerTrackDependency(this: Computed<T>, dependency: Dependency<any>) {
106
+ if (this.dependents.has(dependency as any)) {
107
+ throw new CircularDependencyError();
108
+ }
109
+ this.dependencies.set(dependency, true);
110
+ dependency.addDependent(this);
111
+ return dependency.value;
112
+ }
113
+
114
+ private trackDependency = this.innerTrackDependency.bind(this);
115
+
116
+ private finalizeComputing() {
117
+ this.state = ComputedState.Valid;
118
+ this.lastComputeAttemptPromise = undefined;
119
+ this.prepareComputePromise();
120
+ }
121
+
122
+ public invalidate() {
123
+ if (this.state === ComputedState.Computing) {
124
+ setImmediate(this.compute.bind(this));
125
+ } if (this.state !== ComputedState.Uncertain) {
126
+ this.state = ComputedState.Uncertain;
127
+ super.invalidate();
128
+ }
129
+ }
130
+
131
+ public validate(dependency: Dependency<any>) {
132
+ this.dependencies.set(dependency, false);
133
+ }
134
+
135
+ private validateDependents() {
136
+ for (const dependent of this.dependents.keys()) {
137
+ dependent.validate(this);
138
+ }
139
+ }
140
+
141
+ public dispose() {
142
+ this.clearDependencies();
143
+ this.state = ComputedState.Invalid;
144
+ this._value = undefined;
145
+ this.lastComputeAttemptPromise = undefined;
146
+ this.prepareComputePromise();
147
+ }
148
+ }
@@ -0,0 +1,7 @@
1
+ import Dependent from "./dependent";
2
+
3
+ export default interface Dependency<T> {
4
+ get value(): T;
5
+ addDependent(dependent: Dependent): void;
6
+ removeDependent(dependent: Dependent): void;
7
+ }
@@ -0,0 +1,7 @@
1
+ import Dependency from "./dependency";
2
+
3
+ export default interface Dependent {
4
+ invalidate(): void;
5
+ validate(dependency: Dependency<any>): void;
6
+ dispose(): void;
7
+ }
@@ -0,0 +1,310 @@
1
+ import { Computed, Ref, Watcher } from './';
2
+ import * as assert from 'assert';
3
+
4
+ describe('async reactivity', function () {
5
+ describe('ref', function () {
6
+ it('getter', function () {
7
+ const a = new Ref(5);
8
+ assert.strictEqual(a.value, 5);
9
+ });
10
+
11
+ it('setter', function () {
12
+ const a = new Ref(5);
13
+ a.value = 4;
14
+ assert.strictEqual(a.value, 4);
15
+ });
16
+ });
17
+
18
+ describe('computed', function () {
19
+ it('lazy compute', function () {
20
+ let gate = false;
21
+ const a = new Computed(() => {
22
+ gate = true;
23
+ return 5;
24
+ });
25
+
26
+ assert.strictEqual(gate, false);
27
+ assert.strictEqual(a.value, 5);
28
+ assert.strictEqual(gate, true);
29
+ });
30
+
31
+ it('cache', function () {
32
+ let gate = false;
33
+ const a = new Computed(() => {
34
+ gate = true;
35
+ return 5;
36
+ });
37
+
38
+ assert.strictEqual(a.value, 5);
39
+
40
+ gate = false;
41
+ assert.strictEqual(a.value, 5);
42
+ assert.strictEqual(gate, false);
43
+ });
44
+
45
+ it('invalidate dependents', function () {
46
+ const a = new Ref(5);
47
+ const b = new Computed((value) => {
48
+ return value(a) + 4;
49
+ });
50
+ assert.strictEqual(b.value, 9);
51
+ a.value = 6;
52
+ assert.strictEqual(b.value, 10);
53
+ });
54
+
55
+ it('dependents up-to-date', function () {
56
+ const a = new Ref(5);
57
+ const b = new Ref(10);
58
+ let gate;
59
+ const c = new Computed((value) => {
60
+ gate = true;
61
+ return value(a) < 10 ? value(b) : 0;
62
+ });
63
+ assert.strictEqual(c.value, 10);
64
+ a.value = 15;
65
+ assert.strictEqual(c.value, 0);
66
+ b.value = 15;
67
+ gate = false;
68
+ assert.strictEqual(c.value, 0);
69
+ assert.strictEqual(gate, false);
70
+ });
71
+
72
+ it('detect circular dependency', function () {
73
+ // @ts-expect-error
74
+ const a = new Computed((value) => {
75
+ return value(b);
76
+ });
77
+ // @ts-expect-error
78
+ const b = new Computed((value) => {
79
+ return value(a);
80
+ });
81
+ assert.throws(() => a.value);
82
+ });
83
+
84
+ xit('detect circular deeper dependency', function () {
85
+ // do not support for better performance
86
+ assert.fail('not implemented');
87
+ });
88
+
89
+ it('throw error', function () {
90
+ const a = new Computed(() => {
91
+ throw new Error();
92
+ });
93
+ assert.throws(() => a.value);
94
+ });
95
+
96
+ it('ignore same ref value', function () {
97
+ let gate = 0;
98
+ const a = new Ref(5);
99
+ const b = new Computed((value) => {
100
+ gate++;
101
+ return value(a);
102
+ });
103
+
104
+ assert.strictEqual(b.value, 5);
105
+
106
+ a.value = 5;
107
+ assert.strictEqual(b.value, 5);
108
+ assert.strictEqual(gate, 1);
109
+ });
110
+
111
+ it('ignore same computed value', function () {
112
+ let gate = 0;
113
+ const a = new Ref(5);
114
+ const b = new Computed((value) => {
115
+ return value(a) % 2;
116
+ });
117
+ const c = new Computed((value) => {
118
+ gate++;
119
+ return value(b) + 5;
120
+ });
121
+
122
+ assert.strictEqual(c.value, 6);
123
+
124
+ a.value = 7;
125
+ assert.strictEqual(c.value, 6);
126
+ assert.strictEqual(gate, 1);
127
+ });
128
+ });
129
+
130
+ describe('async computed', function () {
131
+ it('getter', async function () {
132
+ const a = new Computed(async () => {
133
+ await new Promise(resolve => setTimeout(resolve));
134
+ return 5;
135
+ });
136
+ assert.strictEqual(await a.value, 5);
137
+ });
138
+
139
+ it('tracks async dependencies', async function () {
140
+ const a = new Ref(5);
141
+ const b = new Computed(async (value) => {
142
+ await new Promise(resolve => setTimeout(resolve));
143
+ return value(a) + 5;
144
+ });
145
+ assert.strictEqual(await b.value, 10);
146
+ a.value = 6;
147
+ assert.strictEqual(await b.value, 11);
148
+ });
149
+
150
+ it('get value while computing', async function () {
151
+ const a = new Computed(async () => {
152
+ await new Promise(resolve => setTimeout(resolve));
153
+ return 5;
154
+ });
155
+
156
+ a.value;
157
+ assert.strictEqual(await a.value, 5);
158
+ });
159
+
160
+ it('detect circular dependency', async function () {
161
+ // @ts-expect-error
162
+ const a = new Computed(async (value) => {
163
+ await new Promise(resolve => setTimeout(resolve));
164
+ return value(b);
165
+ });
166
+ // @ts-expect-error
167
+ const b = new Computed(async (value) => {
168
+ await new Promise(resolve => setTimeout(resolve));
169
+ return value(a);
170
+ });
171
+
172
+ assert.rejects(async () => await a.value);
173
+ });
174
+
175
+ it('old dependency changed while computing', async function () {
176
+ let gate = 0;
177
+ const a = new Ref(5);
178
+ const b = new Computed(async (value) => {
179
+ gate++;
180
+ await new Promise(resolve => setTimeout(resolve));
181
+ return value(a) + 2;
182
+ });
183
+ assert.strictEqual(await b.value, 7);
184
+ b.invalidate();
185
+ const promise = b.value;
186
+ a.value = 6;
187
+ assert.strictEqual(await promise, 8);
188
+ assert.strictEqual(gate, 2);
189
+ });
190
+
191
+ it('new dependency changed while computing', async function () {
192
+ let gate = 0;
193
+ const a = new Ref(5);
194
+ const b = new Ref(10);
195
+ const c = new Computed(async (value) => {
196
+ gate++;
197
+ await new Promise(resolve => setTimeout(resolve, 50));
198
+ let sum = value(a);
199
+ await new Promise(resolve => setTimeout(resolve, 50));
200
+ sum += value(b);
201
+ return sum;
202
+ });
203
+ assert.strictEqual(await c.value, 15);
204
+ c.invalidate();
205
+ const promise = c.value;
206
+ await new Promise(resolve => setTimeout(resolve, 60));
207
+ a.value = 10;
208
+ assert.strictEqual(await promise, 20);
209
+ assert.strictEqual(gate, 3);
210
+ });
211
+
212
+ it('fallback to primitive while computing', async function () {
213
+ const a = new Ref(5);
214
+ const b = new Ref(10);
215
+ const c = new Computed(async (value) => {
216
+ if (value(a) < 10) {
217
+ await new Promise(resolve => setTimeout(resolve, 50));
218
+ return value(b) + 5;
219
+ }
220
+ return 2;
221
+ });
222
+ const promise = c.value;
223
+ await new Promise(resolve => setTimeout(resolve, 20));
224
+ a.value = 10;
225
+ assert.strictEqual(await promise, 2);
226
+ });
227
+
228
+ it('throw error', async function () {
229
+ const a = new Computed(async () => {
230
+ await new Promise(resolve => setTimeout(resolve));
231
+ throw new Error();
232
+ });
233
+ assert.rejects(() => a.value);
234
+ });
235
+
236
+ it('dispose computed', async function () {
237
+ const a = new Ref(5);
238
+ let gate = 0;
239
+ const b = new Computed(value => {
240
+ gate++;
241
+ return value(a) + 2;
242
+ });
243
+ b.value;
244
+ assert.strictEqual(gate, 1);
245
+ b.dispose();
246
+ a.value = 6;
247
+ b.value;
248
+ assert.strictEqual(gate, 1);
249
+ });
250
+ });
251
+
252
+ describe('watcher', function () {
253
+ it('sync', function () {
254
+ const a = new Ref(5);
255
+ new Watcher(a, (newValue: number, oldValue?: number) => {
256
+ assert.strictEqual(oldValue, 5);
257
+ assert.strictEqual(newValue, 6);
258
+ }, false);
259
+ a.value = 6;
260
+ });
261
+
262
+ it('async', async function () {
263
+ const a = new Computed(async () => {
264
+ await new Promise(resolve => setTimeout(resolve));
265
+ return 10;
266
+ });
267
+ const result = await new Promise<number>(resolve => new Watcher(a, resolve));
268
+ assert.strictEqual(result, 10);
269
+ });
270
+
271
+ it('sync cancel', async function () {
272
+ const a = new Ref(5);
273
+ const b = new Computed((value) => {
274
+ return value(a) % 2;
275
+ });
276
+ let gate = 0;
277
+ new Watcher(b, () => {
278
+ gate++;
279
+ }, false);
280
+ a.value = 6;
281
+ assert.strictEqual(gate, 1);
282
+ a.value = 7;
283
+ a.value = 9;
284
+ a.value = 11;
285
+ assert.strictEqual(gate, 2);
286
+ });
287
+
288
+ it('async sync cancel', async function () {
289
+ const a = new Ref(5);
290
+ const b = new Computed(async (value) => {
291
+ new Promise(resolve => setTimeout(resolve));
292
+ return value(a) % 2;
293
+ });
294
+ let gate = 0;
295
+ new Watcher(b, () => {
296
+ gate++;
297
+ }, false);
298
+ await new Promise(resolve => setTimeout(resolve, 10));
299
+ a.value = 6;
300
+ await new Promise(resolve => setTimeout(resolve, 10));
301
+ assert.strictEqual(gate, 1);
302
+ a.value = 7;
303
+ await new Promise(resolve => setTimeout(resolve, 10));
304
+ assert.strictEqual(gate, 2);
305
+ a.value = 9;
306
+ await new Promise(resolve => setTimeout(resolve, 10));
307
+ assert.strictEqual(gate, 3);
308
+ });
309
+ });
310
+ });
package/src/index.ts ADDED
@@ -0,0 +1,5 @@
1
+ export { default as Computed, ComputeFunc, ComputeFuncScoped } from './computed';
2
+ export { default as Ref } from './ref';
3
+ export { default as Watcher } from './watcher';
4
+ export { default as Dependency } from './dependency';
5
+ export { default as Dependent } from './dependent';
package/src/ref.ts ADDED
@@ -0,0 +1,22 @@
1
+ import Dependency from "./dependency";
2
+ import Tracker from "./tracker";
3
+
4
+ export default class Ref<T> extends Tracker<T> implements Dependency<T> {
5
+
6
+ constructor(_value: T) {
7
+ super();
8
+ this._value = _value;
9
+ }
10
+
11
+ public set value(_value: T) {
12
+ const lastValue = this._value;
13
+ this._value = _value;
14
+ if (lastValue !== _value) {
15
+ this.invalidate();
16
+ }
17
+ }
18
+
19
+ public get value(): T {
20
+ return super.value!;
21
+ }
22
+ }
package/src/tracker.ts ADDED
@@ -0,0 +1,27 @@
1
+ import Computed from "./computed";
2
+ import Watcher from "./watcher";
3
+
4
+ type Dependent = Computed<any> | Watcher<any>;
5
+
6
+ export default class Tracker<T> {
7
+ protected dependents = new Set<Dependent>();
8
+ protected _value?: T;
9
+
10
+ public addDependent(dependent: Dependent) {
11
+ this.dependents.add(dependent);
12
+ }
13
+
14
+ public removeDependent(dependent: Dependent) {
15
+ this.dependents.delete(dependent);
16
+ }
17
+
18
+ public invalidate(): void {
19
+ for (const dependent of [...this.dependents.keys()]) {
20
+ dependent.invalidate();
21
+ }
22
+ }
23
+
24
+ public get value() {
25
+ return this._value;
26
+ }
27
+ }
@@ -0,0 +1,95 @@
1
+ {
2
+ "compilerOptions": {
3
+ /* Visit https://aka.ms/tsconfig to read more about this file */
4
+ /* Projects */
5
+ // "incremental": true, /* Save .tsbuildinfo files to allow for incremental compilation of projects. */
6
+ // "composite": true, /* Enable constraints that allow a TypeScript project to be used with project references. */
7
+ // "tsBuildInfoFile": "./.tsbuildinfo", /* Specify the path to .tsbuildinfo incremental compilation file. */
8
+ // "disableSourceOfProjectReferenceRedirect": true, /* Disable preferring source files instead of declaration files when referencing composite projects. */
9
+ // "disableSolutionSearching": true, /* Opt a project out of multi-project reference checking when editing. */
10
+ // "disableReferencedProjectLoad": true, /* Reduce the number of projects loaded automatically by TypeScript. */
11
+ /* Language and Environment */
12
+ "target": "es2016", /* Set the JavaScript language version for emitted JavaScript and include compatible library declarations. */
13
+ // "lib": [], /* Specify a set of bundled library declaration files that describe the target runtime environment. */
14
+ // "jsx": "preserve", /* Specify what JSX code is generated. */
15
+ // "experimentalDecorators": true, /* Enable experimental support for TC39 stage 2 draft decorators. */
16
+ // "emitDecoratorMetadata": true, /* Emit design-type metadata for decorated declarations in source files. */
17
+ // "jsxFactory": "", /* Specify the JSX factory function used when targeting React JSX emit, e.g. 'React.createElement' or 'h'. */
18
+ // "jsxFragmentFactory": "", /* Specify the JSX Fragment reference used for fragments when targeting React JSX emit e.g. 'React.Fragment' or 'Fragment'. */
19
+ // "jsxImportSource": "", /* Specify module specifier used to import the JSX factory functions when using 'jsx: react-jsx*'. */
20
+ // "reactNamespace": "", /* Specify the object invoked for 'createElement'. This only applies when targeting 'react' JSX emit. */
21
+ // "noLib": true, /* Disable including any library files, including the default lib.d.ts. */
22
+ // "useDefineForClassFields": true, /* Emit ECMAScript-standard-compliant class fields. */
23
+ // "moduleDetection": "auto", /* Control what method is used to detect module-format JS files. */
24
+ /* Modules */
25
+ "module": "commonjs", /* Specify what module code is generated. */
26
+ // "rootDir": "./", /* Specify the root folder within your source files. */
27
+ // "moduleResolution": "node", /* Specify how TypeScript looks up a file from a given module specifier. */
28
+ // "baseUrl": "./", /* Specify the base directory to resolve non-relative module names. */
29
+ // "paths": {}, /* Specify a set of entries that re-map imports to additional lookup locations. */
30
+ // "rootDirs": [], /* Allow multiple folders to be treated as one when resolving modules. */
31
+ // "typeRoots": [], /* Specify multiple folders that act like './node_modules/@types'. */
32
+ // "types": [], /* Specify type package names to be included without being referenced in a source file. */
33
+ // "allowUmdGlobalAccess": true, /* Allow accessing UMD globals from modules. */
34
+ // "moduleSuffixes": [], /* List of file name suffixes to search when resolving a module. */
35
+ // "resolveJsonModule": true, /* Enable importing .json files. */
36
+ // "noResolve": true, /* Disallow 'import's, 'require's or '<reference>'s from expanding the number of files TypeScript should add to a project. */
37
+ /* JavaScript Support */
38
+ // "allowJs": true, /* Allow JavaScript files to be a part of your program. Use the 'checkJS' option to get errors from these files. */
39
+ // "checkJs": true, /* Enable error reporting in type-checked JavaScript files. */
40
+ // "maxNodeModuleJsDepth": 1, /* Specify the maximum folder depth used for checking JavaScript files from 'node_modules'. Only applicable with 'allowJs'. */
41
+ /* Emit */
42
+ "declaration": true, /* Generate .d.ts files from TypeScript and JavaScript files in your project. */
43
+ "declarationMap": true, /* Create sourcemaps for d.ts files. */
44
+ // "emitDeclarationOnly": true, /* Only output d.ts files and not JavaScript files. */
45
+ // "sourceMap": true, /* Create source map files for emitted JavaScript files. */
46
+ // "outFile": "./", /* Specify a file that bundles all outputs into one JavaScript file. If 'declaration' is true, also designates a file that bundles all .d.ts output. */
47
+ "outDir": "../lib", /* Specify an output folder for all emitted files. */
48
+ // "removeComments": true, /* Disable emitting comments. */
49
+ // "noEmit": true, /* Disable emitting files from a compilation. */
50
+ // "importHelpers": true, /* Allow importing helper functions from tslib once per project, instead of including them per-file. */
51
+ // "importsNotUsedAsValues": "remove", /* Specify emit/checking behavior for imports that are only used for types. */
52
+ // "downlevelIteration": true, /* Emit more compliant, but verbose and less performant JavaScript for iteration. */
53
+ // "sourceRoot": "", /* Specify the root path for debuggers to find the reference source code. */
54
+ // "mapRoot": "", /* Specify the location where debugger should locate map files instead of generated locations. */
55
+ // "inlineSourceMap": true, /* Include sourcemap files inside the emitted JavaScript. */
56
+ // "inlineSources": true, /* Include source code in the sourcemaps inside the emitted JavaScript. */
57
+ // "emitBOM": true, /* Emit a UTF-8 Byte Order Mark (BOM) in the beginning of output files. */
58
+ // "newLine": "crlf", /* Set the newline character for emitting files. */
59
+ // "stripInternal": true, /* Disable emitting declarations that have '@internal' in their JSDoc comments. */
60
+ // "noEmitHelpers": true, /* Disable generating custom helper functions like '__extends' in compiled output. */
61
+ // "noEmitOnError": true, /* Disable emitting files if any type checking errors are reported. */
62
+ // "preserveConstEnums": true, /* Disable erasing 'const enum' declarations in generated code. */
63
+ "declarationDir": "../types", /* Specify the output directory for generated declaration files. */
64
+ // "preserveValueImports": true, /* Preserve unused imported values in the JavaScript output that would otherwise be removed. */
65
+ /* Interop Constraints */
66
+ // "isolatedModules": true, /* Ensure that each file can be safely transpiled without relying on other imports. */
67
+ // "allowSyntheticDefaultImports": true, /* Allow 'import x from y' when a module doesn't have a default export. */
68
+ "esModuleInterop": true, /* Emit additional JavaScript to ease support for importing CommonJS modules. This enables 'allowSyntheticDefaultImports' for type compatibility. */
69
+ // "preserveSymlinks": true, /* Disable resolving symlinks to their realpath. This correlates to the same flag in node. */
70
+ "forceConsistentCasingInFileNames": true, /* Ensure that casing is correct in imports. */
71
+ /* Type Checking */
72
+ "strict": true, /* Enable all strict type-checking options. */
73
+ // "noImplicitAny": true, /* Enable error reporting for expressions and declarations with an implied 'any' type. */
74
+ // "strictNullChecks": true, /* When type checking, take into account 'null' and 'undefined'. */
75
+ // "strictFunctionTypes": true, /* When assigning functions, check to ensure parameters and the return values are subtype-compatible. */
76
+ // "strictBindCallApply": true, /* Check that the arguments for 'bind', 'call', and 'apply' methods match the original function. */
77
+ // "strictPropertyInitialization": true, /* Check for class properties that are declared but not set in the constructor. */
78
+ // "noImplicitThis": true, /* Enable error reporting when 'this' is given the type 'any'. */
79
+ // "useUnknownInCatchVariables": true, /* Default catch clause variables as 'unknown' instead of 'any'. */
80
+ // "alwaysStrict": true, /* Ensure 'use strict' is always emitted. */
81
+ // "noUnusedLocals": true, /* Enable error reporting when local variables aren't read. */
82
+ // "noUnusedParameters": true, /* Raise an error when a function parameter isn't read. */
83
+ // "exactOptionalPropertyTypes": true, /* Interpret optional property types as written, rather than adding 'undefined'. */
84
+ // "noImplicitReturns": true, /* Enable error reporting for codepaths that do not explicitly return in a function. */
85
+ // "noFallthroughCasesInSwitch": true, /* Enable error reporting for fallthrough cases in switch statements. */
86
+ // "noUncheckedIndexedAccess": true, /* Add 'undefined' to a type when accessed using an index. */
87
+ // "noImplicitOverride": true, /* Ensure overriding members in derived classes are marked with an override modifier. */
88
+ // "noPropertyAccessFromIndexSignature": true, /* Enforces using indexed accessors for keys declared using an indexed type. */
89
+ // "allowUnusedLabels": true, /* Disable error reporting for unused labels. */
90
+ // "allowUnreachableCode": true, /* Disable error reporting for unreachable code. */
91
+ /* Completeness */
92
+ // "skipDefaultLibCheck": true, /* Skip type checking .d.ts files that are included with TypeScript. */
93
+ "skipLibCheck": true /* Skip type checking all .d.ts files. */
94
+ }
95
+ }
package/src/watcher.ts ADDED
@@ -0,0 +1,47 @@
1
+ import Dependency from "./dependency";
2
+ import Dependent from "./dependent";
3
+ import Tracker from "./tracker";
4
+
5
+ enum WatchState {
6
+ Uncertain,
7
+ Valid
8
+ };
9
+
10
+ type onChangeFunc<T> = (newValue: T, oldValue?: T) => void;
11
+
12
+ export default class Watcher<T> extends Tracker<T> implements Dependent {
13
+
14
+ private onChange: onChangeFunc<T>;
15
+ private dependency: Dependency<T>;
16
+ private state = WatchState.Valid;
17
+
18
+ constructor(dependency: Dependency<T>, onChange: onChangeFunc<T>, immediate: boolean = true) {
19
+ super();
20
+ this.onChange = onChange;
21
+ this.dependency = dependency;
22
+
23
+ dependency.addDependent(this);
24
+ this._value = dependency.value;
25
+ if (immediate) {
26
+ onChange(this._value);
27
+ }
28
+ }
29
+
30
+ public invalidate() {
31
+ this.state = WatchState.Uncertain;
32
+ const oldValue = this._value;
33
+ this._value = this.dependency.value;
34
+ if (this.state === WatchState.Uncertain) {
35
+ this.onChange(this._value, oldValue);
36
+ this.state = WatchState.Valid;
37
+ }
38
+ }
39
+
40
+ public validate() {
41
+ this.state = WatchState.Valid;
42
+ }
43
+
44
+ public dispose() {
45
+ this.dependency.removeDependent(this);
46
+ }
47
+ }