Open History to see the last commit
1import { Dialog as CommandDialogPrimitive } from "@base-ui/react/dialog";
2import { SearchIcon } from "lucide-react";
3import { useEffect, useLayoutEffect, useRef } from "react";
4import type * as React from "react";
5import { cn } from "~/lib/utils";
6import { useNativeTitlebarHeight } from "~/lib/windowControlsOverlay";
7import {
8 Autocomplete,
9 AutocompleteCollection,
10 AutocompleteGroup,
11 AutocompleteGroupLabel,
12 AutocompleteInput,
13 AutocompleteItem,
14 AutocompleteList,
15 AutocompleteListHeading,
16 AutocompleteListVirtualized,
17} from "~/components/ui/autocomplete";
18import { DIALOG_BACKDROP_CLASS, DIALOG_POPUP_CLASS } from "~/components/ui/dialog-styles";
19import { Button } from "~/components/ui/button";
20import { closeOpenPopups } from "~/components/ui/open-popups";
21
22const CommandDialog = CommandDialogPrimitive.Root;
23
24const CommandDialogPortal = CommandDialogPrimitive.Portal;
25
26function CommandDialogTrigger(props: CommandDialogPrimitive.Trigger.Props) {
27 return <CommandDialogPrimitive.Trigger data-slot="command-dialog-trigger" {...props} />;
28}
29
30function CommandDialogBackdrop({ className, ...props }: CommandDialogPrimitive.Backdrop.Props) {
31 return (
32 <CommandDialogPrimitive.Backdrop
33 className={cn(DIALOG_BACKDROP_CLASS, "data-ending-style:pointer-events-none", className)}
34 data-slot="command-dialog-backdrop"
35 {...props}
36 />
37 );
38}
39
40function CommandDialogViewport({ className, ...props }: CommandDialogPrimitive.Viewport.Props) {
41 // Short desktop windows would put the search field under the native window controls.
42 const nativeTitlebarHeight = useNativeTitlebarHeight();
43 const titlebarStyle = {
44 "--command-titlebar-height": `${nativeTitlebarHeight}px`,
45 } as React.CSSProperties;
46 return (
47 <CommandDialogPrimitive.Viewport
48 className={cn(
49 "pointer-events-none fixed inset-0 z-50 flex flex-col items-center px-4 [-webkit-app-region:no-drag] pt-[max(--spacing(4),4vh,calc(var(--command-titlebar-height)+--spacing(2)))] pb-[max(--spacing(4),4vh)] sm:pt-[max(min(25vh,calc(90vh-26.25rem)),10vh,calc(var(--command-titlebar-height)+--spacing(2)))] sm:pb-[10vh]",
50 className,
51 )}
52 data-slot="command-dialog-viewport"
53 style={titlebarStyle}
54 {...props}
55 />
56 );
57}
58
59const POPUP =
60 '[data-open]:is([data-slot="menu-popup"],[data-slot="select-popup"],[data-slot="popover-popup"],[data-slot="combobox-popup"])';
61const canFocus = (el: HTMLElement | null): el is HTMLElement =>
62 !!(el && el !== document.body && !el.closest(":disabled,[inert]")) &&
63 el.checkVisibility({ visibilityProperty: true });
64// Rendered inside the portal, so it mounts each time the palette opens.
65function CloseOpenPopups({ triggerRef }: { triggerRef: React.RefObject<HTMLElement | null> }) {
66 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- capture the open popup trigger before focus moves or popups close
67 useLayoutEffect(() => {
68 const byId = (el: Element) => document.getElementById(el.getAttribute("aria-controls") ?? "");
69 const open = [...document.querySelectorAll<HTMLElement>("[data-popup-open][aria-controls]")];
70 triggerRef.current = open.find((el) => !el.closest(POPUP) && byId(el)?.closest(POPUP)) ?? null;
71 }, [triggerRef]);
72 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- popups opened before the palette would stay drawn above it
73 useEffect(closeOpenPopups, []);
74 return null;
75}
76
77function CommandDialogPopup({
78 className,
79 children,
80 finalFocus,
81 onBackdropPointerDown,
82 ...props
83}: CommandDialogPrimitive.Popup.Props & {
84 onBackdropPointerDown?: React.PointerEventHandler<HTMLDivElement>;
85}) {
86 const popupRef = useRef<HTMLDivElement>(null);
87 const triggerRef = useRef<HTMLElement | null>(null);
88 // A popup open under the palette had focus, and that element is hidden once the popup closes,
89 // so fall back to the popup's trigger.
90 const resolveFinalFocus: CommandDialogPrimitive.Popup.Props["finalFocus"] = (closeType) => {
91 const next = typeof finalFocus === "function" ? finalFocus(closeType) : (finalFocus ?? true);
92 if (next === false || next === undefined) return false;
93 // A function makes the return explicit, which drops Base UI's check that focus has not
94 // already moved elsewhere; keep that check for the default.
95 const active = document.activeElement;
96 if (
97 next === true &&
98 typeof finalFocus !== "function" &&
99 active &&
100 active !== document.body &&
101 !popupRef.current?.contains(active)
102 )
103 return false;
104 const target = next === true || next === null ? null : "current" in next ? next.current : next;
105 if (canFocus(target)) return target;
106 const trigger = triggerRef.current;
107 return canFocus(trigger) ? trigger : (target ?? true);
108 };
109 return (
110 <CommandDialogPortal>
111 <CloseOpenPopups triggerRef={triggerRef} />
112 <CommandDialogBackdrop onPointerDown={onBackdropPointerDown} />
113 <CommandDialogViewport>
114 <CommandDialogPrimitive.Popup
115 // The first tabbable can be an input addon, such as a submenu's Back button.
116 // Skip disabled inputs and Autocomplete's hidden sync input so Base UI focuses the popup.
117 initialFocus={() =>
118 popupRef.current?.querySelector<HTMLInputElement>(
119 'input:not(:disabled):not([aria-hidden="true"])',
120 ) ?? true
121 }
122 finalFocus={resolveFinalFocus}
123 ref={popupRef}
124 className={cn(
125 DIALOG_POPUP_CLASS,
126 "pointer-events-auto max-h-105 max-w-xl text-foreground data-ending-style:pointer-events-none",
127 className,
128 )}
129 data-slot="command-dialog-popup"
130 {...props}
131 >
132 {children}
133 </CommandDialogPrimitive.Popup>
134 </CommandDialogViewport>
135 </CommandDialogPortal>
136 );
137}
138
139function Command({
140 autoHighlight = "always",
141 keepHighlight = true,
142 ...props
143}: React.ComponentProps<typeof Autocomplete>) {
144 return (
145 <Autocomplete
146 autoHighlight={autoHighlight}
147 inline
148 keepHighlight={keepHighlight}
149 open
150 {...props}
151 />
152 );
153}
154
155function CommandInput({
156 className,
157 placeholder,
158 ...props
159}: React.ComponentProps<typeof AutocompleteInput>) {
160 return (
161 <div className="px-[var(--command-shell-inset)] py-1.5 [&_[data-slot=autocomplete-start-addon]]:ps-[calc(var(--command-shell-inset)+0.0625rem)]">
162 <AutocompleteInput
163 autoFocus
164 className={cn(
165 "border-transparent! bg-transparent! shadow-none before:hidden has-focus-visible:ring-0 placeholder:text-placeholder *:data-[slot=autocomplete-input]:ps-9! sm:*:data-[slot=autocomplete-input]:ps-[calc(var(--command-shell-inset)+1.5rem)]!",
166 className,
167 )}
168 placeholder={placeholder}
169 size="lg"
170 startAddon={<SearchIcon className="translate-x-0.5 text-icon-muted" />}
171 {...props}
172 />
173 </div>
174 );
175}
176
177function CommandList({ className, ...props }: React.ComponentProps<typeof AutocompleteList>) {
178 return (
179 <AutocompleteList
180 className={cn("not-empty:scroll-py-2 not-empty:p-2", className)}
181 data-slot="command-list"
182 {...props}
183 />
184 );
185}
186
187function CommandListVirtualized({
188 className,
189 ...props
190}: React.ComponentProps<typeof AutocompleteListVirtualized>) {
191 return (
192 <AutocompleteListVirtualized
193 className={cn("flex max-h-[inherit] min-h-0 flex-col", className)}
194 data-slot="command-list"
195 {...props}
196 />
197 );
198}
199
200function CommandListHeading({
201 className,
202 ...props
203}: React.ComponentProps<typeof AutocompleteListHeading>) {
204 return (
205 <AutocompleteListHeading className={className} data-slot="command-group-label" {...props} />
206 );
207}
208
209function CommandPanel({ className, ...props }: React.ComponentProps<"div">) {
210 return (
211 <div
212 className={cn(
213 "relative min-h-0 overflow-hidden rounded-t-xl not-has-[+[data-slot=command-footer]]:rounded-b-2xl bg-transparent **:data-[slot=scroll-area-scrollbar]:mt-2 [touch-action:pan-y]",
214 className,
215 )}
216 {...props}
217 />
218 );
219}
220
221function CommandGroup({ className, ...props }: React.ComponentProps<typeof AutocompleteGroup>) {
222 return <AutocompleteGroup className={className} data-slot="command-group" {...props} />;
223}
224
225function CommandGroupLabel({
226 className,
227 ...props
228}: React.ComponentProps<typeof AutocompleteGroupLabel>) {
229 return (
230 <AutocompleteGroupLabel className={className} data-slot="command-group-label" {...props} />
231 );
232}
233
234function CommandCollection({ ...props }: React.ComponentProps<typeof AutocompleteCollection>) {
235 return <AutocompleteCollection data-slot="command-collection" {...props} />;
236}
237
238// Pass active to override primitive hover/keyboard highlights when the palette tracks its own row.
239function CommandItem({
240 className,
241 active,
242 ...props
243}: React.ComponentProps<typeof AutocompleteItem> & { active?: boolean }) {
244 return (
245 <AutocompleteItem
246 className={cn(
247 "rounded-lg py-1.5 data-selected:bg-foreground/[0.06] data-highlighted:bg-foreground/[0.09] data-highlighted:text-foreground [&[data-highlighted][data-selected]]:bg-foreground/[0.09] [&[data-highlighted][data-selected]]:text-foreground",
248 active !== undefined &&
249 "cursor-pointer hover:bg-transparent hover:text-inherit data-highlighted:bg-transparent data-highlighted:text-inherit data-selected:bg-transparent data-selected:text-inherit [&[data-highlighted][data-selected]]:bg-transparent [&[data-highlighted][data-selected]]:text-inherit",
250 active && "bg-accent! text-accent-foreground!",
251 className,
252 )}
253 data-active={active || undefined}
254 data-slot="command-item"
255 {...props}
256 />
257 );
258}
259
260function CommandShortcut({ className, ...props }: React.ComponentProps<"kbd">) {
261 return (
262 <kbd
263 className={cn(
264 "ms-auto font-medium font-sans text-secondary-label text-xs tracking-widest",
265 className,
266 )}
267 data-slot="command-shortcut"
268 {...props}
269 />
270 );
271}
272
273function CommandFooter({ className, ...props }: React.ComponentProps<"div">) {
274 return (
275 <div
276 className={cn(
277 "relative flex items-center justify-between gap-2 rounded-b-[calc(var(--radius-2xl)-1px)] border-t border-foreground/[0.07] bg-foreground/[0.025] px-[var(--command-content-inset)] py-2.5 font-medium text-sm text-muted-foreground [&_[data-slot=kbd-group]]:font-sans [&_[data-slot=kbd]]:bg-foreground/[0.08] [&_[data-slot=kbd]]:text-foreground [&_[data-slot=kbd]]:ring-0",
278 className,
279 )}
280 data-slot="command-footer"
281 {...props}
282 />
283 );
284}
285
286function CommandFooterAction({
287 className,
288 ...props
289}: Omit<React.ComponentProps<typeof Button>, "size" | "variant">) {
290 return (
291 <Button
292 {...props}
293 variant="ghost-muted"
294 size="xs"
295 className={cn("h-auto px-2 text-xs hover:bg-transparent", className)}
296 />
297 );
298}
299
300export {
301 Command,
302 CommandCollection,
303 CommandDialog,
304 CommandDialogPopup,
305 CommandDialogTrigger,
306 CommandFooter,
307 CommandFooterAction,
308 CommandGroup,
309 CommandGroupLabel,
310 CommandInput,
311 CommandItem,
312 CommandList,
313 CommandListHeading,
314 CommandListVirtualized,
315 CommandPanel,
316 CommandShortcut,
317};