@jupyterlab/application#ILabShell TypeScript Examples

The following examples show how to use @jupyterlab/application#ILabShell. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: index.ts    From jupyter-extensions with Apache License 2.0 6 votes vote down vote up
async function activate(
  app: JupyterFrontEnd,
  shell: ILabShell,
  manager: IDocumentManager
) {
  const service = new GitSyncService(shell, manager);
  const widget = new GitSyncWidget(service);
  app.shell.add(widget, 'left', { rank: 100 });
}
Example #2
Source File: defaults.tsx    From jupyterlab-tour with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
/**
 * Add all default tours
 *
 * @param manager Tours manager
 * @param app Jupyter application
 * @param nbTracker Notebook tracker (optional)
 */
export function addTours(
  manager: ITourManager,
  app: JupyterFrontEnd,
  nbTracker?: INotebookTracker
): void {
  const { commands, shell } = app;
  addWelcomeTour(manager, commands);
  addNotebookTour(manager, commands, shell as ILabShell, nbTracker);
}
Example #3
Source File: index.ts    From jupyter-extensions with Apache License 2.0 5 votes vote down vote up
function activate(
  app: JupyterFrontEnd,
  labShell: ILabShell,
  palette: ICommandPalette,
  docManager: IDocumentManager
) {
  console.log('JupyterLab extension jupyterlab_comments is activated!');

  let widget: MainAreaWidget<CommentsWidget>;
  let content: CommentsWidget;

  const context = {
    labShell: labShell,
    docManager: docManager,
  };

  // Add an application command
  const command = 'comments:open';
  app.commands.addCommand(command, {
    label: 'Notebook comments in git',
    execute: () => {
      if (!widget || widget.isDisposed) {
        content = new CommentsWidget(context);
        widget = new MainAreaWidget<CommentsWidget>({ content });
        widget.id = 'jupyterlab_comments';
        widget.title.label = 'Comments';
        widget.title.closable = true;
      }

      if (!widget.isAttached) {
        app.shell.add(widget, 'right', { rank: 200 });
      }
      app.shell.activateById(widget.id);
    },
  });
  // Add the command to the palette.
  palette.addItem({ command, category: 'Collaboration' });

  /*
  Command for adding new comment to currently selected line in the file
  This command only support non-Notebook files
  */
  const addNewComment = 'comments:add';
  app.commands.addCommand(addNewComment, {
    execute: () => {
      const file = (labShell.currentWidget as IDocumentWidget)
        .content as FileEditor;
      if (!widget) {
        return;
      }
      const selectionObj = file.editor.getSelection(); //contains start and end line and column attributes
      const dialogWidget = new NewCommentDialogWidget(selectionObj, context);
      dialogWidget.id = 'new_comment';

      app.shell.add(dialogWidget, 'bottom'); //attach widget to UI to display dialog
      app.shell.activateById(dialogWidget.id);
    },
    label: 'New comment',
  });
  //Add command to file editor's right click context menu
  app.contextMenu.addItem({
    command: addNewComment,
    selector: '.jp-FileEditor',
    rank: 1,
  });
}
Example #4
Source File: index.ts    From jupyter-extensions with Apache License 2.0 5 votes vote down vote up
extension: JupyterFrontEndPlugin<void> = {
  id: 'jupyterlab-comments',
  autoStart: true,
  activate: activate,
  requires: [ILabShell, ICommandPalette, IDocumentManager],
}
Example #5
Source File: index.ts    From jupyter-extensions with Apache License 2.0 5 votes vote down vote up
GitSyncPlugin: JupyterFrontEndPlugin<void> = {
  id: 'gitsync:gitsync',
  requires: [ILabShell, IDocumentManager],
  activate: activate,
  autoStart: true,
}
Example #6
Source File: service.ts    From jupyter-extensions with Apache License 2.0 5 votes vote down vote up
constructor(shell: ILabShell, manager: IDocumentManager) {
    this._shell = shell;
    this._manager = manager;
    this._git = new GitManager();
    this._tracker = new FileTracker(this);
    this._addListeners();
  }
