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 0a — Electron + Vite + React の雛形を構築 by ymnao · Pull Request #2 · ymnao/scripta

Conversation

@ymnao

@ymnao ymnao commented Apr 28, 2026

Copy link
Copy Markdown
Owner

概要

Stage 0 を「Stage 0a: Electron セットアップ」と「Stage 0b: 旧フロントエンド流用 + Tauri 差し替え」に分割し、本 PR で 0a を実施する。Electron + electron-vite + React 19 + Tailwind v4 + Biome + Vitest の雛形を構築し、contextIsolation: true / nodeIntegration: false / sandbox: true で Electron が起動することを確認した。

関連 Issue

なし

移行 Stage

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

変更内容

  • package.json: electron / electron-vite / electron-builder / @electron-toolkit / react / vite / tailwind / biome / vitest を追加(Stage 0b で必要となる CodeMirror 系などは別 PR で追加予定)
  • electron.vite.config.ts: main / preload / renderer の 3 バンドル構成。preload は sandbox: true 制約のため CJS 出力 (format: 'cjs', entryFileNames: '[name].js') を強制
  • electron/main/index.ts: BrowserWindow を contextIsolation: true / nodeIntegration: false / sandbox: true / titleBarStyle: 'hiddenInset' で生成。shell.openExternal で外部リンク経路を確保
  • electron/preload/index.ts: contextBridge 経由で window.electron(@electron-toolkit/preload)と window.api(雛形)を expose
  • src/main.tsx / src/App.tsx / src/index.css: 動作確認用の最小 React アプリ
  • src/types/window.d.ts: window.api の型を Stage 0a 範囲で定義
  • tsconfig.{json,web,node}.json / biome.json / index.html: 旧 scripta の構成を踏襲

動作確認

  • pnpm typecheck(main / preload / renderer の 2 プロジェクト)が通る
  • pnpm lint が通る
  • pnpm build で out/main, out/preload, out/renderer が生成される
  • pnpm dev で Electron ウィンドウが起動し、preload 経由で window.api.getVersion() の値が描画される

スクリーンショット

(省略)

メモ

  • Stage 0b で旧 scripta の src/components, src/stores, src/hooks, src/types, src/lib(commands.ts 以外), src/styles を流用し、commands.ts をモック実装に差し替える
  • Stage 0b では Tauri 直接依存の 7 ファイル(store.ts, export.ts, images.ts, ConflictWindow.tsx, useGitSync.ts, useUpdateCheck.ts, useFileWatcher.ts 等)も window.api 経由のモックに差し替える

🤖 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 2 commits April 29, 2026 04:32
@ymnao @claude
chore: Stage 0a — Electron + Vite + React の雛形を構築
ff4ba40
- electron-vite で main / preload / renderer の 3 バンドル構成
- contextIsolation: true / nodeIntegration: false / sandbox: true で起動
- sandbox: true 制約のため preload は CJS 出力
- React 19 + Tailwind v4 + Biome + Vitest の最小セットアップ
- pnpm dev / build / typecheck / lint が通ることを確認

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
@ymnao @claude
refactor: /simplify レビュー指摘を反映
14d0576
- Api 型を electron/preload/api.ts に切り出して preload と window.d.ts の重複を解消
- preload の try/catch を削除(contextIsolation: true 下では throw されないため fail loud に)
- main のイベントリスナ登録を top-level に統一
- optimizer.watchWindowShortcuts を is.dev でガード(本番では F12 等を有効化しない)
- is.dev && ELECTRON_RENDERER_URL の二重チェックを単一条件に整理
- App.tsx の electronVersion const をインライン化
- tsconfig.web.json から useDefineForClassFields を削除(React では不要)
- electron.vite.config.ts のパス解決を import.meta.dirname + path.join に統一

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
@ymnao
ymnao requested review from Copilot and removed request for Copilot April 28, 2026 19:58
Copilot started reviewing on behalf of ymnao April 28, 2026 20:42
View session
Copilot AI reviewed Apr 28, 2026
View reviewed changes

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.

Pull request overview

Stage 0a として、Electron + electron-vite をベースに React 19 / Tailwind v4 / Biome / Vitest を組み合わせたデスクトップアプリの起動確認までを行う雛形PRです。今後の Stage 0b 以降で旧フロント移植・Tauri差し替えを進める前提の土台になります。

Changes:

  • Electron(main/preload/renderer)3バンドル構成と起動用エントリを追加
  • React + Tailwind の最小レンダラーUIと window.api 型定義を追加
  • TypeScript / Biome / Vitest / pnpm まわりの設定と依存関係を追加

Reviewed changes

Copilot reviewed 12 out of 15 changed files in this pull request and generated 5 comments.

Show a summary per file
File Description
package.json Electron/React/Tailwind/Biome/Vitest 等の導入とスクリプト整備
pnpm-lock.yaml 追加依存関係のロック更新
electron.vite.config.ts main/preload/renderer のビルド設定(preload を CJS 出力に固定)
electron/main/index.ts BrowserWindow 作成・dev時ショートカット・外部リンク処理
electron/preload/index.ts window.electron / window.api の expose
electron/preload/api.ts preload 経由で公開する API 型の雛形
src/main.tsx React ルートのマウント
src/App.tsx window.api.getVersion() を表示する最小UI
src/index.css Tailwind v4 読み込みとベーススタイル
src/types/window.d.ts window.api / window.electron の型定義
index.html ルート要素と最小HTML(背景色など)
tsconfig.json project references のルート設定
tsconfig.web.json レンダラー向け TypeScript 設定
tsconfig.node.json Electron(node側)向け TypeScript 設定
biome.json Biome の lint/format 設定

Sorry, something went wrong.

Uh oh!

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

All reactions
Comment thread index.html Resolved

Uh oh!

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

Comment thread electron/main/index.ts Resolved

Uh oh!

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

Comment thread src/App.tsx Resolved

Uh oh!

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

Comment thread electron/main/index.ts Resolved

Uh oh!

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

Comment thread electron/preload/index.ts Resolved

Uh oh!

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

@ymnao @claude
fix: PR レビュー指摘(セキュリティ強化)を反映
3b6575f
- index.html に CSP(default-src 'self' / object-src 'none' / base-uri 'self' 等)を追加
- main: shell.openExternal の URL を http/https のみに制限
- main: will-navigate で同一 origin 外への遷移をブロック
- main: BrowserWindow 変数を mainWindow にリネーム(renderer の window と区別)
- preload: 公開する api を Object.freeze で不変化

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
@ymnao
ymnao requested a review from Copilot April 28, 2026 21:34
Copilot started reviewing on behalf of ymnao April 28, 2026 21:34
View session
Copilot AI reviewed Apr 28, 2026
View reviewed changes

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.

