当前位置: 首页>>代码示例>>TypeScript>>正文


TypeScript ILayoutRestorer.restore方法代码示例

本文整理汇总了TypeScript中@jupyterlab/application.ILayoutRestorer.restore方法的典型用法代码示例。如果您正苦于以下问题:TypeScript ILayoutRestorer.restore方法的具体用法?TypeScript ILayoutRestorer.restore怎么用?TypeScript ILayoutRestorer.restore使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在@jupyterlab/application.ILayoutRestorer的用法示例。


在下文中一共展示了ILayoutRestorer.restore方法的10个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的TypeScript代码示例。

示例1: InspectorManager

  activate: (
    app: JupyterLab,
    palette: ICommandPalette,
    restorer: ILayoutRestorer
  ): IInspector => {
    const { commands, shell } = app;
    const manager = new InspectorManager();
    const category = 'Inspector';
    const command = CommandIDs.open;
    const label = 'Open Inspector';
    const namespace = 'inspector';
    const tracker = new InstanceTracker<MainAreaWidget<InspectorPanel>>({
      namespace
    });

    /**
     * Create and track a new inspector.
     */
    function newInspectorPanel(): InspectorPanel {
      const inspector = new InspectorPanel();

      inspector.id = 'jp-inspector';
      inspector.title.label = 'Inspector';
      inspector.disposed.connect(() => {
        if (manager.inspector === inspector) {
          manager.inspector = null;
        }
      });

      // Track the inspector.
      let widget = new MainAreaWidget({ content: inspector });
      tracker.add(widget);

      // Add the default inspector child items.
      Private.defaultInspectorItems.forEach(item => {
        inspector.add(item);
      });

      return inspector;
    }

    // Handle state restoration.
    restorer.restore(tracker, {
      command,
      args: () => null,
      name: () => 'inspector'
    });

    // Add command to registry and palette.
    commands.addCommand(command, {
      label,
      execute: () => {
        if (!manager.inspector || manager.inspector.isDisposed) {
          manager.inspector = newInspectorPanel();
        }
        if (!manager.inspector.isAttached) {
          shell.addToMainArea(manager.inspector.parent, { activate: false });
        }
        shell.activateById(manager.inspector.parent.id);
      }
    });
    palette.addItem({ command, category });

    return manager;
  }
开发者ID:AlbertHilb,项目名称:jupyterlab,代码行数:65,代码来源:index.ts

示例2: activateConsole

/**
 * Activate the console extension.
 */
