| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838 |
- #!/usr/bin/env python3
- # -*- coding: utf-8 -*-
- """
- 将匹配图谱数据可视化为交互式HTML文件
- 输入:match_graph目录下的JSON文件
- 输出:单个HTML文件,包含所有帖子的图谱,可通过Tab切换
- """
- import json
- from pathlib import Path
- from typing import Dict, List
- import sys
- # 添加项目根目录到路径
- project_root = Path(__file__).parent.parent.parent
- sys.path.insert(0, str(project_root))
- from script.data_processing.path_config import PathConfig
- HTML_TEMPLATE = '''<!DOCTYPE html>
- <html lang="zh-CN">
- <head>
- <meta charset="UTF-8">
- <meta name="viewport" content="width=device-width, initial-scale=1.0">
- <title>匹配图谱可视化</title>
- <script src="https://d3js.org/d3.v7.min.js"></script>
- <style>
- * {{
- margin: 0;
- padding: 0;
- box-sizing: border-box;
- }}
- body {{
- font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif;
- background: #1a1a2e;
- color: #eee;
- overflow: hidden;
- }}
- /* 自定义滚动条 */
- ::-webkit-scrollbar {{
- width: 6px;
- height: 6px;
- }}
- ::-webkit-scrollbar-track {{
- background: transparent;
- }}
- ::-webkit-scrollbar-thumb {{
- background: rgba(255,255,255,0.2);
- border-radius: 3px;
- }}
- ::-webkit-scrollbar-thumb:hover {{
- background: rgba(255,255,255,0.3);
- }}
- #container {{
- display: flex;
- height: 100vh;
- flex-direction: column;
- }}
- /* Tab样式 */
- .tabs {{
- display: flex;
- background: #0f3460;
- padding: 0 20px;
- overflow-x: auto;
- flex-shrink: 0;
- }}
- .tab {{
- padding: 12px 20px;
- cursor: pointer;
- border-bottom: 3px solid transparent;
- white-space: nowrap;
- font-size: 13px;
- color: #888;
- transition: all 0.2s;
- }}
- .tab:hover {{
- color: #fff;
- background: rgba(255,255,255,0.05);
- }}
- .tab.active {{
- color: #e94560;
- border-bottom-color: #e94560;
- background: rgba(233, 69, 96, 0.1);
- }}
- /* 主内容区 */
- .main-content {{
- display: flex;
- flex: 1;
- overflow: hidden;
- }}
- #left-panel {{
- width: 420px;
- display: flex;
- flex-direction: column;
- border-right: 1px solid #0f3460;
- }}
- #tree-container {{
- flex: 1;
- overflow-y: auto;
- overflow-x: hidden;
- }}
- #tree-container svg {{
- display: block;
- }}
- #ego-container {{
- height: 420px;
- border-top: 1px solid #0f3460;
- display: none;
- position: relative;
- }}
- #ego-container svg {{
- display: block;
- }}
- .ego-controls {{
- position: absolute;
- top: 5px;
- left: 5px;
- right: 5px;
- z-index: 10;
- display: flex;
- justify-content: space-between;
- align-items: center;
- font-size: 10px;
- }}
- .ego-title-center {{
- color: #e94560;
- font-weight: bold;
- font-size: 12px;
- text-align: center;
- flex: 1;
- }}
- .ego-stats {{
- color: #8892b0;
- font-size: 10px;
- white-space: nowrap;
- }}
- .ego-controls label {{
- color: #8892b0;
- display: flex;
- align-items: center;
- gap: 3px;
- }}
- .ego-controls select {{
- background: #0f3460;
- color: #e6e6e6;
- border: 1px solid #1a1a2e;
- border-radius: 3px;
- padding: 3px 6px;
- font-size: 10px;
- cursor: pointer;
- }}
- .cascade-dropdown {{
- position: relative;
- }}
- .cascade-btn {{
- background: #0f3460;
- color: #e6e6e6;
- border: 1px solid #1a1a2e;
- border-radius: 3px;
- padding: 4px 10px;
- font-size: 10px;
- cursor: pointer;
- display: flex;
- align-items: center;
- gap: 6px;
- }}
- .cascade-btn:hover {{
- background: #1a4a7a;
- }}
- .cascade-btn::after {{
- content: "▼";
- font-size: 8px;
- opacity: 0.6;
- }}
- .cascade-menu {{
- position: absolute;
- top: 100%;
- left: 0;
- background: #0f3460;
- border: 1px solid #1a1a2e;
- border-radius: 3px;
- display: none;
- z-index: 100;
- box-shadow: 0 4px 12px rgba(0,0,0,0.3);
- flex-direction: row;
- }}
- .cascade-menu.show {{
- display: flex;
- }}
- .cascade-levels {{
- border-right: 1px solid #1a1a2e;
- padding: 4px 0;
- min-width: 50px;
- }}
- .cascade-level-item {{
- padding: 6px 12px;
- cursor: pointer;
- color: #e6e6e6;
- font-size: 10px;
- display: flex;
- align-items: center;
- justify-content: space-between;
- }}
- .cascade-level-item:hover {{
- background: rgba(233, 69, 96, 0.2);
- }}
- .cascade-level-item.active {{
- background: rgba(233, 69, 96, 0.3);
- color: #e94560;
- }}
- .cascade-level-item::after {{
- content: "›";
- margin-left: 8px;
- opacity: 0.5;
- }}
- .cascade-edges {{
- padding: 4px 0;
- min-width: 100px;
- max-height: 300px;
- overflow-y: auto;
- }}
- .cascade-edge-group {{
- display: none;
- }}
- .cascade-edge-group.active {{
- display: block;
- }}
- .cascade-edge-group-header {{
- color: #e94560;
- font-weight: bold;
- font-size: 9px;
- padding: 4px 10px 2px;
- display: flex;
- align-items: center;
- justify-content: space-between;
- }}
- .select-all {{
- font-weight: normal;
- color: #8892b0;
- font-size: 9px;
- cursor: pointer;
- display: flex;
- align-items: center;
- gap: 3px;
- }}
- .select-all input {{
- width: 10px;
- height: 10px;
- cursor: pointer;
- }}
- .header-actions {{
- display: flex;
- align-items: center;
- gap: 6px;
- }}
- .invert-btn, .reset-btn {{
- color: #8892b0;
- cursor: pointer;
- font-size: 9px;
- }}
- .invert-btn:hover {{
- color: #e94560;
- }}
- .reset-btn:hover {{
- color: #2ecc71;
- }}
- .cascade-edge-item {{
- display: flex;
- align-items: center;
- gap: 6px;
- padding: 4px 10px;
- cursor: pointer;
- color: #e6e6e6;
- font-size: 10px;
- }}
- .cascade-edge-item:hover {{
- background: rgba(233, 69, 96, 0.15);
- }}
- .cascade-edge-item input {{
- display: none;
- }}
- .cascade-edge-item .edge-color {{
- width: 12px;
- height: 12px;
- border-radius: 2px;
- border: 1px solid #333;
- opacity: 0.3;
- }}
- .cascade-edge-item input:checked + .edge-color {{
- opacity: 1;
- }}
- #graph {{
- flex: 1;
- position: relative;
- overflow: auto;
- }}
- #sidebar {{
- width: 300px;
- background: #16213e;
- padding: 15px;
- overflow-y: auto;
- border-left: 1px solid #0f3460;
- display: flex;
- flex-direction: column;
- }}
- .match-list-panel {{
- margin-bottom: 15px;
- border-bottom: 1px solid #0f3460;
- padding-bottom: 10px;
- }}
- .match-list-panel h3 {{
- font-size: 13px;
- margin-bottom: 8px;
- color: #e94560;
- }}
- .match-list {{
- max-height: 200px;
- overflow-y: auto;
- }}
- .match-item {{
- display: flex;
- align-items: center;
- padding: 6px 8px;
- margin-bottom: 4px;
- background: rgba(233, 69, 96, 0.1);
- border-radius: 4px;
- cursor: pointer;
- font-size: 11px;
- gap: 8px;
- }}
- .match-item:hover {{
- background: rgba(233, 69, 96, 0.2);
- }}
- .match-item.active {{
- background: rgba(233, 69, 96, 0.3);
- border: 1px solid #e94560;
- }}
- .match-item .score {{
- background: #e94560;
- color: #fff;
- padding: 2px 6px;
- border-radius: 3px;
- font-weight: bold;
- min-width: 40px;
- text-align: center;
- }}
- .match-item .score.high {{
- background: #27ae60;
- }}
- .match-item .score.medium {{
- background: #f39c12;
- }}
- .match-item .names {{
- flex: 1;
- overflow: hidden;
- text-overflow: ellipsis;
- white-space: nowrap;
- }}
- #persona-tree-panel {{
- flex: 1;
- overflow-y: auto;
- margin-top: 15px;
- border-top: 1px solid #0f3460;
- padding-top: 10px;
- }}
- .tree-dimension {{
- margin-bottom: 15px;
- }}
- .tree-dimension-title {{
- font-size: 12px;
- font-weight: bold;
- padding: 5px 8px;
- border-radius: 4px;
- margin-bottom: 5px;
- cursor: pointer;
- display: flex;
- align-items: center;
- gap: 5px;
- }}
- .tree-dimension-title:hover {{
- opacity: 0.8;
- }}
- .tree-dimension-title .toggle {{
- font-size: 10px;
- transition: transform 0.2s;
- }}
- .tree-dimension-title.collapsed .toggle {{
- transform: rotate(-90deg);
- }}
- .tree-dimension.inspiration .tree-dimension-title {{
- background: rgba(243, 156, 18, 0.2);
- color: #f39c12;
- }}
- .tree-dimension.purpose .tree-dimension-title {{
- background: rgba(52, 152, 219, 0.2);
- color: #3498db;
- }}
- .tree-dimension.key .tree-dimension-title {{
- background: rgba(155, 89, 182, 0.2);
- color: #9b59b6;
- }}
- .tree-list {{
- list-style: none;
- padding-left: 0;
- margin: 0;
- font-size: 11px;
- }}
- .tree-list.collapsed {{
- display: none;
- }}
- .tree-item {{
- padding: 3px 0;
- color: #aaa;
- cursor: pointer;
- border-radius: 3px;
- padding: 3px 6px;
- margin: 1px 0;
- }}
- .tree-item:hover {{
- background: rgba(255,255,255,0.08);
- color: #fff;
- }}
- .tree-item.matched {{
- color: #2ecc71;
- font-weight: 500;
- }}
- .tree-item .indent {{
- display: inline-block;
- width: 12px;
- color: #555;
- }}
- h1 {{
- font-size: 15px;
- margin-bottom: 10px;
- color: #e94560;
- }}
- h2 {{
- font-size: 12px;
- margin: 10px 0 6px;
- color: #0f9b8e;
- }}
- .legend {{
- margin-top: 10px;
- }}
- .legend-grid {{
- display: grid;
- grid-template-columns: 1fr 1fr;
- gap: 4px 8px;
- }}
- .legend-item {{
- display: flex;
- align-items: center;
- font-size: 11px;
- }}
- .legend-color {{
- width: 12px;
- height: 12px;
- border-radius: 50%;
- margin-right: 6px;
- flex-shrink: 0;
- }}
- .legend-line {{
- width: 20px;
- height: 3px;
- margin-right: 6px;
- flex-shrink: 0;
- }}
- .detail-panel {{
- margin-top: 20px;
- padding: 15px;
- background: #0f3460;
- border-radius: 8px;
- display: none;
- }}
- .detail-panel.active {{
- display: block;
- }}
- .detail-panel h3 {{
- font-size: 14px;
- margin-bottom: 10px;
- color: #e94560;
- }}
- .detail-panel p {{
- font-size: 12px;
- line-height: 1.6;
- color: #ccc;
- margin: 5px 0;
- }}
- .detail-panel .label {{
- color: #888;
- }}
- .detail-panel .close-btn {{
- position: absolute;
- top: 10px;
- right: 10px;
- background: none;
- border: none;
- color: #888;
- cursor: pointer;
- font-size: 16px;
- }}
- .detail-panel .close-btn:hover {{
- color: #e94560;
- }}
- .detail-panel-wrapper {{
- position: relative;
- }}
- .similarity-score {{
- background: #e94560;
- color: #fff;
- padding: 2px 6px;
- border-radius: 4px;
- font-weight: bold;
- }}
- .edge-description {{
- background: #1a1a2e;
- padding: 10px;
- border-radius: 4px;
- margin-top: 8px;
- font-size: 11px;
- line-height: 1.5;
- }}
- .edge-list {{
- background: #1a1a2e;
- padding: 8px;
- border-radius: 4px;
- margin-top: 4px;
- font-size: 11px;
- }}
- .edge-type-item {{
- display: flex;
- justify-content: space-between;
- padding: 2px 0;
- border-bottom: 1px solid rgba(255,255,255,0.05);
- }}
- .edge-type {{
- color: #aaa;
- }}
- .edge-count {{
- color: #e94560;
- font-weight: bold;
- }}
- .edge-detail {{
- padding: 3px 0;
- color: #888;
- font-size: 10px;
- border-left: 2px solid #333;
- padding-left: 8px;
- margin: 2px 0;
- }}
- .edge-type-tag {{
- background: rgba(255,255,255,0.1);
- padding: 1px 4px;
- border-radius: 2px;
- font-size: 9px;
- margin-left: 4px;
- }}
- .edge-more {{
- color: #666;
- font-size: 10px;
- text-align: center;
- padding: 4px 0;
- }}
- .edge-empty {{
- color: #555;
- font-size: 10px;
- padding: 4px 0;
- }}
- svg {{
- width: 100%;
- display: block; /* 避免底部多余空间 */
- }}
- .node {{
- cursor: pointer;
- }}
- .node circle, .node rect, .node polygon {{
- stroke-width: 3px;
- }}
- .node .post-point-node {{
- stroke: #fff;
- stroke-width: 4px;
- }}
- .node .post-node,
- .node .persona-node {{
- stroke: #fff;
- }}
- .node text {{
- font-size: 11px;
- fill: #fff;
- pointer-events: none;
- }}
- .link {{
- stroke-opacity: 0.7;
- }}
- .link-hitarea {{
- stroke: transparent;
- stroke-width: 15px;
- cursor: pointer;
- fill: none;
- }}
- .link-hitarea:hover + .link {{
- stroke-opacity: 1;
- stroke-width: 3px;
- }}
- .edge-label {{
- font-size: 10px;
- fill: #fff;
- pointer-events: none;
- text-anchor: middle;
- }}
- .edge-label-bg {{
- fill: rgba(0,0,0,0.7);
- }}
- .link.match-same {{
- stroke: #e94560;
- }}
- .link.match-similar {{
- stroke: #e94560;
- stroke-dasharray: 5,5;
- }}
- .link.category-cross {{
- stroke: #2ecc71;
- }}
- .link.category-intra {{
- stroke: #3498db;
- }}
- .link.tag-cooccur {{
- stroke: #f39c12;
- }}
- .link.belong {{
- stroke: #9b59b6;
- }}
- .link.contain {{
- stroke: #8e44ad;
- stroke-dasharray: 2,2;
- }}
- /* 镜像边样式(实线,颜色与原边相同) */
- .link.mirror-category-cross {{
- stroke: #2ecc71;
- }}
- .link.mirror-category-intra {{
- stroke: #3498db;
- }}
- .link.mirror-tag-cooccur {{
- stroke: #f39c12;
- }}
- .link.mirror-belong {{
- stroke: #9b59b6;
- }}
- .link.mirror-contain {{
- stroke: #8e44ad;
- }}
- /* 二阶边现在使用与镜像边相同的样式(基于原始边类型) */
- /* 高亮/灰化样式 */
- .node.dimmed circle, .node.dimmed rect, .node.dimmed polygon {{
- opacity: 0.15 !important;
- }}
- .node.dimmed text {{
- opacity: 0.15 !important;
- }}
- .link-group.dimmed .link {{
- stroke-opacity: 0.08 !important;
- }}
- .link-group.dimmed .edge-label-group {{
- opacity: 0.15 !important;
- }}
- .node.highlighted circle, .node.highlighted rect, .node.highlighted polygon {{
- stroke: #fff !important;
- stroke-width: 4px !important;
- filter: drop-shadow(0 0 8px rgba(255,255,255,0.5));
- }}
- .link-group.highlighted .link {{
- stroke-opacity: 1 !important;
- stroke-width: 3px !important;
- filter: drop-shadow(0 0 4px rgba(255,255,255,0.3));
- }}
- .tooltip {{
- position: absolute;
- background: rgba(0,0,0,0.9);
- color: #fff;
- padding: 10px 15px;
- border-radius: 6px;
- font-size: 12px;
- pointer-events: none;
- max-width: 300px;
- z-index: 1000;
- display: none;
- }}
- .controls {{
- background: rgba(15, 52, 96, 0.5);
- padding: 12px;
- border-radius: 8px;
- margin-top: auto;
- border-top: 1px solid #0f3460;
- padding-top: 15px;
- }}
- .controls button {{
- background: #0f3460;
- color: #fff;
- border: none;
- padding: 8px 15px;
- margin: 5px;
- border-radius: 4px;
- cursor: pointer;
- font-size: 12px;
- }}
- .controls button:hover {{
- background: #e94560;
- }}
- .controls button.active {{
- background: #e94560;
- }}
- .controls .control-group {{
- margin-top: 10px;
- padding-top: 10px;
- border-top: 1px solid rgba(255,255,255,0.1);
- }}
- .controls .control-label {{
- font-size: 11px;
- color: #888;
- margin-bottom: 5px;
- }}
- .controls select {{
- background: #0f3460;
- color: #fff;
- border: none;
- padding: 6px 10px;
- border-radius: 4px;
- font-size: 12px;
- cursor: pointer;
- }}
- /* 关系子图节点样式 */
- .ego-node {{
- cursor: pointer;
- }}
- .ego-node circle {{
- stroke-width: 2px;
- }}
- .ego-node.center circle {{
- stroke: #fff;
- stroke-width: 3px;
- filter: drop-shadow(0 0 8px rgba(255,255,255,0.5));
- }}
- .ego-node text {{
- font-size: 10px;
- fill: #fff;
- pointer-events: none;
- }}
- .ego-edge {{
- stroke-opacity: 0.6;
- stroke-width: 1.5;
- }}
- </style>
- </head>
- <body>
- <div id="container">
- <div class="tabs" id="tabs">
- {tabs_html}
- </div>
- <div class="main-content">
- <div id="left-panel">
- <div id="tree-container"></div>
- <div id="ego-container">
- <div class="ego-controls">
- <div class="cascade-dropdown">
- <div class="cascade-btn" onclick="toggleCascadeMenu()">
- <span id="cascade-label">1级</span>
- </div>
- <div class="cascade-menu" id="cascade-menu">
- <div class="cascade-levels">
- <div class="cascade-level-item active" data-level="1" onclick="selectLevel(1)">1级</div>
- <div class="cascade-level-item" data-level="2" onclick="selectLevel(2)">2级</div>
- <div class="cascade-level-item" data-level="3" onclick="selectLevel(3)">3级</div>
- </div>
- <div class="cascade-edges">
- <div class="cascade-edge-group active" data-level="1">
- <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>
- <label class="cascade-edge-item"><input type="checkbox" data-level="1" data-type="属于" checked><span class="edge-color" style="background:#9b59b6"></span>属于</label>
- <label class="cascade-edge-item"><input type="checkbox" data-level="1" data-type="包含" checked><span class="edge-color" style="background:#ffb6c1"></span>包含</label>
- <label class="cascade-edge-item"><input type="checkbox" data-level="1" data-type="分类共现(跨点)" checked><span class="edge-color" style="background:#2ecc71"></span>跨点共现</label>
- <label class="cascade-edge-item"><input type="checkbox" data-level="1" data-type="分类共现(点内)" checked><span class="edge-color" style="background:#3498db"></span>点内共现</label>
- <label class="cascade-edge-item"><input type="checkbox" data-level="1" data-type="标签共现" checked><span class="edge-color" style="background:#f39c12"></span>标签共现</label>
- </div>
- <div class="cascade-edge-group" data-level="2">
- <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>
- <label class="cascade-edge-item"><input type="checkbox" data-level="2" data-type="属于"><span class="edge-color" style="background:#9b59b6"></span>属于</label>
- <label class="cascade-edge-item"><input type="checkbox" data-level="2" data-type="包含" checked><span class="edge-color" style="background:#ffb6c1"></span>包含</label>
- <label class="cascade-edge-item"><input type="checkbox" data-level="2" data-type="分类共现(跨点)"><span class="edge-color" style="background:#2ecc71"></span>跨点共现</label>
- <label class="cascade-edge-item"><input type="checkbox" data-level="2" data-type="分类共现(点内)"><span class="edge-color" style="background:#3498db"></span>点内共现</label>
- <label class="cascade-edge-item"><input type="checkbox" data-level="2" data-type="标签共现"><span class="edge-color" style="background:#f39c12"></span>标签共现</label>
- </div>
- <div class="cascade-edge-group" data-level="3">
- <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>
- <label class="cascade-edge-item"><input type="checkbox" data-level="3" data-type="属于"><span class="edge-color" style="background:#9b59b6"></span>属于</label>
- <label class="cascade-edge-item"><input type="checkbox" data-level="3" data-type="包含" checked><span class="edge-color" style="background:#ffb6c1"></span>包含</label>
- <label class="cascade-edge-item"><input type="checkbox" data-level="3" data-type="分类共现(跨点)"><span class="edge-color" style="background:#2ecc71"></span>跨点共现</label>
- <label class="cascade-edge-item"><input type="checkbox" data-level="3" data-type="分类共现(点内)"><span class="edge-color" style="background:#3498db"></span>点内共现</label>
- <label class="cascade-edge-item"><input type="checkbox" data-level="3" data-type="标签共现"><span class="edge-color" style="background:#f39c12"></span>标签共现</label>
- </div>
- </div>
- </div>
- </div>
- <div class="ego-title-center" id="ego-node-name"></div>
- <div class="ego-stats" id="ego-stats"></div>
- </div>
- </div>
- </div>
- <div id="graph">
- <div class="tooltip" id="tooltip"></div>
- </div>
- <div id="sidebar">
- <h1>匹配图谱</h1>
- <div class="match-list-panel">
- <h3>匹配关系 <span id="matchCount">(0)</span></h3>
- <div id="matchList" class="match-list"></div>
- </div>
- <div class="detail-panel active" id="detailPanel">
- <h3 id="detailTitle">点击节点或边查看详情</h3>
- <div id="detailContent">
- <p style="color: #888; font-size: 11px;">点击图中的节点或边,这里会显示详细信息</p>
- </div>
- </div>
- <div class="legend">
- <h2>节点</h2>
- <div class="legend-grid">
- <div class="legend-item">
- <div class="legend-color" style="background: #f39c12; border: 2px solid #fff;"></div>
- <span>灵感点</span>
- </div>
- <div class="legend-item">
- <div class="legend-color" style="background: #3498db; border: 2px solid #fff;"></div>
- <span>目的点</span>
- </div>
- <div class="legend-item">
- <div class="legend-color" style="background: #9b59b6; border: 2px solid #fff;"></div>
- <span>关键点</span>
- </div>
- </div>
- <h2>边</h2>
- <div class="legend-grid">
- <div class="legend-item">
- <div class="legend-line" style="background: #e94560;"></div>
- <span>相同(≥0.8)</span>
- </div>
- <div class="legend-item">
- <div class="legend-line" style="background: linear-gradient(90deg, #e94560 0%, #e94560 40%, transparent 40%, transparent 60%, #e94560 60%);"></div>
- <span>相似(0.5-0.8)</span>
- </div>
- <div class="legend-item">
- <div class="legend-line" style="background: #9b59b6;"></div>
- <span>属于</span>
- </div>
- <div class="legend-item">
- <div class="legend-line" style="background: #2ecc71;"></div>
- <span>分类共现(跨)</span>
- </div>
- <div class="legend-item">
- <div class="legend-line" style="background: #3498db;"></div>
- <span>分类共现(内)</span>
- </div>
- <div class="legend-item">
- <div class="legend-line" style="background: #f39c12;"></div>
- <span>标签共现</span>
- </div>
- </div>
- </div>
- <div class="controls">
- <div class="control-label">视图控制</div>
- <button onclick="resetZoom()">重置视图</button>
- <button onclick="toggleLabels()">切换标签</button>
- <button onclick="toggleCrossLayerEdges()" id="crossLayerBtn">显示跨层边</button>
- <div class="control-group">
- <div class="control-label">人设树配置</div>
- <button onclick="toggleTreeTags()" id="treeTagBtn" class="active">显示标签</button>
- <select id="treeDepthSelect" onchange="setTreeDepth(this.value)">
- <option value="0">全部层级</option>
- <option value="2">2层</option>
- <option value="3">3层</option>
- <option value="4">4层</option>
- <option value="5">5层</option>
- </select>
- </div>
- </div>
- </div>
- </div>
- </div>
- <script>
- // 所有帖子的图谱数据
- const allGraphData = {all_graph_data};
- // 完整的人设树数据(所有人设节点和属于边)
- const personaTreeData = {persona_tree_data};
- // 当前选中的帖子索引
- let currentIndex = 0;
- let simulation = null;
- let svg = null;
- let g = null;
- let treeSvg = null; // 人设树独立SVG
- let treeG = null; // 人设树group
- let egoSvg = null; // 关系图独立SVG
- let egoG = null; // 关系图group
- let zoom = null;
- let showLabels = true;
- let showCrossLayerEdges = false; // 跨层边默认隐藏
- let isCrossLayerEdge = null; // 跨层边判断函数(在renderGraph中设置)
- // 人设树配置
- let showTreeTags = true; // 是否显示标签节点
- let treeMaxDepth = 0; // 显示的最大层数(0=全部)
- // 切换标签显示
- function toggleTreeTags() {{
- showTreeTags = !showTreeTags;
- const btn = document.getElementById("treeTagBtn");
- btn.textContent = showTreeTags ? "显示标签" : "隐藏标签";
- btn.classList.toggle("active", showTreeTags);
- // 重新渲染当前图谱
- renderGraph(allGraphData[currentIndex]);
- }}
- // 设置树的显示层数
- function setTreeDepth(depth) {{
- treeMaxDepth = parseInt(depth);
- // 重新渲染当前图谱
- renderGraph(allGraphData[currentIndex]);
- }}
- // 初始化
- function init() {{
- const container = document.getElementById("graph");
- const treeContainer = document.getElementById("tree-container");
- const width = container.clientWidth;
- const height = container.clientHeight;
- // 创建圆形层SVG
- svg = d3.select("#graph")
- .append("svg")
- .attr("width", width)
- .attr("height", height);
- g = svg.append("g");
- zoom = d3.zoom()
- .scaleExtent([0.1, 4])
- .on("zoom", (event) => {{
- g.attr("transform", event.transform);
- }});
- svg.call(zoom);
- // 创建人设树SVG(独立可滚动)
- treeSvg = d3.select("#tree-container")
- .append("svg")
- .attr("width", 400);
- treeG = treeSvg.append("g");
- // 创建关系图SVG(在独立的ego-container中)
- egoSvg = d3.select("#ego-container")
- .append("svg")
- .attr("width", 400)
- .attr("height", 400);
- egoG = egoSvg.append("g");
- // 关系图缩放
- const egoZoom = d3.zoom()
- .scaleExtent([0.3, 3])
- .on("zoom", (event) => {{
- egoG.attr("transform", event.transform);
- }});
- egoSvg.call(egoZoom);
- // 绑定Tab点击事件
- document.querySelectorAll(".tab").forEach((tab, index) => {{
- tab.addEventListener("click", () => switchTab(index));
- }});
- // 绑定关系图控制面板事件
- // 全选复选框事件
- document.querySelectorAll('.select-all input').forEach(cb => {{
- cb.addEventListener('change', (e) => {{
- const level = e.target.dataset.level;
- const checked = e.target.checked;
- // 设置该层级所有边类型复选框
- document.querySelectorAll(`.cascade-edge-item input[data-level="${{level}}"]`).forEach(item => {{
- item.checked = checked;
- }});
- // 重新渲染关系图和人设树高亮
- if (currentEgoCenterNodeId) {{
- handleNodeClick(currentEgoCenterNodeId, currentEgoCenterNodeName);
- }}
- }});
- }});
- // 边类型复选框变化事件
- document.querySelectorAll('.cascade-edge-item input').forEach(cb => {{
- cb.addEventListener('change', (e) => {{
- // 更新全选复选框状态
- const level = e.target.dataset.level;
- const allItems = document.querySelectorAll(`.cascade-edge-item input[data-level="${{level}}"]`);
- const checkedItems = document.querySelectorAll(`.cascade-edge-item input[data-level="${{level}}"]:checked`);
- const selectAllCb = document.querySelector(`.select-all input[data-level="${{level}}"]`);
- selectAllCb.checked = allItems.length === checkedItems.length;
- // 重新渲染关系图和人设树高亮
- if (currentEgoCenterNodeId) {{
- handleNodeClick(currentEgoCenterNodeId, currentEgoCenterNodeName);
- }}
- }});
- }});
- // 点击页面其他地方关闭级联菜单
- document.addEventListener('click', (e) => {{
- if (!e.target.closest('.cascade-dropdown')) {{
- document.getElementById('cascade-menu').classList.remove('show');
- }}
- }});
- // 显示第一个帖子
- switchTab(0);
- }}
- // 构建人设树数据(合并为一棵树,根节点为"人设")
- // showTreeTags: 控制是否显示标签节点
- // treeMaxDepth: 控制树的显示深度(0=全部,2=维度,3=+一层,4=+两层...)
- function buildPersonaTreeData() {{
- const dimensions = ["灵感点", "目的点", "关键点"];
- const dimColors = {{ "灵感点": "#f39c12", "目的点": "#3498db", "关键点": "#9b59b6" }};
- const dimensionChildren = [];
- let totalNodeCount = 0;
- dimensions.forEach(dim => {{
- // 根据 showTreeTags 过滤节点(独立于深度控制)
- let dimNodes = personaTreeData.nodes.filter(n => n.节点层级 === dim);
- if (!showTreeTags) {{
- dimNodes = dimNodes.filter(n => n.节点类型 !== "标签");
- }}
- if (dimNodes.length === 0) {{
- const dimNode = {{
- name: dim,
- 节点名称: dim,
- isDimension: true,
- dimColor: dimColors[dim],
- children: []
- }};
- dimensionChildren.push(dimNode);
- return;
- }}
- const nodeMap = {{}};
- dimNodes.forEach(n => nodeMap[n.节点ID] = {{ ...n, name: n.节点名称, children: [], dimColor: dimColors[dim] }});
- // 只用属于边构建父子关系
- const hierarchyEdgeTypes = ["属于"];
- const hasParent = new Set();
- personaTreeData.edges.forEach(e => {{
- if (!hierarchyEdgeTypes.includes(e.边类型)) return; // 跳过非层级边
- const srcNode = nodeMap[e.源节点ID];
- const tgtNode = nodeMap[e.目标节点ID];
- if (srcNode && tgtNode) {{
- tgtNode.children.push(srcNode);
- hasParent.add(e.源节点ID);
- }}
- }});
- const roots = dimNodes.filter(n => !hasParent.has(n.节点ID)).map(n => nodeMap[n.节点ID]);
- const dimNode = {{
- name: dim,
- 节点名称: dim,
- isDimension: true,
- dimColor: dimColors[dim],
- children: roots
- }};
- dimensionChildren.push(dimNode);
- totalNodeCount += dimNodes.length;
- }});
- // 根节点"人设"
- const rootNode = {{
- name: "人设",
- 节点名称: "人设",
- isRoot: true,
- children: dimensionChildren
- }};
- // 根据 treeMaxDepth 截断树深度(0=全部)
- // 深度1=根,深度2=维度,深度3+=子节点
- if (treeMaxDepth > 0) {{
- truncateTree(rootNode, 1, treeMaxDepth);
- }}
- return {{ root: rootNode, nodeCount: totalNodeCount }};
- }}
- // 递归截断树的深度
- function truncateTree(node, currentDepth, maxDepth) {{
- if (currentDepth >= maxDepth) {{
- node.children = [];
- return;
- }}
- if (node.children) {{
- node.children.forEach(child => truncateTree(child, currentDepth + 1, maxDepth));
- }}
- }}
- // 切换Tab
- function switchTab(index) {{
- currentIndex = index;
- // 更新Tab样式
- document.querySelectorAll(".tab").forEach((tab, i) => {{
- tab.classList.toggle("active", i === index);
- }});
- // 更新图谱
- renderGraph(allGraphData[index]);
- }}
- // 渲染图谱
- function renderGraph(data) {{
- // 清空现有图谱
- g.selectAll("*").remove();
- treeG.selectAll("*").remove();
- if (simulation) {{
- simulation.stop();
- }}
- const container = document.getElementById("graph");
- const width = container.clientWidth;
- // 布局配置:人设树在左侧独立容器,右侧是圆形层
- const treeAreaWidth = 400; // 固定树宽度
- const circleAreaWidth = width - 40;
- const circleAreaCenterX = circleAreaWidth / 2;
- // 准备数据
- const nodes = data.nodes.map(n => ({{
- ...n,
- id: n.节点ID,
- source: n.节点ID.startsWith("帖子_") ? "帖子" : "人设",
- level: n.节点层级
- }}));
- const links = data.edges.map(e => ({{
- ...e,
- source: e.源节点ID,
- target: e.目标节点ID,
- type: e.边类型
- }}));
- // 分离节点类型
- const postNodes = nodes.filter(n => n.source === "帖子");
- const personaNodes = nodes.filter(n => n.source === "人设" && !n.是否扩展);
- const expandedNodes = nodes.filter(n => n.source === "人设" && n.是否扩展);
- const matchLinks = links.filter(l => l.type.startsWith("匹配_"));
- // 更新匹配列表(按分数降序)
- updateMatchList(matchLinks, nodes);
- // 构建帖子节点到人设节点的映射
- const postToPersona = {{}};
- const personaToPost = {{}};
- matchLinks.forEach(l => {{
- const sid = typeof l.source === "object" ? l.source.id : l.source;
- const tid = typeof l.target === "object" ? l.target.id : l.target;
- if (!postToPersona[sid]) postToPersona[sid] = [];
- postToPersona[sid].push(tid);
- if (!personaToPost[tid]) personaToPost[tid] = [];
- personaToPost[tid].push(sid);
- }});
- // 找出所有连通分量
- function findConnectedComponents(nodes, links) {{
- const nodeIds = new Set(nodes.map(n => n.id));
- const adj = {{}};
- nodeIds.forEach(id => adj[id] = []);
- links.forEach(l => {{
- const sid = typeof l.source === "object" ? l.source.id : l.source;
- const tid = typeof l.target === "object" ? l.target.id : l.target;
- if (nodeIds.has(sid) && nodeIds.has(tid)) {{
- adj[sid].push(tid);
- adj[tid].push(sid);
- }}
- }});
- const visited = new Set();
- const components = [];
- nodeIds.forEach(startId => {{
- if (visited.has(startId)) return;
- const component = [];
- const queue = [startId];
- while (queue.length > 0) {{
- const id = queue.shift();
- if (visited.has(id)) continue;
- visited.add(id);
- component.push(id);
- adj[id].forEach(neighbor => {{
- if (!visited.has(neighbor)) queue.push(neighbor);
- }});
- }}
- components.push(component);
- }});
- return components;
- }}
- // 按大小排序连通分量(大的在前)
- const components = findConnectedComponents(nodes, links)
- .sort((a, b) => b.length - a.length);
- console.log(`找到 ${{components.length}} 个连通分量`);
- // 为每个节点分配连通分量ID和分量内的X范围
- const nodeToComponent = {{}};
- const componentCenters = {{}};
- const componentBounds = {{}};
- const padding = 50; // 分量之间的间距
- const totalPadding = padding * (components.length - 1);
- const availableWidth = width - totalPadding - 100; // 留边距
- // 根据分量大小分配宽度
- const totalNodes = nodes.length;
- let currentX = 50; // 起始边距
- components.forEach((comp, i) => {{
- const compWidth = Math.max(150, (comp.length / totalNodes) * availableWidth);
- const centerX = currentX + compWidth / 2;
- componentCenters[i] = centerX;
- componentBounds[i] = {{ start: currentX, end: currentX + compWidth, width: compWidth }};
- comp.forEach(nodeId => {{
- nodeToComponent[nodeId] = i;
- }});
- currentX += compWidth + padding;
- }});
- // 使用重心法(Barycenter)减少边交叉
- // 迭代优化:交替调整两层节点的顺序
- const nodeTargetX = {{}};
- const personaXMap = {{}};
- // 对每个连通分量单独处理
- components.forEach((comp, compIdx) => {{
- const bounds = componentBounds[compIdx];
- const compPostNodes = postNodes.filter(n => nodeToComponent[n.id] === compIdx);
- const compPersonaNodes = personaNodes.filter(n => nodeToComponent[n.id] === compIdx);
- if (compPostNodes.length === 0 || compPersonaNodes.length === 0) {{
- // 没有匹配关系的分量,均匀分布
- const spacing = bounds.width / (comp.length + 1);
- comp.forEach((nodeId, i) => {{
- const node = nodes.find(n => n.id === nodeId);
- if (node) {{
- node.x = bounds.start + spacing * (i + 1);
- nodeTargetX[nodeId] = node.x;
- if (node.source === "人设") personaXMap[nodeId] = node.x;
- }}
- }});
- return;
- }}
- // 初始化:给人设节点一个初始顺序
- let personaOrder = compPersonaNodes.map((n, i) => ({{ node: n, order: i }}));
- // 迭代优化(3轮)
- for (let iter = 0; iter < 3; iter++) {{
- // 1. 根据人设节点位置,计算帖子节点的重心
- const postBarycenter = {{}};
- compPostNodes.forEach(pn => {{
- const matched = postToPersona[pn.id] || [];
- if (matched.length > 0) {{
- const avgOrder = matched.reduce((sum, pid) => {{
- const po = personaOrder.find(p => p.node.id === pid);
- return sum + (po ? po.order : 0);
- }}, 0) / matched.length;
- postBarycenter[pn.id] = avgOrder;
- }} else {{
- postBarycenter[pn.id] = 0;
- }}
- }});
- // 按重心排序帖子节点
- const sortedPosts = [...compPostNodes].sort((a, b) =>
- postBarycenter[a.id] - postBarycenter[b.id]
- );
- // 2. 根据帖子节点位置,重新计算人设节点的重心
- const personaBarycenter = {{}};
- compPersonaNodes.forEach(pn => {{
- const matched = personaToPost[pn.id] || [];
- if (matched.length > 0) {{
- const avgOrder = matched.reduce((sum, pid) => {{
- const idx = sortedPosts.findIndex(p => p.id === pid);
- return sum + (idx >= 0 ? idx : 0);
- }}, 0) / matched.length;
- personaBarycenter[pn.id] = avgOrder;
- }} else {{
- personaBarycenter[pn.id] = personaOrder.find(p => p.node.id === pn.id)?.order || 0;
- }}
- }});
- // 更新人设节点顺序
- personaOrder = compPersonaNodes
- .map(n => ({{ node: n, order: personaBarycenter[n.id] }}))
- .sort((a, b) => a.order - b.order)
- .map((item, i) => ({{ node: item.node, order: i }}));
- }}
- // 最终排序
- const finalPersonaOrder = personaOrder.map(p => p.node);
- const postBarycenter = {{}};
- compPostNodes.forEach(pn => {{
- const matched = postToPersona[pn.id] || [];
- if (matched.length > 0) {{
- const avgOrder = matched.reduce((sum, pid) => {{
- const idx = finalPersonaOrder.findIndex(n => n.id === pid);
- return sum + (idx >= 0 ? idx : 0);
- }}, 0) / matched.length;
- postBarycenter[pn.id] = avgOrder;
- }} else {{
- postBarycenter[pn.id] = 0;
- }}
- }});
- const finalPostOrder = [...compPostNodes].sort((a, b) =>
- postBarycenter[a.id] - postBarycenter[b.id]
- );
- // 设置位置
- const personaSpacing = bounds.width / (finalPersonaOrder.length + 1);
- finalPersonaOrder.forEach((n, i) => {{
- n.x = bounds.start + personaSpacing * (i + 1);
- nodeTargetX[n.id] = n.x;
- personaXMap[n.id] = n.x;
- }});
- const postSpacing = bounds.width / (finalPostOrder.length + 1);
- finalPostOrder.forEach((n, i) => {{
- // 帖子节点用重心位置(匹配人设的平均X)
- const matched = postToPersona[n.id] || [];
- if (matched.length > 0) {{
- const avgX = matched.reduce((sum, pid) => sum + (personaXMap[pid] || bounds.start + bounds.width/2), 0) / matched.length;
- n.x = avgX;
- }} else {{
- n.x = bounds.start + postSpacing * (i + 1);
- }}
- nodeTargetX[n.id] = n.x;
- }});
- }});
- // 节点颜色
- const levelColors = {{
- "灵感点": "#f39c12",
- "目的点": "#3498db",
- "关键点": "#9b59b6"
- }};
- // 获取节点的层级编号(四层结构)
- function getNodeLayer(d) {{
- if (d.source === "帖子") {{
- return d.节点类型 === "点" ? 0 : 1; // 点=0, 标签=1
- }}
- // 人设节点:根据是否扩展分成两层
- return d.是否扩展 ? 3 : 2; // 直接匹配=2, 扩展=3
- }}
- // 统计每层节点数量(四层结构)
- const layerCounts = {{0: 0, 1: 0, 2: 0, 3: 0}};
- nodes.forEach(n => {{
- const layer = getNodeLayer(n);
- layerCounts[layer]++;
- }});
- console.log("每层节点数:", layerCounts);
- // 根据节点数量计算每层圆的半径
- // 左列:帖子标签(上) + 人设匹配(下),右列:帖子点(同一行开始)
- // 左列是主要展示区域,视图中心对准左列
- const minRadius = 80;
- const maxRadius = Math.min(circleAreaWidth / 3 - 20, 180);
- const nodeSpacing = 60;
- function calcRadius(nodeCount) {{
- if (nodeCount <= 1) return minRadius;
- const circumference = nodeCount * nodeSpacing;
- const r = circumference / (2 * Math.PI);
- return Math.max(minRadius, Math.min(maxRadius, r));
- }}
- // 左列3层统一大小(取最大值)
- const leftColRadius = Math.max(
- calcRadius(layerCounts[1]),
- calcRadius(layerCounts[2]),
- calcRadius(layerCounts[3])
- );
- const layerRadius = {{
- 0: calcRadius(layerCounts[0]), // 帖子点(右列)
- 1: leftColRadius, // 帖子标签(左上)
- 2: leftColRadius, // 人设匹配1层(左中)
- 3: leftColRadius // 人设匹配2层(左下)
- }};
- console.log("每层半径:", layerRadius);
- // 获取人设树数据(单棵树)
- const personaTree = buildPersonaTreeData();
- // 树高度自适应:根据节点数量,每个节点约12px,最小800
- const treeHeight = Math.max(800, personaTree.nodeCount * 12 + 150);
- // 关系图配置(放在树下方)
- const egoRadius = 180;
- const egoAreaHeight = egoRadius * 2 + 80;
- // 计算布局:左列(帖子标签+人设匹配1层+人设匹配2层),右列(帖子点)
- const layerPadding = 30;
- const leftColHeight = layerRadius[1] * 2 + layerPadding + layerRadius[2] * 2 + layerPadding + layerRadius[3] * 2 + layerPadding;
- const circleHeight = leftColHeight;
- const height = Math.max(circleHeight + 80, treeHeight + 80, container.clientHeight);
- // 计算每层圆心坐标
- const layerCenterX = {{}};
- const layerCenterY = {{}};
- // 左列居中显示,右列在旁边
- const leftColX = circleAreaCenterX; // 左列居中
- const rightColX = leftColX + Math.max(layerRadius[1], layerRadius[2], layerRadius[3]) + layerPadding + layerRadius[0] + 30; // 右列在右边
- // 左列:帖子标签(上)+ 人设匹配1层(中)+ 人设匹配2层(下)
- layerCenterX[1] = leftColX;
- layerCenterY[1] = layerRadius[1] + layerPadding / 2 + 20;
- layerCenterX[2] = leftColX;
- layerCenterY[2] = layerCenterY[1] + layerRadius[1] + layerPadding + layerRadius[2];
- layerCenterX[3] = leftColX;
- layerCenterY[3] = layerCenterY[2] + layerRadius[2] + layerPadding + layerRadius[3];
- // 右列:帖子点(与帖子标签同一行开始)
- layerCenterX[0] = rightColX;
- layerCenterY[0] = layerCenterY[1]; // 与帖子标签同一行
- console.log("每层圆心X:", layerCenterX);
- console.log("每层圆心Y:", layerCenterY);
- // 更新SVG高度
- svg.attr("height", height);
- // 获取节点的基准Y(层圆心)
- function getNodeBaseY(d) {{
- const layer = getNodeLayer(d);
- return layerCenterY[layer];
- }}
- // 获取节点的基准X(层圆心)
- function getNodeBaseX(d) {{
- const layer = getNodeLayer(d);
- return layerCenterX[layer];
- }}
- // 层边界配置(不再使用)
- const layerBounds = {{}};
- // 自定义层内排斥力(只对同层节点生效,尽量分散)
- function forceIntraLayerRepulsion(strength) {{
- let nodes;
- function force(alpha) {{
- for (let i = 0; i < nodes.length; i++) {{
- const nodeA = nodes[i];
- const layerA = getNodeLayer(nodeA);
- for (let j = i + 1; j < nodes.length; j++) {{
- const nodeB = nodes[j];
- const layerB = getNodeLayer(nodeB);
- // 只对同层节点施加排斥力
- if (layerA !== layerB) continue;
- const dx = nodeB.x - nodeA.x;
- const dy = nodeB.y - nodeA.y;
- const dist = Math.sqrt(dx * dx + dy * dy) || 1;
- const minDist = 150; // 增大最小距离,让节点更分散
- if (dist < minDist) {{
- // 排斥力随距离衰减,但基础强度更大
- const pushStrength = strength * alpha * (minDist - dist) / dist * 2;
- const px = dx * pushStrength;
- const py = dy * pushStrength;
- nodeA.vx -= px;
- nodeA.vy -= py;
- nodeB.vx += px;
- nodeB.vy += py;
- }}
- }}
- }}
- }}
- force.initialize = function(_) {{
- nodes = _;
- }};
- return force;
- }}
- // 层圆的半径(使用动态计算的 layerRadius)
- // layerRadius 和 layerCenterY 已在前面定义
- // 层边界约束力(把节点限制在层内)
- function forceLayerBoundary() {{
- let nodes;
- function force(alpha) {{
- nodes.forEach(node => {{
- const layer = getNodeLayer(node);
- const centerX = layerCenterX[layer];
- const centerY = layerCenterY[layer];
- // 使用圆形边界
- const maxRadius = layerRadius[layer] - 15;
- // 计算到圆心的距离
- const dx = node.x - centerX;
- const dy = node.y - centerY;
- const dist = Math.sqrt(dx * dx + dy * dy);
- // 如果超出圆形边界,拉回来
- if (dist > maxRadius) {{
- const scale = maxRadius / dist;
- node.x = centerX + dx * scale;
- node.y = centerY + dy * scale;
- // 阻止继续向外运动
- const angle = Math.atan2(dy, dx);
- const vOutward = node.vx * Math.cos(angle) + node.vy * Math.sin(angle);
- if (vOutward > 0) {{
- node.vx -= vOutward * Math.cos(angle);
- node.vy -= vOutward * Math.sin(angle);
- }}
- }}
- }});
- }}
- force.initialize = function(_) {{
- nodes = _;
- }};
- return force;
- }}
- // 层内圆形布局力(让同层节点围绕圆心分布)
- function forceCircularLayout(strength) {{
- let nodes;
- function force(alpha) {{
- // 按层分组(三层)
- const layerNodes = {{0: [], 1: [], 2: [], 3: []}};
- nodes.forEach(node => {{
- const layer = getNodeLayer(node);
- layerNodes[layer].push(node);
- }});
- // 对每层计算布局
- Object.entries(layerNodes).forEach(([layerIdx, layerGroup]) => {{
- if (layerGroup.length === 0) return;
- const layer = parseInt(layerIdx);
- const centerX = layerCenterX[layer];
- const centerY = layerCenterY[layer];
- // 使用圆形布局
- const nodeRadius = layerRadius[layer] - 20;
- if (layerGroup.length === 1) {{
- // 单个节点放在圆心
- const node = layerGroup[0];
- node.vx += (centerX - node.x) * strength * alpha;
- node.vy += (centerY - node.y) * strength * alpha;
- return;
- }}
- // 按角度排序节点(保持相对位置稳定)
- layerGroup.forEach(node => {{
- node._angle = Math.atan2(node.y - centerY, node.x - centerX);
- }});
- layerGroup.sort((a, b) => a._angle - b._angle);
- // 均匀分布在圆周上
- const angleStep = (2 * Math.PI) / layerGroup.length;
- layerGroup.forEach((node, i) => {{
- const angle = -Math.PI / 2 + i * angleStep; // 从顶部开始
- const idealX = centerX + nodeRadius * Math.cos(angle);
- const idealY = centerY + nodeRadius * Math.sin(angle);
- node.vx += (idealX - node.x) * strength * alpha;
- node.vy += (idealY - node.y) * strength * alpha;
- }});
- }});
- }}
- force.initialize = function(_) {{
- nodes = _;
- }};
- return force;
- }}
- // 力导向模拟
- simulation = d3.forceSimulation(nodes)
- // 连线力(跨层连接)
- .force("link", d3.forceLink(links).id(d => d.id)
- .distance(d => {{
- // 跨层连线距离
- if (d.type.startsWith("匹配_") || d.type === "属于") {{
- return 150; // 跨层边
- }}
- return 60; // 同层边
- }})
- .strength(d => {{
- // 跨层边力度弱一些,不要拉扯节点出层
- if (d.type.startsWith("匹配_") || d.type === "属于") {{
- return 0.03;
- }}
- return 0.1;
- }}))
- // X方向:轻微拉向各层中心
- .force("x", d3.forceX(d => getNodeBaseX(d)).strength(0.02))
- // Y方向:轻微拉向层中心
- .force("y", d3.forceY(d => getNodeBaseY(d)).strength(0.02))
- // 层内碰撞检测
- .force("collision", d3.forceCollide().radius(30))
- // 层内排斥力(同层节点相互排斥)
- .force("intraLayer", forceIntraLayerRepulsion(0.8))
- // 层内布局(圆形或树状)
- .force("circularLayout", forceCircularLayout(0.15))
- // 层边界约束(节点不能跑出层,硬约束)
- .force("boundary", forceLayerBoundary());
- // 边类型到CSS类的映射
- const edgeTypeClass = {{
- "匹配_相同": "match-same",
- "匹配_相似": "match-similar",
- "分类共现(跨点)": "category-cross",
- "分类共现(点内)": "category-intra",
- "标签共现": "tag-cooccur",
- "属于": "belong",
- "包含": "contain",
- // 镜像边(帖子节点之间,虚线)
- "镜像_分类共现(跨点)": "mirror-category-cross",
- "镜像_分类共现(点内)": "mirror-category-intra",
- "镜像_标签共现": "mirror-tag-cooccur",
- "镜像_属于": "mirror-belong",
- "镜像_包含": "mirror-contain"
- }};
- // 获取边的CSS类(处理二阶边,映射到对应的镜像边样式)
- function getEdgeClass(edgeType) {{
- if (edgeTypeClass[edgeType]) return edgeTypeClass[edgeType];
- // 二阶边映射到对应的镜像边样式(颜色相同,都用虚线)
- if (edgeType.startsWith("二阶_")) {{
- const originalType = edgeType.replace("二阶_", "");
- const mirrorType = "镜像_" + originalType;
- if (edgeTypeClass[mirrorType]) return edgeTypeClass[mirrorType];
- }}
- return "match";
- }}
- // 绘制层背景(圆形,使用动态大小)
- const layerBg = g.append("g").attr("class", "layer-backgrounds");
- // 层配置:名称、颜色(三层圆,关系图在左侧)
- const layerConfig = [
- {{ name: "帖子点", layer: 0, color: "rgba(243, 156, 18, 0.08)", stroke: "rgba(243, 156, 18, 0.3)" }},
- {{ name: "帖子标签", layer: 1, color: "rgba(52, 152, 219, 0.08)", stroke: "rgba(52, 152, 219, 0.3)" }},
- {{ name: "人设匹配_1层", layer: 2, color: "rgba(155, 89, 182, 0.08)", stroke: "rgba(155, 89, 182, 0.3)" }},
- {{ name: "人设匹配_2层", layer: 3, color: "rgba(46, 204, 113, 0.08)", stroke: "rgba(46, 204, 113, 0.3)" }}
- ];
- // 绘制三层圆形背景
- layerConfig.forEach(cfg => {{
- const cx = layerCenterX[cfg.layer];
- const cy = layerCenterY[cfg.layer];
- const r = layerRadius[cfg.layer];
- layerBg.append("circle")
- .attr("cx", cx)
- .attr("cy", cy)
- .attr("r", r)
- .attr("fill", cfg.color)
- .attr("stroke", cfg.stroke)
- .attr("stroke-width", 2);
- // 层标签(圆的左侧)
- layerBg.append("text")
- .attr("x", cx - r - 15)
- .attr("y", cy)
- .attr("dy", "0.35em")
- .attr("fill", "rgba(255,255,255,0.5)")
- .attr("font-size", "13px")
- .attr("font-weight", "bold")
- .attr("text-anchor", "end")
- .text(cfg.name);
- }});
- // 绘制左侧人设树(在独立的treeSvg中)
- const dimColors = {{ "灵感点": "#f39c12", "目的点": "#3498db", "关键点": "#9b59b6" }};
- // 更新树SVG高度
- treeSvg.attr("height", treeHeight + 50);
- const treeGroup = treeG.append("g")
- .attr("class", "persona-tree")
- .attr("transform", `translate(15, 25)`);
- // 设置关系图SVG
- egoG.selectAll("*").remove();
- const egoDisplayRadius = 180;
- const egoCenterGroup = egoG.append("g")
- .attr("class", "ego-center")
- .attr("transform", `translate(200, 210)`);
- // 关系图内容组
- egoCenterGroup.append("g")
- .attr("class", "ego-graph-content");
- // D3树布局 - 宽度留出边距给标签
- const treeLayout = d3.tree()
- .size([treeHeight - 50, treeAreaWidth - 70]);
- const root = d3.hierarchy(personaTree.root);
- treeLayout(root);
- // 获取节点颜色(根据维度)
- function getNodeColor(d) {{
- if (d.data.isRoot) return "#e94560"; // 根节点红色
- if (d.data.isDimension) return d.data.dimColor; // 维度节点用维度颜色
- return d.data.dimColor || "#888"; // 分类节点继承维度颜色
- }}
- // 构建节点ID到D3节点的映射(用于绘制原始边和高亮)
- const treeNodeById = {{}};
- root.descendants().forEach(d => {{
- if (d.data.节点ID) {{
- treeNodeById[d.data.节点ID] = d;
- }}
- }});
- // 边类型颜色和样式
- const treeEdgeColors = {{
- "分类层级": "#2ecc71", // 绿色 - 分类的层级关系
- "属于": "#9b59b6", // 紫色 - 标签属于分类
- "包含": "#ffb6c1", // 淡粉 - 分类包含标签(向下)
- "分类共现(跨点)": "#2ecc71", // 绿色 - 跨帖子分类共现
- "分类共现(点内)": "#3498db", // 蓝色 - 同帖子分类共现
- "标签共现": "#f39c12" // 橙色 - 标签共现
- }};
- const treeEdgeDash = {{
- "分类层级": "none",
- "属于": "3,2",
- "包含": "3,2",
- "分类共现(跨点)": "5,3",
- "分类共现(点内)": "5,3",
- "标签共现": "2,2"
- }};
- // 只用D3树布局的链接作为树边(避免重复)
- const visibleTreeEdges = root.links().map(link => ({{
- 源节点ID: link.source.data.节点ID || link.source.data.name,
- 目标节点ID: link.target.data.节点ID || link.target.data.name,
- 边类型: "属于",
- isTreeLink: true,
- sourceNode: link.source,
- targetNode: link.target
- }}));
- // 生成树边路径的函数
- function treeEdgePath(d) {{
- const source = d.sourceNode;
- const target = d.targetNode;
- if (!source || !target) return "";
- const midX = (source.y + target.y) / 2;
- return `M${{source.y}},${{source.x}} C${{midX}},${{source.x}} ${{midX}},${{target.x}} ${{target.y}},${{target.x}}`;
- }}
- // 绘制原始边(只有属于边)
- const treeEdgeGroup = treeGroup.append("g").attr("class", "tree-edges");
- // 先绘制可见边(只有属于边)
- const treeEdges = treeEdgeGroup.selectAll(".tree-edge")
- .data(visibleTreeEdges)
- .join("path")
- .attr("class", "tree-edge")
- .attr("fill", "none")
- .attr("stroke", "#9b59b6") // 属于边用紫色
- .attr("stroke-opacity", 0.3)
- .attr("stroke-width", 1)
- .attr("d", treeEdgePath);
- // 绘制透明的热区边(便于点击)
- const treeEdgeHitareas = treeEdgeGroup.selectAll(".tree-edge-hitarea")
- .data(visibleTreeEdges)
- .join("path")
- .attr("class", "tree-edge-hitarea")
- .attr("fill", "none")
- .attr("stroke", "transparent")
- .attr("stroke-width", 12)
- .style("cursor", "pointer")
- .attr("d", treeEdgePath)
- .on("click", (event, d) => {{
- event.stopPropagation();
- // 调用共享的边点击处理函数
- handleEdgeClick(d.源节点ID, d.目标节点ID, d.边类型);
- }});
- // 绘制节点
- const treeNodes = treeGroup.selectAll(".tree-node")
- .data(root.descendants())
- .join("g")
- .attr("class", "tree-node")
- .attr("transform", d => `translate(${{d.y}},${{d.x}})`)
- .style("cursor", "pointer")
- .on("click", (event, d) => {{
- event.stopPropagation();
- // 调用共享的节点点击处理函数
- handleNodeClick(d.data.节点ID, d.data.节点名称 || d.data.name);
- }})
- .on("mouseenter", (event, d) => {{
- // 悬停高亮:在关系图中高亮到激活节点的路径
- if (!currentEgoCenterNodeId) return;
- const hoveredNodeId = d.data.节点ID;
- if (!hoveredNodeId || hoveredNodeId === currentEgoCenterNodeId) return;
- highlightPathInEgoGraph(hoveredNodeId);
- }})
- .on("mouseleave", (event, d) => {{
- // 移出时恢复关系图
- if (!currentEgoCenterNodeId) return;
- resetEgoGraphHighlight();
- }});
- // 节点形状:根节点/维度=圆形,分类=正方形,标签=圆形
- // 统一实心填充维度颜色
- treeNodes.each(function(d) {{
- const el = d3.select(this);
- const nodeType = d.data.节点类型;
- const isRoot = d.data.isRoot;
- const isDimension = d.data.isDimension;
- const nodeColor = getNodeColor(d);
- if (nodeType === "分类") {{
- // 分类节点:正方形,实心填充
- el.append("rect")
- .attr("class", "tree-shape")
- .attr("x", -4)
- .attr("y", -4)
- .attr("width", 8)
- .attr("height", 8)
- .attr("rx", 1)
- .attr("fill", nodeColor)
- .attr("stroke", "rgba(255,255,255,0.5)")
- .attr("stroke-width", 1);
- }} else {{
- // 根节点、维度节点、标签节点:圆形,实心填充
- const radius = isRoot ? 6 : (isDimension ? 5 : 3);
- el.append("circle")
- .attr("class", "tree-shape")
- .attr("r", radius)
- .attr("fill", nodeColor)
- .attr("stroke", "rgba(255,255,255,0.5)")
- .attr("stroke-width", 1);
- }}
- }});
- // 节点标签
- treeNodes.append("text")
- .attr("dy", "0.31em")
- .attr("x", d => d.children ? -8 : 8)
- .attr("text-anchor", d => d.children ? "end" : "start")
- .attr("fill", d => (d.data.isRoot || d.data.isDimension) ? getNodeColor(d) : "#bbb")
- .attr("font-size", d => d.data.isRoot ? "11px" : (d.data.isDimension ? "10px" : "8px"))
- .attr("font-weight", d => (d.data.isRoot || d.data.isDimension) ? "bold" : "normal")
- .text(d => d.data.name);
- // 重置树高亮状态的函数
- function resetTreeHighlight() {{
- treeGroup.selectAll(".tree-node")
- .classed("tree-dimmed", false)
- .classed("tree-highlighted", false);
- // 重置所有形状(圆形和方形)- 统一实心填充
- treeGroup.selectAll(".tree-node .tree-shape")
- .attr("fill", d => getNodeColor(d))
- .attr("stroke", "rgba(255,255,255,0.5)")
- .attr("stroke-opacity", 1)
- .attr("opacity", 1);
- treeGroup.selectAll(".tree-node text")
- .attr("fill", d => (d.data.isRoot || d.data.isDimension) ? getNodeColor(d) : "#bbb")
- .attr("opacity", 1);
- // 重置边样式
- treeGroup.selectAll(".tree-edge")
- .attr("stroke-opacity", 0.3)
- .attr("stroke-width", 1);
- }}
- // 重置右侧图高亮状态的函数
- function resetGraphHighlight() {{
- g.selectAll(".node").classed("dimmed", false).classed("highlighted", false);
- g.selectAll(".link-group").classed("dimmed", false).classed("highlighted", false);
- }}
- // 点击树SVG背景取消高亮
- treeSvg.on("click", function(event) {{
- if (event.target === this) {{
- resetTreeHighlight();
- resetGraphHighlight();
- clearEgoGraph();
- closeDetailPanel();
- }}
- }});
- // 创建边的容器
- const linkGroup = g.append("g").attr("class", "links");
- // 为每条边创建组
- const linkG = linkGroup.selectAll("g")
- .data(links)
- .join("g")
- .attr("class", "link-group");
- // 绘制点击热区(透明宽线)
- const linkHitarea = linkG.append("line")
- .attr("class", "link-hitarea");
- // 绘制可见的边
- const link = linkG.append("line")
- .attr("class", d => "link " + getEdgeClass(d.type))
- .attr("stroke-width", d => d.type.startsWith("匹配_") ? 2.5 : 1.5);
- // 判断是否为跨层边(根据源和目标节点的层级)- 赋值给全局变量
- isCrossLayerEdge = function(d) {{
- const sourceNode = typeof d.source === "object" ? d.source : nodes.find(n => n.id === d.source);
- const targetNode = typeof d.target === "object" ? d.target : nodes.find(n => n.id === d.target);
- if (!sourceNode || !targetNode) return false;
- return getNodeLayer(sourceNode) !== getNodeLayer(targetNode);
- }};
- // 设置跨层边的初始可见性(匹配边始终显示,其他跨层边默认隐藏)
- linkG.each(function(d) {{
- if (d.type.startsWith("匹配_")) {{
- d3.select(this).style("display", "block"); // 匹配边始终显示
- }} else if (isCrossLayerEdge(d) && !showCrossLayerEdges) {{
- d3.select(this).style("display", "none");
- }}
- }});
- // 为匹配边添加分数标签
- const edgeLabels = linkG.filter(d => d.type.startsWith("匹配_") && d.边详情 && d.边详情.相似度)
- .append("g")
- .attr("class", "edge-label-group");
- edgeLabels.append("rect")
- .attr("class", "edge-label-bg")
- .attr("rx", 3)
- .attr("ry", 3);
- edgeLabels.append("text")
- .attr("class", "edge-label")
- .text(d => {{
- const score = d.边详情.相似度;
- return typeof score === "number" ? score.toFixed(2) : score;
- }});
- // 边的点击事件
- linkHitarea.on("click", (event, d, i) => {{
- event.stopPropagation();
- const linkIndex = links.indexOf(d);
- // 1. 力导向图高亮(highlightEdge 处理所有路径高亮逻辑)
- highlightEdge(d, linkIndex);
- showEdgeInfo(d);
- // 2. 确定要在人设树和关系图中展示的人设节点路径
- const edgeDetail = d.边详情 || {{}};
- const isMirrorEdge = d.type.startsWith("镜像_") || d.type.startsWith("二阶_");
- let personaPathNodes = [];
- let edgeType;
- if (isMirrorEdge && edgeDetail.路径节点) {{
- // 镜像边/二阶边:从路径节点中提取人设节点(不以帖子_开头的)
- personaPathNodes = edgeDetail.路径节点.filter(id => !id.startsWith("帖子_"));
- edgeType = edgeDetail.原始边类型 || d.type.replace("镜像_", "").replace("二阶_", "");
- }} else {{
- // 普通边:使用边的两端节点
- const sourceNode = typeof d.source === "object" ? d.source : nodes.find(n => n.id === d.source);
- const targetNode = typeof d.target === "object" ? d.target : nodes.find(n => n.id === d.target);
- const srcId = sourceNode ? sourceNode.id : d.source;
- const tgtId = targetNode ? targetNode.id : d.target;
- // 只有人设节点才加入路径
- if (!srcId.startsWith("帖子_")) personaPathNodes.push(srcId);
- if (!tgtId.startsWith("帖子_")) personaPathNodes.push(tgtId);
- edgeType = d.type;
- }}
- // 3. 同步人设树高亮和关系图展示
- syncTreeAndRelationGraph(personaPathNodes, edgeType);
- }})
- .on("mouseover", function(event, d) {{
- d3.select(this.parentNode).select(".link")
- .attr("stroke-opacity", 1)
- .attr("stroke-width", 4);
- }})
- .on("mouseout", function(event, d) {{
- d3.select(this.parentNode).select(".link")
- .attr("stroke-opacity", 0.7)
- .attr("stroke-width", d.type.startsWith("匹配_") ? 2.5 : 1.5);
- }});
- // 绘制节点
- const node = g.append("g")
- .selectAll("g")
- .data(nodes)
- .join("g")
- .attr("class", "node")
- .call(d3.drag()
- .on("start", dragstarted)
- .on("drag", dragged)
- .on("end", dragended));
- // 根据节点类型绘制不同形状
- // - 点节点(帖子点):六边形
- // - 标签节点:圆形
- // - 分类节点:方形
- // 帖子标签用虚线,人设标签用实线
- node.each(function(d) {{
- const el = d3.select(this);
- const isPointNode = d.节点类型 === "点";
- const isPostNode = d.source === "帖子";
- // 节点大小
- let size;
- if (isPointNode) {{
- size = 16; // 点节点最大
- }} else if (isPostNode) {{
- size = 12; // 帖子标签
- }} else {{
- size = 10; // 人设标签
- }}
- const fill = levelColors[d.level] || "#666";
- const nodeClass = isPostNode
- ? (isPointNode ? "post-point-node" : "post-node")
- : "persona-node";
- if (isPointNode) {{
- // 六边形(点节点)
- const hexPoints = [];
- for (let i = 0; i < 6; i++) {{
- const angle = (i * 60 - 30) * Math.PI / 180;
- hexPoints.push([size * Math.cos(angle), size * Math.sin(angle)]);
- }}
- el.append("polygon")
- .attr("points", hexPoints.map(p => p.join(",")).join(" "))
- .attr("fill", fill)
- .attr("class", nodeClass);
- }} else if (d.节点类型 === "分类") {{
- // 方形(分类节点)
- el.append("rect")
- .attr("width", size * 2)
- .attr("height", size * 2)
- .attr("x", -size)
- .attr("y", -size)
- .attr("fill", fill)
- .attr("class", nodeClass)
- .attr("rx", 3);
- }} else {{
- // 圆形(标签节点)
- el.append("circle")
- .attr("r", size)
- .attr("fill", fill)
- .attr("class", nodeClass);
- }}
- }});
- const labels = node.append("text")
- .attr("dx", 15)
- .attr("dy", 4)
- .text(d => d.节点名称)
- .style("display", showLabels ? "block" : "none");
- // 工具提示
- const tooltip = d3.select("#tooltip");
- node.on("mouseover", (event, d) => {{
- let html = `<strong>${{d.节点名称}}</strong><br/>类型: ${{d.节点类型}}<br/>层级: ${{d.节点层级}}`;
- // 点节点显示描述
- if (d.描述) {{
- html += `<br/><br/><em style="font-size:10px;color:#aaa">${{d.描述.slice(0, 100)}}${{d.描述.length > 100 ? '...' : ''}}</em>`;
- }}
- tooltip.style("display", "block").html(html);
- }})
- .on("mousemove", (event) => {{
- tooltip.style("left", (event.pageX + 15) + "px")
- .style("top", (event.pageY - 10) + "px");
- }})
- .on("mouseout", () => {{
- tooltip.style("display", "none");
- }})
- .on("click", (event, d) => {{
- event.stopPropagation();
- highlightNode(d);
- showNodeInfo(d);
- // 人设节点联动:高亮人设树 + 显示关系图
- if (d.source === "人设") {{
- handleNodeClick(d.节点ID, d.节点名称);
- }}
- }});
- // 更新位置
- simulation.on("tick", () => {{
- // 更新热区线
- linkHitarea
- .attr("x1", d => d.source.x)
- .attr("y1", d => d.source.y)
- .attr("x2", d => d.target.x)
- .attr("y2", d => d.target.y);
- // 更新可见边
- link
- .attr("x1", d => d.source.x)
- .attr("y1", d => d.source.y)
- .attr("x2", d => d.target.x)
- .attr("y2", d => d.target.y);
- // 更新边标签位置(放在边的中点)
- edgeLabels.attr("transform", d => {{
- const midX = (d.source.x + d.target.x) / 2;
- const midY = (d.source.y + d.target.y) / 2;
- return `translate(${{midX}},${{midY}})`;
- }});
- // 更新标签背景大小
- edgeLabels.each(function(d) {{
- const textEl = d3.select(this).select("text").node();
- if (textEl) {{
- const bbox = textEl.getBBox();
- d3.select(this).select("rect")
- .attr("x", bbox.x - 3)
- .attr("y", bbox.y - 1)
- .attr("width", bbox.width + 6)
- .attr("height", bbox.height + 2);
- }}
- }});
- node.attr("transform", d => `translate(${{d.x}},${{d.y}})`);
- }});
- // 拖拽函数
- function dragstarted(event, d) {{
- if (!event.active) simulation.alphaTarget(0.3).restart();
- d.fx = d.x;
- d.fy = d.y;
- }}
- function dragged(event, d) {{
- d.fx = event.x;
- d.fy = event.y;
- }}
- function dragended(event, d) {{
- if (!event.active) simulation.alphaTarget(0);
- d.fx = null;
- d.fy = null;
- }}
- // 清除所有高亮
- function clearHighlight() {{
- node.classed("dimmed", false).classed("highlighted", false);
- linkG.classed("dimmed", false).classed("highlighted", false);
- // 恢复跨层边的可见性状态(根据全局开关)
- linkG.each(function(d) {{
- if (isCrossLayerEdge(d)) {{
- d3.select(this).style("display", showCrossLayerEdges ? "block" : "none");
- }}
- }});
- }}
- // 高亮指定的节点和边
- function highlightElements(highlightNodeIds, highlightLinkIndices) {{
- // 先灰化所有
- node.classed("dimmed", true).classed("highlighted", false);
- linkG.classed("dimmed", true).classed("highlighted", false);
- // 高亮指定节点
- node.filter(d => highlightNodeIds.has(d.id))
- .classed("dimmed", false)
- .classed("highlighted", true);
- // 高亮指定边
- linkG.filter((d, i) => highlightLinkIndices.has(i))
- .classed("dimmed", false)
- .classed("highlighted", true);
- }}
- // 点击节点时的高亮逻辑
- function highlightNode(clickedNode) {{
- const highlightNodeIds = new Set([clickedNode.id]);
- const highlightLinkIndices = new Set();
- links.forEach((link, i) => {{
- const sourceId = typeof link.source === "object" ? link.source.id : link.source;
- const targetId = typeof link.target === "object" ? link.target.id : link.target;
- // 与点击节点直接相连的边
- if (sourceId === clickedNode.id || targetId === clickedNode.id) {{
- highlightLinkIndices.add(i);
- highlightNodeIds.add(sourceId);
- highlightNodeIds.add(targetId);
- // 如果是帖子节点,还要高亮对应的镜像边
- if (clickedNode.source === "帖子") {{
- // 找到通过该帖子连接的其他帖子(镜像边)
- links.forEach((otherLink, j) => {{
- const otherType = otherLink.type;
- if (otherType.startsWith("镜像_") || otherType.startsWith("二阶_")) {{
- const oSrc = typeof otherLink.source === "object" ? otherLink.source.id : otherLink.source;
- const oTgt = typeof otherLink.target === "object" ? otherLink.target.id : otherLink.target;
- if (oSrc === clickedNode.id || oTgt === clickedNode.id) {{
- highlightLinkIndices.add(j);
- highlightNodeIds.add(oSrc);
- highlightNodeIds.add(oTgt);
- }}
- }}
- }});
- }}
- }}
- }});
- // 高亮相关的节点和边
- highlightElements(highlightNodeIds, highlightLinkIndices);
- // 临时显示关联的跨层边(即使全局开关是关闭的)
- linkG.each(function(d, i) {{
- if (highlightLinkIndices.has(i)) {{
- d3.select(this).style("display", "block");
- }}
- }});
- }}
- // 点击边时的高亮逻辑
- function highlightEdge(clickedLink, clickedIndex) {{
- const highlightNodeIds = new Set();
- const highlightLinkIndices = new Set([clickedIndex]);
- const sourceId = typeof clickedLink.source === "object" ? clickedLink.source.id : clickedLink.source;
- const targetId = typeof clickedLink.target === "object" ? clickedLink.target.id : clickedLink.target;
- highlightNodeIds.add(sourceId);
- highlightNodeIds.add(targetId);
- // 如果是镜像边或二阶边,使用预计算的路径节点高亮
- if ((clickedLink.type.startsWith("镜像_") || clickedLink.type.startsWith("二阶_")) && clickedLink.边详情) {{
- const detail = clickedLink.边详情;
- const pathNodes = new Set([sourceId, targetId]);
- // 使用预计算的路径节点
- (detail.路径节点 || []).forEach(n => pathNodes.add(n));
- // 高亮路径上的所有节点
- pathNodes.forEach(n => highlightNodeIds.add(n));
- // 高亮连接路径节点的边
- links.forEach((link, i) => {{
- const lSrc = typeof link.source === "object" ? link.source.id : link.source;
- const lTgt = typeof link.target === "object" ? link.target.id : link.target;
- if (pathNodes.has(lSrc) && pathNodes.has(lTgt)) {{
- highlightLinkIndices.add(i);
- }}
- }});
- }}
- // 如果是人设边(两端都不是帖子节点),找对应的镜像边
- else if (!sourceId.startsWith("帖子_") && !targetId.startsWith("帖子_")) {{
- // 收集路径节点
- const pathNodes = new Set([sourceId, targetId]);
- // 找匹配的镜像边,读取其路径节点
- links.forEach((link, i) => {{
- const detail = link.边详情 || {{}};
- if ((link.type.startsWith("镜像_") || link.type.startsWith("二阶_")) && detail.源人设节点 && detail.目标人设节点) {{
- const matches = (detail.源人设节点 === sourceId && detail.目标人设节点 === targetId) ||
- (detail.源人设节点 === targetId && detail.目标人设节点 === sourceId);
- if (matches) {{
- highlightLinkIndices.add(i);
- // 直接使用预存的路径节点
- (detail.路径节点 || []).forEach(n => pathNodes.add(n));
- }}
- }}
- }});
- // 高亮路径上的所有节点
- pathNodes.forEach(n => highlightNodeIds.add(n));
- // 高亮连接路径节点的边
- links.forEach((link, i) => {{
- const lSrc = typeof link.source === "object" ? link.source.id : link.source;
- const lTgt = typeof link.target === "object" ? link.target.id : link.target;
- // 两端都在路径上的边
- if (pathNodes.has(lSrc) && pathNodes.has(lTgt)) {{
- highlightLinkIndices.add(i);
- }}
- }});
- }}
- // 高亮相关的节点和边
- highlightElements(highlightNodeIds, highlightLinkIndices);
- // 临时显示关联的跨层边(即使全局开关是关闭的)
- linkG.each(function(d, i) {{
- if (highlightLinkIndices.has(i)) {{
- d3.select(this).style("display", "block");
- }}
- }});
- }}
- // 点击空白处清除高亮(合并所有空白点击逻辑)
- svg.on("click", (event) => {{
- // 检查是否点击的是空白区域(svg本身或layer-backgrounds)
- const isBlank = event.target === svg.node() ||
- event.target.tagName === "svg" ||
- event.target.classList.contains("layer-backgrounds");
- if (isBlank) {{
- // 清除右侧图高亮
- clearHighlight();
- // 清除人设树高亮
- resetTreeHighlight();
- resetGraphHighlight();
- // 关闭详情面板
- closeDetailPanel();
- // 清除关系图
- clearEgoGraph();
- }}
- }});
- }}
- // 控制函数
- function resetZoom() {{
- const container = document.getElementById("svg-container");
- const width = container.clientWidth;
- const height = container.clientHeight;
- svg.transition().duration(750).call(
- zoom.transform,
- d3.zoomIdentity.translate(width/2, height/2).scale(1).translate(-width/2, -height/2)
- );
- }}
- function toggleLabels() {{
- showLabels = !showLabels;
- g.selectAll(".node text").style("display", showLabels ? "block" : "none");
- }}
- // 切换跨层边显示
- function toggleCrossLayerEdges() {{
- showCrossLayerEdges = !showCrossLayerEdges;
- const btn = document.getElementById("crossLayerBtn");
- btn.textContent = showCrossLayerEdges ? "隐藏跨层边" : "显示跨层边";
- btn.style.background = showCrossLayerEdges ? "#e94560" : "";
- // 更新边的可见性(使用 isCrossLayerEdge 函数判断)
- g.selectAll(".link-group").each(function(d) {{
- if (isCrossLayerEdge(d)) {{
- d3.select(this).style("display", showCrossLayerEdges ? "block" : "none");
- }}
- }});
- }}
- function showNodeInfo(d) {{
- const panel = document.getElementById("detailPanel");
- panel.classList.add("active");
- document.getElementById("detailTitle").textContent = d.source === "帖子" ? "📌 帖子节点" : "👤 人设节点";
- let html = `
- <p><span class="label">节点ID:</span> ${{d.节点ID}}</p>
- <p><span class="label">名称:</span> <strong>${{d.节点名称}}</strong></p>
- <p><span class="label">类型:</span> ${{d.节点类型}}</p>
- <p><span class="label">层级:</span> ${{d.节点层级}}</p>
- `;
- if (d.权重) {{
- html += `<p><span class="label">权重:</span> ${{d.权重}}</p>`;
- }}
- if (d.所属分类 && d.所属分类.length > 0) {{
- html += `<p><span class="label">所属分类:</span> ${{d.所属分类.join(" > ")}}</p>`;
- }}
- if (d.帖子数) {{
- html += `<p><span class="label">帖子数:</span> ${{d.帖子数}}</p>`;
- }}
- document.getElementById("detailContent").innerHTML = html;
- }}
- // 显示人设树节点详情(包含入边、出边、相关节点)
- function showTreeNodeDetail(nodeData, inEdges, outEdges) {{
- const panel = document.getElementById("detailPanel");
- panel.classList.add("active");
- document.getElementById("detailTitle").textContent = "🌳 人设树节点";
- // 节点基本信息
- let html = `
- <p><span class="label">名称:</span> <strong>${{nodeData.节点名称 || nodeData.name}}</strong></p>
- <p><span class="label">类型:</span> ${{nodeData.节点类型 || (nodeData.isRoot ? "根节点" : "维度")}}</p>
- <p><span class="label">层级:</span> ${{nodeData.节点层级 || "-"}}</p>
- `;
- if (nodeData.所属分类 && nodeData.所属分类.length > 0) {{
- html += `<p><span class="label">所属分类:</span> ${{nodeData.所属分类.join(" > ")}}</p>`;
- }}
- if (nodeData.帖子数) {{
- html += `<p><span class="label">帖子数:</span> ${{nodeData.帖子数}}</p>`;
- }}
- // 统计边类型
- const inEdgeTypes = {{}};
- const outEdgeTypes = {{}};
- inEdges.forEach(e => {{ inEdgeTypes[e.边类型] = (inEdgeTypes[e.边类型] || 0) + 1; }});
- outEdges.forEach(e => {{ outEdgeTypes[e.边类型] = (outEdgeTypes[e.边类型] || 0) + 1; }});
- // 入边统计
- html += `<h4 style="margin-top:12px;color:#3498db;font-size:12px;">📥 入边 (${{inEdges.length}})</h4>`;
- if (inEdges.length > 0) {{
- html += `<div class="edge-list">`;
- for (const [type, count] of Object.entries(inEdgeTypes)) {{
- html += `<div class="edge-type-item"><span class="edge-type">${{type}}</span><span class="edge-count">${{count}}</span></div>`;
- }}
- // 显示前5条入边详情
- const showInEdges = inEdges.slice(0, 5);
- showInEdges.forEach(e => {{
- const srcName = personaTreeData.nodes.find(n => n.节点ID === e.源节点ID)?.节点名称 || e.源节点ID;
- html += `<div class="edge-detail">← ${{srcName}} <span class="edge-type-tag">${{e.边类型}}</span></div>`;
- }});
- if (inEdges.length > 5) {{
- html += `<div class="edge-more">... 还有 ${{inEdges.length - 5}} 条</div>`;
- }}
- html += `</div>`;
- }} else {{
- html += `<div class="edge-empty">无</div>`;
- }}
- // 出边统计
- html += `<h4 style="margin-top:12px;color:#e74c3c;font-size:12px;">📤 出边 (${{outEdges.length}})</h4>`;
- if (outEdges.length > 0) {{
- html += `<div class="edge-list">`;
- for (const [type, count] of Object.entries(outEdgeTypes)) {{
- html += `<div class="edge-type-item"><span class="edge-type">${{type}}</span><span class="edge-count">${{count}}</span></div>`;
- }}
- // 显示前5条出边详情
- const showOutEdges = outEdges.slice(0, 5);
- showOutEdges.forEach(e => {{
- const tgtName = personaTreeData.nodes.find(n => n.节点ID === e.目标节点ID)?.节点名称 || e.目标节点ID;
- html += `<div class="edge-detail">→ ${{tgtName}} <span class="edge-type-tag">${{e.边类型}}</span></div>`;
- }});
- if (outEdges.length > 5) {{
- html += `<div class="edge-more">... 还有 ${{outEdges.length - 5}} 条</div>`;
- }}
- html += `</div>`;
- }} else {{
- html += `<div class="edge-empty">无</div>`;
- }}
- document.getElementById("detailContent").innerHTML = html;
- }}
- function showEdgeInfo(d) {{
- const panel = document.getElementById("detailPanel");
- panel.classList.add("active");
- const sourceNode = typeof d.source === "object" ? d.source : {{ id: d.source }};
- const targetNode = typeof d.target === "object" ? d.target : {{ id: d.target }};
- // 判断是否为镜像边
- const isMirror = d.type.startsWith("镜像_");
- document.getElementById("detailTitle").textContent = isMirror ? "🪞 镜像边详情" : "🔗 边详情";
- let html = `
- <p><span class="label">边类型:</span> <strong>${{d.type}}</strong></p>
- <p><span class="label">源节点:</span> ${{sourceNode.节点名称 || sourceNode.id}}</p>
- <p><span class="label">目标节点:</span> ${{targetNode.节点名称 || targetNode.id}}</p>
- `;
- if (d.边详情) {{
- if (d.边详情.相似度 !== undefined) {{
- const score = typeof d.边详情.相似度 === "number" ? d.边详情.相似度.toFixed(2) : d.边详情.相似度;
- html += `<p><span class="label">相似度:</span> <span class="similarity-score">${{score}}</span></p>`;
- }}
- if (d.边详情.说明) {{
- html += `<p><span class="label">说明:</span></p><div class="edge-description">${{d.边详情.说明}}</div>`;
- }}
- if (d.边详情.共现次数 !== undefined) {{
- html += `<p><span class="label">共现次数:</span> ${{d.边详情.共现次数}}</p>`;
- }}
- // 镜像边特有信息
- if (d.边详情.原始边类型) {{
- html += `<p><span class="label">原始边类型:</span> ${{d.边详情.原始边类型}}</p>`;
- }}
- if (d.边详情.源人设节点) {{
- html += `<p><span class="label">源人设节点:</span> ${{d.边详情.源人设节点}}</p>`;
- }}
- if (d.边详情.目标人设节点) {{
- html += `<p><span class="label">目标人设节点:</span> ${{d.边详情.目标人设节点}}</p>`;
- }}
- }}
- document.getElementById("detailContent").innerHTML = html;
- }}
- function closeDetailPanel() {{
- document.getElementById("detailPanel").classList.remove("active");
- }}
- // 更新匹配列表
- function updateMatchList(matchLinks, nodes) {{
- const listEl = document.getElementById("matchList");
- const countEl = document.getElementById("matchCount");
- // 构建节点ID到名称的映射
- const nodeNames = {{}};
- nodes.forEach(n => {{
- nodeNames[n.id] = n.节点名称 || n.id;
- }});
- // 按分数降序排序
- const sortedLinks = [...matchLinks].sort((a, b) => {{
- const scoreA = a.边详情?.相似度 ?? 0;
- const scoreB = b.边详情?.相似度 ?? 0;
- return scoreB - scoreA;
- }});
- countEl.textContent = `(${{sortedLinks.length}})`;
- // 生成列表HTML
- let html = "";
- sortedLinks.forEach((link, index) => {{
- const score = link.边详情?.相似度;
- const scoreText = score !== undefined ? score.toFixed(2) : "N/A";
- const scoreClass = score >= 0.8 ? "high" : (score >= 0.5 ? "medium" : "");
- const srcId = typeof link.source === "object" ? link.source.id : link.source;
- const tgtId = typeof link.target === "object" ? link.target.id : link.target;
- const srcName = nodeNames[srcId] || srcId;
- const tgtName = nodeNames[tgtId] || tgtId;
- html += `
- <div class="match-item" data-index="${{index}}" data-src="${{srcId}}" data-tgt="${{tgtId}}">
- <span class="score ${{scoreClass}}">${{scoreText}}</span>
- <span class="names" title="${{srcName}} → ${{tgtName}}">${{srcName}} → ${{tgtName}}</span>
- </div>
- `;
- }});
- listEl.innerHTML = html;
- // 添加点击事件
- listEl.querySelectorAll(".match-item").forEach(item => {{
- item.addEventListener("click", () => {{
- const srcId = item.dataset.src;
- const tgtId = item.dataset.tgt;
- const index = parseInt(item.dataset.index);
- // 高亮对应的边
- highlightMatchEdge(srcId, tgtId);
- // 更新列表项样式
- listEl.querySelectorAll(".match-item").forEach(el => el.classList.remove("active"));
- item.classList.add("active");
- }});
- }});
- }}
- // 高亮匹配边
- function highlightMatchEdge(srcId, tgtId) {{
- if (!g) return;
- // 重置所有
- g.selectAll(".node").classed("dimmed", true).classed("highlighted", false);
- g.selectAll(".link-group").classed("dimmed", true).classed("highlighted", false);
- // 高亮对应的边和节点
- g.selectAll(".link-group").each(function(d) {{
- const dSrc = typeof d.source === "object" ? d.source.id : d.source;
- const dTgt = typeof d.target === "object" ? d.target.id : d.target;
- if ((dSrc === srcId && dTgt === tgtId) || (dSrc === tgtId && dTgt === srcId)) {{
- d3.select(this).classed("dimmed", false).classed("highlighted", true);
- }}
- }});
- g.selectAll(".node").each(function(d) {{
- if (d.id === srcId || d.id === tgtId) {{
- d3.select(this).classed("dimmed", false).classed("highlighted", true);
- }}
- }});
- }}
- // 获取节点颜色(全局版本,根据节点数据判断维度)
- function getTreeNodeColor(d) {{
- const dimColors = {{ "灵感点": "#f39c12", "目的点": "#3498db", "关键点": "#9b59b6" }};
- if (d.data.isRoot) return "#e94560";
- if (d.data.isDimension) return d.data.dimColor;
- return d.data.dimColor || "#888";
- }}
- // 共享的节点点击处理函数(人设树和关系图复用)
- function handleNodeClick(clickedNodeId, clickedNodeName) {{
- if (!clickedNodeId) return;
- // 动态获取树相关元素
- const treeGroup = d3.select(".persona-tree");
- if (treeGroup.empty()) return;
- const treeEdges = treeGroup.selectAll(".tree-edge");
- // 先重置所有高亮状态
- treeGroup.selectAll(".tree-node")
- .classed("tree-dimmed", false)
- .classed("tree-highlighted", false);
- treeGroup.selectAll(".tree-node .tree-shape")
- .attr("fill", d => getTreeNodeColor(d))
- .attr("stroke", "rgba(255,255,255,0.5)")
- .attr("stroke-width", 1)
- .attr("stroke-opacity", 1)
- .attr("opacity", 1);
- treeGroup.selectAll(".tree-node text")
- .attr("fill", d => (d.data.isRoot || d.data.isDimension) ? getTreeNodeColor(d) : "#bbb")
- .attr("opacity", 1);
- treeEdges.attr("stroke-opacity", 0.3).attr("stroke-width", 1);
- if (g) {{
- g.selectAll(".node").classed("dimmed", false).classed("highlighted", false);
- g.selectAll(".link-group").classed("dimmed", false).classed("highlighted", false);
- }}
- // 构建节点ID到D3节点的映射
- const treeNodeById = {{}};
- treeGroup.selectAll(".tree-node").each(function(n) {{
- if (n.data.节点ID) treeNodeById[n.data.节点ID] = n;
- }});
- // 使用多级配置收集关联节点(与关系图一致)
- const levelConfigs = getLevelConfigs();
- const {{ nodeIds: connectedNodeIds, edges: allConnectedEdges }} = collectNodesAndEdges(clickedNodeId, levelConfigs);
- // 获取D3树节点
- const clickedD3Node = treeNodeById[clickedNodeId];
- // 转换为D3节点集合(只基于 collectNodesAndEdges 的结果,与关系图同步)
- const connectedD3Nodes = new Set();
- if (clickedD3Node) connectedD3Nodes.add(clickedD3Node);
- connectedNodeIds.forEach(id => {{
- if (treeNodeById[id]) connectedD3Nodes.add(treeNodeById[id]);
- }});
- // 高亮树中的节点
- treeGroup.selectAll(".tree-node")
- .classed("tree-dimmed", n => !connectedD3Nodes.has(n))
- .classed("tree-highlighted", n => connectedD3Nodes.has(n));
- // 高亮所有形状(不变粗)
- treeGroup.selectAll(".tree-node .tree-shape")
- .attr("fill", function(n) {{
- if (!connectedD3Nodes.has(n)) return "#555";
- return getTreeNodeColor(n);
- }})
- .attr("stroke", function(n) {{
- if (n.data.节点ID === clickedNodeId) return "#fff";
- return connectedD3Nodes.has(n) ? "rgba(255,255,255,0.8)" : "#333";
- }})
- .attr("stroke-opacity", 1);
- treeGroup.selectAll(".tree-node text")
- .attr("fill", function(n) {{
- if (!connectedD3Nodes.has(n)) return "#555";
- return (n.data.isRoot || n.data.isDimension) ? getTreeNodeColor(n) : "#bbb";
- }});
- // 边高亮(树边基于连接的节点)
- treeEdges.attr("stroke-opacity", function(e) {{
- // 树边高亮条件:子节点(目标)在连接集中,或者两端都在连接集中
- const srcId = e.源节点ID;
- const tgtId = e.目标节点ID;
- const srcConnected = connectedNodeIds.has(srcId) || connectedD3Nodes.has(e.sourceNode);
- const tgtConnected = connectedNodeIds.has(tgtId) || connectedD3Nodes.has(e.targetNode);
- return (srcConnected && tgtConnected) ? 0.9 : 0.15;
- }});
- // 计算入边和出边
- const inEdges = allConnectedEdges.filter(e => e.目标节点ID === clickedNodeId);
- const outEdges = allConnectedEdges.filter(e => e.源节点ID === clickedNodeId);
- // 显示详情面板
- const nodeData = personaTreeData.nodes.find(n => n.节点ID === clickedNodeId);
- if (nodeData) {{
- showTreeNodeDetail(nodeData, inEdges, outEdges);
- }}
- // 显示关系子图(先显示,这样容器高度才正确)
- renderEgoGraph(clickedNodeId, clickedNodeName);
- // 滚动人设树到对应节点位置(放在关系图显示后,高度才准确)
- if (clickedD3Node) {{
- // 用 setTimeout 确保 DOM 更新完成
- setTimeout(() => {{
- const treeContainer = document.getElementById("tree-container");
- const containerHeight = treeContainer.clientHeight;
- // D3树布局中 x 是垂直方向(因为是水平树)
- const nodeY = clickedD3Node.x + 25; // 加上treeGroup的transform偏移
- const targetScroll = nodeY - containerHeight / 2;
- treeContainer.scrollTo({{
- top: Math.max(0, targetScroll),
- behavior: "smooth"
- }});
- }}, 50);
- }}
- // 高亮右侧图中对应节点及其相关节点和边
- if (g) {{
- // 收集相关节点ID(点击的节点及其直接连接的节点)
- const relatedNodeIds = new Set([clickedNodeId]);
- // 找所有与该节点相连的边
- g.selectAll(".link-group").each(function(d) {{
- const srcId = typeof d.source === "object" ? d.source.id : d.source;
- const tgtId = typeof d.target === "object" ? d.target.id : d.target;
- if (srcId === clickedNodeId || tgtId === clickedNodeId) {{
- relatedNodeIds.add(srcId);
- relatedNodeIds.add(tgtId);
- }}
- }});
- // 检查是否有相关节点在图中
- const hasRelatedNodes = g.selectAll(".node").filter(n => relatedNodeIds.has(n.id)).size() > 0;
- if (hasRelatedNodes) {{
- // 高亮相关节点,变灰其他
- g.selectAll(".node")
- .classed("dimmed", n => !relatedNodeIds.has(n.id))
- .classed("highlighted", n => relatedNodeIds.has(n.id));
- // 高亮相关边
- g.selectAll(".link-group").each(function(d) {{
- const srcId = typeof d.source === "object" ? d.source.id : d.source;
- const tgtId = typeof d.target === "object" ? d.target.id : d.target;
- const isRelated = srcId === clickedNodeId || tgtId === clickedNodeId;
- d3.select(this)
- .classed("dimmed", !isRelated)
- .classed("highlighted", isRelated);
- // 显示相关的跨层边
- if (isRelated) {{
- d3.select(this).style("display", "block");
- }}
- }});
- }} else {{
- // 点击的节点不在图中,全部变灰
- g.selectAll(".node").classed("dimmed", true).classed("highlighted", false);
- g.selectAll(".link-group").classed("dimmed", true).classed("highlighted", false);
- }}
- }}
- }}
- // 同步人设树高亮和关系图展示(职责单一:不处理力导向图)
- function syncTreeAndRelationGraph(pathNodeIds, edgeType) {{
- if (!pathNodeIds || pathNodeIds.length === 0) return;
- // 动态获取树相关元素
- const treeGroup = d3.select(".persona-tree");
- if (treeGroup.empty()) return;
- const treeEdges = treeGroup.selectAll(".tree-edge");
- // 重置人设树高亮状态
- treeGroup.selectAll(".tree-node")
- .classed("tree-dimmed", false)
- .classed("tree-highlighted", false);
- treeGroup.selectAll(".tree-node .tree-shape")
- .attr("fill", d => getTreeNodeColor(d))
- .attr("stroke", "rgba(255,255,255,0.5)")
- .attr("stroke-width", 1)
- .attr("stroke-opacity", 1)
- .attr("opacity", 1);
- treeGroup.selectAll(".tree-node text")
- .attr("fill", d => (d.data.isRoot || d.data.isDimension) ? getTreeNodeColor(d) : "#bbb")
- .attr("opacity", 1);
- treeEdges.attr("stroke-opacity", 0.3).attr("stroke-width", 1);
- // 构建节点ID到D3节点的映射
- const treeNodeById = {{}};
- treeGroup.selectAll(".tree-node").each(function(n) {{
- if (n.data.节点ID) treeNodeById[n.data.节点ID] = n;
- }});
- // 路径节点ID集合
- const pathNodeIdSet = new Set(pathNodeIds);
- // 高亮树边(路径上相邻节点之间的边)
- treeEdges.attr("stroke-opacity", function(e) {{
- const srcInPath = pathNodeIdSet.has(e.源节点ID);
- const tgtInPath = pathNodeIdSet.has(e.目标节点ID);
- return (srcInPath && tgtInPath) ? 1 : 0.1;
- }});
- // 高亮路径上的节点
- treeGroup.selectAll(".tree-node").each(function(n) {{
- const nodeId = n.data.节点ID;
- const isInPath = pathNodeIdSet.has(nodeId);
- d3.select(this).select(".tree-shape")
- .attr("fill", isInPath ? getTreeNodeColor(n) : "#555")
- .attr("opacity", 1);
- d3.select(this).select("text")
- .attr("fill", isInPath ?
- ((n.data.isRoot || n.data.isDimension) ? getTreeNodeColor(n) : "#bbb") : "#555")
- .attr("opacity", 1);
- }});
- // 显示路径详情
- const panel = document.getElementById("detailPanel");
- panel.classList.add("active");
- document.getElementById("detailTitle").textContent = "🔗 路径详情";
- // 获取路径上的节点名称
- const pathNodeNames = pathNodeIds.map(id => {{
- const treeNode = treeNodeById[id];
- if (treeNode) return treeNode.data.节点名称 || treeNode.data.name;
- const nodeData = personaTreeData.nodes.find(n => n.节点ID === id);
- return nodeData?.节点名称 || id;
- }});
- let html = `
- <p><span class="label">边类型:</span> <strong>${{edgeType}}</strong></p>
- <p><span class="label">路径节点:</span> ${{pathNodeNames.join(" → ")}}</p>
- <p><span class="label">节点数:</span> ${{pathNodeIds.length}}</p>
- `;
- document.getElementById("detailContent").innerHTML = html;
- // 在关系图中展示路径上的所有节点和边
- renderEgoGraphPath(pathNodeIds, edgeType);
- }}
- // 关系子图(Ego Graph)- 在画布第四层显示
- let currentEgoSimulation = null; // 保存当前的力模拟,用于停止
- let currentEgoCenterNodeId = null; // 当前关系图中心节点ID
- let currentEgoCenterNodeName = null; // 当前关系图中心节点名称
- // 当前选中的层级数
- let currentLevelCount = 1;
- // 切换级联菜单
- function toggleCascadeMenu() {{
- event.stopPropagation();
- const menu = document.getElementById('cascade-menu');
- menu.classList.toggle('show');
- }}
- // 反选指定层级的边类型
- function invertSelection(level) {{
- event.stopPropagation();
- document.querySelectorAll(`.cascade-edge-item input[data-level="${{level}}"]`).forEach(cb => {{
- cb.checked = !cb.checked;
- }});
- // 更新全选复选框状态
- const allItems = document.querySelectorAll(`.cascade-edge-item input[data-level="${{level}}"]`);
- const checkedItems = document.querySelectorAll(`.cascade-edge-item input[data-level="${{level}}"]:checked`);
- const selectAllCb = document.querySelector(`.select-all input[data-level="${{level}}"]`);
- selectAllCb.checked = allItems.length === checkedItems.length;
- // 重新渲染
- if (currentEgoCenterNodeId) {{
- handleNodeClick(currentEgoCenterNodeId, currentEgoCenterNodeName);
- }}
- }}
- // 重置所有层级到默认配置(1级全选,2/3级只选包含)
- function resetSelection() {{
- event.stopPropagation();
- // Level 1: 全选
- document.querySelectorAll('.cascade-edge-item input[data-level="1"]').forEach(cb => {{
- cb.checked = true;
- }});
- document.querySelector('.select-all input[data-level="1"]').checked = true;
- // Level 2 & 3: 只选包含
- [2, 3].forEach(level => {{
- document.querySelectorAll(`.cascade-edge-item input[data-level="${{level}}"]`).forEach(cb => {{
- cb.checked = (cb.dataset.type === "包含");
- }});
- document.querySelector(`.select-all input[data-level="${{level}}"]`).checked = false;
- }});
- // 重新渲染
- if (currentEgoCenterNodeId) {{
- handleNodeClick(currentEgoCenterNodeId, currentEgoCenterNodeName);
- }}
- }}
- // 选择层级
- function selectLevel(level) {{
- event.stopPropagation();
- currentLevelCount = level;
- // 更新层级选中状态
- document.querySelectorAll('.cascade-level-item').forEach(item => {{
- const itemLevel = parseInt(item.dataset.level);
- item.classList.toggle('active', itemLevel === level);
- }});
- // 显示对应的边类型组(1级显示L1,2级显示L1+L2,3级显示L1+L2+L3)
- document.querySelectorAll('.cascade-edge-group').forEach(group => {{
- const groupLevel = parseInt(group.dataset.level);
- group.classList.toggle('active', groupLevel <= level);
- }});
- // 更新按钮显示
- document.getElementById('cascade-label').textContent = level + '级';
- // 重新渲染关系图和人设树高亮
- if (currentEgoCenterNodeId) {{
- handleNodeClick(currentEgoCenterNodeId, currentEgoCenterNodeName);
- }}
- }}
- // 获取指定层级选中的边类型
- function getLevelEdgeTypes(level) {{
- const types = [];
- document.querySelectorAll(`.cascade-edge-item input[data-level="${{level}}"]:checked`).forEach(cb => {{
- types.push(cb.dataset.type);
- }});
- return types;
- }}
- // 获取层级配置(返回每层的边类型数组)
- function getLevelConfigs() {{
- const configs = [];
- for (let i = 1; i <= currentLevelCount; i++) {{
- const types = getLevelEdgeTypes(i);
- configs.push(types);
- }}
- return configs;
- }}
- // 多层级展开:收集指定层级内的所有节点和边(每层可指定不同边类型)
- function collectNodesAndEdges(centerNodeId, levelConfigs) {{
- const nodeIds = new Set([centerNodeId]);
- const collectedEdges = [];
- const visitedEdges = new Set();
- let currentLayer = new Set([centerNodeId]);
- for (let d = 0; d < levelConfigs.length; d++) {{
- const edgeTypes = levelConfigs[d];
- if (edgeTypes.length === 0) break;
- const nextLayer = new Set();
- personaTreeData.edges.forEach(e => {{
- // 筛选边类型
- if (!edgeTypes.includes(e.边类型)) return;
- const edgeKey = `${{e.源节点ID}}-${{e.目标节点ID}}-${{e.边类型}}`;
- if (visitedEdges.has(edgeKey)) return;
- // 单向查找:只从源节点出发,沿边的方向查找
- // 属于:子→父(从子出发找父)
- // 包含:父→子(从父出发找子)
- // 共现:A→B(从A出发找B)
- if (currentLayer.has(e.源节点ID)) {{
- visitedEdges.add(edgeKey);
- collectedEdges.push({{...e, _level: d + 1}});
- // 添加目标节点到下一层
- if (!nodeIds.has(e.目标节点ID)) {{
- nextLayer.add(e.目标节点ID);
- nodeIds.add(e.目标节点ID);
- }}
- }}
- }});
- currentLayer = nextLayer;
- if (nextLayer.size === 0) break;
- }}
- return {{ nodeIds, edges: collectedEdges, depth: levelConfigs.length }};
- }}
- function renderEgoGraph(centerNodeId, centerNodeName) {{
- // 保存当前中心节点
- currentEgoCenterNodeId = centerNodeId;
- currentEgoCenterNodeName = centerNodeName;
- // 显示关系图容器
- document.getElementById("ego-container").style.display = "block";
- // 获取关系图层组
- const egoGroup = d3.select(".ego-graph-content");
- if (egoGroup.empty()) return;
- // 停止之前的模拟
- if (currentEgoSimulation) {{
- currentEgoSimulation.stop();
- currentEgoSimulation = null;
- }}
- // 清除旧内容
- egoGroup.selectAll("*").remove();
- // 获取当前层级配置
- const levelConfigs = getLevelConfigs();
- // 更新顶部标题和统计
- document.getElementById("ego-node-name").textContent = centerNodeName;
- // 获取层半径
- const radius = 160; // 固定半径
- // 根据层级配置收集节点和边
- const {{ nodeIds, edges: relatedEdges, depth }} = collectNodesAndEdges(centerNodeId, levelConfigs);
- // 构建节点数据(确保中心节点始终包含)
- const nodeMap = {{}};
- personaTreeData.nodes.forEach(n => {{
- if (nodeIds.has(n.节点ID) || n.节点ID === centerNodeId) {{
- nodeMap[n.节点ID] = {{
- id: n.节点ID,
- name: n.节点名称,
- type: n.节点类型,
- level: n.节点层级,
- isCenter: n.节点ID === centerNodeId
- }};
- }}
- }});
- const nodes = Object.values(nodeMap);
- // 处理同一对节点间的多条边,分配不同弧度
- const linksByPair = {{}};
- relatedEdges.forEach(e => {{
- // 用排序后的节点对作为key,确保A-B和B-A是同一对
- const pairKey = [e.源节点ID, e.目标节点ID].sort().join("||");
- if (!linksByPair[pairKey]) linksByPair[pairKey] = [];
- linksByPair[pairKey].push(e);
- }});
- // 为每条边分配弧度索引
- const links = [];
- Object.values(linksByPair).forEach(pairEdges => {{
- const count = pairEdges.length;
- pairEdges.forEach((e, i) => {{
- // 弧度:0表示直线,正负值表示向两侧弯曲
- let curvature = 0;
- if (count > 1) {{
- // 多条边时,均匀分布弧度
- curvature = (i - (count - 1) / 2) * 0.3;
- }}
- links.push({{
- source: e.源节点ID,
- target: e.目标节点ID,
- type: e.边类型,
- curvature: curvature
- }});
- }});
- }});
- // 根据节点数量动态计算实际使用的半径
- const nodeCount = nodes.length;
- const nodeSpacingEgo = 65; // 节点间距(增大)
- const minEgoRadius = 120;
- const maxEgoRadius = Math.max(radius, 250); // 允许更大的半径
- let actualRadius;
- if (nodeCount <= 1) {{
- actualRadius = minEgoRadius;
- }} else {{
- const circumference = nodeCount * nodeSpacingEgo;
- const calcR = circumference / (2 * Math.PI);
- actualRadius = Math.max(minEgoRadius, Math.min(maxEgoRadius, calcR));
- }}
- // 更新顶部统计信息
- document.getElementById("ego-stats").textContent = `${{nodeCount}}节点 ${{relatedEdges.length}}边`;
- // 如果只有中心节点,只渲染中心节点
- if (nodes.length === 1) {{
- const centerNode = nodes[0];
- // 获取中心节点的维度颜色
- const dimColors = {{
- "灵感点": "#f39c12",
- "目的点": "#3498db",
- "关键点": "#9b59b6"
- }};
- const level = centerNode.level || "";
- let fillColor = "#888";
- if (level.includes("灵感点")) fillColor = dimColors["灵感点"];
- else if (level.includes("目的点")) fillColor = dimColors["目的点"];
- else if (level.includes("关键点")) fillColor = dimColors["关键点"];
- // 绘制中心节点
- const nodeGroup = egoGroup.append("g")
- .attr("class", "ego-node-group")
- .attr("transform", "translate(0, 0)");
- nodeGroup.append("circle")
- .attr("r", 22)
- .attr("fill", fillColor)
- .attr("stroke", "#fff")
- .attr("stroke-width", 3)
- .attr("cursor", "pointer")
- .style("filter", "drop-shadow(0 2px 4px rgba(0,0,0,0.3))");
- nodeGroup.append("text")
- .attr("dy", "0.35em")
- .attr("text-anchor", "middle")
- .attr("fill", "#fff")
- .attr("font-size", "10px")
- .attr("font-weight", "bold")
- .attr("pointer-events", "none")
- .text(centerNode.name.length > 4 ? centerNode.name.slice(0, 4) + "..." : centerNode.name);
- // 显示提示文字
- egoGroup.append("text")
- .attr("y", 50)
- .attr("text-anchor", "middle")
- .attr("fill", "rgba(255,255,255,0.4)")
- .attr("font-size", "10px")
- .text("无相关边");
- return;
- }}
- // 边类型颜色(统一用实线)
- const edgeColors = {{
- "属于": "#9b59b6", // 紫色 - 层级关系
- "包含": "#ffb6c1", // 淡粉 - 分类包含标签(向下)
- "分类共现(跨点)": "#2ecc71", // 绿色 - 跨帖子分类共现
- "分类共现(点内)": "#3498db", // 蓝色 - 同帖子分类共现
- "标签共现": "#f39c12" // 橙色 - 标签共现
- }};
- // 维度颜色(与人设树完全一致)
- const dimColors = {{
- "灵感点": "#f39c12",
- "目的点": "#3498db",
- "关键点": "#9b59b6"
- }};
- // 获取节点的维度颜色(与人设树一致)
- function getNodeDimColor(d) {{
- // 根据节点层级判断维度
- const level = d.level || "";
- if (level.includes("灵感点")) return dimColors["灵感点"];
- if (level.includes("目的点")) return dimColors["目的点"];
- if (level.includes("关键点")) return dimColors["关键点"];
- return "#888";
- }}
- // 获取节点填充色(实心,用维度颜色,不因选中而改变)
- function getNodeFill(d) {{
- return getNodeDimColor(d); // 始终用维度颜色填充
- }}
- // 获取节点边框色(选中节点用白色边框区分)
- function getNodeStroke(d) {{
- if (d.isCenter) return "#fff"; // 选中节点白色边框
- return "rgba(255,255,255,0.5)"; // 普通节点半透明白边框
- }}
- // 获取节点边框粗细(选中节点更粗)
- function getNodeStrokeWidth(d) {{
- return d.isCenter ? 3 : 1.5;
- }}
- // 根据节点数量调整力模拟参数
- const linkDistance = Math.max(50, Math.min(80, actualRadius / 2.5));
- const chargeStrength = Math.max(-300, Math.min(-100, -nodeCount * 10));
- const collisionRadius = 35; // 碰撞半径,防止重叠
- // 创建力导向模拟(中心在0,0因为已经平移了)
- const simulation = d3.forceSimulation(nodes)
- .force("link", d3.forceLink(links).id(d => d.id).distance(linkDistance))
- .force("charge", d3.forceManyBody().strength(chargeStrength))
- .force("center", d3.forceCenter(0, 0))
- .force("collision", d3.forceCollide().radius(collisionRadius))
- .force("boundary", function() {{
- // 限制节点在圆形区域内
- const maxR = actualRadius - 30;
- return function(alpha) {{
- nodes.forEach(d => {{
- const dist = Math.sqrt(d.x * d.x + d.y * d.y);
- if (dist > maxR) {{
- const scale = maxR / dist;
- d.x *= scale;
- d.y *= scale;
- }}
- }});
- }};
- }}());
- currentEgoSimulation = simulation;
- // 绘制边(用曲线支持多边)
- const link = egoGroup.selectAll(".ego-edge")
- .data(links)
- .join("path")
- .attr("class", "ego-edge")
- .attr("stroke", d => edgeColors[d.type] || "#666")
- .attr("stroke-width", 1.5)
- .attr("stroke-opacity", 0.7)
- .attr("fill", "none");
- // 绘制节点(分类用方形,标签用圆形)
- const node = egoGroup.selectAll(".ego-node")
- .data(nodes)
- .join("g")
- .attr("class", d => "ego-node" + (d.isCenter ? " center" : ""));
- // 根据节点类型绘制不同形状(与人设树样式一致)
- const nodeSize = 8;
- node.each(function(d) {{
- const el = d3.select(this);
- const fill = getNodeFill(d);
- const stroke = getNodeStroke(d);
- const size = d.isCenter ? nodeSize + 2 : nodeSize;
- const strokeWidth = getNodeStrokeWidth(d);
- if (d.type === "分类") {{
- // 方形(分类节点)- 与人设树一致
- el.append("rect")
- .attr("class", "ego-shape")
- .attr("width", size * 2)
- .attr("height", size * 2)
- .attr("x", -size)
- .attr("y", -size)
- .attr("fill", fill)
- .attr("stroke", stroke)
- .attr("stroke-width", strokeWidth)
- .attr("rx", 1);
- }} else {{
- // 圆形(标签节点)- 与人设树一致
- el.append("circle")
- .attr("class", "ego-shape")
- .attr("r", size)
- .attr("fill", fill)
- .attr("stroke", stroke)
- .attr("stroke-width", strokeWidth);
- }}
- }});
- node.append("text")
- .attr("dy", -12)
- .attr("text-anchor", "middle")
- .attr("font-size", "9px")
- .attr("fill", "#fff")
- .text(d => d.name.length > 6 ? d.name.substring(0, 6) + ".." : d.name);
- // 添加点击事件(直接调用共享函数)
- node.on("click", function(event, d) {{
- event.stopPropagation();
- handleNodeClick(d.id, d.name);
- }})
- .on("mouseenter", function(event, d) {{
- // 悬停高亮:高亮到激活节点的路径
- if (!currentEgoCenterNodeId || d.id === currentEgoCenterNodeId) return;
- highlightPathInEgoGraph(d.id);
- }})
- .on("mouseleave", function(event, d) {{
- // 移出时恢复
- if (!currentEgoCenterNodeId) return;
- resetEgoGraphHighlight();
- }});
- // 边点击事件(直接调用共享函数)
- link.on("click", function(event, d) {{
- event.stopPropagation();
- handleEdgeClick(d.source.id, d.target.id, d.type);
- }});
- // 生成曲线路径的函数
- function linkPath(d) {{
- const sx = d.source.x, sy = d.source.y;
- const tx = d.target.x, ty = d.target.y;
- if (d.curvature === 0) {{
- // 直线
- return `M${{sx}},${{sy}}L${{tx}},${{ty}}`;
- }} else {{
- // 曲线:计算控制点
- const dx = tx - sx, dy = ty - sy;
- const dist = Math.sqrt(dx * dx + dy * dy);
- // 控制点垂直于连线方向偏移
- const mx = (sx + tx) / 2;
- const my = (sy + ty) / 2;
- const offset = d.curvature * dist * 0.5;
- // 垂直方向单位向量
- const nx = -dy / dist, ny = dx / dist;
- const cx = mx + nx * offset;
- const cy = my + ny * offset;
- return `M${{sx}},${{sy}}Q${{cx}},${{cy}} ${{tx}},${{ty}}`;
- }}
- }}
- // 更新位置
- simulation.on("tick", () => {{
- link.attr("d", linkPath);
- node.attr("transform", d => `translate(${{d.x}},${{d.y}})`);
- }});
- }}
- function clearEgoGraph() {{
- const egoGroup = d3.select(".ego-graph-content");
- if (!egoGroup.empty()) {{
- egoGroup.selectAll("*").remove();
- }}
- // 隐藏关系图容器
- document.getElementById("ego-container").style.display = "none";
- // 停止模拟
- if (currentEgoSimulation) {{
- currentEgoSimulation.stop();
- currentEgoSimulation = null;
- }}
- }}
- // 在关系图中高亮从悬停节点到激活节点的路径
- function highlightPathInEgoGraph(hoveredNodeId) {{
- const egoGroup = d3.select(".ego-graph-content");
- if (egoGroup.empty()) return;
- // 获取关系图中的边数据
- const egoEdges = egoGroup.selectAll(".ego-edge");
- const egoNodes = egoGroup.selectAll(".ego-node");
- if (egoEdges.empty()) return;
- // 构建邻接表用于路径查找
- const adjacency = {{}};
- const edgeMap = {{}};
- egoEdges.each(function(d) {{
- const srcId = d.source.id || d.source;
- const tgtId = d.target.id || d.target;
- if (!adjacency[srcId]) adjacency[srcId] = [];
- if (!adjacency[tgtId]) adjacency[tgtId] = [];
- adjacency[srcId].push(tgtId);
- adjacency[tgtId].push(srcId);
- // 记录边(双向)
- const key1 = `${{srcId}}|${{tgtId}}`;
- const key2 = `${{tgtId}}|${{srcId}}`;
- edgeMap[key1] = d;
- edgeMap[key2] = d;
- }});
- // BFS找路径
- const visited = new Set();
- const parent = {{}};
- const queue = [currentEgoCenterNodeId];
- visited.add(currentEgoCenterNodeId);
- let found = false;
- while (queue.length > 0 && !found) {{
- const curr = queue.shift();
- const neighbors = adjacency[curr] || [];
- for (const next of neighbors) {{
- if (!visited.has(next)) {{
- visited.add(next);
- parent[next] = curr;
- queue.push(next);
- if (next === hoveredNodeId) {{
- found = true;
- break;
- }}
- }}
- }}
- }}
- if (!found) return;
- // 回溯路径
- const pathNodes = new Set();
- const pathEdgeKeys = new Set();
- let curr = hoveredNodeId;
- while (curr !== undefined) {{
- pathNodes.add(curr);
- const prev = parent[curr];
- if (prev !== undefined) {{
- pathEdgeKeys.add(`${{prev}}|${{curr}}`);
- pathEdgeKeys.add(`${{curr}}|${{prev}}`);
- }}
- curr = prev;
- }}
- // 隐藏不在路径上的边(保持布局不变)
- egoEdges
- .style("visibility", function(d) {{
- const srcId = d.source.id || d.source;
- const tgtId = d.target.id || d.target;
- const key = `${{srcId}}|${{tgtId}}`;
- return pathEdgeKeys.has(key) ? "visible" : "hidden";
- }});
- // 隐藏不在路径上的节点(保持布局不变)
- egoNodes
- .style("visibility", function(d) {{
- return pathNodes.has(d.id) ? "visible" : "hidden";
- }});
- }}
- // 恢复关系图的高亮状态
- function resetEgoGraphHighlight() {{
- const egoGroup = d3.select(".ego-graph-content");
- if (egoGroup.empty()) return;
- // 恢复边的可见性
- egoGroup.selectAll(".ego-edge")
- .style("visibility", "visible");
- // 恢复节点的可见性
- egoGroup.selectAll(".ego-node")
- .style("visibility", "visible");
- }}
- // 渲染路径上的所有节点和边(点击镜像边/二阶边时调用)
- function renderEgoGraphPath(pathNodeIds, edgeType) {{
- if (!pathNodeIds || pathNodeIds.length === 0) return;
- // 显示关系图容器
- document.getElementById("ego-container").style.display = "block";
- const egoGroup = d3.select(".ego-graph-content");
- if (egoGroup.empty()) return;
- // 停止之前的模拟
- if (currentEgoSimulation) {{
- currentEgoSimulation.stop();
- currentEgoSimulation = null;
- }}
- // 清除旧内容
- egoGroup.selectAll("*").remove();
- // 边类型颜色
- const edgeColors = {{
- "属于": "#9b59b6",
- "包含": "#ffb6c1",
- "分类共现(跨点)": "#2ecc71",
- "分类共现(点内)": "#3498db",
- "标签共现": "#f39c12"
- }};
- // 维度颜色
- const dimColors = {{
- "灵感点": "#f39c12",
- "目的点": "#3498db",
- "关键点": "#9b59b6"
- }};
- // 获取节点颜色
- function getNodeColor(nodeData) {{
- const level = nodeData.节点层级 || "";
- if (level.includes("灵感点")) return dimColors["灵感点"];
- if (level.includes("目的点")) return dimColors["目的点"];
- if (level.includes("关键点")) return dimColors["关键点"];
- return "#888";
- }}
- // 获取路径节点数据
- const pathNodes = pathNodeIds.map(id => {{
- const nodeData = personaTreeData.nodes.find(n => n.节点ID === id);
- return nodeData || {{ 节点ID: id, 节点名称: id, 节点类型: "标签" }};
- }});
- // 找出路径上相邻节点之间的边
- const pathEdges = [];
- for (let i = 0; i < pathNodeIds.length - 1; i++) {{
- const srcId = pathNodeIds[i];
- const tgtId = pathNodeIds[i + 1];
- // 在 personaTreeData.edges 中查找
- const edge = personaTreeData.edges.find(e =>
- (e.源节点ID === srcId && e.目标节点ID === tgtId) ||
- (e.源节点ID === tgtId && e.目标节点ID === srcId)
- );
- pathEdges.push(edge || {{ 边类型: edgeType, 源节点ID: srcId, 目标节点ID: tgtId }});
- }}
- // 更新顶部标题
- document.getElementById("ego-node-name").textContent = edgeType;
- document.getElementById("ego-stats").textContent = `${{pathNodes.length}}节点 ${{pathEdges.length}}边`;
- // 水平线性布局
- const nodeSpacing = 80;
- const totalWidth = (pathNodes.length - 1) * nodeSpacing;
- const startX = -totalWidth / 2;
- // 绘制边
- pathEdges.forEach((edge, i) => {{
- const x1 = startX + i * nodeSpacing;
- const x2 = startX + (i + 1) * nodeSpacing;
- // 边的可点击区域(更宽的透明线)
- egoGroup.append("line")
- .attr("class", "ego-edge-hitarea")
- .attr("x1", x1)
- .attr("y1", 0)
- .attr("x2", x2)
- .attr("y2", 0)
- .attr("stroke", "transparent")
- .attr("stroke-width", 15)
- .style("cursor", "pointer")
- .on("click", (event) => {{
- event.stopPropagation();
- handleEdgeClick(edge.源节点ID, edge.目标节点ID, edge.边类型);
- }});
- // 可见的边
- egoGroup.append("line")
- .attr("class", "ego-edge")
- .attr("x1", x1)
- .attr("y1", 0)
- .attr("x2", x2)
- .attr("y2", 0)
- .attr("stroke", edgeColors[edge.边类型] || "#666")
- .attr("stroke-width", 3)
- .attr("stroke-opacity", 0.8)
- .style("pointer-events", "none");
- // 边类型标签
- egoGroup.append("text")
- .attr("x", (x1 + x2) / 2)
- .attr("y", 20)
- .attr("text-anchor", "middle")
- .attr("fill", "#999")
- .attr("font-size", "9px")
- .style("pointer-events", "none")
- .text(edge.边类型);
- }});
- // 绘制节点
- pathNodes.forEach((nodeData, i) => {{
- const x = startX + i * nodeSpacing;
- const nodeGroup = egoGroup.append("g")
- .attr("class", "ego-node")
- .attr("transform", `translate(${{x}}, 0)`)
- .style("cursor", "pointer")
- .on("click", (event) => {{
- event.stopPropagation();
- handleNodeClick(nodeData.节点ID, nodeData.节点名称 || nodeData.name);
- }});
- const nodeSize = 15;
- const nodeColor = getNodeColor(nodeData);
- if (nodeData.节点类型 === "分类") {{
- nodeGroup.append("rect")
- .attr("width", nodeSize * 2)
- .attr("height", nodeSize * 2)
- .attr("x", -nodeSize)
- .attr("y", -nodeSize)
- .attr("fill", nodeColor)
- .attr("stroke", "rgba(255,255,255,0.5)")
- .attr("stroke-width", 2)
- .attr("rx", 2);
- }} else {{
- nodeGroup.append("circle")
- .attr("r", nodeSize)
- .attr("fill", nodeColor)
- .attr("stroke", "rgba(255,255,255,0.5)")
- .attr("stroke-width", 2);
- }}
- // 节点名称
- nodeGroup.append("text")
- .attr("dy", -nodeSize - 8)
- .attr("text-anchor", "middle")
- .attr("fill", "#fff")
- .attr("font-size", "10px")
- .style("pointer-events", "none")
- .text(nodeData.节点名称 || nodeData.name || nodeData.节点ID);
- }});
- }}
- // 渲染单条边和两个节点(点击树边时调用)
- function renderEgoGraphEdge(edgeData, sourceNode, targetNode) {{
- // 显示关系图容器
- document.getElementById("ego-container").style.display = "block";
- const egoGroup = d3.select(".ego-graph-content");
- if (egoGroup.empty()) return;
- // 停止之前的模拟
- if (currentEgoSimulation) {{
- currentEgoSimulation.stop();
- currentEgoSimulation = null;
- }}
- // 清除旧内容
- egoGroup.selectAll("*").remove();
- // 更新顶部标题
- document.getElementById("ego-node-name").textContent = edgeData.边类型;
- document.getElementById("ego-stats").textContent = "2节点 1边";
- const radius = 160;
- // 边类型颜色
- const edgeColors = {{
- "属于": "#9b59b6",
- "包含": "#ffb6c1",
- "分类共现(跨点)": "#2ecc71",
- "分类共现(点内)": "#3498db",
- "标签共现": "#f39c12"
- }};
- // 维度颜色
- const dimColors = {{
- "灵感点": "#f39c12",
- "目的点": "#3498db",
- "关键点": "#9b59b6"
- }};
- // 获取节点颜色
- function getNodeColor(nodeData) {{
- const level = nodeData.节点层级 || "";
- if (level.includes("灵感点")) return dimColors["灵感点"];
- if (level.includes("目的点")) return dimColors["目的点"];
- if (level.includes("关键点")) return dimColors["关键点"];
- return "#888";
- }}
- // 两个节点的位置
- const srcX = -60, srcY = 0;
- const tgtX = 60, tgtY = 0;
- // 绘制边
- egoGroup.append("line")
- .attr("class", "ego-edge")
- .attr("x1", srcX)
- .attr("y1", srcY)
- .attr("x2", tgtX)
- .attr("y2", tgtY)
- .attr("stroke", edgeColors[edgeData.边类型] || "#666")
- .attr("stroke-width", 3)
- .attr("stroke-opacity", 0.8);
- // 获取节点数据
- const srcData = sourceNode ? sourceNode.data : {{}};
- const tgtData = targetNode ? targetNode.data : {{}};
- // 绘制源节点
- const srcGroup = egoGroup.append("g")
- .attr("class", "ego-node")
- .attr("transform", `translate(${{srcX}}, ${{srcY}})`);
- const srcSize = 15;
- const srcColor = getNodeColor(srcData);
- if (srcData.节点类型 === "分类") {{
- srcGroup.append("rect")
- .attr("width", srcSize * 2)
- .attr("height", srcSize * 2)
- .attr("x", -srcSize)
- .attr("y", -srcSize)
- .attr("fill", srcColor)
- .attr("stroke", "rgba(255,255,255,0.5)")
- .attr("stroke-width", 2)
- .attr("rx", 2);
- }} else {{
- srcGroup.append("circle")
- .attr("r", srcSize)
- .attr("fill", srcColor)
- .attr("stroke", "rgba(255,255,255,0.5)")
- .attr("stroke-width", 2);
- }}
- srcGroup.append("text")
- .attr("dy", -srcSize - 8)
- .attr("text-anchor", "middle")
- .attr("fill", "#fff")
- .attr("font-size", "11px")
- .text(srcData.节点名称 || srcData.name || "源节点");
- // 绘制目标节点
- const tgtGroup = egoGroup.append("g")
- .attr("class", "ego-node")
- .attr("transform", `translate(${{tgtX}}, ${{tgtY}})`);
- const tgtSize = 15;
- const tgtColor = getNodeColor(tgtData);
- if (tgtData.节点类型 === "分类") {{
- tgtGroup.append("rect")
- .attr("width", tgtSize * 2)
- .attr("height", tgtSize * 2)
- .attr("x", -tgtSize)
- .attr("y", -tgtSize)
- .attr("fill", tgtColor)
- .attr("stroke", "rgba(255,255,255,0.5)")
- .attr("stroke-width", 2)
- .attr("rx", 2);
- }} else {{
- tgtGroup.append("circle")
- .attr("r", tgtSize)
- .attr("fill", tgtColor)
- .attr("stroke", "rgba(255,255,255,0.5)")
- .attr("stroke-width", 2);
- }}
- tgtGroup.append("text")
- .attr("dy", -tgtSize - 8)
- .attr("text-anchor", "middle")
- .attr("fill", "#fff")
- .attr("font-size", "11px")
- .text(tgtData.节点名称 || tgtData.name || "目标节点");
- // 边标签
- egoGroup.append("text")
- .attr("y", 25)
- .attr("text-anchor", "middle")
- .attr("fill", "rgba(255,255,255,0.6)")
- .attr("font-size", "10px")
- .text(edgeData.边类型);
- }}
- // 页面加载完成后初始化
- window.addEventListener("load", init);
- window.addEventListener("resize", () => {{
- if (currentIndex >= 0) {{
- renderGraph(allGraphData[currentIndex]);
- }}
- }});
- </script>
- </body>
- </html>
- '''
- def generate_combined_html(all_graph_data: List[Dict], persona_tree_data: Dict, output_file: Path):
- """
- 生成包含所有帖子图谱的HTML文件
- Args:
- all_graph_data: 所有帖子的图谱数据列表
- persona_tree_data: 完整的人设树数据(节点和边)
- output_file: 输出文件路径
- """
- # 生成Tab HTML
- tabs_html = ""
- for i, data in enumerate(all_graph_data):
- post_title = data.get("postTitle", "")
- # 使用帖子标题,如果太长则截断
- if post_title:
- tab_name = post_title[:15] + "..." if len(post_title) > 15 else post_title
- else:
- tab_name = f"帖子 {i+1}"
- active_class = "active" if i == 0 else ""
- tabs_html += f'<div class="tab {active_class}" data-index="{i}">{tab_name}</div>\n'
- # 生成HTML
- html_content = HTML_TEMPLATE.format(
- tabs_html=tabs_html,
- all_graph_data=json.dumps(all_graph_data, ensure_ascii=False),
- persona_tree_data=json.dumps(persona_tree_data, ensure_ascii=False)
- )
- with open(output_file, "w", encoding="utf-8") as f:
- f.write(html_content)
- def main():
- # 使用路径配置
- config = PathConfig()
- print(f"账号: {config.account_name}")
- print(f"输出版本: {config.output_version}")
- print()
- # 输入目录
- match_graph_dir = config.intermediate_dir / "match_graph"
- # 输出文件
- output_file = config.intermediate_dir / "match_graph.html"
- print(f"输入目录: {match_graph_dir}")
- print(f"输出文件: {output_file}")
- print()
- # 读取人设树中间数据
- persona_tree_file = config.intermediate_dir / "persona_tree.json"
- persona_tree_data = {"nodes": [], "edges": []}
- if persona_tree_file.exists():
- print(f"读取人设树数据: {persona_tree_file.name}")
- with open(persona_tree_file, "r", encoding="utf-8") as f:
- tree_data = json.load(f)
- persona_tree_data["nodes"] = tree_data.get("nodes", [])
- persona_tree_data["edges"] = tree_data.get("edges", [])
- category_count = len([n for n in persona_tree_data["nodes"] if n.get("节点类型") == "分类"])
- tag_count = len([n for n in persona_tree_data["nodes"] if n.get("节点类型") == "标签"])
- print(f" 分类节点: {category_count}, 标签节点: {tag_count}")
- print(f" 边数: {len(persona_tree_data['edges'])}")
- print()
- # 读取所有匹配图谱文件
- graph_files = sorted(match_graph_dir.glob("*_match_graph.json"))
- print(f"找到 {len(graph_files)} 个匹配图谱文件")
- all_graph_data = []
- for i, graph_file in enumerate(graph_files, 1):
- print(f" [{i}/{len(graph_files)}] 读取: {graph_file.name}")
- with open(graph_file, "r", encoding="utf-8") as f:
- match_graph_data = json.load(f)
- # 提取需要的数据
- graph_data = {
- "postId": match_graph_data["说明"]["帖子ID"],
- "postTitle": match_graph_data["说明"].get("帖子标题", ""),
- "stats": match_graph_data["说明"]["统计"],
- "nodes": match_graph_data["节点列表"],
- "edges": match_graph_data["边列表"],
- "personaEdgeToMirrorEdges": match_graph_data.get("人设边到镜像边映射", {})
- }
- all_graph_data.append(graph_data)
- # 生成HTML
- print("\n生成HTML文件...")
- generate_combined_html(all_graph_data, persona_tree_data, output_file)
- print("\n" + "="*60)
- print("处理完成!")
- print(f"输出文件: {output_file}")
- if __name__ == "__main__":
- main()
|