-
Notifications
You must be signed in to change notification settings - Fork 50
Expand file tree
/
Copy pathCommandMenu.tsx
More file actions
568 lines (544 loc) · 18.4 KB
/
Copy pathCommandMenu.tsx
File metadata and controls
568 lines (544 loc) · 18.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
import { CaretLeftIcon, CaretRightIcon, HashIcon } from "@phosphor-icons/react";
import { resolveService } from "@posthog/di/container";
import {
HOST_TRPC_CLIENT,
type HostTrpcClient,
} from "@posthog/host-router/client";
import {
Autocomplete,
AutocompleteCollection,
AutocompleteGroup,
AutocompleteInput,
AutocompleteItem,
AutocompleteLabel,
AutocompleteList,
AutocompleteStatus,
Dialog,
DialogContent,
Kbd,
} from "@posthog/quill";
import { PROJECT_BLUEBIRD_FLAG } from "@posthog/shared";
import {
ANALYTICS_EVENTS,
type CommandMenuAction,
} from "@posthog/shared/analytics-events";
import type { Task } from "@posthog/shared/domain-types";
import { useChannels } from "@posthog/ui/features/canvas/hooks/useChannels";
import { useTaskChannelMap } from "@posthog/ui/features/canvas/hooks/useTaskChannelMap";
import { useReviewNavigationStore } from "@posthog/ui/features/code-review/reviewNavigationStore";
import { CommandKeyHints } from "@posthog/ui/features/command/CommandKeyHints";
import { useFileSearchStore } from "@posthog/ui/features/command/fileSearchStore";
import {
formatHotkeyParts,
SHORTCUTS,
} from "@posthog/ui/features/command/keyboard-shortcuts";
import { useFileSearchContext } from "@posthog/ui/features/command/useFileSearchContext";
import { useFeatureFlag } from "@posthog/ui/features/feature-flags/useFeatureFlag";
import { useFolders } from "@posthog/ui/features/folders/useFolders";
import {
closeSettings,
openSettings,
} from "@posthog/ui/features/settings/hooks/useOpenSettings";
import { TaskIcon } from "@posthog/ui/features/sidebar/components/items/TaskIcon";
import { useSidebarStore } from "@posthog/ui/features/sidebar/sidebarStore";
import { useTaskPrStatus } from "@posthog/ui/features/sidebar/useTaskPrStatus";
import { useTasks } from "@posthog/ui/features/tasks/useTasks";
import {
goBackInHistory,
goForwardInHistory,
navigateToChannel,
} from "@posthog/ui/router/navigationBridge";
import { useAppView } from "@posthog/ui/router/useAppView";
import { openTask, openTaskInput } from "@posthog/ui/router/useOpenTask";
import { track } from "@posthog/ui/shell/analytics";
import { showLogFolder } from "@posthog/ui/shell/openExternal";
import { useThemeStore } from "@posthog/ui/shell/themeStore";
import {
DesktopIcon,
FileTextIcon,
GearIcon,
HomeIcon,
MagnifyingGlassIcon,
MoonIcon,
ReloadIcon,
SunIcon,
ViewVerticalIcon,
ZoomInIcon,
ZoomOutIcon,
} from "@radix-ui/react-icons";
import { useCallback, useEffect, useMemo, useState } from "react";
interface CommandMenuProps {
open: boolean;
onOpenChange: (open: boolean) => void;
}
type Command = {
id: string;
label: string;
/** Muted trailing detail shown after a middot, e.g. a task's channel. */
detail?: string;
keywords?: string;
icon: React.ReactNode;
action: CommandMenuAction;
/** Channel in scope for the bluebird open-channel / open-task actions. */
channelId?: string;
/** Hotkey string (e.g. "mod+b") shown right-aligned when present. */
shortcut?: string;
onRun: () => void;
};
type CommandSection = { label: string; items: Command[] };
/**
* Task icon for the command palette. Renders the same shared `TaskIcon` as
* the sidebar — cloud run status, PR/branch status, etc. — deriving its
* inputs from the raw task and a per-task PR-status query.
*/
function TaskCommandIcon({ task }: { task: Task }) {
const { prState, hasDiff } = useTaskPrStatus({
id: task.id,
cloudPrUrl: null,
taskRunEnvironment: task.latest_run?.environment,
});
const stateSlackThreadUrl = (
task.latest_run?.state as { slack_thread_url?: unknown } | undefined
)?.slack_thread_url;
const slackThreadUrl =
typeof stateSlackThreadUrl === "string" ? stateSlackThreadUrl : undefined;
return (
<TaskIcon
workspaceMode={task.latest_run?.environment}
taskRunStatus={task.latest_run?.status}
originProduct={task.origin_product}
slackThreadUrl={slackThreadUrl}
prState={prState}
hasDiff={hasDiff}
/>
);
}
export function CommandMenu({ open, onOpenChange }: CommandMenuProps) {
const openSettingsDialog = openSettings;
const closeSettingsDialog = closeSettings;
const { folders } = useFolders();
// Channels (and the task→channel detail) are a Project Bluebird feature. Gate
// the channel fetches behind the flag so they never reach ungated users.
const bluebirdEnabled = useFeatureFlag(
PROJECT_BLUEBIRD_FLAG,
import.meta.env.DEV,
);
const { channels } = useChannels({ enabled: bluebirdEnabled });
const taskChannelMap = useTaskChannelMap(channels, {
enabled: open && bluebirdEnabled,
});
const { theme, setTheme } = useThemeStore();
const toggleLeftSidebar = useSidebarStore((state) => state.toggle);
const view = useAppView();
const setReviewMode = useReviewNavigationStore(
(state) => state.setReviewMode,
);
const getReviewMode = useReviewNavigationStore(
(state) => state.getReviewMode,
);
const { data: tasks = [] } = useTasks();
const [query, setQuery] = useState("");
const { repoPath } = useFileSearchContext();
const canSearchFiles = !!repoPath;
const openFilePicker = useFileSearchStore((state) => state.openPicker);
const [systemPrefersDark, setSystemPrefersDark] = useState(
() => window.matchMedia("(prefers-color-scheme: dark)").matches,
);
useEffect(() => {
const mq = window.matchMedia("(prefers-color-scheme: dark)");
const onChange = (e: MediaQueryListEvent) =>
setSystemPrefersDark(e.matches);
mq.addEventListener("change", onChange);
return () => mq.removeEventListener("change", onChange);
}, []);
// The review panel lives in the task-detail view, so the command only makes
// sense when a task is open. Elsewhere (e.g. the new-task screen) it would be
// a no-op, so we omit it below rather than show a dead entry.
const reviewTaskId = view.type === "task-detail" ? view.taskId : undefined;
const openReviewPanel = useCallback(() => {
if (!reviewTaskId) return;
const mode = getReviewMode(reviewTaskId);
if (mode === "closed") {
setReviewMode(reviewTaskId, "split");
}
}, [reviewTaskId, getReviewMode, setReviewMode]);
useEffect(() => {
if (open) {
track(ANALYTICS_EVENTS.COMMAND_MENU_OPENED);
} else {
setQuery("");
}
}, [open]);
const themeOptions = useMemo<Command[]>(() => {
const options: Command[] = [];
if (theme !== "light") {
options.push({
id: "switch-theme-light",
label: "Switch to light mode",
keywords: "theme appearance",
icon: <SunIcon className="h-3 w-3 text-gray-11" />,
action: "toggle-theme",
onRun: () => setTheme("light"),
});
}
if (theme !== "dark") {
options.push({
id: "switch-theme-dark",
label: "Switch to dark mode",
keywords: "theme appearance",
icon: <MoonIcon className="h-3 w-3 text-gray-11" />,
action: "toggle-theme",
onRun: () => setTheme("dark"),
});
}
const systemMatchesCurrent =
(theme === "dark" && systemPrefersDark) ||
(theme === "light" && !systemPrefersDark);
if (theme !== "system" && !systemMatchesCurrent) {
options.push({
id: "switch-theme-system",
label: "Switch to system theme",
keywords: "theme appearance auto",
icon: <DesktopIcon className="h-3 w-3 text-gray-11" />,
action: "toggle-theme",
onRun: () => setTheme("system"),
});
}
return options;
}, [theme, setTheme, systemPrefersDark]);
const commandSections = useMemo<CommandSection[]>(() => {
const navigation: Command[] = [
{
id: "home",
label: "Home",
icon: <HomeIcon className="h-3 w-3 text-gray-11" />,
action: "home",
onRun: () => {
closeSettingsDialog();
openTaskInput();
},
},
{
id: "settings",
label: "Settings",
icon: <GearIcon className="h-3 w-3 text-gray-11" />,
action: "settings",
shortcut: SHORTCUTS.SETTINGS,
onRun: () => openSettingsDialog(),
},
{
id: "go-back",
label: "Go back",
keywords: "navigate history previous",
icon: <CaretLeftIcon size={12} className="text-gray-11" />,
action: "go-back",
shortcut: SHORTCUTS.GO_BACK,
onRun: goBackInHistory,
},
{
id: "go-forward",
label: "Go forward",
keywords: "navigate history next",
icon: <CaretRightIcon size={12} className="text-gray-11" />,
action: "go-forward",
shortcut: SHORTCUTS.GO_FORWARD,
onRun: goForwardInHistory,
},
];
const actions: Command[] = [
...themeOptions,
{
id: "toggle-left-sidebar",
label: "Toggle left sidebar",
icon: <ViewVerticalIcon className="h-3 w-3 text-gray-11" />,
action: "toggle-left-sidebar",
shortcut: SHORTCUTS.TOGGLE_LEFT_SIDEBAR,
onRun: toggleLeftSidebar,
},
...(reviewTaskId
? [
{
id: "open-review-panel",
label: "Open review panel",
icon: (
<ViewVerticalIcon className="h-3 w-3 rotate-180 text-gray-11" />
),
action: "open-review-panel" as CommandMenuAction,
shortcut: SHORTCUTS.TOGGLE_REVIEW_PANEL,
onRun: openReviewPanel,
},
]
: []),
{
id: "new-task",
label: "New task",
keywords: "create",
icon: <FileTextIcon className="h-3 w-3 text-gray-11" />,
action: "new-task",
shortcut: SHORTCUTS.NEW_TASK,
onRun: () => {
closeSettingsDialog();
openTaskInput();
},
},
];
if (canSearchFiles) {
actions.push({
id: "search-files",
label: "Search files",
keywords: "file find open",
icon: <MagnifyingGlassIcon className="h-3 w-3 text-gray-11" />,
action: "search-files",
onRun: openFilePicker,
});
}
const developer: Command[] = [
{
id: "show-log-folder",
label: "Show log folder",
keywords: "logs debug files finder",
icon: <FileTextIcon className="h-3 w-3 text-gray-11" />,
action: "show-log-folder",
onRun: showLogFolder,
},
{
id: "reload-window",
label: "Reload window",
keywords: "refresh restart",
icon: <ReloadIcon className="h-3 w-3 text-gray-11" />,
action: "reload-window",
shortcut: SHORTCUTS.RELOAD_WINDOW,
onRun: () => window.location.reload(),
},
];
const view: Command[] = [
{
id: "zoom-in",
label: "Zoom in",
keywords: "zoom increase larger",
icon: <ZoomInIcon className="h-3 w-3 text-gray-11" />,
action: "zoom-in",
shortcut: SHORTCUTS.ZOOM_IN,
onRun: () =>
void resolveService<HostTrpcClient>(
HOST_TRPC_CLIENT,
).os.zoomIn.mutate(),
},
{
id: "zoom-out",
label: "Zoom out",
keywords: "zoom decrease smaller",
icon: <ZoomOutIcon className="h-3 w-3 text-gray-11" />,
action: "zoom-out",
shortcut: SHORTCUTS.ZOOM_OUT,
onRun: () =>
void resolveService<HostTrpcClient>(
HOST_TRPC_CLIENT,
).os.zoomOut.mutate(),
},
{
id: "zoom-reset",
label: "Reset zoom",
keywords: "zoom actual size default",
icon: <MagnifyingGlassIcon className="h-3 w-3 text-gray-11" />,
action: "zoom-reset",
shortcut: SHORTCUTS.RESET_ZOOM,
onRun: () =>
void resolveService<HostTrpcClient>(
HOST_TRPC_CLIENT,
).os.resetZoom.mutate(),
},
];
const out: CommandSection[] = [
{ label: "Actions", items: actions },
{ label: "Navigation", items: navigation },
{ label: "View", items: view },
{ label: "Developer", items: developer },
];
if (folders.length > 0) {
out.push({
label: "New task in folder",
items: folders.map((folder) => ({
id: `new-task-folder-${folder.id}`,
label: `New task in ${folder.name}`,
keywords: folder.path,
icon: <FileTextIcon className="h-3 w-3 text-gray-11" />,
action: "new-task",
onRun: () => {
closeSettingsDialog();
openTaskInput(folder.id);
},
})),
});
}
return out;
}, [
folders,
themeOptions,
openSettingsDialog,
closeSettingsDialog,
toggleLeftSidebar,
openReviewPanel,
reviewTaskId,
canSearchFiles,
openFilePicker,
]);
const taskSections = useMemo<CommandSection[]>(() => {
if (tasks.length === 0) return [];
return [
{
label: "Tasks",
items: tasks.map((task) => {
const channel = taskChannelMap.get(task.id);
return {
id: `task-${task.id}`,
label: task.title,
detail: channel?.name,
// Include the channel name so searching it surfaces filed tasks.
keywords: channel?.name,
icon: <TaskCommandIcon task={task} />,
action: "open-task" as CommandMenuAction,
channelId: bluebirdEnabled ? channel?.id : undefined,
onRun: () => {
closeSettingsDialog();
// Bluebird: a task filed to a channel opens in the channel-
// organized view under /website, keeping the channels chrome.
// Otherwise fall back to the /code task detail.
const channelTarget =
bluebirdEnabled && channel
? { channelId: channel.id }
: undefined;
void openTask(task, channelTarget);
},
};
}),
},
];
}, [tasks, taskChannelMap, bluebirdEnabled, closeSettingsDialog]);
const channelSections = useMemo<CommandSection[]>(() => {
if (channels.length === 0) return [];
return [
{
label: "Channels",
items: channels.map((channel) => ({
id: `channel-${channel.id}`,
label: channel.name,
keywords: "channel",
icon: <HashIcon size={12} className="text-gray-11" />,
action: "open-channel" as CommandMenuAction,
channelId: channel.id,
onRun: () => {
closeSettingsDialog();
navigateToChannel(channel.id);
},
})),
},
];
}, [channels, closeSettingsDialog]);
// Commands, channels, and tasks share a single filterable list.
const sections = useMemo(
() => [...commandSections, ...channelSections, ...taskSections],
[commandSections, channelSections, taskSections],
);
const allCommands = useMemo(
() => sections.flatMap((s) => s.items),
[sections],
);
const handleSelect = (id: string | null): void => {
if (id === null) return;
const cmd = allCommands.find((c) => c.id === id);
if (!cmd) return;
track(ANALYTICS_EVENTS.COMMAND_MENU_ACTION, {
action_type: cmd.action,
channel_id: cmd.channelId,
});
cmd.onRun();
onOpenChange(false);
setQuery("");
};
return (
<Dialog open={open} onOpenChange={onOpenChange}>
<DialogContent
className="w-[720px] max-w-[90vw] gap-0 p-0"
showCloseButton={false}
>
<Autocomplete<Command>
inline
defaultOpen
items={sections}
value={query}
autoHighlight="always"
onValueChange={(val, eventDetails) => {
if (eventDetails.reason !== "input-change") return;
if (typeof val === "string") {
setQuery(val);
}
}}
filter={(cmd, q) => {
if (!q) return true;
const haystack = `${cmd.label} ${cmd.keywords ?? ""}`.toLowerCase();
return haystack.includes(q.toLowerCase());
}}
>
<AutocompleteInput
placeholder={
bluebirdEnabled
? "Search commands, channels, and tasks…"
: "Search commands and tasks…"
}
autoFocus
showClear
/>
<AutocompleteStatus
emptyContent={
<span>
No results for <strong>"{query}"</strong>
</span>
}
/>
<AutocompleteList className="max-h-[60vh]">
{(section: CommandSection) => (
<AutocompleteGroup key={section.label} items={section.items}>
<AutocompleteLabel>{section.label}</AutocompleteLabel>
<AutocompleteCollection>
{(cmd: Command) => (
<AutocompleteItem
key={cmd.id}
value={cmd.id}
onClick={() => handleSelect(cmd.id)}
// Long task names wrap instead of truncating, so the
// item must grow: min-height, not a fixed height. Quill
// wraps our children in an inner content span; force it to
// fill the row (so a trailing shortcut can `ml-auto` to the
// end) and let it overflow visibly so the shortcut Kbd
// boxes aren't clipped by the wrapper's `truncate`.
className="flex h-auto! min-h-7 w-full items-center gap-2 py-1.5 pr-2 text-left [&>span]:w-full [&>span]:overflow-visible"
>
{cmd.icon}
<span className="wrap-break-word min-w-0 whitespace-normal">
{cmd.label}
</span>
{cmd.detail && (
<span className="shrink-0 text-gray-9">
· #{cmd.detail}
</span>
)}
{cmd.shortcut && (
<span className="ml-auto flex shrink-0 items-center gap-2 pl-2">
{formatHotkeyParts(cmd.shortcut).map((part) => (
<Kbd key={part}>{part}</Kbd>
))}
</span>
)}
</AutocompleteItem>
)}
</AutocompleteCollection>
</AutocompleteGroup>
)}
</AutocompleteList>
</Autocomplete>
<CommandKeyHints />
</DialogContent>
</Dialog>
);
}