Open History to see the last commit
1import { type ResolvedKeybindingsConfig } from "@t3tools/contracts";
2import { LegendList, type LegendListRef } from "@legendapp/list/react";
3import { ChevronRightIcon } from "lucide-react";
4import { type ReactNode, type RefObject, useState } from "react";
5import { cn } from "~/lib/utils";
6import { textDirection } from "~/textDirection";
7import { shortcutLabelForCommand } from "../keybindings";
8import {
9 type CommandPaletteActionItem,
10 type CommandPaletteGroup,
11 type CommandPaletteRow,
12 type CommandPaletteSubmenuItem,
13} from "./CommandPalette.logic";
14import {
15 CommandCollection,
16 CommandGroup,
17 CommandGroupLabel,
18 CommandItem,
19 CommandList,
20 CommandListHeading,
21 CommandListVirtualized,
22 CommandShortcut,
23} from "./ui/command";
24import { getVirtualizedScrollFadeClassName } from "./ui/scroll-area";
25import {
26 HighlightedSearchText,
27 SearchMatchHintLine,
28 ThreadSearchMatchExcerpt,
29} from "./ThreadSearchMatch";
30
31interface CommandPaletteResultsProps {
32 emptyStateMessage?: string;
33 groups: ReadonlyArray<CommandPaletteGroup>;
34 highlightedItemValue?: string | null;
35 isActionsOnly: boolean;
36 keybindings: ResolvedKeybindingsConfig;
37 onExecuteItem: (item: CommandPaletteActionItem | CommandPaletteSubmenuItem) => void;
38}
39
40function CommandPaletteEmptyState(props: { emptyStateMessage?: string; isActionsOnly: boolean }) {
41 return (
42 <div className="py-10 text-center text-sm text-muted-foreground">
43 {props.emptyStateMessage ??
44 (props.isActionsOnly
45 ? "No matching actions."
46 : "No matching commands, projects, or threads.")}
47 </div>
48 );
49}
50
51export function CommandPaletteResults(props: CommandPaletteResultsProps) {
52 if (props.groups.length === 0) {
53 return <CommandPaletteEmptyState {...props} />;
54 }
55
56 return (
57 <CommandList>
58 {props.groups.map((group) => (
59 <CommandGroup items={group.items} key={group.value}>
60 {group.label ? <CommandGroupLabel>{group.label}</CommandGroupLabel> : null}
61 <CommandCollection>
62 {(item) =>
63 item.disabled ? (
64 <DisabledCommandPaletteResultRow item={item} key={item.value} />
65 ) : (
66 <CommandPaletteResultRow
67 item={item}
68 key={item.value}
69 keybindings={props.keybindings}
70 isActive={props.highlightedItemValue === item.value}
71 onExecuteItem={props.onExecuteItem}
72 />
73 )
74 }
75 </CommandCollection>
76 </CommandGroup>
77 ))}
78 </CommandList>
79 );
80}
81
82export function scrollCommandPaletteRowIntoView(list: LegendListRef | null, rowIndex: number) {
83 const element = list?.getState?.().elementAtIndex(rowIndex);
84 if (element instanceof HTMLElement) {
85 element.scrollIntoView({ block: "nearest" });
86 return;
87 }
88 void list?.scrollIndexIntoView?.({ index: rowIndex, animated: false });
89}
90
91interface CommandPaletteVirtualizedResultsProps extends Omit<CommandPaletteResultsProps, "groups"> {
92 rows: ReadonlyArray<CommandPaletteRow>;
93 listRef: RefObject<LegendListRef | null>;
94}
95
96/** Pass flat items with virtualized to Command, scroll highlights via listRef, and handle Enter for
97 * unmounted rows. */
98export function CommandPaletteVirtualizedResults(props: CommandPaletteVirtualizedResultsProps) {
99 const { listRef } = props;
100 const [scrollFade, setScrollFade] = useState({ top: false, bottom: false });
101 const updateScrollFade = () => {
102 const scrollElement = listRef.current?.getScrollableNode?.();
103 if (!(scrollElement instanceof HTMLElement)) return;
104 const top = scrollElement.scrollTop > 1;
105 const bottom =
106 scrollElement.scrollHeight - scrollElement.clientHeight - scrollElement.scrollTop > 1;
107 setScrollFade((current) =>
108 current.top === top && current.bottom === bottom ? current : { top, bottom },
109 );
110 };
111
112 if (props.rows.length === 0) {
113 return <CommandPaletteEmptyState {...props} />;
114 }
115
116 return (
117 <CommandListVirtualized>
118 <LegendList<CommandPaletteRow>
119 ref={listRef}
120 data={props.rows}
121 keyExtractor={(row) => row.key}
122 getItemType={(row) => row.kind}
123 extraData={props.highlightedItemValue}
124 renderItem={({ item: row }) =>
125 row.kind === "label" ? (
126 <div className={row.first ? undefined : "pt-1.5"}>
127 <CommandListHeading>{row.label}</CommandListHeading>
128 </div>
129 ) : row.itemIndex === null ? (
130 <DisabledCommandPaletteResultRow item={row.item} />
131 ) : (
132 <CommandPaletteResultRow
133 index={row.itemIndex}
134 item={row.item}
135 keybindings={props.keybindings}
136 isActive={props.highlightedItemValue === row.item.value}
137 onExecuteItem={props.onExecuteItem}
138 />
139 )
140 }
141 estimatedItemSize={40}
142 drawDistance={400}
143 onLayout={updateScrollFade}
144 onScroll={updateScrollFade}
145 contentContainerClassName="px-2"
146 className={cn(
147 "min-h-0 scroll-py-6 overflow-x-hidden overscroll-y-contain py-2 [&::-webkit-scrollbar-track]:my-2",
148 getVirtualizedScrollFadeClassName(scrollFade),
149 )}
150 />
151 </CommandListVirtualized>
152 );
153}
154
155export function CommandPaletteTitleIcon(props: { children: ReactNode }) {
156 return <span className="flex h-5 shrink-0 items-center self-start pt-0.5">{props.children}</span>;
157}
158
159function CommandPaletteTitle({
160 item,
161}: {
162 item: Pick<CommandPaletteActionItem | CommandPaletteSubmenuItem, "title" | "titleRanges">;
163}) {
164 const { title } = item;
165 return (
166 <span className="truncate" dir={typeof title === "string" ? textDirection(title) : undefined}>
167 {typeof title === "string" && item.titleRanges ? (
168 <HighlightedSearchText text={title} ranges={item.titleRanges} />
169 ) : (
170 title
171 )}
172 </span>
173 );
174}
175
176/**
177 * Project and environment for a thread row whose second line shows a message
178 * snippet or match hint instead, so similar rows can still be told apart.
179 */
180function ThreadRowContext({
181 item,
182}: {
183 item: CommandPaletteActionItem | CommandPaletteSubmenuItem;
184}) {
185 if (!item.threadSearch || !(item.threadContentMatch || item.matchHint)) return null;
186 // A "Project: …" hint already names the project.
187 const context = [item.threadSearch.projectTitle, item.threadSearch.environmentLabel]
188 .filter((part) => part && part !== item.matchHint?.text)
189 .join(" · ");
190 return context ? (
191 <span className="max-w-[45%] shrink-0 truncate text-muted-foreground/70 text-xs">
192 {context}
193 </span>
194 ) : null;
195}
196
197function DisabledCommandPaletteResultRow(props: {
198 item: CommandPaletteActionItem | CommandPaletteSubmenuItem;
199}) {
200 return (
201 <div className="flex min-h-8 select-none items-center gap-2 rounded-sm px-2 py-1.5 text-base opacity-64 sm:min-h-7 sm:text-sm">
202 <CommandPaletteTitleIcon>{props.item.icon}</CommandPaletteTitleIcon>
203 {props.item.description || props.item.threadContentMatch ? (
204 <span className="flex min-w-0 flex-1 flex-col">
205 <span className="flex min-w-0 items-center gap-1.5 text-sm text-foreground">
206 {props.item.titleLeadingContent}
207 <CommandPaletteTitle item={props.item} />
208 <ThreadRowContext item={props.item} />
209 </span>
210 {props.item.threadContentMatch ? (
211 <ThreadSearchMatchExcerpt match={props.item.threadContentMatch} />
212 ) : props.item.matchHint ? (
213 <SearchMatchHintLine hint={props.item.matchHint} />
214 ) : props.item.description ? (
215 <span className="min-w-0 text-muted-foreground/70 text-xs">
216 {props.item.description}
217 </span>
218 ) : null}
219 </span>
220 ) : (
221 <span className="flex min-w-0 flex-1 items-center gap-1.5 text-sm text-foreground">
222 {props.item.titleLeadingContent}
223 <CommandPaletteTitle item={props.item} />
224 </span>
225 )}
226 {props.item.titleTrailingContent}
227 </div>
228 );
229}
230
231function CommandPaletteResultRow(props: {
232 index?: number;
233 item: CommandPaletteActionItem | CommandPaletteSubmenuItem;
234 isActive: boolean;
235 keybindings: ResolvedKeybindingsConfig;
236 onExecuteItem: (item: CommandPaletteActionItem | CommandPaletteSubmenuItem) => void;
237}) {
238 const shortcutLabel = props.item.shortcutCommand
239 ? shortcutLabelForCommand(props.keybindings, props.item.shortcutCommand)
240 : null;
241
242 return (
243 <CommandItem
244 {...(props.index === undefined ? {} : { index: props.index })}
245 value={props.item.value}
246 active={props.isActive}
247 onMouseDown={(event) => {
248 event.preventDefault();
249 }}
250 onClick={() => {
251 props.onExecuteItem(props.item);
252 }}
253 >
254 <CommandPaletteTitleIcon>{props.item.icon}</CommandPaletteTitleIcon>
255 {props.item.description || props.item.threadContentMatch ? (
256 <span className="flex min-w-0 flex-1 flex-col">
257 <span className="flex min-w-0 items-center gap-1.5 text-sm text-foreground">
258 {props.item.titleLeadingContent}
259 <CommandPaletteTitle item={props.item} />
260 <ThreadRowContext item={props.item} />
261 </span>
262 {props.item.threadContentMatch ? (
263 <ThreadSearchMatchExcerpt match={props.item.threadContentMatch} />
264 ) : props.item.matchHint ? (
265 <SearchMatchHintLine hint={props.item.matchHint} />
266 ) : props.item.description ? (
267 <span className="min-w-0 text-muted-foreground/70 text-xs">
268 {props.item.description}
269 </span>
270 ) : null}
271 </span>
272 ) : (
273 <span className="flex min-w-0 flex-1 items-center gap-1.5 text-sm text-foreground">
274 {props.item.titleLeadingContent}
275 <CommandPaletteTitle item={props.item} />
276 </span>
277 )}
278 {props.item.titleTrailingContent}
279 {props.item.timestamp ? (
280 <span className="min-w-12 shrink-0 text-right text-xs tabular-nums text-muted-foreground/70">
281 {props.item.timestamp}
282 </span>
283 ) : null}
284 {shortcutLabel ? <CommandShortcut>{shortcutLabel}</CommandShortcut> : null}
285 {props.item.kind === "submenu" ? (
286 <ChevronRightIcon className="-me-0.5 ms-auto size-4 shrink-0 text-muted-foreground/70" />
287 ) : null}
288 </CommandItem>
289 );
290}