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