BetterYTM.user.js 301 KB

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