Jupyter Widget JavaScript Integration
Overview
This area owns the JavaScript side of Plotly's Jupyter integration and the small Python fallback used when the widget stack is unavailable. The editable sources live under js/: js/…/widget.ts is the anywidget frontend for FigureWidget, and js/…/mimeExtension.ts is the JupyterLab MIME renderer for application/vnd.plotly.v1+json. Build products are committed into Python package data: plotly/…/widgetbundle.js is the bundled anywidget module, js/…/mimeExtension.js is the bundled MIME renderer, and plotly/labextension/** is the prebuilt JupyterLab extension metadata/static output.
js/package.json defines the frontend package as jupyterlab-plotly and drives all build outputs. build:widget bundles js/…/widget.ts with plotly.js aliased to plotly.js/dist/plotly and writes ../…/widgetbundle.js; build:mimerenderer writes js/…/mimeExtension.js; build:labextension uses jupyter-builder and the jupyterlab.outputDir setting to populate plotly/labextension. plotly/…/package.json mirrors the source package metadata and adds JupyterLab _build metadata pointing at static/remoteEntry.954b872b457cd897.js and ./mimeExtension. js/webpack.config.js does not change labextension behavior, but fixes webpack module/chunk ID choices for reproducible artifact comparison. js/install.json identifies the extension as installed by the Python plotly package.
The anywidget entry point is the default export at the end of js/…/widget.ts. Its initialize(ctx) wraps ctx.model in FigureModel, installs serializers for all synced trait names, and wires trait-change handlers. Its render({ el }) creates a FigureView, calls perform_render(), and returns a cleanup callback that purges the Plotly graph. The Python side points anywidget at the generated bundle via plotly/basewidget.py, where BaseFigureWidget._esm is plotly/…/widgetbundle.js; the synced trait names in that file (_widget_data, _widget_layout, _config, _py2js_*, _js2py_*, and edit IDs) are the contract consumed by FigureModel and FigureView in js/…/widget.ts.
FigureModel in js/…/widget.ts mirrors the Python FigureWidget model. Initial _widget_data, _widget_layout, and _config are synchronized traits, but later figure edits move mostly through message traits. Python-to-JavaScript messages are delivered by setting a _py2js_* trait and then resetting it to null; JavaScript handlers such as do_addTraces, do_restyle, do_relayout, do_update, do_animate, do_deleteTraces, and do_moveTraces update the mirrored data/layout or call the corresponding Plotly.js method in the view. JavaScript-to-Python messages are sent by setting _js2py_restyle, _js2py_relayout, _js2py_update, _js2py_pointsCallback, _js2py_traceDeltas, or a layout-delta trait and then calling save_changes() through FigureView.touch().
FigureView.perform_render() in js/…/widget.ts clones the model data/layout before calling Plotly.newPlot, assigns a random viewID, sends initial trace/layout deltas, and registers Plotly.js event listeners. User-driven plotly_restyle, plotly_relayout, and plotly_update events are translated into _js2py_* messages with source_view_id; click, hover, unhover, selected, and deselect events are normalized into the points callback payload. Python-driven updates mark Plotly.js calls with _doNotReportToPy so event handlers do not echo them back, and relayout also skips applying a message back to the originating view when source_view_id matches. Deltas are computed from Plotly's _fullData/_fullLayout merged with explicit data/layout, then compared against the model state so Python can update defaults and dispatch callbacks after Plotly.js has supplied computed values.
Serialization is duplicated across the JS and Python contract. js/…/widget.ts serializes typed arrays into {dtype, shape, value} objects, deserializes Python buffer/value objects back into JavaScript typed arrays, and maps JavaScript undefined to the _undefined_ sentinel. The Python side's serializer contract is defined in plotly/serializers.py and attached to widget traits in plotly/basewidget.py; changes to the sentinel or typed-array shape must stay compatible with both sides.
js/…/mimeExtension.ts implements the non-widget JupyterLab renderer for Plotly MIME bundles. It registers application/vnd.plotly.v1+json, renders a bundled PNG first when image/png is present, lazily imports plotly.js on first interactive render, calls Plotly.react, stores a PNG fallback back into the MIME model via model.setData, adds frames with Plotly.addFrames, redraws/resizes on Lumino show/resize/update messages, and falls back to the PNG on plotly_webglcontextlost. This path is separate from FigureWidget: it renders MIME bundle figures, not anywidget trait messages.
When widget dependencies are absent, plotly/missing_anywidget.py provides a FigureWidget stand-in that subclasses BaseFigure only so imports such as plotly.graph_objs.FigureWidget can resolve. Its constructor always raises ImportError("Please install anywidget to use the FigureWidget class"). The lazy import paths in plotly/…/__init__.py and plotly/…/__init__.py select this fallback when widget imports/version checks fail, while the real widget class ultimately derives from plotly/basewidget.py and uses plotly/…/widgetbundle.js.
tests/test_core/test_figure_messages/** exercises the Python half of the widget message contract. The tests mock methods such as _send_restyle_msg, _send_relayout_msg, _send_update_msg, _send_animate_msg, _send_addTraces_msg, _send_deleteTraces_msg, and _send_moveTraces_msg to verify which payloads Python emits for property assignments, batch updates/animations, trace addition/deletion/reordering, and plotly_* calls. test_on_change.py verifies Python callback dispatch for assignments and plotly_restyle/plotly_relayout/plotly_update. These tests do not execute the bundled JavaScript, but they define the Python-side payload shapes that js/…/widget.ts must continue to accept.
Coverage/Routing
Route changes here when they touch:
js/**plotly/labextension/**- plotly/missing_anywidget.py
- plotly/…/widgetbundle.js
tests/test_core/test_figure_messages/**
Coupling
- If any trait name, message field, or edit-ID behavior changes in js/…/widget.ts, also check plotly/basewidget.py and
tests/test_core/test_figure_messages/**. Python sends and observes raw dict/list payloads on matching trait names, so a frontend rename can silently leave Python-side tests green if the mocked sender payloads were not updated. - If js/…/widget.ts changes serialization of typed arrays or
undefined, also check plotly/serializers.py. The JavaScript bundle accepts both historicalbufferand currentvaluekeys for array buffers, while Python still emitsbufferin plotly/serializers.py; removing either shape breaks saved notebooks or binary trait sync. - If js/…/widget.ts is edited, rebuild and inspect plotly/…/widgetbundle.js; if js/…/mimeExtension.ts, js/package.json, or labextension metadata changes, rebuild and inspect js/…/mimeExtension.js and
plotly/labextension/**. The shipped Python package uses the committed generated artifacts, not the TypeScript sources, at runtime. - If the Plotly MIME type or renderer registration changes in js/…/mimeExtension.ts, verify plotly/…/package.json still points JupyterLab at the built MIME extension and that js/package.json keeps
jupyterlab.mimeExtensionenabled. - If the fallback behavior in plotly/missing_anywidget.py changes, check the lazy
FigureWidgetimports in plotly/…/__init__.py and plotly/…/__init__.py. Those modules depend on importing a constructor-shaped object even when constructing it will fail with a user-facing install message.
Risks
- js/…/widget.ts and plotly/…/widgetbundle.js currently set layout deltas on
_js2py_widget_layoutDelta, whileFigureModel.defaults()defines_js2py_layoutDeltaand plotly/basewidget.py observes_js2py_layoutDelta. If that generated bundle path is used as-is, layout-default deltas may not reach Python, which can leave default layout state and layout change callbacks stale after frontend edits. tests/test_core/test_figure_messages/**validate Python payload construction but do not run js/…/widget.ts or plotly/…/widgetbundle.js. A frontend-only regression in applying_py2js_*messages, suppressing_doNotReportToPyechoes, or producing points callback payloads can pass these tests unless a JavaScript/widget integration check is run separately.