PNG export, clipboard copy and a right-click save menu - #67
Conversation
c5624f0 to
8557a7e
Compare
Codecov Report❌ Patch coverage is
Additional details and impacted files@@ Coverage Diff @@
## main #67 +/- ##
==========================================
+ Coverage 90.85% 90.97% +0.12%
==========================================
Files 40 41 +1
Lines 4603 4709 +106
==========================================
+ Hits 4182 4284 +102
- Misses 421 425 +4 ☔ View full report in Codecov by Harness. 🚀 New features to boost your workflow:
|
f2f630a to
c682ca5
Compare
There was a problem hiding this comment.
🟡 Changes recommended
The public exportCanvas/exportPNG JS API currently accepts invalid theme values without error, which can mislead embedding hosts and should be validated before release.
Once you've addressed the issues Copilot identified, you can request another Copilot review.
Pull request overview
This PR makes PNG export functionality discoverable and usable across notebook hosts by adding an in-figure export UI (badge + context menu), clipboard copy / save workflows, and a Python Figure.savefig() entry point that drives the existing JS renderer headlessly. It also fixes several export correctness issues (CSS scale compositing and view-state reconciliation) and documents the new export API and embedding hooks.
Changes:
- Added export UI in the JS renderer (badge + right-click menu), including clipboard copy, download/picker save flows, theme override, and an export-action registry for embedding hosts.
- Added Python
Figure.savefig()powered by Playwright and native-resolution export support for tiled 2D images via temporary full-resolution re-encode. - Fixed export correctness issues (CSS
transform: scale()coordinate mismatch; snapshots now capture the reader’s live view state) and expanded docs/tests accordingly.
File summaries
| File | Description |
|---|---|
| upcoming_changes/+png-export.new_feature.rst | Towncrier entry describing new PNG export/copy features and savefig usage. |
| upcoming_changes/+export-view-sync.bugfix.rst | Towncrier entry for JS→Python view-state reconciliation in snapshots. |
| upcoming_changes/+export-key-modifiers.bugfix.rst | Towncrier entry for modifier-key guard so Ctrl/Cmd shortcuts don’t trigger plot shortcuts. |
| upcoming_changes/+export-css-scale.bugfix.rst | Towncrier entry for CSS-scale export compositing fix. |
| docs/index.rst | Adds “Exporting Images” to the docs landing page and toctree. |
| docs/exporting.rst | New end-user + embedding documentation for export menu, sources, savefig, and registry API. |
| docs/embedding.rst | Extends mount-handle reference with exportPNG, exportCanvas, and export-action registry. |
| anyplotlib/tests/test_embed/test_savefig.py | New tests for Figure.savefig(), tiled native export, and view reconciliation behavior. |
| anyplotlib/tests/test_embed/test_export_sources.py | New tests covering export sources, theme override, panel crop contract, and CSS scale behavior. |
| anyplotlib/tests/test_embed/test_export_png.py | Refactors shared helpers into _export_utils, updates mount HTML template usage. |
| anyplotlib/tests/test_embed/test_export_menu.py | New tests for the menu/badge, clipboard, download/picker flows, and action registry. |
| anyplotlib/tests/test_embed/conftest.py | Adds shared mount_page / scaled_mount_page fixtures for embedding/export tests. |
| anyplotlib/tests/test_embed/_export_utils.py | Adds shared mount template and PNG helper utilities for export test modules. |
| anyplotlib/sphinx_anywidget/_scraper.py | Reuses shared Playwright page plumbing via run_in_page() for thumbnails. |
| anyplotlib/figure/_figure.py | Adds JS→Python view-state reconciliation and public Figure.savefig() API. |
| anyplotlib/FIGURE_ESM.md | Updates the renderer section-map anchors and documents the expanded export pipeline/UI. |
| anyplotlib/figure_esm.js | Implements export pipeline (sources/theme/panel crop/native), UI (badge/menu/toast), and registry APIs. |
| anyplotlib/_repr_utils.py | Exposes window._aplRenderApi for headless export and enables iframe clipboard-write permission. |
| anyplotlib/_export.py | New headless-export implementation (savefig, run_in_page, tiled full-res re-encode helpers). |
Review details
- Files reviewed: 19/19 changed files
- Comments generated: 2
- Review effort level: Lite
💡 Add a code-review agent skill or configure MCP servers for context-aware, tailored reviews. Learn more in the docs.
| function exportCanvas(opts) { | ||
| const o = opts || {}; | ||
| const scale = (o.scale != null && o.scale > 0) ? o.scale : 1; | ||
| const source = o.source || 'view'; | ||
| const want = o.theme || 'current'; | ||
| const panelId = o.panelId || null; |
| // Export badge. Hosts (JupyterLab, PyCharm, VS Code) routinely swallow | ||
| // `contextmenu` and Cmd+C before the page sees them, so the menu must also be | ||
| // reachable by an ordinary left click. | ||
| const exportBtn = document.createElement('div'); |
The renderer already composited a complete figure PNG — `exportPNG` — but it
was reachable only from `mount()`'s handle, the standalone-HTML postMessage
protocol, or Playwright. Under plain anywidget nothing captures `render()`'s
return value, so a Jupyter kernel could not reach it at all, and there was no
Python entry point and no UI.
Right-clicking a plot now offers Copy image, Save PNG…, Save full view… and
Save at native resolution… for the clicked panel, the same for the whole
figure, and a sticky light/dark choice that applies to all of them. Ctrl/Cmd+C
copies the plot under the cursor, or the figure when none is hovered.
`Figure.savefig(path, source=, theme=, scale=, panel=)` does the same from
Python, rendering through the real JavaScript renderer in a headless browser so
the file is what the figure actually looks like — including the zoom and
contrast set interactively. Embedding hosts add their own formats through
`handle.registerExportAction({id, label, scope, handler})`.
`exportPNG` gained `panelId`, `source` and `theme`. `panelId` changes only the
origin and the extent, so a panel export is by construction the matching
sub-rectangle of the figure export. `source='full'` transiently resets the view
— and clears the detail tile, without which `_blit2d` stretches a sub-region
over the whole fit-rect. `source='native'` resizes the panel so its image area
is the data resolution and redraws the decorated stack, so the axes, colourbar,
title, markers and widgets come along with it; `p._dprOv = 1` keeps the backing
store in exact data pixels. The whole pipeline runs in one synchronous task, so
the browser never paints an intermediate state and nothing flickers.
Native export cannot work from the browser for a tiled plot: `tile='auto'` is
the default and `TILE_THRESHOLD` is 1024, so any image large enough to want it
holds only a downsampled overview plus one detail tile. The menu shows that
entry disabled with the reason; `savefig` re-encodes the backend at full
resolution into the snapshot and runs the same render headless, leaving the
live figure untouched.
Three pre-existing bugs are fixed here, because the menu makes each reachable:
- Panel key handlers matched bare letters without checking modifiers, so Ctrl+C
toggled the colourbar and Cmd+S flipped the colour scale to symlog.
- `exportPNG` mixed CSS-scaled element rects with an unscaled extent, so a
figure shrunk to fit a narrow cell composited into the top-left corner.
- Nothing read the browser's view state back into Python, so `save_html`,
`to_html` and `figure_state` silently reset the reader's zoom and pan.
Does not add an `Examples/` gallery entry — a right-click menu and a keystroke
do not appear in a static thumbnail. At native resolution the decorations keep
their normal point sizes, so an 11 px tick label is small against a 4096 px
image; raising `title_size` / `tick_size` / `*_label_size` is the workaround.
47 new Playwright tests and no new golden baselines: assertions use exact
sizes, known-LUT pixel probes and the literal `_makeTheme` constants.
Assisted-by: Claude Opus 5 (1M context)
c682ca5 to
3420267
Compare
Why
exportPNGhas composited a full figure PNG for a while, but nothing couldreach it — it is exposed only on
mount()'s handle, the postMessage protocol,or Playwright, and anywidget discards
render()'s return value. No Python entrypoint, no UI, undocumented.
What
Hover a figure for a ⤓ badge in its corner, or right-click any plot (gutters
and colourbar included — the overlay canvas does not cover those):
Ctrl+C, Save PNG, Save full view, Save at native resolutionThe badge matters because JupyterLab, PyCharm and VS Code install their own
contextmenuand keyboard handlers and may swallow a right-click orCmd+Cbefore the figure sees it. A test installs a capture-phase
contextmenuswallower, asserts right-click is dead, then asserts the badge still works.
The badge is revealed by real pointer movement, not
mouseenter, so hoverchrome cannot leak into the visual baselines or the gallery thumbnails.
Hosts add their own formats with
handle.registerExportAction(...).sourceviewfullnativeTwo save entries. Save PNG… downloads with no permission prompt.
Save as… opens a real system dialog via
showSaveFilePicker— listed onlywhere the browser supports it, because it hands the page a persistent writable
handle and so costs Chrome's "this site can see edits you make" prompt. Too
much for a plain save; right when the user asked to choose a folder.
A dialog the user closed and one that never opened both reject with
AbortError, so the name cannot separate them — one that never rendered comesback in well under 250 ms, which is the discriminator. Without that, Save would
silently do nothing in headless and in webviews that stub the API.
panelIdchanges only the origin and extent, so a panel export is exactly thematching sub-rectangle of the figure export. Theme swap, view reset, native
resize, composite and restore all run in one synchronous task, so no
intermediate state paints.
Why native cannot come from the browser
tile='auto'is the default andTILE_THRESHOLDis 1024, so every imagelarge enough to want a native export is tiled, and the page holds only a
downsampled overview.
savefigre-encodes the backend at full resolution intothe snapshot; the menu disables that entry and says why. The test uses a
one-pixel stripe pattern the averaging overview renders flat — a ramp does not
discriminate, since at 1200 px it has only 256 grey levels.
Rasterising in Python was rejected once decorations became a requirement: the
LUT, gutter geometry and label engine would all have to be reimplemented, and
would drift.
Bugs fixed
Ctrl+Ctoggled the colourbar,Cmd+Sflipped the colour scale to symlog.
exportPNGmixed CSS-scaled rects with an unscaled extent, so a figure shrunkto fit a narrow cell composited into the top-left corner.
save_html,to_htmlandfigure_statesilently reset the reader's zoom and pan.Notes
47 new Playwright tests, no new baselines — exact sizes, known-LUT probes and
the literal
_makeThemeconstants. No gallery example: a menu and a keystrokedo not show in a static thumbnail. At native resolution decorations keep their
normal point sizes, so an 11 px tick label is small against a 4096 px image;
decoration_scaleis the obvious follow-up.