feat(web): search the whole panel from one place

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>
This commit is contained in:
nocodeandClaude Opus 5 committed 2026-09-24 18:46:04 +02:00
1 parent fcc82d82d6
commit 9acb523510
10 files changed
+926 -3

No files matched your search

@@ -327,3 +327,26 @@ export function listAssignees(guildId) {
)
.all(guildId);
}
/** Cards whose title, body, labels or issue matches, for the command palette (M19). */
export function searchCards(guildId, term, limit = 8) {
const needle = `%${term}%`;
return getDatabase()
.prepare(
`SELECT c.*,
b.name AS board_name,
b.scope AS board_scope,
b.repository,
col.name AS column_name,
col.is_done AS column_is_done
FROM project_cards c
JOIN project_boards b ON b.id = c.board_id
JOIN project_columns col ON col.id = c.column_id
WHERE b.guild_id = ?
AND (c.title LIKE ? OR c.body LIKE ? OR c.labels LIKE ? OR c.issue_ref LIKE ?)
ORDER BY col.is_done, c.due_at IS NULL, c.due_at, c.id DESC
LIMIT ?`,
)
.all(guildId, needle, needle, needle, needle, limit)
.map(parseAssignedCard);
}
+9
View File
@@ -40,6 +40,15 @@ export const org = {
giteaRequest(`/orgs/${encodeURIComponent(owner)}/hooks`).then(asList),
createRepo: (payload, owner = defaultOwner()) =>
giteaRequest(`/orgs/${encodeURIComponent(owner)}/repos`, { method: 'POST', body: payload }),
/**
* Issues and pull requests of the whole organization, in one request.
*
* The per-repository endpoint would mean one call per repository, which the
* command palette cannot afford on every keystroke. Absent before Gitea 1.15,
* so callers tolerate a rejection.
*/
searchIssues: ({ owner = defaultOwner(), q, state = 'open', type, limit = 10 } = {}) =>
giteaRequest(`/repos/issues/search${query({ q, owner, state, type, limit })}`).then(asList),
/** Identity behind `GITEA_TOKEN`, used by the settings page to check the credentials. */
whoami: () => giteaRequest('/user'),
};
+2
View File
@@ -12,6 +12,7 @@ import { registerOverviewRoutes } from './overview.js';
import { registerProjectRoutes } from './projects.js';
import { registerReleaseRoutes } from './releases.js';
import { registerRepositoryRoutes } from './repositories.js';
import { registerSearchRoutes } from './search.js';
import { registerSettingsRoutes } from './settings.js';
import { registerWikiRoutes } from './wiki.js';
@@ -60,6 +61,7 @@ export function registerApiRoutes(router, { setupOnly = false } = {}) {
registerDeploymentRoutes(router);
registerDiscordRoutes(router);
registerCommunityRoutes(router);
registerSearchRoutes(router);
registerSettingsRoutes(router);
registerLogRoutes(router);
return router;
+159
View File
@@ -0,0 +1,159 @@
import { ACCESS_LEVELS } from '../../config/constants.js';
import { env } from '../../config/env.js';
import { createLogger } from '../../core/logger.js';
import { searchCards } from '../../database/repositories/project-repository.js';
import { searchPublished } from '../../database/repositories/wiki-repository.js';
import { org } from '../../services/gitea/gitea-admin.js';
import { isGiteaConfigured } from '../../services/gitea/gitea-client.js';
import { pagePath } from '../services/wiki-seed.js';
/**
* One search across everything the dashboard knows (M19).
*
* Until now, finding something meant knowing which tab it lived in — which is
* fine once you have learned the panel and hopeless before. Each source is
* asked independently and a source that fails is simply left out: a forge that
* is down must not take the wiki and the boards with it.
*/
const log = createLogger('web:search');
const guildId = () => env.discord.guildId;
/** Below this a search matches half the organization, which helps nobody. */
const MIN_TERM = 2;
const PER_GROUP = 6;
/**
* Repository lists change by the hour and are asked for on every keystroke, so
* they are kept briefly. The stamp only moves on success, which turns a forge
* outage into slightly old results rather than none.
*/
const REPO_TTL_MS = 60_000;
let repoCache = { at: 0, repositories: [] };
async function repositories() {
if (!isGiteaConfigured()) return [];
if (Date.now() - repoCache.at < REPO_TTL_MS) return repoCache.repositories;
const list = await org.listRepos({ limit: 50 }).catch((error) => {
log.debug('Falling back to the cached repository list', error);
return null;
});
if (list) repoCache = { at: Date.now(), repositories: list };
return repoCache.repositories;
}
const contains = (haystack, needle) =>
String(haystack ?? '')
.toLowerCase()
.includes(needle);
async function searchRepositories(needle) {
const list = await repositories();
return list
.filter(
(repository) => contains(repository.full_name, needle) || contains(repository.description, needle),
)
.slice(0, PER_GROUP)
.map((repository) => ({
kind: 'repository',
title: repository.full_name,
subtitle: repository.description || 'Dépôt de l’organisation',
href: `#/repos/${repository.full_name}`,
badge: repository.private ? 'Privé' : null,
}));
}
async function searchIssues(needle) {
if (!isGiteaConfigured()) return [];
// `all` rather than `open`: someone searching for an issue by name usually
// wants the one they remember, closed or not.
const issues = await org.searchIssues({ q: needle, state: 'all', limit: PER_GROUP }).catch((error) => {
log.debug('The forge did not answer the issue search', error);
return [];
});
return issues.slice(0, PER_GROUP).map((issue) => ({
kind: issue.pull_request ? 'pull' : 'issue',
title: issue.title,
subtitle: `${issue.repository?.full_name ?? 'Gitea'}#${issue.number}`,
href: issue.html_url,
external: true,
badge: issue.state === 'closed' ? 'Fermée' : 'Ouverte',
}));
}
function searchBoardCards(needle) {
return searchCards(guildId(), needle, PER_GROUP).map((card) => ({
kind: 'card',
title: card.title,
subtitle: `${card.board_name} · ${card.column_name}`,
href: `#/projects/${card.board_id}`,
badge: card.column_is_done ? 'Terminée' : (card.issue_ref ?? null),
}));
}
function searchWiki(needle) {
return searchPublished(needle)
.slice(0, PER_GROUP)
.map((page) => ({
kind: 'wiki',
title: page.title,
subtitle: page.summary || page.category,
href: pagePath(page.slug),
external: true,
badge: page.category,
}));
}
/**
* Members come from the cache rather than a fetch: pulling the roster from
* Discord on every keystroke would be slow and rate-limited, and whoever is
* being looked for is almost always already cached.
*/
function searchMembers(client, needle) {
const guild = client?.guilds?.cache?.get(guildId());
if (!guild) return [];
return [...guild.members.cache.values()]
.filter(
(member) =>
contains(member.user.username, needle) ||
contains(member.displayName, needle) ||
member.id === needle,
)
.slice(0, PER_GROUP)
.map((member) => ({
kind: 'member',
title: member.displayName,
subtitle: `@${member.user.username}`,
href: `#/discord?member=${encodeURIComponent(member.user.username)}`,
badge: member.user.bot ? 'Bot' : null,
}));
}
export function registerSearchRoutes(router) {
router.get(
'/api/search',
async ({ query, context }) => {
const term = String(query.get('q') ?? '').trim();
if (term.length < MIN_TERM) return { term, results: [], truncated: false };
const needle = term.toLowerCase();
const [repos, issues] = await Promise.all([searchRepositories(needle), searchIssues(term)]);
// Local sources first: they are exact, instant, and what the panel owns.
const results = [
...searchBoardCards(term),
...repos,
...issues,
...searchWiki(term),
...searchMembers(context.client, needle),
];
return { term, results, truncated: results.length >= PER_GROUP * 5 };
},
{ access: ACCESS_LEVELS.STAFF },
);
}
+16
View File
@@ -2,6 +2,7 @@ import { api } from './core/api.js';
import { h, mount, qs } from './core/dom.js';
import { onStatus, resetSubscriptions, startLive } from './core/live.js';
import { activePath, highlight } from './core/nav.js';
import { bindPalette, openPalette } from './core/palette.js';
import { ACCESS_LABELS, button, spinner, toast } from './core/ui.js';
/** Shell, navigation and hash routing of the dashboard (M16-T11). */
@@ -208,6 +209,8 @@ function visibleRoutes() {
);
}
const SHORTCUT = navigator.userAgent.includes('Mac') ? '⌘K' : 'Ctrl+K';
function sidebar() {
const visible = visibleRoutes();
@@ -227,6 +230,18 @@ function sidebar() {
h('img', { src: 'favicon.svg', alt: '' }),
h('div', {}, h('strong', { text: 'FWS-Bot' }), h('span', { text: 'Tableau de bord' })),
),
h(
'button',
{
class: 'nav-search',
type: 'button',
onClick: () => openPalette(visibleRoutes()),
title: `Recherche globale (${SHORTCUT})`,
},
h('span', { class: 'nav-icon', text: '⌕' }),
h('span', { text: 'Rechercher' }),
h('kbd', { text: SHORTCUT }),
),
h(
'nav',
{ class: 'nav' },
@@ -413,6 +428,7 @@ async function boot() {
startLive();
showBuild();
bindPalette(visibleRoutes);
window.addEventListener('hashchange', () => {
const main = qs('.main');
+251
View File
@@ -0,0 +1,251 @@
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());
});
}
+155
View File
@@ -1182,6 +1182,157 @@ body[data-mode='simple'] .advanced-only {
/* Anchored near the top rather than centred: the list grows downwards, and a
dialog that re-centres itself on every keystroke is unusable. */
/* --- Command palette ------------------------------------------------------ */
.nav-search {
display: flex;
align-items: center;
gap: 0.6rem;
width: 100%;
font: inherit;
font-size: 0.88rem;
text-align: left;
color: var(--text-muted);
background: var(--bg-sunken);
border: 1px solid var(--border);
border-radius: var(--radius-sm);
padding: 0.45rem 0.65rem;
margin-bottom: 0.4rem;
cursor: pointer;
}
.nav-search:hover {
border-color: var(--blue);
color: var(--text);
}
.nav-search kbd {
margin-left: auto;
font-family: var(--mono);
font-size: 0.7rem;
background: var(--surface);
border: 1px solid var(--border);
border-radius: 4px;
padding: 0.05rem 0.3rem;
}
.palette-overlay {
align-items: start;
padding-top: min(14vh, 8rem);
}
.palette {
background: var(--bg-elevated);
border: 1px solid var(--border);
border-radius: var(--radius);
box-shadow: var(--shadow);
width: min(640px, 100%);
max-height: 70vh;
display: flex;
flex-direction: column;
overflow: hidden;
}
.palette-head {
display: flex;
align-items: center;
gap: 0.6rem;
padding: 0.7rem 0.9rem;
border-bottom: 1px solid var(--border);
}
.palette-prompt {
color: var(--blue);
font-size: 1.1rem;
}
.palette-input {
flex: 1;
font: inherit;
font-size: 1rem;
background: none;
border: none;
color: var(--text);
outline: none;
}
.palette-input::-webkit-search-cancel-button {
display: none;
}
.palette-list {
overflow-y: auto;
padding: 0.35rem;
}
.palette-group {
padding: 0.55rem 0.6rem 0.25rem;
font-size: 0.68rem;
letter-spacing: 0.09em;
text-transform: uppercase;
color: var(--text-muted);
}
.palette-item {
display: flex;
align-items: center;
gap: 0.7rem;
width: 100%;
font: inherit;
text-align: left;
background: none;
border: none;
border-radius: var(--radius-sm);
color: var(--text);
padding: 0.45rem 0.6rem;
cursor: pointer;
}
.palette-item.active {
background: color-mix(in srgb, var(--blue) 16%, transparent);
}
.palette-icon {
width: 1.3rem;
text-align: center;
color: var(--text-muted);
}
.palette-text {
display: flex;
flex-direction: column;
min-width: 0;
}
.palette-text strong {
font-weight: 600;
font-size: 0.92rem;
}
.palette-text span,
.palette-text strong {
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.palette-badge {
margin-left: auto;
flex: none;
font-size: 0.7rem;
color: var(--text-muted);
background: var(--bg-sunken);
border-radius: 999px;
padding: 0.05rem 0.45rem;
}
.palette-external {
flex: none;
color: var(--text-muted);
font-size: 0.8rem;
}
.palette-empty {
padding: 1.2rem 0.6rem;
text-align: center;
color: var(--text-muted);
}
.palette-foot {
display: flex;
justify-content: space-between;
gap: 1rem;
align-items: center;
padding: 0.5rem 0.9rem;
border-top: 1px solid var(--border);
font-size: 0.76rem;
color: var(--text-muted);
}
.palette-hint {
min-width: 0;
}
@media (max-width: 900px) {
.shell {
grid-template-columns: 1fr;
@@ -1202,4 +1353,8 @@ body[data-mode='simple'] .advanced-only {
flex-direction: row;
overflow-x: auto;
}
.palette-overlay {
padding-top: 6vh;
}
}
+12 -3
View File
@@ -164,9 +164,15 @@ async function announce(channels) {
toast(`Annonce publiée (${result.messageId}).`);
}
function membersCard(guild, level) {
function membersCard(guild, level, initialSearch = '') {
const host = h('div', { class: 'stack' });
const search = input({ type: 'search', placeholder: 'Nom, pseudo ou identifiant…' });
// Pre-filled when the command palette sent us here for one member, so the
// link lands on that person rather than on the top of the roster.
const search = input({
type: 'search',
placeholder: 'Nom, pseudo ou identifiant…',
value: initialSearch,
});
const load = () =>
renderAsync(
@@ -305,6 +311,9 @@ function notificationsCard(guild, level) {
);
}
/** `#/discord?member=nom` — where the command palette points a member result. */
const memberQuery = () => new URLSearchParams(window.location.hash.split('?')[1] ?? '').get('member') ?? '';
export async function render(host, { state }) {
const level = state.me.accessLevel;
mount(host, spinner());
@@ -356,7 +365,7 @@ export async function render(host, { state }) {
),
),
membersCard(guild, level),
membersCard(guild, level, memberQuery()),
card(
'Rôles',
+100
View File
@@ -0,0 +1,100 @@
import assert from 'node:assert/strict';
import { describe, it } from 'node:test';
import { grouped, localPages } from '../src/web/public/core/palette.js';
/**
* Command palette, the parts that hold no DOM (M19).
*
* Both are small and both are the kind of thing that degrades quietly: a
* heading above every line, or a page offered to someone who cannot open it.
*/
const result = (kind, title) => ({ kind, title });
describe('grouping the results', () => {
/** The forge returns issues and pull requests interleaved. */
it('gathers each kind, however they arrive', () => {
const order = grouped([
result('issue', 'i1'),
result('pull', 'p1'),
result('issue', 'i2'),
result('pull', 'p2'),
]).map((entry) => entry.kind);
assert.deepEqual(order, ['issue', 'issue', 'pull', 'pull']);
});
it('keeps the order the server chose inside a group', () => {
const titles = grouped([
result('card', 'première'),
result('page', 'une page'),
result('card', 'seconde'),
])
.filter((entry) => entry.kind === 'card')
.map((entry) => entry.title);
assert.deepEqual(titles, ['première', 'seconde']);
});
it('puts the pages first and the members last', () => {
const order = grouped([
result('member', 'quelqu’un'),
result('repository', 'FWS/x'),
result('page', 'Dépôts'),
]).map((entry) => entry.kind);
assert.deepEqual(order, ['page', 'repository', 'member']);
});
it('sends an unknown kind to the end rather than dropping it', () => {
const order = grouped([result('inconnu', '?'), result('page', 'Dépôts')]).map((entry) => entry.kind);
assert.deepEqual(order, ['page', 'inconnu']);
});
it('survives an empty answer', () => {
assert.deepEqual(grouped([]), []);
});
});
describe('matching the pages locally', () => {
const pages = [
{ path: '', label: 'Vue d’ensemble', group: 'Pilotage' },
{ path: 'tasks', label: 'Mes tâches', group: 'Pilotage' },
{ path: 'repos', label: 'Dépôts', group: 'Code' },
{ path: 'settings', label: 'Paramètres', group: 'Système' },
];
it('lists everything when nothing is typed', () => {
assert.equal(localPages(pages, '').length, pages.length);
});
it('matches on the label', () => {
assert.deepEqual(
localPages(pages, 'tâche').map((entry) => entry.title),
['Mes tâches'],
);
});
/** Typing the section is how people who know the panel navigate it. */
it('matches on the group', () => {
assert.deepEqual(
localPages(pages, 'pilotage').map((entry) => entry.title),
['Vue d’ensemble', 'Mes tâches'],
);
});
it('points at the hash route of each page', () => {
const [overview] = localPages(pages, 'ensemble');
assert.equal(overview.href, '#/');
assert.equal(localPages(pages, 'dépôt')[0].href, '#/repos');
});
/**
* The caller passes only the pages the visitor can see, so a page missing
* from that list must never surface — the palette does no filtering of its own.
*/
it('offers nothing beyond the list it was given', () => {
const visible = pages.filter((page) => page.path !== 'settings');
assert.deepEqual(localPages(visible, 'paramètres'), []);
});
});
+199
View File
@@ -0,0 +1,199 @@
import assert from 'node:assert/strict';
import { createServer } from 'node:http';
import { after, before, beforeEach, describe, it } from 'node:test';
import { ACCESS_LEVELS } from '../src/config/constants.js';
import { closeDatabase, getDatabase, initDatabase } from '../src/database/index.js';
import {
addCard,
createBoard,
listColumns,
searchCards,
} from '../src/database/repositories/project-repository.js';
import { createApiToken } from '../src/database/repositories/web-session-repository.js';
import { createPage } from '../src/database/repositories/wiki-repository.js';
import { hashToken } from '../src/web/auth/session.js';
import { createHandler } from '../src/web/server.js';
/**
* Global search behind the command palette (M19).
*
* Gitea is deliberately left unconfigured here: the point is that the local
* sources answer on their own, so a forge that is down costs the palette its
* repositories and nothing else.
*/
const GUILD = '';
const TOKEN = 'fws_search-test';
describe('global search', () => {
let app;
let board;
let columns;
before(async () => {
initDatabase(':memory:');
createApiToken({
name: 'recherche',
tokenHash: hashToken(TOKEN),
prefix: TOKEN.slice(0, 12),
accessLevel: ACCESS_LEVELS.STAFF,
});
app = createServer(createHandler({ client: null, setupOnly: false }));
await new Promise((resolve) => app.listen(0, '127.0.0.1', resolve));
});
after(async () => {
await new Promise((resolve) => app.close(resolve));
closeDatabase();
});
beforeEach(() => {
getDatabase().exec('DELETE FROM project_boards; DELETE FROM wiki_pages;');
board = createBoard({ guildId: GUILD, scope: 'org', name: 'Organisation' });
columns = listColumns(board.id);
});
const search = (term) =>
fetch(`http://127.0.0.1:${app.address().port}/api/search?q=${encodeURIComponent(term)}`, {
headers: { Authorization: `Bearer ${TOKEN}` },
});
const results = (term) => search(term).then((response) => response.json());
const card = (title, overrides = {}) =>
addCard({ boardId: board.id, columnId: columns[0].id, title, ...overrides });
const page = (title, overrides = {}) =>
createPage({
slug: title.toLowerCase().replaceAll(' ', '-'),
title,
published: true,
category: 'Guides',
...overrides,
});
it('refuses a visitor without a session', async () => {
const response = await fetch(`http://127.0.0.1:${app.address().port}/api/search?q=test`);
assert.equal(response.status, 401);
});
/** One or two letters match half the organization, which helps nobody. */
it('stays silent on a term too short to mean anything', async () => {
card('Pterodactyl');
assert.deepEqual((await results('p')).results, []);
});
it('finds a card and says which board it is on', async () => {
card('Corriger le démarrage');
const [found] = (await results('démarrage')).results;
assert.equal(found.kind, 'card');
assert.equal(found.title, 'Corriger le démarrage');
assert.equal(found.subtitle, 'Organisation · À faire');
assert.equal(found.href, `#/projects/${board.id}`);
});
it('finds a published wiki page at its public address', async () => {
page('Installer FWS Arch', { summary: 'Le guide pas à pas.' });
const [found] = (await results('Installer')).results;
assert.equal(found.kind, 'wiki');
assert.equal(found.href, '/wiki/installer-fws-arch');
assert.equal(found.external, true);
});
it('leaves an unpublished page out of the results', async () => {
page('Brouillon interne', { published: false });
assert.deepEqual((await results('Brouillon')).results, []);
});
/** The legal pages live at the root, not under /wiki. */
it('sends a root page to its own address', async () => {
page('Conditions', { slug: 'terms-of-service' });
const [found] = (await results('Conditions')).results;
assert.equal(found.href, '/terms-of-service');
});
it('gathers several kinds under one answer', async () => {
card('Sauvegarde automatique');
page('Sauvegarde et restauration');
const kinds = (await results('Sauvegarde')).results.map((entry) => entry.kind);
assert.deepEqual(kinds.slice().sort(), ['card', 'wiki']);
});
it('puts the local results first', async () => {
card('Wiki à relire');
page('Wiki public');
assert.equal((await results('Wiki')).results[0].kind, 'card');
});
it('answers with nothing rather than failing when nothing matches', async () => {
const body = await results('introuvable-xyz');
assert.deepEqual(body.results, []);
assert.equal(body.term, 'introuvable-xyz');
});
/** Gitea is not configured here; the palette must still answer. */
it('answers although the forge is absent', async () => {
card('Déploiement');
const response = await search('Déploiement');
assert.equal(response.status, 200);
assert.equal((await response.json()).results.length, 1);
});
});
/** The query behind the palette's card results, exercised without HTTP. */
describe('searching the cards directly', () => {
let board;
let columns;
before(() => initDatabase(':memory:'));
after(() => closeDatabase());
beforeEach(() => {
getDatabase().exec('DELETE FROM project_boards;');
board = createBoard({ guildId: GUILD, scope: 'org', name: 'Organisation' });
columns = listColumns(board.id);
});
const put = (title, overrides = {}) =>
addCard({ boardId: board.id, columnId: columns[0].id, title, ...overrides });
it('matches the title', () => {
put('Corriger le démarrage');
put('Documenter le wiki');
assert.deepEqual(
searchCards(GUILD, 'démarrage').map((entry) => entry.title),
['Corriger le démarrage'],
);
});
it('matches the body, the labels and the issue', () => {
put('Sans rapport', { body: 'contient pterodactyl' });
put('Étiquetée', { labels: ['urgent'] });
put('Liée', { issueRef: 'FWS/FWS-Arch#42' });
assert.equal(searchCards(GUILD, 'pterodactyl').length, 1);
assert.equal(searchCards(GUILD, 'urgent').length, 1);
assert.equal(searchCards(GUILD, '#42').length, 1);
});
/** A finished card is still a result, just never the first one. */
it('puts the finished cards last', () => {
addCard({ boardId: board.id, columnId: columns.at(-1).id, title: 'sujet fini' });
put('sujet en cours');
assert.deepEqual(
searchCards(GUILD, 'sujet').map((entry) => entry.title),
['sujet en cours', 'sujet fini'],
);
});
it('honours the limit', () => {
for (let index = 0; index < 5; index += 1) put(`sujet ${index}`);
assert.equal(searchCards(GUILD, 'sujet', 2).length, 2);
});
});