@jupyterlite/application-extension 0.2.2 → 0.3.0-alpha.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (2) hide show
  1. package/package.json +16 -15
  2. package/src/index.tsx +545 -0
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@jupyterlite/application-extension",
3
- "version": "0.2.2",
3
+ "version": "0.3.0-alpha.0",
4
4
  "description": "JupyterLite - Application Extension",
5
5
  "homepage": "https://github.com/jupyterlite/jupyterlite",
6
6
  "bugs": {
@@ -27,7 +27,8 @@
27
27
  "lib/*.js.map",
28
28
  "lib/*.js",
29
29
  "style/*.css",
30
- "style/index.js"
30
+ "style/index.js",
31
+ "src/**/*.{ts,tsx}"
31
32
  ],
32
33
  "scripts": {
33
34
  "build": "tsc -b",
@@ -37,20 +38,20 @@
37
38
  "watch": "tsc -b --watch"
38
39
  },
39
40
  "dependencies": {
40
- "@jupyterlab/application": "~4.0.9",
41
- "@jupyterlab/apputils": "~4.1.9",
42
- "@jupyterlab/docmanager": "~4.0.9",
43
- "@jupyterlab/filebrowser": "~4.0.9",
44
- "@jupyterlab/help-extension": "~4.0.9",
45
- "@jupyterlab/mainmenu": "~4.0.9",
46
- "@jupyterlab/services": "~7.0.9",
47
- "@jupyterlab/settingregistry": "~4.0.9",
48
- "@jupyterlab/translation": "~4.0.9",
49
- "@jupyterlab/ui-components": "~4.0.9",
50
- "@jupyterlite/ui-components": "^0.2.2",
41
+ "@jupyterlab/application": "~4.1.1",
42
+ "@jupyterlab/apputils": "~4.2.1",
43
+ "@jupyterlab/docmanager": "~4.1.1",
44
+ "@jupyterlab/filebrowser": "~4.1.1",
45
+ "@jupyterlab/help-extension": "~4.1.1",
46
+ "@jupyterlab/mainmenu": "~4.1.1",
47
+ "@jupyterlab/services": "~7.1.1",
48
+ "@jupyterlab/settingregistry": "~4.1.1",
49
+ "@jupyterlab/translation": "~4.1.1",
50
+ "@jupyterlab/ui-components": "~4.1.1",
51
+ "@jupyterlite/ui-components": "^0.3.0-alpha.0",
51
52
  "@lumino/algorithm": "^2.0.1",
52
53
  "@lumino/coreutils": "^2.1.2",
53
- "@lumino/widgets": "^2.3.0"
54
+ "@lumino/widgets": "^2.3.1"
54
55
  },
55
56
  "devDependencies": {
56
57
  "@babel/core": "^7.11.6",
@@ -59,7 +60,7 @@
59
60
  "jest": "^29.6.2",
60
61
  "rimraf": "~5.0.1",
61
62
  "ts-jest": "^29.1.1",
62
- "typescript": "~5.0.4"
63
+ "typescript": "~5.1.6"
63
64
  },
