script.js 231 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782
  1. /**
  2. * TrendRadar 配置文件编辑器核心逻辑
  3. * 特点:确保原始 YAML 的注释和格式 100% 保留
  4. */
  5. // ==========================================
  6. // 0. 注释高亮功能
  7. // ==========================================
  8. /**
  9. * 对文本应用高亮,# 后的内容显示为灰色
  10. */
  11. function applyHighlight(text) {
  12. const escape = s => s.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
  13. return text.split('\n').map(line => {
  14. const idx = line.indexOf('#');
  15. if (idx === -1) return escape(line);
  16. return escape(line.slice(0, idx)) + '<span class="syntax-comment">' + escape(line.slice(idx)) + '</span>';
  17. }).join('\n');
  18. }
  19. /**
  20. * 更新高亮层
  21. */
  22. function updateBackdrop(textareaId, backdropId) {
  23. const ta = document.getElementById(textareaId);
  24. const bd = document.getElementById(backdropId);
  25. if (ta && bd) bd.innerHTML = applyHighlight(ta.value) + '\n';
  26. }
  27. /**
  28. * 同步滚动
  29. */
  30. function syncScroll(textareaId, backdropId) {
  31. const ta = document.getElementById(textareaId);
  32. const bd = document.getElementById(backdropId);
  33. if (ta && bd) {
  34. bd.scrollTop = ta.scrollTop;
  35. bd.scrollLeft = ta.scrollLeft;
  36. }
  37. }
  38. // ==========================================
  39. // 12. 二维码放大弹窗逻辑
  40. // ==========================================
  41. const QR_MODAL_DATA = {
  42. weixin: {
  43. icon: '<i class="fa-brands fa-weixin text-green-600"></i>',
  44. iconBg: 'bg-green-100',
  45. title: '不迷路',
  46. subtitle: '第一时间获取更新通知',
  47. img: './assets/weixin.webp',
  48. alt: '微信公众号',
  49. hint: '微信扫码关注公众号'
  50. },
  51. donate: {
  52. icon: '<i class="fa-solid fa-hand-holding-heart text-emerald-600"></i>',
  53. iconBg: 'bg-emerald-100',
  54. title: '随心赞赏',
  55. subtitle: '金额随意,1 元也是鼓励 (´▽`ʃ♡ƪ)',
  56. img: 'https://cdn-1258574687.cos.ap-shanghai.myqcloud.com/img/%2F2026%2F01%2F18ecce7c224ce0ea4c59394c29e408f8-e0d1db45.webp',
  57. alt: '微信支付',
  58. hint: '微信扫码 · 丰俭由人'
  59. }
  60. };
  61. function openQrModal(type) {
  62. const data = QR_MODAL_DATA[type];
  63. if (!data) return;
  64. const modal = document.getElementById('qr-modal');
  65. document.getElementById('qr-modal-icon').className = 'w-10 h-10 rounded-xl flex items-center justify-center text-lg ' + data.iconBg;
  66. document.getElementById('qr-modal-icon').innerHTML = data.icon;
  67. document.getElementById('qr-modal-title').textContent = data.title;
  68. document.getElementById('qr-modal-subtitle').textContent = data.subtitle;
  69. document.getElementById('qr-modal-img').src = data.img;
  70. document.getElementById('qr-modal-img').alt = data.alt;
  71. document.getElementById('qr-modal-hint').textContent = data.hint;
  72. modal.classList.remove('hidden');
  73. }
  74. function closeQrModal() {
  75. const modal = document.getElementById('qr-modal');
  76. if (modal) modal.classList.add('hidden');
  77. }
  78. window.openQrModal = openQrModal;
  79. window.closeQrModal = closeQrModal;
  80. const MODULE_DEFS = [
  81. { id: 1, name: "1. 基础设置", key: "app", editable: false },
  82. { id: 2, name: "2. 数据源 - 热榜平台", key: "platforms", editable: true },
  83. { id: 3, name: "3. 数据源 - RSS 订阅", key: "rss", editable: true },
  84. { id: 4, name: "4. 报告模式", key: "report", editable: true },
  85. { id: "4.5", name: "4.5 筛选策略", key: "filter", editable: true },
  86. { id: "4.6", name: "4.6 AI 智能筛选", key: "ai_filter", editable: true },
  87. { id: 5, name: "5. 推送内容控制", key: "display", editable: true },
  88. { id: 6, name: "6. 推送通知", key: "notification", editable: true, partial: true },
  89. { id: 7, name: "7. 存储配置", key: "storage", editable: false },
  90. { id: 8, name: "8. AI 模型配置", key: "ai", editable: true },
  91. { id: 9, name: "9. AI 分析功能", key: "ai_analysis", editable: true },
  92. { id: 10, name: "10. AI 翻译功能", key: "ai_translation", editable: true },
  93. { id: 11, name: "11. 高级设置", key: "advanced", editable: false }
  94. ];
  95. // 初始默认内容 (用于空状态) - 只显示提示文本
  96. const INITIAL_YAML = `# 在此粘贴你的 config.yaml...
  97. # 或拖拽文件到编辑器区域
  98. # 或点击右上角"加载官网最新配置"`;
  99. // LocalStorage 键名
  100. const STORAGE_KEY_CONFIG = 'trendradar_config_yaml';
  101. const STORAGE_KEY_FREQUENCY = 'trendradar_frequency_txt';
  102. const STORAGE_KEY_TIMELINE = 'trendradar_timeline_yaml';
  103. const STORAGE_KEY_CONFIG_TIME = 'trendradar_config_time';
  104. const STORAGE_KEY_FREQUENCY_TIME = 'trendradar_frequency_time';
  105. const STORAGE_KEY_TIMELINE_TIME = 'trendradar_timeline_time';
  106. // 官网配置文件 URL
  107. const REMOTE_CONFIG_URL = 'https://raw.githubusercontent.com/sansan0/TrendRadar/refs/heads/master/config/config.yaml';
  108. const REMOTE_FREQUENCY_URL = 'https://raw.githubusercontent.com/sansan0/TrendRadar/refs/heads/master/config/frequency_words.txt';
  109. const REMOTE_TIMELINE_URL = 'https://raw.githubusercontent.com/sansan0/TrendRadar/refs/heads/master/config/timeline.yaml';
  110. const REMOTE_VERSION_URL = 'https://raw.githubusercontent.com/sansan0/TrendRadar/refs/heads/master/version_configs';
  111. let currentYaml = "";
  112. let currentFrequency = "";
  113. let currentTimeline = "";
  114. let currentFrequencyData = null; // 缓存解析后的数据,避免重复解析导致索引错位
  115. let currentTab = "config";
  116. // ==========================================
  117. // 2. 初始化与事件绑定
  118. // ==========================================
  119. // 防抖定时器
  120. let configSaveTimer = null;
  121. let frequencySaveTimer = null;
  122. let timelineSaveTimer = null;
  123. document.addEventListener('DOMContentLoaded', () => {
  124. const yamlEditor = document.getElementById('yaml-editor');
  125. const frequencyEditor = document.getElementById('frequency-editor');
  126. // 尝试从 LocalStorage 恢复配置
  127. const savedConfig = localStorage.getItem(STORAGE_KEY_CONFIG);
  128. const savedFrequency = localStorage.getItem(STORAGE_KEY_FREQUENCY);
  129. // 初始化编辑器
  130. if (savedConfig && savedConfig.trim() && savedConfig !== INITIAL_YAML) {
  131. yamlEditor.value = savedConfig;
  132. currentYaml = savedConfig;
  133. showToast('已恢复上次保存的配置', 'info');
  134. } else {
  135. yamlEditor.value = INITIAL_YAML;
  136. currentYaml = INITIAL_YAML;
  137. }
  138. if (savedFrequency && savedFrequency.trim()) {
  139. frequencyEditor.value = savedFrequency;
  140. currentFrequency = savedFrequency;
  141. } else {
  142. frequencyEditor.value = "# 在此粘贴你的 frequency_words.txt 内容...\n# 或拖拽文件到编辑器区域\n\n[GLOBAL_FILTER]\n\n[WORD_GROUPS]\n";
  143. currentFrequency = frequencyEditor.value;
  144. }
  145. // 初始化 Timeline 编辑器
  146. const timelineEditor = document.getElementById('timeline-editor');
  147. const savedTimeline = localStorage.getItem(STORAGE_KEY_TIMELINE);
  148. const INITIAL_TIMELINE = `# 在此粘贴你的 timeline.yaml...\n# 或拖拽文件到编辑器区域\n# 或点击右上角"加载官网最新配置"`;
  149. if (savedTimeline && savedTimeline.trim() && savedTimeline !== INITIAL_TIMELINE) {
  150. timelineEditor.value = savedTimeline;
  151. currentTimeline = savedTimeline;
  152. } else {
  153. timelineEditor.value = INITIAL_TIMELINE;
  154. currentTimeline = INITIAL_TIMELINE;
  155. }
  156. // 渲染右侧模块列表
  157. renderModules();
  158. // 监听编辑器输入(实时同步到 UI + 防抖保存)
  159. yamlEditor.addEventListener('input', (e) => {
  160. currentYaml = e.target.value;
  161. updateBackdrop('yaml-editor', 'yaml-backdrop');
  162. syncYamlToUI();
  163. debounceSaveConfig();
  164. });
  165. frequencyEditor.addEventListener('input', (e) => {
  166. currentFrequency = e.target.value;
  167. updateBackdrop('frequency-editor', 'frequency-backdrop');
  168. currentFrequencyData = null;
  169. syncFrequencyToUI();
  170. debounceSaveFrequency();
  171. });
  172. timelineEditor.addEventListener('input', (e) => {
  173. currentTimeline = e.target.value;
  174. updateBackdrop('timeline-editor', 'timeline-backdrop');
  175. syncTimelineToUI();
  176. debounceSaveTimeline();
  177. });
  178. // 同步滚动
  179. yamlEditor.addEventListener('scroll', () => syncScroll('yaml-editor', 'yaml-backdrop'));
  180. frequencyEditor.addEventListener('scroll', () => syncScroll('frequency-editor', 'frequency-backdrop'));
  181. timelineEditor.addEventListener('scroll', () => syncScroll('timeline-editor', 'timeline-backdrop'));
  182. // 初始化拖拽上传功能
  183. initDragAndDrop(yamlEditor, 'config');
  184. initDragAndDrop(frequencyEditor, 'frequency');
  185. initDragAndDrop(timelineEditor, 'timeline');
  186. // 页面关闭/刷新时立即保存
  187. window.addEventListener('beforeunload', saveAllToLocalStorage);
  188. document.addEventListener('keydown', function(e) {
  189. if ((e.ctrlKey || e.metaKey) && e.key === 's') {
  190. e.preventDefault();
  191. saveAllToLocalStorage();
  192. showToast('已手动保存配置', 'success');
  193. }
  194. });
  195. syncYamlToUI();
  196. updateBackdrop('yaml-editor', 'yaml-backdrop');
  197. updateBackdrop('frequency-editor', 'frequency-backdrop');
  198. updateBackdrop('timeline-editor', 'timeline-backdrop');
  199. updateSaveTimeDisplay();
  200. });
  201. // 防抖保存 config.yaml
  202. function debounceSaveConfig() {
  203. if (configSaveTimer) clearTimeout(configSaveTimer);
  204. configSaveTimer = setTimeout(() => {
  205. saveConfigToLocalStorage();
  206. }, 1000);
  207. }
  208. // 防抖保存 frequency_words.txt
  209. function debounceSaveFrequency() {
  210. if (frequencySaveTimer) clearTimeout(frequencySaveTimer);
  211. frequencySaveTimer = setTimeout(() => {
  212. saveFrequencyToLocalStorage();
  213. }, 1000);
  214. }
  215. // 防抖保存 timeline.yaml
  216. function debounceSaveTimeline() {
  217. if (timelineSaveTimer) clearTimeout(timelineSaveTimer);
  218. timelineSaveTimer = setTimeout(() => {
  219. saveTimelineToLocalStorage();
  220. }, 1000);
  221. }
  222. // ==========================================
  223. // 2.1 拖拽上传功能
  224. // ==========================================
  225. function initDragAndDrop(editor, type) {
  226. const container = editor.parentElement;
  227. const dropOverlay = document.createElement('div');
  228. dropOverlay.className = 'drop-overlay hidden';
  229. dropOverlay.innerHTML = `
  230. <div class="drop-overlay-content">
  231. <i class="fa-solid fa-cloud-arrow-up text-4xl mb-2"></i>
  232. <div class="text-sm font-bold">释放以加载文件</div>
  233. <div class="text-xs opacity-75">${type === 'config' ? 'config.yaml' : type === 'timeline' ? 'timeline.yaml' : 'frequency_words.txt'}</div>
  234. </div>
  235. `;
  236. container.style.position = 'relative';
  237. container.appendChild(dropOverlay);
  238. editor.addEventListener('dragover', (e) => {
  239. e.preventDefault();
  240. e.stopPropagation();
  241. dropOverlay.classList.remove('hidden');
  242. });
  243. editor.addEventListener('dragleave', (e) => {
  244. e.preventDefault();
  245. e.stopPropagation();
  246. if (!container.contains(e.relatedTarget)) {
  247. dropOverlay.classList.add('hidden');
  248. }
  249. });
  250. dropOverlay.addEventListener('dragleave', (e) => {
  251. e.preventDefault();
  252. e.stopPropagation();
  253. if (!container.contains(e.relatedTarget)) {
  254. dropOverlay.classList.add('hidden');
  255. }
  256. });
  257. dropOverlay.addEventListener('dragover', (e) => {
  258. e.preventDefault();
  259. e.stopPropagation();
  260. });
  261. dropOverlay.addEventListener('drop', (e) => {
  262. e.preventDefault();
  263. e.stopPropagation();
  264. dropOverlay.classList.add('hidden');
  265. handleFileDrop(e, type);
  266. });
  267. editor.addEventListener('drop', (e) => {
  268. e.preventDefault();
  269. e.stopPropagation();
  270. dropOverlay.classList.add('hidden');
  271. handleFileDrop(e, type);
  272. });
  273. }
  274. function handleFileDrop(e, type) {
  275. const files = e.dataTransfer.files;
  276. if (files.length === 0) return;
  277. const file = files[0];
  278. const validExtensions = type === 'config'
  279. ? ['.yaml', '.yml', '.txt']
  280. : type === 'timeline'
  281. ? ['.yaml', '.yml']
  282. : ['.txt', '.yaml', '.yml'];
  283. const fileName = file.name.toLowerCase();
  284. const isValid = validExtensions.some(ext => fileName.endsWith(ext));
  285. if (!isValid) {
  286. showToast(`请拖入 ${type === 'config' || type === 'timeline' ? 'YAML' : 'TXT'} 文件`, 'error');
  287. return;
  288. }
  289. const reader = new FileReader();
  290. reader.onload = (event) => {
  291. const content = event.target.result;
  292. if (type === 'config') {
  293. try {
  294. jsyaml.load(content);
  295. document.getElementById('yaml-editor').value = content;
  296. currentYaml = content;
  297. syncYamlToUI();
  298. showToast(`已加载: ${file.name}`, 'success');
  299. } catch (err) {
  300. showToast(`YAML 语法错误: ${err.message}`, 'error');
  301. // 仍然加载,让用户修复
  302. document.getElementById('yaml-editor').value = content;
  303. currentYaml = content;
  304. }
  305. } else if (type === 'timeline') {
  306. try {
  307. jsyaml.load(content);
  308. document.getElementById('timeline-editor').value = content;
  309. currentTimeline = content;
  310. updateBackdrop('timeline-editor', 'timeline-backdrop');
  311. syncTimelineToUI();
  312. showToast(`已加载: ${file.name}`, 'success');
  313. } catch (err) {
  314. showToast(`YAML 语法错误: ${err.message}`, 'error');
  315. document.getElementById('timeline-editor').value = content;
  316. currentTimeline = content;
  317. }
  318. } else {
  319. document.getElementById('frequency-editor').value = content;
  320. currentFrequency = content;
  321. syncFrequencyToUI();
  322. showToast(`已加载: ${file.name}`, 'success');
  323. }
  324. };
  325. reader.onerror = () => {
  326. showToast('文件读取失败', 'error');
  327. };
  328. reader.readAsText(file);
  329. }
  330. // ==========================================
  331. // 2.2 LocalStorage 保存与恢复
  332. // ==========================================
  333. // 保存 config.yaml
  334. function saveConfigToLocalStorage() {
  335. try {
  336. if (currentYaml && currentYaml.trim().length > 10) {
  337. const now = new Date().toISOString();
  338. localStorage.setItem(STORAGE_KEY_CONFIG, currentYaml);
  339. localStorage.setItem(STORAGE_KEY_CONFIG_TIME, now);
  340. updateSaveTimeDisplay();
  341. }
  342. } catch (e) {
  343. console.warn('LocalStorage 保存 config 失败:', e);
  344. }
  345. }
  346. // 保存 frequency_words.txt
  347. function saveFrequencyToLocalStorage() {
  348. try {
  349. if (currentFrequency && currentFrequency.trim().length > 10) {
  350. const now = new Date().toISOString();
  351. localStorage.setItem(STORAGE_KEY_FREQUENCY, currentFrequency);
  352. localStorage.setItem(STORAGE_KEY_FREQUENCY_TIME, now);
  353. updateSaveTimeDisplay();
  354. }
  355. } catch (e) {
  356. console.warn('LocalStorage 保存 frequency 失败:', e);
  357. }
  358. }
  359. // 保存 timeline.yaml
  360. function saveTimelineToLocalStorage() {
  361. try {
  362. if (currentTimeline && currentTimeline.trim().length > 10) {
  363. const now = new Date().toISOString();
  364. localStorage.setItem(STORAGE_KEY_TIMELINE, currentTimeline);
  365. localStorage.setItem(STORAGE_KEY_TIMELINE_TIME, now);
  366. updateSaveTimeDisplay();
  367. }
  368. } catch (e) {
  369. console.warn('LocalStorage 保存 timeline 失败:', e);
  370. }
  371. }
  372. // 保存全部(页面关闭时调用)
  373. function saveAllToLocalStorage() {
  374. saveConfigToLocalStorage();
  375. saveFrequencyToLocalStorage();
  376. saveTimelineToLocalStorage();
  377. }
  378. // 兼容旧调用
  379. function saveToLocalStorage() {
  380. saveAllToLocalStorage();
  381. }
  382. // 格式化时间显示
  383. function formatSaveTime(isoString) {
  384. if (!isoString) return '未保存';
  385. const date = new Date(isoString);
  386. const now = new Date();
  387. const diffMs = now - date;
  388. const diffMins = Math.floor(diffMs / 60000);
  389. const diffHours = Math.floor(diffMs / 3600000);
  390. const diffDays = Math.floor(diffMs / 86400000);
  391. if (diffMins < 1) return '刚刚';
  392. if (diffMins < 60) return `${diffMins} 分钟前`;
  393. if (diffHours < 24) return `${diffHours} 小时前`;
  394. if (diffDays < 7) return `${diffDays} 天前`;
  395. return date.toLocaleDateString('zh-CN', { month: 'short', day: 'numeric', hour: '2-digit', minute: '2-digit' });
  396. }
  397. // 更新保存时间显示
  398. function updateSaveTimeDisplay() {
  399. const configTime = localStorage.getItem(STORAGE_KEY_CONFIG_TIME);
  400. const frequencyTime = localStorage.getItem(STORAGE_KEY_FREQUENCY_TIME);
  401. // 更新 config.yaml 的时间显示
  402. const configTimeEl = document.getElementById('config-save-time');
  403. const configLabelEl = document.getElementById('config-save-label');
  404. if (configTimeEl) {
  405. configTimeEl.textContent = formatSaveTime(configTime);
  406. configTimeEl.title = configTime ? new Date(configTime).toLocaleString('zh-CN') : '未保存';
  407. if (configLabelEl) {
  408. if (configTime) {
  409. configLabelEl.classList.remove('hidden');
  410. } else {
  411. configLabelEl.classList.add('hidden');
  412. }
  413. }
  414. }
  415. // 更新 frequency_words.txt 的时间显示
  416. const frequencyTimeEl = document.getElementById('frequency-save-time');
  417. const frequencyLabelEl = document.getElementById('frequency-save-label');
  418. if (frequencyTimeEl) {
  419. frequencyTimeEl.textContent = formatSaveTime(frequencyTime);
  420. frequencyTimeEl.title = frequencyTime ? new Date(frequencyTime).toLocaleString('zh-CN') : '未保存';
  421. if (frequencyLabelEl) {
  422. if (frequencyTime) {
  423. frequencyLabelEl.classList.remove('hidden');
  424. } else {
  425. frequencyLabelEl.classList.add('hidden');
  426. }
  427. }
  428. }
  429. // 更新 timeline.yaml 的时间显示
  430. const timelineTime = localStorage.getItem(STORAGE_KEY_TIMELINE_TIME);
  431. const timelineTimeEl = document.getElementById('timeline-save-time');
  432. const timelineLabelEl = document.getElementById('timeline-save-label');
  433. if (timelineTimeEl) {
  434. timelineTimeEl.textContent = formatSaveTime(timelineTime);
  435. timelineTimeEl.title = timelineTime ? new Date(timelineTime).toLocaleString('zh-CN') : '未保存';
  436. if (timelineLabelEl) {
  437. if (timelineTime) {
  438. timelineLabelEl.classList.remove('hidden');
  439. } else {
  440. timelineLabelEl.classList.add('hidden');
  441. }
  442. }
  443. }
  444. }
  445. // ==========================================
  446. // 2.3 加载官网最新配置
  447. // ==========================================
  448. window.openLoadConfigModal = function() {
  449. // 创建选择弹窗
  450. const modal = document.createElement('div');
  451. modal.id = 'load-config-modal';
  452. modal.className = 'modal-overlay';
  453. modal.innerHTML = `
  454. <div class="modal-content" style="max-width: 420px;">
  455. <div class="flex items-center justify-between mb-4">
  456. <h3 class="text-lg font-bold text-gray-800"><i class="fa-solid fa-cloud-arrow-down mr-2 text-blue-500"></i>加载官网最新配置</h3>
  457. <button onclick="closeLoadConfigModal()" class="text-gray-400 hover:text-gray-600"><i class="fa-solid fa-times text-xl"></i></button>
  458. </div>
  459. <div class="text-sm text-gray-600 mb-4">
  460. 选择要从 GitHub 加载的配置文件:
  461. </div>
  462. <div class="space-y-3">
  463. <label class="flex items-center gap-3 p-3 rounded-lg border border-gray-200 hover:bg-blue-50 hover:border-blue-300 cursor-pointer transition-colors">
  464. <input type="checkbox" id="load-config-yaml" checked class="w-4 h-4 text-blue-600 rounded">
  465. <div class="flex-1">
  466. <div class="font-medium text-gray-800">config.yaml</div>
  467. <div class="text-xs text-gray-500">系统配置、平台、AI、通知等</div>
  468. </div>
  469. <i class="fa-solid fa-file-code text-blue-400"></i>
  470. </label>
  471. <label class="flex items-center gap-3 p-3 rounded-lg border border-gray-200 hover:bg-blue-50 hover:border-blue-300 cursor-pointer transition-colors">
  472. <input type="checkbox" id="load-frequency-txt" checked class="w-4 h-4 text-blue-600 rounded">
  473. <div class="flex-1">
  474. <div class="font-medium text-gray-800">frequency_words.txt</div>
  475. <div class="text-xs text-gray-500">关键词组、过滤规则、正则逻辑</div>
  476. </div>
  477. <i class="fa-solid fa-filter text-orange-400"></i>
  478. </label>
  479. <label class="flex items-center gap-3 p-3 rounded-lg border border-gray-200 hover:bg-blue-50 hover:border-blue-300 cursor-pointer transition-colors">
  480. <input type="checkbox" id="load-timeline-yaml" checked class="w-4 h-4 text-blue-600 rounded">
  481. <div class="flex-1">
  482. <div class="font-medium text-gray-800">timeline.yaml</div>
  483. <div class="text-xs text-gray-500">调度时间线、预设模板、自定义时间段</div>
  484. </div>
  485. <i class="fa-solid fa-calendar-week text-purple-400"></i>
  486. </label>
  487. </div>
  488. <div class="text-xs text-gray-400 mt-3 p-2 bg-gray-50 rounded">
  489. <i class="fa-solid fa-info-circle mr-1"></i>
  490. 数据来源:<a href="https://github.com/sansan0/TrendRadar" target="_blank" class="text-blue-500 hover:underline">sansan0/TrendRadar</a>
  491. </div>
  492. <div class="flex justify-end gap-2 mt-4">
  493. <button onclick="closeLoadConfigModal()" class="px-4 py-2 text-gray-600 hover:bg-gray-100 rounded-lg">取消</button>
  494. <button onclick="confirmLoadConfig()" class="px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700">
  495. <i class="fa-solid fa-download mr-1"></i>加载选中
  496. </button>
  497. </div>
  498. </div>
  499. `;
  500. document.body.appendChild(modal);
  501. }
  502. window.closeLoadConfigModal = function() {
  503. const modal = document.getElementById('load-config-modal');
  504. if (modal) modal.remove();
  505. }
  506. window.confirmLoadConfig = async function() {
  507. const loadConfig = document.getElementById('load-config-yaml')?.checked;
  508. const loadFrequency = document.getElementById('load-frequency-txt')?.checked;
  509. const loadTimeline = document.getElementById('load-timeline-yaml')?.checked;
  510. if (!loadConfig && !loadFrequency && !loadTimeline) {
  511. showToast('请至少选择一个文件', 'warning');
  512. return;
  513. }
  514. closeLoadConfigModal();
  515. showToast('正在从 GitHub 加载...', 'info');
  516. try {
  517. const promises = [];
  518. if (loadConfig) promises.push(fetch(REMOTE_CONFIG_URL).then(r => ({ type: 'config', res: r })));
  519. if (loadFrequency) promises.push(fetch(REMOTE_FREQUENCY_URL).then(r => ({ type: 'frequency', res: r })));
  520. if (loadTimeline) promises.push(fetch(REMOTE_TIMELINE_URL).then(r => ({ type: 'timeline', res: r })));
  521. const results = await Promise.all(promises);
  522. for (const { type, res } of results) {
  523. if (!res.ok) {
  524. const names = { config: 'config.yaml', frequency: 'frequency_words.txt', timeline: 'timeline.yaml' };
  525. throw new Error(`${names[type]} 加载失败: ${res.status}`);
  526. }
  527. const text = await res.text();
  528. if (type === 'config') {
  529. try {
  530. jsyaml.load(text);
  531. } catch (yamlErr) {
  532. showToast(`YAML 语法错误: ${yamlErr.message}`, 'error');
  533. continue;
  534. }
  535. document.getElementById('yaml-editor').value = text;
  536. currentYaml = text;
  537. updateBackdrop('yaml-editor', 'yaml-backdrop');
  538. syncYamlToUI();
  539. } else if (type === 'timeline') {
  540. try {
  541. jsyaml.load(text);
  542. } catch (yamlErr) {
  543. showToast(`YAML 语法错误: ${yamlErr.message}`, 'error');
  544. continue;
  545. }
  546. document.getElementById('timeline-editor').value = text;
  547. currentTimeline = text;
  548. updateBackdrop('timeline-editor', 'timeline-backdrop');
  549. syncTimelineToUI();
  550. } else {
  551. document.getElementById('frequency-editor').value = text;
  552. currentFrequency = text;
  553. currentFrequencyData = null;
  554. updateBackdrop('frequency-editor', 'frequency-backdrop');
  555. syncFrequencyToUI();
  556. }
  557. }
  558. saveToLocalStorage();
  559. const loadedFiles = [];
  560. if (loadConfig) loadedFiles.push('config.yaml');
  561. if (loadFrequency) loadedFiles.push('frequency_words.txt');
  562. if (loadTimeline) loadedFiles.push('timeline.yaml');
  563. showToast(`已加载: ${loadedFiles.join(', ')}`, 'success');
  564. } catch (err) {
  565. console.error('加载远程配置失败:', err);
  566. showToast(`加载失败: ${err.message}`, 'error');
  567. }
  568. }
  569. // ==========================================
  570. // 2.4 Toast 提示
  571. // ==========================================
  572. function showToast(message, type = 'info') {
  573. // 移除已有的 toast
  574. const existingToast = document.querySelector('.toast-notification');
  575. if (existingToast) existingToast.remove();
  576. const toast = document.createElement('div');
  577. toast.className = `toast-notification toast-${type}`;
  578. const icons = {
  579. success: 'fa-check-circle',
  580. error: 'fa-times-circle',
  581. info: 'fa-info-circle',
  582. warning: 'fa-exclamation-triangle'
  583. };
  584. toast.innerHTML = `
  585. <i class="fa-solid ${icons[type] || icons.info}"></i>
  586. <span>${message}</span>
  587. `;
  588. document.body.appendChild(toast);
  589. // 动画入场
  590. requestAnimationFrame(() => {
  591. toast.classList.add('show');
  592. });
  593. // 自动消失
  594. setTimeout(() => {
  595. toast.classList.remove('show');
  596. setTimeout(() => toast.remove(), 300);
  597. }, 3000);
  598. }
  599. // ==========================================
  600. // 3. 渲染逻辑
  601. // ==========================================
  602. function renderModules() {
  603. const container = document.getElementById('config-panel');
  604. container.innerHTML = '';
  605. renderModuleNav();
  606. MODULE_DEFS.forEach(mod => {
  607. const card = document.createElement('div');
  608. card.className = `module-card ${mod.editable ? 'active' : 'disabled'}`;
  609. card.id = `module-${mod.key}`;
  610. const header = `
  611. <div class="module-header px-4 py-3 flex items-center justify-between cursor-pointer" onclick="scrollToModuleInEditor('${mod.key}')">
  612. <div class="flex items-center">
  613. <span class="text-sm font-bold">${mod.name}</span>
  614. <i class="fa-solid fa-arrow-up-right-from-square text-blue-400 text-[10px] ml-2 opacity-0 group-hover:opacity-100" title="跳转到左侧编辑器"></i>
  615. </div>
  616. ${!mod.editable ?
  617. '<span class="locked-badge text-[10px] text-gray-400 border border-gray-200 px-1.5 py-0.5 rounded">只读 (请在左侧编辑)</span>' :
  618. '<i class="fa-solid fa-chevron-down text-gray-400 text-xs"></i>'}
  619. </div>
  620. `;
  621. const body = mod.editable ? `<div class="module-body p-5 border-t border-gray-50 space-y-4" id="controls-${mod.key}"></div>` : '';
  622. card.innerHTML = header + body;
  623. container.appendChild(card);
  624. if (mod.editable) {
  625. renderControls(mod);
  626. }
  627. });
  628. }
  629. // 渲染模块导航栏
  630. function renderModuleNav() {
  631. const nav = document.getElementById('module-nav');
  632. if (!nav) return;
  633. nav.innerHTML = MODULE_DEFS.map(mod => `
  634. <button onclick="scrollToModuleInEditor('${mod.key}')"
  635. class="module-nav-btn text-[10px] px-2 py-1 rounded ${mod.editable ? 'bg-blue-100 text-blue-700 hover:bg-blue-200' : 'bg-gray-100 text-gray-500 hover:bg-gray-200'} transition-colors"
  636. title="跳转到模块 ${mod.id}">
  637. ${mod.id}
  638. </button>
  639. `).join('');
  640. }
  641. // 切换组名编辑状态
  642. window.toggleGroupNameEdit = function(btn) {
  643. const container = btn.parentNode;
  644. const span = container.querySelector('span.text-sm');
  645. const input = container.querySelector('input[type="text"]');
  646. if (input.classList.contains('hidden')) {
  647. // 进入编辑模式
  648. span.classList.add('hidden');
  649. input.classList.remove('hidden');
  650. input.focus();
  651. btn.innerHTML = '<i class="fa-solid fa-check text-green-600"></i>';
  652. } else {
  653. // 退出编辑模式
  654. span.classList.remove('hidden');
  655. input.classList.add('hidden');
  656. btn.innerHTML = '<i class="fa-solid fa-pen"></i>';
  657. // 如果内容变化,已经通过 onchange 触发更新
  658. span.textContent = input.value;
  659. }
  660. }
  661. // 跳转到左侧编辑器中对应词组的位置
  662. window.scrollToWordGroupInEditor = function(groupIndex) {
  663. const editor = document.getElementById('frequency-editor');
  664. // 重新解析以确保行号准确
  665. const data = parseFrequencyText(editor.value);
  666. if (!data.wordGroups[groupIndex]) return;
  667. const targetLineIndex = data.wordGroups[groupIndex].startLine;
  668. if (targetLineIndex === undefined || targetLineIndex === -1) return;
  669. const lines = editor.value.split('\n');
  670. const lineHeight = 19.5;
  671. const scrollPosition = targetLineIndex * lineHeight;
  672. // 设置光标选区
  673. let charCount = 0;
  674. for (let i = 0; i < targetLineIndex; i++) {
  675. charCount += lines[i].length + 1; // +1 for newline
  676. }
  677. editor.focus();
  678. editor.setSelectionRange(charCount, charCount + lines[targetLineIndex].length);
  679. editor.scrollTop = scrollPosition - 50;
  680. // 高亮效果
  681. editor.style.transition = 'background-color 0.3s';
  682. const originalBg = editor.style.backgroundColor;
  683. editor.style.backgroundColor = '#2d4a7c';
  684. setTimeout(() => {
  685. editor.style.backgroundColor = originalBg;
  686. }, 300);
  687. }
  688. // 跳转到左侧编辑器中对应模块的位置
  689. window.scrollToModuleInEditor = function(modKey) {
  690. const editor = document.getElementById('yaml-editor');
  691. const yaml = editor.value;
  692. const lines = yaml.split('\n');
  693. // 查找模块标题注释行(# N. 模块名)
  694. let targetLineIndex = -1;
  695. const mod = MODULE_DEFS.find(m => m.key === modKey);
  696. if (!mod) return;
  697. // 直接匹配包含模块编号的标题行,兼容 "4." 和 "4.5" 两种编号格式
  698. const escapedId = String(mod.id).replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
  699. const moduleTitlePattern = new RegExp(`^#\\s*${escapedId}(?:\\.)?\\s+`, 'i');
  700. for (let i = 0; i < lines.length; i++) {
  701. const line = lines[i];
  702. // 匹配模块标题行(包含编号的注释行)
  703. if (moduleTitlePattern.test(line)) {
  704. targetLineIndex = i;
  705. break;
  706. }
  707. }
  708. // 如果没找到标题行,尝试查找模块键名(如 platforms:)
  709. if (targetLineIndex === -1) {
  710. for (let i = 0; i < lines.length; i++) {
  711. if (lines[i].match(new RegExp(`^${modKey}:\\s*`))) {
  712. targetLineIndex = i;
  713. break;
  714. }
  715. }
  716. }
  717. if (targetLineIndex === -1) return;
  718. // 计算目标位置并滚动
  719. const lineHeight = 19.5;
  720. const scrollPosition = targetLineIndex * lineHeight;
  721. // 设置光标位置
  722. const textBeforeTarget = lines.slice(0, targetLineIndex).join('\n').length + (targetLineIndex > 0 ? 1 : 0);
  723. editor.focus();
  724. editor.setSelectionRange(textBeforeTarget, textBeforeTarget + lines[targetLineIndex].length);
  725. editor.scrollTop = scrollPosition - 5;
  726. // 高亮提示(闪烁效果)
  727. editor.style.transition = 'background-color 0.3s';
  728. const originalBg = editor.style.backgroundColor;
  729. editor.style.backgroundColor = '#2d4a7c';
  730. setTimeout(() => {
  731. editor.style.backgroundColor = originalBg;
  732. }, 300);
  733. }
  734. function renderControls(mod) {
  735. const body = document.getElementById(`controls-${mod.key}`);
  736. // 根据模块 key 定义不同的 UI 控件
  737. let html = "";
  738. switch(mod.key) {
  739. case "platforms":
  740. html = createToggleControl(mod.key, "enabled", "启用热榜抓取");
  741. html += `<div class="mt-4 mb-2 text-xs font-bold text-gray-700">平台列表 <span class="text-gray-400 font-normal">(可拖拽排序)</span></div>`;
  742. html += `<div id="platforms-list" class="space-y-2"></div>`;
  743. html += `<div class="flex items-center gap-2 mt-3">
  744. <button onclick="openPlatformModal()" class="text-xs bg-green-600 text-white px-3 py-1.5 rounded hover:bg-green-700 transition-colors">
  745. <i class="fa-solid fa-plus mr-1"></i>添加平台
  746. </button>
  747. <a href="https://github.com/sansan0/TrendRadar?tab=readme-ov-file#%E9%85%8D%E7%BD%AE%E8%AF%A6%E8%A7%A3" target="_blank" class="text-xs bg-gray-100 text-gray-600 px-3 py-1.5 rounded hover:bg-gray-200 transition-colors border border-gray-200 flex items-center gap-1 no-underline">
  748. <i class="fa-solid fa-circle-question text-gray-400"></i>添加其它平台
  749. </a>
  750. </div>`;
  751. break;
  752. case "rss":
  753. html = createToggleControl(mod.key, "enabled", "启用 RSS 抓取");
  754. html += `<div class="mt-3 mb-2 text-xs font-bold text-gray-700">新鲜度过滤</div>`;
  755. html += createToggleControl(mod.key, "freshness_filter.enabled", "启用新鲜度过滤");
  756. html += createNumberControl(mod.key, "freshness_filter.max_age_days", "最大文章年龄 (天)");
  757. html += `<div class="mt-4 mb-2 text-xs font-bold text-gray-700">RSS 源列表</div>`;
  758. html += `<div id="rss-feeds-list" class="space-y-2"></div>`;
  759. html += `<div class="flex items-center gap-2 mt-3">
  760. <button onclick="openRssModal()" class="text-xs bg-green-600 text-white px-3 py-1.5 rounded hover:bg-green-700 transition-colors">
  761. <i class="fa-solid fa-plus mr-1"></i>添加 RSS 源
  762. </button>
  763. <div class="text-xs text-gray-500 italic">
  764. (内附 RSS 源参考库)
  765. </div>
  766. </div>`;
  767. html += `<div class="text-xs text-orange-600 mt-2 p-2 bg-orange-50 rounded border border-orange-200">
  768. <i class="fa-solid fa-triangle-exclamation mr-1"></i>
  769. <strong>注意:</strong>部分海外媒体内容可能涉及敏感话题,AI 模型可能拒绝翻译或分析,建议根据实际需求筛选订阅源。
  770. </div>`;
  771. break;
  772. case "report":
  773. html = createSelectControl(mod.key, "mode", "报告模式", ["current", "daily", "incremental"]);
  774. html += createSelectControl(mod.key, "display_mode", "分组维度", ["keyword", "platform"]);
  775. html += createToggleControl(mod.key, "sort_by_position_first", "按定义顺序排序");
  776. html += createNumberControl(mod.key, "rank_threshold", "排名高亮阈值");
  777. html += createNumberControl(mod.key, "max_news_per_keyword", "每个关键词最大显示数量");
  778. break;
  779. case "filter":
  780. html = createSelectControl(mod.key, "method", "筛选方法", ["keyword", "ai"]);
  781. html += createToggleControl(mod.key, "priority_sort_enabled", "AI 模式按标签优先级排序");
  782. html += `<div class="text-xs text-gray-500 mt-2 p-2 bg-blue-50 rounded border border-blue-200">
  783. <i class="fa-solid fa-info-circle mr-1 text-blue-500"></i>
  784. <strong>说明:</strong><code>method=keyword</code> 使用 <code>frequency_words.txt</code>;
  785. <code>method=ai</code> 使用 <code>ai_interests.txt</code> + AI 筛选配置。<br>
  786. <code>priority_sort_enabled</code> 仅在 <code>method=ai</code> 时生效。
  787. </div>`;
  788. break;
  789. case "ai_filter":
  790. html = `<div class="text-xs text-gray-500 mb-3 p-2 bg-blue-50 rounded border border-blue-200">
  791. <i class="fa-solid fa-info-circle mr-1 text-blue-500"></i>
  792. 仅当 <strong>filter.method=ai</strong> 时生效。
  793. </div>`;
  794. html += createNumberControl(mod.key, "batch_size", "每批标题数量");
  795. html += createNumberControl(mod.key, "batch_interval", "分批间隔 (秒)");
  796. html += createNumberControl(mod.key, "min_score", "最低分数阈值 (0~1)");
  797. html += createInputControl(mod.key, "interests_file", "兴趣描述文件 (可选)");
  798. html += `<div class="text-xs text-amber-700 mt-1 mb-3 p-2 bg-amber-50 rounded border border-amber-200">
  799. <i class="fa-solid fa-folder-tree mr-1"></i>
  800. 留空时使用 <code>config/ai_interests.txt</code>;填写后仅从
  801. <code>config/custom/ai/</code> 查找该文件名。
  802. </div>`;
  803. html += createNumberControl(mod.key, "reclassify_threshold", "全量重分类阈值 (0~1)");
  804. html += createInputControl(mod.key, "prompt_file", "分类提示词文件");
  805. html += createInputControl(mod.key, "extract_prompt_file", "标签提取提示词文件");
  806. html += createInputControl(mod.key, "update_tags_prompt_file", "标签更新提示词文件");
  807. break;
  808. case "display":
  809. html = `<div class="text-xs font-bold text-gray-700 mb-2">推送内容控制 <span class="text-gray-400 font-normal">(可拖拽排序)</span></div>`;
  810. html += `<div id="display-regions-list" class="space-y-2"></div>`;
  811. html += `<div class="text-xs text-gray-500 mt-2 mb-6">
  812. <i class="fa-solid fa-lightbulb mr-1"></i>
  813. 提示:列表顺序决定了报告中的显示顺序
  814. </div>`;
  815. // Standalone Configuration Section
  816. html += `<div class="border-t border-gray-200 pt-4 mt-4">`;
  817. html += `<div class="text-xs font-bold text-gray-700 mb-3">独立展示区配置 <span class="text-gray-400 font-normal">(推送展示由上方开关控制,AI 分析由 AI 模块的开关独立控制)</span></div>`;
  818. html += createNumberControl(mod.key, "standalone.max_items", "每个源最多展示条数");
  819. html += `<div class="mt-3 mb-2 text-xs font-medium text-gray-700">选择要展示的热榜平台</div>`;
  820. html += `<div id="standalone-platforms-list" class="max-h-40 overflow-y-auto border border-gray-200 rounded p-2 bg-gray-50 grid grid-cols-2 gap-2"></div>`;
  821. html += `<div class="mt-3 mb-2 text-xs font-medium text-gray-700">选择要展示的 RSS 源</div>`;
  822. html += `<div id="standalone-rss-list" class="max-h-40 overflow-y-auto border border-gray-200 rounded p-2 bg-gray-50 grid grid-cols-1 gap-2"></div>`;
  823. html += `</div>`;
  824. setTimeout(() => {
  825. renderDisplayRegionsList();
  826. renderStandaloneLists();
  827. }, 0);
  828. break;
  829. case "notification":
  830. html = `<div class="text-xs text-gray-500 mb-2 p-2 bg-blue-50 rounded border border-blue-200">
  831. <i class="fa-solid fa-info-circle mr-1 text-blue-500"></i>
  832. 推送时间由 <strong>timeline.yaml</strong> 控制,切换到 timeline.yaml 标签页可可视化编辑调度规则。<br>
  833. 此处仅配置通知渠道(Telegram / 企业微信等),请在左侧编辑器中修改。
  834. </div>`;
  835. break;
  836. case "ai":
  837. html = createInputControl(mod.key, "model", "模型名称");
  838. html += createInputControl(mod.key, "api_key", "API Key", "password");
  839. html += createInputControl(mod.key, "api_base", "API Base URL (可选)");
  840. html += createNumberControl(mod.key, "timeout", "请求超时 (秒)");
  841. html += createNumberControl(mod.key, "temperature", "采样温度 (0.0-2.0)");
  842. html += createNumberControl(mod.key, "max_tokens", "最大生成 Token 数");
  843. break;
  844. case "ai_analysis":
  845. html = createToggleControl(mod.key, "enabled", "开启 AI 分析报告");
  846. // 提示:分析时间窗口已迁移到 timeline.yaml
  847. html += `<div class="text-xs text-gray-500 mt-3 mb-3 p-2 bg-blue-50 rounded border border-blue-200">
  848. <i class="fa-solid fa-info-circle mr-1 text-blue-500"></i>
  849. AI 分析的执行时间已由 <strong>timeline.yaml</strong> 统一控制。
  850. </div>`;
  851. // 其他 AI 分析配置
  852. html += `<div class="text-xs font-bold text-blue-600 mb-2">分析内容配置</div>`;
  853. html += createInputControl(mod.key, "language", "输出语言");
  854. html += createInputControl(mod.key, "prompt_file", "提示词配置文件");
  855. html += createSelectControl(mod.key, "mode", "AI 分析模式", ["follow_report", "daily", "current", "incremental"]);
  856. html += createNumberControl(mod.key, "max_news_for_analysis", "最大分析条数");
  857. html += createToggleControl(mod.key, "include_rss", "包含 RSS 内容");
  858. html += createToggleControl(mod.key, "include_standalone", "包含独立展示区数据");
  859. html += createToggleControl(mod.key, "include_rank_timeline", "传递完整排名时间线");
  860. break;
  861. case "ai_translation":
  862. html = createToggleControl(mod.key, "enabled", "开启 AI 自动翻译");
  863. html += createInputControl(mod.key, "language", "目标语言");
  864. html += createInputControl(mod.key, "prompt_file", "提示词配置文件");
  865. break;
  866. }
  867. body.innerHTML = html;
  868. // 绑定事件
  869. body.querySelectorAll('input, select').forEach(el => {
  870. el.addEventListener('change', (e) => {
  871. updateYamlFromUI(mod.key, e.target.dataset.path, e.target);
  872. });
  873. });
  874. }
  875. // ==========================================
  876. // 4. 同步逻辑 (YAML -> UI)
  877. // ==========================================
  878. function syncYamlToUI() {
  879. try {
  880. const doc = jsyaml.load(currentYaml);
  881. if (!doc) return;
  882. MODULE_DEFS.filter(m => m.editable).forEach(mod => {
  883. const modData = doc[mod.key];
  884. if (!modData) return;
  885. const controls = document.querySelectorAll(`#controls-${mod.key} [data-path]`);
  886. controls.forEach(ctrl => {
  887. const path = ctrl.dataset.path.split('.');
  888. let val = modData;
  889. for (const part of path) {
  890. val = val ? val[part] : undefined;
  891. }
  892. if (ctrl.type === 'checkbox') {
  893. ctrl.checked = !!val;
  894. } else {
  895. ctrl.value = val !== undefined ? val : "";
  896. }
  897. });
  898. });
  899. renderPlatformsList();
  900. renderRssFeedsList();
  901. renderStandaloneLists();
  902. } catch (e) {
  903. // 解析失败时不更新 UI,保持原有状态
  904. }
  905. }
  906. // ==========================================
  907. // 5. 更新逻辑 (UI -> YAML) - 核心难点:正则保留注释
  908. // ==========================================
  909. function updateYamlFromUI(modKey, path, el) {
  910. let newVal = el.type === 'checkbox' ? el.checked : el.value;
  911. // 如果是数字类型
  912. if (el.type === 'number') {
  913. newVal = parseFloat(newVal);
  914. if (isNaN(newVal)) newVal = 0;
  915. }
  916. const editor = document.getElementById('yaml-editor');
  917. let yaml = editor.value;
  918. const lines = yaml.split('\n');
  919. const pathParts = path.split('.');
  920. // 找到模块的起始行
  921. let moduleStartLine = -1;
  922. let moduleEndLine = lines.length;
  923. for (let i = 0; i < lines.length; i++) {
  924. const line = lines[i];
  925. // 匹配模块开始(非缩进的 key:)
  926. const moduleMatch = line.match(/^([a-z_]+):/);
  927. if (moduleMatch) {
  928. if (moduleMatch[1] === modKey) {
  929. moduleStartLine = i;
  930. } else if (moduleStartLine >= 0) {
  931. // 找到下一个模块,记录当前模块结束位置
  932. moduleEndLine = i;
  933. break;
  934. }
  935. }
  936. }
  937. if (moduleStartLine < 0) return;
  938. // 在模块内查找目标路径
  939. let targetLine = -1;
  940. let currentIndent = 0;
  941. let searchKey = pathParts[pathParts.length - 1];
  942. for (let i = moduleStartLine + 1; i < moduleEndLine; i++) {
  943. const line = lines[i];
  944. if (line.trim() === '' || line.trim().startsWith('#')) continue;
  945. // 检查是否匹配目标键
  946. const indent = line.search(/\S/);
  947. const keyMatch = line.match(/^\s*([a-z_]+):\s*(.*)/i);
  948. if (keyMatch && keyMatch[1] === searchKey) {
  949. // 如果是嵌套路径,需要检查缩进层级是否正确
  950. if (pathParts.length > 1) {
  951. // 简化处理:对于嵌套路径,确保在正确的父级下
  952. let valid = true;
  953. for (let j = 0; j < pathParts.length - 1; j++) {
  954. let found = false;
  955. for (let k = moduleStartLine + 1; k < i; k++) {
  956. const parentMatch = lines[k].match(/^\s*([a-z_]+):/i);
  957. if (parentMatch && parentMatch[1] === pathParts[j]) {
  958. found = true;
  959. break;
  960. }
  961. }
  962. if (!found) {
  963. valid = false;
  964. break;
  965. }
  966. }
  967. if (!valid) continue;
  968. }
  969. targetLine = i;
  970. break;
  971. }
  972. }
  973. if (targetLine < 0) {
  974. // 允许为模块新增一级字段(例如默认被注释掉的 ai_filter.interests_file)
  975. if (pathParts.length === 1) {
  976. let formattedVal = newVal;
  977. if (typeof newVal === 'string') {
  978. formattedVal = `"${newVal.replace(/"/g, '\\"')}"`;
  979. }
  980. lines.splice(moduleEndLine, 0, ` ${searchKey}: ${formattedVal}`);
  981. editor.value = lines.join('\n');
  982. currentYaml = editor.value;
  983. updateBackdrop('yaml-editor', 'yaml-backdrop');
  984. debounceSaveConfig();
  985. }
  986. return;
  987. }
  988. // 更新该行,保留注释
  989. const originalLine = lines[targetLine];
  990. const match = originalLine.match(/^(\s*[a-z_]+:\s*)(.*)$/i);
  991. if (match) {
  992. const prefix = match[1];
  993. const rest = match[2];
  994. // 提取原有注释
  995. const commentMatch = rest.match(/(\s*#.*)$/);
  996. const comment = commentMatch ? commentMatch[1] : '';
  997. // 格式化新值
  998. let formattedVal = newVal;
  999. if (typeof newVal === 'string') {
  1000. // 获取原值部分(去除注释后的部分)
  1001. const valPart = rest.slice(0, rest.length - comment.length).trim();
  1002. // 检查原值是否带有引号
  1003. const isOriginalQuoted = (valPart.startsWith('"') && valPart.endsWith('"')) ||
  1004. (valPart.startsWith("'") && valPart.endsWith("'"));
  1005. // 如果原值有引号,或者新值包含特殊字符(空格、冒号、井号、引号)或者是空字符串,则添加双引号
  1006. if (isOriginalQuoted || newVal.includes(':') || newVal.includes('#') ||
  1007. newVal.includes('"') || newVal.includes(' ') || newVal === "") {
  1008. formattedVal = `"${newVal.replace(/"/g, '\\"')}"`;
  1009. }
  1010. }
  1011. // 构建新行
  1012. lines[targetLine] = `${prefix}${formattedVal}${comment}`;
  1013. }
  1014. // 更新编辑器
  1015. editor.value = lines.join('\n');
  1016. currentYaml = editor.value;
  1017. updateBackdrop('yaml-editor', 'yaml-backdrop');
  1018. debounceSaveConfig();
  1019. }
  1020. // ==========================================
  1021. // 6. UI 组件工厂
  1022. // ==========================================
  1023. function createToggleControl(mod, path, label) {
  1024. const id = `toggle-${mod}-${path.replace('.', '-')}`;
  1025. return `
  1026. <div class="flex items-center justify-between">
  1027. <label for="${id}" class="text-xs font-medium text-gray-700">${label}</label>
  1028. <div class="relative inline-block w-10 mr-2 align-middle select-none">
  1029. <input type="checkbox" id="${id}" data-path="${path}" class="toggle-checkbox absolute block w-5 h-5 rounded-full bg-white border-4 appearance-none cursor-pointer transition-all duration-200 ease-in-out"/>
  1030. <label for="${id}" class="toggle-label block overflow-hidden h-5 rounded-full bg-gray-300 cursor-pointer"></label>
  1031. </div>
  1032. </div>
  1033. `;
  1034. }
  1035. function createInputControl(mod, path, label, type = "text") {
  1036. return `
  1037. <div>
  1038. <label class="block text-[10px] uppercase tracking-wider font-bold text-gray-400 mb-1">${label}</label>
  1039. <input type="${type}" data-path="${path}" class="bg-white border-gray-300 focus:border-blue-500" placeholder="未设置">
  1040. </div>
  1041. `;
  1042. }
  1043. function createNumberControl(mod, path, label) {
  1044. return `
  1045. <div class="flex items-center justify-between">
  1046. <label class="text-xs font-medium text-gray-700">${label}</label>
  1047. <input type="number" data-path="${path}" class="w-20 text-right bg-white border-gray-300" style="width: 80px">
  1048. </div>
  1049. `;
  1050. }
  1051. function createSelectControl(mod, path, label, options) {
  1052. const optionsHtml = options.map(opt => `<option value="${opt}">${opt}</option>`).join('');
  1053. return `
  1054. <div>
  1055. <label class="block text-[10px] uppercase tracking-wider font-bold text-gray-400 mb-1">${label}</label>
  1056. <select data-path="${path}" class="bg-white border-gray-300">
  1057. ${optionsHtml}
  1058. </select>
  1059. </div>
  1060. `;
  1061. }
  1062. // ==========================================
  1063. // 7. 工具函数
  1064. // ==========================================
  1065. window.copyResult = function() {
  1066. const yamlEditor = document.getElementById('yaml-editor');
  1067. const frequencyEditor = document.getElementById('frequency-editor');
  1068. const timelineEditor = document.getElementById('timeline-editor');
  1069. const editor = currentTab === 'config' ? yamlEditor : currentTab === 'timeline' ? timelineEditor : frequencyEditor;
  1070. editor.select();
  1071. document.execCommand('copy');
  1072. const btn = document.querySelector('button[onclick="copyResult()"]');
  1073. const original = btn.innerHTML;
  1074. btn.innerHTML = '<i class="fa-solid fa-check mr-1.5"></i>已复制!';
  1075. setTimeout(() => btn.innerHTML = original, 2000);
  1076. }
  1077. window.resetToDefault = function() {
  1078. if (confirm('确定要重置为初始状态吗?未保存的修改将丢失。')) {
  1079. if (currentTab === 'config') {
  1080. const yamlEditor = document.getElementById('yaml-editor');
  1081. yamlEditor.value = INITIAL_YAML;
  1082. currentYaml = INITIAL_YAML;
  1083. updateBackdrop('yaml-editor', 'yaml-backdrop');
  1084. localStorage.removeItem(STORAGE_KEY_CONFIG);
  1085. localStorage.removeItem(STORAGE_KEY_CONFIG_TIME);
  1086. renderModules();
  1087. syncYamlToUI();
  1088. updateSaveTimeDisplay();
  1089. } else if (currentTab === 'timeline') {
  1090. const timelineEditor = document.getElementById('timeline-editor');
  1091. const initialTimeline = `# 在此粘贴你的 timeline.yaml...\n# 或拖拽文件到编辑器区域\n# 或点击右上角"加载官网最新配置"`;
  1092. timelineEditor.value = initialTimeline;
  1093. currentTimeline = initialTimeline;
  1094. updateBackdrop('timeline-editor', 'timeline-backdrop');
  1095. localStorage.removeItem(STORAGE_KEY_TIMELINE);
  1096. localStorage.removeItem(STORAGE_KEY_TIMELINE_TIME);
  1097. syncTimelineToUI();
  1098. updateSaveTimeDisplay();
  1099. } else {
  1100. const frequencyEditor = document.getElementById('frequency-editor');
  1101. frequencyEditor.value = "# 在此粘贴你的 frequency_words.txt 内容...\n\n[GLOBAL_FILTER]\n\n[WORD_GROUPS]\n";
  1102. currentFrequency = frequencyEditor.value;
  1103. updateBackdrop('frequency-editor', 'frequency-backdrop');
  1104. localStorage.removeItem(STORAGE_KEY_FREQUENCY);
  1105. localStorage.removeItem(STORAGE_KEY_FREQUENCY_TIME);
  1106. syncFrequencyToUI();
  1107. updateSaveTimeDisplay();
  1108. }
  1109. showToast('已重置为初始状态', 'success');
  1110. }
  1111. }
  1112. // ==========================================
  1113. // 8. Tab 切换功能
  1114. // ==========================================
  1115. window.switchTab = function(tab) {
  1116. currentTab = tab;
  1117. const activeClass = "tab-button active px-4 py-2 text-xs font-bold text-gray-300 hover:bg-[#2d2d30] transition-colors border-b-2 border-blue-500";
  1118. const inactiveClass = "tab-button px-4 py-2 text-xs font-bold text-gray-500 hover:bg-[#2d2d30] transition-colors border-b-2 border-transparent";
  1119. // 更新 Tab 按钮状态
  1120. const configBtn = document.getElementById('tab-config');
  1121. const freqBtn = document.getElementById('tab-frequency');
  1122. const timelineBtn = document.getElementById('tab-timeline');
  1123. configBtn.className = tab === 'config' ? activeClass : inactiveClass;
  1124. freqBtn.className = tab === 'frequency' ? activeClass : inactiveClass;
  1125. timelineBtn.className = tab === 'timeline' ? activeClass : inactiveClass;
  1126. // 更新编辑器显示
  1127. document.getElementById('yaml-editor-wrap').classList.toggle('hidden', tab !== 'config');
  1128. document.getElementById('frequency-editor-wrap').classList.toggle('hidden', tab !== 'frequency');
  1129. document.getElementById('timeline-editor-wrap').classList.toggle('hidden', tab !== 'timeline');
  1130. // 更新右侧面板
  1131. document.getElementById('config-panel').classList.toggle('hidden', tab !== 'config');
  1132. document.getElementById('frequency-panel').classList.toggle('hidden', tab !== 'frequency');
  1133. document.getElementById('timeline-panel').classList.toggle('hidden', tab !== 'timeline');
  1134. // 更新模块导航栏显示状态:只在 config 模式下显示
  1135. const moduleNav = document.getElementById('module-nav');
  1136. if (moduleNav) {
  1137. moduleNav.classList.toggle('hidden', tab !== 'config');
  1138. }
  1139. // 更新保存时间显示
  1140. const saveTimeConfig = document.getElementById('save-time-config');
  1141. const saveTimeFrequency = document.getElementById('save-time-frequency');
  1142. const saveTimeTimeline = document.getElementById('save-time-timeline');
  1143. if (saveTimeConfig) saveTimeConfig.classList.toggle('hidden', tab !== 'config');
  1144. if (saveTimeFrequency) saveTimeFrequency.classList.toggle('hidden', tab !== 'frequency');
  1145. if (saveTimeTimeline) saveTimeTimeline.classList.toggle('hidden', tab !== 'timeline');
  1146. // 更新右侧标题
  1147. const versionBtn = document.getElementById('version-check-btn');
  1148. if (tab === 'config') {
  1149. document.getElementById('right-panel-title').textContent = '配置模块';
  1150. if (versionBtn) { versionBtn.style.display = ''; versionBtn.title = "检测 config.yaml 版本"; }
  1151. } else if (tab === 'frequency') {
  1152. document.getElementById('right-panel-title').textContent = '频率词编辑';
  1153. if (versionBtn) { versionBtn.style.display = ''; versionBtn.title = "检测 frequency_words.txt 版本"; }
  1154. } else {
  1155. document.getElementById('right-panel-title').textContent = '时间线调度';
  1156. if (versionBtn) versionBtn.style.display = 'none';
  1157. }
  1158. if (tab === 'frequency') {
  1159. renderFrequencyPanel();
  1160. }
  1161. if (tab === 'timeline') {
  1162. syncTimelineToUI();
  1163. }
  1164. }
  1165. // ==========================================
  1166. // 9. Frequency 编辑器功能
  1167. // ==========================================
  1168. function parseFrequencyText(text) {
  1169. const result = {
  1170. globalFilter: [],
  1171. wordGroups: [],
  1172. originalText: text // 保存原始文本
  1173. };
  1174. const lines = text.split('\n');
  1175. let currentSection = null;
  1176. let currentGroup = null;
  1177. let lastLineWasAlias = false; // 追踪上一行是否为别名行
  1178. let relatedGroupsBuffer = []; // 缓存连续的相关组
  1179. let pendingComments = []; // 缓存待分配的注释行
  1180. // 辅助函数:保存缓存的相关组
  1181. function flushRelatedGroups() {
  1182. if (relatedGroupsBuffer.length > 0) {
  1183. // 如果有多个连续的组,标记它们为相关组
  1184. if (relatedGroupsBuffer.length > 1) {
  1185. relatedGroupsBuffer.forEach((group, idx) => {
  1186. group.isRelatedGroup = true;
  1187. group.relatedGroupIndex = idx;
  1188. group.relatedGroupTotal = relatedGroupsBuffer.length;
  1189. });
  1190. }
  1191. result.wordGroups.push(...relatedGroupsBuffer);
  1192. relatedGroupsBuffer = [];
  1193. }
  1194. }
  1195. for (let i = 0; i < lines.length; i++) {
  1196. const line = lines[i];
  1197. const trimmed = line.trim();
  1198. // 收集注释行(在 [WORD_GROUPS] 区域内)
  1199. if (trimmed.startsWith('#') && currentSection === 'groups') {
  1200. pendingComments.push(line);
  1201. continue;
  1202. }
  1203. // 跳过注释(非 [WORD_GROUPS] 区域)
  1204. if (trimmed.startsWith('#')) continue;
  1205. // 空行:结束当前词组和相关组缓存
  1206. if (!trimmed) {
  1207. if (currentGroup) {
  1208. // 保存当前词组到缓存
  1209. relatedGroupsBuffer.push(currentGroup);
  1210. currentGroup = null;
  1211. }
  1212. // 空行表示相关组结束,刷新缓存
  1213. flushRelatedGroups();
  1214. lastLineWasAlias = false;
  1215. // 在 [WORD_GROUPS] 区域内,空行加入待分配注释(保留空行结构)
  1216. if (currentSection === 'groups') {
  1217. pendingComments.push('');
  1218. }
  1219. continue;
  1220. }
  1221. // 检测区域标记
  1222. if (trimmed === '[GLOBAL_FILTER]') {
  1223. currentSection = 'global';
  1224. continue;
  1225. }
  1226. if (trimmed === '[WORD_GROUPS]') {
  1227. currentSection = 'groups';
  1228. continue;
  1229. }
  1230. // 处理内容
  1231. if (currentSection === 'global') {
  1232. result.globalFilter.push(trimmed);
  1233. } else if (currentSection === 'groups') {
  1234. // 检测组别名 [组名]
  1235. const groupNameMatch = trimmed.match(/^\[([^\]]+)\]$/);
  1236. if (groupNameMatch && !['GLOBAL_FILTER', 'WORD_GROUPS'].includes(groupNameMatch[1])) {
  1237. // 保存当前词组到缓存
  1238. if (currentGroup) {
  1239. relatedGroupsBuffer.push(currentGroup);
  1240. }
  1241. // 刷新缓存(组别名独立成组)
  1242. flushRelatedGroups();
  1243. // 创建组别名类型
  1244. currentGroup = {
  1245. type: 'group-name',
  1246. name: groupNameMatch[1],
  1247. keywords: [],
  1248. startLine: i,
  1249. precedingComments: pendingComments.length > 0 ? [...pendingComments] : []
  1250. };
  1251. pendingComments = [];
  1252. lastLineWasAlias = false;
  1253. } else {
  1254. // 检测 => 别名语法(允许右侧为空)
  1255. const aliasMatch = trimmed.match(/^(.+?)\s*=>\s*(.*)$/);
  1256. if (aliasMatch) {
  1257. const keyword = aliasMatch[1].trim();
  1258. const alias = aliasMatch[2].trim();
  1259. // 关键逻辑:如果上一行也是别名行(无空行分隔),则归入连续别名组
  1260. if (lastLineWasAlias && currentGroup && (currentGroup.type === 'alias' || currentGroup.type === 'alias-group')) {
  1261. // 如果当前是单个别名,升级为别名组
  1262. if (currentGroup.type === 'alias') {
  1263. currentGroup.type = 'alias-group';
  1264. }
  1265. // 添加到别名组
  1266. currentGroup.items.push({ keyword, alias });
  1267. } else {
  1268. // 新的单个别名(可能会升级为别名组)
  1269. if (currentGroup) {
  1270. // 保存当前词组到缓存(而不是直接添加到结果)
  1271. relatedGroupsBuffer.push(currentGroup);
  1272. }
  1273. currentGroup = {
  1274. type: 'alias',
  1275. items: [{ keyword, alias }],
  1276. startLine: i,
  1277. precedingComments: pendingComments.length > 0 ? [...pendingComments] : []
  1278. };
  1279. pendingComments = [];
  1280. }
  1281. lastLineWasAlias = true;
  1282. } else {
  1283. // 普通关键词
  1284. if (!currentGroup || currentGroup.type === 'alias' || currentGroup.type === 'alias-group') {
  1285. // 如果当前是别名类型,需要先保存到缓存
  1286. if (currentGroup) {
  1287. relatedGroupsBuffer.push(currentGroup);
  1288. }
  1289. // 创建新的普通词组
  1290. currentGroup = {
  1291. type: 'plain',
  1292. keywords: [],
  1293. startLine: i,
  1294. precedingComments: pendingComments.length > 0 ? [...pendingComments] : []
  1295. };
  1296. pendingComments = [];
  1297. }
  1298. currentGroup.keywords.push(trimmed);
  1299. lastLineWasAlias = false;
  1300. }
  1301. }
  1302. }
  1303. }
  1304. // 添加最后一个组
  1305. if (currentGroup) {
  1306. relatedGroupsBuffer.push(currentGroup);
  1307. }
  1308. flushRelatedGroups();
  1309. return result;
  1310. }
  1311. function buildFrequencyText(data) {
  1312. // 如果有原始文本,尝试保留注释
  1313. if (data.originalText) {
  1314. const lines = data.originalText.split('\n');
  1315. let result = [];
  1316. // 第一步:保留文件头部的注释
  1317. let i = 0;
  1318. while (i < lines.length) {
  1319. const line = lines[i];
  1320. const trimmed = line.trim();
  1321. if (trimmed === '[GLOBAL_FILTER]') {
  1322. break;
  1323. }
  1324. result.push(line);
  1325. i++;
  1326. }
  1327. // 第二步:重建 [GLOBAL_FILTER] 区域
  1328. result.push('[GLOBAL_FILTER]');
  1329. // 保留 [GLOBAL_FILTER] 后面的注释(直到第一个非注释非空行)
  1330. i++;
  1331. while (i < lines.length) {
  1332. const line = lines[i];
  1333. const trimmed = line.trim();
  1334. if (trimmed.startsWith('#') || trimmed === '') {
  1335. result.push(line);
  1336. i++;
  1337. } else {
  1338. break;
  1339. }
  1340. }
  1341. // 添加全局过滤词
  1342. data.globalFilter.forEach(filter => {
  1343. result.push(filter);
  1344. });
  1345. // 跳过原始文件中的 [GLOBAL_FILTER] 内容(非注释行),保留空行和注释直到 [WORD_GROUPS]
  1346. while (i < lines.length) {
  1347. const line = lines[i];
  1348. const trimmed = line.trim();
  1349. if (trimmed === '[WORD_GROUPS]') {
  1350. break;
  1351. }
  1352. // 保留注释和空行
  1353. if (trimmed.startsWith('#') || trimmed === '') {
  1354. result.push(line);
  1355. }
  1356. i++;
  1357. }
  1358. // 第三步:重建 [WORD_GROUPS] 区域
  1359. result.push('[WORD_GROUPS]');
  1360. // 添加词组(注释已保存在每个词组的 precedingComments 中)
  1361. data.wordGroups.forEach((group, index) => {
  1362. // 先输出词组前的注释
  1363. if (group.precedingComments && group.precedingComments.length > 0) {
  1364. group.precedingComments.forEach(comment => {
  1365. result.push(comment);
  1366. });
  1367. }
  1368. if (group.type === 'group-name') {
  1369. // 组别名类型:[组名] + 关键词
  1370. if (group.name) {
  1371. result.push(`[${group.name}]`);
  1372. }
  1373. group.keywords.forEach(kw => {
  1374. result.push(kw);
  1375. });
  1376. } else if (group.type === 'alias' || group.type === 'alias-group') {
  1377. // 别名类型:keyword => alias
  1378. group.items.forEach(item => {
  1379. result.push(`${item.keyword} => ${item.alias}`);
  1380. });
  1381. } else if (group.type === 'plain') {
  1382. // 普通词组
  1383. group.keywords.forEach(kw => {
  1384. result.push(kw);
  1385. });
  1386. }
  1387. // 空行处理逻辑:
  1388. // 1. 如果当前词组和下一个词组都是相关组,则不添加空行
  1389. // 2. 否则,在词组之间添加空行
  1390. const isLastGroup = index === data.wordGroups.length - 1;
  1391. const nextGroup = !isLastGroup ? data.wordGroups[index + 1] : null;
  1392. // 简化判断:只要当前和下一个都是相关组,就不添加空行
  1393. const bothAreRelatedGroups = group.isRelatedGroup && nextGroup && nextGroup.isRelatedGroup;
  1394. // 如果下一个词组有前置注释,不需要额外添加空行(注释中已包含空行)
  1395. const nextHasComments = nextGroup && nextGroup.precedingComments && nextGroup.precedingComments.length > 0;
  1396. if (bothAreRelatedGroups) {
  1397. // 相关组内部不添加空行
  1398. // 不添加任何内容
  1399. } else if (!isLastGroup && !nextHasComments) {
  1400. // 词组之间添加空行(如果下一个没有前置注释)
  1401. result.push('');
  1402. } else if (isLastGroup) {
  1403. // 最后一个词组后也保留一个空行
  1404. result.push('');
  1405. }
  1406. });
  1407. return result.join('\n');
  1408. }
  1409. // 如果没有原始文本,使用默认模板
  1410. let text = '# ═══════════════════════════════════════════════════════════════\n';
  1411. text += '# TrendRadar 频率词配置文件\n';
  1412. text += '# ═══════════════════════════════════════════════════════════════\n\n';
  1413. text += '[GLOBAL_FILTER]\n';
  1414. data.globalFilter.forEach(filter => {
  1415. text += filter + '\n';
  1416. });
  1417. text += '\n\n';
  1418. text += '[WORD_GROUPS]\n\n';
  1419. data.wordGroups.forEach((group, index) => {
  1420. // 先输出词组前的注释
  1421. if (group.precedingComments && group.precedingComments.length > 0) {
  1422. group.precedingComments.forEach(comment => {
  1423. text += comment + '\n';
  1424. });
  1425. }
  1426. if (group.type === 'group-name') {
  1427. if (group.name) {
  1428. text += `[${group.name}]\n`;
  1429. }
  1430. group.keywords.forEach(kw => {
  1431. text += kw + '\n';
  1432. });
  1433. } else if (group.type === 'alias' || group.type === 'alias-group') {
  1434. group.items.forEach(item => {
  1435. text += `${item.keyword} => ${item.alias}\n`;
  1436. });
  1437. } else if (group.type === 'plain') {
  1438. group.keywords.forEach(kw => {
  1439. text += kw + '\n';
  1440. });
  1441. }
  1442. // 空行处理逻辑:与上面保持一致
  1443. const isLastGroup = index === data.wordGroups.length - 1;
  1444. const nextGroup = !isLastGroup ? data.wordGroups[index + 1] : null;
  1445. const bothAreRelatedGroups = group.isRelatedGroup && nextGroup && nextGroup.isRelatedGroup;
  1446. // 如果下一个词组有前置注释,不需要额外添加空行
  1447. const nextHasComments = nextGroup && nextGroup.precedingComments && nextGroup.precedingComments.length > 0;
  1448. if (bothAreRelatedGroups) {
  1449. // 相关组内部不添加空行
  1450. } else if (!isLastGroup && !nextHasComments) {
  1451. text += '\n'; // 词组之间用空行分隔
  1452. } else if (isLastGroup) {
  1453. text += '\n'; // 最后一个词组后也保留一个空行
  1454. }
  1455. });
  1456. return text;
  1457. }
  1458. function syncFrequencyToUI() {
  1459. const data = parseFrequencyText(currentFrequency);
  1460. currentFrequencyData = data;
  1461. renderFrequencyPanel(data);
  1462. }
  1463. function renderFrequencyPanel(data) {
  1464. if (!data) {
  1465. data = parseFrequencyText(currentFrequency);
  1466. }
  1467. const panel = document.getElementById('frequency-panel');
  1468. // 辅助函数:根据关键词类型返回样式类
  1469. function getKeywordClass(keyword) {
  1470. if (keyword.startsWith('+')) return 'bg-green-500';
  1471. if (keyword.startsWith('!')) return 'bg-red-500';
  1472. if (keyword.startsWith('@')) return 'bg-purple-500';
  1473. if (keyword.startsWith('/') || keyword.includes('=>')) return 'bg-indigo-500';
  1474. return 'bg-blue-500';
  1475. }
  1476. // 辅助函数:为关键词添加标签
  1477. function getKeywordLabel(keyword) {
  1478. if (keyword.startsWith('+')) return '必须';
  1479. if (keyword.startsWith('!')) return '排除';
  1480. if (keyword.startsWith('@')) return '限制';
  1481. if (keyword.startsWith('/')) return '正则';
  1482. if (keyword.includes('=>')) return '别名';
  1483. return '';
  1484. }
  1485. // 渲染词组卡片
  1486. function renderGroupCard(group, idx) {
  1487. const jumpIcon = `<i class="fa-solid fa-grip-vertical text-gray-400 text-xs mr-2" title="拖动调整顺序"></i>`;
  1488. // 序号标记
  1489. const indexBadge = `<span class="text-xs bg-gray-700 text-white px-2.5 py-1 rounded-full font-bold mr-2" title="词组序号">#${idx + 1}</span>`;
  1490. // 相关组标记
  1491. const relatedGroupBadge = group.isRelatedGroup
  1492. ? `<span class="text-[10px] bg-gradient-to-r from-blue-500 to-indigo-500 text-white px-2 py-0.5 rounded font-bold ml-2" title="此组与相邻组相关(无空行分隔)">
  1493. <i class="fa-solid fa-link mr-1"></i>相关组 ${group.relatedGroupIndex + 1}/${group.relatedGroupTotal}
  1494. </span>`
  1495. : '';
  1496. // 相关组边框样式
  1497. const relatedGroupStyle = group.isRelatedGroup
  1498. ? 'border-l-4 border-l-blue-500 shadow-lg'
  1499. : '';
  1500. if (group.type === 'group-name') {
  1501. // 组别名类型
  1502. return `
  1503. <div class="word-group-card border-2 border-orange-200 bg-orange-50 group ${relatedGroupStyle} cursor-move" data-group-index="${idx}" onclick="scrollToWordGroupInEditor(${idx})">
  1504. <div class="flex items-center justify-between mb-3">
  1505. <div class="flex items-center flex-1 gap-2">
  1506. ${jumpIcon}
  1507. ${indexBadge}
  1508. <span class="text-[10px] bg-orange-500 text-white px-2 py-0.5 rounded font-bold">组别名</span>
  1509. ${relatedGroupBadge}
  1510. <input type="text" value="${group.name || ''}" placeholder="组别名(如:东亚)"
  1511. class="text-sm font-bold border-0 border-b-2 border-orange-300 focus:border-orange-500 outline-none px-2 py-1 flex-1 bg-transparent"
  1512. onclick="event.stopPropagation()"
  1513. onchange="updateGroupName(${idx}, this.value)">
  1514. </div>
  1515. <button onclick="event.stopPropagation(); removeWordGroup(${idx})" class="text-red-500 hover:text-red-700 text-xs ml-2">
  1516. <i class="fa-solid fa-trash"></i>
  1517. </button>
  1518. </div>
  1519. <div class="bg-white rounded p-3 border border-orange-200 editable-area" onclick="event.stopPropagation()">
  1520. <div class="text-xs text-gray-600 mb-2 font-bold">关键词列表:</div>
  1521. <div class="tag-input-container">
  1522. ${group.keywords.map(kw => {
  1523. const label = getKeywordLabel(kw);
  1524. const escapedKw = kw.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;');
  1525. return `
  1526. <span class="tag-item ${getKeywordClass(kw)} relative break-all cursor-pointer" data-keyword="${escapedKw}" onclick="editKeyword(${idx}, this.dataset.keyword, this)">
  1527. ${label ? `<span class="text-[9px] opacity-75 mr-1">[${label}]</span>` : ''}
  1528. ${escapedKw}
  1529. <button data-keyword="${escapedKw}" onclick="event.stopPropagation(); removeKeyword(${idx}, this.dataset.keyword)">×</button>
  1530. </span>
  1531. `;
  1532. }).join('')}
  1533. <input type="text" class="tag-input" placeholder="输入关键词后按回车..."
  1534. onkeydown="handleKeywordInput(event, ${idx})">
  1535. </div>
  1536. <div class="flex items-center justify-between mt-2">
  1537. <button onclick="openDeepSeekAI('group', ${idx})" class="text-xs text-blue-600 hover:text-blue-700 flex items-center gap-1">
  1538. <i class="fa-solid fa-wand-magic-sparkles"></i>AI 写正则
  1539. </button>
  1540. <div class="text-[10px] text-gray-400">${group.keywords.length} 个关键词</div>
  1541. </div>
  1542. </div>
  1543. </div>
  1544. `;
  1545. } else if (group.type === 'alias') {
  1546. // 单个别名类型
  1547. const item = group.items[0];
  1548. return `
  1549. <div class="word-group-card border-2 border-teal-200 bg-teal-50 group ${relatedGroupStyle} cursor-move" data-group-index="${idx}" onclick="scrollToWordGroupInEditor(${idx})">
  1550. <div class="flex items-center justify-between mb-3">
  1551. <div class="flex items-center flex-1 gap-2">
  1552. ${jumpIcon}
  1553. ${indexBadge}
  1554. <span class="text-[10px] bg-teal-500 text-white px-2 py-0.5 rounded font-bold">单个别名</span>
  1555. ${relatedGroupBadge}
  1556. </div>
  1557. <button onclick="event.stopPropagation(); removeWordGroup(${idx})" class="text-red-500 hover:text-red-700 text-xs">
  1558. <i class="fa-solid fa-trash"></i>
  1559. </button>
  1560. </div>
  1561. <div class="bg-white rounded p-3 border border-teal-200 editable-area" onclick="event.stopPropagation()">
  1562. <div class="flex items-center gap-2">
  1563. <input type="text" value="${item.keyword || ''}" placeholder="/正则/ 或 关键词"
  1564. class="flex-1 px-3 py-2 border border-gray-300 rounded focus:border-teal-500 outline-none text-sm font-mono"
  1565. onblur="updateAliasItem(${idx}, 0, 'keyword', this.value)">
  1566. <span class="text-teal-600 font-bold">=></span>
  1567. <input type="text" value="${item.alias || ''}" placeholder="别名"
  1568. class="flex-1 px-3 py-2 border border-gray-300 rounded focus:border-teal-500 outline-none text-sm"
  1569. onblur="updateAliasItem(${idx}, 0, 'alias', this.value)">
  1570. </div>
  1571. <div class="flex items-center justify-between mt-2">
  1572. <button onclick="openDeepSeekAI('group', ${idx})" class="text-xs text-blue-600 hover:text-blue-700 flex items-center gap-1">
  1573. <i class="fa-solid fa-wand-magic-sparkles"></i>AI 写正则
  1574. </button>
  1575. <div class="text-[10px] text-gray-500">
  1576. <i class="fa-solid fa-lightbulb mr-1"></i>示例:/胖东来|于东来/ => 胖东来
  1577. </div>
  1578. </div>
  1579. </div>
  1580. </div>
  1581. `;
  1582. } else if (group.type === 'alias-group') {
  1583. // 连续别名组类型
  1584. return `
  1585. <div class="word-group-card border-2 border-purple-200 bg-purple-50 group ${relatedGroupStyle} cursor-move" data-group-index="${idx}" onclick="scrollToWordGroupInEditor(${idx})">
  1586. <div class="flex items-center justify-between mb-3">
  1587. <div class="flex items-center flex-1 gap-2">
  1588. ${jumpIcon}
  1589. ${indexBadge}
  1590. <span class="text-[10px] bg-purple-500 text-white px-2 py-0.5 rounded font-bold">连续别名组</span>
  1591. ${relatedGroupBadge}
  1592. </div>
  1593. <button onclick="event.stopPropagation(); removeWordGroup(${idx})" class="text-red-500 hover:text-red-700 text-xs">
  1594. <i class="fa-solid fa-trash"></i>
  1595. </button>
  1596. </div>
  1597. <div class="bg-white rounded p-3 border border-purple-200 space-y-2 editable-area" onclick="event.stopPropagation()">
  1598. <div class="text-xs text-gray-600 mb-2 font-bold">
  1599. 别名列表(无空行分隔):
  1600. </div>
  1601. ${group.items.map((item, itemIdx) => `
  1602. <div class="flex items-center gap-2">
  1603. <input type="text" value="${item.keyword || ''}" placeholder="/正则/ 或 关键词"
  1604. class="flex-1 px-3 py-2 border border-gray-300 rounded focus:border-purple-500 outline-none text-sm font-mono"
  1605. onblur="updateAliasItem(${idx}, ${itemIdx}, 'keyword', this.value)">
  1606. <span class="text-purple-600 font-bold">=></span>
  1607. <input type="text" value="${item.alias || ''}" placeholder="别名"
  1608. class="flex-1 px-3 py-2 border border-gray-300 rounded focus:border-purple-500 outline-none text-sm"
  1609. onblur="updateAliasItem(${idx}, ${itemIdx}, 'alias', this.value)">
  1610. <button onclick="removeAliasItem(${idx}, ${itemIdx})" class="text-red-500 hover:text-red-700 text-xs">
  1611. <i class="fa-solid fa-trash"></i>
  1612. </button>
  1613. </div>
  1614. `).join('')}
  1615. <div class="flex items-center justify-between mt-2">
  1616. <button onclick="openDeepSeekAI('group', ${idx})" class="text-xs text-blue-600 hover:text-blue-700 flex items-center gap-1">
  1617. <i class="fa-solid fa-wand-magic-sparkles"></i>AI 写正则
  1618. </button>
  1619. <div class="text-[10px] text-gray-500">
  1620. <i class="fa-solid fa-info-circle mr-1"></i>这些别名行在配置文件中无空行分隔,属于同一组
  1621. </div>
  1622. </div>
  1623. </div>
  1624. </div>
  1625. `;
  1626. } else if (group.type === 'plain') {
  1627. // 普通词组类型
  1628. return `
  1629. <div class="word-group-card border-2 border-gray-200 bg-gray-50 group ${relatedGroupStyle} cursor-move" data-group-index="${idx}" onclick="scrollToWordGroupInEditor(${idx})">
  1630. <div class="flex items-center justify-between mb-3">
  1631. <div class="flex items-center flex-1 gap-2">
  1632. ${jumpIcon}
  1633. ${indexBadge}
  1634. <span class="text-[10px] bg-gray-500 text-white px-2 py-0.5 rounded font-bold">普通词组</span>
  1635. ${relatedGroupBadge}
  1636. </div>
  1637. <button onclick="event.stopPropagation(); removeWordGroup(${idx})" class="text-red-500 hover:text-red-700 text-xs">
  1638. <i class="fa-solid fa-trash"></i>
  1639. </button>
  1640. </div>
  1641. <div class="bg-white rounded p-3 border border-gray-200 editable-area" onclick="event.stopPropagation()">
  1642. <div class="tag-input-container">
  1643. ${group.keywords.map(kw => {
  1644. const label = getKeywordLabel(kw);
  1645. const escapedKw = kw.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;');
  1646. return `
  1647. <span class="tag-item ${getKeywordClass(kw)} relative break-all cursor-pointer" data-keyword="${escapedKw}" onclick="editKeyword(${idx}, this.dataset.keyword, this)">
  1648. ${label ? `<span class="text-[9px] opacity-75 mr-1">[${label}]</span>` : ''}
  1649. ${escapedKw}
  1650. <button data-keyword="${escapedKw}" onclick="event.stopPropagation(); removeKeyword(${idx}, this.dataset.keyword)">×</button>
  1651. </span>
  1652. `;
  1653. }).join('')}
  1654. <input type="text" class="tag-input" placeholder="输入关键词后按回车..."
  1655. onkeydown="handleKeywordInput(event, ${idx})">
  1656. </div>
  1657. <div class="flex items-center justify-between mt-2">
  1658. <button onclick="openDeepSeekAI('group', ${idx})" class="text-xs text-blue-600 hover:text-blue-700 flex items-center gap-1">
  1659. <i class="fa-solid fa-wand-magic-sparkles"></i>AI 写正则
  1660. </button>
  1661. <div class="text-[10px] text-gray-400">${group.keywords.length} 个关键词</div>
  1662. </div>
  1663. </div>
  1664. </div>
  1665. `;
  1666. }
  1667. return '';
  1668. }
  1669. panel.innerHTML = `
  1670. <!-- 规则说明区域 -->
  1671. <div class="bg-gradient-to-r from-blue-50 to-indigo-50 rounded-lg border border-blue-200 p-4 mb-4">
  1672. <div class="flex items-start gap-3">
  1673. <i class="fa-solid fa-book text-blue-600 text-lg mt-0.5"></i>
  1674. <div class="flex-1">
  1675. <h3 class="text-sm font-bold text-gray-800 mb-2">四种词组类型说明</h3>
  1676. <div class="grid grid-cols-2 gap-3 text-xs">
  1677. <div class="bg-white rounded p-2 border-l-4 border-orange-500">
  1678. <div class="font-bold text-orange-700 mb-1">组别名</div>
  1679. <div class="text-gray-600 font-mono text-[10px] mb-1">[东亚]<br>日本<br>韩国</div>
  1680. <div class="text-gray-500 text-[10px]">多个关键词,统一显示为组名</div>
  1681. </div>
  1682. <div class="bg-white rounded p-2 border-l-4 border-teal-500">
  1683. <div class="font-bold text-teal-700 mb-1">单个别名</div>
  1684. <div class="text-gray-600 font-mono text-[10px] mb-1">/胖东来|于东来/ => 胖东来</div>
  1685. <div class="text-gray-500 text-[10px]">正则匹配,显示为别名</div>
  1686. </div>
  1687. <div class="bg-white rounded p-2 border-l-4 border-purple-500">
  1688. <div class="font-bold text-purple-700 mb-1">连续别名组</div>
  1689. <div class="text-gray-600 font-mono text-[10px] mb-1">/智元|稚晖君/ => 智元<br>/众擎|EngineAI/ => 众擎</div>
  1690. <div class="text-gray-500 text-[10px]">多个别名无空行分隔</div>
  1691. </div>
  1692. <div class="bg-white rounded p-2 border-l-4 border-gray-500">
  1693. <div class="font-bold text-gray-700 mb-1">普通词组</div>
  1694. <div class="text-gray-600 font-mono text-[10px] mb-1">申奥</div>
  1695. <div class="text-gray-500 text-[10px]">普通关键词</div>
  1696. </div>
  1697. </div>
  1698. </div>
  1699. </div>
  1700. </div>
  1701. <!-- Global Filter 区域 -->
  1702. <div class="bg-white rounded-lg border border-gray-200 p-5">
  1703. <div class="flex items-center justify-between mb-3">
  1704. <h3 class="text-sm font-bold text-gray-700">
  1705. <i class="fa-solid fa-filter mr-2"></i>全局过滤词
  1706. </h3>
  1707. <button onclick="openDeepSeekAI('global')" class="text-xs text-blue-600 hover:text-blue-700 flex items-center gap-1">
  1708. <i class="fa-solid fa-wand-magic-sparkles"></i>AI 写正则
  1709. </button>
  1710. </div>
  1711. <div id="global-filter-tags" class="tag-input-container">
  1712. ${data.globalFilter.map(f => `
  1713. <span class="tag-item ${getKeywordClass(f)}">
  1714. ${f}
  1715. <button onclick="removeGlobalFilter('${f.replace(/'/g, "\\'")}')">×</button>
  1716. </span>
  1717. `).join('')}
  1718. <input type="text" class="tag-input" placeholder="输入过滤词后按回车..." onkeydown="handleGlobalFilterInput(event)">
  1719. </div>
  1720. <div class="text-xs text-gray-500 mt-2">
  1721. <i class="fa-solid fa-lightbulb mr-1"></i>提示:支持正则表达式(用 /.../ 包裹)
  1722. </div>
  1723. </div>
  1724. <!-- Word Groups 区域 -->
  1725. <div class="bg-white rounded-lg border border-gray-200 p-5">
  1726. <div class="flex items-center justify-between mb-3">
  1727. <h3 class="text-sm font-bold text-gray-700">
  1728. <i class="fa-solid fa-layer-group mr-2"></i>关键词组 <span class="text-xs text-gray-400 font-normal">(${data.wordGroups.length} 个词组)</span>
  1729. </h3>
  1730. <button onclick="addWordGroup('top')" class="text-xs bg-blue-600 text-white px-3 py-1 rounded hover:bg-blue-700">
  1731. <i class="fa-solid fa-plus mr-1"></i>添加词组
  1732. </button>
  1733. </div>
  1734. <div id="word-groups-container" class="space-y-3">
  1735. ${data.wordGroups.map((group, idx) => {
  1736. const card = renderGroupCard(group, idx);
  1737. // 在每个词组后添加插入区域(最后一个除外)
  1738. if (idx < data.wordGroups.length - 1) {
  1739. return card + `
  1740. <div class="insert-zone group/insert" data-insert-index="${idx + 1}">
  1741. <button onclick="insertWordGroupAt(${idx + 1})" class="insert-button">
  1742. <i class="fa-solid fa-plus"></i>
  1743. </button>
  1744. </div>
  1745. `;
  1746. }
  1747. return card;
  1748. }).join('')}
  1749. </div>
  1750. <!-- 底部添加按钮 -->
  1751. <div class="mt-4 flex justify-center">
  1752. <button onclick="addWordGroup('bottom')" class="text-sm bg-gradient-to-r from-blue-500 to-blue-600 text-white px-6 py-2 rounded-lg hover:from-blue-600 hover:to-blue-700 shadow-sm transition-all flex items-center gap-2">
  1753. <i class="fa-solid fa-plus-circle"></i>
  1754. <span>在底部添加词组</span>
  1755. </button>
  1756. </div>
  1757. </div>
  1758. `;
  1759. // 初始化拖拽排序功能
  1760. setTimeout(() => {
  1761. const container = document.getElementById('word-groups-container');
  1762. if (container && typeof Sortable !== 'undefined') {
  1763. // 销毁之前的实例(如果存在)
  1764. if (container.sortableInstance) {
  1765. container.sortableInstance.destroy();
  1766. }
  1767. // 创建新的 Sortable 实例
  1768. container.sortableInstance = new Sortable(container, {
  1769. animation: 150,
  1770. filter: '.editable-area, input, button, select, textarea', // 排除编辑区域
  1771. preventOnFilter: false, // 允许在过滤区域正常交互
  1772. ghostClass: 'sortable-ghost',
  1773. chosenClass: 'sortable-chosen',
  1774. dragClass: 'sortable-drag',
  1775. onEnd: function(evt) {
  1776. // 获取所有词组卡片的当前顺序
  1777. const cards = Array.from(container.querySelectorAll('.word-group-card'));
  1778. const newOrder = cards.map(card => parseInt(card.getAttribute('data-group-index')));
  1779. // 检查顺序是否改变
  1780. const data = currentFrequencyData || parseFrequencyText(currentFrequency);
  1781. const oldOrder = data.wordGroups.map((_, idx) => idx);
  1782. if (JSON.stringify(newOrder) !== JSON.stringify(oldOrder)) {
  1783. // 根据新顺序重新排列数据
  1784. const reorderedGroups = newOrder.map(idx => data.wordGroups[idx]);
  1785. data.wordGroups = reorderedGroups;
  1786. // 重新构建文本
  1787. currentFrequency = buildFrequencyText(data);
  1788. currentFrequencyData = parseFrequencyText(currentFrequency);
  1789. document.getElementById('frequency-editor').value = currentFrequency;
  1790. updateBackdrop('frequency-editor', 'frequency-backdrop');
  1791. // 重新渲染
  1792. renderFrequencyPanel(currentFrequencyData);
  1793. }
  1794. }
  1795. });
  1796. }
  1797. }, 0);
  1798. }
  1799. // Global Filter 操作
  1800. window.handleGlobalFilterInput = function(event) {
  1801. if (event.key === 'Enter' && event.target.value.trim()) {
  1802. const data = currentFrequencyData || parseFrequencyText(currentFrequency);
  1803. data.globalFilter.push(event.target.value.trim());
  1804. currentFrequency = buildFrequencyText(data);
  1805. currentFrequencyData = data;
  1806. document.getElementById('frequency-editor').value = currentFrequency;
  1807. updateBackdrop('frequency-editor', 'frequency-backdrop');
  1808. renderFrequencyPanel(data);
  1809. }
  1810. }
  1811. window.removeGlobalFilter = function(filter) {
  1812. const data = currentFrequencyData || parseFrequencyText(currentFrequency);
  1813. data.globalFilter = data.globalFilter.filter(f => f !== filter);
  1814. currentFrequency = buildFrequencyText(data);
  1815. currentFrequencyData = data;
  1816. document.getElementById('frequency-editor').value = currentFrequency;
  1817. updateBackdrop('frequency-editor', 'frequency-backdrop');
  1818. renderFrequencyPanel(data);
  1819. }
  1820. // Word Groups 操作
  1821. let pendingWordGroupPosition = 'top'; // 记录添加位置:'top', 'bottom', 或数字索引
  1822. window.addWordGroup = function(position = 'top') {
  1823. pendingWordGroupPosition = position;
  1824. document.getElementById('wordgroup-type-modal').classList.remove('hidden');
  1825. }
  1826. // 在指定位置插入词组
  1827. window.insertWordGroupAt = function(index) {
  1828. pendingWordGroupPosition = index; // 记录插入位置(数字索引)
  1829. document.getElementById('wordgroup-type-modal').classList.remove('hidden');
  1830. }
  1831. window.closeWordGroupTypeModal = function() {
  1832. document.getElementById('wordgroup-type-modal').classList.add('hidden');
  1833. }
  1834. window.confirmAddWordGroup = function(type) {
  1835. const data = currentFrequencyData || parseFrequencyText(currentFrequency);
  1836. let newGroup;
  1837. if (type === 'group') {
  1838. // 组别名类型
  1839. newGroup = { type: 'group-name', name: '', keywords: [] };
  1840. } else if (type === 'alias') {
  1841. // 单个别名类型
  1842. newGroup = { type: 'alias', items: [{ keyword: '', alias: '' }] };
  1843. } else if (type === 'multi-alias') {
  1844. // 连续别名类型(多个别名行)
  1845. newGroup = { type: 'alias-group', items: [{ keyword: '', alias: '' }, { keyword: '', alias: '' }] };
  1846. } else if (type === 'plain') {
  1847. // 普通词组类型
  1848. newGroup = { type: 'plain', keywords: [] };
  1849. }
  1850. // 根据位置插入
  1851. if (pendingWordGroupPosition === 'bottom') {
  1852. data.wordGroups.push(newGroup);
  1853. } else if (pendingWordGroupPosition === 'top') {
  1854. data.wordGroups.unshift(newGroup);
  1855. } else if (typeof pendingWordGroupPosition === 'number') {
  1856. // 在指定索引位置插入
  1857. data.wordGroups.splice(pendingWordGroupPosition, 0, newGroup);
  1858. }
  1859. currentFrequency = buildFrequencyText(data);
  1860. currentFrequencyData = data;
  1861. document.getElementById('frequency-editor').value = currentFrequency;
  1862. updateBackdrop('frequency-editor', 'frequency-backdrop');
  1863. renderFrequencyPanel(data);
  1864. closeWordGroupTypeModal();
  1865. // 滚动到新添加的词组
  1866. setTimeout(() => {
  1867. const container = document.getElementById('word-groups-container');
  1868. if (pendingWordGroupPosition === 'bottom') {
  1869. container.scrollTop = container.scrollHeight;
  1870. } else if (pendingWordGroupPosition === 'top') {
  1871. container.scrollTop = 0;
  1872. } else if (typeof pendingWordGroupPosition === 'number') {
  1873. // 滚动到插入的位置
  1874. const cards = container.querySelectorAll('.word-group-card');
  1875. if (cards[pendingWordGroupPosition]) {
  1876. cards[pendingWordGroupPosition].scrollIntoView({ behavior: 'smooth', block: 'center' });
  1877. }
  1878. }
  1879. }, 100);
  1880. }
  1881. window.removeWordGroup = function(index) {
  1882. const data = currentFrequencyData || parseFrequencyText(currentFrequency);
  1883. data.wordGroups.splice(index, 1);
  1884. currentFrequency = buildFrequencyText(data);
  1885. // 重新解析以更新相关组信息
  1886. currentFrequencyData = parseFrequencyText(currentFrequency);
  1887. document.getElementById('frequency-editor').value = currentFrequency;
  1888. updateBackdrop('frequency-editor', 'frequency-backdrop');
  1889. renderFrequencyPanel(currentFrequencyData);
  1890. }
  1891. window.updateGroupName = function(index, name) {
  1892. const data = currentFrequencyData || parseFrequencyText(currentFrequency);
  1893. const group = data.wordGroups[index];
  1894. // 只有 group-name 类型才有 name 字段
  1895. if (group.type === 'group-name') {
  1896. group.name = name;
  1897. }
  1898. currentFrequency = buildFrequencyText(data);
  1899. // 重新解析以更新相关组信息
  1900. currentFrequencyData = parseFrequencyText(currentFrequency);
  1901. document.getElementById('frequency-editor').value = currentFrequency;
  1902. updateBackdrop('frequency-editor', 'frequency-backdrop');
  1903. renderFrequencyPanel(currentFrequencyData);
  1904. }
  1905. window.editKeyword = function(groupIndex, oldKeyword, spanElement) {
  1906. const data = currentFrequencyData || parseFrequencyText(currentFrequency);
  1907. const group = data.wordGroups[groupIndex];
  1908. // 只有 group-name 和 plain 类型才有 keywords 字段
  1909. if (group.type !== 'group-name' && group.type !== 'plain') {
  1910. return;
  1911. }
  1912. const originalKeyword = group.keywords.find(kw => kw === oldKeyword) || oldKeyword;
  1913. const input = document.createElement('input');
  1914. input.type = 'text';
  1915. input.value = originalKeyword;
  1916. input.className = 'tag-input inline-block px-2 py-1 text-xs border border-blue-500 rounded';
  1917. input.style.minWidth = '100px';
  1918. const saveEdit = () => {
  1919. const newKeyword = input.value.trim();
  1920. if (newKeyword && newKeyword !== originalKeyword) {
  1921. const kwIndex = group.keywords.indexOf(originalKeyword);
  1922. if (kwIndex !== -1) {
  1923. group.keywords[kwIndex] = newKeyword;
  1924. }
  1925. currentFrequency = buildFrequencyText(data);
  1926. // 重新解析以更新相关组信息
  1927. currentFrequencyData = parseFrequencyText(currentFrequency);
  1928. document.getElementById('frequency-editor').value = currentFrequency;
  1929. updateBackdrop('frequency-editor', 'frequency-backdrop');
  1930. renderFrequencyPanel(currentFrequencyData);
  1931. } else {
  1932. spanElement.style.display = '';
  1933. input.remove();
  1934. }
  1935. };
  1936. input.onblur = saveEdit;
  1937. input.onkeydown = (e) => {
  1938. if (e.key === 'Enter') {
  1939. saveEdit();
  1940. } else if (e.key === 'Escape') {
  1941. spanElement.style.display = '';
  1942. input.remove();
  1943. }
  1944. };
  1945. spanElement.style.display = 'none';
  1946. spanElement.parentNode.insertBefore(input, spanElement);
  1947. input.focus();
  1948. input.select();
  1949. }
  1950. window.handleKeywordInput = function(event, groupIndex) {
  1951. if (event.key === 'Enter' && event.target.value.trim()) {
  1952. const data = currentFrequencyData || parseFrequencyText(currentFrequency);
  1953. const group = data.wordGroups[groupIndex];
  1954. // 只有 group-name 和 plain 类型才能添加关键词
  1955. if (group.type === 'group-name' || group.type === 'plain') {
  1956. group.keywords.push(event.target.value.trim());
  1957. event.target.value = '';
  1958. currentFrequency = buildFrequencyText(data);
  1959. // 重新解析以更新相关组信息
  1960. currentFrequencyData = parseFrequencyText(currentFrequency);
  1961. document.getElementById('frequency-editor').value = currentFrequency;
  1962. updateBackdrop('frequency-editor', 'frequency-backdrop');
  1963. renderFrequencyPanel(currentFrequencyData);
  1964. }
  1965. }
  1966. }
  1967. window.removeKeyword = function(groupIndex, keyword) {
  1968. const data = currentFrequencyData || parseFrequencyText(currentFrequency);
  1969. const group = data.wordGroups[groupIndex];
  1970. // 只有 group-name 和 plain 类型才能删除关键词
  1971. if (group.type === 'group-name' || group.type === 'plain') {
  1972. group.keywords = group.keywords.filter(k => k !== keyword);
  1973. // 如果词组变空,删除整个词组
  1974. if (group.keywords.length === 0) {
  1975. data.wordGroups.splice(groupIndex, 1);
  1976. }
  1977. currentFrequency = buildFrequencyText(data);
  1978. // 重新解析以更新相关组信息
  1979. currentFrequencyData = parseFrequencyText(currentFrequency);
  1980. document.getElementById('frequency-editor').value = currentFrequency;
  1981. updateBackdrop('frequency-editor', 'frequency-backdrop');
  1982. renderFrequencyPanel(currentFrequencyData);
  1983. }
  1984. }
  1985. // 更新别名项
  1986. window.updateAliasItem = function(groupIndex, itemIndex, field, value) {
  1987. const data = currentFrequencyData || parseFrequencyText(currentFrequency);
  1988. const group = data.wordGroups[groupIndex];
  1989. // 只有 alias 和 alias-group 类型才有 items 字段
  1990. if (group.type === 'alias' || group.type === 'alias-group') {
  1991. if (group.items[itemIndex]) {
  1992. group.items[itemIndex][field] = value;
  1993. currentFrequency = buildFrequencyText(data);
  1994. currentFrequencyData = parseFrequencyText(currentFrequency);
  1995. document.getElementById('frequency-editor').value = currentFrequency;
  1996. updateBackdrop('frequency-editor', 'frequency-backdrop');
  1997. renderFrequencyPanel(currentFrequencyData);
  1998. }
  1999. }
  2000. }
  2001. // 添加别名项
  2002. window.addAliasItem = function(groupIndex) {
  2003. const data = currentFrequencyData || parseFrequencyText(currentFrequency);
  2004. const group = data.wordGroups[groupIndex];
  2005. // 只有 alias-group 类型才能添加别名项
  2006. if (group.type === 'alias-group') {
  2007. group.items.push({ keyword: '', alias: '' });
  2008. currentFrequency = buildFrequencyText(data);
  2009. // 重新解析以更新相关组信息
  2010. currentFrequencyData = parseFrequencyText(currentFrequency);
  2011. document.getElementById('frequency-editor').value = currentFrequency;
  2012. updateBackdrop('frequency-editor', 'frequency-backdrop');
  2013. renderFrequencyPanel(currentFrequencyData);
  2014. } else if (group.type === 'alias') {
  2015. // 如果是单个别名,升级为别名组
  2016. group.type = 'alias-group';
  2017. group.items.push({ keyword: '', alias: '' });
  2018. currentFrequency = buildFrequencyText(data);
  2019. // 重新解析以更新相关组信息
  2020. currentFrequencyData = parseFrequencyText(currentFrequency);
  2021. document.getElementById('frequency-editor').value = currentFrequency;
  2022. updateBackdrop('frequency-editor', 'frequency-backdrop');
  2023. renderFrequencyPanel(currentFrequencyData);
  2024. }
  2025. }
  2026. // 删除别名项
  2027. window.removeAliasItem = function(groupIndex, itemIndex) {
  2028. const data = currentFrequencyData || parseFrequencyText(currentFrequency);
  2029. const group = data.wordGroups[groupIndex];
  2030. // 只有 alias-group 类型才能删除别名项
  2031. if (group.type === 'alias-group') {
  2032. group.items.splice(itemIndex, 1);
  2033. // 如果没有别名项了,删除整个词组
  2034. if (group.items.length === 0) {
  2035. data.wordGroups.splice(groupIndex, 1);
  2036. }
  2037. // 如果只剩一个别名项,降级为单个别名
  2038. else if (group.items.length === 1) {
  2039. group.type = 'alias';
  2040. }
  2041. currentFrequency = buildFrequencyText(data);
  2042. currentFrequencyData = parseFrequencyText(currentFrequency);
  2043. document.getElementById('frequency-editor').value = currentFrequency;
  2044. updateBackdrop('frequency-editor', 'frequency-backdrop');
  2045. renderFrequencyPanel(currentFrequencyData);
  2046. }
  2047. }
  2048. // DeepSeek AI 辅助
  2049. window.openDeepSeekAI = function(type, groupIndex) {
  2050. const userInput = window.prompt('请输入核心关键词(例如:华为):');
  2051. if (!userInput) return;
  2052. const promptText = `我正在配置一个新闻聚合系统,需要通过 Python 正则表达式 抓取关于【${userInput}】的新闻。
  2053. 请帮我完成以下步骤,并最终只输出一个正则表达式字符串:
  2054. 第一步:【精准关键词筛选】
  2055. 请列出与【${userInput}】强绑定的核心词汇:
  2056. 1. 核心品牌:包括中文全称、简称、股票代码、别名。
  2057. 2. 核心人物:仅限最高决策层或极具代表性的创始人。
  2058. 3. 独家产品:必须是具有极高辨识度的独家产品名。
  2059. 4. 核心工作室/子品牌:强相关的下属机构。
  2060. 第二步:【严格清洗与过滤】(请严格执行)
  2061. 1. 包含关系去重(最短匹配原则):
  2062. - 中文:如果列表里已经有了核心短词(如“腾讯”),请删除所有包含该短词的长词(如“腾讯云”、“腾讯视频”统统不要,因为它们会被短词命中)。
  2063. - 英文:如果有了 \\bKeyword\\b,就不要再出现 Keyword。
  2064. 2. 彻底排除无关公司:
  2065. - 绝对不要包含:该品牌的竞争对手、合作伙伴(如京东、美团、字节跳动等非隶属公司)。
  2066. 3. 彻底排除通用黑话:
  2067. - 绝对不要包含:行业通用词(如“互联网”、“大厂”、“新质生产力”、“人工智能”、“元宇宙”、“金融科技”等)。
  2068. 第三步:【构建 Python 正则】
  2069. 将清洗后的词汇合并,格式要求如下:
  2070. 1. 英文处理:所有英文单词必须前后加 \\b(例如 \\bWord\\b),严禁出现没有边界符的英文单词。
  2071. 2. 连接符:用 | 连接。
  2072. 最终输出示例格式:
  2073. /词A|词B|\\bEnglishWord\\b/ => ${userInput}
  2074. 输出要求:
  2075. - 只要这一行正则表达式,不要任何解释,不要代码块。`;
  2076. const textArea = document.createElement("textarea");
  2077. textArea.value = promptText;
  2078. textArea.style.position = "fixed";
  2079. textArea.style.left = "-9999px";
  2080. textArea.style.top = "0";
  2081. document.body.appendChild(textArea);
  2082. textArea.focus();
  2083. textArea.select();
  2084. let copySuccess = false;
  2085. try {
  2086. copySuccess = document.execCommand('copy');
  2087. } catch (err) {
  2088. console.error('复制失败:', err);
  2089. }
  2090. document.body.removeChild(textArea);
  2091. if (copySuccess) {
  2092. if (confirm(`提示词已复制到剪贴板!\n\n关键词:${userInput}\n\n点击【确定】跳转 DeepSeek 官网,直接粘贴 (Ctrl+V) 即可。`)) {
  2093. window.open('https://chat.deepseek.com/', '_blank');
  2094. }
  2095. } else {
  2096. prompt('自动复制失败,请手动复制以下内容,然后自行打开 DeepSeek:', promptText);
  2097. window.open('https://chat.deepseek.com/', '_blank');
  2098. }
  2099. }
  2100. // ==========================================
  2101. // 10. 平台管理功能
  2102. // ==========================================
  2103. // 解析当前配置中的平台列表
  2104. function parsePlatformsFromYaml() {
  2105. try {
  2106. const doc = jsyaml.load(currentYaml);
  2107. if (doc && doc.platforms && doc.platforms.sources) {
  2108. return doc.platforms.sources;
  2109. }
  2110. } catch (e) {}
  2111. return [];
  2112. }
  2113. // 渲染平台列表
  2114. function renderPlatformsList() {
  2115. const container = document.getElementById('platforms-list');
  2116. if (!container) return;
  2117. const platforms = parsePlatformsFromYaml();
  2118. if (platforms.length === 0) {
  2119. container.innerHTML = `<div class="text-xs text-gray-400 italic">暂无平台,请添加</div>`;
  2120. return;
  2121. }
  2122. container.innerHTML = platforms.map((p, idx) => `
  2123. <div class="platform-item flex items-center justify-between bg-gray-50 rounded-lg px-3 py-2 border border-gray-200 hover:border-blue-300 transition-colors" data-index="${idx}">
  2124. <div class="flex items-center gap-2">
  2125. <i class="fa-solid fa-grip-vertical text-gray-300 cursor-move"></i>
  2126. <span class="text-xs font-medium text-gray-700">${p.name}</span>
  2127. <span class="text-[10px] text-gray-400">(${p.id})</span>
  2128. </div>
  2129. <button onclick="removePlatform(${idx})" class="text-red-400 hover:text-red-600 text-xs" title="删除">
  2130. <i class="fa-solid fa-trash"></i>
  2131. </button>
  2132. </div>
  2133. `).join('');
  2134. // 初始化拖拽排序
  2135. if (typeof Sortable !== 'undefined') {
  2136. new Sortable(container, {
  2137. animation: 150,
  2138. handle: '.fa-grip-vertical',
  2139. onEnd: function(evt) {
  2140. reorderPlatforms(evt.oldIndex, evt.newIndex);
  2141. }
  2142. });
  2143. }
  2144. }
  2145. // 删除平台
  2146. window.removePlatform = function(index) {
  2147. const platforms = parsePlatformsFromYaml();
  2148. if (index < 0 || index >= platforms.length) return;
  2149. const platformName = platforms[index].name;
  2150. if (!confirm(`确定要删除平台 "${platformName}" 吗?`)) return;
  2151. platforms.splice(index, 1);
  2152. updatePlatformsInYaml(platforms);
  2153. }
  2154. // 重新排序平台
  2155. function reorderPlatforms(oldIndex, newIndex) {
  2156. const platforms = parsePlatformsFromYaml();
  2157. const [removed] = platforms.splice(oldIndex, 1);
  2158. platforms.splice(newIndex, 0, removed);
  2159. updatePlatformsInYaml(platforms);
  2160. }
  2161. // 更新 YAML 中的平台配置(保留注释)
  2162. function updatePlatformsInYaml(platforms) {
  2163. const editor = document.getElementById('yaml-editor');
  2164. let yaml = editor.value;
  2165. const lines = yaml.split('\n');
  2166. // 找到 platforms.sources 的位置
  2167. let sourcesStart = -1;
  2168. let sourcesEnd = -1;
  2169. let inPlatforms = false;
  2170. let inSources = false;
  2171. let baseIndent = 0;
  2172. let lastDataLineIndex = -1; // 记录最后一个数据行的位置
  2173. for (let i = 0; i < lines.length; i++) {
  2174. const line = lines[i];
  2175. const trimmed = line.trim();
  2176. if (line.match(/^platforms:/)) {
  2177. inPlatforms = true;
  2178. continue;
  2179. }
  2180. if (inPlatforms && !inSources && trimmed.startsWith('sources:')) {
  2181. sourcesStart = i + 1;
  2182. inSources = true;
  2183. baseIndent = line.search(/\S/) + 2; // sources 下一级的缩进
  2184. continue;
  2185. }
  2186. if (inSources) {
  2187. const currentIndent = line.search(/\S/);
  2188. // 如果是数据行(以 - 开头或是数据项的属性)
  2189. if (trimmed.startsWith('-')) {
  2190. lastDataLineIndex = i;
  2191. } else if (trimmed && !trimmed.startsWith('#') && currentIndent >= baseIndent) {
  2192. // 数据项的属性行(如 name:, id:)
  2193. lastDataLineIndex = i;
  2194. } else if (trimmed && !trimmed.startsWith('#') && currentIndent < baseIndent) {
  2195. // 遇到缩进更小的非注释行,说明离开了 sources 区域
  2196. sourcesEnd = lastDataLineIndex + 1;
  2197. break;
  2198. }
  2199. }
  2200. // 检查是否进入下一个顶级模块
  2201. if (inPlatforms && line.match(/^[a-z_]+:/) && !line.match(/^platforms:/)) {
  2202. if (lastDataLineIndex >= 0) {
  2203. sourcesEnd = lastDataLineIndex + 1;
  2204. } else {
  2205. sourcesEnd = i;
  2206. }
  2207. break;
  2208. }
  2209. }
  2210. // 如果没有找到结束位置,使用最后一个数据行的下一行
  2211. if (sourcesEnd === -1) {
  2212. sourcesEnd = lastDataLineIndex >= 0 ? lastDataLineIndex + 1 : lines.length;
  2213. }
  2214. // 提取区域内的注释(保留在开头的注释)
  2215. const regionLines = lines.slice(sourcesStart, sourcesEnd);
  2216. const leadingComments = [];
  2217. for (const line of regionLines) {
  2218. const trimmed = line.trim();
  2219. if (trimmed.startsWith('#')) {
  2220. leadingComments.push(line);
  2221. } else if (trimmed.startsWith('-') || (trimmed && !trimmed.startsWith('#'))) {
  2222. // 遇到第一个数据项,停止收集注释
  2223. break;
  2224. } else if (trimmed === '') {
  2225. // 空行也保留
  2226. leadingComments.push(line);
  2227. }
  2228. }
  2229. const indent = ' '; // 4 空格缩进
  2230. const newSourcesLines = platforms.map(p =>
  2231. `${indent}- id: "${p.id}"\n${indent} name: "${p.name}"`
  2232. ).join('\n');
  2233. const beforeSources = lines.slice(0, sourcesStart);
  2234. const afterSources = lines.slice(sourcesEnd);
  2235. // 组合:前面内容 + 开头注释 + 新数据 + 后面内容
  2236. const newYaml = [
  2237. ...beforeSources,
  2238. ...(leadingComments.length > 0 ? leadingComments : []),
  2239. newSourcesLines,
  2240. ...afterSources
  2241. ].join('\n');
  2242. editor.value = newYaml;
  2243. currentYaml = newYaml;
  2244. updateBackdrop('yaml-editor', 'yaml-backdrop');
  2245. debounceSaveConfig();
  2246. renderPlatformsList();
  2247. renderStandaloneLists(); // 同步更新独立展示区的平台选择列表
  2248. }
  2249. // ==========================================
  2250. // 12. Display Regions 排序与管理功能
  2251. // ==========================================
  2252. const DISPLAY_REGIONS_DEF = [
  2253. { key: "hotlist", label: "热榜区域" },
  2254. { key: "new_items", label: "新增热点区域" },
  2255. { key: "rss", label: "RSS 订阅区域" },
  2256. { key: "standalone", label: "独立展示区" },
  2257. { key: "ai_analysis", label: "AI 分析区域" }
  2258. ];
  2259. // 从 YAML 解析 display.regions,严格按照 region_order 定义顺序
  2260. function parseDisplayRegionsFromYaml() {
  2261. try {
  2262. const doc = jsyaml.load(currentYaml);
  2263. if (doc && doc.display) {
  2264. const regionOrder = doc.display.region_order || [];
  2265. const regionStates = doc.display.regions || {};
  2266. // 严格按 region_order 顺序构建列表
  2267. if (regionOrder.length > 0) {
  2268. return regionOrder.map(key => {
  2269. const normalizedKey = key === 'new_item' ? 'new_items' : key;
  2270. const def = DISPLAY_REGIONS_DEF.find(d => d.key === normalizedKey);
  2271. return {
  2272. key: normalizedKey,
  2273. label: def ? def.label : normalizedKey,
  2274. enabled: regionStates[normalizedKey] !== undefined ? regionStates[normalizedKey] : false
  2275. };
  2276. });
  2277. }
  2278. // 后备方案:如果没有 region_order,使用 regions 对象的顺序
  2279. const regions = [];
  2280. for (const key in regionStates) {
  2281. const normalizedKey = key === 'new_item' ? 'new_items' : key;
  2282. const def = DISPLAY_REGIONS_DEF.find(d => d.key === normalizedKey);
  2283. if (def) {
  2284. regions.push({
  2285. key: normalizedKey,
  2286. label: def.label,
  2287. enabled: regionStates[key]
  2288. });
  2289. }
  2290. }
  2291. return regions;
  2292. }
  2293. } catch (e) {}
  2294. // 默认返回所有区域(禁用状态)
  2295. return DISPLAY_REGIONS_DEF.map(def => ({
  2296. key: def.key,
  2297. label: def.label,
  2298. enabled: false
  2299. }));
  2300. }
  2301. // 渲染 Display Regions 列表
  2302. function renderDisplayRegionsList() {
  2303. const container = document.getElementById('display-regions-list');
  2304. if (!container) return;
  2305. const regions = parseDisplayRegionsFromYaml();
  2306. container.innerHTML = regions.map((r, idx) => `
  2307. <div class="display-region-item flex items-center justify-between bg-gray-50 rounded-lg px-3 py-2 border border-gray-200 hover:border-blue-300 transition-colors" data-key="${r.key}">
  2308. <div class="flex items-center gap-2">
  2309. <i class="fa-solid fa-grip-vertical text-gray-300 cursor-move"></i>
  2310. <span class="text-xs font-medium ${r.enabled ? 'text-gray-700' : 'text-gray-400'}">${r.label}</span>
  2311. <span class="text-[10px] text-gray-400">(${r.key})</span>
  2312. </div>
  2313. <div class="relative inline-block w-10 align-middle select-none">
  2314. <input type="checkbox" id="toggle-region-${r.key}"
  2315. ${r.enabled ? 'checked' : ''}
  2316. onchange="toggleDisplayRegion('${r.key}')"
  2317. class="toggle-checkbox absolute block w-4 h-4 mt-0.5 ml-0.5 rounded-full bg-white border-4 appearance-none cursor-pointer transition-all duration-200 ease-in-out"/>
  2318. <label for="toggle-region-${r.key}" class="toggle-label block overflow-hidden h-5 rounded-full bg-gray-300 cursor-pointer"></label>
  2319. </div>
  2320. </div>
  2321. `).join('');
  2322. // 初始化拖拽排序
  2323. if (typeof Sortable !== 'undefined') {
  2324. new Sortable(container, {
  2325. animation: 150,
  2326. handle: '.fa-grip-vertical',
  2327. onEnd: function(evt) {
  2328. reorderDisplayRegions();
  2329. }
  2330. });
  2331. }
  2332. }
  2333. // 切换区域启用状态
  2334. window.toggleDisplayRegion = function(key) {
  2335. const regions = parseDisplayRegionsFromYaml();
  2336. const target = regions.find(r => r.key === key);
  2337. if (target) {
  2338. target.enabled = !target.enabled;
  2339. updateDisplayRegionsInYaml(regions);
  2340. }
  2341. }
  2342. // 重新排序区域
  2343. window.reorderDisplayRegions = function() {
  2344. const container = document.getElementById('display-regions-list');
  2345. const items = container.querySelectorAll('.display-region-item');
  2346. const newOrderKeys = Array.from(items).map(item => item.dataset.key);
  2347. const currentRegions = parseDisplayRegionsFromYaml();
  2348. const newRegions = newOrderKeys.map(key => {
  2349. return currentRegions.find(r => r.key === key);
  2350. }).filter(r => r); // 过滤掉可能的 undefined
  2351. updateDisplayRegionsInYaml(newRegions);
  2352. }
  2353. // 更新 YAML 中的 display.regions 和 display.region_order
  2354. function updateDisplayRegionsInYaml(regions) {
  2355. const editor = document.getElementById('yaml-editor');
  2356. let yaml = editor.value;
  2357. const lines = yaml.split('\n');
  2358. let regionOrderStart = -1;
  2359. let regionOrderEnd = -1;
  2360. let regionsStart = -1;
  2361. let regionsEnd = -1;
  2362. let inDisplay = false;
  2363. let regionOrderIndent = 0;
  2364. let regionsIndent = 0;
  2365. for (let i = 0; i < lines.length; i++) {
  2366. const line = lines[i];
  2367. const trimmed = line.trim();
  2368. if (line.match(/^display:/)) {
  2369. inDisplay = true;
  2370. continue;
  2371. }
  2372. if (!inDisplay) continue;
  2373. // 查找 region_order 数组
  2374. if (trimmed.startsWith('region_order:')) {
  2375. regionOrderStart = i + 1;
  2376. regionOrderIndent = line.search(/\S/) + 2;
  2377. // 找到 region_order 的结束位置
  2378. for (let j = i + 1; j < lines.length; j++) {
  2379. const nextLine = lines[j];
  2380. const nextTrimmed = nextLine.trim();
  2381. if (nextTrimmed && !nextTrimmed.startsWith('#') && !nextTrimmed.startsWith('-')) {
  2382. const nextIndent = nextLine.search(/\S/);
  2383. if (nextIndent < regionOrderIndent) {
  2384. regionOrderEnd = j;
  2385. break;
  2386. }
  2387. }
  2388. }
  2389. if (regionOrderEnd === -1) regionOrderEnd = lines.length;
  2390. continue;
  2391. }
  2392. // 查找 regions 对象
  2393. if (trimmed.startsWith('regions:')) {
  2394. regionsStart = i + 1;
  2395. regionsIndent = line.search(/\S/) + 2;
  2396. // 找到 regions 的结束位置(遇到同级或更高级的键)
  2397. for (let j = i + 1; j < lines.length; j++) {
  2398. const nextLine = lines[j];
  2399. const nextTrimmed = nextLine.trim();
  2400. if (nextTrimmed && !nextTrimmed.startsWith('#')) {
  2401. const nextIndent = nextLine.search(/\S/);
  2402. // 检查是否是同级或更高级的键(如 standalone:)
  2403. if (nextIndent <= line.search(/\S/)) {
  2404. regionsEnd = j;
  2405. break;
  2406. }
  2407. }
  2408. }
  2409. if (regionsEnd === -1) regionsEnd = lines.length;
  2410. break;
  2411. }
  2412. // 检查是否离开 display 模块
  2413. if (line.match(/^[a-z_]+:/) && !line.match(/^display:/)) {
  2414. break;
  2415. }
  2416. }
  2417. // 更新 region_order 数组(保留注释)
  2418. if (regionOrderStart > 0 && regionOrderEnd > regionOrderStart) {
  2419. const indentStr = ' '.repeat(regionOrderIndent);
  2420. // 提取原有行的注释映射
  2421. const originalRegionOrderBlock = lines.slice(regionOrderStart, regionOrderEnd);
  2422. const commentMap = {};
  2423. originalRegionOrderBlock.forEach(line => {
  2424. // 匹配 "- key # 注释" 格式
  2425. const match = line.match(/^\s*-\s*([a-z_]+)\s*(#.*)?$/);
  2426. if (match) {
  2427. const key = match[1];
  2428. const comment = match[2] || '';
  2429. if (key) commentMap[key] = comment;
  2430. }
  2431. });
  2432. // 生成新的行,保留注释
  2433. const newRegionOrderLines = regions.map(r => {
  2434. const comment = commentMap[r.key] || '';
  2435. return `${indentStr}- ${r.key}${comment ? ' ' + comment : ''}`;
  2436. });
  2437. lines.splice(regionOrderStart, regionOrderEnd - regionOrderStart, ...newRegionOrderLines);
  2438. // 调整 regionsStart 和 regionsEnd
  2439. const lineDiff = newRegionOrderLines.length - (regionOrderEnd - regionOrderStart);
  2440. if (regionsStart > regionOrderEnd) {
  2441. regionsStart += lineDiff;
  2442. regionsEnd += lineDiff;
  2443. }
  2444. }
  2445. // 更新 regions 对象
  2446. if (regionsStart > 0 && regionsEnd > regionsStart) {
  2447. const originalRegionsBlock = lines.slice(regionsStart, regionsEnd);
  2448. const commentMap = {};
  2449. originalRegionsBlock.forEach(line => {
  2450. const match = line.match(/^\s*([a-z_]+):\s*[^#]*(#.*)?$/);
  2451. if (match) {
  2452. const key = match[1];
  2453. const comment = match[2] || '';
  2454. if (key) commentMap[key] = comment;
  2455. }
  2456. });
  2457. const indentStr = ' '.repeat(regionsIndent);
  2458. const newRegionsLines = regions.map(r => {
  2459. const comment = commentMap[r.key] || '';
  2460. return `${indentStr}${r.key}: ${r.enabled}${comment ? ' ' + comment.trim() : ''}`;
  2461. });
  2462. lines.splice(regionsStart, regionsEnd - regionsStart, ...newRegionsLines);
  2463. }
  2464. editor.value = lines.join('\n');
  2465. currentYaml = lines.join('\n');
  2466. updateBackdrop('yaml-editor', 'yaml-backdrop');
  2467. debounceSaveConfig();
  2468. renderDisplayRegionsList();
  2469. }
  2470. // 解析当前配置中的 RSS 源列表
  2471. function parseRssFeedsFromYaml() {
  2472. try {
  2473. const doc = jsyaml.load(currentYaml);
  2474. if (doc && doc.rss && doc.rss.feeds) {
  2475. return doc.rss.feeds;
  2476. }
  2477. } catch (e) {}
  2478. return [];
  2479. }
  2480. // 渲染 RSS 源列表
  2481. function renderRssFeedsList() {
  2482. const container = document.getElementById('rss-feeds-list');
  2483. if (!container) return;
  2484. const feeds = parseRssFeedsFromYaml();
  2485. if (feeds.length === 0) {
  2486. container.innerHTML = `<div class="text-xs text-gray-400 italic">暂无 RSS 源,请添加</div>`;
  2487. return;
  2488. }
  2489. container.innerHTML = feeds.map((f, idx) => `
  2490. <div class="rss-feed-item bg-gray-50 rounded-lg px-3 py-2 border border-gray-200 hover:border-blue-300 transition-colors" data-index="${idx}">
  2491. <div class="flex items-center justify-between">
  2492. <div class="flex items-center gap-2 flex-1 min-w-0">
  2493. <i class="fa-solid fa-rss text-orange-400"></i>
  2494. <span class="text-xs font-medium text-gray-700 truncate">${f.name}</span>
  2495. <span class="text-[10px] text-gray-400">(${f.id})</span>
  2496. ${f.enabled === false ? '<span class="text-[9px] bg-gray-200 text-gray-500 px-1 rounded">已禁用</span>' : ''}
  2497. </div>
  2498. <div class="flex items-center gap-1">
  2499. <button onclick="editRssFeed(${idx})" class="text-blue-400 hover:text-blue-600 text-xs px-1" title="编辑">
  2500. <i class="fa-solid fa-pen"></i>
  2501. </button>
  2502. <button onclick="toggleRssFeed(${idx})" class="text-gray-400 hover:text-gray-600 text-xs px-1" title="${f.enabled === false ? '启用' : '禁用'}">
  2503. <i class="fa-solid fa-${f.enabled === false ? 'eye' : 'eye-slash'}"></i>
  2504. </button>
  2505. <button onclick="removeRssFeed(${idx})" class="text-red-400 hover:text-red-600 text-xs px-1" title="删除">
  2506. <i class="fa-solid fa-trash"></i>
  2507. </button>
  2508. </div>
  2509. </div>
  2510. <div class="text-[10px] text-gray-400 mt-1 truncate" title="${f.url}">${f.url}</div>
  2511. </div>
  2512. `).join('');
  2513. }
  2514. // 删除 RSS 源
  2515. window.removeRssFeed = function(index) {
  2516. const feeds = parseRssFeedsFromYaml();
  2517. if (index < 0 || index >= feeds.length) return;
  2518. const feedName = feeds[index].name;
  2519. if (!confirm(`确定要删除 RSS 源 "${feedName}" 吗?`)) return;
  2520. feeds.splice(index, 1);
  2521. updateRssFeedsInYaml(feeds);
  2522. }
  2523. // 切换 RSS 源启用状态
  2524. window.toggleRssFeed = function(index) {
  2525. const feeds = parseRssFeedsFromYaml();
  2526. if (index < 0 || index >= feeds.length) return;
  2527. feeds[index].enabled = feeds[index].enabled === false ? true : false;
  2528. updateRssFeedsInYaml(feeds);
  2529. }
  2530. // 编辑 RSS 源
  2531. window.editRssFeed = function(index) {
  2532. const feeds = parseRssFeedsFromYaml();
  2533. if (index < 0 || index >= feeds.length) return;
  2534. const feed = feeds[index];
  2535. openRssModalWithData(feed, index);
  2536. }
  2537. // 更新 YAML 中的 RSS 配置(保留注释)
  2538. function updateRssFeedsInYaml(feeds) {
  2539. const editor = document.getElementById('yaml-editor');
  2540. let yaml = editor.value;
  2541. const lines = yaml.split('\n');
  2542. // 找到 rss.feeds 的位置
  2543. let feedsStart = -1;
  2544. let feedsEnd = -1;
  2545. let inRss = false;
  2546. let inFeeds = false;
  2547. let lastDataLineIndex = -1; // 记录最后一个数据行的位置
  2548. for (let i = 0; i < lines.length; i++) {
  2549. const line = lines[i];
  2550. const trimmed = line.trim();
  2551. if (line.match(/^rss:/)) {
  2552. inRss = true;
  2553. continue;
  2554. }
  2555. if (inRss && !inFeeds && trimmed.startsWith('feeds:')) {
  2556. feedsStart = i + 1;
  2557. inFeeds = true;
  2558. continue;
  2559. }
  2560. if (inFeeds) {
  2561. const indent = line.search(/\S/);
  2562. // 如果是数据行(以 - 开头或是数据项的属性)
  2563. if (trimmed.startsWith('-')) {
  2564. lastDataLineIndex = i;
  2565. } else if (trimmed && !trimmed.startsWith('#') && indent > 2) {
  2566. // 数据项的属性行(如 name:, id:, url:)
  2567. lastDataLineIndex = i;
  2568. } else if (trimmed && !trimmed.startsWith('#') && indent <= 2 && indent >= 0) {
  2569. // 遇到缩进更小的非注释行,说明离开了 feeds 区域
  2570. feedsEnd = lastDataLineIndex + 1;
  2571. break;
  2572. }
  2573. }
  2574. // 检查是否进入下一个顶级模块
  2575. if (inRss && line.match(/^[a-z_]+:/) && !line.match(/^rss:/)) {
  2576. if (lastDataLineIndex >= 0) {
  2577. feedsEnd = lastDataLineIndex + 1;
  2578. } else {
  2579. feedsEnd = i;
  2580. }
  2581. break;
  2582. }
  2583. }
  2584. // 如果没有找到结束位置,使用最后一个数据行的下一行
  2585. if (feedsEnd === -1) {
  2586. feedsEnd = lastDataLineIndex >= 0 ? lastDataLineIndex + 1 : lines.length;
  2587. }
  2588. // 提取区域内的注释(保留在开头的注释)
  2589. const regionLines = lines.slice(feedsStart, feedsEnd);
  2590. const leadingComments = [];
  2591. for (const line of regionLines) {
  2592. const trimmed = line.trim();
  2593. if (trimmed.startsWith('#')) {
  2594. leadingComments.push(line);
  2595. } else if (trimmed.startsWith('-') || (trimmed && !trimmed.startsWith('#'))) {
  2596. // 遇到第一个数据项,停止收集注释
  2597. break;
  2598. } else if (trimmed === '') {
  2599. // 空行也保留
  2600. leadingComments.push(line);
  2601. }
  2602. }
  2603. // 构建新的 feeds 内容
  2604. const indent = ' '; // 4 空格缩进
  2605. const newFeedsLines = feeds.map(f => {
  2606. let feedYaml = `${indent}- id: "${f.id}"\n${indent} name: "${f.name}"\n${indent} url: "${f.url}"`;
  2607. if (f.enabled === false) {
  2608. feedYaml += `\n${indent} enabled: false`;
  2609. }
  2610. if (f.max_age_days !== undefined && f.max_age_days !== '') {
  2611. feedYaml += `\n${indent} max_age_days: ${f.max_age_days}`;
  2612. }
  2613. return feedYaml;
  2614. }).join('\n\n');
  2615. const beforeFeeds = lines.slice(0, feedsStart);
  2616. const afterFeeds = lines.slice(feedsEnd);
  2617. // 组合:前面内容 + 开头注释 + 新数据 + 空行 + 后面内容
  2618. const newYaml = [
  2619. ...beforeFeeds,
  2620. ...(leadingComments.length > 0 ? leadingComments : []),
  2621. newFeedsLines,
  2622. '',
  2623. ...afterFeeds
  2624. ].join('\n');
  2625. editor.value = newYaml;
  2626. currentYaml = newYaml;
  2627. updateBackdrop('yaml-editor', 'yaml-backdrop');
  2628. debounceSaveConfig();
  2629. renderRssFeedsList();
  2630. renderStandaloneLists(); // 同步更新独立展示区的 RSS 选择列表
  2631. }
  2632. // 打开 RSS 添加/编辑弹窗
  2633. window.openRssModal = function() {
  2634. openRssModalWithData(null, -1);
  2635. }
  2636. function openRssModalWithData(feed, editIndex) {
  2637. const modal = document.getElementById('rss-modal');
  2638. document.getElementById('rss-id').value = feed ? feed.id : '';
  2639. document.getElementById('rss-name').value = feed ? feed.name : '';
  2640. document.getElementById('rss-url').value = feed ? feed.url : '';
  2641. document.getElementById('rss-max-age').value = feed && feed.max_age_days !== undefined ? feed.max_age_days : '';
  2642. modal.dataset.editIndex = editIndex;
  2643. const title = modal.querySelector('h3');
  2644. if (title) {
  2645. title.innerHTML = editIndex >= 0 ?
  2646. '<i class="fa-solid fa-rss mr-2 text-orange-500"></i>编辑 RSS 源' :
  2647. '<i class="fa-solid fa-rss mr-2 text-orange-500"></i>添加 RSS 源';
  2648. }
  2649. modal.classList.remove('hidden');
  2650. }
  2651. // 关闭 RSS 弹窗
  2652. window.closeRssModal = function() {
  2653. const modal = document.getElementById('rss-modal');
  2654. modal.classList.add('hidden');
  2655. modal.dataset.editIndex = '-1';
  2656. document.getElementById('rss-id').value = '';
  2657. document.getElementById('rss-name').value = '';
  2658. document.getElementById('rss-url').value = '';
  2659. document.getElementById('rss-max-age').value = '';
  2660. }
  2661. // 确认添加/编辑 RSS
  2662. window.confirmAddRss = function() {
  2663. const modal = document.getElementById('rss-modal');
  2664. const editIndex = parseInt(modal.dataset.editIndex || '-1');
  2665. const id = document.getElementById('rss-id').value.trim();
  2666. const name = document.getElementById('rss-name').value.trim();
  2667. const url = document.getElementById('rss-url').value.trim();
  2668. const maxAge = document.getElementById('rss-max-age').value.trim();
  2669. if (!id || !name || !url) {
  2670. alert('请填写完整信息:ID、名称和 URL 都是必填项');
  2671. return;
  2672. }
  2673. const feeds = parseRssFeedsFromYaml();
  2674. const newFeed = { id, name, url };
  2675. if (maxAge) {
  2676. newFeed.max_age_days = parseInt(maxAge);
  2677. }
  2678. if (editIndex >= 0) {
  2679. feeds[editIndex] = newFeed;
  2680. } else {
  2681. feeds.push(newFeed);
  2682. }
  2683. updateRssFeedsInYaml(feeds);
  2684. closeRssModal();
  2685. }
  2686. // ==========================================
  2687. // 14. 独立展示区 (Standalone) 管理功能
  2688. // ==========================================
  2689. function parseStandaloneConfigFromYaml() {
  2690. try {
  2691. const doc = jsyaml.load(currentYaml);
  2692. if (doc && doc.display && doc.display.standalone) {
  2693. return {
  2694. platforms: doc.display.standalone.platforms || [],
  2695. rss_feeds: doc.display.standalone.rss_feeds || []
  2696. };
  2697. }
  2698. } catch (e) {}
  2699. return { platforms: [], rss_feeds: [] };
  2700. }
  2701. function renderStandaloneLists() {
  2702. const platformsContainer = document.getElementById('standalone-platforms-list');
  2703. const rssContainer = document.getElementById('standalone-rss-list');
  2704. if (!platformsContainer || !rssContainer) return;
  2705. const standaloneConfig = parseStandaloneConfigFromYaml();
  2706. const availablePlatforms = parsePlatformsFromYaml();
  2707. const availableRss = parseRssFeedsFromYaml();
  2708. // Render Platforms
  2709. if (availablePlatforms.length === 0) {
  2710. platformsContainer.innerHTML = `<div class="col-span-2 text-xs text-gray-400 italic">暂无可用平台</div>`;
  2711. } else {
  2712. platformsContainer.innerHTML = availablePlatforms.map(p => {
  2713. const isChecked = standaloneConfig.platforms.includes(p.id);
  2714. return `
  2715. <label class="flex items-center gap-2 p-1.5 rounded hover:bg-white transition-colors cursor-pointer">
  2716. <input type="checkbox" onchange="toggleStandaloneItem('platforms', '${p.id}')"
  2717. ${isChecked ? 'checked' : ''} class="rounded border-gray-300 text-blue-600 focus:ring-blue-500">
  2718. <div class="min-w-0">
  2719. <div class="text-xs font-medium text-gray-700 truncate">${p.name}</div>
  2720. <div class="text-[9px] text-gray-400 truncate">${p.id}</div>
  2721. </div>
  2722. </label>
  2723. `;
  2724. }).join('');
  2725. }
  2726. // Render RSS
  2727. if (availableRss.length === 0) {
  2728. rssContainer.innerHTML = `<div class="text-xs text-gray-400 italic">暂无可用 RSS 源</div>`;
  2729. } else {
  2730. rssContainer.innerHTML = availableRss.map(f => {
  2731. const isChecked = standaloneConfig.rss_feeds.includes(f.id);
  2732. return `
  2733. <label class="flex items-center gap-2 p-1.5 rounded hover:bg-white transition-colors cursor-pointer">
  2734. <input type="checkbox" onchange="toggleStandaloneItem('rss_feeds', '${f.id}')"
  2735. ${isChecked ? 'checked' : ''} class="rounded border-gray-300 text-blue-600 focus:ring-blue-500">
  2736. <div class="min-w-0 flex-1">
  2737. <div class="flex items-center justify-between">
  2738. <span class="text-xs font-medium text-gray-700 truncate">${f.name}</span>
  2739. <span class="text-[9px] text-gray-400 ml-2">${f.id}</span>
  2740. </div>
  2741. <div class="text-[9px] text-gray-400 truncate">${f.url}</div>
  2742. </div>
  2743. </label>
  2744. `;
  2745. }).join('');
  2746. }
  2747. }
  2748. window.toggleStandaloneItem = function(type, id) {
  2749. const config = parseStandaloneConfigFromYaml();
  2750. const list = config[type];
  2751. const index = list.indexOf(id);
  2752. if (index === -1) {
  2753. list.push(id);
  2754. } else {
  2755. list.splice(index, 1);
  2756. }
  2757. updateStandaloneConfigInYaml(type, list);
  2758. }
  2759. function updateStandaloneConfigInYaml(type, list) {
  2760. const editor = document.getElementById('yaml-editor');
  2761. let yaml = editor.value;
  2762. const lines = yaml.split('\n');
  2763. // 找到 display -> standalone -> [type]
  2764. let inDisplay = false;
  2765. let inStandalone = false;
  2766. let targetLineIndex = -1;
  2767. let indent = '';
  2768. for (let i = 0; i < lines.length; i++) {
  2769. const line = lines[i];
  2770. if (line.match(/^display:/)) {
  2771. inDisplay = true;
  2772. continue;
  2773. }
  2774. if (inDisplay && line.trim().startsWith('standalone:')) {
  2775. inStandalone = true;
  2776. continue;
  2777. }
  2778. if (inStandalone) {
  2779. // 检查是否离开 standalone (遇到缩进更少或相同的非注释行)
  2780. const currentIndent = line.search(/\S/);
  2781. // standalone 下一级的缩进
  2782. if (line.match(new RegExp(`^\\s*${type}:`))) {
  2783. targetLineIndex = i;
  2784. indent = line.substring(0, line.indexOf(type));
  2785. break;
  2786. }
  2787. // 如果遇到下一个模块,停止
  2788. if (line.match(/^[a-z_]+:/) && !line.match(/^display:/)) break;
  2789. }
  2790. }
  2791. if (targetLineIndex !== -1) {
  2792. // 构建新的数组字符串 ["item1", "item2"]
  2793. const jsonStr = JSON.stringify(list);
  2794. // 保留原有注释
  2795. const originalLine = lines[targetLineIndex];
  2796. const commentMatch = originalLine.match(/#.*$/);
  2797. const comment = commentMatch ? commentMatch[0] : '';
  2798. lines[targetLineIndex] = `${indent}${type}: ${jsonStr}${comment ? ' ' + comment : ''}`;
  2799. const newYaml = lines.join('\n');
  2800. editor.value = newYaml;
  2801. currentYaml = newYaml;
  2802. updateBackdrop('yaml-editor', 'yaml-backdrop');
  2803. debounceSaveConfig();
  2804. // 不需要重新渲染整个列表,因为是 checkbox 点击触发的
  2805. // 但如果需要保持一致性,可以重新渲染
  2806. }
  2807. }
  2808. // 从文本中提取版本号
  2809. function extractVersion(text) {
  2810. // 匹配 Version: v5.3.0 或 Version: 5.3.0 格式
  2811. const versionMatch = text.match(/Version:\s*v?(\d+\.\d+\.\d+)/i);
  2812. if (versionMatch) {
  2813. return versionMatch[1]; // 返回不带 v 的版本号
  2814. }
  2815. return null;
  2816. }
  2817. // 比较版本号 (返回 1: v1 > v2, -1: v1 < v2, 0: v1 == v2)
  2818. function compareVersions(v1, v2) {
  2819. if (!v1 || !v2) return 0;
  2820. const parts1 = v1.split('.').map(Number);
  2821. const parts2 = v2.split('.').map(Number);
  2822. for (let i = 0; i < Math.max(parts1.length, parts2.length); i++) {
  2823. const num1 = parts1[i] || 0;
  2824. const num2 = parts2[i] || 0;
  2825. if (num1 > num2) return 1;
  2826. if (num1 < num2) return -1;
  2827. }
  2828. return 0;
  2829. }
  2830. // 版本检测主函数
  2831. window.checkVersion = async function() {
  2832. const btn = document.getElementById('version-check-btn');
  2833. const originalHTML = btn.innerHTML;
  2834. btn.innerHTML = '<i class="fa-solid fa-spinner fa-spin"></i><span>检测中...</span>';
  2835. btn.disabled = true;
  2836. try {
  2837. const versionRes = await fetch(REMOTE_VERSION_URL);
  2838. if (!versionRes.ok) {
  2839. throw new Error(`版本信息获取失败: ${versionRes.status}`);
  2840. }
  2841. const versionConfigText = await versionRes.text();
  2842. const versionMap = {};
  2843. versionConfigText.split('\n').forEach(line => {
  2844. const parts = line.trim().split('=');
  2845. if (parts.length >= 2) {
  2846. versionMap[parts[0].trim()] = parts[1].trim();
  2847. }
  2848. });
  2849. const currentTab = getCurrentTab();
  2850. let currentVersion = null;
  2851. let fileName = '';
  2852. if (currentTab === 'config') {
  2853. currentVersion = extractVersion(currentYaml);
  2854. fileName = 'config.yaml';
  2855. } else {
  2856. currentVersion = extractVersion(currentFrequency);
  2857. fileName = 'frequency_words.txt';
  2858. }
  2859. const latestVersion = versionMap[fileName];
  2860. if (!latestVersion) {
  2861. throw new Error(`未在远程版本清单中找到 ${fileName}`);
  2862. }
  2863. showVersionComparisonModal(fileName, currentVersion, latestVersion);
  2864. } catch (err) {
  2865. console.error('版本检测失败:', err);
  2866. showToast(`版本检测失败: ${err.message}`, 'error');
  2867. } finally {
  2868. btn.innerHTML = originalHTML;
  2869. btn.disabled = false;
  2870. }
  2871. }
  2872. // 获取当前 Tab
  2873. function getCurrentTab() {
  2874. return currentTab;
  2875. }
  2876. // 显示版本对比弹窗
  2877. function showVersionComparisonModal(fileName, currentVersion, latestVersion) {
  2878. const existingModal = document.getElementById('version-comparison-modal');
  2879. if (existingModal) existingModal.remove();
  2880. const comparison = compareVersions(currentVersion, latestVersion);
  2881. let statusIcon = '';
  2882. let statusText = '';
  2883. let statusColor = '';
  2884. let actionButtons = '';
  2885. if (!currentVersion) {
  2886. statusIcon = '<i class="fa-solid fa-question-circle text-gray-500 text-3xl"></i>';
  2887. statusText = '未检测到版本信息';
  2888. statusColor = 'text-gray-600';
  2889. actionButtons = `
  2890. <button onclick="closeVersionModal()" class="px-4 py-2 text-gray-600 hover:bg-gray-100 rounded-lg">关闭</button>
  2891. <button onclick="updateToLatest()" class="px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700">
  2892. <i class="fa-solid fa-download mr-1"></i>更新到最新版本
  2893. </button>
  2894. `;
  2895. } else if (comparison < 0) {
  2896. statusIcon = '<i class="fa-solid fa-arrow-up text-orange-500 text-3xl"></i>';
  2897. statusText = '发现新版本';
  2898. statusColor = 'text-orange-600';
  2899. actionButtons = `
  2900. <button onclick="closeVersionModal()" class="px-4 py-2 text-gray-600 hover:bg-gray-100 rounded-lg">稍后更新</button>
  2901. <button onclick="updateToLatest()" class="px-4 py-2 bg-orange-600 text-white rounded-lg hover:bg-orange-700">
  2902. <i class="fa-solid fa-download mr-1"></i>立即更新
  2903. </button>
  2904. `;
  2905. } else if (comparison > 0) {
  2906. statusIcon = '<i class="fa-solid fa-flask text-purple-500 text-3xl"></i>';
  2907. statusText = '当前版本较新(开发版本?)';
  2908. statusColor = 'text-purple-600';
  2909. actionButtons = `
  2910. <button onclick="closeVersionModal()" class="px-4 py-2 bg-gray-100 text-gray-600 hover:bg-gray-200 rounded-lg">关闭</button>
  2911. `;
  2912. } else {
  2913. statusIcon = '<i class="fa-solid fa-check-circle text-green-500 text-3xl"></i>';
  2914. statusText = '已是最新版本';
  2915. statusColor = 'text-green-600';
  2916. actionButtons = `
  2917. <button onclick="closeVersionModal()" class="px-4 py-2 bg-gray-100 text-gray-600 hover:bg-gray-200 rounded-lg">关闭</button>
  2918. `;
  2919. }
  2920. const modal = document.createElement('div');
  2921. modal.id = 'version-comparison-modal';
  2922. modal.className = 'modal-overlay';
  2923. modal.innerHTML = `
  2924. <div class="modal-content" style="max-width: 480px;">
  2925. <div class="flex items-center justify-between mb-4">
  2926. <h3 class="text-lg font-bold text-gray-800">
  2927. <i class="fa-solid fa-code-compare mr-2 text-blue-500"></i>版本检测结果
  2928. </h3>
  2929. <button onclick="closeVersionModal()" class="text-gray-400 hover:text-gray-600">
  2930. <i class="fa-solid fa-times text-xl"></i>
  2931. </button>
  2932. </div>
  2933. <div class="text-center py-6">
  2934. ${statusIcon}
  2935. <div class="text-xl font-bold ${statusColor} mt-3">${statusText}</div>
  2936. </div>
  2937. <div class="bg-gray-50 rounded-lg p-4 space-y-3 mb-4">
  2938. <div class="flex items-center justify-between text-sm">
  2939. <span class="text-gray-600">配置文件</span>
  2940. <span class="font-mono font-bold text-gray-800">${fileName}</span>
  2941. </div>
  2942. <div class="border-t border-gray-200"></div>
  2943. <div class="flex items-center justify-between text-sm">
  2944. <span class="text-gray-600">当前版本</span>
  2945. <span class="font-mono font-bold ${currentVersion ? 'text-blue-600' : 'text-gray-400'}">
  2946. ${currentVersion ? 'v' + currentVersion : '未知'}
  2947. </span>
  2948. </div>
  2949. <div class="flex items-center justify-between text-sm">
  2950. <span class="text-gray-600">最新版本</span>
  2951. <span class="font-mono font-bold text-green-600">v${latestVersion}</span>
  2952. </div>
  2953. </div>
  2954. ${comparison < 0 || !currentVersion ? `
  2955. <div class="text-xs text-gray-500 bg-yellow-50 border border-yellow-200 rounded p-3 mb-4">
  2956. <i class="fa-solid fa-lightbulb mr-1 text-yellow-600"></i>
  2957. <strong>提示:</strong>更新将从 GitHub 加载最新的 ${fileName},你当前的修改将被覆盖。建议先复制保存你的自定义配置。
  2958. </div>
  2959. ` : ''}
  2960. <div class="flex justify-end gap-2">
  2961. ${actionButtons}
  2962. </div>
  2963. </div>
  2964. `;
  2965. document.body.appendChild(modal);
  2966. }
  2967. window.closeVersionModal = function() {
  2968. const modal = document.getElementById('version-comparison-modal');
  2969. if (modal) modal.remove();
  2970. }
  2971. // ==========================================
  2972. // 13. 平台添加弹窗逻辑
  2973. // ==========================================
  2974. // 预定义可用平台列表 (仅包含官方默认支持的平台)
  2975. const PRESET_PLATFORMS = [
  2976. { key: 'toutiao', name: '今日头条' },
  2977. { key: 'baidu', name: '百度热搜' },
  2978. { key: 'wallstreetcn-hot', name: '华尔街见闻' },
  2979. { key: 'thepaper', name: '澎湃新闻' },
  2980. { key: 'bilibili-hot-search', name: 'bilibili 热搜' },
  2981. { key: 'cls-hot', name: '财联社热门' },
  2982. { key: 'ifeng', name: '凤凰网' },
  2983. { key: 'tieba', name: '贴吧' },
  2984. { key: 'weibo', name: '微博' },
  2985. { key: 'douyin', name: '抖音' },
  2986. { key: 'zhihu', name: '知乎' }
  2987. ];
  2988. /**
  2989. * 打开平台添加弹窗
  2990. */
  2991. window.openPlatformModal = function() {
  2992. const modal = document.getElementById('platform-modal');
  2993. if (modal) {
  2994. modal.classList.remove('hidden');
  2995. if (typeof switchPlatformTab === 'function') {
  2996. switchPlatformTab('select');
  2997. }
  2998. renderAvailablePlatforms();
  2999. }
  3000. }
  3001. /**
  3002. * 关闭平台添加弹窗
  3003. */
  3004. window.closePlatformModal = function() {
  3005. const modal = document.getElementById('platform-modal');
  3006. if (modal) {
  3007. modal.classList.add('hidden');
  3008. }
  3009. }
  3010. /**
  3011. * 切换平台添加标签页
  3012. */
  3013. window.switchPlatformTab = function(tab) {
  3014. currentPlatformTab = tab;
  3015. // 更新 Tab 样式
  3016. const tabSelect = document.getElementById('tab-platform-select');
  3017. const tabCustom = document.getElementById('tab-platform-custom');
  3018. if (tab === 'select') {
  3019. if (tabSelect) {
  3020. tabSelect.classList.add('text-blue-600', 'border-blue-600');
  3021. tabSelect.classList.remove('text-gray-500', 'border-transparent');
  3022. }
  3023. if (tabCustom) {
  3024. tabCustom.classList.remove('text-blue-600', 'border-blue-600');
  3025. tabCustom.classList.add('text-gray-500', 'border-transparent');
  3026. }
  3027. const selectPanel = document.getElementById('platform-select-panel');
  3028. const customPanel = document.getElementById('platform-custom-panel');
  3029. if (selectPanel) selectPanel.classList.remove('hidden');
  3030. if (customPanel) customPanel.classList.add('hidden');
  3031. } else {
  3032. if (tabCustom) {
  3033. tabCustom.classList.add('text-blue-600', 'border-blue-600');
  3034. tabCustom.classList.remove('text-gray-500', 'border-transparent');
  3035. }
  3036. if (tabSelect) {
  3037. tabSelect.classList.remove('text-blue-600', 'border-blue-600');
  3038. tabSelect.classList.add('text-gray-500', 'border-transparent');
  3039. }
  3040. const selectPanel = document.getElementById('platform-select-panel');
  3041. const customPanel = document.getElementById('platform-custom-panel');
  3042. if (selectPanel) selectPanel.classList.add('hidden');
  3043. if (customPanel) customPanel.classList.remove('hidden');
  3044. }
  3045. }
  3046. /**
  3047. * 渲染可用平台列表(排除已添加的)
  3048. */
  3049. function renderAvailablePlatforms() {
  3050. const container = document.getElementById('available-platforms-list');
  3051. const tip = document.getElementById('no-platforms-tip');
  3052. if (!container) return;
  3053. container.innerHTML = '';
  3054. const currentPlatforms = parsePlatformsFromYaml();
  3055. const existingKeys = currentPlatforms.map(p => p.id);
  3056. const available = PRESET_PLATFORMS.filter(p => !existingKeys.includes(p.key));
  3057. if (available.length === 0) {
  3058. if (tip) {
  3059. tip.classList.remove('hidden');
  3060. tip.innerHTML = `<i class="fa-solid fa-check-circle text-green-500 mr-2"></i>所有预设平台已添加`;
  3061. }
  3062. } else {
  3063. if (tip) tip.classList.add('hidden');
  3064. available.forEach(p => {
  3065. const div = document.createElement('div');
  3066. div.className = 'flex items-center justify-between p-3 border border-gray-100 rounded hover:bg-blue-50 cursor-pointer transition-colors group';
  3067. div.onclick = () => confirmAddPlatform(p.key, p.name);
  3068. div.innerHTML = `
  3069. <div class="flex items-center gap-3">
  3070. <div class="w-8 h-8 rounded bg-gray-100 flex items-center justify-center text-gray-500 group-hover:bg-white group-hover:text-blue-600">
  3071. <i class="fa-solid fa-cube"></i>
  3072. </div>
  3073. <div>
  3074. <div class="font-bold text-gray-800 text-sm">${p.name}</div>
  3075. <div class="text-xs text-gray-400 font-mono">${p.key}</div>
  3076. </div>
  3077. </div>
  3078. <button class="text-gray-300 group-hover:text-blue-600">
  3079. <i class="fa-solid fa-plus-circle text-lg"></i>
  3080. </button>
  3081. `;
  3082. container.appendChild(div);
  3083. });
  3084. }
  3085. }
  3086. /**
  3087. * 确认添加平台
  3088. */
  3089. window.confirmAddPlatform = function(key, name) {
  3090. let platformKey = key;
  3091. let platformName = name;
  3092. // 如果是手动输入模式 (且未传入 key)
  3093. if (currentPlatformTab === 'custom' && !key) {
  3094. const keyInput = document.getElementById('custom-platform-key');
  3095. const nameInput = document.getElementById('custom-platform-name');
  3096. if (keyInput) platformKey = keyInput.value.trim();
  3097. if (nameInput) platformName = nameInput.value.trim();
  3098. if (!platformKey) {
  3099. alert('请输入平台 Key');
  3100. return;
  3101. }
  3102. if (!platformName) {
  3103. platformName = platformKey;
  3104. }
  3105. } else if (currentPlatformTab === 'select' && !key) {
  3106. alert('请直接点击上方列表中的平台进行添加');
  3107. return;
  3108. }
  3109. // 检查是否已存在
  3110. const currentPlatforms = parsePlatformsFromYaml();
  3111. if (currentPlatforms.find(p => p.id === platformKey)) {
  3112. alert(`平台 ${platformKey} 已存在!`);
  3113. return;
  3114. }
  3115. // 添加到 YAML (注意字段是 id 和 name)
  3116. const newPlatform = {
  3117. id: platformKey,
  3118. name: platformName,
  3119. enabled: true
  3120. };
  3121. // 重新构建 YAML
  3122. currentPlatforms.push(newPlatform);
  3123. updatePlatformsInYaml(currentPlatforms);
  3124. closePlatformModal();
  3125. const keyInput = document.getElementById('custom-platform-key');
  3126. const nameInput = document.getElementById('custom-platform-name');
  3127. if (keyInput) keyInput.value = '';
  3128. if (nameInput) nameInput.value = '';
  3129. renderPlatformsList();
  3130. showToast(`平台 ${platformName} 已添加`, 'success');
  3131. }
  3132. // 绑定到全局
  3133. window.updateToLatest = async function() {
  3134. closeVersionModal();
  3135. const currentTab = getCurrentTab();
  3136. const fileName = currentTab === 'config' ? 'config.yaml' : 'frequency_words.txt';
  3137. if (!confirm(`确定要从 GitHub 更新 ${fileName} 到最新版本吗?\n\n你当前的自定义配置将被覆盖,建议先复制保存。`)) {
  3138. return;
  3139. }
  3140. showToast('正在从 GitHub 加载最新版本...', 'info');
  3141. try {
  3142. const url = currentTab === 'config' ? REMOTE_CONFIG_URL : REMOTE_FREQUENCY_URL;
  3143. const res = await fetch(url);
  3144. if (!res.ok) {
  3145. throw new Error(`加载失败: ${res.status}`);
  3146. }
  3147. const text = await res.text();
  3148. if (currentTab === 'config') {
  3149. try {
  3150. jsyaml.load(text);
  3151. } catch (yamlErr) {
  3152. showToast(`YAML 语法错误: ${yamlErr.message}`, 'error');
  3153. return;
  3154. }
  3155. document.getElementById('yaml-editor').value = text;
  3156. currentYaml = text;
  3157. syncYamlToUI();
  3158. } else {
  3159. document.getElementById('frequency-editor').value = text;
  3160. currentFrequency = text;
  3161. syncFrequencyToUI();
  3162. }
  3163. saveToLocalStorage();
  3164. showToast(`已更新到最新版本`, 'success');
  3165. } catch (err) {
  3166. console.error('更新失败:', err);
  3167. showToast(`更新失败: ${err.message}`, 'error');
  3168. }
  3169. }
  3170. // ==========================================
  3171. // RSS 辅助功能
  3172. // ==========================================
  3173. function toggleRssTips() {
  3174. const panel = document.getElementById('rss-tips-panel');
  3175. const icon = document.getElementById('rss-tips-icon');
  3176. if (panel) {
  3177. panel.classList.toggle('hidden');
  3178. if (icon) {
  3179. icon.style.transform = panel.classList.contains('hidden') ? 'rotate(0deg)' : 'rotate(180deg)';
  3180. }
  3181. }
  3182. }
  3183. function fillRssUrl(url) {
  3184. const input = document.getElementById('rss-url');
  3185. if (input) {
  3186. input.value = url;
  3187. // 视觉反馈
  3188. input.classList.add('ring-2', 'ring-blue-500', 'bg-blue-50');
  3189. setTimeout(() => {
  3190. input.classList.remove('ring-2', 'ring-blue-500', 'bg-blue-50');
  3191. }, 500);
  3192. }
  3193. }
  3194. // ==========================================
  3195. // 13. Timeline 编辑器功能
  3196. // ==========================================
  3197. const PRESET_META = {
  3198. morning_evening: { icon: 'fa-sun', color: 'text-amber-500', bg: 'bg-amber-50', recommend: true },
  3199. always_on: { icon: 'fa-bolt', color: 'text-blue-500', bg: 'bg-blue-50' },
  3200. office_hours: { icon: 'fa-briefcase', color: 'text-green-500', bg: 'bg-green-50' },
  3201. night_owl: { icon: 'fa-moon', color: 'text-indigo-500', bg: 'bg-indigo-50' },
  3202. custom: { icon: 'fa-sliders', color: 'text-purple-500', bg: 'bg-purple-50' }
  3203. };
  3204. const DAY_NAMES = ['周一', '周二', '周三', '周四', '周五', '周六', '周日'];
  3205. /**
  3206. * 从当前 config.yaml 中读取 schedule.preset
  3207. */
  3208. function getActivePreset() {
  3209. try {
  3210. const doc = jsyaml.load(currentYaml);
  3211. return doc?.schedule?.preset || 'morning_evening';
  3212. } catch { return 'morning_evening'; }
  3213. }
  3214. /**
  3215. * 解析 timeline YAML,返回结构化数据
  3216. */
  3217. function parseTimelineData() {
  3218. try {
  3219. const doc = jsyaml.load(currentTimeline);
  3220. if (!doc) return null;
  3221. return doc;
  3222. } catch { return null; }
  3223. }
  3224. /**
  3225. * 获取指定预设/custom 的完整配置
  3226. */
  3227. function getPresetConfig(data, presetName) {
  3228. if (!data) return null;
  3229. if (presetName === 'custom') return data.custom || null;
  3230. return data.presets?.[presetName] || null;
  3231. }
  3232. /**
  3233. * 主渲染函数:解析 timeline YAML → 渲染右侧面板
  3234. */
  3235. function syncTimelineToUI() {
  3236. const panel = document.getElementById('timeline-panel');
  3237. if (!panel) return;
  3238. const data = parseTimelineData();
  3239. const activePreset = getActivePreset();
  3240. if (!data) {
  3241. panel.innerHTML = `
  3242. <div class="text-center py-12 text-gray-400">
  3243. <i class="fa-solid fa-calendar-xmark text-4xl mb-3"></i>
  3244. <p class="text-sm">请在左侧粘贴 timeline.yaml 内容</p>
  3245. <p class="text-xs mt-1">或点击右上角「加载官网最新配置」</p>
  3246. </div>`;
  3247. return;
  3248. }
  3249. let html = '';
  3250. // ── Layer 1: 预设模式选择卡片 ──
  3251. html += `<div class="mb-6">
  3252. <div class="tl-section-title"><i class="fa-solid fa-swatchbook"></i>调度模式</div>
  3253. <div class="grid grid-cols-2 gap-3" id="tl-preset-grid">`;
  3254. // 收集所有预设名
  3255. const presetNames = Object.keys(data.presets || {});
  3256. // 确保 custom 在最后
  3257. const allModes = [...presetNames.filter(n => n !== 'custom'), ...(data.custom ? ['custom'] : [])];
  3258. allModes.forEach(name => {
  3259. const meta = PRESET_META[name] || { icon: 'fa-puzzle-piece', color: 'text-gray-500', bg: 'bg-gray-50' };
  3260. const presetCfg = getPresetConfig(data, name);
  3261. const label = presetCfg?.name || meta.label || name;
  3262. const desc = presetCfg?.description || meta.desc || '';
  3263. const isActive = name === activePreset;
  3264. const isProtected = ['morning_evening', 'always_on', 'office_hours', 'night_owl', 'custom'].includes(name);
  3265. html += `
  3266. <div class="tl-preset-card ${isActive ? 'selected' : ''}" data-preset="${name}">
  3267. ${meta.recommend ? '<div class="tl-recommend-badge">推荐</div>' : ''}
  3268. <div class="flex items-center gap-3 cursor-pointer" onclick="selectTimelinePreset('${name}')">
  3269. <div class="tl-card-icon ${meta.bg} ${meta.color}"><i class="fa-solid ${meta.icon}"></i></div>
  3270. <div class="flex-1 min-w-0">
  3271. <div class="text-sm font-bold text-gray-800 truncate tl-editable" ondblclick="event.stopPropagation();tlInlineEdit(this,'${name}','name','${escapeAttr(label)}')">${label}</div>
  3272. <div class="text-[10px] text-gray-500 truncate tl-editable" ondblclick="event.stopPropagation();tlInlineEdit(this,'${name}','description','${escapeAttr(desc)}')">${desc}</div>
  3273. </div>
  3274. </div>
  3275. <div class="tl-card-actions">
  3276. <button onclick="event.stopPropagation();duplicateTlPreset('${name}')" class="tl-card-action-btn" title="复制"><i class="fa-regular fa-copy"></i></button>
  3277. ${!isProtected ? `<button onclick="event.stopPropagation();deleteTlPreset('${name}')" class="tl-card-action-btn text-red-400 hover:text-red-600" title="删除"><i class="fa-regular fa-trash-can"></i></button>` : ''}
  3278. </div>
  3279. ${isActive ? '<div class="absolute bottom-1 right-2 text-[9px] text-blue-500 font-bold"><i class="fa-solid fa-check-circle mr-0.5"></i>当前</div>' : ''}
  3280. </div>`;
  3281. });
  3282. // 新建模式卡片
  3283. html += `
  3284. <div class="tl-preset-card tl-new-preset-card" onclick="openTlNewPresetModal()">
  3285. <div class="flex items-center gap-3">
  3286. <div class="tl-card-icon bg-gray-50 text-gray-400"><i class="fa-solid fa-plus"></i></div>
  3287. <div>
  3288. <div class="text-sm font-bold text-gray-500">新建模式</div>
  3289. <div class="text-[10px] text-gray-400">创建自定义调度方案</div>
  3290. </div>
  3291. </div>
  3292. </div>`;
  3293. html += `</div></div>`;
  3294. // 获取当前预设配置
  3295. const config = getPresetConfig(data, activePreset);
  3296. if (!config) {
  3297. html += `<div class="text-center py-6 text-gray-400 text-sm">
  3298. <i class="fa-solid fa-triangle-exclamation text-amber-400 mr-1"></i>
  3299. 未找到预设「${activePreset}」的配置
  3300. </div>`;
  3301. panel.innerHTML = html;
  3302. return;
  3303. }
  3304. // ── Layer 2: 周视图时间线 ──
  3305. html += renderWeekView(config, activePreset);
  3306. // ── Layer 3: 时间段详情 ──
  3307. html += renderPeriodDetails(config, activePreset);
  3308. panel.innerHTML = html;
  3309. // 初始化日计划 Tag 拖拽排序
  3310. initDayPlanSortable(activePreset);
  3311. }
  3312. /**
  3313. * 渲染周视图(7 天 × 24 小时水平条)
  3314. */
  3315. function renderWeekView(config, presetName) {
  3316. const periods = config.periods || {};
  3317. const dayPlans = config.day_plans || {};
  3318. const weekMap = config.week_map || {};
  3319. // 时间刻度
  3320. let html = `<div class="tl-week-view">
  3321. <div class="tl-section-title mb-2"><i class="fa-solid fa-calendar-week"></i>周视图</div>
  3322. <div class="tl-hour-markers">
  3323. <div style="width:2.5rem;flex-shrink:0"></div>
  3324. <div style="flex:1;display:flex;min-width:480px">`;
  3325. for (let h = 0; h <= 24; h += 2) {
  3326. html += `<div class="tl-hour-marker" style="width:${100/12}%;${h===24?'text-align:right;margin-left:-1em':''}">
  3327. ${h < 10 ? '0' : ''}${h}
  3328. </div>`;
  3329. }
  3330. html += `</div></div>`;
  3331. // 获取当前星期几 (1=周一...7=周日)
  3332. const today = new Date().getDay();
  3333. const todayIso = today === 0 ? 7 : today;
  3334. // 7 天的行
  3335. for (let d = 1; d <= 7; d++) {
  3336. const dayPlanName = weekMap[d] || weekMap[String(d)];
  3337. const dayPlan = dayPlans[dayPlanName];
  3338. const dayPeriodNames = dayPlan?.periods || [];
  3339. const isToday = d === todayIso;
  3340. html += `<div class="tl-week-row">
  3341. <div class="tl-day-label ${isToday ? 'today' : ''}">${DAY_NAMES[d-1]}</div>
  3342. <div class="tl-timeline-bar" data-day="${d}" onclick="onTlBarClick(event,'${presetName}',${d})">`;
  3343. // 渲染各时间段色块
  3344. dayPeriodNames.forEach(pName => {
  3345. const p = periods[pName];
  3346. if (!p) return;
  3347. const merged = mergeWithDefault(p, config.default);
  3348. const colorClass = getBlockColorClass(merged);
  3349. const blocks = computeBlocks(p.start, p.end);
  3350. blocks.forEach(b => {
  3351. const left = (b.start / 24 * 100).toFixed(2);
  3352. const width = ((b.end - b.start) / 24 * 100).toFixed(2);
  3353. const label = p.name || pName;
  3354. html += `<div class="tl-period-block ${colorClass}" style="left:${left}%;width:${width}%"
  3355. onclick="scrollToPeriodCard('${pName}')"
  3356. onmouseenter="showTlTooltip(event, '${escapeAttr(label)}', '${p.start||''}', '${p.end||''}', ${!!merged.push}, ${!!merged.analyze}, '${merged.report_mode||''}')"
  3357. onmouseleave="hideTlTooltip()">
  3358. <span class="tl-block-label">${label}</span>
  3359. </div>`;
  3360. });
  3361. });
  3362. // 当前时间指示线(仅今天)
  3363. if (isToday) {
  3364. const nowTime = new Date();
  3365. const nowH = nowTime.getHours() + nowTime.getMinutes() / 60;
  3366. const nowLeftPct = (nowH / 24 * 100).toFixed(2);
  3367. html += `<div class="tl-now-line" style="left:${nowLeftPct}%" title="当前时间 ${String(nowTime.getHours()).padStart(2,'0')}:${String(nowTime.getMinutes()).padStart(2,'0')}"></div>`;
  3368. }
  3369. html += `</div></div>`;
  3370. }
  3371. // 图例
  3372. html += `<div class="tl-legend">
  3373. <div class="tl-legend-item"><div class="tl-legend-color tl-block-push"></div>推送</div>
  3374. <div class="tl-legend-item"><div class="tl-legend-color tl-block-analyze"></div>AI 分析</div>
  3375. <div class="tl-legend-item"><div class="tl-legend-color tl-block-push-analyze"></div>推送 + 分析</div>
  3376. <div class="tl-legend-item"><div class="tl-legend-color tl-block-collect"></div>仅采集</div>
  3377. <div class="tl-legend-item"><div class="tl-legend-color" style="background:#f1f5f9;border:1px solid #e2e8f0"></div>默认 (default)</div>
  3378. </div>`;
  3379. html += `</div>`;
  3380. return html;
  3381. }
  3382. /**
  3383. * 合并 period 与 default(period 字段优先)
  3384. */
  3385. function mergeWithDefault(period, defaultCfg) {
  3386. if (!defaultCfg) return period || {};
  3387. const merged = { ...defaultCfg, ...period };
  3388. if (period.once || defaultCfg.once) {
  3389. merged.once = { ...(defaultCfg.once || {}), ...(period.once || {}) };
  3390. }
  3391. return merged;
  3392. }
  3393. /**
  3394. * 根据 push/analyze 状态确定色块 CSS 类
  3395. */
  3396. function getBlockColorClass(merged) {
  3397. const push = !!merged.push;
  3398. const analyze = !!merged.analyze;
  3399. if (push && analyze) return 'tl-block-push-analyze';
  3400. if (push) return 'tl-block-push';
  3401. if (analyze) return 'tl-block-analyze';
  3402. if (merged.collect !== false) return 'tl-block-collect';
  3403. return 'tl-block-silent';
  3404. }
  3405. /**
  3406. * 计算时间段的渲染块(处理跨午夜情况)
  3407. * 返回 [{start: 小时数, end: 小时数}, ...] 的数组
  3408. */
  3409. function computeBlocks(startStr, endStr) {
  3410. if (!startStr || !endStr) return [];
  3411. const s = parseTime(startStr);
  3412. const e = parseTime(endStr);
  3413. if (s < e) return [{ start: s, end: e }];
  3414. // 跨午夜
  3415. return [{ start: s, end: 24 }, { start: 0, end: e }];
  3416. }
  3417. function parseTime(str) {
  3418. const [h, m] = (str || '00:00').split(':').map(Number);
  3419. return h + (m || 0) / 60;
  3420. }
  3421. function escapeAttr(s) {
  3422. return (s || '').replace(/'/g, "\\'").replace(/"/g, '&quot;');
  3423. }
  3424. /**
  3425. * Tooltip 显示/隐藏
  3426. */
  3427. let tlTooltipEl = null;
  3428. function showTlTooltip(event, name, start, end, push, analyze, mode) {
  3429. hideTlTooltip();
  3430. const el = document.createElement('div');
  3431. el.className = 'tl-tooltip';
  3432. let features = [];
  3433. if (push) features.push('<span style="color:#93c5fd">推送</span>');
  3434. if (analyze) features.push('<span style="color:#c4b5fd">分析</span>');
  3435. if (!push && !analyze) features.push('<span style="color:#94a3b8">仅采集</span>');
  3436. el.innerHTML = `<div style="font-weight:700;margin-bottom:2px">${name}</div>
  3437. <div style="font-size:11px;color:#9ca3af">${start} - ${end}</div>
  3438. <div style="margin-top:4px">${features.join(' / ')}</div>
  3439. ${mode ? `<div style="font-size:10px;color:#9ca3af;margin-top:2px">模式: ${mode}</div>` : ''}`;
  3440. document.body.appendChild(el);
  3441. tlTooltipEl = el;
  3442. const rect = event.target.getBoundingClientRect();
  3443. el.style.left = (rect.left + rect.width / 2 - el.offsetWidth / 2) + 'px';
  3444. el.style.top = (rect.top - el.offsetHeight - 8) + 'px';
  3445. // 确保不超出屏幕
  3446. const elRect = el.getBoundingClientRect();
  3447. if (elRect.left < 4) el.style.left = '4px';
  3448. if (elRect.right > window.innerWidth - 4) el.style.left = (window.innerWidth - el.offsetWidth - 4) + 'px';
  3449. if (elRect.top < 4) {
  3450. el.style.top = (rect.bottom + 8) + 'px';
  3451. el.style.setProperty('--arrow', 'top');
  3452. }
  3453. }
  3454. function hideTlTooltip() {
  3455. if (tlTooltipEl) {
  3456. tlTooltipEl.remove();
  3457. tlTooltipEl = null;
  3458. }
  3459. }
  3460. /**
  3461. * 渲染时间段详情面板
  3462. */
  3463. function renderPeriodDetails(config, presetName) {
  3464. const isCustom = presetName === 'custom';
  3465. const periods = config.periods || {};
  3466. const dayPlans = config.day_plans || {};
  3467. const weekMap = config.week_map || {};
  3468. const defaults = config.default || {};
  3469. let html = '';
  3470. // ── Default 配置(默认展开)──
  3471. html += `<div class="tl-collapsible mt-4">
  3472. <div class="tl-collapsible-header" onclick="toggleTlCollapsible(this)">
  3473. <span><i class="fa-solid fa-gear mr-2 text-gray-400"></i>默认配置 (default)</span>
  3474. <i class="fa-solid fa-chevron-down text-gray-400 text-xs"></i>
  3475. </div>
  3476. <div class="tl-collapsible-body">
  3477. <div class="text-xs text-gray-500 mb-2">不在任何时间段内时,使用以下配置:</div>
  3478. ${renderBehaviorToggles(defaults, presetName, 'default', defaults)}
  3479. </div>
  3480. </div>`;
  3481. // ── 时间段列表 ──
  3482. const periodEntries = Object.entries(periods);
  3483. html += `<div class="mt-6">
  3484. <div class="tl-section-title flex items-center justify-between">
  3485. <span><i class="fa-solid fa-puzzle-piece"></i>时间段 (Periods)</span>
  3486. <button onclick="openTlNewPeriodModal('${presetName}')" class="tl-add-btn"><i class="fa-solid fa-plus mr-1"></i>新增</button>
  3487. </div>`;
  3488. if (periodEntries.length > 0) {
  3489. html += `<div class="space-y-3">`;
  3490. periodEntries.forEach(([key, p]) => {
  3491. const merged = mergeWithDefault(p, defaults);
  3492. const colorClass = getBlockColorClass(merged);
  3493. html += `<div class="tl-period-card" id="tl-period-${key}">
  3494. <div class="flex items-center justify-between mb-2">
  3495. <div class="flex items-center gap-2">
  3496. <div class="w-3 h-3 rounded ${colorClass}"></div>
  3497. <span class="text-sm font-bold text-gray-800 tl-editable" ondblclick="tlInlineEditPeriod(this,'${presetName}','${key}','${escapeAttr(p.name || key)}')">${p.name || key}</span>
  3498. <span class="text-[10px] text-gray-400 font-mono">${key}</span>
  3499. </div>
  3500. <div class="flex items-center gap-2">
  3501. <span class="text-xs text-gray-500 font-mono">${p.start || '?'} - ${p.end || '?'}</span>
  3502. <button onclick="duplicateTlPeriod('${presetName}','${key}')" class="tl-inline-btn" title="复制"><i class="fa-regular fa-copy"></i></button>
  3503. <button onclick="deleteTlPeriod('${presetName}','${key}')" class="tl-inline-btn text-red-400 hover:text-red-600" title="删除"><i class="fa-regular fa-trash-can"></i></button>
  3504. </div>
  3505. </div>
  3506. ${renderBehaviorToggles(merged, presetName, key, p)}
  3507. </div>`;
  3508. });
  3509. html += `</div>`;
  3510. } else {
  3511. html += `<div class="text-xs text-gray-400 text-center py-4">
  3512. <i class="fa-solid fa-info-circle mr-1"></i>此模式无自定义时间段,全天使用 default 配置
  3513. </div>`;
  3514. }
  3515. html += `</div>`;
  3516. // ── 日计划 ──
  3517. const dayPlanEntries = Object.entries(dayPlans);
  3518. html += `<div class="mt-6">
  3519. <div class="tl-section-title flex items-center justify-between">
  3520. <span><i class="fa-solid fa-list-ol"></i>日计划 (Day Plans)</span>
  3521. <button onclick="addTlDayPlan('${presetName}')" class="tl-add-btn"><i class="fa-solid fa-plus mr-1"></i>新增</button>
  3522. </div>`;
  3523. if (dayPlanEntries.length > 0) {
  3524. html += `<div class="space-y-2">`;
  3525. dayPlanEntries.forEach(([name, plan]) => {
  3526. const pList = plan.periods || [];
  3527. // 构建可用 period 下拉(排除已添加的)
  3528. const availablePeriods = periodEntries.filter(([k]) => !pList.includes(k));
  3529. html += `<div class="bg-white border border-gray-200 rounded-lg px-3 py-2 tl-dayplan-card">
  3530. <div class="flex items-center justify-between mb-1">
  3531. <span class="text-xs font-bold text-gray-700">${name}</span>
  3532. <button onclick="deleteTlDayPlan('${presetName}','${name}')" class="tl-inline-btn text-red-400 hover:text-red-600" title="删除日计划"><i class="fa-regular fa-trash-can"></i></button>
  3533. </div>
  3534. <div class="flex flex-wrap gap-1 items-center tl-dayplan-sortable" data-plan-key="${name}">
  3535. ${pList.length > 0 ? pList.map(pn => {
  3536. const p = periods[pn];
  3537. const merged = p ? mergeWithDefault(p, defaults) : {};
  3538. const cc = getBlockColorClass(merged);
  3539. return `<span class="tl-period-tag ${cc}" data-period-key="${pn}">
  3540. ${p?.name || pn}
  3541. <button onclick="removePeriodFromDayPlanUI('${presetName}','${name}','${pn}')" class="tl-tag-remove" title="移除">&times;</button>
  3542. </span>`;
  3543. }).join('') : '<span class="text-[10px] text-gray-400">空 (全天走 default)</span>'}
  3544. ${availablePeriods.length > 0 ? `
  3545. <select class="tl-add-period-select" onchange="if(this.value){addPeriodToDayPlan('${presetName}','${name}',this.value);this.value=''}">
  3546. <option value="">+ 添加</option>
  3547. ${availablePeriods.map(([k, p]) => `<option value="${k}">${p.name || k}</option>`).join('')}
  3548. </select>
  3549. ` : ''}
  3550. </div>
  3551. </div>`;
  3552. });
  3553. html += `</div>`;
  3554. }
  3555. html += `</div>`;
  3556. // ── 周映射(下拉选择)──
  3557. const dayPlanKeys = Object.keys(dayPlans);
  3558. // 为不同日计划分配颜色
  3559. const planColorMap = {};
  3560. const planColors = ['bg-blue-50 border-blue-200', 'bg-green-50 border-green-200', 'bg-amber-50 border-amber-200', 'bg-purple-50 border-purple-200', 'bg-rose-50 border-rose-200', 'bg-cyan-50 border-cyan-200', 'bg-orange-50 border-orange-200'];
  3561. dayPlanKeys.forEach((k, idx) => { planColorMap[k] = planColors[idx % planColors.length]; });
  3562. html += `<div class="mt-6">
  3563. <div class="tl-section-title"><i class="fa-solid fa-calendar-days"></i>周映射 (Week Map)</div>
  3564. <div class="bg-white border border-gray-200 rounded-lg px-3 py-2 space-y-1">`;
  3565. for (let d = 1; d <= 7; d++) {
  3566. const plan = weekMap[d] || weekMap[String(d)] || '';
  3567. const rowColor = planColorMap[plan] || '';
  3568. const options = dayPlanKeys.map(k =>
  3569. `<option value="${k}" ${k === plan ? 'selected' : ''}>${k}</option>`
  3570. ).join('');
  3571. html += `<div class="tl-dayplan-row ${rowColor} rounded px-2">
  3572. <div class="tl-dayplan-label">${DAY_NAMES[d-1]}</div>
  3573. <select class="tl-weekmap-select"
  3574. onchange="onTlWeekMap('${presetName}',${d},this.value)">
  3575. ${options}
  3576. </select>
  3577. </div>`;
  3578. }
  3579. html += `</div>
  3580. <div class="flex gap-2 mt-2">
  3581. <button onclick="tlWeekMapQuick('${presetName}','all_same')" class="tl-quick-btn">全周统一</button>
  3582. <button onclick="tlWeekMapQuick('${presetName}','weekday_same')" class="tl-quick-btn">工作日统一</button>
  3583. <button onclick="tlWeekMapQuick('${presetName}','weekday_weekend')" class="tl-quick-btn">工作日/周末</button>
  3584. </div>
  3585. </div>`;
  3586. // custom 专属:时间段冲突策略
  3587. if (isCustom) {
  3588. const overlapPolicy = (config.overlap && config.overlap.policy) || 'error_on_overlap';
  3589. html += `<div class="mt-6">
  3590. <div class="tl-section-title"><i class="fa-solid fa-code-branch"></i>冲突策略 (Overlap)</div>
  3591. <div class="bg-white border border-gray-200 rounded-lg px-3 py-3">
  3592. <div class="flex items-center gap-2">
  3593. <span class="text-xs text-gray-500">policy:</span>
  3594. <select class="text-xs border border-gray-200 rounded px-2 py-1 bg-white"
  3595. onchange="onTlCustomOverlapPolicy(this.value)">
  3596. <option value="error_on_overlap" ${overlapPolicy === 'error_on_overlap' ? 'selected' : ''}>error_on_overlap(推荐)</option>
  3597. <option value="last_wins" ${overlapPolicy === 'last_wins' ? 'selected' : ''}>last_wins(后定义优先)</option>
  3598. </select>
  3599. </div>
  3600. <div class="text-[10px] text-gray-400 mt-2">
  3601. <i class="fa-solid fa-info-circle mr-1"></i>
  3602. <code>error_on_overlap</code> 会在时间段重叠时直接报错;<code>last_wins</code> 会按 day_plans 中靠后的时间段覆盖。
  3603. </div>
  3604. </div>
  3605. </div>`;
  3606. }
  3607. // 提示
  3608. if (!isCustom) {
  3609. html += `<div class="mt-4 text-xs text-gray-400 p-3 bg-gray-50 rounded-lg border border-gray-200">
  3610. <i class="fa-solid fa-lightbulb mr-1 text-amber-400"></i>
  3611. 直接在上方调整开关和下拉框,左侧 YAML 会同步更新。如需更精细的控制,可直接编辑左侧 YAML 或修改 <strong>timeline.yaml</strong>。
  3612. </div>`;
  3613. } else {
  3614. html += `<div class="mt-4 text-xs text-gray-400 p-3 bg-purple-50 rounded-lg border border-purple-200">
  3615. <i class="fa-solid fa-pen-ruler mr-1 text-purple-400"></i>
  3616. 自定义模式支持完全自由编辑。可直接在上方调整控件,或在左侧编辑 YAML 文本,两边实时同步。
  3617. </div>`;
  3618. }
  3619. return html;
  3620. }
  3621. /**
  3622. * 渲染行为开关(可交互)
  3623. * presetName: 当前预设名(用于定位 YAML 中的位置)
  3624. * periodKey: 'default' 或时间段 key(如 'weekday_morning')
  3625. */
  3626. function renderBehaviorToggles(cfg, presetName, periodKey, rawCfg = null) {
  3627. const toggleItems = [
  3628. { k: 'collect', label: '采集', icon: 'fa-download' },
  3629. { k: 'analyze', label: '分析', icon: 'fa-brain' },
  3630. { k: 'push', label: '推送', icon: 'fa-bell' },
  3631. ];
  3632. const uid = `tl-${presetName}-${periodKey}`;
  3633. let html = '<div class="tl-toggle-row">';
  3634. toggleItems.forEach(item => {
  3635. const val = cfg[item.k];
  3636. const on = val === true || val === 'true';
  3637. const toggleId = `${uid}-${item.k}`;
  3638. html += `<label class="tl-toggle-item ${on ? 'on' : 'off'}" for="${toggleId}" style="cursor:pointer">
  3639. <div class="relative inline-block w-8 mr-1 align-middle select-none">
  3640. <input type="checkbox" id="${toggleId}" ${on ? 'checked' : ''}
  3641. onchange="onTlToggle('${presetName}','${periodKey}','${item.k}',this.checked)"
  3642. class="toggle-checkbox absolute block w-4 h-4 rounded-full bg-white border-4 appearance-none cursor-pointer transition-all duration-200 ease-in-out" style="top:0"/>
  3643. <label for="${toggleId}" class="toggle-label block overflow-hidden h-4 rounded-full bg-gray-300 cursor-pointer"></label>
  3644. </div>
  3645. <i class="fa-solid ${item.icon}" style="font-size:10px"></i>${item.label}
  3646. </label>`;
  3647. });
  3648. html += '</div>';
  3649. // 报告模式下拉
  3650. const reportModes = ['current', 'daily', 'incremental'];
  3651. const aiModes = ['follow_report', 'daily', 'current', 'incremental'];
  3652. html += `<div class="flex flex-wrap gap-2 mt-2 items-center">`;
  3653. // report_mode
  3654. html += `<div class="flex items-center gap-1">
  3655. <span class="text-[10px] text-gray-400">报告:</span>
  3656. <select class="text-[10px] border border-gray-200 rounded px-1 py-0.5 bg-white"
  3657. onchange="onTlSelect('${presetName}','${periodKey}','report_mode',this.value)">
  3658. ${reportModes.map(m => `<option value="${m}" ${cfg.report_mode === m ? 'selected' : ''}>${m}</option>`).join('')}
  3659. </select>
  3660. </div>`;
  3661. // ai_mode
  3662. html += `<div class="flex items-center gap-1">
  3663. <span class="text-[10px] text-gray-400">AI:</span>
  3664. <select class="text-[10px] border border-gray-200 rounded px-1 py-0.5 bg-white"
  3665. onchange="onTlSelect('${presetName}','${periodKey}','ai_mode',this.value)">
  3666. ${aiModes.map(m => `<option value="${m}" ${(cfg.ai_mode || 'follow_report') === m ? 'selected' : ''}>${m}</option>`).join('')}
  3667. </select>
  3668. </div>`;
  3669. // once toggles
  3670. const onceAnalyze = cfg.once?.analyze === true;
  3671. const oncePush = cfg.once?.push === true;
  3672. html += `<label class="flex items-center gap-1 text-[10px] ${onceAnalyze ? 'text-blue-600' : 'text-gray-400'}" style="cursor:pointer">
  3673. <input type="checkbox" ${onceAnalyze ? 'checked' : ''}
  3674. onchange="onTlToggle('${presetName}','${periodKey}','once.analyze',this.checked)"
  3675. class="w-3 h-3 rounded">仅分析一次
  3676. </label>`;
  3677. html += `<label class="flex items-center gap-1 text-[10px] ${oncePush ? 'text-blue-600' : 'text-gray-400'}" style="cursor:pointer">
  3678. <input type="checkbox" ${oncePush ? 'checked' : ''}
  3679. onchange="onTlToggle('${presetName}','${periodKey}','once.push',this.checked)"
  3680. class="w-3 h-3 rounded">仅推送一次
  3681. </label>`;
  3682. html += `</div>`;
  3683. // 时间段编辑(仅非 default)
  3684. if (periodKey !== 'default' && (cfg.start || cfg.end)) {
  3685. html += `<div class="flex items-center gap-2 mt-2">
  3686. <span class="text-[10px] text-gray-400">时间:</span>
  3687. <input type="time" value="${cfg.start || ''}" class="text-xs border border-gray-200 rounded px-1.5 py-0.5"
  3688. onchange="onTlSelect('${presetName}','${periodKey}','start',this.value)">
  3689. <span class="text-gray-300">~</span>
  3690. <input type="time" value="${cfg.end || ''}" class="text-xs border border-gray-200 rounded px-1.5 py-0.5"
  3691. onchange="onTlSelect('${presetName}','${periodKey}','end',this.value)">
  3692. </div>`;
  3693. }
  3694. // 可选筛选覆盖(仅显示“当前层”字段,避免把继承值误当作显式配置)
  3695. const baseCfg = rawCfg || {};
  3696. const filterMethod = baseCfg.filter_method || '';
  3697. const frequencyFile = baseCfg.frequency_file || '';
  3698. const interestsFile = baseCfg.interests_file || '';
  3699. const methodHint = periodKey === 'default' ? '不填则跟随全局 filter.method' : '不填则继承 default(再回退全局)';
  3700. html += `<div class="mt-3 pt-3 border-t border-gray-100">
  3701. <div class="text-[10px] uppercase tracking-wider font-bold text-gray-400 mb-2">筛选覆盖(可选)</div>
  3702. <div class="grid grid-cols-1 md:grid-cols-3 gap-2">
  3703. <div>
  3704. <label class="block text-[10px] text-gray-400 mb-1">filter_method</label>
  3705. <select class="text-[10px] w-full border border-gray-200 rounded px-1.5 py-1 bg-white"
  3706. onchange="onTlOptionalSelect('${presetName}','${periodKey}','filter_method',this.value)">
  3707. <option value="" ${filterMethod === '' ? 'selected' : ''}>继承</option>
  3708. <option value="keyword" ${filterMethod === 'keyword' ? 'selected' : ''}>keyword</option>
  3709. <option value="ai" ${filterMethod === 'ai' ? 'selected' : ''}>ai</option>
  3710. </select>
  3711. </div>
  3712. <div>
  3713. <label class="block text-[10px] text-gray-400 mb-1">frequency_file</label>
  3714. <input type="text" value="${frequencyFile}" placeholder="如 tech.txt"
  3715. class="text-[10px] w-full border border-gray-200 rounded px-1.5 py-1 bg-white"
  3716. onchange="onTlOptionalInput('${presetName}','${periodKey}','frequency_file',this.value)">
  3717. </div>
  3718. <div>
  3719. <label class="block text-[10px] text-gray-400 mb-1">interests_file</label>
  3720. <input type="text" value="${interestsFile}" placeholder="如 geopolitics.txt"
  3721. class="text-[10px] w-full border border-gray-200 rounded px-1.5 py-1 bg-white"
  3722. onchange="onTlOptionalInput('${presetName}','${periodKey}','interests_file',this.value)">
  3723. </div>
  3724. </div>
  3725. <div class="text-[10px] text-gray-400 mt-2">
  3726. <i class="fa-solid fa-lightbulb mr-1"></i>${methodHint}。<code>frequency_file</code> 从 <code>config/custom/keyword/</code> 查找,
  3727. <code>interests_file</code> 从 <code>config/custom/ai/</code> 查找;留空会删除该字段并恢复继承。
  3728. </div>
  3729. </div>`;
  3730. return html;
  3731. }
  3732. /**
  3733. * 点击周视图色块 → 滚动到对应 period 卡片并高亮
  3734. */
  3735. window.scrollToPeriodCard = function(periodKey) {
  3736. const card = document.getElementById('tl-period-' + periodKey);
  3737. if (!card) return;
  3738. card.scrollIntoView({ behavior: 'smooth', block: 'center' });
  3739. card.classList.add('tl-period-highlight');
  3740. setTimeout(() => card.classList.remove('tl-period-highlight'), 1500);
  3741. }
  3742. /**
  3743. * 折叠/展开切换
  3744. */
  3745. window.toggleTlCollapsible = function(header) {
  3746. const body = header.nextElementSibling;
  3747. body.classList.toggle('collapsed');
  3748. header.classList.toggle('is-collapsed');
  3749. }
  3750. /**
  3751. * 右侧开关变更 → 更新左侧 timeline YAML
  3752. */
  3753. window.onTlToggle = function(presetName, periodKey, field, value) {
  3754. updateTimelineField(presetName, periodKey, field, value);
  3755. }
  3756. window.onTlSelect = function(presetName, periodKey, field, value) {
  3757. updateTimelineField(presetName, periodKey, field, value);
  3758. }
  3759. window.onTlOptionalInput = function(presetName, periodKey, field, rawValue) {
  3760. const value = (rawValue || '').trim();
  3761. if (!value) {
  3762. removeTimelineField(presetName, periodKey, field);
  3763. return;
  3764. }
  3765. updateTimelineField(presetName, periodKey, field, value);
  3766. }
  3767. window.onTlOptionalSelect = function(presetName, periodKey, field, value) {
  3768. if (!value) {
  3769. removeTimelineField(presetName, periodKey, field);
  3770. return;
  3771. }
  3772. updateTimelineField(presetName, periodKey, field, value);
  3773. }
  3774. window.onTlCustomOverlapPolicy = function(value) {
  3775. updateTimelineSectionField('custom', 'overlap.policy', value);
  3776. }
  3777. /**
  3778. * 周映射下拉变更 → 更新 timeline YAML 中的 week_map.N
  3779. */
  3780. window.onTlWeekMap = function(presetName, dayNum, value) {
  3781. const editor = document.getElementById('timeline-editor');
  3782. let yaml = editor.value;
  3783. const lines = yaml.split('\n');
  3784. // 定位 preset section
  3785. const isCustom = presetName === 'custom';
  3786. let sectionStart = -1;
  3787. let sectionIndent = 0;
  3788. if (isCustom) {
  3789. for (let i = 0; i < lines.length; i++) {
  3790. if (/^custom:\s*/.test(lines[i])) { sectionStart = i; break; }
  3791. }
  3792. } else {
  3793. let inPresets = false;
  3794. for (let i = 0; i < lines.length; i++) {
  3795. const line = lines[i];
  3796. if (/^presets:\s*/.test(line)) { inPresets = true; continue; }
  3797. if (inPresets && /^\S/.test(line) && !line.startsWith('#')) break;
  3798. if (inPresets) {
  3799. const m = line.match(/^(\s+)(\S+):\s*/);
  3800. if (m && m[2] === presetName) { sectionStart = i; sectionIndent = m[1].length; break; }
  3801. }
  3802. }
  3803. }
  3804. if (sectionStart < 0) return;
  3805. let sectionEnd = lines.length;
  3806. for (let i = sectionStart + 1; i < lines.length; i++) {
  3807. const line = lines[i];
  3808. if (line.trim() === '' || line.trim().startsWith('#')) continue;
  3809. if (line.search(/\S/) <= sectionIndent) { sectionEnd = i; break; }
  3810. }
  3811. // 找 week_map: 行
  3812. const weekMapLine = findChildKey(lines, sectionStart, sectionEnd, sectionIndent, 'week_map');
  3813. if (weekMapLine < 0) return;
  3814. const wmIndent = lines[weekMapLine].search(/\S/);
  3815. const wmEnd = findBlockEnd(lines, weekMapLine, wmIndent, sectionEnd);
  3816. // 找 dayNum: 行
  3817. const dayKey = String(dayNum);
  3818. const dayLine = findChildKey(lines, weekMapLine, wmEnd, wmIndent, dayKey);
  3819. if (dayLine >= 0) {
  3820. replaceLineValue(lines, dayLine, value);
  3821. }
  3822. editor.value = lines.join('\n');
  3823. currentTimeline = editor.value;
  3824. updateBackdrop('timeline-editor', 'timeline-backdrop');
  3825. debounceSaveTimeline();
  3826. clearTimeout(window._tlRenderTimer);
  3827. window._tlRenderTimer = setTimeout(() => syncTimelineToUI(), 300);
  3828. }
  3829. /**
  3830. * 核心:修改 timeline YAML 中的指定字段,保留注释
  3831. */
  3832. function updateTimelineField(presetName, periodKey, field, value) {
  3833. const editor = document.getElementById('timeline-editor');
  3834. let yaml = editor.value;
  3835. const lines = yaml.split('\n');
  3836. // 1. 定位预设/custom 的起始行
  3837. const isCustom = presetName === 'custom';
  3838. let sectionStart = -1;
  3839. let sectionIndent = 0;
  3840. if (isCustom) {
  3841. // 找 custom: 顶层 key
  3842. for (let i = 0; i < lines.length; i++) {
  3843. if (/^custom:\s*/.test(lines[i])) {
  3844. sectionStart = i;
  3845. sectionIndent = 0;
  3846. break;
  3847. }
  3848. }
  3849. } else {
  3850. // 找 presets: 下的 presetName:
  3851. let inPresets = false;
  3852. for (let i = 0; i < lines.length; i++) {
  3853. const line = lines[i];
  3854. if (/^presets:\s*/.test(line)) {
  3855. inPresets = true;
  3856. continue;
  3857. }
  3858. if (inPresets && /^\S/.test(line) && !line.startsWith('#')) {
  3859. break; // left presets block
  3860. }
  3861. if (inPresets) {
  3862. const m = line.match(/^(\s+)(\S+):\s*/);
  3863. if (m && m[2] === presetName) {
  3864. sectionStart = i;
  3865. sectionIndent = m[1].length;
  3866. break;
  3867. }
  3868. }
  3869. }
  3870. }
  3871. if (sectionStart < 0) return;
  3872. // 2. 找到 section 结束行
  3873. let sectionEnd = lines.length;
  3874. for (let i = sectionStart + 1; i < lines.length; i++) {
  3875. const line = lines[i];
  3876. if (line.trim() === '' || line.trim().startsWith('#')) continue;
  3877. const indent = line.search(/\S/);
  3878. if (indent <= sectionIndent) {
  3879. sectionEnd = i;
  3880. break;
  3881. }
  3882. }
  3883. // 3. 在 section 内定位 periodKey 子区域
  3884. let targetStart, targetEnd;
  3885. const fieldParts = field.split('.');
  3886. if (periodKey === 'default') {
  3887. // 找 default: 行
  3888. targetStart = findChildKey(lines, sectionStart, sectionEnd, sectionIndent, 'default');
  3889. } else {
  3890. // 找 periods: 下的 periodKey:
  3891. const periodsLine = findChildKey(lines, sectionStart, sectionEnd, sectionIndent, 'periods');
  3892. if (periodsLine < 0) return;
  3893. const periodsIndent = lines[periodsLine].search(/\S/);
  3894. const periodsEnd = findBlockEnd(lines, periodsLine, periodsIndent, sectionEnd);
  3895. targetStart = findChildKey(lines, periodsLine, periodsEnd, periodsIndent, periodKey);
  3896. }
  3897. if (targetStart < 0) return;
  3898. const targetIndent = lines[targetStart].search(/\S/);
  3899. targetEnd = findBlockEnd(lines, targetStart, targetIndent, sectionEnd);
  3900. // 4. 在 target 内查找 field(支持 once.analyze 嵌套)
  3901. let lineIdx = -1;
  3902. if (fieldParts.length === 1) {
  3903. lineIdx = findChildKey(lines, targetStart, targetEnd, targetIndent, fieldParts[0]);
  3904. } else {
  3905. // nested: once.analyze → find once: then analyze:
  3906. const parentLine = findChildKey(lines, targetStart, targetEnd, targetIndent, fieldParts[0]);
  3907. if (parentLine >= 0) {
  3908. const parentIndent = lines[parentLine].search(/\S/);
  3909. const parentEnd = findBlockEnd(lines, parentLine, parentIndent, targetEnd);
  3910. lineIdx = findChildKey(lines, parentLine, parentEnd, parentIndent, fieldParts[1]);
  3911. }
  3912. }
  3913. if (lineIdx < 0) {
  3914. // 字段不存在 → 需要插入
  3915. insertTimelineField(lines, targetStart, targetEnd, targetIndent, field, value, fieldParts);
  3916. } else {
  3917. // 字段存在 → 原地替换值
  3918. replaceLineValue(lines, lineIdx, value);
  3919. }
  3920. editor.value = lines.join('\n');
  3921. currentTimeline = editor.value;
  3922. updateBackdrop('timeline-editor', 'timeline-backdrop');
  3923. debounceSaveTimeline();
  3924. // 延迟重新渲染(避免输入中途刷新)
  3925. clearTimeout(window._tlRenderTimer);
  3926. window._tlRenderTimer = setTimeout(() => syncTimelineToUI(), 300);
  3927. }
  3928. function resolveTimelineSection(lines, presetName) {
  3929. const isCustom = presetName === 'custom';
  3930. let sectionStart = -1;
  3931. let sectionIndent = 0;
  3932. if (isCustom) {
  3933. for (let i = 0; i < lines.length; i++) {
  3934. if (/^custom:\s*/.test(lines[i])) {
  3935. sectionStart = i;
  3936. sectionIndent = 0;
  3937. break;
  3938. }
  3939. }
  3940. } else {
  3941. let inPresets = false;
  3942. for (let i = 0; i < lines.length; i++) {
  3943. const line = lines[i];
  3944. if (/^presets:\s*/.test(line)) {
  3945. inPresets = true;
  3946. continue;
  3947. }
  3948. if (inPresets && /^\S/.test(line) && !line.startsWith('#')) {
  3949. break;
  3950. }
  3951. if (inPresets) {
  3952. const m = line.match(/^(\s+)(\S+):\s*/);
  3953. if (m && m[2] === presetName) {
  3954. sectionStart = i;
  3955. sectionIndent = m[1].length;
  3956. break;
  3957. }
  3958. }
  3959. }
  3960. }
  3961. if (sectionStart < 0) return null;
  3962. let sectionEnd = lines.length;
  3963. for (let i = sectionStart + 1; i < lines.length; i++) {
  3964. const line = lines[i];
  3965. if (line.trim() === '' || line.trim().startsWith('#')) continue;
  3966. const indent = line.search(/\S/);
  3967. if (indent <= sectionIndent) {
  3968. sectionEnd = i;
  3969. break;
  3970. }
  3971. }
  3972. return { sectionStart, sectionEnd, sectionIndent };
  3973. }
  3974. function resolveTimelineTarget(lines, presetName, periodKey) {
  3975. const section = resolveTimelineSection(lines, presetName);
  3976. if (!section) return null;
  3977. const { sectionStart, sectionEnd, sectionIndent } = section;
  3978. let targetStart = -1;
  3979. if (periodKey === 'default') {
  3980. targetStart = findChildKey(lines, sectionStart, sectionEnd, sectionIndent, 'default');
  3981. } else {
  3982. const periodsLine = findChildKey(lines, sectionStart, sectionEnd, sectionIndent, 'periods');
  3983. if (periodsLine < 0) return null;
  3984. const periodsIndent = lines[periodsLine].search(/\S/);
  3985. const periodsEnd = findBlockEnd(lines, periodsLine, periodsIndent, sectionEnd);
  3986. targetStart = findChildKey(lines, periodsLine, periodsEnd, periodsIndent, periodKey);
  3987. }
  3988. if (targetStart < 0) return null;
  3989. const targetIndent = lines[targetStart].search(/\S/);
  3990. const targetEnd = findBlockEnd(lines, targetStart, targetIndent, sectionEnd);
  3991. return { sectionStart, sectionEnd, sectionIndent, targetStart, targetEnd, targetIndent };
  3992. }
  3993. function applyTimelineEditorChanges(editor, lines) {
  3994. editor.value = lines.join('\n');
  3995. currentTimeline = editor.value;
  3996. updateBackdrop('timeline-editor', 'timeline-backdrop');
  3997. debounceSaveTimeline();
  3998. clearTimeout(window._tlRenderTimer);
  3999. window._tlRenderTimer = setTimeout(() => syncTimelineToUI(), 300);
  4000. }
  4001. function removeTimelineField(presetName, periodKey, field) {
  4002. const editor = document.getElementById('timeline-editor');
  4003. const lines = editor.value.split('\n');
  4004. const target = resolveTimelineTarget(lines, presetName, periodKey);
  4005. if (!target) return;
  4006. const { targetStart, targetEnd, targetIndent } = target;
  4007. const fieldParts = field.split('.');
  4008. if (fieldParts.length === 1) {
  4009. const lineIdx = findChildKey(lines, targetStart, targetEnd, targetIndent, fieldParts[0]);
  4010. if (lineIdx < 0) return;
  4011. const lineIndent = lines[lineIdx].search(/\S/);
  4012. const lineEnd = findBlockEnd(lines, lineIdx, lineIndent, targetEnd);
  4013. lines.splice(lineIdx, lineEnd - lineIdx);
  4014. applyTimelineEditorChanges(editor, lines);
  4015. return;
  4016. }
  4017. const parentLine = findChildKey(lines, targetStart, targetEnd, targetIndent, fieldParts[0]);
  4018. if (parentLine < 0) return;
  4019. const parentIndent = lines[parentLine].search(/\S/);
  4020. const parentEnd = findBlockEnd(lines, parentLine, parentIndent, targetEnd);
  4021. const childLine = findChildKey(lines, parentLine, parentEnd, parentIndent, fieldParts[1]);
  4022. if (childLine < 0) return;
  4023. const childIndent = lines[childLine].search(/\S/);
  4024. const childEnd = findBlockEnd(lines, childLine, childIndent, parentEnd);
  4025. lines.splice(childLine, childEnd - childLine);
  4026. const parentEndAfter = findBlockEnd(lines, parentLine, parentIndent, targetEnd);
  4027. let hasChild = false;
  4028. for (let i = parentLine + 1; i < parentEndAfter; i++) {
  4029. const line = lines[i];
  4030. if (line.trim() === '' || line.trim().startsWith('#')) continue;
  4031. if (line.search(/\S/) > parentIndent) {
  4032. hasChild = true;
  4033. break;
  4034. }
  4035. }
  4036. if (!hasChild) {
  4037. lines.splice(parentLine, 1);
  4038. }
  4039. applyTimelineEditorChanges(editor, lines);
  4040. }
  4041. function updateTimelineSectionField(presetName, field, value) {
  4042. const editor = document.getElementById('timeline-editor');
  4043. const lines = editor.value.split('\n');
  4044. const section = resolveTimelineSection(lines, presetName);
  4045. if (!section) return;
  4046. const { sectionStart, sectionEnd, sectionIndent } = section;
  4047. const fieldParts = field.split('.');
  4048. let lineIdx = -1;
  4049. if (fieldParts.length === 1) {
  4050. lineIdx = findChildKey(lines, sectionStart, sectionEnd, sectionIndent, fieldParts[0]);
  4051. } else {
  4052. const parentLine = findChildKey(lines, sectionStart, sectionEnd, sectionIndent, fieldParts[0]);
  4053. if (parentLine >= 0) {
  4054. const parentIndent = lines[parentLine].search(/\S/);
  4055. const parentEnd = findBlockEnd(lines, parentLine, parentIndent, sectionEnd);
  4056. lineIdx = findChildKey(lines, parentLine, parentEnd, parentIndent, fieldParts[1]);
  4057. }
  4058. }
  4059. if (lineIdx < 0) {
  4060. insertTimelineField(lines, sectionStart, sectionEnd, sectionIndent, field, value, fieldParts);
  4061. } else {
  4062. replaceLineValue(lines, lineIdx, value);
  4063. }
  4064. applyTimelineEditorChanges(editor, lines);
  4065. }
  4066. /**
  4067. * 查找子级 key 行
  4068. */
  4069. function findChildKey(lines, start, end, parentIndent, key) {
  4070. for (let i = start + 1; i < end; i++) {
  4071. const line = lines[i];
  4072. if (line.trim() === '' || line.trim().startsWith('#')) continue;
  4073. const indent = line.search(/\S/);
  4074. if (indent <= parentIndent) break;
  4075. const m = line.match(/^\s*(\S+):\s*/);
  4076. if (m && m[1] === key && indent === parentIndent + 2) {
  4077. return i;
  4078. }
  4079. }
  4080. return -1;
  4081. }
  4082. /**
  4083. * 找一个 block 的结束行号(下一个同级或更低缩进的非空非注释行)
  4084. */
  4085. function findBlockEnd(lines, start, indent, maxEnd) {
  4086. for (let i = start + 1; i < maxEnd; i++) {
  4087. const line = lines[i];
  4088. if (line.trim() === '' || line.trim().startsWith('#')) continue;
  4089. const curIndent = line.search(/\S/);
  4090. if (curIndent <= indent) return i;
  4091. }
  4092. return maxEnd;
  4093. }
  4094. /**
  4095. * 替换行中的值,保留注释
  4096. */
  4097. function replaceLineValue(lines, idx, value) {
  4098. const original = lines[idx];
  4099. const match = original.match(/^(\s*\S+:\s*)(.*)$/);
  4100. if (!match) return;
  4101. const prefix = match[1];
  4102. const rest = match[2];
  4103. const commentMatch = rest.match(/(\s*#.*)$/);
  4104. const comment = commentMatch ? commentMatch[1] : '';
  4105. let formatted;
  4106. if (typeof value === 'boolean') {
  4107. formatted = value ? 'true' : 'false';
  4108. } else if (typeof value === 'string') {
  4109. // 检查原值是否带引号
  4110. const valPart = rest.slice(0, rest.length - comment.length).trim();
  4111. const isQuoted = (valPart.startsWith('"') && valPart.endsWith('"')) ||
  4112. (valPart.startsWith("'") && valPart.endsWith("'"));
  4113. if (isQuoted || value.includes(':') || value.includes('#') || value.includes(' ')) {
  4114. formatted = `"${value}"`;
  4115. } else {
  4116. formatted = value;
  4117. }
  4118. } else {
  4119. formatted = String(value);
  4120. }
  4121. lines[idx] = `${prefix}${formatted}${comment}`;
  4122. }
  4123. /**
  4124. * 字段不存在时,插入新行
  4125. */
  4126. function insertTimelineField(lines, targetStart, targetEnd, targetIndent, field, value, fieldParts) {
  4127. const indent = ' '.repeat(targetIndent + 2);
  4128. let formatted;
  4129. if (typeof value === 'boolean') formatted = value ? 'true' : 'false';
  4130. else if (typeof value === 'string') formatted = value.includes(':') ? `"${value}"` : value;
  4131. else formatted = String(value);
  4132. if (fieldParts.length === 1) {
  4133. // 直接在 target 的末尾插入
  4134. lines.splice(targetEnd, 0, `${indent}${field}: ${formatted}`);
  4135. } else {
  4136. // once.analyze → find or create once: block, then insert child
  4137. const parentLine = findChildKey(lines, targetStart, targetEnd, targetIndent, fieldParts[0]);
  4138. if (parentLine >= 0) {
  4139. const parentIndent = lines[parentLine].search(/\S/);
  4140. const parentEnd = findBlockEnd(lines, parentLine, parentIndent, targetEnd);
  4141. const childIndent = ' '.repeat(parentIndent + 2);
  4142. lines.splice(parentEnd, 0, `${childIndent}${fieldParts[1]}: ${formatted}`);
  4143. } else {
  4144. // parent doesn't exist → create both
  4145. lines.splice(targetEnd, 0,
  4146. `${indent}${fieldParts[0]}:`,
  4147. `${indent} ${fieldParts[1]}: ${formatted}`
  4148. );
  4149. }
  4150. }
  4151. }
  4152. /**
  4153. * 点击预设卡片 → 更新 config.yaml 中的 schedule.preset + 滚动左侧编辑器
  4154. */
  4155. window.selectTimelinePreset = function(name) {
  4156. // 更新 config.yaml 中的 schedule.preset
  4157. const configEditor = document.getElementById('yaml-editor');
  4158. let yaml = configEditor.value;
  4159. const lines = yaml.split('\n');
  4160. let presetLineIdx = -1;
  4161. let inSchedule = false;
  4162. for (let i = 0; i < lines.length; i++) {
  4163. const line = lines[i];
  4164. if (/^schedule:\s*$/.test(line.trimEnd()) || /^schedule:\s*#/.test(line)) {
  4165. inSchedule = true;
  4166. continue;
  4167. }
  4168. if (inSchedule && /^\S/.test(line) && !line.startsWith('#')) {
  4169. inSchedule = false;
  4170. }
  4171. if (inSchedule && /^\s+preset:\s*/.test(line)) {
  4172. presetLineIdx = i;
  4173. break;
  4174. }
  4175. }
  4176. if (presetLineIdx >= 0) {
  4177. const original = lines[presetLineIdx];
  4178. const match = original.match(/^(\s*preset:\s*)(.*)$/);
  4179. if (match) {
  4180. const prefix = match[1];
  4181. const rest = match[2];
  4182. const commentMatch = rest.match(/(\s*#.*)$/);
  4183. const comment = commentMatch ? commentMatch[1] : '';
  4184. lines[presetLineIdx] = `${prefix}"${name}"${comment}`;
  4185. }
  4186. }
  4187. configEditor.value = lines.join('\n');
  4188. currentYaml = configEditor.value;
  4189. updateBackdrop('yaml-editor', 'yaml-backdrop');
  4190. debounceSaveConfig();
  4191. // 左侧 timeline 编辑器跳转到对应预设
  4192. scrollTimelineEditorToPreset(name);
  4193. // 重新渲染 timeline 面板
  4194. syncTimelineToUI();
  4195. const tlData = parseTimelineData();
  4196. const tlCfg = getPresetConfig(tlData, name);
  4197. const displayName = tlCfg?.name || name;
  4198. showToast(`已切换至「${displayName}」模式`, 'success');
  4199. }
  4200. /**
  4201. * 滚动左侧 timeline 编辑器到对应预设位置
  4202. */
  4203. function scrollTimelineEditorToPreset(presetName) {
  4204. const editor = document.getElementById('timeline-editor');
  4205. const text = editor.value;
  4206. const lines = text.split('\n');
  4207. let targetLine = -1;
  4208. if (presetName === 'custom') {
  4209. // 找顶层 custom:
  4210. for (let i = 0; i < lines.length; i++) {
  4211. if (/^custom:\s*/.test(lines[i])) {
  4212. targetLine = i;
  4213. break;
  4214. }
  4215. }
  4216. } else {
  4217. // 找 presets: 下的 presetName:
  4218. let inPresets = false;
  4219. for (let i = 0; i < lines.length; i++) {
  4220. const line = lines[i];
  4221. if (/^presets:\s*/.test(line)) {
  4222. inPresets = true;
  4223. continue;
  4224. }
  4225. if (inPresets && /^\S/.test(line) && !line.startsWith('#')) break;
  4226. if (inPresets) {
  4227. const m = line.match(/^\s+(\S+):\s*/);
  4228. if (m && m[1] === presetName) {
  4229. targetLine = i;
  4230. break;
  4231. }
  4232. }
  4233. }
  4234. }
  4235. if (targetLine < 0) return;
  4236. const lineHeight = 19.5;
  4237. const scrollPosition = targetLine * lineHeight;
  4238. // 设置光标位置
  4239. let charCount = 0;
  4240. for (let i = 0; i < targetLine; i++) {
  4241. charCount += lines[i].length + 1;
  4242. }
  4243. editor.focus();
  4244. editor.setSelectionRange(charCount, charCount + lines[targetLine].length);
  4245. editor.scrollTop = scrollPosition - 50;
  4246. // 高亮闪烁(防止快速点击竞态)
  4247. clearTimeout(window._tlEditorFlashTimer);
  4248. editor.style.transition = 'background-color 0.3s';
  4249. editor.style.backgroundColor = '#2d4a7c';
  4250. window._tlEditorFlashTimer = setTimeout(() => { editor.style.backgroundColor = ''; }, 300);
  4251. }
  4252. // ==========================================
  4253. // 14. Timeline CRUD 功能(新建模式/时间段/日计划/删除等)
  4254. // ==========================================
  4255. // ── 弹窗:新建调度模式 ──
  4256. window.openTlNewPresetModal = function() {
  4257. const modal = document.getElementById('tl-new-preset-modal');
  4258. // 填充模板下拉
  4259. const sel = document.getElementById('tl-new-preset-template');
  4260. const data = parseTimelineData();
  4261. sel.innerHTML = '<option value="">空白模板(仅采集,不推送不分析)</option>';
  4262. if (data?.presets) {
  4263. Object.keys(data.presets).forEach(k => {
  4264. const name = data.presets[k]?.name || k;
  4265. sel.innerHTML += `<option value="${k}">${name} (${k})</option>`;
  4266. });
  4267. }
  4268. if (data?.custom) {
  4269. sel.innerHTML += `<option value="custom">${data.custom.name || '自定义'} (custom)</option>`;
  4270. }
  4271. // 清空输入
  4272. document.getElementById('tl-new-preset-key').value = '';
  4273. document.getElementById('tl-new-preset-name').value = '';
  4274. document.getElementById('tl-new-preset-desc').value = '';
  4275. sel.value = '';
  4276. modal.classList.remove('hidden');
  4277. }
  4278. window.closeTlNewPresetModal = function() {
  4279. document.getElementById('tl-new-preset-modal').classList.add('hidden');
  4280. }
  4281. window.confirmTlNewPreset = function() {
  4282. const key = document.getElementById('tl-new-preset-key').value.trim();
  4283. const name = document.getElementById('tl-new-preset-name').value.trim();
  4284. const desc = document.getElementById('tl-new-preset-desc').value.trim();
  4285. const template = document.getElementById('tl-new-preset-template').value;
  4286. // 验证
  4287. if (!key) { showToast('请输入模式标识 (key)', 'error'); return; }
  4288. if (!/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(key)) { showToast('key 仅支持英文、数字和下划线,且不能以数字开头', 'error'); return; }
  4289. if (!name) { showToast('请输入显示名称', 'error'); return; }
  4290. // 检查重复
  4291. const data = parseTimelineData();
  4292. if (data?.presets?.[key]) { showToast(`预设「${key}」已存在`, 'error'); return; }
  4293. if (key === 'custom') { showToast('不能使用 "custom" 作为预设名', 'error'); return; }
  4294. // 构建 YAML 文本块
  4295. let block;
  4296. if (template && data) {
  4297. const src = getPresetConfig(data, template);
  4298. if (src) {
  4299. block = buildPresetYamlBlock(key, { ...src, name: name, description: desc || src.description || '' });
  4300. } else {
  4301. block = buildEmptyPresetBlock(key, name, desc);
  4302. }
  4303. } else {
  4304. block = buildEmptyPresetBlock(key, name, desc);
  4305. }
  4306. // 插入到 timeline YAML 的 presets: 块末尾
  4307. const editor = document.getElementById('timeline-editor');
  4308. let yaml = editor.value;
  4309. const lines = yaml.split('\n');
  4310. // 找 presets: 块的结束位置
  4311. let presetsStart = -1;
  4312. for (let i = 0; i < lines.length; i++) {
  4313. if (/^presets:\s*/.test(lines[i])) { presetsStart = i; break; }
  4314. }
  4315. if (presetsStart < 0) {
  4316. // 没有 presets: 顶层 key,在文件开头插入
  4317. lines.unshift('presets:', ...block.split('\n'));
  4318. } else {
  4319. // 找 presets 块结束(下一个顶层 key)
  4320. let presetsEnd = lines.length;
  4321. for (let i = presetsStart + 1; i < lines.length; i++) {
  4322. if (/^\S/.test(lines[i]) && !lines[i].startsWith('#') && lines[i].trim() !== '') {
  4323. presetsEnd = i;
  4324. break;
  4325. }
  4326. }
  4327. // 在 presetsEnd 前插入(即 presets 块最后)
  4328. const blockLines = block.split('\n');
  4329. lines.splice(presetsEnd, 0, ...blockLines);
  4330. }
  4331. editor.value = lines.join('\n');
  4332. currentTimeline = editor.value;
  4333. updateBackdrop('timeline-editor', 'timeline-backdrop');
  4334. debounceSaveTimeline();
  4335. // 切换 config.yaml 中 preset 为新模式
  4336. selectTimelinePreset(key);
  4337. closeTlNewPresetModal();
  4338. showToast(`调度模式「${name}」创建成功`, 'success');
  4339. }
  4340. /**
  4341. * 构建空白预设 YAML 文本块
  4342. */
  4343. function buildEmptyPresetBlock(key, name, desc) {
  4344. return [
  4345. ` ${key}:`,
  4346. ` name: "${name}"`,
  4347. ` description: "${desc || ''}"`,
  4348. ` default:`,
  4349. ` collect: true`,
  4350. ` analyze: false`,
  4351. ` ai_mode: follow_report`,
  4352. ` push: false`,
  4353. ` report_mode: current`,
  4354. ` once:`,
  4355. ` analyze: false`,
  4356. ` push: false`,
  4357. ` periods: {}`,
  4358. ` day_plans:`,
  4359. ` all_day:`,
  4360. ` periods: []`,
  4361. ` week_map:`,
  4362. ` 1: all_day`,
  4363. ` 2: all_day`,
  4364. ` 3: all_day`,
  4365. ` 4: all_day`,
  4366. ` 5: all_day`,
  4367. ` 6: all_day`,
  4368. ` 7: all_day`,
  4369. ``
  4370. ].join('\n');
  4371. }
  4372. /**
  4373. * 基于已有配置构建预设 YAML 文本块
  4374. */
  4375. function buildPresetYamlBlock(key, cfg) {
  4376. const obj = { [key]: cfg };
  4377. const dumped = jsyaml.dump(obj, { indent: 2, lineWidth: -1, quotingType: '"', forceQuotes: false });
  4378. return dumped.split('\n').map(l => l ? ' ' + l : l).join('\n');
  4379. }
  4380. // ── 弹窗:新增时间段 ──
  4381. let _tlNewPeriodTarget = '';
  4382. window.openTlNewPeriodModal = function(presetName) {
  4383. _tlNewPeriodTarget = presetName;
  4384. document.getElementById('tl-new-period-key').value = '';
  4385. document.getElementById('tl-new-period-name').value = '';
  4386. document.getElementById('tl-new-period-start').value = '09:00';
  4387. document.getElementById('tl-new-period-end').value = '11:00';
  4388. document.getElementById('tl-new-period-modal').classList.remove('hidden');
  4389. }
  4390. window.closeTlNewPeriodModal = function() {
  4391. document.getElementById('tl-new-period-modal').classList.add('hidden');
  4392. }
  4393. window.confirmTlNewPeriod = function() {
  4394. const key = document.getElementById('tl-new-period-key').value.trim();
  4395. const name = document.getElementById('tl-new-period-name').value.trim();
  4396. const start = document.getElementById('tl-new-period-start').value;
  4397. const end = document.getElementById('tl-new-period-end').value;
  4398. if (!key) { showToast('请输入时间段标识 (key)', 'error'); return; }
  4399. if (!/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(key)) { showToast('key 仅支持英文、数字和下划线', 'error'); return; }
  4400. if (!name) { showToast('请输入显示名称', 'error'); return; }
  4401. if (!start || !end) { showToast('请设置开始和结束时间', 'error'); return; }
  4402. if (start === end) { showToast('开始时间和结束时间不能相同', 'error'); return; }
  4403. const data = parseTimelineData();
  4404. const presetCfg = getPresetConfig(data, _tlNewPeriodTarget);
  4405. if (presetCfg?.periods?.[key]) { showToast(`时间段「${key}」已存在`, 'error'); return; }
  4406. const editor = document.getElementById('timeline-editor');
  4407. const lines = editor.value.split('\n');
  4408. const sectionInfo = findPresetSection(lines, _tlNewPeriodTarget);
  4409. if (!sectionInfo) { showToast('未找到预设配置段', 'error'); return; }
  4410. const periodsLine = findChildKey(lines, sectionInfo.start, sectionInfo.end, sectionInfo.indent, 'periods');
  4411. if (periodsLine < 0) { showToast('未找到 periods 配置段', 'error'); return; }
  4412. const periodsIndent = lines[periodsLine].search(/\S/);
  4413. const periodsContent = lines[periodsLine].trim();
  4414. const childIndent = periodsIndent + 2;
  4415. const periodIndent = childIndent + 2;
  4416. const indent = ' '.repeat(childIndent);
  4417. const subIndent = ' '.repeat(periodIndent);
  4418. const newPeriodLines = [
  4419. `${indent}${key}:`,
  4420. `${subIndent}name: "${name}"`,
  4421. `${subIndent}start: "${start}"`,
  4422. `${subIndent}end: "${end}"`,
  4423. `${subIndent}collect: true`,
  4424. `${subIndent}analyze: false`,
  4425. `${subIndent}push: true`,
  4426. `${subIndent}report_mode: current`
  4427. ];
  4428. if (periodsContent === 'periods: {}' || periodsContent === 'periods:{}') {
  4429. lines[periodsLine] = ' '.repeat(periodsIndent) + 'periods:';
  4430. lines.splice(periodsLine + 1, 0, ...newPeriodLines);
  4431. } else {
  4432. const periodsEnd = findBlockEnd(lines, periodsLine, periodsIndent, sectionInfo.end);
  4433. lines.splice(periodsEnd, 0, ...newPeriodLines);
  4434. }
  4435. editor.value = lines.join('\n');
  4436. currentTimeline = editor.value;
  4437. updateBackdrop('timeline-editor', 'timeline-backdrop');
  4438. debounceSaveTimeline();
  4439. closeTlNewPeriodModal();
  4440. syncTimelineToUI();
  4441. showToast(`时间段「${name}」添加成功`, 'success');
  4442. }
  4443. // ── 删除时间段 ──
  4444. window.deleteTlPeriod = function(presetName, periodKey) {
  4445. const data = parseTimelineData();
  4446. const config = getPresetConfig(data, presetName);
  4447. if (!config) return;
  4448. const refs = [];
  4449. const dayPlans = config.day_plans || {};
  4450. Object.entries(dayPlans).forEach(([planName, plan]) => {
  4451. if ((plan.periods || []).includes(periodKey)) refs.push(planName);
  4452. });
  4453. const periodName = config.periods?.[periodKey]?.name || periodKey;
  4454. let msg = `确定删除时间段「${periodName}」?`;
  4455. if (refs.length > 0) {
  4456. msg += `\n\n⚠️ 该时间段被以下日计划引用,将同时移除引用:\n${refs.map(r => ' • ' + r).join('\n')}`;
  4457. }
  4458. if (!confirm(msg)) return;
  4459. const editor = document.getElementById('timeline-editor');
  4460. const lines = editor.value.split('\n');
  4461. const sectionInfo = findPresetSection(lines, presetName);
  4462. if (!sectionInfo) return;
  4463. const periodsLine = findChildKey(lines, sectionInfo.start, sectionInfo.end, sectionInfo.indent, 'periods');
  4464. if (periodsLine >= 0) {
  4465. const periodsIndent = lines[periodsLine].search(/\S/);
  4466. const periodsEnd = findBlockEnd(lines, periodsLine, periodsIndent, sectionInfo.end);
  4467. const periodLine = findChildKey(lines, periodsLine, periodsEnd, periodsIndent, periodKey);
  4468. if (periodLine >= 0) {
  4469. const periodIndent = lines[periodLine].search(/\S/);
  4470. const periodEnd = findBlockEnd(lines, periodLine, periodIndent, periodsEnd);
  4471. lines.splice(periodLine, periodEnd - periodLine);
  4472. }
  4473. }
  4474. if (refs.length > 0) {
  4475. const updatedSection = findPresetSection(lines, presetName);
  4476. if (updatedSection) removePeriodFromDayPlans(lines, updatedSection, periodKey);
  4477. }
  4478. editor.value = lines.join('\n');
  4479. currentTimeline = editor.value;
  4480. updateBackdrop('timeline-editor', 'timeline-backdrop');
  4481. debounceSaveTimeline();
  4482. syncTimelineToUI();
  4483. showToast(`时间段「${periodName}」已删除`, 'success');
  4484. }
  4485. // ── 复制时间段 ──
  4486. window.duplicateTlPeriod = function(presetName, periodKey) {
  4487. const data = parseTimelineData();
  4488. const config = getPresetConfig(data, presetName);
  4489. if (!config?.periods?.[periodKey]) return;
  4490. let newKey = periodKey + '_copy';
  4491. let i = 2;
  4492. while (config.periods[newKey]) { newKey = periodKey + '_copy' + i; i++; }
  4493. const src = config.periods[periodKey];
  4494. const editor = document.getElementById('timeline-editor');
  4495. const lines = editor.value.split('\n');
  4496. const sectionInfo = findPresetSection(lines, presetName);
  4497. if (!sectionInfo) return;
  4498. const periodsLine = findChildKey(lines, sectionInfo.start, sectionInfo.end, sectionInfo.indent, 'periods');
  4499. if (periodsLine < 0) return;
  4500. const periodsIndent = lines[periodsLine].search(/\S/);
  4501. const periodsEnd = findBlockEnd(lines, periodsLine, periodsIndent, sectionInfo.end);
  4502. const srcLine = findChildKey(lines, periodsLine, periodsEnd, periodsIndent, periodKey);
  4503. if (srcLine < 0) return;
  4504. const srcIndent = lines[srcLine].search(/\S/);
  4505. const srcEnd = findBlockEnd(lines, srcLine, srcIndent, periodsEnd);
  4506. const copiedLines = [];
  4507. for (let li = srcLine; li < srcEnd; li++) {
  4508. let line = lines[li];
  4509. if (li === srcLine) {
  4510. line = line.replace(periodKey, newKey);
  4511. }
  4512. copiedLines.push(line);
  4513. }
  4514. for (let li = 0; li < copiedLines.length; li++) {
  4515. const m = copiedLines[li].match(/^(\s*name:\s*).+$/);
  4516. if (m) {
  4517. const newName = (src.name || periodKey) + ' (副本)';
  4518. copiedLines[li] = `${m[1]}"${newName}"`;
  4519. break;
  4520. }
  4521. }
  4522. lines.splice(srcEnd, 0, ...copiedLines);
  4523. editor.value = lines.join('\n');
  4524. currentTimeline = editor.value;
  4525. updateBackdrop('timeline-editor', 'timeline-backdrop');
  4526. debounceSaveTimeline();
  4527. syncTimelineToUI();
  4528. showToast(`已复制为「${newKey}」`, 'success');
  4529. }
  4530. // ── 删除预设模式 ──
  4531. const PROTECTED_PRESETS = ['morning_evening', 'always_on', 'office_hours', 'night_owl'];
  4532. window.deleteTlPreset = function(presetName) {
  4533. if (PROTECTED_PRESETS.includes(presetName)) {
  4534. showToast('内置预设不可删除,可使用复制功能', 'warning');
  4535. return;
  4536. }
  4537. if (presetName === 'custom') {
  4538. showToast('custom 模式不可删除', 'warning');
  4539. return;
  4540. }
  4541. const data = parseTimelineData();
  4542. const cfg = data?.presets?.[presetName];
  4543. const displayName = cfg?.name || presetName;
  4544. if (!confirm(`确定删除调度模式「${displayName}」?\n此操作不可撤销。`)) return;
  4545. const editor = document.getElementById('timeline-editor');
  4546. const lines = editor.value.split('\n');
  4547. const sectionInfo = findPresetSection(lines, presetName);
  4548. if (!sectionInfo) return;
  4549. lines.splice(sectionInfo.start, sectionInfo.end - sectionInfo.start);
  4550. editor.value = lines.join('\n');
  4551. currentTimeline = editor.value;
  4552. updateBackdrop('timeline-editor', 'timeline-backdrop');
  4553. debounceSaveTimeline();
  4554. if (getActivePreset() === presetName) {
  4555. selectTimelinePreset('morning_evening');
  4556. } else {
  4557. syncTimelineToUI();
  4558. }
  4559. showToast(`调度模式「${displayName}」已删除`, 'success');
  4560. }
  4561. // ── 复制预设模式 ──
  4562. window.duplicateTlPreset = function(presetName) {
  4563. const data = parseTimelineData();
  4564. const src = getPresetConfig(data, presetName);
  4565. if (!src) return;
  4566. openTlNewPresetModal();
  4567. const origName = src.name || presetName;
  4568. document.getElementById('tl-new-preset-key').value = presetName + '_copy';
  4569. document.getElementById('tl-new-preset-name').value = origName + ' (副本)';
  4570. document.getElementById('tl-new-preset-desc').value = src.description || '';
  4571. document.getElementById('tl-new-preset-template').value = presetName;
  4572. }
  4573. // ── 新增日计划 ──
  4574. window.addTlDayPlan = function(presetName) {
  4575. const planKey = prompt('请输入日计划标识 (key),如 holiday:');
  4576. if (!planKey) return;
  4577. if (!/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(planKey)) {
  4578. showToast('key 仅支持英文、数字和下划线', 'error');
  4579. return;
  4580. }
  4581. const data = parseTimelineData();
  4582. const config = getPresetConfig(data, presetName);
  4583. if (config?.day_plans?.[planKey]) {
  4584. showToast(`日计划「${planKey}」已存在`, 'error');
  4585. return;
  4586. }
  4587. const editor = document.getElementById('timeline-editor');
  4588. const lines = editor.value.split('\n');
  4589. const sectionInfo = findPresetSection(lines, presetName);
  4590. if (!sectionInfo) return;
  4591. const dayPlansLine = findChildKey(lines, sectionInfo.start, sectionInfo.end, sectionInfo.indent, 'day_plans');
  4592. if (dayPlansLine < 0) return;
  4593. const dpIndent = lines[dayPlansLine].search(/\S/);
  4594. const dpEnd = findBlockEnd(lines, dayPlansLine, dpIndent, sectionInfo.end);
  4595. const indent = ' '.repeat(dpIndent + 2);
  4596. const subIndent = ' '.repeat(dpIndent + 4);
  4597. lines.splice(dpEnd, 0,
  4598. `${indent}${planKey}:`,
  4599. `${subIndent}periods: []`
  4600. );
  4601. editor.value = lines.join('\n');
  4602. currentTimeline = editor.value;
  4603. updateBackdrop('timeline-editor', 'timeline-backdrop');
  4604. debounceSaveTimeline();
  4605. syncTimelineToUI();
  4606. showToast(`日计划「${planKey}」已添加`, 'success');
  4607. }
  4608. // ── 删除日计划 ──
  4609. window.deleteTlDayPlan = function(presetName, planKey) {
  4610. const data = parseTimelineData();
  4611. const config = getPresetConfig(data, presetName);
  4612. if (!config) return;
  4613. const weekMap = config.week_map || {};
  4614. const refs = [];
  4615. for (let d = 1; d <= 7; d++) {
  4616. const v = weekMap[d] || weekMap[String(d)];
  4617. if (v === planKey) refs.push(DAY_NAMES[d - 1]);
  4618. }
  4619. if (refs.length > 0) {
  4620. showToast(`无法删除:「${planKey}」正在被 ${refs.join('、')} 使用。请先修改周映射。`, 'error');
  4621. return;
  4622. }
  4623. if (!confirm(`确定删除日计划「${planKey}」?`)) return;
  4624. const editor = document.getElementById('timeline-editor');
  4625. const lines = editor.value.split('\n');
  4626. const sectionInfo = findPresetSection(lines, presetName);
  4627. if (!sectionInfo) return;
  4628. const dayPlansLine = findChildKey(lines, sectionInfo.start, sectionInfo.end, sectionInfo.indent, 'day_plans');
  4629. if (dayPlansLine < 0) return;
  4630. const dpIndent = lines[dayPlansLine].search(/\S/);
  4631. const dpEnd = findBlockEnd(lines, dayPlansLine, dpIndent, sectionInfo.end);
  4632. const planLine = findChildKey(lines, dayPlansLine, dpEnd, dpIndent, planKey);
  4633. if (planLine < 0) return;
  4634. const planIndent = lines[planLine].search(/\S/);
  4635. const planEnd = findBlockEnd(lines, planLine, planIndent, dpEnd);
  4636. lines.splice(planLine, planEnd - planLine);
  4637. editor.value = lines.join('\n');
  4638. currentTimeline = editor.value;
  4639. updateBackdrop('timeline-editor', 'timeline-backdrop');
  4640. debounceSaveTimeline();
  4641. syncTimelineToUI();
  4642. showToast(`日计划「${planKey}」已删除`, 'success');
  4643. }
  4644. // ── 日计划中添加/移除时间段引用 ──
  4645. window.addPeriodToDayPlan = function(presetName, planKey, periodKey) {
  4646. const editor = document.getElementById('timeline-editor');
  4647. const lines = editor.value.split('\n');
  4648. const sectionInfo = findPresetSection(lines, presetName);
  4649. if (!sectionInfo) return;
  4650. const dayPlansLine = findChildKey(lines, sectionInfo.start, sectionInfo.end, sectionInfo.indent, 'day_plans');
  4651. if (dayPlansLine < 0) return;
  4652. const dpIndent = lines[dayPlansLine].search(/\S/);
  4653. const dpEnd = findBlockEnd(lines, dayPlansLine, dpIndent, sectionInfo.end);
  4654. const planLine = findChildKey(lines, dayPlansLine, dpEnd, dpIndent, planKey);
  4655. if (planLine < 0) return;
  4656. const planIndent = lines[planLine].search(/\S/);
  4657. const planEnd = findBlockEnd(lines, planLine, planIndent, dpEnd);
  4658. const periodsLine = findChildKey(lines, planLine, planEnd, planIndent, 'periods');
  4659. if (periodsLine < 0) return;
  4660. const periodsContent = lines[periodsLine].trim();
  4661. if (periodsContent === 'periods: []' || periodsContent === 'periods:[]') {
  4662. const pIndent = ' '.repeat(lines[periodsLine].search(/\S/));
  4663. lines[periodsLine] = `${pIndent}periods:`;
  4664. lines.splice(periodsLine + 1, 0, `${pIndent} - ${periodKey}`);
  4665. } else {
  4666. const inlineMatch = lines[periodsLine].match(/^(\s*periods:\s*)\[([^\]]*)\]/);
  4667. if (inlineMatch) {
  4668. const existing = inlineMatch[2].split(',').map(s => s.trim()).filter(Boolean);
  4669. // 保持引号风格一致
  4670. const hasQuotes = existing.length > 0 && existing[0].startsWith('"');
  4671. existing.push(hasQuotes ? `"${periodKey}"` : periodKey);
  4672. lines[periodsLine] = `${inlineMatch[1]}[${existing.join(', ')}]`;
  4673. } else {
  4674. const pIndent = ' '.repeat(lines[periodsLine].search(/\S/) + 2);
  4675. const listEnd = findBlockEnd(lines, periodsLine, lines[periodsLine].search(/\S/), planEnd);
  4676. lines.splice(listEnd, 0, `${pIndent}- ${periodKey}`);
  4677. }
  4678. }
  4679. editor.value = lines.join('\n');
  4680. currentTimeline = editor.value;
  4681. updateBackdrop('timeline-editor', 'timeline-backdrop');
  4682. debounceSaveTimeline();
  4683. syncTimelineToUI();
  4684. }
  4685. window.removePeriodFromDayPlanUI = function(presetName, planKey, periodKey) {
  4686. const editor = document.getElementById('timeline-editor');
  4687. const lines = editor.value.split('\n');
  4688. const sectionInfo = findPresetSection(lines, presetName);
  4689. if (!sectionInfo) return;
  4690. removePeriodFromDayPlanInLines(lines, sectionInfo, planKey, periodKey);
  4691. editor.value = lines.join('\n');
  4692. currentTimeline = editor.value;
  4693. updateBackdrop('timeline-editor', 'timeline-backdrop');
  4694. debounceSaveTimeline();
  4695. syncTimelineToUI();
  4696. }
  4697. // ── 周映射快捷操作 ──
  4698. window.tlWeekMapQuick = function(presetName, mode) {
  4699. const data = parseTimelineData();
  4700. const config = getPresetConfig(data, presetName);
  4701. if (!config) return;
  4702. const dayPlanKeys = Object.keys(config.day_plans || {});
  4703. if (dayPlanKeys.length === 0) { showToast('没有可用的日计划', 'error'); return; }
  4704. let mapping = {};
  4705. if (mode === 'all_same') {
  4706. const plan = dayPlanKeys[0];
  4707. for (let d = 1; d <= 7; d++) mapping[d] = plan;
  4708. } else if (mode === 'weekday_same') {
  4709. const plan = dayPlanKeys[0];
  4710. for (let d = 1; d <= 5; d++) mapping[d] = plan;
  4711. const wm = config.week_map || {};
  4712. mapping[6] = wm[6] || wm['6'] || plan;
  4713. mapping[7] = wm[7] || wm['7'] || plan;
  4714. } else if (mode === 'weekday_weekend') {
  4715. if (dayPlanKeys.length < 2) { showToast('需要至少两个日计划来分离工作日/周末', 'warning'); return; }
  4716. const wd = dayPlanKeys[0];
  4717. const we = dayPlanKeys[1];
  4718. for (let d = 1; d <= 5; d++) mapping[d] = wd;
  4719. mapping[6] = we;
  4720. mapping[7] = we;
  4721. }
  4722. for (let d = 1; d <= 7; d++) {
  4723. if (mapping[d]) onTlWeekMap(presetName, d, mapping[d]);
  4724. }
  4725. showToast('周映射已更新', 'success');
  4726. }
  4727. // ── 辅助函数 ──
  4728. /**
  4729. * 定位预设配置段的起始行和结束行
  4730. */
  4731. function findPresetSection(lines, presetName) {
  4732. const isCustom = presetName === 'custom';
  4733. let start = -1;
  4734. let indent = 0;
  4735. if (isCustom) {
  4736. for (let i = 0; i < lines.length; i++) {
  4737. if (/^custom:\s*/.test(lines[i])) { start = i; indent = 0; break; }
  4738. }
  4739. } else {
  4740. let inPresets = false;
  4741. for (let i = 0; i < lines.length; i++) {
  4742. const line = lines[i];
  4743. if (/^presets:\s*/.test(line)) { inPresets = true; continue; }
  4744. if (inPresets && /^\S/.test(line) && !line.startsWith('#') && line.trim() !== '') break;
  4745. if (inPresets) {
  4746. const m = line.match(/^(\s+)(\S+):\s*/);
  4747. if (m && m[2] === presetName) { start = i; indent = m[1].length; break; }
  4748. }
  4749. }
  4750. }
  4751. if (start < 0) return null;
  4752. let end = lines.length;
  4753. for (let i = start + 1; i < lines.length; i++) {
  4754. const line = lines[i];
  4755. if (line.trim() === '' || line.trim().startsWith('#')) continue;
  4756. const curIndent = line.search(/\S/);
  4757. if (curIndent <= indent) { end = i; break; }
  4758. }
  4759. return { start, end, indent };
  4760. }
  4761. /**
  4762. * 从 day_plans 中批量移除对某 period 的引用
  4763. */
  4764. function removePeriodFromDayPlans(lines, sectionInfo, periodKey) {
  4765. const dayPlansLine = findChildKey(lines, sectionInfo.start, sectionInfo.end, sectionInfo.indent, 'day_plans');
  4766. if (dayPlansLine < 0) return;
  4767. const dpIndent = lines[dayPlansLine].search(/\S/);
  4768. const sectionEnd = findBlockEnd(lines, sectionInfo.start, sectionInfo.indent, lines.length);
  4769. const dpEnd = findBlockEnd(lines, dayPlansLine, dpIndent, sectionEnd);
  4770. for (let i = dayPlansLine + 1; i < dpEnd; i++) {
  4771. const line = lines[i];
  4772. if (line.trim() === '' || line.trim().startsWith('#')) continue;
  4773. const listMatch = line.match(/^(\s*)-\s*(\S+)\s*$/);
  4774. if (listMatch && listMatch[2] === periodKey) {
  4775. lines.splice(i, 1);
  4776. i--;
  4777. continue;
  4778. }
  4779. const inlineMatch = line.match(/^(\s*periods:\s*)\[([^\]]*)\]/);
  4780. if (inlineMatch) {
  4781. const items = inlineMatch[2].split(',').map(s => s.trim()).filter(s => {
  4782. const bare = s.replace(/^["']|["']$/g, '');
  4783. return bare && bare !== periodKey;
  4784. });
  4785. lines[i] = items.length > 0
  4786. ? `${inlineMatch[1]}[${items.join(', ')}]`
  4787. : `${inlineMatch[1]}[]`;
  4788. }
  4789. }
  4790. }
  4791. /**
  4792. * 从指定 day_plan 中移除单个 period 引用
  4793. */
  4794. function removePeriodFromDayPlanInLines(lines, sectionInfo, planKey, periodKey) {
  4795. const dayPlansLine = findChildKey(lines, sectionInfo.start, sectionInfo.end, sectionInfo.indent, 'day_plans');
  4796. if (dayPlansLine < 0) return;
  4797. const dpIndent = lines[dayPlansLine].search(/\S/);
  4798. const dpEnd = findBlockEnd(lines, dayPlansLine, dpIndent, sectionInfo.end);
  4799. const planLine = findChildKey(lines, dayPlansLine, dpEnd, dpIndent, planKey);
  4800. if (planLine < 0) return;
  4801. const planIndent = lines[planLine].search(/\S/);
  4802. const planEnd = findBlockEnd(lines, planLine, planIndent, dpEnd);
  4803. const periodsLine = findChildKey(lines, planLine, planEnd, planIndent, 'periods');
  4804. if (periodsLine < 0) return;
  4805. const inlineMatch = lines[periodsLine].match(/^(\s*periods:\s*)\[([^\]]*)\]/);
  4806. if (inlineMatch) {
  4807. const items = inlineMatch[2].split(',').map(s => s.trim()).filter(s => {
  4808. const bare = s.replace(/^["']|["']$/g, '');
  4809. return bare && bare !== periodKey;
  4810. });
  4811. lines[periodsLine] = items.length > 0
  4812. ? `${inlineMatch[1]}[${items.join(', ')}]`
  4813. : `${inlineMatch[1]}[]`;
  4814. return;
  4815. }
  4816. const pEnd = findBlockEnd(lines, periodsLine, lines[periodsLine].search(/\S/), planEnd);
  4817. for (let i = periodsLine + 1; i < pEnd; i++) {
  4818. const m = lines[i].match(/^(\s*)-\s*(\S+)\s*$/);
  4819. if (m && m[2] === periodKey) {
  4820. lines.splice(i, 1);
  4821. return;
  4822. }
  4823. }
  4824. }
  4825. // ==========================================
  4826. // 15. 后续优化功能
  4827. // ==========================================
  4828. // ── 1.3 / 3A.4 内联编辑(双击编辑文本)──
  4829. /**
  4830. * 预设卡片名称/描述内联编辑
  4831. */
  4832. window.tlInlineEdit = function(el, presetName, field, currentValue) {
  4833. if (el.querySelector('input')) return;
  4834. const original = currentValue;
  4835. const isName = field === 'name';
  4836. const input = document.createElement('input');
  4837. input.type = 'text';
  4838. input.value = original;
  4839. input.className = `tl-inline-input ${isName ? 'text-sm font-bold' : 'text-[10px]'}`;
  4840. input.style.width = '100%';
  4841. el.textContent = '';
  4842. el.appendChild(input);
  4843. input.focus();
  4844. input.select();
  4845. const commit = () => {
  4846. const newVal = input.value.trim();
  4847. if (newVal && newVal !== original) {
  4848. updatePresetMeta(presetName, field, newVal);
  4849. }
  4850. syncTimelineToUI();
  4851. };
  4852. input.addEventListener('blur', commit);
  4853. input.addEventListener('keydown', e => {
  4854. if (e.key === 'Enter') { e.preventDefault(); input.blur(); }
  4855. if (e.key === 'Escape') { el.textContent = original; }
  4856. });
  4857. }
  4858. /**
  4859. * 更新预设顶层的 name / description 字段
  4860. */
  4861. function updatePresetMeta(presetName, field, value) {
  4862. const editor = document.getElementById('timeline-editor');
  4863. const lines = editor.value.split('\n');
  4864. const sectionInfo = findPresetSection(lines, presetName);
  4865. if (!sectionInfo) return;
  4866. const lineIdx = findChildKey(lines, sectionInfo.start, sectionInfo.end, sectionInfo.indent, field);
  4867. if (lineIdx >= 0) {
  4868. replaceLineValue(lines, lineIdx, value);
  4869. } else {
  4870. const indent = ' '.repeat(sectionInfo.indent + 2);
  4871. lines.splice(sectionInfo.start + 1, 0, `${indent}${field}: "${value}"`);
  4872. }
  4873. editor.value = lines.join('\n');
  4874. currentTimeline = editor.value;
  4875. updateBackdrop('timeline-editor', 'timeline-backdrop');
  4876. debounceSaveTimeline();
  4877. }
  4878. /**
  4879. * 时间段名称内联编辑
  4880. */
  4881. window.tlInlineEditPeriod = function(el, presetName, periodKey, currentValue) {
  4882. if (el.querySelector('input')) return;
  4883. const original = currentValue;
  4884. const input = document.createElement('input');
  4885. input.type = 'text';
  4886. input.value = original;
  4887. input.className = 'tl-inline-input text-sm font-bold';
  4888. input.style.width = Math.max(80, original.length * 14) + 'px';
  4889. el.textContent = '';
  4890. el.appendChild(input);
  4891. input.focus();
  4892. input.select();
  4893. const commit = () => {
  4894. const newVal = input.value.trim();
  4895. if (newVal && newVal !== original) {
  4896. updateTimelineField(presetName, periodKey, 'name', newVal);
  4897. }
  4898. syncTimelineToUI();
  4899. };
  4900. input.addEventListener('blur', commit);
  4901. input.addEventListener('keydown', e => {
  4902. if (e.key === 'Enter') { e.preventDefault(); input.blur(); }
  4903. if (e.key === 'Escape') { el.textContent = original; }
  4904. });
  4905. }
  4906. // ── 2.2 周视图空白区域点击 → 显示日计划名称 ──
  4907. window.onTlBarClick = function(event, presetName, dayNum) {
  4908. if (event.target.closest('.tl-period-block')) return;
  4909. const data = parseTimelineData();
  4910. const config = getPresetConfig(data, presetName);
  4911. if (!config) return;
  4912. const weekMap = config.week_map || {};
  4913. const planKey = weekMap[dayNum] || weekMap[String(dayNum)] || '(未设置)';
  4914. hideTlTooltip();
  4915. const el = document.createElement('div');
  4916. el.className = 'tl-tooltip';
  4917. el.innerHTML = `<div style="font-weight:700;margin-bottom:2px">${DAY_NAMES[dayNum - 1]}</div>
  4918. <div style="font-size:11px;color:#9ca3af">日计划: <strong style="color:#374151">${planKey}</strong></div>
  4919. <div style="font-size:10px;color:#9ca3af;margin-top:4px">使用 default 配置</div>`;
  4920. document.body.appendChild(el);
  4921. tlTooltipEl = el;
  4922. const rect = event.currentTarget.getBoundingClientRect();
  4923. const x = event.clientX;
  4924. el.style.left = (x - el.offsetWidth / 2) + 'px';
  4925. el.style.top = (rect.top - el.offsetHeight - 8) + 'px';
  4926. const elRect = el.getBoundingClientRect();
  4927. if (elRect.left < 4) el.style.left = '4px';
  4928. if (elRect.right > window.innerWidth - 4) el.style.left = (window.innerWidth - el.offsetWidth - 4) + 'px';
  4929. if (elRect.top < 4) el.style.top = (rect.bottom + 8) + 'px';
  4930. setTimeout(() => { if (tlTooltipEl === el) hideTlTooltip(); }, 2000);
  4931. }
  4932. // ── 3B.5 日计划 Tag 拖拽排序 ──
  4933. /**
  4934. * 为日计划中的 period tag 容器初始化 SortableJS
  4935. */
  4936. function initDayPlanSortable(presetName) {
  4937. document.querySelectorAll('.tl-dayplan-sortable').forEach(container => {
  4938. const planKey = container.dataset.planKey;
  4939. if (!planKey) return;
  4940. new Sortable(container, {
  4941. animation: 150,
  4942. ghostClass: 'tl-tag-ghost',
  4943. dragClass: 'tl-tag-drag',
  4944. draggable: '.tl-period-tag',
  4945. filter: '.tl-add-period-select, .tl-tag-remove',
  4946. preventOnFilter: false,
  4947. onEnd: function() {
  4948. const items = [];
  4949. container.querySelectorAll('.tl-period-tag').forEach(tag => {
  4950. const key = tag.dataset.periodKey;
  4951. if (key) items.push(key);
  4952. });
  4953. reorderDayPlanPeriods(presetName, planKey, items);
  4954. }
  4955. });
  4956. });
  4957. }
  4958. /**
  4959. * 重新排列 day_plan 中 periods 的顺序
  4960. */
  4961. function reorderDayPlanPeriods(presetName, planKey, orderedKeys) {
  4962. const editor = document.getElementById('timeline-editor');
  4963. const lines = editor.value.split('\n');
  4964. const sectionInfo = findPresetSection(lines, presetName);
  4965. if (!sectionInfo) return;
  4966. const dayPlansLine = findChildKey(lines, sectionInfo.start, sectionInfo.end, sectionInfo.indent, 'day_plans');
  4967. if (dayPlansLine < 0) return;
  4968. const dpIndent = lines[dayPlansLine].search(/\S/);
  4969. const dpEnd = findBlockEnd(lines, dayPlansLine, dpIndent, sectionInfo.end);
  4970. const planLine = findChildKey(lines, dayPlansLine, dpEnd, dpIndent, planKey);
  4971. if (planLine < 0) return;
  4972. const planIndent = lines[planLine].search(/\S/);
  4973. const planEnd = findBlockEnd(lines, planLine, planIndent, dpEnd);
  4974. const periodsLine = findChildKey(lines, planLine, planEnd, planIndent, 'periods');
  4975. if (periodsLine < 0) return;
  4976. const inlineMatch = lines[periodsLine].match(/^(\s*periods:\s*)\[([^\]]*)\]/);
  4977. if (inlineMatch) {
  4978. lines[periodsLine] = `${inlineMatch[1]}[${orderedKeys.join(', ')}]`;
  4979. } else {
  4980. const pIndent = lines[periodsLine].search(/\S/);
  4981. const pEnd = findBlockEnd(lines, periodsLine, pIndent, planEnd);
  4982. lines.splice(periodsLine + 1, pEnd - periodsLine - 1);
  4983. const itemIndent = ' '.repeat(pIndent + 2);
  4984. const newItems = orderedKeys.map(k => `${itemIndent}- ${k}`);
  4985. lines.splice(periodsLine + 1, 0, ...newItems);
  4986. }
  4987. editor.value = lines.join('\n');
  4988. currentTimeline = editor.value;
  4989. updateBackdrop('timeline-editor', 'timeline-backdrop');
  4990. debounceSaveTimeline();
  4991. clearTimeout(window._tlRenderTimer);
  4992. window._tlRenderTimer = setTimeout(() => syncTimelineToUI(), 500);
  4993. }
  4994. // ==========================================
  4995. // 支持侧栏 折叠/展开
  4996. // ==========================================
  4997. function toggleSupportSidebar() {
  4998. const wrap = document.querySelector('.support-sidebar-wrap');
  4999. const btn = document.getElementById('sidebar-toggle-btn');
  5000. const isCollapsed = wrap.classList.toggle('collapsed');
  5001. btn.classList.toggle('is-collapsed', isCollapsed);
  5002. btn.title = isCollapsed ? '展开侧栏' : '收起侧栏';
  5003. }