A RetroSearch Logo

Home - News ( United States | United Kingdom | Italy | Germany ) - Football scores

Search Query:

Showing content from https://jupyterlab.readthedocs.io/en/latest/extension/extension_points.html below:

Common Extension Points — JupyterLab 4.5.0a2 documentation

Common Extension Points#

Most of the component parts of JupyterLab are designed to be extensible, and they provide services that can be requested in extensions via tokens. A list of common core tokens that extension authors can request is given in Core Plugins.

Following the list of core tokens is a guide for using some of JupyterLab’s most commonly-used extension points. However, it is not an exhaustive account of how to extend the application components, and more detailed descriptions of their public APIs may be found in the JupyterLab and Lumino API documentation.

Table of contents

Core Plugins#

The core packages of JupyterLab provide the following plugins. They can be enabled or disabled using the command jupyter labextension enable <plugin-id> or jupyter labextension disable <plugin-id>.

Core Tokens#

The core packages of JupyterLab provide many services for plugins. The tokens for these services are listed here, along with short descriptions of when you might want to use the services in your extensions.

Commands# Add a Command to the Command Registry#

Perhaps the most common way to add functionality to JupyterLab is via commands. These are lightweight objects that include a function to execute combined with additional metadata, including how they are labeled and when they are to be enabled. The application has a single command registry, keyed by string command IDs, to which you can add your custom commands.

The commands added to the command registry can then be used to populate several of the JupyterLab user interface elements, including menus and the launcher.

Here is a sample block of code that adds a command to the application (given by app):

const commandID = 'my-command';
let toggled = false;

app.commands.addCommand(commandID, {
  label: 'My Cool Command',
  isEnabled: () => true,
  isVisible: () => true,
  isToggled: () => toggled,
  iconClass: 'some-css-icon-class',
  describedBy: {
    args: {
      type: 'object',
      properties: {
        text: {
          type: 'string',
          description: 'Optional text to log',
          default: ''
        },
        count: {
          type: 'number',
          description: 'Optional number of times to log the text',
          default: 1
        }
      }
    }
  },
  execute: (args) => {
    const text = args?.text || '';
    const count = args?.count || 1;
    for (let i = 0; i < count; i++) {
      console.log(`Executed ${commandID} with text: ${text}`);
    }
  }
});

This example adds a new command, which, when triggered, calls the execute function. isEnabled indicates whether the command is enabled, and determines whether renderings of it are greyed out. isToggled indicates whether to render a check mark next to the command. isVisible indicates whether to render the command at all. iconClass specifies a CSS class which can be used to display an icon next to renderings of the command. describedBy is an optional but recommended property that provides a JSON schema describing the command’s arguments, which is useful for documentation, tooling, and ensuring consistency in how the command is invoked.

Each of isEnabled, isToggled, and isVisible can be either a boolean value or a function that returns a boolean value, in case you want to do some logic in order to determine those conditions.

Likewise, each of label and iconClass can be either a string value or a function that returns a string value.

There are several more options which can be passed into the command registry when adding new commands. These are documented here.

After a command has been added to the application command registry you can add them to various places in the application user interface, where they will be rendered using the metadata you provided.

For example, you can add a button to the Notebook toolbar to run the command with the CommandToolbarButtonComponent.

Add a Command to the Command Palette#

In order to add an existing, registered command to the command palette, you need to request the ICommandPalette token in your extension. Here is an example showing how to add a command to the command palette (given by palette):

palette.addItem({
  command: commandID,
  category: 'my-category',
  args: {}
});

The command ID is the same ID that you used when registering the command. You must also provide a category, which determines the subheading of the command palette in which to render the command. It can be a preexisting category (e.g., 'notebook'), or a new one of your own choosing.

The args are a JSON object that will be passed into your command’s functions at render/execute time. You can use these to customize the behavior of your command depending on how it is invoked. For instance, you can pass in args: { isPalette: true }. Your command label function can then check the args it is provided for isPalette, and return a different label in that case. This can be useful to make a single command flexible enough to work in multiple contexts.

