git-tm 1.2.0 → 2.0.0

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.
@@ -250,45 +250,84 @@ export async function mountChanges(el, opts) {
250
250
  };
251
251
  const { from = "", to } = opts;
252
252
 
253
- async function load() {
254
- el.innerHTML = String(loading("Loading changes"));
253
+ let gen = 0;
254
+
255
+ function summaryHtml(files, additions, deletions) {
256
+ return html`${plural(files.length, "file")} changed
257
+ ${additions ? html`<span class="a">+${additions.toLocaleString()}</span>` : ""}
258
+ ${deletions ? html`<span class="d">−${deletions.toLocaleString()}</span>` : ""}`;
259
+ }
260
+
261
+ async function load({ preserve = false } = {}) {
262
+ const my = ++gen;
263
+ const openPaths = preserve
264
+ ? new Set(
265
+ $$(".file.open", el)
266
+ .map((s) => state.data?.files[Number(s.dataset.i)]?.path)
267
+ .filter(Boolean),
268
+ )
269
+ : null;
270
+ if (!preserve) el.innerHTML = String(loading("Loading changes"));
255
271
  try {
256
- state.data = await api("files", { from, to, ws: state.ws });
272
+ const data = await api("files", { from, to, ws: state.ws });
273
+ if (my !== gen) return;
274
+ state.data = data;
257
275
  } catch (err) {
258
- el.innerHTML = String(errorBox(err));
276
+ if (my !== gen) return;
277
+ const box = preserve ? $(".files", el) : null;
278
+ if (box) box.innerHTML = String(errorBox(err));
279
+ else el.innerHTML = String(errorBox(err));
259
280
  return;
260
281
  }
261
- draw();
282
+ draw({ preserve, openPaths });
262
283
  }
263
284
 
264
- function draw() {
285
+ function draw({ preserve = false, openPaths = null } = {}) {
265
286
  const { files, additions, deletions } = state.data;
266
- if (!files.length) {
267
- el.innerHTML = `<div class="empty"><strong>No changes</strong><span>${state.ws ? "Only whitespace differs." : "Both sides have identical trees."}</span></div>`;
287
+ const emptyMsg = `<div class="empty"><strong>No changes</strong><span>${state.ws ? "Only whitespace differs." : "Both sides have identical trees."}</span></div>`;
288
+ if (!files.length && !preserve && !state.ws) {
289
+ el.innerHTML = emptyMsg;
268
290
  return;
269
291
  }
270
- el.innerHTML = String(html`
271
- <div class="changes-bar">
272
- <span class="summary">${plural(files.length, "file")} changed
273
- ${additions ? html`<span class="a">+${additions.toLocaleString()}</span>` : ""}
274
- ${deletions ? html`<span class="d">−${deletions.toLocaleString()}</span>` : ""}</span>
275
- ${opts.note ? html`<span class="muted small">${opts.note}</span>` : ""}
276
- <span class="spacer"></span>
277
- <div class="seg" role="group" aria-label="Diff layout">
278
- <button data-act="layout" data-split="0" aria-pressed="${!state.split}">Unified</button>
279
- <button data-act="layout" data-split="1" aria-pressed="${state.split}">Split</button>
292
+ if (preserve && $(".changes-bar", el)) {
293
+ $(".summary", el).innerHTML = String(summaryHtml(files, additions, deletions));
294
+ const box = $(".files", el);
295
+ box.innerHTML = files.length
296
+ ? files.map((f, i) => String(html`<section class="file" data-i="${i}">${fileHeader(f)}<div class="file-body" hidden></div></section>`)).join("")
297
+ : emptyMsg;
298
+ const expandBtn = $('[data-act="expand-all"]', el);
299
+ if (expandBtn) expandBtn.textContent = "Expand all";
300
+ } else {
301
+ el.innerHTML = String(html`
302
+ <div class="changes-bar">
303
+ <span class="summary">${summaryHtml(files, additions, deletions)}</span>
304
+ ${opts.note ? html`<span class="muted small">${opts.note}</span>` : ""}
305
+ <span class="spacer"></span>
306
+ <div class="seg" role="group" aria-label="Diff layout">
307
+ <button data-act="layout" data-split="0" aria-pressed="${!state.split}">Unified</button>
308
+ <button data-act="layout" data-split="1" aria-pressed="${state.split}">Split</button>
309
+ </div>
310
+ <label class="check" title="Ignore whitespace changes"><input type="checkbox" data-act="ws" ${state.ws ? "checked" : ""}> Hide whitespace</label>
311
+ <button class="btn btn-sm btn-ghost" data-act="expand-all">Expand all</button>
280
312
  </div>
281
- <label class="check" title="Ignore whitespace changes"><input type="checkbox" data-act="ws" ${state.ws ? "checked" : ""}> Hide whitespace</label>
282
- <button class="btn btn-sm btn-ghost" data-act="expand-all">Expand all</button>
283
- </div>
284
- <div class="files">${files.map(
285
- (f, i) => html`<section class="file" data-i="${i}">${fileHeader(f)}<div class="file-body" hidden></div></section>`,
286
- )}</div>`);
313
+ <div class="files">${
314
+ files.length
315
+ ? files.map((f, i) => html`<section class="file" data-i="${i}">${fileHeader(f)}<div class="file-body" hidden></div></section>`)
316
+ : raw(emptyMsg)
317
+ }</div>`);
318
+ }
287
319
 
288
- // Open small change sets right away.
289
- const total = additions + deletions;
290
- const auto = files.length <= 8 && total <= 600 ? files.length : files.length <= 30 ? 1 : 0;
291
- $$(".file", el).slice(0, auto).forEach((sec) => toggle(sec, true));
320
+ if (!files.length) return;
321
+ if (openPaths) {
322
+ $$(".file", el).forEach((sec) => {
323
+ if (openPaths.has(files[Number(sec.dataset.i)].path)) toggle(sec, true);
324
+ });
325
+ } else {
326
+ // Open small change sets right away.
327
+ const total = additions + deletions;
328
+ const auto = files.length <= 8 && total <= 600 ? files.length : files.length <= 30 ? 1 : 0;
329
+ $$(".file", el).slice(0, auto).forEach((sec) => toggle(sec, true));
330
+ }
292
331
  }
293
332
 
294
333
  async function toggle(sec, open) {
@@ -338,12 +377,15 @@ export async function mountChanges(el, opts) {
338
377
  switch (t.dataset.act) {
339
378
  case "toggle":
340
379
  return toggle(sec);
341
- case "layout":
342
- state.split = t.dataset.split === "1";
380
+ case "layout": {
381
+ const next = t.dataset.split === "1";
382
+ if (next === state.split) return;
383
+ state.split = next;
343
384
  storage.set("split", state.split);
344
385
  $$("[data-act=layout]", el).forEach((b) => b.setAttribute("aria-pressed", String(b === t)));
345
386
  for (const s of $$(".file", el)) if (s._res) paint(s);
346
387
  return;
388
+ }
347
389
  case "expand-all": {
348
390
  const secs = $$(".file", el);
349
391
  const anyClosed = secs.some((s) => !s.classList.contains("open"));
@@ -366,7 +408,7 @@ export async function mountChanges(el, opts) {
366
408
  if (e.target.dataset.act === "ws") {
367
409
  state.ws = e.target.checked;
368
410
  storage.set("ignore-ws", state.ws);
369
- load();
411
+ load({ preserve: true });
370
412
  }
371
413
  };
372
414
 
@@ -0,0 +1,384 @@
1
+ // Edit mode UI (`git tm --edit`): change a commit, preview the alternate timeline, apply, undo.
2
+ // The server does all the work and the safety checks; this module only collects input and
3
+ // shows what will happen before anything changes.
4
+
5
+ import { api, html, $, short, toast, relTime, fullDate, errorBox, loading } from "./ui.js";
6
+
7
+ const OPS = {
8
+ reword: { label: "Reword", desc: "Change the commit message." },
9
+ author: { label: "Change author", desc: "Change who wrote it, or when." },
10
+ date: { label: "Change date", desc: "Change when this commit was authored." },
11
+ squash: { label: "Squash into parent", desc: "Fold this commit into the one before it." },
12
+ drop: { label: "Drop", desc: "Remove this commit and its changes." },
13
+ revert: { label: "Revert", desc: "Add a new commit that undoes this one. Nothing is rewritten." },
14
+ };
15
+
16
+ const TREE_CHANGING = new Set(["drop", "revert"]);
17
+ const STATUS = { A: "added", D: "deleted", M: "modified", R: "renamed", C: "copied", T: "modified" };
18
+
19
+ function gitAtLeast(version, major, minor) {
20
+ const m = String(version || "").match(/(\d+)\.(\d+)/);
21
+ return Boolean(m) && (Number(m[1]) > major || (Number(m[1]) === major && Number(m[2]) >= minor));
22
+ }
23
+
24
+ /** Why an edit can't be used on this commit, or "" if it can. */
25
+ export function disabledReason(op, commit, { gitVersion, branches }) {
26
+ if (!branches.length) return "Not on a local branch";
27
+ const parents = commit.parents.length;
28
+ if ((op === "squash" || op === "drop" || op === "revert") && parents === 0) return "The first commit";
29
+ if ((op === "squash" || op === "drop" || op === "revert") && parents > 1) return "Merge commit";
30
+ if (TREE_CHANGING.has(op) && !gitAtLeast(gitVersion, 2, 40)) return "Needs Git 2.40+";
31
+ return "";
32
+ }
33
+
34
+ function dialogEl() {
35
+ let dlg = document.getElementById("edit-dialog");
36
+ if (!dlg) {
37
+ dlg = document.createElement("dialog");
38
+ dlg.id = "edit-dialog";
39
+ dlg.className = "edit-dialog";
40
+ dlg.setAttribute("aria-labelledby", "edit-title");
41
+ document.body.append(dlg);
42
+ }
43
+ return dlg;
44
+ }
45
+
46
+ /** Open the edit dialog for a commit (from the commit detail pane). */
47
+ export async function openEdit(app, commit) {
48
+ const dlg = dialogEl();
49
+ const s = { step: "choose", op: null, branch: null, branches: [], fields: {}, preview: null, error: null, busy: false, confirmed: false };
50
+
51
+ // Attach handlers first, so even the error view below (with its Close button) works.
52
+ // They only call function declarations further down, which are hoisted.
53
+ dlg.onclick = (e) => {
54
+ if (e.target === dlg) return dlg.close(); // backdrop
55
+ const opBtn = e.target.closest("[data-op]");
56
+ if (opBtn && !opBtn.disabled) return startForm(opBtn.dataset.op);
57
+ const act = e.target.closest("[data-act]")?.dataset.act;
58
+ if (act === "close") dlg.close();
59
+ else if (act === "back") {
60
+ s.step = "choose";
61
+ drawChoose();
62
+ } else if (act === "back-form") {
63
+ s.step = "form";
64
+ drawForm();
65
+ } else if (act === "preview") preview();
66
+ else if (act === "apply") apply();
67
+ };
68
+ dlg.onchange = (e) => {
69
+ const k = e.target.dataset?.field;
70
+ if (k === "confirm") {
71
+ s.confirmed = e.target.checked;
72
+ const btn = $('[data-act="apply"]', dlg);
73
+ if (btn) btn.disabled = !s.confirmed;
74
+ } else if (k === "changeDate") {
75
+ readFields();
76
+ drawForm();
77
+ }
78
+ };
79
+
80
+ dlg.innerHTML = String(loading("Checking branches"));
81
+ if (!dlg.open) dlg.showModal();
82
+ try {
83
+ const res = await api("contains", { rev: commit.hash });
84
+ s.branches = res.branches;
85
+ } catch (err) {
86
+ dlg.innerHTML = String(html`${errorBox(err)}<div class="edit-actions"><button class="btn" data-act="close">Close</button></div>`);
87
+ return;
88
+ }
89
+ s.branch = s.branches.includes(app.repo.branch) ? app.repo.branch : s.branches[0] || null;
90
+
91
+ function header(title) {
92
+ return html`<div class="edit-head">
93
+ <h2 id="edit-title">${title}</h2>
94
+ <span class="sha-pill" title="${commit.hash}">${short(commit.hash)}</span>
95
+ <span class="edit-subject">${commit.subject}</span>
96
+ </div>`;
97
+ }
98
+
99
+ function branchPicker() {
100
+ if (s.branches.length <= 1) return s.branch ? html`<p class="muted small">On branch <strong>${s.branch}</strong></p>` : "";
101
+ return html`<label class="edit-field"><span>Branch to change</span>
102
+ <select data-field="branch">${s.branches.map((b) => html`<option value="${b}" ${b === s.branch ? "selected" : ""}>${b}</option>`)}</select></label>`;
103
+ }
104
+
105
+ function drawChoose() {
106
+ const ctx = { gitVersion: app.repo.gitVersion, branches: s.branches };
107
+ dlg.innerHTML = String(html`
108
+ ${header("Edit commit")}
109
+ <div class="edit-ops">${Object.entries(OPS).map(([op, o]) => {
110
+ const why = disabledReason(op, commit, ctx);
111
+ return html`<button class="edit-op" data-op="${op}" ${why ? "disabled" : ""}>
112
+ <strong>${o.label}</strong><span>${why || o.desc}</span></button>`;
113
+ })}</div>
114
+ <p class="muted small">You'll see a preview of the new timeline before anything changes, and every edit can be undone.</p>
115
+ <div class="edit-actions"><button class="btn" data-act="close">Cancel</button></div>`);
116
+ }
117
+
118
+ function drawForm() {
119
+ const f = s.fields;
120
+ let body = "";
121
+ if (s.op === "reword" || s.op === "squash") {
122
+ body = html`<label class="edit-field"><span>${s.op === "squash" ? "Message for the combined commit" : "Commit message"}</span>
123
+ <textarea data-field="message" rows="8" spellcheck="true">${f.message ?? ""}</textarea></label>`;
124
+ } else if (s.op === "author") {
125
+ body = html`<label class="edit-field"><span>Name</span><input data-field="name" value="${f.name ?? ""}" autocomplete="off" /></label>
126
+ <label class="edit-field"><span>Email</span><input data-field="email" value="${f.email ?? ""}" autocomplete="off" /></label>
127
+ <label class="edit-check"><input type="checkbox" data-field="changeDate" ${f.changeDate ? "checked" : ""} /> Change the date too</label>
128
+ ${f.changeDate ? html`<label class="edit-field"><span>Date</span><input type="datetime-local" data-field="date" value="${f.date ?? ""}" step="1" /></label>` : ""}`;
129
+ } else if (s.op === "date") {
130
+ body = html`<label class="edit-field"><span>Author date</span><input type="datetime-local" data-field="date" value="${f.date ?? ""}" step="1" /></label>`;
131
+ } else if (s.op === "drop") {
132
+ body = html`<p>This removes <strong>${commit.subject}</strong> and its changes from the branch. Later commits are kept and re-applied without it.</p>`;
133
+ } else if (s.op === "revert") {
134
+ body = html`<p>This adds a new commit on top of the branch that undoes <strong>${commit.subject}</strong>. Existing commits stay exactly as they are, so it's safe even if they're already pushed.</p>`;
135
+ }
136
+ dlg.innerHTML = String(html`
137
+ ${header(OPS[s.op].label)}
138
+ ${branchPicker()}
139
+ <div class="edit-form">${body}</div>
140
+ ${s.error ? errorBox(s.error) : ""}
141
+ <div class="edit-actions">
142
+ <button class="btn" data-act="back">Back</button>
143
+ <span class="spacer"></span>
144
+ <button class="btn btn-primary" data-act="preview" ${s.busy ? "disabled" : ""}>${s.busy ? "Working…" : "Preview"}</button>
145
+ </div>`);
146
+ $("textarea, input:not([type=checkbox])", dlg)?.focus();
147
+ }
148
+
149
+ function timelineRows(plan) {
150
+ const rows = [];
151
+ for (const r of plan.rewritten) {
152
+ rows.push(html`<li class="${r.new ? "" : "dropped"}">
153
+ <code class="old">${short(r.old)}</code><span class="arrow">${r.new ? "→" : "×"}</span>
154
+ <code class="new">${r.new ? short(r.new) : "removed"}</code><span class="subj">${r.subject}</span></li>`);
155
+ }
156
+ for (const a of plan.added) {
157
+ rows.push(html`<li class="added"><code class="old">new</code><span class="arrow">+</span><code class="new">${short(a.new)}</code><span class="subj">${a.subject}</span></li>`);
158
+ }
159
+ return rows;
160
+ }
161
+
162
+ function drawPreview(files) {
163
+ const p = s.preview.plan;
164
+ const pushed = p.pushed.length > 0 && p.type !== "revert";
165
+ const fileNote = files === null
166
+ ? html`<span class="muted small">Loading file changes…</span>`
167
+ : files.files.length
168
+ ? html`<div class="edit-files">${files.files.slice(0, 12).map((f) => html`<div><span class="status status-${STATUS[f.status] || "modified"}">${f.status}</span><code>${f.path}</code><span class="add">+${f.additions}</span><span class="del">−${f.deletions}</span></div>`)}${files.files.length > 12 ? html`<div class="muted small">and ${files.files.length - 12} more</div>` : ""}</div>`
169
+ : html`<p class="muted small">No file changes: only commit details change, so your working tree isn't touched.</p>`;
170
+ dlg.innerHTML = String(html`
171
+ ${header("Preview the new timeline")}
172
+ <p class="edit-summary">${p.summary}</p>
173
+ <ul class="edit-timeline">${timelineRows(p)}</ul>
174
+ <h3 class="edit-sub">Files at the tip of ${p.branch}</h3>
175
+ ${fileNote}
176
+ ${p.warnings.filter((w) => !w.startsWith("Paradox")).map((w) => html`<p class="edit-warn">${w}</p>`)}
177
+ ${pushed ? html`<div class="edit-danger">
178
+ <strong>These commits are already on ${p.pushed.join(", ")}.</strong>
179
+ <p>Rewriting pushed history means a force-push, and anyone who already pulled these commits will have a different history from you. It can get messy. Revert is the safe alternative.</p>
180
+ <label class="edit-check"><input type="checkbox" data-field="confirm" ${s.confirmed ? "checked" : ""} /> I understand this rewrites shared history</label>
181
+ </div>` : ""}
182
+ ${s.error ? errorBox(s.error) : ""}
183
+ <div class="edit-actions">
184
+ <button class="btn" data-act="back-form">Back</button>
185
+ <span class="spacer"></span>
186
+ <button class="btn btn-primary" data-act="apply" ${(pushed && !s.confirmed) || s.busy ? "disabled" : ""}>${s.busy ? "Applying…" : "Apply"}</button>
187
+ </div>`);
188
+ }
189
+
190
+ async function startForm(op) {
191
+ s.op = op;
192
+ s.error = null;
193
+ s.fields = {};
194
+ if (op === "reword") s.fields.message = commit.body ? `${commit.subject}\n\n${commit.body}` : commit.subject;
195
+ if (op === "author" || op === "date") {
196
+ const d = new Date(commit.date * 1000);
197
+ const local = new Date(d.getTime() - d.getTimezoneOffset() * 60000).toISOString().slice(0, 19);
198
+ s.fields = { name: commit.author, email: commit.email, changeDate: op === "date", date: local };
199
+ }
200
+ if (op === "squash") {
201
+ try {
202
+ const parent = (await api("commit", { rev: commit.parents[0] })).commit;
203
+ const msg = (c) => (c.body ? `${c.subject}\n\n${c.body}` : c.subject);
204
+ s.fields.message = `${msg(parent)}\n\n${msg(commit)}`;
205
+ } catch {
206
+ s.fields.message = commit.subject;
207
+ }
208
+ }
209
+ s.step = "form";
210
+ drawForm();
211
+ }
212
+
213
+ function readFields() {
214
+ for (const el of dlg.querySelectorAll("[data-field]")) {
215
+ const k = el.dataset.field;
216
+ if (k === "branch") s.branch = el.value;
217
+ else if (k === "confirm") s.confirmed = el.checked;
218
+ else s.fields[k] = el.type === "checkbox" ? el.checked : el.value;
219
+ }
220
+ }
221
+
222
+ async function preview() {
223
+ readFields();
224
+ const f = s.fields;
225
+ const body = { op: s.op === "date" ? "author" : s.op, commit: commit.hash, branch: s.branch };
226
+ if (s.op === "reword" || s.op === "squash") body.message = f.message;
227
+ if (s.op === "author" || s.op === "date") {
228
+ body.author = { name: f.name, email: f.email };
229
+ if ((s.op === "date" || f.changeDate) && f.date) {
230
+ const t = new Date(f.date).getTime();
231
+ if (Number.isNaN(t)) {
232
+ s.error = new Error("That date isn't valid");
233
+ return drawForm();
234
+ }
235
+ body.author.date = Math.floor(t / 1000);
236
+ } else if (s.op === "date") {
237
+ s.error = new Error("Pick a date");
238
+ return drawForm();
239
+ }
240
+ }
241
+ s.busy = true;
242
+ s.error = null;
243
+ drawForm();
244
+ try {
245
+ s.preview = await api("edit/preview", {}, { method: "POST", body });
246
+ s.confirmed = false;
247
+ s.busy = false;
248
+ s.step = "preview";
249
+ drawPreview(null);
250
+ const p = s.preview.plan;
251
+ const files = await api("files", { from: p.oldTip, to: p.newTip }).catch(() => ({ files: [] }));
252
+ if (s.step === "preview" && s.preview?.plan === p) drawPreview(files);
253
+ s.files = files;
254
+ } catch (err) {
255
+ s.busy = false;
256
+ s.error = err.conflicts?.length ? new Error(`${err.message} Conflicting files: ${err.conflicts.join(", ")}`) : err;
257
+ drawForm();
258
+ }
259
+ }
260
+
261
+ async function apply() {
262
+ readFields();
263
+ const p = s.preview.plan;
264
+ s.busy = true;
265
+ s.error = null;
266
+ drawPreview(s.files ?? null);
267
+ try {
268
+ const res = await api("edit/apply", {}, { method: "POST", body: { token: s.preview.token, allowPushed: s.confirmed } });
269
+ dlg.close();
270
+ await app.afterEdit();
271
+ toast(p.type === "revert" ? "Revert commit added" : "History rewritten. A backup was saved.", "success", 8000, {
272
+ label: "Undo",
273
+ onClick: () => undo(app, res.id),
274
+ });
275
+ // Show the commit that took this one's place.
276
+ const replacement = p.rewritten.find((r) => r.old === commit.hash)?.new || (p.type === "revert" ? p.newTip : null);
277
+ app.navigate(replacement ? `#/commit/${replacement}` : "#/");
278
+ } catch (err) {
279
+ s.busy = false;
280
+ s.error = err;
281
+ drawPreview(s.files ?? null);
282
+ }
283
+ }
284
+
285
+ drawChoose();
286
+ }
287
+
288
+ /** Undo an edit by id, with a toast for the result. */
289
+ export async function undo(app, id, newBranch) {
290
+ try {
291
+ const res = await api("edit/undo", {}, { method: "POST", body: { id, newBranch } });
292
+ await app.afterEdit();
293
+ // An open commit pane would otherwise keep showing the undone (now orphaned) commit.
294
+ if (location.hash.startsWith("#/commit/")) app.navigate(`#/commit/${res.newTip}`);
295
+ toast(newBranch ? `Old timeline restored as ${res.branch}` : "Timeline restored", "success");
296
+ return true;
297
+ } catch (err) {
298
+ toast(err.message, "error", 7000);
299
+ return false;
300
+ }
301
+ }
302
+
303
+ /** The "Edits by git-tm" section in the Reflog view: every edit with Undo, or restore as a new branch. */
304
+ export function mountBackups(container, app) {
305
+ let restoring = null;
306
+
307
+ async function render() {
308
+ let backups;
309
+ try {
310
+ backups = (await api("edit/backups")).backups;
311
+ } catch (err) {
312
+ container.innerHTML = String(errorBox(err));
313
+ return;
314
+ }
315
+ if (!backups.length) {
316
+ container.innerHTML = String(html`<div class="edit-backups-empty muted small">Edits you make in edit mode show up here, ready to undo.</div>`);
317
+ return;
318
+ }
319
+ const cleanSummary = (b) => {
320
+ const s = b.summary || b.op;
321
+ return b.op === "undo" ? s.replace(/^Undo:\s*/i, "") : s;
322
+ };
323
+ const opCls = (op) => (op === "undo" ? "undo" : op === "drop" ? "drop" : op === "revert" ? "revert" : "edit");
324
+
325
+ container.innerHTML = String(html`
326
+ <h2 class="edit-backups-title">Edits by git-tm</h2>
327
+ <ul class="edit-backups-list">${backups.slice(0, 20).map((b) => html`<li>
328
+ <div class="edit-backup-main">
329
+ <div class="edit-backup-top">
330
+ <span class="edit-backup-op op-${opCls(b.op)}">${b.op}</span>
331
+ <span class="edit-backup-sum">${cleanSummary(b)}</span>
332
+ </div>
333
+ <div class="edit-backup-meta muted small" title="${fullDate(b.time)}">
334
+ <span>${b.branch}</span>
335
+ <span>·</span>
336
+ <span>${relTime(b.time)}</span>
337
+ ${b.oldTip && b.newTip ? html`<span>·</span>
338
+ <a class="sha-link" href="#/commit/${b.oldTip}" title="Before: ${b.oldTip}">${b.oldTip.slice(0, 6)}</a>
339
+ <span>→</span>
340
+ <a class="sha-link" href="#/commit/${b.newTip}" title="After: ${b.newTip}">${b.newTip.slice(0, 6)}</a>` : ""}
341
+ </div>
342
+ </div>
343
+ <div class="edit-backup-actions">
344
+ ${b.canUndo
345
+ ? html`<button class="btn btn-sm" data-undo="${b.id}">${b.op === "undo" ? "Redo" : "Undo"}</button>`
346
+ : restoring === b.id
347
+ ? html`<form class="edit-restore" data-restore="${b.id}">
348
+ <input name="branch" value="restore/${b.branch}-${b.id.slice(-4)}" aria-label="New branch name" autocomplete="off" />
349
+ <button class="btn btn-sm btn-primary">Create</button>
350
+ <button type="button" class="btn btn-sm btn-ghost" data-restore-cancel>Cancel</button></form>`
351
+ : html`<button class="btn btn-sm btn-ghost" data-restore-open="${b.id}" title="${b.branch} has moved on — restore the old tip as a new branch">Restore as branch…</button>`}
352
+ </div></li>`)}</ul>`);
353
+ }
354
+
355
+ container.onclick = async (e) => {
356
+ const u = e.target.closest("[data-undo]");
357
+ if (u) {
358
+ u.disabled = true;
359
+ if (!(await undo(app, u.dataset.undo))) u.disabled = false;
360
+ return;
361
+ }
362
+ const open = e.target.closest("[data-restore-open]");
363
+ if (open) {
364
+ restoring = open.dataset.restoreOpen;
365
+ await render();
366
+ $(".edit-restore input", container)?.select();
367
+ return;
368
+ }
369
+ if (e.target.closest("[data-restore-cancel]")) {
370
+ restoring = null;
371
+ await render();
372
+ }
373
+ };
374
+ container.onsubmit = async (e) => {
375
+ const form = e.target.closest("[data-restore]");
376
+ if (!form) return;
377
+ e.preventDefault();
378
+ const name = form.elements.branch.value.trim();
379
+ if (await undo(app, form.dataset.restore, name)) restoring = null;
380
+ };
381
+
382
+ render();
383
+ }
384
+
@@ -1,8 +1,9 @@
1
1
  // History view: virtualised commit list with graph + commit detail pane.
2
2
 
3
- import { api, html, raw, esc, $, avatar, refBadges, relTime, fullDate, short, plural, empty, errorBox, loading, icons, storage, WORKTREE } from "./ui.js";
3
+ import { api, html, raw, esc, $, avatar, refBadges, relTime, fullDate, short, plural, empty, errorBox, loading, icons, storage, toast, copyText, openContextMenu, WORKTREE } from "./ui.js";
4
4
  import { createLayout, layout, rowSvg, LANE_W } from "./graph.js";
5
5
  import { renderDetail } from "./detail.js";
6
+ import { openEdit } from "./edit.js";
6
7
 
7
8
  const ROW_H = 34;
8
9
  const PAGE = 400;
@@ -267,6 +268,74 @@ export function createHistory(app) {
267
268
  app.navigate(`#/commit/${c.hash}`);
268
269
  });
269
270
 
271
+ // Listen on the scroller, which holds keyboard focus, so Shift+F10 / the Menu key opens the menu for the selected row.
272
+ $(".log-scroll", el).addEventListener("contextmenu", (e) => {
273
+ const keyboard = e.clientX === 0 && e.clientY === 0;
274
+ const r = e.target.closest(".row") || (keyboard && s.selected >= 0 ? $(`.row[data-i="${s.selected}"]`, rows) : null);
275
+ if (!r) return;
276
+ const i = Number(r.dataset.i);
277
+ const c = s.commits[i];
278
+ if (!c) return;
279
+ s.selected = i;
280
+ paint(true);
281
+ // paint() re-renders the rows, so look the row up again to anchor a keyboard-opened menu.
282
+ const anchor = keyboard ? $(`.row[data-i="${i}"]`, rows) : null;
283
+ const isHead = app.repo?.head && c.hash === app.repo.head;
284
+ // The "Uncommitted changes" row is not a commit: no SHA to copy and nothing to edit.
285
+ const isWt = c.hash === WORKTREE || c.worktree;
286
+ if (isWt) {
287
+ openContextMenu(e, [
288
+ { label: "Open changes", icon: icons.file, onClick: () => app.navigate(`#/commit/${WORKTREE}`) },
289
+ app.repo?.head ? { label: "Compare HEAD to working tree", icon: icons.compare, onClick: () => app.navigate(`#/compare/HEAD..${WORKTREE}`) } : null,
290
+ ], anchor);
291
+ return;
292
+ }
293
+ openContextMenu(e, [
294
+ { label: "Open commit", icon: icons.file, onClick: () => app.navigate(`#/commit/${c.hash}`) },
295
+ "sep",
296
+ {
297
+ label: "Travel from here",
298
+ icon: icons.compare,
299
+ onClick: () => {
300
+ travel.picking = true;
301
+ renderHead();
302
+ pick("from", c);
303
+ },
304
+ },
305
+ {
306
+ label: "Travel to here",
307
+ icon: icons.compare,
308
+ onClick: () => {
309
+ travel.picking = true;
310
+ renderHead();
311
+ pick("to", c);
312
+ },
313
+ },
314
+ !isHead && app.repo?.head ? { label: "Compare to HEAD", icon: icons.history, onClick: () => app.navigate(`#/compare/${c.hash}..HEAD`) } : null,
315
+ "sep",
316
+ { label: `Copy SHA (${short(c.hash)})`, icon: icons.copy, onClick: () => copyText(c.hash, "Commit SHA copied") },
317
+ { label: "Copy subject", icon: icons.copy, onClick: () => copyText(c.subject, "Subject copied") },
318
+ app.repo?.edit ? "sep" : null,
319
+ app.repo?.edit
320
+ ? {
321
+ label: "Edit commit",
322
+ cls: "warn",
323
+ onClick: async () => {
324
+ // The list row has no message body, so a failed load must not open a Reword form without it.
325
+ let full;
326
+ try {
327
+ full = (await api("commit", { rev: c.hash })).commit;
328
+ } catch (err) {
329
+ toast(`Could not load the commit: ${err.message}`, "error");
330
+ return;
331
+ }
332
+ openEdit(app, full);
333
+ },
334
+ }
335
+ : null,
336
+ ], anchor);
337
+ });
338
+
270
339
  head.addEventListener("click", (e) => {
271
340
  const act = e.target.closest("[data-act]");
272
341
  if (!act) return;