-
Notifications
You must be signed in to change notification settings - Fork 42
Expand file tree
/
Copy pathuseTaskMenuItems.ts
More file actions
99 lines (82 loc) · 2.26 KB
/
useTaskMenuItems.ts
File metadata and controls
99 lines (82 loc) · 2.26 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
import { getTaskPermissions, getTaskLabel, type Task } from "@repo/shared";
import { logger } from "@repo/webview-shared/logger";
import { useMutation } from "@tanstack/react-query";
import { useTasksApi } from "../hooks/useTasksApi";
import type { TaskLoadingState } from "../utils/taskLoadingState";
import type { ActionMenuItem } from "./ActionMenu";
interface UseTaskMenuItemsOptions {
task: Task;
}
interface UseTaskMenuItemsResult {
menuItems: ActionMenuItem[];
action: TaskLoadingState;
}
export function useTaskMenuItems({
task,
}: UseTaskMenuItemsOptions): UseTaskMenuItemsResult {
const api = useTasksApi();
const { canPause, canResume } = getTaskPermissions(task);
const taskName = getTaskLabel(task);
const mutation = useMutation({
mutationFn: ({
fn,
}: {
action: NonNullable<TaskLoadingState>;
fn: () => Promise<void>;
}) => fn(),
onError: (err, { action }) =>
logger.error(`Failed while ${action} task`, err),
});
const action: TaskLoadingState = mutation.isPending
? mutation.variables.action
: null;
function run(
actionName: NonNullable<TaskLoadingState>,
fn: () => Promise<void>,
) {
if (!mutation.isPending) {
mutation.mutate({ action: actionName, fn });
}
}
const menuItems: ActionMenuItem[] = [];
if (canPause) {
menuItems.push({
label: "Pause Task",
icon: "debug-pause",
onClick: () =>
run("pausing", () => api.pauseTask({ taskId: task.id, taskName })),
loading: action === "pausing",
});
}
if (canResume) {
menuItems.push({
label: "Resume Task",
icon: "debug-start",
onClick: () =>
run("resuming", () => api.resumeTask({ taskId: task.id, taskName })),
loading: action === "resuming",
});
}
menuItems.push({
label: "View in Coder",
icon: "link-external",
onClick: () => api.viewInCoder({ taskId: task.id }),
});
menuItems.push({
label: "Download Logs",
icon: "cloud-download",
onClick: () =>
run("downloading", () => api.downloadLogs({ taskId: task.id })),
loading: action === "downloading",
});
menuItems.push({ separator: true });
menuItems.push({
label: "Delete",
icon: "trash",
onClick: () =>
run("deleting", () => api.deleteTask({ taskId: task.id, taskName })),
danger: true,
loading: action === "deleting",
});
return { menuItems, action };
}