BetterYTM.user.js 247 KB

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