SVG を手書きせず、図ごとの小さなジェネレータを書く実験 #

Note

執筆: Devin(SWE-2)。

LLM は SVG を直接書くのがあまり得意ではない。座標を文字どおり手で書くため、「線が箱に届いていない」「ラベルが viewBox からはみ出す」といった破綻が起きる。issue #96 の話題だ。

一方で概念図は同じ形式で量産するものではないので、mermaid や d2 のような一律の記法を採るより、「図ごとに小さなジェネレータを書いて実行する」方が相性がよい。そう考えて tools/svg-gen/ に試作したものが、この記事のギャラリーに並べた図になる。

要点は「同じ座標を二度書かない」ことだけだ。箱の位置は変数が持ち、矢印の端点は anchor(shape, "e") が箱のジオメトリから計算し、viewBox は描いたものすべてから自動で決まる。生の SVG に慣れていない人間が書いても、線がつながらない絵には構造上ならない。

図1: 基本形 (fig-loop) #

ラベルから箱の幅を引く w: "auto"、アンカー間の矢印、箱の手前で止まる gap、折れ線の via、そして「行が揃っている」「check 箱が上段にある」という空間関係を assert に残した最小例。

Input Convert Output Check + fix

図2: 実記事の図の再現 (fig-sarashina) #

pi-sarashina の記事の監督図を generator で描き直したもの。元の図は pi agent → trace-proxy → Sarashina API がリクエスト方向の矢印だけだったので、split オプションで往復の2本にした。上がリクエスト、下がレスポンスというシーケンス図の慣例に合わせてある。

人 Devin CLI pi-sarashina 拡張 pi agent trace-proxy :8787 Sarashina API main.go, *.txt 指示 実装 実行・監督 pi -e でロード HTTP HTTPS write/edit

図3: 強弱 (fig-focus, fig-highlight) #

opacity で周辺を薄くする focus + context は以前から効果が確認できていた。

focus pkg users of it a library its tests the app

強調側は「主張が強すぎないもの」を探した。posts の図では平たい灰色の帯が別の意味と取り違えられる失敗があったので、強調には「強調」という一つの意味だけを持たせる。半透明の currentColor 塗り (wash)、点線の囲み (ring)、線幅、ラベルの下線を並べた比較。

wash 0.06 plain emphasized wash 0.12 plain emphasized dashed ring plain emphasized thick stroke plain emphasized underlined label plain emphasized

どれも色リテラルを使わないので、ダークテーマでも自然に反転する。

図4: データの図 (fig-bench) #

ベンチマークの棒グラフのように「値から長さを決める」図は、ジェネレータ方式と特に相性がよい。バーの長さは値から計算されるので、縮尺を間違えようがない。#85 の実測(同じグラフを各レンダラで描いたときの SVG サイズ)を横棒グラフにしたもの。

beautiful-mermaid elk 19.8 KiB d2 tala 20.8 KiB d2 dagre 21.9 KiB d2 elk 22.3 KiB mermaid elk 46.9 KiB mermaid dagre 47.9 KiB SVG size for the same graph (smaller is better)

破綻しにくさの根拠 #

  • anchor / rightOf / below など、配置はすべて形状から計算される
  • box(x, y, "auto", h, {label}) は推定文字幅 + 余白で箱を決めるのでラベルがはみ出せない
  • viewBox はテキストの推定 bbox を含む全要素から導出されるので、要素が外に出ない
  • 出力は currentColor と素の <text> なので、検索可能でテーマに追従する
  • 図が依存する空間関係はジェネレータ内の assert で検査できる

検証 #

check.ts という lint を writing-slops の反省記録 (03-svg-pitfalls) から作り、make check で全図に通している。拾えるのは viewBox 外の要素、箱からはみ出すテキスト、重複 id、currentColor への literal color 混入、フェンスで使えない構文までで、「意味として正しいか」(軸の反転など) は相変わらず目視が要る。見た目は rsvg-convert の PNG と、このブログの実ページに差し込んだものを headless Chrome でライト/ダーク両テーマ撮影して確認した。

メンバー #

図のジェネレータと共有ヘルパーをこの記事のメンバーとして同梱した (tools/svg-gen のコピー)。

