Repository navigation
Add a zoom/pan viewer and image export for rendered diagrams - #5554
Merged
Merged
Conversation
`renderDiagram` and its mermaid id counter are about turning diagram code into DOM, not about the preview block that happens to host it. Export the work from `utils/diagram/render.ts` so a second caller — an export-time render that needs different mermaid options — can reuse the same dispatch instead of duplicating the five-renderer switch. Pure move: the preview block delegates, and the existing diagramPreview specs (including the renderer theme pass-through cases, which run the real dispatch against the mocked `loadRenderer`) prove behaviour is unchanged. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
A rendered diagram was an unlabelled `<div>` full of anonymous SVG shapes: a screen reader had nothing to announce. Name the preview from whatever the renderer already tells us — mermaid emits `<title>`/`<desc>` from accTitle and accDescr — and mark it `role="img"` so the shapes underneath are not read out one by one. The sizing retry that flowchart.js and js-sequence-diagrams need (their `drawSVG` lands after a font load) already owned a MutationObserver, so the naming rides along on it rather than starting a second one. Raphael stamps `<desc>Created with Raphaël 2.x</desc>` on every flowchart, which would otherwise become the diagram's name. `role` and `aria-label` are applied only on a successful render and cleared at the start of every update: the error and empty states are text, and `role="img"` would hide that text from assistive technology. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
The toolbar was pinned to `width: 90px` and tucked into the block's corner by a hand-computed `mainAxis: -95` — two numbers that only agree as long as the toolbar holds exactly two 35px actions. Measure the rendered toolbar instead and derive the offset from that, so an action can be added without anyone having to recompute the magic number. Rendering now happens before `show()` so the first `computePosition` already sees the real width; without that the float would be placed against the stale wrapper width and visibly snap into place a frame later. No visible change today: two actions still measure 90px and still land 5px inside the block's right edge, which the new e2e pins. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Diagram blocks got no hover toolbar at all: the hit test matched the blockName against `/html-block|math-block/`, so a diagram had neither the edit nor the delete action that html and math blocks have had for years. Matching against an exact set of block names fixes that — and has to be exact, because `elementsFromPoint` reaches `diagram-preview` and `diagram-container` before the `figure`, and a substring test would anchor the toolbar to the inner node. On top of edit and delete, a diagram now offers "view", which hands the host the rendered preview through a `preview-diagram` event — the same seam `preview-image` already uses for images. The host decides what a viewer looks like; the engine only says which diagram the reader asked for. The action is withheld when the preview holds no `<svg>`/`<img>`, so a diagram that failed to parse never offers to open an empty viewer. Tooltips now go through `i18n.t`. They were the only toolbar in the engine still rendering raw English strings. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Mermaid draws flowchart and class labels into a `<foreignObject>`, and Chromium refuses to paint one when an SVG is loaded as an `<img>` — the route any canvas rasteriser has to take. A host that turns a diagram into a PNG would silently get every label back blank. The same quirk already cost us #3359 and #3506 from the other direction. `renderDiagramForExport` re-renders the code with `htmlLabels: false` so the labels come out as real `<text>`. The switch rides in as a per-render `%%{init}%%` directive rather than through `mermaid.initialize()`, which is process-global state the live preview rewrites before every render — toggling it around an export would race whatever else is drawing. Verified in a real browser, since neither half was safe to assume: mermaid does emit foreignObject by default, and `securityLevel: 'strict'` does let the directive through. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
The viewer scaled about the image's centre, so zooming in on a detail in one corner pushed it off screen and the reader had to drag it back. Anchor the zoom at the cursor instead: the point under the pointer stays under the pointer. The transform arithmetic moves to `util/zoomPan.ts` as pure functions plus a small controller, which is both testable without a layout engine and the piece the diagram viewer will reuse. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
The full-screen viewer was four unrelated fragments of a 2200-line editor
component: markup in the template, a class in the middle of the script,
visibility state, and a block of CSS at the bottom. Give it a home, so the
diagram viewer that is about to grow out of it has somewhere to grow.
The overlay is now teleported to `<body>` and carries a single z-index.
`.editor-wrapper` sets `isolation: isolate`, which caps everything inside it
below muya's floats (z-index 10000) whatever z-index it declares — the
orphaned `.image-viewer { z-index: 10001 }` in index.css was an attempt at
this that could never have worked. Teleporting puts the overlay in the root
stacking context where that number means something; the dead rule goes.
Behaviour is unchanged, which `test/e2e/image-viewer.spec.ts` still pins:
same root class, same close affordance, same Space-to-open and Esc-to-close.
Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
…5508) The viewer had exactly one discoverable control — a close cross — and one gesture nobody is told about: scroll to zoom. Anyone reading a large diagram had to guess, and anyone who cannot use a mouse had nothing at all. Adds zoom out / zoom in / fit-to-window buttons and a zoom readout that returns to 100% when clicked, plus `+` `-` `0` `1` and the arrow keys. The overlay is now a real `role="dialog"`: it takes focus when it opens, gives it back when it closes, and answers the keyboard wherever focus happens to be, since it covers everything anyway. Covering the screen visually was not enough on its own — `document.elementsFromPoint` ignores stacking, so muya's mousemove-driven float tools kept re-triggering underneath the overlay. The editor drops out of hit-testing while the viewer is open, the same fix source mode uses (#4731). Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
…a diagram (#4363) Three things the sandboxed renderer cannot do for itself, and needs before it can export a diagram. - `mt::dialog::show-save` asks where to write. `showSaveDialog` existed only inside the file menu's five call sites; this is the generic form, and only the title, default path and filters cross the bridge. - `mt::clipboard::write-image` puts a PNG on the clipboard. The bridge could only carry text — this is the repo's first use of `nativeImage`. - `mt::diagram::fetch-plantuml` retrieves a PlantUML render. The renderer cannot: its CSP allows no outbound connection, and a cross-origin image taints the canvas. It sends the server and the encoded diagram separately and main composes the URL, so a free-form URL is never accepted; the scheme, the absence of credentials and the diagram alphabet are all checked, with a timeout and a size cap on the response. Writing the bytes out reuses the existing `mt::fs::write-file`. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
) A rendered diagram was a dead end: as big as the column allowed, and there was no way to get it out of the document except by exporting the whole file. Clicking the view action now opens it in the media viewer, where it can be zoomed and panned like any image, and saved as SVG, saved as PNG, or copied to the clipboard. The clone keeps the engine's block classes so the editor's theme rules still colour it, so the viewer shows what the document shows. Three things the export has to work around: - Raphael and Snap leave their text uncoloured for our stylesheet to fill in, so a standalone copy of a flowchart or sequence diagram would come out black on black under a dark theme. Their computed fill and stroke are inlined into the exported SVG; mermaid and Vega-Lite style themselves and are left alone. - Mermaid's labels live in a `<foreignObject>` that Chromium will not paint through an `<img>`, so the PNG path re-renders without HTML labels. The e2e settles it by rasterising the live svg the naive way and asserting our export carries more ink than that. - PlantUML renders server-side and the renderer can neither fetch it nor read it back off a canvas, so both formats come from the server's own `/svg/` and `/png/` endpoints through main. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
`toBeVisible` is the wrong signal for a muya float: baseFloat hides one by parking it at -9999px with `opacity: 0` rather than unmounting it, so Playwright calls a hidden toolbar visible and the click that follows fails with "element is outside of the viewport". Poll the inline opacity instead, and scroll the block into view before hovering it — the spec only passed because its diagrams happened to be on screen. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
The viewer is only discoverable by hovering a diagram, so say so where readers look up diagram syntax, along with the keys it answers to and what it can export. The three new IPC channels get a note of their own because their shape is driven by the sandbox rather than by convenience — in particular that main composes the PlantUML URL rather than accepting one. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Contributor
|
Website preview ready: https://pr-5554-marktext-website.ransixi.workers.dev Built from |
The suite was named after `SimpleImageViewer` and its header retold where every piece of it lived, down to line numbers that had already drifted. The class is gone and the pieces moved; the assertions are what carry the contract, and they are unchanged. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
This was referenced Sep 25, 2026
Six of the seven controls are icon-only, and the only thing naming them was a native `title` — which in Electron takes about a second to appear if it appears at all, so in practice the toolbar was unlabelled. Use `el-tooltip`, the same component the title bar, search and preferences already use. Two details the overlay forces: - The popper is teleported to `<body>` and Element Plus numbers poppers from 2000, which the overlay at 10002 would bury. It takes an explicit z-index. - The default 200ms hide delay leaves the previous bubble up while the next one opens, so sweeping along the toolbar showed two at once. Hiding is now immediate, and a short show delay keeps a sweep from flashing a bubble per button. `aria-label` stays on every control: the tooltip is for the eye, and a screen reader should not have to hover. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
A notification is the only channel the app has for telling you a save failed, and it was sitting at z-index 10000 — under the media viewer at 10002. Open the viewer, save a diagram, and the message naming the file (or the reason it could not be written) was painted behind the overlay. The number lives in two places: the stylesheet, and an inline value that `rePositionNotices` writes on every add to keep the newest notice on top. Only raising the stylesheet does nothing, because the inline value wins. Both now start from 10100, above every overlay in the app. Worth knowing for anyone testing this: `.mt-notification` transitions `all`, and a browser will interpolate z-index as an integer, so for ~200ms after a notice mounts its computed z-index is a number that belongs to neither source. Sampling in that window reads a notification as being on top when it is about to be buried — the e2e waits for the value to settle before hit-testing it. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Copying raised a notification, which the reader had to look away from the diagram to find — and which the overlay was covering anyway. The cursor is already on the button, so confirm there: the icon becomes a tick for three seconds and the control renames itself, which the tooltip under the cursor shows immediately. Saving keeps its notification. It carries the path, and a failure carries its reason; neither fits on a button. A tick is invisible to a screen reader, so the same message also goes to a polite live region. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Saving a diagram told you the path and left you to find it. Document export has answered this for years with a confirm button that reveals the file, so the diagram export now says the same thing the same way — same title, same sentence, same affordance — rather than inventing a second vocabulary for the same outcome. Reusing `store.editor.exportSuccess*` also avoids two keys that would have to be translated identically forever; the now-unused `mediaViewer.saved` goes. `notify()` rejects when the notice is dismissed rather than confirmed, so the reveal is guarded — otherwise closing the notice raises an unhandled rejection. (The document export call site has the same gap; left alone here, it is not this change's to fix.) Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
…tion `notify()` rejects when the notice is closed rather than confirmed, which is easy to forget at a call site and invisible when you do: the app's own handler reads `event.error`, but a rejection carries `reason`, so it falls through to `console.error` rather than to the error dialog — and never reaches the renderer-error sink these specs assert on. Watch the console directly instead. Two things the spec has to know about the notification: the close affordance only materialises while the notice is hovered, and a notice lives for ten seconds, so this runs before anything else raises one rather than racing an expiring neighbour. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
…ssal Three call sites take the promise `notify()` returns and only handle the confirm branch. Closing one of those notices instead of confirming it rejects, and nothing catches it — the deletion-URL notice after an upload, the document export notice, and the "PlantUML not found" notice. `autoUpdates.ts` already had this right; these three didn't. Rejection stays meaningful — it is how "declined" is reported, which the updater relies on — so each site says explicitly that declining is fine rather than the service swallowing it for everyone. The pandoc handler reads the outcome instead of awaiting, so declining still skips the download page. The viewer's own save notice was guarded when it was written; this is the rest of them. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
With the viewer open, pressing Backspace, Delete or Enter deleted the image being looked at. The overlay said `aria-modal="true"` and took focus, but `ImageSelection` listens on `document`, so where focus sits is irrelevant — and its `selected` image is only cleared by a document *click*, which opening the viewer with Space never produces. The deletion happened behind an opaque overlay that went on showing the image, so the reader learned about it only after pressing Escape. `pointer-events: none` had shut the mouse out; nothing had shut out the keyboard. Keys the viewer does not act on are now swallowed instead of passed down. Only propagation is stopped, not the default action, so the window's own accelerators still work. That also closes the Space path, which re-entered `open()` on an already open viewer: the second call captured the overlay itself as the element to restore focus to, and closing then blurred it to `<body>` — one Escape left the reader with no caret. `open()` now keeps the focus owner it captured the first time. Both were reachable before this branch, with the old image viewer; claiming modality is what makes them this change's to fix. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Pressing Escape mid-drag left the stage showing a grabbing hand for the rest of the session. `destroy()` dropped the document-level `mouseup` listener, so the release that resets the cursor was never seen — and the stage element is not rebuilt between opens, so the inline `cursor: grabbing` outlived the controller that wrote it. Teardown now ends the drag the same way a release does. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
`copy()` resumes after two awaits and ticks the button without checking that the button still belongs to the diagram it copied. Close the viewer inside that window and the tick — and the "copied" announcement — land on the next diagram opened, which was never copied. Only the in-viewer feedback is guarded. The notifications are not: a save that reached disk, or an export that failed, is a real outcome and should still be reported whether or not the reader is still looking. No test: the window is the length of the export, measured at ~150ms for a 40-node mermaid diagram, so a spec that closed inside it would be timing- dependent rather than a fact about the code. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Switching tabs left the viewer up over the new document. It went on showing the previous document's picture, its export buttons pointed at a node from a block tree that no longer exists, and `viewer-open` held the incoming editor at `pointer-events: none` — a document that looked ready and answered nothing. Switching tabs is a main-process accelerator, so it worked perfectly well from behind the overlay. The watcher that already hides muya's float tools on a document change is the right place: the viewer is the same kind of transient, document-bound UI. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
`onBeforeUnmount` reimplemented part of `close()` and had already drifted from it: it dropped the key listener and cleared the stage, but left `visible` set, never emitted `openChange(false)`, and never handed focus back. Unmounting while open would therefore have stranded the parent's `viewer-open` latch, holding the editor at `pointer-events: none`. Nothing unmounts this component independently today, which is why the drift was invisible. Delegating removes the second path rather than fixing it twice. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
`_block` was assigned on hover and never cleared, so the toolbar went on pinning the last preview block it floated over — including one the user had just deleted with the toolbar's own delete action, whose replacement is already in the tree. The block, its preview attachment and the rendered SVG stayed reachable until the next hover happened to overwrite the field. `selectItem` reads the block before it hides, so releasing it there is safe. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
…t once The overlay's visibility is a `v-show` inside the viewer component while the `viewer-open` class sits on the parent, so the two do not have to land in the same flush. Reading `pointer-events` the instant the overlay reports hidden therefore passed locally and failed on CI, where the parent's re-render came a beat later. These assertions are about where the app settles, so they wait for it. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
An Element Plus popper is teleported to <body> and counts as visible from the moment it is mounted, which is before floating-ui has positioned it. Measuring it in that window returns a box at the top-left corner, where the overlay is what answers the hit test — the spec failed about one run in three for a tooltip that was in fact painting on top. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
The helper aimed at the block's centre, which is off-screen once a block is bigger than the window, and then only waited for a preview toolbar to be shown. The toolbar is a singleton that stays on the block it last served, so both together let a click open whichever diagram the previous test had been on. Clamp the pointer into the viewport and require the toolbar to be tucked inside the block being hovered. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Fitting was arithmetically unable to do anything. Diagram renderers leave their root `<svg>` at `width="100%"`, which offers nothing to shrink-wrap against, so the clone laid out at the CSS default 300px however large the drawing was; the stage capped the content at 90vw/90vh on top of that and flex shrank whatever was left. The measured content therefore always fit the viewport already, `fitScale` always returned 1, and the button did nothing — on a diagram large enough to need the viewer, which is the only reason to open it. Size the clone from the `viewBox` the renderer drew against, let it lay out at that size, and fit on open so the diagram arrives readable. A reader's own zoom or pan switches the automatic fit off, so an image that finishes loading late cannot undo their first gesture. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
An svg's canvas is transparent. Under a dark theme the renderers draw pale strokes and `fill: rgba(255, 255, 255, 0.7)` text, so a saved diagram came out invisible in anything that composites onto white — a browser, Preview, a GitHub embed. The raster path already filled the editor's background behind the drawing; the vector path was handed the same colour and ignored it. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
The offscreen render was cloned out of its host and the host removed before serialization, so the clone was measured detached: no box to fall back on when a renderer omits a viewBox, and no computed style for the inlining pass to read. Serialize while it is still in the document. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Mermaid draws node labels in a `<foreignObject>`, and only a browser paints one. Every other consumer of an svg file drops it: an <img> embed on GitHub, Preview, Quick Look, Inkscape, an import into a design tool. A saved diagram arrived at those as boxes and arrows with no words in them. The raster path already re-rendered with plain `<text>` labels to get around the same refusal in Chromium; take the vector path through it too, so a saved file reads the same everywhere. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
The handler validated the shape of the server the renderer named — a scheme, no credentials, no query — but never its identity, and the configured `plantumlServer` was on the payload unused. Any host that parsed was fetched, which made a privileged main-process GET reachable from renderer-controlled input: a loopback admin port, a cloud metadata endpoint, an intranet host the sandbox cannot otherwise reach. Compare against the preference instead, and build the URL from the configured value rather than from what was sent. An unset preference means the public server, which is what muya renders against. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
…dler The rules for what may come back from a render server — the status, the content type, the size cap — were inlined in an `ipcMain.handle` callback that cannot be loaded outside Electron. Move them to a module that takes the fetch to use, so they can be exercised directly. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
…cookies `net.fetch` follows redirects by default, so pinning the request to the configured server only ever governed the first hop: the render server could answer with a 302 and have the main process fetch a loopback port or an intranet host on its behalf. It also sent the default credentials for a request that has no use for them. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
The size guard read `content-length`, and a chunked response declares
none: `Number.parseInt('')` is NaN, `NaN > MAX_BYTES` is false, so the
check passed and `arrayBuffer()` buffered the whole body before anything
looked at its size. A render server that never stops sending never
returned — the guard could only ever report a download that had already
finished.
Count the body as it is read and close the socket at the cap.
Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
`ok: false` was satisfied either way — by a refusal, or by the fetch being attempted and failing, which is the opposite outcome. Assert the refusal itself. Without the server check these three now come back as net::ERR_CONNECTION_REFUSED, from the main process having dialled a loopback port a renderer named. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
…those `aria-modal` is a claim to assistive tech, not something the browser enforces, so Tab walked out of the overlay and into the editor it is covering — where nothing is visible to focus. And the document-level capture handler swallowed Enter and Space, which meant no control could be activated once focused: the close button's own key handlers never ran, because a capture-phase stopPropagation halts the event before it reaches its target. Cycle focus through the overlay's own controls on Tab, and let Enter and Space through to the control under focus while still keeping them from the editor. The close control becomes a real button, which activates by itself and needs no handlers of its own. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
`notify()` rejects when the reader closes a notice rather than confirming it, so the two notices that report a failed save or copy left an unhandled rejection behind — the success notice was already guarded, the error ones were not. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Switching modes left the overlay up, showing a rendering of a document that is no longer on screen and holding the editor behind it inert. The same teardown already runs when the document itself changes. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
The wheel listener sat on the stage, and the toolbar and close control are layered on top of it — so the wheel was dead over exactly the place the pointer comes to rest after clicking zoom. Listen on the overlay instead; the drag still starts from the stage, so a press on a button is still a press on a button. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
The staleness check sat after the write, so a copy of one diagram that finished late still landed on the clipboard on top of a copy the reader asked for afterwards — the check only stopped it from ticking the wrong button. Decide before writing, and only against a newer copy: a lone copy still lands after the viewer has moved on, which is what was asked for. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
`finalizeRenderedDiagram` left a MutationObserver watching the preview for up to five seconds when the renderer had not produced its `<svg>` yet. Each edit within that window started another, and an earlier render's observer would go on to describe whatever a later one had put in the node. Hand the caller a way to cancel, and have the preview drop the previous render's observer before it starts the next. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
pt.json is Brazilian throughout — sixteen existing strings use "Salvar" — and the diagram viewer's four new ones arrived in European Portuguese. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
The viewer fits on open and traps Tab; a saved file paints its own background and uses text labels; and the PlantUML fetch is pinned to the configured server, refuses redirects and caps the response while reading. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Co-authored-by: Jocs <[email protected]>
3 of 6 tasks
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Closes #4363. Closes #5508.
#4363 asked for four things; this delivers two of them and explains below why the other two are not a good fit for the editor. See Scope.
The problem
A rendered diagram was a dead end. It was as large as the editor column allowed and no larger, so a complex flowchart shrank to unreadable, and the only way to get the picture out of the document was to export the whole file. Worse, the block had no hover toolbar at all:
previewToolBarmatched block names against/html-block|math-block/, so a diagram never even got the edit and delete actions that math and HTML blocks have had for years.What this adds
Hover a diagram and you get a toolbar with view / edit / delete. "View" opens the diagram full-screen, where it can be zoomed (wheel, buttons,
+-), panned (drag or arrow keys), fitted back to the window (0) or returned to actual size (1), and saved as SVG, saved as PNG, or copied to the clipboard as an image.Esccloses it.All five diagram types are covered — mermaid, Vega-Lite, PlantUML, flowchart.js and js-sequence-diagrams — in both light and dark themes.
Along the way a rendered diagram also gained an accessible name (
role="img"plus a label taken from mermaid's ownaccTitle/accDescrwhen present), and the overlay became a realrole="dialog"that takes and returns focus.Scope
In: the viewer, image export, and the a11y naming above.
Out: the node/edge inspector and the JSON/CSV export from #4363. Mermaid's public API returns only
{ diagramType }fromparse(); reaching nodes and edges means the deprecated internalmermaidAPI, it only ever works for some mermaid diagram types, and the other four renderers have no comparable model at all. Building it would mean owning a semantic model per diagram type that upstream can break at any release.Zooming is deliberately confined to the overlay. Wheel-zoom on an inline block inside a scrolling document either hijacks the scroll or fights it.
Notes for review
Four things were not safe to assume and were settled empirically; each has a test that keeps it settled.
<foreignObject>, which Chromium refuses to paint when an SVG is loaded as an<img>— the only route to a canvas. A naive PNG export loses every label. The raster path re-renders withhtmlLabels: false, delivered as a per-render%%{init}%%directive rather than throughmermaid.initialize(), which is process-global state the live preview rewrites before every render.mermaid-export-render.spec.tspins that the directive survivessecurityLevel: 'strict';diagram-viewer.spec.tsrasterises the live SVG the naive way and asserts our export carries more ink..editor-wrappersetsisolation: isolate, which caps everything inside it below muya's floats (z-index 10000) whatever z-index it declares. The orphaned.image-viewer { z-index: 10001 }inindex.csswas an earlier attempt at this that could never have worked. The overlay is now teleported to<body>. Covering the screen visually was not enough either —document.elementsFromPointignores stacking, so the editor drops out of hit-testing while the viewer is open, the same fix source mode uses ([Bug] muya UI float tools (front button, table/preview toolbars) appear in source-code mode #4731)./svg/and/png/endpoints through main. The renderer sends the server and the encoded diagram separately and main composes the URL — a free-form URL is never accepted.Known limitation: a sequence diagram exported as SVG loses the
danielbdhand-drawn face when opened outside MarkText, because the font is not embedded in the file. The PNG is unaffected, and the existing HTML export has the same gap.Verification
pnpm run lint,pnpm run typecheck,pnpm run test,pnpm -C packages/muya test,pnpm -C packages/muya check-circular— all green (muya 2074 unit, desktop 966 unit).packages/muya/e2ediagrams + ui + blocks + typing: 204 passed.diagram-viewer,media-viewer,media-ipc,image-viewer,plantuml— all passed.image-viewer.spec.tswas treated as the contract for the refactor and its assertions are unchanged.build:unpack): every one of the five diagram types exported to both SVG and PNG under both the light and the dark theme — 20 files, each opened and checked by eye.🤖 Generated with Claude Code