index.tsx 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468
  1. // Copyright (c) Jupyter Development Team.
  2. // Distributed under the terms of the Modified BSD License.
  3. import {
  4. ArrayExt, ArrayIterator, IIterator, map, each, toArray
  5. } from '@phosphor/algorithm';
  6. import {
  7. Token
  8. } from '@phosphor/coreutils';
  9. import {
  10. DisposableDelegate, IDisposable
  11. } from '@phosphor/disposable';
  12. import {
  13. Message
  14. } from '@phosphor/messaging';
  15. import {
  16. Widget
  17. } from '@phosphor/widgets';
  18. import * as React from 'react';
  19. import {
  20. showErrorMessage, VDomModel, VDomRenderer
  21. } from '@jupyterlab/apputils';
  22. import '../style/index.css';
  23. /**
  24. * The class name added to Launcher instances.
  25. */
  26. const LAUNCHER_CLASS = 'jp-Launcher';
  27. /**
  28. * The known categories of launcher items and their default ordering.
  29. */
  30. const KNOWN_CATEGORIES = ['Notebook', 'Console', 'Other'];
  31. /**
  32. * These laucher item categories are known to have kernels, so the kernel icons
  33. * are used.
  34. */
  35. const KERNEL_CATEGORIES = ['Notebook', 'Console'];
  36. /**
  37. * The command IDs used by the launcher plugin.
  38. */
  39. export
  40. namespace CommandIDs {
  41. export
  42. const show: string = 'launcher:show';
  43. }
  44. /* tslint:disable */
  45. /**
  46. * The launcher token.
  47. */
  48. export
  49. const ILauncher = new Token<ILauncher>('@jupyterlab/launcher:ILauncher');
  50. /* tslint:enable */
  51. /**
  52. * The launcher interface.
  53. */
  54. export
  55. interface ILauncher {
  56. /**
  57. * Add a command item to the launcher, and trigger re-render event for parent
  58. * widget.
  59. *
  60. * @param options - The specification options for a launcher item.
  61. *
  62. * @returns A disposable that will remove the item from Launcher, and trigger
  63. * re-render event for parent widget.
  64. *
  65. */
  66. add(options: ILauncherItem): IDisposable;
  67. }
  68. /**
  69. * The specification for a launcher item.
  70. */
  71. export
  72. interface ILauncherItem {
  73. /**
  74. * The display name for the launcher item.
  75. */
  76. displayName: string;
  77. /**
  78. * The callback invoked to launch the item.
  79. *
  80. * The callback is invoked with a current working directory and the
  81. * name of the selected launcher item. When the function returns
  82. * the launcher will close.
  83. */
  84. callback: (cwd: string, name: string) => Widget | Promise<Widget>;
  85. /**
  86. * The icon class for the launcher item.
  87. *
  88. * #### Notes
  89. * This class name will be added to the icon node for the visual
  90. * representation of the launcher item.
  91. *
  92. * Multiple class names can be separated with white space.
  93. *
  94. * The default value is an empty string.
  95. */
  96. iconClass?: string;
  97. /**
  98. * The icon label for the launcher item.
  99. *
  100. * #### Notes
  101. * This label will be added as text to the icon node for the visual
  102. * representation of the launcher item.
  103. *
  104. * The default value is an empty string.
  105. */
  106. iconLabel?: string;
  107. /**
  108. * The identifier for the launcher item.
  109. *
  110. * The default value is the displayName.
  111. */
  112. name?: string;
  113. /**
  114. * The category for the launcher item.
  115. *
  116. * The default value is the an empty string.
  117. */
  118. category?: string;
  119. /**
  120. * The rank for the launcher item.
  121. *
  122. * The rank is used when ordering launcher items for display. After grouping
  123. * into categories, items are sorted in the following order:
  124. * 1. Rank (lower is better)
  125. * 3. Display Name (locale order)
  126. *
  127. * The default rank is `Infinity`.
  128. */
  129. rank?: number;
  130. /**
  131. * For items that have a kernel associated with them, the URL of the kernel
  132. * icon.
  133. *
  134. * This is not a CSS class, but the URL that points to the icon in the kernel
  135. * spec.
  136. */
  137. kernelIconUrl?: string;
  138. }
  139. /**
  140. * LauncherModel keeps track of the path to working directory and has a list of
  141. * LauncherItems, which the Launcher will render.
  142. */
  143. export
  144. class LauncherModel extends VDomModel implements ILauncher {
  145. /**
  146. * Create a new launcher model.
  147. */
  148. constructor() {
  149. super();
  150. }
  151. /**
  152. * Add a command item to the launcher, and trigger re-render event for parent
  153. * widget.
  154. *
  155. * @param options - The specification options for a launcher item.
  156. *
  157. * @returns A disposable that will remove the item from Launcher, and trigger
  158. * re-render event for parent widget.
  159. *
  160. */
  161. add(options: ILauncherItem): IDisposable {
  162. // Create a copy of the options to circumvent mutations to the original.
  163. let item = Private.createItem(options);
  164. this._items.push(item);
  165. this.stateChanged.emit(void 0);
  166. return new DisposableDelegate(() => {
  167. ArrayExt.removeFirstOf(this._items, item);
  168. this.stateChanged.emit(void 0);
  169. });
  170. }
  171. /**
  172. * Return an iterator of launcher items.
  173. */
  174. items(): IIterator<ILauncherItem> {
  175. return new ArrayIterator(this._items);
  176. }
  177. private _items: ILauncherItem[] = [];
  178. }
  179. /**
  180. * A virtual-DOM-based widget for the Launcher.
  181. */
  182. export
  183. class Launcher extends VDomRenderer<LauncherModel> {
  184. /**
  185. * Construct a new launcher widget.
  186. */
  187. constructor(options: Launcher.IOptions) {
  188. super();
  189. this._cwd = options.cwd;
  190. this._callback = options.callback;
  191. this.addClass(LAUNCHER_CLASS);
  192. }
  193. /**
  194. * The cwd of the launcher.
  195. */
  196. get cwd(): string {
  197. return this._cwd;
  198. }
  199. set cwd(value: string) {
  200. this._cwd = value;
  201. this.update();
  202. }
  203. /**
  204. * Whether there is a pending item being launched.
  205. */
  206. get pending(): boolean {
  207. return this._pending;
  208. }
  209. set pending(value: boolean) {
  210. this._pending = value;
  211. }
  212. /**
  213. * Handle `'activate-request'` messages.
  214. */
  215. protected onActivateRequest(msg: Message): void {
  216. this.node.tabIndex = -1;
  217. this.node.focus();
  218. }
  219. /**
  220. * Render the launcher to virtual DOM nodes.
  221. */
  222. protected render(): React.ReactElement<any> {
  223. // Bail if there is no model.
  224. if (!this.model) {
  225. return null;
  226. }
  227. // Ensure unique entries.
  228. let keys = new Set();
  229. // First group-by categories
  230. let categories = Object.create(null);
  231. each(this.model.items(), (item, index) => {
  232. let cat = item.category || 'Other';
  233. let key = JSON.stringify(item, Object.keys(item).sort());
  234. if (keys.has(key)) {
  235. return;
  236. }
  237. keys.add(key);
  238. if (!(cat in categories)) {
  239. categories[cat] = [];
  240. }
  241. categories[cat].push(item);
  242. });
  243. // Within each category sort by rank
  244. for (let cat in categories) {
  245. categories[cat] = categories[cat].sort(Private.sortCmp);
  246. }
  247. // Variable to help create sections
  248. let sections: React.ReactElement<any>[] = [];
  249. let section: React.ReactElement<any>;
  250. // Assemble the final ordered list of categories, beginning with
  251. // KNOWN_CATEGORIES.
  252. let orderedCategories: string[] = [];
  253. each(KNOWN_CATEGORIES, (cat, index) => {
  254. orderedCategories.push(cat);
  255. });
  256. for (let cat in categories) {
  257. if (KNOWN_CATEGORIES.indexOf(cat) === -1) {
  258. orderedCategories.push(cat);
  259. }
  260. }
  261. // Now create the sections for each category
  262. each(orderedCategories, cat => {
  263. let iconClass = `${(categories[cat][0] as ILauncherItem).iconClass} ` +
  264. 'jp-Launcher-sectionIcon jp-Launcher-icon';
  265. let kernel = KERNEL_CATEGORIES.indexOf(cat) > -1;
  266. if (cat in categories) {
  267. section = (
  268. <div className='jp-Launcher-section' key={cat}>
  269. <div className='jp-Launcher-sectionHeader'>
  270. {kernel && <div className={iconClass} />}
  271. <h2 className='jp-Launcher-sectionTitle'>{cat}</h2>
  272. </div>
  273. <div className='jp-Launcher-cardContainer'>
  274. {toArray(map(categories[cat], (item: ILauncherItem) => {
  275. return Card(kernel, item, this, this._callback);
  276. }))}
  277. </div>
  278. </div>
  279. );
  280. sections.push(section);
  281. }
  282. });
  283. // Wrap the sections in body and content divs.
  284. return (
  285. <div className='jp-Launcher-body'>
  286. <div className='jp-Launcher-content'>
  287. <div className='jp-Launcher-cwd'>
  288. <h3>{this.cwd}</h3>
  289. </div>
  290. {sections}
  291. </div>
  292. </div>
  293. );
  294. }
  295. private _callback: (widget: Widget) => void;
  296. private _pending = false;
  297. private _cwd = '';
  298. }
  299. /**
  300. * The namespace for `Launcher` class statics.
  301. */
  302. export
  303. namespace Launcher {
  304. /**
  305. * The options used to create a Launcher.
  306. */
  307. export
  308. interface IOptions {
  309. /**
  310. * The cwd of the launcher.
  311. */
  312. cwd: string;
  313. /**
  314. * The callback used when an item is launched.
  315. */
  316. callback: (widget: Widget) => void;
  317. }
  318. }
  319. /**
  320. * A pure tsx component for a launcher card.
  321. *
  322. * @param kernel - whether the item takes uses a kernel.
  323. *
  324. * @param item - the launcher item to render.
  325. *
  326. * @param launcher - the Launcher instance to which this is added.
  327. *
  328. * @param launcherCallback - a callback to call after an item has been launched.
  329. *
  330. * @param index - The index of the card.
  331. *
  332. * @returns a vdom `VirtualElement` for the launcher card.
  333. */
  334. function Card(kernel: boolean, item: ILauncherItem, launcher: Launcher, launcherCallback: (widget: Widget) => void): React.ReactElement<any> {
  335. // Build the onclick handler.
  336. let onclick = () => {
  337. // If an item has already been launched,
  338. // don't try to launch another.
  339. if (launcher.pending === true) {
  340. return;
  341. }
  342. launcher.pending = true;
  343. let callback = item.callback as any;
  344. let value = callback(launcher.cwd, item.name);
  345. Promise.resolve(value).then(widget => {
  346. launcherCallback(widget);
  347. launcher.dispose();
  348. }).catch(err => {
  349. launcher.pending = false;
  350. showErrorMessage('Launcher Error', err);
  351. });
  352. };
  353. let key = JSON.stringify(item, Object.keys(item).sort());
  354. // Return the VDOM element.
  355. return (
  356. <div className='jp-LauncherCard'
  357. title={item.displayName}
  358. onClick={onclick}
  359. data-category={item.category || 'Other'}
  360. key={key}>
  361. <div className='jp-LauncherCard-icon'>
  362. {(item.kernelIconUrl && kernel) &&
  363. <img src={item.kernelIconUrl} className='jp-Launcher-kernelIcon' />}
  364. {(!item.kernelIconUrl && !kernel) &&
  365. <div className={`${item.iconClass} jp-Launcher-icon`} />}
  366. {(!item.kernelIconUrl && kernel) &&
  367. <div className='jp-LauncherCard-noKernelIcon'>
  368. {item.displayName[0].toUpperCase()}
  369. </div>}
  370. </div>
  371. <div className='jp-LauncherCard-label' title={item.displayName}>
  372. {item.displayName}
  373. </div>
  374. </div>
  375. );
  376. }
  377. /**
  378. * The namespace for module private data.
  379. */
  380. namespace Private {
  381. /**
  382. * Create an item given item options.
  383. */
  384. export
  385. function createItem(options: ILauncherItem): ILauncherItem {
  386. return {
  387. ...options,
  388. category: options.category || '',
  389. name: options.name || options.name,
  390. iconClass: options.iconClass || '',
  391. iconLabel: options.iconLabel || '',
  392. rank: options.rank !== undefined ? options.rank : Infinity
  393. };
  394. }
  395. /**
  396. * A sort comparison function for a launcher item.
  397. */
  398. export
  399. function sortCmp(a: ILauncherItem, b: ILauncherItem): number {
  400. // First, compare by rank.
  401. let r1 = a.rank;
  402. let r2 = b.rank;
  403. if (r1 !== r2 && r1 !== undefined && r2 !== undefined) {
  404. return r1 < r2 ? -1 : 1; // Infinity safe
  405. }
  406. // Finally, compare by display name.
  407. return a.displayName.localeCompare(b.displayName);
  408. }
  409. }