Debian Codegraph @

packages/console-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 IRouter,
6 JupyterFrontEnd,
7 JupyterFrontEndPlugin,
8 } from '@jupyterlab/application';
9
10 import { IConsoleTracker } from '@jupyterlab/console';
11
12 import { PageConfig, URLExt } from '@jupyterlab/coreutils';
13
14 import {
15 INotebookPathOpener,
16 defaultNotebookPathOpener,
17 } from '@jupyter-notebook/application';
18
19 import { find } from '@lumino/algorithm';
20
21 /**
22 * A plugin to open consoles in a new tab
23 */
24 const opener: JupyterFrontEndPlugin<void> = {
25 id: '@jupyter-notebook/console-extension:opener',
26 requires: [IRouter],
27 autoStart: true,
28 description: 'A plugin to open consoles in a new tab',
29 activate: (app: JupyterFrontEnd, router: IRouter) => {
30 const { commands } = app;
31 const consolePattern = new RegExp('/consoles/(.*)');
32
33 const command = 'router:console';
34 commands.addCommand(command, {
35 execute: (args: any) => {
36 const parsed = args as IRouter.ILocation;
37 const matches = parsed.path.match(consolePattern);
38 if (!matches) {
39 return;
40 }
41 const [, match] = matches;
42 if (!match) {
43 return;
44 }
45
46 const path = decodeURIComponent(match);
47 commands.execute('console:create', { path });
48 },
49 });
50
51 router.register({ command, pattern: consolePattern });
52 },
53 };
54
55 /**
56 * Open consoles in a new tab.
57 */
58 const redirect: JupyterFrontEndPlugin<void> = {
59 id: '@jupyter-notebook/console-extension:redirect',
60 requires: [IConsoleTracker],
61 optional: [INotebookPathOpener],
62 autoStart: true,
63 description: 'Open consoles in a new tab',
64 activate: (
65 app: JupyterFrontEnd,
66 tracker: IConsoleTracker,
67 notebookPathOpener: INotebookPathOpener | null
68 ) => {
69 const baseUrl = PageConfig.getBaseUrl();
70 const opener = notebookPathOpener ?? defaultNotebookPathOpener;
71
72 tracker.widgetAdded.connect(async (send, console) => {
73 const { sessionContext } = console;
74 await sessionContext.ready;
75 const widget = find(
76 app.shell.widgets('main'),
77 (w) => w.id === console.id
78 );
79 if (widget) {
80 // bail if the console is already added to the main area
81 return;
82 }
83 opener.open({
84 prefix: URLExt.join(baseUrl, 'consoles'),
85 path: sessionContext.path,
86 target: '_blank',
87 });
88
89 // the widget is not needed anymore
90 console.dispose();
91 });
92 },
93 };
94
95 /**
96 * Export the plugins as default.
97 */
98 const plugins: JupyterFrontEndPlugin<any>[] = [opener, redirect];
99
100 export default plugins;