pr_01m47d15m3e54sn21z27rpy5n9/apps/web/app/components/command-palette-dialog.tsx

182 lines7,899 bytesCodeBlame
1import { Command as Cmdk } from "cmdk";
2import { Code2, CornerDownLeft, Search } from "lucide-react";
3import { Dialog as Primitive } from "radix-ui";
4import { useEffect, useState } from "react";
5import { useFetcher, useNavigate } from "react-router";
6
7import type { SiteHit } from "@g1t/contracts";
8
9import { searchHref } from "../lib/search";
10import { hitIcon } from "./search";
11import type { PaletteCommand } from "./command-palette";
12import { Command, CommandEmpty, CommandGroup, CommandItem, CommandList } from "./ui/combobox";
13
14/** How long typing has to pause before results are asked for. */
15const PAUSE_MS = 140;
16
17function hitHint(hit: SiteHit): string {
18 switch (hit.kind) {
19 case "repository":
20 return "Repository";
21 case "issue":
22 return `${hit.repo} #${hit.number}`;
23 case "pull":
24 return `${hit.repo} #${hit.number}`;
25 case "user":
26 return `Person · ${hit.slug}`;
27 case "workspace":
28 return `Workspace · ${hit.slug}`;
29 default:
30 return hit.repo ?? "";
31 }
32}
33
34/**
35 * ⌘K: pages and actions from what the page already knows, and, as someone
36 * types, repositories, issues, pull requests and people from search,
37 * public ones for anyone and private ones for their workspaces' members.
38 * The first row always searches all of g1t for what was typed.
39 */
40export default function CommandPaletteDialog({
41 open,
42 onOpenChange,
43 commands,
44 repo,
45}: {
46 open: boolean;
47 onOpenChange: (open: boolean) => void;
48 commands: PaletteCommand[];
49 /** The repository being looked at, `owner/name`, to offer searching its code. */
50 repo?: string | null;
51}) {
52 const navigate = useNavigate();
53 const fetcher = useFetcher<{ q: string; hits: SiteHit[] }>();
54 const [query, setQuery] = useState("");
55 const trimmed = query.trim();
56
57 useEffect(() => {
58 if (open) setQuery("");
59 }, [open]);
60 useEffect(() => {
61 if (trimmed.length < 2) return;
62 const timer = setTimeout(() => fetcher.load(`/search.json?q=${encodeURIComponent(trimmed)}`), PAUSE_MS);
63 return () => clearTimeout(timer);
64 // `fetcher` changes identity as it loads; only the text should restart it.
65 // eslint-disable-next-line react-hooks/exhaustive-deps
66 }, [trimmed]);
67
68 const hits = trimmed.length >= 2 && fetcher.data?.q === trimmed ? fetcher.data.hits : [];
69 const go = (to: string) => {
70 onOpenChange(false);
71 // The docs and other sites are full page loads.
72 if (/^https?:\/\//.test(to)) window.location.assign(to);
73 else navigate(to);
74 };
75 const words = trimmed.toLowerCase().split(/\s+/).filter(Boolean);
76 const pages = commands
77 .filter((command) => {
78 const text = `${command.label} ${command.hint ?? ""}`.toLowerCase();
79 return words.every((word) => text.includes(word));
80 })
81 .slice(0, trimmed ? 8 : 12);
82 const itemClass = "gap-3 rounded-lg px-3 py-2";
83
84 return (
85 <Primitive.Root open={open} onOpenChange={onOpenChange}>
86 <Primitive.Portal>
87 <Primitive.Overlay className="fixed inset-0 z-50 bg-black/50 backdrop-blur-sm data-[state=open]:animate-fade-in data-[state=closed]:animate-fade-out motion-reduce:animate-none" />
88 <Primitive.Content
89 aria-describedby={undefined}
90 className="fixed top-[12vh] left-1/2 z-50 w-[calc(100vw-2rem)] max-w-xl -translate-x-1/2 overflow-hidden rounded-xl border border-line-strong bg-raised shadow-2xl shadow-black/60 outline-none"
91 >
92 <Primitive.Title className="sr-only">Go to or search</Primitive.Title>
93 {/* Filtering is done here: search already filtered its results. */}
94 <Command shouldFilter={false} loop>
95 <div className="flex items-center gap-3 border-b border-line px-4">
96 <Search size={16} className="shrink-0 text-faint" />
97 <Cmdk.Input
98 value={query}
99 onValueChange={setQuery}
100 placeholder="Search g1t, or go to a page…"
101 autoComplete="off"
102 data-1p-ignore
103 className="h-12 grow border-0 bg-transparent text-sm shadow-none outline-none placeholder:text-faint focus-visible:outline-none"
104 />
105 <kbd className="rounded border border-line px-1.5 font-mono text-[0.6875rem] text-faint">esc</kbd>
106 </div>
107 <CommandList className="max-h-[55vh] p-1.5">
108 <CommandEmpty>Nothing matches.</CommandEmpty>
109 {trimmed && (
110 <CommandGroup heading="Search">
111 <CommandItem value="search:all" onSelect={() => go(searchHref(trimmed))} className={itemClass}>
112 <Search />
113 <span className="min-w-0 grow truncate">
114 Search g1t for <span className="font-medium text-fg">“{trimmed}”</span>
115 </span>
116 <CornerDownLeft className="size-3.5! text-faint!" />
117 </CommandItem>
118 <CommandItem value="search:code" onSelect={() => go(searchHref(trimmed, "code"))} className={itemClass}>
119 <Code2 />
120 <span className="min-w-0 grow truncate">
121 Search code for <span className="font-medium text-fg">“{trimmed}”</span>
122 </span>
123 </CommandItem>
124 {repo && (
125 <CommandItem
126 value="search:repo"
127 onSelect={() => go(searchHref(`${trimmed} repo:${repo}`, "code"))}
128 className={itemClass}
129 >
130 <Code2 />
131 <span className="min-w-0 grow truncate">
132 Search <span className="font-mono">{repo}</span> for{" "}
133 <span className="font-medium text-fg">“{trimmed}”</span>
134 </span>
135 </CommandItem>
136 )}
137 </CommandGroup>
138 )}
139 {hits.length > 0 && (
140 <CommandGroup heading="Results">
141 {hits.map((hit) => (
142 <CommandItem
143 key={`${hit.kind}:${hit.url}`}
144 value={`hit:${hit.kind}:${hit.url}`}
145 onSelect={() => go(hit.url)}
146 className={itemClass}
147 >
148 {hitIcon(hit)}
149 <span className="min-w-0 grow truncate">
150 {hit.kind === "repository" ? <span className="font-mono">{hit.title}</span> : hit.title}
151 </span>
152 <span className="shrink-0 truncate text-xs text-faint">{hitHint(hit)}</span>
153 </CommandItem>
154 ))}
155 </CommandGroup>
156 )}
157 {pages.length > 0 && (
158 <CommandGroup heading="Go to">
159 {pages.map((command) => (
160 <CommandItem
161 key={`${command.to}-${command.label}`}
162 value={`page:${command.to}:${command.label}`}
163 onSelect={() => go(command.to)}
164 className={itemClass}
165 >
166 <span className="shrink-0 text-faint">{command.icon}</span>
167 <span className="min-w-0 grow truncate">{command.label}</span>
168 {command.hint && <span className="shrink-0 truncate text-xs text-faint">{command.hint}</span>}
169 </CommandItem>
170 ))}
171 </CommandGroup>
172 )}
173 </CommandList>
174 </Command>
175 {hits.length === 0 && fetcher.state === "loading" && trimmed.length >= 2 && (
176 <p className="border-t border-line px-4 py-2 text-xs text-faint">Searching…</p>
177 )}
178 </Primitive.Content>
179 </Primitive.Portal>
180 </Primitive.Root>
181 );
182}