Debian Codegraph @

packages/notebook-extension/src/index.ts

raw
1 // Copyright (c) Jupyter Development Team.
2 // Distributed under the terms of the Modified BSD License.
3
4 import {
5 JupyterFrontEnd,
6 JupyterFrontEndPlugin,
7 } from '@jupyterlab/application';
8
9 import {
10 ISessionContext,
11 DOMUtils,
12 IToolbarWidgetRegistry,
13 ICommandPalette,
14 } from '@jupyterlab/apputils';
15
16 import { Cell, CodeCell } from '@jupyterlab/cells';
17
18 import { PageConfig, Text, Time, URLExt } from '@jupyterlab/coreutils';
19
20 import { IDocumentManager } from '@jupyterlab/docmanager';
21
22 import { IMainMenu } from '@jupyterlab/mainmenu';
23
24 import {
25 NotebookPanel,
26 INotebookTracker,
27 INotebookTools,
28 } from '@jupyterlab/notebook';
29
30 import { ISettingRegistry } from '@jupyterlab/settingregistry';
31
32 import { ITranslator, nullTranslator } from '@jupyterlab/translation';
33
34 import { INotebookShell } from '@jupyter-notebook/application';
35
36 import { Poll } from '@lumino/polling';
37
38 import { Widget } from '@lumino/widgets';
39
40 import { TrustedComponent } from './trusted';
41
42 /**
43 * The class for kernel status errors.
44 */
45 const KERNEL_STATUS_ERROR_CLASS = 'jp-NotebookKernelStatus-error';
46
47 /**
48 * The class for kernel status warnings.
49 */
50 const KERNEL_STATUS_WARN_CLASS = 'jp-NotebookKernelStatus-warn';
51
52 /**
53 * The class for kernel status infos.
54 */
55 const KERNEL_STATUS_INFO_CLASS = 'jp-NotebookKernelStatus-info';
56
57 /**
58 * The class to fade out the kernel status.
59 */
60 const KERNEL_STATUS_FADE_OUT_CLASS = 'jp-NotebookKernelStatus-fade';
61
62 /**
63 * The class for scrolled outputs
64 */
65 const SCROLLED_OUTPUTS_CLASS = 'jp-mod-outputsScrolled';
66
67 /**
68 * The class for the full width notebook
69 */
70 const FULL_WIDTH_NOTEBOOK_CLASS = 'jp-mod-fullwidth';
71
72 /**
73 * The command IDs used by the notebook plugins.
74 */
75 namespace CommandIDs {
76 /**
77 * A command to open right sidebar for Editing Notebook Metadata
78 */
79 export const openEditNotebookMetadata = 'notebook:edit-metadata';
80
81 /**
82 * A command to toggle full width of the notebook
83 */
84 export const toggleFullWidth = 'notebook:toggle-full-width';
85 }
86
87 /**
88 * A plugin for the checkpoint indicator
89 */
90 const checkpoints: JupyterFrontEndPlugin<void> = {
91 id: '@jupyter-notebook/notebook-extension:checkpoints',
92 description: 'A plugin for the checkpoint indicator.',
93 autoStart: true,
94 requires: [IDocumentManager, ITranslator],
95 optional: [INotebookShell, IToolbarWidgetRegistry],
96 activate: (
97 app: JupyterFrontEnd,
98 docManager: IDocumentManager,
99 translator: ITranslator,
100 notebookShell: INotebookShell | null,
101 toolbarRegistry: IToolbarWidgetRegistry | null
102 ) => {
103 const { shell } = app;
104 const trans = translator.load('notebook');
105 const node = document.createElement('div');
106
107 if (toolbarRegistry) {
108 toolbarRegistry.addFactory('TopBar', 'checkpoint', (toolbar) => {
109 const widget = new Widget({ node });
110 widget.id = DOMUtils.createDomID();
111 widget.addClass('jp-NotebookCheckpoint');
112 return widget;
113 });
114 }
115
116 const onChange = async () => {
117 const current = shell.currentWidget;
118 if (!current) {
119 return;
120 }
121 const context = docManager.contextForWidget(current);
122
123 context?.fileChanged.disconnect(onChange);
124 context?.fileChanged.connect(onChange);
125
126 const checkpoints = await context?.listCheckpoints();
127 if (!checkpoints || !checkpoints.length) {
128 return;
129 }
130 const checkpoint = checkpoints[checkpoints.length - 1];
131 node.textContent = trans.__(
132 'Last Checkpoint: %1',
133 Time.formatHuman(new Date(checkpoint.last_modified))
134 );
135 };
136
137 if (notebookShell) {
138 notebookShell.currentChanged.connect(onChange);
139 }
140
141 new Poll({
142 auto: true,
143 factory: () => onChange(),
144 frequency: {
145 interval: 2000,
146 backoff: false,
147 },
148 standby: 'when-hidden',
149 });
150 },
151 };
152
153 /**
154 * Add a command to close the browser tab when clicking on "Close and Shut Down"
155 */
156 const closeTab: JupyterFrontEndPlugin<void> = {
157 id: '@jupyter-notebook/notebook-extension:close-tab',
158 description:
159 'Add a command to close the browser tab when clicking on "Close and Shut Down".',
160 autoStart: true,
161 requires: [IMainMenu],
162 optional: [ITranslator],
163 activate: (
164 app: JupyterFrontEnd,
165 menu: IMainMenu,
166 translator: ITranslator | null
167 ) => {
168 const { commands } = app;
169 translator = translator ?? nullTranslator;
170 const trans = translator.load('notebook');
171
172 const id = 'notebook:close-and-halt';
173 commands.addCommand(id, {
174 label: trans.__('Close and Shut Down Notebook'),
175 execute: async () => {
176 // Shut the kernel down, without confirmation
177 await commands.execute('notebook:shutdown-kernel', { activate: false });
178 window.close();
179 },
180 });
181 menu.fileMenu.closeAndCleaners.add({
182 id,
183 // use a small rank to it takes precedence over the default
184 // shut down action for the notebook
185 rank: 0,
186 });
187 },
188 };
189
190 /**
191 * Add a command to open the tree view from the notebook view
192 */
193 const openTreeTab: JupyterFrontEndPlugin<void> = {
194 id: '@jupyter-notebook/notebook-extension:open-tree-tab',
195 description:
196 'Add a command to open a browser tab on the tree view when clicking "Open...".',
197 autoStart: true,
198 optional: [ITranslator],
199 activate: (app: JupyterFrontEnd, translator: ITranslator | null) => {
200 const { commands } = app;
201 translator = translator ?? nullTranslator;
202 const trans = translator.load('notebook');
203
204 const id = 'notebook:open-tree-tab';
205 commands.addCommand(id, {
206 label: trans.__('Open…'),
207 execute: async () => {
208 const url = URLExt.join(PageConfig.getBaseUrl(), 'tree');
209 window.open(url);
210 },
211 });
212 },
213 };
214
215 /**
216 * A plugin to set the notebook to full width.
217 */
218 const fullWidthNotebook: JupyterFrontEndPlugin<void> = {
219 id: '@jupyter-notebook/notebook-extension:full-width-notebook',
220 description: 'A plugin to set the notebook to full width.',
221 autoStart: true,
222 requires: [INotebookTracker],
223 optional: [ICommandPalette, ISettingRegistry, ITranslator],
224 activate: (
225 app: JupyterFrontEnd,
226 tracker: INotebookTracker,
227 palette: ICommandPalette | null,
228 settingRegistry: ISettingRegistry | null,
229 translator: ITranslator | null
230 ) => {
231 const trans = (translator ?? nullTranslator).load('notebook');
232
233 let fullWidth = false;
234
235 const toggleFullWidth = () => {
236 const current = tracker.currentWidget;
237 fullWidth = !fullWidth;
238 if (!current) {
239 return;
240 }
241 const content = current;
242 content.toggleClass(FULL_WIDTH_NOTEBOOK_CLASS, fullWidth);
243 };
244
245 let notebookSettings: ISettingRegistry.ISettings;
246
247 if (settingRegistry) {
248 const loadSettings = settingRegistry.load(fullWidthNotebook.id);
249
250 const updateSettings = (settings: ISettingRegistry.ISettings): void => {
251 const newFullWidth = settings.get('fullWidthNotebook')
252 .composite as boolean;
253 if (newFullWidth !== fullWidth) {
254 toggleFullWidth();
255 }
256 };
257
258 Promise.all([loadSettings, app.restored])
259 .then(([settings]) => {
260 notebookSettings = settings;
261 updateSettings(settings);
262 settings.changed.connect((settings) => {
263 updateSettings(settings);
264 });
265 })
266 .catch((reason: Error) => {
267 console.error(reason.message);
268 });
269 }
270
271 app.commands.addCommand(CommandIDs.toggleFullWidth, {
272 label: trans.__('Enable Full Width Notebook'),
273 execute: () => {
274 toggleFullWidth();
275 if (notebookSettings) {
276 notebookSettings.set('fullWidthNotebook', fullWidth);
277 }
278 },
279 isEnabled: () => tracker.currentWidget !== null,
280 isToggled: () => fullWidth,
281 });
282
283 if (palette) {
284 palette.addItem({
285 command: CommandIDs.toggleFullWidth,
286 category: 'Notebook Operations',
287 });
288 }
289 },
290 };
291
292 /**
293 * The kernel logo plugin.
294 */
295 const kernelLogo: JupyterFrontEndPlugin<void> = {
296 id: '@jupyter-notebook/notebook-extension:kernel-logo',
297 description: 'The kernel logo plugin.',
298 autoStart: true,
299 requires: [INotebookShell],
300 optional: [IToolbarWidgetRegistry],
301 activate: (
302 app: JupyterFrontEnd,
303 shell: INotebookShell,
304 toolbarRegistry: IToolbarWidgetRegistry | null
305 ) => {
306 const { serviceManager } = app;
307
308 const node = document.createElement('div');
309 const img = document.createElement('img');
310
311 const onChange = async () => {
312 const current = shell.currentWidget;
313 if (!(current instanceof NotebookPanel)) {
314 return;
315 }
316
317 if (!node.hasChildNodes()) {
318 node.appendChild(img);
319 }
320
321 await current.sessionContext.ready;
322 current.sessionContext.kernelChanged.disconnect(onChange);
323 current.sessionContext.kernelChanged.connect(onChange);
324
325 const name = current.sessionContext.session?.kernel?.name ?? '';
326 const spec = serviceManager.kernelspecs?.specs?.kernelspecs[name];
327 if (!spec) {
328 node.childNodes[0].remove();
329 return;
330 }
331
332 const kernelIconUrl = spec.resources['logo-64x64'];
333 if (!kernelIconUrl) {
334 node.childNodes[0].remove();
335 return;
336 }
337
338 img.src = kernelIconUrl;
339 img.title = spec.display_name;
340 };
341
342 if (toolbarRegistry) {
343 toolbarRegistry.addFactory('TopBar', 'kernelLogo', (toolbar) => {
344 const widget = new Widget({ node });
345 widget.addClass('jp-NotebookKernelLogo');
346 return widget;
347 });
348 }
349
350 app.started.then(() => {
351 shell.currentChanged.connect(onChange);
352 });
353 },
354 };
355
356 /**
357 * A plugin to display the kernel status;
358 */
359 const kernelStatus: JupyterFrontEndPlugin<void> = {
360 id: '@jupyter-notebook/notebook-extension:kernel-status',
361 description: 'A plugin to display the kernel status.',
362 autoStart: true,
363 requires: [INotebookShell, ITranslator],
364 activate: (
365 app: JupyterFrontEnd,
366 shell: INotebookShell,
367 translator: ITranslator
368 ) => {
369 const trans = translator.load('notebook');
370 const widget = new Widget();
371 widget.addClass('jp-NotebookKernelStatus');
372 app.shell.add(widget, 'menu', { rank: 10_010 });
373
374 const removeClasses = () => {
375 widget.removeClass(KERNEL_STATUS_ERROR_CLASS);
376 widget.removeClass(KERNEL_STATUS_WARN_CLASS);
377 widget.removeClass(KERNEL_STATUS_INFO_CLASS);
378 widget.removeClass(KERNEL_STATUS_FADE_OUT_CLASS);
379 };
380
381 const onStatusChanged = (sessionContext: ISessionContext) => {
382 const status = sessionContext.kernelDisplayStatus;
383 let text = `Kernel ${Text.titleCase(status)}`;
384 removeClasses();
385 switch (status) {
386 case 'busy':
387 case 'idle':
388 text = '';
389 widget.addClass(KERNEL_STATUS_FADE_OUT_CLASS);
390 break;
391 case 'dead':
392 case 'terminating':
393 widget.addClass(KERNEL_STATUS_ERROR_CLASS);
394 break;
395 case 'unknown':
396 widget.addClass(KERNEL_STATUS_WARN_CLASS);
397 break;
398 default:
399 widget.addClass(KERNEL_STATUS_INFO_CLASS);
400 widget.addClass(KERNEL_STATUS_FADE_OUT_CLASS);
401 break;
402 }
403 widget.node.textContent = trans.__(text);
404 };
405
406 const onChange = async () => {
407 const current = shell.currentWidget;
408 if (!(current instanceof NotebookPanel)) {
409 return;
410 }
411 const sessionContext = current.sessionContext;
412 sessionContext.statusChanged.connect(onStatusChanged);
413 };
414
415 shell.currentChanged.connect(onChange);
416 },
417 };
418
419 /**
420 * A plugin to enable scrolling for outputs by default.
421 * Mimic the logic from the classic notebook, as found here:
422 * https://github.com/jupyter/notebook/blob/a9a31c096eeffe1bff4e9164c6a0442e0e13cdb3/notebook/static/notebook/js/outputarea.js#L96-L120
423 */
424 const scrollOutput: JupyterFrontEndPlugin<void> = {
425 id: '@jupyter-notebook/notebook-extension:scroll-output',
426 description: 'A plugin to enable scrolling for outputs by default.',
427 autoStart: true,
428 requires: [INotebookTracker],
429 optional: [ISettingRegistry],
430 activate: async (
431 app: JupyterFrontEnd,
432 tracker: INotebookTracker,
433 settingRegistry: ISettingRegistry | null
434 ) => {
435 const autoScrollThreshold = 100;
436 let autoScrollOutputs = true;
437
438 // decide whether to scroll the output of the cell based on some heuristics
439 const autoScroll = (cell: CodeCell) => {
440 if (!autoScrollOutputs) {
441 // bail if disabled via the settings
442 cell.removeClass(SCROLLED_OUTPUTS_CLASS);
443 return;
444 }
445 const { outputArea } = cell;
446 // respect cells with an explicit scrolled state
447 const scrolled = cell.model.getMetadata('scrolled');
448 if (scrolled !== undefined) {
449 return;
450 }
451 const { node } = outputArea;
452 const height = node.scrollHeight;
453 const fontSize = parseFloat(node.style.fontSize.replace('px', ''));
454 const lineHeight = (fontSize || 14) * 1.3;
455 // do not set via cell.outputScrolled = true, as this would
456 // otherwise synchronize the scrolled state to the notebook metadata
457 const scroll = height > lineHeight * autoScrollThreshold;
458 cell.toggleClass(SCROLLED_OUTPUTS_CLASS, scroll);
459 };
460
461 const handlers: { [id: string]: () => void } = {};
462
463 const setAutoScroll = (cell: Cell) => {
464 if (cell.model.type === 'code') {
465 const codeCell = cell as CodeCell;
466 const id = codeCell.model.id;
467 autoScroll(codeCell);
468 if (handlers[id]) {
469 codeCell.outputArea.model.changed.disconnect(handlers[id]);
470 }
471 handlers[id] = () => autoScroll(codeCell);
472 codeCell.outputArea.model.changed.connect(handlers[id]);
473 }
474 };
475
476 tracker.widgetAdded.connect((sender, notebook) => {
477 // when the notebook widget is created, process all the cells
478 notebook.sessionContext.ready.then(() => {
479 notebook.content.widgets.forEach(setAutoScroll);
480 });
481
482 notebook.model?.cells.changed.connect((sender, args) => {
483 notebook.content.widgets.forEach(setAutoScroll);
484 });
485 });
486
487 if (settingRegistry) {
488 const loadSettings = settingRegistry.load(scrollOutput.id);
489 const updateSettings = (settings: ISettingRegistry.ISettings): void => {
490 autoScrollOutputs = settings.get('autoScrollOutputs')
491 .composite as boolean;
492 };
493
494 Promise.all([loadSettings, app.restored])
495 .then(([settings]) => {
496 updateSettings(settings);
497 settings.changed.connect((settings) => {
498 updateSettings(settings);
499 });
500 })
501 .catch((reason: Error) => {
502 console.error(reason.message);
503 });
504 }
505 },
506 };
507
508 /**
509 * A plugin to add the NotebookTools to the side panel;
510 */
511 const notebookToolsWidget: JupyterFrontEndPlugin<void> = {
512 id: '@jupyter-notebook/notebook-extension:notebook-tools',
513 description: 'A plugin to add the NotebookTools to the side panel.',
514 autoStart: true,
515 requires: [INotebookShell],
516 optional: [INotebookTools],
517 activate: (
518 app: JupyterFrontEnd,
519 shell: INotebookShell,
520 notebookTools: INotebookTools | null
521 ) => {
522 const onChange = async () => {
523 const current = shell.currentWidget;
524 if (!(current instanceof NotebookPanel)) {
525 return;
526 }
527
528 // Add the notebook tools in right area.
529 if (notebookTools) {
530 shell.add(notebookTools, 'right', { type: 'Property Inspector' });
531 }
532 };
533 shell.currentChanged.connect(onChange);
534 },
535 };
536
537 /**
538 * A plugin to update the tab icon based on the kernel status.
539 */
540 const tabIcon: JupyterFrontEndPlugin<void> = {
541 id: '@jupyter-notebook/notebook-extension:tab-icon',
542 description: 'A plugin to update the tab icon based on the kernel status.',
543 autoStart: true,
544 requires: [INotebookTracker],
545 activate: (app: JupyterFrontEnd, tracker: INotebookTracker) => {
546 // the favicons are provided by Jupyter Server
547 const baseURL = PageConfig.getBaseUrl();
548 const notebookIcon = URLExt.join(
549 baseURL,
550 'static/favicons/favicon-notebook.ico'
551 );
552 const busyIcon = URLExt.join(baseURL, 'static/favicons/favicon-busy-1.ico');
553
554 const updateBrowserFavicon = (
555 status: ISessionContext.KernelDisplayStatus
556 ) => {
557 const link = document.querySelector(
558 "link[rel*='icon']"
559 ) as HTMLLinkElement;
560 switch (status) {
561 case 'busy':
562 link.href = busyIcon;
563 break;
564 case 'idle':
565 link.href = notebookIcon;
566 break;
567 }
568 };
569
570 const onChange = async () => {
571 const current = tracker.currentWidget;
572 const sessionContext = current?.sessionContext;
573 if (!sessionContext) {
574 return;
575 }
576
577 sessionContext.statusChanged.connect(() => {
578 const status = sessionContext.kernelDisplayStatus;
579 updateBrowserFavicon(status);
580 });
581 };
582
583 tracker.currentChanged.connect(onChange);
584 },
585 };
586
587 /**
588 * A plugin that adds a Trusted indicator to the menu area
589 */
590 const trusted: JupyterFrontEndPlugin<void> = {
591 id: '@jupyter-notebook/notebook-extension:trusted',
592 description: 'A plugin that adds a Trusted indicator to the menu area.',
593 autoStart: true,
594 requires: [INotebookShell, ITranslator],
595 activate: (
596 app: JupyterFrontEnd,
597 notebookShell: INotebookShell,
598 translator: ITranslator
599 ): void => {
600 const onChange = async () => {
601 const current = notebookShell.currentWidget;
602 if (!(current instanceof NotebookPanel)) {
603 return;
604 }
605
606 const notebook = current.content;
607 await current.context.ready;
608
609 const widget = TrustedComponent.create({ notebook, translator });
610 notebookShell.add(widget, 'menu', {
611 rank: 11_000,
612 });
613 };
614
615 notebookShell.currentChanged.connect(onChange);
616 },
617 };
618
619 /**
620 * Add a command to open right sidebar for Editing Notebook Metadata when clicking on "Edit Notebook Metadata" under Edit menu
621 */
622 const editNotebookMetadata: JupyterFrontEndPlugin<void> = {
623 id: '@jupyter-notebook/notebook-extension:edit-notebook-metadata',
624 description:
625 'Add a command to open right sidebar for Editing Notebook Metadata when clicking on "Edit Notebook Metadata" under Edit menu',
626 autoStart: true,
627 optional: [ICommandPalette, ITranslator, INotebookTools],
628 activate: (
629 app: JupyterFrontEnd,
630 palette: ICommandPalette | null,
631 translator: ITranslator | null,
632 notebookTools: INotebookTools | null
633 ) => {
634 const { commands, shell } = app;
635 translator = translator ?? nullTranslator;
636 const trans = translator.load('notebook');
637
638 commands.addCommand(CommandIDs.openEditNotebookMetadata, {
639 label: trans.__('Edit Notebook Metadata'),
640 execute: async () => {
641 const command = 'application:toggle-panel';
642 const args = {
643 side: 'right',
644 title: 'Show Notebook Tools',
645 id: 'notebook-tools',
646 };
647
648 // Check if Show Notebook Tools (Right Sidebar) is open (expanded)
649 if (!commands.isToggled(command, args)) {
650 await commands.execute(command, args).then((_) => {
651 // For expanding the 'Advanced Tools' section (default: collapsed)
652 if (notebookTools) {
653 const tools = (notebookTools?.layout as any).widgets;
654 tools.forEach((tool: any) => {
655 if (
656 tool.widget.title.label === trans.__('Advanced Tools') &&
657 tool.collapsed
658 ) {
659 tool.toggle();
660 }
661 });
662 }
663 });
664 }
665 },
666 isVisible: () =>
667 shell.currentWidget !== null &&
668 shell.currentWidget instanceof NotebookPanel,
669 });
670
671 if (palette) {
672 palette.addItem({
673 command: CommandIDs.openEditNotebookMetadata,
674 category: 'Notebook Operations',
675 });
676 }
677 },
678 };
679
680 /**
681 * Export the plugins as default.
682 */
683 const plugins: JupyterFrontEndPlugin<any>[] = [
684 checkpoints,
685 closeTab,
686 openTreeTab,
687 editNotebookMetadata,
688 fullWidthNotebook,
689 kernelLogo,
690 kernelStatus,
691 notebookToolsWidget,
692 scrollOutput,
693 tabIcon,
694 trusted,
695 ];
696
697 export default plugins;