visualize_match_graph.py 116 KB

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