git-tm 1.1.2 → 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.
@@ -1,6 +1,7 @@
1
- import { api, html, raw, $, $$, icons, toast, storage, WORKTREE } from "./ui.js";
1
+ import { api, html, raw, $, $$, icons, toast, storage, copyText, openContextMenu, WORKTREE } from "./ui.js";
2
2
  import { createHistory } from "./history.js";
3
3
  import { createCompare } from "./compare.js";
4
+ import { createReflog } from "./reflog.js";
4
5
  import { createInsights } from "./insights.js";
5
6
 
6
7
  const app = {
@@ -35,6 +36,21 @@ const app = {
35
36
  renderRepo();
36
37
  renderSidebar();
37
38
  },
39
+
40
+ /** After git-tm itself changed history: refresh every view without the "changed on disk" banner. */
41
+ async afterEdit() {
42
+ await app.reloadRepo();
43
+ try {
44
+ fingerprint = (await api("state")).fingerprint;
45
+ } catch {
46
+ /* the next poll catches up */
47
+ }
48
+ $("#banner").hidden = true;
49
+ app.views.history.reload();
50
+ app.views.reflog.invalidate();
51
+ app.views.insights.invalidate();
52
+ if (app.current === "reflog") app.views.reflog.load();
53
+ },
38
54
  };
39
55
 
40
56
  // ------------------------------------------------------------------ search
