-
Notifications
You must be signed in to change notification settings - Fork 54
Expand file tree
/
Copy pathSidebarMenu.tsx
More file actions
488 lines (438 loc) · 16.3 KB
/
Copy pathSidebarMenu.tsx
File metadata and controls
488 lines (438 loc) · 16.3 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
import { folderGroupId } from "@posthog/core/sidebar/groupTasks";
import { isTaskActivelyRunning } from "@posthog/core/sidebar/taskRunning";
import { useHostTRPCClient } from "@posthog/host-router/react";
import { Separator } from "@posthog/quill";
import type { Task } from "@posthog/shared/types";
import {
archiveTasksImperative,
useArchiveCacheKeys,
useArchiveTask,
} from "@posthog/ui/features/archive/useArchiveTask";
import { useCommandCenterStore } from "@posthog/ui/features/command-center/commandCenterStore";
import { useExternalAppAction } from "@posthog/ui/features/external-apps/useExternalAppAction";
import { useFolders } from "@posthog/ui/features/folders/useFolders";
import { useArchivingTasksStore } from "@posthog/ui/features/sidebar/archivingTasksStore";
import { useSidebarStore } from "@posthog/ui/features/sidebar/sidebarStore";
import { useTaskSelectionStore } from "@posthog/ui/features/sidebar/taskSelectionStore";
import { usePinnedTasks } from "@posthog/ui/features/sidebar/usePinnedTasks";
import { useSidebarData } from "@posthog/ui/features/sidebar/useSidebarData";
import { useTaskViewed } from "@posthog/ui/features/sidebar/useTaskViewed";
import { useTaskContextMenu } from "@posthog/ui/features/tasks/useTaskContextMenu";
import { useRenameTask } from "@posthog/ui/features/tasks/useTaskMutations";
import { useTasks } from "@posthog/ui/features/tasks/useTasks";
import { useWorkspaces } from "@posthog/ui/features/workspace/useWorkspace";
import { DotsCircleSpinner } from "@posthog/ui/primitives/DotsCircleSpinner";
import { toast } from "@posthog/ui/primitives/toast";
import {
navigateToCommandCenter,
navigateToTaskDetail,
} from "@posthog/ui/router/navigationBridge";
import { useAppView } from "@posthog/ui/router/useAppView";
import { openTask } from "@posthog/ui/router/useOpenTask";
import { logger } from "@posthog/ui/shell/logger";
import { Box, Flex } from "@radix-ui/themes";
import { useQueryClient } from "@tanstack/react-query";
import { memo, useCallback, useEffect, useMemo, useRef, useState } from "react";
import { ArchiveRunningTaskDialog } from "./ArchiveRunningTaskDialog";
import { SidebarItem } from "./SidebarItem";
import { SidebarNavSection } from "./SidebarNavSection";
import { TaskListView } from "./TaskListView";
import { TasksHeader } from "./TasksHeader";
const log = logger.scope("sidebar-menu");
function SidebarMenuComponent() {
const hostClient = useHostTRPCClient();
const archiveCacheKeys = useArchiveCacheKeys();
const view = useAppView();
// Must mirror useSidebarData's filters so taskMap covers every rendered
// task — otherwise handleTaskClick silently bails for tasks not in the map.
const showAllUsers = useSidebarStore((s) => s.showAllUsers);
const showInternal = useSidebarStore((s) => s.showInternal);
const { data: allTasks = [] } = useTasks({ showAllUsers, showInternal });
const { data: workspaces = {} } = useWorkspaces();
const { markAsViewed } = useTaskViewed();
const { folders, removeFolder } = useFolders();
const openExternalApp = useExternalAppAction();
const { showContextMenu, editingTaskId, setEditingTaskId } =
useTaskContextMenu();
const { archiveTask } = useArchiveTask();
const { renameTask } = useRenameTask();
const { togglePin } = usePinnedTasks();
const sidebarData = useSidebarData({
activeView: view,
});
const taskMap = new Map<string, Task>();
for (const task of allTasks) {
taskMap.set(task.id, task);
}
const commandCenterCells = useCommandCenterStore((s) => s.cells);
const assignTaskToCommandCenter = useCommandCenterStore((s) => s.assignTask);
const previousTaskIdRef = useRef<string | null>(null);
useEffect(() => {
const currentTaskId =
view.type === "task-detail" && view.taskId ? view.taskId : null;
if (
previousTaskIdRef.current &&
previousTaskIdRef.current !== currentTaskId
) {
markAsViewed(previousTaskIdRef.current);
}
if (currentTaskId) {
markAsViewed(currentTaskId);
}
previousTaskIdRef.current = currentTaskId;
}, [view, markAsViewed]);
const queryClient = useQueryClient();
const [archiveConfirm, setArchiveConfirm] = useState<{
taskId: string;
taskTitle: string;
} | null>(null);
const selectedTaskIds = useTaskSelectionStore((s) => s.selectedTaskIds);
const toggleTaskSelection = useTaskSelectionStore(
(s) => s.toggleTaskSelection,
);
const selectRange = useTaskSelectionStore((s) => s.selectRange);
const clearSelection = useTaskSelectionStore((s) => s.clearSelection);
const pruneSelection = useTaskSelectionStore((s) => s.pruneSelection);
const organizeMode = useSidebarStore((s) => s.organizeMode);
const collapsedSections = useSidebarStore((s) => s.collapsedSections);
const allSidebarTasks = useMemo(
() => [...sidebarData.pinnedTasks, ...sidebarData.flatTasks],
[sidebarData.pinnedTasks, sidebarData.flatTasks],
);
const allSidebarTaskIds = useMemo(
() => allSidebarTasks.map((t) => t.id),
[allSidebarTasks],
);
// Ordered list of currently visible task IDs in display order. Used as the
// index for shift-click range selection so it matches what the user sees —
// in by-project mode the chronological flat order would span across project
// groups and pull in unrelated tasks.
const orderedVisibleTaskIds = useMemo(() => {
const ids: string[] = sidebarData.pinnedTasks.map((t) => t.id);
if (organizeMode === "by-project") {
for (const group of sidebarData.groupedTasks) {
if (collapsedSections.has(group.id)) continue;
for (const t of group.tasks) ids.push(t.id);
}
} else {
for (const t of sidebarData.flatTasks) ids.push(t.id);
}
return ids;
}, [
sidebarData.pinnedTasks,
sidebarData.flatTasks,
sidebarData.groupedTasks,
organizeMode,
collapsedSections,
]);
useEffect(() => {
pruneSelection(allSidebarTaskIds);
}, [allSidebarTaskIds, pruneSelection]);
// The active (routed) task is implicitly part of any bulk selection — the
// user expects to see and act on it together with cmd/shift-clicked tasks.
const activeTaskId = sidebarData.activeTaskId;
const effectiveBulkIds = useMemo(() => {
if (selectedTaskIds.length === 0) return [];
if (!activeTaskId) return selectedTaskIds;
if (selectedTaskIds.includes(activeTaskId)) return selectedTaskIds;
return [activeTaskId, ...selectedTaskIds];
}, [activeTaskId, selectedTaskIds]);
const handleTaskClick = (taskId: string, e: React.MouseEvent) => {
// Ignore clicks on a row that's mid-archive.
if (useArchivingTasksStore.getState().isArchiving(taskId)) {
e.preventDefault();
return;
}
if (e.shiftKey) {
e.preventDefault();
selectRange(taskId, orderedVisibleTaskIds, activeTaskId);
return;
}
if (e.metaKey || e.ctrlKey) {
e.preventDefault();
toggleTaskSelection(taskId);
return;
}
clearSelection();
const task = taskMap.get(taskId);
if (task) {
void openTask(task);
} else {
// Sidebar rows come from the summaries path, which can include tasks the
// full-list query (taskMap) doesn't carry. Don't silently bail — navigate
// by id; the task-detail route resolves the task from its own query.
navigateToTaskDetail(taskId);
}
};
const handleBulkContextMenu = useCallback(
async (e: React.MouseEvent, taskIds: string[]) => {
e.preventDefault();
e.stopPropagation();
try {
const result =
await hostClient.contextMenu.showBulkTaskContextMenu.mutate({
taskCount: taskIds.length,
});
if (!result.action) return;
if (result.action.type === "archive") {
const { archived, failed } = await archiveTasksImperative(
taskIds,
queryClient,
archiveCacheKeys,
);
clearSelection();
if (failed === 0) {
toast.success(
`${archived} ${archived === 1 ? "task" : "tasks"} archived`,
);
} else {
toast.error(`${archived} archived, ${failed} failed`);
}
}
} catch (error) {
log.error("Failed to show bulk context menu", error);
}
},
[hostClient, queryClient, clearSelection, archiveCacheKeys],
);
const handleGroupContextMenu = useCallback(
async (groupId: string, e: React.MouseEvent) => {
e.preventDefault();
e.stopPropagation();
const folder = folders.find((f) => folderGroupId(f) === groupId);
if (!folder) return;
try {
const result =
await hostClient.contextMenu.showFolderContextMenu.mutate({
folderName: folder.name,
folderPath: folder.path,
});
if (result.action?.type === "remove") {
await removeFolder(folder.id);
} else if (result.action?.type === "external-app") {
await openExternalApp(
result.action.action,
folder.path,
folder.name,
{ workspace: null },
);
}
} catch (error) {
log.error("Failed to show folder context menu", error);
toast.error("Couldn't perform folder action");
}
},
[folders, removeFolder, hostClient, openExternalApp],
);
const handleTaskContextMenu = (
taskId: string,
e: React.MouseEvent,
isPinned: boolean,
) => {
// Right-clicking a row that's mid-archive is a no-op.
if (useArchivingTasksStore.getState().isArchiving(taskId)) {
e.preventDefault();
return;
}
// Bulk menu when 2+ tasks are in the effective selection (active + cmd/shift-clicked)
// and the right-clicked task is one of them. Otherwise clear and fall through.
if (effectiveBulkIds.length > 1) {
if (effectiveBulkIds.includes(taskId)) {
handleBulkContextMenu(e, effectiveBulkIds);
return;
}
clearSelection();
}
const task = taskMap.get(taskId);
if (task) {
const workspace = workspaces[taskId];
const taskData = allSidebarTasks.find((t) => t.id === taskId);
const isInCommandCenter = commandCenterCells.some(
(id) => id === taskId && taskMap.has(id),
);
const hasEmptyCommandCenterCell = commandCenterCells.some(
(id) => id == null || !taskMap.has(id),
);
showContextMenu(task, e, {
worktreePath: workspace?.worktreePath ?? undefined,
folderPath: workspace?.folderPath ?? undefined,
isPinned,
isSuspended: taskData?.isSuspended,
isInCommandCenter,
hasEmptyCommandCenterCell,
onTogglePin: () => handleTaskTogglePin(taskId),
onArchive: handleTaskArchive,
onArchivePrior: handleArchivePrior,
onAddToCommandCenter: () => {
const cells = useCommandCenterStore.getState().cells;
const idx = cells.findIndex((id) => id == null || !taskMap.has(id));
if (idx !== -1) {
assignTaskToCommandCenter(idx, taskId);
navigateToCommandCenter();
} else {
toast.info("Command center is full");
}
},
});
}
};
// Runs the archive while marking the row as in-flight, so its sidebar entry
// shows a spinner and ignores clicks/pins/right-clicks until it resolves.
// Guards against repeated clicks: a second call while archiving is a no-op.
const runArchive = useCallback(
(taskId: string) => {
const store = useArchivingTasksStore.getState();
if (store.isArchiving(taskId)) return;
store.startArchiving(taskId);
void archiveTask({ taskId })
.catch((error) => {
log.error("Failed to archive task", error);
toast.error("Failed to archive task");
})
.finally(() => {
useArchivingTasksStore.getState().stopArchiving(taskId);
});
},
[archiveTask],
);
const handleTaskArchive = useCallback(
(taskId: string) => {
if (useArchivingTasksStore.getState().isArchiving(taskId)) return;
const task = allSidebarTasks.find((t) => t.id === taskId);
if (task && isTaskActivelyRunning(task)) {
setArchiveConfirm({ taskId, taskTitle: task.title });
return;
}
runArchive(taskId);
},
[allSidebarTasks, runArchive],
);
const handleConfirmArchive = useCallback(() => {
if (!archiveConfirm) return;
const { taskId } = archiveConfirm;
setArchiveConfirm(null);
runArchive(taskId);
}, [archiveConfirm, runArchive]);
const handleTaskTogglePin = useCallback(
(taskId: string) => {
// Pinning/unpinning a row that's mid-archive is a no-op.
if (useArchivingTasksStore.getState().isArchiving(taskId)) return;
togglePin(taskId);
},
[togglePin],
);
const handleArchivePrior = useCallback(
async (taskId: string) => {
const allVisible = [...sidebarData.pinnedTasks, ...sidebarData.flatTasks];
const clickedTask = allVisible.find((t) => t.id === taskId);
if (!clickedTask) return;
const threshold = clickedTask.lastActivityAt;
const priorTaskIds = allVisible
.filter((t) => t.id !== taskId && t.lastActivityAt < threshold)
.map((t) => t.id);
if (priorTaskIds.length === 0) {
toast.info("No older tasks to archive");
return;
}
const { archived, failed } = await archiveTasksImperative(
priorTaskIds,
queryClient,
archiveCacheKeys,
);
if (failed === 0) {
toast.success(
`${archived} ${archived === 1 ? "task" : "tasks"} archived`,
);
} else {
toast.error(`${archived} archived, ${failed} failed`);
}
},
[
sidebarData.pinnedTasks,
sidebarData.flatTasks,
queryClient,
archiveCacheKeys,
],
);
const handleTaskDoubleClick = useCallback(
(taskId: string) => {
setEditingTaskId(taskId);
},
[setEditingTaskId],
);
const handleTaskEditSubmit = useCallback(
async (taskId: string, currentTitle: string, newTitle: string) => {
setEditingTaskId(null);
try {
await renameTask({
taskId,
currentTitle,
newTitle,
});
} catch (error) {
log.error("Failed to rename task", error);
}
},
[renameTask, setEditingTaskId],
);
const handleTaskEditCancel = useCallback(() => {
setEditingTaskId(null);
}, [setEditingTaskId]);
return (
<Box
height="100%"
position="relative"
id="side-bar-menu"
className="flex min-h-0 flex-col"
>
{/* Derive the command-center count from data SidebarMenu already holds,
so the nested nav section doesn't open its own task subscription. */}
<SidebarNavSection
commandCenterActiveCount={commandCenterCells.reduce(
(count, taskId) =>
taskId != null && taskMap.has(taskId) ? count + 1 : count,
0,
)}
/>
<Separator className="mx-2 my-2 shrink-0" />
<TasksHeader />
<div className="min-h-0 flex-1 overflow-y-auto overflow-x-hidden">
<Flex direction="column" className="gap-px px-2 pb-2">
{sidebarData.isLoading ? (
<SidebarItem
depth={0}
icon={<DotsCircleSpinner size={12} className="text-gray-10" />}
label="Loading tasks..."
disabled
/>
) : (
<TaskListView
pinnedTasks={sidebarData.pinnedTasks}
flatTasks={sidebarData.flatTasks}
groupedTasks={sidebarData.groupedTasks}
activeTaskId={sidebarData.activeTaskId}
editingTaskId={editingTaskId}
selectedTaskIds={effectiveBulkIds}
onTaskClick={handleTaskClick}
onTaskDoubleClick={handleTaskDoubleClick}
onTaskContextMenu={handleTaskContextMenu}
onTaskArchive={handleTaskArchive}
onTaskTogglePin={handleTaskTogglePin}
onTaskEditSubmit={handleTaskEditSubmit}
onTaskEditCancel={handleTaskEditCancel}
onGroupContextMenu={handleGroupContextMenu}
hasMore={sidebarData.hasMore}
/>
)}
</Flex>
</div>
<ArchiveRunningTaskDialog
open={archiveConfirm !== null}
taskTitle={archiveConfirm?.taskTitle ?? ""}
onConfirm={handleConfirmArchive}
onCancel={() => setArchiveConfirm(null)}
/>
</Box>
);
}
export const SidebarMenu = memo(SidebarMenuComponent);