internal/web/static/app.js

6521399c1c78577eb00f1bcf8947c0900b9cb62e
gitbay/internal/web/static/app.js

1238 lines · 47595 bytes

   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.railcreate, details.railusermenu, 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.railcreate, details.railusermenu, 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 rawText = code.textContent.trim();
  57      const wrap = document.createElement('div');
  58      wrap.className = rawText.includes('\n') ? 'copywrap' : 'copywrap oneline';
  59      pre.parentNode.insertBefore(wrap, pre);
  60      wrap.appendChild(pre);
  61      const btn = document.createElement('button');
  62      btn.type = 'button';
  63      btn.className = 'copybtn';
  64      btn.textContent = 'Copy';
  65      btn.setAttribute('aria-label', 'Copy code');
  66      btn.addEventListener('click', async () => {
  67        try {
  68          await navigator.clipboard.writeText(code.textContent.trim());
  69          btn.textContent = 'Copied';
  70          setTimeout(() => { btn.textContent = 'Copy'; }, 1400);
  71        } catch {
  72          btn.textContent = 'Failed';
  73          setTimeout(() => { btn.textContent = 'Copy'; }, 1400);
  74        }
  75      });
  76      wrap.appendChild(btn);
  77    }
  78  }
  79
  80  document.addEventListener('click', async (e) => {
  81    const urlBtn = e.target.closest('button[data-copy-url]');
  82    if (urlBtn) {
  83      const orig = urlBtn.textContent;
  84      try {
  85        const res = await fetch(urlBtn.dataset.copyUrl, { credentials: 'same-origin' });
  86        if (!res.ok) throw new Error('fetch failed');
  87        await navigator.clipboard.writeText(await res.text());
  88        urlBtn.textContent = 'copied';
  89        showToast('File copied to clipboard');
  90        setTimeout(() => { urlBtn.textContent = orig; }, 1400);
  91      } catch {
  92        showToast('Copy failed', true);
  93      }
  94      return;
  95    }
  96    const quoteBtn = e.target.closest('button[data-quote-from]');
  97    if (quoteBtn) {
  98      const art = document.getElementById(quoteBtn.dataset.quoteFrom);
  99      const ta = document.getElementById('main-comment-box') || document.querySelector('form.commentform textarea[name="body"]');
 100      if (art && ta) {
 101        const rendered = art.querySelector('.rendered');
 102        const text = (rendered ? rendered.innerText : '').trim();
 103        if (text) {
 104          const quoted = text.split('\n').map((l) => '> ' + l).join('\n') + '\n\n';
 105          ta.value = (ta.value ? ta.value.replace(/\s*$/, '\n\n') : '') + quoted;
 106          ta.focus();
 107          ta.setSelectionRange(ta.value.length, ta.value.length);
 108          ta.scrollIntoView({ behavior: 'smooth', block: 'center' });
 109        }
 110      }
 111      return;
 112    }
 113    const btn = e.target.closest('button[data-copy]');
 114    if (!btn) return;
 115    const orig = btn.textContent;
 116    try {
 117      await navigator.clipboard.writeText(btn.dataset.copy);
 118      btn.textContent = 'Copied';
 119      showToast('Copied to clipboard');
 120      setTimeout(() => { btn.textContent = orig; }, 1400);
 121    } catch {
 122      showToast('Copy failed', true);
 123    }
 124  });
 125  document.addEventListener('submit', async (e) => {
 126    const form = e.target;
 127    if (!(form instanceof HTMLFormElement) || form.method.toLowerCase() !== 'post') return;
 128
 129    // No-reload markup preview on any form with a Preview button
 130    if (e.submitter && e.submitter.name === 'preview') {
 131      e.preventDefault();
 132      const btn = e.submitter;
 133      const data = new FormData(form);
 134      data.append('preview', btn.value || '1');
 135      btn.disabled = true;
 136      try {
 137        const res = await fetch(form.action, {
 138          method: 'POST',
 139          body: new URLSearchParams(data),
 140          headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
 141          credentials: 'same-origin',
 142        });
 143        if (!res.ok) { form.submit(); return; }
 144        const doc = new DOMParser().parseFromString(await res.text(), 'text/html');
 145        const nextPrev = doc.querySelector('.preview');
 146        if (!nextPrev) { showToast('Nothing to preview'); return; }
 147        const prev = form.previousElementSibling;
 148        if (prev && prev.classList.contains('preview')) prev.replaceWith(nextPrev);
 149        else form.insertAdjacentElement('beforebegin', nextPrev);
 150        initCopyButtons(nextPrev);
 151      } catch {
 152        form.submit();
 153      } finally {
 154        btn.disabled = false;
 155      }
 156      return;
 157    }
 158
 159    let swapSel = null;
 160    let keepPopoverIdx = -1;
 161    let foldId = '';
 162    if (form.classList.contains('reactions') && form.dataset.reactSlot !== undefined) {
 163      swapSel = `form.reactions[data-react-slot="${CSS.escape(form.dataset.reactSlot)}"]`;
 164    } else if (form.closest('.identity')) {
 165      swapSel = '.identity';
 166    } else if (form.closest('.aside .popover')) {
 167      swapSel = '.aside';
 168      const openPop = form.closest('.aside .popover');
 169      const allPops = Array.from(document.querySelectorAll('.aside .popover'));
 170      keepPopoverIdx = allPops.indexOf(openPop);
 171    } else if (form.dataset.notifForm) {
 172      swapSel = '#notif-root';
 173    } else if (form.closest('details.difffold') && (form.classList.contains('composing') || form.closest('details.threadreply') || form.classList.contains('threadact'))) {
 174      const fold = form.closest('details.difffold');
 175      if (fold && fold.id) {
 176        foldId = fold.id;
 177        swapSel = '#' + CSS.escape(fold.id);
 178      }
 179    }
 180    if (!swapSel) return;
 181    e.preventDefault();
 182    const data = new FormData(form);
 183    if (e.submitter && e.submitter.name) {
 184      data.append(e.submitter.name, e.submitter.value);
 185    }
 186    const body = new URLSearchParams(data);
 187    try {
 188      const res = await fetch(form.action, {
 189        method: 'POST',
 190        body,
 191        headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
 192        credentials: 'same-origin',
 193      });
 194      if (!res.ok) { form.submit(); return; }
 195      const html = await res.text();
 196      const doc = new DOMParser().parseFromString(html, 'text/html');
 197      const errBanner = doc.querySelector('main .error');
 198      if (errBanner) {
 199        showToast(errBanner.textContent.trim(), true);
 200        return;
 201      }
 202      const next = doc.querySelector(swapSel);
 203      const cur = document.querySelector(swapSel);
 204      if (next && cur) {
 205        if (foldId) next.open = true;
 206        cur.replaceWith(next);
 207        initCopyButtons(next);
 208        if (swapSel === '.identity') {
 209          const nextPins = doc.querySelector('.railpins');
 210          const curPins = document.querySelector('.railpins');
 211          if (nextPins && curPins) curPins.replaceWith(nextPins);
 212        } else if (swapSel === '.aside' && keepPopoverIdx >= 0) {
 213          const newPops = next.querySelectorAll('.popover');
 214          if (newPops[keepPopoverIdx]) newPops[keepPopoverIdx].open = true;
 215        } else if (foldId) {
 216          const nextAside = doc.querySelector('.aside');
 217          const curAside = document.querySelector('.aside');
 218          if (nextAside && curAside) curAside.replaceWith(nextAside);
 219        } else if (swapSel === '#notif-root') {
 220          const nextBell = doc.querySelector('.rail a[href="/notifications"]');
 221          const curBell = document.querySelector('.rail a[href="/notifications"]');
 222          if (nextBell && curBell) curBell.replaceWith(nextBell);
 223          showToast('Marked as read');
 224        }
 225      } else {
 226        location.reload();
 227      }
 228    } catch {
 229      form.submit();
 230    }
 231  });
 232
 233  // ---- 4. Inline diff-line comment composer without page reload ----
 234  document.addEventListener('click', (e) => {
 235    const a = e.target.closest('a.cmt');
 236    if (!a) return;
 237    const url = new URL(a.href, location.origin);
 238    const cpath = url.searchParams.get('cpath');
 239    const cline = url.searchParams.get('cline');
 240    const cside = url.searchParams.get('cside') || 'new';
 241    if (!cpath || !cline) return;
 242    const row = a.closest('tr');
 243    if (!row) return;
 244    e.preventDefault();
 245
 246    const existing = document.getElementById('inline-compose-row');
 247    if (existing) existing.remove();
 248
 249    const base = url.pathname;
 250    const isSplit = row.closest('table')?.classList.contains('split');
 251    const cols = isSplit ? 4 : 3;
 252    const tr = document.createElement('tr');
 253    tr.id = 'inline-compose-row';
 254    tr.className = 'threadrow';
 255    const td = document.createElement('td');
 256    td.colSpan = cols;
 257
 258    const form = document.createElement('form');
 259    form.method = 'post';
 260    form.action = base + '/diff-comment';
 261    form.className = 'thread composing';
 262
 263    const hidden = (name, val) => {
 264      const inp = document.createElement('input');
 265      inp.type = 'hidden';
 266      inp.name = name;
 267      inp.value = val;
 268      return inp;
 269    };
 270    form.append(hidden('path', cpath), hidden('line', cline), hidden('side', cside));
 271
 272    const pArea = document.createElement('p');
 273    const ta = document.createElement('textarea');
 274    ta.name = 'body';
 275    ta.rows = 4;
 276    ta.placeholder = `Comment on ${cpath}:${cline}`;
 277    ta.required = true;
 278    pArea.appendChild(ta);
 279
 280    let startInp = null;
 281    if (cside !== 'old') {
 282      const pRange = document.createElement('p');
 283      pRange.className = 'hint';
 284      const lbl = document.createElement('label');
 285      lbl.style.display = 'inline';
 286      lbl.textContent = 'From line ';
 287      startInp = document.createElement('input');
 288      startInp.type = 'number';
 289      startInp.name = 'start_line';
 290      startInp.min = '1';
 291      startInp.max = cline;
 292      startInp.placeholder = cline;
 293      startInp.style.width = '5rem';
 294      startInp.style.height = '26px';
 295      lbl.appendChild(startInp);
 296      const bSug = document.createElement('button');
 297      bSug.type = 'button';
 298      bSug.className = 'linklike';
 299      bSug.style.marginLeft = '8px';
 300      bSug.textContent = 'Insert suggestion';
 301      bSug.addEventListener('click', () => {
 302        const srcCell = isSplit ? row.querySelectorAll('td.src')[1] : row.querySelector('td.src');
 303        const origLine = srcCell ? srcCell.textContent : '';
 304        const block = '```suggestion\n' + origLine + '\n```\n';
 305        const pos = ta.selectionStart ?? ta.value.length;
 306        ta.value = ta.value.slice(0, pos) + block + ta.value.slice(pos);
 307        ta.focus();
 308      });
 309      pRange.append(lbl, document.createTextNode(` to ${cline} · `), bSug);
 310      form.appendChild(pRange);
 311    }
 312
 313    const pAct = document.createElement('p');
 314    pAct.className = 'btngroup';
 315    const bNow = document.createElement('button');
 316    bNow.type = 'submit';
 317    bNow.className = 'btn';
 318    bNow.textContent = 'Comment';
 319    const bPend = document.createElement('button');
 320    bPend.type = 'submit';
 321    bPend.name = 'pending';
 322    bPend.value = 'on';
 323    bPend.className = 'btn';
 324    bPend.textContent = 'Add to review';
 325    const bCancel = document.createElement('button');
 326    bCancel.type = 'button';
 327    bCancel.className = 'linklike';
 328    bCancel.textContent = 'Cancel';
 329    bCancel.addEventListener('click', () => tr.remove());
 330    pAct.append(bNow, bPend, bCancel);
 331
 332    form.append(pArea, pAct);
 333    td.appendChild(form);
 334    tr.appendChild(td);
 335    row.insertAdjacentElement('afterend', tr);
 336    ta.focus();
 337  });
 338
 339  // ---- 5. Cmd+K Command Palette (with live repo/file/issue/MR search) ----
 340  function currentRepoContext() {
 341    const head = document.querySelector('.repohead [data-repo], .repohead[data-repo]');
 342    if (!head) return { repo: '', ref: '' };
 343    return { repo: head.dataset.repo || '', ref: head.dataset.ref || '' };
 344  }
 345
 346  function collectCommands() {
 347    const items = [];
 348    const seen = new Set();
 349    const add = (group, label, href) => {
 350      if (!href || seen.has(href)) return;
 351      seen.add(href);
 352      items.push({ group, label, href });
 353    };
 354    for (const a of document.querySelectorAll('nav.tabs a')) {
 355      add('Repository', a.textContent.trim().replace(/\s+/g, ' '), a.getAttribute('href'));
 356    }
 357    for (const a of document.querySelectorAll('.railpins .raildrop a')) {
 358      add('Pinned', a.textContent.trim(), a.getAttribute('href'));
 359    }
 360    for (const a of document.querySelectorAll('.railusermenu .raildrop a')) {
 361      const txt = a.textContent.trim();
 362      if (txt.includes('queries') || txt.includes('snippets') || txt.includes('Bookmarks')) {
 363        add('Account', txt, a.getAttribute('href'));
 364      }
 365    }
 366    add('Navigate', 'Dashboard', '/');
 367    add('Navigate', 'Explore repositories', '/explore');
 368    add('Navigate', 'Global search', '/search');
 369    add('Navigate', 'Notifications', '/notifications');
 370    add('Navigate', 'New repository', '/new');
 371    add('Navigate', 'Account settings', '/settings');
 372    return items;
 373  }
 374
 375  let paletteFetchTimer = 0;
 376  function openPalette(filesOnly = false) {
 377    const dlg = document.getElementById('cmdk');
 378    if (!(dlg instanceof HTMLDialogElement)) return;
 379    const input = dlg.querySelector('input');
 380    const list = dlg.querySelector('ul');
 381    const ctx = currentRepoContext();
 382    const localItems = filesOnly ? [] : collectCommands();
 383    let remoteItems = [];
 384    let active = 0;
 385
 386    const render = () => {
 387      const raw = input.value.trim();
 388      const q = raw.toLowerCase();
 389      const merged = [];
 390      const seen = new Set();
 391      for (const it of [...remoteItems, ...localItems]) {
 392        if (!it.href || seen.has(it.href)) continue;
 393        if (q && !(it.label + ' ' + it.group).toLowerCase().includes(q)) continue;
 394        seen.add(it.href);
 395        merged.push(it);
 396      }
 397      if (raw) {
 398        if (ctx.repo) {
 399          merged.push({ group: 'Code', label: `Search "${raw}" in ${ctx.repo}…`, href: `/${ctx.repo}/search?q=` + encodeURIComponent(raw) });
 400        }
 401        merged.push({ group: 'Search', label: `Search "${raw}" across site…`, href: '/search?q=' + encodeURIComponent(raw) });
 402      }
 403      active = Math.min(active, Math.max(0, merged.length - 1));
 404      list.textContent = '';
 405      if (merged.length === 0) {
 406        const li = document.createElement('li');
 407        li.className = 'cmdk-empty';
 408        li.textContent = filesOnly ? 'Type to jump to any file in this repository…' : 'No matching destinations';
 409        list.appendChild(li);
 410        return;
 411      }
 412      merged.slice(0, 50).forEach((it, idx) => {
 413        const li = document.createElement('li');
 414        const a = document.createElement('a');
 415        a.href = it.href;
 416        if (idx === active) a.setAttribute('aria-selected', 'true');
 417        const g = document.createElement('span');
 418        g.className = 'cmdk-grp';
 419        g.textContent = it.group;
 420        const t = document.createElement('span');
 421        t.textContent = it.label;
 422        a.append(g, t);
 423        li.appendChild(a);
 424        list.appendChild(li);
 425      });
 426    };
 427
 428    const loadRemote = (q) => {
 429      const params = new URLSearchParams({ format: 'palette', q });
 430      if (ctx.repo) params.set('repo', ctx.repo);
 431      if (ctx.ref) params.set('ref', ctx.ref);
 432      fetch('/search?' + params.toString(), { credentials: 'same-origin' })
 433        .then((r) => (r.ok ? r.json() : null))
 434        .then((data) => {
 435          if (data && Array.isArray(data.items)) {
 436            remoteItems = filesOnly ? data.items.filter((x) => x.group === 'File') : data.items;
 437            render();
 438          }
 439        })
 440        .catch(() => {});
 441    };
 442
 443    input.placeholder = filesOnly && ctx.repo ? `Find file in ${ctx.repo}…` : 'Jump to repository, file, issue, MR, or page…';
 444    input.value = '';
 445    render();
 446    loadRemote('');
 447    if (!dlg.open) dlg.showModal();
 448    input.focus();
 449
 450    input.oninput = () => {
 451      active = 0;
 452      render();
 453      clearTimeout(paletteFetchTimer);
 454      paletteFetchTimer = setTimeout(() => loadRemote(input.value.trim()), 110);
 455    };
 456    input.onkeydown = (ev) => {
 457      const links = list.querySelectorAll('a');
 458      if (ev.key === 'ArrowDown') {
 459        ev.preventDefault();
 460        if (links.length) { active = (active + 1) % links.length; render(); }
 461      } else if (ev.key === 'ArrowUp') {
 462        ev.preventDefault();
 463        if (links.length) { active = (active - 1 + links.length) % links.length; render(); }
 464      } else if (ev.key === 'Enter') {
 465        const sel = links[active];
 466        if (sel) { ev.preventDefault(); location.href = sel.href; }
 467      }
 468    };
 469  }
 470
 471  function openShortcutsHelp() {
 472    const dlg = document.getElementById('kbhelp');
 473    if (dlg instanceof HTMLDialogElement && !dlg.open) dlg.showModal();
 474  }
 475
 476  document.addEventListener('click', (e) => {
 477    if (e.target.closest('.cmdk-trigger')) {
 478      e.preventDefault();
 479      openPalette(false);
 480      return;
 481    }
 482    if (e.target.closest('.kbhelp-trigger')) {
 483      e.preventDefault();
 484      openShortcutsHelp();
 485      return;
 486    }
 487    if (e.target.closest('.kbhelp-close')) {
 488      document.getElementById('kbhelp')?.close();
 489      return;
 490    }
 491    for (const id of ['cmdk', 'kbhelp']) {
 492      const dlg = document.getElementById(id);
 493      if (dlg && e.target === dlg) dlg.close();
 494    }
 495  });
 496
 497  // ---- 6. Keyboard shortcuts ----
 498  let chord = '';
 499  let chordTimer = 0;
 500  document.addEventListener('keydown', (e) => {
 501    if (e.key === 'Escape') {
 502      for (const d of popovers()) if (d.open) d.open = false;
 503      const inline = document.getElementById('inline-compose-row');
 504      if (inline) inline.remove();
 505      return;
 506    }
 507    if ((e.metaKey || e.ctrlKey) && e.key === 'Enter' && e.target instanceof HTMLTextAreaElement && e.target.form) {
 508      e.preventDefault();
 509      const btn = e.target.form.querySelector('button[type="submit"]:not([name="preview"]), button:not([type]):not([name="preview"])');
 510      if (btn) e.target.form.requestSubmit(btn);
 511      else e.target.form.requestSubmit();
 512      return;
 513    }
 514    if ((e.metaKey || e.ctrlKey) && e.key.toLowerCase() === 'k') {
 515      e.preventDefault();
 516      openPalette();
 517      return;
 518    }
 519    if (isTyping(e.target) || e.metaKey || e.ctrlKey || e.altKey) return;
 520
 521    if (e.key === '?') {
 522      e.preventDefault();
 523      openShortcutsHelp();
 524      return;
 525    }
 526    if (e.key === 't' && currentRepoContext().repo) {
 527      e.preventDefault();
 528      openPalette(true);
 529      return;
 530    }
 531    if (e.key === 'y') {
 532      const blobMain = document.querySelector('.blobmain[data-permalink]');
 533      if (blobMain && blobMain.dataset.permalink) {
 534        e.preventDefault();
 535        const nextUrl = blobMain.dataset.permalink + location.search + location.hash;
 536        history.replaceState(null, '', nextUrl);
 537        navigator.clipboard?.writeText(location.origin + nextUrl).catch(() => {});
 538        showToast('Immutable permalink copied');
 539        return;
 540      }
 541    }
 542    if (e.key === '/') {
 543      const search = document.querySelector('main input[type="search"], .railsearch input[type="search"]');
 544      if (search) { e.preventDefault(); search.focus(); return; }
 545      e.preventDefault();
 546      openPalette();
 547      return;
 548    }
 549
 550    if (chord === 'g') {
 551      clearTimeout(chordTimer);
 552      chord = '';
 553      const tabLink = (match) => {
 554        for (const a of document.querySelectorAll('nav.tabs a')) {
 555          if (a.textContent.trim().toLowerCase().startsWith(match)) return a.href;
 556        }
 557        return null;
 558      };
 559      const dest = {
 560        d: '/',
 561        e: '/explore',
 562        n: '/notifications',
 563        c: tabLink('code'),
 564        i: tabLink('issues'),
 565        m: tabLink('merge'),
 566        b: tabLink('builds'),
 567        r: tabLink('releases'),
 568        w: tabLink('wiki'),
 569      }[e.key.toLowerCase()];
 570      if (dest) { e.preventDefault(); location.href = dest; }
 571      return;
 572    }
 573    if (e.key === 'g') {
 574      chord = 'g';
 575      chordTimer = setTimeout(() => { chord = ''; }, 900);
 576    }
 577  });
 578
 579  // ---- 7. Auto-save checkboxes & selects on /settings ----
 580  document.addEventListener('change', async (e) => {
 581    const form = e.target.closest('form[data-autosave]');
 582    if (!(form instanceof HTMLFormElement)) return;
 583    const prevTheme = document.documentElement.dataset.theme || 'system';
 584    if (e.target.matches('[data-live-theme]')) {
 585      const val = e.target.value;
 586      if (val === 'system') delete document.documentElement.dataset.theme;
 587      else document.documentElement.dataset.theme = val;
 588    }
 589    const body = new URLSearchParams(new FormData(form));
 590    try {
 591      const res = await fetch(form.action, {
 592        method: 'POST',
 593        body,
 594        headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
 595        credentials: 'same-origin',
 596      });
 597      if (!res.ok) { showToast('Save failed', true); return; }
 598      const doc = new DOMParser().parseFromString(await res.text(), 'text/html');
 599      const errEl = doc.querySelector('main .error');
 600      if (errEl) {
 601        if (e.target.matches('[data-live-theme]')) {
 602          if (prevTheme === 'system') delete document.documentElement.dataset.theme;
 603          else document.documentElement.dataset.theme = prevTheme;
 604        }
 605        if (e.target.id) {
 606          const serverCtl = doc.getElementById(e.target.id);
 607          if (serverCtl instanceof HTMLInputElement && e.target instanceof HTMLInputElement && serverCtl.type === 'checkbox') {
 608            e.target.checked = serverCtl.checked;
 609          } else if (serverCtl instanceof HTMLSelectElement && e.target instanceof HTMLSelectElement) {
 610            e.target.value = serverCtl.value;
 611          }
 612        }
 613        showToast(errEl.textContent.trim(), true);
 614        return;
 615      }
 616      showToast('Saved');
 617    } catch {
 618      showToast('Save failed', true);
 619    }
 620  });
 621
 622  // ---- 8. Live client-side table, list & link filters ----
 623  document.addEventListener('input', (e) => {
 624    const inp = e.target.closest('input[data-filter-table], input[data-filter-list], input[data-filter-links]');
 625    if (!inp) return;
 626    const q = inp.value.trim().toLowerCase();
 627    if (inp.dataset.filterLinks) {
 628      const box = inp.closest('.' + inp.dataset.filterLinks);
 629      if (!box) return;
 630      let shown = 0;
 631      for (const a of box.querySelectorAll('a:not(.allrefs)')) {
 632        const hide = q !== '' && !a.textContent.toLowerCase().includes(q);
 633        a.hidden = hide;
 634        if (!hide) shown++;
 635      }
 636      let empty = box.querySelector('.filter-empty');
 637      if (q !== '' && shown === 0) {
 638        if (!empty) {
 639          empty = document.createElement('span');
 640          empty.className = 'none filter-empty';
 641          empty.style.display = 'block';
 642          empty.style.padding = '4px 12px';
 643          empty.textContent = 'No matching branches';
 644          box.insertBefore(empty, box.querySelector('.allrefs'));
 645        }
 646        empty.hidden = false;
 647      } else if (empty) {
 648        empty.hidden = true;
 649      }
 650      return;
 651    }
 652    if (inp.dataset.filterTable) {
 653      const container = document.getElementById(inp.dataset.filterTable);
 654      const table = container?.tagName === 'TABLE' ? container : container?.querySelector('table');
 655      if (!table) return;
 656      const colSel = inp.dataset.filterCol || '';
 657      const tbody = table.querySelector('tbody') || table;
 658      let shown = 0;
 659      for (const row of tbody.querySelectorAll('tr:not(.filter-empty):not(.cols):not(.tipbar)')) {
 660        if (row.querySelector('td.empty')) continue;
 661        const cell = colSel ? row.querySelector(colSel) : row;
 662        const hay = (cell ? cell.textContent : row.textContent).toLowerCase();
 663        const hide = q !== '' && !hay.includes(q);
 664        row.hidden = hide;
 665        if (!hide) shown++;
 666      }
 667      let emptyRow = tbody.querySelector('tr.filter-empty');
 668      if (q !== '' && shown === 0) {
 669        if (!emptyRow) {
 670          emptyRow = document.createElement('tr');
 671          emptyRow.className = 'filter-empty';
 672          const td = document.createElement('td');
 673          td.colSpan = 10;
 674          td.className = 'empty';
 675          td.textContent = 'No matching items';
 676          emptyRow.appendChild(td);
 677          tbody.appendChild(emptyRow);
 678        }
 679        emptyRow.hidden = false;
 680      } else if (emptyRow) {
 681        emptyRow.hidden = true;
 682      }
 683      return;
 684    }
 685    const list = document.getElementById(inp.dataset.filterList);
 686    if (!list) return;
 687    const ul = list.tagName === 'UL' ? list : list.querySelector('ul');
 688    if (!ul) return;
 689    let shown = 0;
 690    for (const item of ul.querySelectorAll(':scope > li:not(.filter-empty)')) {
 691      if (item.classList.contains('empty')) continue;
 692      const hide = q !== '' && !item.textContent.toLowerCase().includes(q);
 693      item.hidden = hide;
 694      if (!hide) shown++;
 695    }
 696    let emptyLi = ul.querySelector(':scope > li.filter-empty');
 697    if (q !== '' && shown === 0) {
 698      if (!emptyLi) {
 699        emptyLi = document.createElement('li');
 700        emptyLi.className = 'empty filter-empty';
 701        emptyLi.textContent = 'No matching items';
 702        ul.appendChild(emptyLi);
 703      }
 704      emptyLi.hidden = false;
 705    } else if (emptyLi) {
 706      emptyLi.hidden = true;
 707    }
 708  });
 709
 710  // ---- 9. In-place Refresh (/admin, /, /builds, /notifications) ----
 711  document.addEventListener('click', async (e) => {
 712    const btn = e.target.closest('button[data-refresh]');
 713    if (!btn) return;
 714    const url = btn.dataset.refresh === 'self' ? location.href : btn.dataset.refresh;
 715    const targetId = btn.dataset.refreshTarget || 'admin-queues';
 716    btn.disabled = true;
 717    try {
 718      const res = await fetch(url, { credentials: 'same-origin' });
 719      if (!res.ok) { showToast('Refresh failed', true); return; }
 720      const html = await res.text();
 721      const doc = new DOMParser().parseFromString(html, 'text/html');
 722      const next = doc.getElementById(targetId);
 723      const cur = document.getElementById(targetId);
 724      if (next && cur) {
 725        cur.replaceWith(next);
 726        initCopyButtons(next);
 727        initScrollSpy();
 728        showToast('Refreshed');
 729      }
 730    } catch {
 731      showToast('Refresh failed', true);
 732    } finally {
 733      btn.disabled = false;
 734    }
 735  });
 736
 737  // ---- 9b. Smooth in-place tab switching (profile & list tabs) ----
 738  let tabSwappedOnPage = false;
 739  document.addEventListener('click', async (e) => {
 740    if (e.metaKey || e.ctrlKey || e.shiftKey || e.altKey || e.button !== 0) return;
 741    const a = e.target.closest('nav[data-tab-swap] a');
 742    if (!a) return;
 743    const targetId = a.closest('nav[data-tab-swap]').dataset.tabSwap;
 744    const cur = document.getElementById(targetId);
 745    if (!cur) return;
 746    e.preventDefault();
 747    try {
 748      const res = await fetch(a.href, { credentials: 'same-origin' });
 749      if (!res.ok) { location.href = a.href; return; }
 750      const html = await res.text();
 751      const doc = new DOMParser().parseFromString(html, 'text/html');
 752      const next = doc.getElementById(targetId);
 753      if (!next) { location.href = a.href; return; }
 754      if (!tabSwappedOnPage && !(history.state && history.state.tabSwap)) {
 755        history.replaceState({ tabSwap: targetId }, '', location.href);
 756      }
 757      tabSwappedOnPage = true;
 758      cur.replaceWith(next);
 759      if (doc.title) document.title = doc.title;
 760      history.pushState({ tabSwap: targetId }, '', a.href);
 761      initCopyButtons(next);
 762    } catch {
 763      location.href = a.href;
 764    }
 765  });
 766  window.addEventListener('popstate', async (e) => {
 767    const targetId = (e.state && e.state.tabSwap) || document.querySelector('nav[data-tab-swap]')?.dataset.tabSwap;
 768    if (!targetId) return;
 769    const cur = document.getElementById(targetId);
 770    if (!cur) { location.reload(); return; }
 771    try {
 772      const res = await fetch(location.href, { credentials: 'same-origin' });
 773      if (!res.ok) { location.reload(); return; }
 774      const doc = new DOMParser().parseFromString(await res.text(), 'text/html');
 775      const next = doc.getElementById(targetId);
 776      if (!next) { location.reload(); return; }
 777      cur.replaceWith(next);
 778      if (doc.title) document.title = doc.title;
 779      initCopyButtons(next);
 780    } catch {
 781      location.reload();
 782    }
 783  });
 784
 785  // ---- 10. Scroll-spy on sticky section navs ----
 786  function initScrollSpy() {
 787    const nav = document.querySelector('nav[data-scrollspy]');
 788    if (!nav || !('IntersectionObserver' in window)) return;
 789    const links = Array.from(nav.querySelectorAll('a[href^="#"]'));
 790    const byId = new Map();
 791    for (const a of links) {
 792      const id = a.getAttribute('href').slice(1);
 793      if (id) byId.set(id, a);
 794    }
 795    const io = new IntersectionObserver((entries) => {
 796      for (const ent of entries) {
 797        if (!ent.isIntersecting) continue;
 798        for (const a of links) a.removeAttribute('aria-current');
 799        const hit = byId.get(ent.target.id);
 800        if (hit) hit.setAttribute('aria-current', 'location');
 801      }
 802    }, { rootMargin: '-15% 0px -70% 0px' });
 803    for (const id of byId.keys()) {
 804      const sec = document.getElementById(id);
 805      if (sec) io.observe(sec);
 806    }
 807  }
 808
 809  // ---- 11. Client-side panel tabs (/new) & import repo-name inference ----
 810  function initPanelTabs() {
 811    const nav = document.querySelector('nav[data-panel-tabs]');
 812    if (!nav) return;
 813    const container = document.getElementById(nav.dataset.panelTabs);
 814    if (!container) return;
 815    const links = Array.from(nav.querySelectorAll('a[data-panel]'));
 816    const panels = Array.from(container.querySelectorAll('[data-panel-id]'));
 817    const show = (id) => {
 818      const valid = panels.some((p) => p.dataset.panelId === id);
 819      const target = valid ? id : panels[0]?.dataset.panelId;
 820      for (const p of panels) p.hidden = p.dataset.panelId !== target;
 821      for (const a of links) {
 822        if (a.dataset.panel === target) a.setAttribute('aria-current', 'page');
 823        else a.removeAttribute('aria-current');
 824      }
 825    };
 826    const initial = location.hash.replace(/^#/, '') || nav.dataset.activePanel || (document.querySelector('#import input[name="from"]')?.value ? 'import' : 'create');
 827    show(initial);
 828    for (const a of links) {
 829      a.addEventListener('click', (e) => {
 830        e.preventDefault();
 831        show(a.dataset.panel);
 832        history.replaceState(null, '', '#' + a.dataset.panel);
 833      });
 834    }
 835  }
 836
 837  document.addEventListener('input', (e) => {
 838    const src = e.target.closest('input[data-infer-name]');
 839    if (!src) return;
 840    const dst = document.getElementById(src.dataset.inferName);
 841    if (!dst || dst.dataset.userEdited === '1') return;
 842    const raw = src.value.trim().replace(/\/+$/, '').replace(/\.git$/i, '');
 843    const seg = raw.split('/').pop() || '';
 844    const clean = seg.toLowerCase().replace(/[^a-z0-9._-]+/g, '-').replace(/^[^a-z0-9]+/, '').slice(0, 63);
 845    if (clean) dst.value = clean;
 846  });
 847  document.addEventListener('input', (e) => {
 848    if (e.target.id === 'imp-name') e.target.dataset.userEdited = e.target.value ? '1' : '';
 849  });
 850
 851  function adaptShortcutLabels() {
 852    if (/Mac|iPhone|iPad|iPod/i.test(navigator.platform || navigator.userAgent || '')) return;
 853    for (const kbd of document.querySelectorAll('.cmdk-trigger kbd')) {
 854      kbd.textContent = kbd.textContent.replace('⌘', 'Ctrl+');
 855    }
 856    for (const el of document.querySelectorAll('.meta, .crumbs')) {
 857      if (el.childNodes.length === 1 && el.textContent.includes('⌘↵')) {
 858        el.textContent = el.textContent.replace('⌘↵', 'Ctrl+Enter');
 859      }
 860    }
 861  }
 862
 863  // ---- 12. Diff "Viewed" checkboxes, inline hunk expansion & blob Shift+Click ranges ----
 864  function initDiffEnhancements(root = document) {
 865    const wrap = root.querySelector?.('.diffwrap') || document.querySelector('.diffwrap');
 866    if (!wrap) return;
 867    const repo = wrap.dataset.repo || '';
 868    const head = wrap.dataset.head || '';
 869
 870    // Per-file Viewed checkbox backed by localStorage
 871    if (repo && head) {
 872      for (const fold of wrap.querySelectorAll('details.difffold[data-file-path]')) {
 873        const sum = fold.querySelector(':scope > summary');
 874        if (!sum || sum.dataset.viewedWired) continue;
 875        sum.dataset.viewedWired = '1';
 876        const fpath = fold.dataset.filePath;
 877        const key = `gb-viewed:${repo}:${head}:${fpath}`;
 878        const lbl = document.createElement('label');
 879        lbl.className = 'viewed-toggle';
 880        lbl.addEventListener('click', (ev) => ev.stopPropagation());
 881        const cb = document.createElement('input');
 882        cb.type = 'checkbox';
 883        cb.checked = localStorage.getItem(key) === '1';
 884        const syncViewed = (checked, collapse) => {
 885          const tocItem = wrap.querySelector(`.difftoc-list li[data-toc-path="${CSS.escape(fpath)}"]`);
 886          if (tocItem) tocItem.classList.toggle('toc-viewed', checked);
 887          if (collapse) fold.open = !checked;
 888        };
 889        if (cb.checked) syncViewed(true, true);
 890        cb.addEventListener('change', () => {
 891          try {
 892            if (cb.checked) localStorage.setItem(key, '1');
 893            else localStorage.removeItem(key);
 894          } catch {}
 895          syncViewed(cb.checked, true);
 896        });
 897        lbl.append(cb, document.createTextNode('Viewed'));
 898        sum.appendChild(lbl);
 899      }
 900    }
 901
 902    // Inline hunk context expansion ("↑ Expand")
 903    if (repo && head) {
 904      const hunkRe = /^@@ -(\d+)(?:,\d+)? \+(\d+)(?:,\d+)? @@/;
 905      for (const tr of wrap.querySelectorAll('tr.hunk[data-hunk][data-file]')) {
 906        if (tr.dataset.expandWired) continue;
 907        tr.dataset.expandWired = '1';
 908        const m = hunkRe.exec(tr.dataset.hunk || '');
 909        if (!m) continue;
 910        let curNewStart = parseInt(m[2], 10);
 911        let curOldStart = parseInt(m[1], 10);
 912        if (curNewStart <= 1) continue;
 913        const srcTd = tr.querySelector('td.src');
 914        if (!srcTd) continue;
 915        const btn = document.createElement('button');
 916        btn.type = 'button';
 917        btn.className = 'hunk-expand';
 918        btn.textContent = '↑ Expand';
 919        btn.title = 'Load up to 20 preceding context lines';
 920        btn.addEventListener('click', async () => {
 921          const to = curNewStart - 1;
 922          const from = Math.max(1, to - 19);
 923          if (to < 1) { btn.remove(); return; }
 924          btn.disabled = true;
 925          try {
 926            const fpath = tr.dataset.file;
 927            const res = await fetch(`/${repo}/blob/${head}/${fpath}?lines=${from}:${to}`, { credentials: 'same-origin' });
 928            if (!res.ok) throw new Error('fetch');
 929            const data = await res.json();
 930            const isSplit = tr.closest('table')?.classList.contains('split');
 931            const oldOffset = curOldStart - curNewStart;
 932            for (const item of (data.lines || [])) {
 933              const ctxTr = document.createElement('tr');
 934              if (isSplit) {
 935                ctxTr.className = 'pair';
 936                const ln1 = document.createElement('td'); ln1.className = 'ln ctx old'; ln1.textContent = String(Math.max(1, item.n + oldOffset));
 937                const s1 = document.createElement('td'); s1.className = 'src ctx old chroma'; s1.innerHTML = item.html;
 938                const ln2 = document.createElement('td'); ln2.className = 'ln ctx'; ln2.textContent = String(item.n);
 939                const s2 = document.createElement('td'); s2.className = 'src ctx chroma'; s2.innerHTML = item.html;
 940                ctxTr.append(ln1, s1, ln2, s2);
 941              } else {
 942                ctxTr.className = 'ctx';
 943                const ln1 = document.createElement('td'); ln1.className = 'ln'; ln1.textContent = String(Math.max(1, item.n + oldOffset));
 944                const ln2 = document.createElement('td'); ln2.className = 'ln'; ln2.textContent = String(item.n);
 945                const s = document.createElement('td'); s.className = 'src chroma'; s.innerHTML = item.html;
 946                ctxTr.append(ln1, ln2, s);
 947              }
 948              tr.parentNode.insertBefore(ctxTr, tr.nextSibling);
 949            }
 950            // Move expanded rows in ascending order right after tr
 951            const inserted = [];
 952            let sib = tr.nextSibling;
 953            for (let k = 0; k < (data.lines || []).length && sib; k++) {
 954              inserted.push(sib);
 955              sib = sib.nextSibling;
 956            }
 957            inserted.reverse().forEach((n) => tr.parentNode.insertBefore(n, sib));
 958            curOldStart = Math.max(1, curOldStart - (curNewStart - from));
 959            curNewStart = from;
 960            if (curNewStart <= 1) btn.remove();
 961          } catch {
 962            showToast('Could not expand context', true);
 963          } finally {
 964            btn.disabled = false;
 965          }
 966        });
 967        srcTd.prepend(btn);
 968      }
 969    }
 970  }
 971
 972  // Blob Shift+Click multi-line range (#L10-L25)
 973  function applyLineRangeFromHash() {
 974    const m = /^#L(\d+)(?:-L?(\d+))?$/.exec(location.hash);
 975    for (const el of document.querySelectorAll('.code .line.range-hl')) el.classList.remove('range-hl');
 976    if (!m || !m[2]) return;
 977    let a = parseInt(m[1], 10), b = parseInt(m[2], 10);
 978    if (a > b) [a, b] = [b, a];
 979    for (let i = a; i <= b; i++) {
 980      const anchor = document.getElementById('L' + i);
 981      const line = anchor?.closest('.line');
 982      if (line) line.classList.add('range-hl');
 983    }
 984  }
 985  let lastClickedLine = 0;
 986  document.addEventListener('click', (e) => {
 987    const lnLink = e.target.closest('.code a.lnlinks[href^="#L"]');
 988    if (!lnLink) return;
 989    const n = parseInt(lnLink.getAttribute('href').slice(2), 10);
 990    if (!n) return;
 991    if (e.shiftKey && lastClickedLine > 0 && lastClickedLine !== n) {
 992      e.preventDefault();
 993      const lo = Math.min(lastClickedLine, n), hi = Math.max(lastClickedLine, n);
 994      history.replaceState(null, '', `#L${lo}-L${hi}`);
 995      applyLineRangeFromHash();
 996    } else {
 997      lastClickedLine = n;
 998      setTimeout(applyLineRangeFromHash, 0);
 999    }
1000  });
1001  window.addEventListener('hashchange', applyLineRangeFromHash);
1002
1003  // ---- 13. Composer Write | Preview tabs & @/# /! autocomplete ----
1004  function initComposers(root = document) {
1005    const forms = root.querySelectorAll ? root.querySelectorAll('form') : [];
1006    for (const form of forms) {
1007      if (form.dataset.composerWired) continue;
1008      const previewBtn = form.querySelector('button[name="preview"]');
1009      const ta = form.querySelector('textarea');
1010      if (!previewBtn || !ta) continue;
1011      form.dataset.composerWired = '1';
1012
1013      const bar = document.createElement('div');
1014      bar.className = 'composer-bar';
1015      const writeTab = document.createElement('button');
1016      writeTab.type = 'button';
1017      writeTab.className = 'composer-tab';
1018      writeTab.setAttribute('aria-selected', 'true');
1019      writeTab.textContent = 'Write';
1020
1021      const prevTab = document.createElement('button');
1022      prevTab.type = 'button';
1023      prevTab.className = 'composer-tab';
1024      prevTab.setAttribute('aria-selected', 'false');
1025      prevTab.textContent = 'Preview';
1026
1027      const hint = document.createElement('span');
1028      hint.className = 'composer-hint';
1029      hint.textContent = '@user · #issue · !MR';
1030      bar.append(writeTab, prevTab, hint);
1031
1032      const pane = document.createElement('div');
1033      pane.className = 'composer-preview rendered';
1034      pane.hidden = true;
1035
1036      const wrapTarget = ta.closest('p') || ta;
1037      wrapTarget.parentNode.insertBefore(bar, wrapTarget);
1038      wrapTarget.parentNode.insertBefore(pane, wrapTarget.nextSibling);
1039      previewBtn.classList.add('js-hidden-preview');
1040
1041      writeTab.addEventListener('click', () => {
1042        writeTab.setAttribute('aria-selected', 'true');
1043        prevTab.setAttribute('aria-selected', 'false');
1044        pane.hidden = true;
1045        wrapTarget.hidden = false;
1046        ta.focus();
1047      });
1048
1049      prevTab.addEventListener('click', async () => {
1050        writeTab.setAttribute('aria-selected', 'false');
1051        prevTab.setAttribute('aria-selected', 'true');
1052        wrapTarget.hidden = true;
1053        pane.hidden = false;
1054        if (!ta.value.trim()) {
1055          pane.innerHTML = '<p class="none">Nothing to preview.</p>';
1056          return;
1057        }
1058        pane.innerHTML = '<p class="none">Rendering preview…</p>';
1059        try {
1060          const fd = new FormData(form);
1061          fd.set('preview', '1');
1062          const res = await fetch(form.action || location.href, {
1063            method: 'POST',
1064            body: new URLSearchParams(fd),
1065            headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
1066            credentials: 'same-origin',
1067          });
1068          if (!res.ok) throw new Error('preview');
1069          const doc = new DOMParser().parseFromString(await res.text(), 'text/html');
1070          const rendered = doc.querySelector('.preview .rendered');
1071          pane.innerHTML = rendered ? rendered.innerHTML : '<p class="none">Nothing to preview.</p>';
1072          initCopyButtons(pane);
1073        } catch {
1074          pane.innerHTML = '<p class="error">Preview failed.</p>';
1075        }
1076      });
1077    }
1078  }
1079
1080  // Lightweight @mention, #issue, and !MR autocomplete on textareas
1081  let acMenu = null;
1082  let acItems = [];
1083  let acIndex = 0;
1084  let acContext = null;
1085  let acTimer = 0;
1086
1087  function closeAutocomplete() {
1088    if (acMenu) acMenu.hidden = true;
1089    acItems = [];
1090    acContext = null;
1091  }
1092
1093  function ensureAutocompleteMenu() {
1094    if (acMenu) return acMenu;
1095    acMenu = document.createElement('ul');
1096    acMenu.className = 'ac-menu';
1097    acMenu.hidden = true;
1098    document.body.appendChild(acMenu);
1099    return acMenu;
1100  }
1101
1102  function applyAutocomplete(choice) {
1103    if (!acContext || !choice) return;
1104    const { ta, start, end } = acContext;
1105    const before = ta.value.slice(0, start);
1106    const after = ta.value.slice(end);
1107    const insert = choice.insert + ' ';
1108    ta.value = before + insert + after;
1109    const pos = before.length + insert.length;
1110    ta.setSelectionRange(pos, pos);
1111    ta.focus();
1112    closeAutocomplete();
1113  }
1114
1115  function renderAutocomplete(ta) {
1116    const menu = ensureAutocompleteMenu();
1117    if (!acItems.length) {
1118      closeAutocomplete();
1119      return;
1120    }
1121    menu.innerHTML = '';
1122    acItems.forEach((it, idx) => {
1123      const li = document.createElement('li');
1124      li.className = idx === acIndex ? 'ac-active' : '';
1125      const b = document.createElement('strong');
1126      b.textContent = it.insert;
1127      const sp = document.createElement('span');
1128      sp.textContent = it.label;
1129      li.append(b, sp);
1130      li.addEventListener('mousedown', (ev) => {
1131        ev.preventDefault();
1132        applyAutocomplete(it);
1133      });
1134      menu.appendChild(li);
1135    });
1136    const rect = ta.getBoundingClientRect();
1137    menu.style.left = `${Math.max(8, rect.left + window.scrollX + 12)}px`;
1138    menu.style.top = `${rect.top + window.scrollY + Math.min(rect.height, 42)}px`;
1139    menu.hidden = false;
1140  }
1141
1142  function collectPagePeople() {
1143    const set = new Set();
1144    for (const opt of document.querySelectorAll('#repo-people option')) {
1145      if (opt.value) set.add(opt.value);
1146    }
1147    for (const a of document.querySelectorAll('.commenthead a[href^="/"], .aside a[href^="/"]')) {
1148      const u = a.getAttribute('href').slice(1);
1149      if (u && !u.includes('/') && !u.includes('?')) set.add(u);
1150    }
1151    return Array.from(set);
1152  }
1153
1154  document.addEventListener('input', (e) => {
1155    if (!(e.target instanceof HTMLTextAreaElement)) return;
1156    const ta = e.target;
1157    const pos = ta.selectionStart;
1158    const upto = ta.value.slice(0, pos);
1159    const m = /(?:^|\s)([@#!])([a-zA-Z0-9._-]{0,24})$/.exec(upto);
1160    if (!m) {
1161      closeAutocomplete();
1162      return;
1163    }
1164    const trig = m[1];
1165    const q = m[2].toLowerCase();
1166    const start = pos - m[2].length - 1;
1167    acContext = { ta, start, end: pos };
1168    acIndex = 0;
1169
1170    if (trig === '@') {
1171      const people = collectPagePeople().filter((u) => u.toLowerCase().startsWith(q)).slice(0, 6);
1172      acItems = people.map((u) => ({ insert: '@' + u, label: u }));
1173      renderAutocomplete(ta);
1174      return;
1175    }
1176    const ctx = currentRepoContext();
1177    if (!ctx.repo) {
1178      closeAutocomplete();
1179      return;
1180    }
1181    clearTimeout(acTimer);
1182    acTimer = setTimeout(async () => {
1183      try {
1184        const params = new URLSearchParams({ format: 'palette', repo: ctx.repo, q });
1185        const res = await fetch('/search?' + params.toString(), { credentials: 'same-origin' });
1186        if (!res.ok) return;
1187        const data = await res.json();
1188        const wantGroup = trig === '#' ? 'Issue' : 'MR';
1189        acItems = (data.items || [])
1190          .filter((it) => it.group === wantGroup)
1191          .slice(0, 6)
1192          .map((it) => {
1193            const num = it.href.split('/').pop();
1194            return { insert: trig + num, label: it.label };
1195          });
1196        renderAutocomplete(ta);
1197      } catch {}
1198    }, 120);
1199  });
1200
1201  document.addEventListener('keydown', (e) => {
1202    if (!acMenu || acMenu.hidden || !acItems.length) return;
1203    if (e.key === 'ArrowDown') {
1204      e.preventDefault();
1205      acIndex = (acIndex + 1) % acItems.length;
1206      if (acContext) renderAutocomplete(acContext.ta);
1207    } else if (e.key === 'ArrowUp') {
1208      e.preventDefault();
1209      acIndex = (acIndex - 1 + acItems.length) % acItems.length;
1210      if (acContext) renderAutocomplete(acContext.ta);
1211    } else if (e.key === 'Enter' || e.key === 'Tab') {
1212      e.preventDefault();
1213      applyAutocomplete(acItems[acIndex]);
1214    } else if (e.key === 'Escape') {
1215      e.preventDefault();
1216      closeAutocomplete();
1217    }
1218  }, true);
1219  document.addEventListener('blur', (e) => {
1220    if (e.target instanceof HTMLTextAreaElement) setTimeout(closeAutocomplete, 150);
1221  }, true);
1222
1223  function bootAll() {
1224    initCopyButtons();
1225    initScrollSpy();
1226    initPanelTabs();
1227    adaptShortcutLabels();
1228    initDiffEnhancements();
1229    applyLineRangeFromHash();
1230    initComposers();
1231  }
1232
1233  if (document.readyState === 'loading') {
1234    document.addEventListener('DOMContentLoaded', bootAll);
1235  } else {
1236    bootAll();
1237  }
1238})();
Keyboard shortcuts

Global

⌘K
Command palette & jump
/
Focus search
?
Show this help
g d
Dashboard
g e
Explore repositories
g n
Notifications

Repository & editor

t
Find file in repository
y
Copy immutable SHA permalink
g c
Code tab
g i
Issues tab
g m
Merge requests tab
g b
Builds tab
⌘↵
Submit active form