index.ts 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626
  1. // Copyright (c) Jupyter Development Team.
  2. // Distributed under the terms of the Modified BSD License.
  3. import {
  4. ApplicationShell,
  5. ILayoutRestorer,
  6. JupyterLab,
  7. JupyterLabPlugin
  8. } from '@jupyterlab/application';
  9. import {
  10. Clipboard,
  11. InstanceTracker,
  12. MainAreaWidget,
  13. ToolbarButton
  14. } from '@jupyterlab/apputils';
  15. import { IStateDB, PageConfig, PathExt, URLExt } from '@jupyterlab/coreutils';
  16. import { IDocumentManager } from '@jupyterlab/docmanager';
  17. import { DocumentRegistry } from '@jupyterlab/docregistry';
  18. import {
  19. FileBrowserModel,
  20. FileBrowser,
  21. IFileBrowserFactory
  22. } from '@jupyterlab/filebrowser';
  23. import { Launcher } from '@jupyterlab/launcher';
  24. import { Contents } from '@jupyterlab/services';
  25. import { map, toArray } from '@phosphor/algorithm';
  26. import { CommandRegistry } from '@phosphor/commands';
  27. import { Menu } from '@phosphor/widgets';
  28. /**
  29. * The command IDs used by the file browser plugin.
  30. */
  31. namespace CommandIDs {
  32. export const copy = 'filebrowser:copy';
  33. export const copyDownloadLink = 'filebrowser:copy-download-link';
  34. // For main browser only.
  35. export const createLauncher = 'filebrowser:create-main-launcher';
  36. export const cut = 'filebrowser:cut';
  37. export const del = 'filebrowser:delete';
  38. export const download = 'filebrowser:download';
  39. export const duplicate = 'filebrowser:duplicate';
  40. // For main browser only.
  41. export const hideBrowser = 'filebrowser:hide-main';
  42. export const navigate = 'filebrowser:navigate';
  43. export const open = 'filebrowser:open';
  44. export const openBrowserTab = 'filebrowser:open-browser-tab';
  45. export const paste = 'filebrowser:paste';
  46. export const rename = 'filebrowser:rename';
  47. // For main browser only.
  48. export const share = 'filebrowser:share-main';
  49. // For main browser only.
  50. export const copyPath = 'filebrowser:copy-path';
  51. export const showBrowser = 'filebrowser:activate';
  52. export const shutdown = 'filebrowser:shutdown';
  53. // For main browser only.
  54. export const toggleBrowser = 'filebrowser:toggle-main';
  55. }
  56. /**
  57. * The default file browser extension.
  58. */
  59. const browser: JupyterLabPlugin<void> = {
  60. activate: activateBrowser,
  61. id: '@jupyterlab/filebrowser-extension:browser',
  62. requires: [IFileBrowserFactory, ILayoutRestorer],
  63. autoStart: true
  64. };
  65. /**
  66. * The default file browser factory provider.
  67. */
  68. const factory: JupyterLabPlugin<IFileBrowserFactory> = {
  69. activate: activateFactory,
  70. id: '@jupyterlab/filebrowser-extension:factory',
  71. provides: IFileBrowserFactory,
  72. requires: [IDocumentManager, IStateDB]
  73. };
  74. /**
  75. * The file browser namespace token.
  76. */
  77. const namespace = 'filebrowser';
  78. /**
  79. * Export the plugins as default.
  80. */
  81. const plugins: JupyterLabPlugin<any>[] = [factory, browser];
  82. export default plugins;
  83. /**
  84. * Activate the file browser factory provider.
  85. */
  86. function activateFactory(
  87. app: JupyterLab,
  88. docManager: IDocumentManager,
  89. state: IStateDB
  90. ): IFileBrowserFactory {
  91. const { commands } = app;
  92. const tracker = new InstanceTracker<FileBrowser>({ namespace });
  93. const createFileBrowser = (
  94. id: string,
  95. options: IFileBrowserFactory.IOptions = {}
  96. ) => {
  97. const model = new FileBrowserModel({
  98. manager: docManager,
  99. driveName: options.driveName || '',
  100. refreshInterval: options.refreshInterval,
  101. state: options.state === null ? null : options.state || state
  102. });
  103. const widget = new FileBrowser({
  104. id,
  105. model,
  106. commands: options.commands || commands
  107. });
  108. const { registry } = docManager;
  109. // Add a launcher toolbar item.
  110. let launcher = new ToolbarButton({
  111. iconClassName: 'jp-AddIcon jp-Icon jp-Icon-16',
  112. onClick: () => {
  113. return createLauncher(commands, widget);
  114. },
  115. tooltip: 'New Launcher'
  116. });
  117. widget.toolbar.insertItem(0, 'launch', launcher);
  118. // Add a context menu handler to the file browser's directory listing.
  119. let node = widget.node.getElementsByClassName('jp-DirListing-content')[0];
  120. node.addEventListener('contextmenu', (event: MouseEvent) => {
  121. event.preventDefault();
  122. const model = widget.modelForClick(event);
  123. const menu = createContextMenu(model, commands, registry);
  124. menu.open(event.clientX, event.clientY);
  125. });
  126. // Track the newly created file browser.
  127. tracker.add(widget);
  128. return widget;
  129. };
  130. const defaultBrowser = createFileBrowser('filebrowser');
  131. return { createFileBrowser, defaultBrowser, tracker };
  132. }
  133. /**
  134. * Activate the default file browser in the sidebar.
  135. */
  136. function activateBrowser(
  137. app: JupyterLab,
  138. factory: IFileBrowserFactory,
  139. restorer: ILayoutRestorer
  140. ): void {
  141. const browser = factory.defaultBrowser;
  142. const { commands, shell } = app;
  143. // Let the application restorer track the primary file browser (that is
  144. // automatically created) for restoration of application state (e.g. setting
  145. // the file browser as the current side bar widget).
  146. //
  147. // All other file browsers created by using the factory function are
  148. // responsible for their own restoration behavior, if any.
  149. restorer.add(browser, namespace);
  150. addCommands(app, factory.tracker, browser);
  151. browser.title.iconClass = 'jp-FolderIcon jp-SideBar-tabIcon';
  152. browser.title.caption = 'File Browser';
  153. shell.addToLeftArea(browser, { rank: 100 });
  154. // If the layout is a fresh session without saved data, open file browser.
  155. app.restored.then(layout => {
  156. if (layout.fresh) {
  157. commands.execute(CommandIDs.showBrowser, void 0);
  158. }
  159. });
  160. Promise.all([app.restored, browser.model.restored]).then(() => {
  161. function maybeCreate() {
  162. // Create a launcher if there are no open items.
  163. if (app.shell.isEmpty('main')) {
  164. createLauncher(commands, browser);
  165. }
  166. }
  167. // When layout is modified, create a launcher if there are no open items.
  168. shell.layoutModified.connect(() => {
  169. maybeCreate();
  170. });
  171. maybeCreate();
  172. });
  173. }
  174. /**
  175. * Add the main file browser commands to the application's command registry.
  176. */
  177. function addCommands(
  178. app: JupyterLab,
  179. tracker: InstanceTracker<FileBrowser>,
  180. browser: FileBrowser
  181. ): void {
  182. const getBrowserForPath = (path: string): FileBrowser => {
  183. const driveName = app.serviceManager.contents.driveName(path);
  184. if (driveName) {
  185. let browserForPath = tracker.find(fb => fb.model.driveName === driveName);
  186. if (!browserForPath) {
  187. // warn that no filebrowser could be found for this driveName
  188. console.warn(
  189. `${CommandIDs.navigate} failed to find filebrowser for path: ${path}`
  190. );
  191. return;
  192. }
  193. return browserForPath;
  194. }
  195. // if driveName is empty, assume the main filebrowser
  196. return browser;
  197. };
  198. const { commands } = app;
  199. commands.addCommand(CommandIDs.del, {
  200. execute: () => {
  201. const widget = tracker.currentWidget;
  202. if (widget) {
  203. return widget.delete();
  204. }
  205. },
  206. iconClass: 'jp-MaterialIcon jp-CloseIcon',
  207. label: 'Delete',
  208. mnemonic: 0
  209. });
  210. commands.addCommand(CommandIDs.copy, {
  211. execute: () => {
  212. const widget = tracker.currentWidget;
  213. if (widget) {
  214. return widget.copy();
  215. }
  216. },
  217. iconClass: 'jp-MaterialIcon jp-CopyIcon',
  218. label: 'Copy',
  219. mnemonic: 0
  220. });
  221. commands.addCommand(CommandIDs.cut, {
  222. execute: () => {
  223. const widget = tracker.currentWidget;
  224. if (widget) {
  225. return widget.cut();
  226. }
  227. },
  228. iconClass: 'jp-MaterialIcon jp-CutIcon',
  229. label: 'Cut'
  230. });
  231. commands.addCommand(CommandIDs.download, {
  232. execute: () => {
  233. const widget = tracker.currentWidget;
  234. if (widget) {
  235. return widget.download();
  236. }
  237. },
  238. iconClass: 'jp-MaterialIcon jp-DownloadIcon',
  239. label: 'Download'
  240. });
  241. commands.addCommand(CommandIDs.duplicate, {
  242. execute: () => {
  243. const widget = tracker.currentWidget;
  244. if (widget) {
  245. return widget.duplicate();
  246. }
  247. },
  248. iconClass: 'jp-MaterialIcon jp-CopyIcon',
  249. label: 'Duplicate'
  250. });
  251. commands.addCommand(CommandIDs.hideBrowser, {
  252. execute: () => {
  253. const widget = tracker.currentWidget;
  254. if (widget && !widget.isHidden) {
  255. app.shell.collapseLeft();
  256. }
  257. }
  258. });
  259. commands.addCommand(CommandIDs.navigate, {
  260. execute: args => {
  261. const path = (args.path as string) || '';
  262. const browserForPath = getBrowserForPath(path);
  263. const services = app.serviceManager;
  264. const localPath = services.contents.localPath(path);
  265. const failure = (reason: any) => {
  266. console.warn(`${CommandIDs.navigate} failed to open: ${path}`, reason);
  267. };
  268. return services.ready
  269. .then(() => services.contents.get(path))
  270. .then(value => {
  271. const { model } = browserForPath;
  272. const { restored } = model;
  273. if (value.type === 'directory') {
  274. return restored.then(() => model.cd(`/${localPath}`));
  275. }
  276. return restored
  277. .then(() => model.cd(`/${PathExt.dirname(localPath)}`))
  278. .then(() => commands.execute('docmanager:open', { path: path }));
  279. })
  280. .catch(failure);
  281. }
  282. });
  283. commands.addCommand(CommandIDs.open, {
  284. execute: () => {
  285. const widget = tracker.currentWidget;
  286. if (!widget) {
  287. return;
  288. }
  289. return Promise.all(
  290. toArray(
  291. map(widget.selectedItems(), item => {
  292. if (item.type === 'directory') {
  293. return widget.model.cd(item.name);
  294. }
  295. return commands.execute('docmanager:open', { path: item.path });
  296. })
  297. )
  298. );
  299. },
  300. iconClass: 'jp-MaterialIcon jp-OpenFolderIcon',
  301. label: 'Open',
  302. mnemonic: 0
  303. });
  304. commands.addCommand(CommandIDs.openBrowserTab, {
  305. execute: () => {
  306. const widget = tracker.currentWidget;
  307. if (!widget) {
  308. return;
  309. }
  310. return Promise.all(
  311. toArray(
  312. map(widget.selectedItems(), item => {
  313. return commands.execute('docmanager:open-browser-tab', {
  314. path: item.path
  315. });
  316. })
  317. )
  318. );
  319. },
  320. iconClass: 'jp-MaterialIcon jp-AddIcon',
  321. label: 'Open in New Browser Tab',
  322. mnemonic: 0
  323. });
  324. commands.addCommand(CommandIDs.copyDownloadLink, {
  325. execute: () => {
  326. const widget = tracker.currentWidget;
  327. if (!widget) {
  328. return;
  329. }
  330. return widget.model.manager.services.contents
  331. .getDownloadUrl(widget.selectedItems().next().path)
  332. .then(url => {
  333. Clipboard.copyToSystem(url);
  334. });
  335. },
  336. iconClass: 'jp-MaterialIcon jp-CopyIcon',
  337. label: 'Copy Download Link',
  338. mnemonic: 0
  339. });
  340. commands.addCommand(CommandIDs.paste, {
  341. execute: () => {
  342. const widget = tracker.currentWidget;
  343. if (widget) {
  344. return widget.paste();
  345. }
  346. },
  347. iconClass: 'jp-MaterialIcon jp-PasteIcon',
  348. label: 'Paste',
  349. mnemonic: 0
  350. });
  351. commands.addCommand(CommandIDs.rename, {
  352. execute: args => {
  353. const widget = tracker.currentWidget;
  354. if (widget) {
  355. return widget.rename();
  356. }
  357. },
  358. iconClass: 'jp-MaterialIcon jp-EditIcon',
  359. label: 'Rename',
  360. mnemonic: 0
  361. });
  362. commands.addCommand(CommandIDs.share, {
  363. execute: () => {
  364. const widget = tracker.currentWidget;
  365. if (!widget) {
  366. return;
  367. }
  368. const path = encodeURI(widget.selectedItems().next().path);
  369. const tree = PageConfig.getTreeUrl({ workspace: true });
  370. Clipboard.copyToSystem(URLExt.join(tree, path));
  371. },
  372. isVisible: () =>
  373. tracker.currentWidget &&
  374. toArray(tracker.currentWidget.selectedItems()).length === 1,
  375. iconClass: 'jp-MaterialIcon jp-LinkIcon',
  376. label: 'Copy Shareable Link'
  377. });
  378. commands.addCommand(CommandIDs.copyPath, {
  379. execute: () => {
  380. const widget = tracker.currentWidget;
  381. if (!widget) {
  382. return;
  383. }
  384. const item = widget.selectedItems().next();
  385. if (!item) {
  386. return;
  387. }
  388. Clipboard.copyToSystem(item.path);
  389. },
  390. isVisible: () =>
  391. tracker.currentWidget &&
  392. tracker.currentWidget.selectedItems().next !== undefined,
  393. iconClass: 'jp-MaterialIcon jp-FileIcon',
  394. label: 'Copy Path'
  395. });
  396. commands.addCommand(CommandIDs.showBrowser, {
  397. execute: args => {
  398. const path = (args.path as string) || '';
  399. const browserForPath = getBrowserForPath(path);
  400. // Check for browser not found
  401. if (!browserForPath) {
  402. return;
  403. }
  404. // Shortcut if we are using the main file browser
  405. if (browser === browserForPath) {
  406. app.shell.activateById(browser.id);
  407. return;
  408. } else {
  409. const areas: ApplicationShell.Area[] = ['left', 'right'];
  410. for (let area of areas) {
  411. const it = app.shell.widgets(area);
  412. let widget = it.next();
  413. while (widget) {
  414. if (widget.contains(browserForPath)) {
  415. app.shell.activateById(widget.id);
  416. return;
  417. }
  418. widget = it.next();
  419. }
  420. }
  421. }
  422. }
  423. });
  424. commands.addCommand(CommandIDs.shutdown, {
  425. execute: () => {
  426. const widget = tracker.currentWidget;
  427. if (widget) {
  428. return widget.shutdownKernels();
  429. }
  430. },
  431. iconClass: 'jp-MaterialIcon jp-StopIcon',
  432. label: 'Shutdown Kernel'
  433. });
  434. commands.addCommand(CommandIDs.toggleBrowser, {
  435. execute: () => {
  436. if (browser.isHidden) {
  437. return commands.execute(CommandIDs.showBrowser, void 0);
  438. }
  439. return commands.execute(CommandIDs.hideBrowser, void 0);
  440. }
  441. });
  442. commands.addCommand(CommandIDs.createLauncher, {
  443. label: 'New Launcher',
  444. execute: () => createLauncher(commands, browser)
  445. });
  446. }
  447. /**
  448. * Create a context menu for the file browser listing.
  449. *
  450. * #### Notes
  451. * This function generates temporary commands with an incremented name. These
  452. * commands are disposed when the menu itself is disposed.
  453. */
  454. function createContextMenu(
  455. model: Contents.IModel | undefined,
  456. commands: CommandRegistry,
  457. registry: DocumentRegistry
  458. ): Menu {
  459. const menu = new Menu({ commands });
  460. // If the user did not click on any file, we still want to show
  461. // paste as a possibility.
  462. if (!model) {
  463. menu.addItem({ command: CommandIDs.paste });
  464. return menu;
  465. }
  466. menu.addItem({ command: CommandIDs.open });
  467. const path = model.path;
  468. if (model.type !== 'directory') {
  469. const factories = registry.preferredWidgetFactories(path).map(f => f.name);
  470. const notebookFactory = registry.getWidgetFactory('notebook').name;
  471. if (
  472. model.type === 'notebook' &&
  473. factories.indexOf(notebookFactory) === -1
  474. ) {
  475. factories.unshift(notebookFactory);
  476. }
  477. if (path && factories.length > 1) {
  478. const command = 'docmanager:open';
  479. const openWith = new Menu({ commands });
  480. openWith.title.label = 'Open With';
  481. factories.forEach(factory => {
  482. openWith.addItem({ args: { factory, path }, command });
  483. });
  484. menu.addItem({ type: 'submenu', submenu: openWith });
  485. }
  486. menu.addItem({ command: CommandIDs.openBrowserTab });
  487. }
  488. menu.addItem({ command: CommandIDs.rename });
  489. menu.addItem({ command: CommandIDs.del });
  490. menu.addItem({ command: CommandIDs.cut });
  491. if (model.type !== 'directory') {
  492. menu.addItem({ command: CommandIDs.copy });
  493. }
  494. menu.addItem({ command: CommandIDs.paste });
  495. if (model.type !== 'directory') {
  496. menu.addItem({ command: CommandIDs.duplicate });
  497. menu.addItem({ command: CommandIDs.download });
  498. menu.addItem({ command: CommandIDs.shutdown });
  499. }
  500. menu.addItem({ command: CommandIDs.share });
  501. menu.addItem({ command: CommandIDs.copyPath });
  502. menu.addItem({ command: CommandIDs.copyDownloadLink });
  503. return menu;
  504. }
  505. /**
  506. * Create a launcher for a given filebrowser widget.
  507. */
  508. function createLauncher(
  509. commands: CommandRegistry,
  510. browser: FileBrowser
  511. ): Promise<MainAreaWidget<Launcher>> {
  512. const { model } = browser;
  513. return commands
  514. .execute('launcher:create', { cwd: model.path })
  515. .then((launcher: MainAreaWidget<Launcher>) => {
  516. model.pathChanged.connect(
  517. () => {
  518. launcher.content.cwd = model.path;
  519. },
  520. launcher
  521. );
  522. return launcher;
  523. });
  524. }