visualize_match_graph.py 230 KB

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