BetterYTM.user.js 296 KB

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