app.js 63 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627
  1. import {
  2. connectorPinGroups,
  3. displayBounds,
  4. displayPoint,
  5. extractPathResistors,
  6. findCandidates,
  7. generateAdcSnippet,
  8. itemVisibleOnSide,
  9. sameNetMembers,
  10. sameNetPins,
  11. searchBoard,
  12. } from "./board-logic.mjs";
  13. const SVG_NS = "http://www.w3.org/2000/svg";
  14. const LAYER_ASSETS = {
  15. front: {
  16. mask: "/generated/board-mask-edge.svg",
  17. silk: "/generated/board-silkscreen.svg",
  18. copper: "/generated/board-copper.svg",
  19. },
  20. back: {
  21. mask: "/generated/board-mask-edge-back.svg",
  22. silk: "/generated/board-silkscreen-back.svg",
  23. copper: "/generated/board-copper-back.svg",
  24. },
  25. };
  26. const state = {
  27. data: null,
  28. runtime: {status: "loading", recommendationsEnabled: false, adcCopyEnabled: false, staleSources: []},
  29. categories: new Set(["CON", "J", "PL", "TP"]),
  30. boardSide: "front",
  31. selectedTouchpoint: null,
  32. selectedResistor: null,
  33. selectedPin: null,
  34. baseViewBox: null,
  35. viewBox: null,
  36. dragging: null,
  37. activeTab: "detail",
  38. searchResults: [],
  39. activeSearchIndex: -1,
  40. };
  41. const dom = Object.fromEntries(
  42. [
  43. "app",
  44. "app-status",
  45. "board-summary",
  46. "board-search",
  47. "search-results",
  48. "stale-banner",
  49. "category-filters",
  50. "side-controls",
  51. "layer-controls",
  52. "zoom-in",
  53. "zoom-out",
  54. "reset-view",
  55. "board-viewport",
  56. "board-svg",
  57. "board-loading",
  58. "board-tooltip",
  59. "hotspot-layer",
  60. "pin-layer",
  61. "net-layer",
  62. "selection-layer",
  63. "layer-mask",
  64. "layer-silk",
  65. "layer-copper",
  66. "layer-photo",
  67. "photo-control",
  68. "photo-layer",
  69. "photo-label",
  70. "visible-count",
  71. "zoom-readout",
  72. "selection-readout",
  73. "detail-panel",
  74. "detail-tab",
  75. "candidate-tab",
  76. "detail-content",
  77. "candidate-content",
  78. "candidate-list",
  79. "capability-select",
  80. "drawer-toggle",
  81. ].map((id) => [id, document.getElementById(id)]),
  82. );
  83. function svgElement(name, attributes = {}) {
  84. const node = document.createElementNS(SVG_NS, name);
  85. for (const [key, value] of Object.entries(attributes)) node.setAttribute(key, String(value));
  86. return node;
  87. }
  88. function element(name, className = "", content = null) {
  89. const node = document.createElement(name);
  90. if (className) node.className = className;
  91. if (content != null) node.textContent = String(content);
  92. return node;
  93. }
  94. function formatNumber(value, digits = 3) {
  95. const number = Number(value);
  96. return Number.isFinite(number) ? number.toFixed(digits).replace(/\.0+$|(?<=\.[0-9]*?)0+$/g, "") : "未知";
  97. }
  98. function evidenceLabel(tier) {
  99. return {
  100. board_database: "板数据库原始值",
  101. cross_verified: "已交叉验证",
  102. name_inferred: "名称推断",
  103. unknown: "未知",
  104. }[tier] ?? "未知";
  105. }
  106. function directionLabel(direction) {
  107. return {
  108. input: "输入",
  109. output: "输出",
  110. bidirectional: "双向",
  111. passive: "无源",
  112. unknown: "未知",
  113. }[direction] ?? direction ?? "未知";
  114. }
  115. function activeLevelLabel(level) {
  116. return {
  117. high: "高电平有效",
  118. low: "低电平有效",
  119. rising_edge: "上升沿计步脉冲",
  120. state: "状态选择(非有效电平)",
  121. unknown: "未注明",
  122. }[level] ?? level ?? "未注明";
  123. }
  124. function categoryLabel(category) {
  125. return {CON: "连接器", J: "J 类对象", PL: "PL 器件", TP: "测试点", R: "电阻"}[category] ?? category;
  126. }
  127. function touchpointKindLabel(touchpoint) {
  128. if (touchpoint?.connector) return touchpoint.category === "CON" ? "连接器" : "调试接口";
  129. if (touchpoint?.category === "PL") return "电源器件";
  130. if (touchpoint?.category === "J") {
  131. const pins = Array.isArray(touchpoint.pins) ? touchpoint.pins : [];
  132. if (pins.length && pins.every((pin) => pin.mechanical === true)) return "安装孔";
  133. if (pins.some((pin) => pin.function_category === "manufacturing_mark")) return "制造标记";
  134. }
  135. return categoryLabel(touchpoint?.category);
  136. }
  137. function padRoleLabel(role) {
  138. return {
  139. contact: "接触针",
  140. shield: "屏蔽固定焊盘",
  141. mechanical: "机械孔",
  142. unknown: "未分类焊盘",
  143. }[role] ?? "未分类焊盘";
  144. }
  145. function touchpointPinSummary(touchpoint) {
  146. if (touchpoint.connector) {
  147. return `${touchpoint.connector.contact_count} 接触针 · ${touchpoint.connector.auxiliary_pad_count} 辅助焊盘`;
  148. }
  149. return `${touchpoint.pins.length} 针`;
  150. }
  151. function setStatus(kind, text) {
  152. dom["app-status"].className = `status-badge status-${kind}`;
  153. dom["app-status"].textContent = text;
  154. }
  155. function applyRuntimeStatus() {
  156. const runtime = state.runtime;
  157. if (runtime.status === "pass") {
  158. setStatus("pass", "数据已校验");
  159. dom["stale-banner"].hidden = true;
  160. } else if (runtime.status === "stale_sources") {
  161. setStatus("stale", "来源已变化");
  162. dom["stale-banner"].hidden = false;
  163. dom["stale-banner"].textContent = `源文件与生成时不一致:${(runtime.staleSources ?? []).join(",")}。选脚推荐与 ADC 复制已关闭。`;
  164. } else {
  165. setStatus("error", "资产不可用");
  166. dom["stale-banner"].hidden = false;
  167. dom["stale-banner"].textContent = runtime.message || "生成资产未通过完整性校验。";
  168. }
  169. }
  170. async function loadApplication() {
  171. try {
  172. const [dataResponse, statusResponse] = await Promise.all([
  173. fetch("/generated/board-data.json", {cache: "no-store"}),
  174. fetch("/api/status", {cache: "no-store"}),
  175. ]);
  176. if (!dataResponse.ok) throw new Error(`板数据 HTTP ${dataResponse.status}`);
  177. if (!statusResponse.ok) throw new Error(`状态 HTTP ${statusResponse.status}`);
  178. state.data = await dataResponse.json();
  179. if (state.data?.schema !== "board-viewer-data-v2" || !Array.isArray(state.data?.resistors)) {
  180. throw new Error("生成数据过旧或缺少 resistors[],请重新 generate(需要 board-viewer-data-v2)。");
  181. }
  182. state.runtime = await statusResponse.json();
  183. initializeBoard();
  184. applyRuntimeStatus();
  185. } catch (error) {
  186. state.runtime = {
  187. status: "error",
  188. recommendationsEnabled: false,
  189. adcCopyEnabled: false,
  190. staleSources: [],
  191. message: error instanceof Error ? error.message : String(error),
  192. };
  193. applyRuntimeStatus();
  194. dom["board-loading"].textContent = "板数据载入失败";
  195. renderEmptyDetail("板数据不可用", state.runtime.message);
  196. }
  197. }
  198. function boardWidth() {
  199. return Number(state.data?.board?.view_box?.width) || 0;
  200. }
  201. function toDisplayPoint(point) {
  202. return displayPoint(point, boardWidth(), state.boardSide);
  203. }
  204. function toDisplayBounds(bounds) {
  205. return displayBounds(bounds, boardWidth(), state.boardSide);
  206. }
  207. function applyBoardSide() {
  208. const assets = LAYER_ASSETS[state.boardSide] || LAYER_ASSETS.front;
  209. dom["layer-mask"].setAttribute("href", assets.mask);
  210. dom["layer-silk"].setAttribute("href", assets.silk);
  211. dom["layer-copper"].setAttribute("href", assets.copper);
  212. const sideInput = dom["side-controls"]?.querySelector(`input[value="${state.boardSide}"]`);
  213. if (sideInput instanceof HTMLInputElement) sideInput.checked = true;
  214. dom["board-svg"].dataset.side = state.boardSide;
  215. const photoHidden = state.boardSide !== "front" || !state.data?.photo_overlay;
  216. if (dom["layer-photo"]) {
  217. dom["layer-photo"].hidden = photoHidden || !dom["photo-layer"]?.checked;
  218. }
  219. if (dom["photo-control"]) {
  220. dom["photo-control"].classList.toggle("disabled-control", state.boardSide !== "front");
  221. if (dom["photo-layer"]) dom["photo-layer"].disabled = state.boardSide !== "front" || !state.data?.photo_overlay;
  222. }
  223. }
  224. function setBoardSide(side, {rerender = true} = {}) {
  225. const next = side === "back" ? "back" : "front";
  226. if (state.boardSide === next) {
  227. if (rerender) applyBoardSide();
  228. return false;
  229. }
  230. state.boardSide = next;
  231. applyBoardSide();
  232. if (rerender) {
  233. renderBoardMarkers();
  234. }
  235. return true;
  236. }
  237. function ensureItemSide(item) {
  238. const side = item?.side === "back" ? "back" : "front";
  239. return setBoardSide(side, {rerender: false});
  240. }
  241. function initializeBoard() {
  242. const {board, counts} = state.data;
  243. const width = Number(board.view_box.width);
  244. const height = Number(board.view_box.height);
  245. const padding = Math.max(height * 0.08, 1.2);
  246. state.baseViewBox = {x: -padding, y: -padding, width: width + padding * 2, height: height + padding * 2};
  247. state.viewBox = {...state.baseViewBox};
  248. state.boardSide = "front";
  249. for (const image of [dom["layer-mask"], dom["layer-silk"], dom["layer-copper"], dom["layer-photo"]]) {
  250. image.setAttribute("x", "0");
  251. image.setAttribute("y", "0");
  252. image.setAttribute("width", String(width));
  253. image.setAttribute("height", String(height));
  254. }
  255. applyBoardSide();
  256. const backResistors = (state.data.resistors ?? []).filter((item) => item.side === "back").length;
  257. dom["board-summary"].textContent = `${board.name} · ${counts.touchpoints} 座子 · ${counts.resistors ?? 0} 电阻(背 ${backResistors}) · ${counts.connector_contacts} 个 CON 接触针`;
  258. dom["board-loading"].hidden = true;
  259. updateViewBox();
  260. renderBoardMarkers();
  261. configurePhotoOverlay();
  262. renderEmptyDetail(
  263. "未选择座子或电阻",
  264. `${counts.touchpoints} 个座子 · ${counts.resistors ?? 0} 个电阻 · ${counts.connector_contacts} 个 CON 接触针 · ${counts.connector_auxiliary_pads} 个 CON 辅助焊盘`,
  265. );
  266. renderCandidates();
  267. }
  268. function configurePhotoOverlay() {
  269. const overlay = state.data?.photo_overlay;
  270. if (!overlay) return;
  271. const matrix = Array.isArray(overlay.matrix) ? overlay.matrix : [];
  272. if (matrix.length !== 6 || !matrix.every(Number.isFinite)) return;
  273. const source = `/generated/${overlay.asset}`;
  274. const image = new Image();
  275. image.addEventListener("load", () => {
  276. dom["layer-photo"].setAttribute("href", source);
  277. dom["layer-photo"].setAttribute("width", String(image.naturalWidth));
  278. dom["layer-photo"].setAttribute("height", String(image.naturalHeight));
  279. dom["layer-photo"].setAttribute("transform", `matrix(${matrix.join(" ")})`);
  280. dom["photo-layer"].disabled = false;
  281. dom["photo-control"].classList.remove("disabled-control");
  282. dom["photo-control"].title = `已校准 ${overlay.control_point_count} 个控制点`;
  283. dom["photo-label"].textContent = "照片";
  284. });
  285. image.addEventListener("error", () => {
  286. dom["photo-control"].title = "照片资产载入失败";
  287. dom["photo-label"].textContent = "照片不可用";
  288. });
  289. image.src = source;
  290. }
  291. function updateViewBox() {
  292. if (!state.viewBox) return;
  293. const {x, y, width, height} = state.viewBox;
  294. dom["board-svg"].setAttribute("viewBox", `${x} ${y} ${width} ${height}`);
  295. const ratio = state.baseViewBox.width / width;
  296. const pinsInteractive = ratio >= 1.8;
  297. dom["board-svg"].classList.toggle("pins-interactive", pinsInteractive);
  298. for (const group of dom["pin-layer"].querySelectorAll(".pin-group")) {
  299. group.setAttribute("tabindex", pinsInteractive ? "0" : "-1");
  300. }
  301. dom["zoom-readout"].textContent = `${Math.round(ratio * 100)}%`;
  302. }
  303. function effectiveBounds(bounds, minimum = 3.2) {
  304. const width = Math.max(Number(bounds.width), minimum);
  305. const height = Math.max(Number(bounds.height), minimum);
  306. return {
  307. x: Number(bounds.x) - (width - Number(bounds.width)) / 2,
  308. y: Number(bounds.y) - (height - Number(bounds.height)) / 2,
  309. width,
  310. height,
  311. };
  312. }
  313. function renderBoardMarkers() {
  314. dom["hotspot-layer"].replaceChildren();
  315. dom["pin-layer"].replaceChildren();
  316. if (!state.data) return;
  317. let visibleTouchpoints = 0;
  318. let visibleResistors = 0;
  319. for (const touchpoint of state.data.touchpoints) {
  320. if (!state.categories.has(touchpoint.category)) continue;
  321. if (!itemVisibleOnSide(touchpoint, state.boardSide)) continue;
  322. visibleTouchpoints += 1;
  323. const bounds = effectiveBounds(toDisplayBounds(touchpoint.view_bounds));
  324. const hotspot = svgElement("rect", {
  325. x: bounds.x,
  326. y: bounds.y,
  327. width: bounds.width,
  328. height: bounds.height,
  329. rx: 0.45,
  330. class: `hotspot${state.selectedTouchpoint?.reference === touchpoint.reference ? " is-selected" : ""}`,
  331. tabindex: 0,
  332. role: "button",
  333. "aria-label": `${touchpoint.reference} ${touchpointKindLabel(touchpoint)} ${touchpointPinSummary(touchpoint)}`,
  334. "data-reference": touchpoint.reference,
  335. "data-side": touchpoint.side || "front",
  336. });
  337. hotspot.addEventListener("pointerenter", (event) => showTouchpointTooltip(event, touchpoint));
  338. hotspot.addEventListener("pointermove", positionTooltip);
  339. hotspot.addEventListener("pointerleave", hideTooltip);
  340. hotspot.addEventListener("focus", () => showTouchpointTooltip(null, touchpoint));
  341. hotspot.addEventListener("blur", hideTooltip);
  342. hotspot.addEventListener("click", (event) => {
  343. event.stopPropagation();
  344. selectTouchpoint(touchpoint, null, true);
  345. });
  346. hotspot.addEventListener("keydown", (event) => {
  347. if (event.key === "Enter" || event.key === " ") {
  348. event.preventDefault();
  349. selectTouchpoint(touchpoint, null, true);
  350. }
  351. });
  352. dom["hotspot-layer"].append(hotspot);
  353. for (const pin of touchpoint.pins) {
  354. const point = toDisplayPoint(pin.view_position);
  355. const group = svgElement("g", {
  356. class: `pin-group role-${pin.pad_role}${state.selectedTouchpoint?.reference === touchpoint.reference && state.selectedPin?.id === pin.id ? " is-selected" : ""}`,
  357. tabindex: dom["board-svg"].classList.contains("pins-interactive") ? 0 : -1,
  358. role: "button",
  359. "aria-label": `${touchpoint.reference}.${pin.number || "机械"} ${pin.net || "无网络"}`,
  360. "data-reference": touchpoint.reference,
  361. "data-pin": pin.number,
  362. "data-pin-id": pin.id,
  363. "data-pad-role": pin.pad_role,
  364. });
  365. const width = Math.max(Number(pin.size.width), Number(pin.size.drill_width), 0.65);
  366. const height = Math.max(Number(pin.size.height), Number(pin.size.drill_height), 0.65);
  367. const radius = Math.max(Math.min(width, height) / 2, 0.42);
  368. const hitRadius = Math.max(Math.min(width, height) / 2 + 0.15, 0.58);
  369. group.append(
  370. svgElement("circle", {cx: point.x, cy: point.y, r: hitRadius, class: "pin-hit"}),
  371. svgElement("circle", {cx: point.x, cy: point.y, r: radius, class: "pin-dot"}),
  372. );
  373. group.addEventListener("pointerenter", (event) => showPinTooltip(event, touchpoint, pin));
  374. group.addEventListener("pointermove", positionTooltip);
  375. group.addEventListener("pointerleave", hideTooltip);
  376. group.addEventListener("focus", () => showPinTooltip(null, touchpoint, pin));
  377. group.addEventListener("blur", hideTooltip);
  378. group.addEventListener("click", (event) => {
  379. event.stopPropagation();
  380. selectTouchpoint(touchpoint, pin, true);
  381. });
  382. group.addEventListener("keydown", (event) => {
  383. if (event.key === "Enter" || event.key === " ") {
  384. event.preventDefault();
  385. selectTouchpoint(touchpoint, pin, true);
  386. }
  387. });
  388. dom["pin-layer"].append(group);
  389. }
  390. }
  391. for (const resistor of state.data.resistors ?? []) {
  392. if (!state.categories.has("R")) continue;
  393. if (!itemVisibleOnSide(resistor, state.boardSide)) continue;
  394. visibleResistors += 1;
  395. const bounds = effectiveBounds(toDisplayBounds(resistor.view_bounds), 1.6);
  396. const selected = state.selectedResistor?.reference === resistor.reference;
  397. const hotspot = svgElement("rect", {
  398. x: bounds.x,
  399. y: bounds.y,
  400. width: bounds.width,
  401. height: bounds.height,
  402. rx: 0.25,
  403. class: `hotspot hotspot-resistor${selected ? " is-selected" : ""}`,
  404. tabindex: 0,
  405. role: "button",
  406. "aria-label": `${resistor.reference} 电阻 ${resistor.component_value || "未标注阻值"}`,
  407. "data-reference": resistor.reference,
  408. "data-kind": "resistor",
  409. "data-side": resistor.side || "front",
  410. });
  411. hotspot.addEventListener("pointerenter", (event) => showResistorTooltip(event, resistor));
  412. hotspot.addEventListener("pointermove", positionTooltip);
  413. hotspot.addEventListener("pointerleave", hideTooltip);
  414. hotspot.addEventListener("focus", () => showResistorTooltip(null, resistor));
  415. hotspot.addEventListener("blur", hideTooltip);
  416. hotspot.addEventListener("click", (event) => {
  417. event.stopPropagation();
  418. selectResistor(resistor, null, true);
  419. });
  420. hotspot.addEventListener("keydown", (event) => {
  421. if (event.key === "Enter" || event.key === " ") {
  422. event.preventDefault();
  423. selectResistor(resistor, null, true);
  424. }
  425. });
  426. dom["hotspot-layer"].append(hotspot);
  427. for (const pad of resistor.pads ?? []) {
  428. const point = toDisplayPoint(pad.view_position);
  429. const group = svgElement("g", {
  430. class: `pin-group role-${pad.pad_role} resistor-pad${selected && state.selectedPin?.number === pad.number ? " is-selected" : ""}`,
  431. tabindex: dom["board-svg"].classList.contains("pins-interactive") ? 0 : -1,
  432. role: "button",
  433. "aria-label": `${resistor.reference}.${pad.number || "机械"} ${pad.net || "无网络"}`,
  434. "data-reference": resistor.reference,
  435. "data-pin": pad.number,
  436. "data-kind": "resistor",
  437. "data-pad-role": pad.pad_role,
  438. });
  439. const width = Math.max(Number(pad.size?.width), Number(pad.size?.drill_width), 0.55);
  440. const height = Math.max(Number(pad.size?.height), Number(pad.size?.drill_height), 0.55);
  441. const radius = Math.max(Math.min(width, height) / 2, 0.35);
  442. const hitRadius = Math.max(radius + 0.12, 0.48);
  443. group.append(
  444. svgElement("circle", {cx: point.x, cy: point.y, r: hitRadius, class: "pin-hit"}),
  445. svgElement("circle", {cx: point.x, cy: point.y, r: radius, class: "pin-dot"}),
  446. );
  447. group.addEventListener("pointerenter", (event) => showResistorPadTooltip(event, resistor, pad));
  448. group.addEventListener("pointermove", positionTooltip);
  449. group.addEventListener("pointerleave", hideTooltip);
  450. group.addEventListener("click", (event) => {
  451. event.stopPropagation();
  452. selectResistor(resistor, pad, true);
  453. });
  454. dom["pin-layer"].append(group);
  455. }
  456. }
  457. const sideLabel = state.boardSide === "back" ? "背面" : "正面";
  458. dom["visible-count"].textContent = `${sideLabel} · ${visibleTouchpoints} 个座子 · ${visibleResistors} 个电阻`;
  459. renderSelectionOverlay();
  460. }
  461. function showTouchpointTooltip(event, touchpoint) {
  462. dom["board-tooltip"].replaceChildren();
  463. const key = element("div", "tooltip-key", touchpoint.reference);
  464. const detail = element("div", "", `${touchpointKindLabel(touchpoint)} · ${touchpointPinSummary(touchpoint)}`);
  465. const summary = element("div", "", touchpoint.summary);
  466. dom["board-tooltip"].append(key, detail, summary);
  467. dom["board-tooltip"].hidden = false;
  468. if (event) positionTooltip(event);
  469. else positionTooltipForTouchpoint(touchpoint);
  470. }
  471. function showPinTooltip(event, touchpoint, pin) {
  472. dom["board-tooltip"].replaceChildren();
  473. dom["board-tooltip"].append(
  474. element("div", "tooltip-key", `${touchpoint.reference}.${pin.number || "机械孔"}`),
  475. element("div", "tooltip-role", padRoleLabel(pin.pad_role)),
  476. element("div", "", pin.net || "无命名网络"),
  477. element("div", "", pin.summary || evidenceLabel(pin.evidence_tier)),
  478. );
  479. dom["board-tooltip"].hidden = false;
  480. if (event) positionTooltip(event);
  481. else positionTooltipForTouchpoint(touchpoint);
  482. }
  483. function showResistorTooltip(event, resistor) {
  484. dom["board-tooltip"].replaceChildren();
  485. const nets = (resistor.pads ?? []).filter((pad) => pad.net).map((pad) => pad.net);
  486. dom["board-tooltip"].append(
  487. element("div", "tooltip-key", resistor.reference),
  488. element("div", "", `电阻 · ${resistor.component_value || "阻值未标注"}`),
  489. element("div", "", nets.length ? nets.join(" ↔ ") : "无命名网络"),
  490. );
  491. dom["board-tooltip"].hidden = false;
  492. if (event) positionTooltip(event);
  493. else positionTooltipForBounds(toDisplayBounds(resistor.view_bounds));
  494. }
  495. function showResistorPadTooltip(event, resistor, pad) {
  496. dom["board-tooltip"].replaceChildren();
  497. dom["board-tooltip"].append(
  498. element("div", "tooltip-key", `${resistor.reference}.${pad.number || "机械孔"}`),
  499. element("div", "tooltip-role", pad.pad_role === "electrical" ? "电气焊盘" : "机械焊盘"),
  500. element("div", "", pad.net || "无命名网络"),
  501. element("div", "", resistor.component_value || "阻值未标注"),
  502. );
  503. dom["board-tooltip"].hidden = false;
  504. if (event) positionTooltip(event);
  505. else positionTooltipForBounds(toDisplayBounds(resistor.view_bounds));
  506. }
  507. function positionTooltip(event) {
  508. if (!event || dom["board-tooltip"].hidden) return;
  509. const viewport = dom["board-viewport"].getBoundingClientRect();
  510. const tooltip = dom["board-tooltip"];
  511. const left = Math.min(event.clientX - viewport.left + 12, viewport.width - tooltip.offsetWidth - 12);
  512. const top = Math.min(event.clientY - viewport.top + 12, viewport.height - tooltip.offsetHeight - 12);
  513. tooltip.style.left = `${Math.max(8, left)}px`;
  514. tooltip.style.top = `${Math.max(8, top)}px`;
  515. }
  516. function positionTooltipForTouchpoint(touchpoint) {
  517. positionTooltipForBounds(toDisplayBounds(touchpoint.view_bounds), toDisplayPoint(touchpoint.view_position));
  518. }
  519. function positionTooltipForBounds(bounds, point = null) {
  520. const anchor = point || {
  521. x: Number(bounds.x) + Number(bounds.width) / 2,
  522. y: Number(bounds.y) + Number(bounds.height) / 2,
  523. };
  524. const svgPoint = dom["board-svg"].createSVGPoint();
  525. svgPoint.x = anchor.x;
  526. svgPoint.y = anchor.y;
  527. const screen = svgPoint.matrixTransform(dom["board-svg"].getScreenCTM());
  528. positionTooltip({clientX: screen.x, clientY: screen.y});
  529. }
  530. function hideTooltip() {
  531. dom["board-tooltip"].hidden = true;
  532. }
  533. function appendResistorPadMarker(layer, pad) {
  534. const point = toDisplayPoint(pad.view_position);
  535. const width = Math.max(Number(pad.size?.width) || 0, Number(pad.view_bounds?.width) || 0, 0.2);
  536. const height = Math.max(Number(pad.size?.height) || 0, Number(pad.view_bounds?.height) || 0, 0.2);
  537. let rotation = Number(pad.rotation) || 0;
  538. if (state.boardSide === "back") rotation = -rotation;
  539. const shape = String(pad.shape || "rect").toLowerCase();
  540. const halo = 0.12;
  541. const isRound =
  542. shape.includes("circle")
  543. || shape.includes("round")
  544. || (shape.includes("oval") && Math.abs(width - height) < 0.05);
  545. if (isRound) {
  546. layer.append(
  547. svgElement("ellipse", {
  548. cx: point.x,
  549. cy: point.y,
  550. rx: width / 2 + halo,
  551. ry: height / 2 + halo,
  552. class: "resistor-pad-halo",
  553. }),
  554. svgElement("ellipse", {
  555. cx: point.x,
  556. cy: point.y,
  557. rx: width / 2,
  558. ry: height / 2,
  559. class: "resistor-pad-marker",
  560. "data-pad-id": pad.id || "",
  561. "data-pad-shape": shape || "circle",
  562. }),
  563. );
  564. return;
  565. }
  566. const group = svgElement("g", {
  567. transform: `rotate(${rotation} ${point.x} ${point.y})`,
  568. "data-pad-id": pad.id || "",
  569. "data-pad-shape": shape || "rect",
  570. });
  571. group.append(
  572. svgElement("rect", {
  573. x: point.x - width / 2 - halo,
  574. y: point.y - height / 2 - halo,
  575. width: width + halo * 2,
  576. height: height + halo * 2,
  577. class: "resistor-pad-halo",
  578. }),
  579. svgElement("rect", {
  580. x: point.x - width / 2,
  581. y: point.y - height / 2,
  582. width,
  583. height,
  584. class: "resistor-pad-marker",
  585. }),
  586. );
  587. layer.append(group);
  588. }
  589. function renderSelectionOverlay() {
  590. dom["selection-layer"].replaceChildren();
  591. dom["net-layer"].replaceChildren();
  592. const target = state.selectedResistor || state.selectedTouchpoint;
  593. if (!target || !itemVisibleOnSide(target, state.boardSide)) return;
  594. const bounds = effectiveBounds(toDisplayBounds(target.view_bounds), state.selectedResistor ? 2.4 : 4.2);
  595. const pad = state.selectedResistor ? 0.45 : 0.8;
  596. const x = bounds.x - pad;
  597. const y = bounds.y - pad;
  598. const width = bounds.width + pad * 2;
  599. const height = bounds.height + pad * 2;
  600. dom["selection-layer"].append(
  601. svgElement("rect", {x, y, width, height, rx: 0.55, class: "selection-reticle"}),
  602. svgElement("line", {x1: x - 1.4, y1: y + height / 2, x2: x + 1.1, y2: y + height / 2, class: "selection-cross"}),
  603. svgElement("line", {x1: x + width - 1.1, y1: y + height / 2, x2: x + width + 1.4, y2: y + height / 2, class: "selection-cross"}),
  604. svgElement("line", {x1: x + width / 2, y1: y - 1.4, x2: x + width / 2, y2: y + 1.1, class: "selection-cross"}),
  605. svgElement("line", {x1: x + width / 2, y1: y + height - 1.1, x2: x + width / 2, y2: y + height + 1.4, class: "selection-cross"}),
  606. );
  607. if (state.selectedResistor) {
  608. for (const resistorPad of state.selectedResistor.pads ?? []) {
  609. appendResistorPadMarker(dom["selection-layer"], resistorPad);
  610. }
  611. }
  612. const net = state.selectedPin?.net;
  613. if (!net) return;
  614. for (const item of sameNetMembers(state.data, net)) {
  615. const ownerSide = item.resistor?.side || item.touchpoint?.side || "front";
  616. if (ownerSide !== state.boardSide) continue;
  617. const size = item.pin.size || {};
  618. const point = toDisplayPoint(item.pin.view_position);
  619. dom["net-layer"].append(
  620. svgElement("circle", {
  621. cx: point.x,
  622. cy: point.y,
  623. r: Math.max(Number(size.width), Number(size.height), 1.3),
  624. class: `net-highlight${item.kind === "resistor_pad" ? " net-resistor" : ""}`,
  625. }),
  626. );
  627. }
  628. }
  629. function selectTouchpoint(touchpoint, pin = null, openDrawer = false) {
  630. ensureItemSide(touchpoint);
  631. state.selectedTouchpoint = touchpoint;
  632. state.selectedResistor = null;
  633. state.selectedPin = pin;
  634. dom["selection-readout"].textContent = pin
  635. ? `${touchpoint.reference}.${pin.number || "机械孔"} · ${padRoleLabel(pin.pad_role)} · ${pin.net || "无网络"}`
  636. : `${touchpoint.reference} · ${touchpointPinSummary(touchpoint)}`;
  637. if (openDrawer) setDrawerCollapsed(false);
  638. renderBoardMarkers();
  639. renderDetail();
  640. }
  641. function selectResistor(resistor, pad = null, openDrawer = false) {
  642. ensureItemSide(resistor);
  643. state.selectedResistor = resistor;
  644. state.selectedTouchpoint = null;
  645. state.selectedPin = pad;
  646. const nets = (resistor.pads ?? []).filter((item) => item.net).map((item) => item.net);
  647. const sideNote = resistor.side === "back" ? " · 背面" : "";
  648. dom["selection-readout"].textContent = pad
  649. ? `${resistor.reference}.${pad.number || "机械孔"} · ${pad.net || "无网络"}${sideNote}`
  650. : `${resistor.reference} · ${resistor.component_value || "阻值未标注"} · ${nets.join(" ↔ ") || "无网络"}${sideNote}`;
  651. if (openDrawer) setDrawerCollapsed(false);
  652. renderBoardMarkers();
  653. renderDetail();
  654. }
  655. function renderEmptyDetail(title, subtitle) {
  656. dom["detail-content"].replaceChildren();
  657. const wrapper = element("div", "empty-panel");
  658. wrapper.append(element("strong", "", title), element("span", "empty-stats", subtitle));
  659. dom["detail-content"].append(wrapper);
  660. }
  661. function fact(label, value) {
  662. const wrapper = element("div", "fact");
  663. wrapper.append(element("span", "fact-label", label), element("span", "fact-value", value));
  664. return wrapper;
  665. }
  666. function renderConnectorLayout(touchpoint, groups) {
  667. const connector = touchpoint.connector;
  668. const section = element("section", "connector-layout");
  669. const header = element("div", "connector-layout-header");
  670. header.append(
  671. element("h3", "section-title connector-layout-title", "板正面接触针排列"),
  672. element("span", `evidence-tag${connector.review_status === "cross_verified" ? " verified" : ""}`, evidenceLabel(connector.review_status)),
  673. );
  674. section.append(header);
  675. if (!groups.contactRows.length) {
  676. section.append(element("div", "risk-note", "该连接器尚无经过复核的接触针顺序。"));
  677. return section;
  678. }
  679. const orientation = element("div", "connector-orientation");
  680. orientation.append(element("span", "connector-axis connector-axis-top", "上"));
  681. const middle = element("div", "connector-axis-row");
  682. middle.append(element("span", "connector-axis", "左"));
  683. const grid = element("div", "connector-grid");
  684. const columns = Math.max(...groups.contactRows.map((row) => row.length), 1);
  685. for (const pins of groups.contactRows) {
  686. const row = element("div", "connector-grid-row");
  687. row.style.setProperty("--connector-columns", String(columns));
  688. for (const pin of pins) {
  689. const button = element("button", `connector-contact${state.selectedPin?.id === pin.id ? " is-selected" : ""}`, pin.number);
  690. button.type = "button";
  691. button.dataset.pinId = pin.id;
  692. button.setAttribute("aria-label", `${touchpoint.reference}.${pin.number},板正面第 ${pin.board_order} 位`);
  693. button.addEventListener("click", () => selectTouchpoint(touchpoint, pin, true));
  694. row.append(button);
  695. }
  696. grid.append(row);
  697. }
  698. middle.append(grid, element("span", "connector-axis", "右"));
  699. orientation.append(middle, element("span", "connector-axis connector-axis-bottom", "下"));
  700. section.append(orientation);
  701. section.append(
  702. element(
  703. "div",
  704. "connector-layout-meta",
  705. `${connector.profile} · ${connector.contact_count} 接触针 · ${connector.auxiliary_pad_count} 辅助焊盘`,
  706. ),
  707. element(
  708. "div",
  709. "connector-perspective-note",
  710. "板正面俯视:按页面上/下/左/右读取;线缆端或对接面可能是镜像。",
  711. ),
  712. );
  713. return section;
  714. }
  715. function renderPinRow(touchpoint, pin) {
  716. const row = element("button", `pin-row${state.selectedPin?.id === pin.id ? " is-selected" : ""}`);
  717. row.type = "button";
  718. row.dataset.pin = pin.number;
  719. row.dataset.pinId = pin.id;
  720. row.dataset.padRole = pin.pad_role;
  721. const primary = element("span", "pin-primary");
  722. primary.append(
  723. element("span", "pin-summary", pin.summary),
  724. element("span", "pin-net", `原始网络:${pin.net || "无命名网络"}`),
  725. );
  726. row.append(
  727. element("span", "pin-number", pin.number || "孔"),
  728. primary,
  729. element("span", "pin-direction", pin.pad_role === "contact" ? directionLabel(pin.direction) : padRoleLabel(pin.pad_role)),
  730. );
  731. row.addEventListener("click", () => selectTouchpoint(touchpoint, pin, true));
  732. return row;
  733. }
  734. function appendPinSection(container, touchpoint, title, pins) {
  735. if (!pins.length) return;
  736. container.append(element("h3", "section-title", title));
  737. const pinList = element("div", "pin-list");
  738. for (const pin of pins) pinList.append(renderPinRow(touchpoint, pin));
  739. container.append(pinList);
  740. }
  741. function renderDetail() {
  742. if (state.selectedResistor) {
  743. renderResistorDetail(state.selectedResistor, state.selectedPin);
  744. return;
  745. }
  746. const touchpoint = state.selectedTouchpoint;
  747. if (!touchpoint) {
  748. const counts = state.data?.counts;
  749. renderEmptyDetail(
  750. "未选择座子或电阻",
  751. counts
  752. ? `${counts.touchpoints} 个座子 · ${counts.resistors ?? 0} 个电阻 · ${counts.connector_contacts} 个 CON 接触针 · ${counts.connector_auxiliary_pads} 个 CON 辅助焊盘`
  753. : "",
  754. );
  755. return;
  756. }
  757. dom["detail-content"].replaceChildren();
  758. const heading = element("div", "detail-heading");
  759. const headingText = element("div");
  760. headingText.append(element("h2", "detail-reference", touchpoint.reference), element("p", "detail-summary", touchpoint.summary));
  761. heading.append(headingText, element("span", "category-tag", touchpointKindLabel(touchpoint)));
  762. const facts = element("div", "detail-facts");
  763. if (touchpoint.connector) {
  764. facts.append(
  765. fact("接触针", touchpoint.connector.contact_count),
  766. fact("辅助焊盘", touchpoint.connector.auxiliary_pad_count),
  767. fact("总焊盘", touchpoint.pins.length),
  768. fact("板面", touchpoint.side === "front" ? "正面" : "背面"),
  769. fact("坐标", `${formatNumber(touchpoint.position.x)} / ${formatNumber(touchpoint.position.y)} mm`),
  770. fact("旋转", `${formatNumber(touchpoint.rotation, 1)}°`),
  771. );
  772. } else {
  773. facts.append(
  774. fact("针脚数量", touchpoint.pins.length),
  775. fact("板面", touchpoint.side === "front" ? "正面" : "背面"),
  776. fact("坐标", `${formatNumber(touchpoint.position.x)} / ${formatNumber(touchpoint.position.y)} mm`),
  777. fact("旋转", `${formatNumber(touchpoint.rotation, 1)}°`),
  778. );
  779. }
  780. dom["detail-content"].append(heading, facts);
  781. if (touchpoint.connector) {
  782. const groups = connectorPinGroups(touchpoint);
  783. dom["detail-content"].append(renderConnectorLayout(touchpoint, groups));
  784. const contactPins = groups.contacts.length
  785. ? groups.contacts
  786. : touchpoint.pins.filter((pin) => pin.pad_role === "contact");
  787. const auxiliaryPins = groups.contacts.length
  788. ? groups.auxiliary
  789. : touchpoint.pins.filter((pin) => pin.pad_role !== "contact");
  790. appendPinSection(
  791. dom["detail-content"],
  792. touchpoint,
  793. groups.contacts.length ? "接触针(板正面顺序)" : "接触针(板数据库编号)",
  794. contactPins,
  795. );
  796. appendPinSection(dom["detail-content"], touchpoint, "屏蔽与机械焊盘", auxiliaryPins);
  797. } else {
  798. appendPinSection(dom["detail-content"], touchpoint, "针脚", touchpoint.pins);
  799. }
  800. if (state.selectedPin) dom["detail-content"].append(renderPinDetail(touchpoint, state.selectedPin));
  801. }
  802. function renderResistorDetail(resistor, pad = null) {
  803. dom["detail-content"].replaceChildren();
  804. const heading = element("div", "detail-heading");
  805. const headingText = element("div");
  806. headingText.append(
  807. element("h2", "detail-reference", resistor.reference),
  808. element("p", "detail-summary", resistor.summary || "分立电阻"),
  809. );
  810. heading.append(headingText, element("span", "category-tag", "电阻"));
  811. if (resistor.side === "back") {
  812. heading.append(element("span", "side-tag side-back", "背面"));
  813. }
  814. const nets = (resistor.pads ?? []).filter((item) => item.net).map((item) => item.net);
  815. const facts = element("div", "detail-facts");
  816. const assembly = resistor.assembly_status || "unknown";
  817. facts.append(
  818. fact("阻值", resistor.component_value || "未标注"),
  819. fact(
  820. "解析阻值",
  821. resistor.value_ohms == null
  822. ? `不可解析(${resistor.value_parse_status || "unparsed"})`
  823. : `${resistor.value_ohms} Ω`,
  824. ),
  825. fact("装配状态", assembly === "not_fitted" ? "未装/NC" : assembly === "fitted" ? "已装" : "未知"),
  826. fact("两侧网络", nets.length ? nets.join(" ↔ ") : "无命名网络"),
  827. fact("焊盘数", resistor.pads?.length ?? 0),
  828. fact("板面", resistor.side === "front" ? "正面" : "背面"),
  829. fact("坐标", `${formatNumber(resistor.position.x)} / ${formatNumber(resistor.position.y)} mm`),
  830. fact("旋转", `${formatNumber(resistor.rotation, 1)}°`),
  831. );
  832. dom["detail-content"].append(heading, facts);
  833. if (assembly === "not_fitted") {
  834. dom["detail-content"].append(
  835. element("div", "risk-note", "标注为未装/NC:保留在 PCB 索引中,但不作为已装 0Ω 电气连通默认成员。"),
  836. );
  837. }
  838. if (resistor.side === "back") {
  839. const tip = element("div", "back-view-tip");
  840. tip.id = "back-view-tip";
  841. if (state.boardSide === "back") {
  842. tip.textContent = "当前为背面实物视角(已对 X 做左右镜像);实体坐标/网络不变。切换到「正面投影」可按板正面坐标系查看。";
  843. } else {
  844. tip.textContent = "当前为板正面投影视角;该器件在背面。从实物背面查看时需左右镜像——请切换到「背面实物(左右镜像)」。";
  845. }
  846. dom["detail-content"].append(tip);
  847. }
  848. const coverage = state.data?.value_coverage;
  849. if (coverage) {
  850. dom["detail-content"].append(
  851. element(
  852. "div",
  853. "coverage-hint",
  854. `阻值覆盖 ${coverage.value_parsed}/${coverage.resistors_total}(原始值非空 ${coverage.component_value_nonempty});来源:${state.data.component_value_source_status || coverage.component_value_source_status}`,
  855. ),
  856. );
  857. }
  858. const padSection = element("div", "pin-list");
  859. for (const item of resistor.pads ?? []) {
  860. const row = element("button", `pin-row${pad?.number === item.number ? " is-selected" : ""}`);
  861. row.type = "button";
  862. row.append(
  863. element("span", "pin-number", item.number || "孔"),
  864. element("span", "pin-primary", item.net || "无命名网络"),
  865. element(
  866. "span",
  867. "pin-direction",
  868. `${item.pad_role === "electrical" ? "电气" : "机械"} · ${formatNumber(item.position?.x)}/${formatNumber(item.position?.y)}`,
  869. ),
  870. );
  871. row.addEventListener("click", () => selectResistor(resistor, item, true));
  872. padSection.append(row);
  873. }
  874. dom["detail-content"].append(element("h3", "section-title", "电阻焊盘"), padSection);
  875. if (pad?.net || nets[0]) {
  876. const net = pad?.net || nets[0];
  877. const netMatches = sameNetMembers(state.data, net);
  878. if (netMatches.length) {
  879. dom["detail-content"].append(element("h3", "section-title", `同网成员(${net})`));
  880. const list = element("div", "pin-list");
  881. for (const item of netMatches.slice(0, 32)) {
  882. const row = element("button", "pin-row");
  883. row.type = "button";
  884. const kindLabel = item.kind === "resistor_pad" ? "电阻" : "座子";
  885. row.append(
  886. element("span", "pin-number", item.pinNumber),
  887. element("span", "pin-primary", `${item.reference}.${item.pinNumber}`),
  888. element("span", "pin-direction", kindLabel),
  889. );
  890. row.addEventListener("click", () => {
  891. if (item.kind === "resistor_pad" && item.resistor) {
  892. state.categories.add("R");
  893. const checkbox = dom["category-filters"].querySelector('input[value="R"]');
  894. if (checkbox) checkbox.checked = true;
  895. selectResistor(item.resistor, item.pin, true);
  896. focusOnTouchpoint(item.resistor);
  897. } else if (item.touchpoint) {
  898. state.categories.add(item.touchpoint.category);
  899. selectTouchpoint(item.touchpoint, item.pin, true);
  900. focusOnTouchpoint(item.touchpoint);
  901. }
  902. });
  903. list.append(row);
  904. }
  905. dom["detail-content"].append(list);
  906. }
  907. }
  908. const conflicts = (state.data.evidence_conflicts ?? []).filter(
  909. (item) => item.subject_reference === resistor.reference,
  910. );
  911. if (conflicts.length) {
  912. const section = element("section", "evidence-conflict");
  913. section.append(element("h3", "section-title", "证据与冲突"));
  914. for (const conflict of conflicts) {
  915. const note = element("div", "risk-note evidence-conflict-note");
  916. note.append(
  917. element("strong", "", `${conflict.status || "unresolved"} · ${conflict.kind || "cross_evidence"}`),
  918. document.createTextNode(` — ${conflict.summary || "存在未解决的交叉证据冲突"}`),
  919. );
  920. section.append(note);
  921. if (Array.isArray(conflict.pcb_pads) && conflict.pcb_pads.length) {
  922. section.append(element("div", "info-note", `PCB pad facts:${conflict.pcb_pads.map((item) => `${item.number}:${item.net || "null"}`).join(" · ")}`));
  923. }
  924. if (Array.isArray(conflict.claims)) {
  925. const list = element("ul", "source-list");
  926. for (const claim of conflict.claims) {
  927. const line = element("li", "");
  928. line.textContent = `${claim.source || "claim"} (${claim.source_id || "?"}): ${claim.note || claim.claimed_context || JSON.stringify(claim.claimed_nets || [])}`;
  929. list.append(line);
  930. }
  931. section.append(list);
  932. }
  933. }
  934. dom["detail-content"].append(section);
  935. }
  936. }
  937. function renderPinDetail(touchpoint, pin) {
  938. const wrapper = element("section", "pin-detail");
  939. const header = element("div", "pin-detail-header");
  940. header.append(
  941. element("h3", "", `${touchpoint.reference}.${pin.number || "机械孔"}`),
  942. element("span", `evidence-tag${pin.evidence_tier === "cross_verified" ? " verified" : ""}`, evidenceLabel(pin.evidence_tier)),
  943. );
  944. wrapper.append(header);
  945. const programmingGuide = renderProgrammingGuide(pin);
  946. if (programmingGuide) wrapper.append(programmingGuide);
  947. wrapper.append(element("h4", "section-title", "物理与电气事实"));
  948. const facts = element("div", "detail-facts");
  949. const programmableTarget = pin.fpga
  950. ? "FPGA U3"
  951. : pin.mcu
  952. ? `${pin.mcu.family} ${pin.mcu.device}`
  953. : "无直接可编程映射";
  954. const devicePin = pin.fpga?.ball
  955. ? `FPGA ${pin.fpga.ball}`
  956. : pin.mcu
  957. ? `${pin.mcu.device}.${pin.mcu.pin} (${pin.mcu.signal})`
  958. : "无已验证映射";
  959. const boardPosition = pin.board_order == null
  960. ? "不属于外部接触针"
  961. : `第 ${pin.board_order} 位 · 第 ${pin.row} 行 / 第 ${pin.column} 列`;
  962. facts.append(
  963. fact("焊盘角色", padRoleLabel(pin.pad_role)),
  964. fact("板正面位置", boardPosition),
  965. fact("原始网络", pin.net || "无命名网络"),
  966. fact("逻辑方向", directionLabel(pin.direction)),
  967. fact("外部电平", pin.external_level || "未知"),
  968. fact("可编程目标", programmableTarget),
  969. fact("器件引脚", devicePin),
  970. fact("I/O 标准", pin.fpga?.io_standard || "未知"),
  971. fact("板上 pull", pin.board_pull || "未注明"),
  972. fact("有效电平", activeLevelLabel(pin.active_level)),
  973. fact("极性", pin.polarity && pin.polarity !== "unknown" ? pin.polarity : "未注明"),
  974. );
  975. wrapper.append(facts);
  976. if (pin.external_components?.length) {
  977. wrapper.append(element("h4", "section-title", "相关板上器件"));
  978. const components = element("ul", "component-list");
  979. for (const item of pin.external_components) components.append(element("li", "", item));
  980. wrapper.append(components);
  981. }
  982. if (pin.path?.length) {
  983. wrapper.append(element("h4", "section-title", "已验证板内路径"));
  984. const path = element("ol", "path-list");
  985. for (const item of pin.path) path.append(element("li", "", item));
  986. wrapper.append(path);
  987. }
  988. const related = Array.isArray(pin.related_resistors) ? pin.related_resistors : [];
  989. if (related.length) {
  990. wrapper.append(element("h4", "section-title", "关联电阻(path / external_components)"));
  991. const list = element("div", "pin-list");
  992. for (const link of related) {
  993. const resistor = (state.data.resistors ?? []).find((item) => item.reference === link.resistor_reference);
  994. const row = element("button", "pin-row");
  995. row.type = "button";
  996. const label = link.pad_number
  997. ? `${link.resistor_reference}.${link.pad_number}`
  998. : link.resistor_reference;
  999. const netLine = [
  1000. link.claimed_net != null ? `claimed=${link.claimed_net}` : "claimed=∅",
  1001. link.pcb_net != null ? `pcb=${link.pcb_net}` : "pcb=∅",
  1002. link.status,
  1003. ].join(" · ");
  1004. row.append(
  1005. element("span", "pin-number", "R"),
  1006. element("span", "pin-primary", `${label} · ${netLine}`),
  1007. element("span", "pin-direction", link.source_field || "path"),
  1008. );
  1009. if (link.status === "net_conflict") {
  1010. row.classList.add("is-conflict");
  1011. }
  1012. if ((link.status === "resolved" || link.status === "net_conflict") && resistor) {
  1013. row.addEventListener("click", () => {
  1014. state.categories.add("R");
  1015. const checkbox = dom["category-filters"].querySelector('input[value="R"]');
  1016. if (checkbox) checkbox.checked = true;
  1017. const pad = link.pad_number
  1018. ? (resistor.pads ?? []).find((item) => String(item.number) === String(link.pad_number))
  1019. : null;
  1020. selectResistor(resistor, pad || null, true);
  1021. focusOnTouchpoint(resistor);
  1022. });
  1023. } else {
  1024. row.disabled = true;
  1025. row.classList.add("is-conflict");
  1026. }
  1027. list.append(row);
  1028. }
  1029. wrapper.append(list);
  1030. } else {
  1031. try {
  1032. const pathResistors = extractPathResistors(state.data, pin.path, pin.external_components);
  1033. if (pathResistors.length) {
  1034. wrapper.append(element("h4", "section-title", "路径电阻(可跳转)"));
  1035. const list = element("div", "pin-list");
  1036. for (const resistor of pathResistors) {
  1037. const nets = (resistor.pads ?? []).filter((item) => item.net).map((item) => item.net);
  1038. const row = element("button", "pin-row");
  1039. row.type = "button";
  1040. row.append(
  1041. element("span", "pin-number", "R"),
  1042. element("span", "pin-primary", `${resistor.reference} · ${resistor.component_value || "未标注"} · ${nets.join(" ↔ ") || "无网络"}`),
  1043. element("span", "pin-direction", "跳转"),
  1044. );
  1045. row.addEventListener("click", () => {
  1046. state.categories.add("R");
  1047. const checkbox = dom["category-filters"].querySelector('input[value="R"]');
  1048. if (checkbox) checkbox.checked = true;
  1049. selectResistor(resistor, null, true);
  1050. focusOnTouchpoint(resistor);
  1051. });
  1052. list.append(row);
  1053. }
  1054. wrapper.append(list);
  1055. }
  1056. } catch (error) {
  1057. wrapper.append(element("div", "risk-note", String(error.message || error)));
  1058. }
  1059. }
  1060. wrapper.append(element("h4", "section-title", "证据来源"));
  1061. const sources = element("ul", "source-list");
  1062. for (const source of pin.evidence_sources ?? []) sources.append(element("li", "", source));
  1063. wrapper.append(sources);
  1064. if (pin.net) {
  1065. const netMatches = sameNetMembers(state.data, pin.net);
  1066. wrapper.append(element("div", "info-note", `同网成员 ${netMatches.length} 个(座子+电阻),板图已同步高亮。`));
  1067. }
  1068. const blockers = pin.recommendation?.reasons ?? [];
  1069. if (!pin.recommendation?.eligible) {
  1070. wrapper.append(element("div", "risk-note", `不可用于自动候选或 ADC:${blockers.join("、") || "证据条件不足"}。`));
  1071. }
  1072. const dedicatedConfigurationPin = String(pin.function_category || "").startsWith("jtag_");
  1073. if (!pin.fpga || dedicatedConfigurationPin) {
  1074. wrapper.append(
  1075. element(
  1076. "div",
  1077. "info-note",
  1078. dedicatedConfigurationPin
  1079. ? "专用配置脚不使用用户 ADC 约束"
  1080. : "此针不对应可生成 ADC 的 FPGA 用户 I/O。",
  1081. ),
  1082. );
  1083. return wrapper;
  1084. }
  1085. wrapper.append(element("h4", "section-title", "ADC 片段"));
  1086. const adc = element("div", "adc-controls");
  1087. const input = element("input");
  1088. input.type = "text";
  1089. input.placeholder = "RTL 端口名";
  1090. input.setAttribute("aria-label", "RTL 端口名");
  1091. input.disabled = !pin.recommendation?.eligible || state.runtime.adcCopyEnabled !== true;
  1092. const copy = element("button", "copy-button", "⧉");
  1093. copy.type = "button";
  1094. copy.title = "复制 ADC 片段";
  1095. copy.setAttribute("aria-label", "复制 ADC 片段");
  1096. copy.disabled = input.disabled;
  1097. const status = element("div", "copy-status");
  1098. copy.addEventListener("click", async () => {
  1099. try {
  1100. const snippet = generateAdcSnippet(pin, input.value.trim(), state.runtime);
  1101. await copyText(snippet);
  1102. status.textContent = "ADC 片段已复制";
  1103. } catch (error) {
  1104. status.textContent = error instanceof Error ? error.message : String(error);
  1105. }
  1106. });
  1107. adc.append(input, copy);
  1108. wrapper.append(adc, status, element("div", "risk-note", "这里只证明物理可用性,仍需检查当前工程约束冲突。"));
  1109. return wrapper;
  1110. }
  1111. function appendGuidanceList(container, title, items, className = "guidance-list") {
  1112. if (!Array.isArray(items) || !items.length) return;
  1113. container.append(element("h4", "section-title", title));
  1114. const list = element("ul", className);
  1115. for (const item of items) list.append(element("li", "", item));
  1116. container.append(list);
  1117. }
  1118. function renderProgrammingGuide(pin) {
  1119. const programming = pin.programming;
  1120. if (!programming) return null;
  1121. const section = element("section", `programming-guide status-${programming.status || "unknown"}`);
  1122. const heading = element("div", "programming-guide-heading");
  1123. heading.append(
  1124. element("h4", "section-title programming-title", "编程结论"),
  1125. element(
  1126. "span",
  1127. `evidence-tag${programming.evidence_tier === "cross_verified" ? " verified" : ""}`,
  1128. evidenceLabel(programming.evidence_tier),
  1129. ),
  1130. );
  1131. section.append(heading, element("p", "programming-conclusion", programming.conclusion));
  1132. section.append(element("h4", "section-title", "板内网络解释"));
  1133. section.append(element("p", "programming-copy", programming.network_explanation));
  1134. appendGuidanceList(section, "怎么接", programming.connection_guidance);
  1135. section.append(
  1136. element(
  1137. "h4",
  1138. "section-title",
  1139. programming.status === "verified_mcu" ? "MCU 固件用法" : "HDL 用法",
  1140. ),
  1141. );
  1142. section.append(element("p", "programming-copy", programming.hdl_guidance));
  1143. appendGuidanceList(section, "约束要求", programming.constraints, "guidance-list constraint-list");
  1144. appendGuidanceList(section, "风险与未知", programming.risks, "guidance-list risk-list");
  1145. return section;
  1146. }
  1147. async function copyText(value) {
  1148. if (navigator.clipboard?.writeText) return navigator.clipboard.writeText(value);
  1149. const textarea = element("textarea");
  1150. textarea.value = value;
  1151. textarea.style.position = "fixed";
  1152. textarea.style.opacity = "0";
  1153. document.body.append(textarea);
  1154. textarea.select();
  1155. document.execCommand("copy");
  1156. textarea.remove();
  1157. }
  1158. function renderCandidates() {
  1159. if (!state.data) return;
  1160. dom["candidate-list"].replaceChildren();
  1161. if (state.runtime.recommendationsEnabled !== true) {
  1162. dom["candidate-list"].append(element("div", "risk-note", "源文件状态不是当前值,选脚推荐已关闭。"));
  1163. return;
  1164. }
  1165. const capability = dom["capability-select"].value;
  1166. const candidates = findCandidates(state.data, capability);
  1167. if (!candidates.length) {
  1168. const empty = element("div", "empty-panel");
  1169. empty.append(
  1170. element("strong", "", "没有满足全部证据条件的候选"),
  1171. element("span", "empty-stats", "未知、推断、保留、电源、地、机械焊盘和固定负载冲突均已排除"),
  1172. );
  1173. dom["candidate-list"].append(empty);
  1174. return;
  1175. }
  1176. for (const candidate of candidates) {
  1177. const row = element("button", "candidate-row");
  1178. row.type = "button";
  1179. row.append(
  1180. element("span", "candidate-key", `${candidate.reference}.${candidate.pin.number} · ${candidate.pin.fpga.ball}`),
  1181. element("span", "candidate-reason", candidate.reason),
  1182. element("span", "candidate-warning", candidate.warning),
  1183. );
  1184. row.addEventListener("click", () => {
  1185. switchTab("detail");
  1186. selectTouchpoint(candidate.touchpoint, candidate.pin, true);
  1187. focusOnTouchpoint(candidate.touchpoint);
  1188. });
  1189. dom["candidate-list"].append(row);
  1190. }
  1191. }
  1192. function switchTab(tab) {
  1193. state.activeTab = tab;
  1194. const detail = tab === "detail";
  1195. dom["detail-tab"].setAttribute("aria-selected", String(detail));
  1196. dom["candidate-tab"].setAttribute("aria-selected", String(!detail));
  1197. dom["detail-content"].hidden = !detail;
  1198. dom["candidate-content"].hidden = detail;
  1199. if (!detail) renderCandidates();
  1200. }
  1201. function renderSearchResults(query) {
  1202. state.searchResults = searchBoard(state.data, query).slice(0, 24);
  1203. state.activeSearchIndex = -1;
  1204. dom["search-results"].replaceChildren();
  1205. if (!query.trim()) {
  1206. dom["search-results"].hidden = true;
  1207. return;
  1208. }
  1209. dom["search-results"].hidden = false;
  1210. if (!state.searchResults.length) {
  1211. const coverage = state.data?.value_coverage;
  1212. const looksValue = /^(?:value:)?\d/i.test(query.trim()) || /[rRkKmM]|ohm|Ω/.test(query);
  1213. let message = "没有匹配的座子、电阻或针脚";
  1214. if (looksValue && coverage) {
  1215. message = `当前索引中没有此阻值;当前阻值覆盖 ${coverage.value_parsed}/${coverage.resistors_total}(原始值非空 ${coverage.component_value_nonempty})。位号/网络查询不受影响。`;
  1216. }
  1217. dom["search-results"].append(element("div", "empty-search", message));
  1218. return;
  1219. }
  1220. state.searchResults.forEach((result, index) => {
  1221. const button = element("button", "search-result");
  1222. button.type = "button";
  1223. button.role = "option";
  1224. button.dataset.index = String(index);
  1225. button.setAttribute("aria-selected", "false");
  1226. let key = result.reference;
  1227. let detail = "";
  1228. if (result.type === "pin") {
  1229. key = `${result.reference}.${result.pinNumber}`;
  1230. detail = `${result.pin.net || "无网络"} · ${result.pin.fpga?.ball || evidenceLabel(result.pin.evidence_tier)}`;
  1231. } else if (result.type === "resistor" || result.type === "resistor_pad") {
  1232. key = result.type === "resistor_pad" ? `${result.reference}.${result.pinNumber}` : result.reference;
  1233. const nets = (result.resistor?.pads ?? []).filter((pad) => pad.net).map((pad) => pad.net);
  1234. const valueLabel = result.resistor?.value_ohms != null
  1235. ? `${result.resistor.value_ohms} Ω`
  1236. : (result.resistor?.component_value || "阻值未标注");
  1237. const nf = result.notFitted || result.resistor?.assembly_status === "not_fitted";
  1238. detail = result.type === "resistor_pad"
  1239. ? `${result.pin?.net || "无网络"}`
  1240. : `${valueLabel} · ${nets.join(" ↔ ") || "无网络"}${nf ? " · 未装/NC" : ""}`;
  1241. } else if (result.type === "evidence_conflict") {
  1242. key = `${result.reference} 冲突`;
  1243. detail = result.evidenceConflict?.summary || "原理图声明与 PCB 索引冲突,未解决";
  1244. } else {
  1245. detail = `${touchpointKindLabel(result.touchpoint)} · ${result.touchpoint.summary}`;
  1246. }
  1247. button.append(element("span", "result-key", key), element("span", "result-detail", detail));
  1248. button.addEventListener("click", () => activateSearchResult(index));
  1249. dom["search-results"].append(button);
  1250. });
  1251. }
  1252. function activateSearchResult(index) {
  1253. const result = state.searchResults[index];
  1254. if (!result) return;
  1255. if (result.type === "resistor" || result.type === "resistor_pad" || result.type === "evidence_conflict") {
  1256. if (!result.resistor) return;
  1257. state.categories.add("R");
  1258. const checkbox = dom["category-filters"].querySelector('input[value="R"]');
  1259. if (checkbox) checkbox.checked = true;
  1260. selectResistor(result.resistor, result.pin, true);
  1261. focusOnTouchpoint(result.resistor);
  1262. dom["board-search"].value = result.type === "resistor_pad"
  1263. ? `${result.reference}.${result.pinNumber}`
  1264. : result.reference;
  1265. } else if (result.touchpoint) {
  1266. state.categories.add(result.touchpoint.category);
  1267. const checkbox = dom["category-filters"].querySelector(`input[value="${result.touchpoint.category}"]`);
  1268. if (checkbox) checkbox.checked = true;
  1269. selectTouchpoint(result.touchpoint, result.pin, true);
  1270. focusOnTouchpoint(result.touchpoint);
  1271. dom["board-search"].value = result.type === "pin" ? `${result.reference}.${result.pinNumber}` : result.reference;
  1272. }
  1273. dom["search-results"].hidden = true;
  1274. dom["board-svg"].focus();
  1275. }
  1276. function updateSearchSelection(nextIndex) {
  1277. const options = [...dom["search-results"].querySelectorAll(".search-result")];
  1278. if (!options.length) return;
  1279. state.activeSearchIndex = (nextIndex + options.length) % options.length;
  1280. options.forEach((option, index) => option.setAttribute("aria-selected", String(index === state.activeSearchIndex)));
  1281. options[state.activeSearchIndex].scrollIntoView({block: "nearest"});
  1282. }
  1283. function focusOnTouchpoint(touchpoint) {
  1284. const bounds = effectiveBounds(toDisplayBounds(touchpoint.view_bounds), 8);
  1285. const viewport = dom["board-svg"].getBoundingClientRect();
  1286. const aspect = Math.max(viewport.width / Math.max(viewport.height, 1), 1);
  1287. let width = Math.max(bounds.width * 3.4, state.baseViewBox.width / 12);
  1288. let height = width / aspect;
  1289. if (height < bounds.height * 3.4) {
  1290. height = bounds.height * 3.4;
  1291. width = height * aspect;
  1292. }
  1293. state.viewBox = {
  1294. x: bounds.x + bounds.width / 2 - width / 2,
  1295. y: bounds.y + bounds.height / 2 - height / 2,
  1296. width,
  1297. height,
  1298. };
  1299. clampViewBox();
  1300. updateViewBox();
  1301. }
  1302. function clampViewBox() {
  1303. if (!state.viewBox || !state.baseViewBox) return;
  1304. const marginX = state.baseViewBox.width * 0.25;
  1305. const marginY = state.baseViewBox.height * 0.4;
  1306. const minX = state.baseViewBox.x - marginX;
  1307. const maxX = state.baseViewBox.x + state.baseViewBox.width + marginX - state.viewBox.width;
  1308. const minY = state.baseViewBox.y - marginY;
  1309. const maxY = state.baseViewBox.y + state.baseViewBox.height + marginY - state.viewBox.height;
  1310. state.viewBox.x = Math.min(Math.max(state.viewBox.x, minX), Math.max(minX, maxX));
  1311. state.viewBox.y = Math.min(Math.max(state.viewBox.y, minY), Math.max(minY, maxY));
  1312. }
  1313. function zoomAt(factor, clientX = null, clientY = null) {
  1314. if (!state.viewBox || !state.baseViewBox) return;
  1315. const minimumWidth = state.baseViewBox.width / 35;
  1316. const maximumWidth = state.baseViewBox.width * 1.25;
  1317. const newWidth = Math.min(Math.max(state.viewBox.width * factor, minimumWidth), maximumWidth);
  1318. const ratio = newWidth / state.viewBox.width;
  1319. const anchor = clientX == null ? {
  1320. x: state.viewBox.x + state.viewBox.width / 2,
  1321. y: state.viewBox.y + state.viewBox.height / 2,
  1322. } : clientToSvg(clientX, clientY);
  1323. state.viewBox = {
  1324. x: anchor.x - (anchor.x - state.viewBox.x) * ratio,
  1325. y: anchor.y - (anchor.y - state.viewBox.y) * ratio,
  1326. width: newWidth,
  1327. height: state.viewBox.height * ratio,
  1328. };
  1329. clampViewBox();
  1330. updateViewBox();
  1331. }
  1332. function clientToSvg(clientX, clientY) {
  1333. const point = dom["board-svg"].createSVGPoint();
  1334. point.x = clientX;
  1335. point.y = clientY;
  1336. return point.matrixTransform(dom["board-svg"].getScreenCTM().inverse());
  1337. }
  1338. function resetView() {
  1339. state.viewBox = {...state.baseViewBox};
  1340. updateViewBox();
  1341. }
  1342. function setDrawerCollapsed(collapsed) {
  1343. dom.app.classList.toggle("detail-collapsed", collapsed);
  1344. dom["drawer-toggle"].setAttribute("aria-expanded", String(!collapsed));
  1345. dom["drawer-toggle"].title = collapsed ? "展开详情" : "收起详情";
  1346. dom["drawer-toggle"].setAttribute("aria-label", collapsed ? "展开详情" : "收起详情");
  1347. }
  1348. dom["category-filters"].addEventListener("change", (event) => {
  1349. const input = event.target;
  1350. if (!(input instanceof HTMLInputElement)) return;
  1351. if (input.checked) state.categories.add(input.value);
  1352. else state.categories.delete(input.value);
  1353. renderBoardMarkers();
  1354. });
  1355. dom["side-controls"].addEventListener("change", (event) => {
  1356. const input = event.target;
  1357. if (!(input instanceof HTMLInputElement) || input.name !== "board-side") return;
  1358. setBoardSide(input.value, {rerender: true});
  1359. });
  1360. dom["layer-controls"].addEventListener("change", (event) => {
  1361. const input = event.target;
  1362. if (!(input instanceof HTMLInputElement)) return;
  1363. const layer = dom[`layer-${input.value}`];
  1364. if (layer) layer.hidden = !input.checked;
  1365. });
  1366. dom["zoom-in"].addEventListener("click", () => zoomAt(0.8));
  1367. dom["zoom-out"].addEventListener("click", () => zoomAt(1.25));
  1368. dom["reset-view"].addEventListener("click", resetView);
  1369. dom["detail-tab"].addEventListener("click", () => switchTab("detail"));
  1370. dom["candidate-tab"].addEventListener("click", () => switchTab("candidate"));
  1371. dom["capability-select"].addEventListener("change", renderCandidates);
  1372. dom["drawer-toggle"].addEventListener("click", () => setDrawerCollapsed(!dom.app.classList.contains("detail-collapsed")));
  1373. dom["board-search"].addEventListener("input", (event) => {
  1374. if (state.data) renderSearchResults(event.target.value);
  1375. });
  1376. dom["board-search"].addEventListener("keydown", (event) => {
  1377. if (event.key === "ArrowDown") {
  1378. event.preventDefault();
  1379. updateSearchSelection(state.activeSearchIndex + 1);
  1380. } else if (event.key === "ArrowUp") {
  1381. event.preventDefault();
  1382. updateSearchSelection(state.activeSearchIndex - 1);
  1383. } else if (event.key === "Enter" && state.activeSearchIndex >= 0) {
  1384. event.preventDefault();
  1385. activateSearchResult(state.activeSearchIndex);
  1386. } else if (event.key === "Escape") {
  1387. dom["search-results"].hidden = true;
  1388. }
  1389. });
  1390. document.addEventListener("pointerdown", (event) => {
  1391. if (!dom["search-results"].contains(event.target) && event.target !== dom["board-search"]) {
  1392. dom["search-results"].hidden = true;
  1393. }
  1394. });
  1395. dom["board-svg"].addEventListener("wheel", (event) => {
  1396. event.preventDefault();
  1397. zoomAt(event.deltaY < 0 ? 0.82 : 1.22, event.clientX, event.clientY);
  1398. }, {passive: false});
  1399. dom["board-svg"].addEventListener("pointerdown", (event) => {
  1400. if (event.target.closest?.(".hotspot, .pin-group")) return;
  1401. dom["board-svg"].setPointerCapture(event.pointerId);
  1402. dom["board-svg"].classList.add("is-panning");
  1403. state.dragging = {pointerId: event.pointerId, x: event.clientX, y: event.clientY, viewBox: {...state.viewBox}};
  1404. });
  1405. dom["board-svg"].addEventListener("pointermove", (event) => {
  1406. if (!state.dragging || state.dragging.pointerId !== event.pointerId) return;
  1407. const bounds = dom["board-svg"].getBoundingClientRect();
  1408. state.viewBox = {
  1409. ...state.dragging.viewBox,
  1410. x: state.dragging.viewBox.x - (event.clientX - state.dragging.x) * state.dragging.viewBox.width / bounds.width,
  1411. y: state.dragging.viewBox.y - (event.clientY - state.dragging.y) * state.dragging.viewBox.height / bounds.height,
  1412. };
  1413. clampViewBox();
  1414. updateViewBox();
  1415. });
  1416. function endPan(event) {
  1417. if (!state.dragging || state.dragging.pointerId !== event.pointerId) return;
  1418. state.dragging = null;
  1419. dom["board-svg"].classList.remove("is-panning");
  1420. }
  1421. dom["board-svg"].addEventListener("pointerup", endPan);
  1422. dom["board-svg"].addEventListener("pointercancel", endPan);
  1423. dom["board-svg"].addEventListener("keydown", (event) => {
  1424. const stepX = state.viewBox.width * 0.06;
  1425. const stepY = state.viewBox.height * 0.08;
  1426. if (event.key === "+" || event.key === "=") zoomAt(0.8);
  1427. else if (event.key === "-") zoomAt(1.25);
  1428. else if (event.key === "0") resetView();
  1429. else if (["ArrowLeft", "ArrowRight", "ArrowUp", "ArrowDown"].includes(event.key)) {
  1430. if (event.key === "ArrowLeft") state.viewBox.x -= stepX;
  1431. if (event.key === "ArrowRight") state.viewBox.x += stepX;
  1432. if (event.key === "ArrowUp") state.viewBox.y -= stepY;
  1433. if (event.key === "ArrowDown") state.viewBox.y += stepY;
  1434. clampViewBox();
  1435. updateViewBox();
  1436. } else return;
  1437. event.preventDefault();
  1438. });
  1439. window.addEventListener("resize", () => {
  1440. hideTooltip();
  1441. if (window.innerWidth > 860) setDrawerCollapsed(false);
  1442. });
  1443. const TERM_HELP = {
  1444. RefDes: "RefDes = Reference Designator,器件位号(如 R674、CON104)。",
  1445. Net: "Net = 电气网络名;同网成员按 PCB pad.net / pin.net 索引。裸 PUL1 若精确等于现有网络名,按 exact net 处理。",
  1446. Pad: "Pad = 焊盘;电阻可用 R674.1 精确查询某个焊盘。",
  1447. PCB: "PCB = 印制电路板;本查看器的电阻实体只来自 PCB footprint。",
  1448. BRD: "BRD = Allegro 板文件原件;默认分析包不打包 raw BRD。",
  1449. FPGA: "FPGA = Field-Programmable Gate Array,现场可编程门阵列(本板 U3)。",
  1450. MCU: "MCU = Microcontroller Unit,微控制器。",
  1451. GPIO: "GPIO = General-Purpose Input/Output,通用输入输出。",
  1452. PWM: "PWM = Pulse-Width Modulation,脉冲宽度调制。",
  1453. UART: "UART = Universal Asynchronous Receiver/Transmitter,异步串行收发。",
  1454. ADC: "ADC = Analog-to-Digital Converter,模数转换。",
  1455. JTAG: "JTAG = Joint Test Action Group,边界扫描/调试接口。",
  1456. CON: "CON = Connector,连接器座子位号前缀。",
  1457. TP: "TP = Test Point,测试点。",
  1458. PL: "PL = Plug/socket style header,插座类位号前缀。",
  1459. };
  1460. document.querySelector(".search-help")?.addEventListener("click", (event) => {
  1461. const chip = event.target.closest?.(".help-chip");
  1462. if (chip?.dataset?.query) {
  1463. dom["board-search"].value = chip.dataset.query;
  1464. renderSearchResults(chip.dataset.query);
  1465. dom["board-search"].focus();
  1466. return;
  1467. }
  1468. const term = event.target.closest?.(".term");
  1469. if (term?.dataset?.term) {
  1470. const message = TERM_HELP[term.dataset.term] || term.dataset.term;
  1471. dom["stale-banner"].hidden = false;
  1472. dom["stale-banner"].textContent = message;
  1473. window.setTimeout(() => {
  1474. if (dom["stale-banner"].textContent === message) {
  1475. dom["stale-banner"].hidden = true;
  1476. }
  1477. }, 6000);
  1478. }
  1479. });
  1480. setDrawerCollapsed(window.innerWidth <= 860);
  1481. loadApplication();