collapsible-measurement.test.mjs 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248
  1. // SPT05:真实 ToolLayout / Radix / CSS;无 provider,采集隐藏测量和动画生命周期。
  2. import assert from "node:assert/strict";
  3. import { before, after, test } from "node:test";
  4. import { fileURLToPath } from "node:url";
  5. import { mkdir, writeFile } from "node:fs/promises";
  6. import { join } from "node:path";
  7. import { createServer } from "vite";
  8. import react from "@vitejs/plugin-react";
  9. import tailwindcss from "@tailwindcss/vite";
  10. import { chromium, _electron } from "playwright-core";
  11. const root = fileURLToPath(new URL("../../../../../../", import.meta.url));
  12. const entry = "/packages/ui/test/browser/manual-review/pending/collapsible-measurement.fixture.tsx";
  13. const artifacts =
  14. process.env.ZCODE_E2E_ARTIFACT_DIR ||
  15. join(root, "packages/desktop/.e2e-artifacts/collapsible-measurement");
  16. let server, browser, electron, origin;
  17. before(async () => {
  18. await mkdir(artifacts, { recursive: true });
  19. server = await createServer({
  20. root,
  21. configFile: false,
  22. plugins: [
  23. {
  24. name: "collapsible-fixture",
  25. enforce: "pre",
  26. configureServer(vite) {
  27. vite.middlewares.use(async (req, res, next) => {
  28. if (!req.url?.startsWith("/fixture?")) return next();
  29. res.setHeader("Content-Type", "text/html");
  30. res.end(
  31. await vite.transformIndexHtml(
  32. req.url,
  33. `<!doctype html><html><head><meta name="viewport" content="width=device-width, initial-scale=1" /></head><body><div id="root"></div><script type="module" src="${entry}"></script></body></html>`,
  34. ),
  35. );
  36. });
  37. },
  38. },
  39. react(),
  40. tailwindcss(),
  41. ],
  42. resolve: { alias: { "@": `${root}packages/ui/src` } },
  43. optimizeDeps: { entries: [entry.slice(1)] },
  44. server: { host: "127.0.0.1", port: 0, hmr: false },
  45. });
  46. await server.listen();
  47. origin = server.resolvedUrls.local[0];
  48. if (process.env.ZCODE_COLLAPSIBLE_ELECTRON_PATH) {
  49. const main = join(artifacts, "renderer.cjs");
  50. await writeFile(
  51. main,
  52. 'const {app,BrowserWindow}=require("electron");app.setPath("userData",require("node:path").join(__dirname,"electron-profile"));let window;app.whenReady().then(()=>{window=new BrowserWindow({show:true,webPreferences:{nodeIntegration:false,contextIsolation:true,backgroundThrottling:false}});window.loadURL("about:blank");});',
  53. );
  54. const env = { ...process.env };
  55. delete env.ELECTRON_RUN_AS_NODE;
  56. electron = await _electron.launch({
  57. executablePath: process.env.ZCODE_COLLAPSIBLE_ELECTRON_PATH,
  58. args: [main],
  59. env,
  60. });
  61. } else {
  62. browser = await chromium.launch(
  63. process.env.CHROME_EXECUTABLE_PATH
  64. ? { executablePath: process.env.CHROME_EXECUTABLE_PATH }
  65. : { channel: "chrome" },
  66. );
  67. }
  68. });
  69. after(async () => {
  70. await electron?.close();
  71. await browser?.close();
  72. await server?.close();
  73. });
  74. for (const mobile of [false, true])
  75. for (const theme of ["light", "dark"]) {
  76. test(`SPT05 ${mobile ? "mobile" : "desktop"}/${theme}`, async () => {
  77. const page = electron
  78. ? await electron.firstWindow({ timeout: 30000 })
  79. : await browser.newPage({ isMobile: mobile, hasTouch: mobile });
  80. await page.setViewportSize({ width: mobile ? 430 : 1250, height: 800 });
  81. const errors = [];
  82. const onError = (error) => errors.push(String(error));
  83. page.on("pageerror", onError);
  84. const evidence = { measurements: [], errors };
  85. const client = await page.context().newCDPSession(page);
  86. await client.send("Performance.enable");
  87. const metrics = async () =>
  88. Object.fromEntries(
  89. (await client.send("Performance.getMetrics")).metrics.map(({ name, value }) => [
  90. name,
  91. value,
  92. ]),
  93. );
  94. const frames = () =>
  95. page.evaluate(
  96. () =>
  97. new Promise((resolve) => requestAnimationFrame(() => requestAnimationFrame(resolve))),
  98. );
  99. const waitHidden = (id, hidden) =>
  100. page.waitForFunction(({ id, hidden }) => document.getElementById(id)?.hidden === hidden, {
  101. id,
  102. hidden,
  103. });
  104. try {
  105. await page.addInitScript(() => {
  106. window.__foldProbe = { hiddenReads: 0, reads: 0, animations: [] };
  107. const measure = Element.prototype.getBoundingClientRect;
  108. Element.prototype.getBoundingClientRect = function (...args) {
  109. if (this.hasAttribute("data-state")) {
  110. window.__foldProbe.reads++;
  111. if (this.hidden) window.__foldProbe.hiddenReads++;
  112. }
  113. return measure.apply(this, args);
  114. };
  115. document.addEventListener(
  116. "animationstart",
  117. (event) => {
  118. if (event.target.dataset.slot === "collapsible-content")
  119. window.__foldProbe.animations.push({
  120. name: event.animationName,
  121. state: event.target.dataset.state,
  122. });
  123. },
  124. true,
  125. );
  126. });
  127. await page.goto(`${origin}fixture?mobile=${mobile}&theme=${theme}`);
  128. await page.getByRole("button", { name: "Mount", exact: true }).waitFor();
  129. for (let iteration = 0; iteration < 3; iteration++) {
  130. const previous = await metrics();
  131. await page.evaluate(() => {
  132. window.__foldProbe.hiddenReads = 0;
  133. window.__foldProbe.reads = 0;
  134. window.__mountStart = performance.now();
  135. });
  136. await page.getByRole("button", { name: "Mount", exact: true }).click();
  137. await page.waitForFunction(
  138. () =>
  139. document.querySelectorAll('[data-testid^="tool-summary-trigger-measurement-"]')
  140. .length === 134,
  141. );
  142. await frames();
  143. const current = await metrics();
  144. evidence.measurements.push({
  145. ...(await page.evaluate(() => ({
  146. hiddenReads: window.__foldProbe.hiddenReads,
  147. reads: window.__foldProbe.reads,
  148. elapsedMs: performance.now() - window.__mountStart,
  149. }))),
  150. ...Object.fromEntries(
  151. [
  152. "TaskDuration",
  153. "LayoutDuration",
  154. "RecalcStyleDuration",
  155. "LayoutCount",
  156. "RecalcStyleCount",
  157. ].map((name) => [name, current[name] - previous[name]]),
  158. ),
  159. });
  160. if (iteration < 2) await page.getByRole("button", { name: "Mount", exact: true }).click();
  161. }
  162. const trigger = page.getByTestId("tool-summary-trigger-measurement-0");
  163. const id = await trigger.getAttribute("aria-controls");
  164. await trigger.focus();
  165. await page.keyboard.press("Enter");
  166. await waitHidden(id, false);
  167. await page.waitForFunction(() =>
  168. window.__foldProbe.animations.some((event) => event.state === "open"),
  169. );
  170. await page.getByTestId("detail-0").waitFor();
  171. await page.getByTestId("tool-summary-trigger-measurement-nested").click();
  172. await page.getByTestId("nested-detail").waitFor();
  173. await page.getByRole("button", { name: "Width", exact: true }).click();
  174. assert.equal(await trigger.getAttribute("aria-expanded"), "true");
  175. await page.getByRole("button", { name: "Mount", exact: true }).click();
  176. await page.getByRole("button", { name: "Mount", exact: true }).click();
  177. await page.getByTestId("nested-detail").waitFor();
  178. assert.equal(await trigger.getAttribute("aria-expanded"), "true");
  179. const remountedId = await trigger.getAttribute("aria-controls");
  180. await frames();
  181. await trigger.click();
  182. await page.waitForFunction(() =>
  183. window.__foldProbe.animations.some((event) => event.state === "closed"),
  184. );
  185. await waitHidden(remountedId, true);
  186. // 收起过程中反向打开,不能被旧 animationend 或卸载回调清空。
  187. await trigger.click();
  188. await frames();
  189. await trigger.click();
  190. await frames();
  191. await trigger.click();
  192. await page.getByTestId("detail-0").waitFor();
  193. await page.waitForFunction(
  194. (id) => document.getElementById(id)?.getAnimations({ subtree: true }).length === 0,
  195. remountedId,
  196. );
  197. assert.equal(await trigger.getAttribute("aria-expanded"), "true");
  198. assert.ok(await page.getByTestId("nested-detail").isVisible());
  199. await page.getByRole("button", { name: "Special", exact: true }).click();
  200. for (const name of ["default-content", "force-content"]) {
  201. const value = await page.getByTestId(name).evaluate((node) => ({
  202. hidden: node.hidden,
  203. height: Number.parseFloat(
  204. node.style.getPropertyValue("--radix-collapsible-content-height"),
  205. ),
  206. }));
  207. assert.equal(value.hidden, false);
  208. assert.ok(value.height > 0, JSON.stringify(value));
  209. }
  210. assert.ok(await page.getByRole("button", { name: "Disabled", exact: true }).isDisabled());
  211. await page.getByTestId("auto-detail").waitFor();
  212. await page.getByRole("button", { name: "Complete", exact: true }).click();
  213. const autoTrigger = page.getByTestId("tool-summary-trigger-measurement-auto");
  214. await waitHidden(await autoTrigger.getAttribute("aria-controls"), true);
  215. await autoTrigger.click();
  216. await page.getByTestId("auto-detail").waitFor();
  217. await page.getByRole("button", { name: "Accordion", exact: true }).click();
  218. await page.getByTestId("accordion-detail").waitFor();
  219. await page.getByRole("button", { name: "Accordion", exact: true }).click();
  220. assert.equal(
  221. await page
  222. .getByRole("button", { name: "Accordion", exact: true })
  223. .getAttribute("aria-expanded"),
  224. "false",
  225. );
  226. await trigger.scrollIntoViewIfNeeded();
  227. await page.screenshot({
  228. path: join(artifacts, `${mobile ? "mobile" : "desktop"}-${theme}.png`),
  229. });
  230. evidence.animations = await page.evaluate(() => window.__foldProbe.animations);
  231. assert.deepEqual(errors, []);
  232. assert.ok(
  233. evidence.measurements.every((sample) => sample.hiddenReads === 0),
  234. JSON.stringify(evidence.measurements),
  235. );
  236. } finally {
  237. await writeFile(
  238. join(artifacts, `${mobile ? "mobile" : "desktop"}-${theme}.json`),
  239. JSON.stringify(evidence, null, 2),
  240. );
  241. page.off("pageerror", onError);
  242. await client.detach();
  243. if (!electron) await page.close();
  244. }
  245. });
  246. }