celltools.ts 18 KB

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