Skip to content

Turn any idea, plan, or codebase into a beautiful interactive diagram. An agent skill for Claude Code, Codex, and more.

fix(sequence): keep notes in place and inside their canvas (#676)

yarrbakr0e8a36e993a0
diff --git a/archify.zip b/archify.zip
index c01f0980..54197ddc 100644
Binary files a/archify.zip and b/archify.zip differ
diff --git a/archify/renderers/sequence/README.md b/archify/renderers/sequence/README.md
index bc8599ec..8f7c4e2a 100644
--- a/archify/renderers/sequence/README.md
+++ b/archify/renderers/sequence/README.md
@@ -73,7 +73,7 @@ muted text color.
| Message `y` range | `[160, height − 83]` |
| Message spacing | ≥28px vertical between messages that share horizontal space |
| Arrow span | ≥60px horizontal between the two participants |
-| Message notes | 7px fine-detail text under the arrow, wrapped at 11px line spacing inside one gap between neighbouring lifelines (the widest gap the message spans, nearest the sender on a tie), clear of activation bars; long unbroken text breaks after `/ . - ? & = # _`, otherwise at any character, so the full note is kept in every export. In `showcase`, a note that reaches a later message fails with the `y` that message needs |
+| Message notes | 7px fine-detail text under the arrow, wrapped at 11px line spacing inside one gap between neighbouring lifelines (the widest gap the message spans, the left-most on a tie, where notes have always started), clear of activation bars; long unbroken text breaks after `/ . - ? & = # _`, otherwise at any character, so the full note is kept in every export. In `showcase`, a note that reaches a later message fails with the `y` that message needs, a note past the canvas content limit fails with the `meta.viewBox[1]` it needs, and segment labels step up clear of notes or fail when no clear position remains |
| Segments | y pixel ranges with `to > from`, inside `[72, lifeline bottom + 20]` |
| Legend | last row baseline at height − 54; extra rows wrap upward and stay 12px below the timeline content |
diff --git a/archify/renderers/sequence/render-sequence.mjs b/archify/renderers/sequence/render-sequence.mjs
index 3c02d084..f45cf727 100644
--- a/archify/renderers/sequence/render-sequence.mjs
+++ b/archify/renderers/sequence/render-sequence.mjs
@@ -132,21 +132,24 @@ function wrapNoteText(text, width) {
return lines;
}
-// The widest gap the message spans; equal gaps resolve toward the sender.
+// The widest gap the message spans; equal gaps resolve to the left-most one,
+// where a note has always started, so notes keep their original position.
function noteGapIndex(fromIndex, toIndex) {
const low = Math.min(fromIndex, toIndex);
const high = Math.max(fromIndex, toIndex);
let best = null;
for (let gap = low; gap < high; gap += 1) {
const width = participantX(gap + 1) - participantX(gap);
- const senderDistance = Math.abs((fromIndex < toIndex ? gap : gap + 1) - fromIndex);
- if (!best || width > best.width || (width === best.width && senderDistance < best.senderDistance)) {
- best = { gap, width, senderDistance };
- }
+ if (!best || width > best.width) best = { gap, width };
}
return best?.gap ?? null;
}
+function noteRect(message) {
+ const note = noteLayout(message);
+ return note && { x: note.x, y: note.top, width: note.width, height: note.bottom - note.top };
+}
+
function noteLayout(message) {
if (noteLayouts.has(message)) return noteLayouts.get(message);
let result = null;
@@ -273,7 +276,7 @@ function messageRouteBox(message) {
function segmentLabelBox(segment) {
const labelW = Math.max(42, textUnits(segment.label) * 5.2 + 14);
const occupied = asArray(sequence.messages)
- .flatMap((message) => [messageLabelBox(message), messageRouteBox(message)])
+ .flatMap((message) => [messageLabelBox(message), messageRouteBox(message), noteRect(message)])
.filter(Boolean);
const label = { x: 56, y: segment.from - 22, width: labelW, height: 18 };
for (let attempt = 0; attempt < 4; attempt += 1) {
@@ -442,31 +445,33 @@ function validateSequence() {
}));
// A wrapped note keeps every character (#676), so a note that still reaches a
- // later message needs that message moved; authored y values stay as written.
- // Showcase only, so standard keeps accepting existing diagrams.
+ // later message or the canvas bottom needs the diagram changed; authored y
+ // values and viewBox stay as written. Showcase only, so standard keeps
+ // accepting existing diagrams.
if (readableMessages) {
const messages = asArray(sequence.messages);
+ const noteFloor = layout.lifelineBottom + 20;
messages.forEach((message, messageIndex) => {
const note = noteLayout(message);
if (!note) return;
- const noteRect = { x: note.x, y: note.top, width: note.width, height: note.bottom - note.top };
+ const lines = note.lines.length === 1 ? '1 line' : `${note.lines.length} lines`;
+ const bottom = Math.ceil(note.bottom);
+ if (note.bottom > noteFloor) {
+ const requiredHeight = Math.ceil(viewBox[1] + note.bottom - noteFloor);
+ problems.push(`Note on message "${message.label}" wraps to ${lines} and ends at y=${bottom}, below the canvas content limit y=${noteFloor} — set meta.viewBox[1] to at least ${requiredHeight}, move the message up, or shorten the note.`);
+ }
+ const ownRect = noteRect(message);
const blocker = messages
.map((other, otherIndex) => {
if (otherIndex === messageIndex || typeof other.y !== 'number' || other.y <= message.y) return null;
- const otherNote = noteLayout(other);
- const rects = [
- messageLabelBox(other),
- messageRouteBox(other),
- otherNote && { x: otherNote.x, y: otherNote.top, width: otherNote.width, height: otherNote.bottom - otherNote.top },
- ].filter(Boolean);
- return rects.some((rect) => rectsOverlap(noteRect, rect, 2)) ? other : null;
+ const rects = [messageLabelBox(other), messageRouteBox(other), noteRect(other)].filter(Boolean);
+ return rects.some((rect) => rectsOverlap(ownRect, rect, 2)) ? other : null;
})
.filter(Boolean)
.sort((a, b) => a.y - b.y)[0];
if (!blocker) return;
- const lines = note.lines.length === 1 ? '1 line' : `${note.lines.length} lines`;
const requiredY = Math.ceil(note.bottom + 22);
- problems.push(`Note on message "${message.label}" wraps to ${lines} (down to y=${Math.ceil(note.bottom)}) and reaches message "${blocker.label}" at y=${blocker.y} — move "${blocker.label}" and later messages down so it sits at y=${requiredY} or below, or shorten the note.`);
+ problems.push(`Note on message "${message.label}" wraps to ${lines} (down to y=${bottom}) and reaches message "${blocker.label}" at y=${blocker.y} — move "${blocker.label}" and later messages down so it sits at y=${requiredY} or below, or shorten the note.`);
});
}
@@ -483,6 +488,17 @@ function validateSequence() {
const requiredWidth = Math.ceil(labelBox.x + labelBox.width + 48);
problems.push(`Segment "${segment.label}" label (~${Math.round(labelBox.width)}px) exceeds the segment frame's available width (${availableWidth}px) — shorten the label or increase meta.viewBox[0] to at least ${requiredWidth}.`);
}
+ // Segment labels are drawn above notes and step up to stay clear of them;
+ // in showcase, a label with no clear position would hide note text.
+ if (readableMessages) {
+ const covered = asArray(sequence.messages).find((message) => {
+ const rect = noteRect(message);
+ return rect && rectsOverlap(labelBox, rect, 2);
+ });
+ if (covered) {
+ problems.push(`Segment "${segment.label}" label would cover the note on message "${covered.label}" — move the segment start (from: ${segment.from}) or that message so they are further apart, or shorten the note.`);
+ }
+ }
}
for (const activation of asArray(sequence.activations)) {
diff --git a/scripts/run-browser-tests.mjs b/scripts/run-browser-tests.mjs
index 404279dd..aca4ff3c 100644
--- a/scripts/run-browser-tests.mjs
+++ b/scripts/run-browser-tests.mjs
@@ -35,6 +35,7 @@ const testFiles = [
'crossover-state-browser.test.mjs',
'semantic-passport-move-browser.test.mjs',
'export-browser.test.mjs',
+ 'sequence-note-export-browser.test.mjs',
'viewer-identifiers-browser.test.mjs',
'repository-evidence.test.mjs',
'repository-evidence-types-browser.test.mjs',
diff --git a/test/sequence-note-export-browser.test.mjs b/test/sequence-note-export-browser.test.mjs
new file mode 100644
index 00000000..97b3c493
--- /dev/null
+++ b/test/sequence-note-export-browser.test.mjs
@@ -0,0 +1,100 @@
+import { test } from 'node:test';
+import assert from 'node:assert/strict';
+import fs from 'node:fs';
+import os from 'node:os';
+import path from 'node:path';
+import { execFileSync } from 'node:child_process';
+import { fileURLToPath, pathToFileURL } from 'node:url';
+import { ChromeVisualBrowser, findChrome } from '../archify/bin/visual-check.mjs';
+
+// Wrapped sequence notes are fine-detail text, hidden at the default zoom, so
+// exports must still carry every line (#676).
+const skillRoot = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..', 'archify');
+const chrome = process.env.ARCHIFY_CHROME ? findChrome() : null;
+const LONG_NOTE = 'this note explains the whole retry and backoff policy in a lot of detail so it is very long';
+
+test('SVG and PNG exports keep every line of a wrapped sequence note', {
+ skip: chrome ? false : 'Set ARCHIFY_CHROME to run real-browser export checks.',
+}, async (t) => {
+ const scratch = fs.mkdtempSync(path.join(os.tmpdir(), 'archify-note-export-'));
+ t.after(() => fs.rmSync(scratch, { recursive: true, force: true }));
+ const input = path.join(scratch, 'note.json');
+ const file = path.join(scratch, 'note.html');
+ fs.writeFileSync(input, JSON.stringify({
+ schema_version: 1,
+ diagram_type: 'sequence',
+ meta: { title: 'Note export', output: 'note.html', quality_profile: 'showcase', column_fit: 'spread' },
+ participants: [
+ { id: 'client', type: 'external', label: 'Client' },
+ { id: 'api', type: 'backend', label: 'API' },
+ { id: 'db', type: 'database', label: 'DB' },
+ ],
+ messages: [
+ { id: 'request', from: 'client', to: 'api', y: 200, label: 'request', note: LONG_NOTE },
+ { id: 'reply', from: 'api', to: 'client', y: 300, label: 'reply', variant: 'return' },
+ ],
+ }));
+ execFileSync(process.execPath, [path.join(skillRoot, 'renderers/sequence/render-sequence.mjs'), input, file]);
+ const lines = [...fs.readFileSync(file, 'utf8').matchAll(/<tspan x="[\d.]+" dy="[\d.]+">([^<]*)<\/tspan>/g)].map((match) => match[1]);
+ assert.ok(lines.length > 1, 'the fixture note wraps');
+
+ const browser = new ChromeVisualBrowser(chrome);
+ t.after(() => browser.close());
+ const session = await browser.sessionPromise;
+ const send = (method, params = {}) => browser.cdp.send(method, params, session);
+ await browser.cdp.send('Browser.setDownloadBehavior', { behavior: 'deny' });
+ async function run(expression) {
+ const result = await send('Runtime.evaluate', { expression, awaitPromise: true, returnByValue: true });
+ assert.equal(result.exceptionDetails, undefined, result.exceptionDetails?.exception?.description);
+ return result.result?.value;
+ }
+ // Capture downloads at the anchor boundary; serialization, drawing and
+ // encoding remain production code.
+ await send('Page.addScriptToEvaluateOnNewDocument', { source: `
+ window.noteDownloads=[];
+ const create=URL.createObjectURL.bind(URL),blobs=new Map();
+ URL.createObjectURL=blob=>{const url=create(blob);blobs.set(url,blob);return url;};
+ const click=HTMLAnchorElement.prototype.click;
+ HTMLAnchorElement.prototype.click=function(){if(this.download){noteDownloads.push(blobs.get(this.href));return;}return click.call(this);};
+ window.noteExport=async format=>{const count=noteDownloads.length;await Archify.exportMenu.run(format);
+ const start=performance.now();while(noteDownloads.length===count){if(performance.now()-start>15000)throw new Error('export timed out');await new Promise(r=>setTimeout(r,20));}
+ return noteDownloads[noteDownloads.length-1];};
+ window.notePixels=async blob=>{const bitmap=await createImageBitmap(blob);const canvas=document.createElement('canvas');canvas.width=bitmap.width;canvas.height=bitmap.height;
+ const context=canvas.getContext('2d');context.drawImage(bitmap,0,0);return context.getImageData(0,0,bitmap.width,bitmap.height);};
+ ` });
+ await send('Emulation.setDeviceMetricsOverride', { width: 1440, height: 900, deviceScaleFactor: 1, mobile: false });
+ const loaded = browser.cdp.waitFor('Page.loadEventFired', session);
+ await send('Page.navigate', { url: pathToFileURL(file).href });
+ await loaded;
+ await run('document.fonts.ready');
+ await run('Archify.readerLayout.whenStable()');
+
+ // The default zoom hides fine detail; the export must not.
+ assert.equal(await run(`getComputedStyle(document.querySelector('text[data-detail="fine"]')).opacity`), '0');
+ const svg = await run(`noteExport('svg').then(blob=>blob.text())`);
+ for (const line of lines) assert.ok(svg.includes(`>${line}</tspan>`), `SVG export keeps "${line}"`);
+ assert.doesNotMatch(svg, /data-detail="fine"/, 'SVG export removes the zoom-only marker');
+
+ // Compare PNG exports with and without the note text: the difference is the
+ // note itself, and it must be as tall as its wrapped lines.
+ const diff = await run(`(async()=>{
+ const withNote=await notePixels(await noteExport('png'));
+ const note=document.querySelector('text[data-detail="fine"]');const saved=note.innerHTML;note.innerHTML='';
+ const withoutNote=await notePixels(await noteExport('png'));note.innerHTML=saved;
+ if(withNote.width!==withoutNote.width||withNote.height!==withoutNote.height)return {sameSize:false};
+ let top=Infinity,bottom=-1,left=Infinity,right=-1;
+ for(let y=0;y<withNote.height;y+=1)for(let x=0;x<withNote.width;x+=1){const i=(y*withNote.width+x)*4;
+ if(Math.abs(withNote.data[i]-withoutNote.data[i])+Math.abs(withNote.data[i+1]-withoutNote.data[i+1])+Math.abs(withNote.data[i+2]-withoutNote.data[i+2])>24){
+ top=Math.min(top,y);bottom=Math.max(bottom,y);left=Math.min(left,x);right=Math.max(right,x);}}
+ return {sameSize:true,width:withNote.width,top,bottom,left,right};
+ })()`);
+ assert.equal(diff.sameSize, true);
+ assert.ok(diff.bottom >= 0, 'the PNG export draws the note');
+ const scale = diff.width / 920;
+ assert.ok(diff.bottom - diff.top >= (lines.length - 1) * 11 * scale * 0.8, `the PNG note spans its ${lines.length} lines (${diff.bottom - diff.top}px at scale ${scale.toFixed(2)})`);
+
+ if (process.env.ARCHIFY_NOTE_EXPORT_EVIDENCE) {
+ const png = await run(`noteExport('png').then(blob=>new Promise((resolve,reject)=>{const reader=new FileReader();reader.onload=()=>resolve(String(reader.result).split(',')[1]);reader.onerror=reject;reader.readAsDataURL(blob);}))`);
+ fs.writeFileSync(process.env.ARCHIFY_NOTE_EXPORT_EVIDENCE, Buffer.from(png, 'base64'));
+ }
+});
diff --git a/test/sequence-note-wrap.test.mjs b/test/sequence-note-wrap.test.mjs
index 510f7f1e..05375277 100644
--- a/test/sequence-note-wrap.test.mjs
+++ b/test/sequence-note-wrap.test.mjs
@@ -120,17 +120,69 @@ test('a short note keeps its original single-line markup', (t) => {
assert.doesNotMatch(html, /<tspan/);
});
-test('a note on a message that skips participants uses the gap beside the sender', (t) => {
- const forward = render(t, sequence({ messages: [{ from: 'client', to: 'db', y: 200, label: 'lookup', note: LONG_NOTE }] }));
- const [client, api, db] = lifelines(forward);
- const [forwardNote] = notes(forward);
- assert.equal(forwardNote.x, client + 19);
- for (const line of forwardNote.lines) assert.ok(forwardNote.x + minimumNodeTextWidth(line, 7) <= api - 11, 'clear of the skipped API lifeline');
-
- const backward = render(t, sequence({ messages: [{ from: 'db', to: 'client', y: 200, label: 'result', note: LONG_NOTE }] }));
- const [backwardNote] = notes(backward);
- assert.equal(backwardNote.x, api + 19, 'the gap between API and DB sits beside the sender');
- for (const line of backwardNote.lines) assert.ok(backwardNote.x + minimumNodeTextWidth(line, 7) <= db - 11);
+test('a note on a message that skips participants stays in the left-most gap, in either direction', (t) => {
+ for (const [from, to] of [['client', 'db'], ['db', 'client']]) {
+ const html = render(t, sequence({ messages: [{ from, to, y: 200, label: 'lookup', note: LONG_NOTE }] }));
+ const [client, api] = lifelines(html);
+ const [note] = notes(html);
+ assert.equal(note.x, client + 19, `${from} → ${to} starts where notes always started`);
+ for (const line of note.lines) {
+ assert.ok(note.x + minimumNodeTextWidth(line, 7) <= api - 11, `${from} → ${to}: "${line}" stays clear of the skipped API lifeline`);
+ }
+ }
+});
+
+test('a short note on a reverse message that skips a participant keeps its original position', (t) => {
+ const html = render(t, sequence({ messages: [{ from: 'db', to: 'client', y: 200, label: 'result', note: 'from replica' }] }));
+ const [client] = lifelines(html);
+ assert.match(html, new RegExp(`<text data-detail="fine" x="${client + 19}" y="218" class="t-dim" font-size="7">from replica</text>`));
+});
+
+// Fixed columns keep the first note beside the segment label column at x=56.
+test('a segment label steps up clear of a wrapped note', (t) => {
+ const spec = sequence({
+ messages: [{ from: 'client', to: 'api', y: 200, label: 'request', note: 'retries with backoff when the cache misses' }],
+ });
+ spec.meta.column_fit = 'fixed';
+ spec.segments = [{ label: 'Fallback', from: 260, to: 360 }];
+ const { result } = run(t, 'validate', spec);
+ assert.equal(result.status, 0, result.stdout);
+ const html = render(t, spec);
+ const [note] = notes(html);
+ const labelY = Number(html.match(/<rect x="56" y="(-?[\d.]+)" width="[\d.]+" height="18"/)[1]);
+ const noteTop = note.y - 7;
+ assert.ok(labelY + 18 + 2 <= noteTop || labelY >= note.y + (note.lines.length - 1) * 11 + 4,
+ `segment label at y=${labelY} clears the note from ${noteTop}`);
+});
+
+test('a segment label with no clear position names the note it would cover', (t) => {
+ const spec = sequence({
+ messages: [
+ { from: 'client', to: 'api', y: 160, label: 'open' },
+ { from: 'client', to: 'api', y: 200, label: 'request', note: LONG_NOTE.repeat(3) },
+ ],
+ });
+ spec.meta.column_fit = 'fixed';
+ spec.segments = [{ label: 'Fallback', from: 360, to: 400 }];
+ const { result } = run(t, 'validate', spec);
+ assert.notEqual(result.status, 0);
+ assert.match(result.stdout, /Segment \\"Fallback\\" label would cover the note on message \\"request\\"/);
+});
+
+test('a wrapped note below an authored canvas reports the height it needs', (t) => {
+ const spec = (height) => ({
+ ...sequence({ messages: [{ id: 'late', from: 'client', to: 'api', y: 660, label: 'late', note: LONG_NOTE.repeat(3) }] }),
+ meta: { title: 'Fixed canvas', output: 'note.html', quality_profile: 'showcase', column_fit: 'spread', viewBox: [920, height], legend: { mode: 'hidden' } },
+ });
+ const failed = run(t, 'validate', spec(760)).result;
+ assert.notEqual(failed.status, 0);
+ const required = Number(failed.stdout.match(/set meta\.viewBox\[1\] to at least (\d+)/)?.[1]);
+ assert.ok(required > 760, failed.stdout);
+ const repaired = run(t, 'validate', spec(required)).result;
+ assert.equal(repaired.status, 0, repaired.stdout);
+ const standard = spec(760);
+ standard.meta.quality_profile = 'standard';
+ assert.equal(run(t, 'validate', standard).result.status, 0, 'standard keeps accepting the authored canvas');
});
test('a wrapped note that reaches the next message names the message and the y it needs', (t) => {