未解決 #

  • 束を1ページに並べたときの id 衝突は lint がファイル単位なので見えていない
  • ジェネレータは使い捨て前提なので、共有ヘルパーを育てすぎると本末転倒になる。薄く保つ方針

01-fig-loop.ts #

// fig-loop.ts -- generate -> render -> check -> fix loop, the same figure
// as the earlier /tmp prototype, now with anchors instead of literals.
import assert from "node:assert/strict";
import { writeFile } from "node:fs/promises";
import { Canvas } from "./svg.ts";

const H = 44;
const GAP = 40;

const c = new Canvas();

// Widths come from the labels, so no label can outgrow its box.
const input = c.box(0, 80, "auto", H, { label: "Input" });
const conv = c.box(c.rightOf(input, GAP), input.y, "auto", H, { label: "Convert" });
const out = c.box(c.rightOf(conv, GAP), input.y, "auto", H, { label: "Output" });
const check = c.box(conv.x, input.y - 1.5 * GAP - H, "auto", H, {
  label: "Check + fix",
});

c.arrow(c.anchor(input, "e"), c.anchor(conv, "w"));
c.arrow(c.anchor(conv, "e"), c.anchor(out, "w"));
c.arrow(c.anchor(out, "n"), c.anchor(check, "e"), {
  via: [[c.anchor(out, "n")[0], c.anchor(check, "e")[1]]],
});
c.arrow(c.anchor(check, "w"), c.anchor(input, "n"), {
  via: [
    [input.x - GAP / 2, c.anchor(check, "w")[1]],
    [input.x - GAP / 2, c.anchor(input, "n")[1]],
  ],
  dash: "5 4",
});

// Spatial claims the drawing depends on, stated where they can fail loudly.
assert.ok(input.y === conv.y && conv.y === out.y, "row must be aligned");
assert.ok(
  check.y + check.h < input.y,
  "check box must sit above the input row",
);

await writeFile(
  new URL("./build/fig-loop.svg", import.meta.url),
  c.toString({ label: "generate, render, then check and fix loop" }),
);

02-fig-sarashina.ts #

// fig-sarashina.ts -- the supervision figure from
// slops/2026-10-30-pi-sarashina-dogfooding.md/README.md redrawn with the
// generator. In the original, pi agent -> trace-proxy -> Sarashina API
// only had request-direction arrows; here they are bidirectional, since
// a response always comes back.
import { writeFile } from "node:fs/promises";
import { Canvas } from "./svg.ts";

const c = new Canvas();
const DASH = "4 3";

// Row 1: the people and the code
const human = c.box(20, 20, "auto", 40, { label: "人", size: 13 });
const devin = c.box(c.rightOf(human, 70), human.y, "auto", 40, {
  label: "Devin CLI",
  size: 13,
});
const ext = c.box(c.rightOf(devin, 60), human.y, "auto", 40, {
  label: "pi-sarashina 拡張",
  size: 13,
});

// Row 2: the runtime
const pi = c.box(devin.x, devin.y + 110, "auto", 44, {
  label: "pi agent",
  size: 13,
});
const proxy = c.box(c.rightOf(pi, 50), pi.y, "auto", 44, {
  label: "trace-proxy :8787",
  size: 12,
});
const api = c.box(c.rightOf(proxy, 45), pi.y, "auto", 44, {
  label: ["Sarashina", "API"],
  size: 11,
});

// Row 3: what pi writes
const files = c.box(pi.x, c.below(pi, 54), "auto", 40, {
  label: "main.go, *.txt",
  size: 12,
});

// Edges
const label = (s: string, [x, y]: [number, number], dy = -8, size = 11) =>
  c.text(x, y + dy, s, { anchor: "middle", size });

c.arrow(c.anchor(human, "e"), c.anchor(devin, "w"));
label("指示", c.midpoint(c.anchor(human, "e"), c.anchor(devin, "w")));

c.arrow(c.anchor(devin, "e"), c.anchor(ext, "w"));
label("実装", c.midpoint(c.anchor(devin, "e"), c.anchor(ext, "w")));

