All files / src/notebook presenter.ts

95.44% Statements 419/439
86.8% Branches 204/235
100% Functions 40/40
95.43% Lines 418/438

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929                                                                                    40x 40x       34x 34x 34x                 34x   34x 34x 34x     34x 34x 34x 34x 34x       3410x 2458x   952x       364x 364x       76x 76x 48x 48x   76x 76x 76x   76x   76x 48x 48x 48x               80x 80x 80x   162x       162x   80x   80x 80x 80x     80x 80x 80x       34x       144x 144x 142x   142x   2x       20x   20x       20x       20x 4x     4x           16x     16x         20x 20x   20x       144x 144x 142x 142x   2x       20x 20x       20x       20x 4x     4x           16x     16x         20x 20x   20x       180x 180x 2x   178x       36x   36x     36x       56x 56x 56x 6x 6x 188x 6x           34x 34x       34x     34x 8x 8x   8x     4x 4x   4x     4x       10x   10x     10x 10x 10x 126x 126x 126x 10x 10x             1032x       1032x 1032x         34x 136x           34x 68x 68x                   1488x 1488x 1488x 1488x 1488x 1488x 1488x 16x 16x 16x 40x 40x           1488x 1478x 1478x             10x       34x         446x   446x     446x   446x 446x   446x                     446x 446x   446x 446x                               76x 28x   48x 48x 48x 48x 1020x 1020x 1020x 1020x         1120x   1120x     1098x 1098x   1098x   1098x   1098x   1098x 962x 962x 16x       1098x   1098x 152x 136x 136x 136x   16x 40x 40x 40x 16x           962x       962x   962x   962x   962x   962x   962x   962x 20140x   20140x 152x 152x 152x 152x       19988x 19988x 2634x 2634x   17354x   19988x 3394x 3394x 12x     16594x         962x       962x 962x 4x         160x 160x     160x   160x 160x 160x       12x     200x 44x         378x 378x 378x 140x   238x         80x     80x 8x   80x 8x   80x 80x 80x 80x         3042x                   3042x                                     384x   384x     384x         7062x         11806x             1098x       1098x   1098x 584x     514x       514x               514x 2894x 2894x 2866x       514x 514x         514x 3084x     514x 514x   514x 514x 514x 514x 514x   514x 3042x 3042x 3042x 2922x   120x 120x 400x 116x 116x   284x   120x 120x   44x 44x     36x 52x 8x 8x     36x     20x 36x 8x 8x     20x     20x 80x 20x 20x     20x         120x 808x 296x 296x 52x   244x 244x           514x   514x                                 3032x     3032x 3032x 2484x   548x 548x               548x 548x 3042x 3042x 3042x 3042x 120x 2922x 456x   3042x 3042x 3042x 3042x 3042x 3042x 3042x   148x   820x 366x 660x   366x 366x 366x 366x     366x 366x 454x 16x 16x 16x 438x 96x 96x 96x 342x 342x 342x 342x   820x 1584x   820x 820x 820x     820x     820x   718x   88x 88x 312x 312x 312x     630x 40x 40x 590x 72x 72x 518x 32x 32x 32x 32x     718x 718x 718x 718x 718x 718x 718x 718x   252x 4x 4x 248x 208x 208x 40x 40x 40x 40x 40x   40x   252x 252x 252x 252x 252x 252x 252x   1076x 4360x   1076x 1076x 112x 112x 964x 700x 700x 264x 104x 104x 160x 160x 160x   1076x 1076x 1076x 1076x 1076x 1076x   28x 28x   28x   2894x     548x   548x                                                        
import { ISettings, Stylist } from '@deathbeds/jupyterlab-fonts';
import type { GlobalStyles } from '@deathbeds/jupyterlab-fonts/lib/_schema';
import {
  getCellMetadata,
  getPanelMetadata,
  setCellMetadata,
  deleteCellMetadata,
} from '@deathbeds/jupyterlab-fonts/lib/labcompat';
import { Cell, ICellModel } from '@jupyterlab/cells';
import {
  INotebookModel,
  INotebookTools,
  Notebook,
  NotebookPanel,
} from '@jupyterlab/notebook';
import { CommandRegistry } from '@lumino/commands';
import { JSONExt } from '@lumino/coreutils';
import { ElementExt } from '@lumino/domutils';
import { ISignal, Signal } from '@lumino/signaling';
import { Widget } from '@lumino/widgets';
 
