fix(diagrams): upgrade Pele to 1.9.0 with measured rich text

This commit is contained in:
chengyongru authored and chengyongru committed 2026-10-24 23:46:11 +08:00
1 parent f4aacdbec2
commit d6cc08f335
13 files changed
+305 -52

No files matched your search

+1 -1
View File
@@ -8,7 +8,7 @@ Corresponding upstream source:
- Bun 1.3.13 (`bf2e2cecf27e800962b1e7f03d66278f9d5d2e79`): <https://github.com/oven-sh/bun/tree/bun-v1.3.13>
- Bun's patched WebKit (`4d5e75ebd84a14edbc7ae264245dcd77fe597c10`): <https://github.com/oven-sh/WebKit/tree/4d5e75ebd84a14edbc7ae264245dcd77fe597c10>
- OpenTUI 0.5.11: <https://www.npmjs.com/package/@opentui/core/v/0.5.11> (source: <https://github.com/anomalyco/opentui/tree/6b9863ea7c5fae22bfebb23c242ddcc4c2b0aa0e>)
- Pele 1.6.0: <https://www.npmjs.com/package/pele/v/1.6.0>
- Pele 1.9.0: <https://www.npmjs.com/package/pele/v/1.9.0>
- resvg-js 2.6.2 (MPL-2.0): <https://github.com/yisibl/resvg-js/tree/v2.6.2>. The public `index.js` wrapper and native bindings are unmodified; `tui/scripts/target-bindings.ts` supplies the build-target-specific internal loader and is included in `nanobot-tui-source.tar.gz`. The upstream license text is reproduced in the notices.
- fontkit 2.0.4: <https://www.npmjs.com/package/fontkit/v/2.0.4>; fontkit, dfa 1.2.0, and brotli 1.3.3 declare MIT in their upstream README files, which are reproduced in the notices because these npm releases have no standalone license file. Exact dependency versions and tarball integrity are pinned in `bun.lock`.
+2 -2
View File
@@ -10,7 +10,7 @@
"@xmldom/xmldom": "0.8.11",
"css-tree": "3.2.1",
"fontkit": "2.0.4",
"pele": "1.6.0",
"pele": "1.9.0",
},
"devDependencies": {
"@types/bun": "^1.3.13",
@@ -109,7 +109,7 @@
"pako": ["pako@0.2.9", "", {}, "sha512-NUcwaKxUxWrZLpDG+z/xZaCgQITkA/Dv4V/T6bw7VON6l1Xz/VnrBqrYjZQ12TamKHzITTfOEIYUj48y2KXImA=="],
"pele": ["pele@1.6.0", "", {}, "sha512-VfAiVItsOGlGhvnBfphdT28VCG7mXMZxQNOwAGsCtxI2ztbUsT39MraEOYjsapLxVETkdUZscm0DdotYDQMLdw=="],
"pele": ["pele@1.9.0", "", {}, "sha512-KUmBt7P5JduVKQaP6FKfXiRgH3LBVIKsmdgPJZU7jD3ye6F+Z8fbms+OjivE7rWY09Qx+5X65VKe/9ywKFJ9Sw=="],
"restructure": ["restructure@3.0.2", "", {}, "sha512-gSfoiOEA0VPE6Tukkrr7I0RBdE0s7H1eFCDBk05l1KIQT1UIKNc5JZy6jdyW6eYH3aR3g5b3PuL77rq0hvwtAw=="],
+1 -1
View File
@@ -17,7 +17,7 @@
"@xmldom/xmldom": "0.8.11",
"css-tree": "3.2.1",
"fontkit": "2.0.4",
"pele": "1.6.0"
"pele": "1.9.0"
},
"devDependencies": {
"@types/bun": "^1.3.13",
+122
View File
@@ -0,0 +1,122 @@
import { describe, expect, test } from "bun:test"
import { existsSync, readFileSync } from "node:fs"
import { create, type Font } from "fontkit"
import { DOMParser, XMLSerializer } from "@xmldom/xmldom"
import { Resvg } from "@resvg/resvg-js"
import { render } from "pele/lazy"
import { renderDiagram } from "./render"
import { rasterDiagram } from "./raster"
import { shapeDiagramText } from "./text"
import { resolveDiagramSvg } from "./svg"
import { DIAGRAM_FONT_SIZE, type DiagramInput } from "./types"
const paths = process.platform === "win32"
? ["C:/Windows/Fonts/msyh.ttc", "C:/Windows/Fonts/msyhbd.ttc", "C:/Windows/Fonts/consola.ttf"]
: process.platform === "darwin"
? ["/System/Library/Fonts/Supplemental/Arial.ttf", "/System/Library/Fonts/Supplemental/Arial Bold.ttf", "/System/Library/Fonts/Supplemental/Courier New.ttf"]
: ["/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf", "/usr/share/fonts/truetype/dejavu/DejaVuSans-Bold.ttf", "/usr/share/fonts/truetype/dejavu/DejaVuSansMono.ttf"]
const open = (path: string): Font => {
const loaded = create(readFileSync(path))
return "fonts" in loaded ? loaded.fonts[0]! : loaded
}
const fixture = paths.every(existsSync) ? paths.map(path => ({ path, font: open(path) })) : undefined
const select = (index: number) => ({ path: fixture![index]!.path, postscriptName: fixture![index]!.font.postscriptName })
const input = (): DiagramInput => ({
source: "", width: 800, scale: 1,
fonts: { regular: select(0), bold: select(1), mono: select(2) },
colors: { foreground: "#202020", muted: "#666666", surface: "#eeeeee", border: "#888888", accent: "#3366cc" },
})
const document = (svg: string) => new DOMParser().parseFromString(svg, "image/svg+xml")
const glyphs = (svg: string) => Array.from(document(svg).getElementsByTagName("path")).flatMap(path => {
const match = /^translate\(([^ ]+) ([^)]+)\) matrix\(([^ ]+) 0 ([^ ]+) ([^ ]+) 0 0\)/.exec(path.getAttribute("transform") || "")
return match ? [{ path, x: Number(match[1]), y: Number(match[2]), scale: Number(match[3]), shear: Number(match[4]) }] : []
})
const source = (label: string) => `flowchart LR\n A["${label}"]`
describe.skipIf(!fixture)("Pele rich-text outlines with explicit local fonts", () => {
test("subscript and superscript use measured smaller glyphs, shifted baselines and centered advances", async () => {
const asset = await renderDiagram({ ...input(), source: source("H<sub>H</sub>H<sup>H</sup>H") })
const regular = fixture![0]!.font
const runs = glyphs(asset.layout.svg)
expect(runs).toHaveLength(5)
const [first, sub, middle, sup, last] = runs
const scale = DIAGRAM_FONT_SIZE / regular.unitsPerEm
const smaller = scale / 1.2
const advance = regular.layout("H").positions[0]!.xAdvance
for (const run of [first!, middle!, last!]) {
expect(run.scale).toBeCloseTo(scale, 10)
expect(run.y).toBeCloseTo(first!.y, 10)
}
for (const run of [sub!, sup!]) expect(run.scale).toBeCloseTo(smaller, 10)
expect(sub!.y - first!.y).toBeCloseTo(regular["OS/2"].ySubscriptYOffset * smaller, 10)
expect(sup!.y - first!.y).toBeCloseTo(-regular["OS/2"].ySuperscriptYOffset * smaller, 10)
expect(sub!.y).toBeGreaterThan(first!.y)
expect(sup!.y).toBeLessThan(first!.y)
for (let i = 1; i < runs.length; i++) expect(runs[i]!.x - runs[i - 1]!.x).toBeCloseTo(advance * runs[i - 1]!.scale, 10)
// Pele centers each node's label in its translated local group.
expect((first!.x + last!.x + advance * scale) / 2).toBeCloseTo(0, 10)
expect(asset.layout.svg).not.toContain("<text")
expect(asset.layout.svg).not.toContain("NaN")
expect(Array.from(asset.png.subarray(0, 8))).toEqual([137, 80, 78, 71, 13, 10, 26, 10])
})
test("underline becomes rasterized geometry while bold, mono, italic and scripted runs retain their fonts", async () => {
const label = "<b>H<sub>H</sub></b><code>H</code><i>H</i>"
const plain = await renderDiagram({ ...input(), source: source(label) })
const underlined = await renderDiagram({ ...input(), source: source(`<u>${label}</u>`) })
expect([underlined.width, underlined.height]).toEqual([plain.width, plain.height])
expect(underlined.png).not.toEqual(plain.png)
const runs = glyphs(underlined.layout.svg)
expect(runs).toHaveLength(4)
const regular = fixture![0]!.font, bold = fixture![1]!.font, mono = fixture![2]!.font
const faces = [bold, bold, mono, regular]
for (const [i, face] of faces.entries()) {
expect(runs[i]!.path.getAttribute("d")).toBe(face.glyphForCodePoint(72).path.toSVG())
expect(runs[i]!.scale).toBeCloseTo(DIAGRAM_FONT_SIZE / face.unitsPerEm / (i === 1 ? 1.2 : 1), 10)
}
expect(runs[3]!.shear / runs[3]!.scale).toBeCloseTo(Math.tan(14 * Math.PI / 180), 10)
expect(runs[0]!.shear).toBe(0)
const outlined = document(underlined.layout.svg)
const decorations = Array.from(outlined.getElementsByTagName("g"))
.filter(group => group.getAttribute("text-decoration") === "underline")
.flatMap(group => Array.from(group.getElementsByTagName("path")).filter(path => !path.hasAttribute("transform")))
expect(decorations).toHaveLength(4)
for (const [i, decoration] of decorations.entries()) {
const face = faces[i]!, run = runs[i]!
const bounds = new Resvg(`<svg xmlns="http://www.w3.org/2000/svg" width="800" height="200">${new XMLSerializer().serializeToString(decoration)}</svg>`, { font: { loadSystemFonts: false } }).getBBox()!
const thickness = face.underlineThickness * run.scale
expect(bounds.x).toBeCloseTo(run.x, 4)
expect(bounds.y).toBeCloseTo(run.y - face.underlinePosition * run.scale - thickness / 2, 4)
expect(bounds.width).toBeCloseTo(face.layout("H").positions[0]!.xAdvance * run.scale, 4)
expect(bounds.height).toBeCloseTo(thickness, 4)
decoration.parentNode!.removeChild(decoration)
}
const without = rasterDiagram({ ...underlined.layout, svg: new XMLSerializer().serializeToString(outlined) }, {
width: underlined.width, height: underlined.height, x: 0, y: 0,
viewWidth: underlined.layout.width, viewHeight: underlined.layout.height,
})
expect(without.png).toEqual(plain.png)
})
test("scripted and underlined outline pixels match Pele's native text with the same isolated font files", async () => {
for (const label of ["H<sub>H</sub>H<sup>H</sup>H", "<u>g<sub>g</sub>g<sup>g</sup>g</u>"]) {
const request = { ...input(), source: source(label) }
const asset = await renderDiagram(request)
const fonts = { regular: fixture![0]!.font, bold: fixture![1]!.font, mono: fixture![2]!.font }
const result = render(request.source, {
fontFamily: fonts.regular.familyName, fontFamilyMono: fonts.mono.familyName, fontSize: DIAGRAM_FONT_SIZE,
maxWidth: request.width, responsive: false, links: false, images: false,
measurer: { width: (text, size, style) => shapeDiagramText(fonts, text, size, style).width },
})
const native = new Resvg(resolveDiagramSvg(result.svg, request, fonts.regular.familyName, fonts.mono.familyName), {
font: { loadSystemFonts: false, fontFiles: paths },
}).render()
const outlined = new Resvg(asset.layout.svg, { font: { loadSystemFonts: false } }).render()
expect([outlined.width, outlined.height]).toEqual([native.width, native.height])
const expected = native.pixels, actual = outlined.pixels
let maxDelta = 0
for (let i = 0; i < actual.length; i++) maxDelta = Math.max(maxDelta, Math.abs(actual[i]! - expected[i]!))
expect(maxDelta).toBeLessThanOrEqual(1)
}
})
})
+50 -21
View File
@@ -1,36 +1,52 @@
import { DOMParser, XMLSerializer } from "@xmldom/xmldom"
import type { Font } from "fontkit"
import { OUTPUT_LIMIT } from "./types"
import { DIAGRAM_FONT_SIZE, OUTPUT_LIMIT } from "./types"
const SMALLER_RATIO = 1.2
export interface DiagramFonts { regular: Font; bold: Font; mono: Font }
export function shapeDiagramText(fonts: DiagramFonts, text: string, size: number, style: number) {
if (!Number.isFinite(size) || size <= 0 || size > 200 || (style & ~7)) throw new Error("Unsupported diagram font style")
if (!Number.isFinite(size) || size <= 0 || size > 200 || (style & ~63)) throw new Error("Unsupported diagram font style")
const face = style & 1 ? fonts.bold : style & 4 ? fonts.mono : fonts.regular
for (const char of text) {
if (!face.hasGlyphForCodePoint(char.codePointAt(0)!)) throw new Error("Diagram font missing glyph")
}
const run = face.layout(text)
const scale = size / face.unitsPerEm
return { run, scale, width: run.positions.reduce((width, position) => width + position.xAdvance, 0) * scale }
// Pele measures sub/sup at the CSS "smaller" ratio but passes the original size.
const scale = (style & 24 ? size / SMALLER_RATIO : size) / face.unitsPerEm
return { run, face, scale, width: run.positions.reduce((width, position) => width + position.xAdvance, 0) * scale }
}
/** Use the measured glyphs for every label, including synthetic CJK italics.
* Rasterizers then receive paths only and never reinterpret the font files. */
export function outlineDiagramText(svg: string, fonts: DiagramFonts): string {
const document = new DOMParser().parseFromString(svg, "image/svg+xml")
const declaration = (owner: Element, name: string): string | undefined => {
// The image policy has already parsed and serialized these declarations.
const inline = (owner.getAttribute("style") || "").split(";").find(value => value.startsWith(`${name}:`))
if (inline) return inline.slice(name.length + 1)
return owner.hasAttribute(name) ? owner.getAttribute(name)! : undefined
}
const property = (element: Element, name: string, fallback = ""): string => {
let current: Node | null = element
while (current?.nodeType === 1) {
const owner = current as Element
// The image policy has already parsed and serialized these declarations.
const inline = (owner.getAttribute("style") || "").split(";").find(value => value.startsWith(`${name}:`))
if (inline) return inline.slice(name.length + 1)
if (owner.hasAttribute(name)) return owner.getAttribute(name)!
current = owner.parentNode
const value = declaration(current as Element, name)
if (value !== undefined) return value
current = current.parentNode
}
return fallback
}
const sizes = new Map<Element, number>()
const fontSize = (element: Element): number => {
const cached = sizes.get(element)
if (cached !== undefined) return cached
const value = declaration(element, "font-size")
const inherited = () => element.parentNode?.nodeType === 1 ? fontSize(element.parentNode as Element) : DIAGRAM_FONT_SIZE
const size = value === undefined ? inherited() : value === "smaller" ? inherited() / SMALLER_RATIO : Number.parseFloat(value)
sizes.set(element, size)
return size
}
const style = (element: Element) => {
const weight = property(element, "font-weight")
const family = property(element, "font-family").replace(/^["']|["']$/g, "")
@@ -46,9 +62,18 @@ export function outlineDiagramText(svg: string, fonts: DiagramFonts): string {
}
return result
}
type Run = ReturnType<typeof shapeDiagramText> & { owner: Element; italic: boolean }
type Run = ReturnType<typeof shapeDiagramText> & { owner: Element; italic: boolean; baseline: number; underline: boolean }
type Chunk = { x: number; y: number; anchor: string; runs: Run[] }
let bytes = 0
const appendPath = (parent: Element, data: string, transform?: string) => {
bytes += Buffer.byteLength(data) + 200
if (bytes > OUTPUT_LIMIT) throw new Error("Diagram vector limit")
const path = document.createElementNS("http://www.w3.org/2000/svg", "path")
path.setAttribute("d", data)
if (transform) path.setAttribute("transform", transform)
path.setAttribute("vector-effect", "non-scaling-stroke")
parent.appendChild(path)
}
for (const text of Array.from(document.getElementsByTagName("text"))) {
const chunks: Chunk[] = []
let chunk: Chunk = { x: coordinate(text, "x", 0), y: coordinate(text, "y", 0), anchor: property(text, "text-anchor", "start"), runs: [] }
@@ -61,8 +86,13 @@ export function outlineDiagramText(svg: string, fonts: DiagramFonts): string {
if (child.nodeType === 1) collect(child as Element)
else if (child.nodeType === 3 || child.nodeType === 4) {
const flags = style(owner)
const size = Number.parseFloat(property(owner, "font-size", "16"))
chunk.runs.push({ ...shapeDiagramText(fonts, child.textContent || "", size, flags), owner, italic: !!(flags & 2) })
// SVG has already expressed the reduced size; do not apply the script flags twice.
const shaped = shapeDiagramText(fonts, child.textContent || "", fontSize(owner), flags)
const shift = property(owner, "baseline-shift")
const metrics = shaped.face["OS/2"]
const baseline = shift === "sub" ? (metrics?.ySubscriptYOffset ?? shaped.face.unitsPerEm * 0.2) * shaped.scale
: shift === "super" ? -(metrics?.ySuperscriptYOffset ?? shaped.face.unitsPerEm * 0.4) * shaped.scale : 0
chunk.runs.push({ ...shaped, owner, italic: !!(flags & 2), baseline, underline: property(owner, "text-decoration") === "underline" })
}
}
}
@@ -81,18 +111,17 @@ export function outlineDiagramText(svg: string, fonts: DiagramFonts): string {
parent.appendChild(nested)
parent = nested
}
const y = chunk.y + run.baseline
if (run.underline && run.width > 0) {
const thickness = run.face.underlineThickness * run.scale
const top = y - run.face.underlinePosition * run.scale - thickness / 2
appendPath(parent, `M${x} ${top}h${run.width}v${thickness}h${-run.width}Z`)
}
let advanceX = 0, advanceY = 0
for (let i = 0; i < run.run.glyphs.length; i++) {
const glyph = run.run.glyphs[i]!, position = run.run.positions[i]!
const path = document.createElementNS("http://www.w3.org/2000/svg", "path")
const data = glyph.path.toSVG()
bytes += Buffer.byteLength(data) + 200
if (bytes > OUTPUT_LIMIT) throw new Error("Diagram vector limit")
path.setAttribute("d", data)
const shear = run.italic ? Math.tan(14 * Math.PI / 180) : 0
path.setAttribute("transform", `translate(${x} ${chunk.y}) matrix(${run.scale} 0 ${shear * run.scale} ${-run.scale} 0 0) translate(${advanceX + position.xOffset} ${advanceY + position.yOffset})`)
path.setAttribute("vector-effect", "non-scaling-stroke")
parent.appendChild(path)
appendPath(parent, glyph.path.toSVG(), `translate(${x} ${y}) matrix(${run.scale} 0 ${shear * run.scale} ${-run.scale} 0 0) translate(${advanceX + position.xOffset} ${advanceY + position.yOffset})`)
advanceX += position.xAdvance
advanceY += position.yAdvance
}
+38 -7
View File
@@ -184,15 +184,46 @@ test("an enlarged diagram keeps its camera through resize and recoloring", async
await loadedImage(block.locator("img"));
});
test("published Pele renders Chinese subgraph, wrapping, emoji and measured emphasis", async ({ page }) => {
test("published Pele renders Chinese wrapping and mixed measured styles across widths and themes", async ({ page }) => {
await page.setViewportSize({ width: 1280, height: 1000 });
await page.goto("/browser/fixture.html?case=diagrams&edit");
const source = 'flowchart TD\nsubgraph 审核流程[中文子图:权限审核与结果交付]\nA["接收用户请求并检查工作区权限,保留中文长标签与 emoji ✅"] --> B["生成结果,并返回说明"]\nend\nclassDef measured font-size:18px,font-weight:bold,font-style:italic\nclass B measured';
const chinese = "接收用户请求并检查工作区权限保留中文长标签以及多语言自动换行";
const source = `%%{init: {"flowchart":{"wrappingWidth":140}}}%%\nflowchart TD\nsubgraph 审核流程[中文子图:权限审核与结果交付]\nA["${chinese}"] --> B["H<sub>2</sub>O x<sup>2</sup> <u>下划线</u> <b><i><code>List<T></code></i></b> <kbd>键</kbd> <samp>输出</samp> <tt>类型</tt> emoji ✅"]\nend\nclassDef measured font-size:18px,font-weight:bold,font-style:italic\nclass B measured`;
await page.getByRole("textbox", { name: "Diagram source" }).fill(source);
const image = page.getByTestId("mermaid-block").locator("img");
await loadedImage(image);
const svg = await image.evaluate(async (element: HTMLImageElement) => fetch(element.src).then((response) => response.text()));
expect(svg).toContain("中文子图");
expect(svg).toContain("emoji ✅");
expect(svg).toContain('font-weight="var(--_w)"');
await page.screenshot({ path: test.info().outputPath("chinese-subgraph.png"), fullPage: true });
for (const width of [1280, 390]) {
if (width === 390) {
const previous = await image.getAttribute("src");
await page.setViewportSize({ width, height: 844 });
await expect(image).not.toHaveAttribute("src", previous!);
}
for (const theme of ["light", "dark"]) {
if (await page.evaluate(() => document.documentElement.classList.contains("dark")) !== (theme === "dark")) {
const previous = await image.getAttribute("src");
await page.getByRole("button", { name: "Toggle theme" }).click();
await expect(image).not.toHaveAttribute("src", previous!);
}
await image.scrollIntoViewIfNeeded();
await loadedImage(image);
const rendered = await image.evaluate(async (element: HTMLImageElement) => {
const svg = await fetch(element.src).then((response) => response.text());
const document = new DOMParser().parseFromString(svg, "image/svg+xml");
const lines = Array.from(document.querySelector('g[data-id="A"] text')!.querySelectorAll("tspan"), (span) => span.textContent);
return { svg, lines };
});
expect(rendered.svg).toContain("中文子图");
expect(rendered.svg).toContain("✅");
expect(rendered.svg).toContain('font-weight="var(--_w)"');
expect(rendered.svg).toContain('baseline-shift="sub" font-size="smaller"');
expect(rendered.svg).toContain('baseline-shift="super" font-size="smaller"');
expect(rendered.svg).toContain('text-decoration="underline"');
expect(rendered.svg).toContain('font-family="var(--_fm)"');
expect(rendered.svg).toContain("List&lt;T&gt;");
expect(rendered.lines.length).toBeGreaterThan(1);
expect(rendered.lines.join("")).toBe(chinese);
expect(await page.evaluate(() => document.documentElement.scrollWidth <= innerWidth)).toBe(true);
await page.screenshot({ path: test.info().outputPath(`chinese-mixed-${theme}-${width}.png`), fullPage: true });
}
}
});
+2 -2
View File
@@ -22,7 +22,7 @@
"micromark-factory-space": "^2.0.1",
"micromark-util-decode-string": "^2.0.1",
"motion": "^14.4.0",
"pele": "1.6.0",
"pele": "1.9.0",
"qrcode": "^1.5.4",
"react": "^18.3.1",
"react-dom": "^18.3.1",
@@ -950,7 +950,7 @@
"pathval": ["pathval@2.0.1", "", {}, "sha512-//nshmD55c46FuFw26xV/xFAaB5HF9Xdap7HJBBnrKdAd6/GxDBaNA1870O79+9ueg61cZLSVc+OaFlfmObYVQ=="],
"pele": ["pele@1.6.0", "", {}, "sha512-VfAiVItsOGlGhvnBfphdT28VCG7mXMZxQNOwAGsCtxI2ztbUsT39MraEOYjsapLxVETkdUZscm0DdotYDQMLdw=="],
"pele": ["pele@1.9.0", "", {}, "sha512-KUmBt7P5JduVKQaP6FKfXiRgH3LBVIKsmdgPJZU7jD3ye6F+Z8fbms+OjivE7rWY09Qx+5X65VKe/9ywKFJ9Sw=="],
"picocolors": ["picocolors@1.1.1", "", {}, "sha512-xceH2snhtb5M9liqDsmEw56le376mTZkEX/jEb/RxNFyegNul7eNslCXP9FDj/Lcu0X8KEyMceP2ntpaHrDEVA=="],
+4 -4
View File
@@ -25,7 +25,7 @@
"micromark-factory-space": "^2.0.1",
"micromark-util-decode-string": "^2.0.1",
"motion": "^14.4.0",
"pele": "1.6.0",
"pele": "1.9.0",
"qrcode": "^1.5.4",
"react": "^18.3.1",
"react-dom": "^18.3.1",
@@ -6450,9 +6450,9 @@
}
},
"node_modules/pele": {
"version": "1.6.0",
"resolved": "https://registry.npmjs.org/pele/-/pele-1.6.0.tgz",
"integrity": "sha512-VfAiVItsOGlGhvnBfphdT28VCG7mXMZxQNOwAGsCtxI2ztbUsT39MraEOYjsapLxVETkdUZscm0DdotYDQMLdw==",
"version": "1.9.0",
"resolved": "https://registry.npmjs.org/pele/-/pele-1.9.0.tgz",
"integrity": "sha512-KUmBt7P5JduVKQaP6FKfXiRgH3LBVIKsmdgPJZU7jD3ye6F+Z8fbms+OjivE7rWY09Qx+5X65VKe/9ywKFJ9Sw==",
"license": "MIT",
"engines": {
"node": ">=20"
+1 -1
View File
@@ -35,7 +35,7 @@
"micromark-factory-space": "^2.0.1",
"micromark-util-decode-string": "^2.0.1",
"motion": "^14.4.0",
"pele": "1.6.0",
"pele": "1.9.0",
"qrcode": "^1.5.4",
"react": "^18.3.1",
"react-dom": "^18.3.1",
+1 -1
View File
@@ -1,4 +1,4 @@
Pele 1.6.0 — https://github.com/obsidianmd/pele
Pele 1.9.0 — https://github.com/obsidianmd/pele
MIT License
@@ -1,7 +1,7 @@
import { DiagramImageError } from "./svg-image";
import type { DiagramInput } from "./types";
// Pele's public TextMeasurer contract; the engine import stays in the Worker entry.
// Pele 1.9's public TextMeasurer contract; the engine import stays in the Worker entry.
export function canvasTextMeasurer(fonts: DiagramInput["fonts"]): {
width(text: string, size: number, style: number): number;
} {
@@ -13,10 +13,12 @@ export function canvasTextMeasurer(fonts: DiagramInput["fonts"]): {
const canvas = context;
return {
width(text, size, style) {
if (!Number.isFinite(size) || size <= 0 || size > 200 || (style & ~7) !== 0) {
if (!Number.isFinite(size) || size <= 0 || size > 200 || (style & ~63) !== 0) {
throw new DiagramImageError("unsupported");
}
const font = `${style & 2 ? "italic " : ""}${style & 1 ? "bold " : ""}${size}px ${style & 4 ? fonts.mono : fonts.sans}`;
// Sub=8 and Sup=16 share Pele's smaller scale; Underline=32 has no width effect.
const effectiveSize = style & (8 | 16) ? size / 1.2 : size;
const font = `${style & 2 ? "italic " : ""}${style & 1 ? "bold " : ""}${effectiveSize}px ${style & 4 ? fonts.mono : fonts.sans}`;
// Reset first so an invalid canvas font cannot reuse the preceding measurement.
canvas.font = "1px serif";
canvas.font = font;
@@ -1,4 +1,4 @@
// Worker-only policy for Pele 1.6 image documents. This is NOT an inline-SVG sanitizer.
// Worker-only policy for Pele 1.9 image documents. This is NOT an inline-SVG sanitizer.
import { SaxesParser } from "saxes";
import type * as CssTree from "css-tree";
// css-tree publishes these split entry points, but @types/css-tree declares only the barrel.
@@ -32,7 +32,7 @@ function fail(reason: DiagramFailure = "policy"): never {
throw new DiagramImageError(reason);
}
// Reviewed against the published 1.6.0 string renderer, including nested icon geometry.
// Reviewed against the published 1.9.0 string renderer, including nested icon geometry.
// Local marker/clip structures are accepted, but never <use>, links, images or paint servers.
const ELEMENTS = new Set([
"svg", "g", "path", "rect", "circle", "ellipse", "line", "polyline", "polygon",
@@ -278,6 +278,10 @@ export function diagramImageTemplate(svg: string, fonts: DiagramInput["fonts"]):
const root = stack.length === 0;
if (root && (elements !== 1 || tag.local !== "svg")) fail();
if (stack.at(-1) === "title" || stack.at(-1) === "desc") fail();
// Only Pele's flat, measured sub/sup runs may use relative sizing, never author CSS.
const shift = tag.attributes["baseline-shift"]?.value;
const shifted = tag.local === "tspan" && stack.at(-1) === "text"
&& (shift === "sub" || shift === "super") && tag.attributes["font-size"]?.value === "smaller";
const attributes: string[] = [];
const rootDrawing: string[] = [];
for (const attribute of Object.values(tag.attributes)) {
@@ -290,6 +294,8 @@ export function diagramImageTemplate(svg: string, fonts: DiagramInput["fonts"]):
let accepted = value;
if (name === "xml:space") {
if (value !== "preserve" && value !== "default") fail();
} else if (name === "baseline-shift" || (name === "font-size" && value === "smaller")) {
if (!shifted) fail("unsupported");
} else if (name === "style") accepted = style(value, root, fonts, refs);
else if (DRAWING_PROPERTIES.has(name)) accepted = drawingValue(name, css(value, "value"), refs);
else if (TYPOGRAPHY_PROPERTIES.has(name)) accepted = typography(name, css(value, "value"), root, fonts, true);
+70 -7
View File
@@ -11,11 +11,11 @@ const fonts: DiagramInput["fonts"] = {
const source = 'flowchart LR\n A["`**粗体** _italic_ 中文 😀`"] --> B[Result]';
let base: string;
async function peleSvg(text: string): Promise<string> {
async function peleSvg(text: string, measurer: ReturnType<typeof canvasTextMeasurer> = { width: (text) => text.length * 7 }): Promise<string> {
await load(detectType(text));
return render(text, {
fontFamily: fonts.sans, fontFamilyMono: fonts.mono, fontSize: fonts.size,
measurer: { width: (text) => text.length * 7 }, links: false, images: false,
measurer, links: false, images: false,
responsive: false, maxWidth: 600, maxEdges: 500,
}).svg;
}
@@ -67,11 +67,51 @@ describe("Pele image-only output", () => {
expect(image.content).toContain('font-weight="var(--_w)"');
});
it.each([
'flowchart LR\n A["H<sub>2</sub>O x<sup>2</sup> <u>under</u> <b><i><code>List<T></code></i></b> <kbd>key</kbd> <samp>sample</samp> <tt>type</tt>"] --> B',
'sequenceDiagram\n Alice->>Bob: H<sub>2</sub>O x<sup>2</sup> <u>under</u> <b><i><code>List<T></code></i></b> <kbd>key</kbd> <samp>sample</samp> <tt>type</tt>',
'stateDiagram-v2\n state "H<sub>2</sub>O x<sup>2</sup> <u>under</u> <b><i><code>List<T></code></i></b> <kbd>key</kbd> <samp>sample</samp> <tt>type</tt>" as Active\n [*] --> Active',
])("retains measured subscript, superscript, underline and monospace runs: %s", async (text) => {
const image = diagramImageTemplate(await peleSvg(text), fonts);
const document = new DOMParser().parseFromString(`<svg xmlns="http://www.w3.org/2000/svg">${image.content}</svg>`, "image/svg+xml");
expect(document.querySelector('tspan[baseline-shift="sub"][font-size="smaller"]')?.textContent).toBe("2");
expect(document.querySelector('tspan[baseline-shift="super"][font-size="smaller"]')?.textContent).toBe("2");
expect(document.querySelector('tspan[text-decoration="underline"]')?.textContent).toBe("under");
const mono = Array.from(document.querySelectorAll('tspan[font-family="var(--_fm)"]'));
expect(mono.map((span) => span.textContent)).toEqual(["List<T>", "key", "sample", "type"]);
expect(mono[0].getAttribute("font-weight")).toBe("var(--_w)");
expect(mono[0].getAttribute("font-style")).toBe("italic");
});
it("preserves generic type text without interpreting it as markup", async () => {
const image = diagramImageTemplate(await peleSvg('flowchart LR\n A["List<T>"] --> B["Map<K, V>"]'), fonts);
expect(image.content).toContain("List&lt;T&gt;");
expect(image.content).toContain("Map&lt;K, V&gt;");
});
it("wraps Chinese labels without spaces while preserving the full text", async () => {
const label = "接收用户请求并检查工作区权限保留中文长标签以及多语言自动换行";
const image = diagramImageTemplate(await peleSvg(`%%{init: {"flowchart":{"wrappingWidth":100}}}%%\nflowchart TD\n A["${label}"] --> B[完成]`), fonts);
const document = new DOMParser().parseFromString(`<svg xmlns="http://www.w3.org/2000/svg">${image.content}</svg>`, "image/svg+xml");
const lines = Array.from(document.querySelector('g[data-id="A"] text')!.querySelectorAll("tspan"), (span) => span.textContent ?? "");
expect(lines.length).toBeGreaterThan(1);
expect(lines.join("")).toBe(label);
for (const line of lines) expect(line.length * 7).toBeLessThanOrEqual(100);
});
it.each([
"font-family:fantasy", "letter-spacing:4px", "word-spacing:1em",
"font-size:2em", "font-size:201px", "font-weight:600", "font-style:oblique",
])("rejects unmeasured author typography: %s", async (authorStyle) => {
reject(await peleSvg(`flowchart LR\n A[Label] --> B\n style A ${authorStyle}`), "unsupported");
"font-size:2em", "font-size:smaller", "font-size:larger", "font-size:83.33%",
"font-size:201px", "font-weight:600", "font-style:oblique",
])("rejects unmeasured author typography even alongside measured subscript: %s", async (authorStyle) => {
reject(await peleSvg(`flowchart LR\n A["H<sub>2</sub>O"] --> B\n style A ${authorStyle}`), "unsupported");
});
it("does not promote author HTML attributes, scripts or resources into the image", async () => {
const image = diagramImageTemplate(await peleSvg('flowchart LR\n A["<sub style=font-size:999em onclick=alert(1)>safe</sub> <u><script>alert(2)</script><img src=https://bad.test/i onerror=alert(3)><foreignObject><b>foreign</b></foreignObject></u>"] --> B\n click A "https://bad.test/click"'), fonts);
expect(image.content).toContain('baseline-shift="sub" font-size="smaller">safe</tspan>');
expect(image.content).toContain("&lt;foreignObject&gt;");
expect(image.content).not.toMatch(/<(?:script|image|foreignObject|a)\b|onclick|onerror|999em|bad\.test/i);
});
it("preserves and resolves local marker/clip references and monospace attributes", () => {
@@ -122,19 +162,38 @@ describe("Pele image-only output", () => {
});
describe("canvas-only typography", () => {
it("uses the exact sans/mono size, bold and italic flags", () => {
it("uses the exact sans/mono size and shrinks sub/sup once without changing underline width", () => {
const context = canvasFixture();
const measurer = canvasTextMeasurer(fonts);
for (const [flags, expected] of [
[0, `18px ${fonts.sans}`], [1, `bold 18px ${fonts.sans}`],
[2, `italic 18px ${fonts.sans}`], [4, `18px ${fonts.mono}`],
[7, `italic bold 18px ${fonts.mono}`],
[8, `15px ${fonts.sans}`], [16, `15px ${fonts.sans}`],
[32, `18px ${fonts.sans}`], [47, `italic bold 15px ${fonts.mono}`],
[55, `italic bold 15px ${fonts.mono}`],
] as const) {
expect(measurer.width("中文 emoji 😀", 18, flags)).toBe(77);
expect(context.font).toBe(expected);
}
});
it("measures actual engine mixed styles at their effective numeric author size", async () => {
const context = canvasFixture();
const measured: { text: string; font: string }[] = [];
context.measureText.mockImplementation((text) => {
measured.push({ text, font: context.font });
return { width: text.length * 7 };
});
const svg = await peleSvg('flowchart LR\n A["plain <sub><b><i><u><code>sub</code></u></i></b></sub> <sup><b><i><u><kbd>sup</kbd></u></i></b></sup> <u>under</u>"]\n style A font-size:18px', canvasTextMeasurer(fonts));
expect(diagramImageTemplate(svg, fonts).content).toContain("font-size:18px");
expect(measured).toEqual(expect.arrayContaining([
{ text: "sub", font: `italic bold 15px ${fonts.mono}` },
{ text: "sup", font: `italic bold 15px ${fonts.mono}` },
{ text: "under", font: `18px ${fonts.sans}` },
]));
});
it("fails explicitly without OffscreenCanvas rather than using approximate metrics", () => {
vi.stubGlobal("OffscreenCanvas", undefined);
expect(() => canvasTextMeasurer(fonts)).toThrowError(new DiagramImageError("capability"));
@@ -165,11 +224,15 @@ describe("single-input Worker protocol", () => {
}
it("loads the actual engine, announces sync work, and returns only an image template", async () => {
const replies = await run('---\ntitle: Supported frontmatter\nconfig:\n links: true\n images: true\n---\n%%{init: {"flowchart":{"wrappingWidth":120}}}%%\nflowchart LR\n A["<b>中文</b>"] --> B\n click A "https://bad.test/"\n');
const replies = await run('---\ntitle: Supported frontmatter\nconfig:\n links: true\n images: true\n---\n%%{init: {"flowchart":{"wrappingWidth":120}}}%%\nflowchart LR\n A["<b>中文</b> H<sub>2</sub>O x<sup>2</sup> <u>under</u> <code>List<T></code>"] --> B\n click A "https://bad.test/"\n');
expect(replies.map((reply) => reply.kind)).toEqual(["started", "image"]);
const image = replies[1];
if (image.kind !== "image") throw new Error("Image missing");
expect(image.template.content).toContain("Supported frontmatter");
expect(image.template.content).toContain('baseline-shift="sub" font-size="smaller"');
expect(image.template.content).toContain('baseline-shift="super" font-size="smaller"');
expect(image.template.content).toContain('text-decoration="underline"');
expect(image.template.content).toContain("List&lt;T&gt;");
expect(image.template.content).not.toMatch(/<a\b|href=|<image\b/);
});