WorkspaceArchivedTasksFlatSection.tsx 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345
  1. import { useMemo, useState } from "react";
  2. import { ArchiveX, Cloud, CloudDownload, Folder, Smartphone, Trash2 } from "lucide-react";
  3. import { Button } from "@/components/ui/button.js";
  4. import { cn } from "@/components/lib/utils.js";
  5. import { ControlHintTooltip } from "@/ControlHintTooltip.js";
  6. import { useConfirmDialog } from "@/hooks/useConfirmDialog.js";
  7. import { useGlobalTaskList } from "@/hooks/useGlobalTaskList.js";
  8. import { useBaseWorkspaceServices } from "@/hooks/useWorkspaceServices.js";
  9. import { useZCodeIntl } from "@/i18n/IntlProvider.js";
  10. import { formatTaskRelativeTime } from "@/lib/taskListItemPresentation.js";
  11. import { getTaskChangeSummary } from "@/lib/taskChangeSummary.js";
  12. import { getPathLeaf } from "@/lib/path.js";
  13. import { logger } from "@/logger.js";
  14. import { useRemoteWorkspaceSessionStore } from "@/store/remoteWorkspaceSessionStore.js";
  15. import type { WorkspaceTabState } from "@/store/tabStore.js";
  16. import { buildTaskWorkspaceKey } from "@/lib/taskQueryCache.js";
  17. import { applyTaskQueryCacheMutation } from "@/store/taskQueryCacheStore.js";
  18. import { removeTaskFromTaskCaches } from "@/lib/taskListMetaSync.js";
  19. import { TaskListRemoteSyncHint } from "@/TaskListRemoteSyncHint.js";
  20. import { TaskListLoadingHint } from "@/TaskListLoadingHint.js";
  21. import { buildWorkspaceServiceLookup } from "@/lib/workspaceServiceResolver.js";
  22. import { DeleteAllArchivedTasksButton } from "@/DeleteAllArchivedTasksButton.js";
  23. export function WorkspaceArchivedTasksFlatSection({
  24. workspaceTabs,
  25. activeWorkspacePath,
  26. activeWorkspaceIdentity,
  27. activeTaskId,
  28. sortBy,
  29. mobileActiveTaskKey,
  30. actionsContainer,
  31. onSelectTask,
  32. }: {
  33. workspaceTabs: WorkspaceTabState[];
  34. activeWorkspacePath: string;
  35. activeWorkspaceIdentity?: string;
  36. activeTaskId: string | null;
  37. sortBy: "created" | "updated";
  38. mobileActiveTaskKey?: string | null;
  39. actionsContainer?: HTMLElement | null;
  40. onSelectTask: (
  41. targetWorkspacePath: string,
  42. taskId: string,
  43. targetWorkspaceIdentity?: string,
  44. ) => void;
  45. }) {
  46. const { intl } = useZCodeIntl();
  47. const confirmDialog = useConfirmDialog();
  48. const baseServices = useBaseWorkspaceServices();
  49. const sessionsById = useRemoteWorkspaceSessionStore((state) => state.sessionsById);
  50. const sessionIdByWorkspaceIdentity = useRemoteWorkspaceSessionStore(
  51. (state) => state.sessionIdByWorkspaceIdentity,
  52. );
  53. const sessionIdByWorkspacePath = useRemoteWorkspaceSessionStore(
  54. (state) => state.sessionIdByWorkspacePath,
  55. );
  56. const serviceResolverState = useMemo(
  57. () => ({
  58. sessionsById,
  59. sessionIdByWorkspaceIdentity,
  60. sessionIdByWorkspacePath,
  61. }),
  62. [sessionIdByWorkspaceIdentity, sessionIdByWorkspacePath, sessionsById],
  63. );
  64. const [showAllTasks, setShowAllTasks] = useState(false);
  65. const [deletingTaskKeys, setDeletingTaskKeys] = useState<Set<string>>(() => new Set());
  66. const collapsedLimit = 20;
  67. const workspaceLabelByKey = useMemo(
  68. () =>
  69. new Map(
  70. workspaceTabs.map(
  71. (tab) =>
  72. [
  73. buildTaskWorkspaceKey(tab.workspacePath, tab.workspaceIdentity),
  74. tab.label || getPathLeaf(tab.workspacePath),
  75. ] as const,
  76. ),
  77. ),
  78. [workspaceTabs],
  79. );
  80. const workspaceServiceLookup = useMemo(
  81. () => buildWorkspaceServiceLookup(workspaceTabs, baseServices, serviceResolverState),
  82. [baseServices, serviceResolverState, workspaceTabs],
  83. );
  84. const activeWorkspaceKey = buildTaskWorkspaceKey(activeWorkspacePath, activeWorkspaceIdentity);
  85. const { items, total, loading, syncingRemoteWorkspaces, refresh } = useGlobalTaskList({
  86. kind: "archived",
  87. workspaceTabs,
  88. sortBy,
  89. searchQuery: "",
  90. expanded: showAllTasks,
  91. collapsedLimit,
  92. });
  93. const canToggleExpanded = total > collapsedLimit;
  94. return (
  95. <div>
  96. <DeleteAllArchivedTasksButton
  97. actionsContainer={actionsContainer}
  98. count={total}
  99. disabled={loading || total === 0}
  100. workspaces={workspaceTabs.map((tab) => ({
  101. workspacePath: tab.workspacePath,
  102. workspaceIdentity: tab.workspaceIdentity,
  103. label: tab.label || getPathLeaf(tab.workspacePath),
  104. service: workspaceServiceLookup.get(
  105. buildTaskWorkspaceKey(tab.workspacePath, tab.workspaceIdentity),
  106. )?.services.zcodeTaskService,
  107. }))}
  108. onDeleted={removeTaskFromTaskCaches}
  109. onRefresh={refresh}
  110. />
  111. {items.length === 0 ? (
  112. loading ? (
  113. <TaskListLoadingHint />
  114. ) : (
  115. <div className="px-3 py-2 text-ui-base text-foreground-subtle">
  116. {intl.formatMessage({ id: "taskList.noArchivedTasks" })}
  117. </div>
  118. )
  119. ) : null}
  120. <ul className="space-y-1 pb-4">
  121. {items.map((task) => {
  122. const workspaceServices = workspaceServiceLookup.get(
  123. buildTaskWorkspaceKey(task.workspacePath, task.workspaceIdentity),
  124. );
  125. if (!workspaceServices) {
  126. return null;
  127. }
  128. const { services } = workspaceServices;
  129. const taskTitle = task.title || intl.formatMessage({ id: "taskList.untitled" });
  130. const taskTimeLabel = formatTaskRelativeTime(
  131. sortBy === "created" ? task.createdAt : task.updatedAt,
  132. intl,
  133. );
  134. const taskChangeSummary = getTaskChangeSummary(task);
  135. const workspaceKey = buildTaskWorkspaceKey(task.workspacePath, task.workspaceIdentity);
  136. const workspaceLabel =
  137. workspaceLabelByKey.get(workspaceKey) ?? getPathLeaf(task.workspacePath);
  138. const isRemoteTask = Boolean(task.workspaceIdentity?.trim());
  139. const unarchiveLabel = intl.formatMessage({ id: "taskList.unarchive" });
  140. const deleteLabel = intl.formatMessage({ id: "taskList.delete" });
  141. // archived 平铺列表同样是跨 workspace 视图,选中态要按 workspaceKey 隔离。
  142. const isActive = workspaceKey === activeWorkspaceKey && task.taskId === activeTaskId;
  143. const isMobileActive = mobileActiveTaskKey === `${workspaceKey}:${task.taskId}`;
  144. const taskKey = `${workspaceKey}:${task.taskId}`;
  145. const isDeleting = deletingTaskKeys.has(taskKey);
  146. return (
  147. <li
  148. key={taskKey}
  149. data-mobile-active-task={isMobileActive ? "true" : undefined}
  150. onClick={() => {
  151. onSelectTask(task.workspacePath, task.taskId, task.workspaceIdentity);
  152. }}
  153. className={cn(
  154. "cursor-pointer rounded-lg px-2.5 py-2 transition-[background-color,border-color,box-shadow]",
  155. isActive ? "bg-selected" : "hover:bg-surface-hover",
  156. )}
  157. >
  158. <div className="relative flex items-center gap-2">
  159. {isMobileActive ? (
  160. <ControlHintTooltip
  161. title={intl.formatMessage({ id: "taskList.mobileActive" })}
  162. side="right"
  163. align="center"
  164. triggerClassName="absolute -left-5 top-1/2 z-10 -translate-y-1/2"
  165. >
  166. <span
  167. data-mobile-active-task="true"
  168. className="inline-flex size-4 items-center justify-center rounded-sm text-success"
  169. aria-label={intl.formatMessage({
  170. id: "taskList.mobileActive",
  171. })}
  172. >
  173. {/* Bugfix: 归档视图也可能保留手机端当前 task 的旧状态,展示同一标记避免列表间状态不一致。
  174. 上一版把标记放进标题行 flex 流里,会让只有手机标记的 task 标题右移;
  175. 这里用绝对定位放在标题左侧,让标题文本继续按原始位置对齐。 */}
  176. <Smartphone className="size-3.5" />
  177. </span>
  178. </ControlHintTooltip>
  179. ) : null}
  180. <p className="min-w-0 flex-1 truncate text-ui-base text-foreground" title={taskTitle}>
  181. {taskTitle}
  182. </p>
  183. <span className="shrink-0 text-ui-base text-foreground-subtle">{taskTimeLabel}</span>
  184. </div>
  185. <div className="mt-1 flex items-center gap-2 text-ui-base text-foreground-subtle">
  186. <span className="flex min-w-0 flex-1 items-center gap-1.5" title={task.workspacePath}>
  187. {/* Bugfix: archived 列表以前本地和远端任务都显示 Folder,
  188. 用户无法判断取消归档会作用在哪一侧。这里用 Cloud 区分远端来源。 */}
  189. {isRemoteTask ? (
  190. <Cloud className="size-3 shrink-0" />
  191. ) : (
  192. <Folder className="size-3 shrink-0" />
  193. )}
  194. <span className="min-w-0 truncate">{workspaceLabel}</span>
  195. </span>
  196. {taskChangeSummary ? (
  197. <span className="shrink-0">
  198. {intl.formatMessage(
  199. { id: "taskList.changeStats" },
  200. {
  201. added: String(taskChangeSummary.added),
  202. removed: String(taskChangeSummary.removed),
  203. },
  204. )}
  205. </span>
  206. ) : null}
  207. <ControlHintTooltip title={unarchiveLabel} side="top">
  208. <Button
  209. type="button"
  210. variant="ghost"
  211. size="icon-sm"
  212. className="shrink-0 text-foreground-subtle hover:text-foreground"
  213. aria-label={unarchiveLabel}
  214. onMouseDown={(event) => {
  215. event.preventDefault();
  216. event.stopPropagation();
  217. }}
  218. onClick={(event) => {
  219. event.preventDefault();
  220. event.stopPropagation();
  221. void services.zcodeTaskService
  222. .unarchiveTask({
  223. taskId: task.taskId,
  224. workspacePath: task.workspacePath,
  225. ...(task.workspaceIdentity ? { workspaceIdentity: task.workspaceIdentity } : {}),
  226. })
  227. .then((meta) => {
  228. applyTaskQueryCacheMutation({
  229. previousTask: task,
  230. nextTask: meta,
  231. previousState: { pinned: false, archived: true },
  232. nextState: { pinned: false, archived: false },
  233. });
  234. })
  235. .catch((error) => {
  236. logger.error(
  237. "[WorkspaceArchivedTasksFlatSection] 取消归档 task 失败:",
  238. error,
  239. );
  240. });
  241. }}
  242. >
  243. {/* Bugfix: 取消归档按钮以前本地/远端都用 ArchiveX,
  244. 在混合归档列表中看不出操作目标。远端用 CloudDownload 明确会作用到远端 task。 */}
  245. {isRemoteTask ? (
  246. <CloudDownload className="size-3.5" />
  247. ) : (
  248. <ArchiveX className="size-3.5" />
  249. )}
  250. </Button>
  251. </ControlHintTooltip>
  252. <ControlHintTooltip title={deleteLabel} side="top">
  253. {/* Bugfix:删除请求期间 button 会 disabled,disabled 元素不产生 hover 事件;
  254. 用真实 span 承接 tooltip trigger,保持处理中仍能解释该 action。 */}
  255. <span className="inline-flex shrink-0">
  256. <Button
  257. type="button"
  258. variant="ghost"
  259. size="icon-sm"
  260. disabled={isDeleting}
  261. className="shrink-0 text-destructive hover:text-destructive"
  262. aria-label={deleteLabel}
  263. onMouseDown={(event) => {
  264. event.preventDefault();
  265. event.stopPropagation();
  266. }}
  267. onClick={(event) => {
  268. event.preventDefault();
  269. event.stopPropagation();
  270. void (async () => {
  271. const confirmed = await confirmDialog({
  272. title: intl.formatMessage({
  273. id: "confirmDialog.archivedTaskDeleteTitle",
  274. }),
  275. description: intl.formatMessage({
  276. id: "confirmDialog.archivedTaskDeleteDescription",
  277. }),
  278. confirmLabel: deleteLabel,
  279. });
  280. if (!confirmed) {
  281. return;
  282. }
  283. setDeletingTaskKeys((current) => new Set(current).add(taskKey));
  284. try {
  285. await services.zcodeTaskService.deleteTask({
  286. taskId: task.taskId,
  287. workspacePath: task.workspacePath,
  288. ...(task.workspaceIdentity
  289. ? { workspaceIdentity: task.workspaceIdentity }
  290. : {}),
  291. });
  292. // Bugfix: 删除只发生在归档列表,不能把它当成“取消归档”写回普通列表。
  293. // 这里直接从 task caches 移除目标项,避免失效整表 query cache 导致列表闪空。
  294. removeTaskFromTaskCaches({
  295. workspacePath: task.workspacePath,
  296. workspaceIdentity: task.workspaceIdentity,
  297. taskId: task.taskId,
  298. });
  299. } catch (error) {
  300. logger.error(
  301. "[WorkspaceArchivedTasksFlatSection] 删除归档 task 失败:",
  302. error,
  303. );
  304. } finally {
  305. setDeletingTaskKeys((current) => {
  306. const next = new Set(current);
  307. next.delete(taskKey);
  308. return next;
  309. });
  310. }
  311. })();
  312. }}
  313. >
  314. <Trash2 className="size-3.5" />
  315. </Button>
  316. </span>
  317. </ControlHintTooltip>
  318. </div>
  319. </li>
  320. );
  321. })}
  322. </ul>
  323. {syncingRemoteWorkspaces ? <TaskListRemoteSyncHint /> : null}
  324. {canToggleExpanded ? (
  325. <div className="cursor-pointer pl-8.5 pb-4">
  326. <span
  327. className="text-ui-base text-foreground-subtlest hover:text-foreground-subtle"
  328. onClick={() => {
  329. setShowAllTasks((current) => !current);
  330. }}
  331. >
  332. {intl.formatMessage({
  333. id: showAllTasks ? "taskList.showLess" : "taskList.showMore",
  334. })}
  335. </span>
  336. </div>
  337. ) : null}
  338. </div>
  339. );
  340. }