extension_points.rst 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534
  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 public APIs that can be requested in extensions via tokens.
  6. A list of tokens that extension authors can request is documented in :ref:`tokens`.
  7. This is intended to be a guide for 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 <http://jupyterlab.github.io/jupyterlab/index.html>`__ and
  11. `Lumino <http://jupyterlab.github.io/lumino/index.html>`__ API documentation.
  12. .. contents:: Table of contents
  13. :local:
  14. :depth: 1
  15. Commands
  16. ~~~~~~~~
  17. Add a Command to the Command Registry
  18. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  19. Perhaps the most common way to add functionality to JupyterLab is via commands.
  20. These are lightweight objects that include a function to execute combined with
  21. additional metadata, including how they are labeled and when they are to be enabled.
  22. The application has a single command registry, keyed by string command IDs,
  23. to which you can add your custom commands.
  24. The commands added to the command registry can then be used to populate
  25. several of the JupyterLab user interface elements, including menus and the launcher.
  26. Here is a sample block of code that adds a command to the application (given by ``app``):
  27. .. code:: typescript
  28. const commandID = 'my-command';
  29. const toggled = false;
  30. app.commands.addCommand(commandID, {
  31. label: 'My Cool Command',
  32. isEnabled: true,
  33. isVisible: true,
  34. isToggled: () => toggled,
  35. iconClass: 'some-css-icon-class',
  36. execute: () => {
  37. console.log(`Executed ${commandID}`);
  38. toggled = !toggled;
  39. });
  40. This example adds a new command, which, when triggered, calls the ``execute`` function.
  41. ``isEnabled`` indicates whether the command is enabled, and determines whether renderings of it are greyed out.
  42. ``isToggled`` indicates whether to render a check mark next to the command.
  43. ``isVisible`` indicates whether to render the command at all.
  44. ``iconClass`` specifies a CSS class which can be used to display an icon next to renderings of the command.
  45. Each of ``isEnabled``, ``isToggled``, and ``isVisible`` can be either
  46. a boolean value or a function that returns a boolean value, in case you want
  47. to do some logic in order to determine those conditions.
  48. Likewise, each of ``label`` and ``iconClass`` can be either
  49. a string value or a function that returns a string value.
  50. There are several more options which can be passed into the command registry when
  51. adding new commands. These are documented
  52. `here <http://jupyterlab.github.io/lumino/commands/interfaces/commandregistry.icommandoptions.html>`__.
  53. After a command has been added to the application command registry
  54. you can add them to various places in the application user interface,
  55. where they will be rendered using the metadata you provided.
  56. Add a Command to the Command Palette
  57. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  58. In order to add an existing, registered command to the command palette, you need to request the
  59. ``ICommandPalette`` token in your extension.
  60. Here is an example showing how to add a command to the command palette (given by ``palette``):
  61. .. code:: typescript
  62. palette.addItem({
  63. command: commandID,
  64. category: 'my-category'
  65. args: {}
  66. });
  67. The command ID is the same ID that you used when registering the command.
  68. You must also provide a ``category``, which determines the subheading of
  69. the command palette in which to render the command.
  70. It can be a preexisting category (e.g., ``'notebook'``), or a new one of your own choosing.
  71. The ``args`` are a JSON object that will be passed into your command's functions at render/execute time.
  72. You can use these to customize the behavior of your command depending on how it is invoked.
  73. For instance, you can pass in ``args: { isPalette: true }``.
  74. Your command ``label`` function can then check the ``args`` it is provided for ``isPalette``,
  75. and return a different label in that case.
  76. This can be useful to make a single command flexible enough to work in multiple contexts.
  77. Context Menu
  78. ~~~~~~~~~~~~
  79. The application context menu is shown when the user right-clicks,
  80. and is populated with menu items that are most relevant to the thing that the user clicked.
  81. The context menu system determines which items to show based on
  82. `CSS selectors <https://developer.mozilla.org/en-US/docs/Learn/CSS/Introduction_to_CSS/Selectors>`__.
  83. It propagates up the DOM tree and tests whether a given HTML element
  84. matches the CSS selector provided by a given command.
  85. Here is an example showing how to add a command to the application context menu:
  86. .. code:: typescript
  87. app.contextMenu.addItem({
  88. command: commandID,
  89. selector: '.jp-Notebook'
  90. })
  91. In this example, the command indicated by ``commandID`` is shown whenever the user
  92. right-clicks on a DOM element matching ``.jp-Notebook`` (that is to say, a notebook).
  93. The selector can be any valid CSS selector, and may target your own UI elements, or existing ones.
  94. A list of CSS selectors currently used by context menu commands is given in :ref:`css-selectors`.
  95. If you don't want JupyterLab's custom context menu to appear for your element, because you have
  96. your own right click behavior that you want to trigger, you can add the `data-jp-suppress-context-menu` data attribute
  97. to any node to have it and its children not trigger it.
  98. For example, if you are building a custom React element, it would look like this:
  99. .. code::
  100. function MyElement(props: {}) {
  101. return (
  102. <div data-jp-suppress-context-menu>
  103. <p>Hi</p>
  104. <p onContextMenu={() => {console.log("right clicked")}}>There</p>
  105. </div>
  106. )
  107. }
  108. .. _copy_shareable_link:
  109. Copy Shareable Link
  110. ~~~~~~~~~~~~~~~~~~~
  111. The file browser provides a context menu item "Copy Shareable Link". The
  112. desired behavior will vary by deployment and the users it serves. The file
  113. browser supports overriding the behavior of this item.
  114. .. code:: typescript
  115. import {
  116. IFileBrowserFactory
  117. } from '@jupyterlab/filebrowser';
  118. import {
  119. JupyterFrontEnd, JupyterFrontEndPlugin
  120. } from '@jupyterlab/application';
  121. const shareFile: JupyterFrontEndPlugin<void> = {
  122. activate: activateShareFile,
  123. id: commandID,
  124. requires: [IFileBrowserFactory],
  125. autoStart: true
  126. };
  127. function activateShareFile(
  128. app: JupyterFrontEnd,
  129. factory: IFileBrowserFactory
  130. ): void {
  131. const { commands } = app;
  132. const { tracker } = factory;
  133. commands.addCommand('filebrowser:share-main', {
  134. execute: () => {
  135. const widget = tracker.currentWidget;
  136. if (!widget) {
  137. return;
  138. }
  139. const path = encodeURI(widget.selectedItems().next().path);
  140. // Do something with path.
  141. },
  142. isVisible: () =>
  143. tracker.currentWidget &&
  144. toArray(tracker.currentWidget.selectedItems()).length === 1,
  145. iconClass: 'jp-MaterialIcon jp-LinkIcon',
  146. label: 'Copy Shareable Link'
  147. });
  148. }
  149. Note that before enabling this plugin in the usual way, you must *disable* the
  150. default plugin provided by the built-in file browser.
  151. .. code:: bash
  152. jupyter labextension disable @jupyterlab/filebrowser-extension:share-file
  153. Icons
  154. ~~~~~
  155. ``LabIcon`` is the icon class used by JupyterLab, and is part of the new icon
  156. system introduced in JupyterLab v2.0.
  157. How JupyterLab handles icons
  158. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  159. The ui-components package provides icons to the rest of JupyterLab, in the
  160. form of a set of ``LabIcon`` instances (currently about 80). All of the icons
  161. in the core JupyterLab packages are rendered using one of these ``LabIcon``
  162. instances.
  163. Using the icons in your own code
  164. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  165. You can use any of JupyterLab icons in your own code via an ``import``
  166. statement. For example, to use ``jupyterIcon`` you would first do:
  167. .. code:: typescript
  168. import { jupyterIcon } from "@jupyterlab/ui-components";
  169. How to render an icon into a DOM node
  170. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  171. Icons can be added as children to any ``div`` or ``span`` nodes using the
  172. `icon.element(...)` method (where ``icon`` is any instance of ``LabIcon``).
  173. For example, to render the Jupyter icon you could do:
  174. .. code:: typescript
  175. jupyterIcon.element({
  176. container: elem,
  177. height: '16px',
  178. width: '16px',
  179. marginLeft: '2px'
  180. });
  181. where ``elem`` is any ``HTMLElement`` with a ``div`` or ``span`` tag. As shown in
  182. the above example, the icon can be styled by passing CSS parameters into
  183. `.element(...)`. Any valid CSS parameter can be used, with one caveat:
  184. snake case params have to be converted to camel case. For example, instead
  185. of `foo-bar: '8px'`, you'd need to use `fooBar: '8px'`.
  186. How to render an icon as a React component
  187. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  188. Icons can also be rendered using React. The `icon.react` parameter holds a
  189. standard React component that will display the icon on render. Like any React
  190. component, `icon.react` can be used in various ways.
  191. For example, here is how you would add the Jupyter icon to the render tree of
  192. another React component:
  193. .. code:: jsx
  194. public render() {
  195. return (
  196. <div className="outer">
  197. <div className="inner">
  198. <jupyterIcon.react
  199. tag="span"
  200. right="7px"
  201. top="5px"
  202. />
  203. "and here's a text node"
  204. </div>
  205. </div>
  206. );
  207. }
  208. Alternatively, you can just render the icon directly into any existing DOM
  209. node ``elem`` by using the ``ReactDOM`` module:
  210. .. code:: typescript
  211. ReactDOM.render(jupyterIcon.react, elem);
  212. If do you use ``ReactDOM`` to render, and if the ``elem`` node is ever removed
  213. from the DOM, you'll first need to clean it up:
  214. .. code:: typescript
  215. ReactDOM.unmountComponentAtNode(elem);
  216. This cleanup step is not a special property of ``LabIcon``, but is instead
  217. needed for any React component that is rendered directly at the top level
  218. by ``ReactDOM``: failure to call `unmountComponentAtNode` can result in a
  219. `memory leak <https://stackoverflow.com/a/48198011/425458>`__.
  220. Keyboard Shortcuts
  221. ~~~~~~~~~~~~~~~~~~
  222. There are two ways of adding keyboard shortcuts in JupyterLab.
  223. If you don't want the shortcuts to be user-configurable,
  224. you can add them directly to the application command registry:
  225. .. code:: typescript
  226. app.commands.addKeyBinding({
  227. command: commandID,
  228. args: {},
  229. keys: ['Accel T'],
  230. selector: '.jp-Notebook'
  231. });
  232. In this example ``my-command`` command is mapped to ``Accel T``,
  233. where ``Accel`` corresponds to ``Cmd`` on a Mac and ``Ctrl`` on Windows and Linux computers.
  234. The behavior for keyboard shortcuts is very similar to that of the context menu:
  235. the shortcut handler propagates up the DOM tree from the focused element
  236. and tests each element against the registered selectors. If a match is found,
  237. then that command is executed with the provided ``args``.
  238. Full documentation for the options for ``addKeyBinding`` can be found
  239. `here <http://jupyterlab.github.io/lumino/commands/interfaces/commandregistry.ikeybindingoptions.html>`__.
  240. JupyterLab also provides integration with its settings system for keyboard shortcuts.
  241. Your extension can provide a settings schema with a ``jupyter.lab.shortcuts`` key,
  242. declaring default keyboard shortcuts for a command:
  243. .. code:: json
  244. {
  245. "jupyter.lab.shortcuts": [
  246. {
  247. "command": "my-command",
  248. "keys": ["Accel T"],
  249. "selector": ".jp-mod-searchable"
  250. }
  251. ]
  252. }
  253. Shortcuts added to the settings system will be editable by users.
  254. Launcher
  255. ~~~~~~~~
  256. As with menus, keyboard shortcuts, and the command palette, new items can be added
  257. to the application launcher via commands.
  258. You can do this by requesting the ``ILauncher`` token in your extension:
  259. .. code:: typescript
  260. launcher.add({
  261. command: commandID,
  262. category: 'Other',
  263. rank: 0
  264. });
  265. In addition to providing a command ID, you also provide a category in which to put your item,
  266. (e.g. 'Notebook', or 'Other'), as well as a rank to determine its position among other items.
  267. Left/Right Areas
  268. ~~~~~~~~~~~~~~~~
  269. The left and right areas of JupyterLab are intended to host more persistent user interface
  270. elements than the main area. That being said, extension authors are free to add whatever
  271. components they like to these areas. The outermost-level of the object that you add is expected
  272. to be a Lumino ``Widget``, but that can host any content you like (such as React components).
  273. As an example, the following code executes an application command to a terminal widget
  274. and then adds the terminal to the right area:
  275. .. code:: typescript
  276. app.commands
  277. .execute('terminal:create-new')
  278. .then((terminal: WidgetModuleType.Terminal) => {
  279. app.shell.add(terminal, 'right');
  280. });
  281. Main Menu
  282. ~~~~~~~~~
  283. There are three main ways to extend JupyterLab's main menu.
  284. 1. You can add your own menu to the menu bar.
  285. 2. You can add new commands to the existing menus.
  286. 3. You can register your extension with one of the existing semantic menu items.
  287. In all three cases, you should request the ``IMainMenu`` token for your extension.
  288. Adding a New Menu
  289. ^^^^^^^^^^^^^^^^^
  290. To add a new menu to the menu bar, you need to create a new
  291. `Lumino menu <https://jupyterlab.github.io/lumino/widgets/classes/menu.html>`__.
  292. You can then add commands to the menu in a similar way to the command palette,
  293. and add that menu to the main menu bar:
  294. .. code:: typescript
  295. const menu = new Menu({ commands: app.commands });
  296. menu.addItem({
  297. command: commandID,
  298. args: {},
  299. });
  300. mainMenu.addMenu(menu, { rank: 40 });
  301. As with the command palette, you can optionally pass in ``args`` to customize the
  302. rendering and execution behavior of the command in the menu context.
  303. Adding a New Command to an Existing Menu
  304. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  305. In many cases you will want to add your commands to the existing JupyterLab menus
  306. rather than creating a separate menu for your extension.
  307. Because the top-level JupyterLab menus are shared among many extensions,
  308. the API for adding items is slightly different.
  309. In this case, you provide a list of commands and a rank,
  310. and these commands will be displayed together in a separate group within an existing menu.
  311. For instance, to add a command group with ``firstCommandID`` and ``secondCommandID``
  312. to the File menu, you would do the following:
  313. .. code:: typescript
  314. mainMenu.fileMenu.addGroup([
  315. {
  316. command: firstCommandID,
  317. },
  318. {
  319. command: secondCommandID,
  320. }
  321. ], 40 /* rank */);
  322. Registering a Semantic Menu Item
  323. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  324. There are some commands in the JupyterLab menu system that are considered
  325. common and important enough that they are treated differently.
  326. For instance, we anticipate that many activities may want to provide a command
  327. to close themselves and perform some cleanup operation (like closing a console and shutting down its kernel).
  328. Rather than having a proliferation of similar menu items for this common operation
  329. of "closing-and-cleanup", we provide a single command that can adapt itself to this use case,
  330. which we term a "semantic menu item".
  331. For this example, it is the File Menu ``closeAndCleaners`` set.
  332. Here is an example of using the ``closeAndCleaners`` semantic menu item:
  333. .. code:: typescript
  334. mainMenu.fileMenu.closeAndCleaners.add({
  335. tracker,
  336. action: 'Shutdown',
  337. name: 'My Activity',
  338. closeAndCleanup: current => {
  339. current.close();
  340. return current.shutdown();
  341. }
  342. });
  343. In this example, ``tracker`` is a :ref:`widget-tracker`, which allows the menu
  344. item to determine whether to delegate the menu command to your activity,
  345. ``name`` is a name given to your activity in the menu label,
  346. ``action`` is a verb given to the cleanup operation in the menu label,
  347. and ``closeAndCleanup`` is the actual function that performs the cleanup operation.
  348. So if the current application activity is held in the ``tracker``,
  349. then the menu item will show ``Shutdown My Activity``, and delegate to the
  350. ``closeAndCleanup`` function that was provided.
  351. More examples for how to register semantic menu items are found throughout the JupyterLab code base.
  352. The available semantic menu items are:
  353. - ``IEditMenu.IUndoer``: an activity that knows how to undo and redo.
  354. - ``IEditMenu.IClearer``: an activity that knows how to clear its content.
  355. - ``IEditMenu.IGoToLiner``: an activity that knows how to jump to a given line.
  356. - ``IFileMenu.ICloseAndCleaner``: an activity that knows how to close and clean up after itself.
  357. - ``IFileMenu.IConsoleCreator``: an activity that knows how to create an attached code console for itself.
  358. - ``IHelpMenu.IKernelUser``: an activity that knows how to get a related kernel session.
  359. - ``IKernelMenu.IKernelUser``: an activity that can perform various kernel-related operations.
  360. - ``IRunMenu.ICodeRunner``: an activity that can run code from its content.
  361. - ``IViewMenu.IEditorViewer``: an activity that knows how to set various view-related options on a text editor that it owns.
  362. Status Bar
  363. ~~~~~~~~~~
  364. JupyterLab's status bar is intended to show small pieces of contextual information.
  365. Like the left and right areas, it only expects a Lumino ``Widget``,
  366. which might contain any kind of content. Since the status bar has limited space,
  367. you should endeavor to only add small widgets to it.
  368. The following example shows how to place a status item that displays the current
  369. "busy" status for the application. This information is available from the ``ILabStatus``
  370. token, which we reference by a variable named ``labStatus``.
  371. We place the ``statusWidget`` in the middle of the status bar.
  372. When the ``labStatus`` busy state changes, we update the text content of the
  373. ``statusWidget`` to reflect that.
  374. .. code:: typescript
  375. const statusWidget = new Widget();
  376. labStatus.busySignal.connect(() => {
  377. statusWidget.node.textContent = labStatus.isBusy ? 'Busy' : 'Idle';
  378. });
  379. statusBar.registerStatusItem('lab-status', {
  380. align: 'middle',
  381. item: statusWidget
  382. });
  383. .. _widget-tracker:
  384. Widget Tracker
  385. ~~~~~~~~~~~~~~
  386. Often extensions will want to interact with documents and activities created by other extensions.
  387. For instance, an extension may want to inject some text into a notebook cell,
  388. or set a custom keymap, or close all documents of a certain type.
  389. Actions like these are typically done by widget trackers.
  390. Extensions keep track of instances of their activities in ``WidgetTrackers``,
  391. which are then provided as tokens so that other extensions may request them.
  392. For instance, if you want to interact with notebooks, you should request the ``INotebookTracker`` token.
  393. You can then use this tracker to iterate over, filter, and search all open notebooks.
  394. You can also use it to be notified via signals when notebooks are added and removed from the tracker.
  395. Widget tracker tokens are provided for many activities in JupyterLab, including
  396. notebooks, consoles, text files, mime documents, and terminals.
  397. If you are adding your own activities to JupyterLab, you might consider providing
  398. a ``WidgetTracker`` token of your own, so that other extensions can make use of it.