From 927d0c4b602b08bcef8656ec01b918ae069ad2b9 Mon Sep 17 00:00:00 2001 From: Yauhen Yakimovich Date: Wed, 25 Nov 2026 21:21:33 +0100 Subject: [PATCH 1/4] Diagram cells, and Mermaid drawn on par with D2 A fence that opens `d2#show` or `mermaid#show` is a diagram cell. The preview draws it the way it draws an HQL cell: the drawing first, the source behind Code, Edit beside it, and Show in place of Run. A plain `mermaid` fence is a listing. A plain `d2` fence still draws. Mermaid is drawn by merman-cli, a native renderer that needs no browser. It is run the way d2 is: source on stdin, SVG on stdout, within the same 64 KiB, 2 s and 64-entry bounds, delivered as a data: image. It is asked for the resvg-safe pipeline, because Mermaid's default HTML labels do not show inside an image. Both languages are drawn as the source is typed. When the source stops drawing, the cell keeps its last drawing, marked stale, with the reason under it, and Show retries. - ts-core: DIAGRAM_CELL_KINDS, diagramLanguage, diagramEngine, scanDiagramCells; DiagramBlock gains drawnFrom and current, a cell is keyed by position, and IR_VERSION is 5. - vsc-ext: one engine for both renderers, the hyperMarkdown.diagram.mermaidPath setting, the Show Diagram command and code lens, and the showDiagram message. - hmd: MermaidEngine beside D2Engine, and the site build draws mermaid#show and d2#show cells. --- tests/test_mkdocs.py | 100 +++++++++ tools/hmd-ts-core/src/diagram/fence.ts | 120 ++++++++++- tools/hmd-ts-core/src/index.ts | 8 + tools/hmd-ts-core/src/ir.ts | 16 +- tools/hmd-ts-core/src/render.ts | 21 +- tools/hmd-ts-core/test/extensions.test.ts | 99 ++++++++- tools/hmd-vsc-ext/media/render.ts | 128 +++++++++++- tools/hmd-vsc-ext/media/webview.css | 18 ++ tools/hmd-vsc-ext/media/webview.ts | 18 +- tools/hmd-vsc-ext/package.json | 15 ++ tools/hmd-vsc-ext/src/catalog.ts | 50 ++--- tools/hmd-vsc-ext/src/diagram/attach.ts | 75 +++++++ tools/hmd-vsc-ext/src/diagram/engine.ts | 202 +++++++++++++------ tools/hmd-vsc-ext/src/diagram/lens.ts | 38 ++++ tools/hmd-vsc-ext/src/diagram/options.ts | 31 +-- tools/hmd-vsc-ext/src/extension.ts | 40 +++- tools/hmd-vsc-ext/src/preview/controller.ts | 25 ++- tools/hmd-vsc-ext/src/preview/panel.ts | 5 + tools/hmd-vsc-ext/src/protocol.ts | 16 +- tools/hmd-vsc-ext/test/diagramCells.test.ts | 190 +++++++++++++++++ tools/hmd-vsc-ext/test/engine.test.ts | 160 ++++++++++++++- tools/hmd-vsc-ext/test/grammar.test.ts | 11 + tools/hmd-vsc-ext/test/protocol.test.ts | 20 ++ tools/hmd-vsc-ext/test/renderer.test.ts | 121 ++++++++++- tools/hmd/src/hypermarkdown/diagram.py | 117 +++++++++-- tools/hmd/src/hypermarkdown/mkdocs_plugin.py | 19 +- tools/hmd/tests/test_diagram.py | 146 ++++++++++++++ 27 files changed, 1642 insertions(+), 167 deletions(-) create mode 100644 tools/hmd-vsc-ext/src/diagram/attach.ts create mode 100644 tools/hmd-vsc-ext/src/diagram/lens.ts create mode 100644 tools/hmd-vsc-ext/test/diagramCells.test.ts diff --git a/tests/test_mkdocs.py b/tests/test_mkdocs.py index 5ca8c55..9f0e53c 100644 --- a/tests/test_mkdocs.py +++ b/tests/test_mkdocs.py @@ -759,3 +759,103 @@ def test_a_heading_link_names_the_id_toc_gave_the_matched_heading(tmp_path): # card's own one — the one `[[card#setup]]` matched — is `setup_1`. assert card == ["card", "setup", "setup_1", "404", "_1", "usage", "the-fast-path"] assert hrefs == ["#setup_1", "#404", "#_1", "#usage", "#the-fast-path", ""] + + +# -- diagram cells and Mermaid (HMD-0030, HMD-0034) ----------------------- + + +def _fake_renderer(tmp_path: Path, monkeypatch, program: str) -> None: + """Put a stand-in for a diagram renderer on PATH: an SVG holding its input.""" + bin_dir = tmp_path / "bin" + bin_dir.mkdir(exist_ok=True) + script = bin_dir / program + script.write_text(f"#!/bin/sh\nprintf ''\ncat\nprintf ''\n") + script.chmod(0o755) + monkeypatch.setenv("PATH", f"{bin_dir}:/usr/bin:/bin") + + +def _images(html: str) -> list[str]: + import base64 + + payloads = re.findall(r'src="data:image/svg\+xml;base64,([^"]+)"', html) + return [base64.b64decode(payload).decode() for payload in payloads] + + +def test_a_mermaid_cell_is_drawn_and_a_plain_mermaid_fence_is_a_listing(tmp_path, monkeypatch): + _fake_renderer(tmp_path, monkeypatch, "merman-cli") + docs = tmp_path / "docs" + docs.mkdir() + (docs / "index.hmd").write_text( + PUBLIC + "# Home\n\n" + "```mermaid#show\nflowchart LR\n drawn --> yes\n```\n\n" + "```mermaid\nflowchart LR\n listed --> only\n```\n", + encoding="utf-8", + ) + + html = (build(tmp_path, docs, markdown_extensions=_rich_extensions()) / "index.html").read_text() + images = _images(html) + assert len(images) == 1 + assert 'data-by="merman-cli"' in images[0] and "drawn --> yes" in images[0] + assert 'alt="mermaid diagram"' in html + # The listing reaches the page as code, and no renderer saw it. + assert "listed" in html and " one\n```\n\n```d2\nplain -> two\n```\n", + encoding="utf-8", + ) + + html = (build(tmp_path, docs, markdown_extensions=_rich_extensions()) / "index.html").read_text() + images = _images(html) + assert len(images) == 2 + assert "cell -> one" in images[0] and "plain -> two" in images[1] + + +def test_an_embedded_mermaid_cell_renders_in_the_host_page(tmp_path, monkeypatch): + _fake_renderer(tmp_path, monkeypatch, "merman-cli") + docs = tmp_path / "docs" + docs.mkdir() + (docs / "index.hmd").write_text(PUBLIC + "# Home\n\n![[chart]]\n", encoding="utf-8") + (docs / "chart.hmd").write_text( + "# Chart\n\n```mermaid#show\nflowchart LR\n a --> b\n```\n", encoding="utf-8" + ) + + html = (build(tmp_path, docs, markdown_extensions=_rich_extensions()) / "index.html").read_text() + assert any("a --> b" in image for image in _images(html)) + + +def test_a_mermaid_cell_with_no_renderer_shows_its_source_and_says_why(tmp_path, monkeypatch): + """A site builds without the renderer: the cell degrades, the build is green.""" + empty = tmp_path / "empty" + empty.mkdir() + monkeypatch.setenv("PATH", str(empty)) + docs = tmp_path / "docs" + docs.mkdir() + (docs / "index.hmd").write_text( + PUBLIC + "# Home\n\n```mermaid#show\nflowchart LR\n a --> b\n```\n", encoding="utf-8" + ) + + html = (build(tmp_path, docs, markdown_extensions=_rich_extensions()) / "index.html").read_text() + assert "hmd-diagram--placeholder" in html + assert "mermaid diagram — no mermaid engine is installed" in html + assert "a --> b" in html + + +def test_a_diagram_cell_body_yields_no_link(tmp_path, monkeypatch): + """A wikilink inside a diagram is diagram text, not a link to resolve.""" + _fake_renderer(tmp_path, monkeypatch, "merman-cli") + docs = tmp_path / "docs" + docs.mkdir() + (docs / "index.hmd").write_text( + PUBLIC + '# Home\n\n```mermaid#show\nflowchart LR\n a["[[nowhere]]"] --> b\n```\n', + encoding="utf-8", + ) + + html = (build(tmp_path, docs, markdown_extensions=_rich_extensions()) / "index.html").read_text() + assert any("[[nowhere]]" in image for image in _images(html)) diff --git a/tools/hmd-ts-core/src/diagram/fence.ts b/tools/hmd-ts-core/src/diagram/fence.ts index 82d5372..8c0e1b9 100644 --- a/tools/hmd-ts-core/src/diagram/fence.ts +++ b/tools/hmd-ts-core/src/diagram/fence.ts @@ -1,14 +1,33 @@ /** - * Diagram fences (HMD-0022). + * Diagram fences (HMD-0022, HMD-0030, HMD-0034). * - * The core recognises a ```` ```d2 ```` fence and carries its source. It does not - * render: `d2` is a command-line tool, and only the consumer that can run a - * process knows whether one is available. + * The core recognises a diagram fence and carries its source. It does not + * render: `d2` and `merman-cli` are command-line tools, and only the consumer + * that can run a process knows whether one is available. + * + * A fence whose info string opens `d2#show` or `mermaid#show` is a diagram + * cell. A plain `mermaid` fence is a listing, shown as code. A plain `d2` fence + * still draws, as it did before diagram cells: it becomes a listing in the + * release that turns the listing rule on. */ import { sha256 } from "./sha256.js"; -/** Fence languages that become a `DiagramBlock` rather than a code block. */ +/** The engines a diagram can be drawn by. */ +export type DiagramEngineName = "d2" | "mermaid"; + +/** Fence kinds that are diagram cells, and the engine each one is drawn by. */ +export const DIAGRAM_CELL_KINDS: ReadonlyMap = new Map([ + ["d2#show", "d2"], + ["mermaid#show", "mermaid"], +]); + +/** + * Plain fence languages that still draw, matched without regard to case. + * + * Only `d2`, which drew before diagram cells existed. Nothing is added here: a + * new diagram language gets a `#show` kind. + */ export const DIAGRAM_LANGUAGES: ReadonlySet = new Set(["d2"]); /** @@ -19,16 +38,101 @@ export const MAX_SOURCE_BYTES = 64 * 1024; export const RENDER_TIMEOUT_MS = 2_000; export const CACHE_ENTRIES = 64; +/** The first word of a fence info string, as written. */ +export function fenceKind(info: string): string { + return info.trim().split(/\s+/)[0] ?? ""; +} + /** The first word of a fence info string, lowercased. */ export function fenceLanguage(info: string): string { - return (info.trim().split(/\s+/)[0] ?? "").toLowerCase(); + return fenceKind(info).toLowerCase(); +} + +/** + * What a `DiagramBlock` calls the fence, or null when the fence is not a diagram. + * + * A diagram cell is matched exactly, as an HQL cell is: `D2#show` is a listing. + */ +export function diagramLanguage(info: string): string | null { + const kind = fenceKind(info); + if (DIAGRAM_CELL_KINDS.has(kind)) return kind; + const language = kind.toLowerCase(); + return DIAGRAM_LANGUAGES.has(language) ? language : null; } export function isDiagramFence(info: string): boolean { - return DIAGRAM_LANGUAGES.has(fenceLanguage(info)); + return diagramLanguage(info) !== null; +} + +/** True for `d2#show` and `mermaid#show`, the kinds drawn as cells. */ +export function isDiagramCell(language: string): boolean { + return DIAGRAM_CELL_KINDS.has(language); +} + +/** The engine that draws a `DiagramBlock`'s language, or null when none does. */ +export function diagramEngine(language: string): DiagramEngineName | null { + const cell = DIAGRAM_CELL_KINDS.get(language); + if (cell !== undefined) return cell; + return DIAGRAM_LANGUAGES.has(language) ? (language as DiagramEngineName) : null; +} + +/** A diagram cell as it sits in a card's text. */ +export interface DiagramCell { + /** Position among the card's diagram cells, from 0. */ + index: number; + /** `d2#show` or `mermaid#show`. */ + language: string; + /** The fence body, each line ended with a newline, as a `DiagramBlock` carries it. */ + source: string; + /** 0-based line of the opening fence. */ + openLine: number; + /** 0-based line of the closing fence, or the last line when it is unclosed. */ + closeLine: number; +} + +/** + * The diagram cells of a card, for an editor that needs their lines. + * + * Fences are read the way HQL cells are (HMD-0026): an unindented line opening + * with three backticks opens a fence, and the next such line closes it. + */ +export function scanDiagramCells(text: string): DiagramCell[] { + const lines = text.split("\n").map((line) => (line.endsWith("\r") ? line.slice(0, -1) : line)); + if (lines[lines.length - 1] === "") lines.pop(); + const info = (line: string): string | null => { + const trimmed = line.replace(/\s+$/u, ""); + return trimmed.startsWith("```") ? trimmed.slice(3) : null; + }; + + const cells: DiagramCell[] = []; + let index = 0; + while (index < lines.length) { + const opened = info(lines[index]!); + if (opened === null) { + index += 1; + continue; + } + let close = index + 1; + while (close < lines.length && info(lines[close]!) === null) close += 1; + const kind = fenceKind(opened); + if (DIAGRAM_CELL_KINDS.has(kind)) { + cells.push({ + index: cells.length, + language: kind, + source: lines + .slice(index + 1, close) + .map((line) => `${line}\n`) + .join(""), + openLine: index, + closeLine: Math.min(close, lines.length - 1), + }); + } + index = close + 1; + } + return cells; } -/** Cache key for a rendered diagram: the source decides, nothing else. */ +/** Identifies a diagram's source: equal sources have equal keys. */ export function diagramKey(source: string): string { return sha256(source); } diff --git a/tools/hmd-ts-core/src/index.ts b/tools/hmd-ts-core/src/index.ts index 129003c..cd6aeea 100644 --- a/tools/hmd-ts-core/src/index.ts +++ b/tools/hmd-ts-core/src/index.ts @@ -62,13 +62,21 @@ export { calloutPlugin } from "./parse/callout.js"; export { mathPlugin, renderMath } from "./parse/math.js"; export { CACHE_ENTRIES, + DIAGRAM_CELL_KINDS, DIAGRAM_LANGUAGES, MAX_SOURCE_BYTES, RENDER_TIMEOUT_MS, + diagramEngine, diagramKey, + diagramLanguage, + fenceKind, fenceLanguage, + isDiagramCell, isDiagramFence, + scanDiagramCells, sha256, + type DiagramCell, + type DiagramEngineName, } from "./diagram/fence.js"; export { CELL_KINDS, diff --git a/tools/hmd-ts-core/src/ir.ts b/tools/hmd-ts-core/src/ir.ts index ca1d9be..0461e72 100644 --- a/tools/hmd-ts-core/src/ir.ts +++ b/tools/hmd-ts-core/src/ir.ts @@ -15,8 +15,9 @@ import type { Span } from "./model.js"; * * 2 — `DiagramBlock` joins the union (HMD-0022). * 3 — `CellBlock` joins the union (HMD-0026). - * 4 — headings and heading fragments carry a `key` in place of a `slug`. */ -export const IR_VERSION = 4; + * 4 — headings and heading fragments carry a `key` in place of a `slug`. + * 5 — `DiagramBlock` carries the state of its drawing (HMD-0030). */ +export const IR_VERSION = 5; export type ResolutionState = "resolved" | "unresolved" | "ambiguous" | "escapes"; @@ -71,7 +72,10 @@ export interface EmbedBlock { export interface DiagramBlock { kind: "diagram"; key: string; - /** The fence info string's first word, lowercased. */ + /** + * `d2#show` or `mermaid#show` for a diagram cell, as written. `d2` for a + * plain `d2` fence, which still draws. + */ language: string; /** The fence body, verbatim — carried whether or not it rendered. */ source: string; @@ -80,7 +84,11 @@ export interface DiagramBlock { * renderer. The core runs no processes and performs no I/O. */ dataUri: string | null; - /** Why there is no diagram: a missing engine, or a failed render. */ + /** `diagramKey` of the source `dataUri` was drawn from; null with no drawing. */ + drawnFrom: string | null; + /** True when the drawing on screen was drawn from `source` as it stands. */ + current: boolean; + /** Why `source` is not drawn: a missing engine, or a failed render. */ failure: string | null; span: Span; } diff --git a/tools/hmd-ts-core/src/render.ts b/tools/hmd-ts-core/src/render.ts index 5a922b0..f0135a9 100644 --- a/tools/hmd-ts-core/src/render.ts +++ b/tools/hmd-ts-core/src/render.ts @@ -13,7 +13,7 @@ import footnote from "markdown-it-footnote"; import taskLists from "markdown-it-task-lists"; import { scanCells, type Cell, type CellScan } from "./cell/cells.js"; -import { DIAGRAM_LANGUAGES, fenceLanguage } from "./diagram/fence.js"; +import { diagramLanguage, isDiagramCell } from "./diagram/fence.js"; import { bodySlice, expand, isFailure, type Slice } from "./expand.js"; import { IR_VERSION, @@ -297,8 +297,8 @@ export class Renderer { // and can be absent or stale, none of which survives an HTML string. const only = current.length === 1 ? current[0] : undefined; if (only !== undefined && only.type === "fence") { - const language = fenceLanguage(only.info); - if (DIAGRAM_LANGUAGES.has(language)) { + const language = diagramLanguage(only.info); + if (language !== null) { out.push(diagramBlock(only.content, language, at)); return; } @@ -467,7 +467,7 @@ export class Renderer { // -- helpers ------------------------------------------------------------- -/** A diagram fence, carried unrendered; the consumer runs `d2`. */ +/** A diagram fence, carried unrendered; the consumer runs the renderer. */ function diagramBlock(source: string, language: string, line: number): DiagramBlock { return { kind: "diagram", @@ -475,6 +475,8 @@ function diagramBlock(source: string, language: string, line: number): DiagramBl language, source, dataUri: null, + drawnFrom: null, + current: false, failure: null, span: { start: 0, end: 0, line, column: 1 }, }; @@ -556,6 +558,7 @@ export function escapeAttr(value: string): string { */ function assignKeys(blocks: Block[]): Block[] { const seen = new Map(); + let diagramCells = 0; return blocks.map((block) => { const content = block.kind === "html" @@ -563,8 +566,14 @@ function assignKeys(blocks: Block[]): Block[] { : block.kind === "embed" ? `embed:${block.target.raw}` : block.kind === "diagram" - ? `diagram:${block.source}` - : // By name, not content: running a cell changes its output, and + ? // A diagram cell by position, not content: an edit would give it + // a new key, and the reader's Code toggle and the last drawing + // would be lost with it (HMD-0030). A plain `d2` fence has + // neither, and keeps its key by source. + isDiagramCell(block.language) + ? `diagram:#${diagramCells++}` + : `diagram:${block.source}` + :// By name, not content: running a cell changes its output, and // the element — with the reader's choice to show the code — should // survive that. `cell:${block.id ?? `#${block.index}`}`; diff --git a/tools/hmd-ts-core/test/extensions.test.ts b/tools/hmd-ts-core/test/extensions.test.ts index 686c2ca..c387f7b 100644 --- a/tools/hmd-ts-core/test/extensions.test.ts +++ b/tools/hmd-ts-core/test/extensions.test.ts @@ -4,7 +4,16 @@ import { describe, expect, it } from "vitest"; -import { diagramKey, fenceLanguage, isDiagramFence, sha256 } from "../src/diagram/fence.js"; +import { + diagramEngine, + diagramKey, + diagramLanguage, + fenceLanguage, + isDiagramCell, + isDiagramFence, + scanDiagramCells, + sha256, +} from "../src/diagram/fence.js"; import { MemoryHost } from "../src/host.js"; import type { DiagramBlock, DocumentIR } from "../src/ir.js"; import { Renderer } from "../src/render.js"; @@ -154,6 +163,94 @@ describe("diagram fences", () => { }); }); +describe("diagram cells", () => { + const cell = (info: string, body: string): string => `# T\n\n\`\`\`${info}\n${body}\n\`\`\`\n`; + + it("makes `d2#show` and `mermaid#show` diagram cells", async () => { + const [d2] = await diagrams({ "a.hmd": cell("d2#show", "a -> b") }); + expect(d2).toMatchObject({ kind: "diagram", language: "d2#show", source: "a -> b\n" }); + + const [mermaid] = await diagrams({ "a.hmd": cell("mermaid#show", "flowchart LR\n a --> b") }); + expect(mermaid).toMatchObject({ kind: "diagram", language: "mermaid#show" }); + expect(mermaid!.source).toBe("flowchart LR\n a --> b\n"); + }); + + it("matches a cell kind exactly, and ignores the words after it", () => { + expect(diagramLanguage("d2#show")).toBe("d2#show"); + expect(diagramLanguage("mermaid#show")).toBe("mermaid#show"); + expect(diagramLanguage("mermaid#show wide")).toBe("mermaid#show"); + expect(diagramLanguage("D2#show")).toBeNull(); + expect(diagramLanguage("Mermaid#show")).toBeNull(); + expect(diagramLanguage("mermaid#Show")).toBeNull(); + expect(diagramLanguage("d2#eval")).toBeNull(); + expect(diagramLanguage("hql#eval")).toBeNull(); + expect(isDiagramCell("d2#show")).toBe(true); + expect(isDiagramCell("d2")).toBe(false); + }); + + it("shows a plain `mermaid` fence as a listing", async () => { + const body = cell("mermaid", "flowchart LR\n a --> b"); + expect(await diagrams({ "a.hmd": body })).toHaveLength(0); + expect(await html(body)).toContain(" { + expect(diagramEngine("d2#show")).toBe("d2"); + expect(diagramEngine("mermaid#show")).toBe("mermaid"); + expect(diagramEngine("d2")).toBe("d2"); + expect(diagramEngine("mermaid")).toBeNull(); + expect(diagramEngine("python")).toBeNull(); + }); + + it("carries a cell with no drawing and no drawing state", async () => { + const [diagram] = await diagrams({ "a.hmd": cell("mermaid#show", "flowchart LR\n a --> b") }); + expect(diagram).toMatchObject({ + dataUri: null, + drawnFrom: null, + current: false, + failure: null, + }); + }); + + it("keeps a cell's key when its source changes", async () => { + const [before] = await diagrams({ "a.hmd": cell("mermaid#show", "flowchart LR\n a --> b") }); + const [after] = await diagrams({ "a.hmd": cell("mermaid#show", "flowchart LR\n a --> c") }); + expect(after!.key).toBe(before!.key); + }); + + it("gives two cells with the same source distinct keys", async () => { + const both = await diagrams({ + "a.hmd": "```d2#show\na -> b\n```\n\ntext\n\n```d2#show\na -> b\n```\n", + }); + expect(both).toHaveLength(2); + expect(both[0]!.key).not.toBe(both[1]!.key); + }); + + it("finds the cells of a card with the source a block carries", async () => { + const text = + "# T\n\n```d2#show\na -> b\n```\n\n```mermaid\nlisting\n```\n\n```mermaid#show\nflowchart LR\n a --> b\n```\n"; + const cells = scanDiagramCells(text); + expect(cells.map((c) => [c.index, c.language, c.openLine, c.closeLine])).toEqual([ + [0, "d2#show", 2, 4], + [1, "mermaid#show", 10, 13], + ]); + const blocks = await diagrams({ "a.hmd": text }); + expect(cells.map((c) => c.source)).toEqual(blocks.map((b) => b.source)); + }); + + it("yields no link and no embed from a cell's body", async () => { + const ir = await render({ + "a.hmd": cell("mermaid#show", "flowchart LR\n a[\"[[b]]\"] --> c[\"![[b]]\"]"), + "b.hmd": "# B\n", + }); + expect(ir.blocks.filter((b) => b.kind === "embed")).toHaveLength(0); + const [diagram] = ir.blocks.filter((b): b is DiagramBlock => b.kind === "diagram"); + expect(diagram!.source).toContain("[[b]]"); + }); +}); + describe("sha256", () => { it("matches the known digest of the empty string", () => { expect(sha256("")).toBe("e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"); diff --git a/tools/hmd-vsc-ext/media/render.ts b/tools/hmd-vsc-ext/media/render.ts index ccc0c4a..bb028b8 100644 --- a/tools/hmd-vsc-ext/media/render.ts +++ b/tools/hmd-vsc-ext/media/render.ts @@ -6,12 +6,13 @@ * that an editor exists. */ -import type { - Block, - CellBlock, - DiagramBlock, - DocumentIR, - EmbedBlock, +import { + isDiagramCell, + type Block, + type CellBlock, + type DiagramBlock, + type DocumentIR, + type EmbedBlock, } from "@hypermarkdown/core"; export interface RenderSettings { @@ -85,6 +86,10 @@ function createBlock(block: Block, settings: RenderSettings): HTMLElement { * diagram source from a cloned repository cannot run code in the webview. */ function renderDiagram(element: HTMLElement, block: DiagramBlock): void { + if (isDiagramCell(block.language)) { + renderDiagramCell(element, block); + return; + } const rendered = block.dataUri !== null; element.className = rendered ? "hmd-diagram" : "hmd-diagram is-unrendered"; element.dataset["line"] = String(block.span.line); @@ -114,6 +119,113 @@ function renderDiagram(element: HTMLElement, block: DiagramBlock): void { element.append(pre); } +/** + * A diagram cell (HMD-0030): the drawing, with its source one click away. + * + * Laid out as an HQL cell is, with Show where that has Run. The drawing is what + * a reader opened the card for, so it is shown and the source is not, until the + * reader asks. That choice is the reader's and survives a new drawing: it is + * read off the element before anything is rebuilt. + * + * The drawing follows the source as it is typed. When the source stops + * drawing — a syntax error in the middle of an edit — the last drawing stays, + * marked stale, with the reason under it. + */ +function renderDiagramCell(element: HTMLElement, block: DiagramBlock): void { + const codeShown = element.classList.contains("is-code-shown"); + const state = diagramState(block); + + element.className = `hmd-cell hmd-diagram-cell is-${state.kind}`; + element.classList.toggle("is-code-shown", codeShown); + element.dataset["line"] = String(block.span.line); + element.dataset["language"] = block.language; + + let bar = element.querySelector(":scope > .hmd-cell-bar"); + let source = element.querySelector(":scope > .hmd-cell-source"); + let body = element.querySelector(":scope > .hmd-cell-output"); + if (bar === null || source === null || body === null) { + element.textContent = ""; + bar = document.createElement("div"); + bar.className = "hmd-cell-bar"; + source = document.createElement("pre"); + source.className = "hmd-cell-source"; + body = document.createElement("div"); + body.className = "hmd-cell-output"; + element.append(bar, source, body); + } + + bar.textContent = ""; + const kind = document.createElement("span"); + kind.className = "hmd-cell-kind"; + kind.textContent = block.language; + const badge = document.createElement("span"); + badge.className = "hmd-cell-state"; + badge.textContent = state.label; + badge.title = state.title; + const spacer = document.createElement("span"); + spacer.className = "hmd-cell-spacer"; + bar.append(kind, badge, spacer); + bar.append(cellButton("hmd-cell-code", codeShown ? "Hide code" : "Code", "Show or hide this diagram's source", codeShown)); + bar.append(cellButton("hmd-cell-edit", "Edit", "Edit this diagram in the source")); + // Offered inside an embed too: Show writes nothing, so drawing another + // card's diagram touches no file. + bar.append(cellButton("hmd-cell-show", "Show", "Draw this diagram again")); + + const code = document.createElement("code"); + code.textContent = block.source; + source.textContent = ""; + source.append(code); + source.hidden = !codeShown; + + body.textContent = ""; + body.classList.remove("is-empty"); + if (block.dataUri !== null) { + // An `` with a `data:` URI executes no script, so diagram source from + // a cloned repository cannot run code in the webview. + const image = document.createElement("img"); + image.className = "hmd-diagram-image"; + image.src = block.dataUri; + image.alt = `${block.language} diagram`; + body.append(image); + } + if (!block.current) { + const notice = document.createElement("div"); + notice.className = "hmd-diagram-notice"; + notice.textContent = block.failure ?? `${block.language} diagram not drawn`; + body.append(notice); + if (block.dataUri === null && !codeShown) { + // Nothing is drawn, so the source is what there is to read: a cell that + // shows only a reason would hide what the author has to fix. + const pre = document.createElement("pre"); + pre.className = "hmd-diagram-source"; + const shown = document.createElement("code"); + shown.textContent = block.source; + pre.append(shown); + body.append(pre); + } + } +} + +interface DiagramState { + kind: "current" | "stale" | "none"; + label: string; + title: string; +} + +function diagramState(block: DiagramBlock): DiagramState { + if (block.current) { + return { kind: "current", label: "drawn", title: "This drawing came from the source as it stands" }; + } + if (block.dataUri !== null) { + return { + kind: "stale", + label: "stale", + title: "The source changed and no longer draws. This is the last drawing.", + }; + } + return { kind: "none", label: "not drawn", title: "There is no drawing of this source" }; +} + function updateBlock( element: HTMLElement, block: Block, @@ -332,7 +444,9 @@ function cellState(block: CellBlock): CellState { /** Mark the cells being run, by index; `-1` marks every cell of the card. */ export function markRunning(container: HTMLElement, cells: readonly number[]): void { const all = cells.includes(-1); - for (const element of Array.from(container.querySelectorAll(":scope > .hmd-cell"))) { + // A diagram cell shares the layout and has nothing to run. + const hqlCells = container.querySelectorAll(":scope > .hmd-cell[data-kind='cell']"); + for (const element of Array.from(hqlCells)) { const running = all || cells.includes(Number(element.dataset["index"])); element.classList.toggle("is-running", running); const run = element.querySelector(":scope > .hmd-cell-bar > .hmd-cell-run"); diff --git a/tools/hmd-vsc-ext/media/webview.css b/tools/hmd-vsc-ext/media/webview.css index c50420d..cf208f1 100644 --- a/tools/hmd-vsc-ext/media/webview.css +++ b/tools/hmd-vsc-ext/media/webview.css @@ -573,3 +573,21 @@ body.is-graph-fullscreen .hmd-graph { .hmd-cell.is-running > .hmd-cell-output { opacity: 0.55; } + +/* -- diagram cells (HMD-0030) ------------------------------------------- */ + +/* The layout is the HQL cell's. A cell with no drawing has nothing else to + look at, so its bar says why without waiting to be hovered. */ +.hmd-diagram-cell.is-none > .hmd-cell-bar, +.hmd-diagram-cell.is-drawing > .hmd-cell-bar { + opacity: 1; +} + +.hmd-diagram-cell.is-none { + border-left-color: var(--vscode-panel-border); +} + +.hmd-diagram-cell.is-drawing > .hmd-cell-output, +.hmd-diagram-cell.is-stale > .hmd-cell-output > .hmd-diagram-image { + opacity: 0.55; +} diff --git a/tools/hmd-vsc-ext/media/webview.ts b/tools/hmd-vsc-ext/media/webview.ts index 696a26d..01f2c83 100644 --- a/tools/hmd-vsc-ext/media/webview.ts +++ b/tools/hmd-vsc-ext/media/webview.ts @@ -201,8 +201,24 @@ content.addEventListener("click", (event) => { anchors = collectAnchors(content); } else if (cellButton.classList.contains("hmd-cell-edit")) { // The first line of the code, which is where an edit starts. + // A cell inside an embed is in the embedded card, whose path the embed's + // header carries; an empty path means the card on screen. const line = Number(cell.dataset["line"]) + 1; - if (Number.isFinite(line)) vscode.postMessage({ type: "openSource", path: "", line }); + const embedded = cell + .closest(".hmd-embed") + ?.querySelector(":scope > .hmd-embed-header > .hmd-embed-source"); + const path = embedded?.dataset["hmdPath"] ?? ""; + if (Number.isFinite(line)) vscode.postMessage({ type: "openSource", path, line }); + } else if (cellButton.classList.contains("hmd-cell-show")) { + const language = cell.dataset["language"]; + const source = cell.querySelector(":scope > .hmd-cell-source > code"); + if (language !== undefined && source !== null) { + // Until the host answers with a render, which rebuilds the bar. + cell.classList.add("is-drawing"); + (cellButton as HTMLButtonElement).disabled = true; + cellButton.textContent = "Drawing…"; + vscode.postMessage({ type: "showDiagram", language, source: source.textContent ?? "" }); + } } else if (cellButton.classList.contains("hmd-cell-run")) { const index = Number(cell.dataset["index"]); if (Number.isInteger(index)) vscode.postMessage({ type: "runCell", index }); diff --git a/tools/hmd-vsc-ext/package.json b/tools/hmd-vsc-ext/package.json index 4fe17e8..48754ce 100644 --- a/tools/hmd-vsc-ext/package.json +++ b/tools/hmd-vsc-ext/package.json @@ -207,6 +207,12 @@ "title": "Run All HQL Cells", "category": "HyperMarkDown", "icon": "$(run-all)" + }, + { + "command": "hyperMarkdown.showDiagram", + "title": "Show Diagram", + "category": "HyperMarkDown", + "icon": "$(eye)" } ], "menus": { @@ -250,6 +256,10 @@ { "command": "hyperMarkdown.runAllCells", "when": "editorLangId == hmd && isWorkspaceTrusted" + }, + { + "command": "hyperMarkdown.showDiagram", + "when": "editorLangId == hmd" } ] }, @@ -280,6 +290,11 @@ "default": "", "markdownDescription": "Absolute path to a `d2` executable to render diagrams with. Empty uses the `d2` bundled with this build — a pinned [hypermarkdown-toolchain](https://github.com/ewiger/hypermarkdown-toolchain) release, the same binary the documentation site is built with — falling back to `d2` on `PATH`. Set this only to test a different build of d2 deliberately: it takes precedence over the bundled one, and a path that is not an executable is reported rather than silently ignored." }, + "hyperMarkdown.diagram.mermaidPath": { + "type": "string", + "default": "", + "markdownDescription": "Absolute path to a `merman-cli` executable to draw Mermaid diagrams with. Empty uses the `merman-cli` bundled with this build — a pinned [hypermarkdown-toolchain](https://github.com/ewiger/hypermarkdown-toolchain) release, the same binary the documentation site is built with — falling back to `merman-cli` on `PATH`. [merman](https://github.com/latias94/merman) draws Mermaid without a browser. Set this only to test a different build of it deliberately: it takes precedence over the bundled one, and a path that is not an executable is reported rather than silently ignored." + }, "hyperMarkdown.hql.path": { "type": "string", "default": "", diff --git a/tools/hmd-vsc-ext/src/catalog.ts b/tools/hmd-vsc-ext/src/catalog.ts index f3a4945..d687a12 100644 --- a/tools/hmd-vsc-ext/src/catalog.ts +++ b/tools/hmd-vsc-ext/src/catalog.ts @@ -16,8 +16,9 @@ import * as vscode from "vscode"; -import { SUFFIX, type DocumentIR } from "@hypermarkdown/core"; +import { SUFFIX, diagramEngine, isDiagramCell, type DocumentIR } from "@hypermarkdown/core"; +import { attachDiagrams, type DiagramDrawings } from "./diagram/attach.js"; import { DiagramEngine } from "./diagram/engine.js"; import { diagramOptions } from "./diagram/options.js"; import { CellRunner } from "./hql/runner.js"; @@ -48,7 +49,7 @@ export class VaultCatalog implements vscode.Disposable { /** * @param extensionUri the installed extension's root, which is where the - * bundled `d2` lives in a platform-specific VSIX (issue 0107). + * bundled renderers live in a platform-specific VSIX (issue 0107). */ constructor(private readonly extensionUri: vscode.Uri) { this.diagrams = new DiagramEngine(diagramOptions(extensionUri)); @@ -198,7 +199,7 @@ export class VaultCatalog implements vscode.Disposable { // -- diagrams -------------------------------------------------------- /** - * Re-resolve `d2` and drop every rendered diagram. + * Re-resolve `d2` and `merman-cli`, and drop every rendered diagram. * * The cache is keyed by source alone, so a diagram rendered by the old binary * would otherwise survive a change of binary and the setting would look like @@ -211,28 +212,29 @@ export class VaultCatalog implements vscode.Disposable { } /** - * Render every diagram in an IR (HMD-0022). + * Draw every diagram in an IR, keeping in `drawings` what each diagram cell + * of one preview last showed. + */ + attachDiagrams(ir: DocumentIR, drawings?: DiagramDrawings): Promise { + return attachDiagrams(ir, this.diagrams, drawings); + } + + /** + * Draw one diagram cell because a reader asked (HMD-0030). * - * Done here rather than in the core because rendering needs a subprocess, - * which the core cannot run. + * A failure is not answered from the cache, and a renderer that was missing + * is looked for again, so Show is also how a reader retries. Returns false + * for a language that is not a diagram cell. */ - async attachDiagrams(ir: DocumentIR): Promise { - const blocks = await Promise.all( - ir.blocks.map(async (block) => { - if (block.kind === "embed" && block.document !== null) { - return { ...block, document: await this.attachDiagrams(block.document) }; - } - // A cell's output can carry a diagram — HQL writes a graph as a `d2` - // fence — and it is drawn like one written by hand. - if (block.kind === "cell" && block.output !== null) { - const inner = await this.attachDiagrams({ ...ir, blocks: block.output.blocks }); - return { ...block, output: { ...block.output, blocks: inner.blocks } }; - } - if (block.kind !== "diagram") return block; - const { dataUri, failure } = await this.diagrams.render(block.source); - return { ...block, dataUri, failure }; - }), - ); - return { ...ir, blocks }; + async showDiagram(language: string, source: string): Promise { + const engine = isDiagramCell(language) ? diagramEngine(language) : null; + if (engine === null) return false; + await this.diagrams.render(source, engine, { retry: true }); + // Every preview showing this source takes the new answer, not only the + // one whose button was pressed. + this.changed.fire(null); + return true; } } + +export type { DiagramDrawings }; diff --git a/tools/hmd-vsc-ext/src/diagram/attach.ts b/tools/hmd-vsc-ext/src/diagram/attach.ts new file mode 100644 index 0000000..8804cdf --- /dev/null +++ b/tools/hmd-vsc-ext/src/diagram/attach.ts @@ -0,0 +1,75 @@ +/** + * Drawing every diagram in an IR (HMD-0022, HMD-0030). + * + * Done by the extension host rather than in the core because rendering needs a + * subprocess, which the core cannot run. Free of the `vscode` API, so it is + * exercised with an engine and a document. + */ + +import { + diagramEngine, + diagramKey, + isDiagramCell, + type DocumentIR, +} from "@hypermarkdown/core"; + +import type { DiagramEngine } from "./engine.js"; + +/** What each diagram cell of one preview last showed, by the cell's place. */ +export type DiagramDrawings = Map; + +/** + * Draw the diagrams of `ir`, of the cards it embeds, and of its cells' outputs. + * + * `drawings` is one preview's memory of what each diagram cell last showed. A + * cell whose source no longer draws keeps that drawing, marked as not current, + * with the reason beside it: an author in the middle of an edit goes on seeing + * the diagram they are changing. A plain `d2` fence has no such memory, and + * shows its source when it does not draw. + */ +export async function attachDiagrams( + ir: DocumentIR, + engine: DiagramEngine, + drawings?: DiagramDrawings, + scope = "", +): Promise { + const blocks = await Promise.all( + ir.blocks.map(async (block) => { + if (block.kind === "embed" && block.document !== null) { + const inner = `${scope}${ir.path}>${block.key}>`; + return { ...block, document: await attachDiagrams(block.document, engine, drawings, inner) }; + } + // A cell's output can carry a diagram — HQL writes a graph as a `d2` + // fence — and it is drawn like one written by hand. + if (block.kind === "cell" && block.output !== null) { + const inner = await attachDiagrams( + { ...ir, blocks: block.output.blocks }, + engine, + drawings, + `${scope}${ir.path}>${block.key}>`, + ); + return { ...block, output: { ...block.output, blocks: inner.blocks } }; + } + if (block.kind !== "diagram") return block; + + const name = diagramEngine(block.language); + if (name === null) return block; + const { dataUri, failure } = await engine.render(block.source, name); + const drawnFrom = diagramKey(block.source); + if (dataUri !== null) { + if (isDiagramCell(block.language)) { + drawings?.set(`${scope}${ir.path}|${block.key}`, { dataUri, drawnFrom }); + } + return { ...block, dataUri, drawnFrom, current: true, failure: null }; + } + + const last = isDiagramCell(block.language) + ? drawings?.get(`${scope}${ir.path}|${block.key}`) + : undefined; + return last === undefined + ? { ...block, dataUri: null, drawnFrom: null, current: false, failure } + : { ...block, dataUri: last.dataUri, drawnFrom: last.drawnFrom, current: false, failure }; + }), + ); + return { ...ir, blocks }; +} diff --git a/tools/hmd-vsc-ext/src/diagram/engine.ts b/tools/hmd-vsc-ext/src/diagram/engine.ts index d9036e6..330bbe9 100644 --- a/tools/hmd-vsc-ext/src/diagram/engine.ts +++ b/tools/hmd-vsc-ext/src/diagram/engine.ts @@ -1,25 +1,28 @@ /** - * Rendering `d2` fences (HMD-0022). + * Drawing diagram fences (HMD-0022, HMD-0030, HMD-0034). * - * `d2` is a command-line tool the project depends on. The extension runs it, - * caches the result by source, and degrades to a labelled placeholder when it - * is not available — a diagram that is merely not drawn is not a defect in the - * card and must not look like one. + * D2 and Mermaid are drawn by command-line tools the project depends on: `d2`, + * and `merman-cli`, a Mermaid renderer that needs no browser. The extension + * runs them, caches the result by source, and degrades to a labelled + * placeholder when one is not available — a diagram that is merely not drawn + * is not a defect in the card and must not look like one. * - * Where the binary comes from is settled at package time, not at run time - * (issue 0107). The VSIX is built per target platform and carries the `d2` from - * the pinned `hypermarkdown-toolchain` release at `toolchain/bin/`, which is the - * same binary CI and the published site render with. The extension downloads - * nothing and runs no container: an editor is not a place to acquire software. + * Where a binary comes from is settled at package time, not at run time + * (issue 0107). The VSIX is built per target platform and carries the + * renderers from the pinned `hypermarkdown-toolchain` release at + * `toolchain/bin/`, which are the same binaries CI and the published site + * render with. The extension downloads nothing and runs no container: an + * editor is not a place to acquire software. * - * Resolution order, highest first: + * Resolution order for each renderer, highest first: * - * 1. `hyperMarkdown.diagram.d2Path` — an explicit path, for developers - * deliberately testing another build of d2. It never falls through: a - * setting that points at nothing is a mistake worth seeing, not a reason - * to quietly render with a different binary than the one named. + * 1. its setting, `hyperMarkdown.diagram.d2Path` or + * `hyperMarkdown.diagram.mermaidPath` — an explicit path, for developers + * deliberately testing another build. It never falls through: a setting + * that points at nothing is a mistake worth seeing, not a reason to + * quietly render with a different binary than the one named. * 2. the bundled toolchain in the VSIX — the deterministic default. - * 3. `d2` on `PATH` — for a source checkout, where nothing is bundled. + * 3. the program on `PATH` — for a source checkout, where nothing is bundled. * 4. no renderer; the placeholder says so. * * Bounds and cache size are shared with the Python implementation's `diagram.py`, so a @@ -33,6 +36,7 @@ import { MAX_SOURCE_BYTES, RENDER_TIMEOUT_MS, diagramKey, + type DiagramEngineName, } from "@hypermarkdown/core"; export interface DiagramResult { @@ -40,29 +44,74 @@ export interface DiagramResult { failure: string | null; } -/** - * Where this engine may look for `d2`. Supplied by the extension host rather - * than read here, so the engine stays independent of the `vscode` API and can - * be exercised with a path and a directory. - */ -export interface DiagramEngineOptions { - /** `hyperMarkdown.diagram.d2Path`, trimmed; empty or absent means unset. */ +/** Where one renderer may be found. */ +export interface RendererPaths { + /** The renderer's path setting, trimmed; empty or absent means unset. */ configuredPath?: string | null; - /** The VSIX's `toolchain/bin` directory, absent in a source checkout. */ + /** The renderer inside the VSIX's `toolchain/bin`, absent in a source checkout. */ bundledPath?: string | null; } +/** + * Where this engine may look for its renderers. Supplied by the extension host + * rather than read here, so the engine stays independent of the `vscode` API + * and can be exercised with a path and a directory. + * + * The paths at the top level are `d2`'s, and `mermaid` holds `merman-cli`'s. + */ +export interface DiagramEngineOptions extends RendererPaths { + mermaid?: RendererPaths; +} + +interface Renderer { + /** The program's name, as it is bundled and as it is looked up on `PATH`. */ + program: string; + /** The setting that names another build of it. */ + setting: string; + /** Arguments that make it read source on stdin and write SVG on stdout. */ + args: readonly string[]; +} + +/** + * How each renderer is run. + * + * `merman-cli` is told three things `d2` needs no flag for. `resvg-safe` draws + * labels as SVG text: Mermaid's default is HTML inside `foreignObject`, which + * an `` does not show. `constrained` is its resource policy for input + * nobody vetted. The operation timeout is its own deadline, set to the bound + * the process is killed at anyway. + */ +export const RENDERERS: Readonly> = { + d2: { + program: "d2", + setting: "hyperMarkdown.diagram.d2Path", + args: ["-", "-"], + }, + mermaid: { + program: "merman-cli", + setting: "hyperMarkdown.diagram.mermaidPath", + args: [ + "render", + "-", + "--format", + "svg", + "--svg-pipeline", + "resvg-safe", + "--resource-profile", + "constrained", + "--operation-timeout-ms", + String(RENDER_TIMEOUT_MS), + "--quiet", + ], + }, +}; + interface Candidate { - /** What the placeholder calls this, when nothing works. */ - label: string; command: string; /** A wrong answer here is the user's to fix, so do not try the next one. */ authoritative: boolean; } -const NOTHING_TRIED = - "no diagram renderer found — no `d2` is bundled with this build and none is on `PATH`"; - /** * Run one renderer. * @@ -70,11 +119,11 @@ const NOTHING_TRIED = * string, no temporary file named from user content, no argument built from a * card. */ -function run(command: string, source: string): Promise { +function run(command: string, args: readonly string[], source: string): Promise { return new Promise((resolve, reject) => { const child = execFile( command, - ["-", "-"], + [...args], { timeout: RENDER_TIMEOUT_MS, maxBuffer: 32 * 1024 * 1024 }, (error, stdout, stderr) => { if (error) reject(new Error(stderr.trim() || error.message)); @@ -84,12 +133,12 @@ function run(command: string, source: string): Promise { child.on("error", reject); // A renderer that exits before it has read all of stdin — a crash, a parse - // error it bails on early, a binary that is not d2 at all — makes this - // write fail with EPIPE. Without a listener that is an unhandled `error` - // event on the stream, which takes down the extension host over a diagram. - // The `execFile` callback above is the one that decides the outcome: it - // still fires, with the exit status and whatever the renderer said on - // stderr, which is a better message than the write error anyway. + // error it bails on early, a binary that is not the renderer at all — makes + // this write fail with EPIPE. Without a listener that is an unhandled + // `error` event on the stream, which takes down the extension host over a + // diagram. The `execFile` callback above is the one that decides the + // outcome: it still fires, with the exit status and whatever the renderer + // said on stderr, which is a better message than the write error anyway. const stdin = child.stdin; if (stdin !== null) { stdin.on("error", () => {}); @@ -107,31 +156,44 @@ function missingExecutable(exc: unknown): boolean { export class DiagramEngine { /** Insertion-ordered, so the oldest entry is the first key. */ private readonly cache = new Map(); - private candidate: Candidate | null | undefined; + private readonly resolved = new Map(); private options: DiagramEngineOptions; constructor(options: DiagramEngineOptions = {}) { this.options = options; } - /** Forget every rendered diagram. Used when the engine setting changes. */ + /** Forget every rendered diagram. Used when an engine setting changes. */ clear(options?: DiagramEngineOptions): void { this.cache.clear(); - this.candidate = undefined; + this.resolved.clear(); if (options !== undefined) this.options = options; } - async render(source: string): Promise { - const key = diagramKey(source); + /** + * Draw one diagram, from the cache when the same source was drawn before. + * + * `retry` is what Show asks for: a failure is not served from the cache, and + * a renderer that was missing is looked for again. A drawing is still served + * from the cache, because the same source draws the same picture. + */ + async render( + source: string, + engine: DiagramEngineName = "d2", + options: { retry?: boolean } = {}, + ): Promise { + const key = `${engine}:${diagramKey(source)}`; const hit = this.cache.get(key); - if (hit !== undefined) { + if (hit !== undefined && !(options.retry === true && hit.dataUri === null)) { // Refresh recency: delete and reinsert moves it to the end. this.cache.delete(key); this.cache.set(key, hit); return hit; } + if (options.retry === true && this.resolved.get(engine) === null) this.resolved.delete(engine); - const result = await this.renderUncached(source); + const result = await this.renderUncached(source, engine); + this.cache.delete(key); this.cache.set(key, result); // An unbounded cache in a long-lived editor process is a leak with a slow // fuse, and 64 live diagrams in one session is not the case worth serving. @@ -143,39 +205,41 @@ export class DiagramEngine { return result; } + private paths(engine: DiagramEngineName): RendererPaths { + return engine === "d2" ? this.options : (this.options.mermaid ?? {}); + } + /** The order described in the file header, minus the steps that do not apply. */ - private candidates(): Candidate[] { + private candidates(engine: DiagramEngineName): Candidate[] { + const paths = this.paths(engine); const list: Candidate[] = []; - const configured = this.options.configuredPath?.trim(); - if (configured) { - list.push({ label: configured, command: configured, authoritative: true }); - } - const bundled = this.options.bundledPath?.trim(); - if (bundled) { - list.push({ label: "the bundled toolchain", command: bundled, authoritative: false }); - } - list.push({ label: "`d2` on PATH", command: "d2", authoritative: false }); + const configured = paths.configuredPath?.trim(); + if (configured) list.push({ command: configured, authoritative: true }); + const bundled = paths.bundledPath?.trim(); + if (bundled) list.push({ command: bundled, authoritative: false }); + list.push({ command: RENDERERS[engine].program, authoritative: false }); return list; } - private async renderUncached(source: string): Promise { + private async renderUncached(source: string, engine: DiagramEngineName): Promise { if (Buffer.byteLength(source, "utf8") > MAX_SOURCE_BYTES) { return { dataUri: null, failure: `diagram source exceeds ${MAX_SOURCE_BYTES / 1024} KiB` }; } - const candidate = await this.resolveCandidate(source); + const renderer = RENDERERS[engine]; + const candidate = await this.resolveCandidate(source, engine); if (candidate === null) { - const configured = this.options.configuredPath?.trim(); + const configured = this.paths(engine).configuredPath?.trim(); return { dataUri: null, failure: configured - ? `hyperMarkdown.diagram.d2Path points at \`${configured}\`, which is not an executable` - : NOTHING_TRIED, + ? `${renderer.setting} points at \`${configured}\`, which is not an executable` + : `no ${engine} renderer found — no \`${renderer.program}\` is bundled with this build and none is on \`PATH\``, }; } try { - const svg = await run(candidate.command, source); + const svg = await run(candidate.command, renderer.args, source); // An with a data URI executes no script, which turns SVG injection // from a vulnerability into a rendering limitation (HMD-0022 §6). const base64 = Buffer.from(svg, "utf8").toString("base64"); @@ -186,18 +250,22 @@ export class DiagramEngine { } /** Find a renderer once, then remember the answer for the session. */ - private async resolveCandidate(source: string): Promise { - if (this.candidate !== undefined) return this.candidate; - for (const candidate of this.candidates()) { + private async resolveCandidate( + source: string, + engine: DiagramEngineName, + ): Promise { + const known = this.resolved.get(engine); + if (known !== undefined) return known; + for (const candidate of this.candidates(engine)) { try { - await run(candidate.command, source); - this.candidate = candidate; + await run(candidate.command, RENDERERS[engine].args, source); + this.resolved.set(engine, candidate); return candidate; } catch (exc) { // A renderer that exists but rejects *this* diagram is still the // renderer; only a missing executable moves us to the next candidate. if (!missingExecutable(exc)) { - this.candidate = candidate; + this.resolved.set(engine, candidate); return candidate; } // An explicit setting that resolves to nothing stops the search: the @@ -206,7 +274,7 @@ export class DiagramEngine { if (candidate.authoritative) break; } } - this.candidate = null; + this.resolved.set(engine, null); return null; } } diff --git a/tools/hmd-vsc-ext/src/diagram/lens.ts b/tools/hmd-vsc-ext/src/diagram/lens.ts new file mode 100644 index 0000000..b28a10b --- /dev/null +++ b/tools/hmd-vsc-ext/src/diagram/lens.ts @@ -0,0 +1,38 @@ +/** + * Diagram cells in the editor (HMD-0030). + * + * A **Show diagram** lens above every `d2#show` and `mermaid#show` fence, and + * the cell under the cursor for the command of the same name. Both read the + * card's text the way the core does, so the source they hand to the renderer + * is the source the preview draws. + */ + +import * as vscode from "vscode"; + +import { scanDiagramCells, type DiagramCell } from "@hypermarkdown/core"; + +export class DiagramLensProvider implements vscode.CodeLensProvider { + provideCodeLenses(document: vscode.TextDocument): vscode.CodeLens[] { + return scanDiagramCells(document.getText()).map( + (cell) => + new vscode.CodeLens(new vscode.Range(cell.openLine, 0, cell.openLine, 0), { + title: "$(eye) Show diagram", + command: "hyperMarkdown.showDiagram", + arguments: [document.uri, cell.index], + }), + ); + } +} + +/** The diagram cell at a line of a card's text, or the one with this index. */ +export function diagramCellIn( + text: string, + at: { line: number } | { index: number }, +): DiagramCell | null { + const cells = scanDiagramCells(text); + const found = + "index" in at + ? cells.find((cell) => cell.index === at.index) + : cells.find((cell) => at.line >= cell.openLine && at.line <= cell.closeLine); + return found ?? null; +} diff --git a/tools/hmd-vsc-ext/src/diagram/options.ts b/tools/hmd-vsc-ext/src/diagram/options.ts index 70b0cf5..754ea67 100644 --- a/tools/hmd-vsc-ext/src/diagram/options.ts +++ b/tools/hmd-vsc-ext/src/diagram/options.ts @@ -1,34 +1,34 @@ /** - * Where this installation's `d2` may be found (issue 0107). + * Where this installation's diagram renderers may be found (issue 0107). * * Split from `engine.ts` so the engine stays free of the `vscode` API: it is - * given two paths and knows the order to try them in, and this file is the only - * place that knows those paths come from a setting and from the VSIX layout. + * given two paths for each renderer and knows the order to try them in, and + * this file is the only place that knows those paths come from a setting and + * from the VSIX layout. */ import { accessSync, chmodSync, constants, existsSync } from "node:fs"; import * as vscode from "vscode"; -import type { DiagramEngineOptions } from "./engine.js"; +import type { DiagramEngineOptions, RendererPaths } from "./engine.js"; /** - * The bundled binary's path inside the extension, as the release workflow - * writes it. `d2.exe` on Windows; the platform-specific VSIX for a Windows - * target is the only one that carries it. + * One renderer's paths: its setting, and the binary inside the extension as + * the release workflow writes it. The binary has `.exe` on Windows; the + * platform-specific VSIX for a target is the only one that carries it. */ -const BUNDLED = ["toolchain", "bin", process.platform === "win32" ? "d2.exe" : "d2"]; - -export function diagramOptions(extensionUri: vscode.Uri): DiagramEngineOptions { +function rendererPaths(extensionUri: vscode.Uri, setting: string, program: string): RendererPaths { const configured = vscode.workspace .getConfiguration("hyperMarkdown") - .get("diagram.d2Path", "") + .get(setting, "") .trim(); // A platform-neutral VSIX has no `toolchain/`, and neither does a source // checkout running under the Extension Development Host. Both are supported: // the engine falls through to `PATH`. - const bundled = vscode.Uri.joinPath(extensionUri, ...BUNDLED).fsPath; + const name = process.platform === "win32" ? `${program}.exe` : program; + const bundled = vscode.Uri.joinPath(extensionUri, "toolchain", "bin", name).fsPath; return { configuredPath: configured === "" ? null : configured, @@ -36,6 +36,13 @@ export function diagramOptions(extensionUri: vscode.Uri): DiagramEngineOptions { }; } +export function diagramOptions(extensionUri: vscode.Uri): DiagramEngineOptions { + return { + ...rendererPaths(extensionUri, "diagram.d2Path", "d2"), + mermaid: rendererPaths(extensionUri, "diagram.mermaidPath", "merman-cli"), + }; +} + /** * Make sure the bundled binary can be run, restoring the bit if it was lost. * diff --git a/tools/hmd-vsc-ext/src/extension.ts b/tools/hmd-vsc-ext/src/extension.ts index 199d989..9b04058 100644 --- a/tools/hmd-vsc-ext/src/extension.ts +++ b/tools/hmd-vsc-ext/src/extension.ts @@ -14,6 +14,7 @@ import { createCard } from "./commands/createCard.js"; import { initializeVault, reportMissingVault } from "./commands/initVault.js"; import { debounce } from "./debounce.js"; import { DiagnosticPublisher } from "./diagnostics.js"; +import { DiagramLensProvider, diagramCellIn } from "./diagram/lens.js"; import { CellLensProvider, cellAtCursor } from "./hql/runner.js"; import { LanguageServer } from "./lsp/client.js"; import { PreviewPanel, VIEW_TYPE, type PanelState } from "./preview/panel.js"; @@ -99,6 +100,40 @@ export async function activate(context: vscode.ExtensionContext): Promise { language: "hmd" }, new CellLensProvider(catalog.cells), ), + vscode.commands.registerCommand( + "hyperMarkdown.showDiagram", + async (uri?: vscode.Uri, index?: number) => { + const editor = vscode.window.activeTextEditor; + const document = + uri === undefined + ? editor?.document + : vscode.workspace.textDocuments.find((d) => d.uri.toString() === uri.toString()); + const cell = + document === undefined + ? null + : index !== undefined + ? diagramCellIn(document.getText(), { index }) + : editor === undefined + ? null + : diagramCellIn(document.getText(), { line: editor.selection.active.line }); + if (cell === null) { + void vscode.window.setStatusBarMessage( + "HyperMarkDown: the cursor is not in a diagram cell", + 2000, + ); + return; + } + // The drawing lives in the preview, so asking for one opens it. + if (!PreviewPanel.isOpen) { + PreviewPanel.open(catalog, context.extensionUri, { + column: vscode.ViewColumn.Beside, + preserveFocus: true, + }); + } + await catalog.showDiagram(cell.language, cell.source); + }, + ), + vscode.languages.registerCodeLensProvider({ language: "hmd" }, new DiagramLensProvider()), vscode.commands.registerCommand("hyperMarkdown.createCardFromLink", async () => { const editor = vscode.window.activeTextEditor; if (editor === undefined) return; @@ -113,7 +148,10 @@ export async function activate(context: vscode.ExtensionContext): Promise context.subscriptions.push( vscode.workspace.onDidChangeConfiguration((event) => { if (event.affectsConfiguration("hyperMarkdown.root")) void catalog.rebuild(); - else if (event.affectsConfiguration("hyperMarkdown.diagram.d2Path")) { + else if ( + event.affectsConfiguration("hyperMarkdown.diagram.d2Path") || + event.affectsConfiguration("hyperMarkdown.diagram.mermaidPath") + ) { catalog.refreshDiagramEngine(); } else if (event.affectsConfiguration("hyperMarkdown.hql.path")) { catalog.cells.refresh(); diff --git a/tools/hmd-vsc-ext/src/preview/controller.ts b/tools/hmd-vsc-ext/src/preview/controller.ts index 83cbd25..72d3311 100644 --- a/tools/hmd-vsc-ext/src/preview/controller.ts +++ b/tools/hmd-vsc-ext/src/preview/controller.ts @@ -15,7 +15,7 @@ import * as vscode from "vscode"; import { IR_VERSION, SUFFIX, cardSuffix, headingKey } from "@hypermarkdown/core"; -import { sameCard, type CardRef, type VaultCatalog } from "../catalog.js"; +import { sameCard, type CardRef, type DiagramDrawings, type VaultCatalog } from "../catalog.js"; import { createCard } from "../commands/createCard.js"; import { initializeVault } from "../commands/initVault.js"; import { REPARSE_DEBOUNCE_MS, debounce } from "../debounce.js"; @@ -51,6 +51,10 @@ export class PreviewController implements vscode.Disposable { private maximised = false; private current: CardRef | null = null; private lastAppliedScroll = 0; + /** What each diagram cell of the card on screen last showed (HMD-0030). */ + private readonly drawings: DiagramDrawings = new Map(); + /** Counts renders sent for drawing, so a slow one cannot overwrite a newer one. */ + private renderSerial = 0; /** * An open `.hmd` file no vault claims, and why, so the empty state can say * which card and offer the fix. @@ -245,6 +249,8 @@ export class PreviewController implements vscode.Disposable { private setCard(card: CardRef | null): void { if (sameCard(this.current, card)) return; this.current = card; + // A drawing kept for one card's cell must not show under another card's. + this.drawings.clear(); this.cardChanged.fire(card?.rel ?? null); } @@ -304,6 +310,12 @@ export class PreviewController implements vscode.Disposable { case "initVault": void initializeVault(this.catalog, this.unclaimed?.uri ?? null); return; + case "showDiagram": + // Show writes nothing and runs the renderer the preview already runs, + // on source the preview already holds, so it needs no trust check and + // is offered inside an embed as well (HMD-0030). + void this.catalog.showDiagram(message.language, message.source); + return; case "runCell": case "runAllCells": { // Only the card on screen runs: a cell inside an embed belongs to @@ -574,10 +586,13 @@ export class PreviewController implements vscode.Disposable { const pinned = this.pinned; const card = this.current; - // Reading diagram artifacts is the one asynchronous step; the guard below - // drops the result if the preview moved on while it was in flight. - void this.catalog.attachDiagrams(document).then((withDiagrams) => { - if (!sameCard(this.current, card)) return; + // Drawing diagrams is the one asynchronous step; the guard below drops the + // result if the preview moved on, or sent newer text, while it was in + // flight. Diagrams are drawn on every edit, so two renders of one card are + // often in flight together. + const serial = (this.renderSerial += 1); + void this.catalog.attachDiagrams(document, this.drawings).then((withDiagrams) => { + if (!sameCard(this.current, card) || serial !== this.renderSerial) return; this.post({ type: "render", irVersion: IR_VERSION, diff --git a/tools/hmd-vsc-ext/src/preview/panel.ts b/tools/hmd-vsc-ext/src/preview/panel.ts index 792dbd8..c3c3b18 100644 --- a/tools/hmd-vsc-ext/src/preview/panel.ts +++ b/tools/hmd-vsc-ext/src/preview/panel.ts @@ -133,6 +133,11 @@ export class PreviewPanel implements vscode.Disposable { } /** Tear down every live preview, for the extension's own disposal. */ + /** True while at least one preview tab exists. */ + static get isOpen(): boolean { + return PreviewPanel.panels.size > 0; + } + static disposeAll(): void { for (const preview of [...PreviewPanel.panels]) preview.dispose(); } diff --git a/tools/hmd-vsc-ext/src/protocol.ts b/tools/hmd-vsc-ext/src/protocol.ts index 49b08cb..44f539b 100644 --- a/tools/hmd-vsc-ext/src/protocol.ts +++ b/tools/hmd-vsc-ext/src/protocol.ts @@ -6,7 +6,7 @@ * the extension's own code, but the message boundary is still a trust boundary. */ -import type { DocumentIR } from "@hypermarkdown/core"; +import { MAX_SOURCE_BYTES, isDiagramCell, type DocumentIR } from "@hypermarkdown/core"; export type PreviewMode = "rendered" | "graph"; @@ -91,6 +91,8 @@ export type WebviewMessage = | { type: "fullScreen"; on: boolean } | { type: "runCell"; index: number } | { type: "runAllCells" } + /** Show on a diagram cell: draw this source again (HMD-0030). */ + | { type: "showDiagram"; language: string; source: string } /** The button under a "vault not found" message (issue 0116). */ | { type: "initVault" }; @@ -163,6 +165,18 @@ export function parseWebviewMessage(raw: unknown): WebviewMessage | null { : null; case "runAllCells": return { type: "runAllCells" }; + case "showDiagram": { + // The source is drawn, so it is held to what a card's own fence is held + // to: a diagram cell's kind, and the size bound of a render. + const language = message["language"]; + const source = message["source"]; + return typeof language === "string" && + isDiagramCell(language) && + typeof source === "string" && + new TextEncoder().encode(source).length <= MAX_SOURCE_BYTES + ? { type: "showDiagram", language, source } + : null; + } case "initVault": return { type: "initVault" }; case "fullScreen": diff --git a/tools/hmd-vsc-ext/test/diagramCells.test.ts b/tools/hmd-vsc-ext/test/diagramCells.test.ts new file mode 100644 index 0000000..bbb7bd2 --- /dev/null +++ b/tools/hmd-vsc-ext/test/diagramCells.test.ts @@ -0,0 +1,190 @@ +/** + * Diagram cells in the preview (HMD-0030): what a `d2#show` or `mermaid#show` + * fence shows as its source is typed, and after it stops drawing. + * + * The renderers here are tiny scripts, as in `engine.test.ts`: the thing worth + * testing is which source reached a process, and which drawing came back. + */ + +import { chmodSync, mkdtempSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; + +import { + MemoryHost, + Renderer, + Workspace, + diagramKey, + type DiagramBlock, + type DocumentIR, +} from "@hypermarkdown/core"; +import { describe, expect, it } from "vitest"; + +import { attachDiagrams, type DiagramDrawings } from "../src/diagram/attach.js"; +import { DiagramEngine } from "../src/diagram/engine.js"; +import { diagramCellIn } from "../src/diagram/lens.js"; + +const dir = mkdtempSync(join(tmpdir(), "hmd-diagram-cells-")); + +/** + * A renderer that draws its input, and refuses any input holding `!`. + * + * The SVG carries the source, so a test can tell which text a drawing is of. + */ +function renderer(name: string): string { + const path = join(dir, name); + writeFileSync( + path, + `#!/bin/sh\nbody=$(cat)\ncase "$body" in *'!'*) echo "${name}: syntax error" >&2; exit 1;; esac\nprintf '%s' "$body"\n`, + ); + chmodSync(path, 0o755); + return path; +} + +const engine = (): DiagramEngine => + new DiagramEngine({ + configuredPath: renderer("fake-d2"), + mermaid: { configuredPath: renderer("fake-merman") }, + }); + +async function ir(files: Record, path = "a.hmd"): Promise { + const workspace = await Workspace.load(MemoryHost.from(files), { + autodiscovery: true, + mode: "both", + source: null, + }); + const document = new Renderer(workspace).render(path); + if (document === null) throw new Error(`no such card: ${path}`); + return document; +} + +const card = (info: string, body: string): string => `# T\n\n\`\`\`${info}\n${body}\n\`\`\`\n`; + +function diagramsOf(document: DocumentIR): DiagramBlock[] { + return document.blocks.filter((b): b is DiagramBlock => b.kind === "diagram"); +} + +function svg(block: DiagramBlock): string { + expect(block.dataUri).not.toBeNull(); + return Buffer.from(block.dataUri!.split(",")[1]!, "base64").toString("utf8"); +} + +describe("drawing a diagram cell", () => { + it("draws `mermaid#show` with the Mermaid renderer and `d2#show` with d2", async () => { + const document = await ir({ + "a.hmd": "```mermaid#show\nflowchart LR\n```\n\ntext\n\n```d2#show\na -> b\n```\n", + }); + const [mermaid, d2] = diagramsOf(await attachDiagrams(document, engine(), new Map())); + expect(svg(mermaid!)).toContain('data-by="fake-merman"'); + expect(svg(d2!)).toContain('data-by="fake-d2"'); + expect(mermaid).toMatchObject({ current: true, failure: null }); + expect(mermaid!.drawnFrom).toBe(diagramKey("flowchart LR\n")); + }); + + it("follows the source as it is edited", async () => { + const drawings: DiagramDrawings = new Map(); + const shared = engine(); + const before = await attachDiagrams(await ir({ "a.hmd": card("mermaid#show", "one") }), shared, drawings); + const after = await attachDiagrams(await ir({ "a.hmd": card("mermaid#show", "two") }), shared, drawings); + expect(svg(diagramsOf(before)[0]!)).toContain("one"); + expect(svg(diagramsOf(after)[0]!)).toContain("two"); + expect(diagramsOf(after)[0]).toMatchObject({ current: true, failure: null }); + }); + + it("keeps the last drawing, marked stale, when the source stops drawing", async () => { + const drawings: DiagramDrawings = new Map(); + const shared = engine(); + await attachDiagrams(await ir({ "a.hmd": card("mermaid#show", "good") }), shared, drawings); + const broken = diagramsOf( + await attachDiagrams(await ir({ "a.hmd": card("mermaid#show", "bad!") }), shared, drawings), + )[0]!; + + expect(svg(broken)).toContain("good"); + expect(broken.current).toBe(false); + expect(broken.drawnFrom).toBe(diagramKey("good\n")); + expect(broken.failure).toContain("syntax error"); + expect(broken.source).toBe("bad!\n"); + }); + + it("is current again once the source draws", async () => { + const drawings: DiagramDrawings = new Map(); + const shared = engine(); + await attachDiagrams(await ir({ "a.hmd": card("d2#show", "good") }), shared, drawings); + await attachDiagrams(await ir({ "a.hmd": card("d2#show", "bad!") }), shared, drawings); + const fixed = diagramsOf( + await attachDiagrams(await ir({ "a.hmd": card("d2#show", "better") }), shared, drawings), + )[0]!; + expect(svg(fixed)).toContain("better"); + expect(fixed).toMatchObject({ current: true, failure: null }); + }); + + it("has no drawing, and says why, when the source never drew", async () => { + const [block] = diagramsOf( + await attachDiagrams(await ir({ "a.hmd": card("mermaid#show", "bad!") }), engine(), new Map()), + ); + expect(block).toMatchObject({ dataUri: null, drawnFrom: null, current: false }); + expect(block!.failure).toContain("syntax error"); + }); + + it("does not hand one cell's last drawing to another", async () => { + const drawings: DiagramDrawings = new Map(); + const shared = engine(); + const two = (second: string): string => + `\`\`\`mermaid#show\nfirst\n\`\`\`\n\ntext\n\n\`\`\`mermaid#show\n${second}\n\`\`\`\n`; + await attachDiagrams(await ir({ "a.hmd": two("second") }), shared, drawings); + const [first, second] = diagramsOf( + await attachDiagrams(await ir({ "a.hmd": two("bad!") }), shared, drawings), + ); + expect(svg(first!)).toContain("first"); + expect(svg(second!)).toContain("second"); + expect(second!.current).toBe(false); + }); + + it("draws a cell inside an embedded card, and keeps its drawing apart", async () => { + const drawings: DiagramDrawings = new Map(); + const document = await ir({ + "a.hmd": "```mermaid#show\nhost\n```\n\n![[b]]\n", + "b.hmd": "# B\n\n```mermaid#show\nguest\n```\n", + }); + const drawn = await attachDiagrams(document, engine(), drawings); + const embed = drawn.blocks.find((b) => b.kind === "embed"); + if (embed?.kind !== "embed" || embed.document === null) throw new Error("no embed"); + expect(svg(diagramsOf(drawn)[0]!)).toContain("host"); + expect(svg(diagramsOf(embed.document)[0]!)).toContain("guest"); + expect(drawings.size).toBe(2); + }); + + it("leaves a plain `mermaid` fence as a listing, with no renderer started", async () => { + const document = await ir({ "a.hmd": card("mermaid", "flowchart LR") }); + expect(diagramsOf(await attachDiagrams(document, engine(), new Map()))).toHaveLength(0); + }); + + it("still draws a plain `d2` fence, and shows its source when it fails", async () => { + const drawings: DiagramDrawings = new Map(); + const shared = engine(); + const good = diagramsOf(await attachDiagrams(await ir({ "a.hmd": card("d2", "good") }), shared, drawings))[0]!; + expect(svg(good)).toContain("good"); + const bad = diagramsOf(await attachDiagrams(await ir({ "a.hmd": card("d2", "bad!") }), shared, drawings))[0]!; + // No memory for a plain fence: it has no cell to mark stale. + expect(bad.dataUri).toBeNull(); + expect(bad.failure).toContain("syntax error"); + }); +}); + +describe("the cell under the cursor", () => { + const text = "# T\n\n```mermaid#show\nflowchart LR\n a --> b\n```\n\n```d2\nx -> y\n```\n"; + + it("is found from any line of the fence, with the source the preview draws", async () => { + for (const line of [2, 3, 4, 5]) { + expect(diagramCellIn(text, { line })).toMatchObject({ language: "mermaid#show", index: 0 }); + } + const [block] = diagramsOf(await ir({ "a.hmd": text })); + expect(diagramCellIn(text, { line: 3 })!.source).toBe(block!.source); + }); + + it("is nothing outside a diagram cell, and nothing in a plain fence", () => { + expect(diagramCellIn(text, { line: 0 })).toBeNull(); + expect(diagramCellIn(text, { line: 8 })).toBeNull(); + expect(diagramCellIn(text, { index: 1 })).toBeNull(); + }); +}); diff --git a/tools/hmd-vsc-ext/test/engine.test.ts b/tools/hmd-vsc-ext/test/engine.test.ts index c9fa7bb..d8baef0 100644 --- a/tools/hmd-vsc-ext/test/engine.test.ts +++ b/tools/hmd-vsc-ext/test/engine.test.ts @@ -11,7 +11,7 @@ * mock that records a command string would pass whether or not it could. */ -import { chmodSync, mkdtempSync, writeFileSync } from "node:fs"; +import { chmodSync, mkdirSync, mkdtempSync, writeFileSync } from "node:fs"; import { tmpdir } from "node:os"; import { join } from "node:path"; @@ -119,6 +119,164 @@ describe("a renderer that exits without reading stdin", () => { }); }); +describe("the Mermaid renderer", () => { + /** A stand-in for `merman-cli`: an SVG that names itself and its arguments. */ + function fakeMerman(name: string): string { + const path = join(dir, name); + writeFileSync(path, `#!/bin/sh\ncat >/dev/null\nprintf '' "$*"\n`); + chmodSync(path, 0o755); + return path; + } + + it("draws a Mermaid diagram with its own binary, not with d2", async () => { + const engine = new DiagramEngine({ + bundledPath: bundled, + mermaid: { bundledPath: fakeMerman("merman-bundled") }, + }); + const mermaid = await engine.render("flowchart LR\n a --> b\n", "mermaid"); + expect(mermaid.failure).toBeNull(); + expect(decode(mermaid.dataUri)).toContain('id="merman-bundled"'); + expect(decode((await engine.render("a -> b", "d2")).dataUri)).toContain('id="bundled"'); + }); + + it("reads stdin, asks for SVG text labels, and bounds the render", async () => { + const engine = new DiagramEngine({ mermaid: { configuredPath: fakeMerman("merman-args") } }); + const svg = decode((await engine.render("flowchart LR\n a --> b\n", "mermaid")).dataUri); + expect(svg).toContain("render - --format svg"); + // HTML labels in `foreignObject` do not show inside an ``. + expect(svg).toContain("--svg-pipeline resvg-safe"); + expect(svg).toContain("--resource-profile constrained"); + expect(svg).toContain("--operation-timeout-ms 2000"); + }); + + it("prefers the configured path, then the bundled binary, then PATH", async () => { + const both = new DiagramEngine({ + mermaid: { configuredPath: fakeMerman("merman-configured"), bundledPath: fakeMerman("merman-b") }, + }); + expect(decode((await both.render("x", "mermaid")).dataUri)).toContain('id="merman-configured"'); + + fakeMerman("merman-cli"); + process.env.PATH = `${dir}:/bin:/usr/bin`; + const onPath = new DiagramEngine({ mermaid: { bundledPath: null } }); + expect(decode((await onPath.render("x", "mermaid")).dataUri)).toContain('id="merman-cli"'); + }); + + it("keeps the two languages apart in the cache", async () => { + const engine = new DiagramEngine({ + bundledPath: bundled, + mermaid: { bundledPath: fakeMerman("merman-cache") }, + }); + const source = "a --> b"; + expect(decode((await engine.render(source, "d2")).dataUri)).toContain('id="bundled"'); + expect(decode((await engine.render(source, "mermaid")).dataUri)).toContain('id="merman-cache"'); + expect(decode((await engine.render(source, "d2")).dataUri)).toContain('id="bundled"'); + }); + + it("reports a configured path that is not an executable, by its setting", async () => { + const engine = new DiagramEngine({ + mermaid: { configuredPath: join(dir, "no-merman"), bundledPath: fakeMerman("merman-unused") }, + }); + const { dataUri, failure } = await engine.render("x", "mermaid"); + expect(dataUri).toBeNull(); + expect(failure).toContain("hyperMarkdown.diagram.mermaidPath"); + }); + + it("says which program is missing when there is none", async () => { + process.env.PATH = join(dir, "empty"); + const engine = new DiagramEngine({ bundledPath: bundled }); + const { dataUri, failure } = await engine.render("x", "mermaid"); + expect(dataUri).toBeNull(); + expect(failure).toContain("merman-cli"); + expect(failure).toMatch(/PATH/); + // A missing Mermaid renderer does not take D2 down with it. + process.env.PATH = realPath; + expect((await engine.render("a -> b", "d2")).failure).toBeNull(); + }); + + it("refuses a source over the size bound without starting a renderer", async () => { + const engine = new DiagramEngine({ mermaid: { configuredPath: join(dir, "never-run") } }); + const { dataUri, failure } = await engine.render("x".repeat(64 * 1024 + 1), "mermaid"); + expect(dataUri).toBeNull(); + expect(failure).toContain("64 KiB"); + }); +}); + +describe("Show", () => { + it("answers a repeated failure from the cache, and tries again when asked", async () => { + // Fails its first two runs and draws from then on: a renderer that timed + // out under load. Two, because finding the renderer is a run of its own. + const runs = join(dir, "flaky-runs"); + const flaky = join(dir, "flaky"); + writeFileSync( + flaky, + `#!/bin/sh\ncat >/dev/null\necho run >> '${runs}'\nif [ "$(wc -l < '${runs}')" -gt 2 ]; then printf ''; else echo 'first time' >&2; exit 1; fi\n`, + ); + chmodSync(flaky, 0o755); + + const engine = new DiagramEngine({ mermaid: { configuredPath: flaky } }); + expect((await engine.render("x", "mermaid")).failure).toContain("first time"); + // Answered from the cache: the renderer would have drawn it this time. + expect((await engine.render("x", "mermaid")).failure).toContain("first time"); + const retried = await engine.render("x", "mermaid", { retry: true }); + expect(decode(retried.dataUri)).toContain('id="second"'); + }); + + it("looks again for a renderer that was missing", async () => { + const engine = new DiagramEngine({ mermaid: { bundledPath: null } }); + process.env.PATH = join(dir, "empty"); + expect((await engine.render("x", "mermaid")).failure).toContain("merman-cli"); + + const bin = join(dir, "late"); + mkdirSync(bin, { recursive: true }); + writeFileSync(join(bin, "merman-cli"), `#!/bin/sh\ncat >/dev/null\nprintf ''\n`); + chmodSync(join(bin, "merman-cli"), 0o755); + process.env.PATH = `${bin}:/bin:/usr/bin`; + expect((await engine.render("x", "mermaid")).failure).toContain("merman-cli"); + expect(decode((await engine.render("x", "mermaid", { retry: true })).dataUri)).toContain('id="late"'); + }); +}); + +/** + * The real renderer, when `MERMAN_BIN` names one. The fakes above cannot say + * whether the flags this engine passes are flags `merman-cli` accepts, or + * whether what comes back survives being shown as an image. + */ +const MERMAN_BIN = process.env["MERMAN_BIN"]; + +describe.skipIf(MERMAN_BIN === undefined)("against the real merman-cli", () => { + const real = (): DiagramEngine => new DiagramEngine({ mermaid: { configuredPath: MERMAN_BIN! } }); + + it("draws a flowchart whose labels are SVG text, with nothing that runs", async () => { + const { dataUri, failure } = await real().render( + "flowchart TD\n A[Card on disk] -->|parse| B{Has cells?}\n", + "mermaid", + ); + expect(failure).toBeNull(); + const svg = decode(dataUri); + expect(svg.startsWith("` shows neither of these: the label would be a blank box. + expect(svg).not.toContain("]*>Card on disk<\/text>/); + expect(svg).toMatch(/]*>parse<\/text>/); + }); + + it("draws the same bytes for the same source", async () => { + const source = "sequenceDiagram\n A->>B: hello\n"; + const first = await real().render(source, "mermaid"); + const second = await real().render(source, "mermaid"); + expect(first.dataUri).not.toBeNull(); + expect(second.dataUri).toBe(first.dataUri); + }); + + it("reports a syntax error as the reason, in one line", async () => { + const { dataUri, failure } = await real().render("flowchart TD\n A --> --> [\n", "mermaid"); + expect(dataUri).toBeNull(); + expect(failure).toContain("parse error"); + expect(failure!.split("\n")).toHaveLength(1); + }); +}); + describe("no renderer at all", () => { it("names what it looked for, and does not reach for Docker", async () => { process.env.PATH = join(dir, "empty"); diff --git a/tools/hmd-vsc-ext/test/grammar.test.ts b/tools/hmd-vsc-ext/test/grammar.test.ts index 3a89a5f..933c47e 100644 --- a/tools/hmd-vsc-ext/test/grammar.test.ts +++ b/tools/hmd-vsc-ext/test/grammar.test.ts @@ -100,6 +100,17 @@ describe("the cell fence grammar", () => { expect(fence("python").test("```python title=x")).toBe(true); }); + it("reads a diagram cell as its language with the mode `show`", () => { + // `d2#show` and `mermaid#show` (HMD-0030) need no rule of their own: the + // body is coloured by a D2 or Mermaid grammar when one is installed, and + // is left in one colour when none is. + const d2 = fence("d2").exec("```d2#show")!; + expect(d2.slice(4, 7)).toEqual(["d2", "#", "show"]); + const mermaid = fence("mermaid").exec("```mermaid#show")!; + expect(mermaid.slice(4, 7)).toEqual(["mermaid", "#", "show"]); + expect(fence("mermaid").test("```mermaid")).toBe(true); + }); + it("leaves a fence with a Markdown separator to the Markdown grammar", () => { for (const line of ["```python:x", "```python,x", "```{.python}", "```"]) { expect(fence("python").test(line), line).toBe(false); diff --git a/tools/hmd-vsc-ext/test/protocol.test.ts b/tools/hmd-vsc-ext/test/protocol.test.ts index daf7ccc..9931d53 100644 --- a/tools/hmd-vsc-ext/test/protocol.test.ts +++ b/tools/hmd-vsc-ext/test/protocol.test.ts @@ -60,6 +60,26 @@ describe("inbound messages", () => { expect(parseWebviewMessage(bad)).toBeNull(); } }); + + it("accepts Show for a diagram cell, and for nothing else", () => { + const show = { type: "showDiagram", language: "mermaid#show", source: "flowchart LR\n" }; + expect(parseWebviewMessage(show)).toEqual(show); + expect(parseWebviewMessage({ ...show, language: "d2#show" })).not.toBeNull(); + + for (const bad of [ + { ...show, language: "mermaid" }, + { ...show, language: "d2" }, + { ...show, language: "hql#eval" }, + { ...show, language: "Mermaid#show" }, + { ...show, language: 7 }, + { ...show, source: 7 }, + { type: "showDiagram", language: "d2#show" }, + // Over the size bound of a render: a card's own fence would be refused. + { ...show, source: "x".repeat(64 * 1024 + 1) }, + ]) { + expect(parseWebviewMessage(bad)).toBeNull(); + } + }); }); describe("path safety", () => { diff --git a/tools/hmd-vsc-ext/test/renderer.test.ts b/tools/hmd-vsc-ext/test/renderer.test.ts index 11a915c..da94fe1 100644 --- a/tools/hmd-vsc-ext/test/renderer.test.ts +++ b/tools/hmd-vsc-ext/test/renderer.test.ts @@ -2,12 +2,19 @@ * The webview renderer, under jsdom (HMD-0021 Test Plan). */ -import { MemoryHost, Renderer, Workspace, type DocumentIR } from "@hypermarkdown/core"; +import { + MemoryHost, + Renderer, + Workspace, + type DiagramBlock, + type DocumentIR, +} from "@hypermarkdown/core"; import { beforeEach, describe, expect, it } from "vitest"; import { collectAnchors, lineForOffset, + markRunning, offsetForLine, patchBlocks, renderBreadcrumb, @@ -187,6 +194,118 @@ describe("diagrams", () => { }); }); +describe("diagram cells", () => { + const card = "# T\n\n```mermaid#show\nflowchart LR\n a --> b\n```\n"; + const drawing = `data:image/svg+xml;base64,${btoa("")}`; + + type Patch = Partial>; + const withState = (document: DocumentIR, patch: Patch): DocumentIR["blocks"] => + document.blocks.map((b) => (b.kind === "diagram" ? { ...b, ...patch } : b)); + const cell = (): HTMLElement => container.querySelector(".hmd-diagram-cell")!; + const button = (name: string): HTMLButtonElement | null => + cell().querySelector(`:scope > .hmd-cell-bar > .hmd-cell-${name}`); + + it("shows the drawing and hides the source", async () => { + patchBlocks(container, withState(await ir_(card), { dataUri: drawing, current: true }), settings); + expect(cell().classList.contains("is-current")).toBe(true); + expect(cell().querySelector("img.hmd-diagram-image")!.getAttribute("src")).toBe(drawing); + expect(cell().querySelector(":scope > .hmd-cell-source")!.hidden).toBe(true); + expect(cell().querySelector(".hmd-cell-state")!.textContent).toBe("drawn"); + expect(cell().querySelector(".hmd-cell-kind")!.textContent).toBe("mermaid#show"); + }); + + it("offers Code, Edit, and Show, and no Run", async () => { + patchBlocks(container, withState(await ir_(card), { dataUri: drawing, current: true }), settings); + expect(button("code")).not.toBeNull(); + expect(button("edit")).not.toBeNull(); + expect(button("show")!.textContent).toBe("Show"); + expect(button("run")).toBeNull(); + }); + + it("carries what Show sends: the language, and the source in the hidden listing", async () => { + patchBlocks(container, withState(await ir_(card), { dataUri: drawing, current: true }), settings); + expect(cell().dataset["language"]).toBe("mermaid#show"); + expect(cell().querySelector(":scope > .hmd-cell-source > code")!.textContent).toBe( + "flowchart LR\n a --> b\n", + ); + // The fence opens on line 3, so Edit goes to line 4. + expect(cell().dataset["line"]).toBe("3"); + }); + + it("keeps the last drawing, marked stale, with the reason under it", async () => { + patchBlocks( + container, + withState(await ir_(card), { dataUri: drawing, current: false, failure: "parse error on line 2" }), + settings, + ); + expect(cell().classList.contains("is-stale")).toBe(true); + expect(cell().querySelector("img.hmd-diagram-image")).not.toBeNull(); + expect(cell().querySelector(".hmd-cell-state")!.textContent).toBe("stale"); + expect(cell().querySelector(".hmd-diagram-notice")!.textContent).toBe("parse error on line 2"); + }); + + it("shows the source and the reason when nothing was ever drawn", async () => { + patchBlocks( + container, + withState(await ir_(card), { failure: "no mermaid renderer found" }), + settings, + ); + expect(cell().classList.contains("is-none")).toBe(true); + expect(cell().querySelector("img")).toBeNull(); + expect(cell().querySelector(".hmd-cell-state")!.textContent).toBe("not drawn"); + expect(cell().querySelector(".hmd-diagram-notice")!.textContent).toBe("no mermaid renderer found"); + expect(cell().querySelector(".hmd-diagram-source")!.textContent).toContain("a --> b"); + }); + + it("keeps the element and the Code choice when the source is edited", async () => { + patchBlocks(container, withState(await ir_(card), { dataUri: drawing, current: true }), settings); + const before = cell(); + before.classList.add("is-code-shown"); + + const edited = await ir_(card.replace("a --> b", "a --> c")); + patchBlocks(container, withState(edited, { dataUri: drawing, current: true }), settings); + expect(cell()).toBe(before); + expect(cell().classList.contains("is-code-shown")).toBe(true); + expect(cell().querySelector(":scope > .hmd-cell-source")!.hidden).toBe(false); + expect(cell().querySelector(":scope > .hmd-cell-source > code")!.textContent).toContain("a --> c"); + }); + + it("delivers the drawing as an image, never as markup", async () => { + const evil = `data:image/svg+xml;base64,${btoa("")}`; + patchBlocks(container, withState(await ir_(card), { dataUri: evil, current: true }), settings); + expect(cell().querySelector("img")!.getAttribute("src")).toBe(evil); + expect(container.querySelector("svg")).toBeNull(); + }); + + it("offers Show inside an embed, where an HQL cell offers no Run", async () => { + const document = await ir( + { + "a.hmd": "![[b]]\n", + "b.hmd": "# B\n\n```d2#show\nx -> y\n```\n\n```hql#eval\n1\n```\n", + }, + "a.hmd", + ); + patchBlocks(container, document.blocks, settings); + const embedded = container.querySelector(".hmd-embed .hmd-diagram-cell")!; + expect(embedded.querySelector(".hmd-cell-show")).not.toBeNull(); + expect(container.querySelector(".hmd-embed .hmd-cell-run")).toBeNull(); + }); + + it("draws a plain `d2` fence without the cell layout", async () => { + patchBlocks(container, (await ir_("```d2\na -> b\n```\n")).blocks, settings); + expect(container.querySelector(".hmd-diagram-cell")).toBeNull(); + expect(container.querySelector(".hmd-diagram")).not.toBeNull(); + }); + + it("is not marked running when the card's HQL cells run", async () => { + const document = await ir_(`${card}\n\`\`\`hql#eval\n1\n\`\`\`\n`); + patchBlocks(container, document.blocks, settings); + markRunning(container, [-1]); + expect(cell().classList.contains("is-running")).toBe(false); + expect(container.querySelector(".hmd-cell[data-kind='cell']")!.classList.contains("is-running")).toBe(true); + }); +}); + describe("breadcrumb", () => { it("shows the namespace path and the card name", async () => { const document_ = await ir({ "specs/auth/login.hmd": "# Login\n" }, "specs/auth/login.hmd"); diff --git a/tools/hmd/src/hypermarkdown/diagram.py b/tools/hmd/src/hypermarkdown/diagram.py index 62deefc..fb6368a 100644 --- a/tools/hmd/src/hypermarkdown/diagram.py +++ b/tools/hmd/src/hypermarkdown/diagram.py @@ -1,13 +1,17 @@ -"""D2 diagrams for the Python implementation (HMD-0022 §5-§7). +"""Diagrams for the Python implementation (HMD-0022, HMD-0030, HMD-0034). HMD-0022 is a proposal of the TypeScript implementation and does not change this one: a -site build has a build step and no webview, so the no-subprocess rule of its §1 -does not apply here and the `d2` binary stays the engine. What this module -takes from it is the part that *is* shared — the semantics. - -- A ```` ```d2 ```` fence is a diagram. Its body is opaque to the resolver, and - produces no links and no graph edges (§7). The scanner already guarantees - this by masking fences. +site build has a build step and no webview, so its rule against starting a +process does not apply here and a binary stays the engine: `d2` for D2, and +`merman-cli` for Mermaid. What this module takes from it is the part that *is* +shared — the semantics. + +- A fence whose info string opens `d2#show` or `mermaid#show` is a diagram + cell, and is drawn. A plain `mermaid` fence is a listing. A plain `d2` fence + still draws, as it did before diagram cells: it becomes a listing in the + release that turns the listing rule on. +- A diagram's body is opaque to the resolver, and produces no links and no + graph edges. The scanner already guarantees this by masking fences. - A missing engine degrades to a labelled placeholder showing the source, never to a blank and never to a build failure (§5). A diagram that is merely not drawn is not a defect in the card and must not look like one. @@ -27,8 +31,16 @@ from collections import OrderedDict from dataclasses import dataclass -#: The fence info strings this module claims. -LANGUAGES = frozenset({"d2"}) +#: Fence kinds that are diagram cells, and the engine each one is drawn by. +#: Matched exactly, as an HQL cell is: `D2#show` is a listing. +CELL_KINDS = {"d2#show": "d2", "mermaid#show": "mermaid"} + +#: Plain fence languages that still draw, matched without regard to case. Only +#: `d2`, which drew before diagram cells existed. +PLAIN_LANGUAGES = frozenset({"d2"}) + +#: Every fence kind this module claims, as `engine_name` reads them. +LANGUAGES = frozenset(CELL_KINDS) | PLAIN_LANGUAGES #: Bounds on a single render (HMD-0022 §4). Shared with the TypeScript implementation so #: that a diagram refused there is refused here. @@ -36,10 +48,21 @@ MAX_SOURCE_BYTES = 64 * 1024 CACHE_ENTRIES = 64 -#: Default for `D2Engine(executable=…)`, distinguishing "find one" from "none". +#: Default for `Engine(executable=…)`, distinguishing "find one" from "none". DISCOVER = "\0discover" +def engine_name(info: str) -> str | None: + """The engine that draws a fence with this info string, or None for a listing.""" + words = info.split() + if not words: + return None + kind = words[0] + if kind in CELL_KINDS: + return CELL_KINDS[kind] + return kind.lower() if kind.lower() in PLAIN_LANGUAGES else None + + @dataclass(frozen=True) class Result: """Either an SVG, or the reason there isn't one. Never both, never neither.""" @@ -48,20 +71,27 @@ class Result: failure: str | None = None -class D2Engine: - """Renders through the `d2` binary, if one is on PATH. +class Engine: + """Renders through one binary, if it is on PATH. The engine is content-addressed and bounded rather than clever: the same source and version produce the same bytes (P1), and a hostile diagram fails instead of hanging. """ - id = "d2-binary" + #: What a diagram of this engine is called on the page. + name = "" + #: Identifies the engine in the cache key. + id = "" + #: The program looked up on PATH. + program = "" + #: Arguments that make it read source on stdin and write SVG on stdout. + args: tuple[str, ...] = () def __init__(self, executable: str | None = DISCOVER): # `None` means "no engine" and must stay expressible; discovery is what # the default argument asks for, not what an explicit None asks for. - self.executable = shutil.which("d2") if executable is DISCOVER else executable + self.executable = shutil.which(self.program) if executable is DISCOVER else executable self._cache: OrderedDict[str, Result] = OrderedDict() self._version: str | None = None @@ -86,7 +116,7 @@ def version(self) -> str: def render(self, source: str) -> Result: if not self.available: - return Result(failure="no d2 engine is installed") + return Result(failure=f"no {self.name} engine is installed") encoded = source.encode("utf-8") if len(encoded) > MAX_SOURCE_BYTES: @@ -102,7 +132,7 @@ def render(self, source: str) -> Result: def _run(self, encoded: bytes) -> Result: try: done = subprocess.run( - [self.executable, "-", "-"], + [self.executable, *self.args], input=encoded, capture_output=True, timeout=TIMEOUT_SECONDS, @@ -110,11 +140,11 @@ def _run(self, encoded: bytes) -> Result: except subprocess.TimeoutExpired: return Result(failure=f"diagram render exceeded {TIMEOUT_SECONDS}s") except OSError as exc: - return Result(failure=f"cannot run d2: {exc}") + return Result(failure=f"cannot run {self.program}: {exc}") if done.returncode != 0: detail = done.stderr.decode("utf-8", "replace").strip().splitlines() - return Result(failure=detail[-1] if detail else "d2 exited non-zero") + return Result(failure=detail[-1] if detail else f"{self.program} exited non-zero") return Result(svg=done.stdout.decode("utf-8", "replace")) def _key(self, source: str) -> str: @@ -134,8 +164,53 @@ def _store(self, key: str, result: Result) -> Result: return result -def to_html(language: str, source: str, engine: D2Engine) -> str: - """Render one diagram fence to HTML, degrading rather than failing.""" +class D2Engine(Engine): + """Draws D2 through the `d2` binary.""" + + name = "d2" + id = "d2-binary" + program = "d2" + args = ("-", "-") + + +class MermaidEngine(Engine): + """Draws Mermaid through `merman-cli`, which needs no browser. + + Three flags say what `d2` needs no flag for. `resvg-safe` draws labels as + SVG text: Mermaid's default is HTML inside `foreignObject`, which an + `` does not show. `constrained` is the renderer's resource policy for + input nobody vetted. The operation timeout is its own deadline, set to the + bound the process is killed at anyway. + """ + + name = "mermaid" + id = "merman-cli" + program = "merman-cli" + args = ( + "render", + "-", + "--format", + "svg", + "--svg-pipeline", + "resvg-safe", + "--resource-profile", + "constrained", + "--operation-timeout-ms", + str(TIMEOUT_SECONDS * 1000), + "--quiet", + ) + + +def engines() -> dict[str, Engine]: + """One engine for each diagram language, each finding its binary on PATH.""" + return {"d2": D2Engine(), "mermaid": MermaidEngine()} + + +def to_html(language: str, source: str, engine: Engine) -> str: + """Render one diagram fence to HTML, degrading rather than failing. + + `language` is the name the page gives the diagram: `d2` or `mermaid`. + """ result = engine.render(source) if result.svg: return _image(result.svg, language) diff --git a/tools/hmd/src/hypermarkdown/mkdocs_plugin.py b/tools/hmd/src/hypermarkdown/mkdocs_plugin.py index a4920ed..cc2f5af 100644 --- a/tools/hmd/src/hypermarkdown/mkdocs_plugin.py +++ b/tools/hmd/src/hypermarkdown/mkdocs_plugin.py @@ -58,8 +58,9 @@ class PluginConfig(BaseConfig): #: `doc/wiki`, so a book and its wiki live in one build. root = config_options.Optional(config_options.Dir(exists=True)) build_nav = config_options.Type(bool, default=True) - #: Render `d2` fences. With no `d2` binary on PATH they degrade to a - #: labelled placeholder rather than failing the build (HMD-0022 §5). + #: Draw diagram fences: D2 through `d2`, Mermaid through `merman-cli`. With + #: a binary missing from PATH its diagrams degrade to a labelled + #: placeholder rather than failing the build (HMD-0022, on degradation). diagrams = config_options.Type(bool, default=True) @@ -75,7 +76,8 @@ def __init__(self) -> None: #: Where the namespace root sits inside `docs_dir`, as a URL prefix. self.prefix = "" self.docs_dir: Path | None = None - self.engine = diagram.D2Engine() + #: The engine for each diagram language: `d2` and `mermaid`. + self.engines = diagram.engines() #: Card -> the `toc` id of each of its headings on its built page. self._ids: dict[Path, list[str]] = {} #: How `toc` is configured for this site: slugify, separator, and @@ -310,7 +312,10 @@ def _written_dir(self, source: Path, registered: str) -> str: return "" if directory == "." else directory def _diagrams(self, markdown: str) -> str: - """Render `d2` fences to images, or to a labelled placeholder. + """Render diagram fences to images, or to a labelled placeholder. + + A `d2#show` or `mermaid#show` cell is drawn, and so is a plain `d2` + fence. A plain `mermaid` fence is a listing and stays a code block. Runs after expansion, so a diagram embedded from another card renders like one written here. @@ -321,11 +326,11 @@ def _diagrams(self, markdown: str) -> str: out: list[str] = [] cursor = 0 for info, body, start, end in scan.find_fences(markdown): - language = info.split()[0].lower() if info.split() else "" - if language not in diagram.LANGUAGES: + name = diagram.engine_name(info) + if name is None: continue out.append(markdown[cursor:start]) - out.append(diagram.to_html(language, body, self.engine) + "\n") + out.append(diagram.to_html(name, body, self.engines[name]) + "\n") cursor = end out.append(markdown[cursor:]) diff --git a/tools/hmd/tests/test_diagram.py b/tools/hmd/tests/test_diagram.py index 45528ab..e153cb4 100644 --- a/tools/hmd/tests/test_diagram.py +++ b/tools/hmd/tests/test_diagram.py @@ -137,3 +137,149 @@ def test_the_real_engine_renders_deterministically(): assert first.svg and " b").svg == first.svg + + +# -- diagram cells: which fences are drawn, and by which engine ----------- + + +@pytest.mark.parametrize( + ("info", "engine"), + [ + ("d2#show", "d2"), + ("mermaid#show", "mermaid"), + ("mermaid#show wide", "mermaid"), + # A plain `d2` fence still draws, without regard to case. + ("d2", "d2"), + ("D2 something", "d2"), + ], +) +def test_a_diagram_fence_names_its_engine(info, engine): + assert diagram.engine_name(info) == engine + + +@pytest.mark.parametrize( + "info", + ["mermaid", "Mermaid", "D2#show", "Mermaid#show", "mermaid#Show", "d2#eval", "hql#eval", "python", ""], +) +def test_every_other_fence_is_a_listing(info): + """A cell kind is matched exactly, and a plain `mermaid` fence is how a + card shows Mermaid source as text.""" + assert diagram.engine_name(info) is None + + +def test_there_is_one_engine_for_each_language(): + engines = diagram.engines() + assert sorted(engines) == ["d2", "mermaid"] + assert set(diagram.CELL_KINDS.values()) == set(engines) + assert isinstance(engines["mermaid"], diagram.MermaidEngine) + + +# -- the Mermaid engine --------------------------------------------------- + + +class FakeMermaid(diagram.MermaidEngine): + """A Mermaid engine that renders without a binary, counting its invocations.""" + + def __init__(self, svg: str = "ok", fail: str | None = None): + super().__init__(executable="/nonexistent/merman-cli") + self._version = "test-1" + self.svg, self.fail, self.calls = svg, fail, 0 + + def _run(self, encoded: bytes) -> diagram.Result: + self.calls += 1 + return diagram.Result(failure=self.fail) if self.fail else diagram.Result(svg=self.svg) + + +def test_a_rendered_mermaid_diagram_is_a_data_uri_image(): + html = diagram.to_html("mermaid", "flowchart LR\n a --> b", FakeMermaid()) + assert "data:image/svg+xml;base64," in html + assert 'alt="mermaid diagram"' in html + assert " b", diagram.MermaidEngine(executable=None)) + assert "hmd-diagram--placeholder" in html + assert "a --> b" in html + assert "mermaid diagram — no mermaid engine is installed" in html + + +def test_a_mermaid_failure_is_shown_with_the_source(): + html = diagram.to_html("mermaid", "flowchart TD\n A --> -->", FakeMermaid(fail="Diagram parse error")) + assert "A --> -->" in html + assert "Diagram parse error" in html + + +def test_mermaid_shares_the_bounds_of_d2(): + engine = FakeMermaid() + result = engine.render("a" * (diagram.MAX_SOURCE_BYTES + 1)) + assert result.svg is None and "64 KiB" in result.failure + assert engine.calls == 0, "the engine must not be handed oversized input" + + engine.render("flowchart LR") + engine.render("flowchart LR") + assert engine.calls == 1, "an identical source renders once" + + for index in range(diagram.CACHE_ENTRIES + 1): + engine.render(f"flowchart LR\n n{index}") + assert len(engine._cache) == diagram.CACHE_ENTRIES + + +def test_the_two_engines_do_not_share_a_cache_key(): + """The same text is one diagram in D2 and another in Mermaid.""" + assert FakeEngine()._key("a --> b") != FakeMermaid()._key("a --> b") + + +def test_mermaid_is_asked_for_svg_text_on_stdin_within_the_bound(): + args = diagram.MermaidEngine.args + assert args[:2] == ("render", "-") + # HTML labels in `foreignObject` do not show inside an ``. + assert args[args.index("--svg-pipeline") + 1] == "resvg-safe" + assert args[args.index("--resource-profile") + 1] == "constrained" + assert args[args.index("--operation-timeout-ms") + 1] == str(diagram.TIMEOUT_SECONDS * 1000) + + +def test_the_engine_runs_the_binary_it_was_given_with_its_arguments(tmp_path): + """A stand-in for `merman-cli`: an SVG that carries its arguments and its input.""" + script = tmp_path / "merman-cli" + script.write_text('#!/bin/sh\nprintf \'\' "$*"\ncat\nprintf \'\'\n') + script.chmod(0o755) + svg = diagram.MermaidEngine(executable=str(script)).render("flowchart LR").svg + assert svg is not None + assert "render - --format svg --svg-pipeline resvg-safe" in svg + assert "flowchart LR" in svg + + +def test_a_renderer_that_fails_gives_its_last_line_as_the_reason(tmp_path): + script = tmp_path / "merman-cli" + script.write_text("#!/bin/sh\ncat >/dev/null\necho 'noise' >&2\necho 'Diagram parse error' >&2\nexit 1\n") + script.chmod(0o755) + result = diagram.MermaidEngine(executable=str(script)).render("flowchart TD") + assert result.svg is None and result.failure == "Diagram parse error" + + +@pytest.mark.skipif(not diagram.MermaidEngine().available, reason="no merman-cli binary on PATH") +def test_the_real_mermaid_engine_draws_text_labels_deterministically(): + source = "flowchart TD\n A[Card on disk] -->|parse| B{Has cells?}\n" + first = diagram.MermaidEngine().render(source) + assert first.svg and first.svg.startswith("` shows neither of these: the label would be a blank box. + assert "Card on disk" in first.svg + # A second, uncached engine must produce the same bytes (P1). + assert diagram.MermaidEngine().render(source).svg == first.svg + + +@pytest.mark.skipif(not diagram.MermaidEngine().available, reason="no merman-cli binary on PATH") +def test_the_real_mermaid_engine_reports_a_syntax_error(): + result = diagram.MermaidEngine().render("flowchart TD\n A --> --> [\n") + assert result.svg is None and "parse error" in result.failure From f088458fee1e8e49e517979afd14ace203b7a405 Mon Sep 17 00:00:00 2001 From: Yauhen Yakimovich Date: Wed, 25 Nov 2026 21:26:40 +0100 Subject: [PATCH 2/4] docs: HMD-0034, Mermaid drawn by a native renderer HMD-0034 records the renderer choice with its measurements: merman-cli, run with the resvg-safe pipeline under the bounds D2 has. HMD-0030 is amended: a diagram cell is drawn as its source is edited, in both languages, and stale means the edited source does not draw. The rejection of Mermaid as superseded by D2 is reversed in the source sketch, in HMD-0001, and in HMD-0022. The trackers move the rows this branch closes to Done. What remains is recorded as blocked on a toolchain release that pins merman-cli: the extension build, CI and the Pages build, and the public pages. --- doc/models/requirements/initial_sketch.hmd | 4 +- doc/proposals/HMD-0001/index.hmd | 10 +- doc/proposals/HMD-0022/index.hmd | 12 +- doc/proposals/HMD-0030/index.hmd | 112 +++++--- doc/proposals/HMD-0034/index.hmd | 302 +++++++++++++++++++++ doc/proposals/index.hmd | 1 + doc/status/hmd.hmd | 48 ++-- doc/status/lang.hmd | 12 +- doc/status/open.hmd | 19 +- doc/status/pages.hmd | 4 + doc/status/proposals.hmd | 3 +- doc/status/ts-core.hmd | 13 +- doc/status/vsc-ext.hmd | 24 +- tools/hmd-ts-core/CHANGELOG.md | 21 ++ tools/hmd-vsc-ext/CHANGELOG.md | 31 +++ tools/hmd/CHANGELOG.md | 13 + 16 files changed, 547 insertions(+), 82 deletions(-) create mode 100644 doc/proposals/HMD-0034/index.hmd diff --git a/doc/models/requirements/initial_sketch.hmd b/doc/models/requirements/initial_sketch.hmd index 7134844..8aaedd6 100644 --- a/doc/models/requirements/initial_sketch.hmd +++ b/doc/models/requirements/initial_sketch.hmd @@ -99,7 +99,9 @@ grammar. | 16 | D2 diagrams | ```d2 | free — `mkdocs-d2-plugin` | | 17 | GFM baseline | tables, task lists, fenced code, strikethrough | free | -**Explicitly excluded:** highlights (`==text==`), Mermaid (superseded by D2). +**Explicitly excluded:** highlights (`==text==`). Mermaid was excluded here +too, as superseded by D2. That is reversed: Mermaid is a diagram language with +the same standing as D2 ([HMD-0034](../../proposals/HMD-0034/index.hmd)). **Notes on the free items.** diff --git a/doc/proposals/HMD-0001/index.hmd b/doc/proposals/HMD-0001/index.hmd index c35263b..00a7c40 100644 --- a/doc/proposals/HMD-0001/index.hmd +++ b/doc/proposals/HMD-0001/index.hmd @@ -166,9 +166,11 @@ block_id := ALPHA / DIGIT *63( ALPHA / DIGIT / "_" / "-" ) vocabulary (P3) — but the whole mapping is exposed in the model and in `hmd graph` output. -**Explicitly excluded from the MVP grammar:** inline properties (`key:: value`), -highlights (`==text==`), and Mermaid. The first is deferred; the latter two are -rejected by the source. +**Explicitly excluded from the MVP grammar:** inline properties (`key:: value`) +and highlights (`==text==`). The first is deferred; the second is rejected by +the source. Mermaid was excluded here too, as superseded by D2. HMD-0034 +reverses that: a `mermaid#show` fence is a diagram with the same standing as +a `d2#show` fence. ### 3. Heading anchors @@ -792,6 +794,8 @@ excerpts versus block anchors (Q3), and the query grammar (Q6). ## Changelog +- 2026-11-25: Mermaid is no longer excluded from the grammar; HMD-0034 accepts + it as a diagram language beside D2. - 2026-07-31: drafted - 2026-07-31: §5 reworked from recursive-per-scope to the two-phase spine walk plus single root sweep; folder-note binding added (HMD012); worked example diff --git a/doc/proposals/HMD-0022/index.hmd b/doc/proposals/HMD-0022/index.hmd index c89cb10..dcc288e 100644 --- a/doc/proposals/HMD-0022/index.hmd +++ b/doc/proposals/HMD-0022/index.hmd @@ -73,7 +73,10 @@ and never as a defect in the card. - **Changing the Python implementation**, which renders through the same binary at build time. - **The interactive graph view.** HMD-0021 §10 owns it; §5 fixes the boundary. -- **Mermaid**, rejected by the source sketch as superseded by D2. +- **Choosing a renderer for Mermaid.** Mermaid was rejected here as superseded + by D2. HMD-0034 reverses that: Mermaid is a diagram language with the same + standing as D2, drawn by its own native renderer under the bounds, the + cache, and the image delivery of this record. ## Specification @@ -285,8 +288,8 @@ npm run -w tools/hmd-vsc-ext test - Should a failed diagram raise a diagnostic? It is visible in the preview, and a new rule ID would have to be allocated by the canonical implementation (HMD-0020 §9). -- Should `DiagramBlock` generalise to other fence languages now, given - `language` is already a field, or stay D2-only until a second one is real? +- Answered by HMD-0034: `DiagramBlock` carries Mermaid as well as D2. Its + `language` field already existed, and a second language is now real. - Does the preview honour `rsvg-convert` for a PNG fallback, as the slides style does, or is SVG sufficient inside an editor? @@ -300,3 +303,6 @@ npm run -w tools/hmd-vsc-ext test - 2026-11-22: amended by HMD-0030. A diagram is a `d2#show` or `mermaid#show` fence, matched exactly; a plain `d2` fence is a listing. The renderer, bounds, cache, and image delivery here are unchanged. +- 2026-11-25: amended by HMD-0034. Mermaid is no longer a non-goal: it is + drawn by `merman-cli` under the bounds here, and the cache key gains the + diagram language. diff --git a/doc/proposals/HMD-0030/index.hmd b/doc/proposals/HMD-0030/index.hmd index c1c73e3..15d2c3e 100644 --- a/doc/proposals/HMD-0030/index.hmd +++ b/doc/proposals/HMD-0030/index.hmd @@ -16,12 +16,12 @@ A fence whose info string opens `d2#show` or `mermaid#show` is a **diagram cell**. The preview draws it the way it draws an `hql#eval` cell: the picture first, the source behind a **Code** toggle, and an **Edit** button beside it. Where an HQL cell has **Run**, a diagram cell has **Show**. A diagram cell is -drawn when the card opens. After its source is edited it keeps its last -drawing, marked stale, until the reader presses Show. The drawing lives in the -preview only; nothing is written into the card. A plain `d2` or `mermaid` -fence becomes a **listing**, shown as code, exactly as a plain `hql` fence is. -The document IR's `DiagramBlock` gains a staleness state and moves to version -4. +drawn when the card opens, and drawn again as its source is edited. When an +edit leaves source that does not draw, the cell keeps its last drawing, marked +stale, with the reason under it. The drawing lives in the preview only; +nothing is written into the card. A plain `d2` or `mermaid` fence becomes a +**listing**, shown as code, exactly as a plain `hql` fence is. The document +IR's `DiagramBlock` gains the state of its drawing and moves to version 5. ## Motivation @@ -33,10 +33,14 @@ The document IR's `DiagramBlock` gains a staleness state and moves to version - **A reader wants the picture; an author wants the source.** The notebook layout already solves this for HQL: answer first, code one click away. A diagram is the same shape of thing. -- **Mermaid cannot be drawn on every keystroke.** Its reference renderer - drives a headless browser, and a cold start does not fit the two-second - bound D2 meets. Drawing on open and on Show, and never while typing, keeps - the preview responsive whichever renderer Mermaid ends up with. +- **An author watches the diagram while typing it.** D2 has always been drawn + as its source changes, and that is the feature an author uses most. The cell + layout keeps it, for D2 and for Mermaid. Mermaid's renderer is a native + program that draws in milliseconds, so it needs no exception. +- **A broken edit should not blank the diagram.** Half-typed source does not + draw. A cell that kept nothing would flicker between a picture and an error + on every keystroke, so it keeps its last drawing until the source draws + again. **What this must not break.** A card with diagram cells renders completely with no renderer installed: each cell shows its source and says why it is not @@ -46,7 +50,8 @@ drawn. - `d2#show` and `mermaid#show` behave like HQL cells in the preview, with Show in place of Run. -- No renderer starts while the reader types. +- A diagram follows its source as the author types, in both languages. +- A cell never loses its drawing to an edit that does not draw. - The card stays text: showing a diagram never edits the file. ## Non-goals @@ -55,8 +60,8 @@ drawn. artifacts as more machinery than the problem has, and this record keeps that decision. - **Choosing Mermaid's renderer.** That choice, its bounds, and its security - settings belong to the Mermaid card. Until it is made, a `mermaid#show` cell - shows its source and says no renderer is available. + settings are made in HMD-0034: a native renderer, `merman-cli`, under the + bounds D2 has. - **Interactive diagrams.** A drawing still reaches the page as an image, so links and click handlers inside it do nothing. - **New diagram languages.** Only `d2` and `mermaid` get a `#show` kind. @@ -100,20 +105,26 @@ The first is drawn; the second is shown as code. ### When a diagram cell is drawn -A cell is drawn when the card is shown, and again when the reader asks. - -- When the preview first shows a card, it MUST draw each diagram cell whose - renderer is available, within the bounds of HMD-0022. A drawing already in - the cache is used without starting a renderer. -- When a cell's source changes, the preview MUST NOT start a renderer. If the - new source is in the cache — after an undo, say — that drawing is shown and - the cell is current. Otherwise the last drawing stays on screen, marked - **stale**. -- **Show** draws the cell's current source and replaces its drawing. It is - also how a reader retries after a timeout or a failure. -- A cell whose source has never been drawn, and is not in the cache, is **not - drawn**, with the reason: no renderer, a syntax error, a timeout, or a - source over the size bound. +A cell is drawn when the card is shown, again whenever its source changes, +and again when the reader asks. + +- When the preview shows a card, it MUST draw each diagram cell whose renderer + is available, within the bounds of HMD-0022. A drawing already in the cache + is used without starting a renderer. +- When a cell's source changes, the preview MUST draw the new source, on the + same delay it re-reads the card on. If the new source is in the cache — + after an undo, say — that drawing is shown without starting a renderer. +- When the new source does not draw, the last drawing MUST stay on screen, + marked **stale**, with the reason under it: a syntax error, a timeout, or a + source over the size bound. The cell is current again as soon as its source + draws. +- A cell whose source has never drawn is **not drawn**. It shows its source + and the reason. +- **Show** draws the cell's current source again. A failure is not answered + from the cache, and a renderer that was missing is looked for again, so Show + is how a reader retries after a timeout or after installing a renderer. +- A drawing kept for a stale cell belongs to one preview and one card. It is + dropped when the preview moves to another card. The cache is HMD-0022's: in memory, keyed by source, bounded to 64 entries, least recently used evicted. @@ -167,8 +178,10 @@ DiagramBlock := { } ``` -- `IR_VERSION` becomes **4**. A webview that receives another version refuses +- `IR_VERSION` becomes **5**. A webview that receives another version refuses to render and asks for a reload. +- `language` is `d2` for a plain `d2` fence for as long as that fence still + draws. Such a block has no cell layout and keeps its key by source. - The key is the cell's position among diagram cells, not its content. Editing a cell would otherwise give it a new key, and the reader's Code toggle and the stale drawing would be lost with it. @@ -180,8 +193,8 @@ DiagramBlock := { The canonical implementation follows the same fence rule. - A site build MUST draw `d2#show` cells, with the renderer and bounds it uses - today, and MUST render a plain `d2` fence as a code block. `mermaid#show` - draws once the Mermaid renderer is chosen. + today, and MUST render a plain `d2` fence as a code block. It MUST draw + `mermaid#show` cells with the renderer HMD-0034 chooses. - How a built page shows a diagram cell's source is an open question below. Until it is answered, the page shows the drawing only, as it does today. @@ -197,7 +210,7 @@ The canonical implementation follows the same fence rule. draw. - **HQL's `mermaid` format step writes a plain `mermaid` fence**, which becomes a listing. HQL is asked to write `mermaid#show`. -- **`IR_VERSION` moves from 3 to 4.** A stale webview shows the reload message. +- **`IR_VERSION` moves from 4 to 5.** A stale webview shows the reload message. - No card changes on disk because of this record. Showing a diagram never writes. @@ -215,15 +228,16 @@ Nothing new runs, and nothing runs on new input. ## Deployment / Activation -1. In both implementations, recognise `d2#show` as a diagram, beside plain - `d2`. Both still draw, so nothing breaks. +1. In both implementations, recognise `d2#show` and `mermaid#show` as diagram + cells, beside plain `d2`. All three draw, so nothing breaks. In the same + release, land the preview's cell layout, Show, the stale state, and + `IR_VERSION` 5 for the two cell kinds. 2. Rewrite every `d2` fence in this repository as `d2#show`. -3. In one release of each tool, turn plain `d2` into a listing, and land the - preview's cell layout, Show, the stale state, and `IR_VERSION` 4. State the +3. Ask HQL to write `d2#show` and `mermaid#show` where it writes `d2` and + `mermaid` today. A cell's output is machine-written, and it would otherwise + become a listing in the next step. +4. In one release of each tool, turn plain `d2` into a listing. State the change in each changelog, with the one-line migration: rename the fence. -4. Add `mermaid#show` to the recognised kinds. It shows its source until the - Mermaid renderer lands. -5. Ask HQL to write `mermaid#show` from its `mermaid` step. ## Reference Implementation @@ -248,10 +262,13 @@ Unit tests MUST include: and every other kind are not. - A diagram cell takes no HQL cell number and is untouched by the HQL mask. - A diagram cell's body yields no link and no edge. -- On first render the cell is drawn; after an edit no renderer starts and the - cell is stale; after an undo to a cached source it is current again without - a render. -- Show replaces the drawing and clears stale; a failed draw keeps the reason. +- On first render the cell is drawn; after an edit that draws, the new + drawing is shown and the cell is current; after an edit that does not draw, + the last drawing is kept and the cell is stale, with the reason. +- A source drawn before is answered from the cache without a render. +- Show draws a failed source again and does not answer from the cache; it + looks again for a renderer that was missing. +- One cell's last drawing is never shown under another cell. - The Code toggle survives an edit and a redraw. - Show is offered inside an embed, and Run is still not. - The key of a diagram cell does not change when its source does. @@ -284,6 +301,13 @@ uv run python -m pytest tools/hmd/tests/test_diagram.py ## Changelog - 2026-11-22: drafted. +- 2026-11-25: a cell is drawn as its source is edited, in both languages. The + first draft forbade a renderer while the author types, because Mermaid was + expected to need a headless browser; HMD-0034 chose a native renderer that + draws in milliseconds. Stale now means that the edited source does not + draw. `IR_VERSION` is 5, because 4 was taken by heading keys. The cell + layout lands with the two `#show` kinds, before a plain `d2` fence becomes + a listing. ## See also @@ -291,5 +315,5 @@ uv run python -m pytest tools/hmd/tests/test_diagram.py Edit, and the listing rule this record extends to diagrams. - [HMD-0022](../HMD-0022/index.hmd) — the diagram block, the renderer, its bounds, its cache, and its image delivery, all kept here. -- [The Mermaid card](../../issues/0115-mermaid-diagrams-on-par-with-d2.hmd) — - the Mermaid renderer, still to be chosen. +- [HMD-0034](../HMD-0034/index.hmd) — the Mermaid renderer, its arguments, + and its bounds. diff --git a/doc/proposals/HMD-0034/index.hmd b/doc/proposals/HMD-0034/index.hmd new file mode 100644 index 0000000..b4dbd5f --- /dev/null +++ b/doc/proposals/HMD-0034/index.hmd @@ -0,0 +1,302 @@ +--- +nav: + visibility: public +--- + +# HMD-0034: Mermaid, drawn by a native renderer + +**Status**: drafted +**Created**: 2026-11-25 +**Source**: [the board card that opened the work](../../issues/0115-mermaid-diagrams-on-par-with-d2.hmd) + +## Abstract + +Mermaid is a diagram language of HyperMarkDown with the same standing as D2. +A fence whose info string opens `mermaid#show` is a diagram cell, and every +tool that draws a `d2#show` cell draws it. The renderer is `merman-cli`, a +native program that draws Mermaid without a browser. It is run the way `d2` is +run: the fence body on standard input, SVG on standard output, within the same +bounds, delivered as a `data:` image. It is pinned in the toolchain beside +`d2`. This record reverses the earlier rejection of Mermaid as superseded by +D2. Neither language is the default. + +## Motivation + +- **Readers already know Mermaid.** GitHub, GitLab, and Obsidian draw it, and + it is the diagram language most Markdown authors have used. A card brought in + from elsewhere carries Mermaid, not D2. +- **HQL already writes Mermaid.** Its `mermaid` format step emits a Mermaid + fence, and every preview and site build then shows that output as code. One + half of the toolchain produces a diagram that the other half does not draw. +- **The reason for the rejection was the renderer.** Mermaid's reference + renderer is a JavaScript library that lays out text through a browser, and + its command-line tool drives a headless Chromium. That is hundreds of + megabytes per platform and a cold start of seconds. A native renderer removes + both costs, so the rejection no longer has a reason. + +**What this must not break.** A card with Mermaid cells renders completely +with no renderer installed: each cell shows its source and says why it is not +drawn. D2 keeps everything it has. + +## Goals + +- There is nothing D2 gets that Mermaid does not: the fence rule, the + TypeScript implementation, the site build, the editor preview, the toolchain + pin, the bounds, the image delivery, and the degraded state. +- One renderer draws Mermaid in the editor and on the site, so a diagram looks + the same in both. +- No browser, no Node runtime, and no container is needed to draw a diagram. + +## Non-goals + +- **Drawing a plain `mermaid` fence.** A plain `mermaid` fence is a listing, + shown as code. This is the rule for every diagram language, and it means a + Mermaid block written for GitHub or Obsidian shows as code here until its + fence is renamed to `mermaid#show`. +- **Interactive diagrams.** A drawing reaches the page as an image, so a + `click` directive, a link, or a tooltip inside it does nothing. +- **Pixel parity with mermaid.js.** The renderer follows Mermaid's syntax and + layout closely. It is a second implementation, and a drawing can differ in + detail from what a browser draws. +- **A second renderer as a fallback.** A diagram drawn by one renderer in the + editor and another on the site would differ from itself. + +## Specification + +### The fence + +- A fence whose kind is `mermaid#show` MUST be a diagram cell. Matching is + exact and case-sensitive: `Mermaid#show` is a listing. +- A plain `mermaid` fence MUST NOT be drawn. +- The body of a Mermaid cell is opaque to the resolver. It yields no link, no + embed, no anchor, and no graph edge, even where Mermaid's own syntax uses + double square brackets for a node shape. + +````markdown +```mermaid#show +flowchart LR + client --> server +``` + +```mermaid +flowchart LR + client --> server +``` +```` + +The first is drawn; the second is shown as code. + +### The renderer + +The renderer is `merman-cli`, from the `merman` project, version 0.11.0. + +- It is a native program written in Rust. It starts no browser and needs no + JavaScript runtime. +- It publishes a binary for each of the five toolchain platforms: Linux on + x86-64 and ARM64, macOS on x86-64 and ARM64, and Windows on x86-64. +- Its licence is MIT or Apache-2.0, at the user's choice. The layout engine it + bundles for some diagram types is under EPL-2.0. The toolchain archive + carries the licence files with the binary. +- It follows Mermaid 12 and draws more than thirty diagram types, including + flowchart, sequence, class, state, entity-relationship, Gantt, pie, mindmap, + timeline, and Git graph. + +An implementation MUST run it with exactly these arguments, with the fence +body on standard input: + +```text +merman-cli render - --format svg --svg-pipeline resvg-safe \ + --resource-profile constrained --operation-timeout-ms 2000 --quiet +``` + +- `render -` reads the source from standard input and writes the drawing to + standard output. No path, no workspace, and no environment from the card + reaches the process. +- `--svg-pipeline resvg-safe` draws every label as SVG text. Mermaid's default + draws labels as HTML inside a `foreignObject` element, and an image does not + show the content of that element: the diagram would arrive with empty boxes. +- `--resource-profile constrained` is the renderer's own resource policy for + input nobody has vetted. It bounds the source size, the size of the parsed + model, the layout work, and the size of the SVG. +- `--operation-timeout-ms 2000` is the renderer's own deadline. The + implementation still kills the process at the shared bound. + +The renderer MUST NOT be given `--allow-network`. Without it the renderer +opens no connection, so an icon pack named in a diagram is not fetched. + +### Bounds + +Mermaid shares the numbers D2 has. Both implementations refuse the same input +for the same stated reason. + +| Bound | Value | +| --- | --- | +| Source size | 64 KiB | +| Time for one render | 2 seconds | +| Cached drawings | 64, least recently used evicted | + +The 2-second bound holds with room to spare. On an Apple M-series machine a +flowchart, a sequence diagram, a class diagram, a state diagram, an +entity-relationship diagram, and a Gantt chart each drew in about 10 +milliseconds, which is faster than `d2` draws. + +The cache key holds the diagram language as well as the source, because the +same text is one diagram in D2 and another in Mermaid. + +### When a Mermaid cell is drawn + +A Mermaid cell is drawn exactly when a D2 cell is, as the record on diagram +cells specifies: when the card is shown, and again as its source is edited. +The earlier draft of that record forbade drawing while the author types, +because Mermaid was expected to need a headless browser. The native renderer +draws in milliseconds, so that restriction is withdrawn for both languages. + +### Delivery and security + +- The drawing MUST reach the page as a `data:` URI image and MUST NOT be + inserted as markup. An image runs no script and follows no link, so nothing + in diagram source reaches the page as code. +- Drawing MUST NOT require a trusted workspace. The process gets the fence + body and nothing else. +- A `click` directive or a link in a diagram is written into the SVG as a + link. Inside an image it does nothing. + +### Configuration inside the fence + +Mermaid lets a diagram configure itself, with an `%%{init: …}%%` directive or +a frontmatter block at the top of its body. + +- Configuration inside the fence is honoured. A diagram that asks for the + `dark` theme is drawn in the dark theme. +- It cannot widen what the renderer may do. The resource profile, the + timeout, and the absence of network access are set on the command line, and + the image delivery is the implementation's. + +### Theme + +A drawing sits on a white surface in every editor theme, as a D2 drawing +does. Mermaid ships a dark theme and D2 ships one too, so drawing each diagram +for the editor's theme is possible for both, and remains the open question it +was for D2. + +### The degraded state + +A Mermaid cell that is not drawn shows its source, labelled, with the reason. +The wording is the same as for D2, with the engine's name in it. + +| Cause | What the reader sees | +| --- | --- | +| No renderer | The source, and that no Mermaid renderer was found | +| A syntax error | The renderer's own one-line message | +| A timeout | That the render exceeded 2 seconds | +| A source over 64 KiB | That the source exceeds 64 KiB | + +In the preview, a cell that drew before keeps its last drawing, marked stale, +with the reason under it. On a built page there is no earlier drawing, and the +page shows the source. + +### Where the renderer comes from + +- The toolchain repository pins `merman-cli` beside `d2`, one asset per + platform with its digest, and each archive carries it at `bin/merman-cli` + (`bin/merman-cli.exe` on Windows). +- The extension's package for each platform carries the binary at + `toolchain/bin/`. The extension downloads nothing. +- The extension looks for the renderer in this order: the path in the + setting `hyperMarkdown.diagram.mermaidPath`, then the bundled binary, then + `merman-cli` on `PATH`. A setting that names something that is not an + executable is reported, and the search stops there. +- The site build finds `merman-cli` on `PATH`. Continuous integration installs + the pinned toolchain and checks `merman-cli --version` beside `d2 --version`. + +### The cover's live editor + +The cover's live editor shows a diagram as its text, D2 included. Mermaid gets +the same treatment. + +## Rationale + +- **A native renderer, not Mermaid's own command-line tool.** Mermaid's tool + is faithful, because it is Mermaid. It needs Node and a pinned Chromium, + which is hundreds of megabytes in each platform package, and a cold start + that does not fit in 2 seconds. +- **A native renderer, not mermaid.js inside the preview.** Running the + library in the webview puts diagram source into a script context in the + preview, which the image delivery exists to prevent. It also does nothing + for the site build, which has no browser. +- **`merman-cli`, not `mmdr`.** `mmdr` is the other native renderer with + binaries for all five platforms, and its binary is a tenth of the size. Its + own documentation says its output may not match Mermaid's, it draws fewer + diagram types, and its last release is five months old. `merman-cli` is + checked against Mermaid, its output is the same bytes on every run, it has + resource limits built in, and it released four days before this record. +- **The cost is size.** The `merman-cli` binary is about 66 MB unpacked and + 16 MB to 26 MB compressed, per platform. Each platform package of the + extension grows by that much. + +## Backwards Compatibility + +- No card changes. A plain `mermaid` fence was a code block and stays one. +- A `mermaid#show` fence was a code block in every earlier release. It is + drawn from the release that carries this record. +- The settings, the bounds, and the delivery of D2 are unchanged. + +## Security Considerations + +- A new program runs on text from a cloned repository. It is a pinned binary + with a checked digest, it reads standard input only, it is bounded in time + and in resources, and its output is shown as an image. +- The renderer is given no network access. +- SVG is a scripting context. The drawing is never inserted as markup, so a + script or an event handler in it cannot run. + +## Test Plan + +Unit tests MUST include, for Mermaid, each test that exists for D2: + +- `mermaid#show` is a diagram cell; `mermaid`, `Mermaid#show`, and every other + kind are not. +- The body of a Mermaid cell yields no link and no edge. +- The cache key differs between the two languages for the same source. +- A missing renderer, a failed render, and an oversized source each show the + labelled source with the reason. +- A hostile SVG reaches the page as base64 in an image and never as markup. +- The renderer is started with the arguments above. + +Tests against the real binary MUST include: + +- A flowchart draws with its labels as SVG text, with no `foreignObject` + element and no `script` element. +- The same source draws the same bytes twice. +- A syntax error comes back as a one-line reason. + +Integration tests MUST include: + +- A site build of a card with a `mermaid#show` cell and a plain `mermaid` + fence draws the first and shows the second as code. +- A site build with no renderer shows the source and stays green. + +## Open Questions + +- Should HQL's `mermaid` format step write `mermaid#show`? Until it does, the + output of that step is a listing. +- Should a plain `mermaid` fence raise a diagnostic suggesting `#show`? It + would help a vault brought in from elsewhere, and it would fire on every + deliberate listing. +- Should a smaller build of the renderer be produced, with only the diagram + types a documentation site needs? It would cut the package size, and the + toolchain would then build a binary instead of repackaging a released one. + +## Changelog + +- 2026-11-25: drafted, with the renderer chosen and measured. + +## See also + +- [HMD-0030](../HMD-0030/index.hmd) — diagram cells: the `#show` kinds, the + preview's layout, and when a cell is drawn. +- [HMD-0022](../HMD-0022/index.hmd) — the diagram block, the bounds, the + cache, and the image delivery that Mermaid shares. +- [merman](https://github.com/latias94/merman) — the renderer. +- [The toolchain card](../../issues/archive/0107-toolchain-repository-for-native-binaries.hmd) + — why native binaries are pinned in one repository. diff --git a/doc/proposals/index.hmd b/doc/proposals/index.hmd index 2e1da5d..8e6d7df 100644 --- a/doc/proposals/index.hmd +++ b/doc/proposals/index.hmd @@ -37,6 +37,7 @@ it continues at **`HMD-0100`**, leaving `0020`–`0099` to the editor line. | [HMD-0031](HMD-0031/index.hmd) | drafted | Freeze — every open finding against 0.1, consolidated before fixing | [lang](../status/lang.hmd) | | [HMD-0032](HMD-0032/index.hmd) | drafted | HQL path — addressing inside a card with `@[[…]]`, for HyperMarkDown 0.2.0; a design draft, not ready to implement | [lang](../status/lang.hmd) | | [HMD-0033](HMD-0033/index.hmd) | drafted | `hmd-lsp` — the language server, written in Rust | [lsp](../status/lsp.hmd), [vsc-ext](../status/vsc-ext.hmd), [rs-core](../status/rs-core.hmd) | +| [HMD-0034](HMD-0034/index.hmd) | drafted | Mermaid, drawn by a native renderer — `mermaid#show` on par with `d2#show`, through `merman-cli` | [lang](../status/lang.hmd), [hmd](../status/hmd.hmd), [ts-core](../status/ts-core.hmd), [vsc-ext](../status/vsc-ext.hmd), [pages](../status/pages.hmd) | ## Archived diff --git a/doc/status/hmd.hmd b/doc/status/hmd.hmd index 393bb6c..2a187a3 100644 --- a/doc/status/hmd.hmd +++ b/doc/status/hmd.hmd @@ -8,6 +8,7 @@ import: - from /proposals/HMD-0024 import index as hmd-0024 - from /proposals/HMD-0028 import index as hmd-0028 - from /proposals/HMD-0030 import index as hmd-0030 + - from /proposals/HMD-0034 import index as hmd-0034 work: - kind: open state: backlog @@ -76,25 +77,28 @@ work: state: todo tags: [site, cells] text: >- - **Draw only diagram cells in the site build.** A `d2#show` fence is drawn - as a `d2` fence is today, and a plain `d2` fence becomes a code block + **Draw only diagram cells in the site build.** A plain `d2` fence still + draws beside the `d2#show` cell, and it becomes a code block notes: >- - Lands in the same release as the TypeScript implementation's change and - the rewrite of this repository's fences [`diagram.py`, `LANGUAGES`] + Lands in the same release as the TypeScript implementation's change, + after this repository's fences are rewritten and HQL writes `d2#show` + [`diagram.py`, `PLAIN_LANGUAGES`] refs: >- [[hmd-0030#the-site-build]] - kind: open - state: todo - tags: [site, cells] + state: blocked + tags: [site, ci] text: >- - **Draw Mermaid diagrams in the site build**, for `mermaid#show` cells, - through the same module and the same bounds as D2, with the same labelled - placeholder when no renderer is installed + **Install `merman-cli` where the site is built.** CI and the Pages + deploy install the pinned toolchain, and that toolchain does not carry + the Mermaid renderer yet, so a `mermaid#show` cell on the published site + shows its source with the reason notes: >- - Waits on the renderer being chosen; `LANGUAGES` in `diagram.py` gains - `mermaid#show` + Unblocked by a toolchain release that pins `merman-cli`; then move the + pin in `toolchain.json` and check `merman-cli --version` beside + `d2 --version` in both workflows refs: >- - [the Mermaid card](../issues/0115-mermaid-diagrams-on-par-with-d2.hmd) + [[hmd-0034#where-the-renderer-comes-from]] - kind: broken state: todo tags: [site, embeds] @@ -230,6 +234,16 @@ work: A changelog is a historical record refs: >- [[hmd-0005#what-deliberately-keeps-its-current-spelling]] + - kind: done + tags: [site, cells] + text: >- + **Mermaid diagrams and diagram cells in the site build** — a + `mermaid#show` cell is drawn through `merman-cli` and a `d2#show` cell + through `d2`, by one engine class with the same 64 KiB, 2 s, and + 64-entry bounds, the same `data:` image, and the same labelled + placeholder when a renderer is missing. A plain `mermaid` fence is a + code block. `diagram.py` gains `MermaidEngine`, `CELL_KINDS`, and + `engine_name`; unreleased. - kind: done tags: [config, cli] text: >- @@ -518,8 +532,8 @@ work | todo | **Property-based tests of the resolver's claims, over generated vaults.** The specification asserts properties that no test states for every tree: a wildcard import never changes a name the spine already resolved, a resolved path never lies outside the namespace root, embed expansion always terminates, and the sweep returns one match, an ambiguity, or nothing, never a silent pick. Generate random trees, cards, imports and embeds, and check each claim; a shrunk counterexample is either a resolver bug or a sentence the specification has to withdraw. The existing determinism test could take its trees from the same generator [`test_determinism.py`] | The cheap form of the parked Lean model in the format's tracker, and the condition for unparking it. Needs `hypothesis` as a test dependency | resolver, tests | [[hmd-lang-spec#resolution-rules]], [[hmd-lang-spec#embed-expansion]], [the format's tracker](lang.hmd) | | blocked | **Redirect the retired domain** to the current one, preserving paths | Registrar configuration, not a commit. See Broken | domain | [[hmd-0005#the-canonical-host-and-the-state-dns-has-to-reach]] | | parked | **Rename the package inside the parked integration suite** on the extension's old branch, which still uses the pre-rename directory name | Waits on that branch being picked up | rename | [[hmd-0005#the-repository-and-the-urls-that-point-at-it]] | -| todo | **Draw only diagram cells in the site build.** A `d2#show` fence is drawn as a `d2` fence is today, and a plain `d2` fence becomes a code block | Lands in the same release as the TypeScript implementation's change and the rewrite of this repository's fences [`diagram.py`, `LANGUAGES`] | site, cells | [[hmd-0030#the-site-build]] | -| todo | **Draw Mermaid diagrams in the site build**, for `mermaid#show` cells, through the same module and the same bounds as D2, with the same labelled placeholder when no renderer is installed | Waits on the renderer being chosen; `LANGUAGES` in `diagram.py` gains `mermaid#show` | site, cells | [the Mermaid card](../issues/0115-mermaid-diagrams-on-par-with-d2.hmd) | +| todo | **Draw only diagram cells in the site build.** A plain `d2` fence still draws beside the `d2#show` cell, and it becomes a code block | Lands in the same release as the TypeScript implementation's change, after this repository's fences are rewritten and HQL writes `d2#show` [`diagram.py`, `PLAIN_LANGUAGES`] | site, cells | [[hmd-0030#the-site-build]] | +| blocked | **Install `merman-cli` where the site is built.** CI and the Pages deploy install the pinned toolchain, and that toolchain does not carry the Mermaid renderer yet, so a `mermaid#show` cell on the published site shows its source with the reason | Unblocked by a toolchain release that pins `merman-cli`; then move the pin in `toolchain.json` and check `merman-cli --version` beside `d2 --version` in both workflows | site, ci | [[hmd-0034#where-the-renderer-comes-from]] | ## Broken @@ -573,6 +587,7 @@ work | Shipped | Tags | | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------- | +| **Mermaid diagrams and diagram cells in the site build** — a `mermaid#show` cell is drawn through `merman-cli` and a `d2#show` cell through `d2`, by one engine class with the same 64 KiB, 2 s, and 64-entry bounds, the same `data:` image, and the same labelled placeholder when a renderer is missing. A plain `mermaid` fence is a code block. `diagram.py` gains `MermaidEngine`, `CELL_KINDS`, and `engine_name`; unreleased. | site, cells | | **"Vault not found" when no `.hmd/` is above the start directory** — the error reads the way git's does outside a repository and says to run `hmd init` or pass `--root`; the README no longer describes the `wiki` setting or the `--wiki` flag; released in 0.5.1 | config, cli | | **`location_path` names the namespace root** — the setting formerly called `wiki`, read relative to the vault with the default `.`, the vault itself, instead of `doc/wiki`; no alias. `hmd init --location-path` replaces `--wiki`, and with no flag creates no directory; released in 0.5.0. | config | | **The HMD007 check follows only the embedded region** — it walks the section a fragment expands to, not every embed in the target card, so two embeds of different sections of one card, or a section embedding a sibling section, are no longer a false cycle. A card or a section that embeds itself still is. Held by the `embed-sections-of-one-card` and `embed-self` corpus cases; released in 0.5.0. | linter, embeds | @@ -621,7 +636,8 @@ work | Tag | Open | Broken | Limitations | Done | Questions | | -------- | ---- | ------ | ----------- | ---- | --------- | -| cells | 2 | 0 | 0 | 0 | 0 | +| cells | 1 | 0 | 0 | 1 | 0 | +| ci | 1 | 0 | 0 | 0 | 0 | | cli | 0 | 0 | 0 | 4 | 3 | | config | 0 | 0 | 0 | 4 | 2 | | docs | 0 | 0 | 2 | 0 | 0 | @@ -634,7 +650,7 @@ work | rename | 1 | 0 | 3 | 1 | 2 | | resolver | 1 | 0 | 0 | 2 | 1 | | scanner | 0 | 2 | 0 | 0 | 0 | -| site | 2 | 1 | 0 | 4 | 1 | +| site | 2 | 1 | 0 | 5 | 1 | | tests | 1 | 0 | 0 | 1 | 1 | diff --git a/doc/status/lang.hmd b/doc/status/lang.hmd index a27124c..65487be 100644 --- a/doc/status/lang.hmd +++ b/doc/status/lang.hmd @@ -10,6 +10,7 @@ import: - from /proposals/HMD-0026 import index as hmd-0026 - from /proposals/HMD-0030 import index as hmd-0030 - from /proposals/HMD-0032 import index as hmd-0032 + - from /proposals/HMD-0034 import index as hmd-0034 --- # STATUS — the language @@ -105,7 +106,7 @@ cases), and executable examples (inputs and expected outputs a test can run). | todo | **Validate the grammar, a release requirement for 0.1.** Check every production in *Grammar* against the normative prose, and record each rule the prose adds that a production does not express. Write language-neutral positive and negative cases for every production, block anchors, the frontmatter block, and masking. Run them against Python, TypeScript, and Rust. Compare the syntax recognised, the parsed reference components, source positions, and diagnostics, independently of rendering. Report each discrepancy and correct the implementation; a change to the standard is a reviewed decision, never a quiet match to one implementation. | Kept separate from the specification and from the existing corpus, which compares only diagnostics and resolutions, and in Rust resolutions only. Two things to decide first: grammar cases cannot be generated from the canonical implementation if they are to find it wrong, and they need a parse-level output that `expected.json` does not have | [the card](../issues/archive/0018-validate-the-grammar.hmd), [[hmd-lang-spec#grammar]], [[hmd-lang-spec#lexical-model]] | | todo | **Review lexical compatibility with CommonMark.** *Lexical model* permits a line-oriented scanner to differ from a full CommonMark parser on pathological input, such as a wikilink in an HTML block or a fence opened in a blockquote. *Conformance to the Standard* requires every implementation to recognise the same syntax. Find out whether two conforming implementations can read one document differently, list the cases and what each implementation does, and propose resolutions | The divergence paragraph stays as it is until a semantic decision is made | [the card](../issues/0019-lexical-compatibility-with-commonmark.hmd), [[hmd-lang-spec#lexical-model]] | | backlog | **Derive a test dataset from the standard.** Each construct, each interaction between constructs, and each corner case the formal definitions state becomes an executable example with its expected output. The aim is that every rule in the standard has a case and every case cites the rule it tests. Outside the scope of the 2026-11-24 revision | Follows the proofreading at three levels of specificity; extends the shared corpus rather than replacing it | [[hmd-lang-spec]], `examples/conformance/cases/` | -| todo | **Accept Mermaid as a diagram language on par with D2.** The format rejected it as superseded by D2 when it was first sketched, and the MVP grammar and the D2 proposal's non-goals still say so, while HQL's `mermaid` step already writes Mermaid fences that every tool then shows as code. Reverse the rejection in all three places in one pass. The specification's line rejecting a second diagram notation is already gone. The format's half is answered by diagram cells: a `mermaid#show` fence is a diagram whose body is opaque to the resolver, exactly as a `d2#show` fence is | The renderer choice comes first: Mermaid is a JavaScript library, not a single binary like `d2` | [the Mermaid card](../issues/0115-mermaid-diagrams-on-par-with-d2.hmd), [[hmd-0022]], [[hmd-0030]] | +| todo | **Ask HQL to write `mermaid#show` and `d2#show`.** HQL's `mermaid` format step writes a plain `mermaid` fence, which is a listing, so the output of that step is shown as code while a Mermaid cell written by hand is drawn. Its graph output writes a plain `d2` fence, which still draws and will become a listing | HQL is its own project; the request goes to its tracker. A plain `d2` fence cannot become a listing before this | [[hmd-0034#open-questions]], [[hmd-0030#deployment-activation]] | ## Broken @@ -129,6 +130,14 @@ nothing is wrong yet, only unstated. ## Done +- **Mermaid is a diagram language on par with D2** — the format rejected it as + superseded by D2 when it was first sketched. The rejection is reversed in + the three places that stated it: the source sketch, the MVP grammar, and the + D2 record's non-goals. A `mermaid#show` fence is a diagram cell whose body + is opaque to the resolver, exactly as a `d2#show` fence is, and a plain + `mermaid` fence is a listing. The renderer is a native program, + `merman-cli`, so Mermaid shares D2's bounds and image delivery + [[hmd-0034]]. - **Name resolution agrees across the three implementations** — eighteen `resolve-*` cases, written from the corrected *Name resolution* text rather than generated, cover every point the validation set out to check, @@ -233,6 +242,7 @@ withdrew two dozen claims. ## Changelog +- 2026-11-25: Mermaid is accepted as a diagram language beside D2, HMD-0034, and its Open row moves to Done. A diagram cell is drawn as its source is edited, which amends HMD-0030. A new Open row asks HQL to write `mermaid#show` and `d2#show`. - 2026-11-25: the branch `feat/in-card-address` is deleted, locally and on GitHub, without being merged, so its parked row is removed. HMD-0006 keeps the design. - 2026-11-25: two Open rows are removed: asking HQL to read `location_path`, and re-rendering the generated views once it does. HQL 0.8.0 reads `location_path`, and `hql render` renders all three views again. - 2026-11-25: HMD-0006 archived as deferred. Addressing inside a card continues as HQL path, HMD-0032, for HyperMarkDown 0.2.0; its rows and open questions replace those of HMD-0006, and the branch `feat/in-card-address` is parked. diff --git a/doc/status/open.hmd b/doc/status/open.hmd index 204738b..2ecebd0 100644 --- a/doc/status/open.hmd +++ b/doc/status/open.hmd @@ -76,9 +76,9 @@ the board, in the order this view lists them. | state | rows | | ------- | ---- | | doing | 2 | -| todo | 32 | -| blocked | 3 | -| backlog | 15 | +| todo | 29 | +| blocked | 6 | +| backlog | 16 | | parked | 3 | @@ -101,7 +101,6 @@ Every open row, `doing` first, then `todo`, `blocked`, `backlog` and | doing | Rearrange the site | [pages](pages.hmd) | | todo | Property-based tests of the resolver's claims, over generated vaults. | [hmd](hmd.hmd) | | todo | Draw only diagram cells in the site build. | [hmd](hmd.hmd) | -| todo | Draw Mermaid diagrams in the site build | [hmd](hmd.hmd) | | todo | Answer the open questions of HQL path before it is built. | [lang](lang.hmd) | | todo | Clear numeric section references from the documentation. | [lang](lang.hmd) | | todo | Finish unifying what a vault and a namespace are across the specification, the HMD tools, and HQL. | [lang](lang.hmd) | @@ -109,7 +108,7 @@ Every open row, `doing` first, then `todo`, `blocked`, `backlog` and | todo | Specify the Extended Markdown syntax. | [lang](lang.hmd) | | todo | Validate the grammar, a release requirement for 0.1. | [lang](lang.hmd) | | todo | Review lexical compatibility with CommonMark. | [lang](lang.hmd) | -| todo | Accept Mermaid as a diagram language on par with D2. | [lang](lang.hmd) | +| todo | Ask HQL to write `mermaid#show` and `d2#show`. | [lang](lang.hmd) | | todo | Go to a heading or a block. | [lsp](lsp.hmd) | | todo | Tokens for block anchors and frontmatter. | [lsp](lsp.hmd) | | todo | Completion | [lsp](lsp.hmd) | @@ -121,19 +120,20 @@ Every open row, `doing` first, then `todo`, `blocked`, `backlog` and | todo | The publication model, and the rule that depends on it. | [ts-core](ts-core.hmd) | | todo | Subscript. | [ts-core](ts-core.hmd) | | todo | LaTeX environments at block level. | [ts-core](ts-core.hmd) | -| todo | Recognise diagram cells. | [ts-core](ts-core.hmd) | -| todo | Recognise a `mermaid#show` fence as a diagram. | [ts-core](ts-core.hmd) | +| todo | Turn a plain `d2` fence into a listing. | [ts-core](ts-core.hmd) | | todo | Colour the listings in the preview. | [vsc-ext](vsc-ext.hmd) | | todo | Colour a `d2` listing in the editor. | [vsc-ext](vsc-ext.hmd) | | todo | Colour a fence nested in a list or a quote. | [vsc-ext](vsc-ext.hmd) | | todo | Colour a link inside a paragraph from the grammar. | [vsc-ext](vsc-ext.hmd) | | todo | Automate the by-hand checks. | [vsc-ext](vsc-ext.hmd) | | todo | Create the card a relative link points at. | [vsc-ext](vsc-ext.hmd) | -| todo | Diagram cells in the preview. | [vsc-ext](vsc-ext.hmd) | -| todo | Draw Mermaid diagrams in the preview | [vsc-ext](vsc-ext.hmd) | +| todo | Turn a plain `d2` fence into code in the preview. | [vsc-ext](vsc-ext.hmd) | | blocked | Redirect the retired domain | [hmd](hmd.hmd) | +| blocked | Install `merman-cli` where the site is built. | [hmd](hmd.hmd) | +| blocked | Show Mermaid beside D2 on the public pages | [pages](pages.hmd) | | blocked | Drop the mask. | [vsc-ext](vsc-ext.hmd) | | blocked | Name the HQL project and import `hmd` on the command line. | [vsc-ext](vsc-ext.hmd) | +| blocked | Carry `merman-cli` in the build. | [vsc-ext](vsc-ext.hmd) | | backlog | Lint text, not just files. | [hmd](hmd.hmd) | | backlog | Invalidate one card at a time | [hmd](hmd.hmd) | | backlog | HQL path, for HyperMarkDown 0.2.0. | [lang](lang.hmd) | @@ -149,6 +149,7 @@ Every open row, `doing` first, then `todo`, `blocked`, `backlog` and | backlog | A comparison suite that asks the reference implementation. | [rs-core](rs-core.hmd) | | backlog | Say when `--vault` is not a vault. | [semantics](semantics.hmd) | | backlog | Filter the graph by namespace and tag | [vsc-ext](vsc-ext.hmd) | +| backlog | Show All Diagrams | [vsc-ext](vsc-ext.hmd) | | parked | Rename the package inside the parked integration suite | [hmd](hmd.hmd) | | parked | A Lean model of resolution and embed expansion. | [lang](lang.hmd) | | parked | The integration suite | [vsc-ext](vsc-ext.hmd) | diff --git a/doc/status/pages.hmd b/doc/status/pages.hmd index 6a43026..ac78f6c 100644 --- a/doc/status/pages.hmd +++ b/doc/status/pages.hmd @@ -5,6 +5,7 @@ import: - from /proposals/HMD-0005 import index as hmd-0005 - from /proposals/HMD-0022 import index as hmd-0022 - from /proposals/HMD-0030 import index as hmd-0030 + - from /proposals/HMD-0034 import index as hmd-0034 --- # STATUS — the website @@ -69,6 +70,7 @@ revisiting is that maths loads from a CDN at view time. | todo | **The roadmap is behind the releases**: its version table, its news, and a section that lists released cells as coming | It now says where the work goes — the specification's first version and the editor here, AI and graph querying in HQL — and nothing else on it was brought forward. It is the one page that states versions, so it is the one page that has to be right | [the roadmap card](../issues/0013-the-roadmap-is-behind-the-releases.hmd) | | todo | **A screenshot of the example notebook for the cover**, in place of a crop from another vault | Needs the editor opened by hand | [the screenshot card](../issues/0114-a-screenshot-of-the-example-notebook.hmd) | | todo | **Rewrite every `d2` fence as `d2#show`** — in the book, the wiki, the README, and the example vaults, about eighteen fences — so the diagrams still draw once a plain `d2` fence is a listing. A fence that shows D2 source on purpose, inside an outer example fence, stays as it is | Lands with the release that turns the rule on in both implementations, not before it and not after | [[hmd-0030#backwards-compatibility]] | +| blocked | **Show Mermaid beside D2 on the public pages**: the Features page, the README, and the tools pages list D2 alone, and the Features page shows a diagram as D2 only. Add a `mermaid#show` example next to the D2 one | Unblocked when the Pages build installs a toolchain that carries `merman-cli`; before that the example would be published as its own source with a reason | [[hmd-0034]] | | backlog | **Self-host the maths typesetter**, so the site has no runtime dependency on anything it does not ship | Today it loads from a CDN, which is the site's only network dependency at view time. Not argued yet | — | ## Broken @@ -209,6 +211,8 @@ run permanently. ## Changelog +- 2026-11-25: a blocked Open row for showing Mermaid beside D2 on the public + pages, which waits on the Pages build carrying the Mermaid renderer. - 2026-11-25: the feature list and the interop sketch removed, and every reference to them repointed at Features or dropped. - 2026-11-25: Features moved into Language; Learn regrouped; the Wiki tab diff --git a/doc/status/proposals.hmd b/doc/status/proposals.hmd index e1a94c4..1e949fb 100644 --- a/doc/status/proposals.hmd +++ b/doc/status/proposals.hmd @@ -74,7 +74,7 @@ cards | [HMD-0006](../proposals/HMD-0006/index.hmd) | Extended URI for transclusion and link referencing when addressing inside a card | deferred | [hmd](hmd.hmd), [lang](lang.hmd), [rs-core](rs-core.hmd), [ts-core](ts-core.hmd) | | [HMD-0020](../proposals/HMD-0020/index.hmd) | `@hypermarkdown/core` — the TypeScript document model | drafted | [hmd](hmd.hmd), [lang](lang.hmd), [ts-core](ts-core.hmd), [vsc-ext](vsc-ext.hmd) | | [HMD-0021](../proposals/HMD-0021/index.hmd) | The VS Code extension — the HyperMarkDown preview surface | drafted | [status/index](status/index.hmd), [ts-core](ts-core.hmd), [vsc-ext](vsc-ext.hmd) | -| [HMD-0022](../proposals/HMD-0022/index.hmd) | D2 diagrams | drafted | [lang](lang.hmd), [pages](pages.hmd) | +| [HMD-0022](../proposals/HMD-0022/index.hmd) | D2 diagrams | drafted | [pages](pages.hmd) | | [HMD-0024](../proposals/HMD-0024/index.hmd) | The `tools/` layout, and a Python language server | drafted | [hmd](hmd.hmd) | | [HMD-0025](../proposals/HMD-0025/index.hmd) | The graph tab — the vault as a picture | drafted | [vsc-ext](vsc-ext.hmd) | | [HMD-0026](../proposals/HMD-0026/index.hmd) | HQL cells — a card as a notebook | drafted | [lang](lang.hmd), [ts-core](ts-core.hmd), [vsc-ext](vsc-ext.hmd) | @@ -85,4 +85,5 @@ cards | [HMD-0031](../proposals/HMD-0031/index.hmd) | Freeze | drafted | — | | [HMD-0032](../proposals/HMD-0032/index.hmd) | HQL path — addressing inside a card with `@[[…]]` | drafted | [hmd](hmd.hmd), [lang](lang.hmd), [rs-core](rs-core.hmd), [ts-core](ts-core.hmd) | | [HMD-0033](../proposals/HMD-0033/index.hmd) | `hmd-lsp` — the language server, written in Rust | drafted | [hmd](hmd.hmd), [lsp](lsp.hmd), [vsc-ext](vsc-ext.hmd) | +| [HMD-0034](../proposals/HMD-0034/index.hmd) | Mermaid, drawn by a native renderer | drafted | [lang](lang.hmd), [pages](pages.hmd), [ts-core](ts-core.hmd), [vsc-ext](vsc-ext.hmd) | diff --git a/doc/status/ts-core.hmd b/doc/status/ts-core.hmd index 42a79a5..2242744 100644 --- a/doc/status/ts-core.hmd +++ b/doc/status/ts-core.hmd @@ -6,6 +6,7 @@ import: - from /proposals/HMD-0021 import index as hmd-0021 - from /proposals/HMD-0026 import index as hmd-0026 - from /proposals/HMD-0030 import index as hmd-0030 + - from /proposals/HMD-0034 import index as hmd-0034 --- # STATUS — `@hypermarkdown/core` @@ -53,8 +54,7 @@ subscript, and LaTeX environments written without dollar signs. | todo | **The publication model, and the rule that depends on it.** Parse `nav` as a mapping of order and visibility, inherit visibility from the nearest ancestor folder note defaulting to private, and warn when a published card links to or embeds an unpublished one. Four files; reproduce the canonical behaviour exactly and keep the embed veto a decision the caller passes in, so a later policy change has somewhere to land | Unblocked on 2026-11-22: this implementation's spec now follows the language specification's diagnostics table rather than stopping at sixteen rules [HMD017] | [[hmd-0002#3-expansion]], [[hmd-0020#9-diagnostics]] | | todo | **Subscript.** `~x~` is subscript on the website and nothing here — not a math gap at all: it comes from a markdown extension, and markdown-it's builtin covers only `~~strikethrough~~`. One line to wire in `markdown-it-sub`, a new dependency | Then the ledgered difference is deleted, because a ledger entry that stops diverging fails the build | [[hmd-0020#3-3-free-syntax]] | | todo | **LaTeX environments at block level.** `\begin{align}` on its own is math on the website and prose here, because this implementation only recognises a block that opens with `$$`. The likeliest real-world hit of the KaTeX-versus-MathJax difference, and the only one not written down | Not currently ledgered | [[hmd-0020#3-3-free-syntax]] | -| todo | **Recognise diagram cells.** `d2#show` and `mermaid#show` become a `DiagramBlock`, matched exactly; a plain `d2` fence becomes an ordinary code block. `DiagramBlock` gains the state of the drawing on screen and a key by position among the card's diagram cells, so an edit keeps the reader's Code toggle, and `IR_VERSION` moves to 5 | First recognise `d2#show` beside `d2`, then drop plain `d2` in the release that the repository's fences are rewritten for [`src/diagram/fence.ts`] | [[hmd-0030]] | -| todo | **Recognise a `mermaid#show` fence as a diagram.** One entry in `DIAGRAM_LANGUAGES`; `DiagramBlock` already carries its language | The core does not render, so this does not wait on the renderer; it lands with diagram cells | [the Mermaid card](../issues/0115-mermaid-diagrams-on-par-with-d2.hmd) | +| todo | **Turn a plain `d2` fence into a listing.** It still becomes a `DiagramBlock` beside the `d2#show` cell, so that nothing written before diagram cells stops drawing. Empty `DIAGRAM_LANGUAGES`, and the fence becomes an ordinary code block | Lands in the release that the repository's fences are rewritten for, after HQL writes `d2#show` for a graph [`src/diagram/fence.ts`] | [[hmd-0030#deployment-activation]] | ## Broken @@ -82,6 +82,14 @@ canonical side warns and this one stays silent. ## Done +- **Diagram cells, in D2 and in Mermaid** — a fence that opens `d2#show` or + `mermaid#show` becomes a `DiagramBlock`, matched exactly, and a plain + `mermaid` fence stays a code block. `DiagramBlock` gains `drawnFrom` and + `current`, the state of the drawing on screen, and a cell is keyed by its + position among the card's diagram cells, so an edit keeps the reader's Code + toggle and the last drawing. `diagramEngine` names the renderer of a + language, `scanDiagramCells` finds the cells of a card's text, and + `IR_VERSION` is 5; unreleased. - **`location_path` names the namespace root** — the setting formerly called `wiki`, read relative to the vault with the default `.`, the vault itself, instead of `doc/wiki`; no alias; released in 0.4.0. @@ -166,6 +174,7 @@ environment variable is set, which CI does. ## Changelog +- 2026-11-25: a Done row for diagram cells in D2 and Mermaid, HMD-0030 and HMD-0034. The two Open rows it closes become one: a plain `d2` fence still draws, and turning it into a listing is the remaining work. - 2026-11-25: the HQL path row is withdrawn. HMD-0032 is a design draft and is not ready to implement; the row returns when the record is accepted. - 2026-11-25: a backlog row for HQL path, HMD-0032, the construct `@[[…]]` that HyperMarkDown 0.2.0 would add; it replaces the in-card address of HMD-0006, which is archived as deferred. - 2026-11-24: a Done row for reading `location_path`, the `wiki` setting's new name. diff --git a/doc/status/vsc-ext.hmd b/doc/status/vsc-ext.hmd index 6a95c42..4261395 100644 --- a/doc/status/vsc-ext.hmd +++ b/doc/status/vsc-ext.hmd @@ -10,6 +10,7 @@ import: - from /proposals/HMD-0026 import index as hmd-0026 - from /proposals/HMD-0030 import index as hmd-0030 - from /proposals/HMD-0033 import index as hmd-0033 + - from /proposals/HMD-0034 import index as hmd-0034 --- # STATUS — the VS Code extension @@ -85,8 +86,9 @@ picks and re-indexes without a reload, since `0.6.1` [issue 0116]. | blocked | **Drop the mask.** Before handing a card to HQL the extension renames a bare `hql` fence to `txt` and marks an `hql#query` fence `hidden`, because `hql render` runs bare `hql` fences as cells and writes outputs for queries, and this format says they are a listing and a hidden cell. Unblocks when HQL adopts both rules | One function and its call [`src/hql/engine.ts`, `maskForHql`] | [[hmd-0026#the-divergence-with]] | | blocked | **Name the HQL project and import `hmd` on the command line.** HQL's record of projects and vaults has a host pass the project it resolved, `--project `, and inject `--import hmd`. The extension passes neither: `hql render` imports `hmd` and selects the project itself, and the HQL the toolchain pins predates both flags and refuses an option it does not know. Unblocks when the toolchain pins an HQL release that has them | One argument list [`src/hql/engine.ts`, `run`] | [[hmd-0026#running-a-cell]] | | parked | **The integration suite** under `@vscode/test-cli` — written, compiling, and set aside on the `feat/vsc-ext-1` branch, because two upstream defects make it unrunnable on macOS | Below | [[hmd-0021#12-packaging-and-ci]] | -| todo | **Diagram cells in the preview.** A `d2#show` or `mermaid#show` fence is drawn like an `hql#eval` cell: the drawing first, the source behind Code, Edit beside it, and Show in place of Run. A cell is drawn when the card opens; after an edit it keeps its last drawing, marked stale, until Show. Nothing is written into the card, and a plain `d2` fence becomes code | Lands together with the core's change and the rewrite of this repository's `d2` fences, or the book loses its diagrams | [[hmd-0030]] | -| todo | **Draw Mermaid diagrams in the preview**, for `mermaid#show` cells, with a renderer pinned in the toolchain beside `d2`, falling back to `PATH`, and the same cache, bounds, and `data:` image delivery | The renderer is the cost: Mermaid's reference CLI drives a headless Chromium, which is heavy in a VSIX and slow to start | [the Mermaid card](../issues/0115-mermaid-diagrams-on-par-with-d2.hmd) | +| blocked | **Carry `merman-cli` in the build.** The preview draws a `mermaid#show` cell with `merman-cli` from the `hyperMarkdown.diagram.mermaidPath` setting or from `PATH`. No platform build carries the binary yet, so a fresh install shows a Mermaid cell as its source with the reason | Unblocked by a toolchain release that pins `merman-cli`. Then move the pin in `toolchain.json`, check each VSIX for `toolchain/bin/merman-cli` in the release workflow, and set `MERMAN_BIN` in CI so the tests against the real binary run. Each platform build grows by 16 MB to 26 MB | [[hmd-0034#where-the-renderer-comes-from]] | +| todo | **Turn a plain `d2` fence into code in the preview.** It still draws, without the cell layout, beside the `d2#show` cell | Lands together with the core's change and the rewrite of this repository's `d2` fences, or the book loses its diagrams | [[hmd-0030#deployment-activation]] | +| backlog | **Show All Diagrams**, for a card, the way Run has Run All | An open question of the record, not yet asked for | [[hmd-0030#open-questions]] | **Why the integration suite is parked**, neither reason in our code: the test harness spawns `Contents/MacOS/Electron` and current VS Code ships that binary @@ -119,6 +121,20 @@ about 300 MB on first run, which is why it is not in the default test command. ## Done +- **Diagram cells in the preview** — a `d2#show` or `mermaid#show` fence is + drawn like an `hql#eval` cell: the drawing first, the source behind Code, + Edit beside it, and Show in place of Run. The drawing follows the source as + it is typed. When the source stops drawing, the cell keeps its last drawing, + marked stale, with the reason under it, and Show draws it again. Show is + offered inside an embed, and nothing is written into the card. A **Show + diagram** code lens sits above each cell, and the command *Show Diagram* + draws the cell under the cursor; unreleased [[hmd-0030]]. +- **Mermaid diagrams in the preview** — a `mermaid#show` cell is drawn by + `merman-cli`, a native renderer with no browser, found by the + `hyperMarkdown.diagram.mermaidPath` setting, then in the build's toolchain + directory, then on `PATH`. It shares the cache, the 64 KiB and 2 s bounds, + and the `data:` image delivery of D2, and one engine runs both renderers; + unreleased [[hmd-0034]]. - **The build carries the language server** — every platform build holds `hmd-lsp` 0.1.0 in `toolchain/bin/`, from toolchain 0.6.0, and the client looks there before `PATH`. The release workflow checks each VSIX for it; @@ -265,6 +281,10 @@ npm run -w tools/hmd-vsc-ext package ## Changelog +- 2026-11-25: Done rows for diagram cells in the preview and for Mermaid + drawn by `merman-cli`. The Open row for cells becomes the smaller row for a + plain `d2` fence, and the Open row for Mermaid becomes a blocked row for + carrying the renderer in the build. - 2026-11-25: 0.7.0. Status names it. Done rows for HQL highlighting, for a cell in any language, for the Linguist fence table, and for carrying `hmd-lsp` in the build, whose blocked row is gone. Open rows for a `d2` diff --git a/tools/hmd-ts-core/CHANGELOG.md b/tools/hmd-ts-core/CHANGELOG.md index 6361809..eb6c608 100644 --- a/tools/hmd-ts-core/CHANGELOG.md +++ b/tools/hmd-ts-core/CHANGELOG.md @@ -21,6 +21,27 @@ point in ## [Unreleased] +### Added + +- **Diagram cells.** A fence that opens `d2#show` or `mermaid#show` becomes a + `DiagramBlock`, matched exactly and case-sensitively. `DIAGRAM_CELL_KINDS` + maps each kind to its engine, `diagramLanguage` reads a fence's info string, + `isDiagramCell` and `diagramEngine` answer for a block's language, and + `scanDiagramCells` finds the cells in a card's text with their lines. +- **Mermaid.** `mermaid#show` is a diagram. A plain `mermaid` fence stays a + code block. + +### Changed + +- **`IR_VERSION` is 5.** `DiagramBlock` gains `drawnFrom` and `current`, the + state of the drawing a consumer attached. A consumer that builds a + `DiagramBlock` must set both. +- **A diagram cell is keyed by position** among the card's diagram cells, not + by its source, so an edit keeps the element that shows it. A plain `d2` + fence keeps its key by source. +- `DiagramBlock.language` is `d2#show` or `mermaid#show` for a cell, as + written. It is `d2` for a plain `d2` fence, which still draws. + ## [0.4.0] — 2026-11-25 The HyperMarkDown 0.1 rules for encoding, the lexical model, and heading diff --git a/tools/hmd-vsc-ext/CHANGELOG.md b/tools/hmd-vsc-ext/CHANGELOG.md index 79d865e..20de42a 100644 --- a/tools/hmd-vsc-ext/CHANGELOG.md +++ b/tools/hmd-vsc-ext/CHANGELOG.md @@ -21,6 +21,37 @@ against ## [Unreleased] +### Added + +- **Diagram cells.** A fence that opens `d2#show` or `mermaid#show` is a + diagram cell. The preview draws it the way it draws an HQL cell: the drawing + first, the source behind **Code**, **Edit** beside it, and **Show** in place + of Run. The drawing follows the source as you type. When an edit leaves + source that does not draw, the cell keeps its last drawing, marked stale, + with the reason under it. Nothing is written into the card. +- **Mermaid diagrams.** A `mermaid#show` cell is drawn by + [`merman-cli`](https://github.com/latias94/merman), a native Mermaid + renderer that needs no browser. It shares the bounds of D2: 64 KiB of + source, 2 seconds for a render, and a drawing delivered as an image, so + nothing in a diagram can run. The renderer is found by the new setting + `hyperMarkdown.diagram.mermaidPath`, then in the build's toolchain + directory, then on `PATH`. This build does not carry it yet: install + `merman-cli` on `PATH`, or point the setting at it. Without it a Mermaid + cell shows its source and says why. +- **Show Diagram.** A **Show diagram** code lens above every diagram cell, and + the command *HyperMarkDown: Show Diagram* for the cell under the cursor. + Show draws the cell again, and it is how to retry after a timeout or after + installing a renderer. + +### Changed + +- **A plain `mermaid` fence is a listing.** It is shown as code, as it always + was, and only `mermaid#show` is drawn. A Mermaid block written for GitHub or + Obsidian draws here once its fence is renamed. A plain `d2` fence still + draws; `d2#show` is the form that will keep drawing. +- **The Edit button of a cell inside an embed** opens the embedded card, at + the cell. It opened the card on screen at the wrong line. + ## [0.7.0] — 2026-11-25 ### Added diff --git a/tools/hmd/CHANGELOG.md b/tools/hmd/CHANGELOG.md index e364a6f..21f8abb 100644 --- a/tools/hmd/CHANGELOG.md +++ b/tools/hmd/CHANGELOG.md @@ -13,6 +13,19 @@ only for the Python API. ## [Unreleased] +### Added +- **Mermaid diagrams in the site build.** A fence that opens `mermaid#show` is + drawn by [`merman-cli`](https://github.com/latias94/merman), a native Mermaid + renderer that needs no browser, found on `PATH`. It shares the bounds of D2: + 64 KiB of source, 2 seconds for a render, and a drawing delivered as a + `data:` image. With no `merman-cli` installed the cell shows its source and + the reason, and the build stays green. +- **Diagram cells.** `d2#show` is drawn exactly as a `d2` fence is. A plain + `mermaid` fence is a listing and stays a code block. A plain `d2` fence + still draws; `d2#show` is the form that will keep drawing. +- `diagram.MermaidEngine`, `diagram.engines()`, and `diagram.engine_name()`. + `D2Engine` and `MermaidEngine` share one base class, `diagram.Engine`. + ## [0.5.1] — 2026-11-25 ### Changed From 32a47623579933695351a0f7d51c072d5da2ea74 Mon Sep 17 00:00:00 2001 From: Yauhen Yakimovich Date: Wed, 25 Nov 2026 21:45:06 +0100 Subject: [PATCH 3/4] Zoom buttons on a diagram, and a diagrams example vault Every drawing in the preview, in D2 and in Mermaid, has three small buttons at its top right edge: smaller, the current size, which resets it, and larger. A zoomed drawing scrolls inside its own box, and a cell keeps its zoom when its source is edited. examples/diagrams is a vault to test diagram cells by hand: the same picture in both languages, a listing, a Mermaid gallery, and a cell in each state. Open it with npm run example:diagrams. HMD-0034 is accepted, and the Mermaid card moves to doing. --- .../0115-mermaid-diagrams-on-par-with-d2.hmd | 4 +- doc/issues/kanban.yaml | 2 +- doc/proposals/HMD-0034/index.hmd | 3 +- doc/proposals/index.hmd | 2 +- doc/status/kanban.hmd | 29 +++-- doc/status/proposals.hmd | 2 +- doc/status/vsc-ext.hmd | 8 ++ examples/diagrams/.hmd/config.toml | 9 ++ examples/diagrams/index.hmd | 60 ++++++++++ examples/diagrams/mermaid-gallery.hmd | 103 +++++++++++++++++ examples/diagrams/states.hmd | 45 ++++++++ scripts/launch-example.mjs | 2 +- tools/hmd-vsc-ext/CHANGELOG.md | 6 + tools/hmd-vsc-ext/media/render.ts | 109 ++++++++++++++++-- tools/hmd-vsc-ext/media/webview.css | 67 ++++++++++- tools/hmd-vsc-ext/media/webview.ts | 14 +++ tools/hmd-vsc-ext/package.json | 1 + tools/hmd-vsc-ext/test/renderer.test.ts | 83 +++++++++++++ 18 files changed, 514 insertions(+), 35 deletions(-) create mode 100644 examples/diagrams/.hmd/config.toml create mode 100644 examples/diagrams/index.hmd create mode 100644 examples/diagrams/mermaid-gallery.hmd create mode 100644 examples/diagrams/states.hmd diff --git a/doc/issues/0115-mermaid-diagrams-on-par-with-d2.hmd b/doc/issues/0115-mermaid-diagrams-on-par-with-d2.hmd index 3215dfa..44bc042 100644 --- a/doc/issues/0115-mermaid-diagrams-on-par-with-d2.hmd +++ b/doc/issues/0115-mermaid-diagrams-on-par-with-d2.hmd @@ -1,8 +1,8 @@ # 0115 — Mermaid diagrams, on par with D2 -**Column**: todo +**Column**: doing **Opened**: 2026-11-22 -**Related**: [HMD-0022](../proposals/HMD-0022/index.hmd), [the D2 card](archive/0004-math-callouts-diagrams.hmd), [the toolchain card](archive/0107-toolchain-repository-for-native-binaries.hmd), [the diagram surface card](0102-diagram-theme-surface.hmd) +**Related**: [HMD-0034](../proposals/HMD-0034/index.hmd), [HMD-0030](../proposals/HMD-0030/index.hmd), [HMD-0022](../proposals/HMD-0022/index.hmd), [the D2 card](archive/0004-math-callouts-diagrams.hmd), [the toolchain card](archive/0107-toolchain-repository-for-native-binaries.hmd), [the diagram surface card](0102-diagram-theme-surface.hmd) ## What diff --git a/doc/issues/kanban.yaml b/doc/issues/kanban.yaml index 257a213..11d7bf0 100644 --- a/doc/issues/kanban.yaml +++ b/doc/issues/kanban.yaml @@ -85,10 +85,10 @@ board: - id: "0118" title: "Listings in a fenced block are not coloured in the preview" file: 0118-colour-the-listings-in-a-fenced-block.hmd + doing: - id: "0115" title: "Mermaid diagrams, on par with D2" file: 0115-mermaid-diagrams-on-par-with-d2.hmd - doing: [] done: - id: "0117" title: "A language server, written in Rust" diff --git a/doc/proposals/HMD-0034/index.hmd b/doc/proposals/HMD-0034/index.hmd index b4dbd5f..95ee731 100644 --- a/doc/proposals/HMD-0034/index.hmd +++ b/doc/proposals/HMD-0034/index.hmd @@ -5,7 +5,7 @@ nav: # HMD-0034: Mermaid, drawn by a native renderer -**Status**: drafted +**Status**: accepted **Created**: 2026-11-25 **Source**: [the board card that opened the work](../../issues/0115-mermaid-diagrams-on-par-with-d2.hmd) @@ -290,6 +290,7 @@ Integration tests MUST include: ## Changelog - 2026-11-25: drafted, with the renderer chosen and measured. +- 2026-11-25: accepted. ## See also diff --git a/doc/proposals/index.hmd b/doc/proposals/index.hmd index 8e6d7df..d78086d 100644 --- a/doc/proposals/index.hmd +++ b/doc/proposals/index.hmd @@ -37,7 +37,7 @@ it continues at **`HMD-0100`**, leaving `0020`–`0099` to the editor line. | [HMD-0031](HMD-0031/index.hmd) | drafted | Freeze — every open finding against 0.1, consolidated before fixing | [lang](../status/lang.hmd) | | [HMD-0032](HMD-0032/index.hmd) | drafted | HQL path — addressing inside a card with `@[[…]]`, for HyperMarkDown 0.2.0; a design draft, not ready to implement | [lang](../status/lang.hmd) | | [HMD-0033](HMD-0033/index.hmd) | drafted | `hmd-lsp` — the language server, written in Rust | [lsp](../status/lsp.hmd), [vsc-ext](../status/vsc-ext.hmd), [rs-core](../status/rs-core.hmd) | -| [HMD-0034](HMD-0034/index.hmd) | drafted | Mermaid, drawn by a native renderer — `mermaid#show` on par with `d2#show`, through `merman-cli` | [lang](../status/lang.hmd), [hmd](../status/hmd.hmd), [ts-core](../status/ts-core.hmd), [vsc-ext](../status/vsc-ext.hmd), [pages](../status/pages.hmd) | +| [HMD-0034](HMD-0034/index.hmd) | accepted | Mermaid, drawn by a native renderer — `mermaid#show` on par with `d2#show`, through `merman-cli` | [lang](../status/lang.hmd), [hmd](../status/hmd.hmd), [ts-core](../status/ts-core.hmd), [vsc-ext](../status/vsc-ext.hmd), [pages](../status/pages.hmd) | ## Archived diff --git a/doc/status/kanban.hmd b/doc/status/kanban.hmd index 370dce9..c69cefa 100644 --- a/doc/status/kanban.hmd +++ b/doc/status/kanban.hmd @@ -60,8 +60,8 @@ then the archive. | lane | issues | | ------- | ------ | | backlog | 9 | -| todo | 11 | -| doing | 0 | +| todo | 10 | +| doing | 1 | | done | 0 | | archive | 27 | @@ -91,19 +91,18 @@ range(0, depth) | format(as = Markdown) ``` -| backlog | todo | doing | done | -| ------------------------------------------------------------ | -------------------------------------------------------------------------------- | ----- | ---- | -| 0106 There is no way to search the wiki from the preview | 0118 Listings in a fenced block are not coloured in the preview | | | -| 0102 Diagrams render on a white surface in every theme | 0115 Mermaid diagrams, on par with D2 | | | -| 0101 The live-editing behaviours are only checked by hand | 0114 The cover's notebook screenshot is of another vault | | | -| 0026 Check frontmatter with an HQL-like data type system | 0113 A relative image in a card is not shown in the preview | | | -| 0025 Extend the shared test coverage | 0105 The preview freezes on the card it was opened over | | | -| 0024 Define symbolic link semantics | 0100 A `???` callout snaps shut on every re-render | | | -| 0021 Specify the vault directory and the standard's boundary | 0019 Review lexical compatibility with CommonMark | | | -| 0008 A public card linking to a private one needs a policy | 0015 CommonMark's own examples as a test dataset | | | -| 0007 Conversion should name its output target | 0013 The roadmap is behind the releases, and it is the one page that states them | | | -| | 0012 An embedded card's Markdown links resolve from the host page | | | -| | 0011 Vault and namespace: the declared design, HMD, and HQL have drifted apart | | | +| backlog | todo | doing | done | +| ------------------------------------------------------------ | -------------------------------------------------------------------------------- | ------------------------------------- | ---- | +| 0106 There is no way to search the wiki from the preview | 0118 Listings in a fenced block are not coloured in the preview | 0115 Mermaid diagrams, on par with D2 | | +| 0102 Diagrams render on a white surface in every theme | 0114 The cover's notebook screenshot is of another vault | | | +| 0101 The live-editing behaviours are only checked by hand | 0113 A relative image in a card is not shown in the preview | | | +| 0026 Check frontmatter with an HQL-like data type system | 0105 The preview freezes on the card it was opened over | | | +| 0025 Extend the shared test coverage | 0100 A `???` callout snaps shut on every re-render | | | +| 0024 Define symbolic link semantics | 0019 Review lexical compatibility with CommonMark | | | +| 0021 Specify the vault directory and the standard's boundary | 0015 CommonMark's own examples as a test dataset | | | +| 0008 A public card linking to a private one needs a policy | 0013 The roadmap is behind the releases, and it is the one page that states them | | | +| 0007 Conversion should name its output target | 0012 An embedded card's Markdown links resolve from the host page | | | +| | 0011 Vault and namespace: the declared design, HMD, and HQL have drifted apart | | | ## Archive diff --git a/doc/status/proposals.hmd b/doc/status/proposals.hmd index 9943106..bf9b75d 100644 --- a/doc/status/proposals.hmd +++ b/doc/status/proposals.hmd @@ -85,5 +85,5 @@ cards | [HMD-0031](../proposals/HMD-0031/index.hmd) | Freeze | drafted | — | | [HMD-0032](../proposals/HMD-0032/index.hmd) | HQL path — addressing inside a card with `@[[…]]` | drafted | [hmd](hmd.hmd), [lang](lang.hmd), [rs-core](rs-core.hmd), [ts-core](ts-core.hmd) | | [HMD-0033](../proposals/HMD-0033/index.hmd) | `hmd-lsp` — the language server, written in Rust | drafted | [hmd](hmd.hmd), [lsp](lsp.hmd), [vsc-ext](vsc-ext.hmd) | -| [HMD-0034](../proposals/HMD-0034/index.hmd) | Mermaid, drawn by a native renderer | drafted | [hmd](hmd.hmd), [lang](lang.hmd), [pages](pages.hmd), [ts-core](ts-core.hmd), [vsc-ext](vsc-ext.hmd) | +| [HMD-0034](../proposals/HMD-0034/index.hmd) | Mermaid, drawn by a native renderer | accepted | [hmd](hmd.hmd), [lang](lang.hmd), [pages](pages.hmd), [ts-core](ts-core.hmd), [vsc-ext](vsc-ext.hmd) | diff --git a/doc/status/vsc-ext.hmd b/doc/status/vsc-ext.hmd index 4261395..7768f46 100644 --- a/doc/status/vsc-ext.hmd +++ b/doc/status/vsc-ext.hmd @@ -129,6 +129,14 @@ about 300 MB on first run, which is why it is not in the default test command. offered inside an embed, and nothing is written into the card. A **Show diagram** code lens sits above each cell, and the command *Show Diagram* draws the cell under the cursor; unreleased [[hmd-0030]]. +- **Zoom on a diagram** — every drawing, in D2 and in Mermaid, has three + small buttons at its top right edge: smaller, the current size, which + resets it, and larger. Zoom moves in steps of 1.25 between 25% and 800%, a + zoomed drawing scrolls inside its own box, and a cell keeps its zoom when + its source is edited; unreleased. +- **A diagrams example vault** — `examples/diagrams`, opened with + `npm run example:diagrams`: the same picture in both languages, a listing, a + Mermaid gallery, and a cell in each state; unreleased. - **Mermaid diagrams in the preview** — a `mermaid#show` cell is drawn by `merman-cli`, a native renderer with no browser, found by the `hyperMarkdown.diagram.mermaidPath` setting, then in the build's toolchain diff --git a/examples/diagrams/.hmd/config.toml b/examples/diagrams/.hmd/config.toml new file mode 100644 index 0000000..16de874 --- /dev/null +++ b/examples/diagrams/.hmd/config.toml @@ -0,0 +1,9 @@ +# Project config for the diagrams example: a vault to look at in the editor, +# with diagram cells in D2 and in Mermaid. Open it with +# npm run example:diagrams (in tools/hmd-vsc-ext) +# and lint it with +# hmd lint --root examples/diagrams + +[discovery] +autodiscovery = true +mode = "both" diff --git a/examples/diagrams/index.hmd b/examples/diagrams/index.hmd new file mode 100644 index 0000000..13cfd6d --- /dev/null +++ b/examples/diagrams/index.hmd @@ -0,0 +1,60 @@ +# Diagrams + +A fence that opens `d2#show` or `mermaid#show` is a **diagram cell**. The +preview draws it, and keeps its source one click away behind **Code**. Edit a +cell and the drawing follows as you type. + +Each drawing has three small buttons at its top right edge: smaller, the +current size, and larger. The middle one puts the drawing back at its own +size. + +More diagram types are on [[mermaid-gallery]], and the states a cell can be in +are on [[states]]. + +## The same picture in both languages + +In Mermaid: + +```mermaid#show +flowchart LR + client -->|credentials| edge + edge -->|verify| auth + auth -->|token| edge + edge -->|token + rotation window| client +``` + +In D2: + +```d2#show +direction: right + +client -> edge: credentials +edge -> auth: verify +auth -> edge: token +edge -> client: token + rotation window +``` + +## A listing is not drawn + +A plain `mermaid` fence shows Mermaid source as text. It is how a card +explains the notation without turning the example into a picture. + +```mermaid +flowchart LR + shown --> as-code +``` + +## A plain `d2` fence still draws + +It has no cell layout, only the drawing and its zoom buttons. + +```d2 +before -> cells +``` + +## An embedded card + +The card below is embedded. Its diagram cell is drawn here, and its **Show** +and **Edit** buttons work from here. + +![[states#a-cell-that-draws]] diff --git a/examples/diagrams/mermaid-gallery.hmd b/examples/diagrams/mermaid-gallery.hmd new file mode 100644 index 0000000..c8c68c7 --- /dev/null +++ b/examples/diagrams/mermaid-gallery.hmd @@ -0,0 +1,103 @@ +# A Mermaid gallery + +One cell for each of the diagram types a documentation card uses most. Back to +[[index]]. + +## Sequence + +```mermaid#show +sequenceDiagram + participant U as Author + participant P as Preview + participant R as Renderer + U->>P: edits a cell + loop each diagram cell + P->>R: source on stdin + alt the source draws + R-->>P: SVG + else it does not + R-->>P: the reason + end + end + Note over P,R: bounded to 2 s +``` + +## Class + +```mermaid#show +classDiagram + class Engine { + +String name + +render(source) Result + } + class D2Engine + class MermaidEngine + Engine <|-- D2Engine + Engine <|-- MermaidEngine + Engine "1" o-- "64" Result : caches +``` + +## Entity relationship + +```mermaid#show +erDiagram + VAULT ||--o{ CARD : holds + CARD ||--o{ CELL : contains + CARD { + string path PK + string title + } + CELL { + int index + string kind + } +``` + +## Gantt + +```mermaid#show +gantt + title Mermaid on par with D2 + dateFormat YYYY-MM-DD + section Tools + Fence kinds :a1, 2026-11-25, 1d + Engines :a2, after a1, 1d + section Ship + Toolchain :b1, after a2, 2d +``` + +## Pie + +```mermaid#show +pie title Fences in a vault + "hql" : 40 + "d2" : 18 + "mermaid" : 7 +``` + +## Mindmap + +```mermaid#show +mindmap + root((HyperMarkDown)) + Tools + hmd + core + extension + Cards + wiki + proposals +``` + +## Git graph + +```mermaid#show +gitGraph + commit + branch feature + checkout feature + commit + commit + checkout main + merge feature +``` diff --git a/examples/diagrams/states.hmd b/examples/diagrams/states.hmd new file mode 100644 index 0000000..6643c8b --- /dev/null +++ b/examples/diagrams/states.hmd @@ -0,0 +1,45 @@ +# The states of a diagram cell + +A cell's bar names its state: **drawn**, **stale**, or **not drawn**. Back to +[[index]]. + +## A cell that draws + +```mermaid#show +stateDiagram-v2 + [*] --> NotDrawn + NotDrawn --> Drawn: the source draws + Drawn --> Stale: an edit that does not draw + Stale --> Drawn: the source draws again + Drawn --> Drawn: an edit that draws +``` + +To see **stale**, break the cell above while the preview is open: delete the +`>` of one arrow. The drawing stays, dimmed, with the renderer's message under +it. Put the character back and the cell is drawn again. + +## A cell that never drew + +This source has a syntax error, so there is no drawing to keep. The cell shows +its source and the reason. + +```mermaid#show +flowchart TD + A --> --> [ +``` + +## A cell in D2 that never drew + +```d2#show +a -> { +``` + +## Configuration inside the fence + +A diagram can configure itself. This one asks for Mermaid's dark theme. + +```mermaid#show +%%{init: {"theme": "dark"}}%% +flowchart LR + light --> dark +``` diff --git a/scripts/launch-example.mjs b/scripts/launch-example.mjs index b1b051c..c3df7be 100644 --- a/scripts/launch-example.mjs +++ b/scripts/launch-example.mjs @@ -34,7 +34,7 @@ const target = name === "repo" || name === "wiki" ? repoRoot : join(repoRoot, "e if (!existsSync(target)) { console.error(`launch-example: no such example: ${name}`); console.error(` looked for ${target}`); - console.error(" try one of: cs-alg-sorting, small, notebook, highlighting, repo"); + console.error(" try one of: cs-alg-sorting, small, notebook, highlighting, diagrams, repo"); process.exit(2); } diff --git a/tools/hmd-vsc-ext/CHANGELOG.md b/tools/hmd-vsc-ext/CHANGELOG.md index 20de42a..a836847 100644 --- a/tools/hmd-vsc-ext/CHANGELOG.md +++ b/tools/hmd-vsc-ext/CHANGELOG.md @@ -38,6 +38,12 @@ against directory, then on `PATH`. This build does not carry it yet: install `merman-cli` on `PATH`, or point the setting at it. Without it a Mermaid cell shows its source and says why. +- **Zoom on a diagram.** Every drawing, in D2 and in Mermaid, has three small + buttons at its top right edge: smaller, the current size, and larger. The + middle one puts the drawing back at its own size. A zoomed drawing scrolls + inside its own box, and a cell keeps its zoom while you edit it. +- **A diagrams example.** `npm run example:diagrams` opens a vault of diagram + cells in both languages, with a Mermaid gallery and each state of a cell. - **Show Diagram.** A **Show diagram** code lens above every diagram cell, and the command *HyperMarkDown: Show Diagram* for the cell under the cursor. Show draws the cell again, and it is how to retry after a timeout or after diff --git a/tools/hmd-vsc-ext/media/render.ts b/tools/hmd-vsc-ext/media/render.ts index bb028b8..6d585ff 100644 --- a/tools/hmd-vsc-ext/media/render.ts +++ b/tools/hmd-vsc-ext/media/render.ts @@ -91,16 +91,13 @@ function renderDiagram(element: HTMLElement, block: DiagramBlock): void { return; } const rendered = block.dataUri !== null; + const zoom = zoomOf(element); element.className = rendered ? "hmd-diagram" : "hmd-diagram is-unrendered"; element.dataset["line"] = String(block.span.line); element.textContent = ""; if (rendered) { - const image = document.createElement("img"); - image.className = "hmd-diagram-image"; - image.src = block.dataUri!; - image.alt = `${block.language} diagram`; - element.append(image); + element.append(diagramView(block.dataUri!, `${block.language} diagram`, zoom)); return; } @@ -177,16 +174,11 @@ function renderDiagramCell(element: HTMLElement, block: DiagramBlock): void { source.append(code); source.hidden = !codeShown; + const zoom = zoomOf(body); body.textContent = ""; body.classList.remove("is-empty"); if (block.dataUri !== null) { - // An `` with a `data:` URI executes no script, so diagram source from - // a cloned repository cannot run code in the webview. - const image = document.createElement("img"); - image.className = "hmd-diagram-image"; - image.src = block.dataUri; - image.alt = `${block.language} diagram`; - body.append(image); + body.append(diagramView(block.dataUri, `${block.language} diagram`, zoom)); } if (!block.current) { const notice = document.createElement("div"); @@ -206,6 +198,99 @@ function renderDiagramCell(element: HTMLElement, block: DiagramBlock): void { } } +// -- diagram zoom -------------------------------------------------------- + +/** The zoom steps a reader moves through, and the bounds they stop at. */ +const ZOOM_STEP = 1.25; +const ZOOM_MIN = 0.25; +const ZOOM_MAX = 8; + +export type ZoomAction = "in" | "out" | "reset"; + +/** + * A drawing with its zoom buttons. + * + * A drawing is an SVG, so it stays sharp at any size, and a diagram of any + * size has labels too small to read at the width of a preview. The drawing + * sits in a box that scrolls, with three small buttons at its edge: smaller, + * the current size (which resets it), and larger. + * + * The drawing arrives as a `data:` URI on an ``, which executes no + * script — so diagram source from a cloned repository cannot run code in the + * webview. Zoom changes the size of that image and nothing inside it. + */ +function diagramView(dataUri: string, alt: string, zoom: number): HTMLElement { + const view = document.createElement("div"); + view.className = "hmd-diagram-view"; + + const scroll = document.createElement("div"); + scroll.className = "hmd-diagram-scroll"; + const image = document.createElement("img"); + image.className = "hmd-diagram-image"; + image.src = dataUri; + image.alt = alt; + scroll.append(image); + + const controls = document.createElement("div"); + controls.className = "hmd-diagram-zoom"; + controls.append( + zoomButton("out", "−", "Zoom out"), + zoomButton("reset", "100%", "Reset zoom"), + zoomButton("in", "+", "Zoom in"), + ); + + view.append(scroll, controls); + applyZoom(view, zoom); + return view; +} + +function zoomButton(action: ZoomAction, label: string, title: string): HTMLButtonElement { + const button = document.createElement("button"); + button.type = "button"; + button.className = `hmd-diagram-zoom-button hmd-diagram-zoom-${action}`; + button.dataset["zoom"] = action; + button.textContent = label; + button.title = title; + button.setAttribute("aria-label", title); + return button; +} + +/** + * The zoom of the drawing inside `element`, or 1 when it shows none. + * + * Read before a block is rebuilt, as the Code choice is: the size a reader + * chose survives a new drawing of the same cell. + */ +function zoomOf(element: HTMLElement): number { + const zoom = Number(element.querySelector(".hmd-diagram-view")?.dataset["zoom"]); + return Number.isFinite(zoom) && zoom > 0 ? zoom : 1; +} + +function applyZoom(view: HTMLElement, zoom: number): void { + const image = view.querySelector(".hmd-diagram-image"); + const reset = view.querySelector(".hmd-diagram-zoom-reset"); + view.dataset["zoom"] = String(zoom); + view.classList.toggle("is-zoomed", zoom !== 1); + if (image !== null) { + // At 1 the stylesheet sizes the image: as wide as the preview, at most. + image.style.width = zoom === 1 ? "" : `${Math.round(zoom * 100)}%`; + image.style.maxWidth = zoom === 1 ? "" : "none"; + } + if (reset !== null) reset.textContent = `${Math.round(zoom * 100)}%`; +} + +/** Make the drawing in `view` larger or smaller, or put it back. */ +export function zoomDiagram(view: HTMLElement, action: ZoomAction): number { + const current = Number(view.dataset["zoom"]) || 1; + const wanted = + action === "reset" ? 1 : action === "in" ? current * ZOOM_STEP : current / ZOOM_STEP; + // Snap to 1 when a step lands beside it, so in-then-out is exactly a reset. + const snapped = Math.abs(wanted - 1) < 0.01 ? 1 : wanted; + const zoom = Math.min(ZOOM_MAX, Math.max(ZOOM_MIN, snapped)); + applyZoom(view, zoom); + return zoom; +} + interface DiagramState { kind: "current" | "stale" | "none"; label: string; diff --git a/tools/hmd-vsc-ext/media/webview.css b/tools/hmd-vsc-ext/media/webview.css index cf208f1..853521d 100644 --- a/tools/hmd-vsc-ext/media/webview.css +++ b/tools/hmd-vsc-ext/media/webview.css @@ -588,6 +588,71 @@ body.is-graph-fullscreen .hmd-graph { } .hmd-diagram-cell.is-drawing > .hmd-cell-output, -.hmd-diagram-cell.is-stale > .hmd-cell-output > .hmd-diagram-image { +.hmd-diagram-cell.is-stale > .hmd-cell-output .hmd-diagram-image { opacity: 0.55; } + +/* -- diagram zoom ------------------------------------------------------- */ + +/* The drawing scrolls inside its own box once it is larger than the preview, + so a zoomed diagram does not push the page sideways. */ +.hmd-diagram-view { + position: relative; +} + +.hmd-diagram-scroll { + overflow: auto; + max-height: 85vh; + border-radius: var(--hmd-radius); +} + +.hmd-diagram-scroll > .hmd-diagram-image { + display: block; +} + +/* Three small buttons at the top right edge, quiet until the pointer is over + the drawing or the drawing is not at its own size. */ +.hmd-diagram-zoom { + position: absolute; + top: 0.3rem; + right: 0.3rem; + display: flex; + gap: 1px; + opacity: 0; + transition: opacity 120ms ease-in-out; +} + +.hmd-diagram-view:hover > .hmd-diagram-zoom, +.hmd-diagram-view:focus-within > .hmd-diagram-zoom { + opacity: 1; +} + +.hmd-diagram-view.is-zoomed > .hmd-diagram-zoom { + opacity: 0.85; +} + +.hmd-diagram-zoom-button { + appearance: none; + min-width: 1.35rem; + height: 1.35rem; + padding: 0 0.3rem; + border: 1px solid var(--vscode-panel-border); + background: var(--vscode-editorWidget-background, var(--vscode-editor-background)); + color: var(--vscode-foreground); + font: inherit; + font-size: 0.75em; + line-height: 1; + cursor: pointer; +} + +.hmd-diagram-zoom-button:first-child { + border-radius: var(--hmd-radius) 0 0 var(--hmd-radius); +} + +.hmd-diagram-zoom-button:last-child { + border-radius: 0 var(--hmd-radius) var(--hmd-radius) 0; +} + +.hmd-diagram-zoom-button:hover { + background: var(--vscode-toolbar-hoverBackground); +} diff --git a/tools/hmd-vsc-ext/media/webview.ts b/tools/hmd-vsc-ext/media/webview.ts index 01f2c83..f22868d 100644 --- a/tools/hmd-vsc-ext/media/webview.ts +++ b/tools/hmd-vsc-ext/media/webview.ts @@ -16,6 +16,7 @@ import { offsetForLine, patchBlocks, renderBreadcrumb, + zoomDiagram, type Anchor, type RenderSettings, } from "./render.js"; @@ -187,6 +188,19 @@ content.addEventListener("click", (event) => { return; } + const zoomButton = target.closest(".hmd-diagram-zoom-button"); + if (zoomButton !== null) { + event.preventDefault(); + const view = zoomButton.closest(".hmd-diagram-view"); + const action = zoomButton.dataset["zoom"]; + if (view !== null && (action === "in" || action === "out" || action === "reset")) { + zoomDiagram(view, action); + // A drawing that changed height moved everything below it. + anchors = collectAnchors(content); + } + return; + } + const cellButton = target.closest(".hmd-cell-button"); if (cellButton !== null) { event.preventDefault(); diff --git a/tools/hmd-vsc-ext/package.json b/tools/hmd-vsc-ext/package.json index 48754ce..c259e5d 100644 --- a/tools/hmd-vsc-ext/package.json +++ b/tools/hmd-vsc-ext/package.json @@ -382,6 +382,7 @@ "example:small": "node ../../scripts/launch-example.mjs small", "example:notebook": "node ../../scripts/launch-example.mjs notebook", "example:highlighting": "node ../../scripts/launch-example.mjs highlighting", + "example:diagrams": "node ../../scripts/launch-example.mjs diagrams", "example:repo": "node ../../scripts/launch-example.mjs repo", "example:wiki": "node ../../scripts/launch-example.mjs wiki", "package": "npm run build && node ../../scripts/toolchain.mjs --dest tools/hmd-vsc-ext/toolchain && vsce package --no-dependencies", diff --git a/tools/hmd-vsc-ext/test/renderer.test.ts b/tools/hmd-vsc-ext/test/renderer.test.ts index da94fe1..5db4380 100644 --- a/tools/hmd-vsc-ext/test/renderer.test.ts +++ b/tools/hmd-vsc-ext/test/renderer.test.ts @@ -18,6 +18,7 @@ import { offsetForLine, patchBlocks, renderBreadcrumb, + zoomDiagram, type Anchor, } from "../media/render.js"; @@ -306,6 +307,88 @@ describe("diagram cells", () => { }); }); +describe("diagram zoom", () => { + const drawing = `data:image/svg+xml;base64,${btoa("")}`; + const drawn = async (card: string): Promise => + (await ir_(card)).blocks.map((b) => + b.kind === "diagram" ? { ...b, dataUri: drawing, current: true } : b, + ); + const view = (): HTMLElement => container.querySelector(".hmd-diagram-view")!; + const image = (): HTMLImageElement => view().querySelector("img")!; + const label = (): string => view().querySelector(".hmd-diagram-zoom-reset")!.textContent!; + + for (const [name, card] of [ + ["a Mermaid cell", "```mermaid#show\nflowchart LR\n```\n"], + ["a D2 cell", "```d2#show\na -> b\n```\n"], + ["a plain `d2` fence", "```d2\na -> b\n```\n"], + ] as const) { + it(`gives ${name} three zoom buttons`, async () => { + patchBlocks(container, await drawn(card), settings); + const buttons = Array.from(view().querySelectorAll(".hmd-diagram-zoom-button")); + expect(buttons.map((b) => b.dataset["zoom"])).toEqual(["out", "reset", "in"]); + expect(buttons.map((b) => b.textContent)).toEqual(["−", "100%", "+"]); + }); + } + + it("starts at the drawing's own size, with no size of its own", async () => { + patchBlocks(container, await drawn("```mermaid#show\nflowchart LR\n```\n"), settings); + expect(view().dataset["zoom"]).toBe("1"); + expect(view().classList.contains("is-zoomed")).toBe(false); + expect(image().style.width).toBe(""); + }); + + it("makes the drawing larger and smaller, and says by how much", async () => { + patchBlocks(container, await drawn("```mermaid#show\nflowchart LR\n```\n"), settings); + expect(zoomDiagram(view(), "in")).toBe(1.25); + expect(image().style.width).toBe("125%"); + expect(image().style.maxWidth).toBe("none"); + expect(label()).toBe("125%"); + expect(view().classList.contains("is-zoomed")).toBe(true); + + zoomDiagram(view(), "out"); + zoomDiagram(view(), "out"); + expect(image().style.width).toBe("80%"); + expect(label()).toBe("80%"); + }); + + it("is back at its own size after in then out, and after reset", async () => { + patchBlocks(container, await drawn("```d2#show\na -> b\n```\n"), settings); + zoomDiagram(view(), "in"); + expect(zoomDiagram(view(), "out")).toBe(1); + expect(image().style.width).toBe(""); + + zoomDiagram(view(), "in"); + zoomDiagram(view(), "in"); + expect(zoomDiagram(view(), "reset")).toBe(1); + expect(image().style.width).toBe(""); + expect(image().style.maxWidth).toBe(""); + expect(label()).toBe("100%"); + }); + + it("stops at its bounds", async () => { + patchBlocks(container, await drawn("```d2#show\na -> b\n```\n"), settings); + for (let i = 0; i < 40; i += 1) zoomDiagram(view(), "in"); + expect(view().dataset["zoom"]).toBe("8"); + for (let i = 0; i < 80; i += 1) zoomDiagram(view(), "out"); + expect(view().dataset["zoom"]).toBe("0.25"); + }); + + it("keeps a cell's zoom when its source is edited and drawn again", async () => { + patchBlocks(container, await drawn("```mermaid#show\nflowchart LR\n```\n"), settings); + zoomDiagram(view(), "in"); + zoomDiagram(view(), "in"); + + patchBlocks(container, await drawn("```mermaid#show\nflowchart TD\n```\n"), settings); + expect(Number(view().dataset["zoom"])).toBeCloseTo(1.5625); + expect(image().style.width).toBe("156%"); + }); + + it("offers no zoom where nothing is drawn", async () => { + patchBlocks(container, (await ir_("```mermaid#show\nflowchart LR\n```\n")).blocks, settings); + expect(container.querySelector(".hmd-diagram-zoom")).toBeNull(); + }); +}); + describe("breadcrumb", () => { it("shows the namespace path and the card name", async () => { const document_ = await ir({ "specs/auth/login.hmd": "# Login\n" }, "specs/auth/login.hmd"); From 19ad985cb8c03e4eb65ad85ccd6f54a1d5e19a22 Mon Sep 17 00:00:00 2001 From: Yauhen Yakimovich Date: Wed, 25 Nov 2026 21:58:58 +0100 Subject: [PATCH 4/4] chore: pin toolchain 0.7.0, which carries merman-cli Every platform build of the extension now holds merman-cli 0.11.0, so a Mermaid cell draws on a fresh install. CI and the Pages deploy check merman-cli beside d2, and CI sets MERMAN_BIN so the engine's tests run against the real renderer. The release workflow checks each VSIX for the binary. The Features page draws the same picture in D2 and in Mermaid, and the READMEs and the tools page name Mermaid and its renderer. The three tracker rows that waited on the toolchain release are done. --- .github/workflows/ci.yml | 10 ++++++++++ .github/workflows/pages.yml | 3 +++ .github/workflows/release-vsc-ext.yml | 12 ++++++++---- README.md | 2 +- doc/public/features.hmd | 17 +++++++++++++--- doc/status/hmd.hmd | 28 +++++++++++---------------- doc/status/open.hmd | 5 +---- doc/status/pages.hmd | 8 +++++++- doc/status/proposals.hmd | 2 +- doc/status/vsc-ext.hmd | 10 +++++++++- doc/tools/index.md | 6 ++++-- toolchain.json | 24 +++++++++++------------ tools/hmd-vsc-ext/.vscodeignore | 2 +- tools/hmd-vsc-ext/CHANGELOG.md | 7 ++++--- tools/hmd-vsc-ext/README.md | 13 +++++++++++++ tools/hmd/README.md | 8 +++++++- 16 files changed, 106 insertions(+), 51 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 4a0e19c..bfc0393 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -81,6 +81,12 @@ jobs: - name: Check d2 run: d2 --version + # Mermaid is drawn by `merman-cli`, from the same toolchain release since + # 0.7.0 (issue 0115). With it on PATH the tests against the real renderer + # run instead of skipping, and the site build below draws Mermaid cells. + - name: Check merman-cli + run: merman-cli --version + # The second consumer of the resolver (HMD-0002). A build that goes red # here means the model works for lint but not for rendering. - name: Build the wiki @@ -149,6 +155,10 @@ jobs: env: HMD_REQUIRE_PARITY: "1" HQL_BIN: ${{ steps.toolchain.outputs.bin }}/hql + # The diagram engine's tests against the real Mermaid renderer run + # when this names one: that its flags are accepted, and that labels + # come back as SVG text (issue 0115). + MERMAN_BIN: ${{ steps.toolchain.outputs.bin }}/merman-cli - name: Package the extension run: npm run -w tools/hmd-vsc-ext package diff --git a/.github/workflows/pages.yml b/.github/workflows/pages.yml index 97b9b18..7833fdf 100644 --- a/.github/workflows/pages.yml +++ b/.github/workflows/pages.yml @@ -55,6 +55,9 @@ jobs: - name: Check d2 run: d2 --version + - name: Check merman-cli + run: merman-cli --version + # The cover's live editor is the TypeScript implementation, bundled. It # is build output, so it is built here, from the lockfile, and never # committed. A site built without it still works: the editor's tab says diff --git a/.github/workflows/release-vsc-ext.yml b/.github/workflows/release-vsc-ext.yml index a0387ac..2215941 100644 --- a/.github/workflows/release-vsc-ext.yml +++ b/.github/workflows/release-vsc-ext.yml @@ -137,15 +137,19 @@ jobs: # since 0.6.0, so every VSIX must carry it (issue 0117). Without it the # extension still works, and says once that the server is absent: a # build that lost the binary would look like a working release. - - name: Check every VSIX carries its d2 and hmd-lsp, and its hql where HQL ships one + # + # `merman-cli`, the Mermaid renderer, is in the toolchain for every + # platform since 0.7.0, so every VSIX must carry it (issue 0115). Without + # it a Mermaid cell shows its source and a reason on a fresh install. + - name: Check every VSIX carries its d2, merman-cli and hmd-lsp, and its hql where HQL ships one run: | set -euo pipefail for vsix in dist-vsix/*.vsix; do case "$vsix" in - *win32*) expected="extension/toolchain/bin/d2.exe extension/toolchain/bin/hmd-lsp.exe extension/toolchain/bin/hql.exe" ;; + *win32*) expected="extension/toolchain/bin/d2.exe extension/toolchain/bin/merman-cli.exe extension/toolchain/bin/hmd-lsp.exe extension/toolchain/bin/hql.exe" ;; *linux-x64*|*darwin-x64*|*darwin-arm64*) - expected="extension/toolchain/bin/d2 extension/toolchain/bin/hmd-lsp extension/toolchain/bin/hql" ;; - *) expected="extension/toolchain/bin/d2 extension/toolchain/bin/hmd-lsp" ;; + expected="extension/toolchain/bin/d2 extension/toolchain/bin/merman-cli extension/toolchain/bin/hmd-lsp extension/toolchain/bin/hql" ;; + *) expected="extension/toolchain/bin/d2 extension/toolchain/bin/merman-cli extension/toolchain/bin/hmd-lsp" ;; esac for file in $expected; do if ! unzip -l "$vsix" | grep -q "$file"; then diff --git a/README.md b/README.md index 4bf4877..d35ffc9 100644 --- a/README.md +++ b/README.md @@ -131,7 +131,7 @@ an error. Your prose is left alone. ### Math, diagrams, and metadata -TeX mathematics, D2 diagrams, callouts, collapsible sections, footnotes, task +TeX mathematics, D2 and Mermaid diagrams, callouts, collapsible sections, footnotes, task lists, and tables are part of the format. A diagram is text in the file, so it lives in version control and shows up in a diff you can read: diff --git a/doc/public/features.hmd b/doc/public/features.hmd index 3c4c407..7b0688b 100644 --- a/doc/public/features.hmd +++ b/doc/public/features.hmd @@ -27,7 +27,7 @@ nav: * **Metadata.** YAML frontmatter carries tags, imports, navigation hints, and anything your own tooling needs. -* **Rich content.** TeX mathematics, D2 diagrams, callouts, collapsible +* **Rich content.** TeX mathematics, D2 and Mermaid diagrams, callouts, collapsible sections, footnotes, heading permalinks, tables, code blocks. * **Validation.** `hmd lint` checks a tree. Unwritten pages are warnings; @@ -119,9 +119,20 @@ auth -> edge: token edge -> client: token + rotation window ``` +The same picture in Mermaid, as a `mermaid#show` fence: + +```mermaid#show +flowchart LR + client -->|credentials| edge + edge -->|verify| auth + auth -->|token| edge + edge -->|token + rotation window| client +``` + The diagram is text in the file, in version control, in a diff you can read. -Where no `d2` renderer is available it degrades to its own labelled source, not -to a blank space or a failed build. +Where no renderer is available it degrades to its own labelled source, not +to a blank space or a failed build. A fence marked only `mermaid` is a listing: +it shows the source as code. ## Mathematics diff --git a/doc/status/hmd.hmd b/doc/status/hmd.hmd index 2a187a3..3a5022a 100644 --- a/doc/status/hmd.hmd +++ b/doc/status/hmd.hmd @@ -85,20 +85,6 @@ work: [`diagram.py`, `PLAIN_LANGUAGES`] refs: >- [[hmd-0030#the-site-build]] - - kind: open - state: blocked - tags: [site, ci] - text: >- - **Install `merman-cli` where the site is built.** CI and the Pages - deploy install the pinned toolchain, and that toolchain does not carry - the Mermaid renderer yet, so a `mermaid#show` cell on the published site - shows its source with the reason - notes: >- - Unblocked by a toolchain release that pins `merman-cli`; then move the - pin in `toolchain.json` and check `merman-cli --version` beside - `d2 --version` in both workflows - refs: >- - [[hmd-0034#where-the-renderer-comes-from]] - kind: broken state: todo tags: [site, embeds] @@ -234,6 +220,14 @@ work: A changelog is a historical record refs: >- [[hmd-0005#what-deliberately-keeps-its-current-spelling]] + - kind: done + tags: [site, ci] + text: >- + **`merman-cli` is installed where the site is built** — toolchain 0.7.0 + carries it, the pin in `toolchain.json` names that release, and CI and + the Pages deploy check `merman-cli --version` beside `d2 --version`. A + `mermaid#show` cell on the published site is drawn, and the tests + against the real renderer run in CI. - kind: done tags: [site, cells] text: >- @@ -533,7 +527,6 @@ work | blocked | **Redirect the retired domain** to the current one, preserving paths | Registrar configuration, not a commit. See Broken | domain | [[hmd-0005#the-canonical-host-and-the-state-dns-has-to-reach]] | | parked | **Rename the package inside the parked integration suite** on the extension's old branch, which still uses the pre-rename directory name | Waits on that branch being picked up | rename | [[hmd-0005#the-repository-and-the-urls-that-point-at-it]] | | todo | **Draw only diagram cells in the site build.** A plain `d2` fence still draws beside the `d2#show` cell, and it becomes a code block | Lands in the same release as the TypeScript implementation's change, after this repository's fences are rewritten and HQL writes `d2#show` [`diagram.py`, `PLAIN_LANGUAGES`] | site, cells | [[hmd-0030#the-site-build]] | -| blocked | **Install `merman-cli` where the site is built.** CI and the Pages deploy install the pinned toolchain, and that toolchain does not carry the Mermaid renderer yet, so a `mermaid#show` cell on the published site shows its source with the reason | Unblocked by a toolchain release that pins `merman-cli`; then move the pin in `toolchain.json` and check `merman-cli --version` beside `d2 --version` in both workflows | site, ci | [[hmd-0034#where-the-renderer-comes-from]] | ## Broken @@ -587,6 +580,7 @@ work | Shipped | Tags | | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------- | +| **`merman-cli` is installed where the site is built** — toolchain 0.7.0 carries it, the pin in `toolchain.json` names that release, and CI and the Pages deploy check `merman-cli --version` beside `d2 --version`. A `mermaid#show` cell on the published site is drawn, and the tests against the real renderer run in CI. | site, ci | | **Mermaid diagrams and diagram cells in the site build** — a `mermaid#show` cell is drawn through `merman-cli` and a `d2#show` cell through `d2`, by one engine class with the same 64 KiB, 2 s, and 64-entry bounds, the same `data:` image, and the same labelled placeholder when a renderer is missing. A plain `mermaid` fence is a code block. `diagram.py` gains `MermaidEngine`, `CELL_KINDS`, and `engine_name`; unreleased. | site, cells | | **"Vault not found" when no `.hmd/` is above the start directory** — the error reads the way git's does outside a repository and says to run `hmd init` or pass `--root`; the README no longer describes the `wiki` setting or the `--wiki` flag; released in 0.5.1 | config, cli | | **`location_path` names the namespace root** — the setting formerly called `wiki`, read relative to the vault with the default `.`, the vault itself, instead of `doc/wiki`; no alias. `hmd init --location-path` replaces `--wiki`, and with no flag creates no directory; released in 0.5.0. | config | @@ -637,7 +631,7 @@ work | Tag | Open | Broken | Limitations | Done | Questions | | -------- | ---- | ------ | ----------- | ---- | --------- | | cells | 1 | 0 | 0 | 1 | 0 | -| ci | 1 | 0 | 0 | 0 | 0 | +| ci | 0 | 0 | 0 | 1 | 0 | | cli | 0 | 0 | 0 | 4 | 3 | | config | 0 | 0 | 0 | 4 | 2 | | docs | 0 | 0 | 2 | 0 | 0 | @@ -650,7 +644,7 @@ work | rename | 1 | 0 | 3 | 1 | 2 | | resolver | 1 | 0 | 0 | 2 | 1 | | scanner | 0 | 2 | 0 | 0 | 0 | -| site | 2 | 1 | 0 | 5 | 1 | +| site | 1 | 1 | 0 | 6 | 1 | | tests | 1 | 0 | 0 | 1 | 1 | diff --git a/doc/status/open.hmd b/doc/status/open.hmd index 2ecebd0..399da39 100644 --- a/doc/status/open.hmd +++ b/doc/status/open.hmd @@ -77,7 +77,7 @@ the board, in the order this view lists them. | ------- | ---- | | doing | 2 | | todo | 29 | -| blocked | 6 | +| blocked | 3 | | backlog | 16 | | parked | 3 | @@ -129,11 +129,8 @@ Every open row, `doing` first, then `todo`, `blocked`, `backlog` and | todo | Create the card a relative link points at. | [vsc-ext](vsc-ext.hmd) | | todo | Turn a plain `d2` fence into code in the preview. | [vsc-ext](vsc-ext.hmd) | | blocked | Redirect the retired domain | [hmd](hmd.hmd) | -| blocked | Install `merman-cli` where the site is built. | [hmd](hmd.hmd) | -| blocked | Show Mermaid beside D2 on the public pages | [pages](pages.hmd) | | blocked | Drop the mask. | [vsc-ext](vsc-ext.hmd) | | blocked | Name the HQL project and import `hmd` on the command line. | [vsc-ext](vsc-ext.hmd) | -| blocked | Carry `merman-cli` in the build. | [vsc-ext](vsc-ext.hmd) | | backlog | Lint text, not just files. | [hmd](hmd.hmd) | | backlog | Invalidate one card at a time | [hmd](hmd.hmd) | | backlog | HQL path, for HyperMarkDown 0.2.0. | [lang](lang.hmd) | diff --git a/doc/status/pages.hmd b/doc/status/pages.hmd index 217d32a..999eb22 100644 --- a/doc/status/pages.hmd +++ b/doc/status/pages.hmd @@ -70,7 +70,6 @@ revisiting is that maths loads from a CDN at view time. | todo | **The roadmap is behind the releases**: its version table, its news, and a section that lists released cells as coming | It now says where the work goes — the specification's first version and the editor here, AI and graph querying in HQL — and nothing else on it was brought forward. It is the one page that states versions, so it is the one page that has to be right | [the roadmap card](../issues/0013-the-roadmap-is-behind-the-releases.hmd) | | todo | **A screenshot of the example notebook for the cover**, in place of a crop from another vault | Needs the editor opened by hand | [the screenshot card](../issues/0114-a-screenshot-of-the-example-notebook.hmd) | | todo | **Rewrite every `d2` fence as `d2#show`** — in the book, the wiki, the README, and the example vaults, about eighteen fences — so the diagrams still draw once a plain `d2` fence is a listing. A fence that shows D2 source on purpose, inside an outer example fence, stays as it is | Lands with the release that turns the rule on in both implementations, not before it and not after | [[hmd-0030#backwards-compatibility]] | -| blocked | **Show Mermaid beside D2 on the public pages**: the Features page, the README, and the tools pages list D2 alone, and the Features page shows a diagram as D2 only. Add a `mermaid#show` example next to the D2 one | Unblocked when the Pages build installs a toolchain that carries `merman-cli`; before that the example would be published as its own source with a reason | [[hmd-0034]] | | backlog | **Self-host the maths typesetter**, so the site has no runtime dependency on anything it does not ship | Today it loads from a CDN, which is the site's only network dependency at view time. Not argued yet | — | ## Broken @@ -94,6 +93,11 @@ revisiting is that maths loads from a CDN at view time. ## Done +- **Mermaid is shown beside D2 on the public pages** — the Features page + lists both and draws the same picture in each, as a `mermaid#show` cell + next to the D2 one. The README and the tools pages name Mermaid and its + renderer. The Pages build installs toolchain 0.7.0, which carries + `merman-cli`, so the example is drawn on the published site. - **The cover names the released language** — it says the tools implement HyperMarkDown 0.1, links the specification, and no longer calls it a draft. The cover names the release line and not the patch, so a patch release @@ -217,6 +221,8 @@ run permanently. ## Changelog +- 2026-11-25: the blocked row for showing Mermaid beside D2 is done: the + Pages build installs toolchain 0.7.0, which carries the Mermaid renderer. - 2026-11-25: a blocked Open row for showing Mermaid beside D2 on the public pages, which waits on the Pages build carrying the Mermaid renderer. - 2026-11-25: the cover stops calling the specification a draft and names diff --git a/doc/status/proposals.hmd b/doc/status/proposals.hmd index bf9b75d..77210b1 100644 --- a/doc/status/proposals.hmd +++ b/doc/status/proposals.hmd @@ -85,5 +85,5 @@ cards | [HMD-0031](../proposals/HMD-0031/index.hmd) | Freeze | drafted | — | | [HMD-0032](../proposals/HMD-0032/index.hmd) | HQL path — addressing inside a card with `@[[…]]` | drafted | [hmd](hmd.hmd), [lang](lang.hmd), [rs-core](rs-core.hmd), [ts-core](ts-core.hmd) | | [HMD-0033](../proposals/HMD-0033/index.hmd) | `hmd-lsp` — the language server, written in Rust | drafted | [hmd](hmd.hmd), [lsp](lsp.hmd), [vsc-ext](vsc-ext.hmd) | -| [HMD-0034](../proposals/HMD-0034/index.hmd) | Mermaid, drawn by a native renderer | accepted | [hmd](hmd.hmd), [lang](lang.hmd), [pages](pages.hmd), [ts-core](ts-core.hmd), [vsc-ext](vsc-ext.hmd) | +| [HMD-0034](../proposals/HMD-0034/index.hmd) | Mermaid, drawn by a native renderer | accepted | [hmd](hmd.hmd), [lang](lang.hmd), [ts-core](ts-core.hmd), [vsc-ext](vsc-ext.hmd) | diff --git a/doc/status/vsc-ext.hmd b/doc/status/vsc-ext.hmd index 7768f46..3a3d5c2 100644 --- a/doc/status/vsc-ext.hmd +++ b/doc/status/vsc-ext.hmd @@ -86,7 +86,6 @@ picks and re-indexes without a reload, since `0.6.1` [issue 0116]. | blocked | **Drop the mask.** Before handing a card to HQL the extension renames a bare `hql` fence to `txt` and marks an `hql#query` fence `hidden`, because `hql render` runs bare `hql` fences as cells and writes outputs for queries, and this format says they are a listing and a hidden cell. Unblocks when HQL adopts both rules | One function and its call [`src/hql/engine.ts`, `maskForHql`] | [[hmd-0026#the-divergence-with]] | | blocked | **Name the HQL project and import `hmd` on the command line.** HQL's record of projects and vaults has a host pass the project it resolved, `--project `, and inject `--import hmd`. The extension passes neither: `hql render` imports `hmd` and selects the project itself, and the HQL the toolchain pins predates both flags and refuses an option it does not know. Unblocks when the toolchain pins an HQL release that has them | One argument list [`src/hql/engine.ts`, `run`] | [[hmd-0026#running-a-cell]] | | parked | **The integration suite** under `@vscode/test-cli` — written, compiling, and set aside on the `feat/vsc-ext-1` branch, because two upstream defects make it unrunnable on macOS | Below | [[hmd-0021#12-packaging-and-ci]] | -| blocked | **Carry `merman-cli` in the build.** The preview draws a `mermaid#show` cell with `merman-cli` from the `hyperMarkdown.diagram.mermaidPath` setting or from `PATH`. No platform build carries the binary yet, so a fresh install shows a Mermaid cell as its source with the reason | Unblocked by a toolchain release that pins `merman-cli`. Then move the pin in `toolchain.json`, check each VSIX for `toolchain/bin/merman-cli` in the release workflow, and set `MERMAN_BIN` in CI so the tests against the real binary run. Each platform build grows by 16 MB to 26 MB | [[hmd-0034#where-the-renderer-comes-from]] | | todo | **Turn a plain `d2` fence into code in the preview.** It still draws, without the cell layout, beside the `d2#show` cell | Lands together with the core's change and the rewrite of this repository's `d2` fences, or the book loses its diagrams | [[hmd-0030#deployment-activation]] | | backlog | **Show All Diagrams**, for a card, the way Run has Run All | An open question of the record, not yet asked for | [[hmd-0030#open-questions]] | @@ -121,6 +120,12 @@ about 300 MB on first run, which is why it is not in the default test command. ## Done +- **The build carries the Mermaid renderer** — every platform build holds + `merman-cli` 0.11.0 in `toolchain/bin/`, from toolchain 0.7.0, so a Mermaid + cell draws on a fresh install. The release workflow checks each VSIX for it, + and CI sets `MERMAN_BIN` so the engine's tests run against the real binary. + Each platform build grows by about 26 MiB; unreleased + [[hmd-0034#where-the-renderer-comes-from]]. - **Diagram cells in the preview** — a `d2#show` or `mermaid#show` fence is drawn like an `hql#eval` cell: the drawing first, the source behind Code, Edit beside it, and Show in place of Run. The drawing follows the source as @@ -289,6 +294,9 @@ npm run -w tools/hmd-vsc-ext package ## Changelog +- 2026-11-25: toolchain 0.7.0 carries `merman-cli`, so the blocked row for + carrying the renderer in the build is done. Done rows for zoom on a diagram + and for the diagrams example vault. - 2026-11-25: Done rows for diagram cells in the preview and for Mermaid drawn by `merman-cli`. The Open row for cells becomes the smaller row for a plain `d2` fence, and the Open row for Mermaid becomes a blocked row for diff --git a/doc/tools/index.md b/doc/tools/index.md index 52a770f..4bc8722 100644 --- a/doc/tools/index.md +++ b/doc/tools/index.md @@ -142,8 +142,10 @@ the tree of cards. cards below it. A card without it is left out of the build, and the build warns when a published card links to one that is left out. - **Diagrams draw.** A `d2` fence is drawn when [`d2`](https://d2lang.com) is on - your `PATH` or Docker is available. Otherwise the page shows the diagram's - labelled source, and the build still passes. + your `PATH` or Docker is available. A `mermaid#show` fence is drawn when + [`merman-cli`](https://github.com/latias94/merman) is on your `PATH`. + Otherwise the page shows the diagram's labelled source, and the build still + passes. MkDocs 2.0 removes plugins, so the extra pins MkDocs below 2.0. The plugin's full documentation is in the diff --git a/toolchain.json b/toolchain.json index 003b44d..56dad92 100644 --- a/toolchain.json +++ b/toolchain.json @@ -1,27 +1,27 @@ { - "$comment": "The one pin for every native binary HyperMarkDown runs — d2, hmd-lsp, and hql where HQL publishes the platform. See doc/issues/0107, 0111 and 0117. Bumping d2, hql or hmd-lsp happens in the toolchain repository; here only `version` and the digests move, together, in one commit.", + "$comment": "The one pin for every native binary HyperMarkDown runs — d2, merman-cli, hmd-lsp, and hql where HQL publishes the platform. See doc/issues/0107, 0111, 0115 and 0117. Bumping d2, merman-cli, hql or hmd-lsp happens in the toolchain repository; here only `version` and the digests move, together, in one commit.", "repo": "ewiger/hypermarkdown-toolchain", - "version": "0.6.0", + "version": "0.7.0", "archives": { "linux-x86_64": { - "name": "hypermarkdown-toolchain-0.6.0-linux-x86_64.tar.gz", - "sha256": "6ee19ddc6b94c653b0df6680dcf18b75a1f3948af74f9cd04ac623b9fc5f4c58" + "name": "hypermarkdown-toolchain-0.7.0-linux-x86_64.tar.gz", + "sha256": "46761f10030ccfa760120f470d5d172e8b12b5bb2ffbf4da6c01b4a6741aedd6" }, "linux-arm64": { - "name": "hypermarkdown-toolchain-0.6.0-linux-arm64.tar.gz", - "sha256": "130633611559839f36580396be00b368d27d8414560259e229426748a9c0e8f1" + "name": "hypermarkdown-toolchain-0.7.0-linux-arm64.tar.gz", + "sha256": "c532bc91cf6541e118d03d84f311fd4c49f4fce507e5c15b9ddd632b046518ab" }, "macos-x86_64": { - "name": "hypermarkdown-toolchain-0.6.0-macos-x86_64.tar.gz", - "sha256": "1e6b8e51d1205d207148f831f7a434189b5bc71f320e591737fe92104ca1b5a5" + "name": "hypermarkdown-toolchain-0.7.0-macos-x86_64.tar.gz", + "sha256": "545a91dcdb9a99521adc4577009ba6cb53aa288451db750feb305637c0c5da1b" }, "macos-arm64": { - "name": "hypermarkdown-toolchain-0.6.0-macos-arm64.tar.gz", - "sha256": "86890780b6f41ed03fc1128fb18c5d07b5111aacd5354a03b41b15cb4d8124cf" + "name": "hypermarkdown-toolchain-0.7.0-macos-arm64.tar.gz", + "sha256": "ec140f0558d9ca8f42e03b3cca552a675b407fa47c6f4cb5e2f240bbf5424238" }, "windows-x86_64": { - "name": "hypermarkdown-toolchain-0.6.0-windows-x86_64.zip", - "sha256": "877ffc1dd34f6eaa5a26502df38390e30edbfa8957f9b5ff7a58b9475f7d0bcc" + "name": "hypermarkdown-toolchain-0.7.0-windows-x86_64.zip", + "sha256": "fc77e0e02a6bd9df354947a7892a3f097c51ac3775c0f7ab51ab4450502341b1" } } } diff --git a/tools/hmd-vsc-ext/.vscodeignore b/tools/hmd-vsc-ext/.vscodeignore index 798f3b5..d20f496 100644 --- a/tools/hmd-vsc-ext/.vscodeignore +++ b/tools/hmd-vsc-ext/.vscodeignore @@ -1,5 +1,5 @@ # The VSIX ships two bundles, the static assets they need, and — in a -# platform-specific build — `toolchain/bin/d2`, `toolchain/bin/hmd-lsp`, and +# platform-specific build — `toolchain/bin/d2`, `toolchain/bin/merman-cli`, `toolchain/bin/hmd-lsp`, and # `toolchain/bin/hql` where HQL publishes the platform, from the pinned # toolchain release (issue 0107), nothing else (HMD-0021, Packaging). README.md, CHANGELOG.md, and LICENSE stay: the marketplace # renders the first two as its Details and Changelog tabs. diff --git a/tools/hmd-vsc-ext/CHANGELOG.md b/tools/hmd-vsc-ext/CHANGELOG.md index a836847..721ad76 100644 --- a/tools/hmd-vsc-ext/CHANGELOG.md +++ b/tools/hmd-vsc-ext/CHANGELOG.md @@ -35,9 +35,10 @@ against source, 2 seconds for a render, and a drawing delivered as an image, so nothing in a diagram can run. The renderer is found by the new setting `hyperMarkdown.diagram.mermaidPath`, then in the build's toolchain - directory, then on `PATH`. This build does not carry it yet: install - `merman-cli` on `PATH`, or point the setting at it. Without it a Mermaid - cell shows its source and says why. + directory, then on `PATH`. Every platform build carries `merman-cli` 0.11.0, + from toolchain 0.7.0, so Mermaid draws on a fresh install. Each build is + about 26 MiB larger for it. On Linux the bundled renderer needs glibc 2.35 + or later. Without a renderer a Mermaid cell shows its source and says why. - **Zoom on a diagram.** Every drawing, in D2 and in Mermaid, has three small buttons at its top right edge: smaller, the current size, and larger. The middle one puts the drawing back at its own size. A zoomed drawing scrolls diff --git a/tools/hmd-vsc-ext/README.md b/tools/hmd-vsc-ext/README.md index 50f35ab..ed2ac6d 100644 --- a/tools/hmd-vsc-ext/README.md +++ b/tools/hmd-vsc-ext/README.md @@ -74,6 +74,18 @@ Requires VS Code 1.90 or newer. release, the same binary the documentation site is built with, so a `d2` fence draws on a fresh install with nothing to configure and nothing downloaded at run time. Set `hyperMarkdown.diagram.d2Path` to use a different `d2`. +- **Mermaid diagrams.** A `mermaid#show` fence is drawn by + [`merman-cli`](https://github.com/latias94/merman), a native Mermaid renderer + that starts no browser. It ships in the same pinned toolchain as `d2`, so + Mermaid draws on a fresh install too. A plain `mermaid` fence is a listing + and is shown as code. Set `hyperMarkdown.diagram.mermaidPath` to use a + different `merman-cli`. +- **Diagram cells.** A `d2#show` or `mermaid#show` fence is a cell: the preview + shows the drawing, with its source behind **Code**, plus **Edit** and + **Show**. The drawing follows the source as you type. When an edit leaves + source that does not draw, the cell keeps its last drawing, marked stale, + with the reason under it. Three small buttons at the edge of every drawing + zoom out, reset, and zoom in. - **HQL cells, as a notebook.** A `hql#eval` or `hql#query` fence is a cell. The preview shows the output saved in the card — a table of contents reads as a table of contents — with the query behind **Code**, plus **Edit** and **Run**. @@ -121,6 +133,7 @@ not written yet. | `hyperMarkdown.preview.embeds` | `expanded` | Whether embed cards start expanded. | | `hyperMarkdown.diagnostics.scope` | `workspace` | Publish diagnostics for every indexed card — in every vault opened this session — or only for open ones. | | `hyperMarkdown.diagram.d2Path` | `""` | A `d2` to draw diagrams with instead of the bundled one. | +| `hyperMarkdown.diagram.mermaidPath` | `""` | A `merman-cli` to draw Mermaid diagrams with instead of the bundled one. Empty uses the bundled `merman-cli`, falling back to `merman-cli` on `PATH`. | | `hyperMarkdown.languageServer.enabled` | `true` | Start `hmd-lsp` for `.hmd` files. It never starts in an untrusted or a virtual workspace. | | `hyperMarkdown.languageServer.path` | `""` | An `hmd-lsp` to start instead of the default. Empty uses the bundled one, falling back to `hmd-lsp` on `PATH`. | | `hyperMarkdown.hql.path` | `""` | An `hql` to run cells with instead of the bundled one. Empty uses the bundled `hql`, falling back to `hql` on `PATH`. A shell alias is not on `PATH`. | diff --git a/tools/hmd/README.md b/tools/hmd/README.md index d92902c..8363518 100644 --- a/tools/hmd/README.md +++ b/tools/hmd/README.md @@ -224,7 +224,7 @@ repository's own `doc/` tree. ## Math, diagrams, callouts -TeX mathematics, D2 diagrams, callouts, tables, task lists, footnotes, +TeX mathematics, D2 and Mermaid diagrams, callouts, tables, task lists, footnotes, strikethrough. None of these are HyperMarkDown's own — they are the tier the wider markdown world settled on, and both `hmd render --to html` and the site build assume them present. @@ -233,6 +233,12 @@ Diagrams go through the [`d2`](https://d2lang.com) binary, which is deliberately *not* a Python dependency: without it a diagram degrades to its own labelled source rather than failing the build. +A `mermaid#show` fence is a Mermaid diagram. It goes through +[`merman-cli`](https://github.com/latias94/merman), a native Mermaid renderer +that starts no browser, found on `PATH`, and it degrades the same way without +it. A `d2#show` fence is drawn as a `d2` fence is. A plain `mermaid` fence is a +listing and stays a code block. + ## The library ```python