app.js 39 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038
  1. import {
  2. connectorPinGroups,
  3. findCandidates,
  4. generateAdcSnippet,
  5. sameNetPins,
  6. searchBoard,
  7. } from "./board-logic.mjs";
  8. const SVG_NS = "http://www.w3.org/2000/svg";
  9. const state = {
  10. data: null,
  11. runtime: {status: "loading", recommendationsEnabled: false, adcCopyEnabled: false, staleSources: []},
  12. categories: new Set(["CON", "J", "PL", "TP"]),
  13. selectedTouchpoint: null,
  14. selectedPin: null,
  15. baseViewBox: null,
  16. viewBox: null,
  17. dragging: null,
  18. activeTab: "detail",
  19. searchResults: [],
  20. activeSearchIndex: -1,
  21. };
  22. const dom = Object.fromEntries(
  23. [
  24. "app",
  25. "app-status",
  26. "board-summary",
  27. "board-search",
  28. "search-results",
  29. "stale-banner",
  30. "category-filters",
  31. "layer-controls",
  32. "zoom-in",
  33. "zoom-out",
  34. "reset-view",
  35. "board-viewport",
  36. "board-svg",
  37. "board-loading",
  38. "board-tooltip",
  39. "hotspot-layer",
  40. "pin-layer",
  41. "net-layer",
  42. "selection-layer",
  43. "layer-mask",
  44. "layer-silk",
  45. "layer-copper",
  46. "layer-photo",
  47. "photo-control",
  48. "photo-layer",
  49. "photo-label",
  50. "visible-count",
  51. "zoom-readout",
  52. "selection-readout",
  53. "detail-panel",
  54. "detail-tab",
  55. "candidate-tab",
  56. "detail-content",
  57. "candidate-content",
  58. "candidate-list",
  59. "capability-select",
  60. "drawer-toggle",
  61. ].map((id) => [id, document.getElementById(id)]),
  62. );
  63. function svgElement(name, attributes = {}) {
  64. const node = document.createElementNS(SVG_NS, name);
  65. for (const [key, value] of Object.entries(attributes)) node.setAttribute(key, String(value));
  66. return node;
  67. }
  68. function element(name, className = "", content = null) {
  69. const node = document.createElement(name);
  70. if (className) node.className = className;
  71. if (content != null) node.textContent = String(content);
  72. return node;
  73. }
  74. function formatNumber(value, digits = 3) {
  75. const number = Number(value);
  76. return Number.isFinite(number) ? number.toFixed(digits).replace(/\.0+$|(?<=\.[0-9]*?)0+$/g, "") : "未知";
  77. }
  78. function evidenceLabel(tier) {
  79. return {
  80. board_database: "板数据库原始值",
  81. cross_verified: "已交叉验证",
  82. name_inferred: "名称推断",
  83. unknown: "未知",
  84. }[tier] ?? "未知";
  85. }
  86. function directionLabel(direction) {
  87. return {
  88. input: "输入",
  89. output: "输出",
  90. bidirectional: "双向",
  91. passive: "无源",
  92. unknown: "未知",
  93. }[direction] ?? direction ?? "未知";
  94. }
  95. function activeLevelLabel(level) {
  96. return {
  97. high: "高电平有效",
  98. low: "低电平有效",
  99. rising_edge: "上升沿计步脉冲",
  100. state: "状态选择(非有效电平)",
  101. unknown: "未注明",
  102. }[level] ?? level ?? "未注明";
  103. }
  104. function categoryLabel(category) {
  105. return {CON: "连接器", J: "J 类对象", PL: "PL 器件", TP: "测试点"}[category] ?? category;
  106. }
  107. function touchpointKindLabel(touchpoint) {
  108. if (touchpoint?.connector) return touchpoint.category === "CON" ? "连接器" : "调试接口";
  109. if (touchpoint?.category === "PL") return "电源器件";
  110. if (touchpoint?.category === "J") {
  111. const pins = Array.isArray(touchpoint.pins) ? touchpoint.pins : [];
  112. if (pins.length && pins.every((pin) => pin.mechanical === true)) return "安装孔";
  113. if (pins.some((pin) => pin.function_category === "manufacturing_mark")) return "制造标记";
  114. }
  115. return categoryLabel(touchpoint?.category);
  116. }
  117. function padRoleLabel(role) {
  118. return {
  119. contact: "接触针",
  120. shield: "屏蔽固定焊盘",
  121. mechanical: "机械孔",
  122. unknown: "未分类焊盘",
  123. }[role] ?? "未分类焊盘";
  124. }
  125. function touchpointPinSummary(touchpoint) {
  126. if (touchpoint.connector) {
  127. return `${touchpoint.connector.contact_count} 接触针 · ${touchpoint.connector.auxiliary_pad_count} 辅助焊盘`;
  128. }
  129. return `${touchpoint.pins.length} 针`;
  130. }
  131. function setStatus(kind, text) {
  132. dom["app-status"].className = `status-badge status-${kind}`;
  133. dom["app-status"].textContent = text;
  134. }
  135. function applyRuntimeStatus() {
  136. const runtime = state.runtime;
  137. if (runtime.status === "pass") {
  138. setStatus("pass", "数据已校验");
  139. dom["stale-banner"].hidden = true;
  140. } else if (runtime.status === "stale_sources") {
  141. setStatus("stale", "来源已变化");
  142. dom["stale-banner"].hidden = false;
  143. dom["stale-banner"].textContent = `源文件与生成时不一致:${(runtime.staleSources ?? []).join(",")}。选脚推荐与 ADC 复制已关闭。`;
  144. } else {
  145. setStatus("error", "资产不可用");
  146. dom["stale-banner"].hidden = false;
  147. dom["stale-banner"].textContent = runtime.message || "生成资产未通过完整性校验。";
  148. }
  149. }
  150. async function loadApplication() {
  151. try {
  152. const [dataResponse, statusResponse] = await Promise.all([
  153. fetch("/generated/board-data.json", {cache: "no-store"}),
  154. fetch("/api/status", {cache: "no-store"}),
  155. ]);
  156. if (!dataResponse.ok) throw new Error(`板数据 HTTP ${dataResponse.status}`);
  157. if (!statusResponse.ok) throw new Error(`状态 HTTP ${statusResponse.status}`);
  158. state.data = await dataResponse.json();
  159. state.runtime = await statusResponse.json();
  160. initializeBoard();
  161. applyRuntimeStatus();
  162. } catch (error) {
  163. state.runtime = {
  164. status: "error",
  165. recommendationsEnabled: false,
  166. adcCopyEnabled: false,
  167. staleSources: [],
  168. message: error instanceof Error ? error.message : String(error),
  169. };
  170. applyRuntimeStatus();
  171. dom["board-loading"].textContent = "板数据载入失败";
  172. renderEmptyDetail("板数据不可用", state.runtime.message);
  173. }
  174. }
  175. function initializeBoard() {
  176. const {board, counts} = state.data;
  177. const width = Number(board.view_box.width);
  178. const height = Number(board.view_box.height);
  179. const padding = Math.max(height * 0.08, 1.2);
  180. state.baseViewBox = {x: -padding, y: -padding, width: width + padding * 2, height: height + padding * 2};
  181. state.viewBox = {...state.baseViewBox};
  182. for (const image of [dom["layer-mask"], dom["layer-silk"], dom["layer-copper"], dom["layer-photo"]]) {
  183. image.setAttribute("x", "0");
  184. image.setAttribute("y", "0");
  185. image.setAttribute("width", String(width));
  186. image.setAttribute("height", String(height));
  187. }
  188. dom["board-summary"].textContent = `${board.name} · ${counts.touchpoints} 座子 · ${counts.connector_contacts} 个 CON 接触针`;
  189. dom["board-loading"].hidden = true;
  190. updateViewBox();
  191. renderBoardMarkers();
  192. configurePhotoOverlay();
  193. renderEmptyDetail("未选择座子", `${counts.touchpoints} 个座子 · ${counts.connector_contacts} 个 CON 接触针 · ${counts.connector_auxiliary_pads} 个 CON 辅助焊盘`);
  194. renderCandidates();
  195. }
  196. function configurePhotoOverlay() {
  197. const overlay = state.data?.photo_overlay;
  198. if (!overlay) return;
  199. const matrix = Array.isArray(overlay.matrix) ? overlay.matrix : [];
  200. if (matrix.length !== 6 || !matrix.every(Number.isFinite)) return;
  201. const source = `/generated/${overlay.asset}`;
  202. const image = new Image();
  203. image.addEventListener("load", () => {
  204. dom["layer-photo"].setAttribute("href", source);
  205. dom["layer-photo"].setAttribute("width", String(image.naturalWidth));
  206. dom["layer-photo"].setAttribute("height", String(image.naturalHeight));
  207. dom["layer-photo"].setAttribute("transform", `matrix(${matrix.join(" ")})`);
  208. dom["photo-layer"].disabled = false;
  209. dom["photo-control"].classList.remove("disabled-control");
  210. dom["photo-control"].title = `已校准 ${overlay.control_point_count} 个控制点`;
  211. dom["photo-label"].textContent = "照片";
  212. });
  213. image.addEventListener("error", () => {
  214. dom["photo-control"].title = "照片资产载入失败";
  215. dom["photo-label"].textContent = "照片不可用";
  216. });
  217. image.src = source;
  218. }
  219. function updateViewBox() {
  220. if (!state.viewBox) return;
  221. const {x, y, width, height} = state.viewBox;
  222. dom["board-svg"].setAttribute("viewBox", `${x} ${y} ${width} ${height}`);
  223. const ratio = state.baseViewBox.width / width;
  224. const pinsInteractive = ratio >= 1.8;
  225. dom["board-svg"].classList.toggle("pins-interactive", pinsInteractive);
  226. for (const group of dom["pin-layer"].querySelectorAll(".pin-group")) {
  227. group.setAttribute("tabindex", pinsInteractive ? "0" : "-1");
  228. }
  229. dom["zoom-readout"].textContent = `${Math.round(ratio * 100)}%`;
  230. }
  231. function effectiveBounds(bounds, minimum = 3.2) {
  232. const width = Math.max(Number(bounds.width), minimum);
  233. const height = Math.max(Number(bounds.height), minimum);
  234. return {
  235. x: Number(bounds.x) - (width - Number(bounds.width)) / 2,
  236. y: Number(bounds.y) - (height - Number(bounds.height)) / 2,
  237. width,
  238. height,
  239. };
  240. }
  241. function renderBoardMarkers() {
  242. dom["hotspot-layer"].replaceChildren();
  243. dom["pin-layer"].replaceChildren();
  244. if (!state.data) return;
  245. let visible = 0;
  246. for (const touchpoint of state.data.touchpoints) {
  247. if (!state.categories.has(touchpoint.category)) continue;
  248. visible += 1;
  249. const bounds = effectiveBounds(touchpoint.view_bounds);
  250. const hotspot = svgElement("rect", {
  251. x: bounds.x,
  252. y: bounds.y,
  253. width: bounds.width,
  254. height: bounds.height,
  255. rx: 0.45,
  256. class: `hotspot${state.selectedTouchpoint?.reference === touchpoint.reference ? " is-selected" : ""}`,
  257. tabindex: 0,
  258. role: "button",
  259. "aria-label": `${touchpoint.reference} ${touchpointKindLabel(touchpoint)} ${touchpointPinSummary(touchpoint)}`,
  260. "data-reference": touchpoint.reference,
  261. });
  262. hotspot.addEventListener("pointerenter", (event) => showTouchpointTooltip(event, touchpoint));
  263. hotspot.addEventListener("pointermove", positionTooltip);
  264. hotspot.addEventListener("pointerleave", hideTooltip);
  265. hotspot.addEventListener("focus", () => showTouchpointTooltip(null, touchpoint));
  266. hotspot.addEventListener("blur", hideTooltip);
  267. hotspot.addEventListener("click", (event) => {
  268. event.stopPropagation();
  269. selectTouchpoint(touchpoint, null, true);
  270. });
  271. hotspot.addEventListener("keydown", (event) => {
  272. if (event.key === "Enter" || event.key === " ") {
  273. event.preventDefault();
  274. selectTouchpoint(touchpoint, null, true);
  275. }
  276. });
  277. dom["hotspot-layer"].append(hotspot);
  278. for (const pin of touchpoint.pins) {
  279. const group = svgElement("g", {
  280. class: `pin-group role-${pin.pad_role}${state.selectedTouchpoint?.reference === touchpoint.reference && state.selectedPin?.id === pin.id ? " is-selected" : ""}`,
  281. tabindex: dom["board-svg"].classList.contains("pins-interactive") ? 0 : -1,
  282. role: "button",
  283. "aria-label": `${touchpoint.reference}.${pin.number || "机械"} ${pin.net || "无网络"}`,
  284. "data-reference": touchpoint.reference,
  285. "data-pin": pin.number,
  286. "data-pin-id": pin.id,
  287. "data-pad-role": pin.pad_role,
  288. });
  289. const width = Math.max(Number(pin.size.width), Number(pin.size.drill_width), 0.65);
  290. const height = Math.max(Number(pin.size.height), Number(pin.size.drill_height), 0.65);
  291. const radius = Math.max(Math.min(width, height) / 2, 0.42);
  292. const hitRadius = Math.max(Math.min(width, height) / 2 + 0.15, 0.58);
  293. group.append(
  294. svgElement("circle", {cx: pin.view_position.x, cy: pin.view_position.y, r: hitRadius, class: "pin-hit"}),
  295. svgElement("circle", {cx: pin.view_position.x, cy: pin.view_position.y, r: radius, class: "pin-dot"}),
  296. );
  297. group.addEventListener("pointerenter", (event) => showPinTooltip(event, touchpoint, pin));
  298. group.addEventListener("pointermove", positionTooltip);
  299. group.addEventListener("pointerleave", hideTooltip);
  300. group.addEventListener("focus", () => showPinTooltip(null, touchpoint, pin));
  301. group.addEventListener("blur", hideTooltip);
  302. group.addEventListener("click", (event) => {
  303. event.stopPropagation();
  304. selectTouchpoint(touchpoint, pin, true);
  305. });
  306. group.addEventListener("keydown", (event) => {
  307. if (event.key === "Enter" || event.key === " ") {
  308. event.preventDefault();
  309. selectTouchpoint(touchpoint, pin, true);
  310. }
  311. });
  312. dom["pin-layer"].append(group);
  313. }
  314. }
  315. dom["visible-count"].textContent = `${visible} 个座子`;
  316. renderSelectionOverlay();
  317. }
  318. function showTouchpointTooltip(event, touchpoint) {
  319. dom["board-tooltip"].replaceChildren();
  320. const key = element("div", "tooltip-key", touchpoint.reference);
  321. const detail = element("div", "", `${touchpointKindLabel(touchpoint)} · ${touchpointPinSummary(touchpoint)}`);
  322. const summary = element("div", "", touchpoint.summary);
  323. dom["board-tooltip"].append(key, detail, summary);
  324. dom["board-tooltip"].hidden = false;
  325. if (event) positionTooltip(event);
  326. else positionTooltipForTouchpoint(touchpoint);
  327. }
  328. function showPinTooltip(event, touchpoint, pin) {
  329. dom["board-tooltip"].replaceChildren();
  330. dom["board-tooltip"].append(
  331. element("div", "tooltip-key", `${touchpoint.reference}.${pin.number || "机械孔"}`),
  332. element("div", "tooltip-role", padRoleLabel(pin.pad_role)),
  333. element("div", "", pin.net || "无命名网络"),
  334. element("div", "", pin.summary || evidenceLabel(pin.evidence_tier)),
  335. );
  336. dom["board-tooltip"].hidden = false;
  337. if (event) positionTooltip(event);
  338. else positionTooltipForTouchpoint(touchpoint);
  339. }
  340. function positionTooltip(event) {
  341. if (!event || dom["board-tooltip"].hidden) return;
  342. const viewport = dom["board-viewport"].getBoundingClientRect();
  343. const tooltip = dom["board-tooltip"];
  344. const left = Math.min(event.clientX - viewport.left + 12, viewport.width - tooltip.offsetWidth - 12);
  345. const top = Math.min(event.clientY - viewport.top + 12, viewport.height - tooltip.offsetHeight - 12);
  346. tooltip.style.left = `${Math.max(8, left)}px`;
  347. tooltip.style.top = `${Math.max(8, top)}px`;
  348. }
  349. function positionTooltipForTouchpoint(touchpoint) {
  350. const point = dom["board-svg"].createSVGPoint();
  351. point.x = touchpoint.view_position.x;
  352. point.y = touchpoint.view_position.y;
  353. const screen = point.matrixTransform(dom["board-svg"].getScreenCTM());
  354. positionTooltip({clientX: screen.x, clientY: screen.y});
  355. }
  356. function hideTooltip() {
  357. dom["board-tooltip"].hidden = true;
  358. }
  359. function renderSelectionOverlay() {
  360. dom["selection-layer"].replaceChildren();
  361. dom["net-layer"].replaceChildren();
  362. if (!state.selectedTouchpoint) return;
  363. const bounds = effectiveBounds(state.selectedTouchpoint.view_bounds, 4.2);
  364. const pad = 0.8;
  365. const x = bounds.x - pad;
  366. const y = bounds.y - pad;
  367. const width = bounds.width + pad * 2;
  368. const height = bounds.height + pad * 2;
  369. dom["selection-layer"].append(
  370. svgElement("rect", {x, y, width, height, rx: 0.55, class: "selection-reticle"}),
  371. svgElement("line", {x1: x - 1.4, y1: y + height / 2, x2: x + 1.1, y2: y + height / 2, class: "selection-cross"}),
  372. svgElement("line", {x1: x + width - 1.1, y1: y + height / 2, x2: x + width + 1.4, y2: y + height / 2, class: "selection-cross"}),
  373. svgElement("line", {x1: x + width / 2, y1: y - 1.4, x2: x + width / 2, y2: y + 1.1, class: "selection-cross"}),
  374. svgElement("line", {x1: x + width / 2, y1: y + height - 1.1, x2: x + width / 2, y2: y + height + 1.4, class: "selection-cross"}),
  375. );
  376. if (!state.selectedPin?.net) return;
  377. for (const item of sameNetPins(state.data, state.selectedPin.net)) {
  378. dom["net-layer"].append(
  379. svgElement("circle", {
  380. cx: item.pin.view_position.x,
  381. cy: item.pin.view_position.y,
  382. r: Math.max(Number(item.pin.size.width), Number(item.pin.size.height), 1.3),
  383. class: "net-highlight",
  384. }),
  385. );
  386. }
  387. }
  388. function selectTouchpoint(touchpoint, pin = null, openDrawer = false) {
  389. state.selectedTouchpoint = touchpoint;
  390. state.selectedPin = pin;
  391. dom["selection-readout"].textContent = pin
  392. ? `${touchpoint.reference}.${pin.number || "机械孔"} · ${padRoleLabel(pin.pad_role)} · ${pin.net || "无网络"}`
  393. : `${touchpoint.reference} · ${touchpointPinSummary(touchpoint)}`;
  394. if (openDrawer) setDrawerCollapsed(false);
  395. renderBoardMarkers();
  396. renderDetail();
  397. }
  398. function renderEmptyDetail(title, subtitle) {
  399. dom["detail-content"].replaceChildren();
  400. const wrapper = element("div", "empty-panel");
  401. wrapper.append(element("strong", "", title), element("span", "empty-stats", subtitle));
  402. dom["detail-content"].append(wrapper);
  403. }
  404. function fact(label, value) {
  405. const wrapper = element("div", "fact");
  406. wrapper.append(element("span", "fact-label", label), element("span", "fact-value", value));
  407. return wrapper;
  408. }
  409. function renderConnectorLayout(touchpoint, groups) {
  410. const connector = touchpoint.connector;
  411. const section = element("section", "connector-layout");
  412. const header = element("div", "connector-layout-header");
  413. header.append(
  414. element("h3", "section-title connector-layout-title", "板正面接触针排列"),
  415. element("span", `evidence-tag${connector.review_status === "cross_verified" ? " verified" : ""}`, evidenceLabel(connector.review_status)),
  416. );
  417. section.append(header);
  418. if (!groups.contactRows.length) {
  419. section.append(element("div", "risk-note", "该连接器尚无经过复核的接触针顺序。"));
  420. return section;
  421. }
  422. const orientation = element("div", "connector-orientation");
  423. orientation.append(element("span", "connector-axis connector-axis-top", "上"));
  424. const middle = element("div", "connector-axis-row");
  425. middle.append(element("span", "connector-axis", "左"));
  426. const grid = element("div", "connector-grid");
  427. const columns = Math.max(...groups.contactRows.map((row) => row.length), 1);
  428. for (const pins of groups.contactRows) {
  429. const row = element("div", "connector-grid-row");
  430. row.style.setProperty("--connector-columns", String(columns));
  431. for (const pin of pins) {
  432. const button = element("button", `connector-contact${state.selectedPin?.id === pin.id ? " is-selected" : ""}`, pin.number);
  433. button.type = "button";
  434. button.dataset.pinId = pin.id;
  435. button.setAttribute("aria-label", `${touchpoint.reference}.${pin.number},板正面第 ${pin.board_order} 位`);
  436. button.addEventListener("click", () => selectTouchpoint(touchpoint, pin, true));
  437. row.append(button);
  438. }
  439. grid.append(row);
  440. }
  441. middle.append(grid, element("span", "connector-axis", "右"));
  442. orientation.append(middle, element("span", "connector-axis connector-axis-bottom", "下"));
  443. section.append(orientation);
  444. section.append(
  445. element(
  446. "div",
  447. "connector-layout-meta",
  448. `${connector.profile} · ${connector.contact_count} 接触针 · ${connector.auxiliary_pad_count} 辅助焊盘`,
  449. ),
  450. element(
  451. "div",
  452. "connector-perspective-note",
  453. "板正面俯视:按页面上/下/左/右读取;线缆端或对接面可能是镜像。",
  454. ),
  455. );
  456. return section;
  457. }
  458. function renderPinRow(touchpoint, pin) {
  459. const row = element("button", `pin-row${state.selectedPin?.id === pin.id ? " is-selected" : ""}`);
  460. row.type = "button";
  461. row.dataset.pin = pin.number;
  462. row.dataset.pinId = pin.id;
  463. row.dataset.padRole = pin.pad_role;
  464. const primary = element("span", "pin-primary");
  465. primary.append(
  466. element("span", "pin-summary", pin.summary),
  467. element("span", "pin-net", `原始网络:${pin.net || "无命名网络"}`),
  468. );
  469. row.append(
  470. element("span", "pin-number", pin.number || "孔"),
  471. primary,
  472. element("span", "pin-direction", pin.pad_role === "contact" ? directionLabel(pin.direction) : padRoleLabel(pin.pad_role)),
  473. );
  474. row.addEventListener("click", () => selectTouchpoint(touchpoint, pin, true));
  475. return row;
  476. }
  477. function appendPinSection(container, touchpoint, title, pins) {
  478. if (!pins.length) return;
  479. container.append(element("h3", "section-title", title));
  480. const pinList = element("div", "pin-list");
  481. for (const pin of pins) pinList.append(renderPinRow(touchpoint, pin));
  482. container.append(pinList);
  483. }
  484. function renderDetail() {
  485. const touchpoint = state.selectedTouchpoint;
  486. if (!touchpoint) {
  487. const counts = state.data?.counts;
  488. renderEmptyDetail(
  489. "未选择座子",
  490. counts ? `${counts.touchpoints} 个座子 · ${counts.connector_contacts} 个 CON 接触针 · ${counts.connector_auxiliary_pads} 个 CON 辅助焊盘` : "",
  491. );
  492. return;
  493. }
  494. dom["detail-content"].replaceChildren();
  495. const heading = element("div", "detail-heading");
  496. const headingText = element("div");
  497. headingText.append(element("h2", "detail-reference", touchpoint.reference), element("p", "detail-summary", touchpoint.summary));
  498. heading.append(headingText, element("span", "category-tag", touchpointKindLabel(touchpoint)));
  499. const facts = element("div", "detail-facts");
  500. if (touchpoint.connector) {
  501. facts.append(
  502. fact("接触针", touchpoint.connector.contact_count),
  503. fact("辅助焊盘", touchpoint.connector.auxiliary_pad_count),
  504. fact("总焊盘", touchpoint.pins.length),
  505. fact("板面", touchpoint.side === "front" ? "正面" : "背面"),
  506. fact("坐标", `${formatNumber(touchpoint.position.x)} / ${formatNumber(touchpoint.position.y)} mm`),
  507. fact("旋转", `${formatNumber(touchpoint.rotation, 1)}°`),
  508. );
  509. } else {
  510. facts.append(
  511. fact("针脚数量", touchpoint.pins.length),
  512. fact("板面", touchpoint.side === "front" ? "正面" : "背面"),
  513. fact("坐标", `${formatNumber(touchpoint.position.x)} / ${formatNumber(touchpoint.position.y)} mm`),
  514. fact("旋转", `${formatNumber(touchpoint.rotation, 1)}°`),
  515. );
  516. }
  517. dom["detail-content"].append(heading, facts);
  518. if (touchpoint.connector) {
  519. const groups = connectorPinGroups(touchpoint);
  520. dom["detail-content"].append(renderConnectorLayout(touchpoint, groups));
  521. appendPinSection(dom["detail-content"], touchpoint, "接触针(板正面顺序)", groups.contacts);
  522. appendPinSection(dom["detail-content"], touchpoint, "屏蔽与机械焊盘", groups.auxiliary);
  523. } else {
  524. appendPinSection(dom["detail-content"], touchpoint, "针脚", touchpoint.pins);
  525. }
  526. if (state.selectedPin) dom["detail-content"].append(renderPinDetail(touchpoint, state.selectedPin));
  527. }
  528. function renderPinDetail(touchpoint, pin) {
  529. const wrapper = element("section", "pin-detail");
  530. const header = element("div", "pin-detail-header");
  531. header.append(
  532. element("h3", "", `${touchpoint.reference}.${pin.number || "机械孔"}`),
  533. element("span", `evidence-tag${pin.evidence_tier === "cross_verified" ? " verified" : ""}`, evidenceLabel(pin.evidence_tier)),
  534. );
  535. wrapper.append(header);
  536. const programmingGuide = renderProgrammingGuide(pin);
  537. if (programmingGuide) wrapper.append(programmingGuide);
  538. wrapper.append(element("h4", "section-title", "物理与电气事实"));
  539. const facts = element("div", "detail-facts");
  540. const programmableTarget = pin.fpga
  541. ? "FPGA U3"
  542. : pin.mcu
  543. ? `${pin.mcu.family} ${pin.mcu.device}`
  544. : "无直接可编程映射";
  545. const devicePin = pin.fpga?.ball
  546. ? `FPGA ${pin.fpga.ball}`
  547. : pin.mcu
  548. ? `${pin.mcu.device}.${pin.mcu.pin} (${pin.mcu.signal})`
  549. : "无已验证映射";
  550. const boardPosition = pin.board_order == null
  551. ? "不属于外部接触针"
  552. : `第 ${pin.board_order} 位 · 第 ${pin.row} 行 / 第 ${pin.column} 列`;
  553. facts.append(
  554. fact("焊盘角色", padRoleLabel(pin.pad_role)),
  555. fact("板正面位置", boardPosition),
  556. fact("原始网络", pin.net || "无命名网络"),
  557. fact("逻辑方向", directionLabel(pin.direction)),
  558. fact("外部电平", pin.external_level || "未知"),
  559. fact("可编程目标", programmableTarget),
  560. fact("器件引脚", devicePin),
  561. fact("I/O 标准", pin.fpga?.io_standard || "未知"),
  562. fact("板上 pull", pin.board_pull || "未注明"),
  563. fact("有效电平", activeLevelLabel(pin.active_level)),
  564. fact("极性", pin.polarity && pin.polarity !== "unknown" ? pin.polarity : "未注明"),
  565. );
  566. wrapper.append(facts);
  567. if (pin.external_components?.length) {
  568. wrapper.append(element("h4", "section-title", "相关板上器件"));
  569. const components = element("ul", "component-list");
  570. for (const item of pin.external_components) components.append(element("li", "", item));
  571. wrapper.append(components);
  572. }
  573. if (pin.path?.length) {
  574. wrapper.append(element("h4", "section-title", "已验证板内路径"));
  575. const path = element("ol", "path-list");
  576. for (const item of pin.path) path.append(element("li", "", item));
  577. wrapper.append(path);
  578. }
  579. wrapper.append(element("h4", "section-title", "证据来源"));
  580. const sources = element("ul", "source-list");
  581. for (const source of pin.evidence_sources ?? []) sources.append(element("li", "", source));
  582. wrapper.append(sources);
  583. if (pin.net) {
  584. const netMatches = sameNetPins(state.data, pin.net);
  585. wrapper.append(element("div", "info-note", `同网焊盘 ${netMatches.length} 个,板图已同步高亮。`));
  586. }
  587. const blockers = pin.recommendation?.reasons ?? [];
  588. if (!pin.recommendation?.eligible) {
  589. wrapper.append(element("div", "risk-note", `不可用于自动候选或 ADC:${blockers.join("、") || "证据条件不足"}。`));
  590. }
  591. const dedicatedConfigurationPin = String(pin.function_category || "").startsWith("jtag_");
  592. if (!pin.fpga || dedicatedConfigurationPin) {
  593. wrapper.append(
  594. element(
  595. "div",
  596. "info-note",
  597. dedicatedConfigurationPin
  598. ? "专用配置脚不使用用户 ADC 约束"
  599. : "此针不对应可生成 ADC 的 FPGA 用户 I/O。",
  600. ),
  601. );
  602. return wrapper;
  603. }
  604. wrapper.append(element("h4", "section-title", "ADC 片段"));
  605. const adc = element("div", "adc-controls");
  606. const input = element("input");
  607. input.type = "text";
  608. input.placeholder = "RTL 端口名";
  609. input.setAttribute("aria-label", "RTL 端口名");
  610. input.disabled = !pin.recommendation?.eligible || state.runtime.adcCopyEnabled !== true;
  611. const copy = element("button", "copy-button", "⧉");
  612. copy.type = "button";
  613. copy.title = "复制 ADC 片段";
  614. copy.setAttribute("aria-label", "复制 ADC 片段");
  615. copy.disabled = input.disabled;
  616. const status = element("div", "copy-status");
  617. copy.addEventListener("click", async () => {
  618. try {
  619. const snippet = generateAdcSnippet(pin, input.value.trim(), state.runtime);
  620. await copyText(snippet);
  621. status.textContent = "ADC 片段已复制";
  622. } catch (error) {
  623. status.textContent = error instanceof Error ? error.message : String(error);
  624. }
  625. });
  626. adc.append(input, copy);
  627. wrapper.append(adc, status, element("div", "risk-note", "这里只证明物理可用性,仍需检查当前工程约束冲突。"));
  628. return wrapper;
  629. }
  630. function appendGuidanceList(container, title, items, className = "guidance-list") {
  631. if (!Array.isArray(items) || !items.length) return;
  632. container.append(element("h4", "section-title", title));
  633. const list = element("ul", className);
  634. for (const item of items) list.append(element("li", "", item));
  635. container.append(list);
  636. }
  637. function renderProgrammingGuide(pin) {
  638. const programming = pin.programming;
  639. if (!programming) return null;
  640. const section = element("section", `programming-guide status-${programming.status || "unknown"}`);
  641. const heading = element("div", "programming-guide-heading");
  642. heading.append(
  643. element("h4", "section-title programming-title", "编程结论"),
  644. element(
  645. "span",
  646. `evidence-tag${programming.evidence_tier === "cross_verified" ? " verified" : ""}`,
  647. evidenceLabel(programming.evidence_tier),
  648. ),
  649. );
  650. section.append(heading, element("p", "programming-conclusion", programming.conclusion));
  651. section.append(element("h4", "section-title", "板内网络解释"));
  652. section.append(element("p", "programming-copy", programming.network_explanation));
  653. appendGuidanceList(section, "怎么接", programming.connection_guidance);
  654. section.append(
  655. element(
  656. "h4",
  657. "section-title",
  658. programming.status === "verified_mcu" ? "MCU 固件用法" : "HDL 用法",
  659. ),
  660. );
  661. section.append(element("p", "programming-copy", programming.hdl_guidance));
  662. appendGuidanceList(section, "约束要求", programming.constraints, "guidance-list constraint-list");
  663. appendGuidanceList(section, "风险与未知", programming.risks, "guidance-list risk-list");
  664. return section;
  665. }
  666. async function copyText(value) {
  667. if (navigator.clipboard?.writeText) return navigator.clipboard.writeText(value);
  668. const textarea = element("textarea");
  669. textarea.value = value;
  670. textarea.style.position = "fixed";
  671. textarea.style.opacity = "0";
  672. document.body.append(textarea);
  673. textarea.select();
  674. document.execCommand("copy");
  675. textarea.remove();
  676. }
  677. function renderCandidates() {
  678. if (!state.data) return;
  679. dom["candidate-list"].replaceChildren();
  680. if (state.runtime.recommendationsEnabled !== true) {
  681. dom["candidate-list"].append(element("div", "risk-note", "源文件状态不是当前值,选脚推荐已关闭。"));
  682. return;
  683. }
  684. const capability = dom["capability-select"].value;
  685. const candidates = findCandidates(state.data, capability);
  686. if (!candidates.length) {
  687. const empty = element("div", "empty-panel");
  688. empty.append(
  689. element("strong", "", "没有满足全部证据条件的候选"),
  690. element("span", "empty-stats", "未知、推断、保留、电源、地、机械焊盘和固定负载冲突均已排除"),
  691. );
  692. dom["candidate-list"].append(empty);
  693. return;
  694. }
  695. for (const candidate of candidates) {
  696. const row = element("button", "candidate-row");
  697. row.type = "button";
  698. row.append(
  699. element("span", "candidate-key", `${candidate.reference}.${candidate.pin.number} · ${candidate.pin.fpga.ball}`),
  700. element("span", "candidate-reason", candidate.reason),
  701. element("span", "candidate-warning", candidate.warning),
  702. );
  703. row.addEventListener("click", () => {
  704. switchTab("detail");
  705. selectTouchpoint(candidate.touchpoint, candidate.pin, true);
  706. focusOnTouchpoint(candidate.touchpoint);
  707. });
  708. dom["candidate-list"].append(row);
  709. }
  710. }
  711. function switchTab(tab) {
  712. state.activeTab = tab;
  713. const detail = tab === "detail";
  714. dom["detail-tab"].setAttribute("aria-selected", String(detail));
  715. dom["candidate-tab"].setAttribute("aria-selected", String(!detail));
  716. dom["detail-content"].hidden = !detail;
  717. dom["candidate-content"].hidden = detail;
  718. if (!detail) renderCandidates();
  719. }
  720. function renderSearchResults(query) {
  721. state.searchResults = searchBoard(state.data, query).slice(0, 24);
  722. state.activeSearchIndex = -1;
  723. dom["search-results"].replaceChildren();
  724. if (!query.trim()) {
  725. dom["search-results"].hidden = true;
  726. return;
  727. }
  728. dom["search-results"].hidden = false;
  729. if (!state.searchResults.length) {
  730. dom["search-results"].append(element("div", "empty-search", "没有匹配的座子或针脚"));
  731. return;
  732. }
  733. state.searchResults.forEach((result, index) => {
  734. const button = element("button", "search-result");
  735. button.type = "button";
  736. button.role = "option";
  737. button.dataset.index = String(index);
  738. button.setAttribute("aria-selected", "false");
  739. const key = result.type === "pin" ? `${result.reference}.${result.pinNumber}` : result.reference;
  740. const detail = result.type === "pin"
  741. ? `${result.pin.net || "无网络"} · ${result.pin.fpga?.ball || evidenceLabel(result.pin.evidence_tier)}`
  742. : `${touchpointKindLabel(result.touchpoint)} · ${result.touchpoint.summary}`;
  743. button.append(element("span", "result-key", key), element("span", "result-detail", detail));
  744. button.addEventListener("click", () => activateSearchResult(index));
  745. dom["search-results"].append(button);
  746. });
  747. }
  748. function activateSearchResult(index) {
  749. const result = state.searchResults[index];
  750. if (!result) return;
  751. state.categories.add(result.touchpoint.category);
  752. const checkbox = dom["category-filters"].querySelector(`input[value="${result.touchpoint.category}"]`);
  753. if (checkbox) checkbox.checked = true;
  754. selectTouchpoint(result.touchpoint, result.pin, true);
  755. focusOnTouchpoint(result.touchpoint);
  756. dom["board-search"].value = result.type === "pin" ? `${result.reference}.${result.pinNumber}` : result.reference;
  757. dom["search-results"].hidden = true;
  758. dom["board-svg"].focus();
  759. }
  760. function updateSearchSelection(nextIndex) {
  761. const options = [...dom["search-results"].querySelectorAll(".search-result")];
  762. if (!options.length) return;
  763. state.activeSearchIndex = (nextIndex + options.length) % options.length;
  764. options.forEach((option, index) => option.setAttribute("aria-selected", String(index === state.activeSearchIndex)));
  765. options[state.activeSearchIndex].scrollIntoView({block: "nearest"});
  766. }
  767. function focusOnTouchpoint(touchpoint) {
  768. const bounds = effectiveBounds(touchpoint.view_bounds, 8);
  769. const viewport = dom["board-svg"].getBoundingClientRect();
  770. const aspect = Math.max(viewport.width / Math.max(viewport.height, 1), 1);
  771. let width = Math.max(bounds.width * 3.4, state.baseViewBox.width / 12);
  772. let height = width / aspect;
  773. if (height < bounds.height * 3.4) {
  774. height = bounds.height * 3.4;
  775. width = height * aspect;
  776. }
  777. state.viewBox = {
  778. x: bounds.x + bounds.width / 2 - width / 2,
  779. y: bounds.y + bounds.height / 2 - height / 2,
  780. width,
  781. height,
  782. };
  783. clampViewBox();
  784. updateViewBox();
  785. }
  786. function clampViewBox() {
  787. if (!state.viewBox || !state.baseViewBox) return;
  788. const marginX = state.baseViewBox.width * 0.25;
  789. const marginY = state.baseViewBox.height * 0.4;
  790. const minX = state.baseViewBox.x - marginX;
  791. const maxX = state.baseViewBox.x + state.baseViewBox.width + marginX - state.viewBox.width;
  792. const minY = state.baseViewBox.y - marginY;
  793. const maxY = state.baseViewBox.y + state.baseViewBox.height + marginY - state.viewBox.height;
  794. state.viewBox.x = Math.min(Math.max(state.viewBox.x, minX), Math.max(minX, maxX));
  795. state.viewBox.y = Math.min(Math.max(state.viewBox.y, minY), Math.max(minY, maxY));
  796. }
  797. function zoomAt(factor, clientX = null, clientY = null) {
  798. if (!state.viewBox || !state.baseViewBox) return;
  799. const minimumWidth = state.baseViewBox.width / 35;
  800. const maximumWidth = state.baseViewBox.width * 1.25;
  801. const newWidth = Math.min(Math.max(state.viewBox.width * factor, minimumWidth), maximumWidth);
  802. const ratio = newWidth / state.viewBox.width;
  803. const anchor = clientX == null ? {
  804. x: state.viewBox.x + state.viewBox.width / 2,
  805. y: state.viewBox.y + state.viewBox.height / 2,
  806. } : clientToSvg(clientX, clientY);
  807. state.viewBox = {
  808. x: anchor.x - (anchor.x - state.viewBox.x) * ratio,
  809. y: anchor.y - (anchor.y - state.viewBox.y) * ratio,
  810. width: newWidth,
  811. height: state.viewBox.height * ratio,
  812. };
  813. clampViewBox();
  814. updateViewBox();
  815. }
  816. function clientToSvg(clientX, clientY) {
  817. const point = dom["board-svg"].createSVGPoint();
  818. point.x = clientX;
  819. point.y = clientY;
  820. return point.matrixTransform(dom["board-svg"].getScreenCTM().inverse());
  821. }
  822. function resetView() {
  823. state.viewBox = {...state.baseViewBox};
  824. updateViewBox();
  825. }
  826. function setDrawerCollapsed(collapsed) {
  827. dom.app.classList.toggle("detail-collapsed", collapsed);
  828. dom["drawer-toggle"].setAttribute("aria-expanded", String(!collapsed));
  829. dom["drawer-toggle"].title = collapsed ? "展开详情" : "收起详情";
  830. dom["drawer-toggle"].setAttribute("aria-label", collapsed ? "展开详情" : "收起详情");
  831. }
  832. dom["category-filters"].addEventListener("change", (event) => {
  833. const input = event.target;
  834. if (!(input instanceof HTMLInputElement)) return;
  835. if (input.checked) state.categories.add(input.value);
  836. else state.categories.delete(input.value);
  837. renderBoardMarkers();
  838. });
  839. dom["layer-controls"].addEventListener("change", (event) => {
  840. const input = event.target;
  841. if (!(input instanceof HTMLInputElement)) return;
  842. const layer = dom[`layer-${input.value}`];
  843. if (layer) layer.hidden = !input.checked;
  844. });
  845. dom["zoom-in"].addEventListener("click", () => zoomAt(0.8));
  846. dom["zoom-out"].addEventListener("click", () => zoomAt(1.25));
  847. dom["reset-view"].addEventListener("click", resetView);
  848. dom["detail-tab"].addEventListener("click", () => switchTab("detail"));
  849. dom["candidate-tab"].addEventListener("click", () => switchTab("candidate"));
  850. dom["capability-select"].addEventListener("change", renderCandidates);
  851. dom["drawer-toggle"].addEventListener("click", () => setDrawerCollapsed(!dom.app.classList.contains("detail-collapsed")));
  852. dom["board-search"].addEventListener("input", (event) => {
  853. if (state.data) renderSearchResults(event.target.value);
  854. });
  855. dom["board-search"].addEventListener("keydown", (event) => {
  856. if (event.key === "ArrowDown") {
  857. event.preventDefault();
  858. updateSearchSelection(state.activeSearchIndex + 1);
  859. } else if (event.key === "ArrowUp") {
  860. event.preventDefault();
  861. updateSearchSelection(state.activeSearchIndex - 1);
  862. } else if (event.key === "Enter" && state.activeSearchIndex >= 0) {
  863. event.preventDefault();
  864. activateSearchResult(state.activeSearchIndex);
  865. } else if (event.key === "Escape") {
  866. dom["search-results"].hidden = true;
  867. }
  868. });
  869. document.addEventListener("pointerdown", (event) => {
  870. if (!dom["search-results"].contains(event.target) && event.target !== dom["board-search"]) {
  871. dom["search-results"].hidden = true;
  872. }
  873. });
  874. dom["board-svg"].addEventListener("wheel", (event) => {
  875. event.preventDefault();
  876. zoomAt(event.deltaY < 0 ? 0.82 : 1.22, event.clientX, event.clientY);
  877. }, {passive: false});
  878. dom["board-svg"].addEventListener("pointerdown", (event) => {
  879. if (event.target.closest?.(".hotspot, .pin-group")) return;
  880. dom["board-svg"].setPointerCapture(event.pointerId);
  881. dom["board-svg"].classList.add("is-panning");
  882. state.dragging = {pointerId: event.pointerId, x: event.clientX, y: event.clientY, viewBox: {...state.viewBox}};
  883. });
  884. dom["board-svg"].addEventListener("pointermove", (event) => {
  885. if (!state.dragging || state.dragging.pointerId !== event.pointerId) return;
  886. const bounds = dom["board-svg"].getBoundingClientRect();
  887. state.viewBox = {
  888. ...state.dragging.viewBox,
  889. x: state.dragging.viewBox.x - (event.clientX - state.dragging.x) * state.dragging.viewBox.width / bounds.width,
  890. y: state.dragging.viewBox.y - (event.clientY - state.dragging.y) * state.dragging.viewBox.height / bounds.height,
  891. };
  892. clampViewBox();
  893. updateViewBox();
  894. });
  895. function endPan(event) {
  896. if (!state.dragging || state.dragging.pointerId !== event.pointerId) return;
  897. state.dragging = null;
  898. dom["board-svg"].classList.remove("is-panning");
  899. }
  900. dom["board-svg"].addEventListener("pointerup", endPan);
  901. dom["board-svg"].addEventListener("pointercancel", endPan);
  902. dom["board-svg"].addEventListener("keydown", (event) => {
  903. const stepX = state.viewBox.width * 0.06;
  904. const stepY = state.viewBox.height * 0.08;
  905. if (event.key === "+" || event.key === "=") zoomAt(0.8);
  906. else if (event.key === "-") zoomAt(1.25);
  907. else if (event.key === "0") resetView();
  908. else if (["ArrowLeft", "ArrowRight", "ArrowUp", "ArrowDown"].includes(event.key)) {
  909. if (event.key === "ArrowLeft") state.viewBox.x -= stepX;
  910. if (event.key === "ArrowRight") state.viewBox.x += stepX;
  911. if (event.key === "ArrowUp") state.viewBox.y -= stepY;
  912. if (event.key === "ArrowDown") state.viewBox.y += stepY;
  913. clampViewBox();
  914. updateViewBox();
  915. } else return;
  916. event.preventDefault();
  917. });
  918. window.addEventListener("resize", () => {
  919. hideTooltip();
  920. if (window.innerWidth > 860) setDrawerCollapsed(false);
  921. });
  922. setDrawerCollapsed(window.innerWidth <= 860);
  923. loadApplication();