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