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

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