app.js 149 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934
  1. import {
  2. PERIPHERAL_TYPE_LABELS,
  3. PERIPHERAL_TYPE_ORDER,
  4. buildPeripheralIndex,
  5. classifyTouchpointPeripheral,
  6. connectorPinGroups,
  7. displayBounds,
  8. displayPoint,
  9. extractPathResistors,
  10. filterPeripheralCatalog,
  11. findCandidates,
  12. generateAdcSnippet,
  13. itemVisibleOnSide,
  14. resolveLogicalPin,
  15. sameNetMembers,
  16. sameNetPins,
  17. searchBoard,
  18. } from "./board-logic.mjs";
  19. import {
  20. BOARD_VERSION_COMM_MATRIX,
  21. CPLD_CHIP_SPEC,
  22. CPLD_MENU_TREE,
  23. getCpldTopicDetail,
  24. } from "./cpld-arch-data.mjs";
  25. import {BoardWasmAccelerator} from "./wasm-engine.mjs";
  26. const wasmAccel = new BoardWasmAccelerator();
  27. const SVG_NS = "http://www.w3.org/2000/svg";
  28. const LAYER_ASSETS = {
  29. front: {
  30. mask: "/generated/board-mask-edge.svg",
  31. silk: "/generated/board-silkscreen.svg",
  32. copper: "/generated/board-copper.svg",
  33. },
  34. back: {
  35. mask: "/generated/board-mask-edge-back.svg",
  36. silk: "/generated/board-silkscreen-back.svg",
  37. copper: "/generated/board-copper-back.svg",
  38. },
  39. };
  40. function getLayerAssets(version, side) {
  41. let prefix = "/generated";
  42. if (version === "v1_1") prefix = "/generated-v1_1";
  43. else if (version === "v2_0") prefix = "/generated-v2_0";
  44. else if (version === "v2_0_fan") prefix = "/generated-v2_0_fan";
  45. if (version === "v1_2" && LAYER_ASSETS[side]) return LAYER_ASSETS[side];
  46. return {
  47. mask: `${prefix}/board-mask-edge${side === "back" ? "-back" : ""}.svg`,
  48. silk: `${prefix}/board-silkscreen${side === "back" ? "-back" : ""}.svg`,
  49. copper: `${prefix}/board-copper${side === "back" ? "-back" : ""}.svg`,
  50. };
  51. }
  52. const state = {
  53. data: null,
  54. boardVersion: "v2_0",
  55. boardCache: new Map(),
  56. layerImageCache: new Map(),
  57. layerCompositeCanvas: null,
  58. layerCompositeKey: "",
  59. layerCompositeReady: false,
  60. perfUltraMode: true,
  61. boxZoomMode: false,
  62. boxZoomDrag: null,
  63. minimapDragging: false,
  64. activeTouchPointers: new Map(),
  65. pinchState: null,
  66. tpByRef: new Map(),
  67. tpIndexMap: new Map(),
  68. resByRef: new Map(),
  69. resIndexMap: new Map(),
  70. hoverTargetKey: "",
  71. lastFrameMs: 0.1,
  72. runtime: {status: "loading", recommendationsEnabled: false, adcCopyEnabled: false, staleSources: []},
  73. categories: new Set(["CON", "J", "PL", "TP"]),
  74. showShieldPins: false,
  75. boardSide: "front",
  76. selectedTouchpoint: null,
  77. selectedResistor: null,
  78. selectedPin: null,
  79. highlightAllSame: false,
  80. baseViewBox: null,
  81. viewBox: null,
  82. dragging: null,
  83. activeTab: "detail",
  84. searchResults: [],
  85. activeSearchIndex: -1,
  86. peripheralCategory: "ALL",
  87. peripheralUsage: "all",
  88. peripheralQuery: "",
  89. peripheralHighlightedRefs: new Set(),
  90. cpldDomainId: "comm_params",
  91. cpldGroupId: "board_current",
  92. cpldTopicId: "curr_overview",
  93. cpldFilterQuery: "",
  94. cpldTreeExpanded: false,
  95. widePanel: false,
  96. rafViewBoxId: 0,
  97. animViewBoxId: 0,
  98. };
  99. const dom = Object.fromEntries(
  100. [
  101. "app",
  102. "app-status",
  103. "board-summary",
  104. "board-search",
  105. "search-results",
  106. "stale-banner",
  107. "category-filters",
  108. "side-controls",
  109. "layer-controls",
  110. "box-zoom-toggle",
  111. "zoom-in",
  112. "zoom-out",
  113. "reset-view",
  114. "board-viewport",
  115. "board-layer-canvas",
  116. "board-svg",
  117. "board-fast-canvas",
  118. "box-zoom-marquee",
  119. "board-minimap-wrap",
  120. "minimap-zoom-badge",
  121. "board-minimap",
  122. "zoom-hud-dock",
  123. "hud-box-zoom",
  124. "hud-zoom-out",
  125. "hud-zoom-in",
  126. "zoom-slider",
  127. "hud-zoom-value",
  128. "hud-reset-view",
  129. "board-loading",
  130. "board-tooltip",
  131. "hotspot-layer",
  132. "pin-layer",
  133. "net-layer",
  134. "selection-layer",
  135. "asset-layers",
  136. "layer-mask",
  137. "layer-silk",
  138. "layer-copper",
  139. "layer-photo",
  140. "photo-control",
  141. "photo-layer",
  142. "photo-label",
  143. "visible-count",
  144. "zoom-readout",
  145. "perf-mode-toggle",
  146. "selection-readout",
  147. "detail-panel",
  148. "detail-tab",
  149. "peripheral-tab",
  150. "cpld-arch-tab",
  151. "candidate-tab",
  152. "detail-content",
  153. "peripheral-content",
  154. "cpld-arch-content",
  155. "candidate-content",
  156. "candidate-list",
  157. "capability-select",
  158. "drawer-toggle",
  159. "board-version-select",
  160. "open-peripheral-index",
  161. "open-cpld-arch",
  162. "toggle-wide-panel",
  163. "schematic-tab",
  164. "schematic-content",
  165. ].map((id) => [id, document.getElementById(id)]),
  166. );
  167. function svgElement(name, attributes = {}) {
  168. const node = document.createElementNS(SVG_NS, name);
  169. for (const [key, value] of Object.entries(attributes)) node.setAttribute(key, String(value));
  170. return node;
  171. }
  172. function element(name, className = "", content = null) {
  173. const node = document.createElement(name);
  174. if (className) node.className = className;
  175. if (content != null) node.textContent = String(content);
  176. return node;
  177. }
  178. function formatNumber(value, digits = 3) {
  179. const number = Number(value);
  180. return Number.isFinite(number) ? number.toFixed(digits).replace(/\.0+$|(?<=\.[0-9]*?)0+$/g, "") : "未知";
  181. }
  182. function evidenceLabel(tier) {
  183. return {
  184. board_database: "板数据库原始值",
  185. cross_verified: "已交叉验证",
  186. name_inferred: "名称推断",
  187. unknown: "未知",
  188. }[tier] ?? "未知";
  189. }
  190. function directionLabel(direction) {
  191. return {
  192. input: "输入",
  193. output: "输出",
  194. bidirectional: "双向",
  195. passive: "无源",
  196. unknown: "未知",
  197. }[direction] ?? direction ?? "未知";
  198. }
  199. function activeLevelLabel(level) {
  200. return {
  201. high: "高电平有效",
  202. low: "低电平有效",
  203. rising_edge: "上升沿计步脉冲",
  204. state: "状态选择(非有效电平)",
  205. unknown: "未注明",
  206. }[level] ?? level ?? "未注明";
  207. }
  208. function categoryLabel(category) {
  209. return {CON: "连接器", J: "J 类对象", PL: "PL 器件", TP: "测试点", R: "电阻"}[category] ?? category;
  210. }
  211. function touchpointKindLabel(touchpoint) {
  212. if (touchpoint?.connector) return touchpoint.category === "CON" ? "连接器" : "调试接口";
  213. if (touchpoint?.category === "PL") return "电源器件";
  214. if (touchpoint?.category === "J") {
  215. const pins = Array.isArray(touchpoint.pins) ? touchpoint.pins : [];
  216. if (pins.length && pins.every((pin) => pin.mechanical === true)) return "安装孔";
  217. if (pins.some((pin) => pin.function_category === "manufacturing_mark")) return "制造标记";
  218. }
  219. return categoryLabel(touchpoint?.category);
  220. }
  221. function padRoleLabel(role) {
  222. return {
  223. contact: "接触针",
  224. shield: "屏蔽固定焊盘",
  225. mechanical: "机械孔",
  226. unknown: "未分类焊盘",
  227. }[role] ?? "未分类焊盘";
  228. }
  229. function isShieldPin(pin) {
  230. if (!pin) return false;
  231. const num = String(pin.number || "").trim().toUpperCase();
  232. if (num.startsWith("SH")) return true;
  233. if (pin.pad_role === "shield") return true;
  234. if (pin.pad_role === "mechanical" && (num.startsWith("SH") || num.startsWith("MH") || num === "")) return true;
  235. return false;
  236. }
  237. function touchpointPinSummary(touchpoint) {
  238. if (touchpoint.connector) {
  239. return `${touchpoint.connector.contact_count} 接触针 · ${touchpoint.connector.auxiliary_pad_count} 辅助焊盘`;
  240. }
  241. return `${touchpoint.pins.length} 针`;
  242. }
  243. function setStatus(kind, text) {
  244. dom["app-status"].className = `status-badge status-${kind}`;
  245. dom["app-status"].textContent = text;
  246. }
  247. function applyRuntimeStatus() {
  248. const runtime = state.runtime;
  249. if (runtime.status === "pass") {
  250. setStatus("pass", "数据已校验");
  251. dom["stale-banner"].hidden = true;
  252. } else if (runtime.status === "stale_sources") {
  253. setStatus("stale", "来源已变化");
  254. dom["stale-banner"].hidden = false;
  255. dom["stale-banner"].textContent = `源文件与生成时不一致:${(runtime.staleSources ?? []).join(",")}。选脚推荐与 ADC 复制已关闭。`;
  256. } else {
  257. setStatus("error", "资产不可用");
  258. dom["stale-banner"].hidden = false;
  259. dom["stale-banner"].textContent = runtime.message || "生成资产未通过完整性校验。";
  260. }
  261. }
  262. async function loadApplication(version = state.boardVersion || "v2_0") {
  263. state.boardVersion = version;
  264. if (dom["board-version-select"] && dom["board-version-select"].value !== version) {
  265. dom["board-version-select"].value = version;
  266. }
  267. const versionLabels = {
  268. v2_0: "FCB V2.0 (6400)",
  269. v2_0_fan: "FCB_FAN V2.0 (风扇扩展板)",
  270. v1_2: "FCB V1.2 (MRDIMM)",
  271. v1_1: "FCB V1.1 (6400)",
  272. };
  273. const dataUrl = version === "v1_1"
  274. ? "/generated-v1_1/board-data.json"
  275. : (version === "v2_0"
  276. ? "/generated-v2_0/board-data.json"
  277. : (version === "v2_0_fan"
  278. ? "/generated-v2_0_fan/board-data.json"
  279. : "/generated/board-data.json"));
  280. const statusUrl = version === "v1_1"
  281. ? "/api/status?version=v1_1"
  282. : (version === "v2_0"
  283. ? "/api/status?version=v2_0"
  284. : (version === "v2_0_fan"
  285. ? "/api/status?version=v2_0_fan"
  286. : "/api/status"));
  287. dom["board-loading"].hidden = false;
  288. dom["board-loading"].textContent = `正在载入 ${versionLabels[version] || version} 板数据...`;
  289. try {
  290. await wasmAccel.init("/board-accel.wasm");
  291. const cachedBundle = state.boardCache.get(version);
  292. if (cachedBundle) {
  293. state.data = cachedBundle.data;
  294. state.runtime = cachedBundle.runtime;
  295. } else {
  296. const [dataResponse, statusResponse] = await Promise.all([
  297. version === "v1_2"
  298. ? fetch("/generated/board-data.json")
  299. : fetch(dataUrl),
  300. version === "v1_2"
  301. ? fetch("/api/status")
  302. : fetch(statusUrl),
  303. ]);
  304. if (!dataResponse.ok) throw new Error(`板数据 HTTP ${dataResponse.status}`);
  305. if (!statusResponse.ok) throw new Error(`状态 HTTP ${statusResponse.status}`);
  306. state.data = await dataResponse.json();
  307. if (state.data?.schema !== "board-viewer-data-v2" || !Array.isArray(state.data?.resistors)) {
  308. throw new Error("生成数据过旧或缺少 resistors[],请重新 generate(需要 board-viewer-data-v2)。");
  309. }
  310. state.runtime = await statusResponse.json();
  311. state.boardCache.set(version, {data: state.data, runtime: state.runtime});
  312. }
  313. initializeBoard();
  314. applyRuntimeStatus();
  315. } catch (error) {
  316. state.runtime = {
  317. status: "error",
  318. recommendationsEnabled: false,
  319. adcCopyEnabled: false,
  320. staleSources: [],
  321. message: error instanceof Error ? error.message : String(error),
  322. };
  323. applyRuntimeStatus();
  324. dom["board-loading"].textContent = "板数据载入失败";
  325. renderEmptyDetail("板数据不可用", state.runtime.message);
  326. }
  327. }
  328. function boardWidth() {
  329. return Number(state.data?.board?.view_box?.width) || 0;
  330. }
  331. function boardHeight() {
  332. return Number(state.data?.board?.view_box?.height) || 0;
  333. }
  334. function toDisplayPoint(point) {
  335. return displayPoint(point, boardWidth(), state.boardSide);
  336. }
  337. function toDisplayBounds(bounds) {
  338. return displayBounds(bounds, boardWidth(), state.boardSide);
  339. }
  340. function buildEntityLookupMaps() {
  341. state.tpByRef.clear();
  342. state.tpIndexMap.clear();
  343. state.resByRef.clear();
  344. state.resIndexMap.clear();
  345. if (!state.data) return;
  346. const tps = state.data.touchpoints ?? [];
  347. for (let i = 0; i < tps.length; i++) {
  348. state.tpByRef.set(tps[i].reference, tps[i]);
  349. state.tpIndexMap.set(tps[i].reference, i);
  350. }
  351. const resistors = state.data.resistors ?? [];
  352. for (let i = 0; i < resistors.length; i++) {
  353. state.resByRef.set(resistors[i].reference, resistors[i]);
  354. state.resIndexMap.set(resistors[i].reference, i);
  355. }
  356. wasmAccel.buildIndex(state.data);
  357. }
  358. function parseSvgInlineStyle(styleStr) {
  359. const out = {};
  360. if (!styleStr) return out;
  361. for (const part of styleStr.split(";")) {
  362. const idx = part.indexOf(":");
  363. if (idx <= 0) continue;
  364. const key = part.slice(0, idx).trim().toLowerCase();
  365. const val = part.slice(idx + 1).trim();
  366. if (key && val) out[key] = val;
  367. }
  368. return out;
  369. }
  370. function resolveElementStyle(el, parentStyle) {
  371. const inline = parseSvgInlineStyle(el.getAttribute("style"));
  372. const pick = (attrName, current) => {
  373. const attrVal = el.getAttribute(attrName);
  374. if (inline[attrName] !== undefined) return inline[attrName];
  375. if (attrVal !== null && attrVal !== "") return attrVal;
  376. return current;
  377. };
  378. return {
  379. fill: pick("fill", parentStyle.fill),
  380. fillOpacity: Number(pick("fill-opacity", parentStyle.fillOpacity)),
  381. stroke: pick("stroke", parentStyle.stroke),
  382. strokeOpacity: Number(pick("stroke-opacity", parentStyle.strokeOpacity)),
  383. strokeWidth: Number(pick("stroke-width", parentStyle.strokeWidth)),
  384. fillRule: pick("fill-rule", parentStyle.fillRule),
  385. opacity: Number(pick("opacity", parentStyle.opacity)),
  386. fontSize: Number(pick("font-size", parentStyle.fontSize)),
  387. textAnchor: pick("text-anchor", parentStyle.textAnchor),
  388. };
  389. }
  390. function shapeToSvgPathD(tag, el) {
  391. if (tag === "path") {
  392. return el.getAttribute("d") || "";
  393. }
  394. if (tag === "circle") {
  395. const cx = Number(el.getAttribute("cx")) || 0;
  396. const cy = Number(el.getAttribute("cy")) || 0;
  397. const r = Number(el.getAttribute("r")) || 0;
  398. if (r <= 0) return "";
  399. return `M${cx - r},${cy}a${r},${r} 0 1,0 ${r * 2},0a${r},${r} 0 1,0 ${-r * 2},0Z`;
  400. }
  401. if (tag === "rect") {
  402. const x = Number(el.getAttribute("x")) || 0;
  403. const y = Number(el.getAttribute("y")) || 0;
  404. const w = Number(el.getAttribute("width")) || 0;
  405. const h = Number(el.getAttribute("height")) || 0;
  406. if (w <= 0 || h <= 0) return "";
  407. const rx = Math.min(Number(el.getAttribute("rx")) || 0, w * 0.5, h * 0.5);
  408. if (rx > 0.01) {
  409. const iw = w - rx * 2;
  410. const ih = h - rx * 2;
  411. return `M${x + rx},${y}h${iw}a${rx},${rx} 0 0,1 ${rx},${rx}v${ih}a${rx},${rx} 0 0,1 ${-rx},${rx}h${-iw}a${rx},${rx} 0 0,1 ${-rx},${-rx}v${-ih}a${rx},${rx} 0 0,1 ${rx},${-rx}Z`;
  412. }
  413. return `M${x},${y}h${w}v${h}h${-w}Z`;
  414. }
  415. return "";
  416. }
  417. function compileSvgToVectorLayer(svgText) {
  418. if (!svgText || typeof DOMParser === "undefined" || typeof Path2D === "undefined") {
  419. return null;
  420. }
  421. const doc = new DOMParser().parseFromString(svgText, "image/svg+xml");
  422. const root = doc.documentElement;
  423. if (!root || root.nodeName.toLowerCase() !== "svg") return null;
  424. // 4 painter z-buckets preserve board layer order while collapsing 14,000+ SVG elements into ~8 Path2D batches
  425. const buckets = [new Map(), new Map(), new Map(), new Map()];
  426. const texts = [];
  427. const rootStyle = resolveElementStyle(root, {
  428. fill: "#000000",
  429. fillOpacity: 1,
  430. stroke: "none",
  431. strokeOpacity: 1,
  432. strokeWidth: 0.1,
  433. fillRule: "nonzero",
  434. opacity: 1,
  435. fontSize: 0.82,
  436. textAnchor: "middle",
  437. });
  438. const walk = (node, inheritedStyle) => {
  439. for (const child of node.children) {
  440. const tag = child.tagName.toLowerCase();
  441. if (tag === "title" || tag === "desc" || tag === "defs") continue;
  442. const style = resolveElementStyle(child, inheritedStyle);
  443. if (style.opacity <= 0) continue;
  444. if (tag === "g") {
  445. walk(child, style);
  446. continue;
  447. }
  448. if (tag === "text") {
  449. const content = (child.textContent || "").trim();
  450. if (content && style.opacity > 0 && (style.fill !== "none" || style.strokeOpacity > 0)) {
  451. texts.push({
  452. text: content,
  453. x: Number(child.getAttribute("x")) || 0,
  454. y: Number(child.getAttribute("y")) || 0,
  455. fontSize: style.fontSize > 0 ? style.fontSize : 0.82,
  456. textAnchor: style.textAnchor || "middle",
  457. fill: style.fill && style.fill !== "none" ? style.fill : "#0f172a",
  458. });
  459. }
  460. continue;
  461. }
  462. const d = shapeToSvgPathD(tag, child);
  463. if (!d) continue;
  464. const fillLc = String(style.fill || "none").toLowerCase();
  465. const strokeLc = String(style.stroke || "none").toLowerCase();
  466. let zBucket = 3;
  467. if (fillLc === "#eef7f2" || strokeLc === "#cde7d8" || strokeLc === "#64748b") {
  468. zBucket = 0;
  469. } else if (fillLc === "#529b7a" || strokeLc === "#529b7a") {
  470. zBucket = 1;
  471. } else if (fillLc === "#fbbf24" || strokeLc === "#b45309") {
  472. zBucket = 2;
  473. }
  474. const fOp = Number.isFinite(style.fillOpacity) ? style.fillOpacity * style.opacity : style.opacity;
  475. const sOp = Number.isFinite(style.strokeOpacity) ? style.strokeOpacity * style.opacity : style.opacity;
  476. const sWidth = Number.isFinite(style.strokeWidth) ? style.strokeWidth : 0.1;
  477. const fRule = style.fillRule === "evenodd" ? "evenodd" : "nonzero";
  478. const key = `${fillLc}|${fOp.toFixed(3)}|${strokeLc}|${sOp.toFixed(3)}|${sWidth.toFixed(3)}|${fRule}`;
  479. let entry = buckets[zBucket].get(key);
  480. if (!entry) {
  481. entry = {
  482. fill: fillLc,
  483. fillOpacity: fOp,
  484. stroke: strokeLc,
  485. strokeOpacity: sOp,
  486. strokeWidth: sWidth,
  487. fillRule: fRule,
  488. dParts: [],
  489. };
  490. buckets[zBucket].set(key, entry);
  491. }
  492. entry.dParts.push(d);
  493. }
  494. };
  495. walk(root, rootStyle);
  496. const batches = [];
  497. for (const bucket of buckets) {
  498. for (const entry of bucket.values()) {
  499. if (!entry.dParts.length) continue;
  500. batches.push({
  501. path2D: new Path2D(entry.dParts.join(" ")),
  502. fill: entry.fill,
  503. fillOpacity: entry.fillOpacity,
  504. stroke: entry.stroke,
  505. strokeOpacity: entry.strokeOpacity,
  506. strokeWidth: entry.strokeWidth,
  507. fillRule: entry.fillRule,
  508. });
  509. }
  510. }
  511. return {batches, texts};
  512. }
  513. function loadCompiledVectorLayer(url) {
  514. if (state.layerImageCache.has(url)) {
  515. return state.layerImageCache.get(url);
  516. }
  517. const promise = fetch(url)
  518. .then((res) => (res.ok ? res.text() : ""))
  519. .then((svgText) => compileSvgToVectorLayer(svgText))
  520. .catch(() => null);
  521. state.layerImageCache.set(url, promise);
  522. return promise;
  523. }
  524. function drawCompiledVectorLayer(ctx, compiled, showTexts = true) {
  525. if (!compiled) return;
  526. ctx.lineCap = "round";
  527. ctx.lineJoin = "round";
  528. for (const batch of compiled.batches) {
  529. if (batch.fill && batch.fill !== "none" && batch.fillOpacity > 0) {
  530. ctx.globalAlpha = batch.fillOpacity;
  531. ctx.fillStyle = batch.fill;
  532. ctx.fill(batch.path2D, batch.fillRule);
  533. }
  534. if (batch.stroke && batch.stroke !== "none" && batch.strokeOpacity > 0 && batch.strokeWidth > 0) {
  535. ctx.globalAlpha = batch.strokeOpacity;
  536. ctx.strokeStyle = batch.stroke;
  537. ctx.lineWidth = batch.strokeWidth;
  538. ctx.stroke(batch.path2D);
  539. }
  540. }
  541. if (showTexts && compiled.texts.length > 0) {
  542. ctx.globalAlpha = 1;
  543. ctx.textBaseline = "alphabetic";
  544. let lastFontSize = -1;
  545. for (const item of compiled.texts) {
  546. if (item.fontSize !== lastFontSize) {
  547. lastFontSize = item.fontSize;
  548. ctx.font = `700 ${item.fontSize}px Consolas, "Cascadia Mono", monospace`;
  549. }
  550. ctx.fillStyle = item.fill;
  551. ctx.textAlign = item.textAnchor === "middle" ? "center" : (item.textAnchor === "end" ? "right" : "left");
  552. ctx.fillText(item.text, item.x, item.y);
  553. }
  554. }
  555. ctx.globalAlpha = 1;
  556. }
  557. function isLayerChecked(layerName) {
  558. const input = dom["layer-controls"]?.querySelector(`input[value="${layerName}"]`);
  559. return input ? input.checked : true;
  560. }
  561. async function prepareLayerBitmapCache() {
  562. if (!state.data || typeof document === "undefined") return;
  563. const ver = state.boardVersion || "v2_0";
  564. const side = state.boardSide || "front";
  565. const maskOn = isLayerChecked("mask");
  566. const copperOn = isLayerChecked("copper");
  567. const silkOn = isLayerChecked("silk");
  568. const compositeKey = `${ver}:${side}:${maskOn ? 1 : 0}:${copperOn ? 1 : 0}:${silkOn ? 1 : 0}`;
  569. if (state.layerCompositeKey === compositeKey && state.layerCompositeReady) {
  570. renderLayerCanvasFrame();
  571. return;
  572. }
  573. state.layerCompositeKey = compositeKey;
  574. state.layerCompositeReady = false;
  575. syncStaticLayerVisibility();
  576. const assets = getLayerAssets(ver, side);
  577. const [maskLayer, copperLayer, silkLayer] = await Promise.all([
  578. maskOn ? loadCompiledVectorLayer(assets.mask) : Promise.resolve(null),
  579. copperOn ? loadCompiledVectorLayer(assets.copper) : Promise.resolve(null),
  580. silkOn ? loadCompiledVectorLayer(assets.silk) : Promise.resolve(null),
  581. ]);
  582. if (state.layerCompositeKey !== compositeKey) return;
  583. state.compiledVectorLayers = {maskLayer, copperLayer, silkLayer};
  584. const bw = Math.max(boardWidth(), 1);
  585. const bh = Math.max(boardHeight(), 1);
  586. // Render a compact thumbnail canvas for the Bird's-Eye Minimap and 1x overview
  587. const thumbW = 1320;
  588. const thumbH = Math.max(Math.round((thumbW * bh) / bw), 180);
  589. if (!state.layerCompositeCanvas) {
  590. state.layerCompositeCanvas = document.createElement("canvas");
  591. }
  592. state.layerCompositeCanvas.width = thumbW;
  593. state.layerCompositeCanvas.height = thumbH;
  594. const offCtx = state.layerCompositeCanvas.getContext("2d", {alpha: true});
  595. if (offCtx) {
  596. offCtx.setTransform(1, 0, 0, 1, 0, 0);
  597. offCtx.clearRect(0, 0, thumbW, thumbH);
  598. const sx = thumbW / bw;
  599. const sy = thumbH / bh;
  600. offCtx.setTransform(sx, 0, 0, sy, 0, 0);
  601. if (maskLayer) drawCompiledVectorLayer(offCtx, maskLayer, false);
  602. if (copperLayer) drawCompiledVectorLayer(offCtx, copperLayer, false);
  603. if (silkLayer) drawCompiledVectorLayer(offCtx, silkLayer, true);
  604. state.layerCompositeReady = Boolean(maskLayer || copperLayer || silkLayer);
  605. }
  606. syncStaticLayerVisibility();
  607. renderLayerCanvasFrame();
  608. renderMinimap();
  609. }
  610. function syncStaticLayerVisibility() {
  611. const layerCanvas = dom["board-layer-canvas"];
  612. const assetLayers = dom["asset-layers"];
  613. if (!layerCanvas || !assetLayers || !state.viewBox || !state.baseViewBox) return;
  614. const photoActive = !dom["layer-photo"]?.hidden && Boolean(state.data?.photo_overlay);
  615. const useVectorCanvas = state.perfUltraMode && state.layerCompositeReady && !photoActive;
  616. layerCanvas.hidden = !useVectorCanvas;
  617. assetLayers.style.display = useVectorCanvas ? "none" : "";
  618. }
  619. function renderLayerCanvasFrame() {
  620. const canvas = dom["board-layer-canvas"];
  621. if (!canvas || canvas.hidden || !state.layerCompositeReady || !state.viewBox) {
  622. return;
  623. }
  624. const viewport = dom["board-viewport"];
  625. const cw = viewport.clientWidth || 1;
  626. const ch = viewport.clientHeight || 1;
  627. const dpr = Math.min(window.devicePixelRatio || 1, 2.5);
  628. const targetW = Math.round(cw * dpr);
  629. const targetH = Math.round(ch * dpr);
  630. if (canvas.width !== targetW || canvas.height !== targetH) {
  631. canvas.width = targetW;
  632. canvas.height = targetH;
  633. }
  634. const ctx = canvas.getContext("2d");
  635. if (!ctx) return;
  636. ctx.setTransform(1, 0, 0, 1, 0, 0);
  637. ctx.clearRect(0, 0, targetW, targetH);
  638. const {x: vx, y: vy, width: vw, height: vh} = state.viewBox;
  639. const scale = Math.min(cw / Math.max(vw, 0.001), ch / Math.max(vh, 0.001));
  640. const offsetX = (cw - vw * scale) * 0.5 - vx * scale;
  641. const offsetY = (ch - vh * scale) * 0.5 - vy * scale;
  642. ctx.setTransform(scale * dpr, 0, 0, scale * dpr, offsetX * dpr, offsetY * dpr);
  643. const layers = state.compiledVectorLayers;
  644. if (layers && (layers.maskLayer || layers.copperLayer || layers.silkLayer)) {
  645. const zoomRatio = state.baseViewBox.width / Math.max(vw, 0.001);
  646. const showSilkTexts = zoomRatio >= 1.3;
  647. if (layers.maskLayer) drawCompiledVectorLayer(ctx, layers.maskLayer, false);
  648. if (layers.copperLayer) drawCompiledVectorLayer(ctx, layers.copperLayer, false);
  649. if (layers.silkLayer) drawCompiledVectorLayer(ctx, layers.silkLayer, showSilkTexts);
  650. } else if (state.layerCompositeCanvas) {
  651. ctx.drawImage(state.layerCompositeCanvas, 0, 0, boardWidth(), boardHeight());
  652. }
  653. }
  654. function applyBoardSide() {
  655. const assets = getLayerAssets(state.boardVersion || "v1_2", state.boardSide);
  656. dom["layer-mask"].setAttribute("href", assets.mask);
  657. dom["layer-silk"].setAttribute("href", assets.silk);
  658. dom["layer-copper"].setAttribute("href", assets.copper);
  659. const sideInput = dom["side-controls"]?.querySelector(`input[value="${state.boardSide}"]`);
  660. if (sideInput instanceof HTMLInputElement) sideInput.checked = true;
  661. dom["board-svg"].dataset.side = state.boardSide;
  662. const photoHidden = state.boardSide !== "front" || !state.data?.photo_overlay;
  663. if (dom["layer-photo"]) {
  664. dom["layer-photo"].hidden = photoHidden || !dom["photo-layer"]?.checked;
  665. }
  666. if (dom["photo-control"]) {
  667. dom["photo-control"].classList.toggle("disabled-control", state.boardSide !== "front");
  668. if (dom["photo-layer"]) dom["photo-layer"].disabled = state.boardSide !== "front" || !state.data?.photo_overlay;
  669. }
  670. prepareLayerBitmapCache();
  671. }
  672. function setBoardSide(side, {rerender = true} = {}) {
  673. const next = side === "back" ? "back" : "front";
  674. if (state.boardSide === next) {
  675. if (rerender) applyBoardSide();
  676. return false;
  677. }
  678. state.boardSide = next;
  679. applyBoardSide();
  680. if (rerender) {
  681. renderBoardMarkers();
  682. }
  683. return true;
  684. }
  685. function ensureItemSide(item) {
  686. const side = item?.side === "back" ? "back" : "front";
  687. return setBoardSide(side, {rerender: false});
  688. }
  689. function initializeBoard() {
  690. state.selectedTouchpoint = null;
  691. state.selectedResistor = null;
  692. state.selectedPin = null;
  693. state.searchResults = [];
  694. dom["search-results"].hidden = true;
  695. dom["selection-readout"].textContent = "未选择";
  696. const {board, counts} = state.data;
  697. const width = Number(board.view_box.width);
  698. const height = Number(board.view_box.height);
  699. const padding = Math.max(height * 0.08, 1.2);
  700. state.baseViewBox = {x: -padding, y: -padding, width: width + padding * 2, height: height + padding * 2};
  701. state.viewBox = {...state.baseViewBox};
  702. state.boardSide = "front";
  703. state.layerCompositeKey = "";
  704. state.layerCompositeReady = false;
  705. buildEntityLookupMaps();
  706. for (const image of [dom["layer-mask"], dom["layer-silk"], dom["layer-copper"], dom["layer-photo"]]) {
  707. image.setAttribute("x", "0");
  708. image.setAttribute("y", "0");
  709. image.setAttribute("width", String(width));
  710. image.setAttribute("height", String(height));
  711. }
  712. applyBoardSide();
  713. const backResistors = (state.data.resistors ?? []).filter((item) => item.side === "back").length;
  714. const summaryText = `${board.name} · ${counts.touchpoints} 座子 · ${counts.resistors ?? 0} 电阻(背 ${backResistors}) · ${counts.connector_contacts} 个 CON 接触针`;
  715. dom["board-summary"].textContent = summaryText;
  716. dom["board-summary"].title = summaryText;
  717. const railX = document.getElementById("coordinate-rail-x") || document.querySelector(".coordinate-rail");
  718. if (railX) {
  719. const halfW = Math.round(width / 2);
  720. const fullW = Math.round(width);
  721. railX.innerHTML = `<span>0 mm</span><span>${halfW} mm</span><span>${fullW} mm</span>`;
  722. }
  723. dom["board-loading"].hidden = true;
  724. state.highlightAllSame = false;
  725. state.peripheralHighlightedRefs = new Set();
  726. dom["board-svg"].classList.add("pins-interactive");
  727. dom["board-svg"].classList.toggle("perf-ultra", state.perfUltraMode);
  728. cancelViewBoxAnimation();
  729. renderBoardMarkers();
  730. updateViewBox();
  731. configurePhotoOverlay();
  732. renderEmptyDetail(
  733. "未选择座子或电阻",
  734. `${counts.touchpoints} 个座子 · ${counts.resistors ?? 0} 个电阻 · ${counts.connector_contacts} 个 CON 接触针 · ${counts.connector_auxiliary_pads} 个 CON 辅助焊盘`,
  735. );
  736. renderPeripheralPanel();
  737. renderCpldArchPanel();
  738. renderCandidates();
  739. }
  740. function configurePhotoOverlay() {
  741. const overlay = state.data?.photo_overlay;
  742. if (!overlay) return;
  743. const matrix = Array.isArray(overlay.matrix) ? overlay.matrix : [];
  744. if (matrix.length !== 6 || !matrix.every(Number.isFinite)) return;
  745. const source = `/generated/${overlay.asset}`;
  746. const image = new Image();
  747. image.addEventListener("load", () => {
  748. dom["layer-photo"].setAttribute("href", source);
  749. dom["layer-photo"].setAttribute("width", String(image.naturalWidth));
  750. dom["layer-photo"].setAttribute("height", String(image.naturalHeight));
  751. dom["layer-photo"].setAttribute("transform", `matrix(${matrix.join(" ")})`);
  752. dom["photo-layer"].disabled = false;
  753. dom["photo-control"].classList.remove("disabled-control");
  754. dom["photo-control"].title = `已校准 ${overlay.control_point_count} 个控制点`;
  755. dom["photo-label"].textContent = "照片";
  756. });
  757. image.addEventListener("error", () => {
  758. dom["photo-control"].title = "照片资产载入失败";
  759. dom["photo-label"].textContent = "照片不可用";
  760. });
  761. image.src = source;
  762. }
  763. function getSelectionIndices() {
  764. if (state.selectedResistor) {
  765. const resIdx = state.resIndexMap.get(state.selectedResistor.reference) ?? -1;
  766. let padIdx = -1;
  767. if (state.selectedPin && Array.isArray(state.selectedResistor.pads)) {
  768. padIdx = state.selectedResistor.pads.findIndex((p) => p.number === state.selectedPin.number);
  769. }
  770. return {selectedResistor: state.selectedResistor, resistorIndex: resIdx, padIndex: padIdx};
  771. }
  772. if (state.selectedTouchpoint) {
  773. const tpIdx = state.tpIndexMap.get(state.selectedTouchpoint.reference) ?? -1;
  774. let pinIdx = -1;
  775. if (state.selectedPin && Array.isArray(state.selectedTouchpoint.pins)) {
  776. pinIdx = state.selectedTouchpoint.pins.findIndex((p) => p.id === state.selectedPin.id);
  777. }
  778. return {selectedTouchpoint: state.selectedTouchpoint, touchpointIndex: tpIdx, pinIndex: pinIdx};
  779. }
  780. return null;
  781. }
  782. function tracePadGeometry(ctx, cx, cy, w, h, rotRad, isRound) {
  783. if (isRound) {
  784. const r = Math.min(w, h) * 0.5;
  785. ctx.moveTo(cx + r, cy);
  786. ctx.arc(cx, cy, r, 0, Math.PI * 2);
  787. return;
  788. }
  789. const hw = w * 0.5;
  790. const hh = h * 0.5;
  791. if (Math.abs(rotRad) > 0.001) {
  792. const c = Math.cos(rotRad);
  793. const s = Math.sin(rotRad);
  794. const ux = hw * c;
  795. const uy = hw * s;
  796. const vx = -hh * s;
  797. const vy = hh * c;
  798. ctx.moveTo(cx - ux - vx, cy - uy - vy);
  799. ctx.lineTo(cx + ux - vx, cy + uy - vy);
  800. ctx.lineTo(cx + ux + vx, cy + uy + vy);
  801. ctx.lineTo(cx - ux + vx, cy - uy + vy);
  802. ctx.closePath();
  803. } else {
  804. ctx.rect(cx - hw, cy - hh, w, h);
  805. }
  806. }
  807. function renderFastCanvasFrame() {
  808. const canvas = dom["board-fast-canvas"];
  809. if (!canvas || !state.viewBox || !state.baseViewBox || !state.data) return;
  810. const viewport = dom["board-viewport"];
  811. const cw = viewport.clientWidth || 1;
  812. const ch = viewport.clientHeight || 1;
  813. const dpr = Math.min(window.devicePixelRatio || 1, 2.5);
  814. const targetW = Math.round(cw * dpr);
  815. const targetH = Math.round(ch * dpr);
  816. if (canvas.width !== targetW || canvas.height !== targetH) {
  817. canvas.width = targetW;
  818. canvas.height = targetH;
  819. }
  820. const ctx = canvas.getContext("2d");
  821. if (!ctx) return;
  822. ctx.setTransform(1, 0, 0, 1, 0, 0);
  823. ctx.clearRect(0, 0, targetW, targetH);
  824. if (!state.perfUltraMode) {
  825. if (dom["perf-mode-toggle"]) {
  826. dom["perf-mode-toggle"].className = "perf-badge is-svg-mode";
  827. dom["perf-mode-toggle"].textContent = "矢量 DOM 模式 (点击切换 Rust+WASM)";
  828. }
  829. return;
  830. }
  831. const t0 = performance.now();
  832. const {x: vx, y: vy, width: vw, height: vh} = state.viewBox;
  833. const scale = Math.min(cw / Math.max(vw, 0.001), ch / Math.max(vh, 0.001));
  834. const offsetX = (cw - vw * scale) * 0.5 - vx * scale;
  835. const offsetY = (ch - vh * scale) * 0.5 - vy * scale;
  836. const zoomRatio = state.baseViewBox.width / Math.max(vw, 0.001);
  837. ctx.setTransform(scale * dpr, 0, 0, scale * dpr, offsetX * dpr, offsetY * dpr);
  838. const invScale = 1 / Math.max(scale, 0.1);
  839. const culled = wasmAccel.cullViewport(
  840. state.viewBox,
  841. state.boardSide,
  842. state.categories,
  843. state.showShieldPins,
  844. zoomRatio,
  845. getSelectionIndices(),
  846. );
  847. if (culled && culled.count > 0) {
  848. const buf = culled.buffer;
  849. const count = culled.count;
  850. // Pass 1: Contact pins (kind=2, role=0) batched for single GPU stroke/fill
  851. ctx.beginPath();
  852. for (let i = 0; i < count; i++) {
  853. const base = i * 8;
  854. const packed = buf[base + 5] | 0;
  855. const kind = packed & 0x0f;
  856. const role = (packed >> 4) & 0x0f;
  857. const isRound = (packed & 256) !== 0;
  858. const isShield = (packed & 512) !== 0;
  859. const isSelected = (packed & 1024) !== 0;
  860. if (kind !== 2 || role !== 0 || isShield || isSelected) continue;
  861. const cx = buf[base];
  862. const cy = buf[base + 1];
  863. const w = buf[base + 2];
  864. const h = buf[base + 3];
  865. // Skip painting over large M3/M4 mounting holes that are already drawn on the PCB layer
  866. if (isRound && w >= 5.5 && h >= 5.5) continue;
  867. const rotRad = buf[base + 4];
  868. tracePadGeometry(ctx, cx, cy, w, h, rotRad, isRound);
  869. }
  870. ctx.fillStyle = "rgba(251, 191, 36, 0.12)";
  871. ctx.fill();
  872. ctx.lineWidth = 0.95 * invScale;
  873. ctx.strokeStyle = "rgba(180, 83, 9, 0.55)";
  874. ctx.stroke();
  875. // Pass 2: Shield pins (role=1) & unknown pins (role=3)
  876. for (let i = 0; i < count; i++) {
  877. const base = i * 8;
  878. const packed = buf[base + 5] | 0;
  879. const kind = packed & 0x0f;
  880. const role = (packed >> 4) & 0x0f;
  881. if (kind !== 2 || role === 0 || role === 2) continue;
  882. const isRound = (packed & 256) !== 0;
  883. const cx = buf[base];
  884. const cy = buf[base + 1];
  885. const w = buf[base + 2];
  886. const h = buf[base + 3];
  887. const rotRad = buf[base + 4];
  888. ctx.beginPath();
  889. tracePadGeometry(ctx, cx, cy, w, h, rotRad, isRound);
  890. ctx.fillStyle = role === 1 ? "rgba(251, 191, 36, 0.25)" : "rgba(180, 35, 24, 0.12)";
  891. ctx.fill();
  892. ctx.lineWidth = 0.9 * invScale;
  893. ctx.strokeStyle = role === 1 ? "#b45309" : "#b42318";
  894. ctx.stroke();
  895. }
  896. // Pass 3: Resistor hotspots (kind=3) and resistor pads (kind=4) batched
  897. if (state.categories.has("R")) {
  898. ctx.beginPath();
  899. for (let i = 0; i < count; i++) {
  900. const base = i * 8;
  901. const packed = buf[base + 5] | 0;
  902. if ((packed & 0x0f) !== 3) continue;
  903. const cx = buf[base];
  904. const cy = buf[base + 1];
  905. const w = buf[base + 2];
  906. const h = buf[base + 3];
  907. ctx.rect(cx - w * 0.5, cy - h * 0.5, w, h);
  908. }
  909. ctx.fillStyle = "rgba(99, 102, 241, 0.08)";
  910. ctx.fill();
  911. ctx.lineWidth = 0.85 * invScale;
  912. ctx.strokeStyle = "rgba(99, 102, 241, 0.55)";
  913. ctx.stroke();
  914. ctx.beginPath();
  915. for (let i = 0; i < count; i++) {
  916. const base = i * 8;
  917. const packed = buf[base + 5] | 0;
  918. if ((packed & 0x0f) !== 4) continue;
  919. const cx = buf[base];
  920. const cy = buf[base + 1];
  921. const w = buf[base + 2];
  922. const h = buf[base + 3];
  923. const rotRad = buf[base + 4];
  924. tracePadGeometry(ctx, cx, cy, w, h, rotRad, false);
  925. }
  926. ctx.fillStyle = "rgba(99, 102, 241, 0.16)";
  927. ctx.fill();
  928. ctx.lineWidth = 0.9 * invScale;
  929. ctx.strokeStyle = "#4f46e5";
  930. ctx.stroke();
  931. }
  932. // Pass 4: Selected pin / pad exact contour & border highlight (NO oversized circle!)
  933. for (let i = 0; i < count; i++) {
  934. const base = i * 8;
  935. const packed = buf[base + 5] | 0;
  936. const kind = packed & 0x0f;
  937. const isSelected = (packed & 1024) !== 0;
  938. if (!isSelected || (kind !== 2 && kind !== 4)) continue;
  939. const isRound = (packed & 256) !== 0;
  940. const cx = buf[base];
  941. const cy = buf[base + 1];
  942. const w = buf[base + 2];
  943. const h = buf[base + 3];
  944. const rotRad = buf[base + 4];
  945. ctx.beginPath();
  946. tracePadGeometry(ctx, cx, cy, w, h, rotRad, isRound);
  947. ctx.fillStyle = "rgba(16, 185, 129, 0.42)";
  948. ctx.fill();
  949. ctx.lineWidth = 2.4 * invScale;
  950. ctx.strokeStyle = "#059669";
  951. ctx.stroke();
  952. ctx.lineWidth = 0.9 * invScale;
  953. ctx.strokeStyle = "#ecfdf5";
  954. ctx.stroke();
  955. }
  956. }
  957. const drawMs = performance.now() - t0;
  958. state.lastFrameMs = drawMs;
  959. if (dom["perf-mode-toggle"]) {
  960. dom["perf-mode-toggle"].className = "perf-badge";
  961. const vis = wasmAccel.lastVisibleCount || 0;
  962. const tot = wasmAccel.totalIndexedCount || 0;
  963. dom["perf-mode-toggle"].textContent = `⚡ ${wasmAccel.engineType} · 视口 ${vis}/${tot} · ${drawMs.toFixed(2)}ms`;
  964. }
  965. }
  966. function renderMinimap() {
  967. const wrap = dom["board-minimap-wrap"];
  968. const canvas = dom["board-minimap"];
  969. if (!wrap || !canvas || !state.viewBox || !state.baseViewBox || !state.data) return;
  970. const ratio = state.baseViewBox.width / Math.max(state.viewBox.width, 0.001);
  971. if (ratio <= 1.08) {
  972. wrap.hidden = true;
  973. return;
  974. }
  975. wrap.hidden = false;
  976. if (dom["minimap-zoom-badge"]) {
  977. dom["minimap-zoom-badge"].textContent = `${Math.round(ratio * 100)}%`;
  978. }
  979. const ctx = canvas.getContext("2d");
  980. if (!ctx) return;
  981. const mw = canvas.width;
  982. const mh = canvas.height;
  983. ctx.clearRect(0, 0, mw, mh);
  984. const bx = state.baseViewBox.x;
  985. const by = state.baseViewBox.y;
  986. const bw = Math.max(state.baseViewBox.width, 1);
  987. const bh = Math.max(state.baseViewBox.height, 1);
  988. const scale = Math.min(mw / bw, mh / bh);
  989. const ox = (mw - bw * scale) * 0.5 - bx * scale;
  990. const oy = (mh - bh * scale) * 0.5 - by * scale;
  991. // Draw board outline or pre-rasterized layer thumbnail
  992. const boardW = boardWidth();
  993. const boardH = boardHeight();
  994. if (state.layerCompositeReady && state.layerCompositeCanvas) {
  995. ctx.drawImage(
  996. state.layerCompositeCanvas,
  997. ox,
  998. oy,
  999. boardW * scale,
  1000. boardH * scale,
  1001. );
  1002. } else {
  1003. ctx.fillStyle = "#dcfce7";
  1004. ctx.strokeStyle = "#16a34a";
  1005. ctx.lineWidth = 1;
  1006. ctx.fillRect(ox, oy, boardW * scale, boardH * scale);
  1007. ctx.strokeRect(ox, oy, boardW * scale, boardH * scale);
  1008. }
  1009. // Draw selected target indicator on minimap if present
  1010. const selTarget = state.selectedResistor || state.selectedTouchpoint;
  1011. if (selTarget?.view_position) {
  1012. const pt = toDisplayPoint(selTarget.view_position);
  1013. ctx.fillStyle = "#f59e0b";
  1014. ctx.beginPath();
  1015. ctx.arc(ox + pt.x * scale, oy + pt.y * scale, 3, 0, Math.PI * 2);
  1016. ctx.fill();
  1017. }
  1018. // Draw current viewport rectangle
  1019. const vx = ox + state.viewBox.x * scale;
  1020. const vy = oy + state.viewBox.y * scale;
  1021. const vw = Math.max(state.viewBox.width * scale, 4);
  1022. const vh = Math.max(state.viewBox.height * scale, 4);
  1023. ctx.fillStyle = "rgba(2, 132, 199, 0.22)";
  1024. ctx.fillRect(vx, vy, vw, vh);
  1025. ctx.strokeStyle = "#0284c7";
  1026. ctx.lineWidth = 1.6;
  1027. ctx.strokeRect(vx, vy, vw, vh);
  1028. }
  1029. function updateViewBox() {
  1030. if (!state.viewBox) return;
  1031. const {x, y, width, height} = state.viewBox;
  1032. dom["board-svg"].setAttribute("viewBox", `${x} ${y} ${width} ${height}`);
  1033. const ratio = state.baseViewBox.width / Math.max(width, 0.001);
  1034. const pct = Math.round(ratio * 100);
  1035. const pctText = `${pct}%`;
  1036. dom["zoom-readout"].textContent = pctText;
  1037. if (dom["hud-zoom-value"]) dom["hud-zoom-value"].textContent = pctText;
  1038. if (dom["zoom-slider"]) {
  1039. dom["zoom-slider"].value = String(Math.min(Math.max(pct, 80), 3500));
  1040. }
  1041. if (dom["zoom-hud-dock"]) {
  1042. const presetBtns = dom["zoom-hud-dock"].querySelectorAll(".hud-preset-btn[data-zoom]");
  1043. for (const btn of presetBtns) {
  1044. const targetZ = Number(btn.dataset.zoom);
  1045. btn.classList.toggle("is-active", Math.abs(ratio - targetZ) < targetZ * 0.12);
  1046. }
  1047. }
  1048. syncStaticLayerVisibility();
  1049. renderLayerCanvasFrame();
  1050. renderFastCanvasFrame();
  1051. renderMinimap();
  1052. }
  1053. function scheduleViewBoxUpdate() {
  1054. if (state.rafViewBoxId) return;
  1055. state.rafViewBoxId = window.requestAnimationFrame(() => {
  1056. state.rafViewBoxId = 0;
  1057. updateViewBox();
  1058. });
  1059. }
  1060. function cancelViewBoxAnimation() {
  1061. if (state.animViewBoxId) {
  1062. window.cancelAnimationFrame(state.animViewBoxId);
  1063. state.animViewBoxId = 0;
  1064. }
  1065. if (state.rafViewBoxId) {
  1066. window.cancelAnimationFrame(state.rafViewBoxId);
  1067. state.rafViewBoxId = 0;
  1068. }
  1069. }
  1070. function animateViewBoxTo(target, durationMs = 220) {
  1071. cancelViewBoxAnimation();
  1072. if (!state.viewBox || !target || durationMs <= 0) {
  1073. state.viewBox = {...target};
  1074. clampViewBox();
  1075. updateViewBox();
  1076. return;
  1077. }
  1078. const start = {...state.viewBox};
  1079. const dest = {...target};
  1080. const startTime = performance.now();
  1081. const step = (now) => {
  1082. const t = Math.min(Math.max((now - startTime) / durationMs, 0), 1);
  1083. const ease = 1 - Math.pow(1 - t, 3);
  1084. state.viewBox = {
  1085. x: start.x + (dest.x - start.x) * ease,
  1086. y: start.y + (dest.y - start.y) * ease,
  1087. width: start.width + (dest.width - start.width) * ease,
  1088. height: start.height + (dest.height - start.height) * ease,
  1089. };
  1090. clampViewBox();
  1091. updateViewBox();
  1092. if (t < 1) {
  1093. state.animViewBoxId = window.requestAnimationFrame(step);
  1094. } else {
  1095. state.animViewBoxId = 0;
  1096. }
  1097. };
  1098. state.animViewBoxId = window.requestAnimationFrame(step);
  1099. }
  1100. function effectiveBounds(bounds, minimum = 1.2) {
  1101. const width = Math.max(Number(bounds.width), minimum);
  1102. const height = Math.max(Number(bounds.height), minimum);
  1103. return {
  1104. x: Number(bounds.x) - (width - Number(bounds.width)) / 2,
  1105. y: Number(bounds.y) - (height - Number(bounds.height)) / 2,
  1106. width,
  1107. height,
  1108. };
  1109. }
  1110. function updateSelectionVisuals() {
  1111. const selTpRef = state.selectedTouchpoint?.reference || "";
  1112. const selResRef = state.selectedResistor?.reference || "";
  1113. const selPinId = state.selectedPin?.id || "";
  1114. const selPadNum = state.selectedPin?.number || "";
  1115. for (const node of dom["hotspot-layer"].children) {
  1116. const ref = node.dataset?.reference || "";
  1117. const isRes = node.dataset?.kind === "resistor";
  1118. const isSelected = isRes ? ref === selResRef : ref === selTpRef;
  1119. const isPeriph = !isRes && state.peripheralHighlightedRefs?.has(ref);
  1120. node.classList.toggle("is-selected", isSelected);
  1121. node.classList.toggle("is-peripheral-match", Boolean(isPeriph));
  1122. }
  1123. if (!state.perfUltraMode) {
  1124. for (const group of dom["pin-layer"].children) {
  1125. const ref = group.dataset?.reference || "";
  1126. const isRes = group.dataset?.kind === "resistor";
  1127. const isSelected = isRes
  1128. ? (ref === selResRef && group.dataset?.pin === String(selPadNum))
  1129. : (ref === selTpRef && group.dataset?.pinId === String(selPinId));
  1130. group.classList.toggle("is-selected", isSelected);
  1131. }
  1132. }
  1133. renderSelectionOverlay();
  1134. renderFastCanvasFrame();
  1135. }
  1136. function renderBoardMarkers() {
  1137. dom["hotspot-layer"].replaceChildren();
  1138. dom["pin-layer"].replaceChildren();
  1139. if (!state.data) return;
  1140. dom["board-svg"].classList.toggle("perf-ultra", state.perfUltraMode);
  1141. const hotspotFrag = document.createDocumentFragment();
  1142. const pinFrag = document.createDocumentFragment();
  1143. let visibleTouchpoints = 0;
  1144. let visibleResistors = 0;
  1145. for (const touchpoint of state.data.touchpoints) {
  1146. if (!state.categories.has(touchpoint.category)) continue;
  1147. if (!itemVisibleOnSide(touchpoint, state.boardSide)) continue;
  1148. visibleTouchpoints += 1;
  1149. const bounds = effectiveBounds(toDisplayBounds(touchpoint.view_bounds));
  1150. const isPeripheralMatch = state.peripheralHighlightedRefs?.has(touchpoint.reference);
  1151. const hotspot = svgElement("rect", {
  1152. x: bounds.x,
  1153. y: bounds.y,
  1154. width: bounds.width,
  1155. height: bounds.height,
  1156. rx: 0.45,
  1157. class: `hotspot${state.selectedTouchpoint?.reference === touchpoint.reference ? " is-selected" : ""}${isPeripheralMatch ? " is-peripheral-match" : ""}`,
  1158. tabindex: 0,
  1159. role: "button",
  1160. "aria-label": `${touchpoint.reference} ${touchpointKindLabel(touchpoint)} ${touchpointPinSummary(touchpoint)}`,
  1161. "data-reference": touchpoint.reference,
  1162. "data-side": touchpoint.side || "front",
  1163. });
  1164. hotspotFrag.append(hotspot);
  1165. if (!state.perfUltraMode) {
  1166. for (const pin of touchpoint.pins) {
  1167. const isSh = isShieldPin(pin);
  1168. if (isSh && !state.showShieldPins) continue;
  1169. const point = toDisplayPoint(pin.view_position);
  1170. const group = svgElement("g", {
  1171. class: `pin-group role-${pin.pad_role}${state.selectedTouchpoint?.reference === touchpoint.reference && state.selectedPin?.id === pin.id ? " is-selected" : ""}`,
  1172. tabindex: 0,
  1173. role: "button",
  1174. "aria-label": `${touchpoint.reference}.${pin.number || "机械"} ${pin.net || "无网络"}`,
  1175. "data-reference": touchpoint.reference,
  1176. "data-pin": pin.number,
  1177. "data-pin-id": pin.id,
  1178. "data-pad-role": pin.pad_role,
  1179. });
  1180. const pw = Number(pin.size?.width) || 1.4;
  1181. const ph = Number(pin.size?.height) || 1.4;
  1182. const rot = Number(pin.rotation || 0.0);
  1183. const isRound = pin.shape === "circle" || (!pin.shape && Math.abs(pw - ph) < 0.05);
  1184. const dotEl = isRound
  1185. ? svgElement("circle", {cx: point.x, cy: point.y, r: pw / 2, class: "pin-dot"})
  1186. : svgElement("rect", {x: point.x - pw / 2, y: point.y - ph / 2, width: pw, height: ph, rx: 0.1, class: "pin-dot"});
  1187. if (rot !== 0) group.setAttribute("transform", `rotate(${rot} ${point.x} ${point.y})`);
  1188. group.append(dotEl);
  1189. pinFrag.append(group);
  1190. }
  1191. }
  1192. }
  1193. for (const resistor of state.data.resistors ?? []) {
  1194. if (!state.categories.has("R")) continue;
  1195. if (!itemVisibleOnSide(resistor, state.boardSide)) continue;
  1196. visibleResistors += 1;
  1197. if (!state.perfUltraMode) {
  1198. const bounds = effectiveBounds(toDisplayBounds(resistor.view_bounds), 0.4);
  1199. const selected = state.selectedResistor?.reference === resistor.reference;
  1200. const hotspot = svgElement("rect", {
  1201. x: bounds.x,
  1202. y: bounds.y,
  1203. width: bounds.width,
  1204. height: bounds.height,
  1205. rx: 0.25,
  1206. class: `hotspot hotspot-resistor${selected ? " is-selected" : ""}`,
  1207. tabindex: 0,
  1208. role: "button",
  1209. "aria-label": `${resistor.reference} 电阻 ${resistor.component_value || "未标注阻值"}`,
  1210. "data-reference": resistor.reference,
  1211. "data-kind": "resistor",
  1212. "data-side": resistor.side || "front",
  1213. });
  1214. hotspotFrag.append(hotspot);
  1215. }
  1216. }
  1217. dom["hotspot-layer"].append(hotspotFrag);
  1218. if (!state.perfUltraMode) dom["pin-layer"].append(pinFrag);
  1219. const sideLabel = state.boardSide === "back" ? "背面" : "正面";
  1220. dom["visible-count"].textContent = `${sideLabel} · ${visibleTouchpoints} 个座子 · ${visibleResistors} 个电阻`;
  1221. renderSelectionOverlay();
  1222. renderFastCanvasFrame();
  1223. }
  1224. function showTouchpointTooltip(event, touchpoint) {
  1225. dom["board-tooltip"].replaceChildren();
  1226. const periph = classifyTouchpointPeripheral(touchpoint, state.boardVersion);
  1227. const key = element("div", "tooltip-key", `${touchpoint.reference} · ${periph.peripheralLabel}`);
  1228. const usageText = periph.isUsed ? "已启用外设" : (periph.isSpareConnector ? "空余插座" : "板级节点");
  1229. const detail = element("div", "tooltip-role", `${usageText} · ${touchpointKindLabel(touchpoint)} · ${touchpointPinSummary(touchpoint)}`);
  1230. const summary = element("div", "", touchpoint.summary);
  1231. dom["board-tooltip"].append(key, detail, summary);
  1232. dom["board-tooltip"].hidden = false;
  1233. if (event) positionTooltip(event);
  1234. else positionTooltipForTouchpoint(touchpoint);
  1235. }
  1236. function showPinTooltip(event, touchpoint, pin) {
  1237. dom["board-tooltip"].replaceChildren();
  1238. const logical = resolveLogicalPin(touchpoint, pin, state.boardVersion);
  1239. dom["board-tooltip"].append(
  1240. element("div", "tooltip-key", `${touchpoint.reference}.${pin.number || "机械孔"}`),
  1241. element("div", "tooltip-role", logical.displayBadge),
  1242. element("div", "", `${logical.peripheralRole} · 网络: ${pin.net || "无命名网络"}`),
  1243. element("div", "", logical.pinDefinition || pin.summary || evidenceLabel(pin.evidence_tier)),
  1244. );
  1245. dom["board-tooltip"].hidden = false;
  1246. if (event) positionTooltip(event);
  1247. else positionTooltipForTouchpoint(touchpoint);
  1248. }
  1249. function showResistorTooltip(event, resistor) {
  1250. dom["board-tooltip"].replaceChildren();
  1251. const nets = (resistor.pads ?? []).filter((pad) => pad.net).map((pad) => pad.net);
  1252. dom["board-tooltip"].append(
  1253. element("div", "tooltip-key", resistor.reference),
  1254. element("div", "", `电阻 · ${resistor.component_value || "阻值未标注"}`),
  1255. element("div", "", nets.length ? nets.join(" ↔ ") : "无命名网络"),
  1256. );
  1257. dom["board-tooltip"].hidden = false;
  1258. if (event) positionTooltip(event);
  1259. else positionTooltipForBounds(toDisplayBounds(resistor.view_bounds));
  1260. }
  1261. function showResistorPadTooltip(event, resistor, pad) {
  1262. dom["board-tooltip"].replaceChildren();
  1263. dom["board-tooltip"].append(
  1264. element("div", "tooltip-key", `${resistor.reference}.${pad.number || "机械孔"}`),
  1265. element("div", "tooltip-role", pad.pad_role === "electrical" ? "电气焊盘" : "机械焊盘"),
  1266. element("div", "", pad.net || "无命名网络"),
  1267. element("div", "", resistor.component_value || "阻值未标注"),
  1268. );
  1269. dom["board-tooltip"].hidden = false;
  1270. if (event) positionTooltip(event);
  1271. else positionTooltipForBounds(toDisplayBounds(resistor.view_bounds));
  1272. }
  1273. function positionTooltip(event) {
  1274. if (!event || dom["board-tooltip"].hidden) return;
  1275. const viewport = dom["board-viewport"].getBoundingClientRect();
  1276. const tooltip = dom["board-tooltip"];
  1277. const left = Math.min(event.clientX - viewport.left + 12, viewport.width - tooltip.offsetWidth - 12);
  1278. const top = Math.min(event.clientY - viewport.top + 12, viewport.height - tooltip.offsetHeight - 12);
  1279. tooltip.style.left = `${Math.max(8, left)}px`;
  1280. tooltip.style.top = `${Math.max(8, top)}px`;
  1281. }
  1282. function positionTooltipForTouchpoint(touchpoint) {
  1283. positionTooltipForBounds(toDisplayBounds(touchpoint.view_bounds), toDisplayPoint(touchpoint.view_position));
  1284. }
  1285. function positionTooltipForBounds(bounds, point = null) {
  1286. const anchor = point || {
  1287. x: Number(bounds.x) + Number(bounds.width) / 2,
  1288. y: Number(bounds.y) + Number(bounds.height) / 2,
  1289. };
  1290. const svgPoint = dom["board-svg"].createSVGPoint();
  1291. svgPoint.x = anchor.x;
  1292. svgPoint.y = anchor.y;
  1293. const screen = svgPoint.matrixTransform(dom["board-svg"].getScreenCTM());
  1294. positionTooltip({clientX: screen.x, clientY: screen.y});
  1295. }
  1296. function hideTooltip() {
  1297. state.hoverTargetKey = "";
  1298. dom["board-tooltip"].hidden = true;
  1299. }
  1300. function appendResistorPadMarker(layer, pad) {
  1301. const point = toDisplayPoint(pad.view_position);
  1302. const width = Math.max(Number(pad.size?.width) || 0, Number(pad.view_bounds?.width) || 0, 0.2);
  1303. const height = Math.max(Number(pad.size?.height) || 0, Number(pad.view_bounds?.height) || 0, 0.2);
  1304. let rotation = Number(pad.rotation) || 0;
  1305. if (state.boardSide === "back") rotation = -rotation;
  1306. const shape = String(pad.shape || "rect").toLowerCase();
  1307. const halo = 0.12;
  1308. const isRound =
  1309. shape.includes("circle")
  1310. || shape.includes("round")
  1311. || (shape.includes("oval") && Math.abs(width - height) < 0.05);
  1312. if (isRound) {
  1313. layer.append(
  1314. svgElement("ellipse", {
  1315. cx: point.x,
  1316. cy: point.y,
  1317. rx: width / 2 + halo,
  1318. ry: height / 2 + halo,
  1319. class: "resistor-pad-halo",
  1320. }),
  1321. svgElement("ellipse", {
  1322. cx: point.x,
  1323. cy: point.y,
  1324. rx: width / 2,
  1325. ry: height / 2,
  1326. class: "resistor-pad-marker",
  1327. "data-pad-id": pad.id || "",
  1328. "data-pad-shape": shape || "circle",
  1329. }),
  1330. );
  1331. return;
  1332. }
  1333. const group = svgElement("g", {
  1334. transform: `rotate(${rotation} ${point.x} ${point.y})`,
  1335. "data-pad-id": pad.id || "",
  1336. "data-pad-shape": shape || "rect",
  1337. });
  1338. group.append(
  1339. svgElement("rect", {
  1340. x: point.x - width / 2 - halo,
  1341. y: point.y - height / 2 - halo,
  1342. width: width + halo * 2,
  1343. height: height + halo * 2,
  1344. class: "resistor-pad-halo",
  1345. }),
  1346. svgElement("rect", {
  1347. x: point.x - width / 2,
  1348. y: point.y - height / 2,
  1349. width,
  1350. height,
  1351. class: "resistor-pad-marker",
  1352. }),
  1353. );
  1354. layer.append(group);
  1355. }
  1356. function appendExactNetPadHighlight(layer, pad, isResistorPad) {
  1357. const point = toDisplayPoint(pad.view_position);
  1358. const width = Math.max(Number(pad.size?.width) || 0, Number(pad.view_bounds?.width) || 0, 0.35);
  1359. const height = Math.max(Number(pad.size?.height) || 0, Number(pad.view_bounds?.height) || 0, 0.35);
  1360. let rotation = Number(pad.rotation) || 0;
  1361. if (state.boardSide === "back") rotation = -rotation;
  1362. const shape = String(pad.shape || "").toLowerCase();
  1363. const isRound =
  1364. shape === "circle"
  1365. || shape === "round"
  1366. || (!shape && Math.abs(width - height) < 0.05 && !isResistorPad);
  1367. const cls = `net-highlight${isResistorPad ? " net-resistor" : ""}`;
  1368. if (isRound) {
  1369. layer.append(
  1370. svgElement("circle", {
  1371. cx: point.x,
  1372. cy: point.y,
  1373. r: Math.min(width, height) * 0.5,
  1374. class: cls,
  1375. }),
  1376. );
  1377. return;
  1378. }
  1379. const attrs = {
  1380. x: point.x - width * 0.5,
  1381. y: point.y - height * 0.5,
  1382. width,
  1383. height,
  1384. rx: Math.min(width, height) * 0.16,
  1385. class: cls,
  1386. };
  1387. if (Math.abs(rotation) > 0.01) {
  1388. attrs.transform = `rotate(${rotation} ${point.x} ${point.y})`;
  1389. }
  1390. layer.append(svgElement("rect", attrs));
  1391. }
  1392. function appendSelectedPinMarker(layer, pin) {
  1393. if (!pin?.view_position) return;
  1394. const point = toDisplayPoint(pin.view_position);
  1395. const width = Math.max(Number(pin.size?.width) || 0, Number(pin.view_bounds?.width) || 0, 0.35);
  1396. const height = Math.max(Number(pin.size?.height) || 0, Number(pin.view_bounds?.height) || 0, 0.35);
  1397. let rotation = Number(pin.rotation) || 0;
  1398. if (state.boardSide === "back") rotation = -rotation;
  1399. const shape = String(pin.shape || "").toLowerCase();
  1400. const isRound =
  1401. shape === "circle"
  1402. || shape === "round"
  1403. || (!shape && Math.abs(width - height) < 0.05);
  1404. if (isRound) {
  1405. layer.append(
  1406. svgElement("circle", {
  1407. cx: point.x,
  1408. cy: point.y,
  1409. r: Math.min(width, height) * 0.5,
  1410. class: "selected-pin-marker",
  1411. }),
  1412. );
  1413. return;
  1414. }
  1415. const attrs = {
  1416. x: point.x - width * 0.5,
  1417. y: point.y - height * 0.5,
  1418. width,
  1419. height,
  1420. rx: Math.min(width, height) * 0.16,
  1421. class: "selected-pin-marker",
  1422. };
  1423. if (Math.abs(rotation) > 0.01) {
  1424. attrs.transform = `rotate(${rotation} ${point.x} ${point.y})`;
  1425. }
  1426. layer.append(svgElement("rect", attrs));
  1427. }
  1428. function renderSelectionOverlay() {
  1429. dom["selection-layer"].replaceChildren();
  1430. dom["net-layer"].replaceChildren();
  1431. const target = state.selectedResistor || state.selectedTouchpoint;
  1432. if (target && itemVisibleOnSide(target, state.boardSide)) {
  1433. const bounds = effectiveBounds(toDisplayBounds(target.view_bounds), state.selectedResistor ? 0.65 : 1.3);
  1434. const pad = state.selectedResistor ? 0.18 : 0.32;
  1435. const x = bounds.x - pad;
  1436. const y = bounds.y - pad;
  1437. const width = bounds.width + pad * 2;
  1438. const height = bounds.height + pad * 2;
  1439. dom["selection-layer"].append(
  1440. svgElement("rect", {x, y, width, height, rx: state.selectedResistor ? 0.22 : 0.38, class: "selection-reticle"}),
  1441. );
  1442. if (state.selectedResistor) {
  1443. for (const resistorPad of state.selectedResistor.pads ?? []) {
  1444. appendResistorPadMarker(dom["selection-layer"], resistorPad);
  1445. }
  1446. } else if (state.selectedPin) {
  1447. appendSelectedPinMarker(dom["selection-layer"], state.selectedPin);
  1448. }
  1449. }
  1450. // Only highlight all same-net / same-function points across the board when Ctrl+Click (highlightAllSame) is active
  1451. if (!state.highlightAllSame) return;
  1452. const seenPads = new Set();
  1453. const addPadHighlight = (pad, isResistorPad, key) => {
  1454. if (!pad?.view_position || seenPads.has(key)) return;
  1455. seenPads.add(key);
  1456. appendExactNetPadHighlight(dom["net-layer"], pad, isResistorPad);
  1457. };
  1458. const net = state.selectedPin?.net;
  1459. if (net) {
  1460. for (const item of sameNetMembers(state.data, net)) {
  1461. const ownerSide = item.resistor?.side || item.touchpoint?.side || "front";
  1462. if (ownerSide !== state.boardSide) continue;
  1463. const key = `${item.kind}:${item.reference}:${item.pin.id || item.pin.number}`;
  1464. addPadHighlight(item.pin, item.kind === "resistor_pad", key);
  1465. }
  1466. }
  1467. // If Ctrl-clicked a functional pin (e.g., PTC / FAN / TEMP / LIMIT / MOTOR), also highlight same-function pins
  1468. if (state.selectedTouchpoint && state.selectedPin) {
  1469. const selLogical = resolveLogicalPin(state.selectedTouchpoint, state.selectedPin, state.boardVersion);
  1470. const cat = selLogical.peripheralCategory;
  1471. if (cat && cat !== "OTHER" && cat !== "SPAR" && selLogical.chip !== "GND") {
  1472. for (const tp of state.data?.touchpoints ?? []) {
  1473. if (!itemVisibleOnSide(tp, state.boardSide)) continue;
  1474. if (!state.categories.has(tp.category)) continue;
  1475. for (const p of tp.pins ?? []) {
  1476. if (isShieldPin(p) && !state.showShieldPins) continue;
  1477. const candLogical = resolveLogicalPin(tp, p, state.boardVersion);
  1478. if (
  1479. candLogical.peripheralCategory === cat &&
  1480. candLogical.chip === selLogical.chip &&
  1481. p.pad_role === state.selectedPin.pad_role
  1482. ) {
  1483. addPadHighlight(p, false, `pin:${tp.reference}:${p.id || p.number}`);
  1484. }
  1485. }
  1486. }
  1487. }
  1488. }
  1489. }
  1490. function selectTouchpoint(touchpoint, pin = null, openDrawer = false, options = {}) {
  1491. const highlightAllSame = Boolean(options?.highlightAllSame);
  1492. state.highlightAllSame = highlightAllSame;
  1493. const sideFlipped = ensureItemSide(touchpoint);
  1494. state.selectedTouchpoint = touchpoint;
  1495. state.selectedResistor = null;
  1496. state.selectedPin = pin;
  1497. if (highlightAllSame && touchpoint && !pin) {
  1498. const targetPeriph = classifyTouchpointPeripheral(touchpoint, state.boardVersion);
  1499. const sameRefs = new Set();
  1500. for (const tp of state.data?.touchpoints ?? []) {
  1501. if (!itemVisibleOnSide(tp, state.boardSide)) continue;
  1502. const p = classifyTouchpointPeripheral(tp, state.boardVersion);
  1503. if (
  1504. p.peripheralCategory === targetPeriph.peripheralCategory &&
  1505. p.isSpareConnector === targetPeriph.isSpareConnector
  1506. ) {
  1507. sameRefs.add(tp.reference);
  1508. }
  1509. }
  1510. state.peripheralHighlightedRefs = sameRefs;
  1511. } else {
  1512. state.peripheralHighlightedRefs = new Set();
  1513. }
  1514. if (pin) {
  1515. const logical = resolveLogicalPin(touchpoint, pin, state.boardVersion);
  1516. const modeSuffix = highlightAllSame ? " · [Ctrl 同类全标]" : "";
  1517. dom["selection-readout"].textContent = `${touchpoint.reference}.${pin.number || "机械孔"} · ${logical.displayBadge}${modeSuffix}`;
  1518. } else {
  1519. const modeSuffix = highlightAllSame ? " · [Ctrl 同类全标]" : "";
  1520. dom["selection-readout"].textContent = `${touchpoint.reference} · ${touchpointPinSummary(touchpoint)}${modeSuffix}`;
  1521. }
  1522. if (openDrawer) setDrawerCollapsed(false);
  1523. if (sideFlipped) {
  1524. renderBoardMarkers();
  1525. } else {
  1526. updateSelectionVisuals();
  1527. }
  1528. renderDetail();
  1529. }
  1530. function selectResistor(resistor, pad = null, openDrawer = false, options = {}) {
  1531. const highlightAllSame = Boolean(options?.highlightAllSame);
  1532. state.highlightAllSame = highlightAllSame;
  1533. state.peripheralHighlightedRefs = new Set();
  1534. const sideFlipped = ensureItemSide(resistor);
  1535. state.selectedResistor = resistor;
  1536. state.selectedTouchpoint = null;
  1537. state.selectedPin = pad;
  1538. const nets = (resistor.pads ?? []).filter((item) => item.net).map((item) => item.net);
  1539. const sideNote = resistor.side === "back" ? " · 背面" : "";
  1540. const modeSuffix = highlightAllSame ? " · [Ctrl 同网全标]" : "";
  1541. dom["selection-readout"].textContent = pad
  1542. ? `${resistor.reference}.${pad.number || "机械孔"} · ${pad.net || "无网络"}${sideNote}${modeSuffix}`
  1543. : `${resistor.reference} · ${resistor.component_value || "阻值未标注"} · ${nets.join(" ↔ ") || "无网络"}${sideNote}${modeSuffix}`;
  1544. if (openDrawer) setDrawerCollapsed(false);
  1545. if (sideFlipped) {
  1546. renderBoardMarkers();
  1547. } else {
  1548. updateSelectionVisuals();
  1549. }
  1550. renderDetail();
  1551. }
  1552. function renderEmptyDetail(title, subtitle) {
  1553. dom["detail-content"].replaceChildren();
  1554. const wrapper = element("div", "empty-panel");
  1555. wrapper.append(element("strong", "", title), element("span", "empty-stats", subtitle));
  1556. dom["detail-content"].append(wrapper);
  1557. }
  1558. function fact(label, value) {
  1559. const wrapper = element("div", "fact");
  1560. wrapper.append(element("span", "fact-label", label), element("span", "fact-value", value));
  1561. return wrapper;
  1562. }
  1563. function logicalBadgeClass(logical) {
  1564. const chip = String(logical?.chip || "").toUpperCase();
  1565. if (chip.includes("FPGA")) return "logical-pin-badge is-fpga";
  1566. if (chip.includes("MCU")) return "logical-pin-badge is-mcu";
  1567. if (chip === "GND") return "logical-pin-badge is-gnd";
  1568. return "logical-pin-badge is-power";
  1569. }
  1570. function renderConnectorLayout(touchpoint, groups) {
  1571. const connector = touchpoint.connector;
  1572. const section = element("section", "connector-layout");
  1573. const header = element("div", "connector-layout-header");
  1574. header.append(
  1575. element("h3", "section-title connector-layout-title", "板正面接触针排列"),
  1576. element("span", `evidence-tag${connector.review_status === "cross_verified" ? " verified" : ""}`, evidenceLabel(connector.review_status)),
  1577. );
  1578. section.append(header);
  1579. if (!groups.contactRows.length) {
  1580. section.append(element("div", "risk-note", "该连接器尚无经过复核的接触针顺序。"));
  1581. return section;
  1582. }
  1583. const orientation = element("div", "connector-orientation");
  1584. orientation.append(element("span", "connector-axis connector-axis-top", "上"));
  1585. const middle = element("div", "connector-axis-row");
  1586. middle.append(element("span", "connector-axis", "左"));
  1587. const grid = element("div", "connector-grid");
  1588. const columns = Math.max(...groups.contactRows.map((row) => row.length), 1);
  1589. for (const pins of groups.contactRows) {
  1590. const row = element("div", "connector-grid-row");
  1591. row.style.setProperty("--connector-columns", String(columns));
  1592. for (const pin of pins) {
  1593. const button = element("button", `connector-contact${state.selectedPin?.id === pin.id ? " is-selected" : ""}`, pin.number);
  1594. button.type = "button";
  1595. button.dataset.pinId = pin.id;
  1596. button.setAttribute("aria-label", `${touchpoint.reference}.${pin.number},板正面第 ${pin.board_order} 位`);
  1597. button.addEventListener("click", (event) =>
  1598. selectTouchpoint(touchpoint, pin, true, {highlightAllSame: Boolean(event.ctrlKey || event.metaKey)}),
  1599. );
  1600. row.append(button);
  1601. }
  1602. grid.append(row);
  1603. }
  1604. middle.append(grid, element("span", "connector-axis", "右"));
  1605. orientation.append(middle, element("span", "connector-axis connector-axis-bottom", "下"));
  1606. section.append(orientation);
  1607. section.append(
  1608. element(
  1609. "div",
  1610. "connector-layout-meta",
  1611. `${connector.profile} · ${connector.contact_count} 接触针 · ${connector.auxiliary_pad_count} 辅助焊盘`,
  1612. ),
  1613. element(
  1614. "div",
  1615. "connector-perspective-note",
  1616. "板正面俯视:按页面上/下/左/右读取;线缆端或对接面可能是镜像。",
  1617. ),
  1618. );
  1619. return section;
  1620. }
  1621. function renderPinRow(touchpoint, pin) {
  1622. const row = element("button", `pin-row${state.selectedPin?.id === pin.id ? " is-selected" : ""}`);
  1623. row.type = "button";
  1624. row.dataset.pin = pin.number;
  1625. row.dataset.pinId = pin.id;
  1626. row.dataset.padRole = pin.pad_role;
  1627. const logical = resolveLogicalPin(touchpoint, pin, state.boardVersion);
  1628. const primary = element("span", "pin-primary");
  1629. primary.append(
  1630. element("span", "pin-summary", `${logical.peripheralRole} — ${pin.summary || logical.pinDefinition}`),
  1631. element("span", logicalBadgeClass(logical), `逻辑管脚:${logical.displayBadge}`),
  1632. element("span", "pin-net", `原始网络:${pin.net || "无命名网络"} · 电平:${pin.external_level || "未知"}`),
  1633. );
  1634. row.append(
  1635. element("span", "pin-number", pin.number || "孔"),
  1636. primary,
  1637. element("span", "pin-direction", pin.pad_role === "contact" ? directionLabel(pin.direction) : padRoleLabel(pin.pad_role)),
  1638. );
  1639. row.addEventListener("click", (event) =>
  1640. selectTouchpoint(touchpoint, pin, true, {highlightAllSame: Boolean(event.ctrlKey || event.metaKey)}),
  1641. );
  1642. return row;
  1643. }
  1644. function appendPinSection(container, touchpoint, title, pins) {
  1645. if (!pins.length) return;
  1646. container.append(element("h3", "section-title", title));
  1647. const pinList = element("div", "pin-list");
  1648. for (const pin of pins) pinList.append(renderPinRow(touchpoint, pin));
  1649. container.append(pinList);
  1650. }
  1651. function renderDetail() {
  1652. if (state.selectedResistor) {
  1653. renderResistorDetail(state.selectedResistor, state.selectedPin);
  1654. return;
  1655. }
  1656. const touchpoint = state.selectedTouchpoint;
  1657. if (!touchpoint) {
  1658. const counts = state.data?.counts;
  1659. renderEmptyDetail(
  1660. "未选择座子或电阻",
  1661. counts
  1662. ? `${counts.touchpoints} 个座子 · ${counts.resistors ?? 0} 个电阻 · ${counts.connector_contacts} 个 CON 接触针 · ${counts.connector_auxiliary_pads} 个 CON 辅助焊盘`
  1663. : "",
  1664. );
  1665. return;
  1666. }
  1667. dom["detail-content"].replaceChildren();
  1668. const periph = classifyTouchpointPeripheral(touchpoint, state.boardVersion);
  1669. const heading = element("div", "detail-heading");
  1670. const headingText = element("div");
  1671. headingText.append(element("h2", "detail-reference", touchpoint.reference), element("p", "detail-summary", touchpoint.summary));
  1672. const badgeCluster = element("div", "detail-badge-cluster");
  1673. badgeCluster.append(
  1674. element("span", `category-tag ${periph.isUsed ? "is-used-tag" : (periph.isSpareConnector ? "is-spare-tag" : "")}`, `${periph.peripheralLabel} · ${periph.isUsed ? "已用" : (periph.isSpareConnector ? "空余插座" : "板级")}`),
  1675. );
  1676. heading.append(headingText, badgeCluster);
  1677. const facts = element("div", "detail-facts");
  1678. if (touchpoint.connector) {
  1679. facts.append(
  1680. fact("外设归类", `${periph.peripheralLabel} (${periph.isUsed ? "项目已用" : "空余插座"})`),
  1681. fact("接触针 / 焊盘", `${touchpoint.connector.contact_count} 接触针 / ${touchpoint.pins.length} 总焊盘`),
  1682. fact("板面", touchpoint.side === "front" ? "正面" : "背面"),
  1683. fact("坐标 / 旋转", `${formatNumber(touchpoint.position.x)} / ${formatNumber(touchpoint.position.y)} mm · ${formatNumber(touchpoint.rotation, 1)}°`),
  1684. );
  1685. } else {
  1686. facts.append(
  1687. fact("外设归类", periph.peripheralLabel),
  1688. fact("针脚数量", touchpoint.pins.length),
  1689. fact("板面", touchpoint.side === "front" ? "正面" : "背面"),
  1690. fact("坐标", `${formatNumber(touchpoint.position.x)} / ${formatNumber(touchpoint.position.y)} mm`),
  1691. );
  1692. }
  1693. dom["detail-content"].append(heading, facts);
  1694. if (touchpoint.connector) {
  1695. const groups = connectorPinGroups(touchpoint);
  1696. dom["detail-content"].append(renderConnectorLayout(touchpoint, groups));
  1697. const contactPins = groups.contacts.length
  1698. ? groups.contacts
  1699. : touchpoint.pins.filter((pin) => pin.pad_role === "contact");
  1700. const auxiliaryPins = groups.contacts.length
  1701. ? groups.auxiliary
  1702. : touchpoint.pins.filter((pin) => pin.pad_role !== "contact");
  1703. appendPinSection(
  1704. dom["detail-content"],
  1705. touchpoint,
  1706. groups.contacts.length ? "接触针与 FPGA/MCU 逻辑管脚(板正面顺序)" : "接触针与 FPGA/MCU 逻辑管脚(板数据库编号)",
  1707. contactPins,
  1708. );
  1709. if (state.showShieldPins) {
  1710. appendPinSection(dom["detail-content"], touchpoint, "屏蔽与机械焊盘", auxiliaryPins);
  1711. }
  1712. } else {
  1713. const pinsToShow = state.showShieldPins ? touchpoint.pins : touchpoint.pins.filter((pin) => !isShieldPin(pin));
  1714. appendPinSection(dom["detail-content"], touchpoint, "针脚与 FPGA/MCU 逻辑管脚", pinsToShow);
  1715. }
  1716. if (state.selectedPin) dom["detail-content"].append(renderPinDetail(touchpoint, state.selectedPin));
  1717. }
  1718. function renderResistorDetail(resistor, pad = null) {
  1719. dom["detail-content"].replaceChildren();
  1720. const heading = element("div", "detail-heading");
  1721. const headingText = element("div");
  1722. headingText.append(
  1723. element("h2", "detail-reference", resistor.reference),
  1724. element("p", "detail-summary", resistor.summary || "分立电阻"),
  1725. );
  1726. heading.append(headingText, element("span", "category-tag", "电阻"));
  1727. if (resistor.side === "back") {
  1728. heading.append(element("span", "side-tag side-back", "背面"));
  1729. }
  1730. const nets = (resistor.pads ?? []).filter((item) => item.net).map((item) => item.net);
  1731. const facts = element("div", "detail-facts");
  1732. const assembly = resistor.assembly_status || "unknown";
  1733. facts.append(
  1734. fact("阻值", resistor.component_value || "未标注"),
  1735. fact(
  1736. "解析阻值",
  1737. resistor.value_ohms == null
  1738. ? `不可解析(${resistor.value_parse_status || "unparsed"})`
  1739. : `${resistor.value_ohms} Ω`,
  1740. ),
  1741. fact("装配状态", assembly === "not_fitted" ? "未装/NC" : assembly === "fitted" ? "已装" : "未知"),
  1742. fact("两侧网络", nets.length ? nets.join(" ↔ ") : "无命名网络"),
  1743. fact("焊盘数", resistor.pads?.length ?? 0),
  1744. fact("板面", resistor.side === "front" ? "正面" : "背面"),
  1745. fact("坐标", `${formatNumber(resistor.position.x)} / ${formatNumber(resistor.position.y)} mm`),
  1746. fact("旋转", `${formatNumber(resistor.rotation, 1)}°`),
  1747. );
  1748. dom["detail-content"].append(heading, facts);
  1749. if (assembly === "not_fitted") {
  1750. dom["detail-content"].append(
  1751. element("div", "risk-note", "标注为未装/NC:保留在 PCB 索引中,但不作为已装 0Ω 电气连通默认成员。"),
  1752. );
  1753. }
  1754. if (resistor.side === "back") {
  1755. const tip = element("div", "back-view-tip");
  1756. tip.id = "back-view-tip";
  1757. if (state.boardSide === "back") {
  1758. tip.textContent = "当前为背面实物视角(已对 X 做左右镜像);实体坐标/网络不变。切换到「正面投影」可按板正面坐标系查看。";
  1759. } else {
  1760. tip.textContent = "当前为板正面投影视角;该器件在背面。从实物背面查看时需左右镜像——请切换到「背面实物(左右镜像)」。";
  1761. }
  1762. dom["detail-content"].append(tip);
  1763. }
  1764. const coverage = state.data?.value_coverage;
  1765. if (coverage) {
  1766. dom["detail-content"].append(
  1767. element(
  1768. "div",
  1769. "coverage-hint",
  1770. `阻值覆盖 ${coverage.value_parsed}/${coverage.resistors_total}(原始值非空 ${coverage.component_value_nonempty});来源:${state.data.component_value_source_status || coverage.component_value_source_status}`,
  1771. ),
  1772. );
  1773. }
  1774. const padSection = element("div", "pin-list");
  1775. for (const item of resistor.pads ?? []) {
  1776. const row = element("button", `pin-row${pad?.number === item.number ? " is-selected" : ""}`);
  1777. row.type = "button";
  1778. row.append(
  1779. element("span", "pin-number", item.number || "孔"),
  1780. element("span", "pin-primary", item.net || "无命名网络"),
  1781. element(
  1782. "span",
  1783. "pin-direction",
  1784. `${item.pad_role === "electrical" ? "电气" : "机械"} · ${formatNumber(item.position?.x)}/${formatNumber(item.position?.y)}`,
  1785. ),
  1786. );
  1787. row.addEventListener("click", (event) =>
  1788. selectResistor(resistor, item, true, {highlightAllSame: Boolean(event.ctrlKey || event.metaKey)}),
  1789. );
  1790. padSection.append(row);
  1791. }
  1792. dom["detail-content"].append(element("h3", "section-title", "电阻焊盘"), padSection);
  1793. if (pad?.net || nets[0]) {
  1794. const net = pad?.net || nets[0];
  1795. const netMatches = sameNetMembers(state.data, net);
  1796. if (netMatches.length) {
  1797. dom["detail-content"].append(element("h3", "section-title", `同网成员(${net})`));
  1798. const list = element("div", "pin-list");
  1799. for (const item of netMatches.slice(0, 32)) {
  1800. const row = element("button", "pin-row");
  1801. row.type = "button";
  1802. const kindLabel = item.kind === "resistor_pad" ? "电阻" : "座子";
  1803. row.append(
  1804. element("span", "pin-number", item.pinNumber),
  1805. element("span", "pin-primary", `${item.reference}.${item.pinNumber}`),
  1806. element("span", "pin-direction", kindLabel),
  1807. );
  1808. row.addEventListener("click", (event) => {
  1809. const ctrlMulti = Boolean(event.ctrlKey || event.metaKey);
  1810. if (item.kind === "resistor_pad" && item.resistor) {
  1811. state.categories.add("R");
  1812. const checkbox = dom["category-filters"].querySelector('input[value="R"]');
  1813. if (checkbox) checkbox.checked = true;
  1814. selectResistor(item.resistor, item.pin, true, {highlightAllSame: ctrlMulti});
  1815. focusOnTouchpoint(item.resistor);
  1816. } else if (item.touchpoint) {
  1817. state.categories.add(item.touchpoint.category);
  1818. selectTouchpoint(item.touchpoint, item.pin, true, {highlightAllSame: ctrlMulti});
  1819. focusOnTouchpoint(item.touchpoint);
  1820. }
  1821. });
  1822. list.append(row);
  1823. }
  1824. dom["detail-content"].append(list);
  1825. }
  1826. }
  1827. const conflicts = (state.data.evidence_conflicts ?? []).filter(
  1828. (item) => item.subject_reference === resistor.reference,
  1829. );
  1830. if (conflicts.length) {
  1831. const section = element("section", "evidence-conflict");
  1832. section.append(element("h3", "section-title", "证据与冲突"));
  1833. for (const conflict of conflicts) {
  1834. const note = element("div", "risk-note evidence-conflict-note");
  1835. note.append(
  1836. element("strong", "", `${conflict.status || "unresolved"} · ${conflict.kind || "cross_evidence"}`),
  1837. document.createTextNode(` — ${conflict.summary || "存在未解决的交叉证据冲突"}`),
  1838. );
  1839. section.append(note);
  1840. if (Array.isArray(conflict.pcb_pads) && conflict.pcb_pads.length) {
  1841. section.append(element("div", "info-note", `PCB pad facts:${conflict.pcb_pads.map((item) => `${item.number}:${item.net || "null"}`).join(" · ")}`));
  1842. }
  1843. if (Array.isArray(conflict.claims)) {
  1844. const list = element("ul", "source-list");
  1845. for (const claim of conflict.claims) {
  1846. const line = element("li", "");
  1847. line.textContent = `${claim.source || "claim"} (${claim.source_id || "?"}): ${claim.note || claim.claimed_context || JSON.stringify(claim.claimed_nets || [])}`;
  1848. list.append(line);
  1849. }
  1850. section.append(list);
  1851. }
  1852. }
  1853. dom["detail-content"].append(section);
  1854. }
  1855. }
  1856. function renderPinDetail(touchpoint, pin) {
  1857. const wrapper = element("section", "pin-detail");
  1858. const header = element("div", "pin-detail-header");
  1859. header.append(
  1860. element("h3", "", `${touchpoint.reference}.${pin.number || "机械孔"}`),
  1861. element("span", `evidence-tag${pin.evidence_tier === "cross_verified" ? " verified" : ""}`, evidenceLabel(pin.evidence_tier)),
  1862. );
  1863. wrapper.append(header);
  1864. const logical = resolveLogicalPin(touchpoint, pin, state.boardVersion);
  1865. const logicalBox = element("div", "logical-pin-summary-box");
  1866. logicalBox.append(
  1867. element("div", "logical-pin-box-title", "FPGA / MCU 逻辑管脚与引脚定义"),
  1868. element("div", logicalBadgeClass(logical), logical.displayBadge),
  1869. element("div", "logical-pin-role", `外设角色:${logical.peripheralRole}`),
  1870. element("div", "logical-pin-def", `电气定义:${logical.pinDefinition}`),
  1871. );
  1872. wrapper.append(logicalBox);
  1873. const programmingGuide = renderProgrammingGuide(pin);
  1874. if (programmingGuide) wrapper.append(programmingGuide);
  1875. wrapper.append(element("h4", "section-title", "物理与电气事实"));
  1876. const facts = element("div", "detail-facts");
  1877. const programmableTarget = pin.fpga
  1878. ? "FPGA U3"
  1879. : pin.mcu
  1880. ? `${pin.mcu.family} ${pin.mcu.device}`
  1881. : logical.chip;
  1882. const devicePin = pin.fpga?.ball
  1883. ? `FPGA U3.${pin.fpga.ball} (${logical.logicalSignal})`
  1884. : pin.mcu
  1885. ? `${pin.mcu.device}.${pin.mcu.pin} (${pin.mcu.signal})`
  1886. : logical.physicalPin;
  1887. const boardPosition = pin.board_order == null
  1888. ? "不属于外部接触针"
  1889. : `第 ${pin.board_order} 位 · 第 ${pin.row} 行 / 第 ${pin.column} 列`;
  1890. facts.append(
  1891. fact("焊盘角色", padRoleLabel(pin.pad_role)),
  1892. fact("板正面位置", boardPosition),
  1893. fact("原始网络", pin.net || "无命名网络"),
  1894. fact("逻辑管脚", logical.logicalSignal),
  1895. fact("逻辑方向", directionLabel(pin.direction)),
  1896. fact("外部电平", pin.external_level || "未知"),
  1897. fact("可编程目标", programmableTarget),
  1898. fact("物理封装引脚", devicePin),
  1899. fact("I/O 标准", pin.fpga?.io_standard || "未知"),
  1900. fact("板上 pull", pin.board_pull || "未注明"),
  1901. fact("有效电平", activeLevelLabel(pin.active_level)),
  1902. fact("极性", pin.polarity && pin.polarity !== "unknown" ? pin.polarity : "未注明"),
  1903. );
  1904. wrapper.append(facts);
  1905. if (pin.external_components?.length) {
  1906. wrapper.append(element("h4", "section-title", "相关板上器件"));
  1907. const components = element("ul", "component-list");
  1908. for (const item of pin.external_components) components.append(element("li", "", item));
  1909. wrapper.append(components);
  1910. }
  1911. if (pin.path?.length) {
  1912. wrapper.append(element("h4", "section-title", pin.evidence_tier === "cross_verified" ? "已交叉核对的板内路径" : "路径注释(含推断,不能据此确认导通)"));
  1913. const path = element("ol", "path-list");
  1914. for (const item of pin.path) path.append(element("li", "", item));
  1915. wrapper.append(path);
  1916. }
  1917. const related = Array.isArray(pin.related_resistors) ? pin.related_resistors : [];
  1918. if (related.length) {
  1919. wrapper.append(element("h4", "section-title", "关联电阻(path / external_components)"));
  1920. const list = element("div", "pin-list");
  1921. for (const link of related) {
  1922. const resistor = (state.data.resistors ?? []).find((item) => item.reference === link.resistor_reference);
  1923. const row = element("button", "pin-row");
  1924. row.type = "button";
  1925. const label = link.pad_number
  1926. ? `${link.resistor_reference}.${link.pad_number}`
  1927. : link.resistor_reference;
  1928. const netLine = [
  1929. link.claimed_net != null ? `claimed=${link.claimed_net}` : "claimed=∅",
  1930. link.pcb_net != null ? `pcb=${link.pcb_net}` : "pcb=∅",
  1931. link.status,
  1932. ].join(" · ");
  1933. row.append(
  1934. element("span", "pin-number", "R"),
  1935. element("span", "pin-primary", `${label} · ${netLine}`),
  1936. element("span", "pin-direction", link.source_field || "path"),
  1937. );
  1938. if (link.status === "net_conflict") {
  1939. row.classList.add("is-conflict");
  1940. }
  1941. if ((link.status === "resolved" || link.status === "net_conflict") && resistor) {
  1942. row.addEventListener("click", (event) => {
  1943. state.categories.add("R");
  1944. const checkbox = dom["category-filters"].querySelector('input[value="R"]');
  1945. if (checkbox) checkbox.checked = true;
  1946. const pad = link.pad_number
  1947. ? (resistor.pads ?? []).find((item) => String(item.number) === String(link.pad_number))
  1948. : null;
  1949. selectResistor(resistor, pad || null, true, {highlightAllSame: Boolean(event.ctrlKey || event.metaKey)});
  1950. focusOnTouchpoint(resistor);
  1951. });
  1952. } else {
  1953. row.disabled = true;
  1954. row.classList.add("is-conflict");
  1955. }
  1956. list.append(row);
  1957. }
  1958. wrapper.append(list);
  1959. } else {
  1960. try {
  1961. const pathResistors = extractPathResistors(state.data, pin.path, pin.external_components);
  1962. if (pathResistors.length) {
  1963. wrapper.append(element("h4", "section-title", "路径电阻(可跳转)"));
  1964. const list = element("div", "pin-list");
  1965. for (const resistor of pathResistors) {
  1966. const nets = (resistor.pads ?? []).filter((item) => item.net).map((item) => item.net);
  1967. const row = element("button", "pin-row");
  1968. row.type = "button";
  1969. row.append(
  1970. element("span", "pin-number", "R"),
  1971. element("span", "pin-primary", `${resistor.reference} · ${resistor.component_value || "未标注"} · ${nets.join(" ↔ ") || "无网络"}`),
  1972. element("span", "pin-direction", "跳转"),
  1973. );
  1974. row.addEventListener("click", (event) => {
  1975. state.categories.add("R");
  1976. const checkbox = dom["category-filters"].querySelector('input[value="R"]');
  1977. if (checkbox) checkbox.checked = true;
  1978. selectResistor(resistor, null, true, {highlightAllSame: Boolean(event.ctrlKey || event.metaKey)});
  1979. focusOnTouchpoint(resistor);
  1980. });
  1981. list.append(row);
  1982. }
  1983. wrapper.append(list);
  1984. }
  1985. } catch (error) {
  1986. wrapper.append(element("div", "risk-note", String(error.message || error)));
  1987. }
  1988. }
  1989. wrapper.append(element("h4", "section-title", "证据来源"));
  1990. const sources = element("ul", "source-list");
  1991. for (const source of pin.evidence_sources ?? []) sources.append(element("li", "", source));
  1992. wrapper.append(sources);
  1993. if (pin.net) {
  1994. const netMatches = sameNetMembers(state.data, pin.net);
  1995. const noteRow = element("div", "info-note net-highlight-note");
  1996. const statusText = state.highlightAllSame
  1997. ? `同网成员 ${netMatches.length} 个(座子+电阻),已按 Ctrl 全板同步高亮所有同功能/同网点位。`
  1998. : `同网成员 ${netMatches.length} 个(座子+电阻),当前仅标注本引脚(按住 Ctrl 点击可全板标出)。`;
  1999. const toggleBtn = element(
  2000. "button",
  2001. `net-highlight-toggle-btn${state.highlightAllSame ? " is-active" : ""}`,
  2002. state.highlightAllSame ? "仅标当前点位" : "全板标出同网点位 (Ctrl+点击)",
  2003. );
  2004. toggleBtn.type = "button";
  2005. toggleBtn.addEventListener("click", () => {
  2006. state.highlightAllSame = !state.highlightAllSame;
  2007. updateSelectionVisuals();
  2008. renderDetail();
  2009. });
  2010. noteRow.append(element("span", "", statusText), toggleBtn);
  2011. wrapper.append(noteRow);
  2012. }
  2013. const blockers = pin.recommendation?.reasons ?? [];
  2014. if (!pin.recommendation?.eligible) {
  2015. wrapper.append(element("div", "risk-note", `不可用于自动候选或 ADC:${blockers.join("、") || "证据条件不足"}。`));
  2016. }
  2017. const dedicatedConfigurationPin = String(pin.function_category || "").startsWith("jtag_");
  2018. if (!pin.fpga || dedicatedConfigurationPin) {
  2019. wrapper.append(
  2020. element(
  2021. "div",
  2022. "info-note",
  2023. dedicatedConfigurationPin
  2024. ? "专用配置脚不使用用户 ADC 约束"
  2025. : "此针不对应可生成 ADC 的 FPGA 用户 I/O。",
  2026. ),
  2027. );
  2028. return wrapper;
  2029. }
  2030. wrapper.append(element("h4", "section-title", "ADC 片段"));
  2031. const adc = element("div", "adc-controls");
  2032. const input = element("input");
  2033. input.type = "text";
  2034. input.placeholder = "RTL 端口名";
  2035. input.setAttribute("aria-label", "RTL 端口名");
  2036. input.disabled = !pin.recommendation?.eligible || state.runtime.adcCopyEnabled !== true;
  2037. const copy = element("button", "copy-button", "⧉");
  2038. copy.type = "button";
  2039. copy.title = "复制 ADC 片段";
  2040. copy.setAttribute("aria-label", "复制 ADC 片段");
  2041. copy.disabled = input.disabled;
  2042. const status = element("div", "copy-status");
  2043. copy.addEventListener("click", async () => {
  2044. try {
  2045. const snippet = generateAdcSnippet(pin, input.value.trim(), state.runtime);
  2046. await copyText(snippet);
  2047. status.textContent = "ADC 片段已复制";
  2048. } catch (error) {
  2049. status.textContent = error instanceof Error ? error.message : String(error);
  2050. }
  2051. });
  2052. adc.append(input, copy);
  2053. wrapper.append(adc, status, element("div", "risk-note", "这里只证明物理可用性,仍需检查当前工程约束冲突。"));
  2054. return wrapper;
  2055. }
  2056. function appendGuidanceList(container, title, items, className = "guidance-list") {
  2057. if (!Array.isArray(items) || !items.length) return;
  2058. container.append(element("h4", "section-title", title));
  2059. const list = element("ul", className);
  2060. for (const item of items) list.append(element("li", "", item));
  2061. container.append(list);
  2062. }
  2063. function renderProgrammingGuide(pin) {
  2064. const programming = pin.programming;
  2065. if (!programming) return null;
  2066. const section = element("section", `programming-guide status-${programming.status || "unknown"}`);
  2067. const heading = element("div", "programming-guide-heading");
  2068. heading.append(
  2069. element("h4", "section-title programming-title", "编程结论"),
  2070. element(
  2071. "span",
  2072. `evidence-tag${programming.evidence_tier === "cross_verified" ? " verified" : ""}`,
  2073. evidenceLabel(programming.evidence_tier),
  2074. ),
  2075. );
  2076. section.append(heading, element("p", "programming-conclusion", programming.conclusion));
  2077. section.append(element("h4", "section-title", "板内网络解释"));
  2078. section.append(element("p", "programming-copy", programming.network_explanation));
  2079. appendGuidanceList(section, "怎么接", programming.connection_guidance);
  2080. section.append(
  2081. element(
  2082. "h4",
  2083. "section-title",
  2084. programming.status === "verified_mcu" ? "MCU 固件用法" : "HDL 用法",
  2085. ),
  2086. );
  2087. section.append(element("p", "programming-copy", programming.hdl_guidance));
  2088. appendGuidanceList(section, "约束要求", programming.constraints, "guidance-list constraint-list");
  2089. appendGuidanceList(section, "风险与未知", programming.risks, "guidance-list risk-list");
  2090. return section;
  2091. }
  2092. async function copyText(value) {
  2093. if (navigator.clipboard?.writeText) return navigator.clipboard.writeText(value);
  2094. const textarea = element("textarea");
  2095. textarea.value = value;
  2096. textarea.style.position = "fixed";
  2097. textarea.style.opacity = "0";
  2098. document.body.append(textarea);
  2099. textarea.select();
  2100. document.execCommand("copy");
  2101. textarea.remove();
  2102. }
  2103. function renderCandidates() {
  2104. if (!state.data) return;
  2105. dom["candidate-list"].replaceChildren();
  2106. if (state.runtime.recommendationsEnabled !== true) {
  2107. dom["candidate-list"].append(element("div", "risk-note", "源文件状态不是当前值,选脚推荐已关闭。"));
  2108. return;
  2109. }
  2110. const capability = dom["capability-select"].value;
  2111. const candidates = findCandidates(state.data, capability);
  2112. if (!candidates.length) {
  2113. const empty = element("div", "empty-panel");
  2114. empty.append(
  2115. element("strong", "", "没有满足全部证据条件的候选"),
  2116. element("span", "empty-stats", "未知、推断、保留、电源、地、机械焊盘和固定负载冲突均已排除"),
  2117. );
  2118. dom["candidate-list"].append(empty);
  2119. return;
  2120. }
  2121. for (const candidate of candidates) {
  2122. const row = element("button", "candidate-row");
  2123. row.type = "button";
  2124. row.append(
  2125. element("span", "candidate-key", `${candidate.reference}.${candidate.pin.number} · ${candidate.pin.fpga.ball}`),
  2126. element("span", "candidate-reason", candidate.reason),
  2127. element("span", "candidate-warning", candidate.warning),
  2128. );
  2129. row.addEventListener("click", (event) => {
  2130. switchTab("detail");
  2131. selectTouchpoint(candidate.touchpoint, candidate.pin, true, {
  2132. highlightAllSame: Boolean(event.ctrlKey || event.metaKey),
  2133. });
  2134. focusOnTouchpoint(candidate.touchpoint);
  2135. });
  2136. dom["candidate-list"].append(row);
  2137. }
  2138. }
  2139. function renderPeripheralPanel() {
  2140. const container = dom["peripheral-content"];
  2141. if (!container || !state.data) return;
  2142. container.replaceChildren();
  2143. const catalog = filterPeripheralCatalog(state.data, state.boardVersion, {
  2144. category: state.peripheralCategory,
  2145. usage: state.peripheralUsage,
  2146. query: state.peripheralQuery,
  2147. });
  2148. const isFiltered = state.peripheralCategory !== "ALL" || state.peripheralUsage !== "all" || Boolean(state.peripheralQuery.trim());
  2149. state.peripheralHighlightedRefs = (isFiltered && state.highlightAllSame)
  2150. ? new Set(catalog.filteredItems.map((item) => item.reference))
  2151. : new Set();
  2152. if (state.activeTab === "peripheral") {
  2153. updateSelectionVisuals();
  2154. }
  2155. const wrapper = element("div", "peripheral-panel");
  2156. // 1. Header & Sync Status Bar
  2157. const syncBox = element("div", "peripheral-sync-box");
  2158. const syncHeader = element("div", "peripheral-sync-header");
  2159. syncHeader.append(
  2160. element("strong", "", `电气外设与 FPGA/MCU 接线总表 (${state.data.board?.name || state.boardVersion})`),
  2161. element("span", "evidence-tag verified", `已用 ${catalog.usedCount} · 空余插座 ${catalog.spareCount}`),
  2162. );
  2163. const syncNote = element(
  2164. "div",
  2165. "peripheral-sync-note",
  2166. "全板电气接线同步入口:python3 tools/board-viewer/board_viewer.py sync-wiring(只同步已有生成包的接线说明;源文件变化后请先重新生成并校验,不能代替原生网表核对)。",
  2167. );
  2168. syncBox.append(syncHeader, syncNote);
  2169. wrapper.append(syncBox);
  2170. // 2. Quick-Jump Chips (PTC1, JTAG, HOST TTL, FAN, 空余插座, etc.)
  2171. if (catalog.quickChips?.length) {
  2172. const chipSection = element("div", "peripheral-chip-section");
  2173. chipSection.append(element("div", "peripheral-sub-label", "常用外设一键索引:"));
  2174. const chipRow = element("div", "peripheral-quick-chips");
  2175. for (const chip of catalog.quickChips) {
  2176. const isChipActive =
  2177. state.peripheralCategory === (chip.category || "ALL") &&
  2178. state.peripheralUsage === (chip.usage || "all") &&
  2179. state.peripheralQuery === (chip.query || "");
  2180. const btn = element("button", `peripheral-chip${isChipActive ? " is-active" : ""}`, chip.label);
  2181. btn.type = "button";
  2182. btn.addEventListener("click", (event) => {
  2183. const ctrlMulti = Boolean(event.ctrlKey || event.metaKey);
  2184. state.highlightAllSame = ctrlMulti;
  2185. state.peripheralCategory = chip.category || "ALL";
  2186. state.peripheralUsage = chip.usage || "all";
  2187. state.peripheralQuery = chip.query || "";
  2188. renderPeripheralPanel();
  2189. const updated = filterPeripheralCatalog(state.data, state.boardVersion, {
  2190. category: state.peripheralCategory,
  2191. usage: state.peripheralUsage,
  2192. query: state.peripheralQuery,
  2193. });
  2194. if (updated.filteredItems.length === 1) {
  2195. const item = updated.filteredItems[0];
  2196. const matchedPin = item.matchedPinNumbers?.length === 1
  2197. ? item.touchpoint.pins.find((p) => String(p.number) === String(item.matchedPinNumbers[0]))
  2198. : null;
  2199. selectTouchpoint(item.touchpoint, matchedPin || null, false, {highlightAllSame: ctrlMulti});
  2200. focusOnTouchpoint(item.touchpoint);
  2201. }
  2202. });
  2203. chipRow.append(btn);
  2204. }
  2205. if (isFiltered) {
  2206. const clearBtn = element("button", "peripheral-chip is-reset", "✕ 重置筛选");
  2207. clearBtn.type = "button";
  2208. clearBtn.addEventListener("click", () => {
  2209. state.highlightAllSame = false;
  2210. state.peripheralCategory = "ALL";
  2211. state.peripheralUsage = "all";
  2212. state.peripheralQuery = "";
  2213. renderPeripheralPanel();
  2214. });
  2215. chipRow.append(clearBtn);
  2216. }
  2217. chipSection.append(chipRow);
  2218. wrapper.append(chipSection);
  2219. }
  2220. // 3. Search input + Usage filter (全部 / 已用外设 / 空余插座)
  2221. const filterBar = element("div", "peripheral-filter-bar");
  2222. const searchInput = element("input", "peripheral-search-input");
  2223. searchInput.type = "search";
  2224. searchInput.placeholder = "筛选外设 / 插座 / 管脚 (如 PTC1, JTAG, CON140, FAN, M1, LS1, T11)...";
  2225. searchInput.value = state.peripheralQuery;
  2226. searchInput.setAttribute("aria-label", "筛选外设或逻辑管脚");
  2227. searchInput.addEventListener("input", (e) => {
  2228. state.peripheralQuery = e.target.value;
  2229. const caret = searchInput.selectionStart;
  2230. renderPeripheralPanel();
  2231. const nextInput = dom["peripheral-content"].querySelector(".peripheral-search-input");
  2232. if (nextInput instanceof HTMLInputElement) {
  2233. nextInput.focus();
  2234. if (caret != null) nextInput.setSelectionRange(caret, caret);
  2235. }
  2236. });
  2237. const usageGroup = element("div", "peripheral-usage-tabs");
  2238. const usageOptions = [
  2239. {id: "all", label: `全部 (${catalog.items.length})`},
  2240. {id: "used", label: `已用外设 (${catalog.usedCount})`},
  2241. {id: "spare", label: `空余插座 (${catalog.spareCount})`},
  2242. ];
  2243. for (const opt of usageOptions) {
  2244. const uBtn = element("button", `peripheral-usage-btn${state.peripheralUsage === opt.id ? " is-active" : ""}`, opt.label);
  2245. uBtn.type = "button";
  2246. uBtn.addEventListener("click", (event) => {
  2247. state.highlightAllSame = Boolean(event.ctrlKey || event.metaKey);
  2248. state.peripheralUsage = opt.id;
  2249. renderPeripheralPanel();
  2250. });
  2251. usageGroup.append(uBtn);
  2252. }
  2253. filterBar.append(searchInput, usageGroup);
  2254. wrapper.append(filterBar);
  2255. // 4. Category pills (PTC, FAN, UART, JTAG, MOTOR, LIMIT, TEMP, SSR, GPIO, MCU, POWER)
  2256. const catGrid = element("div", "peripheral-category-pills");
  2257. for (const catKey of PERIPHERAL_TYPE_ORDER) {
  2258. const count = catalog.categoryCounts[catKey] ?? 0;
  2259. if (catKey !== "ALL" && count === 0) continue;
  2260. const labelText = `${PERIPHERAL_TYPE_LABELS[catKey] || catKey} (${count})`;
  2261. const cBtn = element("button", `peripheral-cat-btn${state.peripheralCategory === catKey ? " is-active" : ""}`, labelText);
  2262. cBtn.type = "button";
  2263. cBtn.dataset.category = catKey;
  2264. cBtn.addEventListener("click", (event) => {
  2265. state.highlightAllSame = Boolean(event.ctrlKey || event.metaKey);
  2266. state.peripheralCategory = catKey;
  2267. renderPeripheralPanel();
  2268. });
  2269. catGrid.append(cBtn);
  2270. }
  2271. wrapper.append(catGrid);
  2272. // 5. Filtered Result Count Summary
  2273. const resultHeader = element("div", "peripheral-result-header");
  2274. resultHeader.append(
  2275. element("span", "", `命中 ${catalog.filteredItems.length} 个插座/接触点`),
  2276. element("span", "mono", "点击仅标单点 · 按住 Ctrl 点击全板标出同功能点位"),
  2277. );
  2278. wrapper.append(resultHeader);
  2279. // 6. Connector & Logical Pin Cards
  2280. if (!catalog.filteredItems.length) {
  2281. const empty = element("div", "empty-panel");
  2282. empty.append(
  2283. element("strong", "", "当前筛选条件下无匹配外设或插座"),
  2284. element("span", "empty-stats", "请点击「重置筛选」或切换外设分类 / 空余插座条件"),
  2285. );
  2286. wrapper.append(empty);
  2287. container.append(wrapper);
  2288. return;
  2289. }
  2290. const cardList = element("div", "peripheral-card-list");
  2291. for (const item of catalog.filteredItems) {
  2292. const isSelectedCard = state.selectedTouchpoint?.reference === item.reference;
  2293. const card = element("article", `peripheral-card${isSelectedCard ? " is-selected" : ""}${item.isSpareConnector ? " is-spare" : ""}`);
  2294. card.dataset.reference = item.reference;
  2295. const cardHead = element("div", "peripheral-card-head");
  2296. const titleGroup = element("div", "peripheral-card-title-group");
  2297. const refBtn = element("button", "peripheral-ref-btn", item.reference);
  2298. refBtn.type = "button";
  2299. refBtn.title = "在电路板上定位该插座(按住 Ctrl 点击全板标出同类)";
  2300. refBtn.addEventListener("click", (event) => {
  2301. const ctrlMulti = Boolean(event.ctrlKey || event.metaKey);
  2302. state.categories.add(item.touchpoint.category);
  2303. const checkbox = dom["category-filters"]?.querySelector(`input[value="${item.touchpoint.category}"]`);
  2304. if (checkbox) checkbox.checked = true;
  2305. selectTouchpoint(item.touchpoint, null, false, {highlightAllSame: ctrlMulti});
  2306. focusOnTouchpoint(item.touchpoint);
  2307. renderPeripheralPanel();
  2308. });
  2309. const catBadge = element("span", "peripheral-type-badge", item.peripheralLabel);
  2310. const statusBadge = element(
  2311. "span",
  2312. `peripheral-status-badge ${item.isUsed ? "status-used" : (item.isSpareConnector ? "status-spare" : "status-board")}`,
  2313. item.isUsed ? "已用外设" : (item.isSpareConnector ? "空余插座" : "板级节点"),
  2314. );
  2315. titleGroup.append(refBtn, catBadge, statusBadge);
  2316. const detailJumpBtn = element("button", "peripheral-jump-btn", "详情 ↗");
  2317. detailJumpBtn.type = "button";
  2318. detailJumpBtn.title = "打开该插座完整物理与选脚详情";
  2319. detailJumpBtn.addEventListener("click", (event) => {
  2320. const ctrlMulti = Boolean(event.ctrlKey || event.metaKey);
  2321. state.categories.add(item.touchpoint.category);
  2322. const checkbox = dom["category-filters"]?.querySelector(`input[value="${item.touchpoint.category}"]`);
  2323. if (checkbox) checkbox.checked = true;
  2324. selectTouchpoint(item.touchpoint, null, true, {highlightAllSame: ctrlMulti});
  2325. focusOnTouchpoint(item.touchpoint);
  2326. switchTab("detail");
  2327. });
  2328. cardHead.append(titleGroup, detailJumpBtn);
  2329. card.append(cardHead);
  2330. card.append(element("div", "peripheral-card-summary", item.roleTitle));
  2331. // Pin table with explicit FPGA / MCU logical pin for every pin
  2332. const pinTable = element("div", "peripheral-pin-table");
  2333. for (const rp of item.pins) {
  2334. const isPinMatched = item.matchedPinNumbers?.includes(rp.pinNumber);
  2335. const isPinSelected = isSelectedCard && state.selectedPin?.id === rp.pin.id;
  2336. const pinRow = element(
  2337. "button",
  2338. `peripheral-pin-row${isPinMatched ? " is-query-match" : ""}${isPinSelected ? " is-selected" : ""}`,
  2339. );
  2340. pinRow.type = "button";
  2341. pinRow.dataset.pin = rp.pinNumber;
  2342. const pinNumCol = element("span", "peripheral-pin-num", `Pin ${rp.pinNumber}`);
  2343. const pinBodyCol = element("span", "peripheral-pin-body");
  2344. const topLine = element("span", "peripheral-pin-top");
  2345. topLine.append(
  2346. element("span", "peripheral-pin-role", rp.logical.peripheralRole),
  2347. element("span", logicalBadgeClass(rp.logical), rp.logical.displayBadge),
  2348. );
  2349. const defLine = element(
  2350. "span",
  2351. "peripheral-pin-def",
  2352. `${rp.logical.pinDefinition} · 网络: ${rp.net || "无"} · 电平: ${rp.level || "未知"}`,
  2353. );
  2354. pinBodyCol.append(topLine, defLine);
  2355. pinRow.append(pinNumCol, pinBodyCol);
  2356. pinRow.addEventListener("click", (event) => {
  2357. const ctrlMulti = Boolean(event.ctrlKey || event.metaKey);
  2358. state.categories.add(item.touchpoint.category);
  2359. const checkbox = dom["category-filters"]?.querySelector(`input[value="${item.touchpoint.category}"]`);
  2360. if (checkbox) checkbox.checked = true;
  2361. selectTouchpoint(item.touchpoint, rp.pin, false, {highlightAllSame: ctrlMulti});
  2362. focusOnTouchpoint(item.touchpoint);
  2363. renderPeripheralPanel();
  2364. });
  2365. pinTable.append(pinRow);
  2366. }
  2367. card.append(pinTable);
  2368. cardList.append(card);
  2369. }
  2370. wrapper.append(cardList);
  2371. container.append(wrapper);
  2372. }
  2373. async function jumpToBoardTarget(pill, event = null) {
  2374. if (!pill) return;
  2375. const ctrlMulti = Boolean(event?.ctrlKey || event?.metaKey);
  2376. const targetRef = pill.ref || pill.query;
  2377. if (!targetRef) return;
  2378. if (pill.version && pill.version !== state.boardVersion) {
  2379. const url = new URL(window.location.href);
  2380. url.searchParams.set("version", pill.version);
  2381. window.history.replaceState({}, "", url.toString());
  2382. await loadApplication(pill.version);
  2383. }
  2384. if (!state.data) return;
  2385. const refUpper = String(targetRef).trim().toUpperCase();
  2386. const touchpoint = (state.data.touchpoints ?? []).find(
  2387. (tp) => String(tp.reference).toUpperCase() === refUpper,
  2388. );
  2389. if (touchpoint) {
  2390. state.categories.add(touchpoint.category);
  2391. const checkbox = dom["category-filters"]?.querySelector(`input[value="${touchpoint.category}"]`);
  2392. if (checkbox) checkbox.checked = true;
  2393. const pinObj = pill.pin != null
  2394. ? (touchpoint.pins ?? []).find((p) => String(p.number) === String(pill.pin))
  2395. : null;
  2396. selectTouchpoint(touchpoint, pinObj || null, false, {highlightAllSame: ctrlMulti});
  2397. focusOnTouchpoint(touchpoint);
  2398. return;
  2399. }
  2400. const resistor = (state.data.resistors ?? []).find(
  2401. (r) => String(r.reference).toUpperCase() === refUpper,
  2402. );
  2403. if (resistor) {
  2404. state.categories.add("R");
  2405. const checkbox = dom["category-filters"]?.querySelector('input[value="R"]');
  2406. if (checkbox) checkbox.checked = true;
  2407. const padObj = pill.pin != null
  2408. ? (resistor.pads ?? []).find((p) => String(p.number) === String(pill.pin))
  2409. : null;
  2410. selectResistor(resistor, padObj || null, false, {highlightAllSame: ctrlMulti});
  2411. focusOnTouchpoint(resistor);
  2412. return;
  2413. }
  2414. // Fallback to search box if query is a ball or net (e.g. N8)
  2415. if (dom["board-search"]) {
  2416. dom["board-search"].value = targetRef;
  2417. renderSearchResults(targetRef);
  2418. }
  2419. }
  2420. function navigateCpldTopic(domainId, groupId, topicId) {
  2421. if (domainId) state.cpldDomainId = domainId;
  2422. if (groupId) state.cpldGroupId = groupId;
  2423. if (topicId) state.cpldTopicId = topicId;
  2424. renderCpldArchPanel();
  2425. }
  2426. function flattenAllCpldTopics(ver = state.boardVersion || "v2_0") {
  2427. const list = [];
  2428. for (const domain of CPLD_MENU_TREE) {
  2429. for (const group of domain.children || []) {
  2430. for (const topic of group.topics || []) {
  2431. const detail = getCpldTopicDetail(topic.id, ver);
  2432. list.push({
  2433. domainId: domain.id,
  2434. domainLabel: domain.title,
  2435. domainIcon: domain.icon,
  2436. groupId: group.id,
  2437. groupLabel: group.title,
  2438. groupBadge: group.badge,
  2439. topicId: topic.id,
  2440. topicLabel: topic.title,
  2441. module: detail.tag || detail.file || group.badge,
  2442. file: detail.file || "",
  2443. });
  2444. }
  2445. }
  2446. }
  2447. return list;
  2448. }
  2449. function renderCpldArchPanel() {
  2450. const container = dom["cpld-arch-content"];
  2451. if (!container) return;
  2452. container.replaceChildren();
  2453. const ver = state.boardVersion || "v2_0";
  2454. const currentBoardInfo = BOARD_VERSION_COMM_MATRIX[ver] || BOARD_VERSION_COMM_MATRIX.v2_0;
  2455. // Ensure active domain/group/topic IDs are valid and synchronized
  2456. const activeDomain = CPLD_MENU_TREE.find((d) => d.id === state.cpldDomainId) || CPLD_MENU_TREE[0];
  2457. const activeGroup = (activeDomain.children || []).find((g) => g.id === state.cpldGroupId) || activeDomain.children[0];
  2458. const activeTopic = (activeGroup.topics || []).find((t) => t.id === state.cpldTopicId) || activeGroup.topics[0];
  2459. state.cpldDomainId = activeDomain.id;
  2460. state.cpldGroupId = activeGroup.id;
  2461. state.cpldTopicId = activeTopic.id;
  2462. const wrapper = element("div", "cpld-arch-panel");
  2463. // 1. Hero Chip & Current Board Version Banner
  2464. const heroCard = element("div", "cpld-hero-card");
  2465. const heroTop = element("div", "cpld-hero-top");
  2466. const heroTitleWrap = element("div", "cpld-hero-title-wrap");
  2467. heroTitleWrap.append(
  2468. element(
  2469. "div",
  2470. "cpld-chip-pill",
  2471. `${CPLD_CHIP_SPEC.vendor} ${CPLD_CHIP_SPEC.partNumber} (${CPLD_CHIP_SPEC.reference}) · 25MHz 单时钟域 · ${CPLD_CHIP_SPEC.lutCapacity} LUT4`,
  2472. ),
  2473. element("h2", "cpld-hero-title", `${currentBoardInfo.badge} — 芯片与硬件通信总览`),
  2474. );
  2475. const topModuleBadge = element("span", "cpld-top-module-badge", currentBoardInfo.topModule);
  2476. heroTop.append(heroTitleWrap, topModuleBadge);
  2477. const heroGrid = element("div", "cpld-hero-grid");
  2478. const quickSpecs = [
  2479. {k: "Host TTL 串口", v: `${currentBoardInfo.hostTtl.connector} · ${currentBoardInfo.hostTtl.txPin}`},
  2480. {k: "Host RS232 串口", v: `${currentBoardInfo.hostRs232.connector} · ${currentBoardInfo.hostRs232.txPin}`},
  2481. {k: "BMC 测温串口", v: `${currentBoardInfo.bmcUart.connector} · ${currentBoardInfo.bmcUart.baud}`},
  2482. {k: "500Hz 热控 / 电机", v: `${currentBoardInfo.thermalPwm.freq} · ${currentBoardInfo.motorSpec}`},
  2483. ];
  2484. for (const item of quickSpecs) {
  2485. const cell = element("div", "cpld-hero-cell");
  2486. cell.append(
  2487. element("span", "cpld-hero-cell-k", item.k),
  2488. element("span", "cpld-hero-cell-v", item.v),
  2489. );
  2490. heroGrid.append(cell);
  2491. }
  2492. heroCard.append(heroTop, heroGrid);
  2493. wrapper.append(heroCard);
  2494. // 2. Interactive On-Chip Datapath Topology Strip (点击任意芯片模块直达对应三级架构详情)
  2495. const topologyBox = element("div", "cpld-topology-box");
  2496. const topologyHead = element("div", "cpld-topology-head");
  2497. topologyHead.append(
  2498. element("span", "cpld-topology-title", "⚡ 芯片内部执行流水线与片上总线拓扑 (点击模块直达源码解析)"),
  2499. element("span", "cpld-topology-sub", "25MHz 单时钟域 · Valid/Ready 握手 · BRAM/双 Bank"),
  2500. );
  2501. const topologyFlow = element("div", "cpld-topology-flow");
  2502. const pipelineNodes = [
  2503. {label: "Host RS232/TTL", sub: "源锁定 + 双发广播", domain: "protocol_mcu", group: "mcu_host_topo", topic: "mcu_dual_uart_arb", tag: "IO Pads"},
  2504. {label: "frame_rx + CRC16", sub: "u_req_ram (128×8 BRAM)", domain: "chip_exec", group: "onchip_memory", topic: "mem_req_reply_bram", tag: "BRAM"},
  2505. {label: "transaction_core", sub: "SET_ACCEPT + 30s 看门狗", domain: "protocol_mcu", group: "transaction_fsm", topic: "fsm_atomic_set", tag: "FSM"},
  2506. {label: "双 Bank + 500Hz PWM", sub: "PTC / 风扇 / 12轴步进", domain: "chip_exec", group: "onchip_memory", topic: ver === "v1_2" ? "mem_motor_queue" : "mem_duty_double_bank", tag: "Actuator"},
  2507. {label: "CT7428 + BMC 采样", sub: "4深 FIFO → temp_ram", domain: "chip_exec", group: "onchip_memory", topic: "mem_temp_ram_arb", tag: "I2C/UART"},
  2508. {label: "reply + unified_tx", sub: "u_reply_ram + 轮转仲裁", domain: "protocol_mcu", group: "transaction_fsm", topic: "fsm_tx_ordering", tag: "Arbiter"},
  2509. ];
  2510. pipelineNodes.forEach((node, idx) => {
  2511. const isNodeActive = state.cpldTopicId === node.topic;
  2512. const btn = element("button", `cpld-topo-node${isNodeActive ? " is-active" : ""}`);
  2513. btn.type = "button";
  2514. btn.append(
  2515. element("span", "cpld-topo-tag", node.tag),
  2516. element("strong", "cpld-topo-label", node.label),
  2517. element("span", "cpld-topo-subtext", node.sub),
  2518. );
  2519. btn.addEventListener("click", () => navigateCpldTopic(node.domain, node.group, node.topic));
  2520. topologyFlow.append(btn);
  2521. if (idx < pipelineNodes.length - 1) {
  2522. topologyFlow.append(element("span", "cpld-topo-arrow", "→"));
  2523. }
  2524. });
  2525. topologyBox.append(topologyHead, topologyFlow);
  2526. wrapper.append(topologyBox);
  2527. // 3. Multi-Level Menu Search & Tree Mode Bar
  2528. const menuControlRow = element("div", "cpld-menu-control-row");
  2529. const searchInput = element("input", "cpld-topic-search");
  2530. searchInput.type = "search";
  2531. searchInput.placeholder = "🔍 快速检索全部 29 个 CPLD 架构专题 / 寄存器 / 模块 / 引脚 (如 BRAM, CRC, CON140, MCU, 500Hz)...";
  2532. searchInput.value = state.cpldFilterQuery;
  2533. searchInput.addEventListener("input", (e) => {
  2534. state.cpldFilterQuery = e.target.value;
  2535. const caret = searchInput.selectionStart;
  2536. renderCpldArchPanel();
  2537. const nextInput = dom["cpld-arch-content"]?.querySelector(".cpld-topic-search");
  2538. if (nextInput instanceof HTMLInputElement) {
  2539. nextInput.focus();
  2540. if (caret != null) nextInput.setSelectionRange(caret, caret);
  2541. }
  2542. });
  2543. const treeToggleBtn = element(
  2544. "button",
  2545. `cpld-tree-toggle-btn${state.cpldTreeExpanded ? " is-active" : ""}`,
  2546. state.cpldTreeExpanded ? "📂 收起三级目录树" : "🌳 展开全览目录树",
  2547. );
  2548. treeToggleBtn.type = "button";
  2549. treeToggleBtn.addEventListener("click", () => {
  2550. state.cpldTreeExpanded = !state.cpldTreeExpanded;
  2551. renderCpldArchPanel();
  2552. });
  2553. menuControlRow.append(searchInput, treeToggleBtn);
  2554. wrapper.append(menuControlRow);
  2555. // Quick search filter results across all 21 L3 topics
  2556. const q = state.cpldFilterQuery.trim().toLowerCase();
  2557. if (q) {
  2558. const allTopics = flattenAllCpldTopics(ver);
  2559. const matched = allTopics.filter((item) => {
  2560. const detail = getCpldTopicDetail(item.topicId, ver);
  2561. const haystack = [
  2562. item.domainLabel,
  2563. item.groupLabel,
  2564. item.topicLabel,
  2565. item.module,
  2566. detail.title,
  2567. detail.summary,
  2568. JSON.stringify(detail.kvTable || []),
  2569. JSON.stringify(detail.matrixTable || {}),
  2570. JSON.stringify(detail.pipelineFlow || []),
  2571. detail.codeBlock || "",
  2572. ]
  2573. .join(" ")
  2574. .toLowerCase();
  2575. return haystack.includes(q);
  2576. });
  2577. const searchBox = element("div", "cpld-search-hits");
  2578. searchBox.append(
  2579. element("div", "cpld-search-hits-head", `检索到 ${matched.length} 个匹配的 CPLD 源码与硬件专题:`),
  2580. );
  2581. const hitGrid = element("div", "cpld-search-hits-grid");
  2582. for (const hit of matched) {
  2583. const hitBtn = element(
  2584. "button",
  2585. `cpld-hit-btn${state.cpldTopicId === hit.topicId ? " is-active" : ""}`,
  2586. );
  2587. hitBtn.type = "button";
  2588. hitBtn.append(
  2589. element("span", "cpld-hit-path", `${hit.domainIcon} ${hit.domainLabel} › ${hit.groupLabel}`),
  2590. element("strong", "cpld-hit-title", hit.topicLabel),
  2591. element("span", "cpld-hit-mod", hit.file || hit.module),
  2592. );
  2593. hitBtn.addEventListener("click", () => {
  2594. state.cpldFilterQuery = "";
  2595. navigateCpldTopic(hit.domainId, hit.groupId, hit.topicId);
  2596. });
  2597. hitGrid.append(hitBtn);
  2598. }
  2599. searchBox.append(hitGrid);
  2600. wrapper.append(searchBox);
  2601. }
  2602. // 4. Dynamic 3-Level Cascading Menu (L1 Domain Cards → L2 Subsystem Groups → L3 Deep-Dive Topics)
  2603. const navContainer = element("nav", "cpld-multilevel-nav");
  2604. navContainer.setAttribute("aria-label", "CPLD 架构动态多级菜单");
  2605. // Level 1: 4 Primary Domains
  2606. const l1Bar = element("div", "cpld-l1-grid");
  2607. for (const domain of CPLD_MENU_TREE) {
  2608. const isActive = domain.id === activeDomain.id;
  2609. const topicCount = (domain.children || []).reduce((acc, g) => acc + (g.topics?.length || 0), 0);
  2610. const btn = element("button", `cpld-l1-card${isActive ? " is-active" : ""}`);
  2611. btn.type = "button";
  2612. const headRow = element("div", "cpld-l1-head");
  2613. headRow.append(
  2614. element("span", "cpld-l1-icon", domain.icon),
  2615. element("span", "cpld-l1-badge", `${(domain.children || []).length} 组 · ${topicCount} 专题`),
  2616. );
  2617. btn.append(
  2618. headRow,
  2619. element("div", "cpld-l1-title", domain.title),
  2620. element("div", "cpld-l1-desc", domain.subtitle),
  2621. );
  2622. btn.addEventListener("click", () => {
  2623. const firstGroup = domain.children?.[0];
  2624. const firstTopic = firstGroup?.topics?.[0];
  2625. navigateCpldTopic(domain.id, firstGroup?.id, firstTopic?.id);
  2626. });
  2627. l1Bar.append(btn);
  2628. }
  2629. navContainer.append(l1Bar);
  2630. if (state.cpldTreeExpanded) {
  2631. // Full Expanded 3-Level Directory Tree View
  2632. const fullTree = element("div", "cpld-full-tree");
  2633. for (const domain of CPLD_MENU_TREE) {
  2634. const dBlock = element("div", "cpld-tree-domain");
  2635. dBlock.append(element("div", "cpld-tree-domain-title", `${domain.icon} ${domain.title} — ${domain.subtitle}`));
  2636. for (const grp of domain.children || []) {
  2637. const gBlock = element("div", "cpld-tree-group");
  2638. gBlock.append(element("div", "cpld-tree-group-title", `▸ ${grp.title} [${grp.badge}]`));
  2639. const tList = element("div", "cpld-tree-topics");
  2640. for (const top of grp.topics || []) {
  2641. const topDetail = getCpldTopicDetail(top.id, ver);
  2642. const tBtn = element(
  2643. "button",
  2644. `cpld-tree-topic-btn${state.cpldTopicId === top.id ? " is-active" : ""}`,
  2645. );
  2646. tBtn.type = "button";
  2647. tBtn.append(
  2648. element("span", "", top.title),
  2649. element("code", "cpld-tree-mod", topDetail.tag || grp.badge),
  2650. );
  2651. tBtn.addEventListener("click", () => navigateCpldTopic(domain.id, grp.id, top.id));
  2652. tList.append(tBtn);
  2653. }
  2654. gBlock.append(tList);
  2655. dBlock.append(gBlock);
  2656. }
  2657. fullTree.append(dBlock);
  2658. }
  2659. navContainer.append(fullTree);
  2660. } else {
  2661. // Cascading Level 2 & Level 3 Bars
  2662. const l2Row = element("div", "cpld-l2-bar");
  2663. l2Row.append(element("span", "cpld-level-tag", "二级分类"));
  2664. const l2Pills = element("div", "cpld-l2-pills");
  2665. for (const grp of activeDomain.children || []) {
  2666. const isGrpActive = grp.id === activeGroup.id;
  2667. const gBtn = element(
  2668. "button",
  2669. `cpld-l2-btn${isGrpActive ? " is-active" : ""}`,
  2670. `${grp.title} (${grp.topics.length})`,
  2671. );
  2672. gBtn.type = "button";
  2673. gBtn.addEventListener("click", () => {
  2674. const firstTopic = grp.topics?.[0];
  2675. navigateCpldTopic(activeDomain.id, grp.id, firstTopic?.id);
  2676. });
  2677. l2Pills.append(gBtn);
  2678. }
  2679. l2Row.append(l2Pills);
  2680. const l3Row = element("div", "cpld-l3-bar");
  2681. l3Row.append(element("span", "cpld-level-tag is-l3", "三级专题"));
  2682. const l3Pills = element("div", "cpld-l3-pills");
  2683. for (const top of activeGroup.topics || []) {
  2684. const isTopActive = top.id === activeTopic.id;
  2685. const topDetail = getCpldTopicDetail(top.id, ver);
  2686. const tBtn = element("button", `cpld-l3-btn${isTopActive ? " is-active" : ""}`);
  2687. tBtn.type = "button";
  2688. tBtn.append(
  2689. element("span", "cpld-l3-btn-label", top.title),
  2690. element("span", "cpld-l3-btn-mod", topDetail.file || topDetail.tag || activeGroup.badge),
  2691. );
  2692. tBtn.addEventListener("click", () => navigateCpldTopic(activeDomain.id, activeGroup.id, top.id));
  2693. l3Pills.append(tBtn);
  2694. }
  2695. l3Row.append(l3Pills);
  2696. navContainer.append(l2Row, l3Row);
  2697. }
  2698. wrapper.append(navContainer);
  2699. // 5. Active L3 Topic Deep-Dive Article Card
  2700. const detail = getCpldTopicDetail(activeTopic.id, ver);
  2701. const article = element("article", "cpld-topic-article");
  2702. // Breadcrumb + RTL File Badge
  2703. const breadcrumbRow = element("div", "cpld-breadcrumb-row");
  2704. breadcrumbRow.append(
  2705. element("span", "cpld-breadcrumb", `${activeDomain.icon} ${activeDomain.title} › ${activeGroup.title} › ${activeTopic.title}`),
  2706. element("code", "cpld-file-badge", detail.file || detail.tag || activeGroup.badge),
  2707. );
  2708. article.append(breadcrumbRow);
  2709. article.append(
  2710. element("h3", "cpld-article-title", detail.title),
  2711. element("p", "cpld-article-summary", detail.summary),
  2712. );
  2713. // Interactive PCB Jump Pills (一键在 PCB 图定位对应插座/芯片/引脚)
  2714. if (Array.isArray(detail.jumpPills) && detail.jumpPills.length) {
  2715. const jumpBar = element("div", "cpld-jump-bar");
  2716. jumpBar.append(element("span", "cpld-jump-label", "🎯 关联板级插座与逻辑管脚一键定位:"));
  2717. const jumpList = element("div", "cpld-jump-list");
  2718. for (const pill of detail.jumpPills) {
  2719. const pBtn = element("button", "cpld-jump-pill", `📍 ${pill.label}`);
  2720. pBtn.type = "button";
  2721. pBtn.title = "点击在左侧电路板视图中定位并高亮该硬件接口(按住 Ctrl 点击全板标出同网/同类)";
  2722. pBtn.addEventListener("click", (event) => jumpToBoardTarget(pill, event));
  2723. jumpList.append(pBtn);
  2724. }
  2725. jumpBar.append(jumpList);
  2726. article.append(jumpBar);
  2727. }
  2728. // Render Pipeline Flow (if present)
  2729. if (Array.isArray(detail.pipelineFlow) && detail.pipelineFlow.length) {
  2730. const secEl = element("section", "cpld-sec-block");
  2731. secEl.append(element("h4", "cpld-sec-heading", "芯片内部硬件流水线与总线节拍 (Pipeline & Bus Flow)"));
  2732. const flowList = element("div", "cpld-pipeline-list");
  2733. detail.pipelineFlow.forEach((st, idx) => {
  2734. const card = element("div", "cpld-pipeline-step");
  2735. card.append(
  2736. element("span", "cpld-step-num", String(idx + 1)),
  2737. element("div", "cpld-step-body"),
  2738. );
  2739. card.lastChild.append(
  2740. element("strong", "cpld-step-title", `${st.stage} · ${st.module}`),
  2741. element("div", "cpld-hit-mod", `片上总线/信号: ${st.bus}`),
  2742. element("p", "cpld-step-detail", st.desc),
  2743. );
  2744. flowList.append(card);
  2745. });
  2746. secEl.append(flowList);
  2747. article.append(secEl);
  2748. }
  2749. // Render Key-Value Table (if present)
  2750. if (Array.isArray(detail.kvTable) && detail.kvTable.length) {
  2751. const secEl = element("section", "cpld-sec-block");
  2752. secEl.append(element("h4", "cpld-sec-heading", "核心架构参数、寄存器与电气契约明细"));
  2753. const kvGrid = element("div", "cpld-kv-list");
  2754. for (const [k, v] of detail.kvTable) {
  2755. const row = element("div", "cpld-kv-row");
  2756. row.append(
  2757. element("div", "cpld-kv-key", k),
  2758. element("div", "cpld-kv-val", v),
  2759. );
  2760. kvGrid.append(row);
  2761. }
  2762. secEl.append(kvGrid);
  2763. article.append(secEl);
  2764. }
  2765. // Render Comparison Matrix Table (if present)
  2766. if (detail.matrixTable && Array.isArray(detail.matrixTable.rows)) {
  2767. const secEl = element("section", "cpld-sec-block");
  2768. secEl.append(element("h4", "cpld-sec-heading", "跨版本 / 跨通道硬件与协议映射对比矩阵"));
  2769. const tableWrap = element("div", "cpld-table-wrap");
  2770. const table = element("table", "cpld-matrix-table");
  2771. if (Array.isArray(detail.matrixTable.headers)) {
  2772. const thead = element("thead");
  2773. const tr = element("tr");
  2774. for (const h of detail.matrixTable.headers) {
  2775. tr.append(element("th", "", h));
  2776. }
  2777. thead.append(tr);
  2778. table.append(thead);
  2779. }
  2780. const tbody = element("tbody");
  2781. for (const r of detail.matrixTable.rows) {
  2782. const tr = element("tr");
  2783. const rowText = r.join(" ");
  2784. if (
  2785. (ver === "v2_0" && rowText.includes("6400 V2.0") && !rowText.includes("扩展板")) ||
  2786. (ver === "v2_0_fan" && rowText.includes("扩展板")) ||
  2787. (ver === "v1_2" && rowText.includes("V1.2")) ||
  2788. (ver === "v1_1" && rowText.includes("V1.1"))
  2789. ) {
  2790. tr.classList.add("is-current-board-row");
  2791. }
  2792. for (const cell of r) {
  2793. tr.append(element("td", "", cell));
  2794. }
  2795. tbody.append(tr);
  2796. }
  2797. table.append(tbody);
  2798. tableWrap.append(table);
  2799. secEl.append(tableWrap);
  2800. article.append(secEl);
  2801. }
  2802. // Render Verilog Code Block (if present)
  2803. if (detail.codeBlock) {
  2804. const secEl = element("section", "cpld-sec-block");
  2805. secEl.append(element("h4", "cpld-sec-heading", `实现说明 / 代码示意(当前源码见 ${detail.file || "src/"})`));
  2806. const codeBox = element("div", "cpld-code-box");
  2807. const codeHead = element("div", "cpld-code-head");
  2808. codeHead.append(element("span", "cpld-code-lang", `${detail.file || "Verilog RTL"} · 手工维护说明`));
  2809. const copyBtn = element("button", "cpld-code-copy-btn", "⧉ 复制说明");
  2810. copyBtn.type = "button";
  2811. copyBtn.addEventListener("click", async () => {
  2812. await copyText(detail.codeBlock);
  2813. copyBtn.textContent = "✓ 已复制";
  2814. window.setTimeout(() => {
  2815. copyBtn.textContent = "⧉ 复制说明";
  2816. }, 1800);
  2817. });
  2818. codeHead.append(copyBtn);
  2819. const pre = element("pre", "cpld-code-pre");
  2820. pre.append(element("code", "", detail.codeBlock));
  2821. codeBox.append(codeHead, pre);
  2822. secEl.append(codeBox);
  2823. article.append(secEl);
  2824. }
  2825. // Prev / Next Topic Sequential Footer Navigation
  2826. const allTopics = flattenAllCpldTopics(ver);
  2827. const curIdx = allTopics.findIndex((t) => t.topicId === activeTopic.id);
  2828. if (curIdx >= 0) {
  2829. const pager = element("div", "cpld-topic-pager");
  2830. const prevItem = allTopics[(curIdx - 1 + allTopics.length) % allTopics.length];
  2831. const nextItem = allTopics[(curIdx + 1) % allTopics.length];
  2832. const prevBtn = element("button", "cpld-pager-btn", `← 上一专题:${prevItem.topicLabel}`);
  2833. prevBtn.type = "button";
  2834. prevBtn.addEventListener("click", () =>
  2835. navigateCpldTopic(prevItem.domainId, prevItem.groupId, prevItem.topicId),
  2836. );
  2837. const nextBtn = element("button", "cpld-pager-btn is-next", `下一专题:${nextItem.topicLabel} →`);
  2838. nextBtn.type = "button";
  2839. nextBtn.addEventListener("click", () =>
  2840. navigateCpldTopic(nextItem.domainId, nextItem.groupId, nextItem.topicId),
  2841. );
  2842. pager.append(prevBtn, nextBtn);
  2843. article.append(pager);
  2844. }
  2845. wrapper.append(article);
  2846. container.append(wrapper);
  2847. }
  2848. function switchTab(tab) {
  2849. state.activeTab = tab;
  2850. const isDetail = tab === "detail";
  2851. const isPeripheral = tab === "peripheral";
  2852. const isCpldArch = tab === "cpld-arch";
  2853. const isCandidate = tab === "candidate";
  2854. const isSchematic = tab === "schematic";
  2855. dom["detail-tab"].setAttribute("aria-selected", String(isDetail));
  2856. if (dom["peripheral-tab"]) dom["peripheral-tab"].setAttribute("aria-selected", String(isPeripheral));
  2857. if (dom["cpld-arch-tab"]) dom["cpld-arch-tab"].setAttribute("aria-selected", String(isCpldArch));
  2858. dom["candidate-tab"].setAttribute("aria-selected", String(isCandidate));
  2859. if (dom["schematic-tab"]) dom["schematic-tab"].setAttribute("aria-selected", String(isSchematic));
  2860. dom["detail-content"].hidden = !isDetail;
  2861. if (dom["peripheral-content"]) dom["peripheral-content"].hidden = !isPeripheral;
  2862. if (dom["cpld-arch-content"]) dom["cpld-arch-content"].hidden = !isCpldArch;
  2863. dom["candidate-content"].hidden = !isCandidate;
  2864. if (dom["schematic-content"]) dom["schematic-content"].hidden = !isSchematic;
  2865. if (isPeripheral) {
  2866. renderPeripheralPanel();
  2867. } else {
  2868. if (state.peripheralHighlightedRefs?.size) {
  2869. state.peripheralHighlightedRefs = new Set();
  2870. updateSelectionVisuals();
  2871. }
  2872. }
  2873. if (isCpldArch) renderCpldArchPanel();
  2874. if (isCandidate) renderCandidates();
  2875. }
  2876. function renderSearchResults(query) {
  2877. let results = searchBoard(state.data, query);
  2878. if (!state.showShieldPins && !query.trim().toUpperCase().includes("SH")) {
  2879. results = results.filter((item) => !isShieldPin(item.pin));
  2880. }
  2881. state.searchResults = results.slice(0, 24);
  2882. state.activeSearchIndex = -1;
  2883. dom["search-results"].replaceChildren();
  2884. if (!query.trim()) {
  2885. dom["search-results"].hidden = true;
  2886. return;
  2887. }
  2888. dom["search-results"].hidden = false;
  2889. if (!state.searchResults.length) {
  2890. const coverage = state.data?.value_coverage;
  2891. const looksValue = /^(?:value:)?\d/i.test(query.trim()) || /[rRkKmM]|ohm|Ω/.test(query);
  2892. let message = "没有匹配的座子、电阻或针脚";
  2893. if (looksValue && coverage) {
  2894. message = `当前索引中没有此阻值;当前阻值覆盖 ${coverage.value_parsed}/${coverage.resistors_total}(原始值非空 ${coverage.component_value_nonempty})。位号/网络查询不受影响。`;
  2895. }
  2896. dom["search-results"].append(element("div", "empty-search", message));
  2897. return;
  2898. }
  2899. state.searchResults.forEach((result, index) => {
  2900. const button = element("button", "search-result");
  2901. button.type = "button";
  2902. button.role = "option";
  2903. button.dataset.index = String(index);
  2904. button.setAttribute("aria-selected", "false");
  2905. let key = result.reference;
  2906. let detail = "";
  2907. if (result.type === "pin") {
  2908. key = `${result.reference}.${result.pinNumber}`;
  2909. const logical = resolveLogicalPin(result.touchpoint, result.pin, state.boardVersion);
  2910. detail = `${logical.displayBadge} · ${logical.peripheralRole} · 网络:${result.pin.net || "无"}`;
  2911. } else if (result.type === "resistor" || result.type === "resistor_pad") {
  2912. key = result.type === "resistor_pad" ? `${result.reference}.${result.pinNumber}` : result.reference;
  2913. const nets = (result.resistor?.pads ?? []).filter((pad) => pad.net).map((pad) => pad.net);
  2914. const valueLabel = result.resistor?.value_ohms != null
  2915. ? `${result.resistor.value_ohms} Ω`
  2916. : (result.resistor?.component_value || "阻值未标注");
  2917. const nf = result.notFitted || result.resistor?.assembly_status === "not_fitted";
  2918. detail = result.type === "resistor_pad"
  2919. ? `${result.pin?.net || "无网络"}`
  2920. : `${valueLabel} · ${nets.join(" ↔ ") || "无网络"}${nf ? " · 未装/NC" : ""}`;
  2921. } else if (result.type === "evidence_conflict") {
  2922. key = `${result.reference} 冲突`;
  2923. detail = result.evidenceConflict?.summary || "原理图声明与 PCB 索引冲突,未解决";
  2924. } else {
  2925. const periph = classifyTouchpointPeripheral(result.touchpoint, state.boardVersion);
  2926. detail = `${periph.peripheralLabel} (${periph.isUsed ? "已用" : (periph.isSpareConnector ? "空余插座" : "板级")}) · ${result.touchpoint.summary}`;
  2927. }
  2928. button.append(element("span", "result-key", key), element("span", "result-detail", detail));
  2929. button.addEventListener("click", (event) => activateSearchResult(index, event));
  2930. dom["search-results"].append(button);
  2931. });
  2932. }
  2933. function activateSearchResult(index, event = null) {
  2934. const result = state.searchResults[index];
  2935. if (!result) return;
  2936. const ctrlMulti = Boolean(event?.ctrlKey || event?.metaKey);
  2937. if (result.type === "resistor" || result.type === "resistor_pad" || result.type === "evidence_conflict") {
  2938. if (!result.resistor) return;
  2939. state.categories.add("R");
  2940. const checkbox = dom["category-filters"].querySelector('input[value="R"]');
  2941. if (checkbox) checkbox.checked = true;
  2942. selectResistor(result.resistor, result.pin, true, {highlightAllSame: ctrlMulti});
  2943. focusOnTouchpoint(result.resistor);
  2944. dom["board-search"].value = result.type === "resistor_pad"
  2945. ? `${result.reference}.${result.pinNumber}`
  2946. : result.reference;
  2947. } else if (result.touchpoint) {
  2948. state.categories.add(result.touchpoint.category);
  2949. const checkbox = dom["category-filters"].querySelector(`input[value="${result.touchpoint.category}"]`);
  2950. if (checkbox) checkbox.checked = true;
  2951. selectTouchpoint(result.touchpoint, result.pin, true, {highlightAllSame: ctrlMulti});
  2952. focusOnTouchpoint(result.touchpoint);
  2953. dom["board-search"].value = result.type === "pin" ? `${result.reference}.${result.pinNumber}` : result.reference;
  2954. }
  2955. dom["search-results"].hidden = true;
  2956. dom["board-svg"].focus();
  2957. }
  2958. function updateSearchSelection(nextIndex) {
  2959. const options = [...dom["search-results"].querySelectorAll(".search-result")];
  2960. if (!options.length) return;
  2961. state.activeSearchIndex = (nextIndex + options.length) % options.length;
  2962. options.forEach((option, index) => option.setAttribute("aria-selected", String(index === state.activeSearchIndex)));
  2963. options[state.activeSearchIndex].scrollIntoView({block: "nearest"});
  2964. }
  2965. function focusOnTouchpoint(touchpoint) {
  2966. const bounds = effectiveBounds(toDisplayBounds(touchpoint.view_bounds), 8);
  2967. const viewport = dom["board-svg"].getBoundingClientRect();
  2968. const aspect = Math.max(viewport.width / Math.max(viewport.height, 1), 1);
  2969. let width = Math.max(bounds.width * 3.4, state.baseViewBox.width / 12);
  2970. let height = width / aspect;
  2971. if (height < bounds.height * 3.4) {
  2972. height = bounds.height * 3.4;
  2973. width = height * aspect;
  2974. }
  2975. const target = {
  2976. x: bounds.x + bounds.width / 2 - width / 2,
  2977. y: bounds.y + bounds.height / 2 - height / 2,
  2978. width,
  2979. height,
  2980. };
  2981. animateViewBoxTo(target, 240);
  2982. }
  2983. function clampViewBox() {
  2984. if (!state.viewBox || !state.baseViewBox) return;
  2985. const marginX = state.baseViewBox.width * 0.25;
  2986. const marginY = state.baseViewBox.height * 0.4;
  2987. const minX = state.baseViewBox.x - marginX;
  2988. const maxX = state.baseViewBox.x + state.baseViewBox.width + marginX - state.viewBox.width;
  2989. const minY = state.baseViewBox.y - marginY;
  2990. const maxY = state.baseViewBox.y + state.baseViewBox.height + marginY - state.viewBox.height;
  2991. state.viewBox.x = Math.min(Math.max(state.viewBox.x, minX), Math.max(minX, maxX));
  2992. state.viewBox.y = Math.min(Math.max(state.viewBox.y, minY), Math.max(minY, maxY));
  2993. }
  2994. function zoomAt(factor, clientX = null, clientY = null, animateMs = 0) {
  2995. if (!state.viewBox || !state.baseViewBox) return;
  2996. cancelViewBoxAnimation();
  2997. const minimumWidth = state.baseViewBox.width / 35;
  2998. const maximumWidth = state.baseViewBox.width * 1.25;
  2999. const newWidth = Math.min(Math.max(state.viewBox.width * factor, minimumWidth), maximumWidth);
  3000. const ratio = newWidth / state.viewBox.width;
  3001. const anchor = clientX == null ? {
  3002. x: state.viewBox.x + state.viewBox.width / 2,
  3003. y: state.viewBox.y + state.viewBox.height / 2,
  3004. } : clientToSvg(clientX, clientY);
  3005. const nextBox = {
  3006. x: anchor.x - (anchor.x - state.viewBox.x) * ratio,
  3007. y: anchor.y - (anchor.y - state.viewBox.y) * ratio,
  3008. width: newWidth,
  3009. height: state.viewBox.height * ratio,
  3010. };
  3011. if (animateMs > 0) {
  3012. animateViewBoxTo(nextBox, animateMs);
  3013. } else {
  3014. state.viewBox = nextBox;
  3015. clampViewBox();
  3016. scheduleViewBoxUpdate();
  3017. }
  3018. }
  3019. function setZoomRatio(targetRatio, clientX = null, clientY = null, animateMs = 150) {
  3020. if (!state.viewBox || !state.baseViewBox) return;
  3021. const clampedRatio = Math.min(Math.max(Number(targetRatio) || 1, 0.8), 35);
  3022. const targetWidth = state.baseViewBox.width / clampedRatio;
  3023. const factor = targetWidth / Math.max(state.viewBox.width, 0.001);
  3024. zoomAt(factor, clientX, clientY, animateMs);
  3025. }
  3026. function setBoxZoomMode(enabled) {
  3027. state.boxZoomMode = Boolean(enabled);
  3028. dom["board-svg"].classList.toggle("is-box-zoom", state.boxZoomMode);
  3029. if (dom["box-zoom-toggle"]) {
  3030. dom["box-zoom-toggle"].setAttribute("aria-pressed", String(state.boxZoomMode));
  3031. }
  3032. if (dom["hud-box-zoom"]) {
  3033. dom["hud-box-zoom"].setAttribute("aria-pressed", String(state.boxZoomMode));
  3034. }
  3035. }
  3036. function panMinimapTo(clientX, clientY) {
  3037. const canvas = dom["board-minimap"];
  3038. if (!canvas || !state.viewBox || !state.baseViewBox) return;
  3039. const rect = canvas.getBoundingClientRect();
  3040. const mw = Math.max(rect.width, 1);
  3041. const mh = Math.max(rect.height, 1);
  3042. const bx = state.baseViewBox.x;
  3043. const by = state.baseViewBox.y;
  3044. const bw = Math.max(state.baseViewBox.width, 1);
  3045. const bh = Math.max(state.baseViewBox.height, 1);
  3046. const scale = Math.min(mw / bw, mh / bh);
  3047. const ox = (mw - bw * scale) * 0.5 - bx * scale;
  3048. const oy = (mh - bh * scale) * 0.5 - by * scale;
  3049. const targetX = (clientX - rect.left - ox) / scale;
  3050. const targetY = (clientY - rect.top - oy) / scale;
  3051. cancelViewBoxAnimation();
  3052. state.viewBox.x = targetX - state.viewBox.width * 0.5;
  3053. state.viewBox.y = targetY - state.viewBox.height * 0.5;
  3054. clampViewBox();
  3055. scheduleViewBoxUpdate();
  3056. }
  3057. function bindContinuousZoomButton(buttonEl, direction) {
  3058. if (!buttonEl) return;
  3059. let holdTimer = 0;
  3060. let holdRaf = 0;
  3061. let holding = false;
  3062. const stopHold = () => {
  3063. if (holdTimer) {
  3064. window.clearTimeout(holdTimer);
  3065. holdTimer = 0;
  3066. }
  3067. if (holdRaf) {
  3068. window.cancelAnimationFrame(holdRaf);
  3069. holdRaf = 0;
  3070. }
  3071. holding = false;
  3072. };
  3073. buttonEl.addEventListener("pointerdown", (event) => {
  3074. if (event.button !== 0 && event.pointerType === "mouse") return;
  3075. event.preventDefault();
  3076. stopHold();
  3077. // Immediate responsive step on press
  3078. zoomAt(direction > 0 ? 0.75 : 1.33, null, null, 110);
  3079. holdTimer = window.setTimeout(() => {
  3080. holding = true;
  3081. let lastTime = performance.now();
  3082. const stepHold = (now) => {
  3083. if (!holding) return;
  3084. const dt = Math.min(Math.max((now - lastTime) / 1000, 0.004), 0.05);
  3085. lastTime = now;
  3086. const speedFactor = Math.exp((direction > 0 ? -1.45 : 1.45) * dt);
  3087. zoomAt(speedFactor, null, null, 0);
  3088. holdRaf = window.requestAnimationFrame(stepHold);
  3089. };
  3090. holdRaf = window.requestAnimationFrame(stepHold);
  3091. }, 180);
  3092. });
  3093. buttonEl.addEventListener("pointerup", stopHold);
  3094. buttonEl.addEventListener("pointerleave", stopHold);
  3095. buttonEl.addEventListener("pointercancel", stopHold);
  3096. buttonEl.addEventListener("keydown", (event) => {
  3097. if (event.key === "Enter" || event.key === " ") {
  3098. event.preventDefault();
  3099. zoomAt(direction > 0 ? 0.75 : 1.33, null, null, 140);
  3100. }
  3101. });
  3102. }
  3103. function clientToSvg(clientX, clientY) {
  3104. if (state.viewBox && dom["board-viewport"]) {
  3105. const rect = dom["board-viewport"].getBoundingClientRect();
  3106. const cw = Math.max(rect.width, 1);
  3107. const ch = Math.max(rect.height, 1);
  3108. const {x: vx, y: vy, width: vw, height: vh} = state.viewBox;
  3109. const scale = Math.min(cw / Math.max(vw, 0.001), ch / Math.max(vh, 0.001));
  3110. const offsetX = (cw - vw * scale) * 0.5 - vx * scale;
  3111. const offsetY = (ch - vh * scale) * 0.5 - vy * scale;
  3112. return {
  3113. x: (clientX - rect.left - offsetX) / scale,
  3114. y: (clientY - rect.top - offsetY) / scale,
  3115. };
  3116. }
  3117. const point = dom["board-svg"].createSVGPoint();
  3118. point.x = clientX;
  3119. point.y = clientY;
  3120. return point.matrixTransform(dom["board-svg"].getScreenCTM().inverse());
  3121. }
  3122. function hitTestBoardAt(clientX, clientY) {
  3123. if (!state.data || !state.viewBox || !state.baseViewBox) return null;
  3124. const pt = clientToSvg(clientX, clientY);
  3125. const zoomRatio = state.baseViewBox.width / Math.max(state.viewBox.width, 0.001);
  3126. return wasmAccel.hitTest(
  3127. pt.x,
  3128. pt.y,
  3129. state.boardSide,
  3130. state.categories,
  3131. state.showShieldPins,
  3132. zoomRatio,
  3133. );
  3134. }
  3135. function resetView() {
  3136. setBoxZoomMode(false);
  3137. animateViewBoxTo({...state.baseViewBox}, 200);
  3138. }
  3139. function setDrawerCollapsed(collapsed) {
  3140. dom.app.classList.toggle("detail-collapsed", collapsed);
  3141. dom["drawer-toggle"].setAttribute("aria-expanded", String(!collapsed));
  3142. dom["drawer-toggle"].title = collapsed ? "展开详情" : "收起详情";
  3143. dom["drawer-toggle"].setAttribute("aria-label", collapsed ? "展开详情" : "收起详情");
  3144. }
  3145. function setWidePanel(wide) {
  3146. state.widePanel = Boolean(wide);
  3147. dom.app.classList.toggle("detail-wide", state.widePanel);
  3148. if (dom["toggle-wide-panel"]) {
  3149. dom["toggle-wide-panel"].setAttribute("aria-pressed", String(state.widePanel));
  3150. dom["toggle-wide-panel"].textContent = state.widePanel ? "⤡ 标准宽度" : "⤢ 宽屏";
  3151. }
  3152. }
  3153. dom["category-filters"].addEventListener("change", (event) => {
  3154. const input = event.target;
  3155. if (!(input instanceof HTMLInputElement)) return;
  3156. if (input.value === "SH") {
  3157. state.showShieldPins = input.checked;
  3158. if (!state.showShieldPins && isShieldPin(state.selectedPin)) {
  3159. state.selectedPin = null;
  3160. }
  3161. renderBoardMarkers();
  3162. renderDetail();
  3163. return;
  3164. }
  3165. if (input.checked) state.categories.add(input.value);
  3166. else state.categories.delete(input.value);
  3167. renderBoardMarkers();
  3168. });
  3169. dom["side-controls"].addEventListener("change", (event) => {
  3170. const input = event.target;
  3171. if (!(input instanceof HTMLInputElement) || input.name !== "board-side") return;
  3172. setBoardSide(input.value, {rerender: true});
  3173. });
  3174. dom["layer-controls"].addEventListener("change", (event) => {
  3175. const input = event.target;
  3176. if (!(input instanceof HTMLInputElement)) return;
  3177. const layer = dom[`layer-${input.value}`];
  3178. if (layer) layer.hidden = !input.checked;
  3179. prepareLayerBitmapCache();
  3180. });
  3181. if (dom["perf-mode-toggle"]) {
  3182. dom["perf-mode-toggle"].addEventListener("click", () => {
  3183. state.perfUltraMode = !state.perfUltraMode;
  3184. syncStaticLayerVisibility();
  3185. renderLayerCanvasFrame();
  3186. renderBoardMarkers();
  3187. });
  3188. }
  3189. bindContinuousZoomButton(dom["zoom-in"], 1);
  3190. bindContinuousZoomButton(dom["zoom-out"], -1);
  3191. bindContinuousZoomButton(dom["hud-zoom-in"], 1);
  3192. bindContinuousZoomButton(dom["hud-zoom-out"], -1);
  3193. dom["reset-view"].addEventListener("click", resetView);
  3194. if (dom["hud-reset-view"]) dom["hud-reset-view"].addEventListener("click", resetView);
  3195. if (dom["box-zoom-toggle"]) {
  3196. dom["box-zoom-toggle"].addEventListener("click", () => setBoxZoomMode(!state.boxZoomMode));
  3197. }
  3198. if (dom["hud-box-zoom"]) {
  3199. dom["hud-box-zoom"].addEventListener("click", () => setBoxZoomMode(!state.boxZoomMode));
  3200. }
  3201. if (dom["zoom-slider"]) {
  3202. dom["zoom-slider"].addEventListener("input", (event) => {
  3203. const pct = Number(event.target.value) || 100;
  3204. setZoomRatio(pct / 100, null, null, 0);
  3205. });
  3206. }
  3207. if (dom["zoom-hud-dock"]) {
  3208. dom["zoom-hud-dock"].addEventListener("click", (event) => {
  3209. const presetBtn = event.target?.closest?.(".hud-preset-btn[data-zoom]");
  3210. if (!presetBtn) return;
  3211. const targetRatio = Number(presetBtn.dataset.zoom) || 1;
  3212. setZoomRatio(targetRatio, null, null, 160);
  3213. });
  3214. }
  3215. if (dom["board-minimap"]) {
  3216. dom["board-minimap"].addEventListener("pointerdown", (event) => {
  3217. event.preventDefault();
  3218. event.stopPropagation();
  3219. state.minimapDragging = true;
  3220. dom["board-minimap"].setPointerCapture(event.pointerId);
  3221. panMinimapTo(event.clientX, event.clientY);
  3222. });
  3223. dom["board-minimap"].addEventListener("pointermove", (event) => {
  3224. if (!state.minimapDragging) return;
  3225. panMinimapTo(event.clientX, event.clientY);
  3226. });
  3227. const endMinimapDrag = () => {
  3228. state.minimapDragging = false;
  3229. };
  3230. dom["board-minimap"].addEventListener("pointerup", endMinimapDrag);
  3231. dom["board-minimap"].addEventListener("pointercancel", endMinimapDrag);
  3232. }
  3233. dom["detail-tab"].addEventListener("click", () => switchTab("detail"));
  3234. if (dom["peripheral-tab"]) dom["peripheral-tab"].addEventListener("click", () => switchTab("peripheral"));
  3235. if (dom["cpld-arch-tab"]) {
  3236. dom["cpld-arch-tab"].addEventListener("click", () => {
  3237. if (!state.widePanel && window.innerWidth > 1180) {
  3238. setWidePanel(true);
  3239. }
  3240. switchTab("cpld-arch");
  3241. });
  3242. }
  3243. if (dom["open-peripheral-index"]) {
  3244. dom["open-peripheral-index"].addEventListener("click", () => {
  3245. setDrawerCollapsed(false);
  3246. switchTab("peripheral");
  3247. });
  3248. }
  3249. if (dom["open-cpld-arch"]) {
  3250. dom["open-cpld-arch"].addEventListener("click", () => {
  3251. setDrawerCollapsed(false);
  3252. if (window.innerWidth > 1180) {
  3253. setWidePanel(true);
  3254. }
  3255. switchTab("cpld-arch");
  3256. });
  3257. }
  3258. if (dom["toggle-wide-panel"]) {
  3259. dom["toggle-wide-panel"].addEventListener("click", () => {
  3260. setDrawerCollapsed(false);
  3261. setWidePanel(!state.widePanel);
  3262. });
  3263. }
  3264. dom["candidate-tab"].addEventListener("click", () => switchTab("candidate"));
  3265. if (dom["schematic-tab"]) dom["schematic-tab"].addEventListener("click", () => switchTab("schematic"));
  3266. if (dom["board-version-select"]) {
  3267. dom["board-version-select"].addEventListener("change", (e) => {
  3268. const ver = e.target.value;
  3269. const url = new URL(window.location.href);
  3270. url.searchParams.set("version", ver);
  3271. window.history.replaceState({}, "", url.toString());
  3272. loadApplication(ver);
  3273. });
  3274. }
  3275. dom["capability-select"].addEventListener("change", renderCandidates);
  3276. dom["drawer-toggle"].addEventListener("click", () => setDrawerCollapsed(!dom.app.classList.contains("detail-collapsed")));
  3277. dom["board-search"].addEventListener("input", (event) => {
  3278. if (state.data) renderSearchResults(event.target.value);
  3279. });
  3280. dom["board-search"].addEventListener("keydown", (event) => {
  3281. if (event.key === "ArrowDown") {
  3282. event.preventDefault();
  3283. updateSearchSelection(state.activeSearchIndex + 1);
  3284. } else if (event.key === "ArrowUp") {
  3285. event.preventDefault();
  3286. updateSearchSelection(state.activeSearchIndex - 1);
  3287. } else if (event.key === "Enter" && state.activeSearchIndex >= 0) {
  3288. event.preventDefault();
  3289. activateSearchResult(state.activeSearchIndex);
  3290. } else if (event.key === "Escape") {
  3291. dom["search-results"].hidden = true;
  3292. }
  3293. });
  3294. document.addEventListener("pointerdown", (event) => {
  3295. if (!dom["search-results"].contains(event.target) && event.target !== dom["board-search"]) {
  3296. dom["search-results"].hidden = true;
  3297. }
  3298. });
  3299. // Proportional silky-smooth wheel & trackpad pinch zoom across the entire viewport
  3300. dom["board-viewport"].addEventListener("wheel", (event) => {
  3301. if (event.target?.closest?.(".zoom-hud-dock, .board-minimap-wrap")) return;
  3302. event.preventDefault();
  3303. let dy = event.deltaY;
  3304. if (event.deltaMode === 1) dy *= 32;
  3305. else if (event.deltaMode === 2) dy *= 320;
  3306. // Trackpad pinch gestures set ctrlKey=true with smaller deltas; boost sensitivity
  3307. const sensitivity = event.ctrlKey ? 0.0085 : 0.0024;
  3308. const factor = Math.min(Math.max(Math.exp(dy * sensitivity), 0.52), 1.92);
  3309. zoomAt(factor, event.clientX, event.clientY, 0);
  3310. }, {passive: false});
  3311. // Double-click anywhere on the board to zoom in 2.2x at cursor (Shift + double-click to zoom out)
  3312. dom["board-svg"].addEventListener("dblclick", (event) => {
  3313. event.preventDefault();
  3314. zoomAt(event.shiftKey ? 2.1 : 0.45, event.clientX, event.clientY, 170);
  3315. });
  3316. // Prevent context menu on right-drag box-zoom
  3317. dom["board-svg"].addEventListener("contextmenu", (event) => {
  3318. event.preventDefault();
  3319. });
  3320. dom["board-svg"].addEventListener("pointerdown", (event) => {
  3321. if (event.pointerType === "touch") {
  3322. state.activeTouchPointers.set(event.pointerId, {x: event.clientX, y: event.clientY});
  3323. if (state.activeTouchPointers.size === 2) {
  3324. const pts = [...state.activeTouchPointers.values()];
  3325. const dist = Math.max(Math.hypot(pts[1].x - pts[0].x, pts[1].y - pts[0].y), 10);
  3326. const midX = (pts[0].x + pts[1].x) * 0.5;
  3327. const midY = (pts[0].y + pts[1].y) * 0.5;
  3328. state.dragging = null;
  3329. state.pinchState = {
  3330. startDist: dist,
  3331. midX,
  3332. midY,
  3333. startWidth: state.viewBox.width,
  3334. };
  3335. return;
  3336. }
  3337. }
  3338. const isRightButton = event.pointerType === "mouse" && event.button === 2;
  3339. const isLeftButton = event.pointerType !== "mouse" || event.button === 0;
  3340. if (!isLeftButton && !isRightButton) return;
  3341. cancelViewBoxAnimation();
  3342. dom["board-svg"].setPointerCapture(event.pointerId);
  3343. const bounds = dom["board-viewport"].getBoundingClientRect();
  3344. // Box-Zoom triggered by: 🔍 框选放大 mode, Shift + Left-drag, or Right-button drag
  3345. if (state.boxZoomMode || event.shiftKey || isRightButton) {
  3346. hideTooltip();
  3347. state.boxZoomDrag = {
  3348. pointerId: event.pointerId,
  3349. startClientX: event.clientX,
  3350. startClientY: event.clientY,
  3351. curClientX: event.clientX,
  3352. curClientY: event.clientY,
  3353. viewportRect: bounds,
  3354. };
  3355. return;
  3356. }
  3357. state.dragging = {
  3358. pointerId: event.pointerId,
  3359. x: event.clientX,
  3360. y: event.clientY,
  3361. moved: false,
  3362. scaleX: state.viewBox.width / Math.max(bounds.width, 1),
  3363. scaleY: state.viewBox.height / Math.max(bounds.height, 1),
  3364. viewBox: {...state.viewBox},
  3365. };
  3366. });
  3367. dom["board-svg"].addEventListener("pointermove", (event) => {
  3368. if (state.activeTouchPointers.has(event.pointerId)) {
  3369. state.activeTouchPointers.set(event.pointerId, {x: event.clientX, y: event.clientY});
  3370. if (state.pinchState && state.activeTouchPointers.size === 2) {
  3371. const pts = [...state.activeTouchPointers.values()];
  3372. const dist = Math.max(Math.hypot(pts[1].x - pts[0].x, pts[1].y - pts[0].y), 10);
  3373. const targetWidth = state.pinchState.startWidth * (state.pinchState.startDist / dist);
  3374. const factor = targetWidth / Math.max(state.viewBox.width, 0.001);
  3375. zoomAt(factor, state.pinchState.midX, state.pinchState.midY, 0);
  3376. return;
  3377. }
  3378. }
  3379. if (state.boxZoomDrag && state.boxZoomDrag.pointerId === event.pointerId) {
  3380. state.boxZoomDrag.curClientX = event.clientX;
  3381. state.boxZoomDrag.curClientY = event.clientY;
  3382. const rect = state.boxZoomDrag.viewportRect;
  3383. const x1 = Math.min(state.boxZoomDrag.startClientX, event.clientX) - rect.left;
  3384. const y1 = Math.min(state.boxZoomDrag.startClientY, event.clientY) - rect.top;
  3385. const w = Math.abs(event.clientX - state.boxZoomDrag.startClientX);
  3386. const h = Math.abs(event.clientY - state.boxZoomDrag.startClientY);
  3387. const marquee = dom["box-zoom-marquee"];
  3388. if (marquee && (w > 5 || h > 5)) {
  3389. marquee.hidden = false;
  3390. marquee.style.left = `${Math.max(0, x1)}px`;
  3391. marquee.style.top = `${Math.max(0, y1)}px`;
  3392. marquee.style.width = `${w}px`;
  3393. marquee.style.height = `${h}px`;
  3394. }
  3395. return;
  3396. }
  3397. if (state.dragging && state.dragging.pointerId === event.pointerId) {
  3398. const dx = event.clientX - state.dragging.x;
  3399. const dy = event.clientY - state.dragging.y;
  3400. if (!state.dragging.moved && Math.hypot(dx, dy) > 4) {
  3401. state.dragging.moved = true;
  3402. hideTooltip();
  3403. dom["board-svg"].classList.add("is-panning");
  3404. }
  3405. if (state.dragging.moved) {
  3406. state.viewBox = {
  3407. ...state.dragging.viewBox,
  3408. x: state.dragging.viewBox.x - dx * state.dragging.scaleX,
  3409. y: state.dragging.viewBox.y - dy * state.dragging.scaleY,
  3410. };
  3411. clampViewBox();
  3412. scheduleViewBoxUpdate();
  3413. }
  3414. return;
  3415. }
  3416. // O(1) Rust WASM spatial grid hover hit-test
  3417. const hit = hitTestBoardAt(event.clientX, event.clientY);
  3418. if (!hit) {
  3419. dom["board-svg"].style.cursor = state.boxZoomMode ? "crosshair" : "";
  3420. hideTooltip();
  3421. return;
  3422. }
  3423. dom["board-svg"].style.cursor = state.boxZoomMode ? "crosshair" : "pointer";
  3424. let key = "";
  3425. if (hit.kind === "pin") {
  3426. key = `pin:${hit.touchpoint.reference}:${hit.pin.id || hit.pin.number}`;
  3427. if (state.hoverTargetKey !== key) {
  3428. state.hoverTargetKey = key;
  3429. showPinTooltip(event, hit.touchpoint, hit.pin);
  3430. } else {
  3431. positionTooltip(event);
  3432. }
  3433. } else if (hit.kind === "touchpoint") {
  3434. key = `tp:${hit.touchpoint.reference}`;
  3435. if (state.hoverTargetKey !== key) {
  3436. state.hoverTargetKey = key;
  3437. showTouchpointTooltip(event, hit.touchpoint);
  3438. } else {
  3439. positionTooltip(event);
  3440. }
  3441. } else if (hit.kind === "resistor_pad") {
  3442. key = `rpad:${hit.resistor.reference}:${hit.pad.number}`;
  3443. if (state.hoverTargetKey !== key) {
  3444. state.hoverTargetKey = key;
  3445. showResistorPadTooltip(event, hit.resistor, hit.pad);
  3446. } else {
  3447. positionTooltip(event);
  3448. }
  3449. } else if (hit.kind === "resistor") {
  3450. key = `res:${hit.resistor.reference}`;
  3451. if (state.hoverTargetKey !== key) {
  3452. state.hoverTargetKey = key;
  3453. showResistorTooltip(event, hit.resistor);
  3454. } else {
  3455. positionTooltip(event);
  3456. }
  3457. }
  3458. });
  3459. dom["board-svg"].addEventListener("pointerleave", () => {
  3460. if (!state.dragging && !state.boxZoomDrag) {
  3461. dom["board-svg"].style.cursor = state.boxZoomMode ? "crosshair" : "";
  3462. hideTooltip();
  3463. }
  3464. });
  3465. function endPan(event) {
  3466. if (state.activeTouchPointers.has(event.pointerId)) {
  3467. state.activeTouchPointers.delete(event.pointerId);
  3468. if (state.activeTouchPointers.size < 2) {
  3469. state.pinchState = null;
  3470. }
  3471. }
  3472. if (state.boxZoomDrag && state.boxZoomDrag.pointerId === event.pointerId) {
  3473. const drag = state.boxZoomDrag;
  3474. state.boxZoomDrag = null;
  3475. if (dom["box-zoom-marquee"]) dom["box-zoom-marquee"].hidden = true;
  3476. const wPx = Math.abs(event.clientX - drag.startClientX);
  3477. const hPx = Math.abs(event.clientY - drag.startClientY);
  3478. if (wPx > 10 && hPx > 10) {
  3479. const p1 = clientToSvg(drag.startClientX, drag.startClientY);
  3480. const p2 = clientToSvg(event.clientX, event.clientY);
  3481. const minX = Math.min(p1.x, p2.x);
  3482. const minY = Math.min(p1.y, p2.y);
  3483. const boxW = Math.max(Math.abs(p2.x - p1.x), state.baseViewBox.width / 35);
  3484. const boxH = Math.max(Math.abs(p2.y - p1.y), state.baseViewBox.height / 35);
  3485. const vpAspect = Math.max(drag.viewportRect.width / Math.max(drag.viewportRect.height, 1), 1);
  3486. let targetW = boxW;
  3487. let targetH = targetW / vpAspect;
  3488. if (targetH < boxH) {
  3489. targetH = boxH;
  3490. targetW = targetH * vpAspect;
  3491. }
  3492. animateViewBoxTo(
  3493. {
  3494. x: minX + boxW * 0.5 - targetW * 0.5,
  3495. y: minY + boxH * 0.5 - targetH * 0.5,
  3496. width: targetW,
  3497. height: targetH,
  3498. },
  3499. 190,
  3500. );
  3501. if (state.boxZoomMode) setBoxZoomMode(false);
  3502. }
  3503. return;
  3504. }
  3505. if (!state.dragging || state.dragging.pointerId !== event.pointerId) return;
  3506. const wasMoved = state.dragging.moved;
  3507. state.dragging = null;
  3508. dom["board-svg"].classList.remove("is-panning");
  3509. if (!wasMoved && event.type === "pointerup") {
  3510. const hit = hitTestBoardAt(event.clientX, event.clientY);
  3511. if (hit) {
  3512. const ctrlMulti = Boolean(event.ctrlKey || event.metaKey);
  3513. if (hit.kind === "pin") selectTouchpoint(hit.touchpoint, hit.pin, true, {highlightAllSame: ctrlMulti});
  3514. else if (hit.kind === "touchpoint") selectTouchpoint(hit.touchpoint, null, true, {highlightAllSame: ctrlMulti});
  3515. else if (hit.kind === "resistor_pad") selectResistor(hit.resistor, hit.pad, true, {highlightAllSame: ctrlMulti});
  3516. else if (hit.kind === "resistor") selectResistor(hit.resistor, null, true, {highlightAllSame: ctrlMulti});
  3517. }
  3518. }
  3519. }
  3520. dom["board-svg"].addEventListener("pointerup", endPan);
  3521. dom["board-svg"].addEventListener("pointercancel", endPan);
  3522. dom["board-svg"].addEventListener("keydown", (event) => {
  3523. if (event.key === "Escape" && state.boxZoomMode) {
  3524. setBoxZoomMode(false);
  3525. return;
  3526. }
  3527. const targetHotspot = event.target?.closest?.(".hotspot");
  3528. if (targetHotspot && (event.key === "Enter" || event.key === " ")) {
  3529. event.preventDefault();
  3530. const ctrlMulti = Boolean(event.ctrlKey || event.metaKey);
  3531. const ref = targetHotspot.dataset?.reference;
  3532. if (targetHotspot.dataset?.kind === "resistor") {
  3533. const res = state.resByRef.get(ref);
  3534. if (res) selectResistor(res, null, true, {highlightAllSame: ctrlMulti});
  3535. } else {
  3536. const tp = state.tpByRef.get(ref);
  3537. if (tp) selectTouchpoint(tp, null, true, {highlightAllSame: ctrlMulti});
  3538. }
  3539. return;
  3540. }
  3541. const stepX = state.viewBox.width * 0.06;
  3542. const stepY = state.viewBox.height * 0.08;
  3543. if (event.key === "+" || event.key === "=") zoomAt(0.75, null, null, 120);
  3544. else if (event.key === "-") zoomAt(1.33, null, null, 120);
  3545. else if (event.key === "0") resetView();
  3546. else if (["ArrowLeft", "ArrowRight", "ArrowUp", "ArrowDown"].includes(event.key)) {
  3547. cancelViewBoxAnimation();
  3548. if (event.key === "ArrowLeft") state.viewBox.x -= stepX;
  3549. if (event.key === "ArrowRight") state.viewBox.x += stepX;
  3550. if (event.key === "ArrowUp") state.viewBox.y -= stepY;
  3551. if (event.key === "ArrowDown") state.viewBox.y += stepY;
  3552. clampViewBox();
  3553. scheduleViewBoxUpdate();
  3554. } else return;
  3555. event.preventDefault();
  3556. });
  3557. window.addEventListener("resize", () => {
  3558. hideTooltip();
  3559. if (window.innerWidth > 860) setDrawerCollapsed(false);
  3560. renderLayerCanvasFrame();
  3561. renderFastCanvasFrame();
  3562. renderMinimap();
  3563. });
  3564. const TERM_HELP = {
  3565. RefDes: "RefDes = Reference Designator,器件位号(如 R674、CON104)。",
  3566. Net: "Net = 电气网络名;同网成员按 PCB pad.net / pin.net 索引。裸 PUL1 若精确等于现有网络名,按 exact net 处理。",
  3567. Pad: "Pad = 焊盘;电阻可用 R674.1 精确查询某个焊盘。",
  3568. PCB: "PCB = 印制电路板;本查看器的电阻实体只来自 PCB footprint。",
  3569. BRD: "BRD = Allegro 板文件原件;默认分析包不打包 raw BRD。",
  3570. FPGA: "FPGA = Field-Programmable Gate Array,现场可编程门阵列(本板 U3)。",
  3571. MCU: "MCU = Microcontroller Unit,微控制器。",
  3572. GPIO: "GPIO = General-Purpose Input/Output,通用输入输出。",
  3573. PWM: "PWM = Pulse-Width Modulation,脉冲宽度调制。",
  3574. UART: "UART = Universal Asynchronous Receiver/Transmitter,异步串行收发。",
  3575. ADC: "此处 .adc 是 Anlogic Design Constraint 管脚约束文件,不是模数转换器。",
  3576. JTAG: "JTAG = Joint Test Action Group,边界扫描/调试接口。",
  3577. CON: "CON = Connector,连接器座子位号前缀。",
  3578. TP: "TP = Test Point,测试点。",
  3579. PL: "PL = Plug/socket style header,插座类位号前缀。",
  3580. };
  3581. document.querySelector(".search-help")?.addEventListener("click", (event) => {
  3582. const chip = event.target.closest?.(".help-chip");
  3583. if (chip?.dataset?.query) {
  3584. dom["board-search"].value = chip.dataset.query;
  3585. renderSearchResults(chip.dataset.query);
  3586. dom["board-search"].focus();
  3587. return;
  3588. }
  3589. const term = event.target.closest?.(".term");
  3590. if (term?.dataset?.term) {
  3591. const message = TERM_HELP[term.dataset.term] || term.dataset.term;
  3592. dom["stale-banner"].hidden = false;
  3593. dom["stale-banner"].textContent = message;
  3594. window.setTimeout(() => {
  3595. if (dom["stale-banner"].textContent === message) {
  3596. dom["stale-banner"].hidden = true;
  3597. }
  3598. }, 6000);
  3599. }
  3600. });
  3601. setDrawerCollapsed(window.innerWidth <= 860);
  3602. const urlParams = new URLSearchParams(window.location.search);
  3603. const reqVer = urlParams.get("version");
  3604. const reqTab = urlParams.get("tab");
  3605. const initialVersion = ["v2_0", "v2_0_fan", "v1_2", "v1_1"].includes(reqVer) ? reqVer : "v2_0";
  3606. if (reqTab === "cpld-arch" || reqTab === "cpld") {
  3607. if (window.innerWidth > 1180) setWidePanel(true);
  3608. switchTab("cpld-arch");
  3609. } else if (reqTab === "peripheral") {
  3610. switchTab("peripheral");
  3611. }
  3612. loadApplication(initialVersion);