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