BetterYTM.user.js 308 KB

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