Example #7
Source File: service.ts    From jupyter-extensions with Apache License 2.0 5 votes vote down vote up
/* Member Fields */
  private _shell: ILabShell;
Example #8
Source File: tracker.ts    From jupyter-extensions with Apache License 2.0 5 votes vote down vote up
shell: ILabShell;
Example #9
Source File: index.ts    From jlab-enhanced-launcher with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
plugin: JupyterFrontEndPlugin<ILauncher> = {
  activate,
  id: EXTENSION_ID,
  requires: [ITranslator],
  optional: [ILabShell, ICommandPalette, ISettingRegistry, IStateDB],
  provides: ILauncher,
  autoStart: true
}
Example #10
Source File: plugin.ts    From jupyter-videochat with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
function isFullLab(app: JupyterFrontEnd) {
  return !!(app.shell as ILabShell).layoutModified;
}
Example #11
Source File: index.ts    From jlab-enhanced-launcher with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
/**
 * Activate the launcher.
 */
async function activate(
  app: JupyterFrontEnd,
  translator: ITranslator,
  labShell: ILabShell | null,
  palette: ICommandPalette | null,
  settingRegistry: ISettingRegistry | null,
  state: IStateDB | null
): Promise<ILauncher> {
  const { commands, shell } = app;
  const trans = translator.load('jupyterlab');

  let settings: ISettingRegistry.ISettings | null = null;
  if (settingRegistry) {
    try {
      settings = await settingRegistry.load(EXTENSION_ID);
    } catch (reason) {
      console.log(`Failed to load settings for ${EXTENSION_ID}.`, reason);
    }
  }

  const model = new LauncherModel(settings, state);

  if (state) {
    Promise.all([
      state.fetch(`${EXTENSION_ID}:usageData`),
      state.fetch(`${EXTENSION_ID}:viewMode`),
      app.restored
    ])
      .then(([usage, mode]) => {
        model.viewMode = (mode as any) || 'cards';
        for (const key in usage as any) {
          model.usage[key] = (usage as any)[key];
        }
      })
      .catch(reason => {
        console.error('Fail to restore launcher usage data', reason);
      });
  }

  commands.addCommand(CommandIDs.create, {
    label: trans.__('New Launcher'),
    execute: (args: ReadonlyPartialJSONObject) => {
      const cwd = args['cwd'] ? String(args['cwd']) : '';
      const id = `launcher-${Private.id++}`;
      const callback = (item: Widget): void => {
        shell.add(item, 'main', { ref: id });
      };
      const launcher = new Launcher({ model, cwd, callback, commands });

      launcher.model = model;
      launcher.title.icon = launcherIcon;
      launcher.title.label = trans.__('Launcher');

      const main = new MainAreaWidget({ content: launcher });

      // If there are any other widgets open, remove the launcher close icon.
      main.title.closable = !!toArray(shell.widgets('main')).length;
      main.id = id;

      shell.add(main, 'main', {
        activate: args['activate'] as boolean,
        ref: args['ref'] as string
      });

      if (labShell) {
        labShell.layoutModified.connect(() => {
          // If there is only a launcher open, remove the close icon.
          main.title.closable = toArray(labShell.widgets('main')).length > 1;
        }, main);
      }

      return main;
    }
  });

  if (palette) {
    palette.addItem({
      command: CommandIDs.create,
      category: trans.__('Launcher')
    });
  }

  if (labShell && app.version >= '3.4.0') {
    labShell.addButtonEnabled = true;
    labShell.addRequested.connect((sender: DockPanel, arg: TabBar<Widget>) => {
      // Get the ref for the current tab of the tabbar which the add button was clicked
      const ref =
        arg.currentTitle?.owner.id ||
        arg.titles[arg.titles.length - 1].owner.id;
      if (commands.hasCommand('filebrowser:create-main-launcher')) {
        // If a file browser is defined connect the launcher to it
        return commands.execute('filebrowser:create-main-launcher', { ref });
      }
      return commands.execute(CommandIDs.create, { ref });
    });
  }

  return model;
}
Example #12
Source File: plugin.ts    From jupyter-videochat with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
/**
 * Handle application-level concerns
 */
