BetterYTM.user.js 265 KB

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