import { connectorPinGroups, displayBounds, displayPoint, extractPathResistors, findCandidates, generateAdcSnippet, itemVisibleOnSide, sameNetMembers, sameNetPins, searchBoard, } from "./board-logic.mjs"; const SVG_NS = "http://www.w3.org/2000/svg"; const LAYER_ASSETS = { front: { mask: "/generated/board-mask-edge.svg", silk: "/generated/board-silkscreen.svg", copper: "/generated/board-copper.svg", }, back: { mask: "/generated/board-mask-edge-back.svg", silk: "/generated/board-silkscreen-back.svg", copper: "/generated/board-copper-back.svg", }, }; const state = { data: null, runtime: {status: "loading", recommendationsEnabled: false, adcCopyEnabled: false, staleSources: []}, categories: new Set(["CON", "J", "PL", "TP"]), boardSide: "front", selectedTouchpoint: null, selectedResistor: null, selectedPin: null, baseViewBox: null, viewBox: null, dragging: null, activeTab: "detail", searchResults: [], activeSearchIndex: -1, }; const dom = Object.fromEntries( [ "app", "app-status", "board-summary", "board-search", "search-results", "stale-banner", "category-filters", "side-controls", "layer-controls", "zoom-in", "zoom-out", "reset-view", "board-viewport", "board-svg", "board-loading", "board-tooltip", "hotspot-layer", "pin-layer", "net-layer", "selection-layer", "layer-mask", "layer-silk", "layer-copper", "layer-photo", "photo-control", "photo-layer", "photo-label", "visible-count", "zoom-readout", "selection-readout", "detail-panel", "detail-tab", "candidate-tab", "detail-content", "candidate-content", "candidate-list", "capability-select", "drawer-toggle", ].map((id) => [id, document.getElementById(id)]), ); function svgElement(name, attributes = {}) { const node = document.createElementNS(SVG_NS, name); for (const [key, value] of Object.entries(attributes)) node.setAttribute(key, String(value)); return node; } function element(name, className = "", content = null) { const node = document.createElement(name); if (className) node.className = className; if (content != null) node.textContent = String(content); return node; } function formatNumber(value, digits = 3) { const number = Number(value); return Number.isFinite(number) ? number.toFixed(digits).replace(/\.0+$|(?<=\.[0-9]*?)0+$/g, "") : "未知"; } function evidenceLabel(tier) { return { board_database: "板数据库原始值", cross_verified: "已交叉验证", name_inferred: "名称推断", unknown: "未知", }[tier] ?? "未知"; } function directionLabel(direction) { return { input: "输入", output: "输出", bidirectional: "双向", passive: "无源", unknown: "未知", }[direction] ?? direction ?? "未知"; } function activeLevelLabel(level) { return { high: "高电平有效", low: "低电平有效", rising_edge: "上升沿计步脉冲", state: "状态选择(非有效电平)", unknown: "未注明", }[level] ?? level ?? "未注明"; } function categoryLabel(category) { return {CON: "连接器", J: "J 类对象", PL: "PL 器件", TP: "测试点", R: "电阻"}[category] ?? category; } function touchpointKindLabel(touchpoint) { if (touchpoint?.connector) return touchpoint.category === "CON" ? "连接器" : "调试接口"; if (touchpoint?.category === "PL") return "电源器件"; if (touchpoint?.category === "J") { const pins = Array.isArray(touchpoint.pins) ? touchpoint.pins : []; if (pins.length && pins.every((pin) => pin.mechanical === true)) return "安装孔"; if (pins.some((pin) => pin.function_category === "manufacturing_mark")) return "制造标记"; } return categoryLabel(touchpoint?.category); } function padRoleLabel(role) { return { contact: "接触针", shield: "屏蔽固定焊盘", mechanical: "机械孔", unknown: "未分类焊盘", }[role] ?? "未分类焊盘"; } function touchpointPinSummary(touchpoint) { if (touchpoint.connector) { return `${touchpoint.connector.contact_count} 接触针 · ${touchpoint.connector.auxiliary_pad_count} 辅助焊盘`; } return `${touchpoint.pins.length} 针`; } function setStatus(kind, text) { dom["app-status"].className = `status-badge status-${kind}`; dom["app-status"].textContent = text; } function applyRuntimeStatus() { const runtime = state.runtime; if (runtime.status === "pass") { setStatus("pass", "数据已校验"); dom["stale-banner"].hidden = true; } else if (runtime.status === "stale_sources") { setStatus("stale", "来源已变化"); dom["stale-banner"].hidden = false; dom["stale-banner"].textContent = `源文件与生成时不一致:${(runtime.staleSources ?? []).join(",")}。选脚推荐与 ADC 复制已关闭。`; } else { setStatus("error", "资产不可用"); dom["stale-banner"].hidden = false; dom["stale-banner"].textContent = runtime.message || "生成资产未通过完整性校验。"; } } async function loadApplication() { try { const [dataResponse, statusResponse] = await Promise.all([ fetch("/generated/board-data.json", {cache: "no-store"}), fetch("/api/status", {cache: "no-store"}), ]); if (!dataResponse.ok) throw new Error(`板数据 HTTP ${dataResponse.status}`); if (!statusResponse.ok) throw new Error(`状态 HTTP ${statusResponse.status}`); state.data = await dataResponse.json(); if (state.data?.schema !== "board-viewer-data-v2" || !Array.isArray(state.data?.resistors)) { throw new Error("生成数据过旧或缺少 resistors[],请重新 generate(需要 board-viewer-data-v2)。"); } state.runtime = await statusResponse.json(); initializeBoard(); applyRuntimeStatus(); } catch (error) { state.runtime = { status: "error", recommendationsEnabled: false, adcCopyEnabled: false, staleSources: [], message: error instanceof Error ? error.message : String(error), }; applyRuntimeStatus(); dom["board-loading"].textContent = "板数据载入失败"; renderEmptyDetail("板数据不可用", state.runtime.message); } } function boardWidth() { return Number(state.data?.board?.view_box?.width) || 0; } function toDisplayPoint(point) { return displayPoint(point, boardWidth(), state.boardSide); } function toDisplayBounds(bounds) { return displayBounds(bounds, boardWidth(), state.boardSide); } function applyBoardSide() { const assets = LAYER_ASSETS[state.boardSide] || LAYER_ASSETS.front; dom["layer-mask"].setAttribute("href", assets.mask); dom["layer-silk"].setAttribute("href", assets.silk); dom["layer-copper"].setAttribute("href", assets.copper); const sideInput = dom["side-controls"]?.querySelector(`input[value="${state.boardSide}"]`); if (sideInput instanceof HTMLInputElement) sideInput.checked = true; dom["board-svg"].dataset.side = state.boardSide; const photoHidden = state.boardSide !== "front" || !state.data?.photo_overlay; if (dom["layer-photo"]) { dom["layer-photo"].hidden = photoHidden || !dom["photo-layer"]?.checked; } if (dom["photo-control"]) { dom["photo-control"].classList.toggle("disabled-control", state.boardSide !== "front"); if (dom["photo-layer"]) dom["photo-layer"].disabled = state.boardSide !== "front" || !state.data?.photo_overlay; } } function setBoardSide(side, {rerender = true} = {}) { const next = side === "back" ? "back" : "front"; if (state.boardSide === next) { if (rerender) applyBoardSide(); return false; } state.boardSide = next; applyBoardSide(); if (rerender) { renderBoardMarkers(); } return true; } function ensureItemSide(item) { const side = item?.side === "back" ? "back" : "front"; return setBoardSide(side, {rerender: false}); } function initializeBoard() { const {board, counts} = state.data; const width = Number(board.view_box.width); const height = Number(board.view_box.height); const padding = Math.max(height * 0.08, 1.2); state.baseViewBox = {x: -padding, y: -padding, width: width + padding * 2, height: height + padding * 2}; state.viewBox = {...state.baseViewBox}; state.boardSide = "front"; for (const image of [dom["layer-mask"], dom["layer-silk"], dom["layer-copper"], dom["layer-photo"]]) { image.setAttribute("x", "0"); image.setAttribute("y", "0"); image.setAttribute("width", String(width)); image.setAttribute("height", String(height)); } applyBoardSide(); const backResistors = (state.data.resistors ?? []).filter((item) => item.side === "back").length; dom["board-summary"].textContent = `${board.name} · ${counts.touchpoints} 座子 · ${counts.resistors ?? 0} 电阻(背 ${backResistors}) · ${counts.connector_contacts} 个 CON 接触针`; dom["board-loading"].hidden = true; updateViewBox(); renderBoardMarkers(); configurePhotoOverlay(); renderEmptyDetail( "未选择座子或电阻", `${counts.touchpoints} 个座子 · ${counts.resistors ?? 0} 个电阻 · ${counts.connector_contacts} 个 CON 接触针 · ${counts.connector_auxiliary_pads} 个 CON 辅助焊盘`, ); renderCandidates(); } function configurePhotoOverlay() { const overlay = state.data?.photo_overlay; if (!overlay) return; const matrix = Array.isArray(overlay.matrix) ? overlay.matrix : []; if (matrix.length !== 6 || !matrix.every(Number.isFinite)) return; const source = `/generated/${overlay.asset}`; const image = new Image(); image.addEventListener("load", () => { dom["layer-photo"].setAttribute("href", source); dom["layer-photo"].setAttribute("width", String(image.naturalWidth)); dom["layer-photo"].setAttribute("height", String(image.naturalHeight)); dom["layer-photo"].setAttribute("transform", `matrix(${matrix.join(" ")})`); dom["photo-layer"].disabled = false; dom["photo-control"].classList.remove("disabled-control"); dom["photo-control"].title = `已校准 ${overlay.control_point_count} 个控制点`; dom["photo-label"].textContent = "照片"; }); image.addEventListener("error", () => { dom["photo-control"].title = "照片资产载入失败"; dom["photo-label"].textContent = "照片不可用"; }); image.src = source; } function updateViewBox() { if (!state.viewBox) return; const {x, y, width, height} = state.viewBox; dom["board-svg"].setAttribute("viewBox", `${x} ${y} ${width} ${height}`); const ratio = state.baseViewBox.width / width; const pinsInteractive = ratio >= 1.8; dom["board-svg"].classList.toggle("pins-interactive", pinsInteractive); for (const group of dom["pin-layer"].querySelectorAll(".pin-group")) { group.setAttribute("tabindex", pinsInteractive ? "0" : "-1"); } dom["zoom-readout"].textContent = `${Math.round(ratio * 100)}%`; } function effectiveBounds(bounds, minimum = 3.2) { const width = Math.max(Number(bounds.width), minimum); const height = Math.max(Number(bounds.height), minimum); return { x: Number(bounds.x) - (width - Number(bounds.width)) / 2, y: Number(bounds.y) - (height - Number(bounds.height)) / 2, width, height, }; } function renderBoardMarkers() { dom["hotspot-layer"].replaceChildren(); dom["pin-layer"].replaceChildren(); if (!state.data) return; let visibleTouchpoints = 0; let visibleResistors = 0; for (const touchpoint of state.data.touchpoints) { if (!state.categories.has(touchpoint.category)) continue; if (!itemVisibleOnSide(touchpoint, state.boardSide)) continue; visibleTouchpoints += 1; const bounds = effectiveBounds(toDisplayBounds(touchpoint.view_bounds)); const hotspot = svgElement("rect", { x: bounds.x, y: bounds.y, width: bounds.width, height: bounds.height, rx: 0.45, class: `hotspot${state.selectedTouchpoint?.reference === touchpoint.reference ? " is-selected" : ""}`, tabindex: 0, role: "button", "aria-label": `${touchpoint.reference} ${touchpointKindLabel(touchpoint)} ${touchpointPinSummary(touchpoint)}`, "data-reference": touchpoint.reference, "data-side": touchpoint.side || "front", }); hotspot.addEventListener("pointerenter", (event) => showTouchpointTooltip(event, touchpoint)); hotspot.addEventListener("pointermove", positionTooltip); hotspot.addEventListener("pointerleave", hideTooltip); hotspot.addEventListener("focus", () => showTouchpointTooltip(null, touchpoint)); hotspot.addEventListener("blur", hideTooltip); hotspot.addEventListener("click", (event) => { event.stopPropagation(); selectTouchpoint(touchpoint, null, true); }); hotspot.addEventListener("keydown", (event) => { if (event.key === "Enter" || event.key === " ") { event.preventDefault(); selectTouchpoint(touchpoint, null, true); } }); dom["hotspot-layer"].append(hotspot); for (const pin of touchpoint.pins) { const point = toDisplayPoint(pin.view_position); const group = svgElement("g", { class: `pin-group role-${pin.pad_role}${state.selectedTouchpoint?.reference === touchpoint.reference && state.selectedPin?.id === pin.id ? " is-selected" : ""}`, tabindex: dom["board-svg"].classList.contains("pins-interactive") ? 0 : -1, role: "button", "aria-label": `${touchpoint.reference}.${pin.number || "机械"} ${pin.net || "无网络"}`, "data-reference": touchpoint.reference, "data-pin": pin.number, "data-pin-id": pin.id, "data-pad-role": pin.pad_role, }); const width = Math.max(Number(pin.size.width), Number(pin.size.drill_width), 0.65); const height = Math.max(Number(pin.size.height), Number(pin.size.drill_height), 0.65); const radius = Math.max(Math.min(width, height) / 2, 0.42); const hitRadius = Math.max(Math.min(width, height) / 2 + 0.15, 0.58); group.append( svgElement("circle", {cx: point.x, cy: point.y, r: hitRadius, class: "pin-hit"}), svgElement("circle", {cx: point.x, cy: point.y, r: radius, class: "pin-dot"}), ); group.addEventListener("pointerenter", (event) => showPinTooltip(event, touchpoint, pin)); group.addEventListener("pointermove", positionTooltip); group.addEventListener("pointerleave", hideTooltip); group.addEventListener("focus", () => showPinTooltip(null, touchpoint, pin)); group.addEventListener("blur", hideTooltip); group.addEventListener("click", (event) => { event.stopPropagation(); selectTouchpoint(touchpoint, pin, true); }); group.addEventListener("keydown", (event) => { if (event.key === "Enter" || event.key === " ") { event.preventDefault(); selectTouchpoint(touchpoint, pin, true); } }); dom["pin-layer"].append(group); } } for (const resistor of state.data.resistors ?? []) { if (!state.categories.has("R")) continue; if (!itemVisibleOnSide(resistor, state.boardSide)) continue; visibleResistors += 1; const bounds = effectiveBounds(toDisplayBounds(resistor.view_bounds), 1.6); const selected = state.selectedResistor?.reference === resistor.reference; const hotspot = svgElement("rect", { x: bounds.x, y: bounds.y, width: bounds.width, height: bounds.height, rx: 0.25, class: `hotspot hotspot-resistor${selected ? " is-selected" : ""}`, tabindex: 0, role: "button", "aria-label": `${resistor.reference} 电阻 ${resistor.component_value || "未标注阻值"}`, "data-reference": resistor.reference, "data-kind": "resistor", "data-side": resistor.side || "front", }); hotspot.addEventListener("pointerenter", (event) => showResistorTooltip(event, resistor)); hotspot.addEventListener("pointermove", positionTooltip); hotspot.addEventListener("pointerleave", hideTooltip); hotspot.addEventListener("focus", () => showResistorTooltip(null, resistor)); hotspot.addEventListener("blur", hideTooltip); hotspot.addEventListener("click", (event) => { event.stopPropagation(); selectResistor(resistor, null, true); }); hotspot.addEventListener("keydown", (event) => { if (event.key === "Enter" || event.key === " ") { event.preventDefault(); selectResistor(resistor, null, true); } }); dom["hotspot-layer"].append(hotspot); for (const pad of resistor.pads ?? []) { const point = toDisplayPoint(pad.view_position); const group = svgElement("g", { class: `pin-group role-${pad.pad_role} resistor-pad${selected && state.selectedPin?.number === pad.number ? " is-selected" : ""}`, tabindex: dom["board-svg"].classList.contains("pins-interactive") ? 0 : -1, role: "button", "aria-label": `${resistor.reference}.${pad.number || "机械"} ${pad.net || "无网络"}`, "data-reference": resistor.reference, "data-pin": pad.number, "data-kind": "resistor", "data-pad-role": pad.pad_role, }); const width = Math.max(Number(pad.size?.width), Number(pad.size?.drill_width), 0.55); const height = Math.max(Number(pad.size?.height), Number(pad.size?.drill_height), 0.55); const radius = Math.max(Math.min(width, height) / 2, 0.35); const hitRadius = Math.max(radius + 0.12, 0.48); group.append( svgElement("circle", {cx: point.x, cy: point.y, r: hitRadius, class: "pin-hit"}), svgElement("circle", {cx: point.x, cy: point.y, r: radius, class: "pin-dot"}), ); group.addEventListener("pointerenter", (event) => showResistorPadTooltip(event, resistor, pad)); group.addEventListener("pointermove", positionTooltip); group.addEventListener("pointerleave", hideTooltip); group.addEventListener("click", (event) => { event.stopPropagation(); selectResistor(resistor, pad, true); }); dom["pin-layer"].append(group); } } const sideLabel = state.boardSide === "back" ? "背面" : "正面"; dom["visible-count"].textContent = `${sideLabel} · ${visibleTouchpoints} 个座子 · ${visibleResistors} 个电阻`; renderSelectionOverlay(); } function showTouchpointTooltip(event, touchpoint) { dom["board-tooltip"].replaceChildren(); const key = element("div", "tooltip-key", touchpoint.reference); const detail = element("div", "", `${touchpointKindLabel(touchpoint)} · ${touchpointPinSummary(touchpoint)}`); const summary = element("div", "", touchpoint.summary); dom["board-tooltip"].append(key, detail, summary); dom["board-tooltip"].hidden = false; if (event) positionTooltip(event); else positionTooltipForTouchpoint(touchpoint); } function showPinTooltip(event, touchpoint, pin) { dom["board-tooltip"].replaceChildren(); dom["board-tooltip"].append( element("div", "tooltip-key", `${touchpoint.reference}.${pin.number || "机械孔"}`), element("div", "tooltip-role", padRoleLabel(pin.pad_role)), element("div", "", pin.net || "无命名网络"), element("div", "", pin.summary || evidenceLabel(pin.evidence_tier)), ); dom["board-tooltip"].hidden = false; if (event) positionTooltip(event); else positionTooltipForTouchpoint(touchpoint); } function showResistorTooltip(event, resistor) { dom["board-tooltip"].replaceChildren(); const nets = (resistor.pads ?? []).filter((pad) => pad.net).map((pad) => pad.net); dom["board-tooltip"].append( element("div", "tooltip-key", resistor.reference), element("div", "", `电阻 · ${resistor.component_value || "阻值未标注"}`), element("div", "", nets.length ? nets.join(" ↔ ") : "无命名网络"), ); dom["board-tooltip"].hidden = false; if (event) positionTooltip(event); else positionTooltipForBounds(toDisplayBounds(resistor.view_bounds)); } function showResistorPadTooltip(event, resistor, pad) { dom["board-tooltip"].replaceChildren(); dom["board-tooltip"].append( element("div", "tooltip-key", `${resistor.reference}.${pad.number || "机械孔"}`), element("div", "tooltip-role", pad.pad_role === "electrical" ? "电气焊盘" : "机械焊盘"), element("div", "", pad.net || "无命名网络"), element("div", "", resistor.component_value || "阻值未标注"), ); dom["board-tooltip"].hidden = false; if (event) positionTooltip(event); else positionTooltipForBounds(toDisplayBounds(resistor.view_bounds)); } function positionTooltip(event) { if (!event || dom["board-tooltip"].hidden) return; const viewport = dom["board-viewport"].getBoundingClientRect(); const tooltip = dom["board-tooltip"]; const left = Math.min(event.clientX - viewport.left + 12, viewport.width - tooltip.offsetWidth - 12); const top = Math.min(event.clientY - viewport.top + 12, viewport.height - tooltip.offsetHeight - 12); tooltip.style.left = `${Math.max(8, left)}px`; tooltip.style.top = `${Math.max(8, top)}px`; } function positionTooltipForTouchpoint(touchpoint) { positionTooltipForBounds(toDisplayBounds(touchpoint.view_bounds), toDisplayPoint(touchpoint.view_position)); } function positionTooltipForBounds(bounds, point = null) { const anchor = point || { x: Number(bounds.x) + Number(bounds.width) / 2, y: Number(bounds.y) + Number(bounds.height) / 2, }; const svgPoint = dom["board-svg"].createSVGPoint(); svgPoint.x = anchor.x; svgPoint.y = anchor.y; const screen = svgPoint.matrixTransform(dom["board-svg"].getScreenCTM()); positionTooltip({clientX: screen.x, clientY: screen.y}); } function hideTooltip() { dom["board-tooltip"].hidden = true; } function appendResistorPadMarker(layer, pad) { const point = toDisplayPoint(pad.view_position); const width = Math.max(Number(pad.size?.width) || 0, Number(pad.view_bounds?.width) || 0, 0.2); const height = Math.max(Number(pad.size?.height) || 0, Number(pad.view_bounds?.height) || 0, 0.2); let rotation = Number(pad.rotation) || 0; if (state.boardSide === "back") rotation = -rotation; const shape = String(pad.shape || "rect").toLowerCase(); const halo = 0.12; const isRound = shape.includes("circle") || shape.includes("round") || (shape.includes("oval") && Math.abs(width - height) < 0.05); if (isRound) { layer.append( svgElement("ellipse", { cx: point.x, cy: point.y, rx: width / 2 + halo, ry: height / 2 + halo, class: "resistor-pad-halo", }), svgElement("ellipse", { cx: point.x, cy: point.y, rx: width / 2, ry: height / 2, class: "resistor-pad-marker", "data-pad-id": pad.id || "", "data-pad-shape": shape || "circle", }), ); return; } const group = svgElement("g", { transform: `rotate(${rotation} ${point.x} ${point.y})`, "data-pad-id": pad.id || "", "data-pad-shape": shape || "rect", }); group.append( svgElement("rect", { x: point.x - width / 2 - halo, y: point.y - height / 2 - halo, width: width + halo * 2, height: height + halo * 2, class: "resistor-pad-halo", }), svgElement("rect", { x: point.x - width / 2, y: point.y - height / 2, width, height, class: "resistor-pad-marker", }), ); layer.append(group); } function renderSelectionOverlay() { dom["selection-layer"].replaceChildren(); dom["net-layer"].replaceChildren(); const target = state.selectedResistor || state.selectedTouchpoint; if (!target || !itemVisibleOnSide(target, state.boardSide)) return; const bounds = effectiveBounds(toDisplayBounds(target.view_bounds), state.selectedResistor ? 2.4 : 4.2); const pad = state.selectedResistor ? 0.45 : 0.8; const x = bounds.x - pad; const y = bounds.y - pad; const width = bounds.width + pad * 2; const height = bounds.height + pad * 2; dom["selection-layer"].append( svgElement("rect", {x, y, width, height, rx: 0.55, class: "selection-reticle"}), svgElement("line", {x1: x - 1.4, y1: y + height / 2, x2: x + 1.1, y2: y + height / 2, class: "selection-cross"}), svgElement("line", {x1: x + width - 1.1, y1: y + height / 2, x2: x + width + 1.4, y2: y + height / 2, class: "selection-cross"}), svgElement("line", {x1: x + width / 2, y1: y - 1.4, x2: x + width / 2, y2: y + 1.1, class: "selection-cross"}), svgElement("line", {x1: x + width / 2, y1: y + height - 1.1, x2: x + width / 2, y2: y + height + 1.4, class: "selection-cross"}), ); if (state.selectedResistor) { for (const resistorPad of state.selectedResistor.pads ?? []) { appendResistorPadMarker(dom["selection-layer"], resistorPad); } } const net = state.selectedPin?.net; if (!net) return; for (const item of sameNetMembers(state.data, net)) { const ownerSide = item.resistor?.side || item.touchpoint?.side || "front"; if (ownerSide !== state.boardSide) continue; const size = item.pin.size || {}; const point = toDisplayPoint(item.pin.view_position); dom["net-layer"].append( svgElement("circle", { cx: point.x, cy: point.y, r: Math.max(Number(size.width), Number(size.height), 1.3), class: `net-highlight${item.kind === "resistor_pad" ? " net-resistor" : ""}`, }), ); } } function selectTouchpoint(touchpoint, pin = null, openDrawer = false) { ensureItemSide(touchpoint); state.selectedTouchpoint = touchpoint; state.selectedResistor = null; state.selectedPin = pin; dom["selection-readout"].textContent = pin ? `${touchpoint.reference}.${pin.number || "机械孔"} · ${padRoleLabel(pin.pad_role)} · ${pin.net || "无网络"}` : `${touchpoint.reference} · ${touchpointPinSummary(touchpoint)}`; if (openDrawer) setDrawerCollapsed(false); renderBoardMarkers(); renderDetail(); } function selectResistor(resistor, pad = null, openDrawer = false) { ensureItemSide(resistor); state.selectedResistor = resistor; state.selectedTouchpoint = null; state.selectedPin = pad; const nets = (resistor.pads ?? []).filter((item) => item.net).map((item) => item.net); const sideNote = resistor.side === "back" ? " · 背面" : ""; dom["selection-readout"].textContent = pad ? `${resistor.reference}.${pad.number || "机械孔"} · ${pad.net || "无网络"}${sideNote}` : `${resistor.reference} · ${resistor.component_value || "阻值未标注"} · ${nets.join(" ↔ ") || "无网络"}${sideNote}`; if (openDrawer) setDrawerCollapsed(false); renderBoardMarkers(); renderDetail(); } function renderEmptyDetail(title, subtitle) { dom["detail-content"].replaceChildren(); const wrapper = element("div", "empty-panel"); wrapper.append(element("strong", "", title), element("span", "empty-stats", subtitle)); dom["detail-content"].append(wrapper); } function fact(label, value) { const wrapper = element("div", "fact"); wrapper.append(element("span", "fact-label", label), element("span", "fact-value", value)); return wrapper; } function renderConnectorLayout(touchpoint, groups) { const connector = touchpoint.connector; const section = element("section", "connector-layout"); const header = element("div", "connector-layout-header"); header.append( element("h3", "section-title connector-layout-title", "板正面接触针排列"), element("span", `evidence-tag${connector.review_status === "cross_verified" ? " verified" : ""}`, evidenceLabel(connector.review_status)), ); section.append(header); if (!groups.contactRows.length) { section.append(element("div", "risk-note", "该连接器尚无经过复核的接触针顺序。")); return section; } const orientation = element("div", "connector-orientation"); orientation.append(element("span", "connector-axis connector-axis-top", "上")); const middle = element("div", "connector-axis-row"); middle.append(element("span", "connector-axis", "左")); const grid = element("div", "connector-grid"); const columns = Math.max(...groups.contactRows.map((row) => row.length), 1); for (const pins of groups.contactRows) { const row = element("div", "connector-grid-row"); row.style.setProperty("--connector-columns", String(columns)); for (const pin of pins) { const button = element("button", `connector-contact${state.selectedPin?.id === pin.id ? " is-selected" : ""}`, pin.number); button.type = "button"; button.dataset.pinId = pin.id; button.setAttribute("aria-label", `${touchpoint.reference}.${pin.number},板正面第 ${pin.board_order} 位`); button.addEventListener("click", () => selectTouchpoint(touchpoint, pin, true)); row.append(button); } grid.append(row); } middle.append(grid, element("span", "connector-axis", "右")); orientation.append(middle, element("span", "connector-axis connector-axis-bottom", "下")); section.append(orientation); section.append( element( "div", "connector-layout-meta", `${connector.profile} · ${connector.contact_count} 接触针 · ${connector.auxiliary_pad_count} 辅助焊盘`, ), element( "div", "connector-perspective-note", "板正面俯视:按页面上/下/左/右读取;线缆端或对接面可能是镜像。", ), ); return section; } function renderPinRow(touchpoint, pin) { const row = element("button", `pin-row${state.selectedPin?.id === pin.id ? " is-selected" : ""}`); row.type = "button"; row.dataset.pin = pin.number; row.dataset.pinId = pin.id; row.dataset.padRole = pin.pad_role; const primary = element("span", "pin-primary"); primary.append( element("span", "pin-summary", pin.summary), element("span", "pin-net", `原始网络:${pin.net || "无命名网络"}`), ); row.append( element("span", "pin-number", pin.number || "孔"), primary, element("span", "pin-direction", pin.pad_role === "contact" ? directionLabel(pin.direction) : padRoleLabel(pin.pad_role)), ); row.addEventListener("click", () => selectTouchpoint(touchpoint, pin, true)); return row; } function appendPinSection(container, touchpoint, title, pins) { if (!pins.length) return; container.append(element("h3", "section-title", title)); const pinList = element("div", "pin-list"); for (const pin of pins) pinList.append(renderPinRow(touchpoint, pin)); container.append(pinList); } function renderDetail() { if (state.selectedResistor) { renderResistorDetail(state.selectedResistor, state.selectedPin); return; } const touchpoint = state.selectedTouchpoint; if (!touchpoint) { const counts = state.data?.counts; renderEmptyDetail( "未选择座子或电阻", counts ? `${counts.touchpoints} 个座子 · ${counts.resistors ?? 0} 个电阻 · ${counts.connector_contacts} 个 CON 接触针 · ${counts.connector_auxiliary_pads} 个 CON 辅助焊盘` : "", ); return; } dom["detail-content"].replaceChildren(); const heading = element("div", "detail-heading"); const headingText = element("div"); headingText.append(element("h2", "detail-reference", touchpoint.reference), element("p", "detail-summary", touchpoint.summary)); heading.append(headingText, element("span", "category-tag", touchpointKindLabel(touchpoint))); const facts = element("div", "detail-facts"); if (touchpoint.connector) { facts.append( fact("接触针", touchpoint.connector.contact_count), fact("辅助焊盘", touchpoint.connector.auxiliary_pad_count), fact("总焊盘", touchpoint.pins.length), fact("板面", touchpoint.side === "front" ? "正面" : "背面"), fact("坐标", `${formatNumber(touchpoint.position.x)} / ${formatNumber(touchpoint.position.y)} mm`), fact("旋转", `${formatNumber(touchpoint.rotation, 1)}°`), ); } else { facts.append( fact("针脚数量", touchpoint.pins.length), fact("板面", touchpoint.side === "front" ? "正面" : "背面"), fact("坐标", `${formatNumber(touchpoint.position.x)} / ${formatNumber(touchpoint.position.y)} mm`), fact("旋转", `${formatNumber(touchpoint.rotation, 1)}°`), ); } dom["detail-content"].append(heading, facts); if (touchpoint.connector) { const groups = connectorPinGroups(touchpoint); dom["detail-content"].append(renderConnectorLayout(touchpoint, groups)); const contactPins = groups.contacts.length ? groups.contacts : touchpoint.pins.filter((pin) => pin.pad_role === "contact"); const auxiliaryPins = groups.contacts.length ? groups.auxiliary : touchpoint.pins.filter((pin) => pin.pad_role !== "contact"); appendPinSection( dom["detail-content"], touchpoint, groups.contacts.length ? "接触针(板正面顺序)" : "接触针(板数据库编号)", contactPins, ); appendPinSection(dom["detail-content"], touchpoint, "屏蔽与机械焊盘", auxiliaryPins); } else { appendPinSection(dom["detail-content"], touchpoint, "针脚", touchpoint.pins); } if (state.selectedPin) dom["detail-content"].append(renderPinDetail(touchpoint, state.selectedPin)); } function renderResistorDetail(resistor, pad = null) { dom["detail-content"].replaceChildren(); const heading = element("div", "detail-heading"); const headingText = element("div"); headingText.append( element("h2", "detail-reference", resistor.reference), element("p", "detail-summary", resistor.summary || "分立电阻"), ); heading.append(headingText, element("span", "category-tag", "电阻")); if (resistor.side === "back") { heading.append(element("span", "side-tag side-back", "背面")); } const nets = (resistor.pads ?? []).filter((item) => item.net).map((item) => item.net); const facts = element("div", "detail-facts"); const assembly = resistor.assembly_status || "unknown"; facts.append( fact("阻值", resistor.component_value || "未标注"), fact( "解析阻值", resistor.value_ohms == null ? `不可解析(${resistor.value_parse_status || "unparsed"})` : `${resistor.value_ohms} Ω`, ), fact("装配状态", assembly === "not_fitted" ? "未装/NC" : assembly === "fitted" ? "已装" : "未知"), fact("两侧网络", nets.length ? nets.join(" ↔ ") : "无命名网络"), fact("焊盘数", resistor.pads?.length ?? 0), fact("板面", resistor.side === "front" ? "正面" : "背面"), fact("坐标", `${formatNumber(resistor.position.x)} / ${formatNumber(resistor.position.y)} mm`), fact("旋转", `${formatNumber(resistor.rotation, 1)}°`), ); dom["detail-content"].append(heading, facts); if (assembly === "not_fitted") { dom["detail-content"].append( element("div", "risk-note", "标注为未装/NC:保留在 PCB 索引中,但不作为已装 0Ω 电气连通默认成员。"), ); } if (resistor.side === "back") { const tip = element("div", "back-view-tip"); tip.id = "back-view-tip"; if (state.boardSide === "back") { tip.textContent = "当前为背面实物视角(已对 X 做左右镜像);实体坐标/网络不变。切换到「正面投影」可按板正面坐标系查看。"; } else { tip.textContent = "当前为板正面投影视角;该器件在背面。从实物背面查看时需左右镜像——请切换到「背面实物(左右镜像)」。"; } dom["detail-content"].append(tip); } const coverage = state.data?.value_coverage; if (coverage) { dom["detail-content"].append( element( "div", "coverage-hint", `阻值覆盖 ${coverage.value_parsed}/${coverage.resistors_total}(原始值非空 ${coverage.component_value_nonempty});来源:${state.data.component_value_source_status || coverage.component_value_source_status}`, ), ); } const padSection = element("div", "pin-list"); for (const item of resistor.pads ?? []) { const row = element("button", `pin-row${pad?.number === item.number ? " is-selected" : ""}`); row.type = "button"; row.append( element("span", "pin-number", item.number || "孔"), element("span", "pin-primary", item.net || "无命名网络"), element( "span", "pin-direction", `${item.pad_role === "electrical" ? "电气" : "机械"} · ${formatNumber(item.position?.x)}/${formatNumber(item.position?.y)}`, ), ); row.addEventListener("click", () => selectResistor(resistor, item, true)); padSection.append(row); } dom["detail-content"].append(element("h3", "section-title", "电阻焊盘"), padSection); if (pad?.net || nets[0]) { const net = pad?.net || nets[0]; const netMatches = sameNetMembers(state.data, net); if (netMatches.length) { dom["detail-content"].append(element("h3", "section-title", `同网成员(${net})`)); const list = element("div", "pin-list"); for (const item of netMatches.slice(0, 32)) { const row = element("button", "pin-row"); row.type = "button"; const kindLabel = item.kind === "resistor_pad" ? "电阻" : "座子"; row.append( element("span", "pin-number", item.pinNumber), element("span", "pin-primary", `${item.reference}.${item.pinNumber}`), element("span", "pin-direction", kindLabel), ); row.addEventListener("click", () => { if (item.kind === "resistor_pad" && item.resistor) { state.categories.add("R"); const checkbox = dom["category-filters"].querySelector('input[value="R"]'); if (checkbox) checkbox.checked = true; selectResistor(item.resistor, item.pin, true); focusOnTouchpoint(item.resistor); } else if (item.touchpoint) { state.categories.add(item.touchpoint.category); selectTouchpoint(item.touchpoint, item.pin, true); focusOnTouchpoint(item.touchpoint); } }); list.append(row); } dom["detail-content"].append(list); } } const conflicts = (state.data.evidence_conflicts ?? []).filter( (item) => item.subject_reference === resistor.reference, ); if (conflicts.length) { const section = element("section", "evidence-conflict"); section.append(element("h3", "section-title", "证据与冲突")); for (const conflict of conflicts) { const note = element("div", "risk-note evidence-conflict-note"); note.append( element("strong", "", `${conflict.status || "unresolved"} · ${conflict.kind || "cross_evidence"}`), document.createTextNode(` — ${conflict.summary || "存在未解决的交叉证据冲突"}`), ); section.append(note); if (Array.isArray(conflict.pcb_pads) && conflict.pcb_pads.length) { section.append(element("div", "info-note", `PCB pad facts:${conflict.pcb_pads.map((item) => `${item.number}:${item.net || "null"}`).join(" · ")}`)); } if (Array.isArray(conflict.claims)) { const list = element("ul", "source-list"); for (const claim of conflict.claims) { const line = element("li", ""); line.textContent = `${claim.source || "claim"} (${claim.source_id || "?"}): ${claim.note || claim.claimed_context || JSON.stringify(claim.claimed_nets || [])}`; list.append(line); } section.append(list); } } dom["detail-content"].append(section); } } function renderPinDetail(touchpoint, pin) { const wrapper = element("section", "pin-detail"); const header = element("div", "pin-detail-header"); header.append( element("h3", "", `${touchpoint.reference}.${pin.number || "机械孔"}`), element("span", `evidence-tag${pin.evidence_tier === "cross_verified" ? " verified" : ""}`, evidenceLabel(pin.evidence_tier)), ); wrapper.append(header); const programmingGuide = renderProgrammingGuide(pin); if (programmingGuide) wrapper.append(programmingGuide); wrapper.append(element("h4", "section-title", "物理与电气事实")); const facts = element("div", "detail-facts"); const programmableTarget = pin.fpga ? "FPGA U3" : pin.mcu ? `${pin.mcu.family} ${pin.mcu.device}` : "无直接可编程映射"; const devicePin = pin.fpga?.ball ? `FPGA ${pin.fpga.ball}` : pin.mcu ? `${pin.mcu.device}.${pin.mcu.pin} (${pin.mcu.signal})` : "无已验证映射"; const boardPosition = pin.board_order == null ? "不属于外部接触针" : `第 ${pin.board_order} 位 · 第 ${pin.row} 行 / 第 ${pin.column} 列`; facts.append( fact("焊盘角色", padRoleLabel(pin.pad_role)), fact("板正面位置", boardPosition), fact("原始网络", pin.net || "无命名网络"), fact("逻辑方向", directionLabel(pin.direction)), fact("外部电平", pin.external_level || "未知"), fact("可编程目标", programmableTarget), fact("器件引脚", devicePin), fact("I/O 标准", pin.fpga?.io_standard || "未知"), fact("板上 pull", pin.board_pull || "未注明"), fact("有效电平", activeLevelLabel(pin.active_level)), fact("极性", pin.polarity && pin.polarity !== "unknown" ? pin.polarity : "未注明"), ); wrapper.append(facts); if (pin.external_components?.length) { wrapper.append(element("h4", "section-title", "相关板上器件")); const components = element("ul", "component-list"); for (const item of pin.external_components) components.append(element("li", "", item)); wrapper.append(components); } if (pin.path?.length) { wrapper.append(element("h4", "section-title", "已验证板内路径")); const path = element("ol", "path-list"); for (const item of pin.path) path.append(element("li", "", item)); wrapper.append(path); } const related = Array.isArray(pin.related_resistors) ? pin.related_resistors : []; if (related.length) { wrapper.append(element("h4", "section-title", "关联电阻(path / external_components)")); const list = element("div", "pin-list"); for (const link of related) { const resistor = (state.data.resistors ?? []).find((item) => item.reference === link.resistor_reference); const row = element("button", "pin-row"); row.type = "button"; const label = link.pad_number ? `${link.resistor_reference}.${link.pad_number}` : link.resistor_reference; const netLine = [ link.claimed_net != null ? `claimed=${link.claimed_net}` : "claimed=∅", link.pcb_net != null ? `pcb=${link.pcb_net}` : "pcb=∅", link.status, ].join(" · "); row.append( element("span", "pin-number", "R"), element("span", "pin-primary", `${label} · ${netLine}`), element("span", "pin-direction", link.source_field || "path"), ); if (link.status === "net_conflict") { row.classList.add("is-conflict"); } if ((link.status === "resolved" || link.status === "net_conflict") && resistor) { row.addEventListener("click", () => { state.categories.add("R"); const checkbox = dom["category-filters"].querySelector('input[value="R"]'); if (checkbox) checkbox.checked = true; const pad = link.pad_number ? (resistor.pads ?? []).find((item) => String(item.number) === String(link.pad_number)) : null; selectResistor(resistor, pad || null, true); focusOnTouchpoint(resistor); }); } else { row.disabled = true; row.classList.add("is-conflict"); } list.append(row); } wrapper.append(list); } else { try { const pathResistors = extractPathResistors(state.data, pin.path, pin.external_components); if (pathResistors.length) { wrapper.append(element("h4", "section-title", "路径电阻(可跳转)")); const list = element("div", "pin-list"); for (const resistor of pathResistors) { const nets = (resistor.pads ?? []).filter((item) => item.net).map((item) => item.net); const row = element("button", "pin-row"); row.type = "button"; row.append( element("span", "pin-number", "R"), element("span", "pin-primary", `${resistor.reference} · ${resistor.component_value || "未标注"} · ${nets.join(" ↔ ") || "无网络"}`), element("span", "pin-direction", "跳转"), ); row.addEventListener("click", () => { state.categories.add("R"); const checkbox = dom["category-filters"].querySelector('input[value="R"]'); if (checkbox) checkbox.checked = true; selectResistor(resistor, null, true); focusOnTouchpoint(resistor); }); list.append(row); } wrapper.append(list); } } catch (error) { wrapper.append(element("div", "risk-note", String(error.message || error))); } } wrapper.append(element("h4", "section-title", "证据来源")); const sources = element("ul", "source-list"); for (const source of pin.evidence_sources ?? []) sources.append(element("li", "", source)); wrapper.append(sources); if (pin.net) { const netMatches = sameNetMembers(state.data, pin.net); wrapper.append(element("div", "info-note", `同网成员 ${netMatches.length} 个(座子+电阻),板图已同步高亮。`)); } const blockers = pin.recommendation?.reasons ?? []; if (!pin.recommendation?.eligible) { wrapper.append(element("div", "risk-note", `不可用于自动候选或 ADC:${blockers.join("、") || "证据条件不足"}。`)); } const dedicatedConfigurationPin = String(pin.function_category || "").startsWith("jtag_"); if (!pin.fpga || dedicatedConfigurationPin) { wrapper.append( element( "div", "info-note", dedicatedConfigurationPin ? "专用配置脚不使用用户 ADC 约束" : "此针不对应可生成 ADC 的 FPGA 用户 I/O。", ), ); return wrapper; } wrapper.append(element("h4", "section-title", "ADC 片段")); const adc = element("div", "adc-controls"); const input = element("input"); input.type = "text"; input.placeholder = "RTL 端口名"; input.setAttribute("aria-label", "RTL 端口名"); input.disabled = !pin.recommendation?.eligible || state.runtime.adcCopyEnabled !== true; const copy = element("button", "copy-button", "⧉"); copy.type = "button"; copy.title = "复制 ADC 片段"; copy.setAttribute("aria-label", "复制 ADC 片段"); copy.disabled = input.disabled; const status = element("div", "copy-status"); copy.addEventListener("click", async () => { try { const snippet = generateAdcSnippet(pin, input.value.trim(), state.runtime); await copyText(snippet); status.textContent = "ADC 片段已复制"; } catch (error) { status.textContent = error instanceof Error ? error.message : String(error); } }); adc.append(input, copy); wrapper.append(adc, status, element("div", "risk-note", "这里只证明物理可用性,仍需检查当前工程约束冲突。")); return wrapper; } function appendGuidanceList(container, title, items, className = "guidance-list") { if (!Array.isArray(items) || !items.length) return; container.append(element("h4", "section-title", title)); const list = element("ul", className); for (const item of items) list.append(element("li", "", item)); container.append(list); } function renderProgrammingGuide(pin) { const programming = pin.programming; if (!programming) return null; const section = element("section", `programming-guide status-${programming.status || "unknown"}`); const heading = element("div", "programming-guide-heading"); heading.append( element("h4", "section-title programming-title", "编程结论"), element( "span", `evidence-tag${programming.evidence_tier === "cross_verified" ? " verified" : ""}`, evidenceLabel(programming.evidence_tier), ), ); section.append(heading, element("p", "programming-conclusion", programming.conclusion)); section.append(element("h4", "section-title", "板内网络解释")); section.append(element("p", "programming-copy", programming.network_explanation)); appendGuidanceList(section, "怎么接", programming.connection_guidance); section.append( element( "h4", "section-title", programming.status === "verified_mcu" ? "MCU 固件用法" : "HDL 用法", ), ); section.append(element("p", "programming-copy", programming.hdl_guidance)); appendGuidanceList(section, "约束要求", programming.constraints, "guidance-list constraint-list"); appendGuidanceList(section, "风险与未知", programming.risks, "guidance-list risk-list"); return section; } async function copyText(value) { if (navigator.clipboard?.writeText) return navigator.clipboard.writeText(value); const textarea = element("textarea"); textarea.value = value; textarea.style.position = "fixed"; textarea.style.opacity = "0"; document.body.append(textarea); textarea.select(); document.execCommand("copy"); textarea.remove(); } function renderCandidates() { if (!state.data) return; dom["candidate-list"].replaceChildren(); if (state.runtime.recommendationsEnabled !== true) { dom["candidate-list"].append(element("div", "risk-note", "源文件状态不是当前值,选脚推荐已关闭。")); return; } const capability = dom["capability-select"].value; const candidates = findCandidates(state.data, capability); if (!candidates.length) { const empty = element("div", "empty-panel"); empty.append( element("strong", "", "没有满足全部证据条件的候选"), element("span", "empty-stats", "未知、推断、保留、电源、地、机械焊盘和固定负载冲突均已排除"), ); dom["candidate-list"].append(empty); return; } for (const candidate of candidates) { const row = element("button", "candidate-row"); row.type = "button"; row.append( element("span", "candidate-key", `${candidate.reference}.${candidate.pin.number} · ${candidate.pin.fpga.ball}`), element("span", "candidate-reason", candidate.reason), element("span", "candidate-warning", candidate.warning), ); row.addEventListener("click", () => { switchTab("detail"); selectTouchpoint(candidate.touchpoint, candidate.pin, true); focusOnTouchpoint(candidate.touchpoint); }); dom["candidate-list"].append(row); } } function switchTab(tab) { state.activeTab = tab; const detail = tab === "detail"; dom["detail-tab"].setAttribute("aria-selected", String(detail)); dom["candidate-tab"].setAttribute("aria-selected", String(!detail)); dom["detail-content"].hidden = !detail; dom["candidate-content"].hidden = detail; if (!detail) renderCandidates(); } function renderSearchResults(query) { state.searchResults = searchBoard(state.data, query).slice(0, 24); state.activeSearchIndex = -1; dom["search-results"].replaceChildren(); if (!query.trim()) { dom["search-results"].hidden = true; return; } dom["search-results"].hidden = false; if (!state.searchResults.length) { const coverage = state.data?.value_coverage; const looksValue = /^(?:value:)?\d/i.test(query.trim()) || /[rRkKmM]|ohm|Ω/.test(query); let message = "没有匹配的座子、电阻或针脚"; if (looksValue && coverage) { message = `当前索引中没有此阻值;当前阻值覆盖 ${coverage.value_parsed}/${coverage.resistors_total}(原始值非空 ${coverage.component_value_nonempty})。位号/网络查询不受影响。`; } dom["search-results"].append(element("div", "empty-search", message)); return; } state.searchResults.forEach((result, index) => { const button = element("button", "search-result"); button.type = "button"; button.role = "option"; button.dataset.index = String(index); button.setAttribute("aria-selected", "false"); let key = result.reference; let detail = ""; if (result.type === "pin") { key = `${result.reference}.${result.pinNumber}`; detail = `${result.pin.net || "无网络"} · ${result.pin.fpga?.ball || evidenceLabel(result.pin.evidence_tier)}`; } else if (result.type === "resistor" || result.type === "resistor_pad") { key = result.type === "resistor_pad" ? `${result.reference}.${result.pinNumber}` : result.reference; const nets = (result.resistor?.pads ?? []).filter((pad) => pad.net).map((pad) => pad.net); const valueLabel = result.resistor?.value_ohms != null ? `${result.resistor.value_ohms} Ω` : (result.resistor?.component_value || "阻值未标注"); const nf = result.notFitted || result.resistor?.assembly_status === "not_fitted"; detail = result.type === "resistor_pad" ? `${result.pin?.net || "无网络"}` : `${valueLabel} · ${nets.join(" ↔ ") || "无网络"}${nf ? " · 未装/NC" : ""}`; } else if (result.type === "evidence_conflict") { key = `${result.reference} 冲突`; detail = result.evidenceConflict?.summary || "原理图声明与 PCB 索引冲突,未解决"; } else { detail = `${touchpointKindLabel(result.touchpoint)} · ${result.touchpoint.summary}`; } button.append(element("span", "result-key", key), element("span", "result-detail", detail)); button.addEventListener("click", () => activateSearchResult(index)); dom["search-results"].append(button); }); } function activateSearchResult(index) { const result = state.searchResults[index]; if (!result) return; if (result.type === "resistor" || result.type === "resistor_pad" || result.type === "evidence_conflict") { if (!result.resistor) return; state.categories.add("R"); const checkbox = dom["category-filters"].querySelector('input[value="R"]'); if (checkbox) checkbox.checked = true; selectResistor(result.resistor, result.pin, true); focusOnTouchpoint(result.resistor); dom["board-search"].value = result.type === "resistor_pad" ? `${result.reference}.${result.pinNumber}` : result.reference; } else if (result.touchpoint) { state.categories.add(result.touchpoint.category); const checkbox = dom["category-filters"].querySelector(`input[value="${result.touchpoint.category}"]`); if (checkbox) checkbox.checked = true; selectTouchpoint(result.touchpoint, result.pin, true); focusOnTouchpoint(result.touchpoint); dom["board-search"].value = result.type === "pin" ? `${result.reference}.${result.pinNumber}` : result.reference; } dom["search-results"].hidden = true; dom["board-svg"].focus(); } function updateSearchSelection(nextIndex) { const options = [...dom["search-results"].querySelectorAll(".search-result")]; if (!options.length) return; state.activeSearchIndex = (nextIndex + options.length) % options.length; options.forEach((option, index) => option.setAttribute("aria-selected", String(index === state.activeSearchIndex))); options[state.activeSearchIndex].scrollIntoView({block: "nearest"}); } function focusOnTouchpoint(touchpoint) { const bounds = effectiveBounds(toDisplayBounds(touchpoint.view_bounds), 8); const viewport = dom["board-svg"].getBoundingClientRect(); const aspect = Math.max(viewport.width / Math.max(viewport.height, 1), 1); let width = Math.max(bounds.width * 3.4, state.baseViewBox.width / 12); let height = width / aspect; if (height < bounds.height * 3.4) { height = bounds.height * 3.4; width = height * aspect; } state.viewBox = { x: bounds.x + bounds.width / 2 - width / 2, y: bounds.y + bounds.height / 2 - height / 2, width, height, }; clampViewBox(); updateViewBox(); } function clampViewBox() { if (!state.viewBox || !state.baseViewBox) return; const marginX = state.baseViewBox.width * 0.25; const marginY = state.baseViewBox.height * 0.4; const minX = state.baseViewBox.x - marginX; const maxX = state.baseViewBox.x + state.baseViewBox.width + marginX - state.viewBox.width; const minY = state.baseViewBox.y - marginY; const maxY = state.baseViewBox.y + state.baseViewBox.height + marginY - state.viewBox.height; state.viewBox.x = Math.min(Math.max(state.viewBox.x, minX), Math.max(minX, maxX)); state.viewBox.y = Math.min(Math.max(state.viewBox.y, minY), Math.max(minY, maxY)); } function zoomAt(factor, clientX = null, clientY = null) { if (!state.viewBox || !state.baseViewBox) return; const minimumWidth = state.baseViewBox.width / 35; const maximumWidth = state.baseViewBox.width * 1.25; const newWidth = Math.min(Math.max(state.viewBox.width * factor, minimumWidth), maximumWidth); const ratio = newWidth / state.viewBox.width; const anchor = clientX == null ? { x: state.viewBox.x + state.viewBox.width / 2, y: state.viewBox.y + state.viewBox.height / 2, } : clientToSvg(clientX, clientY); state.viewBox = { x: anchor.x - (anchor.x - state.viewBox.x) * ratio, y: anchor.y - (anchor.y - state.viewBox.y) * ratio, width: newWidth, height: state.viewBox.height * ratio, }; clampViewBox(); updateViewBox(); } function clientToSvg(clientX, clientY) { const point = dom["board-svg"].createSVGPoint(); point.x = clientX; point.y = clientY; return point.matrixTransform(dom["board-svg"].getScreenCTM().inverse()); } function resetView() { state.viewBox = {...state.baseViewBox}; updateViewBox(); } function setDrawerCollapsed(collapsed) { dom.app.classList.toggle("detail-collapsed", collapsed); dom["drawer-toggle"].setAttribute("aria-expanded", String(!collapsed)); dom["drawer-toggle"].title = collapsed ? "展开详情" : "收起详情"; dom["drawer-toggle"].setAttribute("aria-label", collapsed ? "展开详情" : "收起详情"); } dom["category-filters"].addEventListener("change", (event) => { const input = event.target; if (!(input instanceof HTMLInputElement)) return; if (input.checked) state.categories.add(input.value); else state.categories.delete(input.value); renderBoardMarkers(); }); dom["side-controls"].addEventListener("change", (event) => { const input = event.target; if (!(input instanceof HTMLInputElement) || input.name !== "board-side") return; setBoardSide(input.value, {rerender: true}); }); dom["layer-controls"].addEventListener("change", (event) => { const input = event.target; if (!(input instanceof HTMLInputElement)) return; const layer = dom[`layer-${input.value}`]; if (layer) layer.hidden = !input.checked; }); dom["zoom-in"].addEventListener("click", () => zoomAt(0.8)); dom["zoom-out"].addEventListener("click", () => zoomAt(1.25)); dom["reset-view"].addEventListener("click", resetView); dom["detail-tab"].addEventListener("click", () => switchTab("detail")); dom["candidate-tab"].addEventListener("click", () => switchTab("candidate")); dom["capability-select"].addEventListener("change", renderCandidates); dom["drawer-toggle"].addEventListener("click", () => setDrawerCollapsed(!dom.app.classList.contains("detail-collapsed"))); dom["board-search"].addEventListener("input", (event) => { if (state.data) renderSearchResults(event.target.value); }); dom["board-search"].addEventListener("keydown", (event) => { if (event.key === "ArrowDown") { event.preventDefault(); updateSearchSelection(state.activeSearchIndex + 1); } else if (event.key === "ArrowUp") { event.preventDefault(); updateSearchSelection(state.activeSearchIndex - 1); } else if (event.key === "Enter" && state.activeSearchIndex >= 0) { event.preventDefault(); activateSearchResult(state.activeSearchIndex); } else if (event.key === "Escape") { dom["search-results"].hidden = true; } }); document.addEventListener("pointerdown", (event) => { if (!dom["search-results"].contains(event.target) && event.target !== dom["board-search"]) { dom["search-results"].hidden = true; } }); dom["board-svg"].addEventListener("wheel", (event) => { event.preventDefault(); zoomAt(event.deltaY < 0 ? 0.82 : 1.22, event.clientX, event.clientY); }, {passive: false}); dom["board-svg"].addEventListener("pointerdown", (event) => { if (event.target.closest?.(".hotspot, .pin-group")) return; dom["board-svg"].setPointerCapture(event.pointerId); dom["board-svg"].classList.add("is-panning"); state.dragging = {pointerId: event.pointerId, x: event.clientX, y: event.clientY, viewBox: {...state.viewBox}}; }); dom["board-svg"].addEventListener("pointermove", (event) => { if (!state.dragging || state.dragging.pointerId !== event.pointerId) return; const bounds = dom["board-svg"].getBoundingClientRect(); state.viewBox = { ...state.dragging.viewBox, x: state.dragging.viewBox.x - (event.clientX - state.dragging.x) * state.dragging.viewBox.width / bounds.width, y: state.dragging.viewBox.y - (event.clientY - state.dragging.y) * state.dragging.viewBox.height / bounds.height, }; clampViewBox(); updateViewBox(); }); function endPan(event) { if (!state.dragging || state.dragging.pointerId !== event.pointerId) return; state.dragging = null; dom["board-svg"].classList.remove("is-panning"); } dom["board-svg"].addEventListener("pointerup", endPan); dom["board-svg"].addEventListener("pointercancel", endPan); dom["board-svg"].addEventListener("keydown", (event) => { const stepX = state.viewBox.width * 0.06; const stepY = state.viewBox.height * 0.08; if (event.key === "+" || event.key === "=") zoomAt(0.8); else if (event.key === "-") zoomAt(1.25); else if (event.key === "0") resetView(); else if (["ArrowLeft", "ArrowRight", "ArrowUp", "ArrowDown"].includes(event.key)) { if (event.key === "ArrowLeft") state.viewBox.x -= stepX; if (event.key === "ArrowRight") state.viewBox.x += stepX; if (event.key === "ArrowUp") state.viewBox.y -= stepY; if (event.key === "ArrowDown") state.viewBox.y += stepY; clampViewBox(); updateViewBox(); } else return; event.preventDefault(); }); window.addEventListener("resize", () => { hideTooltip(); if (window.innerWidth > 860) setDrawerCollapsed(false); }); const TERM_HELP = { RefDes: "RefDes = Reference Designator,器件位号(如 R674、CON104)。", Net: "Net = 电气网络名;同网成员按 PCB pad.net / pin.net 索引。裸 PUL1 若精确等于现有网络名,按 exact net 处理。", Pad: "Pad = 焊盘;电阻可用 R674.1 精确查询某个焊盘。", PCB: "PCB = 印制电路板;本查看器的电阻实体只来自 PCB footprint。", BRD: "BRD = Allegro 板文件原件;默认分析包不打包 raw BRD。", FPGA: "FPGA = Field-Programmable Gate Array,现场可编程门阵列(本板 U3)。", MCU: "MCU = Microcontroller Unit,微控制器。", GPIO: "GPIO = General-Purpose Input/Output,通用输入输出。", PWM: "PWM = Pulse-Width Modulation,脉冲宽度调制。", UART: "UART = Universal Asynchronous Receiver/Transmitter,异步串行收发。", ADC: "ADC = Analog-to-Digital Converter,模数转换。", JTAG: "JTAG = Joint Test Action Group,边界扫描/调试接口。", CON: "CON = Connector,连接器座子位号前缀。", TP: "TP = Test Point,测试点。", PL: "PL = Plug/socket style header,插座类位号前缀。", }; document.querySelector(".search-help")?.addEventListener("click", (event) => { const chip = event.target.closest?.(".help-chip"); if (chip?.dataset?.query) { dom["board-search"].value = chip.dataset.query; renderSearchResults(chip.dataset.query); dom["board-search"].focus(); return; } const term = event.target.closest?.(".term"); if (term?.dataset?.term) { const message = TERM_HELP[term.dataset.term] || term.dataset.term; dom["stale-banner"].hidden = false; dom["stale-banner"].textContent = message; window.setTimeout(() => { if (dom["stale-banner"].textContent === message) { dom["stale-banner"].hidden = true; } }, 6000); } }); setDrawerCollapsed(window.innerWidth <= 860); loadApplication();