BetterYTM.user.js 342 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323
  1. // ==UserScript==
  2. // @name BetterYTM
  3. // @namespace https://github.com/Sv443/BetterYTM
  4. // @version 2.0.0
  5. // @description Lots of configurable layout and user experience improvements for YouTube Music™ and YouTube™
  6. // @description:de-DE Konfigurierbare Layout- und Benutzererfahrungs-Verbesserungen für YouTube Music™ und YouTube™
  7. // @description:en-US Configurable layout and user experience improvements for YouTube Music™ and YouTube™
  8. // @description:en-UK Configurable layout and user experience improvements for YouTube Music™ and YouTube™
  9. // @description:es-ES Mejoras de diseño y experiencia de usuario configurables para YouTube Music™ y YouTube™
  10. // @description:fr-FR Améliorations de la mise en page et de l'expérience utilisateur configurables pour YouTube Music™ et YouTube™
  11. // @description:hi-IN YouTube Music™ और YouTube™ के लिए कॉन्फ़िगर करने योग्य लेआउट और उपयोगकर्ता अनुभव में सुधार
  12. // @description:ja-JA YouTube Music™ と YouTube™ の構成可能なレイアウトとユーザー エクスペリエンスの向上
  13. // @description:pt-BR Melhorias configuráveis no layout e na experiência do usuário para o YouTube Music™ e o YouTube™
  14. // @description:zh-CN YouTube Music™ 和 YouTube™ 的可配置布局和用户体验改进
  15. // @homepageURL https://github.com/Sv443/BetterYTM#readme
  16. // @supportURL https://github.com/Sv443/BetterYTM/issues
  17. // @license AGPL-3.0-only
  18. // @author Sv443
  19. // @copyright Sv443 (https://github.com/Sv443)
  20. // @icon https://raw.githubusercontent.com/Sv443/BetterYTM/0e498a95/assets/images/logo/logo_dev_48.png
  21. // @match https://music.youtube.com/*
  22. // @match https://www.youtube.com/*
  23. // @run-at document-start
  24. // @connect api.sv443.net
  25. // @connect github.com
  26. // @connect raw.githubusercontent.com
  27. // @grant GM.getValue
  28. // @grant GM.setValue
  29. // @grant GM.deleteValue
  30. // @grant GM.getResourceUrl
  31. // @grant GM.setClipboard
  32. // @grant GM.xmlHttpRequest
  33. // @grant GM.openInTab
  34. // @grant unsafeWindow
  35. // @noframes
  36. // @resource css-above_queue_btns https://raw.githubusercontent.com/Sv443/BetterYTM/0e498a95/assets/style/aboveQueueBtns.css
  37. // @resource css-anchor_improvements https://raw.githubusercontent.com/Sv443/BetterYTM/0e498a95/assets/style/anchorImprovements.css
  38. // @resource css-auto_like https://raw.githubusercontent.com/Sv443/BetterYTM/0e498a95/assets/style/autoLike.css
  39. // @resource css-bundle https://raw.githubusercontent.com/Sv443/BetterYTM/0e498a95/dist/BetterYTM.css
  40. // @resource css-fix_hdr https://raw.githubusercontent.com/Sv443/BetterYTM/0e498a95/assets/style/fixHDR.css
  41. // @resource css-fix_playerpage_theming https://raw.githubusercontent.com/Sv443/BetterYTM/0e498a95/assets/style/fixPlayerPageTheming.css
  42. // @resource css-fix_spacing https://raw.githubusercontent.com/Sv443/BetterYTM/0e498a95/assets/style/fixSpacing.css
  43. // @resource css-fix_sponsorblock https://raw.githubusercontent.com/Sv443/BetterYTM/0e498a95/assets/style/fixSponsorBlock.css
  44. // @resource css-show_votes https://raw.githubusercontent.com/Sv443/BetterYTM/0e498a95/assets/style/showVotes.css
  45. // @resource css-vol_slider_size https://raw.githubusercontent.com/Sv443/BetterYTM/0e498a95/assets/style/volSliderSize.css
  46. // @resource doc-changelog https://raw.githubusercontent.com/Sv443/BetterYTM/0e498a95/changelog.md
  47. // @resource icon-advanced_mode https://raw.githubusercontent.com/Sv443/BetterYTM/0e498a95/assets/icons/plus_circle_small.svg
  48. // @resource icon-arrow_down https://raw.githubusercontent.com/Sv443/BetterYTM/0e498a95/assets/icons/arrow_down.svg
  49. // @resource icon-auto_like https://raw.githubusercontent.com/Sv443/BetterYTM/0e498a95/assets/icons/auto_like.svg
  50. // @resource icon-auto_like_enabled https://raw.githubusercontent.com/Sv443/BetterYTM/0e498a95/assets/icons/auto_like_enabled.svg
  51. // @resource icon-clear_list https://raw.githubusercontent.com/Sv443/BetterYTM/0e498a95/assets/icons/clear_list.svg
  52. // @resource icon-copy https://raw.githubusercontent.com/Sv443/BetterYTM/0e498a95/assets/icons/copy.svg
  53. // @resource icon-delete https://raw.githubusercontent.com/Sv443/BetterYTM/0e498a95/assets/icons/delete.svg
  54. // @resource icon-edit https://raw.githubusercontent.com/Sv443/BetterYTM/0e498a95/assets/icons/edit.svg
  55. // @resource icon-error https://raw.githubusercontent.com/Sv443/BetterYTM/0e498a95/assets/icons/error.svg
  56. // @resource icon-experimental https://raw.githubusercontent.com/Sv443/BetterYTM/0e498a95/assets/icons/beaker_small.svg
  57. // @resource icon-globe https://raw.githubusercontent.com/Sv443/BetterYTM/0e498a95/assets/icons/globe.svg
  58. // @resource icon-globe_small https://raw.githubusercontent.com/Sv443/BetterYTM/0e498a95/assets/icons/globe_small.svg
  59. // @resource icon-help https://raw.githubusercontent.com/Sv443/BetterYTM/0e498a95/assets/icons/help.svg
  60. // @resource icon-image https://raw.githubusercontent.com/Sv443/BetterYTM/0e498a95/assets/icons/image.svg
  61. // @resource icon-image_filled https://raw.githubusercontent.com/Sv443/BetterYTM/0e498a95/assets/icons/image_filled.svg
  62. // @resource icon-link https://raw.githubusercontent.com/Sv443/BetterYTM/0e498a95/assets/icons/link.svg
  63. // @resource icon-lyrics https://raw.githubusercontent.com/Sv443/BetterYTM/0e498a95/assets/icons/lyrics.svg
  64. // @resource icon-reload https://raw.githubusercontent.com/Sv443/BetterYTM/0e498a95/assets/icons/refresh.svg
  65. // @resource icon-skip_to https://raw.githubusercontent.com/Sv443/BetterYTM/0e498a95/assets/icons/skip_to.svg
  66. // @resource icon-spinner https://raw.githubusercontent.com/Sv443/BetterYTM/0e498a95/assets/icons/spinner.svg
  67. // @resource icon-upload https://raw.githubusercontent.com/Sv443/BetterYTM/0e498a95/assets/icons/upload.svg
  68. // @resource img-close https://raw.githubusercontent.com/Sv443/BetterYTM/0e498a95/assets/images/close.png
  69. // @resource img-discord https://raw.githubusercontent.com/Sv443/BetterYTM/0e498a95/assets/images/external/discord.png
  70. // @resource img-github https://raw.githubusercontent.com/Sv443/BetterYTM/0e498a95/assets/images/external/github.png
  71. // @resource img-greasyfork https://raw.githubusercontent.com/Sv443/BetterYTM/0e498a95/assets/images/external/greasyfork.png
  72. // @resource img-logo https://raw.githubusercontent.com/Sv443/BetterYTM/0e498a95/assets/images/logo/logo_48.png
  73. // @resource img-logo_dev https://raw.githubusercontent.com/Sv443/BetterYTM/0e498a95/assets/images/logo/logo_dev_48.png
  74. // @resource img-openuserjs https://raw.githubusercontent.com/Sv443/BetterYTM/0e498a95/assets/images/external/openuserjs.png
  75. // @resource trans-de_DE https://raw.githubusercontent.com/Sv443/BetterYTM/0e498a95/assets/translations/de_DE.json
  76. // @resource trans-en_UK https://raw.githubusercontent.com/Sv443/BetterYTM/0e498a95/assets/translations/en_UK.json
  77. // @resource trans-en_US https://raw.githubusercontent.com/Sv443/BetterYTM/0e498a95/assets/translations/en_US.json
  78. // @resource trans-es_ES https://raw.githubusercontent.com/Sv443/BetterYTM/0e498a95/assets/translations/es_ES.json
  79. // @resource trans-fr_FR https://raw.githubusercontent.com/Sv443/BetterYTM/0e498a95/assets/translations/fr_FR.json
  80. // @resource trans-hi_IN https://raw.githubusercontent.com/Sv443/BetterYTM/0e498a95/assets/translations/hi_IN.json
  81. // @resource trans-ja_JA https://raw.githubusercontent.com/Sv443/BetterYTM/0e498a95/assets/translations/ja_JA.json
  82. // @resource trans-pt_BR https://raw.githubusercontent.com/Sv443/BetterYTM/0e498a95/assets/translations/pt_BR.json
  83. // @resource trans-zh_CN https://raw.githubusercontent.com/Sv443/BetterYTM/0e498a95/assets/translations/zh_CN.json
  84. // @require https://cdn.jsdelivr.net/npm/@sv443-network/[email protected]/dist/index.global.js
  85. // @require https://cdn.jsdelivr.net/npm/[email protected]/lib/marked.umd.js
  86. // @require https://cdn.jsdelivr.net/npm/[email protected]/lib/umd/index.js
  87. // @require https://cdn.jsdelivr.net/npm/[email protected]
  88. // @grant GM.registerMenuCommand
  89. // @grant GM.listValues
  90. // ==/UserScript==
  91. /*
  92. ▄▄▄ ▄ ▄▄▄▄▄▄ ▄
  93. █ █ ▄▄▄ █ █ ▄▄▄ ▄ ▄█ █ █ █▀▄▀█
  94. █▀▀▄ █▄█ █▀ █▀ █▄█ █▀ █ █ █ █
  95. █▄▄▀ ▀▄▄ ▀▄▄ ▀▄▄ ▀▄▄ █ █ █ █ █
  96. Made with ❤️ by Sv443
  97. I welcome every contribution on GitHub!
  98. https://github.com/Sv443/BetterYTM
  99. */
  100. /* Disclaimer: I am not affiliated with or endorsed by YouTube, Google, Alphabet, Genius or anyone else */
  101. /* C&D this 🖕 */
  102. (function(UserUtils,compareVersions,marked,DOMPurify){'use strict';function _interopNamespaceDefault(e){var n=Object.create(null);if(e){Object.keys(e).forEach(function(k){if(k!=='default'){var d=Object.getOwnPropertyDescriptor(e,k);Object.defineProperty(n,k,d.get?d:{enumerable:true,get:function(){return e[k]}});}})}n.default=e;return Object.freeze(n)}var UserUtils__namespace=/*#__PURE__*/_interopNamespaceDefault(UserUtils);var compareVersions__namespace=/*#__PURE__*/_interopNamespaceDefault(compareVersions);// I know TS enums are impure but it doesn't really matter here, plus imo they are cooler than pure enums anyway
  103. var LogLevel;
  104. (function (LogLevel) {
  105. LogLevel[LogLevel["Debug"] = 0] = "Debug";
  106. LogLevel[LogLevel["Info"] = 1] = "Info";
  107. })(LogLevel || (LogLevel = {}));
  108. //#region plugins
  109. /**
  110. * Intents (permissions) BYTM has to grant your plugin for it to be able to access certain features.
  111. * TODO: this feature is unfinished, but you should still specify the intents your plugin needs.
  112. * Never request more permissions than you need, as this is a bad practice and can lead to your plugin being rejected.
  113. */
  114. var PluginIntent;
  115. (function (PluginIntent) {
  116. /** Plugin has access to hidden config values */
  117. PluginIntent[PluginIntent["HiddenConfigValues"] = 1] = "HiddenConfigValues";
  118. /** Plugin can write to the feature configuration */
  119. PluginIntent[PluginIntent["WriteFeatureConfig"] = 2] = "WriteFeatureConfig";
  120. /** Plugin can write to the lyrics cache */
  121. PluginIntent[PluginIntent["WriteLyricsCache"] = 4] = "WriteLyricsCache";
  122. /** Plugin can add new translations and overwrite existing ones */
  123. PluginIntent[PluginIntent["WriteTranslations"] = 8] = "WriteTranslations";
  124. /** Plugin can create modal dialogs */
  125. PluginIntent[PluginIntent["CreateModalDialogs"] = 16] = "CreateModalDialogs";
  126. /** Plugin can read and write auto-like data */
  127. PluginIntent[PluginIntent["ReadAndWriteAutoLikeData"] = 32] = "ReadAndWriteAutoLikeData";
  128. })(PluginIntent || (PluginIntent = {}));// these variables will have their values replaced by the build script:
  129. const modeRaw = "development";
  130. const branchRaw = "develop";
  131. const hostRaw = "github";
  132. const buildNumberRaw = "0e498a95";
  133. /** The mode in which the script was built (production or development) */
  134. const mode = (modeRaw.match(/^#{{.+}}$/) ? "production" : modeRaw);
  135. /** The branch to use in various URLs that point to the GitHub repo */
  136. const branch = (branchRaw.match(/^#{{.+}}$/) ? "main" : branchRaw);
  137. /** Path to the GitHub repo */
  138. const repo = "Sv443/BetterYTM";
  139. /** Which host the userscript was installed from */
  140. const host = (hostRaw.match(/^#{{.+}}$/) ? "github" : hostRaw);
  141. /** The build number of the userscript */
  142. const buildNumber = (buildNumberRaw.match(/^#{{.+}}$/) ? "BUILD_ERROR!" : buildNumberRaw); // asserted as generic string instead of literal
  143. /** The URL search parameters at the earliest possible time */
  144. const initialParams = new URL(location.href).searchParams;
  145. /** Default compression format used throughout BYTM */
  146. const compressionFormat = "deflate-raw";
  147. /** Whether sessionStorage is available and working */
  148. const sessionStorageAvailable = typeof (sessionStorage === null || sessionStorage === void 0 ? void 0 : sessionStorage.setItem) === "function"
  149. && (() => {
  150. try {
  151. const key = `_bytm_test_${UserUtils.randomId(4, 36)}`;
  152. sessionStorage.setItem(key, "test");
  153. sessionStorage.removeItem(key);
  154. return true;
  155. }
  156. catch (_a) {
  157. return false;
  158. }
  159. })();
  160. /**
  161. * Fallback and initial value of how much info should be logged to the devtools console
  162. * 0 = Debug (show everything) or 1 = Info (show only important stuff)
  163. */
  164. const defaultLogLevel = mode === "production" ? LogLevel.Info : LogLevel.Debug;
  165. /** Info about the userscript, parsed from the userscript header (tools/post-build.js) */
  166. const scriptInfo = {
  167. name: GM.info.script.name,
  168. version: GM.info.script.version,
  169. namespace: GM.info.script.namespace,
  170. };let canCompress$2 = true;
  171. const lyricsCacheMgr = new UserUtils.DataStore({
  172. id: "bytm-lyrics-cache",
  173. defaultData: {
  174. cache: [],
  175. },
  176. formatVersion: 1,
  177. encodeData: (data) => canCompress$2 ? UserUtils.compress(data, compressionFormat, "string") : data,
  178. decodeData: (data) => canCompress$2 ? UserUtils.decompress(data, compressionFormat, "string") : data,
  179. });
  180. async function initLyricsCache() {
  181. canCompress$2 = await compressionSupported();
  182. const data = await lyricsCacheMgr.loadData();
  183. log(`Initialized lyrics cache with ${data.cache.length} entries:`, data);
  184. emitInterface("bytm:lyricsCacheReady");
  185. return data;
  186. }
  187. /**
  188. * Returns the cache entry for the passed artist and song, or undefined if it doesn't exist yet
  189. * {@linkcode artist} and {@linkcode song} need to be sanitized first!
  190. * @param refreshEntry If true, the timestamp of the entry will be set to the current time
  191. */
  192. function getLyricsCacheEntry(artist, song, refreshEntry = true) {
  193. const { cache } = lyricsCacheMgr.getData();
  194. const entry = cache.find(e => e.artist === artist && e.song === song);
  195. if (entry && Date.now() - (entry === null || entry === void 0 ? void 0 : entry.added) > getFeature("lyricsCacheTTL") * 1000 * 60 * 60 * 24) {
  196. deleteLyricsCacheEntry(artist, song);
  197. return undefined;
  198. }
  199. // refresh timestamp of the entry by mutating cache
  200. if (entry && refreshEntry)
  201. updateLyricsCacheEntry(artist, song);
  202. return entry;
  203. }
  204. /** Updates the "last viewed" timestamp of the cache entry for the passed artist and song */
  205. function updateLyricsCacheEntry(artist, song) {
  206. const { cache } = lyricsCacheMgr.getData();
  207. const idx = cache.findIndex(e => e.artist === artist && e.song === song);
  208. if (idx !== -1) {
  209. const newEntry = cache.splice(idx, 1)[0];
  210. newEntry.viewed = Date.now();
  211. log(`Updating cache entry for '${artist} - ${song}' to`, newEntry);
  212. lyricsCacheMgr.setData({ cache: [newEntry, ...cache] });
  213. }
  214. }
  215. /** Deletes the cache entry for the passed artist and song */
  216. function deleteLyricsCacheEntry(artist, song) {
  217. const { cache } = lyricsCacheMgr.getData();
  218. const idx = cache.findIndex(e => e.artist === artist && e.song === song);
  219. if (idx !== -1) {
  220. cache.splice(idx, 1);
  221. lyricsCacheMgr.setData({ cache });
  222. }
  223. }
  224. /** Clears the lyrics cache locally and clears it in persistent storage */
  225. function clearLyricsCache() {
  226. emitInterface("bytm:lyricsCacheCleared");
  227. return lyricsCacheMgr.setData({ cache: [] });
  228. }
  229. /** Returns the full lyrics cache array */
  230. function getLyricsCache() {
  231. return lyricsCacheMgr.getData().cache;
  232. }
  233. /**
  234. * Adds the provided "best" (non-penalized) entry into the lyrics URL cache, synchronously to RAM and asynchronously to GM storage
  235. * {@linkcode artist} and {@linkcode song} need to be sanitized first!
  236. */
  237. function addLyricsCacheEntryBest(artist, song, url) {
  238. // refresh entry if it exists and don't overwrite / duplicate it
  239. const cachedEntry = getLyricsCacheEntry(artist, song, true);
  240. if (cachedEntry)
  241. return;
  242. const { cache } = lyricsCacheMgr.getData();
  243. const entry = {
  244. artist, song, url, viewed: Date.now(), added: Date.now(),
  245. };
  246. cache.push(entry);
  247. cache.sort((a, b) => b.viewed - a.viewed);
  248. // always keep the cache <= max size
  249. cache.splice(getFeature("lyricsCacheMaxSize"));
  250. log("Added cache entry for best result", artist, "-", song, "\n", entry);
  251. emitInterface("bytm:lyricsCacheEntryAdded", { entry, type: "best" });
  252. return lyricsCacheMgr.setData({ cache });
  253. }/** Contains all translation keys of all initialized and loaded translations */
  254. const allTrKeys = new Map();
  255. /** Contains the identifiers of all initialized and loaded translation locales */
  256. const initializedLocales = new Set();
  257. /** Initializes the translations */
  258. async function initTranslations(locale) {
  259. var _a, _b;
  260. if (initializedLocales.has(locale))
  261. return;
  262. initializedLocales.add(locale);
  263. try {
  264. const transFile = await fetchLocaleJson(locale);
  265. let fallbackTrans = {};
  266. if (getFeature("localeFallback"))
  267. fallbackTrans = await fetchLocaleJson("en_US");
  268. // merge with base translations if specified
  269. const baseTransFile = transFile.base ? await fetchLocaleJson(transFile.base) : undefined;
  270. const translations = Object.assign(Object.assign(Object.assign({}, ((_a = fallbackTrans === null || fallbackTrans === void 0 ? void 0 : fallbackTrans.translations) !== null && _a !== void 0 ? _a : {})), ((_b = baseTransFile === null || baseTransFile === void 0 ? void 0 : baseTransFile.translations) !== null && _b !== void 0 ? _b : {})), transFile.translations);
  271. UserUtils.tr.addLanguage(locale, translations);
  272. allTrKeys.set(locale, new Set(Object.keys(translations)));
  273. info(`Loaded translations for locale '${locale}'`);
  274. }
  275. catch (err) {
  276. const errStr = `Couldn't load translations for locale '${locale}'`;
  277. error(errStr, err);
  278. throw new Error(errStr);
  279. }
  280. }
  281. /** Fetches the translation JSON file of the passed locale */
  282. async function fetchLocaleJson(locale) {
  283. const url = await getResourceUrl(`trans-${locale}`);
  284. const res = await UserUtils.fetchAdvanced(url);
  285. if (res.status < 200 || res.status >= 300)
  286. throw new Error(`Failed to fetch translation file for locale '${locale}'`);
  287. return await res.json();
  288. }
  289. /** Sets the current language for translations */
  290. function setLocale(locale) {
  291. UserUtils.tr.setLanguage(locale);
  292. setGlobalProp("locale", locale);
  293. emitInterface("bytm:setLocale", { locale });
  294. }
  295. /** Returns the currently set language */
  296. function getLocale() {
  297. return UserUtils.tr.getLanguage();
  298. }
  299. /** Returns whether the given translation key exists in the current locale */
  300. function hasKey(key) {
  301. return hasKeyFor(getLocale(), key);
  302. }
  303. /** Returns whether the given translation key exists in the given locale */
  304. function hasKeyFor(locale, key) {
  305. var _a, _b;
  306. return (_b = (_a = allTrKeys.get(locale)) === null || _a === void 0 ? void 0 : _a.has(key)) !== null && _b !== void 0 ? _b : false;
  307. }
  308. /** Returns the translated string for the given key, after optionally inserting values */
  309. function t(key, ...values) {
  310. return UserUtils.tr(key, ...values);
  311. }
  312. /**
  313. * Returns the translated string for the given key with an added pluralization identifier based on the passed `num`
  314. * Tries to fall back to the non-pluralized syntax if no translation was found
  315. */
  316. function tp(key, num, ...values) {
  317. if (typeof num !== "number")
  318. num = num.length;
  319. const plNum = num === 1 ? "1" : "n";
  320. const trans = t(`${key}-${plNum}`, ...values);
  321. if (trans === key)
  322. return t(key, ...values);
  323. return trans;
  324. }// hoist the class declaration because either rollup or babel is being a hoe
  325. // TODO: remove export as soon as config menu is migrated to use BytmDialog
  326. /** ID of the last opened (top-most) dialog */
  327. let currentDialogId = null;
  328. /** IDs of all currently open dialogs, top-most first */
  329. const openDialogs = [];
  330. /** TODO: remove as soon as config menu is migrated to use BytmDialog */
  331. const setCurrentDialogId = (id) => currentDialogId = id;
  332. /** Creates and manages a modal dialog element */
  333. class BytmDialog extends UserUtils.NanoEmitter {
  334. constructor(options) {
  335. super();
  336. Object.defineProperty(this, "options", {
  337. enumerable: true,
  338. configurable: true,
  339. writable: true,
  340. value: void 0
  341. });
  342. Object.defineProperty(this, "id", {
  343. enumerable: true,
  344. configurable: true,
  345. writable: true,
  346. value: void 0
  347. });
  348. Object.defineProperty(this, "dialogOpen", {
  349. enumerable: true,
  350. configurable: true,
  351. writable: true,
  352. value: false
  353. });
  354. Object.defineProperty(this, "dialogMounted", {
  355. enumerable: true,
  356. configurable: true,
  357. writable: true,
  358. value: false
  359. });
  360. this.options = Object.assign({ closeOnBgClick: true, closeOnEscPress: true, closeBtnEnabled: true, destroyOnClose: false, unmountOnClose: true, removeListenersOnDestroy: true, smallHeader: false, verticalAlign: "center" }, options);
  361. this.id = options.id;
  362. }
  363. //#region public
  364. /** Call after DOMContentLoaded to pre-render the dialog and invisibly mount it in the DOM */
  365. async mount() {
  366. if (this.dialogMounted)
  367. return;
  368. this.dialogMounted = true;
  369. const bgElem = document.createElement("div");
  370. bgElem.id = `bytm-${this.id}-dialog-bg`;
  371. bgElem.classList.add("bytm-dialog-bg");
  372. if (this.options.closeOnBgClick)
  373. bgElem.ariaLabel = bgElem.title = t("close_menu_tooltip");
  374. bgElem.style.setProperty("--bytm-dialog-width-max", `${this.options.width}px`);
  375. bgElem.style.setProperty("--bytm-dialog-height-max", `${this.options.height}px`);
  376. bgElem.style.visibility = "hidden";
  377. bgElem.style.display = "none";
  378. bgElem.inert = true;
  379. try {
  380. bgElem.appendChild(await this.getDialogContent());
  381. document.body.appendChild(bgElem);
  382. }
  383. catch (e) {
  384. return error("Failed to render dialog content:", e);
  385. }
  386. this.attachListeners(bgElem);
  387. this.events.emit("render");
  388. return bgElem;
  389. }
  390. /** Closes the dialog and clears all its contents (unmounts elements from the DOM) in preparation for a new rendering call */
  391. unmount() {
  392. var _a;
  393. this.close();
  394. this.dialogMounted = false;
  395. const clearSelectors = [
  396. `#bytm-${this.id}-dialog-bg`,
  397. `#bytm-style-dialog-${this.id}`,
  398. ];
  399. for (const sel of clearSelectors) {
  400. const elem = document.querySelector(sel);
  401. (elem === null || elem === void 0 ? void 0 : elem.hasChildNodes()) && clearInner(elem);
  402. (_a = document.querySelector(sel)) === null || _a === void 0 ? void 0 : _a.remove();
  403. }
  404. this.events.emit("clear");
  405. }
  406. /** Clears the DOM of the dialog and then renders it again */
  407. async remount() {
  408. this.unmount();
  409. await this.mount();
  410. }
  411. /**
  412. * Opens the dialog - also mounts it if it hasn't been mounted yet
  413. * Prevents default action and immediate propagation of the passed event
  414. */
  415. async open(e) {
  416. var _a;
  417. e === null || e === void 0 ? void 0 : e.preventDefault();
  418. e === null || e === void 0 ? void 0 : e.stopImmediatePropagation();
  419. if (this.isOpen())
  420. return;
  421. this.dialogOpen = true;
  422. if (openDialogs.includes(this.id)) {
  423. openDialogs.splice(openDialogs.indexOf(this.id), 1);
  424. currentDialogId = (_a = openDialogs[0]) !== null && _a !== void 0 ? _a : null;
  425. this.removeBgInert();
  426. this.close();
  427. throw new Error(`A dialog with the same ID of '${this.id}' already exists and is open!`);
  428. }
  429. if (!this.isMounted())
  430. await this.mount();
  431. this.setBgInert();
  432. const dialogBg = document.querySelector(`#bytm-${this.id}-dialog-bg`);
  433. if (!dialogBg)
  434. return warn(`Couldn't find background element for dialog with ID '${this.id}'`);
  435. dialogBg.style.visibility = "visible";
  436. dialogBg.style.display = "block";
  437. currentDialogId = this.id;
  438. openDialogs.unshift(this.id);
  439. this.events.emit("open");
  440. emitInterface("bytm:dialogOpened", this);
  441. emitInterface(`bytm:dialogOpened:${this.id}`, this);
  442. return dialogBg;
  443. }
  444. /** Closes the dialog - prevents default action and immediate propagation of the passed event */
  445. close(e) {
  446. var _a;
  447. e === null || e === void 0 ? void 0 : e.preventDefault();
  448. e === null || e === void 0 ? void 0 : e.stopImmediatePropagation();
  449. if (!this.isOpen())
  450. return;
  451. this.dialogOpen = false;
  452. const dialogBg = document.querySelector(`#bytm-${this.id}-dialog-bg`);
  453. if (!dialogBg)
  454. return warn(`Couldn't find background element for dialog with ID '${this.id}'`);
  455. dialogBg.style.visibility = "hidden";
  456. dialogBg.style.display = "none";
  457. openDialogs.splice(openDialogs.indexOf(this.id), 1);
  458. currentDialogId = (_a = openDialogs[0]) !== null && _a !== void 0 ? _a : null;
  459. this.removeBgInert();
  460. this.events.emit("close");
  461. emitInterface("bytm:dialogClosed", this);
  462. emitInterface(`bytm:dialogClosed:${this.id}`, this);
  463. if (this.options.destroyOnClose)
  464. this.destroy();
  465. // don't destroy *and* unmount at the same time
  466. else if (this.options.unmountOnClose)
  467. this.unmount();
  468. this.removeBgInert();
  469. }
  470. /** Returns true if the dialog is currently open */
  471. isOpen() {
  472. return this.dialogOpen;
  473. }
  474. /** Returns true if the dialog is currently mounted */
  475. isMounted() {
  476. return this.dialogMounted;
  477. }
  478. /** Clears the DOM of the dialog and removes all event listeners */
  479. destroy() {
  480. this.unmount();
  481. this.events.emit("destroy");
  482. this.options.removeListenersOnDestroy && this.unsubscribeAll();
  483. }
  484. //#region static
  485. /** Returns the ID of the top-most dialog (the dialog that has been opened last) */
  486. static getCurrentDialogId() {
  487. return currentDialogId;
  488. }
  489. /** Returns the IDs of all currently open dialogs, top-most first */
  490. static getOpenDialogs() {
  491. return openDialogs;
  492. }
  493. //#region protected
  494. /** Sets this dialog and the body to be inert and makes sure the top-most dialog is not inert. If no other dialogs are open, the body is not set to be inert. */
  495. removeBgInert() {
  496. var _a, _b, _c;
  497. // make sure the new top-most dialog is not inert
  498. if (currentDialogId) {
  499. // special treatment for the old config menu, as always
  500. if (currentDialogId === "cfg-menu")
  501. (_a = document.querySelector("#bytm-cfg-menu-bg")) === null || _a === void 0 ? void 0 : _a.removeAttribute("inert");
  502. else
  503. (_b = document.querySelector(`#bytm-${currentDialogId}-dialog-bg`)) === null || _b === void 0 ? void 0 : _b.removeAttribute("inert");
  504. }
  505. // remove the scroll lock and inert attribute on the body if no dialogs are open
  506. if (openDialogs.length === 0) {
  507. document.body.classList.remove("bytm-disable-scroll");
  508. (_c = document.querySelector(getDomain() === "ytm" ? "ytmusic-app" : "ytd-app")) === null || _c === void 0 ? void 0 : _c.removeAttribute("inert");
  509. }
  510. const dialogBg = document.querySelector(`#bytm-${this.id}-dialog-bg`);
  511. dialogBg === null || dialogBg === void 0 ? void 0 : dialogBg.setAttribute("inert", "true");
  512. }
  513. /** Sets this dialog to be not inert and the body and all other dialogs to be inert */
  514. setBgInert() {
  515. var _a, _b, _c;
  516. // make sure all other dialogs are inert
  517. for (const dialogId of openDialogs) {
  518. if (dialogId !== this.id) {
  519. // special treatment for the old config menu, as always
  520. if (dialogId === "cfg-menu")
  521. (_a = document.querySelector("#bytm-cfg-menu-bg")) === null || _a === void 0 ? void 0 : _a.setAttribute("inert", "true");
  522. else
  523. (_b = document.querySelector(`#bytm-${dialogId}-dialog-bg`)) === null || _b === void 0 ? void 0 : _b.setAttribute("inert", "true");
  524. }
  525. }
  526. // make sure body is inert and scroll is locked
  527. document.body.classList.add("bytm-disable-scroll");
  528. (_c = document.querySelector(getDomain() === "ytm" ? "ytmusic-app" : "ytd-app")) === null || _c === void 0 ? void 0 : _c.setAttribute("inert", "true");
  529. const dialogBg = document.querySelector(`#bytm-${this.id}-dialog-bg`);
  530. dialogBg === null || dialogBg === void 0 ? void 0 : dialogBg.removeAttribute("inert");
  531. }
  532. /** Called once to attach all generic event listeners */
  533. attachListeners(bgElem) {
  534. if (this.options.closeOnBgClick) {
  535. bgElem.addEventListener("click", (e) => {
  536. var _a;
  537. if (this.isOpen() && ((_a = e.target) === null || _a === void 0 ? void 0 : _a.id) === `bytm-${this.id}-dialog-bg`)
  538. this.close(e);
  539. });
  540. }
  541. if (this.options.closeOnEscPress) {
  542. document.body.addEventListener("keydown", (e) => {
  543. if (e.key === "Escape" && this.isOpen() && BytmDialog.getCurrentDialogId() === this.id)
  544. this.close(e);
  545. });
  546. }
  547. }
  548. /** Returns the dialog content element and all its children */
  549. async getDialogContent() {
  550. var _a, _b, _c, _d;
  551. const header = (_b = (_a = this.options).renderHeader) === null || _b === void 0 ? void 0 : _b.call(_a);
  552. const footer = (_d = (_c = this.options).renderFooter) === null || _d === void 0 ? void 0 : _d.call(_c);
  553. const dialogWrapperEl = document.createElement("div");
  554. dialogWrapperEl.id = `bytm-${this.id}-dialog`;
  555. dialogWrapperEl.classList.add("bytm-dialog");
  556. dialogWrapperEl.ariaLabel = dialogWrapperEl.title = "";
  557. dialogWrapperEl.role = "dialog";
  558. dialogWrapperEl.setAttribute("aria-labelledby", `bytm-${this.id}-dialog-title`);
  559. dialogWrapperEl.setAttribute("aria-describedby", `bytm-${this.id}-dialog-body`);
  560. if (this.options.verticalAlign !== "center")
  561. dialogWrapperEl.classList.add(`align-${this.options.verticalAlign}`);
  562. //#region header
  563. const headerWrapperEl = document.createElement("div");
  564. headerWrapperEl.classList.add("bytm-dialog-header");
  565. this.options.small && headerWrapperEl.classList.add("small");
  566. if (header) {
  567. const headerTitleWrapperEl = document.createElement("div");
  568. headerTitleWrapperEl.id = `bytm-${this.id}-dialog-title`;
  569. headerTitleWrapperEl.classList.add("bytm-dialog-title-wrapper");
  570. headerTitleWrapperEl.role = "heading";
  571. headerTitleWrapperEl.ariaLevel = "1";
  572. headerTitleWrapperEl.appendChild(header instanceof Promise ? await header : header);
  573. headerWrapperEl.appendChild(headerTitleWrapperEl);
  574. }
  575. else {
  576. // insert element to pad the header height
  577. const padEl = document.createElement("div");
  578. padEl.classList.add("bytm-dialog-header-pad");
  579. this.options.small && padEl.classList.add("small");
  580. headerWrapperEl.appendChild(padEl);
  581. }
  582. if (this.options.closeBtnEnabled) {
  583. const closeBtnEl = document.createElement("img");
  584. closeBtnEl.classList.add("bytm-dialog-close");
  585. this.options.small && closeBtnEl.classList.add("small");
  586. closeBtnEl.src = await getResourceUrl("img-close");
  587. closeBtnEl.role = "button";
  588. closeBtnEl.tabIndex = 0;
  589. closeBtnEl.alt = closeBtnEl.title = closeBtnEl.ariaLabel = t("close_menu_tooltip");
  590. onInteraction(closeBtnEl, () => this.close());
  591. headerWrapperEl.appendChild(closeBtnEl);
  592. }
  593. dialogWrapperEl.appendChild(headerWrapperEl);
  594. //#region body
  595. const dialogBodyElem = document.createElement("div");
  596. dialogBodyElem.id = `bytm-${this.id}-dialog-body`;
  597. dialogBodyElem.classList.add("bytm-dialog-body");
  598. this.options.small && dialogBodyElem.classList.add("small");
  599. const body = this.options.renderBody();
  600. dialogBodyElem.appendChild(body instanceof Promise ? await body : body);
  601. dialogWrapperEl.appendChild(dialogBodyElem);
  602. //#region footer
  603. if (footer) {
  604. const footerWrapper = document.createElement("div");
  605. footerWrapper.classList.add("bytm-dialog-footer-cont");
  606. dialogWrapperEl.appendChild(footerWrapper);
  607. footerWrapper.appendChild(footer instanceof Promise ? await footer : footer);
  608. }
  609. return dialogWrapperEl;
  610. }
  611. }/******************************************************************************
  612. Copyright (c) Microsoft Corporation.
  613. Permission to use, copy, modify, and/or distribute this software for any
  614. purpose with or without fee is hereby granted.
  615. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
  616. REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
  617. AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
  618. INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
  619. LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
  620. OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
  621. PERFORMANCE OF THIS SOFTWARE.
  622. ***************************************************************************** */
  623. /* global Reflect, Promise, SuppressedError, Symbol */
  624. function __rest(s, e) {
  625. var t = {};
  626. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
  627. t[p] = s[p];
  628. if (s != null && typeof Object.getOwnPropertySymbols === "function")
  629. for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
  630. if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
  631. t[p[i]] = s[p[i]];
  632. }
  633. return t;
  634. }
  635. function __values(o) {
  636. var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0;
  637. if (m) return m.call(o);
  638. if (o && typeof o.length === "number") return {
  639. next: function () {
  640. if (o && i >= o.length) o = void 0;
  641. return { value: o && o[i++], done: !o };
  642. }
  643. };
  644. throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined.");
  645. }
  646. function __asyncValues(o) {
  647. if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined.");
  648. var m = o[Symbol.asyncIterator], i;
  649. return m ? m.call(o) : (o = typeof __values === "function" ? __values(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i);
  650. function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; }
  651. function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); }
  652. }
  653. typeof SuppressedError === "function" ? SuppressedError : function (error, suppressed, message) {
  654. var e = new Error(message);
  655. return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e;
  656. };/**
  657. * Creates an element with a ripple effect on click.
  658. * @param clickEl If passed, this element will be modified to have the ripple effect. Otherwise, a new element will be created.
  659. * @returns The passed element or the newly created element with the ripple effect.
  660. */
  661. function createRipple(rippleElement, properties) {
  662. const props = Object.assign({ speed: "normal" }, properties);
  663. const rippleEl = rippleElement !== null && rippleElement !== void 0 ? rippleElement : document.createElement("div");
  664. rippleEl.classList.add("bytm-ripple", props.speed);
  665. const updateRippleWidth = () => rippleEl.style.setProperty("--bytm-ripple-cont-width", `${rippleEl.clientWidth}px`);
  666. rippleEl.addEventListener("mousedown", (e) => {
  667. updateRippleWidth();
  668. const x = e.clientX - rippleEl.getBoundingClientRect().left;
  669. const y = e.clientY - rippleEl.getBoundingClientRect().top;
  670. const rippleAreaEl = document.createElement("span");
  671. rippleAreaEl.classList.add("bytm-ripple-area");
  672. rippleAreaEl.style.left = `${Math.round(x)}px`;
  673. rippleAreaEl.style.top = `${Math.round(y)}px`;
  674. if (rippleEl.firstChild)
  675. rippleEl.insertBefore(rippleAreaEl, rippleEl.firstChild);
  676. else
  677. rippleEl.appendChild(rippleAreaEl);
  678. rippleAreaEl.addEventListener("animationend", () => rippleAreaEl.remove());
  679. });
  680. updateRippleWidth();
  681. return rippleEl;
  682. }/**
  683. * Creates a generic, circular button element.
  684. * If `href` is provided, the button will be an anchor element.
  685. * If `onClick` is provided, the button will be a div element.
  686. * Provide either `resourceName` or `src` to specify the icon inside the button.
  687. */
  688. async function createCircularBtn(_a) {
  689. var { title, ripple = true } = _a, rest = __rest(_a, ["title", "ripple"]);
  690. let btnElem;
  691. if ("href" in rest && rest.href) {
  692. btnElem = document.createElement("a");
  693. btnElem.href = rest.href;
  694. btnElem.role = "button";
  695. btnElem.target = "_blank";
  696. btnElem.rel = "noopener noreferrer";
  697. }
  698. else if ("onClick" in rest && rest.onClick) {
  699. btnElem = document.createElement("div");
  700. rest.onClick && onInteraction(btnElem, rest.onClick);
  701. }
  702. else
  703. throw new TypeError("Either 'href' or 'onClick' must be provided");
  704. btnElem.classList.add("bytm-generic-btn");
  705. btnElem.ariaLabel = btnElem.title = title;
  706. btnElem.tabIndex = 0;
  707. btnElem.role = "button";
  708. const imgElem = document.createElement("img");
  709. imgElem.classList.add("bytm-generic-btn-img");
  710. imgElem.src = "src" in rest
  711. ? rest.src instanceof Promise
  712. ? await rest.src
  713. : rest.src
  714. : await getResourceUrl(rest.resourceName);
  715. btnElem.appendChild(imgElem);
  716. return ripple ? createRipple(btnElem) : btnElem;
  717. }const interactionKeys = ["Enter", " ", "Space"];
  718. /**
  719. * Adds generic, accessible interaction listeners to the passed element.
  720. * All listeners have the default behavior prevented and stop propagation (for keyboard events only as long as the captured key is valid).
  721. * @param listenerOptions Provide a {@linkcode listenerOptions} object to configure the listeners
  722. */
  723. function onInteraction(elem, listener, listenerOptions) {
  724. const _a = listenerOptions !== null && listenerOptions !== void 0 ? listenerOptions : {}, { preventDefault = true, stopPropagation = true } = _a, listenerOpts = __rest(_a, ["preventDefault", "stopPropagation"]);
  725. const proxListener = (e) => {
  726. if (e instanceof KeyboardEvent) {
  727. if (interactionKeys.includes(e.key)) {
  728. preventDefault && e.preventDefault();
  729. stopPropagation && e.stopPropagation();
  730. }
  731. else
  732. return;
  733. }
  734. else if (e instanceof MouseEvent) {
  735. preventDefault && e.preventDefault();
  736. stopPropagation && e.stopPropagation();
  737. }
  738. // clean up the other listener that isn't automatically removed if `once` is set
  739. (listenerOpts === null || listenerOpts === void 0 ? void 0 : listenerOpts.once) && e.type === "keydown" && elem.removeEventListener("click", proxListener, listenerOpts);
  740. (listenerOpts === null || listenerOpts === void 0 ? void 0 : listenerOpts.once) && e.type === "click" && elem.removeEventListener("keydown", proxListener, listenerOpts);
  741. listener(e);
  742. };
  743. elem.addEventListener("click", proxListener, listenerOpts);
  744. elem.addEventListener("keydown", proxListener, listenerOpts);
  745. }//#region class
  746. /** Generic dialog for exporting and importing any string of data */
  747. class ExImDialog extends BytmDialog {
  748. constructor(options) {
  749. super(Object.assign({ renderHeader: () => ExImDialog.renderHeader(options), renderBody: () => ExImDialog.renderBody(options), renderFooter: undefined, closeOnBgClick: true, closeOnEscPress: true, closeBtnEnabled: true, unmountOnClose: true, small: true }, options));
  750. }
  751. //#region header
  752. static async renderHeader(opts) {
  753. const headerEl = document.createElement("h2");
  754. headerEl.classList.add("bytm-menu-title");
  755. headerEl.role = "heading";
  756. headerEl.ariaLevel = "1";
  757. headerEl.tabIndex = 0;
  758. headerEl.textContent = headerEl.ariaLabel = typeof opts.title === "function"
  759. ? await opts.title()
  760. : opts.title;
  761. return headerEl;
  762. }
  763. //#region body
  764. static async renderBody(opts) {
  765. const panesCont = document.createElement("div");
  766. panesCont.classList.add("bytm-exim-dialog-panes-cont");
  767. //#region export
  768. const exportPane = document.createElement("div");
  769. exportPane.classList.add("bytm-exim-dialog-pane", "export");
  770. {
  771. const descEl = document.createElement("p");
  772. descEl.classList.add("bytm-exim-dialog-desc");
  773. descEl.role = "note";
  774. descEl.tabIndex = 0;
  775. descEl.textContent = descEl.ariaLabel = typeof opts.descExport === "function"
  776. ? await opts.descExport()
  777. : opts.descExport;
  778. const dataEl = document.createElement("textarea");
  779. dataEl.classList.add("bytm-exim-dialog-data");
  780. dataEl.readOnly = true;
  781. dataEl.tabIndex = 0;
  782. dataEl.value = t("click_to_reveal");
  783. onInteraction(dataEl, async () => {
  784. dataEl.value = typeof opts.exportData === "function" ? await opts.exportData() : opts.exportData;
  785. });
  786. const exportCenterBtnCont = document.createElement("div");
  787. exportCenterBtnCont.classList.add("bytm-exim-dialog-center-btn-cont");
  788. const copyBtn = createRipple(await createLongBtn({
  789. title: t("copy_to_clipboard"),
  790. text: t("copy"),
  791. resourceName: "icon-copy",
  792. async onClick({ shiftKey }) {
  793. const copyData = shiftKey && opts.exportDataSpecial ? opts.exportDataSpecial : opts.exportData;
  794. copyToClipboard(typeof copyData === "function" ? await copyData() : copyData);
  795. await showToast({ message: t("copied_to_clipboard") });
  796. },
  797. }));
  798. exportCenterBtnCont.appendChild(copyBtn);
  799. exportPane.append(descEl, dataEl, exportCenterBtnCont);
  800. }
  801. //#region import
  802. const importPane = document.createElement("div");
  803. importPane.classList.add("bytm-exim-dialog-pane", "import");
  804. {
  805. const descEl = document.createElement("p");
  806. descEl.classList.add("bytm-exim-dialog-desc");
  807. descEl.role = "note";
  808. descEl.tabIndex = 0;
  809. descEl.textContent = descEl.ariaLabel = typeof opts.descImport === "function"
  810. ? await opts.descImport()
  811. : opts.descImport;
  812. const dataEl = document.createElement("textarea");
  813. dataEl.classList.add("bytm-exim-dialog-data");
  814. dataEl.tabIndex = 0;
  815. const importCenterBtnCont = document.createElement("div");
  816. importCenterBtnCont.classList.add("bytm-exim-dialog-center-btn-cont");
  817. const importBtn = createRipple(await createLongBtn({
  818. title: t("start_import_tooltip"),
  819. text: t("import"),
  820. resourceName: "icon-upload",
  821. onClick: () => opts.onImport(dataEl.value),
  822. }));
  823. importCenterBtnCont.appendChild(importBtn);
  824. importPane.append(descEl, dataEl, importCenterBtnCont);
  825. }
  826. panesCont.append(exportPane, importPane);
  827. return panesCont;
  828. }
  829. }/** EventEmitter instance that is used to detect various changes to the site and userscript */
  830. const siteEvents = new UserUtils.NanoEmitter({
  831. publicEmit: true,
  832. });
  833. let observers = [];
  834. let lastWatchId = null;
  835. let lastPathname = null;
  836. let lastFullscreen;
  837. /** Creates MutationObservers that check if parts of the site have changed, then emit an event on the `siteEvents` instance. */
  838. async function initSiteEvents() {
  839. try {
  840. if (getDomain() === "ytm") {
  841. //#region queue
  842. // the queue container always exists so it doesn't need an extra init function
  843. const queueObs = new MutationObserver(([{ addedNodes, removedNodes, target }]) => {
  844. if (addedNodes.length > 0 || removedNodes.length > 0) {
  845. info(`Detected queue change - added nodes: ${[...addedNodes.values()].length} - removed nodes: ${[...removedNodes.values()].length}`);
  846. emitSiteEvent("queueChanged", target);
  847. }
  848. });
  849. // only observe added or removed elements
  850. addSelectorListener("sidePanel", "#contents.ytmusic-player-queue", {
  851. listener: (el) => {
  852. queueObs.observe(el, {
  853. childList: true,
  854. });
  855. },
  856. });
  857. const autoplayObs = new MutationObserver(([{ addedNodes, removedNodes, target }]) => {
  858. if (addedNodes.length > 0 || removedNodes.length > 0) {
  859. info(`Detected autoplay queue change - added nodes: ${[...addedNodes.values()].length} - removed nodes: ${[...removedNodes.values()].length}`);
  860. emitSiteEvent("autoplayQueueChanged", target);
  861. }
  862. });
  863. addSelectorListener("sidePanel", "ytmusic-player-queue #automix-contents", {
  864. listener: (el) => {
  865. autoplayObs.observe(el, {
  866. childList: true,
  867. });
  868. },
  869. });
  870. //#region player bar
  871. let lastTitle = null;
  872. addSelectorListener("playerBarInfo", "yt-formatted-string.title", {
  873. continuous: true,
  874. listener: (titleElem) => {
  875. const oldTitle = lastTitle;
  876. const newTitle = titleElem.textContent;
  877. if (newTitle === lastTitle || !newTitle)
  878. return;
  879. lastTitle = newTitle;
  880. info(`Detected song change - old title: "${oldTitle}" - new title: "${newTitle}"`);
  881. emitSiteEvent("songTitleChanged", newTitle, oldTitle);
  882. runIntervalChecks();
  883. },
  884. });
  885. info("Successfully initialized SiteEvents observers");
  886. observers = observers.concat([
  887. queueObs,
  888. autoplayObs,
  889. ]);
  890. //#region player
  891. const playerFullscreenObs = new MutationObserver(([{ target }]) => {
  892. var _a;
  893. const isFullscreen = ((_a = target.getAttribute("player-ui-state")) === null || _a === void 0 ? void 0 : _a.toUpperCase()) === "FULLSCREEN";
  894. if (lastFullscreen !== isFullscreen || typeof lastFullscreen === "undefined") {
  895. emitSiteEvent("fullscreenToggled", isFullscreen);
  896. lastFullscreen = isFullscreen;
  897. }
  898. });
  899. if (getDomain() === "ytm") {
  900. const registerFullScreenObs = () => addSelectorListener("mainPanel", "ytmusic-player#player", {
  901. listener: (el) => {
  902. playerFullscreenObs.observe(el, {
  903. attributeFilter: ["player-ui-state"],
  904. });
  905. },
  906. });
  907. if (globserversReady)
  908. registerFullScreenObs();
  909. else
  910. window.addEventListener("bytm:observersReady", registerFullScreenObs, { once: true });
  911. }
  912. }
  913. window.addEventListener("bytm:ready", () => {
  914. runIntervalChecks();
  915. setInterval(runIntervalChecks, 100);
  916. if (getDomain() === "ytm") {
  917. addSelectorListener("mainPanel", "ytmusic-player #song-video #movie_player .ytp-title-text > a", {
  918. listener(el) {
  919. const urlRefObs = new MutationObserver(([{ target }]) => {
  920. var _a;
  921. if (!target || !((_a = target === null || target === void 0 ? void 0 : target.href) === null || _a === void 0 ? void 0 : _a.includes("/watch")))
  922. return;
  923. const watchId = new URL(target.href).searchParams.get("v");
  924. checkWatchIdChange(watchId);
  925. });
  926. urlRefObs.observe(el, {
  927. attributeFilter: ["href"],
  928. });
  929. }
  930. });
  931. }
  932. if (getDomain() === "ytm") {
  933. setInterval(checkWatchIdChange, 250);
  934. checkWatchIdChange();
  935. }
  936. }, {
  937. once: true,
  938. });
  939. }
  940. catch (err) {
  941. error("Couldn't initialize site event observers due to an error:\n", err);
  942. }
  943. }
  944. let bytmReady = false;
  945. window.addEventListener("bytm:ready", () => bytmReady = true, { once: true });
  946. /** Emits a site event with the given key and arguments - if `bytm:ready` has not been emitted yet, all events will be queued until it is */
  947. function emitSiteEvent(key, ...args) {
  948. try {
  949. if (!bytmReady) {
  950. window.addEventListener("bytm:ready", () => {
  951. bytmReady = true;
  952. emitSiteEvent(key, ...args);
  953. }, { once: true });
  954. return;
  955. }
  956. siteEvents.emit(key, ...args);
  957. emitInterface(`bytm:siteEvent:${key}`, args);
  958. }
  959. catch (err) {
  960. error(`Couldn't emit site event "${key}" due to an error:\n`, err);
  961. }
  962. }
  963. //#region other
  964. /** Checks if the watch ID has changed and emits a `watchIdChanged` siteEvent if it has */
  965. function checkWatchIdChange(newId) {
  966. const newWatchId = newId !== null && newId !== void 0 ? newId : new URL(location.href).searchParams.get("v");
  967. if (newWatchId && newWatchId !== lastWatchId) {
  968. info(`Detected watch ID change - old ID: "${lastWatchId}" - new ID: "${newWatchId}"`);
  969. emitSiteEvent("watchIdChanged", newWatchId, lastWatchId);
  970. lastWatchId = newWatchId;
  971. }
  972. }
  973. /** Periodically called to check for changes in the URL and emit associated siteEvents */
  974. function runIntervalChecks() {
  975. if (!lastWatchId)
  976. checkWatchIdChange();
  977. if (location.pathname !== lastPathname) {
  978. emitSiteEvent("pathChanged", String(location.pathname), lastPathname);
  979. lastPathname = String(location.pathname);
  980. }
  981. }let otherHotkeyInputActive = false;
  982. const reservedKeys = ["ShiftLeft", "ShiftRight", "ControlLeft", "ControlRight", "AltLeft", "AltRight", "Meta", "Tab", "Space", " "];
  983. /** Creates a hotkey input element */
  984. function createHotkeyInput({ initialValue, onChange, createTitle }) {
  985. var _a;
  986. const initialHotkey = initialValue;
  987. let currentHotkey;
  988. if (!createTitle)
  989. createTitle = (value) => value;
  990. const wrapperElem = document.createElement("div");
  991. wrapperElem.classList.add("bytm-hotkey-wrapper");
  992. const infoElem = document.createElement("span");
  993. infoElem.classList.add("bytm-hotkey-info");
  994. const inputElem = document.createElement("button");
  995. inputElem.role = "button";
  996. inputElem.classList.add("bytm-ftconf-input", "bytm-hotkey-input", "bytm-btn");
  997. inputElem.dataset.state = "inactive";
  998. inputElem.innerText = (_a = initialValue === null || initialValue === void 0 ? void 0 : initialValue.code) !== null && _a !== void 0 ? _a : t("hotkey_input_click_to_change");
  999. inputElem.ariaLabel = inputElem.title = createTitle(hotkeyToString(initialValue));
  1000. const resetElem = document.createElement("span");
  1001. resetElem.classList.add("bytm-hotkey-reset", "bytm-link", "bytm-hidden");
  1002. resetElem.role = "button";
  1003. resetElem.tabIndex = 0;
  1004. resetElem.textContent = `(${t("reset")})`;
  1005. resetElem.ariaLabel = resetElem.title = t("hotkey_input_click_to_reset_tooltip");
  1006. const deactivate = () => {
  1007. var _a;
  1008. if (!otherHotkeyInputActive)
  1009. return;
  1010. emitSiteEvent("hotkeyInputActive", false);
  1011. otherHotkeyInputActive = false;
  1012. const curHk = currentHotkey !== null && currentHotkey !== void 0 ? currentHotkey : initialValue;
  1013. inputElem.innerText = (_a = curHk === null || curHk === void 0 ? void 0 : curHk.code) !== null && _a !== void 0 ? _a : t("hotkey_input_click_to_change");
  1014. inputElem.dataset.state = "inactive";
  1015. inputElem.ariaLabel = inputElem.title = createTitle(hotkeyToString(curHk));
  1016. setInnerHtml(infoElem, curHk ? getHotkeyInfoHtml(curHk) : "");
  1017. };
  1018. const activate = () => {
  1019. if (otherHotkeyInputActive)
  1020. return;
  1021. emitSiteEvent("hotkeyInputActive", true);
  1022. otherHotkeyInputActive = true;
  1023. inputElem.innerText = "< ... >";
  1024. inputElem.dataset.state = "active";
  1025. inputElem.ariaLabel = inputElem.title = t("hotkey_input_click_to_cancel_tooltip");
  1026. };
  1027. const resetClicked = (e) => {
  1028. e.preventDefault();
  1029. e.stopImmediatePropagation();
  1030. onChange(initialValue);
  1031. currentHotkey = initialValue;
  1032. deactivate();
  1033. inputElem.innerText = initialValue.code;
  1034. setInnerHtml(infoElem, getHotkeyInfoHtml(initialValue));
  1035. resetElem.classList.add("bytm-hidden");
  1036. };
  1037. onInteraction(resetElem, resetClicked);
  1038. if (initialValue)
  1039. setInnerHtml(infoElem, getHotkeyInfoHtml(initialValue));
  1040. let lastKeyDown;
  1041. document.addEventListener("keypress", (e) => {
  1042. if (inputElem.dataset.state === "inactive")
  1043. return;
  1044. if ((lastKeyDown === null || lastKeyDown === void 0 ? void 0 : lastKeyDown.code) === e.code && (lastKeyDown === null || lastKeyDown === void 0 ? void 0 : lastKeyDown.shift) === e.shiftKey && (lastKeyDown === null || lastKeyDown === void 0 ? void 0 : lastKeyDown.ctrl) === e.ctrlKey && (lastKeyDown === null || lastKeyDown === void 0 ? void 0 : lastKeyDown.alt) === e.altKey)
  1045. return;
  1046. e.preventDefault();
  1047. e.stopImmediatePropagation();
  1048. const hotkey = {
  1049. code: e.code,
  1050. shift: e.shiftKey,
  1051. ctrl: e.ctrlKey,
  1052. alt: e.altKey,
  1053. };
  1054. inputElem.innerText = hotkey.code;
  1055. inputElem.dataset.state = "inactive";
  1056. setInnerHtml(infoElem, getHotkeyInfoHtml(hotkey));
  1057. inputElem.ariaLabel = inputElem.title = t("hotkey_input_click_to_cancel_tooltip");
  1058. onChange(hotkey);
  1059. currentHotkey = hotkey;
  1060. });
  1061. document.addEventListener("keydown", (e) => {
  1062. if (reservedKeys.filter(k => k !== "Tab").includes(e.code))
  1063. return;
  1064. if (inputElem.dataset.state !== "active")
  1065. return;
  1066. if (e.code === "Tab" || e.code === " " || e.code === "Space" || e.code === "Escape" || e.code === "Enter") {
  1067. deactivate();
  1068. return;
  1069. }
  1070. if (["ShiftLeft", "ShiftRight", "ControlLeft", "ControlRight", "AltLeft", "AltRight"].includes(e.code))
  1071. return;
  1072. e.preventDefault();
  1073. e.stopImmediatePropagation();
  1074. const hotkey = {
  1075. code: e.code,
  1076. shift: e.shiftKey,
  1077. ctrl: e.ctrlKey,
  1078. alt: e.altKey,
  1079. };
  1080. const keyChanged = (initialHotkey === null || initialHotkey === void 0 ? void 0 : initialHotkey.code) !== hotkey.code || (initialHotkey === null || initialHotkey === void 0 ? void 0 : initialHotkey.shift) !== hotkey.shift || (initialHotkey === null || initialHotkey === void 0 ? void 0 : initialHotkey.ctrl) !== hotkey.ctrl || (initialHotkey === null || initialHotkey === void 0 ? void 0 : initialHotkey.alt) !== hotkey.alt;
  1081. lastKeyDown = hotkey;
  1082. onChange(hotkey);
  1083. currentHotkey = hotkey;
  1084. if (keyChanged) {
  1085. deactivate();
  1086. resetElem.classList.remove("bytm-hidden");
  1087. }
  1088. else
  1089. resetElem.classList.add("bytm-hidden");
  1090. inputElem.innerText = hotkey.code;
  1091. inputElem.dataset.state = "inactive";
  1092. setInnerHtml(infoElem, getHotkeyInfoHtml(hotkey));
  1093. });
  1094. siteEvents.on("cfgMenuClosed", deactivate);
  1095. inputElem.addEventListener("click", () => {
  1096. if (inputElem.dataset.state === "inactive")
  1097. activate();
  1098. else
  1099. deactivate();
  1100. });
  1101. inputElem.addEventListener("keydown", (e) => {
  1102. if (reservedKeys.includes(e.code))
  1103. return;
  1104. if (inputElem.dataset.state === "inactive")
  1105. activate();
  1106. });
  1107. wrapperElem.appendChild(resetElem);
  1108. wrapperElem.appendChild(infoElem);
  1109. wrapperElem.appendChild(inputElem);
  1110. return wrapperElem;
  1111. }
  1112. /** Returns HTML for the hotkey modifier keys info element */
  1113. function getHotkeyInfoHtml(hotkey) {
  1114. const modifiers = [];
  1115. hotkey.ctrl && modifiers.push(`<kbd class="bytm-kbd">${t("hotkey_key_ctrl")}</kbd>`);
  1116. hotkey.shift && modifiers.push(`<kbd class="bytm-kbd">${t("hotkey_key_shift")}</kbd>`);
  1117. hotkey.alt && modifiers.push(`<kbd class="bytm-kbd">${getOS() === "mac" ? t("hotkey_key_mac_option") : t("hotkey_key_alt")}</kbd>`);
  1118. return `\
  1119. <div style="display: flex; align-items: center;">
  1120. <span>
  1121. ${modifiers.reduce((a, c) => `${a ? a + " " : ""}${c}`, "")}
  1122. </span>
  1123. <span style="padding: 0px 5px;">
  1124. ${modifiers.length > 0 ? "+" : ""}
  1125. </span>
  1126. </div>`;
  1127. }
  1128. /** Crude OS detection for keyboard layout purposes */
  1129. function getOS() {
  1130. if (navigator.userAgent.match(/mac(\s?os|intel)/i))
  1131. return "mac";
  1132. return "other";
  1133. }
  1134. /** Converts a hotkey object to a string */
  1135. function hotkeyToString(hotkey) {
  1136. if (!hotkey)
  1137. return t("hotkey_key_none");
  1138. let str = "";
  1139. if (hotkey.ctrl)
  1140. str += `${t("hotkey_key_ctrl")}+`;
  1141. if (hotkey.shift)
  1142. str += `${t("hotkey_key_shift")}+`;
  1143. if (hotkey.alt)
  1144. str += `${getOS() === "mac" ? t("hotkey_key_mac_option") : t("hotkey_key_alt")}+`;
  1145. str += hotkey.code;
  1146. return str;
  1147. }/**
  1148. * Creates a generic, circular, long button element with an icon and text.
  1149. * Has classes for the enabled and disabled states for easier styling.
  1150. * If `href` is provided, the button will be an anchor element.
  1151. * If `onClick` or `onToggle` is provided, the button will be a div element.
  1152. * Provide either `resourceName` or `src` to specify the icon inside the button.
  1153. */
  1154. async function createLongBtn(_a) {
  1155. var _b;
  1156. var { title, text, iconPosition, ripple } = _a, rest = __rest(_a, ["title", "text", "iconPosition", "ripple"]);
  1157. if (["href", "onClick", "onToggle"].every((key) => !(key in rest)))
  1158. throw new TypeError("Either 'href', 'onClick' or 'onToggle' must be provided");
  1159. let btnElem;
  1160. if ("href" in rest && rest.href) {
  1161. btnElem = document.createElement("a");
  1162. btnElem.href = rest.href;
  1163. btnElem.role = "button";
  1164. btnElem.target = "_blank";
  1165. btnElem.rel = "noopener noreferrer";
  1166. }
  1167. else
  1168. btnElem = document.createElement("div");
  1169. if ("toggle" in rest && rest.toggle) {
  1170. btnElem.classList.add("bytm-toggle");
  1171. if ("toggleInitialState" in rest && rest.toggleInitialState)
  1172. btnElem.classList.add("toggled");
  1173. }
  1174. onInteraction(btnElem, (evt) => {
  1175. var _a;
  1176. if ("onClick" in rest)
  1177. rest.onClick(evt);
  1178. if ("toggle" in rest && rest.toggle && ((_a = rest.togglePredicate) !== null && _a !== void 0 ? _a : (() => true))(evt))
  1179. rest.onToggle(btnElem.classList.toggle("toggled"), evt);
  1180. });
  1181. btnElem.classList.add("bytm-generic-btn", "long");
  1182. btnElem.ariaLabel = btnElem.title = title;
  1183. btnElem.tabIndex = 0;
  1184. btnElem.role = "button";
  1185. const imgElem = document.createElement("src" in rest ? "img" : "div");
  1186. imgElem.classList.add("bytm-generic-btn-img", iconPosition !== null && iconPosition !== void 0 ? iconPosition : "left");
  1187. if ("src" in rest)
  1188. imgElem.src = rest.src;
  1189. else
  1190. setInnerHtml(imgElem, (_b = await resourceAsString(rest.resourceName)) !== null && _b !== void 0 ? _b : "");
  1191. const txtElem = document.createElement("span");
  1192. txtElem.classList.add("bytm-generic-long-btn-txt", "bytm-no-select");
  1193. txtElem.textContent = txtElem.ariaLabel = text;
  1194. iconPosition === "left" || !iconPosition && btnElem.appendChild(imgElem);
  1195. btnElem.appendChild(txtElem);
  1196. iconPosition === "right" && btnElem.appendChild(imgElem);
  1197. return ripple ? createRipple(btnElem, { speed: "normal" }) : btnElem;
  1198. }class MarkdownDialog extends BytmDialog {
  1199. constructor(options) {
  1200. super(Object.assign(Object.assign({}, options), { id: `md-${options.id}`, renderBody: () => this.renderBody() }));
  1201. Object.defineProperty(this, "opts", {
  1202. enumerable: true,
  1203. configurable: true,
  1204. writable: true,
  1205. value: void 0
  1206. });
  1207. this.opts = options;
  1208. }
  1209. /** Parses the passed markdown string (supports GitHub flavor and HTML mixins) and returns it as an HTML string */
  1210. static async parseMd(md) {
  1211. return await marked.marked.parse(md, {
  1212. async: true,
  1213. gfm: true,
  1214. breaks: true,
  1215. });
  1216. }
  1217. /** Renders the dialog body elements from a markdown string using what's set in `this.opts.body` */
  1218. async renderBody() {
  1219. const bodyEl = document.createElement("div");
  1220. bodyEl.classList.add("bytm-md-dialog-body");
  1221. const mdCont = typeof this.opts.body === "string"
  1222. ? this.opts.body
  1223. : await this.opts.body();
  1224. const markdownEl = document.createElement("div");
  1225. markdownEl.classList.add("bytm-markdown-dialog-content", "bytm-markdown-container");
  1226. markdownEl.tabIndex = 0;
  1227. setInnerHtml(markdownEl, await MarkdownDialog.parseMd(mdCont));
  1228. bodyEl.appendChild(markdownEl);
  1229. return bodyEl;
  1230. }
  1231. }/** Max amount of seconds a toast can be shown for */
  1232. const maxToastDuration = 30000;
  1233. let timeout;
  1234. /** Shows a toast message with an icon */
  1235. async function showIconToast(_a) {
  1236. var { duration, position = "tr", iconPos = "left" } = _a, rest = __rest(_a, ["duration", "position", "iconPos"]);
  1237. if (typeof duration !== "number" || isNaN(duration))
  1238. duration = getFeature("toastDuration") * 1000;
  1239. if (duration <= 0)
  1240. return info("Toast duration is <= 0, so it won't be shown");
  1241. const toastWrapper = document.createElement("div");
  1242. toastWrapper.classList.add("bytm-toast-flex-wrapper");
  1243. let toastIcon;
  1244. if ("iconSrc" in rest) {
  1245. toastIcon = document.createElement("img");
  1246. toastIcon.classList.add("bytm-toast-icon", "img");
  1247. toastIcon.src = rest.iconSrc instanceof Promise
  1248. ? await rest.iconSrc
  1249. : rest.iconSrc;
  1250. }
  1251. else {
  1252. toastIcon = document.createElement("div");
  1253. toastIcon.classList.add("bytm-toast-icon");
  1254. const iconHtml = await resourceAsString(rest.icon);
  1255. if (iconHtml)
  1256. setInnerHtml(toastIcon, iconHtml);
  1257. if ("iconFill" in rest && rest.iconFill)
  1258. toastIcon.style.setProperty("--toast-icon-fill", rest.iconFill);
  1259. }
  1260. const toastMessage = document.createElement("div");
  1261. toastMessage.classList.add("bytm-toast-message");
  1262. if ("message" in rest) {
  1263. toastMessage.textContent = rest.message;
  1264. if ("subtitle" in rest && rest.subtitle) {
  1265. const subtitleEl = document.createElement("div");
  1266. subtitleEl.classList.add("bytm-toast-subtitle");
  1267. subtitleEl.textContent = rest.subtitle;
  1268. toastMessage.appendChild(subtitleEl);
  1269. }
  1270. }
  1271. else
  1272. toastMessage.appendChild(rest.element);
  1273. iconPos === "left" && toastWrapper.appendChild(toastIcon);
  1274. toastWrapper.appendChild(toastMessage);
  1275. iconPos === "right" && toastWrapper.appendChild(toastIcon);
  1276. return await showToast({
  1277. duration,
  1278. position,
  1279. element: toastWrapper,
  1280. title: "message" in rest ? rest.message : rest.title,
  1281. onClick: rest.onClick,
  1282. });
  1283. }
  1284. /** Shows a toast message or element in the specified position (top right corner by default) and uses the default timeout from the config option `toastDuration` */
  1285. async function showToast(arg) {
  1286. const props = typeof arg === "string"
  1287. ? {
  1288. message: arg,
  1289. duration: getFeature("toastDuration") * 1000,
  1290. }
  1291. : arg;
  1292. const { duration: durationMs = getFeature("toastDuration") * 1000, onClick, position = "tr" } = props, rest = __rest(props, ["duration", "onClick", "position"]);
  1293. if (durationMs <= 0)
  1294. return info("Toast duration is <= 0, so it won't be shown");
  1295. const toastEl = document.querySelector("#bytm-toast");
  1296. if (toastEl)
  1297. await closeToast();
  1298. const toastElem = document.createElement("div");
  1299. onClick && toastElem.classList.add("clickable");
  1300. toastElem.id = "bytm-toast";
  1301. toastElem.role = "alert";
  1302. toastElem.ariaLive = "polite";
  1303. toastElem.ariaAtomic = "true";
  1304. toastElem.addEventListener("click", async (e) => {
  1305. onClick === null || onClick === void 0 ? void 0 : onClick(e);
  1306. await closeToast();
  1307. }, { once: true });
  1308. if ("message" in rest)
  1309. toastElem.title = toastElem.ariaLabel = toastElem.textContent = rest.message;
  1310. else {
  1311. toastElem.appendChild(rest.element);
  1312. toastElem.title = toastElem.ariaLabel = rest.title;
  1313. }
  1314. document.body.appendChild(toastElem);
  1315. UserUtils.pauseFor(100).then(async () => {
  1316. toastElem.classList.add("visible", `pos-${position.toLowerCase()}`);
  1317. if (durationMs < Number.POSITIVE_INFINITY && durationMs > 0) {
  1318. timeout && clearTimeout(timeout);
  1319. timeout = setTimeout(closeToast, UserUtils.clamp(durationMs, 250, maxToastDuration));
  1320. }
  1321. });
  1322. return toastElem;
  1323. }
  1324. /** Closes the currently open toast */
  1325. async function closeToast() {
  1326. if (timeout) {
  1327. clearTimeout(timeout);
  1328. timeout = undefined;
  1329. }
  1330. const toastEls = document.querySelectorAll("#bytm-toast");
  1331. if (toastEls.length === 0)
  1332. return;
  1333. await Promise.allSettled(Array.from(toastEls).map(async (toastEl) => {
  1334. toastEl.classList.remove("visible");
  1335. await UserUtils.pauseFor(300);
  1336. toastEl.remove();
  1337. await UserUtils.pauseFor(100);
  1338. }));
  1339. }/** Creates a simple toggle element */
  1340. async function createToggleInput({ onChange, initialValue = false, id = UserUtils.randomId(8, 26), labelPos = "left", }) {
  1341. const wrapperEl = document.createElement("div");
  1342. wrapperEl.classList.add("bytm-toggle-input-wrapper", "bytm-no-select");
  1343. wrapperEl.role = "switch";
  1344. wrapperEl.tabIndex = 0;
  1345. const labelEl = labelPos !== "off" && document.createElement("label");
  1346. if (labelEl) {
  1347. labelEl.classList.add("bytm-toggle-input-label");
  1348. labelEl.textContent = t(`toggled_${initialValue ? "on" : "off"}`);
  1349. if (id)
  1350. labelEl.htmlFor = `bytm-toggle-input-${id}`;
  1351. }
  1352. const toggleWrapperEl = document.createElement("div");
  1353. toggleWrapperEl.classList.add("bytm-toggle-input");
  1354. toggleWrapperEl.tabIndex = -1;
  1355. const toggleEl = document.createElement("input");
  1356. toggleEl.type = "checkbox";
  1357. toggleEl.checked = initialValue;
  1358. toggleEl.dataset.toggled = String(Boolean(initialValue));
  1359. toggleEl.tabIndex = -1;
  1360. if (id)
  1361. toggleEl.id = `bytm-toggle-input-${id}`;
  1362. const toggleKnobEl = document.createElement("div");
  1363. toggleKnobEl.classList.add("bytm-toggle-input-knob");
  1364. setInnerHtml(toggleKnobEl, "&nbsp;");
  1365. const toggleElClicked = (e) => {
  1366. e.preventDefault();
  1367. e.stopPropagation();
  1368. onChange(toggleEl.checked);
  1369. toggleEl.dataset.toggled = String(Boolean(toggleEl.checked));
  1370. if (labelEl)
  1371. labelEl.textContent = t(`toggled_${toggleEl.checked ? "on" : "off"}`);
  1372. wrapperEl.ariaValueText = t(`toggled_${toggleEl.checked ? "on" : "off"}`);
  1373. };
  1374. toggleEl.addEventListener("change", toggleElClicked);
  1375. wrapperEl.addEventListener("keydown", (e) => {
  1376. if (["Space", " ", "Enter"].includes(e.code)) {
  1377. toggleEl.checked = !toggleEl.checked;
  1378. toggleElClicked(e);
  1379. }
  1380. });
  1381. toggleEl.appendChild(toggleKnobEl);
  1382. toggleWrapperEl.appendChild(toggleEl);
  1383. labelEl && labelPos === "left" && wrapperEl.appendChild(labelEl);
  1384. wrapperEl.appendChild(toggleWrapperEl);
  1385. labelEl && labelPos === "right" && wrapperEl.appendChild(labelEl);
  1386. return wrapperEl;
  1387. }let autoLikeDialog = null;
  1388. let autoLikeImExDialog = null;
  1389. /** Creates and/or returns the import dialog */
  1390. async function getAutoLikeDialog() {
  1391. if (!autoLikeDialog) {
  1392. await initAutoLikeStore();
  1393. autoLikeDialog = new BytmDialog({
  1394. id: "auto-like-channels",
  1395. width: 700,
  1396. height: 1000,
  1397. closeBtnEnabled: true,
  1398. closeOnBgClick: true,
  1399. closeOnEscPress: true,
  1400. destroyOnClose: true,
  1401. removeListenersOnDestroy: false,
  1402. small: true,
  1403. verticalAlign: "top",
  1404. renderHeader: renderHeader$4,
  1405. renderBody: renderBody$4,
  1406. renderFooter: renderFooter$1,
  1407. });
  1408. siteEvents.on("autoLikeChannelsUpdated", async () => {
  1409. try {
  1410. if (autoLikeImExDialog === null || autoLikeImExDialog === void 0 ? void 0 : autoLikeImExDialog.isOpen())
  1411. autoLikeImExDialog.unmount();
  1412. if (autoLikeDialog === null || autoLikeDialog === void 0 ? void 0 : autoLikeDialog.isOpen()) {
  1413. autoLikeDialog.unmount();
  1414. await autoLikeDialog.open();
  1415. log("Auto-like channels updated, refreshed dialog");
  1416. }
  1417. }
  1418. catch (err) {
  1419. error("Couldn't refresh auto-like channels dialog:", err);
  1420. }
  1421. });
  1422. autoLikeDialog.on("close", () => emitSiteEvent("autoLikeChannelsUpdated"));
  1423. }
  1424. if (!autoLikeImExDialog) {
  1425. autoLikeImExDialog = new ExImDialog({
  1426. id: "auto-like-channels-export-import",
  1427. width: 800,
  1428. height: 600,
  1429. // try to compress the data if possible
  1430. exportData: async () => await compressionSupported()
  1431. ? await UserUtils.compress(JSON.stringify(autoLikeStore.getData()), compressionFormat, "string")
  1432. : JSON.stringify(autoLikeStore.getData()),
  1433. // copy plain when shift-clicking the copy button
  1434. exportDataSpecial: () => JSON.stringify(autoLikeStore.getData()),
  1435. async onImport(data) {
  1436. try {
  1437. const parsed = await tryToDecompressAndParse(data);
  1438. log("Trying to import auto-like data:", parsed);
  1439. if (!parsed || typeof parsed !== "object")
  1440. return alert(t("import_error_invalid"));
  1441. if (!parsed.channels || typeof parsed.channels !== "object" || Object.keys(parsed.channels).length === 0)
  1442. return alert(t("import_error_no_data"));
  1443. await autoLikeStore.setData(parsed);
  1444. emitSiteEvent("autoLikeChannelsUpdated");
  1445. showToast({ message: t("import_success") });
  1446. autoLikeImExDialog === null || autoLikeImExDialog === void 0 ? void 0 : autoLikeImExDialog.unmount();
  1447. }
  1448. catch (err) {
  1449. error("Couldn't import auto-like channels data:", err);
  1450. }
  1451. },
  1452. title: () => t("auto_like_export_import_title"),
  1453. descImport: () => t("auto_like_import_desc"),
  1454. descExport: () => t("auto_like_export_desc"),
  1455. });
  1456. }
  1457. return autoLikeDialog;
  1458. }
  1459. //#region header
  1460. async function renderHeader$4() {
  1461. const headerEl = document.createElement("h2");
  1462. headerEl.classList.add("bytm-dialog-title");
  1463. headerEl.role = "heading";
  1464. headerEl.ariaLevel = "1";
  1465. headerEl.tabIndex = 0;
  1466. headerEl.textContent = headerEl.ariaLabel = t("auto_like_channels_dialog_title");
  1467. return headerEl;
  1468. }
  1469. //#region body
  1470. async function renderBody$4() {
  1471. const contElem = document.createElement("div");
  1472. const descriptionEl = document.createElement("p");
  1473. descriptionEl.classList.add("bytm-auto-like-channels-desc");
  1474. descriptionEl.textContent = t("auto_like_channels_dialog_desc");
  1475. descriptionEl.tabIndex = 0;
  1476. contElem.appendChild(descriptionEl);
  1477. const searchCont = document.createElement("div");
  1478. searchCont.classList.add("bytm-auto-like-channels-search-cont");
  1479. contElem.appendChild(searchCont);
  1480. const searchbarEl = document.createElement("input");
  1481. searchbarEl.classList.add("bytm-auto-like-channels-searchbar");
  1482. searchbarEl.placeholder = t("search_placeholder");
  1483. searchbarEl.type = "search";
  1484. searchbarEl.tabIndex = 0;
  1485. searchbarEl.addEventListener("input", () => {
  1486. var _a, _b, _c;
  1487. const searchVal = searchbarEl.value.trim().toLowerCase();
  1488. const rows = document.querySelectorAll(".bytm-auto-like-channel-row");
  1489. for (const row of rows) {
  1490. const name = (_c = (_b = (_a = row.querySelector(".bytm-auto-like-channel-name")) === null || _a === void 0 ? void 0 : _a.textContent) === null || _b === void 0 ? void 0 : _b.trim().toLowerCase()) !== null && _c !== void 0 ? _c : "";
  1491. row.classList.toggle("hidden", !name.includes(searchVal));
  1492. }
  1493. });
  1494. searchCont.appendChild(searchbarEl);
  1495. const searchClearEl = document.createElement("button");
  1496. searchClearEl.classList.add("bytm-auto-like-channels-search-clear");
  1497. searchClearEl.title = searchClearEl.ariaLabel = t("search_clear");
  1498. searchClearEl.tabIndex = 0;
  1499. searchClearEl.innerText = "×";
  1500. onInteraction(searchClearEl, () => {
  1501. searchbarEl.value = "";
  1502. searchbarEl.dispatchEvent(new Event("input"));
  1503. });
  1504. searchCont.appendChild(searchClearEl);
  1505. const channelListCont = document.createElement("div");
  1506. channelListCont.id = "bytm-auto-like-channels-list";
  1507. const setChannelEnabled = UserUtils.debounce((id, enabled) => {
  1508. autoLikeStore.setData({
  1509. channels: autoLikeStore.getData().channels
  1510. .map((ch) => ch.id === id ? Object.assign(Object.assign({}, ch), { enabled }) : ch),
  1511. });
  1512. }, 250, "rising");
  1513. const sortedChannels = autoLikeStore
  1514. .getData().channels
  1515. .sort((a, b) => a.name.localeCompare(b.name));
  1516. for (const { name: chanName, id: chanId, enabled } of sortedChannels) {
  1517. const rowElem = document.createElement("div");
  1518. rowElem.classList.add("bytm-auto-like-channel-row");
  1519. const leftCont = document.createElement("div");
  1520. leftCont.classList.add("bytm-auto-like-channel-row-left-cont");
  1521. const nameLabelEl = document.createElement("label");
  1522. nameLabelEl.ariaLabel = nameLabelEl.title = chanName;
  1523. nameLabelEl.htmlFor = `bytm-auto-like-channel-list-toggle-${chanId}`;
  1524. nameLabelEl.classList.add("bytm-auto-like-channel-name-label");
  1525. const nameElem = document.createElement("a");
  1526. nameElem.classList.add("bytm-auto-like-channel-name", "bytm-link");
  1527. nameElem.ariaLabel = nameElem.textContent = chanName;
  1528. nameElem.href = (!chanId.startsWith("@") && getDomain() === "ytm")
  1529. ? `https://music.youtube.com/channel/${chanId}`
  1530. : `https://youtube.com/${chanId.startsWith("@") ? chanId : `channel/${chanId}`}`;
  1531. nameElem.target = "_blank";
  1532. nameElem.rel = "noopener noreferrer";
  1533. nameElem.tabIndex = 0;
  1534. const idElem = document.createElement("span");
  1535. idElem.classList.add("bytm-auto-like-channel-id");
  1536. idElem.textContent = idElem.title = chanId;
  1537. nameLabelEl.appendChild(nameElem);
  1538. nameLabelEl.appendChild(idElem);
  1539. const toggleElem = await createToggleInput({
  1540. id: `auto-like-channel-list-${chanId}`,
  1541. labelPos: "off",
  1542. initialValue: enabled,
  1543. onChange: (en) => setChannelEnabled(chanId, en),
  1544. });
  1545. toggleElem.classList.add("bytm-auto-like-channel-toggle");
  1546. const btnCont = document.createElement("div");
  1547. btnCont.classList.add("bytm-auto-like-channel-row-btn-cont");
  1548. const editBtn = await createCircularBtn({
  1549. resourceName: "icon-edit",
  1550. title: t("edit_entry"),
  1551. async onClick() {
  1552. var _a, _b, _c;
  1553. const newNamePr = (_a = prompt(t("auto_like_channel_edit_name_prompt"), chanName)) === null || _a === void 0 ? void 0 : _a.trim();
  1554. if (!newNamePr || newNamePr.length === 0)
  1555. return;
  1556. const newName = newNamePr.length > 0 ? newNamePr : chanName;
  1557. const newIdPr = (_b = prompt(t("auto_like_channel_edit_id_prompt"), chanId)) === null || _b === void 0 ? void 0 : _b.trim();
  1558. if (!newIdPr || newIdPr.length === 0)
  1559. return;
  1560. const newId = newIdPr.length > 0 ? (_c = getChannelIdFromPrompt(newIdPr)) !== null && _c !== void 0 ? _c : chanId : chanId;
  1561. await autoLikeStore.setData({
  1562. channels: autoLikeStore.getData().channels
  1563. .map((ch) => ch.id === chanId ? Object.assign(Object.assign({}, ch), { name: newName, id: newId }) : ch),
  1564. });
  1565. emitSiteEvent("autoLikeChannelsUpdated");
  1566. },
  1567. });
  1568. btnCont.appendChild(editBtn);
  1569. const removeBtn = await createCircularBtn({
  1570. resourceName: "icon-delete",
  1571. title: t("remove_entry"),
  1572. async onClick() {
  1573. autoLikeStore.setData({
  1574. channels: autoLikeStore.getData().channels.filter((ch) => ch.id !== chanId),
  1575. });
  1576. rowElem.remove();
  1577. emitSiteEvent("autoLikeChannelsUpdated");
  1578. },
  1579. });
  1580. btnCont.appendChild(removeBtn);
  1581. leftCont.appendChild(toggleElem);
  1582. leftCont.appendChild(nameLabelEl);
  1583. rowElem.appendChild(leftCont);
  1584. rowElem.appendChild(btnCont);
  1585. channelListCont.appendChild(rowElem);
  1586. }
  1587. contElem.appendChild(channelListCont);
  1588. return contElem;
  1589. }
  1590. //#region footer
  1591. function renderFooter$1() {
  1592. const wrapperEl = document.createElement("div");
  1593. wrapperEl.classList.add("bytm-auto-like-channels-footer-wrapper");
  1594. const addNewBtnElem = document.createElement("button");
  1595. addNewBtnElem.classList.add("bytm-btn");
  1596. addNewBtnElem.textContent = t("new_entry");
  1597. addNewBtnElem.ariaLabel = addNewBtnElem.title = t("new_entry_tooltip");
  1598. wrapperEl.appendChild(addNewBtnElem);
  1599. const importExportBtnElem = document.createElement("button");
  1600. importExportBtnElem.classList.add("bytm-btn");
  1601. importExportBtnElem.textContent = t("export_import");
  1602. importExportBtnElem.ariaLabel = importExportBtnElem.title = t("auto_like_export_or_import_tooltip");
  1603. wrapperEl.appendChild(importExportBtnElem);
  1604. onInteraction(addNewBtnElem, addAutoLikeEntryPrompts);
  1605. onInteraction(importExportBtnElem, openImportExportAutoLikeChannelsDialog);
  1606. return wrapperEl;
  1607. }
  1608. async function openImportExportAutoLikeChannelsDialog() {
  1609. await (autoLikeImExDialog === null || autoLikeImExDialog === void 0 ? void 0 : autoLikeImExDialog.open());
  1610. }
  1611. //#region add prompt
  1612. async function addAutoLikeEntryPrompts() {
  1613. var _a, _b, _c;
  1614. await autoLikeStore.loadData();
  1615. const idPrompt = (_a = prompt(t("add_auto_like_channel_id_prompt"))) === null || _a === void 0 ? void 0 : _a.trim();
  1616. if (!idPrompt)
  1617. return;
  1618. const id = (_b = parseChannelIdFromUrl(idPrompt)) !== null && _b !== void 0 ? _b : (isValidChannelId(idPrompt) ? idPrompt : null);
  1619. if (!id || id.length <= 0)
  1620. return alert(t("add_auto_like_channel_invalid_id"));
  1621. let overwriteName = false;
  1622. const hasChannelEntry = autoLikeStore.getData().channels.find((ch) => ch.id === id);
  1623. if (hasChannelEntry) {
  1624. if (!confirm(t("add_auto_like_channel_already_exists_prompt_new_name")))
  1625. return;
  1626. overwriteName = true;
  1627. }
  1628. const name = (_c = prompt(t("add_auto_like_channel_name_prompt"), hasChannelEntry === null || hasChannelEntry === void 0 ? void 0 : hasChannelEntry.name)) === null || _c === void 0 ? void 0 : _c.trim();
  1629. if (!name || name.length === 0)
  1630. return;
  1631. await autoLikeStore.setData(overwriteName
  1632. ? {
  1633. channels: autoLikeStore.getData().channels
  1634. .map((ch) => ch.id === id ? Object.assign(Object.assign({}, ch), { name }) : ch),
  1635. }
  1636. : {
  1637. channels: [
  1638. ...autoLikeStore.getData().channels,
  1639. { id, name, enabled: true },
  1640. ],
  1641. });
  1642. emitSiteEvent("autoLikeChannelsUpdated");
  1643. const unsub = autoLikeDialog === null || autoLikeDialog === void 0 ? void 0 : autoLikeDialog.on("clear", async () => {
  1644. unsub === null || unsub === void 0 ? void 0 : unsub();
  1645. await (autoLikeDialog === null || autoLikeDialog === void 0 ? void 0 : autoLikeDialog.open());
  1646. });
  1647. autoLikeDialog === null || autoLikeDialog === void 0 ? void 0 : autoLikeDialog.unmount();
  1648. }
  1649. function getChannelIdFromPrompt(promptStr) {
  1650. const isId = promptStr.match(/^@?.+$/);
  1651. const isUrl = promptStr.match(/^(?:https?:\/\/)?(?:www\.)?(?:music\.)?youtube\.com\/(?:channel\/|@)([a-zA-Z0-9_-]+)/);
  1652. const id = ((isId === null || isId === void 0 ? void 0 : isId[0]) || (isUrl === null || isUrl === void 0 ? void 0 : isUrl[1]) || "").trim();
  1653. return id.length > 0 ? id : null;
  1654. }let changelogDialog = null;
  1655. /** Creates and/or returns the changelog dialog */
  1656. async function getChangelogDialog() {
  1657. if (!changelogDialog) {
  1658. changelogDialog = new BytmDialog({
  1659. id: "changelog",
  1660. width: 1000,
  1661. height: 800,
  1662. closeBtnEnabled: true,
  1663. closeOnBgClick: true,
  1664. closeOnEscPress: true,
  1665. small: true,
  1666. verticalAlign: "top",
  1667. renderHeader: renderHeader$3,
  1668. renderBody: renderBody$3,
  1669. });
  1670. changelogDialog.on("render", () => {
  1671. const mdContElem = document.querySelector("#bytm-changelog-dialog-text");
  1672. if (!mdContElem)
  1673. return;
  1674. const anchors = mdContElem.querySelectorAll("a");
  1675. for (const anchor of anchors) {
  1676. anchor.ariaLabel = anchor.title = anchor.href;
  1677. anchor.target = "_blank";
  1678. }
  1679. const firstDetails = mdContElem.querySelector("details");
  1680. if (firstDetails)
  1681. firstDetails.open = true;
  1682. });
  1683. }
  1684. return changelogDialog;
  1685. }
  1686. async function renderHeader$3() {
  1687. const headerEl = document.createElement("h2");
  1688. headerEl.classList.add("bytm-dialog-title");
  1689. headerEl.role = "heading";
  1690. headerEl.ariaLevel = "1";
  1691. headerEl.tabIndex = 0;
  1692. headerEl.textContent = headerEl.ariaLabel = t("changelog_menu_title", scriptInfo.name);
  1693. return headerEl;
  1694. }
  1695. async function renderBody$3() {
  1696. const contElem = document.createElement("div");
  1697. const mdContElem = document.createElement("div");
  1698. mdContElem.id = "bytm-changelog-dialog-text";
  1699. mdContElem.classList.add("bytm-markdown-container");
  1700. setInnerHtml(mdContElem, await getChangelogHtmlWithDetails());
  1701. contElem.appendChild(mdContElem);
  1702. return contElem;
  1703. }let featHelpDialog = null;
  1704. let curFeatKey = null;
  1705. /** Creates or modifies the help dialog for a specific feature and returns it */
  1706. async function getFeatHelpDialog({ featKey, }) {
  1707. curFeatKey = featKey;
  1708. if (!featHelpDialog) {
  1709. featHelpDialog = new BytmDialog({
  1710. id: "feat-help",
  1711. width: 600,
  1712. height: 400,
  1713. closeBtnEnabled: true,
  1714. closeOnBgClick: true,
  1715. closeOnEscPress: true,
  1716. small: true,
  1717. renderHeader: renderHeader$2,
  1718. renderBody: renderBody$2,
  1719. });
  1720. // make config menu inert while help dialog is open
  1721. featHelpDialog.on("open", () => { var _a; return (_a = document.querySelector("#bytm-cfg-menu")) === null || _a === void 0 ? void 0 : _a.setAttribute("inert", "true"); });
  1722. featHelpDialog.on("close", () => { var _a; return (_a = document.querySelector("#bytm-cfg-menu")) === null || _a === void 0 ? void 0 : _a.removeAttribute("inert"); });
  1723. }
  1724. return featHelpDialog;
  1725. }
  1726. async function renderHeader$2() {
  1727. const headerEl = document.createElement("div");
  1728. const helpIconSvg = await resourceAsString("icon-help");
  1729. if (helpIconSvg)
  1730. setInnerHtml(headerEl, helpIconSvg);
  1731. return headerEl;
  1732. }
  1733. async function renderBody$2() {
  1734. var _a, _b;
  1735. const contElem = document.createElement("div");
  1736. const featDescElem = document.createElement("h3");
  1737. featDescElem.role = "subheading";
  1738. featDescElem.tabIndex = 0;
  1739. featDescElem.textContent = t(`feature_desc_${curFeatKey}`);
  1740. featDescElem.id = "bytm-feat-help-dialog-desc";
  1741. const helpTextElem = document.createElement("div");
  1742. helpTextElem.id = "bytm-feat-help-dialog-text";
  1743. helpTextElem.tabIndex = 0;
  1744. // @ts-ignore
  1745. const helpText = (_b = (_a = featInfo[curFeatKey]) === null || _a === void 0 ? void 0 : _a.helpText) === null || _b === void 0 ? void 0 : _b.call(_a);
  1746. helpTextElem.textContent = helpText !== null && helpText !== void 0 ? helpText : t(`feature_helptext_${curFeatKey}`);
  1747. contElem.appendChild(featDescElem);
  1748. contElem.appendChild(helpTextElem);
  1749. return contElem;
  1750. }var name = "betterytm";
  1751. var userscriptName = "BetterYTM";
  1752. var version = "2.0.0";
  1753. var description = "Lots of configurable layout and user experience improvements for YouTube Music™ and YouTube™";
  1754. var homepage = "https://github.com/Sv443/BetterYTM";
  1755. var main = "./src/index.ts";
  1756. var type = "module";
  1757. var scripts = {
  1758. dev: "concurrently \"nodemon --exec pnpm run build-private-dev\" \"pnpm run serve\"",
  1759. serve: "pnpm run node-ts ./src/tools/serve.ts",
  1760. lint: "tsc --noEmit && eslint .",
  1761. build: "rollup -c",
  1762. "build-private-dev": "rollup -c --config-mode development --config-host github --config-branch develop --config-assetSource=local",
  1763. "build-dev": "rollup -c --config-mode development --config-host github --config-branch develop",
  1764. preview: "pnpm run build-dev && pnpm run serve --auto-exit=3",
  1765. "build-prod": "pnpm run build-prod-gh && pnpm run build-prod-gf && pnpm run build-prod-oujs",
  1766. "build-prod-base": "rollup -c --config-mode production --config-branch main",
  1767. "build-prod-gh": "pnpm run build-prod-base --config-host github",
  1768. "build-prod-gf": "pnpm run build-prod-base --config-host greasyfork --config-suffix _gf",
  1769. "build-prod-oujs": "pnpm run build-prod-base --config-host openuserjs --config-suffix _oujs",
  1770. "post-build": "pnpm run node-ts ./src/tools/post-build.ts",
  1771. "tr-progress": "pnpm run node-ts ./src/tools/tr-progress.ts",
  1772. "tr-format": "pnpm run node-ts ./src/tools/tr-format.ts",
  1773. "tr-prep": "pnpm run tr-format -p",
  1774. "gen-readme": "pnpm run node-ts ./src/tools/gen-readme.ts",
  1775. "node-ts": "node --no-warnings=ExperimentalWarning --enable-source-maps --loader ts-node/esm",
  1776. invisible: "node --enable-source-maps src/tools/run-invisible.mjs",
  1777. test: "pnpm run node-ts ./test.ts",
  1778. knip: "knip",
  1779. storybook: "storybook dev -p 6006",
  1780. "build-storybook": "storybook build",
  1781. "dep-cruise": "npx depcruise src",
  1782. "dep-graph": "npx depcruise src --include-only \"^src\" --output-type dot | dot -T svg > dependency-graph.svg && open dependency-graph.svg -R"
  1783. };
  1784. var engines = {
  1785. node: ">=19",
  1786. npm: ">=8"
  1787. };
  1788. var repository = {
  1789. type: "git",
  1790. url: "git+https://github.com/Sv443/BetterYTM.git"
  1791. };
  1792. var author = {
  1793. name: "Sv443",
  1794. url: "https://github.com/Sv443"
  1795. };
  1796. var license = "AGPL-3.0-only";
  1797. var bugs = {
  1798. url: "https://github.com/Sv443/BetterYTM/issues"
  1799. };
  1800. var funding = {
  1801. type: "github",
  1802. url: "https://github.com/sponsors/Sv443"
  1803. };
  1804. var hosts = {
  1805. github: "https://github.com/Sv443/BetterYTM",
  1806. greasyfork: "https://greasyfork.org/en/scripts/475682-betterytm",
  1807. openuserjs: "https://openuserjs.org/scripts/Sv443/BetterYTM"
  1808. };
  1809. var updates = {
  1810. github: "https://github.com/Sv443/BetterYTM/releases",
  1811. greasyfork: "https://greasyfork.org/en/scripts/475682-betterytm",
  1812. openuserjs: "https://openuserjs.org/scripts/Sv443/BetterYTM"
  1813. };
  1814. var dependencies = {
  1815. "@sv443-network/userutils": "^7.2.1",
  1816. "compare-versions": "^6.1.0",
  1817. dompurify: "^3.1.6",
  1818. marked: "^12.0.2",
  1819. tslib: "^2.6.3"
  1820. };
  1821. var devDependencies = {
  1822. "@chromatic-com/storybook": "^1.5.0",
  1823. "@eslint/eslintrc": "^3.1.0",
  1824. "@rollup/plugin-json": "^6.1.0",
  1825. "@rollup/plugin-node-resolve": "^15.2.3",
  1826. "@rollup/plugin-terser": "^0.4.4",
  1827. "@rollup/plugin-typescript": "^11.1.6",
  1828. "@storybook/addon-essentials": "^8.1.10",
  1829. "@storybook/addon-interactions": "^8.1.10",
  1830. "@storybook/addon-links": "^8.1.10",
  1831. "@storybook/blocks": "^8.1.10",
  1832. "@storybook/html": "^8.1.10",
  1833. "@storybook/html-vite": "^8.1.10",
  1834. "@storybook/test": "^8.1.10",
  1835. "@types/dompurify": "^3.0.5",
  1836. "@types/express": "^4.17.21",
  1837. "@types/greasemonkey": "^4.0.7",
  1838. "@types/node": "^20.14.8",
  1839. "@typescript-eslint/eslint-plugin": "^8.0.0",
  1840. "@typescript-eslint/parser": "^8.0.0",
  1841. "@typescript-eslint/utils": "^8.0.0",
  1842. concurrently: "^8.2.2",
  1843. "dependency-cruiser": "^16.3.10",
  1844. dotenv: "^16.4.5",
  1845. eslint: "^9.5.0",
  1846. "eslint-plugin-storybook": "^0.9.0--canary.156.ed236ca.0",
  1847. express: "^4.19.2",
  1848. globals: "^15.6.0",
  1849. knip: "^5.22.2",
  1850. nodemon: "^3.1.4",
  1851. open: "^10.1.0",
  1852. pnpm: "^9.4.0",
  1853. rollup: "^4.18.0",
  1854. "rollup-plugin-execute": "^1.1.1",
  1855. "rollup-plugin-import-css": "^3.5.0",
  1856. storybook: "^8.1.10",
  1857. "storybook-dark-mode": "^4.0.2",
  1858. "ts-node": "^10.9.2",
  1859. typescript: "^5.5.2"
  1860. };
  1861. var browserslist = [
  1862. "last 1 version",
  1863. "> 1%",
  1864. "not dead"
  1865. ];
  1866. var nodemonConfig = {
  1867. watch: [
  1868. "src/**",
  1869. "assets/**",
  1870. "rollup.config.mjs",
  1871. ".env",
  1872. "changelog.md",
  1873. "package.json"
  1874. ],
  1875. ext: "ts,mts,js,jsx,mjs,json,html,css,svg,png",
  1876. ignore: [
  1877. "dist/*",
  1878. "dev/*",
  1879. "*/stories/*"
  1880. ]
  1881. };
  1882. var packageJson = {
  1883. name: name,
  1884. userscriptName: userscriptName,
  1885. version: version,
  1886. description: description,
  1887. homepage: homepage,
  1888. main: main,
  1889. type: type,
  1890. scripts: scripts,
  1891. engines: engines,
  1892. repository: repository,
  1893. author: author,
  1894. license: license,
  1895. bugs: bugs,
  1896. funding: funding,
  1897. hosts: hosts,
  1898. updates: updates,
  1899. dependencies: dependencies,
  1900. devDependencies: devDependencies,
  1901. browserslist: browserslist,
  1902. nodemonConfig: nodemonConfig
  1903. };let verNotifDialog = null;
  1904. /** Creates and/or returns the dialog to be shown when a new version is available */
  1905. async function getVersionNotifDialog({ latestTag, }) {
  1906. if (!verNotifDialog) {
  1907. const changelogMdFull = await getChangelogMd();
  1908. // I messed up because this should be 0 so the changelog will always need to have an extra div at the top for backwards compatibility
  1909. const changelogMd = changelogMdFull.split("<div class=\"split\">")[1];
  1910. const changelogHtml = await parseMarkdown(changelogMd);
  1911. verNotifDialog = new BytmDialog({
  1912. id: "version-notif",
  1913. width: 600,
  1914. height: 800,
  1915. closeBtnEnabled: false,
  1916. closeOnBgClick: false,
  1917. closeOnEscPress: true,
  1918. destroyOnClose: true,
  1919. small: true,
  1920. renderHeader: renderHeader$1,
  1921. renderBody: () => renderBody$1({
  1922. latestTag,
  1923. changelogHtml,
  1924. }),
  1925. });
  1926. }
  1927. return verNotifDialog;
  1928. }
  1929. async function renderHeader$1() {
  1930. const logoEl = document.createElement("img");
  1931. logoEl.classList.add("bytm-dialog-header-img", "bytm-no-select");
  1932. logoEl.src = await getResourceUrl(mode === "development" ? "img-logo_dev" : "img-logo");
  1933. logoEl.alt = "BetterYTM logo";
  1934. return logoEl;
  1935. }
  1936. let disableUpdateCheck = false;
  1937. async function renderBody$1({ latestTag, changelogHtml, }) {
  1938. disableUpdateCheck = false;
  1939. const hostPlatformNames = {
  1940. github: "GitHub",
  1941. greasyfork: "GreasyFork",
  1942. openuserjs: "OpenUserJS",
  1943. };
  1944. const wrapperEl = document.createElement("div");
  1945. const pEl = document.createElement("p");
  1946. pEl.textContent = t("new_version_available", scriptInfo.name, scriptInfo.version, latestTag, hostPlatformNames[host]);
  1947. wrapperEl.appendChild(pEl);
  1948. const changelogDetailsEl = document.createElement("details");
  1949. changelogDetailsEl.id = "bytm-version-notif-changelog-details";
  1950. changelogDetailsEl.open = false;
  1951. const changelogSummaryEl = document.createElement("summary");
  1952. changelogSummaryEl.role = "button";
  1953. changelogSummaryEl.tabIndex = 0;
  1954. changelogSummaryEl.ariaLabel = changelogSummaryEl.title = changelogSummaryEl.textContent = t("expand_release_notes");
  1955. changelogDetailsEl.appendChild(changelogSummaryEl);
  1956. changelogDetailsEl.addEventListener("toggle", () => {
  1957. changelogSummaryEl.ariaLabel = changelogSummaryEl.title = changelogSummaryEl.textContent = changelogDetailsEl.open ? t("collapse_release_notes") : t("expand_release_notes");
  1958. });
  1959. const changelogEl = document.createElement("p");
  1960. changelogEl.id = "bytm-version-notif-changelog-cont";
  1961. changelogEl.classList.add("bytm-markdown-container");
  1962. setInnerHtml(changelogEl, changelogHtml);
  1963. changelogEl.querySelectorAll("a").forEach((a) => {
  1964. a.target = "_blank";
  1965. a.rel = "noopener noreferrer";
  1966. });
  1967. changelogDetailsEl.appendChild(changelogEl);
  1968. wrapperEl.appendChild(changelogDetailsEl);
  1969. const disableUpdCheckEl = document.createElement("div");
  1970. disableUpdCheckEl.id = "bytm-disable-update-check-wrapper";
  1971. if (!getFeature("versionCheck"))
  1972. disableUpdateCheck = true;
  1973. const disableToggleEl = await createToggleInput({
  1974. id: "disable-update-check",
  1975. initialValue: disableUpdateCheck,
  1976. labelPos: "off",
  1977. onChange(checked) {
  1978. disableUpdateCheck = checked;
  1979. if (checked)
  1980. btnClose.textContent = t("close_and_ignore_until_reenabled");
  1981. else
  1982. btnClose.textContent = t("close_and_ignore_for_24h");
  1983. },
  1984. });
  1985. const labelWrapperEl = document.createElement("div");
  1986. labelWrapperEl.classList.add("bytm-disable-update-check-toggle-label-wrapper");
  1987. const labelEl = document.createElement("label");
  1988. labelEl.htmlFor = "bytm-toggle-disable-update-check";
  1989. labelEl.textContent = t("disable_update_check");
  1990. const secondaryLabelEl = document.createElement("span");
  1991. secondaryLabelEl.classList.add("bytm-secondary-label");
  1992. secondaryLabelEl.textContent = t("reenable_in_config_menu");
  1993. labelWrapperEl.appendChild(labelEl);
  1994. labelWrapperEl.appendChild(secondaryLabelEl);
  1995. disableUpdCheckEl.appendChild(disableToggleEl);
  1996. disableUpdCheckEl.appendChild(labelWrapperEl);
  1997. wrapperEl.appendChild(disableUpdCheckEl);
  1998. verNotifDialog === null || verNotifDialog === void 0 ? void 0 : verNotifDialog.on("close", async () => {
  1999. const config = getFeatures();
  2000. const recreateCfgMenu = config.versionCheck === disableUpdateCheck;
  2001. if (config.versionCheck && disableUpdateCheck)
  2002. config.versionCheck = false;
  2003. else if (!config.versionCheck && !disableUpdateCheck)
  2004. config.versionCheck = true;
  2005. await setFeatures(config);
  2006. recreateCfgMenu && emitSiteEvent("recreateCfgMenu");
  2007. });
  2008. const btnWrapper = document.createElement("div");
  2009. btnWrapper.id = "bytm-version-notif-dialog-btns";
  2010. const btnUpdate = document.createElement("button");
  2011. btnUpdate.classList.add("bytm-btn");
  2012. btnUpdate.tabIndex = 0;
  2013. btnUpdate.textContent = t("open_update_page_install_manually", hostPlatformNames[host]);
  2014. onInteraction(btnUpdate, () => {
  2015. window.open(packageJson.updates[host]);
  2016. verNotifDialog === null || verNotifDialog === void 0 ? void 0 : verNotifDialog.close();
  2017. });
  2018. const btnClose = document.createElement("button");
  2019. btnClose.classList.add("bytm-btn");
  2020. btnClose.tabIndex = 0;
  2021. btnClose.textContent = t("close_and_ignore_for_24h");
  2022. onInteraction(btnClose, () => verNotifDialog === null || verNotifDialog === void 0 ? void 0 : verNotifDialog.close());
  2023. btnWrapper.appendChild(btnUpdate);
  2024. btnWrapper.appendChild(btnClose);
  2025. wrapperEl.appendChild(btnWrapper);
  2026. return wrapperEl;
  2027. }//#region create menu
  2028. let isCfgMenuMounted = false;
  2029. let isCfgMenuOpen = false;
  2030. /** Threshold in pixels from the top of the options container that dictates for how long the scroll indicator is shown */
  2031. const scrollIndicatorOffsetThreshold = 50;
  2032. let scrollIndicatorEnabled = true;
  2033. /** Locale at the point of initializing the config menu */
  2034. let initLocale;
  2035. /** Stringified config at the point of initializing the config menu */
  2036. let initConfig$1;
  2037. /** Timeout id for the "copied" text in the hidden value copy button */
  2038. let hiddenCopiedTxtTimeout;
  2039. /**
  2040. * Adds an element to open the BetterYTM menu
  2041. * @deprecated to be replaced with new menu - see https://github.com/Sv443/BetterYTM/issues/23
  2042. */
  2043. async function mountCfgMenu() {
  2044. var _a, _b, _c, _d;
  2045. if (isCfgMenuMounted)
  2046. return;
  2047. isCfgMenuMounted = true;
  2048. initLocale = getFeature("locale");
  2049. initConfig$1 = getFeatures();
  2050. const initLangReloadText = t("lang_changed_prompt_reload");
  2051. //#region bg & container
  2052. const backgroundElem = document.createElement("div");
  2053. backgroundElem.id = "bytm-cfg-menu-bg";
  2054. backgroundElem.classList.add("bytm-menu-bg");
  2055. backgroundElem.ariaLabel = backgroundElem.title = t("close_menu_tooltip");
  2056. backgroundElem.style.visibility = "hidden";
  2057. backgroundElem.style.display = "none";
  2058. backgroundElem.addEventListener("click", (e) => {
  2059. var _a;
  2060. if (isCfgMenuOpen && ((_a = e.target) === null || _a === void 0 ? void 0 : _a.id) === "bytm-cfg-menu-bg")
  2061. closeCfgMenu(e);
  2062. });
  2063. document.body.addEventListener("keydown", (e) => {
  2064. if (isCfgMenuOpen && e.key === "Escape" && BytmDialog.getCurrentDialogId() === "cfg-menu")
  2065. closeCfgMenu(e);
  2066. });
  2067. const menuContainer = document.createElement("div");
  2068. menuContainer.ariaLabel = menuContainer.title = ""; // prevent bg title from propagating downwards
  2069. menuContainer.classList.add("bytm-menu");
  2070. menuContainer.id = "bytm-cfg-menu";
  2071. //#region title bar
  2072. const headerElem = document.createElement("div");
  2073. headerElem.classList.add("bytm-menu-header");
  2074. const titleLogoHeaderCont = document.createElement("div");
  2075. titleLogoHeaderCont.classList.add("bytm-menu-title-logo-header-cont");
  2076. const titleCont = document.createElement("div");
  2077. titleCont.classList.add("bytm-menu-titlecont");
  2078. titleCont.role = "heading";
  2079. titleCont.ariaLevel = "1";
  2080. const titleLogoElem = document.createElement("img");
  2081. const logoSrc = await getResourceUrl(`img-logo${mode === "development" ? "_dev" : ""}`);
  2082. titleLogoElem.classList.add("bytm-cfg-menu-logo", "bytm-no-select");
  2083. if (logoSrc)
  2084. titleLogoElem.src = logoSrc;
  2085. titleLogoHeaderCont.appendChild(titleLogoElem);
  2086. const titleElem = document.createElement("h2");
  2087. titleElem.classList.add("bytm-menu-title");
  2088. const titleTextElem = document.createElement("div");
  2089. titleTextElem.textContent = t("config_menu_title", scriptInfo.name);
  2090. titleElem.appendChild(titleTextElem);
  2091. const linksCont = document.createElement("div");
  2092. linksCont.id = "bytm-menu-linkscont";
  2093. linksCont.role = "navigation";
  2094. const linkTitlesShort = {
  2095. github: "GitHub",
  2096. greasyfork: "GreasyFork",
  2097. openuserjs: "OpenUserJS",
  2098. discord: "Discord",
  2099. };
  2100. const addLink = (imgSrc, href, title, titleKey) => {
  2101. const anchorElem = document.createElement("a");
  2102. anchorElem.classList.add("bytm-menu-link", "bytm-no-select");
  2103. anchorElem.rel = "noopener noreferrer";
  2104. anchorElem.href = href;
  2105. anchorElem.target = "_blank";
  2106. anchorElem.tabIndex = 0;
  2107. anchorElem.role = "button";
  2108. anchorElem.ariaLabel = anchorElem.title = title;
  2109. const extendedAnchorEl = document.createElement("a");
  2110. extendedAnchorEl.classList.add("bytm-menu-link", "extended-link", "bytm-no-select");
  2111. extendedAnchorEl.rel = "noopener noreferrer";
  2112. extendedAnchorEl.href = href;
  2113. extendedAnchorEl.target = "_blank";
  2114. extendedAnchorEl.tabIndex = -1;
  2115. extendedAnchorEl.textContent = linkTitlesShort[titleKey];
  2116. extendedAnchorEl.ariaLabel = extendedAnchorEl.title = title;
  2117. const imgElem = document.createElement("img");
  2118. imgElem.classList.add("bytm-menu-img");
  2119. imgElem.src = imgSrc;
  2120. anchorElem.appendChild(imgElem);
  2121. anchorElem.appendChild(extendedAnchorEl);
  2122. linksCont.appendChild(anchorElem);
  2123. };
  2124. const links = [
  2125. ["github", await getResourceUrl("img-github"), scriptInfo.namespace, t("open_github", scriptInfo.name), "github"],
  2126. ["greasyfork", await getResourceUrl("img-greasyfork"), packageJson.hosts.greasyfork, t("open_greasyfork", scriptInfo.name), "greasyfork"],
  2127. ["openuserjs", await getResourceUrl("img-openuserjs"), packageJson.hosts.openuserjs, t("open_openuserjs", scriptInfo.name), "openuserjs"],
  2128. ];
  2129. const hostLink = links.find(([name]) => name === host);
  2130. const otherLinks = links.filter(([name]) => name !== host);
  2131. const reorderedLinks = hostLink ? [hostLink, ...otherLinks] : links;
  2132. for (const [, ...args] of reorderedLinks)
  2133. addLink(...args);
  2134. addLink(await getResourceUrl("img-discord"), "https://dc.sv443.net/", t("open_discord"), "discord");
  2135. const closeElem = document.createElement("img");
  2136. closeElem.classList.add("bytm-menu-close");
  2137. closeElem.role = "button";
  2138. closeElem.tabIndex = 0;
  2139. closeElem.src = await getResourceUrl("img-close");
  2140. closeElem.ariaLabel = closeElem.title = t("close_menu_tooltip");
  2141. onInteraction(closeElem, closeCfgMenu);
  2142. titleCont.appendChild(titleElem);
  2143. titleCont.appendChild(linksCont);
  2144. titleLogoHeaderCont.appendChild(titleCont);
  2145. headerElem.appendChild(titleLogoHeaderCont);
  2146. headerElem.appendChild(closeElem);
  2147. //#region footer
  2148. const footerCont = document.createElement("div");
  2149. footerCont.classList.add("bytm-menu-footer-cont");
  2150. const reloadFooterCont = document.createElement("div");
  2151. const reloadFooterEl = document.createElement("div");
  2152. reloadFooterEl.classList.add("bytm-menu-footer", "hidden");
  2153. reloadFooterEl.setAttribute("aria-hidden", "true");
  2154. reloadFooterEl.textContent = t("reload_hint");
  2155. reloadFooterEl.role = "alert";
  2156. reloadFooterEl.ariaLive = "polite";
  2157. const reloadTxtEl = document.createElement("button");
  2158. reloadTxtEl.classList.add("bytm-btn");
  2159. reloadTxtEl.style.marginLeft = "10px";
  2160. reloadTxtEl.textContent = t("reload_now");
  2161. reloadTxtEl.ariaLabel = reloadTxtEl.title = t("reload_tooltip");
  2162. reloadTxtEl.addEventListener("click", () => {
  2163. closeCfgMenu();
  2164. disableBeforeUnload();
  2165. location.reload();
  2166. });
  2167. reloadFooterEl.appendChild(reloadTxtEl);
  2168. reloadFooterCont.appendChild(reloadFooterEl);
  2169. /** For copying plain when shift-clicking the copy button or when compression is not supported */
  2170. const exportDataSpecial = () => JSON.stringify({ formatVersion, data: getFeatures() });
  2171. const exImDlg = new ExImDialog({
  2172. id: "bytm-config-export-import",
  2173. width: 800,
  2174. height: 600,
  2175. // try to compress the data if possible
  2176. exportData: async () => await compressionSupported()
  2177. ? await UserUtils.compress(JSON.stringify({ formatVersion, data: getFeatures() }), compressionFormat, "string")
  2178. : exportDataSpecial(),
  2179. exportDataSpecial,
  2180. async onImport(data) {
  2181. try {
  2182. const parsed = await tryToDecompressAndParse(data.trim());
  2183. log("Trying to import configuration:", parsed);
  2184. if (!parsed || typeof parsed !== "object")
  2185. return alert(t("import_error_invalid"));
  2186. if (typeof parsed.formatVersion !== "number")
  2187. return alert(t("import_error_no_format_version"));
  2188. if (typeof parsed.data !== "object" || parsed.data === null || Object.keys(parsed.data).length === 0)
  2189. return alert(t("import_error_no_data"));
  2190. if (parsed.formatVersion < formatVersion) {
  2191. let newData = JSON.parse(JSON.stringify(parsed.data));
  2192. const sortedMigrations = Object.entries(migrations)
  2193. .sort(([a], [b]) => Number(a) - Number(b));
  2194. let curFmtVer = Number(parsed.formatVersion);
  2195. for (const [fmtVer, migrationFunc] of sortedMigrations) {
  2196. const ver = Number(fmtVer);
  2197. if (curFmtVer < formatVersion && curFmtVer < ver) {
  2198. try {
  2199. const migRes = JSON.parse(JSON.stringify(migrationFunc(newData)));
  2200. newData = migRes instanceof Promise ? await migRes : migRes;
  2201. curFmtVer = ver;
  2202. }
  2203. catch (err) {
  2204. error(`Error while running migration function for format version ${fmtVer}:`, err);
  2205. }
  2206. }
  2207. }
  2208. parsed.formatVersion = curFmtVer;
  2209. parsed.data = newData;
  2210. }
  2211. else if (parsed.formatVersion !== formatVersion)
  2212. return alert(t("import_error_wrong_format_version", formatVersion, parsed.formatVersion));
  2213. await setFeatures(Object.assign(Object.assign({}, getFeatures()), parsed.data));
  2214. if (confirm(t("import_success_confirm_reload"))) {
  2215. disableBeforeUnload();
  2216. return location.reload();
  2217. }
  2218. exImDlg.unmount();
  2219. emitSiteEvent("rebuildCfgMenu", parsed.data);
  2220. }
  2221. catch (err) {
  2222. warn("Couldn't import configuration:", err);
  2223. alert(t("import_error_invalid"));
  2224. }
  2225. },
  2226. title: () => t("bytm_config_export_import_title"),
  2227. descImport: () => t("bytm_config_import_desc"),
  2228. descExport: () => t("bytm_config_export_desc"),
  2229. });
  2230. const exportImportBtn = document.createElement("button");
  2231. exportImportBtn.classList.add("bytm-btn");
  2232. exportImportBtn.textContent = exportImportBtn.ariaLabel = exportImportBtn.title = t("export_import");
  2233. onInteraction(exportImportBtn, async () => await exImDlg.open());
  2234. const buttonsCont = document.createElement("div");
  2235. buttonsCont.classList.add("bytm-menu-footer-buttons-cont");
  2236. buttonsCont.appendChild(exportImportBtn);
  2237. footerCont.appendChild(reloadFooterCont);
  2238. footerCont.appendChild(buttonsCont);
  2239. //#region feature list
  2240. const featuresCont = document.createElement("div");
  2241. featuresCont.id = "bytm-menu-opts";
  2242. const onCfgChange = async (key, initialVal, newVal) => {
  2243. var _a, _b;
  2244. const fmt = (val) => typeof val === "object" ? JSON.stringify(val) : String(val);
  2245. info(`Feature config changed at key '${key}', from value '${fmt(initialVal)}' to '${fmt(newVal)}'`);
  2246. const featConf = JSON.parse(JSON.stringify(getFeatures()));
  2247. featConf[key] = newVal;
  2248. const changedKeys = initConfig$1 ? Object.keys(featConf).filter((k) => typeof featConf[k] !== "object"
  2249. && featConf[k] !== initConfig$1[k]) : [];
  2250. const requiresReload =
  2251. // @ts-ignore
  2252. changedKeys.some((k) => { var _a; return ((_a = featInfo[k]) === null || _a === void 0 ? void 0 : _a.reloadRequired) !== false; });
  2253. await setFeatures(featConf);
  2254. // @ts-ignore
  2255. (_b = (_a = featInfo[key]) === null || _a === void 0 ? void 0 : _a.change) === null || _b === void 0 ? void 0 : _b.call(_a, key, initialVal, newVal);
  2256. if (requiresReload) {
  2257. reloadFooterEl.classList.remove("hidden");
  2258. reloadFooterEl.setAttribute("aria-hidden", "false");
  2259. }
  2260. else if (!requiresReload) {
  2261. reloadFooterEl.classList.add("hidden");
  2262. reloadFooterEl.setAttribute("aria-hidden", "true");
  2263. }
  2264. if (initLocale !== featConf.locale) {
  2265. await initTranslations(featConf.locale);
  2266. setLocale(featConf.locale);
  2267. const newText = t("lang_changed_prompt_reload");
  2268. const confirmText = newText !== initLangReloadText ? `${newText}\n\n────────────────────────────────\n\n${initLangReloadText}` : newText;
  2269. if (confirm(confirmText)) {
  2270. closeCfgMenu();
  2271. disableBeforeUnload();
  2272. location.reload();
  2273. }
  2274. }
  2275. else if (getLocale() !== featConf.locale)
  2276. setLocale(featConf.locale);
  2277. emitSiteEvent("configOptionChanged", key, initialVal, newVal);
  2278. };
  2279. /** Call whenever the feature config is changed */
  2280. const confChanged = UserUtils.debounce(onCfgChange, 333, "falling");
  2281. const featureCfg = getFeatures();
  2282. const featureCfgWithCategories = Object.entries(featInfo)
  2283. .reduce((acc, [key, { category }]) => {
  2284. if (!acc[category])
  2285. acc[category] = {};
  2286. acc[category][key] = featureCfg[key];
  2287. return acc;
  2288. }, {});
  2289. /**
  2290. * Formats the value `v` based on the provided `key` using the `featInfo` object.
  2291. * If a custom `renderValue` function is defined for the `key`, it will be used to format the value.
  2292. * If no custom `renderValue` function is defined, the value will be converted to a string and trimmed.
  2293. * If the value is an object, it will be converted to a JSON string representation.
  2294. * If an error occurs during formatting (like when passing objects with circular references), the original value will be returned as a string (trimmed).
  2295. */
  2296. const fmtVal = (v, key) => {
  2297. var _a;
  2298. try {
  2299. // @ts-ignore
  2300. const renderValue = typeof ((_a = featInfo === null || featInfo === void 0 ? void 0 : featInfo[key]) === null || _a === void 0 ? void 0 : _a.renderValue) === "function" ? featInfo[key].renderValue : undefined;
  2301. const retVal = (typeof v === "object" ? JSON.stringify(v) : String(v)).trim();
  2302. return renderValue ? renderValue(retVal) : retVal;
  2303. }
  2304. catch (_b) {
  2305. // absolute last resort fallback because stringify throws on circular refs
  2306. return String(v).trim();
  2307. }
  2308. };
  2309. for (const category in featureCfgWithCategories) {
  2310. const featObj = featureCfgWithCategories[category];
  2311. const catHeaderElem = document.createElement("h3");
  2312. catHeaderElem.classList.add("bytm-ftconf-category-header");
  2313. catHeaderElem.role = "heading";
  2314. catHeaderElem.ariaLevel = "2";
  2315. catHeaderElem.tabIndex = 0;
  2316. catHeaderElem.textContent = `${t(`feature_category_${category}`)}:`;
  2317. featuresCont.appendChild(catHeaderElem);
  2318. for (const featKey in featObj) {
  2319. const ftInfo = featInfo[featKey];
  2320. if (!ftInfo || ("hidden" in ftInfo && ftInfo.hidden === true))
  2321. continue;
  2322. if (ftInfo.advanced && !featureCfg.advancedMode)
  2323. continue;
  2324. const { type, default: ftDefault } = ftInfo;
  2325. const step = "step" in ftInfo ? ftInfo.step : undefined;
  2326. const val = featureCfg[featKey];
  2327. const initialVal = (_a = val !== null && val !== void 0 ? val : ftDefault) !== null && _a !== void 0 ? _a : undefined;
  2328. const ftConfElem = document.createElement("div");
  2329. ftConfElem.classList.add("bytm-ftitem");
  2330. {
  2331. const featLeftSideElem = document.createElement("div");
  2332. featLeftSideElem.classList.add("bytm-ftitem-leftside");
  2333. if (getFeature("advancedMode")) {
  2334. const defVal = fmtVal(ftDefault, featKey);
  2335. const extraTxts = [
  2336. `default: ${defVal.length === 0 ? "(undefined)" : defVal}`,
  2337. ];
  2338. "min" in ftInfo && extraTxts.push(`min: ${ftInfo.min}`);
  2339. "max" in ftInfo && extraTxts.push(`max: ${ftInfo.max}`);
  2340. "step" in ftInfo && extraTxts.push(`step: ${ftInfo.step}`);
  2341. const rel = "reloadRequired" in ftInfo && ftInfo.reloadRequired !== false ? " (reload required)" : "";
  2342. const adv = ftInfo.advanced ? " (advanced feature)" : "";
  2343. featLeftSideElem.title = `${featKey}${rel}${adv}${extraTxts.length > 0 ? `\n${extraTxts.join(" - ")}` : ""}`;
  2344. }
  2345. const textElem = document.createElement("span");
  2346. textElem.textContent = t(`feature_desc_${featKey}`);
  2347. let adornmentElem;
  2348. const adornContentAsync = (_b = ftInfo.textAdornment) === null || _b === void 0 ? void 0 : _b.call(ftInfo);
  2349. const adornContent = adornContentAsync instanceof Promise ? await adornContentAsync : adornContentAsync;
  2350. if ((typeof adornContentAsync === "string" || adornContentAsync instanceof Promise) && typeof adornContent !== "undefined") {
  2351. adornmentElem = document.createElement("span");
  2352. adornmentElem.id = `bytm-ftitem-${featKey}-adornment`;
  2353. adornmentElem.classList.add("bytm-ftitem-adornment");
  2354. setInnerHtml(adornmentElem, adornContent);
  2355. }
  2356. let helpElem;
  2357. // @ts-ignore
  2358. const hasHelpTextFunc = typeof ((_c = featInfo[featKey]) === null || _c === void 0 ? void 0 : _c.helpText) === "function";
  2359. // @ts-ignore
  2360. const helpTextVal = hasHelpTextFunc && featInfo[featKey].helpText();
  2361. if (hasKey(`feature_helptext_${featKey}`) || (helpTextVal && hasKey(helpTextVal))) {
  2362. const helpElemImgHtml = await resourceAsString("icon-help");
  2363. if (helpElemImgHtml) {
  2364. helpElem = document.createElement("div");
  2365. helpElem.classList.add("bytm-ftitem-help-btn", "bytm-generic-btn");
  2366. helpElem.ariaLabel = helpElem.title = t("feature_help_button_tooltip", t(`feature_desc_${featKey}`));
  2367. helpElem.role = "button";
  2368. helpElem.tabIndex = 0;
  2369. setInnerHtml(helpElem, helpElemImgHtml);
  2370. onInteraction(helpElem, async (e) => {
  2371. e.preventDefault();
  2372. e.stopPropagation();
  2373. await (await getFeatHelpDialog({ featKey: featKey })).open();
  2374. });
  2375. }
  2376. else {
  2377. error(`Couldn't create help button SVG element for feature '${featKey}'`);
  2378. }
  2379. }
  2380. adornmentElem && featLeftSideElem.appendChild(adornmentElem);
  2381. featLeftSideElem.appendChild(textElem);
  2382. helpElem && featLeftSideElem.appendChild(helpElem);
  2383. ftConfElem.appendChild(featLeftSideElem);
  2384. }
  2385. {
  2386. let inputType = "text";
  2387. let inputTag = "input";
  2388. switch (type) {
  2389. case "toggle":
  2390. inputTag = undefined;
  2391. inputType = undefined;
  2392. break;
  2393. case "slider":
  2394. inputType = "range";
  2395. break;
  2396. case "number":
  2397. inputType = "number";
  2398. break;
  2399. case "text":
  2400. inputType = "text";
  2401. break;
  2402. case "select":
  2403. inputTag = "select";
  2404. inputType = undefined;
  2405. break;
  2406. case "hotkey":
  2407. inputTag = undefined;
  2408. inputType = undefined;
  2409. break;
  2410. case "button":
  2411. inputTag = undefined;
  2412. inputType = undefined;
  2413. break;
  2414. }
  2415. const inputElemId = `bytm-ftconf-${featKey}-input`;
  2416. const ctrlElem = document.createElement("span");
  2417. ctrlElem.classList.add("bytm-ftconf-ctrl");
  2418. let advCopyHiddenCont;
  2419. if ((getFeature("advancedMode") || mode === "development") && ftInfo.valueHidden) {
  2420. const advCopyHintElem = document.createElement("span");
  2421. advCopyHintElem.classList.add("bytm-ftconf-adv-copy-hint");
  2422. advCopyHintElem.textContent = t("copied");
  2423. advCopyHintElem.role = "status";
  2424. advCopyHintElem.style.display = "none";
  2425. const advCopyHiddenBtn = document.createElement("button");
  2426. advCopyHiddenBtn.classList.add("bytm-ftconf-adv-copy-btn", "bytm-btn");
  2427. advCopyHiddenBtn.tabIndex = 0;
  2428. advCopyHiddenBtn.textContent = t("copy_hidden");
  2429. advCopyHiddenBtn.ariaLabel = advCopyHiddenBtn.title = t("copy_hidden_tooltip");
  2430. const copyHiddenInteraction = (e) => {
  2431. e.preventDefault();
  2432. e.stopPropagation();
  2433. copyToClipboard(getFeatures()[featKey]);
  2434. advCopyHintElem.style.display = "inline";
  2435. if (typeof hiddenCopiedTxtTimeout === "undefined") {
  2436. hiddenCopiedTxtTimeout = setTimeout(() => {
  2437. advCopyHintElem.style.display = "none";
  2438. hiddenCopiedTxtTimeout = undefined;
  2439. }, 3000);
  2440. }
  2441. };
  2442. onInteraction(advCopyHiddenBtn, copyHiddenInteraction);
  2443. advCopyHiddenCont = document.createElement("span");
  2444. advCopyHiddenCont.appendChild(advCopyHintElem);
  2445. advCopyHiddenCont.appendChild(advCopyHiddenBtn);
  2446. }
  2447. advCopyHiddenCont && ctrlElem.appendChild(advCopyHiddenCont);
  2448. if (inputTag) {
  2449. // standard input element:
  2450. const inputElem = document.createElement(inputTag);
  2451. inputElem.classList.add("bytm-ftconf-input");
  2452. inputElem.id = inputElemId;
  2453. inputElem.ariaLabel = t(`feature_desc_${featKey}`);
  2454. if (inputType)
  2455. inputElem.type = inputType;
  2456. if ("min" in ftInfo && typeof ftInfo.min !== "undefined")
  2457. inputElem.min = String(ftInfo.min);
  2458. if ("max" in ftInfo && typeof ftInfo.max !== "undefined")
  2459. inputElem.max = String(ftInfo.max);
  2460. if (typeof initialVal !== "undefined")
  2461. inputElem.value = String(initialVal);
  2462. if (type === "text" && ftInfo.valueHidden) {
  2463. inputElem.type = "password";
  2464. inputElem.autocomplete = "off";
  2465. }
  2466. if (type === "number" || type === "slider" && step)
  2467. inputElem.step = String(step);
  2468. if (type === "toggle" && typeof initialVal !== "undefined")
  2469. inputElem.checked = Boolean(initialVal);
  2470. const unitTxt = ("unit" in ftInfo && typeof ftInfo.unit === "string"
  2471. ? ftInfo.unit
  2472. : ("unit" in ftInfo && typeof ftInfo.unit === "function"
  2473. ? ftInfo.unit(Number(inputElem.value))
  2474. : ""));
  2475. let labelElem;
  2476. let lastDisplayedVal;
  2477. if (type === "slider") {
  2478. labelElem = document.createElement("label");
  2479. labelElem.classList.add("bytm-ftconf-label", "bytm-slider-label");
  2480. labelElem.textContent = `${fmtVal(initialVal, featKey)}${unitTxt}`;
  2481. inputElem.addEventListener("input", () => {
  2482. if (labelElem && lastDisplayedVal !== inputElem.value) {
  2483. labelElem.textContent = `${fmtVal(inputElem.value, featKey)}${unitTxt}`;
  2484. lastDisplayedVal = inputElem.value;
  2485. }
  2486. });
  2487. }
  2488. else if (type === "select") {
  2489. const ftOpts = typeof ftInfo.options === "function"
  2490. ? ftInfo.options()
  2491. : ftInfo.options;
  2492. for (const { value, label } of ftOpts) {
  2493. const optionElem = document.createElement("option");
  2494. optionElem.value = String(value);
  2495. optionElem.textContent = label;
  2496. if (value === initialVal)
  2497. optionElem.selected = true;
  2498. inputElem.appendChild(optionElem);
  2499. }
  2500. }
  2501. if (type === "text") {
  2502. let lastValue = inputElem.value && inputElem.value.length > 0 ? inputElem.value : ftInfo.default;
  2503. const textInputUpdate = () => {
  2504. let v = String(inputElem.value).trim();
  2505. if (type === "text" && ftInfo.normalize)
  2506. v = inputElem.value = ftInfo.normalize(String(v));
  2507. if (v === lastValue)
  2508. return;
  2509. lastValue = v;
  2510. if (v === "")
  2511. v = ftInfo.default;
  2512. if (typeof initialVal !== "undefined")
  2513. confChanged(featKey, initialVal, v);
  2514. };
  2515. const unsub = siteEvents.on("cfgMenuClosed", () => {
  2516. unsub();
  2517. textInputUpdate();
  2518. });
  2519. inputElem.addEventListener("blur", () => textInputUpdate());
  2520. inputElem.addEventListener("keydown", (e) => e.key === "Tab" && textInputUpdate());
  2521. }
  2522. else {
  2523. inputElem.addEventListener("input", () => {
  2524. let v = String(inputElem.value).trim();
  2525. if (["number", "slider"].includes(type) || v.match(/^-?\d+$/))
  2526. v = Number(v);
  2527. if (typeof initialVal !== "undefined")
  2528. confChanged(featKey, initialVal, (type !== "toggle" ? v : inputElem.checked));
  2529. });
  2530. }
  2531. if (labelElem) {
  2532. labelElem.id = `bytm-ftconf-${featKey}-label`;
  2533. labelElem.htmlFor = inputElemId;
  2534. ctrlElem.appendChild(labelElem);
  2535. }
  2536. ctrlElem.appendChild(inputElem);
  2537. }
  2538. else {
  2539. // custom input element:
  2540. let customInputEl;
  2541. switch (type) {
  2542. case "hotkey":
  2543. customInputEl = createHotkeyInput({
  2544. initialValue: typeof initialVal === "object" ? initialVal : undefined,
  2545. onChange: (hotkey) => confChanged(featKey, initialVal, hotkey),
  2546. createTitle: (value) => t("hotkey_input_click_to_change_tooltip", t(`feature_desc_${featKey}`), value),
  2547. });
  2548. break;
  2549. case "toggle":
  2550. customInputEl = await createToggleInput({
  2551. initialValue: Boolean(initialVal),
  2552. onChange: (checked) => confChanged(featKey, initialVal, checked),
  2553. id: `ftconf-${featKey}`,
  2554. labelPos: "left",
  2555. });
  2556. break;
  2557. case "button":
  2558. customInputEl = document.createElement("button");
  2559. customInputEl.classList.add("bytm-btn");
  2560. customInputEl.tabIndex = 0;
  2561. customInputEl.textContent = hasKey(`feature_btn_${featKey}`) ? t(`feature_btn_${featKey}`) : t("trigger_btn_action");
  2562. customInputEl.ariaLabel = customInputEl.title = t(`feature_desc_${featKey}`);
  2563. onInteraction(customInputEl, async () => {
  2564. if (customInputEl.disabled)
  2565. return;
  2566. const startTs = Date.now();
  2567. const res = ftInfo.click();
  2568. customInputEl.disabled = true;
  2569. customInputEl.classList.add("bytm-busy");
  2570. customInputEl.textContent = customInputEl.ariaLabel = customInputEl.title = hasKey(`feature_btn_${featKey}_running`) ? t(`feature_btn_${featKey}_running`) : t("trigger_btn_action_running");
  2571. if (res instanceof Promise)
  2572. await res;
  2573. const finalize = () => {
  2574. customInputEl.disabled = false;
  2575. customInputEl.classList.remove("bytm-busy");
  2576. customInputEl.textContent = customInputEl.ariaLabel = customInputEl.title = hasKey(`feature_btn_${featKey}`) ? t(`feature_btn_${featKey}`) : t("trigger_btn_action");
  2577. };
  2578. // artificial timeout ftw
  2579. if (Date.now() - startTs < 350)
  2580. setTimeout(finalize, 350 - (Date.now() - startTs));
  2581. else
  2582. finalize();
  2583. });
  2584. break;
  2585. }
  2586. if (customInputEl && !customInputEl.hasAttribute("aria-label"))
  2587. customInputEl.ariaLabel = t(`feature_desc_${featKey}`);
  2588. ctrlElem.appendChild(customInputEl);
  2589. }
  2590. ftConfElem.appendChild(ctrlElem);
  2591. }
  2592. featuresCont.appendChild(ftConfElem);
  2593. }
  2594. }
  2595. //#region reset inputs on external change
  2596. siteEvents.on("rebuildCfgMenu", (newConfig) => {
  2597. for (const ftKey in featInfo) {
  2598. const ftElem = document.querySelector(`#bytm-ftconf-${ftKey}-input`);
  2599. const labelElem = document.querySelector(`#bytm-ftconf-${ftKey}-label`);
  2600. if (!ftElem)
  2601. continue;
  2602. const ftInfo = featInfo[ftKey];
  2603. const value = newConfig[ftKey];
  2604. if (ftInfo.type === "toggle")
  2605. ftElem.checked = Boolean(value);
  2606. else
  2607. ftElem.value = String(value);
  2608. if (!labelElem)
  2609. continue;
  2610. const unitTxt = ("unit" in ftInfo && typeof ftInfo.unit === "string"
  2611. ? ftInfo.unit
  2612. : ("unit" in ftInfo && typeof ftInfo.unit === "function"
  2613. ? ftInfo.unit(Number(ftElem.value))
  2614. : ""));
  2615. if (ftInfo.type === "slider")
  2616. labelElem.textContent = `${fmtVal(Number(value), ftKey)}${unitTxt}`;
  2617. }
  2618. info("Rebuilt config menu");
  2619. });
  2620. //#region scroll indicator
  2621. const scrollIndicator = document.createElement("img");
  2622. scrollIndicator.id = "bytm-menu-scroll-indicator";
  2623. scrollIndicator.src = await getResourceUrl("icon-arrow_down");
  2624. scrollIndicator.role = "button";
  2625. scrollIndicator.ariaLabel = scrollIndicator.title = t("scroll_to_bottom");
  2626. featuresCont.appendChild(scrollIndicator);
  2627. scrollIndicator.addEventListener("click", () => {
  2628. const bottomAnchor = document.querySelector("#bytm-menu-bottom-anchor");
  2629. bottomAnchor === null || bottomAnchor === void 0 ? void 0 : bottomAnchor.scrollIntoView({
  2630. behavior: "smooth",
  2631. });
  2632. });
  2633. featuresCont.addEventListener("scroll", (evt) => {
  2634. var _a, _b;
  2635. const scrollPos = (_b = (_a = evt.target) === null || _a === void 0 ? void 0 : _a.scrollTop) !== null && _b !== void 0 ? _b : 0;
  2636. const scrollIndicator = document.querySelector("#bytm-menu-scroll-indicator");
  2637. if (!scrollIndicator)
  2638. return;
  2639. if (scrollIndicatorEnabled && scrollPos > scrollIndicatorOffsetThreshold && !scrollIndicator.classList.contains("bytm-hidden")) {
  2640. scrollIndicator.classList.add("bytm-hidden");
  2641. }
  2642. else if (scrollIndicatorEnabled && scrollPos <= scrollIndicatorOffsetThreshold && scrollIndicator.classList.contains("bytm-hidden")) {
  2643. scrollIndicator.classList.remove("bytm-hidden");
  2644. }
  2645. });
  2646. const bottomAnchor = document.createElement("div");
  2647. bottomAnchor.id = "bytm-menu-bottom-anchor";
  2648. featuresCont.appendChild(bottomAnchor);
  2649. //#region finalize
  2650. menuContainer.appendChild(headerElem);
  2651. menuContainer.appendChild(featuresCont);
  2652. const subtitleElemCont = document.createElement("div");
  2653. subtitleElemCont.id = "bytm-menu-subtitle-cont";
  2654. const versionEl = document.createElement("a");
  2655. versionEl.id = "bytm-menu-version-anchor";
  2656. versionEl.classList.add("bytm-link");
  2657. versionEl.role = "button";
  2658. versionEl.tabIndex = 0;
  2659. versionEl.ariaLabel = versionEl.title = t("version_tooltip", scriptInfo.version, buildNumber);
  2660. versionEl.textContent = `v${scriptInfo.version} (#${buildNumber})`;
  2661. onInteraction(versionEl, async (e) => {
  2662. e.preventDefault();
  2663. e.stopPropagation();
  2664. const dlg = await getChangelogDialog();
  2665. dlg.on("close", openCfgMenu);
  2666. await dlg.mount();
  2667. closeCfgMenu(undefined, false);
  2668. await dlg.open();
  2669. });
  2670. subtitleElemCont.appendChild(versionEl);
  2671. titleElem.appendChild(subtitleElemCont);
  2672. const modeItems = [];
  2673. mode === "development" && modeItems.push("dev_mode");
  2674. getFeature("advancedMode") && modeItems.push("advanced_mode");
  2675. if (modeItems.length > 0) {
  2676. const modeDisplayEl = document.createElement("span");
  2677. modeDisplayEl.id = "bytm-menu-mode-display";
  2678. modeDisplayEl.textContent = `[${t("active_mode_display", arrayWithSeparators(modeItems.map(v => t(`${v}_short`)), ", ", " & "))}]`;
  2679. modeDisplayEl.ariaLabel = modeDisplayEl.title = tp("active_mode_tooltip", modeItems, arrayWithSeparators(modeItems.map(t), ", ", " & "));
  2680. subtitleElemCont.appendChild(modeDisplayEl);
  2681. }
  2682. menuContainer.appendChild(footerCont);
  2683. backgroundElem.appendChild(menuContainer);
  2684. document.body.appendChild(backgroundElem);
  2685. window.addEventListener("resize", UserUtils.debounce(checkToggleScrollIndicator, 250, "rising"));
  2686. log("Added menu element");
  2687. // ensure stuff is reset if menu was opened before being added
  2688. isCfgMenuOpen = false;
  2689. document.body.classList.remove("bytm-disable-scroll");
  2690. (_d = document.querySelector(getDomain() === "ytm" ? "ytmusic-app" : "ytd-app")) === null || _d === void 0 ? void 0 : _d.removeAttribute("inert");
  2691. backgroundElem.style.visibility = "hidden";
  2692. backgroundElem.style.display = "none";
  2693. siteEvents.on("recreateCfgMenu", async () => {
  2694. const bgElem = document.querySelector("#bytm-cfg-menu-bg");
  2695. if (!bgElem)
  2696. return;
  2697. closeCfgMenu();
  2698. bgElem.remove();
  2699. isCfgMenuMounted = false;
  2700. await mountCfgMenu();
  2701. await openCfgMenu();
  2702. });
  2703. }
  2704. //#region open & close
  2705. /** Closes the config menu if it is open. If a bubbling event is passed, its propagation will be prevented. */
  2706. function closeCfgMenu(evt, enableScroll = true) {
  2707. var _a, _b, _c;
  2708. if (!isCfgMenuOpen)
  2709. return;
  2710. isCfgMenuOpen = false;
  2711. (evt === null || evt === void 0 ? void 0 : evt.bubbles) && evt.stopPropagation();
  2712. if (enableScroll) {
  2713. document.body.classList.remove("bytm-disable-scroll");
  2714. (_a = document.querySelector(getDomain() === "ytm" ? "ytmusic-app" : "ytd-app")) === null || _a === void 0 ? void 0 : _a.removeAttribute("inert");
  2715. }
  2716. const menuBg = document.querySelector("#bytm-cfg-menu-bg");
  2717. clearTimeout(hiddenCopiedTxtTimeout);
  2718. openDialogs.splice(openDialogs.indexOf("cfg-menu"), 1);
  2719. setCurrentDialogId((_b = openDialogs === null || openDialogs === void 0 ? void 0 : openDialogs[0]) !== null && _b !== void 0 ? _b : null);
  2720. // since this menu doesn't have a BytmDialog instance, it's undefined here
  2721. emitInterface("bytm:dialogClosed", undefined);
  2722. emitInterface("bytm:dialogClosed:cfg-menu", undefined);
  2723. if (!menuBg)
  2724. return warn("Couldn't close config menu because background element couldn't be found. The config menu is considered closed but might still be open. In this case please reload the page. If the issue persists, please create an issue on GitHub.");
  2725. (_c = menuBg.querySelectorAll(".bytm-ftconf-adv-copy-hint")) === null || _c === void 0 ? void 0 : _c.forEach((el) => el.style.display = "none");
  2726. menuBg.style.visibility = "hidden";
  2727. menuBg.style.display = "none";
  2728. }
  2729. /** Opens the config menu if it is closed */
  2730. async function openCfgMenu() {
  2731. var _a;
  2732. if (!isCfgMenuMounted)
  2733. await mountCfgMenu();
  2734. if (isCfgMenuOpen)
  2735. return;
  2736. isCfgMenuOpen = true;
  2737. document.body.classList.add("bytm-disable-scroll");
  2738. (_a = document.querySelector(getDomain() === "ytm" ? "ytmusic-app" : "ytd-app")) === null || _a === void 0 ? void 0 : _a.setAttribute("inert", "true");
  2739. const menuBg = document.querySelector("#bytm-cfg-menu-bg");
  2740. setCurrentDialogId("cfg-menu");
  2741. openDialogs.unshift("cfg-menu");
  2742. // since this menu doesn't have a BytmDialog instance, it's undefined here
  2743. emitInterface("bytm:dialogOpened", undefined);
  2744. emitInterface("bytm:dialogOpened:cfg-menu", undefined);
  2745. checkToggleScrollIndicator();
  2746. if (!menuBg)
  2747. return warn("Couldn't open config menu because background element couldn't be found. The config menu is considered open but might still be closed. In this case please reload the page. If the issue persists, please create an issue on GitHub.");
  2748. menuBg.style.visibility = "visible";
  2749. menuBg.style.display = "block";
  2750. }
  2751. //#region chk scroll indicator
  2752. /** Checks if the features container is scrollable and toggles the scroll indicator accordingly */
  2753. function checkToggleScrollIndicator() {
  2754. const featuresCont = document.querySelector("#bytm-menu-opts");
  2755. const scrollIndicator = document.querySelector("#bytm-menu-scroll-indicator");
  2756. // disable scroll indicator if container doesn't scroll
  2757. if (featuresCont && scrollIndicator) {
  2758. const verticalScroll = UserUtils.isScrollable(featuresCont).vertical;
  2759. /** If true, the indicator's threshold is under the available scrollable space and so it should be disabled */
  2760. const underThreshold = featuresCont.scrollHeight - featuresCont.clientHeight <= scrollIndicatorOffsetThreshold;
  2761. if (!underThreshold && verticalScroll && !scrollIndicatorEnabled) {
  2762. scrollIndicatorEnabled = true;
  2763. scrollIndicator.classList.remove("bytm-hidden");
  2764. }
  2765. if ((!verticalScroll && scrollIndicatorEnabled) || underThreshold) {
  2766. scrollIndicatorEnabled = false;
  2767. scrollIndicator.classList.add("bytm-hidden");
  2768. }
  2769. }
  2770. }var de_DE = {
  2771. name: "Deutsch (Deutschland)",
  2772. nameEnglish: "German",
  2773. emoji: "🇩🇪",
  2774. userscriptDesc: "Konfigurierbare Layout- und Benutzererfahrungs-Verbesserungen für YouTube Music™ und YouTube™",
  2775. authors: [
  2776. "Sv443"
  2777. ]
  2778. };
  2779. var en_US = {
  2780. name: "English (United States)",
  2781. nameEnglish: "English (US)",
  2782. emoji: "🇺🇸",
  2783. userscriptDesc: "Configurable layout and user experience improvements for YouTube Music™ and YouTube™",
  2784. authors: [
  2785. "Sv443"
  2786. ]
  2787. };
  2788. var en_UK = {
  2789. name: "English (United Kingdom)",
  2790. nameEnglish: "English (UK)",
  2791. emoji: "🇬🇧",
  2792. userscriptDesc: "Configurable layout and user experience improvements for YouTube Music™ and YouTube™",
  2793. authors: [
  2794. "Sv443"
  2795. ]
  2796. };
  2797. var es_ES = {
  2798. name: "Español (España)",
  2799. nameEnglish: "Spanish",
  2800. emoji: "🇪🇸",
  2801. userscriptDesc: "Mejoras de diseño y experiencia de usuario configurables para YouTube Music™ y YouTube™",
  2802. authors: [
  2803. "Sv443"
  2804. ]
  2805. };
  2806. var fr_FR = {
  2807. name: "Français (France)",
  2808. nameEnglish: "French",
  2809. emoji: "🇫🇷",
  2810. userscriptDesc: "Améliorations de la mise en page et de l'expérience utilisateur configurables pour YouTube Music™ et YouTube™",
  2811. authors: [
  2812. "Sv443"
  2813. ]
  2814. };
  2815. var hi_IN = {
  2816. name: "हिंदी (भारत)",
  2817. nameEnglish: "Hindi",
  2818. emoji: "🇮🇳",
  2819. userscriptDesc: "YouTube Music™ और YouTube™ के लिए कॉन्फ़िगर करने योग्य लेआउट और उपयोगकर्ता अनुभव में सुधार",
  2820. authors: [
  2821. "Sv443"
  2822. ]
  2823. };
  2824. var ja_JA = {
  2825. name: "日本語 (日本)",
  2826. nameEnglish: "Japanese",
  2827. emoji: "🇯🇵",
  2828. userscriptDesc: "YouTube Music™ と YouTube™ の構成可能なレイアウトとユーザー エクスペリエンスの向上",
  2829. authors: [
  2830. "Sv443"
  2831. ]
  2832. };
  2833. var pt_BR = {
  2834. name: "Português (Brasil)",
  2835. nameEnglish: "Portuguese",
  2836. emoji: "🇵🇹",
  2837. userscriptDesc: "Melhorias configuráveis no layout e na experiência do usuário para o YouTube Music™ e o YouTube™",
  2838. authors: [
  2839. "Sv443"
  2840. ]
  2841. };
  2842. var zh_CN = {
  2843. name: "中文(简化,中国)",
  2844. nameEnglish: "Chinese (simpl.)",
  2845. emoji: "🇨🇳",
  2846. userscriptDesc: "YouTube Music™ 和 YouTube™ 的可配置布局和用户体验改进",
  2847. authors: [
  2848. "Sv443"
  2849. ]
  2850. };
  2851. var langMapping = {
  2852. de_DE: de_DE,
  2853. en_US: en_US,
  2854. en_UK: en_UK,
  2855. es_ES: es_ES,
  2856. fr_FR: fr_FR,
  2857. hi_IN: hi_IN,
  2858. ja_JA: ja_JA,
  2859. pt_BR: pt_BR,
  2860. zh_CN: zh_CN
  2861. };let welcomeDialog = null;
  2862. /** Creates and/or returns the import dialog */
  2863. async function getWelcomeDialog() {
  2864. if (!welcomeDialog) {
  2865. welcomeDialog = new BytmDialog({
  2866. id: "welcome",
  2867. width: 700,
  2868. height: 500,
  2869. closeBtnEnabled: true,
  2870. closeOnBgClick: true,
  2871. closeOnEscPress: true,
  2872. destroyOnClose: true,
  2873. renderHeader,
  2874. renderBody,
  2875. renderFooter,
  2876. });
  2877. welcomeDialog.on("render", retranslateWelcomeMenu);
  2878. }
  2879. return welcomeDialog;
  2880. }
  2881. async function renderHeader() {
  2882. const titleWrapperElem = document.createElement("div");
  2883. titleWrapperElem.id = "bytm-welcome-menu-title-wrapper";
  2884. const titleLogoElem = document.createElement("img");
  2885. titleLogoElem.id = "bytm-welcome-menu-title-logo";
  2886. titleLogoElem.classList.add("bytm-no-select");
  2887. titleLogoElem.src = await getResourceUrl(mode === "development" ? "img-logo_dev" : "img-logo");
  2888. const titleElem = document.createElement("h2");
  2889. titleElem.id = "bytm-welcome-menu-title";
  2890. titleElem.classList.add("bytm-dialog-title");
  2891. titleElem.role = "heading";
  2892. titleElem.ariaLevel = "1";
  2893. titleElem.tabIndex = 0;
  2894. titleWrapperElem.appendChild(titleLogoElem);
  2895. titleWrapperElem.appendChild(titleElem);
  2896. return titleWrapperElem;
  2897. }
  2898. async function renderBody() {
  2899. const contentWrapper = document.createElement("div");
  2900. contentWrapper.id = "bytm-welcome-menu-content-wrapper";
  2901. // locale switcher
  2902. const localeCont = document.createElement("div");
  2903. localeCont.id = "bytm-welcome-menu-locale-cont";
  2904. const localeImg = document.createElement("img");
  2905. localeImg.id = "bytm-welcome-menu-locale-img";
  2906. localeImg.classList.add("bytm-no-select");
  2907. localeImg.src = await getResourceUrl("icon-globe");
  2908. const localeSelectElem = document.createElement("select");
  2909. localeSelectElem.id = "bytm-welcome-menu-locale-select";
  2910. for (const [locale, { name }] of Object.entries(langMapping)) {
  2911. const localeOptionElem = document.createElement("option");
  2912. localeOptionElem.value = locale;
  2913. localeOptionElem.textContent = name;
  2914. localeSelectElem.appendChild(localeOptionElem);
  2915. }
  2916. localeSelectElem.value = getFeature("locale");
  2917. localeSelectElem.addEventListener("change", async () => {
  2918. const selectedLocale = localeSelectElem.value;
  2919. const feats = Object.assign({}, getFeatures());
  2920. feats.locale = selectedLocale;
  2921. setFeatures(feats);
  2922. await initTranslations(selectedLocale);
  2923. setLocale(selectedLocale);
  2924. retranslateWelcomeMenu();
  2925. });
  2926. localeCont.appendChild(localeImg);
  2927. localeCont.appendChild(localeSelectElem);
  2928. contentWrapper.appendChild(localeCont);
  2929. // text
  2930. const textCont = document.createElement("div");
  2931. textCont.id = "bytm-welcome-menu-text-cont";
  2932. const textElem = document.createElement("p");
  2933. textElem.id = "bytm-welcome-menu-text";
  2934. const textElems = [];
  2935. const line1Elem = document.createElement("span");
  2936. line1Elem.id = "bytm-welcome-text-line1";
  2937. line1Elem.tabIndex = 0;
  2938. textElems.push(line1Elem);
  2939. const br1Elem = document.createElement("br");
  2940. textElems.push(br1Elem);
  2941. const line2Elem = document.createElement("span");
  2942. line2Elem.id = "bytm-welcome-text-line2";
  2943. line2Elem.tabIndex = 0;
  2944. textElems.push(line2Elem);
  2945. const br2Elem = document.createElement("br");
  2946. textElems.push(br2Elem);
  2947. const br3Elem = document.createElement("br");
  2948. textElems.push(br3Elem);
  2949. const line3Elem = document.createElement("span");
  2950. line3Elem.id = "bytm-welcome-text-line3";
  2951. line3Elem.tabIndex = 0;
  2952. textElems.push(line3Elem);
  2953. const br4Elem = document.createElement("br");
  2954. textElems.push(br4Elem);
  2955. const line4Elem = document.createElement("span");
  2956. line4Elem.id = "bytm-welcome-text-line4";
  2957. line4Elem.tabIndex = 0;
  2958. textElems.push(line4Elem);
  2959. const br5Elem = document.createElement("br");
  2960. textElems.push(br5Elem);
  2961. const br6Elem = document.createElement("br");
  2962. textElems.push(br6Elem);
  2963. const line5Elem = document.createElement("span");
  2964. line5Elem.id = "bytm-welcome-text-line5";
  2965. line5Elem.tabIndex = 0;
  2966. textElems.push(line5Elem);
  2967. textElems.forEach((elem) => textElem.appendChild(elem));
  2968. textCont.appendChild(textElem);
  2969. contentWrapper.appendChild(textCont);
  2970. return contentWrapper;
  2971. }
  2972. /** Retranslates all elements inside the welcome menu */
  2973. function retranslateWelcomeMenu() {
  2974. const getLink = (href) => {
  2975. return [`<a href="${href}" class="bytm-link" target="_blank" rel="noopener noreferrer">`, "</a>"];
  2976. };
  2977. const changes = {
  2978. "#bytm-welcome-menu-title": (e) => e.textContent = e.ariaLabel = t("welcome_menu_title", scriptInfo.name),
  2979. "#bytm-welcome-menu-title-close": (e) => e.ariaLabel = e.title = t("close_menu_tooltip"),
  2980. "#bytm-welcome-menu-open-cfg": (e) => {
  2981. e.textContent = e.ariaLabel = t("config_menu");
  2982. e.ariaLabel = e.title = t("open_config_menu_tooltip");
  2983. },
  2984. "#bytm-welcome-menu-open-changelog": (e) => {
  2985. e.textContent = e.ariaLabel = t("open_changelog");
  2986. e.ariaLabel = e.title = t("open_changelog_tooltip");
  2987. },
  2988. "#bytm-welcome-menu-footer-close": (e) => {
  2989. e.textContent = e.ariaLabel = t("close");
  2990. e.ariaLabel = e.title = t("close_menu_tooltip");
  2991. },
  2992. "#bytm-welcome-text-line1": (e) => setInnerHtml(e, e.ariaLabel = t("welcome_text_line_1")),
  2993. "#bytm-welcome-text-line2": (e) => setInnerHtml(e, e.ariaLabel = t("welcome_text_line_2", scriptInfo.name)),
  2994. "#bytm-welcome-text-line3": (e) => setInnerHtml(e, e.ariaLabel = t("welcome_text_line_3", scriptInfo.name, ...getLink(`${packageJson.hosts.greasyfork}/feedback`), ...getLink(packageJson.hosts.openuserjs))),
  2995. "#bytm-welcome-text-line4": (e) => setInnerHtml(e, e.ariaLabel = t("welcome_text_line_4", ...getLink(packageJson.funding.url))),
  2996. "#bytm-welcome-text-line5": (e) => setInnerHtml(e, e.ariaLabel = t("welcome_text_line_5", ...getLink(packageJson.bugs.url))),
  2997. };
  2998. for (const [selector, fn] of Object.entries(changes)) {
  2999. const el = document.querySelector(selector);
  3000. if (!el) {
  3001. warn(`Couldn't find element in welcome menu with selector '${selector}'`);
  3002. continue;
  3003. }
  3004. fn(el);
  3005. }
  3006. }
  3007. async function renderFooter() {
  3008. const footerCont = document.createElement("div");
  3009. footerCont.id = "bytm-welcome-menu-footer-cont";
  3010. const openCfgElem = document.createElement("button");
  3011. openCfgElem.id = "bytm-welcome-menu-open-cfg";
  3012. openCfgElem.classList.add("bytm-btn");
  3013. openCfgElem.addEventListener("click", () => {
  3014. welcomeDialog === null || welcomeDialog === void 0 ? void 0 : welcomeDialog.close();
  3015. openCfgMenu();
  3016. });
  3017. const openChangelogElem = document.createElement("button");
  3018. openChangelogElem.id = "bytm-welcome-menu-open-changelog";
  3019. openChangelogElem.classList.add("bytm-btn");
  3020. openChangelogElem.addEventListener("click", async () => {
  3021. const dlg = await getChangelogDialog();
  3022. await dlg.mount();
  3023. welcomeDialog === null || welcomeDialog === void 0 ? void 0 : welcomeDialog.close();
  3024. await dlg.open();
  3025. });
  3026. const closeBtnElem = document.createElement("button");
  3027. closeBtnElem.id = "bytm-welcome-menu-footer-close";
  3028. closeBtnElem.classList.add("bytm-btn");
  3029. closeBtnElem.addEventListener("click", async () => {
  3030. welcomeDialog === null || welcomeDialog === void 0 ? void 0 : welcomeDialog.close();
  3031. });
  3032. const leftButtonsCont = document.createElement("div");
  3033. leftButtonsCont.id = "bytm-menu-footer-left-buttons-cont";
  3034. leftButtonsCont.appendChild(openCfgElem);
  3035. leftButtonsCont.appendChild(openChangelogElem);
  3036. footerCont.appendChild(leftButtonsCont);
  3037. footerCont.appendChild(closeBtnElem);
  3038. return footerCont;
  3039. }const releaseURL = "https://github.com/Sv443/BetterYTM/releases/latest";
  3040. /** Initializes the version check feature */
  3041. async function initVersionCheck() {
  3042. try {
  3043. if (getFeature("versionCheck") === false)
  3044. return info("Version check is disabled");
  3045. const lastCheck = await GM.getValue("bytm-version-check", 0);
  3046. if (Date.now() - lastCheck < 1000 * 60 * 60 * 24)
  3047. return;
  3048. await doVersionCheck(false);
  3049. }
  3050. catch (err) {
  3051. error("Version check failed:", err);
  3052. }
  3053. }
  3054. /**
  3055. * Checks for a new version of the script and shows a dialog.
  3056. * If {@linkcode notifyNoUpdatesFound} is set to true, a dialog is also shown if no updates were found.
  3057. */
  3058. async function doVersionCheck(notifyNoUpdatesFound = false) {
  3059. var _a;
  3060. await GM.setValue("bytm-version-check", Date.now());
  3061. const res = await sendRequest({
  3062. method: "GET",
  3063. url: releaseURL,
  3064. });
  3065. // TODO: small dialog for "no update found" message?
  3066. const noUpdateFound = () => notifyNoUpdatesFound ? alert(t("no_updates_found")) : undefined;
  3067. const latestTag = (_a = res.finalUrl.split("/").pop()) === null || _a === void 0 ? void 0 : _a.replace(/[a-zA-Z]/g, "");
  3068. if (!latestTag)
  3069. return noUpdateFound();
  3070. info("Version check - current version:", scriptInfo.version, "- latest version:", latestTag, LogLevel.Info);
  3071. if (compareVersions.compare(scriptInfo.version, latestTag, "<")) {
  3072. const dialog = await getVersionNotifDialog({ latestTag });
  3073. await dialog.open();
  3074. return;
  3075. }
  3076. return noUpdateFound();
  3077. }//#region cfg menu btns
  3078. let logoExchanged = false, improveLogoCalled = false;
  3079. /** Adds a watermark beneath the logo */
  3080. async function addWatermark() {
  3081. const watermark = document.createElement("a");
  3082. watermark.role = "button";
  3083. watermark.id = "bytm-watermark";
  3084. watermark.classList.add("style-scope", "ytmusic-nav-bar", "bytm-no-select");
  3085. watermark.textContent = scriptInfo.name;
  3086. watermark.ariaLabel = watermark.title = t("open_menu_tooltip", scriptInfo.name);
  3087. watermark.tabIndex = 0;
  3088. improveLogo();
  3089. const watermarkOpenMenu = (e) => {
  3090. e.stopPropagation();
  3091. if ((!e.shiftKey && !e.ctrlKey) || logoExchanged)
  3092. openCfgMenu();
  3093. if (!logoExchanged && (e.shiftKey || e.ctrlKey))
  3094. exchangeLogo();
  3095. };
  3096. onInteraction(watermark, watermarkOpenMenu);
  3097. addSelectorListener("navBar", "ytmusic-nav-bar #left-content", {
  3098. listener: (logoElem) => logoElem.insertAdjacentElement("afterend", watermark),
  3099. });
  3100. log("Added watermark element");
  3101. }
  3102. /** Turns the regular `<img>`-based logo into inline SVG to be able to animate and modify parts of it */
  3103. async function improveLogo() {
  3104. try {
  3105. if (improveLogoCalled)
  3106. return;
  3107. improveLogoCalled = true;
  3108. const res = await UserUtils.fetchAdvanced("https://music.youtube.com/img/on_platform_logo_dark.svg");
  3109. const svg = await res.text();
  3110. addSelectorListener("navBar", "ytmusic-logo a", {
  3111. listener: (logoElem) => {
  3112. var _a;
  3113. logoElem.classList.add("bytm-mod-logo", "bytm-no-select");
  3114. setInnerHtml(logoElem, svg);
  3115. logoElem.querySelectorAll("ellipse").forEach((e) => {
  3116. e.classList.add("bytm-mod-logo-ellipse");
  3117. });
  3118. (_a = logoElem.querySelector("path")) === null || _a === void 0 ? void 0 : _a.classList.add("bytm-mod-logo-path");
  3119. log("Swapped logo to inline SVG");
  3120. },
  3121. });
  3122. }
  3123. catch (err) {
  3124. error("Couldn't improve logo due to an error:", err);
  3125. }
  3126. }
  3127. /** Exchanges the default YTM logo into BetterYTM's logo with a sick ass animation */
  3128. function exchangeLogo() {
  3129. addSelectorListener("navBar", ".bytm-mod-logo", {
  3130. listener: async (logoElem) => {
  3131. if (logoElem.classList.contains("bytm-logo-exchanged"))
  3132. return;
  3133. logoExchanged = true;
  3134. logoElem.classList.add("bytm-logo-exchanged");
  3135. const iconUrl = await getResourceUrl(mode === "development" ? "img-logo_dev" : "img-logo");
  3136. const newLogo = document.createElement("img");
  3137. newLogo.classList.add("bytm-mod-logo-img");
  3138. newLogo.src = iconUrl;
  3139. logoElem.insertBefore(newLogo, logoElem.querySelector("svg"));
  3140. document.head.querySelectorAll("link[rel=\"icon\"]").forEach((e) => {
  3141. e.href = iconUrl;
  3142. });
  3143. setTimeout(() => {
  3144. logoElem.querySelectorAll(".bytm-mod-logo-ellipse").forEach(e => e.remove());
  3145. }, 1000);
  3146. },
  3147. });
  3148. }
  3149. /** Called whenever the avatar popover menu exists on YTM to add a BYTM config menu button to the user menu popover */
  3150. async function addConfigMenuOptionYTM(container) {
  3151. const cfgOptElem = document.createElement("div");
  3152. cfgOptElem.classList.add("bytm-cfg-menu-option");
  3153. const cfgOptItemElem = document.createElement("div");
  3154. cfgOptItemElem.classList.add("bytm-cfg-menu-option-item");
  3155. cfgOptItemElem.role = "button";
  3156. cfgOptItemElem.tabIndex = 0;
  3157. cfgOptItemElem.ariaLabel = cfgOptItemElem.title = t("open_menu_tooltip", scriptInfo.name);
  3158. onInteraction(cfgOptItemElem, async (e) => {
  3159. const settingsBtnElem = document.querySelector("ytmusic-nav-bar ytmusic-settings-button tp-yt-paper-icon-button");
  3160. settingsBtnElem === null || settingsBtnElem === void 0 ? void 0 : settingsBtnElem.click();
  3161. await UserUtils.pauseFor(20);
  3162. if ((!e.shiftKey && !e.ctrlKey) || logoExchanged)
  3163. openCfgMenu();
  3164. if (!logoExchanged && (e.shiftKey || e.ctrlKey))
  3165. exchangeLogo();
  3166. });
  3167. const cfgOptIconElem = document.createElement("img");
  3168. cfgOptIconElem.classList.add("bytm-cfg-menu-option-icon");
  3169. cfgOptIconElem.src = await getResourceUrl(mode === "development" ? "img-logo_dev" : "img-logo");
  3170. const cfgOptTextElem = document.createElement("div");
  3171. cfgOptTextElem.classList.add("bytm-cfg-menu-option-text");
  3172. cfgOptTextElem.textContent = t("config_menu_option", scriptInfo.name);
  3173. cfgOptItemElem.appendChild(cfgOptIconElem);
  3174. cfgOptItemElem.appendChild(cfgOptTextElem);
  3175. cfgOptElem.appendChild(cfgOptItemElem);
  3176. container.appendChild(cfgOptElem);
  3177. improveLogo();
  3178. log("Added BYTM-Configuration button to menu popover");
  3179. }
  3180. /** Called whenever the titlebar (masthead) exists on YT to add a BYTM config menu button */
  3181. async function addConfigMenuOptionYT(container) {
  3182. const cfgOptWrapperElem = document.createElement("div");
  3183. cfgOptWrapperElem.classList.add("bytm-yt-cfg-menu-option", "darkreader-ignore");
  3184. cfgOptWrapperElem.role = "button";
  3185. cfgOptWrapperElem.tabIndex = 0;
  3186. cfgOptWrapperElem.ariaLabel = cfgOptWrapperElem.title = t("open_menu_tooltip", scriptInfo.name);
  3187. const cfgOptElem = document.createElement("div");
  3188. cfgOptElem.classList.add("bytm-yt-cfg-menu-option-inner");
  3189. const cfgOptImgElem = document.createElement("img");
  3190. cfgOptImgElem.classList.add("bytm-yt-cfg-menu-option-icon");
  3191. cfgOptImgElem.src = await getResourceUrl(mode === "development" ? "img-logo_dev" : "img-logo");
  3192. const cfgOptItemElem = document.createElement("div");
  3193. cfgOptItemElem.classList.add("bytm-yt-cfg-menu-option-item");
  3194. cfgOptItemElem.textContent = scriptInfo.name;
  3195. cfgOptElem.appendChild(cfgOptImgElem);
  3196. cfgOptElem.appendChild(cfgOptItemElem);
  3197. cfgOptWrapperElem.appendChild(cfgOptElem);
  3198. onInteraction(cfgOptWrapperElem, openCfgMenu);
  3199. const firstChild = container === null || container === void 0 ? void 0 : container.firstElementChild;
  3200. if (firstChild)
  3201. container.insertBefore(cfgOptWrapperElem, firstChild);
  3202. else
  3203. return error("Couldn't add config menu option to YT titlebar - couldn't find container element");
  3204. }
  3205. //#region anchor impr.
  3206. /** Adds anchors around elements and tweaks existing ones so songs are easier to open in a new tab */
  3207. async function addAnchorImprovements() {
  3208. try {
  3209. await addStyleFromResource("css-anchor_improvements");
  3210. }
  3211. catch (err) {
  3212. error("Couldn't add anchor improvements CSS due to an error:", err);
  3213. }
  3214. //#region carousel shelves
  3215. try {
  3216. const preventDefault = (e) => e.preventDefault();
  3217. /** Adds anchor improvements to &lt;ytmusic-responsive-list-item-renderer&gt; */
  3218. const addListItemAnchors = (items) => {
  3219. var _a;
  3220. for (const item of items) {
  3221. if (item.classList.contains("bytm-anchor-improved"))
  3222. continue;
  3223. item.classList.add("bytm-anchor-improved");
  3224. const thumbnailElem = item.querySelector(".left-items");
  3225. const titleElem = item.querySelector(".title-column .title a");
  3226. if (!thumbnailElem || !titleElem)
  3227. continue;
  3228. const anchorElem = document.createElement("a");
  3229. anchorElem.classList.add("bytm-anchor", "bytm-carousel-shelf-anchor");
  3230. anchorElem.href = (_a = titleElem === null || titleElem === void 0 ? void 0 : titleElem.href) !== null && _a !== void 0 ? _a : "#";
  3231. anchorElem.target = "_self";
  3232. anchorElem.role = "button";
  3233. anchorElem.addEventListener("click", preventDefault);
  3234. UserUtils.addParent(thumbnailElem, anchorElem);
  3235. }
  3236. };
  3237. // home page
  3238. addSelectorListener("body", "#contents.ytmusic-section-list-renderer ytmusic-carousel-shelf-renderer ytmusic-responsive-list-item-renderer", {
  3239. continuous: true,
  3240. all: true,
  3241. listener: addListItemAnchors,
  3242. });
  3243. // related tab in /watch
  3244. addSelectorListener("body", "ytmusic-tab-renderer[page-type=\"MUSIC_PAGE_TYPE_TRACK_RELATED\"] ytmusic-responsive-list-item-renderer", {
  3245. continuous: true,
  3246. all: true,
  3247. listener: addListItemAnchors,
  3248. });
  3249. // playlists
  3250. addSelectorListener("body", "#contents.ytmusic-section-list-renderer ytmusic-playlist-shelf-renderer ytmusic-responsive-list-item-renderer", {
  3251. continuous: true,
  3252. all: true,
  3253. listener: addListItemAnchors,
  3254. });
  3255. // generic shelves
  3256. addSelectorListener("body", "#contents.ytmusic-section-list-renderer ytmusic-shelf-renderer ytmusic-responsive-list-item-renderer", {
  3257. continuous: true,
  3258. all: true,
  3259. listener: addListItemAnchors,
  3260. });
  3261. }
  3262. catch (err) {
  3263. error("Couldn't improve carousel shelf anchors due to an error:", err);
  3264. }
  3265. //#region sidebar
  3266. try {
  3267. const addSidebarAnchors = (sidebarCont) => {
  3268. const items = sidebarCont.parentNode.querySelectorAll("ytmusic-guide-entry-renderer tp-yt-paper-item");
  3269. improveSidebarAnchors(items);
  3270. return items.length;
  3271. };
  3272. addSelectorListener("sideBar", "#contentContainer #guide-content #items ytmusic-guide-entry-renderer", {
  3273. listener: (sidebarCont) => {
  3274. const itemsAmt = addSidebarAnchors(sidebarCont);
  3275. log(`Added anchors around ${itemsAmt} sidebar ${UserUtils.autoPlural("item", itemsAmt)}`);
  3276. },
  3277. });
  3278. addSelectorListener("sideBarMini", "ytmusic-guide-renderer ytmusic-guide-section-renderer #items ytmusic-guide-entry-renderer", {
  3279. listener: (miniSidebarCont) => {
  3280. const itemsAmt = addSidebarAnchors(miniSidebarCont);
  3281. log(`Added anchors around ${itemsAmt} mini sidebar ${UserUtils.autoPlural("item", itemsAmt)}`);
  3282. },
  3283. });
  3284. }
  3285. catch (err) {
  3286. error("Couldn't add anchors to sidebar items due to an error:", err);
  3287. }
  3288. }
  3289. const sidebarPaths = [
  3290. "/",
  3291. "/explore",
  3292. "/library",
  3293. ];
  3294. /**
  3295. * Adds anchors to the sidebar items so they can be opened in a new tab
  3296. * @param sidebarItem
  3297. */
  3298. function improveSidebarAnchors(sidebarItems) {
  3299. sidebarItems.forEach((item, i) => {
  3300. var _a;
  3301. const anchorElem = document.createElement("a");
  3302. anchorElem.classList.add("bytm-anchor", "bytm-no-select");
  3303. anchorElem.role = "button";
  3304. anchorElem.target = "_self";
  3305. anchorElem.href = (_a = sidebarPaths[i]) !== null && _a !== void 0 ? _a : "#";
  3306. anchorElem.ariaLabel = anchorElem.title = t("middle_click_open_tab");
  3307. anchorElem.addEventListener("click", (e) => {
  3308. e.preventDefault();
  3309. });
  3310. UserUtils.addParent(item, anchorElem);
  3311. });
  3312. }
  3313. //#region share track par.
  3314. /** Removes the ?si tracking parameter from share URLs */
  3315. async function initRemShareTrackParam() {
  3316. const removeSiParam = (inputElem) => {
  3317. try {
  3318. if (!inputElem.value.match(/(&|\?)si=/i))
  3319. return;
  3320. const url = new URL(inputElem.value);
  3321. url.searchParams.delete("si");
  3322. inputElem.value = String(url);
  3323. log(`Removed tracking parameter from share link -> ${url}`);
  3324. }
  3325. catch (err) {
  3326. warn("Couldn't remove tracking parameter from share link due to error:", err);
  3327. }
  3328. };
  3329. const [sharePanelSel, inputSel] = (() => {
  3330. switch (getDomain()) {
  3331. case "ytm": return ["tp-yt-paper-dialog ytmusic-unified-share-panel-renderer", "input#share-url"];
  3332. case "yt": return ["ytd-unified-share-panel-renderer", "input#share-url"];
  3333. }
  3334. })();
  3335. addSelectorListener("body", sharePanelSel, {
  3336. listener: (sharePanelEl) => {
  3337. const obs = new MutationObserver(() => {
  3338. const inputElem = sharePanelEl.querySelector(inputSel);
  3339. inputElem && removeSiParam(inputElem);
  3340. });
  3341. obs.observe(sharePanelEl, {
  3342. childList: true,
  3343. subtree: true,
  3344. characterData: true,
  3345. attributeFilter: ["aria-hidden", "aria-checked", "checked"],
  3346. });
  3347. },
  3348. });
  3349. }
  3350. //#region fix spacing
  3351. /** Applies global CSS to fix various spacings */
  3352. async function fixSpacing() {
  3353. if (!await addStyleFromResource("css-fix_spacing"))
  3354. error("Couldn't fix spacing");
  3355. }
  3356. //#region ab.queue btns
  3357. async function initAboveQueueBtns() {
  3358. const { scrollToActiveSongBtn, clearQueueBtn } = getFeatures();
  3359. if (!await addStyleFromResource("css-above_queue_btns"))
  3360. error("Couldn't add CSS for above queue buttons");
  3361. const contBtns = [
  3362. {
  3363. condition: scrollToActiveSongBtn,
  3364. id: "scroll-to-active",
  3365. resourceName: "icon-skip_to",
  3366. titleKey: "scroll_to_playing",
  3367. async interaction(evt) {
  3368. const activeItem = document.querySelector("#side-panel .ytmusic-player-queue ytmusic-player-queue-item[play-button-state=\"loading\"], #side-panel .ytmusic-player-queue ytmusic-player-queue-item[play-button-state=\"playing\"], #side-panel .ytmusic-player-queue ytmusic-player-queue-item[play-button-state=\"paused\"]");
  3369. if (!activeItem)
  3370. return;
  3371. activeItem.scrollIntoView({
  3372. behavior: evt.shiftKey ? "instant" : "smooth",
  3373. block: evt.ctrlKey || evt.altKey ? "start" : "center",
  3374. inline: "center",
  3375. });
  3376. },
  3377. },
  3378. {
  3379. condition: clearQueueBtn,
  3380. id: "clear-queue",
  3381. resourceName: "icon-clear_list",
  3382. titleKey: "clear_list",
  3383. async interaction(evt) {
  3384. try {
  3385. // TODO: better confirmation dialog?
  3386. if (evt.shiftKey || confirm(t("clear_list_confirm"))) {
  3387. const url = new URL(location.href);
  3388. url.searchParams.delete("list");
  3389. url.searchParams.set("time_continue", String(await getVideoTime(0)));
  3390. location.assign(url);
  3391. }
  3392. }
  3393. catch (err) {
  3394. error("Couldn't clear queue due to an error:", err);
  3395. }
  3396. },
  3397. },
  3398. ];
  3399. if (!contBtns.some(b => Boolean(b.condition)))
  3400. return;
  3401. addSelectorListener("sidePanel", "ytmusic-tab-renderer ytmusic-queue-header-renderer #buttons", {
  3402. async listener(rightBtnsEl) {
  3403. try {
  3404. const aboveQueueBtnCont = document.createElement("div");
  3405. aboveQueueBtnCont.id = "bytm-above-queue-btn-cont";
  3406. UserUtils.addParent(rightBtnsEl, aboveQueueBtnCont);
  3407. const headerEl = rightBtnsEl.closest("ytmusic-queue-header-renderer");
  3408. if (!headerEl)
  3409. return error("Couldn't find queue header element while adding above queue buttons");
  3410. siteEvents.on("fullscreenToggled", (isFullscreen) => {
  3411. headerEl.classList[isFullscreen ? "add" : "remove"]("hidden");
  3412. });
  3413. const wrapperElem = document.createElement("div");
  3414. wrapperElem.id = "bytm-above-queue-btn-wrapper";
  3415. for (const item of contBtns) {
  3416. if (Boolean(item.condition) === false)
  3417. continue;
  3418. const btnElem = await createCircularBtn({
  3419. resourceName: item.resourceName,
  3420. onClick: item.interaction,
  3421. title: t(item.titleKey),
  3422. });
  3423. btnElem.id = `bytm-${item.id}-btn`;
  3424. btnElem.classList.add("ytmusic-player-bar", "bytm-generic-btn", "bytm-above-queue-btn");
  3425. wrapperElem.appendChild(btnElem);
  3426. }
  3427. rightBtnsEl.insertAdjacentElement("beforebegin", wrapperElem);
  3428. }
  3429. catch (err) {
  3430. error("Couldn't add above queue buttons due to an error:", err);
  3431. }
  3432. },
  3433. });
  3434. }
  3435. //#region thumb.overlay
  3436. /** To be changed when the toggle button is pressed - used to invert the state of "showOverlay" */
  3437. let invertOverlay = false;
  3438. async function initThumbnailOverlay() {
  3439. const toggleBtnShown = getFeature("thumbnailOverlayToggleBtnShown");
  3440. if (getFeature("thumbnailOverlayBehavior") === "never" && !toggleBtnShown)
  3441. return;
  3442. // so the script init doesn't keep waiting until a /watch page is loaded
  3443. waitVideoElementReady().then(() => {
  3444. const playerSelector = "ytmusic-player#player";
  3445. const playerEl = document.querySelector(playerSelector);
  3446. if (!playerEl)
  3447. return error("Couldn't find video player element while adding thumbnail overlay");
  3448. /** Checks and updates the overlay and toggle button states based on the current song type (yt video or ytm song) */
  3449. const updateOverlayVisibility = async () => {
  3450. if (!domLoaded)
  3451. return;
  3452. const behavior = getFeature("thumbnailOverlayBehavior");
  3453. let showOverlay = behavior === "always";
  3454. const isVideo = getCurrentMediaType() === "video";
  3455. if (behavior === "videosOnly" && isVideo)
  3456. showOverlay = true;
  3457. else if (behavior === "songsOnly" && !isVideo)
  3458. showOverlay = true;
  3459. showOverlay = invertOverlay ? !showOverlay : showOverlay;
  3460. const overlayElem = document.querySelector("#bytm-thumbnail-overlay");
  3461. const thumbElem = document.querySelector("#bytm-thumbnail-overlay-img");
  3462. const indicatorElem = document.querySelector("#bytm-thumbnail-overlay-indicator");
  3463. if (overlayElem)
  3464. overlayElem.style.display = showOverlay ? "block" : "none";
  3465. if (thumbElem)
  3466. thumbElem.ariaHidden = String(!showOverlay);
  3467. if (indicatorElem) {
  3468. indicatorElem.style.display = showOverlay ? "block" : "none";
  3469. indicatorElem.ariaHidden = String(!showOverlay);
  3470. }
  3471. if (getFeature("thumbnailOverlayToggleBtnShown")) {
  3472. addSelectorListener("playerBarMiddleButtons", "#bytm-thumbnail-overlay-toggle", {
  3473. async listener(toggleBtnElem) {
  3474. const toggleBtnImgElem = toggleBtnElem.querySelector("img");
  3475. if (toggleBtnImgElem)
  3476. toggleBtnImgElem.src = await getResourceUrl(`icon-image${showOverlay ? "_filled" : ""}`);
  3477. if (toggleBtnElem)
  3478. toggleBtnElem.ariaLabel = toggleBtnElem.title = t(`thumbnail_overlay_toggle_btn_tooltip${showOverlay ? "_hide" : "_show"}`);
  3479. },
  3480. });
  3481. }
  3482. };
  3483. const applyThumbUrl = async (watchId) => {
  3484. try {
  3485. const thumbUrl = await getBestThumbnailUrl(watchId);
  3486. if (thumbUrl) {
  3487. const toggleBtnElem = document.querySelector("#bytm-thumbnail-overlay-toggle");
  3488. const thumbImgElem = document.querySelector("#bytm-thumbnail-overlay-img");
  3489. if (toggleBtnElem)
  3490. toggleBtnElem.href = thumbUrl;
  3491. if (thumbImgElem)
  3492. thumbImgElem.src = thumbUrl;
  3493. log("Applied thumbnail URL to overlay:", thumbUrl);
  3494. }
  3495. else
  3496. error("Couldn't get thumbnail URL for watch ID", watchId);
  3497. }
  3498. catch (err) {
  3499. error("Couldn't apply thumbnail URL to overlay due to an error:", err);
  3500. }
  3501. };
  3502. const unsubWatchIdChanged = siteEvents.on("watchIdChanged", (watchId) => {
  3503. unsubWatchIdChanged();
  3504. addSelectorListener("body", "#bytm-thumbnail-overlay", {
  3505. listener: () => {
  3506. applyThumbUrl(watchId);
  3507. updateOverlayVisibility();
  3508. },
  3509. });
  3510. });
  3511. const createElements = async () => {
  3512. try {
  3513. // overlay
  3514. const overlayElem = document.createElement("div");
  3515. overlayElem.id = "bytm-thumbnail-overlay";
  3516. overlayElem.title = ""; // prevent child titles from propagating
  3517. overlayElem.classList.add("bytm-no-select");
  3518. overlayElem.style.display = "none";
  3519. let indicatorElem;
  3520. if (getFeature("thumbnailOverlayShowIndicator")) {
  3521. indicatorElem = document.createElement("img");
  3522. indicatorElem.id = "bytm-thumbnail-overlay-indicator";
  3523. indicatorElem.src = await getResourceUrl("icon-image");
  3524. indicatorElem.role = "presentation";
  3525. indicatorElem.title = indicatorElem.ariaLabel = t("thumbnail_overlay_indicator_tooltip");
  3526. indicatorElem.ariaHidden = "true";
  3527. indicatorElem.style.display = "none";
  3528. indicatorElem.style.opacity = String(getFeature("thumbnailOverlayIndicatorOpacity") / 100);
  3529. }
  3530. const thumbImgElem = document.createElement("img");
  3531. thumbImgElem.id = "bytm-thumbnail-overlay-img";
  3532. thumbImgElem.role = "presentation";
  3533. thumbImgElem.ariaHidden = "true";
  3534. thumbImgElem.style.objectFit = getFeature("thumbnailOverlayImageFit");
  3535. overlayElem.appendChild(thumbImgElem);
  3536. playerEl.appendChild(overlayElem);
  3537. indicatorElem && playerEl.appendChild(indicatorElem);
  3538. siteEvents.on("watchIdChanged", async (watchId) => {
  3539. invertOverlay = false;
  3540. applyThumbUrl(watchId);
  3541. updateOverlayVisibility();
  3542. });
  3543. const params = new URL(location.href).searchParams;
  3544. if (params.has("v")) {
  3545. applyThumbUrl(params.get("v"));
  3546. updateOverlayVisibility();
  3547. }
  3548. // toggle button
  3549. if (toggleBtnShown) {
  3550. const toggleBtnElem = createRipple(document.createElement("a"));
  3551. toggleBtnElem.id = "bytm-thumbnail-overlay-toggle";
  3552. toggleBtnElem.role = "button";
  3553. toggleBtnElem.tabIndex = 0;
  3554. toggleBtnElem.classList.add("ytmusic-player-bar", "bytm-generic-btn", "bytm-no-select");
  3555. onInteraction(toggleBtnElem, (e) => {
  3556. if (e.shiftKey)
  3557. return openInTab(toggleBtnElem.href, false);
  3558. invertOverlay = !invertOverlay;
  3559. updateOverlayVisibility();
  3560. });
  3561. const imgElem = document.createElement("img");
  3562. imgElem.classList.add("bytm-generic-btn-img");
  3563. toggleBtnElem.appendChild(imgElem);
  3564. addSelectorListener("playerBarMiddleButtons", "ytmusic-like-button-renderer#like-button-renderer", {
  3565. listener: (likeContainer) => likeContainer.insertAdjacentElement("afterend", toggleBtnElem),
  3566. });
  3567. }
  3568. log("Added thumbnail overlay");
  3569. }
  3570. catch (err) {
  3571. error("Couldn't create thumbnail overlay elements due to an error:", err);
  3572. }
  3573. };
  3574. addSelectorListener("mainPanel", playerSelector, {
  3575. listener(playerEl) {
  3576. if (playerEl.getAttribute("player-ui-state") === "INACTIVE") {
  3577. const obs = new MutationObserver(() => {
  3578. if (playerEl.getAttribute("player-ui-state") === "INACTIVE")
  3579. return;
  3580. createElements();
  3581. obs.disconnect();
  3582. });
  3583. obs.observe(playerEl, {
  3584. attributes: true,
  3585. attributeFilter: ["player-ui-state"],
  3586. });
  3587. }
  3588. else
  3589. createElements();
  3590. },
  3591. });
  3592. });
  3593. }
  3594. //#region idle hide cursor
  3595. async function initHideCursorOnIdle() {
  3596. addSelectorListener("mainPanel", "ytmusic-player#player", {
  3597. listener(vidContainer) {
  3598. const overlaySelector = "ytmusic-player #song-media-window";
  3599. const overlayElem = document.querySelector(overlaySelector);
  3600. if (!overlayElem)
  3601. return warn("Couldn't find overlay element while initializing cursor hiding");
  3602. /** Timer after which the cursor is hidden */
  3603. let cursorHideTimer;
  3604. /** Timer for the opacity transition while switching to the hidden state */
  3605. let hideTransTimer;
  3606. const hide = () => {
  3607. if (!getFeature("hideCursorOnIdle"))
  3608. return;
  3609. if (vidContainer.classList.contains("bytm-cursor-hidden"))
  3610. return;
  3611. overlayElem.style.opacity = ".000001 !important";
  3612. hideTransTimer = setTimeout(() => {
  3613. overlayElem.style.display = "none";
  3614. vidContainer.style.cursor = "none";
  3615. vidContainer.classList.add("bytm-cursor-hidden");
  3616. hideTransTimer = undefined;
  3617. }, 200);
  3618. };
  3619. const show = () => {
  3620. hideTransTimer && clearTimeout(hideTransTimer);
  3621. if (!vidContainer.classList.contains("bytm-cursor-hidden"))
  3622. return;
  3623. vidContainer.classList.remove("bytm-cursor-hidden");
  3624. vidContainer.style.cursor = "initial";
  3625. overlayElem.style.display = "initial";
  3626. overlayElem.style.opacity = "1 !important";
  3627. };
  3628. const cursorHideTimerCb = () => cursorHideTimer = setTimeout(hide, getFeature("hideCursorOnIdleDelay") * 1000);
  3629. const onMove = () => {
  3630. cursorHideTimer && clearTimeout(cursorHideTimer);
  3631. show();
  3632. cursorHideTimerCb();
  3633. };
  3634. vidContainer.addEventListener("mouseenter", onMove);
  3635. vidContainer.addEventListener("mousemove", UserUtils.debounce(onMove, 200, "rising"));
  3636. vidContainer.addEventListener("mouseleave", () => {
  3637. cursorHideTimer && clearTimeout(cursorHideTimer);
  3638. hideTransTimer && clearTimeout(hideTransTimer);
  3639. hide();
  3640. });
  3641. vidContainer.addEventListener("click", () => {
  3642. show();
  3643. cursorHideTimerCb();
  3644. setTimeout(hide, 3000);
  3645. });
  3646. log("Initialized cursor hiding on idle");
  3647. },
  3648. });
  3649. }
  3650. //#region fix HDR
  3651. /** Prevents visual issues when using HDR */
  3652. async function fixHdrIssues() {
  3653. if (!await addStyleFromResource("css-fix_hdr"))
  3654. error("Couldn't load stylesheet to fix HDR issues");
  3655. else
  3656. log("Fixed HDR issues");
  3657. }
  3658. //#region show vote nums
  3659. /** Shows the amount of likes and dislikes on the current song */
  3660. async function initShowVotes() {
  3661. addSelectorListener("playerBar", ".middle-controls-buttons ytmusic-like-button-renderer", {
  3662. async listener(voteCont) {
  3663. try {
  3664. const watchId = getWatchId();
  3665. if (!watchId) {
  3666. await siteEvents.once("watchIdChanged");
  3667. return initShowVotes();
  3668. }
  3669. const voteObj = await fetchVideoVotes(watchId);
  3670. if (!voteObj || !("likes" in voteObj) || !("dislikes" in voteObj) || !("rating" in voteObj))
  3671. return error("Couldn't fetch votes from the Return YouTube Dislike API");
  3672. if (getFeature("showVotes")) {
  3673. addVoteNumbers(voteCont, voteObj);
  3674. siteEvents.on("watchIdChanged", async (watchId) => {
  3675. var _a, _b;
  3676. const labelLikes = document.querySelector("ytmusic-like-button-renderer .bytm-vote-label.likes");
  3677. const labelDislikes = document.querySelector("ytmusic-like-button-renderer .bytm-vote-label.dislikes");
  3678. if (!labelLikes || !labelDislikes)
  3679. return error("Couldn't find vote label elements while updating like and dislike counts");
  3680. if (labelLikes.dataset.watchId === watchId && labelDislikes.dataset.watchId === watchId)
  3681. return log("Vote labels already updated for this video");
  3682. const voteObj = await fetchVideoVotes(watchId);
  3683. if (!voteObj || !("likes" in voteObj) || !("dislikes" in voteObj) || !("rating" in voteObj))
  3684. return error("Couldn't fetch votes from the Return YouTube Dislike API");
  3685. const likesLabelText = tp("vote_label_likes", voteObj.likes, formatVoteNumber(voteObj.likes, "long"));
  3686. const dislikesLabelText = tp("vote_label_dislikes", voteObj.dislikes, formatVoteNumber(voteObj.dislikes, "long"));
  3687. labelLikes.dataset.watchId = (_a = getWatchId()) !== null && _a !== void 0 ? _a : "";
  3688. labelLikes.textContent = formatVoteNumber(voteObj.likes);
  3689. labelLikes.title = labelLikes.ariaLabel = likesLabelText;
  3690. labelDislikes.textContent = formatVoteNumber(voteObj.dislikes);
  3691. labelDislikes.title = labelDislikes.ariaLabel = dislikesLabelText;
  3692. labelDislikes.dataset.watchId = (_b = getWatchId()) !== null && _b !== void 0 ? _b : "";
  3693. addSelectorListener("playerBar", "ytmusic-like-button-renderer#like-button-renderer", {
  3694. listener: (bar) => upsertVoteBtnLabels(bar, likesLabelText, dislikesLabelText),
  3695. });
  3696. });
  3697. }
  3698. }
  3699. catch (err) {
  3700. error("Couldn't initialize show votes feature due to an error:", err);
  3701. }
  3702. }
  3703. });
  3704. }
  3705. function addVoteNumbers(voteCont, voteObj) {
  3706. const likeBtn = voteCont.querySelector("#button-shape-like");
  3707. const dislikeBtn = voteCont.querySelector("#button-shape-dislike");
  3708. if (!likeBtn || !dislikeBtn)
  3709. return error("Couldn't find like or dislike button while adding vote numbers");
  3710. const createLabel = (amount, type) => {
  3711. var _a;
  3712. const label = document.createElement("span");
  3713. label.classList.add("bytm-vote-label", "bytm-no-select", type);
  3714. label.textContent = String(formatVoteNumber(amount));
  3715. label.title = label.ariaLabel = tp(`vote_label_${type}`, amount, formatVoteNumber(amount, "long"));
  3716. label.dataset.watchId = (_a = getWatchId()) !== null && _a !== void 0 ? _a : "";
  3717. label.addEventListener("click", (e) => {
  3718. var _a;
  3719. e.preventDefault();
  3720. e.stopPropagation();
  3721. (_a = (type === "likes" ? likeBtn : dislikeBtn).querySelector("button")) === null || _a === void 0 ? void 0 : _a.click();
  3722. });
  3723. return label;
  3724. };
  3725. addStyleFromResource("css-show_votes")
  3726. .catch((e) => error("Couldn't add CSS for show votes feature due to an error:", e));
  3727. const likeLblEl = createLabel(voteObj.likes, "likes");
  3728. likeBtn.insertAdjacentElement("afterend", likeLblEl);
  3729. const dislikeLblEl = createLabel(voteObj.dislikes, "dislikes");
  3730. dislikeBtn.insertAdjacentElement("afterend", dislikeLblEl);
  3731. upsertVoteBtnLabels(voteCont, likeLblEl.title, dislikeLblEl.title);
  3732. log("Added vote number labels to like and dislike buttons");
  3733. }
  3734. /** Formats a number formatted based on the config or the passed {@linkcode notation} */
  3735. function formatVoteNumber(num, notation) {
  3736. return num.toLocaleString(getLocale().replace(/_/g, "-"), (notation !== null && notation !== void 0 ? notation : getFeature("showVotesFormat")) === "short"
  3737. ? {
  3738. notation: "compact",
  3739. compactDisplay: "short",
  3740. maximumFractionDigits: 1,
  3741. }
  3742. : {
  3743. style: "decimal",
  3744. maximumFractionDigits: 0,
  3745. });
  3746. }
  3747. /** Updates or inserts the labels on the native like and dislike buttons */
  3748. function upsertVoteBtnLabels(parentEl, likesLabelText, dislikesLabelText) {
  3749. const likeBtn = parentEl.querySelector("#button-shape-like button");
  3750. const dislikeBtn = parentEl.querySelector("#button-shape-dislike button");
  3751. if (likeBtn)
  3752. likeBtn.title = likeBtn.ariaLabel = likesLabelText;
  3753. if (dislikeBtn)
  3754. dislikeBtn.title = dislikeBtn.ariaLabel = dislikesLabelText;
  3755. }//#region beforeunload popup
  3756. let beforeUnloadEnabled = true;
  3757. /** Disables the popup before leaving the site */
  3758. function disableBeforeUnload() {
  3759. beforeUnloadEnabled = false;
  3760. info("Disabled popup before leaving the site");
  3761. }
  3762. /** Adds a spy function into `window.__proto__.addEventListener` to selectively discard `beforeunload` event listeners before they can be called by the site */
  3763. async function initBeforeUnloadHook() {
  3764. UserUtils.interceptWindowEvent("beforeunload", () => !beforeUnloadEnabled);
  3765. }
  3766. //#region auto close toasts
  3767. /** Closes toasts after a set amount of time */
  3768. async function initAutoCloseToasts() {
  3769. const animTimeout = 300;
  3770. addSelectorListener("popupContainer", "ytmusic-notification-action-renderer", {
  3771. all: true,
  3772. continuous: true,
  3773. listener: async (toastContElems) => {
  3774. try {
  3775. for (const toastContElem of toastContElems) {
  3776. const toastElem = toastContElem.querySelector("tp-yt-paper-toast#toast");
  3777. if (!toastElem || !toastElem.hasAttribute("allow-click-through"))
  3778. continue;
  3779. if (toastElem.classList.contains("bytm-closing"))
  3780. continue;
  3781. toastElem.classList.add("bytm-closing");
  3782. const closeTimeout = Math.max(getFeature("closeToastsTimeout") * 1000 + animTimeout, animTimeout);
  3783. await UserUtils.pauseFor(closeTimeout);
  3784. toastElem.classList.remove("paper-toast-open");
  3785. toastElem.addEventListener("transitionend", () => {
  3786. toastElem.classList.remove("bytm-closing");
  3787. toastElem.style.display = "none";
  3788. clearNode(toastElem);
  3789. log(`Automatically closed toast after ${getFeature("closeToastsTimeout") * 1000}ms`);
  3790. }, { once: true });
  3791. }
  3792. }
  3793. catch (err) {
  3794. error("Error in automatic toast closing:", err);
  3795. }
  3796. },
  3797. });
  3798. log("Initialized automatic toast closing");
  3799. }
  3800. let remVidsCache = [];
  3801. /**
  3802. * Remembers the time of the last played video and resumes playback from that time.
  3803. * **Needs to be called *before* DOM is ready!**
  3804. */
  3805. async function initRememberSongTime() {
  3806. if (getFeature("rememberSongTimeSites") !== "all" && getFeature("rememberSongTimeSites") !== getDomain())
  3807. return;
  3808. const storedDataRaw = await GM.getValue("bytm-rem-songs");
  3809. if (!storedDataRaw)
  3810. await GM.setValue("bytm-rem-songs", "[]");
  3811. try {
  3812. remVidsCache = JSON.parse(String(storedDataRaw !== null && storedDataRaw !== void 0 ? storedDataRaw : "[]"));
  3813. }
  3814. catch (err) {
  3815. error("Error parsing stored video time data, defaulting to empty cache:", err);
  3816. await GM.setValue("bytm-rem-songs", "[]");
  3817. remVidsCache = [];
  3818. }
  3819. log(`Initialized video time restoring with ${remVidsCache.length} initial entr${remVidsCache.length === 1 ? "y" : "ies"}`);
  3820. await remTimeRestoreTime();
  3821. try {
  3822. if (!domLoaded)
  3823. document.addEventListener("DOMContentLoaded", remTimeStartUpdateLoop);
  3824. else
  3825. remTimeStartUpdateLoop();
  3826. }
  3827. catch (err) {
  3828. error("Error in video time remembering update loop:", err);
  3829. }
  3830. }
  3831. /** Tries to restore the time of the currently playing video */
  3832. async function remTimeRestoreTime() {
  3833. if (location.pathname.startsWith("/watch")) {
  3834. const watchID = new URL(location.href).searchParams.get("v");
  3835. if (!watchID)
  3836. return;
  3837. if (initialParams.has("t"))
  3838. return info("Not restoring song time because the URL has the '&t' parameter", LogLevel.Info);
  3839. const entry = remVidsCache.find(entry => entry.watchID === watchID);
  3840. if (entry) {
  3841. if (Date.now() - entry.updateTimestamp > getFeature("rememberSongTimeDuration") * 1000) {
  3842. await remTimeDeleteEntry(entry.watchID);
  3843. return;
  3844. }
  3845. else if (isNaN(Number(entry.songTime)))
  3846. return;
  3847. else {
  3848. let vidElem;
  3849. const doRestoreTime = async () => {
  3850. var _a;
  3851. if (!vidElem)
  3852. vidElem = await waitVideoElementReady();
  3853. const vidRestoreTime = entry.songTime - ((_a = getFeature("rememberSongTimeReduction")) !== null && _a !== void 0 ? _a : 0);
  3854. vidElem.currentTime = UserUtils.clamp(Math.max(vidRestoreTime, 0), 0, vidElem.duration);
  3855. await remTimeDeleteEntry(entry.watchID);
  3856. info(`Restored ${getCurrentMediaType()} time to ${Math.floor(vidRestoreTime / 60)}m, ${(vidRestoreTime % 60).toFixed(1)}s`, LogLevel.Info);
  3857. };
  3858. if (!domLoaded)
  3859. document.addEventListener("DOMContentLoaded", doRestoreTime);
  3860. else
  3861. doRestoreTime();
  3862. }
  3863. }
  3864. }
  3865. }
  3866. let lastSongTime = -1;
  3867. let remVidCheckTimeout;
  3868. /** Only call once as this calls itself after a timeout! - Updates the currently playing video's entry in GM storage */
  3869. async function remTimeStartUpdateLoop() {
  3870. var _a, _b, _c;
  3871. if (location.pathname.startsWith("/watch")) {
  3872. const watchID = getWatchId();
  3873. const songTime = (_a = await getVideoTime()) !== null && _a !== void 0 ? _a : 0;
  3874. if (watchID && songTime !== lastSongTime) {
  3875. lastSongTime = songTime;
  3876. const paused = (_c = (_b = getVideoElement()) === null || _b === void 0 ? void 0 : _b.paused) !== null && _c !== void 0 ? _c : false;
  3877. // don't immediately update to reduce race conditions and only update if the video is playing
  3878. // also it just sounds better if the song starts at the beginning if only a couple seconds have passed
  3879. if (songTime > getFeature("rememberSongTimeMinPlayTime") && !paused) {
  3880. const entry = {
  3881. watchID,
  3882. songTime,
  3883. updateTimestamp: Date.now(),
  3884. };
  3885. await remTimeUpsertEntry(entry);
  3886. }
  3887. // if the song is rewound to the beginning, update the entry accordingly
  3888. else if (!paused) {
  3889. const entry = remVidsCache.find(entry => entry.watchID === watchID);
  3890. if (entry && songTime <= entry.songTime)
  3891. await remTimeUpsertEntry(Object.assign(Object.assign({}, entry), { songTime, updateTimestamp: Date.now() }));
  3892. }
  3893. }
  3894. }
  3895. const expiredEntries = remVidsCache.filter(entry => Date.now() - entry.updateTimestamp > getFeature("rememberSongTimeDuration") * 1000);
  3896. for (const entry of expiredEntries)
  3897. await remTimeDeleteEntry(entry.watchID);
  3898. // for no overlapping calls and better error handling:
  3899. if (remVidCheckTimeout)
  3900. clearTimeout(remVidCheckTimeout);
  3901. remVidCheckTimeout = setTimeout(remTimeStartUpdateLoop, 1000);
  3902. }
  3903. /** Updates an existing or inserts a new entry to be remembered */
  3904. async function remTimeUpsertEntry(data) {
  3905. const foundIdx = remVidsCache.findIndex(entry => entry.watchID === data.watchID);
  3906. if (foundIdx >= 0)
  3907. remVidsCache[foundIdx] = data;
  3908. else
  3909. remVidsCache.push(data);
  3910. await GM.setValue("bytm-rem-songs", JSON.stringify(remVidsCache));
  3911. }
  3912. /** Deletes an entry in the "remember cache" */
  3913. async function remTimeDeleteEntry(watchID) {
  3914. remVidsCache = [...remVidsCache.filter(entry => entry.watchID !== watchID)];
  3915. await GM.setValue("bytm-rem-songs", JSON.stringify(remVidsCache));
  3916. }const inputIgnoreTagNames = ["INPUT", "TEXTAREA", "SELECT", "BUTTON", "A"];
  3917. //#region arrow key skip
  3918. async function initArrowKeySkip() {
  3919. document.addEventListener("keydown", (evt) => {
  3920. var _a, _b, _c, _d, _e, _f;
  3921. if (!getFeature("arrowKeySupport"))
  3922. return;
  3923. if (!["ArrowLeft", "ArrowRight"].includes(evt.code))
  3924. return;
  3925. const allowedClasses = ["bytm-generic-btn", "yt-spec-button-shape-next"];
  3926. // discard the event when a (text) input is currently active, like when editing a playlist
  3927. if ((inputIgnoreTagNames.includes((_b = (_a = document.activeElement) === null || _a === void 0 ? void 0 : _a.tagName) !== null && _b !== void 0 ? _b : "") || ["volume-slider"].includes((_d = (_c = document.activeElement) === null || _c === void 0 ? void 0 : _c.id) !== null && _d !== void 0 ? _d : ""))
  3928. && !allowedClasses.some((cls) => { var _a; return (_a = document.activeElement) === null || _a === void 0 ? void 0 : _a.classList.contains(cls); }))
  3929. return info(`Captured valid key to skip forward or backward but the current active element is <${(_e = document.activeElement) === null || _e === void 0 ? void 0 : _e.tagName.toLowerCase()}>, so the keypress is ignored`);
  3930. evt.preventDefault();
  3931. evt.stopImmediatePropagation();
  3932. let skipBy = (_f = getFeature("arrowKeySkipBy")) !== null && _f !== void 0 ? _f : featInfo.arrowKeySkipBy.default;
  3933. if (evt.code === "ArrowLeft")
  3934. skipBy *= -1;
  3935. log(`Captured arrow key '${evt.code}' - skipping by ${skipBy} seconds`);
  3936. const vidElem = getVideoElement();
  3937. if (vidElem)
  3938. vidElem.currentTime = UserUtils.clamp(vidElem.currentTime + skipBy, 0, vidElem.duration);
  3939. });
  3940. log("Added arrow key press listener");
  3941. }
  3942. //#region site switch
  3943. /** switch sites only if current video time is greater than this value */
  3944. const videoTimeThreshold = 3;
  3945. let siteSwitchEnabled = true;
  3946. /** Initializes the site switch feature */
  3947. async function initSiteSwitch(domain) {
  3948. document.addEventListener("keydown", (e) => {
  3949. var _a, _b;
  3950. if (!getFeature("switchBetweenSites"))
  3951. return;
  3952. if (inputIgnoreTagNames.includes((_b = (_a = document.activeElement) === null || _a === void 0 ? void 0 : _a.tagName) !== null && _b !== void 0 ? _b : ""))
  3953. return;
  3954. const hk = getFeature("switchSitesHotkey");
  3955. if (siteSwitchEnabled && e.code === hk.code && e.shiftKey === hk.shift && e.ctrlKey === hk.ctrl && e.altKey === hk.alt)
  3956. switchSite(domain === "yt" ? "ytm" : "yt");
  3957. });
  3958. siteEvents.on("hotkeyInputActive", (state) => {
  3959. if (!getFeature("switchBetweenSites"))
  3960. return;
  3961. siteSwitchEnabled = !state;
  3962. });
  3963. log("Initialized site switch listener");
  3964. }
  3965. /** Switches to the other site (between YT and YTM) */
  3966. async function switchSite(newDomain) {
  3967. try {
  3968. if (!(["/watch", "/playlist"].some(v => location.pathname.startsWith(v))))
  3969. return warn("Not on a supported page, so the site switch is ignored");
  3970. let subdomain;
  3971. if (newDomain === "ytm")
  3972. subdomain = "music";
  3973. else if (newDomain === "yt")
  3974. subdomain = "www";
  3975. if (!subdomain)
  3976. throw new Error(`Unrecognized domain '${newDomain}'`);
  3977. disableBeforeUnload();
  3978. const { pathname, search, hash } = new URL(location.href);
  3979. const vt = await getVideoTime(0);
  3980. log(`Found video time of ${vt} seconds`);
  3981. const cleanSearch = search.split("&")
  3982. .filter((param) => !param.match(/^\??(t|time_continue)=/))
  3983. .join("&");
  3984. const newSearch = typeof vt === "number" && vt > videoTimeThreshold ?
  3985. cleanSearch.includes("?")
  3986. ? `${cleanSearch.startsWith("?")
  3987. ? cleanSearch
  3988. : "?" + cleanSearch}&time_continue=${vt}`
  3989. : `?time_continue=${vt}`
  3990. : cleanSearch;
  3991. const newUrl = `https://${subdomain}.youtube.com${pathname}${newSearch}${hash}`;
  3992. info(`Switching to domain '${newDomain}' at ${newUrl}`);
  3993. location.assign(newUrl);
  3994. }
  3995. catch (err) {
  3996. error("Error while switching site:", err);
  3997. }
  3998. }
  3999. //#region num keys skip
  4000. const numKeysIgnoreTagNames = [...inputIgnoreTagNames];
  4001. /** Adds the ability to skip to a certain time in the video by pressing a number key (0-9) */
  4002. async function initNumKeysSkip() {
  4003. document.addEventListener("keydown", (e) => {
  4004. var _a, _b;
  4005. if (!getFeature("numKeysSkipToTime"))
  4006. return;
  4007. if (!e.key.trim().match(/^[0-9]$/))
  4008. return;
  4009. // discard the event when an unexpected element is currently active or in focus, like when editing a playlist or when the search bar is focused
  4010. const ignoreElement = numKeysIgnoreTagNames.includes((_b = (_a = document.activeElement) === null || _a === void 0 ? void 0 : _a.tagName) !== null && _b !== void 0 ? _b : "");
  4011. if ((document.activeElement !== document.body && ignoreElement) || ignoreElement)
  4012. return info("Captured valid key to skip video to, but ignored it since this element is currently active:", document.activeElement);
  4013. const vidElem = getVideoElement();
  4014. if (!vidElem)
  4015. return warn("Could not find video element, so the keypress is ignored");
  4016. const newVidTime = vidElem.duration / (10 / Number(e.key));
  4017. if (!isNaN(newVidTime)) {
  4018. log(`Captured number key [${e.key}], skipping to ${Math.floor(newVidTime / 60)}m ${(newVidTime % 60).toFixed(1)}s`);
  4019. vidElem.currentTime = newVidTime;
  4020. }
  4021. });
  4022. log("Added number key press listener");
  4023. }
  4024. //#region auto-like vids
  4025. let canCompress$1 = false;
  4026. /** DataStore instance for all auto-liked channels */
  4027. const autoLikeStore = new UserUtils.DataStore({
  4028. id: "bytm-auto-like-channels",
  4029. formatVersion: 2,
  4030. defaultData: {
  4031. channels: [],
  4032. },
  4033. encodeData: (data) => canCompress$1 ? UserUtils.compress(data, compressionFormat, "string") : data,
  4034. decodeData: (data) => canCompress$1 ? UserUtils.decompress(data, compressionFormat, "string") : data,
  4035. migrations: {
  4036. // 1 -> 2 (v2.1-pre) - add @ prefix to channel IDs if missing
  4037. 2: (oldData) => ({
  4038. channels: oldData.channels.map((ch) => (Object.assign(Object.assign({}, ch), { id: isValidChannelId(ch.id.trim())
  4039. ? ch.id.trim()
  4040. : `@${ch.id.trim()}` }))),
  4041. }),
  4042. },
  4043. });
  4044. let autoLikeStoreLoaded = false;
  4045. /** Inits the auto-like DataStore instance */
  4046. function initAutoLikeStore() {
  4047. if (autoLikeStoreLoaded)
  4048. return;
  4049. autoLikeStoreLoaded = true;
  4050. return autoLikeStore.loadData();
  4051. }
  4052. /** Initializes the auto-like feature */
  4053. async function initAutoLike() {
  4054. try {
  4055. canCompress$1 = await compressionSupported();
  4056. await initAutoLikeStore();
  4057. //#SECTION ytm
  4058. if (getDomain() === "ytm") {
  4059. let timeout;
  4060. siteEvents.on("songTitleChanged", () => {
  4061. var _a;
  4062. const autoLikeTimeoutMs = ((_a = getFeature("autoLikeTimeout")) !== null && _a !== void 0 ? _a : 5) * 1000;
  4063. timeout && clearTimeout(timeout);
  4064. const ytmTryAutoLike = () => {
  4065. const artistEls = document.querySelectorAll("ytmusic-player-bar .content-info-wrapper .subtitle a.yt-formatted-string[href]");
  4066. const channelIds = [...artistEls].map(a => a.href.split("/").pop()).filter(a => typeof a === "string");
  4067. const likeChan = autoLikeStore.getData().channels.find((ch) => channelIds.includes(ch.id));
  4068. if (!likeChan || !likeChan.enabled)
  4069. return;
  4070. if (artistEls.length === 0)
  4071. return error("Couldn't auto-like channel because the artist element couldn't be found");
  4072. const likeRendererEl = document.querySelector(".middle-controls-buttons ytmusic-like-button-renderer");
  4073. const likeBtnEl = likeRendererEl === null || likeRendererEl === void 0 ? void 0 : likeRendererEl.querySelector("#button-shape-like button");
  4074. if (!likeRendererEl || !likeBtnEl)
  4075. return error("Couldn't auto-like channel because the like button couldn't be found");
  4076. if (likeRendererEl.getAttribute("like-status") !== "LIKE") {
  4077. likeBtnEl.click();
  4078. getFeature("autoLikeShowToast") && showIconToast({
  4079. message: t(`auto_liked_a_channels_${getCurrentMediaType()}`, likeChan.name),
  4080. icon: "icon-auto_like",
  4081. onClick: () => getAutoLikeDialog().then((dlg) => dlg.open()),
  4082. });
  4083. log(`Auto-liked ${getCurrentMediaType()} from channel '${likeChan.name}' (${likeChan.id})`);
  4084. }
  4085. };
  4086. timeout = setTimeout(ytmTryAutoLike, autoLikeTimeoutMs);
  4087. siteEvents.on("autoLikeChannelsUpdated", () => setTimeout(ytmTryAutoLike, autoLikeTimeoutMs));
  4088. });
  4089. siteEvents.on("pathChanged", (path) => {
  4090. if (getFeature("autoLikeChannelToggleBtn") && path.match(/\/channel\/.+/)) {
  4091. const chanId = getCurrentChannelId();
  4092. if (!chanId)
  4093. return error("Couldn't extract channel ID from URL");
  4094. document.querySelectorAll(".bytm-auto-like-toggle-btn").forEach((btn) => clearNode(btn));
  4095. addSelectorListener("browseResponse", "ytmusic-browse-response #header.ytmusic-browse-response", {
  4096. listener(headerCont) {
  4097. var _a, _b, _c, _d;
  4098. const buttonsCont = headerCont.querySelector(".buttons");
  4099. if (buttonsCont) {
  4100. const lastBtn = buttonsCont.querySelector("ytmusic-subscribe-button-renderer");
  4101. const chanName = (_b = (_a = document.querySelector("ytmusic-immersive-header-renderer .content-container yt-formatted-string[role=\"heading\"]")) === null || _a === void 0 ? void 0 : _a.textContent) !== null && _b !== void 0 ? _b : null;
  4102. lastBtn && addAutoLikeToggleBtn(lastBtn, chanId, chanName);
  4103. }
  4104. else {
  4105. // some channels don't have a subscribe button and instead only have a "share" button for some bullshit reason
  4106. const shareBtnEl = headerCont.querySelector("ytmusic-menu-renderer #top-level-buttons yt-button-renderer:last-of-type");
  4107. const chanName = (_d = (_c = headerCont.querySelector("ytmusic-visual-header-renderer .content-container h2 yt-formatted-string")) === null || _c === void 0 ? void 0 : _c.textContent) !== null && _d !== void 0 ? _d : null;
  4108. shareBtnEl && chanName && addAutoLikeToggleBtn(shareBtnEl, chanId, chanName);
  4109. }
  4110. }
  4111. });
  4112. }
  4113. });
  4114. }
  4115. //#SECTION yt
  4116. else if (getDomain() === "yt") {
  4117. addStyleFromResource("css-auto_like");
  4118. let timeout;
  4119. siteEvents.on("watchIdChanged", () => {
  4120. var _a;
  4121. const autoLikeTimeoutMs = ((_a = getFeature("autoLikeTimeout")) !== null && _a !== void 0 ? _a : 5) * 1000;
  4122. timeout && clearTimeout(timeout);
  4123. if (!location.pathname.startsWith("/watch"))
  4124. return;
  4125. const ytTryAutoLike = () => {
  4126. addSelectorListener("ytWatchMetadata", "#owner ytd-channel-name yt-formatted-string a", {
  4127. listener(chanElem) {
  4128. var _a, _b;
  4129. const chanElemId = (_b = (_a = chanElem.href.split("/").pop()) === null || _a === void 0 ? void 0 : _a.split("/")[0]) !== null && _b !== void 0 ? _b : null;
  4130. const likeChan = autoLikeStore.getData().channels.find((ch) => ch.id === chanElemId);
  4131. if (!likeChan || !likeChan.enabled)
  4132. return;
  4133. addSelectorListener("ytWatchMetadata", "#actions ytd-menu-renderer like-button-view-model button", {
  4134. listener(likeBtn) {
  4135. if (likeBtn.getAttribute("aria-pressed") !== "true") {
  4136. likeBtn.click();
  4137. getFeature("autoLikeShowToast") && showIconToast({
  4138. message: t("auto_liked_a_channels_video", likeChan.name),
  4139. icon: "icon-auto_like",
  4140. onClick: () => getAutoLikeDialog().then((dlg) => dlg.open()),
  4141. });
  4142. log(`Auto-liked video from channel '${likeChan.name}' (${likeChan.id})`);
  4143. }
  4144. }
  4145. });
  4146. }
  4147. });
  4148. };
  4149. siteEvents.on("autoLikeChannelsUpdated", () => setTimeout(ytTryAutoLike, autoLikeTimeoutMs));
  4150. timeout = setTimeout(ytTryAutoLike, autoLikeTimeoutMs);
  4151. });
  4152. siteEvents.on("pathChanged", (path) => {
  4153. if (path.match(/(\/?@|\/?channel\/)\S+/)) {
  4154. const chanId = getCurrentChannelId();
  4155. if (!chanId)
  4156. return error("Couldn't extract channel ID from URL");
  4157. document.querySelectorAll(".bytm-auto-like-toggle-btn").forEach((btn) => clearNode(btn));
  4158. addSelectorListener("ytAppHeader", "#channel-header-container, #page-header", {
  4159. listener(headerCont) {
  4160. var _a, _b;
  4161. const titleCont = headerCont.querySelector("ytd-channel-name #container, yt-dynamic-text-view-model.page-header-view-model-wiz__page-header-title");
  4162. if (!titleCont)
  4163. return;
  4164. const chanName = (_b = (_a = titleCont.querySelector("yt-formatted-string, span.yt-core-attributed-string")) === null || _a === void 0 ? void 0 : _a.textContent) !== null && _b !== void 0 ? _b : null;
  4165. const buttonsCont = headerCont.querySelector("#inner-header-container #buttons, yt-flexible-actions-view-model");
  4166. if (buttonsCont) {
  4167. addSelectorListener("ytAppHeader", "#channel-header-container #other-buttons, yt-flexible-actions-view-model .yt-flexible-actions-view-model-wiz__action", {
  4168. listener: (otherBtns) => addAutoLikeToggleBtn(otherBtns, chanId, chanName, ["left-margin", "right-margin"]),
  4169. });
  4170. }
  4171. else if (titleCont)
  4172. addAutoLikeToggleBtn(titleCont, chanId, chanName);
  4173. }
  4174. });
  4175. }
  4176. });
  4177. }
  4178. log("Initialized auto-like channels feature");
  4179. }
  4180. catch (err) {
  4181. error("Error while auto-liking channel:", err);
  4182. }
  4183. }
  4184. //#SECTION toggle btn
  4185. /** Adds a toggle button to enable or disable auto-liking videos from a channel */
  4186. async function addAutoLikeToggleBtn(siblingEl, channelId, channelName, extraClasses) {
  4187. var _a;
  4188. const chan = autoLikeStore.getData().channels.find((ch) => ch.id === channelId);
  4189. siteEvents.on("autoLikeChannelsUpdated", () => {
  4190. var _a, _b;
  4191. const buttonEl = document.querySelector(`.bytm-auto-like-toggle-btn[data-channel-id="${channelId}"]`);
  4192. if (!buttonEl)
  4193. return warn("Couldn't find auto-like toggle button for channel ID:", channelId);
  4194. const enabled = (_b = (_a = autoLikeStore.getData().channels.find((ch) => ch.id === channelId)) === null || _a === void 0 ? void 0 : _a.enabled) !== null && _b !== void 0 ? _b : false;
  4195. if (enabled)
  4196. buttonEl.classList.add("toggled");
  4197. else
  4198. buttonEl.classList.remove("toggled");
  4199. });
  4200. const buttonEl = await createLongBtn({
  4201. resourceName: `icon-auto_like${(chan === null || chan === void 0 ? void 0 : chan.enabled) ? "_enabled" : ""}`,
  4202. text: t("auto_like"),
  4203. title: t(`auto_like_button_tooltip${(chan === null || chan === void 0 ? void 0 : chan.enabled) ? "_enabled" : "_disabled"}`),
  4204. toggle: true,
  4205. toggleInitialState: (_a = chan === null || chan === void 0 ? void 0 : chan.enabled) !== null && _a !== void 0 ? _a : false,
  4206. togglePredicate(e) {
  4207. e.shiftKey && getAutoLikeDialog().then((dlg) => dlg.open());
  4208. return !e.shiftKey;
  4209. },
  4210. async onToggle(toggled) {
  4211. var _a;
  4212. try {
  4213. await autoLikeStore.loadData();
  4214. buttonEl.title = buttonEl.ariaLabel = t(`auto_like_button_tooltip${toggled ? "_enabled" : "_disabled"}`);
  4215. const chanId = sanitizeChannelId((_a = buttonEl.dataset.channelId) !== null && _a !== void 0 ? _a : channelId);
  4216. const imgEl = buttonEl.querySelector(".bytm-generic-btn-img");
  4217. const imgHtml = await resourceAsString(`icon-auto_like${toggled ? "_enabled" : ""}`);
  4218. if (imgEl && imgHtml)
  4219. setInnerHtml(imgEl, imgHtml);
  4220. if (autoLikeStore.getData().channels.find((ch) => ch.id === chanId) === undefined) {
  4221. await autoLikeStore.setData({
  4222. channels: [
  4223. ...autoLikeStore.getData().channels,
  4224. { id: chanId, name: channelName !== null && channelName !== void 0 ? channelName : "", enabled: toggled },
  4225. ],
  4226. });
  4227. }
  4228. else {
  4229. await autoLikeStore.setData({
  4230. channels: autoLikeStore.getData().channels
  4231. .map((ch) => ch.id === chanId ? Object.assign(Object.assign({}, ch), { enabled: toggled }) : ch),
  4232. });
  4233. }
  4234. emitSiteEvent("autoLikeChannelsUpdated");
  4235. showIconToast({
  4236. message: toggled ? t("auto_like_enabled_toast") : t("auto_like_disabled_toast"),
  4237. icon: `icon-auto_like${toggled ? "_enabled" : ""}`,
  4238. });
  4239. log(`Toggled auto-like for channel '${channelName}' (ID: '${chanId}') to ${toggled ? "enabled" : "disabled"}`);
  4240. }
  4241. catch (err) {
  4242. error("Error while toggling auto-like channel:", err);
  4243. }
  4244. }
  4245. });
  4246. buttonEl.classList.add(...["bytm-auto-like-toggle-btn", ...(extraClasses !== null && extraClasses !== void 0 ? extraClasses : [])]);
  4247. buttonEl.dataset.channelId = channelId;
  4248. siblingEl.insertAdjacentElement("afterend", createRipple(buttonEl));
  4249. siteEvents.on("autoLikeChannelsUpdated", async () => {
  4250. var _a, _b;
  4251. const buttonEl = document.querySelector(`.bytm-auto-like-toggle-btn[data-channel-id="${channelId}"]`);
  4252. if (!buttonEl)
  4253. return;
  4254. const enabled = (_b = (_a = autoLikeStore.getData().channels.find((ch) => ch.id === channelId)) === null || _a === void 0 ? void 0 : _a.enabled) !== null && _b !== void 0 ? _b : false;
  4255. if (enabled)
  4256. buttonEl.classList.add("toggled");
  4257. else
  4258. buttonEl.classList.remove("toggled");
  4259. const imgEl = buttonEl.querySelector(".bytm-generic-btn-img");
  4260. const imgHtml = await resourceAsString(`icon-auto_like${enabled ? "_enabled" : ""}`);
  4261. if (imgEl && imgHtml)
  4262. setInnerHtml(imgEl, imgHtml);
  4263. });
  4264. }//#region misc
  4265. let domain;
  4266. /**
  4267. * Returns the current domain as a constant string representation
  4268. * @throws Throws if script runs on an unexpected website
  4269. */
  4270. function getDomain() {
  4271. if (domain)
  4272. return domain;
  4273. if (location.hostname.match(/^music\.youtube/))
  4274. return domain = "ytm";
  4275. else if (location.hostname.match(/youtube\./))
  4276. return domain = "yt";
  4277. else
  4278. throw new Error("BetterYTM is running on an unexpected website. Please don't tamper with the @match directives in the userscript header.");
  4279. }
  4280. /** Returns a pseudo-random ID unique to each session - returns null if sessionStorage is unavailable */
  4281. function getSessionId() {
  4282. try {
  4283. if (!sessionStorageAvailable)
  4284. throw new Error("Session storage unavailable");
  4285. let sesId = window.sessionStorage.getItem("_bytm-session-id");
  4286. if (!sesId)
  4287. window.sessionStorage.setItem("_bytm-session-id", sesId = UserUtils.randomId(8, 36));
  4288. return sesId;
  4289. }
  4290. catch (err) {
  4291. warn("Couldn't get session ID, sessionStorage / cookies might be disabled:", err);
  4292. return null;
  4293. }
  4294. }
  4295. let isCompressionSupported;
  4296. /** Tests whether compression via the predefined {@linkcode compressionFormat} is supported (only on the first call, then returns the cached result) */
  4297. async function compressionSupported() {
  4298. if (typeof isCompressionSupported === "boolean")
  4299. return isCompressionSupported;
  4300. try {
  4301. await UserUtils.compress(".", compressionFormat, "string");
  4302. return isCompressionSupported = true;
  4303. }
  4304. catch (_a) {
  4305. return isCompressionSupported = false;
  4306. }
  4307. }
  4308. /** Returns a string with the given array's items separated by a default separator (`", "` by default), with an optional different separator for the last item */
  4309. function arrayWithSeparators(array, separator = ", ", lastSeparator) {
  4310. const arr = [...array];
  4311. if (arr.length === 0)
  4312. return "";
  4313. else if (arr.length <= 2)
  4314. return arr.join(lastSeparator);
  4315. else
  4316. return `${arr.slice(0, -1).join(separator)}${lastSeparator}${arr.at(-1)}`;
  4317. }
  4318. /** Returns the watch ID of the current video or null if not on a video page */
  4319. function getWatchId() {
  4320. const { searchParams, pathname } = new URL(location.href);
  4321. return pathname.includes("/watch") ? searchParams.get("v") : null;
  4322. }
  4323. /**
  4324. * Returns the ID of the current channel in the format `@User` or `UC...` from URLs with the path `/@User`, `/@User/videos`, `/channel/UC...` or `/channel/UC.../videos`
  4325. * Returns null if the current page is not a channel page or there was an error parsing the URL
  4326. */
  4327. function getCurrentChannelId() {
  4328. return parseChannelIdFromUrl(location.href);
  4329. }
  4330. /** Returns the channel ID from a URL or null if the URL is invalid */
  4331. function parseChannelIdFromUrl(url) {
  4332. try {
  4333. const { pathname } = url instanceof URL ? url : new URL(url);
  4334. if (pathname.includes("/channel/"))
  4335. return sanitizeChannelId(pathname.split("/channel/")[1].split("/")[0]);
  4336. else if (pathname.includes("/@"))
  4337. return sanitizeChannelId(pathname.split("/@")[1].split("/")[0]);
  4338. else
  4339. return null;
  4340. }
  4341. catch (_a) {
  4342. return null;
  4343. }
  4344. }
  4345. /** Sanitizes a channel ID by adding a leading `@` if the ID doesn't start with `UC...` */
  4346. function sanitizeChannelId(channelId) {
  4347. channelId = String(channelId).trim();
  4348. return isValidChannelId(channelId)
  4349. ? channelId
  4350. : `@${channelId}`;
  4351. }
  4352. /** Tests whether a string is a valid channel ID in the format `@User` or `.C...` */
  4353. function isValidChannelId(channelId) {
  4354. return channelId.match(/^([A-Z]C|@)\w+$/) !== null;
  4355. }
  4356. /** Returns the thumbnail URL for a video with either a given quality identifier or index */
  4357. function getThumbnailUrl(watchId, qualityOrIndex = "maxresdefault") {
  4358. return `https://i.ytimg.com/vi/${watchId}/${qualityOrIndex}.jpg`;
  4359. }
  4360. /** Returns the best available thumbnail URL for a video with the given watch ID */
  4361. async function getBestThumbnailUrl(watchId) {
  4362. try {
  4363. const priorityList = ["maxresdefault", "sddefault", "hqdefault", 0];
  4364. for (const quality of priorityList) {
  4365. let response;
  4366. const url = getThumbnailUrl(watchId, quality);
  4367. try {
  4368. response = await sendRequest({ url, method: "HEAD", timeout: 6000 });
  4369. }
  4370. catch (err) {
  4371. error(`Error while sending HEAD request to thumbnail URL for video '${watchId}' with quality '${quality}':`, err);
  4372. void err;
  4373. }
  4374. if (response && response.status < 300 && response.status >= 200)
  4375. return url;
  4376. }
  4377. }
  4378. catch (err) {
  4379. throw new Error(`Couldn't get thumbnail URL for video '${watchId}': ${err}`);
  4380. }
  4381. }
  4382. /** Opens the given URL in a new tab, using GM.openInTab if available */
  4383. function openInTab(href, background = false) {
  4384. try {
  4385. UserUtils.openInNewTab(href, background);
  4386. }
  4387. catch (_a) {
  4388. window.open(href, "_blank", "noopener noreferrer");
  4389. }
  4390. }
  4391. /** Tries to parse an uncompressed or compressed input string as a JSON object */
  4392. async function tryToDecompressAndParse(input) {
  4393. let parsed = null;
  4394. try {
  4395. parsed = JSON.parse(input);
  4396. }
  4397. catch (_a) {
  4398. try {
  4399. parsed = JSON.parse(await UserUtils.decompress(input, compressionFormat, "string"));
  4400. }
  4401. catch (err) {
  4402. error("Couldn't decompress and parse data due to an error:", err);
  4403. return null;
  4404. }
  4405. }
  4406. // artificial timeout to allow animations to finish and because dumb monkey brains *expect* a delay
  4407. await UserUtils.pauseFor(250);
  4408. return parsed;
  4409. }
  4410. //#region resources
  4411. /**
  4412. * Returns the URL of a resource by its name, as defined in `assets/resources.json`, from GM resource cache - [see GM.getResourceUrl docs](https://wiki.greasespot.net/GM.getResourceUrl)
  4413. * Falls back to a `raw.githubusercontent.com` URL or base64-encoded data URI if the resource is not available in the GM resource cache
  4414. */
  4415. async function getResourceUrl(name) {
  4416. var _a;
  4417. let url = await GM.getResourceUrl(name);
  4418. if (!url || url.length === 0) {
  4419. const resource = (_a = GM.info.script.resources) === null || _a === void 0 ? void 0 : _a[name].url;
  4420. if (typeof resource === "string") {
  4421. const resourceUrl = new URL(resource);
  4422. const resourcePath = resourceUrl.pathname;
  4423. if (resourcePath)
  4424. return `https://raw.githubusercontent.com/${repo}/${branch}${resourcePath}`;
  4425. }
  4426. warn(`Couldn't get blob URL nor external URL for @resource '${name}', trying to use base64-encoded fallback`);
  4427. // @ts-ignore
  4428. url = await GM.getResourceUrl(name, false);
  4429. }
  4430. return url;
  4431. }
  4432. /**
  4433. * Returns the preferred locale of the user, provided it is supported by the userscript.
  4434. * Prioritizes `navigator.language`, then `navigator.languages`, then `"en_US"` as a fallback.
  4435. */
  4436. function getPreferredLocale() {
  4437. var _a;
  4438. const navLang = navigator.language.replace(/-/g, "_");
  4439. const navLangs = navigator.languages
  4440. .filter(lang => lang.match(/^[a-z]{2}(-|_)[A-Z]$/) !== null)
  4441. .map(lang => lang.replace(/-/g, "_"));
  4442. if (Object.entries(langMapping).find(([key]) => key === navLang))
  4443. return navLang;
  4444. for (const loc of navLangs) {
  4445. if (Object.entries(langMapping).find(([key]) => key === loc))
  4446. return loc;
  4447. }
  4448. // if navigator.languages has entries that aren't locale codes in the format xx_XX
  4449. if (navigator.languages.some(lang => lang.match(/^[a-z]{2}$/))) {
  4450. for (const lang of navLangs) {
  4451. const foundLoc = (_a = Object.entries(langMapping).find(([key]) => key.startsWith(lang))) === null || _a === void 0 ? void 0 : _a[0];
  4452. if (foundLoc)
  4453. return foundLoc;
  4454. }
  4455. }
  4456. return "en_US";
  4457. }
  4458. /** Returns the content behind the passed resource identifier as a string, for example to be assigned to an element's innerHTML property */
  4459. async function resourceAsString(resource) {
  4460. try {
  4461. const resourceUrl = await getResourceUrl(resource);
  4462. if (!resourceUrl)
  4463. throw new Error(`Couldn't find URL for resource '${resource}'`);
  4464. return await (await UserUtils.fetchAdvanced(resourceUrl)).text();
  4465. }
  4466. catch (err) {
  4467. error("Couldn't get SVG element from resource:", err);
  4468. return null;
  4469. }
  4470. }
  4471. /** Parses a markdown string using marked and turns it into an HTML string with default settings - doesn't sanitize against XSS! */
  4472. function parseMarkdown(mdString) {
  4473. return marked.marked.parse(mdString, {
  4474. async: true,
  4475. gfm: true,
  4476. });
  4477. }
  4478. /** Returns the content of the changelog markdown file */
  4479. async function getChangelogMd() {
  4480. return await (await UserUtils.fetchAdvanced(await getResourceUrl("doc-changelog"))).text();
  4481. }
  4482. /** Returns the changelog as HTML with a details element for each version */
  4483. async function getChangelogHtmlWithDetails() {
  4484. try {
  4485. const changelogMd = await getChangelogMd();
  4486. let changelogHtml = await parseMarkdown(changelogMd);
  4487. const getVerId = (verStr) => verStr.trim().replace(/[._#\s-]/g, "");
  4488. changelogHtml = changelogHtml.replace(/<div\s+class="split">\s*<\/div>\s*\n?\s*<br(\s\/)?>/gm, "</details>\n<br>\n<details class=\"bytm-changelog-version-details\" tabindex=\"0\">");
  4489. const h2Matches = Array.from(changelogHtml.matchAll(/<h2(\s+id=".+")?>([\d\w\s.]+)<\/h2>/gm));
  4490. for (const match of h2Matches) {
  4491. const [fullMatch, , verStr] = match;
  4492. const verId = getVerId(verStr);
  4493. const h2Elem = `<h2 id="${verId}" role="subheading" aria-level="1">${verStr}</h2>`;
  4494. const summaryElem = `<summary tab-index="0">${h2Elem}</summary>`;
  4495. changelogHtml = changelogHtml.replace(fullMatch, `${summaryElem}`);
  4496. }
  4497. changelogHtml = `<details class="bytm-changelog-version-details" tabindex="0">${changelogHtml}</details>`;
  4498. return changelogHtml;
  4499. }
  4500. catch (err) {
  4501. return `Error while preparing changelog: ${err}`;
  4502. }
  4503. }let curLogLevel = LogLevel.Info;
  4504. /** Common prefix to be able to tell logged messages apart and filter them in devtools */
  4505. const consPrefix = `[${scriptInfo.name}]`;
  4506. const consPrefixDbg = `[${scriptInfo.name}/#DEBUG]`;
  4507. /** Sets the current log level. 0 = Debug, 1 = Info */
  4508. function setLogLevel(level) {
  4509. curLogLevel = level;
  4510. setGlobalProp("logLevel", level);
  4511. if (curLogLevel !== level)
  4512. log("Set the log level to", LogLevel[level]);
  4513. }
  4514. /** Extracts the log level from the last item from spread arguments - returns 0 if the last item is not a number or too low or high */
  4515. function getLogLevel(args) {
  4516. const minLogLvl = 0, maxLogLvl = 1;
  4517. if (typeof args.at(-1) === "number")
  4518. return UserUtils.clamp(args.splice(args.length - 1)[0], minLogLvl, maxLogLvl);
  4519. return LogLevel.Debug;
  4520. }
  4521. /**
  4522. * Logs all passed values to the console, as long as the log level is sufficient.
  4523. * @param args Last parameter is log level (0 = Debug, 1/undefined = Info) - any number as the last parameter will be stripped out! Convert to string if it shouldn't be.
  4524. */
  4525. function log(...args) {
  4526. if (curLogLevel <= getLogLevel(args))
  4527. console.log(consPrefix, ...args);
  4528. }
  4529. /**
  4530. * Logs all passed values to the console as info, as long as the log level is sufficient.
  4531. * @param args Last parameter is log level (0 = Debug, 1/undefined = Info) - any number as the last parameter will be stripped out! Convert to string if it shouldn't be.
  4532. */
  4533. function info(...args) {
  4534. if (curLogLevel <= getLogLevel(args))
  4535. console.info(consPrefix, ...args);
  4536. }
  4537. /** Logs all passed values to the console as a warning, no matter the log level. */
  4538. function warn(...args) {
  4539. console.warn(consPrefix, ...args);
  4540. }
  4541. function getErrorDialog(errName, args) {
  4542. return new MarkdownDialog({
  4543. id: "generic-error",
  4544. height: 400,
  4545. width: 500,
  4546. small: true,
  4547. destroyOnClose: true,
  4548. renderHeader() {
  4549. const header = document.createElement("h2");
  4550. header.classList.add("bytm-dialog-title");
  4551. header.role = "heading";
  4552. header.ariaLevel = "1";
  4553. header.tabIndex = 0;
  4554. header.textContent = header.ariaLabel = errName;
  4555. return header;
  4556. },
  4557. body: `\
  4558. ${args.length > 0 ? args.join(" ") : t("generic_error_dialog_message")}
  4559. ${t("generic_error_dialog_open_console_note", consPrefixDbg, packageJson.bugs.url)}`,
  4560. });
  4561. }
  4562. /** Logs all passed values to the console as an error, no matter the log level. */
  4563. function error(...args) {
  4564. var _a, _b;
  4565. console.error(consPrefix, ...args);
  4566. if (getFeature("showToastOnGenericError")) {
  4567. const errName = (_b = (_a = args.find(a => a instanceof Error)) === null || _a === void 0 ? void 0 : _a.name) !== null && _b !== void 0 ? _b : t("error");
  4568. UserUtils.debounce(() => showIconToast({
  4569. message: t("generic_error_toast_encountered_error_type", errName),
  4570. subtitle: t("generic_error_toast_click_for_details"),
  4571. icon: "icon-error",
  4572. iconFill: "var(--bytm-error-col)",
  4573. onClick: () => getErrorDialog(errName, Array.isArray(args) ? args : []).open(),
  4574. }))();
  4575. }
  4576. }
  4577. /** Logs all passed values to the console with a debug-specific prefix */
  4578. function dbg(...args) {
  4579. console.log(consPrefixDbg, ...args);
  4580. }//#region Dark Reader
  4581. /** Disables Dark Reader if it is present */
  4582. async function disableDarkReader() {
  4583. if (getFeature("disableDarkReaderSites") !== getDomain() && getFeature("disableDarkReaderSites") !== "all")
  4584. return;
  4585. const metaElem = document.createElement("meta");
  4586. metaElem.name = "darkreader-lock";
  4587. metaElem.id = "bytm-disable-dark-reader";
  4588. document.head.appendChild(metaElem);
  4589. info("Disabled Dark Reader");
  4590. }
  4591. //#region SponsorBlock
  4592. /** Fixes the z-index of the SponsorBlock panel */
  4593. async function fixSponsorBlock() {
  4594. try {
  4595. return addStyleFromResource("css-fix_sponsorblock");
  4596. }
  4597. catch (err) {
  4598. error("Failed to fix SponsorBlock styling:", err);
  4599. }
  4600. }
  4601. //#region ThemeSong
  4602. /** Adjust the BetterYTM styles if ThemeSong is ***not*** used */
  4603. async function fixPlayerPageTheming() {
  4604. try {
  4605. return addStyleFromResource("css-fix_playerpage_theming");
  4606. }
  4607. catch (err) {
  4608. error("Failed to fix BetterYTM player page theming:", err);
  4609. }
  4610. }
  4611. /** Sets the lightness of the theme color used by BYTM according to the configured lightness value */
  4612. async function fixThemeSong() {
  4613. try {
  4614. const cssVarName = (() => {
  4615. switch (getFeature("themeSongLightness")) {
  4616. case "darker": return "--ts-palette-darkmuted-hex";
  4617. case "normal": return "--ts-palette-muted-hex";
  4618. case "lighter": return "--ts-palette-lightmuted-hex";
  4619. }
  4620. ;
  4621. })();
  4622. document.documentElement.style.setProperty("--bytm-themesong-bg-accent-col", `var(${cssVarName})`);
  4623. }
  4624. catch (err) {
  4625. error("Failed to set ThemeSong integration color lightness:", err);
  4626. }
  4627. }/** Ratelimit budget timeframe in seconds - should reflect what's in geniURL's docs */
  4628. const geniUrlRatelimitTimeframe = 30;
  4629. //#region media control bar
  4630. let currentSongTitle = "";
  4631. /** Adds a lyrics button to the player bar */
  4632. async function addPlayerBarLyricsBtn() {
  4633. addSelectorListener("playerBarMiddleButtons", "ytmusic-like-button-renderer#like-button-renderer", { listener: addActualLyricsBtn });
  4634. }
  4635. /** Actually adds the lyrics button after the like button renderer has been verified to exist */
  4636. async function addActualLyricsBtn(likeContainer) {
  4637. const songTitleElem = document.querySelector(".content-info-wrapper > yt-formatted-string");
  4638. if (!songTitleElem)
  4639. return warn("Couldn't find song title element");
  4640. currentSongTitle = songTitleElem.title;
  4641. const spinnerIconUrl = await getResourceUrl("icon-spinner");
  4642. const lyricsIconUrl = await getResourceUrl("icon-lyrics");
  4643. const errorIconUrl = await getResourceUrl("icon-error");
  4644. const onMutation = async (mutations) => {
  4645. var _a, e_1, _b, _c;
  4646. try {
  4647. for (var _d = true, mutations_1 = __asyncValues(mutations), mutations_1_1; mutations_1_1 = await mutations_1.next(), _a = mutations_1_1.done, !_a; _d = true) {
  4648. _c = mutations_1_1.value;
  4649. _d = false;
  4650. const mut = _c;
  4651. const newTitle = mut.target.title;
  4652. if (newTitle !== currentSongTitle && newTitle.length > 0) {
  4653. const lyricsBtn = document.querySelector("#bytm-player-bar-lyrics-btn");
  4654. if (!lyricsBtn)
  4655. continue;
  4656. lyricsBtn.style.cursor = "wait";
  4657. lyricsBtn.style.pointerEvents = "none";
  4658. const imgElem = lyricsBtn.querySelector("img");
  4659. imgElem.src = spinnerIconUrl;
  4660. imgElem.classList.add("bytm-spinner");
  4661. currentSongTitle = newTitle;
  4662. const url = await getCurrentLyricsUrl(); // can take a second or two
  4663. imgElem.src = lyricsIconUrl;
  4664. imgElem.classList.remove("bytm-spinner");
  4665. if (!url) {
  4666. let artist, song;
  4667. if ("mediaSession" in navigator && navigator.mediaSession.metadata) {
  4668. artist = navigator.mediaSession.metadata.artist;
  4669. song = navigator.mediaSession.metadata.title;
  4670. }
  4671. const query = artist && song ? "?q=" + encodeURIComponent(sanitizeArtists(artist) + " - " + sanitizeSong(song)) : "";
  4672. imgElem.src = errorIconUrl;
  4673. lyricsBtn.ariaLabel = lyricsBtn.title = t("lyrics_not_found_click_open_search");
  4674. lyricsBtn.style.cursor = "pointer";
  4675. lyricsBtn.style.pointerEvents = "all";
  4676. lyricsBtn.style.display = "inline-flex";
  4677. lyricsBtn.style.visibility = "visible";
  4678. lyricsBtn.href = `https://genius.com/search${query}`;
  4679. continue;
  4680. }
  4681. lyricsBtn.href = url;
  4682. lyricsBtn.ariaLabel = lyricsBtn.title = t("open_current_lyrics");
  4683. lyricsBtn.style.cursor = "pointer";
  4684. lyricsBtn.style.visibility = "visible";
  4685. lyricsBtn.style.display = "inline-flex";
  4686. lyricsBtn.style.pointerEvents = "initial";
  4687. }
  4688. }
  4689. }
  4690. catch (e_1_1) { e_1 = { error: e_1_1 }; }
  4691. finally {
  4692. try {
  4693. if (!_d && !_a && (_b = mutations_1.return)) await _b.call(mutations_1);
  4694. }
  4695. finally { if (e_1) throw e_1.error; }
  4696. }
  4697. };
  4698. // since YT and YTM don't reload the page on video change, MutationObserver needs to be used to watch for changes in the video title
  4699. const obs = new MutationObserver(onMutation);
  4700. obs.observe(songTitleElem, { attributes: true, attributeFilter: ["title"] });
  4701. const lyricsBtnElem = await createLyricsBtn(undefined);
  4702. lyricsBtnElem.id = "bytm-player-bar-lyrics-btn";
  4703. // run parallel so the element is inserted as soon as possible
  4704. getCurrentLyricsUrl().then(url => {
  4705. url && addGeniusUrlToLyricsBtn(lyricsBtnElem, url);
  4706. });
  4707. log("Inserted lyrics button into media controls bar");
  4708. const thumbToggleElem = document.querySelector("#bytm-thumbnail-overlay-toggle");
  4709. if (thumbToggleElem)
  4710. thumbToggleElem.insertAdjacentElement("afterend", lyricsBtnElem);
  4711. else
  4712. likeContainer.insertAdjacentElement("afterend", lyricsBtnElem);
  4713. }
  4714. //#region lyrics utils
  4715. /** Removes everything in parentheses from the passed song name */
  4716. function sanitizeSong(songName) {
  4717. if (typeof songName !== "string")
  4718. return songName;
  4719. const parensRegex = /\(.+\)/gmi;
  4720. const squareParensRegex = /\[.+\]/gmi;
  4721. // trim right after the song name:
  4722. const sanitized = songName
  4723. .replace(parensRegex, "")
  4724. .replace(squareParensRegex, "");
  4725. return sanitized.trim();
  4726. }
  4727. /** Removes the secondary artist (if it exists) from the passed artists string */
  4728. function sanitizeArtists(artists) {
  4729. artists = artists.split(/\s*\u2022\s*/gmiu)[0]; // split at &bull; [•] character
  4730. if (artists.match(/&/))
  4731. artists = artists.split(/\s*&\s*/gm)[0];
  4732. if (artists.match(/,/))
  4733. artists = artists.split(/,\s*/gm)[0];
  4734. if (artists.match(/(f(ea)?t\.?|Remix|Edit|Flip|Cover|Night\s?Core|Bass\s?Boost|pro?d\.?)/i)) {
  4735. const parensRegex = /\(.+\)/gmi;
  4736. const squareParensRegex = /\[.+\]/gmi;
  4737. artists = artists
  4738. .replace(parensRegex, "")
  4739. .replace(squareParensRegex, "");
  4740. }
  4741. return artists.trim();
  4742. }
  4743. /** Returns the lyrics URL from genius for the currently selected song */
  4744. async function getCurrentLyricsUrl() {
  4745. try {
  4746. // In videos the video title contains both artist and song title, in "regular" YTM songs, the video title only contains the song title
  4747. const isVideo = getCurrentMediaType() === "video";
  4748. const songTitleElem = document.querySelector(".content-info-wrapper > yt-formatted-string");
  4749. const songMetaElem = document.querySelector("span.subtitle > yt-formatted-string :first-child");
  4750. if (!songTitleElem || !songMetaElem)
  4751. return undefined;
  4752. const songNameRaw = songTitleElem.title;
  4753. let songName = songNameRaw;
  4754. let artistName = songMetaElem.textContent;
  4755. if (isVideo) {
  4756. // for some fucking reason some music videos have YTM-like song title and artist separation, some don't
  4757. if (songName.includes("-")) {
  4758. const split = splitVideoTitle(songName);
  4759. songName = split.song;
  4760. artistName = split.artist;
  4761. }
  4762. }
  4763. if (!artistName)
  4764. return undefined;
  4765. const url = await fetchLyricsUrlTop(sanitizeArtists(artistName), sanitizeSong(songName));
  4766. if (url) {
  4767. emitInterface("bytm:lyricsLoaded", {
  4768. type: "current",
  4769. artists: artistName,
  4770. title: songName,
  4771. url,
  4772. });
  4773. }
  4774. return url;
  4775. }
  4776. catch (err) {
  4777. error("Couldn't resolve lyrics URL:", err);
  4778. return undefined;
  4779. }
  4780. }
  4781. /** Fetches the top lyrics URL result from geniURL - **the passed parameters need to be sanitized first!** */
  4782. async function fetchLyricsUrlTop(artist, song) {
  4783. var _a, _b;
  4784. try {
  4785. return (_b = (_a = (await fetchLyricsUrls(artist, song))) === null || _a === void 0 ? void 0 : _a[0]) === null || _b === void 0 ? void 0 : _b.url;
  4786. }
  4787. catch (err) {
  4788. error("Couldn't get lyrics URL due to error:", err);
  4789. return undefined;
  4790. }
  4791. }
  4792. /**
  4793. * Fetches the 5 best matching lyrics URLs from geniURL using a combo exact-ish and fuzzy search
  4794. * **the passed parameters need to be sanitized first!**
  4795. */
  4796. async function fetchLyricsUrls(artist, song) {
  4797. var _a, _b, _c;
  4798. try {
  4799. const cacheEntry = getLyricsCacheEntry(artist, song);
  4800. if (cacheEntry) {
  4801. info(`Found lyrics URL in cache: ${cacheEntry.url}`);
  4802. return [cacheEntry];
  4803. }
  4804. const fetchUrl = constructUrl(`${getFeature("geniUrlBase")}/search`, {
  4805. disableFuzzy: null,
  4806. utm_source: `${scriptInfo.name} v${scriptInfo.version}${mode === "development" ? "-pre" : ""}`,
  4807. q: `${artist} ${song}`,
  4808. });
  4809. log("Requesting lyrics from geniURL:", fetchUrl);
  4810. const token = getFeature("geniUrlToken");
  4811. const fetchRes = await UserUtils.fetchAdvanced(fetchUrl, Object.assign({}, (token ? {
  4812. headers: {
  4813. Authorization: `Bearer ${token}`,
  4814. },
  4815. } : {})));
  4816. if (fetchRes.status === 429) {
  4817. const waitSeconds = Number((_a = fetchRes.headers.get("retry-after")) !== null && _a !== void 0 ? _a : geniUrlRatelimitTimeframe);
  4818. alert(tp("lyrics_rate_limited", waitSeconds, waitSeconds));
  4819. return undefined;
  4820. }
  4821. else if (fetchRes.status < 200 || fetchRes.status >= 300) {
  4822. error(`Couldn't fetch lyrics URLs from geniURL - status: ${fetchRes.status} - response: ${(_c = (_b = (await fetchRes.json()).message) !== null && _b !== void 0 ? _b : await fetchRes.text()) !== null && _c !== void 0 ? _c : "(none)"}`);
  4823. return undefined;
  4824. }
  4825. const result = await fetchRes.json();
  4826. if (typeof result === "object" && result.error || !result || !result.all) {
  4827. error("Couldn't fetch lyrics URL:", result.message);
  4828. return undefined;
  4829. }
  4830. const allResults = result.all;
  4831. if (allResults.length === 0) {
  4832. warn("No lyrics URL found for the provided song");
  4833. return undefined;
  4834. }
  4835. const allResultsSan = allResults
  4836. .filter(({ meta, url }) => (meta.title || meta.fullTitle) && meta.artists && url)
  4837. .map(({ meta, url }) => {
  4838. var _a;
  4839. return ({
  4840. meta: Object.assign(Object.assign({}, meta), { title: sanitizeSong(String((_a = meta.title) !== null && _a !== void 0 ? _a : meta.fullTitle)), artists: sanitizeArtists(String(meta.artists)) }),
  4841. url,
  4842. });
  4843. });
  4844. const topRes = allResultsSan[0];
  4845. topRes && addLyricsCacheEntryBest(topRes.meta.artists, topRes.meta.title, topRes.url);
  4846. return allResultsSan.map(r => ({
  4847. artist: r.meta.primaryArtist.name,
  4848. song: r.meta.title,
  4849. url: r.url,
  4850. }));
  4851. }
  4852. catch (err) {
  4853. error("Couldn't get lyrics URL due to error:", err);
  4854. return undefined;
  4855. }
  4856. }
  4857. /** Adds the genius URL to the passed lyrics button element if it was previously instantiated with an undefined URL */
  4858. async function addGeniusUrlToLyricsBtn(btnElem, geniusUrl) {
  4859. btnElem.href = geniusUrl;
  4860. btnElem.ariaLabel = btnElem.title = t("open_lyrics");
  4861. btnElem.style.visibility = "visible";
  4862. btnElem.style.display = "inline-flex";
  4863. }
  4864. /** Creates the base lyrics button element */
  4865. async function createLyricsBtn(geniusUrl, hideIfLoading = true) {
  4866. const linkElem = document.createElement("a");
  4867. linkElem.classList.add("ytmusic-player-bar", "bytm-generic-btn");
  4868. linkElem.ariaLabel = linkElem.title = t("lyrics_loading");
  4869. linkElem.role = "button";
  4870. linkElem.target = "_blank";
  4871. linkElem.rel = "noopener noreferrer";
  4872. linkElem.style.visibility = hideIfLoading && geniusUrl ? "initial" : "hidden";
  4873. linkElem.style.display = hideIfLoading && geniusUrl ? "inline-flex" : "none";
  4874. const imgElem = document.createElement("img");
  4875. imgElem.classList.add("bytm-generic-btn-img");
  4876. imgElem.src = await getResourceUrl("icon-lyrics");
  4877. onInteraction(linkElem, (e) => {
  4878. var _a;
  4879. const url = (_a = linkElem.href) !== null && _a !== void 0 ? _a : geniusUrl;
  4880. if (!url || e instanceof MouseEvent)
  4881. return;
  4882. openInTab(url);
  4883. }, {
  4884. preventDefault: false,
  4885. stopPropagation: false,
  4886. });
  4887. linkElem.appendChild(imgElem);
  4888. onInteraction(linkElem, async (e) => {
  4889. if (e.ctrlKey || e.altKey) {
  4890. e.preventDefault();
  4891. e.stopPropagation();
  4892. const search = prompt(t("open_lyrics_search_prompt"));
  4893. if (search)
  4894. openInTab(`https://genius.com/search?q=${encodeURIComponent(search)}`);
  4895. }
  4896. }, {
  4897. preventDefault: false,
  4898. stopPropagation: false,
  4899. });
  4900. return linkElem;
  4901. }
  4902. /** Splits a video title that contains a hyphen into an artist and song */
  4903. function splitVideoTitle(title) {
  4904. const [artist, ...rest] = title.split("-").map((v, i) => i < 2 ? v.trim() : v);
  4905. return { artist, song: rest.join("-") };
  4906. }//#region init queue btns
  4907. /** Initializes the queue buttons */
  4908. async function initQueueButtons() {
  4909. const addCurrentQueueBtns = (evt) => {
  4910. let amt = 0;
  4911. for (const queueItm of evt.childNodes) {
  4912. if (!queueItm.classList.contains("bytm-has-queue-btns")) {
  4913. addQueueButtons(queueItm, undefined, "currentQueue");
  4914. amt++;
  4915. }
  4916. }
  4917. if (amt > 0)
  4918. log(`Added buttons to ${amt} new queue ${UserUtils.autoPlural("item", amt)}`);
  4919. };
  4920. // current queue
  4921. siteEvents.on("queueChanged", addCurrentQueueBtns);
  4922. siteEvents.on("autoplayQueueChanged", addCurrentQueueBtns);
  4923. const queueItems = document.querySelectorAll("#contents.ytmusic-player-queue > ytmusic-player-queue-item");
  4924. if (queueItems.length > 0) {
  4925. queueItems.forEach(itm => addQueueButtons(itm, undefined, "currentQueue"));
  4926. log(`Added buttons to ${queueItems.length} existing "current song queue" ${UserUtils.autoPlural("item", queueItems)}`);
  4927. }
  4928. // generic lists
  4929. const addGenericListQueueBtns = (listElem) => {
  4930. const queueItems = listElem.querySelectorAll("ytmusic-responsive-list-item-renderer");
  4931. if (queueItems.length === 0)
  4932. return;
  4933. let addedBtnsCount = 0;
  4934. queueItems.forEach(itm => {
  4935. if (itm.classList.contains("bytm-has-btns"))
  4936. return;
  4937. itm.classList.add("bytm-has-btns");
  4938. addQueueButtons(itm, ".flex-columns", "genericList", ["bytm-generic-list-queue-btn-container"], "afterParent");
  4939. addedBtnsCount++;
  4940. });
  4941. addedBtnsCount > 0 &&
  4942. log(`Added buttons to ${addedBtnsCount} new "generic song list" ${UserUtils.autoPlural("item", addedBtnsCount)} in list`, listElem);
  4943. };
  4944. const listSelector = `\
  4945. ytmusic-playlist-shelf-renderer #contents,
  4946. ytmusic-section-list-renderer[main-page-type="MUSIC_PAGE_TYPE_ALBUM"] ytmusic-shelf-renderer #contents,
  4947. ytmusic-section-list-renderer[main-page-type="MUSIC_PAGE_TYPE_ARTIST"] ytmusic-shelf-renderer #contents,
  4948. ytmusic-section-list-renderer[main-page-type="MUSIC_PAGE_TYPE_PLAYLIST"] ytmusic-shelf-renderer #contents\
  4949. `;
  4950. if (getFeature("listButtonsPlacement") === "everywhere") {
  4951. const checkAddGenericBtns = (songLists) => {
  4952. for (const list of songLists)
  4953. addGenericListQueueBtns(list);
  4954. };
  4955. addSelectorListener("body", listSelector, {
  4956. all: true,
  4957. continuous: true,
  4958. debounce: 150,
  4959. // TODO: switch to longer debounce time and edge type "risingIdle" after UserUtils update
  4960. debounceEdge: "falling",
  4961. listener: checkAddGenericBtns,
  4962. });
  4963. siteEvents.on("pathChanged", () => {
  4964. const songLists = document.querySelectorAll(listSelector);
  4965. if (songLists.length > 0)
  4966. checkAddGenericBtns(songLists);
  4967. });
  4968. }
  4969. }
  4970. //#region add queue btns
  4971. /**
  4972. * Adds the buttons to each item in the current song queue.
  4973. * Also observes for changes to add new buttons to new items in the queue.
  4974. * @param queueItem The element with tagname `ytmusic-player-queue-item` or `ytmusic-responsive-list-item-renderer` to add queue buttons to
  4975. * @param listType The type of list the queue item is in
  4976. * @param classes Extra CSS classes to apply to the container
  4977. * @param insertPosition Where to insert the button container in relation to the parent element
  4978. */
  4979. async function addQueueButtons(queueItem, containerParentSelector = ".song-info", listType = "currentQueue", classes = [], insertPosition = "child") {
  4980. const queueBtnsCont = document.createElement("div");
  4981. queueBtnsCont.classList.add(...["bytm-queue-btn-container", ...classes]);
  4982. const lyricsIconUrl = await getResourceUrl("icon-lyrics");
  4983. const deleteIconUrl = await getResourceUrl("icon-delete");
  4984. //#region lyrics btn
  4985. let lyricsBtnElem;
  4986. if (getFeature("lyricsQueueButton")) {
  4987. lyricsBtnElem = await createLyricsBtn(undefined, false);
  4988. lyricsBtnElem.ariaLabel = lyricsBtnElem.title = t("open_lyrics");
  4989. lyricsBtnElem.style.display = "inline-flex";
  4990. lyricsBtnElem.style.visibility = "initial";
  4991. lyricsBtnElem.style.pointerEvents = "initial";
  4992. lyricsBtnElem.role = "link";
  4993. lyricsBtnElem.tabIndex = 0;
  4994. onInteraction(lyricsBtnElem, async (e) => {
  4995. var _a;
  4996. e.preventDefault();
  4997. e.stopImmediatePropagation();
  4998. let song, artist;
  4999. if (listType === "currentQueue") {
  5000. const songInfo = queueItem.querySelector(".song-info");
  5001. if (!songInfo)
  5002. return;
  5003. const [songEl, artistEl] = songInfo.querySelectorAll("yt-formatted-string");
  5004. song = songEl === null || songEl === void 0 ? void 0 : songEl.textContent;
  5005. artist = artistEl === null || artistEl === void 0 ? void 0 : artistEl.textContent;
  5006. }
  5007. else if (listType === "genericList") {
  5008. const songEl = queueItem.querySelector(".title-column yt-formatted-string a");
  5009. let artistEl = null;
  5010. if (location.pathname.startsWith("/playlist"))
  5011. artistEl = document.querySelector("ytmusic-detail-header-renderer .metadata .subtitle-container yt-formatted-string a");
  5012. if (!artistEl || !artistEl.textContent)
  5013. artistEl = queueItem.querySelector(".secondary-flex-columns yt-formatted-string:first-child a");
  5014. song = songEl === null || songEl === void 0 ? void 0 : songEl.textContent;
  5015. artist = artistEl === null || artistEl === void 0 ? void 0 : artistEl.textContent;
  5016. if (!artist) {
  5017. // new playlist design
  5018. artistEl = document.querySelector("ytmusic-responsive-header-renderer .strapline a.yt-formatted-string[href]");
  5019. artist = artistEl === null || artistEl === void 0 ? void 0 : artistEl.textContent;
  5020. }
  5021. }
  5022. else
  5023. return;
  5024. if (!song || !artist)
  5025. return error("Couldn't get song or artist name from queue item - song:", song, "- artist:", artist);
  5026. let lyricsUrl;
  5027. const artistsSan = sanitizeArtists(artist);
  5028. const songSan = sanitizeSong(song);
  5029. const splitTitle = splitVideoTitle(songSan);
  5030. const cachedLyricsEntry = songSan.includes("-")
  5031. ? getLyricsCacheEntry(splitTitle.artist, splitTitle.song)
  5032. : getLyricsCacheEntry(artistsSan, songSan);
  5033. if (cachedLyricsEntry)
  5034. lyricsUrl = cachedLyricsEntry.url;
  5035. else if (!queueItem.hasAttribute("data-bytm-loading")) {
  5036. const imgEl = lyricsBtnElem === null || lyricsBtnElem === void 0 ? void 0 : lyricsBtnElem.querySelector("img");
  5037. if (!imgEl)
  5038. return;
  5039. if (!cachedLyricsEntry) {
  5040. queueItem.setAttribute("data-bytm-loading", "");
  5041. imgEl.src = await getResourceUrl("icon-spinner");
  5042. imgEl.classList.add("bytm-spinner");
  5043. }
  5044. lyricsUrl = (_a = cachedLyricsEntry === null || cachedLyricsEntry === void 0 ? void 0 : cachedLyricsEntry.url) !== null && _a !== void 0 ? _a : await fetchLyricsUrlTop(artistsSan, songSan);
  5045. if (lyricsUrl) {
  5046. emitInterface("bytm:lyricsLoaded", {
  5047. type: "queue",
  5048. artists: artist,
  5049. title: song,
  5050. url: lyricsUrl,
  5051. });
  5052. }
  5053. const resetImgElem = () => {
  5054. imgEl.src = lyricsIconUrl;
  5055. imgEl.classList.remove("bytm-spinner");
  5056. };
  5057. if (!cachedLyricsEntry) {
  5058. queueItem.removeAttribute("data-bytm-loading");
  5059. // so the new image doesn't "blink"
  5060. setTimeout(resetImgElem, 100);
  5061. }
  5062. if (!lyricsUrl) {
  5063. resetImgElem();
  5064. if (confirm(t("lyrics_not_found_confirm_open_search")))
  5065. openInTab(`https://genius.com/search?q=${encodeURIComponent(`${artistsSan} - ${songSan}`)}`);
  5066. return;
  5067. }
  5068. }
  5069. lyricsUrl && openInTab(lyricsUrl);
  5070. });
  5071. }
  5072. //#region delete btn
  5073. let deleteBtnElem;
  5074. if (getFeature("deleteFromQueueButton")) {
  5075. deleteBtnElem = document.createElement("a");
  5076. deleteBtnElem.ariaLabel = deleteBtnElem.title = (listType === "currentQueue" ? t("remove_from_queue") : t("delete_from_list"));
  5077. deleteBtnElem.classList.add("ytmusic-player-bar", "bytm-delete-from-queue", "bytm-generic-btn");
  5078. deleteBtnElem.role = "button";
  5079. deleteBtnElem.tabIndex = 0;
  5080. deleteBtnElem.style.visibility = "initial";
  5081. const imgElem = document.createElement("img");
  5082. imgElem.classList.add("bytm-generic-btn-img");
  5083. imgElem.src = deleteIconUrl;
  5084. onInteraction(deleteBtnElem, async (e) => {
  5085. e.preventDefault();
  5086. e.stopImmediatePropagation();
  5087. // container of the queue item popup menu - element gets reused for every queue item
  5088. let queuePopupCont = document.querySelector("ytmusic-app ytmusic-popup-container tp-yt-iron-dropdown");
  5089. try {
  5090. // three dots button to open the popup menu of a queue item
  5091. const dotsBtnElem = queueItem.querySelector("ytmusic-menu-renderer yt-button-shape[id=\"button-shape\"] button");
  5092. if (dotsBtnElem) {
  5093. if (queuePopupCont)
  5094. queuePopupCont.setAttribute("data-bytm-hidden", "true");
  5095. dotsBtnElem.click();
  5096. }
  5097. else {
  5098. info("Couldn't find three dots button in queue item, trying to open the context menu manually");
  5099. queueItem.dispatchEvent(new MouseEvent("contextmenu", { bubbles: true, cancelable: false }));
  5100. }
  5101. queuePopupCont = document.querySelector("ytmusic-app ytmusic-popup-container tp-yt-iron-dropdown");
  5102. queuePopupCont === null || queuePopupCont === void 0 ? void 0 : queuePopupCont.setAttribute("data-bytm-hidden", "true");
  5103. await UserUtils.pauseFor(15);
  5104. const removeFromQueueBtn = queuePopupCont === null || queuePopupCont === void 0 ? void 0 : queuePopupCont.querySelector("tp-yt-paper-listbox ytmusic-menu-service-item-renderer:nth-of-type(3)");
  5105. removeFromQueueBtn === null || removeFromQueueBtn === void 0 ? void 0 : removeFromQueueBtn.click();
  5106. // queue items aren't removed automatically outside of the current queue
  5107. if (removeFromQueueBtn && listType === "genericList") {
  5108. await UserUtils.pauseFor(200);
  5109. clearInner(queueItem);
  5110. queueItem.remove();
  5111. }
  5112. if (!removeFromQueueBtn) {
  5113. error("Couldn't find 'remove from queue' button in queue item three dots menu.\nPlease make sure all autoplay restrictions on your browser's side are disabled for this page.");
  5114. dotsBtnElem === null || dotsBtnElem === void 0 ? void 0 : dotsBtnElem.click();
  5115. imgElem.src = await getResourceUrl("icon-error");
  5116. if (deleteBtnElem)
  5117. deleteBtnElem.ariaLabel = deleteBtnElem.title = (listType === "currentQueue" ? t("couldnt_remove_from_queue") : t("couldnt_delete_from_list"));
  5118. }
  5119. }
  5120. catch (err) {
  5121. error("Couldn't remove song from queue due to error:", err);
  5122. }
  5123. finally {
  5124. queuePopupCont === null || queuePopupCont === void 0 ? void 0 : queuePopupCont.removeAttribute("data-bytm-hidden");
  5125. }
  5126. });
  5127. deleteBtnElem.appendChild(imgElem);
  5128. }
  5129. lyricsBtnElem && queueBtnsCont.appendChild(createRipple(lyricsBtnElem));
  5130. deleteBtnElem && queueBtnsCont.appendChild(createRipple(deleteBtnElem));
  5131. const parentEl = queueItem.querySelector(containerParentSelector);
  5132. if (insertPosition === "child")
  5133. parentEl === null || parentEl === void 0 ? void 0 : parentEl.appendChild(queueBtnsCont);
  5134. else if (insertPosition === "beforeParent")
  5135. parentEl === null || parentEl === void 0 ? void 0 : parentEl.before(queueBtnsCont);
  5136. else if (insertPosition === "afterParent")
  5137. parentEl === null || parentEl === void 0 ? void 0 : parentEl.after(queueBtnsCont);
  5138. queueItem.classList.add("bytm-has-queue-btns");
  5139. }//#region init vol features
  5140. /** Initializes all volume-related features */
  5141. async function initVolumeFeatures() {
  5142. // not technically an input element but behaves pretty much the same
  5143. addSelectorListener("playerBarRightControls", "tp-yt-paper-slider#volume-slider", {
  5144. listener: async (sliderElem) => {
  5145. const volSliderCont = document.createElement("div");
  5146. volSliderCont.id = "bytm-vol-slider-cont";
  5147. if (getFeature("volumeSliderScrollStep") !== featInfo.volumeSliderScrollStep.default)
  5148. initScrollStep(volSliderCont, sliderElem);
  5149. UserUtils.addParent(sliderElem, volSliderCont);
  5150. if (typeof getFeature("volumeSliderSize") === "number")
  5151. setVolSliderSize();
  5152. if (getFeature("volumeSliderLabel"))
  5153. await addVolumeSliderLabel(sliderElem, volSliderCont);
  5154. setVolSliderStep(sliderElem);
  5155. if (getFeature("volumeSharedBetweenTabs")) {
  5156. sliderElem.addEventListener("change", () => sharedVolumeChanged(Number(sliderElem.value)));
  5157. checkSharedVolume();
  5158. }
  5159. if (getFeature("setInitialTabVolume"))
  5160. setInitialTabVolume(sliderElem);
  5161. },
  5162. });
  5163. }
  5164. //#region scroll step
  5165. /** Initializes the volume slider scroll step features */
  5166. function initScrollStep(volSliderCont, sliderElem) {
  5167. for (const evtName of ["wheel", "scroll", "mousewheel", "DOMMouseScroll"]) {
  5168. volSliderCont.addEventListener(evtName, (e) => {
  5169. var _a, _b;
  5170. e.preventDefault();
  5171. // cancels all the other events that would be fired
  5172. e.stopImmediatePropagation();
  5173. const delta = (_b = (_a = e.deltaY) !== null && _a !== void 0 ? _a : e.detail) !== null && _b !== void 0 ? _b : 1;
  5174. const volumeDir = -Math.sign(delta);
  5175. const newVolume = String(Number(sliderElem.value) + (getFeature("volumeSliderScrollStep") * volumeDir));
  5176. sliderElem.value = newVolume;
  5177. sliderElem.setAttribute("aria-valuenow", newVolume);
  5178. // make the site actually change the volume
  5179. sliderElem.dispatchEvent(new Event("change", { bubbles: true }));
  5180. }, {
  5181. // takes precedence over the slider's own event listener
  5182. capture: true,
  5183. });
  5184. }
  5185. }
  5186. //#region volume slider label
  5187. /** Adds a percentage label to the volume slider and tooltip */
  5188. async function addVolumeSliderLabel(sliderElem, sliderContainer) {
  5189. const labelContElem = document.createElement("div");
  5190. labelContElem.id = "bytm-vol-slider-label";
  5191. const volShared = getFeature("volumeSharedBetweenTabs");
  5192. if (volShared) {
  5193. const linkIconHtml = await resourceAsString("icon-link");
  5194. if (linkIconHtml) {
  5195. const linkIconElem = document.createElement("div");
  5196. linkIconElem.id = "bytm-vol-slider-shared";
  5197. setInnerHtml(linkIconElem, linkIconHtml);
  5198. linkIconElem.role = "alert";
  5199. linkIconElem.ariaLive = "polite";
  5200. linkIconElem.title = linkIconElem.ariaLabel = t("volume_shared_tooltip");
  5201. labelContElem.classList.add("has-icon");
  5202. labelContElem.appendChild(linkIconElem);
  5203. }
  5204. }
  5205. const getLabel = (value) => `${value}%`;
  5206. const labelElem = document.createElement("div");
  5207. labelElem.classList.add("label");
  5208. labelElem.textContent = getLabel(sliderElem.value);
  5209. labelContElem.appendChild(labelElem);
  5210. // prevent video from minimizing
  5211. labelContElem.addEventListener("click", (e) => e.stopPropagation());
  5212. labelContElem.addEventListener("keydown", (e) => ["Enter", "Space", " "].includes(e.key) && e.stopPropagation());
  5213. const getLabelText = (slider) => { var _a; return t("volume_tooltip", slider.value, (_a = getFeature("volumeSliderStep")) !== null && _a !== void 0 ? _a : slider.step); };
  5214. const labelFull = getLabelText(sliderElem);
  5215. sliderContainer.setAttribute("title", labelFull);
  5216. sliderElem.setAttribute("title", labelFull);
  5217. sliderElem.setAttribute("aria-valuetext", labelFull);
  5218. const updateLabel = () => {
  5219. const labelFull = getLabelText(sliderElem);
  5220. sliderContainer.setAttribute("title", labelFull);
  5221. sliderElem.setAttribute("title", labelFull);
  5222. sliderElem.setAttribute("aria-valuetext", labelFull);
  5223. const labelElem2 = document.querySelector("#bytm-vol-slider-label div.label");
  5224. if (labelElem2)
  5225. labelElem2.textContent = getLabel(sliderElem.value);
  5226. };
  5227. sliderElem.addEventListener("change", () => updateLabel());
  5228. siteEvents.on("configChanged", () => {
  5229. updateLabel();
  5230. });
  5231. addSelectorListener("playerBarRightControls", "#bytm-vol-slider-cont", {
  5232. listener: (volumeCont) => volumeCont.appendChild(labelContElem),
  5233. });
  5234. let lastSliderVal = Number(sliderElem.value);
  5235. // show label if hovering over slider or slider is focused
  5236. const sliderHoverObserver = new MutationObserver(() => {
  5237. if (sliderElem.classList.contains("on-hover") || document.activeElement === sliderElem)
  5238. labelContElem.classList.add("bytm-visible");
  5239. else if (labelContElem.classList.contains("bytm-visible") || document.activeElement !== sliderElem)
  5240. labelContElem.classList.remove("bytm-visible");
  5241. if (Number(sliderElem.value) !== lastSliderVal) {
  5242. lastSliderVal = Number(sliderElem.value);
  5243. updateLabel();
  5244. }
  5245. });
  5246. sliderHoverObserver.observe(sliderElem, {
  5247. attributes: true,
  5248. });
  5249. }
  5250. //#region volume slider size
  5251. /** Sets the volume slider to a set size */
  5252. function setVolSliderSize() {
  5253. const size = getFeature("volumeSliderSize");
  5254. if (typeof size !== "number" || isNaN(Number(size)))
  5255. return error("Invalid volume slider size:", size);
  5256. setGlobalCssVar("vol-slider-size", `${size}px`);
  5257. addStyleFromResource("css-vol_slider_size");
  5258. }
  5259. //#region volume slider step
  5260. /** Sets the `step` attribute of the volume slider */
  5261. function setVolSliderStep(sliderElem) {
  5262. sliderElem.setAttribute("step", String(getFeature("volumeSliderStep")));
  5263. }
  5264. //#region shared volume
  5265. /** Saves the shared volume level to persistent storage */
  5266. async function sharedVolumeChanged(vol) {
  5267. try {
  5268. await GM.setValue("bytm-shared-volume", String(lastCheckedSharedVolume = ignoreVal = vol));
  5269. }
  5270. catch (err) {
  5271. error("Couldn't save shared volume level due to an error:", err);
  5272. }
  5273. }
  5274. let ignoreVal = -1;
  5275. let lastCheckedSharedVolume = -1;
  5276. /** Only call once as this calls itself after a timeout! - Checks if the shared volume has changed and updates the volume slider accordingly */
  5277. async function checkSharedVolume() {
  5278. try {
  5279. const vol = await GM.getValue("bytm-shared-volume");
  5280. if (vol && lastCheckedSharedVolume !== Number(vol)) {
  5281. if (ignoreVal === Number(vol))
  5282. return;
  5283. lastCheckedSharedVolume = Number(vol);
  5284. const sliderElem = document.querySelector("tp-yt-paper-slider#volume-slider");
  5285. if (sliderElem) {
  5286. sliderElem.value = String(vol);
  5287. sliderElem.dispatchEvent(new Event("change", { bubbles: true }));
  5288. }
  5289. }
  5290. setTimeout(checkSharedVolume, 333);
  5291. }
  5292. catch (err) {
  5293. error("Couldn't check for shared volume level due to an error:", err);
  5294. }
  5295. }
  5296. //#region initial volume
  5297. /** Sets the volume slider to a set volume level when the session starts */
  5298. async function setInitialTabVolume(sliderElem) {
  5299. await waitVideoElementReady();
  5300. const initialVol = getFeature("initialTabVolumeLevel");
  5301. if (getFeature("volumeSharedBetweenTabs")) {
  5302. lastCheckedSharedVolume = ignoreVal = initialVol;
  5303. if (getFeature("volumeSharedBetweenTabs"))
  5304. GM.setValue("bytm-shared-volume", String(initialVol));
  5305. }
  5306. sliderElem.value = String(initialVol);
  5307. sliderElem.dispatchEvent(new Event("change", { bubbles: true }));
  5308. log(`Set initial tab volume to ${initialVol}%`);
  5309. }/** Decoration elements that can be added next to the label */
  5310. const adornments = {
  5311. advanced: async () => getAdornHtml("bytm-advanced-mode-icon", t("advanced_mode"), "icon-advanced_mode"),
  5312. experimental: async () => getAdornHtml("bytm-experimental-icon", t("experimental_feature"), "icon-experimental"),
  5313. globe: async () => { var _a; return (_a = await resourceAsString("icon-globe_small")) !== null && _a !== void 0 ? _a : ""; },
  5314. alert: async (title) => getAdornHtml("bytm-warning-icon", title, "icon-error", "role=\"alert\""),
  5315. reloadRequired: async () => getFeature("advancedMode") ? getAdornHtml("bytm-reload-icon", t("feature_requires_reload"), "icon-reload") : undefined,
  5316. };
  5317. /** Order of adornment elements in the {@linkcode combineAdornments()} function */
  5318. const adornmentOrder = new Map();
  5319. adornmentOrder.set(adornments.alert, 0);
  5320. adornmentOrder.set(adornments.experimental, 1);
  5321. adornmentOrder.set(adornments.globe, 2);
  5322. adornmentOrder.set(adornments.reloadRequired, 3);
  5323. adornmentOrder.set(adornments.advanced, 4);
  5324. /** Creates an HTML string for the given adornment properties */
  5325. const getAdornHtml = async (className, title, resource, extraParams) => { var _a; return `<span class="${className} bytm-adorn-icon" title="${title}" aria-label="${title}"${extraParams ? " " + extraParams : ""}>${(_a = await resourceAsString(resource)) !== null && _a !== void 0 ? _a : ""}</span>`; };
  5326. /** Combines multiple async functions or promises that resolve with an adornment HTML string into a single string */
  5327. const combineAdornments = (adornments) => new Promise(async (resolve) => {
  5328. const sortedAdornments = adornments.sort((a, b) => {
  5329. const aIndex = adornmentOrder.get(a) ? adornmentOrder.get(a) : -1;
  5330. const bIndex = adornmentOrder.has(b) ? adornmentOrder.get(b) : -1;
  5331. return aIndex - bIndex;
  5332. });
  5333. const html = [];
  5334. for (const adornment of sortedAdornments) {
  5335. const val = typeof adornment === "function"
  5336. ? await adornment()
  5337. : await adornment;
  5338. val && html.push(val);
  5339. }
  5340. resolve(html.join(""));
  5341. });
  5342. /** Common options for config items of type "select" */
  5343. const options = {
  5344. siteSelection: () => [
  5345. { value: "all", label: t("site_selection_both_sites") },
  5346. { value: "yt", label: t("site_selection_only_yt") },
  5347. { value: "ytm", label: t("site_selection_only_ytm") },
  5348. ],
  5349. siteSelectionOrNone: () => [
  5350. { value: "all", label: t("site_selection_both_sites") },
  5351. { value: "yt", label: t("site_selection_only_yt") },
  5352. { value: "ytm", label: t("site_selection_only_ytm") },
  5353. { value: "none", label: t("site_selection_none") },
  5354. ],
  5355. locale: () => Object.entries(langMapping)
  5356. .reduce((a, [locale, { name }]) => {
  5357. return [...a, {
  5358. value: locale,
  5359. label: name,
  5360. }];
  5361. }, [])
  5362. .sort((a, b) => a.label.localeCompare(b.label)),
  5363. colorLightness: () => [
  5364. { value: "darker", label: t("color_lightness_darker") },
  5365. { value: "normal", label: t("color_lightness_normal") },
  5366. { value: "lighter", label: t("color_lightness_lighter") },
  5367. ],
  5368. };
  5369. //#region rendering
  5370. /** Renders a long number with a thousands separator */
  5371. function renderLongNumberValue(val, maximumFractionDigits = 0) {
  5372. return Number(val).toLocaleString(getLocale().replace(/_/g, "-"), {
  5373. style: "decimal",
  5374. maximumFractionDigits,
  5375. });
  5376. }
  5377. //#region features
  5378. /**
  5379. * Contains all possible features with their default values and other configuration.
  5380. *
  5381. * **Required props:**
  5382. * <!-------------------------------------------------------------------------------------------------------------------------------------------------------->
  5383. * | Property | Description |
  5384. * | :------------------- | :------------------------------------------------------------------------------------------------------------------------------- |
  5385. * | `type` | type of the feature configuration element - use autocomplete or check `FeatureTypeProps` in `src/types.ts` |
  5386. * | `category` | category of the feature - use autocomplete or check `FeatureCategory` in `src/types.ts` |
  5387. * | `default` | default value of the feature - type of the value depends on the given `type` |
  5388. * | `enable(value: any)` | (required if reloadRequired = false) - function that will be called when the feature is enabled / initialized for the first time |
  5389. *
  5390. *
  5391. * **Optional props:**
  5392. * <!-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------->
  5393. * | Property | Description |
  5394. * | :------------------------------------------------------------- | :------------------------------------------------------------------------------------------------------------------------------------------------------- |
  5395. * | `disable: (newValue: any) => void` | for type `toggle` only - function that will be called when the feature is disabled - can be a synchronous or asynchronous function |
  5396. * | `change: (key: string, prevValue: any, newValue: any)` => void | for types `number`, `select`, `slider` and `hotkey` only - function that will be called when the value is changed |
  5397. * | `click: () => void` | for type `button` only - function that will be called when the button is clicked |
  5398. * | `helpText: string / () => string` | function that returns an HTML string or the literal string itself that will be the help text for this feature - writing as function is useful for pluralizing or inserting values into the translation at runtime - if not set, translation with key `feature_helptext_featureKey` will be used instead, if available |
  5399. * | `textAdornment: () => string / Promise<string>` | function that returns an HTML string that will be appended to the text in the config menu as an adornment element |
  5400. * | `unit: string / (val: number) => string` | Only if type is `number` or `slider` - The unit text that is displayed next to the input element, i.e. " px" - a leading space need to be added too! |
  5401. * | `min: number` | Only if type is `number` or `slider` - Overwrites the default of the `min` property of the HTML input element |
  5402. * | `max: number` | Only if type is `number` or `slider` - Overwrites the default of the `max` property of the HTML input element |
  5403. * | `step: number` | Only if type is `number` or `slider` - Overwrites the default of the `step` property of the HTML input element |
  5404. * | `options: SelectOption[] / () => SelectOption[]` | Only if type is `select` - function that returns an array of objects with `value` and `label` properties |
  5405. * | `reloadRequired: boolean` | if true (default), the page needs to be reloaded for the changes to take effect - if false, `enable()` needs to be provided |
  5406. * | `advanced: boolean` | if true, the feature will only be shown if the advanced mode feature has been turned on |
  5407. * | `hidden: boolean` | if true, the feature will not be shown in the settings - default is undefined (false) |
  5408. * | `valueHidden: boolean` | If true, the value of the feature will be hidden in the settings and via the plugin interface - default is undefined (false) |
  5409. * | `normalize: (val: any) => any` | Function that will be called to normalize the value before it is saved - useful for trimming strings or other simple operations |
  5410. * | `renderValue: (val: string) => string` | If provided, is used to render the value's label in the config menu |
  5411. *
  5412. * TODO: go through all features and set as many as possible to reloadRequired = false
  5413. */
  5414. const featInfo = {
  5415. //#region cat:layout
  5416. watermarkEnabled: {
  5417. type: "toggle",
  5418. category: "layout",
  5419. default: true,
  5420. textAdornment: adornments.reloadRequired,
  5421. },
  5422. removeShareTrackingParam: {
  5423. type: "toggle",
  5424. category: "layout",
  5425. default: true,
  5426. textAdornment: adornments.reloadRequired,
  5427. },
  5428. removeShareTrackingParamSites: {
  5429. type: "select",
  5430. category: "layout",
  5431. options: options.siteSelection,
  5432. default: "all",
  5433. advanced: true,
  5434. textAdornment: () => combineAdornments([adornments.advanced, adornments.reloadRequired]),
  5435. },
  5436. fixSpacing: {
  5437. type: "toggle",
  5438. category: "layout",
  5439. default: true,
  5440. advanced: true,
  5441. textAdornment: () => combineAdornments([adornments.advanced, adornments.reloadRequired]),
  5442. },
  5443. thumbnailOverlayBehavior: {
  5444. type: "select",
  5445. category: "layout",
  5446. options: () => [
  5447. { value: "songsOnly", label: t("thumbnail_overlay_behavior_songs_only") },
  5448. { value: "videosOnly", label: t("thumbnail_overlay_behavior_videos_only") },
  5449. { value: "always", label: t("thumbnail_overlay_behavior_always") },
  5450. { value: "never", label: t("thumbnail_overlay_behavior_never") },
  5451. ],
  5452. default: "songsOnly",
  5453. reloadRequired: false,
  5454. enable: noop,
  5455. },
  5456. thumbnailOverlayToggleBtnShown: {
  5457. type: "toggle",
  5458. category: "layout",
  5459. default: true,
  5460. textAdornment: adornments.reloadRequired,
  5461. },
  5462. thumbnailOverlayShowIndicator: {
  5463. type: "toggle",
  5464. category: "layout",
  5465. default: true,
  5466. textAdornment: adornments.reloadRequired,
  5467. },
  5468. thumbnailOverlayIndicatorOpacity: {
  5469. type: "slider",
  5470. category: "layout",
  5471. min: 5,
  5472. max: 100,
  5473. step: 5,
  5474. default: 40,
  5475. unit: "%",
  5476. advanced: true,
  5477. textAdornment: () => combineAdornments([adornments.advanced, adornments.reloadRequired]),
  5478. },
  5479. thumbnailOverlayImageFit: {
  5480. type: "select",
  5481. category: "layout",
  5482. options: () => [
  5483. { value: "cover", label: t("thumbnail_overlay_image_fit_crop") },
  5484. { value: "contain", label: t("thumbnail_overlay_image_fit_full") },
  5485. { value: "fill", label: t("thumbnail_overlay_image_fit_stretch") },
  5486. ],
  5487. default: "cover",
  5488. advanced: true,
  5489. textAdornment: () => combineAdornments([adornments.advanced, adornments.reloadRequired]),
  5490. },
  5491. hideCursorOnIdle: {
  5492. type: "toggle",
  5493. category: "layout",
  5494. default: true,
  5495. reloadRequired: false,
  5496. enable: noop,
  5497. },
  5498. hideCursorOnIdleDelay: {
  5499. type: "slider",
  5500. category: "layout",
  5501. min: 0.5,
  5502. max: 10,
  5503. step: 0.25,
  5504. default: 2,
  5505. unit: "s",
  5506. advanced: true,
  5507. textAdornment: adornments.advanced,
  5508. reloadRequired: false,
  5509. enable: noop,
  5510. },
  5511. fixHdrIssues: {
  5512. type: "toggle",
  5513. category: "layout",
  5514. default: true,
  5515. advanced: true,
  5516. textAdornment: () => combineAdornments([adornments.advanced, adornments.reloadRequired]),
  5517. },
  5518. showVotes: {
  5519. type: "toggle",
  5520. category: "layout",
  5521. default: true,
  5522. textAdornment: adornments.reloadRequired,
  5523. },
  5524. showVotesFormat: {
  5525. type: "select",
  5526. category: "layout",
  5527. options: () => [
  5528. { value: "long", label: t("votes_format_full") },
  5529. { value: "short", label: t("votes_format_short") },
  5530. ],
  5531. default: "short",
  5532. reloadRequired: false,
  5533. enable: noop,
  5534. },
  5535. // archived idea for future version
  5536. // (shows a bar under the like/dislike buttons that shows the ratio of likes to dislikes)
  5537. // showVoteRatio: {
  5538. // type: "select",
  5539. // category: "layout",
  5540. // options: () => [
  5541. // { value: "disabled", label: t("vote_ratio_disabled") },
  5542. // { value: "greenRed", label: t("vote_ratio_green_red") },
  5543. // { value: "blueGray", label: t("vote_ratio_blue_gray") },
  5544. // ],
  5545. // default: "disabled",
  5546. // textAdornment: adornments.reloadRequired,
  5547. // },
  5548. //#region cat:volume
  5549. volumeSliderLabel: {
  5550. type: "toggle",
  5551. category: "volume",
  5552. default: true,
  5553. textAdornment: adornments.reloadRequired,
  5554. },
  5555. volumeSliderSize: {
  5556. type: "number",
  5557. category: "volume",
  5558. min: 50,
  5559. max: 500,
  5560. step: 5,
  5561. default: 150,
  5562. unit: "px",
  5563. textAdornment: adornments.reloadRequired,
  5564. },
  5565. volumeSliderStep: {
  5566. type: "slider",
  5567. category: "volume",
  5568. min: 1,
  5569. max: 25,
  5570. default: 2,
  5571. unit: "%",
  5572. textAdornment: adornments.reloadRequired,
  5573. },
  5574. volumeSliderScrollStep: {
  5575. type: "slider",
  5576. category: "volume",
  5577. min: 1,
  5578. max: 25,
  5579. default: 4,
  5580. unit: "%",
  5581. textAdornment: adornments.reloadRequired,
  5582. },
  5583. volumeSharedBetweenTabs: {
  5584. type: "toggle",
  5585. category: "volume",
  5586. default: false,
  5587. textAdornment: adornments.reloadRequired,
  5588. },
  5589. setInitialTabVolume: {
  5590. type: "toggle",
  5591. category: "volume",
  5592. default: false,
  5593. textAdornment: () => getFeature("volumeSharedBetweenTabs")
  5594. ? combineAdornments([adornments.alert(t("feature_warning_setInitialTabVolume_volumeSharedBetweenTabs_incompatible").replace(/"/g, "'")), adornments.reloadRequired])
  5595. : adornments.reloadRequired(),
  5596. },
  5597. initialTabVolumeLevel: {
  5598. type: "slider",
  5599. category: "volume",
  5600. min: 0,
  5601. max: 100,
  5602. step: 1,
  5603. default: 100,
  5604. unit: "%",
  5605. textAdornment: () => getFeature("volumeSharedBetweenTabs")
  5606. ? combineAdornments([adornments.alert(t("feature_warning_setInitialTabVolume_volumeSharedBetweenTabs_incompatible").replace(/"/g, "'")), adornments.reloadRequired])
  5607. : adornments.reloadRequired(),
  5608. reloadRequired: false,
  5609. enable: noop,
  5610. },
  5611. //#region cat:song lists
  5612. lyricsQueueButton: {
  5613. type: "toggle",
  5614. category: "songLists",
  5615. default: true,
  5616. textAdornment: adornments.reloadRequired,
  5617. },
  5618. deleteFromQueueButton: {
  5619. type: "toggle",
  5620. category: "songLists",
  5621. default: true,
  5622. textAdornment: adornments.reloadRequired,
  5623. },
  5624. listButtonsPlacement: {
  5625. type: "select",
  5626. category: "songLists",
  5627. options: () => [
  5628. { value: "queueOnly", label: t("list_button_placement_queue_only") },
  5629. { value: "everywhere", label: t("list_button_placement_everywhere") },
  5630. ],
  5631. default: "everywhere",
  5632. advanced: true,
  5633. textAdornment: () => combineAdornments([adornments.advanced, adornments.reloadRequired]),
  5634. },
  5635. scrollToActiveSongBtn: {
  5636. type: "toggle",
  5637. category: "songLists",
  5638. default: true,
  5639. textAdornment: adornments.reloadRequired,
  5640. },
  5641. clearQueueBtn: {
  5642. type: "toggle",
  5643. category: "songLists",
  5644. default: true,
  5645. textAdornment: adornments.reloadRequired,
  5646. },
  5647. //#region cat:behavior
  5648. disableBeforeUnloadPopup: {
  5649. type: "toggle",
  5650. category: "behavior",
  5651. default: false,
  5652. textAdornment: adornments.reloadRequired,
  5653. },
  5654. closeToastsTimeout: {
  5655. type: "number",
  5656. category: "behavior",
  5657. min: 0,
  5658. max: 30,
  5659. step: 0.5,
  5660. default: 3,
  5661. unit: "s",
  5662. reloadRequired: false,
  5663. enable: noop,
  5664. },
  5665. rememberSongTime: {
  5666. type: "toggle",
  5667. category: "behavior",
  5668. default: true,
  5669. helpText: () => tp("feature_helptext_rememberSongTime", getFeature("rememberSongTimeMinPlayTime"), getFeature("rememberSongTimeMinPlayTime")),
  5670. textAdornment: adornments.reloadRequired,
  5671. },
  5672. rememberSongTimeSites: {
  5673. type: "select",
  5674. category: "behavior",
  5675. options: options.siteSelection,
  5676. default: "all",
  5677. textAdornment: adornments.reloadRequired,
  5678. },
  5679. rememberSongTimeDuration: {
  5680. type: "number",
  5681. category: "behavior",
  5682. min: 1,
  5683. max: 60 * 60 * 24 * 7,
  5684. step: 1,
  5685. default: 60,
  5686. unit: "s",
  5687. advanced: true,
  5688. textAdornment: adornments.advanced,
  5689. reloadRequired: false,
  5690. enable: noop,
  5691. },
  5692. rememberSongTimeReduction: {
  5693. type: "number",
  5694. category: "behavior",
  5695. min: 0,
  5696. max: 30,
  5697. step: 0.05,
  5698. default: 0.2,
  5699. unit: "s",
  5700. advanced: true,
  5701. textAdornment: adornments.advanced,
  5702. reloadRequired: false,
  5703. enable: noop,
  5704. },
  5705. rememberSongTimeMinPlayTime: {
  5706. type: "slider",
  5707. category: "behavior",
  5708. min: 3,
  5709. max: 30,
  5710. step: 0.5,
  5711. default: 10,
  5712. unit: "s",
  5713. advanced: true,
  5714. textAdornment: adornments.advanced,
  5715. reloadRequired: false,
  5716. enable: noop,
  5717. },
  5718. //#region cat:input
  5719. arrowKeySupport: {
  5720. type: "toggle",
  5721. category: "input",
  5722. default: true,
  5723. reloadRequired: false,
  5724. enable: noop,
  5725. },
  5726. arrowKeySkipBy: {
  5727. type: "number",
  5728. category: "input",
  5729. min: 0.5,
  5730. max: 60,
  5731. step: 0.5,
  5732. default: 5,
  5733. reloadRequired: false,
  5734. enable: noop,
  5735. },
  5736. switchBetweenSites: {
  5737. type: "toggle",
  5738. category: "input",
  5739. default: true,
  5740. reloadRequired: false,
  5741. enable: noop,
  5742. },
  5743. switchSitesHotkey: {
  5744. type: "hotkey",
  5745. category: "input",
  5746. default: {
  5747. code: "F9",
  5748. shift: false,
  5749. ctrl: false,
  5750. alt: false,
  5751. },
  5752. reloadRequired: false,
  5753. enable: noop,
  5754. },
  5755. anchorImprovements: {
  5756. type: "toggle",
  5757. category: "input",
  5758. default: true,
  5759. textAdornment: adornments.reloadRequired,
  5760. },
  5761. numKeysSkipToTime: {
  5762. type: "toggle",
  5763. category: "input",
  5764. default: true,
  5765. reloadRequired: false,
  5766. enable: noop,
  5767. },
  5768. autoLikeChannels: {
  5769. type: "toggle",
  5770. category: "input",
  5771. default: false,
  5772. advanced: true,
  5773. textAdornment: () => combineAdornments([adornments.advanced, adornments.reloadRequired]),
  5774. },
  5775. autoLikeChannelToggleBtn: {
  5776. type: "toggle",
  5777. category: "input",
  5778. default: true,
  5779. reloadRequired: false,
  5780. enable: noop,
  5781. advanced: true,
  5782. textAdornment: adornments.advanced,
  5783. },
  5784. // TODO(v2.2):
  5785. // autoLikePlayerBarToggleBtn: {
  5786. // type: "toggle",
  5787. // category: "input",
  5788. // default: false,
  5789. // textAdornment: adornments.reloadRequired,
  5790. // },
  5791. autoLikeTimeout: {
  5792. type: "slider",
  5793. category: "input",
  5794. min: 3,
  5795. max: 30,
  5796. step: 0.5,
  5797. default: 5,
  5798. unit: "s",
  5799. advanced: true,
  5800. reloadRequired: false,
  5801. enable: noop,
  5802. textAdornment: adornments.advanced,
  5803. },
  5804. autoLikeShowToast: {
  5805. type: "toggle",
  5806. category: "input",
  5807. default: true,
  5808. reloadRequired: false,
  5809. advanced: true,
  5810. enable: noop,
  5811. textAdornment: adornments.advanced,
  5812. },
  5813. autoLikeOpenMgmtDialog: {
  5814. type: "button",
  5815. category: "input",
  5816. click: () => getAutoLikeDialog().then(d => d.open()),
  5817. },
  5818. //#region cat:lyrics
  5819. geniusLyrics: {
  5820. type: "toggle",
  5821. category: "lyrics",
  5822. default: true,
  5823. },
  5824. geniUrlBase: {
  5825. type: "text",
  5826. category: "lyrics",
  5827. default: "https://api.sv443.net/geniurl",
  5828. normalize: (val) => val.trim().replace(/\/+$/, ""),
  5829. advanced: true,
  5830. textAdornment: adornments.advanced,
  5831. reloadRequired: false,
  5832. enable: noop,
  5833. },
  5834. geniUrlToken: {
  5835. type: "text",
  5836. valueHidden: true,
  5837. category: "lyrics",
  5838. default: "",
  5839. normalize: (val) => val.trim(),
  5840. advanced: true,
  5841. textAdornment: adornments.advanced,
  5842. reloadRequired: false,
  5843. enable: noop,
  5844. },
  5845. lyricsCacheMaxSize: {
  5846. type: "slider",
  5847. category: "lyrics",
  5848. default: 2000,
  5849. min: 100,
  5850. max: 10000,
  5851. step: 100,
  5852. unit: (val) => ` ${tp("unit_entries", val)}`,
  5853. renderValue: renderLongNumberValue,
  5854. advanced: true,
  5855. textAdornment: adornments.advanced,
  5856. reloadRequired: false,
  5857. enable: noop,
  5858. },
  5859. lyricsCacheTTL: {
  5860. type: "slider",
  5861. category: "lyrics",
  5862. default: 21,
  5863. min: 1,
  5864. max: 100,
  5865. step: 1,
  5866. unit: (val) => " " + tp("unit_days", val),
  5867. advanced: true,
  5868. textAdornment: adornments.advanced,
  5869. reloadRequired: false,
  5870. enable: noop,
  5871. },
  5872. clearLyricsCache: {
  5873. type: "button",
  5874. category: "lyrics",
  5875. async click() {
  5876. const entries = getLyricsCache().length;
  5877. if (confirm(tp("lyrics_clear_cache_confirm_prompt", entries, entries))) {
  5878. await clearLyricsCache();
  5879. alert(t("lyrics_clear_cache_success"));
  5880. }
  5881. },
  5882. advanced: true,
  5883. textAdornment: adornments.advanced,
  5884. },
  5885. // advancedLyricsFilter: {
  5886. // type: "toggle",
  5887. // category: "lyrics",
  5888. // default: false,
  5889. // change: () => setTimeout(() => confirm(t("lyrics_cache_changed_clear_confirm")) && clearLyricsCache(), 200),
  5890. // advanced: true,
  5891. // textAdornment: adornments.experimental,
  5892. // reloadRequired: false,
  5893. // enable: noop,
  5894. // },
  5895. //#region cat:integrations
  5896. disableDarkReaderSites: {
  5897. type: "select",
  5898. category: "integrations",
  5899. options: options.siteSelectionOrNone,
  5900. default: "all",
  5901. advanced: true,
  5902. textAdornment: () => combineAdornments([adornments.advanced, adornments.reloadRequired]),
  5903. },
  5904. sponsorBlockIntegration: {
  5905. type: "toggle",
  5906. category: "integrations",
  5907. default: true,
  5908. textAdornment: adornments.reloadRequired,
  5909. },
  5910. themeSongIntegration: {
  5911. type: "toggle",
  5912. category: "integrations",
  5913. default: false,
  5914. textAdornment: adornments.reloadRequired,
  5915. },
  5916. themeSongLightness: {
  5917. type: "select",
  5918. category: "integrations",
  5919. options: options.colorLightness,
  5920. default: "darker",
  5921. textAdornment: adornments.reloadRequired,
  5922. },
  5923. //#region cat:general
  5924. locale: {
  5925. type: "select",
  5926. category: "general",
  5927. options: options.locale,
  5928. default: getPreferredLocale(),
  5929. textAdornment: () => combineAdornments([adornments.globe, adornments.reloadRequired]),
  5930. },
  5931. localeFallback: {
  5932. type: "toggle",
  5933. category: "general",
  5934. default: true,
  5935. advanced: true,
  5936. textAdornment: () => combineAdornments([adornments.advanced, adornments.reloadRequired]),
  5937. },
  5938. versionCheck: {
  5939. type: "toggle",
  5940. category: "general",
  5941. default: true,
  5942. textAdornment: adornments.reloadRequired,
  5943. },
  5944. checkVersionNow: {
  5945. type: "button",
  5946. category: "general",
  5947. click: () => doVersionCheck(true),
  5948. },
  5949. logLevel: {
  5950. type: "select",
  5951. category: "general",
  5952. options: () => [
  5953. { value: 0, label: t("log_level_debug") },
  5954. { value: 1, label: t("log_level_info") },
  5955. ],
  5956. default: 1,
  5957. textAdornment: adornments.reloadRequired,
  5958. },
  5959. initTimeout: {
  5960. type: "number",
  5961. category: "general",
  5962. min: 3,
  5963. max: 30,
  5964. default: 8,
  5965. step: 0.1,
  5966. unit: "s",
  5967. advanced: true,
  5968. textAdornment: () => combineAdornments([adornments.advanced, adornments.reloadRequired]),
  5969. },
  5970. toastDuration: {
  5971. type: "slider",
  5972. category: "general",
  5973. min: 0,
  5974. max: 15,
  5975. default: 4,
  5976. step: 0.5,
  5977. unit: "s",
  5978. reloadRequired: false,
  5979. advanced: true,
  5980. textAdornment: adornments.advanced,
  5981. enable: noop,
  5982. change: () => showIconToast({
  5983. message: t("example_toast"),
  5984. iconSrc: getResourceUrl(`img-logo${mode === "development" ? "_dev" : ""}`),
  5985. }),
  5986. },
  5987. showToastOnGenericError: {
  5988. type: "toggle",
  5989. category: "general",
  5990. default: true,
  5991. advanced: true,
  5992. textAdornment: () => combineAdornments([adornments.advanced, adornments.reloadRequired]),
  5993. },
  5994. resetConfig: {
  5995. type: "button",
  5996. category: "general",
  5997. click: promptResetConfig,
  5998. textAdornment: adornments.reloadRequired,
  5999. },
  6000. advancedMode: {
  6001. type: "toggle",
  6002. category: "general",
  6003. default: false,
  6004. textAdornment: () => getFeature("advancedMode") ? adornments.advanced() : undefined,
  6005. change: (_key, prevValue, newValue) => prevValue !== newValue &&
  6006. emitSiteEvent("recreateCfgMenu"),
  6007. },
  6008. };
  6009. function noop() {
  6010. }/** If this number is incremented, the features object data will be migrated to the new format */
  6011. const formatVersion = 7;
  6012. const defaultData = Object.keys(featInfo)
  6013. // @ts-ignore
  6014. .filter((ftKey) => { var _a; return ((_a = featInfo === null || featInfo === void 0 ? void 0 : featInfo[ftKey]) === null || _a === void 0 ? void 0 : _a.default) !== undefined; })
  6015. .reduce((acc, key) => {
  6016. var _a;
  6017. // @ts-ignore
  6018. acc[key] = (_a = featInfo === null || featInfo === void 0 ? void 0 : featInfo[key]) === null || _a === void 0 ? void 0 : _a.default;
  6019. return acc;
  6020. }, {});
  6021. /** Config data format migration dictionary */
  6022. const migrations = {
  6023. // 1 -> 2 (<=v1.0)
  6024. 2: (oldData) => {
  6025. const queueBtnsEnabled = Boolean(oldData.queueButtons);
  6026. delete oldData.queueButtons;
  6027. return Object.assign(Object.assign({}, oldData), { deleteFromQueueButton: queueBtnsEnabled, lyricsQueueButton: queueBtnsEnabled });
  6028. },
  6029. // 2 -> 3 (v1.0)
  6030. 3: (oldData) => useDefaultConfig(oldData, [
  6031. "removeShareTrackingParam", "numKeysSkipToTime",
  6032. "fixSpacing", "scrollToActiveSongBtn", "logLevel",
  6033. ]),
  6034. // 3 -> 4 (v1.1)
  6035. 4: (oldData) => {
  6036. var _a, _b, _c, _d;
  6037. const oldSwitchSitesHotkey = oldData.switchSitesHotkey;
  6038. return Object.assign(Object.assign({}, useDefaultConfig(oldData, [
  6039. "rememberSongTime", "rememberSongTimeSites",
  6040. "volumeSliderScrollStep", "locale", "versionCheck",
  6041. ])), { arrowKeySkipBy: 10, switchSitesHotkey: {
  6042. code: (_a = oldSwitchSitesHotkey.key) !== null && _a !== void 0 ? _a : "F9",
  6043. shift: Boolean((_b = oldSwitchSitesHotkey.shift) !== null && _b !== void 0 ? _b : false),
  6044. ctrl: Boolean((_c = oldSwitchSitesHotkey.ctrl) !== null && _c !== void 0 ? _c : false),
  6045. alt: Boolean((_d = oldSwitchSitesHotkey.meta) !== null && _d !== void 0 ? _d : false),
  6046. }, listButtonsPlacement: "queueOnly" });
  6047. },
  6048. // 4 -> 5 (v2.0)
  6049. 5: (oldData) => useDefaultConfig(oldData, [
  6050. "localeFallback", "geniUrlBase", "geniUrlToken",
  6051. "lyricsCacheMaxSize", "lyricsCacheTTL",
  6052. "clearLyricsCache", "advancedMode",
  6053. "checkVersionNow", "advancedLyricsFilter",
  6054. "rememberSongTimeDuration", "rememberSongTimeReduction",
  6055. "rememberSongTimeMinPlayTime", "volumeSharedBetweenTabs",
  6056. "setInitialTabVolume", "initialTabVolumeLevel",
  6057. "thumbnailOverlayBehavior", "thumbnailOverlayToggleBtnShown",
  6058. "thumbnailOverlayShowIndicator", "thumbnailOverlayIndicatorOpacity",
  6059. "thumbnailOverlayImageFit", "removeShareTrackingParamSites",
  6060. "fixHdrIssues", "clearQueueBtn",
  6061. "closeToastsTimeout", "disableDarkReaderSites",
  6062. ]),
  6063. // 5 -> 6 (v2.1)
  6064. 6: (oldData) => {
  6065. const newData = useNewDefaultIfUnchanged(useDefaultConfig(oldData, [
  6066. "autoLikeChannels", "autoLikeChannelToggleBtn",
  6067. "autoLikeTimeout", "autoLikeShowToast",
  6068. "autoLikeOpenMgmtDialog", "showVotes",
  6069. "showVotesFormat", "toastDuration",
  6070. "initTimeout",
  6071. // forgot to add this to the migration when adding the feature way before so now will have to do:
  6072. "volumeSliderLabel",
  6073. ]), [
  6074. { key: "rememberSongTimeSites", oldDefault: "ytm" },
  6075. { key: "volumeSliderScrollStep", oldDefault: 10 },
  6076. ]);
  6077. "removeUpgradeTab" in newData && delete newData.removeUpgradeTab;
  6078. "advancedLyricsFilter" in newData && delete newData.advancedLyricsFilter;
  6079. return newData;
  6080. },
  6081. // TODO(v2.2): use default for "autoLikePlayerBarToggleBtn"
  6082. // TODO(v2.2): set autoLikeChannels to true on migration once feature is fully implemented
  6083. // 6 -> 7 (v2.2)
  6084. 7: (oldData) => useNewDefaultIfUnchanged(useDefaultConfig(oldData, [
  6085. "showToastOnGenericError", "sponsorBlockIntegration",
  6086. "themeSongIntegration", "themeSongLightness",
  6087. ]), [
  6088. { key: "toastDuration", oldDefault: 3 },
  6089. ]),
  6090. };
  6091. /** Uses the default config as the base, then overwrites all values with the passed {@linkcode baseData}, then sets all passed {@linkcode resetKeys} to their default values */
  6092. function useDefaultConfig(baseData, resetKeys) {
  6093. var _a;
  6094. const newData = Object.assign(Object.assign({}, defaultData), (baseData !== null && baseData !== void 0 ? baseData : {}));
  6095. for (const key of resetKeys) // @ts-ignore
  6096. newData[key] = (_a = featInfo === null || featInfo === void 0 ? void 0 : featInfo[key]) === null || _a === void 0 ? void 0 : _a.default; // typescript funny moments
  6097. return newData;
  6098. }
  6099. /**
  6100. * Uses {@linkcode oldData} as the base, then sets all keys provided in {@linkcode defaults} to their old default values, as long as their current value is equal to the provided old default.
  6101. * This essentially means if someone has changed a feature's value from its old default value, that decision will be respected. Only if it has been left on its old default value, it will be reset to the new default value.
  6102. * Returns a copy of the object.
  6103. */
  6104. function useNewDefaultIfUnchanged(oldData, defaults) {
  6105. var _a;
  6106. const newData = Object.assign({}, oldData);
  6107. for (const { key, oldDefault } of defaults) {
  6108. // @ts-ignore
  6109. const defaultVal = (_a = featInfo === null || featInfo === void 0 ? void 0 : featInfo[key]) === null || _a === void 0 ? void 0 : _a.default;
  6110. if (newData[key] === oldDefault)
  6111. newData[key] = defaultVal; // we love TS
  6112. }
  6113. return newData;
  6114. }
  6115. let canCompress = true;
  6116. const configStore = new UserUtils.DataStore({
  6117. id: "bytm-config",
  6118. formatVersion,
  6119. defaultData,
  6120. migrations,
  6121. encodeData: (data) => canCompress ? UserUtils.compress(data, compressionFormat, "string") : data,
  6122. decodeData: (data) => canCompress ? UserUtils.decompress(data, compressionFormat, "string") : data,
  6123. });
  6124. /** Initializes the DataStore instance and loads persistent data into memory. Returns a copy of the config object. */
  6125. async function initConfig() {
  6126. canCompress = await compressionSupported();
  6127. const oldFmtVer = Number(await GM.getValue(`_uucfgver-${configStore.id}`, NaN));
  6128. let data = await configStore.loadData();
  6129. // since the config changes so much in development keys need to be fixed in this special way
  6130. if (mode === "development") {
  6131. await configStore.setData(fixCfgKeys(data));
  6132. data = configStore.getData();
  6133. }
  6134. log(`Initialized feature config DataStore with version ${configStore.formatVersion}`);
  6135. if (isNaN(oldFmtVer))
  6136. info(" !- Config data was initialized with default values");
  6137. else if (oldFmtVer !== configStore.formatVersion) {
  6138. try {
  6139. await configStore.setData(data = fixCfgKeys(data));
  6140. info(` !- Config data was migrated from version ${oldFmtVer} to ${configStore.formatVersion}`);
  6141. }
  6142. catch (err) {
  6143. error(" !- Config data migration failed, falling back to default data:", err);
  6144. await configStore.setData(data = configStore.defaultData);
  6145. }
  6146. }
  6147. emitInterface("bytm:configReady");
  6148. return Object.assign({}, data);
  6149. }
  6150. /**
  6151. * Fixes missing keys in the passed config object with their default values or removes extraneous keys and returns a copy of the fixed object.
  6152. * Returns a copy of the originally passed object if nothing needs to be fixed.
  6153. */
  6154. function fixCfgKeys(cfg) {
  6155. const newCfg = Object.assign({}, cfg);
  6156. const passedKeys = Object.keys(cfg);
  6157. const defaultKeys = Object.keys(defaultData);
  6158. const missingKeys = defaultKeys.filter(k => !passedKeys.includes(k));
  6159. if (missingKeys.length > 0) {
  6160. for (const key of missingKeys)
  6161. newCfg[key] = defaultData[key];
  6162. }
  6163. const extraKeys = passedKeys.filter(k => !defaultKeys.includes(k));
  6164. if (extraKeys.length > 0) {
  6165. for (const key of extraKeys)
  6166. delete newCfg[key];
  6167. }
  6168. return newCfg;
  6169. }
  6170. /** Returns the current feature config from the in-memory cache as a copy */
  6171. function getFeatures() {
  6172. return configStore.getData();
  6173. }
  6174. /** Returns the value of the feature with the given key from the in-memory cache, as a copy */
  6175. function getFeature(key) {
  6176. return configStore.getData()[key];
  6177. }
  6178. /** Saves the feature config synchronously to the in-memory cache and asynchronously to the persistent storage */
  6179. function setFeatures(featureConf) {
  6180. const res = configStore.setData(featureConf);
  6181. emitSiteEvent("configChanged", configStore.getData());
  6182. info("Saved new feature config:", featureConf);
  6183. return res;
  6184. }
  6185. /** Saves the default feature config synchronously to the in-memory cache and asynchronously to persistent storage */
  6186. function setDefaultFeatures() {
  6187. const res = configStore.saveDefaultData();
  6188. emitSiteEvent("configChanged", configStore.getData());
  6189. info("Reset feature config to its default values");
  6190. return res;
  6191. }
  6192. async function promptResetConfig() {
  6193. if (confirm(t("reset_config_confirm"))) {
  6194. closeCfgMenu();
  6195. disableBeforeUnload();
  6196. await setDefaultFeatures();
  6197. if (location.pathname.startsWith("/watch")) {
  6198. const videoTime = await getVideoTime(0);
  6199. const url = new URL(location.href);
  6200. url.searchParams.delete("t");
  6201. if (videoTime)
  6202. url.searchParams.set("time_continue", String(videoTime));
  6203. location.replace(url.href);
  6204. }
  6205. else
  6206. location.reload();
  6207. }
  6208. }
  6209. /** Clears the feature config from the persistent storage - since the cache will be out of whack, this should only be run before a site re-/unload */
  6210. async function clearConfig() {
  6211. await configStore.deleteData();
  6212. info("Deleted config from persistent storage");
  6213. }const { getUnsafeWindow, randomId, NanoEmitter } = UserUtils__namespace;
  6214. /**
  6215. * All functions that can be called on the BYTM interface using `unsafeWindow.BYTM.functionName();` (or `const { functionName } = unsafeWindow.BYTM;`)
  6216. * If prefixed with /**\/, the function is authenticated and requires a token to be passed as the first argument.
  6217. */
  6218. const globalFuncs = {
  6219. // meta:
  6220. registerPlugin,
  6221. /**/ getPluginInfo,
  6222. // bytm-specific:
  6223. getDomain,
  6224. getResourceUrl,
  6225. getSessionId,
  6226. // dom:
  6227. setInnerHtml,
  6228. addSelectorListener,
  6229. onInteraction,
  6230. getVideoTime,
  6231. getThumbnailUrl,
  6232. getBestThumbnailUrl,
  6233. waitVideoElementReady,
  6234. getCurrentMediaType,
  6235. // translations:
  6236. /**/ setLocale: setLocaleInterface,
  6237. getLocale,
  6238. hasKey,
  6239. hasKeyFor,
  6240. t,
  6241. tp,
  6242. // feature config:
  6243. /**/ getFeatures: getFeaturesInterface,
  6244. /**/ saveFeatures: saveFeaturesInterface,
  6245. // lyrics:
  6246. fetchLyricsUrlTop,
  6247. getLyricsCacheEntry,
  6248. sanitizeArtists,
  6249. sanitizeSong,
  6250. // auto-like:
  6251. /**/ getAutoLikeData: getAutoLikeDataInterface,
  6252. /**/ saveAutoLikeData: saveAutoLikeDataInterface,
  6253. fetchVideoVotes,
  6254. // components:
  6255. createHotkeyInput,
  6256. createToggleInput,
  6257. createCircularBtn,
  6258. createRipple,
  6259. showToast,
  6260. showIconToast,
  6261. };
  6262. /** Initializes the BYTM interface */
  6263. function initInterface() {
  6264. const props = Object.assign(Object.assign(Object.assign({
  6265. // meta / constants
  6266. mode,
  6267. branch,
  6268. host,
  6269. buildNumber,
  6270. compressionFormat }, scriptInfo), globalFuncs), {
  6271. // classes
  6272. NanoEmitter,
  6273. BytmDialog,
  6274. ExImDialog,
  6275. MarkdownDialog,
  6276. // libraries
  6277. UserUtils: UserUtils__namespace,
  6278. compareVersions: compareVersions__namespace });
  6279. for (const [key, value] of Object.entries(props))
  6280. setGlobalProp(key, value);
  6281. log("Initialized BYTM interface");
  6282. }
  6283. /** Sets a global property on the unsafeWindow.BYTM object - ⚠️ use with caution as these props can be accessed by any script on the page! */
  6284. function setGlobalProp(key, value) {
  6285. // use unsafeWindow so the properties are available to plugins outside of the userscript's scope
  6286. const win = getUnsafeWindow();
  6287. if (typeof win.BYTM !== "object")
  6288. win.BYTM = {};
  6289. win.BYTM[key] = value;
  6290. }
  6291. /** Emits an event on the BYTM interface */
  6292. function emitInterface(type, ...detail) {
  6293. var _a;
  6294. try {
  6295. getUnsafeWindow().dispatchEvent(new CustomEvent(type, { detail: (_a = detail === null || detail === void 0 ? void 0 : detail[0]) !== null && _a !== void 0 ? _a : undefined }));
  6296. //@ts-ignore
  6297. emitOnPlugins(type, undefined, ...detail);
  6298. log(`Emitted interface event '${type}'${detail.length > 0 && (detail === null || detail === void 0 ? void 0 : detail[0]) ? " with data:" : ""}`, ...detail);
  6299. }
  6300. catch (err) {
  6301. error(`Couldn't emit interface event '${type}' due to an error:\n`, err);
  6302. }
  6303. }
  6304. //#region register plugins
  6305. /** Map of plugin ID and plugins that are queued up for registration */
  6306. const queuedPlugins = new Map();
  6307. /** Map of plugin ID and all registered plugins */
  6308. const registeredPlugins = new Map();
  6309. /** Map of plugin ID to auth token for plugins that have been registered */
  6310. const registeredPluginTokens = new Map();
  6311. /** Initializes plugins that have been registered already. Needs to be run after `bytm:ready`! */
  6312. function initPlugins() {
  6313. // TODO(v1.3): check perms and ask user for initial activation
  6314. for (const [key, { def, events }] of queuedPlugins) {
  6315. try {
  6316. registeredPlugins.set(key, { def, events });
  6317. queuedPlugins.delete(key);
  6318. emitOnPlugins("pluginRegistered", (d) => sameDef(d, def), pluginDefToInfo(def));
  6319. info(`Initialized plugin '${getPluginKey(def)}'`, LogLevel.Info);
  6320. }
  6321. catch (err) {
  6322. error(`Failed to initialize plugin '${getPluginKey(def)}':`, err);
  6323. }
  6324. }
  6325. emitInterface("bytm:pluginsRegistered");
  6326. }
  6327. /** Returns the key for a given plugin definition */
  6328. function getPluginKey(plugin) {
  6329. return `${plugin.plugin.namespace}/${plugin.plugin.name}`;
  6330. }
  6331. /** Converts a PluginDef object (full definition) into a PluginInfo object (restricted definition) or undefined, if undefined is passed */
  6332. function pluginDefToInfo(plugin) {
  6333. return plugin
  6334. ? {
  6335. name: plugin.plugin.name,
  6336. namespace: plugin.plugin.namespace,
  6337. version: plugin.plugin.version,
  6338. }
  6339. : undefined;
  6340. }
  6341. /** Checks whether two plugins are the same, given their resolvable definition objects */
  6342. function sameDef(def1, def2) {
  6343. return getPluginKey(def1) === getPluginKey(def2);
  6344. }
  6345. /** Emits an event on all plugins that match the predicate (all plugins by default) */
  6346. function emitOnPlugins(event, predicate = true, ...data) {
  6347. for (const { def, events } of registeredPlugins.values())
  6348. if (typeof predicate === "boolean" ? predicate : predicate(def))
  6349. events.emit(event, ...data);
  6350. }
  6351. /**
  6352. * Returns info about a registered plugin on the BYTM interface, or undefined if the plugin isn't registered.
  6353. * This is an authenticated function so you must pass the session- and plugin-unique token, retreived at registration.
  6354. * @public Intended for general use in plugins.
  6355. */
  6356. function getPluginInfo(...args) {
  6357. var _a;
  6358. if (resolveToken(args[0]) === undefined)
  6359. return undefined;
  6360. return pluginDefToInfo((_a = registeredPlugins.get(typeof args[1] === "string" && typeof args[2] === "undefined"
  6361. ? args[1]
  6362. : args.length === 2
  6363. ? `${args[2]}/${args[1]}`
  6364. : getPluginKey(args[1]))) === null || _a === void 0 ? void 0 : _a.def);
  6365. }
  6366. /** Validates the passed PluginDef object and returns an array of errors - returns undefined if there were no errors - never returns an empty array */
  6367. function validatePluginDef(pluginDef) {
  6368. const errors = [];
  6369. const addNoPropErr = (jsonPath, type) => errors.push(t("plugin_validation_error_no_property", jsonPath, type));
  6370. const addInvalidPropErr = (jsonPath, value, examples) => errors.push(tp("plugin_validation_error_invalid_property", examples, jsonPath, value, `'${examples.join("', '")}'`));
  6371. // def.plugin and its properties:
  6372. typeof pluginDef.plugin !== "object" && addNoPropErr("plugin", "object");
  6373. const { plugin } = pluginDef;
  6374. !(plugin === null || plugin === void 0 ? void 0 : plugin.name) && addNoPropErr("plugin.name", "string");
  6375. !(plugin === null || plugin === void 0 ? void 0 : plugin.namespace) && addNoPropErr("plugin.namespace", "string");
  6376. if (typeof (plugin === null || plugin === void 0 ? void 0 : plugin.version) !== "string")
  6377. addNoPropErr("plugin.version", "MAJOR.MINOR.PATCH");
  6378. else if (!compareVersions__namespace.validateStrict(plugin.version))
  6379. addInvalidPropErr("plugin.version", plugin.version, ["0.0.1", "2.5.21-rc.1"]);
  6380. return errors.length > 0 ? errors : undefined;
  6381. }
  6382. /** Registers a plugin on the BYTM interface */
  6383. function registerPlugin(def) {
  6384. var _a, _b;
  6385. const validationErrors = validatePluginDef(def);
  6386. if (validationErrors)
  6387. throw new Error(`Failed to register plugin${((_a = def === null || def === void 0 ? void 0 : def.plugin) === null || _a === void 0 ? void 0 : _a.name) ? ` '${(_b = def === null || def === void 0 ? void 0 : def.plugin) === null || _b === void 0 ? void 0 : _b.name}'` : ""} with invalid definition:\n- ${validationErrors.join("\n- ")}`);
  6388. const events = new NanoEmitter({ publicEmit: true });
  6389. const token = randomId(32, 36);
  6390. const { plugin: { name } } = def;
  6391. queuedPlugins.set(getPluginKey(def), {
  6392. def: def,
  6393. events,
  6394. });
  6395. registeredPluginTokens.set(getPluginKey(def), token);
  6396. info(`Registered plugin: ${name}`, LogLevel.Info);
  6397. return {
  6398. info: getPluginInfo(token, def),
  6399. events,
  6400. token,
  6401. };
  6402. }
  6403. /** Checks whether the passed token is a valid auth token for any registered plugin and returns the plugin ID, else returns undefined */
  6404. function resolveToken(token) {
  6405. var _a, _b;
  6406. return typeof token === "string" && token.length > 0
  6407. ? (_b = (_a = [...registeredPluginTokens.entries()]
  6408. .find(([k, t]) => registeredPlugins.has(k) && token === t)) === null || _a === void 0 ? void 0 : _a[0]) !== null && _b !== void 0 ? _b : undefined
  6409. : undefined;
  6410. }
  6411. //#region proxy funcs
  6412. /**
  6413. * Sets the new locale on the BYTM interface
  6414. * This is an authenticated function so you must pass the session- and plugin-unique token, retreived at registration.
  6415. */
  6416. function setLocaleInterface(token, locale) {
  6417. const pluginId = resolveToken(token);
  6418. if (pluginId === undefined)
  6419. return;
  6420. setLocale(locale);
  6421. emitInterface("bytm:setLocale", { pluginId, locale });
  6422. }
  6423. /**
  6424. * Returns the current feature config, with sensitive values replaced by `undefined`
  6425. * This is an authenticated function so you must pass the session- and plugin-unique token, retreived at registration.
  6426. */
  6427. function getFeaturesInterface(token) {
  6428. if (resolveToken(token) === undefined)
  6429. return undefined;
  6430. const features = getFeatures();
  6431. for (const ftKey of Object.keys(features)) {
  6432. const info = featInfo[ftKey];
  6433. if (info && info.valueHidden) // @ts-ignore
  6434. features[ftKey] = undefined;
  6435. }
  6436. return features;
  6437. }
  6438. /**
  6439. * Saves the passed feature config synchronously to the in-memory cache and asynchronously to the persistent storage.
  6440. * This is an authenticated function so you must pass the session- and plugin-unique token, retreived at registration.
  6441. */
  6442. function saveFeaturesInterface(token, features) {
  6443. if (resolveToken(token) === undefined)
  6444. return;
  6445. setFeatures(features);
  6446. }
  6447. /**
  6448. * Returns the auto-like data.
  6449. * This is an authenticated function so you must pass the session- and plugin-unique token, retreived at registration.
  6450. */
  6451. function getAutoLikeDataInterface(token) {
  6452. if (resolveToken(token) === undefined)
  6453. return;
  6454. return autoLikeStore.getData();
  6455. }
  6456. /**
  6457. * Saves new auto-like data, synchronously to the in-memory cache and asynchronously to the persistent storage.
  6458. * This is an authenticated function so you must pass the session- and plugin-unique token, retreived at registration.
  6459. */
  6460. function saveAutoLikeDataInterface(token, data) {
  6461. if (resolveToken(token) === undefined)
  6462. return;
  6463. return autoLikeStore.setData(data);
  6464. }//#region globals
  6465. /** Options that are applied to every SelectorObserver instance */
  6466. const defaultObserverOptions = {
  6467. disableOnNoListeners: false,
  6468. enableOnAddListener: false,
  6469. defaultDebounce: 150,
  6470. defaultDebounceEdge: "rising",
  6471. };
  6472. /** Global SelectorObserver instances usable throughout the script for improved performance */
  6473. const globservers = {};
  6474. /** Whether all observers have been initialized */
  6475. let globserversReady = false;
  6476. //#region add listener func
  6477. /**
  6478. * Interface function for adding listeners to the {@linkcode globservers}
  6479. * If the observers haven't been initialized yet, the function will queue calls until the `bytm:observersReady` event is emitted
  6480. * @param selector Relative to the observer's root element, so the selector can only start at of the root element's children at the earliest!
  6481. * @param options Options for the listener
  6482. * @template TElem The type of the element that the listener will be attached to. If set to `0`, the default type `HTMLElement` will be used.
  6483. * @template TDomain This restricts which observers are available with the current domain
  6484. */
  6485. function addSelectorListener(observerName, selector, options) {
  6486. try {
  6487. if (!globserversReady) {
  6488. window.addEventListener("bytm:observersReady", () => addSelectorListener(observerName, selector, options), { once: true });
  6489. return;
  6490. }
  6491. globservers[observerName].addListener(selector, options);
  6492. }
  6493. catch (err) {
  6494. error(`Couldn't add listener to globserver '${observerName}':`, err);
  6495. }
  6496. }
  6497. //#region init
  6498. /** Call after DOM load to initialize all SelectorObserver instances */
  6499. function initObservers() {
  6500. try {
  6501. //#region both sites
  6502. //#region body
  6503. // -> the entire <body> element - use sparingly due to performance impacts!
  6504. // enabled immediately
  6505. globservers.body = new UserUtils.SelectorObserver(document.body, Object.assign(Object.assign({}, defaultObserverOptions), { defaultDebounceEdge: "falling", defaultDebounce: 150, subtree: false }));
  6506. globservers.body.enable();
  6507. switch (getDomain()) {
  6508. case "ytm": {
  6509. //#region YTM
  6510. //#region browseResponse
  6511. // -> for example the /channel/UC... page#
  6512. // enabled by "body"
  6513. const browseResponseSelector = "ytmusic-browse-response";
  6514. globservers.browseResponse = new UserUtils.SelectorObserver(browseResponseSelector, Object.assign(Object.assign({}, defaultObserverOptions), { subtree: true }));
  6515. globservers.body.addListener(browseResponseSelector, {
  6516. listener: () => globservers.browseResponse.enable(),
  6517. });
  6518. //#region navBar
  6519. // -> the navigation / title bar at the top of the page
  6520. // enabled by "body"
  6521. const navBarSelector = "ytmusic-nav-bar";
  6522. globservers.navBar = new UserUtils.SelectorObserver(navBarSelector, Object.assign(Object.assign({}, defaultObserverOptions), { subtree: false }));
  6523. globservers.body.addListener(navBarSelector, {
  6524. listener: () => globservers.navBar.enable(),
  6525. });
  6526. //#region mainPanel
  6527. // -> the main content panel - includes things like the video element
  6528. // enabled by "body"
  6529. const mainPanelSelector = "ytmusic-player-page #main-panel";
  6530. globservers.mainPanel = new UserUtils.SelectorObserver(mainPanelSelector, Object.assign(Object.assign({}, defaultObserverOptions), { subtree: true }));
  6531. globservers.body.addListener(mainPanelSelector, {
  6532. listener: () => globservers.mainPanel.enable(),
  6533. });
  6534. //#region sideBar
  6535. // -> the sidebar on the left side of the page
  6536. // enabled by "body"
  6537. const sidebarSelector = "ytmusic-app-layout tp-yt-app-drawer";
  6538. globservers.sideBar = new UserUtils.SelectorObserver(sidebarSelector, Object.assign(Object.assign({}, defaultObserverOptions), { subtree: true }));
  6539. globservers.body.addListener(sidebarSelector, {
  6540. listener: () => globservers.sideBar.enable(),
  6541. });
  6542. //#region sideBarMini
  6543. // -> the minimized sidebar on the left side of the page
  6544. // enabled by "body"
  6545. const sideBarMiniSelector = "ytmusic-app-layout #mini-guide";
  6546. globservers.sideBarMini = new UserUtils.SelectorObserver(sideBarMiniSelector, Object.assign(Object.assign({}, defaultObserverOptions), { subtree: true }));
  6547. globservers.body.addListener(sideBarMiniSelector, {
  6548. listener: () => globservers.sideBarMini.enable(),
  6549. });
  6550. //#region sidePanel
  6551. // -> the side panel on the right side of the /watch page
  6552. // enabled by "body"
  6553. const sidePanelSelector = "#side-panel";
  6554. globservers.sidePanel = new UserUtils.SelectorObserver(sidePanelSelector, Object.assign(Object.assign({}, defaultObserverOptions), { subtree: true }));
  6555. globservers.body.addListener(sidePanelSelector, {
  6556. listener: () => globservers.sidePanel.enable(),
  6557. });
  6558. //#region playerBar
  6559. // -> media controls bar at the bottom of the page
  6560. // enabled by "body"
  6561. const playerBarSelector = "ytmusic-app-layout ytmusic-player-bar.ytmusic-app";
  6562. globservers.playerBar = new UserUtils.SelectorObserver(playerBarSelector, Object.assign(Object.assign({}, defaultObserverOptions), { defaultDebounce: 200 }));
  6563. globservers.body.addListener(playerBarSelector, {
  6564. listener: () => {
  6565. globservers.playerBar.enable();
  6566. },
  6567. });
  6568. //#region playerBarInfo
  6569. // -> song title, artist, album, etc. inside the player bar
  6570. // enabled by "playerBar"
  6571. const playerBarInfoSelector = `${playerBarSelector} .middle-controls .content-info-wrapper`;
  6572. globservers.playerBarInfo = new UserUtils.SelectorObserver(playerBarInfoSelector, Object.assign(Object.assign({}, defaultObserverOptions), { attributes: true, attributeFilter: ["title"] }));
  6573. globservers.playerBar.addListener(playerBarInfoSelector, {
  6574. listener: () => globservers.playerBarInfo.enable(),
  6575. });
  6576. //#region playerBarMiddleButtons
  6577. // -> the buttons inside the player bar (like, dislike, lyrics, etc.)
  6578. // enabled by "playerBar"
  6579. const playerBarMiddleButtonsSelector = ".middle-controls .middle-controls-buttons";
  6580. globservers.playerBarMiddleButtons = new UserUtils.SelectorObserver(playerBarMiddleButtonsSelector, Object.assign(Object.assign({}, defaultObserverOptions), { subtree: true }));
  6581. globservers.playerBar.addListener(playerBarMiddleButtonsSelector, {
  6582. listener: () => globservers.playerBarMiddleButtons.enable(),
  6583. });
  6584. //#region playerBarRightControls
  6585. // -> the controls on the right side of the player bar (volume, repeat, shuffle, etc.)
  6586. // enabled by "playerBar"
  6587. const playerBarRightControls = "#right-controls";
  6588. globservers.playerBarRightControls = new UserUtils.SelectorObserver(playerBarRightControls, Object.assign(Object.assign({}, defaultObserverOptions), { subtree: true }));
  6589. globservers.playerBar.addListener(playerBarRightControls, {
  6590. listener: () => globservers.playerBarRightControls.enable(),
  6591. });
  6592. //#region popupContainer
  6593. // -> the container for popups (e.g. the queue popup)
  6594. // enabled by "body"
  6595. const popupContainerSelector = "ytmusic-app ytmusic-popup-container";
  6596. globservers.popupContainer = new UserUtils.SelectorObserver(popupContainerSelector, Object.assign(Object.assign({}, defaultObserverOptions), { subtree: true }));
  6597. globservers.body.addListener(popupContainerSelector, {
  6598. listener: () => globservers.popupContainer.enable(),
  6599. });
  6600. break;
  6601. }
  6602. case "yt": {
  6603. //#region YT
  6604. //#region ytGuide
  6605. // -> the left sidebar menu
  6606. // enabled by "body"
  6607. const ytGuideSelector = "#content tp-yt-app-drawer#guide #guide-inner-content";
  6608. globservers.ytGuide = new UserUtils.SelectorObserver(ytGuideSelector, Object.assign(Object.assign({}, defaultObserverOptions), { subtree: true }));
  6609. globservers.body.addListener(ytGuideSelector, {
  6610. listener: () => globservers.ytGuide.enable(),
  6611. });
  6612. //#region ytdBrowse
  6613. // -> channel pages for example
  6614. // enabled by "body"
  6615. const ytdBrowseSelector = "ytd-app ytd-page-manager ytd-browse";
  6616. globservers.ytdBrowse = new UserUtils.SelectorObserver(ytdBrowseSelector, Object.assign(Object.assign({}, defaultObserverOptions), { subtree: true }));
  6617. globservers.body.addListener(ytdBrowseSelector, {
  6618. listener: () => globservers.ytdBrowse.enable(),
  6619. });
  6620. //#region ytAppHeader
  6621. // -> header of the page
  6622. // enabled by "ytdBrowse"
  6623. const ytAppHeaderSelector = "#header tp-yt-app-header";
  6624. globservers.ytAppHeader = new UserUtils.SelectorObserver(ytAppHeaderSelector, Object.assign(Object.assign({}, defaultObserverOptions), { subtree: true }));
  6625. globservers.ytdBrowse.addListener(ytAppHeaderSelector, {
  6626. listener: () => globservers.ytAppHeader.enable(),
  6627. });
  6628. //#region ytWatchFlexy
  6629. // -> the main content of the /watch page
  6630. // enabled by "body"
  6631. const ytWatchFlexySelector = "ytd-app ytd-watch-flexy";
  6632. globservers.ytWatchFlexy = new UserUtils.SelectorObserver(ytWatchFlexySelector, Object.assign(Object.assign({}, defaultObserverOptions), { subtree: true }));
  6633. globservers.body.addListener(ytWatchFlexySelector, {
  6634. listener: () => globservers.ytWatchFlexy.enable(),
  6635. });
  6636. //#region ytWatchMetadata
  6637. // -> the metadata section of the /watch page (title, channel, views, description, buttons, etc. but not comments)
  6638. // enabled by "ytWatchFlexy"
  6639. const ytWatchMetadataSelector = "#columns #primary-inner ytd-watch-metadata";
  6640. globservers.ytWatchMetadata = new UserUtils.SelectorObserver(ytWatchMetadataSelector, Object.assign(Object.assign({}, defaultObserverOptions), { subtree: true }));
  6641. globservers.ytWatchFlexy.addListener(ytWatchMetadataSelector, {
  6642. listener: () => globservers.ytWatchMetadata.enable(),
  6643. });
  6644. //#region ytMasthead
  6645. // -> the masthead (title bar) at the top of the page
  6646. // enabled by "body"
  6647. const mastheadSelector = "#content ytd-masthead#masthead";
  6648. globservers.ytMasthead = new UserUtils.SelectorObserver(mastheadSelector, Object.assign(Object.assign({}, defaultObserverOptions), { subtree: true }));
  6649. globservers.body.addListener(mastheadSelector, {
  6650. listener: () => globservers.ytMasthead.enable(),
  6651. });
  6652. }
  6653. }
  6654. //#region finalize
  6655. globserversReady = true;
  6656. emitInterface("bytm:observersReady");
  6657. }
  6658. catch (err) {
  6659. error("Failed to initialize observers:", err);
  6660. }
  6661. }/** Whether the DOM has finished loading and elements can be added or modified */
  6662. let domLoaded = false;
  6663. document.addEventListener("DOMContentLoaded", () => domLoaded = true);
  6664. //#region vid time & vol.
  6665. /** Returns the video element selector string based on the current domain */
  6666. const getVideoSelector = () => getDomain() === "ytm" ? "ytmusic-player video" : "#player-container ytd-player video";
  6667. /** Returns the video element based on the current domain */
  6668. function getVideoElement() {
  6669. return document.querySelector(getVideoSelector());
  6670. }
  6671. let vidElemReady = false;
  6672. /**
  6673. * Returns the current video time in seconds, with the given {@linkcode precision} (2 decimal digits by default).
  6674. * Rounds down if the precision is set to 0. The maximum average available precision on YTM is 6.
  6675. * Dispatches mouse movement events in case the video time can't be read from the video or progress bar elements (needs a prior user interaction to work)
  6676. * @returns Returns null if the video time is unavailable or no user interaction has happened prior to calling in case of the fallback behavior being used
  6677. */
  6678. function getVideoTime(precision = 2) {
  6679. return new Promise(async (res) => {
  6680. if (!vidElemReady) {
  6681. await waitVideoElementReady();
  6682. vidElemReady = true;
  6683. }
  6684. const resolveWithVal = (time) => res(time && !isNaN(time)
  6685. ? Number(precision <= 0 ? Math.floor(time) : time.toFixed(precision))
  6686. : null);
  6687. try {
  6688. if (getDomain() === "ytm") {
  6689. const vidElem = getVideoElement();
  6690. if (vidElem)
  6691. return resolveWithVal(vidElem.currentTime);
  6692. addSelectorListener("playerBar", "tp-yt-paper-slider#progress-bar tp-yt-paper-progress#sliderBar", {
  6693. listener: (pbEl) => resolveWithVal(!isNaN(Number(pbEl.value)) ? Math.floor(Number(pbEl.value)) : null)
  6694. });
  6695. }
  6696. else if (getDomain() === "yt") {
  6697. const vidElem = getVideoElement();
  6698. if (vidElem)
  6699. return resolveWithVal(vidElem.currentTime);
  6700. // YT doesn't update the progress bar when it's hidden (contrary to YTM which never hides it)
  6701. ytForceShowVideoTime();
  6702. const pbSelector = ".ytp-chrome-bottom div.ytp-progress-bar[role=\"slider\"]";
  6703. let videoTime = -1;
  6704. const mut = new MutationObserver(() => {
  6705. // .observe() is only called when the element exists - no need to check for null
  6706. videoTime = Number(document.querySelector(pbSelector).getAttribute("aria-valuenow"));
  6707. });
  6708. const observe = (progElem) => {
  6709. mut.observe(progElem, {
  6710. attributes: true,
  6711. attributeFilter: ["aria-valuenow"],
  6712. });
  6713. if (videoTime >= 0 && !isNaN(videoTime)) {
  6714. resolveWithVal(Math.floor(videoTime));
  6715. mut.disconnect();
  6716. }
  6717. else
  6718. setTimeout(() => {
  6719. resolveWithVal(videoTime >= 0 && !isNaN(videoTime) ? Math.floor(videoTime) : null);
  6720. mut.disconnect();
  6721. }, 500);
  6722. };
  6723. addSelectorListener("body", pbSelector, { listener: observe });
  6724. }
  6725. }
  6726. catch (err) {
  6727. error("Couldn't get video time due to error:", err);
  6728. res(null);
  6729. }
  6730. });
  6731. }
  6732. /**
  6733. * Sends events that force the video controls to become visible for about 3 seconds.
  6734. * This only works once (for some reason), then the page needs to be reloaded!
  6735. */
  6736. function ytForceShowVideoTime() {
  6737. const player = document.querySelector("#movie_player");
  6738. if (!player)
  6739. return false;
  6740. const defaultProps = {
  6741. // needed because otherwise YTM errors out - see https://github.com/Sv443/BetterYTM/issues/18#show_issue
  6742. view: UserUtils.getUnsafeWindow(),
  6743. bubbles: true,
  6744. cancelable: false,
  6745. };
  6746. player.dispatchEvent(new MouseEvent("mouseenter", defaultProps));
  6747. const { x, y, width, height } = player.getBoundingClientRect();
  6748. const screenY = Math.round(y + height / 2);
  6749. const screenX = x + Math.min(50, Math.round(width / 3));
  6750. player.dispatchEvent(new MouseEvent("mousemove", Object.assign(Object.assign({}, defaultProps), { screenY,
  6751. screenX, movementX: 5, movementY: 0 })));
  6752. return true;
  6753. }
  6754. /**
  6755. * Waits for the video element to be in its readyState 4 / canplay state and returns it.
  6756. * Resolves immediately if the video element is already ready.
  6757. */
  6758. function waitVideoElementReady() {
  6759. return new Promise(async (res) => {
  6760. var _a;
  6761. if (((_a = getVideoElement()) === null || _a === void 0 ? void 0 : _a.readyState) === 4)
  6762. return res(getVideoElement());
  6763. const waitForEl = () => addSelectorListener("body", getVideoSelector(), {
  6764. listener: async (vidElem) => {
  6765. if (vidElem) {
  6766. // this is just after YT has finished doing their own shenanigans with the video time and volume
  6767. if (vidElem.readyState === 4)
  6768. res(vidElem);
  6769. else
  6770. vidElem.addEventListener("canplay", () => res(vidElem), { once: true });
  6771. }
  6772. },
  6773. });
  6774. if (!location.pathname.startsWith("/watch"))
  6775. await siteEvents.once("watchIdChanged");
  6776. waitForEl();
  6777. });
  6778. }
  6779. //#region css utils
  6780. /**
  6781. * Adds a style element to the DOM at runtime.
  6782. * @param css The CSS stylesheet to add
  6783. * @param ref A reference string to identify the style element - defaults to a random 5-character string
  6784. * @param transform A function to transform the CSS before adding it to the DOM
  6785. */
  6786. async function addStyle(css, ref, transform = (c) => c) {
  6787. if (!domLoaded)
  6788. throw new Error("DOM has not finished loading yet");
  6789. const elem = UserUtils.addGlobalStyle(await transform(css));
  6790. elem.id = `bytm-style-${ref !== null && ref !== void 0 ? ref : UserUtils.randomId(5, 36)}`;
  6791. return elem;
  6792. }
  6793. /**
  6794. * Adds a global style element with the contents fetched from the specified resource starting with `css-`
  6795. * The CSS can be transformed using the provided function before being added to the DOM.
  6796. */
  6797. async function addStyleFromResource(key, transform = (c) => c) {
  6798. const css = await fetchCss(key);
  6799. if (css) {
  6800. await addStyle(transform(css), key.slice(4));
  6801. return true;
  6802. }
  6803. return false;
  6804. }
  6805. /** Sets a global CSS variable on the &lt;document&gt; element with the name `--bytm-global-${name}` */
  6806. function setGlobalCssVar(name, value) {
  6807. document.documentElement.style.setProperty(`--bytm-global-${name.toLowerCase().trim()}`, String(value));
  6808. }
  6809. /** Sets multiple global CSS variables on the &lt;document&gt; element with the name `--bytm-global-${name}` */
  6810. function setGlobalCssVars(vars) {
  6811. for (const [name, value] of Object.entries(vars))
  6812. setGlobalCssVar(name, value);
  6813. }
  6814. //#region other
  6815. /** Removes all child nodes of an element without invoking the slow-ish HTML parser */
  6816. function clearInner(element) {
  6817. while (element.hasChildNodes())
  6818. clearNode(element.firstChild);
  6819. }
  6820. /** Removes all child nodes of an element recursively and also removes the element itself */
  6821. function clearNode(element) {
  6822. while (element.hasChildNodes())
  6823. clearNode(element.firstChild);
  6824. element.parentNode.removeChild(element);
  6825. }
  6826. /**
  6827. * Returns an identifier for the currently playing media type on YTM (song or video).
  6828. * Only works on YTM and will throw on YT or if {@linkcode waitVideoElementReady} hasn't been awaited yet.
  6829. */
  6830. function getCurrentMediaType() {
  6831. if (getDomain() === "yt")
  6832. throw new Error("currentMediaType() is only available on YTM!");
  6833. const songImgElem = document.querySelector("ytmusic-player #song-image");
  6834. if (!songImgElem)
  6835. throw new Error("Couldn't find the song image element. Use this function only after awaiting `waitVideoElementReady()`!");
  6836. return window.getComputedStyle(songImgElem).display !== "none" ? "song" : "video";
  6837. }
  6838. /** Copies the provided text to the clipboard and shows an error message for manual copying if the grant `GM.setClipboard` is not given. */
  6839. function copyToClipboard(text) {
  6840. try {
  6841. GM.setClipboard(String(text));
  6842. }
  6843. catch (_a) {
  6844. alert(t("copy_to_clipboard_error", String(text)));
  6845. }
  6846. }
  6847. let ttPolicy;
  6848. /** Sets innerHTML directly on Firefox and Safari, while on Chromium a [Trusted Types policy](https://developer.mozilla.org/en-US/docs/Web/API/Trusted_Types_API) is used to set the HTML */
  6849. function setInnerHtml(element, html) {
  6850. var _a;
  6851. if (!ttPolicy && ((_a = window === null || window === void 0 ? void 0 : window.trustedTypes) === null || _a === void 0 ? void 0 : _a.createPolicy)) {
  6852. ttPolicy = window.trustedTypes.createPolicy("my-policy", {
  6853. createHTML: (dirty) => DOMPurify.sanitize(dirty, {
  6854. RETURN_TRUSTED_TYPE: true,
  6855. }),
  6856. });
  6857. }
  6858. if (ttPolicy)
  6859. element.innerHTML = ttPolicy.createHTML(html);
  6860. else {
  6861. UserUtils.debounce(() => warn("Trusted Types policy not available, using innerHTML directly"), 1000, "rising")();
  6862. element.innerHTML = html;
  6863. }
  6864. }/**
  6865. * Constructs a URL from a base URL and a record of query parameters.
  6866. * If a value is null, the parameter will be valueless. If a value is undefined, the parameter will be omitted.
  6867. * All values will be stringified using their `toString()` method and then URI-encoded.
  6868. * @returns Returns a string instead of a URL object
  6869. */
  6870. function constructUrlString(baseUrl, params) {
  6871. return `${baseUrl}?${Object.entries(params)
  6872. .filter(([, v]) => v !== undefined)
  6873. .map(([key, val]) => `${key}${val === null ? "" : `=${encodeURIComponent(String(val))}`}`)
  6874. .join("&")}`;
  6875. }
  6876. /**
  6877. * Constructs a URL object from a base URL and a record of query parameters.
  6878. * If a value is null, the parameter will be valueless. If a value is undefined, the parameter will be omitted.
  6879. * All values will be URI-encoded.
  6880. * @returns Returns a URL object instead of a string
  6881. */
  6882. function constructUrl(base, params) {
  6883. return new URL(constructUrlString(base, params));
  6884. }
  6885. /**
  6886. * Sends a request with the specified parameters and returns the response as a Promise.
  6887. * Ignores [CORS](https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS), contrary to fetch and fetchAdvanced.
  6888. */
  6889. function sendRequest(details) {
  6890. return new Promise((resolve, reject) => {
  6891. GM.xmlHttpRequest(Object.assign(Object.assign({ timeout: 10000 }, details), { onload: resolve, onerror: reject, ontimeout: reject, onabort: reject }));
  6892. });
  6893. }
  6894. /** Fetches a CSS file from the specified resource with a key starting with `css-` */
  6895. async function fetchCss(key) {
  6896. try {
  6897. const css = await (await UserUtils.fetchAdvanced(await getResourceUrl(key))).text();
  6898. return css !== null && css !== void 0 ? css : undefined;
  6899. }
  6900. catch (err) {
  6901. error("Couldn't fetch CSS due to an error:", err);
  6902. return undefined;
  6903. }
  6904. }
  6905. /** Cache for the vote data of YouTube videos to prevent some unnecessary requests */
  6906. const voteCache = new Map();
  6907. /** Time-to-live for the vote cache in milliseconds */
  6908. const voteCacheTTL = 1000 * 60 * 10;
  6909. /**
  6910. * Fetches the votes object for a YouTube video from the [Return YouTube Dislike API.](https://returnyoutubedislike.com/docs)
  6911. * @param watchId The watch ID of the video
  6912. */
  6913. async function fetchVideoVotes(watchId) {
  6914. try {
  6915. if (voteCache.has(watchId)) {
  6916. const cached = voteCache.get(watchId);
  6917. if (Date.now() - cached.timestamp < voteCacheTTL) {
  6918. info(`Returning cached video votes for watch ID '${watchId}':`, cached);
  6919. return cached;
  6920. }
  6921. else
  6922. voteCache.delete(watchId);
  6923. }
  6924. const votesRaw = JSON.parse((await sendRequest({
  6925. method: "GET",
  6926. url: `https://returnyoutubedislikeapi.com/votes?videoId=${watchId}`,
  6927. })).response);
  6928. if (!("id" in votesRaw) || !("likes" in votesRaw) || !("dislikes" in votesRaw) || !("rating" in votesRaw)) {
  6929. error("Couldn't parse video votes due to an error:", votesRaw);
  6930. return undefined;
  6931. }
  6932. const votesObj = {
  6933. id: votesRaw.id,
  6934. likes: votesRaw.likes,
  6935. dislikes: votesRaw.dislikes,
  6936. rating: votesRaw.rating,
  6937. timestamp: Date.now(),
  6938. };
  6939. voteCache.set(votesObj.id, votesObj);
  6940. info(`Fetched video votes for watch ID '${watchId}':`, votesObj);
  6941. return votesObj;
  6942. }
  6943. catch (err) {
  6944. error("Couldn't fetch video votes due to an error:", err);
  6945. return undefined;
  6946. }
  6947. }/** Central serializer for all data stores */
  6948. const storeSerializer = new UserUtils.DataStoreSerializer([
  6949. configStore,
  6950. autoLikeStore,
  6951. ], {
  6952. addChecksum: true,
  6953. ensureIntegrity: true,
  6954. });//#region cns. watermark
  6955. {
  6956. // console watermark with sexy gradient
  6957. const styleGradient = "background: rgba(165, 38, 38, 1); background: linear-gradient(90deg, rgb(154, 31, 103) 0%, rgb(135, 31, 31) 40%, rgb(184, 64, 41) 100%);";
  6958. const styleCommon = "color: #fff; font-size: 1.3rem;";
  6959. console.log(`%c${scriptInfo.name}%c${scriptInfo.version}%c • ${scriptInfo.namespace}%c\n\nBuild #${buildNumber}`, `${styleCommon} ${styleGradient} font-weight: bold; padding-left: 6px; padding-right: 6px;`, `${styleCommon} background-color: #333; padding-left: 8px; padding-right: 8px;`, "color: #fff; font-size: 1.2rem;", "padding: initial; font-size: 0.9rem;");
  6960. console.log([
  6961. "Powered by:",
  6962. "─ Lots of ambition and dedication",
  6963. "─ My song metadata API: https://api.sv443.net/geniurl",
  6964. "─ My userscript utility library: https://github.com/Sv443-Network/UserUtils",
  6965. "─ This library for semver comparison: https://github.com/omichelsen/compare-versions",
  6966. "─ This tiny event listener library: https://github.com/ai/nanoevents",
  6967. "─ This markdown parser library: https://github.com/markedjs/marked",
  6968. "─ TypeScript and the tslib runtime: https://github.com/microsoft/TypeScript",
  6969. ].join("\n"));
  6970. }
  6971. //#region preInit
  6972. /** Stuff that needs to be called ASAP, before anything async happens */
  6973. function preInit() {
  6974. try {
  6975. log("Session ID:", getSessionId());
  6976. initInterface();
  6977. setLogLevel(defaultLogLevel);
  6978. if (getDomain() === "ytm")
  6979. initBeforeUnloadHook();
  6980. init();
  6981. }
  6982. catch (err) {
  6983. return error("Fatal pre-init error:", err);
  6984. }
  6985. }
  6986. //#region init
  6987. async function init() {
  6988. var _a, _b;
  6989. try {
  6990. const domain = getDomain();
  6991. const features = await initConfig();
  6992. setLogLevel(features.logLevel);
  6993. await initLyricsCache();
  6994. await initTranslations((_a = features.locale) !== null && _a !== void 0 ? _a : "en_US");
  6995. setLocale((_b = features.locale) !== null && _b !== void 0 ? _b : "en_US");
  6996. emitInterface("bytm:registerPlugins");
  6997. if (features.disableBeforeUnloadPopup && domain === "ytm")
  6998. disableBeforeUnload();
  6999. if (features.rememberSongTime)
  7000. initRememberSongTime();
  7001. if (!domLoaded)
  7002. document.addEventListener("DOMContentLoaded", onDomLoad, { once: true });
  7003. else
  7004. onDomLoad();
  7005. }
  7006. catch (err) {
  7007. error("Fatal error:", err);
  7008. }
  7009. }
  7010. //#region onDomLoad
  7011. /** Called when the DOM has finished loading and can be queried and altered by the userscript */
  7012. async function onDomLoad() {
  7013. const domain = getDomain();
  7014. const feats = getFeatures();
  7015. const ftInit = [];
  7016. // for being able to apply domain-specific styles (prefix any CSS selector with "body.bytm-dom-yt" or "body.bytm-dom-ytm")
  7017. document.body.classList.add(`bytm-dom-${domain}`);
  7018. try {
  7019. initGlobalCssVars();
  7020. initObservers();
  7021. await Promise.allSettled([
  7022. injectCssBundle(),
  7023. initVersionCheck(),
  7024. ]);
  7025. }
  7026. catch (err) {
  7027. error("Fatal error in feature pre-init:", err);
  7028. return;
  7029. }
  7030. log(`DOM loaded and feature pre-init finished, now initializing all features for domain "${domain}"...`);
  7031. try {
  7032. //#region welcome dlg
  7033. if (typeof await GM.getValue("bytm-installed") !== "string") {
  7034. // open welcome menu with language selector
  7035. const dlg = await getWelcomeDialog();
  7036. dlg.on("close", () => GM.setValue("bytm-installed", JSON.stringify({ timestamp: Date.now(), version: scriptInfo.version })));
  7037. info("Showing welcome menu");
  7038. await dlg.open();
  7039. }
  7040. if (domain === "ytm") {
  7041. //#region (ytm) layout
  7042. if (feats.watermarkEnabled)
  7043. ftInit.push(["addWatermark", addWatermark()]);
  7044. if (feats.fixSpacing)
  7045. ftInit.push(["fixSpacing", fixSpacing()]);
  7046. ftInit.push(["thumbnailOverlay", initThumbnailOverlay()]);
  7047. if (feats.hideCursorOnIdle)
  7048. ftInit.push(["hideCursorOnIdle", initHideCursorOnIdle()]);
  7049. if (feats.fixHdrIssues)
  7050. ftInit.push(["fixHdrIssues", fixHdrIssues()]);
  7051. if (feats.showVotes)
  7052. ftInit.push(["showVotes", initShowVotes()]);
  7053. //#region (ytm) volume
  7054. ftInit.push(["volumeFeatures", initVolumeFeatures()]);
  7055. //#region (ytm) song lists
  7056. if (feats.lyricsQueueButton || feats.deleteFromQueueButton)
  7057. ftInit.push(["queueButtons", initQueueButtons()]);
  7058. ftInit.push(["aboveQueueBtns", initAboveQueueBtns()]);
  7059. //#region (ytm) behavior
  7060. if (feats.closeToastsTimeout > 0)
  7061. ftInit.push(["autoCloseToasts", initAutoCloseToasts()]);
  7062. //#region (ytm) input
  7063. ftInit.push(["arrowKeySkip", initArrowKeySkip()]);
  7064. if (feats.anchorImprovements)
  7065. ftInit.push(["anchorImprovements", addAnchorImprovements()]);
  7066. ftInit.push(["numKeysSkip", initNumKeysSkip()]);
  7067. //#region (ytm) lyrics
  7068. if (feats.geniusLyrics)
  7069. ftInit.push(["playerBarLyricsBtn", addPlayerBarLyricsBtn()]);
  7070. // #region (ytm) integrations
  7071. if (feats.sponsorBlockIntegration)
  7072. ftInit.push(["sponsorBlockIntegration", fixSponsorBlock()]);
  7073. if (feats.themeSongIntegration)
  7074. ftInit.push(["themeSongIntegration", fixThemeSong()]);
  7075. else
  7076. ftInit.push(["themeSongIntegration", fixPlayerPageTheming()]);
  7077. }
  7078. //#region (ytm+yt) cfg menu
  7079. try {
  7080. if (domain === "ytm") {
  7081. addSelectorListener("body", "tp-yt-iron-dropdown #contentWrapper ytd-multi-page-menu-renderer #container.menu-container", {
  7082. listener: addConfigMenuOptionYTM,
  7083. });
  7084. }
  7085. else if (domain === "yt") {
  7086. addSelectorListener("ytGuide", "#sections ytd-guide-section-renderer:nth-child(5) #items ytd-guide-entry-renderer:nth-child(1)", {
  7087. listener: (el) => el.parentElement && addConfigMenuOptionYT(el.parentElement),
  7088. });
  7089. }
  7090. }
  7091. catch (err) {
  7092. error("Couldn't add config menu option:", err);
  7093. }
  7094. if (["ytm", "yt"].includes(domain)) {
  7095. //#region general
  7096. ftInit.push(["initSiteEvents", initSiteEvents()]);
  7097. //#region (ytm+yt) layout
  7098. if (feats.removeShareTrackingParamSites && (feats.removeShareTrackingParamSites === domain || feats.removeShareTrackingParamSites === "all"))
  7099. ftInit.push(["initRemShareTrackParam", initRemShareTrackParam()]);
  7100. //#region (ytm+yt) input
  7101. ftInit.push(["siteSwitch", initSiteSwitch(domain)]);
  7102. if (feats.autoLikeChannels)
  7103. ftInit.push(["autoLikeChannels", initAutoLike()]);
  7104. //#region (ytm+yt) integrations
  7105. if (feats.disableDarkReaderSites !== "none")
  7106. ftInit.push(["disableDarkReaderSites", disableDarkReader()]);
  7107. }
  7108. emitInterface("bytm:featureInitStarted");
  7109. try {
  7110. initPlugins();
  7111. }
  7112. catch (err) {
  7113. error("Plugin loading error:", err);
  7114. emitInterface("bytm:fatalError", "Error while loading plugins");
  7115. }
  7116. const initStartTs = Date.now();
  7117. // wait for feature init or timeout (in case an init function is hung up on a promise)
  7118. await Promise.race([
  7119. UserUtils.pauseFor(feats.initTimeout > 0 ? feats.initTimeout * 1000 : 8000),
  7120. Promise.allSettled(ftInit.map(([name, prom]) => new Promise(async (res) => {
  7121. const v = await prom;
  7122. emitInterface("bytm:featureInitialized", name);
  7123. res(v);
  7124. }))),
  7125. ]);
  7126. emitInterface("bytm:ready");
  7127. info(`Done initializing ${ftInit.length} features after ${Math.floor(Date.now() - initStartTs)}ms`);
  7128. try {
  7129. registerDevCommands();
  7130. }
  7131. catch (e) {
  7132. warn("Couldn't register dev menu commands:", e);
  7133. }
  7134. }
  7135. catch (err) {
  7136. error("Feature error:", err);
  7137. emitInterface("bytm:fatalError", "Error while initializing features");
  7138. }
  7139. }
  7140. //#region css
  7141. /** Inserts the bundled CSS files imported throughout the script into a <style> element in the <head> */
  7142. async function injectCssBundle() {
  7143. if (!await addStyleFromResource("css-bundle"))
  7144. error("Couldn't inject CSS bundle due to an error");
  7145. }
  7146. /** Initializes global CSS variables */
  7147. function initGlobalCssVars() {
  7148. try {
  7149. const applyVars = () => {
  7150. setGlobalCssVars({
  7151. "inner-height": `${window.innerHeight}px`,
  7152. "outer-height": `${window.outerHeight}px`,
  7153. "inner-width": `${window.innerWidth}px`,
  7154. "outer-width": `${window.outerWidth}px`,
  7155. });
  7156. };
  7157. window.addEventListener("resize", applyVars);
  7158. applyVars();
  7159. }
  7160. catch (err) {
  7161. error("Couldn't initialize global CSS variables:", err);
  7162. }
  7163. }
  7164. //#region dev menu cmds
  7165. /** Registers dev commands using `GM.registerMenuCommand` */
  7166. function registerDevCommands() {
  7167. if (mode !== "development")
  7168. return;
  7169. GM.registerMenuCommand("Reset config", async () => {
  7170. if (confirm("Reset the configuration to its default values?\nThis will automatically reload the page.")) {
  7171. await clearConfig();
  7172. disableBeforeUnload();
  7173. location.reload();
  7174. }
  7175. }, "r");
  7176. GM.registerMenuCommand("Fix config values", async () => {
  7177. const oldFeats = JSON.parse(JSON.stringify(getFeatures()));
  7178. await setFeatures(fixCfgKeys(oldFeats));
  7179. dbg("Fixed missing or extraneous config values.\nFrom:", oldFeats, "\n\nTo:", getFeatures());
  7180. if (confirm("All missing or config values were set to their default values and extraneous ones were removed.\nDo you want to reload the page now?"))
  7181. location.reload();
  7182. });
  7183. GM.registerMenuCommand("List GM values in console with decompression", async () => {
  7184. const keys = await GM.listValues();
  7185. dbg(`GM values (${keys.length}):`);
  7186. if (keys.length === 0)
  7187. dbg(" No values found.");
  7188. const values = {};
  7189. let longestKey = 0;
  7190. for (const key of keys) {
  7191. const isEncoded = key.startsWith("_uucfg-") ? await GM.getValue(`_uucfgenc-${key.substring(7)}`, false) : false;
  7192. const val = await GM.getValue(key, undefined);
  7193. values[key] = typeof val !== "undefined" && isEncoded ? await UserUtils.decompress(val, compressionFormat, "string") : val;
  7194. longestKey = Math.max(longestKey, key.length);
  7195. }
  7196. for (const [key, finalVal] of Object.entries(values)) {
  7197. const isEncoded = key.startsWith("_uucfg-") ? await GM.getValue(`_uucfgenc-${key.substring(7)}`, false) : false;
  7198. const lengthStr = String(finalVal).length > 50 ? `(${String(finalVal).length} chars) ` : "";
  7199. dbg(` "${key}"${" ".repeat(longestKey - key.length)} -${isEncoded ? "-[decoded]-" : ""}> ${lengthStr}${finalVal}`);
  7200. }
  7201. }, "l");
  7202. GM.registerMenuCommand("List GM values in console, without decompression", async () => {
  7203. const keys = await GM.listValues();
  7204. dbg(`GM values (${keys.length}):`);
  7205. if (keys.length === 0)
  7206. dbg(" No values found.");
  7207. const values = {};
  7208. let longestKey = 0;
  7209. for (const key of keys) {
  7210. const val = await GM.getValue(key, undefined);
  7211. values[key] = val;
  7212. longestKey = Math.max(longestKey, key.length);
  7213. }
  7214. for (const [key, val] of Object.entries(values)) {
  7215. const lengthStr = String(val).length >= 16 ? `(${String(val).length} chars) ` : "";
  7216. dbg(` "${key}"${" ".repeat(longestKey - key.length)} -> ${lengthStr}${val}`);
  7217. }
  7218. });
  7219. GM.registerMenuCommand("Delete all GM values", async () => {
  7220. const keys = await GM.listValues();
  7221. if (confirm(`Clear all ${keys.length} GM values?\nSee console for details.`)) {
  7222. dbg(`Clearing ${keys.length} GM values:`);
  7223. if (keys.length === 0)
  7224. dbg(" No values found.");
  7225. for (const key of keys) {
  7226. await GM.deleteValue(key);
  7227. dbg(` Deleted ${key}`);
  7228. }
  7229. }
  7230. }, "d");
  7231. GM.registerMenuCommand("Delete GM values by name (comma separated)", async () => {
  7232. var _a;
  7233. const keys = prompt("Enter the name(s) of the GM value to delete (comma separated).\nEmpty input cancels the operation.");
  7234. if (!keys)
  7235. return;
  7236. for (const key of (_a = keys === null || keys === void 0 ? void 0 : keys.split(",")) !== null && _a !== void 0 ? _a : []) {
  7237. if (key && key.length > 0) {
  7238. const truncLength = 400;
  7239. const oldVal = await GM.getValue(key);
  7240. await GM.deleteValue(key);
  7241. dbg(`Deleted GM value '${key}' with previous value '${oldVal && String(oldVal).length > truncLength ? String(oldVal).substring(0, truncLength) + `… (${String(oldVal).length} / ${truncLength} chars.)` : oldVal}'`);
  7242. }
  7243. }
  7244. }, "n");
  7245. GM.registerMenuCommand("Reset install timestamp", async () => {
  7246. await GM.deleteValue("bytm-installed");
  7247. dbg("Reset install time.");
  7248. }, "t");
  7249. GM.registerMenuCommand("Reset version check timestamp", async () => {
  7250. await GM.deleteValue("bytm-version-check");
  7251. dbg("Reset version check time.");
  7252. }, "v");
  7253. GM.registerMenuCommand("List active selector listeners in console", async () => {
  7254. const lines = [];
  7255. let listenersAmt = 0;
  7256. for (const [obsName, obs] of Object.entries(globservers)) {
  7257. const listeners = obs.getAllListeners();
  7258. lines.push(`- "${obsName}" (${listeners.size} listeners):`);
  7259. [...listeners].forEach(([k, v]) => {
  7260. listenersAmt += v.length;
  7261. lines.push(` [${v.length}] ${k}`);
  7262. v.forEach(({ all, continuous }, i) => {
  7263. lines.push(` ${v.length > 1 && i !== v.length - 1 ? "├" : "└"}> ${continuous ? "continuous" : "single-shot"}${all ? ", multiple" : ""}`);
  7264. });
  7265. });
  7266. }
  7267. dbg(`Showing currently active listeners for ${Object.keys(globservers).length} observers with ${listenersAmt} total listeners:\n${lines.join("\n")}`);
  7268. }, "s");
  7269. GM.registerMenuCommand("Compress value", async () => {
  7270. const input = prompt("Enter the value to compress.\nSee console for output.");
  7271. if (input && input.length > 0) {
  7272. const compressed = await UserUtils.compress(input, compressionFormat);
  7273. dbg(`Compression result (${input.length} chars -> ${compressed.length} chars)\nValue: ${compressed}`);
  7274. }
  7275. });
  7276. GM.registerMenuCommand("Decompress value", async () => {
  7277. const input = prompt("Enter the value to decompress.\nSee console for output.");
  7278. if (input && input.length > 0) {
  7279. const decompressed = await UserUtils.decompress(input, compressionFormat);
  7280. dbg(`Decompresion result (${input.length} chars -> ${decompressed.length} chars)\nValue: ${decompressed}`);
  7281. }
  7282. });
  7283. GM.registerMenuCommand("Export using DataStoreSerializer", async () => {
  7284. const ser = await storeSerializer.serialize();
  7285. dbg("Serialized data stores:", JSON.stringify(JSON.parse(ser)));
  7286. alert("See console.");
  7287. });
  7288. GM.registerMenuCommand("Import using DataStoreSerializer", async () => {
  7289. const input = prompt("Enter the serialized data to import:");
  7290. if (input && input.length > 0) {
  7291. await storeSerializer.deserialize(input);
  7292. alert("Imported data. Reload the page to apply changes.");
  7293. }
  7294. });
  7295. GM.registerMenuCommand("Throw specific Error", () => error("Test error thrown by user command:", new SyntaxError("Test error")));
  7296. GM.registerMenuCommand("Throw generic Error", () => error());
  7297. GM.registerMenuCommand("Example MarkdownDialog", async () => {
  7298. const mdDlg = new MarkdownDialog({
  7299. id: "example",
  7300. width: 500,
  7301. height: 400,
  7302. renderHeader() {
  7303. const header = document.createElement("h1");
  7304. header.textContent = "Example Markdown Dialog";
  7305. return header;
  7306. },
  7307. body: "## This is a test dialog\n```ts\nconsole.log(\"Hello, world!\");\n```\n\n- List item 1\n- List item 2\n- List item 3",
  7308. });
  7309. await mdDlg.open();
  7310. });
  7311. log("Registered dev menu commands");
  7312. }
  7313. preInit();})(UserUtils,compareVersions,marked,DOMPurify);//# sourceMappingURL=http://localhost:8710/BetterYTM.user.js.map