|
1 | | -import { Computation, type MemoOptions } from "./core"; |
| 1 | +import { Computation, UNCHANGED, type MemoOptions } from "./core"; |
2 | 2 | import { STATE_CLEAN, STATE_DISPOSED } from "./constants"; |
3 | 3 | import type { Owner } from "./owner"; |
4 | 4 | import { handleError } from "./owner"; |
5 | 5 |
|
6 | 6 | let scheduledEffects = false; |
7 | 7 | let runningEffects = false; |
| 8 | +let renderEffects: RenderEffect[] = []; |
8 | 9 | let effects: Effect[] = []; |
9 | 10 |
|
10 | 11 | /** |
@@ -53,6 +54,17 @@ function runEffects() { |
53 | 54 | runningEffects = true; |
54 | 55 |
|
55 | 56 | try { |
| 57 | + for (let i = 0; i < renderEffects.length; i++) { |
| 58 | + if (renderEffects[i]._state !== STATE_CLEAN) { |
| 59 | + renderEffects[i]._updateIfNecessary(); |
| 60 | + } |
| 61 | + } |
| 62 | + for (let i = 0; i < renderEffects.length; i++) { |
| 63 | + if (renderEffects[i].modified) { |
| 64 | + renderEffects[i].effect(renderEffects[i]._value); |
| 65 | + renderEffects[i].modified = false; |
| 66 | + } |
| 67 | + } |
56 | 68 | for (let i = 0; i < effects.length; i++) { |
57 | 69 | if (effects[i]._state !== STATE_CLEAN) { |
58 | 70 | runTop(effects[i]); |
@@ -98,3 +110,42 @@ export class Effect<T = any> extends Computation<T> { |
98 | 110 | handleError(this, error); |
99 | 111 | } |
100 | 112 | } |
| 113 | + |
| 114 | +// eslint-disable-next-line @typescript-eslint/no-explicit-any |
| 115 | +export class RenderEffect<T = any> extends Computation<T> { |
| 116 | + effect: (val: T) => void; |
| 117 | + modified: boolean = false; |
| 118 | + constructor( |
| 119 | + compute: () => T, |
| 120 | + effect: (val: T) => void, |
| 121 | + options?: MemoOptions<T>, |
| 122 | + ) { |
| 123 | + super(undefined, compute, options); |
| 124 | + |
| 125 | + this.effect = effect; |
| 126 | + renderEffects.push(this); |
| 127 | + // this._updateIfNecessary() |
| 128 | + } |
| 129 | + |
| 130 | + override _notify(state: number): void { |
| 131 | + if (this._state >= state) return; |
| 132 | + |
| 133 | + if (this._state === STATE_CLEAN) { |
| 134 | + renderEffects.push(this); |
| 135 | + if (!scheduledEffects) flushEffects(); |
| 136 | + } |
| 137 | + |
| 138 | + this._state = state; |
| 139 | + } |
| 140 | + |
| 141 | + override write(value: T): T { |
| 142 | + this._value = value; |
| 143 | + this.modified = true; |
| 144 | + |
| 145 | + return value; |
| 146 | + } |
| 147 | + |
| 148 | + override _setError(error: unknown): void { |
| 149 | + handleError(this, error); |
| 150 | + } |
| 151 | +} |
0 commit comments