BetterYTM.user.js 297 KB

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