Archived
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01Ls1vMdg2GYqbnKZmPaX1ot
151 lines
8.0 KiB
TypeScript
151 lines
8.0 KiB
TypeScript
"use client";
|
|
|
|
import React, { useCallback, useEffect, useMemo, useRef, useState } from "react";
|
|
import { useRouter } from "next/navigation";
|
|
import { Search, Calendar, User, Banknote, ClipboardList, CornerDownLeft, Zap, FileText, Settings, BarChart2 } from "lucide-react";
|
|
import { useAuth } from "@/hooks/useAuth";
|
|
import { matchPages, type CommandPage } from "@/lib/commandPages";
|
|
import { apiV2Data } from "@/lib/apiV2";
|
|
|
|
type Result = { type: "event" | "payment" | "person" | "registration"; id: string; title: string; subtitle: string; href: string };
|
|
type Item = { key: string; group: string; title: string; subtitle?: string; href: string; icon: React.ElementType };
|
|
|
|
const RESULT_GROUP: Record<Result["type"], [string, React.ElementType]> = {
|
|
event: ["Events", Calendar], payment: ["Payments", Banknote], person: ["People", User], registration: ["Registrations", ClipboardList],
|
|
};
|
|
const PAGE_ICON: Record<CommandPage["group"], React.ElementType> = { Actions: Zap, Pages: FileText, Settings, Reports: BarChart2 };
|
|
|
|
/** Opens with Ctrl+K / ⌘K (or the event below) for staff, supervisors and admins. */
|
|
export const OPEN_PALETTE_EVENT = "cross-events:open-palette";
|
|
|
|
/**
|
|
* Ctrl+K command palette (1.49.0): jump to a page, setting or report, start an action ("New
|
|
* event"), or find an event, a payment by amount ("R450"), a person or a registration — what the
|
|
* person may see. ↑/↓ to move, Enter to open, Esc to close.
|
|
*/
|
|
export function CommandPalette() {
|
|
const { user, token } = useAuth();
|
|
const router = useRouter();
|
|
const role = user?.role || "user";
|
|
const allowed = role === "staff" || role === "supervisor" || role === "admin";
|
|
const [open, setOpen] = useState(false);
|
|
const [query, setQuery] = useState("");
|
|
const [results, setResults] = useState<Result[]>([]);
|
|
const [active, setActive] = useState(0);
|
|
const inputRef = useRef<HTMLInputElement>(null);
|
|
const listRef = useRef<HTMLUListElement>(null);
|
|
|
|
useEffect(() => {
|
|
if (!allowed) return;
|
|
const onKey = (e: KeyboardEvent) => {
|
|
if ((e.ctrlKey || e.metaKey) && e.key.toLowerCase() === "k") {
|
|
e.preventDefault();
|
|
setOpen(o => !o);
|
|
}
|
|
};
|
|
const onOpen = () => setOpen(true);
|
|
window.addEventListener("keydown", onKey);
|
|
window.addEventListener(OPEN_PALETTE_EVENT, onOpen);
|
|
return () => { window.removeEventListener("keydown", onKey); window.removeEventListener(OPEN_PALETTE_EVENT, onOpen); };
|
|
}, [allowed]);
|
|
|
|
useEffect(() => {
|
|
if (open) { setQuery(""); setResults([]); setActive(0); setTimeout(() => inputRef.current?.focus(), 0); }
|
|
}, [open]);
|
|
|
|
// Search as they type (after a short pause); pages are matched here, instantly.
|
|
useEffect(() => {
|
|
if (!open || !token) return;
|
|
const q = query.trim();
|
|
if (q.length < 2) { setResults([]); return; }
|
|
const timer = setTimeout(() => {
|
|
(apiV2Data("get", "/dashboard/search", { query: { q: q }, authToken: token }) as Promise<{ results: Result[] }>)
|
|
.then(r => setResults(r.results || []))
|
|
.catch(() => setResults([]));
|
|
}, 200);
|
|
return () => clearTimeout(timer);
|
|
}, [query, open, token]);
|
|
|
|
const items = useMemo<Item[]>(() => {
|
|
const pages = matchPages(role, query).slice(0, query.trim() ? 8 : 10).map(p => ({ key: `page:${p.href}`, group: p.group, title: p.label, href: p.href, icon: PAGE_ICON[p.group] }));
|
|
const found = results.map(r => ({ key: `${r.type}:${r.id}`, group: RESULT_GROUP[r.type][0], title: r.title, subtitle: r.subtitle, href: r.href, icon: RESULT_GROUP[r.type][1] }));
|
|
return query.trim() ? [...found, ...pages] : pages;
|
|
}, [role, query, results]);
|
|
|
|
useEffect(() => { setActive(a => Math.min(a, Math.max(0, items.length - 1))); }, [items.length]);
|
|
useEffect(() => { listRef.current?.querySelector(`[data-index="${active}"]`)?.scrollIntoView({ block: "nearest" }); }, [active]);
|
|
|
|
const go = useCallback((item: Item | undefined) => {
|
|
if (!item) return;
|
|
setOpen(false);
|
|
router.push(item.href);
|
|
}, [router]);
|
|
|
|
if (!allowed || !open) return null;
|
|
|
|
const onKeyDown = (e: React.KeyboardEvent) => {
|
|
if (e.key === "Escape") { e.preventDefault(); setOpen(false); }
|
|
else if (e.key === "ArrowDown") { e.preventDefault(); setActive(a => Math.min(items.length - 1, a + 1)); }
|
|
else if (e.key === "ArrowUp") { e.preventDefault(); setActive(a => Math.max(0, a - 1)); }
|
|
else if (e.key === "Enter") { e.preventDefault(); go(items[active]); }
|
|
};
|
|
|
|
let lastGroup = "";
|
|
return (
|
|
<div className="fixed inset-0 z-[60] flex items-start justify-center bg-black/40 p-4 pt-[12vh]" onMouseDown={() => setOpen(false)}>
|
|
<div role="dialog" aria-modal="true" aria-label="Go to or search" className="w-full max-w-xl rounded-xl bg-white shadow-2xl overflow-hidden" onMouseDown={e => e.stopPropagation()}>
|
|
<div className="flex items-center gap-2 border-b px-3">
|
|
<Search className="w-4 h-4 text-gray-400 shrink-0" />
|
|
<input
|
|
ref={inputRef} value={query} onChange={e => { setQuery(e.target.value); setActive(0); }} onKeyDown={onKeyDown}
|
|
placeholder={role === "admin" ? "Go to a page, or find an event, person, payment (R450)…" : role === "supervisor" ? "Go to a page, or find an event or payment (R450)…" : "Go to a page or find an event…"}
|
|
className="flex-1 py-3 text-sm outline-none bg-transparent" aria-label="Search" role="combobox" aria-expanded="true" aria-controls="palette-results"
|
|
aria-activedescendant={items[active] ? `palette-item-${active}` : undefined}
|
|
/>
|
|
<kbd className="text-[10px] text-gray-400 border rounded px-1.5 py-0.5">Esc</kbd>
|
|
</div>
|
|
<ul id="palette-results" ref={listRef} role="listbox" className="max-h-[55vh] overflow-y-auto py-1" data-testid="palette-results">
|
|
{items.length === 0 && <li className="px-4 py-6 text-sm text-gray-500 text-center">{query.trim().length < 2 ? "Type to search." : "Nothing found."}</li>}
|
|
{items.map((item, i) => {
|
|
const header = item.group !== lastGroup ? item.group : null;
|
|
lastGroup = item.group;
|
|
const Icon = item.icon;
|
|
return (
|
|
<React.Fragment key={item.key}>
|
|
{header && <li className="px-4 pt-2 pb-1 text-[11px] font-semibold uppercase tracking-wide text-gray-400" role="presentation">{header}</li>}
|
|
<li
|
|
id={`palette-item-${i}`} data-index={i} role="option" aria-selected={i === active}
|
|
className={`mx-1 flex items-center gap-3 rounded-lg px-3 py-2 cursor-pointer ${i === active ? "bg-brand-50" : "hover:bg-gray-50"}`}
|
|
onMouseMove={() => setActive(i)} onClick={() => go(item)}
|
|
>
|
|
<Icon className="w-4 h-4 text-gray-500 shrink-0" />
|
|
<span className="min-w-0 flex-1">
|
|
<span className="block text-sm text-gray-900 truncate">{item.title}</span>
|
|
{item.subtitle && <span className="block text-xs text-gray-500 truncate">{item.subtitle}</span>}
|
|
</span>
|
|
{i === active && <CornerDownLeft className="w-3.5 h-3.5 text-gray-400" />}
|
|
</li>
|
|
</React.Fragment>
|
|
);
|
|
})}
|
|
</ul>
|
|
<div className="border-t px-4 py-2 text-[11px] text-gray-400 flex gap-4">
|
|
<span>↑↓ to move</span><span>Enter to open</span><span>Ctrl K to open or close</span>
|
|
</div>
|
|
</div>
|
|
</div>
|
|
);
|
|
}
|
|
|
|
/** A button that opens the palette (for people who don't use the keyboard shortcut). */
|
|
export function CommandPaletteButton({ className = "" }: { className?: string }) {
|
|
const { user } = useAuth();
|
|
if (!user || !["staff", "supervisor", "admin"].includes(user.role || "")) return null;
|
|
return (
|
|
<button type="button" onClick={() => window.dispatchEvent(new Event(OPEN_PALETTE_EVENT))}
|
|
className={`inline-flex items-center gap-2 rounded-lg border bg-white px-3 py-1.5 text-sm text-gray-500 hover:bg-gray-50 ${className}`}>
|
|
<Search className="w-4 h-4" /> Search or jump to… <kbd className="ml-2 text-[10px] border rounded px-1.5 py-0.5">Ctrl K</kbd>
|
|
</button>
|
|
);
|
|
}
|