extension_tutorial.rst 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947
  1. .. _extension_tutorial:
  2. Let's Make an Astronomy Picture of the Day JupyterLab Extension
  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:: 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 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 -c conda-forge --override-channels jupyterlab cookiecutter nodejs 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 --checkout v1.0
  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. extension_name [myextension]: jupyterlab_apod
  76. project_short_description [A JupyterLab extension.]: Show a random NASA Astronomy Picture of the Day in a JupyterLab panel
  77. repository [https://github.com/my_name/jupyterlab_myextension]: https://github.com/my_name/jupyterlab_apod
  78. Note: if not using a repository, leave the repository field blank. You can come
  79. back and edit the repository field in the ``package.json`` file later.
  80. Change to the directory the cookiecutter created and list the files.
  81. .. code:: bash
  82. cd jupyterlab_apod
  83. ls
  84. You should see a list like the following.
  85. ::
  86. README.md package.json src style tsconfig.json
  87. Build and install the extension for development
  88. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  89. Your new extension project has enough code in it to see it working in
  90. your JupyterLab. Run the following commands to install the initial
  91. project dependencies and install it in the JupyterLab environment. We
  92. defer building since it will be built in the next step.
  93. .. note::
  94. This tutorial uses ``jlpm`` to install Javascript packages and
  95. run build commands, which is JupyterLab's bundled
  96. version of ``yarn``. If you prefer, you can use another Javascript
  97. package manager like ``npm`` or ``yarn`` itself.
  98. .. code:: bash
  99. jlpm install
  100. jupyter labextension install . --no-build
  101. After the install completes, open a second terminal. Run these commands
  102. to activate the ``jupyterlab-ext`` environment and to start a JupyterLab
  103. instance in watch mode so that it will keep up with our changes as we
  104. make them.
  105. .. code:: bash
  106. conda activate jupyterlab-ext
  107. jupyter lab --watch
  108. See the initial extension in action
  109. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  110. After building with your extension, JupyterLab should open in your
  111. default web browser.
  112. In that browser window, open the JavaScript console
  113. by following the instructions for your browser:
  114. - `Accessing the DevTools in Google
  115. Chrome <https://developer.chrome.com/devtools#access>`__
  116. - `Opening the Web Console in
  117. Firefox <https://developer.mozilla.org/en-US/docs/Tools/Web_Console/Opening_the_Web_Console>`__
  118. After you reload the page with the console open, you should see a message that says
  119. ``JupyterLab extension jupyterlab_apod is activated!`` in the console.
  120. If you do, congratulations, you're ready to start modifying the extension!
  121. If not, go back make sure you didn't miss a step, and `reach
  122. out <https://github.com/jupyterlab/jupyterlab/blob/master/README.md#getting-help>`__ if you're stuck.
  123. Note: Leave the terminal running the ``jupyter lab --watch`` command
  124. open.
  125. Commit what you have to git
  126. ^^^^^^^^^^^^^^^^^^^^^^^^^^^
  127. Run the following commands in your ``jupyterlab_apod`` folder to
  128. initialize it as a git repository and commit the current code.
  129. .. code:: bash
  130. git init
  131. git add .
  132. git commit -m 'Seed apod project from cookiecutter'
  133. Note: This step is not technically necessary, but it is good practice to
  134. track changes in version control system in case you need to rollback to
  135. an earlier version or want to collaborate with others. For example, you
  136. can compare your work throughout this tutorial with the commits in a
  137. reference version of ``jupyterlab_apod`` on GitHub at
  138. https://github.com/jupyterlab/jupyterlab_apod.
  139. Add an Astronomy Picture of the Day widget
  140. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  141. Show an empty panel
  142. ^^^^^^^^^^^^^^^^^^^
  143. The *command palette* is the primary view of all commands available to
  144. you in JupyterLab. For your first addition, you're going to add a
  145. *Random Astronomy Picture* command to the palette and get it to show an *Astronomy Picture*
  146. tab panel when invoked.
  147. Fire up your favorite text editor and open the ``src/index.ts`` file in
  148. your extension project. Add the following import at the top of the file
  149. to get a reference to the command palette interface.
  150. .. code:: typescript
  151. import {
  152. ICommandPalette
  153. } from '@jupyterlab/apputils';
  154. You will also need to install this dependency. Run the following command in the
  155. repository root folder install the dependency and save it to your
  156. `package.json`:
  157. .. code:: bash
  158. jlpm add @jupyterlab/apputils
  159. Locate the ``extension`` object of type ``JupyterFrontEndPlugin``. Change the
  160. definition so that it reads like so:
  161. .. code:: typescript
  162. /**
  163. * Initialization data for the jupyterlab_apod extension.
  164. */
  165. const extension: JupyterFrontEndPlugin<void> = {
  166. id: 'jupyterlab_apod',
  167. autoStart: true,
  168. requires: [ICommandPalette],
  169. activate: (app: JupyterFrontEnd, palette: ICommandPalette) => {
  170. console.log('JupyterLab extension jupyterlab_apod is activated!');
  171. console.log('ICommandPalette:', palette);
  172. }
  173. };
  174. The ``requires`` attribute states that your plugin needs an object that
  175. implements the ``ICommandPalette`` interface when it starts. JupyterLab
  176. will pass an instance of ``ICommandPalette`` as the second parameter of
  177. ``activate`` in order to satisfy this requirement. Defining
  178. ``palette: ICommandPalette`` makes this instance available to your code
  179. in that function. The second ``console.log`` line exists only so that
  180. you can immediately check that your changes work.
  181. Run the following to rebuild your extension.
  182. .. code:: bash
  183. jlpm run build
  184. JupyterLab will rebuild after the extension does. You can
  185. see it's progress in the ``jupyter lab --watch`` window. After that
  186. finishes, return to the browser tab that opened when you
  187. started JupyterLab. Refresh it and look in the console. You should see
  188. the same activation message as before, plus the new message about the
  189. ICommandPalette instance you just added. If you don't, check the output
  190. of the build command for errors and correct your code.
  191. ::
  192. JupyterLab extension jupyterlab_apod is activated!
  193. ICommandPalette: Palette {_palette: CommandPalette}
  194. Note that we had to run ``jlpm run build`` in order for the bundle to
  195. update, because it is using the compiled JavaScript files in ``/lib``.
  196. If you wish to avoid running ``jlpm run build`` after each change, you
  197. can open a third terminal, and run the ``jlpm run watch`` command from
  198. your extension directory, which will automatically compile the
  199. TypeScript files as they change.
  200. Now return to your editor. Modify the imports at the top of the file to add a few more imports:
  201. .. code:: typescript
  202. import {
  203. ICommandPalette, MainAreaWidget
  204. } from '@jupyterlab/apputils';
  205. import {
  206. Widget
  207. } from '@phosphor/widgets';
  208. Install this new dependency as well:
  209. .. code:: bash
  210. jlpm add @phosphor/widgets
  211. Then modify the ``activate`` function again so that it has the following
  212. code:
  213. .. code-block:: typescript
  214. activate: (app: JupyterFrontEnd, palette: ICommandPalette) => {
  215. console.log('JupyterLab extension jupyterlab_apod is activated!');
  216. // Create a blank content widget inside of a MainAreaWidget
  217. const content = new Widget();
  218. const widget = new MainAreaWidget({content});
  219. widget.id = 'apod-jupyterlab';
  220. widget.title.label = 'Astronomy Picture';
  221. widget.title.closable = true;
  222. // Add an application command
  223. const command: string = 'apod:open';
  224. app.commands.addCommand(command, {
  225. label: 'Random Astronomy Picture',
  226. execute: () => {
  227. if (!widget.isAttached) {
  228. // Attach the widget to the main work area if it's not there
  229. app.shell.add(widget, 'main');
  230. }
  231. // Activate the widget
  232. app.shell.activateById(widget.id);
  233. }
  234. });
  235. // Add the command to the palette.
  236. palette.addItem({command, category: 'Tutorial'});
  237. }
  238. The first new block of code creates a ``MainAreaWidget`` instance with an empty
  239. content ``Widget`` as its child. It also assigns the main area widget a unique
  240. ID, gives it a label that will appear as its tab title, and makes the tab
  241. closable by the user.
  242. The second block of code adds a new command with id ``apod:open`` and label *Random Astronomy Picture*
  243. to JupyterLab. When the command executes,
  244. it attaches the widget to the main display area if it is not already
  245. present and then makes it the active tab. The last new line of code uses the command id to add
  246. the command to the command palette in a section called *Tutorial*.
  247. Build your extension again using ``jlpm run build`` (unless you are using
  248. ``jlpm run watch`` already) and refresh the browser tab. Open the command
  249. palette on the left side by clicking on *Commands* and type *Astronomy* in
  250. the search box. Your *Random Astronomy Picture*
  251. command should appear. Click it or select it with the keyboard and press
  252. *Enter*. You should see a new, blank panel appear with the tab title
  253. *Astronomy Picture*. Click the *x* on the tab to close it and activate the
  254. command again. The tab should reappear. Finally, click one of the
  255. launcher tabs so that the *Astronomy Picture* panel is still open but no longer
  256. active. Now run the *Random Astronomy Picture* command one more time. The
  257. single *Astronomy Picture* tab should come to the foreground.
  258. .. figure:: extension_tutorial_empty.png
  259. :align: center
  260. :class: jp-screenshot
  261. :alt: The in-progress extension, showing a blank panel.
  262. The in-progress extension, showing a blank panel.
  263. If your widget is not behaving, compare your code with the reference
  264. project state at the `01-show-a-panel
  265. tag <https://github.com/jupyterlab/jupyterlab_apod/tree/1.0-01-show-a-panel>`__.
  266. Once you've got everything working properly, git commit your changes and
  267. carry on.
  268. .. code-block:: bash
  269. git add .
  270. git commit -m 'Show Astronomy Picture command in palette'
  271. Show a picture in the panel
  272. ^^^^^^^^^^^^^^^^^^^^^^^^^^^
  273. You now have an empty panel. It's time to add a picture to it. Go back to
  274. your code editor. Add the following code below the lines that create a
  275. ``MainAreaWidget`` instance and above the lines that define the command.
  276. .. code-block:: typescript
  277. // Add an image element to the content
  278. let img = document.createElement('img');
  279. content.node.appendChild(img);
  280. // Get a random date string in YYYY-MM-DD format
  281. function randomDate() {
  282. const start = new Date(2010, 1, 1);
  283. const end = new Date();
  284. const randomDate = new Date(start.getTime() + Math.random()*(end.getTime() - start.getTime()));
  285. return randomDate.toISOString().slice(0, 10);
  286. }
  287. // Fetch info about a random picture
  288. const response = await fetch(`https://api.nasa.gov/planetary/apod?api_key=DEMO_KEY&date=${randomDate()}`);
  289. const data = await response.json() as APODResponse;
  290. if (data.media_type === 'image') {
  291. // Populate the image
  292. img.src = data.url;
  293. img.title = data.title;
  294. } else {
  295. console.log('Random APOD was not a picture.');
  296. }
  297. The first two lines create a new HTML ``<img>`` element and add it to
  298. 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
  299. `fetch <https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch>`__
  300. API that returns information about the Astronomy Picture of the Day for that date. Finally, we set the
  301. image source and title attributes based on the response.
  302. Now define the ``APODResponse`` type that was introduced in the code above. Put
  303. this definition just under the imports at the top of the file.
  304. .. code-block:: typescript
  305. interface APODResponse {
  306. copyright: string;
  307. date: string;
  308. explanation: string;
  309. media_type: 'video' | 'image';
  310. title: string;
  311. url: string;
  312. };
  313. And update the ``activate`` method to be ``async`` since we are now using
  314. ``await`` in the method body.
  315. .. code-block:: typescript
  316. activate: async (app: JupyterFrontEnd, palette: ICommandPalette) =>
  317. Rebuild your extension if necessary (``jlpm run build``), refresh your browser
  318. tab, and run the *Random Astronomy Picture* command again. You should now see a
  319. picture in the panel when it opens (if that random date had a picture and not a
  320. video).
  321. .. figure:: extension_tutorial_single.png
  322. :align: center
  323. :class: jp-screenshot
  324. The in-progress extension, showing the `Astronomy Picture of the Day for 19 Jan 2014 <https://apod.nasa.gov/apod/ap140119.html>`__.
  325. Note that the image is not centered in the panel nor does the panel
  326. scroll if the image is larger than the panel area. Also note that the
  327. image does not update no matter how many times you close and reopen the
  328. panel. You'll address both of these problems in the upcoming sections.
  329. If you don't see a image at all, compare your code with the
  330. `02-show-an-image
  331. tag <https://github.com/jupyterlab/jupyterlab_apod/tree/1.0-02-show-an-image>`__
  332. in the reference project. When it's working, make another git commit.
  333. .. code:: bash
  334. git add .
  335. git commit -m 'Show a picture in the panel'
  336. Improve the widget behavior
  337. ~~~~~~~~~~~~~~~~~~~~~~~~~~~
  338. Center the image, add attribution, and error messaging
  339. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  340. Open ``style/index.css`` in our extension project directory for editing.
  341. Add the following lines to it.
  342. .. code-block:: css
  343. .my-apodWidget {
  344. display: flex;
  345. flex-direction: column;
  346. align-items: center;
  347. overflow: auto;
  348. }
  349. This CSS stacks content vertically within the widget panel and lets the panel
  350. scroll when the content overflows. This CSS file is included on the page
  351. automatically by JupyterLab because the ``package.json`` file has a ``style``
  352. field pointing to it. In general, you should import all of your styles into a
  353. single CSS file, such as this ``index.css`` file, and put the path to that CSS
  354. file in the ``package.json`` file ``style`` field.
  355. Return to the ``index.ts`` file. Modify the ``activate``
  356. function to apply the CSS classes, the copyright information, and error handling
  357. for the API response.
  358. The beginning of the function should read like the following:
  359. .. code-block:: typescript
  360. :emphasize-lines: 6,16-17,28-50
  361. activate: async (app: JupyterFrontEnd, palette: ICommandPalette) => {
  362. console.log('JupyterLab extension jupyterlab_apod is activated!');
  363. // Create a blank content widget inside of a MainAreaWidget
  364. const content = new Widget();
  365. content.addClass('my-apodWidget'); // new line
  366. const widget = new MainAreaWidget({content});
  367. widget.id = 'apod-jupyterlab';
  368. widget.title.label = 'Astronomy Picture';
  369. widget.title.closable = true;
  370. // Add an image element to the content
  371. let img = document.createElement('img');
  372. content.node.appendChild(img);
  373. let summary = document.createElement('p');
  374. content.node.appendChild(summary);
  375. // Get a random date string in YYYY-MM-DD format
  376. function randomDate() {
  377. const start = new Date(2010, 1, 1);
  378. const end = new Date();
  379. const randomDate = new Date(start.getTime() + Math.random()*(end.getTime() - start.getTime()));
  380. return randomDate.toISOString().slice(0, 10);
  381. }
  382. // Fetch info about a random picture
  383. const response = await fetch(`https://api.nasa.gov/planetary/apod?api_key=DEMO_KEY&date=${randomDate()}`);
  384. if (!response.ok) {
  385. const data = await response.json();
  386. if (data.error) {
  387. summary.innerText = data.error.message;
  388. } else {
  389. summary.innerText = response.statusText;
  390. }
  391. } else {
  392. const data = await response.json() as APODResponse;
  393. if (data.media_type === 'image') {
  394. // Populate the image
  395. img.src = data.url;
  396. img.title = data.title;
  397. summary.innerText = data.title;
  398. if (data.copyright) {
  399. summary.innerText += ` (Copyright ${data.copyright})`;
  400. }
  401. } else {
  402. summary.innerText = 'Random APOD fetched was not an image.';
  403. }
  404. }
  405. // Keep all the remaining fetch and command lines the same
  406. // as before from here down ...
  407. Build your extension if necessary (``jlpm run build``) and refresh your
  408. JupyterLab browser tab. Invoke the *Random Astronomy Picture* command and
  409. confirm the image is centered with the copyright information below it. Resize
  410. the browser window or the panel so that the image is larger than the
  411. available area. Make sure you can scroll the panel over the entire area
  412. of the image.
  413. If anything is not working correctly, compare your code with the reference project
  414. `03-style-and-attribute
  415. tag <https://github.com/jupyterlab/jupyterlab_apod/tree/1.0-03-style-and-attribute>`__.
  416. When everything is working as expected, make another commit.
  417. .. code:: bash
  418. git add .
  419. git commit -m 'Add styling, attribution, error handling'
  420. Show a new image on demand
  421. ^^^^^^^^^^^^^^^^^^^^^^^^^^
  422. The ``activate`` function has grown quite long, and there's still more
  423. functionality to add. Let's refactor the code into two separate
  424. parts:
  425. 1. An ``APODWidget`` that encapsulates the Astronomy Picture panel elements,
  426. configuration, and soon-to-be-added update behavior
  427. 2. An ``activate`` function that adds the widget instance to the UI and
  428. decide when the picture should refresh
  429. Start by refactoring the widget code into the new ``APODWidget`` class.
  430. Add the following additional import to the top of the file.
  431. .. code-block:: typescript
  432. import {
  433. Message
  434. } from '@phosphor/messaging';
  435. Install this dependency:
  436. .. code:: bash
  437. jlpm add @phosphor/messaging
  438. Then add the class just below the import statements in the ``index.ts``
  439. file.
  440. .. code-block:: typescript
  441. class APODWidget extends Widget {
  442. /**
  443. * Construct a new APOD widget.
  444. */
  445. constructor() {
  446. super();
  447. this.addClass('my-apodWidget'); // new line
  448. // Add an image element to the panel
  449. this.img = document.createElement('img');
  450. this.node.appendChild(this.img);
  451. // Add a summary element to the panel
  452. this.summary = document.createElement('p');
  453. this.node.appendChild(this.summary);
  454. }
  455. /**
  456. * The image element associated with the widget.
  457. */
  458. readonly img: HTMLImageElement;
  459. /**
  460. * The summary text element associated with the widget.
  461. */
  462. readonly summary: HTMLParagraphElement;
  463. /**
  464. * Handle update requests for the widget.
  465. */
  466. async onUpdateRequest(msg: Message): Promise<void> {
  467. const response = await fetch(`https://api.nasa.gov/planetary/apod?api_key=DEMO_KEY&date=${this.randomDate()}`);
  468. if (!response.ok) {
  469. const data = await response.json();
  470. if (data.error) {
  471. this.summary.innerText = data.error.message;
  472. } else {
  473. this.summary.innerText = response.statusText;
  474. }
  475. return;
  476. }
  477. const data = await response.json() as APODResponse;
  478. if (data.media_type === 'image') {
  479. // Populate the image
  480. this.img.src = data.url;
  481. this.img.title = data.title;
  482. this.summary.innerText = data.title;
  483. if (data.copyright) {
  484. this.summary.innerText += ` (Copyright ${data.copyright})`;
  485. }
  486. } else {
  487. this.summary.innerText = 'Random APOD fetched was not an image.';
  488. }
  489. }
  490. You've written all of the code before. All you've done is restructure it
  491. to use instance variables and move the image request to its own
  492. function.
  493. Next move the remaining logic in ``activate`` to a new, top-level
  494. function just below the ``APODWidget`` class definition. Modify the code
  495. to create a widget when one does not exist in the main JupyterLab area
  496. or to refresh the image in the exist widget when the command runs again.
  497. The code for the ``activate`` function should read as follows after
  498. these changes:
  499. .. code-block:: typescript
  500. /**
  501. * Activate the APOD widget extension.
  502. */
  503. function activate(app: JupyterFrontEnd, palette: ICommandPalette) {
  504. console.log('JupyterLab extension jupyterlab_apod is activated!');
  505. // Create a single widget
  506. const content = new APODWidget();
  507. const widget = new MainAreaWidget({content});
  508. widget.id = 'apod-jupyterlab';
  509. widget.title.label = 'Astronomy Picture';
  510. widget.title.closable = true;
  511. // Add an application command
  512. const command: string = 'apod:open';
  513. app.commands.addCommand(command, {
  514. label: 'Random Astronomy Picture',
  515. execute: () => {
  516. if (!widget.isAttached) {
  517. // Attach the widget to the main work area if it's not there
  518. app.shell.add(widget, 'main');
  519. }
  520. // Refresh the picture in the widget
  521. content.update();
  522. // Activate the widget
  523. app.shell.activateById(widget.id);
  524. }
  525. });
  526. // Add the command to the palette.
  527. palette.addItem({ command, category: 'Tutorial' });
  528. }
  529. Remove the ``activate`` function definition from the
  530. ``JupyterFrontEndPlugin`` object and refer instead to the top-level function
  531. like this:
  532. .. code-block:: typescript
  533. const extension: JupyterFrontEndPlugin<void> = {
  534. id: 'jupyterlab_apod',
  535. autoStart: true,
  536. requires: [ICommandPalette],
  537. activate: activate
  538. };
  539. Make sure you retain the ``export default extension;`` line in the file.
  540. Now build the extension again and refresh the JupyterLab browser tab.
  541. Run the *Random Astronomy Picture* command more than once without closing the
  542. panel. The picture should update each time you execute the command. Close
  543. the panel, run the command, and it should both reappear and show a new
  544. image.
  545. If anything is not working correctly, compare your code with the
  546. `04-refactor-and-refresh
  547. tag <https://github.com/jupyterlab/jupyterlab_apod/tree/1.0-04-refactor-and-refresh>`__
  548. to debug. Once it is working properly, commit it.
  549. .. code:: bash
  550. git add .
  551. git commit -m 'Refactor, refresh image'
  552. Restore panel state when the browser refreshes
  553. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  554. You may notice that every time you refresh your browser tab, the Astronomy Picture
  555. panel disappears, even if it was open before you refreshed. Other open
  556. panels, like notebooks, terminals, and text editors, all reappear and
  557. return to where you left them in the panel layout. You can make your
  558. extension behave this way too.
  559. Update the imports at the top of your ``index.ts`` file so that the
  560. entire list of import statements looks like the following:
  561. .. code-block:: typescript
  562. :emphasize-lines: 2,6
  563. import {
  564. ILayoutRestorer, JupyterFrontEnd, JupyterFrontEndPlugin
  565. } from '@jupyterlab/application';
  566. import {
  567. ICommandPalette, MainAreaWidget, WidgetTracker
  568. } from '@jupyterlab/apputils';
  569. import {
  570. Message
  571. } from '@phosphor/messaging';
  572. import {
  573. Widget
  574. } from '@phosphor/widgets';
  575. Install this dependency:
  576. .. code:: bash
  577. jlpm add @phosphor/coreutils
  578. Then add the ``ILayoutRestorer`` interface to the ``JupyterFrontEndPlugin``
  579. definition. This addition passes the global ``LayoutRestorer`` as the
  580. third parameter of the ``activate`` function.
  581. .. code-block:: typescript
  582. :emphasize-lines: 4
  583. const extension: JupyterFrontEndPlugin<void> = {
  584. id: 'jupyterlab_apod',
  585. autoStart: true,
  586. requires: [ICommandPalette, ILayoutRestorer],
  587. activate: activate
  588. };
  589. Finally, rewrite the ``activate`` function so that it:
  590. 1. Declares a widget variable, but does not create an instance
  591. immediately.
  592. 2. Constructs a ``WidgetTracker`` and tells the ``ILayoutRestorer``
  593. to use it to save/restore panel state.
  594. 3. Creates, tracks, shows, and refreshes the widget panel appropriately.
  595. .. code-block:: typescript
  596. function activate(app: JupyterFrontEnd, palette: ICommandPalette, restorer: ILayoutRestorer) {
  597. console.log('JupyterLab extension jupyterlab_apod is activated!');
  598. // Declare a widget variable
  599. let widget: MainAreaWidget<APODWidget>;
  600. // Add an application command
  601. const command: string = 'apod:open';
  602. app.commands.addCommand(command, {
  603. label: 'Random Astronomy Picture',
  604. execute: () => {
  605. if (!widget) {
  606. // Create a new widget if one does not exist
  607. const content = new APODWidget();
  608. widget = new MainAreaWidget({content});
  609. widget.id = 'apod-jupyterlab';
  610. widget.title.label = 'Astronomy Picture';
  611. widget.title.closable = true;
  612. }
  613. if (!tracker.has(widget)) {
  614. // Track the state of the widget for later restoration
  615. tracker.add(widget);
  616. }
  617. if (!widget.isAttached) {
  618. // Attach the widget to the main work area if it's not there
  619. app.shell.add(widget, 'main');
  620. }
  621. widget.content.update();
  622. // Activate the widget
  623. app.shell.activateById(widget.id);
  624. }
  625. });
  626. // Add the command to the palette.
  627. palette.addItem({ command, category: 'Tutorial' });
  628. // Track and restore the widget state
  629. let tracker = new WidgetTracker<MainAreaWidget<APODWidget>>({
  630. namespace: 'apod'
  631. });
  632. restorer.restore(tracker, {
  633. command,
  634. name: () => 'apod'
  635. });
  636. }
  637. Rebuild your extension one last time and refresh your browser tab.
  638. Execute the *Random Astronomy Picture* command and validate that the panel
  639. appears with an image in it. Refresh the browser tab again. You should
  640. see an Astronomy Picture panel reappear immediately without running the command. Close
  641. the panel and refresh the browser tab. You should then not see an Astronomy Picture tab
  642. after the refresh.
  643. .. figure:: extension_tutorial_complete.png
  644. :align: center
  645. :class: jp-screenshot
  646. :alt: The completed extension, showing the Astronomy Picture of the Day for 24 Jul 2015.
  647. The completed extension, showing the `Astronomy Picture of the Day for 24 Jul 2015 <https://apod.nasa.gov/apod/ap150724.html>`__.
  648. Refer to the `05-restore-panel-state
  649. tag <https://github.com/jupyterlab/jupyterlab_apod/tree/1.0-05-restore-panel-state>`__
  650. if your extension is not working correctly. Make a commit when the state of your
  651. extension persists properly.
  652. .. code:: bash
  653. git add .
  654. git commit -m 'Restore panel state'
  655. Congratulations! You've implemented all of the behaviors laid out at the start
  656. of this tutorial. Now how about sharing it with the world?
  657. .. _publish-your-extension-to-npmjsorg:
  658. Publish your extension to npmjs.org
  659. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  660. npm is both a JavaScript package manager and the de facto registry for
  661. JavaScript software. You can `sign up for an account on the npmjs.com
  662. site <https://www.npmjs.com/signup>`__ or create an account from the
  663. command line by running ``npm adduser`` and entering values when
  664. prompted. Create an account now if you do not already have one. If you
  665. already have an account, login by running ``npm login`` and answering
  666. the prompts.
  667. Next, open the project ``package.json`` file in your text editor. Prefix
  668. the ``name`` field value with ``@your-npm-username>/`` so that the
  669. entire field reads ``"name": "@your-npm-username/jupyterlab_apod"`` where
  670. you've replaced the string ``your-npm-username`` with your real
  671. username. Review the homepage, repository, license, and `other supported
  672. package.json <https://docs.npmjs.com/files/package.json>`__ fields while
  673. you have the file open. Then open the ``README.md`` file and adjust the
  674. command in the *Installation* section so that it includes the full,
  675. username-prefixed package name you just included in the ``package.json``
  676. file. For example:
  677. .. code:: bash
  678. jupyter labextension install @your-npm-username/jupyterlab_apod
  679. Return to your terminal window and make one more git commit:
  680. .. code:: bash
  681. git add .
  682. git commit -m 'Prepare to publish package'
  683. Now run the following command to publish your package:
  684. .. code:: bash
  685. npm publish --access=public
  686. Check that your package appears on the npm website. You can either
  687. search for it from the homepage or visit
  688. ``https://www.npmjs.com/package/@your-username/jupyterlab_apod``
  689. directly. If it doesn't appear, make sure you've updated the package
  690. name properly in the ``package.json`` and run the npm command correctly.
  691. Compare your work with the state of the reference project at the
  692. `06-prepare-to-publish
  693. tag <https://github.com/jupyterlab/jupyterlab_apod/tree/1.0-06-prepare-to-publish>`__
  694. for further debugging.
  695. You can now try installing your extension as a user would. Open a new
  696. terminal and run the following commands, again substituting your npm
  697. username where appropriate
  698. (make sure to stop the existing ``jupyter lab --watch`` command first):
  699. .. code:: bash
  700. conda create -n jupyterlab-apod jupyterlab nodejs
  701. conda activate jupyterlab-apod
  702. jupyter labextension install @your-npm-username/jupyterlab_apod
  703. jupyter lab
  704. You should see a fresh JupyterLab browser tab appear. When it does,
  705. execute the *Random Astronomy Picture* command to prove that your extension
  706. works when installed from npm.
  707. Learn more
  708. ~~~~~~~~~~
  709. You've completed the tutorial. Nicely done! If you want to keep
  710. learning, here are some suggestions about what to try next:
  711. - Add the image description that comes in the API response to the panel.
  712. - Assign a default hotkey to the *Random Astronomy Picture* command.
  713. - Make the image a link to the picture on the NASA website (URLs are of the form ``https://apod.nasa.gov/apod/apYYMMDD.html``).
  714. - Make the image title and description update after the image loads so that the picture and description are always synced.
  715. - Give users the ability to pin pictures in separate, permanent panels.
  716. - Add a setting for the user to put in their `API key <https://api.nasa.gov/api.html#authentication>`__ so they can make many more requests per hour than the demo key allows.
  717. - Push your extension git repository to GitHub.
  718. - Learn how to write :ref:`other kinds of extensions <developer_extensions>`.