~bigbes/sr-ht-compare

ref: a4853d05281d40832e011b6f03a558c7555b997d sr-ht-compare/frontend/src/app.ts -rw-r--r-- 8.5 KiB
a4853d05 — Eugene Blikh rename module to sourcecraft.dev/bigbes/sr-ht-compare; depend on sourcecraft sr-ht-core 30 days ago
                                                                                
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
/*
 * compare.sr.ht frontend bundle.
 *
 * Consumes the SSR DOM contract:
 *   <script id="compare-data" type="application/json">{...}</script>
 *   <div id="tree-root">   (file tree sidebar)
 *   <div id="diff-root">   (per-file diff sections)
 *   <button data-diff-layout="split">  / <button data-diff-layout="stacked">
 *
 * Rendering uses @pierre/diffs (FileDiff vanilla class) for each file and
 * @pierre/trees (FileTree vanilla class) for the sidebar. Both render on the
 * main thread (no worker pool passed) with the pure-JS Shiki engine, so the
 * bundle is fully self-contained (no wasm / no runtime asset fetches).
 */

import { FileDiff, parsePatchFiles } from "@pierre/diffs";
import type { FileDiffMetadata, FileDiffOptions, ThemesType } from "@pierre/diffs";
import { FileTree } from "@pierre/trees";
import type { GitStatus, GitStatusEntry } from "@pierre/trees";

// ---- DOM contract types (produced by the Go web layer) --------------------

type Layout = "split" | "stacked";

interface FileEntry {
  path: string;
  oldPath: string;
  status: string; // "A" | "M" | "D" | "R" | ...
  additions: number;
  deletions: number;
  binary: boolean;
}

interface CompareData {
  mode: "compare" | "commit";
  patch: string;
  truncated: boolean;
  files: FileEntry[];
  spec: { base: string; head: string; threeDot: boolean };
}

// ---- Constants ------------------------------------------------------------

const LAYOUT_KEY = "compare.layout";
const DEFAULT_LAYOUT: Layout = "stacked";

// Auto light/dark: FileDiff selects the entry matching `themeType`. With
// themeType "system" it follows prefers-color-scheme at runtime.
const THEME: ThemesType = { light: "github-light", dark: "github-dark" };

// ---- Small helpers --------------------------------------------------------

function el<K extends keyof HTMLElementTagNameMap>(
  tag: K,
  className?: string,
  text?: string,
): HTMLElementTagNameMap[K] {
  const node = document.createElement(tag);
  if (className) node.className = className;
  if (text != null) node.textContent = text;
  return node;
}

function readLayout(): Layout {
  try {
    const v = localStorage.getItem(LAYOUT_KEY);
    if (v === "split" || v === "stacked") return v;
  } catch {
    /* localStorage may be unavailable (private mode); fall through */
  }
  return DEFAULT_LAYOUT;
}

function writeLayout(layout: Layout): void {
  try {
    localStorage.setItem(LAYOUT_KEY, layout);
  } catch {
    /* ignore persistence failures */
  }
}

// "stacked" is the user-facing name for the unified diff style.
function diffStyleFor(layout: Layout): "unified" | "split" {
  return layout === "split" ? "split" : "unified";
}

function gitStatusFor(status: string): GitStatus {
  switch (status.toUpperCase()[0]) {
    case "A":
      return "added";
    case "D":
      return "deleted";
    case "R":
      return "renamed";
    case "M":
    default:
      return "modified";
  }
}

function sectionId(index: number): string {
  return `file-${index}`;
}

// ---- Main -----------------------------------------------------------------

function readData(): CompareData | null {
  const script = document.getElementById("compare-data");
  if (!script || !script.textContent) return null;
  try {
    return JSON.parse(script.textContent) as CompareData;
  } catch (err) {
    console.error("compare: failed to parse #compare-data", err);
    return null;
  }
}

function buildFileHeader(index: number, file: FileEntry): HTMLElement {
  const header = el("div", "diff-file-header");

  const path = el("span", "diff-file-path");
  if (file.oldPath && file.oldPath !== file.path) {
    path.append(
      el("span", "diff-file-oldpath", file.oldPath),
      el("span", "diff-file-arrow", " → "),
      el("span", "diff-file-newpath", file.path),
    );
  } else {
    path.textContent = file.path;
  }
  header.append(path);

  const stats = el("span", "diff-file-stats");
  if (file.additions > 0) {
    stats.append(el("span", "diff-file-add", `+${file.additions}`));
  }
  if (file.deletions > 0) {
    stats.append(el("span", "diff-file-del", `-${file.deletions}`));
  }
  header.append(stats);

  if (file.binary) {
    header.append(el("span", "diff-file-badge diff-file-binary", "BIN"));
  }

  header.dataset.fileIndex = String(index);
  return header;
}

