const assert = require("node:assert/strict"); const fs = require("node:fs"); const {createHash} = require("node:crypto"); const path = require("node:path"); const {chromium} = require(path.resolve(__dirname, "../../tools/board-viewer/node_modules/playwright")); const root = path.resolve(__dirname, "../.."); const baseUrl = process.env.BOARD_VIEWER_URL || "http://127.0.0.1:8765"; const targetUrl = new URL(baseUrl); // This suite exercises the MRDIMM fixture, while the app defaults to 6400 V2. targetUrl.searchParams.set("version", "v1_2"); const origin = targetUrl.origin; const artifacts = process.env.BOARD_VIEWER_E2E_ARTIFACTS || path.resolve(process.env.TEMP || root, "board-viewer-e2e"); const schematicPdfUrl = new URL("/schematics/FCB_FPGA+MCU0611.pdf", origin).href; const schematicPdfFile = path.join(root, "reference/original/schematics/FCB_FPGA+MCU0611.pdf"); const pdfResourceEvidence = []; const executablePath = process.env.BOARD_VIEWER_BROWSER || undefined; const launchArgs = String(process.env.BOARD_VIEWER_BROWSER_ARGS || "") .split(/\s+/) .filter(Boolean); if (launchArgs.length === 0 && process.platform === "linux") { launchArgs.push("--disable-gpu", "--disable-dev-shm-usage", "--no-sandbox"); } const boardData = JSON.parse(fs.readFileSync(path.join(root, "tools/board-viewer/generated/board-data.json"), "utf8")); const candidateExpectation = JSON.parse( fs.readFileSync(path.join(root, "tests/board_viewer/fixtures/candidate_count_expectation.json"), "utf8"), ); for (const [file, expected] of [ ["tools/board-viewer/generated/board-data.json", candidateExpectation.bound_to.board_data_sha256], ["tools/board-viewer/generated/build-info.json", candidateExpectation.bound_to.build_info_sha256], ]) { const actual = createHash("sha256").update(fs.readFileSync(path.join(root, file))).digest("hex"); assert.equal(actual, expected, `stale candidate expectation: ${file}`); } const frontTouchpoints = boardData.touchpoints.filter((item) => (item.side || "front") === "front"); const expectedHotspotCount = frontTouchpoints.length; // Desktop checks explicitly turn on SH and SVG mode before inspecting pin DOM. const expectedPinCount = frontTouchpoints.reduce((total, item) => total + item.pins.length, 0); fs.mkdirSync(artifacts, {recursive: true}); function clone(value) { return JSON.parse(JSON.stringify(value)); } async function createPage(browser, viewport, options = {}) { const context = await browser.newContext({ viewport, permissions: ["clipboard-read", "clipboard-write"], locale: "zh-CN", }); const consoleErrors = []; const requestFailures = []; const pdfFrameAborts = []; const badResponses = []; const page = await context.newPage(); page.on("console", (message) => { if (message.type() === "error") consoleErrors.push(message.text()); }); page.on("requestfailed", (request) => { const error = request.failure()?.errorText; if (request.url() === schematicPdfUrl && error === "net::ERR_ABORTED" && request.resourceType() === "document" && request.isNavigationRequest()) { let frame; try { frame = request.frame(); } catch { /* Keep unbound failures strict. */ } if (frame && frame !== page.mainFrame()) { pdfFrameAborts.push({frame, url: request.url(), error}); return; } } requestFailures.push(`${request.url()}: ${error}`); }); page.on("response", (response) => { if (response.status() >= 400) badResponses.push(`${response.status()} ${response.url()}`); }); await page.route("**/*", async (route) => { const url = new URL(route.request().url()); if (url.origin !== origin) { await route.abort("blockedbyclient"); return; } if (options.data && url.pathname === "/generated/board-data.json") { await route.fulfill({status: 200, contentType: "application/json", body: JSON.stringify(options.data)}); return; } if (options.runtime && url.pathname === "/api/status") { await route.fulfill({status: 200, contentType: "application/json", body: JSON.stringify(options.runtime)}); return; } await route.continue(); }); await page.goto(targetUrl.href, {waitUntil: "networkidle"}); await page.waitForFunction( (count) => document.querySelectorAll(".hotspot").length === count, expectedHotspotCount, ); assert.equal(await page.locator("#board-version-select").inputValue(), "v1_2"); return {context, page, consoleErrors, requestFailures, pdfFrameAborts, badResponses}; } async function assertCjkFontLayout(page) { const probe = await page.evaluate(async () => { await document.fonts.ready; const canvas = document.createElement("canvas"); const ctx = canvas.getContext("2d"); const sample = "电阻网络背面冲突"; const fonts = [ "Noto Sans CJK SC", "Noto Sans SC", "Source Han Sans SC", "Microsoft YaHei UI", "Microsoft YaHei", "PingFang SC", "sans-serif", ]; const measurements = []; for (const font of fonts) { ctx.font = `24px "${font}"`; const width = ctx.measureText(sample).width; measurements.push({font, width}); } // This checks declared font fallback and layout width, not glyph availability. // Screenshots remain the evidence for actual rendered CJK glyphs. ctx.font = '24px "Noto Sans CJK SC", "Noto Sans SC", "Microsoft YaHei", sans-serif'; const stacked = ctx.measureText(sample).width; const ascii = ctx.measureText("ABCDEFGH").width; const bodyFont = getComputedStyle(document.body).fontFamily; return {measurements, stacked, ascii, bodyFont, sample}; }); assert.ok(probe.stacked > probe.ascii * 0.9, `CJK text layout width too small: ${JSON.stringify(probe)}`); assert.ok( /Noto Sans CJK SC|Noto Sans SC|Source Han Sans SC|Microsoft YaHei|PingFang SC/i.test(probe.bodyFont), `body font-family missing CJK fallback: ${probe.bodyFont}`, ); // Canvas check: Chinese sample must render wider than 8 ASCII letters roughly. assert.ok(probe.stacked > 80, `CJK canvas text layout width: ${probe.stacked}`); return probe; } async function assertResistorPadUsesRealGeometry(page) { const info = await page.evaluate(() => { const markers = [...document.querySelectorAll(".resistor-pad-marker")]; return markers.map((node) => { const tag = node.tagName.toLowerCase(); if (tag === "circle") { return {tag, r: Number(node.getAttribute("r") || 0)}; } if (tag === "ellipse") { return { tag, rx: Number(node.getAttribute("rx") || 0), ry: Number(node.getAttribute("ry") || 0), }; } if (tag === "rect") { return { tag, width: Number(node.getAttribute("width") || 0), height: Number(node.getAttribute("height") || 0), }; } // marker may be nested in const rect = node.querySelector?.("rect.resistor-pad-marker") || node; return { tag: rect.tagName.toLowerCase(), width: Number(rect.getAttribute("width") || 0), height: Number(rect.getAttribute("height") || 0), parent: node.parentElement?.tagName?.toLowerCase() || "", }; }); }); assert.ok(info.length >= 1, "expected resistor pad markers"); for (const item of info) { assert.notEqual(item.tag, "circle", `pad marker must not be oversized circle: ${JSON.stringify(item)}`); if (item.tag === "rect") { assert.ok(item.width > 0 && item.width < 2.5, `pad width implausible: ${item.width}`); assert.ok(item.height > 0 && item.height < 2.5, `pad height implausible: ${item.height}`); } } } async function assertHealthy(session) { await session.page.waitForTimeout(50); assert.deepEqual(session.consoleErrors, [], `console errors: ${session.consoleErrors.join("\n")}`); assert.deepEqual(session.requestFailures, [], `request failures: ${session.requestFailures.join("\n")}`); assert.deepEqual(session.badResponses, [], `bad responses: ${session.badResponses.join("\n")}`); // Chromium may abort an embedded PDF navigation in headless mode. Keep only // this exact iframe/document abort separate and verify the actual full PDF. for (const failure of session.pdfFrameAborts) { const element = await failure.frame.frameElement(); assert.equal(await element.evaluate((node) => node.matches("#schematic-content iframe.pdf-viewer-frame")), true); const frameSrc = await element.getAttribute("src"); assert.equal(new URL(frameSrc, session.page.url()).href, schematicPdfUrl); } const response = await session.context.request.get(schematicPdfUrl, {maxRedirects: 0}); assert.equal(response.status(), 200, `PDF HTTP status: ${response.status()}`); const contentType = response.headers()["content-type"] || ""; assert.match(contentType, /^application\/pdf(?:;|$)/i); const body = await response.body(); assert.equal(body.subarray(0, 5).toString("ascii"), "%PDF-"); const digest = createHash("sha256").update(body).digest("hex"); const expectedDigest = createHash("sha256").update(fs.readFileSync(schematicPdfFile)).digest("hex"); assert.equal(digest, expectedDigest, "served PDF bytes differ from the server-mapped source file"); pdfResourceEvidence.push({ url: schematicPdfUrl, viewport: session.page.viewportSize(), status: response.status(), contentType, bytes: body.length, sha256: digest, subframeNavigationAborts: session.pdfFrameAborts.map(({url, error}) => ({url, error})), visualRendering: "NOT_ASSERTED; full HTTP PDF bytes checked separately from headless iframe navigation", }); fs.writeFileSync(path.join(artifacts, "pdf-resource-evidence.json"), JSON.stringify(pdfResourceEvidence, null, 2)); } async function assertNoViewportOverflow(page) { const metrics = await page.evaluate(() => { const viewport = {width: window.innerWidth, height: window.innerHeight}; const topbar = document.querySelector(".topbar").getBoundingClientRect(); const board = document.querySelector(".board-pane").getBoundingClientRect(); const boardViewport = document.querySelector("#board-viewport").getBoundingClientRect(); const footer = document.querySelector(".board-footer").getBoundingClientRect(); const panel = document.querySelector("#detail-panel").getBoundingClientRect(); return { viewport, scrollWidth: document.documentElement.scrollWidth, scrollHeight: document.documentElement.scrollHeight, topbar: {left: topbar.left, right: topbar.right, top: topbar.top, bottom: topbar.bottom}, board: {left: board.left, right: board.right, top: board.top, bottom: board.bottom}, boardViewport: {top: boardViewport.top, bottom: boardViewport.bottom, height: boardViewport.height}, footer: {top: footer.top, bottom: footer.bottom, height: footer.height}, panel: {left: panel.left, right: panel.right, top: panel.top, bottom: panel.bottom}, loadingDisplay: getComputedStyle(document.querySelector("#board-loading")).display, }; }); assert.ok(metrics.scrollWidth <= metrics.viewport.width + 1, JSON.stringify(metrics)); assert.ok(metrics.scrollHeight <= metrics.viewport.height + 1, JSON.stringify(metrics)); assert.ok(metrics.topbar.left >= -1 && metrics.topbar.right <= metrics.viewport.width + 1, JSON.stringify(metrics)); assert.ok(metrics.board.left >= -1 && metrics.board.right <= metrics.viewport.width + 1, JSON.stringify(metrics)); assert.ok(metrics.panel.left >= -1 && metrics.panel.right <= metrics.viewport.width + 1, JSON.stringify(metrics)); assert.equal(metrics.loadingDisplay, "none", JSON.stringify(metrics)); if (metrics.viewport.width > 860) { assert.ok(metrics.boardViewport.height > 400, JSON.stringify(metrics)); assert.ok(metrics.footer.height <= 34, JSON.stringify(metrics)); assert.ok(metrics.footer.bottom >= metrics.viewport.height - 1, JSON.stringify(metrics)); } } async function selectSearchResult(page, query, expectedKey) { const search = page.locator("#board-search"); await search.fill(query); const result = page.locator(".search-result").filter({hasText: expectedKey}).first(); await result.waitFor({state: "visible"}); await result.click(); } async function connectorGrid(page) { return page.locator(".connector-grid-row").evaluateAll((rows) => rows.map((row) => Array.from(row.querySelectorAll(".connector-contact")).map((pin) => pin.textContent.trim())), ); } async function assertRenderedPinPositionsMatchGeneratedData(page) { const rendered = await page.locator(".pin-group").evaluateAll((groups) => Object.fromEntries( groups.map((group) => { const dot = group.querySelector(".pin-dot"); const rect = dot.tagName.toLowerCase() === "rect"; const x = rect ? Number(dot.getAttribute("x")) + Number(dot.getAttribute("width")) / 2 : Number(dot.getAttribute("cx")); const y = rect ? Number(dot.getAttribute("y")) + Number(dot.getAttribute("height")) / 2 : Number(dot.getAttribute("cy")); return [group.dataset.pinId, {x, y}]; }), )); const expected = Object.fromEntries(frontTouchpoints.flatMap((touchpoint) => touchpoint.pins.map((pin) => [pin.id, pin.view_position]), )); assert.equal(Object.keys(rendered).length, expectedPinCount); assert.deepEqual(Object.keys(rendered).sort(), Object.keys(expected).sort()); for (const [id, point] of Object.entries(expected)) { assert.ok(Math.abs(rendered[id].x - point.x) < 1e-9, `${id} x: ${rendered[id].x} != ${point.x}`); assert.ok(Math.abs(rendered[id].y - point.y) < 1e-9, `${id} y: ${rendered[id].y} != ${point.y}`); } } async function desktopWorkflow(browser, viewport, name) { const session = await createPage(browser, viewport); const {page} = session; try { await assertCjkFontLayout(page); await page.getByText("数据已校验", {exact: true}).waitFor(); assert.equal(await page.locator(".hotspot").count(), expectedHotspotCount); assert.equal(await page.locator("#board-svg").evaluate((node) => node.classList.contains("perf-ultra")), true); assert.equal(await page.locator(".pin-group").count(), 0); await page.locator("#perf-mode-toggle").click(); await page.locator("#filter-sh").check(); await page.waitForFunction((count) => document.querySelectorAll(".pin-group").length === count, expectedPinCount); assert.equal(await page.locator("#board-svg").evaluate((node) => node.classList.contains("perf-ultra")), false); assert.equal(await page.locator(".pin-group").count(), expectedPinCount); await assertRenderedPinPositionsMatchGeneratedData(page); assert.equal(await page.locator(".pin-group").first().getAttribute("tabindex"), "0"); assert.equal(await page.locator("#photo-layer").isDisabled(), true); assert.equal(await page.locator('#layer-controls input[value="copper"]').isChecked(), true); assert.equal(await page.locator("#layer-copper").isVisible(), true); assert.equal(await page.locator("#layer-mask").getAttribute("href"), "/generated/board-mask-edge.svg"); await assertNoViewportOverflow(page); await page.screenshot({path: path.join(artifacts, `${name}-initial.png`), fullPage: true}); const con18 = page.locator('.hotspot[data-reference="CON18"]'); const con18Box = await con18.boundingBox(); assert.ok(con18Box); // The current SVG keeps connector keyboard targets; pin pointer selection // below separately exercises the shared WASM hit-testing path. await con18.focus(); await con18.press("Enter"); await page.locator(".detail-reference").getByText("CON18", {exact: true}).waitFor(); await page.locator("#detail-content").getByText("板正面接触针排列", {exact: true}).waitFor(); await page.locator("#detail-content").getByText("板正面俯视", {exact: false}).waitFor(); await page.locator("#detail-content").getByText("线缆端或对接面可能是镜像", {exact: false}).waitFor(); assert.deepEqual(await connectorGrid(page), [ ["13", "11", "9", "7", "5", "3", "1"], ["14", "12", "10", "8", "6", "4", "2"], ]); assert.equal(await page.locator('.pin-row[data-pad-role="contact"]').count(), 14); await page.locator("#detail-content").getByText("上", {exact: true}).first().waitFor(); await page.locator("#detail-content").getByText("下", {exact: true}).first().waitFor(); await selectSearchResult(page, "CON23", "CON23"); assert.deepEqual(await connectorGrid(page), [["5", "1"], ["6", "2"], ["7", "3"], ["8", "4"]]); await selectSearchResult(page, "CON8", "CON8"); assert.deepEqual(await connectorGrid(page), [["8"], ["7"], ["6"], ["5"], ["4"], ["3"], ["2"], ["1"]]); await selectSearchResult(page, "J3", "J3"); await page.locator("#detail-content").getByText("EF2L45BG256B FPGA JTAG 调试/配置接口(专用配置脚)", {exact: true}).waitFor(); await page.locator("#detail-content .category-tag").filter({hasText: /^JTAG \/ SWD · /}).waitFor(); assert.deepEqual(await connectorGrid(page), [ ["1", "2"], ["3", "4"], ["5", "6"], ["7", "8"], ["9", "10"], ]); const j3Pin1Primary = await page.locator('.pin-row[data-pin="1"] .pin-primary > span').allTextContents(); assert.match(j3Pin1Primary[0], /TCK/); assert.match(await page.locator('.pin-row[data-pin="1"] .pin-net').textContent(), /原始网络.*N9532014/); await selectSearchResult(page, "J3.1", "J3.1"); await page.locator("#detail-content").getByText("FPGA 专用 JTAG 时钟输入", {exact: false}).first().waitFor(); await page.locator("#detail-content").getByText("U3.A7 专用 TCK", {exact: true}).waitFor(); await page.locator("#detail-content").getByText("R63 22R 串联", {exact: true}).first().waitFor(); await page.locator("#detail-content").getByText("不要在 RTL 顶层声明", {exact: false}).waitFor(); await page.locator("#detail-content").getByText("专用配置脚不使用用户 ADC 约束", {exact: true}).waitFor(); assert.equal(await page.getByLabel("RTL 端口名").count(), 0); await page.screenshot({path: path.join(artifacts, `${name}-j3.png`), fullPage: true}); await assertNoViewportOverflow(page); await selectSearchResult(page, "J3.4", "J3.4"); await page.locator("#detail-content").getByText("不是给板子供电", {exact: false}).first().waitFor(); await page.locator("#detail-content").getByText("R61 0R", {exact: false}).first().waitFor(); await page.locator("#detail-content").getByText("不要通过 VREF 反向给板子供电", {exact: false}).waitFor(); await selectSearchResult(page, "J3.6", "J3.6"); await page.locator("#detail-content").getByText("不能把 NC 当作备用 GPIO", {exact: false}).waitFor(); await selectSearchResult(page, "J11", "J11"); await page.locator("#detail-content").getByText("M3 安装孔(非电气接口)", {exact: true}).waitFor(); await selectSearchResult(page, "J8", "J8"); await page.locator(".detail-reference").getByText("J8", {exact: true}).waitFor(); await selectSearchResult(page, "PL2001", "PL2001"); await page.locator("#detail-content .category-tag").filter({hasText: /^电源 \/ 测点 · /}).waitFor(); await page.locator("#detail-content").getByText("+5V 开关电源电感(非连接器)", {exact: true}).waitFor(); const beforeZoom = await page.locator("#board-svg").getAttribute("viewBox"); await page.locator("#zoom-in").click(); await page.waitForFunction((before) => document.querySelector("#board-svg").getAttribute("viewBox") !== before, beforeZoom); const afterZoom = await page.locator("#board-svg").getAttribute("viewBox"); assert.notEqual(afterZoom, beforeZoom); await selectSearchResult(page, "CON78", "CON78"); assert.equal(await page.locator('.pin-row[data-pad-role="contact"]').count(), 4); assert.equal(await page.locator('.pin-row[data-pad-role="shield"]').count(), 2); assert.equal(await page.locator('.pin-group[data-reference="CON78"][data-pin="5"]').getAttribute("data-pad-role"), "shield"); await page.locator("#detail-content").getByText("屏蔽固定焊盘", {exact: true}).first().waitFor(); await selectSearchResult(page, "CON78.1", "CON78.1"); assert.equal(await page.locator('.pin-group[data-reference="CON78"][data-pin="1"]').getAttribute("tabindex"), "0"); await page.locator("#detail-content").getByText("U23 TRSF3232EIPWR", {exact: true}).first().waitFor(); await page.locator(".pin-detail .detail-facts").getByText("FPGA U3.M10 (host_rs232_tx (UART2_TX))", {exact: true}).waitFor(); await page.locator(".pin-detail").getByText("RS232_TX2", {exact: true}).first().waitFor(); await page.locator("#detail-content").getByText("编程结论", {exact: true}).waitFor(); await page.locator("#detail-content").getByText("FPGA 输出", {exact: false}).waitFor(); await page.locator("#detail-content").getByText("连接到对端设备的接收端(RX)。", {exact: true}).waitFor(); await page.locator("#detail-content").getByText("不能直接接 3.3V TTL/CMOS 串口", {exact: false}).waitFor(); await page.locator("#detail-content").getByText("LOCATION = M10", {exact: true}).waitFor(); await page.locator("#detail-content").getByText("IOSTANDARD = LVCMOS33", {exact: true}).waitFor(); const groundPin = page.locator('.pin-group[data-reference="CON78"][data-pin="3"] .pin-dot'); await page.waitForTimeout(250); // let the existing 220 ms focus animation finish const pinBox = await groundPin.boundingBox(); assert.ok(pinBox); const groundPoint = {x: pinBox.x + pinBox.width / 2, y: pinBox.y + pinBox.height / 2}; await page.mouse.move(groundPoint.x, groundPoint.y); await page.getByRole("tooltip").getByText("CON78.3", {exact: true}).waitFor(); await page.mouse.click(groundPoint.x, groundPoint.y); await page.locator(".pin-detail").getByText("CON78.3", {exact: false}).first().waitFor(); assert.equal(await page.locator(".net-highlight").count(), 0); await page.keyboard.down("Control"); try { await page.mouse.click(groundPoint.x, groundPoint.y); } finally { await page.keyboard.up("Control"); } assert.ok(await page.locator(".net-highlight").count() > 20); await selectSearchResult(page, "CON12.3", "CON12.3"); await page.locator(".detail-reference").getByText("CON12", {exact: true}).waitFor(); await page.locator(".pin-detail").getByText("EX_GPIO3", {exact: false}).first().waitFor(); await page.locator(".pin-detail").getByText("limit_lower_raw[1]", {exact: false}).first().waitFor(); await page.locator(".pin-detail .detail-facts").getByText("FPGA U3.C8 (limit_lower_raw[1] (LS2))", {exact: true}).waitFor(); await selectSearchResult(page, "CON31.4", "CON31.4"); await page.locator("#detail-content").getByText("开集电极", {exact: false}).first().waitFor(); await page.locator("#detail-content").getByText("FPGA high", {exact: false}).first().waitFor(); await page.locator("#detail-content").getByText("LOCATION = E10", {exact: true}).waitFor(); await selectSearchResult(page, "CON54.1", "CON54.1"); await page.locator("#detail-content").getByText("open-drain", {exact: false}).first().waitFor(); await page.locator("#detail-content").getByText("开漏", {exact: false}).first().waitFor(); await page.locator("#detail-content").getByText("LOCATION = B14", {exact: true}).waitFor(); await selectSearchResult(page, "CON53.1", "CON53.1"); await page.locator("#detail-content").getByText("远端温度二极管", {exact: false}).first().waitFor(); await page.locator("#detail-content").getByText("不要为 CON53.1 声明 FPGA GPIO", {exact: false}).waitFor(); await selectSearchResult(page, "CON2.5", "CON2.5"); await page.locator("#detail-content").getByText("板端电源输入", {exact: false}).first().waitFor(); await page.locator("#detail-content").getByText("CON2.5 +12V_VIN", {exact: false}).first().waitFor(); await selectSearchResult(page, "J25.2", "J25.2"); await page.locator("#detail-content").getByText("GD32F303CGT6", {exact: false}).first().waitFor(); await page.locator("#detail-content").getByText("SWCLK", {exact: false}).first().waitFor(); await page.locator("#detail-content").getByText("U27.37", {exact: false}).first().waitFor(); await page.locator("#detail-content").getByText("不对应 FPGA RTL 或 ADC", {exact: false}).waitFor(); await page.locator("#candidate-tab").click(); for (const capability of ["pwm", "gpio", "uart_tx"]) { await page.locator("#capability-select").selectOption(capability); const keys = await page.locator(".candidate-row .candidate-key").allTextContents(); const pinKeys = keys.map((key) => key.split(" · ")[0]); assert.equal(pinKeys.length, candidateExpectation.candidate_counts[capability]); assert.deepEqual(pinKeys.sort(), [...candidateExpectation.candidate_keys[capability]].sort()); if (!pinKeys.length) { await page.locator("#candidate-content").getByText("没有满足全部证据条件的候选", {exact: true}).waitFor(); } } await page.locator("#detail-tab").click(); await page.locator("#board-search").fill("does-not-exist"); await page.locator("#search-results").getByText("没有匹配的座子、电阻或针脚", {exact: true}).waitFor(); // Pass I: resistor search focuses resistor entity with value/net detail. await selectSearchResult(page, "R674", "R674"); await page.locator(".detail-reference").getByText("R674", {exact: true}).waitFor(); await page.locator("#detail-content .category-tag").getByText("电阻", {exact: true}).waitFor(); await page.locator("#detail-content .side-tag").getByText("背面", {exact: true}).waitFor(); assert.equal(await page.locator('#side-controls input[value="back"]').isChecked(), true); assert.equal(await page.locator("#board-svg").getAttribute("data-side"), "back"); assert.equal( await page.locator("#layer-copper").getAttribute("href"), "/generated/board-copper-back.svg", ); await page.locator('.hotspot-resistor[data-reference="R674"]').waitFor(); await page.locator("#detail-content").getByText("两侧网络", {exact: true}).waitFor(); await page.locator("#detail-content").getByText("PUL1", {exact: false}).first().waitFor(); await page.locator("#detail-content").getByText("证据与冲突", {exact: true}).waitFor(); await page.locator("#detail-content").getByText("原理图声明与当前 PCB 索引冲突", {exact: false}).first().waitFor(); await page.locator("#back-view-tip").waitFor(); await page.locator("#detail-content").getByText("阻值覆盖", {exact: false}).first().waitFor(); await assertCjkFontLayout(page); await page.screenshot({path: path.join(artifacts, `${name}-r674.png`), fullPage: true}); await selectSearchResult(page, "R674.1", "R674.1"); await page.locator(".detail-reference").getByText("R674", {exact: true}).waitFor(); await page.locator("#selection-readout").getByText("R674.1", {exact: false}).waitFor(); await assertResistorPadUsesRealGeometry(page); await page.screenshot({path: path.join(artifacts, `${name}-r674-pad.png`), fullPage: true}); await selectSearchResult(page, "120R", "R806"); await page.locator(".detail-reference").getByText("R806", {exact: true}).waitFor(); await page.screenshot({path: path.join(artifacts, `${name}-120r.png`), fullPage: true}); await page.locator("#board-search").fill("0R"); await page.locator(".search-result").first().waitFor(); const zeroKeys = await page.locator(".search-result .result-key").allTextContents(); assert.ok(zeroKeys.length >= 1, "0R should find fitted/unknown zero-ohm resistors"); await page.screenshot({path: path.join(artifacts, `${name}-0r.png`), fullPage: true}); await page.locator("#board-search").fill("4k7"); const expected4k7 = new Set(boardData.resistors.filter((item) => item.value_ohms === 4700).map((item) => item.reference)); if (expected4k7.size) { await page.locator(".search-result").first().waitFor(); const keys = await page.locator(".search-result .result-key").allTextContents(); assert.ok(keys.length > 0); assert.ok(keys.every((key) => expected4k7.has(key)), `4k7 returned another value: ${keys}`); } else { await page.locator(".empty-search").waitFor(); const emptyOrCoverage = await page.locator(".empty-search").textContent(); assert.match(String(emptyOrCoverage || ""), /当前索引中没有此阻值|阻值覆盖/); } await page.locator("#board-search").fill("R7"); await page.locator(".search-result").first().waitFor(); const r7Keys = await page.locator(".search-result .result-key").allTextContents(); assert.equal(r7Keys[0], "R7"); assert.ok(!r7Keys.some((key) => /FPGA|ball/i.test(key))); await page.locator("#board-search").fill("R12"); await page.locator(".search-result .result-key").getByText("R12", {exact: true}).first().waitFor(); const r12Keys = await page.locator(".search-result .result-key").allTextContents(); assert.ok(!r12Keys.includes("R1225")); await page.locator("#board-search").fill("ball:R7"); // May be empty if no ball R7 on product board; just ensure R7 resistor is not sole forced hit. await page.waitForTimeout(80); await selectSearchResult(page, "PUL1", "R674"); await page.locator("#detail-content").getByText("PUL1", {exact: false}).first().waitFor(); await page.screenshot({path: path.join(artifacts, `${name}-pul1.png`), fullPage: true}); await selectSearchResult(page, "CON104.2", "CON104.2"); assert.equal(await page.locator('#side-controls input[value="front"]').isChecked(), true); assert.equal(await page.locator("#board-svg").getAttribute("data-side"), "front"); assert.equal( await page.locator("#layer-copper").getAttribute("href"), "/generated/board-copper.svg", ); await page.locator("#detail-content").getByText("关联电阻", {exact: false}).first().waitFor(); await page.locator(".pin-row").filter({hasText: "R674"}).first().click(); await page.locator(".detail-reference").getByText("R674", {exact: true}).waitFor(); assert.equal(await page.locator('#side-controls input[value="back"]').isChecked(), true); assert.equal(await page.locator("#board-svg").getAttribute("data-side"), "back"); await selectSearchResult(page, "R63", "R63"); await page.locator(".detail-reference").getByText("R63", {exact: true}).waitFor(); await page.locator("#detail-content .category-tag").getByText("电阻", {exact: true}).waitFor(); await page.screenshot({path: path.join(artifacts, `${name}-selected.png`), fullPage: true}); await assertNoViewportOverflow(page); await assertHealthy(session); } finally { await session.context.close(); } } async function mobileWorkflow(browser) { const session = await createPage(browser, {width: 390, height: 844}); const {page} = session; try { await assertNoViewportOverflow(page); await page.screenshot({path: path.join(artifacts, "390x844-initial.png"), fullPage: true}); assert.equal(await page.locator("#app").evaluate((node) => node.classList.contains("detail-collapsed")), true); await selectSearchResult(page, "CON78", "CON78"); assert.equal(await page.locator("#app").evaluate((node) => node.classList.contains("detail-collapsed")), false); await page.locator(".detail-reference").getByText("CON78", {exact: true}).waitFor(); await page.screenshot({path: path.join(artifacts, "390x844-selected.png"), fullPage: true}); await assertNoViewportOverflow(page); await selectSearchResult(page, "J3.1", "J3.1"); await page.locator("#detail-content").getByText("FPGA 专用 JTAG 时钟输入", {exact: false}).first().waitFor(); await page.screenshot({path: path.join(artifacts, "390x844-j3.png"), fullPage: true}); await assertNoViewportOverflow(page); await assertHealthy(session); } finally { await session.context.close(); } } async function adcCopyWorkflow(browser) { const data = clone(boardData); const con78 = data.touchpoints.find((item) => item.reference === "CON78"); const pin = con78.pins.find((item) => item.number === "1"); pin.reserved = false; pin.recommendation = {eligible: true, reasons: ["capability_match", "verified_fpga_path", "external_level_known"]}; const runtime = { status: "pass", staleSources: [], recommendationsEnabled: true, adcCopyEnabled: true, }; const session = await createPage(browser, {width: 1366, height: 768}, {data, runtime}); const {page} = session; try { await selectSearchResult(page, "CON78.1", "CON78.1"); const input = page.getByLabel("RTL 端口名"); assert.equal(await input.isEnabled(), true); await input.fill("uart2_tx"); await page.locator("#detail-content").getByRole("button", {name: "复制 ADC 片段", exact: true}).click(); await page.locator("#detail-content .copy-status").getByText("ADC 片段已复制", {exact: true}).waitFor(); const clipboard = await page.evaluate(() => navigator.clipboard.readText()); assert.equal(clipboard, "set_pin_assignment { uart2_tx } { LOCATION = M10; IOSTANDARD = LVCMOS33; }"); await assertHealthy(session); } finally { await session.context.close(); } } async function staleWorkflow(browser) { const runtime = { status: "stale_sources", staleSources: ["sha256_mismatch:inventory"], recommendationsEnabled: false, adcCopyEnabled: false, }; const session = await createPage(browser, {width: 1366, height: 768}, {runtime}); const {page} = session; try { await page.getByText("来源已变化", {exact: true}).waitFor(); await page.locator("#candidate-tab").click(); await page.locator("#candidate-content").getByText("源文件状态不是当前值,选脚推荐已关闭。", {exact: true}).waitFor(); await page.screenshot({path: path.join(artifacts, "stale-state.png"), fullPage: true}); await assertHealthy(session); } finally { await session.context.close(); } } (async () => { const launchOptions = {headless: true, args: launchArgs}; if (executablePath) launchOptions.executablePath = executablePath; const browser = await chromium.launch(launchOptions); try { const layoutRounds = []; for (const [viewport, name] of [[{width: 1920, height: 1080}, "1920x1080"], [{width: 1912, height: 948}, "1912x948"]]) { await desktopWorkflow(browser, viewport, name); layoutRounds.push({name, round: 1, status: "pass"}); } fs.writeFileSync( path.join(artifacts, "layout-rounds.json"), JSON.stringify({rounds: layoutRounds, note: "One complete desktop workflow per viewport; mobile, mocked ADC copy and mocked stale-status workflows run separately"}, null, 2), ); await mobileWorkflow(browser); await adcCopyWorkflow(browser); await staleWorkflow(browser); process.stdout.write(`Playwright board-viewer E2E passed. Artifacts: ${artifacts}\n`); } finally { await browser.close(); } })().catch((error) => { console.error(error); process.exit(1); });