visualize_match_graph.py 157 KB

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