visualize_match_graph.py 151 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687
  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 personaSrcId, personaTgtId, edgeType;
  1827. if (isMirrorEdge && edgeDetail.源人设节点 && edgeDetail.目标人设节点) {{
  1828. // 镜像边:使用对应的人设节点
  1829. personaSrcId = edgeDetail.源人设节点;
  1830. personaTgtId = edgeDetail.目标人设节点;
  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. personaSrcId = sourceNode ? sourceNode.id : d.source;
  1837. personaTgtId = targetNode ? targetNode.id : d.target;
  1838. edgeType = d.type;
  1839. }}
  1840. // 3. 同步人设树高亮和关系图展示
  1841. syncTreeAndRelationGraph(personaSrcId, personaTgtId, edgeType);
  1842. }})
  1843. .on("mouseover", function(event, d) {{
  1844. d3.select(this.parentNode).select(".link")
  1845. .attr("stroke-opacity", 1)
  1846. .attr("stroke-width", 4);
  1847. }})
  1848. .on("mouseout", function(event, d) {{
  1849. d3.select(this.parentNode).select(".link")
  1850. .attr("stroke-opacity", 0.7)
  1851. .attr("stroke-width", d.type.startsWith("匹配_") ? 2.5 : 1.5);
  1852. }});
  1853. // 绘制节点
  1854. const node = g.append("g")
  1855. .selectAll("g")
  1856. .data(nodes)
  1857. .join("g")
  1858. .attr("class", "node")
  1859. .call(d3.drag()
  1860. .on("start", dragstarted)
  1861. .on("drag", dragged)
  1862. .on("end", dragended));
  1863. // 根据节点类型绘制不同形状
  1864. // - 点节点(帖子点):六边形
  1865. // - 标签节点:圆形
  1866. // - 分类节点:方形
  1867. // 帖子标签用虚线,人设标签用实线
  1868. node.each(function(d) {{
  1869. const el = d3.select(this);
  1870. const isPointNode = d.节点类型 === "点";
  1871. const isPostNode = d.source === "帖子";
  1872. // 节点大小
  1873. let size;
  1874. if (isPointNode) {{
  1875. size = 16; // 点节点最大
  1876. }} else if (isPostNode) {{
  1877. size = 12; // 帖子标签
  1878. }} else {{
  1879. size = 10; // 人设标签
  1880. }}
  1881. const fill = levelColors[d.level] || "#666";
  1882. const nodeClass = isPostNode
  1883. ? (isPointNode ? "post-point-node" : "post-node")
  1884. : "persona-node";
  1885. if (isPointNode) {{
  1886. // 六边形(点节点)
  1887. const hexPoints = [];
  1888. for (let i = 0; i < 6; i++) {{
  1889. const angle = (i * 60 - 30) * Math.PI / 180;
  1890. hexPoints.push([size * Math.cos(angle), size * Math.sin(angle)]);
  1891. }}
  1892. el.append("polygon")
  1893. .attr("points", hexPoints.map(p => p.join(",")).join(" "))
  1894. .attr("fill", fill)
  1895. .attr("class", nodeClass);
  1896. }} else if (d.节点类型 === "分类") {{
  1897. // 方形(分类节点)
  1898. el.append("rect")
  1899. .attr("width", size * 2)
  1900. .attr("height", size * 2)
  1901. .attr("x", -size)
  1902. .attr("y", -size)
  1903. .attr("fill", fill)
  1904. .attr("class", nodeClass)
  1905. .attr("rx", 3);
  1906. }} else {{
  1907. // 圆形(标签节点)
  1908. el.append("circle")
  1909. .attr("r", size)
  1910. .attr("fill", fill)
  1911. .attr("class", nodeClass);
  1912. }}
  1913. }});
  1914. const labels = node.append("text")
  1915. .attr("dx", 15)
  1916. .attr("dy", 4)
  1917. .text(d => d.节点名称)
  1918. .style("display", showLabels ? "block" : "none");
  1919. // 工具提示
  1920. const tooltip = d3.select("#tooltip");
  1921. node.on("mouseover", (event, d) => {{
  1922. let html = `<strong>${{d.节点名称}}</strong><br/>类型: ${{d.节点类型}}<br/>层级: ${{d.节点层级}}`;
  1923. // 点节点显示描述
  1924. if (d.描述) {{
  1925. html += `<br/><br/><em style="font-size:10px;color:#aaa">${{d.描述.slice(0, 100)}}${{d.描述.length > 100 ? '...' : ''}}</em>`;
  1926. }}
  1927. tooltip.style("display", "block").html(html);
  1928. }})
  1929. .on("mousemove", (event) => {{
  1930. tooltip.style("left", (event.pageX + 15) + "px")
  1931. .style("top", (event.pageY - 10) + "px");
  1932. }})
  1933. .on("mouseout", () => {{
  1934. tooltip.style("display", "none");
  1935. }})
  1936. .on("click", (event, d) => {{
  1937. event.stopPropagation();
  1938. highlightNode(d);
  1939. showNodeInfo(d);
  1940. // 人设节点联动:高亮人设树 + 显示关系图
  1941. if (d.source === "人设") {{
  1942. handleNodeClick(d.节点ID, d.节点名称);
  1943. }}
  1944. }});
  1945. // 更新位置
  1946. simulation.on("tick", () => {{
  1947. // 更新热区线
  1948. linkHitarea
  1949. .attr("x1", d => d.source.x)
  1950. .attr("y1", d => d.source.y)
  1951. .attr("x2", d => d.target.x)
  1952. .attr("y2", d => d.target.y);
  1953. // 更新可见边
  1954. link
  1955. .attr("x1", d => d.source.x)
  1956. .attr("y1", d => d.source.y)
  1957. .attr("x2", d => d.target.x)
  1958. .attr("y2", d => d.target.y);
  1959. // 更新边标签位置(放在边的中点)
  1960. edgeLabels.attr("transform", d => {{
  1961. const midX = (d.source.x + d.target.x) / 2;
  1962. const midY = (d.source.y + d.target.y) / 2;
  1963. return `translate(${{midX}},${{midY}})`;
  1964. }});
  1965. // 更新标签背景大小
  1966. edgeLabels.each(function(d) {{
  1967. const textEl = d3.select(this).select("text").node();
  1968. if (textEl) {{
  1969. const bbox = textEl.getBBox();
  1970. d3.select(this).select("rect")
  1971. .attr("x", bbox.x - 3)
  1972. .attr("y", bbox.y - 1)
  1973. .attr("width", bbox.width + 6)
  1974. .attr("height", bbox.height + 2);
  1975. }}
  1976. }});
  1977. node.attr("transform", d => `translate(${{d.x}},${{d.y}})`);
  1978. }});
  1979. // 拖拽函数
  1980. function dragstarted(event, d) {{
  1981. if (!event.active) simulation.alphaTarget(0.3).restart();
  1982. d.fx = d.x;
  1983. d.fy = d.y;
  1984. }}
  1985. function dragged(event, d) {{
  1986. d.fx = event.x;
  1987. d.fy = event.y;
  1988. }}
  1989. function dragended(event, d) {{
  1990. if (!event.active) simulation.alphaTarget(0);
  1991. d.fx = null;
  1992. d.fy = null;
  1993. }}
  1994. // 清除所有高亮
  1995. function clearHighlight() {{
  1996. node.classed("dimmed", false).classed("highlighted", false);
  1997. linkG.classed("dimmed", false).classed("highlighted", false);
  1998. // 恢复跨层边的可见性状态(根据全局开关)
  1999. linkG.each(function(d) {{
  2000. if (isCrossLayerEdge(d)) {{
  2001. d3.select(this).style("display", showCrossLayerEdges ? "block" : "none");
  2002. }}
  2003. }});
  2004. }}
  2005. // 高亮指定的节点和边
  2006. function highlightElements(highlightNodeIds, highlightLinkIndices) {{
  2007. // 先灰化所有
  2008. node.classed("dimmed", true).classed("highlighted", false);
  2009. linkG.classed("dimmed", true).classed("highlighted", false);
  2010. // 高亮指定节点
  2011. node.filter(d => highlightNodeIds.has(d.id))
  2012. .classed("dimmed", false)
  2013. .classed("highlighted", true);
  2014. // 高亮指定边
  2015. linkG.filter((d, i) => highlightLinkIndices.has(i))
  2016. .classed("dimmed", false)
  2017. .classed("highlighted", true);
  2018. }}
  2019. // 点击节点时的高亮逻辑
  2020. function highlightNode(clickedNode) {{
  2021. const highlightNodeIds = new Set([clickedNode.id]);
  2022. const highlightLinkIndices = new Set();
  2023. links.forEach((link, i) => {{
  2024. const sourceId = typeof link.source === "object" ? link.source.id : link.source;
  2025. const targetId = typeof link.target === "object" ? link.target.id : link.target;
  2026. // 与点击节点直接相连的边
  2027. if (sourceId === clickedNode.id || targetId === clickedNode.id) {{
  2028. highlightLinkIndices.add(i);
  2029. highlightNodeIds.add(sourceId);
  2030. highlightNodeIds.add(targetId);
  2031. // 如果是帖子节点,还要高亮对应的镜像边
  2032. if (clickedNode.source === "帖子") {{
  2033. // 找到通过该帖子连接的其他帖子(镜像边)
  2034. links.forEach((otherLink, j) => {{
  2035. const otherType = otherLink.type;
  2036. if (otherType.startsWith("镜像_") || otherType.startsWith("二阶_")) {{
  2037. const oSrc = typeof otherLink.source === "object" ? otherLink.source.id : otherLink.source;
  2038. const oTgt = typeof otherLink.target === "object" ? otherLink.target.id : otherLink.target;
  2039. if (oSrc === clickedNode.id || oTgt === clickedNode.id) {{
  2040. highlightLinkIndices.add(j);
  2041. highlightNodeIds.add(oSrc);
  2042. highlightNodeIds.add(oTgt);
  2043. }}
  2044. }}
  2045. }});
  2046. }}
  2047. }}
  2048. }});
  2049. // 高亮相关的节点和边
  2050. highlightElements(highlightNodeIds, highlightLinkIndices);
  2051. // 临时显示关联的跨层边(即使全局开关是关闭的)
  2052. linkG.each(function(d, i) {{
  2053. if (highlightLinkIndices.has(i)) {{
  2054. d3.select(this).style("display", "block");
  2055. }}
  2056. }});
  2057. }}
  2058. // 点击边时的高亮逻辑
  2059. function highlightEdge(clickedLink, clickedIndex) {{
  2060. const highlightNodeIds = new Set();
  2061. const highlightLinkIndices = new Set([clickedIndex]);
  2062. const sourceId = typeof clickedLink.source === "object" ? clickedLink.source.id : clickedLink.source;
  2063. const targetId = typeof clickedLink.target === "object" ? clickedLink.target.id : clickedLink.target;
  2064. highlightNodeIds.add(sourceId);
  2065. highlightNodeIds.add(targetId);
  2066. // 如果是镜像边或二阶边,使用预计算的路径节点高亮
  2067. if ((clickedLink.type.startsWith("镜像_") || clickedLink.type.startsWith("二阶_")) && clickedLink.边详情) {{
  2068. const detail = clickedLink.边详情;
  2069. const pathNodes = new Set([sourceId, targetId]);
  2070. // 使用预计算的路径节点
  2071. (detail.路径节点 || []).forEach(n => pathNodes.add(n));
  2072. // 高亮路径上的所有节点
  2073. pathNodes.forEach(n => highlightNodeIds.add(n));
  2074. // 高亮连接路径节点的边
  2075. links.forEach((link, i) => {{
  2076. const lSrc = typeof link.source === "object" ? link.source.id : link.source;
  2077. const lTgt = typeof link.target === "object" ? link.target.id : link.target;
  2078. if (pathNodes.has(lSrc) && pathNodes.has(lTgt)) {{
  2079. highlightLinkIndices.add(i);
  2080. }}
  2081. }});
  2082. }}
  2083. // 如果是人设边(两端都不是帖子节点),找对应的镜像边
  2084. else if (!sourceId.startsWith("帖子_") && !targetId.startsWith("帖子_")) {{
  2085. // 收集路径节点
  2086. const pathNodes = new Set([sourceId, targetId]);
  2087. // 找匹配的镜像边,读取其路径节点
  2088. links.forEach((link, i) => {{
  2089. const detail = link.边详情 || {{}};
  2090. if ((link.type.startsWith("镜像_") || link.type.startsWith("二阶_")) && detail.源人设节点 && detail.目标人设节点) {{
  2091. const matches = (detail.源人设节点 === sourceId && detail.目标人设节点 === targetId) ||
  2092. (detail.源人设节点 === targetId && detail.目标人设节点 === sourceId);
  2093. if (matches) {{
  2094. highlightLinkIndices.add(i);
  2095. // 直接使用预存的路径节点
  2096. (detail.路径节点 || []).forEach(n => pathNodes.add(n));
  2097. }}
  2098. }}
  2099. }});
  2100. // 高亮路径上的所有节点
  2101. pathNodes.forEach(n => highlightNodeIds.add(n));
  2102. // 高亮连接路径节点的边
  2103. links.forEach((link, i) => {{
  2104. const lSrc = typeof link.source === "object" ? link.source.id : link.source;
  2105. const lTgt = typeof link.target === "object" ? link.target.id : link.target;
  2106. // 两端都在路径上的边
  2107. if (pathNodes.has(lSrc) && pathNodes.has(lTgt)) {{
  2108. highlightLinkIndices.add(i);
  2109. }}
  2110. }});
  2111. }}
  2112. // 高亮相关的节点和边
  2113. highlightElements(highlightNodeIds, highlightLinkIndices);
  2114. // 临时显示关联的跨层边(即使全局开关是关闭的)
  2115. linkG.each(function(d, i) {{
  2116. if (highlightLinkIndices.has(i)) {{
  2117. d3.select(this).style("display", "block");
  2118. }}
  2119. }});
  2120. }}
  2121. // 点击空白处清除高亮(合并所有空白点击逻辑)
  2122. svg.on("click", (event) => {{
  2123. // 检查是否点击的是空白区域(svg本身或layer-backgrounds)
  2124. const isBlank = event.target === svg.node() ||
  2125. event.target.tagName === "svg" ||
  2126. event.target.classList.contains("layer-backgrounds");
  2127. if (isBlank) {{
  2128. // 清除右侧图高亮
  2129. clearHighlight();
  2130. // 清除人设树高亮
  2131. resetTreeHighlight();
  2132. resetGraphHighlight();
  2133. // 关闭详情面板
  2134. closeDetailPanel();
  2135. // 清除关系图
  2136. clearEgoGraph();
  2137. }}
  2138. }});
  2139. }}
  2140. // 控制函数
  2141. function resetZoom() {{
  2142. const container = document.getElementById("svg-container");
  2143. const width = container.clientWidth;
  2144. const height = container.clientHeight;
  2145. svg.transition().duration(750).call(
  2146. zoom.transform,
  2147. d3.zoomIdentity.translate(width/2, height/2).scale(1).translate(-width/2, -height/2)
  2148. );
  2149. }}
  2150. function toggleLabels() {{
  2151. showLabels = !showLabels;
  2152. g.selectAll(".node text").style("display", showLabels ? "block" : "none");
  2153. }}
  2154. // 切换跨层边显示
  2155. function toggleCrossLayerEdges() {{
  2156. showCrossLayerEdges = !showCrossLayerEdges;
  2157. const btn = document.getElementById("crossLayerBtn");
  2158. btn.textContent = showCrossLayerEdges ? "隐藏跨层边" : "显示跨层边";
  2159. btn.style.background = showCrossLayerEdges ? "#e94560" : "";
  2160. // 更新边的可见性(使用 isCrossLayerEdge 函数判断)
  2161. g.selectAll(".link-group").each(function(d) {{
  2162. if (isCrossLayerEdge(d)) {{
  2163. d3.select(this).style("display", showCrossLayerEdges ? "block" : "none");
  2164. }}
  2165. }});
  2166. }}
  2167. function showNodeInfo(d) {{
  2168. const panel = document.getElementById("detailPanel");
  2169. panel.classList.add("active");
  2170. document.getElementById("detailTitle").textContent = d.source === "帖子" ? "📌 帖子节点" : "👤 人设节点";
  2171. let html = `
  2172. <p><span class="label">节点ID:</span> ${{d.节点ID}}</p>
  2173. <p><span class="label">名称:</span> <strong>${{d.节点名称}}</strong></p>
  2174. <p><span class="label">类型:</span> ${{d.节点类型}}</p>
  2175. <p><span class="label">层级:</span> ${{d.节点层级}}</p>
  2176. `;
  2177. if (d.权重) {{
  2178. html += `<p><span class="label">权重:</span> ${{d.权重}}</p>`;
  2179. }}
  2180. if (d.所属分类 && d.所属分类.length > 0) {{
  2181. html += `<p><span class="label">所属分类:</span> ${{d.所属分类.join(" > ")}}</p>`;
  2182. }}
  2183. if (d.帖子数) {{
  2184. html += `<p><span class="label">帖子数:</span> ${{d.帖子数}}</p>`;
  2185. }}
  2186. document.getElementById("detailContent").innerHTML = html;
  2187. }}
  2188. // 显示人设树节点详情(包含入边、出边、相关节点)
  2189. function showTreeNodeDetail(nodeData, inEdges, outEdges) {{
  2190. const panel = document.getElementById("detailPanel");
  2191. panel.classList.add("active");
  2192. document.getElementById("detailTitle").textContent = "🌳 人设树节点";
  2193. // 节点基本信息
  2194. let html = `
  2195. <p><span class="label">名称:</span> <strong>${{nodeData.节点名称 || nodeData.name}}</strong></p>
  2196. <p><span class="label">类型:</span> ${{nodeData.节点类型 || (nodeData.isRoot ? "根节点" : "维度")}}</p>
  2197. <p><span class="label">层级:</span> ${{nodeData.节点层级 || "-"}}</p>
  2198. `;
  2199. if (nodeData.所属分类 && nodeData.所属分类.length > 0) {{
  2200. html += `<p><span class="label">所属分类:</span> ${{nodeData.所属分类.join(" > ")}}</p>`;
  2201. }}
  2202. if (nodeData.帖子数) {{
  2203. html += `<p><span class="label">帖子数:</span> ${{nodeData.帖子数}}</p>`;
  2204. }}
  2205. // 统计边类型
  2206. const inEdgeTypes = {{}};
  2207. const outEdgeTypes = {{}};
  2208. inEdges.forEach(e => {{ inEdgeTypes[e.边类型] = (inEdgeTypes[e.边类型] || 0) + 1; }});
  2209. outEdges.forEach(e => {{ outEdgeTypes[e.边类型] = (outEdgeTypes[e.边类型] || 0) + 1; }});
  2210. // 入边统计
  2211. html += `<h4 style="margin-top:12px;color:#3498db;font-size:12px;">📥 入边 (${{inEdges.length}})</h4>`;
  2212. if (inEdges.length > 0) {{
  2213. html += `<div class="edge-list">`;
  2214. for (const [type, count] of Object.entries(inEdgeTypes)) {{
  2215. html += `<div class="edge-type-item"><span class="edge-type">${{type}}</span><span class="edge-count">${{count}}</span></div>`;
  2216. }}
  2217. // 显示前5条入边详情
  2218. const showInEdges = inEdges.slice(0, 5);
  2219. showInEdges.forEach(e => {{
  2220. const srcName = personaTreeData.nodes.find(n => n.节点ID === e.源节点ID)?.节点名称 || e.源节点ID;
  2221. html += `<div class="edge-detail">← ${{srcName}} <span class="edge-type-tag">${{e.边类型}}</span></div>`;
  2222. }});
  2223. if (inEdges.length > 5) {{
  2224. html += `<div class="edge-more">... 还有 ${{inEdges.length - 5}} 条</div>`;
  2225. }}
  2226. html += `</div>`;
  2227. }} else {{
  2228. html += `<div class="edge-empty">无</div>`;
  2229. }}
  2230. // 出边统计
  2231. html += `<h4 style="margin-top:12px;color:#e74c3c;font-size:12px;">📤 出边 (${{outEdges.length}})</h4>`;
  2232. if (outEdges.length > 0) {{
  2233. html += `<div class="edge-list">`;
  2234. for (const [type, count] of Object.entries(outEdgeTypes)) {{
  2235. html += `<div class="edge-type-item"><span class="edge-type">${{type}}</span><span class="edge-count">${{count}}</span></div>`;
  2236. }}
  2237. // 显示前5条出边详情
  2238. const showOutEdges = outEdges.slice(0, 5);
  2239. showOutEdges.forEach(e => {{
  2240. const tgtName = personaTreeData.nodes.find(n => n.节点ID === e.目标节点ID)?.节点名称 || e.目标节点ID;
  2241. html += `<div class="edge-detail">→ ${{tgtName}} <span class="edge-type-tag">${{e.边类型}}</span></div>`;
  2242. }});
  2243. if (outEdges.length > 5) {{
  2244. html += `<div class="edge-more">... 还有 ${{outEdges.length - 5}} 条</div>`;
  2245. }}
  2246. html += `</div>`;
  2247. }} else {{
  2248. html += `<div class="edge-empty">无</div>`;
  2249. }}
  2250. document.getElementById("detailContent").innerHTML = html;
  2251. }}
  2252. function showEdgeInfo(d) {{
  2253. const panel = document.getElementById("detailPanel");
  2254. panel.classList.add("active");
  2255. const sourceNode = typeof d.source === "object" ? d.source : {{ id: d.source }};
  2256. const targetNode = typeof d.target === "object" ? d.target : {{ id: d.target }};
  2257. // 判断是否为镜像边
  2258. const isMirror = d.type.startsWith("镜像_");
  2259. document.getElementById("detailTitle").textContent = isMirror ? "🪞 镜像边详情" : "🔗 边详情";
  2260. let html = `
  2261. <p><span class="label">边类型:</span> <strong>${{d.type}}</strong></p>
  2262. <p><span class="label">源节点:</span> ${{sourceNode.节点名称 || sourceNode.id}}</p>
  2263. <p><span class="label">目标节点:</span> ${{targetNode.节点名称 || targetNode.id}}</p>
  2264. `;
  2265. if (d.边详情) {{
  2266. if (d.边详情.相似度 !== undefined) {{
  2267. const score = typeof d.边详情.相似度 === "number" ? d.边详情.相似度.toFixed(2) : d.边详情.相似度;
  2268. html += `<p><span class="label">相似度:</span> <span class="similarity-score">${{score}}</span></p>`;
  2269. }}
  2270. if (d.边详情.说明) {{
  2271. html += `<p><span class="label">说明:</span></p><div class="edge-description">${{d.边详情.说明}}</div>`;
  2272. }}
  2273. if (d.边详情.共现次数 !== undefined) {{
  2274. html += `<p><span class="label">共现次数:</span> ${{d.边详情.共现次数}}</p>`;
  2275. }}
  2276. // 镜像边特有信息
  2277. if (d.边详情.原始边类型) {{
  2278. html += `<p><span class="label">原始边类型:</span> ${{d.边详情.原始边类型}}</p>`;
  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. }}
  2287. document.getElementById("detailContent").innerHTML = html;
  2288. }}
  2289. function closeDetailPanel() {{
  2290. document.getElementById("detailPanel").classList.remove("active");
  2291. }}
  2292. // 更新匹配列表
  2293. function updateMatchList(matchLinks, nodes) {{
  2294. const listEl = document.getElementById("matchList");
  2295. const countEl = document.getElementById("matchCount");
  2296. // 构建节点ID到名称的映射
  2297. const nodeNames = {{}};
  2298. nodes.forEach(n => {{
  2299. nodeNames[n.id] = n.节点名称 || n.id;
  2300. }});
  2301. // 按分数降序排序
  2302. const sortedLinks = [...matchLinks].sort((a, b) => {{
  2303. const scoreA = a.边详情?.相似度 ?? 0;
  2304. const scoreB = b.边详情?.相似度 ?? 0;
  2305. return scoreB - scoreA;
  2306. }});
  2307. countEl.textContent = `(${{sortedLinks.length}})`;
  2308. // 生成列表HTML
  2309. let html = "";
  2310. sortedLinks.forEach((link, index) => {{
  2311. const score = link.边详情?.相似度;
  2312. const scoreText = score !== undefined ? score.toFixed(2) : "N/A";
  2313. const scoreClass = score >= 0.8 ? "high" : (score >= 0.5 ? "medium" : "");
  2314. const srcId = typeof link.source === "object" ? link.source.id : link.source;
  2315. const tgtId = typeof link.target === "object" ? link.target.id : link.target;
  2316. const srcName = nodeNames[srcId] || srcId;
  2317. const tgtName = nodeNames[tgtId] || tgtId;
  2318. html += `
  2319. <div class="match-item" data-index="${{index}}" data-src="${{srcId}}" data-tgt="${{tgtId}}">
  2320. <span class="score ${{scoreClass}}">${{scoreText}}</span>
  2321. <span class="names" title="${{srcName}} → ${{tgtName}}">${{srcName}} → ${{tgtName}}</span>
  2322. </div>
  2323. `;
  2324. }});
  2325. listEl.innerHTML = html;
  2326. // 添加点击事件
  2327. listEl.querySelectorAll(".match-item").forEach(item => {{
  2328. item.addEventListener("click", () => {{
  2329. const srcId = item.dataset.src;
  2330. const tgtId = item.dataset.tgt;
  2331. const index = parseInt(item.dataset.index);
  2332. // 高亮对应的边
  2333. highlightMatchEdge(srcId, tgtId);
  2334. // 更新列表项样式
  2335. listEl.querySelectorAll(".match-item").forEach(el => el.classList.remove("active"));
  2336. item.classList.add("active");
  2337. }});
  2338. }});
  2339. }}
  2340. // 高亮匹配边
  2341. function highlightMatchEdge(srcId, tgtId) {{
  2342. if (!g) return;
  2343. // 重置所有
  2344. g.selectAll(".node").classed("dimmed", true).classed("highlighted", false);
  2345. g.selectAll(".link-group").classed("dimmed", true).classed("highlighted", false);
  2346. // 高亮对应的边和节点
  2347. g.selectAll(".link-group").each(function(d) {{
  2348. const dSrc = typeof d.source === "object" ? d.source.id : d.source;
  2349. const dTgt = typeof d.target === "object" ? d.target.id : d.target;
  2350. if ((dSrc === srcId && dTgt === tgtId) || (dSrc === tgtId && dTgt === srcId)) {{
  2351. d3.select(this).classed("dimmed", false).classed("highlighted", true);
  2352. }}
  2353. }});
  2354. g.selectAll(".node").each(function(d) {{
  2355. if (d.id === srcId || d.id === tgtId) {{
  2356. d3.select(this).classed("dimmed", false).classed("highlighted", true);
  2357. }}
  2358. }});
  2359. }}
  2360. // 获取节点颜色(全局版本,根据节点数据判断维度)
  2361. function getTreeNodeColor(d) {{
  2362. const dimColors = {{ "灵感点": "#f39c12", "目的点": "#3498db", "关键点": "#9b59b6" }};
  2363. if (d.data.isRoot) return "#e94560";
  2364. if (d.data.isDimension) return d.data.dimColor;
  2365. return d.data.dimColor || "#888";
  2366. }}
  2367. // 共享的节点点击处理函数(人设树和关系图复用)
  2368. function handleNodeClick(clickedNodeId, clickedNodeName) {{
  2369. if (!clickedNodeId) return;
  2370. // 动态获取树相关元素
  2371. const treeGroup = d3.select(".persona-tree");
  2372. if (treeGroup.empty()) return;
  2373. const treeEdges = treeGroup.selectAll(".tree-edge");
  2374. // 先重置所有高亮状态
  2375. treeGroup.selectAll(".tree-node")
  2376. .classed("tree-dimmed", false)
  2377. .classed("tree-highlighted", false);
  2378. treeGroup.selectAll(".tree-node .tree-shape")
  2379. .attr("fill", d => getTreeNodeColor(d))
  2380. .attr("stroke", "rgba(255,255,255,0.5)")
  2381. .attr("stroke-width", 1)
  2382. .attr("stroke-opacity", 1)
  2383. .attr("opacity", 1);
  2384. treeGroup.selectAll(".tree-node text")
  2385. .attr("fill", d => (d.data.isRoot || d.data.isDimension) ? getTreeNodeColor(d) : "#bbb")
  2386. .attr("opacity", 1);
  2387. treeEdges.attr("stroke-opacity", 0.3).attr("stroke-width", 1);
  2388. if (g) {{
  2389. g.selectAll(".node").classed("dimmed", false).classed("highlighted", false);
  2390. g.selectAll(".link-group").classed("dimmed", false).classed("highlighted", false);
  2391. }}
  2392. // 构建节点ID到D3节点的映射
  2393. const treeNodeById = {{}};
  2394. treeGroup.selectAll(".tree-node").each(function(n) {{
  2395. if (n.data.节点ID) treeNodeById[n.data.节点ID] = n;
  2396. }});
  2397. // 使用多级配置收集关联节点(与关系图一致)
  2398. const levelConfigs = getLevelConfigs();
  2399. const {{ nodeIds: connectedNodeIds, edges: allConnectedEdges }} = collectNodesAndEdges(clickedNodeId, levelConfigs);
  2400. // 获取D3树节点
  2401. const clickedD3Node = treeNodeById[clickedNodeId];
  2402. // 转换为D3节点集合(只基于 collectNodesAndEdges 的结果,与关系图同步)
  2403. const connectedD3Nodes = new Set();
  2404. if (clickedD3Node) connectedD3Nodes.add(clickedD3Node);
  2405. connectedNodeIds.forEach(id => {{
  2406. if (treeNodeById[id]) connectedD3Nodes.add(treeNodeById[id]);
  2407. }});
  2408. // 高亮树中的节点
  2409. treeGroup.selectAll(".tree-node")
  2410. .classed("tree-dimmed", n => !connectedD3Nodes.has(n))
  2411. .classed("tree-highlighted", n => connectedD3Nodes.has(n));
  2412. // 高亮所有形状(不变粗)
  2413. treeGroup.selectAll(".tree-node .tree-shape")
  2414. .attr("fill", function(n) {{
  2415. if (!connectedD3Nodes.has(n)) return "#555";
  2416. return getTreeNodeColor(n);
  2417. }})
  2418. .attr("stroke", function(n) {{
  2419. if (n.data.节点ID === clickedNodeId) return "#fff";
  2420. return connectedD3Nodes.has(n) ? "rgba(255,255,255,0.8)" : "#333";
  2421. }})
  2422. .attr("stroke-opacity", 1);
  2423. treeGroup.selectAll(".tree-node text")
  2424. .attr("fill", function(n) {{
  2425. if (!connectedD3Nodes.has(n)) return "#555";
  2426. return (n.data.isRoot || n.data.isDimension) ? getTreeNodeColor(n) : "#bbb";
  2427. }});
  2428. // 边高亮(树边基于连接的节点)
  2429. treeEdges.attr("stroke-opacity", function(e) {{
  2430. // 树边高亮条件:子节点(目标)在连接集中,或者两端都在连接集中
  2431. const srcId = e.源节点ID;
  2432. const tgtId = e.目标节点ID;
  2433. const srcConnected = connectedNodeIds.has(srcId) || connectedD3Nodes.has(e.sourceNode);
  2434. const tgtConnected = connectedNodeIds.has(tgtId) || connectedD3Nodes.has(e.targetNode);
  2435. return (srcConnected && tgtConnected) ? 0.9 : 0.15;
  2436. }});
  2437. // 计算入边和出边
  2438. const inEdges = allConnectedEdges.filter(e => e.目标节点ID === clickedNodeId);
  2439. const outEdges = allConnectedEdges.filter(e => e.源节点ID === clickedNodeId);
  2440. // 显示详情面板
  2441. const nodeData = personaTreeData.nodes.find(n => n.节点ID === clickedNodeId);
  2442. if (nodeData) {{
  2443. showTreeNodeDetail(nodeData, inEdges, outEdges);
  2444. }}
  2445. // 显示关系子图(先显示,这样容器高度才正确)
  2446. renderEgoGraph(clickedNodeId, clickedNodeName);
  2447. // 滚动人设树到对应节点位置(放在关系图显示后,高度才准确)
  2448. if (clickedD3Node) {{
  2449. // 用 setTimeout 确保 DOM 更新完成
  2450. setTimeout(() => {{
  2451. const treeContainer = document.getElementById("tree-container");
  2452. const containerHeight = treeContainer.clientHeight;
  2453. // D3树布局中 x 是垂直方向(因为是水平树)
  2454. const nodeY = clickedD3Node.x + 25; // 加上treeGroup的transform偏移
  2455. const targetScroll = nodeY - containerHeight / 2;
  2456. treeContainer.scrollTo({{
  2457. top: Math.max(0, targetScroll),
  2458. behavior: "smooth"
  2459. }});
  2460. }}, 50);
  2461. }}
  2462. // 高亮右侧图中对应节点及其相关节点和边
  2463. if (g) {{
  2464. // 收集相关节点ID(点击的节点及其直接连接的节点)
  2465. const relatedNodeIds = new Set([clickedNodeId]);
  2466. // 找所有与该节点相连的边
  2467. g.selectAll(".link-group").each(function(d) {{
  2468. const srcId = typeof d.source === "object" ? d.source.id : d.source;
  2469. const tgtId = typeof d.target === "object" ? d.target.id : d.target;
  2470. if (srcId === clickedNodeId || tgtId === clickedNodeId) {{
  2471. relatedNodeIds.add(srcId);
  2472. relatedNodeIds.add(tgtId);
  2473. }}
  2474. }});
  2475. // 检查是否有相关节点在图中
  2476. const hasRelatedNodes = g.selectAll(".node").filter(n => relatedNodeIds.has(n.id)).size() > 0;
  2477. if (hasRelatedNodes) {{
  2478. // 高亮相关节点,变灰其他
  2479. g.selectAll(".node")
  2480. .classed("dimmed", n => !relatedNodeIds.has(n.id))
  2481. .classed("highlighted", n => relatedNodeIds.has(n.id));
  2482. // 高亮相关边
  2483. g.selectAll(".link-group").each(function(d) {{
  2484. const srcId = typeof d.source === "object" ? d.source.id : d.source;
  2485. const tgtId = typeof d.target === "object" ? d.target.id : d.target;
  2486. const isRelated = srcId === clickedNodeId || tgtId === clickedNodeId;
  2487. d3.select(this)
  2488. .classed("dimmed", !isRelated)
  2489. .classed("highlighted", isRelated);
  2490. // 显示相关的跨层边
  2491. if (isRelated) {{
  2492. d3.select(this).style("display", "block");
  2493. }}
  2494. }});
  2495. }} else {{
  2496. // 点击的节点不在图中,全部变灰
  2497. g.selectAll(".node").classed("dimmed", true).classed("highlighted", false);
  2498. g.selectAll(".link-group").classed("dimmed", true).classed("highlighted", false);
  2499. }}
  2500. }}
  2501. }}
  2502. // 同步人设树高亮和关系图展示(职责单一:不处理力导向图)
  2503. function syncTreeAndRelationGraph(srcNodeId, tgtNodeId, edgeType) {{
  2504. // 动态获取树相关元素
  2505. const treeGroup = d3.select(".persona-tree");
  2506. if (treeGroup.empty()) return;
  2507. const treeEdges = treeGroup.selectAll(".tree-edge");
  2508. // 重置人设树高亮状态
  2509. treeGroup.selectAll(".tree-node")
  2510. .classed("tree-dimmed", false)
  2511. .classed("tree-highlighted", false);
  2512. treeGroup.selectAll(".tree-node .tree-shape")
  2513. .attr("fill", d => getTreeNodeColor(d))
  2514. .attr("stroke", "rgba(255,255,255,0.5)")
  2515. .attr("stroke-width", 1)
  2516. .attr("stroke-opacity", 1)
  2517. .attr("opacity", 1);
  2518. treeGroup.selectAll(".tree-node text")
  2519. .attr("fill", d => (d.data.isRoot || d.data.isDimension) ? getTreeNodeColor(d) : "#bbb")
  2520. .attr("opacity", 1);
  2521. treeEdges.attr("stroke-opacity", 0.3).attr("stroke-width", 1);
  2522. // 构建节点ID到D3节点的映射
  2523. const treeNodeById = {{}};
  2524. treeGroup.selectAll(".tree-node").each(function(n) {{
  2525. if (n.data.节点ID) treeNodeById[n.data.节点ID] = n;
  2526. }});
  2527. const sourceTreeNode = treeNodeById[srcNodeId];
  2528. const targetTreeNode = treeNodeById[tgtNodeId];
  2529. // 高亮树边(不变粗)
  2530. treeEdges.attr("stroke-opacity", function(e) {{
  2531. const isThisEdge = (e.源节点ID === srcNodeId && e.目标节点ID === tgtNodeId) ||
  2532. (e.源节点ID === tgtNodeId && e.目标节点ID === srcNodeId);
  2533. return isThisEdge ? 1 : 0.1;
  2534. }});
  2535. // 高亮相关节点(使用节点ID集合判断)
  2536. const connectedNodeIds = new Set([srcNodeId, tgtNodeId]);
  2537. treeGroup.selectAll(".tree-node").each(function(n) {{
  2538. const nodeId = n.data.节点ID;
  2539. const isConnected = connectedNodeIds.has(nodeId);
  2540. d3.select(this).select(".tree-shape")
  2541. .attr("fill", isConnected ? getTreeNodeColor(n) : "#555")
  2542. .attr("opacity", 1);
  2543. d3.select(this).select("text")
  2544. .attr("fill", isConnected ?
  2545. ((n.data.isRoot || n.data.isDimension) ? getTreeNodeColor(n) : "#bbb") : "#555")
  2546. .attr("opacity", 1);
  2547. }});
  2548. // 显示边详情
  2549. const panel = document.getElementById("detailPanel");
  2550. panel.classList.add("active");
  2551. document.getElementById("detailTitle").textContent = "🔗 边详情";
  2552. // 从 personaTreeData 中获取节点数据(即使不在可视化树中)
  2553. const srcNodeData = personaTreeData.nodes.find(n => n.节点ID === srcNodeId);
  2554. const tgtNodeData = personaTreeData.nodes.find(n => n.节点ID === tgtNodeId);
  2555. // 构造显示用的节点名称
  2556. const srcName = sourceTreeNode ? (sourceTreeNode.data.节点名称 || sourceTreeNode.data.name) :
  2557. (srcNodeData?.节点名称 || srcNodeId);
  2558. const tgtName = targetTreeNode ? (targetTreeNode.data.节点名称 || targetTreeNode.data.name) :
  2559. (tgtNodeData?.节点名称 || tgtNodeId);
  2560. let html = `
  2561. <p><span class="label">边类型:</span> <strong>${{edgeType}}</strong></p>
  2562. <p><span class="label">源节点:</span> ${{srcName}}</p>
  2563. <p><span class="label">目标节点:</span> ${{tgtName}}</p>
  2564. `;
  2565. document.getElementById("detailContent").innerHTML = html;
  2566. // 在关系图中展示这条边和两个节点
  2567. // 构造节点对象(优先使用树节点,否则使用 personaTreeData 中的数据)
  2568. const srcForEgo = sourceTreeNode || (srcNodeData ? {{ data: srcNodeData }} : null);
  2569. const tgtForEgo = targetTreeNode || (tgtNodeData ? {{ data: tgtNodeData }} : null);
  2570. const edgeData = {{
  2571. 边类型: edgeType,
  2572. 源节点ID: srcNodeId,
  2573. 目标节点ID: tgtNodeId
  2574. }};
  2575. renderEgoGraphEdge(edgeData, srcForEgo, tgtForEgo);
  2576. }}
  2577. // 关系子图(Ego Graph)- 在画布第四层显示
  2578. let currentEgoSimulation = null; // 保存当前的力模拟,用于停止
  2579. let currentEgoCenterNodeId = null; // 当前关系图中心节点ID
  2580. let currentEgoCenterNodeName = null; // 当前关系图中心节点名称
  2581. // 当前选中的层级数
  2582. let currentLevelCount = 1;
  2583. // 切换级联菜单
  2584. function toggleCascadeMenu() {{
  2585. event.stopPropagation();
  2586. const menu = document.getElementById('cascade-menu');
  2587. menu.classList.toggle('show');
  2588. }}
  2589. // 反选指定层级的边类型
  2590. function invertSelection(level) {{
  2591. event.stopPropagation();
  2592. document.querySelectorAll(`.cascade-edge-item input[data-level="${{level}}"]`).forEach(cb => {{
  2593. cb.checked = !cb.checked;
  2594. }});
  2595. // 更新全选复选框状态
  2596. const allItems = document.querySelectorAll(`.cascade-edge-item input[data-level="${{level}}"]`);
  2597. const checkedItems = document.querySelectorAll(`.cascade-edge-item input[data-level="${{level}}"]:checked`);
  2598. const selectAllCb = document.querySelector(`.select-all input[data-level="${{level}}"]`);
  2599. selectAllCb.checked = allItems.length === checkedItems.length;
  2600. // 重新渲染
  2601. if (currentEgoCenterNodeId) {{
  2602. handleNodeClick(currentEgoCenterNodeId, currentEgoCenterNodeName);
  2603. }}
  2604. }}
  2605. // 重置所有层级到默认配置(1级全选,2/3级只选包含)
  2606. function resetSelection() {{
  2607. event.stopPropagation();
  2608. // Level 1: 全选
  2609. document.querySelectorAll('.cascade-edge-item input[data-level="1"]').forEach(cb => {{
  2610. cb.checked = true;
  2611. }});
  2612. document.querySelector('.select-all input[data-level="1"]').checked = true;
  2613. // Level 2 & 3: 只选包含
  2614. [2, 3].forEach(level => {{
  2615. document.querySelectorAll(`.cascade-edge-item input[data-level="${{level}}"]`).forEach(cb => {{
  2616. cb.checked = (cb.dataset.type === "包含");
  2617. }});
  2618. document.querySelector(`.select-all input[data-level="${{level}}"]`).checked = false;
  2619. }});
  2620. // 重新渲染
  2621. if (currentEgoCenterNodeId) {{
  2622. handleNodeClick(currentEgoCenterNodeId, currentEgoCenterNodeName);
  2623. }}
  2624. }}
  2625. // 选择层级
  2626. function selectLevel(level) {{
  2627. event.stopPropagation();
  2628. currentLevelCount = level;
  2629. // 更新层级选中状态
  2630. document.querySelectorAll('.cascade-level-item').forEach(item => {{
  2631. const itemLevel = parseInt(item.dataset.level);
  2632. item.classList.toggle('active', itemLevel === level);
  2633. }});
  2634. // 显示对应的边类型组(1级显示L1,2级显示L1+L2,3级显示L1+L2+L3)
  2635. document.querySelectorAll('.cascade-edge-group').forEach(group => {{
  2636. const groupLevel = parseInt(group.dataset.level);
  2637. group.classList.toggle('active', groupLevel <= level);
  2638. }});
  2639. // 更新按钮显示
  2640. document.getElementById('cascade-label').textContent = level + '级';
  2641. // 重新渲染关系图和人设树高亮
  2642. if (currentEgoCenterNodeId) {{
  2643. handleNodeClick(currentEgoCenterNodeId, currentEgoCenterNodeName);
  2644. }}
  2645. }}
  2646. // 获取指定层级选中的边类型
  2647. function getLevelEdgeTypes(level) {{
  2648. const types = [];
  2649. document.querySelectorAll(`.cascade-edge-item input[data-level="${{level}}"]:checked`).forEach(cb => {{
  2650. types.push(cb.dataset.type);
  2651. }});
  2652. return types;
  2653. }}
  2654. // 获取层级配置(返回每层的边类型数组)
  2655. function getLevelConfigs() {{
  2656. const configs = [];
  2657. for (let i = 1; i <= currentLevelCount; i++) {{
  2658. const types = getLevelEdgeTypes(i);
  2659. configs.push(types);
  2660. }}
  2661. return configs;
  2662. }}
  2663. // 多层级展开:收集指定层级内的所有节点和边(每层可指定不同边类型)
  2664. function collectNodesAndEdges(centerNodeId, levelConfigs) {{
  2665. const nodeIds = new Set([centerNodeId]);
  2666. const collectedEdges = [];
  2667. const visitedEdges = new Set();
  2668. let currentLayer = new Set([centerNodeId]);
  2669. for (let d = 0; d < levelConfigs.length; d++) {{
  2670. const edgeTypes = levelConfigs[d];
  2671. if (edgeTypes.length === 0) break;
  2672. const nextLayer = new Set();
  2673. personaTreeData.edges.forEach(e => {{
  2674. // 筛选边类型
  2675. if (!edgeTypes.includes(e.边类型)) return;
  2676. const edgeKey = `${{e.源节点ID}}-${{e.目标节点ID}}-${{e.边类型}}`;
  2677. if (visitedEdges.has(edgeKey)) return;
  2678. // 单向查找:只从源节点出发,沿边的方向查找
  2679. // 属于:子→父(从子出发找父)
  2680. // 包含:父→子(从父出发找子)
  2681. // 共现:A→B(从A出发找B)
  2682. if (currentLayer.has(e.源节点ID)) {{
  2683. visitedEdges.add(edgeKey);
  2684. collectedEdges.push({{...e, _level: d + 1}});
  2685. // 添加目标节点到下一层
  2686. if (!nodeIds.has(e.目标节点ID)) {{
  2687. nextLayer.add(e.目标节点ID);
  2688. nodeIds.add(e.目标节点ID);
  2689. }}
  2690. }}
  2691. }});
  2692. currentLayer = nextLayer;
  2693. if (nextLayer.size === 0) break;
  2694. }}
  2695. return {{ nodeIds, edges: collectedEdges, depth: levelConfigs.length }};
  2696. }}
  2697. function renderEgoGraph(centerNodeId, centerNodeName) {{
  2698. // 保存当前中心节点
  2699. currentEgoCenterNodeId = centerNodeId;
  2700. currentEgoCenterNodeName = centerNodeName;
  2701. // 显示关系图容器
  2702. document.getElementById("ego-container").style.display = "block";
  2703. // 获取关系图层组
  2704. const egoGroup = d3.select(".ego-graph-content");
  2705. if (egoGroup.empty()) return;
  2706. // 停止之前的模拟
  2707. if (currentEgoSimulation) {{
  2708. currentEgoSimulation.stop();
  2709. currentEgoSimulation = null;
  2710. }}
  2711. // 清除旧内容
  2712. egoGroup.selectAll("*").remove();
  2713. // 获取当前层级配置
  2714. const levelConfigs = getLevelConfigs();
  2715. // 更新顶部标题和统计
  2716. document.getElementById("ego-node-name").textContent = centerNodeName;
  2717. // 获取层半径
  2718. const radius = 160; // 固定半径
  2719. // 根据层级配置收集节点和边
  2720. const {{ nodeIds, edges: relatedEdges, depth }} = collectNodesAndEdges(centerNodeId, levelConfigs);
  2721. // 构建节点数据(确保中心节点始终包含)
  2722. const nodeMap = {{}};
  2723. personaTreeData.nodes.forEach(n => {{
  2724. if (nodeIds.has(n.节点ID) || n.节点ID === centerNodeId) {{
  2725. nodeMap[n.节点ID] = {{
  2726. id: n.节点ID,
  2727. name: n.节点名称,
  2728. type: n.节点类型,
  2729. level: n.节点层级,
  2730. isCenter: n.节点ID === centerNodeId
  2731. }};
  2732. }}
  2733. }});
  2734. const nodes = Object.values(nodeMap);
  2735. // 处理同一对节点间的多条边,分配不同弧度
  2736. const linksByPair = {{}};
  2737. relatedEdges.forEach(e => {{
  2738. // 用排序后的节点对作为key,确保A-B和B-A是同一对
  2739. const pairKey = [e.源节点ID, e.目标节点ID].sort().join("||");
  2740. if (!linksByPair[pairKey]) linksByPair[pairKey] = [];
  2741. linksByPair[pairKey].push(e);
  2742. }});
  2743. // 为每条边分配弧度索引
  2744. const links = [];
  2745. Object.values(linksByPair).forEach(pairEdges => {{
  2746. const count = pairEdges.length;
  2747. pairEdges.forEach((e, i) => {{
  2748. // 弧度:0表示直线,正负值表示向两侧弯曲
  2749. let curvature = 0;
  2750. if (count > 1) {{
  2751. // 多条边时,均匀分布弧度
  2752. curvature = (i - (count - 1) / 2) * 0.3;
  2753. }}
  2754. links.push({{
  2755. source: e.源节点ID,
  2756. target: e.目标节点ID,
  2757. type: e.边类型,
  2758. curvature: curvature
  2759. }});
  2760. }});
  2761. }});
  2762. // 根据节点数量动态计算实际使用的半径
  2763. const nodeCount = nodes.length;
  2764. const nodeSpacingEgo = 65; // 节点间距(增大)
  2765. const minEgoRadius = 120;
  2766. const maxEgoRadius = Math.max(radius, 250); // 允许更大的半径
  2767. let actualRadius;
  2768. if (nodeCount <= 1) {{
  2769. actualRadius = minEgoRadius;
  2770. }} else {{
  2771. const circumference = nodeCount * nodeSpacingEgo;
  2772. const calcR = circumference / (2 * Math.PI);
  2773. actualRadius = Math.max(minEgoRadius, Math.min(maxEgoRadius, calcR));
  2774. }}
  2775. // 更新顶部统计信息
  2776. document.getElementById("ego-stats").textContent = `${{nodeCount}}节点 ${{relatedEdges.length}}边`;
  2777. // 如果只有中心节点,只渲染中心节点
  2778. if (nodes.length === 1) {{
  2779. const centerNode = nodes[0];
  2780. // 获取中心节点的维度颜色
  2781. const dimColors = {{
  2782. "灵感点": "#f39c12",
  2783. "目的点": "#3498db",
  2784. "关键点": "#9b59b6"
  2785. }};
  2786. const level = centerNode.level || "";
  2787. let fillColor = "#888";
  2788. if (level.includes("灵感点")) fillColor = dimColors["灵感点"];
  2789. else if (level.includes("目的点")) fillColor = dimColors["目的点"];
  2790. else if (level.includes("关键点")) fillColor = dimColors["关键点"];
  2791. // 绘制中心节点
  2792. const nodeGroup = egoGroup.append("g")
  2793. .attr("class", "ego-node-group")
  2794. .attr("transform", "translate(0, 0)");
  2795. nodeGroup.append("circle")
  2796. .attr("r", 22)
  2797. .attr("fill", fillColor)
  2798. .attr("stroke", "#fff")
  2799. .attr("stroke-width", 3)
  2800. .attr("cursor", "pointer")
  2801. .style("filter", "drop-shadow(0 2px 4px rgba(0,0,0,0.3))");
  2802. nodeGroup.append("text")
  2803. .attr("dy", "0.35em")
  2804. .attr("text-anchor", "middle")
  2805. .attr("fill", "#fff")
  2806. .attr("font-size", "10px")
  2807. .attr("font-weight", "bold")
  2808. .attr("pointer-events", "none")
  2809. .text(centerNode.name.length > 4 ? centerNode.name.slice(0, 4) + "..." : centerNode.name);
  2810. // 显示提示文字
  2811. egoGroup.append("text")
  2812. .attr("y", 50)
  2813. .attr("text-anchor", "middle")
  2814. .attr("fill", "rgba(255,255,255,0.4)")
  2815. .attr("font-size", "10px")
  2816. .text("无相关边");
  2817. return;
  2818. }}
  2819. // 边类型颜色(统一用实线)
  2820. const edgeColors = {{
  2821. "属于": "#9b59b6", // 紫色 - 层级关系
  2822. "包含": "#ffb6c1", // 淡粉 - 分类包含标签(向下)
  2823. "分类共现(跨点)": "#2ecc71", // 绿色 - 跨帖子分类共现
  2824. "分类共现(点内)": "#3498db", // 蓝色 - 同帖子分类共现
  2825. "标签共现": "#f39c12" // 橙色 - 标签共现
  2826. }};
  2827. // 维度颜色(与人设树完全一致)
  2828. const dimColors = {{
  2829. "灵感点": "#f39c12",
  2830. "目的点": "#3498db",
  2831. "关键点": "#9b59b6"
  2832. }};
  2833. // 获取节点的维度颜色(与人设树一致)
  2834. function getNodeDimColor(d) {{
  2835. // 根据节点层级判断维度
  2836. const level = d.level || "";
  2837. if (level.includes("灵感点")) return dimColors["灵感点"];
  2838. if (level.includes("目的点")) return dimColors["目的点"];
  2839. if (level.includes("关键点")) return dimColors["关键点"];
  2840. return "#888";
  2841. }}
  2842. // 获取节点填充色(实心,用维度颜色,不因选中而改变)
  2843. function getNodeFill(d) {{
  2844. return getNodeDimColor(d); // 始终用维度颜色填充
  2845. }}
  2846. // 获取节点边框色(选中节点用白色边框区分)
  2847. function getNodeStroke(d) {{
  2848. if (d.isCenter) return "#fff"; // 选中节点白色边框
  2849. return "rgba(255,255,255,0.5)"; // 普通节点半透明白边框
  2850. }}
  2851. // 获取节点边框粗细(选中节点更粗)
  2852. function getNodeStrokeWidth(d) {{
  2853. return d.isCenter ? 3 : 1.5;
  2854. }}
  2855. // 根据节点数量调整力模拟参数
  2856. const linkDistance = Math.max(50, Math.min(80, actualRadius / 2.5));
  2857. const chargeStrength = Math.max(-300, Math.min(-100, -nodeCount * 10));
  2858. const collisionRadius = 35; // 碰撞半径,防止重叠
  2859. // 创建力导向模拟(中心在0,0因为已经平移了)
  2860. const simulation = d3.forceSimulation(nodes)
  2861. .force("link", d3.forceLink(links).id(d => d.id).distance(linkDistance))
  2862. .force("charge", d3.forceManyBody().strength(chargeStrength))
  2863. .force("center", d3.forceCenter(0, 0))
  2864. .force("collision", d3.forceCollide().radius(collisionRadius))
  2865. .force("boundary", function() {{
  2866. // 限制节点在圆形区域内
  2867. const maxR = actualRadius - 30;
  2868. return function(alpha) {{
  2869. nodes.forEach(d => {{
  2870. const dist = Math.sqrt(d.x * d.x + d.y * d.y);
  2871. if (dist > maxR) {{
  2872. const scale = maxR / dist;
  2873. d.x *= scale;
  2874. d.y *= scale;
  2875. }}
  2876. }});
  2877. }};
  2878. }}());
  2879. currentEgoSimulation = simulation;
  2880. // 绘制边(用曲线支持多边)
  2881. const link = egoGroup.selectAll(".ego-edge")
  2882. .data(links)
  2883. .join("path")
  2884. .attr("class", "ego-edge")
  2885. .attr("stroke", d => edgeColors[d.type] || "#666")
  2886. .attr("stroke-width", 1.5)
  2887. .attr("stroke-opacity", 0.7)
  2888. .attr("fill", "none");
  2889. // 绘制节点(分类用方形,标签用圆形)
  2890. const node = egoGroup.selectAll(".ego-node")
  2891. .data(nodes)
  2892. .join("g")
  2893. .attr("class", d => "ego-node" + (d.isCenter ? " center" : ""));
  2894. // 根据节点类型绘制不同形状(与人设树样式一致)
  2895. const nodeSize = 8;
  2896. node.each(function(d) {{
  2897. const el = d3.select(this);
  2898. const fill = getNodeFill(d);
  2899. const stroke = getNodeStroke(d);
  2900. const size = d.isCenter ? nodeSize + 2 : nodeSize;
  2901. const strokeWidth = getNodeStrokeWidth(d);
  2902. if (d.type === "分类") {{
  2903. // 方形(分类节点)- 与人设树一致
  2904. el.append("rect")
  2905. .attr("class", "ego-shape")
  2906. .attr("width", size * 2)
  2907. .attr("height", size * 2)
  2908. .attr("x", -size)
  2909. .attr("y", -size)
  2910. .attr("fill", fill)
  2911. .attr("stroke", stroke)
  2912. .attr("stroke-width", strokeWidth)
  2913. .attr("rx", 1);
  2914. }} else {{
  2915. // 圆形(标签节点)- 与人设树一致
  2916. el.append("circle")
  2917. .attr("class", "ego-shape")
  2918. .attr("r", size)
  2919. .attr("fill", fill)
  2920. .attr("stroke", stroke)
  2921. .attr("stroke-width", strokeWidth);
  2922. }}
  2923. }});
  2924. node.append("text")
  2925. .attr("dy", -12)
  2926. .attr("text-anchor", "middle")
  2927. .attr("font-size", "9px")
  2928. .attr("fill", "#fff")
  2929. .text(d => d.name.length > 6 ? d.name.substring(0, 6) + ".." : d.name);
  2930. // 添加点击事件(直接调用共享函数)
  2931. node.on("click", function(event, d) {{
  2932. event.stopPropagation();
  2933. handleNodeClick(d.id, d.name);
  2934. }})
  2935. .on("mouseenter", function(event, d) {{
  2936. // 悬停高亮:高亮到激活节点的路径
  2937. if (!currentEgoCenterNodeId || d.id === currentEgoCenterNodeId) return;
  2938. highlightPathInEgoGraph(d.id);
  2939. }})
  2940. .on("mouseleave", function(event, d) {{
  2941. // 移出时恢复
  2942. if (!currentEgoCenterNodeId) return;
  2943. resetEgoGraphHighlight();
  2944. }});
  2945. // 边点击事件(直接调用共享函数)
  2946. link.on("click", function(event, d) {{
  2947. event.stopPropagation();
  2948. handleEdgeClick(d.source.id, d.target.id, d.type);
  2949. }});
  2950. // 生成曲线路径的函数
  2951. function linkPath(d) {{
  2952. const sx = d.source.x, sy = d.source.y;
  2953. const tx = d.target.x, ty = d.target.y;
  2954. if (d.curvature === 0) {{
  2955. // 直线
  2956. return `M${{sx}},${{sy}}L${{tx}},${{ty}}`;
  2957. }} else {{
  2958. // 曲线:计算控制点
  2959. const dx = tx - sx, dy = ty - sy;
  2960. const dist = Math.sqrt(dx * dx + dy * dy);
  2961. // 控制点垂直于连线方向偏移
  2962. const mx = (sx + tx) / 2;
  2963. const my = (sy + ty) / 2;
  2964. const offset = d.curvature * dist * 0.5;
  2965. // 垂直方向单位向量
  2966. const nx = -dy / dist, ny = dx / dist;
  2967. const cx = mx + nx * offset;
  2968. const cy = my + ny * offset;
  2969. return `M${{sx}},${{sy}}Q${{cx}},${{cy}} ${{tx}},${{ty}}`;
  2970. }}
  2971. }}
  2972. // 更新位置
  2973. simulation.on("tick", () => {{
  2974. link.attr("d", linkPath);
  2975. node.attr("transform", d => `translate(${{d.x}},${{d.y}})`);
  2976. }});
  2977. }}
  2978. function clearEgoGraph() {{
  2979. const egoGroup = d3.select(".ego-graph-content");
  2980. if (!egoGroup.empty()) {{
  2981. egoGroup.selectAll("*").remove();
  2982. }}
  2983. // 隐藏关系图容器
  2984. document.getElementById("ego-container").style.display = "none";
  2985. // 停止模拟
  2986. if (currentEgoSimulation) {{
  2987. currentEgoSimulation.stop();
  2988. currentEgoSimulation = null;
  2989. }}
  2990. }}
  2991. // 在关系图中高亮从悬停节点到激活节点的路径
  2992. function highlightPathInEgoGraph(hoveredNodeId) {{
  2993. const egoGroup = d3.select(".ego-graph-content");
  2994. if (egoGroup.empty()) return;
  2995. // 获取关系图中的边数据
  2996. const egoEdges = egoGroup.selectAll(".ego-edge");
  2997. const egoNodes = egoGroup.selectAll(".ego-node");
  2998. if (egoEdges.empty()) return;
  2999. // 构建邻接表用于路径查找
  3000. const adjacency = {{}};
  3001. const edgeMap = {{}};
  3002. egoEdges.each(function(d) {{
  3003. const srcId = d.source.id || d.source;
  3004. const tgtId = d.target.id || d.target;
  3005. if (!adjacency[srcId]) adjacency[srcId] = [];
  3006. if (!adjacency[tgtId]) adjacency[tgtId] = [];
  3007. adjacency[srcId].push(tgtId);
  3008. adjacency[tgtId].push(srcId);
  3009. // 记录边(双向)
  3010. const key1 = `${{srcId}}|${{tgtId}}`;
  3011. const key2 = `${{tgtId}}|${{srcId}}`;
  3012. edgeMap[key1] = d;
  3013. edgeMap[key2] = d;
  3014. }});
  3015. // BFS找路径
  3016. const visited = new Set();
  3017. const parent = {{}};
  3018. const queue = [currentEgoCenterNodeId];
  3019. visited.add(currentEgoCenterNodeId);
  3020. let found = false;
  3021. while (queue.length > 0 && !found) {{
  3022. const curr = queue.shift();
  3023. const neighbors = adjacency[curr] || [];
  3024. for (const next of neighbors) {{
  3025. if (!visited.has(next)) {{
  3026. visited.add(next);
  3027. parent[next] = curr;
  3028. queue.push(next);
  3029. if (next === hoveredNodeId) {{
  3030. found = true;
  3031. break;
  3032. }}
  3033. }}
  3034. }}
  3035. }}
  3036. if (!found) return;
  3037. // 回溯路径
  3038. const pathNodes = new Set();
  3039. const pathEdgeKeys = new Set();
  3040. let curr = hoveredNodeId;
  3041. while (curr !== undefined) {{
  3042. pathNodes.add(curr);
  3043. const prev = parent[curr];
  3044. if (prev !== undefined) {{
  3045. pathEdgeKeys.add(`${{prev}}|${{curr}}`);
  3046. pathEdgeKeys.add(`${{curr}}|${{prev}}`);
  3047. }}
  3048. curr = prev;
  3049. }}
  3050. // 隐藏不在路径上的边(保持布局不变)
  3051. egoEdges
  3052. .style("visibility", function(d) {{
  3053. const srcId = d.source.id || d.source;
  3054. const tgtId = d.target.id || d.target;
  3055. const key = `${{srcId}}|${{tgtId}}`;
  3056. return pathEdgeKeys.has(key) ? "visible" : "hidden";
  3057. }});
  3058. // 隐藏不在路径上的节点(保持布局不变)
  3059. egoNodes
  3060. .style("visibility", function(d) {{
  3061. return pathNodes.has(d.id) ? "visible" : "hidden";
  3062. }});
  3063. }}
  3064. // 恢复关系图的高亮状态
  3065. function resetEgoGraphHighlight() {{
  3066. const egoGroup = d3.select(".ego-graph-content");
  3067. if (egoGroup.empty()) return;
  3068. // 恢复边的可见性
  3069. egoGroup.selectAll(".ego-edge")
  3070. .style("visibility", "visible");
  3071. // 恢复节点的可见性
  3072. egoGroup.selectAll(".ego-node")
  3073. .style("visibility", "visible");
  3074. }}
  3075. // 渲染单条边和两个节点(点击树边时调用)
  3076. function renderEgoGraphEdge(edgeData, sourceNode, targetNode) {{
  3077. // 显示关系图容器
  3078. document.getElementById("ego-container").style.display = "block";
  3079. const egoGroup = d3.select(".ego-graph-content");
  3080. if (egoGroup.empty()) return;
  3081. // 停止之前的模拟
  3082. if (currentEgoSimulation) {{
  3083. currentEgoSimulation.stop();
  3084. currentEgoSimulation = null;
  3085. }}
  3086. // 清除旧内容
  3087. egoGroup.selectAll("*").remove();
  3088. // 更新顶部标题
  3089. document.getElementById("ego-node-name").textContent = edgeData.边类型;
  3090. document.getElementById("ego-stats").textContent = "2节点 1边";
  3091. const radius = 160;
  3092. // 边类型颜色
  3093. const edgeColors = {{
  3094. "属于": "#9b59b6",
  3095. "包含": "#ffb6c1",
  3096. "分类共现(跨点)": "#2ecc71",
  3097. "分类共现(点内)": "#3498db",
  3098. "标签共现": "#f39c12"
  3099. }};
  3100. // 维度颜色
  3101. const dimColors = {{
  3102. "灵感点": "#f39c12",
  3103. "目的点": "#3498db",
  3104. "关键点": "#9b59b6"
  3105. }};
  3106. // 获取节点颜色
  3107. function getNodeColor(nodeData) {{
  3108. const level = nodeData.节点层级 || "";
  3109. if (level.includes("灵感点")) return dimColors["灵感点"];
  3110. if (level.includes("目的点")) return dimColors["目的点"];
  3111. if (level.includes("关键点")) return dimColors["关键点"];
  3112. return "#888";
  3113. }}
  3114. // 两个节点的位置
  3115. const srcX = -60, srcY = 0;
  3116. const tgtX = 60, tgtY = 0;
  3117. // 绘制边
  3118. egoGroup.append("line")
  3119. .attr("class", "ego-edge")
  3120. .attr("x1", srcX)
  3121. .attr("y1", srcY)
  3122. .attr("x2", tgtX)
  3123. .attr("y2", tgtY)
  3124. .attr("stroke", edgeColors[edgeData.边类型] || "#666")
  3125. .attr("stroke-width", 3)
  3126. .attr("stroke-opacity", 0.8);
  3127. // 获取节点数据
  3128. const srcData = sourceNode ? sourceNode.data : {{}};
  3129. const tgtData = targetNode ? targetNode.data : {{}};
  3130. // 绘制源节点
  3131. const srcGroup = egoGroup.append("g")
  3132. .attr("class", "ego-node")
  3133. .attr("transform", `translate(${{srcX}}, ${{srcY}})`);
  3134. const srcSize = 15;
  3135. const srcColor = getNodeColor(srcData);
  3136. if (srcData.节点类型 === "分类") {{
  3137. srcGroup.append("rect")
  3138. .attr("width", srcSize * 2)
  3139. .attr("height", srcSize * 2)
  3140. .attr("x", -srcSize)
  3141. .attr("y", -srcSize)
  3142. .attr("fill", srcColor)
  3143. .attr("stroke", "rgba(255,255,255,0.5)")
  3144. .attr("stroke-width", 2)
  3145. .attr("rx", 2);
  3146. }} else {{
  3147. srcGroup.append("circle")
  3148. .attr("r", srcSize)
  3149. .attr("fill", srcColor)
  3150. .attr("stroke", "rgba(255,255,255,0.5)")
  3151. .attr("stroke-width", 2);
  3152. }}
  3153. srcGroup.append("text")
  3154. .attr("dy", -srcSize - 8)
  3155. .attr("text-anchor", "middle")
  3156. .attr("fill", "#fff")
  3157. .attr("font-size", "11px")
  3158. .text(srcData.节点名称 || srcData.name || "源节点");
  3159. // 绘制目标节点
  3160. const tgtGroup = egoGroup.append("g")
  3161. .attr("class", "ego-node")
  3162. .attr("transform", `translate(${{tgtX}}, ${{tgtY}})`);
  3163. const tgtSize = 15;
  3164. const tgtColor = getNodeColor(tgtData);
  3165. if (tgtData.节点类型 === "分类") {{
  3166. tgtGroup.append("rect")
  3167. .attr("width", tgtSize * 2)
  3168. .attr("height", tgtSize * 2)
  3169. .attr("x", -tgtSize)
  3170. .attr("y", -tgtSize)
  3171. .attr("fill", tgtColor)
  3172. .attr("stroke", "rgba(255,255,255,0.5)")
  3173. .attr("stroke-width", 2)
  3174. .attr("rx", 2);
  3175. }} else {{
  3176. tgtGroup.append("circle")
  3177. .attr("r", tgtSize)
  3178. .attr("fill", tgtColor)
  3179. .attr("stroke", "rgba(255,255,255,0.5)")
  3180. .attr("stroke-width", 2);
  3181. }}
  3182. tgtGroup.append("text")
  3183. .attr("dy", -tgtSize - 8)
  3184. .attr("text-anchor", "middle")
  3185. .attr("fill", "#fff")
  3186. .attr("font-size", "11px")
  3187. .text(tgtData.节点名称 || tgtData.name || "目标节点");
  3188. // 边标签
  3189. egoGroup.append("text")
  3190. .attr("y", 25)
  3191. .attr("text-anchor", "middle")
  3192. .attr("fill", "rgba(255,255,255,0.6)")
  3193. .attr("font-size", "10px")
  3194. .text(edgeData.边类型);
  3195. }}
  3196. // 页面加载完成后初始化
  3197. window.addEventListener("load", init);
  3198. window.addEventListener("resize", () => {{
  3199. if (currentIndex >= 0) {{
  3200. renderGraph(allGraphData[currentIndex]);
  3201. }}
  3202. }});
  3203. </script>
  3204. </body>
  3205. </html>
  3206. '''
  3207. def generate_combined_html(all_graph_data: List[Dict], persona_tree_data: Dict, output_file: Path):
  3208. """
  3209. 生成包含所有帖子图谱的HTML文件
  3210. Args:
  3211. all_graph_data: 所有帖子的图谱数据列表
  3212. persona_tree_data: 完整的人设树数据(节点和边)
  3213. output_file: 输出文件路径
  3214. """
  3215. # 生成Tab HTML
  3216. tabs_html = ""
  3217. for i, data in enumerate(all_graph_data):
  3218. post_title = data.get("postTitle", "")
  3219. # 使用帖子标题,如果太长则截断
  3220. if post_title:
  3221. tab_name = post_title[:15] + "..." if len(post_title) > 15 else post_title
  3222. else:
  3223. tab_name = f"帖子 {i+1}"
  3224. active_class = "active" if i == 0 else ""
  3225. tabs_html += f'<div class="tab {active_class}" data-index="{i}">{tab_name}</div>\n'
  3226. # 生成HTML
  3227. html_content = HTML_TEMPLATE.format(
  3228. tabs_html=tabs_html,
  3229. all_graph_data=json.dumps(all_graph_data, ensure_ascii=False),
  3230. persona_tree_data=json.dumps(persona_tree_data, ensure_ascii=False)
  3231. )
  3232. with open(output_file, "w", encoding="utf-8") as f:
  3233. f.write(html_content)
  3234. def main():
  3235. # 使用路径配置
  3236. config = PathConfig()
  3237. print(f"账号: {config.account_name}")
  3238. print(f"输出版本: {config.output_version}")
  3239. print()
  3240. # 输入目录
  3241. match_graph_dir = config.intermediate_dir / "match_graph"
  3242. # 输出文件
  3243. output_file = config.intermediate_dir / "match_graph.html"
  3244. print(f"输入目录: {match_graph_dir}")
  3245. print(f"输出文件: {output_file}")
  3246. print()
  3247. # 读取人设树中间数据
  3248. persona_tree_file = config.intermediate_dir / "persona_tree.json"
  3249. persona_tree_data = {"nodes": [], "edges": []}
  3250. if persona_tree_file.exists():
  3251. print(f"读取人设树数据: {persona_tree_file.name}")
  3252. with open(persona_tree_file, "r", encoding="utf-8") as f:
  3253. tree_data = json.load(f)
  3254. persona_tree_data["nodes"] = tree_data.get("nodes", [])
  3255. persona_tree_data["edges"] = tree_data.get("edges", [])
  3256. category_count = len([n for n in persona_tree_data["nodes"] if n.get("节点类型") == "分类"])
  3257. tag_count = len([n for n in persona_tree_data["nodes"] if n.get("节点类型") == "标签"])
  3258. print(f" 分类节点: {category_count}, 标签节点: {tag_count}")
  3259. print(f" 边数: {len(persona_tree_data['edges'])}")
  3260. print()
  3261. # 读取所有匹配图谱文件
  3262. graph_files = sorted(match_graph_dir.glob("*_match_graph.json"))
  3263. print(f"找到 {len(graph_files)} 个匹配图谱文件")
  3264. all_graph_data = []
  3265. for i, graph_file in enumerate(graph_files, 1):
  3266. print(f" [{i}/{len(graph_files)}] 读取: {graph_file.name}")
  3267. with open(graph_file, "r", encoding="utf-8") as f:
  3268. match_graph_data = json.load(f)
  3269. # 提取需要的数据
  3270. graph_data = {
  3271. "postId": match_graph_data["说明"]["帖子ID"],
  3272. "postTitle": match_graph_data["说明"].get("帖子标题", ""),
  3273. "stats": match_graph_data["说明"]["统计"],
  3274. "nodes": match_graph_data["节点列表"],
  3275. "edges": match_graph_data["边列表"],
  3276. "personaEdgeToMirrorEdges": match_graph_data.get("人设边到镜像边映射", {})
  3277. }
  3278. all_graph_data.append(graph_data)
  3279. # 生成HTML
  3280. print("\n生成HTML文件...")
  3281. generate_combined_html(all_graph_data, persona_tree_data, output_file)
  3282. print("\n" + "="*60)
  3283. print("处理完成!")
  3284. print(f"输出文件: {output_file}")
  3285. if __name__ == "__main__":
  3286. main()