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 — chore: Stage 0b — 旧 React フロントエンドのコピー + Tauri 直接依存差し替え by ymnao · Pull Request #4 · ymnao/scripta

Conversation

@ymnao

@ymnao ymnao commented Apr 30, 2026

Copy link
Copy Markdown
Owner

概要

旧 scripta(Tauri 版、参照専用)の React フロントエンドを scripta-next に持ち込み、@tauri-apps/* の直接 import を window.api 経由のモック実装に差し替える。Stage 0 の完了判定(Live Preview の全デコレーションが Chromium 上で破綻なく描画されること)を満たすコード基盤を整える。

テストファイルの移植・vitest 設定は次の PR(PR B)で別途対応する。

関連 Issue

なし(HANDOFF.md の Stage 0b タスクを実施)

移行 Stage

  • Stage 0: 雛形 + フロント表示確認

変更内容

依存追加(commit 1: 7682f01)

  • runtime deps: CodeMirror 群 / @uiw/react-codemirror / dompurify / js-yaml / katex / lucide-react / marked / mermaid / zustand / @lezer/highlight
  • devDeps: @types/js-yaml / @types/katex
  • pnpm.overrides: @codemirror/state 単一バージョン固定、@lezer/common ^1.5.2 ピン留め
  • pnpm.patchedDependencies: 旧 scripta から [email protected] を持ち込み

window.api 拡張 + main IPC ハンドラ(commit 2: 1e3c517 + commit 3: d4f66f6)

  • electron/preload/api.ts: 28 IPC コマンド + イベント subscribe + dialog / window 操作 + settings の型定義
  • electron/preload/index.ts: ipcRenderer.invoke / on への薄い橋渡し
  • electron/main/ipc/{dialog,fs,git,ogp,pdf,search,settings,shell,update,watcher,window}.ts: 12 ファイルでカテゴリ別ハンドラ
    • dialog / shell / settings(memory) / app:get-version: 本物実装
    • fs: メモリ Map ダミー(Stage 1 で fs/promises に置換)
    • git / search / ogp / pdf / update / watcher: 呼ばれても破綻しないシグネチャのダミー
    • openConflictWindow は Stage 4 で実装(現状 console.warn)
  • electron/main/index.ts の CSP を緩和: img-src https: data: blob:、font-src 'self' data:、worker-src 'self' blob:、prod でも style-src 'unsafe-inline'(KaTeX)
  • tsconfig.node.json の include に src/types を追加(main / preload から import type 可能に)
  • 旧 scripta から src/types/*.ts 8 ファイルを持ち込み(型のみ、Tauri 依存ゼロ)
  • electron/main/utils/url.ts に isSafeExternalUrl を抽出(重複解消)

旧 React フロントエンドのコピー + Tauri 差し替え(commit 4: c478b39 + commit 5: d10410d)

  • 旧 scripta の src/{components,hooks,lib,stores}/ の非テストファイル 90 ファイルをコピー(テストは PR B)
  • Tauri 直接依存 10 ファイルの import を window.api 経由(commands.ts ラッパー)に書き換え:
    • src/lib/{commands,store,export}.ts
    • src/components/{layout/AppLayout,layout/Sidebar,conflict/ConflictWindow,editor/live-preview/images}
    • src/hooks/{useFileWatcher,useGitSync,useUpdateCheck}
  • commands.ts に薄いラッパーを集約(CLAUDE.md 規約遵守)。コンポーネント / hook 側は window.api を直接呼ばない

検証用 DemoView(commit 6: 8c608b9)

  • ?demo=1 URL クエリで表示される検証用ビュー
  • Live Preview 14 種を含むサンプル Markdown を MarkdownEditor に流す
  • Stage 1(fs を本物にした時)に削除する一時コード

動作確認

ローカル CI ✓:

  • pnpm format — Formatted 123 files, no fixes applied
  • pnpm lint — Checked 124 files, no errors
  • pnpm typecheck — tsconfig.node.json + tsconfig.web.json 両方 pass
  • pnpm build — main / preload / renderer すべて build 成功
  • pnpm test — passWithNoTests(テストは PR B)

ローカル動作確認(マージ前にユーザー実施):

  • pnpm dev で Electron 起動 → AppLayout 表示
  • Sidebar の「Open Folder」→ ネイティブダイアログでフォルダ選択(メモリ fs ダミーなのでツリーは空表示)
  • ?demo=1 URL で DemoView 表示 → サンプル Markdown が MarkdownEditor に表示
  • Live Preview 14 種すべて描画: 見出し / 強調 / 取消線 / リンク + リンクカード / 外部 https 画像 / コードブロック + コピーボタン / リスト 3 種 / 引用 / 水平線 / テーブル / KaTeX インライン+ブロック / Mermaid / Wikilink
  • DevTools Console に CSP 違反 / undefined エラーが出ていない

スクリーンショット

(マージ前にユーザー側で添付)

残タスク(次の PR で対応)

  • PR B: *.test.ts(x) の移植 + vi.mock を window.api ベースに書き換え + vitest.config.ts 整備
  • Stage 1 で ?demo=1 分岐と DemoView を削除

🤖 Generated with Claude Code

Sorry, something went wrong.

Uh oh!

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

All reactions
ymnao and others added 6 commits April 30, 2026 14:15
@ymnao @claude
chore: Stage 0b 用 runtime deps と style-mod patch を追加
7682f01
- CodeMirror 群 / @uiw/react-codemirror / dompurify / js-yaml / katex
  / lucide-react / marked / mermaid / zustand / @lezer/highlight を追加
- @types/js-yaml / @types/katex を devDependencies に追加
- pnpm.overrides で @codemirror/state を単一バージョンに固定し
  @lezer/common ^1.5.2 をピン留め
- 旧 scripta から [email protected] を持ち込み(CodeMirror の
  adoptedStyleSheets 周りの動作改善)

Stage 0b の準備として、旧 React フロントエンドが要求する依存を揃える。
テスト関連の devDeps(jsdom / @testing-library/*)は PR B で別途追加。

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
@ymnao @claude
feat: window.api を拡張し main 側ダミー IPC ハンドラを追加
1e3c517
- electron/preload/api.ts に Stage 0b で必要な全 API(28 IPC コマンド +
  3 イベント subscribe + dialog / shell / settings / window 操作)を追加
- electron/preload/index.ts で ipcRenderer.invoke/on への薄い橋渡しを実装
  - listen 系は同期 unsubscribe を返す subscribe ヘルパーで整流
- electron/main/ipc/{dialog,fs,git,ogp,pdf,search,settings,shell,update,
  watcher,window}.ts を新設し、registerIpcHandlers() で集約
  - dialog / shell / settings(memory) / app:get-version は本物実装
  - fs はメモリ Map ダミー(Stage 1 で fs/promises に置き換え)
  - git / search / ogp / pdf / update / watcher は呼ばれても破綻しない
    シグネチャのダミー(後続 Stage で本実装)
  - openConflictWindow は Stage 4 で実装するため現状は console.warn
- electron/main/index.ts の CSP を緩和
  - img-src 'self' https: data: blob:(外部画像 + 生成 SVG)
  - font-src 'self' data:(KaTeX フォント)
  - worker-src 'self' blob:(Mermaid Worker 用の保険)
  - prod でも style-src 'unsafe-inline' を許可(KaTeX が大量の inline
    style を生成するため必須)
- 旧 scripta から src/types/* を持ち込み(型のみで Tauri 依存ゼロ)
  - tsconfig.node.json の include に src/types を追加して main / preload
    から `import type` 可能に

renderer 側の差し替えは次の commit で実施。この commit 単独で
typecheck / lint / build が通る状態を維持。

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
@ymnao @claude
refactor: /simplify の指摘を反映してコード重複と冗長な型注釈を解消
d4f66f6
- electron/main/utils/url.ts に isSafeExternalUrl() を抽出
  - electron/main/index.ts と electron/main/ipc/shell.ts で重複していた
    http(s) protocol チェックを共有化
- electron/main/ipc/dialog.ts で showOpenDialog / showSaveDialog の
  parent ? showXxx(parent, opts) : showXxx(opts) パターンを内部関数に
  集約(同じ三項が 2 箇所に重複していた)
- electron/preload/index.ts の as Promise<T> キャスト(30+ 箇所)を全削除
  - const api: Api = Object.freeze({...}) の型注釈から戻り値型と引数型が
    推論されるため、明示キャストは不要
  - これに伴い 6 種類の型 import(ConflictContent / GitStatus 等)も削除
  - onWindowCloseRequested の void event; を削除し _event リネームに変更

機能変更なし。lint / typecheck / build / test が引き続き通る。

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
@ymnao @claude
chore: 旧 React フロントエンドをコピー + Tauri 直接依存を window.api に差し替え
c478b39
旧 scripta(Tauri 版)の src/ から非テストファイルを scripta-next にコピー:
- src/components/ (common / conflict / editor / editor/live-preview /
  filetree / layout / search / slide)
- src/hooks/ (useAutoSave / useFileWatcher / useGitSync /
  useScratchpadVolatile / useUpdateCheck)
- src/lib/ 非テスト 16 ファイル
- src/stores/ 9 ファイル
- src/index.css / src/App.tsx / src/main.tsx
(テスト *.test.ts(x) と test-helper.ts は PR B で別途持ち込む)

Tauri 直接依存 10 ファイルの import を commit 2 で用意した window.api
経由のラッパーに置換:
- src/lib/commands.ts (invoke 28 関数 + plugin-shell.open)
- src/lib/store.ts (plugin-store の Store API → settingsGet/Set/Delete/Save)
- src/lib/export.ts (plugin-dialog.save → showSaveDialog)
- src/components/editor/live-preview/images.ts (convertFileSrc)
- src/components/layout/AppLayout.tsx
  - listen("menu-*") → onMenuEvent (同期 unsubscribe で簡素化)
  - WebviewWindow / getCurrentWindow().setFocus → openConflictWindow
  - getCurrentWindow().onCloseRequested → onWindowCloseRequested
    (preventDefault / destroy 不要、失敗時は throw で preload に伝える)
  - getCurrentWindow().close → closeWindow
- src/components/layout/Sidebar.tsx (plugin-dialog.open → openDirectoryPicker)
- src/components/conflict/ConflictWindow.tsx (emit / getCurrentWindow → emitConflictResolved / closeWindow)
- src/hooks/useFileWatcher.ts (listen<FsChangeEvent[]> → onFsChange)
- src/hooks/useGitSync.ts (listen("conflict-resolved") → onConflictResolved)
- src/hooks/useUpdateCheck.ts (api/app.getVersion → getAppVersion)

検証用 ?demo=1 分岐の追加と DemoView コンポーネントは次の commit。
本 commit 単独で format / lint / typecheck / build がすべて通る。

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
@ymnao @claude
refactor: window.api 直接呼び出しを commands.ts に集約
d10410d
CLAUDE.md 「IPC 経由のコマンドは src/lib/commands.ts に薄いラッパーを
集約する」方針に従い、コンポーネント / hook から window.api を直接
呼んでいた 21 箇所を commands.ts 経由に書き換え。

- commands.ts に 11 関数を追加: getAppVersion / closeWindow /
  openConflictWindow / convertFileSrc / openDirectoryPicker /
  showSaveDialog / emitConflictResolved / onFsChange /
  onConflictResolved / onMenuEvent / onWindowCloseRequested
- AppLayout.tsx / Sidebar.tsx / ConflictWindow.tsx /
  useFileWatcher.ts / useGitSync.ts / useUpdateCheck.ts /
  images.ts / export.ts の window.api.<method> 呼び出しを
  commands.<method> 経由に統一

window.api 直接呼び出しは src/lib/commands.ts(薄いラッパー集約)と
src/lib/store.ts(settings 専用ラッパー、旧 scripta の plugin-store
ラッパーと同じ責務)の 2 ファイルのみに残る。機能変更なし。

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
@ymnao @claude
feat: Stage 0b 検証用 DemoView を追加(Stage 1 で削除予定)
8c608b9
`?demo=1` URL クエリで表示される検証用ビューを追加。Live Preview の
14 種類のデコレーション(見出し / 強調 / 取消線 / リンク / リンクカード /
画像 / コードブロック + コピー / 順序リスト / 非順序リスト / タスクリスト /
引用 / 水平線 / テーブル / KaTeX インライン+ブロック / Mermaid / Wikilink)
を含むサンプル Markdown をハードコードして MarkdownEditor に流す。

scripta-next の Stage 0b ではメモリ fs ダミーで実ファイルが扱えないため、
ワークスペース機能を経由せずに Live Preview を確認できる経路として用意。
Stage 1(fs を本物にした時)で削除する一時コード。

- src/components/demo/sample-markdown.ts: サンプル Markdown 文字列
- src/components/demo/DemoView.tsx: MarkdownEditor のラッパー
  (system theme で hydrate)
- src/App.tsx: ?demo=1 分岐を追加(既存の ?conflict 分岐と同列)

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Copilot AI review requested due to automatic review settings April 30, 2026 07:15
Copilot AI reviewed Apr 30, 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 wasn't able to review this pull request because it exceeds the maximum number of lines (20,000). Try reducing the number of changed lines and requesting a review from Copilot again.

Sorry, something went wrong.

Uh oh!

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

All reactions
ymnao and others added 2 commits April 30, 2026 21:29
@ymnao @claude
fix: display math の Decoration.replace に block: true を追加
ef8da3f
@codemirror/view 6.41.1 で「ViewPlugin から複数行をまたぐ範囲を
Decoration.replace で置換するなら block: true を明示する」ルールが
厳格化された。display math (\$\$...\$\$) は複数行をまたぐ可能性が
あるため block: true を付与する。

エラー詳細:
RangeError: Decorations that replace line breaks may not be specified via plugins

このエラーが発生するとそれ以降の Decoration ロジックが停止し、
水平線より下のテーブル / KaTeX / Mermaid / Wikilink が破綻表示になる。
旧 scripta は @codemirror/view 6.41.0 で動作しているため、6.41.1 への
アップデートで顕在化した問題。

table-decoration.ts と mermaid.ts は既に block: true 指定済み。
display math の指定漏れのみ。

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
@ymnao @claude
fix: math.ts を ViewPlugin から StateField + ViewPlugin の hybrid に移行
9b7623b
@codemirror/view 6.41.1 で「block decoration は ViewPlugin から出せず
StateField 経由必須」のルールが厳格化された。math.ts は ViewPlugin で
display math (\$\$...\$\$) の block widget を出していたため
"Block decorations may not be specified via plugins" でエラーになり、
それ以降の Decoration(テーブル / KaTeX / Mermaid / Wikilink)が
すべて停止していた。

mermaid.ts / table-decoration.ts と同じパターン(StateField + 専用
hasFocusField + ViewPlugin で focus 変更検知)に書き換え:

- buildMathDecorations(state, hasFocus): EditorView 依存をなくして
  state ベースに変更(visibleRanges を使わず doc 全体を scan)
- mathHasFocusField: focus 状態を state に保持
- mathDecorationField: decorations を保持し EditorView.decorations
  に provide
- mathFocusHandler: focus 変更時に rebuildMathDecos effect を dispatch
- createMathClickHandler: view.plugin(mathPlugin) を
  view.state.field(mathDecorationField) に置換

mathDecoration extension の構成:
  [mathHasFocusField, mathDecorationField, mathFocusHandler,
   createMathClickHandler(), dollarInputHandler, dollarBackspace]

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Copilot AI review requested due to automatic review settings April 30, 2026 13:02
Copilot AI reviewed Apr 30, 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 wasn't able to review this pull request because it exceeds the maximum number of lines (20,000). Try reducing the number of changed lines and requesting a review from Copilot again.

Sorry, something went wrong.

Uh oh!

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

All reactions
@ymnao
ymnao merged commit 0b042c9 into main Apr 30, 2026
4 checks passed

Uh oh!

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

@ymnao
ymnao deleted the chore/stage-0b-frontend-import branch April 30, 2026 13:37
ymnao added a commit that referenced this pull request May 31, 2026
@ymnao @claude
chore: PR #103 code-review 7 件反映 (CI ガード設計欠陥修正)
9a1ff5e
/code-review で検出した 7 件全てに対応。最重要は self-counting 解消
(scripts/check-tauri-residue.sh → scripts/check-legacy-residue.sh)。

Fix #1: self-counting で Phase 5 green 化が原理的に不可能だった問題:
- scripts/check-tauri-residue.sh → check-legacy-residue.sh にリネーム
- ci.yml job tauri-residue → legacy-residue にリネーム
- package.json check:tauri-residue → check:legacy-residue にリネーム
- ci.yml コメントから "Tauri" / "WKWebView" verbatim を排除
- 結果: 88 行 (うち 4 行 self-reference) → 84 行 baseline と一致

Fix #2: pnpm verify が CI と divergence していた問題:
- verify chain に typecheck:e2e + build を追加
- check:legacy-residue は意図 fail のため verify には含めない (CLAUDE.md
  で「補助」として別行案内)

Fix #3: PATHS の coverage gap:
- pnpm-workspace.yaml (CLAUDE.md 上 canonical config) 追加
- vite.config.e2e.ts 追加
- tsconfig.json (root) 追加
- docs/tauri-purge-inventory.md §2.1 にも追従

Fix #4: WebKit 扱いの inventory との非整合:
- script ヘッダで WebKit 除外の意図を明記 (-webkit- prefix FP 回避)
- inventory §2.1 / §2.5 / §2.6 で CI ガードとの差分を明記
  (ime.ts:4 等 WebKit 系コメントは CI 非対象 → Phase 3 で手動チェック)

Fix #5: git grep exit ≥2 (pathspec error / 非 git repo 等) を silently
success として扱っていた問題:
- if RESULT=$(...) を捨て、明示的に EXIT=$? を捕捉
- case 0 / 1 / *) で 3 分岐 (match / no-match / error)
- error 時は stderr 出力 + exit 2

Fix #6: continue-on-error は workflow 成否にのみ作用し job の check-run
は failure のまま残るため、branch protection の required status checks
に追加すると merge blocking される:
- workflow コメントに caveat を追記
- 「Phase 5 完了まで required 化しない」運用を明示

Fix #7: :(exclude)scripts/check-tauri-residue.sh の dead code 化:
- 新ファイル名 :(exclude)scripts/check-legacy-residue.sh に更新
- 「PATHS に scripts/ を含めないため現状 no-op、defensive 配置」コメント
  追記

検証:
- bash scripts/check-legacy-residue.sh → 84 行検出 (PR 直前と一致)
- pnpm verify (format / lint / typecheck / typecheck:e2e / test /
  test:e2e / build) 全 pass

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
ymnao added a commit that referenced this pull request May 31, 2026
@ymnao @claude
chore: Tauri 残骸検出 CI ガードを追加 (#82 Phase 1 PR-2) (#103)
d0f3a7b
* chore: Tauri 残骸検出 CI ガードを追加 (#82 Phase 1 PR-2)

Issue #82 サブタスク D。Phase 2-5 の削除・置換進捗を質的に追跡する
CI ガードを設置する。

変更:
- scripts/check-tauri-residue.sh: 13 種の FORBIDDEN keyword
  (tauri / wkwebview / __TAURI / webviewWindow / @tauri-apps /
  src-tauri / tauri:// / tauri-plugin / data-tauri- /
  convertFileSrc / WebviewWindow / appWindow / tauri.conf) を
  git grep で検出。1 hit でも exit 1。対象スコープは
  docs/tauri-purge-inventory.md §2.1 と同期。-webkit- prefix CSS
  の false positive は keyword に WebKit を含めないことで除外
- package.json: check:tauri-residue script + verify script を追加
  (verify = format && lint && typecheck && test && test:e2e の
  chain を codify。check:tauri-residue は Phase 5 完了時に verify
  へ合流予定)
- .github/workflows/ci.yml: tauri-residue job を追加。Phase 1 時点
  では既存残骸 84 行が検出され意図 fail するため continue-on-error:
  true で merge を blocking しない運用。Phase 5 完了 PR で除去
- CLAUDE.md: 「コミット前の検証」を pnpm verify に集約

ローカル実行: 84 行検出で exit 1 (期待動作)。inventory §2.2 の
集計 (B 14 行 + 残り A/C/D) と整合。

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>

* chore: PR #103 code-review 7 件反映 (CI ガード設計欠陥修正)

/code-review で検出した 7 件全てに対応。最重要は self-counting 解消
(scripts/check-tauri-residue.sh → scripts/check-legacy-residue.sh)。

Fix #1: self-counting で Phase 5 green 化が原理的に不可能だった問題:
- scripts/check-tauri-residue.sh → check-legacy-residue.sh にリネーム
- ci.yml job tauri-residue → legacy-residue にリネーム
- package.json check:tauri-residue → check:legacy-residue にリネーム
- ci.yml コメントから "Tauri" / "WKWebView" verbatim を排除
- 結果: 88 行 (うち 4 行 self-reference) → 84 行 baseline と一致

Fix #2: pnpm verify が CI と divergence していた問題:
- verify chain に typecheck:e2e + build を追加
- check:legacy-residue は意図 fail のため verify には含めない (CLAUDE.md
  で「補助」として別行案内)

Fix #3: PATHS の coverage gap:
- pnpm-workspace.yaml (CLAUDE.md 上 canonical config) 追加
- vite.config.e2e.ts 追加
- tsconfig.json (root) 追加
- docs/tauri-purge-inventory.md §2.1 にも追従

Fix #4: WebKit 扱いの inventory との非整合:
- script ヘッダで WebKit 除外の意図を明記 (-webkit- prefix FP 回避)
- inventory §2.1 / §2.5 / §2.6 で CI ガードとの差分を明記
  (ime.ts:4 等 WebKit 系コメントは CI 非対象 → Phase 3 で手動チェック)

Fix #5: git grep exit ≥2 (pathspec error / 非 git repo 等) を silently
success として扱っていた問題:
- if RESULT=$(...) を捨て、明示的に EXIT=$? を捕捉
- case 0 / 1 / *) で 3 分岐 (match / no-match / error)
- error 時は stderr 出力 + exit 2

Fix #6: continue-on-error は workflow 成否にのみ作用し job の check-run
は failure のまま残るため、branch protection の required status checks
に追加すると merge blocking される:
- workflow コメントに caveat を追記
- 「Phase 5 完了まで required 化しない」運用を明示

Fix #7: :(exclude)scripts/check-tauri-residue.sh の dead code 化:
- 新ファイル名 :(exclude)scripts/check-legacy-residue.sh に更新
- 「PATHS に scripts/ を含めないため現状 no-op、defensive 配置」コメント
  追記

検証:
- bash scripts/check-legacy-residue.sh → 84 行検出 (PR 直前と一致)
- pnpm verify (format / lint / typecheck / typecheck:e2e / test /
  test:e2e / build) 全 pass

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>

---------

Co-authored-by: Claude Opus 4.7 (1M context) <[email protected]>
ymnao added a commit that referenced this pull request Jun 3, 2026
@ymnao
fix: PDF 改ページの過剰問題を hybrid 設計で解消 (#93) (#131)
42a1036
* fix: PDF 改ページの過剰問題を redesign (#93)

設計: grill-me セッション 14 で 9 件の Q&A により確定。

主な変更:

- inline `<script>` 注入を廃止し、main 側で組み立てた判定スクリプトを
  `webContents.executeJavaScript` で fonts.ready + idle 後に注入。font /
  image レイアウト確定前に走って測定が狂う問題を構造的に解消
- `electron/main/utils/page-break-script.ts` に判定ロジックを純関数として
  分離。Vitest unit test で安全網化
- `safetyBuffer = 0`(旧: 3 行分マージン)。Chromium 単一 WebView では誤差が
  小さく、buffer の害(widow 増加)の方が大きいため
- 判定基準を select で選択可能化:
  - **コンパクト**(default): 見出し + 直後の最初の本文ブロックが収まれば抑制
  - **節単位**: 見出し + 次の同位以上見出しまでが収まれば抑制
- `<\!-- pagebreak -->` 著者マーカーを `<hr class="pdf-pagebreak"/>` に変換し
  `break-before: page` を適用(HTML / PDF 両経路で利用可能、画面は不可視)
- 旧 `firstTargetHeading` 抑制を削除(CSS 仕様で「最初の要素の forced break
  は無視」が規定されているため不要)
- 旧 `forceUpperBreak` UI を非露出化し内部仕様で常時 ON(「章は常に改ページ、
  節は smart 抑制」を直感的デフォルトに)
- 旧 `applySmartPageBreaks` 静的判定を削除(PDF 経路では動的 script に上書き
  されるため dead code、HTML 経路では未使用)

IPC 契約:

- `pdf:export(html, outputPath, pageBreak?: {level: 1|2|3, criterion: "compact" | "section"})`
- main 側は `isValidPageBreakConfig` で受信時バリデーション

テスト:

- `electron/main/utils/page-break-script.test.ts` 新規: 判定スクリプトの
  構造 / criterion / forceLevel / safetyBuffer / marker 対応を文字列レベルで検証
- `src/lib/export.test.ts`: 旧 `buildDynamicPageBreakScript` / `applySmartPageBreaks`
  関連テスト整理、`preprocessPageBreakMarkers` + IPC contract テストを追加
- `e2e/electron/pdf-pagebreak.electron.spec.ts` 新規: 実 Electron で
  pageBreak option 付き / 不正 option / criterion=section の 3 ケースを safety net 化

* fix: PDF 改ページ default レベルを h2 に変更 (#93)

41 ページ Mermaid playground PDF を再生成して検証した結果、grill-me 設計
(forceUpperBreak 内部 ON)と旧 default `h3` の組み合わせで、典型的な
markdown 文書(H2 = 章/節)の全 H2 が強制改ページされる仕様上の挙動を
確認した。コード自体は意図通り動作していたが、default が文書傾向と
ミスマッチしていた。

変更:
- ExportDialog の useState 初期値を h3 → h2 に
- forceLevel = level - 1 → h2 default では forceLevel=1(h1 のみ常に改ページ、
  h2 は smart 評価対象)
- h3 までブレイクしたい用途は dropdown 操作で従来通り対応

テスト:
- 新 default(h2 / smart=true / criterion=compact)が exportAsPdf に渡る
  ことを検証

* fix: section criterion でセクション中割れを防ぐ (#93 follow-up)

ユーザ報告: 節単位オプションで「セクションが現ページに収まる」と判定されたが、
内部の break-inside: avoid ブロック (LI 等) がページ送りされ、見出しだけ前ページ
に残って中身が次ページに分断されるケースを確認。

原因:
- 旧 section 判定は「セクション総 need <= ページ残量」だけで抑制を確定し、
  その後のシミュレーション走査で個別 avoid-break ブロックが push されても
  抑制決定を撤回しなかった
- 結果として「H2 だけ現ページ末尾 + 末尾 LI が次ページ」という中割れ発生

修正:
- section criterion をシミュレーション走査ベースに書き換え:
  - 走査中に avoid-break ブロックが `simUsed + height > pageHeight` になれば
    セクション overflow と判定 → force-break
  - 走査で累積が pageHeight 超過した時点で同じく force-break
- compact criterion は意味が「H2 + 直後ブロック」までの保証のみなので変更なし

テスト:
- section ロジックに avoid-break 検出が含まれること / 旧 need 単純集計が
  残っていないことを文字列レベルで検証
- compact が従来の heading + first block 判定を維持していることを検証

* fix: PDF 改ページを CSS-only ベストプラクティスに再設計 (#93)

ユーザ報告で「節単位」criterion でもセクションが中割れする問題 (山田レジュメ
PDF) を確認。原因は JS DOM 測定と Chromium 実 layout の不可避な drift。

調査 (pdf4.dev / chromium / paged.js docs) で CSS Paged Media に完全委譲する
のがベストプラクティスと確認:

- pdf4.dev "CSS print styles: the complete guide" — Chromium-based engines は
  `break-after: avoid` / `break-inside: avoid-page` / widows / orphans を確実に
  サポート、JS による事前判定は不要
- "page-break-* は legacy、break-* が future-proof" だが modern+legacy 両出しが
  ガード堅牢
- Apply `break-inside: avoid` on wrapper elements を Chromium に任せれば、
  現ページ残量に section が収まらない時は自動 force-break される

新アーキテクチャ:

1. JS DOM 測定スクリプト完全廃止
   - `electron/main/utils/page-break-script.ts` / `.test.ts` 削除
   - `pdf.ts` の executeJavaScript 注入と pageBreak param 削除
   - IPC `pdf:export(html, outputPath)` の元のシンプルな署名へ戻す

2. `export.ts` で HTML 後処理 + CSS-only 改ページ
   - `wrapSectionsInHtml()`: smart-level の各セクションを
     `<section class="pdf-section-keep">` で wrap (criterion=section の時のみ)
   - `buildHtmlDocument` の CSS を全面刷新:
     * `h1-h6 { break-after: avoid; page-break-after: avoid }` 常時
     * `p, li, blockquote { widows: 3; orphans: 3 }` 常時
     * `p, li, pre, blockquote, table, img, .mermaid-diagram { break-inside: avoid }` 常時
     * `.pdf-section-keep { break-inside: avoid-page }` 常時
     * `hr.pdf-pagebreak { break-before: page }` 著者マーカー
     * `${forceLevels} { break-before: page }` 上位見出し強制 (smart=true は
       smart-level 自身は force しない、smart=false は level 自身も force)

3. smart criterion の意味整理(CSS Paged Media と整合)
   - smart=true + compact: heading break-after: avoid に任せる (wrap なし)
   - smart=true + section: section wrap で Chromium に keep-together 委譲
   - smart=false: level 以上を全部 force-break (旧 aggressive 動作)

期待される動作変化(山田レジュメ PDF):

- 旧 (JS 測定): h2 "頻度主義..." の last LI が次ページに送られて section 中割れ
- 新 (CSS-only): "頻度主義..." section 全体が現ページ残量に収まらない場合、
  Chromium が section 先頭で自動 force-break → section が page 2 先頭から開始

テスト:

- `export.test.ts`:
  - 旧 `buildDynamicPageBreakScript` / `applySmartPageBreaks` / IPC pageBreak
    関連テストを削除
  - `wrapSectionsInHtml()` の単体テスト 6 ケース新規
  - CSS-only 設計の output 検証(forceLevel / widows / orphans / break-after /
    .pdf-section-keep / modern+legacy alias)新規
- `e2e/electron/pdf-pagebreak.electron.spec.ts`:
  - pageBreak IPC param 廃止に追従し safety net を実 PDF 生成のみに簡略化

* fix: section break-before を JS で強制注入する hybrid 補正を再導入 (#93)

# 背景

CSS-only redesign (092f746) でユーザ確認したところ「節単位」criterion でも
セクションが中割れする問題が残った。

# 原因 (深堀り調査の結果)

Chromium の既知の限界:
- `break-inside: avoid` を wrapper 要素(section / div)に当てても、wrapper 全体
  を次ページに送る挙動には **ならない**
- 子要素 (LI 等) がそれぞれ `break-inside: avoid` を持つ場合、Chromium は
  「子要素間で break」を選択し、wrapper の avoid 要件は「子レベルで尊重した」
  とみなして wrapper の中割れを許容する
- known issue: chromium #601033, puppeteer #6366, bootstrap #15082, 多数の
  community report

→ pure CSS Paged Media では「section が現ページに収まらないなら全体を次ページに
送る」という挙動は実現不能。

# 解決策 (hybrid CSS + JS)

実 layout を JS で測定し、ページ境界をまたぐ section にだけ inline で
`break-before: page` を明示注入する。明示的な break-before は Chromium が
確実に尊重するため、wrapper 全体を強制移動できる。

実装:

- `electron/main/utils/page-break-script.ts` 新規:
  - `buildSectionBreakScript()` が返す IIFE を `executeJavaScript` 経由で実行
  - body width を 170mm に揃えて print 相当の text wrap で section 高さを測定
    (screen 幅 800px のままだと wrap が違って height が drift する)
  - body 直下の children を順に走査し、`.pdf-section-keep` が
    `(現ページ残量 < section 高さ) && (section 高さ <= 1 ページ高さ) &&
     (既にページ途中)` の時に `style.breakBefore = 'page'` を強制注入
  - `<hr class="pdf-pagebreak">` 著者マーカーも virtualY を次ページ頭にジャンプ
    させて測定整合性を保つ
  - try/finally で body style を確実に復元(例外でも壊れない)

- `electron/main/ipc/pdf.ts`:
  - `fonts.ready + idle` 後(フォント・画像・Mermaid raster がレイアウト確定後)
    に `executeJavaScript(buildSectionBreakScript())` を実行してから printToPDF
  - script 失敗は warning でログするだけで PDF 出力は続行(中割れリスクは残るが
    PDF 欠落は発生しない)

旧 dynamic measurement (#93 で削除した版) との違い:
- 「全要素のページフロー simulation」ではなく、「section が境界をまたぐ場合
  のみ break-before 注入」という最小限の介入
- 1 セクション当たり 1 つの bool 判定だけなので drift しても被害が小さい
- 既存の CSS `break-inside: avoid` も保険として継続利用

# 期待される動作(山田レジュメ PDF)

旧 (CSS-only): "頻度主義..." section の H2 が page 1 末尾、LI3 が page 2 へ
新 (hybrid):    JS が「section 全体が page 1 残量に収まらず 1 ページに収まる」と
               検出 → break-before:page を inline 注入 → section 全体が page 2 先頭から

# 出典

- chromium bug #601033 "page-break-inside not working"
- puppeteer issue #6366 "break-inside: avoid is ignored when generating PDF"
- bootstrap #15082 "page-break & break-inside in Chrome"
- CSS Fragmentation Module Level 3 (W3C)

* fix: section break correction に safety buffer / diagnostic log / default 化 (#93)

ユーザ報告で「9201d32 の hybrid でも改善せず」とのこと。考えられる原因と対策:

# 仮説 1: screen ⇔ print の layout drift

screen での body.width = 170mm 測定でも、KaTeX や margin collapse 等の微差で
section 高さに数mm〜数十mm の誤差が出る。「screen で測ると現ページに収まる
ように見えるが print では収まらない」境界ケースで break-before 注入が走らず
中割れする。

対策: page-break-script に 10% safety buffer (A4 で約 25mm) を加算。
`(height + buffer) > remaining` で「収まる」判定を厳しくして drift を吸収。

# 仮説 2: default criterion が compact で section wrap が走っていない

ExportDialog の useState 初期値が "compact" のまま。dialog を毎回開くと
リセットされるため、user が「節単位」を選び忘れる経路がある。compact では
section wrapping が走らないため hybrid correction も no-op になる。

対策: default を section に変更。Chromium の wrapper break-inside avoid
unreliability を前提に、section が「期待通りに動く挙動」の default。

# 仮説 3: main 側の HMR で executeJavaScript が反映されていない

electron-vite の main process HMR は限定的。ユーザが pnpm dev を再起動
していない可能性。

対策: script の実行結果を JSON で return し pdf.ts で console.log。
ユーザが pnpm dev のターミナルで:

  [scripta:#93] section-break: {"count":7,"broken":1,"errors":[]}

のように動作確認できる。count=0 ならば section wrap がそもそも走っていない
(criterion=compact の可能性)、broken=0 ならば drift で全 section が
「収まる」判定(buffer 不足)、errors に何か入っていれば script の例外。

# 実装

- `page-break-script.ts`:
  - `SAFETY_BUFFER = pageHeight * 0.10` (10% buffer) を section 判定に加算
  - 走査結果を `{ count, broken, errors }` JSON で return
  - 例外を catch して errors 配列へ収納 (silent failure 防止)

- `pdf.ts`:
  - `executeJavaScript` の戻り値を `console.log` 出力(ユーザ動作確認用)

- `ExportDialog.tsx`:
  - default criterion を "compact" → "section" に変更
  - 設計コメントを更新

- テスト:
  - safety buffer / 診断 JSON のテストを追加
  - default criterion 検証を section に追従

* fix: PDF 改ページ診断ログを強化 + safety buffer を 20% に拡大 (#93)

ユーザから「全然うまくいかない」報告。山田レジュメ PDF が依然 section 4 で中割れ。

原因切り分けのため:

1. safety buffer を 10% → 20% に拡大 (A4 で約 51mm)
   - KaTeX 行送り差、margin collapse、リスト padding 差等で section 高さが
     数十 mm drift する可能性。前回の 10% (25mm) では不足

2. 診断ログを process.stderr.write で目立つ形に
   - `console.log` だと埋もれる可能性があるので stderr 直接書き出し
   - 「count=0 / broken=0 / broken>0」の意味を併記して self-explanatory に

これでユーザが pnpm dev のターミナルで:

  ========== [scripta #93 PDF export diagnostics] ==========
    section-break script result: {"count":7,"broken":1,"errors":[]}
    → count=0 なら ExportDialog の改ページ判定が「節単位」になっていない
    → broken=0 なら drift で全 section が「収まる」判定
    → broken>0 なら本来 break-before が注入された
  ==========================================================

のようなログを確認できる。このログ次第で原因が確定する:
- count=0 → renderer の wrap 経路に問題 (HMR 未反映 / criterion 設定)
- broken=0 → drift 過小評価 (buffer をさらに拡大)
- broken>0 → script は機能。別経路の問題 (Chromium が inline break-before を無視等)

* fix: criterion option を撤廃し常時 section wrap に統一 (#93)

ユーザ報告でログ:

  section-break script result: {"count":0,"broken":0,"errors":[]}

count=0 → renderer 側で wrapSectionsInHtml が走っていない。原因は
ExportDialog の criterion select が「コンパクト」のままで、exportAsPdf の
`criterion === "section"` 条件分岐に弾かれていた(default を section に
変更したつもりが HMR で反映されていなかった or React state 永続)。

# 解決: criterion 概念を撤廃

criterion=compact が wrap を走らせず hybrid 補正が機能しないため、
選択肢を残すこと自体が UX バグだった。常時 wrap に統一する:

- `exportAsPdf`: `pageBreak?.smart` が true なら必ず wrapSectionsInHtml を実行
  - 旧 `criterion === "section"` の条件分岐を撤廃
  - smart=false / level=none の時のみ wrap しない
- `ExportDialog`: 「改ページ判定」select を完全削除
- `PageBreakCriterion` 型は backward compat のため残すが exportAsPdf の引数
  として渡されても無視される (`@deprecated` JSDoc 明記)

renderer 側の動作確認用に exportAsPdf 入口で console.log:

  [scripta:#93] exportAsPdf: level=h2 smart=true wrappedSections=7

を出力。DevTools console と pnpm dev ターミナル両方で「wrap が走ったか」を
直接確認できる。

# テスト

- export.test.ts: criterion=compact 渡しでも wrap される確認 (deprecated 無視)
- ExportDialog.test.tsx: criterion 関連 assertion を削除

* fix: section wrap を main の executeJavaScript 内に内蔵 (#93)

ユーザログで count=0 が継続。これは renderer の HMR が反映されておらず
wrapSectionsInHtml が走っていない状態。renderer のキャッシュ状態に
依存しない設計に切り替える。

# 変更

`buildSectionBreakScript` を「測定だけ」から「wrap + 測定 + 注入」を
すべて行う script に拡張:

1. body 直下に既存の `.pdf-section-keep` があるかチェック
   (= renderer が wrap 済みか)
2. 未 wrap で h2 が body 直下にあれば、DOM 操作で h2 セクションを
   `<section class="pdf-section-keep">` に自前 wrap する
3. `.pdf-section-keep { break-inside: avoid-page }` の CSS も style
   要素で動的 inject (renderer の CSS が無い場合の保険)
4. 既存のページ境界またぎ判定 + inline break-before 注入を実施

これで renderer の状態が古くても新しくても、main の
executeJavaScript で確実に wrap → break-before 注入が走る。

# 診断ログ強化

pdf.ts で受信 HTML の sanity check も出力:

  ========== [scripta #93 PDF export diagnostics] ==========
    received HTML: {"size":50000,"hasSectionKeep":false,"h2Count":7}
    section-break script: {"rendererWrapped":false,"h2Count":7,"count":7,"broken":1,"errors":[]}
  ==========================================================

- hasSectionKeep=false かつ rendererWrapped=false なら、main が自前 wrap
  経路で 0 → count 件にした証拠
- h2Count > 0 なのに count=0 ならば、wrap 経路に bug
- broken>0 なら break-before 注入成功

# テスト

main-side wrap ロジックの存在 / smartLevel 引数 / 動的 CSS inject の
テストを追加。

* fix: heading level を auto-detect する adaptive section wrap (#93)

ユーザログで決定的な情報判明:

  received HTML: {"size":19089,"hasSectionKeep":false,"h2Count":0}
  section-break script: {..."h2Count":0,"count":0,...}

→ そもそも HTML 内に `<h2>` が一つも存在しない。ユーザの markdown 構造は
`# title / ## section` ではなく、別 level の見出し(おそらく全部 `# h1` か、
`## title / ### section` のような構造)。

# 修正

script を heading level 固定 (h2) ではなく、document の見出し分布を自動検出する
adaptive 設計に変更:

1. body 直下の h1〜h6 出現数を測定して `headingCounts` に保存
2. smartLevel を自動選択:
   - h2 が複数あれば h2
   - h3 が複数あれば h3
   - h1 が複数あれば h1
   - h4 が複数あれば h4
   - いずれも無ければ wrap skip (smartLevelUsed = null)
3. 検出した smartLevel で section wrap → break-before 注入

pdf.ts の HTML 診断も全 heading level を出力:

  received HTML: {"size":19089,"hasSectionKeep":false,"headings":{"h1":8,"h2":0,...}}
  section-break script: {"rendererWrapped":false,"headingCounts":{...},"smartLevelUsed":1,"count":7,"broken":1,"errors":[]}

これで markdown の構造に関わらず適切な heading level でセクションをまとめる。

* fix: PDF section 改ページを table-row hack に切替 (#93 v4)

ユーザログ + PDF で確定的な原因判明:

  headings: {h1:1, h2:0, h3:7, ...}  ← セクション = h3 (markdown が #/### 構造)
  smartLevelUsed: 3, count: 7
  broken: 0   ← JS の break-before 注入は走らず

しかし PDF は 5 ページに肥大化、各ページ 1 セクション + 最後だけ 4 詰め込みの
無駄空白だらけ状態に。原因は私が動的 inject していた CSS
`.pdf-section-keep { break-inside: avoid-page }` を Chromium が
**「常に新ページから開始」と過剰解釈** していたこと
(break-after:avoid の heading との連鎖で overcaution が誘発される known quirk)。

# 解決: table-row hack

Chromium の table-row は atomic break unit として安定動作する(CSS Paged Media
community で paged.js, bootstrap, prince 等が共通して推奨)。row が現ページに
入るなら入れる、入らないなら次ページに送る。break-inside hint と違って quirk なし。

実装:
- script が既存 `<section class="pdf-section-keep">` を
  `<table class="pdf-section-keep"><tbody><tr><td>...</td></tr></tbody></table>`
  に変換
- 既存 wrap が無ければ smartLevel の見出しを直接 table 化
- 既存 CSS の break-inside:avoid-page を `auto \!important` で override して
  overcaution を完全に殺す
- table > tbody > tr に `break-inside: avoid` を当てて row atomicity を保証
- table 装飾 CSS (width 100%, border 0, padding 0) で見た目を block と同じに保つ

# 期待される動作(山田レジュメ PDF)

旧 (v3): 5 pages, 各ページ 1 セクション + 最後 4 詰め込み(overcaution)
新 (v4): ~2 pages, h1+meta+sec1-4 を page 1、sec5-7 を page 2(自然な配置)

# 出典

- CSS Paged Media community で table-row 方式は古くから定番
- bootstrap #15082, jsreport docs 等で workaround として推奨

* fix: wrapper を全廃し見出しに直接 inline break-before を注入 (#93 v5)

# 経緯

v1〜v4 はすべて wrapper (section / table) に CSS break-inside hint を当てる
方式だったが、Chromium はどの wrapper 形式でも「各 wrapper を独立した新ページに
送る」overcaution を起こす quirk があり、結果は無駄空白だらけ(5+ ページに肥大化)
だった。

# 設計 (v5)

wrapper 概念を完全に捨てる:

1. script は既存の `.pdf-section-keep` wrapper を **unwrap** する (renderer の
   stale code が wrap していても overcaution 源を完全に排除)
2. body 直下の見出し分布を自動検出して smart level を決定
3. 見出し element に直接 `style.breakBefore = 'page'` を inline 注入
   → Chromium の inline forced break は wrapper hint と違って quirk なく確実に動作

# safety buffer

15% (≈38mm @ A4) は経験則上のスイートスポット:
- 山田レジュメ (h1+meta+sec1-3 ≈ 215mm) で sec4 (30mm) が remaining 42mm に
  対して 30+38=68 > 42 → force-break する
- 一方 sec3 (60mm) は remaining 102mm に対して 60+38=98 <= 102 → 残す
- 過去の試行 (10% / 20% / 25%) は片方しか満たせなかった

# 期待される動作(山田レジュメ)

- v4: 5 ページ、各セクションが独立ページ + 空白だらけ
- v5: ~2 ページ、h1+meta+sec1-3 を page 1、sec4-7 を page 2

# renderer 側の変更

- `.pdf-section-keep { display: block }` の CSS を撤去 (wrapper を使わない)
- 旧 @media print の `.pdf-section-keep { break-inside: avoid-page }` も撤去
- exportAsPdf から wrapSectionsInHtml の呼び出しを撤去 (script 側で処理)

# テスト

v5 仕様 (unwrap / inline break-before / 15% buffer / 診断 JSON) に追従。

* fix: heights を inter-top 距離で測りマージン折り畳み drift を解消 (#93 v5.1)

ユーザ報告と PDF から「sec4 が中割れ (LI3 だけ page 2)」が判明。
診断ログ:

  sectionsBroken: 1  ← sec5 は force-break されたが sec4 は判定漏れ

# 原因

v5 では `heights[i] = bbox.bottom - bbox.top` で element box 高さのみを
測っていた。CSS の上下マージン(h3 の上 0.8em 下 0.2em 等、各 block の
margin-top/margin-bottom)が **完全に抜け落ち**、virtualY の累積が
実 print layout より 30〜50mm 短くなっていた。

これにより script は「sec4 は page 1 に余裕で収まる」と誤判定、
break-before を注入せず、実 print では LI3 が overflow して page 2 に
追いやられる中割れ状態に。

# 修正

旧 v2 で使っていた正しい方式に戻す:

  heights[i] = (次要素の top) - (この要素の top)

これで margin collapse 後の **実際のブロック間距離** が含まれる。次要素が
無い場合は body.bottom を fallback。

# 期待される動作

sec4 (35mm) + buffer (38mm) = 73mm が、より正確な remaining 値 (今度は
< 73mm になるはず) を超えて force-break 注入される。
sec5 は元から正しく force-break されていた。

PDF: page 1 = h1+meta+sec1-3、page 2 = sec4-7。中割れ無し。

* fix: safety buffer を 15% → 10% に詰めて空白を削減 (#93 v5.2)

v5.1 で margin drift を解消したことで script の measurement 精度が向上した。
ユーザ確認 (山田レジュメ PDF) で v5.1 では sec7 が page 3 に単独配置されて
空白が多かったので、buffer を 15% → 10% に詰める方向に追い込む。

- 詰める方向: 不要な force-break で page 3 に追いやる無駄を削減
- 中割れリスク: margin 込みで heights を測れるようになったので低い
- トレードオフは「page 2 に sec7 まで詰まる」を取りに行く側

ユーザの「つめてみよう」リクエストに対応 (#93 v5.2)。

* fix: safety buffer をさらに 10% → 5% へ詰める (#93 v5.3)

v5.2 (10%) でも山田レジュメで sec7 が境界ギリギリで force-break され
page 3 が空白に。margin drift 修正 (v5.1) で measurement は十分正確に
なっているので、buffer をさらに 5% (≈13mm @ A4) まで詰める。

5% は font hinting / subpixel rendering 程度の最小限の drift 吸収を担う設定。
sec4 のような確実に overflow するセクションは「sectionH + 13mm > remaining」
で検出できるはず。

* feat: criterion option 復活 + dialog 並べ替え + zoom 補正 (#93 v5.4)

ユーザ要望 3 点に対応:

# 1. 改ページ判定 option を復活 (default = 現在動作の section)

- ExportDialog に「改ページ判定」 select 復活
- option:
  - 節単位 (default): セクション全体を keep-together (中割れ防止)
  - コンパクト: heading + 直後ブロックのみ keep (中割れ許容、詰めた配置)
- renderer は `<meta name="scripta-pdf-criterion" content="section|compact">`
  を HTML head に埋め込み
- main 側 script が meta tag を読んで分岐:
  - section: 見出し + 次の同位以下見出しまでの全コンテンツを needed height とする
  - compact: 見出し + 直後の最初の非見出しブロックのみを needed height とする

# 2. Export dialog の section 順序を PDF が上に

- ExportDialog の sections 配列を [pdf, html, prompt] に並べ替え
- activeSection の default も "pdf" に
- 関連 test を「初期状態 = PDF」に追従更新

# 3. zoom 補正バグを修正

ultrathink 解析で発見: body.style.zoom \!= 1 の時、pageHeight 測定が
物理ページサイズと一致しない bug があった。

問題:
- ruler は body 内に置くので body.style.zoom が適用される
- 旧: ruler.style.height = '257mm' → rendered 値が zoom 倍されて返る
- zoom=0.5 では pageHeight = 485px (= 物理 128.5mm = 半ページ分) と誤計算
- section 高さは同じく zoomed pixel → ratio が物理的に正しくない

修正:
- ruler height を (257 / zoom) mm に補正
- rendered 値が常に物理 257mm 相当の viewport px (≈971) になる
- どの zoom level でも section/pageHeight ratio が物理と一致

# テスト

- page-break-script.test.ts: zoom 補正と criterion 分岐の assertion 追加
- ExportDialog.test.tsx: PDF default / criterion=section default に追従

* refactor: /simplify — dead code 撤去 + altitude / efficiency 改善 (#93)

4 cleanup agents の指摘を dedup して適用。behavior preserving。

# A. dead code 撤去

- `wrapSectionsInHtml` (renderer 側 wrap 関数) を削除。v5 で renderer 側 wrap
  を廃止して main 側 script に統合した時点で production から呼ばれなくなっていた。
  関連 test (6 ケース) と script の `unwrap` 防御 block も併せて削除。
- `src/types/pdf.ts` から未使用の `PdfPageBreakLevel` / `PdfPageBreakOptions`
  を削除。`PdfPageBreakCriterion` のみが renderer で利用されている。

# B. altitude: smart-level を user 選択値で渡す

- 旧: dialog で level を選んでも main 側 script は無視して body の見出し分布で
  auto-detect していた (CSS は force-break 用に level を反映、JS は別経路)。
- 新: `<meta name="scripta-pdf-smart-level" content="1|2|3">` を renderer が
  emit、script が読み取る。指定 level に該当見出しが 2 件以上ある時はそれを
  採用、無い時のみ heading 分布で auto-detect (例: 「h2 まで」選択だが body は
  h3 のみ → h3 に fallback)。

# C. efficiency

- pdf.ts: 6 個の `(html.match(/<hN\\b/g) ?? []).length` 連続評価を削除。同じ
  情報は script の返却 JSON (`headingCounts`) に含まれており完全重複。
- page-break-script.ts: 6 個の `querySelectorAll('body > hN')` を 1-pass の
  children 走査に置換。100 子要素で 600 ops → 100 ops。
- pdf.ts: 診断 stderr 出力を `SCRIPTA_PDF_DEBUG` env で gate。production の
  hot path から log を排除。

# D. 仕様文書化のノイズ削減

- pdf.ts / page-break-script.ts の v1〜v5.4 経緯コメント (~30 行) を 6 行の
  本質的説明に圧縮。git log が settled history の正準。
- 「(#93 v5.x)」マーカーをコメント / option label / test 名から削除。
- export.test.ts の "criterion option を渡しても無視される (deprecated)" は
  stale (criterion は v5.4 で active) なので、新しい test「smart + level +
  criterion を meta tag 経由で伝える」に置き換え。

# 検証

format / lint / typecheck / typecheck:e2e / test (1838 passed) / build /
legacy-residue 全 green。

* fix: smart 改ページ OFF で script 実行 + CSS force-break の virtualY 反映 (#93)

# Bug 1: smart 改ページ OFF でも見出し改ページが入る

`pageBreak?.smart && pageBreak.level \!== "none"` でない場合、renderer は
meta tag を emit しない設計だった。しかし script 側は meta 不在時に heading
分布で auto-detect する fallback を持っていたため、「見出しで改ページ OFF」
や `smartPageBreak: false` の設定でも勝手に h2/h3 を検出して inline
`break-before: page` を注入してしまうケースがあった。

修正: script の冒頭で `smart-level` meta の有無をチェック、無ければ即 return。
「meta 不在 = smart 改ページ無効」の signal を明確化。

# Bug 2: CSS forced break (h1) が virtualY simulation に反映されていない

renderer の `buildForceBreakSelectors` は smart=true + level=h2 で
`h1 { break-before: page }` を CSS で emit するが、script の virtualY は
自然レイアウト累積で動いていたため、CSS forced break が起きる位置を考慮できず、
後続 smart-level (h2/h3) の現ページ残量判定がページ境界からずれていた。

例: doc 中盤に複数 h1 がある場合、CSS では各 h1 で改ページするが、script は
それを認識せず後ろの h2 を「実際にはページ末尾なのに余裕がある」と誤判定し、
余計な空白や中割れ防止漏れを起こし得る。

修正:
- renderer: `<meta name="scripta-pdf-force-level" content="${level-1}">` を追加。
  level=h2 なら content="1" (h1 で CSS force-break)、level=h3 なら "2" (h1,h2)。
- script: meta を読み、ループ中に該当レベル (h1..h{forceLevel}) の見出しに
  遭遇したら virtualY を次ページ頭にジャンプ。HR pagebreak と同等の処理を
  CSS forced break にも適用する形。

# テスト

- script: smart-level meta 不在で即 return、force-level meta の読み取りと
  virtualY jump ロジックの存在を assert
- export: smart=false / level=none で全 meta が emit されないこと、
  level=h2/h3 でそれぞれ正しい force-level が出ること

verify chain 全 green (1842 passed)。

* fix: break-inside avoid simulation / 浅い方向 fallback / code skip / e2e 書き直し (#93)

# Bug 1 (High): break-inside: avoid を simulation していない

CSS で `p, pre, blockquote, table, img, .mermaid-diagram` に `break-inside: avoid`
が当たっており、実 print ではページ末尾に収まらないこれらは Chromium が次ページに
送る。しかし script の virtualY は線形累積のみで、この push を model していなかった。
結果として後続の smart-level 判定が「自然 layout の高さ」基準で remaining を見積もり、
実 print の paginated layout と乖離して必要な force-break を見逃す可能性があった。

修正: ループ内で各要素について `isAvoidBreakInside(item)` を判定し、true かつ
現ページ残量に収まらない場合は virtualY を次ページ頭にジャンプさせてから h を加算。
HR pagebreak / force-level 見出し / smart-level 見出しと同じ jump 機構を avoid-break
要素にも適用する。

# Bug 2 (Medium): smart level fallback が requested より深いレベルに行く

ユーザが「h2まで」を選んだのに doc 内 h2 が少ないと h3 に fallback していた。
UI 表示と script の決定が乖離してユーザの選択を破る contract 違反。

修正: fallback は requested - 1 から 1 まで降順だけ走査して shallower 方向にのみ
許す。requested が指定されている場合は deeper への fallback は行わない。
requested が無効値 (meta tag emit ロジックに乗らないパスでの保険) のときのみ無制限
auto-detect。

# Bug 3 (Medium): code block 内の <\!-- pagebreak --> も置換される

`preprocessPageBreakMarkers` が markdown parse 前に regex で置換していたため、
fenced/inline code 内のリテラル `<\!-- pagebreak -->` まで変換対象になり、機能を
ドキュメントする目的の code sample 等を壊していた。

修正: `findCodeRanges` (fenced ``` /~~~ と inline `...`) + `isInsideAnyRange` を
追加して、code 範囲内の marker は置換せず残す。

# Bug 4 (Medium / Test gap): e2e が古い section wrap 前提

`e2e/electron/pdf-pagebreak.electron.spec.ts` が v3 の section wrap 前提のままで、
branch の本筋である「renderer が meta を出し → main script が見出しに inline
break-before を注入」経路を検証していなかった。

修正: 4 ケースに書き直し:
- meta 3 種類を持つ HTML が実 PDF として生成される
- 多 section 文書で script が break-before 注入し PDF が 2 ページ以上に分かれる
  (PDF 内の `/Type /Page` 出現数で検証)
- meta tag を持たない HTML では script が no-op (1 ページのまま)
- `hr.pdf-pagebreak` 著者マーカーで複数ページに分かれる

# 検証

format / lint / typecheck / typecheck:e2e / test (1845 passed) / build /
legacy-residue 全 green。

* fix: code 検出共有化 / forceLevel clamp / LI 単位の avoid sim / e2e 強化 (#93)

# Bug 1: code 範囲検出が CommonMark 不完全 + indented を見逃す

`preprocessPageBreakMarkers` の自前 `findCodeRanges` は fenced (\1 は exact-length
照合)・inline しか見ず、4 スペース indented code block / raw `<pre>`/`<code>` 内の
リテラル `<\!-- pagebreak -->` を変換してしまっていた。

修正: `markdown-to-html.ts` の `collectRawCodeRanges` (fenced / indented / HTML
pre+code / inline すべて handle) を export して preprocessPageBreakMarkers でも
共有利用する。KaTeX preprocess と同じ検出ロジックに統一されるので長期的な乖離も
排除できる。

# Bug 2: fallback 後の forceLevel が smart level 以上のまま

例: pageBreakLevel=h3 で h3 が足りず h2 に fallback → smartLevel=2 だが renderer
由来の forceLevel=2 のまま。loop で h2 が force-break として処理されて continue され、
smart-suppression に入らず fallback の意味が消える。

修正: `if (forceLevel >= smartLevel) forceLevel = smartLevel - 1;` で常に
smartLevel より浅い側に clamp。

# Bug 3: UL/OL の LI を avoid-break simulation が見ていない

通常の markdown リストは body 直下に UL/OL が来て中に LI が入る。CSS で li に
break-inside: avoid が当たっているのに、JS の virtualY 計算は body 直下要素しか
見ず UL/OL 全体の自然高さで累積していた。実 print では LI 単位で次ページに押し出され
得るが simulation でそれを反映しないため、リストがページ末尾に絡む場合に後続見出しの
位置推定がずれる可能性があった。

修正:
- body 直下を走査時に UL/OL を子 LI に展開して `children` 配列に並べる
- `isAvoidBreakInside` に 'LI' を追加 (LI も avoid-break 対象)
- heights は inter-top 距離で測るので、混在しても自動で正しく加算される
  (UL/OL 自身は children に入らず、その position は前後要素の top 差で内包される)

# Bug 4: e2e の page-count proxy が弱い + SCRIPTA_PDF_DEBUG で診断 capture

旧 e2e は「複数 section → 複数ページ」を script 注入の証拠としていたが、コンテンツ
量だけでも複数ページになるため、script が実際に動いたかの直接証明ではなかった。

修正:
- multi-page proxy test を削除
- `hr.pdf-pagebreak` で deterministic な 3 ページ test を残す (純 CSS 経路)
- 新規 test: `SCRIPTA_PDF_DEBUG=1` で launch し stderr 経由で診断 JSON を直接
  capture、meta 不在の HTML で script が `smartLevelUsed=null, sectionsTotal=0,
  sectionsBroken=0` を返すことを assert (script の result そのものを見るので
  page count proxy 不要)。

# 検証

format / lint (warning 解消済) / typecheck / typecheck:e2e / test (1849 passed) /
build / legacy-residue 全 green。

* fix: CommonMark fenced 検出を line-scan 化 / e2e の diag JSON regex を nested 対応 (#93)

# Bug 1: collectRawCodeRanges が CommonMark の閉じフェンス長を honor していない

旧実装は ``\${containerPrefix}[ \\t]{0,3}(\`{3,}|~{3,})...\\1[ \\t]*$`` の `\1`
で閉じフェンスを exactly same-length に限定していた。CommonMark spec では
「閉じフェンスは開きと**同じ文字**で**開き以上の長さ**」が許容されるため、
例えば opening 4 backticks + closing 5 backticks の正当な fenced block 内の
リテラル `<\!-- pagebreak -->` を `preprocessPageBreakMarkers` が変換してしまう。

修正:
- `collectRawCodeRanges` の fenced 部分を line-by-line scan に書き換え。
- 開き行で fence char (` or ~) と length を捕捉、閉じ行は `{fenceChar}{fenceLen,}`
  で 「同じ文字 & 同長以上」を判定。
- 閉じが見つからない場合は CommonMark 通り doc 末尾までを code と見なす。
- container prefix (blockquote / list 内 fenced) は引き続きサポート。

これで KaTeX preprocess / preprocessPageBreakMarkers の両方が fence 長を正しく
扱うようになり、共有元 (`markdown-to-html.ts`) を直すことで両経路が同時に修正される。

# Bug 2: e2e の診断 JSON 抽出 regex が nested object で壊れる

旧 regex `/\[scripta:#93\][^{]*({[^}]+})/` は `{[^}]+}` が最初の `}` で切れて、
script の戻り値 (例: `{"headingCounts":{"h1":1,...},...}`) のように内側 object
を含む JSON では incomplete な切り出しを `JSON.parse` に渡してしまっていた。
Electron が起動できる環境では確実に test 失敗する状態。

修正:
- 末尾の ` (html N bytes)` を anchor に使い、greedy `\{.*\}` で最後の `}` まで
  拾う形に: `/\[scripta:#93\] break-before script: (\{.*\}) \(html \d+ bytes\)/`
- 単行 stderr 行に対する match なので `.*` は問題なし。

# テスト

- 「閉じが開きより長い fenced (CommonMark)」「~~~ fence の長い閉じ」の 2 ケースを
  preprocessPageBreakMarkers に追加。両方とも以前は内部 marker が変換されていた。

verify chain 全 green (1851 passed)。

* fix: collectRawCodeRanges を CRLF 対応 + preprocessDisplayMath を共有経路化 (#93)

# Bug 1 (Medium): CRLF fenced code が「未閉じ」と誤判定される

`collectRawCodeRanges` は `text.split('\n')` で行分割するため、CRLF 入力 (\r\n)
では各行末に \r が残る。close fence regex `[ \t]*$` は \r を許容しないため、
CRLF で書かれた正当な fenced code が未閉じと判定され、結果として doc 末尾まで
すべて code 扱いになる。その結果 `preprocessPageBreakMarkers` が外側の `<\!--
pagebreak -->` を `<hr>` に変換しないケースが発生。

修正: close fence regex の末尾を `[ \t]*\r?$` に変更して \r を許容。
open fence は `[^\n]*$` で \r を自然に含むので変更不要。

# Bug 2 (Low/Medium): preprocessDisplayMath の fence 判定が旧 \1 ベースで残存

`preprocessDisplayMath` は code 範囲を skip するため独自に fenced regex
(``\\1`` で同長閉じのみ照合) を持っていた。今回直した `collectRawCodeRanges`
と判定が乖離していて、opening より長い closing fence や CRLF など同じ
edge case を独立に踏む。

修正: local の `codeRanges` 計算を削除し、`collectRawCodeRanges` + `isInsideRanges`
を再利用。fenced + indented + raw HTML pre/code + inline すべての code 範囲で
display math を skip するようになり、共有元を直すと両経路が同時に救われる
正しい関係になった。

# テスト

`preprocessPageBreakMarkers` の CRLF fenced code skip ケースを 1 件追加。
旧コードでは未閉じ判定で doc 末尾まで全 skip され、外側 marker が変換されない
状態だった。

verify chain 全 green (1852 passed)。

* docs: 古い「CSS-only / DOM 測定完全廃止」表現を hybrid 設計に追従 (#93)

実装は実際には main 側 `executeJavaScript(buildSectionBreakScript())` で実
layout を測定し inline `break-before: page` を注入する hybrid 設計だが、
コードコメントとテスト名に v5 前後の "CSS-only redesign" / "JS DOM 測定は完全廃止"
等の表現が残っていた。将来の保守時に「JS 測定経路は無い」と誤読されないよう
現行設計に合わせて書き直す。

- src/lib/export.ts:
  - `buildForceBreakSelectors` JSDoc の "(#93 CSS-only redesign)" → "(#93)"。
    本体の「smart level 自体は section wrap で...」記述を「main 側 script の
    inline break-before 注入」に更新。
  - `exportAsPdf` 末尾のブロックコメント「CSS Paged Media に完全委譲」を、
    実際の meta tag + main script の hybrid 経路に書き直し。

- src/lib/export.test.ts:
  - "buildHtmlDocument page break (CSS-only, #93)" → "buildHtmlDocument page break CSS (#93)"
  - "もはや [data-no-break] CSS は出力しない(CSS-only への移行で廃止)" →
    "[data-no-break] CSS は出力しない (script の inline break-before 注入に移行済み)"
  - "exportAsPdf — CSS-only & section wrapping (#93)" → "exportAsPdf — meta tag + page break CSS (#93)"
  - "does NOT inject inline <script> into HTML (JS DOM 測定は完全廃止)" →
    "renderer は HTML に inline <script> を埋め込まない (DOM 測定は main 側 executeJavaScript)"

実コード挙動の変更なし。grep "CSS-only|JS DOM 測定|完全廃止" の hit ゼロ確認済。

* fix: smart-level fallback の deeper 方向を復活 (#93 中割れ regression 修正)

# 症状

レビュー指摘 (smart level を shallow-only fallback に制限) の対応後、ユーザの
山田レジュメで sec4「頻度主義...」が中割れする regression。

# 原因

ユーザのドキュメント構造: h1=タイトル 1 個 + h3=section 7 個 (h2 は 0)。
shallow-only fallback では:
  - requested=2 (h2 default), h2=0 → match なし
  - shallower fallback: h1=1 (< 2) → 不足
  - → smartLevel=null → script 早期 return → break-before 注入なし
  - → Chromium 自然 layout で sec4 last LI が次ページに押し出されて中割れ

# 修正

shallow-only 制約を撤回し、heading 分布から「複数回現れる最も浅いレベル」を
auto-detect する旧挙動に戻した。ユーザの「h2 まで」選択は該当見出しがあれば
honor するが、ドキュメント構造が合わなければ近いレベルへ自動補正する。

# レビュー指摘との関係

レビュアーは「h2 を選んだのに勝手に h3 を改ページ対象にするのは UI 表示と
乖離する (契約違反)」と指摘。実装としては妥当だが、結果として h1+h3 構造
(典型的な markdown スタイル) で smartLevel=null = no-op = 中割れ放置という
別の UX 違反が出た。実害ベースでこちらを優先。

将来 dialog label に「該当見出しが無い場合は近いレベルへ自動補正します」と
明記すればレビューワーの懸念も解消できるが、それは別 PR で。

# テスト

shallow-only assertion を「auto-detect (h2 > h3 > h1 > h4 priority)」検証に
書き換え。verify chain 全 green (1852 passed)。

* refactor: /simplify 2nd pass — auto-detect を renderer に集約 + dead test 撤去 (#93)

4 cleanup agents の指摘を dedup して適用。net -57 行、behavior-preserving。

# A. Altitude: auto-detect policy を script から renderer に上げる

(レビュー agent #1+#2 の合わせ技。最高 ROI)

旧設計: main 側 page-break-script の中で
  - heading 分布の auto-detect
  - shallow / deeper fallback
  - forceLevel >= smartLevel の clamp
を実行していた。これは policy が JS 文字列に埋まる altitude ミスマッチで、
unit test 困難 + renderer の `forceLevel = level - 1` 導出と独立に動いて
clamp で繕う構造になっていた。

新設計:
- renderer に `resolveSmartLevel(bodyHtml, requested)` を新設。pure TS で
  unit test 可能。auto-detect の優先順 (h2 > h3 > h1 > h4) は本関数に集約。
- renderer が解決後の smartLevel (1〜4) を `<meta name="scripta-pdf-smart-level">`
  に emit。
- script は meta を読み取って使うだけ。force-level meta は廃止し、script 内で
  `forceLevel = smartLevel - 1` として導出。clamp も削除。
- 結果: meta tag transport が 3 個 → 2 個、script 内のロジック分岐が消えて
  ~80 行縮小、headingCounts 中間状態も消えた。

# B. Simplification: dead-archeology test を削除

(#1)
removed: `.pdf-section-keep` / `[data-no-break]` が出力されないことを assert
する 2 ケース。これらは v3/v4 で撤去した中間設計の残骸で、現実装には対応
コードが無いため negative-assertion test 自体が「過去構成への退行ガード」
として無価値。

# C. Simplification: brittle source-pattern test を behavior-contract のみに削減

(#3)
page-break-script.test.ts は実装詳細を文字列マッチで assert する 15 ケースが
あった (`var bodyChildren = ...`, `hc.h2 >= 2`, etc.)。cosmetic rename で
壊れるだけで behavior を検証していない。

新規 6 ケースに縮減:
1. IIFE 形式で返す (contract)
2. smart-level / criterion の meta tag 名 (renderer との契約)
3. meta 不在で no-op (degrade signal)
4. 見出しに inline `breakBefore = 'page'` を注入する経路がある
5. 診断 JSON の fields (smartLevelUsed / criterion / sectionsTotal /
   sectionsBroken / errors)
6. try/finally で body style restore

実 behavior は e2e (stderr capture) でカバー済み。

# D. Simplification: reversal-history コメントを圧縮

(#4)
shallow-only vs bidirectional fallback の経緯を解説する 7 行コメントを削除
(`resolveSmartLevel` の JSDoc に「typical 構造への補正」として 1 文に集約)。

# E. Simplification: PdfPageBreakCriterion を inline + types/pdf.ts 削除

(#2)
`src/types/pdf.ts` は 1 行の type 1 個だけになっていた。`src/lib/export.ts`
が同型を alias 再 export するだけで、IPC 境界もまたがない (preload は import
していない)。直接 inline して file を削除。

# Skip した指摘

- CodeFenceTracker と collectRawCodeRanges の重複 (slide-parser 周辺、scope 外)
- collectRawCodeRanges のメモ化 (markdown が mutate されるので blanket memo
  不可、hot path でない)
- O(N²) section-end scan (現実サイズで無視可、defer)
- 3 transport (CSS + meta + hr) 統合 (中規模、別 PR)
- Dialog 4 knobs 整理 (UX redesign、scope 外)

# 検証

format / lint / typecheck / typecheck:e2e / test (1845 passed) / build /
legacy-residue 全 green。

* test(e2e): export.spec.ts を PDF default に追従 + PDF タブ strict-mode 修正 (#93)

# 失敗ケース 1: HTML default 前提の test
"メニューイベントでエクスポートダイアログが開いて HTML 出力できる" は HTML
セクションが default active な前提で assertion していた。#93 v5.4 で PDF
を default に変更したため、HTML セクションは初期表示されず assert が timeout。

修正: HTML タブを明示的にクリックしてから「HTMLとしてエクスポート」を assert。

# 失敗ケース 2-3: PDF button strict-mode violation
`getByRole("button", { name: "PDF" })` は PDF タブ button (label "PDF") と
「PDFとしてエクスポート」 submit button (label に "PDF" を含む) の両方に
match。dialog open 時 PDF が default active なので、submit button も
visible になっていて strict mode で衝突した。

修正: `{ name: "PDF", exact: true }` で disambiguate。「セクション切り替え
時にダイアログサイズが変動しない」 test の "PDF" / "プロンプト" / "HTML"
の iteration にも同じ修正 (HTML が active になった後の "HTML" iteration、
プロンプトが active になった後の "プロンプト" iteration も同じ衝突を起こす)。
This was referenced Jul 12, 2026
exportAsHtml: ローカル画像を data URI で埋め込む (外部ブラウザ portability) #314
Closed
feat: スライドプレビューと PDF エクスポートでローカル画像を解決 #315
Merged
feat: スライドプレビューを fit-to-frame スケール描画に変更 (Fable #3) #316
Merged
feat: スライド PDF エクスポート機能を追加 #329
Merged
ymnao added a commit that referenced this pull request Jul 14, 2026
@ymnao @claude
feat: スライドプレビュー/発表モードで mermaid ブロックを反映 (#333)
dbdc6cd
* feat: スライドプレビュー/発表モードで mermaid ブロックを反映

- renderSlideHtmlWithMermaid: preprocessMermaidBlocks 経由で
  mermaid fenced code を SVG に差し替える async 版を追加
- useSlideHtml: sync 版 (mermaid 未変換) を即時返し、
  async 完了後に mermaid 込みで上書き (key 一致時のみ採用)
- useSlideHtmls: 発表モード用の複数スライド並列 async 版を追加
- SlideShowOverlay を useSlideHtmls 経由に差し替え
- theme (light/dark) を useThemeStore から購読し renderMermaid に伝搬

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

* refactor: スライド mermaid preview の重複解消と altitude 整理

/simplify 4 agent 並列レビューの findings を反映:

- 汎用フック `useAsyncDerived(deps, initial, asyncFn)` を追加し、
  `useSlideHtml` / `useSlideHtmls` の「sync 即返 → async 上書き → stale
  guard」パターン重複を解消 (Alt #1, Simp #2, Reuse #2)
- `renderSlideHtml` / `renderSlideHtmlWithMermaid` を `lib/slide-render.ts`
  に切り出し、コンポーネント→lib/export への依存 (層反転) を解消 (Alt #2)
- `preprocessMermaidBlocks` 等の mermaid 前処理を独立モジュール
  `lib/mermaid-preprocess.ts` に分離し、slide-render ↔ export の
  循環参照を回避。export.ts では re-export で下位互換を維持
- mermaid fence を含まない markdown は preprocess を skip し、
  1 回だけの `markdownToHtml` に短縮 (Eff #2, #3, #4)
- `exportSlidesAsPdf` を `renderSlideHtmlWithMermaid` 経由に統合し、
  「末尾 --- 除去 → 空スライド convention → mermaid → markdown → image
  resolve」の順序契約を preview / 発表 / PDF export で一致させる
  (Reuse #1, WYSIWYG lock)
- `requestKey` の full-markdown 文字列連結を identity 比較に置換
  (Simp #1, Eff #1)

Defer: 長寿命 closure/debounce (実測負荷なし), sync 版公開撤去 (破壊的),
docstring スコープ (意図的な使い方説明)

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

* fix: /code-review 指摘の flash / silent 失敗 / fence 判定二重化を解消

- useAsyncDerived: async reject 時に console.error を出力
  (silent 化禁止、mermaid-preprocess.ts #106 と同ポリシー)
- useAsyncDerived: deps 変更時も直前の async 成功値を保持し続ける
  (theme 切替 / rapid typing で mermaid が fenced code へ flash する UX
   regression を解消。初回描画のみ initial にフォールバック)
- slide-render.ts: containsMermaidFence を削除
  ・findMermaidCodeBlocks (case-sensitive) との /i 不整合を解消
  ・fence 判定 regex の 3 番目のコピーを廃棄
  ・preprocessMermaidBlocks が既に空マッチで no-op 返却するため fast
    path は不要 (line-scan 1 回のみで単一経路)

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

* docs: useSlideHtmls の slides identity 契約を JSDoc に明記

/code-review F5 (PLAUSIBLE): useAsyncDerived の keepPrevious 化に伴い、

呼び出し側が毎 render 新規配列を渡すと effect 再発火 → setState → 再 render

の loop になる契約を明示。現状 SlideShowOverlay は useMemo で memoize 済み

のため safe (test 済み)。

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

* test: /codex-review qa-fixture 指摘の new hook / mermaid fence 経路をカバー

- useAsyncDerived.test.tsx: 初回 initial / async resolve 上書き /

  keepPrevious / stale resolve 破棄 / reject 時の keepPrevious + console.error

- slide-render.test.ts: mermaid fence を含む markdown が SVG 化されて

  mermaid-diagram wrapper に格納されることを検証 (light/dark theme 分離、

  末尾 --- 除去も含む)

REPORT-ONLY: useSlideHtml/useSlideHtmls の component 層統合、options

passthrough、exportSlidesAsPdf 経路の詳細 → useAsyncDerived +

renderSlideHtmlWithMermaid の単体テストで実質カバー、上位統合は既存

SlideStage/SlideShowOverlay/export.test で担保

REFUTED: mermaid-preprocess.ts のラスタライズ分岐 → 既存 export.test.ts

が re-export 経由で同ロジックを検証済み (2419→2428 passed)

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

* test: codex-review qa-fixture 残 UNRESOLVED 6 件を全対応

- U1: slide-render.test.ts の light/dark 伝搬 assertion を initialize spy

  への theme=default/dark 呼び出し検証に強化

- U4: useAsyncDerived.test.tsx に unmount 後 resolve/reject の cancelled

  分岐 (state 更新なし / console.error なし) を追加

- U6: slide-render.test.ts に mermaid render 失敗時の元 fenced code 保持

  経路を追加 (silent 失敗させない挙動)

- U2/U3: SlideStage.hooks.test.tsx を新設し、useSlideHtml (mermaid sync→

  async 差替 / activeTabPath 再解決 / theme 変更) と useSlideHtmls (空配列 /

  複数入力順維持 / identity 安定 positive path) を hook integration で検証

- U5: export.test.ts exportSlidesAsPdf に PNG data URL 埋込 / filePath

  基準の相対画像解決 / 空スライド保持の回帰テストを追加

- options.mermaidOptions passthrough も slide-render.test.ts で検証追加

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

---------

Co-authored-by: Claude Opus 4.7 <[email protected]>
This was referenced Jul 20, 2026
refactor: MermaidEditorDialog / export でも shouldSkipMermaidInitRetry gate を尊重する #386
Closed
docs: migration-plan と CLAUDE.md アーキ図を実態に同期 #388
Merged
This was referenced Oct 11, 2026
refactor: watcher の canonical → input 変換を canonicalToInputPath に一本化する #629
Merged
fix: スライド表示の左ペインにエディタの本文が出ない不具合を直す #662
Merged
This was referenced Oct 25, 2026
fix: autosave が、削除・rename したファイルの古いパスへ書き込まないようにする #714
Merged
fix: ウィンドウを閉じるとき、main が close 要求を送らないので未保存の編集が消える #727
Open
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.

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.