| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105 |
- #!/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;
- }}
- /* Tab样式 */
- .tabs {{
- display: flex;
- background: #0f3460;
- padding: 0 20px;
- overflow-x: auto;
- flex-shrink: 0;
- }}
- .tab {{
- padding: 12px 20px;
- cursor: pointer;
- border-bottom: 3px solid transparent;
- white-space: nowrap;
- font-size: 13px;
- color: #888;
- transition: all 0.2s;
- }}
- .tab:hover {{
- color: #fff;
- background: rgba(255,255,255,0.05);
- }}
- .tab.active {{
- color: #e94560;
- border-bottom-color: #e94560;
- background: rgba(233, 69, 96, 0.1);
- }}
- /* 主内容区 */
- .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;
- }}
- .legend {{
- margin-top: 10px;
- }}
- .legend-grid {{
- display: grid;
- grid-template-columns: 1fr 1fr;
- gap: 4px 8px;
- }}
- .legend-item {{
- display: flex;
- align-items: center;
- font-size: 11px;
- }}
- .legend-color {{
- width: 12px;
- height: 12px;
- border-radius: 50%;
- margin-right: 6px;
- flex-shrink: 0;
- }}
- .legend-line {{
- width: 20px;
- height: 3px;
- margin-right: 6px;
- flex-shrink: 0;
- }}
- .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="tabs" id="tabs">
- {tabs_html}
- </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:#ffb6c1"></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:#3498db"></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:#ffb6c1"></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:#3498db"></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:#ffb6c1"></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:#3498db"></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">
- <h1>匹配图谱</h1>
- <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 class="legend">
- <h2>节点</h2>
- <div class="legend-grid">
- <div class="legend-item">
- <div class="legend-color" style="background: #f39c12; border: 2px solid #fff;"></div>
- <span>灵感点</span>
- </div>
- <div class="legend-item">
- <div class="legend-color" style="background: #3498db; border: 2px solid #fff;"></div>
- <span>目的点</span>
- </div>
- <div class="legend-item">
- <div class="legend-color" style="background: #9b59b6; border: 2px solid #fff;"></div>
- <span>关键点</span>
- </div>
- </div>
- <h2>边</h2>
- <div class="legend-grid">
- <div class="legend-item">
- <div class="legend-line" style="background: #e94560;"></div>
- <span>相同(≥0.8)</span>
- </div>
- <div class="legend-item">
- <div class="legend-line" style="background: linear-gradient(90deg, #e94560 0%, #e94560 40%, transparent 40%, transparent 60%, #e94560 60%);"></div>
- <span>相似(0.5-0.8)</span>
- </div>
- <div class="legend-item">
- <div class="legend-line" style="background: #9b59b6;"></div>
- <span>属于</span>
- </div>
- <div class="legend-item">
- <div class="legend-line" style="background: #2ecc71;"></div>
- <span>分类共现(跨)</span>
- </div>
- <div class="legend-item">
- <div class="legend-line" style="background: #3498db;"></div>
- <span>分类共现(内)</span>
- </div>
- <div class="legend-item">
- <div class="legend-line" style="background: #f39c12;"></div>
- <span>标签共现</span>
- </div>
- </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);
- // 绑定Tab点击事件
- document.querySelectorAll(".tab").forEach((tab, index) => {{
- tab.addEventListener("click", () => switchTab(index));
- }});
- // 绑定关系图控制面板事件
- // 全选复选框事件
- 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 = '';
- }}
- }}
- // 切换Tab
- function switchTab(index) {{
- currentIndex = index;
- // 更新Tab样式
- document.querySelectorAll(".tab").forEach((tab, i) => {{
- tab.classList.toggle("active", i === index);
- }});
- // 更新图谱
- renderGraph(allGraphData[index]);
- }}
- // 渲染图谱
- 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();
- // 复用共享的节点点击处理函数
- handleNodeClick(d.data.id || d.data.节点ID, d.data.name || d.data.节点名称);
- }});
- // 节点形状
- 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",
- "包含": "#ffb6c1",
- "分类共现(跨点)": "#2ecc71",
- "分类共现(点内)": "#3498db",
- "标签共现": "#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")
- .style("pointer-events", "none"); // 让事件穿透到热区
- // 跨层边热区(方便点击)
- graphLinks.append("path")
- .attr("class", "graph-link-hitarea")
- .attr("d", graphLinkPath)
- .attr("fill", "none")
- .attr("stroke", "transparent")
- .attr("stroke-width", 15)
- .style("cursor", "pointer")
- .on("mouseover", function(event, d) {{
- // 高亮对应的可见边
- d3.select(this.parentNode).select(".graph-link")
- .attr("stroke-width", 3)
- .attr("stroke-opacity", 1);
- }})
- .on("mouseout", function(event, d) {{
- // 恢复边样式
- d3.select(this.parentNode).select(".graph-link")
- .attr("stroke-width", 1.5)
- .attr("stroke-opacity", 0.6);
- }})
- .on("click", function(event, d) {{
- event.stopPropagation();
- // 获取边两端节点ID
- const srcId = d.source ? (d.source.id || d.source) : null;
- const tgtId = d.target ? (d.target.id || d.target) : null;
- if (!srcId || !tgtId) return;
- // 在左边圆中找对应的节点,触发点击
- const leftNode = nodes.find(n => n.id === srcId || n.id === tgtId);
- if (leftNode) {{
- highlightNode(leftNode);
- showNodeInfo(leftNode);
- if (leftNode.source === "人设") {{
- handleNodeClick(leftNode.id, leftNode.节点名称);
- }} else {{
- // 帖子标签节点
- const highlightedNodeIds = new Set([srcId, tgtId]);
- const highlightedEdgeKeys = new Set([`${{srcId}}|${{tgtId}}`, `${{tgtId}}|${{srcId}}`]);
- g.selectAll(".link-group").each(function(link) {{
- const lSrcId = typeof link.source === "object" ? link.source.id : link.source;
- const lTgtId = typeof link.target === "object" ? link.target.id : link.target;
- if (highlightedNodeIds.has(lSrcId) || highlightedNodeIds.has(lTgtId)) {{
- highlightedNodeIds.add(lSrcId);
- highlightedNodeIds.add(lTgtId);
- highlightedEdgeKeys.add(`${{lSrcId}}|${{lTgtId}}`);
- highlightedEdgeKeys.add(`${{lTgtId}}|${{lSrcId}}`);
- }}
- }});
- highlightRightTree(highlightedNodeIds, highlightedEdgeKeys);
- }}
- }}
- }});
- // 在有分数的边上显示分数(统一逻辑)
- 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;
- 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", // 紫色 - 标签属于分类
- "包含": "#ffb6c1", // 淡粉 - 分类包含标签(向下)
- "分类共现(跨点)": "#2ecc71", // 绿色 - 跨帖子分类共现
- "分类共现(点内)": "#3498db", // 蓝色 - 同帖子分类共现
- "标签共现": "#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}})`);
- }});
- // 拖拽函数
- 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 highlightEdge(clickedLink, clickedIndex) {{
- const highlightNodeIds = new Set();
- const highlightLinkIndices = new Set([clickedIndex]);
- const sourceId = typeof clickedLink.source === "object" ? clickedLink.source.id : clickedLink.source;
- const targetId = typeof clickedLink.target === "object" ? clickedLink.target.id : clickedLink.target;
- highlightNodeIds.add(sourceId);
- highlightNodeIds.add(targetId);
- // 如果是镜像边或二阶边,使用预计算的路径节点高亮
- if ((clickedLink.type.startsWith("镜像_") || clickedLink.type.startsWith("二阶_")) && clickedLink.边详情) {{
- const detail = clickedLink.边详情;
- const pathNodes = new Set([sourceId, targetId]);
- // 使用预计算的路径节点
- (detail.路径节点 || []).forEach(n => pathNodes.add(n));
- // 高亮路径上的所有节点
- pathNodes.forEach(n => highlightNodeIds.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)) {{
- highlightLinkIndices.add(i);
- }}
- }});
- }}
- // 如果是人设边(两端都不是帖子节点),找对应的镜像边
- else if (!sourceId.startsWith("帖子_") && !targetId.startsWith("帖子_")) {{
- // 收集路径节点
- const pathNodes = new Set([sourceId, targetId]);
- // 找匹配的镜像边,读取其路径节点
- 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) {{
- highlightLinkIndices.add(i);
- // 直接使用预存的路径节点
- (detail.路径节点 || []).forEach(n => pathNodes.add(n));
- }}
- }}
- }});
- // 高亮路径上的所有节点
- pathNodes.forEach(n => highlightNodeIds.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)) {{
- highlightLinkIndices.add(i);
- }}
- }});
- }}
- // 高亮相关的节点和边
- 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);
- }}
- // 点击空白处清除高亮(合并所有空白点击逻辑)
- 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");
- }});
- }});
- }}
- // 高亮匹配边
- function highlightMatchEdge(srcId, tgtId) {{
- if (!g) return;
- // 重置所有
- g.selectAll(".node").classed("dimmed", true).classed("highlighted", false);
- g.selectAll(".link-group").classed("dimmed", true).classed("highlighted", false);
- // 高亮对应的边和节点
- g.selectAll(".link-group").each(function(d) {{
- const dSrc = typeof d.source === "object" ? d.source.id : d.source;
- const dTgt = typeof d.target === "object" ? d.target.id : d.target;
- if ((dSrc === srcId && dTgt === tgtId) || (dSrc === tgtId && dTgt === srcId)) {{
- d3.select(this).classed("dimmed", false).classed("highlighted", true);
- }}
- }});
- g.selectAll(".node").each(function(d) {{
- if (d.id === srcId || d.id === tgtId) {{
- d3.select(this).classed("dimmed", false).classed("highlighted", true);
- }}
- }});
- }}
- // 获取节点颜色(全局版本,根据节点数据判断维度)
- 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", // 紫色 - 层级关系
- "包含": "#ffb6c1", // 淡粉 - 分类包含标签(向下)
- "分类共现(跨点)": "#2ecc71", // 绿色 - 跨帖子分类共现
- "分类共现(点内)": "#3498db", // 蓝色 - 同帖子分类共现
- "标签共现": "#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;
- }});
- }}
- // 恢复右边树的高亮状态
- 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);
- }}
- // 渲染路径上的所有节点和边(点击镜像边/二阶边时调用)
- 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",
- "包含": "#ffb6c1",
- "分类共现(跨点)": "#2ecc71",
- "分类共现(点内)": "#3498db",
- "标签共现": "#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",
- "包含": "#ffb6c1",
- "分类共现(跨点)": "#2ecc71",
- "分类共现(点内)": "#3498db",
- "标签共现": "#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: 输出文件路径
- """
- # 生成Tab HTML
- tabs_html = ""
- for i, data in enumerate(all_graph_data):
- post_title = data.get("postTitle", "")
- # 使用帖子标题,如果太长则截断
- if post_title:
- tab_name = post_title[:15] + "..." if len(post_title) > 15 else post_title
- else:
- tab_name = f"帖子 {i+1}"
- active_class = "active" if i == 0 else ""
- tabs_html += f'<div class="tab {active_class}" data-index="{i}">{tab_name}</div>\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()
|