Lab extension: Open a notebook + dynamically create cell at top

I’m writing a Jupyter Lab extension. I would like to have a notebook which acts as a kind of template for some visualizations. The notebook would have all the Python code needed to produce a visualization, except without the data. I would like to dynamically add an initial cell that makes a pandas dataframe available. The idea would be, the user will interact with the Jupyter lab extension, select a dataset to visualize, at which point the extension would open the notebook file and insert the selected pandas dataframe as the first cell. How can this be done? Is there a better way to do it?

1 Like

Maybe the jupyterlab-snippets extension can serve as an example?

It inserts a new cell in the notebook when the user clicks on a snippet, using NotebookActions.insertBelow: https://github.com/QuantStack/jupyterlab-snippets/blob/286145d76cc30e5099cab7b1710d26da0171685f/src/index.ts#L121-L125

For your use case, we could imagine that the top cell of the notebook is selected first, and then a new cell is inserted above. Something like this:

const current = notebookTracker.currentWidget;
const notebook = current.content;
notebook.activeCellIndex = 0;
NotebookActions.insertAbove(notebook);
3 Likes

I have used the Jupyter specific percentage sign commands to import Jupyter Notebooks that served as libraries for that purpose. The imported functions used plenty of display invocations to create the long output. Such a solution is maybe less beautiful but it gets its work done.

I’m having trouble adapting the calls used in the snippets widget to my particular use case, as the snippets widget seems to rely on there already being a notebook open when the extension functionality is invoked. For my extension, I have a MainAreaWidget which contains HTML+JavaScript that gives the user some options. I’d like to the user to be able to make a selection from within the MainAreaWidget and trigger the opening of a “template” notebook file in a new tab, but have a cell inserted at the top of this template notebook before it is rendered, the content of the inserted cell being determined by the selection of the user. Is this possible? Do you know? Thank you!