visualize_match_graph.py 202 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869
  1. #!/usr/bin/env python3
  2. # -*- coding: utf-8 -*-
  3. """
  4. 将匹配图谱数据可视化为交互式HTML文件
  5. 输入:match_graph目录下的JSON文件
  6. 输出:单个HTML文件,包含所有帖子的图谱,可通过Tab切换
  7. """
  8. import json
  9. from pathlib import Path
  10. from typing import Dict, List
  11. import sys
  12. # 添加项目根目录到路径
  13. project_root = Path(__file__).parent.parent.parent
  14. sys.path.insert(0, str(project_root))
  15. from script.data_processing.path_config import PathConfig
  16. HTML_TEMPLATE = '''<!DOCTYPE html>
  17. <html lang="zh-CN">
  18. <head>
  19. <meta charset="UTF-8">
  20. <meta name="viewport" content="width=device-width, initial-scale=1.0">
  21. <title>匹配图谱可视化</title>
  22. <script src="https://d3js.org/d3.v7.min.js"></script>
  23. <style>
  24. * {{
  25. margin: 0;
  26. padding: 0;
  27. box-sizing: border-box;
  28. }}
  29. body {{
  30. font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif;
  31. background: #1a1a2e;
  32. color: #eee;
  33. overflow: hidden;
  34. }}
  35. /* 自定义滚动条 */
  36. ::-webkit-scrollbar {{
  37. width: 6px;
  38. height: 6px;
  39. }}
  40. ::-webkit-scrollbar-track {{
  41. background: transparent;
  42. }}
  43. ::-webkit-scrollbar-thumb {{
  44. background: rgba(255,255,255,0.2);
  45. border-radius: 3px;
  46. }}
  47. ::-webkit-scrollbar-thumb:hover {{
  48. background: rgba(255,255,255,0.3);
  49. }}
  50. #container {{
  51. display: flex;
  52. height: 100vh;
  53. flex-direction: column;
  54. }}
  55. /* Tab样式 */
  56. .tabs {{
  57. display: flex;
  58. background: #0f3460;
  59. padding: 0 20px;
  60. overflow-x: auto;
  61. flex-shrink: 0;
  62. }}
  63. .tab {{
  64. padding: 12px 20px;
  65. cursor: pointer;
  66. border-bottom: 3px solid transparent;
  67. white-space: nowrap;
  68. font-size: 13px;
  69. color: #888;
  70. transition: all 0.2s;
  71. }}
  72. .tab:hover {{
  73. color: #fff;
  74. background: rgba(255,255,255,0.05);
  75. }}
  76. .tab.active {{
  77. color: #e94560;
  78. border-bottom-color: #e94560;
  79. background: rgba(233, 69, 96, 0.1);
  80. }}
  81. /* 主内容区 */
  82. .main-content {{
  83. display: flex;
  84. flex: 1;
  85. overflow: hidden;
  86. }}
  87. #left-panel {{
  88. width: 420px;
  89. display: flex;
  90. flex-direction: column;
  91. border-right: 1px solid #0f3460;
  92. }}
  93. #tree-container {{
  94. flex: 1;
  95. overflow-y: auto;
  96. overflow-x: hidden;
  97. }}
  98. #tree-container svg {{
  99. display: block;
  100. }}
  101. #ego-container {{
  102. height: 420px;
  103. border-top: 1px solid #0f3460;
  104. display: none;
  105. position: relative;
  106. }}
  107. #ego-container svg {{
  108. display: block;
  109. }}
  110. .ego-controls {{
  111. position: absolute;
  112. top: 5px;
  113. left: 5px;
  114. right: 5px;
  115. z-index: 10;
  116. display: flex;
  117. justify-content: space-between;
  118. align-items: center;
  119. font-size: 10px;
  120. }}
  121. .ego-title-center {{
  122. color: #e94560;
  123. font-weight: bold;
  124. font-size: 12px;
  125. text-align: center;
  126. flex: 1;
  127. }}
  128. .ego-stats {{
  129. color: #8892b0;
  130. font-size: 10px;
  131. white-space: nowrap;
  132. }}
  133. .ego-controls label {{
  134. color: #8892b0;
  135. display: flex;
  136. align-items: center;
  137. gap: 3px;
  138. }}
  139. .ego-controls select {{
  140. background: #0f3460;
  141. color: #e6e6e6;
  142. border: 1px solid #1a1a2e;
  143. border-radius: 3px;
  144. padding: 3px 6px;
  145. font-size: 10px;
  146. cursor: pointer;
  147. }}
  148. .cascade-dropdown {{
  149. position: relative;
  150. }}
  151. .cascade-btn {{
  152. background: #0f3460;
  153. color: #e6e6e6;
  154. border: 1px solid #1a1a2e;
  155. border-radius: 3px;
  156. padding: 4px 10px;
  157. font-size: 10px;
  158. cursor: pointer;
  159. display: flex;
  160. align-items: center;
  161. gap: 6px;
  162. }}
  163. .cascade-btn:hover {{
  164. background: #1a4a7a;
  165. }}
  166. .cascade-btn::after {{
  167. content: "▼";
  168. font-size: 8px;
  169. opacity: 0.6;
  170. }}
  171. .cascade-menu {{
  172. position: absolute;
  173. top: 100%;
  174. left: 0;
  175. background: #0f3460;
  176. border: 1px solid #1a1a2e;
  177. border-radius: 3px;
  178. display: none;
  179. z-index: 100;
  180. box-shadow: 0 4px 12px rgba(0,0,0,0.3);
  181. flex-direction: row;
  182. }}
  183. .cascade-menu.show {{
  184. display: flex;
  185. }}
  186. .cascade-levels {{
  187. border-right: 1px solid #1a1a2e;
  188. padding: 4px 0;
  189. min-width: 50px;
  190. }}
  191. .cascade-level-item {{
  192. padding: 6px 12px;
  193. cursor: pointer;
  194. color: #e6e6e6;
  195. font-size: 10px;
  196. display: flex;
  197. align-items: center;
  198. justify-content: space-between;
  199. }}
  200. .cascade-level-item:hover {{
  201. background: rgba(233, 69, 96, 0.2);
  202. }}
  203. .cascade-level-item.active {{
  204. background: rgba(233, 69, 96, 0.3);
  205. color: #e94560;
  206. }}
  207. .cascade-level-item::after {{
  208. content: "›";
  209. margin-left: 8px;
  210. opacity: 0.5;
  211. }}
  212. .cascade-edges {{
  213. padding: 4px 0;
  214. min-width: 100px;
  215. max-height: 300px;
  216. overflow-y: auto;
  217. }}
  218. .cascade-edge-group {{
  219. display: none;
  220. }}
  221. .cascade-edge-group.active {{
  222. display: block;
  223. }}
  224. .cascade-edge-group-header {{
  225. color: #e94560;
  226. font-weight: bold;
  227. font-size: 9px;
  228. padding: 4px 10px 2px;
  229. display: flex;
  230. align-items: center;
  231. justify-content: space-between;
  232. }}
  233. .select-all {{
  234. font-weight: normal;
  235. color: #8892b0;
  236. font-size: 9px;
  237. cursor: pointer;
  238. display: flex;
  239. align-items: center;
  240. gap: 3px;
  241. }}
  242. .select-all input {{
  243. width: 10px;
  244. height: 10px;
  245. cursor: pointer;
  246. }}
  247. .header-actions {{
  248. display: flex;
  249. align-items: center;
  250. gap: 6px;
  251. }}
  252. .invert-btn, .reset-btn {{
  253. color: #8892b0;
  254. cursor: pointer;
  255. font-size: 9px;
  256. }}
  257. .invert-btn:hover {{
  258. color: #e94560;
  259. }}
  260. .reset-btn:hover {{
  261. color: #2ecc71;
  262. }}
  263. .cascade-edge-item {{
  264. display: flex;
  265. align-items: center;
  266. gap: 6px;
  267. padding: 4px 10px;
  268. cursor: pointer;
  269. color: #e6e6e6;
  270. font-size: 10px;
  271. }}
  272. .cascade-edge-item:hover {{
  273. background: rgba(233, 69, 96, 0.15);
  274. }}
  275. .cascade-edge-item input {{
  276. display: none;
  277. }}
  278. .cascade-edge-item .edge-color {{
  279. width: 12px;
  280. height: 12px;
  281. border-radius: 2px;
  282. border: 1px solid #333;
  283. opacity: 0.3;
  284. }}
  285. .cascade-edge-item input:checked + .edge-color {{
  286. opacity: 1;
  287. }}
  288. #graph {{
  289. flex: 1;
  290. position: relative;
  291. overflow: auto;
  292. }}
  293. #sidebar {{
  294. width: 300px;
  295. background: #16213e;
  296. padding: 15px;
  297. overflow-y: auto;
  298. border-left: 1px solid #0f3460;
  299. display: flex;
  300. flex-direction: column;
  301. }}
  302. .match-list-panel {{
  303. margin-bottom: 15px;
  304. border-bottom: 1px solid #0f3460;
  305. padding-bottom: 10px;
  306. }}
  307. .match-list-panel h3 {{
  308. font-size: 13px;
  309. margin-bottom: 8px;
  310. color: #e94560;
  311. }}
  312. .match-list {{
  313. max-height: 200px;
  314. overflow-y: auto;
  315. }}
  316. .match-item {{
  317. display: flex;
  318. align-items: center;
  319. padding: 6px 8px;
  320. margin-bottom: 4px;
  321. background: rgba(233, 69, 96, 0.1);
  322. border-radius: 4px;
  323. cursor: pointer;
  324. font-size: 11px;
  325. gap: 8px;
  326. }}
  327. .match-item:hover {{
  328. background: rgba(233, 69, 96, 0.2);
  329. }}
  330. .match-item.active {{
  331. background: rgba(233, 69, 96, 0.3);
  332. border: 1px solid #e94560;
  333. }}
  334. .match-item .score {{
  335. background: #e94560;
  336. color: #fff;
  337. padding: 2px 6px;
  338. border-radius: 3px;
  339. font-weight: bold;
  340. min-width: 40px;
  341. text-align: center;
  342. }}
  343. .match-item .score.high {{
  344. background: #27ae60;
  345. }}
  346. .match-item .score.medium {{
  347. background: #f39c12;
  348. }}
  349. .match-item .names {{
  350. flex: 1;
  351. overflow: hidden;
  352. text-overflow: ellipsis;
  353. white-space: nowrap;
  354. }}
  355. #persona-tree-panel {{
  356. flex: 1;
  357. overflow-y: auto;
  358. margin-top: 15px;
  359. border-top: 1px solid #0f3460;
  360. padding-top: 10px;
  361. }}
  362. .tree-dimension {{
  363. margin-bottom: 15px;
  364. }}
  365. .tree-dimension-title {{
  366. font-size: 12px;
  367. font-weight: bold;
  368. padding: 5px 8px;
  369. border-radius: 4px;
  370. margin-bottom: 5px;
  371. cursor: pointer;
  372. display: flex;
  373. align-items: center;
  374. gap: 5px;
  375. }}
  376. .tree-dimension-title:hover {{
  377. opacity: 0.8;
  378. }}
  379. .tree-dimension-title .toggle {{
  380. font-size: 10px;
  381. transition: transform 0.2s;
  382. }}
  383. .tree-dimension-title.collapsed .toggle {{
  384. transform: rotate(-90deg);
  385. }}
  386. .tree-dimension.inspiration .tree-dimension-title {{
  387. background: rgba(243, 156, 18, 0.2);
  388. color: #f39c12;
  389. }}
  390. .tree-dimension.purpose .tree-dimension-title {{
  391. background: rgba(52, 152, 219, 0.2);
  392. color: #3498db;
  393. }}
  394. .tree-dimension.key .tree-dimension-title {{
  395. background: rgba(155, 89, 182, 0.2);
  396. color: #9b59b6;
  397. }}
  398. .tree-list {{
  399. list-style: none;
  400. padding-left: 0;
  401. margin: 0;
  402. font-size: 11px;
  403. }}
  404. .tree-list.collapsed {{
  405. display: none;
  406. }}
  407. .tree-item {{
  408. padding: 3px 0;
  409. color: #aaa;
  410. cursor: pointer;
  411. border-radius: 3px;
  412. padding: 3px 6px;
  413. margin: 1px 0;
  414. }}
  415. .tree-item:hover {{
  416. background: rgba(255,255,255,0.08);
  417. color: #fff;
  418. }}
  419. .tree-item.matched {{
  420. color: #2ecc71;
  421. font-weight: 500;
  422. }}
  423. .tree-item .indent {{
  424. display: inline-block;
  425. width: 12px;
  426. color: #555;
  427. }}
  428. h1 {{
  429. font-size: 15px;
  430. margin-bottom: 10px;
  431. color: #e94560;
  432. }}
  433. h2 {{
  434. font-size: 12px;
  435. margin: 10px 0 6px;
  436. color: #0f9b8e;
  437. }}
  438. .legend {{
  439. margin-top: 10px;
  440. }}
  441. .legend-grid {{
  442. display: grid;
  443. grid-template-columns: 1fr 1fr;
  444. gap: 4px 8px;
  445. }}
  446. .legend-item {{
  447. display: flex;
  448. align-items: center;
  449. font-size: 11px;
  450. }}
  451. .legend-color {{
  452. width: 12px;
  453. height: 12px;
  454. border-radius: 50%;
  455. margin-right: 6px;
  456. flex-shrink: 0;
  457. }}
  458. .legend-line {{
  459. width: 20px;
  460. height: 3px;
  461. margin-right: 6px;
  462. flex-shrink: 0;
  463. }}
  464. .detail-panel {{
  465. margin-top: 20px;
  466. padding: 15px;
  467. background: #0f3460;
  468. border-radius: 8px;
  469. display: none;
  470. }}
  471. .detail-panel.active {{
  472. display: block;
  473. }}
  474. .detail-panel h3 {{
  475. font-size: 14px;
  476. margin-bottom: 10px;
  477. color: #e94560;
  478. }}
  479. .detail-panel p {{
  480. font-size: 12px;
  481. line-height: 1.6;
  482. color: #ccc;
  483. margin: 5px 0;
  484. }}
  485. .detail-panel .label {{
  486. color: #888;
  487. }}
  488. .detail-panel .close-btn {{
  489. position: absolute;
  490. top: 10px;
  491. right: 10px;
  492. background: none;
  493. border: none;
  494. color: #888;
  495. cursor: pointer;
  496. font-size: 16px;
  497. }}
  498. .detail-panel .close-btn:hover {{
  499. color: #e94560;
  500. }}
  501. .detail-panel-wrapper {{
  502. position: relative;
  503. }}
  504. .similarity-score {{
  505. background: #e94560;
  506. color: #fff;
  507. padding: 2px 6px;
  508. border-radius: 4px;
  509. font-weight: bold;
  510. }}
  511. .edge-description {{
  512. background: #1a1a2e;
  513. padding: 10px;
  514. border-radius: 4px;
  515. margin-top: 8px;
  516. font-size: 11px;
  517. line-height: 1.5;
  518. }}
  519. .edge-list {{
  520. background: #1a1a2e;
  521. padding: 8px;
  522. border-radius: 4px;
  523. margin-top: 4px;
  524. font-size: 11px;
  525. }}
  526. .edge-type-item {{
  527. display: flex;
  528. justify-content: space-between;
  529. padding: 2px 0;
  530. border-bottom: 1px solid rgba(255,255,255,0.05);
  531. }}
  532. .edge-type {{
  533. color: #aaa;
  534. }}
  535. .edge-count {{
  536. color: #e94560;
  537. font-weight: bold;
  538. }}
  539. .edge-detail {{
  540. padding: 3px 0;
  541. color: #888;
  542. font-size: 10px;
  543. border-left: 2px solid #333;
  544. padding-left: 8px;
  545. margin: 2px 0;
  546. }}
  547. .edge-type-tag {{
  548. background: rgba(255,255,255,0.1);
  549. padding: 1px 4px;
  550. border-radius: 2px;
  551. font-size: 9px;
  552. margin-left: 4px;
  553. }}
  554. .edge-more {{
  555. color: #666;
  556. font-size: 10px;
  557. text-align: center;
  558. padding: 4px 0;
  559. }}
  560. .edge-empty {{
  561. color: #555;
  562. font-size: 10px;
  563. padding: 4px 0;
  564. }}
  565. svg {{
  566. width: 100%;
  567. display: block; /* 避免底部多余空间 */
  568. }}
  569. .node {{
  570. cursor: pointer;
  571. }}
  572. .node circle, .node rect, .node polygon {{
  573. stroke-width: 3px;
  574. }}
  575. .node .post-point-node {{
  576. stroke: #fff;
  577. stroke-width: 4px;
  578. }}
  579. .node .post-node,
  580. .node .persona-node {{
  581. stroke: #fff;
  582. }}
  583. .node text {{
  584. font-size: 11px;
  585. fill: #fff;
  586. pointer-events: none;
  587. }}
  588. .link {{
  589. stroke-opacity: 0.7;
  590. }}
  591. .link-hitarea {{
  592. stroke: transparent;
  593. stroke-width: 15px;
  594. cursor: pointer;
  595. fill: none;
  596. }}
  597. .link-hitarea:hover + .link {{
  598. stroke-opacity: 1;
  599. stroke-width: 3px;
  600. }}
  601. .edge-label {{
  602. font-size: 10px;
  603. fill: #fff;
  604. pointer-events: none;
  605. text-anchor: middle;
  606. }}
  607. .edge-label-bg {{
  608. fill: rgba(0,0,0,0.7);
  609. }}
  610. .link.match-same {{
  611. stroke: #e94560;
  612. }}
  613. .link.match-similar {{
  614. stroke: #e94560;
  615. stroke-dasharray: 5,5;
  616. }}
  617. .link.category-cross {{
  618. stroke: #2ecc71;
  619. }}
  620. .link.category-intra {{
  621. stroke: #3498db;
  622. }}
  623. .link.tag-cooccur {{
  624. stroke: #f39c12;
  625. }}
  626. .link.belong {{
  627. stroke: #9b59b6;
  628. }}
  629. .link.contain {{
  630. stroke: #8e44ad;
  631. stroke-dasharray: 2,2;
  632. }}
  633. /* 镜像边样式(实线,颜色与原边相同) */
  634. .link.mirror-category-cross {{
  635. stroke: #2ecc71;
  636. }}
  637. .link.mirror-category-intra {{
  638. stroke: #3498db;
  639. }}
  640. .link.mirror-tag-cooccur {{
  641. stroke: #f39c12;
  642. }}
  643. .link.mirror-belong {{
  644. stroke: #9b59b6;
  645. }}
  646. .link.mirror-contain {{
  647. stroke: #8e44ad;
  648. }}
  649. /* 二阶边现在使用与镜像边相同的样式(基于原始边类型) */
  650. /* 高亮/灰化样式 */
  651. .node.dimmed circle, .node.dimmed rect, .node.dimmed polygon {{
  652. opacity: 0.15 !important;
  653. }}
  654. .node.dimmed text {{
  655. opacity: 0.15 !important;
  656. }}
  657. .link-group.dimmed .link {{
  658. stroke-opacity: 0.08 !important;
  659. }}
  660. .link-group.dimmed .edge-label-group {{
  661. opacity: 0.15 !important;
  662. }}
  663. .node.highlighted circle, .node.highlighted rect, .node.highlighted polygon {{
  664. stroke: #fff !important;
  665. stroke-width: 4px !important;
  666. filter: drop-shadow(0 0 8px rgba(255,255,255,0.5));
  667. }}
  668. .link-group.highlighted .link {{
  669. stroke-opacity: 1 !important;
  670. stroke-width: 3px !important;
  671. filter: drop-shadow(0 0 4px rgba(255,255,255,0.3));
  672. }}
  673. .tooltip {{
  674. position: absolute;
  675. background: rgba(0,0,0,0.9);
  676. color: #fff;
  677. padding: 10px 15px;
  678. border-radius: 6px;
  679. font-size: 12px;
  680. pointer-events: none;
  681. max-width: 300px;
  682. z-index: 1000;
  683. display: none;
  684. }}
  685. .controls {{
  686. background: rgba(15, 52, 96, 0.5);
  687. padding: 12px;
  688. border-radius: 8px;
  689. margin-top: auto;
  690. border-top: 1px solid #0f3460;
  691. padding-top: 15px;
  692. }}
  693. .controls button {{
  694. background: #0f3460;
  695. color: #fff;
  696. border: none;
  697. padding: 8px 15px;
  698. margin: 5px;
  699. border-radius: 4px;
  700. cursor: pointer;
  701. font-size: 12px;
  702. }}
  703. .controls button:hover {{
  704. background: #e94560;
  705. }}
  706. .controls button.active {{
  707. background: #e94560;
  708. }}
  709. .controls .control-group {{
  710. margin-top: 10px;
  711. padding-top: 10px;
  712. border-top: 1px solid rgba(255,255,255,0.1);
  713. }}
  714. .controls .control-label {{
  715. font-size: 11px;
  716. color: #888;
  717. margin-bottom: 5px;
  718. }}
  719. .controls select {{
  720. background: #0f3460;
  721. color: #fff;
  722. border: none;
  723. padding: 6px 10px;
  724. border-radius: 4px;
  725. font-size: 12px;
  726. cursor: pointer;
  727. }}
  728. /* 关系子图节点样式 */
  729. .ego-node {{
  730. cursor: pointer;
  731. }}
  732. .ego-node circle {{
  733. stroke-width: 2px;
  734. }}
  735. .ego-node.center circle {{
  736. stroke: #fff;
  737. stroke-width: 3px;
  738. filter: drop-shadow(0 0 8px rgba(255,255,255,0.5));
  739. }}
  740. .ego-node text {{
  741. font-size: 10px;
  742. fill: #fff;
  743. pointer-events: none;
  744. }}
  745. .ego-edge {{
  746. stroke-opacity: 0.6;
  747. stroke-width: 1.5;
  748. }}
  749. /* 帖子详情模态框 */
  750. .post-detail-modal {{
  751. display: none;
  752. position: fixed;
  753. z-index: 4000;
  754. left: 0;
  755. top: 0;
  756. width: 100%;
  757. height: 100%;
  758. background: rgba(0, 0, 0, 0.7);
  759. overflow: auto;
  760. }}
  761. .post-detail-modal.active {{
  762. display: flex;
  763. align-items: center;
  764. justify-content: center;
  765. padding: 40px 20px;
  766. }}
  767. .post-detail-content {{
  768. position: relative;
  769. background: white;
  770. border-radius: 16px;
  771. max-width: 900px;
  772. width: 100%;
  773. max-height: 90vh;
  774. overflow-y: auto;
  775. box-shadow: 0 20px 60px rgba(0,0,0,0.3);
  776. }}
  777. .post-detail-close {{
  778. position: sticky;
  779. top: 20px;
  780. right: 20px;
  781. float: right;
  782. font-size: 36px;
  783. font-weight: 300;
  784. color: #9ca3af;
  785. background: white;
  786. border: none;
  787. cursor: pointer;
  788. width: 40px;
  789. height: 40px;
  790. border-radius: 50%;
  791. display: flex;
  792. align-items: center;
  793. justify-content: center;
  794. z-index: 10;
  795. box-shadow: 0 2px 8px rgba(0,0,0,0.1);
  796. }}
  797. .post-detail-close:hover {{
  798. color: #ef4444;
  799. background: #fee2e2;
  800. }}
  801. .post-detail-header {{
  802. padding: 40px 40px 20px 40px;
  803. border-bottom: 2px solid #e5e7eb;
  804. }}
  805. .post-detail-title {{
  806. font-size: 28px;
  807. font-weight: bold;
  808. color: #111827;
  809. line-height: 1.4;
  810. margin-bottom: 15px;
  811. }}
  812. .post-detail-meta {{
  813. display: flex;
  814. justify-content: space-between;
  815. align-items: center;
  816. color: #6b7280;
  817. font-size: 14px;
  818. gap: 20px;
  819. }}
  820. .post-detail-stats {{
  821. display: flex;
  822. gap: 15px;
  823. font-weight: 500;
  824. }}
  825. .post-detail-body {{
  826. padding: 30px 40px;
  827. }}
  828. .post-detail-desc {{
  829. font-size: 16px;
  830. line-height: 1.8;
  831. color: #374151;
  832. margin-bottom: 25px;
  833. white-space: pre-wrap;
  834. }}
  835. .post-detail-images {{
  836. display: grid;
  837. grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
  838. gap: 15px;
  839. }}
  840. .post-detail-image {{
  841. width: 100%;
  842. border-radius: 12px;
  843. object-fit: cover;
  844. }}
  845. .post-detail-footer {{
  846. padding: 20px 40px 30px;
  847. text-align: center;
  848. border-top: 1px solid #e5e7eb;
  849. }}
  850. .post-detail-link {{
  851. display: inline-block;
  852. padding: 12px 30px;
  853. background: linear-gradient(135deg, #ff2442 0%, #ff6b81 100%);
  854. color: white;
  855. text-decoration: none;
  856. border-radius: 25px;
  857. font-weight: 600;
  858. }}
  859. /* 帖子树根节点卡片 */
  860. .post-card {{
  861. background: linear-gradient(135deg, #1a1a2e 0%, #16213e 100%);
  862. border: 2px solid #fff;
  863. border-radius: 12px;
  864. cursor: pointer;
  865. transition: all 0.3s ease;
  866. box-shadow: 0 4px 15px rgba(255, 255, 255, 0.2);
  867. height: 100%;
  868. display: flex;
  869. flex-direction: column;
  870. justify-content: center;
  871. }}
  872. .post-card:hover {{
  873. transform: scale(1.05);
  874. box-shadow: 0 6px 25px rgba(255, 255, 255, 0.4);
  875. border-color: #fff;
  876. }}
  877. .post-card-header {{
  878. display: flex;
  879. gap: 10px;
  880. align-items: center;
  881. }}
  882. .post-card-thumbnail-wrapper {{
  883. position: relative;
  884. flex-shrink: 0;
  885. border-radius: 8px;
  886. overflow: hidden;
  887. }}
  888. .post-card-thumbnail {{
  889. object-fit: cover;
  890. border-radius: 8px;
  891. }}
  892. .post-card-image-count {{
  893. position: absolute;
  894. bottom: 2px;
  895. right: 2px;
  896. background: rgba(0,0,0,0.7);
  897. color: #fff;
  898. padding: 1px 4px;
  899. border-radius: 3px;
  900. }}
  901. .post-card-thumbnail-placeholder {{
  902. background: linear-gradient(135deg, #0f3460 0%, #1a1a2e 100%);
  903. border-radius: 8px;
  904. display: flex;
  905. align-items: center;
  906. justify-content: center;
  907. color: #e94560;
  908. }}
  909. .post-card-info {{
  910. flex: 1;
  911. overflow: hidden;
  912. }}
  913. .post-card-title {{
  914. color: #fff;
  915. font-weight: 600;
  916. line-height: 1.3;
  917. display: -webkit-box;
  918. -webkit-box-orient: vertical;
  919. overflow: hidden;
  920. text-overflow: ellipsis;
  921. }}
  922. .post-card-stats {{
  923. color: #8892b0;
  924. display: flex;
  925. gap: 8px;
  926. margin-top: 4px;
  927. }}
  928. </style>
  929. </head>
  930. <body>
  931. <div id="container">
  932. <div class="tabs" id="tabs">
  933. {tabs_html}
  934. </div>
  935. <div class="main-content">
  936. <div id="left-panel">
  937. <div id="tree-container"></div>
  938. <div id="ego-container">
  939. <div class="ego-controls">
  940. <div class="cascade-dropdown">
  941. <div class="cascade-btn" onclick="toggleCascadeMenu()">
  942. <span id="cascade-label">1级</span>
  943. </div>
  944. <div class="cascade-menu" id="cascade-menu">
  945. <div class="cascade-levels">
  946. <div class="cascade-level-item active" data-level="1" onclick="selectLevel(1)">1级</div>
  947. <div class="cascade-level-item" data-level="2" onclick="selectLevel(2)">2级</div>
  948. <div class="cascade-level-item" data-level="3" onclick="selectLevel(3)">3级</div>
  949. </div>
  950. <div class="cascade-edges">
  951. <div class="cascade-edge-group active" data-level="1">
  952. <div class="cascade-edge-group-header">L1 <span class="header-actions"><label class="select-all"><input type="checkbox" data-level="1" data-select-all>全选</label><span class="invert-btn" data-level="1" onclick="invertSelection(1)">反选</span><span class="reset-btn" onclick="resetSelection()">重置</span></span></div>
  953. <label class="cascade-edge-item"><input type="checkbox" data-level="1" data-type="属于"><span class="edge-color" style="background:#9b59b6"></span>属于</label>
  954. <label class="cascade-edge-item"><input type="checkbox" data-level="1" data-type="包含"><span class="edge-color" style="background:#ffb6c1"></span>包含</label>
  955. <label class="cascade-edge-item"><input type="checkbox" data-level="1" data-type="分类共现(跨点)"><span class="edge-color" style="background:#2ecc71"></span>跨点共现</label>
  956. <label class="cascade-edge-item"><input type="checkbox" data-level="1" data-type="分类共现(点内)"><span class="edge-color" style="background:#3498db"></span>点内共现</label>
  957. <label class="cascade-edge-item"><input type="checkbox" data-level="1" data-type="标签共现"><span class="edge-color" style="background:#f39c12"></span>标签共现</label>
  958. </div>
  959. <div class="cascade-edge-group" data-level="2">
  960. <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>
  961. <label class="cascade-edge-item"><input type="checkbox" data-level="2" data-type="属于"><span class="edge-color" style="background:#9b59b6"></span>属于</label>
  962. <label class="cascade-edge-item"><input type="checkbox" data-level="2" data-type="包含"><span class="edge-color" style="background:#ffb6c1"></span>包含</label>
  963. <label class="cascade-edge-item"><input type="checkbox" data-level="2" data-type="分类共现(跨点)"><span class="edge-color" style="background:#2ecc71"></span>跨点共现</label>
  964. <label class="cascade-edge-item"><input type="checkbox" data-level="2" data-type="分类共现(点内)"><span class="edge-color" style="background:#3498db"></span>点内共现</label>
  965. <label class="cascade-edge-item"><input type="checkbox" data-level="2" data-type="标签共现"><span class="edge-color" style="background:#f39c12"></span>标签共现</label>
  966. </div>
  967. <div class="cascade-edge-group" data-level="3">
  968. <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>
  969. <label class="cascade-edge-item"><input type="checkbox" data-level="3" data-type="属于"><span class="edge-color" style="background:#9b59b6"></span>属于</label>
  970. <label class="cascade-edge-item"><input type="checkbox" data-level="3" data-type="包含"><span class="edge-color" style="background:#ffb6c1"></span>包含</label>
  971. <label class="cascade-edge-item"><input type="checkbox" data-level="3" data-type="分类共现(跨点)"><span class="edge-color" style="background:#2ecc71"></span>跨点共现</label>
  972. <label class="cascade-edge-item"><input type="checkbox" data-level="3" data-type="分类共现(点内)"><span class="edge-color" style="background:#3498db"></span>点内共现</label>
  973. <label class="cascade-edge-item"><input type="checkbox" data-level="3" data-type="标签共现"><span class="edge-color" style="background:#f39c12"></span>标签共现</label>
  974. </div>
  975. </div>
  976. </div>
  977. </div>
  978. <div class="ego-title-center" id="ego-node-name"></div>
  979. <div class="ego-stats" id="ego-stats"></div>
  980. </div>
  981. </div>
  982. </div>
  983. <div id="graph">
  984. <div class="tooltip" id="tooltip"></div>
  985. </div>
  986. <div id="sidebar">
  987. <h1>匹配图谱</h1>
  988. <div class="match-list-panel">
  989. <h3>匹配关系 <span id="matchCount">(0)</span></h3>
  990. <div id="matchList" class="match-list"></div>
  991. </div>
  992. <div class="detail-panel active" id="detailPanel">
  993. <h3 id="detailTitle">点击节点或边查看详情</h3>
  994. <div id="detailContent">
  995. <p style="color: #888; font-size: 11px;">点击图中的节点或边,这里会显示详细信息</p>
  996. </div>
  997. </div>
  998. <div class="legend">
  999. <h2>节点</h2>
  1000. <div class="legend-grid">
  1001. <div class="legend-item">
  1002. <div class="legend-color" style="background: #f39c12; border: 2px solid #fff;"></div>
  1003. <span>灵感点</span>
  1004. </div>
  1005. <div class="legend-item">
  1006. <div class="legend-color" style="background: #3498db; border: 2px solid #fff;"></div>
  1007. <span>目的点</span>
  1008. </div>
  1009. <div class="legend-item">
  1010. <div class="legend-color" style="background: #9b59b6; border: 2px solid #fff;"></div>
  1011. <span>关键点</span>
  1012. </div>
  1013. </div>
  1014. <h2>边</h2>
  1015. <div class="legend-grid">
  1016. <div class="legend-item">
  1017. <div class="legend-line" style="background: #e94560;"></div>
  1018. <span>相同(≥0.8)</span>
  1019. </div>
  1020. <div class="legend-item">
  1021. <div class="legend-line" style="background: linear-gradient(90deg, #e94560 0%, #e94560 40%, transparent 40%, transparent 60%, #e94560 60%);"></div>
  1022. <span>相似(0.5-0.8)</span>
  1023. </div>
  1024. <div class="legend-item">
  1025. <div class="legend-line" style="background: #9b59b6;"></div>
  1026. <span>属于</span>
  1027. </div>
  1028. <div class="legend-item">
  1029. <div class="legend-line" style="background: #2ecc71;"></div>
  1030. <span>分类共现(跨)</span>
  1031. </div>
  1032. <div class="legend-item">
  1033. <div class="legend-line" style="background: #3498db;"></div>
  1034. <span>分类共现(内)</span>
  1035. </div>
  1036. <div class="legend-item">
  1037. <div class="legend-line" style="background: #f39c12;"></div>
  1038. <span>标签共现</span>
  1039. </div>
  1040. </div>
  1041. </div>
  1042. <div class="controls">
  1043. <div class="control-label">视图控制</div>
  1044. <button onclick="resetZoom()">重置视图</button>
  1045. <button onclick="toggleLabels()">切换标签</button>
  1046. <button onclick="toggleCrossLayerEdges()" id="crossLayerBtn">显示跨层边</button>
  1047. <div class="control-group">
  1048. <div class="control-label">人设树配置</div>
  1049. <button onclick="toggleTreeTags()" id="treeTagBtn" class="active">显示标签</button>
  1050. <select id="treeDepthSelect" onchange="setTreeDepth(this.value)">
  1051. <option value="0">全部层级</option>
  1052. <option value="2">2层</option>
  1053. <option value="3">3层</option>
  1054. <option value="4">4层</option>
  1055. <option value="5">5层</option>
  1056. </select>
  1057. </div>
  1058. </div>
  1059. </div>
  1060. </div>
  1061. </div>
  1062. <script>
  1063. // 所有帖子的图谱数据
  1064. const allGraphData = {all_graph_data};
  1065. // 完整的人设树数据(所有人设节点和属于边)
  1066. const personaTreeData = {persona_tree_data};
  1067. // 当前选中的帖子索引
  1068. let currentIndex = 0;
  1069. let simulation = null;
  1070. let svg = null;
  1071. let g = null;
  1072. let treeSvg = null; // 人设树独立SVG
  1073. let treeG = null; // 人设树group
  1074. let egoSvg = null; // 关系图独立SVG
  1075. let egoG = null; // 关系图group
  1076. let zoom = null;
  1077. let showLabels = true;
  1078. let showCrossLayerEdges = false; // 跨层边默认隐藏
  1079. let isCrossLayerEdge = null; // 跨层边判断函数(在renderGraph中设置)
  1080. // 人设树配置
  1081. let showTreeTags = true; // 是否显示标签节点
  1082. let treeMaxDepth = 0; // 显示的最大层数(0=全部)
  1083. // 切换标签显示
  1084. function toggleTreeTags() {{
  1085. showTreeTags = !showTreeTags;
  1086. const btn = document.getElementById("treeTagBtn");
  1087. btn.textContent = showTreeTags ? "显示标签" : "隐藏标签";
  1088. btn.classList.toggle("active", showTreeTags);
  1089. // 重新渲染当前图谱
  1090. renderGraph(allGraphData[currentIndex]);
  1091. }}
  1092. // 设置树的显示层数
  1093. function setTreeDepth(depth) {{
  1094. treeMaxDepth = parseInt(depth);
  1095. // 重新渲染当前图谱
  1096. renderGraph(allGraphData[currentIndex]);
  1097. }}
  1098. // 初始化
  1099. function init() {{
  1100. const container = document.getElementById("graph");
  1101. const treeContainer = document.getElementById("tree-container");
  1102. const width = container.clientWidth;
  1103. const height = container.clientHeight;
  1104. // 创建圆形层SVG
  1105. svg = d3.select("#graph")
  1106. .append("svg")
  1107. .attr("width", width)
  1108. .attr("height", height);
  1109. g = svg.append("g");
  1110. zoom = d3.zoom()
  1111. .scaleExtent([0.1, 4])
  1112. .on("zoom", (event) => {{
  1113. g.attr("transform", event.transform);
  1114. }});
  1115. svg.call(zoom);
  1116. // 创建人设树SVG(独立可滚动)
  1117. treeSvg = d3.select("#tree-container")
  1118. .append("svg")
  1119. .attr("width", 400);
  1120. treeG = treeSvg.append("g");
  1121. // 创建关系图SVG(在独立的ego-container中)
  1122. egoSvg = d3.select("#ego-container")
  1123. .append("svg")
  1124. .attr("width", 400)
  1125. .attr("height", 400);
  1126. egoG = egoSvg.append("g");
  1127. // 关系图缩放
  1128. const egoZoom = d3.zoom()
  1129. .scaleExtent([0.3, 3])
  1130. .on("zoom", (event) => {{
  1131. egoG.attr("transform", event.transform);
  1132. }});
  1133. egoSvg.call(egoZoom);
  1134. // 绑定Tab点击事件
  1135. document.querySelectorAll(".tab").forEach((tab, index) => {{
  1136. tab.addEventListener("click", () => switchTab(index));
  1137. }});
  1138. // 绑定关系图控制面板事件
  1139. // 全选复选框事件
  1140. document.querySelectorAll('.select-all input').forEach(cb => {{
  1141. cb.addEventListener('change', (e) => {{
  1142. const level = e.target.dataset.level;
  1143. const checked = e.target.checked;
  1144. // 设置该层级所有边类型复选框
  1145. document.querySelectorAll(`.cascade-edge-item input[data-level="${{level}}"]`).forEach(item => {{
  1146. item.checked = checked;
  1147. }});
  1148. // 重新渲染关系图和人设树高亮
  1149. if (currentEgoCenterNodeId) {{
  1150. handleNodeClick(currentEgoCenterNodeId, currentEgoCenterNodeName);
  1151. }}
  1152. }});
  1153. }});
  1154. // 边类型复选框变化事件
  1155. document.querySelectorAll('.cascade-edge-item input').forEach(cb => {{
  1156. cb.addEventListener('change', (e) => {{
  1157. // 更新全选复选框状态
  1158. const level = e.target.dataset.level;
  1159. const allItems = document.querySelectorAll(`.cascade-edge-item input[data-level="${{level}}"]`);
  1160. const checkedItems = document.querySelectorAll(`.cascade-edge-item input[data-level="${{level}}"]:checked`);
  1161. const selectAllCb = document.querySelector(`.select-all input[data-level="${{level}}"]`);
  1162. selectAllCb.checked = allItems.length === checkedItems.length;
  1163. // 重新渲染关系图和人设树高亮
  1164. if (currentEgoCenterNodeId) {{
  1165. handleNodeClick(currentEgoCenterNodeId, currentEgoCenterNodeName);
  1166. }}
  1167. }});
  1168. }});
  1169. // 点击页面其他地方关闭级联菜单
  1170. document.addEventListener('click', (e) => {{
  1171. if (!e.target.closest('.cascade-dropdown')) {{
  1172. document.getElementById('cascade-menu').classList.remove('show');
  1173. }}
  1174. }});
  1175. // 显示第一个帖子
  1176. switchTab(0);
  1177. }}
  1178. // 构建人设树数据(合并为一棵树,根节点为"人设")
  1179. // showTreeTags: 控制是否显示标签节点
  1180. // treeMaxDepth: 控制树的显示深度(0=全部,2=维度,3=+一层,4=+两层...)
  1181. function buildPersonaTreeData() {{
  1182. const dimensions = ["灵感点", "目的点", "关键点"];
  1183. const dimColors = {{ "灵感点": "#f39c12", "目的点": "#3498db", "关键点": "#9b59b6" }};
  1184. const dimensionChildren = [];
  1185. let totalNodeCount = 0;
  1186. dimensions.forEach(dim => {{
  1187. // 根据 showTreeTags 过滤节点(独立于深度控制)
  1188. let dimNodes = personaTreeData.nodes.filter(n => n.节点层级 === dim);
  1189. if (!showTreeTags) {{
  1190. dimNodes = dimNodes.filter(n => n.节点类型 !== "标签");
  1191. }}
  1192. if (dimNodes.length === 0) {{
  1193. const dimNode = {{
  1194. name: dim,
  1195. 节点名称: dim,
  1196. isDimension: true,
  1197. dimColor: dimColors[dim],
  1198. children: []
  1199. }};
  1200. dimensionChildren.push(dimNode);
  1201. return;
  1202. }}
  1203. const nodeMap = {{}};
  1204. dimNodes.forEach(n => nodeMap[n.节点ID] = {{ ...n, name: n.节点名称, children: [], dimColor: dimColors[dim] }});
  1205. // 只用属于边构建父子关系
  1206. const hierarchyEdgeTypes = ["属于"];
  1207. const hasParent = new Set();
  1208. personaTreeData.edges.forEach(e => {{
  1209. if (!hierarchyEdgeTypes.includes(e.边类型)) return; // 跳过非层级边
  1210. const srcNode = nodeMap[e.源节点ID];
  1211. const tgtNode = nodeMap[e.目标节点ID];
  1212. if (srcNode && tgtNode) {{
  1213. tgtNode.children.push(srcNode);
  1214. hasParent.add(e.源节点ID);
  1215. }}
  1216. }});
  1217. const roots = dimNodes.filter(n => !hasParent.has(n.节点ID)).map(n => nodeMap[n.节点ID]);
  1218. const dimNode = {{
  1219. name: dim,
  1220. 节点名称: dim,
  1221. isDimension: true,
  1222. dimColor: dimColors[dim],
  1223. children: roots
  1224. }};
  1225. dimensionChildren.push(dimNode);
  1226. totalNodeCount += dimNodes.length;
  1227. }});
  1228. // 根节点"人设"
  1229. const rootNode = {{
  1230. name: "人设",
  1231. 节点名称: "人设",
  1232. isRoot: true,
  1233. children: dimensionChildren
  1234. }};
  1235. // 根据 treeMaxDepth 截断树深度(0=全部)
  1236. // 深度1=根,深度2=维度,深度3+=子节点
  1237. if (treeMaxDepth > 0) {{
  1238. truncateTree(rootNode, 1, treeMaxDepth);
  1239. }}
  1240. return {{ root: rootNode, nodeCount: totalNodeCount }};
  1241. }}
  1242. // 递归截断树的深度
  1243. function truncateTree(node, currentDepth, maxDepth) {{
  1244. if (currentDepth >= maxDepth) {{
  1245. node.children = [];
  1246. return;
  1247. }}
  1248. if (node.children) {{
  1249. node.children.forEach(child => truncateTree(child, currentDepth + 1, maxDepth));
  1250. }}
  1251. }}
  1252. // 构建帖子树数据(从上到下:帖子 -> 维度 -> 点 -> 标签)
  1253. function buildPostTreeData(graphData) {{
  1254. const dimensions = ["灵感点", "目的点", "关键点"];
  1255. const dimColors = {{ "灵感点": "#f39c12", "目的点": "#3498db", "关键点": "#9b59b6" }};
  1256. const dimensionChildren = [];
  1257. let totalNodeCount = 0;
  1258. const postDetail = graphData.postDetail || {{}};
  1259. // 获取帖子点和帖子标签
  1260. const postPointNodes = graphData.帖子点节点列表 || [];
  1261. const postTagNodes = graphData.帖子标签节点列表 || [];
  1262. const belongEdges = graphData.帖子属于边列表 || [];
  1263. // 构建节点映射
  1264. const pointMap = {{}};
  1265. postPointNodes.forEach(n => {{
  1266. pointMap[n.节点ID] = {{
  1267. ...n,
  1268. id: n.节点ID,
  1269. name: n.节点名称,
  1270. nodeType: "点",
  1271. dimColor: dimColors[n.节点层级],
  1272. children: []
  1273. }};
  1274. }});
  1275. const tagMap = {{}};
  1276. postTagNodes.forEach(n => {{
  1277. tagMap[n.节点ID] = {{
  1278. ...n,
  1279. id: n.节点ID,
  1280. name: n.节点名称,
  1281. nodeType: "标签",
  1282. dimColor: dimColors[n.节点层级],
  1283. children: []
  1284. }};
  1285. }});
  1286. // 根据属于边,把标签挂到点下面
  1287. belongEdges.forEach(e => {{
  1288. const tagNode = tagMap[e.源节点ID];
  1289. const pointNode = pointMap[e.目标节点ID];
  1290. if (tagNode && pointNode) {{
  1291. pointNode.children.push(tagNode);
  1292. }}
  1293. }});
  1294. // 按维度分组点节点
  1295. dimensions.forEach(dim => {{
  1296. const dimPoints = postPointNodes
  1297. .filter(n => n.节点层级 === dim)
  1298. .map(n => pointMap[n.节点ID]);
  1299. if (dimPoints.length > 0) {{
  1300. const dimNode = {{
  1301. name: dim,
  1302. 节点名称: dim,
  1303. isDimension: true,
  1304. dimColor: dimColors[dim],
  1305. children: dimPoints
  1306. }};
  1307. dimensionChildren.push(dimNode);
  1308. totalNodeCount += dimPoints.length;
  1309. dimPoints.forEach(p => totalNodeCount += p.children.length);
  1310. }}
  1311. }});
  1312. // 根节点"帖子"
  1313. const title = postDetail.title || "帖子";
  1314. const rootNode = {{
  1315. name: title.length > 15 ? title.substring(0, 15) + "..." : title,
  1316. 节点名称: title,
  1317. isRoot: true,
  1318. postDetail: postDetail,
  1319. children: dimensionChildren
  1320. }};
  1321. return {{ root: rootNode, nodeCount: totalNodeCount, tagMap: tagMap }};
  1322. }}
  1323. // 显示帖子详情模态框
  1324. function showPostDetail(postData) {{
  1325. if (!postData) return;
  1326. // 生成图片HTML
  1327. let imagesHtml = '';
  1328. if (postData.images && postData.images.length > 0) {{
  1329. imagesHtml = postData.images.map(img =>
  1330. `<img src="${{img}}" class="post-detail-image" alt="图片" loading="lazy">`
  1331. ).join('');
  1332. }} else {{
  1333. imagesHtml = '<div style="text-align: center; color: #9ca3af; padding: 40px;">暂无图片</div>';
  1334. }}
  1335. const modalHtml = `
  1336. <div class="post-detail-content" onclick="event.stopPropagation()">
  1337. <button class="post-detail-close" onclick="closePostDetail()">×</button>
  1338. <div class="post-detail-header">
  1339. <div class="post-detail-title">${{postData.title || '无标题'}}</div>
  1340. <div class="post-detail-meta">
  1341. <div>
  1342. <span>👤 ${{postData.author || '未知作者'}}</span>
  1343. <span> · 📅 ${{postData.publish_time || ''}}</span>
  1344. </div>
  1345. <div class="post-detail-stats">
  1346. <span>👍 ${{postData.like_count || 0}}</span>
  1347. <span>💬 ${{postData.comment_count || 0}}</span>
  1348. <span>⭐ ${{postData.collect_count || 0}}</span>
  1349. </div>
  1350. </div>
  1351. </div>
  1352. <div class="post-detail-body">
  1353. ${{postData.body_text ? `<div class="post-detail-desc">${{postData.body_text}}</div>` : '<div style="color: #9ca3af;">暂无正文</div>'}}
  1354. <div class="post-detail-images">
  1355. ${{imagesHtml}}
  1356. </div>
  1357. </div>
  1358. <div class="post-detail-footer">
  1359. <a href="${{postData.link || '#'}}" target="_blank" class="post-detail-link">
  1360. 在小红书查看完整内容 →
  1361. </a>
  1362. </div>
  1363. </div>
  1364. `;
  1365. let modal = document.getElementById('postDetailModal');
  1366. if (!modal) {{
  1367. modal = document.createElement('div');
  1368. modal.id = 'postDetailModal';
  1369. modal.className = 'post-detail-modal';
  1370. modal.onclick = closePostDetail;
  1371. document.body.appendChild(modal);
  1372. }}
  1373. modal.innerHTML = modalHtml;
  1374. modal.classList.add('active');
  1375. document.body.style.overflow = 'hidden';
  1376. }}
  1377. function closePostDetail(event) {{
  1378. if (event && event.target !== event.currentTarget) return;
  1379. const modal = document.getElementById('postDetailModal');
  1380. if (modal) {{
  1381. modal.classList.remove('active');
  1382. document.body.style.overflow = '';
  1383. }}
  1384. }}
  1385. // 切换Tab
  1386. function switchTab(index) {{
  1387. currentIndex = index;
  1388. // 更新Tab样式
  1389. document.querySelectorAll(".tab").forEach((tab, i) => {{
  1390. tab.classList.toggle("active", i === index);
  1391. }});
  1392. // 更新图谱
  1393. renderGraph(allGraphData[index]);
  1394. }}
  1395. // 渲染图谱
  1396. function renderGraph(data) {{
  1397. // 清空现有图谱
  1398. g.selectAll("*").remove();
  1399. treeG.selectAll("*").remove();
  1400. if (simulation) {{
  1401. simulation.stop();
  1402. }}
  1403. const container = document.getElementById("graph");
  1404. const width = container.clientWidth;
  1405. // 布局配置:人设树在左侧独立容器,右侧是圆形层
  1406. const treeAreaWidth = 400; // 固定树宽度
  1407. const circleAreaWidth = width - 40;
  1408. const circleAreaCenterX = circleAreaWidth / 2;
  1409. // 准备数据(过滤掉帖子点,只保留帖子标签和人设节点)
  1410. const nodes = data.nodes
  1411. .filter(n => !(n.节点ID.startsWith("帖子_") && n.节点类型 === "点"))
  1412. .map(n => ({{
  1413. ...n,
  1414. id: n.节点ID,
  1415. source: n.节点ID.startsWith("帖子_") ? "帖子" : "人设",
  1416. level: n.节点层级
  1417. }}));
  1418. // 判断是否是帖子点节点ID
  1419. function isPostPointId(id) {{
  1420. return id.startsWith("帖子_") && id.includes("_点_");
  1421. }}
  1422. // 过滤掉引用帖子点节点的边
  1423. const links = data.edges
  1424. .filter(e => !isPostPointId(e.源节点ID) && !isPostPointId(e.目标节点ID))
  1425. .map(e => ({{
  1426. ...e,
  1427. source: e.源节点ID,
  1428. target: e.目标节点ID,
  1429. type: e.边类型,
  1430. similarity: e.边详情 ? e.边详情.相似度 : 0
  1431. }}));
  1432. // 分离节点类型
  1433. const postNodes = nodes.filter(n => n.source === "帖子");
  1434. const personaNodes = nodes.filter(n => n.source === "人设" && !n.是否扩展);
  1435. const expandedNodes = nodes.filter(n => n.source === "人设" && n.是否扩展);
  1436. const matchLinks = links.filter(l => l.type.startsWith("匹配_"));
  1437. // 更新匹配列表(按分数降序)
  1438. updateMatchList(matchLinks, nodes);
  1439. // 构建帖子节点到人设节点的映射
  1440. const postToPersona = {{}};
  1441. const personaToPost = {{}};
  1442. matchLinks.forEach(l => {{
  1443. const sid = typeof l.source === "object" ? l.source.id : l.source;
  1444. const tid = typeof l.target === "object" ? l.target.id : l.target;
  1445. if (!postToPersona[sid]) postToPersona[sid] = [];
  1446. postToPersona[sid].push(tid);
  1447. if (!personaToPost[tid]) personaToPost[tid] = [];
  1448. personaToPost[tid].push(sid);
  1449. }});
  1450. // 找出所有连通分量
  1451. function findConnectedComponents(nodes, links) {{
  1452. const nodeIds = new Set(nodes.map(n => n.id));
  1453. const adj = {{}};
  1454. nodeIds.forEach(id => adj[id] = []);
  1455. links.forEach(l => {{
  1456. const sid = typeof l.source === "object" ? l.source.id : l.source;
  1457. const tid = typeof l.target === "object" ? l.target.id : l.target;
  1458. if (nodeIds.has(sid) && nodeIds.has(tid)) {{
  1459. adj[sid].push(tid);
  1460. adj[tid].push(sid);
  1461. }}
  1462. }});
  1463. const visited = new Set();
  1464. const components = [];
  1465. nodeIds.forEach(startId => {{
  1466. if (visited.has(startId)) return;
  1467. const component = [];
  1468. const queue = [startId];
  1469. while (queue.length > 0) {{
  1470. const id = queue.shift();
  1471. if (visited.has(id)) continue;
  1472. visited.add(id);
  1473. component.push(id);
  1474. adj[id].forEach(neighbor => {{
  1475. if (!visited.has(neighbor)) queue.push(neighbor);
  1476. }});
  1477. }}
  1478. components.push(component);
  1479. }});
  1480. return components;
  1481. }}
  1482. // 按大小排序连通分量(大的在前)
  1483. const components = findConnectedComponents(nodes, links)
  1484. .sort((a, b) => b.length - a.length);
  1485. console.log(`找到 ${{components.length}} 个连通分量`);
  1486. // 为每个节点分配连通分量ID和分量内的X范围
  1487. const nodeToComponent = {{}};
  1488. const componentCenters = {{}};
  1489. const componentBounds = {{}};
  1490. const padding = 50; // 分量之间的间距
  1491. const totalPadding = padding * (components.length - 1);
  1492. const availableWidth = width - totalPadding - 100; // 留边距
  1493. // 根据分量大小分配宽度
  1494. const totalNodes = nodes.length;
  1495. let currentX = 50; // 起始边距
  1496. components.forEach((comp, i) => {{
  1497. const compWidth = Math.max(150, (comp.length / totalNodes) * availableWidth);
  1498. const centerX = currentX + compWidth / 2;
  1499. componentCenters[i] = centerX;
  1500. componentBounds[i] = {{ start: currentX, end: currentX + compWidth, width: compWidth }};
  1501. comp.forEach(nodeId => {{
  1502. nodeToComponent[nodeId] = i;
  1503. }});
  1504. currentX += compWidth + padding;
  1505. }});
  1506. // 使用重心法(Barycenter)减少边交叉
  1507. // 迭代优化:交替调整两层节点的顺序
  1508. const nodeTargetX = {{}};
  1509. const personaXMap = {{}};
  1510. // 对每个连通分量单独处理
  1511. components.forEach((comp, compIdx) => {{
  1512. const bounds = componentBounds[compIdx];
  1513. const compPostNodes = postNodes.filter(n => nodeToComponent[n.id] === compIdx);
  1514. const compPersonaNodes = personaNodes.filter(n => nodeToComponent[n.id] === compIdx);
  1515. if (compPostNodes.length === 0 || compPersonaNodes.length === 0) {{
  1516. // 没有匹配关系的分量,均匀分布
  1517. const spacing = bounds.width / (comp.length + 1);
  1518. comp.forEach((nodeId, i) => {{
  1519. const node = nodes.find(n => n.id === nodeId);
  1520. if (node) {{
  1521. node.x = bounds.start + spacing * (i + 1);
  1522. nodeTargetX[nodeId] = node.x;
  1523. if (node.source === "人设") personaXMap[nodeId] = node.x;
  1524. }}
  1525. }});
  1526. return;
  1527. }}
  1528. // 初始化:给人设节点一个初始顺序
  1529. let personaOrder = compPersonaNodes.map((n, i) => ({{ node: n, order: i }}));
  1530. // 迭代优化(3轮)
  1531. for (let iter = 0; iter < 3; iter++) {{
  1532. // 1. 根据人设节点位置,计算帖子节点的重心
  1533. const postBarycenter = {{}};
  1534. compPostNodes.forEach(pn => {{
  1535. const matched = postToPersona[pn.id] || [];
  1536. if (matched.length > 0) {{
  1537. const avgOrder = matched.reduce((sum, pid) => {{
  1538. const po = personaOrder.find(p => p.node.id === pid);
  1539. return sum + (po ? po.order : 0);
  1540. }}, 0) / matched.length;
  1541. postBarycenter[pn.id] = avgOrder;
  1542. }} else {{
  1543. postBarycenter[pn.id] = 0;
  1544. }}
  1545. }});
  1546. // 按重心排序帖子节点
  1547. const sortedPosts = [...compPostNodes].sort((a, b) =>
  1548. postBarycenter[a.id] - postBarycenter[b.id]
  1549. );
  1550. // 2. 根据帖子节点位置,重新计算人设节点的重心
  1551. const personaBarycenter = {{}};
  1552. compPersonaNodes.forEach(pn => {{
  1553. const matched = personaToPost[pn.id] || [];
  1554. if (matched.length > 0) {{
  1555. const avgOrder = matched.reduce((sum, pid) => {{
  1556. const idx = sortedPosts.findIndex(p => p.id === pid);
  1557. return sum + (idx >= 0 ? idx : 0);
  1558. }}, 0) / matched.length;
  1559. personaBarycenter[pn.id] = avgOrder;
  1560. }} else {{
  1561. personaBarycenter[pn.id] = personaOrder.find(p => p.node.id === pn.id)?.order || 0;
  1562. }}
  1563. }});
  1564. // 更新人设节点顺序
  1565. personaOrder = compPersonaNodes
  1566. .map(n => ({{ node: n, order: personaBarycenter[n.id] }}))
  1567. .sort((a, b) => a.order - b.order)
  1568. .map((item, i) => ({{ node: item.node, order: i }}));
  1569. }}
  1570. // 最终排序
  1571. const finalPersonaOrder = personaOrder.map(p => p.node);
  1572. const postBarycenter = {{}};
  1573. compPostNodes.forEach(pn => {{
  1574. const matched = postToPersona[pn.id] || [];
  1575. if (matched.length > 0) {{
  1576. const avgOrder = matched.reduce((sum, pid) => {{
  1577. const idx = finalPersonaOrder.findIndex(n => n.id === pid);
  1578. return sum + (idx >= 0 ? idx : 0);
  1579. }}, 0) / matched.length;
  1580. postBarycenter[pn.id] = avgOrder;
  1581. }} else {{
  1582. postBarycenter[pn.id] = 0;
  1583. }}
  1584. }});
  1585. const finalPostOrder = [...compPostNodes].sort((a, b) =>
  1586. postBarycenter[a.id] - postBarycenter[b.id]
  1587. );
  1588. // 设置位置
  1589. const personaSpacing = bounds.width / (finalPersonaOrder.length + 1);
  1590. finalPersonaOrder.forEach((n, i) => {{
  1591. n.x = bounds.start + personaSpacing * (i + 1);
  1592. nodeTargetX[n.id] = n.x;
  1593. personaXMap[n.id] = n.x;
  1594. }});
  1595. const postSpacing = bounds.width / (finalPostOrder.length + 1);
  1596. finalPostOrder.forEach((n, i) => {{
  1597. // 帖子节点用重心位置(匹配人设的平均X)
  1598. const matched = postToPersona[n.id] || [];
  1599. if (matched.length > 0) {{
  1600. const avgX = matched.reduce((sum, pid) => sum + (personaXMap[pid] || bounds.start + bounds.width/2), 0) / matched.length;
  1601. n.x = avgX;
  1602. }} else {{
  1603. n.x = bounds.start + postSpacing * (i + 1);
  1604. }}
  1605. nodeTargetX[n.id] = n.x;
  1606. }});
  1607. }});
  1608. // 节点颜色
  1609. const levelColors = {{
  1610. "灵感点": "#f39c12",
  1611. "目的点": "#3498db",
  1612. "关键点": "#9b59b6"
  1613. }};
  1614. // 获取节点的层级编号(三层结构:帖子标签、人设匹配1层、人设匹配2层)
  1615. function getNodeLayer(d) {{
  1616. if (d.source === "帖子") {{
  1617. return 0; // 帖子标签=0
  1618. }}
  1619. // 人设节点:根据是否扩展分成两层
  1620. return d.是否扩展 ? 2 : 1; // 直接匹配=1, 扩展=2
  1621. }}
  1622. // 统计每层节点数量(三层结构)
  1623. const layerCounts = {{0: 0, 1: 0, 2: 0}};
  1624. nodes.forEach(n => {{
  1625. const layer = getNodeLayer(n);
  1626. layerCounts[layer]++;
  1627. }});
  1628. console.log("每层节点数:", layerCounts);
  1629. // 根据节点数量计算每层圆的半径
  1630. // 三层垂直排列:帖子标签(上)+ 人设匹配1层(中)+ 人设匹配2层(下)
  1631. const minRadius = 80;
  1632. const maxRadius = Math.min(circleAreaWidth / 3 - 20, 180);
  1633. const nodeSpacing = 60;
  1634. function calcRadius(nodeCount) {{
  1635. if (nodeCount <= 1) return minRadius;
  1636. const circumference = nodeCount * nodeSpacing;
  1637. const r = circumference / (2 * Math.PI);
  1638. return Math.max(minRadius, Math.min(maxRadius, r));
  1639. }}
  1640. // 三层统一大小(取最大值)
  1641. const unifiedRadius = Math.max(
  1642. calcRadius(layerCounts[0]),
  1643. calcRadius(layerCounts[1]),
  1644. calcRadius(layerCounts[2])
  1645. );
  1646. const layerRadius = {{
  1647. 0: unifiedRadius, // 帖子标签(上)
  1648. 1: unifiedRadius, // 人设匹配1层(中)
  1649. 2: unifiedRadius // 人设匹配2层(下)
  1650. }};
  1651. console.log("每层半径:", layerRadius);
  1652. // 获取人设树数据(单棵树)
  1653. const personaTree = buildPersonaTreeData();
  1654. // 树高度自适应:根据节点数量,每个节点约12px,最小800
  1655. const treeHeight = Math.max(800, personaTree.nodeCount * 12 + 150);
  1656. // 关系图配置(放在树下方)
  1657. const egoRadius = 180;
  1658. const egoAreaHeight = egoRadius * 2 + 80;
  1659. // 计算布局:三层垂直排列(帖子标签+人设匹配1层+人设匹配2层)
  1660. const layerPadding = 60;
  1661. const circleHeight = layerRadius[0] * 2 + layerPadding + layerRadius[1] * 2 + layerPadding + layerRadius[2] * 2 + layerPadding;
  1662. const height = Math.max(circleHeight + 80, treeHeight + 80, container.clientHeight);
  1663. // 计算每层圆心坐标(垂直居中排列)
  1664. const layerCenterX = {{}};
  1665. const layerCenterY = {{}};
  1666. // 三层垂直排列,X坐标相同
  1667. const colX = circleAreaCenterX;
  1668. // 帖子标签(上)+ 人设匹配1层(中)+ 人设匹配2层(下)
  1669. layerCenterX[0] = colX;
  1670. layerCenterY[0] = layerRadius[0] + layerPadding / 2 + 20;
  1671. layerCenterX[1] = colX;
  1672. layerCenterY[1] = layerCenterY[0] + layerRadius[0] + layerPadding + layerRadius[1];
  1673. layerCenterX[2] = colX;
  1674. layerCenterY[2] = layerCenterY[1] + layerRadius[1] + layerPadding + layerRadius[2];
  1675. console.log("每层圆心X:", layerCenterX);
  1676. console.log("每层圆心Y:", layerCenterY);
  1677. // 更新SVG高度
  1678. svg.attr("height", height);
  1679. // 获取节点的基准Y(层圆心)
  1680. function getNodeBaseY(d) {{
  1681. const layer = getNodeLayer(d);
  1682. return layerCenterY[layer];
  1683. }}
  1684. // 获取节点的基准X(层圆心)
  1685. function getNodeBaseX(d) {{
  1686. const layer = getNodeLayer(d);
  1687. return layerCenterX[layer];
  1688. }}
  1689. // 层边界配置(不再使用)
  1690. const layerBounds = {{}};
  1691. // 自定义层内排斥力(只对同层节点生效,尽量分散)
  1692. function forceIntraLayerRepulsion(strength) {{
  1693. let nodes;
  1694. function force(alpha) {{
  1695. for (let i = 0; i < nodes.length; i++) {{
  1696. const nodeA = nodes[i];
  1697. const layerA = getNodeLayer(nodeA);
  1698. for (let j = i + 1; j < nodes.length; j++) {{
  1699. const nodeB = nodes[j];
  1700. const layerB = getNodeLayer(nodeB);
  1701. // 只对同层节点施加排斥力
  1702. if (layerA !== layerB) continue;
  1703. const dx = nodeB.x - nodeA.x;
  1704. const dy = nodeB.y - nodeA.y;
  1705. const dist = Math.sqrt(dx * dx + dy * dy) || 1;
  1706. const minDist = 150; // 增大最小距离,让节点更分散
  1707. if (dist < minDist) {{
  1708. // 排斥力随距离衰减,但基础强度更大
  1709. const pushStrength = strength * alpha * (minDist - dist) / dist * 2;
  1710. const px = dx * pushStrength;
  1711. const py = dy * pushStrength;
  1712. nodeA.vx -= px;
  1713. nodeA.vy -= py;
  1714. nodeB.vx += px;
  1715. nodeB.vy += py;
  1716. }}
  1717. }}
  1718. }}
  1719. }}
  1720. force.initialize = function(_) {{
  1721. nodes = _;
  1722. }};
  1723. return force;
  1724. }}
  1725. // 层圆的半径(使用动态计算的 layerRadius)
  1726. // layerRadius 和 layerCenterY 已在前面定义
  1727. // 层边界约束力(把节点限制在层内)
  1728. function forceLayerBoundary() {{
  1729. let nodes;
  1730. function force(alpha) {{
  1731. nodes.forEach(node => {{
  1732. const layer = getNodeLayer(node);
  1733. const centerX = layerCenterX[layer];
  1734. const centerY = layerCenterY[layer];
  1735. // 使用圆形边界
  1736. const maxRadius = layerRadius[layer] - 15;
  1737. // 计算到圆心的距离
  1738. const dx = node.x - centerX;
  1739. const dy = node.y - centerY;
  1740. const dist = Math.sqrt(dx * dx + dy * dy);
  1741. // 如果超出圆形边界,拉回来
  1742. if (dist > maxRadius) {{
  1743. const scale = maxRadius / dist;
  1744. node.x = centerX + dx * scale;
  1745. node.y = centerY + dy * scale;
  1746. // 阻止继续向外运动
  1747. const angle = Math.atan2(dy, dx);
  1748. const vOutward = node.vx * Math.cos(angle) + node.vy * Math.sin(angle);
  1749. if (vOutward > 0) {{
  1750. node.vx -= vOutward * Math.cos(angle);
  1751. node.vy -= vOutward * Math.sin(angle);
  1752. }}
  1753. }}
  1754. }});
  1755. }}
  1756. force.initialize = function(_) {{
  1757. nodes = _;
  1758. }};
  1759. return force;
  1760. }}
  1761. // 层内圆形布局力(让同层节点围绕圆心分布)
  1762. function forceCircularLayout(strength) {{
  1763. let nodes;
  1764. function force(alpha) {{
  1765. // 按层分组(三层)
  1766. const layerNodes = {{0: [], 1: [], 2: []}};
  1767. nodes.forEach(node => {{
  1768. const layer = getNodeLayer(node);
  1769. if (layerNodes[layer]) layerNodes[layer].push(node);
  1770. }});
  1771. // 对每层计算布局
  1772. Object.entries(layerNodes).forEach(([layerIdx, layerGroup]) => {{
  1773. if (layerGroup.length === 0) return;
  1774. const layer = parseInt(layerIdx);
  1775. const centerX = layerCenterX[layer];
  1776. const centerY = layerCenterY[layer];
  1777. // 使用圆形布局
  1778. const nodeRadius = layerRadius[layer] - 20;
  1779. if (layerGroup.length === 1) {{
  1780. // 单个节点放在圆心
  1781. const node = layerGroup[0];
  1782. node.vx += (centerX - node.x) * strength * alpha;
  1783. node.vy += (centerY - node.y) * strength * alpha;
  1784. return;
  1785. }}
  1786. // 按角度排序节点(保持相对位置稳定)
  1787. layerGroup.forEach(node => {{
  1788. node._angle = Math.atan2(node.y - centerY, node.x - centerX);
  1789. }});
  1790. layerGroup.sort((a, b) => a._angle - b._angle);
  1791. // 均匀分布在圆周上
  1792. const angleStep = (2 * Math.PI) / layerGroup.length;
  1793. layerGroup.forEach((node, i) => {{
  1794. const angle = -Math.PI / 2 + i * angleStep; // 从顶部开始
  1795. const idealX = centerX + nodeRadius * Math.cos(angle);
  1796. const idealY = centerY + nodeRadius * Math.sin(angle);
  1797. node.vx += (idealX - node.x) * strength * alpha;
  1798. node.vy += (idealY - node.y) * strength * alpha;
  1799. }});
  1800. }});
  1801. }}
  1802. force.initialize = function(_) {{
  1803. nodes = _;
  1804. }};
  1805. return force;
  1806. }}
  1807. // 力导向模拟
  1808. simulation = d3.forceSimulation(nodes)
  1809. // 连线力(跨层连接)
  1810. .force("link", d3.forceLink(links).id(d => d.id)
  1811. .distance(d => {{
  1812. // 跨层连线距离
  1813. if (d.type.startsWith("匹配_") || d.type === "属于") {{
  1814. return 150; // 跨层边
  1815. }}
  1816. return 60; // 同层边
  1817. }})
  1818. .strength(d => {{
  1819. // 跨层边力度弱一些,不要拉扯节点出层
  1820. if (d.type.startsWith("匹配_") || d.type === "属于") {{
  1821. return 0.03;
  1822. }}
  1823. return 0.1;
  1824. }}))
  1825. // X方向:轻微拉向各层中心
  1826. .force("x", d3.forceX(d => getNodeBaseX(d)).strength(0.02))
  1827. // Y方向:轻微拉向层中心
  1828. .force("y", d3.forceY(d => getNodeBaseY(d)).strength(0.02))
  1829. // 层内碰撞检测
  1830. .force("collision", d3.forceCollide().radius(30))
  1831. // 层内排斥力(同层节点相互排斥)
  1832. .force("intraLayer", forceIntraLayerRepulsion(0.8))
  1833. // 层内布局(圆形或树状)
  1834. .force("circularLayout", forceCircularLayout(0.15))
  1835. // 层边界约束(节点不能跑出层,硬约束)
  1836. .force("boundary", forceLayerBoundary());
  1837. // 边类型到CSS类的映射
  1838. const edgeTypeClass = {{
  1839. "匹配_相同": "match-same",
  1840. "匹配_相似": "match-similar",
  1841. "分类共现(跨点)": "category-cross",
  1842. "分类共现(点内)": "category-intra",
  1843. "标签共现": "tag-cooccur",
  1844. "属于": "belong",
  1845. "包含": "contain",
  1846. // 镜像边(帖子节点之间,虚线)
  1847. "镜像_分类共现(跨点)": "mirror-category-cross",
  1848. "镜像_分类共现(点内)": "mirror-category-intra",
  1849. "镜像_标签共现": "mirror-tag-cooccur",
  1850. "镜像_属于": "mirror-belong",
  1851. "镜像_包含": "mirror-contain"
  1852. }};
  1853. // 获取边的CSS类(处理二阶边,映射到对应的镜像边样式)
  1854. function getEdgeClass(edgeType) {{
  1855. if (edgeTypeClass[edgeType]) return edgeTypeClass[edgeType];
  1856. // 二阶边映射到对应的镜像边样式(颜色相同,都用虚线)
  1857. if (edgeType.startsWith("二阶_")) {{
  1858. const originalType = edgeType.replace("二阶_", "");
  1859. const mirrorType = "镜像_" + originalType;
  1860. if (edgeTypeClass[mirrorType]) return edgeTypeClass[mirrorType];
  1861. }}
  1862. return "match";
  1863. }}
  1864. // ===== 右侧:帖子树(上半部分) + 三分图(下半部分) =====
  1865. const postDetail = data.postDetail || {{}};
  1866. window.currentPostDetail = postDetail;
  1867. // 使用预构建的帖子树数据
  1868. const postTree = data.postTree || {{ root: null }};
  1869. // 容器
  1870. const postTreeGroup = g.append("g").attr("class", "post-tree");
  1871. let postTreeActualHeight = 0;
  1872. let postRoot = null;
  1873. // 卡片尺寸
  1874. const cardWidth = 240;
  1875. const cardHeight = 90;
  1876. // 计算目标圆心Y坐标
  1877. const circleYOffsetPreview = 40;
  1878. const targetTagY = layerCenterY[0] + circleYOffsetPreview; // 帖子标签圆心
  1879. const targetPersonaY = layerCenterY[1] + circleYOffsetPreview; // 人设匹配_1层圆心
  1880. const targetExpandedY = layerCenterY[2] + circleYOffsetPreview; // 人设匹配_2层圆心
  1881. const circleGap = targetPersonaY - targetTagY;
  1882. const halfGap = circleGap / 2;
  1883. // 树放在圆的右侧
  1884. const circleRightEdge = circleAreaCenterX + unifiedRadius;
  1885. const treeGap = 120;
  1886. // 记录标签节点的位置(用于下方图的对齐)
  1887. const tagNodePositions = {{}};
  1888. if (postTree && postTree.root) {{
  1889. // D3树布局(只用于帖子→维度→点→标签)
  1890. // separation 根据节点名称长度动态计算
  1891. const postTreeLayout = d3.tree()
  1892. .nodeSize([50, 80])
  1893. .separation((a, b) => {{
  1894. const nameA = a.data.name || '';
  1895. const nameB = b.data.name || '';
  1896. const charWidth = 9;
  1897. const baseGap = 30;
  1898. // 根据两个节点的文字长度计算间距
  1899. const widthA = nameA.length * charWidth / 2;
  1900. const widthB = nameB.length * charWidth / 2;
  1901. const minSep = (widthA + widthB + baseGap) / 50; // 除以 nodeSize[0]
  1902. const defaultSep = a.parent === b.parent ? 1.2 : 1.5;
  1903. return Math.max(minSep, defaultSep);
  1904. }});
  1905. // 过滤掉人设节点,只保留树结构
  1906. function filterTreeData(node) {{
  1907. const filtered = {{ ...node }};
  1908. if (node.children) {{
  1909. filtered.children = node.children
  1910. .filter(c => c.nodeType !== "人设" && c.nodeType !== "人设扩展")
  1911. .map(c => filterTreeData(c));
  1912. }}
  1913. return filtered;
  1914. }}
  1915. const treeOnlyData = filterTreeData(postTree.root);
  1916. postRoot = d3.hierarchy(treeOnlyData);
  1917. postTreeLayout(postRoot);
  1918. // 计算树的边界
  1919. let treeMinX = Infinity, treeMaxX = -Infinity;
  1920. postRoot.descendants().forEach(d => {{
  1921. treeMinX = Math.min(treeMinX, d.x);
  1922. treeMaxX = Math.max(treeMaxX, d.x);
  1923. }});
  1924. // 重新分配Y坐标(前3层层高是后面的一半)
  1925. postRoot.descendants().forEach(d => {{
  1926. if (d.data.isRoot) {{
  1927. d.y = targetTagY - halfGap * 3;
  1928. }} else if (d.data.isDimension) {{
  1929. d.y = targetTagY - halfGap * 2;
  1930. }} else if (d.data.nodeType === "点") {{
  1931. d.y = targetTagY - halfGap;
  1932. }} else if (d.data.nodeType === "标签") {{
  1933. d.y = targetTagY;
  1934. // 记录标签节点位置(同一个ID可能有多个位置)
  1935. // 保存 d 的引用,以便后续 spreadTagPositions 可以更新节点位置
  1936. if (!tagNodePositions[d.data.id]) {{
  1937. tagNodePositions[d.data.id] = [];
  1938. }}
  1939. tagNodePositions[d.data.id].push({{ x: d.x, y: d.y, data: d.data, node: d }});
  1940. }}
  1941. }});
  1942. // 计算偏移
  1943. const postTreeOffsetX = circleRightEdge + treeGap - treeMinX;
  1944. const postTreeOffsetY = 0;
  1945. // 六边形路径
  1946. function hexagonPath(r) {{
  1947. const a = Math.PI / 3;
  1948. let path = "";
  1949. for (let i = 0; i < 6; i++) {{
  1950. const angle = a * i - Math.PI / 2;
  1951. const x = r * Math.cos(angle);
  1952. const y = r * Math.sin(angle);
  1953. path += (i === 0 ? "M" : "L") + x + "," + y;
  1954. }}
  1955. return path + "Z";
  1956. }}
  1957. // 绘制树的边(帖子→维度→点→标签)
  1958. const treeLinks = postTreeGroup.selectAll(".tree-link")
  1959. .data(postRoot.links())
  1960. .enter()
  1961. .append("path")
  1962. .attr("class", "tree-link")
  1963. .attr("d", d => {{
  1964. const sourceY = d.source.data.isRoot ? d.source.y + cardHeight/2 : d.source.y;
  1965. return `M${{d.source.x}},${{sourceY}}
  1966. C${{d.source.x}},${{(sourceY + d.target.y) / 2}}
  1967. ${{d.target.x}},${{(sourceY + d.target.y) / 2}}
  1968. ${{d.target.x}},${{d.target.y}}`;
  1969. }})
  1970. .attr("fill", "none")
  1971. .attr("stroke", "#9b59b6")
  1972. .attr("stroke-width", 1.5)
  1973. .attr("stroke-opacity", 0.6);
  1974. // 绘制树节点(非根节点)
  1975. const treeNodes = postTreeGroup.selectAll(".tree-node")
  1976. .data(postRoot.descendants().filter(d => !d.data.isRoot))
  1977. .enter()
  1978. .append("g")
  1979. .attr("class", "tree-node")
  1980. .attr("transform", d => `translate(${{d.x}},${{d.y}})`);
  1981. // 节点形状
  1982. treeNodes.each(function(d) {{
  1983. const node = d3.select(this);
  1984. const fill = d.data.dimColor || "#888";
  1985. if (d.data.nodeType === "点") {{
  1986. node.append("path")
  1987. .attr("d", hexagonPath(16))
  1988. .attr("fill", fill)
  1989. .attr("stroke", "#fff")
  1990. .attr("stroke-width", 2);
  1991. }} else if (d.data.isDimension) {{
  1992. node.append("circle")
  1993. .attr("r", 14)
  1994. .attr("fill", fill)
  1995. .attr("stroke", "#fff")
  1996. .attr("stroke-width", 2);
  1997. }} else if (d.data.nodeType === "标签") {{
  1998. node.append("circle")
  1999. .attr("r", 12)
  2000. .attr("fill", fill)
  2001. .attr("stroke", "#fff")
  2002. .attr("stroke-width", 2);
  2003. }} else {{
  2004. node.append("circle")
  2005. .attr("r", 8)
  2006. .attr("fill", fill)
  2007. .attr("stroke", "#fff")
  2008. .attr("stroke-width", 1);
  2009. }}
  2010. }});
  2011. // 节点标签
  2012. treeNodes.append("text")
  2013. .attr("dy", d => {{
  2014. if (d.data.isDimension) return -22;
  2015. if (d.data.nodeType === "点") return -24;
  2016. if (d.data.nodeType === "标签") return -20;
  2017. return -18;
  2018. }})
  2019. .attr("text-anchor", "middle")
  2020. .attr("fill", d => d.data.dimColor || "#ccc")
  2021. .attr("font-size", "11px")
  2022. .attr("font-weight", d => d.data.isDimension ? "bold" : "normal")
  2023. .text(d => d.data.name || "");
  2024. // 绘制根节点卡片
  2025. const postRootNode = postRoot;
  2026. const cardX = postRootNode.x - cardWidth/2;
  2027. const cardY = postRootNode.y - cardHeight/2;
  2028. const rootCard = postTreeGroup.append("foreignObject")
  2029. .attr("x", cardX)
  2030. .attr("y", cardY)
  2031. .attr("width", cardWidth)
  2032. .attr("height", cardHeight);
  2033. const images = postDetail.images || [];
  2034. const thumbnail = images.length > 0 ? images[0] : "";
  2035. const title = postDetail.title || "未知标题";
  2036. const likeCount = postDetail.like_count || 0;
  2037. const collectCount = postDetail.collect_count || 0;
  2038. const imageCount = images.length || 0;
  2039. const thumbnailHtml = thumbnail
  2040. ? `<div class="post-card-thumbnail-wrapper" style="width:60px;height:60px;">
  2041. <img class="post-card-thumbnail" style="width:60px;height:60px;" src="${{thumbnail}}" alt="封面" onerror="this.style.display='none'"/>
  2042. ${{imageCount > 1 ? `<span class="post-card-image-count">${{imageCount}}图</span>` : ''}}
  2043. </div>`
  2044. : `<div class="post-card-thumbnail-placeholder" style="width:60px;height:60px;font-size:20px;">📝</div>`;
  2045. const cardHtml = `
  2046. <div class="post-card" xmlns="http://www.w3.org/1999/xhtml" style="padding:10px;" onclick="showPostDetail(window.currentPostDetail)">
  2047. <div class="post-card-header">
  2048. ${{thumbnailHtml}}
  2049. <div class="post-card-info">
  2050. <div class="post-card-title" style="font-size:12px;-webkit-line-clamp:2;" title="${{title}}">${{title}}</div>
  2051. <div class="post-card-stats" style="font-size:10px;">
  2052. <span>❤️ ${{likeCount}}</span>
  2053. <span>⭐ ${{collectCount}}</span>
  2054. </div>
  2055. </div>
  2056. </div>
  2057. </div>
  2058. `;
  2059. rootCard.append("xhtml:div").html(cardHtml);
  2060. // 应用树的位置变换
  2061. postTreeGroup.attr("transform", `translate(${{postTreeOffsetX}}, ${{postTreeOffsetY}})`);
  2062. // 更新标签节点位置(加上偏移)- 每个ID可能有多个位置
  2063. Object.keys(tagNodePositions).forEach(id => {{
  2064. tagNodePositions[id].forEach(pos => {{
  2065. pos.x += postTreeOffsetX;
  2066. }});
  2067. }});
  2068. // 对帖子标签层应用防重叠(展平后处理)
  2069. function spreadTagPositions(tagPositions, baseGap = 30, charWidth = 9) {{
  2070. // 展平所有标签位置
  2071. const allTags = [];
  2072. Object.entries(tagPositions).forEach(([id, posArray]) => {{
  2073. posArray.forEach((pos, idx) => {{
  2074. const name = pos.data ? (pos.data.name || '') : '';
  2075. allTags.push({{ id, idx, x: pos.x, y: pos.y, nameLen: name.length, pos }});
  2076. }});
  2077. }});
  2078. // 按y分层
  2079. const layers = {{}};
  2080. allTags.forEach(tag => {{
  2081. const y = tag.y;
  2082. if (!layers[y]) layers[y] = [];
  2083. layers[y].push(tag);
  2084. }});
  2085. // 对每层进行防重叠处理
  2086. Object.values(layers).forEach(layerTags => {{
  2087. if (layerTags.length < 2) return;
  2088. // 按x排序
  2089. layerTags.sort((a, b) => a.x - b.x);
  2090. // 多轮迭代
  2091. for (let iter = 0; iter < 5; iter++) {{
  2092. let hasOverlap = false;
  2093. for (let i = 1; i < layerTags.length; i++) {{
  2094. const prev = layerTags[i - 1];
  2095. const curr = layerTags[i];
  2096. const prevHalfWidth = (prev.nameLen * charWidth) / 2 + 10;
  2097. const currHalfWidth = (curr.nameLen * charWidth) / 2 + 10;
  2098. const minGap = prevHalfWidth + currHalfWidth + baseGap;
  2099. const gap = curr.x - prev.x;
  2100. if (gap < minGap) {{
  2101. hasOverlap = true;
  2102. const shift = (minGap - gap) / 2;
  2103. prev.x -= shift;
  2104. curr.x += shift;
  2105. // 更新原始位置
  2106. prev.pos.x = prev.x;
  2107. curr.pos.x = curr.x;
  2108. // 同步更新节点对象的 x(用于后续更新 DOM 位置)
  2109. if (prev.pos.node) prev.pos.node.x = prev.x - postTreeOffsetX;
  2110. if (curr.pos.node) curr.pos.node.x = curr.x - postTreeOffsetX;
  2111. }}
  2112. }}
  2113. if (!hasOverlap) break;
  2114. }}
  2115. }});
  2116. }}
  2117. spreadTagPositions(tagNodePositions, 25, 9);
  2118. // 更新标签节点的 DOM 位置(根据 spreadTagPositions 调整后的 d.x)
  2119. treeNodes.filter(d => d.data.nodeType === "标签")
  2120. .attr("transform", d => `translate(${{d.x}},${{d.y}})`);
  2121. // 更新树边的路径(因为标签节点位置可能变了)
  2122. treeLinks.attr("d", d => {{
  2123. const sourceY = d.source.data.isRoot ? d.source.y + cardHeight/2 : d.source.y;
  2124. return `M${{d.source.x}},${{sourceY}}
  2125. C${{d.source.x}},${{(sourceY + d.target.y) / 2}}
  2126. ${{d.target.x}},${{(sourceY + d.target.y) / 2}}
  2127. ${{d.target.x}},${{d.target.y}}`;
  2128. }});
  2129. // ===== 下半部分:三分图(标签 ↔ 人设_1层 ↔ 人设_2层)=====
  2130. // 复用圆形图的节点数据,但只取人设节点(去重)
  2131. const personaLayer1Nodes = nodes.filter(n => getNodeLayer(n) === 1);
  2132. const personaLayer2Nodes = nodes.filter(n => getNodeLayer(n) === 2);
  2133. // 过滤出层间边
  2134. const crossLayerLinks = links.filter(link => {{
  2135. const srcLayer = getNodeLayer(link.source);
  2136. const tgtLayer = getNodeLayer(link.target);
  2137. if (srcLayer === tgtLayer) return false;
  2138. // 1-2层之间只显示"属于"边(从上到下),过滤掉"包含"边(从下到上)
  2139. if ((srcLayer === 1 && tgtLayer === 2) || (srcLayer === 2 && tgtLayer === 1)) {{
  2140. if (link.type === "包含") return false;
  2141. }}
  2142. return true;
  2143. }});
  2144. console.log("层间边数:", crossLayerLinks.length, "人设1层:", personaLayer1Nodes.length, "人设2层:", personaLayer2Nodes.length);
  2145. // 为人设节点计算X位置(根据连接的标签节点位置)
  2146. const personaNodePositions = {{}};
  2147. // 人设_1层:根据连接的帖子标签位置来定位
  2148. personaLayer1Nodes.forEach(n => {{
  2149. // 找到连接到这个人设的帖子标签
  2150. const connectedTags = crossLayerLinks
  2151. .filter(l => l.target.id === n.id && getNodeLayer(l.source) === 0)
  2152. .map(l => l.source.id);
  2153. let avgX = 0;
  2154. let count = 0;
  2155. connectedTags.forEach(tagId => {{
  2156. // 在树的标签节点中查找(每个tagId可能有多个位置)
  2157. if (tagNodePositions[tagId]) {{
  2158. tagNodePositions[tagId].forEach(pos => {{
  2159. avgX += pos.x;
  2160. count++;
  2161. }});
  2162. }}
  2163. }});
  2164. if (count > 0) {{
  2165. personaNodePositions[n.id] = {{ x: avgX / count, y: targetPersonaY, node: n }};
  2166. }} else {{
  2167. // 没有连接的标签,放在中间
  2168. const allTagX = Object.values(tagNodePositions).flatMap(arr => arr.map(t => t.x));
  2169. const midX = allTagX.length > 0 ? (Math.min(...allTagX) + Math.max(...allTagX)) / 2 : circleRightEdge + treeGap;
  2170. personaNodePositions[n.id] = {{ x: midX, y: targetPersonaY, node: n }};
  2171. }}
  2172. }});
  2173. // 人设_2层:根据连接的人设_1层位置来定位
  2174. personaLayer2Nodes.forEach(n => {{
  2175. const connectedPersona1 = crossLayerLinks
  2176. .filter(l => (l.target.id === n.id && getNodeLayer(l.source) === 1) ||
  2177. (l.source.id === n.id && getNodeLayer(l.target) === 1))
  2178. .map(l => l.source.id === n.id ? l.target.id : l.source.id);
  2179. let avgX = 0;
  2180. let count = 0;
  2181. connectedPersona1.forEach(pId => {{
  2182. if (personaNodePositions[pId]) {{
  2183. avgX += personaNodePositions[pId].x;
  2184. count++;
  2185. }}
  2186. }});
  2187. if (count > 0) {{
  2188. personaNodePositions[n.id] = {{ x: avgX / count, y: targetExpandedY, node: n }};
  2189. }} else {{
  2190. const allP1X = Object.values(personaNodePositions).filter(p => p.y === targetPersonaY).map(p => p.x);
  2191. const midX = allP1X.length > 0 ? (Math.min(...allP1X) + Math.max(...allP1X)) / 2 : circleRightEdge + treeGap;
  2192. personaNodePositions[n.id] = {{ x: midX, y: targetExpandedY, node: n }};
  2193. }}
  2194. }});
  2195. // 防重叠:分散同层中x坐标太近的节点(根据文字长度动态计算间距)
  2196. function spreadOverlappingNodes(positions, baseGap = 40, charWidth = 8) {{
  2197. // 按y分层
  2198. const layers = {{}};
  2199. Object.entries(positions).forEach(([id, pos]) => {{
  2200. const y = pos.y;
  2201. if (!layers[y]) layers[y] = [];
  2202. // 获取节点名称长度
  2203. const name = pos.node ? (pos.node.节点名称 || pos.node.name || '') : '';
  2204. layers[y].push({{ id, ...pos, nameLen: name.length }});
  2205. }});
  2206. // 对每层进行防重叠处理
  2207. Object.values(layers).forEach(layerNodes => {{
  2208. if (layerNodes.length < 2) return;
  2209. // 按x排序
  2210. layerNodes.sort((a, b) => a.x - b.x);
  2211. // 多轮迭代确保所有节点都不重叠
  2212. for (let iter = 0; iter < 5; iter++) {{
  2213. let hasOverlap = false;
  2214. for (let i = 1; i < layerNodes.length; i++) {{
  2215. const prev = layerNodes[i - 1];
  2216. const curr = layerNodes[i];
  2217. // 根据两个节点的文字长度计算最小间距
  2218. const prevHalfWidth = (prev.nameLen * charWidth) / 2 + 10;
  2219. const currHalfWidth = (curr.nameLen * charWidth) / 2 + 10;
  2220. const minGap = prevHalfWidth + currHalfWidth + baseGap;
  2221. const gap = curr.x - prev.x;
  2222. if (gap < minGap) {{
  2223. hasOverlap = true;
  2224. // 需要分散:向两侧推开
  2225. const shift = (minGap - gap) / 2;
  2226. prev.x -= shift;
  2227. curr.x += shift;
  2228. // 更新原始位置
  2229. positions[prev.id].x = prev.x;
  2230. positions[curr.id].x = curr.x;
  2231. }}
  2232. }}
  2233. if (!hasOverlap) break;
  2234. }}
  2235. }});
  2236. }}
  2237. // 对人设节点应用防重叠
  2238. spreadOverlappingNodes(personaNodePositions, 30, 9);
  2239. // 合并所有节点位置(标签 + 人设)
  2240. const allGraphNodePositions = {{}};
  2241. // 标签位置:取第一个位置用于合并(边绘制时会用所有位置)
  2242. Object.keys(tagNodePositions).forEach(id => {{
  2243. allGraphNodePositions[id] = tagNodePositions[id][0];
  2244. }});
  2245. Object.keys(personaNodePositions).forEach(id => {{
  2246. allGraphNodePositions[id] = personaNodePositions[id];
  2247. }});
  2248. // 边颜色配置
  2249. const graphEdgeColors = {{
  2250. "匹配_相同": "#e94560",
  2251. "匹配_相似": "#e94560",
  2252. "属于": "#9b59b6",
  2253. "包含": "#ffb6c1",
  2254. "分类共现(跨点)": "#2ecc71",
  2255. "分类共现(点内)": "#3498db",
  2256. "标签共现": "#f39c12"
  2257. }};
  2258. // 展开边数据:如果标签有多个位置,为每个位置创建一条边
  2259. // 边直接引用位置对象,绘制时动态获取 x, y
  2260. const expandedLinks = [];
  2261. crossLayerLinks.forEach(link => {{
  2262. const srcId = link.source.id;
  2263. const tgtId = link.target.id;
  2264. const srcLayer = getNodeLayer(link.source);
  2265. const tgtLayer = getNodeLayer(link.target);
  2266. // 源是层0(帖子标签),可能有多个位置
  2267. if (srcLayer === 0 && tagNodePositions[srcId]) {{
  2268. tagNodePositions[srcId].forEach((srcNode, idx) => {{
  2269. const tgtNode = personaNodePositions[tgtId];
  2270. if (tgtNode) {{
  2271. expandedLinks.push({{
  2272. ...link,
  2273. srcNode: srcNode, // 直接引用位置对象
  2274. tgtNode: tgtNode,
  2275. key: `${{srcId}}_${{idx}}_${{tgtId}}`
  2276. }});
  2277. }}
  2278. }});
  2279. }}
  2280. // 目标是层0(帖子标签),可能有多个位置
  2281. else if (tgtLayer === 0 && tagNodePositions[tgtId]) {{
  2282. tagNodePositions[tgtId].forEach((tgtNode, idx) => {{
  2283. const srcNode = personaNodePositions[srcId];
  2284. if (srcNode) {{
  2285. expandedLinks.push({{
  2286. ...link,
  2287. srcNode: srcNode,
  2288. tgtNode: tgtNode,
  2289. key: `${{srcId}}_${{tgtId}}_${{idx}}`
  2290. }});
  2291. }}
  2292. }});
  2293. }}
  2294. // 两端都不是层0,正常处理
  2295. else {{
  2296. const srcNode = personaNodePositions[srcId];
  2297. const tgtNode = personaNodePositions[tgtId];
  2298. if (srcNode && tgtNode) {{
  2299. expandedLinks.push({{
  2300. ...link,
  2301. srcNode: srcNode,
  2302. tgtNode: tgtNode,
  2303. key: `${{srcId}}_${{tgtId}}`
  2304. }});
  2305. }}
  2306. }}
  2307. }});
  2308. console.log("展开后边数:", expandedLinks.length);
  2309. // 绘制层间边(标签→人设、人设→人设扩展)
  2310. // 去重:同一对节点之间相同类型的边只保留一条
  2311. const seenEdges = new Set();
  2312. const dedupedLinks = expandedLinks.filter(link => {{
  2313. const srcId = link.source.id || link.source;
  2314. const tgtId = link.target.id || link.target;
  2315. const edgeKey = [srcId, tgtId].sort().join("|") + "|" + link.type;
  2316. if (seenEdges.has(edgeKey)) return false;
  2317. seenEdges.add(edgeKey);
  2318. return true;
  2319. }});
  2320. // 统计每对节点之间的边数,为多边分配不同曲线偏移
  2321. const edgePairCount = {{}};
  2322. const edgePairIndex = {{}};
  2323. dedupedLinks.forEach(link => {{
  2324. const srcId = link.source.id || link.source;
  2325. const tgtId = link.target.id || link.target;
  2326. const pairKey = [srcId, tgtId].sort().join("|");
  2327. edgePairCount[pairKey] = (edgePairCount[pairKey] || 0) + 1;
  2328. }});
  2329. dedupedLinks.forEach(link => {{
  2330. const srcId = link.source.id || link.source;
  2331. const tgtId = link.target.id || link.target;
  2332. const pairKey = [srcId, tgtId].sort().join("|");
  2333. if (!edgePairIndex[pairKey]) edgePairIndex[pairKey] = 0;
  2334. link._pairCount = edgePairCount[pairKey];
  2335. link._pairIndex = edgePairIndex[pairKey]++;
  2336. }});
  2337. const graphLinksGroup = g.append("g").attr("class", "graph-links");
  2338. const graphLinks = graphLinksGroup.selectAll(".graph-link")
  2339. .data(dedupedLinks)
  2340. .enter()
  2341. .append("g")
  2342. .attr("class", "graph-link-group");
  2343. graphLinks.append("path")
  2344. .attr("class", "graph-link")
  2345. .attr("d", d => {{
  2346. const src = d.srcNode;
  2347. const tgt = d.tgtNode;
  2348. if (!src || !tgt) return "";
  2349. // 如果只有一条边,用默认曲线
  2350. if (d._pairCount <= 1) {{
  2351. return `M${{src.x}},${{src.y}} C${{src.x}},${{(src.y + tgt.y) / 2}} ${{tgt.x}},${{(src.y + tgt.y) / 2}} ${{tgt.x}},${{tgt.y}}`;
  2352. }}
  2353. // 多条边时,根据索引计算水平偏移
  2354. const offsetStep = 25;
  2355. const totalOffset = (d._pairCount - 1) * offsetStep;
  2356. const offset = d._pairIndex * offsetStep - totalOffset / 2;
  2357. const midY = (src.y + tgt.y) / 2;
  2358. const midX = (src.x + tgt.x) / 2 + offset;
  2359. return `M${{src.x}},${{src.y}} Q${{midX}},${{midY}} ${{tgt.x}},${{tgt.y}}`;
  2360. }})
  2361. .attr("fill", "none")
  2362. .attr("stroke", d => graphEdgeColors[d.type] || "#9b59b6")
  2363. .attr("stroke-width", 1.5)
  2364. .attr("stroke-opacity", 0.6)
  2365. .attr("stroke-dasharray", d => d.type === "匹配_相似" ? "4,2" : "none");
  2366. // 在匹配边上显示相似度
  2367. graphLinks.filter(d => d.type && d.type.startsWith("匹配_") && d.similarity > 0)
  2368. .append("text")
  2369. .attr("x", d => (d.srcNode.x + d.tgtNode.x) / 2)
  2370. .attr("y", d => (d.srcNode.y + d.tgtNode.y) / 2)
  2371. .attr("dy", "0.35em")
  2372. .attr("text-anchor", "middle")
  2373. .attr("fill", "#fff")
  2374. .attr("font-size", "8px")
  2375. .attr("font-weight", "bold")
  2376. .style("text-shadow", "0 0 3px #e94560, 0 0 3px #e94560")
  2377. .text(d => d.similarity ? d.similarity.toFixed(2) : "");
  2378. // 绘制人设节点(去重后的)
  2379. const allPersonaNodes = [...personaLayer1Nodes, ...personaLayer2Nodes];
  2380. const graphNodesGroup = g.append("g").attr("class", "graph-nodes");
  2381. const graphNodes = graphNodesGroup.selectAll(".graph-node")
  2382. .data(allPersonaNodes.filter(n => personaNodePositions[n.id]))
  2383. .enter()
  2384. .append("g")
  2385. .attr("class", "graph-node")
  2386. .attr("transform", d => {{
  2387. const pos = personaNodePositions[d.id];
  2388. return `translate(${{pos.x}},${{pos.y}})`;
  2389. }})
  2390. .style("cursor", "pointer");
  2391. // 人设节点形状
  2392. graphNodes.each(function(d) {{
  2393. const node = d3.select(this);
  2394. const fill = levelColors[d.节点层级] || "#888";
  2395. const size = 10;
  2396. if (d.节点类型 === "分类") {{
  2397. node.append("rect")
  2398. .attr("width", size * 2)
  2399. .attr("height", size * 2)
  2400. .attr("x", -size)
  2401. .attr("y", -size)
  2402. .attr("fill", fill)
  2403. .attr("stroke", "#fff")
  2404. .attr("stroke-width", 2)
  2405. .attr("rx", 3);
  2406. }} else {{
  2407. node.append("circle")
  2408. .attr("r", size)
  2409. .attr("fill", fill)
  2410. .attr("stroke", "#fff")
  2411. .attr("stroke-width", 2);
  2412. }}
  2413. }});
  2414. // 人设节点标签
  2415. graphNodes.append("text")
  2416. .attr("dy", -18)
  2417. .attr("text-anchor", "middle")
  2418. .attr("fill", d => levelColors[d.节点层级] || "#ccc")
  2419. .attr("font-size", "11px")
  2420. .text(d => d.节点名称 || d.name || "");
  2421. // 点击联动
  2422. graphNodes.on("click", function(event, d) {{
  2423. event.stopPropagation();
  2424. nodeElements.classed("highlighted", n => n.id === d.id);
  2425. nodeElements.classed("dimmed", n => n.id !== d.id);
  2426. }});
  2427. // 存储引用
  2428. window.graphNodesRef = graphNodes;
  2429. window.allGraphNodePositions = allGraphNodePositions;
  2430. postTreeActualHeight = targetExpandedY - (targetTagY - halfGap * 3) + 100;
  2431. }} // end if (postTree && postTree.root)
  2432. // 计算高度
  2433. const tripartiteHeight = postTreeActualHeight;
  2434. // 圆的Y位置不再受帖子树高度影响,使用固定偏移
  2435. const circleYOffset = 40;
  2436. // 更新圆心Y坐标(三层)
  2437. layerCenterY[0] += circleYOffset;
  2438. layerCenterY[1] += circleYOffset;
  2439. layerCenterY[2] += circleYOffset;
  2440. // 更新SVG高度(取圆和三分图的最大高度)
  2441. const minHeight = Math.max(
  2442. layerCenterY[2] + layerRadius[2] + 50,
  2443. tripartiteHeight + 150
  2444. );
  2445. svg.attr("height", Math.max(height, minHeight));
  2446. // 绘制层背景(圆形,使用动态大小)
  2447. const layerBg = g.append("g").attr("class", "layer-backgrounds");
  2448. // 层配置:名称、颜色(三层圆)
  2449. const layerConfig = [
  2450. {{ name: "帖子标签", layer: 0, color: "rgba(52, 152, 219, 0.08)", stroke: "rgba(52, 152, 219, 0.3)" }},
  2451. {{ name: "人设匹配_1层", layer: 1, color: "rgba(155, 89, 182, 0.08)", stroke: "rgba(155, 89, 182, 0.3)" }},
  2452. {{ name: "人设匹配_2层", layer: 2, color: "rgba(46, 204, 113, 0.08)", stroke: "rgba(46, 204, 113, 0.3)" }}
  2453. ];
  2454. // 绘制三层圆形背景
  2455. layerConfig.forEach(cfg => {{
  2456. const cx = layerCenterX[cfg.layer];
  2457. const cy = layerCenterY[cfg.layer];
  2458. const r = layerRadius[cfg.layer];
  2459. layerBg.append("circle")
  2460. .attr("cx", cx)
  2461. .attr("cy", cy)
  2462. .attr("r", r)
  2463. .attr("fill", cfg.color)
  2464. .attr("stroke", cfg.stroke)
  2465. .attr("stroke-width", 2);
  2466. // 层标签(圆的左侧)
  2467. layerBg.append("text")
  2468. .attr("x", cx - r - 15)
  2469. .attr("y", cy)
  2470. .attr("dy", "0.35em")
  2471. .attr("fill", "rgba(255,255,255,0.5)")
  2472. .attr("font-size", "13px")
  2473. .attr("font-weight", "bold")
  2474. .attr("text-anchor", "end")
  2475. .text(cfg.name);
  2476. }});
  2477. // 绘制左侧人设树(在独立的treeSvg中)
  2478. const dimColors = {{ "灵感点": "#f39c12", "目的点": "#3498db", "关键点": "#9b59b6" }};
  2479. // 更新树SVG高度
  2480. treeSvg.attr("height", treeHeight + 50);
  2481. const treeGroup = treeG.append("g")
  2482. .attr("class", "persona-tree")
  2483. .attr("transform", `translate(15, 25)`);
  2484. // 设置关系图SVG
  2485. egoG.selectAll("*").remove();
  2486. const egoDisplayRadius = 180;
  2487. const egoCenterGroup = egoG.append("g")
  2488. .attr("class", "ego-center")
  2489. .attr("transform", `translate(200, 210)`);
  2490. // 关系图内容组
  2491. egoCenterGroup.append("g")
  2492. .attr("class", "ego-graph-content");
  2493. // D3树布局 - 宽度留出边距给标签
  2494. const treeLayout = d3.tree()
  2495. .size([treeHeight - 50, treeAreaWidth - 70]);
  2496. const root = d3.hierarchy(personaTree.root);
  2497. treeLayout(root);
  2498. // 获取节点颜色(根据维度)
  2499. function getNodeColor(d) {{
  2500. if (d.data.isRoot) return "#e94560"; // 根节点红色
  2501. if (d.data.isDimension) return d.data.dimColor; // 维度节点用维度颜色
  2502. return d.data.dimColor || "#888"; // 分类节点继承维度颜色
  2503. }}
  2504. // 构建节点ID到D3节点的映射(用于绘制原始边和高亮)
  2505. const treeNodeById = {{}};
  2506. root.descendants().forEach(d => {{
  2507. if (d.data.节点ID) {{
  2508. treeNodeById[d.data.节点ID] = d;
  2509. }}
  2510. }});
  2511. // 边类型颜色和样式
  2512. const treeEdgeColors = {{
  2513. "分类层级": "#2ecc71", // 绿色 - 分类的层级关系
  2514. "属于": "#9b59b6", // 紫色 - 标签属于分类
  2515. "包含": "#ffb6c1", // 淡粉 - 分类包含标签(向下)
  2516. "分类共现(跨点)": "#2ecc71", // 绿色 - 跨帖子分类共现
  2517. "分类共现(点内)": "#3498db", // 蓝色 - 同帖子分类共现
  2518. "标签共现": "#f39c12" // 橙色 - 标签共现
  2519. }};
  2520. const treeEdgeDash = {{
  2521. "分类层级": "none",
  2522. "属于": "3,2",
  2523. "包含": "3,2",
  2524. "分类共现(跨点)": "5,3",
  2525. "分类共现(点内)": "5,3",
  2526. "标签共现": "2,2"
  2527. }};
  2528. // 只用D3树布局的链接作为树边(避免重复)
  2529. const visibleTreeEdges = root.links().map(link => ({{
  2530. 源节点ID: link.source.data.节点ID || link.source.data.name,
  2531. 目标节点ID: link.target.data.节点ID || link.target.data.name,
  2532. 边类型: "属于",
  2533. isTreeLink: true,
  2534. sourceNode: link.source,
  2535. targetNode: link.target
  2536. }}));
  2537. // 生成树边路径的函数
  2538. function treeEdgePath(d) {{
  2539. const source = d.sourceNode;
  2540. const target = d.targetNode;
  2541. if (!source || !target) return "";
  2542. const midX = (source.y + target.y) / 2;
  2543. return `M${{source.y}},${{source.x}} C${{midX}},${{source.x}} ${{midX}},${{target.x}} ${{target.y}},${{target.x}}`;
  2544. }}
  2545. // 绘制原始边(只有属于边)
  2546. const treeEdgeGroup = treeGroup.append("g").attr("class", "tree-edges");
  2547. // 先绘制可见边(只有属于边)
  2548. const treeEdges = treeEdgeGroup.selectAll(".tree-edge")
  2549. .data(visibleTreeEdges)
  2550. .join("path")
  2551. .attr("class", "tree-edge")
  2552. .attr("fill", "none")
  2553. .attr("stroke", "#9b59b6") // 属于边用紫色
  2554. .attr("stroke-opacity", 0.3)
  2555. .attr("stroke-width", 1)
  2556. .attr("d", treeEdgePath);
  2557. // 绘制透明的热区边(便于点击)
  2558. const treeEdgeHitareas = treeEdgeGroup.selectAll(".tree-edge-hitarea")
  2559. .data(visibleTreeEdges)
  2560. .join("path")
  2561. .attr("class", "tree-edge-hitarea")
  2562. .attr("fill", "none")
  2563. .attr("stroke", "transparent")
  2564. .attr("stroke-width", 12)
  2565. .style("cursor", "pointer")
  2566. .attr("d", treeEdgePath)
  2567. .on("click", (event, d) => {{
  2568. event.stopPropagation();
  2569. // 调用共享的边点击处理函数
  2570. handleEdgeClick(d.源节点ID, d.目标节点ID, d.边类型);
  2571. }});
  2572. // 绘制节点
  2573. const treeNodes = treeGroup.selectAll(".tree-node")
  2574. .data(root.descendants())
  2575. .join("g")
  2576. .attr("class", "tree-node")
  2577. .attr("transform", d => `translate(${{d.y}},${{d.x}})`)
  2578. .style("cursor", "pointer")
  2579. .on("click", (event, d) => {{
  2580. event.stopPropagation();
  2581. // 调用共享的节点点击处理函数
  2582. handleNodeClick(d.data.节点ID, d.data.节点名称 || d.data.name);
  2583. }})
  2584. .on("mouseenter", (event, d) => {{
  2585. // 悬停高亮:在关系图中高亮到激活节点的路径
  2586. if (!currentEgoCenterNodeId) return;
  2587. const hoveredNodeId = d.data.节点ID;
  2588. if (!hoveredNodeId || hoveredNodeId === currentEgoCenterNodeId) return;
  2589. highlightPathInEgoGraph(hoveredNodeId);
  2590. }})
  2591. .on("mouseleave", (event, d) => {{
  2592. // 移出时恢复关系图
  2593. if (!currentEgoCenterNodeId) return;
  2594. resetEgoGraphHighlight();
  2595. }});
  2596. // 节点形状:根节点/维度=圆形,分类=正方形,标签=圆形
  2597. // 统一实心填充维度颜色
  2598. treeNodes.each(function(d) {{
  2599. const el = d3.select(this);
  2600. const nodeType = d.data.节点类型;
  2601. const isRoot = d.data.isRoot;
  2602. const isDimension = d.data.isDimension;
  2603. const nodeColor = getNodeColor(d);
  2604. if (nodeType === "分类") {{
  2605. // 分类节点:正方形,实心填充
  2606. el.append("rect")
  2607. .attr("class", "tree-shape")
  2608. .attr("x", -4)
  2609. .attr("y", -4)
  2610. .attr("width", 8)
  2611. .attr("height", 8)
  2612. .attr("rx", 1)
  2613. .attr("fill", nodeColor)
  2614. .attr("stroke", "rgba(255,255,255,0.5)")
  2615. .attr("stroke-width", 1);
  2616. }} else {{
  2617. // 根节点、维度节点、标签节点:圆形,实心填充
  2618. const radius = isRoot ? 6 : (isDimension ? 5 : 3);
  2619. el.append("circle")
  2620. .attr("class", "tree-shape")
  2621. .attr("r", radius)
  2622. .attr("fill", nodeColor)
  2623. .attr("stroke", "rgba(255,255,255,0.5)")
  2624. .attr("stroke-width", 1);
  2625. }}
  2626. }});
  2627. // 节点标签
  2628. treeNodes.append("text")
  2629. .attr("dy", "0.31em")
  2630. .attr("x", d => d.children ? -8 : 8)
  2631. .attr("text-anchor", d => d.children ? "end" : "start")
  2632. .attr("fill", d => (d.data.isRoot || d.data.isDimension) ? getNodeColor(d) : "#bbb")
  2633. .attr("font-size", d => d.data.isRoot ? "11px" : (d.data.isDimension ? "10px" : "8px"))
  2634. .attr("font-weight", d => (d.data.isRoot || d.data.isDimension) ? "bold" : "normal")
  2635. .text(d => d.data.name);
  2636. // 重置树高亮状态的函数
  2637. function resetTreeHighlight() {{
  2638. treeGroup.selectAll(".tree-node")
  2639. .classed("tree-dimmed", false)
  2640. .classed("tree-highlighted", false);
  2641. // 重置所有形状(圆形和方形)- 统一实心填充
  2642. treeGroup.selectAll(".tree-node .tree-shape")
  2643. .attr("fill", d => getNodeColor(d))
  2644. .attr("stroke", "rgba(255,255,255,0.5)")
  2645. .attr("stroke-opacity", 1)
  2646. .attr("opacity", 1);
  2647. treeGroup.selectAll(".tree-node text")
  2648. .attr("fill", d => (d.data.isRoot || d.data.isDimension) ? getNodeColor(d) : "#bbb")
  2649. .attr("opacity", 1);
  2650. // 重置边样式
  2651. treeGroup.selectAll(".tree-edge")
  2652. .attr("stroke-opacity", 0.3)
  2653. .attr("stroke-width", 1);
  2654. }}
  2655. // 重置右侧图高亮状态的函数
  2656. function resetGraphHighlight() {{
  2657. g.selectAll(".node").classed("dimmed", false).classed("highlighted", false);
  2658. g.selectAll(".link-group").classed("dimmed", false).classed("highlighted", false);
  2659. }}
  2660. // 点击树SVG背景取消高亮
  2661. treeSvg.on("click", function(event) {{
  2662. if (event.target === this) {{
  2663. resetTreeHighlight();
  2664. resetGraphHighlight();
  2665. clearEgoGraph();
  2666. closeDetailPanel();
  2667. }}
  2668. }});
  2669. // 创建边的容器
  2670. const linkGroup = g.append("g").attr("class", "links");
  2671. // 为每条边创建组
  2672. const linkG = linkGroup.selectAll("g")
  2673. .data(links)
  2674. .join("g")
  2675. .attr("class", "link-group");
  2676. // 绘制点击热区(透明宽线)
  2677. const linkHitarea = linkG.append("line")
  2678. .attr("class", "link-hitarea");
  2679. // 绘制可见的边
  2680. const link = linkG.append("line")
  2681. .attr("class", d => "link " + getEdgeClass(d.type))
  2682. .attr("stroke-width", d => d.type.startsWith("匹配_") ? 2.5 : 1.5);
  2683. // 判断是否为跨层边(根据源和目标节点的层级)- 赋值给全局变量
  2684. isCrossLayerEdge = function(d) {{
  2685. const sourceNode = typeof d.source === "object" ? d.source : nodes.find(n => n.id === d.source);
  2686. const targetNode = typeof d.target === "object" ? d.target : nodes.find(n => n.id === d.target);
  2687. if (!sourceNode || !targetNode) return false;
  2688. return getNodeLayer(sourceNode) !== getNodeLayer(targetNode);
  2689. }};
  2690. // 设置跨层边的初始可见性(默认全部隐藏)
  2691. linkG.each(function(d) {{
  2692. if (d.type.startsWith("匹配_")) {{
  2693. d3.select(this).style("display", "none"); // 匹配边默认隐藏
  2694. }} else if (isCrossLayerEdge(d) && !showCrossLayerEdges) {{
  2695. d3.select(this).style("display", "none");
  2696. }}
  2697. }});
  2698. // 为匹配边添加分数标签
  2699. const edgeLabels = linkG.filter(d => d.type.startsWith("匹配_") && d.边详情 && d.边详情.相似度)
  2700. .append("g")
  2701. .attr("class", "edge-label-group");
  2702. edgeLabels.append("rect")
  2703. .attr("class", "edge-label-bg")
  2704. .attr("rx", 3)
  2705. .attr("ry", 3);
  2706. edgeLabels.append("text")
  2707. .attr("class", "edge-label")
  2708. .text(d => {{
  2709. const score = d.边详情.相似度;
  2710. return typeof score === "number" ? score.toFixed(2) : score;
  2711. }});
  2712. // 边的点击事件
  2713. linkHitarea.on("click", (event, d, i) => {{
  2714. event.stopPropagation();
  2715. const linkIndex = links.indexOf(d);
  2716. // 1. 力导向图高亮(highlightEdge 处理所有路径高亮逻辑)
  2717. highlightEdge(d, linkIndex);
  2718. showEdgeInfo(d);
  2719. // 2. 确定要在人设树和关系图中展示的人设节点路径
  2720. const edgeDetail = d.边详情 || {{}};
  2721. const isMirrorEdge = d.type.startsWith("镜像_") || d.type.startsWith("二阶_");
  2722. let personaPathNodes = [];
  2723. let edgeType;
  2724. if (isMirrorEdge && edgeDetail.路径节点) {{
  2725. // 镜像边/二阶边:从路径节点中提取人设节点(不以帖子_开头的)
  2726. personaPathNodes = edgeDetail.路径节点.filter(id => !id.startsWith("帖子_"));
  2727. edgeType = edgeDetail.原始边类型 || d.type.replace("镜像_", "").replace("二阶_", "");
  2728. }} else {{
  2729. // 普通边:使用边的两端节点
  2730. const sourceNode = typeof d.source === "object" ? d.source : nodes.find(n => n.id === d.source);
  2731. const targetNode = typeof d.target === "object" ? d.target : nodes.find(n => n.id === d.target);
  2732. const srcId = sourceNode ? sourceNode.id : d.source;
  2733. const tgtId = targetNode ? targetNode.id : d.target;
  2734. // 只有人设节点才加入路径
  2735. if (!srcId.startsWith("帖子_")) personaPathNodes.push(srcId);
  2736. if (!tgtId.startsWith("帖子_")) personaPathNodes.push(tgtId);
  2737. edgeType = d.type;
  2738. }}
  2739. // 3. 同步人设树高亮和关系图展示
  2740. syncTreeAndRelationGraph(personaPathNodes, edgeType);
  2741. }})
  2742. .on("mouseover", function(event, d) {{
  2743. d3.select(this.parentNode).select(".link")
  2744. .attr("stroke-opacity", 1)
  2745. .attr("stroke-width", 4);
  2746. }})
  2747. .on("mouseout", function(event, d) {{
  2748. d3.select(this.parentNode).select(".link")
  2749. .attr("stroke-opacity", 0.7)
  2750. .attr("stroke-width", d.type.startsWith("匹配_") ? 2.5 : 1.5);
  2751. }});
  2752. // 绘制节点
  2753. const node = g.append("g")
  2754. .selectAll("g")
  2755. .data(nodes)
  2756. .join("g")
  2757. .attr("class", "node")
  2758. .call(d3.drag()
  2759. .on("start", dragstarted)
  2760. .on("drag", dragged)
  2761. .on("end", dragended));
  2762. // 根据节点类型绘制不同形状
  2763. // - 点节点(帖子点):六边形
  2764. // - 标签节点:圆形
  2765. // - 分类节点:方形
  2766. // 帖子标签用虚线,人设标签用实线
  2767. node.each(function(d) {{
  2768. const el = d3.select(this);
  2769. const isPointNode = d.节点类型 === "点";
  2770. const isPostNode = d.source === "帖子";
  2771. // 节点大小
  2772. let size;
  2773. if (isPointNode) {{
  2774. size = 16; // 点节点最大
  2775. }} else if (isPostNode) {{
  2776. size = 12; // 帖子标签
  2777. }} else {{
  2778. size = 10; // 人设标签
  2779. }}
  2780. const fill = levelColors[d.level] || "#666";
  2781. const nodeClass = isPostNode
  2782. ? (isPointNode ? "post-point-node" : "post-node")
  2783. : "persona-node";
  2784. if (isPointNode) {{
  2785. // 六边形(点节点)
  2786. const hexPoints = [];
  2787. for (let i = 0; i < 6; i++) {{
  2788. const angle = (i * 60 - 30) * Math.PI / 180;
  2789. hexPoints.push([size * Math.cos(angle), size * Math.sin(angle)]);
  2790. }}
  2791. el.append("polygon")
  2792. .attr("points", hexPoints.map(p => p.join(",")).join(" "))
  2793. .attr("fill", fill)
  2794. .attr("class", nodeClass);
  2795. }} else if (d.节点类型 === "分类") {{
  2796. // 方形(分类节点)
  2797. el.append("rect")
  2798. .attr("width", size * 2)
  2799. .attr("height", size * 2)
  2800. .attr("x", -size)
  2801. .attr("y", -size)
  2802. .attr("fill", fill)
  2803. .attr("class", nodeClass)
  2804. .attr("rx", 3);
  2805. }} else {{
  2806. // 圆形(标签节点)
  2807. el.append("circle")
  2808. .attr("r", size)
  2809. .attr("fill", fill)
  2810. .attr("class", nodeClass);
  2811. }}
  2812. }});
  2813. const labels = node.append("text")
  2814. .attr("dx", 15)
  2815. .attr("dy", 4)
  2816. .text(d => d.节点名称)
  2817. .style("display", showLabels ? "block" : "none");
  2818. // 工具提示
  2819. const tooltip = d3.select("#tooltip");
  2820. node.on("mouseover", (event, d) => {{
  2821. let html = `<strong>${{d.节点名称}}</strong><br/>类型: ${{d.节点类型}}<br/>层级: ${{d.节点层级}}`;
  2822. // 点节点显示描述
  2823. if (d.描述) {{
  2824. html += `<br/><br/><em style="font-size:10px;color:#aaa">${{d.描述.slice(0, 100)}}${{d.描述.length > 100 ? '...' : ''}}</em>`;
  2825. }}
  2826. tooltip.style("display", "block").html(html);
  2827. }})
  2828. .on("mousemove", (event) => {{
  2829. tooltip.style("left", (event.pageX + 15) + "px")
  2830. .style("top", (event.pageY - 10) + "px");
  2831. }})
  2832. .on("mouseout", () => {{
  2833. tooltip.style("display", "none");
  2834. }})
  2835. .on("click", (event, d) => {{
  2836. event.stopPropagation();
  2837. highlightNode(d);
  2838. showNodeInfo(d);
  2839. // 人设节点联动:高亮人设树 + 显示关系图
  2840. if (d.source === "人设") {{
  2841. handleNodeClick(d.节点ID, d.节点名称);
  2842. }}
  2843. }});
  2844. // 更新位置
  2845. simulation.on("tick", () => {{
  2846. // 更新热区线
  2847. linkHitarea
  2848. .attr("x1", d => d.source.x)
  2849. .attr("y1", d => d.source.y)
  2850. .attr("x2", d => d.target.x)
  2851. .attr("y2", d => d.target.y);
  2852. // 更新可见边
  2853. link
  2854. .attr("x1", d => d.source.x)
  2855. .attr("y1", d => d.source.y)
  2856. .attr("x2", d => d.target.x)
  2857. .attr("y2", d => d.target.y);
  2858. // 更新边标签位置(放在边的中点)
  2859. edgeLabels.attr("transform", d => {{
  2860. const midX = (d.source.x + d.target.x) / 2;
  2861. const midY = (d.source.y + d.target.y) / 2;
  2862. return `translate(${{midX}},${{midY}})`;
  2863. }});
  2864. // 更新标签背景大小
  2865. edgeLabels.each(function(d) {{
  2866. const textEl = d3.select(this).select("text").node();
  2867. if (textEl) {{
  2868. const bbox = textEl.getBBox();
  2869. d3.select(this).select("rect")
  2870. .attr("x", bbox.x - 3)
  2871. .attr("y", bbox.y - 1)
  2872. .attr("width", bbox.width + 6)
  2873. .attr("height", bbox.height + 2);
  2874. }}
  2875. }});
  2876. node.attr("transform", d => `translate(${{d.x}},${{d.y}})`);
  2877. }});
  2878. // 拖拽函数
  2879. function dragstarted(event, d) {{
  2880. if (!event.active) simulation.alphaTarget(0.3).restart();
  2881. d.fx = d.x;
  2882. d.fy = d.y;
  2883. }}
  2884. function dragged(event, d) {{
  2885. d.fx = event.x;
  2886. d.fy = event.y;
  2887. }}
  2888. function dragended(event, d) {{
  2889. if (!event.active) simulation.alphaTarget(0);
  2890. d.fx = null;
  2891. d.fy = null;
  2892. }}
  2893. // 清除所有高亮
  2894. function clearHighlight() {{
  2895. node.classed("dimmed", false).classed("highlighted", false);
  2896. linkG.classed("dimmed", false).classed("highlighted", false);
  2897. // 恢复跨层边的可见性状态(根据全局开关)
  2898. linkG.each(function(d) {{
  2899. if (isCrossLayerEdge(d)) {{
  2900. d3.select(this).style("display", showCrossLayerEdges ? "block" : "none");
  2901. }}
  2902. }});
  2903. }}
  2904. // 高亮指定的节点和边
  2905. function highlightElements(highlightNodeIds, highlightLinkIndices) {{
  2906. // 先灰化所有
  2907. node.classed("dimmed", true).classed("highlighted", false);
  2908. linkG.classed("dimmed", true).classed("highlighted", false);
  2909. // 高亮指定节点
  2910. node.filter(d => highlightNodeIds.has(d.id))
  2911. .classed("dimmed", false)
  2912. .classed("highlighted", true);
  2913. // 高亮指定边
  2914. linkG.filter((d, i) => highlightLinkIndices.has(i))
  2915. .classed("dimmed", false)
  2916. .classed("highlighted", true);
  2917. }}
  2918. // 点击节点时的高亮逻辑
  2919. function highlightNode(clickedNode) {{
  2920. const highlightNodeIds = new Set([clickedNode.id]);
  2921. const highlightLinkIndices = new Set();
  2922. links.forEach((link, i) => {{
  2923. const sourceId = typeof link.source === "object" ? link.source.id : link.source;
  2924. const targetId = typeof link.target === "object" ? link.target.id : link.target;
  2925. // 与点击节点直接相连的边
  2926. if (sourceId === clickedNode.id || targetId === clickedNode.id) {{
  2927. highlightLinkIndices.add(i);
  2928. highlightNodeIds.add(sourceId);
  2929. highlightNodeIds.add(targetId);
  2930. // 如果是帖子节点,还要高亮对应的镜像边
  2931. if (clickedNode.source === "帖子") {{
  2932. // 找到通过该帖子连接的其他帖子(镜像边)
  2933. links.forEach((otherLink, j) => {{
  2934. const otherType = otherLink.type;
  2935. if (otherType.startsWith("镜像_") || otherType.startsWith("二阶_")) {{
  2936. const oSrc = typeof otherLink.source === "object" ? otherLink.source.id : otherLink.source;
  2937. const oTgt = typeof otherLink.target === "object" ? otherLink.target.id : otherLink.target;
  2938. if (oSrc === clickedNode.id || oTgt === clickedNode.id) {{
  2939. highlightLinkIndices.add(j);
  2940. highlightNodeIds.add(oSrc);
  2941. highlightNodeIds.add(oTgt);
  2942. }}
  2943. }}
  2944. }});
  2945. }}
  2946. }}
  2947. }});
  2948. // 高亮相关的节点和边
  2949. highlightElements(highlightNodeIds, highlightLinkIndices);
  2950. // 临时显示关联的跨层边(即使全局开关是关闭的)
  2951. linkG.each(function(d, i) {{
  2952. if (highlightLinkIndices.has(i)) {{
  2953. d3.select(this).style("display", "block");
  2954. }}
  2955. }});
  2956. }}
  2957. // 点击边时的高亮逻辑
  2958. function highlightEdge(clickedLink, clickedIndex) {{
  2959. const highlightNodeIds = new Set();
  2960. const highlightLinkIndices = new Set([clickedIndex]);
  2961. const sourceId = typeof clickedLink.source === "object" ? clickedLink.source.id : clickedLink.source;
  2962. const targetId = typeof clickedLink.target === "object" ? clickedLink.target.id : clickedLink.target;
  2963. highlightNodeIds.add(sourceId);
  2964. highlightNodeIds.add(targetId);
  2965. // 如果是镜像边或二阶边,使用预计算的路径节点高亮
  2966. if ((clickedLink.type.startsWith("镜像_") || clickedLink.type.startsWith("二阶_")) && clickedLink.边详情) {{
  2967. const detail = clickedLink.边详情;
  2968. const pathNodes = new Set([sourceId, targetId]);
  2969. // 使用预计算的路径节点
  2970. (detail.路径节点 || []).forEach(n => pathNodes.add(n));
  2971. // 高亮路径上的所有节点
  2972. pathNodes.forEach(n => highlightNodeIds.add(n));
  2973. // 高亮连接路径节点的边
  2974. links.forEach((link, i) => {{
  2975. const lSrc = typeof link.source === "object" ? link.source.id : link.source;
  2976. const lTgt = typeof link.target === "object" ? link.target.id : link.target;
  2977. if (pathNodes.has(lSrc) && pathNodes.has(lTgt)) {{
  2978. highlightLinkIndices.add(i);
  2979. }}
  2980. }});
  2981. }}
  2982. // 如果是人设边(两端都不是帖子节点),找对应的镜像边
  2983. else if (!sourceId.startsWith("帖子_") && !targetId.startsWith("帖子_")) {{
  2984. // 收集路径节点
  2985. const pathNodes = new Set([sourceId, targetId]);
  2986. // 找匹配的镜像边,读取其路径节点
  2987. links.forEach((link, i) => {{
  2988. const detail = link.边详情 || {{}};
  2989. if ((link.type.startsWith("镜像_") || link.type.startsWith("二阶_")) && detail.源人设节点 && detail.目标人设节点) {{
  2990. const matches = (detail.源人设节点 === sourceId && detail.目标人设节点 === targetId) ||
  2991. (detail.源人设节点 === targetId && detail.目标人设节点 === sourceId);
  2992. if (matches) {{
  2993. highlightLinkIndices.add(i);
  2994. // 直接使用预存的路径节点
  2995. (detail.路径节点 || []).forEach(n => pathNodes.add(n));
  2996. }}
  2997. }}
  2998. }});
  2999. // 高亮路径上的所有节点
  3000. pathNodes.forEach(n => highlightNodeIds.add(n));
  3001. // 高亮连接路径节点的边
  3002. links.forEach((link, i) => {{
  3003. const lSrc = typeof link.source === "object" ? link.source.id : link.source;
  3004. const lTgt = typeof link.target === "object" ? link.target.id : link.target;
  3005. // 两端都在路径上的边
  3006. if (pathNodes.has(lSrc) && pathNodes.has(lTgt)) {{
  3007. highlightLinkIndices.add(i);
  3008. }}
  3009. }});
  3010. }}
  3011. // 高亮相关的节点和边
  3012. highlightElements(highlightNodeIds, highlightLinkIndices);
  3013. // 临时显示关联的跨层边(即使全局开关是关闭的)
  3014. linkG.each(function(d, i) {{
  3015. if (highlightLinkIndices.has(i)) {{
  3016. d3.select(this).style("display", "block");
  3017. }}
  3018. }});
  3019. }}
  3020. // 点击空白处清除高亮(合并所有空白点击逻辑)
  3021. svg.on("click", (event) => {{
  3022. // 检查是否点击的是空白区域(svg本身或layer-backgrounds)
  3023. const isBlank = event.target === svg.node() ||
  3024. event.target.tagName === "svg" ||
  3025. event.target.classList.contains("layer-backgrounds");
  3026. if (isBlank) {{
  3027. // 清除右侧图高亮
  3028. clearHighlight();
  3029. // 清除人设树高亮
  3030. resetTreeHighlight();
  3031. resetGraphHighlight();
  3032. // 关闭详情面板
  3033. closeDetailPanel();
  3034. // 清除关系图
  3035. clearEgoGraph();
  3036. }}
  3037. }});
  3038. }}
  3039. // 控制函数
  3040. function resetZoom() {{
  3041. const container = document.getElementById("svg-container");
  3042. const width = container.clientWidth;
  3043. const height = container.clientHeight;
  3044. svg.transition().duration(750).call(
  3045. zoom.transform,
  3046. d3.zoomIdentity.translate(width/2, height/2).scale(1).translate(-width/2, -height/2)
  3047. );
  3048. }}
  3049. function toggleLabels() {{
  3050. showLabels = !showLabels;
  3051. g.selectAll(".node text").style("display", showLabels ? "block" : "none");
  3052. }}
  3053. // 切换跨层边显示
  3054. function toggleCrossLayerEdges() {{
  3055. showCrossLayerEdges = !showCrossLayerEdges;
  3056. const btn = document.getElementById("crossLayerBtn");
  3057. btn.textContent = showCrossLayerEdges ? "隐藏跨层边" : "显示跨层边";
  3058. btn.style.background = showCrossLayerEdges ? "#e94560" : "";
  3059. // 更新边的可见性(使用 isCrossLayerEdge 函数判断)
  3060. g.selectAll(".link-group").each(function(d) {{
  3061. if (isCrossLayerEdge(d)) {{
  3062. d3.select(this).style("display", showCrossLayerEdges ? "block" : "none");
  3063. }}
  3064. }});
  3065. }}
  3066. function showNodeInfo(d) {{
  3067. const panel = document.getElementById("detailPanel");
  3068. panel.classList.add("active");
  3069. document.getElementById("detailTitle").textContent = d.source === "帖子" ? "📌 帖子节点" : "👤 人设节点";
  3070. let html = `
  3071. <p><span class="label">节点ID:</span> ${{d.节点ID}}</p>
  3072. <p><span class="label">名称:</span> <strong>${{d.节点名称}}</strong></p>
  3073. <p><span class="label">类型:</span> ${{d.节点类型}}</p>
  3074. <p><span class="label">层级:</span> ${{d.节点层级}}</p>
  3075. `;
  3076. if (d.权重) {{
  3077. html += `<p><span class="label">权重:</span> ${{d.权重}}</p>`;
  3078. }}
  3079. if (d.所属分类 && d.所属分类.length > 0) {{
  3080. html += `<p><span class="label">所属分类:</span> ${{d.所属分类.join(" > ")}}</p>`;
  3081. }}
  3082. if (d.帖子数) {{
  3083. html += `<p><span class="label">帖子数:</span> ${{d.帖子数}}</p>`;
  3084. }}
  3085. document.getElementById("detailContent").innerHTML = html;
  3086. }}
  3087. // 显示人设树节点详情(包含入边、出边、相关节点)
  3088. function showTreeNodeDetail(nodeData, inEdges, outEdges) {{
  3089. const panel = document.getElementById("detailPanel");
  3090. panel.classList.add("active");
  3091. document.getElementById("detailTitle").textContent = "🌳 人设树节点";
  3092. // 节点基本信息
  3093. let html = `
  3094. <p><span class="label">名称:</span> <strong>${{nodeData.节点名称 || nodeData.name}}</strong></p>
  3095. <p><span class="label">类型:</span> ${{nodeData.节点类型 || (nodeData.isRoot ? "根节点" : "维度")}}</p>
  3096. <p><span class="label">层级:</span> ${{nodeData.节点层级 || "-"}}</p>
  3097. `;
  3098. if (nodeData.所属分类 && nodeData.所属分类.length > 0) {{
  3099. html += `<p><span class="label">所属分类:</span> ${{nodeData.所属分类.join(" > ")}}</p>`;
  3100. }}
  3101. if (nodeData.帖子数) {{
  3102. html += `<p><span class="label">帖子数:</span> ${{nodeData.帖子数}}</p>`;
  3103. }}
  3104. // 统计边类型
  3105. const inEdgeTypes = {{}};
  3106. const outEdgeTypes = {{}};
  3107. inEdges.forEach(e => {{ inEdgeTypes[e.边类型] = (inEdgeTypes[e.边类型] || 0) + 1; }});
  3108. outEdges.forEach(e => {{ outEdgeTypes[e.边类型] = (outEdgeTypes[e.边类型] || 0) + 1; }});
  3109. // 入边统计
  3110. html += `<h4 style="margin-top:12px;color:#3498db;font-size:12px;">📥 入边 (${{inEdges.length}})</h4>`;
  3111. if (inEdges.length > 0) {{
  3112. html += `<div class="edge-list">`;
  3113. for (const [type, count] of Object.entries(inEdgeTypes)) {{
  3114. html += `<div class="edge-type-item"><span class="edge-type">${{type}}</span><span class="edge-count">${{count}}</span></div>`;
  3115. }}
  3116. // 显示前5条入边详情
  3117. const showInEdges = inEdges.slice(0, 5);
  3118. showInEdges.forEach(e => {{
  3119. const srcName = personaTreeData.nodes.find(n => n.节点ID === e.源节点ID)?.节点名称 || e.源节点ID;
  3120. html += `<div class="edge-detail">← ${{srcName}} <span class="edge-type-tag">${{e.边类型}}</span></div>`;
  3121. }});
  3122. if (inEdges.length > 5) {{
  3123. html += `<div class="edge-more">... 还有 ${{inEdges.length - 5}} 条</div>`;
  3124. }}
  3125. html += `</div>`;
  3126. }} else {{
  3127. html += `<div class="edge-empty">无</div>`;
  3128. }}
  3129. // 出边统计
  3130. html += `<h4 style="margin-top:12px;color:#e74c3c;font-size:12px;">📤 出边 (${{outEdges.length}})</h4>`;
  3131. if (outEdges.length > 0) {{
  3132. html += `<div class="edge-list">`;
  3133. for (const [type, count] of Object.entries(outEdgeTypes)) {{
  3134. html += `<div class="edge-type-item"><span class="edge-type">${{type}}</span><span class="edge-count">${{count}}</span></div>`;
  3135. }}
  3136. // 显示前5条出边详情
  3137. const showOutEdges = outEdges.slice(0, 5);
  3138. showOutEdges.forEach(e => {{
  3139. const tgtName = personaTreeData.nodes.find(n => n.节点ID === e.目标节点ID)?.节点名称 || e.目标节点ID;
  3140. html += `<div class="edge-detail">→ ${{tgtName}} <span class="edge-type-tag">${{e.边类型}}</span></div>`;
  3141. }});
  3142. if (outEdges.length > 5) {{
  3143. html += `<div class="edge-more">... 还有 ${{outEdges.length - 5}} 条</div>`;
  3144. }}
  3145. html += `</div>`;
  3146. }} else {{
  3147. html += `<div class="edge-empty">无</div>`;
  3148. }}
  3149. document.getElementById("detailContent").innerHTML = html;
  3150. }}
  3151. function showEdgeInfo(d) {{
  3152. const panel = document.getElementById("detailPanel");
  3153. panel.classList.add("active");
  3154. const sourceNode = typeof d.source === "object" ? d.source : {{ id: d.source }};
  3155. const targetNode = typeof d.target === "object" ? d.target : {{ id: d.target }};
  3156. // 判断是否为镜像边
  3157. const isMirror = d.type.startsWith("镜像_");
  3158. document.getElementById("detailTitle").textContent = isMirror ? "🪞 镜像边详情" : "🔗 边详情";
  3159. let html = `
  3160. <p><span class="label">边类型:</span> <strong>${{d.type}}</strong></p>
  3161. <p><span class="label">源节点:</span> ${{sourceNode.节点名称 || sourceNode.id}}</p>
  3162. <p><span class="label">目标节点:</span> ${{targetNode.节点名称 || targetNode.id}}</p>
  3163. `;
  3164. if (d.边详情) {{
  3165. if (d.边详情.相似度 !== undefined) {{
  3166. const score = typeof d.边详情.相似度 === "number" ? d.边详情.相似度.toFixed(2) : d.边详情.相似度;
  3167. html += `<p><span class="label">相似度:</span> <span class="similarity-score">${{score}}</span></p>`;
  3168. }}
  3169. if (d.边详情.说明) {{
  3170. html += `<p><span class="label">说明:</span></p><div class="edge-description">${{d.边详情.说明}}</div>`;
  3171. }}
  3172. if (d.边详情.共现次数 !== undefined) {{
  3173. html += `<p><span class="label">共现次数:</span> ${{d.边详情.共现次数}}</p>`;
  3174. }}
  3175. // 镜像边特有信息
  3176. if (d.边详情.原始边类型) {{
  3177. html += `<p><span class="label">原始边类型:</span> ${{d.边详情.原始边类型}}</p>`;
  3178. }}
  3179. if (d.边详情.源人设节点) {{
  3180. html += `<p><span class="label">源人设节点:</span> ${{d.边详情.源人设节点}}</p>`;
  3181. }}
  3182. if (d.边详情.目标人设节点) {{
  3183. html += `<p><span class="label">目标人设节点:</span> ${{d.边详情.目标人设节点}}</p>`;
  3184. }}
  3185. }}
  3186. document.getElementById("detailContent").innerHTML = html;
  3187. }}
  3188. function closeDetailPanel() {{
  3189. document.getElementById("detailPanel").classList.remove("active");
  3190. }}
  3191. // 更新匹配列表
  3192. function updateMatchList(matchLinks, nodes) {{
  3193. const listEl = document.getElementById("matchList");
  3194. const countEl = document.getElementById("matchCount");
  3195. // 构建节点ID到名称的映射
  3196. const nodeNames = {{}};
  3197. nodes.forEach(n => {{
  3198. nodeNames[n.id] = n.节点名称 || n.id;
  3199. }});
  3200. // 按分数降序排序
  3201. const sortedLinks = [...matchLinks].sort((a, b) => {{
  3202. const scoreA = a.边详情?.相似度 ?? 0;
  3203. const scoreB = b.边详情?.相似度 ?? 0;
  3204. return scoreB - scoreA;
  3205. }});
  3206. countEl.textContent = `(${{sortedLinks.length}})`;
  3207. // 生成列表HTML
  3208. let html = "";
  3209. sortedLinks.forEach((link, index) => {{
  3210. const score = link.边详情?.相似度;
  3211. const scoreText = score !== undefined ? score.toFixed(2) : "N/A";
  3212. const scoreClass = score >= 0.8 ? "high" : (score >= 0.5 ? "medium" : "");
  3213. const srcId = typeof link.source === "object" ? link.source.id : link.source;
  3214. const tgtId = typeof link.target === "object" ? link.target.id : link.target;
  3215. const srcName = nodeNames[srcId] || srcId;
  3216. const tgtName = nodeNames[tgtId] || tgtId;
  3217. html += `
  3218. <div class="match-item" data-index="${{index}}" data-src="${{srcId}}" data-tgt="${{tgtId}}">
  3219. <span class="score ${{scoreClass}}">${{scoreText}}</span>
  3220. <span class="names" title="${{srcName}} → ${{tgtName}}">${{srcName}} → ${{tgtName}}</span>
  3221. </div>
  3222. `;
  3223. }});
  3224. listEl.innerHTML = html;
  3225. // 添加点击事件
  3226. listEl.querySelectorAll(".match-item").forEach(item => {{
  3227. item.addEventListener("click", () => {{
  3228. const srcId = item.dataset.src;
  3229. const tgtId = item.dataset.tgt;
  3230. const index = parseInt(item.dataset.index);
  3231. // 高亮对应的边
  3232. highlightMatchEdge(srcId, tgtId);
  3233. // 更新列表项样式
  3234. listEl.querySelectorAll(".match-item").forEach(el => el.classList.remove("active"));
  3235. item.classList.add("active");
  3236. }});
  3237. }});
  3238. }}
  3239. // 高亮匹配边
  3240. function highlightMatchEdge(srcId, tgtId) {{
  3241. if (!g) return;
  3242. // 重置所有
  3243. g.selectAll(".node").classed("dimmed", true).classed("highlighted", false);
  3244. g.selectAll(".link-group").classed("dimmed", true).classed("highlighted", false);
  3245. // 高亮对应的边和节点
  3246. g.selectAll(".link-group").each(function(d) {{
  3247. const dSrc = typeof d.source === "object" ? d.source.id : d.source;
  3248. const dTgt = typeof d.target === "object" ? d.target.id : d.target;
  3249. if ((dSrc === srcId && dTgt === tgtId) || (dSrc === tgtId && dTgt === srcId)) {{
  3250. d3.select(this).classed("dimmed", false).classed("highlighted", true);
  3251. }}
  3252. }});
  3253. g.selectAll(".node").each(function(d) {{
  3254. if (d.id === srcId || d.id === tgtId) {{
  3255. d3.select(this).classed("dimmed", false).classed("highlighted", true);
  3256. }}
  3257. }});
  3258. }}
  3259. // 获取节点颜色(全局版本,根据节点数据判断维度)
  3260. function getTreeNodeColor(d) {{
  3261. const dimColors = {{ "灵感点": "#f39c12", "目的点": "#3498db", "关键点": "#9b59b6" }};
  3262. if (d.data.isRoot) return "#e94560";
  3263. if (d.data.isDimension) return d.data.dimColor;
  3264. return d.data.dimColor || "#888";
  3265. }}
  3266. // 共享的节点点击处理函数(人设树和关系图复用)
  3267. function handleNodeClick(clickedNodeId, clickedNodeName) {{
  3268. if (!clickedNodeId) return;
  3269. // 动态获取树相关元素
  3270. const treeGroup = d3.select(".persona-tree");
  3271. if (treeGroup.empty()) return;
  3272. const treeEdges = treeGroup.selectAll(".tree-edge");
  3273. // 先重置所有高亮状态
  3274. treeGroup.selectAll(".tree-node")
  3275. .classed("tree-dimmed", false)
  3276. .classed("tree-highlighted", false);
  3277. treeGroup.selectAll(".tree-node .tree-shape")
  3278. .attr("fill", d => getTreeNodeColor(d))
  3279. .attr("stroke", "rgba(255,255,255,0.5)")
  3280. .attr("stroke-width", 1)
  3281. .attr("stroke-opacity", 1)
  3282. .attr("opacity", 1);
  3283. treeGroup.selectAll(".tree-node text")
  3284. .attr("fill", d => (d.data.isRoot || d.data.isDimension) ? getTreeNodeColor(d) : "#bbb")
  3285. .attr("opacity", 1);
  3286. treeEdges.attr("stroke-opacity", 0.3).attr("stroke-width", 1);
  3287. if (g) {{
  3288. g.selectAll(".node").classed("dimmed", false).classed("highlighted", false);
  3289. g.selectAll(".link-group").classed("dimmed", false).classed("highlighted", false);
  3290. }}
  3291. // 构建节点ID到D3节点的映射
  3292. const treeNodeById = {{}};
  3293. treeGroup.selectAll(".tree-node").each(function(n) {{
  3294. if (n.data.节点ID) treeNodeById[n.data.节点ID] = n;
  3295. }});
  3296. // 使用多级配置收集关联节点(与关系图一致)
  3297. const levelConfigs = getLevelConfigs();
  3298. const {{ nodeIds: connectedNodeIds, edges: allConnectedEdges }} = collectNodesAndEdges(clickedNodeId, levelConfigs);
  3299. // 获取D3树节点
  3300. const clickedD3Node = treeNodeById[clickedNodeId];
  3301. // 转换为D3节点集合(只基于 collectNodesAndEdges 的结果,与关系图同步)
  3302. const connectedD3Nodes = new Set();
  3303. if (clickedD3Node) connectedD3Nodes.add(clickedD3Node);
  3304. connectedNodeIds.forEach(id => {{
  3305. if (treeNodeById[id]) connectedD3Nodes.add(treeNodeById[id]);
  3306. }});
  3307. // 高亮树中的节点
  3308. treeGroup.selectAll(".tree-node")
  3309. .classed("tree-dimmed", n => !connectedD3Nodes.has(n))
  3310. .classed("tree-highlighted", n => connectedD3Nodes.has(n));
  3311. // 高亮所有形状(不变粗)
  3312. treeGroup.selectAll(".tree-node .tree-shape")
  3313. .attr("fill", function(n) {{
  3314. if (!connectedD3Nodes.has(n)) return "#555";
  3315. return getTreeNodeColor(n);
  3316. }})
  3317. .attr("stroke", function(n) {{
  3318. if (n.data.节点ID === clickedNodeId) return "#fff";
  3319. return connectedD3Nodes.has(n) ? "rgba(255,255,255,0.8)" : "#333";
  3320. }})
  3321. .attr("stroke-opacity", 1);
  3322. treeGroup.selectAll(".tree-node text")
  3323. .attr("fill", function(n) {{
  3324. if (!connectedD3Nodes.has(n)) return "#555";
  3325. return (n.data.isRoot || n.data.isDimension) ? getTreeNodeColor(n) : "#bbb";
  3326. }});
  3327. // 边高亮(树边基于连接的节点)
  3328. treeEdges.attr("stroke-opacity", function(e) {{
  3329. // 树边高亮条件:子节点(目标)在连接集中,或者两端都在连接集中
  3330. const srcId = e.源节点ID;
  3331. const tgtId = e.目标节点ID;
  3332. const srcConnected = connectedNodeIds.has(srcId) || connectedD3Nodes.has(e.sourceNode);
  3333. const tgtConnected = connectedNodeIds.has(tgtId) || connectedD3Nodes.has(e.targetNode);
  3334. return (srcConnected && tgtConnected) ? 0.9 : 0.15;
  3335. }});
  3336. // 计算入边和出边
  3337. const inEdges = allConnectedEdges.filter(e => e.目标节点ID === clickedNodeId);
  3338. const outEdges = allConnectedEdges.filter(e => e.源节点ID === clickedNodeId);
  3339. // 显示详情面板
  3340. const nodeData = personaTreeData.nodes.find(n => n.节点ID === clickedNodeId);
  3341. if (nodeData) {{
  3342. showTreeNodeDetail(nodeData, inEdges, outEdges);
  3343. }}
  3344. // 显示关系子图(先显示,这样容器高度才正确)
  3345. renderEgoGraph(clickedNodeId, clickedNodeName);
  3346. // 滚动人设树到对应节点位置(放在关系图显示后,高度才准确)
  3347. if (clickedD3Node) {{
  3348. // 用 setTimeout 确保 DOM 更新完成
  3349. setTimeout(() => {{
  3350. const treeContainer = document.getElementById("tree-container");
  3351. const containerHeight = treeContainer.clientHeight;
  3352. // D3树布局中 x 是垂直方向(因为是水平树)
  3353. const nodeY = clickedD3Node.x + 25; // 加上treeGroup的transform偏移
  3354. const targetScroll = nodeY - containerHeight / 2;
  3355. treeContainer.scrollTo({{
  3356. top: Math.max(0, targetScroll),
  3357. behavior: "smooth"
  3358. }});
  3359. }}, 50);
  3360. }}
  3361. // 高亮右侧图中对应节点及其相关节点和边
  3362. if (g) {{
  3363. // 收集相关节点ID(点击的节点及其直接连接的节点)
  3364. const relatedNodeIds = new Set([clickedNodeId]);
  3365. // 找所有与该节点相连的边
  3366. g.selectAll(".link-group").each(function(d) {{
  3367. const srcId = typeof d.source === "object" ? d.source.id : d.source;
  3368. const tgtId = typeof d.target === "object" ? d.target.id : d.target;
  3369. if (srcId === clickedNodeId || tgtId === clickedNodeId) {{
  3370. relatedNodeIds.add(srcId);
  3371. relatedNodeIds.add(tgtId);
  3372. }}
  3373. }});
  3374. // 检查是否有相关节点在图中
  3375. const hasRelatedNodes = g.selectAll(".node").filter(n => relatedNodeIds.has(n.id)).size() > 0;
  3376. if (hasRelatedNodes) {{
  3377. // 高亮相关节点,变灰其他
  3378. g.selectAll(".node")
  3379. .classed("dimmed", n => !relatedNodeIds.has(n.id))
  3380. .classed("highlighted", n => relatedNodeIds.has(n.id));
  3381. // 高亮相关边
  3382. g.selectAll(".link-group").each(function(d) {{
  3383. const srcId = typeof d.source === "object" ? d.source.id : d.source;
  3384. const tgtId = typeof d.target === "object" ? d.target.id : d.target;
  3385. const isRelated = srcId === clickedNodeId || tgtId === clickedNodeId;
  3386. d3.select(this)
  3387. .classed("dimmed", !isRelated)
  3388. .classed("highlighted", isRelated);
  3389. // 显示相关的跨层边
  3390. if (isRelated) {{
  3391. d3.select(this).style("display", "block");
  3392. }}
  3393. }});
  3394. }} else {{
  3395. // 点击的节点不在图中,全部变灰
  3396. g.selectAll(".node").classed("dimmed", true).classed("highlighted", false);
  3397. g.selectAll(".link-group").classed("dimmed", true).classed("highlighted", false);
  3398. }}
  3399. }}
  3400. }}
  3401. // 同步人设树高亮和关系图展示(职责单一:不处理力导向图)
  3402. function syncTreeAndRelationGraph(pathNodeIds, edgeType) {{
  3403. if (!pathNodeIds || pathNodeIds.length === 0) return;
  3404. // 动态获取树相关元素
  3405. const treeGroup = d3.select(".persona-tree");
  3406. if (treeGroup.empty()) return;
  3407. const treeEdges = treeGroup.selectAll(".tree-edge");
  3408. // 重置人设树高亮状态
  3409. treeGroup.selectAll(".tree-node")
  3410. .classed("tree-dimmed", false)
  3411. .classed("tree-highlighted", false);
  3412. treeGroup.selectAll(".tree-node .tree-shape")
  3413. .attr("fill", d => getTreeNodeColor(d))
  3414. .attr("stroke", "rgba(255,255,255,0.5)")
  3415. .attr("stroke-width", 1)
  3416. .attr("stroke-opacity", 1)
  3417. .attr("opacity", 1);
  3418. treeGroup.selectAll(".tree-node text")
  3419. .attr("fill", d => (d.data.isRoot || d.data.isDimension) ? getTreeNodeColor(d) : "#bbb")
  3420. .attr("opacity", 1);
  3421. treeEdges.attr("stroke-opacity", 0.3).attr("stroke-width", 1);
  3422. // 构建节点ID到D3节点的映射
  3423. const treeNodeById = {{}};
  3424. treeGroup.selectAll(".tree-node").each(function(n) {{
  3425. if (n.data.节点ID) treeNodeById[n.data.节点ID] = n;
  3426. }});
  3427. // 路径节点ID集合
  3428. const pathNodeIdSet = new Set(pathNodeIds);
  3429. // 高亮树边(路径上相邻节点之间的边)
  3430. treeEdges.attr("stroke-opacity", function(e) {{
  3431. const srcInPath = pathNodeIdSet.has(e.源节点ID);
  3432. const tgtInPath = pathNodeIdSet.has(e.目标节点ID);
  3433. return (srcInPath && tgtInPath) ? 1 : 0.1;
  3434. }});
  3435. // 高亮路径上的节点
  3436. treeGroup.selectAll(".tree-node").each(function(n) {{
  3437. const nodeId = n.data.节点ID;
  3438. const isInPath = pathNodeIdSet.has(nodeId);
  3439. d3.select(this).select(".tree-shape")
  3440. .attr("fill", isInPath ? getTreeNodeColor(n) : "#555")
  3441. .attr("opacity", 1);
  3442. d3.select(this).select("text")
  3443. .attr("fill", isInPath ?
  3444. ((n.data.isRoot || n.data.isDimension) ? getTreeNodeColor(n) : "#bbb") : "#555")
  3445. .attr("opacity", 1);
  3446. }});
  3447. // 显示路径详情
  3448. const panel = document.getElementById("detailPanel");
  3449. panel.classList.add("active");
  3450. document.getElementById("detailTitle").textContent = "🔗 路径详情";
  3451. // 获取路径上的节点名称
  3452. const pathNodeNames = pathNodeIds.map(id => {{
  3453. const treeNode = treeNodeById[id];
  3454. if (treeNode) return treeNode.data.节点名称 || treeNode.data.name;
  3455. const nodeData = personaTreeData.nodes.find(n => n.节点ID === id);
  3456. return nodeData?.节点名称 || id;
  3457. }});
  3458. let html = `
  3459. <p><span class="label">边类型:</span> <strong>${{edgeType}}</strong></p>
  3460. <p><span class="label">路径节点:</span> ${{pathNodeNames.join(" → ")}}</p>
  3461. <p><span class="label">节点数:</span> ${{pathNodeIds.length}}</p>
  3462. `;
  3463. document.getElementById("detailContent").innerHTML = html;
  3464. // 在关系图中展示路径上的所有节点和边
  3465. renderEgoGraphPath(pathNodeIds, edgeType);
  3466. }}
  3467. // 关系子图(Ego Graph)- 在画布第四层显示
  3468. let currentEgoSimulation = null; // 保存当前的力模拟,用于停止
  3469. let currentEgoCenterNodeId = null; // 当前关系图中心节点ID
  3470. let currentEgoCenterNodeName = null; // 当前关系图中心节点名称
  3471. // 当前选中的层级数
  3472. let currentLevelCount = 1;
  3473. // 切换级联菜单
  3474. function toggleCascadeMenu() {{
  3475. event.stopPropagation();
  3476. const menu = document.getElementById('cascade-menu');
  3477. menu.classList.toggle('show');
  3478. }}
  3479. // 反选指定层级的边类型
  3480. function invertSelection(level) {{
  3481. event.stopPropagation();
  3482. document.querySelectorAll(`.cascade-edge-item input[data-level="${{level}}"]`).forEach(cb => {{
  3483. cb.checked = !cb.checked;
  3484. }});
  3485. // 更新全选复选框状态
  3486. const allItems = document.querySelectorAll(`.cascade-edge-item input[data-level="${{level}}"]`);
  3487. const checkedItems = document.querySelectorAll(`.cascade-edge-item input[data-level="${{level}}"]:checked`);
  3488. const selectAllCb = document.querySelector(`.select-all input[data-level="${{level}}"]`);
  3489. selectAllCb.checked = allItems.length === checkedItems.length;
  3490. // 重新渲染
  3491. if (currentEgoCenterNodeId) {{
  3492. handleNodeClick(currentEgoCenterNodeId, currentEgoCenterNodeName);
  3493. }}
  3494. }}
  3495. // 重置所有层级到默认配置(所有层级边类型默认不选)
  3496. function resetSelection() {{
  3497. event.stopPropagation();
  3498. // 所有层级边类型默认不选
  3499. [1, 2, 3].forEach(level => {{
  3500. document.querySelectorAll(`.cascade-edge-item input[data-level="${{level}}"]`).forEach(cb => {{
  3501. cb.checked = false;
  3502. }});
  3503. document.querySelector(`.select-all input[data-level="${{level}}"]`).checked = false;
  3504. }});
  3505. // 重新渲染
  3506. if (currentEgoCenterNodeId) {{
  3507. handleNodeClick(currentEgoCenterNodeId, currentEgoCenterNodeName);
  3508. }}
  3509. }}
  3510. // 选择层级
  3511. function selectLevel(level) {{
  3512. event.stopPropagation();
  3513. currentLevelCount = level;
  3514. // 更新层级选中状态
  3515. document.querySelectorAll('.cascade-level-item').forEach(item => {{
  3516. const itemLevel = parseInt(item.dataset.level);
  3517. item.classList.toggle('active', itemLevel === level);
  3518. }});
  3519. // 显示对应的边类型组(1级显示L1,2级显示L1+L2,3级显示L1+L2+L3)
  3520. document.querySelectorAll('.cascade-edge-group').forEach(group => {{
  3521. const groupLevel = parseInt(group.dataset.level);
  3522. group.classList.toggle('active', groupLevel <= level);
  3523. }});
  3524. // 更新按钮显示
  3525. document.getElementById('cascade-label').textContent = level + '级';
  3526. // 重新渲染关系图和人设树高亮
  3527. if (currentEgoCenterNodeId) {{
  3528. handleNodeClick(currentEgoCenterNodeId, currentEgoCenterNodeName);
  3529. }}
  3530. }}
  3531. // 获取指定层级选中的边类型
  3532. function getLevelEdgeTypes(level) {{
  3533. const types = [];
  3534. document.querySelectorAll(`.cascade-edge-item input[data-level="${{level}}"]:checked`).forEach(cb => {{
  3535. types.push(cb.dataset.type);
  3536. }});
  3537. return types;
  3538. }}
  3539. // 获取层级配置(返回每层的边类型数组)
  3540. function getLevelConfigs() {{
  3541. const configs = [];
  3542. for (let i = 1; i <= currentLevelCount; i++) {{
  3543. const types = getLevelEdgeTypes(i);
  3544. configs.push(types);
  3545. }}
  3546. return configs;
  3547. }}
  3548. // 多层级展开:收集指定层级内的所有节点和边(每层可指定不同边类型)
  3549. function collectNodesAndEdges(centerNodeId, levelConfigs) {{
  3550. const nodeIds = new Set([centerNodeId]);
  3551. const collectedEdges = [];
  3552. const visitedEdges = new Set();
  3553. let currentLayer = new Set([centerNodeId]);
  3554. for (let d = 0; d < levelConfigs.length; d++) {{
  3555. const edgeTypes = levelConfigs[d];
  3556. if (edgeTypes.length === 0) break;
  3557. const nextLayer = new Set();
  3558. personaTreeData.edges.forEach(e => {{
  3559. // 筛选边类型
  3560. if (!edgeTypes.includes(e.边类型)) return;
  3561. const edgeKey = `${{e.源节点ID}}-${{e.目标节点ID}}-${{e.边类型}}`;
  3562. if (visitedEdges.has(edgeKey)) return;
  3563. // 单向查找:只从源节点出发,沿边的方向查找
  3564. // 属于:子→父(从子出发找父)
  3565. // 包含:父→子(从父出发找子)
  3566. // 共现:A→B(从A出发找B)
  3567. if (currentLayer.has(e.源节点ID)) {{
  3568. visitedEdges.add(edgeKey);
  3569. collectedEdges.push({{...e, _level: d + 1}});
  3570. // 添加目标节点到下一层
  3571. if (!nodeIds.has(e.目标节点ID)) {{
  3572. nextLayer.add(e.目标节点ID);
  3573. nodeIds.add(e.目标节点ID);
  3574. }}
  3575. }}
  3576. }});
  3577. currentLayer = nextLayer;
  3578. if (nextLayer.size === 0) break;
  3579. }}
  3580. return {{ nodeIds, edges: collectedEdges, depth: levelConfigs.length }};
  3581. }}
  3582. function renderEgoGraph(centerNodeId, centerNodeName) {{
  3583. // 保存当前中心节点
  3584. currentEgoCenterNodeId = centerNodeId;
  3585. currentEgoCenterNodeName = centerNodeName;
  3586. // 显示关系图容器
  3587. document.getElementById("ego-container").style.display = "block";
  3588. // 获取关系图层组
  3589. const egoGroup = d3.select(".ego-graph-content");
  3590. if (egoGroup.empty()) return;
  3591. // 停止之前的模拟
  3592. if (currentEgoSimulation) {{
  3593. currentEgoSimulation.stop();
  3594. currentEgoSimulation = null;
  3595. }}
  3596. // 清除旧内容
  3597. egoGroup.selectAll("*").remove();
  3598. // 获取当前层级配置
  3599. const levelConfigs = getLevelConfigs();
  3600. // 更新顶部标题和统计
  3601. document.getElementById("ego-node-name").textContent = centerNodeName;
  3602. // 获取层半径
  3603. const radius = 160; // 固定半径
  3604. // 根据层级配置收集节点和边
  3605. const {{ nodeIds, edges: relatedEdges, depth }} = collectNodesAndEdges(centerNodeId, levelConfigs);
  3606. // 构建节点数据(确保中心节点始终包含)
  3607. const nodeMap = {{}};
  3608. personaTreeData.nodes.forEach(n => {{
  3609. if (nodeIds.has(n.节点ID) || n.节点ID === centerNodeId) {{
  3610. nodeMap[n.节点ID] = {{
  3611. id: n.节点ID,
  3612. name: n.节点名称,
  3613. type: n.节点类型,
  3614. level: n.节点层级,
  3615. isCenter: n.节点ID === centerNodeId
  3616. }};
  3617. }}
  3618. }});
  3619. const nodes = Object.values(nodeMap);
  3620. // 处理同一对节点间的多条边,分配不同弧度
  3621. const linksByPair = {{}};
  3622. relatedEdges.forEach(e => {{
  3623. // 用排序后的节点对作为key,确保A-B和B-A是同一对
  3624. const pairKey = [e.源节点ID, e.目标节点ID].sort().join("||");
  3625. if (!linksByPair[pairKey]) linksByPair[pairKey] = [];
  3626. linksByPair[pairKey].push(e);
  3627. }});
  3628. // 为每条边分配弧度索引
  3629. const links = [];
  3630. Object.values(linksByPair).forEach(pairEdges => {{
  3631. const count = pairEdges.length;
  3632. pairEdges.forEach((e, i) => {{
  3633. // 弧度:0表示直线,正负值表示向两侧弯曲
  3634. let curvature = 0;
  3635. if (count > 1) {{
  3636. // 多条边时,均匀分布弧度
  3637. curvature = (i - (count - 1) / 2) * 0.3;
  3638. }}
  3639. links.push({{
  3640. source: e.源节点ID,
  3641. target: e.目标节点ID,
  3642. type: e.边类型,
  3643. curvature: curvature
  3644. }});
  3645. }});
  3646. }});
  3647. // 根据节点数量动态计算实际使用的半径
  3648. const nodeCount = nodes.length;
  3649. const nodeSpacingEgo = 65; // 节点间距(增大)
  3650. const minEgoRadius = 120;
  3651. const maxEgoRadius = Math.max(radius, 250); // 允许更大的半径
  3652. let actualRadius;
  3653. if (nodeCount <= 1) {{
  3654. actualRadius = minEgoRadius;
  3655. }} else {{
  3656. const circumference = nodeCount * nodeSpacingEgo;
  3657. const calcR = circumference / (2 * Math.PI);
  3658. actualRadius = Math.max(minEgoRadius, Math.min(maxEgoRadius, calcR));
  3659. }}
  3660. // 更新顶部统计信息
  3661. document.getElementById("ego-stats").textContent = `${{nodeCount}}节点 ${{relatedEdges.length}}边`;
  3662. // 如果只有中心节点,只渲染中心节点
  3663. if (nodes.length === 1) {{
  3664. const centerNode = nodes[0];
  3665. // 获取中心节点的维度颜色
  3666. const dimColors = {{
  3667. "灵感点": "#f39c12",
  3668. "目的点": "#3498db",
  3669. "关键点": "#9b59b6"
  3670. }};
  3671. const level = centerNode.level || "";
  3672. let fillColor = "#888";
  3673. if (level.includes("灵感点")) fillColor = dimColors["灵感点"];
  3674. else if (level.includes("目的点")) fillColor = dimColors["目的点"];
  3675. else if (level.includes("关键点")) fillColor = dimColors["关键点"];
  3676. // 绘制中心节点
  3677. const nodeGroup = egoGroup.append("g")
  3678. .attr("class", "ego-node-group")
  3679. .attr("transform", "translate(0, 0)");
  3680. nodeGroup.append("circle")
  3681. .attr("r", 22)
  3682. .attr("fill", fillColor)
  3683. .attr("stroke", "#fff")
  3684. .attr("stroke-width", 3)
  3685. .attr("cursor", "pointer")
  3686. .style("filter", "drop-shadow(0 2px 4px rgba(0,0,0,0.3))");
  3687. nodeGroup.append("text")
  3688. .attr("dy", "0.35em")
  3689. .attr("text-anchor", "middle")
  3690. .attr("fill", "#fff")
  3691. .attr("font-size", "10px")
  3692. .attr("font-weight", "bold")
  3693. .attr("pointer-events", "none")
  3694. .text(centerNode.name.length > 4 ? centerNode.name.slice(0, 4) + "..." : centerNode.name);
  3695. // 显示提示文字
  3696. egoGroup.append("text")
  3697. .attr("y", 50)
  3698. .attr("text-anchor", "middle")
  3699. .attr("fill", "rgba(255,255,255,0.4)")
  3700. .attr("font-size", "10px")
  3701. .text("无相关边");
  3702. return;
  3703. }}
  3704. // 边类型颜色(统一用实线)
  3705. const edgeColors = {{
  3706. "属于": "#9b59b6", // 紫色 - 层级关系
  3707. "包含": "#ffb6c1", // 淡粉 - 分类包含标签(向下)
  3708. "分类共现(跨点)": "#2ecc71", // 绿色 - 跨帖子分类共现
  3709. "分类共现(点内)": "#3498db", // 蓝色 - 同帖子分类共现
  3710. "标签共现": "#f39c12" // 橙色 - 标签共现
  3711. }};
  3712. // 维度颜色(与人设树完全一致)
  3713. const dimColors = {{
  3714. "灵感点": "#f39c12",
  3715. "目的点": "#3498db",
  3716. "关键点": "#9b59b6"
  3717. }};
  3718. // 获取节点的维度颜色(与人设树一致)
  3719. function getNodeDimColor(d) {{
  3720. // 根据节点层级判断维度
  3721. const level = d.level || "";
  3722. if (level.includes("灵感点")) return dimColors["灵感点"];
  3723. if (level.includes("目的点")) return dimColors["目的点"];
  3724. if (level.includes("关键点")) return dimColors["关键点"];
  3725. return "#888";
  3726. }}
  3727. // 获取节点填充色(实心,用维度颜色,不因选中而改变)
  3728. function getNodeFill(d) {{
  3729. return getNodeDimColor(d); // 始终用维度颜色填充
  3730. }}
  3731. // 获取节点边框色(选中节点用白色边框区分)
  3732. function getNodeStroke(d) {{
  3733. if (d.isCenter) return "#fff"; // 选中节点白色边框
  3734. return "rgba(255,255,255,0.5)"; // 普通节点半透明白边框
  3735. }}
  3736. // 获取节点边框粗细(选中节点更粗)
  3737. function getNodeStrokeWidth(d) {{
  3738. return d.isCenter ? 3 : 1.5;
  3739. }}
  3740. // 根据节点数量调整力模拟参数
  3741. const linkDistance = Math.max(50, Math.min(80, actualRadius / 2.5));
  3742. const chargeStrength = Math.max(-300, Math.min(-100, -nodeCount * 10));
  3743. const collisionRadius = 35; // 碰撞半径,防止重叠
  3744. // 创建力导向模拟(中心在0,0因为已经平移了)
  3745. const simulation = d3.forceSimulation(nodes)
  3746. .force("link", d3.forceLink(links).id(d => d.id).distance(linkDistance))
  3747. .force("charge", d3.forceManyBody().strength(chargeStrength))
  3748. .force("center", d3.forceCenter(0, 0))
  3749. .force("collision", d3.forceCollide().radius(collisionRadius))
  3750. .force("boundary", function() {{
  3751. // 限制节点在圆形区域内
  3752. const maxR = actualRadius - 30;
  3753. return function(alpha) {{
  3754. nodes.forEach(d => {{
  3755. const dist = Math.sqrt(d.x * d.x + d.y * d.y);
  3756. if (dist > maxR) {{
  3757. const scale = maxR / dist;
  3758. d.x *= scale;
  3759. d.y *= scale;
  3760. }}
  3761. }});
  3762. }};
  3763. }}());
  3764. currentEgoSimulation = simulation;
  3765. // 绘制边(用曲线支持多边)
  3766. const link = egoGroup.selectAll(".ego-edge")
  3767. .data(links)
  3768. .join("path")
  3769. .attr("class", "ego-edge")
  3770. .attr("stroke", d => edgeColors[d.type] || "#666")
  3771. .attr("stroke-width", 1.5)
  3772. .attr("stroke-opacity", 0.7)
  3773. .attr("fill", "none");
  3774. // 绘制节点(分类用方形,标签用圆形)
  3775. const node = egoGroup.selectAll(".ego-node")
  3776. .data(nodes)
  3777. .join("g")
  3778. .attr("class", d => "ego-node" + (d.isCenter ? " center" : ""));
  3779. // 根据节点类型绘制不同形状(与人设树样式一致)
  3780. const nodeSize = 8;
  3781. node.each(function(d) {{
  3782. const el = d3.select(this);
  3783. const fill = getNodeFill(d);
  3784. const stroke = getNodeStroke(d);
  3785. const size = d.isCenter ? nodeSize + 2 : nodeSize;
  3786. const strokeWidth = getNodeStrokeWidth(d);
  3787. if (d.type === "分类") {{
  3788. // 方形(分类节点)- 与人设树一致
  3789. el.append("rect")
  3790. .attr("class", "ego-shape")
  3791. .attr("width", size * 2)
  3792. .attr("height", size * 2)
  3793. .attr("x", -size)
  3794. .attr("y", -size)
  3795. .attr("fill", fill)
  3796. .attr("stroke", stroke)
  3797. .attr("stroke-width", strokeWidth)
  3798. .attr("rx", 1);
  3799. }} else {{
  3800. // 圆形(标签节点)- 与人设树一致
  3801. el.append("circle")
  3802. .attr("class", "ego-shape")
  3803. .attr("r", size)
  3804. .attr("fill", fill)
  3805. .attr("stroke", stroke)
  3806. .attr("stroke-width", strokeWidth);
  3807. }}
  3808. }});
  3809. node.append("text")
  3810. .attr("dy", -12)
  3811. .attr("text-anchor", "middle")
  3812. .attr("font-size", "9px")
  3813. .attr("fill", "#fff")
  3814. .text(d => d.name.length > 6 ? d.name.substring(0, 6) + ".." : d.name);
  3815. // 添加点击事件(直接调用共享函数)
  3816. node.on("click", function(event, d) {{
  3817. event.stopPropagation();
  3818. handleNodeClick(d.id, d.name);
  3819. }})
  3820. .on("mouseenter", function(event, d) {{
  3821. // 悬停高亮:高亮到激活节点的路径
  3822. if (!currentEgoCenterNodeId || d.id === currentEgoCenterNodeId) return;
  3823. highlightPathInEgoGraph(d.id);
  3824. }})
  3825. .on("mouseleave", function(event, d) {{
  3826. // 移出时恢复
  3827. if (!currentEgoCenterNodeId) return;
  3828. resetEgoGraphHighlight();
  3829. }});
  3830. // 边点击事件(直接调用共享函数)
  3831. link.on("click", function(event, d) {{
  3832. event.stopPropagation();
  3833. handleEdgeClick(d.source.id, d.target.id, d.type);
  3834. }});
  3835. // 生成曲线路径的函数
  3836. function linkPath(d) {{
  3837. const sx = d.source.x, sy = d.source.y;
  3838. const tx = d.target.x, ty = d.target.y;
  3839. if (d.curvature === 0) {{
  3840. // 直线
  3841. return `M${{sx}},${{sy}}L${{tx}},${{ty}}`;
  3842. }} else {{
  3843. // 曲线:计算控制点
  3844. const dx = tx - sx, dy = ty - sy;
  3845. const dist = Math.sqrt(dx * dx + dy * dy);
  3846. // 控制点垂直于连线方向偏移
  3847. const mx = (sx + tx) / 2;
  3848. const my = (sy + ty) / 2;
  3849. const offset = d.curvature * dist * 0.5;
  3850. // 垂直方向单位向量
  3851. const nx = -dy / dist, ny = dx / dist;
  3852. const cx = mx + nx * offset;
  3853. const cy = my + ny * offset;
  3854. return `M${{sx}},${{sy}}Q${{cx}},${{cy}} ${{tx}},${{ty}}`;
  3855. }}
  3856. }}
  3857. // 更新位置
  3858. simulation.on("tick", () => {{
  3859. link.attr("d", linkPath);
  3860. node.attr("transform", d => `translate(${{d.x}},${{d.y}})`);
  3861. }});
  3862. }}
  3863. function clearEgoGraph() {{
  3864. const egoGroup = d3.select(".ego-graph-content");
  3865. if (!egoGroup.empty()) {{
  3866. egoGroup.selectAll("*").remove();
  3867. }}
  3868. // 隐藏关系图容器
  3869. document.getElementById("ego-container").style.display = "none";
  3870. // 停止模拟
  3871. if (currentEgoSimulation) {{
  3872. currentEgoSimulation.stop();
  3873. currentEgoSimulation = null;
  3874. }}
  3875. }}
  3876. // 在关系图中高亮从悬停节点到激活节点的路径
  3877. function highlightPathInEgoGraph(hoveredNodeId) {{
  3878. const egoGroup = d3.select(".ego-graph-content");
  3879. if (egoGroup.empty()) return;
  3880. // 获取关系图中的边数据
  3881. const egoEdges = egoGroup.selectAll(".ego-edge");
  3882. const egoNodes = egoGroup.selectAll(".ego-node");
  3883. if (egoEdges.empty()) return;
  3884. // 构建邻接表用于路径查找
  3885. const adjacency = {{}};
  3886. const edgeMap = {{}};
  3887. egoEdges.each(function(d) {{
  3888. const srcId = d.source.id || d.source;
  3889. const tgtId = d.target.id || d.target;
  3890. if (!adjacency[srcId]) adjacency[srcId] = [];
  3891. if (!adjacency[tgtId]) adjacency[tgtId] = [];
  3892. adjacency[srcId].push(tgtId);
  3893. adjacency[tgtId].push(srcId);
  3894. // 记录边(双向)
  3895. const key1 = `${{srcId}}|${{tgtId}}`;
  3896. const key2 = `${{tgtId}}|${{srcId}}`;
  3897. edgeMap[key1] = d;
  3898. edgeMap[key2] = d;
  3899. }});
  3900. // BFS找路径
  3901. const visited = new Set();
  3902. const parent = {{}};
  3903. const queue = [currentEgoCenterNodeId];
  3904. visited.add(currentEgoCenterNodeId);
  3905. let found = false;
  3906. while (queue.length > 0 && !found) {{
  3907. const curr = queue.shift();
  3908. const neighbors = adjacency[curr] || [];
  3909. for (const next of neighbors) {{
  3910. if (!visited.has(next)) {{
  3911. visited.add(next);
  3912. parent[next] = curr;
  3913. queue.push(next);
  3914. if (next === hoveredNodeId) {{
  3915. found = true;
  3916. break;
  3917. }}
  3918. }}
  3919. }}
  3920. }}
  3921. if (!found) return;
  3922. // 回溯路径
  3923. const pathNodes = new Set();
  3924. const pathEdgeKeys = new Set();
  3925. let curr = hoveredNodeId;
  3926. while (curr !== undefined) {{
  3927. pathNodes.add(curr);
  3928. const prev = parent[curr];
  3929. if (prev !== undefined) {{
  3930. pathEdgeKeys.add(`${{prev}}|${{curr}}`);
  3931. pathEdgeKeys.add(`${{curr}}|${{prev}}`);
  3932. }}
  3933. curr = prev;
  3934. }}
  3935. // 隐藏不在路径上的边(保持布局不变)
  3936. egoEdges
  3937. .style("visibility", function(d) {{
  3938. const srcId = d.source.id || d.source;
  3939. const tgtId = d.target.id || d.target;
  3940. const key = `${{srcId}}|${{tgtId}}`;
  3941. return pathEdgeKeys.has(key) ? "visible" : "hidden";
  3942. }});
  3943. // 隐藏不在路径上的节点(保持布局不变)
  3944. egoNodes
  3945. .style("visibility", function(d) {{
  3946. return pathNodes.has(d.id) ? "visible" : "hidden";
  3947. }});
  3948. }}
  3949. // 恢复关系图的高亮状态
  3950. function resetEgoGraphHighlight() {{
  3951. const egoGroup = d3.select(".ego-graph-content");
  3952. if (egoGroup.empty()) return;
  3953. // 恢复边的可见性
  3954. egoGroup.selectAll(".ego-edge")
  3955. .style("visibility", "visible");
  3956. // 恢复节点的可见性
  3957. egoGroup.selectAll(".ego-node")
  3958. .style("visibility", "visible");
  3959. }}
  3960. // 渲染路径上的所有节点和边(点击镜像边/二阶边时调用)
  3961. function renderEgoGraphPath(pathNodeIds, edgeType) {{
  3962. if (!pathNodeIds || pathNodeIds.length === 0) return;
  3963. // 显示关系图容器
  3964. document.getElementById("ego-container").style.display = "block";
  3965. const egoGroup = d3.select(".ego-graph-content");
  3966. if (egoGroup.empty()) return;
  3967. // 停止之前的模拟
  3968. if (currentEgoSimulation) {{
  3969. currentEgoSimulation.stop();
  3970. currentEgoSimulation = null;
  3971. }}
  3972. // 清除旧内容
  3973. egoGroup.selectAll("*").remove();
  3974. // 边类型颜色
  3975. const edgeColors = {{
  3976. "属于": "#9b59b6",
  3977. "包含": "#ffb6c1",
  3978. "分类共现(跨点)": "#2ecc71",
  3979. "分类共现(点内)": "#3498db",
  3980. "标签共现": "#f39c12"
  3981. }};
  3982. // 维度颜色
  3983. const dimColors = {{
  3984. "灵感点": "#f39c12",
  3985. "目的点": "#3498db",
  3986. "关键点": "#9b59b6"
  3987. }};
  3988. // 获取节点颜色
  3989. function getNodeColor(nodeData) {{
  3990. const level = nodeData.节点层级 || "";
  3991. if (level.includes("灵感点")) return dimColors["灵感点"];
  3992. if (level.includes("目的点")) return dimColors["目的点"];
  3993. if (level.includes("关键点")) return dimColors["关键点"];
  3994. return "#888";
  3995. }}
  3996. // 获取路径节点数据
  3997. const pathNodes = pathNodeIds.map(id => {{
  3998. const nodeData = personaTreeData.nodes.find(n => n.节点ID === id);
  3999. return nodeData || {{ 节点ID: id, 节点名称: id, 节点类型: "标签" }};
  4000. }});
  4001. // 找出路径上相邻节点之间的边
  4002. const pathEdges = [];
  4003. for (let i = 0; i < pathNodeIds.length - 1; i++) {{
  4004. const srcId = pathNodeIds[i];
  4005. const tgtId = pathNodeIds[i + 1];
  4006. // 在 personaTreeData.edges 中查找
  4007. const edge = personaTreeData.edges.find(e =>
  4008. (e.源节点ID === srcId && e.目标节点ID === tgtId) ||
  4009. (e.源节点ID === tgtId && e.目标节点ID === srcId)
  4010. );
  4011. pathEdges.push(edge || {{ 边类型: edgeType, 源节点ID: srcId, 目标节点ID: tgtId }});
  4012. }}
  4013. // 更新顶部标题
  4014. document.getElementById("ego-node-name").textContent = edgeType;
  4015. document.getElementById("ego-stats").textContent = `${{pathNodes.length}}节点 ${{pathEdges.length}}边`;
  4016. // 水平线性布局
  4017. const nodeSpacing = 80;
  4018. const totalWidth = (pathNodes.length - 1) * nodeSpacing;
  4019. const startX = -totalWidth / 2;
  4020. // 绘制边
  4021. pathEdges.forEach((edge, i) => {{
  4022. const x1 = startX + i * nodeSpacing;
  4023. const x2 = startX + (i + 1) * nodeSpacing;
  4024. // 边的可点击区域(更宽的透明线)
  4025. egoGroup.append("line")
  4026. .attr("class", "ego-edge-hitarea")
  4027. .attr("x1", x1)
  4028. .attr("y1", 0)
  4029. .attr("x2", x2)
  4030. .attr("y2", 0)
  4031. .attr("stroke", "transparent")
  4032. .attr("stroke-width", 15)
  4033. .style("cursor", "pointer")
  4034. .on("click", (event) => {{
  4035. event.stopPropagation();
  4036. handleEdgeClick(edge.源节点ID, edge.目标节点ID, edge.边类型);
  4037. }});
  4038. // 可见的边
  4039. egoGroup.append("line")
  4040. .attr("class", "ego-edge")
  4041. .attr("x1", x1)
  4042. .attr("y1", 0)
  4043. .attr("x2", x2)
  4044. .attr("y2", 0)
  4045. .attr("stroke", edgeColors[edge.边类型] || "#666")
  4046. .attr("stroke-width", 3)
  4047. .attr("stroke-opacity", 0.8)
  4048. .style("pointer-events", "none");
  4049. // 边类型标签
  4050. egoGroup.append("text")
  4051. .attr("x", (x1 + x2) / 2)
  4052. .attr("y", 20)
  4053. .attr("text-anchor", "middle")
  4054. .attr("fill", "#999")
  4055. .attr("font-size", "9px")
  4056. .style("pointer-events", "none")
  4057. .text(edge.边类型);
  4058. }});
  4059. // 绘制节点
  4060. pathNodes.forEach((nodeData, i) => {{
  4061. const x = startX + i * nodeSpacing;
  4062. const nodeGroup = egoGroup.append("g")
  4063. .attr("class", "ego-node")
  4064. .attr("transform", `translate(${{x}}, 0)`)
  4065. .style("cursor", "pointer")
  4066. .on("click", (event) => {{
  4067. event.stopPropagation();
  4068. handleNodeClick(nodeData.节点ID, nodeData.节点名称 || nodeData.name);
  4069. }});
  4070. const nodeSize = 15;
  4071. const nodeColor = getNodeColor(nodeData);
  4072. if (nodeData.节点类型 === "分类") {{
  4073. nodeGroup.append("rect")
  4074. .attr("width", nodeSize * 2)
  4075. .attr("height", nodeSize * 2)
  4076. .attr("x", -nodeSize)
  4077. .attr("y", -nodeSize)
  4078. .attr("fill", nodeColor)
  4079. .attr("stroke", "rgba(255,255,255,0.5)")
  4080. .attr("stroke-width", 2)
  4081. .attr("rx", 2);
  4082. }} else {{
  4083. nodeGroup.append("circle")
  4084. .attr("r", nodeSize)
  4085. .attr("fill", nodeColor)
  4086. .attr("stroke", "rgba(255,255,255,0.5)")
  4087. .attr("stroke-width", 2);
  4088. }}
  4089. // 节点名称
  4090. nodeGroup.append("text")
  4091. .attr("dy", -nodeSize - 8)
  4092. .attr("text-anchor", "middle")
  4093. .attr("fill", "#fff")
  4094. .attr("font-size", "10px")
  4095. .style("pointer-events", "none")
  4096. .text(nodeData.节点名称 || nodeData.name || nodeData.节点ID);
  4097. }});
  4098. }}
  4099. // 渲染单条边和两个节点(点击树边时调用)
  4100. function renderEgoGraphEdge(edgeData, sourceNode, targetNode) {{
  4101. // 显示关系图容器
  4102. document.getElementById("ego-container").style.display = "block";
  4103. const egoGroup = d3.select(".ego-graph-content");
  4104. if (egoGroup.empty()) return;
  4105. // 停止之前的模拟
  4106. if (currentEgoSimulation) {{
  4107. currentEgoSimulation.stop();
  4108. currentEgoSimulation = null;
  4109. }}
  4110. // 清除旧内容
  4111. egoGroup.selectAll("*").remove();
  4112. // 更新顶部标题
  4113. document.getElementById("ego-node-name").textContent = edgeData.边类型;
  4114. document.getElementById("ego-stats").textContent = "2节点 1边";
  4115. const radius = 160;
  4116. // 边类型颜色
  4117. const edgeColors = {{
  4118. "属于": "#9b59b6",
  4119. "包含": "#ffb6c1",
  4120. "分类共现(跨点)": "#2ecc71",
  4121. "分类共现(点内)": "#3498db",
  4122. "标签共现": "#f39c12"
  4123. }};
  4124. // 维度颜色
  4125. const dimColors = {{
  4126. "灵感点": "#f39c12",
  4127. "目的点": "#3498db",
  4128. "关键点": "#9b59b6"
  4129. }};
  4130. // 获取节点颜色
  4131. function getNodeColor(nodeData) {{
  4132. const level = nodeData.节点层级 || "";
  4133. if (level.includes("灵感点")) return dimColors["灵感点"];
  4134. if (level.includes("目的点")) return dimColors["目的点"];
  4135. if (level.includes("关键点")) return dimColors["关键点"];
  4136. return "#888";
  4137. }}
  4138. // 两个节点的位置
  4139. const srcX = -60, srcY = 0;
  4140. const tgtX = 60, tgtY = 0;
  4141. // 绘制边
  4142. egoGroup.append("line")
  4143. .attr("class", "ego-edge")
  4144. .attr("x1", srcX)
  4145. .attr("y1", srcY)
  4146. .attr("x2", tgtX)
  4147. .attr("y2", tgtY)
  4148. .attr("stroke", edgeColors[edgeData.边类型] || "#666")
  4149. .attr("stroke-width", 3)
  4150. .attr("stroke-opacity", 0.8);
  4151. // 获取节点数据
  4152. const srcData = sourceNode ? sourceNode.data : {{}};
  4153. const tgtData = targetNode ? targetNode.data : {{}};
  4154. // 绘制源节点
  4155. const srcGroup = egoGroup.append("g")
  4156. .attr("class", "ego-node")
  4157. .attr("transform", `translate(${{srcX}}, ${{srcY}})`);
  4158. const srcSize = 15;
  4159. const srcColor = getNodeColor(srcData);
  4160. if (srcData.节点类型 === "分类") {{
  4161. srcGroup.append("rect")
  4162. .attr("width", srcSize * 2)
  4163. .attr("height", srcSize * 2)
  4164. .attr("x", -srcSize)
  4165. .attr("y", -srcSize)
  4166. .attr("fill", srcColor)
  4167. .attr("stroke", "rgba(255,255,255,0.5)")
  4168. .attr("stroke-width", 2)
  4169. .attr("rx", 2);
  4170. }} else {{
  4171. srcGroup.append("circle")
  4172. .attr("r", srcSize)
  4173. .attr("fill", srcColor)
  4174. .attr("stroke", "rgba(255,255,255,0.5)")
  4175. .attr("stroke-width", 2);
  4176. }}
  4177. srcGroup.append("text")
  4178. .attr("dy", -srcSize - 8)
  4179. .attr("text-anchor", "middle")
  4180. .attr("fill", "#fff")
  4181. .attr("font-size", "11px")
  4182. .text(srcData.节点名称 || srcData.name || "源节点");
  4183. // 绘制目标节点
  4184. const tgtGroup = egoGroup.append("g")
  4185. .attr("class", "ego-node")
  4186. .attr("transform", `translate(${{tgtX}}, ${{tgtY}})`);
  4187. const tgtSize = 15;
  4188. const tgtColor = getNodeColor(tgtData);
  4189. if (tgtData.节点类型 === "分类") {{
  4190. tgtGroup.append("rect")
  4191. .attr("width", tgtSize * 2)
  4192. .attr("height", tgtSize * 2)
  4193. .attr("x", -tgtSize)
  4194. .attr("y", -tgtSize)
  4195. .attr("fill", tgtColor)
  4196. .attr("stroke", "rgba(255,255,255,0.5)")
  4197. .attr("stroke-width", 2)
  4198. .attr("rx", 2);
  4199. }} else {{
  4200. tgtGroup.append("circle")
  4201. .attr("r", tgtSize)
  4202. .attr("fill", tgtColor)
  4203. .attr("stroke", "rgba(255,255,255,0.5)")
  4204. .attr("stroke-width", 2);
  4205. }}
  4206. tgtGroup.append("text")
  4207. .attr("dy", -tgtSize - 8)
  4208. .attr("text-anchor", "middle")
  4209. .attr("fill", "#fff")
  4210. .attr("font-size", "11px")
  4211. .text(tgtData.节点名称 || tgtData.name || "目标节点");
  4212. // 边标签
  4213. egoGroup.append("text")
  4214. .attr("y", 25)
  4215. .attr("text-anchor", "middle")
  4216. .attr("fill", "rgba(255,255,255,0.6)")
  4217. .attr("font-size", "10px")
  4218. .text(edgeData.边类型);
  4219. }}
  4220. // 页面加载完成后初始化
  4221. window.addEventListener("load", init);
  4222. window.addEventListener("resize", () => {{
  4223. if (currentIndex >= 0) {{
  4224. renderGraph(allGraphData[currentIndex]);
  4225. }}
  4226. }});
  4227. </script>
  4228. </body>
  4229. </html>
  4230. '''
  4231. def generate_combined_html(all_graph_data: List[Dict], persona_tree_data: Dict, output_file: Path):
  4232. """
  4233. 生成包含所有帖子图谱的HTML文件
  4234. Args:
  4235. all_graph_data: 所有帖子的图谱数据列表
  4236. persona_tree_data: 完整的人设树数据(节点和边)
  4237. output_file: 输出文件路径
  4238. """
  4239. # 生成Tab HTML
  4240. tabs_html = ""
  4241. for i, data in enumerate(all_graph_data):
  4242. post_title = data.get("postTitle", "")
  4243. # 使用帖子标题,如果太长则截断
  4244. if post_title:
  4245. tab_name = post_title[:15] + "..." if len(post_title) > 15 else post_title
  4246. else:
  4247. tab_name = f"帖子 {i+1}"
  4248. active_class = "active" if i == 0 else ""
  4249. tabs_html += f'<div class="tab {active_class}" data-index="{i}">{tab_name}</div>\n'
  4250. # 生成HTML
  4251. html_content = HTML_TEMPLATE.format(
  4252. tabs_html=tabs_html,
  4253. all_graph_data=json.dumps(all_graph_data, ensure_ascii=False),
  4254. persona_tree_data=json.dumps(persona_tree_data, ensure_ascii=False)
  4255. )
  4256. with open(output_file, "w", encoding="utf-8") as f:
  4257. f.write(html_content)
  4258. def main():
  4259. # 使用路径配置
  4260. config = PathConfig()
  4261. print(f"账号: {config.account_name}")
  4262. print(f"输出版本: {config.output_version}")
  4263. print()
  4264. # 输入目录
  4265. match_graph_dir = config.intermediate_dir / "match_graph"
  4266. # 输出文件
  4267. output_file = config.intermediate_dir / "match_graph.html"
  4268. print(f"输入目录: {match_graph_dir}")
  4269. print(f"输出文件: {output_file}")
  4270. print()
  4271. # 读取人设树中间数据
  4272. persona_tree_file = config.intermediate_dir / "persona_tree.json"
  4273. persona_tree_data = {"nodes": [], "edges": []}
  4274. if persona_tree_file.exists():
  4275. print(f"读取人设树数据: {persona_tree_file.name}")
  4276. with open(persona_tree_file, "r", encoding="utf-8") as f:
  4277. tree_data = json.load(f)
  4278. persona_tree_data["nodes"] = tree_data.get("nodes", [])
  4279. persona_tree_data["edges"] = tree_data.get("edges", [])
  4280. category_count = len([n for n in persona_tree_data["nodes"] if n.get("节点类型") == "分类"])
  4281. tag_count = len([n for n in persona_tree_data["nodes"] if n.get("节点类型") == "标签"])
  4282. print(f" 分类节点: {category_count}, 标签节点: {tag_count}")
  4283. print(f" 边数: {len(persona_tree_data['edges'])}")
  4284. print()
  4285. # 读取帖子树数据
  4286. post_trees_file = match_graph_dir / "post_trees.json"
  4287. post_trees_data = {} # postId -> postTree
  4288. if post_trees_file.exists():
  4289. print(f"读取帖子树数据: {post_trees_file.name}")
  4290. with open(post_trees_file, "r", encoding="utf-8") as f:
  4291. trees_data = json.load(f)
  4292. for tree in trees_data.get("postTrees", []):
  4293. post_trees_data[tree["postId"]] = tree
  4294. print(f" 帖子树数量: {len(post_trees_data)}")
  4295. else:
  4296. print(f"警告: 帖子树数据文件不存在: {post_trees_file}")
  4297. print(" 请先运行 build_post_tree.py 生成帖子树数据")
  4298. print()
  4299. # 读取所有匹配图谱文件
  4300. graph_files = sorted(match_graph_dir.glob("*_match_graph.json"))
  4301. print(f"找到 {len(graph_files)} 个匹配图谱文件")
  4302. # results目录(存放完整帖子详情)
  4303. results_dir = config.intermediate_dir.parent / "results"
  4304. all_graph_data = []
  4305. for i, graph_file in enumerate(graph_files, 1):
  4306. print(f" [{i}/{len(graph_files)}] 读取: {graph_file.name}")
  4307. with open(graph_file, "r", encoding="utf-8") as f:
  4308. match_graph_data = json.load(f)
  4309. post_id = match_graph_data["说明"]["帖子ID"]
  4310. # 尝试读取完整帖子详情
  4311. post_detail = {
  4312. "title": match_graph_data["说明"].get("帖子标题", ""),
  4313. "post_id": post_id
  4314. }
  4315. how_file = results_dir / f"{post_id}_how.json"
  4316. if how_file.exists():
  4317. with open(how_file, "r", encoding="utf-8") as f:
  4318. how_data = json.load(f)
  4319. if "帖子详情" in how_data:
  4320. post_detail = how_data["帖子详情"]
  4321. post_detail["post_id"] = post_id
  4322. # 获取预构建的帖子树数据
  4323. post_tree = post_trees_data.get(post_id, {})
  4324. # 提取需要的数据
  4325. graph_data = {
  4326. "postId": post_id,
  4327. "postTitle": match_graph_data["说明"].get("帖子标题", ""),
  4328. "stats": match_graph_data["说明"]["统计"],
  4329. "nodes": match_graph_data["节点列表"],
  4330. "edges": match_graph_data["边列表"],
  4331. "personaEdgeToMirrorEdges": match_graph_data.get("人设边到镜像边映射", {}),
  4332. # 预构建的帖子树数据
  4333. "postTree": post_tree,
  4334. "postDetail": post_tree.get("postDetail", post_detail)
  4335. }
  4336. all_graph_data.append(graph_data)
  4337. # 生成HTML
  4338. print("\n生成HTML文件...")
  4339. generate_combined_html(all_graph_data, persona_tree_data, output_file)
  4340. print("\n" + "="*60)
  4341. print("处理完成!")
  4342. print(f"输出文件: {output_file}")
  4343. if __name__ == "__main__":
  4344. main()