BetterYTM.user.js 332 KB

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