conversation-timeline-resize.test.mjs 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760
  1. import { registerNavigatorHitCases } from "./conversation-navigator-hit.cases.mjs";
  2. import { registerMarkdownTableMotionCases } from "./markdown-table-motion.cases.mjs";
  3. // SRM10:真实 React timeline、消息组件和 TanStack virtualizer;会话数据由确定性 fixture 提供。
  4. import assert from "node:assert/strict";
  5. import { before, after, test } from "node:test";
  6. import { fileURLToPath } from "node:url";
  7. import { mkdir, writeFile } from "node:fs/promises";
  8. import { join } from "node:path";
  9. import { createServer } from "vite";
  10. import react from "@vitejs/plugin-react";
  11. import tailwindcss from "@tailwindcss/vite";
  12. import { chromium } from "playwright-core";
  13. const root = fileURLToPath(new URL("../../../../../../", import.meta.url));
  14. const entry =
  15. "/packages/ui/test/browser/manual-review/pending/conversation-timeline-resize.fixture.tsx";
  16. const artifacts =
  17. process.env.ZCODE_E2E_ARTIFACT_DIR ||
  18. join(root, "packages/desktop/.e2e-artifacts/conversation-timeline-resize");
  19. let server, browser, origin;
  20. before(async () => {
  21. await mkdir(artifacts, { recursive: true });
  22. server = await createServer({
  23. root,
  24. configFile: false,
  25. cacheDir: join(artifacts, "vite-cache"),
  26. plugins: [
  27. {
  28. name: "timeline-fixture",
  29. enforce: "pre",
  30. configureServer(vite) {
  31. vite.middlewares.use(async (req, res, next) => {
  32. if (!req.url?.startsWith("/fixture?")) return next();
  33. res.setHeader("Content-Type", "text/html");
  34. res.end(
  35. await vite.transformIndexHtml(
  36. req.url,
  37. `<!doctype html><html><head><link rel="icon" href="data:," /><meta name="viewport" content="width=device-width, initial-scale=1" /></head><body><div id="root"></div><script type="module" src="${entry}"></script></body></html>`,
  38. ),
  39. );
  40. });
  41. },
  42. },
  43. react(),
  44. tailwindcss(),
  45. ],
  46. resolve: { alias: { "@": `${root}packages/ui/src` } },
  47. optimizeDeps: { entries: [entry.slice(1)] },
  48. server: {
  49. host: "127.0.0.1",
  50. port: 0,
  51. hmr: false,
  52. watch: { ignored: ["**/packages/desktop/out/**", "**/.e2e-artifacts/**"] },
  53. },
  54. });
  55. await server.listen();
  56. origin = server.resolvedUrls.local[0];
  57. browser = await chromium.launch(
  58. process.env.CHROME_EXECUTABLE_PATH
  59. ? { executablePath: process.env.CHROME_EXECUTABLE_PATH }
  60. : { channel: "chrome" },
  61. );
  62. });
  63. after(async () => {
  64. await browser?.close();
  65. await server?.close();
  66. });
  67. for (const mobile of [false, true])
  68. for (const theme of ["light", "dark"])
  69. for (const terminal of ["stop", "complete", "fail"])
  70. for (const reading of [false, true])
  71. test(`SSV06 terminal identity ${mobile ? "mobile" : "desktop"}/${theme}/${terminal}/${reading ? "reading" : "following"}`, async () => {
  72. const page = await browser.newPage({
  73. viewport: { width: mobile ? 430 : 1250, height: 800 },
  74. isMobile: mobile,
  75. hasTouch: mobile,
  76. });
  77. const errors = [];
  78. page.on("pageerror", (error) => errors.push(String(error)));
  79. page.on("console", (message) => {
  80. if (message.type() === "error") errors.push(message.text());
  81. });
  82. const prefix = `terminal-${mobile}-${theme}-${terminal}-${reading}`;
  83. let evidence;
  84. try {
  85. await page.goto(
  86. `${origin}fixture?mobile=${mobile}&theme=${theme}&terminal=${terminal}`,
  87. );
  88. await page.locator('[data-row-id="8"]').waitFor();
  89. await page.evaluate(async (detached) => {
  90. await Promise.all(
  91. document
  92. .getAnimations()
  93. .filter((a) => Number.isFinite(a.effect?.getComputedTiming().iterations))
  94. .map((a) => a.finished.catch(() => {})),
  95. );
  96. const timeline = document.querySelector('[data-testid="v4-timeline"]');
  97. if (detached) {
  98. timeline.dispatchEvent(new WheelEvent("wheel", { bubbles: true, deltaY: -200 }));
  99. // 阅读顶部历史;完成时过程区折叠后,该位置仍可表示,排除浏览器正常 clamp。
  100. timeline.scrollTop = 0;
  101. timeline.dispatchEvent(new Event("scroll"));
  102. }
  103. await new Promise((resolve) =>
  104. requestAnimationFrame(() => requestAnimationFrame(resolve)),
  105. );
  106. const ids = [3, 5, 6, 7];
  107. const nodes = ids.map((id) => document.querySelector(`[data-row-id="${id}"]`));
  108. if (nodes.some((node) => !node)) throw new Error("SSV06 初始消息缺失");
  109. const turn = nodes[1].closest("[data-v4-turn-unit]");
  110. const probe = { ids, nodes, turn, timeline, animations: [], samples: [] };
  111. probe.listener = (event) => {
  112. if (
  113. event.target instanceof Element &&
  114. probe.ids.some((id) =>
  115. event.target.contains(document.querySelector(`[data-row-id="${id}"]`)),
  116. )
  117. )
  118. probe.animations.push(event.animationName);
  119. };
  120. document.addEventListener("animationstart", probe.listener);
  121. window.__stopIdentityProbe = probe;
  122. }, reading);
  123. await page.getByRole("button", { name: "Stop", exact: true }).click();
  124. evidence = await page.evaluate(async () => {
  125. const probe = window.__stopIdentityProbe;
  126. for (let frame = 0; frame < 24; frame++) {
  127. await new Promise(requestAnimationFrame);
  128. const nodes = probe.ids.map((id) =>
  129. document.querySelector(`[data-row-id="${id}"]`),
  130. );
  131. probe.samples.push({
  132. sameTimeline:
  133. document.querySelector('[data-testid="v4-timeline"]') === probe.timeline,
  134. sameTurn:
  135. document.querySelector('[data-v4-turn-unit][data-turn-id="terminal-turn"]') ===
  136. probe.turn,
  137. sameRows: nodes.map((node, index) => node === probe.nodes[index]),
  138. opacity: nodes.map((node) => {
  139. let opacity = 1;
  140. for (let element = node; element; element = element.parentElement)
  141. opacity *= Number(getComputedStyle(element).opacity);
  142. return node ? opacity : 0;
  143. }),
  144. following: probe.timeline.dataset.following,
  145. bottomGap:
  146. probe.timeline.scrollHeight -
  147. probe.timeline.clientHeight -
  148. probe.timeline.scrollTop,
  149. });
  150. }
  151. document.removeEventListener("animationstart", probe.listener);
  152. return { animations: probe.animations, samples: probe.samples };
  153. });
  154. for (const sample of evidence.samples) {
  155. assert.equal(sample.sameTimeline, true);
  156. assert.equal(sample.sameTurn, true, `终态重挂整轮:${JSON.stringify(sample)}`);
  157. assert.equal(sample.sameRows[0], true, "旧轮消息被重挂");
  158. assert.equal(sample.following, String(!reading), "终态改变滚动归属");
  159. if (terminal !== "complete") {
  160. assert.ok(sample.sameRows.every(Boolean), "停止/失败重挂已有过程内容");
  161. assert.ok(
  162. sample.opacity.every((value) => value === 1),
  163. "已有过程内容出现透明帧",
  164. );
  165. }
  166. if (!reading) assert.ok(Math.abs(sample.bottomGap) <= 1, JSON.stringify(sample));
  167. }
  168. assert.equal(evidence.animations.includes("enter"), false, "终态重播已有内容的淡入");
  169. await page.screenshot({ path: join(artifacts, `${prefix}.png`) });
  170. await page.getByRole("button", { name: "Next turn", exact: true }).click();
  171. await page.locator('[data-row-id="11"]').waitFor();
  172. assert.equal(await page.locator('[data-v4-live-tail="true"]').count(), 1);
  173. assert.equal(
  174. await page.locator('[data-v4-live-tail="true"]').getAttribute("data-turn-id"),
  175. "next-turn",
  176. );
  177. assert.equal(
  178. await page
  179. .locator(
  180. '[data-v4-timeline-virtual-history] [data-v4-turn-unit][data-turn-id="terminal-turn"]',
  181. )
  182. .count(),
  183. 1,
  184. );
  185. assert.equal(
  186. await page.locator('[data-row-id="5"]').count(),
  187. 1,
  188. "下一轮交接丢失或重复旧输入",
  189. );
  190. await page.getByRole("button", { name: "Draft", exact: true }).click();
  191. assert.equal(await page.locator("[data-v4-turn-unit]").count(), 0, "空列表残留尾轮");
  192. assert.deepEqual(errors, []);
  193. } finally {
  194. await writeFile(
  195. join(artifacts, `${prefix}.json`),
  196. JSON.stringify({ evidence, errors }, null, 2),
  197. );
  198. await page.close();
  199. }
  200. });
  201. for (const mobile of [false, true])
  202. for (const theme of ["light", "dark"])
  203. for (const mode of ["tail", "final", "cua", "stream"])
  204. test(`SSV05 group identity ${mobile ? "mobile" : "desktop"}/${theme}/${mode}`, async () => {
  205. const page = await browser.newPage({
  206. viewport: { width: mobile ? 430 : 1250, height: 800 },
  207. isMobile: mobile,
  208. hasTouch: mobile,
  209. });
  210. const errors = [];
  211. page.on("pageerror", (error) => errors.push(String(error)));
  212. page.on("console", (message) => {
  213. if (message.type() === "error") errors.push(message.text());
  214. });
  215. const samples = [];
  216. try {
  217. await page.goto(`${origin}fixture?mobile=${mobile}&theme=${theme}&identity=${mode}`);
  218. const rowId = mode === "stream" ? 60 : 241;
  219. await page.locator(`[data-row-id="${rowId}"]`).waitFor();
  220. await page.evaluate(async (id) => {
  221. const row = document.querySelector(`[data-row-id="${id}"]`);
  222. const content = row.closest('[data-slot="collapsible-content"]');
  223. await Promise.all(
  224. document
  225. .getAnimations()
  226. .filter((animation) =>
  227. Number.isFinite(animation.effect?.getComputedTiming().iterations),
  228. )
  229. .map((animation) => animation.finished.catch(() => {})),
  230. );
  231. window.__identityProbe = { row, content, replacements: 0, animationRestarts: 0 };
  232. const probe = window.__identityProbe;
  233. let last = row;
  234. probe.observer = new MutationObserver(() => {
  235. const current = document.querySelector(`[data-row-id="${id}"]`);
  236. if (current !== last) probe.replacements += 1;
  237. last = current;
  238. });
  239. probe.observer.observe(document.querySelector('[data-testid="v4-timeline"]'), {
  240. childList: true,
  241. subtree: true,
  242. });
  243. document.addEventListener("animationstart", (event) => {
  244. const current = document.querySelector(`[data-row-id="${id}"]`);
  245. if (event.target instanceof Element && event.target.contains(current))
  246. probe.animationRestarts += 1;
  247. });
  248. }, rowId);
  249. for (const expected of [120, 180, 240, mode === "final" || mode === "cua" ? 242 : 241]) {
  250. await page.getByRole("button", { name: "Next page", exact: true }).click();
  251. await page.waitForFunction(
  252. (count) =>
  253. document.querySelector('[data-testid="v4-timeline"]').dataset.windowRowCount ===
  254. String(count),
  255. expected,
  256. );
  257. samples.push(
  258. await page.evaluate(async (id) => {
  259. await new Promise((resolve) =>
  260. requestAnimationFrame(() => requestAnimationFrame(resolve)),
  261. );
  262. const timeline = document.querySelector('[data-testid="v4-timeline"]');
  263. const row = document.querySelector(`[data-row-id="${id}"]`);
  264. const probe = window.__identityProbe;
  265. const content = row?.closest('[data-slot="collapsible-content"]');
  266. return {
  267. rows: timeline.dataset.windowRowCount,
  268. sameRow: row === probe.row,
  269. sameContent: content === probe.content,
  270. replacements: probe.replacements,
  271. animationRestarts: probe.animationRestarts,
  272. rowHeight: row?.getBoundingClientRect().height,
  273. scrollTop: timeline.scrollTop,
  274. opacity: content ? getComputedStyle(content.firstElementChild).opacity : null,
  275. };
  276. }, rowId),
  277. );
  278. }
  279. for (const sample of samples) {
  280. assert.equal(sample.sameRow, true, `已有消息被重挂:${JSON.stringify(sample)}`);
  281. assert.equal(sample.sameContent, true, `折叠内容被重挂:${JSON.stringify(sample)}`);
  282. assert.equal(sample.replacements, 0);
  283. assert.equal(sample.animationRestarts, 0, "补页或追加重播了已有内容的入场动画");
  284. if (sample.opacity !== null) assert.equal(sample.opacity, "1");
  285. }
  286. assert.deepEqual(errors, []);
  287. } finally {
  288. await writeFile(
  289. join(artifacts, `identity-${mobile}-${theme}-${mode}.json`),
  290. JSON.stringify(samples, null, 2),
  291. );
  292. await page.screenshot({
  293. path: join(artifacts, `identity-${mobile}-${theme}-${mode}.png`),
  294. });
  295. await page.close();
  296. }
  297. });
  298. for (const mobile of [false, true])
  299. for (const theme of ["light", "dark"])
  300. for (const mode of ["mixed", "append"])
  301. test(`SSV05 CR-01 ${mobile ? "mobile" : "desktop"}/${theme}/${mode}`, async () => {
  302. const page = await browser.newPage({
  303. viewport: { width: mobile ? 430 : 1250, height: 800 },
  304. isMobile: mobile,
  305. hasTouch: mobile,
  306. });
  307. const errors = [];
  308. page.on("pageerror", (error) => errors.push(String(error)));
  309. page.on("console", (message) => {
  310. if (message.type() === "error") errors.push(message.text());
  311. });
  312. const samples = [];
  313. try {
  314. await page.goto(`${origin}fixture?mobile=${mobile}&theme=${theme}&boundary=${mode}`);
  315. await page.locator('[data-row-id="50"]').waitFor();
  316. if (mode === "mixed") {
  317. await page.locator("[data-summary-group-trigger]").first().click();
  318. await page.locator('[data-tool-call-id="boundary-tool-40"]').waitFor();
  319. }
  320. await page.evaluate(async (mixed) => {
  321. await Promise.all(
  322. document
  323. .getAnimations()
  324. .filter((a) => Number.isFinite(a.effect?.getComputedTiming().iterations))
  325. .map((a) => a.finished.catch(() => {})),
  326. );
  327. // 组头的代表图标也会渲染行外壳;只跟踪展开内容中的真实行,排除图标副本。
  328. const rows = (mixed ? [40, 50] : [50]).map((id) =>
  329. document.querySelector(`[data-row-id="${id}"]:not([data-summary-group-icon] *)`),
  330. );
  331. const contents = rows.map((row) => row.closest('[data-slot="collapsible-content"]'));
  332. window.__boundaryProbe = {
  333. rows,
  334. contents,
  335. groups: [...document.querySelectorAll("[data-consecutive-summary-group]")],
  336. animationRestarts: 0,
  337. };
  338. document.addEventListener("animationstart", (event) => {
  339. if (
  340. event.target instanceof Element &&
  341. (mixed ? [40, 50] : [50]).some((id) =>
  342. event.target.contains(
  343. document.querySelector(
  344. `[data-row-id="${id}"]:not([data-summary-group-icon] *)`,
  345. ),
  346. ),
  347. )
  348. )
  349. window.__boundaryProbe.animationRestarts += 1;
  350. });
  351. }, mode === "mixed");
  352. for (const step of [1, 2]) {
  353. await page.getByRole("button", { name: "Next boundary", exact: true }).click();
  354. await page.waitForFunction(
  355. (value) =>
  356. document.querySelector('[data-testid="boundary-page"]').textContent ===
  357. String(value),
  358. step,
  359. );
  360. samples.push(
  361. await page.evaluate(
  362. async ({ mode, step }) => {
  363. await new Promise((resolve) =>
  364. requestAnimationFrame(() => requestAnimationFrame(resolve)),
  365. );
  366. const probe = window.__boundaryProbe;
  367. const ids = mode === "mixed" ? [40, 50] : [50];
  368. const rows = ids.map((id) =>
  369. document.querySelector(
  370. `[data-row-id="${id}"]:not([data-summary-group-icon] *)`,
  371. ),
  372. );
  373. const groups = [...document.querySelectorAll("[data-consecutive-summary-group]")];
  374. const timeline = document.querySelector('[data-testid="v4-timeline"]');
  375. return {
  376. step,
  377. sameRows: rows.map((row, index) => row === probe.rows[index]),
  378. sameContents: rows.map(
  379. (row, index) =>
  380. row?.closest('[data-slot="collapsible-content"]') === probe.contents[index],
  381. ),
  382. animationRestarts: probe.animationRestarts,
  383. heights: rows.map((row) => row?.getBoundingClientRect().height),
  384. scrollTop: timeline.scrollTop,
  385. sameGroups:
  386. mode === "mixed"
  387. ? probe.groups.map((group, index) => group === groups[index + 1])
  388. : [],
  389. groupIds: groups.map((group) =>
  390. group
  391. .querySelector("[data-summary-group-trigger]")
  392. ?.getAttribute("aria-controls"),
  393. ),
  394. expanded: groups.map((group) =>
  395. group
  396. .querySelector('[role="button"][aria-expanded]')
  397. ?.getAttribute("aria-expanded"),
  398. ),
  399. toolCounts: ids.map(
  400. (id) =>
  401. document.querySelectorAll(
  402. `[data-row-id="${id}"]:not([data-summary-group-icon] *)`,
  403. ).length,
  404. ),
  405. };
  406. },
  407. { mode, step },
  408. ),
  409. );
  410. }
  411. for (const sample of samples) {
  412. assert.ok(sample.sameRows.every(Boolean), `消息/分组重挂:${JSON.stringify(sample)}`);
  413. assert.ok(
  414. sample.sameContents.every(Boolean),
  415. `历史容器重挂:${JSON.stringify(sample)}`,
  416. );
  417. assert.equal(sample.animationRestarts, 0, JSON.stringify(sample));
  418. assert.ok(sample.sameGroups.every(Boolean), JSON.stringify(sample));
  419. assert.deepEqual(
  420. sample.toolCounts,
  421. mode === "mixed" ? [1, 1] : [1],
  422. "已有消息丢失或重复",
  423. );
  424. assert.equal(new Set(sample.groupIds).size, sample.groupIds.length, "CUA 展开身份重复");
  425. const count =
  426. mode === "mixed" ? (sample.step === 1 ? 3 : 4) : sample.step === 1 ? 1 : 3;
  427. assert.equal(sample.groupIds.length, count, "CUA 组丢失或重复");
  428. assert.deepEqual(
  429. sample.expanded,
  430. mode === "mixed"
  431. ? Array.from({ length: count }, (_, index) => (index === 1 ? "true" : "false"))
  432. : Array(count).fill("false"),
  433. "展开状态丢失或串组",
  434. );
  435. }
  436. assert.deepEqual(errors, [], "React 不得报告重复兄弟 key");
  437. } finally {
  438. await writeFile(
  439. join(artifacts, `boundary-${mobile}-${theme}-${mode}.json`),
  440. JSON.stringify({ samples, errors }, null, 2),
  441. );
  442. await page.screenshot({
  443. path: join(artifacts, `boundary-${mobile}-${theme}-${mode}.png`),
  444. });
  445. await page.close();
  446. }
  447. });
  448. for (const width of [390, 1100, 1440])
  449. for (const theme of ["light", "dark"])
  450. test(`SP01 draft first frame ${width}/${theme}`, async () => {
  451. const page = await browser.newPage({ viewport: { width, height: 800 } });
  452. const errors = [];
  453. page.on("pageerror", (error) => errors.push(String(error)));
  454. try {
  455. await page.goto(`${origin}fixture?draft=true&mobile=${width === 390}&theme=${theme}`);
  456. await page.getByTestId("fixture-composer").waitFor();
  457. const samples = await page.evaluate(async () => {
  458. const dock = document.querySelector("[data-v4-composer-dock-content]");
  459. const composer = document.querySelector('[data-testid="fixture-composer"]');
  460. const host = dock.parentElement;
  461. await Promise.all(dock.getAnimations().map((animation) => animation.finished));
  462. const frames = [];
  463. // 在 React 提交的 mutation 回调和后续绘制帧取坐标,不能等动画结束才断言。
  464. await new Promise((resolve) => {
  465. const capture = () => {
  466. const outer = host.getBoundingClientRect();
  467. const input = composer.getBoundingClientRect();
  468. frames.push({
  469. x: input.x,
  470. width: input.width,
  471. centerError: input.x + input.width / 2 - outer.x - outer.width / 2,
  472. animations: dock.getAnimations().map((animation) => animation.transitionProperty),
  473. });
  474. if (frames.length < 18) requestAnimationFrame(capture);
  475. else resolve();
  476. };
  477. const observer = new MutationObserver(() => {
  478. if (!composer.classList.contains("max-w-2xl")) return;
  479. observer.disconnect();
  480. capture();
  481. });
  482. observer.observe(composer, { attributes: true });
  483. [...document.querySelectorAll("button")]
  484. .find((button) => button.textContent === "Draft")
  485. .click();
  486. });
  487. return frames;
  488. });
  489. await writeFile(
  490. join(artifacts, `draft-${width}-${theme}.json`),
  491. JSON.stringify(samples, null, 2),
  492. );
  493. for (const sample of samples) {
  494. assert.ok(Math.abs(sample.centerError) <= 1, JSON.stringify(sample));
  495. assert.deepEqual(sample.animations, []);
  496. assert.ok(Math.abs(sample.x - samples[0].x) <= 1, JSON.stringify(samples));
  497. }
  498. await page.screenshot({ path: join(artifacts, `draft-${width}-${theme}.png`) });
  499. assert.deepEqual(errors, []);
  500. } finally {
  501. await page.close();
  502. }
  503. });
  504. for (const mobile of [false, true])
  505. for (const theme of ["light", "dark"]) {
  506. test(`SRM10 ${mobile ? "mobile" : "desktop"}/${theme}`, async () => {
  507. const page = await browser.newPage({
  508. viewport: { width: mobile ? 430 : 1250, height: 800 },
  509. isMobile: mobile,
  510. hasTouch: mobile,
  511. });
  512. const errors = [];
  513. page.on("pageerror", (error) => errors.push(String(error)));
  514. const prefix = `${mobile ? "mobile" : "desktop"}-${theme}`;
  515. try {
  516. await page.addInitScript(() => {
  517. window.__timelineErrors = [];
  518. window.addEventListener(
  519. "error",
  520. (event) => window.__timelineErrors.push(event.message),
  521. true,
  522. );
  523. });
  524. await page.goto(
  525. `${origin}fixture?mobile=${mobile}&theme=${theme}&heavy=${process.env.ZCODE_RESIZE_HEAVY_TOOLS === "1"}`,
  526. );
  527. const timeline = page.getByTestId("v4-timeline");
  528. await timeline.waitFor();
  529. if (process.env.ZCODE_RESIZE_HEAVY_TOOLS === "1") {
  530. await page.getByRole("button", { name: "Tools", exact: true }).click();
  531. await page.waitForFunction(
  532. () =>
  533. document.querySelectorAll('[data-testid^="tool-summary-trigger-resize-tool-"]')
  534. .length === 134,
  535. );
  536. }
  537. const state = () =>
  538. timeline.evaluate((e) => ({
  539. following: e.dataset.following,
  540. top: e.scrollTop,
  541. gap: e.scrollHeight - e.clientHeight - e.scrollTop,
  542. }));
  543. const settle = () =>
  544. page.evaluate(
  545. () =>
  546. new Promise((resolve) => requestAnimationFrame(() => requestAnimationFrame(resolve))),
  547. );
  548. await settle();
  549. await page.getByRole("button", { name: "Bottom", exact: true }).click();
  550. const evidence = [];
  551. // 每个宽度点都检查布局提交后的实际几何,不只检查整个拖动结束后的落点。
  552. for (const width of mobile
  553. ? [420, 390, 360, 390, 430]
  554. : [1400, 1300, 1250, 1050, 900, 750, 900, 1100, 1250]) {
  555. await page.setViewportSize({ width, height: 800 });
  556. await settle();
  557. const metrics = await timeline.evaluate((e) => {
  558. const history = e.querySelector("[data-v4-timeline-virtual-history]");
  559. const last = history?.lastElementChild;
  560. return {
  561. following: e.dataset.following,
  562. gap: e.scrollHeight - e.clientHeight - e.scrollTop,
  563. stale: last
  564. ? last.getBoundingClientRect().bottom - history.getBoundingClientRect().bottom
  565. : 0,
  566. };
  567. });
  568. evidence.push({ width, ...metrics });
  569. assert.equal(metrics.following, "true");
  570. assert.ok(Math.abs(metrics.gap) <= 1, JSON.stringify(metrics));
  571. assert.ok(Math.abs(metrics.stale) <= 1, JSON.stringify(metrics));
  572. }
  573. // 外层视口不变,仅内容列继续 CSS 宽度过渡:不能停留在旧 stableWidth。
  574. await timeline.evaluate((e) => {
  575. const history = e.querySelector("[data-v4-timeline-virtual-history]");
  576. history.style.transition = "width 160ms linear";
  577. history.style.width = "75%";
  578. });
  579. for (let frame = 0; frame < 8; frame++) {
  580. await settle();
  581. const metrics = await state();
  582. assert.equal(metrics.following, "true");
  583. assert.ok(Math.abs(metrics.gap) <= 1, JSON.stringify(metrics));
  584. }
  585. await timeline.evaluate((e) => {
  586. const history = e.querySelector("[data-v4-timeline-virtual-history]");
  587. history.style.removeProperty("transition");
  588. history.style.removeProperty("width");
  589. });
  590. await settle();
  591. await page.getByRole("button", { name: "Grow", exact: true }).click();
  592. await settle();
  593. assert.ok(Math.abs((await state()).gap) <= 1);
  594. await timeline.evaluate((e) => {
  595. e.dispatchEvent(new WheelEvent("wheel", { bubbles: true, deltaY: -400 }));
  596. e.scrollTop -= 500;
  597. e.dispatchEvent(new Event("scroll"));
  598. });
  599. await settle();
  600. assert.equal((await state()).following, "false");
  601. for (const width of mobile ? [390, 430] : [1000, 1250]) {
  602. await page.setViewportSize({ width, height: 800 });
  603. await settle();
  604. assert.equal((await state()).following, "false");
  605. }
  606. await page.getByRole("button", { name: "Grow", exact: true }).click();
  607. await settle();
  608. assert.equal((await state()).following, "false");
  609. await timeline.evaluate((e) => {
  610. e.dispatchEvent(new WheelEvent("wheel", { bubbles: true, deltaY: -400 }));
  611. e.scrollTop = 0;
  612. e.dispatchEvent(new Event("scroll"));
  613. });
  614. await settle();
  615. const saved = await state();
  616. await page.getByRole("button", { name: "Switch", exact: true }).click();
  617. await settle();
  618. await page.getByRole("button", { name: "Switch", exact: true }).click();
  619. await settle();
  620. assert.equal((await state()).following, "false");
  621. await page.waitForFunction(
  622. (top) =>
  623. Math.abs(document.querySelector('[data-testid="v4-timeline"]').scrollTop - top) <= 1,
  624. saved.top,
  625. );
  626. await page.getByRole("button", { name: "Bottom", exact: true }).click();
  627. await settle();
  628. assert.equal((await state()).following, "true");
  629. assert.ok(Math.abs((await state()).gap) <= 1);
  630. await page.getByRole("button", { name: "Locate", exact: true }).click();
  631. await settle();
  632. assert.equal((await state()).following, "false");
  633. await page.getByRole("button", { name: "Bottom", exact: true }).click();
  634. await settle();
  635. assert.equal((await state()).following, "true");
  636. assert.ok(Math.abs((await state()).gap) <= 1);
  637. await page.screenshot({ path: join(artifacts, `${prefix}.png`) });
  638. await writeFile(join(artifacts, `${prefix}.json`), JSON.stringify(evidence, null, 2));
  639. assert.deepEqual(errors, []);
  640. assert.deepEqual(await page.evaluate(() => window.__timelineErrors), []);
  641. } catch (error) {
  642. console.error(error);
  643. throw error;
  644. } finally {
  645. await page.close();
  646. }
  647. });
  648. }
  649. for (const mobile of [false, true])
  650. for (const theme of ["light", "dark"])
  651. for (const reading of [false, true])
  652. test(`SSV03 hydrate ${mobile ? "mobile" : "desktop"}/${theme}/${reading ? "reading" : "following"}`, async () => {
  653. const page = await browser.newPage({
  654. viewport: { width: mobile ? 430 : 1250, height: 800 },
  655. });
  656. const samples = [];
  657. try {
  658. await page.goto(`${origin}fixture?mobile=${mobile}&theme=${theme}&hydrate=true`);
  659. await page.getByTestId("v4-timeline").waitFor();
  660. await page.waitForFunction(
  661. () => document.querySelectorAll("[data-v4-turn-unit]").length >= 2,
  662. );
  663. if (reading) {
  664. await page.getByTestId("v4-timeline").evaluate((e) => {
  665. e.dispatchEvent(new WheelEvent("wheel", { bubbles: true, deltaY: -100 }));
  666. e.scrollTop -= 100;
  667. e.dispatchEvent(new Event("scroll"));
  668. });
  669. await page.waitForFunction(
  670. () =>
  671. document.querySelector('[data-testid="v4-timeline"]').dataset.following === "false",
  672. );
  673. }
  674. const anchor = page.locator('[data-v4-turn-unit][data-turn-id="turn-1"]');
  675. const beforeTop = reading
  676. ? await anchor.evaluate((e) => e.getBoundingClientRect().top)
  677. : null;
  678. await page.evaluate(() => {
  679. window.__hydrationFrames = [];
  680. window.__hydrationStop = false;
  681. const sample = () => {
  682. if (window.__hydrationStop) return;
  683. const units = [...document.querySelectorAll("[data-v4-turn-unit]")];
  684. const pairs = units.slice(1).map((node, index) => ({
  685. from: units[index].dataset.turnId,
  686. to: node.dataset.turnId,
  687. overlap:
  688. units[index].getBoundingClientRect().bottom - node.getBoundingClientRect().top,
  689. }));
  690. window.__hydrationFrames.push({
  691. count: document.querySelector('[data-testid="v4-timeline"]').dataset.windowRowCount,
  692. top: document.querySelector('[data-testid="v4-timeline"]').scrollTop,
  693. gap: (() => {
  694. const e = document.querySelector('[data-testid="v4-timeline"]');
  695. return e.scrollHeight - e.clientHeight - e.scrollTop;
  696. })(),
  697. following: document.querySelector('[data-testid="v4-timeline"]').dataset.following,
  698. anchorTop: document
  699. .querySelector('[data-v4-turn-unit][data-turn-id="turn-1"]')
  700. ?.getBoundingClientRect().top,
  701. pairs,
  702. });
  703. requestAnimationFrame(sample);
  704. };
  705. requestAnimationFrame(sample);
  706. });
  707. await page.getByRole("button", { name: "Hydrate", exact: true }).click();
  708. await page.waitForFunction(
  709. () => window.__hydrationFrames.filter((f) => f.count === "140").length >= 8,
  710. );
  711. samples.push(
  712. ...(await page.evaluate(() => {
  713. window.__hydrationStop = true;
  714. return window.__hydrationFrames;
  715. })),
  716. );
  717. assert.ok(
  718. samples.some((frame) => frame.count === "60"),
  719. "缺少局部历史前置帧",
  720. );
  721. assert.ok(
  722. samples.some((frame) => frame.count === "140"),
  723. "没有补齐历史",
  724. );
  725. const overlapping = samples.filter((frame) =>
  726. frame.pairs.some((pair) => pair.overlap > 1),
  727. );
  728. assert.deepEqual(overlapping, [], "补齐历史出现重叠帧");
  729. assert.equal(
  730. await page.getByTestId("v4-timeline").getAttribute("data-following"),
  731. reading ? "false" : "true",
  732. );
  733. if (reading)
  734. assert.ok(
  735. Math.abs((await anchor.evaluate((e) => e.getBoundingClientRect().top)) - beforeTop) <=
  736. 1,
  737. "历史补齐改变阅读锚点",
  738. );
  739. } finally {
  740. await writeFile(
  741. join(artifacts, `hydrate-${mobile}-${theme}-${reading}.json`),
  742. JSON.stringify(samples, null, 2),
  743. );
  744. await page.screenshot({
  745. path: join(artifacts, `hydrate-${mobile}-${theme}-${reading}.png`),
  746. });
  747. await page.close();
  748. }
  749. });
  750. registerMarkdownTableMotionCases(() => ({ browser, origin, artifacts }));
  751. registerNavigatorHitCases(() => ({ browser, origin, artifacts }));