index.ts 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610
  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. if (!browser.isHidden) {
  254. app.shell.collapseLeft();
  255. }
  256. }
  257. });
  258. commands.addCommand(CommandIDs.navigate, {
  259. execute: args => {
  260. const path = (args.path as string) || '';
  261. const browserForPath = getBrowserForPath(path);
  262. const services = app.serviceManager;
  263. const localPath = services.contents.localPath(path);
  264. const failure = (reason: any) => {
  265. console.warn(`${CommandIDs.navigate} failed to open: ${path}`, reason);
  266. };
  267. return services.ready
  268. .then(() => services.contents.get(path))
  269. .then(value => {
  270. const { model } = browserForPath;
  271. const { restored } = model;
  272. if (value.type === 'directory') {
  273. return restored.then(() => model.cd(`/${localPath}`));
  274. }
  275. return restored
  276. .then(() => model.cd(`/${PathExt.dirname(localPath)}`))
  277. .then(() => commands.execute('docmanager:open', { path: path }));
  278. })
  279. .catch(failure);
  280. }
  281. });
  282. commands.addCommand(CommandIDs.open, {
  283. execute: () => {
  284. const widget = tracker.currentWidget;
  285. if (!widget) {
  286. return;
  287. }
  288. return Promise.all(
  289. toArray(
  290. map(widget.selectedItems(), item => {
  291. if (item.type === 'directory') {
  292. return widget.model.cd(item.name);
  293. }
  294. return commands.execute('docmanager:open', { path: item.path });
  295. })
  296. )
  297. );
  298. },
  299. iconClass: 'jp-MaterialIcon jp-OpenFolderIcon',
  300. label: 'Open',
  301. mnemonic: 0
  302. });
  303. commands.addCommand(CommandIDs.openBrowserTab, {
  304. execute: () => {
  305. const widget = tracker.currentWidget;
  306. if (!widget) {
  307. return;
  308. }
  309. return Promise.all(
  310. toArray(
  311. map(widget.selectedItems(), item => {
  312. return commands.execute('docmanager:open-browser-tab', {
  313. path: item.path
  314. });
  315. })
  316. )
  317. );
  318. },
  319. iconClass: 'jp-MaterialIcon jp-AddIcon',
  320. label: 'Open in New Browser Tab',
  321. mnemonic: 0
  322. });
  323. commands.addCommand(CommandIDs.copyDownloadLink, {
  324. execute: () => {
  325. const widget = tracker.currentWidget;
  326. if (!widget) {
  327. return;
  328. }
  329. return browser.model.manager.services.contents
  330. .getDownloadUrl(browser.selectedItems().next().path)
  331. .then(url => {
  332. Clipboard.copyToSystem(url);
  333. });
  334. },
  335. iconClass: 'jp-MaterialIcon jp-CopyIcon',
  336. label: 'Copy Download Link',
  337. mnemonic: 0
  338. });
  339. commands.addCommand(CommandIDs.paste, {
  340. execute: () => {
  341. const widget = tracker.currentWidget;
  342. if (widget) {
  343. return widget.paste();
  344. }
  345. },
  346. iconClass: 'jp-MaterialIcon jp-PasteIcon',
  347. label: 'Paste',
  348. mnemonic: 0
  349. });
  350. commands.addCommand(CommandIDs.rename, {
  351. execute: args => {
  352. const widget = tracker.currentWidget;
  353. if (widget) {
  354. return widget.rename();
  355. }
  356. },
  357. iconClass: 'jp-MaterialIcon jp-EditIcon',
  358. label: 'Rename',
  359. mnemonic: 0
  360. });
  361. commands.addCommand(CommandIDs.share, {
  362. execute: () => {
  363. const path = encodeURIComponent(browser.selectedItems().next().path);
  364. const tree = PageConfig.getTreeUrl({ workspace: true });
  365. Clipboard.copyToSystem(URLExt.join(tree, path));
  366. },
  367. isVisible: () => toArray(browser.selectedItems()).length === 1,
  368. iconClass: 'jp-MaterialIcon jp-LinkIcon',
  369. label: 'Copy Shareable Link'
  370. });
  371. commands.addCommand(CommandIDs.copyPath, {
  372. execute: () => {
  373. const item = browser.selectedItems().next();
  374. if (!item) {
  375. return;
  376. }
  377. Clipboard.copyToSystem(item.path);
  378. },
  379. isVisible: () => browser.selectedItems().next !== undefined,
  380. iconClass: 'jp-MaterialIcon jp-FileIcon',
  381. label: 'Copy Path'
  382. });
  383. commands.addCommand(CommandIDs.showBrowser, {
  384. execute: args => {
  385. const path = (args.path as string) || '';
  386. const browserForPath = getBrowserForPath(path);
  387. // Check for browser not found
  388. if (!browserForPath) {
  389. return;
  390. }
  391. // Shortcut if we are using the main file browser
  392. if (browser === browserForPath) {
  393. app.shell.activateById(browser.id);
  394. return;
  395. } else {
  396. const areas: ApplicationShell.Area[] = ['left', 'right'];
  397. for (let area of areas) {
  398. const it = app.shell.widgets(area);
  399. let widget = it.next();
  400. while (widget) {
  401. if (widget.contains(browserForPath)) {
  402. app.shell.activateById(widget.id);
  403. return;
  404. }
  405. widget = it.next();
  406. }
  407. }
  408. }
  409. }
  410. });
  411. commands.addCommand(CommandIDs.shutdown, {
  412. execute: () => {
  413. const widget = tracker.currentWidget;
  414. if (widget) {
  415. return widget.shutdownKernels();
  416. }
  417. },
  418. iconClass: 'jp-MaterialIcon jp-StopIcon',
  419. label: 'Shutdown Kernel'
  420. });
  421. commands.addCommand(CommandIDs.toggleBrowser, {
  422. execute: () => {
  423. if (browser.isHidden) {
  424. return commands.execute(CommandIDs.showBrowser, void 0);
  425. }
  426. return commands.execute(CommandIDs.hideBrowser, void 0);
  427. }
  428. });
  429. commands.addCommand(CommandIDs.createLauncher, {
  430. label: 'New Launcher',
  431. execute: () => createLauncher(commands, browser)
  432. });
  433. }
  434. /**
  435. * Create a context menu for the file browser listing.
  436. *
  437. * #### Notes
  438. * This function generates temporary commands with an incremented name. These
  439. * commands are disposed when the menu itself is disposed.
  440. */
  441. function createContextMenu(
  442. model: Contents.IModel | undefined,
  443. commands: CommandRegistry,
  444. registry: DocumentRegistry
  445. ): Menu {
  446. const menu = new Menu({ commands });
  447. // If the user did not click on any file, we still want to show
  448. // paste as a possibility.
  449. if (!model) {
  450. menu.addItem({ command: CommandIDs.paste });
  451. return menu;
  452. }
  453. menu.addItem({ command: CommandIDs.open });
  454. const path = model.path;
  455. if (model.type !== 'directory') {
  456. const factories = registry.preferredWidgetFactories(path).map(f => f.name);
  457. const notebookFactory = registry.getWidgetFactory('notebook').name;
  458. if (
  459. model.type === 'notebook' &&
  460. factories.indexOf(notebookFactory) === -1
  461. ) {
  462. factories.unshift(notebookFactory);
  463. }
  464. if (path && factories.length > 1) {
  465. const command = 'docmanager:open';
  466. const openWith = new Menu({ commands });
  467. openWith.title.label = 'Open With';
  468. factories.forEach(factory => {
  469. openWith.addItem({ args: { factory, path }, command });
  470. });
  471. menu.addItem({ type: 'submenu', submenu: openWith });
  472. }
  473. menu.addItem({ command: CommandIDs.openBrowserTab });
  474. }
  475. menu.addItem({ command: CommandIDs.rename });
  476. menu.addItem({ command: CommandIDs.del });
  477. menu.addItem({ command: CommandIDs.cut });
  478. if (model.type !== 'directory') {
  479. menu.addItem({ command: CommandIDs.copy });
  480. }
  481. menu.addItem({ command: CommandIDs.paste });
  482. if (model.type !== 'directory') {
  483. menu.addItem({ command: CommandIDs.duplicate });
  484. menu.addItem({ command: CommandIDs.download });
  485. menu.addItem({ command: CommandIDs.shutdown });
  486. }
  487. menu.addItem({ command: CommandIDs.share });
  488. menu.addItem({ command: CommandIDs.copyPath });
  489. menu.addItem({ command: CommandIDs.copyDownloadLink });
  490. return menu;
  491. }
  492. /**
  493. * Create a launcher for a given filebrowser widget.
  494. */
  495. function createLauncher(
  496. commands: CommandRegistry,
  497. browser: FileBrowser
  498. ): Promise<MainAreaWidget<Launcher>> {
  499. const { model } = browser;
  500. return commands
  501. .execute('launcher:create', { cwd: model.path })
  502. .then((launcher: MainAreaWidget<Launcher>) => {
  503. model.pathChanged.connect(() => {
  504. launcher.content.cwd = model.path;
  505. }, launcher);
  506. return launcher;
  507. });
  508. }