visualize_match_graph.py 148 KB

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