import { getCellModels } from '../labcompat';
import {
  DIRECTION,
  IPresenter,
  TDirection,
  CSS,
  IDeckManager,
  TSlideType,
  EMOJI,
  CommandIds,
  DIRECTION_KEYS,
  TCanGoDirection,
  COMPOUND_KEYS,
  META,
  ICellDeckMetadata,
  TLayerScope,
} from '../tokens';
import type { Layover } from '../tools/layover';
 
import { NotebookMetaTools } from './metadata';
 
const emptyMap = Object.freeze(new Map());
const { emptyObject, emptyArray } = JSONExt;
 
/** An presenter for working with notebooks */
export class NotebookPresenter implements IPresenter<NotebookPanel> {
  public readonly id = 'notebooks';
  public readonly rank = 100;
  public readonly capabilities = {
    layout: true,
    slideType: true,
    layerScope: true,
    stylePart: true,
    styleDeck: true,
  };
 
  protected _manager: IDeckManager;
  protected _previousActiveCellIndex: number = -1;
  protected _commands: CommandRegistry;
  protected _activeChanged = new Signal<IPresenter<NotebookPanel>, void>(this);
  protected _extents = new Map<INotebookModel, NotebookPresenter.TExtentMap>();
  protected _layers = new Map<INotebookModel, NotebookPresenter.TLayerMap>();
 
  constructor(options: NotebookPresenter.IOptions) {
    this._manager = options.manager;
    this._commands = options.commands;
    this._makeDeckTools(options.notebookTools);
    this._addKeyBindings();
    this._addWindowListeners();
  }
 
  public accepts(widget: Widget): NotebookPanel | null {
    if (widget instanceof NotebookPanel) {
      return widget;
    }
    return null;
  }
 
  public async style(panel: NotebookPanel): Promise<void> {
    panel.addClass(CSS.deck);
    this._manager.cacheStyle(panel.node, panel.content.node);
  }
 
  public async stop(panel: NotebookPanel): Promise<void> {
    const notebookModel = panel.content.model;
    if (notebookModel) {
      this._extents.delete(notebookModel);
      this._layers.delete(notebookModel);
    }
    this._removeStyle(panel);
    panel.content.activeCellChanged.disconnect(this._onActiveCellChanged, this);
    panel.update();
 
    const { activeCell } = panel.content;
 
    if (activeCell) {
      setTimeout(() => {
        if (this._manager.activeWidget !== panel) {
          return;
        }
        ElementExt.scrollIntoViewIfNeeded(panel.content.node, activeCell.node);
      }, 100);
    }
  }
 
  public async start(panel: NotebookPanel): Promise<void> {
    const { model, content: notebook } = panel;
    if (model) {
      const _watchPanel = async (change: any) => {
        /* istanbul ignore if */
        if (panel.isDisposed) {
          model.stateChanged.disconnect(_watchPanel);
          return;
        }
        await this._onActiveCellChanged(panel.content);
      };
      model.stateChanged.connect(_watchPanel);
    }
    const { model: notebookModel } = notebook;
    if (notebookModel) {
      notebookModel.contentChanged.connect(this._onNotebookContentChanged, this);
    }
 
    panel.content.activeCellChanged.connect(this._onActiveCellChanged, this);
    await this._onActiveCellChanged(panel.content);
    this._forceStyle();
  }
 
  public get activeChanged(): ISignal<IPresenter<NotebookPanel>, void> {
    return this._activeChanged;
  }
 
