From 2bbedd440b43d50eba660c7944cfbef03e41d6a1 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 6 Nov 2026 11:24:16 +0000 Subject: [PATCH] =?UTF-8?q?feat:=20=E5=B7=AE=E5=88=86=E3=83=93=E3=83=A5?= =?UTF-8?q?=E3=83=BC=E3=83=BB=E3=83=A9=E3=82=A4=E3=83=96=E5=A4=89=E6=9B=B4?= =?UTF-8?q?=E3=83=AC=E3=83=93=E3=83=A5=E3=83=BC=E3=83=BBGit=20=E5=B1=A5?= =?UTF-8?q?=E6=AD=B4=E3=83=BB=E3=83=AA=E3=83=B3=E3=82=AF=E3=83=81=E3=82=A7?= =?UTF-8?q?=E3=83=83=E3=82=AF=E3=82=92=E8=BF=BD=E5=8A=A0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - テキスト差分エンジン (Myers, 単語単位ハイライト, unified patch) と差分ビュー (左右/統合表示, 変更箇所ナビ, 空白無視, 行ジャンプ, パッチのコピー/保存, Secret Safe 対応, ファイル変更時の自動再比較) - 開いた後に外部で変更されたファイルに「変更あり +N −M」チップを表示し、 開いた時点との差分を確認・確認済みにできるようにする (D キー) - Git 履歴 API (/api/git/status, /api/git/log, /api/git/show) を追加し、 HEAD・過去コミットとの比較、ファイルツリーの変更バッジと「Git: 変更のみ」絞り込みに対応 - Markdown のリンク切れ検出 API (/api/links/check) とレポート画面、 TOC パネルの文書別リンク切れ表示を追加 - ファイルツリーの右クリックメニューに比較・履歴・リンクチェックの導線を追加 - 単体テスト (差分エンジン, Git/リンクチェック API) と E2E テストを追加 Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01L4uUUgYQkS1qRWZ3odMQPM --- CHANGELOG.md | 9 + CLAUDE.md | 3 + README.md | 7 + index.html | 4 + server.mjs | 374 ++++++++++++++++- src/diff-view.ts | 772 +++++++++++++++++++++++++++++++++++ src/filetree.ts | 151 ++++++- src/help-modal.ts | 9 + src/link-report.ts | 222 ++++++++++ src/main.ts | 132 ++++++ src/style.css | 373 +++++++++++++++++ src/text-diff.ts | 363 ++++++++++++++++ src/toc.ts | 44 ++ tests/diff-linkcheck.spec.ts | 155 +++++++ tests/history-links.test.mjs | 201 +++++++++ tests/setup.ts | 10 + tests/text-diff.test.mjs | 114 ++++++ 17 files changed, 2937 insertions(+), 6 deletions(-) create mode 100644 src/diff-view.ts create mode 100644 src/link-report.ts create mode 100644 src/text-diff.ts create mode 100644 tests/diff-linkcheck.spec.ts create mode 100644 tests/history-links.test.mjs create mode 100644 tests/text-diff.test.mjs diff --git a/CHANGELOG.md b/CHANGELOG.md index ff2736e..bbefc0c 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,6 +5,15 @@ All notable changes to this project will be documented in this file. The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/), and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). +## Unreleased + +### Added + +- Diff view for text files: side-by-side / unified layouts, word-level highlights, change navigation, whitespace-insensitive comparison, expandable context, jump-to-line, and patch copy / download. Secret Safe mode masks both sides. +- Live change review: a chip shows `+N −M` when an open file changes on disk, opening a diff against the version first opened in the session (`D` shortcut). +- Git history: compare a file with `HEAD` or recent commits (`/api/git/log`, `/api/git/show`), Git change badges in the file tree and a "Git: 変更のみ" filter (`/api/git/status`). +- Link check: broken relative links, images, reference definitions and wiki links across Markdown documents (`/api/links/check`), shown per document in the TOC panel and as a folder report. + ## 1.9.0 - 2026-07-30 ### Changed diff --git a/CLAUDE.md b/CLAUDE.md index 312174c..7cd42a6 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -30,6 +30,8 @@ No linter/formatter configured; TypeScript strict mode is the quality gate. - `GET /api/search?q=` — full-text grep across served directory - `GET /api/watch` — SSE stream; Chokidar broadcasts file changes to all connected clients - `GET /api/custom-css` — loads `.docview.css` from the served directory +- `GET /api/git/status` / `GET /api/git/log?path=` / `GET /api/git/show?path=&rev=` — read-only Git history (execFile, validated rev, timeout); `git:false` outside a repo +- `GET /api/links/check?path=` — broken relative links in Markdown (resolved like the viewer), scoped to a folder/file **Frontend (`src/`)** — Vanilla TypeScript SPA, no framework. Each UI concern is a separate module: - `main.ts` — app shell, routing (`#file=path`), file fetching, scroll memory, code-block copy buttons @@ -37,6 +39,7 @@ No linter/formatter configured; TypeScript strict mode is the quality gate. - `filetree.ts` / `tabs.ts` / `toc.ts` / `search.ts` / `find-bar.ts` — sidebar, tabs, TOC, search modal, vim-style find - `json-tree.ts` / `yaml-tree.ts` / `csv-viewer.ts` — structured data viewers (tree views, tables) - `theme.ts` — light/dark toggle with localStorage persistence +- `text-diff.ts` (pure Myers line diff + intraline + unified patch, unit-tested from `tests/text-diff.test.mjs`) / `diff-view.ts` (diff modal: files, Git revisions, in-session snapshots) / `link-report.ts` (link check modal) **CLI (`bin/mdv.mjs`)** — Parses args, imports server, auto-opens browser. diff --git a/README.md b/README.md index dc1a0da..b491fa3 100644 --- a/README.md +++ b/README.md @@ -56,6 +56,10 @@ If the browser doesn't open, copy `http://localhost:4000` into any browser — i - **Text size** — adjust document text from 50% to 200% in 10% steps; preference is persisted - **Table of contents** — auto-generated TOC sidebar from heading structure - **Search** — full-text search across all files in the directory +- **Diff view** — compare any two text files side by side or unified, with word-level highlights, change navigation (`n` / `p`), whitespace-insensitive mode, expandable context, click-through to the line, and patch copy / `.patch` download. Right-click a file → *表示中の「…」と比較* or *比較元として選択* +- **Live change review** — when an open file is edited by another tool, a *変更あり +N −M* chip appears next to the breadcrumb; click it (or press `D`) to see exactly what changed since you opened it, and *確認済みにする* to reset the baseline +- **Git history** — for files in a Git repository, compare the working copy against `HEAD` or any of the last 30 commits that touched the file. The file tree marks uncommitted changes (`M` / `A` / `U`) and the filter menu adds *Git: 変更のみ*. Read-only: DocView only runs `git status`, `git log` and `git show` +- **Link check** — finds relative links, images, reference definitions and `[[wiki links]]` in Markdown whose target does not exist (resolved exactly as the viewer resolves them), with same-name files suggested as fixes. Per-document results appear in the TOC panel; right-click a folder (or the root name) for a report you can copy as a Markdown checklist. The report re-checks live as files change - **Tabs** — open multiple files as tabs within a single session ## Supported Formats @@ -142,6 +146,9 @@ docview ./docs --no-open | `Cmd/Ctrl + E` | Toggle table of contents | | `Cmd/Ctrl + Shift + E` | Toggle theme (dark / light) | | `Cmd/Ctrl + Shift + S` | Present as slides (Marp deck for `marp: true` files) | +| `D` | Diff the current file (changes since opened, else Git `HEAD`) | +| `n` / `p` (`j` / `k`) | Next / previous change in the diff view | +| `u` | Toggle side-by-side / unified diff | | `Cmd/Ctrl + =` / `-` / `0` | Increase / decrease / reset document text size | | `?` | Show keyboard shortcut help | | `↑` / `↓` | Navigate file list / search results | diff --git a/index.html b/index.html index 8551581..b9ae313 100644 --- a/index.html +++ b/index.html @@ -19,6 +19,7 @@

DocView

