script.js 231 KB

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