The best way to control Claude Code, Codex and more from any computer or phone

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