pythontypescriptjupyter-notebookcommipynb

Handling .ipynb Click Event to Open Linked Document in Side-by-Side View in JupyterLab


I'm trying to implement functionality where a link in a .ipynb notebook triggers an event and opens a linked document in a split/side-by-side view in JupyterLab. Specifically, I'm using a custom plugin to listen and handle click events for any links.

Scenario:

User clicks on a link in a notebook (e.g., "Schedule Reference"). This should send an event to the custom JupyterLab plugin, which then opens the linked document in a split/side-by-side view within the JupyterLab interface.

Here’s the Python code I’m using inside the notebook to trigger the event:

from ipykernel.comm import Comm
from IPython import get_ipython

# Registering the comm target
def comm_target(comm, open_msg):
    @comm.on_msg
    def _recv(msg):
        print("Message received:", msg)

get_ipython().kernel.comm_manager.register_target('schedule_reference_link', comm_target)

# Creating a Comm object
comm = Comm(target_name='schedule_reference_link')

# Function to handle button click
def on_schedule_reference_clicked(b):
    print('Clicked')
    comm.send(data={'event': 'schedule_ref_event', 'data': 'https://example.com'})

schedule_reference = Button(description="Schedule Reference")
schedule_reference.on_click(on_schedule_reference_clicked)

On the JupyterLab plugin side, I use the following code to listen for the event:

const kernel = app.serviceManager.sessions.running().next().value.kernel;
const comm = kernel.createComm('schedule_reference_link');

comm.onMsg = (msg: { content: { data: any; }; }) => {
  const eventData = msg.content.data;
  if (eventData.event === 'schedule_ref_event') {
    console.log('Event received:', eventData.data); // supposed to capture event data from ipynb
  }
};

Issue here is below While the comm.send() function seems to execute successfully on the Python side, I'm not able to capture any event in my custom JupyterLab plugin. No event data is being logged or received in the onMsg handler in the JupyterLab plugin.

And my question is

  1. How can I correctly capture and handle the event sent from the .ipynb notebook in my JupyterLab plugin to trigger opening the linked document in a split/side-by-side view?
  2. Am I missing something in the communication setup between the Python side and the JupyterLab plugin?

Any guidance or examples of similar implementations would be greatly appreciated!


Solution

  • You don't need to use comm (e.g., from ipykernel.comm import Comm or kernel.createComm()) to communicate between your JupyterLab extension and .ipynb notebook. There's a simpler and more efficient way to achieve this using just JavaScript.

    Instead of setting up communication through comms, you can trigger events in your notebook with a single line of JavaScript. For example, you can add this line to a button click event in your .ipynb file:

    window.jupyterapp.commands.execute('jlab-render:voila');
    

    Then, in your JupyterLab extension, you can handle this event using the following approach:

    1. Define your custom command:

      const command = 'xyz';
      (window as any).jupyterlabCommands = commands;
      
      commands.addCommand(command, {
        label: 'Your Custom Label',
        caption: 'Your Custom Caption',
        execute: async (patharg) => {
          if (window.parent && (window.parent as any).jupyterlabCommands) {
            await (window.parent as any).jupyterlabCommands.execute('docmanager:open', {
              path: patharg,
              factory: 'notebook', // or 'voilad' based on your requirement
              options: {
                mode: 'split-right' // 'split-left' or other modes as needed
              }
            });
      
            await (window.parent as any).jupyterlabCommands.execute('notebook:render-with-voila', notebook);
          }
        }
      

      });

    2. Explanation: In this case, notebook:render-with-voila is a command provided by the Voilà extension that renders the notebook. You can refer to more options available in the Voilà dashboard extension for customization.

    This way, you can avoid complex comms and use straightforward JavaScript commands to integrate Voilà rendering or other actions directly into your JupyterLab plugin.