Pull request overview

Copilot reviewed 12 out of 15 changed files in this pull request and generated 3 comments.

Sorry, something went wrong.

Uh oh!

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

All reactions
Comment thread electron/main/index.ts Resolved

Uh oh!

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

Comment thread electron/main/index.ts Resolved

Uh oh!

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

Comment thread index.html Resolved

Uh oh!

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

@ymnao @claude
fix: PR レビュー指摘(CSP・will-navigate・openExternal)を反映
24be6c1
- index.html の CSP meta タグを削除し、main プロセスの session.webRequest.onHeadersReceived で動的設定に変更
- CSP を dev/prod で分離: prod は最小権限(default-src 'self' / connect-src 'self')、dev は HMR 用に script-src 'self' 'unsafe-inline' / connect-src ws://localhost:* http://localhost:* を追加
- will-navigate を allowlist 方式に変更: ELECTRON_RENDERER_URL(dev)以外は preventDefault、http/https の外部リンクは shell.openExternal に流す
- shell.openExternal を void ... .catch(() => {}) で unhandled rejection を防止

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
@ymnao
ymnao requested a review from Copilot April 28, 2026 21:45
Copilot started reviewing on behalf of ymnao April 28, 2026 21:45
View session
Copilot AI reviewed Apr 28, 2026
View reviewed changes

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.

Pull request overview

Copilot reviewed 12 out of 15 changed files in this pull request and generated 2 comments.

Sorry, something went wrong.

Uh oh!

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

All reactions
Comment thread electron/main/index.ts Resolved

Uh oh!

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

Comment thread electron/main/index.ts Resolved

Uh oh!

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

@ymnao @claude
fix: PR レビュー指摘(CSP/Renderer URL 検証)を反映
c044d0f
- isAllowedRendererUrl を URL.origin/pathname 比較に変更(startsWith による prefix bypass を防止)
- CSP_PROD から style-src 'unsafe-inline' を削除(XSS 影響範囲を縮小)
- index.html の inline <style> ブロックを src/index.css に統合(CSP 強化のため inline style を排除)

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
@ymnao
ymnao requested a review from Copilot April 28, 2026 21:52
Copilot started reviewing on behalf of ymnao April 28, 2026 21:52
View session
Copilot AI reviewed Apr 28, 2026
View reviewed changes

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.

Pull request overview

Copilot reviewed 12 out of 15 changed files in this pull request and generated 4 comments.

Sorry, something went wrong.

Uh oh!

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

All reactions
Comment thread electron/main/index.ts Resolved

Uh oh!

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

Comment thread electron.vite.config.ts Resolved

Uh oh!

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

Comment thread electron/main/index.ts Resolved

Uh oh!

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

Comment thread electron/main/index.ts Resolved

Uh oh!

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

@ymnao @claude
fix: PR レビュー指摘(main/preload を CJS に統一・CSP 二重防止・openExternal ログ)を反映
5d0fbf1
- electron.vite.config.ts: main の rollupOptions.output に format: cjs / entryFileNames: [name].js を明示
- package.json から "type": "module" を削除し、main/preload (.js) を CJS として実行できるようにする(package.json type と Rollup の cjs 出力の不整合で require is not defined になる問題を解消)
- main の onHeadersReceived で既存 Content-Security-Policy ヘッダを大文字小文字込みで filter してから設定(二重付与・合成による意図しない厳格化を防止)
- shell.openExternal の catch でエラー内容を console.error に出力(既定ブラウザ起動失敗時のデバッグ容易化)

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
@ymnao
ymnao requested a review from Copilot April 28, 2026 22:02
Copilot started reviewing on behalf of ymnao April 28, 2026 22:02
View session
Copilot AI reviewed Apr 28, 2026
View reviewed changes

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.

Pull request overview

Copilot reviewed 12 out of 15 changed files in this pull request and generated 3 comments.

Sorry, something went wrong.

Uh oh!

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

All reactions
Comment thread package.json Resolved

Uh oh!

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

Comment thread package.json Resolved

Uh oh!

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

Comment thread electron/main/index.ts Resolved

Uh oh!

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

