Debian Codegraph @

packages/tree-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 JupyterFrontEnd,
6 JupyterFrontEndPlugin,
7 } from '@jupyterlab/application';
8
9 import {
10 ICommandPalette,
11 IToolbarWidgetRegistry,
12 createToolbarFactory,
13 setToolbar,
14 } from '@jupyterlab/apputils';
15
16 import { PageConfig } from '@jupyterlab/coreutils';
17
18 import {
19 FileBrowser,
20 Uploader,
21 IDefaultFileBrowser,
22 IFileBrowserFactory,
23 } from '@jupyterlab/filebrowser';
24
25 import { ISettingRegistry } from '@jupyterlab/settingregistry';
26
27 import { IRunningSessionManagers, RunningSessions } from '@jupyterlab/running';
28
29 import {
30 IJSONSettingEditorTracker,
31 ISettingEditorTracker,
32 } from '@jupyterlab/settingeditor';
33
34 import { ITranslator } from '@jupyterlab/translation';
35
36 import {
37 caretDownIcon,
38 folderIcon,
39 runningIcon,
40 } from '@jupyterlab/ui-components';
41
42 import { Signal } from '@lumino/signaling';
43
44 import { Menu, MenuBar } from '@lumino/widgets';
45
46 import { NotebookTreeWidget, INotebookTree } from '@jupyter-notebook/tree';
47
48 import { FilesActionButtons } from './fileactions';
49
50 /**
51 * The file browser factory.
52 */
53 const FILE_BROWSER_FACTORY = 'FileBrowser';
54
55 /**
56 * The file browser plugin id.
57 */
58 const FILE_BROWSER_PLUGIN_ID = '@jupyterlab/filebrowser-extension:browser';
59
60 /**
61 * The namespace for command IDs.
62 */
63 namespace CommandIDs {
64 // The command to activate the filebrowser widget in tree view.
65 export const activate = 'filebrowser:activate';
66
67 // Activate the file filter in the file browser
68 export const toggleFileFilter = 'filebrowser:toggle-file-filter';
69 }
70
71 /**
72 * Plugin to add extra commands to the file browser to create
73 * new notebooks, files, consoles and terminals
74 */
75 const createNew: JupyterFrontEndPlugin<void> = {
76 id: '@jupyter-notebook/tree-extension:new',
77 description:
78 'Plugin to add extra commands to the file browser to create new notebooks, files, consoles and terminals.',
79 requires: [ITranslator],
80 optional: [IToolbarWidgetRegistry],
81 autoStart: true,
82 activate: (
83 app: JupyterFrontEnd,
84 translator: ITranslator,
85 toolbarRegistry: IToolbarWidgetRegistry | null
86 ) => {
87 const { commands, serviceManager } = app;
88 const trans = translator.load('notebook');
89
90 const overflowOptions = {
91 overflowMenuOptions: { isVisible: false },
92 };
93 const menubar = new MenuBar(overflowOptions);
94 const newMenu = new Menu({ commands });
95 newMenu.title.label = trans.__('New');
96 newMenu.title.icon = caretDownIcon;
97 menubar.addMenu(newMenu);
98
99 const populateNewMenu = () => {
100 // create an entry per kernel spec for creating a new notebook
101 const specs = serviceManager.kernelspecs?.specs?.kernelspecs;
102 for (const name in specs) {
103 newMenu.addItem({
104 args: { kernelName: name, isLauncher: true },
105 command: 'notebook:create-new',
106 });
107 }
108
109 const baseCommands = [
110 'terminal:create-new',
111 'console:create',
112 'filebrowser:create-new-file',
113 'filebrowser:create-new-directory',
114 ];
115
116 baseCommands.forEach((command) => {
117 newMenu.addItem({ command });
118 });
119 };
120
121 serviceManager.kernelspecs?.specsChanged.connect(() => {
122 newMenu.clearItems();
123 populateNewMenu();
124 });
125
126 populateNewMenu();
127
128 if (toolbarRegistry) {
129 toolbarRegistry.addFactory(
130 FILE_BROWSER_FACTORY,
131 'new-dropdown',
132 (browser: FileBrowser) => {
133 const menubar = new MenuBar(overflowOptions);
134 menubar.addMenu(newMenu);
135 menubar.addClass('jp-DropdownMenu');
136 return menubar;
137 }
138 );
139 }
140 },
141 };
142
143 /**
144 * A plugin to add file browser actions to the file browser toolbar.
145 */
146 const fileActions: JupyterFrontEndPlugin<void> = {
147 id: '@jupyter-notebook/tree-extension:file-actions',
148 description:
149 'A plugin to add file browser actions to the file browser toolbar.',
150 autoStart: true,
151 requires: [IDefaultFileBrowser, IToolbarWidgetRegistry, ITranslator],
152 activate: (
153 app: JupyterFrontEnd,
154 browser: IDefaultFileBrowser,
155 toolbarRegistry: IToolbarWidgetRegistry,
156 translator: ITranslator
157 ) => {
158 // TODO: use upstream signal when available to detect selection changes
159 // https://github.com/jupyterlab/jupyterlab/issues/14598
160 const selectionChanged = new Signal<FileBrowser, void>(browser);
161 const methods = [
162 '_selectItem',
163 '_handleMultiSelect',
164 'handleFileSelect',
165 ] as const;
166 methods.forEach((method: (typeof methods)[number]) => {
167 const original = browser['listing'][method];
168 browser['listing'][method] = (...args: any[]) => {
169 original.call(browser['listing'], ...args);
170 selectionChanged.emit(void 0);
171 };
172 });
173 browser.model.pathChanged.connect(() => {
174 selectionChanged.emit(void 0);
175 });
176
177 // Create a toolbar item that adds buttons to the file browser toolbar
178 // to perform actions on the files
179 const { commands } = app;
180 const fileActions = new FilesActionButtons({
181 commands,
182 browser,
183 selectionChanged,
184 translator,
185 });
186 for (const widget of fileActions.widgets) {
187 toolbarRegistry.addFactory(FILE_BROWSER_FACTORY, widget.id, () => widget);
188 }
189 },
190 };
191
192 /**
193 * A plugin to set the default file browser settings.
194 */
195 const fileBrowserSettings: JupyterFrontEndPlugin<void> = {
196 id: '@jupyter-notebook/tree-extension:settings',
197 description: 'Set up the default file browser settings',
198 requires: [IDefaultFileBrowser],
199 optional: [ISettingRegistry],
200 autoStart: true,
201 activate: (
202 app: JupyterFrontEnd,
203 browser: IDefaultFileBrowser,
204 settingRegistry: ISettingRegistry | null
205 ) => {
206 // Default config for notebook.
207 // This is a different set of defaults than JupyterLab.
208 const defaultFileBrowserConfig = {
209 navigateToCurrentDirectory: false,
210 singleClickNavigation: true,
211 showLastModifiedColumn: true,
212 showFileSizeColumn: true,
213 showHiddenFiles: false,
214 showFileCheckboxes: true,
215 sortNotebooksFirst: true,
216 showFullPath: false,
217 };
218
219 // Apply defaults on plugin activation
220 let key: keyof typeof defaultFileBrowserConfig;
221 for (key in defaultFileBrowserConfig) {
222 browser[key] = defaultFileBrowserConfig[key];
223 }
224
225 if (settingRegistry) {
226 void settingRegistry.load(FILE_BROWSER_PLUGIN_ID).then((settings) => {
227 function onSettingsChanged(settings: ISettingRegistry.ISettings): void {
228 let key: keyof typeof defaultFileBrowserConfig;
229 for (key in defaultFileBrowserConfig) {
230 const value = settings.get(key).user as boolean;
231 // only set the setting if it is defined by the user
232 if (value !== undefined) {
233 browser[key] = value;
234 }
235 }
236 }
237 settings.changed.connect(onSettingsChanged);
238 onSettingsChanged(settings);
239 });
240 }
241 },
242 };
243
244 /**
245 * A plugin to add the file filter toggle command to the palette
246 */
247 const fileFilterCommand: JupyterFrontEndPlugin<void> = {
248 id: '@jupyter-notebook/tree-extension:file-filter-command',
249 description: 'A plugin to add file filter command to the palette.',
250 autoStart: true,
251 optional: [ICommandPalette],
252 activate: (app: JupyterFrontEnd, palette: ICommandPalette | null) => {
253 if (palette) {
254 palette.addItem({
255 command: CommandIDs.toggleFileFilter,
256 category: 'File Browser',
257 });
258 }
259 },
260 };
261
262 /**
263 * Plugin to load the default plugins that are loaded on all the Notebook pages
264 * (tree, edit, view, etc.) so they are visible in the settings editor.
265 */
266 const loadPlugins: JupyterFrontEndPlugin<void> = {
267 id: '@jupyter-notebook/tree-extension:load-plugins',
268 description:
269 'Plugin to load the default plugins that are loaded on all the Notebook pages (tree, edit, view, etc.) so they are visible in the settings editor.',
270 autoStart: true,
271 requires: [ISettingRegistry],
272 activate(app: JupyterFrontEnd, settingRegistry: ISettingRegistry) {
273 const { isDisabled } = PageConfig.Extension;
274 const connector = settingRegistry.connector;
275
276 const allPluginsOption = PageConfig.getOption('allPlugins');
277 if (!allPluginsOption) {
278 return;
279 }
280
281 // build the list of plugins shipped by default on the all the notebook pages
282 // this avoid explicitly loading `'all'` plugins such as the ones used
283 // in JupyterLab only
284 const allPlugins = JSON.parse(allPluginsOption);
285 const pluginsSet = new Set<string>();
286 Object.keys(allPlugins).forEach((key: string) => {
287 const extensionsAndPlugins: { [key: string]: boolean | [string] } =
288 allPlugins[key];
289 Object.keys(extensionsAndPlugins).forEach((plugin) => {
290 const value = extensionsAndPlugins[plugin];
291 if (typeof value === 'boolean' && value) {
292 pluginsSet.add(plugin);
293 } else if (Array.isArray(value)) {
294 value.forEach((v: string) => {
295 pluginsSet.add(v);
296 });
297 }
298 });
299 });
300
301 app.restored.then(async () => {
302 const plugins = await connector.list('all');
303 plugins.ids.forEach(async (id: string) => {
304 const [extension] = id.split(':');
305 // load the plugin if it is built-in the notebook application explicitly
306 // either included as an extension or as a plugin directly
307 const hasPlugin = pluginsSet.has(extension) || pluginsSet.has(id);
308 if (!hasPlugin || isDisabled(id) || id in settingRegistry.plugins) {
309 return;
310 }
311 try {
312 await settingRegistry.load(id);
313 } catch (error) {
314 console.warn(`Settings failed to load for (${id})`, error);
315 }
316 });
317 });
318 },
319 };
320
321 /**
322 * A plugin to add file browser commands for the tree view.
323 */
324 const openFileBrowser: JupyterFrontEndPlugin<void> = {
325 id: '@jupyter-notebook/tree-extension:open-file-browser',
326 description: 'A plugin to add file browser commands for the tree view.',
327 requires: [INotebookTree, IDefaultFileBrowser],
328 autoStart: true,
329 activate: (
330 app: JupyterFrontEnd,
331 notebookTree: INotebookTree,
332 browser: IDefaultFileBrowser
333 ) => {
334 const { commands } = app;
335 commands.addCommand(CommandIDs.activate, {
336 execute: () => {
337 notebookTree.currentWidget = browser;
338 },
339 });
340 },
341 };
342
343 /**
344 * A plugin to add the file browser widget to an INotebookShell
345 */
346 const notebookTreeWidget: JupyterFrontEndPlugin<INotebookTree> = {
347 id: '@jupyter-notebook/tree-extension:widget',
348 description: 'A plugin to add the file browser widget to an INotebookShell.',
349 requires: [
350 IDefaultFileBrowser,
351 ITranslator,
352 ISettingRegistry,
353 IToolbarWidgetRegistry,
354 IFileBrowserFactory,
355 ],
356 optional: [
357 IRunningSessionManagers,
358 ISettingEditorTracker,
359 IJSONSettingEditorTracker,
360 ],
361 autoStart: true,
362 provides: INotebookTree,
363 activate: (
364 app: JupyterFrontEnd,
365 browser: IDefaultFileBrowser,
366 translator: ITranslator,
367 settingRegistry: ISettingRegistry,
368 toolbarRegistry: IToolbarWidgetRegistry,
369 factory: IFileBrowserFactory,
370 manager: IRunningSessionManagers | null,
371 settingEditorTracker: ISettingEditorTracker | null,
372 jsonSettingEditorTracker: IJSONSettingEditorTracker | null
373 ): INotebookTree => {
374 const nbTreeWidget = new NotebookTreeWidget();
375
376 const trans = translator.load('notebook');
377
378 browser.title.label = trans.__('Files');
379 browser.node.setAttribute('role', 'region');
380 browser.node.setAttribute('aria-label', trans.__('File Browser Section'));
381 browser.title.icon = folderIcon;
382
383 nbTreeWidget.addWidget(browser);
384 nbTreeWidget.tabBar.addTab(browser.title);
385 nbTreeWidget.tabsMovable = false;
386
387 toolbarRegistry.addFactory(
388 FILE_BROWSER_FACTORY,
389 'uploader',
390 (browser: FileBrowser) =>
391 new Uploader({
392 model: browser.model,
393 translator,
394 label: trans.__('Upload'),
395 })
396 );
397
398 setToolbar(
399 browser,
400 createToolbarFactory(
401 toolbarRegistry,
402 settingRegistry,
403 FILE_BROWSER_FACTORY,
404 notebookTreeWidget.id,
405 translator
406 )
407 );
408
409 if (manager) {
410 const running = new RunningSessions(manager, translator);
411 running.id = 'jp-running-sessions-tree';
412 running.title.label = trans.__('Running');
413 running.title.icon = runningIcon;
414 nbTreeWidget.addWidget(running);
415 nbTreeWidget.tabBar.addTab(running.title);
416 }
417
418 app.shell.add(nbTreeWidget, 'main', { rank: 100 });
419
420 // add a separate tab for each setting editor
421 [settingEditorTracker, jsonSettingEditorTracker].forEach(
422 (editorTracker) => {
423 if (editorTracker) {
424 editorTracker.widgetAdded.connect((_, editor) => {
425 nbTreeWidget.addWidget(editor);
426 nbTreeWidget.tabBar.addTab(editor.title);
427 nbTreeWidget.currentWidget = editor;
428 });
429 }
430 }
431 );
432
433 const { tracker } = factory;
434
435 // TODO: remove
436 // Workaround to force the focus on the default file browser
437 // See https://github.com/jupyterlab/jupyterlab/issues/15629 for more info
438 const setCurrentToDefaultBrower = () => {
439 tracker['_pool'].current = browser;
440 };
441
442 tracker.widgetAdded.connect((sender, widget) => {
443 setCurrentToDefaultBrower();
444 });
445
446 setCurrentToDefaultBrower();
447
448 return nbTreeWidget;
449 },
450 };
451
452 /**
453 * Export the plugins as default.
454 */
455 const plugins: JupyterFrontEndPlugin<any>[] = [
456 createNew,
457 fileActions,
458 fileBrowserSettings,
459 fileFilterCommand,
460 loadPlugins,
461 openFileBrowser,
462 notebookTreeWidget,
463 ];
464 export default plugins;