playwright_e2e.cjs 29 KB

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