+
+ diff --git a/server.mjs b/server.mjs index b400502..7f6f8b9 100644 --- a/server.mjs +++ b/server.mjs @@ -4,7 +4,7 @@ import { readFile, readdir, stat, realpath, open } from 'node:fs/promises'; import { createInterface } from 'node:readline'; import { join, resolve, relative, extname, basename, dirname, sep } from 'node:path'; import { fileURLToPath } from 'node:url'; -import { spawn } from 'node:child_process'; +import { spawn, execFile } from 'node:child_process'; import { Readable } from 'node:stream'; import { isIP } from 'node:net'; import chokidar from 'chokidar'; @@ -175,6 +175,12 @@ function detectEncoding(buf) { /** * Read a file and decode to UTF-8 string, auto-detecting encoding. */ +function decodeTextBuffer(buf) { + const encoding = detectEncoding(buf); + if (encoding === 'utf-8') return buf.toString('utf-8', hasUtf8Bom(buf) ? 3 : 0); + return new TextDecoder(encoding).decode(buf); +} + async function readFileText(filePath) { const buf = await readFile(filePath); const encoding = detectEncoding(buf); @@ -1213,6 +1219,295 @@ async function safePath(reqPath) { } } +// --- Link check --- +// Finds relative links in Markdown documents whose target does not exist, +// resolving them exactly like the viewer does (URL resolution against the +// source file; wiki links default to `.md` and are relative to the source). + +const LINK_CHECK_EXT = new Set(['.md', '.markdown', '.mdx']); +const LINK_CHECK_MAX_FILES = 5000; +const LINK_CHECK_MAX_BROKEN = 1000; + +/** Blank out code spans/blocks (keeping newlines) so links inside code are ignored. */ +function stripMarkdownCode(text) { + const blank = (m) => m.replace(/[^\n]/g, ' '); + return text + .replace(/^( {0,3})(`{3,}|~{3,})[^\n]*\n[\s\S]*?(?:^\1?\2[`~]*[ \t]*$|(?![\s\S]))/gm, blank) + .replace(/(`+)(?!`)[\s\S]*?[^`]\1(?!`)/g, blank) + .replace(//g, blank); +} + +/** Extract { raw, dest, kind, index } for every inline, image, reference and wiki link. */ +function extractMarkdownLinks(text) { + const links = []; + const inline = /(!?)\[(?:[^\]\\]|\\.)*\]\(\s*(<[^>\n]*>|[^\s)]+)(?:\s+(?:"[^"]*"|'[^']*'|\([^)]*\)))?\s*\)/g; + let m; + while ((m = inline.exec(text)) !== null) { + let dest = m[2]; + if (dest.startsWith('<')) dest = dest.slice(1, -1); + links.push({ raw: m[0], dest, kind: m[1] ? 'image' : 'link', index: m.index }); + } + const reference = /^ {0,3}\[[^\]\n]+\]:\s*(<[^>\n]*>|\S+)/gm; + while ((m = reference.exec(text)) !== null) { + let dest = m[1]; + if (dest.startsWith('<')) dest = dest.slice(1, -1); + links.push({ raw: m[0].trim(), dest, kind: 'reference', index: m.index }); + } + const wiki = /\[\[([^[\]\n|]+)(?:\|[^[\]\n]*)?\]\]/g; + while ((m = wiki.exec(text)) !== null) { + const target = m[1].trim(); + const suffixStart = target.search(/[?#]/); + const path = suffixStart < 0 ? target : target.slice(0, suffixStart); + const filename = path.split('/').pop() || ''; + const dest = path && !filename.includes('.') ? `${path}.md${suffixStart < 0 ? '' : target.slice(suffixStart)}` : target; + links.push({ raw: m[0], dest, kind: 'wiki', index: m.index }); + } + return links.sort((a, b) => a.index - b.index); +} + +/** Resolve a link destination against its source file; null for external/in-page links. */ +function resolveLinkTarget(dest, sourcePath) { + const d = dest.trim(); + if (!d || d.startsWith('#') || /^(?:[a-z][a-z\d+.-]*:|\/\/)/i.test(d)) return null; + try { + const base = sourcePath.split('/').map(encodeURIComponent).join('/'); + const resolvedUrl = new URL(d, `https://docview.invalid/${base}`); + return decodeURIComponent(resolvedUrl.pathname.slice(1)); + } catch { + return undefined; // malformed — reported as broken + } +} + +async function checkLinks(scope) { + refreshDocviewIgnore(); + const docs = []; + const nameIndex = new Map(); // basename -> [relPath] + let truncated = false; + + async function walk(dir) { + let entries; + try { entries = await readdir(dir, { withFileTypes: true }); } catch { return; } + for (const entry of entries) { + const fullPath = join(dir, entry.name); + const rel = relative(targetDir, fullPath).replace(/\\/g, '/'); + if (entry.isSymbolicLink() && !await safePath(rel)) continue; + let isDir = entry.isDirectory(); + if (entry.isSymbolicLink()) { + try { isDir = (await stat(fullPath)).isDirectory(); } catch { continue; } + } + if (isDir) { + if (shouldSkipDir(entry.name, rel)) continue; + await walk(fullPath); + } else { + if (shouldSkipFile(entry.name, rel)) continue; + const list = nameIndex.get(entry.name) || []; + list.push(rel); + nameIndex.set(entry.name, list); + if (!LINK_CHECK_EXT.has(extname(entry.name).toLowerCase())) continue; + if (scope && rel !== scope && !rel.startsWith(`${scope}/`)) continue; + if (docs.length >= LINK_CHECK_MAX_FILES) { truncated = true; continue; } + docs.push({ rel, fullPath }); + } + } + } + await walk(targetDir); + + const existsCache = new Map(); + async function exists(relPath) { + if (existsCache.has(relPath)) return existsCache.get(relPath); + let ok = false; + const resolved = await safePath(relPath); + if (resolved) { + try { await stat(resolved); ok = true; } catch { ok = false; } + } + existsCache.set(relPath, ok); + return ok; + } + + const broken = []; + let totalLinks = 0; + docs.sort((a, b) => a.rel.localeCompare(b.rel)); + for (const doc of docs) { + let content; + try { + const st = await stat(doc.fullPath); + if (st.size > MAX_SEARCH_FILE_BYTES) continue; + content = await readFileText(doc.fullPath); + } catch { continue; } + const text = stripMarkdownCode(content.replace(/\r\n?/g, '\n')); + const lineStarts = [0]; + for (let i = 0; i < text.length; i++) if (text.charCodeAt(i) === 10) lineStarts.push(i + 1); + const lineOf = (index) => { + let lo = 0; + let hi = lineStarts.length - 1; + while (lo < hi) { + const mid = (lo + hi + 1) >> 1; + if (lineStarts[mid] <= index) lo = mid; else hi = mid - 1; + } + return lo + 1; + }; + for (const link of extractMarkdownLinks(text)) { + const target = resolveLinkTarget(link.dest, doc.rel); + if (target === null) continue; + totalLinks++; + let reason = null; + if (target === undefined) reason = 'invalid'; + else if (target !== '' && !await exists(target)) reason = 'missing'; // '' is the served root + if (!reason) continue; + const item = { + source: doc.rel, + line: lineOf(link.index), + kind: link.kind, + link: link.kind === 'wiki' ? link.raw : link.dest, + target: target ?? null, + reason, + suggestions: [], + }; + if (target) { + const candidates = nameIndex.get(basename(target)) || []; + item.suggestions = candidates.filter((c) => c !== target).slice(0, 3); + } + broken.push(item); + if (broken.length >= LINK_CHECK_MAX_BROKEN) { truncated = true; break; } + } + if (broken.length >= LINK_CHECK_MAX_BROKEN) break; + } + return { scope: scope || '', scannedFiles: docs.length, totalLinks, broken, truncated }; +} + +// --- Git history (read-only) --- +// Only `git log` / `git show :` are run, via execFile (no shell), +// with a validated revision, a timeout and an output cap. Paths go through +// safePath first, so history is limited to files inside the served root. + +const GIT_REV_RE = /^(?:HEAD(?:~\d{1,4})?|[0-9a-f]{7,40})$/; +const GIT_MAX_SHOW_BYTES = 8 * 1024 * 1024; + +function runGit(cwd, gitArgs, { maxBuffer = 1024 * 1024, encoding = 'utf8' } = {}) { + return new Promise((resolvePromise, rejectPromise) => { + execFile('git', [ + // Never run repo-configured helpers for these read-only queries. + '-c', 'core.fsmonitor=false', '-c', 'core.hooksPath=/dev/null', + '--no-pager', ...gitArgs, + ], { + cwd, + encoding, + maxBuffer, + timeout: 5000, + windowsHide: true, + env: { ...process.env, GIT_OPTIONAL_LOCKS: '0', GIT_TERMINAL_PROMPT: '0', LC_ALL: 'C' }, + }, (err, stdout, stderr) => { + if (err) { + const e = new Error(String(stderr || err.message || 'git failed').trim().split('\n')[0]); + e.code = err.code; + rejectPromise(e); + return; + } + resolvePromise(stdout); + }); + }); +} + +/** Resolve a request path to an existing regular file inside the root, or send an error. */ +async function resolveGitTarget(res, reqPath) { + if (!reqPath) { + sendJson(res, 400, { error: 'Missing path parameter' }); + return null; + } + const resolved = await safePath(reqPath); + if (!resolved) { + sendJson(res, 403, { error: 'Access denied' }); + return null; + } + try { + const s = await stat(resolved); + if (!s.isFile()) { + sendJson(res, 400, { error: `Not a file: ${reqPath}` }); + return null; + } + } catch { + sendJson(res, 404, { error: 'File not found' }); + return null; + } + return resolved; +} + +function sendJson(res, status, body) { + res.writeHead(status, { 'Content-Type': 'application/json; charset=utf-8', 'Cache-Control': 'no-store' }); + res.end(JSON.stringify(body)); +} + +const GIT_STATUS_MAX_ENTRIES = 5000; + +/** + * Working-tree status of files under the served root, keyed by root-relative + * path: modified | added | untracked | deleted | renamed. Null outside a repo. + */ +async function gitWorkingTreeStatus() { + refreshDocviewIgnore(); + const realRoot = await realpath(targetDir); + let toplevel; + try { + toplevel = (await runGit(realRoot, ['rev-parse', '--show-toplevel'])).trim(); + } catch { + return null; + } + const out = await runGit(realRoot, ['status', '--porcelain=v1', '-z', '--untracked-files=all', '--', '.'], { maxBuffer: 8 * 1024 * 1024 }); + const files = {}; + let count = 0; + let truncated = false; + const parts = out.split('\0'); + for (let i = 0; i < parts.length; i++) { + const entry = parts[i]; + if (entry.length < 4) continue; + const code = entry.slice(0, 2); + const repoPath = entry.slice(3); + // Renames/copies are followed by the original path as a separate field. + if (code[0] === 'R' || code[0] === 'C') i++; + if (code === '!!') continue; + const rel = relative(realRoot, join(toplevel, repoPath)).replace(/\\/g, '/'); + if (!rel || rel.startsWith('../') || rel === '..') continue; + // Match the tree: skipped / .docviewignore'd paths are not reported. + const segments = rel.split('/'); + let hidden = shouldSkipFile(segments[segments.length - 1], rel); + for (let j = 1; j < segments.length && !hidden; j++) { + hidden = shouldSkipDir(segments[j - 1], segments.slice(0, j).join('/')); + } + if (hidden) continue; + let state = 'modified'; + if (code === '??') state = 'untracked'; + else if (code[0] === 'A' || code[1] === 'A') state = 'added'; + else if (code[0] === 'D' || code[1] === 'D') state = 'deleted'; + else if (code[0] === 'R' || code[0] === 'C') state = 'renamed'; + files[rel] = state; + if (++count >= GIT_STATUS_MAX_ENTRIES) { truncated = true; break; } + } + return { files, truncated }; +} + +async function gitFileLog(resolved, limit) { + const cwd = dirname(resolved); + const out = await runGit(cwd, [ + 'log', '--follow', `--max-count=${limit}`, '--date=iso-strict', + '--format=%H%x1f%h%x1f%aI%x1f%an%x1f%s%x1e', '--', `./${basename(resolved)}`, + ]); + return out.split('\x1e').map((rec) => rec.trim()).filter(Boolean).map((rec) => { + const [hash, short, date, author, subject] = rec.split('\x1f'); + return { hash, short, date, author, subject }; + }); +} + +async function gitFileStatus(resolved) { + const cwd = dirname(resolved); + const out = await runGit(cwd, ['status', '--porcelain=v1', '--untracked-files=all', '--', `./${basename(resolved)}`]); + const line = out.split('\n').find(Boolean); + if (!line) return 'clean'; + const code = line.slice(0, 2); + if (code === '??') return 'untracked'; + if (code === '!!') return 'ignored'; + return 'modified'; +} + // MIME types for static files const MIME = { '.html': 'text/html; charset=utf-8', @@ -1787,6 +2082,83 @@ const server = createServer(async (req, res) => { return; } + // Broken relative links across Markdown documents (optionally scoped to a folder or file). + if (url.pathname === '/api/links/check') { + const rawScope = (url.searchParams.get('path') || '').replace(/^\/+|\/+$/g, ''); + if (rawScope) { + const resolved = await safePath(rawScope); + if (!resolved) { + sendJson(res, 403, { error: 'Access denied' }); + return; + } + try { await stat(resolved); } catch { + sendJson(res, 404, { error: 'Not found' }); + return; + } + } + try { + sendJson(res, 200, await checkLinks(rawScope)); + } catch { + sendJson(res, 500, { error: 'Internal server error' }); + } + return; + } + + // Changed files (vs HEAD and untracked) under the served root. + if (url.pathname === '/api/git/status') { + try { + const status = await gitWorkingTreeStatus(); + sendJson(res, 200, status ? { git: true, ...status } : { git: false, files: {}, truncated: false }); + } catch { + sendJson(res, 200, { git: false, files: {}, truncated: false }); + } + return; + } + + // Git history of a single served file: recent commits + working-tree status. + if (url.pathname === '/api/git/log') { + const resolved = await resolveGitTarget(res, url.searchParams.get('path')); + if (!resolved) return; + const limitParam = Number.parseInt(url.searchParams.get('limit') || '30', 10); + const limit = Number.isSafeInteger(limitParam) ? Math.min(Math.max(limitParam, 1), 200) : 30; + try { + const status = await gitFileStatus(resolved); + const commits = status === 'untracked' || status === 'ignored' ? [] : await gitFileLog(resolved, limit); + sendJson(res, 200, { git: true, status, commits }); + } catch { + // Not a repository, git missing, or a timeout — history is simply unavailable. + sendJson(res, 200, { git: false, status: null, commits: [] }); + } + return; + } + + // File content at a past revision (HEAD, HEAD~N or a commit hash). + if (url.pathname === '/api/git/show') { + const rev = url.searchParams.get('rev') || 'HEAD'; + if (!GIT_REV_RE.test(rev)) { + sendJson(res, 400, { error: 'Invalid revision' }); + return; + } + const resolved = await resolveGitTarget(res, url.searchParams.get('path')); + if (!resolved) return; + try { + const buf = await runGit(dirname(resolved), ['show', `${rev}:./${basename(resolved)}`], { + encoding: 'buffer', + maxBuffer: GIT_MAX_SHOW_BYTES, + }); + res.writeHead(200, { + 'Content-Type': 'text/plain; charset=utf-8', + 'Cache-Control': 'no-store', + 'X-Content-Type-Options': 'nosniff', + 'Content-Security-Policy': 'sandbox', + }); + res.end(decodeTextBuffer(buf)); + } catch (err) { + sendJson(res, 404, { error: `Not available at ${rev}: ${err.message}` }); + } + return; + } + if (url.pathname === '/api/remote') { if (!remoteEnabled) { res.writeHead(403, { 'Content-Type': 'application/json' }); diff --git a/src/diff-view.ts b/src/diff-view.ts new file mode 100644 index 0000000..67b9cf0 --- /dev/null +++ b/src/diff-view.ts @@ -0,0 +1,772 @@ +/** + * Diff view — compares two text sources side by side (or unified): + * - two files in the served directory, + * - a file against one of its Git revisions (HEAD, earlier commits), + * - a file against the snapshot taken when it was first opened in this + * session (live-change review while another tool edits it). + * Both sides re-diff automatically when the underlying file changes on disk. + */ +import { diffLines, diffInline, buildRows, toUnifiedPatch, type DiffResult, type DiffRow, type InlineSegment } from './text-diff'; +import { isSecretSafeModeEnabled, maskSecrets } from './secret-mask'; + +export type DiffSource = + | { kind: 'file'; path: string } + | { kind: 'git'; path: string; rev: string } + | { kind: 'snapshot'; path: string }; + +export interface Snapshot { + text: string; + takenAt: number; +} + +export interface DiffViewHooks { + /** In-session baseline of a file, if one was recorded. */ + getSnapshot: (path: string) => Snapshot | null; + /** Replace the baseline with the given text ("mark as reviewed"). */ + resetSnapshot: (path: string, text: string) => void; + /** Navigate the main viewer to a file location. */ + openLocation: (path: string, line: number) => void; + notify: (message: string) => void; +} + +interface GitCommit { + hash: string; + short: string; + date: string; + author: string; + subject: string; +} + +interface GitLog { + git: boolean; + status: 'clean' | 'modified' | 'untracked' | 'ignored' | null; + commits: GitCommit[]; +} + +type Layout = 'split' | 'unified'; + +const NON_TEXT_EXT = new Set([ + 'png', 'jpg', 'jpeg', 'gif', 'svg', 'webp', 'bmp', 'ico', 'avif', + 'mp4', 'm4v', 'webm', 'ogv', 'mov', + 'pdf', 'xls', 'xlsx', 'ppt', 'pptx', 'numbers', 'pages', 'key', +]); + +const MAX_DIFF_CHARS = 4 * 1024 * 1024; +const MAX_RENDER_ROWS = 20000; +const LAYOUT_KEY = 'docview.diffLayout'; +const IGNORE_WS_KEY = 'docview.diffIgnoreWhitespace'; + +/** True when a file can be compared as text. */ +export function isDiffablePath(path: string): boolean { + const name = path.split('/').pop() ?? path; + const dot = name.lastIndexOf('.'); + if (dot <= 0) return true; + return !NON_TEXT_EXT.has(name.slice(dot + 1).toLowerCase()); +} + +function esc(s: string): string { + return s.replace(/&/g, '&').replace(//g, '>').replace(/"/g, '"'); +} + +function baseName(path: string): string { + return path.split('/').pop() ?? path; +} + +function sourceKey(src: DiffSource): string { + if (src.kind === 'file') return `file:${src.path}`; + if (src.kind === 'snapshot') return `snap:${src.path}`; + return `git:${src.rev}:${src.path}`; +} + +function parseSourceKey(key: string): DiffSource | null { + if (key.startsWith('file:')) return { kind: 'file', path: key.slice(5) }; + if (key.startsWith('snap:')) return { kind: 'snapshot', path: key.slice(5) }; + const m = key.match(/^git:([^:]+):(.*)$/); + if (m) return { kind: 'git', rev: m[1], path: m[2] }; + return null; +} + +function formatTime(ts: number | string): string { + const d = new Date(ts); + if (Number.isNaN(d.getTime())) return String(ts); + const pad = (n: number) => String(n).padStart(2, '0'); + const today = new Date(); + const sameDay = d.toDateString() === today.toDateString(); + const hm = `${pad(d.getHours())}:${pad(d.getMinutes())}:${pad(d.getSeconds())}`; + return sameDay ? hm : `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())} ${hm.slice(0, 5)}`; +} + +function readPref(key: string): string | null { + try { return localStorage.getItem(key); } catch { return null; } +} + +function writePref(key: string, value: string): void { + try { localStorage.setItem(key, value); } catch { /* storage unavailable */ } +} + +function segmentsHtml(segs: InlineSegment[], cls: string): string { + return segs.map((s) => (s.changed ? `${esc(s.text)}` : esc(s.text))).join(''); +} + +export class DiffView { + private overlay: HTMLElement; + private dialog: HTMLElement; + private body: HTMLElement; + private oldSelect: HTMLSelectElement; + private newSelect: HTMLSelectElement; + private statsEl: HTMLElement; + private noticeEl: HTMLElement; + private layoutBtns: HTMLButtonElement[]; + private wsToggle: HTMLInputElement; + private changesOnlyToggle: HTMLInputElement; + private navLabel: HTMLElement; + private baselineBtn: HTMLButtonElement; + private hooks: DiffViewHooks; + + private oldSource: DiffSource | null = null; + private newSource: DiffSource | null = null; + private oldText = ''; + private newText = ''; + private result: DiffResult | null = null; + // Without a stored preference, narrow screens start in the single-column layout. + private layout: Layout = (readPref(LAYOUT_KEY) ?? (window.innerWidth < 720 ? 'unified' : 'split')) === 'unified' ? 'unified' : 'split'; + private ignoreWhitespace = readPref(IGNORE_WS_KEY) === 'true'; + private changesOnly = true; + private expandedSkips = new Set(); + private currentChange = -1; + private loadSeq = 0; + private gitLogs = new Map>(); + private fileList: Promise | null = null; + private returnFocus: HTMLElement | null = null; + private reloadTimer: ReturnType | null = null; + + constructor(hooks: DiffViewHooks) { + this.hooks = hooks; + this.overlay = document.createElement('div'); + this.overlay.className = 'diff-overlay'; + this.overlay.hidden = true; + this.overlay.setAttribute('role', 'dialog'); + this.overlay.setAttribute('aria-modal', 'true'); + this.overlay.setAttribute('aria-labelledby', 'diff-title'); + this.overlay.innerHTML = ` +
+
+
+

差分

+
+ + + +
+ +
+
+ +
+ + + +
+
+ + +
+ + + + + + +
+ +
+
+
`; + document.body.appendChild(this.overlay); + + const q = (sel: string) => this.overlay.querySelector(sel)!; + this.dialog = q('.diff-modal'); + this.body = q('.diff-body'); + this.oldSelect = q('select[data-side="old"]'); + this.newSelect = q('select[data-side="new"]'); + this.statsEl = q('.diff-stats'); + this.noticeEl = q('.diff-notice'); + this.navLabel = q('.diff-nav-label'); + this.wsToggle = q('.diff-ignore-ws'); + this.changesOnlyToggle = q('.diff-changes-only'); + this.baselineBtn = q('.diff-baseline'); + this.layoutBtns = Array.from(this.overlay.querySelectorAll('[data-layout]')); + this.wsToggle.checked = this.ignoreWhitespace; + + q('.diff-close').addEventListener('click', () => this.close()); + q('.diff-swap').addEventListener('click', () => this.swap()); + q('.diff-prev').addEventListener('click', () => this.gotoChange(-1)); + q('.diff-next').addEventListener('click', () => this.gotoChange(1)); + q('.diff-copy-patch').addEventListener('click', () => void this.copyPatch()); + q('.diff-download-patch').addEventListener('click', () => this.downloadPatch()); + this.baselineBtn.addEventListener('click', () => this.markReviewed()); + this.layoutBtns.forEach((btn) => btn.addEventListener('click', () => { + this.layout = btn.dataset.layout === 'unified' ? 'unified' : 'split'; + writePref(LAYOUT_KEY, this.layout); + this.renderBody(); + })); + this.wsToggle.addEventListener('change', () => { + this.ignoreWhitespace = this.wsToggle.checked; + writePref(IGNORE_WS_KEY, String(this.ignoreWhitespace)); + this.recompute(); + }); + this.changesOnlyToggle.addEventListener('change', () => { + this.changesOnly = this.changesOnlyToggle.checked; + this.expandedSkips.clear(); + this.renderBody(); + }); + for (const select of [this.oldSelect, this.newSelect]) { + select.addEventListener('change', () => void this.onSelectChange(select)); + } + this.overlay.addEventListener('click', (e) => { + if (e.target === this.overlay) this.close(); + }); + this.body.addEventListener('click', (e) => this.onBodyClick(e)); + this.overlay.addEventListener('keydown', (e) => this.onKeydown(e)); + } + + get isOpen(): boolean { + return !this.overlay.hidden; + } + + /** Open the view comparing `oldSource` (left) to `newSource` (right). */ + async open(oldSource: DiffSource, newSource: DiffSource): Promise { + if (!this.isOpen) { + this.returnFocus = document.activeElement instanceof HTMLElement ? document.activeElement : null; + this.overlay.hidden = false; + document.documentElement.classList.add('diff-open'); + } + this.oldSource = oldSource; + this.newSource = newSource; + this.expandedSkips.clear(); + this.currentChange = -1; + this.dialog.focus(); + await this.load(); + } + + close(): void { + if (!this.isOpen) return; + ++this.loadSeq; + this.overlay.hidden = true; + document.documentElement.classList.remove('diff-open'); + this.body.innerHTML = ''; + if (this.reloadTimer) clearTimeout(this.reloadTimer); + const focus = this.returnFocus; + this.returnFocus = null; + if (focus?.isConnected) focus.focus(); + } + + /** Called on file-change / unlink events so open comparisons stay live. */ + notifyFileChanged(path: string): void { + this.gitLogs.delete(path); + if (!this.isOpen) return; + const touches = (src: DiffSource | null) => src !== null && src.path === path && src.kind === 'file'; + if (!touches(this.oldSource) && !touches(this.newSource)) return; + if (this.reloadTimer) clearTimeout(this.reloadTimer); + this.reloadTimer = setTimeout(() => void this.load({ keepPosition: true }), 150); + } + + /** Forget cached file listings so new files show up in the selector. */ + invalidateFileList(): void { + this.fileList = null; + } + + // --- Loading --- + + private async fetchText(src: DiffSource): Promise { + if (src.kind === 'snapshot') { + const snap = this.hooks.getSnapshot(src.path); + if (!snap) throw new Error('このセッションで記録した内容がありません'); + return snap.text; + } + const url = src.kind === 'file' + ? `/api/file?path=${encodeURIComponent(src.path)}` + : `/api/git/show?path=${encodeURIComponent(src.path)}&rev=${encodeURIComponent(src.rev)}`; + const res = await fetch(url, { cache: 'no-store' }); + if (!res.ok) { + let detail = `${res.status}`; + try { detail = (await res.json()).error ?? detail; } catch { /* not JSON */ } + if (src.kind === 'git' && res.status === 404) throw new Error(`${src.rev} にこのファイルは存在しません`); + throw new Error(detail); + } + const text = await res.text(); + if (text.length > MAX_DIFF_CHARS) throw new Error('ファイルが大きすぎるため比較できません (上限 4 MB)'); + return text; + } + + private gitLog(path: string): Promise { + let p = this.gitLogs.get(path); + if (!p) { + p = fetch(`/api/git/log?path=${encodeURIComponent(path)}&limit=30`, { cache: 'no-store' }) + .then((r) => (r.ok ? r.json() as Promise : { git: false, status: null, commits: [] })) + .catch(() => ({ git: false, status: null, commits: [] } as GitLog)); + this.gitLogs.set(path, p); + p.catch(() => this.gitLogs.delete(path)); + } + return p; + } + + private getFileList(): Promise { + if (!this.fileList) { + this.fileList = fetch('/api/tree', { cache: 'no-store' }) + .then((r) => r.json()) + .then((data: { tree?: Array<{ path: string; type: string; children?: unknown[] }> }) => { + const out: string[] = []; + const walk = (nodes: Array<{ path: string; type: string; children?: unknown[] }>) => { + for (const n of nodes) { + if (n.type === 'file' && isDiffablePath(n.path)) out.push(n.path); + else if (n.children) walk(n.children as typeof nodes); + } + }; + walk(data.tree ?? []); + return out.sort(); + }) + .catch(() => { + this.fileList = null; + return []; + }); + } + return this.fileList; + } + + private async load(opts: { keepPosition?: boolean } = {}): Promise { + const seq = ++this.loadSeq; + const oldSrc = this.oldSource; + const newSrc = this.newSource; + if (!oldSrc || !newSrc) return; + const scrollTop = this.body.scrollTop; + if (!opts.keepPosition) this.body.innerHTML = '
読み込み中…
'; + void this.populateSelectors(); + this.updateTitle(); + + let oldText: string; + let newText: string; + try { + [oldText, newText] = await Promise.all([this.fetchText(oldSrc), this.fetchText(newSrc)]); + } catch (err) { + if (seq !== this.loadSeq) return; + this.result = null; + this.statsEl.textContent = ''; + this.navLabel.textContent = ''; + this.body.innerHTML = ``; + this.updateBaselineButton(); + return; + } + if (seq !== this.loadSeq) return; + if (isSecretSafeModeEnabled()) { + oldText = maskSecrets(oldText); + newText = maskSecrets(newText); + } + this.oldText = oldText; + this.newText = newText; + this.recompute(); + if (opts.keepPosition) this.body.scrollTop = scrollTop; + else if (this.currentChange < 0 && (this.result?.stats.changes ?? 0) > 0) this.gotoChange(1); + } + + private recompute(): void { + this.result = diffLines(this.oldText, this.newText, { ignoreWhitespace: this.ignoreWhitespace }); + if (this.currentChange >= this.result.stats.changes) this.currentChange = this.result.stats.changes - 1; + this.renderBody(); + } + + // --- Selectors --- + + private sourceLabel(src: DiffSource): string { + if (src.kind === 'file') return src.path; + if (src.kind === 'snapshot') { + const snap = this.hooks.getSnapshot(src.path); + return `${src.path} @ 開いた時点${snap ? ` (${formatTime(snap.takenAt)})` : ''}`; + } + return `${src.path} @ ${src.rev}`; + } + + private updateTitle(): void { + const title = this.overlay.querySelector('.diff-title')!; + const o = this.oldSource; + const n = this.newSource; + if (!o || !n) return; + title.textContent = o.path === n.path ? `差分: ${baseName(n.path)}` : `差分: ${baseName(o.path)} ↔ ${baseName(n.path)}`; + title.setAttribute('title', `${this.sourceLabel(o)} → ${this.sourceLabel(n)}`); + } + + private async populateSelectors(): Promise { + const oldSrc = this.oldSource; + const newSrc = this.newSource; + if (!oldSrc || !newSrc) return; + const paths = Array.from(new Set([newSrc.path, oldSrc.path])); + const logs = await Promise.all(paths.map((p) => this.gitLog(p))); + if (oldSrc !== this.oldSource || newSrc !== this.newSource) return; + + const build = (selected: DiffSource) => { + const groups: string[] = []; + for (let i = 0; i < paths.length; i++) { + const path = paths[i]; + const log = logs[i]; + const opts: string[] = []; + opts.push(this.option({ kind: 'file', path }, `現在のファイル — ${path}`, selected)); + if (this.hooks.getSnapshot(path)) { + opts.push(this.option({ kind: 'snapshot', path }, `開いた時点 (${formatTime(this.hooks.getSnapshot(path)!.takenAt)})`, selected)); + } + if (log.git && log.commits.length > 0) { + opts.push(this.option({ kind: 'git', path, rev: 'HEAD' }, 'Git: HEAD (最新コミット)', selected)); + for (const c of log.commits) { + const subject = c.subject.length > 60 ? `${c.subject.slice(0, 57)}…` : c.subject; + opts.push(this.option({ kind: 'git', path, rev: c.short }, `Git: ${c.short} ${formatTime(c.date)} ${subject}`, selected)); + } + } + groups.push(`${opts.join('')}`); + } + // Keep a selected source that isn't otherwise listed (e.g. an old commit beyond the log limit). + const key = sourceKey(selected); + const listed = groups.some((g) => g.includes(`value="${esc(key)}"`)); + const extra = listed ? '' : ``; + return `${extra}${groups.join('')}`; + }; + this.oldSelect.innerHTML = build(oldSrc); + this.newSelect.innerHTML = build(newSrc); + this.oldSelect.title = this.sourceLabel(oldSrc); + this.newSelect.title = this.sourceLabel(newSrc); + } + + private option(src: DiffSource, label: string, selected: DiffSource): string { + const key = sourceKey(src); + return ``; + } + + private async onSelectChange(select: HTMLSelectElement): Promise { + const side = select.dataset.side === 'old' ? 'old' : 'new'; + const current = side === 'old' ? this.oldSource : this.newSource; + let next: DiffSource | null; + if (select.value === '__other__') { + next = await this.pickFile(current?.path ?? ''); + if (!next) { + if (current) select.value = sourceKey(current); + return; + } + } else { + next = parseSourceKey(select.value); + } + if (!next) return; + if (side === 'old') this.oldSource = next; else this.newSource = next; + this.expandedSkips.clear(); + this.currentChange = -1; + await this.load(); + } + + /** Inline picker: a filterable input over every diffable file in the tree. */ + private pickFile(initial: string): Promise { + return new Promise((resolveChoice) => { + const existing = this.overlay.querySelector('.diff-picker'); + existing?.remove(); + const picker = document.createElement('form'); + picker.className = 'diff-picker'; + const listId = `diff-picker-list-${Date.now()}`; + picker.innerHTML = ` + + + + + `; + this.noticeEl.after(picker); + const input = picker.querySelector('input')!; + const list = picker.querySelector('datalist')!; + const error = picker.querySelector('.diff-picker-error')!; + input.value = initial; + input.select(); + input.focus(); + let files: string[] = []; + void this.getFileList().then((f) => { + files = f; + list.innerHTML = f.map((p) => ``).join(''); + }); + const finish = (choice: DiffSource | null) => { + picker.remove(); + resolveChoice(choice); + this.dialog.focus(); + }; + picker.addEventListener('submit', (e) => { + e.preventDefault(); + const value = input.value.trim().replace(/^\/+/, ''); + if (!value) return; + if (files.length > 0 && !files.includes(value)) { + error.textContent = '一覧にないファイルです'; + return; + } + if (!isDiffablePath(value)) { + error.textContent = 'テキストとして比較できない形式です'; + return; + } + finish({ kind: 'file', path: value }); + }); + picker.querySelector('.diff-picker-cancel')!.addEventListener('click', () => finish(null)); + input.addEventListener('keydown', (e) => { + if (e.key === 'Escape') { e.preventDefault(); e.stopPropagation(); finish(null); } + }); + }); + } + + private swap(): void { + if (!this.oldSource || !this.newSource) return; + [this.oldSource, this.newSource] = [this.newSource, this.oldSource]; + [this.oldText, this.newText] = [this.newText, this.oldText]; + this.expandedSkips.clear(); + this.currentChange = -1; + void this.populateSelectors(); + this.updateTitle(); + this.recompute(); + } + + // --- Rendering --- + + private visibleRows(): DiffRow[] { + const result = this.result!; + const rows = buildRows(result, this.changesOnly ? 3 : -1); + if (this.expandedSkips.size === 0) return rows; + const out: DiffRow[] = []; + for (const row of rows) { + if (row.kind !== 'skip' || !this.expandedSkips.has(row.oldStart)) { out.push(row); continue; } + for (let i = 0; i < row.count; i++) { + const o = row.oldStart - 1 + i; + const n = row.newStart - 1 + i; + out.push({ kind: 'equal', old: { line: o + 1, text: result.oldLines[o] }, new: { line: n + 1, text: result.newLines[n] } }); + } + } + return out; + } + + private renderBody(): void { + const result = this.result; + this.layoutBtns.forEach((btn) => btn.setAttribute('aria-pressed', String(btn.dataset.layout === this.layout))); + this.updateBaselineButton(); + if (!result) return; + const { added, removed, changes } = result.stats; + this.statsEl.innerHTML = changes === 0 + ? '差分なし' + : `+${added} −${removed} ${changes} 箇所`; + const notices: string[] = []; + if (result.approximate) notices.push('変更量が多いため、差分は概算で表示しています。'); + if (this.ignoreWhitespace && changes === 0 && this.oldText !== this.newText) notices.push('空白以外の差分はありません。'); + if (isSecretSafeModeEnabled()) notices.push('Secret Safe モード: 機密値はマスクして比較しています。'); + this.noticeEl.hidden = notices.length === 0; + this.noticeEl.textContent = notices.join(' '); + + if (changes === 0 && this.changesOnly) { + this.body.innerHTML = `
${this.oldText === this.newText ? '内容は同一です。' : '比較条件の範囲では同一です。'}
`; + this.updateNav(); + return; + } + + const rows = this.visibleRows(); + const truncated = rows.length > MAX_RENDER_ROWS; + const shown = truncated ? rows.slice(0, MAX_RENDER_ROWS) : rows; + const oldNav = this.oldSource?.kind === 'file' ? this.oldSource.path : null; + const newNav = this.newSource?.kind === 'file' ? this.newSource.path : null; + const num = (cell: { line: number } | null, nav: string | null, side: string) => { + if (!cell) return ``; + if (!nav) return `${cell.line}`; + return ``; + }; + const parts: string[] = []; + let lastChange = -1; + const colspan = this.layout === 'split' ? 4 : 3; + for (const row of shown) { + if (row.kind === 'skip') { + parts.push(``); + continue; + } + let oldHtml: string; + let newHtml: string; + let anchor = ''; + if (row.kind === 'equal') { + oldHtml = esc(row.old.text); + newHtml = esc(row.new.text); + } else { + if (row.changeIndex !== lastChange) { + anchor = ` data-change="${row.changeIndex}"`; + lastChange = row.changeIndex; + } + const inline = row.old && row.new ? diffInline(row.old.text, row.new.text) : null; + oldHtml = row.old ? (inline ? segmentsHtml(inline.old, 'diff-word-del') : esc(row.old.text)) : ''; + newHtml = row.new ? (inline ? segmentsHtml(inline.new, 'diff-word-add') : esc(row.new.text)) : ''; + } + if (this.layout === 'split') { + const oldCls = row.kind === 'equal' ? '' : row.old ? ' diff-cell--del' : ' diff-cell--empty'; + const newCls = row.kind === 'equal' ? '' : row.new ? ' diff-cell--add' : ' diff-cell--empty'; + parts.push(`${num(row.old, oldNav, 'old')}${oldHtml}${num(row.new, newNav, 'new')}${newHtml}`); + } else if (row.kind === 'equal') { + parts.push(`${num(row.old, oldNav, 'old')}${num(row.new, newNav, 'new')} ${newHtml}`); + } else { + // Unified: deletions of a block are emitted before its insertions by + // splitting paired rows — collect into the block's del/ins lists. + parts.push(``); + if (row.old) parts.push(`${num(row.old, oldNav, 'old')}-${oldHtml}`); + if (row.new) parts.push(`${num(row.new, newNav, 'new')}+${newHtml}`); + } + } + let html = parts.join(''); + if (this.layout === 'unified') html = this.reorderUnified(parts); + const tableCls = this.layout === 'split' ? 'diff-table diff-table--split' : 'diff-table diff-table--unified'; + const cols = this.layout === 'split' + ? '' + : ''; + this.body.innerHTML = `${cols}${html}
${truncated ? `
表示行数の上限 (${MAX_RENDER_ROWS.toLocaleString()} 行) に達したため以降を省略しました。パッチのコピー/保存には全体が含まれます。
` : ''}`; + this.updateNav(); + } + + /** In unified layout, list all deletions of a change block before its insertions. */ + private reorderUnified(parts: string[]): string { + const out: string[] = []; + let i = 0; + while (i < parts.length) { + const marker = parts[i].match(/^$/); + if (!marker) { out.push(parts[i]); i++; continue; } + const block = marker[1]; + const dels: string[] = []; + const adds: string[] = []; + while (i < parts.length) { + const m = parts[i].match(/^$/); + if (m) { + if (m[1] !== block) break; + i++; + continue; + } + if (!parts[i].includes(`data-u="${block}"`)) break; + (parts[i].includes('diff-u-del') ? dels : adds).push(parts[i]); + i++; + } + const rows = [...dels, ...adds]; + if (rows.length > 0) rows[0] = rows[0].replace(' el.classList.remove('diff-row--current')); + if (this.currentChange >= 0) { + this.body.querySelectorAll(`[data-change="${this.currentChange}"]`).forEach((el) => el.classList.add('diff-row--current')); + } + } + + private gotoChange(delta: number): void { + const total = this.result?.stats.changes ?? 0; + if (total === 0) return; + let next = this.currentChange + delta; + if (this.currentChange < 0 && delta < 0) next = total - 1; + if (next < 0) next = total - 1; + if (next >= total) next = 0; + // A change may sit inside collapsed rows only when "changes only" is off, + // which renders everything, so every change has an anchor row. + this.currentChange = next; + this.updateNav(); + const row = this.body.querySelector(`[data-change="${next}"]`); + row?.scrollIntoView({ block: 'center' }); + } + + private onBodyClick(e: Event): void { + const target = e.target as HTMLElement; + const expand = target.closest('.diff-expand'); + if (expand) { + this.expandedSkips.add(Number(expand.dataset.oldStart)); + const top = this.body.scrollTop; + this.renderBody(); + this.body.scrollTop = top; + return; + } + const link = target.closest('.diff-line-link'); + if (link?.dataset.path) { + const line = Number(link.dataset.line); + this.close(); + this.hooks.openLocation(link.dataset.path, line); + } + } + + private onKeydown(e: KeyboardEvent): void { + if (e.key === 'Escape') { + e.preventDefault(); + e.stopPropagation(); + this.close(); + return; + } + const target = e.target as HTMLElement; + if (target.closest('input, select, textarea, form')) return; + if (e.metaKey || e.ctrlKey || e.altKey) return; + if (e.key === 'n' || e.key === 'j') { e.preventDefault(); this.gotoChange(1); } + else if (e.key === 'p' || e.key === 'k') { e.preventDefault(); this.gotoChange(-1); } + else if (e.key === 'u') { e.preventDefault(); this.layout = this.layout === 'split' ? 'unified' : 'split'; writePref(LAYOUT_KEY, this.layout); this.renderBody(); } + else if (e.key === 'Tab') this.trapFocus(e); + } + + private trapFocus(e: KeyboardEvent): void { + const focusables = Array.from(this.dialog.querySelectorAll('button:not([hidden]), select, input, [tabindex="0"]')) + .filter((el) => el.offsetParent !== null); + if (focusables.length === 0) return; + const first = focusables[0]; + const last = focusables[focusables.length - 1]; + if (e.shiftKey && document.activeElement === first) { e.preventDefault(); last.focus(); } + else if (!e.shiftKey && document.activeElement === last) { e.preventDefault(); first.focus(); } + } + + // --- Baseline / export --- + + private updateBaselineButton(): void { + const snapSide = this.oldSource?.kind === 'snapshot' && this.newSource?.kind === 'file' && this.oldSource.path === this.newSource.path; + this.baselineBtn.hidden = !snapSide || !this.result || this.result.stats.changes === 0; + } + + private markReviewed(): void { + if (this.oldSource?.kind !== 'snapshot' || this.newSource?.kind !== 'file') return; + // Store the unmasked current file, not the possibly masked display text. + const path = this.newSource.path; + void fetch(`/api/file?path=${encodeURIComponent(path)}`, { cache: 'no-store' }) + .then((r) => (r.ok ? r.text() : Promise.reject(new Error(String(r.status))))) + .then((text) => { + this.hooks.resetSnapshot(path, text); + this.hooks.notify('現在の内容を確認済みにしました'); + void this.load(); + }) + .catch(() => this.hooks.notify('基準の更新に失敗しました')); + } + + private patchText(): string { + if (!this.result || !this.oldSource || !this.newSource) return ''; + const label = (src: DiffSource, prefix: string) => + src.kind === 'file' ? `${prefix}/${src.path}` : src.kind === 'git' ? `${prefix}/${src.path}\t(${src.rev})` : `${prefix}/${src.path}\t(snapshot)`; + return toUnifiedPatch(this.result, label(this.oldSource, 'a'), label(this.newSource, 'b')); + } + + private async copyPatch(): Promise { + const patch = this.patchText(); + if (!patch) { this.hooks.notify('差分がありません'); return; } + try { + await navigator.clipboard.writeText(patch); + this.hooks.notify('パッチをコピーしました'); + } catch { + this.hooks.notify('クリップボードにコピーできませんでした'); + } + } + + private downloadPatch(): void { + const patch = this.patchText(); + if (!patch) { this.hooks.notify('差分がありません'); return; } + const blob = new Blob([patch], { type: 'text/x-diff;charset=utf-8' }); + const a = document.createElement('a'); + a.href = URL.createObjectURL(blob); + a.download = `${baseName(this.newSource!.path).replace(/\.[^.]+$/, '') || 'diff'}.patch`; + document.body.appendChild(a); + a.click(); + a.remove(); + setTimeout(() => URL.revokeObjectURL(a.href), 1000); + } +} diff --git a/src/filetree.ts b/src/filetree.ts index 7cd0099..0f77ecf 100644 --- a/src/filetree.ts +++ b/src/filetree.ts @@ -45,6 +45,25 @@ function formatAbsolute(iso: string): string { return `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())} ${pad(d.getHours())}:${pad(d.getMinutes())}`; } +type GitFileState = 'modified' | 'added' | 'untracked' | 'deleted' | 'renamed'; + +interface GitStatusResponse { + git: boolean; + files: Record; + truncated: boolean; +} + +const GIT_BADGE: Record = { + modified: { letter: 'M', label: '変更あり (未コミット)' }, + added: { letter: 'A', label: '追加 (未コミット)' }, + untracked: { letter: 'U', label: 'Git 未追跡' }, + deleted: { letter: 'D', label: '削除' }, + renamed: { letter: 'R', label: '名前変更' }, +}; + +/** Value of the filter select that shows only files with uncommitted Git changes. */ +const GIT_FILTER_VALUE = 'git'; + interface TreeResponse { root: string; path: string; @@ -66,6 +85,16 @@ export interface FileTreeActions { revealInOS?: (folderPath: string) => void; /** Resolve a tree-relative path to an absolute filesystem path, or null. */ absPath?: (relPath: string) => string | null; + /** Whether a file can be compared as text. */ + canDiff?: (path: string) => boolean; + /** Path of the file currently shown in the main viewer. */ + currentPath?: () => string | null; + /** Open the diff view comparing two files (old → new). */ + compareFiles?: (oldPath: string, newPath: string) => void; + /** Open the diff view for a file's own history (session baseline / Git). */ + showHistory?: (path: string) => void; + /** Open the broken-link report for a folder ('' = served root) or document. */ + checkLinks?: (path: string) => void; } // --- File type icons (#1, SVG) --- @@ -183,6 +212,8 @@ export class FileTree { private onSelect: FileSelectCallback; private onAlbum: AlbumCallback | null; private actions: FileTreeActions; + /** File picked with "比較元として選択", awaiting a second file to compare with. */ + private compareBase: string | null = null; private activePath: string | null = null; private openDirs = new Set(); private treeData: FileNode[] = []; @@ -190,6 +221,12 @@ export class FileTree { private loadSeq = 0; /** Max age in days for the mtime filter; 0 (or NaN) means no time filter. */ private mtimeMaxDays = 0; + private gitOnly = false; + private gitFiles = new Map(); + /** Directories containing at least one changed file. */ + private gitDirs = new Set(); + private gitSeq = 0; + private gitOption: HTMLOptionElement | null = null; private contextMenuEl: HTMLElement | null = null; constructor( @@ -223,7 +260,7 @@ export class FileTree { // Modification-time filter — preset age ranges, combined with the text query (AND). this.mtimeSelect = document.createElement('select'); this.mtimeSelect.className = 'filetree-mtime-filter'; - this.mtimeSelect.setAttribute('aria-label', '更新時間で絞り込み'); + this.mtimeSelect.setAttribute('aria-label', '更新時間・Git の変更で絞り込み'); // days: 0 = no filter; negative = calendar-day cutoff (-1 today, -2 yesterday …); // positive = rolling N-day window. All presets are cumulative (lower bound only). const MTIME_OPTIONS: { label: string; days: number }[] = [ @@ -242,7 +279,8 @@ export class FileTree { this.mtimeSelect.appendChild(el); } this.mtimeSelect.addEventListener('change', () => { - this.mtimeMaxDays = Number(this.mtimeSelect.value); + this.gitOnly = this.mtimeSelect.value === GIT_FILTER_VALUE; + this.mtimeMaxDays = this.gitOnly ? 0 : Number(this.mtimeSelect.value); this.applyFilters(); }); @@ -264,6 +302,12 @@ export class FileTree { e.preventDefault(); this.showContextMenu(e.clientX, e.clientY, item.dataset.path, item.dataset.type === 'dir' ? 'dir' : 'file'); }); + // The root heading offers whole-site actions (link check of every document). + this.rootLabel.addEventListener('contextmenu', (e) => { + if (!this.actions.checkLinks) return; + e.preventDefault(); + this.showRootMenu(e.clientX, e.clientY); + }); document.addEventListener('click', () => this.hideContextMenu()); document.addEventListener('keydown', (e) => { if (e.key === 'Escape') this.hideContextMenu(); }); window.addEventListener('scroll', () => this.hideContextMenu(), true); @@ -283,6 +327,15 @@ export class FileTree { } } + private showRootMenu(x: number, y: number): void { + this.hideContextMenu(); + const entries: { label: string; run: () => void }[] = [ + { label: 'すべての文書のリンク切れをチェック', run: () => this.actions.checkLinks!('') }, + ]; + if (this.actions.revealInOS) entries.push({ label: 'フォルダを開く', run: () => this.actions.revealInOS!('') }); + this.renderMenu(x, y, entries); + } + private showContextMenu(x: number, y: number, path: string, type: 'file' | 'dir'): void { this.hideContextMenu(); const name = path.split('/').pop() || path; @@ -304,6 +357,36 @@ export class FileTree { if (type === 'file' && this.actions.openInApp) { entries.push({ label: 'アプリで開く', run: () => this.actions.openInApp!(path) }); } + if (type === 'file' && this.actions.compareFiles && this.actions.canDiff?.(path)) { + const compareFiles = this.actions.compareFiles; + const current = this.actions.currentPath?.() ?? null; + if (current && current !== path && this.actions.canDiff(current)) { + const currentName = current.split('/').pop() || current; + entries.push({ label: `表示中の「${currentName}」と比較`, run: () => compareFiles(current, path) }); + } + const base = this.compareBase; + if (base && base !== path) { + const baseName = base.split('/').pop() || base; + entries.push({ + label: `選択した「${baseName}」と比較`, + run: () => { this.compareBase = null; compareFiles(base, path); }, + }); + } + entries.push({ + label: '比較元として選択', + run: () => { + this.compareBase = path; + this.actions.notify?.(`比較元: ${name} — 比較したいファイルを右クリックしてください`); + }, + }); + } + if (type === 'file' && this.actions.showHistory && this.actions.canDiff?.(path)) { + entries.push({ label: '変更履歴・差分を表示', run: () => this.actions.showHistory!(path) }); + } + if (this.actions.checkLinks && (type === 'dir' || /\.(?:md|markdown|mdx)$/i.test(path))) { + const checkLinks = this.actions.checkLinks; + entries.push({ label: type === 'dir' ? 'このフォルダのリンク切れをチェック' : 'リンク切れをチェック', run: () => checkLinks(path) }); + } if (this.actions.revealInOS) { if (type === 'file') { // Parent folder of the file ('' when the file sits at the served root). @@ -313,7 +396,10 @@ export class FileTree { entries.push({ label: 'フォルダを開く', run: () => this.actions.revealInOS!(path) }); } } + this.renderMenu(x, y, entries); + } + private renderMenu(x: number, y: number, entries: { label: string; run: () => void }[]): void { const menu = document.createElement('div'); menu.className = 'filetree-context-menu'; menu.setAttribute('role', 'menu'); @@ -360,6 +446,7 @@ export class FileTree { if (query && !node.name.toLowerCase().includes(query) && !node.path.toLowerCase().includes(query)) { return false; } + if (this.gitOnly && !this.gitFiles.has(node.path)) return false; if (cutoff !== null) { if (!node.mtime) return false; const t = new Date(node.mtime).getTime(); @@ -388,7 +475,7 @@ export class FileTree { /** Re-render the tree applying the active text + mtime filters. */ private applyFilters(): void { const cutoff = this.mtimeCutoff(); - const active = this.filterQuery !== '' || cutoff !== null; + const active = this.filterQuery !== '' || cutoff !== null || this.gitOnly; const display = active ? this.filterTree(this.treeData, this.filterQuery, cutoff) : this.treeData; this.renderTree(display, this.treeList, 0); } @@ -406,11 +493,65 @@ export class FileTree { this.rootLabel.textContent = data.root; this.treeData = data.tree; this.applyFilters(); + void this.refreshGitStatus(); } catch { if (seq === this.loadSeq) this.container.style.display = 'none'; } } + /** Re-read uncommitted Git changes and update the tree badges / filter. */ + async refreshGitStatus(): Promise { + const seq = ++this.gitSeq; + let data: GitStatusResponse; + try { + const res = await fetch('/api/git/status', { cache: 'no-store' }); + if (!res.ok) return; + data = await res.json(); + } catch { + return; + } + if (seq !== this.gitSeq) return; + const files = new Map(data.git ? Object.entries(data.files) : []); + const dirs = new Set(); + for (const path of files.keys()) { + const parts = path.split('/'); + for (let i = 1; i < parts.length; i++) dirs.add(parts.slice(0, i).join('/')); + } + const changed = files.size !== this.gitFiles.size + || [...files].some(([path, state]) => this.gitFiles.get(path) !== state); + this.gitFiles = files; + this.gitDirs = dirs; + this.updateGitOption(data.git); + if (changed) this.applyFilters(); + } + + private updateGitOption(available: boolean): void { + if (available && !this.gitOption) { + this.gitOption = document.createElement('option'); + this.gitOption.value = GIT_FILTER_VALUE; + this.mtimeSelect.appendChild(this.gitOption); + } + if (this.gitOption) this.gitOption.textContent = `Git: 変更のみ (${this.gitFiles.size})`; + if (!available && this.gitOption) { + if (this.gitOnly) { + this.gitOnly = false; + this.mtimeSelect.value = '0'; + } + this.gitOption.remove(); + this.gitOption = null; + } + } + + private gitBadge(path: string, type: 'file' | 'dir'): string { + if (type === 'dir') { + return this.gitDirs.has(path) ? '' : ''; + } + const state = this.gitFiles.get(path); + if (!state) return ''; + const badge = GIT_BADGE[state]; + return `${badge.letter}`; + } + private renderTree(nodes: FileNode[], parent: HTMLElement, depth: number) { parent.innerHTML = ''; for (const node of nodes) { @@ -449,7 +590,7 @@ export class FileTree { : ''; const renderDirInner = (open: boolean) => - `${ICON_CHEVRON}${open ? ICON_DIR_OPEN : ICON_DIR_CLOSED}${esc(node.name)}${albumBtnHtml}`; + `${ICON_CHEVRON}${open ? ICON_DIR_OPEN : ICON_DIR_CLOSED}${esc(node.name)}${this.gitBadge(node.path, 'dir')}${albumBtnHtml}`; item.innerHTML = renderDirInner(isOpen); @@ -500,7 +641,7 @@ export class FileTree { const tooltip = tooltipParts.join(' · '); metaHtml = `${esc(rel)}`; } - item.innerHTML = `${fileIcon(node.name)}${esc(node.name)}${metaHtml}`; + item.innerHTML = `${fileIcon(node.name)}${esc(node.name)}${this.gitBadge(node.path, 'file')}${metaHtml}`; if (this.activePath === node.path) { item.classList.add('active'); item.setAttribute('aria-selected', 'true'); diff --git a/src/help-modal.ts b/src/help-modal.ts index 16b6150..30dade9 100644 --- a/src/help-modal.ts +++ b/src/help-modal.ts @@ -26,6 +26,15 @@ function buildSections(): ShortcutSection[] { ['/', 'Find in document'], ], }, + { + title: 'Diff', + items: [ + ['D', 'Diff current file (changes since opened / Git HEAD)'], + ['n / p or j / k', 'Next / previous change'], + ['u', 'Toggle side-by-side / unified'], + ['Right-click file', 'Compare two files'], + ], + }, { title: 'View', items: [ diff --git a/src/link-report.ts b/src/link-report.ts new file mode 100644 index 0000000..b28266e --- /dev/null +++ b/src/link-report.ts @@ -0,0 +1,222 @@ +/** + * Link check report — lists relative links in Markdown documents whose + * target does not exist (inline links, images, reference definitions and wiki + * links), with same-name candidates as fix hints. Re-runs on file changes while + * open so fixes are confirmed live. + */ + +export interface BrokenLink { + source: string; + line: number; + kind: 'link' | 'image' | 'reference' | 'wiki'; + link: string; + target: string | null; + reason: 'missing' | 'invalid'; + suggestions: string[]; +} + +export interface LinkCheckResult { + scope: string; + scannedFiles: number; + totalLinks: number; + broken: BrokenLink[]; + truncated: boolean; +} + +export interface LinkReportHooks { + openLocation: (path: string, line: number | null) => void; + notify: (message: string) => void; +} + +const KIND_LABEL: Record = { + link: 'リンク', + image: '画像', + reference: '参照定義', + wiki: 'Wiki', +}; + +function esc(s: string): string { + return s.replace(/&/g, '&').replace(//g, '>').replace(/"/g, '"'); +} + +export async function fetchLinkCheck(scope: string): Promise { + const res = await fetch(`/api/links/check?path=${encodeURIComponent(scope)}`, { cache: 'no-store' }); + if (!res.ok) { + let detail = String(res.status); + try { detail = (await res.json()).error ?? detail; } catch { /* not JSON */ } + throw new Error(detail); + } + return res.json() as Promise; +} + +function reasonText(item: BrokenLink): string { + if (item.reason === 'invalid') return '不正な URL'; + return item.target ? `${item.target} が見つかりません` : '見つかりません'; +} + +/** Markdown checklist of broken links, suitable for an issue or PR comment. */ +export function linkReportMarkdown(result: LinkCheckResult): string { + const lines = [`## リンク切れ: ${result.broken.length} 件 (${result.scope || 'ルート'} / ${result.scannedFiles} ファイル)`, '']; + for (const item of result.broken) { + const hint = item.suggestions.length > 0 ? ` — 候補: ${item.suggestions.map((s) => `\`${s}\``).join(', ')}` : ''; + lines.push(`- [ ] \`${item.source}:${item.line}\` ${KIND_LABEL[item.kind]} \`${item.link}\` — ${reasonText(item)}${hint}`); + } + return `${lines.join('\n')}\n`; +} + +export class LinkReport { + private overlay: HTMLElement; + private dialog: HTMLElement; + private body: HTMLElement; + private summary: HTMLElement; + private titleEl: HTMLElement; + private hooks: LinkReportHooks; + private scope = ''; + private result: LinkCheckResult | null = null; + private seq = 0; + private timer: ReturnType | null = null; + private returnFocus: HTMLElement | null = null; + + constructor(hooks: LinkReportHooks) { + this.hooks = hooks; + this.overlay = document.createElement('div'); + this.overlay.className = 'linkcheck-overlay'; + this.overlay.hidden = true; + this.overlay.setAttribute('role', 'dialog'); + this.overlay.setAttribute('aria-modal', 'true'); + this.overlay.setAttribute('aria-labelledby', 'linkcheck-title'); + this.overlay.innerHTML = ` +
+
+

