visualize_match_graph.py 128 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167
  1. #!/usr/bin/env python3
  2. # -*- coding: utf-8 -*-
  3. """
  4. 将匹配图谱数据可视化为交互式HTML文件
  5. 输入:match_graph目录下的JSON文件
  6. 输出:单个HTML文件,包含所有帖子的图谱,可通过Tab切换
  7. """
  8. import json
  9. from pathlib import Path
  10. from typing import Dict, List
  11. import sys
  12. # 添加项目根目录到路径
  13. project_root = Path(__file__).parent.parent.parent
  14. sys.path.insert(0, str(project_root))
  15. from script.data_processing.path_config import PathConfig
  16. HTML_TEMPLATE = '''<!DOCTYPE html>
  17. <html lang="zh-CN">
  18. <head>
  19. <meta charset="UTF-8">
  20. <meta name="viewport" content="width=device-width, initial-scale=1.0">
  21. <title>匹配图谱可视化</title>
  22. <script src="https://d3js.org/d3.v7.min.js"></script>
  23. <style>
  24. * {{
  25. margin: 0;
  26. padding: 0;
  27. box-sizing: border-box;
  28. }}
  29. body {{
  30. font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif;
  31. background: #1a1a2e;
  32. color: #eee;
  33. overflow: hidden;
  34. }}
  35. /* 自定义滚动条 */
  36. ::-webkit-scrollbar {{
  37. width: 6px;
  38. height: 6px;
  39. }}
  40. ::-webkit-scrollbar-track {{
  41. background: transparent;
  42. }}
  43. ::-webkit-scrollbar-thumb {{
  44. background: rgba(255,255,255,0.2);
  45. border-radius: 3px;
  46. }}
  47. ::-webkit-scrollbar-thumb:hover {{
  48. background: rgba(255,255,255,0.3);
  49. }}
  50. #container {{
  51. display: flex;
  52. height: 100vh;
  53. flex-direction: column;
  54. }}
  55. /* Tab样式 */
  56. .tabs {{
  57. display: flex;
  58. background: #0f3460;
  59. padding: 0 20px;
  60. overflow-x: auto;
  61. flex-shrink: 0;
  62. }}
  63. .tab {{
  64. padding: 12px 20px;
  65. cursor: pointer;
  66. border-bottom: 3px solid transparent;
  67. white-space: nowrap;
  68. font-size: 13px;
  69. color: #888;
  70. transition: all 0.2s;
  71. }}
  72. .tab:hover {{
  73. color: #fff;
  74. background: rgba(255,255,255,0.05);
  75. }}
  76. .tab.active {{
  77. color: #e94560;
  78. border-bottom-color: #e94560;
  79. background: rgba(233, 69, 96, 0.1);
  80. }}
  81. /* 主内容区 */
  82. .main-content {{
  83. display: flex;
  84. flex: 1;
  85. overflow: hidden;
  86. }}
  87. #left-panel {{
  88. width: 420px;
  89. display: flex;
  90. flex-direction: column;
  91. background: #1a1a2e;
  92. border-right: 1px solid #0f3460;
  93. }}
  94. #tree-container {{
  95. flex: 1;
  96. overflow-y: auto;
  97. overflow-x: hidden;
  98. }}
  99. #tree-container svg {{
  100. display: block;
  101. }}
  102. #ego-container {{
  103. height: 420px;
  104. border-top: 1px solid #0f3460;
  105. display: none;
  106. }}
  107. #ego-container svg {{
  108. display: block;
  109. }}
  110. #graph {{
  111. flex: 1;
  112. position: relative;
  113. overflow: auto;
  114. }}
  115. #sidebar {{
  116. width: 300px;
  117. background: #16213e;
  118. padding: 15px;
  119. overflow-y: auto;
  120. border-left: 1px solid #0f3460;
  121. display: flex;
  122. flex-direction: column;
  123. }}
  124. .match-list-panel {{
  125. margin-bottom: 15px;
  126. border-bottom: 1px solid #0f3460;
  127. padding-bottom: 10px;
  128. }}
  129. .match-list-panel h3 {{
  130. font-size: 13px;
  131. margin-bottom: 8px;
  132. color: #e94560;
  133. }}
  134. .match-list {{
  135. max-height: 200px;
  136. overflow-y: auto;
  137. }}
  138. .match-item {{
  139. display: flex;
  140. align-items: center;
  141. padding: 6px 8px;
  142. margin-bottom: 4px;
  143. background: rgba(233, 69, 96, 0.1);
  144. border-radius: 4px;
  145. cursor: pointer;
  146. font-size: 11px;
  147. gap: 8px;
  148. }}
  149. .match-item:hover {{
  150. background: rgba(233, 69, 96, 0.2);
  151. }}
  152. .match-item.active {{
  153. background: rgba(233, 69, 96, 0.3);
  154. border: 1px solid #e94560;
  155. }}
  156. .match-item .score {{
  157. background: #e94560;
  158. color: #fff;
  159. padding: 2px 6px;
  160. border-radius: 3px;
  161. font-weight: bold;
  162. min-width: 40px;
  163. text-align: center;
  164. }}
  165. .match-item .score.high {{
  166. background: #27ae60;
  167. }}
  168. .match-item .score.medium {{
  169. background: #f39c12;
  170. }}
  171. .match-item .names {{
  172. flex: 1;
  173. overflow: hidden;
  174. text-overflow: ellipsis;
  175. white-space: nowrap;
  176. }}
  177. #persona-tree-panel {{
  178. flex: 1;
  179. overflow-y: auto;
  180. margin-top: 15px;
  181. border-top: 1px solid #0f3460;
  182. padding-top: 10px;
  183. }}
  184. .tree-dimension {{
  185. margin-bottom: 15px;
  186. }}
  187. .tree-dimension-title {{
  188. font-size: 12px;
  189. font-weight: bold;
  190. padding: 5px 8px;
  191. border-radius: 4px;
  192. margin-bottom: 5px;
  193. cursor: pointer;
  194. display: flex;
  195. align-items: center;
  196. gap: 5px;
  197. }}
  198. .tree-dimension-title:hover {{
  199. opacity: 0.8;
  200. }}
  201. .tree-dimension-title .toggle {{
  202. font-size: 10px;
  203. transition: transform 0.2s;
  204. }}
  205. .tree-dimension-title.collapsed .toggle {{
  206. transform: rotate(-90deg);
  207. }}
  208. .tree-dimension.inspiration .tree-dimension-title {{
  209. background: rgba(243, 156, 18, 0.2);
  210. color: #f39c12;
  211. }}
  212. .tree-dimension.purpose .tree-dimension-title {{
  213. background: rgba(52, 152, 219, 0.2);
  214. color: #3498db;
  215. }}
  216. .tree-dimension.key .tree-dimension-title {{
  217. background: rgba(155, 89, 182, 0.2);
  218. color: #9b59b6;
  219. }}
  220. .tree-list {{
  221. list-style: none;
  222. padding-left: 0;
  223. margin: 0;
  224. font-size: 11px;
  225. }}
  226. .tree-list.collapsed {{
  227. display: none;
  228. }}
  229. .tree-item {{
  230. padding: 3px 0;
  231. color: #aaa;
  232. cursor: pointer;
  233. border-radius: 3px;
  234. padding: 3px 6px;
  235. margin: 1px 0;
  236. }}
  237. .tree-item:hover {{
  238. background: rgba(255,255,255,0.08);
  239. color: #fff;
  240. }}
  241. .tree-item.matched {{
  242. color: #2ecc71;
  243. font-weight: 500;
  244. }}
  245. .tree-item .indent {{
  246. display: inline-block;
  247. width: 12px;
  248. color: #555;
  249. }}
  250. h1 {{
  251. font-size: 15px;
  252. margin-bottom: 10px;
  253. color: #e94560;
  254. }}
  255. h2 {{
  256. font-size: 12px;
  257. margin: 10px 0 6px;
  258. color: #0f9b8e;
  259. }}
  260. .legend {{
  261. margin-top: 10px;
  262. }}
  263. .legend-grid {{
  264. display: grid;
  265. grid-template-columns: 1fr 1fr;
  266. gap: 4px 8px;
  267. }}
  268. .legend-item {{
  269. display: flex;
  270. align-items: center;
  271. font-size: 11px;
  272. }}
  273. .legend-color {{
  274. width: 12px;
  275. height: 12px;
  276. border-radius: 50%;
  277. margin-right: 6px;
  278. flex-shrink: 0;
  279. }}
  280. .legend-line {{
  281. width: 20px;
  282. height: 3px;
  283. margin-right: 6px;
  284. flex-shrink: 0;
  285. }}
  286. .detail-panel {{
  287. margin-top: 20px;
  288. padding: 15px;
  289. background: #0f3460;
  290. border-radius: 8px;
  291. display: none;
  292. }}
  293. .detail-panel.active {{
  294. display: block;
  295. }}
  296. .detail-panel h3 {{
  297. font-size: 14px;
  298. margin-bottom: 10px;
  299. color: #e94560;
  300. }}
  301. .detail-panel p {{
  302. font-size: 12px;
  303. line-height: 1.6;
  304. color: #ccc;
  305. margin: 5px 0;
  306. }}
  307. .detail-panel .label {{
  308. color: #888;
  309. }}
  310. .detail-panel .close-btn {{
  311. position: absolute;
  312. top: 10px;
  313. right: 10px;
  314. background: none;
  315. border: none;
  316. color: #888;
  317. cursor: pointer;
  318. font-size: 16px;
  319. }}
  320. .detail-panel .close-btn:hover {{
  321. color: #e94560;
  322. }}
  323. .detail-panel-wrapper {{
  324. position: relative;
  325. }}
  326. .similarity-score {{
  327. background: #e94560;
  328. color: #fff;
  329. padding: 2px 6px;
  330. border-radius: 4px;
  331. font-weight: bold;
  332. }}
  333. .edge-description {{
  334. background: #1a1a2e;
  335. padding: 10px;
  336. border-radius: 4px;
  337. margin-top: 8px;
  338. font-size: 11px;
  339. line-height: 1.5;
  340. }}
  341. .edge-list {{
  342. background: #1a1a2e;
  343. padding: 8px;
  344. border-radius: 4px;
  345. margin-top: 4px;
  346. font-size: 11px;
  347. }}
  348. .edge-type-item {{
  349. display: flex;
  350. justify-content: space-between;
  351. padding: 2px 0;
  352. border-bottom: 1px solid rgba(255,255,255,0.05);
  353. }}
  354. .edge-type {{
  355. color: #aaa;
  356. }}
  357. .edge-count {{
  358. color: #e94560;
  359. font-weight: bold;
  360. }}
  361. .edge-detail {{
  362. padding: 3px 0;
  363. color: #888;
  364. font-size: 10px;
  365. border-left: 2px solid #333;
  366. padding-left: 8px;
  367. margin: 2px 0;
  368. }}
  369. .edge-type-tag {{
  370. background: rgba(255,255,255,0.1);
  371. padding: 1px 4px;
  372. border-radius: 2px;
  373. font-size: 9px;
  374. margin-left: 4px;
  375. }}
  376. .edge-more {{
  377. color: #666;
  378. font-size: 10px;
  379. text-align: center;
  380. padding: 4px 0;
  381. }}
  382. .edge-empty {{
  383. color: #555;
  384. font-size: 10px;
  385. padding: 4px 0;
  386. }}
  387. svg {{
  388. width: 100%;
  389. display: block; /* 避免底部多余空间 */
  390. }}
  391. .node {{
  392. cursor: pointer;
  393. }}
  394. .node circle, .node rect, .node polygon {{
  395. stroke-width: 3px;
  396. }}
  397. .node .post-point-node {{
  398. stroke: #fff;
  399. stroke-width: 4px;
  400. }}
  401. .node .post-node,
  402. .node .persona-node {{
  403. stroke: #fff;
  404. }}
  405. .node text {{
  406. font-size: 11px;
  407. fill: #fff;
  408. pointer-events: none;
  409. }}
  410. .link {{
  411. stroke-opacity: 0.7;
  412. }}
  413. .link-hitarea {{
  414. stroke: transparent;
  415. stroke-width: 15px;
  416. cursor: pointer;
  417. fill: none;
  418. }}
  419. .link-hitarea:hover + .link {{
  420. stroke-opacity: 1;
  421. stroke-width: 3px;
  422. }}
  423. .edge-label {{
  424. font-size: 10px;
  425. fill: #fff;
  426. pointer-events: none;
  427. text-anchor: middle;
  428. }}
  429. .edge-label-bg {{
  430. fill: rgba(0,0,0,0.7);
  431. }}
  432. .link.match {{
  433. stroke: #e94560;
  434. stroke-dasharray: 5,5;
  435. }}
  436. .link.category-cross {{
  437. stroke: #2ecc71;
  438. }}
  439. .link.category-intra {{
  440. stroke: #3498db;
  441. }}
  442. .link.tag-cooccur {{
  443. stroke: #f39c12;
  444. }}
  445. .link.belong {{
  446. stroke: #9b59b6;
  447. }}
  448. .link.contain {{
  449. stroke: #8e44ad;
  450. stroke-dasharray: 2,2;
  451. }}
  452. /* 镜像边样式(实线,颜色与原边相同) */
  453. .link.mirror-category-cross {{
  454. stroke: #2ecc71;
  455. }}
  456. .link.mirror-category-intra {{
  457. stroke: #3498db;
  458. }}
  459. .link.mirror-tag-cooccur {{
  460. stroke: #f39c12;
  461. }}
  462. .link.mirror-belong {{
  463. stroke: #9b59b6;
  464. }}
  465. .link.mirror-contain {{
  466. stroke: #8e44ad;
  467. }}
  468. /* 二阶边现在使用与镜像边相同的样式(基于原始边类型) */
  469. /* 高亮/灰化样式 */
  470. .node.dimmed circle, .node.dimmed rect, .node.dimmed polygon {{
  471. opacity: 0.15 !important;
  472. }}
  473. .node.dimmed text {{
  474. opacity: 0.15 !important;
  475. }}
  476. .link-group.dimmed .link {{
  477. stroke-opacity: 0.08 !important;
  478. }}
  479. .link-group.dimmed .edge-label-group {{
  480. opacity: 0.15 !important;
  481. }}
  482. .node.highlighted circle, .node.highlighted rect, .node.highlighted polygon {{
  483. stroke: #fff !important;
  484. stroke-width: 4px !important;
  485. filter: drop-shadow(0 0 8px rgba(255,255,255,0.5));
  486. }}
  487. .link-group.highlighted .link {{
  488. stroke-opacity: 1 !important;
  489. stroke-width: 3px !important;
  490. filter: drop-shadow(0 0 4px rgba(255,255,255,0.3));
  491. }}
  492. .tooltip {{
  493. position: absolute;
  494. background: rgba(0,0,0,0.9);
  495. color: #fff;
  496. padding: 10px 15px;
  497. border-radius: 6px;
  498. font-size: 12px;
  499. pointer-events: none;
  500. max-width: 300px;
  501. z-index: 1000;
  502. display: none;
  503. }}
  504. .controls {{
  505. background: rgba(15, 52, 96, 0.5);
  506. padding: 12px;
  507. border-radius: 8px;
  508. margin-top: auto;
  509. border-top: 1px solid #0f3460;
  510. padding-top: 15px;
  511. }}
  512. .controls button {{
  513. background: #0f3460;
  514. color: #fff;
  515. border: none;
  516. padding: 8px 15px;
  517. margin: 5px;
  518. border-radius: 4px;
  519. cursor: pointer;
  520. font-size: 12px;
  521. }}
  522. .controls button:hover {{
  523. background: #e94560;
  524. }}
  525. .controls button.active {{
  526. background: #e94560;
  527. }}
  528. .controls .control-group {{
  529. margin-top: 10px;
  530. padding-top: 10px;
  531. border-top: 1px solid rgba(255,255,255,0.1);
  532. }}
  533. .controls .control-label {{
  534. font-size: 11px;
  535. color: #888;
  536. margin-bottom: 5px;
  537. }}
  538. .controls select {{
  539. background: #0f3460;
  540. color: #fff;
  541. border: none;
  542. padding: 6px 10px;
  543. border-radius: 4px;
  544. font-size: 12px;
  545. cursor: pointer;
  546. }}
  547. /* 关系子图节点样式 */
  548. .ego-node {{
  549. cursor: pointer;
  550. }}
  551. .ego-node circle {{
  552. stroke-width: 2px;
  553. }}
  554. .ego-node.center circle {{
  555. stroke: #fff;
  556. stroke-width: 3px;
  557. filter: drop-shadow(0 0 8px rgba(255,255,255,0.5));
  558. }}
  559. .ego-node text {{
  560. font-size: 10px;
  561. fill: #fff;
  562. pointer-events: none;
  563. }}
  564. .ego-edge {{
  565. stroke-opacity: 0.6;
  566. stroke-width: 1.5;
  567. }}
  568. </style>
  569. </head>
  570. <body>
  571. <div id="container">
  572. <div class="tabs" id="tabs">
  573. {tabs_html}
  574. </div>
  575. <div class="main-content">
  576. <div id="left-panel">
  577. <div id="tree-container"></div>
  578. <div id="ego-container"></div>
  579. </div>
  580. <div id="graph">
  581. <div class="tooltip" id="tooltip"></div>
  582. </div>
  583. <div id="sidebar">
  584. <h1>匹配图谱</h1>
  585. <div class="match-list-panel">
  586. <h3>匹配关系 <span id="matchCount">(0)</span></h3>
  587. <div id="matchList" class="match-list"></div>
  588. </div>
  589. <div class="detail-panel active" id="detailPanel">
  590. <h3 id="detailTitle">点击节点或边查看详情</h3>
  591. <div id="detailContent">
  592. <p style="color: #888; font-size: 11px;">点击图中的节点或边,这里会显示详细信息</p>
  593. </div>
  594. </div>
  595. <div class="legend">
  596. <h2>节点</h2>
  597. <div class="legend-grid">
  598. <div class="legend-item">
  599. <div class="legend-color" style="background: #f39c12; border: 2px solid #fff;"></div>
  600. <span>灵感点</span>
  601. </div>
  602. <div class="legend-item">
  603. <div class="legend-color" style="background: #3498db; border: 2px solid #fff;"></div>
  604. <span>目的点</span>
  605. </div>
  606. <div class="legend-item">
  607. <div class="legend-color" style="background: #9b59b6; border: 2px solid #fff;"></div>
  608. <span>关键点</span>
  609. </div>
  610. </div>
  611. <h2>边</h2>
  612. <div class="legend-grid">
  613. <div class="legend-item">
  614. <div class="legend-line" style="background: #e94560;"></div>
  615. <span>匹配</span>
  616. </div>
  617. <div class="legend-item">
  618. <div class="legend-line" style="background: #9b59b6;"></div>
  619. <span>属于</span>
  620. </div>
  621. <div class="legend-item">
  622. <div class="legend-line" style="background: #2ecc71;"></div>
  623. <span>分类共现(跨)</span>
  624. </div>
  625. <div class="legend-item">
  626. <div class="legend-line" style="background: #3498db;"></div>
  627. <span>分类共现(内)</span>
  628. </div>
  629. <div class="legend-item">
  630. <div class="legend-line" style="background: #f39c12;"></div>
  631. <span>标签共现</span>
  632. </div>
  633. </div>
  634. </div>
  635. <div class="controls">
  636. <div class="control-label">视图控制</div>
  637. <button onclick="resetZoom()">重置视图</button>
  638. <button onclick="toggleLabels()">切换标签</button>
  639. <button onclick="toggleCrossLayerEdges()" id="crossLayerBtn">显示跨层边</button>
  640. <div class="control-group">
  641. <div class="control-label">人设树配置</div>
  642. <button onclick="toggleTreeTags()" id="treeTagBtn" class="active">显示标签</button>
  643. <select id="treeDepthSelect" onchange="setTreeDepth(this.value)">
  644. <option value="0">全部层级</option>
  645. <option value="2">2层</option>
  646. <option value="3">3层</option>
  647. <option value="4">4层</option>
  648. <option value="5">5层</option>
  649. </select>
  650. </div>
  651. </div>
  652. </div>
  653. </div>
  654. </div>
  655. <script>
  656. // 所有帖子的图谱数据
  657. const allGraphData = {all_graph_data};
  658. // 完整的人设树数据(所有人设节点和属于边)
  659. const personaTreeData = {persona_tree_data};
  660. // 当前选中的帖子索引
  661. let currentIndex = 0;
  662. let simulation = null;
  663. let svg = null;
  664. let g = null;
  665. let treeSvg = null; // 人设树独立SVG
  666. let treeG = null; // 人设树group
  667. let egoSvg = null; // 关系图独立SVG
  668. let egoG = null; // 关系图group
  669. let zoom = null;
  670. let showLabels = true;
  671. let showCrossLayerEdges = false; // 跨层边默认隐藏
  672. let isCrossLayerEdge = null; // 跨层边判断函数(在renderGraph中设置)
  673. // 人设树配置
  674. let showTreeTags = true; // 是否显示标签节点
  675. let treeMaxDepth = 0; // 显示的最大层数(0=全部)
  676. // 切换标签显示
  677. function toggleTreeTags() {{
  678. showTreeTags = !showTreeTags;
  679. const btn = document.getElementById("treeTagBtn");
  680. btn.textContent = showTreeTags ? "显示标签" : "隐藏标签";
  681. btn.classList.toggle("active", showTreeTags);
  682. // 重新渲染当前图谱
  683. renderGraph(allGraphData[currentIndex]);
  684. }}
  685. // 设置树的显示层数
  686. function setTreeDepth(depth) {{
  687. treeMaxDepth = parseInt(depth);
  688. // 重新渲染当前图谱
  689. renderGraph(allGraphData[currentIndex]);
  690. }}
  691. // 初始化
  692. function init() {{
  693. const container = document.getElementById("graph");
  694. const treeContainer = document.getElementById("tree-container");
  695. const width = container.clientWidth;
  696. const height = container.clientHeight;
  697. // 创建圆形层SVG
  698. svg = d3.select("#graph")
  699. .append("svg")
  700. .attr("width", width)
  701. .attr("height", height);
  702. g = svg.append("g");
  703. zoom = d3.zoom()
  704. .scaleExtent([0.1, 4])
  705. .on("zoom", (event) => {{
  706. g.attr("transform", event.transform);
  707. }});
  708. svg.call(zoom);
  709. // 创建人设树SVG(独立可滚动)
  710. treeSvg = d3.select("#tree-container")
  711. .append("svg")
  712. .attr("width", 400);
  713. treeG = treeSvg.append("g");
  714. // 创建关系图SVG(在独立的ego-container中)
  715. egoSvg = d3.select("#ego-container")
  716. .append("svg")
  717. .attr("width", 400)
  718. .attr("height", 400);
  719. egoG = egoSvg.append("g");
  720. // 关系图缩放
  721. const egoZoom = d3.zoom()
  722. .scaleExtent([0.3, 3])
  723. .on("zoom", (event) => {{
  724. egoG.attr("transform", event.transform);
  725. }});
  726. egoSvg.call(egoZoom);
  727. // 绑定Tab点击事件
  728. document.querySelectorAll(".tab").forEach((tab, index) => {{
  729. tab.addEventListener("click", () => switchTab(index));
  730. }});
  731. // 显示第一个帖子
  732. switchTab(0);
  733. }}
  734. // 构建人设树数据(合并为一棵树,根节点为"人设")
  735. // showTreeTags: 控制是否显示标签节点
  736. // treeMaxDepth: 控制树的显示深度(0=全部,2=维度,3=+一层,4=+两层...)
  737. function buildPersonaTreeData() {{
  738. const dimensions = ["灵感点", "目的点", "关键点"];
  739. const dimColors = {{ "灵感点": "#f39c12", "目的点": "#3498db", "关键点": "#9b59b6" }};
  740. const dimensionChildren = [];
  741. let totalNodeCount = 0;
  742. dimensions.forEach(dim => {{
  743. // 根据 showTreeTags 过滤节点(独立于深度控制)
  744. let dimNodes = personaTreeData.nodes.filter(n => n.节点层级 === dim);
  745. if (!showTreeTags) {{
  746. dimNodes = dimNodes.filter(n => n.节点类型 !== "标签");
  747. }}
  748. if (dimNodes.length === 0) {{
  749. const dimNode = {{
  750. name: dim,
  751. 节点名称: dim,
  752. isDimension: true,
  753. dimColor: dimColors[dim],
  754. children: []
  755. }};
  756. dimensionChildren.push(dimNode);
  757. return;
  758. }}
  759. const nodeMap = {{}};
  760. dimNodes.forEach(n => nodeMap[n.节点ID] = {{ ...n, name: n.节点名称, children: [], dimColor: dimColors[dim] }});
  761. // 只用属于边构建父子关系
  762. const hierarchyEdgeTypes = ["属于"];
  763. const hasParent = new Set();
  764. personaTreeData.edges.forEach(e => {{
  765. if (!hierarchyEdgeTypes.includes(e.边类型)) return; // 跳过非层级边
  766. const srcNode = nodeMap[e.源节点ID];
  767. const tgtNode = nodeMap[e.目标节点ID];
  768. if (srcNode && tgtNode) {{
  769. tgtNode.children.push(srcNode);
  770. hasParent.add(e.源节点ID);
  771. }}
  772. }});
  773. const roots = dimNodes.filter(n => !hasParent.has(n.节点ID)).map(n => nodeMap[n.节点ID]);
  774. const dimNode = {{
  775. name: dim,
  776. 节点名称: dim,
  777. isDimension: true,
  778. dimColor: dimColors[dim],
  779. children: roots
  780. }};
  781. dimensionChildren.push(dimNode);
  782. totalNodeCount += dimNodes.length;
  783. }});
  784. // 根节点"人设"
  785. const rootNode = {{
  786. name: "人设",
  787. 节点名称: "人设",
  788. isRoot: true,
  789. children: dimensionChildren
  790. }};
  791. // 根据 treeMaxDepth 截断树深度(0=全部)
  792. // 深度1=根,深度2=维度,深度3+=子节点
  793. if (treeMaxDepth > 0) {{
  794. truncateTree(rootNode, 1, treeMaxDepth);
  795. }}
  796. return {{ root: rootNode, nodeCount: totalNodeCount }};
  797. }}
  798. // 递归截断树的深度
  799. function truncateTree(node, currentDepth, maxDepth) {{
  800. if (currentDepth >= maxDepth) {{
  801. node.children = [];
  802. return;
  803. }}
  804. if (node.children) {{
  805. node.children.forEach(child => truncateTree(child, currentDepth + 1, maxDepth));
  806. }}
  807. }}
  808. // 切换Tab
  809. function switchTab(index) {{
  810. currentIndex = index;
  811. // 更新Tab样式
  812. document.querySelectorAll(".tab").forEach((tab, i) => {{
  813. tab.classList.toggle("active", i === index);
  814. }});
  815. // 更新图谱
  816. renderGraph(allGraphData[index]);
  817. }}
  818. // 渲染图谱
  819. function renderGraph(data) {{
  820. // 清空现有图谱
  821. g.selectAll("*").remove();
  822. treeG.selectAll("*").remove();
  823. if (simulation) {{
  824. simulation.stop();
  825. }}
  826. const container = document.getElementById("graph");
  827. const width = container.clientWidth;
  828. // 布局配置:人设树在左侧独立容器,右侧是圆形层
  829. const treeAreaWidth = 400; // 固定树宽度
  830. const circleAreaWidth = width - 40;
  831. const circleAreaCenterX = circleAreaWidth / 2;
  832. // 准备数据
  833. const nodes = data.nodes.map(n => ({{
  834. ...n,
  835. id: n.节点ID,
  836. source: n.节点ID.startsWith("帖子_") ? "帖子" : "人设",
  837. level: n.节点层级
  838. }}));
  839. const links = data.edges.map(e => ({{
  840. ...e,
  841. source: e.源节点ID,
  842. target: e.目标节点ID,
  843. type: e.边类型
  844. }}));
  845. // 分离节点类型
  846. const postNodes = nodes.filter(n => n.source === "帖子");
  847. const personaNodes = nodes.filter(n => n.source === "人设" && !n.是否扩展);
  848. const expandedNodes = nodes.filter(n => n.source === "人设" && n.是否扩展);
  849. const matchLinks = links.filter(l => l.type === "匹配");
  850. // 更新匹配列表(按分数降序)
  851. updateMatchList(matchLinks, nodes);
  852. // 构建帖子节点到人设节点的映射
  853. const postToPersona = {{}};
  854. const personaToPost = {{}};
  855. matchLinks.forEach(l => {{
  856. const sid = typeof l.source === "object" ? l.source.id : l.source;
  857. const tid = typeof l.target === "object" ? l.target.id : l.target;
  858. if (!postToPersona[sid]) postToPersona[sid] = [];
  859. postToPersona[sid].push(tid);
  860. if (!personaToPost[tid]) personaToPost[tid] = [];
  861. personaToPost[tid].push(sid);
  862. }});
  863. // 找出所有连通分量
  864. function findConnectedComponents(nodes, links) {{
  865. const nodeIds = new Set(nodes.map(n => n.id));
  866. const adj = {{}};
  867. nodeIds.forEach(id => adj[id] = []);
  868. links.forEach(l => {{
  869. const sid = typeof l.source === "object" ? l.source.id : l.source;
  870. const tid = typeof l.target === "object" ? l.target.id : l.target;
  871. if (nodeIds.has(sid) && nodeIds.has(tid)) {{
  872. adj[sid].push(tid);
  873. adj[tid].push(sid);
  874. }}
  875. }});
  876. const visited = new Set();
  877. const components = [];
  878. nodeIds.forEach(startId => {{
  879. if (visited.has(startId)) return;
  880. const component = [];
  881. const queue = [startId];
  882. while (queue.length > 0) {{
  883. const id = queue.shift();
  884. if (visited.has(id)) continue;
  885. visited.add(id);
  886. component.push(id);
  887. adj[id].forEach(neighbor => {{
  888. if (!visited.has(neighbor)) queue.push(neighbor);
  889. }});
  890. }}
  891. components.push(component);
  892. }});
  893. return components;
  894. }}
  895. // 按大小排序连通分量(大的在前)
  896. const components = findConnectedComponents(nodes, links)
  897. .sort((a, b) => b.length - a.length);
  898. console.log(`找到 ${{components.length}} 个连通分量`);
  899. // 为每个节点分配连通分量ID和分量内的X范围
  900. const nodeToComponent = {{}};
  901. const componentCenters = {{}};
  902. const componentBounds = {{}};
  903. const padding = 50; // 分量之间的间距
  904. const totalPadding = padding * (components.length - 1);
  905. const availableWidth = width - totalPadding - 100; // 留边距
  906. // 根据分量大小分配宽度
  907. const totalNodes = nodes.length;
  908. let currentX = 50; // 起始边距
  909. components.forEach((comp, i) => {{
  910. const compWidth = Math.max(150, (comp.length / totalNodes) * availableWidth);
  911. const centerX = currentX + compWidth / 2;
  912. componentCenters[i] = centerX;
  913. componentBounds[i] = {{ start: currentX, end: currentX + compWidth, width: compWidth }};
  914. comp.forEach(nodeId => {{
  915. nodeToComponent[nodeId] = i;
  916. }});
  917. currentX += compWidth + padding;
  918. }});
  919. // 使用重心法(Barycenter)减少边交叉
  920. // 迭代优化:交替调整两层节点的顺序
  921. const nodeTargetX = {{}};
  922. const personaXMap = {{}};
  923. // 对每个连通分量单独处理
  924. components.forEach((comp, compIdx) => {{
  925. const bounds = componentBounds[compIdx];
  926. const compPostNodes = postNodes.filter(n => nodeToComponent[n.id] === compIdx);
  927. const compPersonaNodes = personaNodes.filter(n => nodeToComponent[n.id] === compIdx);
  928. if (compPostNodes.length === 0 || compPersonaNodes.length === 0) {{
  929. // 没有匹配关系的分量,均匀分布
  930. const spacing = bounds.width / (comp.length + 1);
  931. comp.forEach((nodeId, i) => {{
  932. const node = nodes.find(n => n.id === nodeId);
  933. if (node) {{
  934. node.x = bounds.start + spacing * (i + 1);
  935. nodeTargetX[nodeId] = node.x;
  936. if (node.source === "人设") personaXMap[nodeId] = node.x;
  937. }}
  938. }});
  939. return;
  940. }}
  941. // 初始化:给人设节点一个初始顺序
  942. let personaOrder = compPersonaNodes.map((n, i) => ({{ node: n, order: i }}));
  943. // 迭代优化(3轮)
  944. for (let iter = 0; iter < 3; iter++) {{
  945. // 1. 根据人设节点位置,计算帖子节点的重心
  946. const postBarycenter = {{}};
  947. compPostNodes.forEach(pn => {{
  948. const matched = postToPersona[pn.id] || [];
  949. if (matched.length > 0) {{
  950. const avgOrder = matched.reduce((sum, pid) => {{
  951. const po = personaOrder.find(p => p.node.id === pid);
  952. return sum + (po ? po.order : 0);
  953. }}, 0) / matched.length;
  954. postBarycenter[pn.id] = avgOrder;
  955. }} else {{
  956. postBarycenter[pn.id] = 0;
  957. }}
  958. }});
  959. // 按重心排序帖子节点
  960. const sortedPosts = [...compPostNodes].sort((a, b) =>
  961. postBarycenter[a.id] - postBarycenter[b.id]
  962. );
  963. // 2. 根据帖子节点位置,重新计算人设节点的重心
  964. const personaBarycenter = {{}};
  965. compPersonaNodes.forEach(pn => {{
  966. const matched = personaToPost[pn.id] || [];
  967. if (matched.length > 0) {{
  968. const avgOrder = matched.reduce((sum, pid) => {{
  969. const idx = sortedPosts.findIndex(p => p.id === pid);
  970. return sum + (idx >= 0 ? idx : 0);
  971. }}, 0) / matched.length;
  972. personaBarycenter[pn.id] = avgOrder;
  973. }} else {{
  974. personaBarycenter[pn.id] = personaOrder.find(p => p.node.id === pn.id)?.order || 0;
  975. }}
  976. }});
  977. // 更新人设节点顺序
  978. personaOrder = compPersonaNodes
  979. .map(n => ({{ node: n, order: personaBarycenter[n.id] }}))
  980. .sort((a, b) => a.order - b.order)
  981. .map((item, i) => ({{ node: item.node, order: i }}));
  982. }}
  983. // 最终排序
  984. const finalPersonaOrder = personaOrder.map(p => p.node);
  985. const postBarycenter = {{}};
  986. compPostNodes.forEach(pn => {{
  987. const matched = postToPersona[pn.id] || [];
  988. if (matched.length > 0) {{
  989. const avgOrder = matched.reduce((sum, pid) => {{
  990. const idx = finalPersonaOrder.findIndex(n => n.id === pid);
  991. return sum + (idx >= 0 ? idx : 0);
  992. }}, 0) / matched.length;
  993. postBarycenter[pn.id] = avgOrder;
  994. }} else {{
  995. postBarycenter[pn.id] = 0;
  996. }}
  997. }});
  998. const finalPostOrder = [...compPostNodes].sort((a, b) =>
  999. postBarycenter[a.id] - postBarycenter[b.id]
  1000. );
  1001. // 设置位置
  1002. const personaSpacing = bounds.width / (finalPersonaOrder.length + 1);
  1003. finalPersonaOrder.forEach((n, i) => {{
  1004. n.x = bounds.start + personaSpacing * (i + 1);
  1005. nodeTargetX[n.id] = n.x;
  1006. personaXMap[n.id] = n.x;
  1007. }});
  1008. const postSpacing = bounds.width / (finalPostOrder.length + 1);
  1009. finalPostOrder.forEach((n, i) => {{
  1010. // 帖子节点用重心位置(匹配人设的平均X)
  1011. const matched = postToPersona[n.id] || [];
  1012. if (matched.length > 0) {{
  1013. const avgX = matched.reduce((sum, pid) => sum + (personaXMap[pid] || bounds.start + bounds.width/2), 0) / matched.length;
  1014. n.x = avgX;
  1015. }} else {{
  1016. n.x = bounds.start + postSpacing * (i + 1);
  1017. }}
  1018. nodeTargetX[n.id] = n.x;
  1019. }});
  1020. }});
  1021. // 节点颜色
  1022. const levelColors = {{
  1023. "灵感点": "#f39c12",
  1024. "目的点": "#3498db",
  1025. "关键点": "#9b59b6"
  1026. }};
  1027. // 获取节点的层级编号(三层结构)
  1028. function getNodeLayer(d) {{
  1029. if (d.source === "帖子") {{
  1030. return d.节点类型 === "点" ? 0 : 1; // 点=0, 标签=1
  1031. }}
  1032. return 2; // 人设(标签+分类)都在层2
  1033. }}
  1034. // 统计每层节点数量(三层结构)
  1035. const layerCounts = {{0: 0, 1: 0, 2: 0}};
  1036. nodes.forEach(n => {{
  1037. const layer = getNodeLayer(n);
  1038. layerCounts[layer]++;
  1039. }});
  1040. console.log("每层节点数:", layerCounts);
  1041. // 根据节点数量计算每层圆的半径
  1042. // 左列:帖子标签(上) + 人设匹配(下),右列:帖子点(同一行开始)
  1043. // 左列是主要展示区域,视图中心对准左列
  1044. const minRadius = 80;
  1045. const maxRadius = Math.min(circleAreaWidth / 3 - 20, 180);
  1046. const nodeSpacing = 60;
  1047. function calcRadius(nodeCount) {{
  1048. if (nodeCount <= 1) return minRadius;
  1049. const circumference = nodeCount * nodeSpacing;
  1050. const r = circumference / (2 * Math.PI);
  1051. return Math.max(minRadius, Math.min(maxRadius, r));
  1052. }}
  1053. const layerRadius = {{
  1054. 0: calcRadius(layerCounts[0]), // 帖子点(右列)
  1055. 1: calcRadius(layerCounts[1]), // 帖子标签(左上)
  1056. 2: calcRadius(layerCounts[2]) // 人设匹配(左下)
  1057. }};
  1058. console.log("每层半径:", layerRadius);
  1059. // 获取人设树数据(单棵树)
  1060. const personaTree = buildPersonaTreeData();
  1061. // 树高度自适应:根据节点数量,每个节点约12px,最小800
  1062. const treeHeight = Math.max(800, personaTree.nodeCount * 12 + 150);
  1063. // 关系图配置(放在树下方)
  1064. const egoRadius = 180;
  1065. const egoAreaHeight = egoRadius * 2 + 80;
  1066. // 计算布局:左列(帖子标签+人设匹配),右列(帖子点)
  1067. const layerPadding = 40;
  1068. const leftColHeight = layerRadius[1] * 2 + layerPadding + layerRadius[2] * 2 + layerPadding;
  1069. const circleHeight = leftColHeight;
  1070. const height = Math.max(circleHeight + 80, treeHeight + 80, container.clientHeight);
  1071. // 计算每层圆心坐标
  1072. const layerCenterX = {{}};
  1073. const layerCenterY = {{}};
  1074. // 左列居中显示,右列在旁边
  1075. const leftColX = circleAreaCenterX; // 左列居中
  1076. const rightColX = leftColX + Math.max(layerRadius[1], layerRadius[2]) + layerPadding + layerRadius[0] + 30; // 右列在右边
  1077. // 左列:帖子标签(上)+ 人设匹配(下)
  1078. layerCenterX[1] = leftColX;
  1079. layerCenterY[1] = layerRadius[1] + layerPadding / 2 + 20;
  1080. layerCenterX[2] = leftColX;
  1081. layerCenterY[2] = layerCenterY[1] + layerRadius[1] + layerPadding + layerRadius[2];
  1082. // 右列:帖子点(与帖子标签同一行开始)
  1083. layerCenterX[0] = rightColX;
  1084. layerCenterY[0] = layerCenterY[1]; // 与帖子标签同一行
  1085. console.log("每层圆心X:", layerCenterX);
  1086. console.log("每层圆心Y:", layerCenterY);
  1087. // 更新SVG高度
  1088. svg.attr("height", height);
  1089. // 获取节点的基准Y(层圆心)
  1090. function getNodeBaseY(d) {{
  1091. const layer = getNodeLayer(d);
  1092. return layerCenterY[layer];
  1093. }}
  1094. // 获取节点的基准X(层圆心)
  1095. function getNodeBaseX(d) {{
  1096. const layer = getNodeLayer(d);
  1097. return layerCenterX[layer];
  1098. }}
  1099. // 层边界配置(不再使用)
  1100. const layerBounds = {{}};
  1101. // 自定义层内排斥力(只对同层节点生效,尽量分散)
  1102. function forceIntraLayerRepulsion(strength) {{
  1103. let nodes;
  1104. function force(alpha) {{
  1105. for (let i = 0; i < nodes.length; i++) {{
  1106. const nodeA = nodes[i];
  1107. const layerA = getNodeLayer(nodeA);
  1108. for (let j = i + 1; j < nodes.length; j++) {{
  1109. const nodeB = nodes[j];
  1110. const layerB = getNodeLayer(nodeB);
  1111. // 只对同层节点施加排斥力
  1112. if (layerA !== layerB) continue;
  1113. const dx = nodeB.x - nodeA.x;
  1114. const dy = nodeB.y - nodeA.y;
  1115. const dist = Math.sqrt(dx * dx + dy * dy) || 1;
  1116. const minDist = 150; // 增大最小距离,让节点更分散
  1117. if (dist < minDist) {{
  1118. // 排斥力随距离衰减,但基础强度更大
  1119. const pushStrength = strength * alpha * (minDist - dist) / dist * 2;
  1120. const px = dx * pushStrength;
  1121. const py = dy * pushStrength;
  1122. nodeA.vx -= px;
  1123. nodeA.vy -= py;
  1124. nodeB.vx += px;
  1125. nodeB.vy += py;
  1126. }}
  1127. }}
  1128. }}
  1129. }}
  1130. force.initialize = function(_) {{
  1131. nodes = _;
  1132. }};
  1133. return force;
  1134. }}
  1135. // 层圆的半径(使用动态计算的 layerRadius)
  1136. // layerRadius 和 layerCenterY 已在前面定义
  1137. // 层边界约束力(把节点限制在层内)
  1138. function forceLayerBoundary() {{
  1139. let nodes;
  1140. function force(alpha) {{
  1141. nodes.forEach(node => {{
  1142. const layer = getNodeLayer(node);
  1143. const centerX = layerCenterX[layer];
  1144. const centerY = layerCenterY[layer];
  1145. // 使用圆形边界
  1146. const maxRadius = layerRadius[layer] - 15;
  1147. // 计算到圆心的距离
  1148. const dx = node.x - centerX;
  1149. const dy = node.y - centerY;
  1150. const dist = Math.sqrt(dx * dx + dy * dy);
  1151. // 如果超出圆形边界,拉回来
  1152. if (dist > maxRadius) {{
  1153. const scale = maxRadius / dist;
  1154. node.x = centerX + dx * scale;
  1155. node.y = centerY + dy * scale;
  1156. // 阻止继续向外运动
  1157. const angle = Math.atan2(dy, dx);
  1158. const vOutward = node.vx * Math.cos(angle) + node.vy * Math.sin(angle);
  1159. if (vOutward > 0) {{
  1160. node.vx -= vOutward * Math.cos(angle);
  1161. node.vy -= vOutward * Math.sin(angle);
  1162. }}
  1163. }}
  1164. }});
  1165. }}
  1166. force.initialize = function(_) {{
  1167. nodes = _;
  1168. }};
  1169. return force;
  1170. }}
  1171. // 层内圆形布局力(让同层节点围绕圆心分布)
  1172. function forceCircularLayout(strength) {{
  1173. let nodes;
  1174. function force(alpha) {{
  1175. // 按层分组(三层)
  1176. const layerNodes = {{0: [], 1: [], 2: []}};
  1177. nodes.forEach(node => {{
  1178. const layer = getNodeLayer(node);
  1179. layerNodes[layer].push(node);
  1180. }});
  1181. // 对每层计算布局
  1182. Object.entries(layerNodes).forEach(([layerIdx, layerGroup]) => {{
  1183. if (layerGroup.length === 0) return;
  1184. const layer = parseInt(layerIdx);
  1185. const centerX = layerCenterX[layer];
  1186. const centerY = layerCenterY[layer];
  1187. // 使用圆形布局
  1188. const nodeRadius = layerRadius[layer] - 20;
  1189. if (layerGroup.length === 1) {{
  1190. // 单个节点放在圆心
  1191. const node = layerGroup[0];
  1192. node.vx += (centerX - node.x) * strength * alpha;
  1193. node.vy += (centerY - node.y) * strength * alpha;
  1194. return;
  1195. }}
  1196. // 按角度排序节点(保持相对位置稳定)
  1197. layerGroup.forEach(node => {{
  1198. node._angle = Math.atan2(node.y - centerY, node.x - centerX);
  1199. }});
  1200. layerGroup.sort((a, b) => a._angle - b._angle);
  1201. // 均匀分布在圆周上
  1202. const angleStep = (2 * Math.PI) / layerGroup.length;
  1203. layerGroup.forEach((node, i) => {{
  1204. const angle = -Math.PI / 2 + i * angleStep; // 从顶部开始
  1205. const idealX = centerX + nodeRadius * Math.cos(angle);
  1206. const idealY = centerY + nodeRadius * Math.sin(angle);
  1207. node.vx += (idealX - node.x) * strength * alpha;
  1208. node.vy += (idealY - node.y) * strength * alpha;
  1209. }});
  1210. }});
  1211. }}
  1212. force.initialize = function(_) {{
  1213. nodes = _;
  1214. }};
  1215. return force;
  1216. }}
  1217. // 力导向模拟
  1218. simulation = d3.forceSimulation(nodes)
  1219. // 连线力(跨层连接)
  1220. .force("link", d3.forceLink(links).id(d => d.id)
  1221. .distance(d => {{
  1222. // 跨层连线距离
  1223. if (d.type === "匹配" || d.type === "属于") {{
  1224. return 150; // 跨层边
  1225. }}
  1226. return 60; // 同层边
  1227. }})
  1228. .strength(d => {{
  1229. // 跨层边力度弱一些,不要拉扯节点出层
  1230. if (d.type === "匹配" || d.type === "属于") {{
  1231. return 0.03;
  1232. }}
  1233. return 0.1;
  1234. }}))
  1235. // X方向:轻微拉向各层中心
  1236. .force("x", d3.forceX(d => getNodeBaseX(d)).strength(0.02))
  1237. // Y方向:轻微拉向层中心
  1238. .force("y", d3.forceY(d => getNodeBaseY(d)).strength(0.02))
  1239. // 层内碰撞检测
  1240. .force("collision", d3.forceCollide().radius(30))
  1241. // 层内排斥力(同层节点相互排斥)
  1242. .force("intraLayer", forceIntraLayerRepulsion(0.8))
  1243. // 层内布局(圆形或树状)
  1244. .force("circularLayout", forceCircularLayout(0.15))
  1245. // 层边界约束(节点不能跑出层,硬约束)
  1246. .force("boundary", forceLayerBoundary());
  1247. // 边类型到CSS类的映射
  1248. const edgeTypeClass = {{
  1249. "匹配": "match",
  1250. "分类共现(跨点)": "category-cross",
  1251. "分类共现(点内)": "category-intra",
  1252. "标签共现": "tag-cooccur",
  1253. "属于": "belong",
  1254. "包含": "contain",
  1255. // 镜像边(帖子节点之间,虚线)
  1256. "镜像_分类共现(跨点)": "mirror-category-cross",
  1257. "镜像_分类共现(点内)": "mirror-category-intra",
  1258. "镜像_标签共现": "mirror-tag-cooccur",
  1259. "镜像_属于": "mirror-belong",
  1260. "镜像_包含": "mirror-contain"
  1261. }};
  1262. // 获取边的CSS类(处理二阶边,映射到对应的镜像边样式)
  1263. function getEdgeClass(edgeType) {{
  1264. if (edgeTypeClass[edgeType]) return edgeTypeClass[edgeType];
  1265. // 二阶边映射到对应的镜像边样式(颜色相同,都用虚线)
  1266. if (edgeType.startsWith("二阶_")) {{
  1267. const originalType = edgeType.replace("二阶_", "");
  1268. const mirrorType = "镜像_" + originalType;
  1269. if (edgeTypeClass[mirrorType]) return edgeTypeClass[mirrorType];
  1270. }}
  1271. return "match";
  1272. }}
  1273. // 绘制层背景(圆形,使用动态大小)
  1274. const layerBg = g.append("g").attr("class", "layer-backgrounds");
  1275. // 层配置:名称、颜色(三层圆,关系图在左侧)
  1276. const layerConfig = [
  1277. {{ name: "帖子点", layer: 0, color: "rgba(243, 156, 18, 0.08)", stroke: "rgba(243, 156, 18, 0.3)" }},
  1278. {{ name: "帖子标签", layer: 1, color: "rgba(52, 152, 219, 0.08)", stroke: "rgba(52, 152, 219, 0.3)" }},
  1279. {{ name: "人设匹配", layer: 2, color: "rgba(155, 89, 182, 0.08)", stroke: "rgba(155, 89, 182, 0.3)" }}
  1280. ];
  1281. // 绘制三层圆形背景
  1282. layerConfig.forEach(cfg => {{
  1283. const cx = layerCenterX[cfg.layer];
  1284. const cy = layerCenterY[cfg.layer];
  1285. const r = layerRadius[cfg.layer];
  1286. layerBg.append("circle")
  1287. .attr("cx", cx)
  1288. .attr("cy", cy)
  1289. .attr("r", r)
  1290. .attr("fill", cfg.color)
  1291. .attr("stroke", cfg.stroke)
  1292. .attr("stroke-width", 2);
  1293. // 层标签(圆的左侧)
  1294. layerBg.append("text")
  1295. .attr("x", cx - r - 15)
  1296. .attr("y", cy)
  1297. .attr("dy", "0.35em")
  1298. .attr("fill", "rgba(255,255,255,0.5)")
  1299. .attr("font-size", "13px")
  1300. .attr("font-weight", "bold")
  1301. .attr("text-anchor", "end")
  1302. .text(cfg.name);
  1303. }});
  1304. // 绘制左侧人设树(在独立的treeSvg中)
  1305. const dimColors = {{ "灵感点": "#f39c12", "目的点": "#3498db", "关键点": "#9b59b6" }};
  1306. // 更新树SVG高度
  1307. treeSvg.attr("height", treeHeight + 50);
  1308. const treeGroup = treeG.append("g")
  1309. .attr("class", "persona-tree")
  1310. .attr("transform", `translate(15, 25)`);
  1311. // 设置关系图SVG
  1312. egoG.selectAll("*").remove();
  1313. const egoDisplayRadius = 180;
  1314. const egoCenterGroup = egoG.append("g")
  1315. .attr("class", "ego-center")
  1316. .attr("transform", `translate(200, 210)`);
  1317. // 关系图背景圆
  1318. egoCenterGroup.append("circle")
  1319. .attr("class", "ego-background")
  1320. .attr("r", egoDisplayRadius)
  1321. .attr("fill", "rgba(233, 69, 96, 0.08)")
  1322. .attr("stroke", "rgba(233, 69, 96, 0.3)")
  1323. .attr("stroke-width", 2);
  1324. // 关系图标题
  1325. egoCenterGroup.append("text")
  1326. .attr("class", "ego-title")
  1327. .attr("y", -egoDisplayRadius - 10)
  1328. .attr("text-anchor", "middle")
  1329. .attr("fill", "rgba(255,255,255,0.5)")
  1330. .attr("font-size", "13px")
  1331. .attr("font-weight", "bold")
  1332. .text("关系图");
  1333. // 关系图内容组
  1334. egoCenterGroup.append("g")
  1335. .attr("class", "ego-graph-content");
  1336. // 绘制背景矩形
  1337. treeGroup.append("rect")
  1338. .attr("x", -5)
  1339. .attr("y", -10)
  1340. .attr("width", treeAreaWidth - 20)
  1341. .attr("height", treeHeight - 20)
  1342. .attr("rx", 8)
  1343. .attr("fill", "rgba(100, 100, 100, 0.08)")
  1344. .attr("stroke", "rgba(150, 150, 150, 0.2)")
  1345. .attr("stroke-width", 1);
  1346. // D3树布局 - 宽度留出边距给标签
  1347. const treeLayout = d3.tree()
  1348. .size([treeHeight - 50, treeAreaWidth - 70]);
  1349. const root = d3.hierarchy(personaTree.root);
  1350. treeLayout(root);
  1351. // 获取节点颜色(根据维度)
  1352. function getNodeColor(d) {{
  1353. if (d.data.isRoot) return "#e94560"; // 根节点红色
  1354. if (d.data.isDimension) return d.data.dimColor; // 维度节点用维度颜色
  1355. return d.data.dimColor || "#888"; // 分类节点继承维度颜色
  1356. }}
  1357. // 构建节点ID到D3节点的映射(用于绘制原始边和高亮)
  1358. const treeNodeById = {{}};
  1359. root.descendants().forEach(d => {{
  1360. if (d.data.节点ID) {{
  1361. treeNodeById[d.data.节点ID] = d;
  1362. }}
  1363. }});
  1364. // 边类型颜色和样式
  1365. const treeEdgeColors = {{
  1366. "分类层级": "#2ecc71", // 绿色 - 分类的层级关系
  1367. "属于": "#9b59b6", // 紫色 - 标签属于分类
  1368. "包含": "#8e44ad", // 深紫 - 分类包含标签
  1369. "分类共现(跨点)": "#2ecc71", // 绿色 - 跨帖子分类共现
  1370. "分类共现(点内)": "#3498db", // 蓝色 - 同帖子分类共现
  1371. "标签共现": "#f39c12" // 橙色 - 标签共现
  1372. }};
  1373. const treeEdgeDash = {{
  1374. "分类层级": "none",
  1375. "属于": "3,2",
  1376. "包含": "3,2",
  1377. "分类共现(跨点)": "5,3",
  1378. "分类共现(点内)": "5,3",
  1379. "标签共现": "2,2"
  1380. }};
  1381. // 只保留"属于"边用于树的展示(其他边用专门子图展示)
  1382. const visibleTreeEdges = personaTreeData.edges.filter(e => {{
  1383. return e.边类型 === "属于" && treeNodeById[e.源节点ID] && treeNodeById[e.目标节点ID];
  1384. }});
  1385. // 添加树结构边(根节点->维度,维度->子节点)
  1386. root.links().forEach(link => {{
  1387. visibleTreeEdges.push({{
  1388. 源节点ID: link.source.data.节点ID || link.source.data.name,
  1389. 目标节点ID: link.target.data.节点ID || link.target.data.name,
  1390. 边类型: "属于",
  1391. isTreeLink: true,
  1392. sourceNode: link.source,
  1393. targetNode: link.target
  1394. }});
  1395. }});
  1396. // 绘制原始边(分类层级、标签属于)
  1397. const treeEdgeGroup = treeGroup.append("g").attr("class", "tree-edges");
  1398. // 先绘制可见边
  1399. const treeEdges = treeEdgeGroup.selectAll(".tree-edge")
  1400. .data(visibleTreeEdges)
  1401. .join("path")
  1402. .attr("class", "tree-edge")
  1403. .attr("fill", "none")
  1404. .attr("stroke", "#9b59b6") // 属于边用紫色
  1405. .attr("stroke-opacity", 0.3)
  1406. .attr("stroke-width", 1)
  1407. .attr("d", d => {{
  1408. const source = d.isTreeLink ? d.sourceNode : treeNodeById[d.源节点ID];
  1409. const target = d.isTreeLink ? d.targetNode : treeNodeById[d.目标节点ID];
  1410. if (!source || !target) return "";
  1411. const midX = (source.y + target.y) / 2;
  1412. return `M${{source.y}},${{source.x}} C${{midX}},${{source.x}} ${{midX}},${{target.x}} ${{target.y}},${{target.x}}`;
  1413. }});
  1414. // 绘制透明的热区边(便于点击)
  1415. const treeEdgeHitareas = treeEdgeGroup.selectAll(".tree-edge-hitarea")
  1416. .data(visibleTreeEdges)
  1417. .join("path")
  1418. .attr("class", "tree-edge-hitarea")
  1419. .attr("fill", "none")
  1420. .attr("stroke", "transparent")
  1421. .attr("stroke-width", 12)
  1422. .style("cursor", "pointer")
  1423. .attr("d", d => {{
  1424. const source = d.isTreeLink ? d.sourceNode : treeNodeById[d.源节点ID];
  1425. const target = d.isTreeLink ? d.targetNode : treeNodeById[d.目标节点ID];
  1426. if (!source || !target) return "";
  1427. const midX = (source.y + target.y) / 2;
  1428. return `M${{source.y}},${{source.x}} C${{midX}},${{source.x}} ${{midX}},${{target.x}} ${{target.y}},${{target.x}}`;
  1429. }})
  1430. .on("click", (event, d) => {{
  1431. event.stopPropagation();
  1432. // 调用共享的边点击处理函数
  1433. handleEdgeClick(d.源节点ID, d.目标节点ID, d.边类型);
  1434. }});
  1435. // 绘制节点
  1436. const treeNodes = treeGroup.selectAll(".tree-node")
  1437. .data(root.descendants())
  1438. .join("g")
  1439. .attr("class", "tree-node")
  1440. .attr("transform", d => `translate(${{d.y}},${{d.x}})`)
  1441. .style("cursor", "pointer")
  1442. .on("click", (event, d) => {{
  1443. event.stopPropagation();
  1444. // 调用共享的节点点击处理函数
  1445. handleNodeClick(d.data.节点ID, d.data.节点名称 || d.data.name);
  1446. }});
  1447. // 节点形状:根节点/维度=圆形,分类=正方形,标签=圆形
  1448. // 统一实心填充维度颜色
  1449. treeNodes.each(function(d) {{
  1450. const el = d3.select(this);
  1451. const nodeType = d.data.节点类型;
  1452. const isRoot = d.data.isRoot;
  1453. const isDimension = d.data.isDimension;
  1454. const nodeColor = getNodeColor(d);
  1455. if (nodeType === "分类") {{
  1456. // 分类节点:正方形,实心填充
  1457. el.append("rect")
  1458. .attr("class", "tree-shape")
  1459. .attr("x", -4)
  1460. .attr("y", -4)
  1461. .attr("width", 8)
  1462. .attr("height", 8)
  1463. .attr("rx", 1)
  1464. .attr("fill", nodeColor)
  1465. .attr("stroke", "rgba(255,255,255,0.5)")
  1466. .attr("stroke-width", 1);
  1467. }} else {{
  1468. // 根节点、维度节点、标签节点:圆形,实心填充
  1469. const radius = isRoot ? 6 : (isDimension ? 5 : 3);
  1470. el.append("circle")
  1471. .attr("class", "tree-shape")
  1472. .attr("r", radius)
  1473. .attr("fill", nodeColor)
  1474. .attr("stroke", "rgba(255,255,255,0.5)")
  1475. .attr("stroke-width", 1);
  1476. }}
  1477. }});
  1478. // 节点标签
  1479. treeNodes.append("text")
  1480. .attr("dy", "0.31em")
  1481. .attr("x", d => d.children ? -8 : 8)
  1482. .attr("text-anchor", d => d.children ? "end" : "start")
  1483. .attr("fill", d => (d.data.isRoot || d.data.isDimension) ? getNodeColor(d) : "#bbb")
  1484. .attr("font-size", d => d.data.isRoot ? "11px" : (d.data.isDimension ? "10px" : "8px"))
  1485. .attr("font-weight", d => (d.data.isRoot || d.data.isDimension) ? "bold" : "normal")
  1486. .text(d => d.data.name);
  1487. // 重置树高亮状态的函数
  1488. function resetTreeHighlight() {{
  1489. treeGroup.selectAll(".tree-node")
  1490. .classed("tree-dimmed", false)
  1491. .classed("tree-highlighted", false);
  1492. // 重置所有形状(圆形和方形)- 统一实心填充
  1493. treeGroup.selectAll(".tree-node .tree-shape")
  1494. .attr("fill", d => getNodeColor(d))
  1495. .attr("stroke", "rgba(255,255,255,0.5)")
  1496. .attr("stroke-opacity", 1)
  1497. .attr("opacity", 1);
  1498. treeGroup.selectAll(".tree-node text")
  1499. .attr("fill", d => (d.data.isRoot || d.data.isDimension) ? getNodeColor(d) : "#bbb")
  1500. .attr("opacity", 1);
  1501. // 重置边样式
  1502. treeGroup.selectAll(".tree-edge")
  1503. .attr("stroke-opacity", 0.3)
  1504. .attr("stroke-width", 1);
  1505. }}
  1506. // 重置右侧图高亮状态的函数
  1507. function resetGraphHighlight() {{
  1508. g.selectAll(".node").classed("dimmed", false).classed("highlighted", false);
  1509. g.selectAll(".link-group").classed("dimmed", false).classed("highlighted", false);
  1510. }}
  1511. // 点击树背景也取消高亮
  1512. treeGroup.select("rect").on("click", function(event) {{
  1513. event.stopPropagation();
  1514. resetTreeHighlight();
  1515. resetGraphHighlight();
  1516. clearEgoGraph();
  1517. closeDetailPanel();
  1518. }});
  1519. // 创建边的容器
  1520. const linkGroup = g.append("g").attr("class", "links");
  1521. // 为每条边创建组
  1522. const linkG = linkGroup.selectAll("g")
  1523. .data(links)
  1524. .join("g")
  1525. .attr("class", "link-group");
  1526. // 绘制点击热区(透明宽线)
  1527. const linkHitarea = linkG.append("line")
  1528. .attr("class", "link-hitarea");
  1529. // 绘制可见的边
  1530. const link = linkG.append("line")
  1531. .attr("class", d => "link " + getEdgeClass(d.type))
  1532. .attr("stroke-width", d => d.type === "匹配" ? 2.5 : 1.5)
  1533. .attr("stroke-dasharray", d => {{
  1534. // 匹配边根据相似度设置虚实线
  1535. if (d.type === "匹配" && d.边详情 && d.边详情.相似度 !== undefined) {{
  1536. const score = d.边详情.相似度;
  1537. if (score >= 0.8) return null; // >= 0.8 实线
  1538. if (score >= 0.5) return "6,4"; // 0.5-0.8 虚线
  1539. }}
  1540. return null; // 默认实线
  1541. }});
  1542. // 判断是否为跨层边(根据源和目标节点的层级)- 赋值给全局变量
  1543. isCrossLayerEdge = function(d) {{
  1544. const sourceNode = typeof d.source === "object" ? d.source : nodes.find(n => n.id === d.source);
  1545. const targetNode = typeof d.target === "object" ? d.target : nodes.find(n => n.id === d.target);
  1546. if (!sourceNode || !targetNode) return false;
  1547. return getNodeLayer(sourceNode) !== getNodeLayer(targetNode);
  1548. }};
  1549. // 设置跨层边的初始可见性(匹配边始终显示,其他跨层边默认隐藏)
  1550. linkG.each(function(d) {{
  1551. if (d.type === "匹配") {{
  1552. d3.select(this).style("display", "block"); // 匹配边始终显示
  1553. }} else if (isCrossLayerEdge(d) && !showCrossLayerEdges) {{
  1554. d3.select(this).style("display", "none");
  1555. }}
  1556. }});
  1557. // 为匹配边添加分数标签
  1558. const edgeLabels = linkG.filter(d => d.type === "匹配" && d.边详情 && d.边详情.相似度)
  1559. .append("g")
  1560. .attr("class", "edge-label-group");
  1561. edgeLabels.append("rect")
  1562. .attr("class", "edge-label-bg")
  1563. .attr("rx", 3)
  1564. .attr("ry", 3);
  1565. edgeLabels.append("text")
  1566. .attr("class", "edge-label")
  1567. .text(d => {{
  1568. const score = d.边详情.相似度;
  1569. return typeof score === "number" ? score.toFixed(2) : score;
  1570. }});
  1571. // 边的点击事件
  1572. linkHitarea.on("click", (event, d, i) => {{
  1573. event.stopPropagation();
  1574. const linkIndex = links.indexOf(d);
  1575. highlightEdge(d, linkIndex);
  1576. showEdgeInfo(d);
  1577. // 边联动:如果边涉及人设节点,联动人设树和关系图
  1578. const sourceNode = typeof d.source === "object" ? d.source : nodes.find(n => n.id === d.source);
  1579. const targetNode = typeof d.target === "object" ? d.target : nodes.find(n => n.id === d.target);
  1580. if (sourceNode && sourceNode.source === "人设") {{
  1581. handleNodeClick(sourceNode.节点ID, sourceNode.节点名称);
  1582. }} else if (targetNode && targetNode.source === "人设") {{
  1583. handleNodeClick(targetNode.节点ID, targetNode.节点名称);
  1584. }}
  1585. }})
  1586. .on("mouseover", function(event, d) {{
  1587. d3.select(this.parentNode).select(".link")
  1588. .attr("stroke-opacity", 1)
  1589. .attr("stroke-width", 4);
  1590. }})
  1591. .on("mouseout", function(event, d) {{
  1592. d3.select(this.parentNode).select(".link")
  1593. .attr("stroke-opacity", 0.7)
  1594. .attr("stroke-width", d.type === "匹配" ? 2.5 : 1.5);
  1595. }});
  1596. // 绘制节点
  1597. const node = g.append("g")
  1598. .selectAll("g")
  1599. .data(nodes)
  1600. .join("g")
  1601. .attr("class", "node")
  1602. .call(d3.drag()
  1603. .on("start", dragstarted)
  1604. .on("drag", dragged)
  1605. .on("end", dragended));
  1606. // 根据节点类型绘制不同形状
  1607. // - 点节点(帖子点):六边形
  1608. // - 标签节点:圆形
  1609. // - 分类节点:方形
  1610. // 帖子标签用虚线,人设标签用实线
  1611. node.each(function(d) {{
  1612. const el = d3.select(this);
  1613. const isPointNode = d.节点类型 === "点";
  1614. const isPostNode = d.source === "帖子";
  1615. // 节点大小
  1616. let size;
  1617. if (isPointNode) {{
  1618. size = 16; // 点节点最大
  1619. }} else if (isPostNode) {{
  1620. size = 12; // 帖子标签
  1621. }} else {{
  1622. size = 10; // 人设标签
  1623. }}
  1624. const fill = levelColors[d.level] || "#666";
  1625. const nodeClass = isPostNode
  1626. ? (isPointNode ? "post-point-node" : "post-node")
  1627. : "persona-node";
  1628. if (isPointNode) {{
  1629. // 六边形(点节点)
  1630. const hexPoints = [];
  1631. for (let i = 0; i < 6; i++) {{
  1632. const angle = (i * 60 - 30) * Math.PI / 180;
  1633. hexPoints.push([size * Math.cos(angle), size * Math.sin(angle)]);
  1634. }}
  1635. el.append("polygon")
  1636. .attr("points", hexPoints.map(p => p.join(",")).join(" "))
  1637. .attr("fill", fill)
  1638. .attr("class", nodeClass);
  1639. }} else if (d.节点类型 === "分类") {{
  1640. // 方形(分类节点)
  1641. el.append("rect")
  1642. .attr("width", size * 2)
  1643. .attr("height", size * 2)
  1644. .attr("x", -size)
  1645. .attr("y", -size)
  1646. .attr("fill", fill)
  1647. .attr("class", nodeClass)
  1648. .attr("rx", 3);
  1649. }} else {{
  1650. // 圆形(标签节点)
  1651. el.append("circle")
  1652. .attr("r", size)
  1653. .attr("fill", fill)
  1654. .attr("class", nodeClass);
  1655. }}
  1656. }});
  1657. const labels = node.append("text")
  1658. .attr("dx", 15)
  1659. .attr("dy", 4)
  1660. .text(d => d.节点名称)
  1661. .style("display", showLabels ? "block" : "none");
  1662. // 工具提示
  1663. const tooltip = d3.select("#tooltip");
  1664. node.on("mouseover", (event, d) => {{
  1665. let html = `<strong>${{d.节点名称}}</strong><br/>类型: ${{d.节点类型}}<br/>层级: ${{d.节点层级}}`;
  1666. // 点节点显示描述
  1667. if (d.描述) {{
  1668. html += `<br/><br/><em style="font-size:10px;color:#aaa">${{d.描述.slice(0, 100)}}${{d.描述.length > 100 ? '...' : ''}}</em>`;
  1669. }}
  1670. tooltip.style("display", "block").html(html);
  1671. }})
  1672. .on("mousemove", (event) => {{
  1673. tooltip.style("left", (event.pageX + 15) + "px")
  1674. .style("top", (event.pageY - 10) + "px");
  1675. }})
  1676. .on("mouseout", () => {{
  1677. tooltip.style("display", "none");
  1678. }})
  1679. .on("click", (event, d) => {{
  1680. event.stopPropagation();
  1681. highlightNode(d);
  1682. showNodeInfo(d);
  1683. // 人设节点联动:高亮人设树 + 显示关系图
  1684. if (d.source === "人设") {{
  1685. handleNodeClick(d.节点ID, d.节点名称);
  1686. }}
  1687. }});
  1688. // 更新位置
  1689. simulation.on("tick", () => {{
  1690. // 更新热区线
  1691. linkHitarea
  1692. .attr("x1", d => d.source.x)
  1693. .attr("y1", d => d.source.y)
  1694. .attr("x2", d => d.target.x)
  1695. .attr("y2", d => d.target.y);
  1696. // 更新可见边
  1697. link
  1698. .attr("x1", d => d.source.x)
  1699. .attr("y1", d => d.source.y)
  1700. .attr("x2", d => d.target.x)
  1701. .attr("y2", d => d.target.y);
  1702. // 更新边标签位置(放在边的中点)
  1703. edgeLabels.attr("transform", d => {{
  1704. const midX = (d.source.x + d.target.x) / 2;
  1705. const midY = (d.source.y + d.target.y) / 2;
  1706. return `translate(${{midX}},${{midY}})`;
  1707. }});
  1708. // 更新标签背景大小
  1709. edgeLabels.each(function(d) {{
  1710. const textEl = d3.select(this).select("text").node();
  1711. if (textEl) {{
  1712. const bbox = textEl.getBBox();
  1713. d3.select(this).select("rect")
  1714. .attr("x", bbox.x - 3)
  1715. .attr("y", bbox.y - 1)
  1716. .attr("width", bbox.width + 6)
  1717. .attr("height", bbox.height + 2);
  1718. }}
  1719. }});
  1720. node.attr("transform", d => `translate(${{d.x}},${{d.y}})`);
  1721. }});
  1722. // 拖拽函数
  1723. function dragstarted(event, d) {{
  1724. if (!event.active) simulation.alphaTarget(0.3).restart();
  1725. d.fx = d.x;
  1726. d.fy = d.y;
  1727. }}
  1728. function dragged(event, d) {{
  1729. d.fx = event.x;
  1730. d.fy = event.y;
  1731. }}
  1732. function dragended(event, d) {{
  1733. if (!event.active) simulation.alphaTarget(0);
  1734. d.fx = null;
  1735. d.fy = null;
  1736. }}
  1737. // 清除所有高亮
  1738. function clearHighlight() {{
  1739. node.classed("dimmed", false).classed("highlighted", false);
  1740. linkG.classed("dimmed", false).classed("highlighted", false);
  1741. // 恢复跨层边的可见性状态(根据全局开关)
  1742. linkG.each(function(d) {{
  1743. if (isCrossLayerEdge(d)) {{
  1744. d3.select(this).style("display", showCrossLayerEdges ? "block" : "none");
  1745. }}
  1746. }});
  1747. }}
  1748. // 高亮指定的节点和边
  1749. function highlightElements(highlightNodeIds, highlightLinkIndices) {{
  1750. // 先灰化所有
  1751. node.classed("dimmed", true).classed("highlighted", false);
  1752. linkG.classed("dimmed", true).classed("highlighted", false);
  1753. // 高亮指定节点
  1754. node.filter(d => highlightNodeIds.has(d.id))
  1755. .classed("dimmed", false)
  1756. .classed("highlighted", true);
  1757. // 高亮指定边
  1758. linkG.filter((d, i) => highlightLinkIndices.has(i))
  1759. .classed("dimmed", false)
  1760. .classed("highlighted", true);
  1761. }}
  1762. // 点击节点时的高亮逻辑
  1763. function highlightNode(clickedNode) {{
  1764. const highlightNodeIds = new Set([clickedNode.id]);
  1765. const highlightLinkIndices = new Set();
  1766. links.forEach((link, i) => {{
  1767. const sourceId = typeof link.source === "object" ? link.source.id : link.source;
  1768. const targetId = typeof link.target === "object" ? link.target.id : link.target;
  1769. // 与点击节点直接相连的边
  1770. if (sourceId === clickedNode.id || targetId === clickedNode.id) {{
  1771. highlightLinkIndices.add(i);
  1772. highlightNodeIds.add(sourceId);
  1773. highlightNodeIds.add(targetId);
  1774. // 如果是帖子节点,还要高亮对应的镜像边
  1775. if (clickedNode.source === "帖子") {{
  1776. // 找到通过该帖子连接的其他帖子(镜像边)
  1777. links.forEach((otherLink, j) => {{
  1778. const otherType = otherLink.type;
  1779. if (otherType.startsWith("镜像_") || otherType.startsWith("二阶_")) {{
  1780. const oSrc = typeof otherLink.source === "object" ? otherLink.source.id : otherLink.source;
  1781. const oTgt = typeof otherLink.target === "object" ? otherLink.target.id : otherLink.target;
  1782. if (oSrc === clickedNode.id || oTgt === clickedNode.id) {{
  1783. highlightLinkIndices.add(j);
  1784. highlightNodeIds.add(oSrc);
  1785. highlightNodeIds.add(oTgt);
  1786. }}
  1787. }}
  1788. }});
  1789. }}
  1790. }}
  1791. }});
  1792. // 高亮相关的节点和边
  1793. highlightElements(highlightNodeIds, highlightLinkIndices);
  1794. // 临时显示关联的跨层边(即使全局开关是关闭的)
  1795. linkG.each(function(d, i) {{
  1796. if (highlightLinkIndices.has(i)) {{
  1797. d3.select(this).style("display", "block");
  1798. }}
  1799. }});
  1800. }}
  1801. // 点击边时的高亮逻辑
  1802. function highlightEdge(clickedLink, clickedIndex) {{
  1803. const highlightNodeIds = new Set();
  1804. const highlightLinkIndices = new Set([clickedIndex]);
  1805. const sourceId = typeof clickedLink.source === "object" ? clickedLink.source.id : clickedLink.source;
  1806. const targetId = typeof clickedLink.target === "object" ? clickedLink.target.id : clickedLink.target;
  1807. highlightNodeIds.add(sourceId);
  1808. highlightNodeIds.add(targetId);
  1809. // 如果是二阶边,显示完整路径
  1810. if (clickedLink.type.startsWith("二阶_") && clickedLink.边详情) {{
  1811. const detail = clickedLink.边详情;
  1812. // 分类节点
  1813. if (detail.分类节点1) highlightNodeIds.add(detail.分类节点1);
  1814. if (detail.分类节点2) highlightNodeIds.add(detail.分类节点2);
  1815. // 标签节点
  1816. if (detail.标签节点1) highlightNodeIds.add(detail.标签节点1);
  1817. if (detail.标签节点2) highlightNodeIds.add(detail.标签节点2);
  1818. // 找出路径上的边
  1819. links.forEach((link, i) => {{
  1820. const lSrc = typeof link.source === "object" ? link.source.id : link.source;
  1821. const lTgt = typeof link.target === "object" ? link.target.id : link.target;
  1822. // 帖子->标签 的匹配边
  1823. if (link.type === "匹配") {{
  1824. if ((lSrc === sourceId && lTgt === detail.标签节点1) ||
  1825. (lSrc === targetId && lTgt === detail.标签节点2)) {{
  1826. highlightLinkIndices.add(i);
  1827. }}
  1828. }}
  1829. // 标签->分类 的属于边
  1830. if (link.type === "属于") {{
  1831. if ((lSrc === detail.标签节点1 && lTgt === detail.分类节点1) ||
  1832. (lSrc === detail.标签节点2 && lTgt === detail.分类节点2)) {{
  1833. highlightLinkIndices.add(i);
  1834. }}
  1835. }}
  1836. // 分类之间的边
  1837. if ((lSrc === detail.分类节点1 && lTgt === detail.分类节点2) ||
  1838. (lSrc === detail.分类节点2 && lTgt === detail.分类节点1)) {{
  1839. highlightLinkIndices.add(i);
  1840. }}
  1841. }});
  1842. }}
  1843. // 如果是镜像边,显示对应的人设边
  1844. else if (clickedLink.type.startsWith("镜像_") && clickedLink.边详情) {{
  1845. const detail = clickedLink.边详情;
  1846. if (detail.源人设节点) highlightNodeIds.add(detail.源人设节点);
  1847. if (detail.目标人设节点) highlightNodeIds.add(detail.目标人设节点);
  1848. // 找出对应的人设边和匹配边
  1849. links.forEach((link, i) => {{
  1850. const lSrc = typeof link.source === "object" ? link.source.id : link.source;
  1851. const lTgt = typeof link.target === "object" ? link.target.id : link.target;
  1852. // 匹配边
  1853. if (link.type === "匹配") {{
  1854. if ((lSrc === sourceId && lTgt === detail.源人设节点) ||
  1855. (lSrc === targetId && lTgt === detail.目标人设节点)) {{
  1856. highlightLinkIndices.add(i);
  1857. }}
  1858. }}
  1859. // 人设边
  1860. if ((lSrc === detail.源人设节点 && lTgt === detail.目标人设节点) ||
  1861. (lSrc === detail.目标人设节点 && lTgt === detail.源人设节点)) {{
  1862. highlightLinkIndices.add(i);
  1863. }}
  1864. }});
  1865. }}
  1866. // 高亮相关的节点和边
  1867. highlightElements(highlightNodeIds, highlightLinkIndices);
  1868. // 临时显示关联的跨层边(即使全局开关是关闭的)
  1869. linkG.each(function(d, i) {{
  1870. if (highlightLinkIndices.has(i)) {{
  1871. d3.select(this).style("display", "block");
  1872. }}
  1873. }});
  1874. }}
  1875. // 点击空白处清除高亮(合并所有空白点击逻辑)
  1876. svg.on("click", (event) => {{
  1877. // 检查是否点击的是空白区域(svg本身或layer-backgrounds)
  1878. const isBlank = event.target === svg.node() ||
  1879. event.target.tagName === "svg" ||
  1880. event.target.classList.contains("layer-backgrounds");
  1881. if (isBlank) {{
  1882. // 清除右侧图高亮
  1883. clearHighlight();
  1884. // 清除人设树高亮
  1885. resetTreeHighlight();
  1886. resetGraphHighlight();
  1887. // 关闭详情面板
  1888. closeDetailPanel();
  1889. // 清除关系图
  1890. clearEgoGraph();
  1891. }}
  1892. }});
  1893. }}
  1894. // 控制函数
  1895. function resetZoom() {{
  1896. const container = document.getElementById("svg-container");
  1897. const width = container.clientWidth;
  1898. const height = container.clientHeight;
  1899. svg.transition().duration(750).call(
  1900. zoom.transform,
  1901. d3.zoomIdentity.translate(width/2, height/2).scale(1).translate(-width/2, -height/2)
  1902. );
  1903. }}
  1904. function toggleLabels() {{
  1905. showLabels = !showLabels;
  1906. g.selectAll(".node text").style("display", showLabels ? "block" : "none");
  1907. }}
  1908. // 切换跨层边显示
  1909. function toggleCrossLayerEdges() {{
  1910. showCrossLayerEdges = !showCrossLayerEdges;
  1911. const btn = document.getElementById("crossLayerBtn");
  1912. btn.textContent = showCrossLayerEdges ? "隐藏跨层边" : "显示跨层边";
  1913. btn.style.background = showCrossLayerEdges ? "#e94560" : "";
  1914. // 更新边的可见性(使用 isCrossLayerEdge 函数判断)
  1915. g.selectAll(".link-group").each(function(d) {{
  1916. if (isCrossLayerEdge(d)) {{
  1917. d3.select(this).style("display", showCrossLayerEdges ? "block" : "none");
  1918. }}
  1919. }});
  1920. }}
  1921. function showNodeInfo(d) {{
  1922. const panel = document.getElementById("detailPanel");
  1923. panel.classList.add("active");
  1924. document.getElementById("detailTitle").textContent = d.source === "帖子" ? "📌 帖子节点" : "👤 人设节点";
  1925. let html = `
  1926. <p><span class="label">节点ID:</span> ${{d.节点ID}}</p>
  1927. <p><span class="label">名称:</span> <strong>${{d.节点名称}}</strong></p>
  1928. <p><span class="label">类型:</span> ${{d.节点类型}}</p>
  1929. <p><span class="label">层级:</span> ${{d.节点层级}}</p>
  1930. `;
  1931. if (d.权重) {{
  1932. html += `<p><span class="label">权重:</span> ${{d.权重}}</p>`;
  1933. }}
  1934. if (d.所属分类 && d.所属分类.length > 0) {{
  1935. html += `<p><span class="label">所属分类:</span> ${{d.所属分类.join(" > ")}}</p>`;
  1936. }}
  1937. if (d.帖子数) {{
  1938. html += `<p><span class="label">帖子数:</span> ${{d.帖子数}}</p>`;
  1939. }}
  1940. document.getElementById("detailContent").innerHTML = html;
  1941. }}
  1942. // 显示人设树节点详情(包含入边、出边、相关节点)
  1943. function showTreeNodeDetail(nodeData, inEdges, outEdges) {{
  1944. const panel = document.getElementById("detailPanel");
  1945. panel.classList.add("active");
  1946. document.getElementById("detailTitle").textContent = "🌳 人设树节点";
  1947. // 节点基本信息
  1948. let html = `
  1949. <p><span class="label">名称:</span> <strong>${{nodeData.节点名称 || nodeData.name}}</strong></p>
  1950. <p><span class="label">类型:</span> ${{nodeData.节点类型 || (nodeData.isRoot ? "根节点" : "维度")}}</p>
  1951. <p><span class="label">层级:</span> ${{nodeData.节点层级 || "-"}}</p>
  1952. `;
  1953. if (nodeData.所属分类 && nodeData.所属分类.length > 0) {{
  1954. html += `<p><span class="label">所属分类:</span> ${{nodeData.所属分类.join(" > ")}}</p>`;
  1955. }}
  1956. if (nodeData.帖子数) {{
  1957. html += `<p><span class="label">帖子数:</span> ${{nodeData.帖子数}}</p>`;
  1958. }}
  1959. // 统计边类型
  1960. const inEdgeTypes = {{}};
  1961. const outEdgeTypes = {{}};
  1962. inEdges.forEach(e => {{ inEdgeTypes[e.边类型] = (inEdgeTypes[e.边类型] || 0) + 1; }});
  1963. outEdges.forEach(e => {{ outEdgeTypes[e.边类型] = (outEdgeTypes[e.边类型] || 0) + 1; }});
  1964. // 入边统计
  1965. html += `<h4 style="margin-top:12px;color:#3498db;font-size:12px;">📥 入边 (${{inEdges.length}})</h4>`;
  1966. if (inEdges.length > 0) {{
  1967. html += `<div class="edge-list">`;
  1968. for (const [type, count] of Object.entries(inEdgeTypes)) {{
  1969. html += `<div class="edge-type-item"><span class="edge-type">${{type}}</span><span class="edge-count">${{count}}</span></div>`;
  1970. }}
  1971. // 显示前5条入边详情
  1972. const showInEdges = inEdges.slice(0, 5);
  1973. showInEdges.forEach(e => {{
  1974. const srcName = personaTreeData.nodes.find(n => n.节点ID === e.源节点ID)?.节点名称 || e.源节点ID;
  1975. html += `<div class="edge-detail">← ${{srcName}} <span class="edge-type-tag">${{e.边类型}}</span></div>`;
  1976. }});
  1977. if (inEdges.length > 5) {{
  1978. html += `<div class="edge-more">... 还有 ${{inEdges.length - 5}} 条</div>`;
  1979. }}
  1980. html += `</div>`;
  1981. }} else {{
  1982. html += `<div class="edge-empty">无</div>`;
  1983. }}
  1984. // 出边统计
  1985. html += `<h4 style="margin-top:12px;color:#e74c3c;font-size:12px;">📤 出边 (${{outEdges.length}})</h4>`;
  1986. if (outEdges.length > 0) {{
  1987. html += `<div class="edge-list">`;
  1988. for (const [type, count] of Object.entries(outEdgeTypes)) {{
  1989. html += `<div class="edge-type-item"><span class="edge-type">${{type}}</span><span class="edge-count">${{count}}</span></div>`;
  1990. }}
  1991. // 显示前5条出边详情
  1992. const showOutEdges = outEdges.slice(0, 5);
  1993. showOutEdges.forEach(e => {{
  1994. const tgtName = personaTreeData.nodes.find(n => n.节点ID === e.目标节点ID)?.节点名称 || e.目标节点ID;
  1995. html += `<div class="edge-detail">→ ${{tgtName}} <span class="edge-type-tag">${{e.边类型}}</span></div>`;
  1996. }});
  1997. if (outEdges.length > 5) {{
  1998. html += `<div class="edge-more">... 还有 ${{outEdges.length - 5}} 条</div>`;
  1999. }}
  2000. html += `</div>`;
  2001. }} else {{
  2002. html += `<div class="edge-empty">无</div>`;
  2003. }}
  2004. document.getElementById("detailContent").innerHTML = html;
  2005. }}
  2006. function showEdgeInfo(d) {{
  2007. const panel = document.getElementById("detailPanel");
  2008. panel.classList.add("active");
  2009. const sourceNode = typeof d.source === "object" ? d.source : {{ id: d.source }};
  2010. const targetNode = typeof d.target === "object" ? d.target : {{ id: d.target }};
  2011. // 判断是否为镜像边
  2012. const isMirror = d.type.startsWith("镜像_");
  2013. document.getElementById("detailTitle").textContent = isMirror ? "🪞 镜像边详情" : "🔗 边详情";
  2014. let html = `
  2015. <p><span class="label">边类型:</span> <strong>${{d.type}}</strong></p>
  2016. <p><span class="label">源节点:</span> ${{sourceNode.节点名称 || sourceNode.id}}</p>
  2017. <p><span class="label">目标节点:</span> ${{targetNode.节点名称 || targetNode.id}}</p>
  2018. `;
  2019. if (d.边详情) {{
  2020. if (d.边详情.相似度 !== undefined) {{
  2021. const score = typeof d.边详情.相似度 === "number" ? d.边详情.相似度.toFixed(2) : d.边详情.相似度;
  2022. html += `<p><span class="label">相似度:</span> <span class="similarity-score">${{score}}</span></p>`;
  2023. }}
  2024. if (d.边详情.说明) {{
  2025. html += `<p><span class="label">说明:</span></p><div class="edge-description">${{d.边详情.说明}}</div>`;
  2026. }}
  2027. if (d.边详情.共现次数 !== undefined) {{
  2028. html += `<p><span class="label">共现次数:</span> ${{d.边详情.共现次数}}</p>`;
  2029. }}
  2030. // 镜像边特有信息
  2031. if (d.边详情.原始边类型) {{
  2032. html += `<p><span class="label">原始边类型:</span> ${{d.边详情.原始边类型}}</p>`;
  2033. }}
  2034. if (d.边详情.源人设节点) {{
  2035. html += `<p><span class="label">源人设节点:</span> ${{d.边详情.源人设节点}}</p>`;
  2036. }}
  2037. if (d.边详情.目标人设节点) {{
  2038. html += `<p><span class="label">目标人设节点:</span> ${{d.边详情.目标人设节点}}</p>`;
  2039. }}
  2040. }}
  2041. document.getElementById("detailContent").innerHTML = html;
  2042. }}
  2043. function closeDetailPanel() {{
  2044. document.getElementById("detailPanel").classList.remove("active");
  2045. }}
  2046. // 更新匹配列表
  2047. function updateMatchList(matchLinks, nodes) {{
  2048. const listEl = document.getElementById("matchList");
  2049. const countEl = document.getElementById("matchCount");
  2050. // 构建节点ID到名称的映射
  2051. const nodeNames = {{}};
  2052. nodes.forEach(n => {{
  2053. nodeNames[n.id] = n.节点名称 || n.id;
  2054. }});
  2055. // 按分数降序排序
  2056. const sortedLinks = [...matchLinks].sort((a, b) => {{
  2057. const scoreA = a.边详情?.相似度 ?? 0;
  2058. const scoreB = b.边详情?.相似度 ?? 0;
  2059. return scoreB - scoreA;
  2060. }});
  2061. countEl.textContent = `(${{sortedLinks.length}})`;
  2062. // 生成列表HTML
  2063. let html = "";
  2064. sortedLinks.forEach((link, index) => {{
  2065. const score = link.边详情?.相似度;
  2066. const scoreText = score !== undefined ? score.toFixed(2) : "N/A";
  2067. const scoreClass = score >= 0.8 ? "high" : (score >= 0.5 ? "medium" : "");
  2068. const srcId = typeof link.source === "object" ? link.source.id : link.source;
  2069. const tgtId = typeof link.target === "object" ? link.target.id : link.target;
  2070. const srcName = nodeNames[srcId] || srcId;
  2071. const tgtName = nodeNames[tgtId] || tgtId;
  2072. html += `
  2073. <div class="match-item" data-index="${{index}}" data-src="${{srcId}}" data-tgt="${{tgtId}}">
  2074. <span class="score ${{scoreClass}}">${{scoreText}}</span>
  2075. <span class="names" title="${{srcName}} → ${{tgtName}}">${{srcName}} → ${{tgtName}}</span>
  2076. </div>
  2077. `;
  2078. }});
  2079. listEl.innerHTML = html;
  2080. // 添加点击事件
  2081. listEl.querySelectorAll(".match-item").forEach(item => {{
  2082. item.addEventListener("click", () => {{
  2083. const srcId = item.dataset.src;
  2084. const tgtId = item.dataset.tgt;
  2085. const index = parseInt(item.dataset.index);
  2086. // 高亮对应的边
  2087. highlightMatchEdge(srcId, tgtId);
  2088. // 更新列表项样式
  2089. listEl.querySelectorAll(".match-item").forEach(el => el.classList.remove("active"));
  2090. item.classList.add("active");
  2091. }});
  2092. }});
  2093. }}
  2094. // 高亮匹配边
  2095. function highlightMatchEdge(srcId, tgtId) {{
  2096. if (!g) return;
  2097. // 重置所有
  2098. g.selectAll(".node").classed("dimmed", true).classed("highlighted", false);
  2099. g.selectAll(".link-group").classed("dimmed", true).classed("highlighted", false);
  2100. // 高亮对应的边和节点
  2101. g.selectAll(".link-group").each(function(d) {{
  2102. const dSrc = typeof d.source === "object" ? d.source.id : d.source;
  2103. const dTgt = typeof d.target === "object" ? d.target.id : d.target;
  2104. if ((dSrc === srcId && dTgt === tgtId) || (dSrc === tgtId && dTgt === srcId)) {{
  2105. d3.select(this).classed("dimmed", false).classed("highlighted", true);
  2106. }}
  2107. }});
  2108. g.selectAll(".node").each(function(d) {{
  2109. if (d.id === srcId || d.id === tgtId) {{
  2110. d3.select(this).classed("dimmed", false).classed("highlighted", true);
  2111. }}
  2112. }});
  2113. }}
  2114. // 获取节点颜色(全局版本,根据节点数据判断维度)
  2115. function getTreeNodeColor(d) {{
  2116. const dimColors = {{ "灵感点": "#f39c12", "目的点": "#3498db", "关键点": "#9b59b6" }};
  2117. if (d.data.isRoot) return "#e94560";
  2118. if (d.data.isDimension) return d.data.dimColor;
  2119. return d.data.dimColor || "#888";
  2120. }}
  2121. // 共享的节点点击处理函数(人设树和关系图复用)
  2122. function handleNodeClick(clickedNodeId, clickedNodeName) {{
  2123. if (!clickedNodeId) return;
  2124. // 动态获取树相关元素
  2125. const treeGroup = d3.select(".persona-tree");
  2126. if (treeGroup.empty()) return;
  2127. const treeEdges = treeGroup.selectAll(".tree-edge");
  2128. // 先重置所有高亮状态
  2129. treeGroup.selectAll(".tree-node")
  2130. .classed("tree-dimmed", false)
  2131. .classed("tree-highlighted", false);
  2132. treeGroup.selectAll(".tree-node .tree-shape")
  2133. .attr("fill", d => getTreeNodeColor(d))
  2134. .attr("stroke", "rgba(255,255,255,0.5)")
  2135. .attr("stroke-width", 1)
  2136. .attr("stroke-opacity", 1)
  2137. .attr("opacity", 1);
  2138. treeGroup.selectAll(".tree-node text")
  2139. .attr("fill", d => (d.data.isRoot || d.data.isDimension) ? getTreeNodeColor(d) : "#bbb")
  2140. .attr("opacity", 1);
  2141. treeEdges.attr("stroke-opacity", 0.3).attr("stroke-width", 1);
  2142. if (g) {{
  2143. g.selectAll(".node").classed("dimmed", false).classed("highlighted", false);
  2144. g.selectAll(".link-group").classed("dimmed", false).classed("highlighted", false);
  2145. }}
  2146. // 构建节点ID到D3节点的映射
  2147. const treeNodeById = {{}};
  2148. treeGroup.selectAll(".tree-node").each(function(n) {{
  2149. if (n.data.节点ID) treeNodeById[n.data.节点ID] = n;
  2150. }});
  2151. // 查找所有与该节点相关的边
  2152. const allConnectedEdges = personaTreeData.edges.filter(e =>
  2153. e.源节点ID === clickedNodeId || e.目标节点ID === clickedNodeId
  2154. );
  2155. // 收集所有相关节点ID
  2156. const connectedNodeIds = new Set();
  2157. connectedNodeIds.add(clickedNodeId);
  2158. allConnectedEdges.forEach(e => {{
  2159. connectedNodeIds.add(e.源节点ID);
  2160. connectedNodeIds.add(e.目标节点ID);
  2161. }});
  2162. // 获取D3树节点
  2163. const clickedD3Node = treeNodeById[clickedNodeId];
  2164. // 也添加树结构中的父子节点
  2165. if (clickedD3Node) {{
  2166. if (clickedD3Node.parent && clickedD3Node.parent.data.节点ID) {{
  2167. connectedNodeIds.add(clickedD3Node.parent.data.节点ID);
  2168. }}
  2169. if (clickedD3Node.children) {{
  2170. clickedD3Node.children.forEach(c => {{
  2171. if (c.data.节点ID) connectedNodeIds.add(c.data.节点ID);
  2172. }});
  2173. }}
  2174. }}
  2175. // 转换为D3节点集合
  2176. const connectedD3Nodes = new Set();
  2177. if (clickedD3Node) connectedD3Nodes.add(clickedD3Node);
  2178. connectedNodeIds.forEach(id => {{
  2179. if (treeNodeById[id]) connectedD3Nodes.add(treeNodeById[id]);
  2180. }});
  2181. if (clickedD3Node) {{
  2182. if (clickedD3Node.parent) connectedD3Nodes.add(clickedD3Node.parent);
  2183. if (clickedD3Node.children) clickedD3Node.children.forEach(c => connectedD3Nodes.add(c));
  2184. }}
  2185. // 高亮树中的节点
  2186. treeGroup.selectAll(".tree-node")
  2187. .classed("tree-dimmed", n => !connectedD3Nodes.has(n))
  2188. .classed("tree-highlighted", n => connectedD3Nodes.has(n));
  2189. // 高亮所有形状(不变粗)
  2190. treeGroup.selectAll(".tree-node .tree-shape")
  2191. .attr("fill", function(n) {{
  2192. if (!connectedD3Nodes.has(n)) return "#555";
  2193. return getTreeNodeColor(n);
  2194. }})
  2195. .attr("stroke", function(n) {{
  2196. if (n.data.节点ID === clickedNodeId) return "#fff";
  2197. return connectedD3Nodes.has(n) ? "rgba(255,255,255,0.8)" : "#333";
  2198. }})
  2199. .attr("stroke-opacity", 1);
  2200. treeGroup.selectAll(".tree-node text")
  2201. .attr("fill", function(n) {{
  2202. if (!connectedD3Nodes.has(n)) return "#555";
  2203. return (n.data.isRoot || n.data.isDimension) ? getTreeNodeColor(n) : "#bbb";
  2204. }});
  2205. // 边高亮
  2206. treeEdges.attr("stroke-opacity", function(e) {{
  2207. const isConnected = (e.源节点ID === clickedNodeId || e.目标节点ID === clickedNodeId) ||
  2208. (e.isTreeLink && (e.源节点ID === clickedNodeName || e.目标节点ID === clickedNodeName));
  2209. return isConnected ? 0.9 : 0.15;
  2210. }});
  2211. // 计算入边和出边
  2212. const inEdges = allConnectedEdges.filter(e => e.目标节点ID === clickedNodeId);
  2213. const outEdges = allConnectedEdges.filter(e => e.源节点ID === clickedNodeId);
  2214. // 显示详情面板
  2215. const nodeData = personaTreeData.nodes.find(n => n.节点ID === clickedNodeId);
  2216. if (nodeData) {{
  2217. showTreeNodeDetail(nodeData, inEdges, outEdges);
  2218. }}
  2219. // 显示关系子图(先显示,这样容器高度才正确)
  2220. renderEgoGraph(clickedNodeId, clickedNodeName);
  2221. // 滚动人设树到对应节点位置(放在关系图显示后,高度才准确)
  2222. if (clickedD3Node) {{
  2223. // 用 setTimeout 确保 DOM 更新完成
  2224. setTimeout(() => {{
  2225. const treeContainer = document.getElementById("tree-container");
  2226. const containerHeight = treeContainer.clientHeight;
  2227. // D3树布局中 x 是垂直方向(因为是水平树)
  2228. const nodeY = clickedD3Node.x + 25; // 加上treeGroup的transform偏移
  2229. const targetScroll = nodeY - containerHeight / 2;
  2230. treeContainer.scrollTo({{
  2231. top: Math.max(0, targetScroll),
  2232. behavior: "smooth"
  2233. }});
  2234. }}, 50);
  2235. }}
  2236. // 高亮右侧图中对应节点及其相关节点和边
  2237. if (g) {{
  2238. // 收集相关节点ID(点击的节点及其直接连接的节点)
  2239. const relatedNodeIds = new Set([clickedNodeId]);
  2240. // 找所有与该节点相连的边
  2241. g.selectAll(".link-group").each(function(d) {{
  2242. const srcId = typeof d.source === "object" ? d.source.id : d.source;
  2243. const tgtId = typeof d.target === "object" ? d.target.id : d.target;
  2244. if (srcId === clickedNodeId || tgtId === clickedNodeId) {{
  2245. relatedNodeIds.add(srcId);
  2246. relatedNodeIds.add(tgtId);
  2247. }}
  2248. }});
  2249. // 检查是否有相关节点在图中
  2250. const hasRelatedNodes = g.selectAll(".node").filter(n => relatedNodeIds.has(n.id)).size() > 0;
  2251. if (hasRelatedNodes) {{
  2252. // 高亮相关节点,变灰其他
  2253. g.selectAll(".node")
  2254. .classed("dimmed", n => !relatedNodeIds.has(n.id))
  2255. .classed("highlighted", n => relatedNodeIds.has(n.id));
  2256. // 高亮相关边
  2257. g.selectAll(".link-group").each(function(d) {{
  2258. const srcId = typeof d.source === "object" ? d.source.id : d.source;
  2259. const tgtId = typeof d.target === "object" ? d.target.id : d.target;
  2260. const isRelated = srcId === clickedNodeId || tgtId === clickedNodeId;
  2261. d3.select(this)
  2262. .classed("dimmed", !isRelated)
  2263. .classed("highlighted", isRelated);
  2264. // 显示相关的跨层边
  2265. if (isRelated) {{
  2266. d3.select(this).style("display", "block");
  2267. }}
  2268. }});
  2269. }} else {{
  2270. // 点击的节点不在图中,全部变灰
  2271. g.selectAll(".node").classed("dimmed", true).classed("highlighted", false);
  2272. g.selectAll(".link-group").classed("dimmed", true).classed("highlighted", false);
  2273. }}
  2274. }}
  2275. }}
  2276. // 共享的边点击处理函数(人设树和关系图复用)
  2277. function handleEdgeClick(srcNodeId, tgtNodeId, edgeType) {{
  2278. // 动态获取树相关元素
  2279. const treeGroup = d3.select(".persona-tree");
  2280. if (treeGroup.empty()) return;
  2281. const treeEdges = treeGroup.selectAll(".tree-edge");
  2282. // 先重置所有高亮状态
  2283. treeGroup.selectAll(".tree-node")
  2284. .classed("tree-dimmed", false)
  2285. .classed("tree-highlighted", false);
  2286. treeGroup.selectAll(".tree-node .tree-shape")
  2287. .attr("fill", d => getTreeNodeColor(d))
  2288. .attr("stroke", "rgba(255,255,255,0.5)")
  2289. .attr("stroke-width", 1)
  2290. .attr("stroke-opacity", 1)
  2291. .attr("opacity", 1);
  2292. treeGroup.selectAll(".tree-node text")
  2293. .attr("fill", d => (d.data.isRoot || d.data.isDimension) ? getTreeNodeColor(d) : "#bbb")
  2294. .attr("opacity", 1);
  2295. treeEdges.attr("stroke-opacity", 0.3).attr("stroke-width", 1);
  2296. if (g) {{
  2297. g.selectAll(".node").classed("dimmed", false).classed("highlighted", false);
  2298. g.selectAll(".link-group").classed("dimmed", false).classed("highlighted", false);
  2299. }}
  2300. // 构建节点ID到D3节点的映射
  2301. const treeNodeById = {{}};
  2302. treeGroup.selectAll(".tree-node").each(function(n) {{
  2303. if (n.data.节点ID) treeNodeById[n.data.节点ID] = n;
  2304. }});
  2305. const sourceTreeNode = treeNodeById[srcNodeId];
  2306. const targetTreeNode = treeNodeById[tgtNodeId];
  2307. // 高亮树边(不变粗)
  2308. treeEdges.attr("stroke-opacity", function(e) {{
  2309. const isThisEdge = (e.源节点ID === srcNodeId && e.目标节点ID === tgtNodeId) ||
  2310. (e.源节点ID === tgtNodeId && e.目标节点ID === srcNodeId);
  2311. return isThisEdge ? 1 : 0.1;
  2312. }});
  2313. // 高亮相关节点
  2314. const connectedNodes = new Set();
  2315. if (sourceTreeNode) connectedNodes.add(sourceTreeNode);
  2316. if (targetTreeNode) connectedNodes.add(targetTreeNode);
  2317. treeGroup.selectAll(".tree-node .tree-shape")
  2318. .attr("fill", n => connectedNodes.has(n) ? getTreeNodeColor(n) : "#555")
  2319. .attr("opacity", 1);
  2320. treeGroup.selectAll(".tree-node text")
  2321. .attr("fill", n => connectedNodes.has(n) ?
  2322. ((n.data.isRoot || n.data.isDimension) ? getTreeNodeColor(n) : "#bbb") : "#555")
  2323. .attr("opacity", 1);
  2324. // 显示边详情
  2325. const panel = document.getElementById("detailPanel");
  2326. panel.classList.add("active");
  2327. document.getElementById("detailTitle").textContent = "🔗 边详情";
  2328. const srcNode = personaTreeData.nodes.find(n => n.节点ID === srcNodeId);
  2329. const tgtNode = personaTreeData.nodes.find(n => n.节点ID === tgtNodeId);
  2330. const srcName = sourceTreeNode ? (sourceTreeNode.data.节点名称 || sourceTreeNode.data.name) : (srcNode?.节点名称 || srcNodeId);
  2331. const tgtName = targetTreeNode ? (targetTreeNode.data.节点名称 || targetTreeNode.data.name) : (tgtNode?.节点名称 || tgtNodeId);
  2332. let html = `
  2333. <p><span class="label">边类型:</span> <strong>${{edgeType}}</strong></p>
  2334. <p><span class="label">源节点:</span> ${{srcName}}</p>
  2335. <p><span class="label">目标节点:</span> ${{tgtName}}</p>
  2336. `;
  2337. document.getElementById("detailContent").innerHTML = html;
  2338. // 高亮右侧人设匹配区域
  2339. if (g) {{
  2340. const relatedNodeIds = new Set([srcNodeId, tgtNodeId]);
  2341. const hasRelatedNodes = g.selectAll(".node").filter(n => relatedNodeIds.has(n.id)).size() > 0;
  2342. if (hasRelatedNodes) {{
  2343. // 高亮相关节点
  2344. g.selectAll(".node")
  2345. .classed("dimmed", n => !relatedNodeIds.has(n.id))
  2346. .classed("highlighted", n => relatedNodeIds.has(n.id));
  2347. // 高亮相关边
  2348. g.selectAll(".link-group").each(function(d) {{
  2349. const sid = typeof d.source === "object" ? d.source.id : d.source;
  2350. const tid = typeof d.target === "object" ? d.target.id : d.target;
  2351. const isRelated = (sid === srcNodeId && tid === tgtNodeId) ||
  2352. (sid === tgtNodeId && tid === srcNodeId) ||
  2353. relatedNodeIds.has(sid) || relatedNodeIds.has(tid);
  2354. d3.select(this)
  2355. .classed("dimmed", !isRelated)
  2356. .classed("highlighted", isRelated);
  2357. }});
  2358. }} else {{
  2359. // 全部变灰
  2360. g.selectAll(".node").classed("dimmed", true).classed("highlighted", false);
  2361. g.selectAll(".link-group").classed("dimmed", true).classed("highlighted", false);
  2362. }}
  2363. }}
  2364. // 在关系图中展示这条边和两个节点
  2365. const edgeData = {{
  2366. 边类型: edgeType,
  2367. 源节点ID: srcNodeId,
  2368. 目标节点ID: tgtNodeId
  2369. }};
  2370. renderEgoGraphEdge(edgeData, sourceTreeNode, targetTreeNode);
  2371. }}
  2372. // 关系子图(Ego Graph)- 在画布第四层显示
  2373. let currentEgoSimulation = null; // 保存当前的力模拟,用于停止
  2374. function renderEgoGraph(centerNodeId, centerNodeName) {{
  2375. // 显示关系图容器
  2376. document.getElementById("ego-container").style.display = "block";
  2377. // 获取关系图层组
  2378. const egoGroup = d3.select(".ego-graph-content");
  2379. if (egoGroup.empty()) return;
  2380. // 停止之前的模拟
  2381. if (currentEgoSimulation) {{
  2382. currentEgoSimulation.stop();
  2383. currentEgoSimulation = null;
  2384. }}
  2385. // 清除旧内容
  2386. egoGroup.selectAll("*").remove();
  2387. // 更新标题
  2388. d3.select(".ego-container .ego-title").text(`关系图: ${{centerNodeName}}`);
  2389. // 获取层半径
  2390. const radius = 160; // 固定半径
  2391. // 找到所有相关的边
  2392. const relatedEdges = personaTreeData.edges.filter(e =>
  2393. e.源节点ID === centerNodeId || e.目标节点ID === centerNodeId
  2394. );
  2395. // 收集所有相关节点ID
  2396. const nodeIds = new Set([centerNodeId]);
  2397. relatedEdges.forEach(e => {{
  2398. nodeIds.add(e.源节点ID);
  2399. nodeIds.add(e.目标节点ID);
  2400. }});
  2401. // 构建节点数据
  2402. const nodeMap = {{}};
  2403. personaTreeData.nodes.forEach(n => {{
  2404. if (nodeIds.has(n.节点ID)) {{
  2405. nodeMap[n.节点ID] = {{
  2406. id: n.节点ID,
  2407. name: n.节点名称,
  2408. type: n.节点类型,
  2409. level: n.节点层级,
  2410. isCenter: n.节点ID === centerNodeId
  2411. }};
  2412. }}
  2413. }});
  2414. const nodes = Object.values(nodeMap);
  2415. const links = relatedEdges.map(e => ({{
  2416. source: e.源节点ID,
  2417. target: e.目标节点ID,
  2418. type: e.边类型
  2419. }}));
  2420. // 根据节点数量动态计算实际使用的半径
  2421. const nodeCount = nodes.length;
  2422. const nodeSpacingEgo = 65; // 节点间距(增大)
  2423. const minEgoRadius = 120;
  2424. const maxEgoRadius = Math.max(radius, 250); // 允许更大的半径
  2425. let actualRadius;
  2426. if (nodeCount <= 1) {{
  2427. actualRadius = minEgoRadius;
  2428. }} else {{
  2429. const circumference = nodeCount * nodeSpacingEgo;
  2430. const calcR = circumference / (2 * Math.PI);
  2431. actualRadius = Math.max(minEgoRadius, Math.min(maxEgoRadius, calcR));
  2432. }}
  2433. // 显示节点名称作为标题
  2434. egoGroup.append("text")
  2435. .attr("class", "ego-title")
  2436. .attr("y", -actualRadius - 15)
  2437. .attr("text-anchor", "middle")
  2438. .attr("fill", "#e94560")
  2439. .attr("font-size", "12px")
  2440. .attr("font-weight", "bold")
  2441. .text(centerNodeName + ` (${{nodeCount}}个节点)`);
  2442. // 如果没有相关节点,显示提示
  2443. if (nodes.length <= 1) {{
  2444. egoGroup.append("text")
  2445. .attr("text-anchor", "middle")
  2446. .attr("fill", "rgba(255,255,255,0.4)")
  2447. .attr("font-size", "11px")
  2448. .text("该节点没有相关边");
  2449. return;
  2450. }}
  2451. // 边类型颜色(统一用实线)
  2452. const edgeColors = {{
  2453. "属于": "#9b59b6", // 紫色 - 层级关系
  2454. "分类共现(跨点)": "#2ecc71", // 绿色 - 跨帖子分类共现
  2455. "分类共现(点内)": "#3498db", // 蓝色 - 同帖子分类共现
  2456. "标签共现": "#f39c12" // 橙色 - 标签共现
  2457. }};
  2458. // 维度颜色(与人设树完全一致)
  2459. const dimColors = {{
  2460. "灵感点": "#f39c12",
  2461. "目的点": "#3498db",
  2462. "关键点": "#9b59b6"
  2463. }};
  2464. // 获取节点的维度颜色(与人设树一致)
  2465. function getNodeDimColor(d) {{
  2466. // 根据节点层级判断维度
  2467. const level = d.level || "";
  2468. if (level.includes("灵感点")) return dimColors["灵感点"];
  2469. if (level.includes("目的点")) return dimColors["目的点"];
  2470. if (level.includes("关键点")) return dimColors["关键点"];
  2471. return "#888";
  2472. }}
  2473. // 获取节点填充色(实心,用维度颜色,不因选中而改变)
  2474. function getNodeFill(d) {{
  2475. return getNodeDimColor(d); // 始终用维度颜色填充
  2476. }}
  2477. // 获取节点边框色(选中节点用白色边框区分)
  2478. function getNodeStroke(d) {{
  2479. if (d.isCenter) return "#fff"; // 选中节点白色边框
  2480. return "rgba(255,255,255,0.5)"; // 普通节点半透明白边框
  2481. }}
  2482. // 获取节点边框粗细(选中节点更粗)
  2483. function getNodeStrokeWidth(d) {{
  2484. return d.isCenter ? 3 : 1.5;
  2485. }}
  2486. // 根据节点数量调整力模拟参数
  2487. const linkDistance = Math.max(50, Math.min(80, actualRadius / 2.5));
  2488. const chargeStrength = Math.max(-300, Math.min(-100, -nodeCount * 10));
  2489. const collisionRadius = 35; // 碰撞半径,防止重叠
  2490. // 创建力导向模拟(中心在0,0因为已经平移了)
  2491. const simulation = d3.forceSimulation(nodes)
  2492. .force("link", d3.forceLink(links).id(d => d.id).distance(linkDistance))
  2493. .force("charge", d3.forceManyBody().strength(chargeStrength))
  2494. .force("center", d3.forceCenter(0, 0))
  2495. .force("collision", d3.forceCollide().radius(collisionRadius))
  2496. .force("boundary", function() {{
  2497. // 限制节点在圆形区域内
  2498. const maxR = actualRadius - 30;
  2499. return function(alpha) {{
  2500. nodes.forEach(d => {{
  2501. const dist = Math.sqrt(d.x * d.x + d.y * d.y);
  2502. if (dist > maxR) {{
  2503. const scale = maxR / dist;
  2504. d.x *= scale;
  2505. d.y *= scale;
  2506. }}
  2507. }});
  2508. }};
  2509. }}());
  2510. currentEgoSimulation = simulation;
  2511. // 绘制边(统一用实线)
  2512. const link = egoGroup.selectAll(".ego-edge")
  2513. .data(links)
  2514. .join("line")
  2515. .attr("class", "ego-edge")
  2516. .attr("stroke", d => edgeColors[d.type] || "#666")
  2517. .attr("stroke-width", 1.5)
  2518. .attr("stroke-opacity", 0.7);
  2519. // 绘制节点(分类用方形,标签用圆形)
  2520. const node = egoGroup.selectAll(".ego-node")
  2521. .data(nodes)
  2522. .join("g")
  2523. .attr("class", d => "ego-node" + (d.isCenter ? " center" : ""));
  2524. // 根据节点类型绘制不同形状(与人设树样式一致)
  2525. const nodeSize = 8;
  2526. node.each(function(d) {{
  2527. const el = d3.select(this);
  2528. const fill = getNodeFill(d);
  2529. const stroke = getNodeStroke(d);
  2530. const size = d.isCenter ? nodeSize + 2 : nodeSize;
  2531. const strokeWidth = getNodeStrokeWidth(d);
  2532. if (d.type === "分类") {{
  2533. // 方形(分类节点)- 与人设树一致
  2534. el.append("rect")
  2535. .attr("class", "ego-shape")
  2536. .attr("width", size * 2)
  2537. .attr("height", size * 2)
  2538. .attr("x", -size)
  2539. .attr("y", -size)
  2540. .attr("fill", fill)
  2541. .attr("stroke", stroke)
  2542. .attr("stroke-width", strokeWidth)
  2543. .attr("rx", 1);
  2544. }} else {{
  2545. // 圆形(标签节点)- 与人设树一致
  2546. el.append("circle")
  2547. .attr("class", "ego-shape")
  2548. .attr("r", size)
  2549. .attr("fill", fill)
  2550. .attr("stroke", stroke)
  2551. .attr("stroke-width", strokeWidth);
  2552. }}
  2553. }});
  2554. node.append("text")
  2555. .attr("dy", -12)
  2556. .attr("text-anchor", "middle")
  2557. .attr("font-size", "9px")
  2558. .attr("fill", "#fff")
  2559. .text(d => d.name.length > 6 ? d.name.substring(0, 6) + ".." : d.name);
  2560. // 添加点击事件(直接调用共享函数)
  2561. node.on("click", function(event, d) {{
  2562. event.stopPropagation();
  2563. handleNodeClick(d.id, d.name);
  2564. }});
  2565. // 边点击事件(直接调用共享函数)
  2566. link.on("click", function(event, d) {{
  2567. event.stopPropagation();
  2568. handleEdgeClick(d.source.id, d.target.id, d.type);
  2569. }});
  2570. // 更新位置
  2571. simulation.on("tick", () => {{
  2572. link
  2573. .attr("x1", d => d.source.x)
  2574. .attr("y1", d => d.source.y)
  2575. .attr("x2", d => d.target.x)
  2576. .attr("y2", d => d.target.y);
  2577. node.attr("transform", d => `translate(${{d.x}},${{d.y}})`);
  2578. }});
  2579. }}
  2580. function clearEgoGraph() {{
  2581. const egoGroup = d3.select(".ego-graph-content");
  2582. if (!egoGroup.empty()) {{
  2583. egoGroup.selectAll("*").remove();
  2584. }}
  2585. // 隐藏关系图容器
  2586. document.getElementById("ego-container").style.display = "none";
  2587. // 停止模拟
  2588. if (currentEgoSimulation) {{
  2589. currentEgoSimulation.stop();
  2590. currentEgoSimulation = null;
  2591. }}
  2592. }}
  2593. // 渲染单条边和两个节点(点击树边时调用)
  2594. function renderEgoGraphEdge(edgeData, sourceNode, targetNode) {{
  2595. // 显示关系图容器
  2596. document.getElementById("ego-container").style.display = "block";
  2597. const egoGroup = d3.select(".ego-graph-content");
  2598. if (egoGroup.empty()) return;
  2599. // 停止之前的模拟
  2600. if (currentEgoSimulation) {{
  2601. currentEgoSimulation.stop();
  2602. currentEgoSimulation = null;
  2603. }}
  2604. // 清除旧内容
  2605. egoGroup.selectAll("*").remove();
  2606. // 更新标题
  2607. d3.select(".ego-container .ego-title").text(`关系图: ${{edgeData.边类型}}`);
  2608. const radius = 160;
  2609. // 边类型颜色
  2610. const edgeColors = {{
  2611. "属于": "#9b59b6",
  2612. "分类共现(跨点)": "#2ecc71",
  2613. "分类共现(点内)": "#3498db",
  2614. "标签共现": "#f39c12"
  2615. }};
  2616. // 维度颜色
  2617. const dimColors = {{
  2618. "灵感点": "#f39c12",
  2619. "目的点": "#3498db",
  2620. "关键点": "#9b59b6"
  2621. }};
  2622. // 获取节点颜色
  2623. function getNodeColor(nodeData) {{
  2624. const level = nodeData.节点层级 || "";
  2625. if (level.includes("灵感点")) return dimColors["灵感点"];
  2626. if (level.includes("目的点")) return dimColors["目的点"];
  2627. if (level.includes("关键点")) return dimColors["关键点"];
  2628. return "#888";
  2629. }}
  2630. // 标题
  2631. egoGroup.append("text")
  2632. .attr("class", "ego-title")
  2633. .attr("y", -80)
  2634. .attr("text-anchor", "middle")
  2635. .attr("fill", edgeColors[edgeData.边类型] || "#666")
  2636. .attr("font-size", "12px")
  2637. .attr("font-weight", "bold")
  2638. .text(`${{edgeData.边类型}}`);
  2639. // 两个节点的位置
  2640. const srcX = -60, srcY = 0;
  2641. const tgtX = 60, tgtY = 0;
  2642. // 绘制边
  2643. egoGroup.append("line")
  2644. .attr("class", "ego-edge")
  2645. .attr("x1", srcX)
  2646. .attr("y1", srcY)
  2647. .attr("x2", tgtX)
  2648. .attr("y2", tgtY)
  2649. .attr("stroke", edgeColors[edgeData.边类型] || "#666")
  2650. .attr("stroke-width", 3)
  2651. .attr("stroke-opacity", 0.8);
  2652. // 获取节点数据
  2653. const srcData = sourceNode ? sourceNode.data : {{}};
  2654. const tgtData = targetNode ? targetNode.data : {{}};
  2655. // 绘制源节点
  2656. const srcGroup = egoGroup.append("g")
  2657. .attr("class", "ego-node")
  2658. .attr("transform", `translate(${{srcX}}, ${{srcY}})`);
  2659. const srcSize = 15;
  2660. const srcColor = getNodeColor(srcData);
  2661. if (srcData.节点类型 === "分类") {{
  2662. srcGroup.append("rect")
  2663. .attr("width", srcSize * 2)
  2664. .attr("height", srcSize * 2)
  2665. .attr("x", -srcSize)
  2666. .attr("y", -srcSize)
  2667. .attr("fill", srcColor)
  2668. .attr("stroke", "rgba(255,255,255,0.5)")
  2669. .attr("stroke-width", 2)
  2670. .attr("rx", 2);
  2671. }} else {{
  2672. srcGroup.append("circle")
  2673. .attr("r", srcSize)
  2674. .attr("fill", srcColor)
  2675. .attr("stroke", "rgba(255,255,255,0.5)")
  2676. .attr("stroke-width", 2);
  2677. }}
  2678. srcGroup.append("text")
  2679. .attr("dy", -srcSize - 8)
  2680. .attr("text-anchor", "middle")
  2681. .attr("fill", "#fff")
  2682. .attr("font-size", "11px")
  2683. .text(srcData.节点名称 || srcData.name || "源节点");
  2684. // 绘制目标节点
  2685. const tgtGroup = egoGroup.append("g")
  2686. .attr("class", "ego-node")
  2687. .attr("transform", `translate(${{tgtX}}, ${{tgtY}})`);
  2688. const tgtSize = 15;
  2689. const tgtColor = getNodeColor(tgtData);
  2690. if (tgtData.节点类型 === "分类") {{
  2691. tgtGroup.append("rect")
  2692. .attr("width", tgtSize * 2)
  2693. .attr("height", tgtSize * 2)
  2694. .attr("x", -tgtSize)
  2695. .attr("y", -tgtSize)
  2696. .attr("fill", tgtColor)
  2697. .attr("stroke", "rgba(255,255,255,0.5)")
  2698. .attr("stroke-width", 2)
  2699. .attr("rx", 2);
  2700. }} else {{
  2701. tgtGroup.append("circle")
  2702. .attr("r", tgtSize)
  2703. .attr("fill", tgtColor)
  2704. .attr("stroke", "rgba(255,255,255,0.5)")
  2705. .attr("stroke-width", 2);
  2706. }}
  2707. tgtGroup.append("text")
  2708. .attr("dy", -tgtSize - 8)
  2709. .attr("text-anchor", "middle")
  2710. .attr("fill", "#fff")
  2711. .attr("font-size", "11px")
  2712. .text(tgtData.节点名称 || tgtData.name || "目标节点");
  2713. // 边标签
  2714. egoGroup.append("text")
  2715. .attr("y", 25)
  2716. .attr("text-anchor", "middle")
  2717. .attr("fill", "rgba(255,255,255,0.6)")
  2718. .attr("font-size", "10px")
  2719. .text(edgeData.边类型);
  2720. }}
  2721. // 页面加载完成后初始化
  2722. window.addEventListener("load", init);
  2723. window.addEventListener("resize", () => {{
  2724. if (currentIndex >= 0) {{
  2725. renderGraph(allGraphData[currentIndex]);
  2726. }}
  2727. }});
  2728. </script>
  2729. </body>
  2730. </html>
  2731. '''
  2732. def generate_combined_html(all_graph_data: List[Dict], persona_tree_data: Dict, output_file: Path):
  2733. """
  2734. 生成包含所有帖子图谱的HTML文件
  2735. Args:
  2736. all_graph_data: 所有帖子的图谱数据列表
  2737. persona_tree_data: 完整的人设树数据(节点和边)
  2738. output_file: 输出文件路径
  2739. """
  2740. # 生成Tab HTML
  2741. tabs_html = ""
  2742. for i, data in enumerate(all_graph_data):
  2743. post_title = data.get("postTitle", "")
  2744. # 使用帖子标题,如果太长则截断
  2745. if post_title:
  2746. tab_name = post_title[:15] + "..." if len(post_title) > 15 else post_title
  2747. else:
  2748. tab_name = f"帖子 {i+1}"
  2749. active_class = "active" if i == 0 else ""
  2750. tabs_html += f'<div class="tab {active_class}" data-index="{i}">{tab_name}</div>\n'
  2751. # 生成HTML
  2752. html_content = HTML_TEMPLATE.format(
  2753. tabs_html=tabs_html,
  2754. all_graph_data=json.dumps(all_graph_data, ensure_ascii=False),
  2755. persona_tree_data=json.dumps(persona_tree_data, ensure_ascii=False)
  2756. )
  2757. with open(output_file, "w", encoding="utf-8") as f:
  2758. f.write(html_content)
  2759. def main():
  2760. # 使用路径配置
  2761. config = PathConfig()
  2762. print(f"账号: {config.account_name}")
  2763. print(f"输出版本: {config.output_version}")
  2764. print()
  2765. # 输入目录
  2766. match_graph_dir = config.intermediate_dir / "match_graph"
  2767. # 输出文件
  2768. output_file = config.intermediate_dir / "match_graph.html"
  2769. print(f"输入目录: {match_graph_dir}")
  2770. print(f"输出文件: {output_file}")
  2771. print()
  2772. # 读取人设树中间数据
  2773. persona_tree_file = config.intermediate_dir / "persona_tree.json"
  2774. persona_tree_data = {"nodes": [], "edges": []}
  2775. if persona_tree_file.exists():
  2776. print(f"读取人设树数据: {persona_tree_file.name}")
  2777. with open(persona_tree_file, "r", encoding="utf-8") as f:
  2778. tree_data = json.load(f)
  2779. persona_tree_data["nodes"] = tree_data.get("nodes", [])
  2780. persona_tree_data["edges"] = tree_data.get("edges", [])
  2781. category_count = len([n for n in persona_tree_data["nodes"] if n.get("节点类型") == "分类"])
  2782. tag_count = len([n for n in persona_tree_data["nodes"] if n.get("节点类型") == "标签"])
  2783. print(f" 分类节点: {category_count}, 标签节点: {tag_count}")
  2784. print(f" 边数: {len(persona_tree_data['edges'])}")
  2785. print()
  2786. # 读取所有匹配图谱文件
  2787. graph_files = sorted(match_graph_dir.glob("*_match_graph.json"))
  2788. print(f"找到 {len(graph_files)} 个匹配图谱文件")
  2789. all_graph_data = []
  2790. for i, graph_file in enumerate(graph_files, 1):
  2791. print(f" [{i}/{len(graph_files)}] 读取: {graph_file.name}")
  2792. with open(graph_file, "r", encoding="utf-8") as f:
  2793. match_graph_data = json.load(f)
  2794. # 提取需要的数据
  2795. graph_data = {
  2796. "postId": match_graph_data["说明"]["帖子ID"],
  2797. "postTitle": match_graph_data["说明"].get("帖子标题", ""),
  2798. "stats": match_graph_data["说明"]["统计"],
  2799. "nodes": match_graph_data["节点列表"],
  2800. "edges": match_graph_data["边列表"]
  2801. }
  2802. all_graph_data.append(graph_data)
  2803. # 生成HTML
  2804. print("\n生成HTML文件...")
  2805. generate_combined_html(all_graph_data, persona_tree_data, output_file)
  2806. print("\n" + "="*60)
  2807. print("处理完成!")
  2808. print(f"输出文件: {output_file}")
  2809. if __name__ == "__main__":
  2810. main()