forked from jupyterlab/jupyterlab
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.tsx
444 lines (387 loc) · 12.1 KB
/
index.tsx
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
// Copyright (c) Jupyter Development Team.
// Distributed under the terms of the Modified BSD License.
import {
JupyterLab,
JupyterLabPlugin,
ILayoutRestorer,
IRouter,
LayoutRestorer,
Router
} from '@jupyterlab/application';
import {
Dialog,
ICommandPalette,
IWindowResolver,
showDialog,
showErrorMessage
} from '@jupyterlab/apputils';
import { IStateDB, PageConfig, PathExt, URLExt } from '@jupyterlab/coreutils';
import * as React from 'react';
/**
* The command IDs used by the application plugin.
*/
namespace CommandIDs {
export const activateNextTab: string = 'application:activate-next-tab';
export const activatePreviousTab: string =
'application:activate-previous-tab';
export const closeAll: string = 'application:close-all';
export const setMode: string = 'application:set-mode';
export const toggleMode: string = 'application:toggle-mode';
export const toggleLeftArea: string = 'application:toggle-left-area';
export const toggleRightArea: string = 'application:toggle-right-area';
export const togglePresentationMode: string =
'application:toggle-presentation-mode';
export const tree: string = 'router:tree';
}
/**
* The routing regular expressions used by the application plugin.
*/
namespace Patterns {
export const tree = new RegExp(`^${PageConfig.getOption('treeUrl')}([^?]+)`);
export const workspace = new RegExp(
`^${PageConfig.getOption('workspacesUrl')}[^?\/]+/tree/([^?]+)`
);
}
/**
* The main extension.
*/
const main: JupyterLabPlugin<void> = {
id: '@jupyterlab/application-extension:main',
requires: [ICommandPalette, IRouter, IWindowResolver],
activate: (
app: JupyterLab,
palette: ICommandPalette,
router: IRouter,
resolver: IWindowResolver
) => {
// Requiring the window resolver guarantees that the application extension
// only loads if there is a viable window name. Otherwise, the application
// will short-circuit and ask the user to navigate away.
const workspace = resolver.name;
console.log(`Starting application in workspace: ${workspace}`);
// If there were errors registering plugins, tell the user.
if (app.registerPluginErrors.length !== 0) {
const body = (
<pre>{app.registerPluginErrors.map(e => e.message).join('\n')}</pre>
);
showErrorMessage('Error Registering Plugins', { message: body });
}
addCommands(app, palette);
// If the application shell layout is modified,
// trigger a refresh of the commands.
app.shell.layoutModified.connect(() => {
app.commands.notifyCommandChanged();
});
const builder = app.serviceManager.builder;
const build = () => {
return builder
.build()
.then(() => {
return showDialog({
title: 'Build Complete',
body: 'Build successfully completed, reload page?',
buttons: [
Dialog.cancelButton(),
Dialog.warnButton({ label: 'RELOAD' })
]
});
})
.then(result => {
if (result.button.accept) {
router.reload();
}
})
.catch(err => {
showErrorMessage('Build Failed', {
message: <pre>{err.message}</pre>
});
});
};
if (builder.isAvailable && builder.shouldCheck) {
builder.getStatus().then(response => {
if (response.status === 'building') {
return build();
}
if (response.status !== 'needed') {
return;
}
const body = (
<div>
<p>
JupyterLab build is suggested:
<br />
<pre>{response.message}</pre>
</p>
</div>
);
showDialog({
title: 'Build Recommended',
body,
buttons: [Dialog.cancelButton(), Dialog.okButton({ label: 'BUILD' })]
}).then(result => (result.button.accept ? build() : undefined));
});
}
const message =
'Are you sure you want to exit JupyterLab?\n' +
'Any unsaved changes will be lost.';
// The spec for the `beforeunload` event is implemented differently by
// the different browser vendors. Consequently, the `event.returnValue`
// attribute needs to set in addition to a return value being returned.
// For more information, see:
// https://developer.mozilla.org/en/docs/Web/Events/beforeunload
window.addEventListener('beforeunload', event => {
if (app.isDirty) {
return ((event as any).returnValue = message);
}
});
},
autoStart: true
};
/**
* The default layout restorer provider.
*/
const layout: JupyterLabPlugin<ILayoutRestorer> = {
id: '@jupyterlab/application-extension:layout',
requires: [IStateDB],
activate: (app: JupyterLab, state: IStateDB) => {
const first = app.started;
const registry = app.commands;
const restorer = new LayoutRestorer({ first, registry, state });
restorer.fetch().then(saved => {
app.shell.restoreLayout(saved);
app.shell.layoutModified.connect(() => {
restorer.save(app.shell.saveLayout());
});
});
return restorer;
},
autoStart: true,
provides: ILayoutRestorer
};
/**
* The default URL router provider.
*/
const router: JupyterLabPlugin<IRouter> = {
id: '@jupyterlab/application-extension:router',
activate: (app: JupyterLab) => {
const { commands } = app;
const base = PageConfig.getOption('baseUrl');
const router = new Router({ base, commands });
app.started.then(() => {
// Route the very first request on load.
router.route();
// Route all pop state events.
window.addEventListener('popstate', () => {
router.route();
});
});
return router;
},
autoStart: true,
provides: IRouter
};
/**
* The tree route handler provider.
*/
const tree: JupyterLabPlugin<void> = {
id: '@jupyterlab/application-extension:tree',
autoStart: true,
requires: [IRouter],
activate: (app: JupyterLab, router: IRouter) => {
const { commands } = app;
commands.addCommand(CommandIDs.tree, {
execute: async (args: IRouter.ILocation) => {
const treeMatch = args.path.match(Patterns.tree);
const workspaceMatch = args.path.match(Patterns.workspace);
const match = treeMatch || workspaceMatch;
const path = decodeURIComponent(match[1]);
const { page, workspaces } = app.info.urls;
const workspace = PathExt.basename(app.info.workspace);
const url =
(workspaceMatch ? URLExt.join(workspaces, workspace) : page) +
args.search +
args.hash;
const immediate = true;
const silent = true;
// Silently remove the tree portion of the URL leaving the rest intact.
router.navigate(url, { silent });
try {
await commands.execute('filebrowser:navigate', { path });
await commands.execute('apputils:save-statedb', { immediate });
} catch (error) {
console.warn('Tree routing failed.', error);
}
}
});
router.register({ command: CommandIDs.tree, pattern: Patterns.tree });
router.register({ command: CommandIDs.tree, pattern: Patterns.workspace });
}
};
/**
* The default URL not found extension.
*/
const notfound: JupyterLabPlugin<void> = {
id: '@jupyterlab/application-extension:notfound',
activate: (app: JupyterLab, router: IRouter) => {
const bad = PageConfig.getOption('notFoundUrl');
const base = router.base;
const message = `
The path: ${bad} was not found. JupyterLab redirected to: ${base}
`;
if (!bad) {
return;
}
// Change the URL back to the base application URL without adding the
// URL change to the browser history.
router.navigate('', { silent: true });
showErrorMessage('Path Not Found', { message });
},
requires: [IRouter],
autoStart: true
};
/**
* Change the favicon changing based on the busy status;
*/
const busy: JupyterLabPlugin<void> = {
id: '@jupyterlab/application-extension:faviconbusy',
activate: async (app: JupyterLab) => {
app.busySignal.connect((_, isBusy) => {
const favicon = document.querySelector(
`link[rel="icon"]${isBusy ? '.idle.favicon' : '.busy.favicon'}`
) as HTMLLinkElement;
if (!favicon) {
return;
}
const newFavicon = document.querySelector(
`link${isBusy ? '.busy.favicon' : '.idle.favicon'}`
) as HTMLLinkElement;
if (!newFavicon) {
return;
}
// If we have the two icons with the special classes, then toggle them.
if (favicon !== newFavicon) {
favicon.rel = '';
newFavicon.rel = 'icon';
// Firefox doesn't seem to recognize just changing rel, so we also
// reinsert the link into the DOM.
newFavicon.parentNode.replaceChild(newFavicon, newFavicon);
}
});
},
requires: [],
autoStart: true
};
/**
* Add the main application commands.
*/
function addCommands(app: JupyterLab, palette: ICommandPalette): void {
const category = 'Main Area';
let command = CommandIDs.activateNextTab;
app.commands.addCommand(command, {
label: 'Activate Next Tab',
execute: () => {
app.shell.activateNextTab();
}
});
palette.addItem({ command, category });
command = CommandIDs.activatePreviousTab;
app.commands.addCommand(command, {
label: 'Activate Previous Tab',
execute: () => {
app.shell.activatePreviousTab();
}
});
palette.addItem({ command, category });
command = CommandIDs.closeAll;
app.commands.addCommand(command, {
label: 'Close All Widgets',
execute: () => {
app.shell.closeAll();
}
});
palette.addItem({ command, category });
command = CommandIDs.toggleLeftArea;
app.commands.addCommand(command, {
label: args => 'Show Left Sidebar',
execute: () => {
if (app.shell.leftCollapsed) {
app.shell.expandLeft();
} else {
app.shell.collapseLeft();
if (app.shell.currentWidget) {
app.shell.activateById(app.shell.currentWidget.id);
}
}
},
isToggled: () => !app.shell.leftCollapsed,
isVisible: () => !app.shell.isEmpty('left')
});
palette.addItem({ command, category });
command = CommandIDs.toggleRightArea;
app.commands.addCommand(command, {
label: args => 'Show Right Sidebar',
execute: () => {
if (app.shell.rightCollapsed) {
app.shell.expandRight();
} else {
app.shell.collapseRight();
if (app.shell.currentWidget) {
app.shell.activateById(app.shell.currentWidget.id);
}
}
},
isToggled: () => !app.shell.rightCollapsed,
isVisible: () => !app.shell.isEmpty('right')
});
palette.addItem({ command, category });
command = CommandIDs.togglePresentationMode;
app.commands.addCommand(command, {
label: args => 'Presentation Mode',
execute: () => {
app.shell.presentationMode = !app.shell.presentationMode;
},
isToggled: () => app.shell.presentationMode,
isVisible: () => true
});
palette.addItem({ command, category });
command = CommandIDs.setMode;
app.commands.addCommand(command, {
isVisible: args => {
const mode = args['mode'] as string;
return mode === 'single-document' || mode === 'multiple-document';
},
execute: args => {
const mode = args['mode'] as string;
if (mode === 'single-document' || mode === 'multiple-document') {
app.shell.mode = mode;
return;
}
throw new Error(`Unsupported application shell mode: ${mode}`);
}
});
command = CommandIDs.toggleMode;
app.commands.addCommand(command, {
label: 'Single-Document Mode',
isToggled: () => app.shell.mode === 'single-document',
execute: () => {
const args =
app.shell.mode === 'multiple-document'
? { mode: 'single-document' }
: { mode: 'multiple-document' };
return app.commands.execute(CommandIDs.setMode, args);
}
});
palette.addItem({ command, category });
}
/**
* Export the plugins as default.
*/
const plugins: JupyterLabPlugin<any>[] = [
main,
layout,
router,
tree,
notfound,
busy
];
export default plugins;