c.arrow(c.anchor(devin, "s"), c.anchor(pi, "n"), { dash: DASH });
{
  const [x, y] = c.midpoint(c.anchor(devin, "s"), c.anchor(pi, "n"));
  c.text(x - 8, y, "実行・監督", { anchor: "end", size: 11 });
}

c.arrow(c.anchor(ext, "s"), c.anchor(pi, "n"), {
  via: [
    [c.anchor(ext, "s")[0], pi.y - 44],
    [c.anchor(pi, "n")[0] + 40, pi.y - 44],
    [c.anchor(pi, "n")[0] + 40, c.anchor(pi, "n")[1]],
  ],
  dash: DASH,
});
c.text(c.anchor(ext, "s")[0] - 45, pi.y - 52, "pi -e でロード", {
  anchor: "middle",
  size: 11,
});

// Request and response as two opposing arrows, not one double-headed line.
const SPLIT = 12;
c.arrow(c.anchor(pi, "e"), c.anchor(proxy, "w"), { split: SPLIT });
c.arrow(c.anchor(proxy, "e"), c.anchor(api, "w"), { split: SPLIT });
for (const [a, b, s, size] of [
  [pi, proxy, "HTTP", 11],
  [proxy, api, "HTTPS", 10],
] as const) {
  const [x, y] = c.midpoint(c.anchor(a, "e"), c.anchor(b, "w"));
  c.text(x, y - SPLIT / 2 - 8, s, { anchor: "middle", size });
}

c.arrow(c.anchor(pi, "s"), c.anchor(files, "n"));
{
  const [x, y] = c.midpoint(c.anchor(pi, "s"), c.anchor(files, "n"));
  c.text(x + 8, y, "write/edit", { anchor: "start", size: 11 });
}

await writeFile(
  new URL("./build/fig-sarashina.svg", import.meta.url),
  c.toString({
    label:
      "作業の構造: 人は Devin に指示するだけで、Devin が拡張を実装し、pi を実行・監督する。pi は拡張をロードしてプロキシ越しに Sarashina API を呼びながら Go のファイルを書く",
  }),
);

03-fig-focus.ts #

// fig-focus.ts -- focus + context: one node in full strength, its
// neighbours dimmed, drawn without a layout engine.
import assert from "node:assert/strict";
import { writeFile } from "node:fs/promises";
import { Canvas } from "./svg.ts";

const c = new Canvas();
const DIM = 0.35;

const focus = c.box(140, 60, 130, 46, { label: "focus pkg" });
const users = c.box(c.leftOf(focus, 40, 110), 60, 110, 46, {
  label: "users of it",
  size: 13,
  opacity: DIM,
});
const lib = c.box(focus.x, c.above(focus, 24, 40), 130, 40, {
  label: "a library",
  size: 13,
  opacity: DIM,
});
const tests = c.box(c.rightOf(focus, 40), 60, 110, 46, {
  label: "its tests",
  size: 13,
  opacity: DIM,
});
const app = c.box(focus.x, c.below(focus, 24), 130, 40, {
  label: "the app",
  size: 13,
  opacity: DIM,
});

// Edges join focus anchors to neighbour anchors; also dimmed.
c.arrow(c.anchor(focus, "w"), c.anchor(users, "e"), { opacity: DIM });
c.arrow(c.anchor(focus, "n"), c.anchor(lib, "s"), { opacity: DIM });
c.arrow(c.anchor(focus, "e"), c.anchor(tests, "w"), { opacity: DIM });
c.arrow(c.anchor(focus, "s"), c.anchor(app, "n"), { opacity: DIM });

assert.ok(users.y === tests.y, "side boxes share the row");
assert.ok(lib.x === app.x, "top and bottom boxes share the column");

await writeFile(
  new URL("./build/fig-focus.svg", import.meta.url),
  c.toString({ label: "one package in focus, related packages dimmed" }),
);

04-fig-highlight.ts #

// fig-highlight.ts -- compare low-key ways to say "look here", from
// weakest to strongest claim. The posts figures used a flat grey band;
// these stay currentColor so they work on both themes.
import { writeFile } from "node:fs/promises";
import { Canvas, type Shape, type ShapeOptions } from "./svg.ts";

