internal/web/static/app.js

ac8d910ff31c2fadc452928e1d56c64b4af25495
gitbay/internal/web/static/app.js

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