extension_dev.rst 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472
  1. .. _developer_extensions:
  2. Extension Developer Guide
  3. -------------------------
  4. .. warning::
  5. The extension developer API is not stable and will evolve in JupyterLab
  6. releases in the near future.
  7. JupyterLab can be extended in four ways via:
  8. - **application plugins (top level):** Application plugins extend the
  9. functionality of JupyterLab itself.
  10. - **mime renderer extensions (top level):** Mime Renderer extensions are
  11. a convenience for creating an extension that can render mime data and
  12. potentially render files of a given type.
  13. - **theme extensions (top level):** Theme extensions allow you to customize the appearance of
  14. JupyterLab by adding your own fonts, CSS rules, and graphics to the application.
  15. - **document widget extensions (lower level):** Document widget extensions
  16. extend the functionality of document widgets added to the
  17. application, and we cover them in :ref:`documents`.
  18. See :ref:`xkcd_extension_tutorial` to learn how to make a simple JupyterLab extension.
  19. To understand how to wrap an **Angular** application as a JupyterLab extension,
  20. see the `"Create your own Angular JupyerLab extension" <https://github.com/SimonBiggs/scriptedforms/blob/master/scriptedforms/docs/create-your-own-angular-jupyterlab-extension.md#create-your-own-angular-jupyerlab-extension>`_ guide provided by
  21. `Scripted Forms <https://github.com/SimonBiggs/scriptedforms>`_.
  22. A JupyterLab application is comprised of:
  23. - A core Application object
  24. - Plugins
  25. Plugins
  26. ~~~~~~~
  27. A plugin adds a core functionality to the application:
  28. - A plugin can require other plugins for operation.
  29. - A plugin is activated when it is needed by other plugins, or when
  30. explicitly activated.
  31. - Plugins require and provide ``Token`` objects, which are used to
  32. provide a typed value to the plugin's ``activate()`` method.
  33. - The module providing plugin(s) must meet the
  34. `JupyterLab.IPluginModule <http://jupyterlab.github.io/jupyterlab/interfaces/_application_src_index_.jupyterlab.ipluginmodule.html>`__
  35. interface, by exporting a plugin object or array of plugin objects as
  36. the default export.
  37. We provide two cookie cutters to create JuptyerLab plugin extensions in
  38. `CommonJS <https://github.com/jupyterlab/extension-cookiecutter-js>`__ and
  39. `TypeScript <https://github.com/jupyterlab/extension-cookiecutter-ts>`__.
  40. The default plugins in the JupyterLab application include:
  41. - `Terminal <https://github.com/jupyterlab/jupyterlab/blob/master/packages/terminal-extension/src/index.ts>`__
  42. - Adds the ability to create command prompt terminals.
  43. - `Shortcuts <https://github.com/jupyterlab/jupyterlab/blob/master/packages/shortcuts-extension/src/index.ts>`__
  44. - Sets the default set of shortcuts for the application.
  45. - `Images <https://github.com/jupyterlab/jupyterlab/blob/master/packages/imageviewer-extension/src/index.ts>`__
  46. - Adds a widget factory for displaying image files.
  47. - `Help <https://github.com/jupyterlab/jupyterlab/blob/master/packages/help-extension/src/index.tsx>`__
  48. - Adds a side bar widget for displaying external documentation.
  49. - `File
  50. Browser <https://github.com/jupyterlab/jupyterlab/blob/master/packages/filebrowser-extension/src/index.ts>`__
  51. - Creates the file browser and the document manager and the file
  52. browser to the side bar.
  53. - `Editor <https://github.com/jupyterlab/jupyterlab/blob/master/packages/fileeditor-extension/src/index.ts>`__
  54. - Add a widget factory for displaying editable source files.
  55. - `Console <https://github.com/jupyterlab/jupyterlab/blob/master/packages/console-extension/src/index.ts>`__
  56. - Adds the ability to launch Jupyter Console instances for
  57. interactive kernel console sessions.
  58. A dependency graph for the core JupyterLab plugins (along with links to
  59. their source) is shown here: |dependencies|
  60. Application Object
  61. ~~~~~~~~~~~~~~~~~~
  62. The JupyterLab Application object is given to each plugin in its
  63. ``activate()`` function. The Application object has a:
  64. - commands - used to add and execute commands in the application.
  65. - keymap - used to add keyboard shortcuts to the application.
  66. - shell - a JupyterLab shell instance.
  67. JupyterLab Shell
  68. ~~~~~~~~~~~~~~~~
  69. The JupyterLab
  70. `shell <http://jupyterlab.github.io/jupyterlab/classes/_application_src_shell_.applicationshell.html>`__
  71. is used to add and interact with content in the application. The
  72. application consists of:
  73. - A top area for things like top level menus and toolbars
  74. - Left and right side bar areas for collapsible content
  75. - A main work area for user activity.
  76. - A bottom area for things like status bars
  77. Phosphor
  78. ~~~~~~~~
  79. The Phosphor library is used as the underlying architecture of
  80. JupyterLab and provides many of the low level primitives and widget
  81. structure used in the application. Phosphor provides a rich set of
  82. widgets for developing desktop-like applications in the browser, as well
  83. as patterns and objects for writing clean, well-abstracted code. The
  84. widgets in the application are primarily **Phosphor widgets**, and
  85. Phosphor concepts, like message passing and signals, are used
  86. throughout. **Phosphor messages** are a *many-to-one* interaction that
  87. enables information like resize events to flow through the widget
  88. hierarchy in the application. **Phosphor signals** are a *one-to-many*
  89. interaction that enable listeners to react to changes in an observed
  90. object.
  91. Extension Authoring
  92. ~~~~~~~~~~~~~~~~~~~
  93. An Extension is a valid `npm
  94. package <https://docs.npmjs.com/getting-started/what-is-npm>`__ that
  95. meets the following criteria:
  96. - Exports one or more JupyterLab plugins as the default export in its
  97. main file.
  98. - Has a ``jupyterlab`` key in its ``package.json`` which has
  99. ``"extension"`` metadata. The value can be ``true`` to use the main
  100. module of the package, or a string path to a specific module (e.g.
  101. ``"lib/foo"``).
  102. While authoring the extension, you can use the command:
  103. .. code:: bash
  104. npm install # install npm package dependencies
  105. npm run build # optional build step if using TypeScript, babel, etc.
  106. jupyter labextension install # install the current directory as an extension
  107. This causes the builder to re-install the source folder before building
  108. the application files. You can re-build at any time using
  109. ``jupyter lab build`` and it will reinstall these packages. You can also
  110. link other local npm packages that you are working on simultaneously
  111. using ``jupyter labextension link``; they will be re-installed but not
  112. considered as extensions. Local extensions and linked packages are
  113. included in ``jupyter labextension list``.
  114. When using local extensions and linked packages, you can run the command
  115. ::
  116. jupyter lab --watch
  117. This will cause the application to incrementally rebuild when one of the
  118. linked packages changes. Note that only compiled JavaScript files (and
  119. the CSS files) are watched by the WebPack process.
  120. Note that the application is built against **released** versions of the
  121. core JupyterLab extensions. If your extension depends on JupyterLab
  122. packages, it should be compatible with the dependencies in the
  123. ``jupyterlab/static/package.json`` file. Note that building will always use the latest JavaScript packages that meet the dependency requirements of JupyterLab itself and any installed extensions. If you wish to test against a
  124. specific patch release of one of the core JupyterLab packages you can
  125. temporarily pin that requirement to a specific version in your own
  126. dependencies.
  127. If you must install a extension into a development branch of JupyterLab, you have to graft it into the source tree of JupyterLab itself. This may be done using the command
  128. ::
  129. jlpm run add:sibling <path-or-url>
  130. in the JupyterLab root directory, where ``<path-or-url>`` refers either
  131. to an extension npm package on the local file system, or a URL to a git
  132. repository for an extension npm package. This operation may be
  133. subsequently reversed by running
  134. ::
  135. jlpm run remove:package <extension-dir-name>
  136. This will remove the package metadata from the source tree, but will
  137. **not** remove any files added by the ``addsibling`` script, which
  138. should be removed manually.
  139. The package should export EMCAScript 5 compatible JavaScript. It can
  140. import CSS using the syntax ``require('foo.css')``. The CSS files can
  141. also import CSS from other packages using the syntax
  142. ``@import url('~foo/index.css')``, where ``foo`` is the name of the
  143. package.
  144. The following file types are also supported (both in JavaScript and
  145. CSS): json, html, jpg, png, gif, svg, js.map, woff2, ttf, eot.
  146. If your package uses any other file type it must be converted to one of
  147. the above types. If your JavaScript is written in any other dialect than
  148. EMCAScript 5 it must be converted using an appropriate tool.
  149. If you publish your extension on npm.org, users will be able to install
  150. it as simply ``jupyter labextension install <foo>``, where ``<foo>`` is
  151. the name of the published npm package. You can alternatively provide a
  152. script that runs ``jupyter labextension install`` against a local folder
  153. path on the user's machine or a provided tarball. Any valid
  154. ``npm install`` specifier can be used in
  155. ``jupyter labextension install`` (e.g. ``foo@latest``, ``bar@3.0.0.0``,
  156. ``path/to/folder``, and ``path/to/tar.gz``).
  157. Mime Renderer Extensions
  158. ~~~~~~~~~~~~~~~~~~~~~~~~
  159. Mime Renderer extensions are a convenience for creating an extension
  160. that can render mime data and potentially render files of a given type.
  161. We provide cookiecutters for Mime render extensions in
  162. `JavaScript <https://github.com/jupyterlab/mimerender-cookiecutter>`__ and
  163. `TypeScript <https://github.com/jupyterlab/mimerender-cookiecutter-ts>`__.
  164. Mime renderer extensions are more declarative than standard extensions.
  165. The extension is treated the same from the command line perspective
  166. (``jupyter labextension install`` ), but it does not directly create
  167. JupyterLab plugins. Instead it exports an interface given in the
  168. `rendermime-interfaces <http://jupyterlab.github.io/jupyterlab/interfaces/_rendermime_interfaces_src_index_.irendermime.iextension.html>`__
  169. package.
  170. The JupyterLab repo has an example mime renderer extension for
  171. `pdf <https://github.com/jupyterlab/jupyterlab/tree/master/packages/pdf-extension>`__
  172. files. It provides a mime renderer for pdf data and registers itself as
  173. a document renderer for pdf file types.
  174. The ``rendermime-interfaces`` package is intended to be the only
  175. JupyterLab package needed to create a mime renderer extension (using the
  176. interfaces in TypeScript or as a form of documentation if using plain
  177. JavaScript).
  178. The only other difference from a standard extension is that has a
  179. ``jupyterlab`` key in its ``package.json`` with ``"mimeExtension"``
  180. metadata. The value can be ``true`` to use the main module of the
  181. package, or a string path to a specific module (e.g. ``"lib/foo"``).
  182. The mime renderer can update its data by calling ``.setData()`` on the
  183. model it is given to render. This can be used for example to add a
  184. ``png`` representation of a dynamic figure, which will be picked up by a
  185. notebook model and added to the notebook document. When using
  186. ``IDocumentWidgetFactoryOptions``, you can update the document model by
  187. calling ``.setData()`` with updated data for the rendered MIME type. The
  188. document can then be saved by the user in the usual manner.
  189. Themes
  190. ~~~~~~
  191. A theme is a JupyterLab extension that uses a ``ThemeManager`` and can
  192. be loaded and unloaded dynamically. The package must include all static
  193. assets that are referenced by ``url()`` in its CSS files. Local URLs can
  194. be used to reference files relative to the location of the referring CSS
  195. file in the theme directory. For example ``url('images/foo.png')`` or
  196. ``url('../foo/bar.css')``\ can be used to refer local files in the
  197. theme. Absolute URLs (starting with a ``/``) or external URLs (e.g.
  198. ``https:``) can be used to refer to external assets. The path to the
  199. theme assets is specified ``package.json`` under the ``"jupyterlab"``
  200. key as ``"themeDir"``. See the `JupyterLab Light
  201. Theme <https://github.com/jupyterlab/jupyterlab/tree/master/packages/theme-light-extension>`__
  202. for an example. Ensure that the theme files are included in the
  203. ``"files"`` metadata in package.json. A theme can optionally specify an
  204. ``embed.css`` file that can be consumed outside of a JupyterLab
  205. application.
  206. To quickly create a theme based on the JupyterLab Light Theme, follow
  207. the instructions in the `contributing
  208. guide <https://github.com/jupyterlab/jupyterlab/blob/master/CONTRIBUTING.md#setting-up-a-development-environment>`__ and
  209. then run ``jlpm run create:theme`` from the repository root directory.
  210. Once you select a name, title and a description, a new theme folder will
  211. be created in the current directory. You can move that new folder to a
  212. location of your choice, and start making desired changes.
  213. The theme extension is installed in the same way as a regular extension (see
  214. `extension authoring <#extension-authoring>`__).
  215. Standard (General-Purpose) Extensions
  216. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  217. JupyterLab's modular architecture is based around the idea
  218. that all extensions are on equal footing, and that they interact
  219. with each other through typed interfaces that are provided by ``Token`` objects.
  220. An extension can provide a ``Token`` to the application,
  221. which other extensions can then request for their own use.
  222. Core Tokens
  223. ^^^^^^^^^^^
  224. The core packages of JupyterLab provide a set of tokens,
  225. which are listed here, along with short descriptions of when you
  226. might want to use them in your extensions.
  227. - ``@jupyterlab/application:ILayoutRestorer``: An interface to the application layout
  228. restoration functionality. Use this to have your activities restored across
  229. page loads.
  230. - ``@jupyterlab/application:IMimeDocumentTracker``: An instance tracker for documents
  231. rendered using a mime renderer extension. Use this if you want to list and interact
  232. with documents rendered by such extensions.
  233. - ``@jupyterlab/application:IRouter``: The URL router used by the application.
  234. Use this to add custom URL-routing for your extension (e.g., to invoke
  235. a command if the user navigates to a sub-path).
  236. - ``@jupyterlab/apputils:ICommandPalette``: An interface to the application command palette
  237. in the left panel. Use this to add commands to the palette.
  238. - ``@jupyterlab/apputils:ISplashScreen``: An interface to the splash screen for the application.
  239. Use this if you want to show the splash screen for your own purposes.
  240. - ``@jupyterlab/apputils:IThemeManager``: An interface to the theme manager for the application.
  241. Most extensions will not need to use this, as they can register a
  242. `theme extension <#themes>`__.
  243. - ``@jupyterlab/apputils:IWindowResolver``: An interface to a window resolver for the
  244. application. JupyterLab workspaces are given a name, which are determined using
  245. the window resolver. Require this if you want to use the name of the current workspace.
  246. - ``@jupyterlab/codeeditor:IEditorServices``: An interface to the text editor provider
  247. for the application. Use this to create new text editors and host them in your
  248. UI elements.
  249. - ``@jupyterlab/completer:ICompletionManager``: An interface to the completion manager
  250. for the application. Use this to allow your extension to invoke a completer.
  251. - ``@jupyterlab/console:IConsoleTracker``: An instance tracker for code consoles.
  252. Use this if you want to be able to iterate over and interact with code consoles
  253. created by the application.
  254. - ``@jupyterlab/console:IContentFactory``: A factory object that creates new code
  255. consoles. Use this if you want to create and host code consoles in your own UI elements.
  256. - ``@jupyterlab/coreutils:ISettingRegistry``: An interface to the JupyterLab settings system.
  257. Use this if you want to store settings for your application.
  258. See `extension settings <#extension-settings>`__ for more information.
  259. - ``@jupyterlab/coreutils:IStateDB``: An interface to the JupyterLab state database.
  260. Use this if you want to store data that will persist across page loads.
  261. See `state database <#state-database>`__ for more information.
  262. - ``@jupyterlab/docmanager:IDocumentManager``: An interface to the manager for all
  263. documents used by the application. Use this if you want to open and close documents,
  264. create and delete files, and otherwise interact with the file system.
  265. - ``@jupyterlab/filebrowser:IFileBrowserFactory``: A factory object that creates file browsers.
  266. Use this if you want to create your own file browser (e.g., for a custom storage backend),
  267. or to interact with other file browsers that have been created by extensions.
  268. - ``@jupyterlab/fileeditor:IEditorTracker``: An instance tracker for file editors.
  269. Use this if you want to be able to iterate over and interact with file editors
  270. created by the application.
  271. - ``@jupyterlab/imageviewer:IImageTracker``: An instance tracker for images.
  272. Use this if you want to be able to iterate over and interact with images
  273. viewed by the application.
  274. - ``@jupyterlab/inspector:IInspector``: An interface for adding variable inspectors to widgets.
  275. Use this to add the ability to hook into the variable inspector to your extension.
  276. - ``@jupyterlab/launcher:ILauncher``: An interface to the application activity launcher.
  277. Use this to add your extension activities to the launcher panel.
  278. - ``@jupyterlab/mainmenu:IMainMenu``: An interface to the main menu bar for the application.
  279. Use this if you want to add your own menu items.
  280. - ``@jupyterlab/notebook:ICellTools``: An interface to the ``Cell Tools`` panel in the
  281. application left area. Use this to add your own functionality to the panel.
  282. - ``@jupyterlab/notebook:IContentFactory``: A factory object that creates new notebooks.
  283. Use this if you want to create and host notebooks in your own UI elements.
  284. - ``@jupyterlab/notebook:INotebookTracker``: An instance tracker for code consoles.
  285. Use this if you want to be able to iterate over and interact with notebooks
  286. created by the application.
  287. - ``@jupyterlab/rendermime:IRenderMimeRegistry``: An interface to the rendermime registry
  288. for the application. Use this to create renderers for various mime-types in your extension.
  289. Most extensions will not need to use this, as they can register a
  290. `mime renderer extension <#mime-renderer-extensions>`__.
  291. - ``@jupyterlab/rendermime:ILatexTypesetter``: An interface to the LaTeX typesetter for the
  292. application. Use this if you want to typeset math in your extension.
  293. - ``@jupyterlab/settingeditor:ISettingEditorTracker``: An instance tracker for setting editors.
  294. Use this if you want to be able to iterate over and interact with setting editors
  295. created by the application.
  296. - ``@jupyterlab/terminal:ITerminalTracker``: An instance tracker for terminals.
  297. Use this if you want to be able to iterate over and interact with terminals
  298. created by the application.
  299. - ``@jupyterlab/tooltip:ITooltipManager``: An interface to the tooltip manager for the application.
  300. Use this to allow your extension to invoke a tooltip.
  301. Standard Extension Example
  302. ^^^^^^^^^^^^^^^^^^^^^^^^^^
  303. For a concrete example of a standard extension, see `How to Extend the Notebook
  304. Plugin <./notebook.html#how-to-extend-the-notebook-plugin>`__. Notice
  305. that the mime renderer and themes extensions above use a limited,
  306. simplified interface to JupyterLab's extension system. Modifying the
  307. notebook plugin requires the full, general-purpose interface to the
  308. extension system.
  309. Storing Extension Data
  310. ^^^^^^^^^^^^^^^^^^^^^^
  311. In addition to the file system that is accessed by using the
  312. ``@jupyterlab/services`` package, JupyterLab offers two ways for
  313. extensions to store data: a client-side state database that is built on
  314. top of ``localStorage`` and a plugin settings system that provides for
  315. default setting values and user overrides.
  316. Extension Settings
  317. ``````````````````
  318. An extension can specify user settings using a JSON Schema. The schema
  319. definition should be in a file that resides in the ``schemaDir``
  320. directory that is specified in the ``package.json`` file of the
  321. extension. The actual file name should use is the part that follows the
  322. package name of extension. So for example, the JupyterLab
  323. ``apputils-extension`` package hosts several plugins:
  324. - ``'@jupyterlab/apputils-extension:menu'``
  325. - ``'@jupyterlab/apputils-extension:palette'``
  326. - ``'@jupyterlab/apputils-extension:settings'``
  327. - ``'@jupyterlab/apputils-extension:themes'``
  328. And in the ``package.json`` for ``@jupyterlab/apputils-extension``, the
  329. ``schemaDir`` field is a directory called ``schema``. Since the
  330. ``themes`` plugin requires a JSON schema, its schema file location is:
  331. ``schema/themes.json``. The plugin's name is used to automatically
  332. associate it with its settings file, so this naming convention is
  333. important. Ensure that the schema files are included in the ``"files"``
  334. metadata in ``package.json``.
  335. See the
  336. `fileeditor-extension <https://github.com/jupyterlab/jupyterlab/tree/master/packages/fileeditor-extension>`__
  337. for another example of an extension that uses settings.
  338. State Database
  339. ``````````````
  340. The state database can be accessed by importing ``IStateDB`` from
  341. ``@jupyterlab/coreutils`` and adding it to the list of ``requires`` for
  342. a plugin:
  343. .. code:: typescript
  344. const id = 'foo-extension:IFoo';
  345. const IFoo = new Token<IFoo>(id);
  346. interface IFoo {}
  347. class Foo implements IFoo {}
  348. const plugin: JupyterLabPlugin<IFoo> = {
  349. id,
  350. requires: [IStateDB],
  351. provides: IFoo,
  352. activate: (app: JupyterLab, state: IStateDB): IFoo => {
  353. const foo = new Foo();
  354. const key = `${id}:some-attribute`;
  355. // Load the saved plugin state and apply it once the app
  356. // has finished restoring its former layout.
  357. Promise.all([state.fetch(key), app.restored])
  358. .then(([saved]) => { /* Update `foo` with `saved`. */ });
  359. // Fulfill the plugin contract by returning an `IFoo`.
  360. return foo;
  361. },
  362. autoStart: true
  363. };
  364. Context Menus
  365. ^^^^^^^^^^^^^
  366. JupyterLab has an application-wide context menu available as
  367. ``app.contextMenu``. See the Phosphor
  368. `docs <http://phosphorjs.github.io/phosphor/api/widgets/interfaces/contextmenu.iitemoptions.html>`__
  369. for the item creation options. If you wish to preempt the
  370. application context menu, you can use a 'contextmenu' event listener and
  371. call ``event.stopPropagation`` to prevent the application context menu
  372. handler from being called (it is listening in the bubble phase on the
  373. ``document``). At this point you could show your own Phosphor
  374. `contextMenu <http://phosphorjs.github.io/phosphor/api/widgets/classes/contextmenu.html>`__,
  375. or simply stop propagation and let the system context menu be shown.
  376. This would look something like the following in a ``Widget`` subclass:
  377. .. code:: javascript
  378. // In `onAfterAttach()`
  379. this.node.addEventListener('contextmenu', this);
  380. // In `handleEvent()`
  381. case 'contextmenu':
  382. event.stopPropagation();
  383. .. |dependencies| image:: dependency-graph.svg