  public getSlideType(panel: NotebookPanel): TSlideType {
    let { activeCell } = panel.content;
    if (activeCell) {
      const meta = (getCellMetadata(activeCell.model, META.slideshow) ||
        emptyObject) as any;
      return (meta[META.slideType] || null) as TSlideType;
    }
    return null;
  }
 
  public setSlideType(panel: NotebookPanel, slideType: TSlideType): void {
    let { activeCell } = panel.content;
    /* istanbul ignore if */
    if (!activeCell) {
      return;
    }
    let oldMeta =
      ((getCellMetadata(activeCell.model, META.slideshow) || emptyObject) as Record<
        string,
        any
      >) || null;
    if (slideType == null) {
      Iif (oldMeta == null) {
        deleteCellMetadata(activeCell.model, META.slideshow);
      } else {
        setCellMetadata(activeCell.model, META.slideshow, {
          ...oldMeta,
          [META.slideType]: slideType,
        });
      }
    } else {
      Iif (oldMeta == null) {
        oldMeta = {};
      }
      setCellMetadata(activeCell.model, META.slideshow, {
        ...oldMeta,
        [META.slideType]: slideType,
      });
    }
    if (panel.content.model) {
      this._onNotebookContentChanged(panel.content.model);
    }
    void this._onActiveCellChanged(panel.content);
  }
 
  public getLayerScope(panel: NotebookPanel): string | null {
    let { activeCell } = panel.content;
    if (activeCell) {
      const meta = (getCellMetadata(activeCell.model, META.deck) || emptyObject) as any;
      return (meta[META.layer] || null) as TLayerScope;
    }
    return null;
  }
 
  public setLayerScope(panel: NotebookPanel, layerScope: TLayerScope): void {
    let { activeCell } = panel.content;
    Iif (!activeCell) {
      return;
    }
    let oldMeta =
      ((getCellMetadata(activeCell.model, META.deck) || emptyObject) as Record<
        string,
        any
      >) || null;
    if (layerScope == null) {
      Iif (oldMeta == null) {
        deleteCellMetadata(activeCell.model, META.deck);
      } else {
        setCellMetadata(activeCell.model, META.deck, {
          ...oldMeta,
          [META.layer]: layerScope,
        });
      }
    } else {
      Iif (oldMeta == null) {
        oldMeta = {};
      }
      setCellMetadata(activeCell.model, META.deck, {
        ...oldMeta,
        [META.layer]: layerScope,
      });
    }
    if (panel.content.model) {
      this._onNotebookContentChanged(panel.content.model);
    }
    void this._onActiveCellChanged(panel.content);
  }
 
  public getPartStyles(panel: NotebookPanel): GlobalStyles | null {
    let { activeCell } = panel.content;
    if (!activeCell) {
      return null;
    }
    return this._getCellStyles(activeCell);
  }
 
  public setPartStyles(panel: NotebookPanel, styles: GlobalStyles | null): void {
    let { activeCell } = panel.content;
    /* istanbul ignore if */
    if (!activeCell) {
      return;
    }
    return this._setCellStyles(activeCell, styles);
  }
 
  public preparePanel(panel: NotebookPanel) {
    let notebook = panel.content;
    let oldSetFragment = notebook.setFragment;
    notebook.setFragment = async (fragment: string): Promise<void> => {
      await oldSetFragment.call(notebook, fragment);
      if (this._manager.activePresenter === this) {
        await Promise.all(notebook.widgets.map((widget) => widget.ready));
        this._activateByAnchor(notebook, fragment);
      }
    };
  }
 
  protected _makeDeckTools(notebookTools: INotebookTools) {
    const tool = new NotebookMetaTools({ manager: this._manager, notebookTools });
    notebookTools.addItem({ tool, section: 'commonToolsSection', rank: 3 });
  }
 
  protected _addWindowListeners() {
    window.addEventListener('hashchange', this._onHashChange);
  }
 
