Quick search: palette behaviour
This commit is contained in:
1 parent
d2827ee8f3
commit
26a0394ca9
1 file changed
+462
@@ -0,0 +1,462 @@
|
||||
/* OpenBench quick search: a Spotlight-style palette.
|
||||
Opens with Ctrl+K or Cmd+K ( and with / outside of text fields ).
|
||||
No dependencies. Without this file the Search button still opens /search. */
|
||||
|
||||
(function () {
|
||||
'use strict';
|
||||
|
||||
var root = document.getElementById('palette');
|
||||
var source = document.getElementById('palette-source');
|
||||
if (!root || !source) return;
|
||||
|
||||
var input = root.querySelector('.pl-input');
|
||||
var list = root.querySelector('.pl-list');
|
||||
var status = root.querySelector('.pl-sr');
|
||||
var form = document.getElementById('palette-search');
|
||||
var trigger = document.getElementById('palette-open');
|
||||
|
||||
var isMac = /Mac|iPhone|iPad|iPod/i.test(navigator.platform || navigator.userAgent || '');
|
||||
|
||||
var STATES = {
|
||||
passed: 'Passed', failed: 'Failed', stopped: 'Stopped', running: 'Running',
|
||||
pending: 'Pending', awaiting: 'Awaiting', deleted: 'Deleted'
|
||||
};
|
||||
|
||||
/* Pages and actions come from the server, so they follow the login state */
|
||||
|
||||
var pages = Array.prototype.map.call(source.querySelectorAll('li'), function (li) {
|
||||
return {
|
||||
kind : 'link',
|
||||
key : 'page:' + li.getAttribute('data-href'),
|
||||
title : li.textContent.trim(),
|
||||
href : li.getAttribute('data-href'),
|
||||
icon : li.getAttribute('data-icon') || 'fa-arrow-right',
|
||||
group : li.getAttribute('data-group') || 'Go to',
|
||||
keywords : (li.getAttribute('data-keywords') || '').toLowerCase(),
|
||||
featured : li.hasAttribute('data-featured'),
|
||||
external : li.hasAttribute('data-external')
|
||||
};
|
||||
});
|
||||
|
||||
var rows = []; // what is on screen: { item, el }
|
||||
var active = -1;
|
||||
var moved = false; // the person has picked a row themselves
|
||||
var returnTo = null;
|
||||
var cache = {}; // query -> tests from the server
|
||||
var lastTests = []; // the latest answer, shown while the next one loads
|
||||
var inflight = null; // { timer, controller }
|
||||
|
||||
/* ---------- Matching ---------- */
|
||||
|
||||
function match(text, query) {
|
||||
|
||||
if (!query) return { score: 0, hits: [] };
|
||||
|
||||
var t = text.toLowerCase(), q = query.toLowerCase();
|
||||
var at = t.indexOf(q), hits = [], i;
|
||||
|
||||
if (at !== -1) {
|
||||
for (i = 0; i < q.length; i++) hits.push(at + i);
|
||||
var boundary = at === 0 || /[\s\-_\/.]/.test(t.charAt(at - 1));
|
||||
return { score: (at === 0 ? 120 : boundary ? 100 : 70) - Math.min(at, 30), hits: hits };
|
||||
}
|
||||
|
||||
// The letters in order, so that "mch" still finds "Machines"
|
||||
var from = 0, gaps = 0;
|
||||
for (i = 0; i < q.length; i++) {
|
||||
var found = t.indexOf(q.charAt(i), from);
|
||||
if (found === -1) return null;
|
||||
if (hits.length && found !== hits[hits.length - 1] + 1) gaps++;
|
||||
hits.push(found);
|
||||
from = found + 1;
|
||||
}
|
||||
return { score: Math.max(10, 50 - gaps * 8), hits: hits };
|
||||
}
|
||||
|
||||
function liveTests(q) {
|
||||
|
||||
if (cache[q]) return cache[q];
|
||||
|
||||
// Until the answer for this exact query arrives, keep what still fits
|
||||
var needle = q.toLowerCase();
|
||||
return lastTests.filter(function (t) {
|
||||
return (t.name + ' ' + t.author + ' ' + t.engine + ' ' + t.id).toLowerCase().indexOf(needle) !== -1;
|
||||
});
|
||||
}
|
||||
|
||||
/* ---------- What to show ---------- */
|
||||
|
||||
function buildGroups(q) {
|
||||
|
||||
var groups = [], i;
|
||||
|
||||
// Tests: a direct jump for numbers, then whatever the server found
|
||||
var tests = liveTests(q).map(function (t) {
|
||||
var m = match(t.name, q);
|
||||
return {
|
||||
kind: 'link', key: 'test:' + t.id, href: t.url, icon: 'fa-flask',
|
||||
title: t.name, hits: m ? m.hits : [], state: t.status,
|
||||
sub: '#' + t.id + ' by ' + t.author + ', ' + t.tc
|
||||
};
|
||||
});
|
||||
|
||||
var number = /^#?(\d{1,9})$/.exec(q);
|
||||
if (number && !tests.some(function (t) { return t.key === 'test:' + number[1]; })) {
|
||||
tests.unshift({
|
||||
kind: 'link', key: 'test:' + number[1], href: '/test/' + number[1] + '/', icon: 'fa-flask',
|
||||
title: 'Open test #' + number[1], sub: 'Jump straight to it', hits: []
|
||||
});
|
||||
}
|
||||
|
||||
// Pages and actions, grouped as on the server, best group first
|
||||
var buckets = [], byName = {};
|
||||
pages.forEach(function (page) {
|
||||
|
||||
var m = null;
|
||||
if (!q) { if (!page.featured) return; m = { score: 0, hits: [] }; }
|
||||
else {
|
||||
m = match(page.title, q);
|
||||
if (!m && page.keywords.indexOf(q.toLowerCase()) !== -1) m = { score: 35, hits: [] };
|
||||
}
|
||||
if (!m) return;
|
||||
|
||||
var bucket = byName[page.group];
|
||||
if (!bucket) { bucket = byName[page.group] = { label: page.group, best: 0, items: [] }; buckets.push(bucket); }
|
||||
|
||||
bucket.best = Math.max(bucket.best, m.score);
|
||||
bucket.items.push({ item: page, score: m.score, hits: m.hits });
|
||||
});
|
||||
|
||||
var best = 0;
|
||||
if (q) buckets.sort(function (a, b) { return b.best - a.best; });
|
||||
buckets.forEach(function (bucket) {
|
||||
if (q) bucket.items.sort(function (a, b) { return b.score - a.score; });
|
||||
best = Math.max(best, bucket.best);
|
||||
});
|
||||
|
||||
var pageGroups = buckets.map(function (bucket) {
|
||||
return {
|
||||
label: bucket.label,
|
||||
items: bucket.items.map(function (entry) {
|
||||
var item = Object.create(entry.item);
|
||||
item.hits = entry.hits;
|
||||
return item;
|
||||
})
|
||||
};
|
||||
});
|
||||
|
||||
var testGroup = tests.length ? [{ label: 'Tests', items: tests }] : [];
|
||||
|
||||
// A page that starts with what was typed wins, otherwise tests come first
|
||||
groups = (q && best < 100) ? testGroup.concat(pageGroups) : pageGroups.concat(testGroup);
|
||||
|
||||
if (q) {
|
||||
groups.push({ label: 'Search', items: [{
|
||||
kind: 'search', key: 'search', icon: 'fa-magnifying-glass', hits: [],
|
||||
title: 'Search all tests for \u201C' + q + '\u201D', sub: 'Looks through every branch name'
|
||||
}] });
|
||||
}
|
||||
|
||||
return groups;
|
||||
}
|
||||
|
||||
/* ---------- Drawing ---------- */
|
||||
|
||||
function fill(el, text, hits) {
|
||||
|
||||
if (!hits || !hits.length) { el.textContent = text; return; }
|
||||
|
||||
var marked = {}, run = '', on = false, i;
|
||||
hits.forEach(function (h) { marked[h] = true; });
|
||||
|
||||
function flush() {
|
||||
if (!run) return;
|
||||
if (on) { var b = document.createElement('b'); b.textContent = run; el.appendChild(b); }
|
||||
else el.appendChild(document.createTextNode(run));
|
||||
run = '';
|
||||
}
|
||||
|
||||
for (i = 0; i < text.length; i++) {
|
||||
var hit = !!marked[i];
|
||||
if (hit !== on) { flush(); on = hit; }
|
||||
run += text.charAt(i);
|
||||
}
|
||||
flush();
|
||||
}
|
||||
|
||||
function element(tag, className, text) {
|
||||
var el = document.createElement(tag);
|
||||
if (className) el.className = className;
|
||||
if (text) el.textContent = text;
|
||||
return el;
|
||||
}
|
||||
|
||||
function buildRow(item, index) {
|
||||
|
||||
var li = element('li', 'pl-item');
|
||||
li.id = 'pl-opt-' + index;
|
||||
li.setAttribute('role', 'option');
|
||||
li.setAttribute('aria-selected', 'false');
|
||||
li.setAttribute('data-index', index);
|
||||
|
||||
var tile = element('span', 'pl-icon');
|
||||
var icon = element('i', 'fa-solid ' + item.icon);
|
||||
icon.setAttribute('aria-hidden', 'true');
|
||||
tile.appendChild(icon);
|
||||
|
||||
var text = element('span', 'pl-text');
|
||||
var title = element('span', 'pl-title');
|
||||
fill(title, item.title, item.hits);
|
||||
text.appendChild(title);
|
||||
if (item.sub) text.appendChild(element('span', 'pl-sub', item.sub));
|
||||
|
||||
li.appendChild(tile);
|
||||
li.appendChild(text);
|
||||
|
||||
if (item.state) {
|
||||
var chip = element('span', 'pl-chip', STATES[item.state] || item.state);
|
||||
chip.setAttribute('data-state', item.state);
|
||||
li.appendChild(chip);
|
||||
}
|
||||
|
||||
if (item.external) {
|
||||
var out = element('i', 'fa-solid fa-arrow-up-right-from-square pl-ext');
|
||||
out.setAttribute('aria-hidden', 'true');
|
||||
li.appendChild(out);
|
||||
}
|
||||
|
||||
var enter = element('kbd', 'pl-enter', '\u21B5');
|
||||
enter.setAttribute('aria-hidden', 'true');
|
||||
li.appendChild(enter);
|
||||
|
||||
return li;
|
||||
}
|
||||
|
||||
function setActive(index, scroll) {
|
||||
|
||||
if (rows[active]) rows[active].el.setAttribute('aria-selected', 'false');
|
||||
active = index;
|
||||
|
||||
if (!rows[index]) { input.removeAttribute('aria-activedescendant'); return; }
|
||||
|
||||
rows[index].el.setAttribute('aria-selected', 'true');
|
||||
input.setAttribute('aria-activedescendant', rows[index].el.id);
|
||||
|
||||
if (!scroll) return;
|
||||
if (index === 0) list.scrollTop = 0;
|
||||
else rows[index].el.scrollIntoView({ block: 'nearest' });
|
||||
}
|
||||
|
||||
function render() {
|
||||
|
||||
var q = input.value.trim();
|
||||
var keep = moved && rows[active] ? rows[active].item.key : null;
|
||||
|
||||
list.textContent = '';
|
||||
rows = [];
|
||||
|
||||
buildGroups(q).forEach(function (group) {
|
||||
var head = element('li', 'pl-group', group.label);
|
||||
head.setAttribute('role', 'presentation');
|
||||
list.appendChild(head);
|
||||
|
||||
group.items.forEach(function (item) {
|
||||
var el = buildRow(item, rows.length);
|
||||
list.appendChild(el);
|
||||
rows.push({ item: item, el: el });
|
||||
});
|
||||
});
|
||||
|
||||
var next = 0;
|
||||
rows.forEach(function (row, i) { if (keep && row.item.key === keep) next = i; });
|
||||
|
||||
active = -1;
|
||||
setActive(rows.length ? next : -1, false);
|
||||
status.textContent = rows.length + (rows.length === 1 ? ' result' : ' results');
|
||||
}
|
||||
|
||||
/* ---------- Asking the server for tests ---------- */
|
||||
|
||||
function cancel() {
|
||||
if (!inflight) return;
|
||||
if (inflight.timer) clearTimeout(inflight.timer);
|
||||
if (inflight.controller) inflight.controller.abort();
|
||||
inflight = null;
|
||||
}
|
||||
|
||||
function request(q) {
|
||||
|
||||
var controller = window.AbortController ? new AbortController() : null;
|
||||
inflight = { timer: null, controller: controller };
|
||||
|
||||
fetch('/api/quick-search/?q=' + encodeURIComponent(q), {
|
||||
credentials : 'same-origin',
|
||||
headers : { 'Accept': 'application/json' },
|
||||
signal : controller ? controller.signal : undefined
|
||||
})
|
||||
.then(function (response) { return response.ok ? response.json() : { tests: [] }; })
|
||||
.then(function (data) {
|
||||
cache[q] = data.tests || [];
|
||||
lastTests = cache[q];
|
||||
if (input.value.trim() === q) render();
|
||||
})
|
||||
.catch(function () { /* aborted, or offline: pages still work */ });
|
||||
}
|
||||
|
||||
function schedule() {
|
||||
|
||||
cancel();
|
||||
|
||||
var q = input.value.trim();
|
||||
if (!q || cache[q]) return;
|
||||
|
||||
inflight = { timer: setTimeout(function () { request(q); }, 140), controller: null };
|
||||
}
|
||||
|
||||
/* ---------- Opening, closing, choosing ---------- */
|
||||
|
||||
function isOpen() { return !root.hidden; }
|
||||
|
||||
function open() {
|
||||
|
||||
if (isOpen()) return;
|
||||
|
||||
returnTo = document.activeElement;
|
||||
root.hidden = false;
|
||||
|
||||
root.classList.remove('is-open');
|
||||
void root.offsetWidth; // restart the entrance animation
|
||||
root.classList.add('is-open');
|
||||
|
||||
document.documentElement.classList.add('palette-open');
|
||||
if (trigger) trigger.setAttribute('aria-expanded', 'true');
|
||||
|
||||
input.value = '';
|
||||
moved = false;
|
||||
render();
|
||||
input.focus();
|
||||
}
|
||||
|
||||
function close() {
|
||||
|
||||
if (!isOpen()) return;
|
||||
|
||||
cancel();
|
||||
root.hidden = true;
|
||||
root.classList.remove('is-open');
|
||||
document.documentElement.classList.remove('palette-open');
|
||||
if (trigger) trigger.setAttribute('aria-expanded', 'false');
|
||||
|
||||
if (returnTo && returnTo.focus && document.contains(returnTo)) returnTo.focus();
|
||||
}
|
||||
|
||||
function choose(item, newTab) {
|
||||
|
||||
if (item.kind === 'search') {
|
||||
form.querySelector('[name="keywords"]').value = input.value.trim();
|
||||
form.submit();
|
||||
return;
|
||||
}
|
||||
|
||||
if (item.external || newTab) {
|
||||
window.open(item.href, '_blank', 'noopener');
|
||||
close();
|
||||
return;
|
||||
}
|
||||
|
||||
window.location.href = item.href;
|
||||
close();
|
||||
}
|
||||
|
||||
function move(step) {
|
||||
if (!rows.length) return;
|
||||
moved = true;
|
||||
setActive((active + step + rows.length) % rows.length, true);
|
||||
}
|
||||
|
||||
/* ---------- Events ---------- */
|
||||
|
||||
input.addEventListener('input', function () {
|
||||
moved = false;
|
||||
render();
|
||||
schedule();
|
||||
});
|
||||
|
||||
input.addEventListener('keydown', function (event) {
|
||||
|
||||
if (event.isComposing) return;
|
||||
|
||||
if (event.key === 'ArrowDown') { event.preventDefault(); move(1); }
|
||||
else if (event.key === 'ArrowUp') { event.preventDefault(); move(-1); }
|
||||
else if (event.key === 'Tab') { event.preventDefault(); move(event.shiftKey ? -1 : 1); }
|
||||
else if (event.key === 'Enter') {
|
||||
event.preventDefault();
|
||||
if (rows[active]) choose(rows[active].item, event.metaKey || event.ctrlKey);
|
||||
}
|
||||
else if (event.key === 'Escape') { event.preventDefault(); close(); }
|
||||
});
|
||||
|
||||
// Keep the caret in the field while the pointer works on the list
|
||||
list.addEventListener('mousedown', function (event) { event.preventDefault(); });
|
||||
|
||||
list.addEventListener('mousemove', function (event) {
|
||||
var li = event.target.closest ? event.target.closest('.pl-item') : null;
|
||||
if (!li) return;
|
||||
var index = parseInt(li.getAttribute('data-index'), 10);
|
||||
if (index !== active) { moved = true; setActive(index, false); }
|
||||
});
|
||||
|
||||
list.addEventListener('click', function (event) {
|
||||
var li = event.target.closest ? event.target.closest('.pl-item') : null;
|
||||
if (!li) return;
|
||||
var row = rows[parseInt(li.getAttribute('data-index'), 10)];
|
||||
if (row) choose(row.item, event.metaKey || event.ctrlKey);
|
||||
});
|
||||
|
||||
root.querySelector('.pl-backdrop').addEventListener('click', close);
|
||||
|
||||
// Nothing behind the palette should take the focus
|
||||
root.addEventListener('focusin', function (event) {
|
||||
if (!root.querySelector('.pl-panel').contains(event.target)) input.focus();
|
||||
});
|
||||
|
||||
function typing(target) {
|
||||
if (!target || !target.tagName) return false;
|
||||
return /^(INPUT|TEXTAREA|SELECT)$/.test(target.tagName) || target.isContentEditable;
|
||||
}
|
||||
|
||||
document.addEventListener('keydown', function (event) {
|
||||
|
||||
var key = (event.key || '').toLowerCase();
|
||||
|
||||
if ((event.metaKey || event.ctrlKey) && !event.altKey && !event.shiftKey && key === 'k') {
|
||||
event.preventDefault();
|
||||
if (isOpen()) close(); else open();
|
||||
return;
|
||||
}
|
||||
|
||||
if (key === '/' && !event.metaKey && !event.ctrlKey && !event.altKey && !isOpen() && !typing(event.target)) {
|
||||
event.preventDefault();
|
||||
open();
|
||||
}
|
||||
}, true);
|
||||
|
||||
if (trigger) {
|
||||
trigger.setAttribute('aria-haspopup', 'dialog');
|
||||
trigger.setAttribute('aria-expanded', 'false');
|
||||
|
||||
trigger.addEventListener('click', function (event) {
|
||||
if (event.button !== 0 || event.metaKey || event.ctrlKey || event.shiftKey) return;
|
||||
event.preventDefault();
|
||||
open();
|
||||
});
|
||||
}
|
||||
|
||||
// Coming back with the Back button should never show an open palette
|
||||
window.addEventListener('pageshow', function (event) { if (event.persisted) close(); });
|
||||
|
||||
Array.prototype.forEach.call(document.querySelectorAll('.topbar-kbd'), function (hint) {
|
||||
hint.textContent = isMac ? '\u2318K' : 'Ctrl K';
|
||||
});
|
||||
|
||||
})();
|
||||
Reference in new issue
Block a user