async function activateConsole(
  app: JupyterFrontEnd,
  mainMenu: IMainMenu,
  palette: ICommandPalette,
  contentFactory: ConsolePanel.IContentFactory,
  editorServices: IEditorServices,
  restorer: ILayoutRestorer,
  browserFactory: IFileBrowserFactory,
  rendermime: IRenderMimeRegistry,
  settingRegistry: ISettingRegistry,
  launcher: ILauncher | null,
  status: ILabStatus | null
): Promise<IConsoleTracker> {
  const manager = app.serviceManager;
  const { commands, shell } = app;
  const category = 'Console';

  // Create an instance tracker for all console panels.
  const tracker = new InstanceTracker<ConsolePanel>({ namespace: 'console' });

  // Handle state restoration.
  restorer.restore(tracker, {
    command: CommandIDs.create,
    args: panel => ({
      path: panel.console.session.path,
      name: panel.console.session.name,
      kernelPreference: {
        name: panel.console.session.kernel && panel.console.session.kernel.name,
        language:
          panel.console.session.language &&
          panel.console.session.kernel.language
      }
    }),
    name: panel => panel.console.session.path,
    when: manager.ready
  });

  // Add a launcher item if the launcher is available.
  if (launcher) {
    void manager.ready.then(() => {
      let disposables: DisposableSet | null = null;
      const onSpecsChanged = () => {
        if (disposables) {
          disposables.dispose();
          disposables = null;
        }
        const specs = manager.specs;
        if (!specs) {
          return;
        }
        disposables = new DisposableSet();
        let baseUrl = PageConfig.getBaseUrl();
        for (let name in specs.kernelspecs) {
          let rank = name === specs.default ? 0 : Infinity;
          let kernelIconUrl = specs.kernelspecs[name].resources['logo-64x64'];
          if (kernelIconUrl) {
            let index = kernelIconUrl.indexOf('kernelspecs');
            kernelIconUrl = baseUrl + kernelIconUrl.slice(index);
          }
          disposables.add(
            launcher.add({
              command: CommandIDs.create,
              args: { isLauncher: true, kernelPreference: { name } },
              category: 'Console',
              rank,
              kernelIconUrl
            })
          );
        }
      };
      onSpecsChanged();
      manager.specsChanged.connect(onSpecsChanged);
    });
  }

  /**
   * The options used to create a widget.
   */
  interface ICreateOptions extends Partial<ConsolePanel.IOptions> {
    /**
     * The reference widget id for the insert location.
     *
     * The default is `null`.
     */
    ref?: string | null;

    /**
     * The tab insert mode.
     *
     * An insert mode is used to specify how a widget should be added
     * to the main area relative to a reference widget.
     */
    insertMode?: DockLayout.InsertMode;

    /**
     * Whether to activate the widget.  Defaults to `true`.
     */
//.........这里部分代码省略.........
开发者ID:afshin,项目名称:jupyterlab,代码行数:101,代码来源:index.ts

示例3: activate

/**
 * Activate the setting editor extension.
 */
function activate(app: JupyterLab, restorer: ILayoutRestorer, registry: ISettingRegistry, editorServices: IEditorServices, state: IStateDB, rendermime: IRenderMimeRegistry, palette: ICommandPalette): ISettingEditorTracker {
  const { commands, shell } = app;
  const namespace = 'setting-editor';
  const factoryService = editorServices.factoryService;
  const editorFactory = factoryService.newInlineEditor;
  const tracker = new InstanceTracker<MainAreaWidget<SettingEditor>>({ namespace });
  let editor: SettingEditor;

  // Handle state restoration.
  restorer.restore(tracker, {
    command: CommandIDs.open,
    args: widget => ({ }),
    name: widget => namespace
  });

  commands.addCommand(CommandIDs.debug, {
    execute: () => { tracker.currentWidget.content.toggleDebug(); },
    iconClass: 'jp-MaterialIcon jp-BugIcon',
    label: 'Debug User Settings In Inspector',
    isToggled: () => tracker.currentWidget.content.isDebugVisible
  });

  commands.addCommand(CommandIDs.open, {
    execute: () => {
      if (tracker.currentWidget) {
        shell.activateById(tracker.currentWidget.id);
        return;
      }

      const key = plugin.id;
      const when = app.restored;

      editor = new SettingEditor({
        commands: {
          registry: commands,
          debug: CommandIDs.debug,
          revert: CommandIDs.revert,
          save: CommandIDs.save
        },
        editorFactory, key, registry, rendermime, state, when
      });

      // Notify the command registry when the visibility status of the setting
      // editor's commands change. The setting editor toolbar listens for this
      // signal from the command registry.
      editor.commandsChanged.connect((sender: any, args: string[]) => {
        args.forEach(id => { commands.notifyCommandChanged(id); });
      });

      editor.id = namespace;
      editor.title.label = 'Settings';
      editor.title.iconClass = 'jp-SettingsIcon';

      let main = new MainAreaWidget({ content: editor });
      tracker.add(main);
      shell.addToMainArea(main);
    },
    label: 'Advanced Settings Editor'
  });
  palette.addItem({ category: 'Settings', command: CommandIDs.open });

  commands.addCommand(CommandIDs.revert, {
    execute: () => { tracker.currentWidget.content.revert(); },
    iconClass: 'jp-MaterialIcon jp-UndoIcon',
    label: 'Revert User Settings',
    isEnabled: () => tracker.currentWidget.content.canRevertRaw
  });

  commands.addCommand(CommandIDs.save, {
    execute: () => tracker.currentWidget.content.save(),
    iconClass: 'jp-MaterialIcon jp-SaveIcon',
    label: 'Save User Settings',
    isEnabled: () => tracker.currentWidget.content.canSaveRaw
  });

  return tracker;
}
开发者ID:cfsmile,项目名称:jupyterlab,代码行数:80,代码来源:index.ts

示例4: activate

/**
 * Activate the help handler extension.
 *
 * @param app - The phosphide application object.
 *
 * returns A promise that resolves when the extension is activated.
 */
function activate(app: JupyterLab, mainMenu: IMainMenu, palette: ICommandPalette, restorer: ILayoutRestorer): void {
  let counter = 0;
  const category = 'Help';
  const namespace = 'help-doc';
  const baseUrl = PageConfig.getBaseUrl();
  const { commands, shell, info, serviceManager } = app;
  const tracker = new InstanceTracker<HelpWidget>({ namespace });

  // Handle state restoration.
  restorer.restore(tracker, {
    command: CommandIDs.open,
    args: widget => ({ url: widget.url, text: widget.title.label }),
    name: widget => widget.url
  });

  /**
   * Create a new HelpWidget widget.
   */
  function newClosableIFrame(url: string, text: string): HelpWidget {
    let iframe = new HelpWidget(url);
    iframe.addClass(HELP_CLASS);
    iframe.title.label = text;
    iframe.title.closable = true;
    iframe.id = `${namespace}-${++counter}`;
    tracker.add(iframe);
    return iframe;
  }

  // Populate the Help menu.
  const helpMenu = mainMenu.helpMenu;
  const labGroup = [
    CommandIDs.about,
    'faq-jupyterlab:open',
    CommandIDs.launchClassic
  ].map(command => { return { command }; });
  helpMenu.addGroup(labGroup, 0);
  const resourcesGroup = RESOURCES
    .map(args => ({ args, command: CommandIDs.open }));
  helpMenu.addGroup(resourcesGroup, 10);
  helpMenu.addGroup([{ command: 'apputils:reset' }], 20);

  // Generate a cache of the kernel help links.
  const kernelInfoCache = new Map<string, KernelMessage.IInfoReply>();
  serviceManager.sessions.runningChanged.connect((m, sessions) => {
    // If a new session has been added, it is at the back
    // of the session list. If one has changed or stopped,
    // it does not hurt to check it.
    if (!sessions.length) {
      return;
    }
    const sessionModel = sessions[sessions.length - 1];
    if (kernelInfoCache.has(sessionModel.kernel.name)) {
      return;
    }
    serviceManager.sessions.connectTo(sessionModel).then(session => {
      session.kernel.ready.then(() => {
        // Check the cache second time so that, if two callbacks get scheduled,
        // they don't try to add the same commands.
        if (kernelInfoCache.has(sessionModel.kernel.name)) {
          return;
        }
        // Set the Kernel Info cache.
        const name = session.kernel.name;
        const kernelInfo = session.kernel.info;
        kernelInfoCache.set(name, kernelInfo);

        // Utility function to check if the current widget
        // has registered itself with the help menu.
        const usesKernel = () => {
          let result = false;
          const widget = app.shell.currentWidget;
          if (!widget) {
            return result;
          }
          helpMenu.kernelUsers.forEach(u => {
            if (u.tracker.has(widget) &&
                u.getKernel(widget) &&
                u.getKernel(widget).name === name) {
              result = true;
            }
          });
          return result;
        };

        // Add the kernel banner to the Help Menu.
        const bannerCommand = `help-menu-${name}:banner`;
        const spec = serviceManager.specs.kernelspecs[name];
        const kernelName = spec.display_name;
        let kernelIconUrl = spec.resources['logo-64x64'];
        if (kernelIconUrl) {
          let index = kernelIconUrl.indexOf('kernelspecs');
          kernelIconUrl = baseUrl + kernelIconUrl.slice(index);
        }
//.........这里部分代码省略.........
开发者ID:7125messi,项目名称:jupyterlab,代码行数:101,代码来源:index.ts

示例5: activateConsole

/**
 * Activate the console extension.
 */
function activateConsole(app: JupyterLab, mainMenu: IMainMenu, palette: ICommandPalette, contentFactory: ConsolePanel.IContentFactory,  editorServices: IEditorServices, restorer: ILayoutRestorer, browserFactory: IFileBrowserFactory, rendermime: IRenderMimeRegistry, launcher: ILauncher | null): IConsoleTracker {
  const manager = app.serviceManager;
  const { commands, shell } = app;
  const category = 'Console';

  // Create an instance tracker for all console panels.
  const tracker = new InstanceTracker<ConsolePanel>({ namespace: 'console' });

  // Handle state restoration.
  restorer.restore(tracker, {
    command: CommandIDs.open,
    args: panel => ({
      path: panel.console.session.path,
      name: panel.console.session.name
    }),
    name: panel => panel.console.session.path,
    when: manager.ready
  });

  // The launcher callback.
  let callback = (cwd: string, name: string) => {
    return createConsole({ basePath: cwd, kernelPreference: { name } });
  };

  // Add a launcher item if the launcher is available.
  if (launcher) {
    manager.ready.then(() => {
      const specs = manager.specs;
      if (!specs) {
        return;
      }
      let baseUrl = PageConfig.getBaseUrl();
      for (let name in specs.kernelspecs) {
        let displayName = specs.kernelspecs[name].display_name;
        let rank = name === specs.default ? 0 : Infinity;
        let kernelIconUrl = specs.kernelspecs[name].resources['logo-64x64'];
        if (kernelIconUrl) {
          let index = kernelIconUrl.indexOf('kernelspecs');
          kernelIconUrl = baseUrl + kernelIconUrl.slice(index);
        }
        launcher.add({
          displayName,
          category: 'Console',
          name,
          iconClass: 'jp-CodeConsoleIcon',
          callback,
          rank,
          kernelIconUrl
        });
      }
    });
  }

  interface ICreateOptions extends Partial<ConsolePanel.IOptions> {
    ref?: string;
    insertMode?: DockLayout.InsertMode;
  }

  /**
   * Create a console for a given path.
   */
  function createConsole(options: ICreateOptions): Promise<ConsolePanel> {
    let panel: ConsolePanel;
    return manager.ready.then(() => {
      panel = new ConsolePanel({
        manager,
        contentFactory,
        mimeTypeService: editorServices.mimeTypeService,
        rendermime,
        ...options as Partial<ConsolePanel.IOptions>
      });

      return panel.session.ready;
    }).then(() => {
      // Add the console panel to the tracker.
      tracker.add(panel);
      shell.addToMainArea(
        panel, {
          ref: options.ref || null, mode: options.insertMode || 'tab-after'
        }
      );
      shell.activateById(panel.id);
      return panel;
    });
  }

  /**
   * Whether there is an active console.
   */
  function isEnabled(): boolean {
    return tracker.currentWidget !== null
           && tracker.currentWidget === app.shell.currentWidget;
  }

  let command = CommandIDs.open;
  commands.addCommand(command, {
    execute: (args: Partial<ConsolePanel.IOptions>) => {
//.........这里部分代码省略.........
开发者ID:SimonBiggs,项目名称:jupyterlab,代码行数:101,代码来源:index.ts

示例6: activateNotebookHandler

/**
 * Activate the notebook handler extension.
 */
function activateNotebookHandler(app: JupyterLab, mainMenu: IMainMenu, palette: ICommandPalette, contentFactory: NotebookPanel.IContentFactory, editorServices: IEditorServices, restorer: ILayoutRestorer, launcher: ILauncher | null): INotebookTracker {
  const services = app.serviceManager;
  const factory = new NotebookWidgetFactory({
    name: FACTORY,
    fileTypes: ['notebook'],
    modelName: 'notebook',
    defaultFor: ['notebook'],
    preferKernel: true,
    canStartKernel: true,
    rendermime: app.rendermime,
    contentFactory,
    mimeTypeService: editorServices.mimeTypeService
  });
  const { commands } = app;
  const tracker = new NotebookTracker({ namespace: 'notebook' });

  // Handle state restoration.
  restorer.restore(tracker, {
    command: 'docmanager:open',
    args: panel => ({ path: panel.context.path, factory: FACTORY }),
    name: panel => panel.context.path,
    when: services.ready
  });

  // Update the command registry when the notebook state changes.
  tracker.currentChanged.connect(() => {
    if (tracker.size <= 1) {
      commands.notifyCommandChanged(CommandIDs.interrupt);
    }
  });

  let registry = app.docRegistry;
  registry.addModelFactory(new NotebookModelFactory({}));
  registry.addWidgetFactory(factory);
  registry.addCreator({
    name: 'Notebook',
    fileType: 'Notebook',
    widgetName: 'Notebook'
  });

  addCommands(app, services, tracker);
  populatePalette(palette);

  let id = 0; // The ID counter for notebook panels.

  factory.widgetCreated.connect((sender, widget) => {
    // If the notebook panel does not have an ID, assign it one.
    widget.id = widget.id || `notebook-${++id}`;
    widget.title.icon = NOTEBOOK_ICON_CLASS;
    // Notify the instance tracker if restore data needs to update.
    widget.context.pathChanged.connect(() => { tracker.save(widget); });
    // Add the notebook panel to the tracker.
    tracker.add(widget);
  });

  // Add main menu notebook menu.
  mainMenu.addMenu(createMenu(app), { rank: 20 });

  // The launcher callback.
  let callback = (cwd: string, name: string) => {
    return commands.execute(
      'docmanager:new-untitled', { path: cwd, type: 'notebook' }
    ).then(model => {
      return commands.execute('docmanager:open', {
        path: model.path, factory: FACTORY,
        kernel: { name }
      });
    });
  };

  // Add a launcher item if the launcher is available.
  if (launcher) {
    services.ready.then(() => {
      let specs = services.specs;
      let baseUrl = PageConfig.getBaseUrl();
      for (let name in specs.kernelspecs) {
        let displayName = specs.kernelspecs[name].display_name;
        let rank = name === specs.default ? 0 : Infinity;
        let kernelIconUrl = specs.kernelspecs[name].resources['logo-64x64'];
        if (kernelIconUrl) {
          let index = kernelIconUrl.indexOf('kernelspecs');
          kernelIconUrl = baseUrl + kernelIconUrl.slice(index);
        }
        launcher.add({
          displayName,
          category: 'Notebook',
          name,
          iconClass: 'jp-NotebookRunningIcon',
          callback,
          rank,
          kernelIconUrl
        });
      }
    });
  }

  app.contextMenu.addItem({command: CommandIDs.clearOutputs, selector: '.jp-Notebook .jp-Cell'});
//.........这里部分代码省略.........
开发者ID:cameronoelsen,项目名称:jupyterlab,代码行数:101,代码来源:index.ts

示例7: activate

/**
 * Activate the terminal plugin.
 */
function activate(
  app: JupyterLab,
  mainMenu: IMainMenu,
  palette: ICommandPalette,
  restorer: ILayoutRestorer,
  launcher: ILauncher | null
): ITerminalTracker {
  const { serviceManager } = app;
  const category = 'Terminal';
  const namespace = 'terminal';
  const tracker = new InstanceTracker<MainAreaWidget<Terminal>>({ namespace });

  // Bail if there are no terminals available.
  if (!serviceManager.terminals.isAvailable()) {
    console.log(
      'Disabling terminals plugin because they are not available on the server'
    );
    return tracker;
  }

  // Handle state restoration.
  restorer.restore(tracker, {
    command: CommandIDs.createNew,
    args: widget => ({ name: widget.content.session.name }),
    name: widget => widget.content.session && widget.content.session.name
  });

  addCommands(app, serviceManager, tracker);

  // Add some commands to the application view menu.
  const viewGroup = [
    CommandIDs.increaseFont,
    CommandIDs.decreaseFont,
    CommandIDs.toggleTheme
  ].map(command => {
    return { command };
  });
  mainMenu.viewMenu.addGroup(viewGroup, 30);

  // Add command palette items.
  [
    CommandIDs.createNew,
    CommandIDs.refresh,
    CommandIDs.increaseFont,
    CommandIDs.decreaseFont,
    CommandIDs.toggleTheme
  ].forEach(command => {
    palette.addItem({ command, category, args: { isPalette: true } });
  });

  // Add terminal creation to the file menu.
  mainMenu.fileMenu.newMenu.addGroup([{ command: CommandIDs.createNew }], 20);

  // Add a launcher item if the launcher is available.
  if (launcher) {
    launcher.add({
      command: CommandIDs.createNew,
      category: 'Other',
      rank: 0
    });
  }

  app.contextMenu.addItem({
    command: CommandIDs.refresh,
    selector: '.jp-Terminal',
    rank: 1
  });

  return tracker;
}
开发者ID:SylvainCorlay,项目名称:jupyterlab,代码行数:73,代码来源:index.ts

示例8: activate

/**
 * Activate the terminal plugin.
 */
function activate(app: JupyterLab, mainMenu: IMainMenu, palette: ICommandPalette, restorer: ILayoutRestorer, launcher: ILauncher | null): ITerminalTracker {
  const { commands, serviceManager } = app;
  const category = 'Terminal';
  const namespace = 'terminal';
  const tracker = new InstanceTracker<Terminal>({ namespace });

  // Bail if there are no terminals available.
  if (!serviceManager.terminals.isAvailable()) {
    console.log('Disabling terminals plugin because they are not available on the server');
    return tracker;
  }

  // Handle state restoration.
  restorer.restore(tracker, {
    command: CommandIDs.createNew,
    args: widget => ({ name: widget.session.name }),
    name: widget => widget.session && widget.session.name
  });

  // Update the command registry when the terminal state changes.
  tracker.currentChanged.connect(() => {
    if (tracker.size <= 1) {
      commands.notifyCommandChanged(CommandIDs.refresh);
    }
  });

  addCommands(app, serviceManager, tracker);

  // Add command palette and menu items.
  let menu = new Menu({ commands });
  menu.title.label = category;
  [
    CommandIDs.createNew,
    CommandIDs.refresh,
    CommandIDs.increaseFont,
    CommandIDs.decreaseFont,
    CommandIDs.toggleTheme
  ].forEach(command => {
    palette.addItem({ command, category });
    if (command !== CommandIDs.createNew) {
      menu.addItem({ command });
    }
  });
  mainMenu.addMenu(menu, {rank: 40});

  // Add a launcher item if the launcher is available.
  if (launcher) {
    launcher.add({
      displayName: 'Terminal',
      category: 'Other',
      rank: 0,
      iconClass: TERMINAL_ICON_CLASS,
      callback: () => {
        return commands.execute(CommandIDs.createNew);
      }
    });
  }

  app.contextMenu.addItem({command: CommandIDs.refresh, selector: '.jp-Terminal', rank: 1});

  return tracker;
}
开发者ID:cameronoelsen,项目名称:jupyterlab,代码行数:65,代码来源:index.ts

示例9: activate

/**
 * Activate the image widget extension.
 */
function activate(
  app: JupyterFrontEnd,
  palette: ICommandPalette | null,
  restorer: ILayoutRestorer | null
): IImageTracker {
  const namespace = 'image-widget';
  const factory = new ImageViewerFactory({
    name: FACTORY,
    modelName: 'base64',
    fileTypes: FILE_TYPES,
    defaultFor: FILE_TYPES,
    readOnly: true
  });
  const tracker = new InstanceTracker<IDocumentWidget<ImageViewer>>({
    namespace
  });

  if (restorer) {
    // Handle state restoration.
    restorer.restore(tracker, {
      command: 'docmanager:open',
      args: widget => ({ path: widget.context.path, factory: FACTORY }),
      name: widget => widget.context.path
    });
  }

  app.docRegistry.addWidgetFactory(factory);

  factory.widgetCreated.connect((sender, widget) => {
    // Notify the instance tracker if restore data needs to update.
    widget.context.pathChanged.connect(() => {
      void tracker.save(widget);
    });
    void tracker.add(widget);

    const types = app.docRegistry.getFileTypesForPath(widget.context.path);

    if (types.length > 0) {
      widget.title.iconClass = types[0].iconClass;
      widget.title.iconLabel = types[0].iconLabel;
    }
  });

  addCommands(app, tracker);

  if (palette) {
    const category = 'Image Viewer';
    [
      CommandIDs.zoomIn,
      CommandIDs.zoomOut,
      CommandIDs.resetImage,
      CommandIDs.rotateClockwise,
      CommandIDs.rotateCounterclockwise,
      CommandIDs.flipHorizontal,
      CommandIDs.flipVertical,
      CommandIDs.invertColors
    ].forEach(command => {
      palette.addItem({ command, category });
    });
  }

  return tracker;
}
开发者ID:afshin,项目名称:jupyterlab,代码行数:66,代码来源:index.ts

示例10: activate

/**
 * Activate the markdown viewer plugin.
 */
function activate(
  app: JupyterFrontEnd,
  restorer: ILayoutRestorer,
  rendermime: IRenderMimeRegistry,
  settingRegistry: ISettingRegistry
): IMarkdownViewerTracker {
  const { commands, docRegistry } = app;

  // Add the markdown renderer factory.
  rendermime.addFactory(markdownRendererFactory);

  const namespace = 'markdownviewer-widget';
  const tracker = new InstanceTracker<MarkdownDocument>({
    namespace
  });

  let config: Partial<MarkdownViewer.IConfig> = {
    ...MarkdownViewer.defaultConfig
  };

  /**
   * Update the settings of a widget.
   */
  function updateWidget(widget: MarkdownViewer): void {
    Object.keys(config).forEach((k: keyof MarkdownViewer.IConfig) => {
      widget.setOption(k, config[k]);
    });
  }

  /**
   * Update the setting values.
   */
  function updateSettings(settings: ISettingRegistry.ISettings) {
    config = settings.composite as Partial<MarkdownViewer.IConfig>;
    tracker.forEach(widget => {
      updateWidget(widget.content);
    });
  }

  // Fetch the initial state of the settings.
  settingRegistry
    .load(plugin.id)
    .then((settings: ISettingRegistry.ISettings) => {
      settings.changed.connect(() => {
        updateSettings(settings);
      });
      updateSettings(settings);
    })
    .catch((reason: Error) => {
      console.error(reason.message);
    });

  // Register the MarkdownViewer factory.
  const factory = new MarkdownViewerFactory({
    rendermime,
    name: FACTORY,
    primaryFileType: docRegistry.getFileType('markdown'),
    fileTypes: ['markdown'],
    defaultRendered: ['markdown']
  });
  factory.widgetCreated.connect((sender, widget) => {
    // Notify the instance tracker if restore data needs to update.
    widget.context.pathChanged.connect(() => {
      void tracker.save(widget);
    });
    // Handle the settings of new widgets.
    updateWidget(widget.content);
    void tracker.add(widget);
  });
  docRegistry.addWidgetFactory(factory);

  // Handle state restoration.
  restorer.restore(tracker, {
    command: 'docmanager:open',
    args: widget => ({ path: widget.context.path, factory: FACTORY }),
    name: widget => widget.context.path
  });

  commands.addCommand(CommandIDs.markdownPreview, {
    label: 'Markdown Preview',
    execute: args => {
      let path = args['path'];
      if (typeof path !== 'string') {
        return;
      }
      return commands.execute('docmanager:open', {
        path,
        factory: FACTORY,
        options: args['options']
      });
    }
  });

  return tracker;
}
开发者ID:afshin,项目名称:jupyterlab,代码行数:98,代码来源:index.ts


注:本文中的@jupyterlab/application.ILayoutRestorer.restore方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。