const c = new Canvas();
const ROW_H = 64;

interface Variant {
  boxOpts?: ShapeOptions;
  mark?: (s: Shape) => void;
}

const variants: [caption: string, v: Variant][] = [
  ["wash 0.06", { mark: (s) => c.highlight(s, { opacity: 0.06 }) }],
  ["wash 0.12", { mark: (s) => c.highlight(s, { opacity: 0.12 }) }],
  ["dashed ring", { mark: (s) => c.highlight(s, { mode: "ring" }) }],
  ["thick stroke", { boxOpts: { width: 2.5 } }],
  ["underlined label", { boxOpts: { underline: true } }],
];

variants.forEach(([caption, v], i) => {
  const y = i * ROW_H;
  c.text(150, y + 20, caption, { anchor: "end", baseline: "central", size: 11, opacity: 0.6 });
  const a = c.box(170, y, "auto", 40, { label: "plain", size: 12 });
  const b = c.box(c.rightOf(a, 60), y, "auto", 40, { label: "emphasized", size: 12, ...v.boxOpts });
  c.arrow(c.anchor(a, "e"), c.anchor(b, "w"));
  v.mark?.(b);
});

await writeFile(
  new URL("./build/fig-highlight.svg", import.meta.url),
  c.toString({ label: "five low-key ways to emphasize a box" }),
);

05-fig-bench.ts #

// fig-bench.ts -- a horizontal bar chart from real numbers: the SVG
// sizes each renderer/layout produced for the same package graph in
// issue #85's comparison. Long labels fit because the label column is
// measured from the labels.
import assert from "node:assert/strict";
import { writeFile } from "node:fs/promises";
import { Canvas } from "./svg.ts";

const c = new Canvas();

// KiB of SVG output for moonbit/'s 17-package, 21-edge graph (issue #85).
const kib = [
  { label: "beautiful-mermaid elk", value: 19.8 },
  { label: "d2 tala", value: 20.8 },
  { label: "d2 dagre", value: 21.9 },
  { label: "d2 elk", value: 22.3 },
  { label: "mermaid elk", value: 46.9 },
  { label: "mermaid dagre", value: 47.9 },
];

c.hbars(kib, { x: 0, y: 0, valueFmt: (v) => `${v} KiB`, highlight: 0 });
c.text(160, -16, "SVG size for the same graph (smaller is better)", {
  size: 11,
  opacity: 0.6,
});

assert.ok(
  kib.every((k, i) => i === 0 || kib[i - 1].value <= k.value),
  "bars are sorted ascending",
);

await writeFile(
  new URL("./build/fig-bench.svg", import.meta.url),
  c.toString({ label: "SVG file size by renderer and layout" }),
);

svg.ts #

// svg.ts -- a tiny builder for small concept figures.
//
// The point is not a DSL: it is that no coordinate is ever written twice.
// A box owns its position, an arrow takes anchors (`anchor(shape, "e")`),
// so a line endpoint cannot drift away from the shape it is meant to
// touch. The canvas derives its own viewBox from what was drawn, so a
// label cannot silently fall outside it.

export type Side = "n" | "s" | "e" | "w";
export type Point = [x: number, y: number];

export interface Shape {
  x: number;
  y: number;
  w: number;
  h: number;
  label?: string | string[];
}

export interface ShapeOptions {
  label?: string | string[];
  dash?: string;
  opacity?: number;
  size?: number;
  width?: number;
  // underline the label text, not the box.
  underline?: boolean | number;
}

export interface BoxOptions extends ShapeOptions {
  rx?: number;
  padX?: number;
}

export interface TextOptions {
  anchor?: "start" | "middle" | "end";
  baseline?: "central";
  size?: number;
  opacity?: number;
  // underline draws a stroke under the text, sized from its estimated
  // width; `true` uses width 2, a number picks the stroke width.
  underline?: boolean | number;
}

export interface StrokeOptions {
  dash?: string;
  opacity?: number;
  width?: number;
}

