Debian Codegraph @

packages/application-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 ILabStatus,
6 IRouter,
7 ITreePathUpdater,
8 JupyterFrontEnd,
9 JupyterFrontEndPlugin,
10 } from '@jupyterlab/application';
11
12 import {
13 DOMUtils,
14 ICommandPalette,
15 ISanitizer,
16 ISplashScreen,
17 IToolbarWidgetRegistry,
18 } from '@jupyterlab/apputils';
19
20 import { ConsolePanel } from '@jupyterlab/console';
21
22 import { PageConfig, PathExt, URLExt } from '@jupyterlab/coreutils';
23
24 import { IDocumentManager, renameDialog } from '@jupyterlab/docmanager';
25
26 import { DocumentWidget } from '@jupyterlab/docregistry';
27
28 import { IMainMenu } from '@jupyterlab/mainmenu';
29
30 import {
31 ILatexTypesetter,
32 IMarkdownParser,
33 IRenderMime,
34 IRenderMimeRegistry,
35 RenderMimeRegistry,
36 standardRendererFactories,
37 } from '@jupyterlab/rendermime';
38
39 import { ISettingRegistry } from '@jupyterlab/settingregistry';
40
41 import { ITranslator, nullTranslator } from '@jupyterlab/translation';
42
43 import {
44 NotebookApp,
45 NotebookShell,
46 INotebookShell,
47 SidePanel,
48 SidePanelHandler,
49 SidePanelPalette,
50 } from '@jupyter-notebook/application';
51
52 import { jupyterIcon } from '@jupyter-notebook/ui-components';
53
54 import { PromiseDelegate } from '@lumino/coreutils';
55
56 import {
57 DisposableDelegate,
58 DisposableSet,
59 IDisposable,
60 } from '@lumino/disposable';
61
62 import { Menu, Widget } from '@lumino/widgets';
63
64 /**
65 * A regular expression to match path to notebooks and documents
66 */
67 const TREE_PATTERN = new RegExp('/(notebooks|edit)/(.*)');
68
69 /**
70 * A regular expression to suppress the file extension from display for .ipynb files.
71 */
72 const STRIP_IPYNB = /\.ipynb$/;
73
74 /**
75 * The JupyterLab document manager plugin id.
76 */
77 const JUPYTERLAB_DOCMANAGER_PLUGIN_ID =
78 '@jupyterlab/docmanager-extension:plugin';
79
80 /**
81 * The command IDs used by the application plugin.
82 */
83 namespace CommandIDs {
84 /**
85 * Handle local links
86 */
87 export const handleLink = 'application:handle-local-link';
88
89 /**
90 * Toggle Top Bar visibility
91 */
92 export const toggleTop = 'application:toggle-top';
93
94 /**
95 * Toggle side panel visibility
96 */
97 export const togglePanel = 'application:toggle-panel';
98
99 /**
100 * Toggle the Zen mode
101 */
102 export const toggleZen = 'application:toggle-zen';
103
104 /**
105 * Open JupyterLab
106 */
107 export const openLab = 'application:open-lab';
108
109 /**
110 * Open the tree page.
111 */
112 export const openTree = 'application:open-tree';
113
114 /**
115 * Rename the current document
116 */
117 export const rename = 'application:rename';
118
119 /**
120 * Resolve tree path
121 */
122 export const resolveTree = 'application:resolve-tree';
123 }
124
125 /**
126 * Check if the application is dirty before closing the browser tab.
127 */
128 const dirty: JupyterFrontEndPlugin<void> = {
129 id: '@jupyter-notebook/application-extension:dirty',
130 autoStart: true,
131 requires: [ILabStatus, ITranslator],
132 activate: (
133 app: JupyterFrontEnd,
134 status: ILabStatus,
135 translator: ITranslator
136 ): void => {
137 if (!(app instanceof NotebookApp)) {
138 throw new Error(`${dirty.id} must be activated in Jupyter Notebook.`);
139 }
140 const trans = translator.load('notebook');
141 const message = trans.__(
142 'Are you sure you want to exit Jupyter Notebook?\n\nAny unsaved changes will be lost.'
143 );
144
145 window.addEventListener('beforeunload', (event) => {
146 if (app.status.isDirty) {
147 return ((event as any).returnValue = message);
148 }
149 });
150 },
151 };
152
153 /**
154 * The logo plugin.
155 */
156 const logo: JupyterFrontEndPlugin<void> = {
157 id: '@jupyter-notebook/application-extension:logo',
158 autoStart: true,
159 activate: (app: JupyterFrontEnd) => {
160 const baseUrl = PageConfig.getBaseUrl();
161 const node = document.createElement('a');
162 node.href = `${baseUrl}tree`;
163 node.target = '_blank';
164 node.rel = 'noopener noreferrer';
165 const logo = new Widget({ node });
166
167 jupyterIcon.element({
168 container: node,
169 elementPosition: 'center',
170 padding: '2px 2px 2px 8px',
171 height: '28px',
172 width: 'auto',
173 cursor: 'pointer',
174 margin: 'auto',
175 });
176 logo.id = 'jp-NotebookLogo';
177 app.shell.add(logo, 'top', { rank: 0 });
178 },
179 };
180
181 /**
182 * A plugin to open documents in the main area.
183 */
184 const opener: JupyterFrontEndPlugin<void> = {
185 id: '@jupyter-notebook/application-extension:opener',
186 autoStart: true,
187 requires: [IRouter, IDocumentManager],
188 optional: [ISettingRegistry],
189 activate: (
190 app: JupyterFrontEnd,
191 router: IRouter,
192 docManager: IDocumentManager,
193 settingRegistry: ISettingRegistry | null
194 ): void => {
195 const { commands, docRegistry } = app;
196
197 const command = 'router:tree';
198 commands.addCommand(command, {
199 execute: (args: any) => {
200 const parsed = args as IRouter.ILocation;
201 const matches = parsed.path.match(TREE_PATTERN) ?? [];
202 const [, , path] = matches;
203 if (!path) {
204 return;
205 }
206
207 app.started.then(async () => {
208 const file = decodeURIComponent(path);
209 const urlParams = new URLSearchParams(parsed.search);
210 let defaultFactory = docRegistry.defaultWidgetFactory(path).name;
211
212 // Explicitely get the default viewers from the settings because
213 // JupyterLab might not have had the time to load the settings yet (race condition)
214 // Relevant code: https://github.com/jupyterlab/jupyterlab/blob/d56ff811f39b3c10c6d8b6eb27a94624b753eb53/packages/docmanager-extension/src/index.tsx#L265-L293
215 if (settingRegistry) {
216 const settings = await settingRegistry.load(
217 JUPYTERLAB_DOCMANAGER_PLUGIN_ID
218 );
219 const defaultViewers = settings.get('defaultViewers').composite as {
220 [ft: string]: string;
221 };
222 // get the file types for the path
223 const types = docRegistry.getFileTypesForPath(path);
224 // for each file type, check if there is a default viewer and if it
225 // is available in the docRegistry. If it is the case, use it as the
226 // default factory
227 types.forEach((ft) => {
228 if (
229 defaultViewers[ft.name] !== undefined &&
230 docRegistry.getWidgetFactory(defaultViewers[ft.name])
231 ) {
232 defaultFactory = defaultViewers[ft.name];
233 }
234 });
235 }
236
237 const factory = urlParams.get('factory') ?? defaultFactory;
238 docManager.open(file, factory, undefined, {
239 ref: '_noref',
240 });
241 });
242 },
243 });
244
245 router.register({ command, pattern: TREE_PATTERN });
246 },
247 };
248
249 /**
250 * A plugin to customize menus
251 */
252 const menus: JupyterFrontEndPlugin<void> = {
253 id: '@jupyter-notebook/application-extension:menus',
254 requires: [IMainMenu],
255 autoStart: true,
256 activate: (app: JupyterFrontEnd, menu: IMainMenu) => {
257 // always disable the Tabs menu
258 menu.tabsMenu.dispose();
259
260 const page = PageConfig.getOption('notebookPage');
261 switch (page) {
262 case 'consoles':
263 case 'terminals':
264 case 'tree':
265 menu.editMenu.dispose();
266 menu.kernelMenu.dispose();
267 menu.runMenu.dispose();
268 break;
269 case 'edit':
270 menu.kernelMenu.dispose();
271 menu.runMenu.dispose();
272 break;
273 default:
274 break;
275 }
276 },
277 };
278
279 /**
280 * A plugin to provide a spacer at rank 900 in the menu area
281 */
282 const menuSpacer: JupyterFrontEndPlugin<void> = {
283 id: '@jupyter-notebook/application-extension:menu-spacer',
284 autoStart: true,
285 activate: (app: JupyterFrontEnd) => {
286 const menu = new Widget();
287 menu.id = DOMUtils.createDomID();
288 menu.addClass('jp-NotebookSpacer');
289 app.shell.add(menu, 'menu', { rank: 900 });
290 },
291 };
292
293 /**
294 * Add commands to open the tree and running pages.
295 */
296 const pages: JupyterFrontEndPlugin<void> = {
297 id: '@jupyter-notebook/application-extension:pages',
298 autoStart: true,
299 requires: [ITranslator],
300 optional: [ICommandPalette],
301 activate: (
302 app: JupyterFrontEnd,
303 translator: ITranslator,
304 palette: ICommandPalette | null
305 ): void => {
306 const trans = translator.load('notebook');
307 const baseUrl = PageConfig.getBaseUrl();
308
309 app.commands.addCommand(CommandIDs.openLab, {
310 label: trans.__('Open JupyterLab'),
311 execute: () => {
312 window.open(`${baseUrl}lab`);
313 },
314 });
315 const page = PageConfig.getOption('notebookPage');
316
317 app.commands.addCommand(CommandIDs.openTree, {
318 label: trans.__('File Browser'),
319 execute: () => {
320 if (page === 'tree') {
321 app.commands.execute('filebrowser:activate');
322 } else {
323 window.open(`${baseUrl}tree`);
324 }
325 },
326 });
327
328 if (palette) {
329 palette.addItem({ command: CommandIDs.openLab, category: 'View' });
330 palette.addItem({ command: CommandIDs.openTree, category: 'View' });
331 }
332 },
333 };
334
335 /**
336 * The default paths for a Jupyter Notebook app.
337 */
338 const paths: JupyterFrontEndPlugin<JupyterFrontEnd.IPaths> = {
339 id: '@jupyter-notebook/application-extension:paths',
340 autoStart: true,
341 provides: JupyterFrontEnd.IPaths,
342 activate: (app: JupyterFrontEnd): JupyterFrontEnd.IPaths => {
343 if (!(app instanceof NotebookApp)) {
344 throw new Error(`${paths.id} must be activated in Jupyter Notebook.`);
345 }
346 return app.paths;
347 },
348 };
349
350 /**
351 * A plugin providing a rendermime registry.
352 */
353 const rendermime: JupyterFrontEndPlugin<IRenderMimeRegistry> = {
354 id: '@jupyter-notebook/application-extension:rendermime',
355 autoStart: true,
356 provides: IRenderMimeRegistry,
357 description: 'Provides the render mime registry.',
358 optional: [
359 IDocumentManager,
360 ILatexTypesetter,
361 ISanitizer,
362 IMarkdownParser,
363 ITranslator,
364 ],
365 activate: (
366 app: JupyterFrontEnd,
367 docManager: IDocumentManager | null,
368 latexTypesetter: ILatexTypesetter | null,
369 sanitizer: IRenderMime.ISanitizer | null,
370 markdownParser: IMarkdownParser | null,
371 translator: ITranslator | null
372 ) => {
373 const trans = (translator ?? nullTranslator).load('jupyterlab');
374 if (docManager) {
375 app.commands.addCommand(CommandIDs.handleLink, {
376 label: trans.__('Handle Local Link'),
377 execute: (args) => {
378 const path = args['path'] as string | undefined | null;
379 if (path === undefined || path === null) {
380 return;
381 }
382 return docManager.services.contents
383 .get(path, { content: false })
384 .then((model) => {
385 // Open in a new browser tab
386 const url = PageConfig.getBaseUrl();
387 const treeUrl = URLExt.join(url, 'tree', model.path);
388 window.open(treeUrl, '_blank');
389 });
390 },
391 });
392 }
393 return new RenderMimeRegistry({
394 initialFactories: standardRendererFactories,
395 linkHandler: !docManager
396 ? undefined
397 : {
398 handleLink: (node: HTMLElement, path: string, id?: string) => {
399 // If node has the download attribute explicitly set, use the
400 // default browser downloading behavior.
401 if (node.tagName === 'A' && node.hasAttribute('download')) {
402 return;
403 }
404 app.commandLinker.connectNode(node, CommandIDs.handleLink, {
405 path,
406 id,
407 });
408 },
409 },
410 latexTypesetter: latexTypesetter ?? undefined,
411 markdownParser: markdownParser ?? undefined,
412 translator: translator ?? undefined,
413 sanitizer: sanitizer ?? undefined,
414 });
415 },
416 };
417
418 /**
419 * The default Jupyter Notebook application shell.
420 */
421 const shell: JupyterFrontEndPlugin<INotebookShell> = {
422 id: '@jupyter-notebook/application-extension:shell',
423 autoStart: true,
424 provides: INotebookShell,
425 optional: [ISettingRegistry],
426 activate: (
427 app: JupyterFrontEnd,
428 settingRegistry: ISettingRegistry | null
429 ) => {
430 if (!(app.shell instanceof NotebookShell)) {
431 throw new Error(`${shell.id} did not find a NotebookShell instance.`);
432 }
433 const notebookShell = app.shell;
434
435 if (settingRegistry) {
436 settingRegistry
437 .load(shell.id)
438 .then((settings) => {
439 // Add a layer of customization to support app shell mode
440 const customLayout = settings.composite['layout'] as any;
441
442 // Restore the layout.
443 void notebookShell.restoreLayout(customLayout);
444 })
445 .catch((reason) => {
446 console.error('Fail to load settings for the layout restorer.');
447 console.error(reason);
448 });
449 }
450
451 return notebookShell;
452 },
453 };
454
455 /**
456 * The default splash screen provider.
457 */
458 const splash: JupyterFrontEndPlugin<ISplashScreen> = {
459 id: '@jupyter-notebook/application-extension:splash',
460 description: 'Provides an empty splash screen.',
461 autoStart: true,
462 provides: ISplashScreen,
463 activate: (app: JupyterFrontEnd) => {
464 const { restored } = app;
465 const splash = document.createElement('div');
466 splash.style.position = 'absolute';
467 splash.style.width = '100%';
468 splash.style.height = '100%';
469 splash.style.zIndex = '10';
470
471 return {
472 show: (light = true) => {
473 splash.style.backgroundColor = light ? 'white' : '#111111';
474 document.body.appendChild(splash);
475 return new DisposableDelegate(async () => {
476 await restored;
477 document.body.removeChild(splash);
478 });
479 },
480 };
481 },
482 };
483
484 /**
485 * The default JupyterLab application status provider.
486 */
487 const status: JupyterFrontEndPlugin<ILabStatus> = {
488 id: '@jupyter-notebook/application-extension:status',
489 autoStart: true,
490 provides: ILabStatus,
491 activate: (app: JupyterFrontEnd) => {
492 if (!(app instanceof NotebookApp)) {
493 throw new Error(`${status.id} must be activated in Jupyter Notebook.`);
494 }
495 return app.status;
496 },
497 };
498
499 /**
500 * A plugin to display the document title in the browser tab title
501 */
502 const tabTitle: JupyterFrontEndPlugin<void> = {
503 id: '@jupyter-notebook/application-extension:tab-title',
504 autoStart: true,
505 requires: [INotebookShell],
506 activate: (app: JupyterFrontEnd, shell: INotebookShell) => {
507 const setTabTitle = () => {
508 const current = shell.currentWidget;
509 if (current instanceof ConsolePanel) {
510 const update = () => {
511 const title =
512 current.sessionContext.path || current.sessionContext.name;
513 const basename = PathExt.basename(title);
514 // Strip the ".ipynb" suffix from filenames for display in tab titles.
515 document.title = basename.replace(STRIP_IPYNB, '');
516 };
517 current.sessionContext.sessionChanged.connect(update);
518 update();
519 return;
520 } else if (current instanceof DocumentWidget) {
521 const update = () => {
522 const basename = PathExt.basename(current.context.path);
523 document.title = basename.replace(STRIP_IPYNB, '');
524 };
525 current.context.pathChanged.connect(update);
526 update();
527 }
528 };
529
530 shell.currentChanged.connect(setTabTitle);
531 setTabTitle();
532 },
533 };
534
535 /**
536 * A plugin to display and rename the title of a file
537 */
538 const title: JupyterFrontEndPlugin<void> = {
539 id: '@jupyter-notebook/application-extension:title',
540 autoStart: true,
541 requires: [INotebookShell, ITranslator],
542 optional: [IDocumentManager, IRouter, IToolbarWidgetRegistry],
543 activate: (
544 app: JupyterFrontEnd,
545 shell: INotebookShell,
546 translator: ITranslator,
547 docManager: IDocumentManager | null,
548 router: IRouter | null,
549 toolbarRegistry: IToolbarWidgetRegistry | null
550 ) => {
551 const { commands } = app;
552 const trans = translator.load('notebook');
553
554 const node = document.createElement('div');
555 if (toolbarRegistry) {
556 toolbarRegistry.addFactory('TopBar', 'widgetTitle', (toolbar) => {
557 const widget = new Widget({ node });
558 widget.id = 'jp-title';
559 return widget;
560 });
561 }
562
563 const addTitle = async (): Promise<void> => {
564 const current = shell.currentWidget;
565 if (!current || !(current instanceof DocumentWidget)) {
566 return;
567 }
568 if (node.children.length > 0) {
569 return;
570 }
571
572 const h = document.createElement('h1');
573 h.textContent = current.title.label.replace(STRIP_IPYNB, '');
574 node.appendChild(h);
575 node.style.marginLeft = '10px';
576 if (!docManager) {
577 return;
578 }
579
580 const isEnabled = () => {
581 const { currentWidget } = shell;
582 return !!(currentWidget && docManager.contextForWidget(currentWidget));
583 };
584
585 commands.addCommand(CommandIDs.rename, {
586 label: () => trans.__('Rename…'),
587 isEnabled,
588 execute: async () => {
589 if (!isEnabled()) {
590 return;
591 }
592
593 const result = await renameDialog(docManager, current.context);
594
595 // activate the current widget to bring the focus
596 if (current) {
597 current.activate();
598 }
599
600 if (result === null) {
601 return;
602 }
603
604 const newPath = current.context.path;
605 const basename = PathExt.basename(newPath);
606
607 h.textContent = basename.replace(STRIP_IPYNB, '');
608 if (!router) {
609 return;
610 }
611 const matches = router.current.path.match(TREE_PATTERN) ?? [];
612 const [, route, path] = matches;
613 if (!route || !path) {
614 return;
615 }
616 const encoded = encodeURIComponent(newPath);
617 router.navigate(`/${route}/${encoded}`, {
618 skipRouting: true,
619 });
620 },
621 });
622
623 node.onclick = async () => {
624 void commands.execute(CommandIDs.rename);
625 };
626 };
627
628 shell.currentChanged.connect(addTitle);
629 void addTitle();
630 },
631 };
632
633 /**
634 * Plugin to toggle the top header visibility.
635 */
636 const topVisibility: JupyterFrontEndPlugin<void> = {
637 id: '@jupyter-notebook/application-extension:top',
638 requires: [INotebookShell, ITranslator],
639 optional: [ISettingRegistry, ICommandPalette],
640 activate: (
641 app: JupyterFrontEnd<JupyterFrontEnd.IShell>,
642 notebookShell: INotebookShell,
643 translator: ITranslator,
644 settingRegistry: ISettingRegistry | null,
645 palette: ICommandPalette | null
646 ) => {
647 const trans = translator.load('notebook');
648 const top = notebookShell.top;
649 const pluginId = topVisibility.id;
650
651 app.commands.addCommand(CommandIDs.toggleTop, {
652 label: trans.__('Show Header'),
653 execute: () => {
654 top.setHidden(top.isVisible);
655 if (settingRegistry) {
656 void settingRegistry.set(
657 pluginId,
658 'visible',
659 top.isVisible ? 'yes' : 'no'
660 );
661 }
662 },
663 isToggled: () => top.isVisible,
664 });
665
666 let adjustToScreen = false;
667
668 if (settingRegistry) {
669 const loadSettings = settingRegistry.load(pluginId);
670 const updateSettings = (settings: ISettingRegistry.ISettings): void => {
671 // 'visible' property from user preferences or default settings
672 let visible = settings.get('visible').composite;
673 if (settings.user.visible !== undefined) {
674 visible = settings.user.visible;
675 }
676 top.setHidden(visible === 'no');
677 // adjust to screen from user preferences or default settings
678 adjustToScreen = visible === 'automatic';
679 };
680
681 Promise.all([loadSettings, app.restored])
682 .then(([settings]) => {
683 updateSettings(settings);
684 settings.changed.connect((settings) => {
685 updateSettings(settings);
686 });
687 })
688 .catch((reason: Error) => {
689 console.error(reason.message);
690 });
691 }
692
693 if (palette) {
694 palette.addItem({ command: CommandIDs.toggleTop, category: 'View' });
695 }
696
697 const onChanged = (): void => {
698 if (!adjustToScreen) {
699 return;
700 }
701 if (app.format === 'desktop') {
702 notebookShell.expandTop();
703 } else {
704 notebookShell.collapseTop();
705 }
706 };
707
708 // listen on format change (mobile and desktop) to make the view more compact
709 app.formatChanged.connect(onChanged);
710 },
711 autoStart: true,
712 };
713
714 /**
715 * Plugin to toggle the left or right side panel's visibility.
716 */
717 const sidePanelVisibility: JupyterFrontEndPlugin<void> = {
718 id: '@jupyter-notebook/application-extension:sidepanel',
719 requires: [INotebookShell, ITranslator],
720 optional: [IMainMenu, ICommandPalette],
721 autoStart: true,
722 activate: (
723 app: JupyterFrontEnd<JupyterFrontEnd.IShell>,
724 notebookShell: INotebookShell,
725 translator: ITranslator,
726 menu: IMainMenu | null,
727 palette: ICommandPalette | null
728 ) => {
729 const trans = translator.load('notebook');
730
731 /* Arguments for togglePanel command:
732 * side, left or right area
733 * title, widget title to show in the menu
734 * id, widget ID to activate in the side panel
735 */
736 app.commands.addCommand(CommandIDs.togglePanel, {
737 label: (args) => args['title'] as string,
738 caption: (args) => {
739 // We do not substitute the parameter into the string because the parameter is not
740 // localized (e.g., it is always 'left') even though the string is localized.
741 if (args['side'] === 'left') {
742 return trans.__(
743 'Show %1 in the left sidebar',
744 args['title'] as string
745 );
746 } else if (args['side'] === 'right') {
747 return trans.__(
748 'Show %1 in the right sidebar',
749 args['title'] as string
750 );
751 }
752 return trans.__('Show %1 in the sidebar', args['title'] as string);
753 },
754 execute: (args) => {
755 switch (args['side'] as string) {
756 case 'left':
757 if (notebookShell.leftCollapsed) {
758 notebookShell.expandLeft(args.id as string);
759 } else if (
760 notebookShell.leftHandler.currentWidget?.id !== args.id
761 ) {
762 notebookShell.expandLeft(args.id as string);
763 } else {
764 notebookShell.collapseLeft();
765 if (notebookShell.currentWidget) {
766 notebookShell.activateById(notebookShell.currentWidget.id);
767 }
768 }
769 break;
770 case 'right':
771 if (notebookShell.rightCollapsed) {
772 notebookShell.expandRight(args.id as string);
773 } else if (
774 notebookShell.rightHandler.currentWidget?.id !== args.id
775 ) {
776 notebookShell.expandRight(args.id as string);
777 } else {
778 notebookShell.collapseRight();
779 if (notebookShell.currentWidget) {
780 notebookShell.activateById(notebookShell.currentWidget.id);
781 }
782 }
783 break;
784 }
785 },
786 isToggled: (args) => {
787 switch (args['side'] as string) {
788 case 'left': {
789 if (notebookShell.leftCollapsed) {
790 return false;
791 }
792 const currentWidget = notebookShell.leftHandler.currentWidget;
793 if (!currentWidget) {
794 return false;
795 }
796
797 return currentWidget.id === (args['id'] as string);
798 }
799 case 'right': {
800 if (notebookShell.rightCollapsed) {
801 return false;
802 }
803 const currentWidget = notebookShell.rightHandler.currentWidget;
804 if (!currentWidget) {
805 return false;
806 }
807
808 return currentWidget.id === (args['id'] as string);
809 }
810 }
811 return false;
812 },
813 });
814
815 const sidePanelMenu: { [area in SidePanel.Area]: IDisposable | null } = {
816 left: null,
817 right: null,
818 };
819
820 /**
821 * The function which adds entries to the View menu for each widget of a side panel.
822 *
823 * @param area - 'left' or 'right', the area of the side panel.
824 * @param entryLabel - the name of the main entry in the View menu for that side panel.
825 * @returns - The disposable menu added to the View menu or null.
826 */
827 const updateMenu = (area: SidePanel.Area, entryLabel: string) => {
828 if (menu === null) {
829 return null;
830 }
831
832 // Remove the previous menu entry for this side panel.
833 sidePanelMenu[area]?.dispose();
834
835 // Creates a new menu entry and populates it with side panel widgets.
836 const newMenu = new Menu({ commands: app.commands });
837 newMenu.title.label = entryLabel;
838 const widgets = notebookShell.widgets(area);
839 let menuToAdd = false;
840
841 for (const widget of widgets) {
842 newMenu.addItem({
843 command: CommandIDs.togglePanel,
844 args: {
845 side: area,
846 title: `Show ${widget.title.caption}`,
847 id: widget.id,
848 },
849 });
850 menuToAdd = true;
851 }
852
853 // If there are widgets, add the menu to the main menu entry.
854 if (menuToAdd) {
855 sidePanelMenu[area] = menu.viewMenu.addItem({
856 type: 'submenu',
857 submenu: newMenu,
858 });
859 }
860 };
861
862 app.restored.then(() => {
863 // Create menu entries for the left and right panel.
864 if (menu) {
865 const getSidePanelLabel = (area: SidePanel.Area): string => {
866 if (area === 'left') {
867 return trans.__('Left Sidebar');
868 } else {
869 return trans.__('Right Sidebar');
870 }
871 };
872 const leftArea = notebookShell.leftHandler.area;
873 const leftLabel = getSidePanelLabel(leftArea);
874 updateMenu(leftArea, leftLabel);
875
876 const rightArea = notebookShell.rightHandler.area;
877 const rightLabel = getSidePanelLabel(rightArea);
878 updateMenu(rightArea, rightLabel);
879
880 const handleSidePanelChange = (
881 sidePanel: SidePanelHandler,
882 widget: Widget
883 ) => {
884 const label = getSidePanelLabel(sidePanel.area);
885 updateMenu(sidePanel.area, label);
886 };
887
888 notebookShell.leftHandler.widgetAdded.connect(handleSidePanelChange);
889 notebookShell.leftHandler.widgetRemoved.connect(handleSidePanelChange);
890 notebookShell.rightHandler.widgetAdded.connect(handleSidePanelChange);
891 notebookShell.rightHandler.widgetRemoved.connect(handleSidePanelChange);
892 }
893
894 // Add palette entries for side panels.
895 if (palette) {
896 const sidePanelPalette = new SidePanelPalette({
897 commandPalette: palette as ICommandPalette,
898 command: CommandIDs.togglePanel,
899 });
900
901 notebookShell.leftHandler.widgets.forEach((widget) => {
902 sidePanelPalette.addItem(widget, notebookShell.leftHandler.area);
903 });
904
905 notebookShell.rightHandler.widgets.forEach((widget) => {
906 sidePanelPalette.addItem(widget, notebookShell.rightHandler.area);
907 });
908
909 // Update menu and palette when widgets are added or removed from side panels.
910 notebookShell.leftHandler.widgetAdded.connect((sidePanel, widget) => {
911 sidePanelPalette.addItem(widget, sidePanel.area);
912 });
913 notebookShell.leftHandler.widgetRemoved.connect((sidePanel, widget) => {
914 sidePanelPalette.removeItem(widget, sidePanel.area);
915 });
916 notebookShell.rightHandler.widgetAdded.connect((sidePanel, widget) => {
917 sidePanelPalette.addItem(widget, sidePanel.area);
918 });
919 notebookShell.rightHandler.widgetRemoved.connect(
920 (sidePanel, widget) => {
921 sidePanelPalette.removeItem(widget, sidePanel.area);
922 }
923 );
924 }
925 });
926 },
927 };
928
929 /**
930 * The default tree route resolver plugin.
931 */
932 const tree: JupyterFrontEndPlugin<JupyterFrontEnd.ITreeResolver> = {
933 id: '@jupyter-notebook/application-extension:tree-resolver',
934 autoStart: true,
935 requires: [IRouter],
936 provides: JupyterFrontEnd.ITreeResolver,
937 activate: (
938 app: JupyterFrontEnd,
939 router: IRouter
940 ): JupyterFrontEnd.ITreeResolver => {
941 const { commands } = app;
942 const set = new DisposableSet();
943 const delegate = new PromiseDelegate<JupyterFrontEnd.ITreeResolver.Paths>();
944
945 const treePattern = new RegExp('/(/tree/.*)?');
946
947 set.add(
948 commands.addCommand(CommandIDs.resolveTree, {
949 execute: (async (args: IRouter.ILocation) => {
950 if (set.isDisposed) {
951 return;
952 }
953
954 const query = URLExt.queryStringToObject(args.search ?? '');
955 const browser = query['file-browser-path'] || '';
956
957 // Remove the file browser path from the query string.
958 delete query['file-browser-path'];
959
960 // Clean up artifacts immediately upon routing.
961 set.dispose();
962
963 delegate.resolve({ browser, file: PageConfig.getOption('treePath') });
964 }) as (args: any) => Promise<void>,
965 })
966 );
967 set.add(
968 router.register({ command: CommandIDs.resolveTree, pattern: treePattern })
969 );
970
971 // If a route is handled by the router without the tree command being
972 // invoked, resolve to `null` and clean up artifacts.
973 const listener = () => {
974 if (set.isDisposed) {
975 return;
976 }
977 set.dispose();
978 delegate.resolve(null);
979 };
980 router.routed.connect(listener);
981 set.add(
982 new DisposableDelegate(() => {
983 router.routed.disconnect(listener);
984 })
985 );
986
987 return { paths: delegate.promise };
988 },
989 };
990
991 const treePathUpdater: JupyterFrontEndPlugin<ITreePathUpdater> = {
992 id: '@jupyter-notebook/application-extension:tree-updater',
993 requires: [IRouter],
994 provides: ITreePathUpdater,
995 activate: (app: JupyterFrontEnd, router: IRouter) => {
996 function updateTreePath(treePath: string) {
997 if (treePath !== PageConfig.getOption('treePath')) {
998 const path = URLExt.join(
999 PageConfig.getOption('baseUrl') || '/',
1000 'tree',
1001 URLExt.encodeParts(treePath)
1002 );
1003 router.navigate(path, { skipRouting: true });
1004 // Persist the new tree path to PageConfig as it is used elsewhere at runtime.
1005 PageConfig.setOption('treePath', treePath);
1006 }
1007 }
1008 return updateTreePath;
1009 },
1010 autoStart: true,
1011 };
1012
1013 const translator: JupyterFrontEndPlugin<void> = {
1014 id: '@jupyter-notebook/application-extension:translator',
1015 requires: [INotebookShell, ITranslator],
1016 autoStart: true,
1017 activate: (
1018 app: JupyterFrontEnd,
1019 notebookShell: INotebookShell,
1020 translator: ITranslator
1021 ) => {
1022 notebookShell.translator = translator;
1023 },
1024 };
1025
1026 /**
1027 * Zen mode plugin
1028 */
1029 const zen: JupyterFrontEndPlugin<void> = {
1030 id: '@jupyter-notebook/application-extension:zen',
1031 autoStart: true,
1032 requires: [ITranslator],
1033 optional: [ICommandPalette, INotebookShell],
1034 activate: (
1035 app: JupyterFrontEnd,
1036 translator: ITranslator,
1037 palette: ICommandPalette | null,
1038 notebookShell: INotebookShell | null
1039 ): void => {
1040 const { commands } = app;
1041 const elem = document.documentElement;
1042 const trans = translator.load('notebook');
1043
1044 const toggleOn = () => {
1045 notebookShell?.collapseTop();
1046 notebookShell?.menu.setHidden(true);
1047 zenModeEnabled = true;
1048 };
1049
1050 const toggleOff = () => {
1051 notebookShell?.expandTop();
1052 notebookShell?.menu.setHidden(false);
1053 zenModeEnabled = false;
1054 };
1055
1056 let zenModeEnabled = false;
1057 commands.addCommand(CommandIDs.toggleZen, {
1058 label: trans.__('Toggle Zen Mode'),
1059 execute: () => {
1060 if (!zenModeEnabled) {
1061 elem.requestFullscreen();
1062 toggleOn();
1063 } else {
1064 document.exitFullscreen();
1065 toggleOff();
1066 }
1067 },
1068 });
1069
1070 document.addEventListener('fullscreenchange', () => {
1071 if (!document.fullscreenElement) {
1072 toggleOff();
1073 }
1074 });
1075
1076 if (palette) {
1077 palette.addItem({ command: CommandIDs.toggleZen, category: 'Mode' });
1078 }
1079 },
1080 };
1081
1082 /**
1083 * Export the plugins as default.
1084 */
1085 const plugins: JupyterFrontEndPlugin<any>[] = [
1086 dirty,
1087 logo,
1088 menus,
1089 menuSpacer,
1090 opener,
1091 pages,
1092 paths,
1093 rendermime,
1094 shell,
1095 sidePanelVisibility,
1096 splash,
1097 status,
1098 tabTitle,
1099 title,
1100 topVisibility,
1101 tree,
1102 treePathUpdater,
1103 translator,
1104 zen,
1105 ];
1106
1107 export default plugins;