@ymnao @claude
fix: PR レビュー指摘(engines.node・README 整合・CSP URL フィルタ)を反映
2192063
- package.json に engines.node を明示(^20.19.0 || >=22.12.0、Vite 7 / electron-vite 5 / Vitest 4 の要件)
- README: Vite を v8+ → Vite 7 / electron-vite 5 に修正、Node 最小バージョンを具体化、pnpm test:e2e は Stage 6 で整備予定の旨に変更
- main の onHeadersReceived に URL フィルタを追加し CSP 適用範囲を renderer の origin(dev: localhost dev server / prod: file:///*)に限定

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
@ymnao
ymnao requested a review from Copilot April 28, 2026 22:24
Copilot started reviewing on behalf of ymnao April 28, 2026 22:25
View session
Copilot AI reviewed Apr 28, 2026
View reviewed changes

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.

Pull request overview

Copilot reviewed 13 out of 16 changed files in this pull request and generated 4 comments.

Sorry, something went wrong.

Uh oh!

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

All reactions
Comment thread electron/main/index.ts Resolved

Uh oh!

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

Comment thread electron/main/index.ts Resolved

Uh oh!

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

Comment thread electron/main/index.ts Resolved

Uh oh!

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

Comment thread electron/main/index.ts Resolved

Uh oh!

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

@ymnao @claude
fix: PR レビュー指摘(prod ナビゲーション・Promise rejection・GC 対策)を反映
212df0f
- isAllowedRendererUrl に prod 用分岐を追加: file:// プロトコル かつ out/renderer 配下のみ許可(loadFile した renderer 内の SPA ナビゲーションがブロックされる問題を解消)
- loadURL / loadFile の Promise rejection を console.error でハンドリング(unhandled rejection 防止)
- BrowserWindow を openWindows: Set<BrowserWindow> で module-level に保持し、closed イベントで delete することで GC リスクを解消(複数ウィンドウ対応の下地にもなる)

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
@ymnao
ymnao requested a review from Copilot April 29, 2026 10:33
Copilot started reviewing on behalf of ymnao April 29, 2026 10:34
View session
Copilot AI reviewed Apr 29, 2026
View reviewed changes

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.

Pull request overview

Copilot reviewed 13 out of 16 changed files in this pull request and generated no new comments.

Sorry, something went wrong.

Uh oh!

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

All reactions
@ymnao
ymnao merged commit 420d2e8 into main Apr 29, 2026
4 checks passed

Uh oh!

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

@ymnao
ymnao deleted the chore/stage-0-bootstrap branch April 29, 2026 11:09
ymnao added a commit that referenced this pull request May 8, 2026
@ymnao
docs: 機能パリティ確認チェックリストを追加(Stage 6 GO/NO-GO 判定用) (#21)
5a0f45f
* docs: 機能パリティ確認チェックリストを追加(Stage 6 完了判定用)

旧 Tauri 版 (`ymnao/scripta`) と新 Electron 版(本リポ)の機能差分を
カテゴリ別にチェックリスト化し、リリース切り替え前の GO/NO-GO 判定基盤として
docs/parity-checklist.md を追加。

主な内容:
- 旧 Tauri 30 コマンド + 8 プラグイン API → 新 IPC のマッピング表
- 既知差分の明示:
  - convertFileSrc / CSP img-src の挙動差(packaged build で要実機検証)
  - e2e は renderer-only モード(実 Electron 起動なし、Vitest が補完)
  - update.ts:GITHUB_API_URL の暫定値(scripta-next)
- リリース前 blocker 早見表(§ 12)
- Stage 6 残項目との接続: コードサイニング / electron-updater 配線 /
  リリース切り替え(既に HANDOFF.md / migration-plan.md で把握済の項目を
  該当節に "🔁 別段 follow-up" として再掲)

* docs: parity-checklist のレビュー反映(事実誤認 / 重複 / 優先順位)

/simplify レビューエージェントの指摘を反映:

事実誤認:
- 旧 Tauri コマンド数を「30」→「commands::* 31 個 + clear_webview_browsing_data
  で計 32」へ修正(lib.rs の invoke_handler\! ブロックを精査)
- §8 メニュー対応表で旧 Tauri に View / Window submenu があるかのように
  ✅ 同等としていた行を訂正。旧 setup_menu は app/file/edit/help のみで、
  View / Window は新版で追加(OS 標準動作の補完)。menu.ts のコメントとも整合
- §3 で凡例外の ✨ ラベルを使っていたのを ✅(新規追加)に統一

重複の集約:
- §11 follow-up を HANDOFF.md への pointer に短縮。証明書手配 / Stage 6 残項目
  リストの canonical を HANDOFF.md と明示し、parity-checklist 側は § 12
  ブロッカー早見表での参照役に責務を絞る
- §12 末尾の「Stage 5 から継続課題」4 項目を圧縮(既に pointer 表記あり)

優先順位の修正:
- §12 必須順位を「取り返しのつかなさ × ユーザー影響範囲」基準で並び替え。
  旧 userData 互換(設定消失リスク)を #2 に繰り上げ。
- Git remote 認証実機確認は新版中核機能なので推奨 → 必須 #3 に格上げ
- 推奨の最小 e2e に具体的な pass 条件(workspace 選択 → md open → write
  → 再起動して内容残存)を付記

* docs: parity-checklist に dialog IPC / Prompt エクスポートを追加

レビューで指摘された 3 件の audit 漏れを反映:

1. plugin-dialog 由来のパリティ確認が抜けていた:
   - §2 表に dialog:open-directory を追加。OS ネイティブ folder picker を
     通った path のみ approveWorkspacePath で main 側 approve リストに
     登録される信頼境界を明記
   - §5 表に dialog:save を追加。registerTransientWritePath で発行される
     window-scoped 短命 write capability(consume-on-write、close-cleanup)
     の挙動を備考に明記
   - §2 / §5 検証項目に Open Folder の信頼境界 / transient write capability
     の境界(2 回目書き込み拒否 / window close 後の cleanup)を追加

2. エクスポート機能棚卸しが PDF 中心で Prompt エクスポートが漏れていた:
   - §5 タイトルを "OGP / PDF / 外部リンク" → "OGP / エクスポート / 外部リンク"
     に変更
   - エクスポート機能(フロント実装)小節を新設し、PDF / HTML / Prompt の
     3 形式すべてを旧/新で対応表化(src/lib/export.ts:645 の exportAsPrompt /
     ExportDialog.tsx:122)
   - §10 手動スモークに「PDF / HTML / Prompt(.md) 全 3 形式」を明記
   - 検証項目に Prompt エクスポートの custom template 分岐確認も追加

3. §0 参照基準で「新フロント呼び出し = src/lib/commands.ts」とした
   ベースが不正確だった:
   - settings 系は src/lib/store.ts から window.api.settings* を直接呼ぶ
   - export 系も src/lib/export.ts から window.api.showSaveDialog 等を直接呼ぶ
   - 監査時はこれらも対象に含める旨を明記

* docs: parity-checklist の dialog ラベル / export 経路を訂正

レビュー指摘 2 件への対応:

1. dialog:open-directory / dialog:save の ✅ ラベルが凡例と齟齬:
   - 凡例 §0 の ✅ は「Vitest / Playwright でカバー済」を意味する。
     しかし実態は path-guard / workspace 周辺テストで approveWorkspacePath
     / registerTransientWritePath の単体テストはあるものの、
     electron/main/ipc/dialog.ts ハンドラ自体(getOwnerWindow / IPC 配線 /
     helper 呼び出しの結線)を直接検証する dialog.test.ts は未整備
   - § 2 / § 5 の dialog 行を ✅ → 🟡 に変更し、「helper 単体は周辺テストで
     カバー済 / dialog.ts ハンドラ自体は直接テスト未整備、実機検証依存」と
     明記

2. § 0 / § 5 で export の呼び出し経路を「window.api.* 直接呼び出し」と
   書いていたが、実装は src/lib/export.ts:1 のとおり src/lib/commands.ts
   のラッパー経由(exportPdf / showSaveDialog / writeFile を import):
   - § 0 参照基準を「settings 系のみ store.ts から window.api を直叩き、
     export を含む他はすべて commands.ts ラッパー経由」と訂正。監査の
     索引は commands.ts + store.ts の 2 箇所で足りる旨を明記
   - § 5 エクスポート機能表を commands.ts 経由のフローに書き直し
     (`exportAsPdf → commands.exportPdf → pdf:export` 等)
   - 「export.ts は window.api.* を直接は叩かない」と前置きを追加
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 も同じ衝突を起こす)。
ymnao added a commit that referenced this pull request Jun 3, 2026
@ymnao
fix: #96 URL paste と md リンク/OGP カード UX 改善 (#135)
f2f8b9f
* fix: URL paste 時の md リンク変換を行コンテキスト依存に変更 (#96)

paste 後の行が URL のみになる場合は md リンク変換を行わず plain URL のまま
挿入するように `urlPasteHandler` を修正。これにより link-cards.ts の OGP card
が起動するようになる。

- 選択あり paste → 従来通り md リンクに変換
- 選択なし paste かつ paste 後の行が URL のみ → plain insert(OGP card 起動)
- 選択なし paste かつ paste 後の行に他テキスト混在 → md リンクに変換
- コードブロック内は従来通り変換しない

判定ロジックは pure 関数 `shouldConvertPasteToLink` に切り出してユニット
テスト可能化。

* feat: paste 直後の OGP カードを即時表示

通常 typing 中の 150ms throttle は維持しつつ、`input.paste` userEvent を
持つ transaction を検出した場合は throttle を skip して即時 rebuild する。
これにより URL を空行に貼った直後に loading skeleton card が即座に出る
(OGP fetch 自体は非同期だが UI 上は \"反応がない\" 印象を消す)。

判定は `containsPasteUserEvent` (pure) に切り出してユニットテスト。

* feat: Cmd+Shift+V で URL を強制 md リンク化

新規 keymap `Mod-Shift-v` を追加し、clipboard を読んで:
- URL なら強制的に [label](<url>) に変換(行コンテキスト依存の Cmd+V と
  違い、URL only 行でも常にラップ)
- 非 URL なら plain text として挿入
- コードブロック内なら force convert を override して常に plain

実装は以下の pure / semi-pure 関数群に分割してユニットテストでカバー:
- `isPosInCodeConstruct` / `anyRangeInCodeConstruct` — コード位置判定
- `computeUrlPasteInsert` — Cmd+V / Cmd+Shift+V 共通の insert 決定ロジック
- `applyClipboardPasteAsMdLink` — clipboard 読み取り後の sync 処理
- `pasteAsMarkdownLinkCommand` — keymap 用の薄い CodeMirror Command

既存 `urlPasteHandler` (Cmd+V) も `dispatchUrlInsert` 共通実装に統合し、
両 path で同じ決定ロジックを通る。

* feat: OGP カードに右クリックメニューを追加

CM 拡張 (link-cards.ts) に `contextmenu` handler を追加し、`.cm-link-card`
の右クリックで custom event `link-card-context-menu` を dispatch。
MarkdownEditor.tsx 側で listener を張って ContextMenu を表示する。
mermaid 右クリックメニュー (mermaid-context-menu) と同じパターン。

メニュー項目:
- リンクを開く(openExternal)
- URL をコピー(navigator.clipboard.writeText)
- md リンクに変換(`[title](<url>)` で URL 行を置換、title は OGP cache から)
- カードを削除(行 + 末尾改行を削除して上下の行を連結、最終行なら直前改行)

新規 pure helper / 公開関数:
- `getCardDeleteRange` — 削除 range の計算(middle / last / single-line 全分岐をテスト)
- `buildMdLinkFromCard` — URL+ogpTitle → `[label](<url>)` 文字列生成
- `getCachedOgpTitle` — ogpCache からの title 取得 (internal)

editor-level contextmenu handler の除外リストに `.cm-link-card` を追加し、
通常エディタメニューと二重発火しないようにする。

* feat: md リンクの cmd+click 開閉 + 右クリック「カードにする」

LinkWidget の click 振る舞いを変更:
- plain click → editor に委譲(cursor が行に入り raw md syntax 表示)
- cmd/ctrl+click → URL を openExternal で開く
- title に modifier ヒント `(⌘+クリックで開く)` を表示

CM 拡張に `contextmenu` handler を追加し、`.cm-link-widget` 右クリックで
custom event `link-widget-context-menu` を dispatch。MarkdownEditor.tsx 側で
listener + ContextMenu を実装する。

メニュー項目:
- リンクを開く(modifier shortcut 表示付き)
- URL をコピー
- 「カードにする」 — 行が `[label](<url>)` 単独のときのみ表示。
  label が URL と一致するなら直接置換、違う場合は確認 Dialog を経由して
  「表示テキストが捨てられる」警告を出してから変換

editor-level contextmenu handler の除外リストに `.cm-link-widget` を追加。

新規 pure helper / 公開関数:
- `isOpenLinkModifierEvent` — cmd/ctrl 判定
- `parseSingleMdLink` — `[label](<url>)` / `[label](url)` 形式の文字列 parse
- `isLineOnlyMdLink` — 行内に md リンク以外のテキストが無いか判定
- `extractLinkParts` (internal) — CM Link node から url/label を取り出し

* fix: md リンク widget の cmd+click / 右クリック を CM-level handler で確実に動作させる

問題: 前回 commit (48433ea) で widget DOM 上に click/mousedown listener を
付けて modifier 判定する方式にしたが、実機で cmd+click でも開かず右クリックも
メニューが出ず、カーソルが移動するだけだった。原因は plain click と同じ
mousedown 経路で editor の cursor placement が走り widget が消えてから
click/contextmenu が発火するため、widget の listener にイベントが届かない
ケースがあったこと。加えて anchor の `href` 属性で Chromium の cmd+click
新規ウィンドウ動作と競合する可能性。

修正:
- widget DOM の click/mousedown listener を撤去し、すべて CM-level の
  `EditorView.domEventHandlers` (linkWidgetMouseHandler) で処理する
- mousedown で「右クリック」「cmd/ctrl+左クリック」は preventDefault して
  widget を残し、後続の contextmenu / click が widget 上で発火するようにする
- click handler で modifier を確認して openExternal を呼ぶ
- contextmenu handler は従来通り custom event dispatch
- LinkWidget.ignoreEvent をマウス系・contextmenu は false(editor に渡す)、
  キーボードは true(widget で Enter/Space 処理)に再整理
- anchor.href を撤去し dataset.linkWidgetUrl に URL を保持。CM handler から
  読む。CSS styling はクラス指定なので影響なし
- ヘルパー findEnclosingLinkNode を切り出し

加えて card 右クリック「md リンクに変換」のラベルを OGP title ではなく
URL に統一(lossless 変換):
- buildMdLinkFromCard / getCachedOgpTitle を削除し、`buildMarkdownLink(url, "")`
  を直接使う
- card context menu event detail から title フィールドを削除
- 関連テストを更新

新規テスト:
- LinkWidget.ignoreEvent の新ルール(mouse/contextmenu false, keyboard true)
- toDOM が href を付けず dataset.linkWidgetUrl を持つこと
- 無効リンクで dataset.linkWidgetUrl が付かないこと

* fix: md リンク widget の cmd+click / 右クリックを Prec.highest + dual-layer で確実化

前回 commit (1b30536) で CM-level domEventHandlers パターンに移行したが
実機で cmd+click / 右クリックが効かない問題が継続。原因は CodeMirror 6 の
extension precedence:

> "For any given event, such functions are ordered by extension precedence,
>  and the first handler to return true will be assumed to have handled
>  that event, and no other handlers or built-in behavior will be activated"
> — codemirror.net/docs/ref/

> "If you need your custom mousedown handler to run at higher precedence than
>  the built-in selection handling, you would wrap your handler with
>  Prec.high() when registering it."

デフォルト precedence の `EditorView.domEventHandlers` は built-in
mouseSelection より後に走るため、`return true` しても先に cursor が動いて
しまっていた。

## 修正

1. **`linkWidgetMouseHandler` を `Prec.highest` でラップ** — built-in
   selection より先に走らせ、cmd+click / 右クリックでの cursor 移動を確実に
   阻止する。これが今回の根本修正。

2. **widget DOM に mousedown listener を追加 (defense-in-depth)** —
   cmd/ctrl+左クリックを target レベル (DOM 最深部) で掴み、
   preventDefault + stopPropagation + openExternal を実行。bubbling が
   止まるので CM-level handler も React の delegated handler も一切走らない
   最強路線にする。CM-level handler は fallback として残す。

3. **cmd+click は mousedown で開く(click event を待たない)** — 万一
   widget が再 render されて click event が widget DOM に届かない race を
   完全に排除。LinkCardWidget は plain-click 開閉なので click event 経路で
   問題ないが、md リンクは modifier 判定が入る分よりタイトに処理する。

## 追加テスト (jsdom で dispatchEvent シミュレーション)

- cmd+click / ctrl+click で `openExternal` 呼び出し
- plain click では呼ばない
- 右クリック (button 2) では呼ばない(cmd+右クリックも含む)
- cmd+click が stopPropagation して親に bubbling しない
- 無効リンク (ftp://) では呼ばない

Sources:
- https://codemirror.net/docs/ref/ (EditorView.domEventHandlers, Prec)
- https://discuss.codemirror.net/t/link-widget-is-clicked-only-if-editor-is-out-of-focus/7433
- https://discuss.codemirror.net/t/running-custom-dom-handlers-after-the-built-in-ones/6318

* fix: md リンク widget を LinkCardWidget と同じ atomic-widget パターンに統一

前回までの CM-level domEventHandlers + Prec.highest + dual-layer の組み合わせ
でも実機の cmd+click / 右クリックが動かなかった。ユーザ確認で動作実証済みの
LinkCardWidget パターン(ignoreEvent=true で widget DOM が全 mouse 処理)に
全面的に揃える。

## 新アプローチ

- **`ignoreEvent`**: mouse 系で `true` (atomic-widget) → CM の selection
  placement や mouseSelectionStyle が widget 上のイベントに一切介入しない
- **widget DOM の mousedown listener** が全てを処理:
  - cmd/ctrl + 左クリック → `openExternal`
  - plain 左クリック → `view.dispatch({selection: cursor(pos)})` で手動カーソル
    移動(atomic で CM の placement が止まってるので、ここでやらないと
    cursor 移動しない → raw 表示にならない)
  - 右クリック (button 2) → no-op、後続の contextmenu イベントへ
- **`ignoreEvent` の contextmenu のみ `false`** で CM-level handler に渡す。
  CM の `linkWidgetContextMenuHandler` (domEventHandlers) が syntaxTree から
  link 情報を取り出して custom event を dispatch する
- **`toDOM(view)` で view を受け取る** ようシグネチャ拡張。dispatch に必要

## 削除した複雑さ

- CM-level の mousedown / click handler (linkWidgetMouseHandler) を削除
- `Prec.highest` ラップを削除(atomic-widget では built-in selection との
  競合自体が発生しないので不要)
- defense-in-depth の stopPropagation を削除(atomic-widget が CM 側を
  完全に遮断する)
- `isOpenLinkModifierEvent` helper は test 側でのみ参照されるが export 残す

## テスト更新

`makeMockView` ヘルパーを追加し、`view.posAtDOM` / `view.dispatch` /
`view.focus` を vi.fn でモック。widget DOM の dispatchEvent で
mousedown を発火させて期待挙動を検証:
- cmd+click / ctrl+click → openExternal 呼ばれる
- plain click → openExternal 呼ばれず view.dispatch + view.focus
- 右クリック → 何も呼ばれない
- 無効リンク (ftp:) → 何も呼ばれない
- Enter キー → openExternal

ignoreEvent も新ルールに更新: mousedown/click=true, contextmenu=false

* fix: md リンク widget を ViewPlugin.eventHandlers パターンに移行 (CheckboxWidget と同じ)

調査経過:
- 直前 commit (a964b0c) で widget DOM listener + ignoreEvent=true パターンに
  したが実機で動作せず(hover title は出るが mousedown listener が反応しない)
- 同リポジトリ内の CheckboxWidget が `ViewPlugin.fromClass({ eventHandlers })`
  パターンで動作していることを発見。これは CodeMirror 公式 "Boolean Toggle
  Widget" 例 (https://codemirror.net/examples/decoration/) のパターンと一致
- このパターンは `EditorView.domEventHandlers` とは別の機構で、ViewPlugin の
  decoration と一緒にイベント処理が登録される。CM6 のイベント順序と確実に
  噛み合うため、widget 系の click 処理ではこちらが正解

## 新構造

- `LinkWidget.toDOM()` は純粋に DOM 生成のみ(href / dataset / title /
  tabIndex を設定)。**event listener を付けない**
- `LinkWidget.ignoreEvent() { return false }` で editor にイベントを渡す
- `linkPlugin` (ViewPlugin) の `eventHandlers` で mousedown / click /
  contextmenu / keydown を一元処理:
  - mousedown button 0 + modifier → preventDefault + openExternal
  - mousedown button 2 → preventDefault(cursor 維持、後続 contextmenu へ)
  - mousedown plain → return false(CM の built-in selection が cursor 移動)
  - click → preventDefault(href の navigation 抑止)
  - contextmenu → 専用 custom event dispatch
  - keydown Enter/Space (Tab focus 中) → openExternal
- `EditorView.domEventHandlers` 経由の `linkWidgetContextMenuHandler` を削除
- href 属性を復活(a11y / hover preview)。新規 window 動作は mousedown で抑止

## テスト

widget DOM 直接の dispatchEvent ベースのテストは obsolete(widget DOM に
listener がない)ため削除。代わりに:
- ignoreEvent が false を返すこと
- toDOM の DOM 構造(href / dataset / class / tabIndex / aria)
- toDOM が DOM event listener を持たない(防衛的検証: 直貼り防止)

ViewPlugin.eventHandlers のロジックは pure helper
(isOpenLinkModifierEvent, parseSingleMdLink, isLineOnlyMdLink) の既存テスト
でカバー。end-to-end な動作確認は実 Electron で行う。

Sources:
- https://codemirror.net/examples/decoration/ (Boolean Toggle Widget)
- 本リポジトリ src/components/editor/live-preview/lists.ts (CheckboxWidget)

* debug: link widget の mousedown/contextmenu に console.log を追加

実機で ViewPlugin.eventHandlers が発火しているか確認するための一時的な
debug ログ。動作確認後に削除する。

- widget の anchor に `dataset.lwVersion = "viewplugin-eh-v1"` で新コード
  ロード判定用 marker を追加
- mousedown / contextmenu handler の冒頭に console.log

* fix: md リンクの URL から angle brackets を剥がして disabled 化を防ぐ

## 真因

セッション通じて再現していた「cmd+click / 右クリックが効かない」の根本原因を
ようやく特定:

CommonMark の `[label](<url>)` 形式では Lezer markdown parser は URL ノードに
angle brackets を含めて返す(例: `<https://note.com/>`)。これを stripping
せずに `LinkWidget` に渡すと、`isSafeUrl()` の正規表現 `/^https?:\/\/.../` が
`<` で始まる文字列を弾いて widget が disabled (cm-link-widget-disabled)
扱いになる → ViewPlugin.eventHandlers 内の `widgetEl.classList.contains(
"cm-link-widget-disabled")` 早期 return で全 mouse / contextmenu 処理が skip
されていた。

決定打となった証拠 (DevTools 抜粋):
```
<a class="cm-link-widget cm-link-widget-disabled"
   title="<https://note.com/> (opens only http/https)" ...>
```

`buildMarkdownLink` は `[label](<url>)` 形式で md リンクを作るので、paste /
Cmd+Shift+V 経由のリンクは全て罠にハマっていた。

## 修正

`stripUrlAngleBrackets(rawUrl)` を pure helper として追加し、
`buildDecorations` と `extractLinkParts` の `cursor.name === "URL"` 取得箇所
両方で適用。これだけで `LinkWidget` の `url` が `https://...` に正規化され、
`isSafeUrl` が true を返して widget が有効化される。

## 副次効果

過去数 commit で試した手段はいずれも paint over だったため roll back せず
残すが、本来の問題は今回の 1 行で解消する:
- ViewPlugin.eventHandlers パターン (`7cec644`) ← 正しいが disabled で skip
- Prec.highest + dual-layer (`d1bb78f`) ← 同上
- CM-level domEventHandlers (`1b30536`) ← 同上

## 削除

調査用に追加していた `console.log` と `dataset.lwVersion` marker を削除。

## テスト

`stripUrlAngleBrackets` の単体テスト 6 ケース追加(基本動作 / 片側だけ /
空文字 / 非 http URL / buildMarkdownLink との round-trip)。

* feat: cmd/ctrl 押下中の md リンクで cursor を pointer に切り替え

VS Code 等の cmd+hover 表示と同じ UX。「今 cmd を押せば開ける」ことを
視覚的に示す。

## 実装

- `modifierTrackPlugin` (ViewPlugin) を links.ts に追加。window レベルで
  keydown / keyup / blur を listen し、cmd/ctrl 押下中だけ
  editor wrapper (`view.dom`) に `cm-link-mod-down` クラスを付与
- editor-theme.ts に CSS rule 追加:
  `&.cm-link-mod-down .cm-link-widget:not(.cm-link-widget-disabled)`
  → cursor: pointer
- pure helper `isOpenLinkModifierKey(key)` を切り出してテスト

window レベル listen の理由: editor に focus がない hover-only ケースでも
反応させる。取り残し対策:
- keyup: `event.key` 判定だけでなく `metaKey && ctrlKey` 両 false でも解除
- blur: cmd+Tab 等で keyup が来ない時のため

destroy() で listener と class を確実に cleanup。

* refactor: /simplify pass — 重複除去・dead code 削除・hook 抽出

4-agent review (reuse / simplification / efficiency / altitude) で複数 agent
が指摘した高確度の cleanup を適用。-132 lines。

## 適用

1. **Link node parsing の単一真実源化** (4 agent 全員指摘)
   - `parseLinkNode(state, syntaxNode)` 抽出。Lezer LinkMark/URL walk +
     `stripUrlAngleBrackets` を 1 箇所に集約
   - `buildDecorations` と新規 `resolveLinkAtPos` 両方が parseLinkNode 経由
   - `extractLinkParts` (Lezer walk 再実装) + `findEnclosingLinkNode` (tree 走査
     再実装) を削除し `resolveLinkAtPos` に統合 → contextmenu で tree を 2 回
     walk していたのが 1 回に
2. **`parseSingleMdLink` dead code 削除**: 25 行 regex parser + 7 ケース。
   production 呼び出しゼロ(runtime は Lezer 経由の parseLinkNode を使う)
3. **`containsPasteUserEvent` の tautological wrapper を inline**:
   コメントは「念のため自前実装」と書いてあったが本体は
   `tr.isUserEvent("input.paste")` を呼ぶだけ。callsite 1 箇所に inline、
   helper + 6 ケースのテスト削除
4. **`useWidgetCustomEvent` hook 抽出**: mermaid / link-card / link-widget の
   3 useEffect コピペを 1 hook + 3 呼び出しに。`onEvent` を ref で参照して
   stale closure 回避(lint disable 不要)
5. **`resolveTargetElement` helper 抽出**: `handleEditorMouseDown` /
   `handleEditorContextMenu` の `instanceof Element` cascade 6 行 → 1 関数呼び
6. **`getLinkWidgetMenuItems` useCallback 抽出**: JSX 内の 40 行 IIFE を
   `getEditorContextMenuItems` と同じ粒度に揃える
7. **`isLineOnlyMdLink` signature を 5 引数 → 3 引数に**: line 内 offset を
   呼び出し側で計算するシンプル化。実質使われていなかった 2 引数を削除

## skip した findings

- 3-widget contextmenu dispatch 統合: mermaid.ts は本 PR scope 外
- `isMac` を src/lib/platform.ts に集約: 2 重定義は小さく、ファイル増のコスト
  が見合わない
- `handleEditorContextMenu` の widget exclusion list を defaultPrevented 一本化:
  全 widget handler が確実に preventDefault する保証が要り behavior risk あり
- `modifierTrackPlugin` の window listener singleton 化: 複数 editor 同時運用は
  稀で複雑度に見合わない
- `createLinkCardClickGuard` の `RangeSet.iter(from)` 化: 本 diff 外
- `cardContextMenu` / `linkWidgetContextMenu` / `mermaidContextMenu` の base
  type 共通化: cosmetic、現状で読める

## 検証

format / lint / typecheck / typecheck:e2e: ✅
unit: ✅ 1346 passed (前回 1360 → dead code 削除分 14 ケース減)
build / legacy-residue: ✅

* fix: P1/P2 review 指摘対応 — macOS Ctrl+click 除外 + 非 URL paste lossless 化

## P1: macOS の Ctrl+click を「リンク開く」操作から除外

`isOpenLinkModifierEvent` は OS 判定なしに `metaKey || ctrlKey` を返していた
ため、macOS で md リンク上の Ctrl+click(= context menu 操作)が意図せず URL
を開いていた。

- pure helper `decideOpenLinkModifier(event, isMac)` を抽出し、Mac は metaKey、
  非 Mac は ctrlKey のみで判定する OS 分岐を導入
- `isOpenLinkModifierEvent` は runtime に `IS_MAC` (`navigator.platform`) を
  bind して内部で `decideOpenLinkModifier` を呼ぶ薄い wrapper に
- 同様に `decideOpenLinkModifierKey(key, isMac)` / `isOpenLinkModifierKey` も
  分割(modifierTrackPlugin の cmd+hover pointer cursor も OS-aware に)
- LinkWidget.toDOM 内の重複していた isMac 検出も module-scope `IS_MAC` に統一

## P2: Cmd+Shift+V の非 URL paste で whitespace を保持

`applyClipboardPasteAsMdLink` は冒頭で `raw.trim()` した値を URL 判定にも
挿入文字列にも使っていたため、`Mod-Shift-v` で native paste を抑止している分、
通常テキストの先頭/末尾 whitespace や改行が消える破壊的挙動になっていた。

- URL 判定には trimmed を使い、非 URL を挿入する path では `raw` をそのまま
  使うように分離(lossless)
- whitespace-only clipboard は引き続き no-op(意図的)

## テスト

- `decideOpenLinkModifier` / `decideOpenLinkModifierKey` を pure 引数で
  Mac / 非 Mac 両方検証
- 非 URL paste で leading/trailing whitespace 保持、改行保持を追加

* fix: Cmd+Shift+V を完全 lossless に — コード内 URL の whitespace 保持 + 空白のみ clipboard も挿入

P2 / P3 の指摘対応。前 commit (592c713) で非 URL paste の lossless 化を入れた
が、まだ 2 つの整合性穴があった:

## P2: コードブロック内の URL paste で whitespace が消えていた

`applyClipboardPasteAsMdLink` は URL 判定後に `dispatchUrlInsert(view, trimmed)`
を呼んでいた。`dispatchUrlInsert` 内のコードブロック判定で plain 挿入に倒れる
が、その plain 挿入は trimmed を使うので `"  https://example.com\n"` →
`"https://example.com"` に縮む。コメントは「コードブロック内は常に plain」と
書いてあるが lossless ではなかった。

## P3: whitespace-only clipboard が握り潰されていた

`if (\!trimmed) return;` で no-op。Mod-Shift-v は native paste を抑止するので、
ユーザーは意図的にインデント・空行・空白を paste する手段が無くなっていた。

## 修正

`applyClipboardPasteAsMdLink` の分岐を整理:

- `raw == null || raw === ""` → no-op (clipboard 読めず / 完全空文字)
- URL かつコードブロック外 → md リンク化 (trimmed)
- それ以外 (非 URL / whitespace-only / コードブロック内 URL) → **raw を lossless 挿入**

「Mod-Shift-v keymap が native paste を抑止する以上、plain insert path では
native paste と同じ as-is 体験を保証する」を一貫したルールに昇格。

## テスト

obsolete な「whitespace は no-op」テストを削除し、以下を追加/差し替え:
- 空文字 clipboard → no-op
- whitespace-only → raw 挿入 (lossless, no swallow)
- コードブロック内の URL clipboard → 前後 whitespace 込みで raw 挿入

* test: md link widget / OGP card の e2e カバレッジを Playwright で追加

unit / pure helper では捕まらない実 DOM イベント順序を renderer-only Playwright
で検証する `e2e/link-widget.spec.ts` を新規追加(13 test)。

## カバレッジ

### md link widget — cmd/ctrl+click で URL を開く
- modifier+click で openExternal が呼ばれる (`mock.getCalls("openExternal")` 検証)
- plain click は openExternal を呼ばずカーソル移動だけする
  (widget が cursorInRange で再 render → 該当 widget だけ消えるのを count 検証)

### md link widget — 右クリックメニュー
- URL only line でメニューに「リンクを開く」「URL をコピー」「カードにする」が出る
- 混在 line では「カードにする」が出ない (`isUrlOnlyLine=false` の case)
- 「リンクを開く」メニュー click で openExternal が呼ばれる
- 「URL をコピー」が clipboard に URL を書き込む (`navigator.clipboard.readText()`)
- 「カードにする」(label \!= URL) → 確認 Dialog → 「変換する」で plain URL 化
  → OGP card が新たに出現 (1→2 枚)
- 「カードにする」確認 Dialog を「キャンセル」すると元の widget が残る

### OGP card — 右クリックメニュー
- カード上の右クリックで 4 項目メニュー (リンクを開く / URL をコピー /
  md リンクに変換 / カードを削除)
- 「リンクを開く」が openExternal を呼ぶ
- 「md リンクに変換」で `[url](<url>)` に置き換わりカードが消え、URL ラベル
  widget が出現
- 「カードを削除」で URL 行が文書から消える

### modifier 押下中の class toggle
- `cm-link-mod-down` クラスが editor wrapper に動的に付くこと
  (CSS の cursor: pointer 切替の前提)

## 検証

- pnpm test:e2e: 156 passed (新規 13 含む)
- format / lint / typecheck:e2e: ✅

* refactor: /simplify pass #2 — platform helper / regex 統合 / e2e setup 抽出

2 回目の /simplify pass で 4 agent 共通指摘の高価値 cleanup を適用。-29 lines
(helper 追加分含む / 既存コードからは大幅減)。

## 適用

1. **`src/lib/platform.ts` 新規** — `IS_MAC` + `PRIMARY_MOD_SYMBOL` を集約。
   `MarkdownEditor.tsx` (10+ shortcut 文字列) と `links.ts` の独自 isMac 判定
   を全て置き換え。`navigator.platform` の検出ロジックが `.toLowerCase()
   .includes("mac")` / `.includes("Mac")` / `/Mac|iPhone.../` と 3 種類混在
   していた潜在 bug source を解消(他ファイル NewTabContent/HelpDialog/TabBar
   は scope 外で別 PR)

2. **URL 正規表現 3 重複 → 1** — `SAFE_URL_RE` / `URL_PASTE_RE` /
   `STANDALONE_URL_RE` がすべて `/^https?:\/\/[^\s]+$/i` で同一だったので
   `URL_PASTE_RE` を単一 source として `isSafeUrl` / `isStandaloneUrlLine`
   両方から参照

3. **`openLinkWidgetUrl` helper** — `openExternal(url).catch(console.error)`
   の 2 callsite 重複を解消(error 文言ハードコード 2 箇所→1)

4. **`parseLinkNode` 早期 break** — url / textFrom / foundCloseBracket が
   揃ったら以降の sibling iteration を skip

5. **`isLineOnlyMdLink` whole-line short-circuit** — link が行全体を占める
   common case で slice+trim を回避

6. **`applyClipboardPasteAsMdLink` の inCode lazy 評価** — `anyRangeInCodeConstruct`
   は syntaxTree walk を含むので、非 URL paste の hot path で URL 判定が
   false の時は短絡。`raw == null || raw === ""` を `\!raw` に簡略化も

7. **e2e `openSingleFileWorkspace` helper** (`e2e/helpers/workspace-setup.ts`)
   — `mock.setup({fs}) → goto → Open folder → click file → wait editor` の
   ~15 行ボイラーが 10+ spec で重複していたので 1 関数に集約。`files` から
   `directories` マップを自動生成。今回は新規 spec に適用(既存 spec への
   migrate は別 PR)

8. **e2e `modKey === "Meta" ? "Meta" : "Control"` identity 削除** —
   `modKey` は既に `"Meta" | "Control"` リテラル union(Playwright の
   Modifier 型と互換)なので三項は無駄

9. **e2e `mock.clearCalls("openExternal")` を setup 内へ集約** — 各テストで
   毎回呼んでいた boilerplate を `setupLinksFile()` の末尾に 1 箇所化

## skip した findings

- 4 modifier helper (`decideOpenLink*` + `isOpenLink*`) の縮約 → testability
  の利点が cost を上回るので維持
- 3 widget menu (mermaid / card / link-widget) の `useWidgetContextMenu<T>`
  統合 → mermaid.ts に手を入れる scope 外
- e2e test の `test.describe.serial` / `beforeAll` 化 → 既存 worker 並列で
  CI 全体 24s なので gain 小
- `modifierTrackPlugin` の per-editor → singleton 化 → 単一 editor 運用なので
  per-editor cost が低く、`ViewPlugin destroy lifecycle` の利点が勝る

## 検証

format / lint / typecheck / typecheck:e2e: ✅
unit: ✅ 1349 passed
e2e (link-widget): ✅ 13 passed
e2e (full): ✅ 156 passed
build / legacy-residue: ✅
@ymnao ymnao mentioned this pull request Jul 6, 2026
fix: CodeQL alerts 2 件と同族 ReDoS pattern を修正 #297
Merged
5 tasks done
ymnao added a commit that referenced this pull request Jul 6, 2026
@ymnao
fix: CodeQL alerts 2 件 + 同族 ReDoS pattern を予防修正 (#297)
453b0d3
- markdown-to-html.ts:230 `OPENING_LINE_PREFIX_RE`: trailing `[ \t]*`
  を繰り返しの外に出し、各 iteration の boundary を marker character に
  確定させ backtrack を線形化 (CodeQL js/redos #1)。認識言語は等価
  (`(prefix_ws + marker)* + trailing_ws`)。
- markdown-to-html.ts:65 `containerPrefix`: 同一ファイル内に同形 pattern
  が残り `.source` で 3 regex (fenced open / fenced close / indented) に
  splice されていたため予防的に同形へ書き換え。CodeQL は
  `new RegExp(string)` の dataflow を追えず未検出だが構造は等価。
- table-decoration.ts:175 `sanitizeCellText`: backslash を先に `\\` へ
  倍化し、後段の `\|` 挿入で cell separator に化けるのを防止
  (CodeQL js/incomplete-sanitization #2)。

verify:
- typecheck × 3 (web / node / e2e): all PASS
- biome check 323 files: No fixes applied
- vitest run: 101 files / 2273 passed / 2 skipped

Refs: v1.0.0 昇格 checklist § 13-6 (security advisory clean) blocker 解消
@ymnao ymnao mentioned this pull request Jul 12, 2026
feat: スライドプレビューと PDF エクスポートでローカル画像を解決 #315
Merged
6 of 7 tasks
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]>
@ymnao ymnao mentioned this pull request Jul 18, 2026
fix: exportAsHtml の埋め込み画像に累積バイト数上限を追加 (#354) #355
Merged
5 tasks done
@ymnao ymnao mentioned this pull request Aug 1, 2026
refactor: AppLayout 1630 行を 3 hook / モジュールへ分割する #459
Merged
7 tasks done
@ymnao ymnao mentioned this pull request Oct 6, 2026
fix: 折りたたみ中に外部変更を取りこぼしたフォルダを再展開時に取り直す #610
Merged
3 of 10 tasks
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.