app.js 39 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049
  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. const contactPins = groups.contacts.length
  522. ? groups.contacts
  523. : touchpoint.pins.filter((pin) => pin.pad_role === "contact");
  524. const auxiliaryPins = groups.contacts.length
  525. ? groups.auxiliary
  526. : touchpoint.pins.filter((pin) => pin.pad_role !== "contact");
  527. appendPinSection(
  528. dom["detail-content"],
  529. touchpoint,
  530. groups.contacts.length ? "接触针(板正面顺序)" : "接触针(板数据库编号)",
  531. contactPins,
  532. );
  533. appendPinSection(dom["detail-content"], touchpoint, "屏蔽与机械焊盘", auxiliaryPins);
  534. } else {
  535. appendPinSection(dom["detail-content"], touchpoint, "针脚", touchpoint.pins);
  536. }
  537. if (state.selectedPin) dom["detail-content"].append(renderPinDetail(touchpoint, state.selectedPin));
  538. }
  539. function renderPinDetail(touchpoint, pin) {
  540. const wrapper = element("section", "pin-detail");
  541. const header = element("div", "pin-detail-header");
  542. header.append(
  543. element("h3", "", `${touchpoint.reference}.${pin.number || "机械孔"}`),
  544. element("span", `evidence-tag${pin.evidence_tier === "cross_verified" ? " verified" : ""}`, evidenceLabel(pin.evidence_tier)),
  545. );
  546. wrapper.append(header);
  547. const programmingGuide = renderProgrammingGuide(pin);
  548. if (programmingGuide) wrapper.append(programmingGuide);
  549. wrapper.append(element("h4", "section-title", "物理与电气事实"));
  550. const facts = element("div", "detail-facts");
  551. const programmableTarget = pin.fpga
  552. ? "FPGA U3"
  553. : pin.mcu
  554. ? `${pin.mcu.family} ${pin.mcu.device}`
  555. : "无直接可编程映射";
  556. const devicePin = pin.fpga?.ball
  557. ? `FPGA ${pin.fpga.ball}`
  558. : pin.mcu
  559. ? `${pin.mcu.device}.${pin.mcu.pin} (${pin.mcu.signal})`
  560. : "无已验证映射";
  561. const boardPosition = pin.board_order == null
  562. ? "不属于外部接触针"
  563. : `第 ${pin.board_order} 位 · 第 ${pin.row} 行 / 第 ${pin.column} 列`;
  564. facts.append(
  565. fact("焊盘角色", padRoleLabel(pin.pad_role)),
  566. fact("板正面位置", boardPosition),
  567. fact("原始网络", pin.net || "无命名网络"),
  568. fact("逻辑方向", directionLabel(pin.direction)),
  569. fact("外部电平", pin.external_level || "未知"),
  570. fact("可编程目标", programmableTarget),
  571. fact("器件引脚", devicePin),
  572. fact("I/O 标准", pin.fpga?.io_standard || "未知"),
  573. fact("板上 pull", pin.board_pull || "未注明"),
  574. fact("有效电平", activeLevelLabel(pin.active_level)),
  575. fact("极性", pin.polarity && pin.polarity !== "unknown" ? pin.polarity : "未注明"),
  576. );
  577. wrapper.append(facts);
  578. if (pin.external_components?.length) {
  579. wrapper.append(element("h4", "section-title", "相关板上器件"));
  580. const components = element("ul", "component-list");
  581. for (const item of pin.external_components) components.append(element("li", "", item));
  582. wrapper.append(components);
  583. }
  584. if (pin.path?.length) {
  585. wrapper.append(element("h4", "section-title", "已验证板内路径"));
  586. const path = element("ol", "path-list");
  587. for (const item of pin.path) path.append(element("li", "", item));
  588. wrapper.append(path);
  589. }
  590. wrapper.append(element("h4", "section-title", "证据来源"));
  591. const sources = element("ul", "source-list");
  592. for (const source of pin.evidence_sources ?? []) sources.append(element("li", "", source));
  593. wrapper.append(sources);
  594. if (pin.net) {
  595. const netMatches = sameNetPins(state.data, pin.net);
  596. wrapper.append(element("div", "info-note", `同网焊盘 ${netMatches.length} 个,板图已同步高亮。`));
  597. }
  598. const blockers = pin.recommendation?.reasons ?? [];
  599. if (!pin.recommendation?.eligible) {
  600. wrapper.append(element("div", "risk-note", `不可用于自动候选或 ADC:${blockers.join("、") || "证据条件不足"}。`));
  601. }
  602. const dedicatedConfigurationPin = String(pin.function_category || "").startsWith("jtag_");
  603. if (!pin.fpga || dedicatedConfigurationPin) {
  604. wrapper.append(
  605. element(
  606. "div",
  607. "info-note",
  608. dedicatedConfigurationPin
  609. ? "专用配置脚不使用用户 ADC 约束"
  610. : "此针不对应可生成 ADC 的 FPGA 用户 I/O。",
  611. ),
  612. );
  613. return wrapper;
  614. }
  615. wrapper.append(element("h4", "section-title", "ADC 片段"));
  616. const adc = element("div", "adc-controls");
  617. const input = element("input");
  618. input.type = "text";
  619. input.placeholder = "RTL 端口名";
  620. input.setAttribute("aria-label", "RTL 端口名");
  621. input.disabled = !pin.recommendation?.eligible || state.runtime.adcCopyEnabled !== true;
  622. const copy = element("button", "copy-button", "⧉");
  623. copy.type = "button";
  624. copy.title = "复制 ADC 片段";
  625. copy.setAttribute("aria-label", "复制 ADC 片段");
  626. copy.disabled = input.disabled;
  627. const status = element("div", "copy-status");
  628. copy.addEventListener("click", async () => {
  629. try {
  630. const snippet = generateAdcSnippet(pin, input.value.trim(), state.runtime);
  631. await copyText(snippet);
  632. status.textContent = "ADC 片段已复制";
  633. } catch (error) {
  634. status.textContent = error instanceof Error ? error.message : String(error);
  635. }
  636. });
  637. adc.append(input, copy);
  638. wrapper.append(adc, status, element("div", "risk-note", "这里只证明物理可用性,仍需检查当前工程约束冲突。"));
  639. return wrapper;
  640. }
  641. function appendGuidanceList(container, title, items, className = "guidance-list") {
  642. if (!Array.isArray(items) || !items.length) return;
  643. container.append(element("h4", "section-title", title));
  644. const list = element("ul", className);
  645. for (const item of items) list.append(element("li", "", item));
  646. container.append(list);
  647. }
  648. function renderProgrammingGuide(pin) {
  649. const programming = pin.programming;
  650. if (!programming) return null;
  651. const section = element("section", `programming-guide status-${programming.status || "unknown"}`);
  652. const heading = element("div", "programming-guide-heading");
  653. heading.append(
  654. element("h4", "section-title programming-title", "编程结论"),
  655. element(
  656. "span",
  657. `evidence-tag${programming.evidence_tier === "cross_verified" ? " verified" : ""}`,
  658. evidenceLabel(programming.evidence_tier),
  659. ),
  660. );
  661. section.append(heading, element("p", "programming-conclusion", programming.conclusion));
  662. section.append(element("h4", "section-title", "板内网络解释"));
  663. section.append(element("p", "programming-copy", programming.network_explanation));
  664. appendGuidanceList(section, "怎么接", programming.connection_guidance);
  665. section.append(
  666. element(
  667. "h4",
  668. "section-title",
  669. programming.status === "verified_mcu" ? "MCU 固件用法" : "HDL 用法",
  670. ),
  671. );
  672. section.append(element("p", "programming-copy", programming.hdl_guidance));
  673. appendGuidanceList(section, "约束要求", programming.constraints, "guidance-list constraint-list");
  674. appendGuidanceList(section, "风险与未知", programming.risks, "guidance-list risk-list");
  675. return section;
  676. }
  677. async function copyText(value) {
  678. if (navigator.clipboard?.writeText) return navigator.clipboard.writeText(value);
  679. const textarea = element("textarea");
  680. textarea.value = value;
  681. textarea.style.position = "fixed";
  682. textarea.style.opacity = "0";
  683. document.body.append(textarea);
  684. textarea.select();
  685. document.execCommand("copy");
  686. textarea.remove();
  687. }
  688. function renderCandidates() {
  689. if (!state.data) return;
  690. dom["candidate-list"].replaceChildren();
  691. if (state.runtime.recommendationsEnabled !== true) {
  692. dom["candidate-list"].append(element("div", "risk-note", "源文件状态不是当前值,选脚推荐已关闭。"));
  693. return;
  694. }
  695. const capability = dom["capability-select"].value;
  696. const candidates = findCandidates(state.data, capability);
  697. if (!candidates.length) {
  698. const empty = element("div", "empty-panel");
  699. empty.append(
  700. element("strong", "", "没有满足全部证据条件的候选"),
  701. element("span", "empty-stats", "未知、推断、保留、电源、地、机械焊盘和固定负载冲突均已排除"),
  702. );
  703. dom["candidate-list"].append(empty);
  704. return;
  705. }
  706. for (const candidate of candidates) {
  707. const row = element("button", "candidate-row");
  708. row.type = "button";
  709. row.append(
  710. element("span", "candidate-key", `${candidate.reference}.${candidate.pin.number} · ${candidate.pin.fpga.ball}`),
  711. element("span", "candidate-reason", candidate.reason),
  712. element("span", "candidate-warning", candidate.warning),
  713. );
  714. row.addEventListener("click", () => {
  715. switchTab("detail");
  716. selectTouchpoint(candidate.touchpoint, candidate.pin, true);
  717. focusOnTouchpoint(candidate.touchpoint);
  718. });
  719. dom["candidate-list"].append(row);
  720. }
  721. }
  722. function switchTab(tab) {
  723. state.activeTab = tab;
  724. const detail = tab === "detail";
  725. dom["detail-tab"].setAttribute("aria-selected", String(detail));
  726. dom["candidate-tab"].setAttribute("aria-selected", String(!detail));
  727. dom["detail-content"].hidden = !detail;
  728. dom["candidate-content"].hidden = detail;
  729. if (!detail) renderCandidates();
  730. }
  731. function renderSearchResults(query) {
  732. state.searchResults = searchBoard(state.data, query).slice(0, 24);
  733. state.activeSearchIndex = -1;
  734. dom["search-results"].replaceChildren();
  735. if (!query.trim()) {
  736. dom["search-results"].hidden = true;
  737. return;
  738. }
  739. dom["search-results"].hidden = false;
  740. if (!state.searchResults.length) {
  741. dom["search-results"].append(element("div", "empty-search", "没有匹配的座子或针脚"));
  742. return;
  743. }
  744. state.searchResults.forEach((result, index) => {
  745. const button = element("button", "search-result");
  746. button.type = "button";
  747. button.role = "option";
  748. button.dataset.index = String(index);
  749. button.setAttribute("aria-selected", "false");
  750. const key = result.type === "pin" ? `${result.reference}.${result.pinNumber}` : result.reference;
  751. const detail = result.type === "pin"
  752. ? `${result.pin.net || "无网络"} · ${result.pin.fpga?.ball || evidenceLabel(result.pin.evidence_tier)}`
  753. : `${touchpointKindLabel(result.touchpoint)} · ${result.touchpoint.summary}`;
  754. button.append(element("span", "result-key", key), element("span", "result-detail", detail));
  755. button.addEventListener("click", () => activateSearchResult(index));
  756. dom["search-results"].append(button);
  757. });
  758. }
  759. function activateSearchResult(index) {
  760. const result = state.searchResults[index];
  761. if (!result) return;
  762. state.categories.add(result.touchpoint.category);
  763. const checkbox = dom["category-filters"].querySelector(`input[value="${result.touchpoint.category}"]`);
  764. if (checkbox) checkbox.checked = true;
  765. selectTouchpoint(result.touchpoint, result.pin, true);
  766. focusOnTouchpoint(result.touchpoint);
  767. dom["board-search"].value = result.type === "pin" ? `${result.reference}.${result.pinNumber}` : result.reference;
  768. dom["search-results"].hidden = true;
  769. dom["board-svg"].focus();
  770. }
  771. function updateSearchSelection(nextIndex) {
  772. const options = [...dom["search-results"].querySelectorAll(".search-result")];
  773. if (!options.length) return;
  774. state.activeSearchIndex = (nextIndex + options.length) % options.length;
  775. options.forEach((option, index) => option.setAttribute("aria-selected", String(index === state.activeSearchIndex)));
  776. options[state.activeSearchIndex].scrollIntoView({block: "nearest"});
  777. }
  778. function focusOnTouchpoint(touchpoint) {
  779. const bounds = effectiveBounds(touchpoint.view_bounds, 8);
  780. const viewport = dom["board-svg"].getBoundingClientRect();
  781. const aspect = Math.max(viewport.width / Math.max(viewport.height, 1), 1);
  782. let width = Math.max(bounds.width * 3.4, state.baseViewBox.width / 12);
  783. let height = width / aspect;
  784. if (height < bounds.height * 3.4) {
  785. height = bounds.height * 3.4;
  786. width = height * aspect;
  787. }
  788. state.viewBox = {
  789. x: bounds.x + bounds.width / 2 - width / 2,
  790. y: bounds.y + bounds.height / 2 - height / 2,
  791. width,
  792. height,
  793. };
  794. clampViewBox();
  795. updateViewBox();
  796. }
  797. function clampViewBox() {
  798. if (!state.viewBox || !state.baseViewBox) return;
  799. const marginX = state.baseViewBox.width * 0.25;
  800. const marginY = state.baseViewBox.height * 0.4;
  801. const minX = state.baseViewBox.x - marginX;
  802. const maxX = state.baseViewBox.x + state.baseViewBox.width + marginX - state.viewBox.width;
  803. const minY = state.baseViewBox.y - marginY;
  804. const maxY = state.baseViewBox.y + state.baseViewBox.height + marginY - state.viewBox.height;
  805. state.viewBox.x = Math.min(Math.max(state.viewBox.x, minX), Math.max(minX, maxX));
  806. state.viewBox.y = Math.min(Math.max(state.viewBox.y, minY), Math.max(minY, maxY));
  807. }
  808. function zoomAt(factor, clientX = null, clientY = null) {
  809. if (!state.viewBox || !state.baseViewBox) return;
  810. const minimumWidth = state.baseViewBox.width / 35;
  811. const maximumWidth = state.baseViewBox.width * 1.25;
  812. const newWidth = Math.min(Math.max(state.viewBox.width * factor, minimumWidth), maximumWidth);
  813. const ratio = newWidth / state.viewBox.width;
  814. const anchor = clientX == null ? {
  815. x: state.viewBox.x + state.viewBox.width / 2,
  816. y: state.viewBox.y + state.viewBox.height / 2,
  817. } : clientToSvg(clientX, clientY);
  818. state.viewBox = {
  819. x: anchor.x - (anchor.x - state.viewBox.x) * ratio,
  820. y: anchor.y - (anchor.y - state.viewBox.y) * ratio,
  821. width: newWidth,
  822. height: state.viewBox.height * ratio,
  823. };
  824. clampViewBox();
  825. updateViewBox();
  826. }
  827. function clientToSvg(clientX, clientY) {
  828. const point = dom["board-svg"].createSVGPoint();
  829. point.x = clientX;
  830. point.y = clientY;
  831. return point.matrixTransform(dom["board-svg"].getScreenCTM().inverse());
  832. }
  833. function resetView() {
  834. state.viewBox = {...state.baseViewBox};
  835. updateViewBox();
  836. }
  837. function setDrawerCollapsed(collapsed) {
  838. dom.app.classList.toggle("detail-collapsed", collapsed);
  839. dom["drawer-toggle"].setAttribute("aria-expanded", String(!collapsed));
  840. dom["drawer-toggle"].title = collapsed ? "展开详情" : "收起详情";
  841. dom["drawer-toggle"].setAttribute("aria-label", collapsed ? "展开详情" : "收起详情");
  842. }
  843. dom["category-filters"].addEventListener("change", (event) => {
  844. const input = event.target;
  845. if (!(input instanceof HTMLInputElement)) return;
  846. if (input.checked) state.categories.add(input.value);
  847. else state.categories.delete(input.value);
  848. renderBoardMarkers();
  849. });
  850. dom["layer-controls"].addEventListener("change", (event) => {
  851. const input = event.target;
  852. if (!(input instanceof HTMLInputElement)) return;
  853. const layer = dom[`layer-${input.value}`];
  854. if (layer) layer.hidden = !input.checked;
  855. });
  856. dom["zoom-in"].addEventListener("click", () => zoomAt(0.8));
  857. dom["zoom-out"].addEventListener("click", () => zoomAt(1.25));
  858. dom["reset-view"].addEventListener("click", resetView);
  859. dom["detail-tab"].addEventListener("click", () => switchTab("detail"));
  860. dom["candidate-tab"].addEventListener("click", () => switchTab("candidate"));
  861. dom["capability-select"].addEventListener("change", renderCandidates);
  862. dom["drawer-toggle"].addEventListener("click", () => setDrawerCollapsed(!dom.app.classList.contains("detail-collapsed")));
  863. dom["board-search"].addEventListener("input", (event) => {
  864. if (state.data) renderSearchResults(event.target.value);
  865. });
  866. dom["board-search"].addEventListener("keydown", (event) => {
  867. if (event.key === "ArrowDown") {
  868. event.preventDefault();
  869. updateSearchSelection(state.activeSearchIndex + 1);
  870. } else if (event.key === "ArrowUp") {
  871. event.preventDefault();
  872. updateSearchSelection(state.activeSearchIndex - 1);
  873. } else if (event.key === "Enter" && state.activeSearchIndex >= 0) {
  874. event.preventDefault();
  875. activateSearchResult(state.activeSearchIndex);
  876. } else if (event.key === "Escape") {
  877. dom["search-results"].hidden = true;
  878. }
  879. });
  880. document.addEventListener("pointerdown", (event) => {
  881. if (!dom["search-results"].contains(event.target) && event.target !== dom["board-search"]) {
  882. dom["search-results"].hidden = true;
  883. }
  884. });
  885. dom["board-svg"].addEventListener("wheel", (event) => {
  886. event.preventDefault();
  887. zoomAt(event.deltaY < 0 ? 0.82 : 1.22, event.clientX, event.clientY);
  888. }, {passive: false});
  889. dom["board-svg"].addEventListener("pointerdown", (event) => {
  890. if (event.target.closest?.(".hotspot, .pin-group")) return;
  891. dom["board-svg"].setPointerCapture(event.pointerId);
  892. dom["board-svg"].classList.add("is-panning");
  893. state.dragging = {pointerId: event.pointerId, x: event.clientX, y: event.clientY, viewBox: {...state.viewBox}};
  894. });
  895. dom["board-svg"].addEventListener("pointermove", (event) => {
  896. if (!state.dragging || state.dragging.pointerId !== event.pointerId) return;
  897. const bounds = dom["board-svg"].getBoundingClientRect();
  898. state.viewBox = {
  899. ...state.dragging.viewBox,
  900. x: state.dragging.viewBox.x - (event.clientX - state.dragging.x) * state.dragging.viewBox.width / bounds.width,
  901. y: state.dragging.viewBox.y - (event.clientY - state.dragging.y) * state.dragging.viewBox.height / bounds.height,
  902. };
  903. clampViewBox();
  904. updateViewBox();
  905. });
  906. function endPan(event) {
  907. if (!state.dragging || state.dragging.pointerId !== event.pointerId) return;
  908. state.dragging = null;
  909. dom["board-svg"].classList.remove("is-panning");
  910. }
  911. dom["board-svg"].addEventListener("pointerup", endPan);
  912. dom["board-svg"].addEventListener("pointercancel", endPan);
  913. dom["board-svg"].addEventListener("keydown", (event) => {
  914. const stepX = state.viewBox.width * 0.06;
  915. const stepY = state.viewBox.height * 0.08;
  916. if (event.key === "+" || event.key === "=") zoomAt(0.8);
  917. else if (event.key === "-") zoomAt(1.25);
  918. else if (event.key === "0") resetView();
  919. else if (["ArrowLeft", "ArrowRight", "ArrowUp", "ArrowDown"].includes(event.key)) {
  920. if (event.key === "ArrowLeft") state.viewBox.x -= stepX;
  921. if (event.key === "ArrowRight") state.viewBox.x += stepX;
  922. if (event.key === "ArrowUp") state.viewBox.y -= stepY;
  923. if (event.key === "ArrowDown") state.viewBox.y += stepY;
  924. clampViewBox();
  925. updateViewBox();
  926. } else return;
  927. event.preventDefault();
  928. });
  929. window.addEventListener("resize", () => {
  930. hideTooltip();
  931. if (window.innerWidth > 860) setDrawerCollapsed(false);
  932. });
  933. setDrawerCollapsed(window.innerWidth <= 860);
  934. loadApplication();