visualize_match_graph.py 232 KB

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