playwright_e2e.cjs 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664
  1. const assert = require("node:assert/strict");
  2. const fs = require("node:fs");
  3. const {createHash} = require("node:crypto");
  4. const path = require("node:path");
  5. const {chromium} = require(path.resolve(__dirname, "../../tools/board-viewer/node_modules/playwright"));
  6. const root = path.resolve(__dirname, "../..");
  7. const baseUrl = process.env.BOARD_VIEWER_URL || "http://127.0.0.1:8765";
  8. const targetUrl = new URL(baseUrl);
  9. // This suite exercises the MRDIMM fixture, while the app defaults to 6400 V2.
  10. targetUrl.searchParams.set("version", "v1_2");
  11. const origin = targetUrl.origin;
  12. const artifacts = process.env.BOARD_VIEWER_E2E_ARTIFACTS || path.resolve(process.env.TEMP || root, "board-viewer-e2e");
  13. const schematicPdfUrl = new URL("/schematics/FCB_FPGA+MCU0611.pdf", origin).href;
  14. const schematicPdfFile = path.join(root, "reference/original/schematics/FCB_FPGA+MCU0611.pdf");
  15. const pdfResourceEvidence = [];
  16. const executablePath = process.env.BOARD_VIEWER_BROWSER || undefined;
  17. const launchArgs = String(process.env.BOARD_VIEWER_BROWSER_ARGS || "")
  18. .split(/\s+/)
  19. .filter(Boolean);
  20. if (launchArgs.length === 0 && process.platform === "linux") {
  21. launchArgs.push("--disable-gpu", "--disable-dev-shm-usage", "--no-sandbox");
  22. }
  23. const boardData = JSON.parse(fs.readFileSync(path.join(root, "tools/board-viewer/generated/board-data.json"), "utf8"));
  24. const candidateExpectation = JSON.parse(
  25. fs.readFileSync(path.join(root, "tests/board_viewer/fixtures/candidate_count_expectation.json"), "utf8"),
  26. );
  27. for (const [file, expected] of [
  28. ["tools/board-viewer/generated/board-data.json", candidateExpectation.bound_to.board_data_sha256],
  29. ["tools/board-viewer/generated/build-info.json", candidateExpectation.bound_to.build_info_sha256],
  30. ]) {
  31. const actual = createHash("sha256").update(fs.readFileSync(path.join(root, file))).digest("hex");
  32. assert.equal(actual, expected, `stale candidate expectation: ${file}`);
  33. }
  34. const frontTouchpoints = boardData.touchpoints.filter((item) => (item.side || "front") === "front");
  35. const expectedHotspotCount = frontTouchpoints.length;
  36. // Desktop checks explicitly turn on SH and SVG mode before inspecting pin DOM.
  37. const expectedPinCount = frontTouchpoints.reduce((total, item) => total + item.pins.length, 0);
  38. fs.mkdirSync(artifacts, {recursive: true});
  39. function clone(value) {
  40. return JSON.parse(JSON.stringify(value));
  41. }
  42. async function createPage(browser, viewport, options = {}) {
  43. const context = await browser.newContext({
  44. viewport,
  45. permissions: ["clipboard-read", "clipboard-write"],
  46. locale: "zh-CN",
  47. });
  48. const consoleErrors = [];
  49. const requestFailures = [];
  50. const pdfFrameAborts = [];
  51. const badResponses = [];
  52. const page = await context.newPage();
  53. page.on("console", (message) => {
  54. if (message.type() === "error") consoleErrors.push(message.text());
  55. });
  56. page.on("requestfailed", (request) => {
  57. const error = request.failure()?.errorText;
  58. if (request.url() === schematicPdfUrl && error === "net::ERR_ABORTED"
  59. && request.resourceType() === "document" && request.isNavigationRequest()) {
  60. let frame;
  61. try { frame = request.frame(); } catch { /* Keep unbound failures strict. */ }
  62. if (frame && frame !== page.mainFrame()) {
  63. pdfFrameAborts.push({frame, url: request.url(), error});
  64. return;
  65. }
  66. }
  67. requestFailures.push(`${request.url()}: ${error}`);
  68. });
  69. page.on("response", (response) => {
  70. if (response.status() >= 400) badResponses.push(`${response.status()} ${response.url()}`);
  71. });
  72. await page.route("**/*", async (route) => {
  73. const url = new URL(route.request().url());
  74. if (url.origin !== origin) {
  75. await route.abort("blockedbyclient");
  76. return;
  77. }
  78. if (options.data && url.pathname === "/generated/board-data.json") {
  79. await route.fulfill({status: 200, contentType: "application/json", body: JSON.stringify(options.data)});
  80. return;
  81. }
  82. if (options.runtime && url.pathname === "/api/status") {
  83. await route.fulfill({status: 200, contentType: "application/json", body: JSON.stringify(options.runtime)});
  84. return;
  85. }
  86. await route.continue();
  87. });
  88. await page.goto(targetUrl.href, {waitUntil: "networkidle"});
  89. await page.waitForFunction(
  90. (count) => document.querySelectorAll(".hotspot").length === count,
  91. expectedHotspotCount,
  92. );
  93. assert.equal(await page.locator("#board-version-select").inputValue(), "v1_2");
  94. return {context, page, consoleErrors, requestFailures, pdfFrameAborts, badResponses};
  95. }
  96. async function assertCjkFontLayout(page) {
  97. const probe = await page.evaluate(async () => {
  98. await document.fonts.ready;
  99. const canvas = document.createElement("canvas");
  100. const ctx = canvas.getContext("2d");
  101. const sample = "电阻网络背面冲突";
  102. const fonts = [
  103. "Noto Sans CJK SC",
  104. "Noto Sans SC",
  105. "Source Han Sans SC",
  106. "Microsoft YaHei UI",
  107. "Microsoft YaHei",
  108. "PingFang SC",
  109. "sans-serif",
  110. ];
  111. const measurements = [];
  112. for (const font of fonts) {
  113. ctx.font = `24px "${font}"`;
  114. const width = ctx.measureText(sample).width;
  115. measurements.push({font, width});
  116. }
  117. // This checks declared font fallback and layout width, not glyph availability.
  118. // Screenshots remain the evidence for actual rendered CJK glyphs.
  119. ctx.font = '24px "Noto Sans CJK SC", "Noto Sans SC", "Microsoft YaHei", sans-serif';
  120. const stacked = ctx.measureText(sample).width;
  121. const ascii = ctx.measureText("ABCDEFGH").width;
  122. const bodyFont = getComputedStyle(document.body).fontFamily;
  123. return {measurements, stacked, ascii, bodyFont, sample};
  124. });
  125. assert.ok(probe.stacked > probe.ascii * 0.9, `CJK text layout width too small: ${JSON.stringify(probe)}`);
  126. assert.ok(
  127. /Noto Sans CJK SC|Noto Sans SC|Source Han Sans SC|Microsoft YaHei|PingFang SC/i.test(probe.bodyFont),
  128. `body font-family missing CJK fallback: ${probe.bodyFont}`,
  129. );
  130. // Canvas check: Chinese sample must render wider than 8 ASCII letters roughly.
  131. assert.ok(probe.stacked > 80, `CJK canvas text layout width: ${probe.stacked}`);
  132. return probe;
  133. }
  134. async function assertResistorPadUsesRealGeometry(page) {
  135. const info = await page.evaluate(() => {
  136. const markers = [...document.querySelectorAll(".resistor-pad-marker")];
  137. return markers.map((node) => {
  138. const tag = node.tagName.toLowerCase();
  139. if (tag === "circle") {
  140. return {tag, r: Number(node.getAttribute("r") || 0)};
  141. }
  142. if (tag === "ellipse") {
  143. return {
  144. tag,
  145. rx: Number(node.getAttribute("rx") || 0),
  146. ry: Number(node.getAttribute("ry") || 0),
  147. };
  148. }
  149. if (tag === "rect") {
  150. return {
  151. tag,
  152. width: Number(node.getAttribute("width") || 0),
  153. height: Number(node.getAttribute("height") || 0),
  154. };
  155. }
  156. // marker may be nested in <g>
  157. const rect = node.querySelector?.("rect.resistor-pad-marker") || node;
  158. return {
  159. tag: rect.tagName.toLowerCase(),
  160. width: Number(rect.getAttribute("width") || 0),
  161. height: Number(rect.getAttribute("height") || 0),
  162. parent: node.parentElement?.tagName?.toLowerCase() || "",
  163. };
  164. });
  165. });
  166. assert.ok(info.length >= 1, "expected resistor pad markers");
  167. for (const item of info) {
  168. assert.notEqual(item.tag, "circle", `pad marker must not be oversized circle: ${JSON.stringify(item)}`);
  169. if (item.tag === "rect") {
  170. assert.ok(item.width > 0 && item.width < 2.5, `pad width implausible: ${item.width}`);
  171. assert.ok(item.height > 0 && item.height < 2.5, `pad height implausible: ${item.height}`);
  172. }
  173. }
  174. }
  175. async function assertHealthy(session) {
  176. await session.page.waitForTimeout(50);
  177. assert.deepEqual(session.consoleErrors, [], `console errors: ${session.consoleErrors.join("\n")}`);
  178. assert.deepEqual(session.requestFailures, [], `request failures: ${session.requestFailures.join("\n")}`);
  179. assert.deepEqual(session.badResponses, [], `bad responses: ${session.badResponses.join("\n")}`);
  180. // Chromium may abort an embedded PDF navigation in headless mode. Keep only
  181. // this exact iframe/document abort separate and verify the actual full PDF.
  182. for (const failure of session.pdfFrameAborts) {
  183. const element = await failure.frame.frameElement();
  184. assert.equal(await element.evaluate((node) =>
  185. node.matches("#schematic-content iframe.pdf-viewer-frame")), true);
  186. const frameSrc = await element.getAttribute("src");
  187. assert.equal(new URL(frameSrc, session.page.url()).href, schematicPdfUrl);
  188. }
  189. const response = await session.context.request.get(schematicPdfUrl, {maxRedirects: 0});
  190. assert.equal(response.status(), 200, `PDF HTTP status: ${response.status()}`);
  191. const contentType = response.headers()["content-type"] || "";
  192. assert.match(contentType, /^application\/pdf(?:;|$)/i);
  193. const body = await response.body();
  194. assert.equal(body.subarray(0, 5).toString("ascii"), "%PDF-");
  195. const digest = createHash("sha256").update(body).digest("hex");
  196. const expectedDigest = createHash("sha256").update(fs.readFileSync(schematicPdfFile)).digest("hex");
  197. assert.equal(digest, expectedDigest, "served PDF bytes differ from the server-mapped source file");
  198. pdfResourceEvidence.push({
  199. url: schematicPdfUrl, viewport: session.page.viewportSize(), status: response.status(),
  200. contentType, bytes: body.length, sha256: digest,
  201. subframeNavigationAborts: session.pdfFrameAborts.map(({url, error}) => ({url, error})),
  202. visualRendering: "NOT_ASSERTED; full HTTP PDF bytes checked separately from headless iframe navigation",
  203. });
  204. fs.writeFileSync(path.join(artifacts, "pdf-resource-evidence.json"), JSON.stringify(pdfResourceEvidence, null, 2));
  205. }
  206. async function assertNoViewportOverflow(page) {
  207. const metrics = await page.evaluate(() => {
  208. const viewport = {width: window.innerWidth, height: window.innerHeight};
  209. const topbar = document.querySelector(".topbar").getBoundingClientRect();
  210. const board = document.querySelector(".board-pane").getBoundingClientRect();
  211. const boardViewport = document.querySelector("#board-viewport").getBoundingClientRect();
  212. const footer = document.querySelector(".board-footer").getBoundingClientRect();
  213. const panel = document.querySelector("#detail-panel").getBoundingClientRect();
  214. return {
  215. viewport,
  216. scrollWidth: document.documentElement.scrollWidth,
  217. scrollHeight: document.documentElement.scrollHeight,
  218. topbar: {left: topbar.left, right: topbar.right, top: topbar.top, bottom: topbar.bottom},
  219. board: {left: board.left, right: board.right, top: board.top, bottom: board.bottom},
  220. boardViewport: {top: boardViewport.top, bottom: boardViewport.bottom, height: boardViewport.height},
  221. footer: {top: footer.top, bottom: footer.bottom, height: footer.height},
  222. panel: {left: panel.left, right: panel.right, top: panel.top, bottom: panel.bottom},
  223. loadingDisplay: getComputedStyle(document.querySelector("#board-loading")).display,
  224. };
  225. });
  226. assert.ok(metrics.scrollWidth <= metrics.viewport.width + 1, JSON.stringify(metrics));
  227. assert.ok(metrics.scrollHeight <= metrics.viewport.height + 1, JSON.stringify(metrics));
  228. assert.ok(metrics.topbar.left >= -1 && metrics.topbar.right <= metrics.viewport.width + 1, JSON.stringify(metrics));
  229. assert.ok(metrics.board.left >= -1 && metrics.board.right <= metrics.viewport.width + 1, JSON.stringify(metrics));
  230. assert.ok(metrics.panel.left >= -1 && metrics.panel.right <= metrics.viewport.width + 1, JSON.stringify(metrics));
  231. assert.equal(metrics.loadingDisplay, "none", JSON.stringify(metrics));
  232. if (metrics.viewport.width > 860) {
  233. assert.ok(metrics.boardViewport.height > 400, JSON.stringify(metrics));
  234. assert.ok(metrics.footer.height <= 34, JSON.stringify(metrics));
  235. assert.ok(metrics.footer.bottom >= metrics.viewport.height - 1, JSON.stringify(metrics));
  236. }
  237. }
  238. async function selectSearchResult(page, query, expectedKey) {
  239. const search = page.locator("#board-search");
  240. await search.fill(query);
  241. const result = page.locator(".search-result").filter({hasText: expectedKey}).first();
  242. await result.waitFor({state: "visible"});
  243. await result.click();
  244. }
  245. async function connectorGrid(page) {
  246. return page.locator(".connector-grid-row").evaluateAll((rows) =>
  247. rows.map((row) => Array.from(row.querySelectorAll(".connector-contact")).map((pin) => pin.textContent.trim())),
  248. );
  249. }
  250. async function assertRenderedPinPositionsMatchGeneratedData(page) {
  251. const rendered = await page.locator(".pin-group").evaluateAll((groups) => Object.fromEntries(
  252. groups.map((group) => {
  253. const dot = group.querySelector(".pin-dot");
  254. const rect = dot.tagName.toLowerCase() === "rect";
  255. const x = rect ? Number(dot.getAttribute("x")) + Number(dot.getAttribute("width")) / 2 : Number(dot.getAttribute("cx"));
  256. const y = rect ? Number(dot.getAttribute("y")) + Number(dot.getAttribute("height")) / 2 : Number(dot.getAttribute("cy"));
  257. return [group.dataset.pinId, {x, y}];
  258. }),
  259. ));
  260. const expected = Object.fromEntries(frontTouchpoints.flatMap((touchpoint) =>
  261. touchpoint.pins.map((pin) => [pin.id, pin.view_position]),
  262. ));
  263. assert.equal(Object.keys(rendered).length, expectedPinCount);
  264. assert.deepEqual(Object.keys(rendered).sort(), Object.keys(expected).sort());
  265. for (const [id, point] of Object.entries(expected)) {
  266. assert.ok(Math.abs(rendered[id].x - point.x) < 1e-9, `${id} x: ${rendered[id].x} != ${point.x}`);
  267. assert.ok(Math.abs(rendered[id].y - point.y) < 1e-9, `${id} y: ${rendered[id].y} != ${point.y}`);
  268. }
  269. }
  270. async function desktopWorkflow(browser, viewport, name) {
  271. const session = await createPage(browser, viewport);
  272. const {page} = session;
  273. try {
  274. await assertCjkFontLayout(page);
  275. await page.getByText("数据已校验", {exact: true}).waitFor();
  276. assert.equal(await page.locator(".hotspot").count(), expectedHotspotCount);
  277. assert.equal(await page.locator("#board-svg").evaluate((node) => node.classList.contains("perf-ultra")), true);
  278. assert.equal(await page.locator(".pin-group").count(), 0);
  279. await page.locator("#perf-mode-toggle").click();
  280. await page.locator("#filter-sh").check();
  281. await page.waitForFunction((count) => document.querySelectorAll(".pin-group").length === count, expectedPinCount);
  282. assert.equal(await page.locator("#board-svg").evaluate((node) => node.classList.contains("perf-ultra")), false);
  283. assert.equal(await page.locator(".pin-group").count(), expectedPinCount);
  284. await assertRenderedPinPositionsMatchGeneratedData(page);
  285. assert.equal(await page.locator(".pin-group").first().getAttribute("tabindex"), "0");
  286. assert.equal(await page.locator("#photo-layer").isDisabled(), true);
  287. assert.equal(await page.locator('#layer-controls input[value="copper"]').isChecked(), true);
  288. assert.equal(await page.locator("#layer-copper").isVisible(), true);
  289. assert.equal(await page.locator("#layer-mask").getAttribute("href"), "/generated/board-mask-edge.svg");
  290. await assertNoViewportOverflow(page);
  291. await page.screenshot({path: path.join(artifacts, `${name}-initial.png`), fullPage: true});
  292. const con18 = page.locator('.hotspot[data-reference="CON18"]');
  293. const con18Box = await con18.boundingBox();
  294. assert.ok(con18Box);
  295. // The current SVG keeps connector keyboard targets; pin pointer selection
  296. // below separately exercises the shared WASM hit-testing path.
  297. await con18.focus();
  298. await con18.press("Enter");
  299. await page.locator(".detail-reference").getByText("CON18", {exact: true}).waitFor();
  300. await page.locator("#detail-content").getByText("板正面接触针排列", {exact: true}).waitFor();
  301. await page.locator("#detail-content").getByText("板正面俯视", {exact: false}).waitFor();
  302. await page.locator("#detail-content").getByText("线缆端或对接面可能是镜像", {exact: false}).waitFor();
  303. assert.deepEqual(await connectorGrid(page), [
  304. ["13", "11", "9", "7", "5", "3", "1"],
  305. ["14", "12", "10", "8", "6", "4", "2"],
  306. ]);
  307. assert.equal(await page.locator('.pin-row[data-pad-role="contact"]').count(), 14);
  308. await page.locator("#detail-content").getByText("上", {exact: true}).first().waitFor();
  309. await page.locator("#detail-content").getByText("下", {exact: true}).first().waitFor();
  310. await selectSearchResult(page, "CON23", "CON23");
  311. assert.deepEqual(await connectorGrid(page), [["5", "1"], ["6", "2"], ["7", "3"], ["8", "4"]]);
  312. await selectSearchResult(page, "CON8", "CON8");
  313. assert.deepEqual(await connectorGrid(page), [["8"], ["7"], ["6"], ["5"], ["4"], ["3"], ["2"], ["1"]]);
  314. await selectSearchResult(page, "J3", "J3");
  315. await page.locator("#detail-content").getByText("EF2L45BG256B FPGA JTAG 调试/配置接口(专用配置脚)", {exact: true}).waitFor();
  316. await page.locator("#detail-content .category-tag").filter({hasText: /^JTAG \/ SWD · /}).waitFor();
  317. assert.deepEqual(await connectorGrid(page), [
  318. ["1", "2"],
  319. ["3", "4"],
  320. ["5", "6"],
  321. ["7", "8"],
  322. ["9", "10"],
  323. ]);
  324. const j3Pin1Primary = await page.locator('.pin-row[data-pin="1"] .pin-primary > span').allTextContents();
  325. assert.match(j3Pin1Primary[0], /TCK/);
  326. assert.match(await page.locator('.pin-row[data-pin="1"] .pin-net').textContent(), /原始网络.*N9532014/);
  327. await selectSearchResult(page, "J3.1", "J3.1");
  328. await page.locator("#detail-content").getByText("FPGA 专用 JTAG 时钟输入", {exact: false}).first().waitFor();
  329. await page.locator("#detail-content").getByText("U3.A7 专用 TCK", {exact: true}).waitFor();
  330. await page.locator("#detail-content").getByText("R63 22R 串联", {exact: true}).first().waitFor();
  331. await page.locator("#detail-content").getByText("不要在 RTL 顶层声明", {exact: false}).waitFor();
  332. await page.locator("#detail-content").getByText("专用配置脚不使用用户 ADC 约束", {exact: true}).waitFor();
  333. assert.equal(await page.getByLabel("RTL 端口名").count(), 0);
  334. await page.screenshot({path: path.join(artifacts, `${name}-j3.png`), fullPage: true});
  335. await assertNoViewportOverflow(page);
  336. await selectSearchResult(page, "J3.4", "J3.4");
  337. await page.locator("#detail-content").getByText("不是给板子供电", {exact: false}).first().waitFor();
  338. await page.locator("#detail-content").getByText("R61 0R", {exact: false}).first().waitFor();
  339. await page.locator("#detail-content").getByText("不要通过 VREF 反向给板子供电", {exact: false}).waitFor();
  340. await selectSearchResult(page, "J3.6", "J3.6");
  341. await page.locator("#detail-content").getByText("不能把 NC 当作备用 GPIO", {exact: false}).waitFor();
  342. await selectSearchResult(page, "J11", "J11");
  343. await page.locator("#detail-content").getByText("M3 安装孔(非电气接口)", {exact: true}).waitFor();
  344. await selectSearchResult(page, "J8", "J8");
  345. await page.locator(".detail-reference").getByText("J8", {exact: true}).waitFor();
  346. await selectSearchResult(page, "PL2001", "PL2001");
  347. await page.locator("#detail-content .category-tag").filter({hasText: /^电源 \/ 测点 · /}).waitFor();
  348. await page.locator("#detail-content").getByText("+5V 开关电源电感(非连接器)", {exact: true}).waitFor();
  349. const beforeZoom = await page.locator("#board-svg").getAttribute("viewBox");
  350. await page.locator("#zoom-in").click();
  351. await page.waitForFunction((before) => document.querySelector("#board-svg").getAttribute("viewBox") !== before, beforeZoom);
  352. const afterZoom = await page.locator("#board-svg").getAttribute("viewBox");
  353. assert.notEqual(afterZoom, beforeZoom);
  354. await selectSearchResult(page, "CON78", "CON78");
  355. assert.equal(await page.locator('.pin-row[data-pad-role="contact"]').count(), 4);
  356. assert.equal(await page.locator('.pin-row[data-pad-role="shield"]').count(), 2);
  357. assert.equal(await page.locator('.pin-group[data-reference="CON78"][data-pin="5"]').getAttribute("data-pad-role"), "shield");
  358. await page.locator("#detail-content").getByText("屏蔽固定焊盘", {exact: true}).first().waitFor();
  359. await selectSearchResult(page, "CON78.1", "CON78.1");
  360. assert.equal(await page.locator('.pin-group[data-reference="CON78"][data-pin="1"]').getAttribute("tabindex"), "0");
  361. await page.locator("#detail-content").getByText("U23 TRSF3232EIPWR", {exact: true}).first().waitFor();
  362. await page.locator(".pin-detail .detail-facts").getByText("FPGA U3.M10 (host_rs232_tx (UART2_TX))", {exact: true}).waitFor();
  363. await page.locator(".pin-detail").getByText("RS232_TX2", {exact: true}).first().waitFor();
  364. await page.locator("#detail-content").getByText("编程结论", {exact: true}).waitFor();
  365. await page.locator("#detail-content").getByText("FPGA 输出", {exact: false}).waitFor();
  366. await page.locator("#detail-content").getByText("连接到对端设备的接收端(RX)。", {exact: true}).waitFor();
  367. await page.locator("#detail-content").getByText("不能直接接 3.3V TTL/CMOS 串口", {exact: false}).waitFor();
  368. await page.locator("#detail-content").getByText("LOCATION = M10", {exact: true}).waitFor();
  369. await page.locator("#detail-content").getByText("IOSTANDARD = LVCMOS33", {exact: true}).waitFor();
  370. const groundPin = page.locator('.pin-group[data-reference="CON78"][data-pin="3"] .pin-dot');
  371. await page.waitForTimeout(250); // let the existing 220 ms focus animation finish
  372. const pinBox = await groundPin.boundingBox();
  373. assert.ok(pinBox);
  374. const groundPoint = {x: pinBox.x + pinBox.width / 2, y: pinBox.y + pinBox.height / 2};
  375. await page.mouse.move(groundPoint.x, groundPoint.y);
  376. await page.getByRole("tooltip").getByText("CON78.3", {exact: true}).waitFor();
  377. await page.mouse.click(groundPoint.x, groundPoint.y);
  378. await page.locator(".pin-detail").getByText("CON78.3", {exact: false}).first().waitFor();
  379. assert.equal(await page.locator(".net-highlight").count(), 0);
  380. await page.keyboard.down("Control");
  381. try {
  382. await page.mouse.click(groundPoint.x, groundPoint.y);
  383. } finally {
  384. await page.keyboard.up("Control");
  385. }
  386. assert.ok(await page.locator(".net-highlight").count() > 20);
  387. await selectSearchResult(page, "CON12.3", "CON12.3");
  388. await page.locator(".detail-reference").getByText("CON12", {exact: true}).waitFor();
  389. await page.locator(".pin-detail").getByText("EX_GPIO3", {exact: false}).first().waitFor();
  390. await page.locator(".pin-detail").getByText("limit_lower_raw[1]", {exact: false}).first().waitFor();
  391. await page.locator(".pin-detail .detail-facts").getByText("FPGA U3.C8 (limit_lower_raw[1] (LS2))", {exact: true}).waitFor();
  392. await selectSearchResult(page, "CON31.4", "CON31.4");
  393. await page.locator("#detail-content").getByText("开集电极", {exact: false}).first().waitFor();
  394. await page.locator("#detail-content").getByText("FPGA high", {exact: false}).first().waitFor();
  395. await page.locator("#detail-content").getByText("LOCATION = E10", {exact: true}).waitFor();
  396. await selectSearchResult(page, "CON54.1", "CON54.1");
  397. await page.locator("#detail-content").getByText("open-drain", {exact: false}).first().waitFor();
  398. await page.locator("#detail-content").getByText("开漏", {exact: false}).first().waitFor();
  399. await page.locator("#detail-content").getByText("LOCATION = B14", {exact: true}).waitFor();
  400. await selectSearchResult(page, "CON53.1", "CON53.1");
  401. await page.locator("#detail-content").getByText("远端温度二极管", {exact: false}).first().waitFor();
  402. await page.locator("#detail-content").getByText("不要为 CON53.1 声明 FPGA GPIO", {exact: false}).waitFor();
  403. await selectSearchResult(page, "CON2.5", "CON2.5");
  404. await page.locator("#detail-content").getByText("板端电源输入", {exact: false}).first().waitFor();
  405. await page.locator("#detail-content").getByText("CON2.5 +12V_VIN", {exact: false}).first().waitFor();
  406. await selectSearchResult(page, "J25.2", "J25.2");
  407. await page.locator("#detail-content").getByText("GD32F303CGT6", {exact: false}).first().waitFor();
  408. await page.locator("#detail-content").getByText("SWCLK", {exact: false}).first().waitFor();
  409. await page.locator("#detail-content").getByText("U27.37", {exact: false}).first().waitFor();
  410. await page.locator("#detail-content").getByText("不对应 FPGA RTL 或 ADC", {exact: false}).waitFor();
  411. await page.locator("#candidate-tab").click();
  412. for (const capability of ["pwm", "gpio", "uart_tx"]) {
  413. await page.locator("#capability-select").selectOption(capability);
  414. const keys = await page.locator(".candidate-row .candidate-key").allTextContents();
  415. const pinKeys = keys.map((key) => key.split(" · ")[0]);
  416. assert.equal(pinKeys.length, candidateExpectation.candidate_counts[capability]);
  417. assert.deepEqual(pinKeys.sort(), [...candidateExpectation.candidate_keys[capability]].sort());
  418. if (!pinKeys.length) {
  419. await page.locator("#candidate-content").getByText("没有满足全部证据条件的候选", {exact: true}).waitFor();
  420. }
  421. }
  422. await page.locator("#detail-tab").click();
  423. await page.locator("#board-search").fill("does-not-exist");
  424. await page.locator("#search-results").getByText("没有匹配的座子、电阻或针脚", {exact: true}).waitFor();
  425. // Pass I: resistor search focuses resistor entity with value/net detail.
  426. await selectSearchResult(page, "R674", "R674");
  427. await page.locator(".detail-reference").getByText("R674", {exact: true}).waitFor();
  428. await page.locator("#detail-content .category-tag").getByText("电阻", {exact: true}).waitFor();
  429. await page.locator("#detail-content .side-tag").getByText("背面", {exact: true}).waitFor();
  430. assert.equal(await page.locator('#side-controls input[value="back"]').isChecked(), true);
  431. assert.equal(await page.locator("#board-svg").getAttribute("data-side"), "back");
  432. assert.equal(
  433. await page.locator("#layer-copper").getAttribute("href"),
  434. "/generated/board-copper-back.svg",
  435. );
  436. await page.locator('.hotspot-resistor[data-reference="R674"]').waitFor();
  437. await page.locator("#detail-content").getByText("两侧网络", {exact: true}).waitFor();
  438. await page.locator("#detail-content").getByText("PUL1", {exact: false}).first().waitFor();
  439. await page.locator("#detail-content").getByText("证据与冲突", {exact: true}).waitFor();
  440. await page.locator("#detail-content").getByText("原理图声明与当前 PCB 索引冲突", {exact: false}).first().waitFor();
  441. await page.locator("#back-view-tip").waitFor();
  442. await page.locator("#detail-content").getByText("阻值覆盖", {exact: false}).first().waitFor();
  443. await assertCjkFontLayout(page);
  444. await page.screenshot({path: path.join(artifacts, `${name}-r674.png`), fullPage: true});
  445. await selectSearchResult(page, "R674.1", "R674.1");
  446. await page.locator(".detail-reference").getByText("R674", {exact: true}).waitFor();
  447. await page.locator("#selection-readout").getByText("R674.1", {exact: false}).waitFor();
  448. await assertResistorPadUsesRealGeometry(page);
  449. await page.screenshot({path: path.join(artifacts, `${name}-r674-pad.png`), fullPage: true});
  450. await selectSearchResult(page, "120R", "R806");
  451. await page.locator(".detail-reference").getByText("R806", {exact: true}).waitFor();
  452. await page.screenshot({path: path.join(artifacts, `${name}-120r.png`), fullPage: true});
  453. await page.locator("#board-search").fill("0R");
  454. await page.locator(".search-result").first().waitFor();
  455. const zeroKeys = await page.locator(".search-result .result-key").allTextContents();
  456. assert.ok(zeroKeys.length >= 1, "0R should find fitted/unknown zero-ohm resistors");
  457. await page.screenshot({path: path.join(artifacts, `${name}-0r.png`), fullPage: true});
  458. await page.locator("#board-search").fill("4k7");
  459. const expected4k7 = new Set(boardData.resistors.filter((item) => item.value_ohms === 4700).map((item) => item.reference));
  460. if (expected4k7.size) {
  461. await page.locator(".search-result").first().waitFor();
  462. const keys = await page.locator(".search-result .result-key").allTextContents();
  463. assert.ok(keys.length > 0);
  464. assert.ok(keys.every((key) => expected4k7.has(key)), `4k7 returned another value: ${keys}`);
  465. } else {
  466. await page.locator(".empty-search").waitFor();
  467. const emptyOrCoverage = await page.locator(".empty-search").textContent();
  468. assert.match(String(emptyOrCoverage || ""), /当前索引中没有此阻值|阻值覆盖/);
  469. }
  470. await page.locator("#board-search").fill("R7");
  471. await page.locator(".search-result").first().waitFor();
  472. const r7Keys = await page.locator(".search-result .result-key").allTextContents();
  473. assert.equal(r7Keys[0], "R7");
  474. assert.ok(!r7Keys.some((key) => /FPGA|ball/i.test(key)));
  475. await page.locator("#board-search").fill("R12");
  476. await page.locator(".search-result .result-key").getByText("R12", {exact: true}).first().waitFor();
  477. const r12Keys = await page.locator(".search-result .result-key").allTextContents();
  478. assert.ok(!r12Keys.includes("R1225"));
  479. await page.locator("#board-search").fill("ball:R7");
  480. // May be empty if no ball R7 on product board; just ensure R7 resistor is not sole forced hit.
  481. await page.waitForTimeout(80);
  482. await selectSearchResult(page, "PUL1", "R674");
  483. await page.locator("#detail-content").getByText("PUL1", {exact: false}).first().waitFor();
  484. await page.screenshot({path: path.join(artifacts, `${name}-pul1.png`), fullPage: true});
  485. await selectSearchResult(page, "CON104.2", "CON104.2");
  486. assert.equal(await page.locator('#side-controls input[value="front"]').isChecked(), true);
  487. assert.equal(await page.locator("#board-svg").getAttribute("data-side"), "front");
  488. assert.equal(
  489. await page.locator("#layer-copper").getAttribute("href"),
  490. "/generated/board-copper.svg",
  491. );
  492. await page.locator("#detail-content").getByText("关联电阻", {exact: false}).first().waitFor();
  493. await page.locator(".pin-row").filter({hasText: "R674"}).first().click();
  494. await page.locator(".detail-reference").getByText("R674", {exact: true}).waitFor();
  495. assert.equal(await page.locator('#side-controls input[value="back"]').isChecked(), true);
  496. assert.equal(await page.locator("#board-svg").getAttribute("data-side"), "back");
  497. await selectSearchResult(page, "R63", "R63");
  498. await page.locator(".detail-reference").getByText("R63", {exact: true}).waitFor();
  499. await page.locator("#detail-content .category-tag").getByText("电阻", {exact: true}).waitFor();
  500. await page.screenshot({path: path.join(artifacts, `${name}-selected.png`), fullPage: true});
  501. await assertNoViewportOverflow(page);
  502. await assertHealthy(session);
  503. } finally {
  504. await session.context.close();
  505. }
  506. }
  507. async function mobileWorkflow(browser) {
  508. const session = await createPage(browser, {width: 390, height: 844});
  509. const {page} = session;
  510. try {
  511. await assertNoViewportOverflow(page);
  512. await page.screenshot({path: path.join(artifacts, "390x844-initial.png"), fullPage: true});
  513. assert.equal(await page.locator("#app").evaluate((node) => node.classList.contains("detail-collapsed")), true);
  514. await selectSearchResult(page, "CON78", "CON78");
  515. assert.equal(await page.locator("#app").evaluate((node) => node.classList.contains("detail-collapsed")), false);
  516. await page.locator(".detail-reference").getByText("CON78", {exact: true}).waitFor();
  517. await page.screenshot({path: path.join(artifacts, "390x844-selected.png"), fullPage: true});
  518. await assertNoViewportOverflow(page);
  519. await selectSearchResult(page, "J3.1", "J3.1");
  520. await page.locator("#detail-content").getByText("FPGA 专用 JTAG 时钟输入", {exact: false}).first().waitFor();
  521. await page.screenshot({path: path.join(artifacts, "390x844-j3.png"), fullPage: true});
  522. await assertNoViewportOverflow(page);
  523. await assertHealthy(session);
  524. } finally {
  525. await session.context.close();
  526. }
  527. }
  528. async function adcCopyWorkflow(browser) {
  529. const data = clone(boardData);
  530. const con78 = data.touchpoints.find((item) => item.reference === "CON78");
  531. const pin = con78.pins.find((item) => item.number === "1");
  532. pin.reserved = false;
  533. pin.recommendation = {eligible: true, reasons: ["capability_match", "verified_fpga_path", "external_level_known"]};
  534. const runtime = {
  535. status: "pass",
  536. staleSources: [],
  537. recommendationsEnabled: true,
  538. adcCopyEnabled: true,
  539. };
  540. const session = await createPage(browser, {width: 1366, height: 768}, {data, runtime});
  541. const {page} = session;
  542. try {
  543. await selectSearchResult(page, "CON78.1", "CON78.1");
  544. const input = page.getByLabel("RTL 端口名");
  545. assert.equal(await input.isEnabled(), true);
  546. await input.fill("uart2_tx");
  547. await page.locator("#detail-content").getByRole("button", {name: "复制 ADC 片段", exact: true}).click();
  548. await page.locator("#detail-content .copy-status").getByText("ADC 片段已复制", {exact: true}).waitFor();
  549. const clipboard = await page.evaluate(() => navigator.clipboard.readText());
  550. assert.equal(clipboard, "set_pin_assignment { uart2_tx } { LOCATION = M10; IOSTANDARD = LVCMOS33; }");
  551. await assertHealthy(session);
  552. } finally {
  553. await session.context.close();
  554. }
  555. }
  556. async function staleWorkflow(browser) {
  557. const runtime = {
  558. status: "stale_sources",
  559. staleSources: ["sha256_mismatch:inventory"],
  560. recommendationsEnabled: false,
  561. adcCopyEnabled: false,
  562. };
  563. const session = await createPage(browser, {width: 1366, height: 768}, {runtime});
  564. const {page} = session;
  565. try {
  566. await page.getByText("来源已变化", {exact: true}).waitFor();
  567. await page.locator("#candidate-tab").click();
  568. await page.locator("#candidate-content").getByText("源文件状态不是当前值,选脚推荐已关闭。", {exact: true}).waitFor();
  569. await page.screenshot({path: path.join(artifacts, "stale-state.png"), fullPage: true});
  570. await assertHealthy(session);
  571. } finally {
  572. await session.context.close();
  573. }
  574. }
  575. (async () => {
  576. const launchOptions = {headless: true, args: launchArgs};
  577. if (executablePath) launchOptions.executablePath = executablePath;
  578. const browser = await chromium.launch(launchOptions);
  579. try {
  580. const layoutRounds = [];
  581. for (const [viewport, name] of [[{width: 1920, height: 1080}, "1920x1080"], [{width: 1912, height: 948}, "1912x948"]]) {
  582. await desktopWorkflow(browser, viewport, name);
  583. layoutRounds.push({name, round: 1, status: "pass"});
  584. }
  585. fs.writeFileSync(
  586. path.join(artifacts, "layout-rounds.json"),
  587. JSON.stringify({rounds: layoutRounds, note: "One complete desktop workflow per viewport; mobile, mocked ADC copy and mocked stale-status workflows run separately"}, null, 2),
  588. );
  589. await mobileWorkflow(browser);
  590. await adcCopyWorkflow(browser);
  591. await staleWorkflow(browser);
  592. process.stdout.write(`Playwright board-viewer E2E passed. Artifacts: ${artifacts}\n`);
  593. } finally {
  594. await browser.close();
  595. }
  596. })().catch((error) => {
  597. console.error(error);
  598. process.exit(1);
  599. });