extension_dev.rst 41 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837
  1. .. _developer_extensions:
  2. Extension Developer Guide
  3. =========================
  4. The JupyterLab application is comprised of a core application object and a set of plugins. JupyterLab plugins provide nearly every function in JupyterLab, including notebooks, document editors and viewers, code consoles, terminals, themes, the file browser, contextual help system, debugger, and settings editor. Plugins even provide more fundamental parts of the application, such as the menu system, status bar, and the underlying communication mechanism with the server.
  5. Getting Started
  6. ---------------
  7. The documentation in this section covers the basic and advanced concepts for writing extensions. If you would rather get hands-on practice or more in-depth reference documentation, we have a number of tutorials, examples, cookiecutters, and generated reference documentation.
  8. Tutorials
  9. ^^^^^^^^^
  10. We provide a set of guides to get started writing extensions for JupyterLab:
  11. - :ref:`extension_tutorial`: An in-depth tutorial to learn how to make a simple JupyterLab extension.
  12. - The `JupyterLab Extension Examples Repository <https://github.com/jupyterlab/extension-examples>`_: A short tutorial series
  13. to learn how to develop extensions for JupyterLab, by example.
  14. - :ref:`developer-extension-points`: A list of the most common JupyterLab extension points.
  15. - Another common pattern for extending JupyterLab document widgets with application plugins is covered in :ref:`documents`.
  16. Cookiecutters
  17. ^^^^^^^^^^^^^
  18. We provide several cookiecutters to create JupyterLab extensions:
  19. - `extension-cookiecutter-ts <https://github.com/jupyterlab/extension-cookiecutter-ts>`_: Create a JupyterLab extension in TypeScript
  20. - `extension-cookiecutter-js <https://github.com/jupyterlab/extension-cookiecutter-js>`_: Create a JupyterLab extension in JavaScript
  21. - `mimerender-cookiecutter-ts <https://github.com/jupyterlab/mimerender-cookiecutter-ts>`_: Create a MIME Renderer JupyterLab extension in TypeScript
  22. - `theme-cookiecutter <https://github.com/jupyterlab/theme-cookiecutter>`_: Create a new theme for JupyterLab
  23. API Reference Documentation
  24. ^^^^^^^^^^^^^^^^^^^^^^^^^^^
  25. If you are looking for generated reference API documentation on the JupyterLab and Lumino API:
  26. - `JupyterLab API Documentation <https://jupyterlab.github.io/jupyterlab/>`_
  27. - `Lumino API Documentation <https://jupyterlab.github.io/lumino/>`_
  28. JupyterLab Extensions
  29. ---------------------
  30. A plugin is the basic unit of extensibility in JupyterLab. JupyterLab supports several types of plugins:
  31. - **application plugins:** Application plugins are the fundamental building block of JupyterLab functionality. Application plugins interact with JupyterLab and other plugins by requiring services provided by other plugins, and optionally providing their own service to the system.
  32. - **mime renderer plugins:** Mime renderer plugins are simplified, restricted ways to extend JupyterLab to render custom mime data in notebooks and files. These plugins are automatically converted to equivalent application plugins by JupyterLab when they are loaded.
  33. - **theme plugins:** Theme plugins provide a way to customize the appearance of JupyterLab by changing themeable values (i.e., CSS variable values) and providing additional fonts and graphics to JupyterLab.
  34. Plugins are distributed in JupyterLab extensions—one extension can contain multiple plugins. An extension can be distributed in several ways:
  35. - A "source" extension is a JavaScript (npm) package that exports one or more plugins. Installing a source extension requires a user to rebuild JupyterLab. This rebuilding step requires Node.js and may take a lot of time and memory, so some users may not be able to install the extension.
  36. - A "prebuilt" extension (new in JupyterLab 3.0) is a bundle of JavaScript code that can be loaded into JupyterLab without rebuilding JupyterLab. In this case, the extension developer uses tools provided by JupyterLab to compile a source extension into a JavaScript bundle that includes the non-JupyterLab JavaScript dependencies, then distributes the resulting bundle in, for example, a Python pip or conda package. Users installing prebuilt extensions do not have to have Node.js installed and can immediately use the extension without a JupyterLab rebuild.
  37. An extension may be distributed as both a source JavaScript package published on NPM and as a prebuilt extension bundle published in a Python package, giving users the choice of how to install it.
  38. Because prebuilt extensions do not require a JupyterLab rebuild, they have a distinct advantage in multiuser systems where JuptyerLab is installed at the system level. On such systems, only the system administrator has permissions to rebuild JupyterLab and install source extensions. Since prebuilt extensions can be installed at the per-user level, the per-environment level, or the system level, each user can have their own separate set of prebuilt extensions that are loaded dynamically in their browser on top of the system-wide JupyterLab.
  39. .. tip::
  40. We recommend developing prebuilt extensions in Python packages for user convenience.
  41. Writing an Extension
  42. --------------------
  43. We encourage extension authors to add the `jupyterlab-extension GitHub topic
  44. <https://github.com/search?utf8=%E2%9C%93&q=topic%3Ajupyterlab-extension&type=Repositories>`__
  45. to any GitHub extension repository.
  46. Plugin metadata
  47. ^^^^^^^^^^^^^^^
  48. A typical plugin is specified by the following metadata. The ``id`` and ``activate`` fields are required and the other fields may be omitted. For more information about the ``requires``, ``optional``, or ``provides`` fields, see :ref:`services`.
  49. .. code::
  50. const plugin: JupyterFrontEndPlugin<MyToken> = {
  51. id: 'MyExtension:my_plugin',
  52. autoStart: true,
  53. requires: [ILabShell, ITranslator],
  54. optional: [ICommandPalette],
  55. provides: MyToken,
  56. activate: activateFunction
  57. };
  58. - ``id`` is a required unique string. The convention is to use the NPM extension package name and a string identifying the plugin inside the extension, separated by a colon.
  59. - ``autostart`` indicates whether your plugin should be activated at application startup. Typically this should be ``true``. If it is ``false`` or omitted, your plugin will be instantiated when any other plugin requests the token your plugin is providing.
  60. - ``requires`` and ``optional`` are lists of tokens. The corresponding objects in the system will be provided to the ``activate`` function when the plugin is instantiated. Tokens in the ``requires`` list will be required for your plugin to work, and your plugin activation will error if a ``required`` token is not registered with JupyterLab. Tokens in the ``optional`` list may or may not be registered, but will be provided to your plugin if they exist.
  61. - ``provides`` is the token associated with the service your plugin is providing to the system. A token can only be registered with the system once. If your plugin does not provide a service to the system, omit this field and do not return a value from your ``activate`` function.
  62. - ``activate`` is the function called when your plugin is activated. The arguments are, in order, the Application object, the services corresponding to the ``requires`` tokens, then the services corresponding to the ``optional`` tokens (or ``null`` if that particular ``optional`` token is not registered in the system). The return value of the ``activate`` function (or resolved return value if a promise is returned) will be stored in the system as the service associated with the ``provides`` token.
  63. package.json metadata
  64. ^^^^^^^^^^^^^^^^^^^^^
  65. Custom webpack config
  66. """""""""""""""""""""
  67. Disabling other extensions
  68. """"""""""""""""""""""""""
  69. Federation data
  70. """""""""""""""
  71. Sharing configuration
  72. """""""""""""""""""""
  73. Companion packages
  74. """"""""""""""""""
  75. Packaging extensions
  76. ^^^^^^^^^^^^^^^^^^^^
  77. Prebuilt Extensions
  78. ^^^^^^^^^^^^^^^^^^^
  79. ``install.json``
  80. How prebuilt extensions work
  81. """""""""""""""""""""""""""""
  82. Steps for building
  83. """"""""""""""""""
  84. Directory walkthrough
  85. """""""""""""""""""""
  86. Migrating extensions
  87. ^^^^^^^^^^^^^^^^^^^^
  88. Plugins
  89. -------
  90. Mime renderers
  91. ^^^^^^^^^^^^^^
  92. Theme plugins
  93. ^^^^^^^^^^^^^
  94. .. _services:
  95. Plugins Interacting with Each Other
  96. -----------------------------------
  97. One of the foundational features of the JupyterLab plugin system is that plugins can interact with other plugins by providing a service to the system and requiring services provided by other plugins. A service can be any JavaScript value, and typically is a JavaScript object with methods and data attributes. For example, the plugin that supplies the JupyterLab main menu provides a service object to the system with methods and attributes other plugins can use to interact with the main menu.
  98. In the following discussion, the plugin that is providing a service to the system is the *provider* plugin, and the plugin that is requiring and using the service is the *consumer* plugin.
  99. A service provided by a plugin is identified by a *token*, i.e., a concrete instance of the Lumino Token class. The provider plugin lists the token in its plugin metadata ``provides`` field, and returns the associated service from its ``activate`` function. Consumer plugins import the token (for example, from the provider plugin's extension JavaScript package) and list the token in their plugin metadata ``requires`` or ``optional`` fields. When JupyterLab instantiates the consumer plugin, it will pass in the service associated with the token. JupyterLab orders plugin activation to ensure that a provider of a service is activated before its consumers.
  100. A token defined in TypeScript can also define a TypeScript interface for the service associated with the token. If the provider or consumer uses TypeScript, the service will be type-checked against this interface.
  101. .. note::
  102. JupyterLab uses tokens to identify services (instead of strings, for example) to prevent conflicts between identifiers and to enable type checking when using TypeScript.
  103. Publishing Tokens
  104. ^^^^^^^^^^^^^^^^^
  105. Since consumers will need to import a token used by a provider, the token should be exported in a published JavaScript package. A pattern in core JupyterLab is to create and export tokens from a self-contained ``tokens`` JavaScript module in a package. This enables consumers to import a token directly from the package's ``tokens`` module (e.g., ``import { MyToken } from 'provider/tokens';``), thus enabling a tree-shaking bundling optimization to bundle only the tokens and not other code from the package.
  106. Another pattern in core JupyterLab is to create and export a token from a third package that both the provider and consumer extensions import, rather than defining the token in the provider's package. This enables a user to swap out the provider extension for a different extension that provides the same token with an alternative service implementation. For example, the core JupyterLab ``filebrowser`` package exports a token representing the file browser service (enabling interactions with the file browser). The ``filebrowser-extension`` package contains a plugin that implements the file browser in JupyterLab and provides the file browser service to JupyterLab (identified with the token imported from the ``filebrowser`` package). Extensions in JupyterLab that want to interact with the filebrowser thus do not need to have a JavaScript dependency on the ``filebrowser-extension`` package, but only need to import the token from the ``filebrowser`` package. This pattern enables users to seamlessly change the file browser in JupyterLab by writing their own extension that imports the same token from the ``filebrowser`` package and provides it to the system with their own alternative file browser service.
  107. Deduplication of Dependencies
  108. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  109. ..
  110. TODO: Maybe put this part in the place where we talk about the sharedPackages metadata? It's an important implementation detail in JupyterLab that has consequences for extension metadata.
  111. One important concern and challenge in the JupyterLab extension system is deduplicating dependencies of extensions instead of having extensions use their own bundled copies of dependencies. For example, the Lumino widgets system on which JupyterLab relies for communication across the application requires all packages use the same copy of the ``@lumino/widgets`` package. Tokens identifying plugin services also need to be shared across the providers and consumers of the services, so dependencies that export tokens need to be deduplicated.
  112. Deduplication in JupyterLab happens in two ways. For source extensions, JupyterLab deduplicates dependencies when rebuilds itself to include the extension during the extension installation process. Deduplication is one of the main reasons JupyterLab needs to be rebuilt when installing source extensions. For prebuilt extensions, JupyterLab relies on the new Webpack module federation system to share dependencies across different bundles (including the core JupyterLab application bundle).
  113. To ensure that a consumer gets the same token instance as the provider provided to the sytem, any required tokens that are imported by a consumer extension should list the exporting extension as a singleton package in their ``jupyterlab.sharedPackages`` config. Required token packages should be listed as ``bundled: false`` - this will generate a JavaScript error if the package (and thus the token) is not present in the system at runtime. Optional token packages should be listed as singletons that are bundled (otherwise, if they are not present in the system, it will cause a js error when you try to import them).
  114. Advanced Plugins
  115. ----------------
  116. Plugin Settings
  117. ^^^^^^^^^^^^^^^
  118. In addition to the file system that is accessed by using the
  119. ``@jupyterlab/services`` package, JupyterLab exposes a plugin settings
  120. system that can be used to provide default setting values and user overrides.
  121. An extension can specify user settings using a JSON Schema. The schema
  122. definition should be in a file that resides in the ``schemaDir``
  123. directory that is specified in the ``package.json`` file of the
  124. extension. The actual file name should use is the part that follows the
  125. package name of extension. So for example, the JupyterLab
  126. ``apputils-extension`` package hosts several plugins:
  127. - ``'@jupyterlab/apputils-extension:menu'``
  128. - ``'@jupyterlab/apputils-extension:palette'``
  129. - ``'@jupyterlab/apputils-extension:settings'``
  130. - ``'@jupyterlab/apputils-extension:themes'``
  131. And in the ``package.json`` for ``@jupyterlab/apputils-extension``, the
  132. ``schemaDir`` field is a directory called ``schema``. Since the
  133. ``themes`` plugin requires a JSON schema, its schema file location is:
  134. ``schema/themes.json``. The plugin's name is used to automatically
  135. associate it with its settings file, so this naming convention is
  136. important. Ensure that the schema files are included in the ``"files"``
  137. metadata in ``package.json``.
  138. See the
  139. `fileeditor-extension <https://github.com/jupyterlab/jupyterlab/tree/master/packages/fileeditor-extension>`__
  140. for another example of an extension that uses settings.
  141. .. _setting_overrides:
  142. System Overrides
  143. """"""""""""""""
  144. You can override default values of the extension settings by
  145. defining new default values in an ``overrides.json`` file in the
  146. application settings directory. For example, if you would like
  147. to set the dark theme by default instead of the light one, an
  148. ``overrides.json`` file containing the following lines needs to be
  149. added in the application settings directory (by default this is the
  150. ``share/jupyter/lab/settings`` folder).
  151. .. code:: json
  152. {
  153. "@jupyterlab/apputils-extension:themes": {
  154. "theme": "JupyterLab Dark"
  155. }
  156. }
  157. State Database
  158. ^^^^^^^^^^^^^^
  159. The state database can be accessed by importing ``IStateDB`` from
  160. ``@jupyterlab/statedb`` and adding it to the list of ``requires`` for
  161. a plugin:
  162. .. code:: typescript
  163. const id = 'foo-extension:IFoo';
  164. const IFoo = new Token<IFoo>(id);
  165. interface IFoo {}
  166. class Foo implements IFoo {}
  167. const plugin: JupyterFrontEndPlugin<IFoo> = {
  168. id,
  169. autoStart: true,
  170. requires: [IStateDB],
  171. provides: IFoo,
  172. activate: (app: JupyterFrontEnd, state: IStateDB): IFoo => {
  173. const foo = new Foo();
  174. const key = `${id}:some-attribute`;
  175. // Load the saved plugin state and apply it once the app
  176. // has finished restoring its former layout.
  177. Promise.all([state.fetch(key), app.restored])
  178. .then(([saved]) => { /* Update `foo` with `saved`. */ });
  179. // Fulfill the plugin contract by returning an `IFoo`.
  180. return foo;
  181. }
  182. };
  183. Custom webpack config for prebuilt extensions
  184. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  185. .. warning::
  186. This feature is *experimental*, as it makes it possible to override the base config used by the
  187. JupyterLab Federated Extension System.
  188. It also exposes the internals of the federated extension build system (namely ``webpack``) to extension authors, which was until now
  189. kept as an implementation detail.
  190. The JupyterLab Federated Extension System uses ``webpack`` to build federated extensions, relying on the
  191. `Module Federation System <https://webpack.js.org/concepts/module-federation/>`_ added in webpack 5.
  192. To specify a custom webpack config to the federated extension build system, extension authors can add the ``webpackConfig`` subkey to the
  193. ``package.json`` of their extension::
  194. "jupyterlab": {
  195. "webpackConfig": "webpack.config.js"
  196. }
  197. The webpack config file can be placed in a different location with a custom name::
  198. "jupyterlab": {
  199. "webpackConfig": "./config/test-config.js"
  200. }
  201. Here is an example of a custom config that enables the async WebAssembly and top-level ``await`` experiments:
  202. .. code-block:: javascript
  203. module.exports = {
  204. experiments: {
  205. topLevelAwait: true,
  206. asyncWebAssembly: true,
  207. }
  208. };
  209. This custom config will be merged with the `default config <https://github.com/jupyterlab/jupyterlab/blob/master/builder/src/webpack.config.base.ts>`_
  210. when building the federated extension with ``jlpm run build``.
  211. Companion Packages
  212. ^^^^^^^^^^^^^^^^^^
  213. If your extensions depends on the presence of one or more packages in the
  214. kernel, or on a notebook server extension, you can add metadata to indicate
  215. this to the extension manager by adding metadata to your package.json file.
  216. The full options available are::
  217. "jupyterlab": {
  218. "discovery": {
  219. "kernel": [
  220. {
  221. "kernel_spec": {
  222. "language": "<regexp for matching kernel language>",
  223. "display_name": "<regexp for matching kernel display name>" // optional
  224. },
  225. "base": {
  226. "name": "<the name of the kernel package>"
  227. },
  228. "overrides": { // optional
  229. "<manager name, e.g. 'pip'>": {
  230. "name": "<name of kernel package on pip, if it differs from base name>"
  231. }
  232. },
  233. "managers": [ // list of package managers that have your kernel package
  234. "pip",
  235. "conda"
  236. ]
  237. }
  238. ],
  239. "server": {
  240. "base": {
  241. "name": "<the name of the server extension package>"
  242. },
  243. "overrides": { // optional
  244. "<manager name, e.g. 'pip'>": {
  245. "name": "<name of server extension package on pip, if it differs from base name>"
  246. }
  247. },
  248. "managers": [ // list of package managers that have your server extension package
  249. "pip",
  250. "conda"
  251. ]
  252. }
  253. }
  254. }
  255. A typical setup for e.g. a jupyter-widget based package will then be::
  256. "keywords": [
  257. "jupyterlab-extension",
  258. "jupyter",
  259. "widgets",
  260. "jupyterlab"
  261. ],
  262. "jupyterlab": {
  263. "extension": true,
  264. "discovery": {
  265. "kernel": [
  266. {
  267. "kernel_spec": {
  268. "language": "^python",
  269. },
  270. "base": {
  271. "name": "myipywidgetspackage"
  272. },
  273. "managers": [
  274. "pip",
  275. "conda"
  276. ]
  277. }
  278. ]
  279. }
  280. }
  281. Currently supported package managers are:
  282. - ``pip``
  283. - ``conda``
  284. .. _ext-author-companion-packages:
  285. Development workflow
  286. --------------------
  287. We encourage extension authors to add the `jupyterlab-extension GitHub topic
  288. <https://github.com/search?utf8=%E2%9C%93&q=topic%3Ajupyterlab-extension&type=Repositories>`__
  289. to any GitHub extension repository.
  290. Older Docs
  291. ==========
  292. Writing extensions
  293. ------------------
  294. Starting in JupyterLab 3.0, extensions are distributed as ``pip`` or
  295. ``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.
  296. Implementation
  297. --------------
  298. - We provide a ``jupyter labextension build`` script that is used to build federated bundles
  299. - The command produces a set of static assets that are shipped along with a package (notionally on ``pip``/``conda``)
  300. - It is a Python cli so that it can use the dependency metadata from the active JupyterLab
  301. - The assets include a module federation ``remoteEntry.*.js``, generated bundles, and some other files that we use
  302. - ``package.json`` is the original ``package.json`` file that we use to gather metadata about the package, with some included build metadata
  303. - we use the previously existing ``@jupyterlab/builder -> build`` to generate the ``imports.css``, ``schemas`` and ``themes`` file structure
  304. - We provide a schema for the valid ``jupyterlab`` metadata for an extension's ``package.json`` describing the available options
  305. - 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
  306. - 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
  307. - 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
  308. - 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``
  309. - 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
  310. - Extensions can provide ``disabled`` metadata that can be used to replace an entire extension or individual plugins
  311. - ``page_config`` and ``overrides`` are also handled with traits so that admins can provide defaults and users can provide overrides
  312. - We provide a script to update extensions: ``python -m jupyterlab.upgrade_extension``
  313. - We update the ``extension-manager`` to target metadata on ``pypi``/``conda`` and consume those packages.
  314. Tools
  315. -----
  316. - ``jupyter labexension build`` python command line tool
  317. - ``jupyter labextension develop`` python command line tool
  318. - ``python -m jupyterlab.upgrade_extension`` python command line tool
  319. - ``cookiecutter`` for extension authors
  320. Workflow for extension authors
  321. ------------------------------
  322. - Use the ``cookiecutter`` to create the extension
  323. - Run ``jupyter labextension develop`` to build and symlink the files
  324. - Run ``jlpm run watch`` to start watching
  325. - Run ``jupyter lab``
  326. - Make changes to source
  327. - Refresh the application page
  328. - When finished, publish the package to ``pypi``/``conda``
  329. Plugins
  330. -------
  331. A plugin adds a core functionality to the application:
  332. - A plugin can require other plugins for operation.
  333. - A plugin is activated when it is needed by other plugins, or when
  334. explicitly activated.
  335. - Plugins require and provide ``Token`` objects, which are used to
  336. provide a typed value to the plugin's ``activate()`` method.
  337. - The module providing plugin(s) must meet the
  338. `JupyterLab.IPluginModule <https://jupyterlab.github.io/jupyterlab/interfaces/_application_src_index_.jupyterlab.ipluginmodule.html>`__
  339. interface, by exporting a plugin object or array of plugin objects as
  340. the default export.
  341. The default plugins in the JupyterLab application include:
  342. - `Terminal <https://github.com/jupyterlab/jupyterlab/blob/master/packages/terminal-extension/src/index.ts>`__
  343. - Adds the ability to create command prompt terminals.
  344. - `Shortcuts <https://github.com/jupyterlab/jupyterlab/blob/master/packages/shortcuts-extension/src/index.ts>`__
  345. - Sets the default set of shortcuts for the application.
  346. - `Images <https://github.com/jupyterlab/jupyterlab/blob/master/packages/imageviewer-extension/src/index.ts>`__
  347. - Adds a widget factory for displaying image files.
  348. - `Help <https://github.com/jupyterlab/jupyterlab/blob/master/packages/help-extension/src/index.tsx>`__
  349. - Adds a side bar widget for displaying external documentation.
  350. - `File
  351. Browser <https://github.com/jupyterlab/jupyterlab/blob/master/packages/filebrowser-extension/src/index.ts>`__
  352. - Creates the file browser and the document manager and the file
  353. browser to the side bar.
  354. - `Editor <https://github.com/jupyterlab/jupyterlab/blob/master/packages/fileeditor-extension/src/index.ts>`__
  355. - Add a widget factory for displaying editable source files.
  356. - `Console <https://github.com/jupyterlab/jupyterlab/blob/master/packages/console-extension/src/index.ts>`__
  357. - Adds the ability to launch Jupyter Console instances for
  358. interactive kernel console sessions.
  359. Here is a dependency graph for the core JupyterLab components: |dependencies|
  360. .. danger::
  361. Installing an extension allows for arbitrary code execution on the
  362. server, kernel, and in the client's browser. You should therefore
  363. take steps to protect against malicious changes to your extension's
  364. code. This includes ensuring strong authentication for your PyPI
  365. account.
  366. Application Object
  367. ------------------
  368. A Jupyter front-end application object is given to each plugin in its
  369. ``activate()`` function. The application object has:
  370. - ``commands`` - an extensible registry used to add and execute commands in the application.
  371. - ``commandLinker`` - used to connect DOM nodes with the command registry so that clicking on them executes a command.
  372. - ``docRegistry`` - an extensible registry containing the document types that the application is able to read and render.
  373. - ``restored`` - a promise that is resolved when the application has finished loading.
  374. - ``serviceManager`` - low-level manager for talking to the Jupyter REST API.
  375. - ``shell`` - a generic Jupyter front-end shell instance, which holds the user interface for the application.
  376. Lumino
  377. ------
  378. The Lumino library is used as the underlying architecture of
  379. JupyterLab and provides many of the low level primitives and widget
  380. structure used in the application. Lumino provides a rich set of
  381. widgets for developing desktop-like applications in the browser, as well
  382. as patterns and objects for writing clean, well-abstracted code. The
  383. widgets in the application are primarily **Lumino widgets**, and
  384. Lumino concepts, like message passing and signals, are used
  385. throughout. **Lumino messages** are a *many-to-one* interaction that
  386. enables information like resize events to flow through the widget
  387. hierarchy in the application. **Lumino signals** are a *one-to-many*
  388. interaction that enable listeners to react to changes in an observed
  389. object.
  390. Extension Authoring
  391. -------------------
  392. An Extension is a valid `npm
  393. package <https://docs.npmjs.com/getting-started/what-is-npm>`__ that
  394. meets the following criteria:
  395. - Exports one or more JupyterLab plugins as the default export in its
  396. main file.
  397. - Has a ``jupyterlab`` key in its ``package.json`` which has
  398. ``"extension"`` metadata. The value can be ``true`` to use the main
  399. module of the package, or a string path to a specific module (e.g.
  400. ``"lib/foo"``). Example::
  401. "jupyterlab": {
  402. "extension": true
  403. }
  404. - It is also recommended to include the keyword ``jupyterlab-extension``
  405. in the ``package.json``, to aid with discovery (e.g. by the extension
  406. manager). Example::
  407. "keywords": [
  408. "jupyter",
  409. "jupyterlab",
  410. "jupyterlab-extension"
  411. ],
  412. While authoring the extension, you can use the command:
  413. .. code:: bash
  414. npm install # install npm package dependencies
  415. npm run build # optional build step if using TypeScript, babel, etc.
  416. jupyter labextension install # install the current directory as an extension
  417. This causes the builder to re-install the source folder before building
  418. the application files. You can re-build at any time using
  419. ``jupyter lab build`` and it will reinstall these packages.
  420. You can also link other local ``npm`` packages that you are working on
  421. simultaneously using ``jupyter labextension link``; they will be re-installed
  422. but not considered as extensions. Local extensions and linked packages are
  423. included in ``jupyter labextension list``.
  424. When using local extensions and linked packages, you can run the command
  425. ::
  426. jupyter lab --watch
  427. This will cause the application to incrementally rebuild when one of the
  428. linked packages changes. Note that only compiled JavaScript files (and
  429. the CSS files) are watched by the WebPack process. This means that if
  430. your extension is in TypeScript you'll have to run a ``jlpm run build``
  431. before the changes will be reflected in JupyterLab. To avoid this step
  432. you can also watch the TypeScript sources in your extension which is
  433. usually assigned to the ``tsc -w`` shortcut. If WebPack doesn't seem to
  434. detect the changes, this can be related to `the number of available watches <https://github.com/webpack/docs/wiki/troubleshooting#not-enough-watchers>`__.
  435. Note that the application is built against **released** versions of the
  436. core JupyterLab extensions. If your extension depends on JupyterLab
  437. packages, it should be compatible with the dependencies in the
  438. ``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
  439. specific patch release of one of the core JupyterLab packages you can
  440. temporarily pin that requirement to a specific version in your own
  441. dependencies.
  442. 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
  443. ::
  444. jlpm run add:sibling <path-or-url>
  445. in the JupyterLab root directory, where ``<path-or-url>`` refers either
  446. to an extension ``npm`` package on the local file system, or a URL to a git
  447. repository for an extension ``npm`` package. This operation may be
  448. subsequently reversed by running
  449. ::
  450. jlpm run remove:package <extension-dir-name>
  451. This will remove the package metadata from the source tree and delete
  452. all of the package files.
  453. The package should export EMCAScript 6 compatible JavaScript. It can
  454. import CSS using the syntax ``require('foo.css')``. The CSS files can
  455. also import CSS from other packages using the syntax
  456. ``@import url('~foo/index.css')``, where ``foo`` is the name of the
  457. package.
  458. The following file types are also supported (both in JavaScript and
  459. CSS): ``json``, ``html``, ``jpg``, ``png``, ``gif``, ``svg``,
  460. ``js.map``, ``woff2``, ``ttf``, ``eot``.
  461. If your package uses any other file type it must be converted to one of
  462. the above types or `include a loader in the import statement <https://webpack.js.org/concepts/loaders/#inline>`__.
  463. If you include a loader, the loader must be importable at build time, so if
  464. it is not already installed by JupyterLab, you must add it as a dependency
  465. of your extension.
  466. If your JavaScript is written in any other dialect than
  467. EMCAScript 6 (2015) it should be converted using an appropriate tool.
  468. You can use Webpack to pre-build your extension to use any of it's features
  469. not enabled in our build configuration. To build a compatible package set
  470. ``output.libraryTarget`` to ``"commonjs2"`` in your Webpack configuration.
  471. (see `this <https://github.com/saulshanabrook/jupyterlab-webpack>`__ example repo).
  472. Another option to try out your extension with a local version of JupyterLab is to add it to the
  473. list of locally installed packages and to have JupyterLab register your extension when it starts up.
  474. You can do this by adding your extension to the ``jupyterlab.externalExtensions`` key
  475. in the ``dev_mode/package.json`` file. It should be a mapping
  476. of extension name to version, just like in ``dependencies``. Then run ``jlpm run integrity``
  477. and these extensions should be added automatically to the ``dependencies`` and pulled in.
  478. When you then run ``jlpm run build && jupyter lab --dev`` or ``jupyter lab --dev --watch`` this extension
  479. will be loaded by default. For example, this is how you can add the Jupyter Widgets
  480. extensions:
  481. ::
  482. "externalExtensions": {
  483. "@jupyter-widgets/jupyterlab-manager": "2.0.0"
  484. },
  485. If you publish your extension on ``npm.org``, users will be able to install
  486. it as simply ``jupyter labextension install <foo>``, where ``<foo>`` is
  487. the name of the published ``npm`` package. You can alternatively provide a
  488. script that runs ``jupyter labextension install`` against a local folder
  489. path on the user's machine or a provided tarball. Any valid
  490. ``npm install`` specifier can be used in
  491. ``jupyter labextension install`` (e.g. ``foo@latest``, ``bar@3.0.0.0``,
  492. ``path/to/folder``, and ``path/to/tar.gz``).
  493. Testing your extension
  494. ^^^^^^^^^^^^^^^^^^^^^^
  495. There are a number of helper functions in ``testutils`` in this repo (which
  496. is a public ``npm`` package called ``@jupyterlab/testutils``) that can be used when
  497. writing tests for an extension. See ``tests/test-application`` for an example
  498. of the infrastructure needed to run tests. There is a ``karma`` config file
  499. that points to the parent directory's ``karma`` config, and a test runner,
  500. ``run-test.py`` that starts a Jupyter server.
  501. If you are using `jest <https://jestjs.io/>`__ to test your extension, you will
  502. need to transpile the jupyterlab packages to ``commonjs`` as they are using ES6 modules
  503. that ``node`` does not support.
  504. To transpile jupyterlab packages, you need to install the following package:
  505. ::
  506. jlpm add --dev jest@^24 @types/jest@^24 ts-jest@^24 @babel/core@^7 @babel/preset-env@^7
  507. Then in `jest.config.js`, you will specify to use babel for js files and ignore
  508. all node modules except the jupyterlab ones:
  509. ::
  510. module.exports = {
  511. preset: 'ts-jest/presets/js-with-babel',
  512. moduleFileExtensions: ['ts', 'tsx', 'js', 'jsx', 'json', 'node'],
  513. transformIgnorePatterns: ['/node_modules/(?!(@jupyterlab/.*)/)'],
  514. globals: {
  515. 'ts-jest': {
  516. tsConfig: 'tsconfig.json'
  517. }
  518. },
  519. ... // Other options useful for your extension
  520. };
  521. Finally, you will need to configure babel with a ``babel.config.js`` file containing:
  522. ::
  523. module.exports = {
  524. presets: [
  525. [
  526. '@babel/preset-env',
  527. {
  528. targets: {
  529. node: 'current'
  530. }
  531. }
  532. ]
  533. ]
  534. };
  535. .. _rendermime:
  536. Mime Renderer Extensions
  537. ------------------------
  538. Mime Renderer extensions are a convenience for creating an extension
  539. that can render mime data and potentially render files of a given type.
  540. We provide a cookiecutter for mime renderer extensions in TypeScript
  541. `here <https://github.com/jupyterlab/mimerender-cookiecutter-ts>`__.
  542. Mime renderer extensions are more declarative than standard extensions.
  543. The extension is treated the same from the command line perspective
  544. (``jupyter labextension install`` ), but it does not directly create
  545. JupyterLab plugins. Instead it exports an interface given in the
  546. `rendermime-interfaces <https://jupyterlab.github.io/jupyterlab/interfaces/_rendermime_interfaces_src_index_.irendermime.iextension.html>`__
  547. package.
  548. The JupyterLab repo has an example mime renderer extension for
  549. `pdf <https://github.com/jupyterlab/jupyterlab/tree/master/packages/pdf-extension>`__
  550. files. It provides a mime renderer for pdf data and registers itself as
  551. a document renderer for pdf file types.
  552. The JupyterLab organization also has a mime renderer extension tutorial
  553. which adds mp4 video rendering to the application
  554. `here <https://github.com/jupyterlab/jupyterlab-mp4>`__.
  555. The ``rendermime-interfaces`` package is intended to be the only
  556. JupyterLab package needed to create a mime renderer extension (using the
  557. interfaces in TypeScript or as a form of documentation if using plain
  558. JavaScript).
  559. The only other difference from a standard extension is that has a
  560. ``jupyterlab`` key in its ``package.json`` with ``"mimeExtension"``
  561. metadata. The value can be ``true`` to use the main module of the
  562. package, or a string path to a specific module (e.g. ``"lib/foo"``).
  563. The mime renderer can update its data by calling ``.setData()`` on the
  564. model it is given to render. This can be used for example to add a
  565. ``png`` representation of a dynamic figure, which will be picked up by a
  566. notebook model and added to the notebook document. When using
  567. ``IDocumentWidgetFactoryOptions``, you can update the document model by
  568. calling ``.setData()`` with updated data for the rendered MIME type. The
  569. document can then be saved by the user in the usual manner.
  570. Themes
  571. ------
  572. A theme is a JupyterLab extension that uses a ``ThemeManager`` and can
  573. be loaded and unloaded dynamically. The package must include all static
  574. assets that are referenced by ``url()`` in its CSS files. Local URLs can
  575. be used to reference files relative to the location of the referring sibling CSS files. For example ``url('images/foo.png')`` or
  576. ``url('../foo/bar.css')``\ can be used to refer local files in the
  577. theme. Absolute URLs (starting with a ``/``) or external URLs (e.g.
  578. ``https:``) can be used to refer to external assets. The path to the
  579. theme asset entry point is specified ``package.json`` under the ``"jupyterlab"``
  580. key as ``"themePath"``. See the `JupyterLab Light
  581. Theme <https://github.com/jupyterlab/jupyterlab/tree/master/packages/theme-light-extension>`__
  582. for an example. Ensure that the theme files are included in the
  583. ``"files"`` metadata in ``package.json``. Note that if you want to use SCSS, SASS, or LESS files,
  584. you must compile them to CSS and point JupyterLab to the CSS files.
  585. The theme extension is installed in the same way as a regular extension (see
  586. `extension authoring <#extension-authoring>`__).
  587. It is also possible to create a new theme using the
  588. `TypeScript theme cookiecutter <https://github.com/jupyterlab/theme-cookiecutter>`__.
  589. Shipping Packages
  590. -----------------
  591. Most extensions are single JavaScript packages, and can be shipped on npmjs.org.
  592. This makes them discoverable by the JupyterLab extension manager, provided they
  593. have the ``jupyterlab-extension`` keyword in their ``package.json``. If the package also
  594. contains a server extension (Python package), the author has two options.
  595. The server extension and the JupyterLab extension can be shipped in a single package,
  596. or they can be shipped separately.
  597. The JupyterLab extension can be bundled in a package on PyPI and conda-forge so
  598. that it ends up in the user's application directory. Note that the user will still have to run ``jupyter lab build``
  599. (or build when prompted in the UI) in order to use the extension.
  600. The general idea is to pack the Jupyterlab extension using ``npm pack``, and then
  601. use the ``data_files`` logic in ``setup.py`` to ensure the file ends up in the
  602. ``<jupyterlab_application>/share/jupyter/lab/extensions``
  603. directory.
  604. Note that even if the JupyterLab extension is unusable without the
  605. server extension, as long as you use the companion package metadata it is still
  606. useful to publish it to npmjs.org so it is discoverable by the JupyterLab extension manager.
  607. The server extension can be enabled on install by using ``data_files``.
  608. 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
  609. enabler is in `setup.py <https://github.com/matplotlib/jupyter-matplotlib/blob/ce9cc91e52065d33e57c3265282640f2aa44e08f/setup.py>`__. Note that the ``setup.py``
  610. file has additional logic to automatically create the JS tarball as part of the
  611. release process, but this could also be done manually.
  612. Technically, a package that contains only a JupyterLab extension could be created
  613. and published on ``conda-forge``, but it would not be discoverable by the JupyterLab
  614. extension manager.
  615. .. |dependencies| image:: images/dependency-graph.svg