BetterYTM.user.js 247 KB

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