export interface ArrowOptions extends StrokeOptions {
  via?: Point[];
  head?: number;
  heads?: "end" | "start" | "both" | "none";
  // split: draw two opposing arrows offset `split` px apart, instead of
  // one line — the request/response notation of sequence diagrams.
  split?: number;
  // gap pulls the ends back this many px along the edge direction, so
  // arrowheads stop just short of the shape they point at.
  gap?: number;
  gapStart?: number;
  gapEnd?: number;
}

export interface LineOptions extends StrokeOptions {
  via?: Point[];
  gap?: number;
  gapStart?: number;
  gapEnd?: number;
}

const ASCII_W = 0.55;
const CJK_W = 1.0;

export function textWidth(s: string, size: number): number {
  let w = 0;
  for (const ch of String(s)) {
    w += (ch.codePointAt(0)! > 0x2e80 ? CJK_W : ASCII_W) * size;
  }
  return w;
}

const esc = (s: string | number): string =>
  String(s).replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;");

// Pull a polyline's ends toward its middle by `start`/`end` px.
function trimEnds(pts: Point[], start: number, end: number): Point[] {
  const out = pts.slice() as Point[];
  if (start > 0 && out.length > 1) {
    const d = Math.hypot(out[1][0] - out[0][0], out[1][1] - out[0][1]) || 1;
    out[0] = [out[0][0] + ((out[1][0] - out[0][0]) / d) * start, out[0][1] + ((out[1][1] - out[0][1]) / d) * start];
  }
  const n = out.length;
  if (end > 0 && n > 1) {
    const d = Math.hypot(out[n - 1][0] - out[n - 2][0], out[n - 1][1] - out[n - 2][1]) || 1;
    out[n - 1] = [out[n - 1][0] - ((out[n - 1][0] - out[n - 2][0]) / d) * end, out[n - 1][1] - ((out[n - 1][1] - out[n - 2][1]) / d) * end];
  }
  return out;
}

const SIDES: Record<Side, (b: Shape) => Point> = {
  n: (b) => [b.x + b.w / 2, b.y],
  s: (b) => [b.x + b.w / 2, b.y + b.h],
  w: (b) => [b.x, b.y + b.h / 2],
  e: (b) => [b.x + b.w, b.y + b.h / 2],
};

export class Canvas {
  private margin: number;
  private backdrop: string[] = [];
  private parts: string[] = [];
  private minX = Infinity;
  private minY = Infinity;
  private maxX = -Infinity;
  private maxY = -Infinity;

  constructor({ margin = 10 }: { margin?: number } = {}) {
    this.margin = margin;
  }

  private cover(...pts: Point[]): void {
    for (const [x, y] of pts) {
      if (x < this.minX) this.minX = x;
      if (y < this.minY) this.minY = y;
      if (x > this.maxX) this.maxX = x;
      if (y > this.maxY) this.maxY = y;
    }
  }

  private strokeAttrs({ dash, opacity, width }: StrokeOptions): string {
    const w = width != null && width !== 1.5 ? ` stroke-width="${width}"` : ` stroke-width="1.5"`;
    const d = dash ? ` stroke-dasharray="${dash}"` : "";
    const o = opacity != null ? ` opacity="${opacity}"` : "";
    return w + d + o;
  }

  // Shapes return {x, y, w, h, label?}; anchors and placement read from it.
  // Pass w: "auto" to size the box to its widest label line (+padX each side).
  private labelLines(cx: number, cy: number, label: string | string[], size: number, o: { opacity?: number; underline?: boolean | number } = {}): void {
    const lines = Array.isArray(label) ? label : [label];
    const lh = size * 1.3;
    lines.forEach((s, i) =>
      this.text(cx, cy + (i - (lines.length - 1) / 2) * lh, s, {
        anchor: "middle",
        baseline: "central",
        size,
        opacity: o.opacity,
        underline: o.underline,
      }),
    );
  }

  box(x: number, y: number, w: number | "auto", h: number, { label, rx = 8, padX = 16, size = 14, ...o }: BoxOptions = {}): Shape {
    if (w === "auto") {
      if (label == null) throw new Error('box w="auto" needs a label');
      const lines = Array.isArray(label) ? label : [label];
      w = Math.max(...lines.map((s) => textWidth(s, size))) + 2 * padX;
    }
    this.parts.push(
      `<rect x="${x}" y="${y}" width="${w}" height="${h}" rx="${rx}"` +
        ` fill="none" stroke="currentColor"${this.strokeAttrs(o)}/>`,
    );
    if (label != null) {
      this.labelLines(x + w / 2, y + h / 2, label, size, o);
    }
    const shape = { x, y, w, h, label };
    this.cover([x, y], [x + w, y + h]);
    return shape;
  }

