BetterYTM.user.js 312 KB

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