xkcd_extension_tutorial.rst 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902
  1. .. _xkcd_extension_tutorial:
  2. Let's Make an xkcd JupyterLab Extension
  3. ---------------------------------------
  4. .. warning::
  5. The extension developer API is not stable and will evolve in JupyterLab
  6. releases in the near future.
  7. JupyterLab extensions add features to the user experience. This page
  8. describes how to create one type of extension, an *application plugin*,
  9. that:
  10. - Adds a "Random `xkcd <https://xkcd.com>`__ comic" command to the
  11. *command palette* sidebar
  12. - Fetches the comic image and metadata when activated
  13. - Shows the image and metadata in a tab panel
  14. By working through this tutorial, you'll learn:
  15. - How to setup an extension development environment from scratch on a
  16. Linux or OSX machine.
  17. - Windows users: You'll need to modify the commands slightly.
  18. - How to start an extension project from
  19. `jupyterlab/extension-cookiecutter-ts <https://github.com/jupyterlab/extension-cookiecutter-ts>`__
  20. - How to iteratively code, build, and load your extension in JupyterLab
  21. - How to version control your work with git
  22. - How to release your extension for others to enjoy
  23. |Completed xkcd extension screenshot|
  24. Sound like fun? Excellent. Here we go!
  25. Setup a development environment
  26. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  27. Install conda using miniconda
  28. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  29. Start by opening your web browser and downloading the latest Python 3.x
  30. `Miniconda installer <https://conda.io/miniconda.html>`__ to your home
  31. directory. When the download completes, open a terminal and create a
  32. root conda environment by running this command.
  33. .. code:: bash
  34. bash Miniconda3*.sh -b -p ~/miniconda
  35. Now activate the conda environment you just created so that you can run
  36. the ``conda`` package manager.
  37. .. code:: bash
  38. source ~/miniconda/bin/activate
  39. .. _install-nodejs-jupyterlab-etc-in-a-conda-environment:
  40. Install NodeJS, JupyterLab, etc. in a conda environment
  41. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  42. Next create a conda environment that includes:
  43. 1. the latest release of JupyterLab
  44. 2. `cookiecutter <https://github.com/audreyr/cookiecutter>`__, the tool
  45. you'll use to bootstrap your extension project structure
  46. 3. `NodeJS <https://nodejs.org>`__, the JavaScript runtime you'll use to
  47. compile the web assets (e.g., TypeScript, CSS) for your extension
  48. 4. `git <https://git-scm.com>`__, a version control system you'll use to
  49. take snapshots of your work as you progress through this tutorial
  50. It's best practice to leave the root conda environment, the one created
  51. by the miniconda installer, untouched and install your project specific
  52. dependencies in a named conda environment. Run this command to create a
  53. new environment named ``jupyterlab-ext``.
  54. .. code:: bash
  55. conda create -n jupyterlab-ext nodejs jupyterlab cookiecutter git -c conda-forge
  56. Now activate the new environment so that all further commands you run
  57. work out of that environment.
  58. .. code:: bash
  59. source ~/miniconda/bin/activate jupyterlab-ext
  60. Note: You'll need to run the command above in each new terminal you open
  61. before you can work with the tools you installed in the
  62. ``jupyterlab-ext`` environment.
  63. Create a repository
  64. ~~~~~~~~~~~~~~~~~~~
  65. Create a new repository for your extension. For example, on
  66. `GitHub <https://help.github.com/articles/create-a-repo/>`__. This is an
  67. optional step but highly recommended if you want to share your
  68. extension.
  69. Create an extension project
  70. ~~~~~~~~~~~~~~~~~~~~~~~~~~~
  71. Initialize the project from a cookiecutter
  72. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  73. Next use cookiecutter to create a new project for your extension.
  74. .. code:: bash
  75. cookiecutter https://github.com/jupyterlab/extension-cookiecutter-ts
  76. When prompted, enter values like the following for all of the
  77. cookiecutter prompts.
  78. ::
  79. author_name []: Your Name
  80. extension_name [jupyterlab_myextension]: jupyterlab_xkcd
  81. project_short_description [A JupyterLab extension.]: Show a random xkcd.com comic in a JupyterLab panel
  82. repository [https://github.com/my_name/jupyterlab_myextension]: Your repository
  83. url
  84. Note: if not using a repository, leave the field blank. You can come
  85. back and edit the repository links in the ``package.json`` file later.
  86. Change to the directory the cookiecutter created and list the files.
  87. .. code:: bash
  88. cd jupyterlab_xkcd
  89. ls
  90. You should see a list like the following.
  91. ::
  92. README.md package.json src style tsconfig.json
  93. Build and install the extension for development
  94. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  95. Your new extension project has enough code in it to see it working in
  96. your JupyterLab. Run the following commands to install the initial
  97. project dependencies and install it in the JupyterLab environment. We
  98. defer building since it will be built in the next step.
  99. .. code:: bash
  100. npm install
  101. npm run build
  102. jupyter labextension install . --no-build
  103. After the install completes, open a second terminal. Run these commands
  104. to activate the ``jupyterlab-ext`` environment and to start a JupyterLab
  105. instance in watch mode so that it will keep up with our changes as we
  106. make them.
  107. .. code:: bash
  108. source ~/miniconda/bin/activate jupyterlab-ext
  109. jupyter lab --watch
  110. See the initial extension in action
  111. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  112. JupyterLab should appear momentarily in your default web browser. If all
  113. goes well, the last bunch of messages you should see in your terminal
  114. should look something like the following:
  115. ::
  116. Webpack is watching the files…
  117. Hash: 1c15fc765a97c45c075c
  118. Version: webpack 2.7.0
  119. Time: 6423ms
  120. Asset Size Chunks Chunk Names
  121. 674f50d287a8c48dc19ba404d20fe713.eot 166 kB [emitted]
  122. af7ae505a9eed503f8b8e6982036873e.woff2 77.2 kB [emitted]
  123. fee66e712a8a08eef5805a46892932ad.woff 98 kB [emitted]
  124. b06871f281fee6b241d60582ae9369b9.ttf 166 kB [emitted]
  125. 912ec66d7572ff821749319396470bde.svg 444 kB [emitted] [big]
  126. 0.bundle.js 890 kB 0 [emitted] [big]
  127. main.bundle.js 6.82 MB 1 [emitted] [big] main
  128. 0.bundle.js.map 1.08 MB 0 [emitted]
  129. main.bundle.js.map 8.19 MB 1 [emitted] main
  130. [27] ./~/@jupyterlab/application/lib/index.js 5.66 kB {1} [built]
  131. [427] ./~/@jupyterlab/application-extension/lib/index.js 6.14 kB {1} [optional] [built]
  132. [443] ./~/@jupyterlab/pdf-extension/lib/index.js 4.98 kB {1} [optional] [built]
  133. [445] ./~/@jupyterlab/settingeditor-extension/lib/index.js 2.67 kB {1} [optional] [built]
  134. [446] ./~/@jupyterlab/shortcuts-extension/lib/index.js 3.75 kB {1} [optional] [built]
  135. [447] ./~/@jupyterlab/tabmanager-extension/lib/index.js 1.8 kB {1} [optional] [built]
  136. [448] ./~/@jupyterlab/terminal-extension/lib/index.js 7.33 kB {1} [optional] [built]
  137. [449] ./~/@jupyterlab/theme-dark-extension/lib/index.js 800 bytes {1} [optional] [built]
  138. [450] ./~/@jupyterlab/theme-light-extension/lib/index.js 804 bytes {1} [optional] [built]
  139. [451] ./~/@jupyterlab/tooltip-extension/lib/index.js 5.61 kB {1} [optional] [built]
  140. [453] ./~/es6-promise/auto.js 179 bytes {1} [built]
  141. [454] /Users/foo/workspace/xkcd/lib/index.js 353 bytes {1} [optional] [built]
  142. [455] ./~/font-awesome/css/font-awesome.min.css 892 bytes {1} [built]
  143. [860] ./build/index.out.js 35.2 kB {1} [built]
  144. + 1114 hidden modules
  145. Return to the browser. Open the JavaScript console in the JupyterLab tab
  146. by following the instructions for your browser:
  147. - `Accessing the DevTools in Google
  148. Chrome <https://developer.chrome.com/devtools#access>`__
  149. - `Opening the Web Console in
  150. Firefox <https://developer.mozilla.org/en-US/docs/Tools/Web_Console/Opening_the_Web_Console>`__
  151. You should see a message that says
  152. ``JupyterLab extension jupyterlab_xkcd is activated!`` in the console.
  153. If you do, congrats, you're ready to start modifying the the extension!
  154. If not, go back, make sure you didn't miss a step, and `reach
  155. out <README.html#getting-help>`__ if you're stuck.
  156. Note: Leave the terminal running the ``jupyter lab --watch`` command
  157. open.
  158. Commit what you have to git
  159. ^^^^^^^^^^^^^^^^^^^^^^^^^^^
  160. Run the following commands in your ``jupyterlab_xkcd`` folder to
  161. initialize it as a git repository and commit the current code.
  162. .. code:: bash
  163. git init
  164. git add .
  165. git commit -m 'Seed xkcd project from cookiecutter'
  166. Note: This step is not technically necessary, but it is good practice to
  167. track changes in version control system in case you need to rollback to
  168. an earlier version or want to collaborate with others. For example, you
  169. can compare your work throughout this tutorial with the commits in a
  170. reference version of ``jupyterlab_xkcd`` on GitHub at
  171. https://github.com/jupyterlab/jupyterlab_xkcd.
  172. Add an xkcd widget
  173. ~~~~~~~~~~~~~~~~~~
  174. Show an empty panel
  175. ^^^^^^^^^^^^^^^^^^^
  176. The *command palette* is the primary view of all commands available to
  177. you in JupyterLab. For your first addition, you're going to add a
  178. *Random xkcd comic* command to the palette and get it to show an *xkcd*
  179. tab panel when invoked.
  180. Fire up your favorite text editor and open the ``src/index.ts`` file in
  181. your extension project. Add the following import at the top of the file
  182. to get a reference to the command palette interface.
  183. .. code:: typescript
  184. import {
  185. ICommandPalette
  186. } from '@jupyterlab/apputils';
  187. You will also need to install this dependency. Run the following command in the
  188. repository root folder install the dependency and save it to your
  189. `package.json`:
  190. .. code:: bash
  191. npm install --save @jupyterlab/apputils
  192. Locate the ``extension`` object of type ``JupyterLabPlugin``. Change the
  193. definition so that it reads like so:
  194. .. code:: typescript
  195. /**
  196. * Initialization data for the jupyterlab_xkcd extension.
  197. */
  198. const extension: JupyterLabPlugin<void> = {
  199. id: 'jupyterlab_xkcd',
  200. autoStart: true,
  201. requires: [ICommandPalette],
  202. activate: (app: JupyterLab, palette: ICommandPalette) => {
  203. console.log('JupyterLab extension jupyterlab_xkcd is activated!');
  204. console.log('ICommandPalette:', palette);
  205. }
  206. };
  207. The ``requires`` attribute states that your plugin needs an object that
  208. implements the ``ICommandPalette`` interface when it starts. JupyterLab
  209. will pass an instance of ``ICommandPalette`` as the second parameter of
  210. ``activate`` in order to satisfy this requirement. Defining
  211. ``palette: ICommandPalette`` makes this instance available to your code
  212. in that function. The second ``console.log`` line exists only so that
  213. you can immediately check that your changes work.
  214. Run the following to rebuild your extension.
  215. .. code:: bash
  216. npm run build
  217. When the build completes, return to the browser tab that opened when you
  218. started JupyterLab. Refresh it and look in the console. You should see
  219. the same activation message as before, plus the new message about the
  220. ICommandPalette instance you just added. If you don't, check the output
  221. of the build command for errors and correct your code.
  222. ::
  223. JupyterLab extension jupyterlab_xkcd is activated!
  224. ICommandPalette: Palette {_palette: CommandPalette}
  225. Note that we had to run ``npm run build`` in order for the bundle to
  226. update, because it is using the compiled JavaScript files in ``/lib``.
  227. If you wish to avoid running ``npm run build`` after each change, you
  228. can open a third terminal, and run the ``npm run watch`` command from
  229. your extension directory, which will automatically compile the
  230. TypeScript files as they change.
  231. Now return to your editor. Add the following additional import to the
  232. top of the file.
  233. .. code:: typescript
  234. import {
  235. Widget
  236. } from '@phosphor/widgets';
  237. Install this dependency as well:
  238. .. code:: bash
  239. npm install --save @phosphor/widgets
  240. Then modify the ``activate`` function again so that it has the following
  241. code:
  242. .. code-block:: typescript
  243. activate: (app: JupyterLab, palette: ICommandPalette) => {
  244. console.log('JupyterLab extension jupyterlab_xkcd is activated!');
  245. // Create a single widget
  246. let widget: Widget = new Widget();
  247. widget.id = 'xkcd-jupyterlab';
  248. widget.title.label = 'xkcd.com';
  249. widget.title.closable = true;
  250. // Add an application command
  251. const command: string = 'xkcd:open';
  252. app.commands.addCommand(command, {
  253. label: 'Random xkcd comic',
  254. execute: () => {
  255. if (!widget.isAttached) {
  256. // Attach the widget to the main work area if it's not there
  257. app.shell.addToMainArea(widget);
  258. }
  259. // Activate the widget
  260. app.shell.activateById(widget.id);
  261. }
  262. });
  263. // Add the command to the palette.
  264. palette.addItem({command, category: 'Tutorial'});
  265. }
  266. The first new block of code creates a ``Widget`` instance, assigns it a
  267. unique ID, gives it a label that will appear as its tab title, and makes
  268. the tab closable by the user. The second block of code add a new command
  269. labeled *Random xkcd comic* to JupyterLab. When the command executes,
  270. it attaches the widget to the main display area if it is not already
  271. present and then makes it the active tab. The last new line of code adds
  272. the command to the command palette in a section called *Tutorial*.
  273. Build your extension again using ``npm run build`` (unless you are using
  274. ``npm run watch`` already) and refresh the browser tab. Open the command
  275. palette on the left side and type *xkcd*. Your *Random xkcd comic*
  276. command should appear. Click it or select it with the keyboard and press
  277. *Enter*. You should see a new, blank panel appear with the tab title
  278. *xkcd.com*. Click the *x* on the tab to close it and activate the
  279. command again. The tab should reappear. Finally, click one of the
  280. launcher tabs so that the *xkcd.com* panel is still open but no longer
  281. active. Now run the *Random xkcd comic* command one more time. The
  282. single *xkcd.com* tab should come to the foreground.
  283. |Empty xkcd extension panel|
  284. If your widget is not behaving, compare your code with the reference
  285. project state at the `01-show-a-panel
  286. tag <https://github.com/jupyterlab/jupyterlab_xkcd/tree/0.32-01-show-a-panel>`__.
  287. Once you've got everything working properly, git commit your changes and
  288. carry on.
  289. .. code-block:: bash
  290. git add .
  291. git commit -m 'Show xkcd command on panel'
  292. Show a comic in the panel
  293. ^^^^^^^^^^^^^^^^^^^^^^^^^
  294. You've got an empty panel. It's time to add a comic to it. Go back to
  295. your code editor. Add the following code below the lines that create a
  296. ``Widget`` instance and above the lines that define the command.
  297. .. code-block:: typescript
  298. // Add an image element to the panel
  299. let img = document.createElement('img');
  300. widget.node.appendChild(img);
  301. // Fetch info about a random comic
  302. fetch('https:////egszlpbmle.execute-api.us-east-1.amazonaws.com/prod').then(response => {
  303. return response.json();
  304. }).then(data => {
  305. img.src = data.img;
  306. img.alt = data.title;
  307. img.title = data.alt;
  308. });
  309. The first two lines create a new HTML ``<img>`` element and add it to
  310. the widget DOM node. The next lines make a request using the HTML
  311. `fetch <https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch>`__
  312. API that returns information about a random xkcd comic, and set the
  313. image source, alternate text, and title attributes based on the
  314. response.
  315. Rebuild your extension if necessary (``npm run build``), refresh your
  316. browser tab, and run the *Random xkcd comic* command again. You should
  317. now see a comic in the xkcd.com panel when it opens.
  318. |Single xkcd extension panel|
  319. Note that the comic is not centered in the panel nor does the panel
  320. scroll if the comic is larger than the panel area. Also note that the
  321. comic does not update no matter how many times you close and reopen the
  322. panel. You'll address both of these problems in the upcoming sections.
  323. If you don't see a comic at all, compare your code with the
  324. `02-show-a-comic
  325. tag <https://github.com/jupyterlab/jupyterlab_xkcd/tree/0.32-02-show-a-comic>`__
  326. in the reference project. When it's working, make another git commit.
  327. .. code:: bash
  328. git add .
  329. git commit -m 'Show a comic in the panel'
  330. Improve the widget behavior
  331. ~~~~~~~~~~~~~~~~~~~~~~~~~~~
  332. Center the comic and add attribution
  333. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  334. Open ``style/index.css`` in our extension project directory for editing.
  335. Add the following lines to it.
  336. .. code-block:: css
  337. .jp-xkcdWidget {
  338. display: flex;
  339. flex-direction: column;
  340. overflow: auto;
  341. }
  342. .jp-xkcdCartoon {
  343. margin: auto;
  344. }
  345. .jp-xkcdAttribution {
  346. margin: 20px auto;
  347. }
  348. The first rule stacks content vertically within the widget panel and
  349. lets the panel scroll when the content overflows. The other rules center
  350. the cartoon and attribution badge horizontally and space them out
  351. vertically.
  352. Return to the ``index.ts`` file. Note that there is already an import of
  353. the CSS file in the ``index.ts`` file. Modify the the ``activate``
  354. function to apply the CSS classes and add the attribution badge markup.
  355. The beginning of the function should read like the following:
  356. .. code-block:: typescript
  357. :emphasize-lines: 9,13,16-22
  358. activate: (app: JupyterLab, palette: ICommandPalette) => {
  359. console.log('JupyterLab extension jupyterlab_xkcd is activated!');
  360. // Create a single widget
  361. let widget: Widget = new Widget();
  362. widget.id = 'xkcd-jupyterlab';
  363. widget.title.label = 'xkcd.com';
  364. widget.title.closable = true;
  365. widget.addClass('jp-xkcdWidget'); // new line
  366. // Add an image element to the panel
  367. let img = document.createElement('img');
  368. img.className = 'jp-xkcdCartoon'; // new line
  369. widget.node.appendChild(img);
  370. // New: add an attribution badge
  371. img.insertAdjacentHTML('afterend',
  372. `<div class="jp-xkcdAttribution">
  373. <a href="https://creativecommons.org/licenses/by-nc/2.5/" class="jp-xkcdAttribution" target="_blank">
  374. <img src="https://licensebuttons.net/l/by-nc/2.5/80x15.png" />
  375. </a>
  376. </div>`
  377. );
  378. // Keep all the remaining fetch and command lines the same
  379. // as before from here down ...
  380. Build your extension if necessary (``npm run build``) and refresh your
  381. JupyterLab browser tab. Invoke the *Random xkcd comic* command and
  382. confirm the comic is centered with an attribution badge below it. Resize
  383. the browser window or the panel so that the comic is larger than the
  384. available area. Make sure you can scroll the panel over the entire area
  385. of the comic.
  386. |Styled xkcd panel with attribution|
  387. If anything is misbehaving, compare your code with the reference project
  388. `03-style-and-attribute
  389. tag <https://github.com/jupyterlab/jupyterlab_xkcd/tree/0.32-03-style-and-attribute>`__.
  390. When everything is working as expected, make another commit.
  391. .. code:: bash
  392. git add .
  393. git commit -m 'Add styling, attribution'
  394. Show a new comic on demand
  395. ^^^^^^^^^^^^^^^^^^^^^^^^^^
  396. The ``activate`` function has grown quite long, and there's still more
  397. functionality to add. You should refactor the code into two separate
  398. parts:
  399. 1. An ``XkcdWidget`` that encapsulates the xkcd panel elements,
  400. configuration, and soon-to-be-added update behavior
  401. 2. An ``activate`` function that adds the widget instance to the UI and
  402. decide when the comic should refresh
  403. Start by refactoring the widget code into the new ``XkcdWidget`` class.
  404. Add the following additional import to the top of the file.
  405. .. code-block:: typescript
  406. import {
  407. Message
  408. } from '@phosphor/messaging';
  409. Install this dependency:
  410. .. code:: bash
  411. npm install --save @phosphor/messaging
  412. Then add the class just below the import statements in the ``index.ts``
  413. file.
  414. .. code-block:: typescript
  415. /**
  416. * An xckd comic viewer.
  417. */
  418. class XkcdWidget extends Widget {
  419. /**
  420. * Construct a new xkcd widget.
  421. */
  422. constructor() {
  423. super();
  424. this.id = 'xkcd-jupyterlab';
  425. this.title.label = 'xkcd.com';
  426. this.title.closable = true;
  427. this.addClass('jp-xkcdWidget');
  428. this.img = document.createElement('img');
  429. this.img.className = 'jp-xkcdCartoon';
  430. this.node.appendChild(this.img);
  431. this.img.insertAdjacentHTML('afterend',
  432. `<div class="jp-xkcdAttribution">
  433. <a href="https://creativecommons.org/licenses/by-nc/2.5/" class="jp-xkcdAttribution" target="_blank">
  434. <img src="https://licensebuttons.net/l/by-nc/2.5/80x15.png" />
  435. </a>
  436. </div>`
  437. );
  438. }
  439. /**
  440. * The image element associated with the widget.
  441. */
  442. readonly img: HTMLImageElement;
  443. /**
  444. * Handle update requests for the widget.
  445. */
  446. onUpdateRequest(msg: Message): void {
  447. fetch('https://egszlpbmle.execute-api.us-east-1.amazonaws.com/prod').then(response => {
  448. return response.json();
  449. }).then(data => {
  450. this.img.src = data.img;
  451. this.img.alt = data.title;
  452. this.img.title = data.alt;
  453. });
  454. }
  455. };
  456. You've written all of the code before. All you've done is restructure it
  457. to use instance variables and move the comic request to its own
  458. function.
  459. Next move the remaining logic in ``activate`` to a new, top-level
  460. function just below the ``XkcdWidget`` class definition. Modify the code
  461. to create a widget when one does not exist in the main JupyterLab area
  462. or to refresh the comic in the exist widget when the command runs again.
  463. The code for the ``activate`` function should read as follows after
  464. these changes:
  465. .. code-block:: typescript
  466. /**
  467. * Activate the xckd widget extension.
  468. */
  469. function activate(app: JupyterLab, palette: ICommandPalette) {
  470. console.log('JupyterLab extension jupyterlab_xkcd is activated!');
  471. // Create a single widget
  472. let widget: XkcdWidget = new XkcdWidget();
  473. // Add an application command
  474. const command: string = 'xkcd:open';
  475. app.commands.addCommand(command, {
  476. label: 'Random xkcd comic',
  477. execute: () => {
  478. if (!widget.isAttached) {
  479. // Attach the widget to the main work area if it's not there
  480. app.shell.addToMainArea(widget);
  481. }
  482. // Refresh the comic in the widget
  483. widget.update();
  484. // Activate the widget
  485. app.shell.activateById(widget.id);
  486. }
  487. });
  488. // Add the command to the palette.
  489. palette.addItem({ command, category: 'Tutorial' });
  490. };
  491. Remove the ``activate`` function definition from the
  492. ``JupyterLabPlugin`` object and refer instead to the top-level function
  493. like so:
  494. .. code-block:: typescript
  495. const extension: JupyterLabPlugin<void> = {
  496. id: 'jupyterlab_xkcd',
  497. autoStart: true,
  498. requires: [ICommandPalette],
  499. activate: activate
  500. };
  501. Make sure you retain the ``export default extension;`` line in the file.
  502. Now build the extension again and refresh the JupyterLab browser tab.
  503. Run the *Random xkcd comic* command more than once without closing the
  504. panel. The comic should update each time you execute the command. Close
  505. the panel, run the command, and it should both reappear and show a new
  506. comic.
  507. If anything is amiss, compare your code with the
  508. `04-refactor-and-refresh
  509. tag <https://github.com/jupyterlab/jupyterlab_xkcd/tree/0.32-04-refactor-and-refresh>`__
  510. to debug. Once it's working properly, commit it.
  511. .. code:: bash
  512. git add .
  513. git commit -m 'Refactor, refresh comic'
  514. Restore panel state when the browser refreshes
  515. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  516. You may notice that every time you refresh your browser tab, the xkcd
  517. panel disappears, even if it was open before you refreshed. Other open
  518. panels, like notebooks, terminals, and text editors, all reappear and
  519. return to where you left them in the panel layout. You can make your
  520. extension behave this way too.
  521. Update the imports at the top of your ``index.ts`` file so that the
  522. entire list of import statements looks like the following:
  523. .. code-block:: typescript
  524. :emphasize-lines: 2,6,9-11
  525. import {
  526. JupyterLab, JupyterLabPlugin, ILayoutRestorer // new
  527. } from '@jupyterlab/application';
  528. import {
  529. ICommandPalette, InstanceTracker // new
  530. } from '@jupyterlab/apputils';
  531. import {
  532. JSONExt // new
  533. } from '@phosphor/coreutils';
  534. import {
  535. Message
  536. } from '@phosphor/messaging';
  537. import {
  538. Widget
  539. } from '@phosphor/widgets';
  540. import '../style/index.css';
  541. Install this dependency:
  542. .. code:: bash
  543. npm install --save @phosphor/coreutils
  544. Then, add the ``ILayoutRestorer`` interface to the ``JupyterLabPlugin``
  545. definition. This addition passes the global ``LayoutRestorer`` to the
  546. third parameter of the ``activate``.
  547. .. code:: typescript
  548. const extension: JupyterLabPlugin<void> = {
  549. id: 'jupyterlab_xkcd',
  550. autoStart: true,
  551. requires: [ICommandPalette, ILayoutRestorer],
  552. activate: activate
  553. };
  554. Finally, rewrite the ``activate`` function so that it:
  555. 1. Declares a widget variable, but does not create an instance
  556. immediately
  557. 2. Constructs an ``InstanceTracker`` and tells the ``ILayoutRestorer``
  558. to use it to save/restore panel state
  559. 3. Creates, tracks, shows, and refreshes the widget panel appropriately
  560. .. code-block:: typescript
  561. function activate(app: JupyterLab, palette: ICommandPalette, restorer: ILayoutRestorer) {
  562. console.log('JupyterLab extension jupyterlab_xkcd is activated!');
  563. // Declare a widget variable
  564. let widget: XkcdWidget;
  565. // Add an application command
  566. const command: string = 'xkcd:open';
  567. app.commands.addCommand(command, {
  568. label: 'Random xkcd comic',
  569. execute: () => {
  570. if (!widget) {
  571. // Create a new widget if one does not exist
  572. widget = new XkcdWidget();
  573. widget.update();
  574. }
  575. if (!tracker.has(widget)) {
  576. // Track the state of the widget for later restoration
  577. tracker.add(widget);
  578. }
  579. if (!widget.isAttached) {
  580. // Attach the widget to the main work area if it's not there
  581. app.shell.addToMainArea(widget);
  582. } else {
  583. // Refresh the comic in the widget
  584. widget.update();
  585. }
  586. // Activate the widget
  587. app.shell.activateById(widget.id);
  588. }
  589. });
  590. // Add the command to the palette.
  591. palette.addItem({ command, category: 'Tutorial' });
  592. // Track and restore the widget state
  593. let tracker = new InstanceTracker<Widget>({ namespace: 'xkcd' });
  594. restorer.restore(tracker, {
  595. command,
  596. args: () => JSONExt.emptyObject,
  597. name: () => 'xkcd'
  598. });
  599. };
  600. Rebuild your extension one last time and refresh your browser tab.
  601. Execute the *Random xkcd comic* command and validate that the panel
  602. appears with a comic in it. Refresh the browser tab again. You should
  603. see an xkcd panel appear immediately without running the command. Close
  604. the panel and refresh the browser tab. You should not see an xkcd tab
  605. after the refresh.
  606. Refer to the `05-restore-panel-state
  607. tag <https://github.com/jupyterlab/jupyterlab_xkcd/tree/0.32-05-restore-panel-state>`__
  608. if your extension is misbehaving. Make a commit when the state of your
  609. extension persists properly.
  610. .. code:: bash
  611. git add .
  612. git commit -m 'Restore panel state'
  613. Congrats! You've implemented all of the behaviors laid out at the start
  614. of this tutorial. Now how about sharing it with the world?
  615. .. _publish-your-extension-to-npmjsorg:
  616. Publish your extension to npmjs.org
  617. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  618. npm is both a JavaScript package manager and the de facto registry for
  619. JavaScript software. You can `sign up for an account on the npmjs.com
  620. site <https://www.npmjs.com/signup>`__ or create an account from the
  621. command line by running ``npm adduser`` and entering values when
  622. prompted. Create an account now if you do not already have one. If you
  623. already have an account, login by running ``npm login`` and answering
  624. the prompts.
  625. Next, open the project ``package.json`` file in your text editor. Prefix
  626. the ``name`` field value with ``@your-npm-username>/`` so that the
  627. entire field reads ``"name": "@your-npm-username/xkcd-extension"`` where
  628. you've replaced the string ``your-npm-username`` with your real
  629. username. Review the homepage, repository, license, and `other supported
  630. package.json <https://docs.npmjs.com/files/package.json>`__ fields while
  631. you have the file open. Then open the ``README.md`` file and adjust the
  632. command in the *Installation* section so that it includes the full,
  633. username-prefixed package name you just included in the ``package.json``
  634. file. For example:
  635. .. code:: bash
  636. jupyter labextension install @your-npm-username/xkcd-extension
  637. Return to your terminal window and make one more git commit:
  638. .. code:: bash
  639. git add .
  640. git commit -m 'Prepare to publish package'
  641. Now run the following command to publish your package:
  642. .. code:: bash
  643. npm publish --access=public
  644. Check that your package appears on the npm website. You can either
  645. search for it from the homepage or visit
  646. ``https://www.npmjs.com/package/@your-username/jupyterlab_xkcd``
  647. directly. If it doesn't appear, make sure you've updated the package
  648. name properly in the ``package.json`` and run the npm command correctly.
  649. Compare your work with the state of the reference project at the
  650. `06-prepare-to-publish
  651. tag <https://github.com/jupyterlab/jupyterlab_xkcd/tree/0.32-06-prepare-to-publish>`__
  652. for further debugging.
  653. |Extension page on npmjs.com|
  654. You can now try installing your extension as a user would. Open a new
  655. terminal and run the following commands, again substituting your npm
  656. username where appropriate:
  657. .. code:: bash
  658. conda create -n jupyterlab-xkcd jupyterlab nodejs
  659. source activate jupyterlab-xkcd
  660. jupyter labextension install @your-npm-username/xkcd-extension
  661. jupyter lab
  662. You should see a fresh JupyterLab browser tab appear. When it does,
  663. execute the *Random xkcd comic* command to prove that your extension
  664. works when installed from npm.
  665. Learn more
  666. ~~~~~~~~~~
  667. You've completed the tutorial. Nicely done! If you want to keep
  668. learning, here are some suggestions about what to try next:
  669. - Assign a hotkey to the *Random xkcd comic* command.
  670. - Make the image a link to the comic on https://xkcd.com.
  671. - Push your extension git repository to GitHub.
  672. - Give users the ability to pin comics in separate, permanent panels.
  673. - Learn how to write `other kinds of
  674. extensions <./extension_dev.html>`__.
  675. .. |Completed xkcd extension screenshot| image:: xkcd_tutorial_complete.png
  676. .. |Empty xkcd extension panel| image:: xkcd_tutorial_empty.png
  677. .. |Single xkcd extension panel| image:: xkcd_tutorial_single.png
  678. .. |Styled xkcd panel with attribution| image:: xkcd_tutorial_complete.png
  679. .. |Extension page on npmjs.com| image:: xkcd_tutorial_npm.png