workflowTimelineLedge.test.ts 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416
  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. const lamps = view.getAllByTestId("workflow-timeline-ledge-lamp");
  214. expect(lamps.map((lamp) => lamp.getAttribute("data-station-index"))).toEqual(["5", "6", "7"]);
  215. expect(lamps[0]?.getAttribute("title")).toBe("verify · pending");
  216. const stations = view.getAllByTestId("workflow-timeline-station");
  217. expect(stations[5]?.getAttribute("data-station-folded")).toBe("true");
  218. expect(stations[4]?.getAttribute("data-station-folded")).toBeNull();
  219. expect(view.getByTestId(SCROLLER).getAttribute("data-timeline-fade")).toBe("right");
  220. expect(view.getByTestId("workflow-timeline-scrollbar")).toBeTruthy();
  221. });
  222. it("re-folds on scroll: the left ledge takes the stations that left, and the fixpoint takes review", async () => {
  223. const view = renderTimeline();
  224. await scrollBy(view, 552);
  225. await waitFor(() => expect(view.getByTestId("workflow-timeline-ledge-left")).toBeTruthy());
  226. expect(view.queryByTestId("workflow-timeline-ledge-right")).toBeNull();
  227. const lamps = view.getAllByTestId("workflow-timeline-ledge-lamp");
  228. expect(lamps.map((lamp) => lamp.getAttribute("data-station-index"))).toEqual(["1", "2", "3"]);
  229. expect(view.getByTestId("workflow-timeline-ledge-more").textContent).toBe("+1");
  230. expect(view.getByTestId("workflow-timeline-scrollbar").getAttribute("data-scrolling")).toBe(
  231. "true",
  232. );
  233. const thumb = view.getByTestId("workflow-timeline-scrollbar-thumb");
  234. expect(thumb.style.left).toBe("350px");
  235. expect(thumb.style.width).toBe("610px");
  236. expect(view.getByTestId(SCROLLER).getAttribute("data-timeline-fade")).toBe("left");
  237. });
  238. it("the scrollbar keeps its clicks: dragging the thumb or paging the track never reaches the host card", async () => {
  239. // 宿主卡(轮尾摘要)把空白处的 click 当折叠;拖完拇指浏览器会补发 click,它不能冒上去。
  240. const onHostClick = vi.fn();
  241. const model = buildWorkflowTimeline(GRAPH, undefined);
  242. const view = render(
  243. createElement(
  244. ZCodeIntlProvider,
  245. { initialLocale: "en-US" },
  246. createElement("div", { onClick: onHostClick }, createElement(WorkflowTimeline, { model })),
  247. ),
  248. );
  249. await waitFor(() => expect(view.getByTestId("workflow-timeline-scrollbar")).toBeTruthy());
  250. const thumb = view.getByTestId("workflow-timeline-scrollbar-thumb");
  251. // jsdom 没有指针捕获。
  252. thumb.setPointerCapture = vi.fn();
  253. thumb.releasePointerCapture = vi.fn();
  254. fireEvent.pointerDown(thumb, { pointerId: 1, clientX: 100 });
  255. fireEvent.pointerMove(thumb, { pointerId: 1, clientX: 160 });
  256. fireEvent.pointerUp(thumb, { pointerId: 1, clientX: 160 });
  257. fireEvent.click(thumb);
  258. fireEvent.click(view.getByTestId("workflow-timeline-scrollbar"));
  259. expect(onHostClick).not.toHaveBeenCalled();
  260. // 对照:时间线上真正的空白处仍然把 click 交给宿主。
  261. fireEvent.click(view.getByTestId(SCROLLER));
  262. expect(onHostClick).toHaveBeenCalledOnce();
  263. });
  264. it("a ledge lamp brings its station back to the centre", async () => {
  265. const view = renderTimeline();
  266. await waitFor(() => expect(view.getByTestId("workflow-timeline-ledge-right")).toBeTruthy());
  267. fireEvent.click(view.getAllByTestId("workflow-timeline-ledge-lamp")[2]!);
  268. expect(scrollTo).toHaveBeenLastCalledWith(
  269. expect.objectContaining({ left: stationCameraLeft(7, VIEW) }),
  270. );
  271. });
  272. it("← → on a focused station head scroll one station", async () => {
  273. const view = renderTimeline(() => {});
  274. await waitFor(() => expect(view.getByTestId("workflow-timeline-ledge-right")).toBeTruthy());
  275. const head = view.getAllByTestId("workflow-timeline-station")[1]!.querySelector("button")!;
  276. fireEvent.keyDown(head, { key: "ArrowRight" });
  277. expect(scrollTo).toHaveBeenLastCalledWith(expect.objectContaining({ left: 192 }));
  278. scrollLeftStore = 400;
  279. fireEvent.keyDown(head, { key: "ArrowLeft" });
  280. expect(scrollTo).toHaveBeenLastCalledWith(expect.objectContaining({ left: 208 }));
  281. });
  282. it("without overflow nothing folds, fades or scrolls", () => {
  283. // 缺省原型:clientWidth 0 = 量不到,与静态测试同一路。
  284. for (const key of ["clientWidth", "scrollWidth", "scrollLeft"]) {
  285. delete (HTMLElement.prototype as unknown as Record<string, unknown>)[key];
  286. }
  287. const view = renderTimeline();
  288. expect(view.queryByTestId("workflow-timeline-ledge-right")).toBeNull();
  289. expect(view.queryByTestId("workflow-timeline-scrollbar")).toBeNull();
  290. expect(view.getByTestId(SCROLLER).getAttribute("data-timeline-fade")).toBeNull();
  291. expect(view.container.querySelector(".wf-folded")).toBeNull();
  292. });
  293. });
  294. describe("WorkflowTimeline draft ledge", () => {
  295. // 追记「草稿时间线的边檐误折」:草稿首帧没有站(笔从 0 起步),滚动层晚一帧才挂上;内容宽随笔的揭示增长;
  296. // 镜头的 scrollTo 像浏览器的平滑滚动一样 150ms 后才落地、落地才派发 scroll。
  297. const DRAFT = NAMES.map((name) => `await phase("${name}")`).join("\n");
  298. const scrollTo = vi.fn(function (this: HTMLElement, options: ScrollToOptions) {
  299. const max = this.scrollWidth - this.clientWidth;
  300. setTimeout(() => {
  301. scrollLeftStore = Math.max(0, Math.min(options.left ?? 0, max));
  302. this.dispatchEvent(new Event("scroll"));
  303. }, 150);
  304. });
  305. beforeEach(() => {
  306. scrollLeftStore = 0;
  307. scrollTo.mockClear();
  308. fakeGeometry((scroller) =>
  309. timelineWidth(scroller.querySelectorAll("[data-testid='workflow-timeline-station']").length),
  310. );
  311. Element.prototype.scrollTo = scrollTo as unknown as Element["scrollTo"];
  312. vi.useFakeTimers({
  313. toFake: [
  314. "setTimeout",
  315. "clearTimeout",
  316. "setInterval",
  317. "clearInterval",
  318. "Date",
  319. "requestAnimationFrame",
  320. "cancelAnimationFrame",
  321. ],
  322. });
  323. });
  324. afterEach(() => {
  325. cleanup();
  326. vi.useRealTimers();
  327. for (const key of ["clientWidth", "scrollWidth", "scrollLeft"]) {
  328. delete (HTMLElement.prototype as unknown as Record<string, unknown>)[key];
  329. }
  330. });
  331. async function advance(ms: number) {
  332. await act(async () => {
  333. vi.advanceTimersByTime(ms);
  334. });
  335. }
  336. async function until(view: ReturnType<typeof render>, done: () => boolean) {
  337. for (let elapsed = 0; elapsed < 10_000 && !done(); elapsed += 10) await advance(10);
  338. expect(done()).toBe(true);
  339. }
  340. const stationCount = (view: ReturnType<typeof render>) =>
  341. view.queryAllByTestId("workflow-timeline-station").length;
  342. it("the pen writes past the viewport: the newest station never folds, and the ledge answers a user scroll", async () => {
  343. const view = render(
  344. createElement(
  345. ZCodeIntlProvider,
  346. { initialLocale: "en-US" },
  347. createElement(WorkflowTimeline, { model: draftTimeline(scanWorkflowDraft(DRAFT)) }),
  348. ),
  349. );
  350. // 第六站一揭示就溢出,镜头起飞;落地前(150ms 内)最新站不折、右檐缺席,镜头恰好把它贴到右缘。
  351. await until(view, () => stationCount(view) === 6);
  352. expect(scrollTo).toHaveBeenLastCalledWith(
  353. expect.objectContaining({ left: timelineWidth(6) - VIEW }),
  354. );
  355. expect(view.queryByTestId("workflow-timeline-ledge-right")).toBeNull();
  356. expect(view.container.querySelector(".wf-folded")).toBeNull();
  357. // 笔写完、镜头落地:滚动层在最右(没有 24px 过冲),什么都没折到右檐;左檐接住了滚过去的站。
  358. await until(
  359. view,
  360. () => view.queryByTestId("workflow-timeline-caret")?.dataset["pen"] === "idle",
  361. );
  362. await advance(200);
  363. expect(stationCount(view)).toBe(8);
  364. expect(scrollTo).toHaveBeenLastCalledWith(
  365. expect.objectContaining({ left: timelineWidth(8) - VIEW }),
  366. );
  367. expect(scrollLeftStore).toBe(timelineWidth(8) - VIEW);
  368. expect(view.queryByTestId("workflow-timeline-ledge-right")).toBeNull();
  369. const landed = view.getAllByTestId("workflow-timeline-station");
  370. expect(landed[7]?.getAttribute("data-station-folded")).toBeNull();
  371. expect(landed[0]?.getAttribute("data-station-folded")).toBe("true");
  372. expect(view.getByTestId("workflow-timeline-ledge-left")).toBeTruthy();
  373. expect(view.getByTestId(SCROLLER).getAttribute("data-timeline-fade")).toBe("left");
  374. // 用户把它滚回起点:监听真的接上了——右檐出现、最新站折进去、左檐退场。
  375. scrollLeftStore = 0;
  376. await act(async () => {
  377. view.getByTestId(SCROLLER).dispatchEvent(new Event("scroll"));
  378. vi.advanceTimersByTime(20);
  379. });
  380. expect(view.getByTestId("workflow-timeline-ledge-right")).toBeTruthy();
  381. expect(view.queryByTestId("workflow-timeline-ledge-left")).toBeNull();
  382. const stations = view.getAllByTestId("workflow-timeline-station");
  383. expect(stations[7]?.getAttribute("data-station-folded")).toBe("true");
  384. expect(stations[4]?.getAttribute("data-station-folded")).toBeNull();
  385. });
  386. });