  protected _onHashChange = (event: HashChangeEvent) => {
    const { activeWidget } = this._manager;
    const panel = activeWidget && this.accepts(activeWidget);
    /* istanbul ignore if */
    if (!panel) {
      return;
    }
    const url = new URL(event.newURL);
    const { hash } = url || '#';
    /* istanbul ignore if */
    if (hash === '#') {
      return;
    }
    this._activateByAnchor(panel.content, hash);
  };
 
  protected _activateByAnchor(notebook: Notebook, fragment: string) {
    const anchored = document.getElementById(fragment.slice(1));
    /* istanbul ignore if */
    if (!anchored || !notebook.node.contains(anchored)) {
      return;
    }
    let i = -1;
    let cellCount = notebook.widgets.length;
    while (i < cellCount) {
      i++;
      let cell = notebook.widgets[i];
      if (cell.node.contains(anchored)) {
        notebook.activeCellIndex = i;
        return;
      }
    }
  }
 
  protected _onNotebookContentChanged(notebookModel: INotebookModel) {
    /* istanbul ignore if */
    if (notebookModel.isDisposed) {
      notebookModel.contentChanged.disconnect(this._onNotebookContentChanged, this);
      return;
    }
    this._extents.delete(notebookModel);
    this._layers.delete(notebookModel);
  }
 
  /** overload the stock notebook keyboard shortcuts */
  protected _addKeyBindings() {
    for (const direction of Object.values(DIRECTION)) {
      this._commands.addKeyBinding({
        command: CommandIds[direction],
        keys: DIRECTION_KEYS[direction],
        selector: `.${CSS.deck} .jp-Notebook.jp-mod-commandMode:focus`,
      });
    }
    for (const [directions, keys] of COMPOUND_KEYS.entries()) {
      const [direction, alternate] = directions;
      this._commands.addKeyBinding({
        command: CommandIds.go,
        args: { direction, alternate },
        keys,
        selector: `.${CSS.deck} .jp-Notebook.jp-mod-commandMode:focus`,
      });
    }
  }
 
  public async canGo(panel: NotebookPanel): Promise<Partial<TCanGoDirection>> {
    let { activeCellIndex, activeCell } = panel.content;
    const notebookModel = panel.content.model;
    let activeExtent: NotebookPresenter.IExtent | null = null;
    if (notebookModel) {
      const extents = this._getExtents(notebookModel);
      activeExtent = extents.get(activeCellIndex) || null;
      if (!activeExtent && activeCell) {
        let meta = this._getCellDeckMetadata(activeCell.model);
        if (meta.layer) {
          while (!activeExtent && activeCellIndex) {
            activeCellIndex--;
            activeExtent = extents.get(activeCellIndex) || null;
          }
        }
      }
    }
 
    if (activeExtent) {
      const { up, down, forward, back } = activeExtent;
      return {
        up: up != null,
        down: down != null,
        forward: forward != null,
        back: back != null,
      };
    }
    return emptyObject;
  }
 
  /** move around */
  public go = async (
    panel: NotebookPanel,
    direction: TDirection,
    alternate?: TDirection,
  ): Promise<void> => {
    const notebookModel = panel.content.model;
    /* istanbul ignore if */
    if (!notebookModel) {
      return;
    }
    let { activeCellIndex, activeCell } = panel.content;
 
    const extents = this._getExtents(notebookModel);
    let activeExtent = extents.get(activeCellIndex);
 
    Iif (!activeExtent && activeCell) {
      let meta = this._getCellDeckMetadata(activeCell.model);
      Iif (!meta.layer && direction === 'up') {
        return;
      }
      while (!activeExtent && activeCellIndex) {
        activeCellIndex--;
        activeExtent = extents.get(activeCellIndex);
      }
    }
 
    const fromExtent = activeExtent && activeExtent[direction];
    const fromExtentAlternate = alternate && activeExtent && activeExtent[alternate];
 
    if (fromExtent != null) {
      panel.content.activeCellIndex = fromExtent;
    } else Eif (fromExtentAlternate != null) {
      panel.content.activeCellIndex = fromExtentAlternate;
    } else {
      console.warn(
        EMOJI,
        this._manager.__(
          `Cannot go "%1" from cell %2`,
          direction,
          `${activeCellIndex}`,
        ),
      );
    }
  };
 
