BetterYTM.user.js 284 KB

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