visualize_match_graph.py 114 KB

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