Open History to see the last commit
1import { startPaletteThreadDrag } from "./CommandPalette.drag";
2import { useLegendListRef } from "~/hooks/useLegendListRef";
3import { useStableCallback } from "~/hooks/useStableCallback";
4import { type ResolvedKeybindingsConfig } from "@t3tools/contracts";
5import { LegendList, type LegendListRef } from "@legendapp/list/react";
6import { ChevronRightIcon } from "lucide-react";
7import { type ReactNode, type RefObject, useState } from "react";
8import { T } from "gt-react";
9import { cn } from "~/lib/utils";
10import { textDirection } from "~/textDirection";
11import { shortcutLabelForCommand } from "../keybindings";
12import {
13 type CommandPaletteActionItem,
14 type CommandPaletteGroup,
15 type CommandPaletteRow,
16 type CommandPaletteSubmenuItem,
17} from "./CommandPalette.logic";
18import {
19 CommandCollection,
20 CommandGroup,
21 CommandGroupLabel,
22 CommandItem,
23 CommandList,
24 CommandListHeading,
25 CommandListVirtualized,
26 CommandShortcut,
27} from "./ui/command";
28import { getVirtualizedScrollFadeClassName } from "./ui/scroll-area";
29import { ProjectPinButton } from "./ProjectPinButton";
30import { SearchMatchHintLine, ThreadSearchMatchExcerpt } from "./ThreadSearchMatch";
31
32interface CommandPaletteResultsProps {
33 emptyStateMessage?: string;
34 groups: ReadonlyArray<CommandPaletteGroup>;
35 highlightedItemValue?: string | null;
36 isActionsOnly: boolean;
37 keybindings: ResolvedKeybindingsConfig;
38 onExecuteItem: (item: CommandPaletteActionItem | CommandPaletteSubmenuItem) => void;
39}
40
41function CommandPaletteEmptyState(props: { emptyStateMessage?: string; isActionsOnly: boolean }) {
42 return (
43 <div className="py-10 text-center text-sm text-muted-foreground">
44 {props.emptyStateMessage ??
45 (props.isActionsOnly ? (
46 <T>No matching actions.</T>
47 ) : (
48 <T>No matching commands, projects, or threads.</T>
49 ))}
50 </div>
51 );
52}
53
54export function CommandPaletteResults(props: CommandPaletteResultsProps) {
55 if (props.groups.length === 0) {
56 return <CommandPaletteEmptyState {...props} />;
57 }
58
59 return (
60 <CommandList>
61 {props.groups.map((group) => (
62 <CommandGroup items={group.items} key={group.value}>
63 {group.label ? <CommandGroupLabel>{group.label}</CommandGroupLabel> : null}
64 <CommandCollection>
65 {(item) =>
66 item.disabled ? (
67 <DisabledCommandPaletteResultRow item={item} key={item.value} />
68 ) : (
69 <CommandPaletteResultRow
70 item={item}
71 key={item.value}
72 keybindings={props.keybindings}
73 isActive={props.highlightedItemValue === item.value}
74 onExecuteItem={props.onExecuteItem}
75 />
76 )
77 }
78 </CommandCollection>
79 </CommandGroup>
80 ))}
81 </CommandList>
82 );
83}
84
85export function scrollCommandPaletteRowIntoView(
86 list: LegendListRef | null,
87 rowIndex: number,
88 isFirstItem: boolean,
89) {
90 if (isFirstItem) {
91 void list?.scrollToOffset({ offset: 0, animated: false });
92 return;
93 }
94 void list?.scrollIndexIntoView({
95 index: rowIndex,
96 animated: false,
97 viewportMargin: { start: 24, end: 24 },
98 });
99}
100
101// Keeps a mounted row's old data when it shows the same item, so typing re-renders only the
102// rows whose item or position changed.
103function commandPaletteRowsAreEqual(previous: CommandPaletteRow, next: CommandPaletteRow) {
104 if (previous.kind === "label" || next.kind === "label") {
105 return (
106 previous.kind === "label" &&
107 next.kind === "label" &&
108 previous.label === next.label &&
109 previous.first === next.first
110 );
111 }
112 return previous.item === next.item && previous.itemIndex === next.itemIndex;
113}
114
115interface CommandPaletteVirtualizedResultsProps extends Omit<CommandPaletteResultsProps, "groups"> {
116 rows: ReadonlyArray<CommandPaletteRow>;
117 listRef: RefObject<LegendListRef | null>;
118}
119
120/** Pass flat items with virtualized to Command, scroll highlights via listRef, and handle Enter for
121 * unmounted rows. */
122export function CommandPaletteVirtualizedResults(props: CommandPaletteVirtualizedResultsProps) {
123 const { listRef } = props;
124 // The palette rebuilds its handler every render; a stable one keeps rows from re-rendering.
125 const onExecuteItem = useStableCallback(props.onExecuteItem);
126 const [scrollFade, setScrollFade] = useState({ top: false, bottom: false });
127 const updateScrollFade = () => {
128 const metrics = listRef.current?.getState();
129 if (!metrics) return;
130 const top = !metrics.isAtStart;
131 const bottom = !metrics.isAtEnd;
132 setScrollFade((current) =>
133 current.top === top && current.bottom === bottom ? current : { top, bottom },
134 );
135 };
136 const scrollRef = useLegendListRef(listRef, updateScrollFade);
137 // Kept rows re-render only when this changes, so it holds everything rows read besides their item.
138 const rowInputs = {
139 highlightedItemValue: props.highlightedItemValue,
140 keybindings: props.keybindings,
141 };
142
143 if (props.rows.length === 0) {
144 return <CommandPaletteEmptyState {...props} />;
145 }
146
147 return (
148 <CommandListVirtualized>
149 <LegendList<CommandPaletteRow>
150 ref={scrollRef}
151 data={props.rows}
152 initialScrollOffset={0}
153 keyExtractor={(row) => row.key}
154 itemsAreEqual={commandPaletteRowsAreEqual}
155 getItemType={(row) => row.kind}
156 extraData={rowInputs}
157 renderItem={({ item: row }) =>
158 row.kind === "label" ? (
159 <div className={row.first ? undefined : "pt-1.5"}>
160 <CommandListHeading>{row.label}</CommandListHeading>
161 </div>
162 ) : row.itemIndex === null ? (
163 <DisabledCommandPaletteResultRow item={row.item} />
164 ) : (
165 <CommandPaletteResultRow
166 index={row.itemIndex}
167 item={row.item}
168 keybindings={props.keybindings}
169 isActive={props.highlightedItemValue === row.item.value}
170 onExecuteItem={onExecuteItem}
171 />
172 )
173 }
174 estimatedItemSize={40}
175 drawDistance={400}
176 onLayout={updateScrollFade}
177 onScroll={updateScrollFade}
178 onReady={updateScrollFade}
179 // Legend counts style padding (not class padding) in its size, end state and row positions.
180 style={{ paddingTop: 8, paddingBottom: 8 }}
181 contentContainerClassName="px-2"
182 className={cn(
183 "min-h-0 scroll-py-6 overflow-x-hidden overscroll-y-contain [&::-webkit-scrollbar-track]:my-2",
184 getVirtualizedScrollFadeClassName(scrollFade),
185 )}
186 />
187 </CommandListVirtualized>
188 );
189}
190
191export function CommandPaletteTitleIcon(props: { children: ReactNode }) {
192 return <span className="flex h-5 shrink-0 items-center self-start pt-0.5">{props.children}</span>;
193}
194
195function CommandPaletteTitle({
196 item,
197}: {
198 item: Pick<CommandPaletteActionItem | CommandPaletteSubmenuItem, "title">;
199}) {
200 const { title } = item;
201 return (
202 <span className="truncate" dir={typeof title === "string" ? textDirection(title) : undefined}>
203 {title}
204 </span>
205 );
206}
207
208/**
209 * Project and environment for a thread row whose second line shows a message
210 * snippet or match hint instead, so similar rows can still be told apart.
211 */
212function ThreadRowContext({
213 item,
214}: {
215 item: CommandPaletteActionItem | CommandPaletteSubmenuItem;
216}) {
217 if (!item.threadSearch || !(item.threadContentMatch || item.matchHint)) return null;
218 // A "Project: …" hint already names the project.
219 const context = [item.threadSearch.projectTitle, item.threadSearch.environmentLabel]
220 .filter((part) => part && part !== item.matchHint?.text)
221 .join(" · ");
222 return context ? (
223 <span className="max-w-[45%] shrink-0 truncate text-muted-foreground/70 text-xs">
224 {context}
225 </span>
226 ) : null;
227}
228
229function DisabledCommandPaletteResultRow(props: {
230 item: CommandPaletteActionItem | CommandPaletteSubmenuItem;
231}) {
232 return (
233 <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">
234 <CommandPaletteTitleIcon>{props.item.icon}</CommandPaletteTitleIcon>
235 {props.item.description || props.item.threadContentMatch ? (
236 <span className="flex min-w-0 flex-1 flex-col">
237 <span className="flex min-w-0 items-center gap-1.5 text-sm text-foreground">
238 {props.item.titleLeadingContent}
239 <CommandPaletteTitle item={props.item} />
240 <ThreadRowContext item={props.item} />
241 </span>
242 {props.item.threadContentMatch ? (
243 <ThreadSearchMatchExcerpt match={props.item.threadContentMatch} />
244 ) : props.item.matchHint ? (
245 <SearchMatchHintLine hint={props.item.matchHint} />
246 ) : props.item.description ? (
247 <span className="min-w-0 text-muted-foreground/70 text-xs">
248 {props.item.description}
249 </span>
250 ) : null}
251 </span>
252 ) : (
253 <span className="flex min-w-0 flex-1 items-center gap-1.5 text-sm text-foreground">
254 {props.item.titleLeadingContent}
255 <CommandPaletteTitle item={props.item} />
256 </span>
257 )}
258 {props.item.titleTrailingContent}
259 </div>
260 );
261}
262
263function CommandPaletteResultRow(props: {
264 index?: number;
265 item: CommandPaletteActionItem | CommandPaletteSubmenuItem;
266 isActive: boolean;
267 keybindings: ResolvedKeybindingsConfig;
268 onExecuteItem: (item: CommandPaletteActionItem | CommandPaletteSubmenuItem) => void;
269}) {
270 const shortcutLabel = props.item.shortcutCommand
271 ? shortcutLabelForCommand(props.keybindings, props.item.shortcutCommand)
272 : null;
273
274 return (
275 <CommandItem
276 {...(props.index === undefined ? {} : { index: props.index })}
277 value={props.item.value}
278 active={props.isActive}
279 {...(props.item.kind === "action" && props.item.checked !== undefined
280 ? { "aria-checked": props.item.checked }
281 : {})}
282 onPointerDown={(event) => {
283 if (props.item.threadRef) {
284 startPaletteThreadDrag(
285 event.nativeEvent,
286 props.item.threadRef,
287 props.item.searchTitle ??
288 (typeof props.item.title === "string" ? props.item.title : "Thread"),
289 );
290 }
291 }}
292 onMouseDown={(event) => {
293 event.preventDefault();
294 }}
295 onClick={() => {
296 props.onExecuteItem(props.item);
297 }}
298 >
299 <CommandPaletteTitleIcon>{props.item.icon}</CommandPaletteTitleIcon>
300 {props.item.description || props.item.threadContentMatch ? (
301 <span className="flex min-w-0 flex-1 flex-col">
302 <span className="flex min-w-0 items-center gap-1.5 text-sm text-foreground">
303 {props.item.titleLeadingContent}
304 <CommandPaletteTitle item={props.item} />
305 <ThreadRowContext item={props.item} />
306 </span>
307 {props.item.threadContentMatch ? (
308 <ThreadSearchMatchExcerpt match={props.item.threadContentMatch} />
309 ) : props.item.matchHint ? (
310 <SearchMatchHintLine hint={props.item.matchHint} />
311 ) : props.item.description ? (
312 <span className="min-w-0 text-muted-foreground/70 text-xs">
313 {props.item.description}
314 </span>
315 ) : null}
316 </span>
317 ) : (
318 <span className="flex min-w-0 flex-1 items-center gap-1.5 text-sm text-foreground">
319 {props.item.titleLeadingContent}
320 <CommandPaletteTitle item={props.item} />
321 </span>
322 )}
323 {props.item.titleTrailingContent}
324 {props.item.kind === "action" && props.item.pin ? (
325 <ProjectPinButton
326 name={props.item.pin.name}
327 pinned={props.item.pin.pinned}
328 onToggle={props.item.pin.toggle}
329 shortcutLabel={shortcutLabelForCommand(props.keybindings, "thread.pin")}
330 />
331 ) : null}
332 {props.item.timestamp ? (
333 <span className="min-w-12 shrink-0 text-right text-xs tabular-nums text-muted-foreground/70">
334 {props.item.timestamp}
335 </span>
336 ) : null}
337 {shortcutLabel ? <CommandShortcut>{shortcutLabel}</CommandShortcut> : null}
338 {props.item.kind === "submenu" ? (
339 <ChevronRightIcon className="-me-0.5 ms-auto size-4 shrink-0 text-muted-foreground/70" />
340 ) : null}
341 </CommandItem>
342 );
343}