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