Icons#

See Reusing JupyterLab UI

Keyboard Shortcuts#

There are two ways of adding keyboard shortcuts in JupyterLab. If you don’t want the shortcuts to be user-configurable, you can add them directly to the application command registry:

app.commands.addKeyBinding({
  command: commandID,
  args: {},
  keys: ['Accel T'],
  selector: '.jp-Notebook'
});

In this example my-command command is mapped to Accel T, where Accel corresponds to Cmd on a Mac and Ctrl on Windows and Linux computers.

The behavior for keyboard shortcuts is very similar to that of the context menu: the shortcut handler propagates up the DOM tree from the focused element and tests each element against the registered selectors. If a match is found, then that command is executed with the provided args. Full documentation for the options for addKeyBinding can be found here.

JupyterLab also provides integration with its settings system for keyboard shortcuts. Your extension can provide a settings schema with a jupyter.lab.shortcuts key, declaring default keyboard shortcuts for a command:

{
  "jupyter.lab.shortcuts": [
    {
      "command": "my-command",
      "keys": ["Accel T"],
      "selector": ".jp-mod-searchable"
    }
  ]
}

Shortcuts added to the settings system will be editable by users.

From Jupyterlab version 3.1 onwards, it is possible to execute multiple commands with a single shortcut. This requires you to define a keyboard shortcut for apputils:run-all-enabled command:

{
  "command": "apputils:run-all-enabled",
  "keys": ["Accel T"],
  "args": {
    "commands": [
      "my-command-1",
      "my-command-2"
    ],
    "args": [
      {},
      {}
    ]
  },
  "selector": "body"
}

In this example my-command-1 and my-command-2 are passed in args of apputils:run-all-enabled command as commands list. You can optionally pass the command arguments of my-command-1 and my-command-2 in args of apputils:run-all-enabled command as args list.

Launcher#

As with menus, keyboard shortcuts, and the command palette, new items can be added to the application launcher via commands. You can do this by requesting the ILauncher token in your extension:

launcher.add({
  command: commandID,
  category: 'Other',
  rank: 0
});

In addition to providing a command ID, you also provide a category in which to put your item, (e.g. ‘Notebook’, or ‘Other’), as well as a rank to determine its position among other items.

Jupyter Front-End Shell#

The Jupyter front-end shell is used to add and interact with content in the application. The IShell interface provides an add() method for adding widgets to the application. In JupyterLab, the application shell consists of:

Top Area#

The top area is intended to host most persistent user interface elements that span the whole session of a user. A toolbar named TopBar is available on the right of the main menu bar. For example, JupyterLab adds a user dropdown to that toolbar when started in collaborative mode.

See generic toolbars to see how to add a toolbar or a custom widget to a toolbar.

You can use a numeric rank to control the ordering of top bar items in the settings; see Toolbar definitions.

JupyterLab adds a spacer widget to the top bar at rank 50 by default. You can then use the following guidelines to place your items:

Left/Right Areas#

The left and right sidebar areas of JupyterLab are intended to host more persistent user interface elements than the main area. That being said, extension authors are free to add whatever components they like to these areas. The outermost-level of the object that you add is expected to be a Lumino Widget, but that can host any content you like (such as React components).

As an example, the following code executes an application command to a terminal widget and then adds the terminal to the right area:

app.commands
  .execute('terminal:create-new')
  .then((terminal: WidgetModuleType.Terminal) => {
    app.shell.add(terminal, 'right');
  });

You can use a numeric rank to control the ordering of the left and right tabs:

app.shell.add(terminal, 'left', {rank: 600});

The recommended ranges for this rank are:

Main Menu#

There are two ways to extend JupyterLab’s main menu.

  1. Using the settings - this is the preferred way as they are configurable by the user.

  2. Using the API - this is for advanced cases like dynamic menu or semantic items.

