{showList ? (
@@ -249,6 +258,8 @@ export function DiagramViewer({ kit, spec, component, source, summary, opener, o
{showList ? "Hide the list" : "View as list"}
)}
+ {/* An app's actions follow the figure (the foot decision): handed the viewer's drawing, at 100% whatever the zoom, the list open or closed. */}
+ {Actions && actions ? ({ figure: layerRef.current!.querySelector(`.${P}`)!, viewer: true, layout: laidRef.current })} /> : null}
diff --git a/packages/react/src/diagram-zoom-core.ts b/packages/react/src/diagram-zoom-core.ts
index 2c26e5c7..27ca76d3 100644
--- a/packages/react/src/diagram-zoom-core.ts
+++ b/packages/react/src/diagram-zoom-core.ts
@@ -326,6 +326,16 @@ export function attachZoom(host: ZoomHost): ZoomController {
};
}
+/**
+ * What the zoom fits and scrolls (the one-column ruling, diagrams-cimip): the drawing's own box at 100%, not the width it was laid out in. A drawn column
+ * capped at size-breakpoint-container is narrower than its figure; every other drawing is as wide as it. The height is the figure's, which in the viewer
+ * holds the drawing alone.
+ */
+export function drawnSize(fig: HTMLElement): [number, number] {
+ const drawing = fig.querySelector(":scope > [class$='-drawing']");
+ return [drawing?.offsetWidth || fig.offsetWidth, fig.offsetHeight];
+}
+
/** Brings a focused card into the stage's view by the least distance, `margin` clear of its edges (9.5). */
export function revealIn(stage: HTMLElement, el: Element, margin: number): void {
const s = stage.getBoundingClientRect();
diff --git a/packages/react/src/flowchart-diagram.tsx b/packages/react/src/flowchart-diagram.tsx
index 585d37da..7962dc93 100644
--- a/packages/react/src/flowchart-diagram.tsx
+++ b/packages/react/src/flowchart-diagram.tsx
@@ -5,6 +5,7 @@ import type { DiagramFigureProps } from "./diagram-figure";
import type { DiagramEdge, DiagramShapeLabels, FlowchartNode, DiagramPlacement, DiagramUnplaced } from "./diagram-core";
export type { DiagramEdge, DiagramLegend, DiagramLineKind, DiagramShapeLabels, DiagramSide, FlowchartNode } from "./diagram-core";
+export type { DiagramAction, DiagramActionContext } from "./diagram-figure";
interface FlowchartDiagramBase extends DiagramFigureProps {
/** The steps in the author's order; the first is the start. A shape carries the type: a step (the default), a decision or a terminal. */
diff --git a/packages/react/src/index.ts b/packages/react/src/index.ts
index 255314f2..671a1d66 100644
--- a/packages/react/src/index.ts
+++ b/packages/react/src/index.ts
@@ -94,7 +94,7 @@ export { ChartGroup, TimeChart } from "./chart";
export { trailingMean } from "./trailing-mean";
export type { ChartGroupProps, ChartKind, ChartLaneGeometry, ChartPlan, ChartSeries, TimeChartProps } from "./chart";
export { ArchitectureDiagram } from "./architecture-diagram";
-export type { ArchitectureDiagramProps, ArchitectureNode, DiagramEdge, DiagramFigureProps, DiagramFlowEdge, DiagramGroup, DiagramLayoutInfo, DiagramLegend, DiagramLineKind, DiagramMark, DiagramMotion, DiagramNode, DiagramPacket, DiagramPlacement, DiagramSide, DiagramUnplaced } from "./architecture-diagram";
+export type { ArchitectureDiagramProps, ArchitectureNode, DiagramAction, DiagramActionContext, DiagramEdge, DiagramFigureProps, DiagramFlowEdge, DiagramGroup, DiagramLayoutInfo, DiagramLegend, DiagramLineKind, DiagramMark, DiagramMotion, DiagramNode, DiagramPacket, DiagramPlacement, DiagramSide, DiagramUnplaced } from "./architecture-diagram";
export { FlowchartDiagram } from "./flowchart-diagram";
export type { DiagramShapeLabels, FlowchartDiagramProps, FlowchartNode } from "./flowchart-diagram";
export { DataFlowDiagram } from "./data-flow-diagram";
diff --git a/packages/react/src/schema-diagram.tsx b/packages/react/src/schema-diagram.tsx
index 6a272d58..bdbdcb46 100644
--- a/packages/react/src/schema-diagram.tsx
+++ b/packages/react/src/schema-diagram.tsx
@@ -5,6 +5,7 @@ import type { DiagramFigureProps } from "./diagram-figure";
import type { SchemaTable, DiagramPlacement, DiagramUnplaced } from "./diagram-core";
export type { DiagramCardinality, DiagramCardinalityPair, DiagramLegend, SchemaColumn, SchemaTable } from "./diagram-core";
+export type { DiagramAction, DiagramActionContext } from "./diagram-figure";
interface SchemaDiagramBase extends DiagramFigureProps {
/**
diff --git a/packages/react/src/sequence-diagram.tsx b/packages/react/src/sequence-diagram.tsx
index 8c4c55b5..5dfc992f 100644
--- a/packages/react/src/sequence-diagram.tsx
+++ b/packages/react/src/sequence-diagram.tsx
@@ -5,6 +5,7 @@ import type { DiagramFigureProps } from "./diagram-figure";
import type { SequenceParticipant, SequenceStep, DiagramFrameLabels } from "./diagram-core";
export type { DiagramFrameLabels, DiagramLegend, DiagramLineKind, SequenceMessage, SequenceParticipant, SequenceStep } from "./diagram-core";
+export type { DiagramAction, DiagramActionContext } from "./diagram-figure";
export interface SequenceDiagramProps extends DiagramFigureProps {
/** The participants, start to end. `short` names one in the stacked list. */
diff --git a/packages/react/src/styles/components.css b/packages/react/src/styles/components.css
index 1f165572..ade6c2d5 100644
--- a/packages/react/src/styles/components.css
+++ b/packages/react/src/styles/components.css
@@ -5035,6 +5035,12 @@
align-items: start;
max-width: none;
}
+ /* One column is at most size-breakpoint-container wide, drawn or stacked (the one-column ruling, diagrams-cimip): a drawn layout of one column (not a
+ sequence's, whose columns are participants) is capped on the start edge as the stack is, or at its column's least width where that is more (--_one,
+ written by the engine with the layout, so the cap is in place before the drawing is measured). Before script the same cap, at the token. The room
+ beside it is open page. */
+ .basalt-diagram:not([data-type="sequence"])[data-cols="1"] > .basalt-diagram-drawing { --_d-max: var(--_drawn) max(var(--basalt-size-breakpoint-container), var(--_one, var(--basalt-size-breakpoint-container))); }
+ .basalt-diagram[data-type="schema"][data-cols="1"] > .basalt-diagram-drawing { max-width: var(--_d-max, none); }
/* A schema that draws cardinality marks (DECISIONS 306, 1.1): its column gap is space-12 plus space-3, so three lanes keep 18 from its tables. */
.basalt-diagram[data-type="schema"][data-marks] > .basalt-diagram-drawing { --_col-gap: calc(var(--basalt-space-12) + var(--basalt-space-3)); }
.basalt-diagram[data-type="sequence"] > .basalt-diagram-drawing { display: flex; gap: 0; }
@@ -5647,7 +5653,8 @@
(DECISIONS 292, 2.6; every focal node, with a mark or without, DECISIONS 298). */
@media print {
.basalt-diagram-svg, .basalt-diagram-lifes, .basalt-diagram-swatch, .basalt-diagram-arrow, .basalt-diagram-mark, .basalt-diagram-node[data-focal] { -webkit-print-color-adjust: exact; print-color-adjust: exact; }
- .basalt-diagram-hint, .basalt-diagram-tap-hint, .basalt-diagram-clear, .basalt-diagram-download { display: none !important; }
+ /* The foot does not print (the foot decision, 3.2): one rule, so no control in it, an app's own actions included, is drawn on paper. */
+ .basalt-diagram-hint, .basalt-diagram-tap-hint, .basalt-diagram-foot { display: none !important; }
/* A figure prints untraced (DECISIONS 306, 1.7): every line, head and label in its resting ink, over a trace, a touch trace or a quiet run. */
.basalt-diagram .basalt-diagram-edge :is(.basalt-diagram-line, .basalt-diagram-tip[data-open]) { stroke: var(--basalt-diagram-edge) !important; }
.basalt-diagram .basalt-diagram-edge .basalt-diagram-line[data-kind="main"] { stroke: var(--basalt-diagram-edge-main) !important; }
@@ -5792,6 +5799,9 @@
/* The sizer is as large as the zoomed drawing, plus the padding; its auto margins centre a drawing smaller than the stage and resolve to 0 past it. */
.basalt-diagram-sizer { position: relative; flex: none; box-sizing: content-box; margin: auto; padding: var(--_pad); }
.basalt-diagram-sizer[hidden] { display: none; }
+ /* The sizer is the drawing's own box at the zoom (the one-column ruling): a capped column's layer is wider than its drawing, and what is past the drawing
+ is empty, so it is clipped and adds no scroll extent. */
+ .basalt-diagram-sizer { overflow: clip; }
.basalt-diagram-layer { position: absolute; top: var(--_pad); inset-inline-start: var(--_pad); transform-origin: 0 0; user-select: none; -webkit-user-select: none; -webkit-touch-callout: none; }
.basalt-diagram-layer:dir(rtl) { transform-origin: 100% 0; }
/* The viewer's figure shows its drawing alone: the dialog holds its title, its key, its hint and its controls. */
@@ -5804,13 +5814,16 @@
.basalt-diagram-viewer-key .basalt-diagram-key { padding-block-start: 0; border-top: 0; }
.basalt-diagram-viewer-key[data-layout="drawn"] .basalt-diagram-entry[data-when="stacked"], .basalt-diagram-viewer-key[data-layout="stacked"] .basalt-diagram-entry[data-when="drawn"], .basalt-diagram-viewer-key[data-bare] .basalt-diagram-entry[data-line] { display: none; }
.basalt-diagram-viewer-row { display: flex; flex-wrap: wrap; align-items: center; gap: var(--basalt-space-2); }
- .basalt-diagram-zoom { display: flex; align-items: center; gap: var(--basalt-space-1); }
+ /* The end group's auto margin is the zoom group's end (the foot decision, 3.1): where the hint shows it grows first and the margin is 0; where it does not
+ (touch) the margin sends the end group to the row's end; and an end group on a row of its own has none, so it starts on the start edge. */
+ .basalt-diagram-zoom { display: flex; align-items: center; gap: var(--basalt-space-1); margin-inline-end: auto; }
/* The level between the two buttons, its width held for "400%" so the buttons never move. */
.basalt-diagram-level { display: inline-grid; justify-items: center; color: var(--basalt-text-secondary); font: var(--basalt-font-weight-regular) var(--basalt-text-sm-size) / var(--basalt-text-sm-line-height) var(--basalt-font-family-sans); font-variant-numeric: tabular-nums; }
.basalt-diagram-level::before { content: attr(data-reserve); grid-area: 1 / 1; visibility: hidden; }
.basalt-diagram-level > span { grid-area: 1 / 1; }
.basalt-diagram-viewer-hint { flex: 1 1 auto; min-width: 0; }
- .basalt-diagram-viewer-end { display: flex; gap: var(--basalt-space-2); margin-inline-start: auto; }
+ /* The end group ("View as list", then the skill's downloads or an app's actions) wraps and is never cut. */
+ .basalt-diagram-viewer-end { display: flex; flex-wrap: wrap; gap: var(--basalt-space-2); min-width: 0; }
@media (pointer: coarse) {
.basalt-diagram-zoom .basalt-button, .basalt-diagram-viewer-end .basalt-button { min-height: var(--basalt-size-tap-min); min-width: var(--basalt-size-tap-min); }
}
diff --git a/packages/react/test/content-policy.test.mjs b/packages/react/test/content-policy.test.mjs
index 06c8124c..b22c311b 100644
--- a/packages/react/test/content-policy.test.mjs
+++ b/packages/react/test/content-policy.test.mjs
@@ -225,7 +225,7 @@ const EXPORT = `${DIAGRAMS}
import { diagramToPng } from "./dist/diagram-export.js";
window.png = () => diagramToPng(document.getElementById("arch")).then(
(blob) => createImageBitmap(blob).then((image) => ({ type: blob.type, width: image.width, height: image.height })),
- (error) => ({ error: error.message }));`;
+ (error) => ({ error: error.message, name: error.name }));`;
describe("a diagram's PNG under img-src", () => {
for (const [name, images, drawn] of [["'self'", "'self'", false], ["'self' blob:", "'self' blob:", true], ["'self' data:", "'self' data:", true]]) {
@@ -242,6 +242,8 @@ describe("a diagram's PNG under img-src", () => {
assert.ok(got.width >= 2 * width, `${got.width} is at 2x of ${width}`);
} else {
assert.match(got.error, /img-src 'self' blob:/);
+ // Named, so the skill's note tells the policy from any other failure without reading the words (diagrams-cimip ruling 2).
+ assert.equal(got.name, "DiagramPolicyError");
assert.equal(got.width, undefined);
}
assert.deepEqual(errors, []);
@@ -251,3 +253,126 @@ describe("a diagram's PNG under img-src", () => {
});
}
});
+
+// The skill's "Download PNG" refused (diagrams-cimip ruling 2), on a composed page served under `img-src 'self'`: the note under the foot's buttons, the
+// button switched off in place, no second try on the page, spoken once; "Download SVG" still saves; the viewer's foot does the same; the note neither
+// prints nor is in a file. Written while tests are paused (DECISIONS 359): not yet run. The ruling is the decider's alone (no draft, no check).
+const REFUSED_WORDS = "This page's security policy blocks the PNG. Download SVG still works.";
+async function skillPolicyPage() {
+ const { compose } = await import(pathToFileURL(path.join(pkg, "..", "..", ".agent", "skills", "basalt-html", "compose.mjs")).href);
+ const data = JSON.parse(fs.readFileSync(path.join(pkg, "test", "fixtures", "cimip-diagrams.json"), "utf8"));
+ const figure = (id, d) => ``;
+ const html = compose(`Policy${figure("one", data.architecture)}${figure("two", data.flowchart)}`).html;
+ const context = await browser.newContext({ viewport: { width: 1440, height: 900 } });
+ await context.addInitScript(() => {
+ window.__refused = [];
+ window.__saved = [];
+ document.addEventListener("securitypolicyviolation", (event) => window.__refused.push(`${event.effectiveDirective} ${event.blockedURI}`));
+ // The files the module saves, read where it hands them to an anchor (blob: and data: images are refused here; a blob URL for a download is not).
+ const make = URL.createObjectURL.bind(URL);
+ URL.createObjectURL = (blob) => { window.__saved.push(blob); return make(blob); };
+ });
+ // Only images are held to the policy: the skill's page is inline script and style by design.
+ await context.route(`${ORIGIN}/**`, (route) => route.fulfill({ status: 200, contentType: "text/html", headers: { "content-security-policy": "img-src 'self'" }, body: html }));
+ const page = await context.newPage();
+ const errors = [];
+ page.on("pageerror", (error) => errors.push(error.message));
+ await page.goto(`${ORIGIN}/`);
+ await page.waitForSelector("#two .diagram-download");
+ await page.evaluate(() => document.fonts.ready);
+ return { page, context, errors };
+}
+const footOf = (id) => `#${id} > .diagram-foot`;
+const pngIn = (scope) => `${scope} .diagram-download:has-text("Download PNG")`;
+const svgIn = (scope) => `${scope} .diagram-download:has-text("Download SVG")`;
+
+describe("the skill's Download PNG under img-src 'self' (ruling 2)", () => {
+ test("a press leaves no file, shows the note with its words, switches the button off in place, keeps focus, and is spoken once", async () => {
+ const { page, context, errors } = await skillPolicyPage();
+ try {
+ const png = page.locator(pngIn(footOf("one")));
+ const before = await png.boundingBox();
+ await png.focus();
+ await png.press("Enter");
+ await page.waitForSelector(`${footOf("one")} > .diagram-export-note`);
+ await page.waitForTimeout(100);
+ const got = await page.evaluate(() => {
+ const foot = document.querySelector("#one > .diagram-foot"), note = foot.querySelector(":scope > .diagram-export-note");
+ const png = [...foot.querySelectorAll(".diagram-download")].find((b) => b.textContent.includes("PNG"));
+ const buttons = [...foot.querySelectorAll("button")];
+ const cs = getComputedStyle(note);
+ return {
+ words: note.textContent, last: foot.lastElementChild === note, tag: note.tagName, disabled: png.getAttribute("aria-disabled"), describedBy: png.getAttribute("aria-describedby"), noteId: note.id,
+ focused: document.activeElement === png, live: document.getElementById("basalt-live")?.textContent, saved: window.__saved.map((b) => b.type),
+ under: note.getBoundingClientRect().top - Math.max(...buttons.map((b) => b.getBoundingClientRect().bottom)), size: cs.fontSize, weight: cs.fontWeight, wrap: cs.textWrap || cs.textWrapStyle,
+ };
+ });
+ assert.equal(got.words, REFUSED_WORDS);
+ assert.equal(got.tag, "P");
+ assert.ok(got.last, "the note is the last thing in the foot");
+ assert.equal(got.disabled, "true");
+ assert.equal(got.describedBy, got.noteId);
+ assert.ok(got.focused, "the button keeps focus");
+ assert.equal(got.live, REFUSED_WORDS, "spoken through the page's announcer");
+ assert.deepEqual(got.saved, [], "no file");
+ assert.ok(got.under > 0, "under the last row of buttons");
+ assert.equal(got.size, "12px");
+ assert.equal(got.weight, "400");
+ assert.match(String(got.wrap), /balance/);
+ const after = await png.boundingBox();
+ assert.deepEqual([after.x, after.width], [before.x, before.width], "the button keeps its seat and width");
+ // A second press does nothing: no new refusal, no new words.
+ const refusals = (await refused(page)).length;
+ await page.evaluate(() => { document.getElementById("basalt-live").textContent = ""; });
+ await png.click();
+ await page.waitForTimeout(100);
+ assert.equal((await refused(page)).length, refusals, "no second try");
+ assert.equal(await page.evaluate(() => document.getElementById("basalt-live").textContent), "", "spoken once");
+ assert.deepEqual(errors, []);
+ } finally {
+ await context.close();
+ }
+ });
+
+ test("a second figure's first press answers at once with no new violation; Download SVG still saves; the note neither prints nor is in a file", async () => {
+ const { page, context } = await skillPolicyPage();
+ try {
+ await page.locator(pngIn(footOf("one"))).click();
+ await page.waitForSelector(`${footOf("one")} > .diagram-export-note`);
+ const refusals = (await refused(page)).length;
+ await page.locator(pngIn(footOf("two"))).click();
+ await page.waitForSelector(`${footOf("two")} > .diagram-export-note`);
+ assert.equal((await refused(page)).length, refusals, "the second figure did not try");
+ assert.equal(await page.locator(pngIn(footOf("two"))).getAttribute("aria-disabled"), "true");
+ await page.locator(svgIn(footOf("one"))).click();
+ await page.waitForFunction(() => window.__saved.some((b) => b.type === "image/svg+xml"));
+ const svg = await page.evaluate(() => window.__saved.find((b) => b.type === "image/svg+xml").text());
+ assert.ok(!svg.includes("security policy"), "the note is in no file");
+ assert.equal(await page.locator(`${footOf("one")} > .diagram-export-note`).textContent(), REFUSED_WORDS, "the refusal stays");
+ await page.emulateMedia({ media: "print" });
+ assert.equal(await page.locator(`${footOf("one")} > .diagram-export-note`).evaluate((el) => el.getClientRects().length), 0, "the note does not print");
+ } finally {
+ await context.close();
+ }
+ });
+
+ test("the viewer's foot does the same: the note last in the controls' row, on the end edge, spoken through the viewer's status", async () => {
+ const { page, context } = await skillPolicyPage();
+ try {
+ await page.locator("#one .diagram-expand").click();
+ await page.waitForSelector("dialog.diagram-viewer[open] figure.diagram[data-layout]");
+ await page.evaluate(() => Promise.all(document.getAnimations().map((a) => a.finished.catch(() => {}))));
+ await page.locator(pngIn("dialog.diagram-viewer[open] .diagram-viewer-end")).click();
+ await page.waitForSelector("dialog.diagram-viewer[open] .diagram-viewer-row > .diagram-export-note");
+ await page.waitForTimeout(100);
+ const got = await page.evaluate(() => {
+ const d = document.querySelector("dialog.diagram-viewer[open]"), row = d.querySelector(".diagram-viewer-row"), note = row.querySelector(":scope > .diagram-export-note");
+ const png = [...d.querySelectorAll(".diagram-viewer-end .diagram-download")].find((b) => b.textContent.includes("PNG"));
+ return { words: note.textContent, last: row.lastElementChild === note, align: getComputedStyle(note).textAlign, disabled: png.getAttribute("aria-disabled"), describedBy: png.getAttribute("aria-describedby") === note.id, status: d.querySelector('[role="status"]').textContent };
+ });
+ assert.deepEqual(got, { words: REFUSED_WORDS, last: true, align: "end", disabled: "true", describedBy: true, status: REFUSED_WORDS });
+ } finally {
+ await context.close();
+ }
+ });
+});
diff --git a/packages/react/test/diagram-actions.test.mjs b/packages/react/test/diagram-actions.test.mjs
new file mode 100644
index 00000000..ef031e36
--- /dev/null
+++ b/packages/react/test/diagram-actions.test.mjs
@@ -0,0 +1,357 @@
+// An app's own actions in a diagram's foot (the foot decision, diagrams-cimip, section 6): the order, nothing moving, the viewer, the end group's wrap, the
+// export of the viewer's drawing, the settle before onSelect, busy, disabled and id, print, before script and the development warnings, and the sizes. In
+// Chromium against the built package. Written while tests are paused (DECISIONS 359): not yet run. The implementation hasn't been reviewed.
+import assert from "node:assert/strict";
+import fs from "node:fs";
+import { createRequire } from "node:module";
+import path from "node:path";
+import { pathToFileURL } from "node:url";
+import { after, before, describe, test } from "node:test";
+
+import * as esbuild from "esbuild";
+
+import { measureExport } from "./export-sizes.mjs";
+import { fixturePage, launch, pkg } from "./support.mjs";
+
+const require = createRequire(import.meta.url);
+const P = "basalt-diagram";
+const font = (file) => fs.readFileSync(path.join(pkg, "dist", "fonts", file)).toString("base64");
+const FONTS = `@font-face{font-family:"Geist";src:url(data:font/woff2;base64,${font("Geist-Variable.woff2")}) format("woff2");font-weight:100 900}@font-face{font-family:"Geist Mono";src:url(data:font/woff2;base64,${font("GeistMono-Variable.woff2")}) format("woff2");font-weight:100 900}`;
+const PAGE = `${FONTS} body{background:var(--basalt-surface-page);margin:0;padding:16px;box-sizing:border-box} #root{max-width:1104px;margin:0 auto}`;
+const THREE = ["Download the diagram", "Copy link", "Open in draw.io"];
+
+let browser;
+before(async () => { browser = await launch(); });
+after(async () => { await browser?.close(); });
+
+// The host: figures from `window.__set(list)`, each `{ key, data: "still" | "kit", actions: [{ label, id?, disabled?, inViewer?, wait?, svg? }], hidden? }`.
+// Every press is logged in `window.__log`, with what it was handed. `wait` returns a promise the test settles (`window.__settle(label, ok)`); `svg` writes
+// the figure it was handed with diagramToSvg and keeps the text (or the error) in `window.__svg`.
+const HOST = `
+import still from "./test/fixtures/cimip-diagrams.json";
+import moving from "./test/fixtures/diagram-motion.json";
+import { diagramToSvg } from "./dist/diagram-export.js";
+window.__log = [];
+window.__svg = [];
+const waits = {};
+window.__settle = (label, ok) => { const w = waits[label]; delete waits[label]; if (w) (ok ? w.resolve : w.reject)(new Error("refused")); };
+const strip = ({ type, ...p }) => p;
+const DATA = { still: strip(still.architecture), kit: strip(moving.kit) };
+const make = (list) => list?.map((a) => ({ ...a, onSelect: (ctx) => {
+ window.__log.push({ label: a.label, viewer: ctx.viewer, inViewer: Boolean(ctx.figure.closest("dialog")), isFigure: ctx.figure.matches(".${P}"), layout: ctx.layout ? ctx.layout.layout : null, layoutFigure: ctx.layout ? ctx.layout.figure === ctx.figure : null, entrance: ctx.figure.getAttribute("data-entrance") });
+ if (a.wait) return new Promise((resolve, reject) => { waits[a.label] = { resolve, reject }; });
+ if (a.svg) return diagramToSvg(ctx.figure).then((b) => b.text()).then((t) => { window.__svg.push(t); }, (e) => { window.__svg.push({ error: String(e && e.message) }); });
+ return undefined;
+} }));
+function Host() {
+ const [list, setList] = React.useState([]);
+ window.__set = (next) => flushSync(() => setList(next));
+ return
{list.map(({ key, data, actions, hidden }) => (
+
+ ))}
;
+}
+createRoot(document.getElementById("root")).render();`;
+
+const frames = (page, n = 3) => page.evaluate((n) => new Promise((resolve) => { let k = 0; const step = () => (++k >= n ? resolve() : requestAnimationFrame(step)); requestAnimationFrame(step); }), n);
+
+async function actionsPage(list, { theme = "dark", width = 1440, height = 900, touch = false, hasTouch = touch, dir, media } = {}) {
+ const { page, errors } = await fixturePage(browser, HOST, { theme, standards: true, viewport: { width, height }, hasTouch, isMobile: touch });
+ if (touch) await page.evaluate(() => { const meta = document.createElement("meta"); meta.name = "viewport"; meta.content = "width=device-width, initial-scale=1"; document.head.append(meta); });
+ if (dir) await page.evaluate((d) => { document.documentElement.dir = d; }, dir);
+ if (media) await page.emulateMedia(media);
+ await page.addStyleTag({ content: PAGE });
+ await page.evaluate(() => document.fonts.ready);
+ await page.evaluate((list) => window.__set(list), list);
+ // The actions' module arrives after the first effect: wait for the buttons the list asks for.
+ for (const { key, actions, hidden } of list) if (actions?.some((a) => a.label) && !hidden) await page.waitForSelector(`#fig-${key} .${P}-foot .${P}-action`);
+ await frames(page, 4);
+ return { page, errors };
+}
+const fig = (key, actions, data = "still", more = {}) => ({ key, data, actions: actions?.map((a) => (typeof a === "string" ? { label: a } : a)), ...more });
+const footWords = (page, key) => page.locator(`#fig-${key} .${P}-foot button`).evaluateAll((els) => els.map((b) => b.textContent.trim()));
+const boxes = (page, sel) => page.locator(sel).evaluateAll((els) => els.map((b) => { const r = b.getBoundingClientRect(); return { words: b.textContent.trim(), left: r.left, right: r.right, top: r.top, bottom: r.bottom, width: r.width }; }));
+
+/** Opens a figure's viewer and waits until its figure is laid out and the dialog has finished its entrance. */
+async function open(page, key, { tap = false } = {}) {
+ const button = page.locator(`#fig-${key} .${P}-expand`);
+ await button.scrollIntoViewIfNeeded();
+ if (tap) await button.tap(); else await button.click();
+ await page.waitForSelector(`dialog.${P}-viewer[open] .${P}[data-layout]`);
+ await page.evaluate(() => Promise.all(document.getAnimations().map((a) => a.finished.catch(() => {}))));
+ await frames(page, 3);
+}
+
+describe("1. the order", () => {
+ test("three actions on an animated figure on touch: the foot is View as list, Expand, Pause animations, the three in order, Clear highlight; Tab visits them so", async () => {
+ const { page, errors } = await actionsPage([fig("kit", THREE, "kit")], { width: 390, height: 844, touch: true });
+ await page.waitForSelector(`#fig-kit .${P}-pause`);
+ await page.waitForSelector(`#fig-kit .${P}-clear`);
+ const want = ["View as list", "Expand", "Pause animations", ...THREE, "Clear highlight"];
+ assert.deepEqual(await footWords(page, "kit"), want);
+ // The visual order is the DOM order: each button starts after the one before it, in reading order.
+ const b = await boxes(page, `#fig-kit .${P}-foot button`);
+ for (let i = 1; i < b.length; i++) assert.ok(b[i].top > b[i - 1].top + 1 || (Math.abs(b[i].top - b[i - 1].top) <= 1 && b[i].left > b[i - 1].left), `${b[i].words} comes after ${b[i - 1].words}`);
+ // Every action is a tab stop of its own: the foot takes no roving focus.
+ await page.locator(`#fig-kit .${P}-toggle`).focus();
+ const visited = [await page.evaluate(() => document.activeElement.textContent.trim())];
+ for (let i = 1; i < want.length; i++) { await page.keyboard.press("Tab"); visited.push(await page.evaluate(() => document.activeElement.textContent.trim())); }
+ assert.deepEqual(visited, want);
+ for (const label of THREE) assert.equal(await page.getByRole("button", { name: label, exact: true }).count(), 1, `${label} is a button named by its label`);
+ assert.deepEqual(errors, []);
+ await page.close();
+ });
+});
+
+describe("2. nothing moves", () => {
+ test("at a 760px figure, a first touch tap mounts Clear highlight last and every other button's box is unchanged", async () => {
+ // A laptop with a touch screen: a mouse page (no Clear at rest) that takes a touch tap.
+ const { page } = await actionsPage([fig("kit", THREE, "kit")], { width: 792, hasTouch: true });
+ assert.equal(await page.locator(`#fig-kit .${P}-clear`).count(), 0, "no Clear highlight before a touch tap");
+ const before = await boxes(page, `#fig-kit .${P}-foot button`);
+ const card = await page.locator(`#fig-kit .${P}-node`).first().boundingBox();
+ await page.touchscreen.tap(card.x + card.width / 2, card.y + card.height / 2);
+ await page.waitForSelector(`#fig-kit .${P}-clear`);
+ await frames(page, 2);
+ const after = await boxes(page, `#fig-kit .${P}-foot button`);
+ assert.equal(after.at(-1).words, "Clear highlight");
+ assert.deepEqual(after.slice(0, -1), before, "no control already in the foot moved");
+ await page.close();
+ });
+});
+
+describe("3. the viewer", () => {
+ test("the end group is View as list then the actions; inViewer: false leaves one out; a press hands the viewer's figure and its drawn layout", async () => {
+ const { page, errors } = await actionsPage([fig("a", ["Download the diagram", "Copy link", { label: "Open in draw.io", inViewer: false }])]);
+ await open(page, "a");
+ const end = await page.locator(`dialog.${P}-viewer .${P}-viewer-end button`).evaluateAll((els) => els.map((b) => b.textContent.trim()));
+ assert.deepEqual(end, ["View as list", "Download the diagram", "Copy link"]);
+ await page.locator(`dialog.${P}-viewer .${P}-viewer-end button`, { hasText: "Copy link" }).click();
+ const { entrance: _entrance, ...got } = (await page.evaluate(() => window.__log)).at(-1);
+ assert.deepEqual(got, { label: "Copy link", viewer: true, inViewer: true, isFigure: true, layout: "drawn", layoutFigure: true });
+ // A press does not close the viewer and does not move focus.
+ assert.equal(await page.locator(`dialog.${P}-viewer[open]`).count(), 1);
+ assert.equal(await page.evaluate(() => document.activeElement.textContent.trim()), "Copy link");
+ // On the page the same action is handed the page's figure.
+ await page.keyboard.press("Escape");
+ await page.waitForSelector(`dialog.${P}-viewer`, { state: "detached" });
+ await page.locator(`#fig-a .${P}-foot button`, { hasText: "Copy link" }).click();
+ const page1 = (await page.evaluate(() => window.__log)).at(-1);
+ assert.equal(page1.viewer, false);
+ assert.equal(page1.inViewer, false);
+ assert.equal(page1.layoutFigure, true);
+ assert.deepEqual(errors, []);
+ await page.close();
+ });
+});
+
+describe("4. the end group wraps (3.1)", () => {
+ const cases = [
+ { name: "390 touch, no action", n: 0, width: 390, height: 844, touch: true },
+ { name: "390 touch, one action", n: 1, width: 390, height: 844, touch: true },
+ { name: "390 touch, three actions", n: 3, width: 390, height: 844, touch: true },
+ { name: "760 with a mouse, three actions", n: 3, width: 760, height: 900, touch: false },
+ ];
+ for (const dir of ["ltr", "rtl"]) for (const c of cases) {
+ test(`${c.name}, ${dir}: no button leaves the dialog; the group ends on the row's edge while it shares the row, and starts on its start edge on a row of its own`, async () => {
+ const { page } = await actionsPage([fig("a", c.n ? THREE.slice(0, c.n) : undefined)], { width: c.width, height: c.height, touch: c.touch, dir });
+ await open(page, "a", { tap: c.touch });
+ const got = await page.evaluate((P) => {
+ const d = document.querySelector(`dialog.${P}-viewer`);
+ const box = (el) => el.getBoundingClientRect();
+ const row = d.querySelector(`.${P}-viewer-row`), zoom = d.querySelector(`.${P}-zoom`);
+ const r = box(row), z = box(zoom);
+ const end = [...d.querySelectorAll(`.${P}-viewer-end button`)].map((b) => { const x = box(b); return { words: b.textContent.trim(), left: x.left, right: x.right, top: x.top }; });
+ return { dialog: [box(d).left, box(d).right], row: [r.left, r.right], zoomTop: z.top, end, overflow: d.scrollWidth - d.clientWidth };
+ }, P);
+ assert.equal(got.overflow, 0, "no horizontal overflow");
+ for (const b of got.end) assert.ok(b.left >= got.dialog[0] - 0.5 && b.right <= got.dialog[1] + 0.5, `${b.words} stays inside the dialog`);
+ const first = got.end[0];
+ const startEdge = dir === "rtl" ? got.row[1] : got.row[0];
+ const endEdge = dir === "rtl" ? got.row[0] : got.row[1];
+ const sharesRow = Math.abs(first.top - got.zoomTop) < 8;
+ if (c.n === 0) {
+ assert.ok(sharesRow, "with no action View as list shares the zoom row");
+ assert.ok(Math.abs((dir === "rtl" ? first.left : first.right) - endEdge) <= 1, "and ends on the row's content edge");
+ } else if (!sharesRow) {
+ assert.ok(Math.abs((dir === "rtl" ? first.right : first.left) - startEdge) <= 1, "a wrapped group's first button starts on the row's start edge");
+ }
+ await page.close();
+ });
+ }
+});
+
+describe("5. the viewer's drawing writes a whole file (2.2)", () => {
+ test("an action's diagramToSvg in the viewer holds the source; with the list open it writes the same viewBox; the sizer is hidden again; a hidden figure rejects", async () => {
+ const { page, errors } = await actionsPage([fig("a", [{ label: "Download the diagram", svg: true }]), fig("h", [{ label: "Download the diagram", svg: true }], "still", { hidden: true })]);
+ const source = await page.locator(`#fig-a .${P}-source`).textContent();
+ await open(page, "a");
+ const press = () => page.locator(`dialog.${P}-viewer .${P}-viewer-end button`, { hasText: "Download the diagram" }).click();
+ await press();
+ await page.waitForFunction(() => window.__svg.length === 1);
+ await page.locator(`dialog.${P}-viewer .${P}-viewer-end button`, { hasText: "View as list" }).click();
+ await frames(page, 2);
+ await press();
+ await page.waitForFunction(() => window.__svg.length === 2);
+ const [closed, opened] = await page.evaluate(() => window.__svg);
+ assert.equal(typeof closed, "string");
+ assert.equal(typeof opened, "string");
+ const viewBox = (svg) => /viewBox="([^"]+)"/.exec(svg)?.[1];
+ assert.ok(source && source.trim().split(/\s+/).every((w) => closed.includes(w.replace(/&/g, "&"))), "the viewer's file holds the source's words");
+ assert.match(viewBox(closed), /^0 0 \d+ \d+$/);
+ assert.equal(viewBox(opened), viewBox(closed), "the list open writes the same drawing");
+ assert.equal(await page.locator(`dialog.${P}-viewer .${P}-sizer`).evaluate((el) => el.hidden), true, "the sizer is hidden again after the read");
+ await page.keyboard.press("Escape");
+ await page.waitForSelector(`dialog.${P}-viewer`, { state: "detached" });
+ // A figure in a display: none parent: no box, so it rejects and no file is made.
+ const hidden = await page.evaluate(async (P) => {
+ const f = document.querySelector("#fig-h");
+ const before = window.__svg.length;
+ // The hidden figure's foot is not displayed either: its action is pressed as an app would call it.
+ f.querySelector(`.${P}-foot .${P}-action`)?.click();
+ await new Promise((r) => setTimeout(r, 100));
+ return window.__svg.slice(before);
+ }, P);
+ assert.equal(hidden.length, 1);
+ assert.match(hidden[0].error, /not displayed/);
+ assert.deepEqual(errors, []);
+ await page.close();
+ });
+});
+
+describe("6. a press settles the entrance (2.3)", () => {
+ test("a press on a page action while the entrance is pending leaves the figure at rest before onSelect runs", async () => {
+ // Below the fold, so its entrance has not started; the press is the element's own click, which does not scroll it into view.
+ const { page } = await actionsPage([fig("spacer", undefined), fig("spacer2", undefined), fig("kit", ["Copy link"], "kit")], { width: 1440, height: 600 });
+ await page.evaluate(() => window.scrollTo(0, 0));
+ const pending = await page.locator("#fig-kit").getAttribute("data-entrance");
+ assert.ok(pending && pending !== "done", `the entrance is pending (${pending})`);
+ await page.evaluate((P) => document.querySelector(`#fig-kit .${P}-action`).click(), P);
+ const log = (await page.evaluate(() => window.__log)).at(-1);
+ assert.equal(log.label, "Copy link");
+ assert.equal(log.entrance, "done", "at rest when onSelect ran");
+ await page.close();
+ });
+});
+
+describe("7. busy", () => {
+ test("a promise makes that button aria-busy and leaves the others pressable; a second press sends nothing; a rejection ends it", async () => {
+ const { page, errors } = await actionsPage([fig("a", [{ label: "Download the diagram", wait: true }, "Copy link"])]);
+ const slow = page.locator(`#fig-a .${P}-action`, { hasText: "Download the diagram" });
+ const quick = page.locator(`#fig-a .${P}-action`, { hasText: "Copy link" });
+ await slow.click();
+ assert.equal(await slow.getAttribute("aria-busy"), "true");
+ await slow.click();
+ await quick.click();
+ assert.equal(await quick.getAttribute("aria-busy"), null);
+ const labels = (await page.evaluate(() => window.__log)).map((l) => l.label);
+ assert.deepEqual(labels, ["Download the diagram", "Copy link"], "the busy button sent once; the other was pressed");
+ await page.evaluate(() => window.__settle("Download the diagram", false));
+ await page.waitForFunction((P) => !document.querySelector(`#fig-a .${P}-action`).hasAttribute("aria-busy"), P);
+ // The rejection is raised again (the server rule): the page sees it.
+ assert.ok(errors.some((e) => /refused/.test(e)), errors.join("; "));
+ await slow.click();
+ assert.equal((await page.evaluate(() => window.__log)).filter((l) => l.label === "Download the diagram").length, 2, "pressable again once it settled");
+ await page.close();
+ });
+});
+
+describe("8. disabled and id", () => {
+ test("disabled: mounted, aria-disabled, focusable, onSelect not called", async () => {
+ const { page } = await actionsPage([fig("a", ["Copy link", { label: "Open in draw.io", disabled: true }])]);
+ const off = page.locator(`#fig-a .${P}-action`, { hasText: "Open in draw.io" });
+ assert.equal(await off.getAttribute("aria-disabled"), "true");
+ await off.focus();
+ assert.equal(await page.evaluate(() => document.activeElement.textContent.trim()), "Open in draw.io");
+ await off.click({ force: true });
+ await page.keyboard.press("Enter");
+ assert.deepEqual(await page.evaluate(() => window.__log), []);
+ await page.close();
+ });
+ test("id: a label that changes keeps the same element and its focus", async () => {
+ const { page } = await actionsPage([fig("a", [{ id: "copy", label: "Copy link" }])]);
+ await page.locator(`#fig-a .${P}-action`).focus();
+ await page.evaluate((P) => { document.querySelector(`#fig-a .${P}-action`).__mark = true; }, P);
+ await page.evaluate(() => window.__set([{ key: "a", data: "still", actions: [{ id: "copy", label: "Copy the link" }] }]));
+ await frames(page, 2);
+ const kept = await page.evaluate((P) => { const b = document.querySelector(`#fig-a .${P}-action`); return { mark: b.__mark === true, words: b.textContent.trim(), focused: document.activeElement === b }; }, P);
+ assert.deepEqual(kept, { mark: true, words: "Copy the link", focused: true });
+ await page.close();
+ });
+});
+
+describe("9. print (3.2)", () => {
+ test("under print media no button of a figure has a box, with and without actions", async () => {
+ const { page } = await actionsPage([fig("none", undefined, "kit"), fig("some", THREE, "kit")], { width: 1440 });
+ await page.waitForSelector(`#fig-some .${P}-pause`);
+ await page.emulateMedia({ media: "print" });
+ await frames(page, 2);
+ for (const key of ["none", "some"]) {
+ const shown = await page.locator(`#fig-${key} button`).evaluateAll((els) => els.filter((b) => b.getClientRects().length).map((b) => b.textContent.trim()));
+ assert.deepEqual(shown, [], `${key}: no control prints`);
+ assert.equal(await page.locator(`#fig-${key} .${P}-foot`).evaluate((el) => getComputedStyle(el).display), "none");
+ }
+ await page.close();
+ });
+});
+
+describe("10. before script, and development", () => {
+ test("the server's HTML holds no action button", async () => {
+ const React = require("react");
+ const { renderToString } = require("react-dom/server");
+ const B = await import(pathToFileURL(path.join(pkg, "dist", "index.js")).href);
+ const data = JSON.parse(fs.readFileSync(path.join(pkg, "test", "fixtures", "cimip-diagrams.json"), "utf8"));
+ const { type: _type, ...props } = data.architecture;
+ const html = renderToString(React.createElement(B.ArchitectureDiagram, { ...props, actions: THREE.map((label) => ({ label, onSelect() {} })) }));
+ assert.doesNotMatch(html, new RegExp(`${P}-action`));
+ for (const label of THREE) assert.ok(!html.includes(`>${label}<`), `no ${label} before script`);
+ });
+ test("a development build warns past three actions, past 24 characters, and for a repeated key, and does not draw an empty label", async () => {
+ const React = require("react");
+ const { renderToString } = require("react-dom/server");
+ const { DiagramActions } = await import(pathToFileURL(path.join(pkg, "dist", "diagram-actions.js")).href);
+ const said = [];
+ const [warn, error] = [console.warn, console.error];
+ console.warn = (m) => said.push(String(m));
+ console.error = (m) => said.push(String(m));
+ let html;
+ try {
+ const actions = [
+ { label: "Copy link", onSelect() {} }, { label: "Copy link", onSelect() {} }, { label: "Download the whole diagram", onSelect() {} },
+ { label: "Open in draw.io", onSelect() {} }, { label: "", onSelect() {} },
+ ];
+ html = renderToString(React.createElement(DiagramActions, { actions, viewer: false, component: "ArchitectureDiagram", context: () => null }));
+ } finally { console.warn = warn; console.error = error; }
+ assert.ok(said.some((m) => /5 actions in the foot; three at most/.test(m)), said.join("\n"));
+ assert.ok(said.some((m) => /"Download the whole diagram" is past 24 characters/.test(m)), said.join("\n"));
+ assert.ok(said.some((m) => /two actions are keyed "Copy link"/.test(m)), said.join("\n"));
+ assert.ok(said.some((m) => /an action has no label/.test(m)), said.join("\n"));
+ assert.equal((html.match(/