リンクチェック

+ + + + + +
+
+
`; + document.body.appendChild(this.overlay); + this.dialog = this.overlay.querySelector('.linkcheck-modal')!; + this.body = this.overlay.querySelector('.linkcheck-body')!; + this.summary = this.overlay.querySelector('.linkcheck-summary')!; + this.titleEl = this.overlay.querySelector('.linkcheck-title')!; + this.overlay.querySelector('.linkcheck-close')!.addEventListener('click', () => this.close()); + this.overlay.querySelector('.linkcheck-rerun')!.addEventListener('click', () => void this.run()); + this.overlay.querySelector('.linkcheck-copy')!.addEventListener('click', () => void this.copy()); + this.overlay.addEventListener('click', (e) => { + if (e.target === this.overlay) this.close(); + }); + this.overlay.addEventListener('keydown', (e) => { + if (e.key === 'Escape') { e.preventDefault(); e.stopPropagation(); this.close(); } + }); + this.body.addEventListener('click', (e) => { + const btn = (e.target as HTMLElement).closest('[data-open]'); + if (!btn) return; + const path = btn.dataset.open!; + const line = btn.dataset.line ? Number(btn.dataset.line) : null; + this.close(); + this.hooks.openLocation(path, line); + }); + } + + get isOpen(): boolean { + return !this.overlay.hidden; + } + + async open(scope: string): Promise { + if (!this.isOpen) { + this.returnFocus = document.activeElement instanceof HTMLElement ? document.activeElement : null; + this.overlay.hidden = false; + } + this.scope = scope; + this.titleEl.textContent = `リンクチェック: ${scope || 'すべての文書'}`; + this.dialog.focus(); + await this.run(); + } + + close(): void { + if (!this.isOpen) return; + ++this.seq; + if (this.timer) clearTimeout(this.timer); + this.overlay.hidden = true; + const focus = this.returnFocus; + this.returnFocus = null; + if (focus?.isConnected) focus.focus(); + } + + /** Re-check (debounced) after any file add/change/unlink while open. */ + notifyChange(): void { + if (!this.isOpen) return; + if (this.timer) clearTimeout(this.timer); + this.timer = setTimeout(() => void this.run(true), 400); + } + + private async run(quiet = false): Promise { + const seq = ++this.seq; + if (!quiet) { + this.summary.textContent = 'チェック中…'; + this.body.innerHTML = '
チェック中…
'; + } + let result: LinkCheckResult; + try { + result = await fetchLinkCheck(this.scope); + } catch (err) { + if (seq !== this.seq) return; + this.result = null; + this.summary.textContent = ''; + this.body.innerHTML = ``; + return; + } + if (seq !== this.seq) return; + this.result = result; + this.render(); + } + + private render(): void { + const result = this.result!; + const count = result.broken.length; + this.summary.innerHTML = `${result.scannedFiles} 文書 · ${result.totalLinks} リンク · ${count === 0 + ? 'リンク切れなし' + : `リンク切れ ${count}${result.truncated ? '+' : ''} 件`}`; + if (count === 0) { + this.body.innerHTML = `
${result.scannedFiles === 0 ? 'Markdown 文書がありません。' : 'すべての相対リンクの参照先が存在します。'}
`; + return; + } + const groups = new Map(); + for (const item of result.broken) { + const list = groups.get(item.source) ?? []; + list.push(item); + groups.set(item.source, list); + } + const parts: string[] = []; + if (result.truncated) parts.push('
件数またはファイル数が上限に達したため、一部のみ表示しています。フォルダを絞ってチェックしてください。
'); + for (const [source, items] of groups) { + parts.push(`

