| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689 |
- #!/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;
- }}
- </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="包含" checked><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="包含" checked><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 class="controls">
- <div class="control-label">视图控制</div>
- <button onclick="resetZoom()">重置视图</button>
- <button onclick="toggleLabels()">切换标签</button>
- <button onclick="toggleCrossLayerEdges()" id="crossLayerBtn">显示跨层边</button>
- <div class="control-group">
- <div class="control-label">人设树配置</div>
- <button onclick="toggleTreeTags()" id="treeTagBtn" class="active">显示标签</button>
- <select id="treeDepthSelect" onchange="setTreeDepth(this.value)">
- <option value="0">全部层级</option>
- <option value="2">2层</option>
- <option value="3">3层</option>
- <option value="4">4层</option>
- <option value="5">5层</option>
- </select>
- </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));
- }}
- }}
- // 切换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.map(n => ({{
- ...n,
- id: n.节点ID,
- source: n.节点ID.startsWith("帖子_") ? "帖子" : "人设",
- level: n.节点层级
- }}));
- const links = data.edges.map(e => ({{
- ...e,
- source: e.源节点ID,
- target: e.目标节点ID,
- type: e.边类型
- }}));
- // 分离节点类型
- 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"
- }};
- // 获取节点的层级编号(三层结构)
- function getNodeLayer(d) {{
- if (d.source === "帖子") {{
- return d.节点类型 === "点" ? 0 : 1; // 点=0, 标签=1
- }}
- return 2; // 人设(标签+分类)都在层2
- }}
- // 统计每层节点数量(三层结构)
- const layerCounts = {{0: 0, 1: 0, 2: 0}};
- nodes.forEach(n => {{
- const layer = getNodeLayer(n);
- layerCounts[layer]++;
- }});
- console.log("每层节点数:", layerCounts);
- // 根据节点数量计算每层圆的半径
- // 左列:帖子标签(上) + 人设匹配(下),右列:帖子点(同一行开始)
- // 左列是主要展示区域,视图中心对准左列
- 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 layerRadius = {{
- 0: calcRadius(layerCounts[0]), // 帖子点(右列)
- 1: calcRadius(layerCounts[1]), // 帖子标签(左上)
- 2: calcRadius(layerCounts[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;
- // 计算布局:左列(帖子标签+人设匹配),右列(帖子点)
- const layerPadding = 40;
- const leftColHeight = layerRadius[1] * 2 + layerPadding + layerRadius[2] * 2 + layerPadding;
- const circleHeight = leftColHeight;
- const height = Math.max(circleHeight + 80, treeHeight + 80, container.clientHeight);
- // 计算每层圆心坐标
- const layerCenterX = {{}};
- const layerCenterY = {{}};
- // 左列居中显示,右列在旁边
- const leftColX = circleAreaCenterX; // 左列居中
- const rightColX = leftColX + Math.max(layerRadius[1], layerRadius[2]) + layerPadding + layerRadius[0] + 30; // 右列在右边
- // 左列:帖子标签(上)+ 人设匹配(下)
- layerCenterX[1] = leftColX;
- layerCenterY[1] = layerRadius[1] + layerPadding / 2 + 20;
- layerCenterX[2] = leftColX;
- layerCenterY[2] = layerCenterY[1] + layerRadius[1] + layerPadding + layerRadius[2];
- // 右列:帖子点(与帖子标签同一行开始)
- layerCenterX[0] = rightColX;
- layerCenterY[0] = layerCenterY[1]; // 与帖子标签同一行
- 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);
- 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 layerBg = g.append("g").attr("class", "layer-backgrounds");
- // 层配置:名称、颜色(三层圆,关系图在左侧)
- const layerConfig = [
- {{ name: "帖子点", layer: 0, color: "rgba(243, 156, 18, 0.08)", stroke: "rgba(243, 156, 18, 0.3)" }},
- {{ name: "帖子标签", layer: 1, color: "rgba(52, 152, 219, 0.08)", stroke: "rgba(52, 152, 219, 0.3)" }},
- {{ name: "人设匹配", layer: 2, color: "rgba(155, 89, 182, 0.08)", stroke: "rgba(155, 89, 182, 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();
- 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", "block"); // 匹配边始终显示
- }} else if (isCrossLayerEdge(d) && !showCrossLayerEdges) {{
- d3.select(this).style("display", "none");
- }}
- }});
- // 为匹配边添加分数标签
- const edgeLabels = linkG.filter(d => d.type.startsWith("匹配_") && d.边详情 && d.边详情.相似度)
- .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 => {{
- const score = d.边详情.相似度;
- return typeof score === "number" ? score.toFixed(2) : score;
- }});
- // 边的点击事件
- linkHitarea.on("click", (event, d, i) => {{
- event.stopPropagation();
- const linkIndex = links.indexOf(d);
- highlightEdge(d, linkIndex);
- showEdgeInfo(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 && sourceNode.source === "人设") {{
- handleNodeClick(sourceNode.节点ID, sourceNode.节点名称);
- }} else if (targetNode && targetNode.source === "人设") {{
- handleNodeClick(targetNode.节点ID, targetNode.节点名称);
- }}
- }})
- .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.节点名称);
- }}
- }});
- // 更新位置
- 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.边详情) {{
- const detail = clickedLink.边详情;
- // 分类节点
- if (detail.分类节点1) highlightNodeIds.add(detail.分类节点1);
- if (detail.分类节点2) highlightNodeIds.add(detail.分类节点2);
- // 标签节点
- if (detail.标签节点1) highlightNodeIds.add(detail.标签节点1);
- if (detail.标签节点2) highlightNodeIds.add(detail.标签节点2);
- // 找出路径上的边
- 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 (link.type.startsWith("匹配_")) {{
- if ((lSrc === sourceId && lTgt === detail.标签节点1) ||
- (lSrc === targetId && lTgt === detail.标签节点2)) {{
- highlightLinkIndices.add(i);
- }}
- }}
- // 标签->分类 的属于边
- if (link.type === "属于") {{
- if ((lSrc === detail.标签节点1 && lTgt === detail.分类节点1) ||
- (lSrc === detail.标签节点2 && lTgt === detail.分类节点2)) {{
- highlightLinkIndices.add(i);
- }}
- }}
- // 分类之间的边
- if ((lSrc === detail.分类节点1 && lTgt === detail.分类节点2) ||
- (lSrc === detail.分类节点2 && lTgt === detail.分类节点1)) {{
- highlightLinkIndices.add(i);
- }}
- }});
- }}
- // 如果是镜像边,显示对应的人设边
- else if (clickedLink.type.startsWith("镜像_") && clickedLink.边详情) {{
- const detail = clickedLink.边详情;
- if (detail.源人设节点) highlightNodeIds.add(detail.源人设节点);
- if (detail.目标人设节点) highlightNodeIds.add(detail.目标人设节点);
- // 找出对应的人设边和匹配边
- 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 (link.type.startsWith("匹配_")) {{
- if ((lSrc === sourceId && lTgt === detail.源人设节点) ||
- (lSrc === targetId && lTgt === detail.目标人设节点)) {{
- highlightLinkIndices.add(i);
- }}
- }}
- // 人设边
- if ((lSrc === detail.源人设节点 && lTgt === detail.目标人设节点) ||
- (lSrc === detail.目标人设节点 && lTgt === detail.源人设节点)) {{
- highlightLinkIndices.add(i);
- }}
- }});
- }}
- // 高亮相关的节点和边
- highlightElements(highlightNodeIds, highlightLinkIndices);
- // 临时显示关联的跨层边(即使全局开关是关闭的)
- linkG.each(function(d, i) {{
- if (highlightLinkIndices.has(i)) {{
- d3.select(this).style("display", "block");
- }}
- }});
- }}
- // 点击空白处清除高亮(合并所有空白点击逻辑)
- 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();
- // 关闭详情面板
- 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);
- }}
- // 高亮右侧图中对应节点及其相关节点和边
- if (g) {{
- // 收集相关节点ID(点击的节点及其直接连接的节点)
- const relatedNodeIds = new Set([clickedNodeId]);
- // 找所有与该节点相连的边
- 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) {{
- relatedNodeIds.add(srcId);
- relatedNodeIds.add(tgtId);
- }}
- }});
- // 检查是否有相关节点在图中
- const hasRelatedNodes = g.selectAll(".node").filter(n => relatedNodeIds.has(n.id)).size() > 0;
- if (hasRelatedNodes) {{
- // 高亮相关节点,变灰其他
- g.selectAll(".node")
- .classed("dimmed", n => !relatedNodeIds.has(n.id))
- .classed("highlighted", n => relatedNodeIds.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);
- }}
- }}
- }}
- // 共享的边点击处理函数(人设树和关系图复用)
- function handleEdgeClick(srcNodeId, tgtNodeId, edgeType) {{
- // 动态获取树相关元素
- 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 sourceTreeNode = treeNodeById[srcNodeId];
- const targetTreeNode = treeNodeById[tgtNodeId];
- // 高亮树边(不变粗)
- treeEdges.attr("stroke-opacity", function(e) {{
- const isThisEdge = (e.源节点ID === srcNodeId && e.目标节点ID === tgtNodeId) ||
- (e.源节点ID === tgtNodeId && e.目标节点ID === srcNodeId);
- return isThisEdge ? 1 : 0.1;
- }});
- // 高亮相关节点
- const connectedNodes = new Set();
- if (sourceTreeNode) connectedNodes.add(sourceTreeNode);
- if (targetTreeNode) connectedNodes.add(targetTreeNode);
- treeGroup.selectAll(".tree-node .tree-shape")
- .attr("fill", n => connectedNodes.has(n) ? getTreeNodeColor(n) : "#555")
- .attr("opacity", 1);
- treeGroup.selectAll(".tree-node text")
- .attr("fill", n => connectedNodes.has(n) ?
- ((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 srcNode = personaTreeData.nodes.find(n => n.节点ID === srcNodeId);
- const tgtNode = personaTreeData.nodes.find(n => n.节点ID === tgtNodeId);
- const srcName = sourceTreeNode ? (sourceTreeNode.data.节点名称 || sourceTreeNode.data.name) : (srcNode?.节点名称 || srcNodeId);
- const tgtName = targetTreeNode ? (targetTreeNode.data.节点名称 || targetTreeNode.data.name) : (tgtNode?.节点名称 || tgtNodeId);
- let html = `
- <p><span class="label">边类型:</span> <strong>${{edgeType}}</strong></p>
- <p><span class="label">源节点:</span> ${{srcName}}</p>
- <p><span class="label">目标节点:</span> ${{tgtName}}</p>
- `;
- document.getElementById("detailContent").innerHTML = html;
- // 高亮右侧人设匹配区域
- if (g) {{
- const relatedNodeIds = new Set([srcNodeId, tgtNodeId]);
- const hasRelatedNodes = g.selectAll(".node").filter(n => relatedNodeIds.has(n.id)).size() > 0;
- if (hasRelatedNodes) {{
- // 高亮相关节点
- g.selectAll(".node")
- .classed("dimmed", n => !relatedNodeIds.has(n.id))
- .classed("highlighted", n => relatedNodeIds.has(n.id));
- // 高亮相关边
- g.selectAll(".link-group").each(function(d) {{
- const sid = typeof d.source === "object" ? d.source.id : d.source;
- const tid = typeof d.target === "object" ? d.target.id : d.target;
- const isRelated = (sid === srcNodeId && tid === tgtNodeId) ||
- (sid === tgtNodeId && tid === srcNodeId) ||
- relatedNodeIds.has(sid) || relatedNodeIds.has(tid);
- d3.select(this)
- .classed("dimmed", !isRelated)
- .classed("highlighted", isRelated);
- }});
- }} else {{
- // 全部变灰
- g.selectAll(".node").classed("dimmed", true).classed("highlighted", false);
- g.selectAll(".link-group").classed("dimmed", true).classed("highlighted", false);
- }}
- }}
- // 在关系图中展示这条边和两个节点
- const edgeData = {{
- 边类型: edgeType,
- 源节点ID: srcNodeId,
- 目标节点ID: tgtNodeId
- }};
- renderEgoGraphEdge(edgeData, sourceTreeNode, targetTreeNode);
- }}
- // 关系子图(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);
- }}
- }}
- // 重置所有层级到默认配置(1级全选,2/3级只选包含)
- function resetSelection() {{
- event.stopPropagation();
- // Level 1: 全选
- document.querySelectorAll('.cascade-edge-item input[data-level="1"]').forEach(cb => {{
- cb.checked = true;
- }});
- document.querySelector('.select-all input[data-level="1"]').checked = true;
- // Level 2 & 3: 只选包含
- [2, 3].forEach(level => {{
- document.querySelectorAll(`.cascade-edge-item input[data-level="${{level}}"]`).forEach(cb => {{
- cb.checked = (cb.dataset.type === "包含");
- }});
- 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
- }});
- }});
- }});
- // 根据节点数量动态计算实际使用的半径
- 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 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}})`);
- }});
- }}
- 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";
- }});
- // 隐藏不在路径上的节点(保持布局不变)
- egoNodes
- .style("visibility", function(d) {{
- return pathNodes.has(d.id) ? "visible" : "hidden";
- }});
- }}
- // 恢复关系图的高亮状态
- function resetEgoGraphHighlight() {{
- const egoGroup = d3.select(".ego-graph-content");
- if (egoGroup.empty()) return;
- // 恢复边的可见性
- egoGroup.selectAll(".ego-edge")
- .style("visibility", "visible");
- // 恢复节点的可见性
- egoGroup.selectAll(".ego-node")
- .style("visibility", "visible");
- }}
- // 渲染单条边和两个节点(点击树边时调用)
- 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()
- # 读取所有匹配图谱文件
- graph_files = sorted(match_graph_dir.glob("*_match_graph.json"))
- print(f"找到 {len(graph_files)} 个匹配图谱文件")
- 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)
- # 提取需要的数据
- graph_data = {
- "postId": match_graph_data["说明"]["帖子ID"],
- "postTitle": match_graph_data["说明"].get("帖子标题", ""),
- "stats": match_graph_data["说明"]["统计"],
- "nodes": match_graph_data["节点列表"],
- "edges": match_graph_data["边列表"]
- }
- 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()
|