xkcd_extension_tutorial.rst 30 KB

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