${items.length}

    `); + for (const item of items) { + const suggestions = item.suggestions.map((s) => + ``).join(' '); + parts.push(`
  • + + ${KIND_LABEL[item.kind]} + ${esc(item.link)} + ${esc(reasonText(item))} + ${suggestions ? `候補: ${suggestions}` : ''} +
  • `); + } + parts.push('
'); + } + this.body.innerHTML = parts.join(''); + } + + private async copy(): Promise { + if (!this.result) return; + try { + await navigator.clipboard.writeText(linkReportMarkdown(this.result)); + this.hooks.notify('リンクチェック結果をコピーしました'); + } catch { + this.hooks.notify('クリップボードにコピーできませんでした'); + } + } +} diff --git a/src/main.ts b/src/main.ts index aaaf75a..d69a185 100644 --- a/src/main.ts +++ b/src/main.ts @@ -18,6 +18,9 @@ import { ImageMetaPanel } from './image-meta-panel'; import { HelpModal } from './help-modal'; import { UrlBar } from './url-bar'; import { isSecretSafeModeEnabled, maskSecretValue, maskSecrets } from './secret-mask'; +import { DiffView, isDiffablePath, type DiffSource, type Snapshot } from './diff-view'; +import { diffLines } from './text-diff'; +import { LinkReport } from './link-report'; import DOMPurify from 'dompurify'; import hljs from 'highlight.js'; import './style.css'; @@ -257,6 +260,99 @@ const searchModal = new SearchModal(({ path, line }) => openFileLocation(path, l // --- Help modal (?) --- const helpModal = new HelpModal(); +// --- Diff view & live-change tracking --- +// The first text loaded for a path in this session is kept as its baseline, so +// edits made by another tool while the file is open can be reviewed as a diff. +const SNAPSHOT_LIMIT = 50; +const SNAPSHOT_MAX_CHARS = 4 * 1024 * 1024; +const liveSnapshots = new Map(); +const btnLiveChanges = document.getElementById('btn-live-changes') as HTMLButtonElement | null; +const btnDiff = document.getElementById('btn-diff') as HTMLButtonElement | null; + +function recordSnapshot(path: string, text: string, replace = false): void { + if (text.length > SNAPSHOT_MAX_CHARS) return; + if (liveSnapshots.has(path) && !replace) { + // Refresh LRU order without replacing the baseline. + const snap = liveSnapshots.get(path)!; + liveSnapshots.delete(path); + liveSnapshots.set(path, snap); + return; + } + liveSnapshots.delete(path); + liveSnapshots.set(path, { text, takenAt: Date.now() }); + while (liveSnapshots.size > SNAPSHOT_LIMIT) { + const oldest = liveSnapshots.keys().next().value; + if (oldest === undefined) break; + liveSnapshots.delete(oldest); + } +} + +/** Show "changed since opened" with +/− counts, or hide it when unchanged. */ +function updateLiveChangeChip(path: string | null, text: string | null): void { + if (!btnLiveChanges) return; + const snap = path ? liveSnapshots.get(path) : undefined; + if (!path || text === null || !snap || snap.text === text) { + btnLiveChanges.hidden = true; + btnLiveChanges.dataset.path = ''; + return; + } + const { stats } = diffLines(snap.text, text); + btnLiveChanges.hidden = false; + btnLiveChanges.dataset.path = path; + btnLiveChanges.innerHTML = `変更あり +${stats.added} −${stats.removed}`; + btnLiveChanges.setAttribute('aria-label', `開いてから変更されました: ${stats.added} 行追加、${stats.removed} 行削除。差分を表示`); +} + +const diffView = new DiffView({ + getSnapshot: (path) => liveSnapshots.get(path) ?? null, + resetSnapshot: (path, text) => { + recordSnapshot(path, text, true); + if (path === currentFilePath) updateLiveChangeChip(path, text); + }, + openLocation: (path, line) => openFileLocation(path, line, null, 'left'), + notify: (message) => showCopyToast(message), +}); + +/** Open the most useful diff for a file: unseen live edits first, then Git HEAD. */ +async function openDiffForFile(path: string | null): Promise { + if (!path || !isDiffablePath(path)) { + showCopyToast('テキストファイルを開いているときに使えます'); + return; + } + const working: DiffSource = { kind: 'file', path }; + if (btnLiveChanges && !btnLiveChanges.hidden && btnLiveChanges.dataset.path === path) { + await diffView.open({ kind: 'snapshot', path }, working); + return; + } + let base: DiffSource = liveSnapshots.has(path) ? { kind: 'snapshot', path } : working; + try { + const res = await fetch(`/api/git/log?path=${encodeURIComponent(path)}&limit=1`, { cache: 'no-store' }); + const log = res.ok ? await res.json() as { git: boolean; commits: unknown[] } : null; + if (log?.git && log.commits.length > 0) base = { kind: 'git', path, rev: 'HEAD' }; + } catch { /* no git history — fall back to the session baseline */ } + await diffView.open(base, working); +} + +/** Compare two served files (old → new). */ +function compareFiles(oldPath: string, newPath: string): void { + if (!isDiffablePath(oldPath) || !isDiffablePath(newPath)) { + showCopyToast('テキストとして比較できない形式です'); + return; + } + void diffView.open({ kind: 'file', path: oldPath }, { kind: 'file', path: newPath }); +} + +const linkReport = new LinkReport({ + openLocation: (path, line) => openFileLocation(path, line, null, 'left'), + notify: (message) => showCopyToast(message), +}); + +btnLiveChanges?.addEventListener('click', () => { + const path = btnLiveChanges.dataset.path; + if (path) void diffView.open({ kind: 'snapshot', path }, { kind: 'file', path }); +}); +btnDiff?.addEventListener('click', () => void openDiffForFile(currentFilePath)); + // --- URL bar (Cmd+L) --- const urlBar = new UrlBar((target) => { if (target.kind === 'local') { @@ -919,6 +1015,7 @@ function renderContent(content: string, path: string, target: HTMLElement = view if (target === viewer) { toc.update(); toc.loadBacklinks(path); + if (!sourceUrl && /\.(?:md|markdown|mdx)$/i.test(path)) void toc.loadBrokenLinks(path); } interceptRelativeLinks(sourceUrl ?? path, target, pane); addHeadingCopyButtons(target, path); @@ -2009,6 +2106,7 @@ async function loadServerFile(path: string) { const type = detectFileType(path); const fileChanged = currentFilePath !== path; currentFilePath = path; + if (fileChanged) updateLiveChangeChip(null, null); document.title = `${path} — DocView`; updateBreadcrumb(path); updatePaneLabels(); @@ -2223,6 +2321,8 @@ async function loadFullFile(path: string, seq: number) { updateBreadcrumb(path, mtime); const content = await res.text(); if (seq !== leftLoadSeq) return; + recordSnapshot(path, content); + updateLiveChangeChip(path, content); // Large file warning if (content.length > MAX_FILE_SIZE) { @@ -2394,6 +2494,7 @@ img{max-width:100%}h1,h2,h3{color:#1a1c2e} function handleKeyboard(e: KeyboardEvent) { if (e.isComposing || e.keyCode === 229) return; // keys driving an IME conversion if (helpModal.isOpen) return; + if (diffView.isOpen || linkReport.isOpen) return; const openPaneFindBar = [findBar, splitFindBar].find((bar) => bar?.active); if (openPaneFindBar) { if (e.key === 'Escape') { openPaneFindBar.close(); e.preventDefault(); } @@ -2417,6 +2518,14 @@ function handleKeyboard(e: KeyboardEvent) { // n/N for next/prev match when find was used } + // Diff for the current file (live edits since opened, else Git HEAD) + if ((e.key === 'd' || e.key === 'D') && !e.metaKey && !e.ctrlKey && !e.altKey && !isEditable + && !document.querySelector('.album-view, .slide-overlay, .marp-slide-overlay')) { + e.preventDefault(); + void openDiffForFile(activePane === 'right' && splitActive ? splitFilePath : currentFilePath); + return; + } + if (e.key === '?' && !e.metaKey && !e.ctrlKey && !isEditable) { e.preventDefault(); helpModal.toggle(); @@ -2500,6 +2609,16 @@ let _currentAlbumRecursive = false; // that changed during the outage is only picked up by resyncing on reconnect. let sseNeedsResync = false; +// Edits change Git status without a tree reload; coalesce bursts of events. +let gitStatusTimer: ReturnType | null = null; +function scheduleGitStatusRefresh() { + if (gitStatusTimer) clearTimeout(gitStatusTimer); + gitStatusTimer = setTimeout(() => { gitStatusTimer = null; void fileTree?.refreshGitStatus(); }, 600); +} + +// A commit made in a terminal changes status without touching watched files. +window.addEventListener('focus', () => scheduleGitStatusRefresh()); + function connectSSE() { const evtSource = new EventSource('/api/watch'); evtSource.onmessage = (event) => { @@ -2512,6 +2631,10 @@ function connectSSE() { } try { const data = JSON.parse(event.data) as { event: string; path: string }; + if (data.event === 'change' || data.event === 'unlink') diffView.notifyFileChanged(data.path); + if (data.event === 'add' || data.event === 'unlink') diffView.invalidateFileList(); + scheduleGitStatusRefresh(); + linkReport.notifyChange(); if (data.event === 'change' && data.path === currentFilePath) reloadCurrentFile(); if (data.event === 'change' && splitActive && data.path === splitFilePath) void loadIntoSplit(data.path); if (data.event === 'add' || data.event === 'unlink') fileTree?.refresh(); @@ -2928,12 +3051,21 @@ async function init() { openInApp, revealInOS, absPath: (rel) => (serverRootPath ? `${serverRootPath.replace(/\/$/, '')}/${rel}` : null), + canDiff: isDiffablePath, + currentPath: () => currentFilePath, + compareFiles, + showHistory: (path) => void openDiffForFile(path), + checkLinks: (path) => void linkReport.open(path), }, ); await fileTree.load(); // Wire up TOC backlinks to navigate files toc.setFileSelectCallback((path) => { void loadServerFile(path); collapseSidebarOnMobile(); }); + toc.setLinkCallbacks( + (path, line) => openFileLocation(path, line, null, 'left'), + (scope) => void linkReport.open(scope), + ); sidebarVisible = true; sidebar.classList.remove('sidebar-hidden'); diff --git a/src/style.css b/src/style.css index 4034254..22917a5 100644 --- a/src/style.css +++ b/src/style.css @@ -11359,3 +11359,376 @@ tr:hover .imp-copy { max-height: 50vh; } } + +/* ===== Diff view ===== */ +.diff-overlay { + position: fixed; + inset: 0; + z-index: 1000; + display: flex; + align-items: stretch; + justify-content: center; + padding: 24px; + background: rgba(0, 0, 0, 0.4); + backdrop-filter: blur(4px); +} +.diff-overlay[hidden] { display: none; } +.diff-modal:focus, +.diff-modal:focus-visible { outline: none; } +html.diff-open { overflow: hidden; } +.diff-modal { + display: flex; + flex-direction: column; + width: min(1400px, 100%); + min-height: 0; + background: var(--bg-primary); + color: var(--text-primary); + border: 1px solid var(--border); + border-radius: var(--radius-xl); + box-shadow: var(--shadow-lg); + overflow: hidden; + outline: none; +} +.diff-header { + display: flex; + flex-direction: column; + gap: 8px; + padding: 12px 16px; + border-bottom: 1px solid var(--border); + background: var(--bg-secondary); +} +.diff-header-row { + display: flex; + flex-wrap: wrap; + align-items: center; + gap: 8px 12px; +} +.diff-title { + margin: 0; + font-size: 15px; + font-weight: 600; + max-width: 32ch; + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; +} +.diff-sources { + display: flex; + flex: 1 1 420px; + flex-wrap: wrap; + align-items: center; + gap: 6px; + min-width: 0; +} +.diff-source { + display: flex; + flex: 1 1 200px; + align-items: center; + gap: 6px; + min-width: 0; +} +.diff-source-tag { + flex-shrink: 0; + padding: 1px 6px; + border-radius: var(--radius-sm); + font-size: 11px; + font-weight: 600; +} +.diff-source-tag--old { background: var(--color-danger-bg); color: var(--color-danger); } +.diff-source-tag--new { background: var(--color-success-bg); color: var(--color-success); } +.diff-select, +.diff-picker-input { + flex: 1 1 auto; + min-width: 0; + max-width: 100%; + padding: 4px 8px; + border: 1px solid var(--border); + border-radius: var(--radius-md); + background: var(--bg-primary); + color: var(--text-primary); + font: inherit; + font-size: 13px; +} +.diff-btn { + display: inline-flex; + align-items: center; + gap: 4px; + padding: 4px 10px; + border: 1px solid var(--border); + border-radius: var(--radius-md); + background: var(--bg-primary); + color: var(--text-secondary); + font: inherit; + font-size: 13px; + cursor: pointer; +} +.diff-btn:hover { color: var(--accent); border-color: var(--accent-border); background: var(--accent-bg); } +.diff-btn:focus-visible, +.diff-select:focus-visible, +.diff-line-link:focus-visible, +.diff-expand:focus-visible { outline: 2px solid var(--accent); outline-offset: 1px; } +.diff-btn[aria-pressed="true"] { color: var(--accent); border-color: var(--accent-border); background: var(--accent-bg); } +.diff-btn[hidden] { display: none; } +.diff-close { margin-left: auto; } +.diff-layout, +.diff-nav { display: inline-flex; align-items: center; gap: 4px; } +.diff-nav-label { min-width: 4.5em; text-align: center; font-size: 12px; color: var(--text-secondary); font-variant-numeric: tabular-nums; } +.diff-check { display: inline-flex; align-items: center; gap: 4px; font-size: 13px; color: var(--text-secondary); cursor: pointer; } +.diff-spacer { flex: 1 1 auto; } +.diff-stats { font-size: 13px; font-variant-numeric: tabular-nums; } +.diff-stat-add { color: var(--color-success); font-weight: 600; } +.diff-stat-del { color: var(--color-danger); font-weight: 600; } +.diff-stat-blocks, +.diff-stat-same { color: var(--text-secondary); } +.diff-notice { + padding: 6px 10px; + border-radius: var(--radius-md); + background: var(--color-warning-bg); + color: var(--text-primary); + font-size: 12px; +} +.diff-notice[hidden] { display: none; } +.diff-picker { display: flex; flex-wrap: wrap; align-items: center; gap: 8px; } +.diff-picker-label { display: flex; flex: 1 1 320px; align-items: center; gap: 8px; font-size: 13px; } +.diff-picker-error { color: var(--color-danger); font-size: 12px; } +.diff-body { + flex: 1 1 auto; + min-height: 0; + overflow: auto; + background: var(--bg-primary); +} +.diff-loading, +.diff-empty { + padding: 32px 16px; + text-align: center; + color: var(--text-secondary); + font-size: 14px; +} +.diff-error { color: var(--color-danger); } +.diff-table { + width: 100%; + border-collapse: collapse; + table-layout: fixed; + font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace; + font-size: 12.5px; + line-height: 1.55; +} +.diff-col-num { width: 4.5em; } +.diff-num { + padding: 0 8px; + text-align: right; + vertical-align: top; + color: var(--text-muted); + background: var(--gutter-bg); + user-select: none; + font-variant-numeric: tabular-nums; +} +.diff-table--split .diff-num--new { border-left: 1px solid var(--border); } +.diff-line-link { + padding: 0; + border: 0; + background: none; + color: inherit; + font: inherit; + cursor: pointer; +} +.diff-line-link:hover { color: var(--accent); text-decoration: underline; } +.diff-code { + padding: 0 10px; + white-space: pre-wrap; + word-break: break-word; + overflow-wrap: anywhere; + vertical-align: top; +} +.diff-sign { display: inline-block; width: 1.2em; color: var(--text-muted); user-select: none; } +.diff-cell--del { background: var(--color-danger-bg); } +.diff-cell--add { background: var(--color-success-bg); } +.diff-cell--empty { background: var(--bg-tertiary); } +.diff-word-del { + background: color-mix(in srgb, var(--color-danger) 28%, transparent); + border-radius: 2px; + text-decoration: line-through; + text-decoration-color: color-mix(in srgb, var(--color-danger) 60%, transparent); +} +.diff-word-add { + background: color-mix(in srgb, var(--color-success) 28%, transparent); + border-radius: 2px; +} +.diff-row--current > td:first-child { box-shadow: inset 3px 0 0 var(--accent); } +.diff-row--skip td { padding: 0; background: var(--bg-secondary); } +.diff-expand { + width: 100%; + padding: 3px 12px; + border: 0; + background: none; + color: var(--accent); + font: inherit; + font-size: 12px; + text-align: left; + cursor: pointer; +} +.diff-expand:hover { background: var(--accent-bg); } + +/* Live-change chip next to the breadcrumb */ +.live-change-chip { + display: inline-flex; + flex-shrink: 0; + align-items: center; + gap: 5px; + margin-left: 8px; + padding: 2px 10px; + border: 1px solid var(--accent-border); + border-radius: var(--radius-pill); + background: var(--accent-bg); + color: var(--text-primary); + font: inherit; + font-size: 12px; + white-space: nowrap; + cursor: pointer; +} +.live-change-chip[hidden] { display: none; } +.live-change-chip:hover { border-color: var(--accent); } +.live-change-chip:focus-visible { outline: 2px solid var(--accent); outline-offset: 1px; } +.live-change-dot { + width: 7px; + height: 7px; + border-radius: 50%; + background: var(--accent); +} + +@media (max-width: 720px) { + .diff-overlay { padding: 0; } + .diff-modal { border-radius: 0; border: 0; } + .diff-title { flex: 1 1 0; min-width: 0; max-width: none; } + .diff-sources { order: 3; flex-basis: 100%; } + .diff-table { font-size: 11.5px; } + .diff-col-num { width: 3.2em; } + .diff-num { padding: 0 4px; } + .diff-code { padding: 0 6px; } + .live-change-chip .diff-stat-add, + .live-change-chip .diff-stat-del { display: none; } +} +@media print { + .diff-overlay, .live-change-chip { display: none !important; } +} + +/* ===== Link check report ===== */ +.linkcheck-overlay { + position: fixed; + inset: 0; + z-index: 1000; + display: flex; + align-items: flex-start; + justify-content: center; + padding: 8vh 16px 16px; + background: rgba(0, 0, 0, 0.4); + backdrop-filter: blur(4px); +} +.linkcheck-overlay[hidden] { display: none; } +.linkcheck-modal { + display: flex; + flex-direction: column; + width: min(900px, 100%); + max-height: 84vh; + background: var(--bg-primary); + color: var(--text-primary); + border: 1px solid var(--border); + border-radius: var(--radius-xl); + box-shadow: var(--shadow-lg); + overflow: hidden; + outline: none; +} +.linkcheck-header { + display: flex; + flex-wrap: wrap; + align-items: center; + gap: 8px 12px; + padding: 12px 16px; + border-bottom: 1px solid var(--border); + background: var(--bg-secondary); +} +.linkcheck-title { margin: 0; font-size: 15px; font-weight: 600; overflow-wrap: anywhere; } +.linkcheck-summary { font-size: 13px; color: var(--text-secondary); } +.linkcheck-body { flex: 1 1 auto; min-height: 0; overflow: auto; padding: 8px 16px 16px; } +.linkcheck-body .diff-notice { margin: 8px 0; } +.linkcheck-group + .linkcheck-group { border-top: 1px solid var(--border-subtle); } +.linkcheck-source { display: flex; align-items: center; gap: 8px; margin: 12px 0 6px; font-size: 14px; } +.linkcheck-count { + padding: 0 7px; + border-radius: var(--radius-pill); + background: var(--color-danger-bg); + color: var(--color-danger); + font-size: 12px; +} +.linkcheck-list { margin: 0; padding: 0; list-style: none; } +.linkcheck-item { + display: flex; + flex-wrap: wrap; + align-items: baseline; + gap: 4px 10px; + padding: 5px 0; + font-size: 13px; +} +.linkcheck-open, +.linkcheck-line, +.linkcheck-suggestion { + padding: 0; + border: 0; + background: none; + color: var(--link-color); + font: inherit; + cursor: pointer; + text-align: left; + overflow-wrap: anywhere; +} +.linkcheck-open:hover, +.linkcheck-line:hover, +.linkcheck-suggestion:hover { text-decoration: underline; } +.linkcheck-open:focus-visible, +.linkcheck-line:focus-visible, +.linkcheck-suggestion:focus-visible { outline: 2px solid var(--accent); outline-offset: 1px; } +.linkcheck-line { min-width: 3.5em; font-variant-numeric: tabular-nums; } +.linkcheck-kind { + padding: 0 6px; + border-radius: var(--radius-sm); + background: var(--bg-tertiary); + color: var(--text-secondary); + font-size: 11px; +} +.linkcheck-link { overflow-wrap: anywhere; } +.linkcheck-reason { color: var(--color-danger); } +.linkcheck-hint { flex-basis: 100%; padding-left: calc(3.5em + 10px); color: var(--text-secondary); font-size: 12px; } +.brokenlinks-title { color: var(--color-danger); } +@media (max-width: 720px) { + .linkcheck-overlay { padding: 0; } + .linkcheck-modal { max-height: 100vh; height: 100%; border-radius: 0; border: 0; } + .linkcheck-hint { padding-left: 0; } +} +@media print { .linkcheck-overlay { display: none !important; } } + +/* ===== Git status badges in the file tree ===== */ +.filetree-git { + flex-shrink: 0; + min-width: 1.4em; + margin-left: 4px; + padding: 0 3px; + border-radius: var(--radius-xs); + font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace; + font-size: 10.5px; + font-weight: 700; + line-height: 1.5; + text-align: center; +} +.filetree-git--modified, +.filetree-git--renamed { background: var(--color-warning-bg); color: var(--color-warning); } +.filetree-git--added, +.filetree-git--untracked { background: var(--color-success-bg); color: var(--color-success); } +.filetree-git--deleted { background: var(--color-danger-bg); color: var(--color-danger); } +.filetree-git-dot { + flex-shrink: 0; + width: 6px; + height: 6px; + margin-left: 6px; + border-radius: 50%; + background: var(--color-warning); +} diff --git a/src/text-diff.ts b/src/text-diff.ts new file mode 100644 index 0000000..c953766 --- /dev/null +++ b/src/text-diff.ts @@ -0,0 +1,363 @@ +/** + * Line-based text diff (Myers O(ND)) with intraline word highlighting, + * hunk grouping and unified-patch output. Pure functions, no DOM — shared by + * the diff view and covered directly by unit tests. + */ + +export type DiffOpType = 'equal' | 'delete' | 'insert'; + +export interface DiffOp { + type: DiffOpType; + /** 0-based index in the old line array (absent for inserts). */ + oldIndex?: number; + /** 0-based index in the new line array (absent for deletes). */ + newIndex?: number; +} + +export interface DiffOptions { + /** Treat lines equal when they only differ in whitespace runs / trailing space. */ + ignoreWhitespace?: boolean; + /** Abort exact search past this edit distance and fall back to a coarse replace. */ + maxEditDistance?: number; +} + +export interface DiffStats { + added: number; + removed: number; + /** Number of separate change blocks. */ + changes: number; +} + +export interface DiffResult { + oldLines: string[]; + newLines: string[]; + ops: DiffOp[]; + stats: DiffStats; + /** True when the edit distance bound was hit and the middle was replaced wholesale. */ + approximate: boolean; +} + +/** Split text into lines; a trailing newline does not produce an empty last line. */ +export function splitLines(text: string): string[] { + if (text === '') return []; + const lines = text.replace(/\r\n?/g, '\n').split('\n'); + if (lines[lines.length - 1] === '') lines.pop(); + return lines; +} + +function normalizeWs(line: string): string { + return line.replace(/\s+/g, ' ').trim(); +} + +/** + * Myers' greedy shortest-edit-script over integer token ids. Returns the ops + * for a[aStart..aEnd) vs b[bStart..bEnd), or null when the bound is exceeded. + */ +function myers(a: Int32Array, b: Int32Array, maxD: number): DiffOp[] | null { + const n = a.length; + const m = b.length; + const max = n + m; + const limit = Math.min(max, maxD); + const offset = max + 1; + const v = new Int32Array(2 * max + 3); + const trace: Int32Array[] = []; + let found = -1; + for (let d = 0; d <= limit; d++) { + trace.push(v.slice(offset - d - 1, offset + d + 2)); + for (let k = -d; k <= d; k += 2) { + let x: number; + if (k === -d || (k !== d && v[offset + k - 1] < v[offset + k + 1])) x = v[offset + k + 1]; + else x = v[offset + k - 1] + 1; + let y = x - k; + while (x < n && y < m && a[x] === b[y]) { x++; y++; } + v[offset + k] = x; + if (x >= n && y >= m) { found = d; break; } + } + if (found >= 0) break; + } + if (found < 0) return null; + + // Backtrack through the saved frontier snapshots. + const ops: DiffOp[] = []; + let x = n; + let y = m; + for (let d = found; d > 0; d--) { + const snap = trace[d]; + // snap index for diagonal k is (k + d + 1) + const get = (k: number) => snap[k + d + 1]; + const k = x - y; + let prevK: number; + if (k === -d || (k !== d && get(k - 1) < get(k + 1))) prevK = k + 1; + else prevK = k - 1; + const prevX = get(prevK); + const prevY = prevX - prevK; + while (x > prevX && y > prevY) { x--; y--; ops.push({ type: 'equal', oldIndex: x, newIndex: y }); } + if (prevK === k + 1) { y--; ops.push({ type: 'insert', newIndex: y }); } + else { x--; ops.push({ type: 'delete', oldIndex: x }); } + x = prevX; + y = prevY; + } + while (x > 0 && y > 0) { x--; y--; ops.push({ type: 'equal', oldIndex: x, newIndex: y }); } + ops.reverse(); + return ops; +} + +function tokenIds(oldKeys: string[], newKeys: string[]): [Int32Array, Int32Array] { + const ids = new Map(); + const map = (keys: string[]) => { + const out = new Int32Array(keys.length); + keys.forEach((key, i) => { + let id = ids.get(key); + if (id === undefined) { id = ids.size; ids.set(key, id); } + out[i] = id; + }); + return out; + }; + return [map(oldKeys), map(newKeys)]; +} + +/** Diff two key sequences; trims common prefix/suffix before running Myers. */ +function diffKeys(oldKeys: string[], newKeys: string[], maxD: number): { ops: DiffOp[]; approximate: boolean } { + let start = 0; + while (start < oldKeys.length && start < newKeys.length && oldKeys[start] === newKeys[start]) start++; + let endOld = oldKeys.length; + let endNew = newKeys.length; + while (endOld > start && endNew > start && oldKeys[endOld - 1] === newKeys[endNew - 1]) { endOld--; endNew--; } + + const ops: DiffOp[] = []; + for (let i = 0; i < start; i++) ops.push({ type: 'equal', oldIndex: i, newIndex: i }); + + const [a, b] = tokenIds(oldKeys.slice(start, endOld), newKeys.slice(start, endNew)); + let approximate = false; + let middle = myers(a, b, maxD); + if (!middle) { + approximate = true; + middle = []; + for (let i = 0; i < a.length; i++) middle.push({ type: 'delete', oldIndex: i }); + for (let j = 0; j < b.length; j++) middle.push({ type: 'insert', newIndex: j }); + } + for (const op of middle) { + ops.push({ + type: op.type, + oldIndex: op.oldIndex === undefined ? undefined : op.oldIndex + start, + newIndex: op.newIndex === undefined ? undefined : op.newIndex + start, + }); + } + + const tailOffsetNew = endNew - endOld; + for (let i = endOld; i < oldKeys.length; i++) ops.push({ type: 'equal', oldIndex: i, newIndex: i + tailOffsetNew }); + return { ops, approximate }; +} + +/** Within each change block, emit deletions before insertions (git style). */ +function normalizeBlocks(ops: DiffOp[]): DiffOp[] { + const out: DiffOp[] = []; + let dels: DiffOp[] = []; + let ins: DiffOp[] = []; + const flush = () => { out.push(...dels, ...ins); dels = []; ins = []; }; + for (const op of ops) { + if (op.type === 'equal') { flush(); out.push(op); } + else if (op.type === 'delete') dels.push(op); + else ins.push(op); + } + flush(); + return out; +} + +export function diffLines(oldText: string, newText: string, options: DiffOptions = {}): DiffResult { + const oldLines = splitLines(oldText); + const newLines = splitLines(newText); + const key = options.ignoreWhitespace ? normalizeWs : (s: string) => s; + const maxD = options.maxEditDistance ?? 2000; + const { ops: raw, approximate } = diffKeys(oldLines.map(key), newLines.map(key), maxD); + const ops = normalizeBlocks(raw); + let added = 0; + let removed = 0; + let changes = 0; + let inChange = false; + for (const op of ops) { + if (op.type === 'equal') { inChange = false; continue; } + if (!inChange) { changes++; inChange = true; } + if (op.type === 'insert') added++; + else removed++; + } + return { oldLines, newLines, ops, stats: { added, removed, changes }, approximate }; +} + +// --- Intraline --- + +export interface InlineSegment { + text: string; + changed: boolean; +} + +const WORD_RE = /[\p{L}\p{N}_]+|\s+|[^\p{L}\p{N}_\s]/gu; + +function tokenize(line: string): string[] { + return line.match(WORD_RE) ?? []; +} + +function mergeSegments(segs: InlineSegment[]): InlineSegment[] { + const out: InlineSegment[] = []; + for (const seg of segs) { + if (!seg.text) continue; + const last = out[out.length - 1]; + if (last && last.changed === seg.changed) last.text += seg.text; + else out.push({ ...seg }); + } + return out; +} + +/** + * Word-level diff of a changed line pair. Returns null when the lines are too + * dissimilar (or too long) for highlighting to be useful. + */ +export function diffInline(oldLine: string, newLine: string): { old: InlineSegment[]; new: InlineSegment[] } | null { + if (oldLine.length + newLine.length > 4000) return null; + const a = tokenize(oldLine); + const b = tokenize(newLine); + const { ops } = diffKeys(a, b, 400); + const oldSegs: InlineSegment[] = []; + const newSegs: InlineSegment[] = []; + let same = 0; + for (const op of ops) { + if (op.type === 'equal') { + oldSegs.push({ text: a[op.oldIndex!], changed: false }); + newSegs.push({ text: b[op.newIndex!], changed: false }); + same += a[op.oldIndex!].length; + } else if (op.type === 'delete') { + oldSegs.push({ text: a[op.oldIndex!], changed: true }); + } else { + newSegs.push({ text: b[op.newIndex!], changed: true }); + } + } + const longest = Math.max(oldLine.length, newLine.length); + // Below ~30% shared content the highlight is mostly noise. + if (longest > 0 && same / longest < 0.3) return null; + return { old: mergeSegments(oldSegs), new: mergeSegments(newSegs) }; +} + +// --- Hunks / side-by-side rows --- + +export interface SideCell { + /** 1-based line number. */ + line: number; + text: string; +} + +export type DiffRow = + | { kind: 'equal'; old: SideCell; new: SideCell } + | { kind: 'change'; old: SideCell | null; new: SideCell | null; changeIndex: number } + | { kind: 'skip'; oldStart: number; newStart: number; count: number; skipIndex: number }; + +/** + * Pair deletions with insertions inside each change block and collapse long + * unchanged stretches into `skip` rows (keeping `context` lines around changes). + * `context < 0` keeps every line. + */ +export function buildRows(result: DiffResult, context = 3): DiffRow[] { + const rows: DiffRow[] = []; + const { ops, oldLines, newLines } = result; + let changeIndex = -1; + let i = 0; + // First build full rows. + const full: DiffRow[] = []; + while (i < ops.length) { + const op = ops[i]; + if (op.type === 'equal') { + full.push({ + kind: 'equal', + old: { line: op.oldIndex! + 1, text: oldLines[op.oldIndex!] }, + new: { line: op.newIndex! + 1, text: newLines[op.newIndex!] }, + }); + i++; + continue; + } + changeIndex++; + const dels: DiffOp[] = []; + const ins: DiffOp[] = []; + while (i < ops.length && ops[i].type !== 'equal') { + if (ops[i].type === 'delete') dels.push(ops[i]); else ins.push(ops[i]); + i++; + } + const n = Math.max(dels.length, ins.length); + for (let k = 0; k < n; k++) { + const d = dels[k]; + const a = ins[k]; + full.push({ + kind: 'change', + old: d ? { line: d.oldIndex! + 1, text: oldLines[d.oldIndex!] } : null, + new: a ? { line: a.newIndex! + 1, text: newLines[a.newIndex!] } : null, + changeIndex, + }); + } + } + if (context < 0) return full; + + // Mark which equal rows stay visible. + const keep = new Uint8Array(full.length); + full.forEach((row, idx) => { + if (row.kind !== 'change') return; + for (let j = Math.max(0, idx - context); j <= Math.min(full.length - 1, idx + context); j++) keep[j] = 1; + }); + let skipIndex = 0; + let idx = 0; + while (idx < full.length) { + if (keep[idx] || full[idx].kind !== 'equal') { rows.push(full[idx]); idx++; continue; } + const start = idx; + while (idx < full.length && !keep[idx] && full[idx].kind === 'equal') idx++; + const first = full[start] as Extract; + rows.push({ kind: 'skip', oldStart: first.old.line, newStart: first.new.line, count: idx - start, skipIndex: skipIndex++ }); + } + return rows; +} + +// --- Unified patch --- + +export function toUnifiedPatch(result: DiffResult, oldLabel: string, newLabel: string, context = 3): string { + const { ops, oldLines, newLines } = result; + if (result.stats.changes === 0) return ''; + const out: string[] = [`--- ${oldLabel}`, `+++ ${newLabel}`]; + // Indices of non-equal ops + let i = 0; + while (i < ops.length) { + while (i < ops.length && ops[i].type === 'equal') i++; + if (i >= ops.length) break; + // Hunk start: back up `context` equal ops + let start = i; + let back = 0; + while (start > 0 && back < context && ops[start - 1].type === 'equal') { start--; back++; } + // Extend until we see more than 2*context equal ops in a row (or EOF) + let end = i; + while (end < ops.length) { + if (ops[end].type !== 'equal') { end++; continue; } + let run = 0; + while (end + run < ops.length && ops[end + run].type === 'equal') run++; + if (end + run >= ops.length || run > 2 * context) { end += Math.min(run, context); break; } + end += run; + } + const slice = ops.slice(start, end); + // Line numbers: position of first line on each side + let oldStart = 0; + let newStart = 0; + let oldCount = 0; + let newCount = 0; + const firstOld = slice.find((op) => op.oldIndex !== undefined); + const firstNew = slice.find((op) => op.newIndex !== undefined); + // Determine starting positions from preceding ops when one side is empty. + const countBefore = (side: 'oldIndex' | 'newIndex') => + ops.slice(0, start).filter((op) => op[side] !== undefined).length; + oldStart = firstOld ? firstOld.oldIndex! + 1 : countBefore('oldIndex'); + newStart = firstNew ? firstNew.newIndex! + 1 : countBefore('newIndex'); + const body: string[] = []; + for (const op of slice) { + if (op.type === 'equal') { body.push(` ${oldLines[op.oldIndex!]}`); oldCount++; newCount++; } + else if (op.type === 'delete') { body.push(`-${oldLines[op.oldIndex!]}`); oldCount++; } + else { body.push(`+${newLines[op.newIndex!]}`); newCount++; } + } + const range = (s: number, c: number) => (c === 1 ? `${s}` : `${s},${c}`); + out.push(`@@ -${range(oldStart, oldCount)} +${range(newStart, newCount)} @@`, ...body); + i = end; + } + return out.join('\n') + '\n'; +} diff --git a/src/toc.ts b/src/toc.ts index dfe5da3..b227759 100644 --- a/src/toc.ts +++ b/src/toc.ts @@ -1,4 +1,7 @@ +import { fetchLinkCheck } from './link-report'; + type FileSelectCallback = (path: string) => void; +type LocationCallback = (path: string, line: number) => void; interface Backlink { path: string; @@ -9,6 +12,9 @@ export class TableOfContents { private container: HTMLElement; private viewer: HTMLElement; private onFileSelect: FileSelectCallback | null = null; + private onLocation: LocationCallback | null = null; + private onLinkReport: ((scope: string) => void) | null = null; + private brokenSeq = 0; constructor(container: HTMLElement, viewer: HTMLElement) { this.container = container; @@ -19,6 +25,12 @@ export class TableOfContents { this.onFileSelect = cb; } + /** Hooks for the broken-links section: jump to a line / open the full report. */ + setLinkCallbacks(onLocation: LocationCallback, onLinkReport: (scope: string) => void) { + this.onLocation = onLocation; + this.onLinkReport = onLinkReport; + } + update() { const headings = this.viewer.querySelectorAll('h1, h2, h3, h4'); if (headings.length === 0) { @@ -43,6 +55,7 @@ export class TableOfContents { html += ''; // Backlinks container (populated async) html += ''; + html += ''; this.container.innerHTML = html; // Click handler — smooth scroll @@ -88,6 +101,37 @@ export class TableOfContents { } catch { /* ignore */ } } + /** List this document's relative links whose targets are missing. */ + async loadBrokenLinks(filePath: string) { + const seq = ++this.brokenSeq; + const section = this.container.querySelector('#brokenlinks-section'); + if (!section) return; + try { + const result = await fetchLinkCheck(filePath); + if (seq !== this.brokenSeq || !section.isConnected) return; + if (result.broken.length === 0) { + section.innerHTML = ''; + return; + } + const esc = (s: string) => s.replace(/&/g, '&').replace(//g, '>').replace(/"/g, '"'); + section.innerHTML = ``; + section.querySelectorAll('.brokenlink-item').forEach((a) => { + a.addEventListener('click', (e) => { + e.preventDefault(); + this.onLocation?.(filePath, Number(a.dataset.line)); + }); + }); + section.querySelector('.brokenlink-report')?.addEventListener('click', (e) => { + e.preventDefault(); + this.onLinkReport?.(''); + }); + } catch { /* ignore */ } + } + private setActive(active: HTMLElement) { this.container.querySelectorAll('.toc-link.active').forEach((el) => el.classList.remove('active')); active.classList.add('active'); diff --git a/tests/diff-linkcheck.spec.ts b/tests/diff-linkcheck.spec.ts new file mode 100644 index 0000000..a6d0400 --- /dev/null +++ b/tests/diff-linkcheck.spec.ts @@ -0,0 +1,155 @@ +import { test, expect, type Locator, type Page } from '@playwright/test'; +import { writeFileSync, readFileSync } from 'node:fs'; + +const DIR = '/tmp/md-test-docs/diffcheck'; + +// Headless Chromium does not emit `contextmenu` from a synthetic right-click. +function rightClick(locator: Locator) { + return locator.dispatchEvent('contextmenu', { bubbles: true, clientX: 60, clientY: 60 }); +} + +async function openFile(page: Page, path: string) { + await page.goto(`/#file=${encodeURIComponent(path)}`); + await page.waitForSelector('.filetree-item[data-path]'); + await expect(page.locator('#breadcrumb')).toContainText(path.split('/').pop()!); +} + +async function expandFolder(page: Page) { + const folder = page.locator('.filetree-item[data-path="diffcheck"]'); + if (await page.locator('.filetree-item[data-path="diffcheck/config.dev.yaml"]').count() === 0) await folder.click(); +} + +test.describe('Diff view', () => { + test('compares two files from the file tree with word-level highlights', async ({ page }) => { + await openFile(page, 'diffcheck/config.prod.yaml'); + await expandFolder(page); + await rightClick(page.locator('.filetree-item[data-path="diffcheck/config.dev.yaml"]')); + await page.locator('.filetree-context-item', { hasText: '表示中の「config.prod.yaml」と比較' }).click(); + + const dialog = page.getByRole('dialog', { name: /差分/ }); + await expect(dialog).toBeVisible(); + await expect(dialog.locator('.diff-stats')).toHaveText(/\+3\s*−2\s*2 箇所/); + await expect(dialog.locator('.diff-word-del')).toHaveText(['8080', 'false']); + await expect(dialog.locator('.diff-word-add')).toHaveText(['3000', 'true']); + await expect(dialog.locator('.diff-nav-label')).toHaveText('1 / 2'); + + // Unified layout via keyboard, then swap sides. + await page.keyboard.press('u'); + await expect(dialog.locator('.diff-table--unified')).toBeVisible(); + await dialog.getByRole('button', { name: '比較元と比較先を入れ替え' }).click(); + await expect(dialog.locator('.diff-stats')).toHaveText(/\+2\s*−3/); + + await page.keyboard.press('Escape'); + await expect(dialog).toBeHidden(); + }); + + test('"比較元として選択" then "選択した…と比較" compares any two files', async ({ page }) => { + await openFile(page, 'README.md'); + await expandFolder(page); + await rightClick(page.locator('.filetree-item[data-path="diffcheck/config.dev.yaml"]')); + await page.locator('.filetree-context-item', { hasText: '比較元として選択' }).click(); + await rightClick(page.locator('.filetree-item[data-path="diffcheck/config.prod.yaml"]')); + await page.locator('.filetree-context-item', { hasText: '選択した「config.dev.yaml」と比較' }).click(); + const dialog = page.getByRole('dialog', { name: /差分/ }); + await expect(dialog.locator('select[data-side="old"]')).toHaveValue('file:diffcheck/config.dev.yaml'); + await expect(dialog.locator('select[data-side="new"]')).toHaveValue('file:diffcheck/config.prod.yaml'); + }); + + test('copy patch produces a unified diff and clicking a line number opens the file there', async ({ page, context }) => { + await context.grantPermissions(['clipboard-read', 'clipboard-write']); + await openFile(page, 'diffcheck/config.prod.yaml'); + await expandFolder(page); + await rightClick(page.locator('.filetree-item[data-path="diffcheck/config.dev.yaml"]')); + await page.locator('.filetree-context-item', { hasText: '表示中の' }).click(); + const dialog = page.getByRole('dialog', { name: /差分/ }); + await dialog.getByRole('button', { name: 'パッチをコピー' }).click(); + const patch = await page.evaluate(() => navigator.clipboard.readText()); + expect(patch).toContain('--- a/diffcheck/config.prod.yaml'); + expect(patch).toContain('+++ b/diffcheck/config.dev.yaml'); + expect(patch).toContain('-port: 8080\n'); + expect(patch).toContain('+extra: on\n'); + + await dialog.locator('.diff-num--new .diff-line-link', { hasText: '5' }).click(); + await expect(dialog).toBeHidden(); + await expect(page).toHaveURL(/file=diffcheck%2Fconfig\.dev\.yaml&line=5/); + }); + + test('secret-safe mode masks secrets on both sides of a diff', async ({ page }) => { + await page.goto('/?secretSafe=1#file=diffcheck%2Fsecret-a.env'); + await page.waitForSelector('.filetree-item[data-path]'); + await expandFolder(page); + await rightClick(page.locator('.filetree-item[data-path="diffcheck/secret-b.env"]')); + await page.locator('.filetree-context-item', { hasText: '表示中の' }).click(); + const dialog = page.getByRole('dialog', { name: /差分/ }); + await expect(dialog.locator('.diff-stats')).toContainText('+1'); + await expect(dialog.locator('.diff-body')).not.toContainText('ABC1234567890'); + await expect(dialog.locator('.diff-body')).not.toContainText('XYZ0987654321'); + await expect(dialog.locator('.diff-notice')).toContainText('Secret Safe'); + }); + + test('live edits show a change chip and a diff against the version first opened', async ({ page }) => { + const file = `${DIR}/live.md`; + const original = readFileSync(file, 'utf8'); + try { + await openFile(page, 'diffcheck/live.md'); + await expect(page.locator('#viewer')).toContainText('first line'); + await expect(page.locator('#btn-live-changes')).toBeHidden(); + + writeFileSync(file, `${original}second line\n`); + const chip = page.locator('#btn-live-changes'); + await expect(chip).toBeVisible({ timeout: 10000 }); + await expect(chip).toContainText('+1'); + + await page.keyboard.press('d'); + const dialog = page.getByRole('dialog', { name: /差分/ }); + await expect(dialog.locator('select[data-side="old"]')).toHaveValue('snap:diffcheck/live.md'); + await expect(dialog.locator('.diff-cell--add')).toContainText('second line'); + + // The open diff follows further edits. + writeFileSync(file, `${original}second line\nthird line\n`); + await expect(dialog.locator('.diff-stats')).toContainText('+2', { timeout: 10000 }); + + // Marking as reviewed resets the baseline. + await dialog.getByRole('button', { name: '確認済みにする' }).click(); + await expect(dialog.locator('.diff-empty')).toContainText('同一'); + await page.keyboard.press('Escape'); + await expect(chip).toBeHidden(); + } finally { + writeFileSync(file, original); + } + }); + + test('outside a Git repository the D shortcut still opens the comparison picker', async ({ page }) => { + await openFile(page, 'diffcheck/config.prod.yaml'); + await page.keyboard.press('d'); + const dialog = page.getByRole('dialog', { name: /差分/ }); + await expect(dialog.locator('.diff-empty')).toContainText('同一'); + await dialog.locator('select[data-side="old"]').selectOption('__other__'); + const input = dialog.locator('.diff-picker-input'); + await input.fill('diffcheck/config.dev.yaml'); + await input.press('Enter'); + await expect(dialog.locator('.diff-stats')).toHaveText(/\+2\s*−3/); + }); +}); + +test.describe('Link check', () => { + test('folder report lists broken links and jumps to the source line', async ({ page }) => { + await openFile(page, 'README.md'); + await rightClick(page.locator('.filetree-item[data-path="diffcheck"]')); + await page.locator('.filetree-context-item', { hasText: 'このフォルダのリンク切れをチェック' }).click(); + const dialog = page.getByRole('dialog', { name: /リンクチェック/ }); + await expect(dialog.locator('.linkcheck-summary')).toContainText('リンク切れ 2 件'); + await expect(dialog.locator('.linkcheck-link')).toHaveText(['missing-page.md', 'pics/none.png']); + + await dialog.locator('.linkcheck-line').first().click(); + await expect(dialog).toBeHidden(); + await expect(page).toHaveURL(/file=diffcheck%2Flinks\.md&line=4/); + }); + + test('the TOC lists the current document\'s broken links', async ({ page }) => { + await openFile(page, 'diffcheck/links.md'); + const section = page.locator('#brokenlinks-section'); + await expect(section.locator('.brokenlinks-title')).toHaveText('Broken links (2)'); + await expect(section.locator('.brokenlink-item')).toHaveText(['L4 missing-page.md', 'L5 pics/none.png']); + }); +}); diff --git a/tests/history-links.test.mjs b/tests/history-links.test.mjs new file mode 100644 index 0000000..68736b8 --- /dev/null +++ b/tests/history-links.test.mjs @@ -0,0 +1,201 @@ +// Server tests for the Git history API (/api/git/log, /api/git/show) and the +// broken-link checker (/api/links/check). +import test, { before, after } from 'node:test'; +import assert from 'node:assert/strict'; +import { fork, execFileSync } from 'node:child_process'; +import { createServer } from 'node:http'; +import { mkdtemp, mkdir, writeFile, symlink, rm, appendFile } from 'node:fs/promises'; +import { tmpdir } from 'node:os'; +import { join, dirname } from 'node:path'; +import { fileURLToPath } from 'node:url'; +import { once } from 'node:events'; + +const ROOT = join(dirname(fileURLToPath(import.meta.url)), '..'); +let fixture; +let repo; +let plain; +let hasGit = true; + +function git(cwd, ...args) { + return execFileSync('git', args, { cwd, encoding: 'utf8', env: { ...process.env, GIT_AUTHOR_DATE: '2026-01-02T03:04:05Z', GIT_COMMITTER_DATE: '2026-01-02T03:04:05Z' } }); +} + +before(async () => { + fixture = await mkdtemp(join(tmpdir(), 'docview-history-links-')); + repo = join(fixture, 'repo'); + plain = join(fixture, 'plain'); + await mkdir(join(repo, 'docs'), { recursive: true }); + await mkdir(join(plain, 'guide'), { recursive: true }); + await mkdir(join(plain, 'node_modules', 'pkg'), { recursive: true }); + await writeFile(join(fixture, 'outside.md'), 'outside\n'); + + try { execFileSync('git', ['--version'], { stdio: 'ignore' }); } catch { hasGit = false; } + if (hasGit) { + git(repo, 'init', '-q'); + git(repo, 'config', 'user.email', 'test@example.com'); + git(repo, 'config', 'user.name', 'Tester'); + git(repo, 'config', 'commit.gpgsign', 'false'); + await writeFile(join(repo, 'docs', 'a.md'), 'one\ntwo\n'); + git(repo, 'add', '.'); + git(repo, 'commit', '-qm', 'first version'); + await writeFile(join(repo, 'docs', 'a.md'), 'one\ntwo\nthree\n'); + git(repo, 'commit', '-qam', 'second version'); + await appendFile(join(repo, 'docs', 'a.md'), 'working tree\n'); + await writeFile(join(repo, 'docs', 'new.md'), 'untracked\n'); + await symlink(join(fixture, 'outside.md'), join(repo, 'docs', 'escape.md')); + } + + await writeFile(join(plain, 'index.md'), [ + '# Index', + '[ok](guide/intro.md) [gone](guide/missing.md) [web](https://example.com) [top](#index)', + '![logo](img/logo.png)', + '[[intro]] [[guide/intro]]', + '`[code](not-a-link.md)`', + '```', + '[fenced](also-not.md)', + '```', + '[ref]: ./nowhere.md', + '[heading](guide/intro.md#section) [encoded](guide/my%20notes.md)', + '', + ].join('\n')); + await writeFile(join(plain, 'guide', 'intro.md'), '# Intro\n[back](../index.md)\n'); + await writeFile(join(plain, 'guide', 'my notes.md'), '# Notes\n'); + await writeFile(join(plain, 'node_modules', 'pkg', 'readme.md'), '[skip](absent.md)\n'); +}); +after(async () => { await rm(fixture, { recursive: true, force: true }); }); + +async function availablePort() { + const server = createServer(); + server.listen(0, '127.0.0.1'); + await once(server, 'listening'); + const port = server.address().port; + await new Promise((resolve) => server.close(resolve)); + return port; +} + +async function startServer(t, directory) { + const port = await availablePort(); + const child = fork(join(ROOT, 'server.mjs'), [directory, '--port', String(port)], { + cwd: ROOT, + stdio: ['ignore', 'pipe', 'pipe', 'ipc'], + }); + t.after(async () => { + if (child.exitCode === null && child.signalCode === null) { + const exited = once(child, 'exit'); + child.kill('SIGTERM'); + await exited; + } + }); + await new Promise((resolve, reject) => { + const timer = setTimeout(() => reject(new Error('Server startup timed out')), 10000); + child.once('exit', (code) => { clearTimeout(timer); reject(new Error(`Server exited ${code}`)); }); + child.on('message', (message) => { + if (message.type === 'listening') { clearTimeout(timer); resolve(); } + }); + }); + const base = `http://127.0.0.1:${port}`; + return (path) => fetch(base + path, { signal: AbortSignal.timeout(8000) }); +} + +test('git log lists commits for a tracked file and reports working-tree status', async (t) => { + if (!hasGit) return t.skip('git not installed'); + const request = await startServer(t, repo); + const res = await request('/api/git/log?path=docs/a.md'); + assert.equal(res.status, 200); + const log = await res.json(); + assert.equal(log.git, true); + assert.equal(log.status, 'modified'); + assert.deepEqual(log.commits.map((c) => c.subject), ['second version', 'first version']); + assert.match(log.commits[0].hash, /^[0-9a-f]{40}$/); + assert.equal(log.commits[0].author, 'Tester'); + + const limited = await (await request('/api/git/log?path=docs/a.md&limit=1')).json(); + assert.equal(limited.commits.length, 1); + + const untracked = await (await request('/api/git/log?path=docs/new.md')).json(); + assert.deepEqual(untracked, { git: true, status: 'untracked', commits: [] }); +}); + +test('git show returns file content at HEAD, HEAD~N and a commit hash', async (t) => { + if (!hasGit) return t.skip('git not installed'); + const request = await startServer(t, repo); + const head = await request('/api/git/show?path=docs/a.md&rev=HEAD'); + assert.equal(head.status, 200); + assert.equal(head.headers.get('content-security-policy'), 'sandbox'); + assert.equal(await head.text(), 'one\ntwo\nthree\n'); + assert.equal(await (await request('/api/git/show?path=docs/a.md&rev=HEAD~1')).text(), 'one\ntwo\n'); + const { commits } = await (await request('/api/git/log?path=docs/a.md')).json(); + assert.equal(await (await request(`/api/git/show?path=docs/a.md&rev=${commits[1].short}`)).text(), 'one\ntwo\n'); + assert.equal((await request('/api/git/show?path=docs/new.md')).status, 404); +}); + +test('git endpoints reject unsafe revisions and paths outside the root', async (t) => { + if (!hasGit) return t.skip('git not installed'); + const request = await startServer(t, repo); + for (const rev of ['--output=/tmp/x', 'HEAD:../../etc/passwd', 'main', 'HEAD^', '']) { + if (rev === '') continue; + const res = await request(`/api/git/show?path=docs/a.md&rev=${encodeURIComponent(rev)}`); + assert.equal(res.status, 400, rev); + } + assert.equal((await request('/api/git/show?path=../outside.md')).status, 403); + assert.equal((await request('/api/git/log?path=docs/escape.md')).status, 403); + assert.equal((await request('/api/git/show?path=docs')).status, 400); + assert.equal((await request('/api/git/log')).status, 400); +}); + +test('git status maps changed files to served-root paths, including from a subfolder root', async (t) => { + if (!hasGit) return t.skip('git not installed'); + const request = await startServer(t, repo); + const status = await (await request('/api/git/status')).json(); + assert.equal(status.git, true); + assert.equal(status.files['docs/a.md'], 'modified'); + assert.equal(status.files['docs/new.md'], 'untracked'); + + const sub = await startServer(t, join(repo, 'docs')); + const subStatus = await (await sub('/api/git/status')).json(); + assert.equal(subStatus.files['a.md'], 'modified'); + assert.equal(subStatus.files['docs/a.md'], undefined); +}); + +test('git status is unavailable outside a repository', async (t) => { + const request = await startServer(t, plain); + assert.deepEqual(await (await request('/api/git/status')).json(), { git: false, files: {}, truncated: false }); +}); + +test('git log degrades to git:false outside a repository', async (t) => { + const request = await startServer(t, plain); + const res = await request('/api/git/log?path=index.md'); + assert.equal(res.status, 200); + const body = await res.json(); + assert.equal(body.git, false); + assert.deepEqual(body.commits, []); +}); + +test('link check reports missing relative targets the way the viewer resolves them', async (t) => { + const request = await startServer(t, plain); + const res = await request('/api/links/check'); + assert.equal(res.status, 200); + const result = await res.json(); + assert.equal(result.scannedFiles, 3); // node_modules is skipped + const broken = result.broken.map((b) => `${b.source}:${b.line} ${b.kind} ${b.link} -> ${b.target}`); + assert.deepEqual(broken, [ + 'index.md:2 link guide/missing.md -> guide/missing.md', + 'index.md:3 image img/logo.png -> img/logo.png', + 'index.md:4 wiki [[intro]] -> intro.md', + 'index.md:9 reference ./nowhere.md -> nowhere.md', + ]); + // Wiki links resolve relative to the source; a same-name file elsewhere is offered as a fix. + assert.deepEqual(result.broken[2].suggestions, ['guide/intro.md']); +}); + +test('link check can be scoped to a folder or a document and stays inside the root', async (t) => { + const request = await startServer(t, plain); + const scoped = await (await request('/api/links/check?path=guide')).json(); + assert.equal(scoped.scannedFiles, 2); + assert.deepEqual(scoped.broken, []); + const single = await (await request('/api/links/check?path=index.md')).json(); + assert.equal(single.scannedFiles, 1); + assert.equal(single.broken.length, 4); + assert.equal((await request('/api/links/check?path=../')).status, 403); + assert.equal((await request('/api/links/check?path=nope')).status, 404); +}); diff --git a/tests/setup.ts b/tests/setup.ts index 5033807..eca74f2 100644 --- a/tests/setup.ts +++ b/tests/setup.ts @@ -459,4 +459,14 @@ flowchart TD todayStart.setHours(0, 0, 0, 0); const yesterdayNoon = new Date(todayStart.getTime() - 12 * 3_600_000); // always yesterday 12:00 utimesSync(join(DIR, 'edited-yesterday.md'), yesterdayNoon, yesterdayNoon); + + // Diff view & link check fixtures (diff-linkcheck.spec.ts) — kept in their own + // folder so the broken links below never touch other suites. + mkdirSync(join(DIR, 'diffcheck'), { recursive: true }); + write('diffcheck/config.prod.yaml', 'name: app\nport: 8080\ndebug: false\nreplicas: 3\n'); + write('diffcheck/config.dev.yaml', 'name: app\nport: 3000\ndebug: true\nreplicas: 3\nextra: on\n'); + write('diffcheck/secret-a.env', 'API_KEY=dv_live_ABC1234567890SECRETKEY\nNAME=one\n'); + write('diffcheck/secret-b.env', 'API_KEY=dv_live_XYZ0987654321OTHERKEY\nNAME=two\n'); + write('diffcheck/live.md', '# Live\n\nfirst line\n'); + write('diffcheck/links.md', '# Links\n\n[ok](live.md)\n[broken](missing-page.md)\n![img](pics/none.png)\n'); } diff --git a/tests/text-diff.test.mjs b/tests/text-diff.test.mjs new file mode 100644 index 0000000..28964fc --- /dev/null +++ b/tests/text-diff.test.mjs @@ -0,0 +1,114 @@ +// Unit tests for the line diff engine used by the diff view (src/text-diff.ts). +// Node strips the TypeScript types at import time. +import test from 'node:test'; +import assert from 'node:assert/strict'; +import { execFileSync } from 'node:child_process'; +import { mkdtemp, writeFile, readFile, rm } from 'node:fs/promises'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import { diffLines, diffInline, buildRows, toUnifiedPatch, splitLines } from '../src/text-diff.ts'; + +function rebuild(result) { + return { + oldText: result.ops.filter((o) => o.type !== 'insert').map((o) => result.oldLines[o.oldIndex]), + newText: result.ops.filter((o) => o.type !== 'delete').map((o) => result.newLines[o.newIndex]), + }; +} + +function seeded(seed) { + let s = seed; + return () => { s = (s * 1103515245 + 12345) & 0x7fffffff; return s / 0x7fffffff; }; +} + +test('splitLines normalizes CRLF and ignores the trailing newline', () => { + assert.deepEqual(splitLines('a\r\nb\rc\n'), ['a', 'b', 'c']); + assert.deepEqual(splitLines(''), []); + assert.deepEqual(splitLines('\n'), ['']); +}); + +test('identical texts produce no changes', () => { + const r = diffLines('a\nb\n', 'a\nb\n'); + assert.deepEqual(r.stats, { added: 0, removed: 0, changes: 0 }); + assert.equal(toUnifiedPatch(r, 'a', 'b'), ''); +}); + +test('counts additions, removals and separate change blocks', () => { + const r = diffLines('a\nb\nc\nd\ne\nf\ng\nh\n', 'a\nB\nc\nd\ne\nf\ng\nh\ni\n'); + assert.deepEqual(r.stats, { added: 2, removed: 1, changes: 2 }); + assert.equal(r.approximate, false); +}); + +test('ops always reconstruct both inputs and pair only equal lines (fuzz)', () => { + const rand = seeded(42); + for (let t = 0; t < 400; t++) { + const gen = () => Array.from({ length: Math.floor(rand() * 40) }, () => 'abcde'[Math.floor(rand() * 5)]).join('\n'); + const x = gen(); + const y = gen(); + const r = diffLines(x, y); + const { oldText, newText } = rebuild(r); + assert.deepEqual(oldText, r.oldLines); + assert.deepEqual(newText, r.newLines); + for (const op of r.ops) { + if (op.type === 'equal') assert.equal(r.oldLines[op.oldIndex], r.newLines[op.newIndex]); + } + } +}); + +test('ignoreWhitespace treats re-indented lines as equal', () => { + const r = diffLines('if (x) {\n y();\n}\n', 'if (x) {\n y();\n}\n', { ignoreWhitespace: true }); + assert.equal(r.stats.changes, 0); + assert.equal(diffLines('a b\n', 'a b\n').stats.changes, 1); +}); + +test('falls back to an approximate replace beyond the edit-distance bound', () => { + const a = Array.from({ length: 300 }, (_, i) => `a${i}`).join('\n'); + const b = Array.from({ length: 300 }, (_, i) => `b${i}`).join('\n'); + const r = diffLines(a, b, { maxEditDistance: 10 }); + assert.equal(r.approximate, true); + assert.deepEqual(r.stats, { added: 300, removed: 300, changes: 1 }); + const { oldText, newText } = rebuild(r); + assert.deepEqual(oldText, r.oldLines); + assert.deepEqual(newText, r.newLines); +}); + +test('diffInline highlights only the changed words', () => { + const r = diffInline('port: 8080 # prod', 'port: 3000 # prod'); + assert.ok(r); + assert.deepEqual(r.old.filter((s) => s.changed).map((s) => s.text), ['8080']); + assert.deepEqual(r.new.filter((s) => s.changed).map((s) => s.text), ['3000']); + assert.equal(r.old.map((s) => s.text).join(''), 'port: 8080 # prod'); + // Completely different lines are not worth highlighting. + assert.equal(diffInline('alpha beta', 'gamma delta'), null); +}); + +test('buildRows pairs deletions with insertions and collapses unchanged runs', () => { + const old = Array.from({ length: 20 }, (_, i) => `l${i}`); + const neu = old.slice(); + neu[10] = 'changed'; + const r = diffLines(old.join('\n'), neu.join('\n')); + const rows = buildRows(r, 2); + assert.deepEqual(rows.map((row) => row.kind), ['skip', 'equal', 'equal', 'change', 'equal', 'equal', 'skip']); + const change = rows[3]; + assert.equal(change.old.line, 11); + assert.equal(change.new.text, 'changed'); + assert.equal(rows[0].count, 8); + assert.equal(buildRows(r, -1).length, 20); +}); + +test('unified patches apply cleanly with patch(1) (fuzz)', async (t) => { + try { execFileSync('patch', ['--version'], { stdio: 'ignore' }); } catch { t.skip('patch(1) not installed'); return; } + const dir = await mkdtemp(join(tmpdir(), 'docview-diff-')); + t.after(() => rm(dir, { recursive: true, force: true })); + const rand = seeded(7); + for (let i = 0; i < 60; i++) { + const gen = () => `${Array.from({ length: Math.floor(rand() * 40) }, () => 'abcdef'[Math.floor(rand() * 6)]).join('\n')}\n`; + const x = gen(); + const y = gen(); + const patch = toUnifiedPatch(diffLines(x, y), 'a/w.txt', 'b/w.txt'); + if (!patch) { assert.equal(x, y); continue; } + await writeFile(join(dir, 'w.txt'), x); + await writeFile(join(dir, 'p.diff'), patch); + execFileSync('patch', ['-s', join(dir, 'w.txt'), join(dir, 'p.diff')]); + assert.equal(await readFile(join(dir, 'w.txt'), 'utf8'), y); + } +});