Status Bar#

JupyterLab’s status bar is intended to show small pieces of contextual information. Like the left and right areas, it only expects a Lumino Widget, which might contain any kind of content. Since the status bar has limited space, you should endeavor to only add small widgets to it.

The following example shows how to place a status item that displays the current “busy” status for the application. This information is available from the ILabStatus token, which we reference by a variable named labStatus. We place the statusWidget in the middle of the status bar. When the labStatus busy state changes, we update the text content of the statusWidget to reflect that.

const statusWidget = new Widget();
labStatus.busySignal.connect(() => {
  statusWidget.node.textContent = labStatus.isBusy ? 'Busy' : 'Idle';
});
statusBar.registerStatusItem('lab-status', {
  align: 'middle',
  item: statusWidget
});
Toolbar Registry#

JupyterLab provides an infrastructure to define and customize toolbar widgets from the settings, which is similar to that defining the context menu and the main menu bar.

Document Widgets#

A typical example is the notebook toolbar as in the snippet below:

function activatePlugin(
  app: JupyterFrontEnd,
  // ...
  toolbarRegistry: IToolbarWidgetRegistry | null,
  settingRegistry: ISettingRegistry | null
): NotebookWidgetFactory.IFactory {
  const { commands } = app;
  let toolbarFactory:
    | ((widget: NotebookPanel) => DocumentRegistry.IToolbarItem[])
    | undefined;

  // Register notebook toolbar specific widgets
  if (toolbarRegistry) {
    toolbarRegistry.registerFactory<NotebookPanel>(FACTORY, 'cellType', panel =>
      ToolbarItems.createCellTypeItem(panel, translator)
    );

    toolbarRegistry.registerFactory<NotebookPanel>(
      FACTORY,
      'kernelStatus',
      panel => Toolbar.createKernelStatusItem(panel.sessionContext, translator)
    );
    // etc...

    if (settingRegistry) {
      // Create the factory
      toolbarFactory = createToolbarFactory(
        toolbarRegistry,
        settingRegistry,
        // Factory name
        FACTORY,
        // Setting id in which the toolbar items are defined
        '@jupyterlab/notebook-extension:panel',
        translator
      );
    }
  }

  const factory = new NotebookWidgetFactory({
    name: FACTORY,
    fileTypes: ['notebook'],
    modelName: 'notebook',
    defaultFor: ['notebook'],
    // ...
    toolbarFactory,
    translator: translator
  });
  app.docRegistry.addWidgetFactory(factory);

The registry registerFactory method allows an extension to provide special widget for a unique pair (factory name, toolbar item name). Then the helper createToolbarFactory can be used to extract the toolbar definition from the settings and build the factory to pass to the widget factory.

The default toolbar items can be defined across multiple extensions by providing an entry in the "jupyter.lab.toolbars" mapping. For example for the notebook panel:

The settings registry will merge those definitions from settings schema with any user-provided overrides (customizations) transparently and save them under the toolbar property in the final settings object. The toolbar list will be used to create the toolbar. Both the source settings schema and the final settings object are identified by the plugin ID passed to createToolbarFactory. The user can customize the toolbar by adding new items or overriding existing ones (like providing a different rank or adding "disabled": true to remove the item).

Note

You need to set jupyter.lab.transform to true in the plugin id that will gather all items.

What are transforms? The jupyter.lab.transform flag tells JupyterLab to wait for a transform function before loading the plugin. This allows dynamic modification of settings schemas, commonly used to merge toolbar/menu definitions from multiple extensions.

Loading order pitfall: Extensions providing transforms must register them early in activation, before dependent plugins load, otherwise those plugins will timeout waiting for the transform.

The current widget factories supporting the toolbar customization are:

And the toolbar item must follow this definition:

{
  "toolbarItem": {
    "properties": {
      "name": {
        "title": "Unique name",
        "type": "string"
      },
      "args": {
        "title": "Command arguments",
        "type": "object"
      },
      "command": {
        "title": "Command id",
        "type": "string",
        "default": ""
      },
      "disabled": {
        "title": "Whether the item is ignored or not",
        "type": "boolean",
        "default": false
      },
      "icon": {
        "title": "Item icon id",
        "description": "If defined, it will override the command icon",
        "type": "string"
      },
      "label": {
        "title": "Item label",
        "description": "If defined, it will override the command label",
        "type": "string"
      },
      "caption": {
        "title": "Item caption",
        "description": "If defined, it will override the command caption",
        "type": "string"
      },
      "type": {
        "title": "Item type",
        "type": "string",
        "enum": [
          "command",
          "spacer"
        ]
      },
      "rank": {
        "title": "Item rank",
        "type": "number",
        "minimum": 0,
        "default": 50
      }
    },
    "required": [
      "name"
    ],
    "additionalProperties": false,
    "type": "object"
  }
}
Generic Widget with Toolbar#

The logic detailed in the previous section can be used to customize any widgets with a toolbar.

The additional keys used in jupyter.lab.toolbars settings attributes are:

Here is an example for enabling a toolbar on a widget:

function activatePlugin(
  app: JupyterFrontEnd,
  // ...
  toolbarRegistry: IToolbarWidgetRegistry,
  settingRegistry: ISettingRegistry
): void {

  const browser = new FileBrowser();

  // Toolbar
  // - Define a custom toolbar item
  toolbarRegistry.registerFactory(
    'FileBrowser', // Factory name
    'uploader',
    (browser: FileBrowser) =>
      new Uploader({ model: browser.model, translator })
  );

  // - Link the widget toolbar and its definition from the settings
  setToolbar(
    browser, // This widget is the one passed to the toolbar item factory
    createToolbarFactory(
      toolbarRegistry,
      settings,
      'FileBrowser', // Factory name
      plugin.id,
      translator
    ),
    // You can explicitly pass the toolbar widget if it is not accessible as `toolbar` attribute
    // toolbar,
  );

See Toolbar definitions example on how to define the toolbar items in the settings.

Widget Tracker#

Often extensions will want to interact with documents and activities created by other extensions. For instance, an extension may want to inject some text into a notebook cell, or set a custom keymap, or close all documents of a certain type. Actions like these are typically done by widget trackers. Extensions keep track of instances of their activities in WidgetTrackers, which are then provided as tokens so that other extensions may request them.

For instance, if you want to interact with notebooks, you should request the INotebookTracker token. You can then use this tracker to iterate over, filter, and search all open notebooks. You can also use it to be notified via signals when notebooks are added and removed from the tracker.

Widget tracker tokens are provided for many activities in JupyterLab, including notebooks, consoles, text files, mime documents, and terminals. If you are adding your own activities to JupyterLab, you might consider providing a WidgetTracker token of your own, so that other extensions can make use of it.

Completion Providers#

Both code completer and inline completer can be extended by registering an (inline) completion provider on the completion manager provided by the ICompletionProviderManager token.

Code Completer#

A minimal code completion provider needs to implement the fetch and isApplicable methods, and define a unique identifier property, but the ICompletionProvider interface allows for much more extensive customization of the completer.

import {
  CompletionHandler,
  ICompletionProviderManager,
  ICompletionContext,
  ICompletionProvider
} from '@jupyterlab/completer';

class MyProvider implements ICompletionProvider {
  readonly identifier = 'my-provider';

  async isApplicable(context: ICompletionContext) {
    return true;
  }

  async fetch(
    request: CompletionHandler.IRequest,
    context: ICompletionContext
  ) {
    return {
      start: request.offset,
      end: request.offset,
      items: [
        { label: 'option 1' },
        { label: 'option 2' }
      ]
    };
  }
}

const plugin: JupyterFrontEndPlugin<void> = {
  id: 'my-completer-extension:provider',
  autoStart: true,
  requires: [ICompletionProviderManager],
  activate: (app: JupyterFrontEnd, manager: ICompletionProviderManager): void => {
    const provider = new MyProvider();
    manager.registerProvider(provider);
  }
};

A more detailed example is provided in the extension-examples repository.

For an example of an extensively customised completion provider, see the jupyterlab-lsp extension.

Inline Completer#

A minimal inline completion provider extension would only implement the required method fetch and define identifier and name properties, but a number of additional fields can be used for enhanced functionality, such as streaming, see the IInlineCompletionProvider documentation.

import {
  CompletionHandler,
  ICompletionProviderManager,
  IInlineCompletionContext,
  IInlineCompletionProvider
} from '@jupyterlab/completer';

class MyInlineProvider implements IInlineCompletionProvider {
  readonly identifier = 'my-provider';
  readonly name = 'My provider';

  async fetch(
    request: CompletionHandler.IRequest,
    context: IInlineCompletionContext
  ) {
    return {
      items: [
        { insertText: 'suggestion 1' },
        { insertText: 'suggestion 2' }
      ]
    };
  }
}

const plugin: JupyterFrontEndPlugin<void> = {
  id: 'my-completer-extension:inline-provider',
  autoStart: true,
  requires: [ICompletionProviderManager],
  activate: (app: JupyterFrontEnd, manager: ICompletionProviderManager): void => {
    const provider = new MyInlineProvider();
    manager.registerInlineProvider(provider);
  }
};

For an example of an inline completion provider with streaming support, see jupyterlab-transformers-completer.

State Database#

The state database can be accessed by importing IStateDB from @jupyterlab/statedb and adding it to the list of requires for a plugin:

const id = 'foo-extension:IFoo';

const IFoo = new Token<IFoo>(id);

interface IFoo {}

class Foo implements IFoo {}

const plugin: JupyterFrontEndPlugin<IFoo> = {
  id,
  autoStart: true,
  requires: [IStateDB],
  provides: IFoo,
  activate: (app: JupyterFrontEnd, state: IStateDB): IFoo => {
    const foo = new Foo();
    const key = `${id}:some-attribute`;

    // Load the saved plugin state and apply it once the app
    // has finished restoring its former layout.
    Promise.all([state.fetch(key), app.restored])
      .then(([saved]) => { /* Update `foo` with `saved`. */ });

    // Fulfill the plugin contract by returning an `IFoo`.
    return foo;
  }
};
Kernel Subshells#

Kernel subshells enable concurrent code execution within kernels that support them. Subshells are separate threads of execution that allow interaction with a kernel while it’s busy executing long-running code, enabling non-blocking communication and parallel execution.

Kernel Support

Subshells are supported by:

User Interface

For user interface details, see Subshell Consoles.

Extension Development

Extension developers can use subshell functionality through the kernel service API:

import { INotebookTracker } from '@jupyterlab/notebook';

// Get the current kernel from a notebook
const current = tracker.currentWidget;
if (!current) return;

const kernel = current.sessionContext.session?.kernel;
if (!kernel) return;

// Check if kernel supports subshells
if (kernel.supportsSubshells) {
  // Create a new subshell
  const reply = await kernel.requestCreateSubshell({}).done;
  const subshellId = reply.content.subshell_id;
  console.log(`Created subshell: ${subshellId}`);

  // List existing subshells
  const listReply = await kernel.requestListSubshell({}).done;
  console.log(`Active subshells: ${listReply.content.subshell_id}`);

  // Execute code in a specific subshell
  const future = kernel.requestExecute(
    { code: 'print("Hello from subshell!")' },
    false, // disposeOnDone
    { subshell_id: subshellId } // metadata
  );
  await future.done;

  // Delete a subshell when done
  await kernel.requestDeleteSubshell({ subshell_id: subshellId }).done;
  console.log(`Deleted subshell: ${subshellId}`);
}

For detailed specifications, see JEP 91.

LSP Features#

JupyterLab provides an infrastructure to communicate with the language servers. If the LSP services are activated and users have language servers installed, JupyterLab will start the language servers for the language of the opened notebook or file. Extension authors can access the virtual documents and the associated LSP connection of opened document by requiring the ILSPDocumentConnectionManager token from @jupyterlab/lsp.

Here is an example for making requests to the language server.

const plugin: JupyterFrontEndPlugin<void> = {
  id,
  autoStart: true,
  requires: [ILSPDocumentConnectionManager],
  activate: async (app: JupyterFrontEnd, manager: ILSPDocumentConnectionManager): Promise<void> => {

    // Get the path to the opened notebook of file
    const path = ...

    // Get the widget adapter of opened document
    const adapter = manager.adapters.get(path);
    if (!adapter) {
      return
    }
    // Get the associated virtual document of the opened document
    const virtualDocument = adapter.virtualDocument;

    // Get the LSP connection of the virtual document.
    const connection = manager.connections.get(virtualDocument.uri);
    ...
    // Send completion request to the language server
    const response = await connection.clientRequests['textDocument/completion'].request(params);
    ...
  }
};

Occasionally, LSP extensions include a CodeMirror extension to modify the code editor. In those cases, you can follow this example:

const renamePlugin: JupyterFrontEndPlugin<void> = {
  id,
  autoStart: true,
  requires: [ILSPDocumentConnectionManager, ILSPFeatureManager, IWidgetLSPAdapterTracker],
  activate: (app: JupyterFrontEnd, connectionManager: ILSPDocumentConnectionManager, featureManager: ILSPFeatureManager, tracker: IWidgetLSPAdapterTracker) => {
    const FEATURE_ID = "rename_symbol";
    const extensionFactory: EditorAdapter.ILSPEditorExtensionFactory = {
      name: FEATURE_ID,
      factory: (options) =>  {
        const { editor, widgetAdapter } = options;

        // Get the editor
        const ceEditor: CodeEditor.IEditor | null = editor.getEditor();
        if (!ceEditor) {
          return null;
        }

        // Get the associated virtual document of the opened document
        if (!widgetAdapter.virtualDocument) {
          return null;
        }

        // Get the LSP connection of the virtual document.
        const connection = connectionManager.connections.get(widgetAdapter.virtualDocument.uri);
        if (!connection || !connection.provides('renameProvider')) {
          return null;
        }

        // Create a CodeMirror extension that listens for double click, gets the
        // selected code and makes a LSP request to rename it and prints the results.
        const ext = EditorView.domEventHandlers({ dblclick: (e, view) => {
          const range = ceEditor.getSelection();
            const res = connection.clientRequests['textDocument/rename'].request({
              newName: "test",
              position: { line: range.start.line, character: range.start.column },
              textDocument: { uri: widgetAdapter.virtualDocument!.uri }
            });

            res.then(value => {
              console.debug(value);
            }).catch(e => console.error);
        }});

        // Wrap the CodeMirror extension in the extension registry object.
        return EditorExtensionRegistry.createImmutableExtension(ext);
      }
    }

    // Register the extension with the LSP feature
    featureManager.register({
      id: FEATURE_ID,
      extensionFactory
    });
  }
};
Content Provisioning#

The file system interactions can be customized by adding:

While both the content provider and drive are meant to provide custom implementations of the Contents API methods such as get() and save(), and optionally a custom sharedModelFactory, the intended use cases, and the way these are exposed in the user interface are different:

To register a custom drive, use the contents manager’s addDrive method. The drive needs to follow the IDrive interface. For drives that use a jupyter-server compliant REST API you may wish to extend or re-use the built-in Drive class, as demonstrated below:

import { Drive, ServerConnection } from '@jupyterlab/services';

const customDrivePlugin: JupyterFrontEndPlugin<void> = {
  id: 'my-extension:custom-drive',
  autoStart: true,
  activate: (app: JupyterFrontEnd) => {
    const myDrive = new Drive({
      apiEndpoint: 'api/contents',
      name: 'MyNetworkDrive',
      serverSettings: {
        baseUrl: 'https://your-jupyter-server.com',
        // ...
      } as ServerConnection.ISettings,
    });
    app.serviceManager.contents.addDrive(myDrive);
  }
};

To use a content provider, first register it on a drive (or multiple drives):

import { Contents, ContentsManager, RestContentProvider } from '@jupyterlab/services';

interface IMyContentChunk {
  /** URL allowing to fetch the content chunk */
  url: string;
}

interface CustomContentsModel extends Contents.IModel {
  /**
   * Specializes the content (which in `Contents.IModel` is just `any`).
   */
  content: IMyContentChunk[];
}

class CustomContentProvider extends RestContentProvider {
  async get(
    localPath: string,
    options?: Contents.IFetchOptions,
  ): Promise<CustomContentsModel> {
    // Customize the behaviour of the `get` action to fetch a list of
    // content chunks from a custom API endpoint instead of the `get`

    try {
      return getChunks();    // this method needs to be implemented
    }
    catch {
      // fall back to the REST API on errors:
      const model = await super.get(localPath, options);
      return {
        ...model,
        content: []
      };
    }
  }

  // ...
}

const customContentProviderPlugin: JupyterFrontEndPlugin<void> = {
  id: 'my-extension:custom-content-provider',
  autoStart: true,
  activate: (app: JupyterFrontEnd) => {
    const drive = (app.serviceManager.contents as ContentsManager).defaultDrive;
    const registry = drive?.contentProviderRegistry;
    if (!registry) {
      // If content provider is a non-essential feature and support for JupyterLab <4.4 is desired:
      console.error('Cannot initialize content provider: no content provider registry.');
      return;
    }
    const customContentProvider = new CustomContentProvider({
      // These options are only required if extending the `RestContentProvider`.
      apiEndpoint: '/api/contents',
      serverSettings: app.serviceManager.serverSettings,
    });
    registry.register('my-custom-provider', customContentProvider);
  }
};

and then create and register a widget factory which will understand how to make use of your custom content provider:

class ExampleWidgetFactory extends ABCWidgetFactory<ExampleDocWidget, ExampleDocModel> {
  protected createNewWidget(
    context: DocumentRegistry.IContext<ExampleDocModel>
  ): ExampleDocWidget {

    return new ExampleDocWidget({
      context,
      content: new ExamplePanel(context)
    });
  }
}

const widgetFactoryPlugin: JupyterFrontEndPlugin<void> = {
  id: 'my-extension:custom-widget-factory',
  autoStart: true,
  activate: (app: JupyterFrontEnd) => {

    const widgetFactory = new ExampleWidgetFactory({
      name: FACTORY,
      modelName: 'example-model',
      fileTypes: ['example'],
      defaultFor: ['example'],
      // Instructs the document registry to use the custom provider
      // for context of widgets created with `ExampleWidgetFactory`.
      contentProviderId: 'my-custom-provider'
    });
    app.docRegistry.addWidgetFactory(widgetFactory);
  }
};

Where ExampleDocModel can now expect the CustomContentsModel rather than Contents.IModel:

class ExampleDocModel implements DocumentRegistry.IModel {
  // ...

  fromJSON(chunks: IMyContentChunk[]): void {
    this.sharedModel.transact(() => {
      let i = 0;
      for (const chunk of chunks) {
        const chunk = fetch(chunk.url);
        this.sharedModel.set(`chunk-${i}`, chunk);
        i += 1;
      }
    });
  }

  fromString(data: string): void {
    const chunks = JSON.parse(data) as IMyContentChunk[];
    return this.fromJSON(chunks);
  }
}

For a complete example of a widget factory (although not using a content provider), see the documents extension example.


RetroSearch is an open source project built by @garambo | Open a GitHub Issue

Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo

HTML: 3.2 | Encoding: UTF-8 | Version: 0.7.4