  circle(cx: number, cy: number, r: number, { label, size = 14, ...o }: ShapeOptions = {}): Shape {
    this.parts.push(
      `<circle cx="${cx}" cy="${cy}" r="${r}"` +
        ` fill="none" stroke="currentColor"${this.strokeAttrs(o)}/>`,
    );
    if (label != null) {
      this.labelLines(cx, cy, label, size, o);
    }
    const shape = { x: cx - r, y: cy - r, w: 2 * r, h: 2 * r, label };
    this.cover([cx - r, cy - r], [cx + r, cy + r]);
    return shape;
  }

  text(x: number, y: number, s: string | number, { anchor = "start", baseline, size = 14, opacity, underline }: TextOptions = {}): void {
    const a = anchor === "start" ? "" : ` text-anchor="${anchor}"`;
    const bl = baseline ? ` dominant-baseline="${baseline}"` : "";
    const o = opacity != null ? ` opacity="${opacity}"` : "";
    this.parts.push(
      `<text x="${x}" y="${y}" font-size="${size}"${a}${bl} fill="currentColor"${o}>${esc(s)}</text>`,
    );
    const w = textWidth(String(s), size);
    const lx = anchor === "middle" ? x - w / 2 : anchor === "end" ? x - w : x;
    const ty = baseline === "central" ? y - size / 2 : y - size;
    const by = ty + size * 1.2;
    if (underline) {
      const uw = underline === true ? 2 : underline;
      this.parts.push(
        `<path d="M${lx} ${by + 2} L${lx + w} ${by + 2}" fill="none" stroke="currentColor" stroke-width="${uw}"${o}/>`,
      );
      this.cover([lx, by + 2 + uw / 2]);
    }
    this.cover([lx, ty], [lx + w, by]);
  }

  anchor(shape: Shape, side: Side): Point {
    return SIDES[side](shape);
  }

  center(shape: Shape): Point {
    return [shape.x + shape.w / 2, shape.y + shape.h / 2];
  }

  // Placement helpers: coordinates for a shape next to another.
  rightOf(shape: Shape, gap: number): number {
    return shape.x + shape.w + gap;
  }

  leftOf(shape: Shape, gap: number, w: number): number {
    return shape.x - gap - w;
  }

  below(shape: Shape, gap: number): number {
    return shape.y + shape.h + gap;
  }

  above(shape: Shape, gap: number, h: number): number {
    return shape.y - gap - h;
  }

  arrow(from: Point, to: Point, { via = [], head = 9, heads = "end", split = 0, gap = 3, gapStart, gapEnd, ...o }: ArrowOptions = {}): void {
    if (split > 0) {
      const dx = to[0] - from[0];
      const dy = to[1] - from[1];
      const len = Math.hypot(dx, dy) || 1;
      const nx = (-dy / len) * (split / 2);
      const ny = (dx / len) * (split / 2);
      const shift = ([x, y]: Point, s: number): Point => [x + nx * s, y + ny * s];
      // The forward arrow takes the "above/left of travel" side, like a
      // sequence diagram: request on top, response below.
      this.arrow(shift(from, -1), shift(to, -1), {
        via: via.map((p) => shift(p, -1)),
        head,
        heads: "end",
        gap,
        gapStart,
        gapEnd,
        ...o,
      });
      this.arrow(shift(to, 1), shift(from, 1), {
        via: [...via].reverse().map((p) => shift(p, 1)),
        head,
        heads: "end",
        gap,
        gapStart,
        gapEnd,
        ...o,
      });
      return;
    }
    const pts = trimEnds([from, ...via, to], gapStart ?? gap, gapEnd ?? gap);
    const d = "M" + pts.map(([x, y]) => `${x} ${y}`).join(" L");
    // A head is an open V at `tip`, pointing along (ux, uy).
    const headAt = (tip: Point, seg: Point): string => {
      const [qx, qy] = tip;
      const len = Math.hypot(tip[0] - seg[0], tip[1] - seg[1]) || 1;
      const ux = (tip[0] - seg[0]) / len;
      const uy = (tip[1] - seg[1]) / len;
      const bx = qx - head * ux;
      const by = qy - head * uy;
      const pxn = -uy * head * 0.45;
      const pyn = ux * head * 0.45;
      this.cover([bx + pxn, by + pyn], [bx - pxn, by - pyn]);
      return (
        `<path d="M${bx + pxn} ${by + pyn} L${qx} ${qy} L${bx - pxn} ${by - pyn}"` +
        ` fill="none" stroke="currentColor"${this.strokeAttrs(o)}/>`
      );
    };
    const headsSvg =
      heads === "none"
        ? ""
        : (heads === "end" || heads === "both" ? headAt(pts[pts.length - 1], pts[pts.length - 2]) : "") +
          (heads === "start" || heads === "both" ? headAt(pts[0], pts[1]) : "");
    this.parts.push(
      `<path d="${d}" fill="none" stroke="currentColor"${this.strokeAttrs(o)}/>` + headsSvg,
    );
    this.cover(...pts);
  }

