extension_dev.rst 40 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863
  1. .. _developer_extensions:
  2. Extension Developer Guide
  3. =========================
  4. JupyterLab can be extended in four ways via:
  5. - **application plugins (top level):** Application plugins extend the
  6. functionality of JupyterLab itself.
  7. - **mime renderer extensions (top level):** Mime Renderer extensions are
  8. a convenience for creating an extension that can render mime data and
  9. potentially render files of a given type.
  10. - **theme extensions (top level):** Theme extensions allow you to customize the appearance of
  11. JupyterLab by adding your own fonts, CSS rules, and graphics to the application.
  12. - **document widget extensions (lower level):** Document widget extensions
  13. extend the functionality of document widgets added to the
  14. application, and we cover them in :ref:`documents`.
  15. A JupyterLab application is comprised of:
  16. - A core Application object
  17. - Plugins
  18. Starting in JupyterLab 3.0, extensions are distributed as ``pip`` or
  19. ``conda`` packages that contain federated JavaScript bundles. You can write extensions in JavaScript or any language that compiles to JavaScript. We recommend writing extensions in `TypeScript <https://www.typescriptlang.org/>`_, which is used for the JupyterLab core extensions and many popular community extensions. You use our build tool to generate the bundles that are shipped with the package, typically through a cookiecutter.
  20. We encourage extension authors to add the `jupyterlab-extension GitHub topic
  21. <https://github.com/search?utf8=%E2%9C%93&q=topic%3Ajupyterlab-extension&type=Repositories>`__
  22. to any GitHub extension repository.
  23. Goals of the Federated Extension System
  24. ---------------------------------------
  25. - Users should be able to install and use extensions without requiring ``node`` or a build step
  26. - Extension authors should be able to easily build and distribute extensions
  27. - The existing capabilities of built-in extensions should still work
  28. - Administrators should retain the ability to set global configuration and packages where possible
  29. - Federated extensions should layer on top of existing extensions similar to how ``pip install --user`` works
  30. - Extensions should be discoverable
  31. Implementation
  32. --------------
  33. - We provide a ``jupyter labextension build`` script that is used to build federated bundles
  34. - The command produces a set of static assets that are shipped along with a package (notionally on ``pip``/``conda``)
  35. - It is a Python cli so that it can use the dependency metadata from the active JupyterLab
  36. - The assets include a module federation ``remoteEntry.*.js``, generated bundles, and some other files that we use
  37. - ``package.json`` is the original ``package.json`` file that we use to gather metadata about the package, with some included build metadata
  38. - we use the previously existing ``@jupyterlab/builder -> build`` to generate the ``imports.css``, ``schemas`` and ``themes`` file structure
  39. - We provide a schema for the valid ``jupyterlab`` metadata for an extension's ``package.json`` describing the available options
  40. - We provide a ``labextensions`` handler in ``jupyterlab_server`` that loads static assets from ``labextensions`` paths, following a similar logic to how ``nbextensions`` are discovered and loaded from disk
  41. - The ``settings`` and ``themes`` handlers in ``jupyterlab_server`` has been updated to load from the new ``labextensions`` locations, favoring the federated extension locations over the bundled ones
  42. - A ``labextension develop`` command has been added to install an in-development extension into JupyterLab. The default behavior is to create a symlink in the ``sys-prefix/share/jupyter/labextensions/package-name`` to the static directory of the extension
  43. - We provide a ``cookiecutter`` that handles all of the scaffolding for an extension author, including the shipping of ``data_files`` so that when the user installs the package, the static assets end up in ``share/jupyter/labextensions``
  44. - We handle disabling of lab extensions using a trait on the ``LabApp`` class, so it can be set by admins and overridden by users. Extensions are automatically enabled when installed, and must be explicitly disabled. The disabled config can consist of a package name or a plugin regex pattern
  45. - Extensions can provide ``disabled`` metadata that can be used to replace an entire extension or individual plugins
  46. - ``page_config`` and ``overrides`` are also handled with traits so that admins can provide defaults and users can provide overrides
  47. - We provide a script to update extensions: ``python -m jupyterlab.upgrade_extension``
  48. - We update the ``extension-manager`` to target metadata on ``pypi``/``conda`` and consume those packages.
  49. Tools
  50. -----
  51. - ``jupyter labexension build`` python command line tool
  52. - ``jupyter labextension develop`` python command line tool
  53. - ``python -m jupyterlab.upgrade_extension`` python command line tool
  54. - ``cookiecutter`` for extension authors
  55. Workflow for extension authors
  56. ------------------------------
  57. - Use the ``cookiecutter`` to create the extension
  58. - Run ``jupyter labextension develop`` to build and symlink the files
  59. - Run ``jlpm run watch`` to start watching
  60. - Run ``jupyter lab``
  61. - Make changes to source
  62. - Refresh the application page
  63. - When finished, publish the package to ``pypi``/``conda``
  64. Custom webpack config for federated extensions
  65. ----------------------------------------------
  66. .. warning::
  67. This feature is *experimental*, as it makes it possible to override the base config used by the
  68. JupyterLab Federated Extension System.
  69. It also exposes the internals of the federated extension build system (namely ``webpack``) to extension authors, which was until now
  70. kept as an implementation detail.
  71. The JupyterLab Federated Extension System uses ``webpack`` to build federated extensions, relying on the
  72. `Module Federation System <https://webpack.js.org/concepts/module-federation/>`_ added in webpack 5.
  73. To specify a custom webpack config to the federated extension build system, extension authors can add the ``webpackConfig`` subkey to the
  74. ``package.json`` of their extension::
  75. "jupyterlab": {
  76. "webpackConfig": "webpack.config.js"
  77. }
  78. The webpack config file can be placed in a different location with a custom name::
  79. "jupyterlab": {
  80. "webpackConfig": "./config/test-config.js"
  81. }
  82. Here is an example of a custom config that enables the async WebAssembly and top-level ``await`` experiments:
  83. .. code-block:: javascript
  84. module.exports = {
  85. experiments: {
  86. topLevelAwait: true,
  87. asyncWebAssembly: true,
  88. }
  89. };
  90. This custom config will be merged with the `default config <https://github.com/jupyterlab/jupyterlab/blob/master/builder/src/webpack.config.base.ts>`_
  91. when building the federated extension with ``jlpm run build``.
  92. .. note::
  93. These docs are under construction as we iterate and update tutorials and cookiecutters.
  94. Tutorials
  95. ---------
  96. We provide a set of guides to get started writing third-party extensions for JupyterLab:
  97. - :ref:`extension_tutorial`: An in-depth tutorial to learn how to make a simple JupyterLab extension.
  98. - The `JupyterLab Extension Examples Repository <https://github.com/jupyterlab/extension-examples>`_: A short tutorial series
  99. to learn how to develop extensions for JupyterLab, by example.
  100. - :ref:`developer-extension-points`: A list of the most common JupyterLab extension points.
  101. Cookiecutters
  102. -------------
  103. We provide several cookiecutters to create JupyterLab plugin extensions:
  104. - `extension-cookiecutter-ts <https://github.com/jupyterlab/extension-cookiecutter-ts>`_: Create a JupyterLab extension in TypeScript
  105. - `extension-cookiecutter-js <https://github.com/jupyterlab/extension-cookiecutter-js>`_: Create a JupyterLab extension in JavaScript
  106. - `mimerender-cookiecutter-ts <https://github.com/jupyterlab/mimerender-cookiecutter-ts>`_: Create a MIME Renderer JupyterLab extension in TypeScript
  107. - `theme-cookiecutter <https://github.com/jupyterlab/theme-cookiecutter>`_: Create a new theme for JupyterLab
  108. API Documentation
  109. -----------------
  110. If you are looking for lower level details on the JupyterLab and Lumino API:
  111. - `JupyterLab API Documentation <https://jupyterlab.github.io/jupyterlab/>`_
  112. - `Lumino API Documentation <https://jupyterlab.github.io/lumino/>`_
  113. Plugins
  114. -------
  115. A plugin adds a core functionality to the application:
  116. - A plugin can require other plugins for operation.
  117. - A plugin is activated when it is needed by other plugins, or when
  118. explicitly activated.
  119. - Plugins require and provide ``Token`` objects, which are used to
  120. provide a typed value to the plugin's ``activate()`` method.
  121. - The module providing plugin(s) must meet the
  122. `JupyterLab.IPluginModule <https://jupyterlab.github.io/jupyterlab/interfaces/_application_src_index_.jupyterlab.ipluginmodule.html>`__
  123. interface, by exporting a plugin object or array of plugin objects as
  124. the default export.
  125. The default plugins in the JupyterLab application include:
  126. - `Terminal <https://github.com/jupyterlab/jupyterlab/blob/master/packages/terminal-extension/src/index.ts>`__
  127. - Adds the ability to create command prompt terminals.
  128. - `Shortcuts <https://github.com/jupyterlab/jupyterlab/blob/master/packages/shortcuts-extension/src/index.ts>`__
  129. - Sets the default set of shortcuts for the application.
  130. - `Images <https://github.com/jupyterlab/jupyterlab/blob/master/packages/imageviewer-extension/src/index.ts>`__
  131. - Adds a widget factory for displaying image files.
  132. - `Help <https://github.com/jupyterlab/jupyterlab/blob/master/packages/help-extension/src/index.tsx>`__
  133. - Adds a side bar widget for displaying external documentation.
  134. - `File
  135. Browser <https://github.com/jupyterlab/jupyterlab/blob/master/packages/filebrowser-extension/src/index.ts>`__
  136. - Creates the file browser and the document manager and the file
  137. browser to the side bar.
  138. - `Editor <https://github.com/jupyterlab/jupyterlab/blob/master/packages/fileeditor-extension/src/index.ts>`__
  139. - Add a widget factory for displaying editable source files.
  140. - `Console <https://github.com/jupyterlab/jupyterlab/blob/master/packages/console-extension/src/index.ts>`__
  141. - Adds the ability to launch Jupyter Console instances for
  142. interactive kernel console sessions.
  143. Here is a dependency graph for the core JupyterLab components: |dependencies|
  144. .. danger::
  145. Installing an extension allows for arbitrary code execution on the
  146. server, kernel, and in the client's browser. You should therefore
  147. take steps to protect against malicious changes to your extension's
  148. code. This includes ensuring strong authentication for your PyPI
  149. account.
  150. Application Object
  151. ------------------
  152. A Jupyter front-end application object is given to each plugin in its
  153. ``activate()`` function. The application object has:
  154. - ``commands`` - an extensible registry used to add and execute commands in the application.
  155. - ``commandLinker`` - used to connect DOM nodes with the command registry so that clicking on them executes a command.
  156. - ``docRegistry`` - an extensible registry containing the document types that the application is able to read and render.
  157. - ``restored`` - a promise that is resolved when the application has finished loading.
  158. - ``serviceManager`` - low-level manager for talking to the Jupyter REST API.
  159. - ``shell`` - a generic Jupyter front-end shell instance, which holds the user interface for the application.
  160. Jupyter Front-End Shell
  161. -----------------------
  162. The Jupyter front-end
  163. `shell <https://jupyterlab.github.io/jupyterlab/interfaces/_application_src_index_.jupyterfrontend.ishell.html>`__
  164. is used to add and interact with content in the application. The ``IShell``
  165. interface provides an ``add()`` method for adding widgets to the application.
  166. In JupyterLab, the application shell consists of:
  167. - A ``top`` area for things like top-level toolbars and information.
  168. - 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.
  169. - ``left`` and ``right`` side bar areas for collapsible content.
  170. - A ``main`` work area for user activity.
  171. - A ``bottom`` area for things like status bars.
  172. - A ``header`` area for custom elements.
  173. Lumino
  174. ------
  175. The Lumino library is used as the underlying architecture of
  176. JupyterLab and provides many of the low level primitives and widget
  177. structure used in the application. Lumino provides a rich set of
  178. widgets for developing desktop-like applications in the browser, as well
  179. as patterns and objects for writing clean, well-abstracted code. The
  180. widgets in the application are primarily **Lumino widgets**, and
  181. Lumino concepts, like message passing and signals, are used
  182. throughout. **Lumino messages** are a *many-to-one* interaction that
  183. enables information like resize events to flow through the widget
  184. hierarchy in the application. **Lumino signals** are a *one-to-many*
  185. interaction that enable listeners to react to changes in an observed
  186. object.
  187. Extension Authoring
  188. -------------------
  189. An Extension is a valid `npm
  190. package <https://docs.npmjs.com/getting-started/what-is-npm>`__ that
  191. meets the following criteria:
  192. - Exports one or more JupyterLab plugins as the default export in its
  193. main file.
  194. - Has a ``jupyterlab`` key in its ``package.json`` which has
  195. ``"extension"`` metadata. The value can be ``true`` to use the main
  196. module of the package, or a string path to a specific module (e.g.
  197. ``"lib/foo"``). Example::
  198. "jupyterlab": {
  199. "extension": true
  200. }
  201. - It is also recommended to include the keyword ``jupyterlab-extension``
  202. in the ``package.json``, to aid with discovery (e.g. by the extension
  203. manager). Example::
  204. "keywords": [
  205. "jupyter",
  206. "jupyterlab",
  207. "jupyterlab-extension"
  208. ],
  209. While authoring the extension, you can use the command:
  210. .. code:: bash
  211. npm install # install npm package dependencies
  212. npm run build # optional build step if using TypeScript, babel, etc.
  213. jupyter labextension install # install the current directory as an extension
  214. This causes the builder to re-install the source folder before building
  215. the application files. You can re-build at any time using
  216. ``jupyter lab build`` and it will reinstall these packages.
  217. You can also link other local ``npm`` packages that you are working on
  218. simultaneously using ``jupyter labextension link``; they will be re-installed
  219. but not considered as extensions. Local extensions and linked packages are
  220. included in ``jupyter labextension list``.
  221. When using local extensions and linked packages, you can run the command
  222. ::
  223. jupyter lab --watch
  224. This will cause the application to incrementally rebuild when one of the
  225. linked packages changes. Note that only compiled JavaScript files (and
  226. the CSS files) are watched by the WebPack process. This means that if
  227. your extension is in TypeScript you'll have to run a ``jlpm run build``
  228. before the changes will be reflected in JupyterLab. To avoid this step
  229. you can also watch the TypeScript sources in your extension which is
  230. usually assigned to the ``tsc -w`` shortcut. If WebPack doesn't seem to
  231. detect the changes, this can be related to `the number of available watches <https://github.com/webpack/docs/wiki/troubleshooting#not-enough-watchers>`__.
  232. Note that the application is built against **released** versions of the
  233. core JupyterLab extensions. If your extension depends on JupyterLab
  234. packages, it should be compatible with the dependencies in the
  235. ``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
  236. specific patch release of one of the core JupyterLab packages you can
  237. temporarily pin that requirement to a specific version in your own
  238. dependencies.
  239. If you must install an 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
  240. ::
  241. jlpm run add:sibling <path-or-url>
  242. in the JupyterLab root directory, where ``<path-or-url>`` refers either
  243. to an extension ``npm`` package on the local file system, or a URL to a git
  244. repository for an extension ``npm`` package. This operation may be
  245. subsequently reversed by running
  246. ::
  247. jlpm run remove:package <extension-dir-name>
  248. This will remove the package metadata from the source tree and delete
  249. all of the package files.
  250. The package should export EMCAScript 6 compatible JavaScript. It can
  251. import CSS using the syntax ``require('foo.css')``. The CSS files can
  252. also import CSS from other packages using the syntax
  253. ``@import url('~foo/index.css')``, where ``foo`` is the name of the
  254. package.
  255. The following file types are also supported (both in JavaScript and
  256. CSS): ``json``, ``html``, ``jpg``, ``png``, ``gif``, ``svg``,
  257. ``js.map``, ``woff2``, ``ttf``, ``eot``.
  258. If your package uses any other file type it must be converted to one of
  259. the above types or `include a loader in the import statement <https://webpack.js.org/concepts/loaders/#inline>`__.
  260. If you include a loader, the loader must be importable at build time, so if
  261. it is not already installed by JupyterLab, you must add it as a dependency
  262. of your extension.
  263. If your JavaScript is written in any other dialect than
  264. EMCAScript 6 (2015) it should be converted using an appropriate tool.
  265. You can use Webpack to pre-build your extension to use any of it's features
  266. not enabled in our build configuration. To build a compatible package set
  267. ``output.libraryTarget`` to ``"commonjs2"`` in your Webpack configuration.
  268. (see `this <https://github.com/saulshanabrook/jupyterlab-webpack>`__ example repo).
  269. Another option to try out your extension with a local version of JupyterLab is to add it to the
  270. list of locally installed packages and to have JupyterLab register your extension when it starts up.
  271. You can do this by adding your extension to the ``jupyterlab.externalExtensions`` key
  272. in the ``dev_mode/package.json`` file. It should be a mapping
  273. of extension name to version, just like in ``dependencies``. Then run ``jlpm run integrity``
  274. and these extensions should be added automatically to the ``dependencies`` and pulled in.
  275. When you then run ``jlpm run build && jupyter lab --dev`` or ``jupyter lab --dev --watch`` this extension
  276. will be loaded by default. For example, this is how you can add the Jupyter Widgets
  277. extensions:
  278. ::
  279. "externalExtensions": {
  280. "@jupyter-widgets/jupyterlab-manager": "2.0.0"
  281. },
  282. If you publish your extension on ``npm.org``, users will be able to install
  283. it as simply ``jupyter labextension install <foo>``, where ``<foo>`` is
  284. the name of the published ``npm`` package. You can alternatively provide a
  285. script that runs ``jupyter labextension install`` against a local folder
  286. path on the user's machine or a provided tarball. Any valid
  287. ``npm install`` specifier can be used in
  288. ``jupyter labextension install`` (e.g. ``foo@latest``, ``bar@3.0.0.0``,
  289. ``path/to/folder``, and ``path/to/tar.gz``).
  290. Testing your extension
  291. ^^^^^^^^^^^^^^^^^^^^^^
  292. There are a number of helper functions in ``testutils`` in this repo (which
  293. is a public ``npm`` package called ``@jupyterlab/testutils``) that can be used when
  294. writing tests for an extension. See ``tests/test-application`` for an example
  295. of the infrastructure needed to run tests. There is a ``karma`` config file
  296. that points to the parent directory's ``karma`` config, and a test runner,
  297. ``run-test.py`` that starts a Jupyter server.
  298. If you are using `jest <https://jestjs.io/>`__ to test your extension, you will
  299. need to transpile the jupyterlab packages to ``commonjs`` as they are using ES6 modules
  300. that ``node`` does not support.
  301. To transpile jupyterlab packages, you need to install the following package:
  302. ::
  303. jlpm add --dev jest@^24 @types/jest@^24 ts-jest@^24 @babel/core@^7 @babel/preset-env@^7
  304. Then in `jest.config.js`, you will specify to use babel for js files and ignore
  305. all node modules except the jupyterlab ones:
  306. ::
  307. module.exports = {
  308. preset: 'ts-jest/presets/js-with-babel',
  309. moduleFileExtensions: ['ts', 'tsx', 'js', 'jsx', 'json', 'node'],
  310. transformIgnorePatterns: ['/node_modules/(?!(@jupyterlab/.*)/)'],
  311. globals: {
  312. 'ts-jest': {
  313. tsConfig: 'tsconfig.json'
  314. }
  315. },
  316. ... // Other options useful for your extension
  317. };
  318. Finally, you will need to configure babel with a ``babel.config.js`` file containing:
  319. ::
  320. module.exports = {
  321. presets: [
  322. [
  323. '@babel/preset-env',
  324. {
  325. targets: {
  326. node: 'current'
  327. }
  328. }
  329. ]
  330. ]
  331. };
  332. .. _rendermime:
  333. Mime Renderer Extensions
  334. ------------------------
  335. Mime Renderer extensions are a convenience for creating an extension
  336. that can render mime data and potentially render files of a given type.
  337. We provide a cookiecutter for mime renderer extensions in TypeScript
  338. `here <https://github.com/jupyterlab/mimerender-cookiecutter-ts>`__.
  339. Mime renderer extensions are more declarative than standard extensions.
  340. The extension is treated the same from the command line perspective
  341. (``jupyter labextension install`` ), but it does not directly create
  342. JupyterLab plugins. Instead it exports an interface given in the
  343. `rendermime-interfaces <https://jupyterlab.github.io/jupyterlab/interfaces/_rendermime_interfaces_src_index_.irendermime.iextension.html>`__
  344. package.
  345. The JupyterLab repo has an example mime renderer extension for
  346. `pdf <https://github.com/jupyterlab/jupyterlab/tree/master/packages/pdf-extension>`__
  347. files. It provides a mime renderer for pdf data and registers itself as
  348. a document renderer for pdf file types.
  349. The JupyterLab organization also has a mime renderer extension tutorial
  350. which adds mp4 video rendering to the application
  351. `here <https://github.com/jupyterlab/jupyterlab-mp4>`__.
  352. The ``rendermime-interfaces`` package is intended to be the only
  353. JupyterLab package needed to create a mime renderer extension (using the
  354. interfaces in TypeScript or as a form of documentation if using plain
  355. JavaScript).
  356. The only other difference from a standard extension is that has a
  357. ``jupyterlab`` key in its ``package.json`` with ``"mimeExtension"``
  358. metadata. The value can be ``true`` to use the main module of the
  359. package, or a string path to a specific module (e.g. ``"lib/foo"``).
  360. The mime renderer can update its data by calling ``.setData()`` on the
  361. model it is given to render. This can be used for example to add a
  362. ``png`` representation of a dynamic figure, which will be picked up by a
  363. notebook model and added to the notebook document. When using
  364. ``IDocumentWidgetFactoryOptions``, you can update the document model by
  365. calling ``.setData()`` with updated data for the rendered MIME type. The
  366. document can then be saved by the user in the usual manner.
  367. Themes
  368. ------
  369. A theme is a JupyterLab extension that uses a ``ThemeManager`` and can
  370. be loaded and unloaded dynamically. The package must include all static
  371. assets that are referenced by ``url()`` in its CSS files. Local URLs can
  372. be used to reference files relative to the location of the referring sibling CSS files. For example ``url('images/foo.png')`` or
  373. ``url('../foo/bar.css')``\ can be used to refer local files in the
  374. theme. Absolute URLs (starting with a ``/``) or external URLs (e.g.
  375. ``https:``) can be used to refer to external assets. The path to the
  376. theme asset entry point is specified ``package.json`` under the ``"jupyterlab"``
  377. key as ``"themePath"``. See the `JupyterLab Light
  378. Theme <https://github.com/jupyterlab/jupyterlab/tree/master/packages/theme-light-extension>`__
  379. for an example. Ensure that the theme files are included in the
  380. ``"files"`` metadata in ``package.json``. Note that if you want to use SCSS, SASS, or LESS files,
  381. you must compile them to CSS and point JupyterLab to the CSS files.
  382. The theme extension is installed in the same way as a regular extension (see
  383. `extension authoring <#extension-authoring>`__).
  384. It is also possible to create a new theme using the
  385. `TypeScript theme cookiecutter <https://github.com/jupyterlab/theme-cookiecutter>`__.
  386. Standard (General-Purpose) Extensions
  387. -------------------------------------
  388. JupyterLab's modular architecture is based around the idea
  389. that all extensions are on equal footing, and that they interact
  390. with each other through typed interfaces that are provided by ``Token`` objects.
  391. An extension can provide a ``Token`` to the application,
  392. which other extensions can then request for their own use.
  393. .. _tokens:
  394. Core Tokens
  395. ^^^^^^^^^^^
  396. The core packages of JupyterLab provide a set of tokens,
  397. which are listed here, along with short descriptions of when you
  398. might want to use them in your extensions.
  399. - ``@jupyterlab/application:IConnectionLost``: A token for invoking the dialog shown
  400. when JupyterLab has lost its connection to the server. Use this if, for some reason,
  401. you want to bring up the "connection lost" dialog under new circumstances.
  402. - ``@jupyterlab/application:IInfo``: A token providing metadata about the current
  403. application, including currently disabled extensions and whether dev mode is enabled.
  404. - ``@jupyterlab/application:IPaths``: A token providing information about various
  405. URLs and server paths for the current application. Use this token if you want to
  406. assemble URLs to use the JupyterLab REST API.
  407. - ``@jupyterlab/application:ILabStatus``: An interface for interacting with the application busy/dirty
  408. status. Use this if you want to set the application "busy" favicon, or to set
  409. the application "dirty" status, which asks the user for confirmation before leaving.
  410. - ``@jupyterlab/application:ILabShell``: An interface to the JupyterLab shell.
  411. The top-level application object also has a reference to the shell, but it has a restricted
  412. interface in order to be agnostic to different spins on the application.
  413. Use this to get more detailed information about currently active widgets and layout state.
  414. - ``@jupyterlab/application:ILayoutRestorer``: An interface to the application layout
  415. restoration functionality. Use this to have your activities restored across
  416. page loads.
  417. - ``@jupyterlab/application:IMimeDocumentTracker``: A widget tracker for documents
  418. rendered using a mime renderer extension. Use this if you want to list and interact
  419. with documents rendered by such extensions.
  420. - ``@jupyterlab/application:IRouter``: The URL router used by the application.
  421. Use this to add custom URL-routing for your extension (e.g., to invoke
  422. a command if the user navigates to a sub-path).
  423. - ``@jupyterlab/apputils:ICommandPalette``: An interface to the application command palette
  424. in the left panel. Use this to add commands to the palette.
  425. - ``@jupyterlab/apputils:ISplashScreen``: An interface to the splash screen for the application.
  426. Use this if you want to show the splash screen for your own purposes.
  427. - ``@jupyterlab/apputils:IThemeManager``: An interface to the theme manager for the application.
  428. Most extensions will not need to use this, as they can register a
  429. `theme extension <#themes>`__.
  430. - ``@jupyterlab/apputils:IWindowResolver``: An interface to a window resolver for the
  431. application. JupyterLab workspaces are given a name, which are determined using
  432. the window resolver. Require this if you want to use the name of the current workspace.
  433. - ``@jupyterlab/codeeditor:IEditorServices``: An interface to the text editor provider
  434. for the application. Use this to create new text editors and host them in your
  435. UI elements.
  436. - ``@jupyterlab/completer:ICompletionManager``: An interface to the completion manager
  437. for the application. Use this to allow your extension to invoke a completer.
  438. - ``@jupyterlab/console:IConsoleTracker``: A widget tracker for code consoles.
  439. Use this if you want to be able to iterate over and interact with code consoles
  440. created by the application.
  441. - ``@jupyterlab/console:IContentFactory``: A factory object that creates new code
  442. consoles. Use this if you want to create and host code consoles in your own UI elements.
  443. - ``@jupyterlab/docmanager:IDocumentManager``: An interface to the manager for all
  444. documents used by the application. Use this if you want to open and close documents,
  445. create and delete files, and otherwise interact with the file system.
  446. - ``@jupyterlab/documentsearch:ISearchProviderRegistry``: An interface for a registry of search
  447. providers for the application. Extensions can register their UI elements with this registry
  448. to provide find/replace support.
  449. - ``@jupyterlab/filebrowser:IFileBrowserFactory``: A factory object that creates file browsers.
  450. Use this if you want to create your own file browser (e.g., for a custom storage backend),
  451. or to interact with other file browsers that have been created by extensions.
  452. - ``@jupyterlab/fileeditor:IEditorTracker``: A widget tracker for file editors.
  453. Use this if you want to be able to iterate over and interact with file editors
  454. created by the application.
  455. - ``@jupyterlab/htmlviewer:IHTMLViewerTracker``: A widget tracker for rendered HTML documents.
  456. Use this if you want to be able to iterate over and interact with HTML documents
  457. viewed by the application.
  458. - ``@jupyterlab/imageviewer:IImageTracker``: A widget tracker for images.
  459. Use this if you want to be able to iterate over and interact with images
  460. viewed by the application.
  461. - ``@jupyterlab/inspector:IInspector``: An interface for adding variable inspectors to widgets.
  462. Use this to add the ability to hook into the variable inspector to your extension.
  463. - ``@jupyterlab/launcher:ILauncher``: An interface to the application activity launcher.
  464. Use this to add your extension activities to the launcher panel.
  465. - ``@jupyterlab/mainmenu:IMainMenu``: An interface to the main menu bar for the application.
  466. Use this if you want to add your own menu items.
  467. - ``@jupyterlab/markdownviewer:IMarkdownViewerTracker``: A widget tracker for markdown
  468. document viewers. Use this if you want to iterate over and interact with rendered markdown documents.
  469. - ``@jupyterlab/notebook:INotebookTools``: An interface to the ``Notebook Tools`` panel in the
  470. application left area. Use this to add your own functionality to the panel.
  471. - ``@jupyterlab/notebook:IContentFactory``: A factory object that creates new notebooks.
  472. Use this if you want to create and host notebooks in your own UI elements.
  473. - ``@jupyterlab/notebook:INotebookTracker``: A widget tracker for notebooks.
  474. Use this if you want to be able to iterate over and interact with notebooks
  475. created by the application.
  476. - ``@jupyterlab/rendermime:IRenderMimeRegistry``: An interface to the rendermime registry
  477. for the application. Use this to create renderers for various mime-types in your extension.
  478. Most extensions will not need to use this, as they can register a
  479. `mime renderer extension <#mime-renderer-extensions>`__.
  480. - ``@jupyterlab/rendermime:ILatexTypesetter``: An interface to the LaTeX typesetter for the
  481. application. Use this if you want to typeset math in your extension.
  482. - ``@jupyterlab/settingeditor:ISettingEditorTracker``: A widget tracker for setting editors.
  483. Use this if you want to be able to iterate over and interact with setting editors
  484. created by the application.
  485. - ``@jupyterlab/settingregistry:ISettingRegistry``: An interface to the JupyterLab settings system.
  486. Use this if you want to store settings for your application.
  487. See `extension settings <#extension-settings>`__ for more information.
  488. - ``@jupyterlab/statedb:IStateDB``: An interface to the JupyterLab state database.
  489. Use this if you want to store data that will persist across page loads.
  490. See `state database <#state-database>`__ for more information.
  491. - ``@jupyterlab/statusbar:IStatusBar``: An interface to the status bar on the application.
  492. Use this if you want to add new status bar items.
  493. - ``@jupyterlab/terminal:ITerminalTracker``: A widget tracker for terminals.
  494. Use this if you want to be able to iterate over and interact with terminals
  495. created by the application.
  496. - ``@jupyterlab/tooltip:ITooltipManager``: An interface to the tooltip manager for the application.
  497. Use this to allow your extension to invoke a tooltip.
  498. - ``@jupyterlab/vdom:IVDOMTracker``: A widget tracker for virtual DOM (VDOM) documents.
  499. Use this to iterate over and interact with VDOM instances created by the application.
  500. Standard Extension Example
  501. ^^^^^^^^^^^^^^^^^^^^^^^^^^
  502. For a concrete example of a standard extension, see :ref:`How to extend the Notebook plugin <extend-notebook-plugin>`.
  503. Notice that the mime renderer extensions use a limited,
  504. simplified interface to JupyterLab's extension system. Modifying the
  505. notebook plugin requires the full, general-purpose interface to the
  506. extension system.
  507. Storing Extension Data
  508. ^^^^^^^^^^^^^^^^^^^^^^
  509. In addition to the file system that is accessed by using the
  510. ``@jupyterlab/services`` package, JupyterLab exposes a plugin settings
  511. system that can be used to provide default setting values and user overrides.
  512. Extension Settings
  513. """"""""""""""""""
  514. An extension can specify user settings using a JSON Schema. The schema
  515. definition should be in a file that resides in the ``schemaDir``
  516. directory that is specified in the ``package.json`` file of the
  517. extension. The actual file name should use is the part that follows the
  518. package name of extension. So for example, the JupyterLab
  519. ``apputils-extension`` package hosts several plugins:
  520. - ``'@jupyterlab/apputils-extension:menu'``
  521. - ``'@jupyterlab/apputils-extension:palette'``
  522. - ``'@jupyterlab/apputils-extension:settings'``
  523. - ``'@jupyterlab/apputils-extension:themes'``
  524. And in the ``package.json`` for ``@jupyterlab/apputils-extension``, the
  525. ``schemaDir`` field is a directory called ``schema``. Since the
  526. ``themes`` plugin requires a JSON schema, its schema file location is:
  527. ``schema/themes.json``. The plugin's name is used to automatically
  528. associate it with its settings file, so this naming convention is
  529. important. Ensure that the schema files are included in the ``"files"``
  530. metadata in ``package.json``.
  531. See the
  532. `fileeditor-extension <https://github.com/jupyterlab/jupyterlab/tree/master/packages/fileeditor-extension>`__
  533. for another example of an extension that uses settings.
  534. Note: You can override default values of the extension settings by
  535. defining new default values in an ``overrides.json`` file in the
  536. application settings directory. So for example, if you would like
  537. to set the dark theme by default instead of the light one, an
  538. ``overrides.json`` file containing the following lines needs to be
  539. added in the application settings directory (by default this is the
  540. ``share/jupyter/lab/settings`` folder).
  541. .. code:: json
  542. {
  543. "@jupyterlab/apputils-extension:themes": {
  544. "theme": "JupyterLab Dark"
  545. }
  546. }
  547. State Database
  548. """"""""""""""
  549. The state database can be accessed by importing ``IStateDB`` from
  550. ``@jupyterlab/statedb`` and adding it to the list of ``requires`` for
  551. a plugin:
  552. .. code:: typescript
  553. const id = 'foo-extension:IFoo';
  554. const IFoo = new Token<IFoo>(id);
  555. interface IFoo {}
  556. class Foo implements IFoo {}
  557. const plugin: JupyterFrontEndPlugin<IFoo> = {
  558. id,
  559. requires: [IStateDB],
  560. provides: IFoo,
  561. activate: (app: JupyterFrontEnd, state: IStateDB): IFoo => {
  562. const foo = new Foo();
  563. const key = `${id}:some-attribute`;
  564. // Load the saved plugin state and apply it once the app
  565. // has finished restoring its former layout.
  566. Promise.all([state.fetch(key), app.restored])
  567. .then(([saved]) => { /* Update `foo` with `saved`. */ });
  568. // Fulfill the plugin contract by returning an `IFoo`.
  569. return foo;
  570. },
  571. autoStart: true
  572. };
  573. Context Menus
  574. ^^^^^^^^^^^^^
  575. JupyterLab has an application-wide context menu available as
  576. ``app.contextMenu``. See the Lumino
  577. `docs <https://jupyterlab.github.io/lumino/widgets/interfaces/contextmenu.iitemoptions.html>`__
  578. for the item creation options. If you wish to preempt the
  579. application context menu, you can use a 'contextmenu' event listener and
  580. call ``event.stopPropagation`` to prevent the application context menu
  581. handler from being called (it is listening in the bubble phase on the
  582. ``document``). At this point you could show your own Lumino
  583. `contextMenu <https://jupyterlab.github.io/lumino/widgets/classes/contextmenu.html>`__,
  584. or simply stop propagation and let the system context menu be shown.
  585. This would look something like the following in a ``Widget`` subclass:
  586. .. code:: javascript
  587. // In `onAfterAttach()`
  588. this.node.addEventListener('contextmenu', this);
  589. // In `handleEvent()`
  590. case 'contextmenu':
  591. event.stopPropagation();
  592. .. |dependencies| image:: dependency-graph.svg
  593. Using React
  594. ^^^^^^^^^^^
  595. We also provide support for using :ref:`react` in your JupyterLab
  596. extensions, as well as in the core codebase.
  597. .. _ext-author-companion-packages:
  598. Companion Packages
  599. ^^^^^^^^^^^^^^^^^^
  600. If your extensions depends on the presence of one or more packages in the
  601. kernel, or on a notebook server extension, you can add metadata to indicate
  602. this to the extension manager by adding metadata to your package.json file.
  603. The full options available are::
  604. "jupyterlab": {
  605. "discovery": {
  606. "kernel": [
  607. {
  608. "kernel_spec": {
  609. "language": "<regexp for matching kernel language>",
  610. "display_name": "<regexp for matching kernel display name>" // optional
  611. },
  612. "base": {
  613. "name": "<the name of the kernel package>"
  614. },
  615. "overrides": { // optional
  616. "<manager name, e.g. 'pip'>": {
  617. "name": "<name of kernel package on pip, if it differs from base name>"
  618. }
  619. },
  620. "managers": [ // list of package managers that have your kernel package
  621. "pip",
  622. "conda"
  623. ]
  624. }
  625. ],
  626. "server": {
  627. "base": {
  628. "name": "<the name of the server extension package>"
  629. },
  630. "overrides": { // optional
  631. "<manager name, e.g. 'pip'>": {
  632. "name": "<name of server extension package on pip, if it differs from base name>"
  633. }
  634. },
  635. "managers": [ // list of package managers that have your server extension package
  636. "pip",
  637. "conda"
  638. ]
  639. }
  640. }
  641. }
  642. A typical setup for e.g. a jupyter-widget based package will then be::
  643. "keywords": [
  644. "jupyterlab-extension",
  645. "jupyter",
  646. "widgets",
  647. "jupyterlab"
  648. ],
  649. "jupyterlab": {
  650. "extension": true,
  651. "discovery": {
  652. "kernel": [
  653. {
  654. "kernel_spec": {
  655. "language": "^python",
  656. },
  657. "base": {
  658. "name": "myipywidgetspackage"
  659. },
  660. "managers": [
  661. "pip",
  662. "conda"
  663. ]
  664. }
  665. ]
  666. }
  667. }
  668. Currently supported package managers are:
  669. - ``pip``
  670. - ``conda``
  671. Shipping Packages
  672. ^^^^^^^^^^^^^^^^^
  673. Most extensions are single JavaScript packages, and can be shipped on npmjs.org.
  674. This makes them discoverable by the JupyterLab extension manager, provided they
  675. have the ``jupyterlab-extension`` keyword in their ``package.json``. If the package also
  676. contains a server extension (Python package), the author has two options.
  677. The server extension and the JupyterLab extension can be shipped in a single package,
  678. or they can be shipped separately.
  679. The JupyterLab extension can be bundled in a package on PyPI and conda-forge so
  680. that it ends up in the user's application directory. Note that the user will still have to run ``jupyter lab build``
  681. (or build when prompted in the UI) in order to use the extension.
  682. The general idea is to pack the Jupyterlab extension using ``npm pack``, and then
  683. use the ``data_files`` logic in ``setup.py`` to ensure the file ends up in the
  684. ``<jupyterlab_application>/share/jupyter/lab/extensions``
  685. directory.
  686. Note that even if the JupyterLab extension is unusable without the
  687. server extension, as long as you use the companion package metadata it is still
  688. useful to publish it to npmjs.org so it is discoverable by the JupyterLab extension manager.
  689. The server extension can be enabled on install by using ``data_files``.
  690. an example of this approach is `jupyterlab-matplotlib <https://github.com/matplotlib/jupyter-matplotlib/tree/ce9cc91e52065d33e57c3265282640f2aa44e08f>`__. The file used to enable the server extension is `here <https://github.com/matplotlib/jupyter-matplotlib/blob/ce9cc91e52065d33e57c3265282640f2aa44e08f/jupyter-matplotlib.json>`__. The logic to ship the JS tarball and server extension
  691. enabler is in `setup.py <https://github.com/matplotlib/jupyter-matplotlib/blob/ce9cc91e52065d33e57c3265282640f2aa44e08f/setup.py>`__. Note that the ``setup.py``
  692. file has additional logic to automatically create the JS tarball as part of the
  693. release process, but this could also be done manually.
  694. Technically, a package that contains only a JupyterLab extension could be created
  695. and published on ``conda-forge``, but it would not be discoverable by the JupyterLab
  696. extension manager.