297 lines
11 KiB
TypeScript
297 lines
11 KiB
TypeScript
"use client";
|
||
// Command palette ⌘K and keyboard shortcuts (PEP-52). One document keydown listener: ⌘K/Ctrl+K
|
||
// toggles the palette anywhere; the rest (/, g x, j/k, a, ?) only outside text fields.
|
||
|
||
import { useRouter } from "next/navigation";
|
||
import { useCallback, useEffect, useRef, useState, useTransition } from "react";
|
||
import { Bot, CircleHelp, FileText, FolderKanban, Keyboard, MessageCircleQuestion, Play, Search } from "lucide-react";
|
||
import { matchPalette, type PaletteItem } from "@peppa/shared/palette";
|
||
import { moveTaskCard } from "@/app/(app)/actions";
|
||
import { PALETTE_KEYS, shortcutsFor } from "@/lib/shortcuts";
|
||
import { useWords } from "@/components/Words";
|
||
import { cn } from "@/lib/utils";
|
||
|
||
const ICON = { project: FolderKanban, story: FileText, runner: Bot, question: MessageCircleQuestion, page: CircleHelp } as const;
|
||
const GO: Record<string, string> = { h: "/", p: "/projects", r: "/runners", s: "/settings" };
|
||
const CACHE_MS = 30_000;
|
||
|
||
const typing = (t: EventTarget | null) => {
|
||
const el = t as HTMLElement | null;
|
||
return !!el && (el.isContentEditable || ["INPUT", "TEXTAREA", "SELECT"].includes(el.tagName));
|
||
};
|
||
|
||
export function Kbd({ children }: { children: React.ReactNode }) {
|
||
return <kbd className="rounded border bg-muted px-1.5 py-0.5 font-mono text-[11px] text-muted-foreground">{children}</kbd>;
|
||
}
|
||
|
||
export function ShortcutsList() {
|
||
const w = useWords();
|
||
return (
|
||
<table className="w-full border-collapse text-sm">
|
||
<tbody>
|
||
{shortcutsFor(w).map((s) => (
|
||
<tr key={s.keys.join(" ") + s.what} className="border-b last:border-0">
|
||
<td className="py-1.5 pr-3 whitespace-nowrap">
|
||
{s.keys.map((k, i) => (
|
||
<span key={k}>
|
||
{i > 0 && <span className="px-0.5 text-muted-foreground">{s.keys[0]!.length > 1 ? "/" : " "}</span>}
|
||
<Kbd>{k}</Kbd>
|
||
</span>
|
||
))}
|
||
</td>
|
||
<td className="py-1.5">
|
||
{s.what}
|
||
{s.where && <span className="text-muted-foreground"> — {s.where}</span>}
|
||
</td>
|
||
</tr>
|
||
))}
|
||
</tbody>
|
||
</table>
|
||
);
|
||
}
|
||
|
||
export function CommandPalette() {
|
||
const router = useRouter();
|
||
const palette = useRef<HTMLDialogElement>(null);
|
||
const help = useRef<HTMLDialogElement>(null);
|
||
const input = useRef<HTMLInputElement>(null);
|
||
const [items, setItems] = useState<PaletteItem[]>([]);
|
||
const [loadedAt, setLoadedAt] = useState(0);
|
||
const [query, setQuery] = useState("");
|
||
const [sel, setSel] = useState(0);
|
||
const [note, setNote] = useState<string | null>(null);
|
||
const w = useWords();
|
||
// PEP-123: «g r» (terminals of agents) works in «Инженер» only.
|
||
const engineer = useRef(w.engineer);
|
||
engineer.current = w.engineer;
|
||
const [pending, start] = useTransition();
|
||
const shown = matchPalette(items, query);
|
||
|
||
const load = useCallback(async () => {
|
||
if (Date.now() - loadedAt < CACHE_MS) return;
|
||
try {
|
||
const r = await fetch("/api/palette", { cache: "no-store" });
|
||
if (r.ok) {
|
||
setItems(((await r.json()) as { items: PaletteItem[] }).items);
|
||
setLoadedAt(Date.now());
|
||
}
|
||
} catch {}
|
||
}, [loadedAt]);
|
||
|
||
const open = useCallback(() => {
|
||
help.current?.close();
|
||
setQuery("");
|
||
setSel(0);
|
||
setNote(null);
|
||
if (!palette.current?.open) palette.current?.showModal();
|
||
input.current?.focus();
|
||
void load();
|
||
}, [load]);
|
||
const close = () => palette.current?.close();
|
||
|
||
const go = (item: PaletteItem) => {
|
||
close();
|
||
router.push(item.href);
|
||
};
|
||
const startStory = (item: PaletteItem) => {
|
||
if (!item.canStart) return;
|
||
const f = new FormData();
|
||
f.set("taskKey", item.key);
|
||
f.set("to", "in_progress");
|
||
f.set("back", item.href);
|
||
setNote(`${item.key} → В работу…`);
|
||
start(async () => {
|
||
close();
|
||
setLoadedAt(0);
|
||
await moveTaskCard(f); // redirects to the story page
|
||
});
|
||
};
|
||
|
||
// Global keys.
|
||
useEffect(() => {
|
||
let prefix: { key: string; at: number } | null = null;
|
||
const onKey = (e: KeyboardEvent) => {
|
||
if ((e.metaKey || e.ctrlKey) && e.key.toLowerCase() === "k") {
|
||
e.preventDefault();
|
||
if (palette.current?.open) close();
|
||
else open();
|
||
return;
|
||
}
|
||
if (e.metaKey || e.ctrlKey || e.altKey || typing(e.target) || palette.current?.open || help.current?.open) return;
|
||
if (prefix && prefix.key === "g" && Date.now() - prefix.at < 1000 && GO[e.key] && (e.key !== "r" || engineer.current)) {
|
||
e.preventDefault();
|
||
prefix = null;
|
||
router.push(GO[e.key]!);
|
||
return;
|
||
}
|
||
prefix = null;
|
||
switch (e.key) {
|
||
case "g":
|
||
prefix = { key: "g", at: Date.now() };
|
||
return;
|
||
case "/": {
|
||
const el = document.querySelector<HTMLInputElement>("[data-hotkey-search]");
|
||
if (el) {
|
||
e.preventDefault();
|
||
el.focus();
|
||
el.select();
|
||
} else {
|
||
e.preventDefault();
|
||
open();
|
||
}
|
||
return;
|
||
}
|
||
case "?":
|
||
e.preventDefault();
|
||
help.current?.showModal();
|
||
return;
|
||
case "a": {
|
||
const el = document.querySelector<HTMLInputElement>("[data-hotkey-answer]");
|
||
if (el) {
|
||
e.preventDefault();
|
||
el.scrollIntoView({ block: "center" });
|
||
el.focus();
|
||
}
|
||
return;
|
||
}
|
||
case "j":
|
||
case "k": {
|
||
const list = [...document.querySelectorAll<HTMLAnchorElement>("[data-hotkey-item]")];
|
||
if (!list.length) return;
|
||
e.preventDefault();
|
||
const cur = list.findIndex((a) => a.getAttribute("aria-current") === "true");
|
||
const next = list[Math.min(list.length - 1, Math.max(0, cur < 0 ? 0 : cur + (e.key === "j" ? 1 : -1)))]!;
|
||
next.focus();
|
||
next.click();
|
||
return;
|
||
}
|
||
}
|
||
};
|
||
document.addEventListener("keydown", onKey);
|
||
return () => document.removeEventListener("keydown", onKey);
|
||
}, [open, router]);
|
||
|
||
// Anyone can open the palette from a button: <button data-open-palette>.
|
||
useEffect(() => {
|
||
const onClick = (e: MouseEvent) => {
|
||
if ((e.target as HTMLElement | null)?.closest("[data-open-palette]")) {
|
||
e.preventDefault();
|
||
open();
|
||
}
|
||
};
|
||
document.addEventListener("click", onClick);
|
||
return () => document.removeEventListener("click", onClick);
|
||
}, [open]);
|
||
|
||
useEffect(() => {
|
||
document.getElementById(`palette-item-${sel}`)?.scrollIntoView({ block: "nearest" });
|
||
}, [sel]);
|
||
|
||
return (
|
||
<>
|
||
<dialog
|
||
ref={palette}
|
||
aria-label="Командная палитра"
|
||
className="m-auto mt-[12vh] w-[min(640px,calc(100vw-2rem))] rounded-xl border bg-popover p-0 text-popover-foreground shadow-2xl backdrop:bg-black/50"
|
||
onClick={(e) => e.target === palette.current && close()}
|
||
>
|
||
<div className="flex items-center gap-2 border-b px-3">
|
||
<Search className="size-4 text-muted-foreground" />
|
||
<input
|
||
ref={input}
|
||
value={query}
|
||
onChange={(e) => {
|
||
setQuery(e.target.value);
|
||
setSel(0);
|
||
}}
|
||
onKeyDown={(e) => {
|
||
if (e.key === "ArrowDown") {
|
||
e.preventDefault();
|
||
setSel((s) => Math.min(shown.length - 1, s + 1));
|
||
} else if (e.key === "ArrowUp") {
|
||
e.preventDefault();
|
||
setSel((s) => Math.max(0, s - 1));
|
||
} else if (e.key === "Enter" && shown[sel]) {
|
||
e.preventDefault();
|
||
if ((e.metaKey || e.ctrlKey) && shown[sel]!.canStart) startStory(shown[sel]!);
|
||
else go(shown[sel]!);
|
||
}
|
||
}}
|
||
placeholder={w.engineer ? "Проект, стори, раннер, вопрос или раздел…" : "Проект, задача, вопрос или раздел…"}
|
||
aria-label="Поиск"
|
||
role="combobox"
|
||
aria-expanded="true"
|
||
aria-controls="palette-list"
|
||
aria-activedescendant={shown[sel] ? `palette-item-${sel}` : undefined}
|
||
className="h-12 min-w-0 flex-1 bg-transparent text-sm outline-none"
|
||
/>
|
||
<Kbd>Esc</Kbd>
|
||
</div>
|
||
<ul id="palette-list" role="listbox" className="m-0 max-h-[52vh] list-none overflow-y-auto p-1.5">
|
||
{shown.length === 0 && <li className="px-3 py-6 text-center text-sm text-muted-foreground">{loadedAt ? "Ничего не найдено" : "Загрузка…"}</li>}
|
||
{shown.map((item, i) => {
|
||
const Icon = ICON[item.kind];
|
||
return (
|
||
<li
|
||
key={`${item.kind}:${item.key}:${item.href}`}
|
||
id={`palette-item-${i}`}
|
||
role="option"
|
||
aria-selected={i === sel}
|
||
onMouseMove={() => setSel(i)}
|
||
onClick={() => go(item)}
|
||
className={cn("flex cursor-pointer items-center gap-2.5 rounded-md px-2.5 py-2 text-sm", i === sel && "bg-accent")}
|
||
>
|
||
<Icon className="size-4 shrink-0 text-muted-foreground" />
|
||
{item.key && <span className={cn("shrink-0 font-mono text-xs", item.kind === "page" ? "text-muted-foreground" : "text-primary")}>{item.key}</span>}
|
||
<span className="min-w-0 flex-1 truncate">{item.title}</span>
|
||
{item.hint && <span className="hidden shrink-0 text-xs text-muted-foreground sm:inline">{item.hint}</span>}
|
||
{item.canStart && (
|
||
<button
|
||
type="button"
|
||
title="В работу (⌘Enter)"
|
||
disabled={pending}
|
||
onClick={(e) => {
|
||
e.stopPropagation();
|
||
startStory(item);
|
||
}}
|
||
className="flex shrink-0 items-center gap-1 rounded border px-1.5 py-0.5 text-xs text-muted-foreground hover:border-primary hover:text-foreground"
|
||
>
|
||
<Play className="size-3" />В работу
|
||
</button>
|
||
)}
|
||
</li>
|
||
);
|
||
})}
|
||
</ul>
|
||
<div className="flex items-center gap-2 border-t px-3 py-2 text-[11px] text-muted-foreground">
|
||
<span className="min-w-0 flex-1 truncate">{note ?? PALETTE_KEYS}</span>
|
||
<button
|
||
type="button"
|
||
onClick={() => {
|
||
close();
|
||
help.current?.showModal();
|
||
}}
|
||
className="flex items-center gap-1 hover:text-foreground"
|
||
>
|
||
<Keyboard className="size-3.5" />
|
||
Сочетания <Kbd>?</Kbd>
|
||
</button>
|
||
</div>
|
||
</dialog>
|
||
|
||
<dialog
|
||
ref={help}
|
||
aria-label="Горячие клавиши"
|
||
className="m-auto w-[min(560px,calc(100vw-2rem))] rounded-xl border bg-popover p-4 text-popover-foreground shadow-2xl backdrop:bg-black/50"
|
||
onClick={(e) => e.target === help.current && help.current?.close()}
|
||
>
|
||
<h2 className="m-0 mb-2 text-base font-semibold">Горячие клавиши</h2>
|
||
<ShortcutsList />
|
||
<p className="m-0 mt-3 text-xs text-muted-foreground">
|
||
Клавиши без ⌘ работают вне полей ввода. Список — на странице <a href="/help/shortcuts" className="text-primary">Помощь → Горячие клавиши</a>.
|
||
</p>
|
||
</dialog>
|
||
</>
|
||
);
|
||
}
|