wiki.js 3.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. /* Wiki search: titles and headings from /wiki/search.json (built by _src/build.py), nothing leaves the browser.
  2. Ctrl+K (or /) focuses the box, arrows move, Enter opens. Without this script the box is hidden. */
  3. (() => {
  4. const box = document.getElementById('wq'), res = document.getElementById('wres');
  5. if (!box || !res) return;
  6. const t = window.LYNX_T || (k => k);
  7. let index = null, groups = {}, sel = 0, hits = [];
  8. const group = k => { const v = t(k); return v === k ? (groups[k] || '') : v; };
  9. const V = window.LYNX_V || '';
  10. const loadIndex = () => index ? Promise.resolve(index) : fetch('/wiki/search.json?v=' + V).then(r => r.json()).then(d => { groups = d.g; return index = d.p; });
  11. // the headings of the translated bodies, by page: {address: [[id, text], ...]} (languages without them search the English ones)
  12. let local = {}, localFor = 'en';
  13. const loadLocal = () => {
  14. const l = document.documentElement.lang || 'en';
  15. if (l === localFor) return Promise.resolve();
  16. localFor = l; local = {};
  17. return l === 'en' ? Promise.resolve() : fetch('/i18n/wiki/' + l + '/heads.json?v=' + V).then(r => r.ok ? r.json() : {}).then(d => { if (localFor === l) local = d; }).catch(() => {});
  18. };
  19. const load = () => Promise.all([loadIndex(), loadLocal()]);
  20. const anchor = s => s.toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-|-$/g, '');
  21. const norm = s => String(s).toLowerCase().normalize('NFD').replace(/[̀-ͯ]/g, '');
  22. const esc = s => String(s).replace(/[&<>"]/g, c => ({'&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;'}[c]));
  23. const title = e => { const v = e[1] ? t(e[1]) : e[2]; return v === e[1] ? e[2] : v; };
  24. function search(q){
  25. const words = norm(q).split(/\s+/).filter(Boolean);
  26. if (!words.length) return [];
  27. const out = [];
  28. for (const e of index){
  29. const ti = norm(title(e) + ' ' + e[2]);
  30. let score = 0, head = null;
  31. for (const w of words){
  32. if (ti.startsWith(w)) score += 6; else if (ti.includes(w)) score += 4;
  33. else {
  34. const h = (local[e[0]] || []).find(x => norm(x[1]).includes(w)) || (e[4].map(x => [anchor(x), x]).find(x => norm(x[1]).includes(w)));
  35. if (h){ score += 1; head = head || h; } else { score = -1; break; }
  36. }
  37. }
  38. if (score > 0) out.push([score, e, head]);
  39. }
  40. return out.sort((a, b) => b[0] - a[0]).slice(0, 12);
  41. }
  42. function draw(){
  43. if (!box.value.trim()){ res.hidden = true; return; }
  44. res.hidden = false;
  45. res.innerHTML = hits.length ? hits.map(([, e, head], i) => `<a href="${e[0]}${head ? '#' + head[0] : ''}" class="${i === sel ? 'on' : ''}">${esc(title(e))}<small>${esc(head ? head[1] : group(e[3]))}</small></a>`).join('')
  46. : `<p>${esc(t('ws.none'))}</p>`;
  47. }
  48. box.addEventListener('input', () => load().then(() => { hits = search(box.value); sel = 0; draw(); }));
  49. box.addEventListener('focus', () => { load(); if (box.value.trim()) draw(); });
  50. box.addEventListener('keydown', e => {
  51. if (e.key === 'ArrowDown' || e.key === 'ArrowUp'){ e.preventDefault(); if (hits.length){ sel = (sel + (e.key === 'ArrowDown' ? 1 : hits.length - 1)) % hits.length; draw(); } }
  52. else if (e.key === 'Enter' && hits[sel]){ e.preventDefault(); const a = res.querySelectorAll('a')[sel]; if (a) location.href = a.href; }
  53. else if (e.key === 'Escape'){ res.hidden = true; box.blur(); }
  54. });
  55. document.addEventListener('click', e => { if (!e.target.closest('.wsearch')) res.hidden = true; });
  56. // /wiki/?q=reverb opens with the results shown
  57. try { const q = new URLSearchParams(location.search).get('q'); if (q){ box.value = q; load().then(() => { hits = search(q); draw(); }); } } catch (x) {}
  58. document.addEventListener('keydown', e => {
  59. const typing = /^(INPUT|TEXTAREA|SELECT)$/.test((e.target || {}).tagName || '');
  60. if ((e.key === 'k' && (e.ctrlKey || e.metaKey)) || (e.key === '/' && !typing)){ e.preventDefault(); box.scrollIntoView({block: 'nearest'}); box.focus(); box.select(); }
  61. });
  62. })();