async function activateCore(
  app: JupyterFrontEnd,
  settingRegistry: ISettingRegistry,
  translator?: ITranslator,
  palette?: ICommandPalette,
  launcher?: ILauncher,
  restorer?: ILayoutRestorer,
  mainmenu?: IMainMenu
): Promise<IVideoChatManager> {
  const { commands, shell } = app;

  const labShell = isFullLab(app) ? (shell as LabShell) : null;

  const manager = new VideoChatManager({
    trans: (translator || nullTranslator).load(NS),
  });

  const { __ } = manager;

  let widget: MainAreaWidget;
  let chat: VideoChat;
  let subject: string | null = null;

  const tracker = new WidgetTracker<MainAreaWidget>({ namespace: NS });

  if (!widget || widget.isDisposed) {
    // Create widget
    chat = new VideoChat(manager, {});
    widget = new MainAreaWidget({ content: chat });
    widget.addClass(`${CSS}-wrapper`);
    manager.setMainWidget(widget);

    widget.toolbar.addItem(ToolbarIds.SPACER_LEFT, Toolbar.createSpacerItem());

    widget.toolbar.addItem(ToolbarIds.TITLE, new RoomTitle(manager));

    widget.toolbar.addItem(ToolbarIds.SPACER_RIGHT, Toolbar.createSpacerItem());

    const disconnectBtn = new CommandToolbarButton({
      id: CommandIds.disconnect,
      commands,
      icon: stopIcon,
    });

    const onCurrentRoomChanged = () => {
      if (manager.currentRoom) {
        disconnectBtn.show();
      } else {
        disconnectBtn.hide();
      }
    };

    manager.currentRoomChanged.connect(onCurrentRoomChanged);

    widget.toolbar.addItem(ToolbarIds.DISCONNECT, disconnectBtn);

    onCurrentRoomChanged();

    chat.id = `id-${NS}`;
    chat.title.caption = __(DEFAULT_LABEL);
    chat.title.closable = false;
    chat.title.icon = chatIcon;
  }

  // hide the label when in sidebar, as it shows the rotated text
  function updateTitle() {
    if (subject != null) {
      widget.title.caption = subject;
    } else {
      widget.title.caption = __(DEFAULT_LABEL);
    }
    widget.title.label = manager.currentArea === 'main' ? widget.title.caption : '';
  }

  // add to shell, update tracker, title, etc.
  function addToShell(area?: ILabShell.Area, activate = true) {
    DEBUG && console.warn(`add to shell in are ${area}, ${!activate || 'not '} active`);
    area = area || manager.currentArea;
    if (labShell) {
      labShell.add(widget, area);
      updateTitle();
      widget.update();
      if (!tracker.has(widget)) {
        tracker.add(widget).catch(void 0);
      }
      if (activate) {
        shell.activateById(widget.id);
      }
    } else if (window.location.search.indexOf(FORCE_URL_PARAM) !== -1) {
      document.title = [document.title.split(' - ')[0], __(DEFAULT_LABEL)].join(' - ');
      app.shell.currentWidget.parent = null;
      app.shell.add(widget, 'main', { rank: 0 });
      const { parent } = widget;
      parent.addClass(`${CSS}-main-parent`);
      setTimeout(() => {
        parent.update();
        parent.fit();
        app.shell.fit();
        app.shell.update();
      }, 100);
    }
  }

  // listen for the subject to update the widget title dynamically
  manager.meetChanged.connect(() => {
    if (manager.meet) {
      manager.meet.on('subjectChange', (args: any) => {
        subject = args.subject;
        updateTitle();
      });
    } else {
      subject = null;
    }
    updateTitle();
  });

  // connect settings
  settingRegistry
    .load(corePlugin.id)
    .then((settings) => {
      manager.settings = settings;
      let lastArea = manager.settings.composite.area;
      settings.changed.connect(() => {
        if (lastArea !== manager.settings.composite.area) {
          addToShell();
        }
        lastArea = manager.settings.composite.area;
      });
      addToShell(null, false);
    })
    .catch(() => addToShell(null, false));

  // add commands
  commands.addCommand(CommandIds.open, {
    label: __(DEFAULT_LABEL),
    icon: prettyChatIcon,
    execute: async (args: IChatArgs) => {
      await manager.initialized;
      addToShell(null, true);
      // Potentially navigate to new room
      if (manager.currentRoom?.displayName !== args.displayName) {
        manager.currentRoom = { displayName: args.displayName };
      }
    },
  });

  commands.addCommand(CommandIds.disconnect, {
    label: __('Disconnect Video Chat'),
    execute: () => (manager.currentRoom = null),
    icon: stopIcon,
  });

  commands.addCommand(CommandIds.toggleArea, {
    label: __('Toggle Video Chat Sidebar'),
    icon: launcherIcon,
    execute: async () => {
      manager.currentArea = ['right', 'left'].includes(manager.currentArea)
        ? 'main'
        : 'right';
    },
  });

  // If available, add the commands to the palette
  if (palette) {
    palette.addItem({ command: CommandIds.open, category: __(category) });
  }

  // If available, add a card to the launcher
  if (launcher) {
    launcher.add({ command: CommandIds.open, args: { area: 'main' } });
  }

  // If available, restore the position
  if (restorer) {
    restorer
      .restore(tracker, { command: CommandIds.open, name: () => `id-${NS}` })
      .catch(console.warn);
  }

  // If available, add to the file->new menu.... new tab handled in retroPlugin
  if (mainmenu && labShell) {
    mainmenu.fileMenu.newMenu.addGroup([{ command: CommandIds.open }]);
  }

  // Return the manager that others extensions can use
  return manager;
}
Example #13
Source File: defaults.tsx    From jupyterlab-tour with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
/**
 * Add the default notebook tour
 *
 * @param manager Tours manager
 * @param shell Jupyter shell
 * @param nbTracker Notebook tracker (optional)
 */
