visualize_match_graph.py 151 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689
  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. </style>
  750. </head>
  751. <body>
  752. <div id="container">
  753. <div class="tabs" id="tabs">
  754. {tabs_html}
  755. </div>
  756. <div class="main-content">
  757. <div id="left-panel">
  758. <div id="tree-container"></div>
  759. <div id="ego-container">
  760. <div class="ego-controls">
  761. <div class="cascade-dropdown">
  762. <div class="cascade-btn" onclick="toggleCascadeMenu()">
  763. <span id="cascade-label">1级</span>
  764. </div>
  765. <div class="cascade-menu" id="cascade-menu">
  766. <div class="cascade-levels">
  767. <div class="cascade-level-item active" data-level="1" onclick="selectLevel(1)">1级</div>
  768. <div class="cascade-level-item" data-level="2" onclick="selectLevel(2)">2级</div>
  769. <div class="cascade-level-item" data-level="3" onclick="selectLevel(3)">3级</div>
  770. </div>
  771. <div class="cascade-edges">
  772. <div class="cascade-edge-group active" data-level="1">
  773. <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>
  774. <label class="cascade-edge-item"><input type="checkbox" data-level="1" data-type="属于" checked><span class="edge-color" style="background:#9b59b6"></span>属于</label>
  775. <label class="cascade-edge-item"><input type="checkbox" data-level="1" data-type="包含" checked><span class="edge-color" style="background:#ffb6c1"></span>包含</label>
  776. <label class="cascade-edge-item"><input type="checkbox" data-level="1" data-type="分类共现(跨点)" checked><span class="edge-color" style="background:#2ecc71"></span>跨点共现</label>
  777. <label class="cascade-edge-item"><input type="checkbox" data-level="1" data-type="分类共现(点内)" checked><span class="edge-color" style="background:#3498db"></span>点内共现</label>
  778. <label class="cascade-edge-item"><input type="checkbox" data-level="1" data-type="标签共现" checked><span class="edge-color" style="background:#f39c12"></span>标签共现</label>
  779. </div>
  780. <div class="cascade-edge-group" data-level="2">
  781. <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>
  782. <label class="cascade-edge-item"><input type="checkbox" data-level="2" data-type="属于"><span class="edge-color" style="background:#9b59b6"></span>属于</label>
  783. <label class="cascade-edge-item"><input type="checkbox" data-level="2" data-type="包含" checked><span class="edge-color" style="background:#ffb6c1"></span>包含</label>
  784. <label class="cascade-edge-item"><input type="checkbox" data-level="2" data-type="分类共现(跨点)"><span class="edge-color" style="background:#2ecc71"></span>跨点共现</label>
  785. <label class="cascade-edge-item"><input type="checkbox" data-level="2" data-type="分类共现(点内)"><span class="edge-color" style="background:#3498db"></span>点内共现</label>
  786. <label class="cascade-edge-item"><input type="checkbox" data-level="2" data-type="标签共现"><span class="edge-color" style="background:#f39c12"></span>标签共现</label>
  787. </div>
  788. <div class="cascade-edge-group" data-level="3">
  789. <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>
  790. <label class="cascade-edge-item"><input type="checkbox" data-level="3" data-type="属于"><span class="edge-color" style="background:#9b59b6"></span>属于</label>
  791. <label class="cascade-edge-item"><input type="checkbox" data-level="3" data-type="包含" checked><span class="edge-color" style="background:#ffb6c1"></span>包含</label>
  792. <label class="cascade-edge-item"><input type="checkbox" data-level="3" data-type="分类共现(跨点)"><span class="edge-color" style="background:#2ecc71"></span>跨点共现</label>
  793. <label class="cascade-edge-item"><input type="checkbox" data-level="3" data-type="分类共现(点内)"><span class="edge-color" style="background:#3498db"></span>点内共现</label>
  794. <label class="cascade-edge-item"><input type="checkbox" data-level="3" data-type="标签共现"><span class="edge-color" style="background:#f39c12"></span>标签共现</label>
  795. </div>
  796. </div>
  797. </div>
  798. </div>
  799. <div class="ego-title-center" id="ego-node-name"></div>
  800. <div class="ego-stats" id="ego-stats"></div>
  801. </div>
  802. </div>
  803. </div>
  804. <div id="graph">
  805. <div class="tooltip" id="tooltip"></div>
  806. </div>
  807. <div id="sidebar">
  808. <h1>匹配图谱</h1>
  809. <div class="match-list-panel">
  810. <h3>匹配关系 <span id="matchCount">(0)</span></h3>
  811. <div id="matchList" class="match-list"></div>
  812. </div>
  813. <div class="detail-panel active" id="detailPanel">
  814. <h3 id="detailTitle">点击节点或边查看详情</h3>
  815. <div id="detailContent">
  816. <p style="color: #888; font-size: 11px;">点击图中的节点或边,这里会显示详细信息</p>
  817. </div>
  818. </div>
  819. <div class="legend">
  820. <h2>节点</h2>
  821. <div class="legend-grid">
  822. <div class="legend-item">
  823. <div class="legend-color" style="background: #f39c12; border: 2px solid #fff;"></div>
  824. <span>灵感点</span>
  825. </div>
  826. <div class="legend-item">
  827. <div class="legend-color" style="background: #3498db; border: 2px solid #fff;"></div>
  828. <span>目的点</span>
  829. </div>
  830. <div class="legend-item">
  831. <div class="legend-color" style="background: #9b59b6; border: 2px solid #fff;"></div>
  832. <span>关键点</span>
  833. </div>
  834. </div>
  835. <h2>边</h2>
  836. <div class="legend-grid">
  837. <div class="legend-item">
  838. <div class="legend-line" style="background: #e94560;"></div>
  839. <span>相同(≥0.8)</span>
  840. </div>
  841. <div class="legend-item">
  842. <div class="legend-line" style="background: linear-gradient(90deg, #e94560 0%, #e94560 40%, transparent 40%, transparent 60%, #e94560 60%);"></div>
  843. <span>相似(0.5-0.8)</span>
  844. </div>
  845. <div class="legend-item">
  846. <div class="legend-line" style="background: #9b59b6;"></div>
  847. <span>属于</span>
  848. </div>
  849. <div class="legend-item">
  850. <div class="legend-line" style="background: #2ecc71;"></div>
  851. <span>分类共现(跨)</span>
  852. </div>
  853. <div class="legend-item">
  854. <div class="legend-line" style="background: #3498db;"></div>
  855. <span>分类共现(内)</span>
  856. </div>
  857. <div class="legend-item">
  858. <div class="legend-line" style="background: #f39c12;"></div>
  859. <span>标签共现</span>
  860. </div>
  861. </div>
  862. </div>
  863. <div class="controls">
  864. <div class="control-label">视图控制</div>
  865. <button onclick="resetZoom()">重置视图</button>
  866. <button onclick="toggleLabels()">切换标签</button>
  867. <button onclick="toggleCrossLayerEdges()" id="crossLayerBtn">显示跨层边</button>
  868. <div class="control-group">
  869. <div class="control-label">人设树配置</div>
  870. <button onclick="toggleTreeTags()" id="treeTagBtn" class="active">显示标签</button>
  871. <select id="treeDepthSelect" onchange="setTreeDepth(this.value)">
  872. <option value="0">全部层级</option>
  873. <option value="2">2层</option>
  874. <option value="3">3层</option>
  875. <option value="4">4层</option>
  876. <option value="5">5层</option>
  877. </select>
  878. </div>
  879. </div>
  880. </div>
  881. </div>
  882. </div>
  883. <script>
  884. // 所有帖子的图谱数据
  885. const allGraphData = {all_graph_data};
  886. // 完整的人设树数据(所有人设节点和属于边)
  887. const personaTreeData = {persona_tree_data};
  888. // 当前选中的帖子索引
  889. let currentIndex = 0;
  890. let simulation = null;
  891. let svg = null;
  892. let g = null;
  893. let treeSvg = null; // 人设树独立SVG
  894. let treeG = null; // 人设树group
  895. let egoSvg = null; // 关系图独立SVG
  896. let egoG = null; // 关系图group
  897. let zoom = null;
  898. let showLabels = true;
  899. let showCrossLayerEdges = false; // 跨层边默认隐藏
  900. let isCrossLayerEdge = null; // 跨层边判断函数(在renderGraph中设置)
  901. // 人设树配置
  902. let showTreeTags = true; // 是否显示标签节点
  903. let treeMaxDepth = 0; // 显示的最大层数(0=全部)
  904. // 切换标签显示
  905. function toggleTreeTags() {{
  906. showTreeTags = !showTreeTags;
  907. const btn = document.getElementById("treeTagBtn");
  908. btn.textContent = showTreeTags ? "显示标签" : "隐藏标签";
  909. btn.classList.toggle("active", showTreeTags);
  910. // 重新渲染当前图谱
  911. renderGraph(allGraphData[currentIndex]);
  912. }}
  913. // 设置树的显示层数
  914. function setTreeDepth(depth) {{
  915. treeMaxDepth = parseInt(depth);
  916. // 重新渲染当前图谱
  917. renderGraph(allGraphData[currentIndex]);
  918. }}
  919. // 初始化
  920. function init() {{
  921. const container = document.getElementById("graph");
  922. const treeContainer = document.getElementById("tree-container");
  923. const width = container.clientWidth;
  924. const height = container.clientHeight;
  925. // 创建圆形层SVG
  926. svg = d3.select("#graph")
  927. .append("svg")
  928. .attr("width", width)
  929. .attr("height", height);
  930. g = svg.append("g");
  931. zoom = d3.zoom()
  932. .scaleExtent([0.1, 4])
  933. .on("zoom", (event) => {{
  934. g.attr("transform", event.transform);
  935. }});
  936. svg.call(zoom);
  937. // 创建人设树SVG(独立可滚动)
  938. treeSvg = d3.select("#tree-container")
  939. .append("svg")
  940. .attr("width", 400);
  941. treeG = treeSvg.append("g");
  942. // 创建关系图SVG(在独立的ego-container中)
  943. egoSvg = d3.select("#ego-container")
  944. .append("svg")
  945. .attr("width", 400)
  946. .attr("height", 400);
  947. egoG = egoSvg.append("g");
  948. // 关系图缩放
  949. const egoZoom = d3.zoom()
  950. .scaleExtent([0.3, 3])
  951. .on("zoom", (event) => {{
  952. egoG.attr("transform", event.transform);
  953. }});
  954. egoSvg.call(egoZoom);
  955. // 绑定Tab点击事件
  956. document.querySelectorAll(".tab").forEach((tab, index) => {{
  957. tab.addEventListener("click", () => switchTab(index));
  958. }});
  959. // 绑定关系图控制面板事件
  960. // 全选复选框事件
  961. document.querySelectorAll('.select-all input').forEach(cb => {{
  962. cb.addEventListener('change', (e) => {{
  963. const level = e.target.dataset.level;
  964. const checked = e.target.checked;
  965. // 设置该层级所有边类型复选框
  966. document.querySelectorAll(`.cascade-edge-item input[data-level="${{level}}"]`).forEach(item => {{
  967. item.checked = checked;
  968. }});
  969. // 重新渲染关系图和人设树高亮
  970. if (currentEgoCenterNodeId) {{
  971. handleNodeClick(currentEgoCenterNodeId, currentEgoCenterNodeName);
  972. }}
  973. }});
  974. }});
  975. // 边类型复选框变化事件
  976. document.querySelectorAll('.cascade-edge-item input').forEach(cb => {{
  977. cb.addEventListener('change', (e) => {{
  978. // 更新全选复选框状态
  979. const level = e.target.dataset.level;
  980. const allItems = document.querySelectorAll(`.cascade-edge-item input[data-level="${{level}}"]`);
  981. const checkedItems = document.querySelectorAll(`.cascade-edge-item input[data-level="${{level}}"]:checked`);
  982. const selectAllCb = document.querySelector(`.select-all input[data-level="${{level}}"]`);
  983. selectAllCb.checked = allItems.length === checkedItems.length;
  984. // 重新渲染关系图和人设树高亮
  985. if (currentEgoCenterNodeId) {{
  986. handleNodeClick(currentEgoCenterNodeId, currentEgoCenterNodeName);
  987. }}
  988. }});
  989. }});
  990. // 点击页面其他地方关闭级联菜单
  991. document.addEventListener('click', (e) => {{
  992. if (!e.target.closest('.cascade-dropdown')) {{
  993. document.getElementById('cascade-menu').classList.remove('show');
  994. }}
  995. }});
  996. // 显示第一个帖子
  997. switchTab(0);
  998. }}
  999. // 构建人设树数据(合并为一棵树,根节点为"人设")
  1000. // showTreeTags: 控制是否显示标签节点
  1001. // treeMaxDepth: 控制树的显示深度(0=全部,2=维度,3=+一层,4=+两层...)
  1002. function buildPersonaTreeData() {{
  1003. const dimensions = ["灵感点", "目的点", "关键点"];
  1004. const dimColors = {{ "灵感点": "#f39c12", "目的点": "#3498db", "关键点": "#9b59b6" }};
  1005. const dimensionChildren = [];
  1006. let totalNodeCount = 0;
  1007. dimensions.forEach(dim => {{
  1008. // 根据 showTreeTags 过滤节点(独立于深度控制)
  1009. let dimNodes = personaTreeData.nodes.filter(n => n.节点层级 === dim);
  1010. if (!showTreeTags) {{
  1011. dimNodes = dimNodes.filter(n => n.节点类型 !== "标签");
  1012. }}
  1013. if (dimNodes.length === 0) {{
  1014. const dimNode = {{
  1015. name: dim,
  1016. 节点名称: dim,
  1017. isDimension: true,
  1018. dimColor: dimColors[dim],
  1019. children: []
  1020. }};
  1021. dimensionChildren.push(dimNode);
  1022. return;
  1023. }}
  1024. const nodeMap = {{}};
  1025. dimNodes.forEach(n => nodeMap[n.节点ID] = {{ ...n, name: n.节点名称, children: [], dimColor: dimColors[dim] }});
  1026. // 只用属于边构建父子关系
  1027. const hierarchyEdgeTypes = ["属于"];
  1028. const hasParent = new Set();
  1029. personaTreeData.edges.forEach(e => {{
  1030. if (!hierarchyEdgeTypes.includes(e.边类型)) return; // 跳过非层级边
  1031. const srcNode = nodeMap[e.源节点ID];
  1032. const tgtNode = nodeMap[e.目标节点ID];
  1033. if (srcNode && tgtNode) {{
  1034. tgtNode.children.push(srcNode);
  1035. hasParent.add(e.源节点ID);
  1036. }}
  1037. }});
  1038. const roots = dimNodes.filter(n => !hasParent.has(n.节点ID)).map(n => nodeMap[n.节点ID]);
  1039. const dimNode = {{
  1040. name: dim,
  1041. 节点名称: dim,
  1042. isDimension: true,
  1043. dimColor: dimColors[dim],
  1044. children: roots
  1045. }};
  1046. dimensionChildren.push(dimNode);
  1047. totalNodeCount += dimNodes.length;
  1048. }});
  1049. // 根节点"人设"
  1050. const rootNode = {{
  1051. name: "人设",
  1052. 节点名称: "人设",
  1053. isRoot: true,
  1054. children: dimensionChildren
  1055. }};
  1056. // 根据 treeMaxDepth 截断树深度(0=全部)
  1057. // 深度1=根,深度2=维度,深度3+=子节点
  1058. if (treeMaxDepth > 0) {{
  1059. truncateTree(rootNode, 1, treeMaxDepth);
  1060. }}
  1061. return {{ root: rootNode, nodeCount: totalNodeCount }};
  1062. }}
  1063. // 递归截断树的深度
  1064. function truncateTree(node, currentDepth, maxDepth) {{
  1065. if (currentDepth >= maxDepth) {{
  1066. node.children = [];
  1067. return;
  1068. }}
  1069. if (node.children) {{
  1070. node.children.forEach(child => truncateTree(child, currentDepth + 1, maxDepth));
  1071. }}
  1072. }}
  1073. // 切换Tab
  1074. function switchTab(index) {{
  1075. currentIndex = index;
  1076. // 更新Tab样式
  1077. document.querySelectorAll(".tab").forEach((tab, i) => {{
  1078. tab.classList.toggle("active", i === index);
  1079. }});
  1080. // 更新图谱
  1081. renderGraph(allGraphData[index]);
  1082. }}
  1083. // 渲染图谱
  1084. function renderGraph(data) {{
  1085. // 清空现有图谱
  1086. g.selectAll("*").remove();
  1087. treeG.selectAll("*").remove();
  1088. if (simulation) {{
  1089. simulation.stop();
  1090. }}
  1091. const container = document.getElementById("graph");
  1092. const width = container.clientWidth;
  1093. // 布局配置:人设树在左侧独立容器,右侧是圆形层
  1094. const treeAreaWidth = 400; // 固定树宽度
  1095. const circleAreaWidth = width - 40;
  1096. const circleAreaCenterX = circleAreaWidth / 2;
  1097. // 准备数据
  1098. const nodes = data.nodes.map(n => ({{
  1099. ...n,
  1100. id: n.节点ID,
  1101. source: n.节点ID.startsWith("帖子_") ? "帖子" : "人设",
  1102. level: n.节点层级
  1103. }}));
  1104. const links = data.edges.map(e => ({{
  1105. ...e,
  1106. source: e.源节点ID,
  1107. target: e.目标节点ID,
  1108. type: e.边类型
  1109. }}));
  1110. // 分离节点类型
  1111. const postNodes = nodes.filter(n => n.source === "帖子");
  1112. const personaNodes = nodes.filter(n => n.source === "人设" && !n.是否扩展);
  1113. const expandedNodes = nodes.filter(n => n.source === "人设" && n.是否扩展);
  1114. const matchLinks = links.filter(l => l.type.startsWith("匹配_"));
  1115. // 更新匹配列表(按分数降序)
  1116. updateMatchList(matchLinks, nodes);
  1117. // 构建帖子节点到人设节点的映射
  1118. const postToPersona = {{}};
  1119. const personaToPost = {{}};
  1120. matchLinks.forEach(l => {{
  1121. const sid = typeof l.source === "object" ? l.source.id : l.source;
  1122. const tid = typeof l.target === "object" ? l.target.id : l.target;
  1123. if (!postToPersona[sid]) postToPersona[sid] = [];
  1124. postToPersona[sid].push(tid);
  1125. if (!personaToPost[tid]) personaToPost[tid] = [];
  1126. personaToPost[tid].push(sid);
  1127. }});
  1128. // 找出所有连通分量
  1129. function findConnectedComponents(nodes, links) {{
  1130. const nodeIds = new Set(nodes.map(n => n.id));
  1131. const adj = {{}};
  1132. nodeIds.forEach(id => adj[id] = []);
  1133. links.forEach(l => {{
  1134. const sid = typeof l.source === "object" ? l.source.id : l.source;
  1135. const tid = typeof l.target === "object" ? l.target.id : l.target;
  1136. if (nodeIds.has(sid) && nodeIds.has(tid)) {{
  1137. adj[sid].push(tid);
  1138. adj[tid].push(sid);
  1139. }}
  1140. }});
  1141. const visited = new Set();
  1142. const components = [];
  1143. nodeIds.forEach(startId => {{
  1144. if (visited.has(startId)) return;
  1145. const component = [];
  1146. const queue = [startId];
  1147. while (queue.length > 0) {{
  1148. const id = queue.shift();
  1149. if (visited.has(id)) continue;
  1150. visited.add(id);
  1151. component.push(id);
  1152. adj[id].forEach(neighbor => {{
  1153. if (!visited.has(neighbor)) queue.push(neighbor);
  1154. }});
  1155. }}
  1156. components.push(component);
  1157. }});
  1158. return components;
  1159. }}
  1160. // 按大小排序连通分量(大的在前)
  1161. const components = findConnectedComponents(nodes, links)
  1162. .sort((a, b) => b.length - a.length);
  1163. console.log(`找到 ${{components.length}} 个连通分量`);
  1164. // 为每个节点分配连通分量ID和分量内的X范围
  1165. const nodeToComponent = {{}};
  1166. const componentCenters = {{}};
  1167. const componentBounds = {{}};
  1168. const padding = 50; // 分量之间的间距
  1169. const totalPadding = padding * (components.length - 1);
  1170. const availableWidth = width - totalPadding - 100; // 留边距
  1171. // 根据分量大小分配宽度
  1172. const totalNodes = nodes.length;
  1173. let currentX = 50; // 起始边距
  1174. components.forEach((comp, i) => {{
  1175. const compWidth = Math.max(150, (comp.length / totalNodes) * availableWidth);
  1176. const centerX = currentX + compWidth / 2;
  1177. componentCenters[i] = centerX;
  1178. componentBounds[i] = {{ start: currentX, end: currentX + compWidth, width: compWidth }};
  1179. comp.forEach(nodeId => {{
  1180. nodeToComponent[nodeId] = i;
  1181. }});
  1182. currentX += compWidth + padding;
  1183. }});
  1184. // 使用重心法(Barycenter)减少边交叉
  1185. // 迭代优化:交替调整两层节点的顺序
  1186. const nodeTargetX = {{}};
  1187. const personaXMap = {{}};
  1188. // 对每个连通分量单独处理
  1189. components.forEach((comp, compIdx) => {{
  1190. const bounds = componentBounds[compIdx];
  1191. const compPostNodes = postNodes.filter(n => nodeToComponent[n.id] === compIdx);
  1192. const compPersonaNodes = personaNodes.filter(n => nodeToComponent[n.id] === compIdx);
  1193. if (compPostNodes.length === 0 || compPersonaNodes.length === 0) {{
  1194. // 没有匹配关系的分量,均匀分布
  1195. const spacing = bounds.width / (comp.length + 1);
  1196. comp.forEach((nodeId, i) => {{
  1197. const node = nodes.find(n => n.id === nodeId);
  1198. if (node) {{
  1199. node.x = bounds.start + spacing * (i + 1);
  1200. nodeTargetX[nodeId] = node.x;
  1201. if (node.source === "人设") personaXMap[nodeId] = node.x;
  1202. }}
  1203. }});
  1204. return;
  1205. }}
  1206. // 初始化:给人设节点一个初始顺序
  1207. let personaOrder = compPersonaNodes.map((n, i) => ({{ node: n, order: i }}));
  1208. // 迭代优化(3轮)
  1209. for (let iter = 0; iter < 3; iter++) {{
  1210. // 1. 根据人设节点位置,计算帖子节点的重心
  1211. const postBarycenter = {{}};
  1212. compPostNodes.forEach(pn => {{
  1213. const matched = postToPersona[pn.id] || [];
  1214. if (matched.length > 0) {{
  1215. const avgOrder = matched.reduce((sum, pid) => {{
  1216. const po = personaOrder.find(p => p.node.id === pid);
  1217. return sum + (po ? po.order : 0);
  1218. }}, 0) / matched.length;
  1219. postBarycenter[pn.id] = avgOrder;
  1220. }} else {{
  1221. postBarycenter[pn.id] = 0;
  1222. }}
  1223. }});
  1224. // 按重心排序帖子节点
  1225. const sortedPosts = [...compPostNodes].sort((a, b) =>
  1226. postBarycenter[a.id] - postBarycenter[b.id]
  1227. );
  1228. // 2. 根据帖子节点位置,重新计算人设节点的重心
  1229. const personaBarycenter = {{}};
  1230. compPersonaNodes.forEach(pn => {{
  1231. const matched = personaToPost[pn.id] || [];
  1232. if (matched.length > 0) {{
  1233. const avgOrder = matched.reduce((sum, pid) => {{
  1234. const idx = sortedPosts.findIndex(p => p.id === pid);
  1235. return sum + (idx >= 0 ? idx : 0);
  1236. }}, 0) / matched.length;
  1237. personaBarycenter[pn.id] = avgOrder;
  1238. }} else {{
  1239. personaBarycenter[pn.id] = personaOrder.find(p => p.node.id === pn.id)?.order || 0;
  1240. }}
  1241. }});
  1242. // 更新人设节点顺序
  1243. personaOrder = compPersonaNodes
  1244. .map(n => ({{ node: n, order: personaBarycenter[n.id] }}))
  1245. .sort((a, b) => a.order - b.order)
  1246. .map((item, i) => ({{ node: item.node, order: i }}));
  1247. }}
  1248. // 最终排序
  1249. const finalPersonaOrder = personaOrder.map(p => p.node);
  1250. const postBarycenter = {{}};
  1251. compPostNodes.forEach(pn => {{
  1252. const matched = postToPersona[pn.id] || [];
  1253. if (matched.length > 0) {{
  1254. const avgOrder = matched.reduce((sum, pid) => {{
  1255. const idx = finalPersonaOrder.findIndex(n => n.id === pid);
  1256. return sum + (idx >= 0 ? idx : 0);
  1257. }}, 0) / matched.length;
  1258. postBarycenter[pn.id] = avgOrder;
  1259. }} else {{
  1260. postBarycenter[pn.id] = 0;
  1261. }}
  1262. }});
  1263. const finalPostOrder = [...compPostNodes].sort((a, b) =>
  1264. postBarycenter[a.id] - postBarycenter[b.id]
  1265. );
  1266. // 设置位置
  1267. const personaSpacing = bounds.width / (finalPersonaOrder.length + 1);
  1268. finalPersonaOrder.forEach((n, i) => {{
  1269. n.x = bounds.start + personaSpacing * (i + 1);
  1270. nodeTargetX[n.id] = n.x;
  1271. personaXMap[n.id] = n.x;
  1272. }});
  1273. const postSpacing = bounds.width / (finalPostOrder.length + 1);
  1274. finalPostOrder.forEach((n, i) => {{
  1275. // 帖子节点用重心位置(匹配人设的平均X)
  1276. const matched = postToPersona[n.id] || [];
  1277. if (matched.length > 0) {{
  1278. const avgX = matched.reduce((sum, pid) => sum + (personaXMap[pid] || bounds.start + bounds.width/2), 0) / matched.length;
  1279. n.x = avgX;
  1280. }} else {{
  1281. n.x = bounds.start + postSpacing * (i + 1);
  1282. }}
  1283. nodeTargetX[n.id] = n.x;
  1284. }});
  1285. }});
  1286. // 节点颜色
  1287. const levelColors = {{
  1288. "灵感点": "#f39c12",
  1289. "目的点": "#3498db",
  1290. "关键点": "#9b59b6"
  1291. }};
  1292. // 获取节点的层级编号(三层结构)
  1293. function getNodeLayer(d) {{
  1294. if (d.source === "帖子") {{
  1295. return d.节点类型 === "点" ? 0 : 1; // 点=0, 标签=1
  1296. }}
  1297. return 2; // 人设(标签+分类)都在层2
  1298. }}
  1299. // 统计每层节点数量(三层结构)
  1300. const layerCounts = {{0: 0, 1: 0, 2: 0}};
  1301. nodes.forEach(n => {{
  1302. const layer = getNodeLayer(n);
  1303. layerCounts[layer]++;
  1304. }});
  1305. console.log("每层节点数:", layerCounts);
  1306. // 根据节点数量计算每层圆的半径
  1307. // 左列:帖子标签(上) + 人设匹配(下),右列:帖子点(同一行开始)
  1308. // 左列是主要展示区域,视图中心对准左列
  1309. const minRadius = 80;
  1310. const maxRadius = Math.min(circleAreaWidth / 3 - 20, 180);
  1311. const nodeSpacing = 60;
  1312. function calcRadius(nodeCount) {{
  1313. if (nodeCount <= 1) return minRadius;
  1314. const circumference = nodeCount * nodeSpacing;
  1315. const r = circumference / (2 * Math.PI);
  1316. return Math.max(minRadius, Math.min(maxRadius, r));
  1317. }}
  1318. const layerRadius = {{
  1319. 0: calcRadius(layerCounts[0]), // 帖子点(右列)
  1320. 1: calcRadius(layerCounts[1]), // 帖子标签(左上)
  1321. 2: calcRadius(layerCounts[2]) // 人设匹配(左下)
  1322. }};
  1323. console.log("每层半径:", layerRadius);
  1324. // 获取人设树数据(单棵树)
  1325. const personaTree = buildPersonaTreeData();
  1326. // 树高度自适应:根据节点数量,每个节点约12px,最小800
  1327. const treeHeight = Math.max(800, personaTree.nodeCount * 12 + 150);
  1328. // 关系图配置(放在树下方)
  1329. const egoRadius = 180;
  1330. const egoAreaHeight = egoRadius * 2 + 80;
  1331. // 计算布局:左列(帖子标签+人设匹配),右列(帖子点)
  1332. const layerPadding = 40;
  1333. const leftColHeight = layerRadius[1] * 2 + layerPadding + layerRadius[2] * 2 + layerPadding;
  1334. const circleHeight = leftColHeight;
  1335. const height = Math.max(circleHeight + 80, treeHeight + 80, container.clientHeight);
  1336. // 计算每层圆心坐标
  1337. const layerCenterX = {{}};
  1338. const layerCenterY = {{}};
  1339. // 左列居中显示,右列在旁边
  1340. const leftColX = circleAreaCenterX; // 左列居中
  1341. const rightColX = leftColX + Math.max(layerRadius[1], layerRadius[2]) + layerPadding + layerRadius[0] + 30; // 右列在右边
  1342. // 左列:帖子标签(上)+ 人设匹配(下)
  1343. layerCenterX[1] = leftColX;
  1344. layerCenterY[1] = layerRadius[1] + layerPadding / 2 + 20;
  1345. layerCenterX[2] = leftColX;
  1346. layerCenterY[2] = layerCenterY[1] + layerRadius[1] + layerPadding + layerRadius[2];
  1347. // 右列:帖子点(与帖子标签同一行开始)
  1348. layerCenterX[0] = rightColX;
  1349. layerCenterY[0] = layerCenterY[1]; // 与帖子标签同一行
  1350. console.log("每层圆心X:", layerCenterX);
  1351. console.log("每层圆心Y:", layerCenterY);
  1352. // 更新SVG高度
  1353. svg.attr("height", height);
  1354. // 获取节点的基准Y(层圆心)
  1355. function getNodeBaseY(d) {{
  1356. const layer = getNodeLayer(d);
  1357. return layerCenterY[layer];
  1358. }}
  1359. // 获取节点的基准X(层圆心)
  1360. function getNodeBaseX(d) {{
  1361. const layer = getNodeLayer(d);
  1362. return layerCenterX[layer];
  1363. }}
  1364. // 层边界配置(不再使用)
  1365. const layerBounds = {{}};
  1366. // 自定义层内排斥力(只对同层节点生效,尽量分散)
  1367. function forceIntraLayerRepulsion(strength) {{
  1368. let nodes;
  1369. function force(alpha) {{
  1370. for (let i = 0; i < nodes.length; i++) {{
  1371. const nodeA = nodes[i];
  1372. const layerA = getNodeLayer(nodeA);
  1373. for (let j = i + 1; j < nodes.length; j++) {{
  1374. const nodeB = nodes[j];
  1375. const layerB = getNodeLayer(nodeB);
  1376. // 只对同层节点施加排斥力
  1377. if (layerA !== layerB) continue;
  1378. const dx = nodeB.x - nodeA.x;
  1379. const dy = nodeB.y - nodeA.y;
  1380. const dist = Math.sqrt(dx * dx + dy * dy) || 1;
  1381. const minDist = 150; // 增大最小距离,让节点更分散
  1382. if (dist < minDist) {{
  1383. // 排斥力随距离衰减,但基础强度更大
  1384. const pushStrength = strength * alpha * (minDist - dist) / dist * 2;
  1385. const px = dx * pushStrength;
  1386. const py = dy * pushStrength;
  1387. nodeA.vx -= px;
  1388. nodeA.vy -= py;
  1389. nodeB.vx += px;
  1390. nodeB.vy += py;
  1391. }}
  1392. }}
  1393. }}
  1394. }}
  1395. force.initialize = function(_) {{
  1396. nodes = _;
  1397. }};
  1398. return force;
  1399. }}
  1400. // 层圆的半径(使用动态计算的 layerRadius)
  1401. // layerRadius 和 layerCenterY 已在前面定义
  1402. // 层边界约束力(把节点限制在层内)
  1403. function forceLayerBoundary() {{
  1404. let nodes;
  1405. function force(alpha) {{
  1406. nodes.forEach(node => {{
  1407. const layer = getNodeLayer(node);
  1408. const centerX = layerCenterX[layer];
  1409. const centerY = layerCenterY[layer];
  1410. // 使用圆形边界
  1411. const maxRadius = layerRadius[layer] - 15;
  1412. // 计算到圆心的距离
  1413. const dx = node.x - centerX;
  1414. const dy = node.y - centerY;
  1415. const dist = Math.sqrt(dx * dx + dy * dy);
  1416. // 如果超出圆形边界,拉回来
  1417. if (dist > maxRadius) {{
  1418. const scale = maxRadius / dist;
  1419. node.x = centerX + dx * scale;
  1420. node.y = centerY + dy * scale;
  1421. // 阻止继续向外运动
  1422. const angle = Math.atan2(dy, dx);
  1423. const vOutward = node.vx * Math.cos(angle) + node.vy * Math.sin(angle);
  1424. if (vOutward > 0) {{
  1425. node.vx -= vOutward * Math.cos(angle);
  1426. node.vy -= vOutward * Math.sin(angle);
  1427. }}
  1428. }}
  1429. }});
  1430. }}
  1431. force.initialize = function(_) {{
  1432. nodes = _;
  1433. }};
  1434. return force;
  1435. }}
  1436. // 层内圆形布局力(让同层节点围绕圆心分布)
  1437. function forceCircularLayout(strength) {{
  1438. let nodes;
  1439. function force(alpha) {{
  1440. // 按层分组(三层)
  1441. const layerNodes = {{0: [], 1: [], 2: []}};
  1442. nodes.forEach(node => {{
  1443. const layer = getNodeLayer(node);
  1444. layerNodes[layer].push(node);
  1445. }});
  1446. // 对每层计算布局
  1447. Object.entries(layerNodes).forEach(([layerIdx, layerGroup]) => {{
  1448. if (layerGroup.length === 0) return;
  1449. const layer = parseInt(layerIdx);
  1450. const centerX = layerCenterX[layer];
  1451. const centerY = layerCenterY[layer];
  1452. // 使用圆形布局
  1453. const nodeRadius = layerRadius[layer] - 20;
  1454. if (layerGroup.length === 1) {{
  1455. // 单个节点放在圆心
  1456. const node = layerGroup[0];
  1457. node.vx += (centerX - node.x) * strength * alpha;
  1458. node.vy += (centerY - node.y) * strength * alpha;
  1459. return;
  1460. }}
  1461. // 按角度排序节点(保持相对位置稳定)
  1462. layerGroup.forEach(node => {{
  1463. node._angle = Math.atan2(node.y - centerY, node.x - centerX);
  1464. }});
  1465. layerGroup.sort((a, b) => a._angle - b._angle);
  1466. // 均匀分布在圆周上
  1467. const angleStep = (2 * Math.PI) / layerGroup.length;
  1468. layerGroup.forEach((node, i) => {{
  1469. const angle = -Math.PI / 2 + i * angleStep; // 从顶部开始
  1470. const idealX = centerX + nodeRadius * Math.cos(angle);
  1471. const idealY = centerY + nodeRadius * Math.sin(angle);
  1472. node.vx += (idealX - node.x) * strength * alpha;
  1473. node.vy += (idealY - node.y) * strength * alpha;
  1474. }});
  1475. }});
  1476. }}
  1477. force.initialize = function(_) {{
  1478. nodes = _;
  1479. }};
  1480. return force;
  1481. }}
  1482. // 力导向模拟
  1483. simulation = d3.forceSimulation(nodes)
  1484. // 连线力(跨层连接)
  1485. .force("link", d3.forceLink(links).id(d => d.id)
  1486. .distance(d => {{
  1487. // 跨层连线距离
  1488. if (d.type.startsWith("匹配_") || d.type === "属于") {{
  1489. return 150; // 跨层边
  1490. }}
  1491. return 60; // 同层边
  1492. }})
  1493. .strength(d => {{
  1494. // 跨层边力度弱一些,不要拉扯节点出层
  1495. if (d.type.startsWith("匹配_") || d.type === "属于") {{
  1496. return 0.03;
  1497. }}
  1498. return 0.1;
  1499. }}))
  1500. // X方向:轻微拉向各层中心
  1501. .force("x", d3.forceX(d => getNodeBaseX(d)).strength(0.02))
  1502. // Y方向:轻微拉向层中心
  1503. .force("y", d3.forceY(d => getNodeBaseY(d)).strength(0.02))
  1504. // 层内碰撞检测
  1505. .force("collision", d3.forceCollide().radius(30))
  1506. // 层内排斥力(同层节点相互排斥)
  1507. .force("intraLayer", forceIntraLayerRepulsion(0.8))
  1508. // 层内布局(圆形或树状)
  1509. .force("circularLayout", forceCircularLayout(0.15))
  1510. // 层边界约束(节点不能跑出层,硬约束)
  1511. .force("boundary", forceLayerBoundary());
  1512. // 边类型到CSS类的映射
  1513. const edgeTypeClass = {{
  1514. "匹配_相同": "match-same",
  1515. "匹配_相似": "match-similar",
  1516. "分类共现(跨点)": "category-cross",
  1517. "分类共现(点内)": "category-intra",
  1518. "标签共现": "tag-cooccur",
  1519. "属于": "belong",
  1520. "包含": "contain",
  1521. // 镜像边(帖子节点之间,虚线)
  1522. "镜像_分类共现(跨点)": "mirror-category-cross",
  1523. "镜像_分类共现(点内)": "mirror-category-intra",
  1524. "镜像_标签共现": "mirror-tag-cooccur",
  1525. "镜像_属于": "mirror-belong",
  1526. "镜像_包含": "mirror-contain"
  1527. }};
  1528. // 获取边的CSS类(处理二阶边,映射到对应的镜像边样式)
  1529. function getEdgeClass(edgeType) {{
  1530. if (edgeTypeClass[edgeType]) return edgeTypeClass[edgeType];
  1531. // 二阶边映射到对应的镜像边样式(颜色相同,都用虚线)
  1532. if (edgeType.startsWith("二阶_")) {{
  1533. const originalType = edgeType.replace("二阶_", "");
  1534. const mirrorType = "镜像_" + originalType;
  1535. if (edgeTypeClass[mirrorType]) return edgeTypeClass[mirrorType];
  1536. }}
  1537. return "match";
  1538. }}
  1539. // 绘制层背景(圆形,使用动态大小)
  1540. const layerBg = g.append("g").attr("class", "layer-backgrounds");
  1541. // 层配置:名称、颜色(三层圆,关系图在左侧)
  1542. const layerConfig = [
  1543. {{ name: "帖子点", layer: 0, color: "rgba(243, 156, 18, 0.08)", stroke: "rgba(243, 156, 18, 0.3)" }},
  1544. {{ name: "帖子标签", layer: 1, color: "rgba(52, 152, 219, 0.08)", stroke: "rgba(52, 152, 219, 0.3)" }},
  1545. {{ name: "人设匹配", layer: 2, color: "rgba(155, 89, 182, 0.08)", stroke: "rgba(155, 89, 182, 0.3)" }}
  1546. ];
  1547. // 绘制三层圆形背景
  1548. layerConfig.forEach(cfg => {{
  1549. const cx = layerCenterX[cfg.layer];
  1550. const cy = layerCenterY[cfg.layer];
  1551. const r = layerRadius[cfg.layer];
  1552. layerBg.append("circle")
  1553. .attr("cx", cx)
  1554. .attr("cy", cy)
  1555. .attr("r", r)
  1556. .attr("fill", cfg.color)
  1557. .attr("stroke", cfg.stroke)
  1558. .attr("stroke-width", 2);
  1559. // 层标签(圆的左侧)
  1560. layerBg.append("text")
  1561. .attr("x", cx - r - 15)
  1562. .attr("y", cy)
  1563. .attr("dy", "0.35em")
  1564. .attr("fill", "rgba(255,255,255,0.5)")
  1565. .attr("font-size", "13px")
  1566. .attr("font-weight", "bold")
  1567. .attr("text-anchor", "end")
  1568. .text(cfg.name);
  1569. }});
  1570. // 绘制左侧人设树(在独立的treeSvg中)
  1571. const dimColors = {{ "灵感点": "#f39c12", "目的点": "#3498db", "关键点": "#9b59b6" }};
  1572. // 更新树SVG高度
  1573. treeSvg.attr("height", treeHeight + 50);
  1574. const treeGroup = treeG.append("g")
  1575. .attr("class", "persona-tree")
  1576. .attr("transform", `translate(15, 25)`);
  1577. // 设置关系图SVG
  1578. egoG.selectAll("*").remove();
  1579. const egoDisplayRadius = 180;
  1580. const egoCenterGroup = egoG.append("g")
  1581. .attr("class", "ego-center")
  1582. .attr("transform", `translate(200, 210)`);
  1583. // 关系图内容组
  1584. egoCenterGroup.append("g")
  1585. .attr("class", "ego-graph-content");
  1586. // D3树布局 - 宽度留出边距给标签
  1587. const treeLayout = d3.tree()
  1588. .size([treeHeight - 50, treeAreaWidth - 70]);
  1589. const root = d3.hierarchy(personaTree.root);
  1590. treeLayout(root);
  1591. // 获取节点颜色(根据维度)
  1592. function getNodeColor(d) {{
  1593. if (d.data.isRoot) return "#e94560"; // 根节点红色
  1594. if (d.data.isDimension) return d.data.dimColor; // 维度节点用维度颜色
  1595. return d.data.dimColor || "#888"; // 分类节点继承维度颜色
  1596. }}
  1597. // 构建节点ID到D3节点的映射(用于绘制原始边和高亮)
  1598. const treeNodeById = {{}};
  1599. root.descendants().forEach(d => {{
  1600. if (d.data.节点ID) {{
  1601. treeNodeById[d.data.节点ID] = d;
  1602. }}
  1603. }});
  1604. // 边类型颜色和样式
  1605. const treeEdgeColors = {{
  1606. "分类层级": "#2ecc71", // 绿色 - 分类的层级关系
  1607. "属于": "#9b59b6", // 紫色 - 标签属于分类
  1608. "包含": "#ffb6c1", // 淡粉 - 分类包含标签(向下)
  1609. "分类共现(跨点)": "#2ecc71", // 绿色 - 跨帖子分类共现
  1610. "分类共现(点内)": "#3498db", // 蓝色 - 同帖子分类共现
  1611. "标签共现": "#f39c12" // 橙色 - 标签共现
  1612. }};
  1613. const treeEdgeDash = {{
  1614. "分类层级": "none",
  1615. "属于": "3,2",
  1616. "包含": "3,2",
  1617. "分类共现(跨点)": "5,3",
  1618. "分类共现(点内)": "5,3",
  1619. "标签共现": "2,2"
  1620. }};
  1621. // 只用D3树布局的链接作为树边(避免重复)
  1622. const visibleTreeEdges = root.links().map(link => ({{
  1623. 源节点ID: link.source.data.节点ID || link.source.data.name,
  1624. 目标节点ID: link.target.data.节点ID || link.target.data.name,
  1625. 边类型: "属于",
  1626. isTreeLink: true,
  1627. sourceNode: link.source,
  1628. targetNode: link.target
  1629. }}));
  1630. // 生成树边路径的函数
  1631. function treeEdgePath(d) {{
  1632. const source = d.sourceNode;
  1633. const target = d.targetNode;
  1634. if (!source || !target) return "";
  1635. const midX = (source.y + target.y) / 2;
  1636. return `M${{source.y}},${{source.x}} C${{midX}},${{source.x}} ${{midX}},${{target.x}} ${{target.y}},${{target.x}}`;
  1637. }}
  1638. // 绘制原始边(只有属于边)
  1639. const treeEdgeGroup = treeGroup.append("g").attr("class", "tree-edges");
  1640. // 先绘制可见边(只有属于边)
  1641. const treeEdges = treeEdgeGroup.selectAll(".tree-edge")
  1642. .data(visibleTreeEdges)
  1643. .join("path")
  1644. .attr("class", "tree-edge")
  1645. .attr("fill", "none")
  1646. .attr("stroke", "#9b59b6") // 属于边用紫色
  1647. .attr("stroke-opacity", 0.3)
  1648. .attr("stroke-width", 1)
  1649. .attr("d", treeEdgePath);
  1650. // 绘制透明的热区边(便于点击)
  1651. const treeEdgeHitareas = treeEdgeGroup.selectAll(".tree-edge-hitarea")
  1652. .data(visibleTreeEdges)
  1653. .join("path")
  1654. .attr("class", "tree-edge-hitarea")
  1655. .attr("fill", "none")
  1656. .attr("stroke", "transparent")
  1657. .attr("stroke-width", 12)
  1658. .style("cursor", "pointer")
  1659. .attr("d", treeEdgePath)
  1660. .on("click", (event, d) => {{
  1661. event.stopPropagation();
  1662. // 调用共享的边点击处理函数
  1663. handleEdgeClick(d.源节点ID, d.目标节点ID, d.边类型);
  1664. }});
  1665. // 绘制节点
  1666. const treeNodes = treeGroup.selectAll(".tree-node")
  1667. .data(root.descendants())
  1668. .join("g")
  1669. .attr("class", "tree-node")
  1670. .attr("transform", d => `translate(${{d.y}},${{d.x}})`)
  1671. .style("cursor", "pointer")
  1672. .on("click", (event, d) => {{
  1673. event.stopPropagation();
  1674. // 调用共享的节点点击处理函数
  1675. handleNodeClick(d.data.节点ID, d.data.节点名称 || d.data.name);
  1676. }})
  1677. .on("mouseenter", (event, d) => {{
  1678. // 悬停高亮:在关系图中高亮到激活节点的路径
  1679. if (!currentEgoCenterNodeId) return;
  1680. const hoveredNodeId = d.data.节点ID;
  1681. if (!hoveredNodeId || hoveredNodeId === currentEgoCenterNodeId) return;
  1682. highlightPathInEgoGraph(hoveredNodeId);
  1683. }})
  1684. .on("mouseleave", (event, d) => {{
  1685. // 移出时恢复关系图
  1686. if (!currentEgoCenterNodeId) return;
  1687. resetEgoGraphHighlight();
  1688. }});
  1689. // 节点形状:根节点/维度=圆形,分类=正方形,标签=圆形
  1690. // 统一实心填充维度颜色
  1691. treeNodes.each(function(d) {{
  1692. const el = d3.select(this);
  1693. const nodeType = d.data.节点类型;
  1694. const isRoot = d.data.isRoot;
  1695. const isDimension = d.data.isDimension;
  1696. const nodeColor = getNodeColor(d);
  1697. if (nodeType === "分类") {{
  1698. // 分类节点:正方形,实心填充
  1699. el.append("rect")
  1700. .attr("class", "tree-shape")
  1701. .attr("x", -4)
  1702. .attr("y", -4)
  1703. .attr("width", 8)
  1704. .attr("height", 8)
  1705. .attr("rx", 1)
  1706. .attr("fill", nodeColor)
  1707. .attr("stroke", "rgba(255,255,255,0.5)")
  1708. .attr("stroke-width", 1);
  1709. }} else {{
  1710. // 根节点、维度节点、标签节点:圆形,实心填充
  1711. const radius = isRoot ? 6 : (isDimension ? 5 : 3);
  1712. el.append("circle")
  1713. .attr("class", "tree-shape")
  1714. .attr("r", radius)
  1715. .attr("fill", nodeColor)
  1716. .attr("stroke", "rgba(255,255,255,0.5)")
  1717. .attr("stroke-width", 1);
  1718. }}
  1719. }});
  1720. // 节点标签
  1721. treeNodes.append("text")
  1722. .attr("dy", "0.31em")
  1723. .attr("x", d => d.children ? -8 : 8)
  1724. .attr("text-anchor", d => d.children ? "end" : "start")
  1725. .attr("fill", d => (d.data.isRoot || d.data.isDimension) ? getNodeColor(d) : "#bbb")
  1726. .attr("font-size", d => d.data.isRoot ? "11px" : (d.data.isDimension ? "10px" : "8px"))
  1727. .attr("font-weight", d => (d.data.isRoot || d.data.isDimension) ? "bold" : "normal")
  1728. .text(d => d.data.name);
  1729. // 重置树高亮状态的函数
  1730. function resetTreeHighlight() {{
  1731. treeGroup.selectAll(".tree-node")
  1732. .classed("tree-dimmed", false)
  1733. .classed("tree-highlighted", false);
  1734. // 重置所有形状(圆形和方形)- 统一实心填充
  1735. treeGroup.selectAll(".tree-node .tree-shape")
  1736. .attr("fill", d => getNodeColor(d))
  1737. .attr("stroke", "rgba(255,255,255,0.5)")
  1738. .attr("stroke-opacity", 1)
  1739. .attr("opacity", 1);
  1740. treeGroup.selectAll(".tree-node text")
  1741. .attr("fill", d => (d.data.isRoot || d.data.isDimension) ? getNodeColor(d) : "#bbb")
  1742. .attr("opacity", 1);
  1743. // 重置边样式
  1744. treeGroup.selectAll(".tree-edge")
  1745. .attr("stroke-opacity", 0.3)
  1746. .attr("stroke-width", 1);
  1747. }}
  1748. // 重置右侧图高亮状态的函数
  1749. function resetGraphHighlight() {{
  1750. g.selectAll(".node").classed("dimmed", false).classed("highlighted", false);
  1751. g.selectAll(".link-group").classed("dimmed", false).classed("highlighted", false);
  1752. }}
  1753. // 点击树SVG背景取消高亮
  1754. treeSvg.on("click", function(event) {{
  1755. if (event.target === this) {{
  1756. resetTreeHighlight();
  1757. resetGraphHighlight();
  1758. clearEgoGraph();
  1759. closeDetailPanel();
  1760. }}
  1761. }});
  1762. // 创建边的容器
  1763. const linkGroup = g.append("g").attr("class", "links");
  1764. // 为每条边创建组
  1765. const linkG = linkGroup.selectAll("g")
  1766. .data(links)
  1767. .join("g")
  1768. .attr("class", "link-group");
  1769. // 绘制点击热区(透明宽线)
  1770. const linkHitarea = linkG.append("line")
  1771. .attr("class", "link-hitarea");
  1772. // 绘制可见的边
  1773. const link = linkG.append("line")
  1774. .attr("class", d => "link " + getEdgeClass(d.type))
  1775. .attr("stroke-width", d => d.type.startsWith("匹配_") ? 2.5 : 1.5);
  1776. // 判断是否为跨层边(根据源和目标节点的层级)- 赋值给全局变量
  1777. isCrossLayerEdge = function(d) {{
  1778. const sourceNode = typeof d.source === "object" ? d.source : nodes.find(n => n.id === d.source);
  1779. const targetNode = typeof d.target === "object" ? d.target : nodes.find(n => n.id === d.target);
  1780. if (!sourceNode || !targetNode) return false;
  1781. return getNodeLayer(sourceNode) !== getNodeLayer(targetNode);
  1782. }};
  1783. // 设置跨层边的初始可见性(匹配边始终显示,其他跨层边默认隐藏)
  1784. linkG.each(function(d) {{
  1785. if (d.type.startsWith("匹配_")) {{
  1786. d3.select(this).style("display", "block"); // 匹配边始终显示
  1787. }} else if (isCrossLayerEdge(d) && !showCrossLayerEdges) {{
  1788. d3.select(this).style("display", "none");
  1789. }}
  1790. }});
  1791. // 为匹配边添加分数标签
  1792. const edgeLabels = linkG.filter(d => d.type.startsWith("匹配_") && d.边详情 && d.边详情.相似度)
  1793. .append("g")
  1794. .attr("class", "edge-label-group");
  1795. edgeLabels.append("rect")
  1796. .attr("class", "edge-label-bg")
  1797. .attr("rx", 3)
  1798. .attr("ry", 3);
  1799. edgeLabels.append("text")
  1800. .attr("class", "edge-label")
  1801. .text(d => {{
  1802. const score = d.边详情.相似度;
  1803. return typeof score === "number" ? score.toFixed(2) : score;
  1804. }});
  1805. // 边的点击事件
  1806. linkHitarea.on("click", (event, d, i) => {{
  1807. event.stopPropagation();
  1808. const linkIndex = links.indexOf(d);
  1809. highlightEdge(d, linkIndex);
  1810. showEdgeInfo(d);
  1811. // 边联动:如果边涉及人设节点,联动人设树和关系图
  1812. const sourceNode = typeof d.source === "object" ? d.source : nodes.find(n => n.id === d.source);
  1813. const targetNode = typeof d.target === "object" ? d.target : nodes.find(n => n.id === d.target);
  1814. if (sourceNode && sourceNode.source === "人设") {{
  1815. handleNodeClick(sourceNode.节点ID, sourceNode.节点名称);
  1816. }} else if (targetNode && targetNode.source === "人设") {{
  1817. handleNodeClick(targetNode.节点ID, targetNode.节点名称);
  1818. }}
  1819. }})
  1820. .on("mouseover", function(event, d) {{
  1821. d3.select(this.parentNode).select(".link")
  1822. .attr("stroke-opacity", 1)
  1823. .attr("stroke-width", 4);
  1824. }})
  1825. .on("mouseout", function(event, d) {{
  1826. d3.select(this.parentNode).select(".link")
  1827. .attr("stroke-opacity", 0.7)
  1828. .attr("stroke-width", d.type.startsWith("匹配_") ? 2.5 : 1.5);
  1829. }});
  1830. // 绘制节点
  1831. const node = g.append("g")
  1832. .selectAll("g")
  1833. .data(nodes)
  1834. .join("g")
  1835. .attr("class", "node")
  1836. .call(d3.drag()
  1837. .on("start", dragstarted)
  1838. .on("drag", dragged)
  1839. .on("end", dragended));
  1840. // 根据节点类型绘制不同形状
  1841. // - 点节点(帖子点):六边形
  1842. // - 标签节点:圆形
  1843. // - 分类节点:方形
  1844. // 帖子标签用虚线,人设标签用实线
  1845. node.each(function(d) {{
  1846. const el = d3.select(this);
  1847. const isPointNode = d.节点类型 === "点";
  1848. const isPostNode = d.source === "帖子";
  1849. // 节点大小
  1850. let size;
  1851. if (isPointNode) {{
  1852. size = 16; // 点节点最大
  1853. }} else if (isPostNode) {{
  1854. size = 12; // 帖子标签
  1855. }} else {{
  1856. size = 10; // 人设标签
  1857. }}
  1858. const fill = levelColors[d.level] || "#666";
  1859. const nodeClass = isPostNode
  1860. ? (isPointNode ? "post-point-node" : "post-node")
  1861. : "persona-node";
  1862. if (isPointNode) {{
  1863. // 六边形(点节点)
  1864. const hexPoints = [];
  1865. for (let i = 0; i < 6; i++) {{
  1866. const angle = (i * 60 - 30) * Math.PI / 180;
  1867. hexPoints.push([size * Math.cos(angle), size * Math.sin(angle)]);
  1868. }}
  1869. el.append("polygon")
  1870. .attr("points", hexPoints.map(p => p.join(",")).join(" "))
  1871. .attr("fill", fill)
  1872. .attr("class", nodeClass);
  1873. }} else if (d.节点类型 === "分类") {{
  1874. // 方形(分类节点)
  1875. el.append("rect")
  1876. .attr("width", size * 2)
  1877. .attr("height", size * 2)
  1878. .attr("x", -size)
  1879. .attr("y", -size)
  1880. .attr("fill", fill)
  1881. .attr("class", nodeClass)
  1882. .attr("rx", 3);
  1883. }} else {{
  1884. // 圆形(标签节点)
  1885. el.append("circle")
  1886. .attr("r", size)
  1887. .attr("fill", fill)
  1888. .attr("class", nodeClass);
  1889. }}
  1890. }});
  1891. const labels = node.append("text")
  1892. .attr("dx", 15)
  1893. .attr("dy", 4)
  1894. .text(d => d.节点名称)
  1895. .style("display", showLabels ? "block" : "none");
  1896. // 工具提示
  1897. const tooltip = d3.select("#tooltip");
  1898. node.on("mouseover", (event, d) => {{
  1899. let html = `<strong>${{d.节点名称}}</strong><br/>类型: ${{d.节点类型}}<br/>层级: ${{d.节点层级}}`;
  1900. // 点节点显示描述
  1901. if (d.描述) {{
  1902. html += `<br/><br/><em style="font-size:10px;color:#aaa">${{d.描述.slice(0, 100)}}${{d.描述.length > 100 ? '...' : ''}}</em>`;
  1903. }}
  1904. tooltip.style("display", "block").html(html);
  1905. }})
  1906. .on("mousemove", (event) => {{
  1907. tooltip.style("left", (event.pageX + 15) + "px")
  1908. .style("top", (event.pageY - 10) + "px");
  1909. }})
  1910. .on("mouseout", () => {{
  1911. tooltip.style("display", "none");
  1912. }})
  1913. .on("click", (event, d) => {{
  1914. event.stopPropagation();
  1915. highlightNode(d);
  1916. showNodeInfo(d);
  1917. // 人设节点联动:高亮人设树 + 显示关系图
  1918. if (d.source === "人设") {{
  1919. handleNodeClick(d.节点ID, d.节点名称);
  1920. }}
  1921. }});
  1922. // 更新位置
  1923. simulation.on("tick", () => {{
  1924. // 更新热区线
  1925. linkHitarea
  1926. .attr("x1", d => d.source.x)
  1927. .attr("y1", d => d.source.y)
  1928. .attr("x2", d => d.target.x)
  1929. .attr("y2", d => d.target.y);
  1930. // 更新可见边
  1931. link
  1932. .attr("x1", d => d.source.x)
  1933. .attr("y1", d => d.source.y)
  1934. .attr("x2", d => d.target.x)
  1935. .attr("y2", d => d.target.y);
  1936. // 更新边标签位置(放在边的中点)
  1937. edgeLabels.attr("transform", d => {{
  1938. const midX = (d.source.x + d.target.x) / 2;
  1939. const midY = (d.source.y + d.target.y) / 2;
  1940. return `translate(${{midX}},${{midY}})`;
  1941. }});
  1942. // 更新标签背景大小
  1943. edgeLabels.each(function(d) {{
  1944. const textEl = d3.select(this).select("text").node();
  1945. if (textEl) {{
  1946. const bbox = textEl.getBBox();
  1947. d3.select(this).select("rect")
  1948. .attr("x", bbox.x - 3)
  1949. .attr("y", bbox.y - 1)
  1950. .attr("width", bbox.width + 6)
  1951. .attr("height", bbox.height + 2);
  1952. }}
  1953. }});
  1954. node.attr("transform", d => `translate(${{d.x}},${{d.y}})`);
  1955. }});
  1956. // 拖拽函数
  1957. function dragstarted(event, d) {{
  1958. if (!event.active) simulation.alphaTarget(0.3).restart();
  1959. d.fx = d.x;
  1960. d.fy = d.y;
  1961. }}
  1962. function dragged(event, d) {{
  1963. d.fx = event.x;
  1964. d.fy = event.y;
  1965. }}
  1966. function dragended(event, d) {{
  1967. if (!event.active) simulation.alphaTarget(0);
  1968. d.fx = null;
  1969. d.fy = null;
  1970. }}
  1971. // 清除所有高亮
  1972. function clearHighlight() {{
  1973. node.classed("dimmed", false).classed("highlighted", false);
  1974. linkG.classed("dimmed", false).classed("highlighted", false);
  1975. // 恢复跨层边的可见性状态(根据全局开关)
  1976. linkG.each(function(d) {{
  1977. if (isCrossLayerEdge(d)) {{
  1978. d3.select(this).style("display", showCrossLayerEdges ? "block" : "none");
  1979. }}
  1980. }});
  1981. }}
  1982. // 高亮指定的节点和边
  1983. function highlightElements(highlightNodeIds, highlightLinkIndices) {{
  1984. // 先灰化所有
  1985. node.classed("dimmed", true).classed("highlighted", false);
  1986. linkG.classed("dimmed", true).classed("highlighted", false);
  1987. // 高亮指定节点
  1988. node.filter(d => highlightNodeIds.has(d.id))
  1989. .classed("dimmed", false)
  1990. .classed("highlighted", true);
  1991. // 高亮指定边
  1992. linkG.filter((d, i) => highlightLinkIndices.has(i))
  1993. .classed("dimmed", false)
  1994. .classed("highlighted", true);
  1995. }}
  1996. // 点击节点时的高亮逻辑
  1997. function highlightNode(clickedNode) {{
  1998. const highlightNodeIds = new Set([clickedNode.id]);
  1999. const highlightLinkIndices = new Set();
  2000. links.forEach((link, i) => {{
  2001. const sourceId = typeof link.source === "object" ? link.source.id : link.source;
  2002. const targetId = typeof link.target === "object" ? link.target.id : link.target;
  2003. // 与点击节点直接相连的边
  2004. if (sourceId === clickedNode.id || targetId === clickedNode.id) {{
  2005. highlightLinkIndices.add(i);
  2006. highlightNodeIds.add(sourceId);
  2007. highlightNodeIds.add(targetId);
  2008. // 如果是帖子节点,还要高亮对应的镜像边
  2009. if (clickedNode.source === "帖子") {{
  2010. // 找到通过该帖子连接的其他帖子(镜像边)
  2011. links.forEach((otherLink, j) => {{
  2012. const otherType = otherLink.type;
  2013. if (otherType.startsWith("镜像_") || otherType.startsWith("二阶_")) {{
  2014. const oSrc = typeof otherLink.source === "object" ? otherLink.source.id : otherLink.source;
  2015. const oTgt = typeof otherLink.target === "object" ? otherLink.target.id : otherLink.target;
  2016. if (oSrc === clickedNode.id || oTgt === clickedNode.id) {{
  2017. highlightLinkIndices.add(j);
  2018. highlightNodeIds.add(oSrc);
  2019. highlightNodeIds.add(oTgt);
  2020. }}
  2021. }}
  2022. }});
  2023. }}
  2024. }}
  2025. }});
  2026. // 高亮相关的节点和边
  2027. highlightElements(highlightNodeIds, highlightLinkIndices);
  2028. // 临时显示关联的跨层边(即使全局开关是关闭的)
  2029. linkG.each(function(d, i) {{
  2030. if (highlightLinkIndices.has(i)) {{
  2031. d3.select(this).style("display", "block");
  2032. }}
  2033. }});
  2034. }}
  2035. // 点击边时的高亮逻辑
  2036. function highlightEdge(clickedLink, clickedIndex) {{
  2037. const highlightNodeIds = new Set();
  2038. const highlightLinkIndices = new Set([clickedIndex]);
  2039. const sourceId = typeof clickedLink.source === "object" ? clickedLink.source.id : clickedLink.source;
  2040. const targetId = typeof clickedLink.target === "object" ? clickedLink.target.id : clickedLink.target;
  2041. highlightNodeIds.add(sourceId);
  2042. highlightNodeIds.add(targetId);
  2043. // 如果是二阶边,显示完整路径
  2044. if (clickedLink.type.startsWith("二阶_") && clickedLink.边详情) {{
  2045. const detail = clickedLink.边详情;
  2046. // 分类节点
  2047. if (detail.分类节点1) highlightNodeIds.add(detail.分类节点1);
  2048. if (detail.分类节点2) highlightNodeIds.add(detail.分类节点2);
  2049. // 标签节点
  2050. if (detail.标签节点1) highlightNodeIds.add(detail.标签节点1);
  2051. if (detail.标签节点2) highlightNodeIds.add(detail.标签节点2);
  2052. // 找出路径上的边
  2053. links.forEach((link, i) => {{
  2054. const lSrc = typeof link.source === "object" ? link.source.id : link.source;
  2055. const lTgt = typeof link.target === "object" ? link.target.id : link.target;
  2056. // 帖子->标签 的匹配边
  2057. if (link.type.startsWith("匹配_")) {{
  2058. if ((lSrc === sourceId && lTgt === detail.标签节点1) ||
  2059. (lSrc === targetId && lTgt === detail.标签节点2)) {{
  2060. highlightLinkIndices.add(i);
  2061. }}
  2062. }}
  2063. // 标签->分类 的属于边
  2064. if (link.type === "属于") {{
  2065. if ((lSrc === detail.标签节点1 && lTgt === detail.分类节点1) ||
  2066. (lSrc === detail.标签节点2 && lTgt === detail.分类节点2)) {{
  2067. highlightLinkIndices.add(i);
  2068. }}
  2069. }}
  2070. // 分类之间的边
  2071. if ((lSrc === detail.分类节点1 && lTgt === detail.分类节点2) ||
  2072. (lSrc === detail.分类节点2 && lTgt === detail.分类节点1)) {{
  2073. highlightLinkIndices.add(i);
  2074. }}
  2075. }});
  2076. }}
  2077. // 如果是镜像边,显示对应的人设边
  2078. else if (clickedLink.type.startsWith("镜像_") && clickedLink.边详情) {{
  2079. const detail = clickedLink.边详情;
  2080. if (detail.源人设节点) highlightNodeIds.add(detail.源人设节点);
  2081. if (detail.目标人设节点) highlightNodeIds.add(detail.目标人设节点);
  2082. // 找出对应的人设边和匹配边
  2083. links.forEach((link, i) => {{
  2084. const lSrc = typeof link.source === "object" ? link.source.id : link.source;
  2085. const lTgt = typeof link.target === "object" ? link.target.id : link.target;
  2086. // 匹配边
  2087. if (link.type.startsWith("匹配_")) {{
  2088. if ((lSrc === sourceId && lTgt === detail.源人设节点) ||
  2089. (lSrc === targetId && lTgt === detail.目标人设节点)) {{
  2090. highlightLinkIndices.add(i);
  2091. }}
  2092. }}
  2093. // 人设边
  2094. if ((lSrc === detail.源人设节点 && lTgt === detail.目标人设节点) ||
  2095. (lSrc === detail.目标人设节点 && lTgt === detail.源人设节点)) {{
  2096. highlightLinkIndices.add(i);
  2097. }}
  2098. }});
  2099. }}
  2100. // 高亮相关的节点和边
  2101. highlightElements(highlightNodeIds, highlightLinkIndices);
  2102. // 临时显示关联的跨层边(即使全局开关是关闭的)
  2103. linkG.each(function(d, i) {{
  2104. if (highlightLinkIndices.has(i)) {{
  2105. d3.select(this).style("display", "block");
  2106. }}
  2107. }});
  2108. }}
  2109. // 点击空白处清除高亮(合并所有空白点击逻辑)
  2110. svg.on("click", (event) => {{
  2111. // 检查是否点击的是空白区域(svg本身或layer-backgrounds)
  2112. const isBlank = event.target === svg.node() ||
  2113. event.target.tagName === "svg" ||
  2114. event.target.classList.contains("layer-backgrounds");
  2115. if (isBlank) {{
  2116. // 清除右侧图高亮
  2117. clearHighlight();
  2118. // 清除人设树高亮
  2119. resetTreeHighlight();
  2120. resetGraphHighlight();
  2121. // 关闭详情面板
  2122. closeDetailPanel();
  2123. // 清除关系图
  2124. clearEgoGraph();
  2125. }}
  2126. }});
  2127. }}
  2128. // 控制函数
  2129. function resetZoom() {{
  2130. const container = document.getElementById("svg-container");
  2131. const width = container.clientWidth;
  2132. const height = container.clientHeight;
  2133. svg.transition().duration(750).call(
  2134. zoom.transform,
  2135. d3.zoomIdentity.translate(width/2, height/2).scale(1).translate(-width/2, -height/2)
  2136. );
  2137. }}
  2138. function toggleLabels() {{
  2139. showLabels = !showLabels;
  2140. g.selectAll(".node text").style("display", showLabels ? "block" : "none");
  2141. }}
  2142. // 切换跨层边显示
  2143. function toggleCrossLayerEdges() {{
  2144. showCrossLayerEdges = !showCrossLayerEdges;
  2145. const btn = document.getElementById("crossLayerBtn");
  2146. btn.textContent = showCrossLayerEdges ? "隐藏跨层边" : "显示跨层边";
  2147. btn.style.background = showCrossLayerEdges ? "#e94560" : "";
  2148. // 更新边的可见性(使用 isCrossLayerEdge 函数判断)
  2149. g.selectAll(".link-group").each(function(d) {{
  2150. if (isCrossLayerEdge(d)) {{
  2151. d3.select(this).style("display", showCrossLayerEdges ? "block" : "none");
  2152. }}
  2153. }});
  2154. }}
  2155. function showNodeInfo(d) {{
  2156. const panel = document.getElementById("detailPanel");
  2157. panel.classList.add("active");
  2158. document.getElementById("detailTitle").textContent = d.source === "帖子" ? "📌 帖子节点" : "👤 人设节点";
  2159. let html = `
  2160. <p><span class="label">节点ID:</span> ${{d.节点ID}}</p>
  2161. <p><span class="label">名称:</span> <strong>${{d.节点名称}}</strong></p>
  2162. <p><span class="label">类型:</span> ${{d.节点类型}}</p>
  2163. <p><span class="label">层级:</span> ${{d.节点层级}}</p>
  2164. `;
  2165. if (d.权重) {{
  2166. html += `<p><span class="label">权重:</span> ${{d.权重}}</p>`;
  2167. }}
  2168. if (d.所属分类 && d.所属分类.length > 0) {{
  2169. html += `<p><span class="label">所属分类:</span> ${{d.所属分类.join(" > ")}}</p>`;
  2170. }}
  2171. if (d.帖子数) {{
  2172. html += `<p><span class="label">帖子数:</span> ${{d.帖子数}}</p>`;
  2173. }}
  2174. document.getElementById("detailContent").innerHTML = html;
  2175. }}
  2176. // 显示人设树节点详情(包含入边、出边、相关节点)
  2177. function showTreeNodeDetail(nodeData, inEdges, outEdges) {{
  2178. const panel = document.getElementById("detailPanel");
  2179. panel.classList.add("active");
  2180. document.getElementById("detailTitle").textContent = "🌳 人设树节点";
  2181. // 节点基本信息
  2182. let html = `
  2183. <p><span class="label">名称:</span> <strong>${{nodeData.节点名称 || nodeData.name}}</strong></p>
  2184. <p><span class="label">类型:</span> ${{nodeData.节点类型 || (nodeData.isRoot ? "根节点" : "维度")}}</p>
  2185. <p><span class="label">层级:</span> ${{nodeData.节点层级 || "-"}}</p>
  2186. `;
  2187. if (nodeData.所属分类 && nodeData.所属分类.length > 0) {{
  2188. html += `<p><span class="label">所属分类:</span> ${{nodeData.所属分类.join(" > ")}}</p>`;
  2189. }}
  2190. if (nodeData.帖子数) {{
  2191. html += `<p><span class="label">帖子数:</span> ${{nodeData.帖子数}}</p>`;
  2192. }}
  2193. // 统计边类型
  2194. const inEdgeTypes = {{}};
  2195. const outEdgeTypes = {{}};
  2196. inEdges.forEach(e => {{ inEdgeTypes[e.边类型] = (inEdgeTypes[e.边类型] || 0) + 1; }});
  2197. outEdges.forEach(e => {{ outEdgeTypes[e.边类型] = (outEdgeTypes[e.边类型] || 0) + 1; }});
  2198. // 入边统计
  2199. html += `<h4 style="margin-top:12px;color:#3498db;font-size:12px;">📥 入边 (${{inEdges.length}})</h4>`;
  2200. if (inEdges.length > 0) {{
  2201. html += `<div class="edge-list">`;
  2202. for (const [type, count] of Object.entries(inEdgeTypes)) {{
  2203. html += `<div class="edge-type-item"><span class="edge-type">${{type}}</span><span class="edge-count">${{count}}</span></div>`;
  2204. }}
  2205. // 显示前5条入边详情
  2206. const showInEdges = inEdges.slice(0, 5);
  2207. showInEdges.forEach(e => {{
  2208. const srcName = personaTreeData.nodes.find(n => n.节点ID === e.源节点ID)?.节点名称 || e.源节点ID;
  2209. html += `<div class="edge-detail">← ${{srcName}} <span class="edge-type-tag">${{e.边类型}}</span></div>`;
  2210. }});
  2211. if (inEdges.length > 5) {{
  2212. html += `<div class="edge-more">... 还有 ${{inEdges.length - 5}} 条</div>`;
  2213. }}
  2214. html += `</div>`;
  2215. }} else {{
  2216. html += `<div class="edge-empty">无</div>`;
  2217. }}
  2218. // 出边统计
  2219. html += `<h4 style="margin-top:12px;color:#e74c3c;font-size:12px;">📤 出边 (${{outEdges.length}})</h4>`;
  2220. if (outEdges.length > 0) {{
  2221. html += `<div class="edge-list">`;
  2222. for (const [type, count] of Object.entries(outEdgeTypes)) {{
  2223. html += `<div class="edge-type-item"><span class="edge-type">${{type}}</span><span class="edge-count">${{count}}</span></div>`;
  2224. }}
  2225. // 显示前5条出边详情
  2226. const showOutEdges = outEdges.slice(0, 5);
  2227. showOutEdges.forEach(e => {{
  2228. const tgtName = personaTreeData.nodes.find(n => n.节点ID === e.目标节点ID)?.节点名称 || e.目标节点ID;
  2229. html += `<div class="edge-detail">→ ${{tgtName}} <span class="edge-type-tag">${{e.边类型}}</span></div>`;
  2230. }});
  2231. if (outEdges.length > 5) {{
  2232. html += `<div class="edge-more">... 还有 ${{outEdges.length - 5}} 条</div>`;
  2233. }}
  2234. html += `</div>`;
  2235. }} else {{
  2236. html += `<div class="edge-empty">无</div>`;
  2237. }}
  2238. document.getElementById("detailContent").innerHTML = html;
  2239. }}
  2240. function showEdgeInfo(d) {{
  2241. const panel = document.getElementById("detailPanel");
  2242. panel.classList.add("active");
  2243. const sourceNode = typeof d.source === "object" ? d.source : {{ id: d.source }};
  2244. const targetNode = typeof d.target === "object" ? d.target : {{ id: d.target }};
  2245. // 判断是否为镜像边
  2246. const isMirror = d.type.startsWith("镜像_");
  2247. document.getElementById("detailTitle").textContent = isMirror ? "🪞 镜像边详情" : "🔗 边详情";
  2248. let html = `
  2249. <p><span class="label">边类型:</span> <strong>${{d.type}}</strong></p>
  2250. <p><span class="label">源节点:</span> ${{sourceNode.节点名称 || sourceNode.id}}</p>
  2251. <p><span class="label">目标节点:</span> ${{targetNode.节点名称 || targetNode.id}}</p>
  2252. `;
  2253. if (d.边详情) {{
  2254. if (d.边详情.相似度 !== undefined) {{
  2255. const score = typeof d.边详情.相似度 === "number" ? d.边详情.相似度.toFixed(2) : d.边详情.相似度;
  2256. html += `<p><span class="label">相似度:</span> <span class="similarity-score">${{score}}</span></p>`;
  2257. }}
  2258. if (d.边详情.说明) {{
  2259. html += `<p><span class="label">说明:</span></p><div class="edge-description">${{d.边详情.说明}}</div>`;
  2260. }}
  2261. if (d.边详情.共现次数 !== undefined) {{
  2262. html += `<p><span class="label">共现次数:</span> ${{d.边详情.共现次数}}</p>`;
  2263. }}
  2264. // 镜像边特有信息
  2265. if (d.边详情.原始边类型) {{
  2266. html += `<p><span class="label">原始边类型:</span> ${{d.边详情.原始边类型}}</p>`;
  2267. }}
  2268. if (d.边详情.源人设节点) {{
  2269. html += `<p><span class="label">源人设节点:</span> ${{d.边详情.源人设节点}}</p>`;
  2270. }}
  2271. if (d.边详情.目标人设节点) {{
  2272. html += `<p><span class="label">目标人设节点:</span> ${{d.边详情.目标人设节点}}</p>`;
  2273. }}
  2274. }}
  2275. document.getElementById("detailContent").innerHTML = html;
  2276. }}
  2277. function closeDetailPanel() {{
  2278. document.getElementById("detailPanel").classList.remove("active");
  2279. }}
  2280. // 更新匹配列表
  2281. function updateMatchList(matchLinks, nodes) {{
  2282. const listEl = document.getElementById("matchList");
  2283. const countEl = document.getElementById("matchCount");
  2284. // 构建节点ID到名称的映射
  2285. const nodeNames = {{}};
  2286. nodes.forEach(n => {{
  2287. nodeNames[n.id] = n.节点名称 || n.id;
  2288. }});
  2289. // 按分数降序排序
  2290. const sortedLinks = [...matchLinks].sort((a, b) => {{
  2291. const scoreA = a.边详情?.相似度 ?? 0;
  2292. const scoreB = b.边详情?.相似度 ?? 0;
  2293. return scoreB - scoreA;
  2294. }});
  2295. countEl.textContent = `(${{sortedLinks.length}})`;
  2296. // 生成列表HTML
  2297. let html = "";
  2298. sortedLinks.forEach((link, index) => {{
  2299. const score = link.边详情?.相似度;
  2300. const scoreText = score !== undefined ? score.toFixed(2) : "N/A";
  2301. const scoreClass = score >= 0.8 ? "high" : (score >= 0.5 ? "medium" : "");
  2302. const srcId = typeof link.source === "object" ? link.source.id : link.source;
  2303. const tgtId = typeof link.target === "object" ? link.target.id : link.target;
  2304. const srcName = nodeNames[srcId] || srcId;
  2305. const tgtName = nodeNames[tgtId] || tgtId;
  2306. html += `
  2307. <div class="match-item" data-index="${{index}}" data-src="${{srcId}}" data-tgt="${{tgtId}}">
  2308. <span class="score ${{scoreClass}}">${{scoreText}}</span>
  2309. <span class="names" title="${{srcName}} → ${{tgtName}}">${{srcName}} → ${{tgtName}}</span>
  2310. </div>
  2311. `;
  2312. }});
  2313. listEl.innerHTML = html;
  2314. // 添加点击事件
  2315. listEl.querySelectorAll(".match-item").forEach(item => {{
  2316. item.addEventListener("click", () => {{
  2317. const srcId = item.dataset.src;
  2318. const tgtId = item.dataset.tgt;
  2319. const index = parseInt(item.dataset.index);
  2320. // 高亮对应的边
  2321. highlightMatchEdge(srcId, tgtId);
  2322. // 更新列表项样式
  2323. listEl.querySelectorAll(".match-item").forEach(el => el.classList.remove("active"));
  2324. item.classList.add("active");
  2325. }});
  2326. }});
  2327. }}
  2328. // 高亮匹配边
  2329. function highlightMatchEdge(srcId, tgtId) {{
  2330. if (!g) return;
  2331. // 重置所有
  2332. g.selectAll(".node").classed("dimmed", true).classed("highlighted", false);
  2333. g.selectAll(".link-group").classed("dimmed", true).classed("highlighted", false);
  2334. // 高亮对应的边和节点
  2335. g.selectAll(".link-group").each(function(d) {{
  2336. const dSrc = typeof d.source === "object" ? d.source.id : d.source;
  2337. const dTgt = typeof d.target === "object" ? d.target.id : d.target;
  2338. if ((dSrc === srcId && dTgt === tgtId) || (dSrc === tgtId && dTgt === srcId)) {{
  2339. d3.select(this).classed("dimmed", false).classed("highlighted", true);
  2340. }}
  2341. }});
  2342. g.selectAll(".node").each(function(d) {{
  2343. if (d.id === srcId || d.id === tgtId) {{
  2344. d3.select(this).classed("dimmed", false).classed("highlighted", true);
  2345. }}
  2346. }});
  2347. }}
  2348. // 获取节点颜色(全局版本,根据节点数据判断维度)
  2349. function getTreeNodeColor(d) {{
  2350. const dimColors = {{ "灵感点": "#f39c12", "目的点": "#3498db", "关键点": "#9b59b6" }};
  2351. if (d.data.isRoot) return "#e94560";
  2352. if (d.data.isDimension) return d.data.dimColor;
  2353. return d.data.dimColor || "#888";
  2354. }}
  2355. // 共享的节点点击处理函数(人设树和关系图复用)
  2356. function handleNodeClick(clickedNodeId, clickedNodeName) {{
  2357. if (!clickedNodeId) return;
  2358. // 动态获取树相关元素
  2359. const treeGroup = d3.select(".persona-tree");
  2360. if (treeGroup.empty()) return;
  2361. const treeEdges = treeGroup.selectAll(".tree-edge");
  2362. // 先重置所有高亮状态
  2363. treeGroup.selectAll(".tree-node")
  2364. .classed("tree-dimmed", false)
  2365. .classed("tree-highlighted", false);
  2366. treeGroup.selectAll(".tree-node .tree-shape")
  2367. .attr("fill", d => getTreeNodeColor(d))
  2368. .attr("stroke", "rgba(255,255,255,0.5)")
  2369. .attr("stroke-width", 1)
  2370. .attr("stroke-opacity", 1)
  2371. .attr("opacity", 1);
  2372. treeGroup.selectAll(".tree-node text")
  2373. .attr("fill", d => (d.data.isRoot || d.data.isDimension) ? getTreeNodeColor(d) : "#bbb")
  2374. .attr("opacity", 1);
  2375. treeEdges.attr("stroke-opacity", 0.3).attr("stroke-width", 1);
  2376. if (g) {{
  2377. g.selectAll(".node").classed("dimmed", false).classed("highlighted", false);
  2378. g.selectAll(".link-group").classed("dimmed", false).classed("highlighted", false);
  2379. }}
  2380. // 构建节点ID到D3节点的映射
  2381. const treeNodeById = {{}};
  2382. treeGroup.selectAll(".tree-node").each(function(n) {{
  2383. if (n.data.节点ID) treeNodeById[n.data.节点ID] = n;
  2384. }});
  2385. // 使用多级配置收集关联节点(与关系图一致)
  2386. const levelConfigs = getLevelConfigs();
  2387. const {{ nodeIds: connectedNodeIds, edges: allConnectedEdges }} = collectNodesAndEdges(clickedNodeId, levelConfigs);
  2388. // 获取D3树节点
  2389. const clickedD3Node = treeNodeById[clickedNodeId];
  2390. // 转换为D3节点集合(只基于 collectNodesAndEdges 的结果,与关系图同步)
  2391. const connectedD3Nodes = new Set();
  2392. if (clickedD3Node) connectedD3Nodes.add(clickedD3Node);
  2393. connectedNodeIds.forEach(id => {{
  2394. if (treeNodeById[id]) connectedD3Nodes.add(treeNodeById[id]);
  2395. }});
  2396. // 高亮树中的节点
  2397. treeGroup.selectAll(".tree-node")
  2398. .classed("tree-dimmed", n => !connectedD3Nodes.has(n))
  2399. .classed("tree-highlighted", n => connectedD3Nodes.has(n));
  2400. // 高亮所有形状(不变粗)
  2401. treeGroup.selectAll(".tree-node .tree-shape")
  2402. .attr("fill", function(n) {{
  2403. if (!connectedD3Nodes.has(n)) return "#555";
  2404. return getTreeNodeColor(n);
  2405. }})
  2406. .attr("stroke", function(n) {{
  2407. if (n.data.节点ID === clickedNodeId) return "#fff";
  2408. return connectedD3Nodes.has(n) ? "rgba(255,255,255,0.8)" : "#333";
  2409. }})
  2410. .attr("stroke-opacity", 1);
  2411. treeGroup.selectAll(".tree-node text")
  2412. .attr("fill", function(n) {{
  2413. if (!connectedD3Nodes.has(n)) return "#555";
  2414. return (n.data.isRoot || n.data.isDimension) ? getTreeNodeColor(n) : "#bbb";
  2415. }});
  2416. // 边高亮(树边基于连接的节点)
  2417. treeEdges.attr("stroke-opacity", function(e) {{
  2418. // 树边高亮条件:子节点(目标)在连接集中,或者两端都在连接集中
  2419. const srcId = e.源节点ID;
  2420. const tgtId = e.目标节点ID;
  2421. const srcConnected = connectedNodeIds.has(srcId) || connectedD3Nodes.has(e.sourceNode);
  2422. const tgtConnected = connectedNodeIds.has(tgtId) || connectedD3Nodes.has(e.targetNode);
  2423. return (srcConnected && tgtConnected) ? 0.9 : 0.15;
  2424. }});
  2425. // 计算入边和出边
  2426. const inEdges = allConnectedEdges.filter(e => e.目标节点ID === clickedNodeId);
  2427. const outEdges = allConnectedEdges.filter(e => e.源节点ID === clickedNodeId);
  2428. // 显示详情面板
  2429. const nodeData = personaTreeData.nodes.find(n => n.节点ID === clickedNodeId);
  2430. if (nodeData) {{
  2431. showTreeNodeDetail(nodeData, inEdges, outEdges);
  2432. }}
  2433. // 显示关系子图(先显示,这样容器高度才正确)
  2434. renderEgoGraph(clickedNodeId, clickedNodeName);
  2435. // 滚动人设树到对应节点位置(放在关系图显示后,高度才准确)
  2436. if (clickedD3Node) {{
  2437. // 用 setTimeout 确保 DOM 更新完成
  2438. setTimeout(() => {{
  2439. const treeContainer = document.getElementById("tree-container");
  2440. const containerHeight = treeContainer.clientHeight;
  2441. // D3树布局中 x 是垂直方向(因为是水平树)
  2442. const nodeY = clickedD3Node.x + 25; // 加上treeGroup的transform偏移
  2443. const targetScroll = nodeY - containerHeight / 2;
  2444. treeContainer.scrollTo({{
  2445. top: Math.max(0, targetScroll),
  2446. behavior: "smooth"
  2447. }});
  2448. }}, 50);
  2449. }}
  2450. // 高亮右侧图中对应节点及其相关节点和边
  2451. if (g) {{
  2452. // 收集相关节点ID(点击的节点及其直接连接的节点)
  2453. const relatedNodeIds = new Set([clickedNodeId]);
  2454. // 找所有与该节点相连的边
  2455. g.selectAll(".link-group").each(function(d) {{
  2456. const srcId = typeof d.source === "object" ? d.source.id : d.source;
  2457. const tgtId = typeof d.target === "object" ? d.target.id : d.target;
  2458. if (srcId === clickedNodeId || tgtId === clickedNodeId) {{
  2459. relatedNodeIds.add(srcId);
  2460. relatedNodeIds.add(tgtId);
  2461. }}
  2462. }});
  2463. // 检查是否有相关节点在图中
  2464. const hasRelatedNodes = g.selectAll(".node").filter(n => relatedNodeIds.has(n.id)).size() > 0;
  2465. if (hasRelatedNodes) {{
  2466. // 高亮相关节点,变灰其他
  2467. g.selectAll(".node")
  2468. .classed("dimmed", n => !relatedNodeIds.has(n.id))
  2469. .classed("highlighted", n => relatedNodeIds.has(n.id));
  2470. // 高亮相关边
  2471. g.selectAll(".link-group").each(function(d) {{
  2472. const srcId = typeof d.source === "object" ? d.source.id : d.source;
  2473. const tgtId = typeof d.target === "object" ? d.target.id : d.target;
  2474. const isRelated = srcId === clickedNodeId || tgtId === clickedNodeId;
  2475. d3.select(this)
  2476. .classed("dimmed", !isRelated)
  2477. .classed("highlighted", isRelated);
  2478. // 显示相关的跨层边
  2479. if (isRelated) {{
  2480. d3.select(this).style("display", "block");
  2481. }}
  2482. }});
  2483. }} else {{
  2484. // 点击的节点不在图中,全部变灰
  2485. g.selectAll(".node").classed("dimmed", true).classed("highlighted", false);
  2486. g.selectAll(".link-group").classed("dimmed", true).classed("highlighted", false);
  2487. }}
  2488. }}
  2489. }}
  2490. // 共享的边点击处理函数(人设树和关系图复用)
  2491. function handleEdgeClick(srcNodeId, tgtNodeId, edgeType) {{
  2492. // 动态获取树相关元素
  2493. const treeGroup = d3.select(".persona-tree");
  2494. if (treeGroup.empty()) return;
  2495. const treeEdges = treeGroup.selectAll(".tree-edge");
  2496. // 先重置所有高亮状态
  2497. treeGroup.selectAll(".tree-node")
  2498. .classed("tree-dimmed", false)
  2499. .classed("tree-highlighted", false);
  2500. treeGroup.selectAll(".tree-node .tree-shape")
  2501. .attr("fill", d => getTreeNodeColor(d))
  2502. .attr("stroke", "rgba(255,255,255,0.5)")
  2503. .attr("stroke-width", 1)
  2504. .attr("stroke-opacity", 1)
  2505. .attr("opacity", 1);
  2506. treeGroup.selectAll(".tree-node text")
  2507. .attr("fill", d => (d.data.isRoot || d.data.isDimension) ? getTreeNodeColor(d) : "#bbb")
  2508. .attr("opacity", 1);
  2509. treeEdges.attr("stroke-opacity", 0.3).attr("stroke-width", 1);
  2510. if (g) {{
  2511. g.selectAll(".node").classed("dimmed", false).classed("highlighted", false);
  2512. g.selectAll(".link-group").classed("dimmed", false).classed("highlighted", false);
  2513. }}
  2514. // 构建节点ID到D3节点的映射
  2515. const treeNodeById = {{}};
  2516. treeGroup.selectAll(".tree-node").each(function(n) {{
  2517. if (n.data.节点ID) treeNodeById[n.data.节点ID] = n;
  2518. }});
  2519. const sourceTreeNode = treeNodeById[srcNodeId];
  2520. const targetTreeNode = treeNodeById[tgtNodeId];
  2521. // 高亮树边(不变粗)
  2522. treeEdges.attr("stroke-opacity", function(e) {{
  2523. const isThisEdge = (e.源节点ID === srcNodeId && e.目标节点ID === tgtNodeId) ||
  2524. (e.源节点ID === tgtNodeId && e.目标节点ID === srcNodeId);
  2525. return isThisEdge ? 1 : 0.1;
  2526. }});
  2527. // 高亮相关节点
  2528. const connectedNodes = new Set();
  2529. if (sourceTreeNode) connectedNodes.add(sourceTreeNode);
  2530. if (targetTreeNode) connectedNodes.add(targetTreeNode);
  2531. treeGroup.selectAll(".tree-node .tree-shape")
  2532. .attr("fill", n => connectedNodes.has(n) ? getTreeNodeColor(n) : "#555")
  2533. .attr("opacity", 1);
  2534. treeGroup.selectAll(".tree-node text")
  2535. .attr("fill", n => connectedNodes.has(n) ?
  2536. ((n.data.isRoot || n.data.isDimension) ? getTreeNodeColor(n) : "#bbb") : "#555")
  2537. .attr("opacity", 1);
  2538. // 显示边详情
  2539. const panel = document.getElementById("detailPanel");
  2540. panel.classList.add("active");
  2541. document.getElementById("detailTitle").textContent = "🔗 边详情";
  2542. const srcNode = personaTreeData.nodes.find(n => n.节点ID === srcNodeId);
  2543. const tgtNode = personaTreeData.nodes.find(n => n.节点ID === tgtNodeId);
  2544. const srcName = sourceTreeNode ? (sourceTreeNode.data.节点名称 || sourceTreeNode.data.name) : (srcNode?.节点名称 || srcNodeId);
  2545. const tgtName = targetTreeNode ? (targetTreeNode.data.节点名称 || targetTreeNode.data.name) : (tgtNode?.节点名称 || tgtNodeId);
  2546. let html = `
  2547. <p><span class="label">边类型:</span> <strong>${{edgeType}}</strong></p>
  2548. <p><span class="label">源节点:</span> ${{srcName}}</p>
  2549. <p><span class="label">目标节点:</span> ${{tgtName}}</p>
  2550. `;
  2551. document.getElementById("detailContent").innerHTML = html;
  2552. // 高亮右侧人设匹配区域
  2553. if (g) {{
  2554. const relatedNodeIds = new Set([srcNodeId, tgtNodeId]);
  2555. const hasRelatedNodes = g.selectAll(".node").filter(n => relatedNodeIds.has(n.id)).size() > 0;
  2556. if (hasRelatedNodes) {{
  2557. // 高亮相关节点
  2558. g.selectAll(".node")
  2559. .classed("dimmed", n => !relatedNodeIds.has(n.id))
  2560. .classed("highlighted", n => relatedNodeIds.has(n.id));
  2561. // 高亮相关边
  2562. g.selectAll(".link-group").each(function(d) {{
  2563. const sid = typeof d.source === "object" ? d.source.id : d.source;
  2564. const tid = typeof d.target === "object" ? d.target.id : d.target;
  2565. const isRelated = (sid === srcNodeId && tid === tgtNodeId) ||
  2566. (sid === tgtNodeId && tid === srcNodeId) ||
  2567. relatedNodeIds.has(sid) || relatedNodeIds.has(tid);
  2568. d3.select(this)
  2569. .classed("dimmed", !isRelated)
  2570. .classed("highlighted", isRelated);
  2571. }});
  2572. }} else {{
  2573. // 全部变灰
  2574. g.selectAll(".node").classed("dimmed", true).classed("highlighted", false);
  2575. g.selectAll(".link-group").classed("dimmed", true).classed("highlighted", false);
  2576. }}
  2577. }}
  2578. // 在关系图中展示这条边和两个节点
  2579. const edgeData = {{
  2580. 边类型: edgeType,
  2581. 源节点ID: srcNodeId,
  2582. 目标节点ID: tgtNodeId
  2583. }};
  2584. renderEgoGraphEdge(edgeData, sourceTreeNode, targetTreeNode);
  2585. }}
  2586. // 关系子图(Ego Graph)- 在画布第四层显示
  2587. let currentEgoSimulation = null; // 保存当前的力模拟,用于停止
  2588. let currentEgoCenterNodeId = null; // 当前关系图中心节点ID
  2589. let currentEgoCenterNodeName = null; // 当前关系图中心节点名称
  2590. // 当前选中的层级数
  2591. let currentLevelCount = 1;
  2592. // 切换级联菜单
  2593. function toggleCascadeMenu() {{
  2594. event.stopPropagation();
  2595. const menu = document.getElementById('cascade-menu');
  2596. menu.classList.toggle('show');
  2597. }}
  2598. // 反选指定层级的边类型
  2599. function invertSelection(level) {{
  2600. event.stopPropagation();
  2601. document.querySelectorAll(`.cascade-edge-item input[data-level="${{level}}"]`).forEach(cb => {{
  2602. cb.checked = !cb.checked;
  2603. }});
  2604. // 更新全选复选框状态
  2605. const allItems = document.querySelectorAll(`.cascade-edge-item input[data-level="${{level}}"]`);
  2606. const checkedItems = document.querySelectorAll(`.cascade-edge-item input[data-level="${{level}}"]:checked`);
  2607. const selectAllCb = document.querySelector(`.select-all input[data-level="${{level}}"]`);
  2608. selectAllCb.checked = allItems.length === checkedItems.length;
  2609. // 重新渲染
  2610. if (currentEgoCenterNodeId) {{
  2611. handleNodeClick(currentEgoCenterNodeId, currentEgoCenterNodeName);
  2612. }}
  2613. }}
  2614. // 重置所有层级到默认配置(1级全选,2/3级只选包含)
  2615. function resetSelection() {{
  2616. event.stopPropagation();
  2617. // Level 1: 全选
  2618. document.querySelectorAll('.cascade-edge-item input[data-level="1"]').forEach(cb => {{
  2619. cb.checked = true;
  2620. }});
  2621. document.querySelector('.select-all input[data-level="1"]').checked = true;
  2622. // Level 2 & 3: 只选包含
  2623. [2, 3].forEach(level => {{
  2624. document.querySelectorAll(`.cascade-edge-item input[data-level="${{level}}"]`).forEach(cb => {{
  2625. cb.checked = (cb.dataset.type === "包含");
  2626. }});
  2627. document.querySelector(`.select-all input[data-level="${{level}}"]`).checked = false;
  2628. }});
  2629. // 重新渲染
  2630. if (currentEgoCenterNodeId) {{
  2631. handleNodeClick(currentEgoCenterNodeId, currentEgoCenterNodeName);
  2632. }}
  2633. }}
  2634. // 选择层级
  2635. function selectLevel(level) {{
  2636. event.stopPropagation();
  2637. currentLevelCount = level;
  2638. // 更新层级选中状态
  2639. document.querySelectorAll('.cascade-level-item').forEach(item => {{
  2640. const itemLevel = parseInt(item.dataset.level);
  2641. item.classList.toggle('active', itemLevel === level);
  2642. }});
  2643. // 显示对应的边类型组(1级显示L1,2级显示L1+L2,3级显示L1+L2+L3)
  2644. document.querySelectorAll('.cascade-edge-group').forEach(group => {{
  2645. const groupLevel = parseInt(group.dataset.level);
  2646. group.classList.toggle('active', groupLevel <= level);
  2647. }});
  2648. // 更新按钮显示
  2649. document.getElementById('cascade-label').textContent = level + '级';
  2650. // 重新渲染关系图和人设树高亮
  2651. if (currentEgoCenterNodeId) {{
  2652. handleNodeClick(currentEgoCenterNodeId, currentEgoCenterNodeName);
  2653. }}
  2654. }}
  2655. // 获取指定层级选中的边类型
  2656. function getLevelEdgeTypes(level) {{
  2657. const types = [];
  2658. document.querySelectorAll(`.cascade-edge-item input[data-level="${{level}}"]:checked`).forEach(cb => {{
  2659. types.push(cb.dataset.type);
  2660. }});
  2661. return types;
  2662. }}
  2663. // 获取层级配置(返回每层的边类型数组)
  2664. function getLevelConfigs() {{
  2665. const configs = [];
  2666. for (let i = 1; i <= currentLevelCount; i++) {{
  2667. const types = getLevelEdgeTypes(i);
  2668. configs.push(types);
  2669. }}
  2670. return configs;
  2671. }}
  2672. // 多层级展开:收集指定层级内的所有节点和边(每层可指定不同边类型)
  2673. function collectNodesAndEdges(centerNodeId, levelConfigs) {{
  2674. const nodeIds = new Set([centerNodeId]);
  2675. const collectedEdges = [];
  2676. const visitedEdges = new Set();
  2677. let currentLayer = new Set([centerNodeId]);
  2678. for (let d = 0; d < levelConfigs.length; d++) {{
  2679. const edgeTypes = levelConfigs[d];
  2680. if (edgeTypes.length === 0) break;
  2681. const nextLayer = new Set();
  2682. personaTreeData.edges.forEach(e => {{
  2683. // 筛选边类型
  2684. if (!edgeTypes.includes(e.边类型)) return;
  2685. const edgeKey = `${{e.源节点ID}}-${{e.目标节点ID}}-${{e.边类型}}`;
  2686. if (visitedEdges.has(edgeKey)) return;
  2687. // 单向查找:只从源节点出发,沿边的方向查找
  2688. // 属于:子→父(从子出发找父)
  2689. // 包含:父→子(从父出发找子)
  2690. // 共现:A→B(从A出发找B)
  2691. if (currentLayer.has(e.源节点ID)) {{
  2692. visitedEdges.add(edgeKey);
  2693. collectedEdges.push({{...e, _level: d + 1}});
  2694. // 添加目标节点到下一层
  2695. if (!nodeIds.has(e.目标节点ID)) {{
  2696. nextLayer.add(e.目标节点ID);
  2697. nodeIds.add(e.目标节点ID);
  2698. }}
  2699. }}
  2700. }});
  2701. currentLayer = nextLayer;
  2702. if (nextLayer.size === 0) break;
  2703. }}
  2704. return {{ nodeIds, edges: collectedEdges, depth: levelConfigs.length }};
  2705. }}
  2706. function renderEgoGraph(centerNodeId, centerNodeName) {{
  2707. // 保存当前中心节点
  2708. currentEgoCenterNodeId = centerNodeId;
  2709. currentEgoCenterNodeName = centerNodeName;
  2710. // 显示关系图容器
  2711. document.getElementById("ego-container").style.display = "block";
  2712. // 获取关系图层组
  2713. const egoGroup = d3.select(".ego-graph-content");
  2714. if (egoGroup.empty()) return;
  2715. // 停止之前的模拟
  2716. if (currentEgoSimulation) {{
  2717. currentEgoSimulation.stop();
  2718. currentEgoSimulation = null;
  2719. }}
  2720. // 清除旧内容
  2721. egoGroup.selectAll("*").remove();
  2722. // 获取当前层级配置
  2723. const levelConfigs = getLevelConfigs();
  2724. // 更新顶部标题和统计
  2725. document.getElementById("ego-node-name").textContent = centerNodeName;
  2726. // 获取层半径
  2727. const radius = 160; // 固定半径
  2728. // 根据层级配置收集节点和边
  2729. const {{ nodeIds, edges: relatedEdges, depth }} = collectNodesAndEdges(centerNodeId, levelConfigs);
  2730. // 构建节点数据(确保中心节点始终包含)
  2731. const nodeMap = {{}};
  2732. personaTreeData.nodes.forEach(n => {{
  2733. if (nodeIds.has(n.节点ID) || n.节点ID === centerNodeId) {{
  2734. nodeMap[n.节点ID] = {{
  2735. id: n.节点ID,
  2736. name: n.节点名称,
  2737. type: n.节点类型,
  2738. level: n.节点层级,
  2739. isCenter: n.节点ID === centerNodeId
  2740. }};
  2741. }}
  2742. }});
  2743. const nodes = Object.values(nodeMap);
  2744. // 处理同一对节点间的多条边,分配不同弧度
  2745. const linksByPair = {{}};
  2746. relatedEdges.forEach(e => {{
  2747. // 用排序后的节点对作为key,确保A-B和B-A是同一对
  2748. const pairKey = [e.源节点ID, e.目标节点ID].sort().join("||");
  2749. if (!linksByPair[pairKey]) linksByPair[pairKey] = [];
  2750. linksByPair[pairKey].push(e);
  2751. }});
  2752. // 为每条边分配弧度索引
  2753. const links = [];
  2754. Object.values(linksByPair).forEach(pairEdges => {{
  2755. const count = pairEdges.length;
  2756. pairEdges.forEach((e, i) => {{
  2757. // 弧度:0表示直线,正负值表示向两侧弯曲
  2758. let curvature = 0;
  2759. if (count > 1) {{
  2760. // 多条边时,均匀分布弧度
  2761. curvature = (i - (count - 1) / 2) * 0.3;
  2762. }}
  2763. links.push({{
  2764. source: e.源节点ID,
  2765. target: e.目标节点ID,
  2766. type: e.边类型,
  2767. curvature: curvature
  2768. }});
  2769. }});
  2770. }});
  2771. // 根据节点数量动态计算实际使用的半径
  2772. const nodeCount = nodes.length;
  2773. const nodeSpacingEgo = 65; // 节点间距(增大)
  2774. const minEgoRadius = 120;
  2775. const maxEgoRadius = Math.max(radius, 250); // 允许更大的半径
  2776. let actualRadius;
  2777. if (nodeCount <= 1) {{
  2778. actualRadius = minEgoRadius;
  2779. }} else {{
  2780. const circumference = nodeCount * nodeSpacingEgo;
  2781. const calcR = circumference / (2 * Math.PI);
  2782. actualRadius = Math.max(minEgoRadius, Math.min(maxEgoRadius, calcR));
  2783. }}
  2784. // 更新顶部统计信息
  2785. document.getElementById("ego-stats").textContent = `${{nodeCount}}节点 ${{relatedEdges.length}}边`;
  2786. // 如果只有中心节点,只渲染中心节点
  2787. if (nodes.length === 1) {{
  2788. const centerNode = nodes[0];
  2789. // 获取中心节点的维度颜色
  2790. const dimColors = {{
  2791. "灵感点": "#f39c12",
  2792. "目的点": "#3498db",
  2793. "关键点": "#9b59b6"
  2794. }};
  2795. const level = centerNode.level || "";
  2796. let fillColor = "#888";
  2797. if (level.includes("灵感点")) fillColor = dimColors["灵感点"];
  2798. else if (level.includes("目的点")) fillColor = dimColors["目的点"];
  2799. else if (level.includes("关键点")) fillColor = dimColors["关键点"];
  2800. // 绘制中心节点
  2801. const nodeGroup = egoGroup.append("g")
  2802. .attr("class", "ego-node-group")
  2803. .attr("transform", "translate(0, 0)");
  2804. nodeGroup.append("circle")
  2805. .attr("r", 22)
  2806. .attr("fill", fillColor)
  2807. .attr("stroke", "#fff")
  2808. .attr("stroke-width", 3)
  2809. .attr("cursor", "pointer")
  2810. .style("filter", "drop-shadow(0 2px 4px rgba(0,0,0,0.3))");
  2811. nodeGroup.append("text")
  2812. .attr("dy", "0.35em")
  2813. .attr("text-anchor", "middle")
  2814. .attr("fill", "#fff")
  2815. .attr("font-size", "10px")
  2816. .attr("font-weight", "bold")
  2817. .attr("pointer-events", "none")
  2818. .text(centerNode.name.length > 4 ? centerNode.name.slice(0, 4) + "..." : centerNode.name);
  2819. // 显示提示文字
  2820. egoGroup.append("text")
  2821. .attr("y", 50)
  2822. .attr("text-anchor", "middle")
  2823. .attr("fill", "rgba(255,255,255,0.4)")
  2824. .attr("font-size", "10px")
  2825. .text("无相关边");
  2826. return;
  2827. }}
  2828. // 边类型颜色(统一用实线)
  2829. const edgeColors = {{
  2830. "属于": "#9b59b6", // 紫色 - 层级关系
  2831. "包含": "#ffb6c1", // 淡粉 - 分类包含标签(向下)
  2832. "分类共现(跨点)": "#2ecc71", // 绿色 - 跨帖子分类共现
  2833. "分类共现(点内)": "#3498db", // 蓝色 - 同帖子分类共现
  2834. "标签共现": "#f39c12" // 橙色 - 标签共现
  2835. }};
  2836. // 维度颜色(与人设树完全一致)
  2837. const dimColors = {{
  2838. "灵感点": "#f39c12",
  2839. "目的点": "#3498db",
  2840. "关键点": "#9b59b6"
  2841. }};
  2842. // 获取节点的维度颜色(与人设树一致)
  2843. function getNodeDimColor(d) {{
  2844. // 根据节点层级判断维度
  2845. const level = d.level || "";
  2846. if (level.includes("灵感点")) return dimColors["灵感点"];
  2847. if (level.includes("目的点")) return dimColors["目的点"];
  2848. if (level.includes("关键点")) return dimColors["关键点"];
  2849. return "#888";
  2850. }}
  2851. // 获取节点填充色(实心,用维度颜色,不因选中而改变)
  2852. function getNodeFill(d) {{
  2853. return getNodeDimColor(d); // 始终用维度颜色填充
  2854. }}
  2855. // 获取节点边框色(选中节点用白色边框区分)
  2856. function getNodeStroke(d) {{
  2857. if (d.isCenter) return "#fff"; // 选中节点白色边框
  2858. return "rgba(255,255,255,0.5)"; // 普通节点半透明白边框
  2859. }}
  2860. // 获取节点边框粗细(选中节点更粗)
  2861. function getNodeStrokeWidth(d) {{
  2862. return d.isCenter ? 3 : 1.5;
  2863. }}
  2864. // 根据节点数量调整力模拟参数
  2865. const linkDistance = Math.max(50, Math.min(80, actualRadius / 2.5));
  2866. const chargeStrength = Math.max(-300, Math.min(-100, -nodeCount * 10));
  2867. const collisionRadius = 35; // 碰撞半径,防止重叠
  2868. // 创建力导向模拟(中心在0,0因为已经平移了)
  2869. const simulation = d3.forceSimulation(nodes)
  2870. .force("link", d3.forceLink(links).id(d => d.id).distance(linkDistance))
  2871. .force("charge", d3.forceManyBody().strength(chargeStrength))
  2872. .force("center", d3.forceCenter(0, 0))
  2873. .force("collision", d3.forceCollide().radius(collisionRadius))
  2874. .force("boundary", function() {{
  2875. // 限制节点在圆形区域内
  2876. const maxR = actualRadius - 30;
  2877. return function(alpha) {{
  2878. nodes.forEach(d => {{
  2879. const dist = Math.sqrt(d.x * d.x + d.y * d.y);
  2880. if (dist > maxR) {{
  2881. const scale = maxR / dist;
  2882. d.x *= scale;
  2883. d.y *= scale;
  2884. }}
  2885. }});
  2886. }};
  2887. }}());
  2888. currentEgoSimulation = simulation;
  2889. // 绘制边(用曲线支持多边)
  2890. const link = egoGroup.selectAll(".ego-edge")
  2891. .data(links)
  2892. .join("path")
  2893. .attr("class", "ego-edge")
  2894. .attr("stroke", d => edgeColors[d.type] || "#666")
  2895. .attr("stroke-width", 1.5)
  2896. .attr("stroke-opacity", 0.7)
  2897. .attr("fill", "none");
  2898. // 绘制节点(分类用方形,标签用圆形)
  2899. const node = egoGroup.selectAll(".ego-node")
  2900. .data(nodes)
  2901. .join("g")
  2902. .attr("class", d => "ego-node" + (d.isCenter ? " center" : ""));
  2903. // 根据节点类型绘制不同形状(与人设树样式一致)
  2904. const nodeSize = 8;
  2905. node.each(function(d) {{
  2906. const el = d3.select(this);
  2907. const fill = getNodeFill(d);
  2908. const stroke = getNodeStroke(d);
  2909. const size = d.isCenter ? nodeSize + 2 : nodeSize;
  2910. const strokeWidth = getNodeStrokeWidth(d);
  2911. if (d.type === "分类") {{
  2912. // 方形(分类节点)- 与人设树一致
  2913. el.append("rect")
  2914. .attr("class", "ego-shape")
  2915. .attr("width", size * 2)
  2916. .attr("height", size * 2)
  2917. .attr("x", -size)
  2918. .attr("y", -size)
  2919. .attr("fill", fill)
  2920. .attr("stroke", stroke)
  2921. .attr("stroke-width", strokeWidth)
  2922. .attr("rx", 1);
  2923. }} else {{
  2924. // 圆形(标签节点)- 与人设树一致
  2925. el.append("circle")
  2926. .attr("class", "ego-shape")
  2927. .attr("r", size)
  2928. .attr("fill", fill)
  2929. .attr("stroke", stroke)
  2930. .attr("stroke-width", strokeWidth);
  2931. }}
  2932. }});
  2933. node.append("text")
  2934. .attr("dy", -12)
  2935. .attr("text-anchor", "middle")
  2936. .attr("font-size", "9px")
  2937. .attr("fill", "#fff")
  2938. .text(d => d.name.length > 6 ? d.name.substring(0, 6) + ".." : d.name);
  2939. // 添加点击事件(直接调用共享函数)
  2940. node.on("click", function(event, d) {{
  2941. event.stopPropagation();
  2942. handleNodeClick(d.id, d.name);
  2943. }})
  2944. .on("mouseenter", function(event, d) {{
  2945. // 悬停高亮:高亮到激活节点的路径
  2946. if (!currentEgoCenterNodeId || d.id === currentEgoCenterNodeId) return;
  2947. highlightPathInEgoGraph(d.id);
  2948. }})
  2949. .on("mouseleave", function(event, d) {{
  2950. // 移出时恢复
  2951. if (!currentEgoCenterNodeId) return;
  2952. resetEgoGraphHighlight();
  2953. }});
  2954. // 边点击事件(直接调用共享函数)
  2955. link.on("click", function(event, d) {{
  2956. event.stopPropagation();
  2957. handleEdgeClick(d.source.id, d.target.id, d.type);
  2958. }});
  2959. // 生成曲线路径的函数
  2960. function linkPath(d) {{
  2961. const sx = d.source.x, sy = d.source.y;
  2962. const tx = d.target.x, ty = d.target.y;
  2963. if (d.curvature === 0) {{
  2964. // 直线
  2965. return `M${{sx}},${{sy}}L${{tx}},${{ty}}`;
  2966. }} else {{
  2967. // 曲线:计算控制点
  2968. const dx = tx - sx, dy = ty - sy;
  2969. const dist = Math.sqrt(dx * dx + dy * dy);
  2970. // 控制点垂直于连线方向偏移
  2971. const mx = (sx + tx) / 2;
  2972. const my = (sy + ty) / 2;
  2973. const offset = d.curvature * dist * 0.5;
  2974. // 垂直方向单位向量
  2975. const nx = -dy / dist, ny = dx / dist;
  2976. const cx = mx + nx * offset;
  2977. const cy = my + ny * offset;
  2978. return `M${{sx}},${{sy}}Q${{cx}},${{cy}} ${{tx}},${{ty}}`;
  2979. }}
  2980. }}
  2981. // 更新位置
  2982. simulation.on("tick", () => {{
  2983. link.attr("d", linkPath);
  2984. node.attr("transform", d => `translate(${{d.x}},${{d.y}})`);
  2985. }});
  2986. }}
  2987. function clearEgoGraph() {{
  2988. const egoGroup = d3.select(".ego-graph-content");
  2989. if (!egoGroup.empty()) {{
  2990. egoGroup.selectAll("*").remove();
  2991. }}
  2992. // 隐藏关系图容器
  2993. document.getElementById("ego-container").style.display = "none";
  2994. // 停止模拟
  2995. if (currentEgoSimulation) {{
  2996. currentEgoSimulation.stop();
  2997. currentEgoSimulation = null;
  2998. }}
  2999. }}
  3000. // 在关系图中高亮从悬停节点到激活节点的路径
  3001. function highlightPathInEgoGraph(hoveredNodeId) {{
  3002. const egoGroup = d3.select(".ego-graph-content");
  3003. if (egoGroup.empty()) return;
  3004. // 获取关系图中的边数据
  3005. const egoEdges = egoGroup.selectAll(".ego-edge");
  3006. const egoNodes = egoGroup.selectAll(".ego-node");
  3007. if (egoEdges.empty()) return;
  3008. // 构建邻接表用于路径查找
  3009. const adjacency = {{}};
  3010. const edgeMap = {{}};
  3011. egoEdges.each(function(d) {{
  3012. const srcId = d.source.id || d.source;
  3013. const tgtId = d.target.id || d.target;
  3014. if (!adjacency[srcId]) adjacency[srcId] = [];
  3015. if (!adjacency[tgtId]) adjacency[tgtId] = [];
  3016. adjacency[srcId].push(tgtId);
  3017. adjacency[tgtId].push(srcId);
  3018. // 记录边(双向)
  3019. const key1 = `${{srcId}}|${{tgtId}}`;
  3020. const key2 = `${{tgtId}}|${{srcId}}`;
  3021. edgeMap[key1] = d;
  3022. edgeMap[key2] = d;
  3023. }});
  3024. // BFS找路径
  3025. const visited = new Set();
  3026. const parent = {{}};
  3027. const queue = [currentEgoCenterNodeId];
  3028. visited.add(currentEgoCenterNodeId);
  3029. let found = false;
  3030. while (queue.length > 0 && !found) {{
  3031. const curr = queue.shift();
  3032. const neighbors = adjacency[curr] || [];
  3033. for (const next of neighbors) {{
  3034. if (!visited.has(next)) {{
  3035. visited.add(next);
  3036. parent[next] = curr;
  3037. queue.push(next);
  3038. if (next === hoveredNodeId) {{
  3039. found = true;
  3040. break;
  3041. }}
  3042. }}
  3043. }}
  3044. }}
  3045. if (!found) return;
  3046. // 回溯路径
  3047. const pathNodes = new Set();
  3048. const pathEdgeKeys = new Set();
  3049. let curr = hoveredNodeId;
  3050. while (curr !== undefined) {{
  3051. pathNodes.add(curr);
  3052. const prev = parent[curr];
  3053. if (prev !== undefined) {{
  3054. pathEdgeKeys.add(`${{prev}}|${{curr}}`);
  3055. pathEdgeKeys.add(`${{curr}}|${{prev}}`);
  3056. }}
  3057. curr = prev;
  3058. }}
  3059. // 隐藏不在路径上的边(保持布局不变)
  3060. egoEdges
  3061. .style("visibility", function(d) {{
  3062. const srcId = d.source.id || d.source;
  3063. const tgtId = d.target.id || d.target;
  3064. const key = `${{srcId}}|${{tgtId}}`;
  3065. return pathEdgeKeys.has(key) ? "visible" : "hidden";
  3066. }});
  3067. // 隐藏不在路径上的节点(保持布局不变)
  3068. egoNodes
  3069. .style("visibility", function(d) {{
  3070. return pathNodes.has(d.id) ? "visible" : "hidden";
  3071. }});
  3072. }}
  3073. // 恢复关系图的高亮状态
  3074. function resetEgoGraphHighlight() {{
  3075. const egoGroup = d3.select(".ego-graph-content");
  3076. if (egoGroup.empty()) return;
  3077. // 恢复边的可见性
  3078. egoGroup.selectAll(".ego-edge")
  3079. .style("visibility", "visible");
  3080. // 恢复节点的可见性
  3081. egoGroup.selectAll(".ego-node")
  3082. .style("visibility", "visible");
  3083. }}
  3084. // 渲染单条边和两个节点(点击树边时调用)
  3085. function renderEgoGraphEdge(edgeData, sourceNode, targetNode) {{
  3086. // 显示关系图容器
  3087. document.getElementById("ego-container").style.display = "block";
  3088. const egoGroup = d3.select(".ego-graph-content");
  3089. if (egoGroup.empty()) return;
  3090. // 停止之前的模拟
  3091. if (currentEgoSimulation) {{
  3092. currentEgoSimulation.stop();
  3093. currentEgoSimulation = null;
  3094. }}
  3095. // 清除旧内容
  3096. egoGroup.selectAll("*").remove();
  3097. // 更新顶部标题
  3098. document.getElementById("ego-node-name").textContent = edgeData.边类型;
  3099. document.getElementById("ego-stats").textContent = "2节点 1边";
  3100. const radius = 160;
  3101. // 边类型颜色
  3102. const edgeColors = {{
  3103. "属于": "#9b59b6",
  3104. "包含": "#ffb6c1",
  3105. "分类共现(跨点)": "#2ecc71",
  3106. "分类共现(点内)": "#3498db",
  3107. "标签共现": "#f39c12"
  3108. }};
  3109. // 维度颜色
  3110. const dimColors = {{
  3111. "灵感点": "#f39c12",
  3112. "目的点": "#3498db",
  3113. "关键点": "#9b59b6"
  3114. }};
  3115. // 获取节点颜色
  3116. function getNodeColor(nodeData) {{
  3117. const level = nodeData.节点层级 || "";
  3118. if (level.includes("灵感点")) return dimColors["灵感点"];
  3119. if (level.includes("目的点")) return dimColors["目的点"];
  3120. if (level.includes("关键点")) return dimColors["关键点"];
  3121. return "#888";
  3122. }}
  3123. // 两个节点的位置
  3124. const srcX = -60, srcY = 0;
  3125. const tgtX = 60, tgtY = 0;
  3126. // 绘制边
  3127. egoGroup.append("line")
  3128. .attr("class", "ego-edge")
  3129. .attr("x1", srcX)
  3130. .attr("y1", srcY)
  3131. .attr("x2", tgtX)
  3132. .attr("y2", tgtY)
  3133. .attr("stroke", edgeColors[edgeData.边类型] || "#666")
  3134. .attr("stroke-width", 3)
  3135. .attr("stroke-opacity", 0.8);
  3136. // 获取节点数据
  3137. const srcData = sourceNode ? sourceNode.data : {{}};
  3138. const tgtData = targetNode ? targetNode.data : {{}};
  3139. // 绘制源节点
  3140. const srcGroup = egoGroup.append("g")
  3141. .attr("class", "ego-node")
  3142. .attr("transform", `translate(${{srcX}}, ${{srcY}})`);
  3143. const srcSize = 15;
  3144. const srcColor = getNodeColor(srcData);
  3145. if (srcData.节点类型 === "分类") {{
  3146. srcGroup.append("rect")
  3147. .attr("width", srcSize * 2)
  3148. .attr("height", srcSize * 2)
  3149. .attr("x", -srcSize)
  3150. .attr("y", -srcSize)
  3151. .attr("fill", srcColor)
  3152. .attr("stroke", "rgba(255,255,255,0.5)")
  3153. .attr("stroke-width", 2)
  3154. .attr("rx", 2);
  3155. }} else {{
  3156. srcGroup.append("circle")
  3157. .attr("r", srcSize)
  3158. .attr("fill", srcColor)
  3159. .attr("stroke", "rgba(255,255,255,0.5)")
  3160. .attr("stroke-width", 2);
  3161. }}
  3162. srcGroup.append("text")
  3163. .attr("dy", -srcSize - 8)
  3164. .attr("text-anchor", "middle")
  3165. .attr("fill", "#fff")
  3166. .attr("font-size", "11px")
  3167. .text(srcData.节点名称 || srcData.name || "源节点");
  3168. // 绘制目标节点
  3169. const tgtGroup = egoGroup.append("g")
  3170. .attr("class", "ego-node")
  3171. .attr("transform", `translate(${{tgtX}}, ${{tgtY}})`);
  3172. const tgtSize = 15;
  3173. const tgtColor = getNodeColor(tgtData);
  3174. if (tgtData.节点类型 === "分类") {{
  3175. tgtGroup.append("rect")
  3176. .attr("width", tgtSize * 2)
  3177. .attr("height", tgtSize * 2)
  3178. .attr("x", -tgtSize)
  3179. .attr("y", -tgtSize)
  3180. .attr("fill", tgtColor)
  3181. .attr("stroke", "rgba(255,255,255,0.5)")
  3182. .attr("stroke-width", 2)
  3183. .attr("rx", 2);
  3184. }} else {{
  3185. tgtGroup.append("circle")
  3186. .attr("r", tgtSize)
  3187. .attr("fill", tgtColor)
  3188. .attr("stroke", "rgba(255,255,255,0.5)")
  3189. .attr("stroke-width", 2);
  3190. }}
  3191. tgtGroup.append("text")
  3192. .attr("dy", -tgtSize - 8)
  3193. .attr("text-anchor", "middle")
  3194. .attr("fill", "#fff")
  3195. .attr("font-size", "11px")
  3196. .text(tgtData.节点名称 || tgtData.name || "目标节点");
  3197. // 边标签
  3198. egoGroup.append("text")
  3199. .attr("y", 25)
  3200. .attr("text-anchor", "middle")
  3201. .attr("fill", "rgba(255,255,255,0.6)")
  3202. .attr("font-size", "10px")
  3203. .text(edgeData.边类型);
  3204. }}
  3205. // 页面加载完成后初始化
  3206. window.addEventListener("load", init);
  3207. window.addEventListener("resize", () => {{
  3208. if (currentIndex >= 0) {{
  3209. renderGraph(allGraphData[currentIndex]);
  3210. }}
  3211. }});
  3212. </script>
  3213. </body>
  3214. </html>
  3215. '''
  3216. def generate_combined_html(all_graph_data: List[Dict], persona_tree_data: Dict, output_file: Path):
  3217. """
  3218. 生成包含所有帖子图谱的HTML文件
  3219. Args:
  3220. all_graph_data: 所有帖子的图谱数据列表
  3221. persona_tree_data: 完整的人设树数据(节点和边)
  3222. output_file: 输出文件路径
  3223. """
  3224. # 生成Tab HTML
  3225. tabs_html = ""
  3226. for i, data in enumerate(all_graph_data):
  3227. post_title = data.get("postTitle", "")
  3228. # 使用帖子标题,如果太长则截断
  3229. if post_title:
  3230. tab_name = post_title[:15] + "..." if len(post_title) > 15 else post_title
  3231. else:
  3232. tab_name = f"帖子 {i+1}"
  3233. active_class = "active" if i == 0 else ""
  3234. tabs_html += f'<div class="tab {active_class}" data-index="{i}">{tab_name}</div>\n'
  3235. # 生成HTML
  3236. html_content = HTML_TEMPLATE.format(
  3237. tabs_html=tabs_html,
  3238. all_graph_data=json.dumps(all_graph_data, ensure_ascii=False),
  3239. persona_tree_data=json.dumps(persona_tree_data, ensure_ascii=False)
  3240. )
  3241. with open(output_file, "w", encoding="utf-8") as f:
  3242. f.write(html_content)
  3243. def main():
  3244. # 使用路径配置
  3245. config = PathConfig()
  3246. print(f"账号: {config.account_name}")
  3247. print(f"输出版本: {config.output_version}")
  3248. print()
  3249. # 输入目录
  3250. match_graph_dir = config.intermediate_dir / "match_graph"
  3251. # 输出文件
  3252. output_file = config.intermediate_dir / "match_graph.html"
  3253. print(f"输入目录: {match_graph_dir}")
  3254. print(f"输出文件: {output_file}")
  3255. print()
  3256. # 读取人设树中间数据
  3257. persona_tree_file = config.intermediate_dir / "persona_tree.json"
  3258. persona_tree_data = {"nodes": [], "edges": []}
  3259. if persona_tree_file.exists():
  3260. print(f"读取人设树数据: {persona_tree_file.name}")
  3261. with open(persona_tree_file, "r", encoding="utf-8") as f:
  3262. tree_data = json.load(f)
  3263. persona_tree_data["nodes"] = tree_data.get("nodes", [])
  3264. persona_tree_data["edges"] = tree_data.get("edges", [])
  3265. category_count = len([n for n in persona_tree_data["nodes"] if n.get("节点类型") == "分类"])
  3266. tag_count = len([n for n in persona_tree_data["nodes"] if n.get("节点类型") == "标签"])
  3267. print(f" 分类节点: {category_count}, 标签节点: {tag_count}")
  3268. print(f" 边数: {len(persona_tree_data['edges'])}")
  3269. print()
  3270. # 读取所有匹配图谱文件
  3271. graph_files = sorted(match_graph_dir.glob("*_match_graph.json"))
  3272. print(f"找到 {len(graph_files)} 个匹配图谱文件")
  3273. all_graph_data = []
  3274. for i, graph_file in enumerate(graph_files, 1):
  3275. print(f" [{i}/{len(graph_files)}] 读取: {graph_file.name}")
  3276. with open(graph_file, "r", encoding="utf-8") as f:
  3277. match_graph_data = json.load(f)
  3278. # 提取需要的数据
  3279. graph_data = {
  3280. "postId": match_graph_data["说明"]["帖子ID"],
  3281. "postTitle": match_graph_data["说明"].get("帖子标题", ""),
  3282. "stats": match_graph_data["说明"]["统计"],
  3283. "nodes": match_graph_data["节点列表"],
  3284. "edges": match_graph_data["边列表"]
  3285. }
  3286. all_graph_data.append(graph_data)
  3287. # 生成HTML
  3288. print("\n生成HTML文件...")
  3289. generate_combined_html(all_graph_data, persona_tree_data, output_file)
  3290. print("\n" + "="*60)
  3291. print("处理完成!")
  3292. print(f"输出文件: {output_file}")
  3293. if __name__ == "__main__":
  3294. main()