extension_tutorial.rst 36 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998
  1. .. _extension_tutorial:
  2. Extension Tutorial
  3. ==================
  4. JupyterLab extensions add features to the user experience. This page
  5. describes how to create one type of extension, an *application plugin*,
  6. that:
  7. - Adds a "Random `Astronomy Picture <https://apod.nasa.gov/apod/astropix.html>`__" command to the
  8. *command palette* sidebar
  9. - Fetches the image and metadata when activated
  10. - Shows the image and metadata in a tab panel
  11. By working through this tutorial, you'll learn:
  12. - How to set up an extension development environment from scratch on a
  13. Linux or OSX machine. (You'll need to modify the commands slightly if you are on Windows.)
  14. - How to start an extension project from
  15. `jupyterlab/extension-cookiecutter-ts <https://github.com/jupyterlab/extension-cookiecutter-ts>`__
  16. - How to iteratively code, build, and load your extension in JupyterLab
  17. - How to version control your work with git
  18. - How to release your extension for others to enjoy
  19. .. figure:: images/extension_tutorial_complete.png
  20. :align: center
  21. :class: jp-screenshot
  22. :alt: The completed extension, showing the Astronomy Picture of the Day for 24 Jul 2015.
  23. The completed extension, showing the `Astronomy Picture of the Day for 24 Jul 2015 <https://apod.nasa.gov/apod/ap150724.html>`__.
  24. Sound like fun? Excellent. Here we go!
  25. Set up a development environment
  26. --------------------------------
  27. Install conda using miniconda
  28. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  29. Start by installing miniconda, following
  30. `Conda's installation documentation <https://docs.conda.io/projects/conda/en/latest/user-guide/install/index.html>`__.
  31. .. _install-nodejs-jupyterlab-etc-in-a-conda-environment:
  32. Install NodeJS, JupyterLab, etc. in a conda environment
  33. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  34. Next create a conda environment that includes:
  35. 1. the latest release of JupyterLab
  36. 2. `cookiecutter <https://github.com/audreyr/cookiecutter>`__, the tool
  37. you'll use to bootstrap your extension project structure (this is a Python tool
  38. which we'll install using conda below).
  39. 3. `NodeJS <https://nodejs.org>`__, the JavaScript runtime you'll use to
  40. compile the web assets (e.g., TypeScript, CSS) for your extension
  41. 4. `git <https://git-scm.com>`__, a version control system you'll use to
  42. take snapshots of your work as you progress through this tutorial
  43. It's a best practice to leave the root conda environment (i.e., the environment created
  44. by the miniconda installer) untouched and install your project-specific
  45. dependencies in a named conda environment. Run this command to create a
  46. new environment named ``jupyterlab-ext``.
  47. .. code:: bash
  48. conda create -n jupyterlab-ext --override-channels --strict-channel-priority -c conda-forge -c nodefaults jupyterlab=3 cookiecutter nodejs jupyter-packaging git
  49. Now activate the new environment so that all further commands you run
  50. work out of that environment.
  51. .. code:: bash
  52. conda activate jupyterlab-ext
  53. Note: You'll need to run the command above in each new terminal you open
  54. before you can work with the tools you installed in the
  55. ``jupyterlab-ext`` environment.
  56. Create a repository
  57. -------------------
  58. Create a new repository for your extension (see, for example, the
  59. `GitHub instructions <https://help.github.com/articles/create-a-repo/>`__. This is an
  60. optional step, but highly recommended if you want to share your
  61. extension.
  62. Create an extension project
  63. ---------------------------
  64. Initialize the project from a cookiecutter
  65. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  66. Next use cookiecutter to create a new project for your extension.
  67. This will create a new folder for your extension in your current directory.
  68. .. code:: bash
  69. cookiecutter https://github.com/jupyterlab/extension-cookiecutter-ts
  70. When prompted, enter values like the following for all of the cookiecutter
  71. prompts (``apod`` stands for Astronomy Picture of the Day, the NASA service we
  72. are using to fetch pictures).
  73. ::
  74. author_name []: Your Name
  75. author_email []: your@name.org
  76. python_name [myextension]: jupyterlab_apod
  77. labextension_name [myextension]: jupyterlab_apod
  78. project_short_description [A JupyterLab extension.]: Show a random NASA Astronomy Picture of the Day in a JupyterLab panel
  79. has_server_extension [n]: n
  80. has_binder [n]: y
  81. repository [https://github.com/my_name/myextension]: https://github.com/my_name/jupyterlab_apod
  82. Note: if not using a repository, leave the repository field blank. You can come
  83. back and edit the repository field in the ``package.json`` file later.
  84. Change to the directory the cookiecutter created and list the files.
  85. .. code:: bash
  86. cd jupyterlab_apod
  87. ls
  88. You should see a list like the following.
  89. ::
  90. LICENSE README.md jupyterlab_apod/ pyproject.toml src/ tsconfig.json
  91. MANIFEST.in install.json package.json setup.py style/
  92. Commit what you have to git
  93. ^^^^^^^^^^^^^^^^^^^^^^^^^^^
  94. Run the following commands in your ``jupyterlab_apod`` folder to
  95. initialize it as a git repository and commit the current code.
  96. .. code:: bash
  97. git init
  98. git add .
  99. git commit -m 'Seed apod project from cookiecutter'
  100. Note: This step is not technically necessary, but it is good practice to
  101. track changes in version control system in case you need to rollback to
  102. an earlier version or want to collaborate with others. You
  103. can compare your work throughout this tutorial with the commits in a
  104. reference version of ``jupyterlab_apod`` on GitHub at
  105. https://github.com/jupyterlab/jupyterlab_apod.
  106. Build and install the extension for development
  107. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  108. Your new extension project has enough code in it to see it working in your
  109. JupyterLab. Run the following commands to install the initial project
  110. dependencies and install the extension into the JupyterLab environment.
  111. .. code:: bash
  112. pip install -ve .
  113. The above command copies the frontend part of the extension into JupyterLab.
  114. We can run this ``pip install`` command again every time we make a change to
  115. copy the change into JupyterLab. Even better, we can use
  116. the ``develop`` command to create a symbolic link from JupyterLab to our
  117. source directory. This means our changes are automatically available in
  118. JupyterLab:
  119. .. code:: bash
  120. jupyter labextension develop --overwrite .
  121. .. note::
  122. On Windows, symbolic links can be activated on Windows 10 for Python version 3.8 or higher
  123. by activating the 'Developer Mode'. That may not be allowed by your administrators.
  124. See `Activate Developer Mode on Windows <https://docs.microsoft.com/en-us/windows/apps/get-started/enable-your-device-for-development>`__
  125. for instructions.
  126. See the initial extension in action
  127. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  128. After the install completes, open a second terminal. Run these commands to
  129. activate the ``jupyterlab-ext`` environment and start JupyterLab in your
  130. default web browser.
  131. .. code:: bash
  132. conda activate jupyterlab-ext
  133. jupyter lab
  134. In that browser window, open the JavaScript console
  135. by following the instructions for your browser:
  136. - `Accessing the DevTools in Google
  137. Chrome <https://developer.chrome.com/devtools#access>`__
  138. - `Opening the Web Console in
  139. Firefox <https://developer.mozilla.org/en-US/docs/Tools/Web_Console/Opening_the_Web_Console>`__
  140. After you reload the page with the console open, you should see a message that says
  141. ``JupyterLab extension jupyterlab_apod is activated!`` in the console.
  142. If you do, congratulations, you're ready to start modifying the extension!
  143. If not, go back make sure you didn't miss a step, and `reach
  144. out <https://github.com/jupyterlab/jupyterlab/blob/3.1.x/README.md#getting-help>`__ if you're stuck.
  145. Note: Leave the terminal running the ``jupyter lab`` command open and running
  146. JupyterLab to see the effects of changes below.
  147. Add an Astronomy Picture of the Day widget
  148. ------------------------------------------
  149. Show an empty panel
  150. ^^^^^^^^^^^^^^^^^^^
  151. The *command palette* is the primary view of all commands available to
  152. you in JupyterLab. For your first addition, you're going to add a
  153. *Random Astronomy Picture* command to the palette and get it to show an *Astronomy Picture*
  154. tab panel when invoked.
  155. Fire up your favorite text editor and open the ``src/index.ts`` file in your
  156. extension project. Change the import at the top of the file to get a reference
  157. to the command palette interface and the `JupyterFrontEnd` instance.
  158. .. code:: typescript
  159. import {
  160. JupyterFrontEnd,
  161. JupyterFrontEndPlugin
  162. } from '@jupyterlab/application';
  163. import { ICommandPalette } from '@jupyterlab/apputils';
  164. Locate the ``extension`` object of type ``JupyterFrontEndPlugin``. Change the
  165. definition so that it reads like so:
  166. .. code:: typescript
  167. /**
  168. * Initialization data for the jupyterlab_apod extension.
  169. */
  170. const extension: JupyterFrontEndPlugin<void> = {
  171. id: 'jupyterlab-apod',
  172. autoStart: true,
  173. requires: [ICommandPalette],
  174. activate: (app: JupyterFrontEnd, palette: ICommandPalette) => {
  175. console.log('JupyterLab extension jupyterlab_apod is activated!');
  176. console.log('ICommandPalette:', palette);
  177. }
  178. };
  179. The ``requires`` attribute states that your plugin needs an object that
  180. implements the ``ICommandPalette`` interface when it starts. JupyterLab
  181. will pass an instance of ``ICommandPalette`` as the second parameter of
  182. ``activate`` in order to satisfy this requirement. Defining
  183. ``palette: ICommandPalette`` makes this instance available to your code
  184. in that function. The second ``console.log`` line exists only so that
  185. you can immediately check that your changes work.
  186. Now you will need to install these dependencies. Run the following commands in the
  187. repository root folder to install the dependencies and save them to your
  188. `package.json`:
  189. .. code:: bash
  190. jlpm add @jupyterlab/apputils
  191. jlpm add @jupyterlab/application
  192. Finally, run the following to rebuild your extension.
  193. .. code:: bash
  194. jlpm run build
  195. .. note::
  196. This tutorial uses ``jlpm`` to install Javascript packages and
  197. run build commands, which is JupyterLab's bundled
  198. version of ``yarn``. If you prefer, you can use another Javascript
  199. package manager like ``npm`` or ``yarn`` itself.
  200. After the extension build finishes, return to the browser tab that opened when
  201. you started JupyterLab. Refresh it and look in the console. You should see the
  202. same activation message as before, plus the new message about the
  203. ICommandPalette instance you just added. If you don't, check the output of the
  204. build command for errors and correct your code.
  205. ::
  206. JupyterLab extension jupyterlab_apod is activated!
  207. ICommandPalette: Palette {_palette: CommandPalette}
  208. Note that we had to run ``jlpm run build`` in order for the bundle to
  209. update. This command does two things: compiles the TypeScript files in `src/`
  210. into JavaScript files in ``lib/`` (``jlpm run build``), then bundles the
  211. JavaScript files in ``lib/`` into a JupyterLab extension in
  212. ``jupyterlab_apod/static`` (``jlpm run build:extension``). If you wish to avoid
  213. running ``jlpm run build`` after each change, you can open a third terminal,
  214. activate the ``jupyterlab-ext`` environment, and run the ``jlpm run watch``
  215. command from your extension directory, which will automatically compile the
  216. TypeScript files as they are changed and saved.
  217. Now return to your editor. Modify the imports at the top of the file to add a few more imports:
  218. .. code:: typescript
  219. import { ICommandPalette, MainAreaWidget } from '@jupyterlab/apputils';
  220. import { Widget } from '@lumino/widgets';
  221. Install this new dependency as well:
  222. .. code:: bash
  223. jlpm add @lumino/widgets
  224. Then modify the ``activate`` function again so that it has the following
  225. code:
  226. .. code-block:: typescript
  227. activate: (app: JupyterFrontEnd, palette: ICommandPalette) => {
  228. console.log('JupyterLab extension jupyterlab_apod is activated!');
  229. // Create a blank content widget inside of a MainAreaWidget
  230. const content = new Widget();
  231. const widget = new MainAreaWidget({ content });
  232. widget.id = 'apod-jupyterlab';
  233. widget.title.label = 'Astronomy Picture';
  234. widget.title.closable = true;
  235. // Add an application command
  236. const command: string = 'apod:open';
  237. app.commands.addCommand(command, {
  238. label: 'Random Astronomy Picture',
  239. execute: () => {
  240. if (!widget.isAttached) {
  241. // Attach the widget to the main work area if it's not there
  242. app.shell.add(widget, 'main');
  243. }
  244. // Activate the widget
  245. app.shell.activateById(widget.id);
  246. }
  247. });
  248. // Add the command to the palette.
  249. palette.addItem({ command, category: 'Tutorial' });
  250. }
  251. The first new block of code creates a ``MainAreaWidget`` instance with an
  252. empty content ``Widget`` as its child. It also assigns the main area widget a
  253. unique ID, gives it a label that will appear as its tab title, and makes the
  254. tab closable by the user. The second block of code adds a new command with id
  255. ``apod:open`` and label *Random Astronomy Picture* to JupyterLab. When the
  256. command executes, it attaches the widget to the main display area if it is not
  257. already present and then makes it the active tab. The last new line of code
  258. uses the command id to add the command to the command palette in a section
  259. called *Tutorial*.
  260. Build your extension again using ``jlpm run build`` (unless you are using
  261. ``jlpm run watch`` already) and refresh the browser tab. Open the command
  262. palette by clicking on *Commands* from the View menu or using the keyboard
  263. shortcut ``Command/Ctrl Shift C`` and type *Astronomy* in the search box. Your
  264. *Random Astronomy Picture* command should appear. Click it or select it with
  265. the keyboard and press *Enter*. You should see a new, blank panel appear with
  266. the tab title *Astronomy Picture*. Click the *x* on the tab to close it and
  267. activate the command again. The tab should reappear. Finally, click one of the
  268. launcher tabs so that the *Astronomy Picture* panel is still open but no
  269. longer active. Now run the *Random Astronomy Picture* command one more time.
  270. The single *Astronomy Picture* tab should come to the foreground.
  271. .. figure:: images/extension_tutorial_empty.png
  272. :align: center
  273. :class: jp-screenshot
  274. :alt: The in-progress extension, showing a blank panel.
  275. The in-progress extension, showing a blank panel.
  276. If your widget is not behaving, compare your code with the reference
  277. project state at the `01-show-a-panel
  278. tag <https://github.com/jupyterlab/jupyterlab_apod/tree/3.0-01-show-a-panel>`__.
  279. Once you've got everything working properly, git commit your changes and
  280. carry on.
  281. .. code-block:: bash
  282. git add package.json src/index.ts
  283. git commit -m 'Show Astronomy Picture command in palette'
  284. Show a picture in the panel
  285. ^^^^^^^^^^^^^^^^^^^^^^^^^^^
  286. You now have an empty panel. It's time to add a picture to it. Go back to
  287. your code editor. Add the following code below the lines that create a
  288. ``MainAreaWidget`` instance and above the lines that define the command.
  289. .. code-block:: typescript
  290. // Add an image element to the content
  291. let img = document.createElement('img');
  292. content.node.appendChild(img);
  293. // Get a random date string in YYYY-MM-DD format
  294. function randomDate() {
  295. const start = new Date(2010, 1, 1);
  296. const end = new Date();
  297. const randomDate = new Date(start.getTime() + Math.random()*(end.getTime() - start.getTime()));
  298. return randomDate.toISOString().slice(0, 10);
  299. }
  300. // Fetch info about a random picture
  301. const response = await fetch(`https://api.nasa.gov/planetary/apod?api_key=DEMO_KEY&date=${randomDate()}`);
  302. const data = await response.json() as APODResponse;
  303. if (data.media_type === 'image') {
  304. // Populate the image
  305. img.src = data.url;
  306. img.title = data.title;
  307. } else {
  308. console.log('Random APOD was not a picture.');
  309. }
  310. The first two lines create a new HTML ``<img>`` element and add it to
  311. the widget DOM node. The next lines define a function get a random date in the form ``YYYY-MM-DD`` format, and then the function is used to make a request using the HTML
  312. `fetch <https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch>`__
  313. API that returns information about the Astronomy Picture of the Day for that date. Finally, we set the
  314. image source and title attributes based on the response.
  315. Now define the ``APODResponse`` type that was introduced in the code above. Put
  316. this definition just under the imports at the top of the file.
  317. .. code-block:: typescript
  318. interface APODResponse {
  319. copyright: string;
  320. date: string;
  321. explanation: string;
  322. media_type: 'video' | 'image';
  323. title: string;
  324. url: string;
  325. };
  326. And update the ``activate`` method to be ``async`` since we are now using
  327. ``await`` in the method body.
  328. .. code-block:: typescript
  329. activate: async (app: JupyterFrontEnd, palette: ICommandPalette) =>
  330. Rebuild your extension if necessary (``jlpm run build``), refresh your browser
  331. tab, and run the *Random Astronomy Picture* command again. You should now see a
  332. picture in the panel when it opens (if that random date had a picture and not a
  333. video).
  334. .. figure:: images/extension_tutorial_single.png
  335. :align: center
  336. :class: jp-screenshot
  337. The in-progress extension, showing the `Astronomy Picture of the Day for 19 Jan 2014 <https://apod.nasa.gov/apod/ap140119.html>`__.
  338. Note that the image is not centered in the panel nor does the panel
  339. scroll if the image is larger than the panel area. Also note that the
  340. image does not update no matter how many times you close and reopen the
  341. panel. You'll address both of these problems in the upcoming sections.
  342. If you don't see a image at all, compare your code with the
  343. `02-show-an-image
  344. tag <https://github.com/jupyterlab/jupyterlab_apod/tree/3.0-02-show-an-image>`__
  345. in the reference project. When it's working, make another git commit.
  346. .. code:: bash
  347. git add src/index.ts
  348. git commit -m 'Show a picture in the panel'
  349. Improve the widget behavior
  350. ---------------------------
  351. Center the image, add attribution, and error messaging
  352. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  353. Open ``style/base.css`` in our extension project directory for editing.
  354. Add the following lines to it.
  355. .. code-block:: css
  356. .my-apodWidget {
  357. display: flex;
  358. flex-direction: column;
  359. align-items: center;
  360. overflow: auto;
  361. }
  362. This CSS stacks content vertically within the widget panel and lets the panel
  363. scroll when the content overflows. This CSS file is included on the page
  364. automatically by JupyterLab because the ``package.json`` file has a ``style``
  365. field pointing to it. In general, you should import all of your styles into a
  366. single CSS file, such as this ``index.css`` file, and put the path to that CSS
  367. file in the ``package.json`` file ``style`` field.
  368. Return to the ``index.ts`` file. Modify the ``activate``
  369. function to apply the CSS classes, the copyright information, and error handling
  370. for the API response.
  371. The beginning of the function should read like the following:
  372. .. code-block:: typescript
  373. :emphasize-lines: 6,16-17,28-50
  374. activate: async (app: JupyterFrontEnd, palette: ICommandPalette) => {
  375. console.log('JupyterLab extension jupyterlab_apod is activated!');
  376. // Create a blank content widget inside of a MainAreaWidget
  377. const content = new Widget();
  378. content.addClass('my-apodWidget'); // new line
  379. const widget = new MainAreaWidget({content});
  380. widget.id = 'apod-jupyterlab';
  381. widget.title.label = 'Astronomy Picture';
  382. widget.title.closable = true;
  383. // Add an image element to the content
  384. let img = document.createElement('img');
  385. content.node.appendChild(img);
  386. let summary = document.createElement('p');
  387. content.node.appendChild(summary);
  388. // Get a random date string in YYYY-MM-DD format
  389. function randomDate() {
  390. const start = new Date(2010, 1, 1);
  391. const end = new Date();
  392. const randomDate = new Date(start.getTime() + Math.random()*(end.getTime() - start.getTime()));
  393. return randomDate.toISOString().slice(0, 10);
  394. }
  395. // Fetch info about a random picture
  396. const response = await fetch(`https://api.nasa.gov/planetary/apod?api_key=DEMO_KEY&date=${randomDate()}`);
  397. if (!response.ok) {
  398. const data = await response.json();
  399. if (data.error) {
  400. summary.innerText = data.error.message;
  401. } else {
  402. summary.innerText = response.statusText;
  403. }
  404. } else {
  405. const data = await response.json() as APODResponse;
  406. if (data.media_type === 'image') {
  407. // Populate the image
  408. img.src = data.url;
  409. img.title = data.title;
  410. summary.innerText = data.title;
  411. if (data.copyright) {
  412. summary.innerText += ` (Copyright ${data.copyright})`;
  413. }
  414. } else {
  415. summary.innerText = 'Random APOD fetched was not an image.';
  416. }
  417. }
  418. // Keep all the remaining command lines the same
  419. // as before from here down ...
  420. Build your extension if necessary (``jlpm run build``) and refresh your
  421. JupyterLab browser tab. Invoke the *Random Astronomy Picture* command and
  422. confirm the image is centered with the copyright information below it. Resize
  423. the browser window or the panel so that the image is larger than the
  424. available area. Make sure you can scroll the panel over the entire area
  425. of the image.
  426. If anything is not working correctly, compare your code with the reference project
  427. `03-style-and-attribute
  428. tag <https://github.com/jupyterlab/jupyterlab_apod/tree/3.0-03-style-and-attribute>`__.
  429. When everything is working as expected, make another commit.
  430. .. code:: bash
  431. git add style/index.css src/index.ts
  432. git commit -m 'Add styling, attribution, error handling'
  433. Show a new image on demand
  434. ^^^^^^^^^^^^^^^^^^^^^^^^^^
  435. The ``activate`` function has grown quite long, and there's still more
  436. functionality to add. Let's refactor the code into two separate
  437. parts:
  438. 1. An ``APODWidget`` that encapsulates the Astronomy Picture panel elements,
  439. configuration, and soon-to-be-added update behavior
  440. 2. An ``activate`` function that adds the widget instance to the UI and
  441. decide when the picture should refresh
  442. Start by refactoring the widget code into the new ``APODWidget`` class.
  443. Add the following additional import to the top of the file.
  444. .. code-block:: typescript
  445. import { Message } from '@lumino/messaging';
  446. Install this dependency:
  447. .. code:: bash
  448. jlpm add @lumino/messaging
  449. Then add the class just below the definition of ``APODResponse`` in the ``index.ts``
  450. file.
  451. .. code-block:: typescript
  452. class APODWidget extends Widget {
  453. /**
  454. * Construct a new APOD widget.
  455. */
  456. constructor() {
  457. super();
  458. this.addClass('my-apodWidget');
  459. // Add an image element to the panel
  460. this.img = document.createElement('img');
  461. this.node.appendChild(this.img);
  462. // Add a summary element to the panel
  463. this.summary = document.createElement('p');
  464. this.node.appendChild(this.summary);
  465. }
  466. /**
  467. * The image element associated with the widget.
  468. */
  469. readonly img: HTMLImageElement;
  470. /**
  471. * The summary text element associated with the widget.
  472. */
  473. readonly summary: HTMLParagraphElement;
  474. /**
  475. * Handle update requests for the widget.
  476. */
  477. async onUpdateRequest(msg: Message): Promise<void> {
  478. const response = await fetch(`https://api.nasa.gov/planetary/apod?api_key=DEMO_KEY&date=${this.randomDate()}`);
  479. if (!response.ok) {
  480. const data = await response.json();
  481. if (data.error) {
  482. this.summary.innerText = data.error.message;
  483. } else {
  484. this.summary.innerText = response.statusText;
  485. }
  486. return;
  487. }
  488. const data = await response.json() as APODResponse;
  489. if (data.media_type === 'image') {
  490. // Populate the image
  491. this.img.src = data.url;
  492. this.img.title = data.title;
  493. this.summary.innerText = data.title;
  494. if (data.copyright) {
  495. this.summary.innerText += ` (Copyright ${data.copyright})`;
  496. }
  497. } else {
  498. this.summary.innerText = 'Random APOD fetched was not an image.';
  499. }
  500. }
  501. /**
  502. * Get a random date string in YYYY-MM-DD format.
  503. */
  504. randomDate(): string {
  505. const start = new Date(2010, 1, 1);
  506. const end = new Date();
  507. const randomDate = new Date(start.getTime() + Math.random()*(end.getTime() - start.getTime()));
  508. return randomDate.toISOString().slice(0, 10);
  509. }
  510. }
  511. You've written all of the code before. All you've done is restructure it
  512. to use instance variables and move the image request to its own
  513. function.
  514. Next move the remaining logic in ``activate`` to a new, top-level
  515. function just below the ``APODWidget`` class definition. Modify the code
  516. to create a widget when one does not exist in the main JupyterLab area
  517. or to refresh the image in the existing widget when the command runs again.
  518. The code for the ``activate`` function should read as follows after
  519. these changes:
  520. .. code-block:: typescript
  521. /**
  522. * Activate the APOD widget extension.
  523. */
  524. function activate(app: JupyterFrontEnd, palette: ICommandPalette) {
  525. console.log('JupyterLab extension jupyterlab_apod is activated!');
  526. // Create a single widget
  527. const content = new APODWidget();
  528. const widget = new MainAreaWidget({content});
  529. widget.id = 'apod-jupyterlab';
  530. widget.title.label = 'Astronomy Picture';
  531. widget.title.closable = true;
  532. // Add an application command
  533. const command: string = 'apod:open';
  534. app.commands.addCommand(command, {
  535. label: 'Random Astronomy Picture',
  536. execute: () => {
  537. if (!widget.isAttached) {
  538. // Attach the widget to the main work area if it's not there
  539. app.shell.add(widget, 'main');
  540. }
  541. // Refresh the picture in the widget
  542. content.update();
  543. // Activate the widget
  544. app.shell.activateById(widget.id);
  545. }
  546. });
  547. // Add the command to the palette.
  548. palette.addItem({ command, category: 'Tutorial' });
  549. }
  550. Remove the ``activate`` function definition from the
  551. ``JupyterFrontEndPlugin`` object and refer instead to the top-level function
  552. like this:
  553. .. code-block:: typescript
  554. const extension: JupyterFrontEndPlugin<void> = {
  555. id: 'jupyterlab_apod',
  556. autoStart: true,
  557. requires: [ICommandPalette],
  558. activate: activate
  559. };
  560. Make sure you retain the ``export default extension;`` line in the file.
  561. Now build the extension again and refresh the JupyterLab browser tab.
  562. Run the *Random Astronomy Picture* command more than once without closing the
  563. panel. The picture should update each time you execute the command. Close
  564. the panel, run the command, and it should both reappear and show a new
  565. image.
  566. If anything is not working correctly, compare your code with the
  567. `04-refactor-and-refresh
  568. tag <https://github.com/jupyterlab/jupyterlab_apod/tree/3.0-04-refactor-and-refresh>`__
  569. to debug. Once it is working properly, commit it.
  570. .. code:: bash
  571. git add package.json src/index.ts
  572. git commit -m 'Refactor, refresh image'
  573. Restore panel state when the browser refreshes
  574. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  575. You may notice that every time you refresh your browser tab, the Astronomy Picture
  576. panel disappears, even if it was open before you refreshed. Other open
  577. panels, like notebooks, terminals, and text editors, all reappear and
  578. return to where you left them in the panel layout. You can make your
  579. extension behave this way too.
  580. Update the imports at the top of your ``index.ts`` file so that the
  581. entire list of import statements looks like the following:
  582. .. code-block:: typescript
  583. :emphasize-lines: 2,10
  584. import {
  585. ILayoutRestorer,
  586. JupyterFrontEnd,
  587. JupyterFrontEndPlugin
  588. } from '@jupyterlab/application';
  589. import {
  590. ICommandPalette,
  591. MainAreaWidget,
  592. WidgetTracker
  593. } from '@jupyterlab/apputils';
  594. import { Message } from '@lumino/messaging';
  595. import { Widget } from '@lumino/widgets';
  596. Then add the ``ILayoutRestorer`` interface to the ``JupyterFrontEndPlugin``
  597. definition. This addition passes the global ``LayoutRestorer`` as the
  598. third parameter of the ``activate`` function.
  599. .. code-block:: typescript
  600. :emphasize-lines: 4
  601. const extension: JupyterFrontEndPlugin<void> = {
  602. id: 'jupyterlab_apod',
  603. autoStart: true,
  604. requires: [ICommandPalette, ILayoutRestorer],
  605. activate: activate
  606. };
  607. Finally, rewrite the ``activate`` function so that it:
  608. 1. Declares a widget variable, but does not create an instance
  609. immediately.
  610. 2. Constructs a ``WidgetTracker`` and tells the ``ILayoutRestorer``
  611. to use it to save/restore panel state.
  612. 3. Creates, tracks, shows, and refreshes the widget panel appropriately.
  613. .. code-block:: typescript
  614. function activate(app: JupyterFrontEnd, palette: ICommandPalette, restorer: ILayoutRestorer) {
  615. console.log('JupyterLab extension jupyterlab_apod is activated!');
  616. // Declare a widget variable
  617. let widget: MainAreaWidget<APODWidget>;
  618. // Add an application command
  619. const command: string = 'apod:open';
  620. app.commands.addCommand(command, {
  621. label: 'Random Astronomy Picture',
  622. execute: () => {
  623. if (!widget || widget.isDisposed) {
  624. // Create a new widget if one does not exist
  625. // or if the previous one was disposed after closing the panel
  626. const content = new APODWidget();
  627. widget = new MainAreaWidget({content});
  628. widget.id = 'apod-jupyterlab';
  629. widget.title.label = 'Astronomy Picture';
  630. widget.title.closable = true;
  631. }
  632. if (!tracker.has(widget)) {
  633. // Track the state of the widget for later restoration
  634. tracker.add(widget);
  635. }
  636. if (!widget.isAttached) {
  637. // Attach the widget to the main work area if it's not there
  638. app.shell.add(widget, 'main');
  639. }
  640. widget.content.update();
  641. // Activate the widget
  642. app.shell.activateById(widget.id);
  643. }
  644. });
  645. // Add the command to the palette.
  646. palette.addItem({ command, category: 'Tutorial' });
  647. // Track and restore the widget state
  648. let tracker = new WidgetTracker<MainAreaWidget<APODWidget>>({
  649. namespace: 'apod'
  650. });
  651. restorer.restore(tracker, {
  652. command,
  653. name: () => 'apod'
  654. });
  655. }
  656. Rebuild your extension one last time and refresh your browser tab.
  657. Execute the *Random Astronomy Picture* command and validate that the panel
  658. appears with an image in it. Refresh the browser tab again. You should
  659. see an Astronomy Picture panel reappear immediately without running the command. Close
  660. the panel and refresh the browser tab. You should then not see an Astronomy Picture tab
  661. after the refresh.
  662. .. figure:: images/extension_tutorial_complete.png
  663. :align: center
  664. :class: jp-screenshot
  665. :alt: The completed extension, showing the Astronomy Picture of the Day for 24 Jul 2015.
  666. The completed extension, showing the `Astronomy Picture of the Day for 24 Jul 2015 <https://apod.nasa.gov/apod/ap150724.html>`__.
  667. Refer to the `05-restore-panel-state
  668. tag <https://github.com/jupyterlab/jupyterlab_apod/tree/3.0-05-restore-panel-state>`__
  669. if your extension is not working correctly. Make a commit when the state of your
  670. extension persists properly.
  671. .. code:: bash
  672. git add src/index.ts
  673. git commit -m 'Restore panel state'
  674. Congratulations! You've implemented all of the behaviors laid out at the start
  675. of this tutorial.
  676. .. _packaging your extension:
  677. Packaging your extension
  678. ------------------------
  679. JupyterLab extensions for JupyterLab 3.0 can be distributed as Python
  680. packages. The cookiecutter template we used contains all of the Python
  681. packaging instructions in the ``pyproject.toml`` file to wrap your extension in a
  682. Python package. Before generating a package, we first need to install ``build``.
  683. .. code:: bash
  684. pip install build
  685. To create a Python source package (``.tar.gz``) in the ``dist/`` directory, do:
  686. .. code:: bash
  687. python -m build -s
  688. To create a Python wheel package (``.whl``) in the ``dist/`` directory, do:
  689. .. code:: bash
  690. python -m build
  691. Both of these commands will build the JavaScript into a bundle in the
  692. ``jupyterlab_apod/labextension/static`` directory, which is then distributed with the
  693. Python package. This bundle will include any necessary JavaScript dependencies
  694. as well. You may want to check in the ``jupyterlab_apod/labextension/static`` directory to
  695. retain a record of what JavaScript is distributed in your package, or you may
  696. want to keep this "build artifact" out of your source repository history.
  697. You can now try installing your extension as a user would. Open a new terminal
  698. and run the following commands to create a new environment and install your
  699. extension.
  700. .. code:: bash
  701. conda create -n jupyterlab-apod jupyterlab
  702. conda activate jupyterlab-apod
  703. pip install jupyterlab_apod/dist/jupyterlab_apod-0.1.0-py3-none-any.whl
  704. jupyter lab
  705. You should see a fresh JupyterLab browser tab appear. When it does,
  706. execute the *Random Astronomy Picture* command to check that your extension
  707. works.
  708. .. _extension_tutorial_publish:
  709. Publishing your extension
  710. -------------------------
  711. You can publish your Python package to the `PyPI <https://pypi.org>`_ or
  712. `conda-forge <https://conda-forge.org>`_ repositories so users can easily
  713. install the extension using ``pip`` or ``conda``.
  714. You may want to also publish your extension as a JavaScript package to the
  715. `npm <https://www.npmjs.com>`_ package repository for several reasons:
  716. 1. Distributing an extension as an npm package allows users to compile the
  717. extension into JupyterLab explicitly (similar to how was done in JupyterLab
  718. versions 1 and 2), which leads to a more optimal JupyterLab package.
  719. 2. As we saw above, JupyterLab enables extensions to use services provided by
  720. other extensions. For example, our extension above uses the ``ICommandPalette``
  721. and ``ILayoutRestorer`` services provided by core extensions in
  722. JupyterLab. We were able to tell JupyterLab we required these services by
  723. importing their tokens from the ``@jupyterlab/apputils`` and
  724. ``@jupyterlab/application`` npm packages and listing them in our plugin
  725. definition. If you want to provide a service to the JupyterLab system
  726. for other extensions to use, you will need to publish your JavaScript
  727. package to npm so other extensions can depend on it and import and require
  728. your token.
  729. Automated Releases
  730. ^^^^^^^^^^^^^^^^^^
  731. If you used the cookiecutter to bootstrap your extension, the repository should already
  732. be compatible with the `Jupyter Releaser <https://github.com/jupyter-server/jupyter_releaser>`_.
  733. The Jupyter Releaser provides a set of GitHub Actions Workflows to:
  734. - Generate a new entry in the Changelog
  735. - Draft a new release
  736. - Publish the release to ``PyPI`` and ``npm``
  737. For more information on how to run the release workflows,
  738. check out the documentation: https://github.com/jupyter-server/jupyter_releaser
  739. Learn more
  740. ----------
  741. You've completed the tutorial. Nicely done! If you want to keep
  742. learning, here are some suggestions about what to try next:
  743. - Add the image description that comes in the API response to the panel.
  744. - Assign a default hotkey to the *Random Astronomy Picture* command.
  745. - Make the image a link to the picture on the NASA website (URLs are of the form ``https://apod.nasa.gov/apod/apYYMMDD.html``).
  746. - Make the image title and description update after the image loads so that the picture and description are always synced.
  747. - Give users the ability to pin pictures in separate, permanent panels.
  748. - Add a setting for the user to put in their `API key <https://api.nasa.gov/#authentication>`__ so they can make many more requests per hour than the demo key allows.
  749. - Push your extension git repository to GitHub.
  750. - Learn how to write :ref:`other kinds of extensions <developer_extensions>`.