extension_points.rst 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335
  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 via 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 not an exhaustive account of how to extend the application components,
  8. it is instead intended to be a guide for some of the most common extension points.
  9. Commands
  10. ~~~~~~~~
  11. Perhaps the most common way to add functionality to JupyterLab is via commands.
  12. These are lightweight objects that include a function to execute combined with
  13. additional such as how they are labeled and when they are enabled.
  14. The application has a single command registry, keyed by string command IDs,
  15. to which you can add your custom commands.
  16. The commands added to the command registry can then be used to populate
  17. several of the JupyterLab user interface elements, including menus and the launcher.
  18. Here is a sample block of code that adds a command to the application (given by ``app``):
  19. .. code:: typescript
  20. const commandID = 'my-command';
  21. const toggled = false;
  22. app.commands.addCommand(commandID, {
  23. label: 'My Cool Command',
  24. isEnabled: true,
  25. isVisible: true,
  26. isToggled: () => toggled,
  27. iconClass: 'some-css-icon-class',
  28. execute: () => {
  29. console.log(`Activated ${commandID}`);
  30. toggled = !toggled;
  31. });
  32. This example adds a new command, which, when triggered, calls the ``execute`` function.
  33. ``isEnabled`` indicates whether the command is enabled, and is determined whether
  34. renderings of it are greyed out.
  35. ``isToggled`` indicates whether to render a check mark next to the command.
  36. ``isVisible`` indicates whether to render the command at all.
  37. ``iconClass`` specifies a CSS class which can be used to display an icon next to renderings of the command.
  38. Each of ``isEnabled``, ``isToggled``, and ``isVisible`` can be either
  39. a boolean value or a function that returns a boolean value, in case you want
  40. to do some logic in order to determine those conditions.
  41. Likewise, each of ``label`` and ``iconClass`` can be either
  42. a string value or a function that returns a string value.
  43. There are several more options which can be passed into the command registry when
  44. adding new commands. These are documented
  45. `here <http://phosphorjs.github.io/phosphor/api/commands/interfaces/commandregistry.icommandoptions.html>`__.
  46. Once a command has been added to the application, it can then be added
  47. to various places in the application user interface.
  48. Command Palette
  49. ~~~~~~~~~~~~~~~
  50. In order to add a command to the command palette, you need to request the
  51. ``ICommandPalette`` token in your extension.
  52. Here is an example showing how to add a command to the command palette (given by ``palette``):
  53. .. code:: typescript
  54. palette.addItem({
  55. command: commandID,
  56. category: 'my-category'
  57. args: {}
  58. });
  59. The command ID is the same ID as you used when registering the command.
  60. You must also provide a ``category``, which determines the subcategory of
  61. the command palette in which to render the command.
  62. It can be a preexisting category (e.g., ``'notebook'``), or a new one of your own choosing.
  63. The ``args`` are a JSON object that will be passed into your command's functions at render/execute time.
  64. You can use these to customize the behavior of your command depending on how it is invoked.
  65. For instance, you can pass in ``args: { isPalette: true }``.
  66. Your command ``label`` function can then check the ``args`` it is provided for ``isPalette``,
  67. and return a different label in that case.
  68. This can be useful to make a single command flexible enough to work in multiple contexts.
  69. Main Menu
  70. ~~~~~~~~~
  71. There are three main ways to extend JupyterLab's main menu.
  72. 1. You can add your own menu to the menu bar.
  73. 2. You can add new commands to the existing menus.
  74. 3. You can register your extension with one of the existing semantic menu items.
  75. In all three cases, you should request the ``IMainMenu`` token for your extension.
  76. Adding a New Menu
  77. ^^^^^^^^^^^^^^^^^
  78. To add a new menu to the menu bar, you need to create a new
  79. `Phosphor menu <https://phosphorjs.github.io/phosphor/api/widgets/classes/menu.html>`__.
  80. You can then add commands to the menu in a similar way to the command palette,
  81. and add that menu to the main menu bar:
  82. .. code:: typescript
  83. const menu = new Menu({ commands: app.commands });
  84. menu.addItem({
  85. command: commandID,
  86. args: {},
  87. });
  88. mainMenu.addMenu(menu, { rank: 40 });
  89. As with the command palette, you can optionally pass in ``args`` to customize the
  90. rendering and execution behavior of the command in the menu context.
  91. Adding a New Command to an Existing Menu
  92. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  93. In many cases you will want to add your commands to the existing JupyterLab menus
  94. rather than creating a separate menu for your extension.
  95. Because the top-level JupyterLab menus are shared among many extensions,
  96. the API for adding items is slightly different.
  97. In this case, you provide a list of commands and a rank,
  98. and these commands will be displayed together in a separate group with an existing menu.
  99. For instance, to add a command group with ``firstCommandID`` and ``secondCommandID``
  100. to the File menu, you would do the following:
  101. .. code:: typescript
  102. mainMenu.fileMenu.addGroup([
  103. {
  104. command: firstCommandID,
  105. },
  106. {
  107. command: secondCommandID,
  108. }
  109. ], 40 /* rank */);
  110. Registering a Semantic Menu Item
  111. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  112. There are some commands in the JupyterLab menu system that are considered
  113. common and important enough that they are treated differently.
  114. For instance, we anticipate that many activities may want to provide a command
  115. to close themselves and perform some cleanup operation (like closing a console and shutting down its kernel).
  116. Rather than having a proliferation of similar menu items for this common operation
  117. of "closing-and-cleanup", we provide a single command that can adapt itself to this use case,
  118. which we term "semantic menu items".
  119. For this example, it is the File Menu ``closeAndCleaners`` set.
  120. Here is an example of using the ``closeAndCleaners`` semantic menu item:
  121. .. code:: typescript
  122. mainMenu.fileMenu.closeAndCleaners.add({
  123. tracker,
  124. action: 'Shutdown',
  125. name: 'My Activity',
  126. closeAndCleanup: current => {
  127. current.close();
  128. return current.shutdown();
  129. }
  130. });
  131. In this example, ``tracker`` is a :ref:`widget-tracker`, which allows the menu
  132. item to determine whether to delegate the menu command to your activity,
  133. ``name`` is a name given to your activity in the menu label,
  134. ``action`` is a verb given to the cleanup operation in the menu label,
  135. and ``closeAndCleanup`` is the actual function that performs the cleanup operation.
  136. More examples for how to register semantic menu items are found throughout the JupyterLab code base.
  137. The available semantic menu items are:
  138. - ``IEditMenu.IUndoer``: an activity that knows how to undo and redo.
  139. - ``IEditMenu.IClearer``: an activity that knows how to clear its content.
  140. - ``IEditMenu.IGoToLiner``: an activity that knows how to jump to a given line.
  141. - ``IFileMenu.ICloseAndCleaner``: an activity that knows how to close and clean up after itself.
  142. - ``IFileMenu.IConsoleCreator``: an activity that knows how to create an attached code console for itself.
  143. - ``IHelpMenu.IKernelUser``: an activity that knows how to get a related kernel session.
  144. - ``IKernelMenu.IKernelUser``: an activity that can perform various kernel-related operations.
  145. - ``IRunMenu.ICodeRunner``: an activity that can run code from its content.
  146. - ``IViewMenu.IEditorViewer``: an activity that knows how to set various view-related options on a text editor that it owns.
  147. Context Menu
  148. ~~~~~~~~~~~~
  149. The application context menu is shown when the user right-clicks,
  150. and is populated with menu items that are most relevant to the thing that the user clicked.
  151. The context menu system determines which items to show based on
  152. `CSS selectors <https://developer.mozilla.org/en-US/docs/Learn/CSS/Introduction_to_CSS/Selectors>`__.
  153. It propagates up the DOM tree and tests whether a given HTML element
  154. matches the CSS selector provided by a given command.
  155. Here is an example showing how to add a command to the application context menu:
  156. .. code:: typescript
  157. app.contextMenu.addItem({
  158. command: commandID,
  159. selector: '.jp-Notebook'
  160. })
  161. In this example, the command indicated by ``commandID`` is shown whenever the user
  162. right-clicks on a DOM element matching ``.jp-Notebook`` (that is to say, a notebook).
  163. The selector can be any valid CSS selector, and may target your own UI elements, or existing ones.
  164. A list of CSS selectors currently used by context menu commands is given in :ref:`css-selectors`.
  165. Keyboard Shortcuts
  166. ~~~~~~~~~~~~~~~~~~
  167. There are two ways of adding keyboard shortcuts in JupyterLab.
  168. If you don't want the shortcuts to be user-configurable,
  169. you can add them directly to the application command registry:
  170. .. code:: typescript
  171. app.commands.addKeyBinding({
  172. command: commandID,
  173. args: {},
  174. keys: ['Accel T'],
  175. selector: '.jp-Notebook'
  176. });
  177. In this example ``my-command`` command is mapped to ``Accel T``,
  178. where ``Accel`` corresponds to ``Cmd`` on a Mac and ``Ctrl`` on Windows and Linux computers.
  179. The behavior for keyboard shortcuts is very similar to that of the context menu:
  180. the shortcut handler propagates up the DOM tree from the focused element
  181. and tests each element against the registered selectors. If a match is found,
  182. then that command is executed with the provided ``args``.
  183. Full documentation for the options for ``addKeyBinding`` can be found
  184. `here <http://phosphorjs.github.io/phosphor/api/commands/interfaces/commandregistry.ikeybindingoptions.html>`__.
  185. JupyterLab also provides integration with its settings system for keyboard shortcuts.
  186. Your extension can provide a settings schema with a ``jupyter.lab.shortcuts`` key,
  187. declaring default keyboard shortcuts for a command:
  188. .. code:: json
  189. {
  190. "jupyter.lab.shortcuts": [
  191. {
  192. "command": "my-command",
  193. "keys": ["Accel T"],
  194. "selector": ".jp-mod-searchable"
  195. }
  196. ]
  197. }
  198. Shortcuts added to the settings system will be editable by users.
  199. Launcher
  200. ~~~~~~~~
  201. As with menus, keyboard shortcuts, and the command palette, new items can be added
  202. to the application launcher via commands.
  203. You can do this by requesting the ``ILauncher`` token in your extension:
  204. .. code:: typescript
  205. launcher.add({
  206. command: commandID,
  207. category: 'Other',
  208. rank: 0
  209. });
  210. In addition to providing a command ID, you also provide a category in which to put your item,
  211. (e.g. 'Notebook', or 'Other'), as well as a rank to determine its position among other items.
  212. Left/Right Areas
  213. ~~~~~~~~~~~~~~~~
  214. The left and right areas of JupyterLab are intended to host more persistent user interface
  215. elements than the main area. That being said, extension authors are free to add whatever
  216. components they like to these areas. The outermost-level of the object that you add is expected
  217. to be a Phosphor ``Widget``, but that can host any content you like (such as React components).
  218. As an example, the following code executes an application command to a terminal widget
  219. and then adds the terminal to the right area:
  220. .. code:: typescript
  221. app.commands
  222. .execute('terminal:create-new')
  223. .then((terminal: WidgetModuleType.Terminal) => {
  224. app.shell.add(terminal, 'right');
  225. });
  226. Status Bar
  227. ~~~~~~~~~~
  228. .. _widget-tracker:
  229. Widget Tracker
  230. ~~~~~~~~~~~~~~
  231. Often extensions will want to interact with documents and activities created by other extensions.
  232. For instance, an extension may want to inject some text into a notebook cell,
  233. or set a custom keymap, or close all documents of a certain type.
  234. Actions like these are typically done by widget trackers.
  235. Extensions keep track of instances of their activities in ``WidgetTrackers``,
  236. which are then provided as tokens so that other extensions may request them.
  237. For instance, if you want to interact with notebooks, you should request the ``INotebookTracker`` token.
  238. You can then use this tracker to iterate over, filter, and search all open notebooks.
  239. You can also use it to be notified via signals when notebooks are added and removed from the tracker.
  240. Widget tracker tokens are provided for many activities in JupyterLab, including
  241. notebooks, consoles, text files, mime documents, and terminals.
  242. If you are adding your own activities to JupyterLab, you might consider providing
  243. a ``WidgetTracker`` token of your own, so that other extensions can make use of it.
  244. RenderMime Registry and Documents
  245. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~