visualize_match_graph.py 229 KB

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