visualize_match_graph.py 230 KB

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