forked from jupyterlab/jupyterlab
/
widget.ts
477 lines (415 loc) · 13.1 KB
/
widget.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
// Copyright (c) Jupyter Development Team.
// Distributed under the terms of the Modified BSD License.
import { nbformat, IChangedArgs } from '@jupyterlab/coreutils';
import { OutputArea, IOutputPrompt } from '@jupyterlab/outputarea';
import { IRenderMimeRegistry } from '@jupyterlab/rendermime';
import { Kernel, KernelMessage } from '@jupyterlab/services';
import { Message } from '@phosphor/messaging';
import { ISignal, Signal } from '@phosphor/signaling';
import { Widget, Panel, PanelLayout, StackedPanel } from '@phosphor/widgets';
import { LogOutputModel, LoggerOutputAreaModel } from './logger';
import {
ILogger,
IContentChange,
ILoggerRegistry,
ILoggerRegistryChange,
LogLevel,
IStateChange
} from './tokens';
function toTitleCase(value: string) {
return value.length === 0 ? value : value[0].toUpperCase() + value.slice(1);
}
/**
* All severity levels, including an internal one for metadata.
*/
type FullLogLevel = LogLevel | 'metadata';
/**
* Log console output prompt implementation
*/
class LogConsoleOutputPrompt extends Widget implements IOutputPrompt {
constructor() {
super();
this._timestampNode = document.createElement('div');
this.node.append(this._timestampNode);
}
/**
* Date & time when output is logged.
*/
set timestamp(value: Date) {
this._timestamp = value;
this._timestampNode.innerHTML = this._timestamp.toLocaleTimeString();
this.update();
}
/**
* Log level
*/
set level(value: FullLogLevel) {
this._level = value;
this.node.dataset.logLevel = value;
this.update();
}
update() {
if (this._level !== undefined && this._timestamp !== undefined) {
this.node.title = `${this._timestamp.toLocaleString()}; ${toTitleCase(
this._level
)} level`;
}
}
/**
* The execution count for the prompt.
*/
executionCount: nbformat.ExecutionCount;
private _timestamp: Date;
private _level: FullLogLevel;
private _timestampNode: HTMLDivElement;
}
/**
* Output Area implementation displaying log outputs
* with prompts showing log timestamps.
*/
class LogConsoleOutputArea extends OutputArea {
/**
* The rendermime instance used by the widget.
*/
rendermime: IRenderMimeRegistry;
/**
* Output area model used by the widget.
*/
readonly model: LoggerOutputAreaModel;
/**
* Create an output item with a prompt and actual output
*/
protected createOutputItem(model: LogOutputModel): Widget | null {
const panel = super.createOutputItem(model) as Panel;
if (panel === null) {
// Could not render model
return null;
}
// first widget in panel is prompt of type LoggerOutputPrompt
let prompt = panel.widgets[0] as LogConsoleOutputPrompt;
prompt.timestamp = model.timestamp;
prompt.level = model.level;
return panel;
}
/**
* Handle an input request from a kernel by doing nothing.
*/
protected onInputRequest(
msg: KernelMessage.IInputRequestMsg,
future: Kernel.IShellFuture
): void {
return;
}
}
/**
* Implementation of `IContentFactory` for Output Area
* which creates custom output prompts.
*/
class LogConsoleContentFactory extends OutputArea.ContentFactory {
/**
* Create the output prompt for the widget.
*/
createOutputPrompt(): LogConsoleOutputPrompt {
return new LogConsoleOutputPrompt();
}
}
/**
* Implements a panel which supports pinning the position to the end if it is
* scrolled to the end.
*
* #### Notes
* This is useful for log viewing components or chat components that append
* elements at the end. We would like to automatically scroll when the user
* has scrolled to the bottom, but not change the scrolling when the user has
* changed the scroll position.
*/
export class ScrollingWidget<T extends Widget> extends Widget {
constructor({ content, ...options }: ScrollingWidget.IOptions<T>) {
super(options);
this.addClass('jp-Scrolling');
const layout = (this.layout = new PanelLayout());
layout.addWidget(content);
this._content = content;
this._sentinel = document.createElement('div');
this.node.appendChild(this._sentinel);
}
/**
* The content widget.
*/
get content(): T {
return this._content;
}
protected onAfterAttach(msg: Message) {
super.onAfterAttach(msg);
// defer so content gets a chance to attach first
requestAnimationFrame(() => {
this._sentinel.scrollIntoView();
this._scrollHeight = this.node.scrollHeight;
});
// Set up intersection observer for the sentinel
if (typeof IntersectionObserver !== 'undefined') {
this._observer = new IntersectionObserver(
args => {
this._handleScroll(args);
},
{ root: this.node, threshold: 1 }
);
this._observer.observe(this._sentinel);
}
}
protected onBeforeDetach(msg: Message) {
if (this._observer) {
this._observer.disconnect();
}
}
protected onAfterShow(msg: Message) {
if (this._tracking) {
this._sentinel.scrollIntoView();
}
}
private _handleScroll([entry]: IntersectionObserverEntry[]) {
if (entry.isIntersecting) {
this._tracking = true;
} else if (this.isVisible) {
const currentHeight = this.node.scrollHeight;
if (currentHeight === this._scrollHeight) {
// Likely the user scrolled manually
this._tracking = false;
} else {
// We assume we scrolled because our size changed, so scroll to the end.
this._sentinel.scrollIntoView();
this._scrollHeight = currentHeight;
this._tracking = true;
}
}
}
private _content: T;
private _observer: IntersectionObserver = null;
private _scrollHeight: number;
private _sentinel: HTMLDivElement;
private _tracking: boolean;
}
export namespace ScrollingWidget {
export interface IOptions<T extends Widget> extends Widget.IOptions {
content: T;
}
}
/**
* A StackedPanel implementation that creates Output Areas
* for each log source and activates as source is switched.
*/
export class LogConsolePanel extends StackedPanel {
/**
* Construct a LogConsolePanel instance.
*
* @param loggerRegistry - The logger registry that provides
* logs to be displayed.
*/
constructor(loggerRegistry: ILoggerRegistry) {
super();
this._loggerRegistry = loggerRegistry;
this.addClass('jp-LogConsolePanel');
loggerRegistry.registryChanged.connect(
(sender: ILoggerRegistry, args: ILoggerRegistryChange) => {
this._bindLoggerSignals();
},
this
);
this._bindLoggerSignals();
this._placeholder = new Widget();
this._placeholder.addClass('jp-LogConsoleListPlaceholder');
this.addWidget(this._placeholder);
}
/**
* The logger registry providing the logs.
*/
get loggerRegistry(): ILoggerRegistry {
return this._loggerRegistry;
}
/**
* The current logger.
*/
get logger(): ILogger | null {
if (this.source === null) {
return null;
}
return this.loggerRegistry.getLogger(this.source);
}
/**
* The log source displayed
*/
get source(): string | null {
return this._source;
}
set source(name: string | null) {
if (name === this._source) {
return;
}
const oldValue = this._source;
const newValue = (this._source = name);
this._showOutputFromSource(newValue);
this._handlePlaceholder();
this._sourceChanged.emit({ oldValue, newValue, name: 'source' });
}
/**
* The source version displayed.
*/
get sourceVersion(): number | null {
const source = this.source;
return source && this._loggerRegistry.getLogger(source).version;
}
/**
* Signal for source changes
*/
get sourceChanged(): ISignal<this, IChangedArgs<string | null, 'source'>> {
return this._sourceChanged;
}
/**
* Signal for source changes
*/
get sourceDisplayed(): ISignal<this, ISourceDisplayed> {
return this._sourceDisplayed;
}
protected onAfterAttach(msg: Message): void {
super.onAfterAttach(msg);
this._updateOutputAreas();
this._showOutputFromSource(this._source);
this._handlePlaceholder();
}
protected onAfterShow(msg: Message) {
super.onAfterShow(msg);
if (this.source !== null) {
this._sourceDisplayed.emit({
source: this.source,
version: this.sourceVersion
});
}
}
private _bindLoggerSignals() {
const loggers = this._loggerRegistry.getLoggers();
for (let logger of loggers) {
if (this._loggersWatched.has(logger.source)) {
continue;
}
logger.contentChanged.connect((sender: ILogger, args: IContentChange) => {
this._updateOutputAreas();
this._handlePlaceholder();
}, this);
logger.stateChanged.connect((sender: ILogger, change: IStateChange) => {
if (change.name !== 'rendermime') {
return;
}
const viewId = `source:${sender.source}`;
const outputArea = this._outputAreas.get(viewId);
if (outputArea) {
outputArea.rendermime = change.newValue;
}
}, this);
this._loggersWatched.add(logger.source);
}
}
private _showOutputFromSource(source: string | null) {
// If the source is null, pick a unique name so all output areas hide.
const viewId = source === null ? 'null source' : `source:${source}`;
this._outputAreas.forEach(
(outputArea: LogConsoleOutputArea, name: string) => {
// Show/hide the output area parents, the scrolling windows.
if (outputArea.id === viewId) {
outputArea.parent.show();
if (outputArea.isVisible) {
this._sourceDisplayed.emit({
source: this.source,
version: this.sourceVersion
});
}
} else {
outputArea.parent.hide();
}
}
);
const title = source === null ? 'Log Console' : `Log: ${source}`;
this.title.label = title;
this.title.caption = title;
}
private _handlePlaceholder() {
if (this.source === null) {
this._placeholder.node.textContent = 'No source selected.';
this._placeholder.show();
} else if (this._loggerRegistry.getLogger(this.source).length === 0) {
this._placeholder.node.textContent = 'No log messages.';
this._placeholder.show();
} else {
this._placeholder.hide();
this._placeholder.node.textContent = '';
}
}
private _updateOutputAreas() {
const loggerIds = new Set<string>();
const loggers = this._loggerRegistry.getLoggers();
for (let logger of loggers) {
const source = logger.source;
const viewId = `source:${source}`;
loggerIds.add(viewId);
// add view for logger if not exist
if (!this._outputAreas.has(viewId)) {
const outputArea = new LogConsoleOutputArea({
rendermime: logger.rendermime,
contentFactory: new LogConsoleContentFactory(),
model: logger.outputAreaModel
});
outputArea.id = viewId;
// Attach the output area so it is visible, so the accounting
// functions below record the outputs actually displayed.
let w = new ScrollingWidget({
content: outputArea
});
this.addWidget(w);
this._outputAreas.set(viewId, outputArea);
// This is where the source object is associated with the output area.
// We capture the source from this environment in the closure.
const outputUpdate = (sender: LogConsoleOutputArea) => {
// If the current log console panel source is the source associated
// with this output area, and the output area is visible, then emit
// the logConsolePanel source displayed signal.
if (this.source === source && sender.isVisible) {
// We assume that the output area has been updated to the current
// version of the source.
this._sourceDisplayed.emit({
source: this.source,
version: this.sourceVersion
});
}
};
// Notify messages were displayed any time the output area is updated
// and update for any outputs rendered on construction.
outputArea.outputLengthChanged.connect(outputUpdate, this);
// Since the output area was attached above, we can rely on its
// visibility to account for the messages displayed.
outputUpdate(outputArea);
}
}
// remove output areas that do not have corresponding loggers anymore
const viewIds = this._outputAreas.keys();
for (let viewId of viewIds) {
if (!loggerIds.has(viewId)) {
const outputArea = this._outputAreas.get(viewId);
outputArea.dispose();
this._outputAreas.delete(viewId);
}
}
}
private _loggerRegistry: ILoggerRegistry;
private _outputAreas = new Map<string, LogConsoleOutputArea>();
private _source: string | null = null;
private _sourceChanged = new Signal<
this,
IChangedArgs<string | null, 'source'>
>(this);
private _sourceDisplayed = new Signal<this, ISourceDisplayed>(this);
private _placeholder: Widget;
private _loggersWatched: Set<string> = new Set();
}
export interface ISourceDisplayed {
source: string;
version: number;
}