visualize_match_graph.py 230 KB

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