|
| 1 | +"use client"; |
| 2 | + |
| 3 | +import { FileIcon } from "@phosphor-icons/react"; |
| 4 | +import { useRouter } from "next/navigation"; |
| 5 | +import { useEffect, useState } from "react"; |
| 6 | +import { |
| 7 | + Command, |
| 8 | + CommandDialog, |
| 9 | + CommandEmpty, |
| 10 | + CommandGroup, |
| 11 | + CommandInput, |
| 12 | + CommandItem, |
| 13 | + CommandList, |
| 14 | +} from "@/components/ui/command"; |
| 15 | + |
| 16 | +type DocsNavPage = { |
| 17 | + title: string; |
| 18 | + url: string; |
| 19 | +}; |
| 20 | + |
| 21 | +const EDITABLE_TAGS = new Set(["INPUT", "TEXTAREA", "SELECT"]); |
| 22 | + |
| 23 | +function isEditableTarget(target: EventTarget | null): boolean { |
| 24 | + const element = target as HTMLElement | null; |
| 25 | + if (!element) return false; |
| 26 | + if (EDITABLE_TAGS.has(element.tagName)) return true; |
| 27 | + return element.isContentEditable; |
| 28 | +} |
| 29 | + |
| 30 | +export function DocsCommandMenu({ pages }: { pages: DocsNavPage[] }) { |
| 31 | + const router = useRouter(); |
| 32 | + const [open, setOpen] = useState(false); |
| 33 | + |
| 34 | + useEffect(() => { |
| 35 | + const onKeyDown = (event: KeyboardEvent) => { |
| 36 | + if (event.defaultPrevented) return; |
| 37 | + if (event.isComposing) return; |
| 38 | + if (!(event.metaKey || event.ctrlKey)) return; |
| 39 | + if (event.key.toLowerCase() !== "k") return; |
| 40 | + if (isEditableTarget(event.target)) return; |
| 41 | + |
| 42 | + event.preventDefault(); |
| 43 | + setOpen((value) => !value); |
| 44 | + }; |
| 45 | + |
| 46 | + window.addEventListener("keydown", onKeyDown); |
| 47 | + return () => window.removeEventListener("keydown", onKeyDown); |
| 48 | + }, []); |
| 49 | + |
| 50 | + return ( |
| 51 | + <CommandDialog |
| 52 | + open={open} |
| 53 | + onOpenChange={setOpen} |
| 54 | + title="Search docs" |
| 55 | + description="Jump to a button documentation page" |
| 56 | + > |
| 57 | + <Command> |
| 58 | + <CommandInput placeholder="Search buttons…" /> |
| 59 | + <CommandList> |
| 60 | + <CommandEmpty>No pages found.</CommandEmpty> |
| 61 | + <CommandGroup heading="Buttons"> |
| 62 | + {pages.map((page) => ( |
| 63 | + <CommandItem |
| 64 | + key={page.url} |
| 65 | + value={`${page.title} ${page.url}`} |
| 66 | + onSelect={() => { |
| 67 | + setOpen(false); |
| 68 | + router.push(page.url); |
| 69 | + }} |
| 70 | + > |
| 71 | + <FileIcon /> |
| 72 | + <span>{page.title}</span> |
| 73 | + </CommandItem> |
| 74 | + ))} |
| 75 | + </CommandGroup> |
| 76 | + </CommandList> |
| 77 | + </Command> |
| 78 | + </CommandDialog> |
| 79 | + ); |
| 80 | +} |
0 commit comments