| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484 |
- #!/usr/bin/env python3
- # -*- coding: utf-8 -*-
- """
- 将匹配图谱数据可视化为交互式HTML文件
- 输入:match_graph目录下的JSON文件
- 输出:单个HTML文件,包含所有帖子的图谱,可通过Tab切换
- """
- import json
- from pathlib import Path
- from typing import Dict, List
- import sys
- # 添加项目根目录到路径
- project_root = Path(__file__).parent.parent.parent
- sys.path.insert(0, str(project_root))
- from script.data_processing.path_config import PathConfig
- HTML_TEMPLATE = '''<!DOCTYPE html>
- <html lang="zh-CN">
- <head>
- <meta charset="UTF-8">
- <meta name="viewport" content="width=device-width, initial-scale=1.0">
- <title>匹配图谱可视化</title>
- <script src="https://d3js.org/d3.v7.min.js"></script>
- <style>
- * {{
- margin: 0;
- padding: 0;
- box-sizing: border-box;
- }}
- body {{
- font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif;
- background: #1a1a2e;
- color: #eee;
- overflow: hidden;
- }}
- /* 自定义滚动条 */
- ::-webkit-scrollbar {{
- width: 6px;
- height: 6px;
- }}
- ::-webkit-scrollbar-track {{
- background: transparent;
- }}
- ::-webkit-scrollbar-thumb {{
- background: rgba(255,255,255,0.2);
- border-radius: 3px;
- }}
- ::-webkit-scrollbar-thumb:hover {{
- background: rgba(255,255,255,0.3);
- }}
- #container {{
- display: flex;
- height: 100vh;
- flex-direction: column;
- }}
- /* 顶部栏样式 */
- .top-bar {{
- display: flex;
- align-items: center;
- background: #0f3460;
- padding: 6px 20px;
- flex-shrink: 0;
- gap: 20px;
- }}
- .post-selector-container {{
- display: flex;
- align-items: center;
- gap: 8px;
- }}
- .post-selector-label {{
- color: #888;
- font-size: 12px;
- white-space: nowrap;
- }}
- .post-selector {{
- width: 280px;
- padding: 6px 10px;
- background: #1a1a2e;
- border: 1px solid #0f3460;
- border-radius: 4px;
- color: #fff;
- font-size: 12px;
- cursor: pointer;
- outline: none;
- transition: all 0.2s;
- }}
- .post-selector:hover {{
- border-color: #e94560;
- }}
- .post-selector:focus {{
- border-color: #e94560;
- box-shadow: 0 0 0 2px rgba(233, 69, 96, 0.2);
- }}
- .post-selector option {{
- background: #1a1a2e;
- color: #fff;
- }}
- /* 顶部图例样式 */
- .top-legend {{
- display: flex;
- align-items: center;
- gap: 6px;
- margin-left: auto;
- }}
- .top-legend-group {{
- display: flex;
- align-items: center;
- gap: 8px;
- padding: 4px 10px;
- background: rgba(0,0,0,0.3);
- border-radius: 4px;
- }}
- .top-legend-title {{
- color: #fff;
- font-size: 11px;
- font-weight: bold;
- background: #e94560;
- padding: 2px 6px;
- border-radius: 3px;
- margin-right: 6px;
- }}
- .top-legend-item {{
- display: flex;
- align-items: center;
- font-size: 11px;
- color: #fff;
- gap: 4px;
- }}
- .top-legend-circle {{
- width: 10px;
- height: 10px;
- border-radius: 50%;
- border: 1.5px solid rgba(255,255,255,0.8);
- }}
- .top-legend-square {{
- width: 9px;
- height: 9px;
- border-radius: 2px;
- border: 1.5px solid rgba(255,255,255,0.8);
- }}
- .top-legend-line {{
- width: 16px;
- height: 2px;
- }}
- .top-legend-line.dashed {{
- background: none !important;
- border-top: 2px dashed;
- }}
- .top-legend-divider {{
- width: 1px;
- height: 16px;
- background: #444;
- margin: 0 2px;
- }}
- /* 主内容区 */
- .main-content {{
- display: flex;
- flex: 1;
- overflow: hidden;
- }}
- #left-panel {{
- width: 420px;
- display: flex;
- flex-direction: column;
- border-right: 1px solid #0f3460;
- }}
- #tree-container {{
- flex: 1;
- overflow-y: auto;
- overflow-x: hidden;
- }}
- #tree-container svg {{
- display: block;
- }}
- #ego-container {{
- height: 420px;
- border-top: 1px solid #0f3460;
- display: none;
- position: relative;
- }}
- #ego-container svg {{
- display: block;
- }}
- .ego-controls {{
- position: absolute;
- top: 5px;
- left: 5px;
- right: 5px;
- z-index: 10;
- display: flex;
- justify-content: space-between;
- align-items: center;
- font-size: 10px;
- }}
- .ego-title-center {{
- color: #e94560;
- font-weight: bold;
- font-size: 12px;
- text-align: center;
- flex: 1;
- }}
- .ego-stats {{
- color: #8892b0;
- font-size: 10px;
- white-space: nowrap;
- }}
- .ego-controls label {{
- color: #8892b0;
- display: flex;
- align-items: center;
- gap: 3px;
- }}
- .ego-controls select {{
- background: #0f3460;
- color: #e6e6e6;
- border: 1px solid #1a1a2e;
- border-radius: 3px;
- padding: 3px 6px;
- font-size: 10px;
- cursor: pointer;
- }}
- .cascade-dropdown {{
- position: relative;
- }}
- .cascade-btn {{
- background: #0f3460;
- color: #e6e6e6;
- border: 1px solid #1a1a2e;
- border-radius: 3px;
- padding: 4px 10px;
- font-size: 10px;
- cursor: pointer;
- display: flex;
- align-items: center;
- gap: 6px;
- }}
- .cascade-btn:hover {{
- background: #1a4a7a;
- }}
- .cascade-btn::after {{
- content: "▼";
- font-size: 8px;
- opacity: 0.6;
- }}
- .cascade-menu {{
- position: absolute;
- top: 100%;
- left: 0;
- background: #0f3460;
- border: 1px solid #1a1a2e;
- border-radius: 3px;
- display: none;
- z-index: 100;
- box-shadow: 0 4px 12px rgba(0,0,0,0.3);
- flex-direction: row;
- }}
- .cascade-menu.show {{
- display: flex;
- }}
- .cascade-levels {{
- border-right: 1px solid #1a1a2e;
- padding: 4px 0;
- min-width: 50px;
- }}
- .cascade-level-item {{
- padding: 6px 12px;
- cursor: pointer;
- color: #e6e6e6;
- font-size: 10px;
- display: flex;
- align-items: center;
- justify-content: space-between;
- }}
- .cascade-level-item:hover {{
- background: rgba(233, 69, 96, 0.2);
- }}
- .cascade-level-item.active {{
- background: rgba(233, 69, 96, 0.3);
- color: #e94560;
- }}
- .cascade-level-item::after {{
- content: "›";
- margin-left: 8px;
- opacity: 0.5;
- }}
- .cascade-edges {{
- padding: 4px 0;
- min-width: 100px;
- max-height: 300px;
- overflow-y: auto;
- }}
- .cascade-edge-group {{
- display: none;
- }}
- .cascade-edge-group.active {{
- display: block;
- }}
- .cascade-edge-group-header {{
- color: #e94560;
- font-weight: bold;
- font-size: 9px;
- padding: 4px 10px 2px;
- display: flex;
- align-items: center;
- justify-content: space-between;
- }}
- .select-all {{
- font-weight: normal;
- color: #8892b0;
- font-size: 9px;
- cursor: pointer;
- display: flex;
- align-items: center;
- gap: 3px;
- }}
- .select-all input {{
- width: 10px;
- height: 10px;
- cursor: pointer;
- }}
- .header-actions {{
- display: flex;
- align-items: center;
- gap: 6px;
- }}
- .invert-btn, .reset-btn {{
- color: #8892b0;
- cursor: pointer;
- font-size: 9px;
- }}
- .invert-btn:hover {{
- color: #e94560;
- }}
- .reset-btn:hover {{
- color: #2ecc71;
- }}
- .cascade-edge-item {{
- display: flex;
- align-items: center;
- gap: 6px;
- padding: 4px 10px;
- cursor: pointer;
- color: #e6e6e6;
- font-size: 10px;
- }}
- .cascade-edge-item:hover {{
- background: rgba(233, 69, 96, 0.15);
- }}
- .cascade-edge-item input {{
- display: none;
- }}
- .cascade-edge-item .edge-color {{
- width: 12px;
- height: 12px;
- border-radius: 2px;
- border: 1px solid #333;
- opacity: 0.3;
- }}
- .cascade-edge-item input:checked + .edge-color {{
- opacity: 1;
- }}
- #graph {{
- flex: 1;
- position: relative;
- overflow: auto;
- }}
- #sidebar {{
- width: 300px;
- background: #16213e;
- padding: 15px;
- overflow-y: auto;
- border-left: 1px solid #0f3460;
- display: flex;
- flex-direction: column;
- }}
- .match-list-panel {{
- margin-bottom: 15px;
- border-bottom: 1px solid #0f3460;
- padding-bottom: 10px;
- }}
- .match-list-panel h3 {{
- font-size: 13px;
- margin-bottom: 8px;
- color: #e94560;
- }}
- .match-list {{
- max-height: 200px;
- overflow-y: auto;
- }}
- .match-item {{
- display: flex;
- align-items: center;
- padding: 6px 8px;
- margin-bottom: 4px;
- background: rgba(233, 69, 96, 0.1);
- border-radius: 4px;
- cursor: pointer;
- font-size: 11px;
- gap: 8px;
- }}
- .match-item:hover {{
- background: rgba(233, 69, 96, 0.2);
- }}
- .match-item.active {{
- background: rgba(233, 69, 96, 0.3);
- border: 1px solid #e94560;
- }}
- .match-item .score {{
- background: #e94560;
- color: #fff;
- padding: 2px 6px;
- border-radius: 3px;
- font-weight: bold;
- min-width: 40px;
- text-align: center;
- }}
- .match-item .score.high {{
- background: #27ae60;
- }}
- .match-item .score.medium {{
- background: #f39c12;
- }}
- .match-item .names {{
- flex: 1;
- overflow: hidden;
- text-overflow: ellipsis;
- white-space: nowrap;
- }}
- #persona-tree-panel {{
- flex: 1;
- overflow-y: auto;
- margin-top: 15px;
- border-top: 1px solid #0f3460;
- padding-top: 10px;
- }}
- .tree-dimension {{
- margin-bottom: 15px;
- }}
- .tree-dimension-title {{
- font-size: 12px;
- font-weight: bold;
- padding: 5px 8px;
- border-radius: 4px;
- margin-bottom: 5px;
- cursor: pointer;
- display: flex;
- align-items: center;
- gap: 5px;
- }}
- .tree-dimension-title:hover {{
- opacity: 0.8;
- }}
- .tree-dimension-title .toggle {{
- font-size: 10px;
- transition: transform 0.2s;
- }}
- .tree-dimension-title.collapsed .toggle {{
- transform: rotate(-90deg);
- }}
- .tree-dimension.inspiration .tree-dimension-title {{
- background: rgba(243, 156, 18, 0.2);
- color: #f39c12;
- }}
- .tree-dimension.purpose .tree-dimension-title {{
- background: rgba(52, 152, 219, 0.2);
- color: #3498db;
- }}
- .tree-dimension.key .tree-dimension-title {{
- background: rgba(155, 89, 182, 0.2);
- color: #9b59b6;
- }}
- .tree-list {{
- list-style: none;
- padding-left: 0;
- margin: 0;
- font-size: 11px;
- }}
- .tree-list.collapsed {{
- display: none;
- }}
- .tree-item {{
- padding: 3px 0;
- color: #aaa;
- cursor: pointer;
- border-radius: 3px;
- padding: 3px 6px;
- margin: 1px 0;
- }}
- .tree-item:hover {{
- background: rgba(255,255,255,0.08);
- color: #fff;
- }}
- .tree-item.matched {{
- color: #2ecc71;
- font-weight: 500;
- }}
- .tree-item .indent {{
- display: inline-block;
- width: 12px;
- color: #555;
- }}
- h1 {{
- font-size: 15px;
- margin-bottom: 10px;
- color: #e94560;
- }}
- h2 {{
- font-size: 12px;
- margin: 10px 0 6px;
- color: #0f9b8e;
- }}
- .detail-panel {{
- margin-top: 20px;
- padding: 15px;
- background: #0f3460;
- border-radius: 8px;
- display: none;
- }}
- .detail-panel.active {{
- display: block;
- }}
- .detail-panel h3 {{
- font-size: 14px;
- margin-bottom: 10px;
- color: #e94560;
- }}
- .detail-panel p {{
- font-size: 12px;
- line-height: 1.6;
- color: #ccc;
- margin: 5px 0;
- }}
- .detail-panel .label {{
- color: #888;
- }}
- .detail-panel .close-btn {{
- position: absolute;
- top: 10px;
- right: 10px;
- background: none;
- border: none;
- color: #888;
- cursor: pointer;
- font-size: 16px;
- }}
- .detail-panel .close-btn:hover {{
- color: #e94560;
- }}
- .detail-panel-wrapper {{
- position: relative;
- }}
- .similarity-score {{
- background: #e94560;
- color: #fff;
- padding: 2px 6px;
- border-radius: 4px;
- font-weight: bold;
- }}
- .edge-description {{
- background: #1a1a2e;
- padding: 10px;
- border-radius: 4px;
- margin-top: 8px;
- font-size: 11px;
- line-height: 1.5;
- }}
- .edge-list {{
- background: #1a1a2e;
- padding: 8px;
- border-radius: 4px;
- margin-top: 4px;
- font-size: 11px;
- }}
- .edge-type-item {{
- display: flex;
- justify-content: space-between;
- padding: 2px 0;
- border-bottom: 1px solid rgba(255,255,255,0.05);
- }}
- .edge-type {{
- color: #aaa;
- }}
- .edge-count {{
- color: #e94560;
- font-weight: bold;
- }}
- .edge-detail {{
- padding: 3px 0;
- color: #888;
- font-size: 10px;
- border-left: 2px solid #333;
- padding-left: 8px;
- margin: 2px 0;
- }}
- .edge-type-tag {{
- background: rgba(255,255,255,0.1);
- padding: 1px 4px;
- border-radius: 2px;
- font-size: 9px;
- margin-left: 4px;
- }}
- .edge-more {{
- color: #666;
- font-size: 10px;
- text-align: center;
- padding: 4px 0;
- }}
- .edge-empty {{
- color: #555;
- font-size: 10px;
- padding: 4px 0;
- }}
- svg {{
- width: 100%;
- display: block; /* 避免底部多余空间 */
- }}
- .node {{
- cursor: pointer;
- }}
- .node circle, .node rect, .node polygon {{
- stroke-width: 3px;
- }}
- .node .post-point-node {{
- stroke: #fff;
- stroke-width: 4px;
- }}
- .node .post-node,
- .node .persona-node {{
- stroke: #fff;
- }}
- .node text {{
- font-size: 11px;
- fill: #fff;
- pointer-events: none;
- }}
- .link {{
- stroke-opacity: 0.7;
- }}
- .link-hitarea {{
- stroke: transparent;
- stroke-width: 15px;
- cursor: pointer;
- fill: none;
- }}
- .link-hitarea:hover + .link {{
- stroke-opacity: 1;
- stroke-width: 3px;
- }}
- .edge-label {{
- font-size: 10px;
- fill: #fff;
- pointer-events: none;
- text-anchor: middle;
- }}
- .edge-label-bg {{
- fill: rgba(0,0,0,0.7);
- }}
- .link.match-same {{
- stroke: #e94560;
- }}
- .link.match-similar {{
- stroke: #e94560;
- stroke-dasharray: 5,5;
- }}
- .link.category-cross {{
- stroke: #2ecc71;
- }}
- .link.category-intra {{
- stroke: #3498db;
- }}
- .link.tag-cooccur {{
- stroke: #f39c12;
- }}
- .link.belong {{
- stroke: #9b59b6;
- }}
- .link.contain {{
- stroke: #8e44ad;
- stroke-dasharray: 2,2;
- }}
- /* 镜像边样式(实线,颜色与原边相同) */
- .link.mirror-category-cross {{
- stroke: #2ecc71;
- }}
- .link.mirror-category-intra {{
- stroke: #3498db;
- }}
- .link.mirror-tag-cooccur {{
- stroke: #f39c12;
- }}
- .link.mirror-belong {{
- stroke: #9b59b6;
- }}
- .link.mirror-contain {{
- stroke: #8e44ad;
- }}
- /* 二阶边现在使用与镜像边相同的样式(基于原始边类型) */
- /* 高亮/灰化样式 */
- .node.dimmed circle, .node.dimmed rect, .node.dimmed polygon {{
- opacity: 0.15 !important;
- }}
- .node.dimmed text {{
- opacity: 0.15 !important;
- }}
- .link-group.dimmed .link {{
- stroke-opacity: 0.08 !important;
- }}
- .link-group.dimmed .edge-label-group {{
- opacity: 0.15 !important;
- }}
- .node.highlighted circle, .node.highlighted rect, .node.highlighted polygon {{
- stroke: #fff !important;
- stroke-width: 4px !important;
- filter: drop-shadow(0 0 8px rgba(255,255,255,0.5));
- }}
- .link-group.highlighted .link {{
- stroke-opacity: 1 !important;
- stroke-width: 3px !important;
- filter: drop-shadow(0 0 4px rgba(255,255,255,0.3));
- }}
- .tooltip {{
- position: absolute;
- background: rgba(0,0,0,0.9);
- color: #fff;
- padding: 10px 15px;
- border-radius: 6px;
- font-size: 12px;
- pointer-events: none;
- max-width: 300px;
- z-index: 1000;
- display: none;
- }}
- .controls {{
- background: rgba(15, 52, 96, 0.5);
- padding: 12px;
- border-radius: 8px;
- margin-top: auto;
- border-top: 1px solid #0f3460;
- padding-top: 15px;
- }}
- .controls button {{
- background: #0f3460;
- color: #fff;
- border: none;
- padding: 8px 15px;
- margin: 5px;
- border-radius: 4px;
- cursor: pointer;
- font-size: 12px;
- }}
- .controls button:hover {{
- background: #e94560;
- }}
- .controls button.active {{
- background: #e94560;
- }}
- .controls .control-group {{
- margin-top: 10px;
- padding-top: 10px;
- border-top: 1px solid rgba(255,255,255,0.1);
- }}
- .controls .control-label {{
- font-size: 11px;
- color: #888;
- margin-bottom: 5px;
- }}
- .controls select {{
- background: #0f3460;
- color: #fff;
- border: none;
- padding: 6px 10px;
- border-radius: 4px;
- font-size: 12px;
- cursor: pointer;
- }}
- /* 关系子图节点样式 */
- .ego-node {{
- cursor: pointer;
- }}
- .ego-node circle {{
- stroke-width: 2px;
- }}
- .ego-node.center circle {{
- stroke: #fff;
- stroke-width: 3px;
- filter: drop-shadow(0 0 8px rgba(255,255,255,0.5));
- }}
- .ego-node text {{
- font-size: 10px;
- fill: #fff;
- pointer-events: none;
- }}
- .ego-edge {{
- stroke-opacity: 0.6;
- stroke-width: 1.5;
- }}
- /* 帖子详情模态框 */
- .post-detail-modal {{
- display: none;
- position: fixed;
- z-index: 4000;
- left: 0;
- top: 0;
- width: 100%;
- height: 100%;
- background: rgba(0, 0, 0, 0.7);
- overflow: auto;
- }}
- .post-detail-modal.active {{
- display: flex;
- align-items: center;
- justify-content: center;
- padding: 40px 20px;
- }}
- .post-detail-content {{
- position: relative;
- background: white;
- border-radius: 16px;
- max-width: 900px;
- width: 100%;
- max-height: 90vh;
- overflow-y: auto;
- box-shadow: 0 20px 60px rgba(0,0,0,0.3);
- }}
- .post-detail-close {{
- position: sticky;
- top: 20px;
- right: 20px;
- float: right;
- font-size: 36px;
- font-weight: 300;
- color: #9ca3af;
- background: white;
- border: none;
- cursor: pointer;
- width: 40px;
- height: 40px;
- border-radius: 50%;
- display: flex;
- align-items: center;
- justify-content: center;
- z-index: 10;
- box-shadow: 0 2px 8px rgba(0,0,0,0.1);
- }}
- .post-detail-close:hover {{
- color: #ef4444;
- background: #fee2e2;
- }}
- .post-detail-header {{
- padding: 40px 40px 20px 40px;
- border-bottom: 2px solid #e5e7eb;
- }}
- .post-detail-title {{
- font-size: 28px;
- font-weight: bold;
- color: #111827;
- line-height: 1.4;
- margin-bottom: 15px;
- }}
- .post-detail-meta {{
- display: flex;
- justify-content: space-between;
- align-items: center;
- color: #6b7280;
- font-size: 14px;
- gap: 20px;
- }}
- .post-detail-stats {{
- display: flex;
- gap: 15px;
- font-weight: 500;
- }}
- .post-detail-body {{
- padding: 30px 40px;
- }}
- .post-detail-desc {{
- font-size: 16px;
- line-height: 1.8;
- color: #374151;
- margin-bottom: 25px;
- white-space: pre-wrap;
- }}
- .post-detail-images {{
- display: grid;
- grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
- gap: 15px;
- }}
- .post-detail-image {{
- width: 100%;
- border-radius: 12px;
- object-fit: cover;
- }}
- .post-detail-footer {{
- padding: 20px 40px 30px;
- text-align: center;
- border-top: 1px solid #e5e7eb;
- }}
- .post-detail-link {{
- display: inline-block;
- padding: 12px 30px;
- background: linear-gradient(135deg, #ff2442 0%, #ff6b81 100%);
- color: white;
- text-decoration: none;
- border-radius: 25px;
- font-weight: 600;
- }}
- /* 帖子树根节点卡片 */
- .post-card {{
- background: linear-gradient(135deg, #1a1a2e 0%, #16213e 100%);
- border: 2px solid #fff;
- border-radius: 12px;
- cursor: pointer;
- transition: all 0.3s ease;
- box-shadow: 0 4px 15px rgba(255, 255, 255, 0.2);
- height: 100%;
- display: flex;
- flex-direction: column;
- justify-content: center;
- }}
- .post-card:hover {{
- transform: scale(1.05);
- box-shadow: 0 6px 25px rgba(255, 255, 255, 0.4);
- border-color: #fff;
- }}
- .post-card-header {{
- display: flex;
- gap: 10px;
- align-items: center;
- }}
- .post-card-thumbnail-wrapper {{
- position: relative;
- flex-shrink: 0;
- border-radius: 8px;
- overflow: hidden;
- }}
- .post-card-thumbnail {{
- object-fit: cover;
- border-radius: 8px;
- }}
- .post-card-image-count {{
- position: absolute;
- bottom: 2px;
- right: 2px;
- background: rgba(0,0,0,0.7);
- color: #fff;
- padding: 1px 4px;
- border-radius: 3px;
- }}
- .post-card-thumbnail-placeholder {{
- background: linear-gradient(135deg, #0f3460 0%, #1a1a2e 100%);
- border-radius: 8px;
- display: flex;
- align-items: center;
- justify-content: center;
- color: #e94560;
- }}
- .post-card-info {{
- flex: 1;
- overflow: hidden;
- }}
- .post-card-title {{
- color: #fff;
- font-weight: 600;
- line-height: 1.3;
- display: -webkit-box;
- -webkit-box-orient: vertical;
- overflow: hidden;
- text-overflow: ellipsis;
- }}
- .post-card-stats {{
- color: #8892b0;
- display: flex;
- gap: 8px;
- margin-top: 4px;
- }}
- </style>
- </head>
- <body>
- <div id="container">
- <div class="top-bar">
- <div class="post-selector-container">
- <span class="post-selector-label">帖子:</span>
- <select class="post-selector" id="post-selector" onchange="switchTab(this.value)">
- {tabs_html}
- </select>
- </div>
- <div class="top-legend">
- <div class="top-legend-group">
- <span class="top-legend-title">点形状:</span>
- <div class="top-legend-item"><div class="top-legend-circle" style="background:#888;"></div>标签</div>
- <div class="top-legend-item"><div class="top-legend-square" style="background:#888;"></div>分类</div>
- </div>
- <div class="top-legend-group">
- <span class="top-legend-title">点颜色:</span>
- <div class="top-legend-item"><div class="top-legend-circle" style="background:#f39c12;"></div>灵感</div>
- <div class="top-legend-item"><div class="top-legend-circle" style="background:#3498db;"></div>目的</div>
- <div class="top-legend-item"><div class="top-legend-circle" style="background:#9b59b6;"></div>关键</div>
- </div>
- <div class="top-legend-group">
- <span class="top-legend-title">边:</span>
- <div class="top-legend-item"><div class="top-legend-line" style="background:#e94560;"></div>相同</div>
- <div class="top-legend-item"><div class="top-legend-line dashed" style="border-color:#e94560;"></div>相似</div>
- <div class="top-legend-divider"></div>
- <div class="top-legend-item"><div class="top-legend-line" style="background:#9b59b6;"></div>属于</div>
- <div class="top-legend-item"><div class="top-legend-line" style="background:#3498db;"></div>包含</div>
- <div class="top-legend-item"><div class="top-legend-line" style="background:#2ecc71;"></div>分类共现</div>
- <div class="top-legend-item"><div class="top-legend-line" style="background:#f39c12;"></div>标签共现</div>
- </div>
- </div>
- </div>
- <div class="main-content">
- <div id="left-panel">
- <div id="tree-container"></div>
- <div id="ego-container">
- <div class="ego-controls">
- <div class="cascade-dropdown">
- <div class="cascade-btn" onclick="toggleCascadeMenu()">
- <span id="cascade-label">1级</span>
- </div>
- <div class="cascade-menu" id="cascade-menu">
- <div class="cascade-levels">
- <div class="cascade-level-item active" data-level="1" onclick="selectLevel(1)">1级</div>
- <div class="cascade-level-item" data-level="2" onclick="selectLevel(2)">2级</div>
- <div class="cascade-level-item" data-level="3" onclick="selectLevel(3)">3级</div>
- </div>
- <div class="cascade-edges">
- <div class="cascade-edge-group active" data-level="1">
- <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>
- <label class="cascade-edge-item"><input type="checkbox" data-level="1" data-type="属于" checked><span class="edge-color" style="background:#9b59b6"></span>属于</label>
- <label class="cascade-edge-item"><input type="checkbox" data-level="1" data-type="包含" checked><span class="edge-color" style="background:#3498db"></span>包含</label>
- <label class="cascade-edge-item"><input type="checkbox" data-level="1" data-type="分类共现(跨点)" checked><span class="edge-color" style="background:#2ecc71"></span>跨点共现</label>
- <label class="cascade-edge-item"><input type="checkbox" data-level="1" data-type="分类共现(点内)" checked><span class="edge-color" style="background:#2ecc71"></span>点内共现</label>
- <label class="cascade-edge-item"><input type="checkbox" data-level="1" data-type="标签共现" checked><span class="edge-color" style="background:#f39c12"></span>标签共现</label>
- </div>
- <div class="cascade-edge-group" data-level="2">
- <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>
- <label class="cascade-edge-item"><input type="checkbox" data-level="2" data-type="属于"><span class="edge-color" style="background:#9b59b6"></span>属于</label>
- <label class="cascade-edge-item"><input type="checkbox" data-level="2" data-type="包含"><span class="edge-color" style="background:#3498db"></span>包含</label>
- <label class="cascade-edge-item"><input type="checkbox" data-level="2" data-type="分类共现(跨点)"><span class="edge-color" style="background:#2ecc71"></span>跨点共现</label>
- <label class="cascade-edge-item"><input type="checkbox" data-level="2" data-type="分类共现(点内)"><span class="edge-color" style="background:#2ecc71"></span>点内共现</label>
- <label class="cascade-edge-item"><input type="checkbox" data-level="2" data-type="标签共现"><span class="edge-color" style="background:#f39c12"></span>标签共现</label>
- </div>
- <div class="cascade-edge-group" data-level="3">
- <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>
- <label class="cascade-edge-item"><input type="checkbox" data-level="3" data-type="属于"><span class="edge-color" style="background:#9b59b6"></span>属于</label>
- <label class="cascade-edge-item"><input type="checkbox" data-level="3" data-type="包含"><span class="edge-color" style="background:#3498db"></span>包含</label>
- <label class="cascade-edge-item"><input type="checkbox" data-level="3" data-type="分类共现(跨点)"><span class="edge-color" style="background:#2ecc71"></span>跨点共现</label>
- <label class="cascade-edge-item"><input type="checkbox" data-level="3" data-type="分类共现(点内)"><span class="edge-color" style="background:#2ecc71"></span>点内共现</label>
- <label class="cascade-edge-item"><input type="checkbox" data-level="3" data-type="标签共现"><span class="edge-color" style="background:#f39c12"></span>标签共现</label>
- </div>
- </div>
- </div>
- </div>
- <div class="ego-title-center" id="ego-node-name"></div>
- <div class="ego-stats" id="ego-stats"></div>
- </div>
- </div>
- </div>
- <div id="graph">
- <div class="tooltip" id="tooltip"></div>
- </div>
- <div id="sidebar">
- <div class="match-list-panel">
- <h3>帖子标签匹配人设结果 <span id="matchCount">(0)</span></h3>
- <div id="matchList" class="match-list"></div>
- </div>
- <div class="detail-panel active" id="detailPanel">
- <h3 id="detailTitle">点击节点或边查看详情</h3>
- <div id="detailContent">
- <p style="color: #888; font-size: 11px;">点击图中的节点或边,这里会显示详细信息</p>
- </div>
- </div>
- </div>
- </div>
- </div>
- <script>
- // 所有帖子的图谱数据
- const allGraphData = {all_graph_data};
- // 完整的人设树数据(所有人设节点和属于边)
- const personaTreeData = {persona_tree_data};
- // 当前选中的帖子索引
- let currentIndex = 0;
- let simulation = null;
- let svg = null;
- let g = null;
- let treeSvg = null; // 人设树独立SVG
- let treeG = null; // 人设树group
- let egoSvg = null; // 关系图独立SVG
- let egoG = null; // 关系图group
- let zoom = null;
- let showLabels = true;
- let showCrossLayerEdges = false; // 跨层边默认隐藏
- let isCrossLayerEdge = null; // 跨层边判断函数(在renderGraph中设置)
- // 人设树配置
- let showTreeTags = true; // 是否显示标签节点
- let treeMaxDepth = 0; // 显示的最大层数(0=全部)
- // 切换标签显示
- function toggleTreeTags() {{
- showTreeTags = !showTreeTags;
- const btn = document.getElementById("treeTagBtn");
- btn.textContent = showTreeTags ? "显示标签" : "隐藏标签";
- btn.classList.toggle("active", showTreeTags);
- // 重新渲染当前图谱
- renderGraph(allGraphData[currentIndex]);
- }}
- // 设置树的显示层数
- function setTreeDepth(depth) {{
- treeMaxDepth = parseInt(depth);
- // 重新渲染当前图谱
- renderGraph(allGraphData[currentIndex]);
- }}
- // 初始化
- function init() {{
- const container = document.getElementById("graph");
- const treeContainer = document.getElementById("tree-container");
- const width = container.clientWidth;
- const height = container.clientHeight;
- // 创建圆形层SVG
- svg = d3.select("#graph")
- .append("svg")
- .attr("width", width)
- .attr("height", height);
- g = svg.append("g");
- zoom = d3.zoom()
- .scaleExtent([0.1, 4])
- .on("zoom", (event) => {{
- g.attr("transform", event.transform);
- }});
- svg.call(zoom);
- // 创建人设树SVG(独立可滚动)
- treeSvg = d3.select("#tree-container")
- .append("svg")
- .attr("width", 400);
- treeG = treeSvg.append("g");
- // 创建关系图SVG(在独立的ego-container中)
- egoSvg = d3.select("#ego-container")
- .append("svg")
- .attr("width", 400)
- .attr("height", 400);
- egoG = egoSvg.append("g");
- // 关系图缩放
- const egoZoom = d3.zoom()
- .scaleExtent([0.3, 3])
- .on("zoom", (event) => {{
- egoG.attr("transform", event.transform);
- }});
- egoSvg.call(egoZoom);
- // 绑定关系图控制面板事件
- // 全选复选框事件
- document.querySelectorAll('.select-all input').forEach(cb => {{
- cb.addEventListener('change', (e) => {{
- const level = e.target.dataset.level;
- const checked = e.target.checked;
- // 设置该层级所有边类型复选框
- document.querySelectorAll(`.cascade-edge-item input[data-level="${{level}}"]`).forEach(item => {{
- item.checked = checked;
- }});
- // 重新渲染关系图和人设树高亮
- if (currentEgoCenterNodeId) {{
- handleNodeClick(currentEgoCenterNodeId, currentEgoCenterNodeName);
- }}
- }});
- }});
- // 边类型复选框变化事件
- document.querySelectorAll('.cascade-edge-item input').forEach(cb => {{
- cb.addEventListener('change', (e) => {{
- // 更新全选复选框状态
- const level = e.target.dataset.level;
- const allItems = document.querySelectorAll(`.cascade-edge-item input[data-level="${{level}}"]`);
- const checkedItems = document.querySelectorAll(`.cascade-edge-item input[data-level="${{level}}"]:checked`);
- const selectAllCb = document.querySelector(`.select-all input[data-level="${{level}}"]`);
- selectAllCb.checked = allItems.length === checkedItems.length;
- // 重新渲染关系图和人设树高亮
- if (currentEgoCenterNodeId) {{
- handleNodeClick(currentEgoCenterNodeId, currentEgoCenterNodeName);
- }}
- }});
- }});
- // 点击页面其他地方关闭级联菜单
- document.addEventListener('click', (e) => {{
- if (!e.target.closest('.cascade-dropdown')) {{
- document.getElementById('cascade-menu').classList.remove('show');
- }}
- }});
- // 显示第一个帖子
- switchTab(0);
- }}
- // 构建人设树数据(合并为一棵树,根节点为"人设")
- // showTreeTags: 控制是否显示标签节点
- // treeMaxDepth: 控制树的显示深度(0=全部,2=维度,3=+一层,4=+两层...)
- function buildPersonaTreeData() {{
- const dimensions = ["灵感点", "目的点", "关键点"];
- const dimColors = {{ "灵感点": "#f39c12", "目的点": "#3498db", "关键点": "#9b59b6" }};
- const dimensionChildren = [];
- let totalNodeCount = 0;
- dimensions.forEach(dim => {{
- // 根据 showTreeTags 过滤节点(独立于深度控制)
- let dimNodes = personaTreeData.nodes.filter(n => n.节点层级 === dim);
- if (!showTreeTags) {{
- dimNodes = dimNodes.filter(n => n.节点类型 !== "标签");
- }}
- if (dimNodes.length === 0) {{
- const dimNode = {{
- name: dim,
- 节点名称: dim,
- isDimension: true,
- dimColor: dimColors[dim],
- children: []
- }};
- dimensionChildren.push(dimNode);
- return;
- }}
- const nodeMap = {{}};
- dimNodes.forEach(n => nodeMap[n.节点ID] = {{ ...n, name: n.节点名称, children: [], dimColor: dimColors[dim] }});
- // 只用属于边构建父子关系
- const hierarchyEdgeTypes = ["属于"];
- const hasParent = new Set();
- personaTreeData.edges.forEach(e => {{
- if (!hierarchyEdgeTypes.includes(e.边类型)) return; // 跳过非层级边
- const srcNode = nodeMap[e.源节点ID];
- const tgtNode = nodeMap[e.目标节点ID];
- if (srcNode && tgtNode) {{
- tgtNode.children.push(srcNode);
- hasParent.add(e.源节点ID);
- }}
- }});
- const roots = dimNodes.filter(n => !hasParent.has(n.节点ID)).map(n => nodeMap[n.节点ID]);
- const dimNode = {{
- name: dim,
- 节点名称: dim,
- isDimension: true,
- dimColor: dimColors[dim],
- children: roots
- }};
- dimensionChildren.push(dimNode);
- totalNodeCount += dimNodes.length;
- }});
- // 根节点"人设"
- const rootNode = {{
- name: "人设",
- 节点名称: "人设",
- isRoot: true,
- children: dimensionChildren
- }};
- // 根据 treeMaxDepth 截断树深度(0=全部)
- // 深度1=根,深度2=维度,深度3+=子节点
- if (treeMaxDepth > 0) {{
- truncateTree(rootNode, 1, treeMaxDepth);
- }}
- return {{ root: rootNode, nodeCount: totalNodeCount }};
- }}
- // 递归截断树的深度
- function truncateTree(node, currentDepth, maxDepth) {{
- if (currentDepth >= maxDepth) {{
- node.children = [];
- return;
- }}
- if (node.children) {{
- node.children.forEach(child => truncateTree(child, currentDepth + 1, maxDepth));
- }}
- }}
- // 构建帖子树数据(从上到下:帖子 -> 维度 -> 点 -> 标签)
- function buildPostTreeData(graphData) {{
- const dimensions = ["灵感点", "目的点", "关键点"];
- const dimColors = {{ "灵感点": "#f39c12", "目的点": "#3498db", "关键点": "#9b59b6" }};
- const dimensionChildren = [];
- let totalNodeCount = 0;
- const postDetail = graphData.postDetail || {{}};
- // 获取帖子点和帖子标签
- const postPointNodes = graphData.帖子点节点列表 || [];
- const postTagNodes = graphData.帖子标签节点列表 || [];
- const belongEdges = graphData.帖子属于边列表 || [];
- // 构建节点映射
- const pointMap = {{}};
- postPointNodes.forEach(n => {{
- pointMap[n.节点ID] = {{
- ...n,
- id: n.节点ID,
- name: n.节点名称,
- nodeType: "点",
- dimColor: dimColors[n.节点层级],
- children: []
- }};
- }});
- const tagMap = {{}};
- postTagNodes.forEach(n => {{
- tagMap[n.节点ID] = {{
- ...n,
- id: n.节点ID,
- name: n.节点名称,
- nodeType: "标签",
- dimColor: dimColors[n.节点层级],
- children: []
- }};
- }});
- // 根据属于边,把标签挂到点下面
- belongEdges.forEach(e => {{
- const tagNode = tagMap[e.源节点ID];
- const pointNode = pointMap[e.目标节点ID];
- if (tagNode && pointNode) {{
- pointNode.children.push(tagNode);
- }}
- }});
- // 按维度分组点节点
- dimensions.forEach(dim => {{
- const dimPoints = postPointNodes
- .filter(n => n.节点层级 === dim)
- .map(n => pointMap[n.节点ID]);
- if (dimPoints.length > 0) {{
- const dimNode = {{
- name: dim,
- 节点名称: dim,
- isDimension: true,
- dimColor: dimColors[dim],
- children: dimPoints
- }};
- dimensionChildren.push(dimNode);
- totalNodeCount += dimPoints.length;
- dimPoints.forEach(p => totalNodeCount += p.children.length);
- }}
- }});
- // 根节点"帖子"
- const title = postDetail.title || "帖子";
- const rootNode = {{
- name: title.length > 15 ? title.substring(0, 15) + "..." : title,
- 节点名称: title,
- isRoot: true,
- postDetail: postDetail,
- children: dimensionChildren
- }};
- return {{ root: rootNode, nodeCount: totalNodeCount, tagMap: tagMap }};
- }}
- // 统一提取边的分数字段(全局函数)
- function getEdgeScore(e) {{
- if (!e.边详情) return null;
- // 优先级:相似度 > Jaccard相似度 > 重叠系数
- if (e.边详情.相似度 !== undefined) return e.边详情.相似度;
- if (e.边详情.Jaccard相似度 !== undefined) return e.边详情.Jaccard相似度;
- if (e.边详情.重叠系数 !== undefined) return e.边详情.重叠系数;
- return null;
- }}
- // 显示帖子详情模态框
- function showPostDetail(postData) {{
- if (!postData) return;
- // 生成图片HTML
- let imagesHtml = '';
- if (postData.images && postData.images.length > 0) {{
- imagesHtml = postData.images.map(img =>
- `<img src="${{img}}" class="post-detail-image" alt="图片" loading="lazy">`
- ).join('');
- }} else {{
- imagesHtml = '<div style="text-align: center; color: #9ca3af; padding: 40px;">暂无图片</div>';
- }}
- const modalHtml = `
- <div class="post-detail-content" onclick="event.stopPropagation()">
- <button class="post-detail-close" onclick="closePostDetail()">×</button>
- <div class="post-detail-header">
- <div class="post-detail-title">${{postData.title || '无标题'}}</div>
- <div class="post-detail-meta">
- <div>
- <span>👤 ${{postData.author || '未知作者'}}</span>
- <span> · 📅 ${{postData.publish_time || ''}}</span>
- </div>
- <div class="post-detail-stats">
- <span>👍 ${{postData.like_count || 0}}</span>
- <span>💬 ${{postData.comment_count || 0}}</span>
- <span>⭐ ${{postData.collect_count || 0}}</span>
- </div>
- </div>
- </div>
- <div class="post-detail-body">
- ${{postData.body_text ? `<div class="post-detail-desc">${{postData.body_text}}</div>` : '<div style="color: #9ca3af;">暂无正文</div>'}}
- <div class="post-detail-images">
- ${{imagesHtml}}
- </div>
- </div>
- <div class="post-detail-footer">
- <a href="${{postData.link || '#'}}" target="_blank" class="post-detail-link">
- 在小红书查看完整内容 →
- </a>
- </div>
- </div>
- `;
- let modal = document.getElementById('postDetailModal');
- if (!modal) {{
- modal = document.createElement('div');
- modal.id = 'postDetailModal';
- modal.className = 'post-detail-modal';
- modal.onclick = closePostDetail;
- document.body.appendChild(modal);
- }}
- modal.innerHTML = modalHtml;
- modal.classList.add('active');
- document.body.style.overflow = 'hidden';
- }}
- function closePostDetail(event) {{
- if (event && event.target !== event.currentTarget) return;
- const modal = document.getElementById('postDetailModal');
- if (modal) {{
- modal.classList.remove('active');
- document.body.style.overflow = '';
- }}
- }}
- // 切换帖子
- function switchTab(index) {{
- currentIndex = parseInt(index);
- // 更新图谱
- renderGraph(allGraphData[currentIndex]);
- }}
- // 渲染图谱
- function renderGraph(data) {{
- // 清空现有图谱
- g.selectAll("*").remove();
- treeG.selectAll("*").remove();
- if (simulation) {{
- simulation.stop();
- }}
- const container = document.getElementById("graph");
- const width = container.clientWidth;
- // 布局配置:人设树在左侧独立容器,右侧是圆形层
- const treeAreaWidth = 400; // 固定树宽度
- const circleAreaWidth = width - 40;
- const circleAreaCenterX = circleAreaWidth / 2;
- // 准备数据(过滤掉帖子点,只保留帖子标签和人设节点)
- const nodes = data.nodes
- .filter(n => !(n.节点ID.startsWith("帖子_") && n.节点类型 === "点"))
- .map(n => ({{
- ...n,
- id: n.节点ID,
- source: n.节点ID.startsWith("帖子_") ? "帖子" : "人设",
- level: n.节点层级
- }}));
- // 判断是否是帖子点节点ID
- function isPostPointId(id) {{
- return id.startsWith("帖子_") && id.includes("_点_");
- }}
- // 过滤掉引用帖子点节点的边
- const rawLinks = data.edges
- .filter(e => !isPostPointId(e.源节点ID) && !isPostPointId(e.目标节点ID))
- .map(e => ({{
- ...e,
- source: e.源节点ID,
- target: e.目标节点ID,
- type: e.边类型,
- score: getEdgeScore(e)
- }}));
- // 去重:同一对节点之间相同类型的边只保留一条
- const seenEdgeKeys = new Set();
- const links = rawLinks.filter(e => {{
- const edgeKey = [e.source, e.target].sort().join("|") + "|" + e.type;
- if (seenEdgeKeys.has(edgeKey)) return false;
- seenEdgeKeys.add(edgeKey);
- return true;
- }});
- // 分离节点类型
- const postNodes = nodes.filter(n => n.source === "帖子");
- const personaNodes = nodes.filter(n => n.source === "人设" && !n.是否扩展);
- const expandedNodes = nodes.filter(n => n.source === "人设" && n.是否扩展);
- const matchLinks = links.filter(l => l.type.startsWith("匹配_"));
- // 更新匹配列表(按分数降序)
- updateMatchList(matchLinks, nodes);
- // 构建帖子节点到人设节点的映射
- const postToPersona = {{}};
- const personaToPost = {{}};
- matchLinks.forEach(l => {{
- const sid = typeof l.source === "object" ? l.source.id : l.source;
- const tid = typeof l.target === "object" ? l.target.id : l.target;
- if (!postToPersona[sid]) postToPersona[sid] = [];
- postToPersona[sid].push(tid);
- if (!personaToPost[tid]) personaToPost[tid] = [];
- personaToPost[tid].push(sid);
- }});
- // 找出所有连通分量
- function findConnectedComponents(nodes, links) {{
- const nodeIds = new Set(nodes.map(n => n.id));
- const adj = {{}};
- nodeIds.forEach(id => adj[id] = []);
- links.forEach(l => {{
- const sid = typeof l.source === "object" ? l.source.id : l.source;
- const tid = typeof l.target === "object" ? l.target.id : l.target;
- if (nodeIds.has(sid) && nodeIds.has(tid)) {{
- adj[sid].push(tid);
- adj[tid].push(sid);
- }}
- }});
- const visited = new Set();
- const components = [];
- nodeIds.forEach(startId => {{
- if (visited.has(startId)) return;
- const component = [];
- const queue = [startId];
- while (queue.length > 0) {{
- const id = queue.shift();
- if (visited.has(id)) continue;
- visited.add(id);
- component.push(id);
- adj[id].forEach(neighbor => {{
- if (!visited.has(neighbor)) queue.push(neighbor);
- }});
- }}
- components.push(component);
- }});
- return components;
- }}
- // 按大小排序连通分量(大的在前)
- const components = findConnectedComponents(nodes, links)
- .sort((a, b) => b.length - a.length);
- console.log(`找到 ${{components.length}} 个连通分量`);
- // 为每个节点分配连通分量ID和分量内的X范围
- const nodeToComponent = {{}};
- const componentCenters = {{}};
- const componentBounds = {{}};
- const padding = 50; // 分量之间的间距
- const totalPadding = padding * (components.length - 1);
- const availableWidth = width - totalPadding - 100; // 留边距
- // 根据分量大小分配宽度
- const totalNodes = nodes.length;
- let currentX = 50; // 起始边距
- components.forEach((comp, i) => {{
- const compWidth = Math.max(150, (comp.length / totalNodes) * availableWidth);
- const centerX = currentX + compWidth / 2;
- componentCenters[i] = centerX;
- componentBounds[i] = {{ start: currentX, end: currentX + compWidth, width: compWidth }};
- comp.forEach(nodeId => {{
- nodeToComponent[nodeId] = i;
- }});
- currentX += compWidth + padding;
- }});
- // 使用重心法(Barycenter)减少边交叉
- // 迭代优化:交替调整两层节点的顺序
- const nodeTargetX = {{}};
- const personaXMap = {{}};
- // 对每个连通分量单独处理
- components.forEach((comp, compIdx) => {{
- const bounds = componentBounds[compIdx];
- const compPostNodes = postNodes.filter(n => nodeToComponent[n.id] === compIdx);
- const compPersonaNodes = personaNodes.filter(n => nodeToComponent[n.id] === compIdx);
- if (compPostNodes.length === 0 || compPersonaNodes.length === 0) {{
- // 没有匹配关系的分量,均匀分布
- const spacing = bounds.width / (comp.length + 1);
- comp.forEach((nodeId, i) => {{
- const node = nodes.find(n => n.id === nodeId);
- if (node) {{
- node.x = bounds.start + spacing * (i + 1);
- nodeTargetX[nodeId] = node.x;
- if (node.source === "人设") personaXMap[nodeId] = node.x;
- }}
- }});
- return;
- }}
- // 初始化:给人设节点一个初始顺序
- let personaOrder = compPersonaNodes.map((n, i) => ({{ node: n, order: i }}));
- // 迭代优化(3轮)
- for (let iter = 0; iter < 3; iter++) {{
- // 1. 根据人设节点位置,计算帖子节点的重心
- const postBarycenter = {{}};
- compPostNodes.forEach(pn => {{
- const matched = postToPersona[pn.id] || [];
- if (matched.length > 0) {{
- const avgOrder = matched.reduce((sum, pid) => {{
- const po = personaOrder.find(p => p.node.id === pid);
- return sum + (po ? po.order : 0);
- }}, 0) / matched.length;
- postBarycenter[pn.id] = avgOrder;
- }} else {{
- postBarycenter[pn.id] = 0;
- }}
- }});
- // 按重心排序帖子节点
- const sortedPosts = [...compPostNodes].sort((a, b) =>
- postBarycenter[a.id] - postBarycenter[b.id]
- );
- // 2. 根据帖子节点位置,重新计算人设节点的重心
- const personaBarycenter = {{}};
- compPersonaNodes.forEach(pn => {{
- const matched = personaToPost[pn.id] || [];
- if (matched.length > 0) {{
- const avgOrder = matched.reduce((sum, pid) => {{
- const idx = sortedPosts.findIndex(p => p.id === pid);
- return sum + (idx >= 0 ? idx : 0);
- }}, 0) / matched.length;
- personaBarycenter[pn.id] = avgOrder;
- }} else {{
- personaBarycenter[pn.id] = personaOrder.find(p => p.node.id === pn.id)?.order || 0;
- }}
- }});
- // 更新人设节点顺序
- personaOrder = compPersonaNodes
- .map(n => ({{ node: n, order: personaBarycenter[n.id] }}))
- .sort((a, b) => a.order - b.order)
- .map((item, i) => ({{ node: item.node, order: i }}));
- }}
- // 最终排序
- const finalPersonaOrder = personaOrder.map(p => p.node);
- const postBarycenter = {{}};
- compPostNodes.forEach(pn => {{
- const matched = postToPersona[pn.id] || [];
- if (matched.length > 0) {{
- const avgOrder = matched.reduce((sum, pid) => {{
- const idx = finalPersonaOrder.findIndex(n => n.id === pid);
- return sum + (idx >= 0 ? idx : 0);
- }}, 0) / matched.length;
- postBarycenter[pn.id] = avgOrder;
- }} else {{
- postBarycenter[pn.id] = 0;
- }}
- }});
- const finalPostOrder = [...compPostNodes].sort((a, b) =>
- postBarycenter[a.id] - postBarycenter[b.id]
- );
- // 设置位置
- const personaSpacing = bounds.width / (finalPersonaOrder.length + 1);
- finalPersonaOrder.forEach((n, i) => {{
- n.x = bounds.start + personaSpacing * (i + 1);
- nodeTargetX[n.id] = n.x;
- personaXMap[n.id] = n.x;
- }});
- const postSpacing = bounds.width / (finalPostOrder.length + 1);
- finalPostOrder.forEach((n, i) => {{
- // 帖子节点用重心位置(匹配人设的平均X)
- const matched = postToPersona[n.id] || [];
- if (matched.length > 0) {{
- const avgX = matched.reduce((sum, pid) => sum + (personaXMap[pid] || bounds.start + bounds.width/2), 0) / matched.length;
- n.x = avgX;
- }} else {{
- n.x = bounds.start + postSpacing * (i + 1);
- }}
- nodeTargetX[n.id] = n.x;
- }});
- }});
- // 节点颜色
- const levelColors = {{
- "灵感点": "#f39c12",
- "目的点": "#3498db",
- "关键点": "#9b59b6"
- }};
- // 获取节点的层级编号(三层结构:帖子标签、人设匹配1层、人设匹配2层)
- function getNodeLayer(d) {{
- if (d.source === "帖子") {{
- return 0; // 帖子标签=0
- }}
- // 人设节点:根据是否扩展分成两层
- return d.是否扩展 ? 2 : 1; // 直接匹配=1, 扩展=2
- }}
- // 统计每层节点数量(三层结构)
- const layerCounts = {{0: 0, 1: 0, 2: 0}};
- nodes.forEach(n => {{
- const layer = getNodeLayer(n);
- layerCounts[layer]++;
- }});
- console.log("每层节点数:", layerCounts);
- // 根据节点数量计算每层圆的半径
- // 三层垂直排列:帖子标签(上)+ 人设匹配1层(中)+ 人设匹配2层(下)
- const minRadius = 80;
- const maxRadius = Math.min(circleAreaWidth / 3 - 20, 180);
- const nodeSpacing = 60;
- function calcRadius(nodeCount) {{
- if (nodeCount <= 1) return minRadius;
- const circumference = nodeCount * nodeSpacing;
- const r = circumference / (2 * Math.PI);
- return Math.max(minRadius, Math.min(maxRadius, r));
- }}
- // 三层统一大小(取最大值)
- const unifiedRadius = Math.max(
- calcRadius(layerCounts[0]),
- calcRadius(layerCounts[1]),
- calcRadius(layerCounts[2])
- );
- const layerRadius = {{
- 0: unifiedRadius, // 帖子标签(上)
- 1: unifiedRadius, // 人设匹配1层(中)
- 2: unifiedRadius // 人设匹配2层(下)
- }};
- console.log("每层半径:", layerRadius);
- // 获取人设树数据(单棵树)
- const personaTree = buildPersonaTreeData();
- // 树高度自适应:根据节点数量,每个节点约12px,最小800
- const treeHeight = Math.max(800, personaTree.nodeCount * 12 + 150);
- // 关系图配置(放在树下方)
- const egoRadius = 180;
- const egoAreaHeight = egoRadius * 2 + 80;
- // 计算布局:三层垂直排列(帖子标签+人设匹配1层+人设匹配2层)
- const layerPadding = 60;
- const circleHeight = layerRadius[0] * 2 + layerPadding + layerRadius[1] * 2 + layerPadding + layerRadius[2] * 2 + layerPadding;
- const height = Math.max(circleHeight + 80, treeHeight + 80, container.clientHeight);
- // 计算每层圆心坐标(垂直居中排列)
- const layerCenterX = {{}};
- const layerCenterY = {{}};
- // 三层垂直排列,X坐标相同
- const colX = circleAreaCenterX;
- // 帖子标签(上)+ 人设匹配1层(中)+ 人设匹配2层(下)
- layerCenterX[0] = colX;
- layerCenterY[0] = layerRadius[0] + layerPadding / 2 + 20;
- layerCenterX[1] = colX;
- layerCenterY[1] = layerCenterY[0] + layerRadius[0] + layerPadding + layerRadius[1];
- layerCenterX[2] = colX;
- layerCenterY[2] = layerCenterY[1] + layerRadius[1] + layerPadding + layerRadius[2];
- console.log("每层圆心X:", layerCenterX);
- console.log("每层圆心Y:", layerCenterY);
- // 更新SVG高度
- svg.attr("height", height);
- // 获取节点的基准Y(层圆心)
- function getNodeBaseY(d) {{
- const layer = getNodeLayer(d);
- return layerCenterY[layer];
- }}
- // 获取节点的基准X(层圆心)
- function getNodeBaseX(d) {{
- const layer = getNodeLayer(d);
- return layerCenterX[layer];
- }}
- // 层边界配置(不再使用)
- const layerBounds = {{}};
- // 自定义层内排斥力(只对同层节点生效,尽量分散)
- function forceIntraLayerRepulsion(strength) {{
- let nodes;
- function force(alpha) {{
- for (let i = 0; i < nodes.length; i++) {{
- const nodeA = nodes[i];
- const layerA = getNodeLayer(nodeA);
- for (let j = i + 1; j < nodes.length; j++) {{
- const nodeB = nodes[j];
- const layerB = getNodeLayer(nodeB);
- // 只对同层节点施加排斥力
- if (layerA !== layerB) continue;
- const dx = nodeB.x - nodeA.x;
- const dy = nodeB.y - nodeA.y;
- const dist = Math.sqrt(dx * dx + dy * dy) || 1;
- const minDist = 150; // 增大最小距离,让节点更分散
- if (dist < minDist) {{
- // 排斥力随距离衰减,但基础强度更大
- const pushStrength = strength * alpha * (minDist - dist) / dist * 2;
- const px = dx * pushStrength;
- const py = dy * pushStrength;
- nodeA.vx -= px;
- nodeA.vy -= py;
- nodeB.vx += px;
- nodeB.vy += py;
- }}
- }}
- }}
- }}
- force.initialize = function(_) {{
- nodes = _;
- }};
- return force;
- }}
- // 层圆的半径(使用动态计算的 layerRadius)
- // layerRadius 和 layerCenterY 已在前面定义
- // 层边界约束力(把节点限制在层内)
- function forceLayerBoundary() {{
- let nodes;
- function force(alpha) {{
- nodes.forEach(node => {{
- const layer = getNodeLayer(node);
- const centerX = layerCenterX[layer];
- const centerY = layerCenterY[layer];
- // 使用圆形边界
- const maxRadius = layerRadius[layer] - 15;
- // 计算到圆心的距离
- const dx = node.x - centerX;
- const dy = node.y - centerY;
- const dist = Math.sqrt(dx * dx + dy * dy);
- // 如果超出圆形边界,拉回来
- if (dist > maxRadius) {{
- const scale = maxRadius / dist;
- node.x = centerX + dx * scale;
- node.y = centerY + dy * scale;
- // 阻止继续向外运动
- const angle = Math.atan2(dy, dx);
- const vOutward = node.vx * Math.cos(angle) + node.vy * Math.sin(angle);
- if (vOutward > 0) {{
- node.vx -= vOutward * Math.cos(angle);
- node.vy -= vOutward * Math.sin(angle);
- }}
- }}
- }});
- }}
- force.initialize = function(_) {{
- nodes = _;
- }};
- return force;
- }}
- // 层内圆形布局力(让同层节点围绕圆心分布)
- function forceCircularLayout(strength) {{
- let nodes;
- function force(alpha) {{
- // 按层分组(三层)
- const layerNodes = {{0: [], 1: [], 2: []}};
- nodes.forEach(node => {{
- const layer = getNodeLayer(node);
- if (layerNodes[layer]) layerNodes[layer].push(node);
- }});
- // 对每层计算布局
- Object.entries(layerNodes).forEach(([layerIdx, layerGroup]) => {{
- if (layerGroup.length === 0) return;
- const layer = parseInt(layerIdx);
- const centerX = layerCenterX[layer];
- const centerY = layerCenterY[layer];
- // 使用圆形布局
- const nodeRadius = layerRadius[layer] - 20;
- if (layerGroup.length === 1) {{
- // 单个节点放在圆心
- const node = layerGroup[0];
- node.vx += (centerX - node.x) * strength * alpha;
- node.vy += (centerY - node.y) * strength * alpha;
- return;
- }}
- // 按角度排序节点(保持相对位置稳定)
- layerGroup.forEach(node => {{
- node._angle = Math.atan2(node.y - centerY, node.x - centerX);
- }});
- layerGroup.sort((a, b) => a._angle - b._angle);
- // 均匀分布在圆周上
- const angleStep = (2 * Math.PI) / layerGroup.length;
- layerGroup.forEach((node, i) => {{
- const angle = -Math.PI / 2 + i * angleStep; // 从顶部开始
- const idealX = centerX + nodeRadius * Math.cos(angle);
- const idealY = centerY + nodeRadius * Math.sin(angle);
- node.vx += (idealX - node.x) * strength * alpha;
- node.vy += (idealY - node.y) * strength * alpha;
- }});
- }});
- }}
- force.initialize = function(_) {{
- nodes = _;
- }};
- return force;
- }}
- // 力导向模拟
- simulation = d3.forceSimulation(nodes)
- // 连线力(跨层连接)
- .force("link", d3.forceLink(links).id(d => d.id)
- .distance(d => {{
- // 跨层连线距离
- if (d.type.startsWith("匹配_") || d.type === "属于") {{
- return 150; // 跨层边
- }}
- return 60; // 同层边
- }})
- .strength(d => {{
- // 跨层边力度弱一些,不要拉扯节点出层
- if (d.type.startsWith("匹配_") || d.type === "属于") {{
- return 0.03;
- }}
- return 0.1;
- }}))
- // X方向:轻微拉向各层中心
- .force("x", d3.forceX(d => getNodeBaseX(d)).strength(0.02))
- // Y方向:轻微拉向层中心
- .force("y", d3.forceY(d => getNodeBaseY(d)).strength(0.02))
- // 层内碰撞检测
- .force("collision", d3.forceCollide().radius(30))
- // 层内排斥力(同层节点相互排斥)
- .force("intraLayer", forceIntraLayerRepulsion(0.8))
- // 层内布局(圆形或树状)
- .force("circularLayout", forceCircularLayout(0.15))
- // 层边界约束(节点不能跑出层,硬约束)
- .force("boundary", forceLayerBoundary());
- // 边类型到CSS类的映射
- const edgeTypeClass = {{
- "匹配_相同": "match-same",
- "匹配_相似": "match-similar",
- "分类共现(跨点)": "category-cross",
- "分类共现(点内)": "category-intra",
- "标签共现": "tag-cooccur",
- "属于": "belong",
- "包含": "contain",
- // 镜像边(帖子节点之间,虚线)
- "镜像_分类共现(跨点)": "mirror-category-cross",
- "镜像_分类共现(点内)": "mirror-category-intra",
- "镜像_标签共现": "mirror-tag-cooccur",
- "镜像_属于": "mirror-belong",
- "镜像_包含": "mirror-contain"
- }};
- // 获取边的CSS类(处理二阶边,映射到对应的镜像边样式)
- function getEdgeClass(edgeType) {{
- if (edgeTypeClass[edgeType]) return edgeTypeClass[edgeType];
- // 二阶边映射到对应的镜像边样式(颜色相同,都用虚线)
- if (edgeType.startsWith("二阶_")) {{
- const originalType = edgeType.replace("二阶_", "");
- const mirrorType = "镜像_" + originalType;
- if (edgeTypeClass[mirrorType]) return edgeTypeClass[mirrorType];
- }}
- return "match";
- }}
- // ===== 右侧:帖子树(上半部分) + 三分图(下半部分) =====
- const postDetail = data.postDetail || {{}};
- window.currentPostDetail = postDetail;
- // 使用预构建的帖子树数据
- const postTree = data.postTree || {{ root: null }};
- // 容器
- const postTreeGroup = g.append("g").attr("class", "post-tree");
- let postTreeActualHeight = 0;
- let postRoot = null;
- // 卡片尺寸
- const cardWidth = 240;
- const cardHeight = 90;
- // 计算目标圆心Y坐标
- const circleYOffsetPreview = 40;
- const targetTagY = layerCenterY[0] + circleYOffsetPreview; // 帖子标签圆心
- const targetPersonaY = layerCenterY[1] + circleYOffsetPreview; // 人设匹配_1层圆心
- const targetExpandedY = layerCenterY[2] + circleYOffsetPreview; // 人设匹配_2层圆心
- const circleGap = targetPersonaY - targetTagY;
- const halfGap = circleGap / 2;
- // 树放在圆的右侧
- const circleRightEdge = circleAreaCenterX + unifiedRadius;
- const treeGap = 120;
- // 记录标签节点的位置(用于下方图的对齐)
- const tagNodePositions = {{}};
- if (postTree && postTree.root) {{
- // D3树布局(只用于帖子→维度→点→标签)
- // separation 根据节点名称长度动态计算
- const postTreeLayout = d3.tree()
- .nodeSize([50, 80])
- .separation((a, b) => {{
- const nameA = a.data.name || '';
- const nameB = b.data.name || '';
- const charWidth = 9;
- const baseGap = 30;
- // 根据两个节点的文字长度计算间距
- const widthA = nameA.length * charWidth / 2;
- const widthB = nameB.length * charWidth / 2;
- const minSep = (widthA + widthB + baseGap) / 50; // 除以 nodeSize[0]
- const defaultSep = a.parent === b.parent ? 1.2 : 1.5;
- return Math.max(minSep, defaultSep);
- }});
- // 从原始节点数据中构建权重映射(标签节点有权重字段)
- const nodeWeightMap = {{}};
- nodes.forEach(n => {{
- if (n.权重 !== undefined) {{
- nodeWeightMap[n.id] = n.权重;
- }}
- }});
- // 过滤掉人设节点,只保留树结构,并补充权重
- function filterTreeData(node) {{
- const filtered = {{ ...node }};
- // 补充权重信息
- if (node.id && nodeWeightMap[node.id] !== undefined) {{
- filtered.权重 = nodeWeightMap[node.id];
- }}
- if (node.children) {{
- filtered.children = node.children
- .filter(c => c.nodeType !== "人设" && c.nodeType !== "人设扩展")
- .map(c => filterTreeData(c));
- }}
- return filtered;
- }}
- const treeOnlyData = filterTreeData(postTree.root);
- postRoot = d3.hierarchy(treeOnlyData);
- postTreeLayout(postRoot);
- // 计算树的边界
- let treeMinX = Infinity, treeMaxX = -Infinity;
- postRoot.descendants().forEach(d => {{
- treeMinX = Math.min(treeMinX, d.x);
- treeMaxX = Math.max(treeMaxX, d.x);
- }});
- // 重新分配Y坐标(前3层层高是后面的一半)
- postRoot.descendants().forEach(d => {{
- if (d.data.isRoot) {{
- d.y = targetTagY - halfGap * 3;
- }} else if (d.data.isDimension) {{
- d.y = targetTagY - halfGap * 2;
- }} else if (d.data.nodeType === "点") {{
- d.y = targetTagY - halfGap;
- }} else if (d.data.nodeType === "标签") {{
- d.y = targetTagY;
- // 记录标签节点位置(同一个ID可能有多个位置)
- // 保存 d 的引用,以便后续 spreadTagPositions 可以更新节点位置
- if (!tagNodePositions[d.data.id]) {{
- tagNodePositions[d.data.id] = [];
- }}
- tagNodePositions[d.data.id].push({{ x: d.x, y: d.y, data: d.data, node: d }});
- }}
- }});
- // 计算偏移
- const postTreeOffsetX = circleRightEdge + treeGap - treeMinX;
- const postTreeOffsetY = 0;
- // 六边形路径
- function hexagonPath(r) {{
- const a = Math.PI / 3;
- let path = "";
- for (let i = 0; i < 6; i++) {{
- const angle = a * i - Math.PI / 2;
- const x = r * Math.cos(angle);
- const y = r * Math.sin(angle);
- path += (i === 0 ? "M" : "L") + x + "," + y;
- }}
- return path + "Z";
- }}
- // 树边路径生成函数
- const treeLinkPath = d => {{
- const sourceY = d.source.data.isRoot ? d.source.y + cardHeight/2 : d.source.y;
- return `M${{d.source.x}},${{sourceY}}
- C${{d.source.x}},${{(sourceY + d.target.y) / 2}}
- ${{d.target.x}},${{(sourceY + d.target.y) / 2}}
- ${{d.target.x}},${{d.target.y}}`;
- }};
- // 为树边添加score字段(从目标节点的权重获取)
- const treeLinkData = postRoot.links().map(d => {{
- d.score = d.target.data.权重 !== undefined ? d.target.data.权重 : null;
- return d;
- }});
- // 绘制树的边(帖子→维度→点→标签)- 用g元素包裹边和分数
- const treeLinkGroups = postTreeGroup.selectAll(".tree-link-group")
- .data(treeLinkData)
- .enter()
- .append("g")
- .attr("class", "tree-link-group");
- // 边的路径
- const treeLinks = treeLinkGroups.append("path")
- .attr("class", "tree-link")
- .attr("d", treeLinkPath)
- .attr("fill", "none")
- .attr("stroke", "#9b59b6")
- .attr("stroke-width", 1.5)
- .attr("stroke-opacity", 0.6);
- // 在有分数的边上显示分数(统一逻辑,居中显示在边上)
- treeLinkGroups.filter(d => d.score !== null)
- .append("text")
- .attr("class", "tree-link-score")
- .attr("x", d => (d.source.x + d.target.x) / 2)
- .attr("y", d => (d.source.y + d.target.y) / 2)
- .attr("dy", "0.35em")
- .attr("text-anchor", "middle")
- .attr("fill", "#fff")
- .attr("font-size", "8px")
- .attr("font-weight", "bold")
- .style("text-shadow", "0 0 3px #9b59b6, 0 0 3px #9b59b6")
- .text(d => d.score.toFixed(2));
- // 绘制树节点(非根节点)
- const treeNodes = postTreeGroup.selectAll(".tree-node")
- .data(postRoot.descendants().filter(d => !d.data.isRoot))
- .enter()
- .append("g")
- .attr("class", "tree-node")
- .attr("transform", d => `translate(${{d.x}},${{d.y}})`)
- .style("cursor", "pointer")
- .on("click", (event, d) => {{
- event.stopPropagation();
- const nodeId = d.data.id || d.data.节点ID;
- const nodeName = d.data.name || d.data.节点名称;
- // 帖子标签节点使用专门的处理函数
- if (d.data.nodeType === "标签") {{
- handlePostTagClick(nodeId, nodeName);
- }} else {{
- handleNodeClick(nodeId, nodeName);
- }}
- }});
- // 节点形状
- // 帖子标签节点点击处理函数(激活所有直连的层内边,效果等价于点击N条层内边的并集)
- function handlePostTagClick(tagNodeId, tagNodeName) {{
- if (!tagNodeId) return;
- // 层内边类型
- const intraLayerEdgeTypes = [
- "标签共现", "分类共现(跨点)", "分类共现(点内)",
- "镜像_标签共现", "镜像_分类共现(跨点)", "镜像_分类共现(点内)",
- "二阶_标签共现", "二阶_分类共现(跨点)", "二阶_分类共现(点内)"
- ];
- // 找到所有与该标签直连的层内边及其索引
- const connectedIntraEdges = [];
- links.forEach((link, index) => {{
- const srcId = typeof link.source === "object" ? link.source.id : link.source;
- const tgtId = typeof link.target === "object" ? link.target.id : link.target;
- if ((srcId === tagNodeId || tgtId === tagNodeId) && intraLayerEdgeTypes.includes(link.type)) {{
- connectedIntraEdges.push({{ link, index }});
- }}
- }});
- console.log("帖子标签直连的层内边数:", connectedIntraEdges.length);
- if (connectedIntraEdges.length === 0) {{
- // 没有层内边,回退到普通处理
- handleNodeClick(tagNodeId, tagNodeName);
- return;
- }}
- // 对每条边调用collectEdgeHighlightData,然后合并结果
- const mergedNodeIds = new Set();
- const mergedLinkIndices = new Set();
- const mergedPathNodes = new Set();
- connectedIntraEdges.forEach(({{ link, index }}) => {{
- const {{ nodeIds, linkIndices, pathNodes }} = collectEdgeHighlightData(link, index);
- nodeIds.forEach(id => mergedNodeIds.add(id));
- linkIndices.forEach(i => mergedLinkIndices.add(i));
- pathNodes.forEach(n => mergedPathNodes.add(n));
- }});
- // 复用applyEdgeHighlight进行高亮(处理左边圆和右边树)
- applyEdgeHighlight(mergedNodeIds, mergedLinkIndices);
- // 在人设树中高亮所有相关路径节点(过滤掉帖子节点)
- const personaPathNodes = Array.from(mergedPathNodes).filter(id => !id.startsWith("帖子_"));
- if (personaPathNodes.length > 0) {{
- // 获取边类型统计作为显示
- const edgeTypeCount = {{}};
- connectedIntraEdges.forEach(e => {{
- const t = e.link.type.replace("镜像_", "").replace("二阶_", "");
- edgeTypeCount[t] = (edgeTypeCount[t] || 0) + 1;
- }});
- const typeStr = Object.entries(edgeTypeCount).map(([t, c]) => `${{t}}×${{c}}`).join(", ");
- syncTreeAndRelationGraph(personaPathNodes, typeStr);
- }}
- // 显示节点详情
- const panel = document.getElementById("detailPanel");
- panel.classList.add("active");
- document.getElementById("detailTitle").textContent = "📌 帖子标签";
- let html = `
- <p><span class="label">标签:</span> <strong>${{tagNodeName}}</strong></p>
- <p><span class="label">层内边数:</span> ${{connectedIntraEdges.length}}</p>
- <h4 style="margin-top:12px;color:#f39c12;font-size:12px;">🔗 层内关联</h4>
- <div class="edge-list">
- `;
- // 按边类型分组统计
- const edgeTypeCount = {{}};
- connectedIntraEdges.forEach(e => {{
- const t = e.link.type.replace("镜像_", "").replace("二阶_", "");
- edgeTypeCount[t] = (edgeTypeCount[t] || 0) + 1;
- }});
- for (const [type, count] of Object.entries(edgeTypeCount)) {{
- html += `<div class="edge-type-item"><span class="edge-type">${{type}}</span><span class="edge-count">${{count}}</span></div>`;
- }}
- html += `</div>`;
- document.getElementById("detailContent").innerHTML = html;
- }}
- treeNodes.each(function(d) {{
- const node = d3.select(this);
- const fill = d.data.dimColor || "#888";
- if (d.data.nodeType === "点") {{
- node.append("path")
- .attr("d", hexagonPath(16))
- .attr("fill", fill)
- .attr("stroke", "#fff")
- .attr("stroke-width", 2);
- }} else if (d.data.isDimension) {{
- node.append("circle")
- .attr("r", 14)
- .attr("fill", fill)
- .attr("stroke", "#fff")
- .attr("stroke-width", 2);
- }} else if (d.data.nodeType === "标签") {{
- node.append("circle")
- .attr("r", 12)
- .attr("fill", fill)
- .attr("stroke", "#fff")
- .attr("stroke-width", 2);
- }} else {{
- node.append("circle")
- .attr("r", 8)
- .attr("fill", fill)
- .attr("stroke", "#fff")
- .attr("stroke-width", 1);
- }}
- }});
- // 节点标签
- treeNodes.append("text")
- .attr("dy", d => {{
- if (d.data.isDimension) return -22;
- if (d.data.nodeType === "点") return -24;
- if (d.data.nodeType === "标签") return -20;
- return -18;
- }})
- .attr("text-anchor", "middle")
- .attr("fill", d => d.data.dimColor || "#ccc")
- .attr("font-size", "11px")
- .attr("font-weight", d => d.data.isDimension ? "bold" : "normal")
- .text(d => d.data.name || "");
- // 绘制根节点卡片
- const postRootNode = postRoot;
- const cardX = postRootNode.x - cardWidth/2;
- const cardY = postRootNode.y - cardHeight/2;
- const rootCard = postTreeGroup.append("foreignObject")
- .attr("x", cardX)
- .attr("y", cardY)
- .attr("width", cardWidth)
- .attr("height", cardHeight);
- const images = postDetail.images || [];
- const thumbnail = images.length > 0 ? images[0] : "";
- const title = postDetail.title || "未知标题";
- const likeCount = postDetail.like_count || 0;
- const collectCount = postDetail.collect_count || 0;
- const imageCount = images.length || 0;
- const thumbnailHtml = thumbnail
- ? `<div class="post-card-thumbnail-wrapper" style="width:60px;height:60px;">
- <img class="post-card-thumbnail" style="width:60px;height:60px;" src="${{thumbnail}}" alt="封面" onerror="this.style.display='none'"/>
- ${{imageCount > 1 ? `<span class="post-card-image-count">${{imageCount}}图</span>` : ''}}
- </div>`
- : `<div class="post-card-thumbnail-placeholder" style="width:60px;height:60px;font-size:20px;">📝</div>`;
- const cardHtml = `
- <div class="post-card" xmlns="http://www.w3.org/1999/xhtml" style="padding:10px;" onclick="showPostDetail(window.currentPostDetail)">
- <div class="post-card-header">
- ${{thumbnailHtml}}
- <div class="post-card-info">
- <div class="post-card-title" style="font-size:12px;-webkit-line-clamp:2;" title="${{title}}">${{title}}</div>
- <div class="post-card-stats" style="font-size:10px;">
- <span>❤️ ${{likeCount}}</span>
- <span>⭐ ${{collectCount}}</span>
- </div>
- </div>
- </div>
- </div>
- `;
- rootCard.append("xhtml:div").html(cardHtml);
- // 应用树的位置变换
- postTreeGroup.attr("transform", `translate(${{postTreeOffsetX}}, ${{postTreeOffsetY}})`);
- // 更新标签节点位置(加上偏移)- 每个ID可能有多个位置
- Object.keys(tagNodePositions).forEach(id => {{
- tagNodePositions[id].forEach(pos => {{
- pos.x += postTreeOffsetX;
- }});
- }});
- // 对帖子标签层应用防重叠(展平后处理)
- function spreadTagPositions(tagPositions, baseGap = 30, charWidth = 9) {{
- // 展平所有标签位置
- const allTags = [];
- Object.entries(tagPositions).forEach(([id, posArray]) => {{
- posArray.forEach((pos, idx) => {{
- const name = pos.data ? (pos.data.name || '') : '';
- allTags.push({{ id, idx, x: pos.x, y: pos.y, nameLen: name.length, pos }});
- }});
- }});
- // 按y分层
- const layers = {{}};
- allTags.forEach(tag => {{
- const y = tag.y;
- if (!layers[y]) layers[y] = [];
- layers[y].push(tag);
- }});
- // 对每层进行防重叠处理
- Object.values(layers).forEach(layerTags => {{
- if (layerTags.length < 2) return;
- // 按x排序
- layerTags.sort((a, b) => a.x - b.x);
- // 多轮迭代
- for (let iter = 0; iter < 5; iter++) {{
- let hasOverlap = false;
- for (let i = 1; i < layerTags.length; i++) {{
- const prev = layerTags[i - 1];
- const curr = layerTags[i];
- const prevHalfWidth = (prev.nameLen * charWidth) / 2 + 10;
- const currHalfWidth = (curr.nameLen * charWidth) / 2 + 10;
- const minGap = prevHalfWidth + currHalfWidth + baseGap;
- const gap = curr.x - prev.x;
- if (gap < minGap) {{
- hasOverlap = true;
- const shift = (minGap - gap) / 2;
- prev.x -= shift;
- curr.x += shift;
- // 更新原始位置
- prev.pos.x = prev.x;
- curr.pos.x = curr.x;
- // 同步更新节点对象的 x(用于后续更新 DOM 位置)
- if (prev.pos.node) prev.pos.node.x = prev.x - postTreeOffsetX;
- if (curr.pos.node) curr.pos.node.x = curr.x - postTreeOffsetX;
- }}
- }}
- if (!hasOverlap) break;
- }}
- }});
- }}
- spreadTagPositions(tagNodePositions, 25, 9);
- // 更新标签节点的 DOM 位置(根据 spreadTagPositions 调整后的 d.x)
- treeNodes.filter(d => d.data.nodeType === "标签")
- .attr("transform", d => `translate(${{d.x}},${{d.y}})`);
- // 更新树边的路径(因为标签节点位置可能变了)
- treeLinks.attr("d", d => {{
- const sourceY = d.source.data.isRoot ? d.source.y + cardHeight/2 : d.source.y;
- return `M${{d.source.x}},${{sourceY}}
- C${{d.source.x}},${{(sourceY + d.target.y) / 2}}
- ${{d.target.x}},${{(sourceY + d.target.y) / 2}}
- ${{d.target.x}},${{d.target.y}}`;
- }});
- // 更新分数文本位置(因为标签节点位置可能变了)
- postTreeGroup.selectAll(".tree-link-score")
- .attr("x", d => (d.source.x + d.target.x) / 2)
- .attr("y", d => (d.source.y + d.target.y) / 2);
- // ===== 下半部分:三分图(标签 ↔ 人设_1层 ↔ 人设_2层)=====
- // 复用圆形图的节点数据,但只取人设节点(去重)
- const personaLayer1Nodes = nodes.filter(n => getNodeLayer(n) === 1);
- const personaLayer2Nodes = nodes.filter(n => getNodeLayer(n) === 2);
- // 过滤出层间边
- const crossLayerLinks = links.filter(link => {{
- const srcLayer = getNodeLayer(link.source);
- const tgtLayer = getNodeLayer(link.target);
- if (srcLayer === tgtLayer) return false;
- // 1-2层之间只显示"属于"边(从上到下),过滤掉"包含"边(从下到上)
- if ((srcLayer === 1 && tgtLayer === 2) || (srcLayer === 2 && tgtLayer === 1)) {{
- if (link.type === "包含") return false;
- }}
- return true;
- }});
- console.log("层间边数:", crossLayerLinks.length, "人设1层:", personaLayer1Nodes.length, "人设2层:", personaLayer2Nodes.length);
- // 为人设节点计算X位置(根据连接的标签节点位置)
- const personaNodePositions = {{}};
- // 人设_1层:根据连接的帖子标签位置来定位
- personaLayer1Nodes.forEach(n => {{
- // 找到连接到这个人设的帖子标签
- const connectedTags = crossLayerLinks
- .filter(l => l.target.id === n.id && getNodeLayer(l.source) === 0)
- .map(l => l.source.id);
- let avgX = 0;
- let count = 0;
- connectedTags.forEach(tagId => {{
- // 在树的标签节点中查找(每个tagId可能有多个位置)
- if (tagNodePositions[tagId]) {{
- tagNodePositions[tagId].forEach(pos => {{
- avgX += pos.x;
- count++;
- }});
- }}
- }});
- if (count > 0) {{
- personaNodePositions[n.id] = {{ x: avgX / count, y: targetPersonaY, node: n }};
- }} else {{
- // 没有连接的标签,放在中间
- const allTagX = Object.values(tagNodePositions).flatMap(arr => arr.map(t => t.x));
- const midX = allTagX.length > 0 ? (Math.min(...allTagX) + Math.max(...allTagX)) / 2 : circleRightEdge + treeGap;
- personaNodePositions[n.id] = {{ x: midX, y: targetPersonaY, node: n }};
- }}
- }});
- // 人设_2层:根据连接的人设_1层位置来定位
- personaLayer2Nodes.forEach(n => {{
- const connectedPersona1 = crossLayerLinks
- .filter(l => (l.target.id === n.id && getNodeLayer(l.source) === 1) ||
- (l.source.id === n.id && getNodeLayer(l.target) === 1))
- .map(l => l.source.id === n.id ? l.target.id : l.source.id);
- let avgX = 0;
- let count = 0;
- connectedPersona1.forEach(pId => {{
- if (personaNodePositions[pId]) {{
- avgX += personaNodePositions[pId].x;
- count++;
- }}
- }});
- if (count > 0) {{
- personaNodePositions[n.id] = {{ x: avgX / count, y: targetExpandedY, node: n }};
- }} else {{
- const allP1X = Object.values(personaNodePositions).filter(p => p.y === targetPersonaY).map(p => p.x);
- const midX = allP1X.length > 0 ? (Math.min(...allP1X) + Math.max(...allP1X)) / 2 : circleRightEdge + treeGap;
- personaNodePositions[n.id] = {{ x: midX, y: targetExpandedY, node: n }};
- }}
- }});
- // 防重叠:分散同层中x坐标太近的节点(根据文字长度动态计算间距)
- function spreadOverlappingNodes(positions, baseGap = 40, charWidth = 8) {{
- // 按y分层
- const layers = {{}};
- Object.entries(positions).forEach(([id, pos]) => {{
- const y = pos.y;
- if (!layers[y]) layers[y] = [];
- // 获取节点名称长度
- const name = pos.node ? (pos.node.节点名称 || pos.node.name || '') : '';
- layers[y].push({{ id, ...pos, nameLen: name.length }});
- }});
- // 对每层进行防重叠处理
- Object.values(layers).forEach(layerNodes => {{
- if (layerNodes.length < 2) return;
- // 按x排序
- layerNodes.sort((a, b) => a.x - b.x);
- // 多轮迭代确保所有节点都不重叠
- for (let iter = 0; iter < 5; iter++) {{
- let hasOverlap = false;
- for (let i = 1; i < layerNodes.length; i++) {{
- const prev = layerNodes[i - 1];
- const curr = layerNodes[i];
- // 根据两个节点的文字长度计算最小间距
- const prevHalfWidth = (prev.nameLen * charWidth) / 2 + 10;
- const currHalfWidth = (curr.nameLen * charWidth) / 2 + 10;
- const minGap = prevHalfWidth + currHalfWidth + baseGap;
- const gap = curr.x - prev.x;
- if (gap < minGap) {{
- hasOverlap = true;
- // 需要分散:向两侧推开
- const shift = (minGap - gap) / 2;
- prev.x -= shift;
- curr.x += shift;
- // 更新原始位置
- positions[prev.id].x = prev.x;
- positions[curr.id].x = curr.x;
- }}
- }}
- if (!hasOverlap) break;
- }}
- }});
- }}
- // 对人设节点应用防重叠
- spreadOverlappingNodes(personaNodePositions, 30, 9);
- // 合并所有节点位置(标签 + 人设)
- const allGraphNodePositions = {{}};
- // 标签位置:取第一个位置用于合并(边绘制时会用所有位置)
- Object.keys(tagNodePositions).forEach(id => {{
- allGraphNodePositions[id] = tagNodePositions[id][0];
- }});
- Object.keys(personaNodePositions).forEach(id => {{
- allGraphNodePositions[id] = personaNodePositions[id];
- }});
- // 边颜色配置(包括镜像边和二阶边)
- const graphEdgeColors = {{
- "匹配_相同": "#e94560",
- "匹配_相似": "#e94560",
- "属于": "#9b59b6",
- "包含": "#3498db",
- "分类共现(跨点)": "#2ecc71",
- "分类共现(点内)": "#2ecc71",
- "标签共现": "#f39c12",
- // 镜像边(与原始边颜色相同)
- "镜像_分类共现(跨点)": "#2ecc71",
- "镜像_分类共现(点内)": "#2ecc71",
- "镜像_标签共现": "#f39c12",
- // 二阶边(与原始边颜色相同)
- "二阶_分类共现(跨点)": "#2ecc71",
- "二阶_分类共现(点内)": "#2ecc71",
- "二阶_标签共现": "#f39c12"
- }};
- // 展开边数据:如果标签有多个位置,为每个位置创建一条边
- // 边直接引用位置对象,绘制时动态获取 x, y
- const expandedLinks = [];
- crossLayerLinks.forEach(link => {{
- const srcId = link.source.id;
- const tgtId = link.target.id;
- const srcLayer = getNodeLayer(link.source);
- const tgtLayer = getNodeLayer(link.target);
- // 源是层0(帖子标签),可能有多个位置
- if (srcLayer === 0 && tagNodePositions[srcId]) {{
- tagNodePositions[srcId].forEach((srcNode, idx) => {{
- const tgtNode = personaNodePositions[tgtId];
- if (tgtNode) {{
- expandedLinks.push({{
- ...link,
- srcNode: srcNode, // 直接引用位置对象
- tgtNode: tgtNode,
- key: `${{srcId}}_${{idx}}_${{tgtId}}`
- }});
- }}
- }});
- }}
- // 目标是层0(帖子标签),可能有多个位置
- else if (tgtLayer === 0 && tagNodePositions[tgtId]) {{
- tagNodePositions[tgtId].forEach((tgtNode, idx) => {{
- const srcNode = personaNodePositions[srcId];
- if (srcNode) {{
- expandedLinks.push({{
- ...link,
- srcNode: srcNode,
- tgtNode: tgtNode,
- key: `${{srcId}}_${{tgtId}}_${{idx}}`
- }});
- }}
- }});
- }}
- // 两端都不是层0,正常处理
- else {{
- const srcNode = personaNodePositions[srcId];
- const tgtNode = personaNodePositions[tgtId];
- if (srcNode && tgtNode) {{
- expandedLinks.push({{
- ...link,
- srcNode: srcNode,
- tgtNode: tgtNode,
- key: `${{srcId}}_${{tgtId}}`
- }});
- }}
- }}
- }});
- console.log("展开后边数:", expandedLinks.length);
- // 绘制层间边(标签→人设、人设→人设扩展)
- // 去重:同一对节点之间相同类型的边只保留一条
- const seenEdges = new Set();
- const dedupedLinks = expandedLinks.filter(link => {{
- const srcId = link.source.id || link.source;
- const tgtId = link.target.id || link.target;
- const edgeKey = [srcId, tgtId].sort().join("|") + "|" + link.type;
- if (seenEdges.has(edgeKey)) return false;
- seenEdges.add(edgeKey);
- return true;
- }});
- // 统计每对节点之间的边数,为多边分配不同曲线偏移
- const edgePairCount = {{}};
- const edgePairIndex = {{}};
- dedupedLinks.forEach(link => {{
- const srcId = link.source.id || link.source;
- const tgtId = link.target.id || link.target;
- const pairKey = [srcId, tgtId].sort().join("|");
- edgePairCount[pairKey] = (edgePairCount[pairKey] || 0) + 1;
- }});
- dedupedLinks.forEach(link => {{
- const srcId = link.source.id || link.source;
- const tgtId = link.target.id || link.target;
- const pairKey = [srcId, tgtId].sort().join("|");
- if (!edgePairIndex[pairKey]) edgePairIndex[pairKey] = 0;
- link._pairCount = edgePairCount[pairKey];
- link._pairIndex = edgePairIndex[pairKey]++;
- }});
- const graphLinksGroup = g.append("g").attr("class", "graph-links");
- const graphLinks = graphLinksGroup.selectAll(".graph-link")
- .data(dedupedLinks)
- .enter()
- .append("g")
- .attr("class", "graph-link-group");
- // 跨层边路径生成函数
- const graphLinkPath = d => {{
- const src = d.srcNode;
- const tgt = d.tgtNode;
- if (!src || !tgt) return "";
- // 如果只有一条边,用默认曲线
- if (d._pairCount <= 1) {{
- 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}}`;
- }}
- // 多条边时,根据索引计算水平偏移
- const offsetStep = 25;
- const totalOffset = (d._pairCount - 1) * offsetStep;
- const offset = d._pairIndex * offsetStep - totalOffset / 2;
- const midY = (src.y + tgt.y) / 2;
- const midX = (src.x + tgt.x) / 2 + offset;
- return `M${{src.x}},${{src.y}} Q${{midX}},${{midY}} ${{tgt.x}},${{tgt.y}}`;
- }};
- // 可见的跨层边(不可交互)
- graphLinks.append("path")
- .attr("class", "graph-link")
- .attr("d", graphLinkPath)
- .attr("fill", "none")
- .attr("stroke", d => graphEdgeColors[d.type] || "#9b59b6")
- .attr("stroke-width", 1.5)
- .attr("stroke-opacity", 0.6)
- .attr("stroke-dasharray", d => d.type === "匹配_相似" ? "4,2" : "none");
- // 跨层边设为不可交互
- graphLinks.style("pointer-events", "none");
- // 在有分数的边上显示分数(统一逻辑)
- graphLinks.filter(d => d.score !== null && d.score !== undefined)
- .append("text")
- .attr("x", d => (d.srcNode.x + d.tgtNode.x) / 2)
- .attr("y", d => (d.srcNode.y + d.tgtNode.y) / 2)
- .attr("dy", "0.35em")
- .attr("text-anchor", "middle")
- .attr("fill", "#fff")
- .attr("font-size", "8px")
- .attr("font-weight", "bold")
- .style("text-shadow", "0 0 3px #e94560, 0 0 3px #e94560")
- .text(d => d.score.toFixed(2));
- // 绘制人设节点(去重后的)
- const allPersonaNodes = [...personaLayer1Nodes, ...personaLayer2Nodes];
- const graphNodesGroup = g.append("g").attr("class", "graph-nodes");
- const graphNodes = graphNodesGroup.selectAll(".graph-node")
- .data(allPersonaNodes.filter(n => personaNodePositions[n.id]))
- .enter()
- .append("g")
- .attr("class", "graph-node")
- .attr("transform", d => {{
- const pos = personaNodePositions[d.id];
- return `translate(${{pos.x}},${{pos.y}})`;
- }})
- .style("cursor", "pointer");
- // 人设节点形状
- graphNodes.each(function(d) {{
- const node = d3.select(this);
- const fill = levelColors[d.节点层级] || "#888";
- const size = 10;
- if (d.节点类型 === "分类") {{
- node.append("rect")
- .attr("width", size * 2)
- .attr("height", size * 2)
- .attr("x", -size)
- .attr("y", -size)
- .attr("fill", fill)
- .attr("stroke", "#fff")
- .attr("stroke-width", 2)
- .attr("rx", 3);
- }} else {{
- node.append("circle")
- .attr("r", size)
- .attr("fill", fill)
- .attr("stroke", "#fff")
- .attr("stroke-width", 2);
- }}
- }});
- // 人设节点标签
- graphNodes.append("text")
- .attr("dy", -18)
- .attr("text-anchor", "middle")
- .attr("fill", d => levelColors[d.节点层级] || "#ccc")
- .attr("font-size", "11px")
- .text(d => d.节点名称 || d.name || "");
- // 点击联动 - 复用共享的节点点击处理函数
- graphNodes.on("click", function(event, d) {{
- event.stopPropagation();
- handleNodeClick(d.id || d.节点ID, d.节点名称 || d.name);
- }});
- // 存储引用
- window.graphNodesRef = graphNodes;
- window.allGraphNodePositions = allGraphNodePositions;
- // ===== 层内边:同层节点之间的关系边 =====
- // 筛选层内边(包括原始边、镜像边、二阶边)
- const intraLayerEdgeTypes = [
- "标签共现", "分类共现(跨点)", "分类共现(点内)",
- "镜像_标签共现", "镜像_分类共现(跨点)", "镜像_分类共现(点内)",
- "二阶_标签共现", "二阶_分类共现(跨点)", "二阶_分类共现(点内)"
- ];
- const intraLayerLinks = links.filter(link => {{
- const srcLayer = getNodeLayer(link.source);
- const tgtLayer = getNodeLayer(link.target);
- // 同层且是关系类边
- return srcLayer === tgtLayer && intraLayerEdgeTypes.includes(link.type);
- }});
- console.log("层内边数:", intraLayerLinks.length);
- // 展开层内边数据(处理多位置标签)
- const expandedIntraLinks = [];
- intraLayerLinks.forEach(link => {{
- const srcId = link.source.id;
- const tgtId = link.target.id;
- const srcLayer = getNodeLayer(link.source);
- // 帖子标签层(层0)- 可能有多个位置
- if (srcLayer === 0) {{
- const srcPositions = tagNodePositions[srcId] || [];
- const tgtPositions = tagNodePositions[tgtId] || [];
- // 为每对位置创建一条边
- srcPositions.forEach((srcPos, si) => {{
- tgtPositions.forEach((tgtPos, ti) => {{
- expandedIntraLinks.push({{
- ...link,
- srcNode: srcPos,
- tgtNode: tgtPos,
- key: `intra_${{srcId}}_${{si}}_${{tgtId}}_${{ti}}`
- }});
- }});
- }});
- }}
- // 人设层(层1、2)
- else {{
- const srcNode = personaNodePositions[srcId];
- const tgtNode = personaNodePositions[tgtId];
- if (srcNode && tgtNode) {{
- expandedIntraLinks.push({{
- ...link,
- srcNode: srcNode,
- tgtNode: tgtNode,
- key: `intra_${{srcId}}_${{tgtId}}`
- }});
- }}
- }}
- }});
- // 去重层内边
- const seenIntraEdges = new Set();
- const dedupedIntraLinks = expandedIntraLinks.filter(link => {{
- const srcId = link.source.id || link.source;
- const tgtId = link.target.id || link.target;
- const edgeKey = [srcId, tgtId].sort().join("|") + "|" + link.type;
- if (seenIntraEdges.has(edgeKey)) return false;
- seenIntraEdges.add(edgeKey);
- return true;
- }});
- console.log("去重后层内边数:", dedupedIntraLinks.length);
- // 为层内边计算偏移(避免重叠)
- // 按源节点分组,给每条边分配不同的弧度
- const intraEdgesBySource = {{}};
- dedupedIntraLinks.forEach((link, idx) => {{
- const srcId = link.source.id || link.source;
- if (!intraEdgesBySource[srcId]) intraEdgesBySource[srcId] = [];
- intraEdgesBySource[srcId].push({{ link, idx }});
- }});
- // 为每条边分配偏移索引
- dedupedIntraLinks.forEach((link, idx) => {{
- const srcId = link.source.id || link.source;
- const group = intraEdgesBySource[srcId];
- const indexInGroup = group.findIndex(item => item.idx === idx);
- link._arcIndex = indexInGroup;
- link._arcTotal = group.length;
- }});
- // 绘制层内边(默认隐藏)
- const intraLinksGroup = g.append("g").attr("class", "intra-layer-links");
- const intraLinks = intraLinksGroup.selectAll(".intra-link-group")
- .data(dedupedIntraLinks)
- .enter()
- .append("g")
- .attr("class", "intra-link-group")
- .style("display", "none"); // 默认隐藏
- // 层内边路径生成函数(弧线统一向下,弧度递增避免重叠)
- const intraLinkPath = d => {{
- const src = d.srcNode;
- const tgt = d.tgtNode;
- if (!src || !tgt) return "";
- const dx = tgt.x - src.x;
- const dy = tgt.y - src.y;
- const dist = Math.sqrt(dx * dx + dy * dy);
- // 根据边的索引计算弧度(统一向下)
- const baseArc = Math.min(dist * 0.2, 30);
- const arcStep = 20; // 每条边的弧度增量
- const arcIndex = d._arcIndex || 0;
- const arcHeight = baseArc + arcIndex * arcStep;
- const midX = (src.x + tgt.x) / 2;
- const midY = (src.y + tgt.y) / 2;
- // 统一向下弯曲(Y增大)
- return `M${{src.x}},${{src.y}} Q${{midX}},${{midY + arcHeight}} ${{tgt.x}},${{tgt.y}}`;
- }};
- // 层内边虚线配置(与左边一致)
- const intraEdgeDash = {{
- "匹配_相似": "5,5",
- "包含": "2,2",
- "镜像_包含": "2,2"
- }};
- // 层内边可见路径(样式与左边圆形图一致)
- intraLinks.append("path")
- .attr("class", d => "intra-link " + getEdgeClass(d.type))
- .attr("d", intraLinkPath)
- .attr("fill", "none")
- .attr("stroke", d => graphEdgeColors[d.type] || "#f39c12")
- .attr("stroke-width", 2)
- .attr("stroke-opacity", 0.8)
- .attr("stroke-dasharray", d => intraEdgeDash[d.type] || "none");
- // 层内边热区(可点击,效果与左边圆一致)
- intraLinks.append("path")
- .attr("class", "intra-link-hitarea")
- .attr("d", intraLinkPath)
- .attr("fill", "none")
- .attr("stroke", "transparent")
- .attr("stroke-width", 15)
- .style("cursor", "pointer")
- .on("mouseover", function(event, d) {{
- d3.select(this.parentNode).select(".intra-link")
- .attr("stroke-width", 3)
- .attr("stroke-opacity", 1);
- }})
- .on("mouseout", function(event, d) {{
- d3.select(this.parentNode).select(".intra-link")
- .attr("stroke-width", 2)
- .attr("stroke-opacity", 0.8);
- }})
- .on("click", function(event, d) {{
- event.stopPropagation();
- // 在左边圆中找到对应的边
- const srcId = d.source ? (d.source.id || d.source) : null;
- const tgtId = d.target ? (d.target.id || d.target) : null;
- let foundLink = null;
- let foundIndex = -1;
- links.forEach((link, idx) => {{
- const lSrcId = typeof link.source === "object" ? link.source.id : link.source;
- const lTgtId = typeof link.target === "object" ? link.target.id : link.target;
- if ((lSrcId === srcId && lTgtId === tgtId) || (lSrcId === tgtId && lTgtId === srcId)) {{
- if (link.type === d.type) {{
- foundLink = link;
- foundIndex = idx;
- }}
- }}
- }});
- if (foundLink) {{
- // 1. 高亮左边圆的边
- highlightEdge(foundLink, foundIndex);
- showEdgeInfo(foundLink);
- // 2. 同步人设树高亮和关系图展示
- const edgeDetail = foundLink.边详情 || {{}};
- const isMirrorEdge = foundLink.type.startsWith("镜像_") || foundLink.type.startsWith("二阶_");
- let personaPathNodes = [];
- let edgeType;
- if (isMirrorEdge && edgeDetail.路径节点) {{
- personaPathNodes = edgeDetail.路径节点.filter(id => !id.startsWith("帖子_"));
- edgeType = edgeDetail.原始边类型 || foundLink.type.replace("镜像_", "").replace("二阶_", "");
- }} else {{
- const sourceNode = typeof foundLink.source === "object" ? foundLink.source : nodes.find(n => n.id === foundLink.source);
- const targetNode = typeof foundLink.target === "object" ? foundLink.target : nodes.find(n => n.id === foundLink.target);
- const sId = sourceNode ? sourceNode.id : foundLink.source;
- const tId = targetNode ? targetNode.id : foundLink.target;
- if (!sId.startsWith("帖子_")) personaPathNodes.push(sId);
- if (!tId.startsWith("帖子_")) personaPathNodes.push(tId);
- edgeType = foundLink.type;
- }}
- syncTreeAndRelationGraph(personaPathNodes, edgeType);
- }} else {{
- // 没找到对应边,只显示详情
- showEdgeInfo(d);
- }}
- }});
- // 层内边分数标签(直接显示在弧线上)
- // 计算二次贝塞尔曲线在 t=0.5 时的实际位置(曲线中点)
- const getIntraArcMid = d => {{
- const dist = Math.sqrt(
- Math.pow(d.tgtNode.x - d.srcNode.x, 2) +
- Math.pow(d.tgtNode.y - d.srcNode.y, 2)
- );
- const baseArc = Math.min(dist * 0.2, 30);
- const arcStep = 20;
- const arcIndex = d._arcIndex || 0;
- const arcHeight = baseArc + arcIndex * arcStep;
- // 二次贝塞尔曲线 t=0.5 时的点: (1-t)²*P0 + 2*(1-t)*t*P1 + t²*P2
- // = 0.25*src + 0.5*ctrl + 0.25*tgt
- const midY = (d.srcNode.y + d.tgtNode.y) / 2;
- const ctrlY = midY + arcHeight; // 向下弯曲
- return {{
- x: (d.srcNode.x + d.tgtNode.x) / 2,
- y: 0.25 * d.srcNode.y + 0.5 * ctrlY + 0.25 * d.tgtNode.y
- }};
- }};
- // 分数背景(让文字在边上更清晰)
- intraLinks.filter(d => d.score !== null && d.score !== undefined)
- .append("rect")
- .attr("class", "intra-link-score-bg")
- .attr("x", d => getIntraArcMid(d).x - 14)
- .attr("y", d => getIntraArcMid(d).y - 7)
- .attr("width", 28)
- .attr("height", 14)
- .attr("rx", 3)
- .attr("fill", "rgba(0,0,0,0.7)");
- // 分数文字
- intraLinks.filter(d => d.score !== null && d.score !== undefined)
- .append("text")
- .attr("class", "intra-link-score")
- .attr("x", d => getIntraArcMid(d).x)
- .attr("y", d => getIntraArcMid(d).y)
- .attr("dy", "0.35em")
- .attr("text-anchor", "middle")
- .attr("fill", "#fff")
- .attr("font-size", "9px")
- .attr("font-weight", "bold")
- .text(d => d.score.toFixed(2));
- // 存储层内边引用供后续使用
- window.intraLayerLinksRef = intraLinks;
- window.intraLayerLinksData = dedupedIntraLinks;
- postTreeActualHeight = targetExpandedY - (targetTagY - halfGap * 3) + 100;
- }} // end if (postTree && postTree.root)
- // 计算高度
- const tripartiteHeight = postTreeActualHeight;
- // 圆的Y位置不再受帖子树高度影响,使用固定偏移
- const circleYOffset = 40;
- // 更新圆心Y坐标(三层)
- layerCenterY[0] += circleYOffset;
- layerCenterY[1] += circleYOffset;
- layerCenterY[2] += circleYOffset;
- // 更新SVG高度(取圆和三分图的最大高度)
- const minHeight = Math.max(
- layerCenterY[2] + layerRadius[2] + 50,
- tripartiteHeight + 150
- );
- svg.attr("height", Math.max(height, minHeight));
- // 绘制层背景(圆形,使用动态大小)
- const layerBg = g.append("g").attr("class", "layer-backgrounds");
- // 层配置:名称、颜色(三层圆)
- const layerConfig = [
- {{ name: "帖子标签", layer: 0, color: "rgba(52, 152, 219, 0.08)", stroke: "rgba(52, 152, 219, 0.3)" }},
- {{ name: "人设匹配_1层", layer: 1, color: "rgba(155, 89, 182, 0.08)", stroke: "rgba(155, 89, 182, 0.3)" }},
- {{ name: "人设匹配_2层", layer: 2, color: "rgba(46, 204, 113, 0.08)", stroke: "rgba(46, 204, 113, 0.3)" }}
- ];
- // 绘制三层圆形背景
- layerConfig.forEach(cfg => {{
- const cx = layerCenterX[cfg.layer];
- const cy = layerCenterY[cfg.layer];
- const r = layerRadius[cfg.layer];
- layerBg.append("circle")
- .attr("cx", cx)
- .attr("cy", cy)
- .attr("r", r)
- .attr("fill", cfg.color)
- .attr("stroke", cfg.stroke)
- .attr("stroke-width", 2);
- // 层标签(圆的左侧)
- layerBg.append("text")
- .attr("x", cx - r - 15)
- .attr("y", cy)
- .attr("dy", "0.35em")
- .attr("fill", "rgba(255,255,255,0.5)")
- .attr("font-size", "13px")
- .attr("font-weight", "bold")
- .attr("text-anchor", "end")
- .text(cfg.name);
- }});
- // 绘制左侧人设树(在独立的treeSvg中)
- const dimColors = {{ "灵感点": "#f39c12", "目的点": "#3498db", "关键点": "#9b59b6" }};
- // 更新树SVG高度
- treeSvg.attr("height", treeHeight + 50);
- const treeGroup = treeG.append("g")
- .attr("class", "persona-tree")
- .attr("transform", `translate(15, 25)`);
- // 设置关系图SVG
- egoG.selectAll("*").remove();
- const egoDisplayRadius = 180;
- const egoCenterGroup = egoG.append("g")
- .attr("class", "ego-center")
- .attr("transform", `translate(200, 210)`);
- // 关系图内容组
- egoCenterGroup.append("g")
- .attr("class", "ego-graph-content");
- // D3树布局 - 宽度留出边距给标签
- const treeLayout = d3.tree()
- .size([treeHeight - 50, treeAreaWidth - 70]);
- const root = d3.hierarchy(personaTree.root);
- treeLayout(root);
- // 获取节点颜色(根据维度)
- function getNodeColor(d) {{
- if (d.data.isRoot) return "#e94560"; // 根节点红色
- if (d.data.isDimension) return d.data.dimColor; // 维度节点用维度颜色
- return d.data.dimColor || "#888"; // 分类节点继承维度颜色
- }}
- // 构建节点ID到D3节点的映射(用于绘制原始边和高亮)
- const treeNodeById = {{}};
- root.descendants().forEach(d => {{
- if (d.data.节点ID) {{
- treeNodeById[d.data.节点ID] = d;
- }}
- }});
- // 边类型颜色和样式
- const treeEdgeColors = {{
- "分类层级": "#2ecc71", // 绿色 - 分类的层级关系
- "属于": "#9b59b6", // 紫色 - 标签属于分类
- "包含": "#3498db", // 蓝色 - 分类包含标签(向下)
- "分类共现(跨点)": "#2ecc71", // 绿色 - 分类共现
- "分类共现(点内)": "#2ecc71", // 绿色 - 分类共现
- "标签共现": "#f39c12" // 橙色 - 标签共现
- }};
- const treeEdgeDash = {{
- "分类层级": "none",
- "属于": "3,2",
- "包含": "3,2",
- "分类共现(跨点)": "5,3",
- "分类共现(点内)": "5,3",
- "标签共现": "2,2"
- }};
- // 只用D3树布局的链接作为树边(避免重复)
- const visibleTreeEdges = root.links().map(link => ({{
- 源节点ID: link.source.data.节点ID || link.source.data.name,
- 目标节点ID: link.target.data.节点ID || link.target.data.name,
- 边类型: "属于",
- isTreeLink: true,
- sourceNode: link.source,
- targetNode: link.target
- }}));
- // 生成树边路径的函数
- function treeEdgePath(d) {{
- const source = d.sourceNode;
- const target = d.targetNode;
- if (!source || !target) return "";
- const midX = (source.y + target.y) / 2;
- return `M${{source.y}},${{source.x}} C${{midX}},${{source.x}} ${{midX}},${{target.x}} ${{target.y}},${{target.x}}`;
- }}
- // 绘制原始边(只有属于边)
- const treeEdgeGroup = treeGroup.append("g").attr("class", "tree-edges");
- // 先绘制可见边(只有属于边)
- const treeEdges = treeEdgeGroup.selectAll(".tree-edge")
- .data(visibleTreeEdges)
- .join("path")
- .attr("class", "tree-edge")
- .attr("fill", "none")
- .attr("stroke", "#9b59b6") // 属于边用紫色
- .attr("stroke-opacity", 0.3)
- .attr("stroke-width", 1)
- .attr("d", treeEdgePath);
- // 绘制透明的热区边(便于点击)
- const treeEdgeHitareas = treeEdgeGroup.selectAll(".tree-edge-hitarea")
- .data(visibleTreeEdges)
- .join("path")
- .attr("class", "tree-edge-hitarea")
- .attr("fill", "none")
- .attr("stroke", "transparent")
- .attr("stroke-width", 12)
- .style("cursor", "pointer")
- .attr("d", treeEdgePath)
- .on("click", (event, d) => {{
- event.stopPropagation();
- // 调用共享的边点击处理函数
- handleEdgeClick(d.源节点ID, d.目标节点ID, d.边类型);
- }});
- // 绘制节点
- const treeNodes = treeGroup.selectAll(".tree-node")
- .data(root.descendants())
- .join("g")
- .attr("class", "tree-node")
- .attr("transform", d => `translate(${{d.y}},${{d.x}})`)
- .style("cursor", "pointer")
- .on("click", (event, d) => {{
- event.stopPropagation();
- // 调用共享的节点点击处理函数
- handleNodeClick(d.data.节点ID, d.data.节点名称 || d.data.name);
- }})
- .on("mouseenter", (event, d) => {{
- // 悬停高亮:在关系图中高亮到激活节点的路径
- if (!currentEgoCenterNodeId) return;
- const hoveredNodeId = d.data.节点ID;
- if (!hoveredNodeId || hoveredNodeId === currentEgoCenterNodeId) return;
- highlightPathInEgoGraph(hoveredNodeId);
- }})
- .on("mouseleave", (event, d) => {{
- // 移出时恢复关系图
- if (!currentEgoCenterNodeId) return;
- resetEgoGraphHighlight();
- }});
- // 节点形状:根节点/维度=圆形,分类=正方形,标签=圆形
- // 统一实心填充维度颜色
- treeNodes.each(function(d) {{
- const el = d3.select(this);
- const nodeType = d.data.节点类型;
- const isRoot = d.data.isRoot;
- const isDimension = d.data.isDimension;
- const nodeColor = getNodeColor(d);
- if (nodeType === "分类") {{
- // 分类节点:正方形,实心填充
- el.append("rect")
- .attr("class", "tree-shape")
- .attr("x", -4)
- .attr("y", -4)
- .attr("width", 8)
- .attr("height", 8)
- .attr("rx", 1)
- .attr("fill", nodeColor)
- .attr("stroke", "rgba(255,255,255,0.5)")
- .attr("stroke-width", 1);
- }} else {{
- // 根节点、维度节点、标签节点:圆形,实心填充
- const radius = isRoot ? 6 : (isDimension ? 5 : 3);
- el.append("circle")
- .attr("class", "tree-shape")
- .attr("r", radius)
- .attr("fill", nodeColor)
- .attr("stroke", "rgba(255,255,255,0.5)")
- .attr("stroke-width", 1);
- }}
- }});
- // 节点标签
- treeNodes.append("text")
- .attr("dy", "0.31em")
- .attr("x", d => d.children ? -8 : 8)
- .attr("text-anchor", d => d.children ? "end" : "start")
- .attr("fill", d => (d.data.isRoot || d.data.isDimension) ? getNodeColor(d) : "#bbb")
- .attr("font-size", d => d.data.isRoot ? "11px" : (d.data.isDimension ? "10px" : "8px"))
- .attr("font-weight", d => (d.data.isRoot || d.data.isDimension) ? "bold" : "normal")
- .text(d => d.data.name);
- // 重置树高亮状态的函数
- function resetTreeHighlight() {{
- treeGroup.selectAll(".tree-node")
- .classed("tree-dimmed", false)
- .classed("tree-highlighted", false);
- // 重置所有形状(圆形和方形)- 统一实心填充
- treeGroup.selectAll(".tree-node .tree-shape")
- .attr("fill", d => getNodeColor(d))
- .attr("stroke", "rgba(255,255,255,0.5)")
- .attr("stroke-opacity", 1)
- .attr("opacity", 1);
- treeGroup.selectAll(".tree-node text")
- .attr("fill", d => (d.data.isRoot || d.data.isDimension) ? getNodeColor(d) : "#bbb")
- .attr("opacity", 1);
- // 重置边样式
- treeGroup.selectAll(".tree-edge")
- .attr("stroke-opacity", 0.3)
- .attr("stroke-width", 1);
- }}
- // 重置右侧图高亮状态的函数
- function resetGraphHighlight() {{
- g.selectAll(".node").classed("dimmed", false).classed("highlighted", false);
- g.selectAll(".link-group").classed("dimmed", false).classed("highlighted", false);
- }}
- // 点击树SVG背景取消高亮
- treeSvg.on("click", function(event) {{
- if (event.target === this) {{
- resetTreeHighlight();
- resetGraphHighlight();
- resetRightTreeHighlight();
- clearEgoGraph();
- closeDetailPanel();
- }}
- }});
- // 创建边的容器
- const linkGroup = g.append("g").attr("class", "links");
- // 为每条边创建组
- const linkG = linkGroup.selectAll("g")
- .data(links)
- .join("g")
- .attr("class", "link-group");
- // 绘制点击热区(透明宽线)
- const linkHitarea = linkG.append("line")
- .attr("class", "link-hitarea");
- // 绘制可见的边
- const link = linkG.append("line")
- .attr("class", d => "link " + getEdgeClass(d.type))
- .attr("stroke-width", d => d.type.startsWith("匹配_") ? 2.5 : 1.5);
- // 判断是否为跨层边(根据源和目标节点的层级)- 赋值给全局变量
- isCrossLayerEdge = function(d) {{
- const sourceNode = typeof d.source === "object" ? d.source : nodes.find(n => n.id === d.source);
- const targetNode = typeof d.target === "object" ? d.target : nodes.find(n => n.id === d.target);
- if (!sourceNode || !targetNode) return false;
- return getNodeLayer(sourceNode) !== getNodeLayer(targetNode);
- }};
- // 设置跨层边的初始可见性(默认全部隐藏)
- linkG.each(function(d) {{
- if (d.type.startsWith("匹配_")) {{
- d3.select(this).style("display", "none"); // 匹配边默认隐藏
- }} else if (isCrossLayerEdge(d) && !showCrossLayerEdges) {{
- d3.select(this).style("display", "none");
- }}
- }});
- // 为有分数的边添加分数标签(统一逻辑)
- const edgeLabels = linkG.filter(d => d.score !== null && d.score !== undefined)
- .append("g")
- .attr("class", "edge-label-group");
- edgeLabels.append("rect")
- .attr("class", "edge-label-bg")
- .attr("rx", 3)
- .attr("ry", 3);
- edgeLabels.append("text")
- .attr("class", "edge-label")
- .text(d => d.score.toFixed(2));
- // 边的点击事件
- linkHitarea.on("click", (event, d, i) => {{
- event.stopPropagation();
- const linkIndex = links.indexOf(d);
- // 1. 力导向图高亮(highlightEdge 处理所有路径高亮逻辑)
- highlightEdge(d, linkIndex);
- showEdgeInfo(d);
- // 2. 确定要在人设树和关系图中展示的人设节点路径
- const edgeDetail = d.边详情 || {{}};
- const isMirrorEdge = d.type.startsWith("镜像_") || d.type.startsWith("二阶_");
- let personaPathNodes = [];
- let edgeType;
- if (isMirrorEdge && edgeDetail.路径节点) {{
- // 镜像边/二阶边:从路径节点中提取人设节点(不以帖子_开头的)
- personaPathNodes = edgeDetail.路径节点.filter(id => !id.startsWith("帖子_"));
- edgeType = edgeDetail.原始边类型 || d.type.replace("镜像_", "").replace("二阶_", "");
- }} else {{
- // 普通边:使用边的两端节点
- const sourceNode = typeof d.source === "object" ? d.source : nodes.find(n => n.id === d.source);
- const targetNode = typeof d.target === "object" ? d.target : nodes.find(n => n.id === d.target);
- const srcId = sourceNode ? sourceNode.id : d.source;
- const tgtId = targetNode ? targetNode.id : d.target;
- // 只有人设节点才加入路径
- if (!srcId.startsWith("帖子_")) personaPathNodes.push(srcId);
- if (!tgtId.startsWith("帖子_")) personaPathNodes.push(tgtId);
- edgeType = d.type;
- }}
- // 3. 同步人设树高亮和关系图展示
- syncTreeAndRelationGraph(personaPathNodes, edgeType);
- // 注:highlightEdge 内部已调用 highlightRightTree 联动右边树
- }})
- .on("mouseover", function(event, d) {{
- d3.select(this.parentNode).select(".link")
- .attr("stroke-opacity", 1)
- .attr("stroke-width", 4);
- }})
- .on("mouseout", function(event, d) {{
- d3.select(this.parentNode).select(".link")
- .attr("stroke-opacity", 0.7)
- .attr("stroke-width", d.type.startsWith("匹配_") ? 2.5 : 1.5);
- }});
- // 绘制节点
- const node = g.append("g")
- .selectAll("g")
- .data(nodes)
- .join("g")
- .attr("class", "node")
- .call(d3.drag()
- .on("start", dragstarted)
- .on("drag", dragged)
- .on("end", dragended));
- // 根据节点类型绘制不同形状
- // - 点节点(帖子点):六边形
- // - 标签节点:圆形
- // - 分类节点:方形
- // 帖子标签用虚线,人设标签用实线
- node.each(function(d) {{
- const el = d3.select(this);
- const isPointNode = d.节点类型 === "点";
- const isPostNode = d.source === "帖子";
- // 节点大小
- let size;
- if (isPointNode) {{
- size = 16; // 点节点最大
- }} else if (isPostNode) {{
- size = 12; // 帖子标签
- }} else {{
- size = 10; // 人设标签
- }}
- const fill = levelColors[d.level] || "#666";
- const nodeClass = isPostNode
- ? (isPointNode ? "post-point-node" : "post-node")
- : "persona-node";
- if (isPointNode) {{
- // 六边形(点节点)
- const hexPoints = [];
- for (let i = 0; i < 6; i++) {{
- const angle = (i * 60 - 30) * Math.PI / 180;
- hexPoints.push([size * Math.cos(angle), size * Math.sin(angle)]);
- }}
- el.append("polygon")
- .attr("points", hexPoints.map(p => p.join(",")).join(" "))
- .attr("fill", fill)
- .attr("class", nodeClass);
- }} else if (d.节点类型 === "分类") {{
- // 方形(分类节点)
- el.append("rect")
- .attr("width", size * 2)
- .attr("height", size * 2)
- .attr("x", -size)
- .attr("y", -size)
- .attr("fill", fill)
- .attr("class", nodeClass)
- .attr("rx", 3);
- }} else {{
- // 圆形(标签节点)
- el.append("circle")
- .attr("r", size)
- .attr("fill", fill)
- .attr("class", nodeClass);
- }}
- }});
- const labels = node.append("text")
- .attr("dx", 15)
- .attr("dy", 4)
- .text(d => d.节点名称)
- .style("display", showLabels ? "block" : "none");
- // 工具提示
- const tooltip = d3.select("#tooltip");
- node.on("mouseover", (event, d) => {{
- let html = `<strong>${{d.节点名称}}</strong><br/>类型: ${{d.节点类型}}<br/>层级: ${{d.节点层级}}`;
- // 点节点显示描述
- if (d.描述) {{
- html += `<br/><br/><em style="font-size:10px;color:#aaa">${{d.描述.slice(0, 100)}}${{d.描述.length > 100 ? '...' : ''}}</em>`;
- }}
- tooltip.style("display", "block").html(html);
- }})
- .on("mousemove", (event) => {{
- tooltip.style("left", (event.pageX + 15) + "px")
- .style("top", (event.pageY - 10) + "px");
- }})
- .on("mouseout", () => {{
- tooltip.style("display", "none");
- }})
- .on("click", (event, d) => {{
- event.stopPropagation();
- highlightNode(d);
- showNodeInfo(d);
- // 联动:高亮人设树 + 显示关系图 + 右边树
- if (d.source === "人设") {{
- handleNodeClick(d.节点ID, d.节点名称);
- }} else {{
- // 帖子标签节点:直接联动右边树高亮
- const highlightedNodeIds = new Set([d.id]);
- const highlightedEdgeKeys = new Set();
- // 找相连的边和节点
- g.selectAll(".link-group").each(function(link) {{
- const srcId = typeof link.source === "object" ? link.source.id : link.source;
- const tgtId = typeof link.target === "object" ? link.target.id : link.target;
- if (srcId === d.id || tgtId === d.id) {{
- highlightedNodeIds.add(srcId);
- highlightedNodeIds.add(tgtId);
- highlightedEdgeKeys.add(`${{srcId}}|${{tgtId}}`);
- highlightedEdgeKeys.add(`${{tgtId}}|${{srcId}}`);
- }}
- }});
- highlightRightTree(highlightedNodeIds, highlightedEdgeKeys);
- }}
- }});
- // 更新位置
- simulation.on("tick", () => {{
- // 更新热区线
- linkHitarea
- .attr("x1", d => d.source.x)
- .attr("y1", d => d.source.y)
- .attr("x2", d => d.target.x)
- .attr("y2", d => d.target.y);
- // 更新可见边
- link
- .attr("x1", d => d.source.x)
- .attr("y1", d => d.source.y)
- .attr("x2", d => d.target.x)
- .attr("y2", d => d.target.y);
- // 更新边标签位置(放在边的中点)
- edgeLabels.attr("transform", d => {{
- const midX = (d.source.x + d.target.x) / 2;
- const midY = (d.source.y + d.target.y) / 2;
- return `translate(${{midX}},${{midY}})`;
- }});
- // 更新标签背景大小
- edgeLabels.each(function(d) {{
- const textEl = d3.select(this).select("text").node();
- if (textEl) {{
- const bbox = textEl.getBBox();
- d3.select(this).select("rect")
- .attr("x", bbox.x - 3)
- .attr("y", bbox.y - 1)
- .attr("width", bbox.width + 6)
- .attr("height", bbox.height + 2);
- }}
- }});
- node.attr("transform", d => `translate(${{d.x}},${{d.y}})`);
- }});
- // 模拟结束后自动适配视图
- simulation.on("end", () => {{
- fitToView();
- }});
- // 适配视图:缩放并平移使所有内容可见
- function fitToView() {{
- const container = document.getElementById("graph");
- const containerWidth = container.clientWidth;
- const containerHeight = container.clientHeight;
- // 使用getBBox获取g元素的实际边界(包含所有子元素)
- const gNode = g.node();
- if (!gNode) return;
- const bbox = gNode.getBBox();
- if (bbox.width === 0 || bbox.height === 0) return;
- // 添加边距
- const padding = 30;
- const contentWidth = bbox.width + padding * 2;
- const contentHeight = bbox.height + padding * 2;
- // 计算缩放比例
- const scaleX = containerWidth / contentWidth;
- const scaleY = containerHeight / contentHeight;
- const scale = Math.min(scaleX, scaleY, 1); // 最大不超过1
- // 计算平移使内容居中
- const contentCenterX = bbox.x + bbox.width / 2;
- const contentCenterY = bbox.y + bbox.height / 2;
- const translateX = containerWidth / 2 - contentCenterX * scale;
- const translateY = containerHeight / 2 - contentCenterY * scale;
- // 应用变换
- svg.call(zoom.transform, d3.zoomIdentity.translate(translateX, translateY).scale(scale));
- }}
- // 首次渲染延迟调用适配(等待DOM完成)
- setTimeout(fitToView, 300);
- // 拖拽函数
- function dragstarted(event, d) {{
- if (!event.active) simulation.alphaTarget(0.3).restart();
- d.fx = d.x;
- d.fy = d.y;
- }}
- function dragged(event, d) {{
- d.fx = event.x;
- d.fy = event.y;
- }}
- function dragended(event, d) {{
- if (!event.active) simulation.alphaTarget(0);
- d.fx = null;
- d.fy = null;
- }}
- // 清除所有高亮
- function clearHighlight() {{
- node.classed("dimmed", false).classed("highlighted", false);
- linkG.classed("dimmed", false).classed("highlighted", false);
- // 恢复跨层边的可见性状态(根据全局开关)
- linkG.each(function(d) {{
- if (isCrossLayerEdge(d)) {{
- d3.select(this).style("display", showCrossLayerEdges ? "block" : "none");
- }}
- }});
- }}
- // 高亮指定的节点和边
- function highlightElements(highlightNodeIds, highlightLinkIndices) {{
- // 先灰化所有
- node.classed("dimmed", true).classed("highlighted", false);
- linkG.classed("dimmed", true).classed("highlighted", false);
- // 高亮指定节点
- node.filter(d => highlightNodeIds.has(d.id))
- .classed("dimmed", false)
- .classed("highlighted", true);
- // 高亮指定边
- linkG.filter((d, i) => highlightLinkIndices.has(i))
- .classed("dimmed", false)
- .classed("highlighted", true);
- }}
- // 点击节点时的高亮逻辑
- function highlightNode(clickedNode) {{
- const highlightNodeIds = new Set([clickedNode.id]);
- const highlightLinkIndices = new Set();
- links.forEach((link, i) => {{
- const sourceId = typeof link.source === "object" ? link.source.id : link.source;
- const targetId = typeof link.target === "object" ? link.target.id : link.target;
- // 与点击节点直接相连的边
- if (sourceId === clickedNode.id || targetId === clickedNode.id) {{
- highlightLinkIndices.add(i);
- highlightNodeIds.add(sourceId);
- highlightNodeIds.add(targetId);
- // 如果是帖子节点,还要高亮对应的镜像边
- if (clickedNode.source === "帖子") {{
- // 找到通过该帖子连接的其他帖子(镜像边)
- links.forEach((otherLink, j) => {{
- const otherType = otherLink.type;
- if (otherType.startsWith("镜像_") || otherType.startsWith("二阶_")) {{
- const oSrc = typeof otherLink.source === "object" ? otherLink.source.id : otherLink.source;
- const oTgt = typeof otherLink.target === "object" ? otherLink.target.id : otherLink.target;
- if (oSrc === clickedNode.id || oTgt === clickedNode.id) {{
- highlightLinkIndices.add(j);
- highlightNodeIds.add(oSrc);
- highlightNodeIds.add(oTgt);
- }}
- }}
- }});
- }}
- }}
- }});
- // 高亮相关的节点和边
- highlightElements(highlightNodeIds, highlightLinkIndices);
- // 临时显示关联的跨层边(即使全局开关是关闭的)
- linkG.each(function(d, i) {{
- if (highlightLinkIndices.has(i)) {{
- d3.select(this).style("display", "block");
- }}
- }});
- }}
- // 收集单条边的高亮数据(供复用)
- function collectEdgeHighlightData(clickedLink, clickedIndex) {{
- const nodeIds = new Set();
- const linkIndices = new Set([clickedIndex]);
- const pathNodes = new Set();
- const sourceId = typeof clickedLink.source === "object" ? clickedLink.source.id : clickedLink.source;
- const targetId = typeof clickedLink.target === "object" ? clickedLink.target.id : clickedLink.target;
- nodeIds.add(sourceId);
- nodeIds.add(targetId);
- pathNodes.add(sourceId);
- pathNodes.add(targetId);
- // 如果是镜像边或二阶边,使用预计算的路径节点
- if ((clickedLink.type.startsWith("镜像_") || clickedLink.type.startsWith("二阶_")) && clickedLink.边详情) {{
- const detail = clickedLink.边详情;
- (detail.路径节点 || []).forEach(n => pathNodes.add(n));
- }}
- // 如果是人设边(两端都不是帖子节点),找对应的镜像边
- else if (!sourceId.startsWith("帖子_") && !targetId.startsWith("帖子_")) {{
- links.forEach((link, i) => {{
- const detail = link.边详情 || {{}};
- if ((link.type.startsWith("镜像_") || link.type.startsWith("二阶_")) && detail.源人设节点 && detail.目标人设节点) {{
- const matches = (detail.源人设节点 === sourceId && detail.目标人设节点 === targetId) ||
- (detail.源人设节点 === targetId && detail.目标人设节点 === sourceId);
- if (matches) {{
- linkIndices.add(i);
- (detail.路径节点 || []).forEach(n => pathNodes.add(n));
- }}
- }}
- }});
- }}
- // 高亮路径上的所有节点
- pathNodes.forEach(n => nodeIds.add(n));
- // 高亮连接路径节点的边
- links.forEach((link, i) => {{
- const lSrc = typeof link.source === "object" ? link.source.id : link.source;
- const lTgt = typeof link.target === "object" ? link.target.id : link.target;
- if (pathNodes.has(lSrc) && pathNodes.has(lTgt)) {{
- linkIndices.add(i);
- }}
- }});
- return {{ nodeIds, linkIndices, pathNodes }};
- }}
- // 应用高亮数据(统一处理高亮结果)
- function applyEdgeHighlight(highlightNodeIds, highlightLinkIndices) {{
- // 高亮相关的节点和边
- highlightElements(highlightNodeIds, highlightLinkIndices);
- // 临时显示关联的跨层边(即使全局开关是关闭的)
- linkG.each(function(d, i) {{
- if (highlightLinkIndices.has(i)) {{
- d3.select(this).style("display", "block");
- }}
- }});
- // 联动右边树:收集高亮边的key
- const highlightEdgeKeys = new Set();
- highlightLinkIndices.forEach(i => {{
- const link = links[i];
- const srcId = typeof link.source === "object" ? link.source.id : link.source;
- const tgtId = typeof link.target === "object" ? link.target.id : link.target;
- highlightEdgeKeys.add(`${{srcId}}|${{tgtId}}`);
- highlightEdgeKeys.add(`${{tgtId}}|${{srcId}}`);
- }});
- highlightRightTree(highlightNodeIds, highlightEdgeKeys);
- }}
- // 点击边时的高亮逻辑
- function highlightEdge(clickedLink, clickedIndex) {{
- const {{ nodeIds, linkIndices }} = collectEdgeHighlightData(clickedLink, clickedIndex);
- applyEdgeHighlight(nodeIds, linkIndices);
- }}
- // 点击空白处清除高亮(合并所有空白点击逻辑)
- svg.on("click", (event) => {{
- // 检查是否点击的是空白区域(svg本身或layer-backgrounds)
- const isBlank = event.target === svg.node() ||
- event.target.tagName === "svg" ||
- event.target.classList.contains("layer-backgrounds");
- if (isBlank) {{
- // 清除右侧图高亮
- clearHighlight();
- // 清除人设树高亮
- resetTreeHighlight();
- resetGraphHighlight();
- // 恢复右边帖子树
- resetRightTreeHighlight();
- // 关闭详情面板
- closeDetailPanel();
- // 清除关系图
- clearEgoGraph();
- }}
- }});
- }}
- // 控制函数
- function resetZoom() {{
- const container = document.getElementById("svg-container");
- const width = container.clientWidth;
- const height = container.clientHeight;
- svg.transition().duration(750).call(
- zoom.transform,
- d3.zoomIdentity.translate(width/2, height/2).scale(1).translate(-width/2, -height/2)
- );
- }}
- function toggleLabels() {{
- showLabels = !showLabels;
- g.selectAll(".node text").style("display", showLabels ? "block" : "none");
- }}
- // 切换跨层边显示
- function toggleCrossLayerEdges() {{
- showCrossLayerEdges = !showCrossLayerEdges;
- const btn = document.getElementById("crossLayerBtn");
- btn.textContent = showCrossLayerEdges ? "隐藏跨层边" : "显示跨层边";
- btn.style.background = showCrossLayerEdges ? "#e94560" : "";
- // 更新边的可见性(使用 isCrossLayerEdge 函数判断)
- g.selectAll(".link-group").each(function(d) {{
- if (isCrossLayerEdge(d)) {{
- d3.select(this).style("display", showCrossLayerEdges ? "block" : "none");
- }}
- }});
- }}
- function showNodeInfo(d) {{
- const panel = document.getElementById("detailPanel");
- panel.classList.add("active");
- document.getElementById("detailTitle").textContent = d.source === "帖子" ? "📌 帖子节点" : "👤 人设节点";
- let html = `
- <p><span class="label">节点ID:</span> ${{d.节点ID}}</p>
- <p><span class="label">名称:</span> <strong>${{d.节点名称}}</strong></p>
- <p><span class="label">类型:</span> ${{d.节点类型}}</p>
- <p><span class="label">层级:</span> ${{d.节点层级}}</p>
- `;
- if (d.权重) {{
- html += `<p><span class="label">权重:</span> ${{d.权重}}</p>`;
- }}
- if (d.所属分类 && d.所属分类.length > 0) {{
- html += `<p><span class="label">所属分类:</span> ${{d.所属分类.join(" > ")}}</p>`;
- }}
- if (d.帖子数) {{
- html += `<p><span class="label">帖子数:</span> ${{d.帖子数}}</p>`;
- }}
- document.getElementById("detailContent").innerHTML = html;
- }}
- // 显示人设树节点详情(包含入边、出边、相关节点)
- function showTreeNodeDetail(nodeData, inEdges, outEdges) {{
- const panel = document.getElementById("detailPanel");
- panel.classList.add("active");
- document.getElementById("detailTitle").textContent = "🌳 人设树节点";
- // 节点基本信息
- let html = `
- <p><span class="label">名称:</span> <strong>${{nodeData.节点名称 || nodeData.name}}</strong></p>
- <p><span class="label">类型:</span> ${{nodeData.节点类型 || (nodeData.isRoot ? "根节点" : "维度")}}</p>
- <p><span class="label">层级:</span> ${{nodeData.节点层级 || "-"}}</p>
- `;
- if (nodeData.所属分类 && nodeData.所属分类.length > 0) {{
- html += `<p><span class="label">所属分类:</span> ${{nodeData.所属分类.join(" > ")}}</p>`;
- }}
- if (nodeData.帖子数) {{
- html += `<p><span class="label">帖子数:</span> ${{nodeData.帖子数}}</p>`;
- }}
- // 统计边类型
- const inEdgeTypes = {{}};
- const outEdgeTypes = {{}};
- inEdges.forEach(e => {{ inEdgeTypes[e.边类型] = (inEdgeTypes[e.边类型] || 0) + 1; }});
- outEdges.forEach(e => {{ outEdgeTypes[e.边类型] = (outEdgeTypes[e.边类型] || 0) + 1; }});
- // 入边统计
- html += `<h4 style="margin-top:12px;color:#3498db;font-size:12px;">📥 入边 (${{inEdges.length}})</h4>`;
- if (inEdges.length > 0) {{
- html += `<div class="edge-list">`;
- for (const [type, count] of Object.entries(inEdgeTypes)) {{
- html += `<div class="edge-type-item"><span class="edge-type">${{type}}</span><span class="edge-count">${{count}}</span></div>`;
- }}
- // 显示前5条入边详情
- const showInEdges = inEdges.slice(0, 5);
- showInEdges.forEach(e => {{
- const srcName = personaTreeData.nodes.find(n => n.节点ID === e.源节点ID)?.节点名称 || e.源节点ID;
- html += `<div class="edge-detail">← ${{srcName}} <span class="edge-type-tag">${{e.边类型}}</span></div>`;
- }});
- if (inEdges.length > 5) {{
- html += `<div class="edge-more">... 还有 ${{inEdges.length - 5}} 条</div>`;
- }}
- html += `</div>`;
- }} else {{
- html += `<div class="edge-empty">无</div>`;
- }}
- // 出边统计
- html += `<h4 style="margin-top:12px;color:#e74c3c;font-size:12px;">📤 出边 (${{outEdges.length}})</h4>`;
- if (outEdges.length > 0) {{
- html += `<div class="edge-list">`;
- for (const [type, count] of Object.entries(outEdgeTypes)) {{
- html += `<div class="edge-type-item"><span class="edge-type">${{type}}</span><span class="edge-count">${{count}}</span></div>`;
- }}
- // 显示前5条出边详情
- const showOutEdges = outEdges.slice(0, 5);
- showOutEdges.forEach(e => {{
- const tgtName = personaTreeData.nodes.find(n => n.节点ID === e.目标节点ID)?.节点名称 || e.目标节点ID;
- html += `<div class="edge-detail">→ ${{tgtName}} <span class="edge-type-tag">${{e.边类型}}</span></div>`;
- }});
- if (outEdges.length > 5) {{
- html += `<div class="edge-more">... 还有 ${{outEdges.length - 5}} 条</div>`;
- }}
- html += `</div>`;
- }} else {{
- html += `<div class="edge-empty">无</div>`;
- }}
- document.getElementById("detailContent").innerHTML = html;
- }}
- function showEdgeInfo(d) {{
- const panel = document.getElementById("detailPanel");
- panel.classList.add("active");
- const sourceNode = typeof d.source === "object" ? d.source : {{ id: d.source }};
- const targetNode = typeof d.target === "object" ? d.target : {{ id: d.target }};
- // 判断是否为镜像边
- const isMirror = d.type.startsWith("镜像_");
- document.getElementById("detailTitle").textContent = isMirror ? "🪞 镜像边详情" : "🔗 边详情";
- let html = `
- <p><span class="label">边类型:</span> <strong>${{d.type}}</strong></p>
- <p><span class="label">源节点:</span> ${{sourceNode.节点名称 || sourceNode.id}}</p>
- <p><span class="label">目标节点:</span> ${{targetNode.节点名称 || targetNode.id}}</p>
- `;
- if (d.边详情) {{
- if (d.边详情.相似度 !== undefined) {{
- const score = typeof d.边详情.相似度 === "number" ? d.边详情.相似度.toFixed(2) : d.边详情.相似度;
- html += `<p><span class="label">相似度:</span> <span class="similarity-score">${{score}}</span></p>`;
- }}
- if (d.边详情.说明) {{
- html += `<p><span class="label">说明:</span></p><div class="edge-description">${{d.边详情.说明}}</div>`;
- }}
- if (d.边详情.共现次数 !== undefined) {{
- html += `<p><span class="label">共现次数:</span> ${{d.边详情.共现次数}}</p>`;
- }}
- // 镜像边特有信息
- if (d.边详情.原始边类型) {{
- html += `<p><span class="label">原始边类型:</span> ${{d.边详情.原始边类型}}</p>`;
- }}
- if (d.边详情.源人设节点) {{
- html += `<p><span class="label">源人设节点:</span> ${{d.边详情.源人设节点}}</p>`;
- }}
- if (d.边详情.目标人设节点) {{
- html += `<p><span class="label">目标人设节点:</span> ${{d.边详情.目标人设节点}}</p>`;
- }}
- }}
- document.getElementById("detailContent").innerHTML = html;
- }}
- function closeDetailPanel() {{
- document.getElementById("detailPanel").classList.remove("active");
- }}
- // 更新匹配列表
- function updateMatchList(matchLinks, nodes) {{
- const listEl = document.getElementById("matchList");
- const countEl = document.getElementById("matchCount");
- // 构建节点ID到名称的映射
- const nodeNames = {{}};
- nodes.forEach(n => {{
- nodeNames[n.id] = n.节点名称 || n.id;
- }});
- // 按分数降序排序
- const sortedLinks = [...matchLinks].sort((a, b) => {{
- const scoreA = a.边详情?.相似度 ?? 0;
- const scoreB = b.边详情?.相似度 ?? 0;
- return scoreB - scoreA;
- }});
- countEl.textContent = `(${{sortedLinks.length}})`;
- // 生成列表HTML
- let html = "";
- sortedLinks.forEach((link, index) => {{
- const score = link.边详情?.相似度;
- const scoreText = score !== undefined ? score.toFixed(2) : "N/A";
- const scoreClass = score >= 0.8 ? "high" : (score >= 0.5 ? "medium" : "");
- const srcId = typeof link.source === "object" ? link.source.id : link.source;
- const tgtId = typeof link.target === "object" ? link.target.id : link.target;
- const srcName = nodeNames[srcId] || srcId;
- const tgtName = nodeNames[tgtId] || tgtId;
- html += `
- <div class="match-item" data-index="${{index}}" data-src="${{srcId}}" data-tgt="${{tgtId}}">
- <span class="score ${{scoreClass}}">${{scoreText}}</span>
- <span class="names" title="${{srcName}} → ${{tgtName}}">${{srcName}} → ${{tgtName}}</span>
- </div>
- `;
- }});
- listEl.innerHTML = html;
- // 添加点击事件
- listEl.querySelectorAll(".match-item").forEach(item => {{
- item.addEventListener("click", () => {{
- const srcId = item.dataset.src;
- const tgtId = item.dataset.tgt;
- const index = parseInt(item.dataset.index);
- // 高亮对应的边
- highlightMatchEdge(srcId, tgtId);
- // 更新列表项样式
- listEl.querySelectorAll(".match-item").forEach(el => el.classList.remove("active"));
- item.classList.add("active");
- }});
- }});
- }}
- // 高亮匹配边(复用highlightEdge逻辑)
- function highlightMatchEdge(srcId, tgtId) {{
- if (!links) return;
- // 找到对应的边和索引
- let targetLink = null;
- let targetIndex = -1;
- links.forEach((link, i) => {{
- const lSrc = typeof link.source === "object" ? link.source.id : link.source;
- const lTgt = typeof link.target === "object" ? link.target.id : link.target;
- if ((lSrc === srcId && lTgt === tgtId) || (lSrc === tgtId && lTgt === srcId)) {{
- targetLink = link;
- targetIndex = i;
- }}
- }});
- if (targetLink && targetIndex >= 0) {{
- // 复用highlightEdge的完整逻辑
- highlightEdge(targetLink, targetIndex);
- // 显示边详情
- showEdgeInfo(targetLink);
- // 联动人设树和关系图
- const pathNodes = [];
- const srcNode = typeof targetLink.source === "object" ? targetLink.source.id : targetLink.source;
- const tgtNode = typeof targetLink.target === "object" ? targetLink.target.id : targetLink.target;
- if (!srcNode.startsWith("帖子_")) pathNodes.push(srcNode);
- if (!tgtNode.startsWith("帖子_")) pathNodes.push(tgtNode);
- if (pathNodes.length > 0) {{
- syncTreeAndRelationGraph(pathNodes, targetLink.type);
- }}
- }}
- }}
- // 获取节点颜色(全局版本,根据节点数据判断维度)
- function getTreeNodeColor(d) {{
- const dimColors = {{ "灵感点": "#f39c12", "目的点": "#3498db", "关键点": "#9b59b6" }};
- if (d.data.isRoot) return "#e94560";
- if (d.data.isDimension) return d.data.dimColor;
- return d.data.dimColor || "#888";
- }}
- // 共享的节点点击处理函数(人设树和关系图复用)
- function handleNodeClick(clickedNodeId, clickedNodeName) {{
- if (!clickedNodeId) return;
- // 动态获取树相关元素
- const treeGroup = d3.select(".persona-tree");
- if (treeGroup.empty()) return;
- const treeEdges = treeGroup.selectAll(".tree-edge");
- // 先重置所有高亮状态
- treeGroup.selectAll(".tree-node")
- .classed("tree-dimmed", false)
- .classed("tree-highlighted", false);
- treeGroup.selectAll(".tree-node .tree-shape")
- .attr("fill", d => getTreeNodeColor(d))
- .attr("stroke", "rgba(255,255,255,0.5)")
- .attr("stroke-width", 1)
- .attr("stroke-opacity", 1)
- .attr("opacity", 1);
- treeGroup.selectAll(".tree-node text")
- .attr("fill", d => (d.data.isRoot || d.data.isDimension) ? getTreeNodeColor(d) : "#bbb")
- .attr("opacity", 1);
- treeEdges.attr("stroke-opacity", 0.3).attr("stroke-width", 1);
- if (g) {{
- g.selectAll(".node").classed("dimmed", false).classed("highlighted", false);
- g.selectAll(".link-group").classed("dimmed", false).classed("highlighted", false);
- }}
- // 构建节点ID到D3节点的映射
- const treeNodeById = {{}};
- treeGroup.selectAll(".tree-node").each(function(n) {{
- if (n.data.节点ID) treeNodeById[n.data.节点ID] = n;
- }});
- // 使用多级配置收集关联节点(与关系图一致)
- const levelConfigs = getLevelConfigs();
- const {{ nodeIds: connectedNodeIds, edges: allConnectedEdges }} = collectNodesAndEdges(clickedNodeId, levelConfigs);
- // 获取D3树节点
- const clickedD3Node = treeNodeById[clickedNodeId];
- // 转换为D3节点集合(只基于 collectNodesAndEdges 的结果,与关系图同步)
- const connectedD3Nodes = new Set();
- if (clickedD3Node) connectedD3Nodes.add(clickedD3Node);
- connectedNodeIds.forEach(id => {{
- if (treeNodeById[id]) connectedD3Nodes.add(treeNodeById[id]);
- }});
- // 高亮树中的节点
- treeGroup.selectAll(".tree-node")
- .classed("tree-dimmed", n => !connectedD3Nodes.has(n))
- .classed("tree-highlighted", n => connectedD3Nodes.has(n));
- // 高亮所有形状(不变粗)
- treeGroup.selectAll(".tree-node .tree-shape")
- .attr("fill", function(n) {{
- if (!connectedD3Nodes.has(n)) return "#555";
- return getTreeNodeColor(n);
- }})
- .attr("stroke", function(n) {{
- if (n.data.节点ID === clickedNodeId) return "#fff";
- return connectedD3Nodes.has(n) ? "rgba(255,255,255,0.8)" : "#333";
- }})
- .attr("stroke-opacity", 1);
- treeGroup.selectAll(".tree-node text")
- .attr("fill", function(n) {{
- if (!connectedD3Nodes.has(n)) return "#555";
- return (n.data.isRoot || n.data.isDimension) ? getTreeNodeColor(n) : "#bbb";
- }});
- // 边高亮(树边基于连接的节点)
- treeEdges.attr("stroke-opacity", function(e) {{
- // 树边高亮条件:子节点(目标)在连接集中,或者两端都在连接集中
- const srcId = e.源节点ID;
- const tgtId = e.目标节点ID;
- const srcConnected = connectedNodeIds.has(srcId) || connectedD3Nodes.has(e.sourceNode);
- const tgtConnected = connectedNodeIds.has(tgtId) || connectedD3Nodes.has(e.targetNode);
- return (srcConnected && tgtConnected) ? 0.9 : 0.15;
- }});
- // 计算入边和出边
- const inEdges = allConnectedEdges.filter(e => e.目标节点ID === clickedNodeId);
- const outEdges = allConnectedEdges.filter(e => e.源节点ID === clickedNodeId);
- // 显示详情面板
- const nodeData = personaTreeData.nodes.find(n => n.节点ID === clickedNodeId);
- if (nodeData) {{
- showTreeNodeDetail(nodeData, inEdges, outEdges);
- }}
- // 显示关系子图(先显示,这样容器高度才正确)
- renderEgoGraph(clickedNodeId, clickedNodeName);
- // 滚动人设树到对应节点位置(放在关系图显示后,高度才准确)
- if (clickedD3Node) {{
- // 用 setTimeout 确保 DOM 更新完成
- setTimeout(() => {{
- const treeContainer = document.getElementById("tree-container");
- const containerHeight = treeContainer.clientHeight;
- // D3树布局中 x 是垂直方向(因为是水平树)
- const nodeY = clickedD3Node.x + 25; // 加上treeGroup的transform偏移
- const targetScroll = nodeY - containerHeight / 2;
- treeContainer.scrollTo({{
- top: Math.max(0, targetScroll),
- behavior: "smooth"
- }});
- }}, 50);
- }}
- // 高亮左边圆中对应节点及边,同时收集用于右边树联动的数据
- // 收集高亮的节点ID和边key(左边圆高亮什么,右边树就高亮什么)
- const highlightedNodeIds = new Set([clickedNodeId]);
- const highlightedEdgeKeys = new Set();
- if (g) {{
- // 找所有与该节点相连的边,收集相关节点和边
- g.selectAll(".link-group").each(function(d) {{
- const srcId = typeof d.source === "object" ? d.source.id : d.source;
- const tgtId = typeof d.target === "object" ? d.target.id : d.target;
- if (srcId === clickedNodeId || tgtId === clickedNodeId) {{
- highlightedNodeIds.add(srcId);
- highlightedNodeIds.add(tgtId);
- highlightedEdgeKeys.add(`${{srcId}}|${{tgtId}}`);
- highlightedEdgeKeys.add(`${{tgtId}}|${{srcId}}`);
- }}
- }});
- // 检查是否有相关节点在图中
- const hasRelatedNodes = g.selectAll(".node").filter(n => highlightedNodeIds.has(n.id)).size() > 0;
- if (hasRelatedNodes) {{
- // 高亮相关节点,变灰其他
- g.selectAll(".node")
- .classed("dimmed", n => !highlightedNodeIds.has(n.id))
- .classed("highlighted", n => highlightedNodeIds.has(n.id));
- // 高亮相关边
- g.selectAll(".link-group").each(function(d) {{
- const srcId = typeof d.source === "object" ? d.source.id : d.source;
- const tgtId = typeof d.target === "object" ? d.target.id : d.target;
- const isRelated = srcId === clickedNodeId || tgtId === clickedNodeId;
- d3.select(this)
- .classed("dimmed", !isRelated)
- .classed("highlighted", isRelated);
- // 显示相关的跨层边
- if (isRelated) {{
- d3.select(this).style("display", "block");
- }}
- }});
- }} else {{
- // 点击的节点不在图中,全部变灰
- g.selectAll(".node").classed("dimmed", true).classed("highlighted", false);
- g.selectAll(".link-group").classed("dimmed", true).classed("highlighted", false);
- }}
- }}
- // 联动高亮右边帖子树(直接用左边圆高亮的节点和边)
- highlightRightTree(highlightedNodeIds, highlightedEdgeKeys);
- }}
- // 同步人设树高亮和关系图展示(职责单一:不处理力导向图)
- function syncTreeAndRelationGraph(pathNodeIds, edgeType) {{
- if (!pathNodeIds || pathNodeIds.length === 0) return;
- // 动态获取树相关元素
- const treeGroup = d3.select(".persona-tree");
- if (treeGroup.empty()) return;
- const treeEdges = treeGroup.selectAll(".tree-edge");
- // 重置人设树高亮状态
- treeGroup.selectAll(".tree-node")
- .classed("tree-dimmed", false)
- .classed("tree-highlighted", false);
- treeGroup.selectAll(".tree-node .tree-shape")
- .attr("fill", d => getTreeNodeColor(d))
- .attr("stroke", "rgba(255,255,255,0.5)")
- .attr("stroke-width", 1)
- .attr("stroke-opacity", 1)
- .attr("opacity", 1);
- treeGroup.selectAll(".tree-node text")
- .attr("fill", d => (d.data.isRoot || d.data.isDimension) ? getTreeNodeColor(d) : "#bbb")
- .attr("opacity", 1);
- treeEdges.attr("stroke-opacity", 0.3).attr("stroke-width", 1);
- // 构建节点ID到D3节点的映射
- const treeNodeById = {{}};
- treeGroup.selectAll(".tree-node").each(function(n) {{
- if (n.data.节点ID) treeNodeById[n.data.节点ID] = n;
- }});
- // 路径节点ID集合
- const pathNodeIdSet = new Set(pathNodeIds);
- // 高亮树边(路径上相邻节点之间的边)
- treeEdges.attr("stroke-opacity", function(e) {{
- const srcInPath = pathNodeIdSet.has(e.源节点ID);
- const tgtInPath = pathNodeIdSet.has(e.目标节点ID);
- return (srcInPath && tgtInPath) ? 1 : 0.1;
- }});
- // 高亮路径上的节点
- treeGroup.selectAll(".tree-node").each(function(n) {{
- const nodeId = n.data.节点ID;
- const isInPath = pathNodeIdSet.has(nodeId);
- d3.select(this).select(".tree-shape")
- .attr("fill", isInPath ? getTreeNodeColor(n) : "#555")
- .attr("opacity", 1);
- d3.select(this).select("text")
- .attr("fill", isInPath ?
- ((n.data.isRoot || n.data.isDimension) ? getTreeNodeColor(n) : "#bbb") : "#555")
- .attr("opacity", 1);
- }});
- // 显示路径详情
- const panel = document.getElementById("detailPanel");
- panel.classList.add("active");
- document.getElementById("detailTitle").textContent = "🔗 路径详情";
- // 获取路径上的节点名称
- const pathNodeNames = pathNodeIds.map(id => {{
- const treeNode = treeNodeById[id];
- if (treeNode) return treeNode.data.节点名称 || treeNode.data.name;
- const nodeData = personaTreeData.nodes.find(n => n.节点ID === id);
- return nodeData?.节点名称 || id;
- }});
- let html = `
- <p><span class="label">边类型:</span> <strong>${{edgeType}}</strong></p>
- <p><span class="label">路径节点:</span> ${{pathNodeNames.join(" → ")}}</p>
- <p><span class="label">节点数:</span> ${{pathNodeIds.length}}</p>
- `;
- document.getElementById("detailContent").innerHTML = html;
- // 在关系图中展示路径上的所有节点和边
- renderEgoGraphPath(pathNodeIds, edgeType);
- }}
- // 关系子图(Ego Graph)- 在画布第四层显示
- let currentEgoSimulation = null; // 保存当前的力模拟,用于停止
- let currentEgoCenterNodeId = null; // 当前关系图中心节点ID
- let currentEgoCenterNodeName = null; // 当前关系图中心节点名称
- // 当前选中的层级数
- let currentLevelCount = 1;
- // 切换级联菜单
- function toggleCascadeMenu() {{
- event.stopPropagation();
- const menu = document.getElementById('cascade-menu');
- menu.classList.toggle('show');
- }}
- // 反选指定层级的边类型
- function invertSelection(level) {{
- event.stopPropagation();
- document.querySelectorAll(`.cascade-edge-item input[data-level="${{level}}"]`).forEach(cb => {{
- cb.checked = !cb.checked;
- }});
- // 更新全选复选框状态
- const allItems = document.querySelectorAll(`.cascade-edge-item input[data-level="${{level}}"]`);
- const checkedItems = document.querySelectorAll(`.cascade-edge-item input[data-level="${{level}}"]:checked`);
- const selectAllCb = document.querySelector(`.select-all input[data-level="${{level}}"]`);
- selectAllCb.checked = allItems.length === checkedItems.length;
- // 重新渲染
- if (currentEgoCenterNodeId) {{
- handleNodeClick(currentEgoCenterNodeId, currentEgoCenterNodeName);
- }}
- }}
- // 重置所有层级到默认配置(所有层级边类型默认不选)
- function resetSelection() {{
- event.stopPropagation();
- // 所有层级边类型默认不选
- [1, 2, 3].forEach(level => {{
- document.querySelectorAll(`.cascade-edge-item input[data-level="${{level}}"]`).forEach(cb => {{
- cb.checked = false;
- }});
- document.querySelector(`.select-all input[data-level="${{level}}"]`).checked = false;
- }});
- // 重新渲染
- if (currentEgoCenterNodeId) {{
- handleNodeClick(currentEgoCenterNodeId, currentEgoCenterNodeName);
- }}
- }}
- // 选择层级
- function selectLevel(level) {{
- event.stopPropagation();
- currentLevelCount = level;
- // 更新层级选中状态
- document.querySelectorAll('.cascade-level-item').forEach(item => {{
- const itemLevel = parseInt(item.dataset.level);
- item.classList.toggle('active', itemLevel === level);
- }});
- // 显示对应的边类型组(1级显示L1,2级显示L1+L2,3级显示L1+L2+L3)
- document.querySelectorAll('.cascade-edge-group').forEach(group => {{
- const groupLevel = parseInt(group.dataset.level);
- group.classList.toggle('active', groupLevel <= level);
- }});
- // 更新按钮显示
- document.getElementById('cascade-label').textContent = level + '级';
- // 重新渲染关系图和人设树高亮
- if (currentEgoCenterNodeId) {{
- handleNodeClick(currentEgoCenterNodeId, currentEgoCenterNodeName);
- }}
- }}
- // 获取指定层级选中的边类型
- function getLevelEdgeTypes(level) {{
- const types = [];
- document.querySelectorAll(`.cascade-edge-item input[data-level="${{level}}"]:checked`).forEach(cb => {{
- types.push(cb.dataset.type);
- }});
- return types;
- }}
- // 获取层级配置(返回每层的边类型数组)
- function getLevelConfigs() {{
- const configs = [];
- for (let i = 1; i <= currentLevelCount; i++) {{
- const types = getLevelEdgeTypes(i);
- configs.push(types);
- }}
- return configs;
- }}
- // 多层级展开:收集指定层级内的所有节点和边(每层可指定不同边类型)
- function collectNodesAndEdges(centerNodeId, levelConfigs) {{
- const nodeIds = new Set([centerNodeId]);
- const collectedEdges = [];
- const visitedEdges = new Set();
- let currentLayer = new Set([centerNodeId]);
- for (let d = 0; d < levelConfigs.length; d++) {{
- const edgeTypes = levelConfigs[d];
- if (edgeTypes.length === 0) break;
- const nextLayer = new Set();
- personaTreeData.edges.forEach(e => {{
- // 筛选边类型
- if (!edgeTypes.includes(e.边类型)) return;
- const edgeKey = `${{e.源节点ID}}-${{e.目标节点ID}}-${{e.边类型}}`;
- if (visitedEdges.has(edgeKey)) return;
- // 单向查找:只从源节点出发,沿边的方向查找
- // 属于:子→父(从子出发找父)
- // 包含:父→子(从父出发找子)
- // 共现:A→B(从A出发找B)
- if (currentLayer.has(e.源节点ID)) {{
- visitedEdges.add(edgeKey);
- collectedEdges.push({{...e, _level: d + 1}});
- // 添加目标节点到下一层
- if (!nodeIds.has(e.目标节点ID)) {{
- nextLayer.add(e.目标节点ID);
- nodeIds.add(e.目标节点ID);
- }}
- }}
- }});
- currentLayer = nextLayer;
- if (nextLayer.size === 0) break;
- }}
- return {{ nodeIds, edges: collectedEdges, depth: levelConfigs.length }};
- }}
- function renderEgoGraph(centerNodeId, centerNodeName) {{
- // 保存当前中心节点
- currentEgoCenterNodeId = centerNodeId;
- currentEgoCenterNodeName = centerNodeName;
- // 显示关系图容器
- document.getElementById("ego-container").style.display = "block";
- // 获取关系图层组
- const egoGroup = d3.select(".ego-graph-content");
- if (egoGroup.empty()) return;
- // 停止之前的模拟
- if (currentEgoSimulation) {{
- currentEgoSimulation.stop();
- currentEgoSimulation = null;
- }}
- // 清除旧内容
- egoGroup.selectAll("*").remove();
- // 获取当前层级配置
- const levelConfigs = getLevelConfigs();
- // 更新顶部标题和统计
- document.getElementById("ego-node-name").textContent = centerNodeName;
- // 获取层半径
- const radius = 160; // 固定半径
- // 根据层级配置收集节点和边
- const {{ nodeIds, edges: relatedEdges, depth }} = collectNodesAndEdges(centerNodeId, levelConfigs);
- // 构建节点数据(确保中心节点始终包含)
- const nodeMap = {{}};
- personaTreeData.nodes.forEach(n => {{
- if (nodeIds.has(n.节点ID) || n.节点ID === centerNodeId) {{
- nodeMap[n.节点ID] = {{
- id: n.节点ID,
- name: n.节点名称,
- type: n.节点类型,
- level: n.节点层级,
- isCenter: n.节点ID === centerNodeId
- }};
- }}
- }});
- const nodes = Object.values(nodeMap);
- // 处理同一对节点间的多条边,分配不同弧度
- const linksByPair = {{}};
- relatedEdges.forEach(e => {{
- // 用排序后的节点对作为key,确保A-B和B-A是同一对
- const pairKey = [e.源节点ID, e.目标节点ID].sort().join("||");
- if (!linksByPair[pairKey]) linksByPair[pairKey] = [];
- linksByPair[pairKey].push(e);
- }});
- // 为每条边分配弧度索引
- const links = [];
- Object.values(linksByPair).forEach(pairEdges => {{
- const count = pairEdges.length;
- pairEdges.forEach((e, i) => {{
- // 弧度:0表示直线,正负值表示向两侧弯曲
- let curvature = 0;
- if (count > 1) {{
- // 多条边时,均匀分布弧度
- curvature = (i - (count - 1) / 2) * 0.3;
- }}
- links.push({{
- source: e.源节点ID,
- target: e.目标节点ID,
- type: e.边类型,
- curvature: curvature,
- score: getEdgeScore(e)
- }});
- }});
- }});
- // 根据节点数量动态计算实际使用的半径
- const nodeCount = nodes.length;
- const nodeSpacingEgo = 65; // 节点间距(增大)
- const minEgoRadius = 120;
- const maxEgoRadius = Math.max(radius, 250); // 允许更大的半径
- let actualRadius;
- if (nodeCount <= 1) {{
- actualRadius = minEgoRadius;
- }} else {{
- const circumference = nodeCount * nodeSpacingEgo;
- const calcR = circumference / (2 * Math.PI);
- actualRadius = Math.max(minEgoRadius, Math.min(maxEgoRadius, calcR));
- }}
- // 更新顶部统计信息
- document.getElementById("ego-stats").textContent = `${{nodeCount}}节点 ${{relatedEdges.length}}边`;
- // 如果只有中心节点,只渲染中心节点
- if (nodes.length === 1) {{
- const centerNode = nodes[0];
- // 获取中心节点的维度颜色
- const dimColors = {{
- "灵感点": "#f39c12",
- "目的点": "#3498db",
- "关键点": "#9b59b6"
- }};
- const level = centerNode.level || "";
- let fillColor = "#888";
- if (level.includes("灵感点")) fillColor = dimColors["灵感点"];
- else if (level.includes("目的点")) fillColor = dimColors["目的点"];
- else if (level.includes("关键点")) fillColor = dimColors["关键点"];
- // 绘制中心节点
- const nodeGroup = egoGroup.append("g")
- .attr("class", "ego-node-group")
- .attr("transform", "translate(0, 0)");
- nodeGroup.append("circle")
- .attr("r", 22)
- .attr("fill", fillColor)
- .attr("stroke", "#fff")
- .attr("stroke-width", 3)
- .attr("cursor", "pointer")
- .style("filter", "drop-shadow(0 2px 4px rgba(0,0,0,0.3))");
- nodeGroup.append("text")
- .attr("dy", "0.35em")
- .attr("text-anchor", "middle")
- .attr("fill", "#fff")
- .attr("font-size", "10px")
- .attr("font-weight", "bold")
- .attr("pointer-events", "none")
- .text(centerNode.name.length > 4 ? centerNode.name.slice(0, 4) + "..." : centerNode.name);
- // 显示提示文字
- egoGroup.append("text")
- .attr("y", 50)
- .attr("text-anchor", "middle")
- .attr("fill", "rgba(255,255,255,0.4)")
- .attr("font-size", "10px")
- .text("无相关边");
- return;
- }}
- // 边类型颜色(统一用实线)
- const edgeColors = {{
- "属于": "#9b59b6", // 紫色 - 层级关系
- "包含": "#3498db", // 蓝色 - 分类包含标签(向下)
- "分类共现(跨点)": "#2ecc71", // 绿色 - 分类共现
- "分类共现(点内)": "#2ecc71", // 绿色 - 分类共现
- "标签共现": "#f39c12" // 橙色 - 标签共现
- }};
- // 维度颜色(与人设树完全一致)
- const dimColors = {{
- "灵感点": "#f39c12",
- "目的点": "#3498db",
- "关键点": "#9b59b6"
- }};
- // 获取节点的维度颜色(与人设树一致)
- function getNodeDimColor(d) {{
- // 根据节点层级判断维度
- const level = d.level || "";
- if (level.includes("灵感点")) return dimColors["灵感点"];
- if (level.includes("目的点")) return dimColors["目的点"];
- if (level.includes("关键点")) return dimColors["关键点"];
- return "#888";
- }}
- // 获取节点填充色(实心,用维度颜色,不因选中而改变)
- function getNodeFill(d) {{
- return getNodeDimColor(d); // 始终用维度颜色填充
- }}
- // 获取节点边框色(选中节点用白色边框区分)
- function getNodeStroke(d) {{
- if (d.isCenter) return "#fff"; // 选中节点白色边框
- return "rgba(255,255,255,0.5)"; // 普通节点半透明白边框
- }}
- // 获取节点边框粗细(选中节点更粗)
- function getNodeStrokeWidth(d) {{
- return d.isCenter ? 3 : 1.5;
- }}
- // 根据节点数量调整力模拟参数
- const linkDistance = Math.max(50, Math.min(80, actualRadius / 2.5));
- const chargeStrength = Math.max(-300, Math.min(-100, -nodeCount * 10));
- const collisionRadius = 35; // 碰撞半径,防止重叠
- // 创建力导向模拟(中心在0,0因为已经平移了)
- const simulation = d3.forceSimulation(nodes)
- .force("link", d3.forceLink(links).id(d => d.id).distance(linkDistance))
- .force("charge", d3.forceManyBody().strength(chargeStrength))
- .force("center", d3.forceCenter(0, 0))
- .force("collision", d3.forceCollide().radius(collisionRadius))
- .force("boundary", function() {{
- // 限制节点在圆形区域内
- const maxR = actualRadius - 30;
- return function(alpha) {{
- nodes.forEach(d => {{
- const dist = Math.sqrt(d.x * d.x + d.y * d.y);
- if (dist > maxR) {{
- const scale = maxR / dist;
- d.x *= scale;
- d.y *= scale;
- }}
- }});
- }};
- }}());
- currentEgoSimulation = simulation;
- // 绘制边(用曲线支持多边)
- const link = egoGroup.selectAll(".ego-edge")
- .data(links)
- .join("path")
- .attr("class", "ego-edge")
- .attr("stroke", d => edgeColors[d.type] || "#666")
- .attr("stroke-width", 1.5)
- .attr("stroke-opacity", 0.7)
- .attr("fill", "none");
- // 在有分数的边上显示分数(统一逻辑)
- const edgeScoreText = egoGroup.selectAll(".ego-edge-score")
- .data(links.filter(d => d.score !== null && d.score !== undefined))
- .join("text")
- .attr("class", "ego-edge-score")
- .attr("text-anchor", "middle")
- .attr("fill", "#fff")
- .attr("font-size", "8px")
- .attr("font-weight", "bold")
- .style("text-shadow", "0 0 3px #333, 0 0 3px #333")
- .text(d => d.score.toFixed(2));
- // 绘制节点(分类用方形,标签用圆形)
- const node = egoGroup.selectAll(".ego-node")
- .data(nodes)
- .join("g")
- .attr("class", d => "ego-node" + (d.isCenter ? " center" : ""));
- // 根据节点类型绘制不同形状(与人设树样式一致)
- const nodeSize = 8;
- node.each(function(d) {{
- const el = d3.select(this);
- const fill = getNodeFill(d);
- const stroke = getNodeStroke(d);
- const size = d.isCenter ? nodeSize + 2 : nodeSize;
- const strokeWidth = getNodeStrokeWidth(d);
- if (d.type === "分类") {{
- // 方形(分类节点)- 与人设树一致
- el.append("rect")
- .attr("class", "ego-shape")
- .attr("width", size * 2)
- .attr("height", size * 2)
- .attr("x", -size)
- .attr("y", -size)
- .attr("fill", fill)
- .attr("stroke", stroke)
- .attr("stroke-width", strokeWidth)
- .attr("rx", 1);
- }} else {{
- // 圆形(标签节点)- 与人设树一致
- el.append("circle")
- .attr("class", "ego-shape")
- .attr("r", size)
- .attr("fill", fill)
- .attr("stroke", stroke)
- .attr("stroke-width", strokeWidth);
- }}
- }});
- node.append("text")
- .attr("dy", -12)
- .attr("text-anchor", "middle")
- .attr("font-size", "9px")
- .attr("fill", "#fff")
- .text(d => d.name.length > 6 ? d.name.substring(0, 6) + ".." : d.name);
- // 添加点击事件(直接调用共享函数)
- node.on("click", function(event, d) {{
- event.stopPropagation();
- handleNodeClick(d.id, d.name);
- }})
- .on("mouseenter", function(event, d) {{
- // 悬停高亮:高亮到激活节点的路径
- if (!currentEgoCenterNodeId || d.id === currentEgoCenterNodeId) return;
- highlightPathInEgoGraph(d.id);
- }})
- .on("mouseleave", function(event, d) {{
- // 移出时恢复
- if (!currentEgoCenterNodeId) return;
- resetEgoGraphHighlight();
- }});
- // 边点击事件(直接调用共享函数)
- link.on("click", function(event, d) {{
- event.stopPropagation();
- handleEdgeClick(d.source.id, d.target.id, d.type);
- }});
- // 生成曲线路径的函数
- function linkPath(d) {{
- const sx = d.source.x, sy = d.source.y;
- const tx = d.target.x, ty = d.target.y;
- if (d.curvature === 0) {{
- // 直线
- return `M${{sx}},${{sy}}L${{tx}},${{ty}}`;
- }} else {{
- // 曲线:计算控制点
- const dx = tx - sx, dy = ty - sy;
- const dist = Math.sqrt(dx * dx + dy * dy);
- // 控制点垂直于连线方向偏移
- const mx = (sx + tx) / 2;
- const my = (sy + ty) / 2;
- const offset = d.curvature * dist * 0.5;
- // 垂直方向单位向量
- const nx = -dy / dist, ny = dx / dist;
- const cx = mx + nx * offset;
- const cy = my + ny * offset;
- return `M${{sx}},${{sy}}Q${{cx}},${{cy}} ${{tx}},${{ty}}`;
- }}
- }}
- // 更新位置
- simulation.on("tick", () => {{
- link.attr("d", linkPath);
- node.attr("transform", d => `translate(${{d.x}},${{d.y}})`);
- // 更新分数位置(边的中点)
- edgeScoreText
- .attr("x", d => (d.source.x + d.target.x) / 2)
- .attr("y", d => (d.source.y + d.target.y) / 2);
- }});
- }}
- function clearEgoGraph() {{
- const egoGroup = d3.select(".ego-graph-content");
- if (!egoGroup.empty()) {{
- egoGroup.selectAll("*").remove();
- }}
- // 隐藏关系图容器
- document.getElementById("ego-container").style.display = "none";
- // 停止模拟
- if (currentEgoSimulation) {{
- currentEgoSimulation.stop();
- currentEgoSimulation = null;
- }}
- }}
- // 在关系图中高亮从悬停节点到激活节点的路径
- function highlightPathInEgoGraph(hoveredNodeId) {{
- const egoGroup = d3.select(".ego-graph-content");
- if (egoGroup.empty()) return;
- // 获取关系图中的边数据
- const egoEdges = egoGroup.selectAll(".ego-edge");
- const egoNodes = egoGroup.selectAll(".ego-node");
- if (egoEdges.empty()) return;
- // 构建邻接表用于路径查找
- const adjacency = {{}};
- const edgeMap = {{}};
- egoEdges.each(function(d) {{
- const srcId = d.source.id || d.source;
- const tgtId = d.target.id || d.target;
- if (!adjacency[srcId]) adjacency[srcId] = [];
- if (!adjacency[tgtId]) adjacency[tgtId] = [];
- adjacency[srcId].push(tgtId);
- adjacency[tgtId].push(srcId);
- // 记录边(双向)
- const key1 = `${{srcId}}|${{tgtId}}`;
- const key2 = `${{tgtId}}|${{srcId}}`;
- edgeMap[key1] = d;
- edgeMap[key2] = d;
- }});
- // BFS找路径
- const visited = new Set();
- const parent = {{}};
- const queue = [currentEgoCenterNodeId];
- visited.add(currentEgoCenterNodeId);
- let found = false;
- while (queue.length > 0 && !found) {{
- const curr = queue.shift();
- const neighbors = adjacency[curr] || [];
- for (const next of neighbors) {{
- if (!visited.has(next)) {{
- visited.add(next);
- parent[next] = curr;
- queue.push(next);
- if (next === hoveredNodeId) {{
- found = true;
- break;
- }}
- }}
- }}
- }}
- if (!found) return;
- // 回溯路径
- const pathNodes = new Set();
- const pathEdgeKeys = new Set();
- let curr = hoveredNodeId;
- while (curr !== undefined) {{
- pathNodes.add(curr);
- const prev = parent[curr];
- if (prev !== undefined) {{
- pathEdgeKeys.add(`${{prev}}|${{curr}}`);
- pathEdgeKeys.add(`${{curr}}|${{prev}}`);
- }}
- curr = prev;
- }}
- // 隐藏不在路径上的边(保持布局不变)
- egoEdges
- .style("visibility", function(d) {{
- const srcId = d.source.id || d.source;
- const tgtId = d.target.id || d.target;
- const key = `${{srcId}}|${{tgtId}}`;
- return pathEdgeKeys.has(key) ? "visible" : "hidden";
- }});
- // 隐藏不在路径上的边的分数
- egoGroup.selectAll(".ego-edge-score")
- .style("visibility", function(d) {{
- const srcId = d.source.id || d.source;
- const tgtId = d.target.id || d.target;
- const key = `${{srcId}}|${{tgtId}}`;
- return pathEdgeKeys.has(key) ? "visible" : "hidden";
- }});
- // 隐藏不在路径上的节点(保持布局不变)
- egoNodes
- .style("visibility", function(d) {{
- return pathNodes.has(d.id) ? "visible" : "hidden";
- }});
- // 联动:高亮右边树上对应的节点和边
- highlightRightTree(pathNodes, pathEdgeKeys);
- }}
- // 恢复关系图的高亮状态
- function resetEgoGraphHighlight() {{
- const egoGroup = d3.select(".ego-graph-content");
- if (egoGroup.empty()) return;
- // 恢复边的可见性
- egoGroup.selectAll(".ego-edge")
- .style("visibility", "visible");
- // 恢复边分数的可见性
- egoGroup.selectAll(".ego-edge-score")
- .style("visibility", "visible");
- // 恢复节点的可见性
- egoGroup.selectAll(".ego-node")
- .style("visibility", "visible");
- // 联动:恢复右边树
- resetRightTreeHighlight();
- }}
- // 高亮右边树上对应的节点和边
- function highlightRightTree(pathNodes, pathEdgeKeys) {{
- const postTreeGroup = d3.select(".post-tree");
- // 高亮帖子树节点
- if (!postTreeGroup.empty()) {{
- postTreeGroup.selectAll(".tree-node")
- .style("opacity", function(d) {{
- const nodeId = d.data.id || d.data.节点ID;
- return pathNodes.has(nodeId) ? 1 : 0.2;
- }});
- // 高亮帖子树边(包含边和分数的组)
- postTreeGroup.selectAll(".tree-link-group")
- .style("opacity", function(d) {{
- const srcId = d.source.data.id || d.source.data.节点ID;
- const tgtId = d.target.data.id || d.target.data.节点ID;
- // 如果两端节点都在路径中,边高亮
- return (pathNodes.has(srcId) && pathNodes.has(tgtId)) ? 1 : 0.2;
- }});
- }}
- // 高亮人设节点(右边下方的图节点,在g下面不是postTreeGroup下)
- d3.selectAll(".graph-node")
- .style("opacity", function(d) {{
- return pathNodes.has(d.id) ? 1 : 0.2;
- }});
- // 高亮跨层边(graph-link-group 包含 graph-link)
- d3.selectAll(".graph-link-group")
- .style("opacity", function(d) {{
- const srcId = d.source ? (d.source.id || d.source) : null;
- const tgtId = d.target ? (d.target.id || d.target) : null;
- if (!srcId || !tgtId) return 0.2;
- const key1 = `${{srcId}}|${{tgtId}}`;
- const key2 = `${{tgtId}}|${{srcId}}`;
- return (pathEdgeKeys.has(key1) || pathEdgeKeys.has(key2)) ? 1 : 0.2;
- }});
- // 显示并高亮层内边(只显示左边圆形图中存在的边)
- d3.selectAll(".intra-link-group").each(function(d) {{
- const srcId = d.source ? (d.source.id || d.source) : null;
- const tgtId = d.target ? (d.target.id || d.target) : null;
- if (!srcId || !tgtId) {{
- d3.select(this).style("display", "none");
- return;
- }}
- // 只显示在左边圆形图中高亮的边(来自 pathEdgeKeys)
- const key1 = `${{srcId}}|${{tgtId}}`;
- const key2 = `${{tgtId}}|${{srcId}}`;
- const isInLeftGraph = pathEdgeKeys.has(key1) || pathEdgeKeys.has(key2);
- d3.select(this)
- .style("display", isInLeftGraph ? "block" : "none")
- .style("opacity", isInLeftGraph ? 1 : 0.2);
- }});
- }}
- // 恢复右边树的高亮状态
- function resetRightTreeHighlight() {{
- const postTreeGroup = d3.select(".post-tree");
- // 恢复帖子树节点和边(包含边和分数的组)
- if (!postTreeGroup.empty()) {{
- postTreeGroup.selectAll(".tree-node").style("opacity", 1);
- postTreeGroup.selectAll(".tree-link-group").style("opacity", 1);
- }}
- // 恢复人设节点(在g下面)
- d3.selectAll(".graph-node").style("opacity", 1);
- // 恢复跨层边
- d3.selectAll(".graph-link-group").style("opacity", 1);
- // 隐藏层内边(恢复默认隐藏状态)
- d3.selectAll(".intra-link-group")
- .style("display", "none")
- .style("opacity", 1);
- }}
- // 渲染路径上的所有节点和边(点击镜像边/二阶边时调用)
- function renderEgoGraphPath(pathNodeIds, edgeType) {{
- if (!pathNodeIds || pathNodeIds.length === 0) return;
- // 显示关系图容器
- document.getElementById("ego-container").style.display = "block";
- const egoGroup = d3.select(".ego-graph-content");
- if (egoGroup.empty()) return;
- // 停止之前的模拟
- if (currentEgoSimulation) {{
- currentEgoSimulation.stop();
- currentEgoSimulation = null;
- }}
- // 清除旧内容
- egoGroup.selectAll("*").remove();
- // 边类型颜色
- const edgeColors = {{
- "属于": "#9b59b6",
- "包含": "#3498db",
- "分类共现(跨点)": "#2ecc71",
- "分类共现(点内)": "#2ecc71",
- "标签共现": "#f39c12"
- }};
- // 维度颜色
- const dimColors = {{
- "灵感点": "#f39c12",
- "目的点": "#3498db",
- "关键点": "#9b59b6"
- }};
- // 获取节点颜色
- function getNodeColor(nodeData) {{
- const level = nodeData.节点层级 || "";
- if (level.includes("灵感点")) return dimColors["灵感点"];
- if (level.includes("目的点")) return dimColors["目的点"];
- if (level.includes("关键点")) return dimColors["关键点"];
- return "#888";
- }}
- // 获取路径节点数据
- const pathNodes = pathNodeIds.map(id => {{
- const nodeData = personaTreeData.nodes.find(n => n.节点ID === id);
- return nodeData || {{ 节点ID: id, 节点名称: id, 节点类型: "标签" }};
- }});
- // 找出路径上相邻节点之间的边
- const pathEdges = [];
- for (let i = 0; i < pathNodeIds.length - 1; i++) {{
- const srcId = pathNodeIds[i];
- const tgtId = pathNodeIds[i + 1];
- // 在 personaTreeData.edges 中查找
- const edge = personaTreeData.edges.find(e =>
- (e.源节点ID === srcId && e.目标节点ID === tgtId) ||
- (e.源节点ID === tgtId && e.目标节点ID === srcId)
- );
- pathEdges.push(edge || {{ 边类型: edgeType, 源节点ID: srcId, 目标节点ID: tgtId }});
- }}
- // 更新顶部标题
- document.getElementById("ego-node-name").textContent = edgeType;
- document.getElementById("ego-stats").textContent = `${{pathNodes.length}}节点 ${{pathEdges.length}}边`;
- // 水平线性布局
- const nodeSpacing = 80;
- const totalWidth = (pathNodes.length - 1) * nodeSpacing;
- const startX = -totalWidth / 2;
- // 绘制边
- pathEdges.forEach((edge, i) => {{
- const x1 = startX + i * nodeSpacing;
- const x2 = startX + (i + 1) * nodeSpacing;
- // 边的可点击区域(更宽的透明线)
- egoGroup.append("line")
- .attr("class", "ego-edge-hitarea")
- .attr("x1", x1)
- .attr("y1", 0)
- .attr("x2", x2)
- .attr("y2", 0)
- .attr("stroke", "transparent")
- .attr("stroke-width", 15)
- .style("cursor", "pointer")
- .on("click", (event) => {{
- event.stopPropagation();
- handleEdgeClick(edge.源节点ID, edge.目标节点ID, edge.边类型);
- }});
- // 可见的边
- egoGroup.append("line")
- .attr("class", "ego-edge")
- .attr("x1", x1)
- .attr("y1", 0)
- .attr("x2", x2)
- .attr("y2", 0)
- .attr("stroke", edgeColors[edge.边类型] || "#666")
- .attr("stroke-width", 3)
- .attr("stroke-opacity", 0.8)
- .style("pointer-events", "none");
- // 边类型标签
- egoGroup.append("text")
- .attr("x", (x1 + x2) / 2)
- .attr("y", 20)
- .attr("text-anchor", "middle")
- .attr("fill", "#999")
- .attr("font-size", "9px")
- .style("pointer-events", "none")
- .text(edge.边类型);
- }});
- // 绘制节点
- pathNodes.forEach((nodeData, i) => {{
- const x = startX + i * nodeSpacing;
- const nodeGroup = egoGroup.append("g")
- .attr("class", "ego-node")
- .attr("transform", `translate(${{x}}, 0)`)
- .style("cursor", "pointer")
- .on("click", (event) => {{
- event.stopPropagation();
- handleNodeClick(nodeData.节点ID, nodeData.节点名称 || nodeData.name);
- }});
- const nodeSize = 15;
- const nodeColor = getNodeColor(nodeData);
- if (nodeData.节点类型 === "分类") {{
- nodeGroup.append("rect")
- .attr("width", nodeSize * 2)
- .attr("height", nodeSize * 2)
- .attr("x", -nodeSize)
- .attr("y", -nodeSize)
- .attr("fill", nodeColor)
- .attr("stroke", "rgba(255,255,255,0.5)")
- .attr("stroke-width", 2)
- .attr("rx", 2);
- }} else {{
- nodeGroup.append("circle")
- .attr("r", nodeSize)
- .attr("fill", nodeColor)
- .attr("stroke", "rgba(255,255,255,0.5)")
- .attr("stroke-width", 2);
- }}
- // 节点名称
- nodeGroup.append("text")
- .attr("dy", -nodeSize - 8)
- .attr("text-anchor", "middle")
- .attr("fill", "#fff")
- .attr("font-size", "10px")
- .style("pointer-events", "none")
- .text(nodeData.节点名称 || nodeData.name || nodeData.节点ID);
- }});
- }}
- // 渲染单条边和两个节点(点击树边时调用)
- function renderEgoGraphEdge(edgeData, sourceNode, targetNode) {{
- // 显示关系图容器
- document.getElementById("ego-container").style.display = "block";
- const egoGroup = d3.select(".ego-graph-content");
- if (egoGroup.empty()) return;
- // 停止之前的模拟
- if (currentEgoSimulation) {{
- currentEgoSimulation.stop();
- currentEgoSimulation = null;
- }}
- // 清除旧内容
- egoGroup.selectAll("*").remove();
- // 更新顶部标题
- document.getElementById("ego-node-name").textContent = edgeData.边类型;
- document.getElementById("ego-stats").textContent = "2节点 1边";
- const radius = 160;
- // 边类型颜色
- const edgeColors = {{
- "属于": "#9b59b6",
- "包含": "#3498db",
- "分类共现(跨点)": "#2ecc71",
- "分类共现(点内)": "#2ecc71",
- "标签共现": "#f39c12"
- }};
- // 维度颜色
- const dimColors = {{
- "灵感点": "#f39c12",
- "目的点": "#3498db",
- "关键点": "#9b59b6"
- }};
- // 获取节点颜色
- function getNodeColor(nodeData) {{
- const level = nodeData.节点层级 || "";
- if (level.includes("灵感点")) return dimColors["灵感点"];
- if (level.includes("目的点")) return dimColors["目的点"];
- if (level.includes("关键点")) return dimColors["关键点"];
- return "#888";
- }}
- // 两个节点的位置
- const srcX = -60, srcY = 0;
- const tgtX = 60, tgtY = 0;
- // 绘制边
- egoGroup.append("line")
- .attr("class", "ego-edge")
- .attr("x1", srcX)
- .attr("y1", srcY)
- .attr("x2", tgtX)
- .attr("y2", tgtY)
- .attr("stroke", edgeColors[edgeData.边类型] || "#666")
- .attr("stroke-width", 3)
- .attr("stroke-opacity", 0.8);
- // 获取节点数据
- const srcData = sourceNode ? sourceNode.data : {{}};
- const tgtData = targetNode ? targetNode.data : {{}};
- // 绘制源节点
- const srcGroup = egoGroup.append("g")
- .attr("class", "ego-node")
- .attr("transform", `translate(${{srcX}}, ${{srcY}})`);
- const srcSize = 15;
- const srcColor = getNodeColor(srcData);
- if (srcData.节点类型 === "分类") {{
- srcGroup.append("rect")
- .attr("width", srcSize * 2)
- .attr("height", srcSize * 2)
- .attr("x", -srcSize)
- .attr("y", -srcSize)
- .attr("fill", srcColor)
- .attr("stroke", "rgba(255,255,255,0.5)")
- .attr("stroke-width", 2)
- .attr("rx", 2);
- }} else {{
- srcGroup.append("circle")
- .attr("r", srcSize)
- .attr("fill", srcColor)
- .attr("stroke", "rgba(255,255,255,0.5)")
- .attr("stroke-width", 2);
- }}
- srcGroup.append("text")
- .attr("dy", -srcSize - 8)
- .attr("text-anchor", "middle")
- .attr("fill", "#fff")
- .attr("font-size", "11px")
- .text(srcData.节点名称 || srcData.name || "源节点");
- // 绘制目标节点
- const tgtGroup = egoGroup.append("g")
- .attr("class", "ego-node")
- .attr("transform", `translate(${{tgtX}}, ${{tgtY}})`);
- const tgtSize = 15;
- const tgtColor = getNodeColor(tgtData);
- if (tgtData.节点类型 === "分类") {{
- tgtGroup.append("rect")
- .attr("width", tgtSize * 2)
- .attr("height", tgtSize * 2)
- .attr("x", -tgtSize)
- .attr("y", -tgtSize)
- .attr("fill", tgtColor)
- .attr("stroke", "rgba(255,255,255,0.5)")
- .attr("stroke-width", 2)
- .attr("rx", 2);
- }} else {{
- tgtGroup.append("circle")
- .attr("r", tgtSize)
- .attr("fill", tgtColor)
- .attr("stroke", "rgba(255,255,255,0.5)")
- .attr("stroke-width", 2);
- }}
- tgtGroup.append("text")
- .attr("dy", -tgtSize - 8)
- .attr("text-anchor", "middle")
- .attr("fill", "#fff")
- .attr("font-size", "11px")
- .text(tgtData.节点名称 || tgtData.name || "目标节点");
- // 边标签
- egoGroup.append("text")
- .attr("y", 25)
- .attr("text-anchor", "middle")
- .attr("fill", "rgba(255,255,255,0.6)")
- .attr("font-size", "10px")
- .text(edgeData.边类型);
- }}
- // 页面加载完成后初始化
- window.addEventListener("load", init);
- window.addEventListener("resize", () => {{
- if (currentIndex >= 0) {{
- renderGraph(allGraphData[currentIndex]);
- }}
- }});
- </script>
- </body>
- </html>
- '''
- def generate_combined_html(all_graph_data: List[Dict], persona_tree_data: Dict, output_file: Path):
- """
- 生成包含所有帖子图谱的HTML文件
- Args:
- all_graph_data: 所有帖子的图谱数据列表
- persona_tree_data: 完整的人设树数据(节点和边)
- output_file: 输出文件路径
- """
- # 生成帖子选项HTML
- tabs_html = ""
- for i, data in enumerate(all_graph_data):
- post_title = data.get("postTitle", "")
- # 使用帖子标题,如果太长则截断
- if post_title:
- option_name = post_title[:30] + "..." if len(post_title) > 30 else post_title
- else:
- option_name = f"帖子 {i+1}"
- selected = "selected" if i == 0 else ""
- tabs_html += f'<option value="{i}" {selected}>{i+1}. {option_name}</option>\n'
- # 生成HTML
- html_content = HTML_TEMPLATE.format(
- tabs_html=tabs_html,
- all_graph_data=json.dumps(all_graph_data, ensure_ascii=False),
- persona_tree_data=json.dumps(persona_tree_data, ensure_ascii=False)
- )
- with open(output_file, "w", encoding="utf-8") as f:
- f.write(html_content)
- def main():
- # 使用路径配置
- config = PathConfig()
- print(f"账号: {config.account_name}")
- print(f"输出版本: {config.output_version}")
- print()
- # 输入目录
- match_graph_dir = config.intermediate_dir / "match_graph"
- # 输出文件
- output_file = config.intermediate_dir / "match_graph.html"
- print(f"输入目录: {match_graph_dir}")
- print(f"输出文件: {output_file}")
- print()
- # 读取人设树中间数据
- persona_tree_file = config.intermediate_dir / "persona_tree.json"
- persona_tree_data = {"nodes": [], "edges": []}
- if persona_tree_file.exists():
- print(f"读取人设树数据: {persona_tree_file.name}")
- with open(persona_tree_file, "r", encoding="utf-8") as f:
- tree_data = json.load(f)
- persona_tree_data["nodes"] = tree_data.get("nodes", [])
- persona_tree_data["edges"] = tree_data.get("edges", [])
- category_count = len([n for n in persona_tree_data["nodes"] if n.get("节点类型") == "分类"])
- tag_count = len([n for n in persona_tree_data["nodes"] if n.get("节点类型") == "标签"])
- print(f" 分类节点: {category_count}, 标签节点: {tag_count}")
- print(f" 边数: {len(persona_tree_data['edges'])}")
- print()
- # 读取帖子树数据
- post_trees_file = match_graph_dir / "post_trees.json"
- post_trees_data = {} # postId -> postTree
- if post_trees_file.exists():
- print(f"读取帖子树数据: {post_trees_file.name}")
- with open(post_trees_file, "r", encoding="utf-8") as f:
- trees_data = json.load(f)
- for tree in trees_data.get("postTrees", []):
- post_trees_data[tree["postId"]] = tree
- print(f" 帖子树数量: {len(post_trees_data)}")
- else:
- print(f"警告: 帖子树数据文件不存在: {post_trees_file}")
- print(" 请先运行 build_post_tree.py 生成帖子树数据")
- print()
- # 读取所有匹配图谱文件
- graph_files = sorted(match_graph_dir.glob("*_match_graph.json"))
- print(f"找到 {len(graph_files)} 个匹配图谱文件")
- # results目录(存放完整帖子详情)
- results_dir = config.intermediate_dir.parent / "results"
- all_graph_data = []
- for i, graph_file in enumerate(graph_files, 1):
- print(f" [{i}/{len(graph_files)}] 读取: {graph_file.name}")
- with open(graph_file, "r", encoding="utf-8") as f:
- match_graph_data = json.load(f)
- post_id = match_graph_data["说明"]["帖子ID"]
- # 尝试读取完整帖子详情
- post_detail = {
- "title": match_graph_data["说明"].get("帖子标题", ""),
- "post_id": post_id
- }
- how_file = results_dir / f"{post_id}_how.json"
- if how_file.exists():
- with open(how_file, "r", encoding="utf-8") as f:
- how_data = json.load(f)
- if "帖子详情" in how_data:
- post_detail = how_data["帖子详情"]
- post_detail["post_id"] = post_id
- # 获取预构建的帖子树数据
- post_tree = post_trees_data.get(post_id, {})
- # 提取需要的数据
- graph_data = {
- "postId": post_id,
- "postTitle": match_graph_data["说明"].get("帖子标题", ""),
- "stats": match_graph_data["说明"]["统计"],
- "nodes": match_graph_data["节点列表"],
- "edges": match_graph_data["边列表"],
- "personaEdgeToMirrorEdges": match_graph_data.get("人设边到镜像边映射", {}),
- # 预构建的帖子树数据
- "postTree": post_tree,
- "postDetail": post_tree.get("postDetail", post_detail)
- }
- all_graph_data.append(graph_data)
- # 生成HTML
- print("\n生成HTML文件...")
- generate_combined_html(all_graph_data, persona_tree_data, output_file)
- print("\n" + "="*60)
- print("处理完成!")
- print(f"输出文件: {output_file}")
- if __name__ == "__main__":
- main()
|