extension_dev.rst 16 KB

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