  protected _removeStyle(panel: NotebookPanel) {
    if (panel.isDisposed) {
      return;
    }
    const { _manager } = this;
    panel.removeClass(CSS.deck);
    _manager.uncacheStyle(panel.content.node, panel.node);
    for (const cell of panel.content.widgets) {
      cell.removeClass(CSS.layer);
      cell.removeClass(CSS.onScreen);
      cell.removeClass(CSS.visible);
      cell.node.setAttribute('style', '');
    }
  }
 
  protected async _onActiveCellChanged(notebook: Notebook): Promise<void> {
    const notebookModel = notebook.model;
    /* istanbul ignore if */
    if (!notebookModel || this._manager.activeWidget !== notebook.parent) {
      return;
    }
    const extents = this._getExtents(notebookModel);
    const layers = this._getLayers(notebookModel, extents);
 
    let { activeCellIndex } = notebook;
 
    let cell = getCellModels(notebookModel)[activeCellIndex];
 
    let layerIndex: number | null = null;
 
    if (cell) {
      let meta = this._getCellDeckMetadata(cell);
      if (meta && meta.layer) {
        layerIndex = activeCellIndex;
      }
    }
 
    let activeExtent = extents.get(activeCellIndex);
 
    if (!activeExtent) {
      if (layerIndex == null) {
        let offset = this._previousActiveCellIndex > activeCellIndex ? -1 : 1;
        notebook.activeCellIndex = activeCellIndex + offset;
        return;
      } else {
        while (activeCellIndex) {
          activeCellIndex--;
          activeExtent = extents.get(activeCellIndex);
          if (activeExtent) {
            break;
          }
        }
      }
    }
 
    Iif (!activeExtent) {
      return;
    }
 
    this._previousActiveCellIndex = activeCellIndex;
 
    let idx = -1;
 
    let activeLayers = layers.get(activeCellIndex) || [];
 
    idx = -1;
 
    let { layover } = this._manager;
 
    let onScreen: Layover.BasePart[] = [];
 
    for (const cell of notebook.widgets) {
      idx++;
 
      if (activeLayers.includes(idx)) {
        cell.addClass(CSS.layer);
        cell.addClass(CSS.onScreen);
        cell.addClass(CSS.visible);
        Iif (layover) {
          onScreen.push(this._toLayoutPart(cell));
        }
      } else {
        cell.removeClass(CSS.layer);
        if (activeExtent.visible.includes(idx)) {
          cell.addClass(CSS.visible);
          cell.editorWidget?.update();
        } else {
          cell.removeClass(CSS.visible);
        }
        if (activeExtent.onScreen.includes(idx)) {
          cell.addClass(CSS.onScreen);
          if (layover) {
            onScreen.push(this._toLayoutPart(cell));
          }
        } else {
          cell.removeClass(CSS.onScreen);
        }
      }
    }
 
    ElementExt.scrollIntoViewIfNeeded(
      notebook.node,
      notebook.widgets[activeCellIndex].node,
    );
    this._activeChanged.emit(void 0);
    if (this._manager.layover) {
      this._manager.layover.model.parts = onScreen;
    }
  }
 
  protected _forceStyle() {
    let panel = this._manager.activeWidget;
    Iif (!panel || !(panel instanceof NotebookPanel)) {
      return;
    }
    let stylist = (this._manager.fonts as any)._stylist as Stylist;
    let meta =
      (panel.model ? getPanelMetadata(panel.model, META.fonts) : null) || emptyObject;
    stylist.stylesheet(meta as ISettings, panel);
    this._manager.layover?.render();
  }
 
