visualize_match_graph.py 229 KB

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