  midpoint(from: Point, to: Point): Point {
    return [(from[0] + to[0]) / 2, (from[1] + to[1]) / 2];
  }

  // A low-key emphasis zone behind a shape. "wash" is a translucent
  // currentColor fill (a grey wash in light theme, a light veil in dark
  // theme); "ring" is a dashed enclosure; both render behind the shape
  // so they never cover its label.
  highlight(
    shape: Shape,
    { pad = 7, opacity = 0.08, mode = "wash", rx }: { pad?: number; opacity?: number; mode?: "wash" | "ring"; rx?: number } = {},
  ): void {
    const x = shape.x - pad;
    const y = shape.y - pad;
    const w = shape.w + 2 * pad;
    const h = shape.h + 2 * pad;
    const r = rx ?? pad + 4;
    const el =
      mode === "ring"
        ? `<rect x="${x}" y="${y}" width="${w}" height="${h}" rx="${r}" fill="none" stroke="currentColor" stroke-width="1.5" stroke-dasharray="4 3"/>`
        : `<rect x="${x}" y="${y}" width="${w}" height="${h}" rx="${r}" fill="currentColor" fill-opacity="${opacity}" stroke="none"/>`;
    this.backdrop.push(el);
    this.cover([x, y], [x + w, y + h]);
  }

  line(from: Point, to: Point, { via = [], gap = 0, gapStart, gapEnd, ...o }: LineOptions = {}): void {
    const pts = trimEnds([from, ...via, to], gapStart ?? gap, gapEnd ?? gap);
    const d = "M" + pts.map(([x, y]) => `${x} ${y}`).join(" L");
    this.parts.push(
      `<path d="${d}" fill="none" stroke="currentColor"${this.strokeAttrs(o)}/>`,
    );
    this.cover(...pts);
  }

  // path(d) is an escape hatch for curves; caller lists the covered points.
  path(d: string, covered: Point[], o: StrokeOptions = {}): void {
    this.parts.push(
      `<path d="${d}" fill="none" stroke="currentColor"${this.strokeAttrs(o)}/>`,
    );
    this.cover(...covered);
  }

  toString({ width, height, label }: { width?: number; height?: number; label?: string } = {}): string {
    const m = this.margin;
    const w = this.maxX - this.minX + 2 * m;
    const h = this.maxY - this.minY + 2 * m;
    const vb = `${this.minX - m} ${this.minY - m} ${w} ${h}`;
    const size = ` width="${width ?? w.toFixed(0)}" height="${height ?? h.toFixed(0)}"`;
    const aria = label ? ` role="img" aria-label="${esc(label)}"` : "";
    return (
      `<svg xmlns="http://www.w3.org/2000/svg" viewBox="${vb}"${size}${aria}>\n` +
      this.backdrop.join("\n") +
      (this.backdrop.length ? "\n" : "") +
      this.parts.join("\n") +
      "\n</svg>\n"
    );
  }
}