BetterYTM.user.js 277 KB

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