BetterYTM.user.js 300 KB

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