@@ -91,8 +107,32 @@ function renderRepo() {
91
107
  const r = app.repo;
92
108
  const where = r.branch ?? (r.head ? `detached at ${r.head.slice(0, 7)}` : "no commits yet");
93
109
  $("#repo").innerHTML = String(html`<span class="repo-name" title="${r.root}">${r.name}</span>
94
- <span class="repo-branch" title="Current branch">${raw(icons.branch)}${where}</span>`);
110
+ <span class="repo-branch" title="Current branch">${raw(icons.branch)}${where}</span>
111
+ ${r.edit ? html`<span class="edit-badge" title="Started with --edit: history can be changed. Every edit is backed up and can be undone.">Edit mode</span>` : ""}`);
95
112
  document.title = `${r.name} · Git Time Machine`;
113
+ const mb = $("#mode-banner");
114
+ if (mb) {
115
+ if (r.edit) {
116
+ mb.className = "mode-banner edit";
117
+ mb.hidden = false;
118
+ mb.innerHTML = String(html`<span><strong>Edit mode active</strong> — read-only protection is off. History can be rewritten here; every edit is previewed and backed up for Undo.</span>`);
119
+ mb.onclick = null;
120
+ } else {
121
+ const show = !storage.get("hide-edit-hint", false);
122
+ mb.className = "mode-banner";
123
+ mb.hidden = !show;
124
+ if (show && !mb.childElementCount) {
125
+ mb.innerHTML = String(html`<span><strong>Read-only mode</strong> — want to reword, squash, drop, or revert commits? Restart with <code>git-tm --edit</code></span>
126
+ <button class="icon-btn" data-act="dismiss-mode" title="Dismiss" aria-label="Dismiss">${raw(icons.close)}</button>`);
127
+ mb.onclick = (e) => {
128
+ if (e.target.closest("[data-act=dismiss-mode]")) {
129
+ mb.hidden = true;
130
+ storage.set("hide-edit-hint", true);
131
+ }
132
+ };
133
+ }
134
+ }
135
+ }
96
136
  }
97
137
 
98
138
  const collapsed = new Set(storage.get("collapsed", ["tags"]));
@@ -205,6 +245,7 @@ function route() {
205
245
  const [, view = "", ...rest] = hash.split("/");
206
246
  let name = "history";
207
247
  if (view === "compare") name = "compare";
248
+ else if (view === "reflog") name = "reflog";
208
249
  else if (view === "insights") name = "insights";
209
250
 
210
251
  for (const a of $$("#tabs a")) a.classList.toggle("active", a.dataset.view === name);
@@ -227,6 +268,8 @@ function route() {
227
268
  }
228
269
  } else if (name === "compare") {
229
270
  app.views.compare.load(rest.join("/"));
271
+ } else if (name === "reflog") {
272
+ app.views.reflog.load();
230
273
  } else if (name === "insights") {
231
274
  app.views.insights.load();
232
275
  }
@@ -277,6 +320,7 @@ window.addEventListener("gtm-online", async () => {
277
320
  return;
278
321
  }
279
322
  app.views.history.reload();
323
+ app.views.reflog.invalidate();
280
324
  app.views.insights.invalidate();
281
325
  route();
282
326
  toast("Reconnected to git-tm", "success");
@@ -288,7 +332,9 @@ $("#banner").addEventListener("click", (e) => {
288
332
  $("#banner").hidden = true;
289
333
  if (act === "reload") {
290
334
  app.views.history.reload();
335
+ app.views.reflog.invalidate();
291
336
  app.views.insights.invalidate();
337
+ if (app.current === "reflog") app.views.reflog.load();
292
338
  }
293
339
  });
294
340
 
@@ -342,7 +388,7 @@ function onKey(e) {
342
388
  if (typing || e.metaKey || e.ctrlKey || e.altKey) return;
343
389
  if (pendingG) {
344
390
  pendingG = false;
345
- const to = { h: "#/", c: "#/compare", i: "#/insights" }[e.key];
391
+ const to = { h: "#/", c: "#/compare", r: "#/reflog", i: "#/insights" }[e.key];
346
392
  if (to) {
347
393
  e.preventDefault();
348
394
  return app.navigate(to);
@@ -373,6 +419,27 @@ async function boot() {
373
419
  if (!$("#search").value && app.filter) app.setFilter(null);
374
420
  });
375
421
  $("#sidebar").addEventListener("click", onSidebarClick);
422
+ $("#sidebar").addEventListener("contextmenu", (e) => {
423
+ const item = e.target.closest("[data-ref]");
424
+ if (!item || !item.dataset.ref) return;
425
+ const ref = item.dataset.ref;
426
+ const base = app.repo.branch || "HEAD";
427
+ openContextMenu(e, [
428
+ { label: "View history", icon: icons.history, onClick: () => app.setRef(ref) },
429
+ ref !== base
430
+ ? {
431
+ label: `Compare with ${base}`,
432
+ icon: icons.compare,
433
+ onClick: () => {
434
+ closeSidebar();
435
+ app.navigate(`#/compare/${encodeURIComponent(base)}...${encodeURIComponent(ref)}`);
436
+ },
437
+ }
438
+ : null,
439
+ "sep",
440
+ { label: "Copy ref name", icon: icons.copy, onClick: () => copyText(ref, "Ref name copied") },
441
+ ]);
442
+ });
376
443
  $("#sidebar").addEventListener("keydown", (e) => {
377
444
  if (e.key === "Enter" && e.target.matches("[data-ref]")) app.setRef(e.target.dataset.ref || null);
378
445
  });