  protected _toLayoutPart(cell: Cell<ICellModel>): Layover.BasePart {
    return {
      key: cell.model.id,
      node: cell.node,
      getStyles: () => this._getCellStyles(cell),
      setStyles: (styles: GlobalStyles | null) => this._setCellStyles(cell, styles),
    };
  }
 
  protected _getCellStyles(cell: Cell<ICellModel>) {
    try {
      const meta = (getCellMetadata(cell.model, META.fonts) || emptyObject) as any;
      const styles = meta.styles[META.nullSelector][META.presentingCell];
      return styles;
    } catch {
      return emptyObject;
    }
  }
 
  protected _setCellStyles(cell: Cell<ICellModel>, styles: GlobalStyles | null) {
    let meta = {
      ...(getCellMetadata(cell.model, META.fonts) || emptyObject),
    } as ISettings;
    if (!meta.styles) {
      meta.styles = {};
    }
    if (!meta.styles[META.nullSelector]) {
      meta.styles[META.nullSelector] = {};
    }
    (meta.styles[META.nullSelector] as any)[META.presentingCell] = styles;
    setCellMetadata(cell.model, META.fonts, emptyObject);
    setCellMetadata(cell.model, META.fonts, { ...meta });
    this._forceStyle();
  }
 
  /** Get the nbconvert-compatible `slide_type` from metadata. */
  protected _getSlideType(cell: ICellModel): TSlideType {
    return (
      (getCellMetadata(cell, META.slideshow) || emptyObject)[META.slideType] || null
    );
  }
 
  protected _initExtent(
    index: number,
    slideType: TSlideType,
    extent: Partial<NotebookPresenter.IExtent> = emptyObject,
  ): NotebookPresenter.IExtent {
    return {
      parent: null,
      onScreen: [],
      visible: [],
      notes: [],
      forward: null,
      back: null,
      up: null,
      down: null,
      ...extent,
      index,
      slideType,
    };
  }
 
  protected _lastOnScreenOf(
    index: number,
    extents: NotebookPresenter.TExtentMap,
  ): null | NotebookPresenter.IExtent {
    let e = extents.get(index);
    /* istanbul ignore if */
    if (!e) {
      return null;
    }
    return extents.get(e.onScreen[0]) || null;
  }
 
  /** Get layer metadata from `jupyterlab-deck` namespace */
  protected _getCellDeckMetadata(cell: ICellModel): ICellDeckMetadata {
    return (getCellMetadata(cell, META.deck) ||
      emptyObject) as any as ICellDeckMetadata;
  }
 
  _numSort(a: number, b: number): number {
    return a - b;
  }
 
  protected _getLayers(
    notebookModel: INotebookModel | null,
    extents: NotebookPresenter.TExtentMap,
  ): NotebookPresenter.TLayerMap {
    Iif (!notebookModel) {
      return emptyMap;
    }
 
    let cachedLayers = this._layers.get(notebookModel);
 
    if (cachedLayers) {
      return cachedLayers;
    }
 
    let layers = new Map<number, number[]>();
    // layers visible on this extent
    let extentLayers: number[] | null;
 
    let extentTypes = {
      slide: [],
      subslide: [],
      fragment: [],
      _anySlide: [],
      _anyFragment: [],
      null: [],
    };
    for (let extent of extents.values()) {
      let etype = (extentTypes as any)[extent.slideType || 'null'];
      if (etype) {
        etype.push(extent.index);
      }
    }
 
    extentTypes._anySlide = [...extentTypes.slide, ...extentTypes.subslide];
    extentTypes._anyFragment = [
      ...extentTypes._anySlide,
      ...extentTypes.fragment,
      ...extentTypes.null,
    ];
    for (let key in extentTypes) {
      (extentTypes as any)[key].sort(this._numSort);
    }
 
    let extentIndexes = [...extents.keys()];
    extentIndexes.sort(this._numSort);
 
    let i = -1;
    let j = -1;
    let prev = -1;
    let start = -1;
    let end = -1;
 
    for (const cell of getCellModels(notebookModel)) {
      i++;
      let { layer } = this._getCellDeckMetadata(cell);
      if (!layer) {
        continue;
      }
      start = extentIndexes[0];
      for (j of extentIndexes) {
        if (j > i) {
          start = prev;
          break;
        }
        prev = j;
      }
      prev = end = -1;
      switch (layer) {
        case 'deck':
          end = extentIndexes.slice(-1)[0];
          break;
        case 'stack':
          // visible until the next `slide`
          for (j of extentTypes.slide) {
            if (j > start) {
              end = j - 1;
              break;
            }
          }
          break;
        case 'slide':
          // visible until the next `slide`/`subslide`
          for (j of extentTypes._anySlide) {
            if (j > start) {
              end = j - 1;
              break;
            }
          }
          break;
        case 'fragment':
          // visible until the next `fragment`
          for (j of extentTypes._anyFragment) {
            if (j > start) {
              end = j - 1;
              break;
            }
          }
          break;
        default:
          break;
      }
 
      for (let extentIndex of extentIndexes) {
        if (extentIndex >= start && extentIndex <= end) {
          extentLayers = layers.get(extentIndex) || null;
          if (extentLayers != null) {
            extentLayers.push(i);
          } else {
            extentLayers = [i];
            layers.set(extentIndex, extentLayers);
          }
        }
      }
    }
 
    this._layers.set(notebookModel, layers);
 
    return layers;
  }
 