function renderDiffs(
  root: HTMLElement,
  data: CompareData,
  metaByPath: Map<string, FileDiffMetadata>,
  layout: Layout,
): FileDiff[] {
  root.textContent = "";
  const instances: FileDiff[] = [];

  if (data.files.length === 0) {
    root.append(el("div", "diff-empty", "No changes to display."));
    return instances;
  }

  const style = diffStyleFor(layout);

  data.files.forEach((file, index) => {
    const section = el("section", "diff-file");
    section.id = sectionId(index);
    section.dataset.path = file.path;
    section.append(buildFileHeader(index, file));

    const body = el("div", "diff-file-body");
    section.append(body);
    root.append(section);

    if (file.binary) {
      body.append(el("div", "diff-file-note", "Binary file not shown."));
      return;
    }

    const meta = metaByPath.get(file.path);
    if (!meta) {
      body.append(el("div", "diff-file-note", "No textual diff available."));
      return;
    }

    const options: FileDiffOptions<undefined> = {
      theme: THEME,
      themeType: "system",
      diffStyle: style,
      // We render our own header row above, so disable the library header.
      disableFileHeader: true,
    };
    const instance = new FileDiff(options);
    instance.render({ fileDiff: meta, containerWrapper: body });
    instances.push(instance);
  });

  return instances;
}

function buildTree(
  root: HTMLElement,
  data: CompareData,
): FileTree | null {
  root.textContent = "";
  if (data.files.length === 0) return null;

  const paths = data.files.map((f) => f.path);
  const gitStatus: GitStatusEntry[] = data.files.map((f) => ({
    path: f.path,
    status: gitStatusFor(f.status),
  }));

  const indexByPath = new Map(data.files.map((f, i) => [f.path, i]));

  const tree = new FileTree({
    paths,
    gitStatus,
    initialExpansion: "open",
    onSelectionChange: (selected) => {
      const path = selected[0];
      if (path == null) return;
      const index = indexByPath.get(String(path));
      if (index == null) return;
      const section = document.getElementById(sectionId(index));
      section?.scrollIntoView({ behavior: "smooth", block: "start" });
    },
  });
  tree.render({ containerWrapper: root });
  return tree;
}

function wireLayoutToggle(
  buttons: HTMLButtonElement[],
  getInstances: () => FileDiff[],
  initial: Layout,
): void {
  let current = initial;

  const apply = (layout: Layout) => {
    current = layout;
    writeLayout(layout);
    for (const btn of buttons) {
      btn.classList.toggle("active", btn.dataset.diffLayout === layout);
    }
    const style = diffStyleFor(layout);
    for (const instance of getInstances()) {
      instance.setOptions({
        theme: THEME,
        themeType: "system",
        diffStyle: style,
        disableFileHeader: true,
      });
      instance.rerender();
    }
  };

  for (const btn of buttons) {
    btn.addEventListener("click", (ev) => {
      ev.preventDefault();
      const layout = btn.dataset.diffLayout;
      if (layout === "split" || layout === "stacked") apply(layout);
    });
  }

  // Reflect the initial (possibly persisted) layout on the buttons.
  for (const btn of buttons) {
    btn.classList.toggle("active", btn.dataset.diffLayout === current);
  }
}

function main(): void {
  const data = readData();
  if (!data) return;

  const diffRoot = document.getElementById("diff-root");
  const treeRoot = document.getElementById("tree-root");
  if (!diffRoot) return;

  const layout = readLayout();

  // parsePatchFiles returns one ParsedPatch per commit; each has a `files`
  // array of FileDiffMetadata. Flatten across patches and index by path.
  const metaByPath = new Map<string, FileDiffMetadata>();
  if (data.patch) {
    try {
      for (const patch of parsePatchFiles(data.patch)) {
        for (const meta of patch.files) {
          metaByPath.set(meta.name, meta);
        }
      }
    } catch (err) {
      console.error("compare: failed to parse patch", err);
    }
  }

  const instances = renderDiffs(diffRoot, data, metaByPath, layout);
  if (treeRoot) buildTree(treeRoot, data);

  const buttons = Array.from(
    document.querySelectorAll<HTMLButtonElement>("button[data-diff-layout]"),
  );
  if (buttons.length > 0) {
    wireLayoutToggle(buttons, () => instances, layout);
  }
}

if (document.readyState === "loading") {
  document.addEventListener("DOMContentLoaded", main);
} else {
  main();
}