SPB Git

Repository Public

CommandPalette.tsx 6.4 KB 121 lines tsx

1"use client";2import { useRouter } from "next/navigation";3import { useEffect, useId, useMemo, useState } from "react";4import { useApiQuery } from "@/api/query";5import { useI18n } from "@/i18n";6import { Dialog, FreshnessBadge, Icon, Kbd, type IconName } from "@/ui";7import { NAV, hrefFor } from "./nav";8import { useSession } from "./session";9import { useTheme } from "./theme";1011interface Entry {12  id: string;13  group: string;14  label: string;15  sub?: string | undefined;16  icon: IconName;17  run: () => void;18  extra?: React.ReactNode;19}2021const KIND_ICON: Record<string, IconName> = { node: "nodes", service: "services", alert: "alerts", action: "bolt", incident: "critical", job: "jobs", inference_server: "models", maintenance_window: "maintenance", maintenance_note: "note" };2223/** Universal search (GET /search) + commands. ⌘K / Ctrl+K. Combobox pattern: the input keeps focus, ↑/↓ move, ↵ opens. */24export function CommandPalette({ open, onClose }: { open: boolean; onClose: () => void }) {25  // mounted only while open: every opening starts from an empty query26  return open ? <Palette onClose={onClose} /> : null;27}2829function Palette({ onClose }: { onClose: () => void }) {30  const open = true;31  const { t } = useI18n();32  const router = useRouter();33  const session = useSession();34  const { theme, setTheme } = useTheme();35  const listId = useId();36  const [text, setText] = useState("");37  const [debounced, setDebounced] = useState("");38  const [active, setActive] = useState(0);3940  useEffect(() => {41    const id = window.setTimeout(() => setDebounced(text.trim()), 180);42    return () => window.clearTimeout(id);43  }, [text]);4445  const search = useApiQuery("/search", { query: { q: debounced, limit: 12 } }, { enabled: open && debounced.length >= 2, staleTime: 5_000 });4647  const entries = useMemo<Entry[]>(() => {48    const go = (href: string) => () => { onClose(); router.push(href); };49    const q = text.trim().toLowerCase();50    const nav: Entry[] = NAV.filter((i) => !i.permission || session.can(i.permission)).map((i) => ({ id: `nav:${i.href}`, group: t("shell.palette.goTo"), label: t(i.key), icon: i.icon, run: go(i.href) }));51    const cmds: Entry[] = [52      { id: "cmd:theme", group: t("shell.palette.commands"), label: theme === "dark" ? t("shell.account.toLight") : t("shell.account.toDark"), icon: theme === "dark" ? "sun" : "moon", run: () => { setTheme(theme === "dark" ? "light" : "dark"); onClose(); } },53      { id: "cmd:ops", group: t("shell.palette.commands"), label: t("shell.palette.opsMode"), icon: "monitor", run: go("/ops") },54      { id: "cmd:security", group: t("shell.palette.commands"), label: t("shell.account.security"), icon: "passkey", run: go("/settings/security") },55      { id: "cmd:signout", group: t("shell.palette.commands"), label: t("shell.account.signOut"), icon: "logout", run: () => { onClose(); void session.signOut(); } },56    ];57    const statics = [...nav, ...cmds].filter((e) => !q || e.label.toLowerCase().includes(q));58    const results: Entry[] = (search.data?.items ?? []).map((r) => ({59      id: `res:${r.kind}:${r.id}`,60      group: t("shell.palette.results"),61      label: r.title,62      sub: [t(`shell.palette.kind.${r.kind}`), r.subtitle, r.state].filter(Boolean).join(" · "),63      icon: KIND_ICON[r.kind] ?? "search",64      run: go(hrefFor(r.kind, r.id, r.node_id)),65      extra: r.freshness ? <FreshnessBadge freshness={r.freshness} subtle /> : undefined,66    }));67    return [...results, ...statics];68  }, [text, search.data, session, theme, setTheme, t, router, onClose]);6970  const safeActive = Math.min(active, Math.max(0, entries.length - 1));71  let lastGroup = "";72  return (73    <Dialog open={open} onClose={onClose} title={t("shell.palette.title")} hideHeader className="mcc-palette">74      <div className="mcc-palette-input">75        <Icon name="search" size={18} />76        <input77          autoFocus78          role="combobox"79          aria-expanded="true"80          aria-controls={listId}81          aria-activedescendant={entries[safeActive] ? `${listId}-${safeActive}` : undefined}82          aria-label={t("shell.search.placeholder")}83          placeholder={t("shell.search.placeholder")}84          value={text}85          autoComplete="off"86          spellCheck={false}87          data-testid="palette-input"88          onChange={(e) => { setText(e.target.value); setActive(0); }}89          onKeyDown={(e) => {90            if (e.key === "ArrowDown") { e.preventDefault(); setActive((i) => Math.min(entries.length - 1, i + 1)); }91            else if (e.key === "ArrowUp") { e.preventDefault(); setActive((i) => Math.max(0, i - 1)); }92            else if (e.key === "Enter") { e.preventDefault(); entries[safeActive]?.run(); }93          }}94        />95      </div>96      <ul className="mcc-palette-list" id={listId} role="listbox" aria-label={t("shell.palette.title")}>97        {debounced.length >= 2 && search.isError ? (98          <li role="presentation" className="mcc-menu-label muted" data-testid="search-unavailable">{search.error.notImplemented ? t("shell.palette.searchNotAvailable") : t("shell.palette.searchFailed")}</li>99        ) : null}100        {debounced.length >= 2 && search.isLoading ? <li role="presentation" className="mcc-menu-label muted">{t("shell.palette.searching")}</li> : null}101        {debounced.length >= 2 && search.data && search.data.items.length === 0 ? <li role="presentation" className="mcc-menu-label muted">{t("shell.palette.noResults", { query: debounced })}</li> : null}102        {entries.map((e, i) => {103          const header = e.group !== lastGroup ? e.group : null;104          lastGroup = e.group;105          return (106            <li key={e.id} role="presentation">107              {header ? <div className="mcc-palette-group caps" role="presentation">{header}</div> : null}108              <div id={`${listId}-${i}`} role="option" aria-selected={i === safeActive} data-active={i === safeActive} className="mcc-option" onMouseEnter={() => setActive(i)} onClick={e.run}>109                <Icon name={e.icon} size={15} />110                <span className="grow truncate">{e.label}{e.sub ? <span className="sub"> — {e.sub}</span> : null}</span>111                {e.extra}112              </div>113            </li>114          );115        })}116      </ul>117      <div className="mcc-palette-foot"><span><Kbd>↑</Kbd> <Kbd>↓</Kbd> {t("shell.palette.hintMove")}</span><span><Kbd>↵</Kbd> {t("shell.palette.hintOpen")}</span><span><Kbd>esc</Kbd> {t("common.close")}</span></div>118    </Dialog>119  );120}121
Files main
Menu

Theme