import {
PERIPHERAL_TYPE_LABELS,
PERIPHERAL_TYPE_ORDER,
buildPeripheralIndex,
classifyTouchpointPeripheral,
connectorPinGroups,
displayBounds,
displayPoint,
extractPathResistors,
filterPeripheralCatalog,
findCandidates,
generateAdcSnippet,
itemVisibleOnSide,
resolveLogicalPin,
sameNetMembers,
sameNetPins,
searchBoard,
} from "./board-logic.mjs";
import {
BOARD_VERSION_COMM_MATRIX,
CPLD_CHIP_SPEC,
CPLD_MENU_TREE,
getCpldTopicDetail,
} from "./cpld-arch-data.mjs";
import {BoardWasmAccelerator} from "./wasm-engine.mjs";
const wasmAccel = new BoardWasmAccelerator();
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",
},
};
function getLayerAssets(version, side) {
let prefix = "/generated";
if (version === "v1_1") prefix = "/generated-v1_1";
else if (version === "v2_0") prefix = "/generated-v2_0";
else if (version === "v2_0_fan") prefix = "/generated-v2_0_fan";
if (version === "v1_2" && LAYER_ASSETS[side]) return LAYER_ASSETS[side];
return {
mask: `${prefix}/board-mask-edge${side === "back" ? "-back" : ""}.svg`,
silk: `${prefix}/board-silkscreen${side === "back" ? "-back" : ""}.svg`,
copper: `${prefix}/board-copper${side === "back" ? "-back" : ""}.svg`,
};
}
const state = {
data: null,
boardVersion: "v2_0",
boardCache: new Map(),
layerImageCache: new Map(),
layerCompositeCanvas: null,
layerCompositeKey: "",
layerCompositeReady: false,
perfUltraMode: true,
boxZoomMode: false,
boxZoomDrag: null,
minimapDragging: false,
activeTouchPointers: new Map(),
pinchState: null,
tpByRef: new Map(),
tpIndexMap: new Map(),
resByRef: new Map(),
resIndexMap: new Map(),
hoverTargetKey: "",
lastFrameMs: 0.1,
runtime: {status: "loading", recommendationsEnabled: false, adcCopyEnabled: false, staleSources: []},
categories: new Set(["CON", "J", "PL", "TP"]),
showShieldPins: false,
boardSide: "front",
selectedTouchpoint: null,
selectedResistor: null,
selectedPin: null,
highlightAllSame: false,
baseViewBox: null,
viewBox: null,
dragging: null,
activeTab: "detail",
searchResults: [],
activeSearchIndex: -1,
peripheralCategory: "ALL",
peripheralUsage: "all",
peripheralQuery: "",
peripheralHighlightedRefs: new Set(),
cpldDomainId: "comm_params",
cpldGroupId: "board_current",
cpldTopicId: "curr_overview",
cpldFilterQuery: "",
cpldTreeExpanded: false,
widePanel: false,
rafViewBoxId: 0,
animViewBoxId: 0,
};
const dom = Object.fromEntries(
[
"app",
"app-status",
"board-summary",
"board-search",
"search-results",
"stale-banner",
"category-filters",
"side-controls",
"layer-controls",
"box-zoom-toggle",
"zoom-in",
"zoom-out",
"reset-view",
"board-viewport",
"board-layer-canvas",
"board-svg",
"board-fast-canvas",
"box-zoom-marquee",
"board-minimap-wrap",
"minimap-zoom-badge",
"board-minimap",
"zoom-hud-dock",
"hud-box-zoom",
"hud-zoom-out",
"hud-zoom-in",
"zoom-slider",
"hud-zoom-value",
"hud-reset-view",
"board-loading",
"board-tooltip",
"hotspot-layer",
"pin-layer",
"net-layer",
"selection-layer",
"asset-layers",
"layer-mask",
"layer-silk",
"layer-copper",
"layer-photo",
"photo-control",
"photo-layer",
"photo-label",
"visible-count",
"zoom-readout",
"perf-mode-toggle",
"selection-readout",
"detail-panel",
"detail-tab",
"peripheral-tab",
"cpld-arch-tab",
"candidate-tab",
"detail-content",
"peripheral-content",
"cpld-arch-content",
"candidate-content",
"candidate-list",
"capability-select",
"drawer-toggle",
"board-version-select",
"open-peripheral-index",
"open-cpld-arch",
"toggle-wide-panel",
"schematic-tab",
"schematic-content",
].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 isShieldPin(pin) {
if (!pin) return false;
const num = String(pin.number || "").trim().toUpperCase();
if (num.startsWith("SH")) return true;
if (pin.pad_role === "shield") return true;
if (pin.pad_role === "mechanical" && (num.startsWith("SH") || num.startsWith("MH") || num === "")) return true;
return false;
}
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(version = state.boardVersion || "v2_0") {
state.boardVersion = version;
if (dom["board-version-select"] && dom["board-version-select"].value !== version) {
dom["board-version-select"].value = version;
}
const versionLabels = {
v2_0: "FCB V2.0 (6400)",
v2_0_fan: "FCB_FAN V2.0 (风扇扩展板)",
v1_2: "FCB V1.2 (MRDIMM)",
v1_1: "FCB V1.1 (6400)",
};
const dataUrl = version === "v1_1"
? "/generated-v1_1/board-data.json"
: (version === "v2_0"
? "/generated-v2_0/board-data.json"
: (version === "v2_0_fan"
? "/generated-v2_0_fan/board-data.json"
: "/generated/board-data.json"));
const statusUrl = version === "v1_1"
? "/api/status?version=v1_1"
: (version === "v2_0"
? "/api/status?version=v2_0"
: (version === "v2_0_fan"
? "/api/status?version=v2_0_fan"
: "/api/status"));
dom["board-loading"].hidden = false;
dom["board-loading"].textContent = `正在载入 ${versionLabels[version] || version} 板数据...`;
try {
await wasmAccel.init("/board-accel.wasm");
const cachedBundle = state.boardCache.get(version);
if (cachedBundle) {
state.data = cachedBundle.data;
state.runtime = cachedBundle.runtime;
} else {
const [dataResponse, statusResponse] = await Promise.all([
version === "v1_2"
? fetch("/generated/board-data.json")
: fetch(dataUrl),
version === "v1_2"
? fetch("/api/status")
: fetch(statusUrl),
]);
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();
state.boardCache.set(version, {data: state.data, runtime: state.runtime});
}
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 boardHeight() {
return Number(state.data?.board?.view_box?.height) || 0;
}
function toDisplayPoint(point) {
return displayPoint(point, boardWidth(), state.boardSide);
}
function toDisplayBounds(bounds) {
return displayBounds(bounds, boardWidth(), state.boardSide);
}
function buildEntityLookupMaps() {
state.tpByRef.clear();
state.tpIndexMap.clear();
state.resByRef.clear();
state.resIndexMap.clear();
if (!state.data) return;
const tps = state.data.touchpoints ?? [];
for (let i = 0; i < tps.length; i++) {
state.tpByRef.set(tps[i].reference, tps[i]);
state.tpIndexMap.set(tps[i].reference, i);
}
const resistors = state.data.resistors ?? [];
for (let i = 0; i < resistors.length; i++) {
state.resByRef.set(resistors[i].reference, resistors[i]);
state.resIndexMap.set(resistors[i].reference, i);
}
wasmAccel.buildIndex(state.data);
}
function parseSvgInlineStyle(styleStr) {
const out = {};
if (!styleStr) return out;
for (const part of styleStr.split(";")) {
const idx = part.indexOf(":");
if (idx <= 0) continue;
const key = part.slice(0, idx).trim().toLowerCase();
const val = part.slice(idx + 1).trim();
if (key && val) out[key] = val;
}
return out;
}
function resolveElementStyle(el, parentStyle) {
const inline = parseSvgInlineStyle(el.getAttribute("style"));
const pick = (attrName, current) => {
const attrVal = el.getAttribute(attrName);
if (inline[attrName] !== undefined) return inline[attrName];
if (attrVal !== null && attrVal !== "") return attrVal;
return current;
};
return {
fill: pick("fill", parentStyle.fill),
fillOpacity: Number(pick("fill-opacity", parentStyle.fillOpacity)),
stroke: pick("stroke", parentStyle.stroke),
strokeOpacity: Number(pick("stroke-opacity", parentStyle.strokeOpacity)),
strokeWidth: Number(pick("stroke-width", parentStyle.strokeWidth)),
fillRule: pick("fill-rule", parentStyle.fillRule),
opacity: Number(pick("opacity", parentStyle.opacity)),
fontSize: Number(pick("font-size", parentStyle.fontSize)),
textAnchor: pick("text-anchor", parentStyle.textAnchor),
};
}
function shapeToSvgPathD(tag, el) {
if (tag === "path") {
return el.getAttribute("d") || "";
}
if (tag === "circle") {
const cx = Number(el.getAttribute("cx")) || 0;
const cy = Number(el.getAttribute("cy")) || 0;
const r = Number(el.getAttribute("r")) || 0;
if (r <= 0) return "";
return `M${cx - r},${cy}a${r},${r} 0 1,0 ${r * 2},0a${r},${r} 0 1,0 ${-r * 2},0Z`;
}
if (tag === "rect") {
const x = Number(el.getAttribute("x")) || 0;
const y = Number(el.getAttribute("y")) || 0;
const w = Number(el.getAttribute("width")) || 0;
const h = Number(el.getAttribute("height")) || 0;
if (w <= 0 || h <= 0) return "";
const rx = Math.min(Number(el.getAttribute("rx")) || 0, w * 0.5, h * 0.5);
if (rx > 0.01) {
const iw = w - rx * 2;
const ih = h - rx * 2;
return `M${x + rx},${y}h${iw}a${rx},${rx} 0 0,1 ${rx},${rx}v${ih}a${rx},${rx} 0 0,1 ${-rx},${rx}h${-iw}a${rx},${rx} 0 0,1 ${-rx},${-rx}v${-ih}a${rx},${rx} 0 0,1 ${rx},${-rx}Z`;
}
return `M${x},${y}h${w}v${h}h${-w}Z`;
}
return "";
}
function compileSvgToVectorLayer(svgText) {
if (!svgText || typeof DOMParser === "undefined" || typeof Path2D === "undefined") {
return null;
}
const doc = new DOMParser().parseFromString(svgText, "image/svg+xml");
const root = doc.documentElement;
if (!root || root.nodeName.toLowerCase() !== "svg") return null;
// 4 painter z-buckets preserve board layer order while collapsing 14,000+ SVG elements into ~8 Path2D batches
const buckets = [new Map(), new Map(), new Map(), new Map()];
const texts = [];
const rootStyle = resolveElementStyle(root, {
fill: "#000000",
fillOpacity: 1,
stroke: "none",
strokeOpacity: 1,
strokeWidth: 0.1,
fillRule: "nonzero",
opacity: 1,
fontSize: 0.82,
textAnchor: "middle",
});
const walk = (node, inheritedStyle) => {
for (const child of node.children) {
const tag = child.tagName.toLowerCase();
if (tag === "title" || tag === "desc" || tag === "defs") continue;
const style = resolveElementStyle(child, inheritedStyle);
if (style.opacity <= 0) continue;
if (tag === "g") {
walk(child, style);
continue;
}
if (tag === "text") {
const content = (child.textContent || "").trim();
if (content && style.opacity > 0 && (style.fill !== "none" || style.strokeOpacity > 0)) {
texts.push({
text: content,
x: Number(child.getAttribute("x")) || 0,
y: Number(child.getAttribute("y")) || 0,
fontSize: style.fontSize > 0 ? style.fontSize : 0.82,
textAnchor: style.textAnchor || "middle",
fill: style.fill && style.fill !== "none" ? style.fill : "#0f172a",
});
}
continue;
}
const d = shapeToSvgPathD(tag, child);
if (!d) continue;
const fillLc = String(style.fill || "none").toLowerCase();
const strokeLc = String(style.stroke || "none").toLowerCase();
let zBucket = 3;
if (fillLc === "#eef7f2" || strokeLc === "#cde7d8" || strokeLc === "#64748b") {
zBucket = 0;
} else if (fillLc === "#529b7a" || strokeLc === "#529b7a") {
zBucket = 1;
} else if (fillLc === "#fbbf24" || strokeLc === "#b45309") {
zBucket = 2;
}
const fOp = Number.isFinite(style.fillOpacity) ? style.fillOpacity * style.opacity : style.opacity;
const sOp = Number.isFinite(style.strokeOpacity) ? style.strokeOpacity * style.opacity : style.opacity;
const sWidth = Number.isFinite(style.strokeWidth) ? style.strokeWidth : 0.1;
const fRule = style.fillRule === "evenodd" ? "evenodd" : "nonzero";
const key = `${fillLc}|${fOp.toFixed(3)}|${strokeLc}|${sOp.toFixed(3)}|${sWidth.toFixed(3)}|${fRule}`;
let entry = buckets[zBucket].get(key);
if (!entry) {
entry = {
fill: fillLc,
fillOpacity: fOp,
stroke: strokeLc,
strokeOpacity: sOp,
strokeWidth: sWidth,
fillRule: fRule,
dParts: [],
};
buckets[zBucket].set(key, entry);
}
entry.dParts.push(d);
}
};
walk(root, rootStyle);
const batches = [];
for (const bucket of buckets) {
for (const entry of bucket.values()) {
if (!entry.dParts.length) continue;
batches.push({
path2D: new Path2D(entry.dParts.join(" ")),
fill: entry.fill,
fillOpacity: entry.fillOpacity,
stroke: entry.stroke,
strokeOpacity: entry.strokeOpacity,
strokeWidth: entry.strokeWidth,
fillRule: entry.fillRule,
});
}
}
return {batches, texts};
}
function loadCompiledVectorLayer(url) {
if (state.layerImageCache.has(url)) {
return state.layerImageCache.get(url);
}
const promise = fetch(url)
.then((res) => (res.ok ? res.text() : ""))
.then((svgText) => compileSvgToVectorLayer(svgText))
.catch(() => null);
state.layerImageCache.set(url, promise);
return promise;
}
function drawCompiledVectorLayer(ctx, compiled, showTexts = true) {
if (!compiled) return;
ctx.lineCap = "round";
ctx.lineJoin = "round";
for (const batch of compiled.batches) {
if (batch.fill && batch.fill !== "none" && batch.fillOpacity > 0) {
ctx.globalAlpha = batch.fillOpacity;
ctx.fillStyle = batch.fill;
ctx.fill(batch.path2D, batch.fillRule);
}
if (batch.stroke && batch.stroke !== "none" && batch.strokeOpacity > 0 && batch.strokeWidth > 0) {
ctx.globalAlpha = batch.strokeOpacity;
ctx.strokeStyle = batch.stroke;
ctx.lineWidth = batch.strokeWidth;
ctx.stroke(batch.path2D);
}
}
if (showTexts && compiled.texts.length > 0) {
ctx.globalAlpha = 1;
ctx.textBaseline = "alphabetic";
let lastFontSize = -1;
for (const item of compiled.texts) {
if (item.fontSize !== lastFontSize) {
lastFontSize = item.fontSize;
ctx.font = `700 ${item.fontSize}px Consolas, "Cascadia Mono", monospace`;
}
ctx.fillStyle = item.fill;
ctx.textAlign = item.textAnchor === "middle" ? "center" : (item.textAnchor === "end" ? "right" : "left");
ctx.fillText(item.text, item.x, item.y);
}
}
ctx.globalAlpha = 1;
}
function isLayerChecked(layerName) {
const input = dom["layer-controls"]?.querySelector(`input[value="${layerName}"]`);
return input ? input.checked : true;
}
async function prepareLayerBitmapCache() {
if (!state.data || typeof document === "undefined") return;
const ver = state.boardVersion || "v2_0";
const side = state.boardSide || "front";
const maskOn = isLayerChecked("mask");
const copperOn = isLayerChecked("copper");
const silkOn = isLayerChecked("silk");
const compositeKey = `${ver}:${side}:${maskOn ? 1 : 0}:${copperOn ? 1 : 0}:${silkOn ? 1 : 0}`;
if (state.layerCompositeKey === compositeKey && state.layerCompositeReady) {
renderLayerCanvasFrame();
return;
}
state.layerCompositeKey = compositeKey;
state.layerCompositeReady = false;
syncStaticLayerVisibility();
const assets = getLayerAssets(ver, side);
const [maskLayer, copperLayer, silkLayer] = await Promise.all([
maskOn ? loadCompiledVectorLayer(assets.mask) : Promise.resolve(null),
copperOn ? loadCompiledVectorLayer(assets.copper) : Promise.resolve(null),
silkOn ? loadCompiledVectorLayer(assets.silk) : Promise.resolve(null),
]);
if (state.layerCompositeKey !== compositeKey) return;
state.compiledVectorLayers = {maskLayer, copperLayer, silkLayer};
const bw = Math.max(boardWidth(), 1);
const bh = Math.max(boardHeight(), 1);
// Render a compact thumbnail canvas for the Bird's-Eye Minimap and 1x overview
const thumbW = 1320;
const thumbH = Math.max(Math.round((thumbW * bh) / bw), 180);
if (!state.layerCompositeCanvas) {
state.layerCompositeCanvas = document.createElement("canvas");
}
state.layerCompositeCanvas.width = thumbW;
state.layerCompositeCanvas.height = thumbH;
const offCtx = state.layerCompositeCanvas.getContext("2d", {alpha: true});
if (offCtx) {
offCtx.setTransform(1, 0, 0, 1, 0, 0);
offCtx.clearRect(0, 0, thumbW, thumbH);
const sx = thumbW / bw;
const sy = thumbH / bh;
offCtx.setTransform(sx, 0, 0, sy, 0, 0);
if (maskLayer) drawCompiledVectorLayer(offCtx, maskLayer, false);
if (copperLayer) drawCompiledVectorLayer(offCtx, copperLayer, false);
if (silkLayer) drawCompiledVectorLayer(offCtx, silkLayer, true);
state.layerCompositeReady = Boolean(maskLayer || copperLayer || silkLayer);
}
syncStaticLayerVisibility();
renderLayerCanvasFrame();
renderMinimap();
}
function syncStaticLayerVisibility() {
const layerCanvas = dom["board-layer-canvas"];
const assetLayers = dom["asset-layers"];
if (!layerCanvas || !assetLayers || !state.viewBox || !state.baseViewBox) return;
const photoActive = !dom["layer-photo"]?.hidden && Boolean(state.data?.photo_overlay);
const useVectorCanvas = state.perfUltraMode && state.layerCompositeReady && !photoActive;
layerCanvas.hidden = !useVectorCanvas;
assetLayers.style.display = useVectorCanvas ? "none" : "";
}
function renderLayerCanvasFrame() {
const canvas = dom["board-layer-canvas"];
if (!canvas || canvas.hidden || !state.layerCompositeReady || !state.viewBox) {
return;
}
const viewport = dom["board-viewport"];
const cw = viewport.clientWidth || 1;
const ch = viewport.clientHeight || 1;
const dpr = Math.min(window.devicePixelRatio || 1, 2.5);
const targetW = Math.round(cw * dpr);
const targetH = Math.round(ch * dpr);
if (canvas.width !== targetW || canvas.height !== targetH) {
canvas.width = targetW;
canvas.height = targetH;
}
const ctx = canvas.getContext("2d");
if (!ctx) return;
ctx.setTransform(1, 0, 0, 1, 0, 0);
ctx.clearRect(0, 0, targetW, targetH);
const {x: vx, y: vy, width: vw, height: vh} = state.viewBox;
const scale = Math.min(cw / Math.max(vw, 0.001), ch / Math.max(vh, 0.001));
const offsetX = (cw - vw * scale) * 0.5 - vx * scale;
const offsetY = (ch - vh * scale) * 0.5 - vy * scale;
ctx.setTransform(scale * dpr, 0, 0, scale * dpr, offsetX * dpr, offsetY * dpr);
const layers = state.compiledVectorLayers;
if (layers && (layers.maskLayer || layers.copperLayer || layers.silkLayer)) {
const zoomRatio = state.baseViewBox.width / Math.max(vw, 0.001);
const showSilkTexts = zoomRatio >= 1.3;
if (layers.maskLayer) drawCompiledVectorLayer(ctx, layers.maskLayer, false);
if (layers.copperLayer) drawCompiledVectorLayer(ctx, layers.copperLayer, false);
if (layers.silkLayer) drawCompiledVectorLayer(ctx, layers.silkLayer, showSilkTexts);
} else if (state.layerCompositeCanvas) {
ctx.drawImage(state.layerCompositeCanvas, 0, 0, boardWidth(), boardHeight());
}
}
function applyBoardSide() {
const assets = getLayerAssets(state.boardVersion || "v1_2", state.boardSide);
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;
}
prepareLayerBitmapCache();
}
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() {
state.selectedTouchpoint = null;
state.selectedResistor = null;
state.selectedPin = null;
state.searchResults = [];
dom["search-results"].hidden = true;
dom["selection-readout"].textContent = "未选择";
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";
state.layerCompositeKey = "";
state.layerCompositeReady = false;
buildEntityLookupMaps();
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;
const summaryText = `${board.name} · ${counts.touchpoints} 座子 · ${counts.resistors ?? 0} 电阻(背 ${backResistors}) · ${counts.connector_contacts} 个 CON 接触针`;
dom["board-summary"].textContent = summaryText;
dom["board-summary"].title = summaryText;
const railX = document.getElementById("coordinate-rail-x") || document.querySelector(".coordinate-rail");
if (railX) {
const halfW = Math.round(width / 2);
const fullW = Math.round(width);
railX.innerHTML = `0 mm${halfW} mm${fullW} mm`;
}
dom["board-loading"].hidden = true;
state.highlightAllSame = false;
state.peripheralHighlightedRefs = new Set();
dom["board-svg"].classList.add("pins-interactive");
dom["board-svg"].classList.toggle("perf-ultra", state.perfUltraMode);
cancelViewBoxAnimation();
renderBoardMarkers();
updateViewBox();
configurePhotoOverlay();
renderEmptyDetail(
"未选择座子或电阻",
`${counts.touchpoints} 个座子 · ${counts.resistors ?? 0} 个电阻 · ${counts.connector_contacts} 个 CON 接触针 · ${counts.connector_auxiliary_pads} 个 CON 辅助焊盘`,
);
renderPeripheralPanel();
renderCpldArchPanel();
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 getSelectionIndices() {
if (state.selectedResistor) {
const resIdx = state.resIndexMap.get(state.selectedResistor.reference) ?? -1;
let padIdx = -1;
if (state.selectedPin && Array.isArray(state.selectedResistor.pads)) {
padIdx = state.selectedResistor.pads.findIndex((p) => p.number === state.selectedPin.number);
}
return {selectedResistor: state.selectedResistor, resistorIndex: resIdx, padIndex: padIdx};
}
if (state.selectedTouchpoint) {
const tpIdx = state.tpIndexMap.get(state.selectedTouchpoint.reference) ?? -1;
let pinIdx = -1;
if (state.selectedPin && Array.isArray(state.selectedTouchpoint.pins)) {
pinIdx = state.selectedTouchpoint.pins.findIndex((p) => p.id === state.selectedPin.id);
}
return {selectedTouchpoint: state.selectedTouchpoint, touchpointIndex: tpIdx, pinIndex: pinIdx};
}
return null;
}
function tracePadGeometry(ctx, cx, cy, w, h, rotRad, isRound) {
if (isRound) {
const r = Math.min(w, h) * 0.5;
ctx.moveTo(cx + r, cy);
ctx.arc(cx, cy, r, 0, Math.PI * 2);
return;
}
const hw = w * 0.5;
const hh = h * 0.5;
if (Math.abs(rotRad) > 0.001) {
const c = Math.cos(rotRad);
const s = Math.sin(rotRad);
const ux = hw * c;
const uy = hw * s;
const vx = -hh * s;
const vy = hh * c;
ctx.moveTo(cx - ux - vx, cy - uy - vy);
ctx.lineTo(cx + ux - vx, cy + uy - vy);
ctx.lineTo(cx + ux + vx, cy + uy + vy);
ctx.lineTo(cx - ux + vx, cy - uy + vy);
ctx.closePath();
} else {
ctx.rect(cx - hw, cy - hh, w, h);
}
}
function renderFastCanvasFrame() {
const canvas = dom["board-fast-canvas"];
if (!canvas || !state.viewBox || !state.baseViewBox || !state.data) return;
const viewport = dom["board-viewport"];
const cw = viewport.clientWidth || 1;
const ch = viewport.clientHeight || 1;
const dpr = Math.min(window.devicePixelRatio || 1, 2.5);
const targetW = Math.round(cw * dpr);
const targetH = Math.round(ch * dpr);
if (canvas.width !== targetW || canvas.height !== targetH) {
canvas.width = targetW;
canvas.height = targetH;
}
const ctx = canvas.getContext("2d");
if (!ctx) return;
ctx.setTransform(1, 0, 0, 1, 0, 0);
ctx.clearRect(0, 0, targetW, targetH);
if (!state.perfUltraMode) {
if (dom["perf-mode-toggle"]) {
dom["perf-mode-toggle"].className = "perf-badge is-svg-mode";
dom["perf-mode-toggle"].textContent = "矢量 DOM 模式 (点击切换 Rust+WASM)";
}
return;
}
const t0 = performance.now();
const {x: vx, y: vy, width: vw, height: vh} = state.viewBox;
const scale = Math.min(cw / Math.max(vw, 0.001), ch / Math.max(vh, 0.001));
const offsetX = (cw - vw * scale) * 0.5 - vx * scale;
const offsetY = (ch - vh * scale) * 0.5 - vy * scale;
const zoomRatio = state.baseViewBox.width / Math.max(vw, 0.001);
ctx.setTransform(scale * dpr, 0, 0, scale * dpr, offsetX * dpr, offsetY * dpr);
const invScale = 1 / Math.max(scale, 0.1);
const culled = wasmAccel.cullViewport(
state.viewBox,
state.boardSide,
state.categories,
state.showShieldPins,
zoomRatio,
getSelectionIndices(),
);
if (culled && culled.count > 0) {
const buf = culled.buffer;
const count = culled.count;
// Pass 1: Contact pins (kind=2, role=0) batched for single GPU stroke/fill
ctx.beginPath();
for (let i = 0; i < count; i++) {
const base = i * 8;
const packed = buf[base + 5] | 0;
const kind = packed & 0x0f;
const role = (packed >> 4) & 0x0f;
const isRound = (packed & 256) !== 0;
const isShield = (packed & 512) !== 0;
const isSelected = (packed & 1024) !== 0;
if (kind !== 2 || role !== 0 || isShield || isSelected) continue;
const cx = buf[base];
const cy = buf[base + 1];
const w = buf[base + 2];
const h = buf[base + 3];
// Skip painting over large M3/M4 mounting holes that are already drawn on the PCB layer
if (isRound && w >= 5.5 && h >= 5.5) continue;
const rotRad = buf[base + 4];
tracePadGeometry(ctx, cx, cy, w, h, rotRad, isRound);
}
ctx.fillStyle = "rgba(251, 191, 36, 0.12)";
ctx.fill();
ctx.lineWidth = 0.95 * invScale;
ctx.strokeStyle = "rgba(180, 83, 9, 0.55)";
ctx.stroke();
// Pass 2: Shield pins (role=1) & unknown pins (role=3)
for (let i = 0; i < count; i++) {
const base = i * 8;
const packed = buf[base + 5] | 0;
const kind = packed & 0x0f;
const role = (packed >> 4) & 0x0f;
if (kind !== 2 || role === 0 || role === 2) continue;
const isRound = (packed & 256) !== 0;
const cx = buf[base];
const cy = buf[base + 1];
const w = buf[base + 2];
const h = buf[base + 3];
const rotRad = buf[base + 4];
ctx.beginPath();
tracePadGeometry(ctx, cx, cy, w, h, rotRad, isRound);
ctx.fillStyle = role === 1 ? "rgba(251, 191, 36, 0.25)" : "rgba(180, 35, 24, 0.12)";
ctx.fill();
ctx.lineWidth = 0.9 * invScale;
ctx.strokeStyle = role === 1 ? "#b45309" : "#b42318";
ctx.stroke();
}
// Pass 3: Resistor hotspots (kind=3) and resistor pads (kind=4) batched
if (state.categories.has("R")) {
ctx.beginPath();
for (let i = 0; i < count; i++) {
const base = i * 8;
const packed = buf[base + 5] | 0;
if ((packed & 0x0f) !== 3) continue;
const cx = buf[base];
const cy = buf[base + 1];
const w = buf[base + 2];
const h = buf[base + 3];
ctx.rect(cx - w * 0.5, cy - h * 0.5, w, h);
}
ctx.fillStyle = "rgba(99, 102, 241, 0.08)";
ctx.fill();
ctx.lineWidth = 0.85 * invScale;
ctx.strokeStyle = "rgba(99, 102, 241, 0.55)";
ctx.stroke();
ctx.beginPath();
for (let i = 0; i < count; i++) {
const base = i * 8;
const packed = buf[base + 5] | 0;
if ((packed & 0x0f) !== 4) continue;
const cx = buf[base];
const cy = buf[base + 1];
const w = buf[base + 2];
const h = buf[base + 3];
const rotRad = buf[base + 4];
tracePadGeometry(ctx, cx, cy, w, h, rotRad, false);
}
ctx.fillStyle = "rgba(99, 102, 241, 0.16)";
ctx.fill();
ctx.lineWidth = 0.9 * invScale;
ctx.strokeStyle = "#4f46e5";
ctx.stroke();
}
// Pass 4: Selected pin / pad exact contour & border highlight (NO oversized circle!)
for (let i = 0; i < count; i++) {
const base = i * 8;
const packed = buf[base + 5] | 0;
const kind = packed & 0x0f;
const isSelected = (packed & 1024) !== 0;
if (!isSelected || (kind !== 2 && kind !== 4)) continue;
const isRound = (packed & 256) !== 0;
const cx = buf[base];
const cy = buf[base + 1];
const w = buf[base + 2];
const h = buf[base + 3];
const rotRad = buf[base + 4];
ctx.beginPath();
tracePadGeometry(ctx, cx, cy, w, h, rotRad, isRound);
ctx.fillStyle = "rgba(16, 185, 129, 0.42)";
ctx.fill();
ctx.lineWidth = 2.4 * invScale;
ctx.strokeStyle = "#059669";
ctx.stroke();
ctx.lineWidth = 0.9 * invScale;
ctx.strokeStyle = "#ecfdf5";
ctx.stroke();
}
}
const drawMs = performance.now() - t0;
state.lastFrameMs = drawMs;
if (dom["perf-mode-toggle"]) {
dom["perf-mode-toggle"].className = "perf-badge";
const vis = wasmAccel.lastVisibleCount || 0;
const tot = wasmAccel.totalIndexedCount || 0;
dom["perf-mode-toggle"].textContent = `⚡ ${wasmAccel.engineType} · 视口 ${vis}/${tot} · ${drawMs.toFixed(2)}ms`;
}
}
function renderMinimap() {
const wrap = dom["board-minimap-wrap"];
const canvas = dom["board-minimap"];
if (!wrap || !canvas || !state.viewBox || !state.baseViewBox || !state.data) return;
const ratio = state.baseViewBox.width / Math.max(state.viewBox.width, 0.001);
if (ratio <= 1.08) {
wrap.hidden = true;
return;
}
wrap.hidden = false;
if (dom["minimap-zoom-badge"]) {
dom["minimap-zoom-badge"].textContent = `${Math.round(ratio * 100)}%`;
}
const ctx = canvas.getContext("2d");
if (!ctx) return;
const mw = canvas.width;
const mh = canvas.height;
ctx.clearRect(0, 0, mw, mh);
const bx = state.baseViewBox.x;
const by = state.baseViewBox.y;
const bw = Math.max(state.baseViewBox.width, 1);
const bh = Math.max(state.baseViewBox.height, 1);
const scale = Math.min(mw / bw, mh / bh);
const ox = (mw - bw * scale) * 0.5 - bx * scale;
const oy = (mh - bh * scale) * 0.5 - by * scale;
// Draw board outline or pre-rasterized layer thumbnail
const boardW = boardWidth();
const boardH = boardHeight();
if (state.layerCompositeReady && state.layerCompositeCanvas) {
ctx.drawImage(
state.layerCompositeCanvas,
ox,
oy,
boardW * scale,
boardH * scale,
);
} else {
ctx.fillStyle = "#dcfce7";
ctx.strokeStyle = "#16a34a";
ctx.lineWidth = 1;
ctx.fillRect(ox, oy, boardW * scale, boardH * scale);
ctx.strokeRect(ox, oy, boardW * scale, boardH * scale);
}
// Draw selected target indicator on minimap if present
const selTarget = state.selectedResistor || state.selectedTouchpoint;
if (selTarget?.view_position) {
const pt = toDisplayPoint(selTarget.view_position);
ctx.fillStyle = "#f59e0b";
ctx.beginPath();
ctx.arc(ox + pt.x * scale, oy + pt.y * scale, 3, 0, Math.PI * 2);
ctx.fill();
}
// Draw current viewport rectangle
const vx = ox + state.viewBox.x * scale;
const vy = oy + state.viewBox.y * scale;
const vw = Math.max(state.viewBox.width * scale, 4);
const vh = Math.max(state.viewBox.height * scale, 4);
ctx.fillStyle = "rgba(2, 132, 199, 0.22)";
ctx.fillRect(vx, vy, vw, vh);
ctx.strokeStyle = "#0284c7";
ctx.lineWidth = 1.6;
ctx.strokeRect(vx, vy, vw, vh);
}
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 / Math.max(width, 0.001);
const pct = Math.round(ratio * 100);
const pctText = `${pct}%`;
dom["zoom-readout"].textContent = pctText;
if (dom["hud-zoom-value"]) dom["hud-zoom-value"].textContent = pctText;
if (dom["zoom-slider"]) {
dom["zoom-slider"].value = String(Math.min(Math.max(pct, 80), 3500));
}
if (dom["zoom-hud-dock"]) {
const presetBtns = dom["zoom-hud-dock"].querySelectorAll(".hud-preset-btn[data-zoom]");
for (const btn of presetBtns) {
const targetZ = Number(btn.dataset.zoom);
btn.classList.toggle("is-active", Math.abs(ratio - targetZ) < targetZ * 0.12);
}
}
syncStaticLayerVisibility();
renderLayerCanvasFrame();
renderFastCanvasFrame();
renderMinimap();
}
function scheduleViewBoxUpdate() {
if (state.rafViewBoxId) return;
state.rafViewBoxId = window.requestAnimationFrame(() => {
state.rafViewBoxId = 0;
updateViewBox();
});
}
function cancelViewBoxAnimation() {
if (state.animViewBoxId) {
window.cancelAnimationFrame(state.animViewBoxId);
state.animViewBoxId = 0;
}
if (state.rafViewBoxId) {
window.cancelAnimationFrame(state.rafViewBoxId);
state.rafViewBoxId = 0;
}
}
function animateViewBoxTo(target, durationMs = 220) {
cancelViewBoxAnimation();
if (!state.viewBox || !target || durationMs <= 0) {
state.viewBox = {...target};
clampViewBox();
updateViewBox();
return;
}
const start = {...state.viewBox};
const dest = {...target};
const startTime = performance.now();
const step = (now) => {
const t = Math.min(Math.max((now - startTime) / durationMs, 0), 1);
const ease = 1 - Math.pow(1 - t, 3);
state.viewBox = {
x: start.x + (dest.x - start.x) * ease,
y: start.y + (dest.y - start.y) * ease,
width: start.width + (dest.width - start.width) * ease,
height: start.height + (dest.height - start.height) * ease,
};
clampViewBox();
updateViewBox();
if (t < 1) {
state.animViewBoxId = window.requestAnimationFrame(step);
} else {
state.animViewBoxId = 0;
}
};
state.animViewBoxId = window.requestAnimationFrame(step);
}
function effectiveBounds(bounds, minimum = 1.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 updateSelectionVisuals() {
const selTpRef = state.selectedTouchpoint?.reference || "";
const selResRef = state.selectedResistor?.reference || "";
const selPinId = state.selectedPin?.id || "";
const selPadNum = state.selectedPin?.number || "";
for (const node of dom["hotspot-layer"].children) {
const ref = node.dataset?.reference || "";
const isRes = node.dataset?.kind === "resistor";
const isSelected = isRes ? ref === selResRef : ref === selTpRef;
const isPeriph = !isRes && state.peripheralHighlightedRefs?.has(ref);
node.classList.toggle("is-selected", isSelected);
node.classList.toggle("is-peripheral-match", Boolean(isPeriph));
}
if (!state.perfUltraMode) {
for (const group of dom["pin-layer"].children) {
const ref = group.dataset?.reference || "";
const isRes = group.dataset?.kind === "resistor";
const isSelected = isRes
? (ref === selResRef && group.dataset?.pin === String(selPadNum))
: (ref === selTpRef && group.dataset?.pinId === String(selPinId));
group.classList.toggle("is-selected", isSelected);
}
}
renderSelectionOverlay();
renderFastCanvasFrame();
}
function renderBoardMarkers() {
dom["hotspot-layer"].replaceChildren();
dom["pin-layer"].replaceChildren();
if (!state.data) return;
dom["board-svg"].classList.toggle("perf-ultra", state.perfUltraMode);
const hotspotFrag = document.createDocumentFragment();
const pinFrag = document.createDocumentFragment();
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 isPeripheralMatch = state.peripheralHighlightedRefs?.has(touchpoint.reference);
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" : ""}${isPeripheralMatch ? " is-peripheral-match" : ""}`,
tabindex: 0,
role: "button",
"aria-label": `${touchpoint.reference} ${touchpointKindLabel(touchpoint)} ${touchpointPinSummary(touchpoint)}`,
"data-reference": touchpoint.reference,
"data-side": touchpoint.side || "front",
});
hotspotFrag.append(hotspot);
if (!state.perfUltraMode) {
for (const pin of touchpoint.pins) {
const isSh = isShieldPin(pin);
if (isSh && !state.showShieldPins) continue;
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: 0,
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 pw = Number(pin.size?.width) || 1.4;
const ph = Number(pin.size?.height) || 1.4;
const rot = Number(pin.rotation || 0.0);
const isRound = pin.shape === "circle" || (!pin.shape && Math.abs(pw - ph) < 0.05);
const dotEl = isRound
? svgElement("circle", {cx: point.x, cy: point.y, r: pw / 2, class: "pin-dot"})
: svgElement("rect", {x: point.x - pw / 2, y: point.y - ph / 2, width: pw, height: ph, rx: 0.1, class: "pin-dot"});
if (rot !== 0) group.setAttribute("transform", `rotate(${rot} ${point.x} ${point.y})`);
group.append(dotEl);
pinFrag.append(group);
}
}
}
for (const resistor of state.data.resistors ?? []) {
if (!state.categories.has("R")) continue;
if (!itemVisibleOnSide(resistor, state.boardSide)) continue;
visibleResistors += 1;
if (!state.perfUltraMode) {
const bounds = effectiveBounds(toDisplayBounds(resistor.view_bounds), 0.4);
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",
});
hotspotFrag.append(hotspot);
}
}
dom["hotspot-layer"].append(hotspotFrag);
if (!state.perfUltraMode) dom["pin-layer"].append(pinFrag);
const sideLabel = state.boardSide === "back" ? "背面" : "正面";
dom["visible-count"].textContent = `${sideLabel} · ${visibleTouchpoints} 个座子 · ${visibleResistors} 个电阻`;
renderSelectionOverlay();
renderFastCanvasFrame();
}
function showTouchpointTooltip(event, touchpoint) {
dom["board-tooltip"].replaceChildren();
const periph = classifyTouchpointPeripheral(touchpoint, state.boardVersion);
const key = element("div", "tooltip-key", `${touchpoint.reference} · ${periph.peripheralLabel}`);
const usageText = periph.isUsed ? "已启用外设" : (periph.isSpareConnector ? "空余插座" : "板级节点");
const detail = element("div", "tooltip-role", `${usageText} · ${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();
const logical = resolveLogicalPin(touchpoint, pin, state.boardVersion);
dom["board-tooltip"].append(
element("div", "tooltip-key", `${touchpoint.reference}.${pin.number || "机械孔"}`),
element("div", "tooltip-role", logical.displayBadge),
element("div", "", `${logical.peripheralRole} · 网络: ${pin.net || "无命名网络"}`),
element("div", "", logical.pinDefinition || 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() {
state.hoverTargetKey = "";
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 appendExactNetPadHighlight(layer, pad, isResistorPad) {
const point = toDisplayPoint(pad.view_position);
const width = Math.max(Number(pad.size?.width) || 0, Number(pad.view_bounds?.width) || 0, 0.35);
const height = Math.max(Number(pad.size?.height) || 0, Number(pad.view_bounds?.height) || 0, 0.35);
let rotation = Number(pad.rotation) || 0;
if (state.boardSide === "back") rotation = -rotation;
const shape = String(pad.shape || "").toLowerCase();
const isRound =
shape === "circle"
|| shape === "round"
|| (!shape && Math.abs(width - height) < 0.05 && !isResistorPad);
const cls = `net-highlight${isResistorPad ? " net-resistor" : ""}`;
if (isRound) {
layer.append(
svgElement("circle", {
cx: point.x,
cy: point.y,
r: Math.min(width, height) * 0.5,
class: cls,
}),
);
return;
}
const attrs = {
x: point.x - width * 0.5,
y: point.y - height * 0.5,
width,
height,
rx: Math.min(width, height) * 0.16,
class: cls,
};
if (Math.abs(rotation) > 0.01) {
attrs.transform = `rotate(${rotation} ${point.x} ${point.y})`;
}
layer.append(svgElement("rect", attrs));
}
function appendSelectedPinMarker(layer, pin) {
if (!pin?.view_position) return;
const point = toDisplayPoint(pin.view_position);
const width = Math.max(Number(pin.size?.width) || 0, Number(pin.view_bounds?.width) || 0, 0.35);
const height = Math.max(Number(pin.size?.height) || 0, Number(pin.view_bounds?.height) || 0, 0.35);
let rotation = Number(pin.rotation) || 0;
if (state.boardSide === "back") rotation = -rotation;
const shape = String(pin.shape || "").toLowerCase();
const isRound =
shape === "circle"
|| shape === "round"
|| (!shape && Math.abs(width - height) < 0.05);
if (isRound) {
layer.append(
svgElement("circle", {
cx: point.x,
cy: point.y,
r: Math.min(width, height) * 0.5,
class: "selected-pin-marker",
}),
);
return;
}
const attrs = {
x: point.x - width * 0.5,
y: point.y - height * 0.5,
width,
height,
rx: Math.min(width, height) * 0.16,
class: "selected-pin-marker",
};
if (Math.abs(rotation) > 0.01) {
attrs.transform = `rotate(${rotation} ${point.x} ${point.y})`;
}
layer.append(svgElement("rect", attrs));
}
function renderSelectionOverlay() {
dom["selection-layer"].replaceChildren();
dom["net-layer"].replaceChildren();
const target = state.selectedResistor || state.selectedTouchpoint;
if (target && itemVisibleOnSide(target, state.boardSide)) {
const bounds = effectiveBounds(toDisplayBounds(target.view_bounds), state.selectedResistor ? 0.65 : 1.3);
const pad = state.selectedResistor ? 0.18 : 0.32;
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: state.selectedResistor ? 0.22 : 0.38, class: "selection-reticle"}),
);
if (state.selectedResistor) {
for (const resistorPad of state.selectedResistor.pads ?? []) {
appendResistorPadMarker(dom["selection-layer"], resistorPad);
}
} else if (state.selectedPin) {
appendSelectedPinMarker(dom["selection-layer"], state.selectedPin);
}
}
// Only highlight all same-net / same-function points across the board when Ctrl+Click (highlightAllSame) is active
if (!state.highlightAllSame) return;
const seenPads = new Set();
const addPadHighlight = (pad, isResistorPad, key) => {
if (!pad?.view_position || seenPads.has(key)) return;
seenPads.add(key);
appendExactNetPadHighlight(dom["net-layer"], pad, isResistorPad);
};
const net = state.selectedPin?.net;
if (net) {
for (const item of sameNetMembers(state.data, net)) {
const ownerSide = item.resistor?.side || item.touchpoint?.side || "front";
if (ownerSide !== state.boardSide) continue;
const key = `${item.kind}:${item.reference}:${item.pin.id || item.pin.number}`;
addPadHighlight(item.pin, item.kind === "resistor_pad", key);
}
}
// If Ctrl-clicked a functional pin (e.g., PTC / FAN / TEMP / LIMIT / MOTOR), also highlight same-function pins
if (state.selectedTouchpoint && state.selectedPin) {
const selLogical = resolveLogicalPin(state.selectedTouchpoint, state.selectedPin, state.boardVersion);
const cat = selLogical.peripheralCategory;
if (cat && cat !== "OTHER" && cat !== "SPAR" && selLogical.chip !== "GND") {
for (const tp of state.data?.touchpoints ?? []) {
if (!itemVisibleOnSide(tp, state.boardSide)) continue;
if (!state.categories.has(tp.category)) continue;
for (const p of tp.pins ?? []) {
if (isShieldPin(p) && !state.showShieldPins) continue;
const candLogical = resolveLogicalPin(tp, p, state.boardVersion);
if (
candLogical.peripheralCategory === cat &&
candLogical.chip === selLogical.chip &&
p.pad_role === state.selectedPin.pad_role
) {
addPadHighlight(p, false, `pin:${tp.reference}:${p.id || p.number}`);
}
}
}
}
}
}
function selectTouchpoint(touchpoint, pin = null, openDrawer = false, options = {}) {
const highlightAllSame = Boolean(options?.highlightAllSame);
state.highlightAllSame = highlightAllSame;
const sideFlipped = ensureItemSide(touchpoint);
state.selectedTouchpoint = touchpoint;
state.selectedResistor = null;
state.selectedPin = pin;
if (highlightAllSame && touchpoint && !pin) {
const targetPeriph = classifyTouchpointPeripheral(touchpoint, state.boardVersion);
const sameRefs = new Set();
for (const tp of state.data?.touchpoints ?? []) {
if (!itemVisibleOnSide(tp, state.boardSide)) continue;
const p = classifyTouchpointPeripheral(tp, state.boardVersion);
if (
p.peripheralCategory === targetPeriph.peripheralCategory &&
p.isSpareConnector === targetPeriph.isSpareConnector
) {
sameRefs.add(tp.reference);
}
}
state.peripheralHighlightedRefs = sameRefs;
} else {
state.peripheralHighlightedRefs = new Set();
}
if (pin) {
const logical = resolveLogicalPin(touchpoint, pin, state.boardVersion);
const modeSuffix = highlightAllSame ? " · [Ctrl 同类全标]" : "";
dom["selection-readout"].textContent = `${touchpoint.reference}.${pin.number || "机械孔"} · ${logical.displayBadge}${modeSuffix}`;
} else {
const modeSuffix = highlightAllSame ? " · [Ctrl 同类全标]" : "";
dom["selection-readout"].textContent = `${touchpoint.reference} · ${touchpointPinSummary(touchpoint)}${modeSuffix}`;
}
if (openDrawer) setDrawerCollapsed(false);
if (sideFlipped) {
renderBoardMarkers();
} else {
updateSelectionVisuals();
}
renderDetail();
}
function selectResistor(resistor, pad = null, openDrawer = false, options = {}) {
const highlightAllSame = Boolean(options?.highlightAllSame);
state.highlightAllSame = highlightAllSame;
state.peripheralHighlightedRefs = new Set();
const sideFlipped = 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" ? " · 背面" : "";
const modeSuffix = highlightAllSame ? " · [Ctrl 同网全标]" : "";
dom["selection-readout"].textContent = pad
? `${resistor.reference}.${pad.number || "机械孔"} · ${pad.net || "无网络"}${sideNote}${modeSuffix}`
: `${resistor.reference} · ${resistor.component_value || "阻值未标注"} · ${nets.join(" ↔ ") || "无网络"}${sideNote}${modeSuffix}`;
if (openDrawer) setDrawerCollapsed(false);
if (sideFlipped) {
renderBoardMarkers();
} else {
updateSelectionVisuals();
}
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 logicalBadgeClass(logical) {
const chip = String(logical?.chip || "").toUpperCase();
if (chip.includes("FPGA")) return "logical-pin-badge is-fpga";
if (chip.includes("MCU")) return "logical-pin-badge is-mcu";
if (chip === "GND") return "logical-pin-badge is-gnd";
return "logical-pin-badge is-power";
}
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", (event) =>
selectTouchpoint(touchpoint, pin, true, {highlightAllSame: Boolean(event.ctrlKey || event.metaKey)}),
);
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 logical = resolveLogicalPin(touchpoint, pin, state.boardVersion);
const primary = element("span", "pin-primary");
primary.append(
element("span", "pin-summary", `${logical.peripheralRole} — ${pin.summary || logical.pinDefinition}`),
element("span", logicalBadgeClass(logical), `逻辑管脚:${logical.displayBadge}`),
element("span", "pin-net", `原始网络:${pin.net || "无命名网络"} · 电平:${pin.external_level || "未知"}`),
);
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", (event) =>
selectTouchpoint(touchpoint, pin, true, {highlightAllSame: Boolean(event.ctrlKey || event.metaKey)}),
);
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 periph = classifyTouchpointPeripheral(touchpoint, state.boardVersion);
const heading = element("div", "detail-heading");
const headingText = element("div");
headingText.append(element("h2", "detail-reference", touchpoint.reference), element("p", "detail-summary", touchpoint.summary));
const badgeCluster = element("div", "detail-badge-cluster");
badgeCluster.append(
element("span", `category-tag ${periph.isUsed ? "is-used-tag" : (periph.isSpareConnector ? "is-spare-tag" : "")}`, `${periph.peripheralLabel} · ${periph.isUsed ? "已用" : (periph.isSpareConnector ? "空余插座" : "板级")}`),
);
heading.append(headingText, badgeCluster);
const facts = element("div", "detail-facts");
if (touchpoint.connector) {
facts.append(
fact("外设归类", `${periph.peripheralLabel} (${periph.isUsed ? "项目已用" : "空余插座"})`),
fact("接触针 / 焊盘", `${touchpoint.connector.contact_count} 接触针 / ${touchpoint.pins.length} 总焊盘`),
fact("板面", touchpoint.side === "front" ? "正面" : "背面"),
fact("坐标 / 旋转", `${formatNumber(touchpoint.position.x)} / ${formatNumber(touchpoint.position.y)} mm · ${formatNumber(touchpoint.rotation, 1)}°`),
);
} else {
facts.append(
fact("外设归类", periph.peripheralLabel),
fact("针脚数量", touchpoint.pins.length),
fact("板面", touchpoint.side === "front" ? "正面" : "背面"),
fact("坐标", `${formatNumber(touchpoint.position.x)} / ${formatNumber(touchpoint.position.y)} mm`),
);
}
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 ? "接触针与 FPGA/MCU 逻辑管脚(板正面顺序)" : "接触针与 FPGA/MCU 逻辑管脚(板数据库编号)",
contactPins,
);
if (state.showShieldPins) {
appendPinSection(dom["detail-content"], touchpoint, "屏蔽与机械焊盘", auxiliaryPins);
}
} else {
const pinsToShow = state.showShieldPins ? touchpoint.pins : touchpoint.pins.filter((pin) => !isShieldPin(pin));
appendPinSection(dom["detail-content"], touchpoint, "针脚与 FPGA/MCU 逻辑管脚", pinsToShow);
}
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", (event) =>
selectResistor(resistor, item, true, {highlightAllSame: Boolean(event.ctrlKey || event.metaKey)}),
);
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", (event) => {
const ctrlMulti = Boolean(event.ctrlKey || event.metaKey);
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, {highlightAllSame: ctrlMulti});
focusOnTouchpoint(item.resistor);
} else if (item.touchpoint) {
state.categories.add(item.touchpoint.category);
selectTouchpoint(item.touchpoint, item.pin, true, {highlightAllSame: ctrlMulti});
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 logical = resolveLogicalPin(touchpoint, pin, state.boardVersion);
const logicalBox = element("div", "logical-pin-summary-box");
logicalBox.append(
element("div", "logical-pin-box-title", "FPGA / MCU 逻辑管脚与引脚定义"),
element("div", logicalBadgeClass(logical), logical.displayBadge),
element("div", "logical-pin-role", `外设角色:${logical.peripheralRole}`),
element("div", "logical-pin-def", `电气定义:${logical.pinDefinition}`),
);
wrapper.append(logicalBox);
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}`
: logical.chip;
const devicePin = pin.fpga?.ball
? `FPGA U3.${pin.fpga.ball} (${logical.logicalSignal})`
: pin.mcu
? `${pin.mcu.device}.${pin.mcu.pin} (${pin.mcu.signal})`
: logical.physicalPin;
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("逻辑管脚", logical.logicalSignal),
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", pin.evidence_tier === "cross_verified" ? "已交叉核对的板内路径" : "路径注释(含推断,不能据此确认导通)"));
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", (event) => {
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, {highlightAllSame: Boolean(event.ctrlKey || event.metaKey)});
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", (event) => {
state.categories.add("R");
const checkbox = dom["category-filters"].querySelector('input[value="R"]');
if (checkbox) checkbox.checked = true;
selectResistor(resistor, null, true, {highlightAllSame: Boolean(event.ctrlKey || event.metaKey)});
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);
const noteRow = element("div", "info-note net-highlight-note");
const statusText = state.highlightAllSame
? `同网成员 ${netMatches.length} 个(座子+电阻),已按 Ctrl 全板同步高亮所有同功能/同网点位。`
: `同网成员 ${netMatches.length} 个(座子+电阻),当前仅标注本引脚(按住 Ctrl 点击可全板标出)。`;
const toggleBtn = element(
"button",
`net-highlight-toggle-btn${state.highlightAllSame ? " is-active" : ""}`,
state.highlightAllSame ? "仅标当前点位" : "全板标出同网点位 (Ctrl+点击)",
);
toggleBtn.type = "button";
toggleBtn.addEventListener("click", () => {
state.highlightAllSame = !state.highlightAllSame;
updateSelectionVisuals();
renderDetail();
});
noteRow.append(element("span", "", statusText), toggleBtn);
wrapper.append(noteRow);
}
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", (event) => {
switchTab("detail");
selectTouchpoint(candidate.touchpoint, candidate.pin, true, {
highlightAllSame: Boolean(event.ctrlKey || event.metaKey),
});
focusOnTouchpoint(candidate.touchpoint);
});
dom["candidate-list"].append(row);
}
}
function renderPeripheralPanel() {
const container = dom["peripheral-content"];
if (!container || !state.data) return;
container.replaceChildren();
const catalog = filterPeripheralCatalog(state.data, state.boardVersion, {
category: state.peripheralCategory,
usage: state.peripheralUsage,
query: state.peripheralQuery,
});
const isFiltered = state.peripheralCategory !== "ALL" || state.peripheralUsage !== "all" || Boolean(state.peripheralQuery.trim());
state.peripheralHighlightedRefs = (isFiltered && state.highlightAllSame)
? new Set(catalog.filteredItems.map((item) => item.reference))
: new Set();
if (state.activeTab === "peripheral") {
updateSelectionVisuals();
}
const wrapper = element("div", "peripheral-panel");
// 1. Header & Sync Status Bar
const syncBox = element("div", "peripheral-sync-box");
const syncHeader = element("div", "peripheral-sync-header");
syncHeader.append(
element("strong", "", `电气外设与 FPGA/MCU 接线总表 (${state.data.board?.name || state.boardVersion})`),
element("span", "evidence-tag verified", `已用 ${catalog.usedCount} · 空余插座 ${catalog.spareCount}`),
);
const syncNote = element(
"div",
"peripheral-sync-note",
"全板电气接线同步入口:python3 tools/board-viewer/board_viewer.py sync-wiring(只同步已有生成包的接线说明;源文件变化后请先重新生成并校验,不能代替原生网表核对)。",
);
syncBox.append(syncHeader, syncNote);
wrapper.append(syncBox);
// 2. Quick-Jump Chips (PTC1, JTAG, HOST TTL, FAN, 空余插座, etc.)
if (catalog.quickChips?.length) {
const chipSection = element("div", "peripheral-chip-section");
chipSection.append(element("div", "peripheral-sub-label", "常用外设一键索引:"));
const chipRow = element("div", "peripheral-quick-chips");
for (const chip of catalog.quickChips) {
const isChipActive =
state.peripheralCategory === (chip.category || "ALL") &&
state.peripheralUsage === (chip.usage || "all") &&
state.peripheralQuery === (chip.query || "");
const btn = element("button", `peripheral-chip${isChipActive ? " is-active" : ""}`, chip.label);
btn.type = "button";
btn.addEventListener("click", (event) => {
const ctrlMulti = Boolean(event.ctrlKey || event.metaKey);
state.highlightAllSame = ctrlMulti;
state.peripheralCategory = chip.category || "ALL";
state.peripheralUsage = chip.usage || "all";
state.peripheralQuery = chip.query || "";
renderPeripheralPanel();
const updated = filterPeripheralCatalog(state.data, state.boardVersion, {
category: state.peripheralCategory,
usage: state.peripheralUsage,
query: state.peripheralQuery,
});
if (updated.filteredItems.length === 1) {
const item = updated.filteredItems[0];
const matchedPin = item.matchedPinNumbers?.length === 1
? item.touchpoint.pins.find((p) => String(p.number) === String(item.matchedPinNumbers[0]))
: null;
selectTouchpoint(item.touchpoint, matchedPin || null, false, {highlightAllSame: ctrlMulti});
focusOnTouchpoint(item.touchpoint);
}
});
chipRow.append(btn);
}
if (isFiltered) {
const clearBtn = element("button", "peripheral-chip is-reset", "✕ 重置筛选");
clearBtn.type = "button";
clearBtn.addEventListener("click", () => {
state.highlightAllSame = false;
state.peripheralCategory = "ALL";
state.peripheralUsage = "all";
state.peripheralQuery = "";
renderPeripheralPanel();
});
chipRow.append(clearBtn);
}
chipSection.append(chipRow);
wrapper.append(chipSection);
}
// 3. Search input + Usage filter (全部 / 已用外设 / 空余插座)
const filterBar = element("div", "peripheral-filter-bar");
const searchInput = element("input", "peripheral-search-input");
searchInput.type = "search";
searchInput.placeholder = "筛选外设 / 插座 / 管脚 (如 PTC1, JTAG, CON140, FAN, M1, LS1, T11)...";
searchInput.value = state.peripheralQuery;
searchInput.setAttribute("aria-label", "筛选外设或逻辑管脚");
searchInput.addEventListener("input", (e) => {
state.peripheralQuery = e.target.value;
const caret = searchInput.selectionStart;
renderPeripheralPanel();
const nextInput = dom["peripheral-content"].querySelector(".peripheral-search-input");
if (nextInput instanceof HTMLInputElement) {
nextInput.focus();
if (caret != null) nextInput.setSelectionRange(caret, caret);
}
});
const usageGroup = element("div", "peripheral-usage-tabs");
const usageOptions = [
{id: "all", label: `全部 (${catalog.items.length})`},
{id: "used", label: `已用外设 (${catalog.usedCount})`},
{id: "spare", label: `空余插座 (${catalog.spareCount})`},
];
for (const opt of usageOptions) {
const uBtn = element("button", `peripheral-usage-btn${state.peripheralUsage === opt.id ? " is-active" : ""}`, opt.label);
uBtn.type = "button";
uBtn.addEventListener("click", (event) => {
state.highlightAllSame = Boolean(event.ctrlKey || event.metaKey);
state.peripheralUsage = opt.id;
renderPeripheralPanel();
});
usageGroup.append(uBtn);
}
filterBar.append(searchInput, usageGroup);
wrapper.append(filterBar);
// 4. Category pills (PTC, FAN, UART, JTAG, MOTOR, LIMIT, TEMP, SSR, GPIO, MCU, POWER)
const catGrid = element("div", "peripheral-category-pills");
for (const catKey of PERIPHERAL_TYPE_ORDER) {
const count = catalog.categoryCounts[catKey] ?? 0;
if (catKey !== "ALL" && count === 0) continue;
const labelText = `${PERIPHERAL_TYPE_LABELS[catKey] || catKey} (${count})`;
const cBtn = element("button", `peripheral-cat-btn${state.peripheralCategory === catKey ? " is-active" : ""}`, labelText);
cBtn.type = "button";
cBtn.dataset.category = catKey;
cBtn.addEventListener("click", (event) => {
state.highlightAllSame = Boolean(event.ctrlKey || event.metaKey);
state.peripheralCategory = catKey;
renderPeripheralPanel();
});
catGrid.append(cBtn);
}
wrapper.append(catGrid);
// 5. Filtered Result Count Summary
const resultHeader = element("div", "peripheral-result-header");
resultHeader.append(
element("span", "", `命中 ${catalog.filteredItems.length} 个插座/接触点`),
element("span", "mono", "点击仅标单点 · 按住 Ctrl 点击全板标出同功能点位"),
);
wrapper.append(resultHeader);
// 6. Connector & Logical Pin Cards
if (!catalog.filteredItems.length) {
const empty = element("div", "empty-panel");
empty.append(
element("strong", "", "当前筛选条件下无匹配外设或插座"),
element("span", "empty-stats", "请点击「重置筛选」或切换外设分类 / 空余插座条件"),
);
wrapper.append(empty);
container.append(wrapper);
return;
}
const cardList = element("div", "peripheral-card-list");
for (const item of catalog.filteredItems) {
const isSelectedCard = state.selectedTouchpoint?.reference === item.reference;
const card = element("article", `peripheral-card${isSelectedCard ? " is-selected" : ""}${item.isSpareConnector ? " is-spare" : ""}`);
card.dataset.reference = item.reference;
const cardHead = element("div", "peripheral-card-head");
const titleGroup = element("div", "peripheral-card-title-group");
const refBtn = element("button", "peripheral-ref-btn", item.reference);
refBtn.type = "button";
refBtn.title = "在电路板上定位该插座(按住 Ctrl 点击全板标出同类)";
refBtn.addEventListener("click", (event) => {
const ctrlMulti = Boolean(event.ctrlKey || event.metaKey);
state.categories.add(item.touchpoint.category);
const checkbox = dom["category-filters"]?.querySelector(`input[value="${item.touchpoint.category}"]`);
if (checkbox) checkbox.checked = true;
selectTouchpoint(item.touchpoint, null, false, {highlightAllSame: ctrlMulti});
focusOnTouchpoint(item.touchpoint);
renderPeripheralPanel();
});
const catBadge = element("span", "peripheral-type-badge", item.peripheralLabel);
const statusBadge = element(
"span",
`peripheral-status-badge ${item.isUsed ? "status-used" : (item.isSpareConnector ? "status-spare" : "status-board")}`,
item.isUsed ? "已用外设" : (item.isSpareConnector ? "空余插座" : "板级节点"),
);
titleGroup.append(refBtn, catBadge, statusBadge);
const detailJumpBtn = element("button", "peripheral-jump-btn", "详情 ↗");
detailJumpBtn.type = "button";
detailJumpBtn.title = "打开该插座完整物理与选脚详情";
detailJumpBtn.addEventListener("click", (event) => {
const ctrlMulti = Boolean(event.ctrlKey || event.metaKey);
state.categories.add(item.touchpoint.category);
const checkbox = dom["category-filters"]?.querySelector(`input[value="${item.touchpoint.category}"]`);
if (checkbox) checkbox.checked = true;
selectTouchpoint(item.touchpoint, null, true, {highlightAllSame: ctrlMulti});
focusOnTouchpoint(item.touchpoint);
switchTab("detail");
});
cardHead.append(titleGroup, detailJumpBtn);
card.append(cardHead);
card.append(element("div", "peripheral-card-summary", item.roleTitle));
// Pin table with explicit FPGA / MCU logical pin for every pin
const pinTable = element("div", "peripheral-pin-table");
for (const rp of item.pins) {
const isPinMatched = item.matchedPinNumbers?.includes(rp.pinNumber);
const isPinSelected = isSelectedCard && state.selectedPin?.id === rp.pin.id;
const pinRow = element(
"button",
`peripheral-pin-row${isPinMatched ? " is-query-match" : ""}${isPinSelected ? " is-selected" : ""}`,
);
pinRow.type = "button";
pinRow.dataset.pin = rp.pinNumber;
const pinNumCol = element("span", "peripheral-pin-num", `Pin ${rp.pinNumber}`);
const pinBodyCol = element("span", "peripheral-pin-body");
const topLine = element("span", "peripheral-pin-top");
topLine.append(
element("span", "peripheral-pin-role", rp.logical.peripheralRole),
element("span", logicalBadgeClass(rp.logical), rp.logical.displayBadge),
);
const defLine = element(
"span",
"peripheral-pin-def",
`${rp.logical.pinDefinition} · 网络: ${rp.net || "无"} · 电平: ${rp.level || "未知"}`,
);
pinBodyCol.append(topLine, defLine);
pinRow.append(pinNumCol, pinBodyCol);
pinRow.addEventListener("click", (event) => {
const ctrlMulti = Boolean(event.ctrlKey || event.metaKey);
state.categories.add(item.touchpoint.category);
const checkbox = dom["category-filters"]?.querySelector(`input[value="${item.touchpoint.category}"]`);
if (checkbox) checkbox.checked = true;
selectTouchpoint(item.touchpoint, rp.pin, false, {highlightAllSame: ctrlMulti});
focusOnTouchpoint(item.touchpoint);
renderPeripheralPanel();
});
pinTable.append(pinRow);
}
card.append(pinTable);
cardList.append(card);
}
wrapper.append(cardList);
container.append(wrapper);
}
async function jumpToBoardTarget(pill, event = null) {
if (!pill) return;
const ctrlMulti = Boolean(event?.ctrlKey || event?.metaKey);
const targetRef = pill.ref || pill.query;
if (!targetRef) return;
if (pill.version && pill.version !== state.boardVersion) {
const url = new URL(window.location.href);
url.searchParams.set("version", pill.version);
window.history.replaceState({}, "", url.toString());
await loadApplication(pill.version);
}
if (!state.data) return;
const refUpper = String(targetRef).trim().toUpperCase();
const touchpoint = (state.data.touchpoints ?? []).find(
(tp) => String(tp.reference).toUpperCase() === refUpper,
);
if (touchpoint) {
state.categories.add(touchpoint.category);
const checkbox = dom["category-filters"]?.querySelector(`input[value="${touchpoint.category}"]`);
if (checkbox) checkbox.checked = true;
const pinObj = pill.pin != null
? (touchpoint.pins ?? []).find((p) => String(p.number) === String(pill.pin))
: null;
selectTouchpoint(touchpoint, pinObj || null, false, {highlightAllSame: ctrlMulti});
focusOnTouchpoint(touchpoint);
return;
}
const resistor = (state.data.resistors ?? []).find(
(r) => String(r.reference).toUpperCase() === refUpper,
);
if (resistor) {
state.categories.add("R");
const checkbox = dom["category-filters"]?.querySelector('input[value="R"]');
if (checkbox) checkbox.checked = true;
const padObj = pill.pin != null
? (resistor.pads ?? []).find((p) => String(p.number) === String(pill.pin))
: null;
selectResistor(resistor, padObj || null, false, {highlightAllSame: ctrlMulti});
focusOnTouchpoint(resistor);
return;
}
// Fallback to search box if query is a ball or net (e.g. N8)
if (dom["board-search"]) {
dom["board-search"].value = targetRef;
renderSearchResults(targetRef);
}
}
function navigateCpldTopic(domainId, groupId, topicId) {
if (domainId) state.cpldDomainId = domainId;
if (groupId) state.cpldGroupId = groupId;
if (topicId) state.cpldTopicId = topicId;
renderCpldArchPanel();
}
function flattenAllCpldTopics(ver = state.boardVersion || "v2_0") {
const list = [];
for (const domain of CPLD_MENU_TREE) {
for (const group of domain.children || []) {
for (const topic of group.topics || []) {
const detail = getCpldTopicDetail(topic.id, ver);
list.push({
domainId: domain.id,
domainLabel: domain.title,
domainIcon: domain.icon,
groupId: group.id,
groupLabel: group.title,
groupBadge: group.badge,
topicId: topic.id,
topicLabel: topic.title,
module: detail.tag || detail.file || group.badge,
file: detail.file || "",
});
}
}
}
return list;
}
function renderCpldArchPanel() {
const container = dom["cpld-arch-content"];
if (!container) return;
container.replaceChildren();
const ver = state.boardVersion || "v2_0";
const currentBoardInfo = BOARD_VERSION_COMM_MATRIX[ver] || BOARD_VERSION_COMM_MATRIX.v2_0;
// Ensure active domain/group/topic IDs are valid and synchronized
const activeDomain = CPLD_MENU_TREE.find((d) => d.id === state.cpldDomainId) || CPLD_MENU_TREE[0];
const activeGroup = (activeDomain.children || []).find((g) => g.id === state.cpldGroupId) || activeDomain.children[0];
const activeTopic = (activeGroup.topics || []).find((t) => t.id === state.cpldTopicId) || activeGroup.topics[0];
state.cpldDomainId = activeDomain.id;
state.cpldGroupId = activeGroup.id;
state.cpldTopicId = activeTopic.id;
const wrapper = element("div", "cpld-arch-panel");
// 1. Hero Chip & Current Board Version Banner
const heroCard = element("div", "cpld-hero-card");
const heroTop = element("div", "cpld-hero-top");
const heroTitleWrap = element("div", "cpld-hero-title-wrap");
heroTitleWrap.append(
element(
"div",
"cpld-chip-pill",
`${CPLD_CHIP_SPEC.vendor} ${CPLD_CHIP_SPEC.partNumber} (${CPLD_CHIP_SPEC.reference}) · 25MHz 单时钟域 · ${CPLD_CHIP_SPEC.lutCapacity} LUT4`,
),
element("h2", "cpld-hero-title", `${currentBoardInfo.badge} — 芯片与硬件通信总览`),
);
const topModuleBadge = element("span", "cpld-top-module-badge", currentBoardInfo.topModule);
heroTop.append(heroTitleWrap, topModuleBadge);
const heroGrid = element("div", "cpld-hero-grid");
const quickSpecs = [
{k: "Host TTL 串口", v: `${currentBoardInfo.hostTtl.connector} · ${currentBoardInfo.hostTtl.txPin}`},
{k: "Host RS232 串口", v: `${currentBoardInfo.hostRs232.connector} · ${currentBoardInfo.hostRs232.txPin}`},
{k: "BMC 测温串口", v: `${currentBoardInfo.bmcUart.connector} · ${currentBoardInfo.bmcUart.baud}`},
{k: "500Hz 热控 / 电机", v: `${currentBoardInfo.thermalPwm.freq} · ${currentBoardInfo.motorSpec}`},
];
for (const item of quickSpecs) {
const cell = element("div", "cpld-hero-cell");
cell.append(
element("span", "cpld-hero-cell-k", item.k),
element("span", "cpld-hero-cell-v", item.v),
);
heroGrid.append(cell);
}
heroCard.append(heroTop, heroGrid);
wrapper.append(heroCard);
// 2. Interactive On-Chip Datapath Topology Strip (点击任意芯片模块直达对应三级架构详情)
const topologyBox = element("div", "cpld-topology-box");
const topologyHead = element("div", "cpld-topology-head");
topologyHead.append(
element("span", "cpld-topology-title", "⚡ 芯片内部执行流水线与片上总线拓扑 (点击模块直达源码解析)"),
element("span", "cpld-topology-sub", "25MHz 单时钟域 · Valid/Ready 握手 · BRAM/双 Bank"),
);
const topologyFlow = element("div", "cpld-topology-flow");
const pipelineNodes = [
{label: "Host RS232/TTL", sub: "源锁定 + 双发广播", domain: "protocol_mcu", group: "mcu_host_topo", topic: "mcu_dual_uart_arb", tag: "IO Pads"},
{label: "frame_rx + CRC16", sub: "u_req_ram (128×8 BRAM)", domain: "chip_exec", group: "onchip_memory", topic: "mem_req_reply_bram", tag: "BRAM"},
{label: "transaction_core", sub: "SET_ACCEPT + 30s 看门狗", domain: "protocol_mcu", group: "transaction_fsm", topic: "fsm_atomic_set", tag: "FSM"},
{label: "双 Bank + 500Hz PWM", sub: "PTC / 风扇 / 12轴步进", domain: "chip_exec", group: "onchip_memory", topic: ver === "v1_2" ? "mem_motor_queue" : "mem_duty_double_bank", tag: "Actuator"},
{label: "CT7428 + BMC 采样", sub: "4深 FIFO → temp_ram", domain: "chip_exec", group: "onchip_memory", topic: "mem_temp_ram_arb", tag: "I2C/UART"},
{label: "reply + unified_tx", sub: "u_reply_ram + 轮转仲裁", domain: "protocol_mcu", group: "transaction_fsm", topic: "fsm_tx_ordering", tag: "Arbiter"},
];
pipelineNodes.forEach((node, idx) => {
const isNodeActive = state.cpldTopicId === node.topic;
const btn = element("button", `cpld-topo-node${isNodeActive ? " is-active" : ""}`);
btn.type = "button";
btn.append(
element("span", "cpld-topo-tag", node.tag),
element("strong", "cpld-topo-label", node.label),
element("span", "cpld-topo-subtext", node.sub),
);
btn.addEventListener("click", () => navigateCpldTopic(node.domain, node.group, node.topic));
topologyFlow.append(btn);
if (idx < pipelineNodes.length - 1) {
topologyFlow.append(element("span", "cpld-topo-arrow", "→"));
}
});
topologyBox.append(topologyHead, topologyFlow);
wrapper.append(topologyBox);
// 3. Multi-Level Menu Search & Tree Mode Bar
const menuControlRow = element("div", "cpld-menu-control-row");
const searchInput = element("input", "cpld-topic-search");
searchInput.type = "search";
searchInput.placeholder = "🔍 快速检索全部 29 个 CPLD 架构专题 / 寄存器 / 模块 / 引脚 (如 BRAM, CRC, CON140, MCU, 500Hz)...";
searchInput.value = state.cpldFilterQuery;
searchInput.addEventListener("input", (e) => {
state.cpldFilterQuery = e.target.value;
const caret = searchInput.selectionStart;
renderCpldArchPanel();
const nextInput = dom["cpld-arch-content"]?.querySelector(".cpld-topic-search");
if (nextInput instanceof HTMLInputElement) {
nextInput.focus();
if (caret != null) nextInput.setSelectionRange(caret, caret);
}
});
const treeToggleBtn = element(
"button",
`cpld-tree-toggle-btn${state.cpldTreeExpanded ? " is-active" : ""}`,
state.cpldTreeExpanded ? "📂 收起三级目录树" : "🌳 展开全览目录树",
);
treeToggleBtn.type = "button";
treeToggleBtn.addEventListener("click", () => {
state.cpldTreeExpanded = !state.cpldTreeExpanded;
renderCpldArchPanel();
});
menuControlRow.append(searchInput, treeToggleBtn);
wrapper.append(menuControlRow);
// Quick search filter results across all 21 L3 topics
const q = state.cpldFilterQuery.trim().toLowerCase();
if (q) {
const allTopics = flattenAllCpldTopics(ver);
const matched = allTopics.filter((item) => {
const detail = getCpldTopicDetail(item.topicId, ver);
const haystack = [
item.domainLabel,
item.groupLabel,
item.topicLabel,
item.module,
detail.title,
detail.summary,
JSON.stringify(detail.kvTable || []),
JSON.stringify(detail.matrixTable || {}),
JSON.stringify(detail.pipelineFlow || []),
detail.codeBlock || "",
]
.join(" ")
.toLowerCase();
return haystack.includes(q);
});
const searchBox = element("div", "cpld-search-hits");
searchBox.append(
element("div", "cpld-search-hits-head", `检索到 ${matched.length} 个匹配的 CPLD 源码与硬件专题:`),
);
const hitGrid = element("div", "cpld-search-hits-grid");
for (const hit of matched) {
const hitBtn = element(
"button",
`cpld-hit-btn${state.cpldTopicId === hit.topicId ? " is-active" : ""}`,
);
hitBtn.type = "button";
hitBtn.append(
element("span", "cpld-hit-path", `${hit.domainIcon} ${hit.domainLabel} › ${hit.groupLabel}`),
element("strong", "cpld-hit-title", hit.topicLabel),
element("span", "cpld-hit-mod", hit.file || hit.module),
);
hitBtn.addEventListener("click", () => {
state.cpldFilterQuery = "";
navigateCpldTopic(hit.domainId, hit.groupId, hit.topicId);
});
hitGrid.append(hitBtn);
}
searchBox.append(hitGrid);
wrapper.append(searchBox);
}
// 4. Dynamic 3-Level Cascading Menu (L1 Domain Cards → L2 Subsystem Groups → L3 Deep-Dive Topics)
const navContainer = element("nav", "cpld-multilevel-nav");
navContainer.setAttribute("aria-label", "CPLD 架构动态多级菜单");
// Level 1: 4 Primary Domains
const l1Bar = element("div", "cpld-l1-grid");
for (const domain of CPLD_MENU_TREE) {
const isActive = domain.id === activeDomain.id;
const topicCount = (domain.children || []).reduce((acc, g) => acc + (g.topics?.length || 0), 0);
const btn = element("button", `cpld-l1-card${isActive ? " is-active" : ""}`);
btn.type = "button";
const headRow = element("div", "cpld-l1-head");
headRow.append(
element("span", "cpld-l1-icon", domain.icon),
element("span", "cpld-l1-badge", `${(domain.children || []).length} 组 · ${topicCount} 专题`),
);
btn.append(
headRow,
element("div", "cpld-l1-title", domain.title),
element("div", "cpld-l1-desc", domain.subtitle),
);
btn.addEventListener("click", () => {
const firstGroup = domain.children?.[0];
const firstTopic = firstGroup?.topics?.[0];
navigateCpldTopic(domain.id, firstGroup?.id, firstTopic?.id);
});
l1Bar.append(btn);
}
navContainer.append(l1Bar);
if (state.cpldTreeExpanded) {
// Full Expanded 3-Level Directory Tree View
const fullTree = element("div", "cpld-full-tree");
for (const domain of CPLD_MENU_TREE) {
const dBlock = element("div", "cpld-tree-domain");
dBlock.append(element("div", "cpld-tree-domain-title", `${domain.icon} ${domain.title} — ${domain.subtitle}`));
for (const grp of domain.children || []) {
const gBlock = element("div", "cpld-tree-group");
gBlock.append(element("div", "cpld-tree-group-title", `▸ ${grp.title} [${grp.badge}]`));
const tList = element("div", "cpld-tree-topics");
for (const top of grp.topics || []) {
const topDetail = getCpldTopicDetail(top.id, ver);
const tBtn = element(
"button",
`cpld-tree-topic-btn${state.cpldTopicId === top.id ? " is-active" : ""}`,
);
tBtn.type = "button";
tBtn.append(
element("span", "", top.title),
element("code", "cpld-tree-mod", topDetail.tag || grp.badge),
);
tBtn.addEventListener("click", () => navigateCpldTopic(domain.id, grp.id, top.id));
tList.append(tBtn);
}
gBlock.append(tList);
dBlock.append(gBlock);
}
fullTree.append(dBlock);
}
navContainer.append(fullTree);
} else {
// Cascading Level 2 & Level 3 Bars
const l2Row = element("div", "cpld-l2-bar");
l2Row.append(element("span", "cpld-level-tag", "二级分类"));
const l2Pills = element("div", "cpld-l2-pills");
for (const grp of activeDomain.children || []) {
const isGrpActive = grp.id === activeGroup.id;
const gBtn = element(
"button",
`cpld-l2-btn${isGrpActive ? " is-active" : ""}`,
`${grp.title} (${grp.topics.length})`,
);
gBtn.type = "button";
gBtn.addEventListener("click", () => {
const firstTopic = grp.topics?.[0];
navigateCpldTopic(activeDomain.id, grp.id, firstTopic?.id);
});
l2Pills.append(gBtn);
}
l2Row.append(l2Pills);
const l3Row = element("div", "cpld-l3-bar");
l3Row.append(element("span", "cpld-level-tag is-l3", "三级专题"));
const l3Pills = element("div", "cpld-l3-pills");
for (const top of activeGroup.topics || []) {
const isTopActive = top.id === activeTopic.id;
const topDetail = getCpldTopicDetail(top.id, ver);
const tBtn = element("button", `cpld-l3-btn${isTopActive ? " is-active" : ""}`);
tBtn.type = "button";
tBtn.append(
element("span", "cpld-l3-btn-label", top.title),
element("span", "cpld-l3-btn-mod", topDetail.file || topDetail.tag || activeGroup.badge),
);
tBtn.addEventListener("click", () => navigateCpldTopic(activeDomain.id, activeGroup.id, top.id));
l3Pills.append(tBtn);
}
l3Row.append(l3Pills);
navContainer.append(l2Row, l3Row);
}
wrapper.append(navContainer);
// 5. Active L3 Topic Deep-Dive Article Card
const detail = getCpldTopicDetail(activeTopic.id, ver);
const article = element("article", "cpld-topic-article");
// Breadcrumb + RTL File Badge
const breadcrumbRow = element("div", "cpld-breadcrumb-row");
breadcrumbRow.append(
element("span", "cpld-breadcrumb", `${activeDomain.icon} ${activeDomain.title} › ${activeGroup.title} › ${activeTopic.title}`),
element("code", "cpld-file-badge", detail.file || detail.tag || activeGroup.badge),
);
article.append(breadcrumbRow);
article.append(
element("h3", "cpld-article-title", detail.title),
element("p", "cpld-article-summary", detail.summary),
);
// Interactive PCB Jump Pills (一键在 PCB 图定位对应插座/芯片/引脚)
if (Array.isArray(detail.jumpPills) && detail.jumpPills.length) {
const jumpBar = element("div", "cpld-jump-bar");
jumpBar.append(element("span", "cpld-jump-label", "🎯 关联板级插座与逻辑管脚一键定位:"));
const jumpList = element("div", "cpld-jump-list");
for (const pill of detail.jumpPills) {
const pBtn = element("button", "cpld-jump-pill", `📍 ${pill.label}`);
pBtn.type = "button";
pBtn.title = "点击在左侧电路板视图中定位并高亮该硬件接口(按住 Ctrl 点击全板标出同网/同类)";
pBtn.addEventListener("click", (event) => jumpToBoardTarget(pill, event));
jumpList.append(pBtn);
}
jumpBar.append(jumpList);
article.append(jumpBar);
}
// Render Pipeline Flow (if present)
if (Array.isArray(detail.pipelineFlow) && detail.pipelineFlow.length) {
const secEl = element("section", "cpld-sec-block");
secEl.append(element("h4", "cpld-sec-heading", "芯片内部硬件流水线与总线节拍 (Pipeline & Bus Flow)"));
const flowList = element("div", "cpld-pipeline-list");
detail.pipelineFlow.forEach((st, idx) => {
const card = element("div", "cpld-pipeline-step");
card.append(
element("span", "cpld-step-num", String(idx + 1)),
element("div", "cpld-step-body"),
);
card.lastChild.append(
element("strong", "cpld-step-title", `${st.stage} · ${st.module}`),
element("div", "cpld-hit-mod", `片上总线/信号: ${st.bus}`),
element("p", "cpld-step-detail", st.desc),
);
flowList.append(card);
});
secEl.append(flowList);
article.append(secEl);
}
// Render Key-Value Table (if present)
if (Array.isArray(detail.kvTable) && detail.kvTable.length) {
const secEl = element("section", "cpld-sec-block");
secEl.append(element("h4", "cpld-sec-heading", "核心架构参数、寄存器与电气契约明细"));
const kvGrid = element("div", "cpld-kv-list");
for (const [k, v] of detail.kvTable) {
const row = element("div", "cpld-kv-row");
row.append(
element("div", "cpld-kv-key", k),
element("div", "cpld-kv-val", v),
);
kvGrid.append(row);
}
secEl.append(kvGrid);
article.append(secEl);
}
// Render Comparison Matrix Table (if present)
if (detail.matrixTable && Array.isArray(detail.matrixTable.rows)) {
const secEl = element("section", "cpld-sec-block");
secEl.append(element("h4", "cpld-sec-heading", "跨版本 / 跨通道硬件与协议映射对比矩阵"));
const tableWrap = element("div", "cpld-table-wrap");
const table = element("table", "cpld-matrix-table");
if (Array.isArray(detail.matrixTable.headers)) {
const thead = element("thead");
const tr = element("tr");
for (const h of detail.matrixTable.headers) {
tr.append(element("th", "", h));
}
thead.append(tr);
table.append(thead);
}
const tbody = element("tbody");
for (const r of detail.matrixTable.rows) {
const tr = element("tr");
const rowText = r.join(" ");
if (
(ver === "v2_0" && rowText.includes("6400 V2.0") && !rowText.includes("扩展板")) ||
(ver === "v2_0_fan" && rowText.includes("扩展板")) ||
(ver === "v1_2" && rowText.includes("V1.2")) ||
(ver === "v1_1" && rowText.includes("V1.1"))
) {
tr.classList.add("is-current-board-row");
}
for (const cell of r) {
tr.append(element("td", "", cell));
}
tbody.append(tr);
}
table.append(tbody);
tableWrap.append(table);
secEl.append(tableWrap);
article.append(secEl);
}
// Render Verilog Code Block (if present)
if (detail.codeBlock) {
const secEl = element("section", "cpld-sec-block");
secEl.append(element("h4", "cpld-sec-heading", `实现说明 / 代码示意(当前源码见 ${detail.file || "src/"})`));
const codeBox = element("div", "cpld-code-box");
const codeHead = element("div", "cpld-code-head");
codeHead.append(element("span", "cpld-code-lang", `${detail.file || "Verilog RTL"} · 手工维护说明`));
const copyBtn = element("button", "cpld-code-copy-btn", "⧉ 复制说明");
copyBtn.type = "button";
copyBtn.addEventListener("click", async () => {
await copyText(detail.codeBlock);
copyBtn.textContent = "✓ 已复制";
window.setTimeout(() => {
copyBtn.textContent = "⧉ 复制说明";
}, 1800);
});
codeHead.append(copyBtn);
const pre = element("pre", "cpld-code-pre");
pre.append(element("code", "", detail.codeBlock));
codeBox.append(codeHead, pre);
secEl.append(codeBox);
article.append(secEl);
}
// Prev / Next Topic Sequential Footer Navigation
const allTopics = flattenAllCpldTopics(ver);
const curIdx = allTopics.findIndex((t) => t.topicId === activeTopic.id);
if (curIdx >= 0) {
const pager = element("div", "cpld-topic-pager");
const prevItem = allTopics[(curIdx - 1 + allTopics.length) % allTopics.length];
const nextItem = allTopics[(curIdx + 1) % allTopics.length];
const prevBtn = element("button", "cpld-pager-btn", `← 上一专题:${prevItem.topicLabel}`);
prevBtn.type = "button";
prevBtn.addEventListener("click", () =>
navigateCpldTopic(prevItem.domainId, prevItem.groupId, prevItem.topicId),
);
const nextBtn = element("button", "cpld-pager-btn is-next", `下一专题:${nextItem.topicLabel} →`);
nextBtn.type = "button";
nextBtn.addEventListener("click", () =>
navigateCpldTopic(nextItem.domainId, nextItem.groupId, nextItem.topicId),
);
pager.append(prevBtn, nextBtn);
article.append(pager);
}
wrapper.append(article);
container.append(wrapper);
}
function switchTab(tab) {
state.activeTab = tab;
const isDetail = tab === "detail";
const isPeripheral = tab === "peripheral";
const isCpldArch = tab === "cpld-arch";
const isCandidate = tab === "candidate";
const isSchematic = tab === "schematic";
dom["detail-tab"].setAttribute("aria-selected", String(isDetail));
if (dom["peripheral-tab"]) dom["peripheral-tab"].setAttribute("aria-selected", String(isPeripheral));
if (dom["cpld-arch-tab"]) dom["cpld-arch-tab"].setAttribute("aria-selected", String(isCpldArch));
dom["candidate-tab"].setAttribute("aria-selected", String(isCandidate));
if (dom["schematic-tab"]) dom["schematic-tab"].setAttribute("aria-selected", String(isSchematic));
dom["detail-content"].hidden = !isDetail;
if (dom["peripheral-content"]) dom["peripheral-content"].hidden = !isPeripheral;
if (dom["cpld-arch-content"]) dom["cpld-arch-content"].hidden = !isCpldArch;
dom["candidate-content"].hidden = !isCandidate;
if (dom["schematic-content"]) dom["schematic-content"].hidden = !isSchematic;
if (isPeripheral) {
renderPeripheralPanel();
} else {
if (state.peripheralHighlightedRefs?.size) {
state.peripheralHighlightedRefs = new Set();
updateSelectionVisuals();
}
}
if (isCpldArch) renderCpldArchPanel();
if (isCandidate) renderCandidates();
}
function renderSearchResults(query) {
let results = searchBoard(state.data, query);
if (!state.showShieldPins && !query.trim().toUpperCase().includes("SH")) {
results = results.filter((item) => !isShieldPin(item.pin));
}
state.searchResults = results.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}`;
const logical = resolveLogicalPin(result.touchpoint, result.pin, state.boardVersion);
detail = `${logical.displayBadge} · ${logical.peripheralRole} · 网络:${result.pin.net || "无"}`;
} 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 {
const periph = classifyTouchpointPeripheral(result.touchpoint, state.boardVersion);
detail = `${periph.peripheralLabel} (${periph.isUsed ? "已用" : (periph.isSpareConnector ? "空余插座" : "板级")}) · ${result.touchpoint.summary}`;
}
button.append(element("span", "result-key", key), element("span", "result-detail", detail));
button.addEventListener("click", (event) => activateSearchResult(index, event));
dom["search-results"].append(button);
});
}
function activateSearchResult(index, event = null) {
const result = state.searchResults[index];
if (!result) return;
const ctrlMulti = Boolean(event?.ctrlKey || event?.metaKey);
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, {highlightAllSame: ctrlMulti});
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, {highlightAllSame: ctrlMulti});
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;
}
const target = {
x: bounds.x + bounds.width / 2 - width / 2,
y: bounds.y + bounds.height / 2 - height / 2,
width,
height,
};
animateViewBoxTo(target, 240);
}
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, animateMs = 0) {
if (!state.viewBox || !state.baseViewBox) return;
cancelViewBoxAnimation();
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);
const nextBox = {
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,
};
if (animateMs > 0) {
animateViewBoxTo(nextBox, animateMs);
} else {
state.viewBox = nextBox;
clampViewBox();
scheduleViewBoxUpdate();
}
}
function setZoomRatio(targetRatio, clientX = null, clientY = null, animateMs = 150) {
if (!state.viewBox || !state.baseViewBox) return;
const clampedRatio = Math.min(Math.max(Number(targetRatio) || 1, 0.8), 35);
const targetWidth = state.baseViewBox.width / clampedRatio;
const factor = targetWidth / Math.max(state.viewBox.width, 0.001);
zoomAt(factor, clientX, clientY, animateMs);
}
function setBoxZoomMode(enabled) {
state.boxZoomMode = Boolean(enabled);
dom["board-svg"].classList.toggle("is-box-zoom", state.boxZoomMode);
if (dom["box-zoom-toggle"]) {
dom["box-zoom-toggle"].setAttribute("aria-pressed", String(state.boxZoomMode));
}
if (dom["hud-box-zoom"]) {
dom["hud-box-zoom"].setAttribute("aria-pressed", String(state.boxZoomMode));
}
}
function panMinimapTo(clientX, clientY) {
const canvas = dom["board-minimap"];
if (!canvas || !state.viewBox || !state.baseViewBox) return;
const rect = canvas.getBoundingClientRect();
const mw = Math.max(rect.width, 1);
const mh = Math.max(rect.height, 1);
const bx = state.baseViewBox.x;
const by = state.baseViewBox.y;
const bw = Math.max(state.baseViewBox.width, 1);
const bh = Math.max(state.baseViewBox.height, 1);
const scale = Math.min(mw / bw, mh / bh);
const ox = (mw - bw * scale) * 0.5 - bx * scale;
const oy = (mh - bh * scale) * 0.5 - by * scale;
const targetX = (clientX - rect.left - ox) / scale;
const targetY = (clientY - rect.top - oy) / scale;
cancelViewBoxAnimation();
state.viewBox.x = targetX - state.viewBox.width * 0.5;
state.viewBox.y = targetY - state.viewBox.height * 0.5;
clampViewBox();
scheduleViewBoxUpdate();
}
function bindContinuousZoomButton(buttonEl, direction) {
if (!buttonEl) return;
let holdTimer = 0;
let holdRaf = 0;
let holding = false;
const stopHold = () => {
if (holdTimer) {
window.clearTimeout(holdTimer);
holdTimer = 0;
}
if (holdRaf) {
window.cancelAnimationFrame(holdRaf);
holdRaf = 0;
}
holding = false;
};
buttonEl.addEventListener("pointerdown", (event) => {
if (event.button !== 0 && event.pointerType === "mouse") return;
event.preventDefault();
stopHold();
// Immediate responsive step on press
zoomAt(direction > 0 ? 0.75 : 1.33, null, null, 110);
holdTimer = window.setTimeout(() => {
holding = true;
let lastTime = performance.now();
const stepHold = (now) => {
if (!holding) return;
const dt = Math.min(Math.max((now - lastTime) / 1000, 0.004), 0.05);
lastTime = now;
const speedFactor = Math.exp((direction > 0 ? -1.45 : 1.45) * dt);
zoomAt(speedFactor, null, null, 0);
holdRaf = window.requestAnimationFrame(stepHold);
};
holdRaf = window.requestAnimationFrame(stepHold);
}, 180);
});
buttonEl.addEventListener("pointerup", stopHold);
buttonEl.addEventListener("pointerleave", stopHold);
buttonEl.addEventListener("pointercancel", stopHold);
buttonEl.addEventListener("keydown", (event) => {
if (event.key === "Enter" || event.key === " ") {
event.preventDefault();
zoomAt(direction > 0 ? 0.75 : 1.33, null, null, 140);
}
});
}
function clientToSvg(clientX, clientY) {
if (state.viewBox && dom["board-viewport"]) {
const rect = dom["board-viewport"].getBoundingClientRect();
const cw = Math.max(rect.width, 1);
const ch = Math.max(rect.height, 1);
const {x: vx, y: vy, width: vw, height: vh} = state.viewBox;
const scale = Math.min(cw / Math.max(vw, 0.001), ch / Math.max(vh, 0.001));
const offsetX = (cw - vw * scale) * 0.5 - vx * scale;
const offsetY = (ch - vh * scale) * 0.5 - vy * scale;
return {
x: (clientX - rect.left - offsetX) / scale,
y: (clientY - rect.top - offsetY) / scale,
};
}
const point = dom["board-svg"].createSVGPoint();
point.x = clientX;
point.y = clientY;
return point.matrixTransform(dom["board-svg"].getScreenCTM().inverse());
}
function hitTestBoardAt(clientX, clientY) {
if (!state.data || !state.viewBox || !state.baseViewBox) return null;
const pt = clientToSvg(clientX, clientY);
const zoomRatio = state.baseViewBox.width / Math.max(state.viewBox.width, 0.001);
return wasmAccel.hitTest(
pt.x,
pt.y,
state.boardSide,
state.categories,
state.showShieldPins,
zoomRatio,
);
}
function resetView() {
setBoxZoomMode(false);
animateViewBoxTo({...state.baseViewBox}, 200);
}
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 ? "展开详情" : "收起详情");
}
function setWidePanel(wide) {
state.widePanel = Boolean(wide);
dom.app.classList.toggle("detail-wide", state.widePanel);
if (dom["toggle-wide-panel"]) {
dom["toggle-wide-panel"].setAttribute("aria-pressed", String(state.widePanel));
dom["toggle-wide-panel"].textContent = state.widePanel ? "⤡ 标准宽度" : "⤢ 宽屏";
}
}
dom["category-filters"].addEventListener("change", (event) => {
const input = event.target;
if (!(input instanceof HTMLInputElement)) return;
if (input.value === "SH") {
state.showShieldPins = input.checked;
if (!state.showShieldPins && isShieldPin(state.selectedPin)) {
state.selectedPin = null;
}
renderBoardMarkers();
renderDetail();
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;
prepareLayerBitmapCache();
});
if (dom["perf-mode-toggle"]) {
dom["perf-mode-toggle"].addEventListener("click", () => {
state.perfUltraMode = !state.perfUltraMode;
syncStaticLayerVisibility();
renderLayerCanvasFrame();
renderBoardMarkers();
});
}
bindContinuousZoomButton(dom["zoom-in"], 1);
bindContinuousZoomButton(dom["zoom-out"], -1);
bindContinuousZoomButton(dom["hud-zoom-in"], 1);
bindContinuousZoomButton(dom["hud-zoom-out"], -1);
dom["reset-view"].addEventListener("click", resetView);
if (dom["hud-reset-view"]) dom["hud-reset-view"].addEventListener("click", resetView);
if (dom["box-zoom-toggle"]) {
dom["box-zoom-toggle"].addEventListener("click", () => setBoxZoomMode(!state.boxZoomMode));
}
if (dom["hud-box-zoom"]) {
dom["hud-box-zoom"].addEventListener("click", () => setBoxZoomMode(!state.boxZoomMode));
}
if (dom["zoom-slider"]) {
dom["zoom-slider"].addEventListener("input", (event) => {
const pct = Number(event.target.value) || 100;
setZoomRatio(pct / 100, null, null, 0);
});
}
if (dom["zoom-hud-dock"]) {
dom["zoom-hud-dock"].addEventListener("click", (event) => {
const presetBtn = event.target?.closest?.(".hud-preset-btn[data-zoom]");
if (!presetBtn) return;
const targetRatio = Number(presetBtn.dataset.zoom) || 1;
setZoomRatio(targetRatio, null, null, 160);
});
}
if (dom["board-minimap"]) {
dom["board-minimap"].addEventListener("pointerdown", (event) => {
event.preventDefault();
event.stopPropagation();
state.minimapDragging = true;
dom["board-minimap"].setPointerCapture(event.pointerId);
panMinimapTo(event.clientX, event.clientY);
});
dom["board-minimap"].addEventListener("pointermove", (event) => {
if (!state.minimapDragging) return;
panMinimapTo(event.clientX, event.clientY);
});
const endMinimapDrag = () => {
state.minimapDragging = false;
};
dom["board-minimap"].addEventListener("pointerup", endMinimapDrag);
dom["board-minimap"].addEventListener("pointercancel", endMinimapDrag);
}
dom["detail-tab"].addEventListener("click", () => switchTab("detail"));
if (dom["peripheral-tab"]) dom["peripheral-tab"].addEventListener("click", () => switchTab("peripheral"));
if (dom["cpld-arch-tab"]) {
dom["cpld-arch-tab"].addEventListener("click", () => {
if (!state.widePanel && window.innerWidth > 1180) {
setWidePanel(true);
}
switchTab("cpld-arch");
});
}
if (dom["open-peripheral-index"]) {
dom["open-peripheral-index"].addEventListener("click", () => {
setDrawerCollapsed(false);
switchTab("peripheral");
});
}
if (dom["open-cpld-arch"]) {
dom["open-cpld-arch"].addEventListener("click", () => {
setDrawerCollapsed(false);
if (window.innerWidth > 1180) {
setWidePanel(true);
}
switchTab("cpld-arch");
});
}
if (dom["toggle-wide-panel"]) {
dom["toggle-wide-panel"].addEventListener("click", () => {
setDrawerCollapsed(false);
setWidePanel(!state.widePanel);
});
}
dom["candidate-tab"].addEventListener("click", () => switchTab("candidate"));
if (dom["schematic-tab"]) dom["schematic-tab"].addEventListener("click", () => switchTab("schematic"));
if (dom["board-version-select"]) {
dom["board-version-select"].addEventListener("change", (e) => {
const ver = e.target.value;
const url = new URL(window.location.href);
url.searchParams.set("version", ver);
window.history.replaceState({}, "", url.toString());
loadApplication(ver);
});
}
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;
}
});
// Proportional silky-smooth wheel & trackpad pinch zoom across the entire viewport
dom["board-viewport"].addEventListener("wheel", (event) => {
if (event.target?.closest?.(".zoom-hud-dock, .board-minimap-wrap")) return;
event.preventDefault();
let dy = event.deltaY;
if (event.deltaMode === 1) dy *= 32;
else if (event.deltaMode === 2) dy *= 320;
// Trackpad pinch gestures set ctrlKey=true with smaller deltas; boost sensitivity
const sensitivity = event.ctrlKey ? 0.0085 : 0.0024;
const factor = Math.min(Math.max(Math.exp(dy * sensitivity), 0.52), 1.92);
zoomAt(factor, event.clientX, event.clientY, 0);
}, {passive: false});
// Double-click anywhere on the board to zoom in 2.2x at cursor (Shift + double-click to zoom out)
dom["board-svg"].addEventListener("dblclick", (event) => {
event.preventDefault();
zoomAt(event.shiftKey ? 2.1 : 0.45, event.clientX, event.clientY, 170);
});
// Prevent context menu on right-drag box-zoom
dom["board-svg"].addEventListener("contextmenu", (event) => {
event.preventDefault();
});
dom["board-svg"].addEventListener("pointerdown", (event) => {
if (event.pointerType === "touch") {
state.activeTouchPointers.set(event.pointerId, {x: event.clientX, y: event.clientY});
if (state.activeTouchPointers.size === 2) {
const pts = [...state.activeTouchPointers.values()];
const dist = Math.max(Math.hypot(pts[1].x - pts[0].x, pts[1].y - pts[0].y), 10);
const midX = (pts[0].x + pts[1].x) * 0.5;
const midY = (pts[0].y + pts[1].y) * 0.5;
state.dragging = null;
state.pinchState = {
startDist: dist,
midX,
midY,
startWidth: state.viewBox.width,
};
return;
}
}
const isRightButton = event.pointerType === "mouse" && event.button === 2;
const isLeftButton = event.pointerType !== "mouse" || event.button === 0;
if (!isLeftButton && !isRightButton) return;
cancelViewBoxAnimation();
dom["board-svg"].setPointerCapture(event.pointerId);
const bounds = dom["board-viewport"].getBoundingClientRect();
// Box-Zoom triggered by: 🔍 框选放大 mode, Shift + Left-drag, or Right-button drag
if (state.boxZoomMode || event.shiftKey || isRightButton) {
hideTooltip();
state.boxZoomDrag = {
pointerId: event.pointerId,
startClientX: event.clientX,
startClientY: event.clientY,
curClientX: event.clientX,
curClientY: event.clientY,
viewportRect: bounds,
};
return;
}
state.dragging = {
pointerId: event.pointerId,
x: event.clientX,
y: event.clientY,
moved: false,
scaleX: state.viewBox.width / Math.max(bounds.width, 1),
scaleY: state.viewBox.height / Math.max(bounds.height, 1),
viewBox: {...state.viewBox},
};
});
dom["board-svg"].addEventListener("pointermove", (event) => {
if (state.activeTouchPointers.has(event.pointerId)) {
state.activeTouchPointers.set(event.pointerId, {x: event.clientX, y: event.clientY});
if (state.pinchState && state.activeTouchPointers.size === 2) {
const pts = [...state.activeTouchPointers.values()];
const dist = Math.max(Math.hypot(pts[1].x - pts[0].x, pts[1].y - pts[0].y), 10);
const targetWidth = state.pinchState.startWidth * (state.pinchState.startDist / dist);
const factor = targetWidth / Math.max(state.viewBox.width, 0.001);
zoomAt(factor, state.pinchState.midX, state.pinchState.midY, 0);
return;
}
}
if (state.boxZoomDrag && state.boxZoomDrag.pointerId === event.pointerId) {
state.boxZoomDrag.curClientX = event.clientX;
state.boxZoomDrag.curClientY = event.clientY;
const rect = state.boxZoomDrag.viewportRect;
const x1 = Math.min(state.boxZoomDrag.startClientX, event.clientX) - rect.left;
const y1 = Math.min(state.boxZoomDrag.startClientY, event.clientY) - rect.top;
const w = Math.abs(event.clientX - state.boxZoomDrag.startClientX);
const h = Math.abs(event.clientY - state.boxZoomDrag.startClientY);
const marquee = dom["box-zoom-marquee"];
if (marquee && (w > 5 || h > 5)) {
marquee.hidden = false;
marquee.style.left = `${Math.max(0, x1)}px`;
marquee.style.top = `${Math.max(0, y1)}px`;
marquee.style.width = `${w}px`;
marquee.style.height = `${h}px`;
}
return;
}
if (state.dragging && state.dragging.pointerId === event.pointerId) {
const dx = event.clientX - state.dragging.x;
const dy = event.clientY - state.dragging.y;
if (!state.dragging.moved && Math.hypot(dx, dy) > 4) {
state.dragging.moved = true;
hideTooltip();
dom["board-svg"].classList.add("is-panning");
}
if (state.dragging.moved) {
state.viewBox = {
...state.dragging.viewBox,
x: state.dragging.viewBox.x - dx * state.dragging.scaleX,
y: state.dragging.viewBox.y - dy * state.dragging.scaleY,
};
clampViewBox();
scheduleViewBoxUpdate();
}
return;
}
// O(1) Rust WASM spatial grid hover hit-test
const hit = hitTestBoardAt(event.clientX, event.clientY);
if (!hit) {
dom["board-svg"].style.cursor = state.boxZoomMode ? "crosshair" : "";
hideTooltip();
return;
}
dom["board-svg"].style.cursor = state.boxZoomMode ? "crosshair" : "pointer";
let key = "";
if (hit.kind === "pin") {
key = `pin:${hit.touchpoint.reference}:${hit.pin.id || hit.pin.number}`;
if (state.hoverTargetKey !== key) {
state.hoverTargetKey = key;
showPinTooltip(event, hit.touchpoint, hit.pin);
} else {
positionTooltip(event);
}
} else if (hit.kind === "touchpoint") {
key = `tp:${hit.touchpoint.reference}`;
if (state.hoverTargetKey !== key) {
state.hoverTargetKey = key;
showTouchpointTooltip(event, hit.touchpoint);
} else {
positionTooltip(event);
}
} else if (hit.kind === "resistor_pad") {
key = `rpad:${hit.resistor.reference}:${hit.pad.number}`;
if (state.hoverTargetKey !== key) {
state.hoverTargetKey = key;
showResistorPadTooltip(event, hit.resistor, hit.pad);
} else {
positionTooltip(event);
}
} else if (hit.kind === "resistor") {
key = `res:${hit.resistor.reference}`;
if (state.hoverTargetKey !== key) {
state.hoverTargetKey = key;
showResistorTooltip(event, hit.resistor);
} else {
positionTooltip(event);
}
}
});
dom["board-svg"].addEventListener("pointerleave", () => {
if (!state.dragging && !state.boxZoomDrag) {
dom["board-svg"].style.cursor = state.boxZoomMode ? "crosshair" : "";
hideTooltip();
}
});
function endPan(event) {
if (state.activeTouchPointers.has(event.pointerId)) {
state.activeTouchPointers.delete(event.pointerId);
if (state.activeTouchPointers.size < 2) {
state.pinchState = null;
}
}
if (state.boxZoomDrag && state.boxZoomDrag.pointerId === event.pointerId) {
const drag = state.boxZoomDrag;
state.boxZoomDrag = null;
if (dom["box-zoom-marquee"]) dom["box-zoom-marquee"].hidden = true;
const wPx = Math.abs(event.clientX - drag.startClientX);
const hPx = Math.abs(event.clientY - drag.startClientY);
if (wPx > 10 && hPx > 10) {
const p1 = clientToSvg(drag.startClientX, drag.startClientY);
const p2 = clientToSvg(event.clientX, event.clientY);
const minX = Math.min(p1.x, p2.x);
const minY = Math.min(p1.y, p2.y);
const boxW = Math.max(Math.abs(p2.x - p1.x), state.baseViewBox.width / 35);
const boxH = Math.max(Math.abs(p2.y - p1.y), state.baseViewBox.height / 35);
const vpAspect = Math.max(drag.viewportRect.width / Math.max(drag.viewportRect.height, 1), 1);
let targetW = boxW;
let targetH = targetW / vpAspect;
if (targetH < boxH) {
targetH = boxH;
targetW = targetH * vpAspect;
}
animateViewBoxTo(
{
x: minX + boxW * 0.5 - targetW * 0.5,
y: minY + boxH * 0.5 - targetH * 0.5,
width: targetW,
height: targetH,
},
190,
);
if (state.boxZoomMode) setBoxZoomMode(false);
}
return;
}
if (!state.dragging || state.dragging.pointerId !== event.pointerId) return;
const wasMoved = state.dragging.moved;
state.dragging = null;
dom["board-svg"].classList.remove("is-panning");
if (!wasMoved && event.type === "pointerup") {
const hit = hitTestBoardAt(event.clientX, event.clientY);
if (hit) {
const ctrlMulti = Boolean(event.ctrlKey || event.metaKey);
if (hit.kind === "pin") selectTouchpoint(hit.touchpoint, hit.pin, true, {highlightAllSame: ctrlMulti});
else if (hit.kind === "touchpoint") selectTouchpoint(hit.touchpoint, null, true, {highlightAllSame: ctrlMulti});
else if (hit.kind === "resistor_pad") selectResistor(hit.resistor, hit.pad, true, {highlightAllSame: ctrlMulti});
else if (hit.kind === "resistor") selectResistor(hit.resistor, null, true, {highlightAllSame: ctrlMulti});
}
}
}
dom["board-svg"].addEventListener("pointerup", endPan);
dom["board-svg"].addEventListener("pointercancel", endPan);
dom["board-svg"].addEventListener("keydown", (event) => {
if (event.key === "Escape" && state.boxZoomMode) {
setBoxZoomMode(false);
return;
}
const targetHotspot = event.target?.closest?.(".hotspot");
if (targetHotspot && (event.key === "Enter" || event.key === " ")) {
event.preventDefault();
const ctrlMulti = Boolean(event.ctrlKey || event.metaKey);
const ref = targetHotspot.dataset?.reference;
if (targetHotspot.dataset?.kind === "resistor") {
const res = state.resByRef.get(ref);
if (res) selectResistor(res, null, true, {highlightAllSame: ctrlMulti});
} else {
const tp = state.tpByRef.get(ref);
if (tp) selectTouchpoint(tp, null, true, {highlightAllSame: ctrlMulti});
}
return;
}
const stepX = state.viewBox.width * 0.06;
const stepY = state.viewBox.height * 0.08;
if (event.key === "+" || event.key === "=") zoomAt(0.75, null, null, 120);
else if (event.key === "-") zoomAt(1.33, null, null, 120);
else if (event.key === "0") resetView();
else if (["ArrowLeft", "ArrowRight", "ArrowUp", "ArrowDown"].includes(event.key)) {
cancelViewBoxAnimation();
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();
scheduleViewBoxUpdate();
} else return;
event.preventDefault();
});
window.addEventListener("resize", () => {
hideTooltip();
if (window.innerWidth > 860) setDrawerCollapsed(false);
renderLayerCanvasFrame();
renderFastCanvasFrame();
renderMinimap();
});
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 是 Anlogic Design Constraint 管脚约束文件,不是模数转换器。",
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);
const urlParams = new URLSearchParams(window.location.search);
const reqVer = urlParams.get("version");
const reqTab = urlParams.get("tab");
const initialVersion = ["v2_0", "v2_0_fan", "v1_2", "v1_1"].includes(reqVer) ? reqVer : "v2_0";
if (reqTab === "cpld-arch" || reqTab === "cpld") {
if (window.innerWidth > 1180) setWidePanel(true);
switchTab("cpld-arch");
} else if (reqTab === "peripheral") {
switchTab("peripheral");
}
loadApplication(initialVersion);