Finding anything meant knowing which tab it lived in — fine once you have learned the panel, hopeless before. ⌘K now covers cards, repositories, issues, wiki pages and members at once. Pages are matched in the browser, so the palette answers before it has asked the server and stays useful while the forge is down. Each remote source is queried independently and a source that fails is simply absent from the results, rather than taking the others with it. Issues come from one organization-wide request: per repository, the palette could not afford them on every keystroke. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
252 lines
8.0 KiB
JavaScript
252 lines
8.0 KiB
JavaScript
import { api } from './api.js';
|
||
import { h, mount } from './dom.js';
|
||
|
||
/**
|
||
* Command palette: one search across everything (M19).
|
||
*
|
||
* Before this, finding something meant knowing which tab it lived in. Pages are
|
||
* matched in the browser so the palette is useful the instant it opens, even
|
||
* with the forge down; everything else comes from `/api/search`.
|
||
*/
|
||
|
||
const DEBOUNCE_MS = 180;
|
||
const MIN_REMOTE = 2;
|
||
|
||
const GROUPS = [
|
||
{ kind: 'page', label: 'Pages', icon: '◈' },
|
||
{ kind: 'card', label: 'Cartes', icon: '▦' },
|
||
{ kind: 'repository', label: 'Dépôts', icon: '◫' },
|
||
{ kind: 'issue', label: 'Issues', icon: '◇' },
|
||
{ kind: 'pull', label: 'Pull requests', icon: '⑂' },
|
||
{ kind: 'wiki', label: 'Wiki', icon: '📖' },
|
||
{ kind: 'member', label: 'Membres', icon: '☺' },
|
||
];
|
||
|
||
const ICONS = Object.fromEntries(GROUPS.map((group) => [group.kind, group.icon]));
|
||
const RANK = Object.fromEntries(GROUPS.map((group, index) => [group.kind, index]));
|
||
|
||
/**
|
||
* Sorts the results into their groups, keeping the order inside each one.
|
||
*
|
||
* The forge returns issues and pull requests interleaved, which would print a
|
||
* heading above almost every line.
|
||
*/
|
||
export const grouped = (results) =>
|
||
results
|
||
.map((result, index) => ({ result, index }))
|
||
.sort((a, b) => (RANK[a.result.kind] ?? 99) - (RANK[b.result.kind] ?? 99) || a.index - b.index)
|
||
.map((entry) => entry.result);
|
||
|
||
let open = false;
|
||
|
||
const matches = (text, needle) =>
|
||
String(text ?? '')
|
||
.toLowerCase()
|
||
.includes(needle);
|
||
|
||
/** Pages the visitor may actually reach, matched locally on label and group. */
|
||
export function localPages(pages, needle) {
|
||
return pages
|
||
.filter((page) => needle === '' || matches(page.label, needle) || matches(page.group, needle))
|
||
.slice(0, 8)
|
||
.map((page) => ({
|
||
kind: 'page',
|
||
title: page.label,
|
||
subtitle: page.group,
|
||
href: `#/${page.path}`,
|
||
}));
|
||
}
|
||
|
||
function go(result) {
|
||
if (result.external) window.open(result.href, '_blank', 'noreferrer');
|
||
else window.location.hash = result.href.replace(/^#/, '');
|
||
}
|
||
|
||
/**
|
||
* Opens the palette. `pages` is the navigation the visitor can see, so a page
|
||
* they have no access to never shows up as a result.
|
||
*/
|
||
export function openPalette(pages = []) {
|
||
if (open) return;
|
||
open = true;
|
||
|
||
const restoreFocus = document.activeElement;
|
||
const overlay = h('div', { class: 'overlay palette-overlay' });
|
||
const list = h('div', { class: 'palette-list', role: 'listbox', id: 'palette-results' });
|
||
const hint = h('div', { class: 'palette-hint' });
|
||
|
||
const field = h('input', {
|
||
class: 'palette-input',
|
||
type: 'search',
|
||
placeholder: 'Rechercher une page, un dépôt, une carte, une issue…',
|
||
'aria-label': 'Recherche globale',
|
||
'aria-controls': 'palette-results',
|
||
autocomplete: 'off',
|
||
spellcheck: 'false',
|
||
});
|
||
|
||
let results = [];
|
||
let cursor = 0;
|
||
let timer = null;
|
||
/** Answers can arrive out of order; only the latest query may draw. */
|
||
let sequence = 0;
|
||
|
||
const close = () => {
|
||
open = false;
|
||
clearTimeout(timer);
|
||
document.removeEventListener('keydown', onKey, true);
|
||
overlay.remove();
|
||
restoreFocus?.focus?.();
|
||
};
|
||
|
||
const draw = () => {
|
||
if (results.length === 0) {
|
||
mount(list, h('p', { class: 'palette-empty', text: 'Aucun résultat.' }));
|
||
return;
|
||
}
|
||
cursor = Math.max(0, Math.min(cursor, results.length - 1));
|
||
|
||
const nodes = [];
|
||
let group = null;
|
||
|
||
for (const [index, result] of results.entries()) {
|
||
if (result.kind !== group) {
|
||
group = result.kind;
|
||
const label = GROUPS.find((entry) => entry.kind === group)?.label ?? group;
|
||
nodes.push(h('div', { class: 'palette-group', text: label }));
|
||
}
|
||
|
||
nodes.push(
|
||
h(
|
||
'button',
|
||
{
|
||
class: index === cursor ? 'palette-item active' : 'palette-item',
|
||
type: 'button',
|
||
role: 'option',
|
||
'aria-selected': index === cursor ? 'true' : 'false',
|
||
// `mousedown` rather than `click`: the input keeps focus, so the
|
||
// palette does not close under the pointer before the choice lands.
|
||
onMousedown: (event) => {
|
||
event.preventDefault();
|
||
close();
|
||
go(result);
|
||
},
|
||
// Guarded: a redraw replaces the node under the pointer, which
|
||
// fires `mouseenter` again — without this the two loop forever.
|
||
onMouseenter: () => {
|
||
if (cursor === index) return;
|
||
cursor = index;
|
||
draw();
|
||
},
|
||
},
|
||
h('span', { class: 'palette-icon', text: ICONS[result.kind] ?? '·' }),
|
||
h(
|
||
'span',
|
||
{ class: 'palette-text' },
|
||
h('strong', { text: result.title }),
|
||
result.subtitle && h('span', { class: 'muted', text: result.subtitle }),
|
||
),
|
||
result.badge && h('span', { class: 'palette-badge', text: result.badge }),
|
||
result.external && h('span', { class: 'palette-external', text: '↗', title: 'Ouvre un onglet' }),
|
||
),
|
||
);
|
||
}
|
||
|
||
mount(list, nodes);
|
||
list.querySelector('.palette-item.active')?.scrollIntoView({ block: 'nearest' });
|
||
};
|
||
|
||
const search = async (term) => {
|
||
const needle = term.trim().toLowerCase();
|
||
const local = localPages(pages, needle);
|
||
|
||
results = grouped(local);
|
||
cursor = 0;
|
||
hint.textContent = needle.length < MIN_REMOTE ? 'Tape au moins 2 caractères pour chercher partout.' : '';
|
||
draw();
|
||
if (needle.length < MIN_REMOTE) return;
|
||
|
||
const mine = ++sequence;
|
||
const remote = await api.get('/api/search', { q: term.trim() }).catch(() => null);
|
||
if (mine !== sequence || !open) return;
|
||
|
||
if (!remote) {
|
||
hint.textContent = 'La recherche étendue n’a pas répondu ; seules les pages sont listées.';
|
||
return;
|
||
}
|
||
|
||
hint.textContent = '';
|
||
// Pages stay first: they are the fastest thing the palette can do.
|
||
results = grouped([...local, ...remote.results]);
|
||
draw();
|
||
};
|
||
|
||
const onKey = (event) => {
|
||
if (event.key === 'Escape') {
|
||
event.preventDefault();
|
||
close();
|
||
} else if (event.key === 'ArrowDown' || (event.key === 'Tab' && !event.shiftKey)) {
|
||
event.preventDefault();
|
||
cursor = results.length === 0 ? 0 : (cursor + 1) % results.length;
|
||
draw();
|
||
} else if (event.key === 'ArrowUp' || (event.key === 'Tab' && event.shiftKey)) {
|
||
event.preventDefault();
|
||
cursor = results.length === 0 ? 0 : (cursor - 1 + results.length) % results.length;
|
||
draw();
|
||
} else if (event.key === 'Enter' && results[cursor]) {
|
||
event.preventDefault();
|
||
const chosen = results[cursor];
|
||
close();
|
||
go(chosen);
|
||
}
|
||
};
|
||
|
||
field.addEventListener('input', () => {
|
||
clearTimeout(timer);
|
||
timer = setTimeout(() => search(field.value), DEBOUNCE_MS);
|
||
});
|
||
overlay.addEventListener('click', (event) => {
|
||
if (event.target === overlay) close();
|
||
});
|
||
document.addEventListener('keydown', onKey, true);
|
||
|
||
overlay.append(
|
||
h(
|
||
'div',
|
||
{ class: 'palette', role: 'dialog', 'aria-modal': 'true', 'aria-label': 'Recherche globale' },
|
||
h('div', { class: 'palette-head' }, h('span', { class: 'palette-prompt', text: '⌕' }), field),
|
||
list,
|
||
h(
|
||
'footer',
|
||
{ class: 'palette-foot' },
|
||
hint,
|
||
h('span', { class: 'muted', text: '↑ ↓ pour naviguer · ↵ pour ouvrir · Échap pour fermer' }),
|
||
),
|
||
),
|
||
);
|
||
|
||
document.body.append(overlay);
|
||
field.focus();
|
||
search('');
|
||
}
|
||
|
||
/**
|
||
* Binds ⌘K / Ctrl+K globally.
|
||
*
|
||
* `/` opens it too, but only when nothing is being typed into: stealing a
|
||
* slash from someone writing a release note would be unforgivable.
|
||
*/
|
||
export function bindPalette(pages) {
|
||
const typing = () =>
|
||
['INPUT', 'TEXTAREA', 'SELECT'].includes(document.activeElement?.tagName) ||
|
||
document.activeElement?.isContentEditable;
|
||
|
||
document.addEventListener('keydown', (event) => {
|
||
const combo = (event.metaKey || event.ctrlKey) && event.key.toLowerCase() === 'k';
|
||
if (!combo && !(event.key === '/' && !typing())) return;
|
||
|
||
event.preventDefault();
|
||
openPalette(pages());
|
||
});
|
||
}
|