WorkspaceGroupedTasksSection.tsx 62 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946
  1. /* eslint-disable max-lines -- 顶层 grouped task 容器仍集中维护远程 workspace service 解析、group 菜单、task 菜单和列表写回;子行与纯 helper 已拆到 workspace-grouped-tasks 目录。 */
  2. import { useCallback, useEffect, useMemo, useRef, useState } from "react";
  3. import type { PointerEvent as ReactPointerEvent, ReactNode } from "react";
  4. import {
  5. closestCenter,
  6. DndContext,
  7. DragOverlay,
  8. PointerSensor,
  9. useSensor,
  10. useSensors,
  11. } from "@dnd-kit/core";
  12. import type {
  13. CollisionDetection,
  14. DragCancelEvent,
  15. DragEndEvent,
  16. DragMoveEvent,
  17. DragOverEvent,
  18. DragStartEvent,
  19. DropAnimation,
  20. } from "@dnd-kit/core";
  21. import type {
  22. ZCodeGroupedTaskView,
  23. ZCodeTaskGroupColor,
  24. } from "@zcode/services";
  25. import { OFF_PEAK_DEFAULT_GROUP_ID, type ZCodeTaskMeta } from "@zcode/shared";
  26. import { createPortal } from "react-dom";
  27. import { cn } from "@/components/lib/utils.js";
  28. import { useZCodeIntl } from "@/i18n/IntlProvider.js";
  29. import { TaskRenameDialog } from "@/TaskRenameDialog.js";
  30. import {
  31. shouldHideGroupedTaskContent,
  32. useGroupedTaskView,
  33. } from "@/hooks/useGroupedTaskView.js";
  34. import type { WorkspaceTabState } from "@/store/tabStore.js";
  35. import { buildTaskWorkspaceKey } from "@/lib/taskQueryCache.js";
  36. import { getPathLeaf } from "@/lib/path.js";
  37. import { resolveTaskFileTreeTargetFromTabs } from "@/lib/taskFileTreeTarget.js";
  38. import { toast } from "@/components/ui/toast.js";
  39. import { useBaseWorkspaceServices } from "@/hooks/useWorkspaceServices.js";
  40. import {
  41. selectWorkspaceZCodeState,
  42. useZCodeSessionStore,
  43. } from "@/store/zcodeSessionStore.js";
  44. import { useRemoteWorkspaceSessionStore } from "@/store/remoteWorkspaceSessionStore.js";
  45. import { buildWorkspaceServiceLookup } from "@/lib/workspaceServiceResolver.js";
  46. import { applyTaskQueryCacheMutation } from "@/store/taskQueryCacheStore.js";
  47. import { useRemotePinnedTaskStore } from "@/store/remotePinnedTaskStore.js";
  48. import { useRemoteTimelineTaskStore } from "@/store/remoteTimelineTaskStore.js";
  49. import { bumpTaskListMembershipVersion } from "@/v4/taskListMembershipVersion.js";
  50. import { GroupItem, GroupedTaskItem } from "@/workspace-grouped-tasks/items.js";
  51. import { GroupDragOverlay } from "@/workspace-grouped-tasks/group-drag-overlay.js";
  52. import { VirtualizedGroupedTopLevelList } from "@/workspace-grouped-tasks/virtualized-top-level-list.js";
  53. import { GroupedDraftTaskRow } from "@/workspace-grouped-tasks/draft-task-row.js";
  54. import { StickyGroupHeader } from "@/workspace-grouped-tasks/sticky-group-header.js";
  55. import type { CreateTaskRequest } from "@/app-shell/types.js";
  56. import {
  57. findTaskInGroupedView,
  58. filterGroupedViewByTaskKeys,
  59. getGroupedTaskGroupIds,
  60. moveGroupAroundTopLevelNode,
  61. moveTaskByMenu,
  62. moveTaskToTopByMenu,
  63. moveTaskToGroupEnd,
  64. moveTaskToGroupStart,
  65. moveTaskToRootAroundGroup,
  66. moveTaskOverTask,
  67. replaceTaskInGroupedView,
  68. resolveGroupedDraftTaskPlacementForTask,
  69. taskKey,
  70. } from "@/workspace-grouped-tasks/shared.js";
  71. import type { TaskGroupMenuItem } from "@/workspace-grouped-tasks/shared.js";
  72. import type { WorkbenchSessionDragPayload } from "@/v4/workbenchDragDrop.js";
  73. import {
  74. cancelWorkbenchPointerDrag,
  75. finishWorkbenchPointerDrag,
  76. updateWorkbenchPointerDrag,
  77. } from "@/v4/workbenchPointerDragDrop.js";
  78. import {
  79. createWorkbenchPointerPositionTracker,
  80. type WorkbenchPointerPositionTracker,
  81. } from "@/v4/workbenchPointerPositionTracker.js";
  82. function findNearestScrollableAncestor(
  83. element: HTMLElement,
  84. ): HTMLElement | null {
  85. let current = element.parentElement;
  86. while (current) {
  87. const style = window.getComputedStyle(current);
  88. const canScrollY =
  89. /(auto|scroll)/.test(style.overflowY) &&
  90. current.scrollHeight > current.clientHeight;
  91. if (canScrollY) {
  92. return current;
  93. }
  94. current = current.parentElement;
  95. }
  96. return null;
  97. }
  98. function areTaskGroupMenuItemsEqual(
  99. left: readonly TaskGroupMenuItem[],
  100. right: readonly TaskGroupMenuItem[],
  101. ): boolean {
  102. return (
  103. left.length === right.length &&
  104. left.every(
  105. (item, index) =>
  106. item.id === right[index]?.id &&
  107. item.title === right[index]?.title &&
  108. item.color === right[index]?.color,
  109. )
  110. );
  111. }
  112. function areStringArraysEqual(
  113. left: readonly string[],
  114. right: readonly string[],
  115. ): boolean {
  116. return (
  117. left.length === right.length &&
  118. left.every((item, index) => item === right[index])
  119. );
  120. }
  121. function getGroupedTaskDragTaskKey(value: unknown): string | null {
  122. if (!value || typeof value !== "object") {
  123. return null;
  124. }
  125. const data = value as { type?: unknown; taskKey?: unknown };
  126. return data.type === "grouped-task" && typeof data.taskKey === "string"
  127. ? data.taskKey
  128. : null;
  129. }
  130. function getGroupedTaskDragGroupId(value: unknown): string | null {
  131. if (!value || typeof value !== "object") {
  132. return null;
  133. }
  134. const data = value as { type?: unknown; groupId?: unknown };
  135. return data.type === "grouped-group" && typeof data.groupId === "string"
  136. ? data.groupId
  137. : null;
  138. }
  139. function getGroupedTaskDragType(value: unknown): string | null {
  140. if (!value || typeof value !== "object") {
  141. return null;
  142. }
  143. const data = value as { type?: unknown };
  144. return typeof data.type === "string" ? data.type : null;
  145. }
  146. function getGroupedGroupOverGroupId(value: unknown): string | null {
  147. if (!value || typeof value !== "object") {
  148. return null;
  149. }
  150. const data = value as { type?: unknown; groupId?: unknown };
  151. return data.type === "grouped-group-over" && typeof data.groupId === "string"
  152. ? data.groupId
  153. : null;
  154. }
  155. function getGroupedTaskCollapsedOverGroupId(value: unknown): string | null {
  156. if (!value || typeof value !== "object") {
  157. return null;
  158. }
  159. const data = value as { type?: unknown; groupId?: unknown };
  160. return data.type === "grouped-collapsed-group" &&
  161. typeof data.groupId === "string"
  162. ? data.groupId
  163. : null;
  164. }
  165. function getGroupedTaskHeaderOverGroupId(value: unknown): string | null {
  166. if (!value || typeof value !== "object") {
  167. return null;
  168. }
  169. const data = value as { type?: unknown; groupId?: unknown };
  170. return data.type === "grouped-expanded-group-header" &&
  171. typeof data.groupId === "string"
  172. ? data.groupId
  173. : null;
  174. }
  175. function getGroupedTaskFooterOverGroupId(value: unknown): string | null {
  176. if (!value || typeof value !== "object") {
  177. return null;
  178. }
  179. const data = value as { type?: unknown; groupId?: unknown };
  180. return data.type === "grouped-expanded-group-footer" &&
  181. typeof data.groupId === "string"
  182. ? data.groupId
  183. : null;
  184. }
  185. function getGroupedTaskEmptyOverGroupId(value: unknown): string | null {
  186. if (!value || typeof value !== "object") {
  187. return null;
  188. }
  189. const data = value as { type?: unknown; groupId?: unknown };
  190. return data.type === "grouped-empty-drop-zone" &&
  191. typeof data.groupId === "string"
  192. ? data.groupId
  193. : null;
  194. }
  195. type GroupedTaskDragDirectionPosition = "before" | "after";
  196. const groupedTaskCollisionDetection: CollisionDetection = (args) => {
  197. const activeType = getGroupedTaskDragType(args.active.data.current);
  198. const droppableContainers =
  199. activeType === "grouped-group"
  200. ? args.droppableContainers.filter((container) => {
  201. const type = getGroupedTaskDragType(container.data.current);
  202. return type === "grouped-task" || type === "grouped-group-over";
  203. })
  204. : args.droppableContainers.filter(
  205. (container) =>
  206. getGroupedTaskDragType(container.data.current) !==
  207. "grouped-group-over",
  208. );
  209. return closestCenter({
  210. ...args,
  211. droppableContainers,
  212. });
  213. };
  214. function getGroupedTaskOverTaskPreviewView(
  215. view: ZCodeGroupedTaskView,
  216. event: DragOverEvent,
  217. position: GroupedTaskDragDirectionPosition,
  218. ): ZCodeGroupedTaskView {
  219. const activeTaskKey = getGroupedTaskDragTaskKey(event.active.data.current);
  220. const overTaskKey = getGroupedTaskDragTaskKey(event.over?.data.current);
  221. if (!activeTaskKey || !overTaskKey || activeTaskKey === overTaskKey) {
  222. return view;
  223. }
  224. return moveTaskOverTask(view, {
  225. activeTaskKey,
  226. overTaskKey,
  227. position,
  228. });
  229. }
  230. function getGroupedTaskOverCollapsedGroupPreviewView(
  231. view: ZCodeGroupedTaskView,
  232. event: DragOverEvent,
  233. position: GroupedTaskDragDirectionPosition,
  234. ): ZCodeGroupedTaskView {
  235. const activeTaskKey = getGroupedTaskDragTaskKey(event.active.data.current);
  236. const overGroupId = getGroupedTaskCollapsedOverGroupId(
  237. event.over?.data.current,
  238. );
  239. if (!activeTaskKey || !overGroupId) {
  240. return view;
  241. }
  242. return moveTaskToRootAroundGroup(view, {
  243. activeTaskKey,
  244. groupId: overGroupId,
  245. position,
  246. });
  247. }
  248. function getGroupedTaskOverGroupHeaderPreviewView(
  249. view: ZCodeGroupedTaskView,
  250. event: DragOverEvent,
  251. position: GroupedTaskDragDirectionPosition,
  252. ): ZCodeGroupedTaskView {
  253. const activeTaskKey = getGroupedTaskDragTaskKey(event.active.data.current);
  254. const overGroupId = getGroupedTaskHeaderOverGroupId(event.over?.data.current);
  255. if (!activeTaskKey || !overGroupId) {
  256. return view;
  257. }
  258. if (position === "before") {
  259. return moveTaskToRootAroundGroup(view, {
  260. activeTaskKey,
  261. groupId: overGroupId,
  262. position: "before",
  263. });
  264. }
  265. return moveTaskToGroupStart(view, {
  266. activeTaskKey,
  267. groupId: overGroupId,
  268. });
  269. }
  270. function getGroupedTaskOverGroupFooterPreviewView(
  271. view: ZCodeGroupedTaskView,
  272. event: DragOverEvent,
  273. position: GroupedTaskDragDirectionPosition,
  274. ): ZCodeGroupedTaskView {
  275. const activeTaskKey = getGroupedTaskDragTaskKey(event.active.data.current);
  276. const overGroupId = getGroupedTaskFooterOverGroupId(event.over?.data.current);
  277. if (!activeTaskKey || !overGroupId) {
  278. return view;
  279. }
  280. if (position === "before") {
  281. return moveTaskToGroupEnd(view, {
  282. activeTaskKey,
  283. groupId: overGroupId,
  284. });
  285. }
  286. return moveTaskToRootAroundGroup(view, {
  287. activeTaskKey,
  288. groupId: overGroupId,
  289. position: "after",
  290. });
  291. }
  292. function getGroupedTaskOverEmptyDropZonePreviewView(
  293. view: ZCodeGroupedTaskView,
  294. event: DragOverEvent,
  295. ): ZCodeGroupedTaskView {
  296. const activeTaskKey = getGroupedTaskDragTaskKey(event.active.data.current);
  297. const overGroupId = getGroupedTaskEmptyOverGroupId(event.over?.data.current);
  298. if (!activeTaskKey || !overGroupId) {
  299. return view;
  300. }
  301. return moveTaskToGroupStart(view, {
  302. activeTaskKey,
  303. groupId: overGroupId,
  304. });
  305. }
  306. function getGroupedGroupOverGroupPreviewView(
  307. view: ZCodeGroupedTaskView,
  308. event: DragOverEvent,
  309. position: GroupedTaskDragDirectionPosition,
  310. ): ZCodeGroupedTaskView {
  311. const activeGroupId = getGroupedTaskDragGroupId(event.active.data.current);
  312. const overGroupId = getGroupedGroupOverGroupId(event.over?.data.current);
  313. if (!activeGroupId || !overGroupId || activeGroupId === overGroupId) {
  314. return view;
  315. }
  316. return moveGroupAroundTopLevelNode(view, {
  317. activeGroupId,
  318. over: { type: "group", groupId: overGroupId },
  319. position,
  320. });
  321. }
  322. function getGroupedGroupOverTaskPreviewView(
  323. view: ZCodeGroupedTaskView,
  324. event: DragOverEvent,
  325. position: GroupedTaskDragDirectionPosition,
  326. ): ZCodeGroupedTaskView {
  327. const activeGroupId = getGroupedTaskDragGroupId(event.active.data.current);
  328. const overTaskKey = getGroupedTaskDragTaskKey(event.over?.data.current);
  329. if (!activeGroupId || !overTaskKey) {
  330. return view;
  331. }
  332. return moveGroupAroundTopLevelNode(view, {
  333. activeGroupId,
  334. over: { type: "task", taskKey: overTaskKey },
  335. position,
  336. });
  337. }
  338. function getGroupedTaskViewSignature(view: ZCodeGroupedTaskView): string {
  339. return view.nodes
  340. .map((node) =>
  341. node.type === "task"
  342. ? `t:${taskKey(node.task)}`
  343. : `g:${node.group.id}[${node.tasks.map(taskKey).join(",")}]`,
  344. )
  345. .join("|");
  346. }
  347. type GroupedTaskLayoutRects = Map<
  348. string,
  349. {
  350. height: number;
  351. left: number;
  352. top: number;
  353. }
  354. >;
  355. const GROUPED_TASK_DROP_ANIMATION: DropAnimation = {
  356. duration: 150,
  357. easing: "cubic-bezier(0.2, 0, 0, 1)",
  358. };
  359. const GROUPED_TASK_AUTO_SCROLL_THRESHOLD = {
  360. x: 0.1,
  361. y: 0.1,
  362. } as const;
  363. function collectGroupedTaskLayoutRects(
  364. root: HTMLElement | null,
  365. ): GroupedTaskLayoutRects {
  366. const rects: GroupedTaskLayoutRects = new Map();
  367. if (!root) {
  368. return rects;
  369. }
  370. root
  371. .querySelectorAll<HTMLElement>("[data-grouped-layout-key]")
  372. .forEach((element) => {
  373. const key = element.getAttribute("data-grouped-layout-key");
  374. if (!key) {
  375. return;
  376. }
  377. const rect = element.getBoundingClientRect();
  378. rects.set(`layout:${key}`, {
  379. height: rect.height,
  380. left: rect.left,
  381. top: rect.top,
  382. });
  383. });
  384. root
  385. .querySelectorAll<HTMLElement>("[data-grouped-task-key]")
  386. .forEach((element) => {
  387. const key = element.getAttribute("data-grouped-task-key");
  388. if (!key) {
  389. return;
  390. }
  391. const rect = element.getBoundingClientRect();
  392. rects.set(`task:${key}`, {
  393. height: rect.height,
  394. left: rect.left,
  395. top: rect.top,
  396. });
  397. });
  398. return rects;
  399. }
  400. function measureGroupedTaskPreviewWidth(
  401. root: HTMLElement | null,
  402. targetTaskKey: string,
  403. ): number | null {
  404. if (!root) {
  405. return null;
  406. }
  407. const targetDomKey = encodeURIComponent(targetTaskKey);
  408. for (const element of root.querySelectorAll<HTMLElement>(
  409. "[data-grouped-task-key]",
  410. )) {
  411. if (element.getAttribute("data-grouped-task-key") === targetDomKey) {
  412. return element.getBoundingClientRect().width;
  413. }
  414. }
  415. return null;
  416. }
  417. function measureGroupedGroupPreviewWidth(
  418. root: HTMLElement | null,
  419. targetGroupId: string,
  420. ): number | null {
  421. if (!root) {
  422. return null;
  423. }
  424. for (const element of root.querySelectorAll<HTMLElement>(
  425. "[data-grouped-group-item-id]",
  426. )) {
  427. if (element.getAttribute("data-grouped-group-item-id") === targetGroupId) {
  428. return element.getBoundingClientRect().width;
  429. }
  430. }
  431. return null;
  432. }
  433. function resolveStickyGroupedTaskGroupId(
  434. root: HTMLElement | null,
  435. ): string | null {
  436. if (!root) {
  437. return null;
  438. }
  439. const scrollContainer = findNearestScrollableAncestor(root);
  440. if (!scrollContainer) {
  441. return null;
  442. }
  443. const containerTop = scrollContainer.getBoundingClientRect().top;
  444. let stickyGroupId: string | null = null;
  445. for (const element of root.querySelectorAll<HTMLElement>(
  446. "[data-grouped-group-item-id]",
  447. )) {
  448. const groupId = element.getAttribute("data-grouped-group-item-id");
  449. if (element.getAttribute("data-group-collapsed") === "true") {
  450. continue;
  451. }
  452. const header = groupId
  453. ? root.querySelector<HTMLElement>(
  454. `[data-grouped-group-header-id="${CSS.escape(groupId)}"]`,
  455. )
  456. : null;
  457. if (!groupId || !header) {
  458. continue;
  459. }
  460. const groupRect = element.getBoundingClientRect();
  461. const headerRect = header.getBoundingClientRect();
  462. const headerHeight = headerRect.height || 32;
  463. const headerHasScrolledPastTop = headerRect.top < containerTop - 0.5;
  464. const groupStillCoversTop =
  465. groupRect.bottom > containerTop + headerHeight + 0.5;
  466. if (headerHasScrolledPastTop && groupStillCoversTop) {
  467. stickyGroupId = groupId;
  468. }
  469. }
  470. return stickyGroupId;
  471. }
  472. function animateGroupedTaskLayoutFrom(
  473. root: HTMLElement | null,
  474. previousRects: GroupedTaskLayoutRects,
  475. ) {
  476. if (!root || previousRects.size === 0) {
  477. return;
  478. }
  479. if (window.matchMedia("(prefers-reduced-motion: reduce)").matches) {
  480. return;
  481. }
  482. const selector = "[data-grouped-layout-key], [data-grouped-task-key]";
  483. root.querySelectorAll<HTMLElement>(selector).forEach((element) => {
  484. const layoutKey = element.getAttribute("data-grouped-layout-key");
  485. const taskKeyValue = element.getAttribute("data-grouped-task-key");
  486. const previousRect = layoutKey
  487. ? previousRects.get(`layout:${layoutKey}`)
  488. : taskKeyValue
  489. ? previousRects.get(`task:${taskKeyValue}`)
  490. : null;
  491. if (!previousRect) {
  492. return;
  493. }
  494. const nextRect = element.getBoundingClientRect();
  495. const deltaX = previousRect.left - nextRect.left;
  496. const deltaY = previousRect.top - nextRect.top;
  497. const deltaHeight = previousRect.height - nextRect.height;
  498. const shouldAnimateHeight =
  499. Boolean(layoutKey) && Math.abs(deltaHeight) >= 0.5;
  500. if (
  501. Math.abs(deltaX) < 0.5 &&
  502. Math.abs(deltaY) < 0.5 &&
  503. !shouldAnimateHeight
  504. ) {
  505. return;
  506. }
  507. element.getAnimations().forEach((animation) => animation.cancel());
  508. const previousOverflow = element.style.overflow;
  509. if (shouldAnimateHeight) {
  510. element.style.overflow = "hidden";
  511. }
  512. const animation = element.animate(
  513. [
  514. {
  515. height: shouldAnimateHeight ? `${previousRect.height}px` : undefined,
  516. transform: `translate(${deltaX}px, ${deltaY}px)`,
  517. },
  518. {
  519. height: shouldAnimateHeight ? `${nextRect.height}px` : undefined,
  520. transform: "translate(0, 0)",
  521. },
  522. ],
  523. {
  524. duration: 150,
  525. easing: "cubic-bezier(0.2, 0, 0, 1)",
  526. },
  527. );
  528. animation.addEventListener(
  529. "finish",
  530. () => {
  531. element.style.overflow = previousOverflow;
  532. },
  533. { once: true },
  534. );
  535. animation.addEventListener(
  536. "cancel",
  537. () => {
  538. element.style.overflow = previousOverflow;
  539. },
  540. { once: true },
  541. );
  542. });
  543. }
  544. export function WorkspaceGroupedTasksSection({
  545. workspaceTabs,
  546. activeWorkspacePath,
  547. activeWorkspaceIdentity,
  548. activeTaskId,
  549. mobileActiveTaskKey,
  550. onSelectTask,
  551. onCreateTask,
  552. onOpenFileTree,
  553. onCreateGroupActionChange,
  554. onCreateDraftTaskActionChange,
  555. collapsedGroupIds,
  556. onGroupedTaskGroupIdsChange,
  557. onCollapsedGroupIdsChange,
  558. onStickyGroupHeaderChange,
  559. onOpenAutomations,
  560. }: {
  561. workspaceTabs: WorkspaceTabState[];
  562. activeWorkspacePath: string;
  563. activeWorkspaceIdentity?: string;
  564. activeTaskId: string | null;
  565. mobileActiveTaskKey?: string | null;
  566. onSelectTask: (
  567. workspacePath: string,
  568. taskId: string,
  569. workspaceIdentity?: string,
  570. ) => void;
  571. onCreateTask: (request?: CreateTaskRequest) => void;
  572. onOpenFileTree?: (target: {
  573. workspacePath: string;
  574. workspaceName: string;
  575. workspaceIdentity?: string;
  576. workspaceRemoteSessionId?: string;
  577. }) => void;
  578. onCreateGroupActionChange?: (action: (() => void) | null) => void;
  579. onCreateDraftTaskActionChange?: (action: (() => void) | null) => void;
  580. collapsedGroupIds: ReadonlySet<string>;
  581. onGroupedTaskGroupIdsChange?: (groupIds: string[]) => void;
  582. onCollapsedGroupIdsChange: (
  583. updater: (currentGroupIds: Set<string>) => Set<string>,
  584. ) => void;
  585. onStickyGroupHeaderChange?: (node: ReactNode | null) => void;
  586. /** 闲时系统分组的「+」/右键新建路由到 Automations 主视图。 */
  587. onOpenAutomations?: () => void;
  588. }) {
  589. const { intl } = useZCodeIntl();
  590. const baseServices = useBaseWorkspaceServices();
  591. const sessionsById = useRemoteWorkspaceSessionStore(
  592. (state) => state.sessionsById,
  593. );
  594. const sessionIdByWorkspaceIdentity = useRemoteWorkspaceSessionStore(
  595. (state) => state.sessionIdByWorkspaceIdentity,
  596. );
  597. const sessionIdByWorkspacePath = useRemoteWorkspaceSessionStore(
  598. (state) => state.sessionIdByWorkspacePath,
  599. );
  600. const serviceResolverState = useMemo(
  601. () => ({
  602. sessionsById,
  603. sessionIdByWorkspaceIdentity,
  604. sessionIdByWorkspacePath,
  605. }),
  606. [sessionIdByWorkspaceIdentity, sessionIdByWorkspacePath, sessionsById],
  607. );
  608. const workspaceServiceLookup = useMemo(
  609. () =>
  610. buildWorkspaceServiceLookup(
  611. workspaceTabs,
  612. baseServices,
  613. serviceResolverState,
  614. ),
  615. [baseServices, serviceResolverState, workspaceTabs],
  616. );
  617. const removeTaskState = useZCodeSessionStore(
  618. (state) => state.removeTaskState,
  619. );
  620. const upsertOptimisticTaskListItem = useZCodeSessionStore(
  621. (state) => state.upsertOptimisticTaskListItem,
  622. );
  623. const setTaskUnreadIndicator = useZCodeSessionStore(
  624. (state) => state.setTaskUnreadIndicator,
  625. );
  626. const groupedDraftTask = useZCodeSessionStore(
  627. (state) =>
  628. selectWorkspaceZCodeState(
  629. state,
  630. activeWorkspacePath,
  631. activeWorkspaceIdentity,
  632. ).groupedDraftTask,
  633. );
  634. const groupedDraftFocusVersion = useZCodeSessionStore(
  635. (state) =>
  636. selectWorkspaceZCodeState(
  637. state,
  638. activeWorkspacePath,
  639. activeWorkspaceIdentity,
  640. ).draftFocusVersion,
  641. );
  642. const clearGroupedDraftTask = useZCodeSessionStore(
  643. (state) => state.clearGroupedDraftTask,
  644. );
  645. const {
  646. view: authoritativeView,
  647. setView,
  648. loading,
  649. initialized,
  650. saving,
  651. createGroup,
  652. renameGroup,
  653. updateGroupColor,
  654. ungroupGroup,
  655. applyOrder,
  656. } = useGroupedTaskView({
  657. workspaceTabs,
  658. });
  659. const [archivingTaskKeys, setArchivingTaskKeys] = useState<ReadonlySet<string>>(
  660. () => new Set(),
  661. );
  662. const view = useMemo(
  663. () => filterGroupedViewByTaskKeys(authoritativeView, archivingTaskKeys),
  664. [archivingTaskKeys, authoritativeView],
  665. );
  666. useEffect(() => {
  667. if (archivingTaskKeys.size === 0) {
  668. return;
  669. }
  670. setArchivingTaskKeys((current) => {
  671. const next = new Set(
  672. [...current].filter((key) => findTaskInGroupedView(authoritativeView, key)),
  673. );
  674. return next.size === current.size ? current : next;
  675. });
  676. }, [archivingTaskKeys.size, authoritativeView]);
  677. const groupedSectionRootRef = useRef<HTMLDivElement | null>(null);
  678. // 已经画出过 grouped 列表:之后任何 loading/未初始化帧都不再回到空白门禁。
  679. // 挂载时若模块级缓存已种出非空 view,本帧就会画出列表,闩锁直接种 true——把「渲染期置位」
  680. // 的窗口收窄到只剩真正的首屏。
  681. const hasPaintedGroupedListRef = useRef(view.nodes.length > 0);
  682. const renameInputRef = useRef<HTMLInputElement | null>(null);
  683. const groupMenuItemsRef = useRef<TaskGroupMenuItem[]>([]);
  684. const groupIdsRef = useRef<string[]>([]);
  685. const dragOriginViewRef = useRef<ZCodeGroupedTaskView | null>(null);
  686. const dragPreviewViewRef = useRef<ZCodeGroupedTaskView | null>(null);
  687. const lastDragOverEventRef = useRef<DragOverEvent | null>(null);
  688. const createDraftContextRef = useRef({
  689. activeTaskId,
  690. activeWorkspaceIdentity,
  691. activeWorkspacePath,
  692. groupedDraftPlacement: groupedDraftTask?.placement,
  693. view,
  694. });
  695. const groupDragCollapsedSnapshotRef = useRef<Set<string> | null>(null);
  696. const layoutAnimationFrameRef = useRef<number | null>(null);
  697. const dragDirectionRef = useRef<GroupedTaskDragDirectionPosition>("after");
  698. const lastDragDeltaYRef = useRef(0);
  699. const workbenchDragPayloadRef =
  700. useRef<WorkbenchSessionDragPayload | null>(null);
  701. const workbenchPointerPositionTrackerRef =
  702. useRef<WorkbenchPointerPositionTracker | null>(null);
  703. const [renamingTaskKey, setRenamingTaskKey] = useState<string | null>(null);
  704. const [renameDraft, setRenameDraft] = useState("");
  705. const [newGroupSetupId, setNewGroupSetupId] = useState<string | null>(null);
  706. const [activeDragTaskKey, setActiveDragTaskKey] = useState<string | null>(
  707. null,
  708. );
  709. const [activeDragGroupId, setActiveDragGroupId] = useState<string | null>(
  710. null,
  711. );
  712. const [activeDragOverlayWidth, setActiveDragOverlayWidth] = useState<
  713. number | null
  714. >(null);
  715. const [stickyGroupId, setStickyGroupId] = useState<string | null>(null);
  716. const sensors = useSensors(
  717. useSensor(PointerSensor, {
  718. activationConstraint: {
  719. distance: 6,
  720. },
  721. }),
  722. );
  723. const isGroupedDraftActive = Boolean(
  724. groupedDraftTask && activeTaskId === null,
  725. );
  726. const handleGroupedPointerDownCapture = useCallback(
  727. (event: ReactPointerEvent<HTMLDivElement>) => {
  728. // 必须在 dnd-kit 激活前监听,才能捕获越过 6px 阈值的首个
  729. // pointermove;快速拖到 Workbench 后立即松手也要使用真实 viewport 坐标。
  730. workbenchPointerPositionTrackerRef.current?.dispose();
  731. workbenchPointerPositionTrackerRef.current =
  732. createWorkbenchPointerPositionTracker(
  733. event.currentTarget.ownerDocument,
  734. event.nativeEvent,
  735. );
  736. },
  737. [],
  738. );
  739. useEffect(
  740. () => () => {
  741. workbenchPointerPositionTrackerRef.current?.dispose();
  742. workbenchPointerPositionTrackerRef.current = null;
  743. cancelWorkbenchPointerDrag();
  744. },
  745. [],
  746. );
  747. useEffect(() => {
  748. createDraftContextRef.current = {
  749. activeTaskId,
  750. activeWorkspaceIdentity,
  751. activeWorkspacePath,
  752. groupedDraftPlacement: groupedDraftTask?.placement,
  753. view,
  754. };
  755. }, [
  756. activeTaskId,
  757. activeWorkspaceIdentity,
  758. activeWorkspacePath,
  759. groupedDraftTask?.placement,
  760. view,
  761. ]);
  762. const handleCreateTopDraftTask = useCallback(() => {
  763. onCreateTask({ groupedDraftPlacement: { type: "top" } });
  764. }, [onCreateTask]);
  765. const handleCreateGroupDraftTask = useCallback(
  766. (groupId: string) => {
  767. onCollapsedGroupIdsChange((current) => {
  768. if (!current.has(groupId)) {
  769. return current;
  770. }
  771. const next = new Set(current);
  772. next.delete(groupId);
  773. return next;
  774. });
  775. onCreateTask({ groupedDraftPlacement: { type: "group", groupId } });
  776. },
  777. [onCollapsedGroupIdsChange, onCreateTask],
  778. );
  779. const handleCreateContextualDraftTask = useCallback(() => {
  780. const {
  781. activeTaskId: currentActiveTaskId,
  782. activeWorkspaceIdentity: currentActiveWorkspaceIdentity,
  783. activeWorkspacePath: currentActiveWorkspacePath,
  784. groupedDraftPlacement,
  785. view: currentView,
  786. } = createDraftContextRef.current;
  787. const activeTaskKey = currentActiveTaskId
  788. ? taskKey({
  789. taskId: currentActiveTaskId,
  790. workspaceIdentity: currentActiveWorkspaceIdentity,
  791. workspacePath: currentActiveWorkspacePath,
  792. })
  793. : null;
  794. const draftPlacement = activeTaskKey
  795. ? resolveGroupedDraftTaskPlacementForTask(currentView, activeTaskKey)
  796. : (groupedDraftPlacement ?? { type: "top" });
  797. if (draftPlacement.type === "group") {
  798. onCollapsedGroupIdsChange((current) => {
  799. if (!current.has(draftPlacement.groupId)) {
  800. return current;
  801. }
  802. const next = new Set(current);
  803. next.delete(draftPlacement.groupId);
  804. return next;
  805. });
  806. }
  807. onCreateTask({ groupedDraftPlacement: draftPlacement });
  808. }, [onCollapsedGroupIdsChange, onCreateTask]);
  809. const handleCloseGroupedDraftTask = useCallback(() => {
  810. // grouped 草稿会在切 workspace 时迁移到目标 workspace。
  811. // 只能由用户关闭、真实 task 创建或明确离开草稿时清理,不能跟随列表组件卸载自动清掉。
  812. clearGroupedDraftTask(activeWorkspacePath, activeWorkspaceIdentity);
  813. }, [activeWorkspaceIdentity, activeWorkspacePath, clearGroupedDraftTask]);
  814. useEffect(() => {
  815. onCreateDraftTaskActionChange?.(handleCreateContextualDraftTask);
  816. return () => onCreateDraftTaskActionChange?.(null);
  817. }, [handleCreateContextualDraftTask, onCreateDraftTaskActionChange]);
  818. useEffect(() => {
  819. if (groupedDraftTask?.placement.type !== "top") {
  820. return;
  821. }
  822. const rootElement = groupedSectionRootRef.current;
  823. if (!rootElement) {
  824. return;
  825. }
  826. const frameId = window.requestAnimationFrame(() => {
  827. const scrollContainer = findNearestScrollableAncestor(rootElement);
  828. // 全局 New task 的草稿创建在 grouped 列表顶部。
  829. // 用户可能已经滚到下面的 group;这里按入口语义把列表滚动条归零,而不是只保证草稿可见。
  830. scrollContainer?.scrollTo({ top: 0 });
  831. });
  832. return () => {
  833. window.cancelAnimationFrame(frameId);
  834. };
  835. }, [groupedDraftFocusVersion, groupedDraftTask]);
  836. const groups = useMemo<TaskGroupMenuItem[]>(() => {
  837. const nextGroups = view.nodes.flatMap((node) =>
  838. node.type === "group"
  839. ? [
  840. {
  841. id: node.group.id,
  842. title: node.group.title,
  843. color: node.group.color,
  844. },
  845. ]
  846. : [],
  847. );
  848. if (areTaskGroupMenuItemsEqual(groupMenuItemsRef.current, nextGroups)) {
  849. return groupMenuItemsRef.current;
  850. }
  851. groupMenuItemsRef.current = nextGroups;
  852. return nextGroups;
  853. }, [view.nodes]);
  854. const groupIds = useMemo(() => {
  855. const nextGroupIds = getGroupedTaskGroupIds(view);
  856. if (areStringArraysEqual(groupIdsRef.current, nextGroupIds)) {
  857. return groupIdsRef.current;
  858. }
  859. groupIdsRef.current = nextGroupIds;
  860. return nextGroupIds;
  861. }, [view]);
  862. useEffect(() => {
  863. onGroupedTaskGroupIdsChange?.(groupIds);
  864. }, [groupIds, onGroupedTaskGroupIdsChange]);
  865. useEffect(() => {
  866. const rootElement = groupedSectionRootRef.current;
  867. if (
  868. !rootElement ||
  869. activeDragTaskKey !== null ||
  870. activeDragGroupId !== null
  871. ) {
  872. setStickyGroupId(null);
  873. return undefined;
  874. }
  875. const scrollContainer = findNearestScrollableAncestor(rootElement);
  876. if (!scrollContainer) {
  877. setStickyGroupId(null);
  878. return undefined;
  879. }
  880. let animationFrame: number | null = null;
  881. const updateStickyGroup = () => {
  882. animationFrame = null;
  883. setStickyGroupId(resolveStickyGroupedTaskGroupId(rootElement));
  884. };
  885. const scheduleUpdate = () => {
  886. if (animationFrame !== null) {
  887. return;
  888. }
  889. animationFrame = window.requestAnimationFrame(updateStickyGroup);
  890. };
  891. updateStickyGroup();
  892. scrollContainer.addEventListener("scroll", scheduleUpdate, {
  893. passive: true,
  894. });
  895. window.addEventListener("resize", scheduleUpdate);
  896. const resizeObserver =
  897. typeof ResizeObserver === "undefined"
  898. ? null
  899. : new ResizeObserver(scheduleUpdate);
  900. resizeObserver?.observe(rootElement);
  901. return () => {
  902. if (animationFrame !== null) {
  903. window.cancelAnimationFrame(animationFrame);
  904. }
  905. scrollContainer.removeEventListener("scroll", scheduleUpdate);
  906. window.removeEventListener("resize", scheduleUpdate);
  907. resizeObserver?.disconnect();
  908. };
  909. }, [
  910. activeDragGroupId,
  911. activeDragTaskKey,
  912. collapsedGroupIds,
  913. groupedDraftTask?.placement,
  914. view.nodes,
  915. ]);
  916. const workspaceTabByKey = useMemo(
  917. () =>
  918. new Map(
  919. workspaceTabs.map((tab) => [
  920. buildTaskWorkspaceKey(tab.workspacePath, tab.workspaceIdentity),
  921. tab,
  922. ]),
  923. ),
  924. [workspaceTabs],
  925. );
  926. const getTaskWorkspaceLabel = useCallback(
  927. (task: ZCodeTaskMeta) => {
  928. const tab = workspaceTabByKey.get(
  929. buildTaskWorkspaceKey(task.workspacePath, task.workspaceIdentity),
  930. );
  931. if (tab?.workspacePurpose === "conversation") {
  932. return intl.formatMessage({
  933. id: "workspaceSidebar.conversationsSection",
  934. });
  935. }
  936. return (
  937. tab?.label || getPathLeaf(task.workspacePath) || task.workspacePath
  938. );
  939. },
  940. [intl, workspaceTabByKey],
  941. );
  942. const draftWorkspaceLabel = useMemo(() => {
  943. const tab = workspaceTabByKey.get(
  944. buildTaskWorkspaceKey(activeWorkspacePath, activeWorkspaceIdentity),
  945. );
  946. if (tab?.workspacePurpose === "conversation") {
  947. return intl.formatMessage({
  948. id: "workspaceSidebar.conversationsSection",
  949. });
  950. }
  951. return (
  952. tab?.label || getPathLeaf(activeWorkspacePath) || activeWorkspacePath
  953. );
  954. }, [activeWorkspaceIdentity, activeWorkspacePath, intl, workspaceTabByKey]);
  955. const getTaskRemoteSessionId = useCallback(
  956. (task: ZCodeTaskMeta) =>
  957. workspaceServiceLookup.get(
  958. buildTaskWorkspaceKey(task.workspacePath, task.workspaceIdentity),
  959. )?.remoteSessionId,
  960. [workspaceServiceLookup],
  961. );
  962. const handleOpenTaskFileTree = useCallback(
  963. (task: ZCodeTaskMeta) => {
  964. const target = resolveTaskFileTreeTargetFromTabs(task, workspaceTabs);
  965. if (!onOpenFileTree || !target) {
  966. return;
  967. }
  968. onOpenFileTree(target);
  969. },
  970. [onOpenFileTree, workspaceTabs],
  971. );
  972. const handleCreateGroup = useCallback(() => {
  973. void createGroup()
  974. .then((group) => {
  975. setNewGroupSetupId(group.id);
  976. })
  977. .catch(() => {
  978. toast(intl.formatMessage({ id: "taskGroup.createFailed" }));
  979. });
  980. }, [createGroup, intl]);
  981. useEffect(() => {
  982. onCreateGroupActionChange?.(handleCreateGroup);
  983. return () => onCreateGroupActionChange?.(null);
  984. }, [handleCreateGroup, onCreateGroupActionChange]);
  985. const handleNewGroupSetupStarted = useCallback((groupId: string) => {
  986. setNewGroupSetupId((currentGroupId) =>
  987. currentGroupId === groupId ? null : currentGroupId,
  988. );
  989. }, []);
  990. const handleToggleGroupCollapsed = useCallback(
  991. (groupId: string) => {
  992. onCollapsedGroupIdsChange((currentGroupIds) => {
  993. const nextGroupIds = new Set(currentGroupIds);
  994. if (nextGroupIds.has(groupId)) {
  995. nextGroupIds.delete(groupId);
  996. } else {
  997. nextGroupIds.add(groupId);
  998. }
  999. return nextGroupIds;
  1000. });
  1001. },
  1002. [onCollapsedGroupIdsChange],
  1003. );
  1004. const isGroupCollapsed = useCallback(
  1005. (groupId: string) => collapsedGroupIds.has(groupId),
  1006. [collapsedGroupIds],
  1007. );
  1008. const handleCancelRenameTask = useCallback(() => {
  1009. setRenamingTaskKey(null);
  1010. setRenameDraft("");
  1011. }, []);
  1012. const handleStartRenameTask = useCallback((task: ZCodeTaskMeta) => {
  1013. setRenamingTaskKey(taskKey(task));
  1014. setRenameDraft(task.title ?? "");
  1015. }, []);
  1016. const handleMoveTaskToGroup = useCallback(
  1017. (task: ZCodeTaskMeta, groupId: string | null) => {
  1018. // archivingTaskKeys 过滤后的 view 只用于渲染;若拿它计算并持久化排序,
  1019. // 归档请求失败前的任意结构变更都会把被隐藏任务从权威分组中永久删除。
  1020. const nextView = moveTaskByMenu(authoritativeView, task, groupId);
  1021. if (nextView === authoritativeView) {
  1022. return;
  1023. }
  1024. void applyOrder(nextView).catch(() => {
  1025. toast(intl.formatMessage({ id: "taskGroup.updateFailed" }));
  1026. });
  1027. },
  1028. [applyOrder, authoritativeView, intl],
  1029. );
  1030. const handleMoveTaskToTop = useCallback(
  1031. (task: ZCodeTaskMeta) => {
  1032. const nextView = moveTaskToTopByMenu(authoritativeView, task);
  1033. if (nextView === authoritativeView) {
  1034. return;
  1035. }
  1036. void applyOrder(nextView).catch(() => {
  1037. toast(intl.formatMessage({ id: "taskGroup.updateFailed" }));
  1038. });
  1039. },
  1040. [applyOrder, authoritativeView, intl],
  1041. );
  1042. const handleSubmitRenameTask = useCallback(async () => {
  1043. if (!renamingTaskKey) {
  1044. return;
  1045. }
  1046. const task = findTaskInGroupedView(view, renamingTaskKey);
  1047. if (!task) {
  1048. handleCancelRenameTask();
  1049. return;
  1050. }
  1051. const workspaceServices = workspaceServiceLookup.get(
  1052. buildTaskWorkspaceKey(task.workspacePath, task.workspaceIdentity),
  1053. );
  1054. if (!workspaceServices) {
  1055. handleCancelRenameTask();
  1056. return;
  1057. }
  1058. const normalizedTitle = renameDraft.trim();
  1059. if (normalizedTitle === (task.title ?? "").trim()) {
  1060. handleCancelRenameTask();
  1061. return;
  1062. }
  1063. try {
  1064. const meta = await workspaceServices.services.zcodeTaskService.renameTask(
  1065. {
  1066. taskId: task.taskId,
  1067. workspacePath: task.workspacePath,
  1068. title: normalizedTitle,
  1069. ...(task.workspaceIdentity
  1070. ? { workspaceIdentity: task.workspaceIdentity }
  1071. : {}),
  1072. },
  1073. );
  1074. if (!meta) {
  1075. toast(intl.formatMessage({ id: "taskList.renameFailed" }));
  1076. return;
  1077. }
  1078. setView((currentView) => replaceTaskInGroupedView(currentView, meta));
  1079. upsertOptimisticTaskListItem(
  1080. task.workspacePath,
  1081. meta,
  1082. task.workspaceIdentity,
  1083. );
  1084. applyTaskQueryCacheMutation({
  1085. previousTask: task,
  1086. nextTask: meta,
  1087. previousState: { pinned: false, archived: false },
  1088. nextState: { pinned: false, archived: false },
  1089. });
  1090. handleCancelRenameTask();
  1091. } catch {
  1092. toast(intl.formatMessage({ id: "taskList.renameFailed" }));
  1093. }
  1094. }, [
  1095. handleCancelRenameTask,
  1096. intl,
  1097. renameDraft,
  1098. renamingTaskKey,
  1099. setView,
  1100. upsertOptimisticTaskListItem,
  1101. view,
  1102. workspaceServiceLookup,
  1103. ]);
  1104. const handleMarkTaskAsUnread = useCallback(
  1105. (task: ZCodeTaskMeta) => {
  1106. const workspaceServices = workspaceServiceLookup.get(
  1107. buildTaskWorkspaceKey(task.workspacePath, task.workspaceIdentity),
  1108. );
  1109. if (!workspaceServices) {
  1110. return;
  1111. }
  1112. void workspaceServices.services.zcodeTaskService
  1113. .setTaskUnread({
  1114. taskId: task.taskId,
  1115. workspacePath: task.workspacePath,
  1116. unread: true,
  1117. ...(task.workspaceIdentity
  1118. ? { workspaceIdentity: task.workspaceIdentity }
  1119. : {}),
  1120. })
  1121. .then((meta) => {
  1122. setTaskUnreadIndicator(
  1123. task.workspacePath,
  1124. task.taskId,
  1125. true,
  1126. task.workspaceIdentity,
  1127. );
  1128. setView((currentView) => replaceTaskInGroupedView(currentView, meta));
  1129. upsertOptimisticTaskListItem(
  1130. task.workspacePath,
  1131. meta,
  1132. task.workspaceIdentity,
  1133. );
  1134. applyTaskQueryCacheMutation({
  1135. previousTask: task,
  1136. nextTask: meta,
  1137. previousState: { pinned: false, archived: false },
  1138. nextState: { pinned: false, archived: false },
  1139. });
  1140. })
  1141. .catch(() => {
  1142. toast(intl.formatMessage({ id: "taskList.markAsUnreadFailed" }));
  1143. });
  1144. },
  1145. [
  1146. intl,
  1147. setTaskUnreadIndicator,
  1148. setView,
  1149. upsertOptimisticTaskListItem,
  1150. workspaceServiceLookup,
  1151. ],
  1152. );
  1153. const handleCloseTask = useCallback(
  1154. (task: ZCodeTaskMeta) => {
  1155. const workspaceServices = workspaceServiceLookup.get(
  1156. buildTaskWorkspaceKey(task.workspacePath, task.workspaceIdentity),
  1157. );
  1158. if (!workspaceServices) {
  1159. return;
  1160. }
  1161. const closingTaskKey = taskKey(task);
  1162. setArchivingTaskKeys((current) => {
  1163. if (current.has(closingTaskKey)) {
  1164. return current;
  1165. }
  1166. return new Set(current).add(closingTaskKey);
  1167. });
  1168. void workspaceServices.services.zcodeTaskService
  1169. .archiveTask({
  1170. taskId: task.taskId,
  1171. workspacePath: task.workspacePath,
  1172. ...(task.workspaceIdentity
  1173. ? { workspaceIdentity: task.workspaceIdentity }
  1174. : {}),
  1175. })
  1176. .then((meta) => {
  1177. // grouped 的后台 refresh 可能携带归档前的 membership,直接覆盖乐观删除。
  1178. // 归档成功后主动换代 membership;渲染层在权威列表确认消失前继续屏蔽该 task。
  1179. bumpTaskListMembershipVersion();
  1180. removeTaskState(
  1181. task.workspacePath,
  1182. task.taskId,
  1183. task.workspaceIdentity,
  1184. );
  1185. if (task.workspaceIdentity) {
  1186. useRemoteTimelineTaskStore
  1187. .getState()
  1188. .removeTask(
  1189. task.workspacePath,
  1190. task.taskId,
  1191. task.workspaceIdentity,
  1192. );
  1193. useRemotePinnedTaskStore
  1194. .getState()
  1195. .removeTask(
  1196. task.workspacePath,
  1197. task.taskId,
  1198. task.workspaceIdentity,
  1199. );
  1200. }
  1201. applyTaskQueryCacheMutation({
  1202. previousTask: task,
  1203. nextTask: meta,
  1204. previousState: { pinned: false, archived: false },
  1205. nextState: { pinned: false, archived: true },
  1206. });
  1207. })
  1208. .catch(() => {
  1209. setArchivingTaskKeys((current) => {
  1210. if (!current.has(closingTaskKey)) {
  1211. return current;
  1212. }
  1213. const next = new Set(current);
  1214. next.delete(closingTaskKey);
  1215. return next;
  1216. });
  1217. toast(intl.formatMessage({ id: "taskList.archiveFailed" }));
  1218. });
  1219. },
  1220. [intl, removeTaskState, workspaceServiceLookup],
  1221. );
  1222. const handleRenameGroup = useCallback(
  1223. (groupId: string, title: string) => {
  1224. void renameGroup(groupId, title).catch(() => {
  1225. toast(intl.formatMessage({ id: "taskGroup.renameFailed" }));
  1226. });
  1227. },
  1228. [intl, renameGroup],
  1229. );
  1230. const handleUpdateGroupColor = useCallback(
  1231. (groupId: string, color: ZCodeTaskGroupColor) => {
  1232. void updateGroupColor(groupId, color).catch(() => {
  1233. toast(intl.formatMessage({ id: "taskGroup.colorFailed" }));
  1234. });
  1235. },
  1236. [intl, updateGroupColor],
  1237. );
  1238. const handleUngroupGroup = useCallback(
  1239. (groupId: string) => {
  1240. void ungroupGroup(groupId).catch(() => {
  1241. toast(intl.formatMessage({ id: "taskGroup.ungroupFailed" }));
  1242. });
  1243. },
  1244. [intl, ungroupGroup],
  1245. );
  1246. useEffect(() => {
  1247. return () => {
  1248. if (layoutAnimationFrameRef.current !== null) {
  1249. window.cancelAnimationFrame(layoutAnimationFrameRef.current);
  1250. }
  1251. };
  1252. }, []);
  1253. const setViewWithGroupedTaskAnimation = useCallback(
  1254. (nextView: ZCodeGroupedTaskView) => {
  1255. const previousRects = collectGroupedTaskLayoutRects(
  1256. groupedSectionRootRef.current,
  1257. );
  1258. setView(nextView);
  1259. if (layoutAnimationFrameRef.current !== null) {
  1260. window.cancelAnimationFrame(layoutAnimationFrameRef.current);
  1261. }
  1262. layoutAnimationFrameRef.current = window.requestAnimationFrame(() => {
  1263. layoutAnimationFrameRef.current = null;
  1264. animateGroupedTaskLayoutFrom(
  1265. groupedSectionRootRef.current,
  1266. previousRects,
  1267. );
  1268. });
  1269. },
  1270. [setView],
  1271. );
  1272. useEffect(() => {
  1273. if (!renamingTaskKey) {
  1274. return;
  1275. }
  1276. renameInputRef.current?.focus();
  1277. renameInputRef.current?.select();
  1278. }, [renamingTaskKey]);
  1279. useEffect(() => {
  1280. if (!renamingTaskKey) {
  1281. return;
  1282. }
  1283. if (!findTaskInGroupedView(view, renamingTaskKey)) {
  1284. handleCancelRenameTask();
  1285. }
  1286. }, [handleCancelRenameTask, renamingTaskKey, view]);
  1287. const restoreGroupDragCollapsedState = useCallback(() => {
  1288. const snapshot = groupDragCollapsedSnapshotRef.current;
  1289. if (!snapshot) {
  1290. return;
  1291. }
  1292. groupDragCollapsedSnapshotRef.current = null;
  1293. onCollapsedGroupIdsChange(() => new Set(snapshot));
  1294. }, [onCollapsedGroupIdsChange]);
  1295. const handleGroupedTaskDragStart = useCallback(
  1296. (event: DragStartEvent) => {
  1297. dragDirectionRef.current = "after";
  1298. lastDragDeltaYRef.current = 0;
  1299. lastDragOverEventRef.current = null;
  1300. const nextActiveGroupId = getGroupedTaskDragGroupId(
  1301. event.active.data.current,
  1302. );
  1303. if (nextActiveGroupId) {
  1304. dragOriginViewRef.current = authoritativeView;
  1305. dragPreviewViewRef.current = authoritativeView;
  1306. groupDragCollapsedSnapshotRef.current = new Set(collapsedGroupIds);
  1307. setActiveDragGroupId(nextActiveGroupId);
  1308. const nextWidth = measureGroupedGroupPreviewWidth(
  1309. groupedSectionRootRef.current,
  1310. nextActiveGroupId,
  1311. );
  1312. if (nextWidth !== null) {
  1313. setActiveDragOverlayWidth(nextWidth);
  1314. }
  1315. onCollapsedGroupIdsChange((currentGroupIds) => {
  1316. if (currentGroupIds.has(nextActiveGroupId)) {
  1317. return currentGroupIds;
  1318. }
  1319. const nextGroupIds = new Set(currentGroupIds);
  1320. nextGroupIds.add(nextActiveGroupId);
  1321. return nextGroupIds;
  1322. });
  1323. return;
  1324. }
  1325. const nextActiveTaskKey = getGroupedTaskDragTaskKey(
  1326. event.active.data.current,
  1327. );
  1328. if (!nextActiveTaskKey) {
  1329. return;
  1330. }
  1331. const activeTask = findTaskInGroupedView(view, nextActiveTaskKey);
  1332. if (activeTask) {
  1333. workbenchDragPayloadRef.current = {
  1334. kind: "zcode/session",
  1335. workspacePath: activeTask.workspacePath,
  1336. workspaceIdentity: activeTask.workspaceIdentity,
  1337. remoteSessionId: getTaskRemoteSessionId(activeTask),
  1338. sessionId: activeTask.taskId,
  1339. };
  1340. }
  1341. dragOriginViewRef.current = authoritativeView;
  1342. dragPreviewViewRef.current = authoritativeView;
  1343. // task overlay 宽度只在 drag start 测一次。
  1344. // 之前依赖 view 的 layout effect 会在每次拖拽 preview 重排后同步 setState,容易和 dnd-kit 测量形成嵌套更新循环。
  1345. const nextWidth = measureGroupedTaskPreviewWidth(
  1346. groupedSectionRootRef.current,
  1347. nextActiveTaskKey,
  1348. );
  1349. if (nextWidth !== null) {
  1350. setActiveDragOverlayWidth(nextWidth);
  1351. }
  1352. setActiveDragTaskKey(nextActiveTaskKey);
  1353. },
  1354. [
  1355. collapsedGroupIds,
  1356. getTaskRemoteSessionId,
  1357. onCollapsedGroupIdsChange,
  1358. authoritativeView,
  1359. view,
  1360. ],
  1361. );
  1362. const applyGroupedTaskDragOverPreview = useCallback(
  1363. (event: DragOverEvent) => {
  1364. const activeTaskKey = getGroupedTaskDragTaskKey(
  1365. event.active.data.current,
  1366. );
  1367. const activeGroupId = getGroupedTaskDragGroupId(
  1368. event.active.data.current,
  1369. );
  1370. if ((!activeTaskKey && !activeGroupId) || !event.over) {
  1371. return;
  1372. }
  1373. const currentPreviewView =
  1374. dragPreviewViewRef.current ?? authoritativeView;
  1375. const dragDirection = dragDirectionRef.current;
  1376. const nextView = activeGroupId
  1377. ? getGroupedGroupOverTaskPreviewView(
  1378. getGroupedGroupOverGroupPreviewView(
  1379. currentPreviewView,
  1380. event,
  1381. dragDirection,
  1382. ),
  1383. event,
  1384. dragDirection,
  1385. )
  1386. : getGroupedTaskOverTaskPreviewView(
  1387. getGroupedTaskOverEmptyDropZonePreviewView(
  1388. getGroupedTaskOverGroupFooterPreviewView(
  1389. getGroupedTaskOverGroupHeaderPreviewView(
  1390. getGroupedTaskOverCollapsedGroupPreviewView(
  1391. currentPreviewView,
  1392. event,
  1393. dragDirection,
  1394. ),
  1395. event,
  1396. dragDirection,
  1397. ),
  1398. event,
  1399. dragDirection,
  1400. ),
  1401. event,
  1402. ),
  1403. event,
  1404. dragDirection,
  1405. );
  1406. if (
  1407. nextView === currentPreviewView ||
  1408. getGroupedTaskViewSignature(nextView) ===
  1409. getGroupedTaskViewSignature(currentPreviewView)
  1410. ) {
  1411. return;
  1412. }
  1413. dragPreviewViewRef.current = nextView;
  1414. setViewWithGroupedTaskAnimation(nextView);
  1415. },
  1416. [authoritativeView, setViewWithGroupedTaskAnimation],
  1417. );
  1418. const handleGroupedTaskDragMove = useCallback(
  1419. (event: DragMoveEvent) => {
  1420. const workbenchPayload = workbenchDragPayloadRef.current;
  1421. const position = workbenchPointerPositionTrackerRef.current?.getPosition();
  1422. if (workbenchPayload && position) {
  1423. updateWorkbenchPointerDrag(
  1424. workbenchPayload,
  1425. position.x,
  1426. position.y,
  1427. );
  1428. }
  1429. const nextDeltaY = event.delta.y;
  1430. const previousDirection = dragDirectionRef.current;
  1431. if (nextDeltaY > lastDragDeltaYRef.current) {
  1432. dragDirectionRef.current = "after";
  1433. } else if (nextDeltaY < lastDragDeltaYRef.current) {
  1434. dragDirectionRef.current = "before";
  1435. }
  1436. lastDragDeltaYRef.current = nextDeltaY;
  1437. if (
  1438. dragDirectionRef.current !== previousDirection &&
  1439. lastDragOverEventRef.current
  1440. ) {
  1441. applyGroupedTaskDragOverPreview(lastDragOverEventRef.current);
  1442. }
  1443. },
  1444. [applyGroupedTaskDragOverPreview],
  1445. );
  1446. const handleGroupedTaskDragOver = useCallback(
  1447. (event: DragOverEvent) => {
  1448. lastDragOverEventRef.current = event.over ? event : null;
  1449. applyGroupedTaskDragOverPreview(event);
  1450. },
  1451. [applyGroupedTaskDragOverPreview],
  1452. );
  1453. const resetGroupedTaskDrag = useCallback(() => {
  1454. cancelWorkbenchPointerDrag();
  1455. workbenchDragPayloadRef.current = null;
  1456. workbenchPointerPositionTrackerRef.current?.dispose();
  1457. workbenchPointerPositionTrackerRef.current = null;
  1458. setActiveDragTaskKey(null);
  1459. setActiveDragGroupId(null);
  1460. setActiveDragOverlayWidth(null);
  1461. dragDirectionRef.current = "after";
  1462. lastDragDeltaYRef.current = 0;
  1463. lastDragOverEventRef.current = null;
  1464. dragOriginViewRef.current = null;
  1465. dragPreviewViewRef.current = null;
  1466. }, []);
  1467. const handleGroupedTaskDragCancel = useCallback(
  1468. (event?: DragCancelEvent) => {
  1469. const activeGroupId =
  1470. getGroupedTaskDragGroupId(event?.active.data.current) ??
  1471. activeDragGroupId;
  1472. if (activeGroupId) {
  1473. restoreGroupDragCollapsedState();
  1474. resetGroupedTaskDrag();
  1475. return;
  1476. }
  1477. if (dragOriginViewRef.current) {
  1478. setViewWithGroupedTaskAnimation(dragOriginViewRef.current);
  1479. }
  1480. resetGroupedTaskDrag();
  1481. },
  1482. [
  1483. activeDragGroupId,
  1484. resetGroupedTaskDrag,
  1485. restoreGroupDragCollapsedState,
  1486. setViewWithGroupedTaskAnimation,
  1487. ],
  1488. );
  1489. const handleGroupedTaskDragEnd = useCallback(
  1490. (event: DragEndEvent) => {
  1491. const activeGroupId =
  1492. getGroupedTaskDragGroupId(event.active.data.current) ??
  1493. activeDragGroupId;
  1494. if (activeGroupId) {
  1495. const originView = dragOriginViewRef.current;
  1496. const currentPreviewView =
  1497. dragPreviewViewRef.current ?? authoritativeView;
  1498. const nextView = currentPreviewView;
  1499. restoreGroupDragCollapsedState();
  1500. resetGroupedTaskDrag();
  1501. if (
  1502. !originView ||
  1503. getGroupedTaskViewSignature(nextView) ===
  1504. getGroupedTaskViewSignature(originView)
  1505. ) {
  1506. if (originView) {
  1507. setViewWithGroupedTaskAnimation(originView);
  1508. }
  1509. return;
  1510. }
  1511. setViewWithGroupedTaskAnimation(nextView);
  1512. void applyOrder(nextView).catch(() => {
  1513. setViewWithGroupedTaskAnimation(originView);
  1514. toast(intl.formatMessage({ id: "taskGroup.updateFailed" }));
  1515. });
  1516. return;
  1517. }
  1518. const originView = dragOriginViewRef.current;
  1519. const workbenchPayload = workbenchDragPayloadRef.current;
  1520. const workbenchDropPosition =
  1521. workbenchPointerPositionTrackerRef.current?.getPosition() ?? null;
  1522. if (
  1523. originView &&
  1524. workbenchPayload &&
  1525. workbenchDropPosition &&
  1526. finishWorkbenchPointerDrag(
  1527. workbenchPayload,
  1528. workbenchDropPosition.x,
  1529. workbenchDropPosition.y,
  1530. )
  1531. ) {
  1532. resetGroupedTaskDrag();
  1533. setViewWithGroupedTaskAnimation(originView);
  1534. return;
  1535. }
  1536. const currentPreviewView =
  1537. dragPreviewViewRef.current ?? authoritativeView;
  1538. const nextView = currentPreviewView;
  1539. resetGroupedTaskDrag();
  1540. if (
  1541. !originView ||
  1542. getGroupedTaskViewSignature(nextView) ===
  1543. getGroupedTaskViewSignature(originView)
  1544. ) {
  1545. if (originView) {
  1546. setViewWithGroupedTaskAnimation(originView);
  1547. }
  1548. return;
  1549. }
  1550. setViewWithGroupedTaskAnimation(nextView);
  1551. void applyOrder(nextView).catch(() => {
  1552. setViewWithGroupedTaskAnimation(originView);
  1553. toast(intl.formatMessage({ id: "taskGroup.updateFailed" }));
  1554. });
  1555. },
  1556. [
  1557. activeDragGroupId,
  1558. applyOrder,
  1559. authoritativeView,
  1560. intl,
  1561. resetGroupedTaskDrag,
  1562. restoreGroupDragCollapsedState,
  1563. setViewWithGroupedTaskAnimation,
  1564. ],
  1565. );
  1566. const activeDragTask = useMemo(
  1567. () =>
  1568. activeDragTaskKey
  1569. ? findTaskInGroupedView(view, activeDragTaskKey)
  1570. : null,
  1571. [activeDragTaskKey, view],
  1572. );
  1573. const activeDragGroup = useMemo(
  1574. () =>
  1575. activeDragGroupId
  1576. ? view.nodes.find(
  1577. (node) =>
  1578. node.type === "group" && node.group.id === activeDragGroupId,
  1579. )
  1580. : null,
  1581. [activeDragGroupId, view.nodes],
  1582. );
  1583. useEffect(() => {
  1584. const dragging = activeDragTaskKey !== null || activeDragGroupId !== null;
  1585. if (!dragging || typeof document === "undefined") {
  1586. return undefined;
  1587. }
  1588. const previousCursor = document.body.style.cursor;
  1589. document.body.style.cursor = "grabbing";
  1590. return () => {
  1591. document.body.style.cursor = previousCursor;
  1592. };
  1593. }, [activeDragTaskKey, activeDragGroupId]);
  1594. const groupedTooltipsDisabled =
  1595. activeDragTaskKey !== null || activeDragGroupId !== null;
  1596. const stickyGroupNode = useMemo(
  1597. () =>
  1598. stickyGroupId
  1599. ? view.nodes.find(
  1600. (node) => node.type === "group" && node.group.id === stickyGroupId,
  1601. )
  1602. : null,
  1603. [view.nodes, stickyGroupId],
  1604. );
  1605. useEffect(() => {
  1606. if (!onStickyGroupHeaderChange) {
  1607. return undefined;
  1608. }
  1609. if (stickyGroupNode?.type !== "group") {
  1610. onStickyGroupHeaderChange(null);
  1611. return () => onStickyGroupHeaderChange(null);
  1612. }
  1613. onStickyGroupHeaderChange(
  1614. <StickyGroupHeader
  1615. node={stickyGroupNode}
  1616. collapsed={collapsedGroupIds.has(stickyGroupNode.group.id)}
  1617. tooltipsDisabled={groupedTooltipsDisabled}
  1618. onCreateTask={() =>
  1619. stickyGroupNode.group.id === OFF_PEAK_DEFAULT_GROUP_ID
  1620. ? onOpenAutomations?.()
  1621. : handleCreateGroupDraftTask(stickyGroupNode.group.id)
  1622. }
  1623. onToggleCollapsed={handleToggleGroupCollapsed}
  1624. onUpdateGroupColor={handleUpdateGroupColor}
  1625. onUngroupGroup={handleUngroupGroup}
  1626. />,
  1627. );
  1628. return () => onStickyGroupHeaderChange(null);
  1629. }, [
  1630. collapsedGroupIds,
  1631. groupedTooltipsDisabled,
  1632. handleCreateGroupDraftTask,
  1633. onOpenAutomations,
  1634. handleToggleGroupCollapsed,
  1635. handleUngroupGroup,
  1636. handleUpdateGroupColor,
  1637. onStickyGroupHeaderChange,
  1638. stickyGroupNode,
  1639. ]);
  1640. const renderTopLevelNode = useCallback(
  1641. (node: ZCodeGroupedTaskView["nodes"][number]) =>
  1642. node.type === "group" ? (
  1643. <div
  1644. key={node.group.id}
  1645. data-grouped-layout-key={`group:${node.group.id}`}
  1646. >
  1647. <GroupItem
  1648. node={node}
  1649. groups={groups}
  1650. activeWorkspacePath={activeWorkspacePath}
  1651. activeWorkspaceIdentity={activeWorkspaceIdentity}
  1652. activeTaskId={activeTaskId}
  1653. mobileActiveTaskKey={mobileActiveTaskKey}
  1654. getTaskRemoteSessionId={getTaskRemoteSessionId}
  1655. getTaskWorkspaceLabel={getTaskWorkspaceLabel}
  1656. onSelectTask={onSelectTask}
  1657. onCloseTask={handleCloseTask}
  1658. onOpenFileTree={onOpenFileTree ? handleOpenTaskFileTree : undefined}
  1659. onCreateTask={() =>
  1660. node.group.id === OFF_PEAK_DEFAULT_GROUP_ID
  1661. ? onOpenAutomations?.()
  1662. : handleCreateGroupDraftTask(node.group.id)
  1663. }
  1664. hasDraftTask={
  1665. groupedDraftTask?.placement.type === "group" &&
  1666. groupedDraftTask.placement.groupId === node.group.id
  1667. }
  1668. draftTaskActive={isGroupedDraftActive}
  1669. draftWorkspaceLabel={draftWorkspaceLabel}
  1670. onSelectDraftTask={() => handleCreateGroupDraftTask(node.group.id)}
  1671. onCloseDraftTask={handleCloseGroupedDraftTask}
  1672. onRenameGroup={handleRenameGroup}
  1673. onUpdateGroupColor={handleUpdateGroupColor}
  1674. onUngroupGroup={handleUngroupGroup}
  1675. onMoveTaskToGroup={handleMoveTaskToGroup}
  1676. onMoveTaskToTop={handleMoveTaskToTop}
  1677. onStartRenameTask={handleStartRenameTask}
  1678. onArchiveTask={handleCloseTask}
  1679. onMarkTaskAsUnread={handleMarkTaskAsUnread}
  1680. newGroupSetup={newGroupSetupId === node.group.id}
  1681. onNewGroupSetupStarted={handleNewGroupSetupStarted}
  1682. collapsed={collapsedGroupIds.has(node.group.id)}
  1683. onToggleCollapsed={handleToggleGroupCollapsed}
  1684. activeDragTaskKey={activeDragTaskKey}
  1685. activeDragGroupId={activeDragGroupId}
  1686. tooltipsDisabled={groupedTooltipsDisabled}
  1687. />
  1688. </div>
  1689. ) : (
  1690. <GroupedTaskItem
  1691. key={taskKey(node.task)}
  1692. task={node.task}
  1693. groups={groups}
  1694. remoteSessionId={getTaskRemoteSessionId(node.task)}
  1695. workspaceLabel={getTaskWorkspaceLabel(node.task)}
  1696. activeWorkspacePath={activeWorkspacePath}
  1697. activeWorkspaceIdentity={activeWorkspaceIdentity}
  1698. activeTaskId={activeTaskId}
  1699. mobileActiveTaskKey={mobileActiveTaskKey}
  1700. onSelectTask={onSelectTask}
  1701. onCloseTask={handleCloseTask}
  1702. onOpenFileTree={onOpenFileTree ? handleOpenTaskFileTree : undefined}
  1703. onMoveTaskToGroup={handleMoveTaskToGroup}
  1704. onMoveTaskToTop={handleMoveTaskToTop}
  1705. onStartRenameTask={handleStartRenameTask}
  1706. onArchiveTask={handleCloseTask}
  1707. onMarkTaskAsUnread={handleMarkTaskAsUnread}
  1708. dragId={taskKey(node.task)}
  1709. dragging={activeDragTaskKey === taskKey(node.task)}
  1710. tooltipsDisabled={groupedTooltipsDisabled}
  1711. />
  1712. ),
  1713. [
  1714. activeTaskId,
  1715. activeWorkspaceIdentity,
  1716. activeWorkspacePath,
  1717. activeDragTaskKey,
  1718. activeDragGroupId,
  1719. groupedTooltipsDisabled,
  1720. collapsedGroupIds,
  1721. draftWorkspaceLabel,
  1722. getTaskRemoteSessionId,
  1723. getTaskWorkspaceLabel,
  1724. groupedDraftTask?.placement,
  1725. groups,
  1726. handleCloseGroupedDraftTask,
  1727. handleCloseTask,
  1728. handleCreateGroupDraftTask,
  1729. onOpenAutomations,
  1730. handleMoveTaskToGroup,
  1731. handleMoveTaskToTop,
  1732. handleNewGroupSetupStarted,
  1733. handleOpenTaskFileTree,
  1734. handleRenameGroup,
  1735. handleToggleGroupCollapsed,
  1736. handleUngroupGroup,
  1737. handleUpdateGroupColor,
  1738. handleMarkTaskAsUnread,
  1739. handleStartRenameTask,
  1740. isGroupedDraftActive,
  1741. mobileActiveTaskKey,
  1742. newGroupSetupId,
  1743. onOpenFileTree,
  1744. onSelectTask,
  1745. ],
  1746. );
  1747. // 首次权威请求结束前既需要阻止 grouped draft/空态抢先出现,又曾把这个
  1748. // 数据门禁直接渲染成“正在获取任务”;切换到分组时,置顶列表下方因此闪出无帮助的文案。
  1749. // 这里保留 initialized 门禁但隐藏主体,数据就绪后再一次性展示权威列表。
  1750. // 门禁只该拦首屏。之前每次会话流式节点都可能让它回关,
  1751. // grouped 整棵子树随之卸载再重挂载——这就是「左侧分组列表整块闪一下」。
  1752. // 画过一次列表后一律继续渲染,旧数据优于空白。
  1753. if (
  1754. shouldHideGroupedTaskContent({
  1755. initialized,
  1756. loading,
  1757. hasNodes: view.nodes.length > 0,
  1758. hasPaintedOnce: hasPaintedGroupedListRef.current,
  1759. })
  1760. ) {
  1761. return null;
  1762. }
  1763. if (view.nodes.length > 0) {
  1764. // 渲染期写 ref 的前提(禁止照搬到非单调状态):本 ref 是单调闩锁(false→true,永不回落),
  1765. // 新值只由本次渲染的 view 内容推导。concurrent 下被丢弃的渲染也会执行这次赋值,最坏结果是
  1766. // 门禁提前开门一帧、显示空态文案而不是隐藏;对可回落状态用同样写法则会产生不可复现的漏帧。
  1767. hasPaintedGroupedListRef.current = true;
  1768. }
  1769. const dragOverlayWidthStyle = activeDragOverlayWidth
  1770. ? { width: `${activeDragOverlayWidth}px` }
  1771. : undefined;
  1772. const dragOverlayWidthClassName =
  1773. "transition-[width,max-width] duration-150 ease-out motion-reduce:transition-none";
  1774. const groupedTaskDragOverlay = (
  1775. <DragOverlay dropAnimation={GROUPED_TASK_DROP_ANIMATION}>
  1776. {activeDragTask ? (
  1777. <div
  1778. className={dragOverlayWidthClassName}
  1779. style={dragOverlayWidthStyle}
  1780. >
  1781. <GroupedTaskItem
  1782. task={activeDragTask}
  1783. groups={groups}
  1784. remoteSessionId={getTaskRemoteSessionId(activeDragTask)}
  1785. workspaceLabel={getTaskWorkspaceLabel(activeDragTask)}
  1786. activeWorkspacePath={activeWorkspacePath}
  1787. activeWorkspaceIdentity={activeWorkspaceIdentity}
  1788. activeTaskId={activeTaskId}
  1789. mobileActiveTaskKey={mobileActiveTaskKey}
  1790. onSelectTask={onSelectTask}
  1791. onCloseTask={handleCloseTask}
  1792. onOpenFileTree={onOpenFileTree ? handleOpenTaskFileTree : undefined}
  1793. onMoveTaskToGroup={handleMoveTaskToGroup}
  1794. onMoveTaskToTop={handleMoveTaskToTop}
  1795. onStartRenameTask={handleStartRenameTask}
  1796. onArchiveTask={handleCloseTask}
  1797. onMarkTaskAsUnread={handleMarkTaskAsUnread}
  1798. dragId={activeDragTaskKey ?? undefined}
  1799. dragOverlay
  1800. />
  1801. </div>
  1802. ) : activeDragGroup?.type === "group" ? (
  1803. <GroupDragOverlay
  1804. node={activeDragGroup}
  1805. className={dragOverlayWidthClassName}
  1806. style={dragOverlayWidthStyle}
  1807. />
  1808. ) : null}
  1809. </DragOverlay>
  1810. );
  1811. return (
  1812. <>
  1813. <TaskRenameDialog
  1814. open={renamingTaskKey !== null}
  1815. value={renameDraft}
  1816. inputRef={renameInputRef}
  1817. intl={intl}
  1818. onOpenChange={(open) => {
  1819. if (!open) {
  1820. handleCancelRenameTask();
  1821. }
  1822. }}
  1823. onChange={setRenameDraft}
  1824. onCancel={handleCancelRenameTask}
  1825. onConfirm={() => {
  1826. void handleSubmitRenameTask();
  1827. }}
  1828. />
  1829. <DndContext
  1830. sensors={sensors}
  1831. autoScroll={{ threshold: GROUPED_TASK_AUTO_SCROLL_THRESHOLD }}
  1832. collisionDetection={groupedTaskCollisionDetection}
  1833. onDragStart={handleGroupedTaskDragStart}
  1834. onDragMove={handleGroupedTaskDragMove}
  1835. onDragOver={handleGroupedTaskDragOver}
  1836. onDragEnd={handleGroupedTaskDragEnd}
  1837. onDragCancel={handleGroupedTaskDragCancel}
  1838. >
  1839. <div
  1840. ref={groupedSectionRootRef}
  1841. onPointerDownCapture={handleGroupedPointerDownCapture}
  1842. className={cn("pb-4", saving && "opacity-90")}
  1843. >
  1844. {groupedDraftTask?.placement.type === "top" ? (
  1845. <GroupedDraftTaskRow
  1846. active={isGroupedDraftActive}
  1847. workspaceLabel={draftWorkspaceLabel}
  1848. onSelect={handleCreateTopDraftTask}
  1849. onClose={handleCloseGroupedDraftTask}
  1850. />
  1851. ) : null}
  1852. <VirtualizedGroupedTopLevelList
  1853. nodes={view.nodes}
  1854. isGroupCollapsed={isGroupCollapsed}
  1855. renderNode={renderTopLevelNode}
  1856. />
  1857. {view.nodes.length === 0 &&
  1858. !groupedDraftTask &&
  1859. !loading ? (
  1860. <div className="px-3 py-2 text-ui-base text-foreground-subtle">
  1861. {intl.formatMessage({ id: "taskList.noTasks" })}
  1862. </div>
  1863. ) : null}
  1864. </div>
  1865. {/* overlay 是鼠标浮层,挂到 body,避免被 grouped task 滚动容器的滚动条/裁剪上下文影响。 */}
  1866. {typeof document === "undefined"
  1867. ? groupedTaskDragOverlay
  1868. : createPortal(groupedTaskDragOverlay, document.body)}
  1869. </DndContext>
  1870. </>
  1871. );
  1872. }