Skip to content

PNG export, clipboard copy and a right-click save menu - #67

Merged
CSSFrancis merged 1 commit into
mainfrom
feat/png-export
Sep 10, 2026
Merged

PNG export, clipboard copy and a right-click save menu#67
CSSFrancis merged 1 commit into
mainfrom
feat/png-export

Conversation

@CSSFrancis

@CSSFrancis CSSFrancis commented Sep 4, 2026

Copy link
Copy Markdown
Owner

Why

exportPNG has composited a full figure PNG for a while, but nothing could
reach it — it is exposed only on mount()'s handle, the postMessage protocol,
or Playwright, and anywidget discards render()'s return value. No Python entry
point, 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):

  • This panel — Copy image Ctrl+C, Save PNG, Save full view, Save at native resolution
  • Whole figure — Copy, Save PNG, Save full view
  • Theme — Current / Light / Dark, sticky per figure

The badge matters because JupyterLab, PyCharm and VS Code install their own
contextmenu and keyboard handlers and may swallow a right-click or Cmd+C
before the figure sees it. A test installs a capture-phase contextmenu
swallower, asserts right-click is dead, then asserts the badge still works.
The badge is revealed by real pointer movement, not mouseenter, so hover
chrome cannot leak into the visual baselines or the gallery thumbnails.

fig.savefig("paper.png", theme="light", scale=2)
fig.savefig("data.png", source="native", panel=plot)   # 1:1 with the data

Hosts add their own formats with handle.registerExportAction(...).

source Output
view As displayed — zoom, pan, contrast
full Whole data extent at panel resolution
native One output pixel per data pixel, decorations redrawn at that size

Two save entries. Save PNG… downloads with no permission prompt.
Save as… opens a real system dialog via showSaveFilePicker — listed only
where 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 comes
back 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.

panelId changes only the origin and extent, so a panel export is exactly the
matching 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 and TILE_THRESHOLD is 1024, so every image
large enough to want a native export is tiled
, and the page holds only a
downsampled overview. savefig re-encodes the backend at full resolution into
the 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

  • Key handlers ignored modifiers: Ctrl+C toggled the colourbar, Cmd+S
    flipped the colour scale to symlog
    .
  • exportPNG mixed CSS-scaled rects with an unscaled extent, so a figure shrunk
    to fit a narrow cell composited into the top-left corner.
  • Browser view state was never read back into Python, so save_html,
    to_html and figure_state silently reset the reader's zoom and pan
    .

Notes

47 new Playwright tests, no new baselines — exact sizes, known-LUT probes and
the literal _makeTheme constants. No gallery example: a menu and a keystroke
do 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_scale is the obvious follow-up.

@codecov-commenter

codecov-commenter commented Sep 4, 2026

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 86.86131% with 18 lines in your changes missing coverage. Please review.
✅ Project coverage is 90.97%. Comparing base (c1e8c36) to head (3420267).

Files with missing lines Patch % Lines
anyplotlib/_export.py 86.20% 16 Missing ⚠️
anyplotlib/figure/_figure.py 89.47% 2 Missing ⚠️
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.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

@CSSFrancis
CSSFrancis force-pushed the feat/png-export branch 5 times, most recently from f2f630a to c682ca5 Compare September 4, 2026 16:18
@CSSFrancis
CSSFrancis requested a lite review from Copilot September 6, 2026 12:26

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 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.

Comment thread anyplotlib/figure_esm.js
Comment on lines +10262 to +10267
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;
Comment thread anyplotlib/figure_esm.js
// 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)
@CSSFrancis
CSSFrancis merged commit 3870516 into main Sep 10, 2026
12 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants