BetterYTM.user.js 343 KB

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