| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437 |
- #!/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;
- }}
- /* 顶部栏样式 */
- .top-bar {{
- display: flex;
- align-items: center;
- background: #0f3460;
- padding: 6px 20px;
- flex-shrink: 0;
- gap: 20px;
- }}
- .post-selector-container {{
- display: flex;
- align-items: center;
- gap: 8px;
- }}
- .post-selector-label {{
- color: #888;
- font-size: 12px;
- white-space: nowrap;
- }}
- .post-selector {{
- width: 280px;
- padding: 6px 10px;
- background: #1a1a2e;
- border: 1px solid #0f3460;
- border-radius: 4px;
- color: #fff;
- font-size: 12px;
- cursor: pointer;
- outline: none;
- transition: all 0.2s;
- }}
- .post-selector:hover {{
- border-color: #e94560;
- }}
- .post-selector:focus {{
- border-color: #e94560;
- box-shadow: 0 0 0 2px rgba(233, 69, 96, 0.2);
- }}
- .post-selector option {{
- background: #1a1a2e;
- color: #fff;
- }}
- /* 顶部图例样式 */
- .top-legend {{
- display: flex;
- align-items: center;
- gap: 6px;
- margin-left: auto;
- }}
- .top-legend-group {{
- display: flex;
- align-items: center;
- gap: 8px;
- padding: 4px 10px;
- background: rgba(0,0,0,0.3);
- border-radius: 4px;
- }}
- .top-legend-title {{
- color: #fff;
- font-size: 11px;
- font-weight: bold;
- background: #e94560;
- padding: 2px 6px;
- border-radius: 3px;
- margin-right: 6px;
- }}
- .top-legend-item {{
- display: flex;
- align-items: center;
- font-size: 11px;
- color: #fff;
- gap: 4px;
- }}
- .top-legend-circle {{
- width: 10px;
- height: 10px;
- border-radius: 50%;
- border: 1.5px solid rgba(255,255,255,0.8);
- }}
- .top-legend-square {{
- width: 9px;
- height: 9px;
- border-radius: 2px;
- border: 1.5px solid rgba(255,255,255,0.8);
- }}
- .top-legend-line {{
- width: 16px;
- height: 2px;
- }}
- .top-legend-line.dashed {{
- background: none !important;
- border-top: 2px dashed;
- }}
- .top-legend-divider {{
- width: 1px;
- height: 16px;
- background: #444;
- margin: 0 2px;
- }}
- /* 主内容区 */
- .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;
- }}
- .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;
- }}
- /* 帖子详情模态框 */
- .post-detail-modal {{
- display: none;
- position: fixed;
- z-index: 4000;
- left: 0;
- top: 0;
- width: 100%;
- height: 100%;
- background: rgba(0, 0, 0, 0.7);
- overflow: auto;
- }}
- .post-detail-modal.active {{
- display: flex;
- align-items: center;
- justify-content: center;
- padding: 40px 20px;
- }}
- .post-detail-content {{
- position: relative;
- background: white;
- border-radius: 16px;
- max-width: 900px;
- width: 100%;
- max-height: 90vh;
- overflow-y: auto;
- box-shadow: 0 20px 60px rgba(0,0,0,0.3);
- }}
- .post-detail-close {{
- position: sticky;
- top: 20px;
- right: 20px;
- float: right;
- font-size: 36px;
- font-weight: 300;
- color: #9ca3af;
- background: white;
- border: none;
- cursor: pointer;
- width: 40px;
- height: 40px;
- border-radius: 50%;
- display: flex;
- align-items: center;
- justify-content: center;
- z-index: 10;
- box-shadow: 0 2px 8px rgba(0,0,0,0.1);
- }}
- .post-detail-close:hover {{
- color: #ef4444;
- background: #fee2e2;
- }}
- .post-detail-header {{
- padding: 40px 40px 20px 40px;
- border-bottom: 2px solid #e5e7eb;
- }}
- .post-detail-title {{
- font-size: 28px;
- font-weight: bold;
- color: #111827;
- line-height: 1.4;
- margin-bottom: 15px;
- }}
- .post-detail-meta {{
- display: flex;
- justify-content: space-between;
- align-items: center;
- color: #6b7280;
- font-size: 14px;
- gap: 20px;
- }}
- .post-detail-stats {{
- display: flex;
- gap: 15px;
- font-weight: 500;
- }}
- .post-detail-body {{
- padding: 30px 40px;
- }}
- .post-detail-desc {{
- font-size: 16px;
- line-height: 1.8;
- color: #374151;
- margin-bottom: 25px;
- white-space: pre-wrap;
- }}
- .post-detail-images {{
- display: grid;
- grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
- gap: 15px;
- }}
- .post-detail-image {{
- width: 100%;
- border-radius: 12px;
- object-fit: cover;
- }}
- .post-detail-footer {{
- padding: 20px 40px 30px;
- text-align: center;
- border-top: 1px solid #e5e7eb;
- }}
- .post-detail-link {{
- display: inline-block;
- padding: 12px 30px;
- background: linear-gradient(135deg, #ff2442 0%, #ff6b81 100%);
- color: white;
- text-decoration: none;
- border-radius: 25px;
- font-weight: 600;
- }}
- /* 帖子树根节点卡片 */
- .post-card {{
- background: linear-gradient(135deg, #1a1a2e 0%, #16213e 100%);
- border: 2px solid #fff;
- border-radius: 12px;
- cursor: pointer;
- transition: all 0.3s ease;
- box-shadow: 0 4px 15px rgba(255, 255, 255, 0.2);
- height: 100%;
- display: flex;
- flex-direction: column;
- justify-content: center;
- }}
- .post-card:hover {{
- transform: scale(1.05);
- box-shadow: 0 6px 25px rgba(255, 255, 255, 0.4);
- border-color: #fff;
- }}
- .post-card-header {{
- display: flex;
- gap: 10px;
- align-items: center;
- }}
- .post-card-thumbnail-wrapper {{
- position: relative;
- flex-shrink: 0;
- border-radius: 8px;
- overflow: hidden;
- }}
- .post-card-thumbnail {{
- object-fit: cover;
- border-radius: 8px;
- }}
- .post-card-image-count {{
- position: absolute;
- bottom: 2px;
- right: 2px;
- background: rgba(0,0,0,0.7);
- color: #fff;
- padding: 1px 4px;
- border-radius: 3px;
- }}
- .post-card-thumbnail-placeholder {{
- background: linear-gradient(135deg, #0f3460 0%, #1a1a2e 100%);
- border-radius: 8px;
- display: flex;
- align-items: center;
- justify-content: center;
- color: #e94560;
- }}
- .post-card-info {{
- flex: 1;
- overflow: hidden;
- }}
- .post-card-title {{
- color: #fff;
- font-weight: 600;
- line-height: 1.3;
- display: -webkit-box;
- -webkit-box-orient: vertical;
- overflow: hidden;
- text-overflow: ellipsis;
- }}
- .post-card-stats {{
- color: #8892b0;
- display: flex;
- gap: 8px;
- margin-top: 4px;
- }}
- </style>
- </head>
- <body>
- <div id="container">
- <div class="top-bar">
- <div class="post-selector-container">
- <span class="post-selector-label">帖子:</span>
- <select class="post-selector" id="post-selector" onchange="switchTab(this.value)">
- {tabs_html}
- </select>
- </div>
- <div class="top-legend">
- <div class="top-legend-group">
- <span class="top-legend-title">点形状:</span>
- <div class="top-legend-item"><div class="top-legend-circle" style="background:#888;"></div>标签</div>
- <div class="top-legend-item"><div class="top-legend-square" style="background:#888;"></div>分类</div>
- </div>
- <div class="top-legend-group">
- <span class="top-legend-title">点颜色:</span>
- <div class="top-legend-item"><div class="top-legend-circle" style="background:#f39c12;"></div>灵感</div>
- <div class="top-legend-item"><div class="top-legend-circle" style="background:#3498db;"></div>目的</div>
- <div class="top-legend-item"><div class="top-legend-circle" style="background:#9b59b6;"></div>关键</div>
- <div class="top-legend-divider"></div>
- <div class="top-legend-item"><div class="top-legend-circle" style="background:#2ecc71;"></div>人设</div>
- </div>
- <div class="top-legend-group">
- <span class="top-legend-title">边:</span>
- <div class="top-legend-item"><div class="top-legend-line" style="background:#e94560;"></div>相同</div>
- <div class="top-legend-item"><div class="top-legend-line dashed" style="border-color:#e94560;"></div>相似</div>
- <div class="top-legend-divider"></div>
- <div class="top-legend-item"><div class="top-legend-line" style="background:#9b59b6;"></div>属于</div>
- <div class="top-legend-item"><div class="top-legend-line" style="background:#2ecc71;"></div>分类共现</div>
- <div class="top-legend-item"><div class="top-legend-line" style="background:#f39c12;"></div>标签共现</div>
- </div>
- </div>
- </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:#3498db"></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:#2ecc71"></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="包含"><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:#2ecc71"></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:#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="包含"><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:#2ecc71"></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:#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>
- </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);
- // 绑定关系图控制面板事件
- // 全选复选框事件
- 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));
- }}
- }}
- // 构建帖子树数据(从上到下:帖子 -> 维度 -> 点 -> 标签)
- function buildPostTreeData(graphData) {{
- const dimensions = ["灵感点", "目的点", "关键点"];
- const dimColors = {{ "灵感点": "#f39c12", "目的点": "#3498db", "关键点": "#9b59b6" }};
- const dimensionChildren = [];
- let totalNodeCount = 0;
- const postDetail = graphData.postDetail || {{}};
- // 获取帖子点和帖子标签
- const postPointNodes = graphData.帖子点节点列表 || [];
- const postTagNodes = graphData.帖子标签节点列表 || [];
- const belongEdges = graphData.帖子属于边列表 || [];
- // 构建节点映射
- const pointMap = {{}};
- postPointNodes.forEach(n => {{
- pointMap[n.节点ID] = {{
- ...n,
- id: n.节点ID,
- name: n.节点名称,
- nodeType: "点",
- dimColor: dimColors[n.节点层级],
- children: []
- }};
- }});
- const tagMap = {{}};
- postTagNodes.forEach(n => {{
- tagMap[n.节点ID] = {{
- ...n,
- id: n.节点ID,
- name: n.节点名称,
- nodeType: "标签",
- dimColor: dimColors[n.节点层级],
- children: []
- }};
- }});
- // 根据属于边,把标签挂到点下面
- belongEdges.forEach(e => {{
- const tagNode = tagMap[e.源节点ID];
- const pointNode = pointMap[e.目标节点ID];
- if (tagNode && pointNode) {{
- pointNode.children.push(tagNode);
- }}
- }});
- // 按维度分组点节点
- dimensions.forEach(dim => {{
- const dimPoints = postPointNodes
- .filter(n => n.节点层级 === dim)
- .map(n => pointMap[n.节点ID]);
- if (dimPoints.length > 0) {{
- const dimNode = {{
- name: dim,
- 节点名称: dim,
- isDimension: true,
- dimColor: dimColors[dim],
- children: dimPoints
- }};
- dimensionChildren.push(dimNode);
- totalNodeCount += dimPoints.length;
- dimPoints.forEach(p => totalNodeCount += p.children.length);
- }}
- }});
- // 根节点"帖子"
- const title = postDetail.title || "帖子";
- const rootNode = {{
- name: title.length > 15 ? title.substring(0, 15) + "..." : title,
- 节点名称: title,
- isRoot: true,
- postDetail: postDetail,
- children: dimensionChildren
- }};
- return {{ root: rootNode, nodeCount: totalNodeCount, tagMap: tagMap }};
- }}
- // 统一提取边的分数字段(全局函数)
- function getEdgeScore(e) {{
- if (!e.边详情) return null;
- // 优先级:相似度 > Jaccard相似度 > 重叠系数
- if (e.边详情.相似度 !== undefined) return e.边详情.相似度;
- if (e.边详情.Jaccard相似度 !== undefined) return e.边详情.Jaccard相似度;
- if (e.边详情.重叠系数 !== undefined) return e.边详情.重叠系数;
- return null;
- }}
- // 显示帖子详情模态框
- function showPostDetail(postData) {{
- if (!postData) return;
- // 生成图片HTML
- let imagesHtml = '';
- if (postData.images && postData.images.length > 0) {{
- imagesHtml = postData.images.map(img =>
- `<img src="${{img}}" class="post-detail-image" alt="图片" loading="lazy">`
- ).join('');
- }} else {{
- imagesHtml = '<div style="text-align: center; color: #9ca3af; padding: 40px;">暂无图片</div>';
- }}
- const modalHtml = `
- <div class="post-detail-content" onclick="event.stopPropagation()">
- <button class="post-detail-close" onclick="closePostDetail()">×</button>
- <div class="post-detail-header">
- <div class="post-detail-title">${{postData.title || '无标题'}}</div>
- <div class="post-detail-meta">
- <div>
- <span>👤 ${{postData.author || '未知作者'}}</span>
- <span> · 📅 ${{postData.publish_time || ''}}</span>
- </div>
- <div class="post-detail-stats">
- <span>👍 ${{postData.like_count || 0}}</span>
- <span>💬 ${{postData.comment_count || 0}}</span>
- <span>⭐ ${{postData.collect_count || 0}}</span>
- </div>
- </div>
- </div>
- <div class="post-detail-body">
- ${{postData.body_text ? `<div class="post-detail-desc">${{postData.body_text}}</div>` : '<div style="color: #9ca3af;">暂无正文</div>'}}
- <div class="post-detail-images">
- ${{imagesHtml}}
- </div>
- </div>
- <div class="post-detail-footer">
- <a href="${{postData.link || '#'}}" target="_blank" class="post-detail-link">
- 在小红书查看完整内容 →
- </a>
- </div>
- </div>
- `;
- let modal = document.getElementById('postDetailModal');
- if (!modal) {{
- modal = document.createElement('div');
- modal.id = 'postDetailModal';
- modal.className = 'post-detail-modal';
- modal.onclick = closePostDetail;
- document.body.appendChild(modal);
- }}
- modal.innerHTML = modalHtml;
- modal.classList.add('active');
- document.body.style.overflow = 'hidden';
- }}
- function closePostDetail(event) {{
- if (event && event.target !== event.currentTarget) return;
- const modal = document.getElementById('postDetailModal');
- if (modal) {{
- modal.classList.remove('active');
- document.body.style.overflow = '';
- }}
- }}
- // 切换帖子
- function switchTab(index) {{
- currentIndex = parseInt(index);
- // 更新图谱
- renderGraph(allGraphData[currentIndex]);
- }}
- // 渲染图谱
- 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
- .filter(n => !(n.节点ID.startsWith("帖子_") && n.节点类型 === "点"))
- .map(n => ({{
- ...n,
- id: n.节点ID,
- source: n.节点ID.startsWith("帖子_") ? "帖子" : "人设",
- level: n.节点层级
- }}));
- // 判断是否是帖子点节点ID
- function isPostPointId(id) {{
- return id.startsWith("帖子_") && id.includes("_点_");
- }}
- // 过滤掉引用帖子点节点的边
- const rawLinks = data.edges
- .filter(e => !isPostPointId(e.源节点ID) && !isPostPointId(e.目标节点ID))
- .map(e => ({{
- ...e,
- source: e.源节点ID,
- target: e.目标节点ID,
- type: e.边类型,
- score: getEdgeScore(e)
- }}));
- // 去重:同一对节点之间相同类型的边只保留一条
- const seenEdgeKeys = new Set();
- const links = rawLinks.filter(e => {{
- const edgeKey = [e.source, e.target].sort().join("|") + "|" + e.type;
- if (seenEdgeKeys.has(edgeKey)) return false;
- seenEdgeKeys.add(edgeKey);
- return true;
- }});
- // 分离节点类型
- 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"
- }};
- // 获取节点的层级编号(三层结构:帖子标签、人设匹配1层、人设匹配2层)
- function getNodeLayer(d) {{
- if (d.source === "帖子") {{
- return 0; // 帖子标签=0
- }}
- // 人设节点:根据是否扩展分成两层
- return d.是否扩展 ? 2 : 1; // 直接匹配=1, 扩展=2
- }}
- // 统计每层节点数量(三层结构)
- const layerCounts = {{0: 0, 1: 0, 2: 0}};
- nodes.forEach(n => {{
- const layer = getNodeLayer(n);
- layerCounts[layer]++;
- }});
- console.log("每层节点数:", layerCounts);
- // 根据节点数量计算每层圆的半径
- // 三层垂直排列:帖子标签(上)+ 人设匹配1层(中)+ 人设匹配2层(下)
- 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));
- }}
- // 三层统一大小(取最大值)
- const unifiedRadius = Math.max(
- calcRadius(layerCounts[0]),
- calcRadius(layerCounts[1]),
- calcRadius(layerCounts[2])
- );
- const layerRadius = {{
- 0: unifiedRadius, // 帖子标签(上)
- 1: unifiedRadius, // 人设匹配1层(中)
- 2: unifiedRadius // 人设匹配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 = 60;
- const circleHeight = layerRadius[0] * 2 + layerPadding + layerRadius[1] * 2 + layerPadding + layerRadius[2] * 2 + layerPadding;
- const height = Math.max(circleHeight + 80, treeHeight + 80, container.clientHeight);
- // 计算每层圆心坐标(垂直居中排列)
- const layerCenterX = {{}};
- const layerCenterY = {{}};
- // 三层垂直排列,X坐标相同
- const colX = circleAreaCenterX;
- // 帖子标签(上)+ 人设匹配1层(中)+ 人设匹配2层(下)
- layerCenterX[0] = colX;
- layerCenterY[0] = layerRadius[0] + layerPadding / 2 + 20;
- layerCenterX[1] = colX;
- layerCenterY[1] = layerCenterY[0] + layerRadius[0] + layerPadding + layerRadius[1];
- layerCenterX[2] = colX;
- layerCenterY[2] = layerCenterY[1] + layerRadius[1] + layerPadding + layerRadius[2];
- 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: []}};
- nodes.forEach(node => {{
- const layer = getNodeLayer(node);
- if (layerNodes[layer]) 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 postDetail = data.postDetail || {{}};
- window.currentPostDetail = postDetail;
- // 使用预构建的帖子树数据
- const postTree = data.postTree || {{ root: null }};
- // 容器
- const postTreeGroup = g.append("g").attr("class", "post-tree");
- let postTreeActualHeight = 0;
- let postRoot = null;
- // 卡片尺寸
- const cardWidth = 240;
- const cardHeight = 90;
- // 计算目标圆心Y坐标
- const circleYOffsetPreview = 40;
- const targetTagY = layerCenterY[0] + circleYOffsetPreview; // 帖子标签圆心
- const targetPersonaY = layerCenterY[1] + circleYOffsetPreview; // 人设匹配_1层圆心
- const targetExpandedY = layerCenterY[2] + circleYOffsetPreview; // 人设匹配_2层圆心
- const circleGap = targetPersonaY - targetTagY;
- const halfGap = circleGap / 2;
- // 树放在圆的右侧
- const circleRightEdge = circleAreaCenterX + unifiedRadius;
- const treeGap = 120;
- // 记录标签节点的位置(用于下方图的对齐)
- const tagNodePositions = {{}};
- if (postTree && postTree.root) {{
- // D3树布局(只用于帖子→维度→点→标签)
- // separation 根据节点名称长度动态计算
- const postTreeLayout = d3.tree()
- .nodeSize([50, 80])
- .separation((a, b) => {{
- const nameA = a.data.name || '';
- const nameB = b.data.name || '';
- const charWidth = 9;
- const baseGap = 30;
- // 根据两个节点的文字长度计算间距
- const widthA = nameA.length * charWidth / 2;
- const widthB = nameB.length * charWidth / 2;
- const minSep = (widthA + widthB + baseGap) / 50; // 除以 nodeSize[0]
- const defaultSep = a.parent === b.parent ? 1.2 : 1.5;
- return Math.max(minSep, defaultSep);
- }});
- // 从原始节点数据中构建权重映射(标签节点有权重字段)
- const nodeWeightMap = {{}};
- nodes.forEach(n => {{
- if (n.权重 !== undefined) {{
- nodeWeightMap[n.id] = n.权重;
- }}
- }});
- // 过滤掉人设节点,只保留树结构,并补充权重
- function filterTreeData(node) {{
- const filtered = {{ ...node }};
- // 补充权重信息
- if (node.id && nodeWeightMap[node.id] !== undefined) {{
- filtered.权重 = nodeWeightMap[node.id];
- }}
- if (node.children) {{
- filtered.children = node.children
- .filter(c => c.nodeType !== "人设" && c.nodeType !== "人设扩展")
- .map(c => filterTreeData(c));
- }}
- return filtered;
- }}
- const treeOnlyData = filterTreeData(postTree.root);
- postRoot = d3.hierarchy(treeOnlyData);
- postTreeLayout(postRoot);
- // 计算树的边界
- let treeMinX = Infinity, treeMaxX = -Infinity;
- postRoot.descendants().forEach(d => {{
- treeMinX = Math.min(treeMinX, d.x);
- treeMaxX = Math.max(treeMaxX, d.x);
- }});
- // 重新分配Y坐标(前3层层高是后面的一半)
- postRoot.descendants().forEach(d => {{
- if (d.data.isRoot) {{
- d.y = targetTagY - halfGap * 3;
- }} else if (d.data.isDimension) {{
- d.y = targetTagY - halfGap * 2;
- }} else if (d.data.nodeType === "点") {{
- d.y = targetTagY - halfGap;
- }} else if (d.data.nodeType === "标签") {{
- d.y = targetTagY;
- // 记录标签节点位置(同一个ID可能有多个位置)
- // 保存 d 的引用,以便后续 spreadTagPositions 可以更新节点位置
- if (!tagNodePositions[d.data.id]) {{
- tagNodePositions[d.data.id] = [];
- }}
- tagNodePositions[d.data.id].push({{ x: d.x, y: d.y, data: d.data, node: d }});
- }}
- }});
- // 计算偏移
- const postTreeOffsetX = circleRightEdge + treeGap - treeMinX;
- const postTreeOffsetY = 0;
- // 六边形路径
- function hexagonPath(r) {{
- const a = Math.PI / 3;
- let path = "";
- for (let i = 0; i < 6; i++) {{
- const angle = a * i - Math.PI / 2;
- const x = r * Math.cos(angle);
- const y = r * Math.sin(angle);
- path += (i === 0 ? "M" : "L") + x + "," + y;
- }}
- return path + "Z";
- }}
- // 树边路径生成函数
- const treeLinkPath = d => {{
- const sourceY = d.source.data.isRoot ? d.source.y + cardHeight/2 : d.source.y;
- return `M${{d.source.x}},${{sourceY}}
- C${{d.source.x}},${{(sourceY + d.target.y) / 2}}
- ${{d.target.x}},${{(sourceY + d.target.y) / 2}}
- ${{d.target.x}},${{d.target.y}}`;
- }};
- // 为树边添加score字段(从目标节点的权重获取)
- const treeLinkData = postRoot.links().map(d => {{
- d.score = d.target.data.权重 !== undefined ? d.target.data.权重 : null;
- return d;
- }});
- // 绘制树的边(帖子→维度→点→标签)- 用g元素包裹边和分数
- const treeLinkGroups = postTreeGroup.selectAll(".tree-link-group")
- .data(treeLinkData)
- .enter()
- .append("g")
- .attr("class", "tree-link-group");
- // 边的路径
- const treeLinks = treeLinkGroups.append("path")
- .attr("class", "tree-link")
- .attr("d", treeLinkPath)
- .attr("fill", "none")
- .attr("stroke", "#9b59b6")
- .attr("stroke-width", 1.5)
- .attr("stroke-opacity", 0.6);
- // 在有分数的边上显示分数(统一逻辑,居中显示在边上)
- treeLinkGroups.filter(d => d.score !== null)
- .append("text")
- .attr("class", "tree-link-score")
- .attr("x", d => (d.source.x + d.target.x) / 2)
- .attr("y", d => (d.source.y + d.target.y) / 2)
- .attr("dy", "0.35em")
- .attr("text-anchor", "middle")
- .attr("fill", "#fff")
- .attr("font-size", "8px")
- .attr("font-weight", "bold")
- .style("text-shadow", "0 0 3px #9b59b6, 0 0 3px #9b59b6")
- .text(d => d.score.toFixed(2));
- // 绘制树节点(非根节点)
- const treeNodes = postTreeGroup.selectAll(".tree-node")
- .data(postRoot.descendants().filter(d => !d.data.isRoot))
- .enter()
- .append("g")
- .attr("class", "tree-node")
- .attr("transform", d => `translate(${{d.x}},${{d.y}})`)
- .style("cursor", "pointer")
- .on("click", (event, d) => {{
- event.stopPropagation();
- const nodeId = d.data.id || d.data.节点ID;
- const nodeName = d.data.name || d.data.节点名称;
- // 帖子标签节点使用专门的处理函数
- if (d.data.nodeType === "标签") {{
- handlePostTagClick(nodeId, nodeName);
- }} else {{
- handleNodeClick(nodeId, nodeName);
- }}
- }});
- // 节点形状
- // 帖子标签节点点击处理函数(激活所有直连的层内边,效果等价于点击N条层内边的并集)
- function handlePostTagClick(tagNodeId, tagNodeName) {{
- if (!tagNodeId) return;
- // 层内边类型
- const intraLayerEdgeTypes = [
- "标签共现", "分类共现(跨点)", "分类共现(点内)",
- "镜像_标签共现", "镜像_分类共现(跨点)", "镜像_分类共现(点内)",
- "二阶_标签共现", "二阶_分类共现(跨点)", "二阶_分类共现(点内)"
- ];
- // 找到所有与该标签直连的层内边及其索引
- const connectedIntraEdges = [];
- links.forEach((link, index) => {{
- const srcId = typeof link.source === "object" ? link.source.id : link.source;
- const tgtId = typeof link.target === "object" ? link.target.id : link.target;
- if ((srcId === tagNodeId || tgtId === tagNodeId) && intraLayerEdgeTypes.includes(link.type)) {{
- connectedIntraEdges.push({{ link, index }});
- }}
- }});
- console.log("帖子标签直连的层内边数:", connectedIntraEdges.length);
- if (connectedIntraEdges.length === 0) {{
- // 没有层内边,回退到普通处理
- handleNodeClick(tagNodeId, tagNodeName);
- return;
- }}
- // 对每条边调用collectEdgeHighlightData,然后合并结果
- const mergedNodeIds = new Set();
- const mergedLinkIndices = new Set();
- const mergedPathNodes = new Set();
- connectedIntraEdges.forEach(({{ link, index }}) => {{
- const {{ nodeIds, linkIndices, pathNodes }} = collectEdgeHighlightData(link, index);
- nodeIds.forEach(id => mergedNodeIds.add(id));
- linkIndices.forEach(i => mergedLinkIndices.add(i));
- pathNodes.forEach(n => mergedPathNodes.add(n));
- }});
- // 复用applyEdgeHighlight进行高亮(处理左边圆和右边树)
- applyEdgeHighlight(mergedNodeIds, mergedLinkIndices);
- // 在人设树中高亮所有相关路径节点(过滤掉帖子节点)
- const personaPathNodes = Array.from(mergedPathNodes).filter(id => !id.startsWith("帖子_"));
- if (personaPathNodes.length > 0) {{
- // 获取边类型统计作为显示
- const edgeTypeCount = {{}};
- connectedIntraEdges.forEach(e => {{
- const t = e.link.type.replace("镜像_", "").replace("二阶_", "");
- edgeTypeCount[t] = (edgeTypeCount[t] || 0) + 1;
- }});
- const typeStr = Object.entries(edgeTypeCount).map(([t, c]) => `${{t}}×${{c}}`).join(", ");
- syncTreeAndRelationGraph(personaPathNodes, typeStr);
- }}
- // 显示节点详情
- const panel = document.getElementById("detailPanel");
- panel.classList.add("active");
- document.getElementById("detailTitle").textContent = "📌 帖子标签";
- let html = `
- <p><span class="label">标签:</span> <strong>${{tagNodeName}}</strong></p>
- <p><span class="label">层内边数:</span> ${{connectedIntraEdges.length}}</p>
- <h4 style="margin-top:12px;color:#f39c12;font-size:12px;">🔗 层内关联</h4>
- <div class="edge-list">
- `;
- // 按边类型分组统计
- const edgeTypeCount = {{}};
- connectedIntraEdges.forEach(e => {{
- const t = e.link.type.replace("镜像_", "").replace("二阶_", "");
- edgeTypeCount[t] = (edgeTypeCount[t] || 0) + 1;
- }});
- for (const [type, count] of Object.entries(edgeTypeCount)) {{
- html += `<div class="edge-type-item"><span class="edge-type">${{type}}</span><span class="edge-count">${{count}}</span></div>`;
- }}
- html += `</div>`;
- document.getElementById("detailContent").innerHTML = html;
- }}
- treeNodes.each(function(d) {{
- const node = d3.select(this);
- const fill = d.data.dimColor || "#888";
- if (d.data.nodeType === "点") {{
- node.append("path")
- .attr("d", hexagonPath(16))
- .attr("fill", fill)
- .attr("stroke", "#fff")
- .attr("stroke-width", 2);
- }} else if (d.data.isDimension) {{
- node.append("circle")
- .attr("r", 14)
- .attr("fill", fill)
- .attr("stroke", "#fff")
- .attr("stroke-width", 2);
- }} else if (d.data.nodeType === "标签") {{
- node.append("circle")
- .attr("r", 12)
- .attr("fill", fill)
- .attr("stroke", "#fff")
- .attr("stroke-width", 2);
- }} else {{
- node.append("circle")
- .attr("r", 8)
- .attr("fill", fill)
- .attr("stroke", "#fff")
- .attr("stroke-width", 1);
- }}
- }});
- // 节点标签
- treeNodes.append("text")
- .attr("dy", d => {{
- if (d.data.isDimension) return -22;
- if (d.data.nodeType === "点") return -24;
- if (d.data.nodeType === "标签") return -20;
- return -18;
- }})
- .attr("text-anchor", "middle")
- .attr("fill", d => d.data.dimColor || "#ccc")
- .attr("font-size", "11px")
- .attr("font-weight", d => d.data.isDimension ? "bold" : "normal")
- .text(d => d.data.name || "");
- // 绘制根节点卡片
- const postRootNode = postRoot;
- const cardX = postRootNode.x - cardWidth/2;
- const cardY = postRootNode.y - cardHeight/2;
- const rootCard = postTreeGroup.append("foreignObject")
- .attr("x", cardX)
- .attr("y", cardY)
- .attr("width", cardWidth)
- .attr("height", cardHeight);
- const images = postDetail.images || [];
- const thumbnail = images.length > 0 ? images[0] : "";
- const title = postDetail.title || "未知标题";
- const likeCount = postDetail.like_count || 0;
- const collectCount = postDetail.collect_count || 0;
- const imageCount = images.length || 0;
- const thumbnailHtml = thumbnail
- ? `<div class="post-card-thumbnail-wrapper" style="width:60px;height:60px;">
- <img class="post-card-thumbnail" style="width:60px;height:60px;" src="${{thumbnail}}" alt="封面" onerror="this.style.display='none'"/>
- ${{imageCount > 1 ? `<span class="post-card-image-count">${{imageCount}}图</span>` : ''}}
- </div>`
- : `<div class="post-card-thumbnail-placeholder" style="width:60px;height:60px;font-size:20px;">📝</div>`;
- const cardHtml = `
- <div class="post-card" xmlns="http://www.w3.org/1999/xhtml" style="padding:10px;" onclick="showPostDetail(window.currentPostDetail)">
- <div class="post-card-header">
- ${{thumbnailHtml}}
- <div class="post-card-info">
- <div class="post-card-title" style="font-size:12px;-webkit-line-clamp:2;" title="${{title}}">${{title}}</div>
- <div class="post-card-stats" style="font-size:10px;">
- <span>❤️ ${{likeCount}}</span>
- <span>⭐ ${{collectCount}}</span>
- </div>
- </div>
- </div>
- </div>
- `;
- rootCard.append("xhtml:div").html(cardHtml);
- // 应用树的位置变换
- postTreeGroup.attr("transform", `translate(${{postTreeOffsetX}}, ${{postTreeOffsetY}})`);
- // 更新标签节点位置(加上偏移)- 每个ID可能有多个位置
- Object.keys(tagNodePositions).forEach(id => {{
- tagNodePositions[id].forEach(pos => {{
- pos.x += postTreeOffsetX;
- }});
- }});
- // 对帖子标签层应用防重叠(展平后处理)
- function spreadTagPositions(tagPositions, baseGap = 30, charWidth = 9) {{
- // 展平所有标签位置
- const allTags = [];
- Object.entries(tagPositions).forEach(([id, posArray]) => {{
- posArray.forEach((pos, idx) => {{
- const name = pos.data ? (pos.data.name || '') : '';
- allTags.push({{ id, idx, x: pos.x, y: pos.y, nameLen: name.length, pos }});
- }});
- }});
- // 按y分层
- const layers = {{}};
- allTags.forEach(tag => {{
- const y = tag.y;
- if (!layers[y]) layers[y] = [];
- layers[y].push(tag);
- }});
- // 对每层进行防重叠处理
- Object.values(layers).forEach(layerTags => {{
- if (layerTags.length < 2) return;
- // 按x排序
- layerTags.sort((a, b) => a.x - b.x);
- // 多轮迭代
- for (let iter = 0; iter < 5; iter++) {{
- let hasOverlap = false;
- for (let i = 1; i < layerTags.length; i++) {{
- const prev = layerTags[i - 1];
- const curr = layerTags[i];
- const prevHalfWidth = (prev.nameLen * charWidth) / 2 + 10;
- const currHalfWidth = (curr.nameLen * charWidth) / 2 + 10;
- const minGap = prevHalfWidth + currHalfWidth + baseGap;
- const gap = curr.x - prev.x;
- if (gap < minGap) {{
- hasOverlap = true;
- const shift = (minGap - gap) / 2;
- prev.x -= shift;
- curr.x += shift;
- // 更新原始位置
- prev.pos.x = prev.x;
- curr.pos.x = curr.x;
- // 同步更新节点对象的 x(用于后续更新 DOM 位置)
- if (prev.pos.node) prev.pos.node.x = prev.x - postTreeOffsetX;
- if (curr.pos.node) curr.pos.node.x = curr.x - postTreeOffsetX;
- }}
- }}
- if (!hasOverlap) break;
- }}
- }});
- }}
- spreadTagPositions(tagNodePositions, 25, 9);
- // 更新标签节点的 DOM 位置(根据 spreadTagPositions 调整后的 d.x)
- treeNodes.filter(d => d.data.nodeType === "标签")
- .attr("transform", d => `translate(${{d.x}},${{d.y}})`);
- // 更新树边的路径(因为标签节点位置可能变了)
- treeLinks.attr("d", d => {{
- const sourceY = d.source.data.isRoot ? d.source.y + cardHeight/2 : d.source.y;
- return `M${{d.source.x}},${{sourceY}}
- C${{d.source.x}},${{(sourceY + d.target.y) / 2}}
- ${{d.target.x}},${{(sourceY + d.target.y) / 2}}
- ${{d.target.x}},${{d.target.y}}`;
- }});
- // 更新分数文本位置(因为标签节点位置可能变了)
- postTreeGroup.selectAll(".tree-link-score")
- .attr("x", d => (d.source.x + d.target.x) / 2)
- .attr("y", d => (d.source.y + d.target.y) / 2);
- // ===== 下半部分:三分图(标签 ↔ 人设_1层 ↔ 人设_2层)=====
- // 复用圆形图的节点数据,但只取人设节点(去重)
- const personaLayer1Nodes = nodes.filter(n => getNodeLayer(n) === 1);
- const personaLayer2Nodes = nodes.filter(n => getNodeLayer(n) === 2);
- // 过滤出层间边
- const crossLayerLinks = links.filter(link => {{
- const srcLayer = getNodeLayer(link.source);
- const tgtLayer = getNodeLayer(link.target);
- if (srcLayer === tgtLayer) return false;
- // 1-2层之间只显示"属于"边(从上到下),过滤掉"包含"边(从下到上)
- if ((srcLayer === 1 && tgtLayer === 2) || (srcLayer === 2 && tgtLayer === 1)) {{
- if (link.type === "包含") return false;
- }}
- return true;
- }});
- console.log("层间边数:", crossLayerLinks.length, "人设1层:", personaLayer1Nodes.length, "人设2层:", personaLayer2Nodes.length);
- // 为人设节点计算X位置(根据连接的标签节点位置)
- const personaNodePositions = {{}};
- // 人设_1层:根据连接的帖子标签位置来定位
- personaLayer1Nodes.forEach(n => {{
- // 找到连接到这个人设的帖子标签
- const connectedTags = crossLayerLinks
- .filter(l => l.target.id === n.id && getNodeLayer(l.source) === 0)
- .map(l => l.source.id);
- let avgX = 0;
- let count = 0;
- connectedTags.forEach(tagId => {{
- // 在树的标签节点中查找(每个tagId可能有多个位置)
- if (tagNodePositions[tagId]) {{
- tagNodePositions[tagId].forEach(pos => {{
- avgX += pos.x;
- count++;
- }});
- }}
- }});
- if (count > 0) {{
- personaNodePositions[n.id] = {{ x: avgX / count, y: targetPersonaY, node: n }};
- }} else {{
- // 没有连接的标签,放在中间
- const allTagX = Object.values(tagNodePositions).flatMap(arr => arr.map(t => t.x));
- const midX = allTagX.length > 0 ? (Math.min(...allTagX) + Math.max(...allTagX)) / 2 : circleRightEdge + treeGap;
- personaNodePositions[n.id] = {{ x: midX, y: targetPersonaY, node: n }};
- }}
- }});
- // 人设_2层:根据连接的人设_1层位置来定位
- personaLayer2Nodes.forEach(n => {{
- const connectedPersona1 = crossLayerLinks
- .filter(l => (l.target.id === n.id && getNodeLayer(l.source) === 1) ||
- (l.source.id === n.id && getNodeLayer(l.target) === 1))
- .map(l => l.source.id === n.id ? l.target.id : l.source.id);
- let avgX = 0;
- let count = 0;
- connectedPersona1.forEach(pId => {{
- if (personaNodePositions[pId]) {{
- avgX += personaNodePositions[pId].x;
- count++;
- }}
- }});
- if (count > 0) {{
- personaNodePositions[n.id] = {{ x: avgX / count, y: targetExpandedY, node: n }};
- }} else {{
- const allP1X = Object.values(personaNodePositions).filter(p => p.y === targetPersonaY).map(p => p.x);
- const midX = allP1X.length > 0 ? (Math.min(...allP1X) + Math.max(...allP1X)) / 2 : circleRightEdge + treeGap;
- personaNodePositions[n.id] = {{ x: midX, y: targetExpandedY, node: n }};
- }}
- }});
- // 防重叠:分散同层中x坐标太近的节点(根据文字长度动态计算间距)
- function spreadOverlappingNodes(positions, baseGap = 40, charWidth = 8) {{
- // 按y分层
- const layers = {{}};
- Object.entries(positions).forEach(([id, pos]) => {{
- const y = pos.y;
- if (!layers[y]) layers[y] = [];
- // 获取节点名称长度
- const name = pos.node ? (pos.node.节点名称 || pos.node.name || '') : '';
- layers[y].push({{ id, ...pos, nameLen: name.length }});
- }});
- // 对每层进行防重叠处理
- Object.values(layers).forEach(layerNodes => {{
- if (layerNodes.length < 2) return;
- // 按x排序
- layerNodes.sort((a, b) => a.x - b.x);
- // 多轮迭代确保所有节点都不重叠
- for (let iter = 0; iter < 5; iter++) {{
- let hasOverlap = false;
- for (let i = 1; i < layerNodes.length; i++) {{
- const prev = layerNodes[i - 1];
- const curr = layerNodes[i];
- // 根据两个节点的文字长度计算最小间距
- const prevHalfWidth = (prev.nameLen * charWidth) / 2 + 10;
- const currHalfWidth = (curr.nameLen * charWidth) / 2 + 10;
- const minGap = prevHalfWidth + currHalfWidth + baseGap;
- const gap = curr.x - prev.x;
- if (gap < minGap) {{
- hasOverlap = true;
- // 需要分散:向两侧推开
- const shift = (minGap - gap) / 2;
- prev.x -= shift;
- curr.x += shift;
- // 更新原始位置
- positions[prev.id].x = prev.x;
- positions[curr.id].x = curr.x;
- }}
- }}
- if (!hasOverlap) break;
- }}
- }});
- }}
- // 对人设节点应用防重叠
- spreadOverlappingNodes(personaNodePositions, 30, 9);
- // 合并所有节点位置(标签 + 人设)
- const allGraphNodePositions = {{}};
- // 标签位置:取第一个位置用于合并(边绘制时会用所有位置)
- Object.keys(tagNodePositions).forEach(id => {{
- allGraphNodePositions[id] = tagNodePositions[id][0];
- }});
- Object.keys(personaNodePositions).forEach(id => {{
- allGraphNodePositions[id] = personaNodePositions[id];
- }});
- // 边颜色配置(包括镜像边和二阶边)
- const graphEdgeColors = {{
- "匹配_相同": "#e94560",
- "匹配_相似": "#e94560",
- "属于": "#9b59b6",
- "包含": "#3498db",
- "分类共现(跨点)": "#2ecc71",
- "分类共现(点内)": "#2ecc71",
- "标签共现": "#f39c12",
- // 镜像边(与原始边颜色相同)
- "镜像_分类共现(跨点)": "#2ecc71",
- "镜像_分类共现(点内)": "#2ecc71",
- "镜像_标签共现": "#f39c12",
- // 二阶边(与原始边颜色相同)
- "二阶_分类共现(跨点)": "#2ecc71",
- "二阶_分类共现(点内)": "#2ecc71",
- "二阶_标签共现": "#f39c12"
- }};
- // 展开边数据:如果标签有多个位置,为每个位置创建一条边
- // 边直接引用位置对象,绘制时动态获取 x, y
- const expandedLinks = [];
- crossLayerLinks.forEach(link => {{
- const srcId = link.source.id;
- const tgtId = link.target.id;
- const srcLayer = getNodeLayer(link.source);
- const tgtLayer = getNodeLayer(link.target);
- // 源是层0(帖子标签),可能有多个位置
- if (srcLayer === 0 && tagNodePositions[srcId]) {{
- tagNodePositions[srcId].forEach((srcNode, idx) => {{
- const tgtNode = personaNodePositions[tgtId];
- if (tgtNode) {{
- expandedLinks.push({{
- ...link,
- srcNode: srcNode, // 直接引用位置对象
- tgtNode: tgtNode,
- key: `${{srcId}}_${{idx}}_${{tgtId}}`
- }});
- }}
- }});
- }}
- // 目标是层0(帖子标签),可能有多个位置
- else if (tgtLayer === 0 && tagNodePositions[tgtId]) {{
- tagNodePositions[tgtId].forEach((tgtNode, idx) => {{
- const srcNode = personaNodePositions[srcId];
- if (srcNode) {{
- expandedLinks.push({{
- ...link,
- srcNode: srcNode,
- tgtNode: tgtNode,
- key: `${{srcId}}_${{tgtId}}_${{idx}}`
- }});
- }}
- }});
- }}
- // 两端都不是层0,正常处理
- else {{
- const srcNode = personaNodePositions[srcId];
- const tgtNode = personaNodePositions[tgtId];
- if (srcNode && tgtNode) {{
- expandedLinks.push({{
- ...link,
- srcNode: srcNode,
- tgtNode: tgtNode,
- key: `${{srcId}}_${{tgtId}}`
- }});
- }}
- }}
- }});
- console.log("展开后边数:", expandedLinks.length);
- // 绘制层间边(标签→人设、人设→人设扩展)
- // 去重:同一对节点之间相同类型的边只保留一条
- const seenEdges = new Set();
- const dedupedLinks = expandedLinks.filter(link => {{
- const srcId = link.source.id || link.source;
- const tgtId = link.target.id || link.target;
- const edgeKey = [srcId, tgtId].sort().join("|") + "|" + link.type;
- if (seenEdges.has(edgeKey)) return false;
- seenEdges.add(edgeKey);
- return true;
- }});
- // 统计每对节点之间的边数,为多边分配不同曲线偏移
- const edgePairCount = {{}};
- const edgePairIndex = {{}};
- dedupedLinks.forEach(link => {{
- const srcId = link.source.id || link.source;
- const tgtId = link.target.id || link.target;
- const pairKey = [srcId, tgtId].sort().join("|");
- edgePairCount[pairKey] = (edgePairCount[pairKey] || 0) + 1;
- }});
- dedupedLinks.forEach(link => {{
- const srcId = link.source.id || link.source;
- const tgtId = link.target.id || link.target;
- const pairKey = [srcId, tgtId].sort().join("|");
- if (!edgePairIndex[pairKey]) edgePairIndex[pairKey] = 0;
- link._pairCount = edgePairCount[pairKey];
- link._pairIndex = edgePairIndex[pairKey]++;
- }});
- const graphLinksGroup = g.append("g").attr("class", "graph-links");
- const graphLinks = graphLinksGroup.selectAll(".graph-link")
- .data(dedupedLinks)
- .enter()
- .append("g")
- .attr("class", "graph-link-group");
- // 跨层边路径生成函数
- const graphLinkPath = d => {{
- const src = d.srcNode;
- const tgt = d.tgtNode;
- if (!src || !tgt) return "";
- // 如果只有一条边,用默认曲线
- if (d._pairCount <= 1) {{
- return `M${{src.x}},${{src.y}} C${{src.x}},${{(src.y + tgt.y) / 2}} ${{tgt.x}},${{(src.y + tgt.y) / 2}} ${{tgt.x}},${{tgt.y}}`;
- }}
- // 多条边时,根据索引计算水平偏移
- const offsetStep = 25;
- const totalOffset = (d._pairCount - 1) * offsetStep;
- const offset = d._pairIndex * offsetStep - totalOffset / 2;
- const midY = (src.y + tgt.y) / 2;
- const midX = (src.x + tgt.x) / 2 + offset;
- return `M${{src.x}},${{src.y}} Q${{midX}},${{midY}} ${{tgt.x}},${{tgt.y}}`;
- }};
- // 可见的跨层边(不可交互)
- graphLinks.append("path")
- .attr("class", "graph-link")
- .attr("d", graphLinkPath)
- .attr("fill", "none")
- .attr("stroke", d => graphEdgeColors[d.type] || "#9b59b6")
- .attr("stroke-width", 1.5)
- .attr("stroke-opacity", 0.6)
- .attr("stroke-dasharray", d => d.type === "匹配_相似" ? "4,2" : "none");
- // 跨层边设为不可交互
- graphLinks.style("pointer-events", "none");
- // 在有分数的边上显示分数(统一逻辑)
- graphLinks.filter(d => d.score !== null && d.score !== undefined)
- .append("text")
- .attr("x", d => (d.srcNode.x + d.tgtNode.x) / 2)
- .attr("y", d => (d.srcNode.y + d.tgtNode.y) / 2)
- .attr("dy", "0.35em")
- .attr("text-anchor", "middle")
- .attr("fill", "#fff")
- .attr("font-size", "8px")
- .attr("font-weight", "bold")
- .style("text-shadow", "0 0 3px #e94560, 0 0 3px #e94560")
- .text(d => d.score.toFixed(2));
- // 绘制人设节点(去重后的)
- const allPersonaNodes = [...personaLayer1Nodes, ...personaLayer2Nodes];
- const graphNodesGroup = g.append("g").attr("class", "graph-nodes");
- const graphNodes = graphNodesGroup.selectAll(".graph-node")
- .data(allPersonaNodes.filter(n => personaNodePositions[n.id]))
- .enter()
- .append("g")
- .attr("class", "graph-node")
- .attr("transform", d => {{
- const pos = personaNodePositions[d.id];
- return `translate(${{pos.x}},${{pos.y}})`;
- }})
- .style("cursor", "pointer");
- // 人设节点形状
- graphNodes.each(function(d) {{
- const node = d3.select(this);
- const fill = levelColors[d.节点层级] || "#888";
- const size = 10;
- if (d.节点类型 === "分类") {{
- node.append("rect")
- .attr("width", size * 2)
- .attr("height", size * 2)
- .attr("x", -size)
- .attr("y", -size)
- .attr("fill", fill)
- .attr("stroke", "#fff")
- .attr("stroke-width", 2)
- .attr("rx", 3);
- }} else {{
- node.append("circle")
- .attr("r", size)
- .attr("fill", fill)
- .attr("stroke", "#fff")
- .attr("stroke-width", 2);
- }}
- }});
- // 人设节点标签
- graphNodes.append("text")
- .attr("dy", -18)
- .attr("text-anchor", "middle")
- .attr("fill", d => levelColors[d.节点层级] || "#ccc")
- .attr("font-size", "11px")
- .text(d => d.节点名称 || d.name || "");
- // 点击联动 - 复用共享的节点点击处理函数
- graphNodes.on("click", function(event, d) {{
- event.stopPropagation();
- handleNodeClick(d.id || d.节点ID, d.节点名称 || d.name);
- }});
- // 存储引用
- window.graphNodesRef = graphNodes;
- window.allGraphNodePositions = allGraphNodePositions;
- // ===== 层内边:同层节点之间的关系边 =====
- // 筛选层内边(包括原始边、镜像边、二阶边)
- const intraLayerEdgeTypes = [
- "标签共现", "分类共现(跨点)", "分类共现(点内)",
- "镜像_标签共现", "镜像_分类共现(跨点)", "镜像_分类共现(点内)",
- "二阶_标签共现", "二阶_分类共现(跨点)", "二阶_分类共现(点内)"
- ];
- const intraLayerLinks = links.filter(link => {{
- const srcLayer = getNodeLayer(link.source);
- const tgtLayer = getNodeLayer(link.target);
- // 同层且是关系类边
- return srcLayer === tgtLayer && intraLayerEdgeTypes.includes(link.type);
- }});
- console.log("层内边数:", intraLayerLinks.length);
- // 展开层内边数据(处理多位置标签)
- const expandedIntraLinks = [];
- intraLayerLinks.forEach(link => {{
- const srcId = link.source.id;
- const tgtId = link.target.id;
- const srcLayer = getNodeLayer(link.source);
- // 帖子标签层(层0)- 可能有多个位置
- if (srcLayer === 0) {{
- const srcPositions = tagNodePositions[srcId] || [];
- const tgtPositions = tagNodePositions[tgtId] || [];
- // 为每对位置创建一条边
- srcPositions.forEach((srcPos, si) => {{
- tgtPositions.forEach((tgtPos, ti) => {{
- expandedIntraLinks.push({{
- ...link,
- srcNode: srcPos,
- tgtNode: tgtPos,
- key: `intra_${{srcId}}_${{si}}_${{tgtId}}_${{ti}}`
- }});
- }});
- }});
- }}
- // 人设层(层1、2)
- else {{
- const srcNode = personaNodePositions[srcId];
- const tgtNode = personaNodePositions[tgtId];
- if (srcNode && tgtNode) {{
- expandedIntraLinks.push({{
- ...link,
- srcNode: srcNode,
- tgtNode: tgtNode,
- key: `intra_${{srcId}}_${{tgtId}}`
- }});
- }}
- }}
- }});
- // 去重层内边
- const seenIntraEdges = new Set();
- const dedupedIntraLinks = expandedIntraLinks.filter(link => {{
- const srcId = link.source.id || link.source;
- const tgtId = link.target.id || link.target;
- const edgeKey = [srcId, tgtId].sort().join("|") + "|" + link.type;
- if (seenIntraEdges.has(edgeKey)) return false;
- seenIntraEdges.add(edgeKey);
- return true;
- }});
- console.log("去重后层内边数:", dedupedIntraLinks.length);
- // 为层内边计算偏移(避免重叠)
- // 按源节点分组,给每条边分配不同的弧度
- const intraEdgesBySource = {{}};
- dedupedIntraLinks.forEach((link, idx) => {{
- const srcId = link.source.id || link.source;
- if (!intraEdgesBySource[srcId]) intraEdgesBySource[srcId] = [];
- intraEdgesBySource[srcId].push({{ link, idx }});
- }});
- // 为每条边分配偏移索引
- dedupedIntraLinks.forEach((link, idx) => {{
- const srcId = link.source.id || link.source;
- const group = intraEdgesBySource[srcId];
- const indexInGroup = group.findIndex(item => item.idx === idx);
- link._arcIndex = indexInGroup;
- link._arcTotal = group.length;
- }});
- // 绘制层内边(默认隐藏)
- const intraLinksGroup = g.append("g").attr("class", "intra-layer-links");
- const intraLinks = intraLinksGroup.selectAll(".intra-link-group")
- .data(dedupedIntraLinks)
- .enter()
- .append("g")
- .attr("class", "intra-link-group")
- .style("display", "none"); // 默认隐藏
- // 层内边路径生成函数(弧线统一向下,弧度递增避免重叠)
- const intraLinkPath = d => {{
- const src = d.srcNode;
- const tgt = d.tgtNode;
- if (!src || !tgt) return "";
- const dx = tgt.x - src.x;
- const dy = tgt.y - src.y;
- const dist = Math.sqrt(dx * dx + dy * dy);
- // 根据边的索引计算弧度(统一向下)
- const baseArc = Math.min(dist * 0.2, 30);
- const arcStep = 20; // 每条边的弧度增量
- const arcIndex = d._arcIndex || 0;
- const arcHeight = baseArc + arcIndex * arcStep;
- const midX = (src.x + tgt.x) / 2;
- const midY = (src.y + tgt.y) / 2;
- // 统一向下弯曲(Y增大)
- return `M${{src.x}},${{src.y}} Q${{midX}},${{midY + arcHeight}} ${{tgt.x}},${{tgt.y}}`;
- }};
- // 层内边虚线配置(与左边一致)
- const intraEdgeDash = {{
- "匹配_相似": "5,5",
- "包含": "2,2",
- "镜像_包含": "2,2"
- }};
- // 层内边可见路径(样式与左边圆形图一致)
- intraLinks.append("path")
- .attr("class", d => "intra-link " + getEdgeClass(d.type))
- .attr("d", intraLinkPath)
- .attr("fill", "none")
- .attr("stroke", d => graphEdgeColors[d.type] || "#f39c12")
- .attr("stroke-width", 2)
- .attr("stroke-opacity", 0.8)
- .attr("stroke-dasharray", d => intraEdgeDash[d.type] || "none");
- // 层内边热区(可点击,效果与左边圆一致)
- intraLinks.append("path")
- .attr("class", "intra-link-hitarea")
- .attr("d", intraLinkPath)
- .attr("fill", "none")
- .attr("stroke", "transparent")
- .attr("stroke-width", 15)
- .style("cursor", "pointer")
- .on("mouseover", function(event, d) {{
- d3.select(this.parentNode).select(".intra-link")
- .attr("stroke-width", 3)
- .attr("stroke-opacity", 1);
- }})
- .on("mouseout", function(event, d) {{
- d3.select(this.parentNode).select(".intra-link")
- .attr("stroke-width", 2)
- .attr("stroke-opacity", 0.8);
- }})
- .on("click", function(event, d) {{
- event.stopPropagation();
- // 在左边圆中找到对应的边
- const srcId = d.source ? (d.source.id || d.source) : null;
- const tgtId = d.target ? (d.target.id || d.target) : null;
- let foundLink = null;
- let foundIndex = -1;
- links.forEach((link, idx) => {{
- const lSrcId = typeof link.source === "object" ? link.source.id : link.source;
- const lTgtId = typeof link.target === "object" ? link.target.id : link.target;
- if ((lSrcId === srcId && lTgtId === tgtId) || (lSrcId === tgtId && lTgtId === srcId)) {{
- if (link.type === d.type) {{
- foundLink = link;
- foundIndex = idx;
- }}
- }}
- }});
- if (foundLink) {{
- // 1. 高亮左边圆的边
- highlightEdge(foundLink, foundIndex);
- showEdgeInfo(foundLink);
- // 2. 同步人设树高亮和关系图展示
- const edgeDetail = foundLink.边详情 || {{}};
- const isMirrorEdge = foundLink.type.startsWith("镜像_") || foundLink.type.startsWith("二阶_");
- let personaPathNodes = [];
- let edgeType;
- if (isMirrorEdge && edgeDetail.路径节点) {{
- personaPathNodes = edgeDetail.路径节点.filter(id => !id.startsWith("帖子_"));
- edgeType = edgeDetail.原始边类型 || foundLink.type.replace("镜像_", "").replace("二阶_", "");
- }} else {{
- const sourceNode = typeof foundLink.source === "object" ? foundLink.source : nodes.find(n => n.id === foundLink.source);
- const targetNode = typeof foundLink.target === "object" ? foundLink.target : nodes.find(n => n.id === foundLink.target);
- const sId = sourceNode ? sourceNode.id : foundLink.source;
- const tId = targetNode ? targetNode.id : foundLink.target;
- if (!sId.startsWith("帖子_")) personaPathNodes.push(sId);
- if (!tId.startsWith("帖子_")) personaPathNodes.push(tId);
- edgeType = foundLink.type;
- }}
- syncTreeAndRelationGraph(personaPathNodes, edgeType);
- }} else {{
- // 没找到对应边,只显示详情
- showEdgeInfo(d);
- }}
- }});
- // 层内边分数标签(直接显示在弧线上)
- // 计算二次贝塞尔曲线在 t=0.5 时的实际位置(曲线中点)
- const getIntraArcMid = d => {{
- const dist = Math.sqrt(
- Math.pow(d.tgtNode.x - d.srcNode.x, 2) +
- Math.pow(d.tgtNode.y - d.srcNode.y, 2)
- );
- const baseArc = Math.min(dist * 0.2, 30);
- const arcStep = 20;
- const arcIndex = d._arcIndex || 0;
- const arcHeight = baseArc + arcIndex * arcStep;
- // 二次贝塞尔曲线 t=0.5 时的点: (1-t)²*P0 + 2*(1-t)*t*P1 + t²*P2
- // = 0.25*src + 0.5*ctrl + 0.25*tgt
- const midY = (d.srcNode.y + d.tgtNode.y) / 2;
- const ctrlY = midY + arcHeight; // 向下弯曲
- return {{
- x: (d.srcNode.x + d.tgtNode.x) / 2,
- y: 0.25 * d.srcNode.y + 0.5 * ctrlY + 0.25 * d.tgtNode.y
- }};
- }};
- // 分数背景(让文字在边上更清晰)
- intraLinks.filter(d => d.score !== null && d.score !== undefined)
- .append("rect")
- .attr("class", "intra-link-score-bg")
- .attr("x", d => getIntraArcMid(d).x - 14)
- .attr("y", d => getIntraArcMid(d).y - 7)
- .attr("width", 28)
- .attr("height", 14)
- .attr("rx", 3)
- .attr("fill", "rgba(0,0,0,0.7)");
- // 分数文字
- intraLinks.filter(d => d.score !== null && d.score !== undefined)
- .append("text")
- .attr("class", "intra-link-score")
- .attr("x", d => getIntraArcMid(d).x)
- .attr("y", d => getIntraArcMid(d).y)
- .attr("dy", "0.35em")
- .attr("text-anchor", "middle")
- .attr("fill", "#fff")
- .attr("font-size", "9px")
- .attr("font-weight", "bold")
- .text(d => d.score.toFixed(2));
- // 存储层内边引用供后续使用
- window.intraLayerLinksRef = intraLinks;
- window.intraLayerLinksData = dedupedIntraLinks;
- postTreeActualHeight = targetExpandedY - (targetTagY - halfGap * 3) + 100;
- }} // end if (postTree && postTree.root)
- // 计算高度
- const tripartiteHeight = postTreeActualHeight;
- // 圆的Y位置不再受帖子树高度影响,使用固定偏移
- const circleYOffset = 40;
- // 更新圆心Y坐标(三层)
- layerCenterY[0] += circleYOffset;
- layerCenterY[1] += circleYOffset;
- layerCenterY[2] += circleYOffset;
- // 更新SVG高度(取圆和三分图的最大高度)
- const minHeight = Math.max(
- layerCenterY[2] + layerRadius[2] + 50,
- tripartiteHeight + 150
- );
- svg.attr("height", Math.max(height, minHeight));
- // 绘制层背景(圆形,使用动态大小)
- const layerBg = g.append("g").attr("class", "layer-backgrounds");
- // 层配置:名称、颜色(三层圆)
- const layerConfig = [
- {{ name: "帖子标签", layer: 0, color: "rgba(52, 152, 219, 0.08)", stroke: "rgba(52, 152, 219, 0.3)" }},
- {{ name: "人设匹配_1层", layer: 1, color: "rgba(155, 89, 182, 0.08)", stroke: "rgba(155, 89, 182, 0.3)" }},
- {{ name: "人设匹配_2层", layer: 2, 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", // 紫色 - 标签属于分类
- "包含": "#3498db", // 蓝色 - 分类包含标签(向下)
- "分类共现(跨点)": "#2ecc71", // 绿色 - 分类共现
- "分类共现(点内)": "#2ecc71", // 绿色 - 分类共现
- "标签共现": "#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();
- resetRightTreeHighlight();
- 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", "none"); // 匹配边默认隐藏
- }} else if (isCrossLayerEdge(d) && !showCrossLayerEdges) {{
- d3.select(this).style("display", "none");
- }}
- }});
- // 为有分数的边添加分数标签(统一逻辑)
- const edgeLabels = linkG.filter(d => d.score !== null && d.score !== undefined)
- .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 => d.score.toFixed(2));
- // 边的点击事件
- 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);
- // 注:highlightEdge 内部已调用 highlightRightTree 联动右边树
- }})
- .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.节点名称);
- }} else {{
- // 帖子标签节点:直接联动右边树高亮
- const highlightedNodeIds = new Set([d.id]);
- const highlightedEdgeKeys = new Set();
- // 找相连的边和节点
- g.selectAll(".link-group").each(function(link) {{
- const srcId = typeof link.source === "object" ? link.source.id : link.source;
- const tgtId = typeof link.target === "object" ? link.target.id : link.target;
- if (srcId === d.id || tgtId === d.id) {{
- highlightedNodeIds.add(srcId);
- highlightedNodeIds.add(tgtId);
- highlightedEdgeKeys.add(`${{srcId}}|${{tgtId}}`);
- highlightedEdgeKeys.add(`${{tgtId}}|${{srcId}}`);
- }}
- }});
- highlightRightTree(highlightedNodeIds, highlightedEdgeKeys);
- }}
- }});
- // 更新位置
- 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 collectEdgeHighlightData(clickedLink, clickedIndex) {{
- const nodeIds = new Set();
- const linkIndices = new Set([clickedIndex]);
- const pathNodes = new Set();
- const sourceId = typeof clickedLink.source === "object" ? clickedLink.source.id : clickedLink.source;
- const targetId = typeof clickedLink.target === "object" ? clickedLink.target.id : clickedLink.target;
- nodeIds.add(sourceId);
- nodeIds.add(targetId);
- pathNodes.add(sourceId);
- pathNodes.add(targetId);
- // 如果是镜像边或二阶边,使用预计算的路径节点
- if ((clickedLink.type.startsWith("镜像_") || clickedLink.type.startsWith("二阶_")) && clickedLink.边详情) {{
- const detail = clickedLink.边详情;
- (detail.路径节点 || []).forEach(n => pathNodes.add(n));
- }}
- // 如果是人设边(两端都不是帖子节点),找对应的镜像边
- else if (!sourceId.startsWith("帖子_") && !targetId.startsWith("帖子_")) {{
- 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) {{
- linkIndices.add(i);
- (detail.路径节点 || []).forEach(n => pathNodes.add(n));
- }}
- }}
- }});
- }}
- // 高亮路径上的所有节点
- pathNodes.forEach(n => nodeIds.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)) {{
- linkIndices.add(i);
- }}
- }});
- return {{ nodeIds, linkIndices, pathNodes }};
- }}
- // 应用高亮数据(统一处理高亮结果)
- function applyEdgeHighlight(highlightNodeIds, highlightLinkIndices) {{
- // 高亮相关的节点和边
- highlightElements(highlightNodeIds, highlightLinkIndices);
- // 临时显示关联的跨层边(即使全局开关是关闭的)
- linkG.each(function(d, i) {{
- if (highlightLinkIndices.has(i)) {{
- d3.select(this).style("display", "block");
- }}
- }});
- // 联动右边树:收集高亮边的key
- const highlightEdgeKeys = new Set();
- highlightLinkIndices.forEach(i => {{
- const link = links[i];
- const srcId = typeof link.source === "object" ? link.source.id : link.source;
- const tgtId = typeof link.target === "object" ? link.target.id : link.target;
- highlightEdgeKeys.add(`${{srcId}}|${{tgtId}}`);
- highlightEdgeKeys.add(`${{tgtId}}|${{srcId}}`);
- }});
- highlightRightTree(highlightNodeIds, highlightEdgeKeys);
- }}
- // 点击边时的高亮逻辑
- function highlightEdge(clickedLink, clickedIndex) {{
- const {{ nodeIds, linkIndices }} = collectEdgeHighlightData(clickedLink, clickedIndex);
- applyEdgeHighlight(nodeIds, linkIndices);
- }}
- // 点击空白处清除高亮(合并所有空白点击逻辑)
- 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();
- // 恢复右边帖子树
- resetRightTreeHighlight();
- // 关闭详情面板
- 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);
- }}
- // 高亮左边圆中对应节点及边,同时收集用于右边树联动的数据
- // 收集高亮的节点ID和边key(左边圆高亮什么,右边树就高亮什么)
- const highlightedNodeIds = new Set([clickedNodeId]);
- const highlightedEdgeKeys = new Set();
- if (g) {{
- // 找所有与该节点相连的边,收集相关节点和边
- 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) {{
- highlightedNodeIds.add(srcId);
- highlightedNodeIds.add(tgtId);
- highlightedEdgeKeys.add(`${{srcId}}|${{tgtId}}`);
- highlightedEdgeKeys.add(`${{tgtId}}|${{srcId}}`);
- }}
- }});
- // 检查是否有相关节点在图中
- const hasRelatedNodes = g.selectAll(".node").filter(n => highlightedNodeIds.has(n.id)).size() > 0;
- if (hasRelatedNodes) {{
- // 高亮相关节点,变灰其他
- g.selectAll(".node")
- .classed("dimmed", n => !highlightedNodeIds.has(n.id))
- .classed("highlighted", n => highlightedNodeIds.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);
- }}
- }}
- // 联动高亮右边帖子树(直接用左边圆高亮的节点和边)
- highlightRightTree(highlightedNodeIds, highlightedEdgeKeys);
- }}
- // 同步人设树高亮和关系图展示(职责单一:不处理力导向图)
- 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);
- }}
- }}
- // 重置所有层级到默认配置(所有层级边类型默认不选)
- function resetSelection() {{
- event.stopPropagation();
- // 所有层级边类型默认不选
- [1, 2, 3].forEach(level => {{
- document.querySelectorAll(`.cascade-edge-item input[data-level="${{level}}"]`).forEach(cb => {{
- cb.checked = false;
- }});
- 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,
- score: getEdgeScore(e)
- }});
- }});
- }});
- // 根据节点数量动态计算实际使用的半径
- 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", // 紫色 - 层级关系
- "包含": "#3498db", // 蓝色 - 分类包含标签(向下)
- "分类共现(跨点)": "#2ecc71", // 绿色 - 分类共现
- "分类共现(点内)": "#2ecc71", // 绿色 - 分类共现
- "标签共现": "#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 edgeScoreText = egoGroup.selectAll(".ego-edge-score")
- .data(links.filter(d => d.score !== null && d.score !== undefined))
- .join("text")
- .attr("class", "ego-edge-score")
- .attr("text-anchor", "middle")
- .attr("fill", "#fff")
- .attr("font-size", "8px")
- .attr("font-weight", "bold")
- .style("text-shadow", "0 0 3px #333, 0 0 3px #333")
- .text(d => d.score.toFixed(2));
- // 绘制节点(分类用方形,标签用圆形)
- 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}})`);
- // 更新分数位置(边的中点)
- edgeScoreText
- .attr("x", d => (d.source.x + d.target.x) / 2)
- .attr("y", d => (d.source.y + d.target.y) / 2);
- }});
- }}
- 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";
- }});
- // 隐藏不在路径上的边的分数
- egoGroup.selectAll(".ego-edge-score")
- .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";
- }});
- // 联动:高亮右边树上对应的节点和边
- highlightRightTree(pathNodes, pathEdgeKeys);
- }}
- // 恢复关系图的高亮状态
- function resetEgoGraphHighlight() {{
- const egoGroup = d3.select(".ego-graph-content");
- if (egoGroup.empty()) return;
- // 恢复边的可见性
- egoGroup.selectAll(".ego-edge")
- .style("visibility", "visible");
- // 恢复边分数的可见性
- egoGroup.selectAll(".ego-edge-score")
- .style("visibility", "visible");
- // 恢复节点的可见性
- egoGroup.selectAll(".ego-node")
- .style("visibility", "visible");
- // 联动:恢复右边树
- resetRightTreeHighlight();
- }}
- // 高亮右边树上对应的节点和边
- function highlightRightTree(pathNodes, pathEdgeKeys) {{
- const postTreeGroup = d3.select(".post-tree");
- // 高亮帖子树节点
- if (!postTreeGroup.empty()) {{
- postTreeGroup.selectAll(".tree-node")
- .style("opacity", function(d) {{
- const nodeId = d.data.id || d.data.节点ID;
- return pathNodes.has(nodeId) ? 1 : 0.2;
- }});
- // 高亮帖子树边(包含边和分数的组)
- postTreeGroup.selectAll(".tree-link-group")
- .style("opacity", function(d) {{
- const srcId = d.source.data.id || d.source.data.节点ID;
- const tgtId = d.target.data.id || d.target.data.节点ID;
- // 如果两端节点都在路径中,边高亮
- return (pathNodes.has(srcId) && pathNodes.has(tgtId)) ? 1 : 0.2;
- }});
- }}
- // 高亮人设节点(右边下方的图节点,在g下面不是postTreeGroup下)
- d3.selectAll(".graph-node")
- .style("opacity", function(d) {{
- return pathNodes.has(d.id) ? 1 : 0.2;
- }});
- // 高亮跨层边(graph-link-group 包含 graph-link)
- d3.selectAll(".graph-link-group")
- .style("opacity", function(d) {{
- const srcId = d.source ? (d.source.id || d.source) : null;
- const tgtId = d.target ? (d.target.id || d.target) : null;
- if (!srcId || !tgtId) return 0.2;
- const key1 = `${{srcId}}|${{tgtId}}`;
- const key2 = `${{tgtId}}|${{srcId}}`;
- return (pathEdgeKeys.has(key1) || pathEdgeKeys.has(key2)) ? 1 : 0.2;
- }});
- // 显示并高亮层内边(只显示左边圆形图中存在的边)
- d3.selectAll(".intra-link-group").each(function(d) {{
- const srcId = d.source ? (d.source.id || d.source) : null;
- const tgtId = d.target ? (d.target.id || d.target) : null;
- if (!srcId || !tgtId) {{
- d3.select(this).style("display", "none");
- return;
- }}
- // 只显示在左边圆形图中高亮的边(来自 pathEdgeKeys)
- const key1 = `${{srcId}}|${{tgtId}}`;
- const key2 = `${{tgtId}}|${{srcId}}`;
- const isInLeftGraph = pathEdgeKeys.has(key1) || pathEdgeKeys.has(key2);
- d3.select(this)
- .style("display", isInLeftGraph ? "block" : "none")
- .style("opacity", isInLeftGraph ? 1 : 0.2);
- }});
- }}
- // 恢复右边树的高亮状态
- function resetRightTreeHighlight() {{
- const postTreeGroup = d3.select(".post-tree");
- // 恢复帖子树节点和边(包含边和分数的组)
- if (!postTreeGroup.empty()) {{
- postTreeGroup.selectAll(".tree-node").style("opacity", 1);
- postTreeGroup.selectAll(".tree-link-group").style("opacity", 1);
- }}
- // 恢复人设节点(在g下面)
- d3.selectAll(".graph-node").style("opacity", 1);
- // 恢复跨层边
- d3.selectAll(".graph-link-group").style("opacity", 1);
- // 隐藏层内边(恢复默认隐藏状态)
- d3.selectAll(".intra-link-group")
- .style("display", "none")
- .style("opacity", 1);
- }}
- // 渲染路径上的所有节点和边(点击镜像边/二阶边时调用)
- 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",
- "包含": "#3498db",
- "分类共现(跨点)": "#2ecc71",
- "分类共现(点内)": "#2ecc71",
- "标签共现": "#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",
- "包含": "#3498db",
- "分类共现(跨点)": "#2ecc71",
- "分类共现(点内)": "#2ecc71",
- "标签共现": "#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: 输出文件路径
- """
- # 生成帖子选项HTML
- tabs_html = ""
- for i, data in enumerate(all_graph_data):
- post_title = data.get("postTitle", "")
- # 使用帖子标题,如果太长则截断
- if post_title:
- option_name = post_title[:30] + "..." if len(post_title) > 30 else post_title
- else:
- option_name = f"帖子 {i+1}"
- selected = "selected" if i == 0 else ""
- tabs_html += f'<option value="{i}" {selected}>{i+1}. {option_name}</option>\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()
- # 读取帖子树数据
- post_trees_file = match_graph_dir / "post_trees.json"
- post_trees_data = {} # postId -> postTree
- if post_trees_file.exists():
- print(f"读取帖子树数据: {post_trees_file.name}")
- with open(post_trees_file, "r", encoding="utf-8") as f:
- trees_data = json.load(f)
- for tree in trees_data.get("postTrees", []):
- post_trees_data[tree["postId"]] = tree
- print(f" 帖子树数量: {len(post_trees_data)}")
- else:
- print(f"警告: 帖子树数据文件不存在: {post_trees_file}")
- print(" 请先运行 build_post_tree.py 生成帖子树数据")
- print()
- # 读取所有匹配图谱文件
- graph_files = sorted(match_graph_dir.glob("*_match_graph.json"))
- print(f"找到 {len(graph_files)} 个匹配图谱文件")
- # results目录(存放完整帖子详情)
- results_dir = config.intermediate_dir.parent / "results"
- 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)
- post_id = match_graph_data["说明"]["帖子ID"]
- # 尝试读取完整帖子详情
- post_detail = {
- "title": match_graph_data["说明"].get("帖子标题", ""),
- "post_id": post_id
- }
- how_file = results_dir / f"{post_id}_how.json"
- if how_file.exists():
- with open(how_file, "r", encoding="utf-8") as f:
- how_data = json.load(f)
- if "帖子详情" in how_data:
- post_detail = how_data["帖子详情"]
- post_detail["post_id"] = post_id
- # 获取预构建的帖子树数据
- post_tree = post_trees_data.get(post_id, {})
- # 提取需要的数据
- graph_data = {
- "postId": post_id,
- "postTitle": match_graph_data["说明"].get("帖子标题", ""),
- "stats": match_graph_data["说明"]["统计"],
- "nodes": match_graph_data["节点列表"],
- "edges": match_graph_data["边列表"],
- "personaEdgeToMirrorEdges": match_graph_data.get("人设边到镜像边映射", {}),
- # 预构建的帖子树数据
- "postTree": post_tree,
- "postDetail": post_tree.get("postDetail", post_detail)
- }
- 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()
|