BetterYTM.user.js 287 KB

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