local-diff-san 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,209 @@
1
+ """FastAPI web GUI and CLI for local_diff_san."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import argparse
6
+ from pathlib import Path
7
+ import subprocess
8
+ import sys
9
+ import threading
10
+ from typing import Any, Sequence
11
+
12
+ from fastapi import FastAPI, HTTPException, Query
13
+ from fastapi.responses import HTMLResponse
14
+ from pydantic import BaseModel
15
+ import uvicorn
16
+
17
+ from pull_requests_san import local_helpers
18
+ from pull_requests_san.assets import render_html_with_shared_assets
19
+ from pull_requests_san.diff import VALID_DIFF_MODES, VALID_NORMALIZATIONS
20
+
21
+ from local_diff_san import core
22
+
23
+
24
+ _TEMPLATE_PATH = Path(__file__).with_name("templates") / "local_diff.html"
25
+
26
+
27
+ def load_html_template() -> str:
28
+ """Read the local diff viewer HTML template with shared diff CSS/JS injected."""
29
+ return render_html_with_shared_assets(_TEMPLATE_PATH.read_text(encoding="utf-8"))
30
+
31
+
32
+ def _resolve_idea_binary() -> str | None:
33
+ return local_helpers.resolve_idea_binary()
34
+
35
+
36
+ def _resolve_goldendict_binary() -> str | None:
37
+ return local_helpers.resolve_goldendict_binary()
38
+
39
+
40
+ class _CompareRequest(BaseModel):
41
+ mode: str = "git_head" # "file_pair" | "git_head" | "git_dir"
42
+ left_path: str | None = None
43
+ right_path: str | None = None
44
+ path: str | None = None
45
+ rev: str = core.DEFAULT_REV
46
+ active_id: str | None = None
47
+ diff_mode: str = "word"
48
+ normalize: str = "none"
49
+ ignore_punct: bool = False
50
+
51
+
52
+ class _StateHolder:
53
+ def __init__(self, initial_spec: core.LocalDiffSpec) -> None:
54
+ self.lock = threading.RLock()
55
+ self.spec = initial_spec
56
+
57
+
58
+ def _spec_from_request(req: _CompareRequest, current: core.LocalDiffSpec) -> core.LocalDiffSpec:
59
+ m = (req.mode or current.mode).strip().lower()
60
+ rev = (req.rev or current.rev or core.DEFAULT_REV).strip() or core.DEFAULT_REV
61
+ if m == "file_pair":
62
+ lp = (req.left_path or "").strip()
63
+ rp = (req.right_path or "").strip()
64
+ return core.LocalDiffSpec(
65
+ mode="file_pair",
66
+ left_path=str(Path(lp).expanduser().resolve()) if lp else current.left_path,
67
+ right_path=str(Path(rp).expanduser().resolve()) if rp else current.right_path,
68
+ rev=rev,
69
+ )
70
+ raw_p = (req.path or "").strip()
71
+ if raw_p:
72
+ p = Path(raw_p).expanduser()
73
+ resolved = p.resolve() if p.exists() else p.absolute()
74
+ if resolved.is_dir():
75
+ return core.LocalDiffSpec(mode="git_dir", paths=[str(resolved)], rev=rev)
76
+ return core.LocalDiffSpec(mode="git_head", paths=[str(resolved)], rev=rev)
77
+ return core.LocalDiffSpec(mode=current.mode, left_path=current.left_path, right_path=current.right_path, paths=list(current.paths), rev=rev)
78
+
79
+
80
+ def create_app(*, initial_spec: core.LocalDiffSpec | None = None) -> FastAPI:
81
+ """Create the FastAPI application for local file and Git HEAD diff viewing."""
82
+ holder = _StateHolder(initial_spec or core.resolve_spec_from_paths([]))
83
+ app = FastAPI(title="local-diff-san — Sanskrit Local & Git Diff Viewer")
84
+
85
+ @app.get("/", response_class=HTMLResponse)
86
+ def index() -> HTMLResponse:
87
+ return HTMLResponse(load_html_template())
88
+
89
+ @app.get("/api/meta")
90
+ def api_meta() -> dict[str, Any]:
91
+ with holder.lock:
92
+ return {
93
+ "spec": holder.spec.to_dict(),
94
+ "diff_modes": list(VALID_DIFF_MODES),
95
+ "normalizations": list(VALID_NORMALIZATIONS),
96
+ }
97
+
98
+ @app.get("/api/diff")
99
+ def api_diff(
100
+ active_id: str | None = Query(None),
101
+ diff_mode: str = Query("word"),
102
+ normalize: str = Query("none"),
103
+ ignore_punct: bool = Query(False),
104
+ rev: str | None = Query(None),
105
+ ) -> dict[str, Any]:
106
+ try:
107
+ with holder.lock:
108
+ eff_spec = holder.spec
109
+ if rev is not None and rev.strip():
110
+ eff_spec = core.LocalDiffSpec(
111
+ mode=holder.spec.mode,
112
+ left_path=holder.spec.left_path,
113
+ right_path=holder.spec.right_path,
114
+ paths=list(holder.spec.paths),
115
+ rev=rev.strip(),
116
+ )
117
+ return core.build_diff_workspace(
118
+ eff_spec,
119
+ active_id=active_id,
120
+ char_diff_mode=diff_mode,
121
+ normalize=normalize,
122
+ ignore_punct=ignore_punct,
123
+ )
124
+ except FileNotFoundError as exc:
125
+ raise HTTPException(status_code=404, detail=str(exc)) from exc
126
+ except ValueError as exc:
127
+ raise HTTPException(status_code=400, detail=str(exc)) from exc
128
+
129
+ @app.post("/api/compare")
130
+ def api_compare(req: _CompareRequest) -> dict[str, Any]:
131
+ try:
132
+ with holder.lock:
133
+ next_spec = _spec_from_request(req, holder.spec)
134
+ res = core.build_diff_workspace(
135
+ next_spec,
136
+ active_id=req.active_id,
137
+ char_diff_mode=req.diff_mode,
138
+ normalize=req.normalize,
139
+ ignore_punct=req.ignore_punct,
140
+ )
141
+ holder.spec = next_spec
142
+ return res
143
+ except FileNotFoundError as exc:
144
+ raise HTTPException(status_code=404, detail=str(exc)) from exc
145
+ except ValueError as exc:
146
+ raise HTTPException(status_code=400, detail=str(exc)) from exc
147
+
148
+ @app.post("/api/open_in_idea")
149
+ def api_open_in_idea(req: local_helpers.OpenPathIdeaRequest) -> dict[str, Any]:
150
+ try:
151
+ return local_helpers.open_path_in_intellij(
152
+ req.path,
153
+ line=req.line,
154
+ idea_resolver=_resolve_idea_binary,
155
+ popen_fn=subprocess.Popen,
156
+ )
157
+ except FileNotFoundError as exc:
158
+ raise HTTPException(status_code=404, detail=str(exc)) from exc
159
+ except ValueError as exc:
160
+ raise HTTPException(status_code=400, detail=str(exc)) from exc
161
+ except Exception as exc:
162
+ raise HTTPException(status_code=500, detail=str(exc)) from exc
163
+
164
+ @app.post("/api/open_in_goldendict")
165
+ def api_open_in_goldendict(req: local_helpers.OpenGoldenDictRequest) -> dict[str, Any]:
166
+ try:
167
+ return local_helpers.open_in_goldendict(
168
+ req.word,
169
+ gd_resolver=_resolve_goldendict_binary,
170
+ popen_fn=subprocess.Popen,
171
+ )
172
+ except ValueError as exc:
173
+ raise HTTPException(status_code=400, detail=str(exc)) from exc
174
+ except Exception as exc:
175
+ raise HTTPException(status_code=500, detail=str(exc)) from exc
176
+
177
+ return app
178
+
179
+
180
+ def main(argv: Sequence[str] | None = None) -> int:
181
+ p = argparse.ArgumentParser(
182
+ description="Launch local-diff-san — compare a local file vs Git HEAD (or 2 given files) with Sanskrit word/char highlighting.",
183
+ )
184
+ p.add_argument(
185
+ "paths",
186
+ nargs="*",
187
+ help="0 args: changed files in current repo vs --rev; 1 file: compare file vs --rev; 1 dir: changed files in dir; 2 files: compare file1 vs file2.",
188
+ )
189
+ p.add_argument("--rev", default=core.DEFAULT_REV, help="Git revision to compare against (default: HEAD).")
190
+ p.add_argument("--head", action="store_true", help="Always compare passed path(s) against --rev even when 2 files are given.")
191
+ p.add_argument("--port", type=int, default=8772, help="Port to bind on 127.0.0.1 (default: 8772 or next free port).")
192
+ p.add_argument("--no-browser", action="store_true", help="Do not auto-open browser window.")
193
+ args = p.parse_args(argv)
194
+
195
+ spec = core.resolve_spec_from_paths(args.paths, rev=args.rev, force_head=args.head)
196
+ try:
197
+ core.build_diff_workspace(spec)
198
+ except (FileNotFoundError, ValueError) as exc:
199
+ print(f"Error: {exc}", file=sys.stderr)
200
+ return 2
201
+
202
+ app = create_app(initial_spec=spec)
203
+ port = local_helpers.find_free_port(args.port)
204
+ url = f"http://127.0.0.1:{port}/"
205
+ print(f"local-diff-san running at {url} (mode={spec.mode})", flush=True)
206
+ if not args.no_browser:
207
+ threading.Thread(target=local_helpers.launch_browser, args=(url,), daemon=True).start()
208
+ uvicorn.run(app, host="127.0.0.1", port=port, log_level="warning")
209
+ return 0
@@ -0,0 +1,465 @@
1
+ <!DOCTYPE html>
2
+ <html lang="en">
3
+ <head>
4
+ <meta charset="utf-8" />
5
+ <meta name="viewport" content="width=device-width, initial-scale=1" />
6
+ <title>local-diff-san — Sanskrit Local & Git Diff Viewer</title>
7
+ <style>
8
+ /* {{SHARED_DIFF_CSS}} */
9
+ .sidebar-local-files {
10
+ flex: 1;
11
+ }
12
+ .label-pair {
13
+ display: flex;
14
+ gap: 10px;
15
+ flex-wrap: wrap;
16
+ font-size: 15.5px;
17
+ color: var(--muted);
18
+ }
19
+ .label-chip {
20
+ display: inline-flex;
21
+ align-items: center;
22
+ gap: 5px;
23
+ padding: 2px 8px;
24
+ border-radius: 6px;
25
+ border: 1px solid var(--border);
26
+ background: var(--surface);
27
+ }
28
+ .label-chip.left { background: var(--red-row); color: var(--del-text); border-color: var(--del-word-border); }
29
+ .label-chip.right { background: var(--ins-row); color: var(--ins-text); border-color: var(--ins-word-border); }
30
+ table.local-single col.col-num { width: 56px; }
31
+ table.local-single col.col-single-code { width: calc(100% - 112px); }
32
+ table.local-two col.col-num { width: 58px; }
33
+ table.local-two col.col-code { width: calc(50% - 58px); }
34
+ </style>
35
+ </head>
36
+ <body>
37
+ <header>
38
+ <div class="row">
39
+ <strong style="font-size:21px;">local-diff-san</strong>
40
+ <label>Mode:
41
+ <select id="compareModeSelect" onchange="onCompareModeSwitch()">
42
+ <option value="git">Git vs Rev</option>
43
+ <option value="pair">2 Local Files</option>
44
+ </select>
45
+ </label>
46
+ <span id="gitInputsRow" class="row" style="gap:6px;">
47
+ <label>Path: <input id="gitPathInput" type="text" placeholder="file or directory..." style="width:320px;" onkeydown="if(event.key==='Enter') submitCompareSpec()" /></label>
48
+ <label>Rev: <input id="revInput" type="text" value="HEAD" style="width:110px;" onkeydown="if(event.key==='Enter') submitCompareSpec()" /></label>
49
+ </span>
50
+ <span id="pairInputsRow" class="row" style="gap:6px; display:none;">
51
+ <label>Left: <input id="leftPathInput" type="text" placeholder="left/old file..." style="width:260px;" onkeydown="if(event.key==='Enter') submitCompareSpec()" /></label>
52
+ <label>Right: <input id="rightPathInput" type="text" placeholder="right/new file..." style="width:260px;" onkeydown="if(event.key==='Enter') submitCompareSpec()" /></label>
53
+ </span>
54
+ <button id="compareBtn" class="primary" type="button" onclick="submitCompareSpec()">Compare</button>
55
+ <button id="refreshBtn" class="small" type="button" title="Reload from disk & Git (Ctrl+R)" onclick="refreshDiff()">↻ Refresh <span class="kbd-hint">Ctrl+R</span></button>
56
+ <button id="reloadBtn" class="small" type="button" onclick="window.location.reload()">↻ Reload UI</button>
57
+ <span id="statusText" style="color:var(--muted); font-size:16px;"></span>
58
+ </div>
59
+ <div class="row">
60
+ <label>Diff unit:
61
+ <select id="diffModeSelect" onchange="changeDiffOptions()">
62
+ <option value="word" selected>Word (space-separated)</option>
63
+ <option value="grapheme">Char (Grapheme \X)</option>
64
+ <option value="codepoint">Codepoint (Raw)</option>
65
+ </select>
66
+ </label>
67
+ <label title="Apply Unicode normalization before diffing">Norm:
68
+ <select id="normalizeSelect" onchange="changeDiffOptions()">
69
+ <option value="none" selected>None</option>
70
+ <option value="nfc">NFC</option>
71
+ <option value="nfd">NFD</option>
72
+ <option value="nfkc">NFKC</option>
73
+ <option value="nfkd">NFKD</option>
74
+ </select>
75
+ </label>
76
+ <label style="display:inline-flex; align-items:center; gap:5px; cursor:pointer;">
77
+ <input id="ignorePunctChk" type="checkbox" onchange="changeDiffOptions()" /> Ignore punct
78
+ </label>
79
+ <label title="Matches VS Code (25) / IntelliJ IDEA (28)">Editor font (px): <input id="fontPxInput" type="number" min="14" max="42" value="26" style="width:74px;" onchange="applyEditorFont(this.value, 'local_diff_san_font_px')" /></label>
80
+ <label style="display:inline-flex; align-items:center; gap:5px; cursor:pointer;" title="Single pane inline word flow (Alt+S)">
81
+ <input id="singlePaneChk" type="checkbox" checked onchange="toggleSinglePane(this.checked)" /> Single pane <span class="kbd-hint">Alt+S</span>
82
+ </label>
83
+ <label style="display:inline-flex; align-items:center; gap:5px; cursor:pointer;">
84
+ <input id="changedOnlyChk" type="checkbox" onchange="renderWorkspace()" /> Changed lines only
85
+ </label>
86
+ <label style="display:inline-flex; align-items:center; gap:5px; cursor:pointer;">
87
+ <input id="wrapLinesChk" type="checkbox" checked onchange="renderWorkspace()" /> Wrap long lines
88
+ </label>
89
+ <button id="gdSelectionBtn" class="small" type="button" title="Look up currently selected text in GoldenDict" onclick="lookupSelectedGoldenDict()">📖 GoldenDict Selection</button>
90
+ <button id="settingsBtn" class="small" type="button" title="Customize deleted and added diff highlight colors" onclick="toggleSettingsPane()">⚙ Settings</button>
91
+ </div>
92
+ </header>
93
+ <div id="settingsPane" class="settings-drawer" style="display:none;"></div>
94
+
95
+ <div class="workspace">
96
+ <aside class="sidebar">
97
+ <div class="sidebar-section sidebar-local-files">
98
+ <div class="pane-title">
99
+ <span>Compared Files (<span id="fileCountLabel">0</span>)</span>
100
+ <button class="small" type="button" onclick="refreshDiff()">↻</button>
101
+ </div>
102
+ <div id="fileList" class="scroll-list"></div>
103
+ </div>
104
+ </aside>
105
+
106
+ <main id="mainPane">
107
+ <div id="errorBanner" class="error-banner"></div>
108
+ <div id="diffContainer">
109
+ <div class="card">Loading diff...</div>
110
+ </div>
111
+ <div style="color:var(--muted); font-size:15px; padding:4px 0;">Shortcuts: Alt+S Single/2-Pane • Ctrl+R Refresh from disk/Git • j/k/↑/↓ Navigate files • Esc Close Settings</div>
112
+ </main>
113
+ </div>
114
+
115
+ <script>
116
+ // {{SHARED_DIFF_JS}}
117
+ let workspaceData = null;
118
+ let selectedItemId = null;
119
+
120
+ function getDiffMode() {
121
+ return document.getElementById("diffModeSelect")?.value || "word";
122
+ }
123
+
124
+ function getDiffOptions() {
125
+ return {
126
+ diff_mode: getDiffMode(),
127
+ normalize: document.getElementById("normalizeSelect")?.value || "none",
128
+ ignore_punct: !!document.getElementById("ignorePunctChk")?.checked,
129
+ };
130
+ }
131
+
132
+ function isSinglePaneMode() {
133
+ return !!document.getElementById("singlePaneChk")?.checked;
134
+ }
135
+
136
+ function toggleSinglePane(checked) {
137
+ const chk = document.getElementById("singlePaneChk");
138
+ if (chk) chk.checked = !!checked;
139
+ try { localStorage.setItem("local_diff_san_single_pane", checked ? "true" : "false"); } catch (_) {}
140
+ renderWorkspace();
141
+ }
142
+
143
+ function syncSpecInputs(spec) {
144
+ if (!spec) return;
145
+ const isPair = spec.mode === "file_pair";
146
+ const sel = document.getElementById("compareModeSelect");
147
+ if (sel) sel.value = isPair ? "pair" : "git";
148
+ const gitRow = document.getElementById("gitInputsRow");
149
+ const pairRow = document.getElementById("pairInputsRow");
150
+ if (gitRow) gitRow.style.display = isPair ? "none" : "flex";
151
+ if (pairRow) pairRow.style.display = isPair ? "flex" : "none";
152
+ if (isPair) {
153
+ const lp = document.getElementById("leftPathInput");
154
+ const rp = document.getElementById("rightPathInput");
155
+ if (lp) lp.value = spec.left_path || "";
156
+ if (rp) rp.value = spec.right_path || "";
157
+ } else {
158
+ const gp = document.getElementById("gitPathInput");
159
+ const rv = document.getElementById("revInput");
160
+ if (gp) gp.value = (spec.paths && spec.paths[0]) || "";
161
+ if (rv) rv.value = spec.rev || "HEAD";
162
+ }
163
+ }
164
+
165
+ function onCompareModeSwitch() {
166
+ const modeVal = document.getElementById("compareModeSelect")?.value || "git";
167
+ const isPair = modeVal === "pair";
168
+ const gitRow = document.getElementById("gitInputsRow");
169
+ const pairRow = document.getElementById("pairInputsRow");
170
+ if (gitRow) gitRow.style.display = isPair ? "none" : "flex";
171
+ if (pairRow) pairRow.style.display = isPair ? "flex" : "none";
172
+ }
173
+
174
+ function statusPillClass(st) {
175
+ if (st === "added" || st === "untracked") return "pill-green";
176
+ if (st === "deleted") return "pill-red";
177
+ if (st === "unchanged") return "pill-blue";
178
+ return "pill-amber";
179
+ }
180
+
181
+ function renderSidebar() {
182
+ const items = workspaceData?.items || [];
183
+ const cntEl = document.getElementById("fileCountLabel");
184
+ if (cntEl) cntEl.textContent = String(items.length);
185
+ const listEl = document.getElementById("fileList");
186
+ if (!listEl) return;
187
+ if (!items.length) {
188
+ listEl.innerHTML = `<div style="color:var(--muted); font-size:15px;">No modified files.</div>`;
189
+ return;
190
+ }
191
+ const activeId = workspaceData?.active_item?.id || selectedItemId || items[0].id;
192
+ listEl.innerHTML = items.map((it, idx) => {
193
+ const isAct = it.id === activeId;
194
+ return `<div class="file-item ${isAct ? 'active' : ''}" onclick="selectItem('${esc(it.id)}')">
195
+ <div class="mono" style="font-size:15.5px; font-weight:600; word-break:break-word;">${esc(it.title)}</div>
196
+ <div class="file-item-meta">
197
+ <span class="pill ${statusPillClass(it.status)}" style="padding:0 6px; font-size:13.5px;">${esc(it.status)}</span>
198
+ <span style="color:var(--green); font-weight:600;">+${it.additions}</span>
199
+ <span style="color:var(--red); font-weight:600;">-${it.deletions}</span>
200
+ </div>
201
+ </div>`;
202
+ }).join("");
203
+ }
204
+
205
+ function renderLocalLineCell(num, diskPath) {
206
+ const numTxt = num != null ? num : "";
207
+ if (num != null && diskPath) {
208
+ const jsPath = esc(JSON.stringify(diskPath));
209
+ return `<td class="ln clickable" title="Open in IntelliJ IDEA at line ${num}" onclick="openPathInIdea(${jsPath}, ${num})">${numTxt}</td>`;
210
+ }
211
+ return `<td class="ln">${numTxt}</td>`;
212
+ }
213
+
214
+ function renderDiffItemHtml(item) {
215
+ if (!item) {
216
+ return `<div class="card">
217
+ <div><strong>No changed files found</strong> against <span class="mono">${esc(workspaceData?.spec?.rev || 'HEAD')}</span>.</div>
218
+ <div style="color:var(--muted); font-size:16px;">Switch to <strong>2 Local Files</strong> or enter a path above to compare.</div>
219
+ </div>`;
220
+ }
221
+ const singlePane = isSinglePaneMode();
222
+ const changedOnly = !!document.getElementById("changedOnlyChk")?.checked;
223
+ const wrapClass = document.getElementById("wrapLinesChk")?.checked ? "wrap-on" : "wrap-off";
224
+
225
+ let bodyHtml = "";
226
+ if (item.is_binary) {
227
+ bodyHtml = `<div style="padding:12px; color:var(--muted);">Binary file (${esc(item.status)}).</div>`;
228
+ } else if (!(item.hunks || []).length) {
229
+ bodyHtml = `<div style="padding:12px; color:var(--muted);">Empty file or no textual lines.</div>`;
230
+ } else {
231
+ bodyHtml = (item.hunks || []).map(h => {
232
+ const useInline = singlePane && Array.isArray(h.inline_rows) && h.inline_rows.length;
233
+ const baseRows = useInline ? h.inline_rows : (h.rows || []);
234
+ const rows = changedOnly ? baseRows.filter(r => r.kind !== "context") : baseRows;
235
+ if (changedOnly && !rows.length) return "";
236
+ if (useInline) {
237
+ const rowsHtml = rows.map(r => {
238
+ const rowCls = `diff-row single-row-${esc(r.kind || 'modify')}`;
239
+ return `<tr class="${rowCls}">
240
+ ${renderLocalLineCell(r.left_num, item.left_path)}
241
+ ${renderLocalLineCell(r.right_num, item.right_path)}
242
+ <td class="code-cell single-code-cell">${renderDiffSegments(r.segments)}</td>
243
+ </tr>`;
244
+ }).join("");
245
+ return `<div class="hunk-bar">${esc(h.header)}</div>
246
+ <table class="diff-table diff-table-single local-single ${wrapClass}">
247
+ <colgroup><col class="col-num" /><col class="col-num" /><col class="col-single-code" /></colgroup>
248
+ <tbody>${rowsHtml}</tbody>
249
+ </table>`;
250
+ }
251
+ const rowsHtml = rows.map(r => {
252
+ const rowCls = `diff-row diff-row-${esc(r.kind || 'modify')}`;
253
+ const lhsHtml = r.left_text == null ? "" : renderDiffSegments(r.lhs_segments);
254
+ const rhsHtml = r.right_text == null ? "" : renderDiffSegments(r.rhs_segments);
255
+ const lhsCls = r.left_text == null ? "code-cell lhs-cell diff-empty" : "code-cell lhs-cell";
256
+ const rhsCls = r.right_text == null ? "code-cell rhs-cell diff-empty" : "code-cell rhs-cell";
257
+ return `<tr class="${rowCls}">
258
+ ${renderLocalLineCell(r.left_num, item.left_path)}
259
+ <td class="${lhsCls}">${lhsHtml}</td>
260
+ ${renderLocalLineCell(r.right_num, item.right_path)}
261
+ <td class="${rhsCls}">${rhsHtml}</td>
262
+ </tr>`;
263
+ }).join("");
264
+ return `<div class="hunk-bar">${esc(h.header)}</div>
265
+ <table class="diff-table local-two ${wrapClass}">
266
+ <colgroup><col class="col-num" /><col class="col-code" /><col class="col-num" /><col class="col-code" /></colgroup>
267
+ <tbody>${rowsHtml}</tbody>
268
+ </table>`;
269
+ }).join("");
270
+ if (changedOnly && !bodyHtml) {
271
+ bodyHtml = `<div style="padding:12px; color:var(--muted);">No differences under current diff/normalization/punctuation settings.</div>`;
272
+ }
273
+ }
274
+
275
+ const leftBtn = item.left_path
276
+ ? `<button class="small" type="button" onclick="openPathInIdea(${esc(JSON.stringify(item.left_path))}, null)">Open Left in IDEA</button>`
277
+ : "";
278
+ const rightBtn = item.right_path
279
+ ? `<button class="small" type="button" onclick="openPathInIdea(${esc(JSON.stringify(item.right_path))}, null)">Open Right in IDEA</button>`
280
+ : "";
281
+
282
+ return `<div class="file-card focused">
283
+ <div class="file-card-header">
284
+ <div class="row" style="gap:8px;">
285
+ <span class="mono" style="font-weight:700; font-size:18px;">${esc(item.title)}</span>
286
+ <span class="pill ${statusPillClass(item.status)}">${esc(item.status)}</span>
287
+ <span style="color:var(--green); font-weight:600; font-size:16px;">+${item.additions}</span>
288
+ <span style="color:var(--red); font-weight:600; font-size:16px;">-${item.deletions}</span>
289
+ </div>
290
+ <div class="row" style="gap:6px;">
291
+ ${leftBtn}
292
+ ${rightBtn}
293
+ </div>
294
+ </div>
295
+ <div style="padding:7px 12px; background:var(--surface-2); border-bottom:1px solid var(--border);" class="label-pair">
296
+ <span class="label-chip left mono"><strong>Old / Left:</strong> ${esc(item.left_label)}</span>
297
+ <span class="label-chip right mono"><strong>New / Right:</strong> ${esc(item.right_label)}</span>
298
+ </div>
299
+ <div class="file-card-body">${bodyHtml}</div>
300
+ </div>`;
301
+ }
302
+
303
+ function renderWorkspace() {
304
+ renderSidebar();
305
+ const container = document.getElementById("diffContainer");
306
+ if (!container) return;
307
+ container.innerHTML = renderDiffItemHtml(workspaceData?.active_item || null);
308
+ }
309
+
310
+ async function fetchDiff(activeId = null) {
311
+ showError("");
312
+ const opts = getDiffOptions();
313
+ const params = new URLSearchParams({
314
+ diff_mode: opts.diff_mode,
315
+ normalize: opts.normalize,
316
+ ignore_punct: opts.ignore_punct ? "true" : "false",
317
+ });
318
+ if (activeId) params.set("active_id", activeId);
319
+ setStatus("Computing diff...");
320
+ try {
321
+ workspaceData = await apiJson(`/api/diff?${params.toString()}`, null, "Failed to compute diff");
322
+ selectedItemId = workspaceData.active_item?.id || null;
323
+ syncSpecInputs(workspaceData.spec);
324
+ renderWorkspace();
325
+ setStatus("Ready", 1800);
326
+ } catch (e) {
327
+ showError(e.message);
328
+ setStatus("");
329
+ }
330
+ }
331
+
332
+ async function submitCompareSpec() {
333
+ showError("");
334
+ const modeVal = document.getElementById("compareModeSelect")?.value || "git";
335
+ const opts = getDiffOptions();
336
+ const payload = modeVal === "pair"
337
+ ? {
338
+ mode: "file_pair",
339
+ left_path: document.getElementById("leftPathInput")?.value || "",
340
+ right_path: document.getElementById("rightPathInput")?.value || "",
341
+ ...opts,
342
+ }
343
+ : {
344
+ mode: "git_head",
345
+ path: document.getElementById("gitPathInput")?.value || "",
346
+ rev: document.getElementById("revInput")?.value || "HEAD",
347
+ ...opts,
348
+ };
349
+ setStatus("Comparing...");
350
+ try {
351
+ workspaceData = await apiJson("/api/compare", {
352
+ method: "POST",
353
+ headers: { "Content-Type": "application/json" },
354
+ body: JSON.stringify(payload),
355
+ }, "Compare failed");
356
+ selectedItemId = workspaceData.active_item?.id || null;
357
+ syncSpecInputs(workspaceData.spec);
358
+ renderWorkspace();
359
+ setStatus("Updated", 1800);
360
+ } catch (e) {
361
+ showError(e.message);
362
+ setStatus("");
363
+ }
364
+ }
365
+
366
+ async function refreshDiff() {
367
+ return fetchDiff(selectedItemId);
368
+ }
369
+
370
+ async function selectItem(itemId) {
371
+ selectedItemId = itemId;
372
+ return fetchDiff(itemId);
373
+ }
374
+
375
+ async function changeDiffOptions() {
376
+ const opts = getDiffOptions();
377
+ try {
378
+ localStorage.setItem("local_diff_san_diff_mode", opts.diff_mode);
379
+ localStorage.setItem("local_diff_san_normalize", opts.normalize);
380
+ localStorage.setItem("local_diff_san_ignore_punct", opts.ignore_punct ? "true" : "false");
381
+ } catch (_) {}
382
+ return fetchDiff(selectedItemId);
383
+ }
384
+
385
+ async function openPathInIdea(filePath, line = null) {
386
+ showError("");
387
+ try {
388
+ const data = await apiJson("/api/open_in_idea", {
389
+ method: "POST",
390
+ headers: { "Content-Type": "application/json" },
391
+ body: JSON.stringify({ path: filePath, line }),
392
+ }, "Failed to open in IDEA");
393
+ setStatus(`Opened in IDEA: ${data.file_path}`, 2500);
394
+ } catch (e) {
395
+ showError(e.message);
396
+ }
397
+ }
398
+
399
+ async function init() {
400
+ initDiffSettingsPane();
401
+ try {
402
+ const savedPx = localStorage.getItem("local_diff_san_font_px") || localStorage.getItem("github_pr_review_font_px");
403
+ if (savedPx) applyEditorFont(savedPx, "local_diff_san_font_px");
404
+ const savedSingle = localStorage.getItem("local_diff_san_single_pane");
405
+ const spChk = document.getElementById("singlePaneChk");
406
+ if (spChk && (savedSingle === "true" || savedSingle === "false")) spChk.checked = savedSingle === "true";
407
+ const savedMode = localStorage.getItem("local_diff_san_diff_mode");
408
+ const dmSel = document.getElementById("diffModeSelect");
409
+ if (dmSel && savedMode && ["word", "grapheme", "codepoint"].includes(savedMode)) dmSel.value = savedMode;
410
+ const savedNorm = localStorage.getItem("local_diff_san_normalize");
411
+ const normSel = document.getElementById("normalizeSelect");
412
+ if (normSel && savedNorm && ["none", "nfc", "nfd", "nfkc", "nfkd"].includes(savedNorm)) normSel.value = savedNorm;
413
+ const savedIp = localStorage.getItem("local_diff_san_ignore_punct");
414
+ const ipChk = document.getElementById("ignorePunctChk");
415
+ if (ipChk && (savedIp === "true" || savedIp === "false")) ipChk.checked = savedIp === "true";
416
+ } catch (_) {}
417
+ try {
418
+ const meta = await apiJson("/api/meta", null, "Failed to load metadata");
419
+ syncSpecInputs(meta.spec);
420
+ } catch (e) {
421
+ showError(e.message);
422
+ }
423
+ await fetchDiff();
424
+ }
425
+
426
+ document.addEventListener("keydown", (ev) => {
427
+ const target = ev.target;
428
+ const tag = (target && target.tagName || "").toUpperCase();
429
+ if ((ev.key === "r" || ev.key === "R") && ev.ctrlKey && !ev.altKey && !ev.metaKey && !ev.shiftKey) {
430
+ ev.preventDefault();
431
+ refreshDiff();
432
+ return;
433
+ }
434
+ if (ev.altKey && !ev.ctrlKey && !ev.metaKey && !ev.shiftKey) {
435
+ const ak = (ev.key || "").toLowerCase();
436
+ if (ak === "s" || ev.code === "KeyS") {
437
+ ev.preventDefault();
438
+ toggleSinglePane(!isSinglePaneMode());
439
+ return;
440
+ }
441
+ }
442
+ if (ev.key === "Escape" && isSettingsPaneOpen()) {
443
+ ev.preventDefault();
444
+ closeSettingsPane();
445
+ return;
446
+ }
447
+ if (tag === "INPUT" || tag === "TEXTAREA" || tag === "SELECT") return;
448
+ const items = workspaceData?.items || [];
449
+ if (items.length <= 1) return;
450
+ const curIdx = Math.max(0, items.findIndex(it => it.id === selectedItemId));
451
+ if (ev.key === "j" || ev.key === "ArrowDown") {
452
+ ev.preventDefault();
453
+ const nxt = items[Math.min(items.length - 1, curIdx + 1)];
454
+ if (nxt) selectItem(nxt.id);
455
+ } else if (ev.key === "k" || ev.key === "ArrowUp") {
456
+ ev.preventDefault();
457
+ const prev = items[Math.max(0, curIdx - 1)];
458
+ if (prev) selectItem(prev.id);
459
+ }
460
+ });
461
+
462
+ init();
463
+ </script>
464
+ </body>
465
+ </html>