  /** Build a cell index (not id) map of what would be on-screen(s) for a given index
   *
   * gather:
   * - the index
   * - what is forward/back/up/down
   *   - fragments advance on down|forward, reverse on up|back
   * - what is onscreen
   * - what is visible
   * - what are the notes
   */
  protected _getExtents(
    notebookModel: INotebookModel | null,
  ): NotebookPresenter.TExtentMap {
    /* istanbul ignore if */
    if (!notebookModel) {
      return emptyMap;
    }
    const cachedExtents = this._extents.get(notebookModel);
    if (cachedExtents && cachedExtents.size) {
      return cachedExtents;
    }
    const extents: NotebookPresenter.TExtentMap = new Map();
    const stacks: Record<NotebookPresenter.TStackType, NotebookPresenter.IExtent[]> = {
      slides: [],
      subslides: [],
      fragments: [],
      nulls: [],
      onScreen: [],
    };
 
    let index = -1;
    for (const cell of getCellModels(notebookModel)) {
      index++;
      let slideType = this._getSlideType(cell);
      let { layer } = this._getCellDeckMetadata(cell);
      if (layer) {
        slideType = 'skip';
      } else if (index === 0 && (slideType == null || slideType === 'subslide')) {
        slideType = 'slide';
      }
      let extent = this._initExtent(index, slideType);
      let s0: NotebookPresenter.IExtent | null = stacks.slides[0] || null;
      let ss0: NotebookPresenter.IExtent | null = stacks.subslides[0] || null;
      let f0: NotebookPresenter.IExtent | null = stacks.fragments[0] || null;
      let n0: NotebookPresenter.IExtent | null = stacks.nulls[0] || null;
      let a0 = n0 || f0 || ss0 || s0;
      switch (slideType) {
        case 'skip':
          continue;
        case null:
          if (n0) {
            for (let n of stacks.nulls) {
              n.visible.unshift(index);
            }
            if (!f0) {
              let a = ss0 || s0;
              if (a) {
                a.visible.unshift(index);
              }
            }
            n0.forward = n0.down = index;
            extent.back = extent.up = n0.index;
          } else if (f0) {
            f0.visible.unshift(index);
            f0.forward = f0.down = index;
            extent.back = extent.up = f0.index;
          } else if (ss0) {
            ss0.visible.unshift(index);
            ss0.forward = ss0.down = index;
            extent.back = extent.up = ss0.index;
          } else if (s0) {
            s0.visible.unshift(index);
            s0.forward = s0.down = index;
            extent.back = extent.up = s0.index;
          }
          for (let n of stacks.onScreen) {
            n.onScreen.unshift(index);
          }
          stacks.onScreen.unshift(extent);
          stacks.nulls.unshift(extent);
          extent.onScreen.unshift(
            ...(a0?.onScreen || /* istanbul ignore next */ emptyArray),
          );
          extent.visible.unshift(
            ...(a0?.visible || /* istanbul ignore next */ emptyArray),
          );
          break;
        case 'slide':
          if (stacks.subslides.length && s0) {
            // this is not strictly accurate, needs state for `y` in previous subslide stack
            extent.back = s0.index;
            for (let s of [...stacks.subslides, s0]) {
              let lastOnScreen = this._lastOnScreenOf(s.index, extents);
              if (lastOnScreen) {
                lastOnScreen.forward = index;
              }
            }
          } else if (n0) {
            n0.forward = index;
            extent.back = n0.index;
          } else if (f0) {
            f0.forward = index;
            extent.back = f0.index;
          } else if (s0) {
            let lastOnScreen = this._lastOnScreenOf(s0.index, extents);
            if (lastOnScreen) {
              lastOnScreen.forward = index;
              extent.back = lastOnScreen.index;
            }
          }
          stacks.subslides = [];
          stacks.nulls = [];
          stacks.fragments = [];
          stacks.onScreen = [extent];
          stacks.slides.unshift(extent);
          extent.onScreen.unshift(index);
          extent.visible.unshift(index);
          break;
        case 'subslide':
          if (n0) {
            n0.down = index;
            extent.up = n0.index;
          } else if (f0) {
            f0.down = index;
            extent.up = f0.index;
          } else if (s0) {
            let lastOnScreen = this._lastOnScreenOf(s0.index, extents);
            if (lastOnScreen) {
              lastOnScreen.down = index;
              extent.up = lastOnScreen.index;
            }
            extent.back = s0.back;
          }
          stacks.fragments = [];
          stacks.nulls = [];
          stacks.onScreen = [extent];
          stacks.subslides.unshift(extent);
          extent.onScreen.unshift(index);
          extent.visible.unshift(index);
          break;
        case 'fragment':
          for (let n of stacks.onScreen) {
            n.onScreen.unshift(index);
          }
          stacks.onScreen.unshift(extent);
          if (n0) {
            n0.down = n0.forward = index;
            extent.up = extent.back = n0.index;
          } else if (f0) {
            f0.down = f0.forward = index;
            extent.up = extent.back = f0.index;
          } else if (ss0) {
            ss0.down = ss0.forward = index;
            extent.up = extent.back = ss0.index;
          } else if (s0) {
            s0.down = s0.forward = index;
            extent.up = extent.back = s0.index;
          }
          stacks.nulls = [];
          stacks.onScreen.unshift(extent);
          extent.onScreen.unshift(...(a0?.onScreen || emptyArray));
          extent.visible.unshift(index, ...(a0?.visible || emptyArray));
          stacks.fragments.unshift(extent);
          break;
        case 'notes':
          if (a0) {
            a0.notes.unshift(index);
          }
          break;
      }
      extents.set(index, extent);
    }
 
    this._extents.set(notebookModel, extents);
 
    return extents;
  }
}
 
export namespace NotebookPresenter {
  export interface IOptions {
    manager: IDeckManager;
    commands: CommandRegistry;
    notebookTools: INotebookTools;
  }
  export type TStackType = 'nulls' | 'fragments' | 'slides' | 'subslides' | 'onScreen';
  export interface IExtent {
    slideType: TSlideType;
    parent: IExtent | null;
    index: number;
    up: number | null;
    down: number | null;
    forward: number | null;
    back: number | null;
    onScreen: number[];
    visible: number[];
    notes: number[];
  }
  export type TExtentMap = Map<number, IExtent>;
  /** a map of active slide to active layers */
  export type TLayerMap = Map<number, number[]>;
  export type TExtentIndexMap = Map<TSlideType, number[]>;
}