visualize_match_graph.py 214 KB

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