-
Notifications
You must be signed in to change notification settings - Fork 5.1k
/
Copy pathindex.ts
581 lines (513 loc) · 16.5 KB
/
index.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
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
// Copyright (c) Jupyter Development Team.
// Distributed under the terms of the Modified BSD License.
import {
JupyterFrontEnd,
JupyterFrontEndPlugin,
} from '@jupyterlab/application';
import {
ISessionContext,
DOMUtils,
IToolbarWidgetRegistry,
ICommandPalette,
} from '@jupyterlab/apputils';
import { Cell, CodeCell } from '@jupyterlab/cells';
import { PageConfig, Text, Time, URLExt } from '@jupyterlab/coreutils';
import { IDocumentManager } from '@jupyterlab/docmanager';
import { IMainMenu } from '@jupyterlab/mainmenu';
import {
NotebookPanel,
INotebookTracker,
INotebookTools,
} from '@jupyterlab/notebook';
import { ISettingRegistry } from '@jupyterlab/settingregistry';
import { ITranslator, nullTranslator } from '@jupyterlab/translation';
import { INotebookShell } from '@jupyter-notebook/application';
import { Poll } from '@lumino/polling';
import { Widget } from '@lumino/widgets';
import { TrustedComponent } from './trusted';
/**
* The class for kernel status errors.
*/
const KERNEL_STATUS_ERROR_CLASS = 'jp-NotebookKernelStatus-error';
/**
* The class for kernel status warnings.
*/
const KERNEL_STATUS_WARN_CLASS = 'jp-NotebookKernelStatus-warn';
/**
* The class for kernel status infos.
*/
const KERNEL_STATUS_INFO_CLASS = 'jp-NotebookKernelStatus-info';
/**
* The class to fade out the kernel status.
*/
const KERNEL_STATUS_FADE_OUT_CLASS = 'jp-NotebookKernelStatus-fade';
/**
* The class for scrolled outputs
*/
const SCROLLED_OUTPUTS_CLASS = 'jp-mod-outputsScrolled';
/**
* The command IDs used by the notebook plugins.
*/
namespace CommandIDs {
/**
* A command to open right sidebar for Editing Notebook Metadata
*/
export const openEditNotebookMetadata = 'notebook:edit-metadata';
}
/**
* A plugin for the checkpoint indicator
*/
const checkpoints: JupyterFrontEndPlugin<void> = {
id: '@jupyter-notebook/notebook-extension:checkpoints',
description: 'A plugin for the checkpoint indicator.',
autoStart: true,
requires: [IDocumentManager, ITranslator],
optional: [INotebookShell, IToolbarWidgetRegistry],
activate: (
app: JupyterFrontEnd,
docManager: IDocumentManager,
translator: ITranslator,
notebookShell: INotebookShell | null,
toolbarRegistry: IToolbarWidgetRegistry | null
) => {
const { shell } = app;
const trans = translator.load('notebook');
const node = document.createElement('div');
if (toolbarRegistry) {
toolbarRegistry.addFactory('TopBar', 'checkpoint', (toolbar) => {
const widget = new Widget({ node });
widget.id = DOMUtils.createDomID();
widget.addClass('jp-NotebookCheckpoint');
return widget;
});
}
const onChange = async () => {
const current = shell.currentWidget;
if (!current) {
return;
}
const context = docManager.contextForWidget(current);
context?.fileChanged.disconnect(onChange);
context?.fileChanged.connect(onChange);
const checkpoints = await context?.listCheckpoints();
if (!checkpoints) {
return;
}
const checkpoint = checkpoints[checkpoints.length - 1];
node.textContent = trans.__(
'Last Checkpoint: %1',
Time.formatHuman(new Date(checkpoint.last_modified))
);
};
if (notebookShell) {
notebookShell.currentChanged.connect(onChange);
}
new Poll({
auto: true,
factory: () => onChange(),
frequency: {
interval: 2000,
backoff: false,
},
standby: 'when-hidden',
});
},
};
/**
* Add a command to close the browser tab when clicking on "Close and Shut Down"
*/
const closeTab: JupyterFrontEndPlugin<void> = {
id: '@jupyter-notebook/notebook-extension:close-tab',
description:
'Add a command to close the browser tab when clicking on "Close and Shut Down".',
autoStart: true,
requires: [IMainMenu],
optional: [ITranslator],
activate: (
app: JupyterFrontEnd,
menu: IMainMenu,
translator: ITranslator | null
) => {
const { commands } = app;
translator = translator ?? nullTranslator;
const trans = translator.load('notebook');
const id = 'notebook:close-and-halt';
commands.addCommand(id, {
label: trans.__('Close and Shut Down Notebook'),
execute: async () => {
await commands.execute('notebook:close-and-shutdown');
window.close();
},
});
menu.fileMenu.closeAndCleaners.add({
id,
// use a small rank to it takes precedence over the default
// shut down action for the notebook
rank: 0,
});
},
};
/**
* The kernel logo plugin.
*/
const kernelLogo: JupyterFrontEndPlugin<void> = {
id: '@jupyter-notebook/notebook-extension:kernel-logo',
description: 'The kernel logo plugin.',
autoStart: true,
requires: [INotebookShell],
optional: [IToolbarWidgetRegistry],
activate: (
app: JupyterFrontEnd,
shell: INotebookShell,
toolbarRegistry: IToolbarWidgetRegistry | null
) => {
const { serviceManager } = app;
const node = document.createElement('div');
const img = document.createElement('img');
const onChange = async () => {
const current = shell.currentWidget;
if (!(current instanceof NotebookPanel)) {
return;
}
if (!node.hasChildNodes()) {
node.appendChild(img);
}
await current.sessionContext.ready;
current.sessionContext.kernelChanged.disconnect(onChange);
current.sessionContext.kernelChanged.connect(onChange);
const name = current.sessionContext.session?.kernel?.name ?? '';
const spec = serviceManager.kernelspecs?.specs?.kernelspecs[name];
if (!spec) {
node.childNodes[0].remove();
return;
}
const kernelIconUrl = spec.resources['logo-64x64'];
if (!kernelIconUrl) {
node.childNodes[0].remove();
return;
}
img.src = kernelIconUrl;
img.title = spec.display_name;
};
if (toolbarRegistry) {
toolbarRegistry.addFactory('TopBar', 'kernelLogo', (toolbar) => {
const widget = new Widget({ node });
widget.addClass('jp-NotebookKernelLogo');
return widget;
});
}
app.started.then(() => {
shell.currentChanged.connect(onChange);
});
},
};
/**
* A plugin to display the kernel status;
*/
const kernelStatus: JupyterFrontEndPlugin<void> = {
id: '@jupyter-notebook/notebook-extension:kernel-status',
description: 'A plugin to display the kernel status.',
autoStart: true,
requires: [INotebookShell, ITranslator],
activate: (
app: JupyterFrontEnd,
shell: INotebookShell,
translator: ITranslator
) => {
const trans = translator.load('notebook');
const widget = new Widget();
widget.addClass('jp-NotebookKernelStatus');
app.shell.add(widget, 'menu', { rank: 10_010 });
const removeClasses = () => {
widget.removeClass(KERNEL_STATUS_ERROR_CLASS);
widget.removeClass(KERNEL_STATUS_WARN_CLASS);
widget.removeClass(KERNEL_STATUS_INFO_CLASS);
widget.removeClass(KERNEL_STATUS_FADE_OUT_CLASS);
};
const onStatusChanged = (sessionContext: ISessionContext) => {
const status = sessionContext.kernelDisplayStatus;
let text = `Kernel ${Text.titleCase(status)}`;
removeClasses();
switch (status) {
case 'busy':
case 'idle':
text = '';
widget.addClass(KERNEL_STATUS_FADE_OUT_CLASS);
break;
case 'dead':
case 'terminating':
widget.addClass(KERNEL_STATUS_ERROR_CLASS);
break;
case 'unknown':
widget.addClass(KERNEL_STATUS_WARN_CLASS);
break;
default:
widget.addClass(KERNEL_STATUS_INFO_CLASS);
widget.addClass(KERNEL_STATUS_FADE_OUT_CLASS);
break;
}
widget.node.textContent = trans.__(text);
};
const onChange = async () => {
const current = shell.currentWidget;
if (!(current instanceof NotebookPanel)) {
return;
}
const sessionContext = current.sessionContext;
sessionContext.statusChanged.connect(onStatusChanged);
};
shell.currentChanged.connect(onChange);
},
};
/**
* A plugin to enable scrolling for outputs by default.
* Mimic the logic from the classic notebook, as found here:
* https://github.com/jupyter/notebook/blob/a9a31c096eeffe1bff4e9164c6a0442e0e13cdb3/notebook/static/notebook/js/outputarea.js#L96-L120
*/
const scrollOutput: JupyterFrontEndPlugin<void> = {
id: '@jupyter-notebook/notebook-extension:scroll-output',
description: 'A plugin to enable scrolling for outputs by default.',
autoStart: true,
requires: [INotebookTracker],
optional: [ISettingRegistry],
activate: async (
app: JupyterFrontEnd,
tracker: INotebookTracker,
settingRegistry: ISettingRegistry | null
) => {
const autoScrollThreshold = 100;
let autoScrollOutputs = true;
// decide whether to scroll the output of the cell based on some heuristics
const autoScroll = (cell: CodeCell) => {
if (!autoScrollOutputs) {
// bail if disabled via the settings
return;
}
const { outputArea } = cell;
// respect cells with an explicit scrolled state
const scrolled = cell.model.getMetadata('scrolled');
if (scrolled !== undefined) {
return;
}
const { node } = outputArea;
const height = node.scrollHeight;
const fontSize = parseFloat(node.style.fontSize.replace('px', ''));
const lineHeight = (fontSize || 14) * 1.3;
// do not set via cell.outputScrolled = true, as this would
// otherwise synchronize the scrolled state to the notebook metadata
const scroll = height > lineHeight * autoScrollThreshold;
cell.toggleClass(SCROLLED_OUTPUTS_CLASS, scroll);
};
const handlers: { [id: string]: () => void } = {};
const setAutoScroll = (cell: Cell) => {
if (cell.model.type === 'code') {
const codeCell = cell as CodeCell;
const id = codeCell.model.id;
autoScroll(codeCell);
if (handlers[id]) {
codeCell.outputArea.model.changed.disconnect(handlers[id]);
}
handlers[id] = () => autoScroll(codeCell);
codeCell.outputArea.model.changed.connect(handlers[id]);
}
};
tracker.widgetAdded.connect((sender, notebook) => {
// when the notebook widget is created, process all the cells
notebook.sessionContext.ready.then(() => {
notebook.content.widgets.forEach(setAutoScroll);
});
notebook.model?.cells.changed.connect((sender, args) => {
notebook.content.widgets.forEach(setAutoScroll);
});
});
if (settingRegistry) {
const loadSettings = settingRegistry.load(scrollOutput.id);
const updateSettings = (settings: ISettingRegistry.ISettings): void => {
autoScrollOutputs = settings.get('autoScrollOutputs')
.composite as boolean;
};
Promise.all([loadSettings, app.restored])
.then(([settings]) => {
updateSettings(settings);
settings.changed.connect((settings) => {
updateSettings(settings);
});
})
.catch((reason: Error) => {
console.error(reason.message);
});
}
},
};
/**
* A plugin to add the NotebookTools to the side panel;
*/
const notebookToolsWidget: JupyterFrontEndPlugin<void> = {
id: '@jupyter-notebook/notebook-extension:notebook-tools',
description: 'A plugin to add the NotebookTools to the side panel.',
autoStart: true,
requires: [INotebookShell],
optional: [INotebookTools],
activate: (
app: JupyterFrontEnd,
shell: INotebookShell,
notebookTools: INotebookTools | null
) => {
const onChange = async () => {
const current = shell.currentWidget;
if (!(current instanceof NotebookPanel)) {
return;
}
// Add the notebook tools in right area.
if (notebookTools) {
shell.add(notebookTools, 'right', { type: 'Property Inspector' });
}
};
shell.currentChanged.connect(onChange);
},
};
/**
* A plugin to update the tab icon based on the kernel status.
*/
const tabIcon: JupyterFrontEndPlugin<void> = {
id: '@jupyter-notebook/notebook-extension:tab-icon',
description: 'A plugin to update the tab icon based on the kernel status.',
autoStart: true,
requires: [INotebookTracker],
activate: (app: JupyterFrontEnd, tracker: INotebookTracker) => {
// the favicons are provided by Jupyter Server
const baseURL = PageConfig.getBaseUrl();
const notebookIcon = URLExt.join(
baseURL,
'static/favicons/favicon-notebook.ico'
);
const busyIcon = URLExt.join(baseURL, 'static/favicons/favicon-busy-1.ico');
const updateBrowserFavicon = (
status: ISessionContext.KernelDisplayStatus
) => {
const link = document.querySelector(
"link[rel*='icon']"
) as HTMLLinkElement;
switch (status) {
case 'busy':
link.href = busyIcon;
break;
case 'idle':
link.href = notebookIcon;
break;
}
};
const onChange = async () => {
const current = tracker.currentWidget;
const sessionContext = current?.sessionContext;
if (!sessionContext) {
return;
}
sessionContext.statusChanged.connect(() => {
const status = sessionContext.kernelDisplayStatus;
updateBrowserFavicon(status);
});
};
tracker.currentChanged.connect(onChange);
},
};
/**
* A plugin that adds a Trusted indicator to the menu area
*/
const trusted: JupyterFrontEndPlugin<void> = {
id: '@jupyter-notebook/notebook-extension:trusted',
description: 'A plugin that adds a Trusted indicator to the menu area.',
autoStart: true,
requires: [INotebookShell, ITranslator],
activate: (
app: JupyterFrontEnd,
notebookShell: INotebookShell,
translator: ITranslator
): void => {
const onChange = async () => {
const current = notebookShell.currentWidget;
if (!(current instanceof NotebookPanel)) {
return;
}
const notebook = current.content;
await current.context.ready;
const widget = TrustedComponent.create({ notebook, translator });
notebookShell.add(widget, 'menu', {
rank: 11_000,
});
};
notebookShell.currentChanged.connect(onChange);
},
};
/**
* Add a command to open right sidebar for Editing Notebook Metadata when clicking on "Edit Notebook Metadata" under Edit menu
*/
const editNotebookMetadata: JupyterFrontEndPlugin<void> = {
id: '@jupyter-notebook/notebook-extension:edit-notebook-metadata',
description:
'Add a command to open right sidebar for Editing Notebook Metadata when clicking on "Edit Notebook Metadata" under Edit menu',
autoStart: true,
optional: [ICommandPalette, ITranslator, INotebookTools],
activate: (
app: JupyterFrontEnd,
palette: ICommandPalette | null,
translator: ITranslator | null,
notebookTools: INotebookTools | null
) => {
const { commands, shell } = app;
translator = translator ?? nullTranslator;
const trans = translator.load('notebook');
commands.addCommand(CommandIDs.openEditNotebookMetadata, {
label: trans.__('Edit Notebook Metadata'),
execute: async () => {
const command = 'application:toggle-panel';
const args = {
side: 'right',
title: 'Show Notebook Tools',
id: 'notebook-tools',
};
// Check if Show Notebook Tools (Right Sidebar) is open (expanded)
if (!commands.isToggled(command, args)) {
await commands.execute(command, args).then((_) => {
// For expanding the 'Advanced Tools' section (default: collapsed)
if (notebookTools) {
const tools = (notebookTools?.layout as any).widgets;
tools.forEach((tool: any) => {
if (
tool.widget.title.label === trans.__('Advanced Tools') &&
tool.collapsed
) {
tool.toggle();
}
});
}
});
}
},
isVisible: () =>
shell.currentWidget !== null &&
shell.currentWidget instanceof NotebookPanel,
});
if (palette) {
palette.addItem({
command: CommandIDs.openEditNotebookMetadata,
category: 'Notebook Operations',
});
}
},
};
/**
* Export the plugins as default.
*/
const plugins: JupyterFrontEndPlugin<any>[] = [
checkpoints,
closeTab,
editNotebookMetadata,
kernelLogo,
kernelStatus,
notebookToolsWidget,
scrollOutput,
tabIcon,
trusted,
];
export default plugins;