visualize_match_graph.py 122 KB

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