widget.ts 63 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296
  1. // Copyright (c) Jupyter Development Team.
  2. // Distributed under the terms of the Modified BSD License.
  3. import { ArrayExt, each } from '@lumino/algorithm';
  4. import { ReadonlyPartialJSONValue } from '@lumino/coreutils';
  5. import { Message } from '@lumino/messaging';
  6. import { MimeData } from '@lumino/coreutils';
  7. import { AttachedProperty } from '@lumino/properties';
  8. import { ISignal, Signal } from '@lumino/signaling';
  9. import { Drag, IDragEvent } from '@lumino/dragdrop';
  10. import { PanelLayout, Widget } from '@lumino/widgets';
  11. import { h, VirtualDOM } from '@lumino/virtualdom';
  12. import {
  13. ICellModel,
  14. Cell,
  15. IMarkdownCellModel,
  16. CodeCell,
  17. MarkdownCell,
  18. ICodeCellModel,
  19. RawCell,
  20. IRawCellModel
  21. } from '@jupyterlab/cells';
  22. import { IEditorMimeTypeService, CodeEditor } from '@jupyterlab/codeeditor';
  23. import { IChangedArgs } from '@jupyterlab/coreutils';
  24. import * as nbformat from '@jupyterlab/nbformat';
  25. import { IObservableMap, IObservableList } from '@jupyterlab/observables';
  26. import { IRenderMimeRegistry } from '@jupyterlab/rendermime';
  27. import { INotebookModel } from './model';
  28. /**
  29. * The data attribute added to a widget that has an active kernel.
  30. */
  31. const KERNEL_USER = 'jpKernelUser';
  32. /**
  33. * The data attribute added to a widget that can run code.
  34. */
  35. const CODE_RUNNER = 'jpCodeRunner';
  36. /**
  37. * The data attribute added to a widget that can undo.
  38. */
  39. const UNDOER = 'jpUndoer';
  40. /**
  41. * The class name added to notebook widgets.
  42. */
  43. const NB_CLASS = 'jp-Notebook';
  44. /**
  45. * The class name added to notebook widget cells.
  46. */
  47. const NB_CELL_CLASS = 'jp-Notebook-cell';
  48. /**
  49. * The class name added to a notebook in edit mode.
  50. */
  51. const EDIT_CLASS = 'jp-mod-editMode';
  52. /**
  53. * The class name added to a notebook in command mode.
  54. */
  55. const COMMAND_CLASS = 'jp-mod-commandMode';
  56. /**
  57. * The class name added to the active cell.
  58. */
  59. const ACTIVE_CLASS = 'jp-mod-active';
  60. /**
  61. * The class name added to selected cells.
  62. */
  63. const SELECTED_CLASS = 'jp-mod-selected';
  64. /**
  65. * The class name added to an active cell when there are other selected cells.
  66. */
  67. const OTHER_SELECTED_CLASS = 'jp-mod-multiSelected';
  68. /**
  69. * The class name added to unconfined images.
  70. */
  71. const UNCONFINED_CLASS = 'jp-mod-unconfined';
  72. /**
  73. * The class name added to a drop target.
  74. */
  75. const DROP_TARGET_CLASS = 'jp-mod-dropTarget';
  76. /**
  77. * The class name added to a drop source.
  78. */
  79. const DROP_SOURCE_CLASS = 'jp-mod-dropSource';
  80. /**
  81. * The class name added to drag images.
  82. */
  83. const DRAG_IMAGE_CLASS = 'jp-dragImage';
  84. /**
  85. * The class name added to singular drag images
  86. */
  87. const SINGLE_DRAG_IMAGE_CLASS = 'jp-dragImage-singlePrompt';
  88. /**
  89. * The class name added to the drag image cell content.
  90. */
  91. const CELL_DRAG_CONTENT_CLASS = 'jp-dragImage-content';
  92. /**
  93. * The class name added to the drag image cell content.
  94. */
  95. const CELL_DRAG_PROMPT_CLASS = 'jp-dragImage-prompt';
  96. /**
  97. * The class name added to the drag image cell content.
  98. */
  99. const CELL_DRAG_MULTIPLE_BACK = 'jp-dragImage-multipleBack';
  100. /**
  101. * The mimetype used for Jupyter cell data.
  102. */
  103. const JUPYTER_CELL_MIME = 'application/vnd.jupyter.cells';
  104. /**
  105. * The threshold in pixels to start a drag event.
  106. */
  107. const DRAG_THRESHOLD = 5;
  108. /**
  109. * The interactivity modes for the notebook.
  110. */
  111. export type NotebookMode = 'command' | 'edit';
  112. /**
  113. * A widget which renders static non-interactive notebooks.
  114. *
  115. * #### Notes
  116. * The widget model must be set separately and can be changed
  117. * at any time. Consumers of the widget must account for a
  118. * `null` model, and may want to listen to the `modelChanged`
  119. * signal.
  120. */
  121. export class StaticNotebook extends Widget {
  122. /**
  123. * Construct a notebook widget.
  124. */
  125. constructor(options: StaticNotebook.IOptions) {
  126. super();
  127. this.addClass(NB_CLASS);
  128. this.node.dataset[KERNEL_USER] = 'true';
  129. this.node.dataset[UNDOER] = 'true';
  130. this.rendermime = options.rendermime;
  131. this.layout = new Private.NotebookPanelLayout();
  132. this.contentFactory =
  133. options.contentFactory || StaticNotebook.defaultContentFactory;
  134. this.editorConfig =
  135. options.editorConfig || StaticNotebook.defaultEditorConfig;
  136. this.notebookConfig =
  137. options.notebookConfig || StaticNotebook.defaultNotebookConfig;
  138. this._mimetypeService = options.mimeTypeService;
  139. }
  140. /**
  141. * A signal emitted when the model of the notebook changes.
  142. */
  143. get modelChanged(): ISignal<this, void> {
  144. return this._modelChanged;
  145. }
  146. /**
  147. * A signal emitted when the model content changes.
  148. *
  149. * #### Notes
  150. * This is a convenience signal that follows the current model.
  151. */
  152. get modelContentChanged(): ISignal<this, void> {
  153. return this._modelContentChanged;
  154. }
  155. /**
  156. * The cell factory used by the widget.
  157. */
  158. readonly contentFactory: StaticNotebook.IContentFactory;
  159. /**
  160. * The Rendermime instance used by the widget.
  161. */
  162. readonly rendermime: IRenderMimeRegistry;
  163. /**
  164. * The model for the widget.
  165. */
  166. get model(): INotebookModel | null {
  167. return this._model;
  168. }
  169. set model(newValue: INotebookModel | null) {
  170. newValue = newValue || null;
  171. if (this._model === newValue) {
  172. return;
  173. }
  174. const oldValue = this._model;
  175. this._model = newValue;
  176. if (oldValue && oldValue.modelDB.isCollaborative) {
  177. void oldValue.modelDB.connected.then(() => {
  178. oldValue!.modelDB.collaborators!.changed.disconnect(
  179. this._onCollaboratorsChanged,
  180. this
  181. );
  182. });
  183. }
  184. if (newValue && newValue.modelDB.isCollaborative) {
  185. void newValue.modelDB.connected.then(() => {
  186. newValue!.modelDB.collaborators!.changed.connect(
  187. this._onCollaboratorsChanged,
  188. this
  189. );
  190. });
  191. }
  192. // Trigger private, protected, and public changes.
  193. this._onModelChanged(oldValue, newValue);
  194. this.onModelChanged(oldValue, newValue);
  195. this._modelChanged.emit(void 0);
  196. }
  197. /**
  198. * Get the mimetype for code cells.
  199. */
  200. get codeMimetype(): string {
  201. return this._mimetype;
  202. }
  203. /**
  204. * A read-only sequence of the widgets in the notebook.
  205. */
  206. get widgets(): ReadonlyArray<Cell> {
  207. return (this.layout as PanelLayout).widgets as ReadonlyArray<Cell>;
  208. }
  209. /**
  210. * A configuration object for cell editor settings.
  211. */
  212. get editorConfig(): StaticNotebook.IEditorConfig {
  213. return this._editorConfig;
  214. }
  215. set editorConfig(value: StaticNotebook.IEditorConfig) {
  216. this._editorConfig = value;
  217. this._updateEditorConfig();
  218. }
  219. /**
  220. * A configuration object for notebook settings.
  221. */
  222. get notebookConfig(): StaticNotebook.INotebookConfig {
  223. return this._notebookConfig;
  224. }
  225. set notebookConfig(value: StaticNotebook.INotebookConfig) {
  226. this._notebookConfig = value;
  227. this._updateNotebookConfig();
  228. }
  229. /**
  230. * Dispose of the resources held by the widget.
  231. */
  232. dispose() {
  233. // Do nothing if already disposed.
  234. if (this.isDisposed) {
  235. return;
  236. }
  237. this._model = null;
  238. super.dispose();
  239. }
  240. /**
  241. * Handle a new model.
  242. *
  243. * #### Notes
  244. * This method is called after the model change has been handled
  245. * internally and before the `modelChanged` signal is emitted.
  246. * The default implementation is a no-op.
  247. */
  248. protected onModelChanged(
  249. oldValue: INotebookModel | null,
  250. newValue: INotebookModel | null
  251. ): void {
  252. // No-op.
  253. }
  254. /**
  255. * Handle changes to the notebook model content.
  256. *
  257. * #### Notes
  258. * The default implementation emits the `modelContentChanged` signal.
  259. */
  260. protected onModelContentChanged(model: INotebookModel, args: void): void {
  261. this._modelContentChanged.emit(void 0);
  262. }
  263. /**
  264. * Handle changes to the notebook model metadata.
  265. *
  266. * #### Notes
  267. * The default implementation updates the mimetypes of the code cells
  268. * when the `language_info` metadata changes.
  269. */
  270. protected onMetadataChanged(
  271. sender: IObservableMap<ReadonlyPartialJSONValue | undefined>,
  272. args: IObservableMap.IChangedArgs<ReadonlyPartialJSONValue>
  273. ): void {
  274. switch (args.key) {
  275. case 'language_info':
  276. this._updateMimetype();
  277. break;
  278. default:
  279. break;
  280. }
  281. }
  282. /**
  283. * Handle a cell being inserted.
  284. *
  285. * The default implementation is a no-op
  286. */
  287. protected onCellInserted(index: number, cell: Cell): void {
  288. // This is a no-op.
  289. }
  290. /**
  291. * Handle a cell being moved.
  292. *
  293. * The default implementation is a no-op
  294. */
  295. protected onCellMoved(fromIndex: number, toIndex: number): void {
  296. // This is a no-op.
  297. }
  298. /**
  299. * Handle a cell being removed.
  300. *
  301. * The default implementation is a no-op
  302. */
  303. protected onCellRemoved(index: number, cell: Cell): void {
  304. // This is a no-op.
  305. }
  306. /**
  307. * Handle a new model on the widget.
  308. */
  309. private _onModelChanged(
  310. oldValue: INotebookModel | null,
  311. newValue: INotebookModel | null
  312. ): void {
  313. const layout = this.layout as PanelLayout;
  314. if (oldValue) {
  315. oldValue.cells.changed.disconnect(this._onCellsChanged, this);
  316. oldValue.metadata.changed.disconnect(this.onMetadataChanged, this);
  317. oldValue.contentChanged.disconnect(this.onModelContentChanged, this);
  318. // TODO: reuse existing cell widgets if possible. Remember to initially
  319. // clear the history of each cell if we do this.
  320. while (layout.widgets.length) {
  321. this._removeCell(0);
  322. }
  323. }
  324. if (!newValue) {
  325. this._mimetype = 'text/plain';
  326. return;
  327. }
  328. this._updateMimetype();
  329. const cells = newValue.cells;
  330. if (!cells.length) {
  331. cells.push(
  332. newValue.contentFactory.createCell(this.notebookConfig.defaultCell, {})
  333. );
  334. }
  335. each(cells, (cell: ICellModel, i: number) => {
  336. this._insertCell(i, cell);
  337. });
  338. cells.changed.connect(this._onCellsChanged, this);
  339. newValue.contentChanged.connect(this.onModelContentChanged, this);
  340. newValue.metadata.changed.connect(this.onMetadataChanged, this);
  341. }
  342. /**
  343. * Handle a change cells event.
  344. */
  345. private _onCellsChanged(
  346. sender: IObservableList<ICellModel>,
  347. args: IObservableList.IChangedArgs<ICellModel>
  348. ) {
  349. let index = 0;
  350. switch (args.type) {
  351. case 'add':
  352. index = args.newIndex;
  353. each(args.newValues, value => {
  354. this._insertCell(index++, value);
  355. });
  356. break;
  357. case 'move':
  358. this._moveCell(args.oldIndex, args.newIndex);
  359. break;
  360. case 'remove':
  361. each(args.oldValues, value => {
  362. this._removeCell(args.oldIndex);
  363. });
  364. // Add default cell if there are no cells remaining.
  365. if (!sender.length) {
  366. const model = this.model;
  367. // Add the cell in a new context to avoid triggering another
  368. // cell changed event during the handling of this signal.
  369. requestAnimationFrame(() => {
  370. if (model && !model.isDisposed && !model.cells.length) {
  371. model.cells.push(
  372. model.contentFactory.createCell(
  373. this.notebookConfig.defaultCell,
  374. {}
  375. )
  376. );
  377. }
  378. });
  379. }
  380. break;
  381. case 'set':
  382. // TODO: reuse existing widgets if possible.
  383. index = args.newIndex;
  384. each(args.newValues, value => {
  385. // Note: this ordering (insert then remove)
  386. // is important for getting the active cell
  387. // index for the editable notebook correct.
  388. this._insertCell(index, value);
  389. this._removeCell(index + 1);
  390. index++;
  391. });
  392. break;
  393. default:
  394. return;
  395. }
  396. }
  397. /**
  398. * Create a cell widget and insert into the notebook.
  399. */
  400. private _insertCell(index: number, cell: ICellModel): void {
  401. let widget: Cell;
  402. switch (cell.type) {
  403. case 'code':
  404. widget = this._createCodeCell(cell as ICodeCellModel);
  405. widget.model.mimeType = this._mimetype;
  406. break;
  407. case 'markdown':
  408. widget = this._createMarkdownCell(cell as IMarkdownCellModel);
  409. if (cell.value.text === '') {
  410. (widget as MarkdownCell).rendered = false;
  411. }
  412. break;
  413. default:
  414. widget = this._createRawCell(cell as IRawCellModel);
  415. }
  416. widget.addClass(NB_CELL_CLASS);
  417. const layout = this.layout as PanelLayout;
  418. layout.insertWidget(index, widget);
  419. this.onCellInserted(index, widget);
  420. }
  421. /**
  422. * Create a code cell widget from a code cell model.
  423. */
  424. private _createCodeCell(model: ICodeCellModel): CodeCell {
  425. const rendermime = this.rendermime;
  426. const contentFactory = this.contentFactory;
  427. const editorConfig = this.editorConfig.code;
  428. const options = {
  429. editorConfig,
  430. model,
  431. rendermime,
  432. contentFactory,
  433. updateEditorOnShow: false
  434. };
  435. const cell = this.contentFactory.createCodeCell(options, this);
  436. cell.syncCollapse = true;
  437. cell.syncEditable = true;
  438. cell.syncScrolled = true;
  439. return cell;
  440. }
  441. /**
  442. * Create a markdown cell widget from a markdown cell model.
  443. */
  444. private _createMarkdownCell(model: IMarkdownCellModel): MarkdownCell {
  445. const rendermime = this.rendermime;
  446. const contentFactory = this.contentFactory;
  447. const editorConfig = this.editorConfig.markdown;
  448. const options = {
  449. editorConfig,
  450. model,
  451. rendermime,
  452. contentFactory,
  453. updateEditorOnShow: false
  454. };
  455. const cell = this.contentFactory.createMarkdownCell(options, this);
  456. cell.syncCollapse = true;
  457. cell.syncEditable = true;
  458. return cell;
  459. }
  460. /**
  461. * Create a raw cell widget from a raw cell model.
  462. */
  463. private _createRawCell(model: IRawCellModel): RawCell {
  464. const contentFactory = this.contentFactory;
  465. const editorConfig = this.editorConfig.raw;
  466. const options = {
  467. editorConfig,
  468. model,
  469. contentFactory,
  470. updateEditorOnShow: false
  471. };
  472. const cell = this.contentFactory.createRawCell(options, this);
  473. cell.syncCollapse = true;
  474. cell.syncEditable = true;
  475. return cell;
  476. }
  477. /**
  478. * Move a cell widget.
  479. */
  480. private _moveCell(fromIndex: number, toIndex: number): void {
  481. const layout = this.layout as PanelLayout;
  482. layout.insertWidget(toIndex, layout.widgets[fromIndex]);
  483. this.onCellMoved(fromIndex, toIndex);
  484. }
  485. /**
  486. * Remove a cell widget.
  487. */
  488. private _removeCell(index: number): void {
  489. const layout = this.layout as PanelLayout;
  490. const widget = layout.widgets[index] as Cell;
  491. widget.parent = null;
  492. this.onCellRemoved(index, widget);
  493. widget.dispose();
  494. }
  495. /**
  496. * Update the mimetype of the notebook.
  497. */
  498. private _updateMimetype(): void {
  499. const info = this._model?.metadata.get(
  500. 'language_info'
  501. ) as nbformat.ILanguageInfoMetadata;
  502. if (!info) {
  503. return;
  504. }
  505. this._mimetype = this._mimetypeService.getMimeTypeByLanguage(info);
  506. each(this.widgets, widget => {
  507. if (widget.model.type === 'code') {
  508. widget.model.mimeType = this._mimetype;
  509. }
  510. });
  511. }
  512. /**
  513. * Handle an update to the collaborators.
  514. */
  515. private _onCollaboratorsChanged(): void {
  516. // If there are selections corresponding to non-collaborators,
  517. // they are stale and should be removed.
  518. for (let i = 0; i < this.widgets.length; i++) {
  519. const cell = this.widgets[i];
  520. for (const key of cell.model.selections.keys()) {
  521. if (false === this._model?.modelDB?.collaborators?.has(key)) {
  522. cell.model.selections.delete(key);
  523. }
  524. }
  525. }
  526. }
  527. /**
  528. * Update editor settings for notebook cells.
  529. */
  530. private _updateEditorConfig() {
  531. for (let i = 0; i < this.widgets.length; i++) {
  532. const cell = this.widgets[i];
  533. let config: Partial<CodeEditor.IConfig>;
  534. switch (cell.model.type) {
  535. case 'code':
  536. config = this._editorConfig.code;
  537. break;
  538. case 'markdown':
  539. config = this._editorConfig.markdown;
  540. break;
  541. default:
  542. config = this._editorConfig.raw;
  543. break;
  544. }
  545. Object.keys(config).forEach((key: keyof CodeEditor.IConfig) => {
  546. cell.editor.setOption(key, config[key] ?? null);
  547. });
  548. cell.editor.refresh();
  549. }
  550. }
  551. /**
  552. * Apply updated notebook settings.
  553. */
  554. private _updateNotebookConfig() {
  555. // Apply scrollPastEnd setting.
  556. this.toggleClass(
  557. 'jp-mod-scrollPastEnd',
  558. this._notebookConfig.scrollPastEnd
  559. );
  560. }
  561. private _editorConfig = StaticNotebook.defaultEditorConfig;
  562. private _notebookConfig = StaticNotebook.defaultNotebookConfig;
  563. private _mimetype = 'text/plain';
  564. private _model: INotebookModel | null = null;
  565. private _mimetypeService: IEditorMimeTypeService;
  566. private _modelChanged = new Signal<this, void>(this);
  567. private _modelContentChanged = new Signal<this, void>(this);
  568. }
  569. /**
  570. * The namespace for the `StaticNotebook` class statics.
  571. */
  572. export namespace StaticNotebook {
  573. /**
  574. * An options object for initializing a static notebook.
  575. */
  576. export interface IOptions {
  577. /**
  578. * The rendermime instance used by the widget.
  579. */
  580. rendermime: IRenderMimeRegistry;
  581. /**
  582. * The language preference for the model.
  583. */
  584. languagePreference?: string;
  585. /**
  586. * A factory for creating content.
  587. */
  588. contentFactory?: IContentFactory;
  589. /**
  590. * A configuration object for the cell editor settings.
  591. */
  592. editorConfig?: IEditorConfig;
  593. /**
  594. * A configuration object for notebook settings.
  595. */
  596. notebookConfig?: INotebookConfig;
  597. /**
  598. * The service used to look up mime types.
  599. */
  600. mimeTypeService: IEditorMimeTypeService;
  601. }
  602. /**
  603. * A factory for creating notebook content.
  604. *
  605. * #### Notes
  606. * This extends the content factory of the cell itself, which extends the content
  607. * factory of the output area and input area. The result is that there is a single
  608. * factory for creating all child content of a notebook.
  609. */
  610. export interface IContentFactory extends Cell.IContentFactory {
  611. /**
  612. * Create a new code cell widget.
  613. */
  614. createCodeCell(
  615. options: CodeCell.IOptions,
  616. parent: StaticNotebook
  617. ): CodeCell;
  618. /**
  619. * Create a new markdown cell widget.
  620. */
  621. createMarkdownCell(
  622. options: MarkdownCell.IOptions,
  623. parent: StaticNotebook
  624. ): MarkdownCell;
  625. /**
  626. * Create a new raw cell widget.
  627. */
  628. createRawCell(options: RawCell.IOptions, parent: StaticNotebook): RawCell;
  629. }
  630. /**
  631. * A config object for the cell editors.
  632. */
  633. export interface IEditorConfig {
  634. /**
  635. * Config options for code cells.
  636. */
  637. readonly code: Partial<CodeEditor.IConfig>;
  638. /**
  639. * Config options for markdown cells.
  640. */
  641. readonly markdown: Partial<CodeEditor.IConfig>;
  642. /**
  643. * Config options for raw cells.
  644. */
  645. readonly raw: Partial<CodeEditor.IConfig>;
  646. }
  647. /**
  648. * Default configuration options for cell editors.
  649. */
  650. export const defaultEditorConfig: IEditorConfig = {
  651. code: {
  652. ...CodeEditor.defaultConfig,
  653. lineWrap: 'off',
  654. matchBrackets: true,
  655. autoClosingBrackets: true
  656. },
  657. markdown: {
  658. ...CodeEditor.defaultConfig,
  659. lineWrap: 'on',
  660. matchBrackets: false,
  661. autoClosingBrackets: false
  662. },
  663. raw: {
  664. ...CodeEditor.defaultConfig,
  665. lineWrap: 'on',
  666. matchBrackets: false,
  667. autoClosingBrackets: false
  668. }
  669. };
  670. /**
  671. * A config object for the notebook widget
  672. */
  673. export interface INotebookConfig {
  674. /**
  675. * Enable scrolling past the last cell
  676. */
  677. scrollPastEnd: boolean;
  678. /**
  679. * The default type for new notebook cells.
  680. */
  681. defaultCell: nbformat.CellType;
  682. /**
  683. * Should timing be recorded in metadata
  684. */
  685. recordTiming: boolean;
  686. }
  687. /**
  688. * Default configuration options for notebooks.
  689. */
  690. export const defaultNotebookConfig: INotebookConfig = {
  691. scrollPastEnd: true,
  692. defaultCell: 'code',
  693. recordTiming: false
  694. };
  695. /**
  696. * The default implementation of an `IContentFactory`.
  697. */
  698. export class ContentFactory extends Cell.ContentFactory
  699. implements IContentFactory {
  700. /**
  701. * Create a new code cell widget.
  702. *
  703. * #### Notes
  704. * If no cell content factory is passed in with the options, the one on the
  705. * notebook content factory is used.
  706. */
  707. createCodeCell(
  708. options: CodeCell.IOptions,
  709. parent: StaticNotebook
  710. ): CodeCell {
  711. if (!options.contentFactory) {
  712. options.contentFactory = this;
  713. }
  714. return new CodeCell(options).initializeState();
  715. }
  716. /**
  717. * Create a new markdown cell widget.
  718. *
  719. * #### Notes
  720. * If no cell content factory is passed in with the options, the one on the
  721. * notebook content factory is used.
  722. */
  723. createMarkdownCell(
  724. options: MarkdownCell.IOptions,
  725. parent: StaticNotebook
  726. ): MarkdownCell {
  727. if (!options.contentFactory) {
  728. options.contentFactory = this;
  729. }
  730. return new MarkdownCell(options).initializeState();
  731. }
  732. /**
  733. * Create a new raw cell widget.
  734. *
  735. * #### Notes
  736. * If no cell content factory is passed in with the options, the one on the
  737. * notebook content factory is used.
  738. */
  739. createRawCell(options: RawCell.IOptions, parent: StaticNotebook): RawCell {
  740. if (!options.contentFactory) {
  741. options.contentFactory = this;
  742. }
  743. return new RawCell(options).initializeState();
  744. }
  745. }
  746. /**
  747. * A namespace for the staic notebook content factory.
  748. */
  749. export namespace ContentFactory {
  750. /**
  751. * Options for the content factory.
  752. */
  753. export interface IOptions extends Cell.ContentFactory.IOptions {}
  754. }
  755. /**
  756. * Default content factory for the static notebook widget.
  757. */
  758. export const defaultContentFactory: IContentFactory = new ContentFactory();
  759. }
  760. /**
  761. * A notebook widget that supports interactivity.
  762. */
  763. export class Notebook extends StaticNotebook {
  764. /**
  765. * Construct a notebook widget.
  766. */
  767. constructor(options: Notebook.IOptions) {
  768. super(Private.processNotebookOptions(options));
  769. this.node.tabIndex = -1; // Allow the widget to take focus.
  770. // Allow the node to scroll while dragging items.
  771. this.node.setAttribute('data-lm-dragscroll', 'true');
  772. }
  773. /**
  774. * A signal emitted when the active cell changes.
  775. *
  776. * #### Notes
  777. * This can be due to the active index changing or the
  778. * cell at the active index changing.
  779. */
  780. get activeCellChanged(): ISignal<this, Cell> {
  781. return this._activeCellChanged;
  782. }
  783. /**
  784. * A signal emitted when the state of the notebook changes.
  785. */
  786. get stateChanged(): ISignal<this, IChangedArgs<any>> {
  787. return this._stateChanged;
  788. }
  789. /**
  790. * A signal emitted when the selection state of the notebook changes.
  791. */
  792. get selectionChanged(): ISignal<this, void> {
  793. return this._selectionChanged;
  794. }
  795. /**
  796. * The interactivity mode of the notebook.
  797. */
  798. get mode(): NotebookMode {
  799. return this._mode;
  800. }
  801. set mode(newValue: NotebookMode) {
  802. const activeCell = this.activeCell;
  803. if (!activeCell) {
  804. newValue = 'command';
  805. }
  806. if (newValue === this._mode) {
  807. this._ensureFocus();
  808. return;
  809. }
  810. // Post an update request.
  811. this.update();
  812. const oldValue = this._mode;
  813. this._mode = newValue;
  814. if (newValue === 'edit') {
  815. // Edit mode deselects all cells.
  816. each(this.widgets, widget => {
  817. this.deselect(widget);
  818. });
  819. // Edit mode unrenders an active markdown widget.
  820. if (activeCell instanceof MarkdownCell) {
  821. activeCell.rendered = false;
  822. }
  823. activeCell!.inputHidden = false;
  824. } else {
  825. // Focus on the notebook document, which blurs the active cell.
  826. this.node.focus();
  827. }
  828. this._stateChanged.emit({ name: 'mode', oldValue, newValue });
  829. this._ensureFocus();
  830. }
  831. /**
  832. * The active cell index of the notebook.
  833. *
  834. * #### Notes
  835. * The index will be clamped to the bounds of the notebook cells.
  836. */
  837. get activeCellIndex(): number {
  838. if (!this.model) {
  839. return -1;
  840. }
  841. return this.model.cells.length ? this._activeCellIndex : -1;
  842. }
  843. set activeCellIndex(newValue: number) {
  844. const oldValue = this._activeCellIndex;
  845. if (!this.model || !this.model.cells.length) {
  846. newValue = -1;
  847. } else {
  848. newValue = Math.max(newValue, 0);
  849. newValue = Math.min(newValue, this.model.cells.length - 1);
  850. }
  851. this._activeCellIndex = newValue;
  852. const cell = this.widgets[newValue];
  853. if (cell !== this._activeCell) {
  854. // Post an update request.
  855. this.update();
  856. this._activeCell = cell;
  857. this._activeCellChanged.emit(cell);
  858. }
  859. if (this.mode === 'edit' && cell instanceof MarkdownCell) {
  860. cell.rendered = false;
  861. }
  862. this._ensureFocus();
  863. if (newValue === oldValue) {
  864. return;
  865. }
  866. this._trimSelections();
  867. this._stateChanged.emit({ name: 'activeCellIndex', oldValue, newValue });
  868. }
  869. /**
  870. * Get the active cell widget.
  871. *
  872. * #### Notes
  873. * This is a cell or `null` if there is no active cell.
  874. */
  875. get activeCell(): Cell | null {
  876. return this._activeCell;
  877. }
  878. /**
  879. * Dispose of the resources held by the widget.
  880. */
  881. dispose(): void {
  882. if (this.isDisposed) {
  883. return;
  884. }
  885. this._activeCell = null;
  886. super.dispose();
  887. }
  888. /**
  889. * Select a cell widget.
  890. *
  891. * #### Notes
  892. * It is a no-op if the value does not change.
  893. * It will emit the `selectionChanged` signal.
  894. */
  895. select(widget: Cell): void {
  896. if (Private.selectedProperty.get(widget)) {
  897. return;
  898. }
  899. Private.selectedProperty.set(widget, true);
  900. this._selectionChanged.emit(void 0);
  901. this.update();
  902. }
  903. /**
  904. * Deselect a cell widget.
  905. *
  906. * #### Notes
  907. * It is a no-op if the value does not change.
  908. * It will emit the `selectionChanged` signal.
  909. */
  910. deselect(widget: Cell): void {
  911. if (!Private.selectedProperty.get(widget)) {
  912. return;
  913. }
  914. Private.selectedProperty.set(widget, false);
  915. this._selectionChanged.emit(void 0);
  916. this.update();
  917. }
  918. /**
  919. * Whether a cell is selected.
  920. */
  921. isSelected(widget: Cell): boolean {
  922. return Private.selectedProperty.get(widget);
  923. }
  924. /**
  925. * Whether a cell is selected or is the active cell.
  926. */
  927. isSelectedOrActive(widget: Cell): boolean {
  928. if (widget === this._activeCell) {
  929. return true;
  930. }
  931. return Private.selectedProperty.get(widget);
  932. }
  933. /**
  934. * Deselect all of the cells.
  935. */
  936. deselectAll(): void {
  937. let changed = false;
  938. each(this.widgets, widget => {
  939. if (Private.selectedProperty.get(widget)) {
  940. changed = true;
  941. }
  942. Private.selectedProperty.set(widget, false);
  943. });
  944. if (changed) {
  945. this._selectionChanged.emit(void 0);
  946. }
  947. // Make sure we have a valid active cell.
  948. this.activeCellIndex = this.activeCellIndex; // eslint-disable-line
  949. this.update();
  950. }
  951. /**
  952. * Move the head of an existing contiguous selection to extend the selection.
  953. *
  954. * @param index - The new head of the existing selection.
  955. *
  956. * #### Notes
  957. * If there is no existing selection, the active cell is considered an
  958. * existing one-cell selection.
  959. *
  960. * If the new selection is a single cell, that cell becomes the active cell
  961. * and all cells are deselected.
  962. *
  963. * There is no change if there are no cells (i.e., activeCellIndex is -1).
  964. */
  965. extendContiguousSelectionTo(index: number): void {
  966. let { head, anchor } = this.getContiguousSelection();
  967. let i: number;
  968. // Handle the case of no current selection.
  969. if (anchor === null || head === null) {
  970. if (index === this.activeCellIndex) {
  971. // Already collapsed selection, nothing more to do.
  972. return;
  973. }
  974. // We will start a new selection below.
  975. head = this.activeCellIndex;
  976. anchor = this.activeCellIndex;
  977. }
  978. // Move the active cell. We do this before the collapsing shortcut below.
  979. this.activeCellIndex = index;
  980. // Make sure the index is valid, according to the rules for setting and clipping the
  981. // active cell index. This may change the index.
  982. index = this.activeCellIndex;
  983. // Collapse the selection if it is only the active cell.
  984. if (index === anchor) {
  985. this.deselectAll();
  986. return;
  987. }
  988. let selectionChanged = false;
  989. if (head < index) {
  990. if (head < anchor) {
  991. Private.selectedProperty.set(this.widgets[head], false);
  992. selectionChanged = true;
  993. }
  994. // Toggle everything strictly between head and index except anchor.
  995. for (i = head + 1; i < index; i++) {
  996. if (i !== anchor) {
  997. Private.selectedProperty.set(
  998. this.widgets[i],
  999. !Private.selectedProperty.get(this.widgets[i])
  1000. );
  1001. selectionChanged = true;
  1002. }
  1003. }
  1004. } else if (index < head) {
  1005. if (anchor < head) {
  1006. Private.selectedProperty.set(this.widgets[head], false);
  1007. selectionChanged = true;
  1008. }
  1009. // Toggle everything strictly between index and head except anchor.
  1010. for (i = index + 1; i < head; i++) {
  1011. if (i !== anchor) {
  1012. Private.selectedProperty.set(
  1013. this.widgets[i],
  1014. !Private.selectedProperty.get(this.widgets[i])
  1015. );
  1016. selectionChanged = true;
  1017. }
  1018. }
  1019. }
  1020. // Anchor and index should *always* be selected.
  1021. if (!Private.selectedProperty.get(this.widgets[anchor])) {
  1022. selectionChanged = true;
  1023. }
  1024. Private.selectedProperty.set(this.widgets[anchor], true);
  1025. if (!Private.selectedProperty.get(this.widgets[index])) {
  1026. selectionChanged = true;
  1027. }
  1028. Private.selectedProperty.set(this.widgets[index], true);
  1029. if (selectionChanged) {
  1030. this._selectionChanged.emit(void 0);
  1031. }
  1032. }
  1033. /**
  1034. * Get the head and anchor of a contiguous cell selection.
  1035. *
  1036. * The head of a contiguous selection is always the active cell.
  1037. *
  1038. * If there are no cells selected, `{head: null, anchor: null}` is returned.
  1039. *
  1040. * Throws an error if the currently selected cells do not form a contiguous
  1041. * selection.
  1042. */
  1043. getContiguousSelection():
  1044. | { head: number; anchor: number }
  1045. | { head: null; anchor: null } {
  1046. const cells = this.widgets;
  1047. const first = ArrayExt.findFirstIndex(cells, c => this.isSelected(c));
  1048. // Return early if no cells are selected.
  1049. if (first === -1) {
  1050. return { head: null, anchor: null };
  1051. }
  1052. const last = ArrayExt.findLastIndex(
  1053. cells,
  1054. c => this.isSelected(c),
  1055. -1,
  1056. first
  1057. );
  1058. // Check that the selection is contiguous.
  1059. for (let i = first; i <= last; i++) {
  1060. if (!this.isSelected(cells[i])) {
  1061. throw new Error('Selection not contiguous');
  1062. }
  1063. }
  1064. // Check that the active cell is one of the endpoints of the selection.
  1065. const activeIndex = this.activeCellIndex;
  1066. if (first !== activeIndex && last !== activeIndex) {
  1067. throw new Error('Active cell not at endpoint of selection');
  1068. }
  1069. // Determine the head and anchor of the selection.
  1070. if (first === activeIndex) {
  1071. return { head: first, anchor: last };
  1072. } else {
  1073. return { head: last, anchor: first };
  1074. }
  1075. }
  1076. /**
  1077. * Scroll so that the given position is centered.
  1078. *
  1079. * @param position - The vertical position in the notebook widget.
  1080. *
  1081. * @param threshold - An optional threshold for the scroll (0-50, defaults to
  1082. * 25).
  1083. *
  1084. * #### Notes
  1085. * If the position is within the threshold percentage of the widget height,
  1086. * measured from the center of the widget, the scroll position will not be
  1087. * changed. A threshold of 0 means we will always scroll so the position is
  1088. * centered, and a threshold of 50 means scrolling only happens if position is
  1089. * outside the current window.
  1090. */
  1091. scrollToPosition(position: number, threshold = 25): void {
  1092. const node = this.node;
  1093. const ar = node.getBoundingClientRect();
  1094. const delta = position - ar.top - ar.height / 2;
  1095. if (Math.abs(delta) > (ar.height * threshold) / 100) {
  1096. node.scrollTop += delta;
  1097. }
  1098. }
  1099. /**
  1100. * Set URI fragment identifier.
  1101. */
  1102. setFragment(fragment: string): void {
  1103. // Wait all cells are rendered then set fragment and update.
  1104. void Promise.all(this.widgets.map(widget => widget.ready)).then(() => {
  1105. this._fragment = fragment;
  1106. this.update();
  1107. });
  1108. }
  1109. /**
  1110. * Handle the DOM events for the widget.
  1111. *
  1112. * @param event - The DOM event sent to the widget.
  1113. *
  1114. * #### Notes
  1115. * This method implements the DOM `EventListener` interface and is
  1116. * called in response to events on the notebook panel's node. It should
  1117. * not be called directly by user code.
  1118. */
  1119. handleEvent(event: Event): void {
  1120. if (!this.model) {
  1121. return;
  1122. }
  1123. switch (event.type) {
  1124. case 'contextmenu':
  1125. if (event.eventPhase === Event.CAPTURING_PHASE) {
  1126. this._evtContextMenuCapture(event as PointerEvent);
  1127. }
  1128. break;
  1129. case 'mousedown':
  1130. if (event.eventPhase === Event.CAPTURING_PHASE) {
  1131. this._evtMouseDownCapture(event as MouseEvent);
  1132. } else {
  1133. this._evtMouseDown(event as MouseEvent);
  1134. }
  1135. break;
  1136. case 'mouseup':
  1137. if (event.currentTarget === document) {
  1138. this._evtDocumentMouseup(event as MouseEvent);
  1139. }
  1140. break;
  1141. case 'mousemove':
  1142. if (event.currentTarget === document) {
  1143. this._evtDocumentMousemove(event as MouseEvent);
  1144. }
  1145. break;
  1146. case 'keydown':
  1147. this._ensureFocus(true);
  1148. break;
  1149. case 'dblclick':
  1150. this._evtDblClick(event as MouseEvent);
  1151. break;
  1152. case 'focusin':
  1153. this._evtFocusIn(event as MouseEvent);
  1154. break;
  1155. case 'focusout':
  1156. this._evtFocusOut(event as MouseEvent);
  1157. break;
  1158. case 'lm-dragenter':
  1159. this._evtDragEnter(event as IDragEvent);
  1160. break;
  1161. case 'lm-dragleave':
  1162. this._evtDragLeave(event as IDragEvent);
  1163. break;
  1164. case 'lm-dragover':
  1165. this._evtDragOver(event as IDragEvent);
  1166. break;
  1167. case 'lm-drop':
  1168. this._evtDrop(event as IDragEvent);
  1169. break;
  1170. default:
  1171. break;
  1172. }
  1173. }
  1174. /**
  1175. * Handle `after-attach` messages for the widget.
  1176. */
  1177. protected onAfterAttach(msg: Message): void {
  1178. super.onAfterAttach(msg);
  1179. const node = this.node;
  1180. node.addEventListener('contextmenu', this, true);
  1181. node.addEventListener('mousedown', this, true);
  1182. node.addEventListener('mousedown', this);
  1183. node.addEventListener('keydown', this);
  1184. node.addEventListener('dblclick', this);
  1185. node.addEventListener('focusin', this);
  1186. node.addEventListener('focusout', this);
  1187. // Capture drag events for the notebook widget
  1188. // in order to preempt the drag/drop handlers in the
  1189. // code editor widgets, which can take text data.
  1190. node.addEventListener('lm-dragenter', this, true);
  1191. node.addEventListener('lm-dragleave', this, true);
  1192. node.addEventListener('lm-dragover', this, true);
  1193. node.addEventListener('lm-drop', this, true);
  1194. }
  1195. /**
  1196. * Handle `before-detach` messages for the widget.
  1197. */
  1198. protected onBeforeDetach(msg: Message): void {
  1199. const node = this.node;
  1200. node.removeEventListener('contextmenu', this, true);
  1201. node.removeEventListener('mousedown', this, true);
  1202. node.removeEventListener('mousedown', this);
  1203. node.removeEventListener('keydown', this);
  1204. node.removeEventListener('dblclick', this);
  1205. node.removeEventListener('focusin', this);
  1206. node.removeEventListener('focusout', this);
  1207. node.removeEventListener('lm-dragenter', this, true);
  1208. node.removeEventListener('lm-dragleave', this, true);
  1209. node.removeEventListener('lm-dragover', this, true);
  1210. node.removeEventListener('lm-drop', this, true);
  1211. document.removeEventListener('mousemove', this, true);
  1212. document.removeEventListener('mouseup', this, true);
  1213. }
  1214. /**
  1215. * A message handler invoked on an `'after-show'` message.
  1216. */
  1217. protected onAfterShow(msg: Message): void {
  1218. this._checkCacheOnNextResize = true;
  1219. }
  1220. /**
  1221. * A message handler invoked on a `'resize'` message.
  1222. */
  1223. protected onResize(msg: Widget.ResizeMessage): void {
  1224. if (!this._checkCacheOnNextResize) {
  1225. return super.onResize(msg);
  1226. }
  1227. this._checkCacheOnNextResize = false;
  1228. const cache = this._cellLayoutStateCache;
  1229. const width = parseInt(this.node.style.width, 10);
  1230. if (cache) {
  1231. if (width === cache.width) {
  1232. // Cache identical, do nothing
  1233. return;
  1234. }
  1235. }
  1236. // Update cache
  1237. this._cellLayoutStateCache = { width };
  1238. // Fallback:
  1239. for (const w of this.widgets) {
  1240. if (w instanceof Cell) {
  1241. w.editorWidget.update();
  1242. }
  1243. }
  1244. }
  1245. /**
  1246. * A message handler invoked on an `'before-hide'` message.
  1247. */
  1248. protected onBeforeHide(msg: Message): void {
  1249. // Update cache
  1250. const width = parseInt(this.node.style.width, 10);
  1251. this._cellLayoutStateCache = { width };
  1252. }
  1253. /**
  1254. * Handle `'activate-request'` messages.
  1255. */
  1256. protected onActivateRequest(msg: Message): void {
  1257. this._ensureFocus(true);
  1258. }
  1259. /**
  1260. * Handle `update-request` messages sent to the widget.
  1261. */
  1262. protected onUpdateRequest(msg: Message): void {
  1263. const activeCell = this.activeCell;
  1264. // Set the appropriate classes on the cells.
  1265. if (this.mode === 'edit') {
  1266. this.addClass(EDIT_CLASS);
  1267. this.removeClass(COMMAND_CLASS);
  1268. } else {
  1269. this.addClass(COMMAND_CLASS);
  1270. this.removeClass(EDIT_CLASS);
  1271. }
  1272. if (activeCell) {
  1273. activeCell.addClass(ACTIVE_CLASS);
  1274. }
  1275. let count = 0;
  1276. each(this.widgets, widget => {
  1277. if (widget !== activeCell) {
  1278. widget.removeClass(ACTIVE_CLASS);
  1279. }
  1280. widget.removeClass(OTHER_SELECTED_CLASS);
  1281. if (this.isSelectedOrActive(widget)) {
  1282. widget.addClass(SELECTED_CLASS);
  1283. count++;
  1284. } else {
  1285. widget.removeClass(SELECTED_CLASS);
  1286. }
  1287. });
  1288. if (count > 1) {
  1289. activeCell?.addClass(OTHER_SELECTED_CLASS);
  1290. }
  1291. if (this._fragment) {
  1292. let el;
  1293. try {
  1294. el = this.node.querySelector(this._fragment);
  1295. } catch (error) {
  1296. console.warn('Unable to set URI fragment identifier', error);
  1297. }
  1298. if (el) {
  1299. el.scrollIntoView();
  1300. }
  1301. this._fragment = '';
  1302. }
  1303. }
  1304. /**
  1305. * Handle a cell being inserted.
  1306. */
  1307. protected onCellInserted(index: number, cell: Cell): void {
  1308. if (this.model && this.model.modelDB.isCollaborative) {
  1309. const modelDB = this.model.modelDB;
  1310. void modelDB.connected.then(() => {
  1311. if (!cell.isDisposed) {
  1312. // Setup the selection style for collaborators.
  1313. const localCollaborator = modelDB.collaborators!.localCollaborator;
  1314. cell.editor.uuid = localCollaborator.sessionId;
  1315. cell.editor.selectionStyle = {
  1316. ...CodeEditor.defaultSelectionStyle,
  1317. color: localCollaborator.color
  1318. };
  1319. }
  1320. });
  1321. }
  1322. cell.editor.edgeRequested.connect(this._onEdgeRequest, this);
  1323. // If the insertion happened above, increment the active cell
  1324. // index, otherwise it stays the same.
  1325. this.activeCellIndex =
  1326. index <= this.activeCellIndex
  1327. ? this.activeCellIndex + 1
  1328. : this.activeCellIndex;
  1329. }
  1330. /**
  1331. * Handle a cell being moved.
  1332. */
  1333. protected onCellMoved(fromIndex: number, toIndex: number): void {
  1334. const i = this.activeCellIndex;
  1335. if (fromIndex === i) {
  1336. this.activeCellIndex = toIndex;
  1337. } else if (fromIndex < i && i <= toIndex) {
  1338. this.activeCellIndex--;
  1339. } else if (toIndex <= i && i < fromIndex) {
  1340. this.activeCellIndex++;
  1341. }
  1342. }
  1343. /**
  1344. * Handle a cell being removed.
  1345. */
  1346. protected onCellRemoved(index: number, cell: Cell): void {
  1347. // If the removal happened above, decrement the active
  1348. // cell index, otherwise it stays the same.
  1349. this.activeCellIndex =
  1350. index <= this.activeCellIndex
  1351. ? this.activeCellIndex - 1
  1352. : this.activeCellIndex;
  1353. if (this.isSelected(cell)) {
  1354. this._selectionChanged.emit(void 0);
  1355. }
  1356. }
  1357. /**
  1358. * Handle a new model.
  1359. */
  1360. protected onModelChanged(
  1361. oldValue: INotebookModel,
  1362. newValue: INotebookModel
  1363. ): void {
  1364. super.onModelChanged(oldValue, newValue);
  1365. // Try to set the active cell index to 0.
  1366. // It will be set to `-1` if there is no new model or the model is empty.
  1367. this.activeCellIndex = 0;
  1368. }
  1369. /**
  1370. * Handle edge request signals from cells.
  1371. */
  1372. private _onEdgeRequest(
  1373. editor: CodeEditor.IEditor,
  1374. location: CodeEditor.EdgeLocation
  1375. ): void {
  1376. const prev = this.activeCellIndex;
  1377. if (location === 'top') {
  1378. this.activeCellIndex--;
  1379. // Move the cursor to the first position on the last line.
  1380. if (this.activeCellIndex < prev) {
  1381. const editor = this.activeCell!.editor;
  1382. const lastLine = editor.lineCount - 1;
  1383. editor.setCursorPosition({ line: lastLine, column: 0 });
  1384. }
  1385. } else if (location === 'bottom') {
  1386. this.activeCellIndex++;
  1387. // Move the cursor to the first character.
  1388. if (this.activeCellIndex > prev) {
  1389. const editor = this.activeCell!.editor;
  1390. editor.setCursorPosition({ line: 0, column: 0 });
  1391. }
  1392. }
  1393. this.mode = 'edit';
  1394. }
  1395. /**
  1396. * Ensure that the notebook has proper focus.
  1397. */
  1398. private _ensureFocus(force = false): void {
  1399. const activeCell = this.activeCell;
  1400. if (this.mode === 'edit' && activeCell) {
  1401. if (!activeCell.editor.hasFocus()) {
  1402. activeCell.editor.focus();
  1403. }
  1404. }
  1405. if (force && !this.node.contains(document.activeElement)) {
  1406. this.node.focus();
  1407. }
  1408. }
  1409. /**
  1410. * Find the cell index containing the target html element.
  1411. *
  1412. * #### Notes
  1413. * Returns -1 if the cell is not found.
  1414. */
  1415. private _findCell(node: HTMLElement): number {
  1416. // Trace up the DOM hierarchy to find the root cell node.
  1417. // Then find the corresponding child and select it.
  1418. let n: HTMLElement | null = node;
  1419. while (n && n !== this.node) {
  1420. if (n.classList.contains(NB_CELL_CLASS)) {
  1421. const i = ArrayExt.findFirstIndex(
  1422. this.widgets,
  1423. widget => widget.node === n
  1424. );
  1425. if (i !== -1) {
  1426. return i;
  1427. }
  1428. break;
  1429. }
  1430. n = n.parentElement;
  1431. }
  1432. return -1;
  1433. }
  1434. /**
  1435. * Find the target of html mouse event and cell index containing this target.
  1436. *
  1437. * #### Notes
  1438. * Returned index is -1 if the cell is not found.
  1439. */
  1440. private _findEventTargetAndCell(event: MouseEvent): [HTMLElement, number] {
  1441. let target = event.target as HTMLElement;
  1442. let index = this._findCell(target);
  1443. if (index === -1) {
  1444. // `event.target` sometimes gives an orphaned node in Firefox 57, which
  1445. // can have `null` anywhere in its parent line. If we fail to find a cell
  1446. // using `event.target`, try again using a target reconstructed from the
  1447. // position of the click event.
  1448. target = document.elementFromPoint(
  1449. event.clientX,
  1450. event.clientY
  1451. ) as HTMLElement;
  1452. index = this._findCell(target);
  1453. }
  1454. return [target, index];
  1455. }
  1456. /**
  1457. * Handle `contextmenu` event.
  1458. */
  1459. private _evtContextMenuCapture(event: PointerEvent): void {
  1460. // Allow the event to propagate un-modified if the user
  1461. // is holding the shift-key (and probably requesting
  1462. // the native context menu).
  1463. if (event.shiftKey) {
  1464. return;
  1465. }
  1466. const [target, index] = this._findEventTargetAndCell(event);
  1467. const widget = this.widgets[index];
  1468. if (widget && widget.editorWidget.node.contains(target)) {
  1469. // Prevent CodeMirror from focusing the editor.
  1470. // TODO: find an editor-agnostic solution.
  1471. event.preventDefault();
  1472. }
  1473. }
  1474. /**
  1475. * Handle `mousedown` event in the capture phase for the widget.
  1476. */
  1477. private _evtMouseDownCapture(event: MouseEvent): void {
  1478. const { button, shiftKey } = event;
  1479. const [target, index] = this._findEventTargetAndCell(event);
  1480. const widget = this.widgets[index];
  1481. // On OS X, the context menu may be triggered with ctrl-left-click. In
  1482. // Firefox, ctrl-left-click gives an event with button 2, but in Chrome,
  1483. // ctrl-left-click gives an event with button 0 with the ctrl modifier.
  1484. if (
  1485. button === 2 &&
  1486. !shiftKey &&
  1487. widget &&
  1488. widget.editorWidget.node.contains(target)
  1489. ) {
  1490. this.mode = 'command';
  1491. // Prevent CodeMirror from focusing the editor.
  1492. // TODO: find an editor-agnostic solution.
  1493. event.preventDefault();
  1494. }
  1495. }
  1496. /**
  1497. * Handle `mousedown` events for the widget.
  1498. */
  1499. private _evtMouseDown(event: MouseEvent): void {
  1500. const { button, shiftKey } = event;
  1501. // We only handle main or secondary button actions.
  1502. if (!(button === 0 || button === 2)) {
  1503. return;
  1504. }
  1505. // Shift right-click gives the browser default behavior.
  1506. if (shiftKey && button === 2) {
  1507. return;
  1508. }
  1509. const [target, index] = this._findEventTargetAndCell(event);
  1510. const widget = this.widgets[index];
  1511. let targetArea: 'input' | 'prompt' | 'cell' | 'notebook';
  1512. if (widget) {
  1513. if (widget.editorWidget.node.contains(target)) {
  1514. targetArea = 'input';
  1515. } else if (widget.promptNode.contains(target)) {
  1516. targetArea = 'prompt';
  1517. } else {
  1518. targetArea = 'cell';
  1519. }
  1520. } else {
  1521. targetArea = 'notebook';
  1522. }
  1523. // Make sure we go to command mode if the click isn't in the cell editor If
  1524. // we do click in the cell editor, the editor handles the focus event to
  1525. // switch to edit mode.
  1526. if (targetArea !== 'input') {
  1527. this.mode = 'command';
  1528. }
  1529. if (targetArea === 'notebook') {
  1530. this.deselectAll();
  1531. } else if (targetArea === 'prompt' || targetArea === 'cell') {
  1532. // We don't want to prevent the default selection behavior
  1533. // if there is currently text selected in an output.
  1534. const hasSelection = (window.getSelection() ?? '').toString() !== '';
  1535. if (button === 0 && shiftKey && !hasSelection) {
  1536. // Prevent browser selecting text in prompt or output
  1537. event.preventDefault();
  1538. // Shift-click - extend selection
  1539. try {
  1540. this.extendContiguousSelectionTo(index);
  1541. } catch (e) {
  1542. console.error(e);
  1543. this.deselectAll();
  1544. return;
  1545. }
  1546. // Enter selecting mode
  1547. this._mouseMode = 'select';
  1548. document.addEventListener('mouseup', this, true);
  1549. document.addEventListener('mousemove', this, true);
  1550. } else if (button === 0 && !shiftKey) {
  1551. // Prepare to start a drag if we are on the drag region.
  1552. if (targetArea === 'prompt') {
  1553. // Prepare for a drag start
  1554. this._dragData = {
  1555. pressX: event.clientX,
  1556. pressY: event.clientY,
  1557. index: index
  1558. };
  1559. // Enter possible drag mode
  1560. this._mouseMode = 'couldDrag';
  1561. document.addEventListener('mouseup', this, true);
  1562. document.addEventListener('mousemove', this, true);
  1563. event.preventDefault();
  1564. }
  1565. if (!this.isSelectedOrActive(widget)) {
  1566. this.deselectAll();
  1567. this.activeCellIndex = index;
  1568. }
  1569. } else if (button === 2) {
  1570. if (!this.isSelectedOrActive(widget)) {
  1571. this.deselectAll();
  1572. this.activeCellIndex = index;
  1573. }
  1574. event.preventDefault();
  1575. }
  1576. } else if (targetArea === 'input') {
  1577. if (button === 2 && !this.isSelectedOrActive(widget)) {
  1578. this.deselectAll();
  1579. this.activeCellIndex = index;
  1580. }
  1581. }
  1582. // If we didn't set focus above, make sure we get focus now.
  1583. this._ensureFocus(true);
  1584. }
  1585. /**
  1586. * Handle the `'mouseup'` event on the document.
  1587. */
  1588. private _evtDocumentMouseup(event: MouseEvent): void {
  1589. event.preventDefault();
  1590. event.stopPropagation();
  1591. // Remove the event listeners we put on the document
  1592. document.removeEventListener('mousemove', this, true);
  1593. document.removeEventListener('mouseup', this, true);
  1594. if (this._mouseMode === 'couldDrag') {
  1595. // We didn't end up dragging if we are here, so treat it as a click event.
  1596. const [, index] = this._findEventTargetAndCell(event);
  1597. this.deselectAll();
  1598. this.activeCellIndex = index;
  1599. }
  1600. this._mouseMode = null;
  1601. }
  1602. /**
  1603. * Handle the `'mousemove'` event for the widget.
  1604. */
  1605. private _evtDocumentMousemove(event: MouseEvent): void {
  1606. event.preventDefault();
  1607. event.stopPropagation();
  1608. // If in select mode, update the selection
  1609. switch (this._mouseMode) {
  1610. case 'select':
  1611. const target = event.target as HTMLElement;
  1612. const index = this._findCell(target);
  1613. if (index !== -1) {
  1614. this.extendContiguousSelectionTo(index);
  1615. }
  1616. break;
  1617. case 'couldDrag':
  1618. // Check for a drag initialization.
  1619. const data = this._dragData!;
  1620. const dx = Math.abs(event.clientX - data.pressX);
  1621. const dy = Math.abs(event.clientY - data.pressY);
  1622. if (dx >= DRAG_THRESHOLD || dy >= DRAG_THRESHOLD) {
  1623. this._mouseMode = null;
  1624. this._startDrag(data.index, event.clientX, event.clientY);
  1625. }
  1626. break;
  1627. default:
  1628. break;
  1629. }
  1630. }
  1631. /**
  1632. * Handle the `'lm-dragenter'` event for the widget.
  1633. */
  1634. private _evtDragEnter(event: IDragEvent): void {
  1635. if (!event.mimeData.hasData(JUPYTER_CELL_MIME)) {
  1636. return;
  1637. }
  1638. event.preventDefault();
  1639. event.stopPropagation();
  1640. const target = event.target as HTMLElement;
  1641. const index = this._findCell(target);
  1642. if (index === -1) {
  1643. return;
  1644. }
  1645. const widget = (this.layout as PanelLayout).widgets[index];
  1646. widget.node.classList.add(DROP_TARGET_CLASS);
  1647. }
  1648. /**
  1649. * Handle the `'lm-dragleave'` event for the widget.
  1650. */
  1651. private _evtDragLeave(event: IDragEvent): void {
  1652. if (!event.mimeData.hasData(JUPYTER_CELL_MIME)) {
  1653. return;
  1654. }
  1655. event.preventDefault();
  1656. event.stopPropagation();
  1657. const elements = this.node.getElementsByClassName(DROP_TARGET_CLASS);
  1658. if (elements.length) {
  1659. (elements[0] as HTMLElement).classList.remove(DROP_TARGET_CLASS);
  1660. }
  1661. }
  1662. /**
  1663. * Handle the `'lm-dragover'` event for the widget.
  1664. */
  1665. private _evtDragOver(event: IDragEvent): void {
  1666. if (!event.mimeData.hasData(JUPYTER_CELL_MIME)) {
  1667. return;
  1668. }
  1669. event.preventDefault();
  1670. event.stopPropagation();
  1671. event.dropAction = event.proposedAction;
  1672. const elements = this.node.getElementsByClassName(DROP_TARGET_CLASS);
  1673. if (elements.length) {
  1674. (elements[0] as HTMLElement).classList.remove(DROP_TARGET_CLASS);
  1675. }
  1676. const target = event.target as HTMLElement;
  1677. const index = this._findCell(target);
  1678. if (index === -1) {
  1679. return;
  1680. }
  1681. const widget = (this.layout as PanelLayout).widgets[index];
  1682. widget.node.classList.add(DROP_TARGET_CLASS);
  1683. }
  1684. /**
  1685. * Handle the `'lm-drop'` event for the widget.
  1686. */
  1687. private _evtDrop(event: IDragEvent): void {
  1688. if (!event.mimeData.hasData(JUPYTER_CELL_MIME)) {
  1689. return;
  1690. }
  1691. event.preventDefault();
  1692. event.stopPropagation();
  1693. if (event.proposedAction === 'none') {
  1694. event.dropAction = 'none';
  1695. return;
  1696. }
  1697. let target = event.target as HTMLElement;
  1698. while (target && target.parentElement) {
  1699. if (target.classList.contains(DROP_TARGET_CLASS)) {
  1700. target.classList.remove(DROP_TARGET_CLASS);
  1701. break;
  1702. }
  1703. target = target.parentElement;
  1704. }
  1705. // Model presence should be checked before calling event handlers
  1706. const model = this.model!;
  1707. const source: Notebook = event.source;
  1708. if (source === this) {
  1709. // Handle the case where we are moving cells within
  1710. // the same notebook.
  1711. event.dropAction = 'move';
  1712. const toMove: Cell[] = event.mimeData.getData('internal:cells');
  1713. // Compute the to/from indices for the move.
  1714. let fromIndex = ArrayExt.firstIndexOf(this.widgets, toMove[0]);
  1715. let toIndex = this._findCell(target);
  1716. // This check is needed for consistency with the view.
  1717. if (toIndex !== -1 && toIndex > fromIndex) {
  1718. toIndex -= 1;
  1719. } else if (toIndex === -1) {
  1720. // If the drop is within the notebook but not on any cell,
  1721. // most often this means it is past the cell areas, so
  1722. // set it to move the cells to the end of the notebook.
  1723. toIndex = this.widgets.length - 1;
  1724. }
  1725. // Don't move if we are within the block of selected cells.
  1726. if (toIndex >= fromIndex && toIndex < fromIndex + toMove.length) {
  1727. return;
  1728. }
  1729. // Move the cells one by one
  1730. model.cells.beginCompoundOperation();
  1731. if (fromIndex < toIndex) {
  1732. each(toMove, cellWidget => {
  1733. model.cells.move(fromIndex, toIndex);
  1734. });
  1735. } else if (fromIndex > toIndex) {
  1736. each(toMove, cellWidget => {
  1737. model.cells.move(fromIndex++, toIndex++);
  1738. });
  1739. }
  1740. model.cells.endCompoundOperation();
  1741. } else {
  1742. // Handle the case where we are copying cells between
  1743. // notebooks.
  1744. event.dropAction = 'copy';
  1745. // Find the target cell and insert the copied cells.
  1746. let index = this._findCell(target);
  1747. if (index === -1) {
  1748. index = this.widgets.length;
  1749. }
  1750. const start = index;
  1751. const values = event.mimeData.getData(JUPYTER_CELL_MIME);
  1752. const factory = model.contentFactory;
  1753. // Insert the copies of the original cells.
  1754. model.cells.beginCompoundOperation();
  1755. each(values, (cell: nbformat.ICell) => {
  1756. let value: ICellModel;
  1757. switch (cell.cell_type) {
  1758. case 'code':
  1759. value = factory.createCodeCell({ cell });
  1760. break;
  1761. case 'markdown':
  1762. value = factory.createMarkdownCell({ cell });
  1763. break;
  1764. default:
  1765. value = factory.createRawCell({ cell });
  1766. break;
  1767. }
  1768. model.cells.insert(index++, value);
  1769. });
  1770. model.cells.endCompoundOperation();
  1771. // Select the inserted cells.
  1772. this.deselectAll();
  1773. this.activeCellIndex = start;
  1774. this.extendContiguousSelectionTo(index - 1);
  1775. }
  1776. }
  1777. /**
  1778. * Start a drag event.
  1779. */
  1780. private _startDrag(index: number, clientX: number, clientY: number): void {
  1781. const cells = this.model!.cells;
  1782. const selected: nbformat.ICell[] = [];
  1783. const toMove: Cell[] = [];
  1784. each(this.widgets, (widget, i) => {
  1785. const cell = cells.get(i);
  1786. if (this.isSelectedOrActive(widget)) {
  1787. widget.addClass(DROP_SOURCE_CLASS);
  1788. selected.push(cell.toJSON());
  1789. toMove.push(widget);
  1790. }
  1791. });
  1792. const activeCell = this.activeCell;
  1793. let dragImage: HTMLElement | null = null;
  1794. let countString: string;
  1795. if (activeCell?.model.type === 'code') {
  1796. const executionCount = (activeCell.model as ICodeCellModel)
  1797. .executionCount;
  1798. countString = ' ';
  1799. if (executionCount) {
  1800. countString = executionCount.toString();
  1801. }
  1802. } else {
  1803. countString = '';
  1804. }
  1805. // Create the drag image.
  1806. dragImage = Private.createDragImage(
  1807. selected.length,
  1808. countString,
  1809. activeCell?.model.value.text.split('\n')[0].slice(0, 26) ?? ''
  1810. );
  1811. // Set up the drag event.
  1812. this._drag = new Drag({
  1813. mimeData: new MimeData(),
  1814. dragImage,
  1815. supportedActions: 'copy-move',
  1816. proposedAction: 'copy',
  1817. source: this
  1818. });
  1819. this._drag.mimeData.setData(JUPYTER_CELL_MIME, selected);
  1820. // Add mimeData for the fully reified cell widgets, for the
  1821. // case where the target is in the same notebook and we
  1822. // can just move the cells.
  1823. this._drag.mimeData.setData('internal:cells', toMove);
  1824. // Add mimeData for the text content of the selected cells,
  1825. // allowing for drag/drop into plain text fields.
  1826. const textContent = toMove.map(cell => cell.model.value.text).join('\n');
  1827. this._drag.mimeData.setData('text/plain', textContent);
  1828. // Remove mousemove and mouseup listeners and start the drag.
  1829. document.removeEventListener('mousemove', this, true);
  1830. document.removeEventListener('mouseup', this, true);
  1831. this._mouseMode = null;
  1832. void this._drag.start(clientX, clientY).then(action => {
  1833. if (this.isDisposed) {
  1834. return;
  1835. }
  1836. this._drag = null;
  1837. each(toMove, widget => {
  1838. widget.removeClass(DROP_SOURCE_CLASS);
  1839. });
  1840. });
  1841. }
  1842. /**
  1843. * Handle `focus` events for the widget.
  1844. */
  1845. private _evtFocusIn(event: MouseEvent): void {
  1846. const target = event.target as HTMLElement;
  1847. const index = this._findCell(target);
  1848. if (index !== -1) {
  1849. const widget = this.widgets[index];
  1850. // If the editor itself does not have focus, ensure command mode.
  1851. if (!widget.editorWidget.node.contains(target)) {
  1852. this.mode = 'command';
  1853. }
  1854. this.activeCellIndex = index;
  1855. // If the editor has focus, ensure edit mode.
  1856. const node = widget.editorWidget.node;
  1857. if (node.contains(target)) {
  1858. this.mode = 'edit';
  1859. }
  1860. } else {
  1861. // No cell has focus, ensure command mode.
  1862. this.mode = 'command';
  1863. }
  1864. if (this.mode === 'command' && target !== this.node) {
  1865. delete this.node.dataset[CODE_RUNNER];
  1866. } else {
  1867. this.node.dataset[CODE_RUNNER] = 'true';
  1868. }
  1869. }
  1870. /**
  1871. * Handle `focusout` events for the notebook.
  1872. */
  1873. private _evtFocusOut(event: MouseEvent): void {
  1874. const relatedTarget = event.relatedTarget as HTMLElement;
  1875. // Bail if the window is losing focus, to preserve edit mode. This test
  1876. // assumes that we explicitly focus things rather than calling blur()
  1877. if (!relatedTarget) {
  1878. return;
  1879. }
  1880. // Bail if the item gaining focus is another cell,
  1881. // and we should not be entering command mode.
  1882. const index = this._findCell(relatedTarget);
  1883. if (index !== -1) {
  1884. const widget = this.widgets[index];
  1885. if (widget.editorWidget.node.contains(relatedTarget)) {
  1886. return;
  1887. }
  1888. }
  1889. // Otherwise enter command mode if not already.
  1890. if (this.mode !== 'command') {
  1891. this.mode = 'command';
  1892. // Switching to command mode currently focuses the notebook element, so
  1893. // refocus the relatedTarget so the focus actually switches as intended.
  1894. if (relatedTarget) {
  1895. relatedTarget.focus();
  1896. }
  1897. }
  1898. }
  1899. /**
  1900. * Handle `dblclick` events for the widget.
  1901. */
  1902. private _evtDblClick(event: MouseEvent): void {
  1903. const model = this.model;
  1904. if (!model) {
  1905. return;
  1906. }
  1907. this.deselectAll();
  1908. const [target, index] = this._findEventTargetAndCell(event);
  1909. if (index === -1) {
  1910. return;
  1911. }
  1912. this.activeCellIndex = index;
  1913. if (model.cells.get(index).type === 'markdown') {
  1914. const widget = this.widgets[index] as MarkdownCell;
  1915. widget.rendered = false;
  1916. } else if (target.localName === 'img') {
  1917. target.classList.toggle(UNCONFINED_CLASS);
  1918. }
  1919. }
  1920. /**
  1921. * Remove selections from inactive cells to avoid
  1922. * spurious cursors.
  1923. */
  1924. private _trimSelections(): void {
  1925. for (let i = 0; i < this.widgets.length; i++) {
  1926. if (i !== this._activeCellIndex) {
  1927. const cell = this.widgets[i];
  1928. cell.model.selections.delete(cell.editor.uuid);
  1929. }
  1930. }
  1931. }
  1932. private _activeCellIndex = -1;
  1933. private _activeCell: Cell | null = null;
  1934. private _mode: NotebookMode = 'command';
  1935. private _drag: Drag | null = null;
  1936. private _fragment = '';
  1937. private _dragData: {
  1938. pressX: number;
  1939. pressY: number;
  1940. index: number;
  1941. } | null = null;
  1942. private _mouseMode: 'select' | 'couldDrag' | null = null;
  1943. private _activeCellChanged = new Signal<this, Cell>(this);
  1944. private _stateChanged = new Signal<this, IChangedArgs<any>>(this);
  1945. private _selectionChanged = new Signal<this, void>(this);
  1946. // Attributes for optimized cell refresh:
  1947. private _cellLayoutStateCache?: { width: number };
  1948. private _checkCacheOnNextResize = false;
  1949. }
  1950. /**
  1951. * The namespace for the `Notebook` class statics.
  1952. */
  1953. export namespace Notebook {
  1954. /**
  1955. * An options object for initializing a notebook widget.
  1956. */
  1957. export interface IOptions extends StaticNotebook.IOptions {}
  1958. /**
  1959. * The content factory for the notebook widget.
  1960. */
  1961. export interface IContentFactory extends StaticNotebook.IContentFactory {}
  1962. /**
  1963. * The default implementation of a notebook content factory..
  1964. *
  1965. * #### Notes
  1966. * Override methods on this class to customize the default notebook factory
  1967. * methods that create notebook content.
  1968. */
  1969. export class ContentFactory extends StaticNotebook.ContentFactory {}
  1970. /**
  1971. * A namespace for the notebook content factory.
  1972. */
  1973. export namespace ContentFactory {
  1974. /**
  1975. * An options object for initializing a notebook content factory.
  1976. */
  1977. export interface IOptions extends StaticNotebook.ContentFactory.IOptions {}
  1978. }
  1979. export const defaultContentFactory: IContentFactory = new ContentFactory();
  1980. }
  1981. /**
  1982. * A namespace for private data.
  1983. */
  1984. namespace Private {
  1985. /**
  1986. * An attached property for the selected state of a cell.
  1987. */
  1988. export const selectedProperty = new AttachedProperty<Cell, boolean>({
  1989. name: 'selected',
  1990. create: () => false
  1991. });
  1992. /**
  1993. * A custom panel layout for the notebook.
  1994. */
  1995. export class NotebookPanelLayout extends PanelLayout {
  1996. /**
  1997. * A message handler invoked on an `'update-request'` message.
  1998. *
  1999. * #### Notes
  2000. * This is a reimplementation of the base class method,
  2001. * and is a no-op.
  2002. */
  2003. protected onUpdateRequest(msg: Message): void {
  2004. // This is a no-op.
  2005. }
  2006. }
  2007. /**
  2008. * Create a cell drag image.
  2009. */
  2010. export function createDragImage(
  2011. count: number,
  2012. promptNumber: string,
  2013. cellContent: string
  2014. ): HTMLElement {
  2015. if (count > 1) {
  2016. if (promptNumber !== '') {
  2017. return VirtualDOM.realize(
  2018. h.div(
  2019. h.div(
  2020. { className: DRAG_IMAGE_CLASS },
  2021. h.span(
  2022. { className: CELL_DRAG_PROMPT_CLASS },
  2023. '[' + promptNumber + ']:'
  2024. ),
  2025. h.span({ className: CELL_DRAG_CONTENT_CLASS }, cellContent)
  2026. ),
  2027. h.div({ className: CELL_DRAG_MULTIPLE_BACK }, '')
  2028. )
  2029. );
  2030. } else {
  2031. return VirtualDOM.realize(
  2032. h.div(
  2033. h.div(
  2034. { className: DRAG_IMAGE_CLASS },
  2035. h.span({ className: CELL_DRAG_PROMPT_CLASS }),
  2036. h.span({ className: CELL_DRAG_CONTENT_CLASS }, cellContent)
  2037. ),
  2038. h.div({ className: CELL_DRAG_MULTIPLE_BACK }, '')
  2039. )
  2040. );
  2041. }
  2042. } else {
  2043. if (promptNumber !== '') {
  2044. return VirtualDOM.realize(
  2045. h.div(
  2046. h.div(
  2047. { className: `${DRAG_IMAGE_CLASS} ${SINGLE_DRAG_IMAGE_CLASS}` },
  2048. h.span(
  2049. { className: CELL_DRAG_PROMPT_CLASS },
  2050. '[' + promptNumber + ']:'
  2051. ),
  2052. h.span({ className: CELL_DRAG_CONTENT_CLASS }, cellContent)
  2053. )
  2054. )
  2055. );
  2056. } else {
  2057. return VirtualDOM.realize(
  2058. h.div(
  2059. h.div(
  2060. { className: `${DRAG_IMAGE_CLASS} ${SINGLE_DRAG_IMAGE_CLASS}` },
  2061. h.span({ className: CELL_DRAG_PROMPT_CLASS }),
  2062. h.span({ className: CELL_DRAG_CONTENT_CLASS }, cellContent)
  2063. )
  2064. )
  2065. );
  2066. }
  2067. }
  2068. }
  2069. /**
  2070. * Process the `IOptions` passed to the notebook widget.
  2071. *
  2072. * #### Notes
  2073. * This defaults the content factory to that in the `Notebook` namespace.
  2074. */
  2075. export function processNotebookOptions(options: Notebook.IOptions) {
  2076. if (options.contentFactory) {
  2077. return options;
  2078. } else {
  2079. return {
  2080. rendermime: options.rendermime,
  2081. languagePreference: options.languagePreference,
  2082. contentFactory: Notebook.defaultContentFactory,
  2083. mimeTypeService: options.mimeTypeService
  2084. };
  2085. }
  2086. }
  2087. }