visualize_match_graph.py 230 KB

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