Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion .agent/skills/basalt-html/parts/diagram-export.js

Large diffs are not rendered by default.

4 changes: 2 additions & 2 deletions .agent/skills/basalt-html/parts/diagram-text.js

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

12 changes: 6 additions & 6 deletions .agent/skills/basalt-html/parts/diagram.js

Large diffs are not rendered by default.

1 change: 1 addition & 0 deletions .agent/skills/basalt-html/parts/usage/diagram-export.md
Original file line number Diff line number Diff line change
Expand Up @@ -3,4 +3,5 @@
Added for you when a diagram's JSON says `"export": true`.

- The figure's foot gets "Download SVG" and "Download PNG", and so does its viewer's (the drawn layout at 100%, whatever the zoom). Each writes the figure in the theme shown: the title and source, the drawing and the key, at rest; native SVG with its words as text and the faces embedded; the PNG at 2x.
- The PNG is drawn through an image: under a content policy, `img-src` must allow `blob:` or `data:`. Where it allows neither, "Download PNG" makes no file and the console says why; "Download SVG" needs neither.
- Without `"export": true` there are no buttons and no module. Don't add your own.
3 changes: 2 additions & 1 deletion docs/foundations.md
Original file line number Diff line number Diff line change
Expand Up @@ -2009,7 +2009,8 @@ over its lifeline; a stacked chip draws the mark before the name.
- Right to left: the figure mirrors and its words do not, drawn and stacked (stacked, the rail and the trunk run down the right, a
branch is indented from the right, and the end lines and the end gutter are on the left). Identifiers are isolated left to right as
runs; named sides swap; the arrow keys stay physical; the text art stays left to right.
- Export: a linked card's arrow is not drawn in a file.
- Export: a linked card's arrow is not drawn in a file. A PNG is drawn through an image, so under a content policy `img-src` must allow
`blob:` or `data:`; where it allows neither, `diagramToPng` rejects with an error that says so and no file is made (the SVG needs neither).

### Diagram tokens

Expand Down
2 changes: 1 addition & 1 deletion packages/react/src/architecture-diagram.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import type { DiagramFigureProps } from "./diagram-figure";
import type { ArchitectureNode, DiagramFlowEdge, DiagramGroup, DiagramPacket, DiagramPlacement, DiagramUnplaced } from "./diagram-core";

export type { ArchitectureNode, DiagramEdge, DiagramFlowEdge, DiagramGroup, DiagramLegend, DiagramLineKind, DiagramMark, DiagramMotion, DiagramNode, DiagramPacket, DiagramPlacement, DiagramSide, DiagramUnplaced } from "./diagram-core";
export type { DiagramFigureProps } from "./diagram-figure";
export type { DiagramFigureProps, DiagramLayoutInfo } from "./diagram-figure";