64
65
  "publishConfig": {
65
66
  "access": "public"
package/src/index.tsx ADDED
@@ -0,0 +1,545 @@
1
+ // Copyright (c) Jupyter Development Team.
2
+ // Distributed under the terms of the Modified BSD License.
3
+
4
+ import {
5
+ IRouter,
6
+ JupyterFrontEndPlugin,
7
+ JupyterFrontEnd,
8
+ ILabShell,
9
+ } from '@jupyterlab/application';
10
+
11
+ import {
12
+ Clipboard,
13
+ ICommandPalette,
14
+ Dialog,
15
+ showDialog,
16
+ SessionContext,
17
+ } from '@jupyterlab/apputils';
18
+
19
+ import { PageConfig, URLExt } from '@jupyterlab/coreutils';
20
+
21
+ import { IDocumentManager, IDocumentWidgetOpener } from '@jupyterlab/docmanager';
22
+
23
+ import { IFileBrowserFactory } from '@jupyterlab/filebrowser';
24
+
25
+ import { IMainMenu } from '@jupyterlab/mainmenu';
26
+
27
+ import { ISettingRegistry } from '@jupyterlab/settingregistry';
28
+
29
+ import { ITranslator } from '@jupyterlab/translation';
30
+
31
+ import { downloadIcon, linkIcon } from '@jupyterlab/ui-components';
32
+
33
+ import { liteIcon, liteWordmark } from '@jupyterlite/ui-components';
34
+
35
+ import { filter } from '@lumino/algorithm';
36
+
37
+ import { Widget } from '@lumino/widgets';
38
+
39
+ import { getParam } from 'lib0/environment';
40
+
41
+ import React from 'react';
42
+
43
+ /**
44
+ * A regular expression to match path to notebooks, documents and consoles
45
+ */
46
+ const URL_PATTERN = new RegExp('/(lab|tree|notebooks|edit|consoles)\\/?');
47
+
48
+ /**
49
+ * The JupyterLab document manager plugin id.
50
+ */
51
+ const JUPYTERLAB_DOCMANAGER_PLUGIN_ID = '@jupyterlab/docmanager-extension:plugin';
52
+
53
+ /**
54
+ * The command IDs used by the application extension.
55
+ */
56
+ namespace CommandIDs {
57
+ export const about = 'application:about';
58
+
59
+ export const docmanagerDownload = 'docmanager:download';
60
+
61
+ export const filebrowserDownload = 'filebrowser:download';
62
+
63
+ export const copyShareableLink = 'filebrowser:share-main';
64
+ }
65
+
66
+ /**
67
+ * The name of the translation bundle for internationalized strings.
68
+ */
69
+
70
+ const I18N_BUNDLE = 'jupyterlite';
71
+
72
+ /**
73
+ * Add a command to show an About dialog.
74
+ */
75
+ const about: JupyterFrontEndPlugin<void> = {
76
+ id: '@jupyterlite/application-extension:about',
77
+ autoStart: true,
78
+ requires: [ITranslator],
79
+ optional: [ICommandPalette, IMainMenu],
80
+ activate: (
81
+ app: JupyterFrontEnd,
82
+ translator: ITranslator,
83
+ palette: ICommandPalette | null,
84
+ menu: IMainMenu | null,
85
+ ): void => {
86
+ const { commands } = app;
87
+ const trans = translator.load(I18N_BUNDLE);
88
+ const category = trans.__('Help');
89
+
90
+ commands.addCommand(CommandIDs.about, {
91
+ label: trans.__('About %1', app.name),
92
+ execute: () => {
93
+ const versionNumber = trans.__('Version %1', app.version);
94
+ const versionInfo = (
95
+ <span className="jp-About-version-info">
96
+ <span className="jp-About-version">{versionNumber}</span>
97
+ </span>
98
+ );
99
+ const title = (
100
+ <span className="jp-About-header">
101
+ <div className="jp-About-header-info">
102
+ <liteWordmark.react height="auto" width="196px" />
103
+ {versionInfo}
104
+ </div>
105
+ </span>
106
+ );
107
+
108
+ // Create the body of the about dialog
109
+ const jupyterliteURL = 'https://github.com/jupyterlite/jupyterlite';
110
+ const contributorsURL =
111
+ 'https://github.com/jupyterlite/jupyterlite/graphs/contributors';
112
+ const externalLinks = (
113
+ <span className="jp-About-externalLinks">
114
+ <a
115
+ href={contributorsURL}
116
+ target="_blank"
117
+ rel="noopener noreferrer"
118
+ className="jp-Button-flat"
119
+ >
120
+ {trans.__('CONTRIBUTOR LIST')}
121
+ </a>
122
+ <a
123
+ href={jupyterliteURL}
124
+ target="_blank"
125
+ rel="noopener noreferrer"
126
+ className="jp-Button-flat"
127
+ >
128
+ {trans.__('JUPYTERLITE ON GITHUB')}
129
+ </a>
130
+ </span>
131
+ );
132
+ const copyright = (
133
+ <span className="jp-About-copyright">
134
+ {trans.__('© 2021-2022 JupyterLite Contributors')}
135
+ </span>
136
+ );
137
+ const body = (
138
+ <div className="jp-About-body">
139
+ {externalLinks}
140
+ {copyright}
141
+ </div>
142
+ );
143
+
144
+ return showDialog({
145
+ title,
146
+ body,
147
+ buttons: [
148
+ Dialog.createButton({
149
+ label: trans.__('Dismiss'),
150
+ className: 'jp-About-button jp-mod-reject jp-mod-styled',
151
+ }),
152
+ ],
153
+ });
154
+ },
155
+ });
156
+
157
+ if (palette) {
158
+ palette.addItem({ command: CommandIDs.about, category });
159
+ }
160
+
161
+ if (menu) {
162
+ menu.helpMenu.addGroup([{ command: CommandIDs.about }], 0);
163
+ }
164
+ },
165
+ };
166
+
167
+ /**
168
+ * A plugin providing download commands in the file menu and command palette.
169
+ */
170
+ const downloadPlugin: JupyterFrontEndPlugin<void> = {
171
+ id: '@jupyterlite/application-extension:download',
172
+ autoStart: true,
173
+ requires: [ITranslator, IDocumentManager],
174
+ optional: [ICommandPalette, IFileBrowserFactory],
175
+ activate: (
176
+ app: JupyterFrontEnd,
177
+ translator: ITranslator,
178
+ docManager: IDocumentManager,
179
+ palette: ICommandPalette | null,
180
+ factory: IFileBrowserFactory | null,
181
+ ) => {
182
+ const trans = translator.load(I18N_BUNDLE);
183
+ const { commands, serviceManager, shell } = app;
184
+ const { contents } = serviceManager;
185
+
186
+ const isEnabled = () => {
187
+ const { currentWidget } = shell;
188
+ return !!(currentWidget && docManager.contextForWidget(currentWidget));
189
+ };
190
+
191
+ const downloadContent = async (contentPath: string, fileName: string) => {
192
+ const model = await contents.get(contentPath, { content: true });
193
+ const element = document.createElement('a');
194
+ if (model.type === 'notebook' || model.format === 'json') {
195
+ const mime = model.mimetype ?? 'text/json';
196
+ const content = JSON.stringify(model.content, null, 2);
197
+ element.href = `data:${mime};charset=utf-8,${encodeURIComponent(content)}`;
198
+ } else if (model.type === 'file') {
199
+ if (model.format === 'base64') {
200
+ const mime = model.mimetype ?? 'application/octet-stream';
201
+ element.href = `data:${mime};base64,${model.content}`;
202
+ } else {
203
+ const mime = model.mimetype ?? 'text/plain';
204
+ element.href = `data:${mime};charset=utf-8,${encodeURIComponent(
205
+ model.content,
206
+ )}`;
207
+ }
208
+ } else {
209
+ throw new Error(`Content whose type is "${model.type}" cannot be downloaded`);
210
+ }
211
+ element.download = fileName;
212
+ document.body.appendChild(element);
213
+ element.click();
214
+ document.body.removeChild(element);
215
+ };
216
+
217
+ commands.addCommand(CommandIDs.docmanagerDownload, {
218
+ label: trans.__('Download'),
219
+ caption: trans.__('Download the file to your computer'),
220
+ isEnabled,
221
+ execute: async () => {
222
+ // Checks that shell.currentWidget is valid:
223
+ const current = shell.currentWidget;
224
+ if (!isEnabled() || !current) {
225
+ return;
226
+ }
227
+ const context = docManager.contextForWidget(current);
228
+ if (!context) {
229
+ return showDialog({
230
+ title: trans.__('Cannot Download'),
231
+ body: trans.__('No context found for current widget!'),
232
+ buttons: [Dialog.okButton({ label: trans.__('OK') })],
233
+ });
234
+ }
235
+ await context.save();
236
+ await downloadContent(context.path, context.path);
237
+ },
238
+ });
239
+
240
+ const category = trans.__('File Operations');
241
+
242
+ if (palette) {
243
+ palette.addItem({ command: CommandIDs.docmanagerDownload, category });
244
+ }
245
+
246
+ if (factory) {
247
+ const { tracker } = factory;
248
+
249
+ commands.addCommand(CommandIDs.filebrowserDownload, {
250
+ execute: async () => {
251
+ const widget = tracker.currentWidget;
252
+
253
+ if (!widget) {
254
+ return;
255
+ }
256
+ const selected = Array.from(widget.selectedItems());
257
+ selected.forEach(async (item) => {
258
+ if (item.type !== 'directory') {
259
+ await downloadContent(item.path, item.name);
260
+ }
261
+ });
262
+ },
263
+ icon: downloadIcon.bindprops({ stylesheet: 'menuItem' }),
264
+ label: trans.__('Download'),
265
+ });
266
+ }
267
+ },
268
+ };
269
+
270
+ /**
271
+ * The main application icon.
272
+ */
273
+ const liteLogo: JupyterFrontEndPlugin<void> = {
274
+ id: '@jupyterlite/application-extension:logo',
275
+ // marking as optional to not throw errors in Notebook
276
+ optional: [ILabShell],
277
+ autoStart: true,
278
+ activate: (app: JupyterFrontEnd, labShell: ILabShell) => {
279
+ if (!labShell) {
280
+ return;
281
+ }
282
+ const logo = new Widget();
283
+ liteIcon.element({
284
+ container: logo.node,
285
+ elementPosition: 'center',
286
+ margin: '2px 2px 2px 8px',
287
+ height: 'auto',
288
+ width: '16px',
289
+ });
290
+ logo.id = 'jp-MainLogo';
291
+ labShell.add(logo, 'top', { rank: 0 });
292
+ },
293
+ };
294
+
295
+ /**
296
+ * A plugin to trigger a refresh of the commands when the shell layout changes.
297
+ */
298
+ const notifyCommands: JupyterFrontEndPlugin<void> = {
299
+ id: '@jupyterlite/application-extension:notify-commands',
300
+ autoStart: true,
301
+ optional: [ILabShell],
302
+ activate: (app: JupyterFrontEnd, labShell: ILabShell | null) => {
303
+ if (labShell) {
304
+ labShell.layoutModified.connect(() => {
305
+ app.commands.notifyCommandChanged();
306
+ });
307
+ }
308
+ },
309
+ };
310
+
311
+ /**
312
+ * A custom opener plugin to pass the path to documents as
313
+ * query string parameters.
314
+ */
315
+ const opener: JupyterFrontEndPlugin<void> = {
316
+ id: '@jupyterlite/application-extension:opener',
317
+ autoStart: true,
318
+ requires: [IRouter, IDocumentManager],
319
+ optional: [ILabShell, ISettingRegistry],
320
+ activate: (
321
+ app: JupyterFrontEnd,
322
+ router: IRouter,
323
+ docManager: IDocumentManager,
324
+ labShell: ILabShell | null,
325
+ settingRegistry: ISettingRegistry | null,
326
+ ): void => {
327
+ const { commands, docRegistry } = app;
328
+
329
+ const command = 'router:tree';
330
+ commands.addCommand(command, {
331
+ execute: (args: any) => {
332
+ const parsed = args as IRouter.ILocation;
333
+ // use request to do the matching
334
+ const { request, search } = parsed;
335
+ const matches = request.match(URL_PATTERN) ?? [];
336
+ if (!matches) {
337
+ return;
338
+ }
339
+
340
+ const urlParams = new URLSearchParams(search);
341
+ const paths = urlParams.getAll('path');
342
+ if (paths.length === 0) {
343
+ return;
344
+ }
345
+ const files = paths.map((path) => decodeURIComponent(path));
346
+ app.started.then(async () => {
347
+ const page = PageConfig.getOption('notebookPage');
348
+ const [file] = files;
349
+ if (page === 'tree') {
350
+ let appUrl = '/edit';
351
+ // check if the file is a notebook
352
+ const defaultFactory = docRegistry.defaultWidgetFactory(file);
353
+ if (defaultFactory.name === 'Notebook') {
354
+ appUrl = '/notebooks';
355
+ }
356
+ const baseUrl = PageConfig.getBaseUrl();
357
+ const url = new URL(URLExt.join(baseUrl, appUrl, 'index.html'));
358
+ url.searchParams.append('path', file);
359
+
360
+ // redirect to the proper page
361
+ window.location.href = url.toString();
362
+ return;
363
+ } else if (page === 'consoles') {
364
+ commands.execute('console:create', { path: file });
365
+ return;
366
+ } else if (page === 'notebooks' || page === 'edit') {
367
+ let defaultFactory = docRegistry.defaultWidgetFactory(file).name;
368
+
369
+ // Explicitly get the default viewers from the settings because
370
+ // JupyterLab might not have had the time to load the settings yet (race condition)
371
+ // Relevant code: https://github.com/jupyterlab/jupyterlab/blob/d56ff811f39b3c10c6d8b6eb27a94624b753eb53/packages/docmanager-extension/src/index.tsx#L265-L293
372
+ if (settingRegistry) {
373
+ const settings = await settingRegistry.load(
374
+ JUPYTERLAB_DOCMANAGER_PLUGIN_ID,
375
+ );
376
+ const defaultViewers = settings.get('defaultViewers').composite as {
377
+ [ft: string]: string;
378
+ };
379
+ // get the file types for the path
380
+ const types = docRegistry.getFileTypesForPath(file);
381
+ // for each file type, check if there is a default viewer and if it
382
+ // is available in the docRegistry. If it is the case, use it as the
383
+ // default factory
384
+ types.forEach((ft) => {
385
+ if (
386
+ defaultViewers[ft.name] !== undefined &&
387
+ docRegistry.getWidgetFactory(defaultViewers[ft.name])
388
+ ) {
389
+ defaultFactory = defaultViewers[ft.name];
390
+ }
391
+ });
392
+ }
393
+
394
+ const factory = urlParams.get('factory') ?? defaultFactory;
395
+ docManager.open(file, factory, undefined, {
396
+ ref: '_noref',
397
+ });
398
+ } else {
399
+ // open all files in the lab interface
400
+ files.forEach((file) => docManager.open(file));
401
+ const url = new URL(URLExt.join(PageConfig.getBaseUrl(), request));
402
+ // only remove the path (to keep extra parameters like the RTC room)
403
+ url.searchParams.delete('path');
404
+ const { pathname, search } = url;
405
+ router.navigate(`${pathname}${search}`, { skipRouting: true });
406
+
407
+ if (labShell) {
408
+ // open the folder where the files are located on startup
409
+ const showInBrowser = () => {
410
+ commands.execute('docmanager:show-in-file-browser');
411
+ labShell.currentChanged.disconnect(showInBrowser);
412
+ };
413
+
414
+ labShell.currentChanged.connect(showInBrowser);
415
+ }
416
+ }
417
+ });
418
+ },
419
+ });
420
+
421
+ router.register({ command, pattern: URL_PATTERN });
422
+ },
423
+ };
424
+
425
+ /**
426
+ * A plugin to patch the session context path so it includes the drive name.
427
+ * TODO: investigate a better way for the kernel to be aware of the drive it is
428
+ * associated with.
429
+ */
430
+ const sessionContextPatch: JupyterFrontEndPlugin<void> = {
431
+ id: '@jupyterlite/application-extension:session-context-patch',
432
+ autoStart: true,
433
+ requires: [IDocumentManager, IDocumentWidgetOpener],
434
+ activate: (
435
+ app: JupyterFrontEnd,
436
+ docManager: IDocumentManager,
437
+ widgetOpener: IDocumentWidgetOpener,
438
+ ) => {
439
+ const contents = app.serviceManager.contents;
440
+
441
+ widgetOpener.opened.connect((_, widget) => {
442
+ const context = docManager.contextForWidget(widget);
443
+ const driveName = contents.driveName(context?.path ?? '');
444
+ if (driveName === '') {
445
+ // do nothing if this is the default drive
446
+ return;
447
+ }
448
+ const sessionContext = widget.context.sessionContext as SessionContext;
449
+ // Path the session context to include the drive name
450
+ // In JupyterLab 3 the path used to contain the drive name as prefix, which was
451
+ // also part of the /api/sessions requests. Which allowed for knowing the drive associated
452
+ // with a kernel.
453
+ // This was changed in JupyterLab 4 in https://github.com/jupyterlab/jupyterlab/pull/14519
454
+ // and is needed for the kernel to be aware of the drive it is associated with.
455
+ // This is a temporary fix until a better solution is found upstream in JupyterLab ideally.
456
+ // This also avoid having to patch the downstream kernels (e.g. xeus-python and pyodide)
457
+ sessionContext['_name'] = context?.path;
458
+ sessionContext['_path'] = context?.path;
459
+ });
460
+ },
461
+ };
462
+
463
+ /**
464
+ * A custom plugin to share a link to a file.
465
+ *
466
+ * This url can be used to open a particular file in JupyterLab.
467
+ * It also adds the corresponding room if RTC is enabled.
468
+ *
469
+ */
470
+ const shareFile: JupyterFrontEndPlugin<void> = {
471
+ id: '@jupyterlite/application-extension:share-file',
472
+ requires: [IFileBrowserFactory, ITranslator],
473
+ autoStart: true,
474
+ activate: (
475
+ app: JupyterFrontEnd,
476
+ factory: IFileBrowserFactory,
477
+ translator: ITranslator,
478
+ ): void => {
479
+ const trans = translator.load(I18N_BUNDLE);
480
+ const { commands, docRegistry } = app;
481
+ const { tracker } = factory;
482
+
483
+ const roomName = getParam('--room', '').trim();
484
+ const collaborative = PageConfig.getOption('collaborative') === 'true' && roomName;
485
+
486
+ commands.addCommand(CommandIDs.copyShareableLink, {
487
+ execute: () => {
488
+ const widget = tracker.currentWidget;
489
+ if (!widget) {
490
+ return;
491
+ }
492
+
493
+ const baseUrl = PageConfig.getBaseUrl();
494
+ let appUrl = PageConfig.getOption('appUrl');
495
+
496
+ const models = Array.from(
497
+ filter(widget.selectedItems(), (item) => item.type !== 'directory'),
498
+ );
499
+
500
+ if (!models.length) {
501
+ return;
502
+ }
503
+
504
+ // In the notebook application:
505
+ // - only copy the first element
506
+ // - open /notebooks if it's a notebook, /edit otherwise
507
+ if (appUrl === '/tree') {
508
+ const [model] = models;
509
+ const defaultFactory = docRegistry.defaultWidgetFactory(model.path);
510
+ if (defaultFactory.name === 'Notebook') {
511
+ appUrl = '/notebooks';
512
+ } else {
513
+ appUrl = '/edit';
514
+ }
515
+ }
516
+
517
+ const url = new URL(URLExt.join(baseUrl, appUrl, 'index.html'));
518
+ models.forEach((model) => {
519
+ url.searchParams.append('path', model.path);
520
+ });
521
+ if (collaborative) {
522
+ url.searchParams.append('room', roomName);
523
+ }
524
+ Clipboard.copyToSystem(url.href);
525
+ },
526
+ isVisible: () =>
527
+ !!tracker.currentWidget &&
528
+ Array.from(tracker.currentWidget.selectedItems()).length >= 1,
529
+ icon: linkIcon.bindprops({ stylesheet: 'menuItem' }),
530
+ label: trans.__('Copy Shareable Link'),
531
+ });
532
+ },
533
+ };
534
+
535
+ const plugins: JupyterFrontEndPlugin<any>[] = [
536
+ about,
537
+ downloadPlugin,
538
+ liteLogo,
539
+ notifyCommands,
540
+ opener,
541
+ sessionContextPatch,
542
+ shareFile,
543
+ ];
544
+
545
+ export default plugins;