src/vs/base/common/observableInternal/logging/consoleObservableLogger.ts

387 LOC · 65 covered · 322 uncovered · 28 ranges · 6771 concepts · 2 introducers · 3467 tests

File neighbourhood

The centred file is linked to every concept that introduces one of its ranges, every test that runs code from the file, and the gray connector concepts standing between those tests and the file's own introducer concepts. Undirected links join concepts to every file where they introduce source and concepts to the tests they introduce; arrows show specialization between the displayed concepts and bridge only concepts omitted from this view. Concept colors match the source ranges below; connector concepts have no source color and are shown in gray.

Focused file, its introducer and connector concepts, their introduced files, and tests that run code from the file

In the embedded map, ordinary wheel input scrolls the page; use the visible controls to zoom and drag to pan. Open the full-screen map for canvas navigation: wheel pans, Ctrl/Command plus wheel zooms, and arrow keys pan when this region is focused. On touch screens, open the full-screen map to pan or pinch. If JavaScript or WebGL is unavailable, use the related-file, concept, and source links on this page.

Graph controls are ready.

Interactive rendering requires JavaScript and WebGL. Use the related-file, concept, and source links on this page while the interactive map is unavailable.

1 > /*--------------------------------------------------------------------------------------------- devToolsLogger.ts ×24
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 { IObservable } from '../base.js';
7 > import { TransactionImpl } from '../transaction.js';
8 > import { IObservableLogger, IChangeInformation, addLogger } from './logging.js';
9 > import { FromEventObservable } from '../observables/observableFromEvent.js';
10 > import { getClassName } from '../debugName.js';
11 > import { Derived } from '../observables/derivedImpl.js';
12 > import { AutorunObserver } from '../reactions/autorunImpl.js';
13 >
14 > let consoleObservableLogger: ConsoleObservableLogger | undefined;
15 >
16 > export function logObservableToConsole(obs: IObservable<any>): void {
17 if (!consoleObservableLogger) {
18 consoleObservableLogger = new ConsoleObservableLogger();
19 addLogger(consoleObservableLogger);
20 }
21 consoleObservableLogger.addFilteredObj(obs);
22 }
24 > export class ConsoleObservableLogger implements IObservableLogger {
25 private indentation = 0;
26
27 private _filteredObjects: Set<unknown> | undefined;
28
29 public addFilteredObj(obj: unknown): void {
30 if (!this._filteredObjects) {
31 this._filteredObjects = new Set();
32 }
33 this._filteredObjects.add(obj);
34 }
35
36 private _isIncluded(obj: unknown): boolean {
37 return this._filteredObjects?.has(obj) ?? true;
38 }
39
40 private textToConsoleArgs(text: ConsoleText): unknown[] {
41 return consoleTextToArgs([
42 normalText(repeat('| ', this.indentation)),
43 text,
44 ]);
45 }
46
47 private formatInfo(info: IChangeInformation): ConsoleText[] {
48 if (!info.hadValue) {
49 return [
50 normalText(` `),
51 styled(formatValue(info.newValue, 60), {
52 color: 'green',
53 }),
54 normalText(` (initial)`),
55 ];
56 }
57 return info.didChange
58 ? [
59 normalText(` `),
60 styled(formatValue(info.oldValue, 70), {
61 color: 'red',
62 strikeThrough: true,
63 }),
64 normalText(` `),
65 styled(formatValue(info.newValue, 60), {
66 color: 'green',
67 }),
68 ]
69 : [normalText(` (unchanged)`)];
70 }
71
72 handleObservableCreated(observable: IObservable<any>): void {
73 if (observable instanceof Derived) {
74 const derived = observable;
75 this.changedObservablesSets.set(derived, new Set());
76
77 const debugTrackUpdating = false;
78 if (debugTrackUpdating) {
79 const updating: IObservable<any>[] = [];
80 // eslint-disable-next-line local/code-no-any-casts
81 (derived as any).__debugUpdating = updating;
82
83 const existingBeginUpdate = derived.beginUpdate;
84 derived.beginUpdate = (obs) => {
85 updating.push(obs);
86 return existingBeginUpdate.apply(derived, [obs]);
87 };
88
89 const existingEndUpdate = derived.endUpdate;
90 derived.endUpdate = (obs) => {
91 const idx = updating.indexOf(obs);
92 if (idx === -1) {
93 console.error('endUpdate called without beginUpdate', derived.debugName, obs.debugName);
94 }
95 updating.splice(idx, 1);
96 return existingEndUpdate.apply(derived, [obs]);
97 };
98 }
99 }
100 }
101
102 handleOnListenerCountChanged(observable: IObservable<any>, newCount: number): void {
103 }
104
105 handleObservableUpdated(observable: IObservable<unknown>, info: IChangeInformation): void {
106 if (!this._isIncluded(observable)) { return; }
107 if (observable instanceof Derived) {
108 this._handleDerivedRecomputed(observable, info);
109 return;
110 }
111
112 console.log(...this.textToConsoleArgs([
113 formatKind('observable value changed'),
114 styled(observable.debugName, { color: 'BlueViolet' }),
115 ...this.formatInfo(info),
116 ]));
117 }
118
119 private readonly changedObservablesSets = new WeakMap<object, Set<IObservable<any>>>();
121 > formatChanges(changes: Set<IObservable<any>>): ConsoleText | undefined {
122 if (changes.size === 0) {
123 return undefined;
124 }
125 return styled(
126 ' (changed deps: ' +
127 [...changes].map((o) => o.debugName).join(', ') +
128 ')',
129 { color: 'gray' }
130 );
131 }
133 > handleDerivedDependencyChanged(derived: Derived<any>, observable: IObservable<any>, change: unknown): void {
134 if (!this._isIncluded(derived)) { return; }
135
136 this.changedObservablesSets.get(derived)?.add(observable);
137 }
139 > _handleDerivedRecomputed(derived: Derived<unknown>, info: IChangeInformation): void {
140 if (!this._isIncluded(derived)) { return; }
141
142 const changedObservables = this.changedObservablesSets.get(derived);
143 if (!changedObservables) { return; }
144 console.log(...this.textToConsoleArgs([
145 formatKind('derived recomputed'),
146 styled(derived.debugName, { color: 'BlueViolet' }),
147 ...this.formatInfo(info),
148 this.formatChanges(changedObservables),
149 { data: [{ fn: derived._debugNameData.referenceFn ?? derived._computeFn }] }
150 ]));
151 changedObservables.clear();
152 }
154 > handleDerivedCleared(derived: Derived<unknown>): void {
155 if (!this._isIncluded(derived)) { return; }
156
157 console.log(...this.textToConsoleArgs([
158 formatKind('derived cleared'),
159 styled(derived.debugName, { color: 'BlueViolet' }),
160 ]));
161 }
163 > handleFromEventObservableTriggered(observable: FromEventObservable<any, any>, info: IChangeInformation): void {
164 if (!this._isIncluded(observable)) { return; }
165
166 console.log(...this.textToConsoleArgs([
167 formatKind('observable from event triggered'),
168 styled(observable.debugName, { color: 'BlueViolet' }),
169 ...this.formatInfo(info),
170 { data: [{ fn: observable._getValue }] }
171 ]));
172 }
174 > handleAutorunCreated(autorun: AutorunObserver): void {
175 if (!this._isIncluded(autorun)) { return; }
176
177 this.changedObservablesSets.set(autorun, new Set());
178 }
180 > handleAutorunDisposed(autorun: AutorunObserver): void {
181 }
183 > handleAutorunDependencyChanged(autorun: AutorunObserver, observable: IObservable<any>, change: unknown): void {
184 if (!this._isIncluded(autorun)) { return; }
185
186 this.changedObservablesSets.get(autorun)!.add(observable);
187 }
189 > handleAutorunStarted(autorun: AutorunObserver): void {
190 const changedObservables = this.changedObservablesSets.get(autorun);
191 if (!changedObservables) { return; }
192
193 if (this._isIncluded(autorun)) {
194 console.log(...this.textToConsoleArgs([
195 formatKind('autorun'),
196 styled(autorun.debugName, { color: 'BlueViolet' }),
197 this.formatChanges(changedObservables),
198 { data: [{ fn: autorun._debugNameData.referenceFn ?? autorun._runFn }] }
199 ]));
200 }
201 changedObservables.clear();
202 this.indentation++;
203 }
205 > handleAutorunFinished(autorun: AutorunObserver): void {
206 this.indentation--;
207 }
209 > handleBeginTransaction(transaction: TransactionImpl): void {
210 let transactionName = transaction.getDebugName();
211 if (transactionName === undefined) {
212 transactionName = '';
213 }
214 if (this._isIncluded(transaction)) {
215 console.log(...this.textToConsoleArgs([
216 formatKind('transaction'),
217 styled(transactionName, { color: 'BlueViolet' }),
218 { data: [{ fn: transaction._fn }] }
219 ]));
220 }
221 this.indentation++;
222 }
224 > handleEndTransaction(): void {
225 this.indentation--;
226 }
228 > type ConsoleText = (ConsoleText | undefined)[] |
229 > { text: string; style: string; data?: unknown[] } |
230 > { data: unknown[] };
231 function consoleTextToArgs(text: ConsoleText): unknown[] {
232 const styles = new Array<any>();
233 const data: unknown[] = [];
234 let firstArg = '';
235
236 function process(t: ConsoleText): void {
237 if ('length' in t) {
238 for (const item of t) {
239 if (item) {
240 process(item);
241 }
242 }
243 } else if ('text' in t) {
244 firstArg += `%c${t.text}`;
245 styles.push(t.style);
246 if (t.data) {
247 data.push(...t.data);
248 }
249 } else if ('data' in t) {
250 data.push(...t.data);
251 }
252 }
253
254 process(text);
255
256 const result = [firstArg, ...styles];
257 result.push(...data);
258 return result;
259 }
260 function normalText(text: string): ConsoleText {
261 return styled(text, { color: 'black' });
262 }
263 function formatKind(kind: string): ConsoleText {
264 return styled(padStr(`${kind}: `, 10), { color: 'black', bold: true });
265 }
266 function styled(
267 text: string,
268 options: { color: string; strikeThrough?: boolean; bold?: boolean } = {
269 color: 'black',
270 }
271 ): ConsoleText {
272 function objToCss(styleObj: Record<string, string>): string {
273 return Object.entries(styleObj).reduce(
274 (styleString, [propName, propValue]) => {
275 return `${styleString}${propName}:${propValue};`;
276 },
277 ''
278 );
279 }
280
281 const style: Record<string, string> = {
282 color: options.color,
283 };
284 if (options.strikeThrough) {
285 style['text-decoration'] = 'line-through';
286 }
287 if (options.bold) {
288 style['font-weight'] = 'bold';
289 }
290
291 return {
292 text,
293 style: objToCss(style),
294 };
295 }
297 > export function formatValue(value: unknown, availableLen: number): string {
298 > switch (typeof value) { consoleObservableLogger.ts ×8
299 > case 'number':
300 > return '' + value;
301 > case 'string':
302 if (value.length + 2 <= availableLen) {
303 return `"${value}"`;
304 }
305 return `"${value.substr(0, availableLen - 7)}"+...`;
307 > case 'boolean':
308 return value ? 'true' : 'false';
309 > case 'undefined': consoleObservableLogger.ts ×8
310 return 'undefined';
311 > case 'object': consoleObservableLogger.ts ×8
312 if (value === null) {
313 return 'null';
314 }
315 if (Array.isArray(value)) {
316 return formatArray(value, availableLen);
317 }
318 return formatObject(value, availableLen);
319 > case 'symbol': consoleObservableLogger.ts ×8
320 return value.toString();
321 > case 'function': consoleObservableLogger.ts ×8
322 return `[[Function${value.name ? ' ' + value.name : ''}]]`;
324 return '' + value;
326 > }
328 function formatArray(value: unknown[], availableLen: number): string {
329 let result = '[ ';
330 let first = true;
331 for (const val of value) {
332 if (!first) {
333 result += ', ';
334 }
335 if (result.length - 5 > availableLen) {
336 result += '...';
337 break;
338 }
339 first = false;
340 result += `${formatValue(val, availableLen - result.length)}`;
341 }
342 result += ' ]';
343 return result;
344 }
346 function formatObject(value: object, availableLen: number): string {
347 if (typeof value.toString === 'function' && value.toString !== Object.prototype.toString) {
348 const val = value.toString();
349 if (val.length <= availableLen) {
350 return val;
351 }
352 return val.substring(0, availableLen - 3) + '...';
353 }
354
355 const className = getClassName(value);
356
357 let result = className ? className + '(' : '{ ';
358 let first = true;
359 for (const [key, val] of Object.entries(value)) {
360 if (!first) {
361 result += ', ';
362 }
363 if (result.length - 5 > availableLen) {
364 result += '...';
365 break;
366 }
367 first = false;
368 result += `${key}: ${formatValue(val, availableLen - result.length)}`;
369 }
370 result += className ? ')' : ' }';
371 return result;
372 }
374 function repeat(str: string, count: number): string {
375 let result = '';
376 for (let i = 1; i <= count; i++) {
377 result += str;
378 }
379 return result;
380 }
382 function padStr(str: string, length: number): string {
383 while (str.length < length) {
384 str += ' ';
385 }
386 return str;
387 }