Clipboard and Export Implementation in Vanilla-Diagram
What is copied
The selected nodes, a selected container's descendants, and the connectors
whose ends are all among them; a free end counts as among them, so a
selected connector with two free ends is copied alone. A selected connector whose node isn't selected is left out.
Nothing to copy: copy(), cut() and duplicate() return false.
The format is text/plain holding JSON:
{ "vanilla-diagram-clipboard": 1, "nodes": [ ... ], "connectors": [ ... ] }
Nodes in z order, as copies of the model's items.
Keys and API
| Keys (canvas focused) | API | |
|---|---|---|
| Copy | Ctrl/Cmd + C: the copy event |
copy() |
| Cut | Ctrl/Cmd + X: the cut event |
cut() |
| Paste | Ctrl/Cmd + V: the paste event |
paste(), a promise |
| Duplicate | Ctrl/Cmd + D | duplicate() |
- The keys use the clipboard events, which the browser fires on the
focused canvas: the handlers write and read
clipboardData, which needs no permission and works on plainhttp, so copy and paste work between pages and tabs. The handlers also fill the page's clipboard. PlainCstays connect mode. - The page's clipboard is one per page, shared by every diagram: a paste
works between two diagrams on a page.
copy()andcut()fill it and, wherenavigator.clipboardexists (a secure context), also callwriteText().paste()reads it, elsenavigator.clipboard.readText()where that exists, which may prompt (Firefox shows a paste button and waits for it). - Cut fires
vn-diagram-removingfirst, itsidslisting a selected container's descendants too; cancelled, it copies nothing. Then it removes the selection and those descendants. - Duplicate is a copy and a paste in one step, labelled
command.duplicate; it leaves the clipboard as it was. - Read-only. The keys copy; cut, paste and duplicate do nothing. A cut with a selection still prevents the browser's own cut, and writes nothing. The API works, as every API mutation does in read-only mode.
- Busy (01-web-component ยง The busy state). The keys copy nothing, cut nothing and paste nothing; a copy or cut with a selection prevents the browser's own, and writes nothing.
- A paste of text that isn't this format does nothing, and the event's default isn't prevented.
Paste
- The items are validated as a load validates them (02-model-and-commands): an unknown symbol is kept and drawn as a rectangle, a connector whose node isn't pasted, or whose known symbol lacks the port, is left out.
- Every node and connector gets a new id, and the connector ends are
remapped, and so is a
parentpasted with its node; a parent that isn't pasted is dropped. The nodes go on top, frommaxZ + 1in their order. - Each paste of the same content in the same diagram lands 16 world px right and below the previous one (the first 16px from the original); when the result's centre would be out of view, the items are centred in the view instead. Free ends and an elbow's stored points move with them; a bezier's points are offsets and don't. A node without a parent then takes the container under its pasted centre, if any (13-containers).
vn-diagram-pastingfires, cancelable, with{ nodes, connectors, source }(copies, new ids assigned); the host may change each node'stext,dataandswatch.- One
addcommand, labelledcommand.paste, adds them, and the nodes are selected: one undo step, one change set.
The pure part (VanillaDiagramClipboard: collect(), serialize(),
parse(), prepare(), pasteOffset(), translate()) loads without the core,
for tests/node/diagram-clipboard.test.js.
toSVG()
toSVG({ ids, padding, background }) resolves with a standalone SVG of the
items: default all, a listed container with its descendants, a connector
included when both its ends are (a free end counts). It is a promise: the
export is built in slices (During an export).
- In the canvas's order: the container frames first (depth-first), then the
connectors, then the other nodes, so
toSVG()andtoPNG()alike show a lane under the connectors between its children. Each route is the one drawn, around the shapes whileavoid-shapesis on. - The canvas draws only what is in view (14-large-diagrams): the export draws the items it exports that aren't drawn, and writes the text boxes and labels the far view (below zoom 0.4) leaves out, so every item is exported at full detail at any zoom; then it releases the extra items and hides the far view's text again. An export of many items holds the drawing instead (The drawing's hold).
- Each node and connector group is cloned in world coordinates, with the
arrowhead marker (as
vn-diagram-export-arrow), and without the adorners, the preview, the hit paths (a container's border and label-band hits included), the grid and the text placeholder. A selected connector is painted as unselected. - The computed paint of every element is written onto its clone (fill, stroke, widths, dash, opacity; the text's font, colour, alignment, padding, wrapping and flex centring), and every custom property removed, so the file needs neither the theme nor its tokens: a swatch's and a node style's colours included.
- The
viewBoxis the items' box (the nodes' bounds and the route points) pluspadding(default 24), andwidthandheightare its size, scaled down, the ratio kept, so that neither passes 32,767 px: librsvg (cairo), so GIMP, refuses to open an SVG one px wider ("Could not open ... for reading"). TheviewBoxkeeps the whole drawing, so the picture is the same; a viewer only opens it smaller. The 10,000-shape sample after Tidy up is 47,992 x 15,644 px, and its file now opens at 32,767 x 10,681.toPNG()'s build keeps the box's size: its canvas has its own fit. backgrounddefaults to the canvas's computed background;nullleaves it transparent.- Text in a
<switch>. Each text is written twice in a<switch>: first its HTML in a<foreignObject>, in the XHTML namespace, withrequiredExtensions="http://www.w3.org/1999/xhtml"; then the same text as SVG<text>lines, built astoPNG()'s refused-canvas copy builds them (below). A viewer draws the first branch it supports. Browsers draw the HTML, so the file looks as it did with the HTML alone (diagram-export.spec.jscompares the pixels); a viewer that draws no HTML in a<foreignObject>fails the extension and draws the lines. librsvg, which GIMP opens SVG files with, is one: without the lines its text would be blank. An empty text, or the placeholder, has no lines.
Before initializeDiagram(), after destroy(), or with nothing to draw, it
resolves with an empty <svg xmlns="http://www.w3.org/2000/svg"></svg>.
In slices. The items are listed first, in the canvas's order, then built
in slices of VanillaDiagram.EXPORT_SLICE_MS (SLICE_MS, 8ms; tests lower
it), yielding with VanillaDiagram.yieldToPage between slices; the first
slice runs before toSVG() returns. Each slice:
- draws its items the canvas leaves out, and the far view's text of the drawn ones, at full detail, places them, and grows the box with their bounds and routes;
- clones and paints each group, and measures its texts for the
<text>lines; - releases the items it drew and gives the far view back, so between slices the drawing is as it was, unless the export holds it (below);
- serializes its clones: they are appended to one detached
<svg>, which is serialized and its own start and end tags cut off, so the groups inherit the SVG namespace, declared once on the root.
At the end the root's start tag (the box's viewBox, width and height, capped as above),
the <defs> and the background <rect> are written, and the slices' markup
joined inside them. A slice sizes itself from the previous one's rate, about
4 items per ms at first.
The drawing's hold
Steps 1 and 3 change the live drawing for each drawn item a slice exports
(in the far view its text box is written and hidden again), and a slice
that draws an undrawn item places it among the drawn ones. Either way the
page renders every drawn item again in the frame after the slice, and the
slice's own paint and text reads restyle and lay them out. With the whole
10,000-shape sample drawn (fitted in view, 21,400 items) that was about
40ms a frame in Chromium and 99ms in Firefox, for about one frame every
second slice: toSVG() took 42.8s there against 5.6s with nothing drawn,
and 243.6s against 14.2s in Firefox.
So an export with VanillaDiagram.EXPORT_HOLD_ITEMS (1,000; tests lower it)
or more items left after its first slice holds the drawing
(_holdDrawing(), in the rendering), from then until its last slice:
- the drawn items leave over the next write passes, at the passes' release budget (releasing 21,400 at once took 68 to 97ms, then a frame of 162 to 191ms), but the text editor's item, which keeps its record;
- nothing enters: there is no drawn rect, so an API edit, a selection or a viewport change made meanwhile updates the indexes and is drawn when the hold ends;
- the adorners hide (outlines, handles, the focus ring, ports);
_drawnComplete()is false, so a load's draw loop or an applied layout's wait doesn't end on the emptied canvas.
Each slice then draws its items into nearly empty layers, as with nothing drawn. The first slice runs with the drawing in place, so an export of one slice, or one with fewer items left, never changes it. Under the scrim the drawing empties item by item over a few passes.
When the last slice is done the hold is released: what is still drawn is
queued for a rewrite at the zoom's detail (a zoom across 0.4 meanwhile
queued none), and the export draws the drawn rect again, a pass per frame
as a load does, before it returns: toSVG() settles, and toPNG()
rasters, with the drawing back (about 1 to 1.4s in Chromium and 5.3 to
6.5s in Firefox at the 10,000-shape fit, as a zoom-out there). Holds count:
with two exports at once the drawing comes back after the last. A load's
swap drops every hold, and a rejected export doesn't wait: destroy()
draws nothing again, and off the page the drawing comes back when the
element does. The checks between slices hold for that wait too: a load's
swap, destroy() or the element leaving the page during it rejects the
export.
One Range per export. The lines are measured with one Range for the
whole export, never one per text: a live range stays registered with its
document until it is garbage collected, and every insertion and removal in
the document updates every registered range, so a range per text made each
later append, removal and release cost more, and the 10,000-shape export
grew from about 5s to 25s.
toPNG()
toPNG({ ids, padding, background, scale }) builds that SVG (its text as
HTML only), loads it from a data: URL into an image, draws it on a canvas
at the box times scale (default devicePixelRatio), or smaller where the
browser refuses that canvas, and resolves with toBlob('image/png').
The canvas fit. Each canvas size is checked before drawing: a 2D context, then one pixel written at the far corner and read back; a thrown error is a refusal too (Firefox throws
NS_ERROR_FAILURE). The asked size first; once refused, the size capped to 32,767 px a side and 268,435,456 px, the smaller of the limits measured in Chromium (268M px; a 21,488 x 13,188 canvas, the 10,000-shape sample at scale 1, is refused) and Firefox (32,767 px a side); after that, half the area each try, down to 1 px. Firefox keeps that sample at scale 1, Chromium gets the largest capped size. No API reports the scale used: the PNG's dimensions tell it. Safari's smaller limit is unverified.The raster is one task: the image's decode and draw, about 2.3s at 10,000 shapes and 17s at 100,000 (the image's load alone 13.6s) in Chromium, with the overlay up and the page not responding meanwhile. Drawing in spatial tiles of 2,048 or 1,024 px, each a small SVG of the items meeting it, kept Firefox's frames under 100ms at 10,000 shapes, but at 100,000 a dense tile still decoded for 450 to 1,200ms in Chromium, so the picture is drawn as one image.
A
data:URL, not a Blob URL. Chromium taints the canvas for an SVG with<foreignObject>loaded from a Blob URL, and not from adata:URL; Firefox accepts both.diagram-export.spec.jspins thedata:URL path in both.A refused canvas. Where reading the canvas throws a
SecurityError(Safari is unchecked),toPNG()draws again from a copy in which each<foreignObject>is replaced by SVG<text>lines, one per line box the browser lays out for that text. The lines are measured withRange.getClientRects(), character by character, in an off-screen copy of the text at the box's world size, with its computed font and padding, at zoom 1 and unrotated, so neither the zoom nor a node's rotation skews them. The<text>goes into the node's group, which rotates it as it rotated the HTML; a label's background is drawn under its lines. The picture keeps the canvas's wrapping.It rejects when the image doesn't load, when not even a 1 px canvas is given, before
initializeDiagram(), with nothing to draw, and astoSVG()does (below).
During an export
- The job.
toSVG()andtoPNG()each begin an'export'busy job when called and end it when they settle (after the drawing is back, for an export that held it) (01-web-component): the overlay saysexporting("Exporting..."), user input is refused, and the toolbar's export buttons are off. The first slice runs before the call returns, so an export that fits in one slice ends its job in the same task and the overlay is never painted; the busy events still fire, true then false. A PNG whose build fits in one slice ends its job before the raster, which takes a few ms at that size; the refused canvas's copy with SVG text is built and drawn under a job of its own. - An open text edit is committed first, as a job beginning commits it:
the export shows the edit, which is one undo step, fires
vn-diagram-changedand is saved. A click on the toolbar's button had committed it already. Not while a load's job runs: the load leaves the edit to its swap, which closes it without committing, and so does the export; the swap rejects an export it lands during anyway. - A gesture in progress ends, as when any job begins (a
layout()too): a drag or a resize goes back, the rubber band and connect mode end, the hover ports hide. The toolbar's click has ended any gesture already, so only an API export can catch one, such as a host's thumbnail made on each save. - Changes between slices. User input is refused, but API calls work. Each slice draws its items as they are when it runs; an item removed meanwhile is left out, so an API edit or a reverted save between slices doesn't fail the export, and the picture may mix the states before and after it. While the export holds the drawing, such a change is drawn when the drawing comes back.
- A load whose swap lands during an export,
destroy(), and the element leaving the page reject it at its next slice;destroy()ends its job with no event. Off the page the computed paint is empty and the theme's stylesheet is released, so the items left would have no paint and no text. Leaving counts as it does for a layout's wait: past the end of the task, so a move in the DOM within one task doesn't stop it, and an element gone and back between two slices does.setDataManager()changes nothing drawn and doesn't affect it. - While busy. An export started during a load or a
layout()starts at once: its job joins the running ones and, the newest, labels the overlay. - There is no way to cancel an export.
Fonts. A picture drawn from an SVG can't load the page's web fonts, so text in a web font (IBM Plex Sans in the Carbon themes, when the page loads it) falls back to an installed one. Fonts are not embedded.
Cost. Both are O(n + m) per call: one clone and one computed style per
element, and one draw of each item the canvas leaves out. toSVG() adds, per
text, one off-screen layout and one measure per character, for its <text>
lines, with the export's one Range. They are not on a hot path. In the
process-flowchart-js sample, headless Chromium, with the drawing held:
toSVG() about 7s at 10,000 shapes at zoom 0.1, about 8s fitted in view
(the redraw included), and 62s at 100,000 at zoom 0.1, with no frame gap
over about 115ms (the final join included). toPNG({ scale: 1 }) about 8s
at 10,000, the raster included. Without the hold they took 13 to 15s, 43s
and 144s: every drawn item rendered again in each frame between slices
(with the canvas visibility: hidden, 28s at the fit: paint was about a
third of it)
(14-large-diagrams).