celltools.ts 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744
  1. // Copyright (c) Jupyter Development Team.
  2. // Distributed under the terms of the Modified BSD License.
  3. import {
  4. ArrayExt, each
  5. } from '@phosphor/algorithm';
  6. import {
  7. JSONObject, JSONValue, Token
  8. } from '@phosphor/coreutils';
  9. import {
  10. ConflatableMessage, Message, MessageLoop
  11. } from '@phosphor/messaging';
  12. import {
  13. h, VirtualDOM, VirtualNode
  14. } from '@phosphor/virtualdom';
  15. import {
  16. PanelLayout, Widget
  17. } from '@phosphor/widgets';
  18. import {
  19. Styling
  20. } from '@jupyterlab/apputils';
  21. import {
  22. Cell, ICellModel
  23. } from '@jupyterlab/cells';
  24. import {
  25. CodeEditor, CodeEditorWrapper, JSONEditor
  26. } from '@jupyterlab/codeeditor';
  27. import {
  28. nbformat
  29. } from '@jupyterlab/coreutils';
  30. import {
  31. IObservableMap, ObservableJSON
  32. } from '@jupyterlab/observables';
  33. import {
  34. INotebookTracker
  35. } from './';
  36. /**
  37. * The class name added to a CellTools instance.
  38. */
  39. const CELLTOOLS_CLASS = 'jp-CellTools';
  40. /**
  41. * The class name added to a CellTools tool.
  42. */
  43. const CHILD_CLASS = 'jp-CellTools-tool';
  44. /**
  45. * The class name added to a CellTools active cell.
  46. */
  47. const ACTIVE_CELL_CLASS = 'jp-ActiveCellTool';
  48. /**
  49. * The class name added to an Editor instance.
  50. */
  51. const EDITOR_CLASS = 'jp-MetadataEditorTool';
  52. /**
  53. * The class name added to a KeySelector instance.
  54. */
  55. const KEYSELECTOR_CLASS = 'jp-KeySelector';
  56. /* tslint:disable */
  57. /**
  58. * The main menu token.
  59. */
  60. export
  61. const ICellTools = new Token<ICellTools>('@jupyterlab/notebook:ICellTools');
  62. /* tslint:enable */
  63. /**
  64. * The interface for cell metadata tools.
  65. */
  66. export
  67. interface ICellTools extends CellTools {}
  68. /**
  69. * A widget that provides cell metadata tools.
  70. */
  71. export
  72. class CellTools extends Widget {
  73. /**
  74. * Construct a new CellTools object.
  75. */
  76. constructor(options: CellTools.IOptions) {
  77. super();
  78. this.addClass(CELLTOOLS_CLASS);
  79. this.layout = new PanelLayout();
  80. this._tracker = options.tracker;
  81. this._tracker.activeCellChanged.connect(this._onActiveCellChanged, this);
  82. this._tracker.selectionChanged.connect(this._onSelectionChanged, this);
  83. this._onActiveCellChanged();
  84. this._onSelectionChanged();
  85. }
  86. /**
  87. * The active cell widget.
  88. */
  89. get activeCell(): Cell | null {
  90. return this._tracker.activeCell;
  91. }
  92. /**
  93. * The currently selected cells.
  94. */
  95. get selectedCells(): Cell[] {
  96. let selected: Cell[] = [];
  97. let panel = this._tracker.currentWidget;
  98. if (!panel) {
  99. return selected;
  100. }
  101. each(panel.notebook.widgets, widget => {
  102. if (panel.notebook.isSelectedOrActive(widget)) {
  103. selected.push(widget);
  104. }
  105. });
  106. return selected;
  107. }
  108. /**
  109. * Add a cell tool item.
  110. */
  111. addItem(options: CellTools.IAddOptions): void {
  112. let tool = options.tool;
  113. let rank = 'rank' in options ? options.rank : 100;
  114. let rankItem = { tool, rank };
  115. let index = ArrayExt.upperBound(this._items, rankItem, Private.itemCmp);
  116. tool.addClass(CHILD_CLASS);
  117. // Add the tool.
  118. ArrayExt.insert(this._items, index, rankItem);
  119. let layout = this.layout as PanelLayout;
  120. layout.insertWidget(index, tool);
  121. // Trigger the tool to update its active cell.
  122. MessageLoop.sendMessage(tool, CellTools.ActiveCellMessage);
  123. }
  124. /**
  125. * Handle the removal of a child
  126. */
  127. protected onChildRemoved(msg: Widget.ChildMessage): void {
  128. let index = ArrayExt.findFirstIndex(this._items, item => item.tool === msg.child);
  129. if (index !== -1) {
  130. ArrayExt.removeAt(this._items, index);
  131. }
  132. }
  133. /**
  134. * Handle a change to the active cell.
  135. */
  136. private _onActiveCellChanged(): void {
  137. if (this._prevActive && !this._prevActive.isDisposed) {
  138. this._prevActive.metadata.changed.disconnect(this._onMetadataChanged, this);
  139. }
  140. let activeCell = this._tracker.activeCell;
  141. this._prevActive = activeCell ? activeCell.model : null;
  142. if (activeCell) {
  143. activeCell.model.metadata.changed.connect(this._onMetadataChanged, this);
  144. }
  145. each(this.children(), widget => {
  146. MessageLoop.sendMessage(widget, CellTools.ActiveCellMessage);
  147. });
  148. }
  149. /**
  150. * Handle a change in the selection.
  151. */
  152. private _onSelectionChanged(): void {
  153. each(this.children(), widget => {
  154. MessageLoop.sendMessage(widget, CellTools.SelectionMessage);
  155. });
  156. }
  157. /**
  158. * Handle a change in the metadata.
  159. */
  160. private _onMetadataChanged(sender: IObservableMap<JSONValue>, args: IObservableMap.IChangedArgs<JSONValue>): void {
  161. let message = new ObservableJSON.ChangeMessage(args);
  162. each(this.children(), widget => {
  163. MessageLoop.sendMessage(widget, message);
  164. });
  165. }
  166. private _items: Private.IRankItem[] = [];
  167. private _tracker: INotebookTracker;
  168. private _prevActive: ICellModel | null;
  169. }
  170. /**
  171. * The namespace for CellTools class statics.
  172. */
  173. export
  174. namespace CellTools {
  175. /**
  176. * The options used to create a CellTools object.
  177. */
  178. export
  179. interface IOptions {
  180. /**
  181. * The notebook tracker used by the cell tools.
  182. */
  183. tracker: INotebookTracker;
  184. }
  185. /**
  186. * The options used to add an item to the cell tools.
  187. */
  188. export
  189. interface IAddOptions {
  190. /**
  191. * The tool to add to the cell tools area.
  192. */
  193. tool: Tool;
  194. /**
  195. * The rank order of the widget among its siblings.
  196. */
  197. rank?: number;
  198. }
  199. /**
  200. * A singleton conflatable `'activecell-changed'` message.
  201. */
  202. export
  203. // tslint:disable-next-line
  204. const ActiveCellMessage = new ConflatableMessage('activecell-changed');
  205. /**
  206. * A singleton conflatable `'selection-changed'` message.
  207. */
  208. export
  209. // tslint:disable-next-line
  210. const SelectionMessage = new ConflatableMessage('selection-changed');
  211. /**
  212. * The base cell tool, meant to be subclassed.
  213. */
  214. export
  215. class Tool extends Widget {
  216. /**
  217. * The cell tools object.
  218. */
  219. readonly parent: ICellTools;
  220. /**
  221. * Process a message sent to the widget.
  222. *
  223. * @param msg - The message sent to the widget.
  224. */
  225. processMessage(msg: Message): void {
  226. super.processMessage(msg);
  227. switch (msg.type) {
  228. case 'activecell-changed':
  229. this.onActiveCellChanged(msg);
  230. break;
  231. case 'selection-changed':
  232. this.onSelectionChanged(msg);
  233. break;
  234. case 'jsonvalue-changed':
  235. this.onMetadataChanged(msg as ObservableJSON.ChangeMessage);
  236. break;
  237. default:
  238. break;
  239. }
  240. }
  241. /**
  242. * Handle a change to the active cell.
  243. *
  244. * #### Notes
  245. * The default implemenatation is a no-op.
  246. */
  247. protected onActiveCellChanged(msg: Message): void { /* no-op */ }
  248. /**
  249. * Handle a change to the selection.
  250. *
  251. * #### Notes
  252. * The default implementation is a no-op.
  253. */
  254. protected onSelectionChanged(msg: Message): void { /* no-op */ }
  255. /**
  256. * Handle a change to the metadata of the active cell.
  257. *
  258. * #### Notes
  259. * The default implementation is a no-op.
  260. */
  261. protected onMetadataChanged(msg: ObservableJSON.ChangeMessage): void { /* no-op */ }
  262. }
  263. /**
  264. * A cell tool displaying the active cell contents.
  265. */
  266. export
  267. class ActiveCellTool extends Tool {
  268. /**
  269. * Construct a new active cell tool.
  270. */
  271. constructor() {
  272. super();
  273. this.addClass(ACTIVE_CELL_CLASS);
  274. this.addClass('jp-InputArea');
  275. this.layout = new PanelLayout();
  276. }
  277. /**
  278. * Dispose of the resources used by the tool.
  279. */
  280. dispose() {
  281. if (this._model === null) {
  282. return;
  283. }
  284. this._model.dispose();
  285. this._model = null;
  286. super.dispose();
  287. }
  288. /**
  289. * Handle a change to the active cell.
  290. */
  291. protected onActiveCellChanged(): void {
  292. let activeCell = this.parent.activeCell;
  293. let layout = this.layout as PanelLayout;
  294. let count = layout.widgets.length;
  295. for (let i = 0; i < count; i++) {
  296. layout.widgets[0].dispose();
  297. }
  298. if (this._cellModel && !this._cellModel.isDisposed) {
  299. this._cellModel.value.changed.disconnect(this._onValueChanged, this);
  300. this._cellModel.mimeTypeChanged.disconnect(this._onMimeTypeChanged, this);
  301. }
  302. if (!activeCell) {
  303. let cell = new Widget();
  304. cell.addClass('jp-InputArea-editor');
  305. cell.addClass('jp-InputArea-editor');
  306. layout.addWidget(cell);
  307. this._cellModel = null;
  308. return;
  309. }
  310. let promptNode = activeCell.promptNode.cloneNode(true) as HTMLElement;
  311. let prompt = new Widget({ node: promptNode });
  312. let factory = activeCell.contentFactory.editorFactory;
  313. let cellModel = this._cellModel = activeCell.model;
  314. cellModel.value.changed.connect(this._onValueChanged, this);
  315. cellModel.mimeTypeChanged.connect(this._onMimeTypeChanged, this);
  316. this._model.value.text = cellModel.value.text.split('\n')[0];
  317. this._model.mimeType = cellModel.mimeType;
  318. let model = this._model;
  319. let editorWidget = new CodeEditorWrapper({ model, factory });
  320. editorWidget.addClass('jp-InputArea-editor');
  321. editorWidget.addClass('jp-InputArea-editor');
  322. editorWidget.editor.setOption('readOnly', true);
  323. layout.addWidget(prompt);
  324. layout.addWidget(editorWidget);
  325. }
  326. /**
  327. * Handle a change to the current editor value.
  328. */
  329. private _onValueChanged(): void {
  330. this._model.value.text = this._cellModel.value.text.split('\n')[0];
  331. }
  332. /**
  333. * Handle a change to the current editor mimetype.
  334. */
  335. private _onMimeTypeChanged(): void {
  336. this._model.mimeType = this._cellModel.mimeType;
  337. }
  338. private _model = new CodeEditor.Model();
  339. private _cellModel: CodeEditor.IModel;
  340. }
  341. /**
  342. * A raw metadata editor.
  343. */
  344. export
  345. class MetadataEditorTool extends Tool {
  346. /**
  347. * Construct a new raw metadata tool.
  348. */
  349. constructor(options: MetadataEditorTool.IOptions) {
  350. super();
  351. let editorFactory = options.editorFactory;
  352. this.addClass(EDITOR_CLASS);
  353. let layout = this.layout = new PanelLayout();
  354. this.editor = new JSONEditor({
  355. editorFactory,
  356. title: 'Edit Metadata',
  357. collapsible: true
  358. });
  359. layout.addWidget(this.editor);
  360. }
  361. /**
  362. * The editor used by the tool.
  363. */
  364. readonly editor: JSONEditor;
  365. /**
  366. * Handle a change to the active cell.
  367. */
  368. protected onActiveCellChanged(msg: Message): void {
  369. let cell = this.parent.activeCell;
  370. this.editor.source = cell ? cell.model.metadata : null;
  371. }
  372. }
  373. /**
  374. * The namespace for `MetadataEditorTool` static data.
  375. */
  376. export
  377. namespace MetadataEditorTool {
  378. /**
  379. * The options used to initialize a metadata editor tool.
  380. */
  381. export
  382. interface IOptions {
  383. /**
  384. * The editor factory used by the tool.
  385. */
  386. editorFactory: CodeEditor.Factory;
  387. }
  388. }
  389. /**
  390. * A cell tool that provides a selection for a given metadata key.
  391. */
  392. export
  393. class KeySelector extends Tool {
  394. /**
  395. * Construct a new KeySelector.
  396. */
  397. constructor(options: KeySelector.IOptions) {
  398. super({ node: Private.createSelectorNode(options) });
  399. this.addClass(KEYSELECTOR_CLASS);
  400. this.key = options.key;
  401. this._validCellTypes = options.validCellTypes || [];
  402. this._getter = options.getter || this._getValue;
  403. this._setter = options.setter || this._setValue;
  404. }
  405. /**
  406. * The metadata key used by the selector.
  407. */
  408. readonly key: string;
  409. /**
  410. * The select node for the widget.
  411. */
  412. get selectNode(): HTMLSelectElement {
  413. return this.node.getElementsByTagName('select')[0] as HTMLSelectElement;
  414. }
  415. /**
  416. * Handle the DOM events for the widget.
  417. *
  418. * @param event - The DOM event sent to the widget.
  419. *
  420. * #### Notes
  421. * This method implements the DOM `EventListener` interface and is
  422. * called in response to events on the notebook panel's node. It should
  423. * not be called directly by user code.
  424. */
  425. handleEvent(event: Event): void {
  426. switch (event.type) {
  427. case 'change':
  428. this.onValueChanged();
  429. break;
  430. default:
  431. break;
  432. }
  433. }
  434. /**
  435. * Handle `after-attach` messages for the widget.
  436. */
  437. protected onAfterAttach(msg: Message): void {
  438. let node = this.selectNode;
  439. node.addEventListener('change', this);
  440. }
  441. /**
  442. * Handle `before-detach` messages for the widget.
  443. */
  444. protected onBeforeDetach(msg: Message): void {
  445. let node = this.selectNode;
  446. node.removeEventListener('change', this);
  447. }
  448. /**
  449. * Handle a change to the active cell.
  450. */
  451. protected onActiveCellChanged(msg: Message): void {
  452. let select = this.selectNode;
  453. let activeCell = this.parent.activeCell;
  454. if (!activeCell) {
  455. select.disabled = true;
  456. select.value = '';
  457. return;
  458. }
  459. let cellType = activeCell.model.type;
  460. if (this._validCellTypes.length &&
  461. this._validCellTypes.indexOf(cellType) === -1) {
  462. select.disabled = true;
  463. return;
  464. }
  465. select.disabled = false;
  466. this._changeGuard = true;
  467. let getter = this._getter;
  468. select.value = JSON.stringify(getter(activeCell));
  469. this._changeGuard = false;
  470. }
  471. /**
  472. * Handle a change to the metadata of the active cell.
  473. */
  474. protected onMetadataChanged(msg: ObservableJSON.ChangeMessage) {
  475. if (this._changeGuard) {
  476. return;
  477. }
  478. let select = this.selectNode;
  479. let cell = this.parent.activeCell;
  480. if (msg.args.key === this.key && cell) {
  481. this._changeGuard = true;
  482. let getter = this._getter;
  483. select.value = JSON.stringify(getter(cell));
  484. this._changeGuard = false;
  485. }
  486. }
  487. /**
  488. * Handle a change to the value.
  489. */
  490. protected onValueChanged(): void {
  491. let activeCell = this.parent.activeCell;
  492. if (!activeCell || this._changeGuard) {
  493. return;
  494. }
  495. this._changeGuard = true;
  496. let select = this.selectNode;
  497. let setter = this._setter;
  498. setter(activeCell, JSON.parse(select.value));
  499. this._changeGuard = false;
  500. }
  501. /**
  502. * Get the value for the data.
  503. */
  504. private _getValue = (cell: Cell) => {
  505. return cell.model.metadata.get(this.key);
  506. }
  507. /**
  508. * Set the value for the data.
  509. */
  510. private _setValue = (cell: Cell, value: JSONValue) => {
  511. cell.model.metadata.set(this.key, value);
  512. }
  513. private _changeGuard = false;
  514. private _validCellTypes: string[];
  515. private _getter: (cell: Cell) => JSONValue;
  516. private _setter: (cell: Cell, value: JSONValue) => void;
  517. }
  518. /**
  519. * The namespace for `KeySelector` static data.
  520. */
  521. export
  522. namespace KeySelector {
  523. /**
  524. * The options used to initialize a keyselector.
  525. */
  526. export
  527. interface IOptions {
  528. /**
  529. * The metadata key of interest.
  530. */
  531. key: string;
  532. /**
  533. * The map of options to values.
  534. */
  535. optionsMap: { [key: string]: JSONValue };
  536. /**
  537. * The optional title of the selector - defaults to capitalized `key`.
  538. */
  539. title?: string;
  540. /**
  541. * The optional valid cell types - defaults to all valid types.
  542. */
  543. validCellTypes?: nbformat.CellType[];
  544. /**
  545. * An optional value getter for the selector.
  546. *
  547. * @param cell - The currently active cell.
  548. *
  549. * @returns The appropriate value for the selector.
  550. */
  551. getter?: (cell: Cell) => JSONValue;
  552. /**
  553. * An optional value setter for the selector.
  554. *
  555. * @param cell - The currently active cell.
  556. *
  557. * @param value - The value of the selector.
  558. *
  559. * #### Notes
  560. * The setter should set the appropriate metadata value
  561. * given the value of the selector.
  562. */
  563. setter?: (cell: Cell, value: JSONValue) => void;
  564. }
  565. }
  566. /**
  567. * Create a slideshow selector.
  568. */
  569. export
  570. function createSlideShowSelector(): KeySelector {
  571. let options: KeySelector.IOptions = {
  572. key: 'slideshow',
  573. title: 'Slide Type',
  574. optionsMap: {
  575. '-': '-',
  576. 'Slide': 'slide',
  577. 'Sub-Slide': 'subslide',
  578. 'Fragment': 'fragment',
  579. 'Skip': 'skip',
  580. 'Notes': 'notes'
  581. },
  582. getter: cell => {
  583. let value = cell.model.metadata.get('slideshow');
  584. return value && (value as JSONObject)['slide_type'];
  585. },
  586. setter: (cell, value) => {
  587. let data = cell.model.metadata.get('slideshow') || Object.create(null);
  588. data = { ...data, 'slide_type': value };
  589. cell.model.metadata.set('slideshow', data);
  590. }
  591. };
  592. return new KeySelector(options);
  593. }
  594. /**
  595. * Create an nbcovert selector.
  596. */
  597. export
  598. function createNBConvertSelector(): KeySelector {
  599. return new KeySelector({
  600. key: 'raw_mimetype',
  601. title: 'Raw NBConvert Format',
  602. optionsMap: {
  603. 'None': '-',
  604. 'LaTeX': 'text/latex',
  605. 'reST': 'text/restructuredtext',
  606. 'HTML': 'text/html',
  607. 'Markdown': 'text/markdown',
  608. 'Python': 'text/x-python'
  609. },
  610. validCellTypes: ['raw']
  611. });
  612. }
  613. }
  614. /**
  615. * A namespace for private data.
  616. */
  617. namespace Private {
  618. /**
  619. * An object which holds a widget and its sort rank.
  620. */
  621. export
  622. interface IRankItem {
  623. /**
  624. * The widget for the item.
  625. */
  626. tool: CellTools.Tool;
  627. /**
  628. * The sort rank of the menu.
  629. */
  630. rank: number;
  631. }
  632. /**
  633. * A comparator function for widget rank items.
  634. */
  635. export
  636. function itemCmp(first: IRankItem, second: IRankItem): number {
  637. return first.rank - second.rank;
  638. }
  639. /**
  640. * Create the node for a KeySelector.
  641. */
  642. export
  643. function createSelectorNode(options: CellTools.KeySelector.IOptions): HTMLElement {
  644. let name = options.key;
  645. let title = (
  646. options.title || name[0].toLocaleUpperCase() + name.slice(1)
  647. );
  648. let optionNodes: VirtualNode[] = [];
  649. for (let label in options.optionsMap) {
  650. let value = JSON.stringify(options.optionsMap[label]);
  651. optionNodes.push(h.option({ value }, label));
  652. }
  653. let node = VirtualDOM.realize(
  654. h.div({},
  655. h.label(title),
  656. h.select({}, optionNodes))
  657. );
  658. Styling.styleNode(node);
  659. return node;
  660. }
  661. }