internal/web/static/app.js
589 lines · 21387 bytes
6 symbols in this file
1// gitbay progressive enhancement: popovers, Cmd+K palette, copy buttons,
2// in-place swaps for reactions/toggles/pickers, inline diff comments, and
3// keyboard shortcuts. Every action degrades cleanly without JS.
4(() => {
5 'use strict';
6 document.documentElement.classList.add('js');
7
8 let toastTimer = 0;
9 function showToast(msg, isErr = false) {
10 let el = document.getElementById('gb-toast');
11 if (!el) {
12 el = document.createElement('div');
13 el.id = 'gb-toast';
14 el.className = 'toast';
15 el.setAttribute('role', 'status');
16 document.body.appendChild(el);
17 }
18 el.textContent = msg;
19 el.classList.toggle('toast-err', isErr);
20 el.classList.add('toast-show');
21 clearTimeout(toastTimer);
22 toastTimer = setTimeout(() => el.classList.remove('toast-show'), 2200);
23 }
24
25 const isTyping = (el) => {
26 if (!el) return false;
27 const tag = el.tagName;
28 return tag === 'INPUT' || tag === 'TEXTAREA' || tag === 'SELECT' || el.isContentEditable;
29 };
30
31 // ---- 1. Popover hygiene (close others, click outside, Escape) ----
32 const popovers = () => document.querySelectorAll('details.popover, details.railpins, details.refmenu');
33 document.addEventListener('toggle', (e) => {
34 const d = e.target;
35 if (!(d instanceof HTMLDetailsElement) || !d.open) return;
36 if (!d.matches('details.popover, details.railpins, details.refmenu')) return;
37 for (const other of popovers()) {
38 if (other !== d && other.open) other.open = false;
39 }
40 const input = d.querySelector('input[type="text"], input[type="search"]');
41 if (input) setTimeout(() => input.focus(), 0);
42 }, true);
43
44 document.addEventListener('click', (e) => {
45 for (const d of popovers()) {
46 if (d.open && !d.contains(e.target)) d.open = false;
47 }
48 });
49
50 // ---- 2. Copy buttons on clone, copyable & rendered code blocks ----
51 function initCopyButtons(root = document) {
52 for (const pre of root.querySelectorAll('.clone pre, pre.copyable, .rendered pre')) {
53 if (pre.dataset.copyWired) continue;
54 pre.dataset.copyWired = '1';
55 const code = pre.querySelector('code') || pre;
56 const wrap = document.createElement('div');
57 wrap.className = 'copywrap';
58 pre.parentNode.insertBefore(wrap, pre);
59 wrap.appendChild(pre);
60 const btn = document.createElement('button');
61 btn.type = 'button';
62 btn.className = 'copybtn';
63 btn.textContent = 'Copy';
64 btn.setAttribute('aria-label', 'Copy code');
65 btn.addEventListener('click', async () => {
66 try {
67 await navigator.clipboard.writeText(code.textContent.trim());
68 btn.textContent = 'Copied';
69 setTimeout(() => { btn.textContent = 'Copy'; }, 1400);
70 } catch {
71 btn.textContent = 'Failed';
72 setTimeout(() => { btn.textContent = 'Copy'; }, 1400);
73 }
74 });
75 wrap.appendChild(btn);
76 }
77 }
78
79 document.addEventListener('click', async (e) => {
80 const btn = e.target.closest('button[data-copy]');
81 if (!btn) return;
82 const orig = btn.textContent;
83 try {
84 await navigator.clipboard.writeText(btn.dataset.copy);
85 btn.textContent = 'Copied';
86 showToast('Copied to clipboard');
87 setTimeout(() => { btn.textContent = orig; }, 1400);
88 } catch {
89 showToast('Copy failed', true);
90 }
91 });
92 document.addEventListener('submit', async (e) => {
93 const form = e.target;
94 if (!(form instanceof HTMLFormElement) || form.method.toLowerCase() !== 'post') return;
95
96 // No-reload markup preview on any form with a Preview button
97 if (e.submitter && e.submitter.name === 'preview') {
98 e.preventDefault();
99 const btn = e.submitter;
100 const data = new FormData(form);
101 data.append('preview', btn.value || '1');
102 btn.disabled = true;
103 try {
104 const res = await fetch(form.action, {
105 method: 'POST',
106 body: new URLSearchParams(data),
107 headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
108 credentials: 'same-origin',
109 });
110 if (!res.ok) { form.submit(); return; }
111 const doc = new DOMParser().parseFromString(await res.text(), 'text/html');
112 const nextPrev = doc.querySelector('.preview');
113 if (!nextPrev) { showToast('Nothing to preview'); return; }
114 const prev = form.previousElementSibling;
115 if (prev && prev.classList.contains('preview')) prev.replaceWith(nextPrev);
116 else form.insertAdjacentElement('beforebegin', nextPrev);
117 initCopyButtons(nextPrev);
118 } catch {
119 form.submit();
120 } finally {
121 btn.disabled = false;
122 }
123 return;
124 }
125
126 let swapSel = null;
127 if (form.classList.contains('reactions')) {
128 swapSel = 'main#content';
129 } else if (form.closest('.identity')) {
130 swapSel = '.identity';
131 } else if (form.closest('.aside .popover')) {
132 swapSel = '.aside';
133 } else if (form.dataset.notifForm) {
134 swapSel = '#notif-root';
135 } else {
136 return;
137 }
138 e.preventDefault();
139 const data = new FormData(form);
140 if (e.submitter && e.submitter.name) {
141 data.append(e.submitter.name, e.submitter.value);
142 }
143 const body = new URLSearchParams(data);
144 try {
145 const res = await fetch(form.action, {
146 method: 'POST',
147 body,
148 headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
149 credentials: 'same-origin',
150 });
151 if (!res.ok) { form.submit(); return; }
152 const html = await res.text();
153 const doc = new DOMParser().parseFromString(html, 'text/html');
154 const next = doc.querySelector(swapSel);
155 const cur = document.querySelector(swapSel);
156 if (next && cur) {
157 cur.replaceWith(next);
158 initCopyButtons(next);
159 if (swapSel === '#notif-root') {
160 const nextBell = doc.querySelector('.rail a[href="/notifications"]');
161 const curBell = document.querySelector('.rail a[href="/notifications"]');
162 if (nextBell && curBell) curBell.replaceWith(nextBell);
163 showToast('Marked as read');
164 }
165 } else {
166 location.reload();
167 }
168 } catch {
169 form.submit();
170 }
171 });
172
173 // ---- 4. Inline diff-line comment composer without page reload ----
174 document.addEventListener('click', (e) => {
175 const a = e.target.closest('a.cmt');
176 if (!a) return;
177 const url = new URL(a.href, location.origin);
178 const cpath = url.searchParams.get('cpath');
179 const cline = url.searchParams.get('cline');
180 const cside = url.searchParams.get('cside') || 'new';
181 if (!cpath || !cline) return;
182 const row = a.closest('tr');
183 if (!row) return;
184 e.preventDefault();
185
186 const existing = document.getElementById('inline-compose-row');
187 if (existing) existing.remove();
188
189 const base = url.pathname;
190 const cols = row.closest('table')?.classList.contains('split') ? 4 : 3;
191 const tr = document.createElement('tr');
192 tr.id = 'inline-compose-row';
193 tr.className = 'threadrow';
194 const td = document.createElement('td');
195 td.colSpan = cols;
196
197 const form = document.createElement('form');
198 form.method = 'post';
199 form.action = base + '/diff-comment';
200 form.className = 'thread composing';
201
202 const hidden = (name, val) => {
203 const inp = document.createElement('input');
204 inp.type = 'hidden';
205 inp.name = name;
206 inp.value = val;
207 return inp;
208 };
209 form.append(hidden('path', cpath), hidden('line', cline), hidden('side', cside));
210
211 if (cside !== 'old') {
212 const pRange = document.createElement('p');
213 pRange.className = 'hint';
214 pRange.textContent = `Line ${cline} — use \`\`\`suggestion to propose replacement lines`;
215 form.appendChild(pRange);
216 }
217
218 const pArea = document.createElement('p');
219 const ta = document.createElement('textarea');
220 ta.name = 'body';
221 ta.rows = 3;
222 ta.placeholder = `Comment on ${cpath}:${cline}`;
223 ta.required = true;
224 pArea.appendChild(ta);
225
226 const pAct = document.createElement('p');
227 pAct.className = 'btngroup';
228 const bNow = document.createElement('button');
229 bNow.type = 'submit';
230 bNow.textContent = 'Comment';
231 const bPend = document.createElement('button');
232 bPend.type = 'submit';
233 bPend.name = 'pending';
234 bPend.value = 'on';
235 bPend.className = 'btn';
236 bPend.textContent = 'Add to review';
237 const bCancel = document.createElement('button');
238 bCancel.type = 'button';
239 bCancel.className = 'linklike';
240 bCancel.textContent = 'Cancel';
241 bCancel.addEventListener('click', () => tr.remove());
242 pAct.append(bNow, bPend, bCancel);
243
244 form.append(pArea, pAct);
245 td.appendChild(form);
246 tr.appendChild(td);
247 row.insertAdjacentElement('afterend', tr);
248 ta.focus();
249 });
250
251 // ---- 5. Cmd+K Command Palette ----
252 function collectCommands() {
253 const items = [];
254 const seen = new Set();
255 const add = (group, label, href) => {
256 if (!href || seen.has(href)) return;
257 seen.add(href);
258 items.push({ group, label, href });
259 };
260 for (const a of document.querySelectorAll('nav.tabs a')) {
261 add('Repository', a.textContent.trim().replace(/\s+/g, ' '), a.getAttribute('href'));
262 }
263 for (const a of document.querySelectorAll('.railpins .raildrop a')) {
264 add('Pinned', a.textContent.trim(), a.getAttribute('href'));
265 }
266 add('Navigate', 'Dashboard', '/');
267 add('Navigate', 'Explore repositories', '/explore');
268 add('Navigate', 'Global search', '/search');
269 add('Navigate', 'Notifications', '/notifications');
270 add('Navigate', 'New repository', '/new');
271 add('Navigate', 'Account settings', '/settings');
272 return items;
273 }
274
275 function openPalette() {
276 const dlg = document.getElementById('cmdk');
277 if (!(dlg instanceof HTMLDialogElement)) return;
278 const input = dlg.querySelector('input');
279 const list = dlg.querySelector('ul');
280 const all = collectCommands();
281 let active = 0;
282
283 const render = () => {
284 const raw = input.value.trim();
285 const q = raw.toLowerCase();
286 const filtered = q ? all.filter((it) => (it.label + ' ' + it.group).toLowerCase().includes(q)) : all.slice();
287 if (raw) {
288 filtered.push({ group: 'Search', label: `Search “${raw}”…`, href: '/search?q=' + encodeURIComponent(raw) });
289 }
290 active = Math.min(active, Math.max(0, filtered.length - 1));
291 list.textContent = '';
292 if (filtered.length === 0) {
293 const li = document.createElement('li');
294 li.className = 'cmdk-empty';
295 li.textContent = 'No matching destinations';
296 list.appendChild(li);
297 return;
298 }
299 filtered.forEach((it, idx) => {
300 const li = document.createElement('li');
301 const a = document.createElement('a');
302 a.href = it.href;
303 if (idx === active) a.setAttribute('aria-selected', 'true');
304 const g = document.createElement('span');
305 g.className = 'cmdk-grp';
306 g.textContent = it.group;
307 const t = document.createElement('span');
308 t.textContent = it.label;
309 a.append(g, t);
310 li.appendChild(a);
311 list.appendChild(li);
312 });
313 };
314
315 input.value = '';
316 render();
317 if (!dlg.open) dlg.showModal();
318 input.focus();
319
320 input.oninput = () => { active = 0; render(); };
321 input.onkeydown = (ev) => {
322 const links = list.querySelectorAll('a');
323 if (ev.key === 'ArrowDown') {
324 ev.preventDefault();
325 if (links.length) { active = (active + 1) % links.length; render(); }
326 } else if (ev.key === 'ArrowUp') {
327 ev.preventDefault();
328 if (links.length) { active = (active - 1 + links.length) % links.length; render(); }
329 } else if (ev.key === 'Enter') {
330 const sel = links[active];
331 if (sel) { ev.preventDefault(); location.href = sel.href; }
332 }
333 };
334 }
335
336 document.addEventListener('click', (e) => {
337 if (e.target.closest('.cmdk-trigger')) {
338 e.preventDefault();
339 openPalette();
340 return;
341 }
342 const dlg = document.getElementById('cmdk');
343 if (dlg && e.target === dlg) dlg.close();
344 });
345
346 // ---- 6. Keyboard shortcuts ----
347 let chord = '';
348 let chordTimer = 0;
349 document.addEventListener('keydown', (e) => {
350 if (e.key === 'Escape') {
351 for (const d of popovers()) if (d.open) d.open = false;
352 const inline = document.getElementById('inline-compose-row');
353 if (inline) inline.remove();
354 return;
355 }
356 if ((e.metaKey || e.ctrlKey) && e.key === 'Enter' && e.target instanceof HTMLTextAreaElement && e.target.form) {
357 e.preventDefault();
358 const btn = e.target.form.querySelector('button[type="submit"]:not([name="preview"]), button:not([type]):not([name="preview"])');
359 if (btn) e.target.form.requestSubmit(btn);
360 else e.target.form.requestSubmit();
361 return;
362 }
363 if ((e.metaKey || e.ctrlKey) && e.key.toLowerCase() === 'k') {
364 e.preventDefault();
365 openPalette();
366 return;
367 }
368 if (isTyping(e.target) || e.metaKey || e.ctrlKey || e.altKey) return;
369
370 if (e.key === '/') {
371 const search = document.querySelector('main input[type="search"], .railsearch input[type="search"]');
372 if (search) { e.preventDefault(); search.focus(); return; }
373 e.preventDefault();
374 openPalette();
375 return;
376 }
377
378 if (chord === 'g') {
379 clearTimeout(chordTimer);
380 chord = '';
381 const tabLink = (match) => {
382 for (const a of document.querySelectorAll('nav.tabs a')) {
383 if (a.textContent.trim().toLowerCase().startsWith(match)) return a.href;
384 }
385 return null;
386 };
387 const dest = {
388 d: '/',
389 e: '/explore',
390 n: '/notifications',
391 c: tabLink('code'),
392 i: tabLink('issues'),
393 m: tabLink('merge'),
394 b: tabLink('builds'),
395 r: tabLink('releases'),
396 w: tabLink('wiki'),
397 }[e.key.toLowerCase()];
398 if (dest) { e.preventDefault(); location.href = dest; }
399 return;
400 }
401 if (e.key === 'g') {
402 chord = 'g';
403 chordTimer = setTimeout(() => { chord = ''; }, 900);
404 }
405 });
406
407 // ---- 7. Auto-save checkboxes & selects on /settings ----
408 document.addEventListener('change', async (e) => {
409 const form = e.target.closest('form[data-autosave]');
410 if (!(form instanceof HTMLFormElement)) return;
411 if (e.target.matches('[data-live-theme]')) {
412 const val = e.target.value;
413 if (val === 'system') delete document.documentElement.dataset.theme;
414 else document.documentElement.dataset.theme = val;
415 }
416 const body = new URLSearchParams(new FormData(form));
417 try {
418 const res = await fetch(form.action, {
419 method: 'POST',
420 body,
421 headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
422 credentials: 'same-origin',
423 });
424 if (!res.ok) { showToast('Save failed', true); return; }
425 showToast('Saved');
426 } catch {
427 showToast('Save failed', true);
428 }
429 });
430
431 // ---- 8. Live client-side table, list & link filters ----
432 document.addEventListener('input', (e) => {
433 const inp = e.target.closest('input[data-filter-table], input[data-filter-list], input[data-filter-links]');
434 if (!inp) return;
435 const q = inp.value.trim().toLowerCase();
436 if (inp.dataset.filterLinks) {
437 const box = inp.closest('.' + inp.dataset.filterLinks);
438 if (!box) return;
439 for (const a of box.querySelectorAll('a:not(.allrefs)')) {
440 a.hidden = q !== '' && !a.textContent.toLowerCase().includes(q);
441 }
442 return;
443 }
444 if (inp.dataset.filterTable) {
445 const table = document.getElementById(inp.dataset.filterTable);
446 if (!table) return;
447 for (const row of table.querySelectorAll('tbody tr')) {
448 row.hidden = q !== '' && !row.textContent.toLowerCase().includes(q);
449 }
450 return;
451 }
452 const list = document.getElementById(inp.dataset.filterList);
453 if (!list) return;
454 const ul = list.tagName === 'UL' ? list : list.querySelector('ul');
455 if (!ul) return;
456 for (const item of ul.querySelectorAll(':scope > li')) {
457 if (item.classList.contains('empty')) continue;
458 item.hidden = q !== '' && !item.textContent.toLowerCase().includes(q);
459 }
460 });
461
462 // ---- 9. In-place Refresh (/admin, /, /builds, /notifications) ----
463 document.addEventListener('click', async (e) => {
464 const btn = e.target.closest('button[data-refresh]');
465 if (!btn) return;
466 const url = btn.dataset.refresh === 'self' ? location.href : btn.dataset.refresh;
467 const targetId = btn.dataset.refreshTarget || 'admin-queues';
468 btn.disabled = true;
469 try {
470 const res = await fetch(url, { credentials: 'same-origin' });
471 if (!res.ok) { showToast('Refresh failed', true); return; }
472 const html = await res.text();
473 const doc = new DOMParser().parseFromString(html, 'text/html');
474 const next = doc.getElementById(targetId);
475 const cur = document.getElementById(targetId);
476 if (next && cur) {
477 cur.replaceWith(next);
478 initCopyButtons(next);
479 initScrollSpy();
480 showToast('Refreshed');
481 }
482 } catch {
483 showToast('Refresh failed', true);
484 } finally {
485 btn.disabled = false;
486 }
487 });
488
489 // ---- 9b. Smooth in-place tab switching (profile tabs) ----
490 document.addEventListener('click', async (e) => {
491 if (e.metaKey || e.ctrlKey || e.shiftKey || e.altKey || e.button !== 0) return;
492 const a = e.target.closest('nav[data-tab-swap] a');
493 if (!a) return;
494 const targetId = a.closest('nav[data-tab-swap]').dataset.tabSwap;
495 const cur = document.getElementById(targetId);
496 if (!cur) return;
497 e.preventDefault();
498 try {
499 const res = await fetch(a.href, { credentials: 'same-origin' });
500 if (!res.ok) { location.href = a.href; return; }
501 const html = await res.text();
502 const doc = new DOMParser().parseFromString(html, 'text/html');
503 const next = doc.getElementById(targetId);
504 if (!next) { location.href = a.href; return; }
505 cur.replaceWith(next);
506 history.pushState({ tabSwap: targetId }, '', a.href);
507 initCopyButtons(next);
508 } catch {
509 location.href = a.href;
510 }
511 });
512 window.addEventListener('popstate', (e) => {
513 if (e.state && e.state.tabSwap) location.reload();
514 });
515
516 // ---- 10. Scroll-spy on sticky section navs ----
517 function initScrollSpy() {
518 const nav = document.querySelector('nav[data-scrollspy]');
519 if (!nav || !('IntersectionObserver' in window)) return;
520 const links = Array.from(nav.querySelectorAll('a[href^="#"]'));
521 const byId = new Map();
522 for (const a of links) {
523 const id = a.getAttribute('href').slice(1);
524 if (id) byId.set(id, a);
525 }
526 const io = new IntersectionObserver((entries) => {
527 for (const ent of entries) {
528 if (!ent.isIntersecting) continue;
529 for (const a of links) a.removeAttribute('aria-current');
530 const hit = byId.get(ent.target.id);
531 if (hit) hit.setAttribute('aria-current', 'location');
532 }
533 }, { rootMargin: '-15% 0px -70% 0px' });
534 for (const id of byId.keys()) {
535 const sec = document.getElementById(id);
536 if (sec) io.observe(sec);
537 }
538 }
539
540 // ---- 11. Client-side panel tabs (/new) & import repo-name inference ----
541 function initPanelTabs() {
542 const nav = document.querySelector('nav[data-panel-tabs]');
543 if (!nav) return;
544 const container = document.getElementById(nav.dataset.panelTabs);
545 if (!container) return;
546 const links = Array.from(nav.querySelectorAll('a[data-panel]'));
547 const panels = Array.from(container.querySelectorAll('[data-panel-id]'));
548 const show = (id) => {
549 const valid = panels.some((p) => p.dataset.panelId === id);
550 const target = valid ? id : panels[0]?.dataset.panelId;
551 for (const p of panels) p.hidden = p.dataset.panelId !== target;
552 for (const a of links) {
553 if (a.dataset.panel === target) a.setAttribute('aria-current', 'page');
554 else a.removeAttribute('aria-current');
555 }
556 };
557 const initial = location.hash.replace(/^#/, '') || (document.querySelector('#import input[name="from"]')?.value ? 'import' : 'create');
558 show(initial);
559 for (const a of links) {
560 a.addEventListener('click', (e) => {
561 e.preventDefault();
562 show(a.dataset.panel);
563 history.replaceState(null, '', '#' + a.dataset.panel);
564 });
565 }
566 }
567
568 document.addEventListener('input', (e) => {
569 const src = e.target.closest('input[data-infer-name]');
570 if (!src) return;
571 const dst = document.getElementById(src.dataset.inferName);
572 if (!dst || dst.dataset.userEdited === '1') return;
573 const raw = src.value.trim().replace(/\/+$/, '').replace(/\.git$/i, '');
574 const seg = raw.split('/').pop() || '';
575 const clean = seg.toLowerCase().replace(/[^a-z0-9._-]+/g, '-').replace(/^[^a-z0-9]+/, '').slice(0, 63);
576 if (clean) dst.value = clean;
577 });
578 document.addEventListener('input', (e) => {
579 if (e.target.id === 'imp-name') e.target.dataset.userEdited = e.target.value ? '1' : '';
580 });
581
582 if (document.readyState === 'loading') {
583 document.addEventListener('DOMContentLoaded', () => { initCopyButtons(); initScrollSpy(); initPanelTabs(); });
584 } else {
585 initCopyButtons();
586 initScrollSpy();
587 initPanelTabs();
588 }
589})();