visualize_match_graph.py 128 KB

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