interface ArchitectureDiagramBase extends DiagramFigureProps {
/** The parts, in the author's order: the stacked order, the focus order and the list's. `col` and `row` place each in the drawn layout. */
Expand Down
26 changes: 24 additions & 2 deletions packages/react/src/diagram-core.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2943,10 +2943,30 @@ export function inkHtml(P: string, geo: Geo, tk: Tokens, base: string): string {
const lines = geo.lines.map((l, k) => lineMarkup(P, l, tk, ids.get(k) ?? null, l.from === l.to ? tk.radiusXs : tk.radius)).join("");
const under = lifelines ? `<svg class="${P}-lifes" width="${geo.w}" height="${geo.h}" viewBox="0 0 ${geo.w} ${geo.h}" focusable="false">${lifelines}</svg>` : "";
const svg = `${under}<svg class="${P}-svg" width="${geo.w}" height="${geo.h}" viewBox="0 0 ${geo.w} ${geo.h}" focusable="false">${defs ? `<defs>${defs}</defs>` : ""}${bars}<g class="${P}-edges">${lines}</g></svg>`;
const labels = geo.labels.map((l) => `<span class="${P}-label" data-edge="${l.i}"${l.on ? ' data-on=""' : ""}${labelLines(l.text) > 1 ? ' data-lines="2"' : ""} style="left:${Math.round(l.box.l * 100) / 100}px;top:${Math.round(l.box.t * 100) / 100}px;width:${Math.round((l.box.r - l.box.l) * 100) / 100}px">${l.text.split("\n").map(escapeHtml).join("<br>")}</span>`).join("");
// A label's place is not in the string: a style attribute in markup written as HTML is refused under a strict `style-src` (no 'unsafe-inline'), so
// placeLabels sets it through the CSSOM once the ink is in the page.
const labels = geo.labels.map((l) => `<span class="${P}-label" data-edge="${l.i}"${l.on ? ' data-on=""' : ""}${labelLines(l.text) > 1 ? ' data-lines="2"' : ""}>${l.text.split("\n").map(escapeHtml).join("<br>")}</span>`).join("");
return svg + labels;
}

/**
* Places the ink's labels (inkHtml writes them with no place): each one's box from the layout, set through the CSSOM, which a content policy allows where
* it refuses a style attribute. Called after the ink is written, and after every measure, since a label can move while the ink's string stays the same.
* The labels are paired with the layout's in order, and a label whose line is not the layout's is left alone.
*/
export function placeLabels(fig: Element, P: string, geo: Geo | null): void {
const ink = fig.querySelector(`.${P}-ink`);
if (!ink || !geo) return;
const r2 = (n: number) => `${Math.round(n * 100) / 100}px`;
const els = ink.querySelectorAll<HTMLElement>(`:scope > .${P}-label`);
els.forEach((el, k) => {
const l = geo.labels[k];
if (!l || el.dataset.edge !== String(l.i)) return;
const at: Array<[string, string]> = [["left", r2(l.box.l)], ["top", r2(l.box.t)], ["width", r2(l.box.r - l.box.l)]];
for (const [name, value] of at) if (el.style.getPropertyValue(name) !== value) el.style.setProperty(name, value);
});
}

// ---- Laying a figure out ----

export interface Measured { dyn: Dyn; geo: Geo | null; ink: string; tokens: Tokens | null; least?: number }
Expand Down Expand Up @@ -3242,7 +3262,9 @@ export function syncAttributes(el: Element, v: VNode, root = true): void {
const s = value === true ? "" : String(value);
if (el.getAttribute(k) !== s) el.setAttribute(k, s);
}
if (v.t === "svg" || (typeof v.a.class === "string" && /-(ink|ruler)$/.test(v.a.class))) return;
// The ink and the ruler are written apart from the tree, except a text sequence's transcript (its `-text-ink`): that is the tree's own, and its lines'
// indents are styles, which a content policy refuses in markup written as HTML (the page's or a script's), so they are set here through the CSSOM.
if (v.t === "svg" || (typeof v.a.class === "string" && (/-ruler$/.test(v.a.class) || (/-ink$/.test(v.a.class) && !v.a.class.endsWith("-text-ink"))))) return;
if (v.c.some((c) => typeof c !== "string" && "slot" in c)) return;
const els = [...el.children];
let at = 0;
Expand Down
56 changes: 45 additions & 11 deletions packages/react/src/diagram-export.ts
Original file line number Diff line number Diff line change
Expand Up @@ -249,18 +249,52 @@ export async function diagramToSvg(figure: HTMLElement, options: DiagramExportOp
return new Blob([svg], { type: "image/svg+xml" });
}

/** The figure as a PNG file, at `scale` (2 by default), always drawn with the faces embedded. */
/**
* The SVG as something a canvas draws. First `createImageBitmap` from the SVG as a Blob, which needs no URL and so no `img-src`, where the browser decodes
* SVG that way; then an image from a `blob:` URL, then from a `data:` URL. Under a content policy that allows neither in `img-src` there is no way left,
* and the error says so: never a broken or empty file.
*/
async function drawable(svg: string): Promise<{ source: CanvasImageSource; done: () => void }> {
const blob = new Blob([svg], { type: "image/svg+xml" });
if (typeof createImageBitmap === "function") {
try {
const bitmap = await createImageBitmap(blob);
return { source: bitmap, done: () => bitmap.close() };
} catch { /* this browser decodes no SVG Blob: an image next */ }
}
const urls: Array<() => string> = [() => URL.createObjectURL(blob), () => `data:image/svg+xml;charset=utf-8,${encodeURIComponent(svg)}`];
for (const make of urls) {
const url = make();
const done = () => { if (url.startsWith("blob:")) URL.revokeObjectURL(url); };
const img = new Image();
img.src = url;
try {
await img.decode();
return { source: img, done };
} catch { done(); }
}
throw new Error("Basalt diagramToPng: the PNG could not be drawn. A canvas draws the figure's SVG through an image, and this page refused it both as a blob: URL and as a data: URL: a content policy allows them with `img-src 'self' blob:` (or `data:`). diagramToSvg needs neither");
}

/**
* The figure as a PNG file, at `scale` (2 by default), always drawn with the faces embedded.
*
* A canvas draws SVG only through an image: under a `Content-Security-Policy`, `img-src` must allow `blob:` or `data:` (where the browser decodes an SVG
* Blob with `createImageBitmap`, neither is needed). Where the page allows neither, the promise rejects with an error that says so, and no file is made.
*/
export async function diagramToPng(figure: HTMLElement, options: DiagramExportOptions = {}): Promise<Blob> {
const { svg, w, h } = await svgText(figure, options, true);
const scale = options.scale ?? 2;
const img = new Image();
img.src = `data:image/svg+xml;charset=utf-8,${encodeURIComponent(svg)}`;
await img.decode();
const canvas = document.createElement("canvas");
canvas.width = Math.round(w * scale);
canvas.height = Math.round(h * scale);
const ctx = canvas.getContext("2d")!;
ctx.scale(scale, scale);
ctx.drawImage(img, 0, 0, w, h);
return new Promise<Blob>((resolve, reject) => canvas.toBlob((b) => (b ? resolve(b) : reject(new Error("the PNG could not be made"))), "image/png"));
const { source, done } = await drawable(svg);
try {
const canvas = document.createElement("canvas");
canvas.width = Math.round(w * scale);
canvas.height = Math.round(h * scale);
const ctx = canvas.getContext("2d")!;
ctx.scale(scale, scale);
ctx.drawImage(source, 0, 0, w, h);
return await new Promise<Blob>((resolve, reject) => canvas.toBlob((b) => (b ? resolve(b) : reject(new Error("Basalt diagramToPng: the PNG could not be made"))), "image/png"));
} finally {
done();
}
}
Loading
Loading