script.js 216 KB

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