workflowTimelineLedge.test.ts 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421
  1. // @vitest-environment jsdom
  2. // 边檐(docs/dynamic-workflow/presentation.md「Overflow: the ledge」):纯几何(折叠不动点、檐宽、遮罩、
  3. // 拇指)与 DOM(檐上的灯、折叠的站、点灯回镜头、← → 翻站)。jsdom 量不出尺寸,几何由原型 getter 假装。
  4. import { act, cleanup, fireEvent, render, waitFor } from "@testing-library/react";
  5. import { createElement } from "react";
  6. import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
  7. import type { WorkflowCausalityGraphData } from "@/components/workflow-graph/types.js";
  8. import { buildWorkflowTimeline } from "@/components/workflow-timeline/timeline-model.js";
  9. import { draftTimeline, scanWorkflowDraft } from "@/components/workflow-timeline/draft-scan.js";
  10. import {
  11. NO_FOLD,
  12. flightAfterScroll,
  13. foldStations,
  14. ledgeLamps,
  15. ledgeStubWidth,
  16. ledgeWidth,
  17. scrollbarThumb,
  18. stationCameraLeft,
  19. timelineMaskStyle,
  20. } from "@/components/workflow-timeline/timeline-ledge.js";
  21. import { timelineWidth } from "@/components/workflow-timeline/timeline-geometry.js";
  22. import { WorkflowTimeline } from "@/components/workflow-timeline/WorkflowTimeline.js";
  23. import { ZCodeIntlProvider } from "@/i18n/IntlProvider.js";
  24. import enUS from "../src/i18n/locales/en-US.js";
  25. import zhCN from "../src/i18n/locales/zh-CN.js";
  26. describe("timeline-ledge geometry", () => {
  27. it("ledge width: none for none, lamps 16 apart with 8px pads, +n past three", () => {
  28. expect(ledgeWidth(0)).toBe(0);
  29. expect(ledgeWidth(1)).toBe(26);
  30. expect(ledgeWidth(3)).toBe(58);
  31. expect(ledgeWidth(4)).toBe(84);
  32. });
  33. it("folds nothing when the viewport is unmeasured", () => {
  34. expect(foldStations(8, 300, 0)).toBe(NO_FOLD);
  35. expect(foldStations(0, 0, 960)).toBe(NO_FOLD);
  36. });
  37. it("at the start, the three stations past the right edge fold; the fixpoint pulls none more", () => {
  38. // lamps at 17 + 192·i: verify (977), publish, wrap-up are past 960; revise (785) stays clear of 960 − 98.
  39. expect(foldStations(8, 0, 960)).toEqual({ left: [], right: [5, 6, 7] });
  40. });
  41. it("scrolled to the end, the fixpoint folds the station whose lamp sits under the growing ledge", () => {
  42. // review's lamp lands at 41: outside the first pass (x < 0) but under ledge(3) + fade = 98.
  43. expect(foldStations(8, 552, 960)).toEqual({ left: [0, 1, 2, 3], right: [] });
  44. });
  45. it("keep: the camera's target station never folds while the rest still do", () => {
  46. // 追记「草稿时间线的边檐误折」:镜头在飞时目标站不折——它就要进视野了,檐上闪一枚灯是误报。
  47. expect(foldStations(8, 0, 960, 5)).toEqual({ left: [], right: [6, 7] });
  48. expect(foldStations(8, 552, 960, 7)).toEqual({ left: [0, 1, 2, 3], right: [] });
  49. });
  50. it("a flight follows the scroll, lands within 1px, and ends when the scroll turns away", () => {
  51. const flight = { from: 360, index: 7, target: 552 };
  52. expect(flightAfterScroll(flight, 450)).toEqual({ from: 450, index: 7, target: 552 });
  53. expect(flightAfterScroll(flight, 551)).toBeUndefined();
  54. // 离目标比上一次采样更远:平滑滚动只会单调靠近,这是用户接手了。
  55. expect(flightAfterScroll(flight, 300)).toBeUndefined();
  56. expect(flightAfterScroll(undefined, 300)).toBeUndefined();
  57. });
  58. it("shows at most three lamps, nearest to the content, and counts the rest", () => {
  59. expect(ledgeLamps([0, 1, 2, 3, 4, 5, 6], "left")).toEqual({ shown: [4, 5, 6], more: 4 });
  60. expect(ledgeLamps([5, 6, 7, 8, 9, 10, 11], "right")).toEqual({
  61. shown: [5, 6, 7],
  62. more: 4,
  63. });
  64. expect(ledgeLamps([5, 6], "right")).toEqual({ shown: [5, 6], more: 0 });
  65. });
  66. it("stubs reach the first open lamp on the left and start at the slot end on the right", () => {
  67. const end = foldStations(8, 552, 960);
  68. // revise's lamp at 233; ledge(4) = three lamps + `+1`, inner edge at 84 − 8 = 76; 233 − 6 − 76.
  69. expect(ledgeStubWidth(end, "left", 552, 960)).toBe(151);
  70. expect(ledgeStubWidth(end, "right", 552, 960)).toBe(0);
  71. const start = foldStations(8, 0, 960);
  72. // revise's slot ends at 936; the ledge's inner edge is 960 − 50 = 910: shorter than 6 → none.
  73. expect(ledgeStubWidth(start, "right", 0, 960)).toBe(0);
  74. });
  75. it("masks in two bands: the rail row beside the ledge, the pills only at the viewport edge", () => {
  76. expect(timelineMaskStyle(NO_FOLD, 30, { left: false, right: false })).toBeUndefined();
  77. const start = timelineMaskStyle({ left: [], right: [5, 6, 7] }, 30, {
  78. left: false,
  79. right: true,
  80. });
  81. expect(start?.maskImage).toBe(
  82. "linear-gradient(90deg, #000 0px, #000 calc(100% - 106px), transparent calc(100% - 66px)), linear-gradient(90deg, #000 0px, #000 calc(100% - 40px), transparent 100%)",
  83. );
  84. expect(start?.maskSize).toBe("100% 30px, 100% calc(100% - 30px)");
  85. expect(start?.maskPosition).toBe("0 0, 0 30px");
  86. expect(start?.maskRepeat).toBe("no-repeat, no-repeat");
  87. expect(start?.WebkitMaskImage).toBe(start?.maskImage);
  88. // no ledge on a side that still overflows: the rail row fades at the edge like the pills do
  89. const plain = timelineMaskStyle(NO_FOLD, 30, { left: true, right: true });
  90. expect(plain?.maskImage).toBe(
  91. "linear-gradient(90deg, transparent 0px, #000 40px, #000 calc(100% - 40px), transparent 100%), linear-gradient(90deg, transparent 0px, #000 40px, #000 calc(100% - 40px), transparent 100%)",
  92. );
  93. const end = timelineMaskStyle({ left: [0, 1, 2, 3], right: [] }, 30, {
  94. left: true,
  95. right: false,
  96. });
  97. expect(end?.maskImage).toBe(
  98. "linear-gradient(90deg, transparent 92px, #000 132px, #000 100%), linear-gradient(90deg, transparent 0px, #000 40px, #000 100%)",
  99. );
  100. });
  101. it("thumb: viewport² / content, positioned by the scroll ratio, absent without overflow", () => {
  102. expect(scrollbarThumb(0, 960, 936)).toBeUndefined();
  103. expect(scrollbarThumb(0, 960, 0)).toBeUndefined();
  104. expect(scrollbarThumb(0, 960, 1512)).toEqual({ left: 0, width: 610 });
  105. expect(scrollbarThumb(552, 960, 1512)).toEqual({ left: 350, width: 610 });
  106. expect(scrollbarThumb(0, 100, 10_000)?.width).toBe(24);
  107. });
  108. it("camera centres a station and never scrolls past the start", () => {
  109. expect(stationCameraLeft(5, 960)).toBe(564);
  110. expect(stationCameraLeft(0, 960)).toBe(0);
  111. });
  112. it("has both locales for the ledge and scrollbar labels", () => {
  113. for (const key of [
  114. "chat.toolCall.workflow.timeline.ledge.earlier",
  115. "chat.toolCall.workflow.timeline.ledge.later",
  116. "chat.toolCall.workflow.timeline.scrollbar",
  117. ]) {
  118. expect(enUS[key as keyof typeof enUS]).toBeTruthy();
  119. expect(zhCN[key as keyof typeof zhCN]).toBeTruthy();
  120. }
  121. });
  122. });
  123. const NAMES = ["scope", "survey", "draft", "review", "revise", "verify", "publish", "wrap-up"];
  124. const GRAPH: WorkflowCausalityGraphData = {
  125. steps: NAMES.map((name, i) => ({
  126. id: `ask#${i + 1}`,
  127. kind: "ask",
  128. label: name,
  129. line: i + 1,
  130. column: 1,
  131. lane: "actor#1",
  132. phase: `phase#${i + 1}`,
  133. })),
  134. lanes: [{ id: "actor#1", name: "worker", line: 1, column: 1 }],
  135. participants: NAMES.map((_, i) => ({
  136. id: `phase#${i + 1}:actor#1`,
  137. phase: `phase#${i + 1}`,
  138. lane: "actor#1",
  139. steps: [`ask#${i + 1}`],
  140. })),
  141. handoffs: [],
  142. phases: NAMES.map((name, i) => ({ id: `phase#${i + 1}`, name, line: i + 1, column: 1 })),
  143. phaseEdges: NAMES.slice(1).map((_, i) => ({ from: `phase#${i + 1}`, to: `phase#${i + 2}` })),
  144. exits: ["phase#8"],
  145. } as WorkflowCausalityGraphData;
  146. const VIEW = 960;
  147. const SCROLLER = "workflow-timeline-scroller";
  148. let scrollLeftStore = 0;
  149. function fakeGeometry(
  150. contentWidth: (scroller: HTMLElement) => number = () => timelineWidth(NAMES.length),
  151. ) {
  152. const isScroller = (element: HTMLElement) => element.dataset["testid"] === SCROLLER;
  153. Object.defineProperty(HTMLElement.prototype, "clientWidth", {
  154. configurable: true,
  155. get(this: HTMLElement) {
  156. return isScroller(this) ? VIEW : 0;
  157. },
  158. });
  159. Object.defineProperty(HTMLElement.prototype, "scrollWidth", {
  160. configurable: true,
  161. get(this: HTMLElement) {
  162. return isScroller(this) ? contentWidth(this) : 0;
  163. },
  164. });
  165. Object.defineProperty(HTMLElement.prototype, "scrollLeft", {
  166. configurable: true,
  167. get(this: HTMLElement) {
  168. return isScroller(this) ? scrollLeftStore : 0;
  169. },
  170. set(this: HTMLElement, value: number) {
  171. if (isScroller(this)) scrollLeftStore = value;
  172. },
  173. });
  174. }
  175. describe("WorkflowTimeline ledge", () => {
  176. const scrollTo = vi.fn();
  177. beforeEach(() => {
  178. scrollLeftStore = 0;
  179. scrollTo.mockReset();
  180. fakeGeometry();
  181. Element.prototype.scrollTo = scrollTo as unknown as Element["scrollTo"];
  182. });
  183. afterEach(() => {
  184. cleanup();
  185. for (const key of ["clientWidth", "scrollWidth", "scrollLeft"]) {
  186. delete (HTMLElement.prototype as unknown as Record<string, unknown>)[key];
  187. }
  188. });
  189. function renderTimeline(onSelectStation?: () => void) {
  190. const model = buildWorkflowTimeline(GRAPH, undefined);
  191. return render(
  192. createElement(
  193. ZCodeIntlProvider,
  194. { initialLocale: "en-US" },
  195. createElement(WorkflowTimeline, {
  196. model,
  197. ...(onSelectStation === undefined ? {} : { onSelectStation }),
  198. }),
  199. ),
  200. );
  201. }
  202. async function scrollBy(view: ReturnType<typeof render>, left: number) {
  203. scrollLeftStore = left;
  204. await act(async () => {
  205. fireEvent.scroll(view.getByTestId(SCROLLER));
  206. await new Promise((resolve) => requestAnimationFrame(() => resolve(undefined)));
  207. });
  208. }
  209. it("folds the stations past the right edge onto the right ledge and masks that side only", async () => {
  210. const view = renderTimeline();
  211. await waitFor(() => expect(view.getByTestId("workflow-timeline-ledge-right")).toBeTruthy());
  212. expect(view.queryByTestId("workflow-timeline-ledge-left")).toBeNull();
  213. expect(view.container.querySelector("[data-ledge-ink]")?.className).toContain("border-t");
  214. expect(view.container.querySelector("[data-ledge-ink]")?.className).toContain(
  215. "border-foreground-subtlest",
  216. );
  217. const lamps = view.getAllByTestId("workflow-timeline-ledge-lamp");
  218. expect(lamps.map((lamp) => lamp.getAttribute("data-station-index"))).toEqual(["5", "6", "7"]);
  219. expect(lamps[0]?.getAttribute("title")).toBe("verify · pending");
  220. const stations = view.getAllByTestId("workflow-timeline-station");
  221. expect(stations[5]?.getAttribute("data-station-folded")).toBe("true");
  222. expect(stations[4]?.getAttribute("data-station-folded")).toBeNull();
  223. expect(view.getByTestId(SCROLLER).getAttribute("data-timeline-fade")).toBe("right");
  224. expect(view.queryByTestId("workflow-rank-strip")).toBeNull();
  225. expect(view.getByTestId("workflow-timeline-scrollbar")).toBeTruthy();
  226. });
  227. it("re-folds on scroll: the left ledge takes the stations that left, and the fixpoint takes review", async () => {
  228. const view = renderTimeline();
  229. await scrollBy(view, 552);
  230. await waitFor(() => expect(view.getByTestId("workflow-timeline-ledge-left")).toBeTruthy());
  231. expect(view.queryByTestId("workflow-timeline-ledge-right")).toBeNull();
  232. const lamps = view.getAllByTestId("workflow-timeline-ledge-lamp");
  233. expect(lamps.map((lamp) => lamp.getAttribute("data-station-index"))).toEqual(["1", "2", "3"]);
  234. expect(view.getByTestId("workflow-timeline-ledge-more").textContent).toBe("+1");
  235. expect(view.getByTestId("workflow-timeline-scrollbar").getAttribute("data-scrolling")).toBe(
  236. "true",
  237. );
  238. const thumb = view.getByTestId("workflow-timeline-scrollbar-thumb");
  239. expect(thumb.style.left).toBe("350px");
  240. expect(thumb.style.width).toBe("610px");
  241. expect(view.getByTestId(SCROLLER).getAttribute("data-timeline-fade")).toBe("left");
  242. });
  243. it("the scrollbar keeps its clicks: dragging the thumb or paging the track never reaches the host card", async () => {
  244. // 宿主卡(轮尾摘要)把空白处的 click 当折叠;拖完拇指浏览器会补发 click,它不能冒上去。
  245. const onHostClick = vi.fn();
  246. const model = buildWorkflowTimeline(GRAPH, undefined);
  247. const view = render(
  248. createElement(
  249. ZCodeIntlProvider,
  250. { initialLocale: "en-US" },
  251. createElement("div", { onClick: onHostClick }, createElement(WorkflowTimeline, { model })),
  252. ),
  253. );
  254. await waitFor(() => expect(view.getByTestId("workflow-timeline-scrollbar")).toBeTruthy());
  255. const thumb = view.getByTestId("workflow-timeline-scrollbar-thumb");
  256. // jsdom 没有指针捕获。
  257. thumb.setPointerCapture = vi.fn();
  258. thumb.releasePointerCapture = vi.fn();
  259. fireEvent.pointerDown(thumb, { pointerId: 1, clientX: 100 });
  260. fireEvent.pointerMove(thumb, { pointerId: 1, clientX: 160 });
  261. fireEvent.pointerUp(thumb, { pointerId: 1, clientX: 160 });
  262. fireEvent.click(thumb);
  263. fireEvent.click(view.getByTestId("workflow-timeline-scrollbar"));
  264. expect(onHostClick).not.toHaveBeenCalled();
  265. // 对照:时间线上真正的空白处仍然把 click 交给宿主。
  266. fireEvent.click(view.getByTestId(SCROLLER));
  267. expect(onHostClick).toHaveBeenCalledOnce();
  268. });
  269. it("a ledge lamp brings its station back to the centre", async () => {
  270. const view = renderTimeline();
  271. await waitFor(() => expect(view.getByTestId("workflow-timeline-ledge-right")).toBeTruthy());
  272. fireEvent.click(view.getAllByTestId("workflow-timeline-ledge-lamp")[2]!);
  273. expect(scrollTo).toHaveBeenLastCalledWith(
  274. expect.objectContaining({ left: stationCameraLeft(7, VIEW) }),
  275. );
  276. });
  277. it("← → on a focused station head scroll one station", async () => {
  278. const view = renderTimeline(() => {});
  279. await waitFor(() => expect(view.getByTestId("workflow-timeline-ledge-right")).toBeTruthy());
  280. const head = view.getAllByTestId("workflow-timeline-station")[1]!.querySelector("button")!;
  281. fireEvent.keyDown(head, { key: "ArrowRight" });
  282. expect(scrollTo).toHaveBeenLastCalledWith(expect.objectContaining({ left: 192 }));
  283. scrollLeftStore = 400;
  284. fireEvent.keyDown(head, { key: "ArrowLeft" });
  285. expect(scrollTo).toHaveBeenLastCalledWith(expect.objectContaining({ left: 208 }));
  286. });
  287. it("without overflow nothing folds, fades or scrolls", () => {
  288. // 缺省原型:clientWidth 0 = 量不到,与静态测试同一路。
  289. for (const key of ["clientWidth", "scrollWidth", "scrollLeft"]) {
  290. delete (HTMLElement.prototype as unknown as Record<string, unknown>)[key];
  291. }
  292. const view = renderTimeline();
  293. expect(view.queryByTestId("workflow-timeline-ledge-right")).toBeNull();
  294. expect(view.queryByTestId("workflow-timeline-scrollbar")).toBeNull();
  295. expect(view.getByTestId(SCROLLER).getAttribute("data-timeline-fade")).toBeNull();
  296. expect(view.container.querySelector(".wf-folded")).toBeNull();
  297. });
  298. });
  299. describe("WorkflowTimeline draft ledge", () => {
  300. // 追记「草稿时间线的边檐误折」:草稿首帧没有站(笔从 0 起步),滚动层晚一帧才挂上;内容宽随笔的揭示增长;
  301. // 镜头的 scrollTo 像浏览器的平滑滚动一样 150ms 后才落地、落地才派发 scroll。
  302. const DRAFT = NAMES.map((name) => `await phase("${name}")`).join("\n");
  303. const scrollTo = vi.fn(function (this: HTMLElement, options: ScrollToOptions) {
  304. const max = this.scrollWidth - this.clientWidth;
  305. setTimeout(() => {
  306. scrollLeftStore = Math.max(0, Math.min(options.left ?? 0, max));
  307. this.dispatchEvent(new Event("scroll"));
  308. }, 150);
  309. });
  310. beforeEach(() => {
  311. scrollLeftStore = 0;
  312. scrollTo.mockClear();
  313. fakeGeometry((scroller) =>
  314. timelineWidth(scroller.querySelectorAll("[data-testid='workflow-timeline-station']").length),
  315. );
  316. Element.prototype.scrollTo = scrollTo as unknown as Element["scrollTo"];
  317. vi.useFakeTimers({
  318. toFake: [
  319. "setTimeout",
  320. "clearTimeout",
  321. "setInterval",
  322. "clearInterval",
  323. "Date",
  324. "requestAnimationFrame",
  325. "cancelAnimationFrame",
  326. ],
  327. });
  328. });
  329. afterEach(() => {
  330. cleanup();
  331. vi.useRealTimers();
  332. for (const key of ["clientWidth", "scrollWidth", "scrollLeft"]) {
  333. delete (HTMLElement.prototype as unknown as Record<string, unknown>)[key];
  334. }
  335. });
  336. async function advance(ms: number) {
  337. await act(async () => {
  338. vi.advanceTimersByTime(ms);
  339. });
  340. }
  341. async function until(view: ReturnType<typeof render>, done: () => boolean) {
  342. for (let elapsed = 0; elapsed < 10_000 && !done(); elapsed += 10) await advance(10);
  343. expect(done()).toBe(true);
  344. }
  345. const stationCount = (view: ReturnType<typeof render>) =>
  346. view.queryAllByTestId("workflow-timeline-station").length;
  347. it("the pen writes past the viewport: the newest station never folds, and the ledge answers a user scroll", async () => {
  348. const view = render(
  349. createElement(
  350. ZCodeIntlProvider,
  351. { initialLocale: "en-US" },
  352. createElement(WorkflowTimeline, { model: draftTimeline(scanWorkflowDraft(DRAFT)) }),
  353. ),
  354. );
  355. // 第六站一揭示就溢出,镜头起飞;落地前(150ms 内)最新站不折、右檐缺席,镜头恰好把它贴到右缘。
  356. await until(view, () => stationCount(view) === 6);
  357. expect(scrollTo).toHaveBeenLastCalledWith(
  358. expect.objectContaining({ left: timelineWidth(6) - VIEW }),
  359. );
  360. expect(view.queryByTestId("workflow-timeline-ledge-right")).toBeNull();
  361. expect(view.container.querySelector(".wf-folded")).toBeNull();
  362. // 笔写完、镜头落地:滚动层在最右(没有 24px 过冲),什么都没折到右檐;左檐接住了滚过去的站。
  363. await until(
  364. view,
  365. () => view.queryByTestId("workflow-timeline-caret")?.dataset["pen"] === "idle",
  366. );
  367. await advance(200);
  368. expect(stationCount(view)).toBe(8);
  369. expect(scrollTo).toHaveBeenLastCalledWith(
  370. expect.objectContaining({ left: timelineWidth(8) - VIEW }),
  371. );
  372. expect(scrollLeftStore).toBe(timelineWidth(8) - VIEW);
  373. expect(view.queryByTestId("workflow-timeline-ledge-right")).toBeNull();
  374. const landed = view.getAllByTestId("workflow-timeline-station");
  375. expect(landed[7]?.getAttribute("data-station-folded")).toBeNull();
  376. expect(landed[0]?.getAttribute("data-station-folded")).toBe("true");
  377. expect(view.getByTestId("workflow-timeline-ledge-left")).toBeTruthy();
  378. expect(view.getByTestId(SCROLLER).getAttribute("data-timeline-fade")).toBe("left");
  379. // 用户把它滚回起点:监听真的接上了——右檐出现、最新站折进去、左檐退场。
  380. scrollLeftStore = 0;
  381. await act(async () => {
  382. view.getByTestId(SCROLLER).dispatchEvent(new Event("scroll"));
  383. vi.advanceTimersByTime(20);
  384. });
  385. expect(view.getByTestId("workflow-timeline-ledge-right")).toBeTruthy();
  386. expect(view.queryByTestId("workflow-timeline-ledge-left")).toBeNull();
  387. const stations = view.getAllByTestId("workflow-timeline-station");
  388. expect(stations[7]?.getAttribute("data-station-folded")).toBe("true");
  389. expect(stations[4]?.getAttribute("data-station-folded")).toBeNull();
  390. });
  391. });