GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • Sign in
  • ActionsCI/CD and automation
  • CodespacesCloud development environments
  • All Features
  • Documentation
  • Training
  • Certifications
  • Build with Copilot
  • Customize Copilot
  • Integrations
  • Trending repos
  • GitHub Sponsors
  • Developer articles
  • Enterprises

This view

  • Original page
  • New address

GeezerVison is showing github.com — fix: PDF / editor の Mermaid ラベル消失・サイズ過大を 6 層 defense で解消 (#106) by ymnao · Pull Request #130 · ymnao/scripta

Conversation

@ymnao

@ymnao ymnao commented Jun 2, 2026

Copy link
Copy Markdown
Owner

概要

webContents.printToPDF の印刷経路で Mermaid 図が崩れる #106 を、6 層の defense として根本対処。最終形は scripta renderer 側で SVG を canvas で PNG にラスタライズして <img> で埋め込む(印刷経路の SVG quirk を構造的 bypass)。さらに editor / PDF 双方で発生していた 「Mermaid がでかすぎる」UX 問題、レビューで指摘された class/state diagram の config key bug + foreignObject silent strip も同 PR で解消。

経路別の出力形態:

経路 出力 理由
editor live preview inline SVG(自然寸法尊重) scalable・対話可、1.35x 拡大は撤去
HTML export inline SVG ブラウザは SVG を正しく描画
PDF export 2x PNG <img width="W" height="H">(標準 retina pattern) 印刷経路の SVG quirk を構造的 bypass、表示は自然寸法

関連 Issue

Closes #106

移行 Stage

該当なし(bug fix [7] フェーズ、PDF export 機能は Stage 5 で実装済みのバグ修正)。

  • Stage 0: 雛形 + フロント表示確認
  • Stage 1: ファイル I/O
  • Stage 2: ワークスペース・ファイルツリー・ファイル監視
  • Stage 3: 全文検索(ripgrep sidecar)
  • Stage 4: Git Sync
  • Stage 5: OGP / PDF / アップデート(既存機能のバグ修正)
  • Stage 6: 仕上げ・配布・切り替え

変更内容

Layer 1: foreignObject ラベル不可視

Mermaid 既定 htmlLabels: true は <foreignObject> 内 HTML でラベル描画するが Chromium 印刷経路は描画しない。htmlLabels: false を mermaid v11 正規 top-level key で指定し SVG <text> 強制。

Layer 2: SVG 寸法崩壊

useMaxWidth: true で width="100%" + style max-width emit → Chromium 印刷時 intrinsic 不在で height: auto が 0 解決される quirk。useMaxWidth: false で SVG に intrinsic width/height を出させる。mermaid v11 schema の全 diagram type に波及(class/state を含む、後述)。

Layer 3: SVG <text> ラベルの fill 透明化(mermaid#885)

theme variable fallback ${nodeTextColor || textColor} が undefined / 同色値解決される。themeVariables + themeCSS で .label text / .nodeLabel 等の fill を明示。

Layer 4: themeCSS の specificity / source order 負け

<text> / <tspan> 要素に fill 属性を SVG postprocess で直接注入。既存 fill / inline style の fill は除去。CSS specificity を完全 bypass。

Layer 5: 印刷経路の SVG text レンダリング自体が不安定(root cause)

scripta renderer で SVG → canvas → PNG ラスタライズ(src/lib/svg-rasterize.ts:svgToPng)し <img src="data:image/png;..."/> で埋め込み。print 経路は static bitmap のみ描画 → font 解決 / CSS 評価順序 / printToPDF 内 SVG quirk 全てを bypass。失敗時は inline SVG にフォールバック + console.error で診断情報出力(silent 化禁止)。

Layer 6: PDF / editor の Mermaid サイズ過大

  • PDF: 2x PNG / 1x display の retina pattern。extractSvgNaturalSizeAttrs() で SVG 自然寸法を <img width="W" height="H"> に設定、CSS で max-width: 100%
  • Editor: 旧 1.35x 拡大ロジック撤去 → 自然サイズに任せる

レビュー指摘 3 件への対処(最終 commit a8cadd6)

  • High: classDiagram / stateDiagram は mermaid v11 schema に存在しない config key で、useMaxWidth: false が silent に無視されていた。class / state に修正し、BaseDiagramConfig extends な全 type を schema から漏れなく列挙(26 type 全網羅)
  • 再発防止の静的型 guard: buildConfig の戻り型を mermaid 公式の MermaidConfig に明示。間違った key は TypeScript の excess property check で compile error
  • Medium (test): test を実 mermaid key で assert し直し、旧 wrong key (classDiagram 等) が undefined であることの regression guard も追加
  • Medium (foreignObject): svg-rasterize.ts で残存 foreignObject を検出した際 console.warn で必ず surface(silent label loss 回避)

動作確認

  • pnpm format clean
  • pnpm lint clean
  • pnpm typecheck clean
  • pnpm typecheck:e2e clean
  • pnpm test(unit, 1829 pass, 2 skipped)
  • pnpm build 成功
  • pnpm check:legacy-residue clean
  • 実機 (pnpm dev) で PDF export → flowchart の文字(英語 / 日本語ラベル / 記号)が全部読める / サイズ適切(ユーザ動作確認の PDF 共有済み)
  • 静的型 guard 動作確認: classDiagram: {...} を意図的に再追加して compile error が出ることを確認
  • 実機で class diagram / state diagram の PDF export → 300px に潰れず natural size で出ることを確認(class/state バグ修正後の動作確認)

スクリーンショット

ユーザによる実機 PDF 出力で flowchart (英語 / 日本語ラベル / 記号系全部表示)、サイズ適切、画像 quality OK を確認済(41 ページ文書、Layer 1〜6 全 defense 効果確認)。

References

  • mermaid#2688: Replace foreignObject with standard SVG
  • mermaid#7565: Labels not visible when foreignObject HTML labels (JCEF)
  • mermaid#885: Text not readable with fill styling when htmlLabels false
  • mermaid-cli#585: White text becomes gray when exporting as PDF
  • mermaid#1490 / #5038: SVG sizing / useMaxWidth behavior
  • mermaid v11 getEffectiveHtmlLabels: top-level htmlLabels new key, flowchart.htmlLabels deprecated
  • mermaid v11 MermaidConfig schema: authoritative diagram type keys
  • mermaid2img / mkdocs-mermaid-to-svg: rasterize + retina 2x pattern (ベストプラクティス)

Sorry, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

All reactions
ymnao and others added 3 commits June 2, 2026 18:07
@ymnao @claude
fix: PDF / editor の Mermaid ラベル消失とサイズ過大を解消 (#106)
caf2824
調査で判明した複数の真因を全部塞ぐ。前半(label visibility)と後半
(display size)を 1 commit に集約。

## 経路別の出力形態

| 経路 | 出力 | 理由 |
|---|---|---|
| editor live preview | inline SVG(自然寸法尊重) | scalable・対話可 |
| HTML export | inline SVG | ブラウザは SVG を正しく描画 |
| **PDF export** | **2x PNG `<img width="W" height="H">`**(標準 retina pattern) | 印刷経路の SVG quirk を構造的 bypass、表示は自然寸法 |

## 真因と対処

### Layer 1: foreignObject HTML ラベルの不可視

Mermaid 既定 `htmlLabels: true` は `<foreignObject>` 内 HTML でラベル描画
するが、Chromium 印刷経路は foreignObject を描画しない。

→ `htmlLabels: false` で SVG `<text>` 強制。mermaid v11 で `flowchart.
htmlLabels` は DEPRECATED なので **top-level `htmlLabels`** にも同値を
明示(`config.htmlLabels ?? config.flowchart?.htmlLabels ?? true` の解決
を確実に false にする)。

### Layer 2: SVG 寸法崩壊

`useMaxWidth: true` で `width="100%"` + style max-width emit → Chromium
印刷時 intrinsic 不在で `height: auto` が 0 解決される quirk → `useMaxWidth:
false` で intrinsic emit。

### Layer 3: SVG <text> ラベルの fill 透明化

mermaid#885: 印刷経路で SVG `<text>` の `fill` が theme variable fallback
の undefined / 同色値解決で透明化。themeVariables + themeCSS で fill 明示。

### Layer 4: themeCSS が CSS specificity / source order で負ける case

`<text>` / `<tspan>` 要素に `fill` 属性を直接注入する SVG 後処理
(既存 fill / inline style の fill は除去)。

### Layer 5: 印刷経路の SVG text レンダリング自体が不安定 (root cause)

font 解決 / CSS 評価順序 / printToPDF 内 SVG quirk が複合し、4 層対処
してもケースによっては text が消える。**scripta renderer 側で
SVG → canvas → PNG ラスタライズ**し、`<img src="data:image/png;..."/>` で
埋め込む。印刷経路は static bitmap だけ描画するので全ての不確定要素を
bypass する。

#### Layer 5 内の予防
- `stripForeignObjects`: rasterize 前に foreignObject を strip
  (htmlLabels: false 指定でも残ることがあり canvas tainted を引き起こす)
- `document.fonts.ready` 待ち: custom font 安定後に焼き付け
- ラスタライズ失敗時は inline SVG にフォールバック + DevTools console に
  必ず error 出力(silent 化禁止)

### Layer 6: PDF / editor で Mermaid がでかすぎる

ベストプラクティスに沿って display size を矯正。

**PDF 側 (`<img>` retina pattern)**:
- PNG は 2x scale(retina sharpness 確保)
- `<img width="W" height="H">` の表示寸法は SVG 自然寸法(1x)
- `.mermaid-diagram img { max-width: 100%; height: auto; }` で印刷ページ幅を
  超える時は縮む
- `extractSvgNaturalSizeAttrs()` で SVG ルートの width / height を抽出して
  img 属性に流し込む

**Editor live preview 側**:
- 以前は `max-width` を 1.35x に上書きして人工的に拡大していた
- mermaid v11 の自然サイズと組み合わさり「でかすぎる」UX に
- 1.35x 撤去、`width="100%"` + viewBox の自然サイズに任せる

### 診断用 hook

`SCRIPTA_PDF_DEBUG_HTML_PATH` 環境変数 → pdf.ts が printToPDF 直前の
HTML を指定 path にコピー(本番では env を設定しないので no-op、#106
等で「実際に何が WebView に届くか」を取り出すための debug 経路)。

## 実装ファイル

- `src/lib/svg-rasterize.ts` 新規:
  - `svgToPng(svg, opts)`, `stripForeignObjects(svg)`
- `src/lib/mermaid.ts`:
  - `MermaidRenderOptions` 型 export
  - top-level + flowchart の htmlLabels 両方明示
  - `getInvisibleLabelOverrides` / `forceVisibleTextInSvg`
- `src/lib/export.ts`:
  - `preprocessMermaidBlocks` に `embedOptions.rasterize`
  - `extractSvgNaturalSizeAttrs()` で img 表示寸法を 1x に
  - CSS に `.mermaid-diagram img { max-width: 100%; height: auto; }` 追加
  - rasterize 失敗時 `console.error` で診断情報を出す
- `src/components/editor/live-preview/mermaid.ts`:
  - 1.35x 拡大ロジック撤去、natural size 尊重
- `electron/main/ipc/pdf.ts`:
  - `SCRIPTA_PDF_DEBUG_HTML_PATH` debug hook

## References

- mermaid#2688: Replace foreignObject with standard SVG
- mermaid#7565: Labels not visible when foreignObject HTML labels
- mermaid#885: Text not readable with fill styling when htmlLabels false
- mermaid-cli#585: White text becomes gray when exporting as PDF
- mermaid#1490: SVG width and height attributes consistency
- mermaid#838 / #5038: useMaxWidth / sizing behavior
- mermaid v11 `getEffectiveHtmlLabels`: top-level htmlLabels new key
- mermaid2img / mkdocs-mermaid-to-svg: rasterize + retina 2x pattern

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
@ymnao @claude
refactor: #106 fix の verbose comment / 重複リテラルを simplify
8704b44
/simplify の 4 angle レビュー指摘から、複数 agent が convergent に挙げた
低リスクの cleanup のみ反映。挙動変更なし。

- mermaid.ts: `#1a1a1a` / `#d4d4d4` のリテラル重複を `LABEL_FILL_LIGHT`
  / `LABEL_FILL_DARK` の module-level 定数に抽出(Layer 3 themeVariables
  と Layer 4 forceVisibleTextInSvg が同色を共有、将来の drift 防止)
- mermaid.ts: `getInvisibleLabelOverrides` / `forceVisibleTextInSvg` /
  flowchart.htmlLabels deprecation 周りの 4-7 行コメントを 2-3 行に圧縮
- mermaid.ts buildConfig: diagram type 列挙周りの 3 行コメントを 2 行に
- export.ts: `extractSvgNaturalSizeAttrs` の 6 行 JSDoc → 2 行
- export.ts: `preprocessMermaidBlocks` JSDoc の重複した layer 説明を
  圧縮(function 内コメントと重複)
- export.ts: rasterize 分岐内の 7 行コメント → 2 行(function JSDoc に集約)
- svg-rasterize.ts: 先頭の 18 行 file header(実は svgToPng の JSDoc
  だったが順序 bug で stripForeignObjects の上にあった)を svgToPng の
  上に正しく配置し直し、5 行に圧縮。stripForeignObjects の JSDoc も
  「canvas tainted」重複を整理

不採用の指摘:
- Layers 3+4(themeVariables / forceVisibleTextInSvg)の削除案
  → Efficiency agent が「PNG ラスタライズ前の SVG <text> 色確定に必要、
    透明 text は透明 PNG に焼かれる」と反駁。user 動作確認済みの状態
    を維持
- 1.35x 撤去を別 PR へ split
  → user が editor の「でかすぎる」報告→撤去→ OK の流れで動作確認済
- `SCRIPTA_PDF_DEBUG_HTML_PATH` 削除
  → #93 改ページ redesign で同じ debug hook が再度欲しくなるはず
- buildConfig diagram type を Object.fromEntries で collapse
  → 字面のミニマル化と引き換えに「どの type にどの key を渡すか」の
    一覧性を失うので as-is が読みやすい

verify chain 全 green(format / lint / typecheck / unit 1827 pass /
build)。

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
@ymnao @claude
fix: class/state diagram の useMaxWidth が効いていなかった bug を解消 + 静的型 guard …
a8cadd6
…追加 (#106)

レビュー指摘 3 件への対処。

## High: class/state diagram で useMaxWidth:false が silent に無視されていた

`src/lib/mermaid.ts` の buildConfig が `classDiagram` / `stateDiagram` という
存在しない config key を設定していた。Mermaid v11.15.0 の正規 key は
`class` / `state`(`node_modules/mermaid/dist/config.type.d.ts:204-205` 参照)。

結果: 該当 SVG root は `width="100%" style="max-width: ..."` のまま emit され、
`svgToPng` の Image element で `naturalWidth` が読めず default 300px で
ラスタライズ → PDF 内で 300px に膨張 / 潰れ。

修正:
- `classDiagram` → `class`, `stateDiagram` → `state` に rename
- BaseDiagramConfig extends な全 type を mermaid v11 schema から漏れなく列挙
  (flowchart / sequence / class / state / er / pie / gantt / journey /
  timeline / quadrantChart / xyChart / requirement / architecture / mindmap /
  ishikawa / kanban / gitGraph / c4 / sankey / packet / block / eventmodeling /
  treeView / radar / venn / wardley-beta)
- `flowchart.htmlLabels` は deprecated なので削除し top-level htmlLabels のみに

## 静的型 guard(同 bug の再発防止)

`buildConfig` の戻り型を `MermaidConfig`(mermaid 公式型)に明示。間違った
diagram type key(`classDiagram` 等)を書くと TypeScript の excess property
check で **compile error**:

```
error TS2353: Object literal may only specify known properties, and
'classDiagram' does not exist in type 'MermaidConfig'.
```

mock-based test より厳格な guard。手元で意図的に classDiagram を再追加して
確認、上記エラーで弾かれる。

## Medium: test が mock 期待 shape だけで実 mermaid 挙動を見ていなかった

`config.classDiagram.useMaxWidth` を expect していたが mermaid は読まない key。
authoritative な key 名で assert し直し、加えて regression guard として
`config.classDiagram` / `config.stateDiagram` が **undefined** であることも
assert(旧 wrong key への drift 防止)。

## Medium: <foreignObject> 無条件 strip が silent label loss を許す

`svg-rasterize.ts` で stripForeignObjects は canvas tainted 回避に必要だが、
未対応 diagram type が foreignObject にラベルを出している場合、ラベル抜けの
PNG が成功扱いで通る。

修正: rasterize 前に foreignObject 存在を検出して `console.warn` で必ず
surface(label が消えた / htmlLabels:false を未対応 type に伝播していない
等の signal)。Strip 自体は変えない(canvas taint 防止)。test 2 件追加。

## Verify

- format / lint / typecheck / typecheck:e2e / unit (1829 pass) / build /
  legacy-residue 全 green
- mermaid.test.ts: regression guard test (config.classDiagram === undefined,
  config.class.useMaxWidth === false 等) 追加
- svg-rasterize.test.ts: foreignObject 検出 warning / 非検出時 no-warn の
  test 2 件追加

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Copilot AI review requested due to automatic review settings June 2, 2026 10:23
Copilot AI reviewed Jun 2, 2026

Copilot AI left a comment

Copy link
Copy Markdown

There was a problem hiding this comment.

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Copilot was unable to review this pull request because the user who requested the review has reached their quota limit.

Sorry, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

All reactions
@ymnao
ymnao merged commit 9732860 into main Jun 2, 2026
7 checks passed

Uh oh!

There was an error while loading. Please reload this page.

@ymnao
ymnao deleted the fix/pdf-mermaid-svg-sizing branch June 2, 2026 10:27
ymnao added a commit that referenced this pull request Jun 5, 2026
@ymnao @claude
docs: CHANGELOG を v0.2.0 リリース内容に更新
0598509
- Fixed にバグ修正クラスタをロールアップ追記 (#116 #117 #120 #124 #130 #131 #132 #134 #135 #136 #137)
- Added に手動アップデートチェック (#98 → #138) を追記
- Dependencies を Phase α 反映の実バージョンに更新
  (electron 42.3.3 / biome 2.4.16 / zustand 5.0.14 / js-yaml 4.2.0 /
   dompurify 3.4.8 / marked 18.0.4 / lucide-react 1.17.0 /
   @codemirror/view 6.43.0 / vite 8.0.14 / vitest 4.1.7)
- リリース日を _(unreleased)_ に、旧リポ表記を scripta-tauri (private) に、
  footer URL を ymnao/scripta に修正

Co-Authored-By: Claude Opus 4.8 <[email protected]>
ymnao added a commit that referenced this pull request Jun 5, 2026
@ymnao @claude
release: v0.2.0 (Electron 版初回リリース) (#61)
be27030
* release: v0.2.0

- package.json:version 0.0.0 → 0.2.0
- CHANGELOG.md 新設(旧 Tauri 版から Electron への完全書き直し版として
  Added / Changed / Fixed / Dependencies / Security / 既知の制限 を記載)

closes #27

* docs: v0.2.0 リリース運用注釈と README の表現を release-ready に更新

レビュー指摘反映:
- README.md: "v0.2.0 を予定" / "リリース後 ... 取得できる予定" を
  リリース後にも valid な表現へ書き換え(merge → tag push 後に
  Releases ページが publish される前提)
- docs/parity-checklist.md § 12: 「必須 4 項目は tag push 前に
  手動検証で pass させ、検証ログを Release Notes に追記する」
  というリリース運用を冒頭に明示

* docs: CHANGELOG リリース日と parity-checklist リリース運用を実態に合わせる

レビュー指摘反映:
- CHANGELOG.md: リリース日を 2026-05-13 → 2026-05-14 (publish/tag 日に揃える)
- docs/parity-checklist.md § 12: release.yml が tag push 後に
  draft Release を `--generate-notes` で自動生成する流れに合わせ、
  「Release Notes 追記 → tag push」を「tag push → draft 自動生成
  → 生成された draft に検証ログ追記 → publish」の正しい順序へ修正

* docs: CHANGELOG を v0.2.0 リリース内容に更新

- Fixed にバグ修正クラスタをロールアップ追記 (#116 #117 #120 #124 #130 #131 #132 #134 #135 #136 #137)
- Added に手動アップデートチェック (#98 → #138) を追記
- Dependencies を Phase α 反映の実バージョンに更新
  (electron 42.3.3 / biome 2.4.16 / zustand 5.0.14 / js-yaml 4.2.0 /
   dompurify 3.4.8 / marked 18.0.4 / lucide-react 1.17.0 /
   @codemirror/view 6.43.0 / vite 8.0.14 / vitest 4.1.7)
- リリース日を _(unreleased)_ に、旧リポ表記を scripta-tauri (private) に、
  footer URL を ymnao/scripta に修正

Co-Authored-By: Claude Opus 4.8 <[email protected]>

---------

Co-authored-by: Claude Opus 4.8 <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Reviewers

Copilot code review Copilot
Copilot review effort
Applies to this pull request for everyone.Learn more about Copilot code review.
Copilot left review comments

Uh oh!

There was an error while loading. Please reload this page.

Assignees

No one assigned

Labels

None yet

Projects

None yet

Milestone

No milestone

Development

Successfully merging this pull request may close these issues.

fix: PDF 書き出しで Mermaid 図が一切表示されない

Uh oh!

There was an error while loading. Please reload this page.

2 participants

@ymnao
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
You are visitor 01402775 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.