visualize_match_graph.py 178 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391
  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="包含" checked><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="包含" checked><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 class="controls">
  1043. <div class="control-label">视图控制</div>
  1044. <button onclick="resetZoom()">重置视图</button>
  1045. <button onclick="toggleLabels()">切换标签</button>
  1046. <button onclick="toggleCrossLayerEdges()" id="crossLayerBtn">显示跨层边</button>
  1047. <div class="control-group">
  1048. <div class="control-label">人设树配置</div>
  1049. <button onclick="toggleTreeTags()" id="treeTagBtn" class="active">显示标签</button>
  1050. <select id="treeDepthSelect" onchange="setTreeDepth(this.value)">
  1051. <option value="0">全部层级</option>
  1052. <option value="2">2层</option>
  1053. <option value="3">3层</option>
  1054. <option value="4">4层</option>
  1055. <option value="5">5层</option>
  1056. </select>
  1057. </div>
  1058. </div>
  1059. </div>
  1060. </div>
  1061. </div>
  1062. <script>
  1063. // 所有帖子的图谱数据
  1064. const allGraphData = {all_graph_data};
  1065. // 完整的人设树数据(所有人设节点和属于边)
  1066. const personaTreeData = {persona_tree_data};
  1067. // 当前选中的帖子索引
  1068. let currentIndex = 0;
  1069. let simulation = null;
  1070. let svg = null;
  1071. let g = null;
  1072. let treeSvg = null; // 人设树独立SVG
  1073. let treeG = null; // 人设树group
  1074. let egoSvg = null; // 关系图独立SVG
  1075. let egoG = null; // 关系图group
  1076. let zoom = null;
  1077. let showLabels = true;
  1078. let showCrossLayerEdges = false; // 跨层边默认隐藏
  1079. let isCrossLayerEdge = null; // 跨层边判断函数(在renderGraph中设置)
  1080. // 人设树配置
  1081. let showTreeTags = true; // 是否显示标签节点
  1082. let treeMaxDepth = 0; // 显示的最大层数(0=全部)
  1083. // 切换标签显示
  1084. function toggleTreeTags() {{
  1085. showTreeTags = !showTreeTags;
  1086. const btn = document.getElementById("treeTagBtn");
  1087. btn.textContent = showTreeTags ? "显示标签" : "隐藏标签";
  1088. btn.classList.toggle("active", showTreeTags);
  1089. // 重新渲染当前图谱
  1090. renderGraph(allGraphData[currentIndex]);
  1091. }}
  1092. // 设置树的显示层数
  1093. function setTreeDepth(depth) {{
  1094. treeMaxDepth = parseInt(depth);
  1095. // 重新渲染当前图谱
  1096. renderGraph(allGraphData[currentIndex]);
  1097. }}
  1098. // 初始化
  1099. function init() {{
  1100. const container = document.getElementById("graph");
  1101. const treeContainer = document.getElementById("tree-container");
  1102. const width = container.clientWidth;
  1103. const height = container.clientHeight;
  1104. // 创建圆形层SVG
  1105. svg = d3.select("#graph")
  1106. .append("svg")
  1107. .attr("width", width)
  1108. .attr("height", height);
  1109. g = svg.append("g");
  1110. zoom = d3.zoom()
  1111. .scaleExtent([0.1, 4])
  1112. .on("zoom", (event) => {{
  1113. g.attr("transform", event.transform);
  1114. }});
  1115. svg.call(zoom);
  1116. // 创建人设树SVG(独立可滚动)
  1117. treeSvg = d3.select("#tree-container")
  1118. .append("svg")
  1119. .attr("width", 400);
  1120. treeG = treeSvg.append("g");
  1121. // 创建关系图SVG(在独立的ego-container中)
  1122. egoSvg = d3.select("#ego-container")
  1123. .append("svg")
  1124. .attr("width", 400)
  1125. .attr("height", 400);
  1126. egoG = egoSvg.append("g");
  1127. // 关系图缩放
  1128. const egoZoom = d3.zoom()
  1129. .scaleExtent([0.3, 3])
  1130. .on("zoom", (event) => {{
  1131. egoG.attr("transform", event.transform);
  1132. }});
  1133. egoSvg.call(egoZoom);
  1134. // 绑定Tab点击事件
  1135. document.querySelectorAll(".tab").forEach((tab, index) => {{
  1136. tab.addEventListener("click", () => switchTab(index));
  1137. }});
  1138. // 绑定关系图控制面板事件
  1139. // 全选复选框事件
  1140. document.querySelectorAll('.select-all input').forEach(cb => {{
  1141. cb.addEventListener('change', (e) => {{
  1142. const level = e.target.dataset.level;
  1143. const checked = e.target.checked;
  1144. // 设置该层级所有边类型复选框
  1145. document.querySelectorAll(`.cascade-edge-item input[data-level="${{level}}"]`).forEach(item => {{
  1146. item.checked = checked;
  1147. }});
  1148. // 重新渲染关系图和人设树高亮
  1149. if (currentEgoCenterNodeId) {{
  1150. handleNodeClick(currentEgoCenterNodeId, currentEgoCenterNodeName);
  1151. }}
  1152. }});
  1153. }});
  1154. // 边类型复选框变化事件
  1155. document.querySelectorAll('.cascade-edge-item input').forEach(cb => {{
  1156. cb.addEventListener('change', (e) => {{
  1157. // 更新全选复选框状态
  1158. const level = e.target.dataset.level;
  1159. const allItems = document.querySelectorAll(`.cascade-edge-item input[data-level="${{level}}"]`);
  1160. const checkedItems = document.querySelectorAll(`.cascade-edge-item input[data-level="${{level}}"]:checked`);
  1161. const selectAllCb = document.querySelector(`.select-all input[data-level="${{level}}"]`);
  1162. selectAllCb.checked = allItems.length === checkedItems.length;
  1163. // 重新渲染关系图和人设树高亮
  1164. if (currentEgoCenterNodeId) {{
  1165. handleNodeClick(currentEgoCenterNodeId, currentEgoCenterNodeName);
  1166. }}
  1167. }});
  1168. }});
  1169. // 点击页面其他地方关闭级联菜单
  1170. document.addEventListener('click', (e) => {{
  1171. if (!e.target.closest('.cascade-dropdown')) {{
  1172. document.getElementById('cascade-menu').classList.remove('show');
  1173. }}
  1174. }});
  1175. // 显示第一个帖子
  1176. switchTab(0);
  1177. }}
  1178. // 构建人设树数据(合并为一棵树,根节点为"人设")
  1179. // showTreeTags: 控制是否显示标签节点
  1180. // treeMaxDepth: 控制树的显示深度(0=全部,2=维度,3=+一层,4=+两层...)
  1181. function buildPersonaTreeData() {{
  1182. const dimensions = ["灵感点", "目的点", "关键点"];
  1183. const dimColors = {{ "灵感点": "#f39c12", "目的点": "#3498db", "关键点": "#9b59b6" }};
  1184. const dimensionChildren = [];
  1185. let totalNodeCount = 0;
  1186. dimensions.forEach(dim => {{
  1187. // 根据 showTreeTags 过滤节点(独立于深度控制)
  1188. let dimNodes = personaTreeData.nodes.filter(n => n.节点层级 === dim);
  1189. if (!showTreeTags) {{
  1190. dimNodes = dimNodes.filter(n => n.节点类型 !== "标签");
  1191. }}
  1192. if (dimNodes.length === 0) {{
  1193. const dimNode = {{
  1194. name: dim,
  1195. 节点名称: dim,
  1196. isDimension: true,
  1197. dimColor: dimColors[dim],
  1198. children: []
  1199. }};
  1200. dimensionChildren.push(dimNode);
  1201. return;
  1202. }}
  1203. const nodeMap = {{}};
  1204. dimNodes.forEach(n => nodeMap[n.节点ID] = {{ ...n, name: n.节点名称, children: [], dimColor: dimColors[dim] }});
  1205. // 只用属于边构建父子关系
  1206. const hierarchyEdgeTypes = ["属于"];
  1207. const hasParent = new Set();
  1208. personaTreeData.edges.forEach(e => {{
  1209. if (!hierarchyEdgeTypes.includes(e.边类型)) return; // 跳过非层级边
  1210. const srcNode = nodeMap[e.源节点ID];
  1211. const tgtNode = nodeMap[e.目标节点ID];
  1212. if (srcNode && tgtNode) {{
  1213. tgtNode.children.push(srcNode);
  1214. hasParent.add(e.源节点ID);
  1215. }}
  1216. }});
  1217. const roots = dimNodes.filter(n => !hasParent.has(n.节点ID)).map(n => nodeMap[n.节点ID]);
  1218. const dimNode = {{
  1219. name: dim,
  1220. 节点名称: dim,
  1221. isDimension: true,
  1222. dimColor: dimColors[dim],
  1223. children: roots
  1224. }};
  1225. dimensionChildren.push(dimNode);
  1226. totalNodeCount += dimNodes.length;
  1227. }});
  1228. // 根节点"人设"
  1229. const rootNode = {{
  1230. name: "人设",
  1231. 节点名称: "人设",
  1232. isRoot: true,
  1233. children: dimensionChildren
  1234. }};
  1235. // 根据 treeMaxDepth 截断树深度(0=全部)
  1236. // 深度1=根,深度2=维度,深度3+=子节点
  1237. if (treeMaxDepth > 0) {{
  1238. truncateTree(rootNode, 1, treeMaxDepth);
  1239. }}
  1240. return {{ root: rootNode, nodeCount: totalNodeCount }};
  1241. }}
  1242. // 递归截断树的深度
  1243. function truncateTree(node, currentDepth, maxDepth) {{
  1244. if (currentDepth >= maxDepth) {{
  1245. node.children = [];
  1246. return;
  1247. }}
  1248. if (node.children) {{
  1249. node.children.forEach(child => truncateTree(child, currentDepth + 1, maxDepth));
  1250. }}
  1251. }}
  1252. // 构建帖子树数据(从上到下:帖子 -> 维度 -> 点 -> 标签)
  1253. function buildPostTreeData(graphData) {{
  1254. const dimensions = ["灵感点", "目的点", "关键点"];
  1255. const dimColors = {{ "灵感点": "#f39c12", "目的点": "#3498db", "关键点": "#9b59b6" }};
  1256. const dimensionChildren = [];
  1257. let totalNodeCount = 0;
  1258. const postDetail = graphData.postDetail || {{}};
  1259. // 获取帖子点和帖子标签
  1260. const postPointNodes = graphData.帖子点节点列表 || [];
  1261. const postTagNodes = graphData.帖子标签节点列表 || [];
  1262. const belongEdges = graphData.帖子属于边列表 || [];
  1263. // 构建节点映射
  1264. const pointMap = {{}};
  1265. postPointNodes.forEach(n => {{
  1266. pointMap[n.节点ID] = {{
  1267. ...n,
  1268. id: n.节点ID,
  1269. name: n.节点名称,
  1270. nodeType: "点",
  1271. dimColor: dimColors[n.节点层级],
  1272. children: []
  1273. }};
  1274. }});
  1275. const tagMap = {{}};
  1276. postTagNodes.forEach(n => {{
  1277. tagMap[n.节点ID] = {{
  1278. ...n,
  1279. id: n.节点ID,
  1280. name: n.节点名称,
  1281. nodeType: "标签",
  1282. dimColor: dimColors[n.节点层级],
  1283. children: []
  1284. }};
  1285. }});
  1286. // 根据属于边,把标签挂到点下面
  1287. belongEdges.forEach(e => {{
  1288. const tagNode = tagMap[e.源节点ID];
  1289. const pointNode = pointMap[e.目标节点ID];
  1290. if (tagNode && pointNode) {{
  1291. pointNode.children.push(tagNode);
  1292. }}
  1293. }});
  1294. // 按维度分组点节点
  1295. dimensions.forEach(dim => {{
  1296. const dimPoints = postPointNodes
  1297. .filter(n => n.节点层级 === dim)
  1298. .map(n => pointMap[n.节点ID]);
  1299. if (dimPoints.length > 0) {{
  1300. const dimNode = {{
  1301. name: dim,
  1302. 节点名称: dim,
  1303. isDimension: true,
  1304. dimColor: dimColors[dim],
  1305. children: dimPoints
  1306. }};
  1307. dimensionChildren.push(dimNode);
  1308. totalNodeCount += dimPoints.length;
  1309. dimPoints.forEach(p => totalNodeCount += p.children.length);
  1310. }}
  1311. }});
  1312. // 根节点"帖子"
  1313. const title = postDetail.title || "帖子";
  1314. const rootNode = {{
  1315. name: title.length > 15 ? title.substring(0, 15) + "..." : title,
  1316. 节点名称: title,
  1317. isRoot: true,
  1318. postDetail: postDetail,
  1319. children: dimensionChildren
  1320. }};
  1321. return {{ root: rootNode, nodeCount: totalNodeCount, tagMap: tagMap }};
  1322. }}
  1323. // 显示帖子详情模态框
  1324. function showPostDetail(postData) {{
  1325. if (!postData) return;
  1326. // 生成图片HTML
  1327. let imagesHtml = '';
  1328. if (postData.images && postData.images.length > 0) {{
  1329. imagesHtml = postData.images.map(img =>
  1330. `<img src="${{img}}" class="post-detail-image" alt="图片" loading="lazy">`
  1331. ).join('');
  1332. }} else {{
  1333. imagesHtml = '<div style="text-align: center; color: #9ca3af; padding: 40px;">暂无图片</div>';
  1334. }}
  1335. const modalHtml = `
  1336. <div class="post-detail-content" onclick="event.stopPropagation()">
  1337. <button class="post-detail-close" onclick="closePostDetail()">×</button>
  1338. <div class="post-detail-header">
  1339. <div class="post-detail-title">${{postData.title || '无标题'}}</div>
  1340. <div class="post-detail-meta">
  1341. <div>
  1342. <span>👤 ${{postData.author || '未知作者'}}</span>
  1343. <span> · 📅 ${{postData.publish_time || ''}}</span>
  1344. </div>
  1345. <div class="post-detail-stats">
  1346. <span>👍 ${{postData.like_count || 0}}</span>
  1347. <span>💬 ${{postData.comment_count || 0}}</span>
  1348. <span>⭐ ${{postData.collect_count || 0}}</span>
  1349. </div>
  1350. </div>
  1351. </div>
  1352. <div class="post-detail-body">
  1353. ${{postData.body_text ? `<div class="post-detail-desc">${{postData.body_text}}</div>` : '<div style="color: #9ca3af;">暂无正文</div>'}}
  1354. <div class="post-detail-images">
  1355. ${{imagesHtml}}
  1356. </div>
  1357. </div>
  1358. <div class="post-detail-footer">
  1359. <a href="${{postData.link || '#'}}" target="_blank" class="post-detail-link">
  1360. 在小红书查看完整内容 →
  1361. </a>
  1362. </div>
  1363. </div>
  1364. `;
  1365. let modal = document.getElementById('postDetailModal');
  1366. if (!modal) {{
  1367. modal = document.createElement('div');
  1368. modal.id = 'postDetailModal';
  1369. modal.className = 'post-detail-modal';
  1370. modal.onclick = closePostDetail;
  1371. document.body.appendChild(modal);
  1372. }}
  1373. modal.innerHTML = modalHtml;
  1374. modal.classList.add('active');
  1375. document.body.style.overflow = 'hidden';
  1376. }}
  1377. function closePostDetail(event) {{
  1378. if (event && event.target !== event.currentTarget) return;
  1379. const modal = document.getElementById('postDetailModal');
  1380. if (modal) {{
  1381. modal.classList.remove('active');
  1382. document.body.style.overflow = '';
  1383. }}
  1384. }}
  1385. // 切换Tab
  1386. function switchTab(index) {{
  1387. currentIndex = index;
  1388. // 更新Tab样式
  1389. document.querySelectorAll(".tab").forEach((tab, i) => {{
  1390. tab.classList.toggle("active", i === index);
  1391. }});
  1392. // 更新图谱
  1393. renderGraph(allGraphData[index]);
  1394. }}
  1395. // 渲染图谱
  1396. function renderGraph(data) {{
  1397. // 清空现有图谱
  1398. g.selectAll("*").remove();
  1399. treeG.selectAll("*").remove();
  1400. if (simulation) {{
  1401. simulation.stop();
  1402. }}
  1403. const container = document.getElementById("graph");
  1404. const width = container.clientWidth;
  1405. // 布局配置:人设树在左侧独立容器,右侧是圆形层
  1406. const treeAreaWidth = 400; // 固定树宽度
  1407. const circleAreaWidth = width - 40;
  1408. const circleAreaCenterX = circleAreaWidth / 2;
  1409. // 准备数据(过滤掉帖子点,只保留帖子标签和人设节点)
  1410. const nodes = data.nodes
  1411. .filter(n => !(n.节点ID.startsWith("帖子_") && n.节点类型 === "点"))
  1412. .map(n => ({{
  1413. ...n,
  1414. id: n.节点ID,
  1415. source: n.节点ID.startsWith("帖子_") ? "帖子" : "人设",
  1416. level: n.节点层级
  1417. }}));
  1418. // 判断是否是帖子点节点ID
  1419. function isPostPointId(id) {{
  1420. return id.startsWith("帖子_") && id.includes("_点_");
  1421. }}
  1422. // 过滤掉引用帖子点节点的边
  1423. const links = data.edges
  1424. .filter(e => !isPostPointId(e.源节点ID) && !isPostPointId(e.目标节点ID))
  1425. .map(e => ({{
  1426. ...e,
  1427. source: e.源节点ID,
  1428. target: e.目标节点ID,
  1429. type: e.边类型
  1430. }}));
  1431. // 分离节点类型
  1432. const postNodes = nodes.filter(n => n.source === "帖子");
  1433. const personaNodes = nodes.filter(n => n.source === "人设" && !n.是否扩展);
  1434. const expandedNodes = nodes.filter(n => n.source === "人设" && n.是否扩展);
  1435. const matchLinks = links.filter(l => l.type.startsWith("匹配_"));
  1436. // 更新匹配列表(按分数降序)
  1437. updateMatchList(matchLinks, nodes);
  1438. // 构建帖子节点到人设节点的映射
  1439. const postToPersona = {{}};
  1440. const personaToPost = {{}};
  1441. matchLinks.forEach(l => {{
  1442. const sid = typeof l.source === "object" ? l.source.id : l.source;
  1443. const tid = typeof l.target === "object" ? l.target.id : l.target;
  1444. if (!postToPersona[sid]) postToPersona[sid] = [];
  1445. postToPersona[sid].push(tid);
  1446. if (!personaToPost[tid]) personaToPost[tid] = [];
  1447. personaToPost[tid].push(sid);
  1448. }});
  1449. // 找出所有连通分量
  1450. function findConnectedComponents(nodes, links) {{
  1451. const nodeIds = new Set(nodes.map(n => n.id));
  1452. const adj = {{}};
  1453. nodeIds.forEach(id => adj[id] = []);
  1454. links.forEach(l => {{
  1455. const sid = typeof l.source === "object" ? l.source.id : l.source;
  1456. const tid = typeof l.target === "object" ? l.target.id : l.target;
  1457. if (nodeIds.has(sid) && nodeIds.has(tid)) {{
  1458. adj[sid].push(tid);
  1459. adj[tid].push(sid);
  1460. }}
  1461. }});
  1462. const visited = new Set();
  1463. const components = [];
  1464. nodeIds.forEach(startId => {{
  1465. if (visited.has(startId)) return;
  1466. const component = [];
  1467. const queue = [startId];
  1468. while (queue.length > 0) {{
  1469. const id = queue.shift();
  1470. if (visited.has(id)) continue;
  1471. visited.add(id);
  1472. component.push(id);
  1473. adj[id].forEach(neighbor => {{
  1474. if (!visited.has(neighbor)) queue.push(neighbor);
  1475. }});
  1476. }}
  1477. components.push(component);
  1478. }});
  1479. return components;
  1480. }}
  1481. // 按大小排序连通分量(大的在前)
  1482. const components = findConnectedComponents(nodes, links)
  1483. .sort((a, b) => b.length - a.length);
  1484. console.log(`找到 ${{components.length}} 个连通分量`);
  1485. // 为每个节点分配连通分量ID和分量内的X范围
  1486. const nodeToComponent = {{}};
  1487. const componentCenters = {{}};
  1488. const componentBounds = {{}};
  1489. const padding = 50; // 分量之间的间距
  1490. const totalPadding = padding * (components.length - 1);
  1491. const availableWidth = width - totalPadding - 100; // 留边距
  1492. // 根据分量大小分配宽度
  1493. const totalNodes = nodes.length;
  1494. let currentX = 50; // 起始边距
  1495. components.forEach((comp, i) => {{
  1496. const compWidth = Math.max(150, (comp.length / totalNodes) * availableWidth);
  1497. const centerX = currentX + compWidth / 2;
  1498. componentCenters[i] = centerX;
  1499. componentBounds[i] = {{ start: currentX, end: currentX + compWidth, width: compWidth }};
  1500. comp.forEach(nodeId => {{
  1501. nodeToComponent[nodeId] = i;
  1502. }});
  1503. currentX += compWidth + padding;
  1504. }});
  1505. // 使用重心法(Barycenter)减少边交叉
  1506. // 迭代优化:交替调整两层节点的顺序
  1507. const nodeTargetX = {{}};
  1508. const personaXMap = {{}};
  1509. // 对每个连通分量单独处理
  1510. components.forEach((comp, compIdx) => {{
  1511. const bounds = componentBounds[compIdx];
  1512. const compPostNodes = postNodes.filter(n => nodeToComponent[n.id] === compIdx);
  1513. const compPersonaNodes = personaNodes.filter(n => nodeToComponent[n.id] === compIdx);
  1514. if (compPostNodes.length === 0 || compPersonaNodes.length === 0) {{
  1515. // 没有匹配关系的分量,均匀分布
  1516. const spacing = bounds.width / (comp.length + 1);
  1517. comp.forEach((nodeId, i) => {{
  1518. const node = nodes.find(n => n.id === nodeId);
  1519. if (node) {{
  1520. node.x = bounds.start + spacing * (i + 1);
  1521. nodeTargetX[nodeId] = node.x;
  1522. if (node.source === "人设") personaXMap[nodeId] = node.x;
  1523. }}
  1524. }});
  1525. return;
  1526. }}
  1527. // 初始化:给人设节点一个初始顺序
  1528. let personaOrder = compPersonaNodes.map((n, i) => ({{ node: n, order: i }}));
  1529. // 迭代优化(3轮)
  1530. for (let iter = 0; iter < 3; iter++) {{
  1531. // 1. 根据人设节点位置,计算帖子节点的重心
  1532. const postBarycenter = {{}};
  1533. compPostNodes.forEach(pn => {{
  1534. const matched = postToPersona[pn.id] || [];
  1535. if (matched.length > 0) {{
  1536. const avgOrder = matched.reduce((sum, pid) => {{
  1537. const po = personaOrder.find(p => p.node.id === pid);
  1538. return sum + (po ? po.order : 0);
  1539. }}, 0) / matched.length;
  1540. postBarycenter[pn.id] = avgOrder;
  1541. }} else {{
  1542. postBarycenter[pn.id] = 0;
  1543. }}
  1544. }});
  1545. // 按重心排序帖子节点
  1546. const sortedPosts = [...compPostNodes].sort((a, b) =>
  1547. postBarycenter[a.id] - postBarycenter[b.id]
  1548. );
  1549. // 2. 根据帖子节点位置,重新计算人设节点的重心
  1550. const personaBarycenter = {{}};
  1551. compPersonaNodes.forEach(pn => {{
  1552. const matched = personaToPost[pn.id] || [];
  1553. if (matched.length > 0) {{
  1554. const avgOrder = matched.reduce((sum, pid) => {{
  1555. const idx = sortedPosts.findIndex(p => p.id === pid);
  1556. return sum + (idx >= 0 ? idx : 0);
  1557. }}, 0) / matched.length;
  1558. personaBarycenter[pn.id] = avgOrder;
  1559. }} else {{
  1560. personaBarycenter[pn.id] = personaOrder.find(p => p.node.id === pn.id)?.order || 0;
  1561. }}
  1562. }});
  1563. // 更新人设节点顺序
  1564. personaOrder = compPersonaNodes
  1565. .map(n => ({{ node: n, order: personaBarycenter[n.id] }}))
  1566. .sort((a, b) => a.order - b.order)
  1567. .map((item, i) => ({{ node: item.node, order: i }}));
  1568. }}
  1569. // 最终排序
  1570. const finalPersonaOrder = personaOrder.map(p => p.node);
  1571. const postBarycenter = {{}};
  1572. compPostNodes.forEach(pn => {{
  1573. const matched = postToPersona[pn.id] || [];
  1574. if (matched.length > 0) {{
  1575. const avgOrder = matched.reduce((sum, pid) => {{
  1576. const idx = finalPersonaOrder.findIndex(n => n.id === pid);
  1577. return sum + (idx >= 0 ? idx : 0);
  1578. }}, 0) / matched.length;
  1579. postBarycenter[pn.id] = avgOrder;
  1580. }} else {{
  1581. postBarycenter[pn.id] = 0;
  1582. }}
  1583. }});
  1584. const finalPostOrder = [...compPostNodes].sort((a, b) =>
  1585. postBarycenter[a.id] - postBarycenter[b.id]
  1586. );
  1587. // 设置位置
  1588. const personaSpacing = bounds.width / (finalPersonaOrder.length + 1);
  1589. finalPersonaOrder.forEach((n, i) => {{
  1590. n.x = bounds.start + personaSpacing * (i + 1);
  1591. nodeTargetX[n.id] = n.x;
  1592. personaXMap[n.id] = n.x;
  1593. }});
  1594. const postSpacing = bounds.width / (finalPostOrder.length + 1);
  1595. finalPostOrder.forEach((n, i) => {{
  1596. // 帖子节点用重心位置(匹配人设的平均X)
  1597. const matched = postToPersona[n.id] || [];
  1598. if (matched.length > 0) {{
  1599. const avgX = matched.reduce((sum, pid) => sum + (personaXMap[pid] || bounds.start + bounds.width/2), 0) / matched.length;
  1600. n.x = avgX;
  1601. }} else {{
  1602. n.x = bounds.start + postSpacing * (i + 1);
  1603. }}
  1604. nodeTargetX[n.id] = n.x;
  1605. }});
  1606. }});
  1607. // 节点颜色
  1608. const levelColors = {{
  1609. "灵感点": "#f39c12",
  1610. "目的点": "#3498db",
  1611. "关键点": "#9b59b6"
  1612. }};
  1613. // 获取节点的层级编号(三层结构:帖子标签、人设匹配1层、人设匹配2层)
  1614. function getNodeLayer(d) {{
  1615. if (d.source === "帖子") {{
  1616. return 0; // 帖子标签=0
  1617. }}
  1618. // 人设节点:根据是否扩展分成两层
  1619. return d.是否扩展 ? 2 : 1; // 直接匹配=1, 扩展=2
  1620. }}
  1621. // 统计每层节点数量(三层结构)
  1622. const layerCounts = {{0: 0, 1: 0, 2: 0}};
  1623. nodes.forEach(n => {{
  1624. const layer = getNodeLayer(n);
  1625. layerCounts[layer]++;
  1626. }});
  1627. console.log("每层节点数:", layerCounts);
  1628. // 根据节点数量计算每层圆的半径
  1629. // 三层垂直排列:帖子标签(上)+ 人设匹配1层(中)+ 人设匹配2层(下)
  1630. const minRadius = 80;
  1631. const maxRadius = Math.min(circleAreaWidth / 3 - 20, 180);
  1632. const nodeSpacing = 60;
  1633. function calcRadius(nodeCount) {{
  1634. if (nodeCount <= 1) return minRadius;
  1635. const circumference = nodeCount * nodeSpacing;
  1636. const r = circumference / (2 * Math.PI);
  1637. return Math.max(minRadius, Math.min(maxRadius, r));
  1638. }}
  1639. // 三层统一大小(取最大值)
  1640. const unifiedRadius = Math.max(
  1641. calcRadius(layerCounts[0]),
  1642. calcRadius(layerCounts[1]),
  1643. calcRadius(layerCounts[2])
  1644. );
  1645. const layerRadius = {{
  1646. 0: unifiedRadius, // 帖子标签(上)
  1647. 1: unifiedRadius, // 人设匹配1层(中)
  1648. 2: unifiedRadius // 人设匹配2层(下)
  1649. }};
  1650. console.log("每层半径:", layerRadius);
  1651. // 获取人设树数据(单棵树)
  1652. const personaTree = buildPersonaTreeData();
  1653. // 树高度自适应:根据节点数量,每个节点约12px,最小800
  1654. const treeHeight = Math.max(800, personaTree.nodeCount * 12 + 150);
  1655. // 关系图配置(放在树下方)
  1656. const egoRadius = 180;
  1657. const egoAreaHeight = egoRadius * 2 + 80;
  1658. // 计算布局:三层垂直排列(帖子标签+人设匹配1层+人设匹配2层)
  1659. const layerPadding = 60;
  1660. const circleHeight = layerRadius[0] * 2 + layerPadding + layerRadius[1] * 2 + layerPadding + layerRadius[2] * 2 + layerPadding;
  1661. const height = Math.max(circleHeight + 80, treeHeight + 80, container.clientHeight);
  1662. // 计算每层圆心坐标(垂直居中排列)
  1663. const layerCenterX = {{}};
  1664. const layerCenterY = {{}};
  1665. // 三层垂直排列,X坐标相同
  1666. const colX = circleAreaCenterX;
  1667. // 帖子标签(上)+ 人设匹配1层(中)+ 人设匹配2层(下)
  1668. layerCenterX[0] = colX;
  1669. layerCenterY[0] = layerRadius[0] + layerPadding / 2 + 20;
  1670. layerCenterX[1] = colX;
  1671. layerCenterY[1] = layerCenterY[0] + layerRadius[0] + layerPadding + layerRadius[1];
  1672. layerCenterX[2] = colX;
  1673. layerCenterY[2] = layerCenterY[1] + layerRadius[1] + layerPadding + layerRadius[2];
  1674. console.log("每层圆心X:", layerCenterX);
  1675. console.log("每层圆心Y:", layerCenterY);
  1676. // 更新SVG高度
  1677. svg.attr("height", height);
  1678. // 获取节点的基准Y(层圆心)
  1679. function getNodeBaseY(d) {{
  1680. const layer = getNodeLayer(d);
  1681. return layerCenterY[layer];
  1682. }}
  1683. // 获取节点的基准X(层圆心)
  1684. function getNodeBaseX(d) {{
  1685. const layer = getNodeLayer(d);
  1686. return layerCenterX[layer];
  1687. }}
  1688. // 层边界配置(不再使用)
  1689. const layerBounds = {{}};
  1690. // 自定义层内排斥力(只对同层节点生效,尽量分散)
  1691. function forceIntraLayerRepulsion(strength) {{
  1692. let nodes;
  1693. function force(alpha) {{
  1694. for (let i = 0; i < nodes.length; i++) {{
  1695. const nodeA = nodes[i];
  1696. const layerA = getNodeLayer(nodeA);
  1697. for (let j = i + 1; j < nodes.length; j++) {{
  1698. const nodeB = nodes[j];
  1699. const layerB = getNodeLayer(nodeB);
  1700. // 只对同层节点施加排斥力
  1701. if (layerA !== layerB) continue;
  1702. const dx = nodeB.x - nodeA.x;
  1703. const dy = nodeB.y - nodeA.y;
  1704. const dist = Math.sqrt(dx * dx + dy * dy) || 1;
  1705. const minDist = 150; // 增大最小距离,让节点更分散
  1706. if (dist < minDist) {{
  1707. // 排斥力随距离衰减,但基础强度更大
  1708. const pushStrength = strength * alpha * (minDist - dist) / dist * 2;
  1709. const px = dx * pushStrength;
  1710. const py = dy * pushStrength;
  1711. nodeA.vx -= px;
  1712. nodeA.vy -= py;
  1713. nodeB.vx += px;
  1714. nodeB.vy += py;
  1715. }}
  1716. }}
  1717. }}
  1718. }}
  1719. force.initialize = function(_) {{
  1720. nodes = _;
  1721. }};
  1722. return force;
  1723. }}
  1724. // 层圆的半径(使用动态计算的 layerRadius)
  1725. // layerRadius 和 layerCenterY 已在前面定义
  1726. // 层边界约束力(把节点限制在层内)
  1727. function forceLayerBoundary() {{
  1728. let nodes;
  1729. function force(alpha) {{
  1730. nodes.forEach(node => {{
  1731. const layer = getNodeLayer(node);
  1732. const centerX = layerCenterX[layer];
  1733. const centerY = layerCenterY[layer];
  1734. // 使用圆形边界
  1735. const maxRadius = layerRadius[layer] - 15;
  1736. // 计算到圆心的距离
  1737. const dx = node.x - centerX;
  1738. const dy = node.y - centerY;
  1739. const dist = Math.sqrt(dx * dx + dy * dy);
  1740. // 如果超出圆形边界,拉回来
  1741. if (dist > maxRadius) {{
  1742. const scale = maxRadius / dist;
  1743. node.x = centerX + dx * scale;
  1744. node.y = centerY + dy * scale;
  1745. // 阻止继续向外运动
  1746. const angle = Math.atan2(dy, dx);
  1747. const vOutward = node.vx * Math.cos(angle) + node.vy * Math.sin(angle);
  1748. if (vOutward > 0) {{
  1749. node.vx -= vOutward * Math.cos(angle);
  1750. node.vy -= vOutward * Math.sin(angle);
  1751. }}
  1752. }}
  1753. }});
  1754. }}
  1755. force.initialize = function(_) {{
  1756. nodes = _;
  1757. }};
  1758. return force;
  1759. }}
  1760. // 层内圆形布局力(让同层节点围绕圆心分布)
  1761. function forceCircularLayout(strength) {{
  1762. let nodes;
  1763. function force(alpha) {{
  1764. // 按层分组(三层)
  1765. const layerNodes = {{0: [], 1: [], 2: []}};
  1766. nodes.forEach(node => {{
  1767. const layer = getNodeLayer(node);
  1768. if (layerNodes[layer]) layerNodes[layer].push(node);
  1769. }});
  1770. // 对每层计算布局
  1771. Object.entries(layerNodes).forEach(([layerIdx, layerGroup]) => {{
  1772. if (layerGroup.length === 0) return;
  1773. const layer = parseInt(layerIdx);
  1774. const centerX = layerCenterX[layer];
  1775. const centerY = layerCenterY[layer];
  1776. // 使用圆形布局
  1777. const nodeRadius = layerRadius[layer] - 20;
  1778. if (layerGroup.length === 1) {{
  1779. // 单个节点放在圆心
  1780. const node = layerGroup[0];
  1781. node.vx += (centerX - node.x) * strength * alpha;
  1782. node.vy += (centerY - node.y) * strength * alpha;
  1783. return;
  1784. }}
  1785. // 按角度排序节点(保持相对位置稳定)
  1786. layerGroup.forEach(node => {{
  1787. node._angle = Math.atan2(node.y - centerY, node.x - centerX);
  1788. }});
  1789. layerGroup.sort((a, b) => a._angle - b._angle);
  1790. // 均匀分布在圆周上
  1791. const angleStep = (2 * Math.PI) / layerGroup.length;
  1792. layerGroup.forEach((node, i) => {{
  1793. const angle = -Math.PI / 2 + i * angleStep; // 从顶部开始
  1794. const idealX = centerX + nodeRadius * Math.cos(angle);
  1795. const idealY = centerY + nodeRadius * Math.sin(angle);
  1796. node.vx += (idealX - node.x) * strength * alpha;
  1797. node.vy += (idealY - node.y) * strength * alpha;
  1798. }});
  1799. }});
  1800. }}
  1801. force.initialize = function(_) {{
  1802. nodes = _;
  1803. }};
  1804. return force;
  1805. }}
  1806. // 力导向模拟
  1807. simulation = d3.forceSimulation(nodes)
  1808. // 连线力(跨层连接)
  1809. .force("link", d3.forceLink(links).id(d => d.id)
  1810. .distance(d => {{
  1811. // 跨层连线距离
  1812. if (d.type.startsWith("匹配_") || d.type === "属于") {{
  1813. return 150; // 跨层边
  1814. }}
  1815. return 60; // 同层边
  1816. }})
  1817. .strength(d => {{
  1818. // 跨层边力度弱一些,不要拉扯节点出层
  1819. if (d.type.startsWith("匹配_") || d.type === "属于") {{
  1820. return 0.03;
  1821. }}
  1822. return 0.1;
  1823. }}))
  1824. // X方向:轻微拉向各层中心
  1825. .force("x", d3.forceX(d => getNodeBaseX(d)).strength(0.02))
  1826. // Y方向:轻微拉向层中心
  1827. .force("y", d3.forceY(d => getNodeBaseY(d)).strength(0.02))
  1828. // 层内碰撞检测
  1829. .force("collision", d3.forceCollide().radius(30))
  1830. // 层内排斥力(同层节点相互排斥)
  1831. .force("intraLayer", forceIntraLayerRepulsion(0.8))
  1832. // 层内布局(圆形或树状)
  1833. .force("circularLayout", forceCircularLayout(0.15))
  1834. // 层边界约束(节点不能跑出层,硬约束)
  1835. .force("boundary", forceLayerBoundary());
  1836. // 边类型到CSS类的映射
  1837. const edgeTypeClass = {{
  1838. "匹配_相同": "match-same",
  1839. "匹配_相似": "match-similar",
  1840. "分类共现(跨点)": "category-cross",
  1841. "分类共现(点内)": "category-intra",
  1842. "标签共现": "tag-cooccur",
  1843. "属于": "belong",
  1844. "包含": "contain",
  1845. // 镜像边(帖子节点之间,虚线)
  1846. "镜像_分类共现(跨点)": "mirror-category-cross",
  1847. "镜像_分类共现(点内)": "mirror-category-intra",
  1848. "镜像_标签共现": "mirror-tag-cooccur",
  1849. "镜像_属于": "mirror-belong",
  1850. "镜像_包含": "mirror-contain"
  1851. }};
  1852. // 获取边的CSS类(处理二阶边,映射到对应的镜像边样式)
  1853. function getEdgeClass(edgeType) {{
  1854. if (edgeTypeClass[edgeType]) return edgeTypeClass[edgeType];
  1855. // 二阶边映射到对应的镜像边样式(颜色相同,都用虚线)
  1856. if (edgeType.startsWith("二阶_")) {{
  1857. const originalType = edgeType.replace("二阶_", "");
  1858. const mirrorType = "镜像_" + originalType;
  1859. if (edgeTypeClass[mirrorType]) return edgeTypeClass[mirrorType];
  1860. }}
  1861. return "match";
  1862. }}
  1863. // ===== 在上方绘制帖子树(只是展示用)=====
  1864. const postDetail = data.postDetail || {{}};
  1865. window.currentPostDetail = postDetail;
  1866. // 使用预构建的帖子树数据
  1867. const postTree = data.postTree || {{ root: null }};
  1868. // 帖子树D3布局(只在有帖子树数据时绘制)
  1869. const postTreeGroup = g.append("g").attr("class", "post-tree");
  1870. let postTreeActualHeight = 0;
  1871. let postTreeOffsetY = 60;
  1872. let postRoot = null;
  1873. if (postTree && postTree.root) {{
  1874. const postTreeLayout = d3.tree()
  1875. .nodeSize([70, 80])
  1876. .separation((a, b) => a.parent === b.parent ? 1.2 : 1.5);
  1877. postRoot = d3.hierarchy(postTree.root);
  1878. postTreeLayout(postRoot);
  1879. // 计算树的实际边界
  1880. let treeMinX = Infinity, treeMaxX = -Infinity, treeMinY = Infinity, treeMaxY = -Infinity;
  1881. postRoot.descendants().forEach(d => {{
  1882. treeMinX = Math.min(treeMinX, d.x);
  1883. treeMaxX = Math.max(treeMaxX, d.x);
  1884. treeMinY = Math.min(treeMinY, d.y);
  1885. treeMaxY = Math.max(treeMaxY, d.y);
  1886. }});
  1887. // 帖子树居中,放在圆的上方
  1888. const postTreeOffsetX = circleAreaCenterX - (treeMinX + treeMaxX) / 2;
  1889. postTreeGroup.attr("transform", `translate(${{postTreeOffsetX}}, ${{postTreeOffsetY}})`);
  1890. // 卡片尺寸(提前定义,边绘制时需要用)
  1891. const cardWidth = 240;
  1892. const cardHeight = 90;
  1893. // 绘制帖子树边(属于边,紫色,粗细根据权重)
  1894. const postTreeLinks = postTreeGroup.selectAll(".post-tree-link")
  1895. .data(postRoot.links())
  1896. .enter()
  1897. .append("g")
  1898. .attr("class", "post-tree-link-group");
  1899. postTreeLinks.append("path")
  1900. .attr("class", "post-tree-link")
  1901. .attr("d", d => {{
  1902. // 如果源节点是根节点(帖子卡片),从卡片下边框中心出发
  1903. const sourceY = d.source.data.isRoot ? d.source.y + cardHeight/2 : d.source.y;
  1904. return `M${{d.source.x}},${{sourceY}}
  1905. C${{d.source.x}},${{(sourceY + d.target.y) / 2}}
  1906. ${{d.target.x}},${{(sourceY + d.target.y) / 2}}
  1907. ${{d.target.x}},${{d.target.y}}`;
  1908. }})
  1909. .attr("fill", "none")
  1910. .attr("stroke", "#9b59b6")
  1911. .attr("stroke-width", 1.5)
  1912. .attr("stroke-opacity", 0.6);
  1913. // 在点->标签的边上显示权重(浮点数)
  1914. postTreeLinks.filter(d => d.target.data.nodeType === "标签" && d.target.data.weight > 0)
  1915. .append("text")
  1916. .attr("x", d => (d.source.x + d.target.x) / 2)
  1917. .attr("y", d => (d.source.y + d.target.y) / 2)
  1918. .attr("text-anchor", "middle")
  1919. .attr("fill", "#9b59b6")
  1920. .attr("font-size", "9px")
  1921. .attr("font-weight", "bold")
  1922. .text(d => d.target.data.weight.toFixed(1));
  1923. // 六边形路径生成函数
  1924. function hexagonPath(r) {{
  1925. const a = Math.PI / 3;
  1926. let path = "";
  1927. for (let i = 0; i < 6; i++) {{
  1928. const angle = a * i - Math.PI / 2;
  1929. const x = r * Math.cos(angle);
  1930. const y = r * Math.sin(angle);
  1931. path += (i === 0 ? "M" : "L") + x + "," + y;
  1932. }}
  1933. return path + "Z";
  1934. }}
  1935. // 绘制帖子树节点(非根节点)
  1936. const postTreeNodes = postTreeGroup.selectAll(".post-tree-node")
  1937. .data(postRoot.descendants().filter(d => !d.data.isRoot))
  1938. .enter()
  1939. .append("g")
  1940. .attr("class", "post-tree-node")
  1941. .attr("transform", d => `translate(${{d.x}},${{d.y}})`);
  1942. // 节点形状(维度=大圆,点=六边形,标签=小圆)
  1943. postTreeNodes.each(function(d) {{
  1944. const node = d3.select(this);
  1945. if (d.data.nodeType === "点") {{
  1946. // 点节点用六边形
  1947. node.append("path")
  1948. .attr("d", hexagonPath(6))
  1949. .attr("fill", d.data.dimColor || "#888")
  1950. .attr("stroke", "#fff")
  1951. .attr("stroke-width", 1);
  1952. }} else {{
  1953. // 维度和标签用圆形
  1954. node.append("circle")
  1955. .attr("r", d.data.isDimension ? 7 : 3)
  1956. .attr("fill", d.data.dimColor || "#888")
  1957. .attr("stroke", "#fff")
  1958. .attr("stroke-width", 1);
  1959. }}
  1960. }});
  1961. // 节点标签
  1962. postTreeNodes.append("text")
  1963. .attr("dy", d => d.children ? -10 : 12)
  1964. .attr("text-anchor", "middle")
  1965. .attr("fill", d => d.data.dimColor || "#ccc")
  1966. .attr("font-size", d => {{
  1967. if (d.data.isDimension) return "11px";
  1968. if (d.data.nodeType === "点") return "10px";
  1969. return "8px";
  1970. }})
  1971. .attr("font-weight", d => d.data.isDimension ? "bold" : "normal")
  1972. .text(d => d.data.name || "");
  1973. // 绘制根节点卡片(帖子详情卡片)
  1974. const postRootNode = postRoot;
  1975. const cardX = postRootNode.x - cardWidth/2;
  1976. const cardY = postRootNode.y - cardHeight/2;
  1977. const rootCard = postTreeGroup.append("foreignObject")
  1978. .attr("x", cardX)
  1979. .attr("y", cardY)
  1980. .attr("width", cardWidth)
  1981. .attr("height", cardHeight);
  1982. const images = postDetail.images || [];
  1983. const thumbnail = images.length > 0 ? images[0] : "";
  1984. const title = postDetail.title || "未知标题";
  1985. const likeCount = postDetail.like_count || 0;
  1986. const collectCount = postDetail.collect_count || 0;
  1987. const imageCount = images.length || 0;
  1988. const thumbnailHtml = thumbnail
  1989. ? `<div class="post-card-thumbnail-wrapper" style="width:60px;height:60px;">
  1990. <img class="post-card-thumbnail" style="width:60px;height:60px;" src="${{thumbnail}}" alt="封面" onerror="this.style.display='none'"/>
  1991. ${{imageCount > 1 ? `<span class="post-card-image-count">${{imageCount}}图</span>` : ''}}
  1992. </div>`
  1993. : `<div class="post-card-thumbnail-placeholder" style="width:60px;height:60px;font-size:20px;">📝</div>`;
  1994. const cardHtml = `
  1995. <div class="post-card" xmlns="http://www.w3.org/1999/xhtml" style="padding:10px;" onclick="showPostDetail(window.currentPostDetail)">
  1996. <div class="post-card-header">
  1997. ${{thumbnailHtml}}
  1998. <div class="post-card-info">
  1999. <div class="post-card-title" style="font-size:12px;-webkit-line-clamp:2;" title="${{title}}">${{title}}</div>
  2000. <div class="post-card-stats" style="font-size:10px;">
  2001. <span>❤️ ${{likeCount}}</span>
  2002. <span>⭐ ${{collectCount}}</span>
  2003. </div>
  2004. </div>
  2005. </div>
  2006. </div>
  2007. `;
  2008. rootCard.append("xhtml:div").html(cardHtml);
  2009. postTreeActualHeight = treeMaxY - treeMinY;
  2010. }} // end if (postTree && postTree.root)
  2011. // 根据帖子树高度,调整圆的Y位置
  2012. const postTreeTotalHeight = postTreeOffsetY + postTreeActualHeight + 80;
  2013. const circleYOffset = postTreeTotalHeight;
  2014. // 更新圆心Y坐标(三层)
  2015. layerCenterY[0] += circleYOffset;
  2016. layerCenterY[1] += circleYOffset;
  2017. layerCenterY[2] += circleYOffset;
  2018. // 更新SVG高度
  2019. svg.attr("height", height + circleYOffset);
  2020. // 绘制层背景(圆形,使用动态大小)
  2021. const layerBg = g.append("g").attr("class", "layer-backgrounds");
  2022. // 层配置:名称、颜色(三层圆)
  2023. const layerConfig = [
  2024. {{ name: "帖子标签", layer: 0, color: "rgba(52, 152, 219, 0.08)", stroke: "rgba(52, 152, 219, 0.3)" }},
  2025. {{ name: "人设匹配_1层", layer: 1, color: "rgba(155, 89, 182, 0.08)", stroke: "rgba(155, 89, 182, 0.3)" }},
  2026. {{ name: "人设匹配_2层", layer: 2, color: "rgba(46, 204, 113, 0.08)", stroke: "rgba(46, 204, 113, 0.3)" }}
  2027. ];
  2028. // 绘制三层圆形背景
  2029. layerConfig.forEach(cfg => {{
  2030. const cx = layerCenterX[cfg.layer];
  2031. const cy = layerCenterY[cfg.layer];
  2032. const r = layerRadius[cfg.layer];
  2033. layerBg.append("circle")
  2034. .attr("cx", cx)
  2035. .attr("cy", cy)
  2036. .attr("r", r)
  2037. .attr("fill", cfg.color)
  2038. .attr("stroke", cfg.stroke)
  2039. .attr("stroke-width", 2);
  2040. // 层标签(圆的左侧)
  2041. layerBg.append("text")
  2042. .attr("x", cx - r - 15)
  2043. .attr("y", cy)
  2044. .attr("dy", "0.35em")
  2045. .attr("fill", "rgba(255,255,255,0.5)")
  2046. .attr("font-size", "13px")
  2047. .attr("font-weight", "bold")
  2048. .attr("text-anchor", "end")
  2049. .text(cfg.name);
  2050. }});
  2051. // 绘制左侧人设树(在独立的treeSvg中)
  2052. const dimColors = {{ "灵感点": "#f39c12", "目的点": "#3498db", "关键点": "#9b59b6" }};
  2053. // 更新树SVG高度
  2054. treeSvg.attr("height", treeHeight + 50);
  2055. const treeGroup = treeG.append("g")
  2056. .attr("class", "persona-tree")
  2057. .attr("transform", `translate(15, 25)`);
  2058. // 设置关系图SVG
  2059. egoG.selectAll("*").remove();
  2060. const egoDisplayRadius = 180;
  2061. const egoCenterGroup = egoG.append("g")
  2062. .attr("class", "ego-center")
  2063. .attr("transform", `translate(200, 210)`);
  2064. // 关系图内容组
  2065. egoCenterGroup.append("g")
  2066. .attr("class", "ego-graph-content");
  2067. // D3树布局 - 宽度留出边距给标签
  2068. const treeLayout = d3.tree()
  2069. .size([treeHeight - 50, treeAreaWidth - 70]);
  2070. const root = d3.hierarchy(personaTree.root);
  2071. treeLayout(root);
  2072. // 获取节点颜色(根据维度)
  2073. function getNodeColor(d) {{
  2074. if (d.data.isRoot) return "#e94560"; // 根节点红色
  2075. if (d.data.isDimension) return d.data.dimColor; // 维度节点用维度颜色
  2076. return d.data.dimColor || "#888"; // 分类节点继承维度颜色
  2077. }}
  2078. // 构建节点ID到D3节点的映射(用于绘制原始边和高亮)
  2079. const treeNodeById = {{}};
  2080. root.descendants().forEach(d => {{
  2081. if (d.data.节点ID) {{
  2082. treeNodeById[d.data.节点ID] = d;
  2083. }}
  2084. }});
  2085. // 边类型颜色和样式
  2086. const treeEdgeColors = {{
  2087. "分类层级": "#2ecc71", // 绿色 - 分类的层级关系
  2088. "属于": "#9b59b6", // 紫色 - 标签属于分类
  2089. "包含": "#ffb6c1", // 淡粉 - 分类包含标签(向下)
  2090. "分类共现(跨点)": "#2ecc71", // 绿色 - 跨帖子分类共现
  2091. "分类共现(点内)": "#3498db", // 蓝色 - 同帖子分类共现
  2092. "标签共现": "#f39c12" // 橙色 - 标签共现
  2093. }};
  2094. const treeEdgeDash = {{
  2095. "分类层级": "none",
  2096. "属于": "3,2",
  2097. "包含": "3,2",
  2098. "分类共现(跨点)": "5,3",
  2099. "分类共现(点内)": "5,3",
  2100. "标签共现": "2,2"
  2101. }};
  2102. // 只用D3树布局的链接作为树边(避免重复)
  2103. const visibleTreeEdges = root.links().map(link => ({{
  2104. 源节点ID: link.source.data.节点ID || link.source.data.name,
  2105. 目标节点ID: link.target.data.节点ID || link.target.data.name,
  2106. 边类型: "属于",
  2107. isTreeLink: true,
  2108. sourceNode: link.source,
  2109. targetNode: link.target
  2110. }}));
  2111. // 生成树边路径的函数
  2112. function treeEdgePath(d) {{
  2113. const source = d.sourceNode;
  2114. const target = d.targetNode;
  2115. if (!source || !target) return "";
  2116. const midX = (source.y + target.y) / 2;
  2117. return `M${{source.y}},${{source.x}} C${{midX}},${{source.x}} ${{midX}},${{target.x}} ${{target.y}},${{target.x}}`;
  2118. }}
  2119. // 绘制原始边(只有属于边)
  2120. const treeEdgeGroup = treeGroup.append("g").attr("class", "tree-edges");
  2121. // 先绘制可见边(只有属于边)
  2122. const treeEdges = treeEdgeGroup.selectAll(".tree-edge")
  2123. .data(visibleTreeEdges)
  2124. .join("path")
  2125. .attr("class", "tree-edge")
  2126. .attr("fill", "none")
  2127. .attr("stroke", "#9b59b6") // 属于边用紫色
  2128. .attr("stroke-opacity", 0.3)
  2129. .attr("stroke-width", 1)
  2130. .attr("d", treeEdgePath);
  2131. // 绘制透明的热区边(便于点击)
  2132. const treeEdgeHitareas = treeEdgeGroup.selectAll(".tree-edge-hitarea")
  2133. .data(visibleTreeEdges)
  2134. .join("path")
  2135. .attr("class", "tree-edge-hitarea")
  2136. .attr("fill", "none")
  2137. .attr("stroke", "transparent")
  2138. .attr("stroke-width", 12)
  2139. .style("cursor", "pointer")
  2140. .attr("d", treeEdgePath)
  2141. .on("click", (event, d) => {{
  2142. event.stopPropagation();
  2143. // 调用共享的边点击处理函数
  2144. handleEdgeClick(d.源节点ID, d.目标节点ID, d.边类型);
  2145. }});
  2146. // 绘制节点
  2147. const treeNodes = treeGroup.selectAll(".tree-node")
  2148. .data(root.descendants())
  2149. .join("g")
  2150. .attr("class", "tree-node")
  2151. .attr("transform", d => `translate(${{d.y}},${{d.x}})`)
  2152. .style("cursor", "pointer")
  2153. .on("click", (event, d) => {{
  2154. event.stopPropagation();
  2155. // 调用共享的节点点击处理函数
  2156. handleNodeClick(d.data.节点ID, d.data.节点名称 || d.data.name);
  2157. }})
  2158. .on("mouseenter", (event, d) => {{
  2159. // 悬停高亮:在关系图中高亮到激活节点的路径
  2160. if (!currentEgoCenterNodeId) return;
  2161. const hoveredNodeId = d.data.节点ID;
  2162. if (!hoveredNodeId || hoveredNodeId === currentEgoCenterNodeId) return;
  2163. highlightPathInEgoGraph(hoveredNodeId);
  2164. }})
  2165. .on("mouseleave", (event, d) => {{
  2166. // 移出时恢复关系图
  2167. if (!currentEgoCenterNodeId) return;
  2168. resetEgoGraphHighlight();
  2169. }});
  2170. // 节点形状:根节点/维度=圆形,分类=正方形,标签=圆形
  2171. // 统一实心填充维度颜色
  2172. treeNodes.each(function(d) {{
  2173. const el = d3.select(this);
  2174. const nodeType = d.data.节点类型;
  2175. const isRoot = d.data.isRoot;
  2176. const isDimension = d.data.isDimension;
  2177. const nodeColor = getNodeColor(d);
  2178. if (nodeType === "分类") {{
  2179. // 分类节点:正方形,实心填充
  2180. el.append("rect")
  2181. .attr("class", "tree-shape")
  2182. .attr("x", -4)
  2183. .attr("y", -4)
  2184. .attr("width", 8)
  2185. .attr("height", 8)
  2186. .attr("rx", 1)
  2187. .attr("fill", nodeColor)
  2188. .attr("stroke", "rgba(255,255,255,0.5)")
  2189. .attr("stroke-width", 1);
  2190. }} else {{
  2191. // 根节点、维度节点、标签节点:圆形,实心填充
  2192. const radius = isRoot ? 6 : (isDimension ? 5 : 3);
  2193. el.append("circle")
  2194. .attr("class", "tree-shape")
  2195. .attr("r", radius)
  2196. .attr("fill", nodeColor)
  2197. .attr("stroke", "rgba(255,255,255,0.5)")
  2198. .attr("stroke-width", 1);
  2199. }}
  2200. }});
  2201. // 节点标签
  2202. treeNodes.append("text")
  2203. .attr("dy", "0.31em")
  2204. .attr("x", d => d.children ? -8 : 8)
  2205. .attr("text-anchor", d => d.children ? "end" : "start")
  2206. .attr("fill", d => (d.data.isRoot || d.data.isDimension) ? getNodeColor(d) : "#bbb")
  2207. .attr("font-size", d => d.data.isRoot ? "11px" : (d.data.isDimension ? "10px" : "8px"))
  2208. .attr("font-weight", d => (d.data.isRoot || d.data.isDimension) ? "bold" : "normal")
  2209. .text(d => d.data.name);
  2210. // 重置树高亮状态的函数
  2211. function resetTreeHighlight() {{
  2212. treeGroup.selectAll(".tree-node")
  2213. .classed("tree-dimmed", false)
  2214. .classed("tree-highlighted", false);
  2215. // 重置所有形状(圆形和方形)- 统一实心填充
  2216. treeGroup.selectAll(".tree-node .tree-shape")
  2217. .attr("fill", d => getNodeColor(d))
  2218. .attr("stroke", "rgba(255,255,255,0.5)")
  2219. .attr("stroke-opacity", 1)
  2220. .attr("opacity", 1);
  2221. treeGroup.selectAll(".tree-node text")
  2222. .attr("fill", d => (d.data.isRoot || d.data.isDimension) ? getNodeColor(d) : "#bbb")
  2223. .attr("opacity", 1);
  2224. // 重置边样式
  2225. treeGroup.selectAll(".tree-edge")
  2226. .attr("stroke-opacity", 0.3)
  2227. .attr("stroke-width", 1);
  2228. }}
  2229. // 重置右侧图高亮状态的函数
  2230. function resetGraphHighlight() {{
  2231. g.selectAll(".node").classed("dimmed", false).classed("highlighted", false);
  2232. g.selectAll(".link-group").classed("dimmed", false).classed("highlighted", false);
  2233. }}
  2234. // 点击树SVG背景取消高亮
  2235. treeSvg.on("click", function(event) {{
  2236. if (event.target === this) {{
  2237. resetTreeHighlight();
  2238. resetGraphHighlight();
  2239. clearEgoGraph();
  2240. closeDetailPanel();
  2241. }}
  2242. }});
  2243. // 创建边的容器
  2244. const linkGroup = g.append("g").attr("class", "links");
  2245. // 为每条边创建组
  2246. const linkG = linkGroup.selectAll("g")
  2247. .data(links)
  2248. .join("g")
  2249. .attr("class", "link-group");
  2250. // 绘制点击热区(透明宽线)
  2251. const linkHitarea = linkG.append("line")
  2252. .attr("class", "link-hitarea");
  2253. // 绘制可见的边
  2254. const link = linkG.append("line")
  2255. .attr("class", d => "link " + getEdgeClass(d.type))
  2256. .attr("stroke-width", d => d.type.startsWith("匹配_") ? 2.5 : 1.5);
  2257. // 判断是否为跨层边(根据源和目标节点的层级)- 赋值给全局变量
  2258. isCrossLayerEdge = function(d) {{
  2259. const sourceNode = typeof d.source === "object" ? d.source : nodes.find(n => n.id === d.source);
  2260. const targetNode = typeof d.target === "object" ? d.target : nodes.find(n => n.id === d.target);
  2261. if (!sourceNode || !targetNode) return false;
  2262. return getNodeLayer(sourceNode) !== getNodeLayer(targetNode);
  2263. }};
  2264. // 设置跨层边的初始可见性(匹配边始终显示,其他跨层边默认隐藏)
  2265. linkG.each(function(d) {{
  2266. if (d.type.startsWith("匹配_")) {{
  2267. d3.select(this).style("display", "block"); // 匹配边始终显示
  2268. }} else if (isCrossLayerEdge(d) && !showCrossLayerEdges) {{
  2269. d3.select(this).style("display", "none");
  2270. }}
  2271. }});
  2272. // 为匹配边添加分数标签
  2273. const edgeLabels = linkG.filter(d => d.type.startsWith("匹配_") && d.边详情 && d.边详情.相似度)
  2274. .append("g")
  2275. .attr("class", "edge-label-group");
  2276. edgeLabels.append("rect")
  2277. .attr("class", "edge-label-bg")
  2278. .attr("rx", 3)
  2279. .attr("ry", 3);
  2280. edgeLabels.append("text")
  2281. .attr("class", "edge-label")
  2282. .text(d => {{
  2283. const score = d.边详情.相似度;
  2284. return typeof score === "number" ? score.toFixed(2) : score;
  2285. }});
  2286. // 边的点击事件
  2287. linkHitarea.on("click", (event, d, i) => {{
  2288. event.stopPropagation();
  2289. const linkIndex = links.indexOf(d);
  2290. // 1. 力导向图高亮(highlightEdge 处理所有路径高亮逻辑)
  2291. highlightEdge(d, linkIndex);
  2292. showEdgeInfo(d);
  2293. // 2. 确定要在人设树和关系图中展示的人设节点路径
  2294. const edgeDetail = d.边详情 || {{}};
  2295. const isMirrorEdge = d.type.startsWith("镜像_") || d.type.startsWith("二阶_");
  2296. let personaPathNodes = [];
  2297. let edgeType;
  2298. if (isMirrorEdge && edgeDetail.路径节点) {{
  2299. // 镜像边/二阶边:从路径节点中提取人设节点(不以帖子_开头的)
  2300. personaPathNodes = edgeDetail.路径节点.filter(id => !id.startsWith("帖子_"));
  2301. edgeType = edgeDetail.原始边类型 || d.type.replace("镜像_", "").replace("二阶_", "");
  2302. }} else {{
  2303. // 普通边:使用边的两端节点
  2304. const sourceNode = typeof d.source === "object" ? d.source : nodes.find(n => n.id === d.source);
  2305. const targetNode = typeof d.target === "object" ? d.target : nodes.find(n => n.id === d.target);
  2306. const srcId = sourceNode ? sourceNode.id : d.source;
  2307. const tgtId = targetNode ? targetNode.id : d.target;
  2308. // 只有人设节点才加入路径
  2309. if (!srcId.startsWith("帖子_")) personaPathNodes.push(srcId);
  2310. if (!tgtId.startsWith("帖子_")) personaPathNodes.push(tgtId);
  2311. edgeType = d.type;
  2312. }}
  2313. // 3. 同步人设树高亮和关系图展示
  2314. syncTreeAndRelationGraph(personaPathNodes, edgeType);
  2315. }})
  2316. .on("mouseover", function(event, d) {{
  2317. d3.select(this.parentNode).select(".link")
  2318. .attr("stroke-opacity", 1)
  2319. .attr("stroke-width", 4);
  2320. }})
  2321. .on("mouseout", function(event, d) {{
  2322. d3.select(this.parentNode).select(".link")
  2323. .attr("stroke-opacity", 0.7)
  2324. .attr("stroke-width", d.type.startsWith("匹配_") ? 2.5 : 1.5);
  2325. }});
  2326. // 绘制节点
  2327. const node = g.append("g")
  2328. .selectAll("g")
  2329. .data(nodes)
  2330. .join("g")
  2331. .attr("class", "node")
  2332. .call(d3.drag()
  2333. .on("start", dragstarted)
  2334. .on("drag", dragged)
  2335. .on("end", dragended));
  2336. // 根据节点类型绘制不同形状
  2337. // - 点节点(帖子点):六边形
  2338. // - 标签节点:圆形
  2339. // - 分类节点:方形
  2340. // 帖子标签用虚线,人设标签用实线
  2341. node.each(function(d) {{
  2342. const el = d3.select(this);
  2343. const isPointNode = d.节点类型 === "点";
  2344. const isPostNode = d.source === "帖子";
  2345. // 节点大小
  2346. let size;
  2347. if (isPointNode) {{
  2348. size = 16; // 点节点最大
  2349. }} else if (isPostNode) {{
  2350. size = 12; // 帖子标签
  2351. }} else {{
  2352. size = 10; // 人设标签
  2353. }}
  2354. const fill = levelColors[d.level] || "#666";
  2355. const nodeClass = isPostNode
  2356. ? (isPointNode ? "post-point-node" : "post-node")
  2357. : "persona-node";
  2358. if (isPointNode) {{
  2359. // 六边形(点节点)
  2360. const hexPoints = [];
  2361. for (let i = 0; i < 6; i++) {{
  2362. const angle = (i * 60 - 30) * Math.PI / 180;
  2363. hexPoints.push([size * Math.cos(angle), size * Math.sin(angle)]);
  2364. }}
  2365. el.append("polygon")
  2366. .attr("points", hexPoints.map(p => p.join(",")).join(" "))
  2367. .attr("fill", fill)
  2368. .attr("class", nodeClass);
  2369. }} else if (d.节点类型 === "分类") {{
  2370. // 方形(分类节点)
  2371. el.append("rect")
  2372. .attr("width", size * 2)
  2373. .attr("height", size * 2)
  2374. .attr("x", -size)
  2375. .attr("y", -size)
  2376. .attr("fill", fill)
  2377. .attr("class", nodeClass)
  2378. .attr("rx", 3);
  2379. }} else {{
  2380. // 圆形(标签节点)
  2381. el.append("circle")
  2382. .attr("r", size)
  2383. .attr("fill", fill)
  2384. .attr("class", nodeClass);
  2385. }}
  2386. }});
  2387. const labels = node.append("text")
  2388. .attr("dx", 15)
  2389. .attr("dy", 4)
  2390. .text(d => d.节点名称)
  2391. .style("display", showLabels ? "block" : "none");
  2392. // 工具提示
  2393. const tooltip = d3.select("#tooltip");
  2394. node.on("mouseover", (event, d) => {{
  2395. let html = `<strong>${{d.节点名称}}</strong><br/>类型: ${{d.节点类型}}<br/>层级: ${{d.节点层级}}`;
  2396. // 点节点显示描述
  2397. if (d.描述) {{
  2398. html += `<br/><br/><em style="font-size:10px;color:#aaa">${{d.描述.slice(0, 100)}}${{d.描述.length > 100 ? '...' : ''}}</em>`;
  2399. }}
  2400. tooltip.style("display", "block").html(html);
  2401. }})
  2402. .on("mousemove", (event) => {{
  2403. tooltip.style("left", (event.pageX + 15) + "px")
  2404. .style("top", (event.pageY - 10) + "px");
  2405. }})
  2406. .on("mouseout", () => {{
  2407. tooltip.style("display", "none");
  2408. }})
  2409. .on("click", (event, d) => {{
  2410. event.stopPropagation();
  2411. highlightNode(d);
  2412. showNodeInfo(d);
  2413. // 人设节点联动:高亮人设树 + 显示关系图
  2414. if (d.source === "人设") {{
  2415. handleNodeClick(d.节点ID, d.节点名称);
  2416. }}
  2417. }});
  2418. // 更新位置
  2419. simulation.on("tick", () => {{
  2420. // 更新热区线
  2421. linkHitarea
  2422. .attr("x1", d => d.source.x)
  2423. .attr("y1", d => d.source.y)
  2424. .attr("x2", d => d.target.x)
  2425. .attr("y2", d => d.target.y);
  2426. // 更新可见边
  2427. link
  2428. .attr("x1", d => d.source.x)
  2429. .attr("y1", d => d.source.y)
  2430. .attr("x2", d => d.target.x)
  2431. .attr("y2", d => d.target.y);
  2432. // 更新边标签位置(放在边的中点)
  2433. edgeLabels.attr("transform", d => {{
  2434. const midX = (d.source.x + d.target.x) / 2;
  2435. const midY = (d.source.y + d.target.y) / 2;
  2436. return `translate(${{midX}},${{midY}})`;
  2437. }});
  2438. // 更新标签背景大小
  2439. edgeLabels.each(function(d) {{
  2440. const textEl = d3.select(this).select("text").node();
  2441. if (textEl) {{
  2442. const bbox = textEl.getBBox();
  2443. d3.select(this).select("rect")
  2444. .attr("x", bbox.x - 3)
  2445. .attr("y", bbox.y - 1)
  2446. .attr("width", bbox.width + 6)
  2447. .attr("height", bbox.height + 2);
  2448. }}
  2449. }});
  2450. node.attr("transform", d => `translate(${{d.x}},${{d.y}})`);
  2451. }});
  2452. // 拖拽函数
  2453. function dragstarted(event, d) {{
  2454. if (!event.active) simulation.alphaTarget(0.3).restart();
  2455. d.fx = d.x;
  2456. d.fy = d.y;
  2457. }}
  2458. function dragged(event, d) {{
  2459. d.fx = event.x;
  2460. d.fy = event.y;
  2461. }}
  2462. function dragended(event, d) {{
  2463. if (!event.active) simulation.alphaTarget(0);
  2464. d.fx = null;
  2465. d.fy = null;
  2466. }}
  2467. // 清除所有高亮
  2468. function clearHighlight() {{
  2469. node.classed("dimmed", false).classed("highlighted", false);
  2470. linkG.classed("dimmed", false).classed("highlighted", false);
  2471. // 恢复跨层边的可见性状态(根据全局开关)
  2472. linkG.each(function(d) {{
  2473. if (isCrossLayerEdge(d)) {{
  2474. d3.select(this).style("display", showCrossLayerEdges ? "block" : "none");
  2475. }}
  2476. }});
  2477. }}
  2478. // 高亮指定的节点和边
  2479. function highlightElements(highlightNodeIds, highlightLinkIndices) {{
  2480. // 先灰化所有
  2481. node.classed("dimmed", true).classed("highlighted", false);
  2482. linkG.classed("dimmed", true).classed("highlighted", false);
  2483. // 高亮指定节点
  2484. node.filter(d => highlightNodeIds.has(d.id))
  2485. .classed("dimmed", false)
  2486. .classed("highlighted", true);
  2487. // 高亮指定边
  2488. linkG.filter((d, i) => highlightLinkIndices.has(i))
  2489. .classed("dimmed", false)
  2490. .classed("highlighted", true);
  2491. }}
  2492. // 点击节点时的高亮逻辑
  2493. function highlightNode(clickedNode) {{
  2494. const highlightNodeIds = new Set([clickedNode.id]);
  2495. const highlightLinkIndices = new Set();
  2496. links.forEach((link, i) => {{
  2497. const sourceId = typeof link.source === "object" ? link.source.id : link.source;
  2498. const targetId = typeof link.target === "object" ? link.target.id : link.target;
  2499. // 与点击节点直接相连的边
  2500. if (sourceId === clickedNode.id || targetId === clickedNode.id) {{
  2501. highlightLinkIndices.add(i);
  2502. highlightNodeIds.add(sourceId);
  2503. highlightNodeIds.add(targetId);
  2504. // 如果是帖子节点,还要高亮对应的镜像边
  2505. if (clickedNode.source === "帖子") {{
  2506. // 找到通过该帖子连接的其他帖子(镜像边)
  2507. links.forEach((otherLink, j) => {{
  2508. const otherType = otherLink.type;
  2509. if (otherType.startsWith("镜像_") || otherType.startsWith("二阶_")) {{
  2510. const oSrc = typeof otherLink.source === "object" ? otherLink.source.id : otherLink.source;
  2511. const oTgt = typeof otherLink.target === "object" ? otherLink.target.id : otherLink.target;
  2512. if (oSrc === clickedNode.id || oTgt === clickedNode.id) {{
  2513. highlightLinkIndices.add(j);
  2514. highlightNodeIds.add(oSrc);
  2515. highlightNodeIds.add(oTgt);
  2516. }}
  2517. }}
  2518. }});
  2519. }}
  2520. }}
  2521. }});
  2522. // 高亮相关的节点和边
  2523. highlightElements(highlightNodeIds, highlightLinkIndices);
  2524. // 临时显示关联的跨层边(即使全局开关是关闭的)
  2525. linkG.each(function(d, i) {{
  2526. if (highlightLinkIndices.has(i)) {{
  2527. d3.select(this).style("display", "block");
  2528. }}
  2529. }});
  2530. }}
  2531. // 点击边时的高亮逻辑
  2532. function highlightEdge(clickedLink, clickedIndex) {{
  2533. const highlightNodeIds = new Set();
  2534. const highlightLinkIndices = new Set([clickedIndex]);
  2535. const sourceId = typeof clickedLink.source === "object" ? clickedLink.source.id : clickedLink.source;
  2536. const targetId = typeof clickedLink.target === "object" ? clickedLink.target.id : clickedLink.target;
  2537. highlightNodeIds.add(sourceId);
  2538. highlightNodeIds.add(targetId);
  2539. // 如果是镜像边或二阶边,使用预计算的路径节点高亮
  2540. if ((clickedLink.type.startsWith("镜像_") || clickedLink.type.startsWith("二阶_")) && clickedLink.边详情) {{
  2541. const detail = clickedLink.边详情;
  2542. const pathNodes = new Set([sourceId, targetId]);
  2543. // 使用预计算的路径节点
  2544. (detail.路径节点 || []).forEach(n => pathNodes.add(n));
  2545. // 高亮路径上的所有节点
  2546. pathNodes.forEach(n => highlightNodeIds.add(n));
  2547. // 高亮连接路径节点的边
  2548. links.forEach((link, i) => {{
  2549. const lSrc = typeof link.source === "object" ? link.source.id : link.source;
  2550. const lTgt = typeof link.target === "object" ? link.target.id : link.target;
  2551. if (pathNodes.has(lSrc) && pathNodes.has(lTgt)) {{
  2552. highlightLinkIndices.add(i);
  2553. }}
  2554. }});
  2555. }}
  2556. // 如果是人设边(两端都不是帖子节点),找对应的镜像边
  2557. else if (!sourceId.startsWith("帖子_") && !targetId.startsWith("帖子_")) {{
  2558. // 收集路径节点
  2559. const pathNodes = new Set([sourceId, targetId]);
  2560. // 找匹配的镜像边,读取其路径节点
  2561. links.forEach((link, i) => {{
  2562. const detail = link.边详情 || {{}};
  2563. if ((link.type.startsWith("镜像_") || link.type.startsWith("二阶_")) && detail.源人设节点 && detail.目标人设节点) {{
  2564. const matches = (detail.源人设节点 === sourceId && detail.目标人设节点 === targetId) ||
  2565. (detail.源人设节点 === targetId && detail.目标人设节点 === sourceId);
  2566. if (matches) {{
  2567. highlightLinkIndices.add(i);
  2568. // 直接使用预存的路径节点
  2569. (detail.路径节点 || []).forEach(n => pathNodes.add(n));
  2570. }}
  2571. }}
  2572. }});
  2573. // 高亮路径上的所有节点
  2574. pathNodes.forEach(n => highlightNodeIds.add(n));
  2575. // 高亮连接路径节点的边
  2576. links.forEach((link, i) => {{
  2577. const lSrc = typeof link.source === "object" ? link.source.id : link.source;
  2578. const lTgt = typeof link.target === "object" ? link.target.id : link.target;
  2579. // 两端都在路径上的边
  2580. if (pathNodes.has(lSrc) && pathNodes.has(lTgt)) {{
  2581. highlightLinkIndices.add(i);
  2582. }}
  2583. }});
  2584. }}
  2585. // 高亮相关的节点和边
  2586. highlightElements(highlightNodeIds, highlightLinkIndices);
  2587. // 临时显示关联的跨层边(即使全局开关是关闭的)
  2588. linkG.each(function(d, i) {{
  2589. if (highlightLinkIndices.has(i)) {{
  2590. d3.select(this).style("display", "block");
  2591. }}
  2592. }});
  2593. }}
  2594. // 点击空白处清除高亮(合并所有空白点击逻辑)
  2595. svg.on("click", (event) => {{
  2596. // 检查是否点击的是空白区域(svg本身或layer-backgrounds)
  2597. const isBlank = event.target === svg.node() ||
  2598. event.target.tagName === "svg" ||
  2599. event.target.classList.contains("layer-backgrounds");
  2600. if (isBlank) {{
  2601. // 清除右侧图高亮
  2602. clearHighlight();
  2603. // 清除人设树高亮
  2604. resetTreeHighlight();
  2605. resetGraphHighlight();
  2606. // 关闭详情面板
  2607. closeDetailPanel();
  2608. // 清除关系图
  2609. clearEgoGraph();
  2610. }}
  2611. }});
  2612. }}
  2613. // 控制函数
  2614. function resetZoom() {{
  2615. const container = document.getElementById("svg-container");
  2616. const width = container.clientWidth;
  2617. const height = container.clientHeight;
  2618. svg.transition().duration(750).call(
  2619. zoom.transform,
  2620. d3.zoomIdentity.translate(width/2, height/2).scale(1).translate(-width/2, -height/2)
  2621. );
  2622. }}
  2623. function toggleLabels() {{
  2624. showLabels = !showLabels;
  2625. g.selectAll(".node text").style("display", showLabels ? "block" : "none");
  2626. }}
  2627. // 切换跨层边显示
  2628. function toggleCrossLayerEdges() {{
  2629. showCrossLayerEdges = !showCrossLayerEdges;
  2630. const btn = document.getElementById("crossLayerBtn");
  2631. btn.textContent = showCrossLayerEdges ? "隐藏跨层边" : "显示跨层边";
  2632. btn.style.background = showCrossLayerEdges ? "#e94560" : "";
  2633. // 更新边的可见性(使用 isCrossLayerEdge 函数判断)
  2634. g.selectAll(".link-group").each(function(d) {{
  2635. if (isCrossLayerEdge(d)) {{
  2636. d3.select(this).style("display", showCrossLayerEdges ? "block" : "none");
  2637. }}
  2638. }});
  2639. }}
  2640. function showNodeInfo(d) {{
  2641. const panel = document.getElementById("detailPanel");
  2642. panel.classList.add("active");
  2643. document.getElementById("detailTitle").textContent = d.source === "帖子" ? "📌 帖子节点" : "👤 人设节点";
  2644. let html = `
  2645. <p><span class="label">节点ID:</span> ${{d.节点ID}}</p>
  2646. <p><span class="label">名称:</span> <strong>${{d.节点名称}}</strong></p>
  2647. <p><span class="label">类型:</span> ${{d.节点类型}}</p>
  2648. <p><span class="label">层级:</span> ${{d.节点层级}}</p>
  2649. `;
  2650. if (d.权重) {{
  2651. html += `<p><span class="label">权重:</span> ${{d.权重}}</p>`;
  2652. }}
  2653. if (d.所属分类 && d.所属分类.length > 0) {{
  2654. html += `<p><span class="label">所属分类:</span> ${{d.所属分类.join(" > ")}}</p>`;
  2655. }}
  2656. if (d.帖子数) {{
  2657. html += `<p><span class="label">帖子数:</span> ${{d.帖子数}}</p>`;
  2658. }}
  2659. document.getElementById("detailContent").innerHTML = html;
  2660. }}
  2661. // 显示人设树节点详情(包含入边、出边、相关节点)
  2662. function showTreeNodeDetail(nodeData, inEdges, outEdges) {{
  2663. const panel = document.getElementById("detailPanel");
  2664. panel.classList.add("active");
  2665. document.getElementById("detailTitle").textContent = "🌳 人设树节点";
  2666. // 节点基本信息
  2667. let html = `
  2668. <p><span class="label">名称:</span> <strong>${{nodeData.节点名称 || nodeData.name}}</strong></p>
  2669. <p><span class="label">类型:</span> ${{nodeData.节点类型 || (nodeData.isRoot ? "根节点" : "维度")}}</p>
  2670. <p><span class="label">层级:</span> ${{nodeData.节点层级 || "-"}}</p>
  2671. `;
  2672. if (nodeData.所属分类 && nodeData.所属分类.length > 0) {{
  2673. html += `<p><span class="label">所属分类:</span> ${{nodeData.所属分类.join(" > ")}}</p>`;
  2674. }}
  2675. if (nodeData.帖子数) {{
  2676. html += `<p><span class="label">帖子数:</span> ${{nodeData.帖子数}}</p>`;
  2677. }}
  2678. // 统计边类型
  2679. const inEdgeTypes = {{}};
  2680. const outEdgeTypes = {{}};
  2681. inEdges.forEach(e => {{ inEdgeTypes[e.边类型] = (inEdgeTypes[e.边类型] || 0) + 1; }});
  2682. outEdges.forEach(e => {{ outEdgeTypes[e.边类型] = (outEdgeTypes[e.边类型] || 0) + 1; }});
  2683. // 入边统计
  2684. html += `<h4 style="margin-top:12px;color:#3498db;font-size:12px;">📥 入边 (${{inEdges.length}})</h4>`;
  2685. if (inEdges.length > 0) {{
  2686. html += `<div class="edge-list">`;
  2687. for (const [type, count] of Object.entries(inEdgeTypes)) {{
  2688. html += `<div class="edge-type-item"><span class="edge-type">${{type}}</span><span class="edge-count">${{count}}</span></div>`;
  2689. }}
  2690. // 显示前5条入边详情
  2691. const showInEdges = inEdges.slice(0, 5);
  2692. showInEdges.forEach(e => {{
  2693. const srcName = personaTreeData.nodes.find(n => n.节点ID === e.源节点ID)?.节点名称 || e.源节点ID;
  2694. html += `<div class="edge-detail">← ${{srcName}} <span class="edge-type-tag">${{e.边类型}}</span></div>`;
  2695. }});
  2696. if (inEdges.length > 5) {{
  2697. html += `<div class="edge-more">... 还有 ${{inEdges.length - 5}} 条</div>`;
  2698. }}
  2699. html += `</div>`;
  2700. }} else {{
  2701. html += `<div class="edge-empty">无</div>`;
  2702. }}
  2703. // 出边统计
  2704. html += `<h4 style="margin-top:12px;color:#e74c3c;font-size:12px;">📤 出边 (${{outEdges.length}})</h4>`;
  2705. if (outEdges.length > 0) {{
  2706. html += `<div class="edge-list">`;
  2707. for (const [type, count] of Object.entries(outEdgeTypes)) {{
  2708. html += `<div class="edge-type-item"><span class="edge-type">${{type}}</span><span class="edge-count">${{count}}</span></div>`;
  2709. }}
  2710. // 显示前5条出边详情
  2711. const showOutEdges = outEdges.slice(0, 5);
  2712. showOutEdges.forEach(e => {{
  2713. const tgtName = personaTreeData.nodes.find(n => n.节点ID === e.目标节点ID)?.节点名称 || e.目标节点ID;
  2714. html += `<div class="edge-detail">→ ${{tgtName}} <span class="edge-type-tag">${{e.边类型}}</span></div>`;
  2715. }});
  2716. if (outEdges.length > 5) {{
  2717. html += `<div class="edge-more">... 还有 ${{outEdges.length - 5}} 条</div>`;
  2718. }}
  2719. html += `</div>`;
  2720. }} else {{
  2721. html += `<div class="edge-empty">无</div>`;
  2722. }}
  2723. document.getElementById("detailContent").innerHTML = html;
  2724. }}
  2725. function showEdgeInfo(d) {{
  2726. const panel = document.getElementById("detailPanel");
  2727. panel.classList.add("active");
  2728. const sourceNode = typeof d.source === "object" ? d.source : {{ id: d.source }};
  2729. const targetNode = typeof d.target === "object" ? d.target : {{ id: d.target }};
  2730. // 判断是否为镜像边
  2731. const isMirror = d.type.startsWith("镜像_");
  2732. document.getElementById("detailTitle").textContent = isMirror ? "🪞 镜像边详情" : "🔗 边详情";
  2733. let html = `
  2734. <p><span class="label">边类型:</span> <strong>${{d.type}}</strong></p>
  2735. <p><span class="label">源节点:</span> ${{sourceNode.节点名称 || sourceNode.id}}</p>
  2736. <p><span class="label">目标节点:</span> ${{targetNode.节点名称 || targetNode.id}}</p>
  2737. `;
  2738. if (d.边详情) {{
  2739. if (d.边详情.相似度 !== undefined) {{
  2740. const score = typeof d.边详情.相似度 === "number" ? d.边详情.相似度.toFixed(2) : d.边详情.相似度;
  2741. html += `<p><span class="label">相似度:</span> <span class="similarity-score">${{score}}</span></p>`;
  2742. }}
  2743. if (d.边详情.说明) {{
  2744. html += `<p><span class="label">说明:</span></p><div class="edge-description">${{d.边详情.说明}}</div>`;
  2745. }}
  2746. if (d.边详情.共现次数 !== undefined) {{
  2747. html += `<p><span class="label">共现次数:</span> ${{d.边详情.共现次数}}</p>`;
  2748. }}
  2749. // 镜像边特有信息
  2750. if (d.边详情.原始边类型) {{
  2751. html += `<p><span class="label">原始边类型:</span> ${{d.边详情.原始边类型}}</p>`;
  2752. }}
  2753. if (d.边详情.源人设节点) {{
  2754. html += `<p><span class="label">源人设节点:</span> ${{d.边详情.源人设节点}}</p>`;
  2755. }}
  2756. if (d.边详情.目标人设节点) {{
  2757. html += `<p><span class="label">目标人设节点:</span> ${{d.边详情.目标人设节点}}</p>`;
  2758. }}
  2759. }}
  2760. document.getElementById("detailContent").innerHTML = html;
  2761. }}
  2762. function closeDetailPanel() {{
  2763. document.getElementById("detailPanel").classList.remove("active");
  2764. }}
  2765. // 更新匹配列表
  2766. function updateMatchList(matchLinks, nodes) {{
  2767. const listEl = document.getElementById("matchList");
  2768. const countEl = document.getElementById("matchCount");
  2769. // 构建节点ID到名称的映射
  2770. const nodeNames = {{}};
  2771. nodes.forEach(n => {{
  2772. nodeNames[n.id] = n.节点名称 || n.id;
  2773. }});
  2774. // 按分数降序排序
  2775. const sortedLinks = [...matchLinks].sort((a, b) => {{
  2776. const scoreA = a.边详情?.相似度 ?? 0;
  2777. const scoreB = b.边详情?.相似度 ?? 0;
  2778. return scoreB - scoreA;
  2779. }});
  2780. countEl.textContent = `(${{sortedLinks.length}})`;
  2781. // 生成列表HTML
  2782. let html = "";
  2783. sortedLinks.forEach((link, index) => {{
  2784. const score = link.边详情?.相似度;
  2785. const scoreText = score !== undefined ? score.toFixed(2) : "N/A";
  2786. const scoreClass = score >= 0.8 ? "high" : (score >= 0.5 ? "medium" : "");
  2787. const srcId = typeof link.source === "object" ? link.source.id : link.source;
  2788. const tgtId = typeof link.target === "object" ? link.target.id : link.target;
  2789. const srcName = nodeNames[srcId] || srcId;
  2790. const tgtName = nodeNames[tgtId] || tgtId;
  2791. html += `
  2792. <div class="match-item" data-index="${{index}}" data-src="${{srcId}}" data-tgt="${{tgtId}}">
  2793. <span class="score ${{scoreClass}}">${{scoreText}}</span>
  2794. <span class="names" title="${{srcName}} → ${{tgtName}}">${{srcName}} → ${{tgtName}}</span>
  2795. </div>
  2796. `;
  2797. }});
  2798. listEl.innerHTML = html;
  2799. // 添加点击事件
  2800. listEl.querySelectorAll(".match-item").forEach(item => {{
  2801. item.addEventListener("click", () => {{
  2802. const srcId = item.dataset.src;
  2803. const tgtId = item.dataset.tgt;
  2804. const index = parseInt(item.dataset.index);
  2805. // 高亮对应的边
  2806. highlightMatchEdge(srcId, tgtId);
  2807. // 更新列表项样式
  2808. listEl.querySelectorAll(".match-item").forEach(el => el.classList.remove("active"));
  2809. item.classList.add("active");
  2810. }});
  2811. }});
  2812. }}
  2813. // 高亮匹配边
  2814. function highlightMatchEdge(srcId, tgtId) {{
  2815. if (!g) return;
  2816. // 重置所有
  2817. g.selectAll(".node").classed("dimmed", true).classed("highlighted", false);
  2818. g.selectAll(".link-group").classed("dimmed", true).classed("highlighted", false);
  2819. // 高亮对应的边和节点
  2820. g.selectAll(".link-group").each(function(d) {{
  2821. const dSrc = typeof d.source === "object" ? d.source.id : d.source;
  2822. const dTgt = typeof d.target === "object" ? d.target.id : d.target;
  2823. if ((dSrc === srcId && dTgt === tgtId) || (dSrc === tgtId && dTgt === srcId)) {{
  2824. d3.select(this).classed("dimmed", false).classed("highlighted", true);
  2825. }}
  2826. }});
  2827. g.selectAll(".node").each(function(d) {{
  2828. if (d.id === srcId || d.id === tgtId) {{
  2829. d3.select(this).classed("dimmed", false).classed("highlighted", true);
  2830. }}
  2831. }});
  2832. }}
  2833. // 获取节点颜色(全局版本,根据节点数据判断维度)
  2834. function getTreeNodeColor(d) {{
  2835. const dimColors = {{ "灵感点": "#f39c12", "目的点": "#3498db", "关键点": "#9b59b6" }};
  2836. if (d.data.isRoot) return "#e94560";
  2837. if (d.data.isDimension) return d.data.dimColor;
  2838. return d.data.dimColor || "#888";
  2839. }}
  2840. // 共享的节点点击处理函数(人设树和关系图复用)
  2841. function handleNodeClick(clickedNodeId, clickedNodeName) {{
  2842. if (!clickedNodeId) return;
  2843. // 动态获取树相关元素
  2844. const treeGroup = d3.select(".persona-tree");
  2845. if (treeGroup.empty()) return;
  2846. const treeEdges = treeGroup.selectAll(".tree-edge");
  2847. // 先重置所有高亮状态
  2848. treeGroup.selectAll(".tree-node")
  2849. .classed("tree-dimmed", false)
  2850. .classed("tree-highlighted", false);
  2851. treeGroup.selectAll(".tree-node .tree-shape")
  2852. .attr("fill", d => getTreeNodeColor(d))
  2853. .attr("stroke", "rgba(255,255,255,0.5)")
  2854. .attr("stroke-width", 1)
  2855. .attr("stroke-opacity", 1)
  2856. .attr("opacity", 1);
  2857. treeGroup.selectAll(".tree-node text")
  2858. .attr("fill", d => (d.data.isRoot || d.data.isDimension) ? getTreeNodeColor(d) : "#bbb")
  2859. .attr("opacity", 1);
  2860. treeEdges.attr("stroke-opacity", 0.3).attr("stroke-width", 1);
  2861. if (g) {{
  2862. g.selectAll(".node").classed("dimmed", false).classed("highlighted", false);
  2863. g.selectAll(".link-group").classed("dimmed", false).classed("highlighted", false);
  2864. }}
  2865. // 构建节点ID到D3节点的映射
  2866. const treeNodeById = {{}};
  2867. treeGroup.selectAll(".tree-node").each(function(n) {{
  2868. if (n.data.节点ID) treeNodeById[n.data.节点ID] = n;
  2869. }});
  2870. // 使用多级配置收集关联节点(与关系图一致)
  2871. const levelConfigs = getLevelConfigs();
  2872. const {{ nodeIds: connectedNodeIds, edges: allConnectedEdges }} = collectNodesAndEdges(clickedNodeId, levelConfigs);
  2873. // 获取D3树节点
  2874. const clickedD3Node = treeNodeById[clickedNodeId];
  2875. // 转换为D3节点集合(只基于 collectNodesAndEdges 的结果,与关系图同步)
  2876. const connectedD3Nodes = new Set();
  2877. if (clickedD3Node) connectedD3Nodes.add(clickedD3Node);
  2878. connectedNodeIds.forEach(id => {{
  2879. if (treeNodeById[id]) connectedD3Nodes.add(treeNodeById[id]);
  2880. }});
  2881. // 高亮树中的节点
  2882. treeGroup.selectAll(".tree-node")
  2883. .classed("tree-dimmed", n => !connectedD3Nodes.has(n))
  2884. .classed("tree-highlighted", n => connectedD3Nodes.has(n));
  2885. // 高亮所有形状(不变粗)
  2886. treeGroup.selectAll(".tree-node .tree-shape")
  2887. .attr("fill", function(n) {{
  2888. if (!connectedD3Nodes.has(n)) return "#555";
  2889. return getTreeNodeColor(n);
  2890. }})
  2891. .attr("stroke", function(n) {{
  2892. if (n.data.节点ID === clickedNodeId) return "#fff";
  2893. return connectedD3Nodes.has(n) ? "rgba(255,255,255,0.8)" : "#333";
  2894. }})
  2895. .attr("stroke-opacity", 1);
  2896. treeGroup.selectAll(".tree-node text")
  2897. .attr("fill", function(n) {{
  2898. if (!connectedD3Nodes.has(n)) return "#555";
  2899. return (n.data.isRoot || n.data.isDimension) ? getTreeNodeColor(n) : "#bbb";
  2900. }});
  2901. // 边高亮(树边基于连接的节点)
  2902. treeEdges.attr("stroke-opacity", function(e) {{
  2903. // 树边高亮条件:子节点(目标)在连接集中,或者两端都在连接集中
  2904. const srcId = e.源节点ID;
  2905. const tgtId = e.目标节点ID;
  2906. const srcConnected = connectedNodeIds.has(srcId) || connectedD3Nodes.has(e.sourceNode);
  2907. const tgtConnected = connectedNodeIds.has(tgtId) || connectedD3Nodes.has(e.targetNode);
  2908. return (srcConnected && tgtConnected) ? 0.9 : 0.15;
  2909. }});
  2910. // 计算入边和出边
  2911. const inEdges = allConnectedEdges.filter(e => e.目标节点ID === clickedNodeId);
  2912. const outEdges = allConnectedEdges.filter(e => e.源节点ID === clickedNodeId);
  2913. // 显示详情面板
  2914. const nodeData = personaTreeData.nodes.find(n => n.节点ID === clickedNodeId);
  2915. if (nodeData) {{
  2916. showTreeNodeDetail(nodeData, inEdges, outEdges);
  2917. }}
  2918. // 显示关系子图(先显示,这样容器高度才正确)
  2919. renderEgoGraph(clickedNodeId, clickedNodeName);
  2920. // 滚动人设树到对应节点位置(放在关系图显示后,高度才准确)
  2921. if (clickedD3Node) {{
  2922. // 用 setTimeout 确保 DOM 更新完成
  2923. setTimeout(() => {{
  2924. const treeContainer = document.getElementById("tree-container");
  2925. const containerHeight = treeContainer.clientHeight;
  2926. // D3树布局中 x 是垂直方向(因为是水平树)
  2927. const nodeY = clickedD3Node.x + 25; // 加上treeGroup的transform偏移
  2928. const targetScroll = nodeY - containerHeight / 2;
  2929. treeContainer.scrollTo({{
  2930. top: Math.max(0, targetScroll),
  2931. behavior: "smooth"
  2932. }});
  2933. }}, 50);
  2934. }}
  2935. // 高亮右侧图中对应节点及其相关节点和边
  2936. if (g) {{
  2937. // 收集相关节点ID(点击的节点及其直接连接的节点)
  2938. const relatedNodeIds = new Set([clickedNodeId]);
  2939. // 找所有与该节点相连的边
  2940. g.selectAll(".link-group").each(function(d) {{
  2941. const srcId = typeof d.source === "object" ? d.source.id : d.source;
  2942. const tgtId = typeof d.target === "object" ? d.target.id : d.target;
  2943. if (srcId === clickedNodeId || tgtId === clickedNodeId) {{
  2944. relatedNodeIds.add(srcId);
  2945. relatedNodeIds.add(tgtId);
  2946. }}
  2947. }});
  2948. // 检查是否有相关节点在图中
  2949. const hasRelatedNodes = g.selectAll(".node").filter(n => relatedNodeIds.has(n.id)).size() > 0;
  2950. if (hasRelatedNodes) {{
  2951. // 高亮相关节点,变灰其他
  2952. g.selectAll(".node")
  2953. .classed("dimmed", n => !relatedNodeIds.has(n.id))
  2954. .classed("highlighted", n => relatedNodeIds.has(n.id));
  2955. // 高亮相关边
  2956. g.selectAll(".link-group").each(function(d) {{
  2957. const srcId = typeof d.source === "object" ? d.source.id : d.source;
  2958. const tgtId = typeof d.target === "object" ? d.target.id : d.target;
  2959. const isRelated = srcId === clickedNodeId || tgtId === clickedNodeId;
  2960. d3.select(this)
  2961. .classed("dimmed", !isRelated)
  2962. .classed("highlighted", isRelated);
  2963. // 显示相关的跨层边
  2964. if (isRelated) {{
  2965. d3.select(this).style("display", "block");
  2966. }}
  2967. }});
  2968. }} else {{
  2969. // 点击的节点不在图中,全部变灰
  2970. g.selectAll(".node").classed("dimmed", true).classed("highlighted", false);
  2971. g.selectAll(".link-group").classed("dimmed", true).classed("highlighted", false);
  2972. }}
  2973. }}
  2974. }}
  2975. // 同步人设树高亮和关系图展示(职责单一:不处理力导向图)
  2976. function syncTreeAndRelationGraph(pathNodeIds, edgeType) {{
  2977. if (!pathNodeIds || pathNodeIds.length === 0) return;
  2978. // 动态获取树相关元素
  2979. const treeGroup = d3.select(".persona-tree");
  2980. if (treeGroup.empty()) return;
  2981. const treeEdges = treeGroup.selectAll(".tree-edge");
  2982. // 重置人设树高亮状态
  2983. treeGroup.selectAll(".tree-node")
  2984. .classed("tree-dimmed", false)
  2985. .classed("tree-highlighted", false);
  2986. treeGroup.selectAll(".tree-node .tree-shape")
  2987. .attr("fill", d => getTreeNodeColor(d))
  2988. .attr("stroke", "rgba(255,255,255,0.5)")
  2989. .attr("stroke-width", 1)
  2990. .attr("stroke-opacity", 1)
  2991. .attr("opacity", 1);
  2992. treeGroup.selectAll(".tree-node text")
  2993. .attr("fill", d => (d.data.isRoot || d.data.isDimension) ? getTreeNodeColor(d) : "#bbb")
  2994. .attr("opacity", 1);
  2995. treeEdges.attr("stroke-opacity", 0.3).attr("stroke-width", 1);
  2996. // 构建节点ID到D3节点的映射
  2997. const treeNodeById = {{}};
  2998. treeGroup.selectAll(".tree-node").each(function(n) {{
  2999. if (n.data.节点ID) treeNodeById[n.data.节点ID] = n;
  3000. }});
  3001. // 路径节点ID集合
  3002. const pathNodeIdSet = new Set(pathNodeIds);
  3003. // 高亮树边(路径上相邻节点之间的边)
  3004. treeEdges.attr("stroke-opacity", function(e) {{
  3005. const srcInPath = pathNodeIdSet.has(e.源节点ID);
  3006. const tgtInPath = pathNodeIdSet.has(e.目标节点ID);
  3007. return (srcInPath && tgtInPath) ? 1 : 0.1;
  3008. }});
  3009. // 高亮路径上的节点
  3010. treeGroup.selectAll(".tree-node").each(function(n) {{
  3011. const nodeId = n.data.节点ID;
  3012. const isInPath = pathNodeIdSet.has(nodeId);
  3013. d3.select(this).select(".tree-shape")
  3014. .attr("fill", isInPath ? getTreeNodeColor(n) : "#555")
  3015. .attr("opacity", 1);
  3016. d3.select(this).select("text")
  3017. .attr("fill", isInPath ?
  3018. ((n.data.isRoot || n.data.isDimension) ? getTreeNodeColor(n) : "#bbb") : "#555")
  3019. .attr("opacity", 1);
  3020. }});
  3021. // 显示路径详情
  3022. const panel = document.getElementById("detailPanel");
  3023. panel.classList.add("active");
  3024. document.getElementById("detailTitle").textContent = "🔗 路径详情";
  3025. // 获取路径上的节点名称
  3026. const pathNodeNames = pathNodeIds.map(id => {{
  3027. const treeNode = treeNodeById[id];
  3028. if (treeNode) return treeNode.data.节点名称 || treeNode.data.name;
  3029. const nodeData = personaTreeData.nodes.find(n => n.节点ID === id);
  3030. return nodeData?.节点名称 || id;
  3031. }});
  3032. let html = `
  3033. <p><span class="label">边类型:</span> <strong>${{edgeType}}</strong></p>
  3034. <p><span class="label">路径节点:</span> ${{pathNodeNames.join(" → ")}}</p>
  3035. <p><span class="label">节点数:</span> ${{pathNodeIds.length}}</p>
  3036. `;
  3037. document.getElementById("detailContent").innerHTML = html;
  3038. // 在关系图中展示路径上的所有节点和边
  3039. renderEgoGraphPath(pathNodeIds, edgeType);
  3040. }}
  3041. // 关系子图(Ego Graph)- 在画布第四层显示
  3042. let currentEgoSimulation = null; // 保存当前的力模拟,用于停止
  3043. let currentEgoCenterNodeId = null; // 当前关系图中心节点ID
  3044. let currentEgoCenterNodeName = null; // 当前关系图中心节点名称
  3045. // 当前选中的层级数
  3046. let currentLevelCount = 1;
  3047. // 切换级联菜单
  3048. function toggleCascadeMenu() {{
  3049. event.stopPropagation();
  3050. const menu = document.getElementById('cascade-menu');
  3051. menu.classList.toggle('show');
  3052. }}
  3053. // 反选指定层级的边类型
  3054. function invertSelection(level) {{
  3055. event.stopPropagation();
  3056. document.querySelectorAll(`.cascade-edge-item input[data-level="${{level}}"]`).forEach(cb => {{
  3057. cb.checked = !cb.checked;
  3058. }});
  3059. // 更新全选复选框状态
  3060. const allItems = document.querySelectorAll(`.cascade-edge-item input[data-level="${{level}}"]`);
  3061. const checkedItems = document.querySelectorAll(`.cascade-edge-item input[data-level="${{level}}"]:checked`);
  3062. const selectAllCb = document.querySelector(`.select-all input[data-level="${{level}}"]`);
  3063. selectAllCb.checked = allItems.length === checkedItems.length;
  3064. // 重新渲染
  3065. if (currentEgoCenterNodeId) {{
  3066. handleNodeClick(currentEgoCenterNodeId, currentEgoCenterNodeName);
  3067. }}
  3068. }}
  3069. // 重置所有层级到默认配置(1级全选,2/3级只选包含)
  3070. function resetSelection() {{
  3071. event.stopPropagation();
  3072. // Level 1: 全选
  3073. document.querySelectorAll('.cascade-edge-item input[data-level="1"]').forEach(cb => {{
  3074. cb.checked = true;
  3075. }});
  3076. document.querySelector('.select-all input[data-level="1"]').checked = true;
  3077. // Level 2 & 3: 只选包含
  3078. [2, 3].forEach(level => {{
  3079. document.querySelectorAll(`.cascade-edge-item input[data-level="${{level}}"]`).forEach(cb => {{
  3080. cb.checked = (cb.dataset.type === "包含");
  3081. }});
  3082. document.querySelector(`.select-all input[data-level="${{level}}"]`).checked = false;
  3083. }});
  3084. // 重新渲染
  3085. if (currentEgoCenterNodeId) {{
  3086. handleNodeClick(currentEgoCenterNodeId, currentEgoCenterNodeName);
  3087. }}
  3088. }}
  3089. // 选择层级
  3090. function selectLevel(level) {{
  3091. event.stopPropagation();
  3092. currentLevelCount = level;
  3093. // 更新层级选中状态
  3094. document.querySelectorAll('.cascade-level-item').forEach(item => {{
  3095. const itemLevel = parseInt(item.dataset.level);
  3096. item.classList.toggle('active', itemLevel === level);
  3097. }});
  3098. // 显示对应的边类型组(1级显示L1,2级显示L1+L2,3级显示L1+L2+L3)
  3099. document.querySelectorAll('.cascade-edge-group').forEach(group => {{
  3100. const groupLevel = parseInt(group.dataset.level);
  3101. group.classList.toggle('active', groupLevel <= level);
  3102. }});
  3103. // 更新按钮显示
  3104. document.getElementById('cascade-label').textContent = level + '级';
  3105. // 重新渲染关系图和人设树高亮
  3106. if (currentEgoCenterNodeId) {{
  3107. handleNodeClick(currentEgoCenterNodeId, currentEgoCenterNodeName);
  3108. }}
  3109. }}
  3110. // 获取指定层级选中的边类型
  3111. function getLevelEdgeTypes(level) {{
  3112. const types = [];
  3113. document.querySelectorAll(`.cascade-edge-item input[data-level="${{level}}"]:checked`).forEach(cb => {{
  3114. types.push(cb.dataset.type);
  3115. }});
  3116. return types;
  3117. }}
  3118. // 获取层级配置(返回每层的边类型数组)
  3119. function getLevelConfigs() {{
  3120. const configs = [];
  3121. for (let i = 1; i <= currentLevelCount; i++) {{
  3122. const types = getLevelEdgeTypes(i);
  3123. configs.push(types);
  3124. }}
  3125. return configs;
  3126. }}
  3127. // 多层级展开:收集指定层级内的所有节点和边(每层可指定不同边类型)
  3128. function collectNodesAndEdges(centerNodeId, levelConfigs) {{
  3129. const nodeIds = new Set([centerNodeId]);
  3130. const collectedEdges = [];
  3131. const visitedEdges = new Set();
  3132. let currentLayer = new Set([centerNodeId]);
  3133. for (let d = 0; d < levelConfigs.length; d++) {{
  3134. const edgeTypes = levelConfigs[d];
  3135. if (edgeTypes.length === 0) break;
  3136. const nextLayer = new Set();
  3137. personaTreeData.edges.forEach(e => {{
  3138. // 筛选边类型
  3139. if (!edgeTypes.includes(e.边类型)) return;
  3140. const edgeKey = `${{e.源节点ID}}-${{e.目标节点ID}}-${{e.边类型}}`;
  3141. if (visitedEdges.has(edgeKey)) return;
  3142. // 单向查找:只从源节点出发,沿边的方向查找
  3143. // 属于:子→父(从子出发找父)
  3144. // 包含:父→子(从父出发找子)
  3145. // 共现:A→B(从A出发找B)
  3146. if (currentLayer.has(e.源节点ID)) {{
  3147. visitedEdges.add(edgeKey);
  3148. collectedEdges.push({{...e, _level: d + 1}});
  3149. // 添加目标节点到下一层
  3150. if (!nodeIds.has(e.目标节点ID)) {{
  3151. nextLayer.add(e.目标节点ID);
  3152. nodeIds.add(e.目标节点ID);
  3153. }}
  3154. }}
  3155. }});
  3156. currentLayer = nextLayer;
  3157. if (nextLayer.size === 0) break;
  3158. }}
  3159. return {{ nodeIds, edges: collectedEdges, depth: levelConfigs.length }};
  3160. }}
  3161. function renderEgoGraph(centerNodeId, centerNodeName) {{
  3162. // 保存当前中心节点
  3163. currentEgoCenterNodeId = centerNodeId;
  3164. currentEgoCenterNodeName = centerNodeName;
  3165. // 显示关系图容器
  3166. document.getElementById("ego-container").style.display = "block";
  3167. // 获取关系图层组
  3168. const egoGroup = d3.select(".ego-graph-content");
  3169. if (egoGroup.empty()) return;
  3170. // 停止之前的模拟
  3171. if (currentEgoSimulation) {{
  3172. currentEgoSimulation.stop();
  3173. currentEgoSimulation = null;
  3174. }}
  3175. // 清除旧内容
  3176. egoGroup.selectAll("*").remove();
  3177. // 获取当前层级配置
  3178. const levelConfigs = getLevelConfigs();
  3179. // 更新顶部标题和统计
  3180. document.getElementById("ego-node-name").textContent = centerNodeName;
  3181. // 获取层半径
  3182. const radius = 160; // 固定半径
  3183. // 根据层级配置收集节点和边
  3184. const {{ nodeIds, edges: relatedEdges, depth }} = collectNodesAndEdges(centerNodeId, levelConfigs);
  3185. // 构建节点数据(确保中心节点始终包含)
  3186. const nodeMap = {{}};
  3187. personaTreeData.nodes.forEach(n => {{
  3188. if (nodeIds.has(n.节点ID) || n.节点ID === centerNodeId) {{
  3189. nodeMap[n.节点ID] = {{
  3190. id: n.节点ID,
  3191. name: n.节点名称,
  3192. type: n.节点类型,
  3193. level: n.节点层级,
  3194. isCenter: n.节点ID === centerNodeId
  3195. }};
  3196. }}
  3197. }});
  3198. const nodes = Object.values(nodeMap);
  3199. // 处理同一对节点间的多条边,分配不同弧度
  3200. const linksByPair = {{}};
  3201. relatedEdges.forEach(e => {{
  3202. // 用排序后的节点对作为key,确保A-B和B-A是同一对
  3203. const pairKey = [e.源节点ID, e.目标节点ID].sort().join("||");
  3204. if (!linksByPair[pairKey]) linksByPair[pairKey] = [];
  3205. linksByPair[pairKey].push(e);
  3206. }});
  3207. // 为每条边分配弧度索引
  3208. const links = [];
  3209. Object.values(linksByPair).forEach(pairEdges => {{
  3210. const count = pairEdges.length;
  3211. pairEdges.forEach((e, i) => {{
  3212. // 弧度:0表示直线,正负值表示向两侧弯曲
  3213. let curvature = 0;
  3214. if (count > 1) {{
  3215. // 多条边时,均匀分布弧度
  3216. curvature = (i - (count - 1) / 2) * 0.3;
  3217. }}
  3218. links.push({{
  3219. source: e.源节点ID,
  3220. target: e.目标节点ID,
  3221. type: e.边类型,
  3222. curvature: curvature
  3223. }});
  3224. }});
  3225. }});
  3226. // 根据节点数量动态计算实际使用的半径
  3227. const nodeCount = nodes.length;
  3228. const nodeSpacingEgo = 65; // 节点间距(增大)
  3229. const minEgoRadius = 120;
  3230. const maxEgoRadius = Math.max(radius, 250); // 允许更大的半径
  3231. let actualRadius;
  3232. if (nodeCount <= 1) {{
  3233. actualRadius = minEgoRadius;
  3234. }} else {{
  3235. const circumference = nodeCount * nodeSpacingEgo;
  3236. const calcR = circumference / (2 * Math.PI);
  3237. actualRadius = Math.max(minEgoRadius, Math.min(maxEgoRadius, calcR));
  3238. }}
  3239. // 更新顶部统计信息
  3240. document.getElementById("ego-stats").textContent = `${{nodeCount}}节点 ${{relatedEdges.length}}边`;
  3241. // 如果只有中心节点,只渲染中心节点
  3242. if (nodes.length === 1) {{
  3243. const centerNode = nodes[0];
  3244. // 获取中心节点的维度颜色
  3245. const dimColors = {{
  3246. "灵感点": "#f39c12",
  3247. "目的点": "#3498db",
  3248. "关键点": "#9b59b6"
  3249. }};
  3250. const level = centerNode.level || "";
  3251. let fillColor = "#888";
  3252. if (level.includes("灵感点")) fillColor = dimColors["灵感点"];
  3253. else if (level.includes("目的点")) fillColor = dimColors["目的点"];
  3254. else if (level.includes("关键点")) fillColor = dimColors["关键点"];
  3255. // 绘制中心节点
  3256. const nodeGroup = egoGroup.append("g")
  3257. .attr("class", "ego-node-group")
  3258. .attr("transform", "translate(0, 0)");
  3259. nodeGroup.append("circle")
  3260. .attr("r", 22)
  3261. .attr("fill", fillColor)
  3262. .attr("stroke", "#fff")
  3263. .attr("stroke-width", 3)
  3264. .attr("cursor", "pointer")
  3265. .style("filter", "drop-shadow(0 2px 4px rgba(0,0,0,0.3))");
  3266. nodeGroup.append("text")
  3267. .attr("dy", "0.35em")
  3268. .attr("text-anchor", "middle")
  3269. .attr("fill", "#fff")
  3270. .attr("font-size", "10px")
  3271. .attr("font-weight", "bold")
  3272. .attr("pointer-events", "none")
  3273. .text(centerNode.name.length > 4 ? centerNode.name.slice(0, 4) + "..." : centerNode.name);
  3274. // 显示提示文字
  3275. egoGroup.append("text")
  3276. .attr("y", 50)
  3277. .attr("text-anchor", "middle")
  3278. .attr("fill", "rgba(255,255,255,0.4)")
  3279. .attr("font-size", "10px")
  3280. .text("无相关边");
  3281. return;
  3282. }}
  3283. // 边类型颜色(统一用实线)
  3284. const edgeColors = {{
  3285. "属于": "#9b59b6", // 紫色 - 层级关系
  3286. "包含": "#ffb6c1", // 淡粉 - 分类包含标签(向下)
  3287. "分类共现(跨点)": "#2ecc71", // 绿色 - 跨帖子分类共现
  3288. "分类共现(点内)": "#3498db", // 蓝色 - 同帖子分类共现
  3289. "标签共现": "#f39c12" // 橙色 - 标签共现
  3290. }};
  3291. // 维度颜色(与人设树完全一致)
  3292. const dimColors = {{
  3293. "灵感点": "#f39c12",
  3294. "目的点": "#3498db",
  3295. "关键点": "#9b59b6"
  3296. }};
  3297. // 获取节点的维度颜色(与人设树一致)
  3298. function getNodeDimColor(d) {{
  3299. // 根据节点层级判断维度
  3300. const level = d.level || "";
  3301. if (level.includes("灵感点")) return dimColors["灵感点"];
  3302. if (level.includes("目的点")) return dimColors["目的点"];
  3303. if (level.includes("关键点")) return dimColors["关键点"];
  3304. return "#888";
  3305. }}
  3306. // 获取节点填充色(实心,用维度颜色,不因选中而改变)
  3307. function getNodeFill(d) {{
  3308. return getNodeDimColor(d); // 始终用维度颜色填充
  3309. }}
  3310. // 获取节点边框色(选中节点用白色边框区分)
  3311. function getNodeStroke(d) {{
  3312. if (d.isCenter) return "#fff"; // 选中节点白色边框
  3313. return "rgba(255,255,255,0.5)"; // 普通节点半透明白边框
  3314. }}
  3315. // 获取节点边框粗细(选中节点更粗)
  3316. function getNodeStrokeWidth(d) {{
  3317. return d.isCenter ? 3 : 1.5;
  3318. }}
  3319. // 根据节点数量调整力模拟参数
  3320. const linkDistance = Math.max(50, Math.min(80, actualRadius / 2.5));
  3321. const chargeStrength = Math.max(-300, Math.min(-100, -nodeCount * 10));
  3322. const collisionRadius = 35; // 碰撞半径,防止重叠
  3323. // 创建力导向模拟(中心在0,0因为已经平移了)
  3324. const simulation = d3.forceSimulation(nodes)
  3325. .force("link", d3.forceLink(links).id(d => d.id).distance(linkDistance))
  3326. .force("charge", d3.forceManyBody().strength(chargeStrength))
  3327. .force("center", d3.forceCenter(0, 0))
  3328. .force("collision", d3.forceCollide().radius(collisionRadius))
  3329. .force("boundary", function() {{
  3330. // 限制节点在圆形区域内
  3331. const maxR = actualRadius - 30;
  3332. return function(alpha) {{
  3333. nodes.forEach(d => {{
  3334. const dist = Math.sqrt(d.x * d.x + d.y * d.y);
  3335. if (dist > maxR) {{
  3336. const scale = maxR / dist;
  3337. d.x *= scale;
  3338. d.y *= scale;
  3339. }}
  3340. }});
  3341. }};
  3342. }}());
  3343. currentEgoSimulation = simulation;
  3344. // 绘制边(用曲线支持多边)
  3345. const link = egoGroup.selectAll(".ego-edge")
  3346. .data(links)
  3347. .join("path")
  3348. .attr("class", "ego-edge")
  3349. .attr("stroke", d => edgeColors[d.type] || "#666")
  3350. .attr("stroke-width", 1.5)
  3351. .attr("stroke-opacity", 0.7)
  3352. .attr("fill", "none");
  3353. // 绘制节点(分类用方形,标签用圆形)
  3354. const node = egoGroup.selectAll(".ego-node")
  3355. .data(nodes)
  3356. .join("g")
  3357. .attr("class", d => "ego-node" + (d.isCenter ? " center" : ""));
  3358. // 根据节点类型绘制不同形状(与人设树样式一致)
  3359. const nodeSize = 8;
  3360. node.each(function(d) {{
  3361. const el = d3.select(this);
  3362. const fill = getNodeFill(d);
  3363. const stroke = getNodeStroke(d);
  3364. const size = d.isCenter ? nodeSize + 2 : nodeSize;
  3365. const strokeWidth = getNodeStrokeWidth(d);
  3366. if (d.type === "分类") {{
  3367. // 方形(分类节点)- 与人设树一致
  3368. el.append("rect")
  3369. .attr("class", "ego-shape")
  3370. .attr("width", size * 2)
  3371. .attr("height", size * 2)
  3372. .attr("x", -size)
  3373. .attr("y", -size)
  3374. .attr("fill", fill)
  3375. .attr("stroke", stroke)
  3376. .attr("stroke-width", strokeWidth)
  3377. .attr("rx", 1);
  3378. }} else {{
  3379. // 圆形(标签节点)- 与人设树一致
  3380. el.append("circle")
  3381. .attr("class", "ego-shape")
  3382. .attr("r", size)
  3383. .attr("fill", fill)
  3384. .attr("stroke", stroke)
  3385. .attr("stroke-width", strokeWidth);
  3386. }}
  3387. }});
  3388. node.append("text")
  3389. .attr("dy", -12)
  3390. .attr("text-anchor", "middle")
  3391. .attr("font-size", "9px")
  3392. .attr("fill", "#fff")
  3393. .text(d => d.name.length > 6 ? d.name.substring(0, 6) + ".." : d.name);
  3394. // 添加点击事件(直接调用共享函数)
  3395. node.on("click", function(event, d) {{
  3396. event.stopPropagation();
  3397. handleNodeClick(d.id, d.name);
  3398. }})
  3399. .on("mouseenter", function(event, d) {{
  3400. // 悬停高亮:高亮到激活节点的路径
  3401. if (!currentEgoCenterNodeId || d.id === currentEgoCenterNodeId) return;
  3402. highlightPathInEgoGraph(d.id);
  3403. }})
  3404. .on("mouseleave", function(event, d) {{
  3405. // 移出时恢复
  3406. if (!currentEgoCenterNodeId) return;
  3407. resetEgoGraphHighlight();
  3408. }});
  3409. // 边点击事件(直接调用共享函数)
  3410. link.on("click", function(event, d) {{
  3411. event.stopPropagation();
  3412. handleEdgeClick(d.source.id, d.target.id, d.type);
  3413. }});
  3414. // 生成曲线路径的函数
  3415. function linkPath(d) {{
  3416. const sx = d.source.x, sy = d.source.y;
  3417. const tx = d.target.x, ty = d.target.y;
  3418. if (d.curvature === 0) {{
  3419. // 直线
  3420. return `M${{sx}},${{sy}}L${{tx}},${{ty}}`;
  3421. }} else {{
  3422. // 曲线:计算控制点
  3423. const dx = tx - sx, dy = ty - sy;
  3424. const dist = Math.sqrt(dx * dx + dy * dy);
  3425. // 控制点垂直于连线方向偏移
  3426. const mx = (sx + tx) / 2;
  3427. const my = (sy + ty) / 2;
  3428. const offset = d.curvature * dist * 0.5;
  3429. // 垂直方向单位向量
  3430. const nx = -dy / dist, ny = dx / dist;
  3431. const cx = mx + nx * offset;
  3432. const cy = my + ny * offset;
  3433. return `M${{sx}},${{sy}}Q${{cx}},${{cy}} ${{tx}},${{ty}}`;
  3434. }}
  3435. }}
  3436. // 更新位置
  3437. simulation.on("tick", () => {{
  3438. link.attr("d", linkPath);
  3439. node.attr("transform", d => `translate(${{d.x}},${{d.y}})`);
  3440. }});
  3441. }}
  3442. function clearEgoGraph() {{
  3443. const egoGroup = d3.select(".ego-graph-content");
  3444. if (!egoGroup.empty()) {{
  3445. egoGroup.selectAll("*").remove();
  3446. }}
  3447. // 隐藏关系图容器
  3448. document.getElementById("ego-container").style.display = "none";
  3449. // 停止模拟
  3450. if (currentEgoSimulation) {{
  3451. currentEgoSimulation.stop();
  3452. currentEgoSimulation = null;
  3453. }}
  3454. }}
  3455. // 在关系图中高亮从悬停节点到激活节点的路径
  3456. function highlightPathInEgoGraph(hoveredNodeId) {{
  3457. const egoGroup = d3.select(".ego-graph-content");
  3458. if (egoGroup.empty()) return;
  3459. // 获取关系图中的边数据
  3460. const egoEdges = egoGroup.selectAll(".ego-edge");
  3461. const egoNodes = egoGroup.selectAll(".ego-node");
  3462. if (egoEdges.empty()) return;
  3463. // 构建邻接表用于路径查找
  3464. const adjacency = {{}};
  3465. const edgeMap = {{}};
  3466. egoEdges.each(function(d) {{
  3467. const srcId = d.source.id || d.source;
  3468. const tgtId = d.target.id || d.target;
  3469. if (!adjacency[srcId]) adjacency[srcId] = [];
  3470. if (!adjacency[tgtId]) adjacency[tgtId] = [];
  3471. adjacency[srcId].push(tgtId);
  3472. adjacency[tgtId].push(srcId);
  3473. // 记录边(双向)
  3474. const key1 = `${{srcId}}|${{tgtId}}`;
  3475. const key2 = `${{tgtId}}|${{srcId}}`;
  3476. edgeMap[key1] = d;
  3477. edgeMap[key2] = d;
  3478. }});
  3479. // BFS找路径
  3480. const visited = new Set();
  3481. const parent = {{}};
  3482. const queue = [currentEgoCenterNodeId];
  3483. visited.add(currentEgoCenterNodeId);
  3484. let found = false;
  3485. while (queue.length > 0 && !found) {{
  3486. const curr = queue.shift();
  3487. const neighbors = adjacency[curr] || [];
  3488. for (const next of neighbors) {{
  3489. if (!visited.has(next)) {{
  3490. visited.add(next);
  3491. parent[next] = curr;
  3492. queue.push(next);
  3493. if (next === hoveredNodeId) {{
  3494. found = true;
  3495. break;
  3496. }}
  3497. }}
  3498. }}
  3499. }}
  3500. if (!found) return;
  3501. // 回溯路径
  3502. const pathNodes = new Set();
  3503. const pathEdgeKeys = new Set();
  3504. let curr = hoveredNodeId;
  3505. while (curr !== undefined) {{
  3506. pathNodes.add(curr);
  3507. const prev = parent[curr];
  3508. if (prev !== undefined) {{
  3509. pathEdgeKeys.add(`${{prev}}|${{curr}}`);
  3510. pathEdgeKeys.add(`${{curr}}|${{prev}}`);
  3511. }}
  3512. curr = prev;
  3513. }}
  3514. // 隐藏不在路径上的边(保持布局不变)
  3515. egoEdges
  3516. .style("visibility", function(d) {{
  3517. const srcId = d.source.id || d.source;
  3518. const tgtId = d.target.id || d.target;
  3519. const key = `${{srcId}}|${{tgtId}}`;
  3520. return pathEdgeKeys.has(key) ? "visible" : "hidden";
  3521. }});
  3522. // 隐藏不在路径上的节点(保持布局不变)
  3523. egoNodes
  3524. .style("visibility", function(d) {{
  3525. return pathNodes.has(d.id) ? "visible" : "hidden";
  3526. }});
  3527. }}
  3528. // 恢复关系图的高亮状态
  3529. function resetEgoGraphHighlight() {{
  3530. const egoGroup = d3.select(".ego-graph-content");
  3531. if (egoGroup.empty()) return;
  3532. // 恢复边的可见性
  3533. egoGroup.selectAll(".ego-edge")
  3534. .style("visibility", "visible");
  3535. // 恢复节点的可见性
  3536. egoGroup.selectAll(".ego-node")
  3537. .style("visibility", "visible");
  3538. }}
  3539. // 渲染路径上的所有节点和边(点击镜像边/二阶边时调用)
  3540. function renderEgoGraphPath(pathNodeIds, edgeType) {{
  3541. if (!pathNodeIds || pathNodeIds.length === 0) return;
  3542. // 显示关系图容器
  3543. document.getElementById("ego-container").style.display = "block";
  3544. const egoGroup = d3.select(".ego-graph-content");
  3545. if (egoGroup.empty()) return;
  3546. // 停止之前的模拟
  3547. if (currentEgoSimulation) {{
  3548. currentEgoSimulation.stop();
  3549. currentEgoSimulation = null;
  3550. }}
  3551. // 清除旧内容
  3552. egoGroup.selectAll("*").remove();
  3553. // 边类型颜色
  3554. const edgeColors = {{
  3555. "属于": "#9b59b6",
  3556. "包含": "#ffb6c1",
  3557. "分类共现(跨点)": "#2ecc71",
  3558. "分类共现(点内)": "#3498db",
  3559. "标签共现": "#f39c12"
  3560. }};
  3561. // 维度颜色
  3562. const dimColors = {{
  3563. "灵感点": "#f39c12",
  3564. "目的点": "#3498db",
  3565. "关键点": "#9b59b6"
  3566. }};
  3567. // 获取节点颜色
  3568. function getNodeColor(nodeData) {{
  3569. const level = nodeData.节点层级 || "";
  3570. if (level.includes("灵感点")) return dimColors["灵感点"];
  3571. if (level.includes("目的点")) return dimColors["目的点"];
  3572. if (level.includes("关键点")) return dimColors["关键点"];
  3573. return "#888";
  3574. }}
  3575. // 获取路径节点数据
  3576. const pathNodes = pathNodeIds.map(id => {{
  3577. const nodeData = personaTreeData.nodes.find(n => n.节点ID === id);
  3578. return nodeData || {{ 节点ID: id, 节点名称: id, 节点类型: "标签" }};
  3579. }});
  3580. // 找出路径上相邻节点之间的边
  3581. const pathEdges = [];
  3582. for (let i = 0; i < pathNodeIds.length - 1; i++) {{
  3583. const srcId = pathNodeIds[i];
  3584. const tgtId = pathNodeIds[i + 1];
  3585. // 在 personaTreeData.edges 中查找
  3586. const edge = personaTreeData.edges.find(e =>
  3587. (e.源节点ID === srcId && e.目标节点ID === tgtId) ||
  3588. (e.源节点ID === tgtId && e.目标节点ID === srcId)
  3589. );
  3590. pathEdges.push(edge || {{ 边类型: edgeType, 源节点ID: srcId, 目标节点ID: tgtId }});
  3591. }}
  3592. // 更新顶部标题
  3593. document.getElementById("ego-node-name").textContent = edgeType;
  3594. document.getElementById("ego-stats").textContent = `${{pathNodes.length}}节点 ${{pathEdges.length}}边`;
  3595. // 水平线性布局
  3596. const nodeSpacing = 80;
  3597. const totalWidth = (pathNodes.length - 1) * nodeSpacing;
  3598. const startX = -totalWidth / 2;
  3599. // 绘制边
  3600. pathEdges.forEach((edge, i) => {{
  3601. const x1 = startX + i * nodeSpacing;
  3602. const x2 = startX + (i + 1) * nodeSpacing;
  3603. // 边的可点击区域(更宽的透明线)
  3604. egoGroup.append("line")
  3605. .attr("class", "ego-edge-hitarea")
  3606. .attr("x1", x1)
  3607. .attr("y1", 0)
  3608. .attr("x2", x2)
  3609. .attr("y2", 0)
  3610. .attr("stroke", "transparent")
  3611. .attr("stroke-width", 15)
  3612. .style("cursor", "pointer")
  3613. .on("click", (event) => {{
  3614. event.stopPropagation();
  3615. handleEdgeClick(edge.源节点ID, edge.目标节点ID, edge.边类型);
  3616. }});
  3617. // 可见的边
  3618. egoGroup.append("line")
  3619. .attr("class", "ego-edge")
  3620. .attr("x1", x1)
  3621. .attr("y1", 0)
  3622. .attr("x2", x2)
  3623. .attr("y2", 0)
  3624. .attr("stroke", edgeColors[edge.边类型] || "#666")
  3625. .attr("stroke-width", 3)
  3626. .attr("stroke-opacity", 0.8)
  3627. .style("pointer-events", "none");
  3628. // 边类型标签
  3629. egoGroup.append("text")
  3630. .attr("x", (x1 + x2) / 2)
  3631. .attr("y", 20)
  3632. .attr("text-anchor", "middle")
  3633. .attr("fill", "#999")
  3634. .attr("font-size", "9px")
  3635. .style("pointer-events", "none")
  3636. .text(edge.边类型);
  3637. }});
  3638. // 绘制节点
  3639. pathNodes.forEach((nodeData, i) => {{
  3640. const x = startX + i * nodeSpacing;
  3641. const nodeGroup = egoGroup.append("g")
  3642. .attr("class", "ego-node")
  3643. .attr("transform", `translate(${{x}}, 0)`)
  3644. .style("cursor", "pointer")
  3645. .on("click", (event) => {{
  3646. event.stopPropagation();
  3647. handleNodeClick(nodeData.节点ID, nodeData.节点名称 || nodeData.name);
  3648. }});
  3649. const nodeSize = 15;
  3650. const nodeColor = getNodeColor(nodeData);
  3651. if (nodeData.节点类型 === "分类") {{
  3652. nodeGroup.append("rect")
  3653. .attr("width", nodeSize * 2)
  3654. .attr("height", nodeSize * 2)
  3655. .attr("x", -nodeSize)
  3656. .attr("y", -nodeSize)
  3657. .attr("fill", nodeColor)
  3658. .attr("stroke", "rgba(255,255,255,0.5)")
  3659. .attr("stroke-width", 2)
  3660. .attr("rx", 2);
  3661. }} else {{
  3662. nodeGroup.append("circle")
  3663. .attr("r", nodeSize)
  3664. .attr("fill", nodeColor)
  3665. .attr("stroke", "rgba(255,255,255,0.5)")
  3666. .attr("stroke-width", 2);
  3667. }}
  3668. // 节点名称
  3669. nodeGroup.append("text")
  3670. .attr("dy", -nodeSize - 8)
  3671. .attr("text-anchor", "middle")
  3672. .attr("fill", "#fff")
  3673. .attr("font-size", "10px")
  3674. .style("pointer-events", "none")
  3675. .text(nodeData.节点名称 || nodeData.name || nodeData.节点ID);
  3676. }});
  3677. }}
  3678. // 渲染单条边和两个节点(点击树边时调用)
  3679. function renderEgoGraphEdge(edgeData, sourceNode, targetNode) {{
  3680. // 显示关系图容器
  3681. document.getElementById("ego-container").style.display = "block";
  3682. const egoGroup = d3.select(".ego-graph-content");
  3683. if (egoGroup.empty()) return;
  3684. // 停止之前的模拟
  3685. if (currentEgoSimulation) {{
  3686. currentEgoSimulation.stop();
  3687. currentEgoSimulation = null;
  3688. }}
  3689. // 清除旧内容
  3690. egoGroup.selectAll("*").remove();
  3691. // 更新顶部标题
  3692. document.getElementById("ego-node-name").textContent = edgeData.边类型;
  3693. document.getElementById("ego-stats").textContent = "2节点 1边";
  3694. const radius = 160;
  3695. // 边类型颜色
  3696. const edgeColors = {{
  3697. "属于": "#9b59b6",
  3698. "包含": "#ffb6c1",
  3699. "分类共现(跨点)": "#2ecc71",
  3700. "分类共现(点内)": "#3498db",
  3701. "标签共现": "#f39c12"
  3702. }};
  3703. // 维度颜色
  3704. const dimColors = {{
  3705. "灵感点": "#f39c12",
  3706. "目的点": "#3498db",
  3707. "关键点": "#9b59b6"
  3708. }};
  3709. // 获取节点颜色
  3710. function getNodeColor(nodeData) {{
  3711. const level = nodeData.节点层级 || "";
  3712. if (level.includes("灵感点")) return dimColors["灵感点"];
  3713. if (level.includes("目的点")) return dimColors["目的点"];
  3714. if (level.includes("关键点")) return dimColors["关键点"];
  3715. return "#888";
  3716. }}
  3717. // 两个节点的位置
  3718. const srcX = -60, srcY = 0;
  3719. const tgtX = 60, tgtY = 0;
  3720. // 绘制边
  3721. egoGroup.append("line")
  3722. .attr("class", "ego-edge")
  3723. .attr("x1", srcX)
  3724. .attr("y1", srcY)
  3725. .attr("x2", tgtX)
  3726. .attr("y2", tgtY)
  3727. .attr("stroke", edgeColors[edgeData.边类型] || "#666")
  3728. .attr("stroke-width", 3)
  3729. .attr("stroke-opacity", 0.8);
  3730. // 获取节点数据
  3731. const srcData = sourceNode ? sourceNode.data : {{}};
  3732. const tgtData = targetNode ? targetNode.data : {{}};
  3733. // 绘制源节点
  3734. const srcGroup = egoGroup.append("g")
  3735. .attr("class", "ego-node")
  3736. .attr("transform", `translate(${{srcX}}, ${{srcY}})`);
  3737. const srcSize = 15;
  3738. const srcColor = getNodeColor(srcData);
  3739. if (srcData.节点类型 === "分类") {{
  3740. srcGroup.append("rect")
  3741. .attr("width", srcSize * 2)
  3742. .attr("height", srcSize * 2)
  3743. .attr("x", -srcSize)
  3744. .attr("y", -srcSize)
  3745. .attr("fill", srcColor)
  3746. .attr("stroke", "rgba(255,255,255,0.5)")
  3747. .attr("stroke-width", 2)
  3748. .attr("rx", 2);
  3749. }} else {{
  3750. srcGroup.append("circle")
  3751. .attr("r", srcSize)
  3752. .attr("fill", srcColor)
  3753. .attr("stroke", "rgba(255,255,255,0.5)")
  3754. .attr("stroke-width", 2);
  3755. }}
  3756. srcGroup.append("text")
  3757. .attr("dy", -srcSize - 8)
  3758. .attr("text-anchor", "middle")
  3759. .attr("fill", "#fff")
  3760. .attr("font-size", "11px")
  3761. .text(srcData.节点名称 || srcData.name || "源节点");
  3762. // 绘制目标节点
  3763. const tgtGroup = egoGroup.append("g")
  3764. .attr("class", "ego-node")
  3765. .attr("transform", `translate(${{tgtX}}, ${{tgtY}})`);
  3766. const tgtSize = 15;
  3767. const tgtColor = getNodeColor(tgtData);
  3768. if (tgtData.节点类型 === "分类") {{
  3769. tgtGroup.append("rect")
  3770. .attr("width", tgtSize * 2)
  3771. .attr("height", tgtSize * 2)
  3772. .attr("x", -tgtSize)
  3773. .attr("y", -tgtSize)
  3774. .attr("fill", tgtColor)
  3775. .attr("stroke", "rgba(255,255,255,0.5)")
  3776. .attr("stroke-width", 2)
  3777. .attr("rx", 2);
  3778. }} else {{
  3779. tgtGroup.append("circle")
  3780. .attr("r", tgtSize)
  3781. .attr("fill", tgtColor)
  3782. .attr("stroke", "rgba(255,255,255,0.5)")
  3783. .attr("stroke-width", 2);
  3784. }}
  3785. tgtGroup.append("text")
  3786. .attr("dy", -tgtSize - 8)
  3787. .attr("text-anchor", "middle")
  3788. .attr("fill", "#fff")
  3789. .attr("font-size", "11px")
  3790. .text(tgtData.节点名称 || tgtData.name || "目标节点");
  3791. // 边标签
  3792. egoGroup.append("text")
  3793. .attr("y", 25)
  3794. .attr("text-anchor", "middle")
  3795. .attr("fill", "rgba(255,255,255,0.6)")
  3796. .attr("font-size", "10px")
  3797. .text(edgeData.边类型);
  3798. }}
  3799. // 页面加载完成后初始化
  3800. window.addEventListener("load", init);
  3801. window.addEventListener("resize", () => {{
  3802. if (currentIndex >= 0) {{
  3803. renderGraph(allGraphData[currentIndex]);
  3804. }}
  3805. }});
  3806. </script>
  3807. </body>
  3808. </html>
  3809. '''
  3810. def generate_combined_html(all_graph_data: List[Dict], persona_tree_data: Dict, output_file: Path):
  3811. """
  3812. 生成包含所有帖子图谱的HTML文件
  3813. Args:
  3814. all_graph_data: 所有帖子的图谱数据列表
  3815. persona_tree_data: 完整的人设树数据(节点和边)
  3816. output_file: 输出文件路径
  3817. """
  3818. # 生成Tab HTML
  3819. tabs_html = ""
  3820. for i, data in enumerate(all_graph_data):
  3821. post_title = data.get("postTitle", "")
  3822. # 使用帖子标题,如果太长则截断
  3823. if post_title:
  3824. tab_name = post_title[:15] + "..." if len(post_title) > 15 else post_title
  3825. else:
  3826. tab_name = f"帖子 {i+1}"
  3827. active_class = "active" if i == 0 else ""
  3828. tabs_html += f'<div class="tab {active_class}" data-index="{i}">{tab_name}</div>\n'
  3829. # 生成HTML
  3830. html_content = HTML_TEMPLATE.format(
  3831. tabs_html=tabs_html,
  3832. all_graph_data=json.dumps(all_graph_data, ensure_ascii=False),
  3833. persona_tree_data=json.dumps(persona_tree_data, ensure_ascii=False)
  3834. )
  3835. with open(output_file, "w", encoding="utf-8") as f:
  3836. f.write(html_content)
  3837. def main():
  3838. # 使用路径配置
  3839. config = PathConfig()
  3840. print(f"账号: {config.account_name}")
  3841. print(f"输出版本: {config.output_version}")
  3842. print()
  3843. # 输入目录
  3844. match_graph_dir = config.intermediate_dir / "match_graph"
  3845. # 输出文件
  3846. output_file = config.intermediate_dir / "match_graph.html"
  3847. print(f"输入目录: {match_graph_dir}")
  3848. print(f"输出文件: {output_file}")
  3849. print()
  3850. # 读取人设树中间数据
  3851. persona_tree_file = config.intermediate_dir / "persona_tree.json"
  3852. persona_tree_data = {"nodes": [], "edges": []}
  3853. if persona_tree_file.exists():
  3854. print(f"读取人设树数据: {persona_tree_file.name}")
  3855. with open(persona_tree_file, "r", encoding="utf-8") as f:
  3856. tree_data = json.load(f)
  3857. persona_tree_data["nodes"] = tree_data.get("nodes", [])
  3858. persona_tree_data["edges"] = tree_data.get("edges", [])
  3859. category_count = len([n for n in persona_tree_data["nodes"] if n.get("节点类型") == "分类"])
  3860. tag_count = len([n for n in persona_tree_data["nodes"] if n.get("节点类型") == "标签"])
  3861. print(f" 分类节点: {category_count}, 标签节点: {tag_count}")
  3862. print(f" 边数: {len(persona_tree_data['edges'])}")
  3863. print()
  3864. # 读取帖子树数据
  3865. post_trees_file = match_graph_dir / "post_trees.json"
  3866. post_trees_data = {} # postId -> postTree
  3867. if post_trees_file.exists():
  3868. print(f"读取帖子树数据: {post_trees_file.name}")
  3869. with open(post_trees_file, "r", encoding="utf-8") as f:
  3870. trees_data = json.load(f)
  3871. for tree in trees_data.get("postTrees", []):
  3872. post_trees_data[tree["postId"]] = tree
  3873. print(f" 帖子树数量: {len(post_trees_data)}")
  3874. else:
  3875. print(f"警告: 帖子树数据文件不存在: {post_trees_file}")
  3876. print(" 请先运行 build_post_tree.py 生成帖子树数据")
  3877. print()
  3878. # 读取所有匹配图谱文件
  3879. graph_files = sorted(match_graph_dir.glob("*_match_graph.json"))
  3880. print(f"找到 {len(graph_files)} 个匹配图谱文件")
  3881. # results目录(存放完整帖子详情)
  3882. results_dir = config.intermediate_dir.parent / "results"
  3883. all_graph_data = []
  3884. for i, graph_file in enumerate(graph_files, 1):
  3885. print(f" [{i}/{len(graph_files)}] 读取: {graph_file.name}")
  3886. with open(graph_file, "r", encoding="utf-8") as f:
  3887. match_graph_data = json.load(f)
  3888. post_id = match_graph_data["说明"]["帖子ID"]
  3889. # 尝试读取完整帖子详情
  3890. post_detail = {
  3891. "title": match_graph_data["说明"].get("帖子标题", ""),
  3892. "post_id": post_id
  3893. }
  3894. how_file = results_dir / f"{post_id}_how.json"
  3895. if how_file.exists():
  3896. with open(how_file, "r", encoding="utf-8") as f:
  3897. how_data = json.load(f)
  3898. if "帖子详情" in how_data:
  3899. post_detail = how_data["帖子详情"]
  3900. post_detail["post_id"] = post_id
  3901. # 获取预构建的帖子树数据
  3902. post_tree = post_trees_data.get(post_id, {})
  3903. # 提取需要的数据
  3904. graph_data = {
  3905. "postId": post_id,
  3906. "postTitle": match_graph_data["说明"].get("帖子标题", ""),
  3907. "stats": match_graph_data["说明"]["统计"],
  3908. "nodes": match_graph_data["节点列表"],
  3909. "edges": match_graph_data["边列表"],
  3910. "personaEdgeToMirrorEdges": match_graph_data.get("人设边到镜像边映射", {}),
  3911. # 预构建的帖子树数据
  3912. "postTree": post_tree,
  3913. "postDetail": post_tree.get("postDetail", post_detail)
  3914. }
  3915. all_graph_data.append(graph_data)
  3916. # 生成HTML
  3917. print("\n生成HTML文件...")
  3918. generate_combined_html(all_graph_data, persona_tree_data, output_file)
  3919. print("\n" + "="*60)
  3920. print("处理完成!")
  3921. print(f"输出文件: {output_file}")
  3922. if __name__ == "__main__":
  3923. main()