import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
import { useNavigate } from 'react-router';
import { Search } from 'lucide-react';
import { rank } from './match';
import { useSpotlightItems, type SpotlightItem } from './useSpotlightItems';
import { useTranslation } from '@/lib/i18n';
// Spotlight: type a few letters, go somewhere.
//
// The dock is full and cannot grow, which is what this is for — once navigation lives here, the dock is
// free to be a short list of what you actually use rather than a complete one.
//
// ── Keyboard first, and the trigger ──
//
// `shift-space`, and ONLY that. Fifth setting: ctrl-space → shift-space → alt-space → ctrl-space →
// shift-space. Every move was the owner naming a collision, and by now the list is the useful part:
//
// ctrl-space Brave takes it for the address bar, at the browser level. Tried twice, on the theory that
// preventDefault would win. It does not — the key never reaches this handler.
// alt-space the GNOME window menu. He rebound the desktop to keep it, disliked the replacement, and
// would rather move the app than the window manager.
// shift-space where it lands, with BOTH of its stock behaviours deliberately overridden.
//
// ── Shift-space overrides two things, on purpose ──
//
// It types a space in a text field, and it scrolls a page UP when nothing has focus. The owner's judgement,
// and it is his to make: neither is worth a launcher. Page-up-by-shift-space is a fossil nobody reaches for,
// and typing a space is what the unmodified spacebar is for.
//
// The cost, stated once because it is the one that will bite: typing in CAPS by holding shift rather than
// using caps lock puts a shift-space between every word. That opens the launcher mid-sentence. If it turns
// out to be a nuisance, the fix is a guard for text fields only — which this had for a day, and which is
// what made the launcher unopenable from the composer, where it is most wanted.
//
// This is also why the ctrl+? registry names the file that implements each chord: five moves in three days
// is the argument for making them configurable, not for choosing better.
//
// **Shift-space was never a good choice**, and that is why it did not last a day. It is a real key
// combination inside a text field: it types a space, and people hold shift through one more often than
// they think while typing capitals. Guarding it meant IGNORING the trigger whenever focus was in an input
// — which is where focus usually is, the chat composer — so opening Spotlight meant clicking out first.
// A launcher you have to prepare for is not a launcher.
//
// There is NO focus check, and here that is a choice with a cost rather than a free one — see above. The guard shift-space
// needed was kept for one commit as "belt-and-braces" and was simply the old bug wearing a new hat: focus
// is usually in the chat composer, so a launcher that stands down there is a launcher that does not open
// when you want it. `preventDefault` on the handler covers the only real risk the guard addressed.
//
// Nothing else opens it. There is deliberately no second chord — two triggers for one thing means two
// things to collide with, and this one moved twice already.
//
// Escape closes, arrows move, enter goes. The mouse works, but nothing here is designed around it.
//
// ── Sizing ──
//
// Loosened 2026-08-22: the first pass reused the app's list metrics (7px tile, text-sm, py-2) and read as
// cramped, because this is not a list inside a panel — it is a modal you look at for two seconds with
// nothing else competing for the eye. So the search input leads at `text-base`, rows are `py-2.5` with a
// 9px tile, and the label is `text-[15px]` with the hint and path kept deliberately subordinate.
//
// The panel widened with them (560 → 640). Rows now carry a label, a hint and a route on one line, and the
// route is the first thing to be squeezed out — it is also the thing that disambiguates two rows with the
// same name.
//
// The results box grew 52vh → 60vh for the arithmetic reason: taller rows in the same box show fewer
// results, and the cap on how many are listed was removed for a reason.
/*
No cap, deliberately, and it used to be 8.
Eight was fine on the machine it was written on, which has few plugins. On a populated server the dock
carries fourteen plugin tiles and the core items alone fill all eight slots — so with an empty query the
list stopped at Browser and every plugin was unreachable unless you already knew its name well enough to
type it. A launcher you can only use for things you can already name is not doing the job.
The container has scrolled since it was written (`max-h-[52vh] overflow-y-auto`), so there was never a
layout reason for the limit, and the truncation was silent — nothing said "and 20 more", which is how a
cap becomes indistinguishable from a missing feature.
*/
/** Label with the matched characters picked out, so it is obvious WHY a result is here. */
const Highlighted = ({ label, hits }: { label: string; hits: number[] }) => {
if (!hits.length) return <>{label}>;
const set = new Set(hits);
return (
<>
{label.split('').map((char, i) =>
set.has(i) ? (
{char}
) : (
{char}
),
)}
>
);
};
const Row = ({
item,
hits,
active,
onPick,
}: {
item: SpotlightItem;
hits: number[];
active: boolean;
onPick: () => void;
}) => {
const Icon = item.icon;
// Keyboard navigation has to survive a list taller than the box. `block: 'nearest'` scrolls only when the
// row is actually out of sight, so arrowing through the visible middle of the list does not jump it.
const ref = useRef(null);
useEffect(() => {
if (active) ref.current?.scrollIntoView({ block: 'nearest' });
}, [active]);
return (
);
};
export const Spotlight = () => {
const [open, setOpen] = useState(false);
const [query, setQuery] = useState('');
const [active, setActive] = useState(0);
const inputRef = useRef(null);
const navigate = useNavigate();
const items = useSpotlightItems();
const { t } = useTranslation();
const results = useMemo(() => rank(items, query), [items, query]);
/*
The window handler reads these through refs.
It has to: the listener is registered once per open, and closing over `results` and `active` would pin
it to their values at registration — so arrowing down would read a stale list and Enter would open
whatever was first when the panel appeared. Adding them to the effect's deps instead would tear down and
re-register the listener on every keystroke, which is the same bug wearing a costume.
*/
const resultsRef = useRef(results);
resultsRef.current = results;
const activeRef = useRef(active);
activeRef.current = active;
const close = useCallback(() => {
setOpen(false);
setQuery('');
setActive(0);
}, []);
const pick = useCallback(
(item: SpotlightItem | undefined) => {
if (!item) return;
close();
navigate(item.to);
},
[close, navigate],
);
// The trigger. Bound to the window rather than to a container, because it has to work while focus is
// anywhere — including inside a panel that has its own key handling.
useEffect(() => {
const onKey = (ev: KeyboardEvent) => {
// `code`, not `key`: shift+space reports `key: ' '` on most layouts and something else on a few, while
// the physical key is `Space` everywhere.
//
// Every other modifier must be ABSENT. `ctrl+shift+space` is the theme browser, and one chord opening
// both is the bug that took a capture-phase listener to fix on the theme side.
//
// No focus check. There was one, inherited from shift-space where it was mandatory, and keeping it
// "as belt-and-braces" was wrong in the plainest way: focus is usually IN the chat composer, so the
// guard meant the launcher did not open from the place it is most often wanted. `preventDefault`
// below covers the only thing the guard was protecting against — a layout that would otherwise type
// a character.
if (ev.shiftKey && !ev.ctrlKey && !ev.altKey && !ev.metaKey && ev.code === 'Space') {
ev.preventDefault();
// Take focus off whatever had it, explicitly, before the overlay mounts. The effect below focuses
// this panel's own input, and on paper that is enough — but "on paper" is what produced arrow keys
// that sometimes did nothing: focus stayed in the composer, so ArrowDown went to the textarea and
// the launcher never saw it. Blurring the outgoing element is one line and removes the race rather
// than narrowing it.
(document.activeElement as HTMLElement | null)?.blur?.();
setOpen((wasOpen) => !wasOpen);
return;
}
if (!open) return;
if (ev.key === 'Escape') {
close();
return;
}
// Navigation is handled HERE rather than on the input, so it works no matter what has focus — a
// panel that grabbed it back, a blur that lost the race, an element with its own key handling. The
// input's own onKeyDown used to own this, which made every keystroke conditional on focus having
// landed where we expected.
if (ev.key === 'ArrowDown') {
ev.preventDefault();
setActive((i) => Math.min(i + 1, resultsRef.current.length - 1));
} else if (ev.key === 'ArrowUp') {
ev.preventDefault();
setActive((i) => Math.max(i - 1, 0));
} else if (ev.key === 'Enter') {
ev.preventDefault();
pick(resultsRef.current[activeRef.current]?.item);
}
};
window.addEventListener('keydown', onKey);
return () => window.removeEventListener('keydown', onKey);
}, [open, close, pick]);
useEffect(() => {
if (open) inputRef.current?.focus();
}, [open]);
// Reset the cursor whenever the result set changes, so it never points past the end.
useEffect(() => setActive(0), [query]);
if (!open) return null;
return (