function addNotebookTour(
  manager: ITourManager,
  commands: CommandRegistry,
  shell: ILabShell,
  nbTracker?: INotebookTracker
): void {
  const __ = manager.translator.__.bind(manager.translator);
  const notebookTour = manager.createTour(
    NOTEBOOK_ID,
    __('Notebook Tour'),
    true
  );

  notebookTour.options = {
    ...notebookTour.options,
    hideBackButton: true,
    disableScrolling: true
  };

  let currentNbPanel: NotebookPanel | null = null;
  let addedCellIndex: number | null = null;

  notebookTour.addStep({
    target: '.jp-MainAreaWidget.jp-NotebookPanel',
    content: (
      <p>
        {__(
          'Notebooks are documents combining live runnable code with narrative text (i.e. text, images,...).'
        )}
      </p>
    ),
    placement: 'center',
    title: __('Working with notebooks!')
  });

  notebookTour.addStep({
    target: '.jp-Cell.jp-Notebook-cell',
    content: (
      <p>
        {__('Notebook consists of one cells list.')}
        <br />
        {__('This is the first cell.')}
      </p>
    ),
    placement: 'bottom'
  });

  notebookTour.addStep({
    target: '.jp-NotebookPanel-toolbar .jp-Notebook-toolbarCellType',
    content: (
      <>
        <p>{__('A cell can have different type')}</p>
        <ul>
          <li>
            <strong>{__('Code')}</strong>
            {__(': Executable code')}
          </li>
          <li>
            <strong>{__('Markdown')}</strong>
            {__(': Markdown formatted text')}
          </li>
          <li>
            <strong>{__('Raw')}</strong>
            {__(': Plain text')}
          </li>
        </ul>
      </>
    )
  });

  notebookTour.addStep({
    target: '.jp-Notebook-cell:last-child .jp-InputArea.jp-Cell-inputArea',
    content: (
      <p>
        {__(
          `A cell has an input and an output area. This is the input area that you can edit with 
          the proper syntax depending on the type.`
        )}
      </p>
    ),
    placement: 'bottom'
  });

  notebookTour.addStep({
    target: '.jp-NotebookPanel-toolbar svg[data-icon="ui-components:run"]',
    content: (
      <p>
        {__(
          'Hitting the Play button (or pressing Shift+Enter) will execute the cell content.'
        )}
      </p>
    ),
    placement: 'right'
  });

  notebookTour.addStep({
    target: '.jp-Notebook-cell:last-child .jp-OutputArea.jp-Cell-outputArea',
    content: (
      <p>
        {__(
          'Once a cell has been executed. Its result is display in the output cell area.'
        )}
      </p>
    ),
    placement: 'bottom'
  });

  notebookTour.addStep({
    target: '.jp-NotebookPanel-toolbar .jp-KernelName',
    content: (
      <p>
        {__(
          'When executing a "Code" cell, its code is sent to a execution kernel.'
        )}
        <br />
        {__(
          'Its name and its status are displayed here and in the status bar.'
        )}
      </p>
    ),
    placement: 'bottom'
  });

  notebookTour.addStep({
    target: '#jp-running-sessions',
    content: (
      <p>
        {__('The running kernels are listed on this tab.')}
        <br />
        {__(
          ' It can be used to open the associated document or to shut them down.'
        )}
      </p>
    ),
    placement: 'right'
  });

  notebookTour.addStep({
    target: '#jp-property-inspector',
    content: (
      <p>
        {__('Metadata (like tags) can be added to cells through this tab.')}
      </p>
    ),
    placement: 'left'
  });

  notebookTour.stepChanged.connect((_, data) => {
    if (data.type === 'tour:start') {
      addedCellIndex = null;
    } else if (data.type === 'step:before') {
      switch (data.step.target) {
        case '.jp-NotebookPanel-toolbar svg[data-icon="ui-components:run"]':
          {
            if (nbTracker && currentNbPanel) {
              const { content, context } = currentNbPanel;
              NotebookActions.run(content, context.sessionContext);
            }
          }
          break;
        default:
          break;
      }
    } else if (data.type === 'step:after') {
      switch (data.step.target) {
        case '.jp-NotebookPanel-toolbar .jp-Notebook-toolbarCellType':
          {
            if (nbTracker) {
              currentNbPanel = nbTracker.currentWidget;
              if (currentNbPanel && !addedCellIndex) {
                const notebook = currentNbPanel.content;
                NotebookActions.insertBelow(notebook);
                const activeCell = notebook.activeCell;
                addedCellIndex = notebook.activeCellIndex;
                if (activeCell) {
                  activeCell.model.value.text = 'a = 2\na';
                }
              }
            }
          }

          break;
        case '.jp-NotebookPanel-toolbar .jp-KernelName':
          shell.activateById('jp-running-sessions');
          break;
        case '#jp-running-sessions':
          shell.activateById('jp-property-inspector');
          break;
        default:
          break;
      }
    }
  });

  // clean
  notebookTour.finished.connect((_, data) => {
    if (data.step.target === '#jp-property-inspector') {
      commands.execute('filebrowser:activate');
      if (nbTracker) {
        if (currentNbPanel && addedCellIndex !== null) {
          currentNbPanel.content.activeCellIndex = addedCellIndex;
          NotebookActions.deleteCells(currentNbPanel.content);
          addedCellIndex = null;
        }
      }
    }
  });
}