Skip to content

Commit 6f1d631

Browse files
Merge pull request #1 from Wave-RF/fix/measurement-css-label-clipping
feat: measurementCss option to stop label clipping (v0.3.0)
2 parents 938f765 + e3c368f commit 6f1d631

5 files changed

Lines changed: 124 additions & 19 deletions

File tree

‎README.md‎

Lines changed: 34 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -23,7 +23,7 @@ what makes it shareable across docs sites with different brands.
2323
## Install
2424

2525
```sh
26-
pnpm add github:Wave-RF/astro-themed-mermaid#v0.2.0 rehype-mermaid
26+
pnpm add github:Wave-RF/astro-themed-mermaid#v0.3.0 rehype-mermaid
2727
```
2828

2929
`rehype-mermaid` (and its peer `mermaid`) is a peer dependency — you wire it up
@@ -135,6 +135,7 @@ The plugin rewrites SVG *geometry* and swaps in your CSS variables; the matching
135135
|---|---|---|
136136
| `font.family` | string | font for build-time SSR measurement |
137137
| `font.woff2` | string (abs path) | woff2 inlined into build Chromium so it measures with the real font |
138+
| `measurementCss` | string | label-metric CSS injected at measure time (see [Label clipping](#label-clipping)) |
138139
| `themeVariables` | object | Mermaid `base` theme variables (build-time hex) |
139140
| `classDefs` | string[] | `classDef …` lines injected into every flowchart/graph block |
140141
| `colorReplacements` | `[from,to][]` | baked color → runtime CSS var; the **only** place colors enter |
@@ -149,6 +150,38 @@ The factory returns three things to wire up:
149150
| `rehypeMermaidOptions` | `markdown.rehypePlugins: [[rehypeMermaid, …]]` |
150151
| `integration` | `integrations` |
151152

153+
## Label clipping
154+
155+
Mermaid sizes each node's box by **measuring** the label in the build-time
156+
Chromium; the browser then **displays** it. If display is even ~1px wider than
157+
the measurement, the `<foreignObject>` crops the last glyph (`Buffer Consumer`
158+
→ `Buffer Consume`). Two things cause that drift, and both are fixed by feeding
159+
the build the same inputs the browser uses:
160+
161+
- **Font** — set `font.woff2` so the real font is loaded at measure time
162+
(a fallback like Arial measures ~6–8% narrower than Inter).
163+
- **Label metrics** — if your stylesheet renders labels at, say,
164+
`font-weight: 500` (or any `letter-spacing`), Mermaid measured them at the
165+
default `400` and every box is a hair too narrow. Pass those rules as
166+
`measurementCss`:
167+
168+
```js
169+
themedMermaid({
170+
font: { family: '"Inter Variable", sans-serif', woff2: "/abs/inter.woff2" },
171+
// matches what your global CSS applies to node labels at display time,
172+
// plus a hair of padding for sub-pixel safety:
173+
measurementCss:
174+
".nodeLabel p{font-weight:500;letter-spacing:-0.005em;padding-inline:1.5px;}",
175+
});
176+
```
177+
178+
> **Selectors must be bare.** Mermaid measures the label *before* it's
179+
> parented by the final `svg[aria-roledescription="flowchart…"]`, so a rule
180+
> scoped as `svg[aria-roledescription^="flowchart"] .nodeLabel p { … }`
181+
> matches at **display** time but is a **no-op at measure time**. Drop the
182+
> ancestor: `.nodeLabel p { … }`. (Edge/cluster labels usually render as
183+
> `overflow: visible` pills and don't need this — scope to `.nodeLabel p`.)
184+
152185
## How it works
153186

154187
`classDefs` are injected (via the remark plugin) after each flowchart/graph

‎index.d.ts‎

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,15 @@ export interface ThemedMermaidConfig {
2727
colorReplacements?: Array<[string, string]>;
2828
/** Font used for SSR measurement. */
2929
font?: ThemedMermaidFont;
30+
/**
31+
* Extra CSS injected into the build-time render page so Mermaid measures
32+
* labels with the same metrics (font-weight / letter-spacing / padding) your
33+
* stylesheet displays them at. Without it, labels whose display weight
34+
* differs from the measured one clip on the right. Selectors must NOT include
35+
* the `svg[aria-roledescription…]` ancestor (Mermaid measures before that
36+
* wrapper exists) — use bare `.nodeLabel p`, `.edgeLabel p`, etc.
37+
*/
38+
measurementCss?: string;
3039
/** Mermaid flowchart config (non-color), e.g. `{ curve: "basis", useMaxWidth: true }`. */
3140
flowchart?: Record<string, unknown>;
3241
/** Mermaid sequence config (non-color). */

‎index.mjs‎

Lines changed: 46 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -54,6 +54,13 @@ const FLOWCHART_SVG_RE =
5454
* @param {{family?:string, woff2?:string}} [config.font] - Font used for SSR
5555
* measurement. If `woff2` (an absolute path) is given it's inlined as a
5656
* data URL with font-display:block so Chromium measures with the real font.
57+
* @param {string} [config.measurementCss] - Extra CSS injected into the
58+
* build-time render page so Mermaid measures labels with the SAME metrics
59+
* (font-weight / letter-spacing / padding) your stylesheet displays them at —
60+
* otherwise labels whose display weight differs from the measured one clip on
61+
* the right. Selectors must NOT include the `svg[aria-roledescription…]`
62+
* ancestor (Mermaid measures before that wrapper exists); use bare
63+
* `.nodeLabel p`, `.edgeLabel p`, etc.
5764
* @param {object} [config.flowchart] - Mermaid flowchart config (non-color).
5865
* @param {object} [config.sequence] - Mermaid sequence config (non-color).
5966
* @param {string} [config.securityLevel] - Mermaid securityLevel (default strict).
@@ -64,21 +71,37 @@ export function themedMermaid(config = {}) {
6471
classDefs = [],
6572
colorReplacements = [],
6673
font = {},
74+
measurementCss = "",
6775
flowchart = {},
6876
sequence = {},
6977
securityLevel = "strict",
7078
cache = join("node_modules", ".cache", "astro-themed-mermaid"),
7179
} = config;
7280

73-
// --- build-time font inlining --------------------------------------------
74-
// Mermaid measures node widths in the build-time Chromium against whatever
75-
// font is available. If the declared font isn't actually loaded there, labels
76-
// are measured against a fallback (~Arial) and overflow at runtime (Inter is
77-
// ~6-8% wider per char). Inlining the woff2 with font-display:block makes
78-
// Chromium load it synchronously before measuring. (fontsource's own CSS uses
79-
// font-display:swap, which doesn't block, so it can't substitute for this.)
81+
// --- build-time measurement CSS ------------------------------------------
82+
// Mermaid sizes each label's box by MEASURING the label DOM in the build-time
83+
// Chromium, then the host browser DISPLAYS it. Anything that makes display
84+
// wider than measurement clips the last glyph (foreignObject crops to its
85+
// box). Two independent culprits, two pieces of injected CSS:
86+
//
87+
// 1. The FONT. If the declared font isn't loaded in the build Chromium,
88+
// labels are measured against a fallback (~Arial) and overflow at
89+
// runtime (Inter is ~6-8% wider per char). Inlining the woff2 with
90+
// font-display:block makes Chromium load it synchronously before
91+
// measuring. (fontsource's own CSS uses font-display:swap, which doesn't
92+
// block, so it can't substitute for this.)
93+
//
94+
// 2. Label METRICS — font-weight / letter-spacing / padding. If your
95+
// stylesheet renders node labels at, say, weight 500 but Mermaid
96+
// measured them at the default 400, every box is ~1px too narrow and the
97+
// last letter clips. Pass those rules as `measurementCss` so the build
98+
// measures what the browser shows. IMPORTANT: Mermaid measures the label
99+
// BEFORE it's parented by the final `svg[aria-roledescription="flowchart…"]`,
100+
// so write these selectors WITHOUT that ancestor — e.g. `.nodeLabel p`,
101+
// not `svg[aria-roledescription^="flowchart"] .nodeLabel p` (the latter
102+
// matches at display time but NOT at measure time, so it's a no-op here).
80103
let fontFamily = font.family || '"Arial", sans-serif';
81-
let fontCssDataUrl;
104+
const cssParts = [];
82105
if (font.woff2) {
83106
try {
84107
const b64 = readFileSync(font.woff2).toString("base64");
@@ -93,24 +116,30 @@ export function themedMermaid(config = {}) {
93116
const primaryFamily =
94117
(font.family || "").split(",")[0].trim().replace(/^["']|["']$/g, "") ||
95118
"sans-serif";
96-
const inlineCss = [
97-
"@font-face{",
98-
`font-family:${JSON.stringify(primaryFamily)};`,
99-
`src:url(data:font/woff2;base64,${b64}) format('woff2-variations');`,
100-
"font-weight:100 900;font-style:normal;font-display:block;}",
101-
].join("");
102-
fontCssDataUrl =
103-
"data:text/css;base64," + Buffer.from(inlineCss).toString("base64");
119+
cssParts.push(
120+
[
121+
"@font-face{",
122+
`font-family:${JSON.stringify(primaryFamily)};`,
123+
`src:url(data:font/woff2;base64,${b64}) format('woff2-variations');`,
124+
"font-weight:100 900;font-style:normal;font-display:block;}",
125+
].join("")
126+
);
104127
} catch {
105128
// Font file not on disk (e.g. fresh clone, no install). Fall back to the
106129
// default family so the build still succeeds.
107130
fontFamily = '"Arial", sans-serif';
108131
}
109132
}
133+
// Caller's label-metric rules, injected after the @font-face so they can
134+
// depend on the inlined font being available.
135+
if (measurementCss) cssParts.push(measurementCss);
136+
const measurementCssDataUrl = cssParts.length
137+
? "data:text/css;base64," + Buffer.from(cssParts.join("")).toString("base64")
138+
: undefined;
110139

111140
const rehypeMermaidOptions = {
112141
strategy: "inline-svg",
113-
...(fontCssDataUrl ? { css: fontCssDataUrl } : {}),
142+
...(measurementCssDataUrl ? { css: measurementCssDataUrl } : {}),
114143
mermaidConfig: {
115144
// `fontFamily` must sit at the top level — mermaid-isomorphic hard-codes
116145
// arial here if absent and ignores the same key in themeVariables.

‎package.json‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
{
22
"name": "astro-themed-mermaid",
3-
"version": "0.2.0",
3+
"version": "0.3.0",
44
"description": "Build-time, theme-aware Mermaid diagrams for Astro / Starlight — color-agnostic SVG rewriting (CSS-variable theming, cluster-title pills, edge-label pills) on top of rehype-mermaid.",
55
"type": "module",
66
"license": "MIT",

‎test/plugin.test.mjs‎

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -39,6 +39,40 @@ test("inlined @font-face registers the PRIMARY family name, not the whole CSS st
3939
);
4040
});
4141

42+
test("measurementCss is appended to the injected build-time CSS", async () => {
43+
// Label metrics (weight/letter-spacing/padding) the host applies at display
44+
// time must also be seen at measure time, or boxes are sized too narrow and
45+
// the last glyph clips. measurementCss is how the caller supplies them.
46+
const dir = await mkdtemp(join(tmpdir(), "atm-meas-"));
47+
const woff2 = join(dir, "x.woff2");
48+
await writeFile(woff2, "not-a-real-font-bytes");
49+
const meas = ".nodeLabel p{font-weight:500;letter-spacing:-0.005em;padding-inline:1.5px;}";
50+
const { rehypeMermaidOptions: o } = themedMermaid({
51+
font: { family: '"Inter Variable", sans-serif', woff2 },
52+
measurementCss: meas,
53+
});
54+
const css = Buffer.from(o.css.split(",")[1], "base64").toString("utf8");
55+
assert.match(css, /@font-face\{/, "still inlines the font");
56+
assert.ok(css.includes(meas), "appends the caller's measurementCss verbatim");
57+
assert.ok(css.indexOf("@font-face") < css.indexOf(meas), "measurementCss comes AFTER the @font-face");
58+
});
59+
60+
test("measurementCss is injected even without a woff2", () => {
61+
const meas = ".nodeLabel p{font-weight:500;}";
62+
const { rehypeMermaidOptions: o } = themedMermaid({ measurementCss: meas });
63+
assert.ok(
64+
typeof o.css === "string" && o.css.startsWith("data:text/css;base64,"),
65+
"css is present from measurementCss alone"
66+
);
67+
const css = Buffer.from(o.css.split(",")[1], "base64").toString("utf8");
68+
assert.equal(css, meas, "css is exactly the measurementCss when there's no font");
69+
});
70+
71+
test("no css option when neither font nor measurementCss is given", () => {
72+
const { rehypeMermaidOptions: o } = themedMermaid();
73+
assert.equal("css" in o, false, "css is omitted entirely so rehype-mermaid uses its defaults");
74+
});
75+
4276
test("rehypeMermaidOptions carries fontFamily at top level AND in themeVariables", () => {
4377
const { rehypeMermaidOptions: o } = themedMermaid({
4478
font: { family: "Test Font" },

0 commit comments

Comments
 (0)