Debian Codegraph @

node/@xterm/xterm/src/vs/base/common/observableInternal/autorun.ts

raw
1 /*---------------------------------------------------------------------------------------------
2 * Copyright (c) Microsoft Corporation. All rights reserved.
3 * Licensed under the MIT License. See License.txt in the project root for license information.
4 *--------------------------------------------------------------------------------------------*/
5
6 import { assertFn } from 'vs/base/common/assert';
7 import { DisposableStore, IDisposable, markAsDisposed, toDisposable, trackDisposable } from 'vs/base/common/lifecycle';
8 import { IReader, IObservable, IObserver, IChangeContext } from 'vs/base/common/observableInternal/base';
9 import { DebugNameData, IDebugNameData } from 'vs/base/common/observableInternal/debugName';
10 import { getLogger } from 'vs/base/common/observableInternal/logging';
11
12 /**
13 * Runs immediately and whenever a transaction ends and an observed observable changed.
14 * {@link fn} should start with a JS Doc using `@description` to name the autorun.
15 */
16 export function autorun(fn: (reader: IReader) => void): IDisposable {
17 return new AutorunObserver(
18 new DebugNameData(undefined, undefined, fn),
19 fn,
20 undefined,
21 undefined
22 );
23 }
24
25 /**
26 * Runs immediately and whenever a transaction ends and an observed observable changed.
27 * {@link fn} should start with a JS Doc using `@description` to name the autorun.
28 */
29 export function autorunOpts(options: IDebugNameData & {}, fn: (reader: IReader) => void): IDisposable {
30 return new AutorunObserver(
31 new DebugNameData(options.owner, options.debugName, options.debugReferenceFn ?? fn),
32 fn,
33 undefined,
34 undefined
35 );
36 }
37
38 /**
39 * Runs immediately and whenever a transaction ends and an observed observable changed.
40 * {@link fn} should start with a JS Doc using `@description` to name the autorun.
41 *
42 * Use `createEmptyChangeSummary` to create a "change summary" that can collect the changes.
43 * Use `handleChange` to add a reported change to the change summary.
44 * The run function is given the last change summary.
45 * The change summary is discarded after the run function was called.
46 *
47 * @see autorun
48 */
49 export function autorunHandleChanges<TChangeSummary>(
50 options: IDebugNameData & {
51 createEmptyChangeSummary?: () => TChangeSummary;
52 handleChange: (context: IChangeContext, changeSummary: TChangeSummary) => boolean;
53 },
54 fn: (reader: IReader, changeSummary: TChangeSummary) => void
55 ): IDisposable {
56 return new AutorunObserver(
57 new DebugNameData(options.owner, options.debugName, options.debugReferenceFn ?? fn),
58 fn,
59 options.createEmptyChangeSummary,
60 options.handleChange
61 );
62 }
63
64 /**
65 * @see autorunHandleChanges (but with a disposable store that is cleared before the next run or on dispose)
66 */
67 export function autorunWithStoreHandleChanges<TChangeSummary>(
68 options: IDebugNameData & {
69 createEmptyChangeSummary?: () => TChangeSummary;
70 handleChange: (context: IChangeContext, changeSummary: TChangeSummary) => boolean;
71 },
72 fn: (reader: IReader, changeSummary: TChangeSummary, store: DisposableStore) => void
73 ): IDisposable {
74 const store = new DisposableStore();
75 const disposable = autorunHandleChanges(
76 {
77 owner: options.owner,
78 debugName: options.debugName,
79 debugReferenceFn: options.debugReferenceFn ?? fn,
80 createEmptyChangeSummary: options.createEmptyChangeSummary,
81 handleChange: options.handleChange,
82 },
83 (reader, changeSummary) => {
84 store.clear();
85 fn(reader, changeSummary, store);
86 }
87 );
88 return toDisposable(() => {
89 disposable.dispose();
90 store.dispose();
91 });
92 }
93
94 /**
95 * @see autorun (but with a disposable store that is cleared before the next run or on dispose)
96 */
97 export function autorunWithStore(fn: (reader: IReader, store: DisposableStore) => void): IDisposable {
98 const store = new DisposableStore();
99 const disposable = autorunOpts(
100 {
101 owner: undefined,
102 debugName: undefined,
103 debugReferenceFn: fn,
104 },
105 reader => {
106 store.clear();
107 fn(reader, store);
108 }
109 );
110 return toDisposable(() => {
111 disposable.dispose();
112 store.dispose();
113 });
114 }
115
116 export function autorunDelta<T>(
117 observable: IObservable<T>,
118 handler: (args: { lastValue: T | undefined; newValue: T }) => void
119 ): IDisposable {
120 let _lastValue: T | undefined;
121 return autorunOpts({ debugReferenceFn: handler }, (reader) => {
122 const newValue = observable.read(reader);
123 const lastValue = _lastValue;
124 _lastValue = newValue;
125 handler({ lastValue, newValue });
126 });
127 }
128
129
130 const enum AutorunState {
131 /**
132 * A dependency could have changed.
133 * We need to explicitly ask them if at least one dependency changed.
134 */
135 dependenciesMightHaveChanged = 1,
136
137 /**
138 * A dependency changed and we need to recompute.
139 */
140 stale = 2,
141 upToDate = 3,
142 }
143
144 export class AutorunObserver<TChangeSummary = any> implements IObserver, IReader, IDisposable {
145 private state = AutorunState.stale;
146 private updateCount = 0;
147 private disposed = false;
148 private dependencies = new Set<IObservable<any>>();
149 private dependenciesToBeRemoved = new Set<IObservable<any>>();
150 private changeSummary: TChangeSummary | undefined;
151
152 public get debugName(): string {
153 return this._debugNameData.getDebugName(this) ?? '(anonymous)';
154 }
155
156 constructor(
157 public readonly _debugNameData: DebugNameData,
158 public readonly _runFn: (reader: IReader, changeSummary: TChangeSummary) => void,
159 private readonly createChangeSummary: (() => TChangeSummary) | undefined,
160 private readonly _handleChange: ((context: IChangeContext, summary: TChangeSummary) => boolean) | undefined,
161 ) {
162 this.changeSummary = this.createChangeSummary?.();
163 getLogger()?.handleAutorunCreated(this);
164 this._runIfNeeded();
165
166 trackDisposable(this);
167 }
168
169 public dispose(): void {
170 this.disposed = true;
171 for (const o of this.dependencies) {
172 o.removeObserver(this);
173 }
174 this.dependencies.clear();
175
176 markAsDisposed(this);
177 }
178
179 private _runIfNeeded() {
180 if (this.state === AutorunState.upToDate) {
181 return;
182 }
183
184 const emptySet = this.dependenciesToBeRemoved;
185 this.dependenciesToBeRemoved = this.dependencies;
186 this.dependencies = emptySet;
187
188 this.state = AutorunState.upToDate;
189
190 const isDisposed = this.disposed;
191 try {
192 if (!isDisposed) {
193 getLogger()?.handleAutorunTriggered(this);
194 const changeSummary = this.changeSummary!;
195 this.changeSummary = this.createChangeSummary?.();
196 this._runFn(this, changeSummary);
197 }
198 } finally {
199 if (!isDisposed) {
200 getLogger()?.handleAutorunFinished(this);
201 }
202 // We don't want our observed observables to think that they are (not even temporarily) not being observed.
203 // Thus, we only unsubscribe from observables that are definitely not read anymore.
204 for (const o of this.dependenciesToBeRemoved) {
205 o.removeObserver(this);
206 }
207 this.dependenciesToBeRemoved.clear();
208 }
209 }
210
211 public toString(): string {
212 return `Autorun<${this.debugName}>`;
213 }
214
215 // IObserver implementation
216 public beginUpdate(): void {
217 if (this.state === AutorunState.upToDate) {
218 this.state = AutorunState.dependenciesMightHaveChanged;
219 }
220 this.updateCount++;
221 }
222
223 public endUpdate(): void {
224 if (this.updateCount === 1) {
225 do {
226 if (this.state === AutorunState.dependenciesMightHaveChanged) {
227 this.state = AutorunState.upToDate;
228 for (const d of this.dependencies) {
229 d.reportChanges();
230 if (this.state as AutorunState === AutorunState.stale) {
231 // The other dependencies will refresh on demand
232 break;
233 }
234 }
235 }
236
237 this._runIfNeeded();
238 } while (this.state !== AutorunState.upToDate);
239 }
240 this.updateCount--;
241
242 assertFn(() => this.updateCount >= 0);
243 }
244
245 public handlePossibleChange(observable: IObservable<any>): void {
246 if (this.state === AutorunState.upToDate && this.dependencies.has(observable) && !this.dependenciesToBeRemoved.has(observable)) {
247 this.state = AutorunState.dependenciesMightHaveChanged;
248 }
249 }
250
251 public handleChange<T, TChange>(observable: IObservable<T, TChange>, change: TChange): void {
252 if (this.dependencies.has(observable) && !this.dependenciesToBeRemoved.has(observable)) {
253 const shouldReact = this._handleChange ? this._handleChange({
254 changedObservable: observable,
255 change,
256 didChange: (o): this is any => o === observable as any,
257 }, this.changeSummary!) : true;
258 if (shouldReact) {
259 this.state = AutorunState.stale;
260 }
261 }
262 }
263
264 // IReader implementation
265 public readObservable<T>(observable: IObservable<T>): T {
266 // In case the run action disposes the autorun
267 if (this.disposed) {
268 return observable.get();
269 }
270
271 observable.addObserver(this);
272 const value = observable.get();
273 this.dependencies.add(observable);
274 this.dependenciesToBeRemoved.delete(observable);
275 return value;
276 }
277 }
278
279 export namespace autorun {
280 export const Observer = AutorunObserver;
281 }