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/**
97 * The parent passes the flat item order to the Command root as `items` with
98 * `virtualized`, scrolls keyboard highlights into view through `listRef`, and
99 * runs Enter itself since the row may be unmounted.
100 */
101export function CommandPaletteVirtualizedResults(props: CommandPaletteVirtualizedResultsProps) {
102 const { listRef } = props;
103 const [scrollFade, setScrollFade] = useState({ top: false, bottom: false });
104 const updateScrollFade = () => {
105 const scrollElement = listRef.current?.getScrollableNode?.();
106 if (!(scrollElement instanceof HTMLElement)) return;
107 const top = scrollElement.scrollTop > 1;
108 const bottom =
109 scrollElement.scrollHeight - scrollElement.clientHeight - scrollElement.scrollTop > 1;
110 setScrollFade((current) =>
111 current.top === top && current.bottom === bottom ? current : { top, bottom },
112 );
113 };
114
115 if (props.rows.length === 0) {
116 return <CommandPaletteEmptyState {...props} />;
117 }
118
119 return (
120 <CommandListVirtualized>
121 <LegendList<CommandPaletteRow>
122 ref={listRef}
123 data={props.rows}
124 keyExtractor={(row) => row.key}
125 getItemType={(row) => row.kind}
126 extraData={props.highlightedItemValue}
127 renderItem={({ item: row }) =>
128 row.kind === "label" ? (
129 <div className={row.first ? undefined : "pt-1.5"}>
130 <CommandListHeading>{row.label}</CommandListHeading>
131 </div>
132 ) : row.itemIndex === null ? (
133 <DisabledCommandPaletteResultRow item={row.item} />
134 ) : (
135 <CommandPaletteResultRow
136 index={row.itemIndex}
137 item={row.item}
138 keybindings={props.keybindings}
139 isActive={props.highlightedItemValue === row.item.value}
140 onExecuteItem={props.onExecuteItem}
141 />
142 )
143 }
144 estimatedItemSize={40}
145 drawDistance={400}
146 onLayout={updateScrollFade}
147 onScroll={updateScrollFade}
148 contentContainerClassName="px-2"
149 className={cn(
150 "min-h-0 scroll-py-6 overflow-x-hidden overscroll-y-contain py-2 [&::-webkit-scrollbar-track]:my-2",
151 getVirtualizedScrollFadeClassName(scrollFade),
152 )}
153 />
154 </CommandListVirtualized>
155 );
156}
157
158export function CommandPaletteTitleIcon(props: { children: ReactNode }) {
159 return <span className="flex h-5 shrink-0 items-center self-start pt-0.5">{props.children}</span>;
160}
161
162function CommandPaletteTitle({
163 item,
164}: {
165 item: Pick<CommandPaletteActionItem | CommandPaletteSubmenuItem, "title" | "titleRanges">;
166}) {
167 const { title } = item;
168 return (
169 <span className="truncate" dir={typeof title === "string" ? textDirection(title) : undefined}>
170 {typeof title === "string" && item.titleRanges ? (
171 <HighlightedSearchText text={title} ranges={item.titleRanges} />
172 ) : (
173 title
174 )}
175 </span>
176 );
177}
178
179/**
180 * Project and environment for a thread row whose second line shows a message
181 * snippet or match hint instead, so similar rows can still be told apart.
182 */
183function ThreadRowContext({
184 item,
185}: {
186 item: CommandPaletteActionItem | CommandPaletteSubmenuItem;
187}) {
188 if (!item.threadSearch || !(item.threadContentMatch || item.matchHint)) return null;
189 // A "Project: …" hint already names the project.
190 const context = [item.threadSearch.projectTitle, item.threadSearch.environmentLabel]
191 .filter((part) => part && part !== item.matchHint?.text)
192 .join(" · ");
193 return context ? (
194 <span className="max-w-[45%] shrink-0 truncate text-muted-foreground/70 text-xs">
195 {context}
196 </span>
197 ) : null;
198}
199
200function DisabledCommandPaletteResultRow(props: {
201 item: CommandPaletteActionItem | CommandPaletteSubmenuItem;
202}) {
203 return (
204 <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">
205 <CommandPaletteTitleIcon>{props.item.icon}</CommandPaletteTitleIcon>
206 {props.item.description || props.item.threadContentMatch ? (
207 <span className="flex min-w-0 flex-1 flex-col">
208 <span className="flex min-w-0 items-center gap-1.5 text-sm text-foreground">
209 {props.item.titleLeadingContent}
210 <CommandPaletteTitle item={props.item} />
211 <ThreadRowContext item={props.item} />
212 </span>
213 {props.item.threadContentMatch ? (
214 <ThreadSearchMatchExcerpt match={props.item.threadContentMatch} />
215 ) : props.item.matchHint ? (
216 <SearchMatchHintLine hint={props.item.matchHint} />
217 ) : props.item.description ? (
218 <span className="min-w-0 text-muted-foreground/70 text-xs">
219 {props.item.description}
220 </span>
221 ) : null}
222 </span>
223 ) : (
224 <span className="flex min-w-0 flex-1 items-center gap-1.5 text-sm text-foreground">
225 {props.item.titleLeadingContent}
226 <CommandPaletteTitle item={props.item} />
227 </span>
228 )}
229 {props.item.titleTrailingContent}
230 </div>
231 );
232}
233
234function CommandPaletteResultRow(props: {
235 index?: number;
236 item: CommandPaletteActionItem | CommandPaletteSubmenuItem;
237 isActive: boolean;
238 keybindings: ResolvedKeybindingsConfig;
239 onExecuteItem: (item: CommandPaletteActionItem | CommandPaletteSubmenuItem) => void;
240}) {
241 const shortcutLabel = props.item.shortcutCommand
242 ? shortcutLabelForCommand(props.keybindings, props.item.shortcutCommand)
243 : null;
244
245 return (
246 <CommandItem
247 {...(props.index === undefined ? {} : { index: props.index })}
248 value={props.item.value}
249 active={props.isActive}
250 onMouseDown={(event) => {
251 event.preventDefault();
252 }}
253 onClick={() => {
254 props.onExecuteItem(props.item);
255 }}
256 >
257 <CommandPaletteTitleIcon>{props.item.icon}</CommandPaletteTitleIcon>
258 {props.item.description || props.item.threadContentMatch ? (
259 <span className="flex min-w-0 flex-1 flex-col">
260 <span className="flex min-w-0 items-center gap-1.5 text-sm text-foreground">
261 {props.item.titleLeadingContent}
262 <CommandPaletteTitle item={props.item} />
263 <ThreadRowContext item={props.item} />
264 </span>
265 {props.item.threadContentMatch ? (
266 <ThreadSearchMatchExcerpt match={props.item.threadContentMatch} />
267 ) : props.item.matchHint ? (
268 <SearchMatchHintLine hint={props.item.matchHint} />
269 ) : props.item.description ? (
270 <span className="min-w-0 text-muted-foreground/70 text-xs">
271 {props.item.description}
272 </span>
273 ) : null}
274 </span>
275 ) : (
276 <span className="flex min-w-0 flex-1 items-center gap-1.5 text-sm text-foreground">
277 {props.item.titleLeadingContent}
278 <CommandPaletteTitle item={props.item} />
279 </span>
280 )}
281 {props.item.titleTrailingContent}
282 {props.item.timestamp ? (
283 <span className="min-w-12 shrink-0 text-right text-xs tabular-nums text-muted-foreground/70">
284 {props.item.timestamp}
285 </span>
286 ) : null}
287 {shortcutLabel ? <CommandShortcut>{shortcutLabel}</CommandShortcut> : null}
288 {props.item.kind === "submenu" ? (
289 <ChevronRightIcon className="-me-0.5 ms-auto size-4 shrink-0 text-muted-foreground/70" />
290 ) : null}
291 </CommandItem>
292 );
293}