widget.ts 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861
  1. // Copyright (c) Jupyter Development Team.
  2. // Distributed under the terms of the Modified BSD License.
  3. import {
  4. IClientSession
  5. } from '@jupyterlab/apputils';
  6. import {
  7. Cell, CellModel, CodeCell, CodeCellModel, ICodeCellModel, IRawCellModel,
  8. RawCell, RawCellModel
  9. } from '@jupyterlab/cells';
  10. import {
  11. IEditorMimeTypeService, CodeEditor
  12. } from '@jupyterlab/codeeditor';
  13. import {
  14. nbformat
  15. } from '@jupyterlab/coreutils';
  16. import {
  17. IObservableList, ObservableList
  18. } from '@jupyterlab/observables';
  19. import {
  20. RenderMimeRegistry
  21. } from '@jupyterlab/rendermime';
  22. import {
  23. KernelMessage
  24. } from '@jupyterlab/services';
  25. import {
  26. map, toArray
  27. } from '@phosphor/algorithm';
  28. import {
  29. Message
  30. } from '@phosphor/messaging';
  31. import {
  32. ISignal, Signal
  33. } from '@phosphor/signaling';
  34. import {
  35. Panel, PanelLayout, Widget
  36. } from '@phosphor/widgets';
  37. import {
  38. ForeignHandler
  39. } from './foreign';
  40. import {
  41. ConsoleHistory, IConsoleHistory
  42. } from './history';
  43. /**
  44. * The data attribute added to a widget that has an active kernel.
  45. */
  46. const KERNEL_USER = 'jpKernelUser';
  47. /**
  48. * The data attribute added to a widget can run code.
  49. */
  50. const CODE_RUNNER = 'jpCodeRunner';
  51. /**
  52. * The class name added to console widgets.
  53. */
  54. const CONSOLE_CLASS = 'jp-CodeConsole';
  55. /**
  56. * The class name added to the console banner.
  57. */
  58. const BANNER_CLASS = 'jp-CodeConsole-banner';
  59. /**
  60. * The class name of a cell whose input originated from a foreign session.
  61. */
  62. const FOREIGN_CELL_CLASS = 'jp-CodeConsole-foreignCell';
  63. /**
  64. * The class name of the active prompt cell.
  65. */
  66. const PROMPT_CLASS = 'jp-CodeConsole-promptCell';
  67. /**
  68. * The class name of the panel that holds cell content.
  69. */
  70. const CONTENT_CLASS = 'jp-CodeConsole-content';
  71. /**
  72. * The class name of the panel that holds prompts.
  73. */
  74. const INPUT_CLASS = 'jp-CodeConsole-input';
  75. /**
  76. * The timeout in ms for execution requests to the kernel.
  77. */
  78. const EXECUTION_TIMEOUT = 250;
  79. /**
  80. * A widget containing a Jupyter console.
  81. *
  82. * #### Notes
  83. * The CodeConsole class is intended to be used within a ConsolePanel
  84. * instance. Under most circumstances, it is not instantiated by user code.
  85. */
  86. export
  87. class CodeConsole extends Widget {
  88. /**
  89. * Construct a console widget.
  90. */
  91. constructor(options: CodeConsole.IOptions) {
  92. super();
  93. this.addClass(CONSOLE_CLASS);
  94. this.node.dataset[KERNEL_USER] = 'true';
  95. this.node.dataset[CODE_RUNNER] = 'true';
  96. this.node.tabIndex = -1; // Allow the widget to take focus.
  97. // Create the panels that hold the content and input.
  98. let layout = this.layout = new PanelLayout();
  99. this._cells = new ObservableList<Cell>();
  100. this._content = new Panel();
  101. this._input = new Panel();
  102. let contentFactory = this.contentFactory = (
  103. options.contentFactory || CodeConsole.defaultContentFactory
  104. );
  105. let modelFactory = this.modelFactory = (
  106. options.modelFactory || CodeConsole.defaultModelFactory
  107. );
  108. this.rendermime = options.rendermime;
  109. this.session = options.session;
  110. this._mimeTypeService = options.mimeTypeService;
  111. // Add top-level CSS classes.
  112. this._content.addClass(CONTENT_CLASS);
  113. this._input.addClass(INPUT_CLASS);
  114. // Insert the content and input panes into the widget.
  115. layout.addWidget(this._content);
  116. layout.addWidget(this._input);
  117. // Create the banner.
  118. let model = modelFactory.createRawCell({});
  119. model.value.text = '...';
  120. let banner = this._banner = new RawCell({
  121. model,
  122. contentFactory: contentFactory
  123. });
  124. banner.addClass(BANNER_CLASS);
  125. banner.readOnly = true;
  126. this._content.addWidget(banner);
  127. // Set up the foreign iopub handler.
  128. this._foreignHandler = new ForeignHandler({
  129. session: this.session,
  130. parent: this,
  131. cellFactory: () => this._createCodeCell()
  132. });
  133. this._history = new ConsoleHistory({
  134. session: this.session
  135. });
  136. this._onKernelChanged();
  137. this.session.kernelChanged.connect(this._onKernelChanged, this);
  138. }
  139. /**
  140. * A signal emitted when the console finished executing its prompt cell.
  141. */
  142. get executed(): ISignal<this, Date> {
  143. return this._executed;
  144. }
  145. /**
  146. * A signal emitted when a new prompt cell is created.
  147. */
  148. get promptCellCreated(): ISignal<this, CodeCell> {
  149. return this._promptCellCreated;
  150. }
  151. /**
  152. * The content factory used by the console.
  153. */
  154. readonly contentFactory: CodeConsole.IContentFactory;
  155. /**
  156. * The model factory for the console widget.
  157. */
  158. readonly modelFactory: CodeConsole.IModelFactory;
  159. /**
  160. * The rendermime instance used by the console.
  161. */
  162. readonly rendermime: RenderMimeRegistry;
  163. /**
  164. * The client session used by the console.
  165. */
  166. readonly session: IClientSession;
  167. /**
  168. * The list of content cells in the console.
  169. *
  170. * #### Notes
  171. * This list does not include the banner or the prompt for a console.
  172. */
  173. get cells(): IObservableList<Cell> {
  174. return this._cells;
  175. }
  176. /*
  177. * The console input prompt cell.
  178. */
  179. get promptCell(): CodeCell | null {
  180. let inputLayout = (this._input.layout as PanelLayout);
  181. return inputLayout.widgets[0] as CodeCell || null;
  182. }
  183. /**
  184. * Add a new cell to the content panel.
  185. *
  186. * @param cell - The cell widget being added to the content panel.
  187. *
  188. * #### Notes
  189. * This method is meant for use by outside classes that want to inject content
  190. * into a console. It is distinct from the `inject` method in that it requires
  191. * rendered code cell widgets and does not execute them.
  192. */
  193. addCell(cell: Cell) {
  194. this._content.addWidget(cell);
  195. this._cells.push(cell);
  196. cell.disposed.connect(this._onCellDisposed, this);
  197. this.update();
  198. }
  199. /**
  200. * Clear the code cells.
  201. */
  202. clear(): void {
  203. // Dispose all the content cells except the first, which is the banner.
  204. let cells = this._content.widgets;
  205. while (cells.length > 1) {
  206. cells[1].dispose();
  207. }
  208. }
  209. /**
  210. * Dispose of the resources held by the widget.
  211. */
  212. dispose() {
  213. // Do nothing if already disposed.
  214. if (this.isDisposed) {
  215. return;
  216. }
  217. this._cells.clear();
  218. this._history.dispose();
  219. this._foreignHandler.dispose();
  220. super.dispose();
  221. }
  222. /**
  223. * Execute the current prompt.
  224. *
  225. * @param force - Whether to force execution without checking code
  226. * completeness.
  227. *
  228. * @param timeout - The length of time, in milliseconds, that the execution
  229. * should wait for the API to determine whether code being submitted is
  230. * incomplete before attempting submission anyway. The default value is `250`.
  231. */
  232. execute(force = false, timeout = EXECUTION_TIMEOUT): Promise<void> {
  233. if (this.session.status === 'dead') {
  234. return Promise.resolve(void 0);
  235. }
  236. const promptCell = this.promptCell;
  237. if (!promptCell) {
  238. return Promise.reject('Cannot execute without a prompt cell');
  239. }
  240. promptCell.model.trusted = true;
  241. if (force) {
  242. // Create a new prompt cell before kernel execution to allow typeahead.
  243. this.newPromptCell();
  244. return this._execute(promptCell);
  245. }
  246. // Check whether we should execute.
  247. return this._shouldExecute(timeout).then(should => {
  248. if (this.isDisposed) {
  249. return;
  250. }
  251. if (should) {
  252. // Create a new prompt cell before kernel execution to allow typeahead.
  253. this.newPromptCell();
  254. return this._execute(promptCell);
  255. }
  256. });
  257. }
  258. /**
  259. * Inject arbitrary code for the console to execute immediately.
  260. *
  261. * @param code - The code contents of the cell being injected.
  262. *
  263. * @returns A promise that indicates when the injected cell's execution ends.
  264. */
  265. inject(code: string): Promise<void> {
  266. let cell = this._createCodeCell();
  267. cell.model.value.text = code;
  268. this.addCell(cell);
  269. return this._execute(cell);
  270. }
  271. /**
  272. * Insert a line break in the prompt cell.
  273. */
  274. insertLinebreak(): void {
  275. let promptCell = this.promptCell;
  276. if (!promptCell) {
  277. return;
  278. }
  279. let model = promptCell.model;
  280. let editor = promptCell.editor;
  281. // Insert the line break at the cursor position, and move cursor forward.
  282. let pos = editor.getCursorPosition();
  283. let offset = editor.getOffsetAt(pos);
  284. let text = model.value.text;
  285. model.value.text = text.substr(0, offset) + '\n' + text.substr(offset);
  286. pos = editor.getPositionAt(offset + 1) as CodeEditor.IPosition;
  287. if (pos) {
  288. editor.setCursorPosition(pos);
  289. }
  290. }
  291. /**
  292. * Serialize the output.
  293. */
  294. serialize(): nbformat.ICodeCell[] {
  295. let promptCell = this.promptCell;
  296. let layout = this._content.layout as PanelLayout;
  297. // Serialize content.
  298. let output = map(layout.widgets, widget => {
  299. return (widget as CodeCell).model.toJSON() as nbformat.ICodeCell;
  300. });
  301. if (!promptCell) {
  302. return toArray(output);
  303. }
  304. // Serialize prompt cell and return.
  305. return toArray(output).concat(promptCell.model.toJSON() as nbformat.ICodeCell);
  306. }
  307. /**
  308. * Handle the DOM events for the widget.
  309. *
  310. * @param event - The DOM event sent to the widget.
  311. *
  312. * #### Notes
  313. * This method implements the DOM `EventListener` interface and is
  314. * called in response to events on the notebook panel's node. It should
  315. * not be called directly by user code.
  316. */
  317. handleEvent(event: Event): void {
  318. switch (event.type) {
  319. case 'keydown':
  320. this._evtKeyDown(event as KeyboardEvent);
  321. break;
  322. case 'onclick':
  323. this.node.focus();
  324. event.preventDefault();
  325. break;
  326. default:
  327. break;
  328. }
  329. }
  330. /**
  331. * Handle `after_attach` messages for the widget.
  332. */
  333. protected onAfterAttach(msg: Message): void {
  334. let node = this.node;
  335. node.addEventListener('keydown', this, true);
  336. node.addEventListener('click', this);
  337. // Create a prompt if necessary.
  338. if (!this.promptCell) {
  339. this.newPromptCell();
  340. } else {
  341. this.promptCell.editor.focus();
  342. this.update();
  343. }
  344. }
  345. /**
  346. * Handle `before-detach` messages for the widget.
  347. */
  348. protected onBeforeDetach(msg: Message): void {
  349. let node = this.node;
  350. node.removeEventListener('keydown', this, true);
  351. node.removeEventListener('click', this);
  352. }
  353. /**
  354. * Handle `'activate-request'` messages.
  355. */
  356. protected onActivateRequest(msg: Message): void {
  357. let editor = this.promptCell && this.promptCell.editor;
  358. if (editor) {
  359. editor.focus();
  360. }
  361. this.update();
  362. }
  363. /**
  364. * Make a new prompt cell.
  365. */
  366. protected newPromptCell(): void {
  367. let promptCell = this.promptCell;
  368. let input = this._input;
  369. // Make the last prompt read-only, clear its signals, and move to content.
  370. if (promptCell) {
  371. promptCell.readOnly = true;
  372. promptCell.removeClass(PROMPT_CLASS);
  373. Signal.clearData(promptCell.editor);
  374. let child = input.widgets[0];
  375. child.parent = null;
  376. this.addCell(promptCell);
  377. }
  378. // Create the new prompt cell.
  379. let factory = this.contentFactory;
  380. let options = this._createCodeCellOptions();
  381. promptCell = factory.createCodeCell(options);
  382. promptCell.model.mimeType = this._mimetype;
  383. promptCell.addClass(PROMPT_CLASS);
  384. this._input.addWidget(promptCell);
  385. // Suppress the default "Enter" key handling.
  386. let editor = promptCell.editor;
  387. editor.addKeydownHandler(this._onEditorKeydown);
  388. this._history.editor = editor;
  389. if (this.isAttached) {
  390. this.activate();
  391. }
  392. this._promptCellCreated.emit(promptCell);
  393. }
  394. /**
  395. * Handle `update-request` messages.
  396. */
  397. protected onUpdateRequest(msg: Message): void {
  398. Private.scrollToBottom(this._content.node);
  399. }
  400. /**
  401. * Handle the `'keydown'` event for the widget.
  402. */
  403. private _evtKeyDown(event: KeyboardEvent): void {
  404. let editor = this.promptCell && this.promptCell.editor;
  405. if (!editor) {
  406. return;
  407. }
  408. if (event.keyCode === 13 && !editor.hasFocus()) {
  409. event.preventDefault();
  410. editor.focus();
  411. }
  412. }
  413. /**
  414. * Execute the code in the current prompt cell.
  415. */
  416. private _execute(cell: CodeCell): Promise<void> {
  417. let source = cell.model.value.text;
  418. this._history.push(source);
  419. // If the source of the console is just "clear", clear the console as we
  420. // do in IPython or QtConsole.
  421. if ( source === 'clear' || source === '%clear' ) {
  422. this.clear();
  423. return Promise.resolve(void 0);
  424. }
  425. cell.model.contentChanged.connect(this.update, this);
  426. let onSuccess = (value: KernelMessage.IExecuteReplyMsg) => {
  427. if (this.isDisposed) {
  428. return;
  429. }
  430. if (value && value.content.status === 'ok') {
  431. let content = value.content as KernelMessage.IExecuteOkReply;
  432. // Use deprecated payloads for backwards compatibility.
  433. if (content.payload && content.payload.length) {
  434. let setNextInput = content.payload.filter(i => {
  435. return (i as any).source === 'set_next_input';
  436. })[0];
  437. if (setNextInput) {
  438. let text = (setNextInput as any).text;
  439. // Ignore the `replace` value and always set the next cell.
  440. cell.model.value.text = text;
  441. }
  442. }
  443. }
  444. cell.model.contentChanged.disconnect(this.update, this);
  445. this.update();
  446. this._executed.emit(new Date());
  447. };
  448. let onFailure = () => {
  449. if (this.isDisposed) {
  450. return;
  451. }
  452. cell.model.contentChanged.disconnect(this.update, this);
  453. this.update();
  454. };
  455. return CodeCell.execute(cell, this.session).then(onSuccess, onFailure);
  456. }
  457. /**
  458. * Update the console based on the kernel info.
  459. */
  460. private _handleInfo(info: KernelMessage.IInfoReply): void {
  461. let layout = this._content.layout as PanelLayout;
  462. let banner = layout.widgets[0] as RawCell;
  463. banner.model.value.text = info.banner;
  464. let lang = info.language_info as nbformat.ILanguageInfoMetadata;
  465. this._mimetype = this._mimeTypeService.getMimeTypeByLanguage(lang);
  466. if (this.promptCell) {
  467. this.promptCell.model.mimeType = this._mimetype;
  468. }
  469. }
  470. /**
  471. * Create a new foreign cell.
  472. */
  473. private _createCodeCell(): CodeCell {
  474. let factory = this.contentFactory;
  475. let options = this._createCodeCellOptions();
  476. let cell = factory.createCodeCell(options);
  477. cell.readOnly = true;
  478. cell.model.mimeType = this._mimetype;
  479. cell.addClass(FOREIGN_CELL_CLASS);
  480. return cell;
  481. }
  482. /**
  483. * Create the options used to initialize a code cell widget.
  484. */
  485. private _createCodeCellOptions(): CodeCell.IOptions {
  486. let contentFactory = this.contentFactory;
  487. let modelFactory = this.modelFactory;
  488. let model = modelFactory.createCodeCell({ });
  489. let rendermime = this.rendermime;
  490. return { model, rendermime, contentFactory };
  491. }
  492. /**
  493. * Handle cell disposed signals.
  494. */
  495. private _onCellDisposed(sender: Widget, args: void): void {
  496. if (!this.isDisposed) {
  497. this._cells.removeValue(sender as CodeCell);
  498. }
  499. }
  500. /**
  501. * Test whether we should execute the prompt cell.
  502. */
  503. private _shouldExecute(timeout: number): Promise<boolean> {
  504. const promptCell = this.promptCell;
  505. if (!promptCell) {
  506. return Promise.resolve(false);
  507. }
  508. let model = promptCell.model;
  509. let code = model.value.text + '\n';
  510. return new Promise<boolean>((resolve, reject) => {
  511. let timer = setTimeout(() => { resolve(true); }, timeout);
  512. let kernel = this.session.kernel;
  513. if (!kernel) {
  514. resolve(false);
  515. return;
  516. }
  517. kernel.requestIsComplete({ code }).then(isComplete => {
  518. clearTimeout(timer);
  519. if (this.isDisposed) {
  520. resolve(false);
  521. }
  522. if (isComplete.content.status !== 'incomplete') {
  523. resolve(true);
  524. return;
  525. }
  526. model.value.text = code + isComplete.content.indent;
  527. let editor = promptCell.editor;
  528. let pos = editor.getPositionAt(model.value.text.length);
  529. if (pos) {
  530. editor.setCursorPosition(pos);
  531. }
  532. resolve(false);
  533. }).catch(() => { resolve(true); });
  534. });
  535. }
  536. /**
  537. * Handle a keydown event on an editor.
  538. */
  539. private _onEditorKeydown(editor: CodeEditor.IEditor, event: KeyboardEvent) {
  540. // Suppress "Enter" events.
  541. return event.keyCode === 13;
  542. }
  543. /**
  544. * Handle a change to the kernel.
  545. */
  546. private _onKernelChanged(): void {
  547. this.clear();
  548. let kernel = this.session.kernel;
  549. if (!kernel) {
  550. return;
  551. }
  552. kernel.ready.then(() => {
  553. if (this.isDisposed || !kernel || !kernel.info) {
  554. return;
  555. }
  556. this._handleInfo(kernel.info);
  557. });
  558. }
  559. private _banner: RawCell;
  560. private _cells: IObservableList<Cell>;
  561. private _content: Panel;
  562. private _executed = new Signal<this, Date>(this);
  563. private _foreignHandler: ForeignHandler;
  564. private _history: IConsoleHistory ;
  565. private _input: Panel;
  566. private _mimetype = 'text/x-ipython';
  567. private _mimeTypeService: IEditorMimeTypeService;
  568. private _promptCellCreated = new Signal<this, CodeCell>(this);
  569. }
  570. /**
  571. * A namespace for CodeConsole statics.
  572. */
  573. export
  574. namespace CodeConsole {
  575. /**
  576. * The initialization options for a console widget.
  577. */
  578. export
  579. interface IOptions {
  580. /**
  581. * The content factory for the console widget.
  582. */
  583. contentFactory: IContentFactory;
  584. /**
  585. * The model factory for the console widget.
  586. */
  587. modelFactory?: IModelFactory;
  588. /**
  589. * The mime renderer for the console widget.
  590. */
  591. rendermime: RenderMimeRegistry;
  592. /**
  593. * The client session for the console widget.
  594. */
  595. session: IClientSession;
  596. /**
  597. * The service used to look up mime types.
  598. */
  599. mimeTypeService: IEditorMimeTypeService;
  600. }
  601. /**
  602. * A content factory for console children.
  603. */
  604. export
  605. interface IContentFactory extends Cell.IContentFactory {
  606. /**
  607. * Create a new code cell widget.
  608. */
  609. createCodeCell(options: CodeCell.IOptions): CodeCell;
  610. /**
  611. * Create a new raw cell widget.
  612. */
  613. createRawCell(options: RawCell.IOptions): RawCell;
  614. }
  615. /**
  616. * Default implementation of `IContentFactory`.
  617. */
  618. export
  619. class ContentFactory extends Cell.ContentFactory implements IContentFactory {
  620. /**
  621. * Create a new code cell widget.
  622. *
  623. * #### Notes
  624. * If no cell content factory is passed in with the options, the one on the
  625. * notebook content factory is used.
  626. */
  627. createCodeCell(options: CodeCell.IOptions): CodeCell {
  628. if (!options.contentFactory) {
  629. options.contentFactory = this;
  630. }
  631. return new CodeCell(options);
  632. }
  633. /**
  634. * Create a new raw cell widget.
  635. *
  636. * #### Notes
  637. * If no cell content factory is passed in with the options, the one on the
  638. * notebook content factory is used.
  639. */
  640. createRawCell(options: RawCell.IOptions): RawCell {
  641. if (!options.contentFactory) {
  642. options.contentFactory = this;
  643. }
  644. return new RawCell(options);
  645. }
  646. }
  647. /**
  648. * A namespace for the code console content factory.
  649. */
  650. export
  651. namespace ContentFactory {
  652. /**
  653. * An initialize options for `ContentFactory`.
  654. */
  655. export
  656. interface IOptions extends Cell.IContentFactory { }
  657. }
  658. /**
  659. * A default content factory for the code console.
  660. */
  661. export
  662. const defaultContentFactory: IContentFactory = new ContentFactory();
  663. /**
  664. * A model factory for a console widget.
  665. */
  666. export
  667. interface IModelFactory {
  668. /**
  669. * The factory for code cell content.
  670. */
  671. readonly codeCellContentFactory: CodeCellModel.IContentFactory;
  672. /**
  673. * Create a new code cell.
  674. *
  675. * @param options - The options used to create the cell.
  676. *
  677. * @returns A new code cell. If a source cell is provided, the
  678. * new cell will be intialized with the data from the source.
  679. */
  680. createCodeCell(options: CodeCellModel.IOptions): ICodeCellModel;
  681. /**
  682. * Create a new raw cell.
  683. *
  684. * @param options - The options used to create the cell.
  685. *
  686. * @returns A new raw cell. If a source cell is provided, the
  687. * new cell will be intialized with the data from the source.
  688. */
  689. createRawCell(options: CellModel.IOptions): IRawCellModel;
  690. }
  691. /**
  692. * The default implementation of an `IModelFactory`.
  693. */
  694. export
  695. class ModelFactory {
  696. /**
  697. * Create a new cell model factory.
  698. */
  699. constructor(options: IModelFactoryOptions = {}) {
  700. this.codeCellContentFactory = (options.codeCellContentFactory ||
  701. CodeCellModel.defaultContentFactory
  702. );
  703. }
  704. /**
  705. * The factory for output area models.
  706. */
  707. readonly codeCellContentFactory: CodeCellModel.IContentFactory;
  708. /**
  709. * Create a new code cell.
  710. *
  711. * @param source - The data to use for the original source data.
  712. *
  713. * @returns A new code cell. If a source cell is provided, the
  714. * new cell will be intialized with the data from the source.
  715. * If the contentFactory is not provided, the instance
  716. * `codeCellContentFactory` will be used.
  717. */
  718. createCodeCell(options: CodeCellModel.IOptions): ICodeCellModel {
  719. if (!options.contentFactory) {
  720. options.contentFactory = this.codeCellContentFactory;
  721. }
  722. return new CodeCellModel(options);
  723. }
  724. /**
  725. * Create a new raw cell.
  726. *
  727. * @param source - The data to use for the original source data.
  728. *
  729. * @returns A new raw cell. If a source cell is provided, the
  730. * new cell will be intialized with the data from the source.
  731. */
  732. createRawCell(options: CellModel.IOptions): IRawCellModel {
  733. return new RawCellModel(options);
  734. }
  735. }
  736. /**
  737. * The options used to initialize a `ModelFactory`.
  738. */
  739. export
  740. interface IModelFactoryOptions {
  741. /**
  742. * The factory for output area models.
  743. */
  744. codeCellContentFactory?: CodeCellModel.IContentFactory;
  745. }
  746. /**
  747. * The default `ModelFactory` instance.
  748. */
  749. export
  750. const defaultModelFactory = new ModelFactory({});
  751. }
  752. /**
  753. * A namespace for console widget private data.
  754. */
  755. namespace Private {
  756. /**
  757. * Jump to the bottom of a node.
  758. *
  759. * @param node - The scrollable element.
  760. */
  761. export
  762. function scrollToBottom(node: HTMLElement): void {
  763. node.scrollTop = node.scrollHeight - node.clientHeight;
  764. }
  765. }