BetterYTM.user.js 322 KB

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