@@ -397,6 +464,7 @@ async function boot() {
397
464
 
398
465
  app.views.history = createHistory(app);
399
466
  app.views.compare = createCompare(app);
467
+ app.views.reflog = createReflog(app);
400
468
  app.views.insights = createInsights(app);
401
469
  route();
402
470
 
@@ -0,0 +1,244 @@
1
+ // Reflog view: recent HEAD movements and read-only recovery of lost commits.
2
+
3
+ import { api, html, raw, $, avatar, refBadges, relTime, fullDate, short, plural, icons, copyText, loading, errorBox, empty } from "./ui.js";
4
+ import { mountBackups } from "./edit.js";
5
+
6
+ const PAGE = 200;
7
+
8
+ const ACTION_KIND = {
9
+ commit: "commit",
10
+ amend: "warn",
11
+ reset: "danger",
12
+ rebase: "warn",
13
+ checkout: "move",
14
+ switch: "move",
15
+ merge: "merge",
16
+ pull: "merge",
17
+ "cherry-pick": "merge",
18
+ branch: "move",
19
+ };
20
+
21
+ function rescueCommands(hash) {
22
+ const s = short(hash);
23
+ return [
24
+ { cmd: `git branch rescue-${s} ${s}`, note: "Create a new branch pointing at this commit (safest)" },
25
+ { cmd: `git cherry-pick ${s}`, note: "Apply this commit onto your current branch" },
26
+ { cmd: `git checkout ${s}`, note: "Inspect this commit in detached HEAD" },
27
+ ];
28
+ }
29
+
30
+ function showSubject(entry) {
31
+ if (!entry.subject) return false;
32
+ return !entry.message.includes(entry.subject);
33
+ }
34
+
35
+ export function createReflog(app) {
36
+ const el = document.createElement("div");
37
+ el.className = "reflog page";
38
+
39
+ let entries = [];
40
+ let done = true;
41
+ let loaded = false;
42
+ let gen = 0;
43
+ let onlyLost = false;
44
+ let query = "";
45
+ const expanded = new Set();
46
+
47
+ async function load({ more = false } = {}) {
48
+ if (!more && loaded && el.childElementCount) return;
49
+ const my = ++gen;
50
+ if (!more) {
51
+ entries = [];
52
+ done = true;
53
+ expanded.clear();
54
+ backupsEl = null;
55
+ el.innerHTML = String(html`
56
+ <div class="page-head">
57
+ <h1>Reflog</h1>
58
+ <p class="muted">Recent <code>HEAD</code> movements — inspect or recover commits lost to <code>reset</code>, <code>rebase</code>, <code>amend</code>, or deleted branches.</p>
59
+ </div>
60
+ ${loading("Reading reflog")}`);
61
+ }
62
+ try {
63
+ const res = await api("reflog", { skip: more ? entries.length : 0, limit: PAGE });
64
+ if (my !== gen) return;
65
+ entries = more ? entries.concat(res.entries) : res.entries;
66
+ done = res.done;
67
+ loaded = true;
68
+ draw();
69
+ } catch (err) {
70
+ if (my !== gen) return;
71
+ if (!more) el.lastElementChild.outerHTML = String(errorBox(err));
72
+ }
73
+ }
74
+
75
+ function filtered() {
76
+ const q = query.trim().toLowerCase();
77
+ return entries.filter((e) => {
78
+ if (onlyLost && !e.orphaned) return false;
79
+ if (!q) return true;
80
+ return (
81
+ e.message.toLowerCase().includes(q) ||
82
+ e.subject.toLowerCase().includes(q) ||
83
+ e.action.toLowerCase().includes(q) ||
84
+ e.hash.toLowerCase().startsWith(q) ||
85
+ e.selector.toLowerCase().includes(q)
86
+ );
87
+ });
88
+ }
89
+
90
+ function renderItem(e) {
91
+ const kind = ACTION_KIND[e.action] || "other";
92
+ const isHead = app.repo?.head && e.hash === app.repo.head;
93
+ const isOpen = expanded.has(e.index);
94
+ const cmds = e.orphaned ? rescueCommands(e.hash) : null;
95
+ return html`<article class="reflog-item${e.orphaned ? " orphaned" : ""}" data-index="${e.index}">
96
+ <div class="reflog-row">
97
+ <div class="reflog-left">
98
+ <span class="reflog-sel">${e.selector}</span>
99
+ <span class="reflog-act act-${kind}">${e.action}</span>
100
+ ${e.orphaned ? html`<span class="reflog-lost" title="Not reachable from any branch, remote branch, or tag">lost</span>` : ""}
101
+ </div>
102
+ <div class="reflog-main">
103
+ <div class="reflog-msg">
104
+ <a class="reflog-link" href="#/commit/${e.hash}">${e.message || "(no message)"}</a>
105
+ ${refBadges(e.refs, { max: 4 })}
106
+ </div>
107
+ ${showSubject(e) ? html`<div class="reflog-sub muted small">${e.subject}</div>` : ""}
108
+ </div>
109
+ <div class="reflog-meta">
110
+ <a class="sha-link" href="#/commit/${e.hash}" title="Open commit ${e.hash}">${short(e.hash)}</a>
111
+ ${e.author ? html`<span class="reflog-who" title="${e.author}">${avatar(e.author, e.email, 18)}</span>` : ""}
112
+ <span class="reflog-when muted small" title="${fullDate(e.date)}">${relTime(e.date)}</span>
113
+ </div>
114
+ <div class="reflog-actions">
115
+ ${!isHead && app.repo?.head ? html`<a class="btn btn-sm btn-ghost" href="#/compare/${e.hash}..HEAD" title="Time travel from this commit to HEAD">${raw(icons.compare)} To HEAD</a>` : ""}
116
+ ${e.orphaned ? html`<button class="btn btn-sm ${isOpen ? "btn-primary" : ""}" data-act="rescue" data-index="${e.index}" aria-expanded="${isOpen}">Recover</button>` : ""}
117
+ </div>
118
+ </div>
119
+ ${isOpen && cmds ? html`<div class="rescue-box">
120
+ <div class="rescue-head">
121
+ <strong>Recover commit <code>${short(e.hash)}</code></strong>
122
+ <span class="muted small">git-tm stays read-only — copy a command to run in your terminal.</span>
123
+ </div>
124
+ <div class="rescue-cmds">${cmds.map(
125
+ (c) => html`<div class="rescue-cmd">
126
+ <div class="rescue-line"><code>${c.cmd}</code><button class="btn btn-sm" data-copy-cmd="${c.cmd}">${raw(icons.copy)} Copy</button></div>
127
+ <span class="muted small">${c.note}</span>
128
+ </div>`,
129
+ )}</div>
130
+ </div>` : ""}
131
+ </article>`;
132
+ }
133
+
134
+ function draw() {
135
+ if (!entries.length) {
136
+ el.innerHTML = String(html`
137
+ <div class="page-head">
138
+ <h1>Reflog</h1>
139
+ <p class="muted">Recent <code>HEAD</code> movements — read-only.</p>
140
+ </div>
141
+ ${backupsSlot()}
142
+ ${empty("No reflog entries", "Git records HEAD movements here as you commit, checkout, reset, or rebase.")}`);
143
+ mountSlot();
144
+ return;
145
+ }
146
+
147
+ drawFull();
148
+ }
149
+
150
+ // Edits made in edit mode, with Undo, shown above the reflog when git-tm runs with --edit.
151
+ // One element per load, moved into place on each redraw, so typing in the filter doesn't refetch it.
152
+ let backupsEl = null;
153
+ function backupsSlot() {
154
+ return app.repo?.edit ? html`<div id="edit-backups"></div>` : "";
155
+ }
156
+
157
+ function mountSlot() {
158
+ const slot = $("#edit-backups", el);
159
+ if (!slot) return;
160
+ if (!backupsEl) {
161
+ backupsEl = document.createElement("section");
162
+ backupsEl.className = "edit-backups";
163
+ mountBackups(backupsEl, app);
164
+ }
165
+ slot.replaceWith(backupsEl);
166
+ }
167
+
168
+ function drawFull() {
169
+ const lostCount = entries.filter((e) => e.orphaned).length;
170
+ const list = filtered();
171
+ const hadFocus = document.activeElement?.id === "reflog-filter";
172
+ const selStart = hadFocus ? document.activeElement.selectionStart : null;
173
+
174
+ el.innerHTML = String(html`
175
+ <div class="page-head">
176
+ <h1>Reflog</h1>
177
+ <p class="muted">Recent <code>HEAD</code> movements — inspect or recover commits lost to <code>reset</code>, <code>rebase</code>, <code>amend</code>, or deleted branches.</p>
178
+ </div>
179
+ ${backupsSlot()}
180
+ <div class="reflog-bar">
181
+ <div class="seg" role="group" aria-label="Filter reflog">
182
+ <button data-filter="all" aria-pressed="${!onlyLost}">All <span class="seg-count">${entries.length}</span></button>
183
+ <button data-filter="lost" aria-pressed="${onlyLost}">Lost commits <span class="seg-count${lostCount ? " warn" : ""}">${lostCount}</span></button>
184
+ </div>
185
+ <input id="reflog-filter" class="reflog-search" type="search" value="${query}" placeholder="Filter by action, message, or SHA" autocomplete="off" spellcheck="false" aria-label="Filter reflog entries" />
186
+ <span class="spacer"></span>
187
+ <span class="muted small">${plural(list.length, "entry", "entries")}</span>
188
+ </div>
189
+ ${list.length
190
+ ? html`<div class="reflog-list">${list.map(renderItem)}</div>`
191
+ : empty(onlyLost ? "No lost commits in reflog" : "No matching reflog entries", onlyLost ? "Every recent HEAD commit is reachable from a branch or tag." : "Try clearing the filter.")}
192
+ ${!done ? html`<div class="reflog-more"><button class="btn" data-act="more">Load older entries</button></div>` : ""}`);
193
+
194
+ mountSlot();
195
+
196
+ if (hadFocus) {
197
+ const inp = $("#reflog-filter", el);
198
+ if (inp) {
199
+ inp.focus();
200
+ if (selStart !== null) inp.setSelectionRange(selStart, selStart);
201
+ }
202
+ }
203
+ }
204
+
205
+ el.addEventListener("click", (e) => {
206
+ const copy = e.target.closest("[data-copy-cmd]");
207
+ if (copy) return copyText(copy.dataset.copyCmd, "Command copied");
208
+
209
+ const filterBtn = e.target.closest("[data-filter]");
210
+ if (filterBtn) {
211
+ onlyLost = filterBtn.dataset.filter === "lost";
212
+ draw();
213
+ return;
214
+ }
215
+
216
+ const act = e.target.closest("[data-act]");
217
+ if (!act) return;
218
+ if (act.dataset.act === "rescue") {
219
+ const idx = Number(act.dataset.index);
220
+ if (expanded.has(idx)) expanded.delete(idx);
221
+ else expanded.add(idx);
222
+ draw();
223
+ } else if (act.dataset.act === "more") {
224
+ act.disabled = true;
225
+ act.textContent = "Loading…";
226
+ load({ more: true });
227
+ }
228
+ });
229
+
230
+ el.addEventListener("input", (e) => {
231
+ if (e.target.id === "reflog-filter") {
232
+ query = e.target.value;
233
+ draw();
234
+ }
235
+ });
236
+
237
+ return {
238
+ el,
239
+ load: () => load({ more: false }),
240
+ invalidate() {
241
+ loaded = false;
242
+ },
243
+ };
244
+ }
@@ -4,7 +4,7 @@ export const WORKTREE = "WORKTREE";
4
4
 
5
5
  const avatarMap = Object.create(null);
6
6
 
7
- export async function api(path, params = {}, { method = "GET" } = {}) {
7
+ export async function api(path, params = {}, { method = "GET", body } = {}) {
8
8
  const qs = new URLSearchParams();
9
9
  for (const [k, v] of Object.entries(params)) {
10
10
  if (v !== undefined && v !== null && v !== "" && v !== false) qs.set(k, v === true ? "1" : String(v));
@@ -13,7 +13,9 @@ export async function api(path, params = {}, { method = "GET" } = {}) {
13
13
  const url = `/api/${path}${query ? `?${query}` : ""}`;
14
14
  let res;
15
15
  try {
16
- res = await fetch(url, { method, headers: method === "GET" ? {} : { "x-git-tm": "1" } });
16
+ const headers = method === "GET" ? {} : { "x-git-tm": "1" };
17
+ if (body !== undefined) headers["content-type"] = "application/json";
18
+ res = await fetch(url, { method, headers, body: body === undefined ? undefined : JSON.stringify(body) });
17
19
  } catch {
18
20
  // No HTTP response. Either git-tm stopped, or the browser cancelled the
19
21
  // request (ad blockers do this to URLs that look like tracking). Ask the
@@ -31,7 +33,7 @@ export async function api(path, params = {}, { method = "GET" } = {}) {
31
33
  } catch {
32
34
  throw new Error(`Request failed (${res.status})`);
33
35
  }
34
- if (!res.ok) throw Object.assign(new Error(data.error || `Request failed (${res.status})`), { status: res.status });
36
+ if (!res.ok) throw Object.assign(new Error(data.error || `Request failed (${res.status})`), { status: res.status, conflicts: data.conflicts });
35
37
  if (data && data.avatars) Object.assign(avatarMap, data.avatars);
36
38
  return data;
37
39
  }
@@ -131,13 +133,15 @@ export function avatar(name, email, size = 20) {
131
133
  }
132
134
 
133
135
  // A failed avatar image is simply removed, revealing the initials underneath.
134
- document.addEventListener(
135
- "error",
136
- (e) => {
137
- if (e.target instanceof HTMLImageElement && e.target.parentElement?.classList.contains("avatar")) e.target.remove();
138
- },
139
- true,
140
- );
136
+ if (typeof document !== "undefined") {
137
+ document.addEventListener(
138
+ "error",
139
+ (e) => {
140
+ if (e.target instanceof HTMLImageElement && e.target.parentElement?.classList.contains("avatar")) e.target.remove();
141
+ },
142
+ true,
143
+ );
144
+ }
141
145
 
142
146
  // ------------------------------------------------------------------ refs
143
147
 
@@ -174,18 +178,33 @@ export const icons = {
174
178
 
175
179
  // ------------------------------------------------------------------ toasts
176
180
 
177
- export function toast(message, type = "info", ms = 3500) {
181
+ /** Show a toast. `action` ({ label, onClick }) adds a button, for example Undo. */
182
+ export function toast(message, type = "info", ms = 3500, action = null) {
178
183
  const box = document.getElementById("toasts");
179
184
  const el = document.createElement("div");
180
185
  el.className = `toast toast-${type}`;
181
186
  el.setAttribute("role", type === "error" ? "alert" : "status");
182
- el.textContent = message;
183
- box.append(el);
184
- requestAnimationFrame(() => el.classList.add("in"));
185
- setTimeout(() => {
187
+ const text = document.createElement("span");
188
+ text.textContent = message;
189
+ el.append(text);
190
+ const close = () => {
186
191
  el.classList.remove("in");
187
192
  setTimeout(() => el.remove(), 250);
188
- }, ms);
193
+ };
194
+ if (action) {
195
+ el.classList.add("has-action");
196
+ const btn = document.createElement("button");
197
+ btn.className = "btn btn-sm";
198
+ btn.textContent = action.label;
199
+ btn.addEventListener("click", () => {
200
+ close();
201
+ action.onClick();
202
+ });
203
+ el.append(btn);
204
+ }
205
+ box.append(el);
206
+ requestAnimationFrame(() => el.classList.add("in"));
207
+ setTimeout(close, ms);
189
208
  }
190
209
 
191
210
  export async function copyText(text, label = "Copied") {
@@ -224,3 +243,98 @@ export const storage = {
224
243
  } catch {}
225
244
  },
226
245
  };
246
+
247
+ // ------------------------------------------------------------------ context menu
248
+
249
+ let activeMenu = null;
250
+
251
+ export function closeContextMenu() {
252
+ if (!activeMenu) return;
253
+ activeMenu.cleanup();
254
+ activeMenu = null;
255
+ }
256
+
257
+ /**
258
+ * Show a floating context menu at the pointer location.
259
+ * items: Array<{ label, icon?, cls?, onClick } | "sep">
260
+ * anchorEl: where to show the menu when it was opened from the keyboard (defaults to the event target).
261
+ */
262
+ export function openContextMenu(e, items, anchorEl = null) {
263
+ if (typeof document === "undefined") return;
264
+ const list = items.filter(Boolean);
265
+ if (!list.length) return;
266
+ e.preventDefault();
267
+ closeContextMenu();
268
+
269
+ const menu = document.createElement("div");
270
+ menu.className = "ctx-menu";
271
+ menu.setAttribute("role", "menu");
272
+ const handlers = [];
273
+ menu.innerHTML = String(
274
+ html`${list.map((item) => {
275
+ if (item === "sep") return raw('<div class="ctx-sep" role="separator"></div>');
276
+ const idx = handlers.push(item.onClick) - 1;
277
+ return html`<button type="button" class="ctx-item${item.cls ? ` ${item.cls}` : ""}" role="menuitem" data-idx="${idx}">${item.icon ? raw(item.icon) : ""}<span>${item.label}</span></button>`;
278
+ })}`,
279
+ );
280
+ document.body.append(menu);
281
+
282
+ // Opened from the keyboard (Shift+F10 or the Menu key) there is no pointer position: anchor to the element.
283
+ const trigger = anchorEl || (e.target instanceof Element ? e.target : null);
284
+ const fromKeyboard = e.clientX === 0 && e.clientY === 0 && trigger;
285
+ const anchor = fromKeyboard ? trigger.getBoundingClientRect() : null;
286
+ const px = anchor ? anchor.left + Math.min(24, anchor.width / 2) : e.clientX;
287
+ const py = anchor ? anchor.bottom : e.clientY;
288
+ const rect = menu.getBoundingClientRect();
289
+ const x = Math.max(8, Math.min(px, window.innerWidth - rect.width - 8));
290
+ const y = Math.max(8, Math.min(py, window.innerHeight - rect.height - 8));
291
+ menu.style.left = `${x}px`;
292
+ menu.style.top = `${y}px`;
293
+
294
+ const onDown = (ev) => {
295
+ if (!menu.contains(ev.target)) closeContextMenu();
296
+ };
297
+ const onKey = (ev) => {
298
+ if (ev.key === "Escape") {
299
+ ev.preventDefault();
300
+ closeContextMenu();
301
+ return;
302
+ }
303
+ const btns = [...menu.querySelectorAll(".ctx-item")];
304
+ if (!btns.length) return;
305
+ if (ev.key === "ArrowDown" || ev.key === "ArrowUp") {
306
+ ev.preventDefault();
307
+ const i = btns.indexOf(document.activeElement);
308
+ const next = ev.key === "ArrowDown" ? (i + 1) % btns.length : (i - 1 + btns.length) % btns.length;
309
+ btns[next].focus();
310
+ }
311
+ };
312
+ const onScroll = () => closeContextMenu();
313
+ menu.addEventListener("click", (ev) => {
314
+ const btn = ev.target.closest("[data-idx]");
315
+ if (!btn) return;
316
+ const fn = handlers[Number(btn.dataset.idx)];
317
+ closeContextMenu();
318
+ fn?.();
319
+ });
320
+
321
+ document.addEventListener("pointerdown", onDown, true);
322
+ document.addEventListener("keydown", onKey, true);
323
+ window.addEventListener("scroll", onScroll, true);
324
+ window.addEventListener("resize", onScroll);
325
+
326
+ const returnFocus = document.activeElement;
327
+ if (fromKeyboard) menu.querySelector(".ctx-item")?.focus();
328
+
329
+ activeMenu = {
330
+ cleanup() {
331
+ const hadFocus = menu.contains(document.activeElement);
332
+ menu.remove();
333
+ if (hadFocus && returnFocus instanceof HTMLElement) returnFocus.focus({ preventScroll: true });
334
+ document.removeEventListener("pointerdown", onDown, true);
335
+ document.removeEventListener("keydown", onKey, true);
336
+ window.removeEventListener("scroll", onScroll, true);
337
+ window.removeEventListener("resize", onScroll);
338
+ },
339
+ };
340
+ }