forked from jupyterlab/jupyterlab
/
index.ts
763 lines (656 loc) · 21 KB
/
index.ts
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
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
/*-----------------------------------------------------------------------------
| Copyright (c) Jupyter Development Team.
| Distributed under the terms of the Modified BSD License.
|----------------------------------------------------------------------------*/
import {
ILayoutRestorer,
IRouter,
JupyterFrontEnd,
JupyterFrontEndPlugin
} from '@jupyterlab/application';
import {
Dialog,
ICommandPalette,
ISplashScreen,
IThemeManager,
IWindowResolver,
ThemeManager,
WindowResolver,
Printing
} from '@jupyterlab/apputils';
import {
ISettingRegistry,
IStateDB,
SettingRegistry,
StateDB,
URLExt
} from '@jupyterlab/coreutils';
import { IMainMenu } from '@jupyterlab/mainmenu';
import { CommandRegistry } from '@phosphor/commands';
import { PromiseDelegate } from '@phosphor/coreutils';
import { DisposableDelegate, IDisposable } from '@phosphor/disposable';
import { Menu } from '@phosphor/widgets';
import { Palette } from './palette';
import '../style/index.css';
/**
* The interval in milliseconds that calls to save a workspace are debounced
* to allow for multiple quickly executed state changes to result in a single
* workspace save operation.
*/
const WORKSPACE_SAVE_DEBOUNCE_INTERVAL = 750;
/**
* The interval in milliseconds before recover options appear during splash.
*/
const SPLASH_RECOVER_TIMEOUT = 12000;
/**
* The command IDs used by the apputils plugin.
*/
namespace CommandIDs {
export const changeTheme = 'apputils:change-theme';
export const loadState = 'apputils:load-statedb';
export const recoverState = 'apputils:recover-statedb';
export const reset = 'apputils:reset';
export const resetOnLoad = 'apputils:reset-on-load';
export const saveState = 'apputils:save-statedb';
export const print = 'apputils:print';
}
/**
* The default command palette extension.
*/
const palette: JupyterFrontEndPlugin<ICommandPalette> = {
activate: Palette.activate,
id: '@jupyterlab/apputils-extension:palette',
provides: ICommandPalette,
autoStart: true
};
/**
* The default command palette's restoration extension.
*
* #### Notes
* The command palette's restoration logic is handled separately from the
* command palette provider extension because the layout restorer dependency
* causes the command palette to be unavailable to other extensions earlier
* in the application load cycle.
*/
const paletteRestorer: JupyterFrontEndPlugin<void> = {
activate: Palette.restore,
id: '@jupyterlab/apputils-extension:palette-restorer',
requires: [ILayoutRestorer],
autoStart: true
};
/**
* The default setting registry provider.
*/
const settings: JupyterFrontEndPlugin<ISettingRegistry> = {
id: '@jupyterlab/apputils-extension:settings',
activate: async (app: JupyterFrontEnd): Promise<ISettingRegistry> => {
const connector = app.serviceManager.settings;
const plugins = (await connector.list()).values;
return new SettingRegistry({ connector, plugins });
},
autoStart: true,
provides: ISettingRegistry
};
/**
* The default theme manager provider.
*/
const themes: JupyterFrontEndPlugin<IThemeManager> = {
id: '@jupyterlab/apputils-extension:themes',
requires: [ISettingRegistry, JupyterFrontEnd.IPaths],
optional: [ISplashScreen],
activate: (
app: JupyterFrontEnd,
settings: ISettingRegistry,
paths: JupyterFrontEnd.IPaths,
splash: ISplashScreen | null
): IThemeManager => {
const host = app.shell;
const commands = app.commands;
const url = URLExt.join(paths.urls.base, paths.urls.themes);
const key = themes.id;
const manager = new ThemeManager({ key, host, settings, splash, url });
// Keep a synchronously set reference to the current theme,
// since the asynchronous setting of the theme in `changeTheme`
// can lead to an incorrect toggle on the currently used theme.
let currentTheme: string;
// Set data attributes on the application shell for the current theme.
manager.themeChanged.connect((sender, args) => {
currentTheme = args.newValue;
app.shell.dataset.themeLight = String(manager.isLight(currentTheme));
app.shell.dataset.themeName = currentTheme;
if (
app.shell.dataset.themeScrollbars !==
String(manager.themeScrollbars(currentTheme))
) {
app.shell.dataset.themeScrollbars = String(
manager.themeScrollbars(currentTheme)
);
}
commands.notifyCommandChanged(CommandIDs.changeTheme);
});
commands.addCommand(CommandIDs.changeTheme, {
label: args => {
const theme = args['theme'] as string;
return args['isPalette'] ? `Use ${theme} Theme` : theme;
},
isToggled: args => args['theme'] === currentTheme,
execute: args => {
const theme = args['theme'] as string;
if (theme === manager.theme) {
return;
}
return manager.setTheme(theme);
}
});
return manager;
},
autoStart: true,
provides: IThemeManager
};
/**
* The default theme manager's UI command palette and main menu functionality.
*
* #### Notes
* This plugin loads separately from the theme manager plugin in order to
* prevent blocking of the theme manager while it waits for the command palette
* and main menu to become available.
*/
const themesPaletteMenu: JupyterFrontEndPlugin<void> = {
id: '@jupyterlab/apputils-extension:themes-palette-menu',
requires: [IThemeManager],
optional: [ICommandPalette, IMainMenu],
activate: (
app: JupyterFrontEnd,
manager: IThemeManager,
palette: ICommandPalette | null,
mainMenu: IMainMenu | null
): void => {
const commands = app.commands;
// If we have a main menu, add the theme manager to the settings menu.
if (mainMenu) {
const themeMenu = new Menu({ commands });
themeMenu.title.label = 'JupyterLab Theme';
void app.restored.then(() => {
const command = CommandIDs.changeTheme;
const isPalette = false;
manager.themes.forEach(theme => {
themeMenu.addItem({ command, args: { isPalette, theme } });
});
});
mainMenu.settingsMenu.addGroup(
[
{
type: 'submenu' as Menu.ItemType,
submenu: themeMenu
}
],
0
);
}
// If we have a command palette, add theme switching options to it.
if (palette) {
void app.restored.then(() => {
const category = 'Settings';
const command = CommandIDs.changeTheme;
const isPalette = true;
manager.themes.forEach(theme => {
palette.addItem({ command, args: { isPalette, theme }, category });
});
});
}
},
autoStart: true
};
/**
* The default window name resolver provider.
*/
const resolver: JupyterFrontEndPlugin<IWindowResolver> = {
id: '@jupyterlab/apputils-extension:resolver',
autoStart: true,
provides: IWindowResolver,
requires: [JupyterFrontEnd.IPaths, IRouter],
activate: async (
_: JupyterFrontEnd,
paths: JupyterFrontEnd.IPaths,
router: IRouter
) => {
const { hash, path, search } = router.current;
const query = URLExt.queryStringToObject(search || '');
const solver = new WindowResolver();
const match = path.match(new RegExp(`^${paths.urls.workspaces}([^?\/]+)`));
const workspace = (match && decodeURIComponent(match[1])) || '';
const candidate = Private.candidate(paths, workspace);
const rest = workspace
? path.replace(new RegExp(`^${paths.urls.workspaces}${workspace}`), '')
: path.replace(new RegExp(`^${paths.urls.page}`), '');
try {
await solver.resolve(candidate);
return solver;
} catch (error) {
// Window resolution has failed so the URL must change. Return a promise
// that never resolves to prevent the application from loading plugins
// that rely on `IWindowResolver`.
return new Promise<IWindowResolver>(() => {
const { base, workspaces } = paths.urls;
const pool =
'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
const random = pool[Math.floor(Math.random() * pool.length)];
const path = URLExt.join(base, workspaces, `auto-${random}`) + rest;
// Clone the originally requested workspace after redirecting.
query['clone'] = workspace;
// Change the URL and trigger a hard reload to re-route.
const url = path + URLExt.objectToQueryString(query) + (hash || '');
router.navigate(url, { hard: true, silent: true });
});
}
}
};
/**
* The default splash screen provider.
*/
const splash: JupyterFrontEndPlugin<ISplashScreen> = {
id: '@jupyterlab/apputils-extension:splash',
autoStart: true,
provides: ISplashScreen,
activate: app => {
return {
show: (light = true) => {
const { commands, restored } = app;
return Private.showSplash(restored, commands, CommandIDs.reset, light);
}
};
}
};
const print: JupyterFrontEndPlugin<void> = {
id: '@jupyterlab/apputils-extension:print',
autoStart: true,
activate: (app: JupyterFrontEnd) => {
app.commands.addCommand(CommandIDs.print, {
label: 'Print...',
isEnabled: () => {
const widget = app.shell.currentWidget;
return Printing.getPrintFunction(widget) !== null;
},
execute: async () => {
const widget = app.shell.currentWidget;
const printFunction = Printing.getPrintFunction(widget);
if (printFunction) {
await printFunction();
}
}
});
}
};
/**
* The default state database for storing application state.
*/
const state: JupyterFrontEndPlugin<IStateDB> = {
id: '@jupyterlab/apputils-extension:state',
autoStart: true,
provides: IStateDB,
requires: [JupyterFrontEnd.IPaths, IRouter, IWindowResolver],
optional: [ISplashScreen],
activate: (
app: JupyterFrontEnd,
paths: JupyterFrontEnd.IPaths,
router: IRouter,
resolver: IWindowResolver,
splash: ISplashScreen | null
) => {
let debouncer: number;
let resolved = false;
const { commands, serviceManager } = app;
const { workspaces } = serviceManager;
const workspace = resolver.name;
const transform = new PromiseDelegate<StateDB.DataTransform>();
const db = new StateDB({
namespace: app.namespace,
transform: transform.promise,
windowName: workspace
});
commands.addCommand(CommandIDs.recoverState, {
execute: async ({ global }) => {
const immediate = true;
const silent = true;
// Clear the state silently so that the state changed signal listener
// will not be triggered as it causes a save state.
await db.clear(silent);
// If the user explictly chooses to recover state, all of local storage
// should be cleared.
if (global) {
try {
window.localStorage.clear();
console.log('Cleared local storage');
} catch (error) {
console.warn('Clearing local storage failed.', error);
// To give the user time to see the console warning before redirect,
// do not set the `immediate` flag.
return commands.execute(CommandIDs.saveState);
}
}
return commands.execute(CommandIDs.saveState, { immediate });
}
});
// Conflate all outstanding requests to the save state command that happen
// within the `WORKSPACE_SAVE_DEBOUNCE_INTERVAL` into a single promise.
let conflated: PromiseDelegate<void> | null = null;
commands.addCommand(CommandIDs.saveState, {
label: () => `Save Workspace (${workspace})`,
execute: ({ immediate }) => {
const timeout = immediate ? 0 : WORKSPACE_SAVE_DEBOUNCE_INTERVAL;
const id = workspace;
const metadata = { id };
// Only instantiate a new conflated promise if one is not outstanding.
if (!conflated) {
conflated = new PromiseDelegate<void>();
}
if (debouncer) {
window.clearTimeout(debouncer);
}
debouncer = window.setTimeout(async () => {
const data = await db.toJSON();
try {
await workspaces.save(id, { data, metadata });
if (conflated) {
conflated.resolve(undefined);
}
} catch (error) {
if (conflated) {
conflated.reject(error);
}
}
conflated = null;
}, timeout);
return conflated.promise;
}
});
const listener = (sender: any, change: StateDB.Change) => {
return commands.execute(CommandIDs.saveState);
};
commands.addCommand(CommandIDs.loadState, {
execute: async (args: IRouter.ILocation) => {
// Since the command can be executed an arbitrary number of times, make
// sure it is safe to call multiple times.
if (resolved) {
return;
}
const { hash, path, search } = args;
const { urls } = paths;
const query = URLExt.queryStringToObject(search || '');
const clone =
typeof query['clone'] === 'string'
? query['clone'] === ''
? urls.defaultWorkspace
: URLExt.join(urls.base, urls.workspaces, query['clone'])
: null;
const source = clone || workspace;
try {
const saved = await workspaces.fetch(source);
// If this command is called after a reset, the state database
// will already be resolved.
if (!resolved) {
resolved = true;
transform.resolve({ type: 'overwrite', contents: saved.data });
}
} catch (error) {
console.warn(`Fetching workspace (${workspace}) failed:`, error);
// If the workspace does not exist, cancel the data transformation
// and save a workspace with the current user state data.
if (!resolved) {
resolved = true;
transform.resolve({ type: 'cancel', contents: null });
}
}
// Any time the local state database changes, save the workspace.
db.changed.connect(listener, db);
const immediate = true;
if (source === clone) {
// Maintain the query string parameters but remove `clone`.
delete query['clone'];
const url = path + URLExt.objectToQueryString(query) + hash;
const cloned = commands
.execute(CommandIDs.saveState, { immediate })
.then(() => router.stop);
// After the state has been cloned, navigate to the URL.
void cloned.then(() => {
router.navigate(url, { silent: true });
});
return cloned;
}
// After the state database has finished loading, save it.
return commands.execute(CommandIDs.saveState, { immediate });
}
});
commands.addCommand(CommandIDs.reset, {
label: 'Reset Application State',
execute: async () => {
const global = true;
try {
await commands.execute(CommandIDs.recoverState, { global });
} catch (error) {
/* Ignore failures and redirect. */
}
router.reload();
}
});
commands.addCommand(CommandIDs.resetOnLoad, {
execute: (args: IRouter.ILocation) => {
const { hash, path, search } = args;
const query = URLExt.queryStringToObject(search || '');
const reset = 'reset' in query;
const clone = 'clone' in query;
if (!reset) {
return;
}
// If a splash provider exists, launch the splash screen.
const loading = splash
? splash.show()
: new DisposableDelegate(() => undefined);
// If the state database has already been resolved, resetting is
// impossible without reloading.
if (resolved) {
return router.reload();
}
// Empty the state database.
resolved = true;
transform.resolve({ type: 'clear', contents: null });
// Maintain the query string parameters but remove `reset`.
delete query['reset'];
const silent = true;
const hard = true;
const url = path + URLExt.objectToQueryString(query) + hash;
const cleared = commands
.execute(CommandIDs.recoverState)
.then(() => router.stop); // Stop routing before new route navigation.
// After the state has been reset, navigate to the URL.
if (clone) {
void cleared.then(() => {
router.navigate(url, { silent, hard });
});
} else {
void cleared.then(() => {
router.navigate(url, { silent });
loading.dispose();
});
}
return cleared;
}
});
router.register({
command: CommandIDs.loadState,
pattern: /.?/,
rank: 30 // High priority: 30:100.
});
router.register({
command: CommandIDs.resetOnLoad,
pattern: /(\?reset|\&reset)($|&)/,
rank: 20 // High priority: 20:100.
});
// Clean up state database when the window unloads.
window.addEventListener('beforeunload', () => {
const silent = true;
db.clear(silent).catch(() => {
/* no-op */
});
});
return db;
}
};
/**
* Export the plugins as default.
*/
const plugins: JupyterFrontEndPlugin<any>[] = [
palette,
paletteRestorer,
resolver,
settings,
state,
splash,
themes,
themesPaletteMenu,
print
];
export default plugins;
/**
* The namespace for module private data.
*/
namespace Private {
/**
* Generate a workspace name candidate.
*
* @param workspace - A potential workspace name parsed from the URL.
*
* @returns A workspace name candidate.
*/
export function candidate(
paths: JupyterFrontEnd.IPaths,
workspace = ''
): string {
return workspace
? URLExt.join(paths.urls.base, paths.urls.workspaces, workspace)
: paths.urls.defaultWorkspace;
}
/**
* Create a splash element.
*/
function createSplash(): HTMLElement {
const splash = document.createElement('div');
const galaxy = document.createElement('div');
const logo = document.createElement('div');
splash.id = 'jupyterlab-splash';
galaxy.id = 'galaxy';
logo.id = 'main-logo';
galaxy.appendChild(logo);
['1', '2', '3'].forEach(id => {
const moon = document.createElement('div');
const planet = document.createElement('div');
moon.id = `moon${id}`;
moon.className = 'moon orbit';
planet.id = `planet${id}`;
planet.className = 'planet';
moon.appendChild(planet);
galaxy.appendChild(moon);
});
splash.appendChild(galaxy);
return splash;
}
/**
* A debouncer for recovery attempts.
*/
let debouncer = 0;
/**
* The recovery dialog.
*/
let dialog: Dialog<any>;
/**
* Allows the user to clear state if splash screen takes too long.
*/
function recover(fn: () => void): void {
if (dialog) {
return;
}
dialog = new Dialog({
title: 'Loading...',
body: `The loading screen is taking a long time.
Would you like to clear the workspace or keep waiting?`,
buttons: [
Dialog.cancelButton({ label: 'Keep Waiting' }),
Dialog.warnButton({ label: 'Clear Workspace' })
]
});
dialog
.launch()
.then(result => {
if (result.button.accept) {
return fn();
}
dialog.dispose();
dialog = null;
debouncer = window.setTimeout(() => {
recover(fn);
}, SPLASH_RECOVER_TIMEOUT);
})
.catch(() => {
/* no-op */
});
}
/**
* The splash element.
*/
const splash = createSplash();
/**
* The splash screen counter.
*/
let splashCount = 0;
/**
* Show the splash element.
*
* @param ready - A promise that must be resolved before splash disappears.
*
* @param commands - The application's command registry.
*
* @param recovery - A command that recovers from a hanging splash.
*
* @param light - A flag indicating whether the theme is light or dark.
*/
export function showSplash(
ready: Promise<any>,
commands: CommandRegistry,
recovery: string,
light: boolean
): IDisposable {
splash.classList.remove('splash-fade');
splash.classList.toggle('light', light);
splash.classList.toggle('dark', !light);
splashCount++;
if (debouncer) {
window.clearTimeout(debouncer);
}
debouncer = window.setTimeout(() => {
if (commands.hasCommand(recovery)) {
recover(() => {
return commands.execute(recovery);
});
}
}, SPLASH_RECOVER_TIMEOUT);
document.body.appendChild(splash);
return new DisposableDelegate(() => {
void ready.then(() => {
if (--splashCount === 0) {
if (debouncer) {
window.clearTimeout(debouncer);
debouncer = 0;
}
if (dialog) {
dialog.dispose();
dialog = null;
}
splash.classList.add('splash-fade');
window.setTimeout(() => {
document.body.removeChild(splash);
}, 500);
}
});
});
}
}