extension_points.rst 37 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969
  1. .. _developer-extension-points:
  2. Common Extension Points
  3. =======================
  4. Most of the component parts of JupyterLab are designed to be extensible,
  5. and they provide services that can be requested in extensions via tokens.
  6. A list of common core tokens that extension authors can request is given in :ref:`core_tokens`.
  7. Following the list of core tokens is a guide for using some of JupyterLab's most commonly-used extension points.
  8. However, it is not an exhaustive account of how to extend the application components,
  9. and more detailed descriptions of their public APIs may be found in the
  10. `JupyterLab <../api/index.html>`__ and
  11. `Lumino <https://jupyterlab.github.io/lumino/index.html>`__ API documentation.
  12. .. contents:: Table of contents
  13. :local:
  14. :depth: 1
  15. .. _core_tokens:
  16. Core Tokens
  17. -----------
  18. The core packages of JupyterLab provide many services for plugins. The tokens
  19. for these services are listed here, along with short descriptions of when you
  20. might want to use the services in your extensions.
  21. - ``@jupyterlab/application:IConnectionLost``: A service for invoking the dialog shown
  22. when JupyterLab has lost its connection to the server. Use this if, for some reason,
  23. you want to bring up the "connection lost" dialog under new circumstances.
  24. - ``@jupyterlab/application:IInfo``: A service providing metadata about the current
  25. application, including disabled extensions and whether dev mode is enabled.
  26. - ``@jupyterlab/application:IPaths``: A service providing information about various
  27. URLs and server paths for the current application. Use this service if you want to
  28. assemble URLs to use the JupyterLab REST API.
  29. - ``@jupyterlab/application:ILabStatus``: A service for interacting with the application busy/dirty
  30. status. Use this if you want to set the application "busy" favicon, or to set
  31. the application "dirty" status, which asks the user for confirmation before leaving the application page.
  32. - ``@jupyterlab/application:ILabShell``: A service for interacting with the JupyterLab shell.
  33. The top-level ``application`` object also has a reference to the shell, but it has a restricted
  34. interface in order to be agnostic to different shell implementations on the application.
  35. Use this to get more detailed information about currently active widgets and layout state.
  36. - ``@jupyterlab/application:ILayoutRestorer``: A service providing application layout
  37. restoration functionality. Use this to have your activities restored across
  38. page loads.
  39. - ``@jupyterlab/application:IMimeDocumentTracker``: A widget tracker for documents
  40. rendered using a mime renderer extension. Use this if you want to list and interact
  41. with documents rendered by such extensions.
  42. - ``@jupyterlab/application:IRouter``: The URL router used by the application.
  43. Use this to add custom URL-routing for your extension (e.g., to invoke
  44. a command if the user navigates to a sub-path).
  45. - ``@jupyterlab/apputils:ICommandPalette``: A service for the application command palette
  46. in the left panel. Use this to add commands to the palette.
  47. - ``@jupyterlab/apputils:ISplashScreen``: A service for the splash screen for the application.
  48. Use this if you want to show the splash screen for your own purposes.
  49. - ``@jupyterlab/apputils:IThemeManager``: A service for the theme manager for the application. This is used primarily in theme extensions to register new themes.
  50. - ``@jupyterlab/apputils:IToolbarWidgetRegistry``: A registry for toolbar widgets. Require this
  51. if you want to build the toolbar dynamically from a data definition (stored in settings for example).
  52. - ``@jupyterlab/apputils:IWindowResolver``: A service for a window resolver for the
  53. application. JupyterLab workspaces are given a name, which are determined using
  54. the window resolver. Require this if you want to use the name of the current workspace.
  55. - ``@jupyterlab/codeeditor:IEditorServices``: A service for the text editor provider
  56. for the application. Use this to create new text editors and host them in your
  57. UI elements.
  58. - ``@jupyterlab/completer:ICompletionManager``: A service for the completion manager
  59. for the application. Use this to allow your extension to invoke a completer.
  60. - ``@jupyterlab/console:IConsoleTracker``: A widget tracker for code consoles.
  61. Use this if you want to be able to iterate over and interact with code consoles
  62. created by the application.
  63. - ``@jupyterlab/console:IContentFactory``: A factory object that creates new code
  64. consoles. Use this if you want to create and host code consoles in your own UI elements.
  65. - ``@jupyterlab/docmanager:IDocumentManager``: A service for the manager for all
  66. documents used by the application. Use this if you want to open and close documents,
  67. create and delete files, and otherwise interact with the file system.
  68. - ``@jupyterlab/docprovider:IDocumentProviderFactory``: A factory object that creates new providers for
  69. shared documents. Use this if you want to create a provider for a new shared document.
  70. - ``@jupyterlab/documentsearch:ISearchProviderRegistry``: A service for a registry of search
  71. providers for the application. Plugins can register their UI elements with this registry
  72. to provide find/replace support.
  73. - ``@jupyterlab/filebrowser:IFileBrowserFactory``: A factory object that creates file browsers.
  74. Use this if you want to create your own file browser (e.g., for a custom storage backend),
  75. or to interact with other file browsers that have been created by extensions.
  76. - ``@jupyterlab/fileeditor:IEditorTracker``: A widget tracker for file editors.
  77. Use this if you want to be able to iterate over and interact with file editors
  78. created by the application.
  79. - ``@jupyterlab/htmlviewer:IHTMLViewerTracker``: A widget tracker for rendered HTML documents.
  80. Use this if you want to be able to iterate over and interact with HTML documents
  81. viewed by the application.
  82. - ``@jupyterlab/imageviewer:IImageTracker``: A widget tracker for images.
  83. Use this if you want to be able to iterate over and interact with images
  84. viewed by the application.
  85. - ``@jupyterlab/inspector:IInspector``: A service for adding contextual help to widgets (visible using "Show Contextual Help" from the Help menu).
  86. Use this to hook into the contextual help system in your extension.
  87. - ``@jupyterlab/launcher:ILauncher``: A service for the application activity launcher.
  88. Use this to add your extension activities to the launcher panel.
  89. - ``@jupyterlab/mainmenu:IMainMenu``: A service for the main menu bar for the application.
  90. Use this if you want to add your own menu items or provide implementations for standardized menu items for specific activities.
  91. - ``@jupyterlab/markdownviewer:IMarkdownViewerTracker``: A widget tracker for markdown
  92. document viewers. Use this if you want to iterate over and interact with rendered markdown documents.
  93. - ``@jupyterlab/notebook:INotebookTools``: A service for the ``Notebook Tools`` panel in the
  94. right sidebar. Use this to add your own functionality to the panel.
  95. - ``@jupyterlab/notebook:IContentFactory``: A factory object that creates new notebooks.
  96. Use this if you want to create and host notebooks in your own UI elements.
  97. - ``@jupyterlab/notebook:INotebookTracker``: A widget tracker for notebooks.
  98. Use this if you want to be able to iterate over and interact with notebooks
  99. created by the application.
  100. - ``@jupyterlab/rendermime:IRenderMimeRegistry``: A service for the rendermime registry
  101. for the application. Use this to create renderers for various mime-types in your extension. Many times it will be easier to create a `mime renderer extension <#mime-renderer-extensions>`__ rather than using this service directly.
  102. - ``@jupyterlab/rendermime:ILatexTypesetter``: A service for the LaTeX typesetter for the
  103. application. Use this if you want to typeset math in your extension.
  104. - ``@jupyterlab/settingeditor:ISettingEditorTracker``: A widget tracker for setting editors.
  105. Use this if you want to be able to iterate over and interact with setting editors
  106. created by the application.
  107. - ``@jupyterlab/settingregistry:ISettingRegistry``: A service for the JupyterLab settings system.
  108. Use this if you want to store settings for your application.
  109. See :ref:`schemaDir` for more information.
  110. - ``@jupyterlab/statedb:IStateDB``: A service for the JupyterLab state database.
  111. Use this if you want to store data that will persist across page loads.
  112. See `state database <#state-database>`__ for more information.
  113. - ``@jupyterlab/statusbar:IStatusBar``: A service for the status bar on the application.
  114. Use this if you want to add new status bar items.
  115. - ``@jupyterlab/terminal:ITerminalTracker``: A widget tracker for terminals.
  116. Use this if you want to be able to iterate over and interact with terminals
  117. created by the application.
  118. - ``@jupyterlab/tooltip:ITooltipManager``: A service for the tooltip manager for the application.
  119. Use this to allow your extension to invoke a tooltip.
  120. - ``@jupyterlab/vdom:IVDOMTracker``: A widget tracker for virtual DOM (VDOM) documents.
  121. Use this to iterate over and interact with VDOM document instances created by the application.
  122. Commands
  123. --------
  124. Add a Command to the Command Registry
  125. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  126. Perhaps the most common way to add functionality to JupyterLab is via commands.
  127. These are lightweight objects that include a function to execute combined with
  128. additional metadata, including how they are labeled and when they are to be enabled.
  129. The application has a single command registry, keyed by string command IDs,
  130. to which you can add your custom commands.
  131. The commands added to the command registry can then be used to populate
  132. several of the JupyterLab user interface elements, including menus and the launcher.
  133. Here is a sample block of code that adds a command to the application (given by ``app``):
  134. .. code:: typescript
  135. const commandID = 'my-command';
  136. let toggled = false;
  137. app.commands.addCommand(commandID, {
  138. label: 'My Cool Command',
  139. isEnabled: () => true,
  140. isVisible: () => true,
  141. isToggled: () => toggled,
  142. iconClass: 'some-css-icon-class',
  143. execute: () => {
  144. console.log(`Executed ${commandID}`);
  145. toggled = !toggled;
  146. });
  147. This example adds a new command, which, when triggered, calls the ``execute`` function.
  148. ``isEnabled`` indicates whether the command is enabled, and determines whether renderings of it are greyed out.
  149. ``isToggled`` indicates whether to render a check mark next to the command.
  150. ``isVisible`` indicates whether to render the command at all.
  151. ``iconClass`` specifies a CSS class which can be used to display an icon next to renderings of the command.
  152. Each of ``isEnabled``, ``isToggled``, and ``isVisible`` can be either
  153. a boolean value or a function that returns a boolean value, in case you want
  154. to do some logic in order to determine those conditions.
  155. Likewise, each of ``label`` and ``iconClass`` can be either
  156. a string value or a function that returns a string value.
  157. There are several more options which can be passed into the command registry when
  158. adding new commands. These are documented
  159. `here <https://jupyterlab.github.io/lumino/commands/interfaces/commandregistry.icommandoptions.html>`__.
  160. After a command has been added to the application command registry
  161. you can add them to various places in the application user interface,
  162. where they will be rendered using the metadata you provided.
  163. For example, you can add a button to the Notebook toolbar to run the command with the ``CommandToolbarButtonComponent``.
  164. Add a Command to the Command Palette
  165. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  166. In order to add an existing, registered command to the command palette, you need to request the
  167. ``ICommandPalette`` token in your extension.
  168. Here is an example showing how to add a command to the command palette (given by ``palette``):
  169. .. code:: typescript
  170. palette.addItem({
  171. command: commandID,
  172. category: 'my-category',
  173. args: {}
  174. });
  175. The command ID is the same ID that you used when registering the command.
  176. You must also provide a ``category``, which determines the subheading of
  177. the command palette in which to render the command.
  178. It can be a preexisting category (e.g., ``'notebook'``), or a new one of your own choosing.
  179. The ``args`` are a JSON object that will be passed into your command's functions at render/execute time.
  180. You can use these to customize the behavior of your command depending on how it is invoked.
  181. For instance, you can pass in ``args: { isPalette: true }``.
  182. Your command ``label`` function can then check the ``args`` it is provided for ``isPalette``,
  183. and return a different label in that case.
  184. This can be useful to make a single command flexible enough to work in multiple contexts.
  185. .. _context_menu:
  186. Context Menu
  187. ------------
  188. JupyterLab has an application-wide context menu available as
  189. ``app.contextMenu``. The application context menu is shown when the user right-clicks,
  190. and is populated with menu items that are most relevant to the thing that the user clicked.
  191. The context menu system determines which items to show based on
  192. `CSS selectors <https://developer.mozilla.org/en-US/docs/Learn/CSS/Introduction_to_CSS/Selectors>`__.
  193. It propagates up the DOM tree and tests whether a given HTML element
  194. matches the CSS selector provided by a given command.
  195. Items can be added in the context menu in two ways:
  196. 1. Using the settings - this is the preferred way as they are configurable by the user.
  197. 2. Using the API - this is for advanced cases like dynamic menu or semantic items.
  198. Here is an example showing how to add a command to the application context
  199. menu using the settings.
  200. .. code:: json
  201. {
  202. "jupyter.lab.menus": {
  203. "context": [
  204. {
  205. "command": "my-command",
  206. "selector": ".jp-Notebook",
  207. "rank": 500
  208. }
  209. ]
  210. }
  211. In this example, the command with id ``my-command`` is shown whenever the user
  212. right-clicks on a DOM element matching ``.jp-Notebook`` (that is to say, a notebook).
  213. The selector can be any valid CSS selector, and may target your own UI elements, or existing ones.
  214. A list of CSS selectors currently used by context menu commands is given in :ref:`css-selectors`.
  215. Item must follow this definition:
  216. .. literalinclude:: ../snippets/packages/settingregistry/src/plugin-schema.json
  217. :language: json
  218. :lines: 37-55
  219. where ``menuItem`` definition is:
  220. .. literalinclude:: ../snippets/packages/settingregistry/src/plugin-schema.json
  221. :language: json
  222. :lines: 158-196
  223. The same example using the API is shown below. See the Lumino `docs
  224. <https://jupyterlab.github.io/lumino/widgets/interfaces/contextmenu.iitemoptions.html>`__
  225. for the item creation options.
  226. .. code:: typescript
  227. app.contextMenu.addItem({
  228. command: commandID,
  229. selector: '.jp-Notebook'
  230. })
  231. If you don't want JupyterLab's custom context menu to appear for your element, because you have
  232. your own right click behavior that you want to trigger, you can add the `data-jp-suppress-context-menu` data attribute
  233. to any node to have it and its children not trigger it.
  234. For example, if you are building a custom React element, it would look like this:
  235. .. code::
  236. function MyElement(props: {}) {
  237. return (
  238. <div data-jp-suppress-context-menu>
  239. <p>Hi</p>
  240. <p onContextMenu={() => {console.log("right clicked")}}>There</p>
  241. </div>
  242. )
  243. }
  244. Alternatively, you can use a 'contextmenu' event listener and
  245. call ``event.stopPropagation`` to prevent the application context menu
  246. handler from being called (it is listening in the bubble phase on the
  247. ``document``). At this point you could show your own Lumino
  248. `contextMenu <https://jupyterlab.github.io/lumino/widgets/classes/contextmenu.html>`__,
  249. or simply stop propagation and let the system context menu be shown.
  250. This would look something like the following in a ``Widget`` subclass:
  251. .. code:: javascript
  252. // In `onAfterAttach()`
  253. this.node.addEventListener('contextmenu', this);
  254. // In `handleEvent()`
  255. case 'contextmenu':
  256. event.stopPropagation();
  257. .. _copy_shareable_link:
  258. Copy Shareable Link
  259. -------------------
  260. The file browser provides a context menu item "Copy Shareable Link". The
  261. desired behavior will vary by deployment and the users it serves. The file
  262. browser supports overriding the behavior of this item.
  263. .. code:: typescript
  264. import {
  265. IFileBrowserFactory
  266. } from '@jupyterlab/filebrowser';
  267. import {
  268. JupyterFrontEnd, JupyterFrontEndPlugin
  269. } from '@jupyterlab/application';
  270. const shareFile: JupyterFrontEndPlugin<void> = {
  271. activate: activateShareFile,
  272. id: commandID,
  273. requires: [IFileBrowserFactory],
  274. autoStart: true
  275. };
  276. function activateShareFile(
  277. app: JupyterFrontEnd,
  278. factory: IFileBrowserFactory
  279. ): void {
  280. const { commands } = app;
  281. const { tracker } = factory;
  282. commands.addCommand('filebrowser:share-main', {
  283. execute: () => {
  284. const widget = tracker.currentWidget;
  285. if (!widget) {
  286. return;
  287. }
  288. const path = encodeURI(widget.selectedItems().next().path);
  289. // Do something with path.
  290. },
  291. isVisible: () =>
  292. tracker.currentWidget &&
  293. toArray(tracker.currentWidget.selectedItems()).length === 1,
  294. iconClass: 'jp-MaterialIcon jp-LinkIcon',
  295. label: 'Copy Shareable Link'
  296. });
  297. }
  298. Note that an extension providing a replacement plugin like this must either :ref:`automatically disable <disabledExtensions>` the replaced core plugin or the user must disable the core plugin manually:
  299. .. code-block:: bash
  300. jupyter labextension disable @jupyterlab/filebrowser-extension:share-file
  301. Icons
  302. -----
  303. See :ref:`ui_components`
  304. Keyboard Shortcuts
  305. ------------------
  306. There are two ways of adding keyboard shortcuts in JupyterLab.
  307. If you don't want the shortcuts to be user-configurable,
  308. you can add them directly to the application command registry:
  309. .. code:: typescript
  310. app.commands.addKeyBinding({
  311. command: commandID,
  312. args: {},
  313. keys: ['Accel T'],
  314. selector: '.jp-Notebook'
  315. });
  316. In this example ``my-command`` command is mapped to ``Accel T``,
  317. where ``Accel`` corresponds to ``Cmd`` on a Mac and ``Ctrl`` on Windows and Linux computers.
  318. The behavior for keyboard shortcuts is very similar to that of the context menu:
  319. the shortcut handler propagates up the DOM tree from the focused element
  320. and tests each element against the registered selectors. If a match is found,
  321. then that command is executed with the provided ``args``.
  322. Full documentation for the options for ``addKeyBinding`` can be found
  323. `here <https://jupyterlab.github.io/lumino/commands/interfaces/commandregistry.ikeybindingoptions.html>`__.
  324. JupyterLab also provides integration with its settings system for keyboard shortcuts.
  325. Your extension can provide a settings schema with a ``jupyter.lab.shortcuts`` key,
  326. declaring default keyboard shortcuts for a command:
  327. .. code:: json
  328. {
  329. "jupyter.lab.shortcuts": [
  330. {
  331. "command": "my-command",
  332. "keys": ["Accel T"],
  333. "selector": ".jp-mod-searchable"
  334. }
  335. ]
  336. }
  337. Shortcuts added to the settings system will be editable by users.
  338. Launcher
  339. --------
  340. As with menus, keyboard shortcuts, and the command palette, new items can be added
  341. to the application launcher via commands.
  342. You can do this by requesting the ``ILauncher`` token in your extension:
  343. .. code:: typescript
  344. launcher.add({
  345. command: commandID,
  346. category: 'Other',
  347. rank: 0
  348. });
  349. In addition to providing a command ID, you also provide a category in which to put your item,
  350. (e.g. 'Notebook', or 'Other'), as well as a rank to determine its position among other items.
  351. .. _shell:
  352. Jupyter Front-End Shell
  353. -----------------------
  354. The Jupyter front-end
  355. `shell <../api/interfaces/application.jupyterfrontend.ishell.html>`__
  356. is used to add and interact with content in the application. The ``IShell``
  357. interface provides an ``add()`` method for adding widgets to the application.
  358. In JupyterLab, the application shell consists of:
  359. - A ``top`` area for things like top-level toolbars and information.
  360. - A ``menu`` area for top-level menus, which is collapsed into the ``top`` area in multiple-document mode and put below it in single-document mode.
  361. - ``left`` and ``right`` sidebar areas for collapsible content.
  362. - A ``main`` work area for user activity.
  363. - A ``down`` area for information content; like log console, contextual help.
  364. - A ``bottom`` area for things like status bars.
  365. - A ``header`` area for custom elements.
  366. Left/Right Areas
  367. ^^^^^^^^^^^^^^^^
  368. The left and right sidebar areas of JupyterLab are intended to host more persistent user interface
  369. elements than the main area. That being said, extension authors are free to add whatever
  370. components they like to these areas. The outermost-level of the object that you add is expected
  371. to be a Lumino ``Widget``, but that can host any content you like (such as React components).
  372. As an example, the following code executes an application command to a terminal widget
  373. and then adds the terminal to the right area:
  374. .. code:: typescript
  375. app.commands
  376. .execute('terminal:create-new')
  377. .then((terminal: WidgetModuleType.Terminal) => {
  378. app.shell.add(terminal, 'right');
  379. });
  380. You can use a numeric rank to control the ordering of the left and right tabs:
  381. .. code:: typescript
  382. app.shell.add(terminal, 'left', {rank: 600});
  383. The recommended ranges for this rank are:
  384. * 0-500: reserved for first-party JupyterLab extensions.
  385. * 501-899: reserved for third-party extensions.
  386. * 900: The default rank if none is specified.
  387. * 1000: The JupyterLab extension manager.
  388. .. _mainmenu:
  389. Main Menu
  390. ---------
  391. There are two ways to extend JupyterLab's main menu.
  392. 1. Using the settings - this is the preferred way as they are configurable by the user.
  393. 2. Using the API - this is for advanced cases like dynamic menu or semantic items.
  394. Settings-defined menu
  395. ^^^^^^^^^^^^^^^^^^^^^
  396. JupyterLab provides integration with its settings system for menu definitions.
  397. Your extension can provide a settings schema with a ``jupyter.lab.menus`` key,
  398. declaring default menus. You don't need to set anything in the TypeScript code
  399. (except the command definitions).
  400. To add a new menu with your extension command:
  401. .. code:: json
  402. {
  403. "jupyter.lab.menus": {
  404. "main": [
  405. {
  406. "id": "jp-mainmenu-myextension",
  407. "label": "My Menu",
  408. "items": [
  409. {
  410. "command": "my-command",
  411. "rank": 500
  412. }
  413. ],
  414. "rank": 100
  415. }
  416. ]
  417. }
  418. The menu item label will be set with the command label. For menus (and
  419. submenus), the label needs to be set explicitly with the ``label``
  420. property.
  421. Menu and item have a ``rank`` that will determine the elements order.
  422. To add a new entry in an existing menu:
  423. .. code:: json
  424. {
  425. "jupyter.lab.menus": {
  426. "main": [
  427. {
  428. "id": "jp-mainmenu-file",
  429. "items": [
  430. {
  431. "command": "my-command",
  432. "rank": 500
  433. }
  434. ]
  435. }
  436. ]
  437. }
  438. Here is the list of default menu ids:
  439. - File menu: ``jp-mainmenu-file``
  440. * New file submenu: ``jp-mainmenu-file-new``
  441. - Edit menu: ``jp-mainmenu-edit``
  442. - View menu: ``jp-mainmenu-view``
  443. - Run menu: ``jp-mainmenu-run``
  444. - Kernel menu: ``jp-mainmenu-kernel``
  445. - Tabs menu: ``jp-mainmenu-tabs``
  446. - Settings menu: ``jp-mainmenu-settings``
  447. - Help menu: ``jp-mainmenu-help``
  448. The default main menu is defined in the ``mainmenu-extension`` package settings.
  449. A menu must respect the following schema:
  450. .. literalinclude:: ../snippets/packages/settingregistry/src/plugin-schema.json
  451. :language: json
  452. :lines: 101-157
  453. And an item must follow:
  454. .. literalinclude:: ../snippets/packages/settingregistry/src/plugin-schema.json
  455. :language: json
  456. :lines: 158-196
  457. Menus added to the settings system will be editable by users using the ``mainmenu-extension``
  458. settings. In particular, they can be disabled at the item or the menu level by setting the
  459. property ``disabled`` to ``true``.
  460. API-defined menu
  461. ^^^^^^^^^^^^^^^^
  462. To use the API, you should request the ``IMainMenu`` token for your extension.
  463. There are three main ways to extend:
  464. 1. You can add your own menu to the menu bar.
  465. 2. You can add new commands to the existing menus.
  466. 3. You can register your extension with one of the existing semantic menu items.
  467. Adding a New Menu
  468. ~~~~~~~~~~~~~~~~~
  469. To add a new menu to the menu bar, you need to create a new
  470. `Lumino menu <https://jupyterlab.github.io/lumino/widgets/classes/menu.html>`__.
  471. You can then add commands to the menu in a similar way to the command palette,
  472. and add that menu to the main menu bar:
  473. .. code:: typescript
  474. const menu = new Menu({ commands: app.commands });
  475. menu.addItem({
  476. command: commandID,
  477. args: {},
  478. });
  479. mainMenu.addMenu(menu, { rank: 40 });
  480. As with the command palette, you can optionally pass in ``args`` to customize the
  481. rendering and execution behavior of the command in the menu context.
  482. Adding a New Command to an Existing Menu
  483. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  484. In many cases you will want to add your commands to the existing JupyterLab menus
  485. rather than creating a separate menu for your extension.
  486. Because the top-level JupyterLab menus are shared among many extensions,
  487. the API for adding items is slightly different.
  488. In this case, you provide a list of commands and a rank,
  489. and these commands will be displayed together in a separate group within an existing menu.
  490. For instance, to add a command group with ``firstCommandID`` and ``secondCommandID``
  491. to the File menu, you would do the following:
  492. .. code:: typescript
  493. mainMenu.fileMenu.addGroup([
  494. {
  495. command: firstCommandID,
  496. },
  497. {
  498. command: secondCommandID,
  499. }
  500. ], 40 /* rank */);
  501. Registering a Semantic Menu Item
  502. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  503. There are some commands in the JupyterLab menu system that are considered
  504. common and important enough that they are treated differently.
  505. For instance, we anticipate that many activities may want to provide a command
  506. to close themselves and perform some cleanup operation (like closing a console and shutting down its kernel).
  507. Rather than having a proliferation of similar menu items for this common operation
  508. of "closing-and-cleanup", we provide a single command that can adapt itself to this use case,
  509. which we term a "semantic menu item".
  510. For this example, it is the File Menu ``closeAndCleaners`` set.
  511. Here is an example of using the ``closeAndCleaners`` semantic menu item:
  512. .. code:: typescript
  513. mainMenu.fileMenu.closeAndCleaners.add({
  514. tracker,
  515. action: 'Shutdown',
  516. name: 'My Activity',
  517. closeAndCleanup: current => {
  518. current.close();
  519. return current.shutdown();
  520. }
  521. });
  522. In this example, ``tracker`` is a :ref:`widget-tracker`, which allows the menu
  523. item to determine whether to delegate the menu command to your activity,
  524. ``name`` is a name given to your activity in the menu label,
  525. ``action`` is a verb given to the cleanup operation in the menu label,
  526. and ``closeAndCleanup`` is the actual function that performs the cleanup operation.
  527. So if the current application activity is held in the ``tracker``,
  528. then the menu item will show ``Shutdown My Activity``, and delegate to the
  529. ``closeAndCleanup`` function that was provided.
  530. More examples for how to register semantic menu items are found throughout the JupyterLab code base.
  531. The available semantic menu items are:
  532. - ``IEditMenu.IUndoer``: an activity that knows how to undo and redo.
  533. - ``IEditMenu.IClearer``: an activity that knows how to clear its content.
  534. - ``IEditMenu.IGoToLiner``: an activity that knows how to jump to a given line.
  535. - ``IFileMenu.ICloseAndCleaner``: an activity that knows how to close and clean up after itself.
  536. - ``IFileMenu.IConsoleCreator``: an activity that knows how to create an attached code console for itself.
  537. - ``IHelpMenu.IKernelUser``: an activity that knows how to get a related kernel session.
  538. - ``IKernelMenu.IKernelUser``: an activity that can perform various kernel-related operations.
  539. - ``IRunMenu.ICodeRunner``: an activity that can run code from its content.
  540. - ``IViewMenu.IEditorViewer``: an activity that knows how to set various view-related options on a text editor that it owns.
  541. Status Bar
  542. ----------
  543. JupyterLab's status bar is intended to show small pieces of contextual information.
  544. Like the left and right areas, it only expects a Lumino ``Widget``,
  545. which might contain any kind of content. Since the status bar has limited space,
  546. you should endeavor to only add small widgets to it.
  547. The following example shows how to place a status item that displays the current
  548. "busy" status for the application. This information is available from the ``ILabStatus``
  549. token, which we reference by a variable named ``labStatus``.
  550. We place the ``statusWidget`` in the middle of the status bar.
  551. When the ``labStatus`` busy state changes, we update the text content of the
  552. ``statusWidget`` to reflect that.
  553. .. code:: typescript
  554. const statusWidget = new Widget();
  555. labStatus.busySignal.connect(() => {
  556. statusWidget.node.textContent = labStatus.isBusy ? 'Busy' : 'Idle';
  557. });
  558. statusBar.registerStatusItem('lab-status', {
  559. align: 'middle',
  560. item: statusWidget
  561. });
  562. .. _toolbar-registry:
  563. Toolbar Registry
  564. ----------------
  565. JupyterLab provides an infrastructure to define and customize toolbar widgets
  566. from the settings, which is similar to that defining the context menu and the main menu
  567. bar.
  568. Document Widgets
  569. ^^^^^^^^^^^^^^^^
  570. A typical example is the notebook toolbar as in the snippet below:
  571. .. code:: typescript
  572. function activatePlugin(
  573. app: JupyterFrontEnd,
  574. // ...
  575. toolbarRegistry: IToolbarWidgetRegistry | null,
  576. settingRegistry: ISettingRegistry | null
  577. ): NotebookWidgetFactory.IFactory {
  578. const { commands } = app;
  579. let toolbarFactory:
  580. | ((widget: NotebookPanel) => DocumentRegistry.IToolbarItem[])
  581. | undefined;
  582. // Register notebook toolbar specific widgets
  583. if (toolbarRegistry) {
  584. toolbarRegistry.registerFactory<NotebookPanel>(FACTORY, 'cellType', panel =>
  585. ToolbarItems.createCellTypeItem(panel, translator)
  586. );
  587. toolbarRegistry.registerFactory<NotebookPanel>(
  588. FACTORY,
  589. 'kernelStatus',
  590. panel => Toolbar.createKernelStatusItem(panel.sessionContext, translator)
  591. );
  592. // etc...
  593. if (settingRegistry) {
  594. // Create the factory
  595. toolbarFactory = createToolbarFactory(
  596. toolbarRegistry,
  597. settingRegistry,
  598. // Factory name
  599. FACTORY,
  600. // Setting id in which the toolbar items are defined
  601. '@jupyterlab/notebook-extension:panel',
  602. translator
  603. );
  604. }
  605. }
  606. const factory = new NotebookWidgetFactory({
  607. name: FACTORY,
  608. fileTypes: ['notebook'],
  609. modelName: 'notebook',
  610. defaultFor: ['notebook'],
  611. // ...
  612. toolbarFactory,
  613. translator: translator
  614. });
  615. app.docRegistry.addWidgetFactory(factory);
  616. The registry ``registerFactory`` method allows an extension to provide special widget for a unique pair
  617. (factory name, toolbar item name). Then the helper ``createToolbarFactory`` can be used to extract the
  618. toolbar definition from the settings and build the factory to pass to the widget factory.
  619. The default toolbar items can be defined across multiple extensions by providing an entry in the ``"jupyter.lab.toolbars"``
  620. mapping. For example for the notebook panel:
  621. .. code:: js
  622. "jupyter.lab.toolbars": {
  623. "Notebook": [ // Factory name
  624. // Item with non-default widget - it must be registered within an extension
  625. {
  626. "name": "save", // Unique toolbar item name
  627. "rank": 10 // Item rank
  628. },
  629. // Item with default button widget triggering a command
  630. { "name": "insert", "command": "notebook:insert-cell-below", "rank": 20 },
  631. { "name": "cut", "command": "notebook:cut-cell", "rank": 21 },
  632. { "name": "copy", "command": "notebook:copy-cell", "rank": 22 },
  633. { "name": "paste", "command": "notebook:paste-cell-below", "rank": 23 },
  634. { "name": "run", "command": "runmenu:run", "rank": 30 },
  635. { "name": "interrupt", "command": "kernelmenu:interrupt", "rank": 31 },
  636. { "name": "restart", "command": "kernelmenu:restart", "rank": 32 },
  637. {
  638. "name": "restart-and-run",
  639. "command": "runmenu:restart-and-run-all",
  640. "rank": 33 // The default rank is 50
  641. },
  642. { "name": "cellType", "rank": 40 },
  643. // Horizontal spacer widget
  644. { "name": "spacer", "type": "spacer", "rank": 100 },
  645. { "name": "kernelName", "rank": 1000 },
  646. { "name": "kernelStatus", "rank": 1001 }
  647. ]
  648. },
  649. "jupyter.lab.transform": true,
  650. "properties": {
  651. "toolbar": {
  652. "title": "Notebook panel toolbar items",
  653. "items": {
  654. "$ref": "#/definitions/toolbarItem"
  655. },
  656. "type": "array",
  657. "default": []
  658. }
  659. }
  660. The settings registry will merge those definitions from settings schema with any
  661. user-provided overrides (customizations) transparently and save them under the
  662. ``toolbar`` property in the final settings object. The ``toolbar`` list will be used to
  663. create the toolbar. Both the source settings schema and the final settings object
  664. are identified by the plugin ID passed to ``createToolbarFactory``. The user can
  665. customize the toolbar by adding new items or overriding existing ones (like
  666. providing a different rank or adding ``"disabled": true`` to remove the item).
  667. .. note::
  668. You need to set ``jupyter.lab.transform`` to ``true`` in the plugin id that will gather all items.
  669. The current widget factories supporting the toolbar customization are:
  670. - ``Notebook``: Notebook panel toolbar
  671. - ``Cell``: Cell toolbar
  672. - ``Editor``: Text editor toolbar
  673. - ``HTML Viewer``: HTML Viewer toolbar
  674. - ``CSVTable``: CSV (Comma Separated Value) Viewer toolbar
  675. - ``TSVTable``: TSV (Tabulation Separated Value) Viewer toolbar
  676. Add the toolbar item must follow this definition:
  677. .. literalinclude:: ../snippets/packages/settingregistry/src/plugin-schema.json
  678. :language: json
  679. :lines: 207-252
  680. Generic Widget with Toolbar
  681. ^^^^^^^^^^^^^^^^^^^^^^^^^^^
  682. The logic detailed in the previous section can be used to customize any widgets with a toolbar.
  683. The additional keys used in ``jupyter.lab.toolbars`` settings attributes are:
  684. - ``FileBrowser``: Default file browser panel toolbar items
  685. Here is an example for enabling that definition on a widget:
  686. .. code:: typescript
  687. function activatePlugin(
  688. app: JupyterFrontEnd,
  689. // ...
  690. toolbarRegistry: IToolbarWidgetRegistry,
  691. settingRegistry: ISettingRegistry
  692. ): void {
  693. const browser = new FileBrowser();
  694. // Toolbar
  695. // - Define a custom toolbar item
  696. toolbarRegistry.registerFactory(
  697. 'FileBrowser', // Factory name
  698. 'uploader',
  699. (browser: FileBrowser) =>
  700. new Uploader({ model: browser.model, translator })
  701. );
  702. // - Link the widget toolbar and its definition from the settings
  703. setToolbar(
  704. browser,
  705. createToolbarFactory(
  706. toolbarRegistry,
  707. settings,
  708. 'FileBrowser', // Factory name
  709. plugin.id,
  710. translator
  711. )
  712. );
  713. .. _widget-tracker:
  714. Widget Tracker
  715. --------------
  716. Often extensions will want to interact with documents and activities created by other extensions.
  717. For instance, an extension may want to inject some text into a notebook cell,
  718. or set a custom keymap, or close all documents of a certain type.
  719. Actions like these are typically done by widget trackers.
  720. Extensions keep track of instances of their activities in ``WidgetTrackers``,
  721. which are then provided as tokens so that other extensions may request them.
  722. For instance, if you want to interact with notebooks, you should request the ``INotebookTracker`` token.
  723. You can then use this tracker to iterate over, filter, and search all open notebooks.
  724. You can also use it to be notified via signals when notebooks are added and removed from the tracker.
  725. Widget tracker tokens are provided for many activities in JupyterLab, including
  726. notebooks, consoles, text files, mime documents, and terminals.
  727. If you are adding your own activities to JupyterLab, you might consider providing
  728. a ``WidgetTracker`` token of your own, so that other extensions can make use of it.
  729. State Database
  730. --------------
  731. The state database can be accessed by importing ``IStateDB`` from
  732. ``@jupyterlab/statedb`` and adding it to the list of ``requires`` for
  733. a plugin:
  734. .. code:: typescript
  735. const id = 'foo-extension:IFoo';
  736. const IFoo = new Token<IFoo>(id);
  737. interface IFoo {}
  738. class Foo implements IFoo {}
  739. const plugin: JupyterFrontEndPlugin<IFoo> = {
  740. id,
  741. autoStart: true,
  742. requires: [IStateDB],
  743. provides: IFoo,
  744. activate: (app: JupyterFrontEnd, state: IStateDB): IFoo => {
  745. const foo = new Foo();
  746. const key = `${id}:some-attribute`;
  747. // Load the saved plugin state and apply it once the app
  748. // has finished restoring its former layout.
  749. Promise.all([state.fetch(key), app.restored])
  750. .then(([saved]) => { /* Update `foo` with `saved`. */ });
  751. // Fulfill the plugin contract by returning an `IFoo`.
  752. return foo;
  753. }
  754. };