BetterYTM.user.js 172 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756
  1. // ==UserScript==
  2. // @name BetterYTM
  3. // @homepageURL https://github.com/Sv443/BetterYTM#readme
  4. // @namespace https://github.com/Sv443/BetterYTM
  5. // @version 1.0.0
  6. // @description Configurable layout and UX improvements for YouTube Music
  7. // @description:de Konfigurierbares Layout und UX-Verbesserungen für YouTube Music
  8. // @license MIT
  9. // @author Sv443
  10. // @copyright Sv443 (https://github.com/Sv443)
  11. // @icon https://raw.githubusercontent.com/Sv443/BetterYTM/develop/assets/icon/icon_48.png
  12. // @match https://music.youtube.com/*
  13. // @match https://www.youtube.com/*
  14. // @run-at document-start
  15. // @downloadURL https://raw.githubusercontent.com/Sv443/BetterYTM/develop/dist/BetterYTM.user.js
  16. // @updateURL https://raw.githubusercontent.com/Sv443/BetterYTM/develop/dist/BetterYTM.user.js
  17. // @connect api.sv443.net
  18. // @grant GM.getValue
  19. // @grant GM.setValue
  20. // @grant GM.getResourceUrl
  21. // @grant unsafeWindow
  22. // @noframes
  23. // @resource icon https://raw.githubusercontent.com/Sv443/BetterYTM/develop/assets/icon/icon_48.png
  24. // @resource close https://raw.githubusercontent.com/Sv443/BetterYTM/develop/assets/close.png
  25. // @resource delete https://raw.githubusercontent.com/Sv443/BetterYTM/develop/assets/delete.svg
  26. // @resource error https://raw.githubusercontent.com/Sv443/BetterYTM/develop/assets/error.svg
  27. // @resource lyrics https://raw.githubusercontent.com/Sv443/BetterYTM/develop/assets/lyrics.svg
  28. // @resource spinner https://raw.githubusercontent.com/Sv443/BetterYTM/develop/assets/spinner.svg
  29. // @resource arrow_down https://raw.githubusercontent.com/Sv443/BetterYTM/develop/assets/arrow_down.svg
  30. // @resource github https://raw.githubusercontent.com/Sv443/BetterYTM/develop/assets/external/github.png
  31. // @resource greasyfork https://raw.githubusercontent.com/Sv443/BetterYTM/develop/assets/external/greasyfork.png
  32. // @grant GM.deleteValue
  33. // @grant GM.registerMenuCommand
  34. // @grant GM.listValues
  35. // ==/UserScript==
  36. /*
  37. ▄▄▄ ▄ ▄▄▄▄▄▄ ▄
  38. █ █ ▄▄▄ █ █ ▄▄▄ ▄ ▄█ █ █ █▀▄▀█
  39. █▀▀▄ █▄█ █▀ █▀ █▄█ █▀ █ █ █ █
  40. █▄▄▀ ▀▄▄ ▀▄▄ ▀▄▄ ▀▄▄ █ █ █ █ █
  41. Made with ❤️ by Sv443
  42. I welcome every contribution on GitHub!
  43. https://github.com/Sv443/BetterYTM
  44. */
  45. /* Disclaimer: I am not affiliated with YouTube, Google, Alphabet, Genius or anyone else */
  46. /* C&D this 🖕 */
  47. /******/ var __webpack_modules__ = ({
  48. /***/ "./changelog.md":
  49. /*!**********************!*\
  50. !*** ./changelog.md ***!
  51. \**********************/
  52. /***/ (function(__unused_webpack_module, __webpack_exports__, __webpack_require__) {
  53. __webpack_require__.r(__webpack_exports__);
  54. // Module
  55. var code = "<h1 id=\"betterytm-changelog\">BetterYTM Changelog</h1>\n<br>\n\n<h2 id=\"history\">History:</h2>\n<ul>\n<li><strong><a href=\"#100\">v1.0.0</a></strong></li>\n<li><a href=\"#020\">v0.2.0</a></li>\n<li><a href=\"#010\">v0.1.0</a></li>\n</ul>\n<hr>\n<p><br><br></p>\n<h2 id=\"100\">1.0.0</h2>\n<p>TODO:</p>\n<ul>\n<li>Added menu to configure features</li>\n<li>New configurable features:<ul>\n<li>Make volume slider bigger</li>\n<li>Choose step of volume slider for finer control</li>\n<li>Add lyrics button to each song in a playlist</li>\n</ul>\n</li>\n<li>Changes / Fixes:<ul>\n<li>Now the lyrics button will directly link to the lyrics (using my API <a href=\"https://github.com/Sv443/geniURL\">geniURL</a>)</li>\n<li>Site switch with <kbd>F9</kbd> will now keep the video time</li>\n</ul>\n</li>\n</ul>\n<br>\n\n<h2 id=\"020\">0.2.0</h2>\n<ul>\n<li>Added Features:<ul>\n<li>Switch between YouTube and YT Music (with <kbd>F9</kbd> by default)</li>\n<li>Search for song lyrics with new button in media controls</li>\n<li>Remove &quot;Upgrade to YTM Premium&quot; tab</li>\n</ul>\n</li>\n</ul>\n<br>\n\n<h2 id=\"010\">0.1.0</h2>\n<ul>\n<li>Added support for arrow keys to skip forward or backward (currently only by fixed 10 second interval)</li>\n</ul>\n";
  56. // Exports
  57. /* harmony default export */ __webpack_exports__["default"] = (code);
  58. /***/ }),
  59. /***/ "./src/menu/menu.html":
  60. /*!****************************!*\
  61. !*** ./src/menu/menu.html ***!
  62. \****************************/
  63. /***/ (function(__unused_webpack_module, __webpack_exports__, __webpack_require__) {
  64. __webpack_require__.r(__webpack_exports__);
  65. // Module
  66. var code = "<dialog id=\"bytm-menu-dialog\">\n <div id=\"bytm-menu-header-container\">\n <div class=\"bytm-menu-header-option\" id=\"bytm-menu-tab-options-header\" data-active=\"true\">\n <h3>Options</h3>\n </div>\n <div class=\"bytm-menu-header-option\" id=\"bytm-menu-tab-info-header\" data-active=\"false\">\n <h3>Info</h3>\n </div>\n <div class=\"bytm-menu-header-option\" id=\"bytm-menu-tab-changelog-header\" data-active=\"false\">\n <h3>Changelog</h3>\n </div>\n </div>\n <div id=\"bytm-menu-body\">\n <div class=\"bytm-menu-tab-content\" id=\"bytm-menu-tab-options-content\" data-active=\"true\"></div>\n <div class=\"bytm-menu-tab-content\" id=\"bytm-menu-tab-info-content\" data-active=\"false\">\n ayo info\n </div>\n <div class=\"bytm-menu-tab-content\" id=\"bytm-menu-tab-changelog-content\" data-active=\"false\"></div>\n </div>\n</dialog>\n";
  67. // Exports
  68. /* harmony default export */ __webpack_exports__["default"] = (code);
  69. /***/ }),
  70. /***/ "./src/features/layout.css":
  71. /*!*********************************!*\
  72. !*** ./src/features/layout.css ***!
  73. \*********************************/
  74. /***/ (function(__unused_webpack_module, __webpack_exports__, __webpack_require__) {
  75. __webpack_require__.r(__webpack_exports__);
  76. // extracted by mini-css-extract-plugin
  77. /***/ }),
  78. /***/ "./src/menu/menu.css":
  79. /*!***************************!*\
  80. !*** ./src/menu/menu.css ***!
  81. \***************************/
  82. /***/ (function(__unused_webpack_module, __webpack_exports__, __webpack_require__) {
  83. __webpack_require__.r(__webpack_exports__);
  84. // extracted by mini-css-extract-plugin
  85. /***/ }),
  86. /***/ "./src/menu/menu_old.css":
  87. /*!*******************************!*\
  88. !*** ./src/menu/menu_old.css ***!
  89. \*******************************/
  90. /***/ (function(__unused_webpack_module, __webpack_exports__, __webpack_require__) {
  91. __webpack_require__.r(__webpack_exports__);
  92. // extracted by mini-css-extract-plugin
  93. /***/ }),
  94. /***/ "./src/config.ts":
  95. /*!***********************!*\
  96. !*** ./src/config.ts ***!
  97. \***********************/
  98. /***/ (function(__unused_webpack_module, __webpack_exports__, __webpack_require__) {
  99. __webpack_require__.r(__webpack_exports__);
  100. /* harmony export */ __webpack_require__.d(__webpack_exports__, {
  101. /* harmony export */ clearConfig: function() { return /* binding */ clearConfig; },
  102. /* harmony export */ defaultConfig: function() { return /* binding */ defaultConfig; },
  103. /* harmony export */ formatVersion: function() { return /* binding */ formatVersion; },
  104. /* harmony export */ getFeatures: function() { return /* binding */ getFeatures; },
  105. /* harmony export */ initConfig: function() { return /* binding */ initConfig; },
  106. /* harmony export */ migrations: function() { return /* binding */ migrations; },
  107. /* harmony export */ saveFeatures: function() { return /* binding */ saveFeatures; },
  108. /* harmony export */ setDefaultFeatures: function() { return /* binding */ setDefaultFeatures; }
  109. /* harmony export */ });
  110. /* harmony import */ var _sv443_network_userutils__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @sv443-network/userutils */ "./node_modules/@sv443-network/userutils/dist/index.mjs");
  111. /* harmony import */ var _features_index__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./features/index */ "./src/features/index.ts");
  112. /* harmony import */ var _utils__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./utils */ "./src/utils.ts");
  113. /* harmony import */ var _events__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./events */ "./src/events.ts");
  114. var __awaiter = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) {
  115. function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
  116. return new (P || (P = Promise))(function (resolve, reject) {
  117. function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
  118. function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
  119. function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
  120. step((generator = generator.apply(thisArg, _arguments || [])).next());
  121. });
  122. };
  123. /** If this number is incremented, the features object data will be migrated to the new format */
  124. const formatVersion = 3;
  125. /** Config data format migration dictionary */
  126. const migrations = {
  127. // 1 -> 2
  128. 2: (oldData) => {
  129. const queueBtnsEnabled = Boolean(oldData.queueButtons);
  130. delete oldData.queueButtons;
  131. return Object.assign(Object.assign({}, oldData), { deleteFromQueueButton: queueBtnsEnabled, lyricsQueueButton: queueBtnsEnabled });
  132. },
  133. // 2 -> 3
  134. 3: (oldData) => (Object.assign(Object.assign({}, oldData), { removeShareTrackingParam: true, numKeysSkipToTime: true })),
  135. };
  136. const defaultConfig = Object.keys(_features_index__WEBPACK_IMPORTED_MODULE_1__.featInfo)
  137. .reduce((acc, key) => {
  138. acc[key] = _features_index__WEBPACK_IMPORTED_MODULE_1__.featInfo[key].default;
  139. return acc;
  140. }, {});
  141. const cfgMgr = new _sv443_network_userutils__WEBPACK_IMPORTED_MODULE_0__.ConfigManager({
  142. id: "bytm-config",
  143. formatVersion,
  144. defaultConfig,
  145. migrations,
  146. });
  147. /** Initializes the ConfigManager instance and loads persistent data into memory */
  148. function initConfig() {
  149. return __awaiter(this, void 0, void 0, function* () {
  150. const oldFmtVer = Number(yield GM.getValue(`_uucfgver-${cfgMgr.id}`, NaN));
  151. const data = yield cfgMgr.loadData();
  152. (0,_utils__WEBPACK_IMPORTED_MODULE_2__.log)(`Initialized ConfigManager (format version = ${cfgMgr.formatVersion})`);
  153. if (isNaN(oldFmtVer))
  154. (0,_utils__WEBPACK_IMPORTED_MODULE_2__.info)("Config data initialized with default values");
  155. else if (oldFmtVer !== cfgMgr.formatVersion)
  156. (0,_utils__WEBPACK_IMPORTED_MODULE_2__.info)(`Config data migrated from version ${oldFmtVer} to ${cfgMgr.formatVersion}`);
  157. return data;
  158. });
  159. }
  160. /** Returns the current feature config from the in-memory cache */
  161. function getFeatures() {
  162. return cfgMgr.getData();
  163. }
  164. /** Saves the feature config synchronously to the in-memory cache and asynchronously to the persistent storage */
  165. function saveFeatures(featureConf) {
  166. return __awaiter(this, void 0, void 0, function* () {
  167. yield cfgMgr.setData(featureConf);
  168. _events__WEBPACK_IMPORTED_MODULE_3__.siteEvents.emit("configChanged", cfgMgr.getData());
  169. (0,_utils__WEBPACK_IMPORTED_MODULE_2__.info)("Saved new feature config:", featureConf);
  170. });
  171. }
  172. /** Saves the default feature config synchronously to the in-memory cache and asynchronously to persistent storage */
  173. function setDefaultFeatures() {
  174. return __awaiter(this, void 0, void 0, function* () {
  175. yield cfgMgr.saveDefaultData();
  176. _events__WEBPACK_IMPORTED_MODULE_3__.siteEvents.emit("configChanged", cfgMgr.getData());
  177. (0,_utils__WEBPACK_IMPORTED_MODULE_2__.info)("Reset feature config to its default values");
  178. });
  179. }
  180. /** 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 */
  181. function clearConfig() {
  182. return __awaiter(this, void 0, void 0, function* () {
  183. yield cfgMgr.deleteConfig();
  184. (0,_utils__WEBPACK_IMPORTED_MODULE_2__.info)("Deleted config from persistent storage");
  185. });
  186. }
  187. /***/ }),
  188. /***/ "./src/constants.ts":
  189. /*!**************************!*\
  190. !*** ./src/constants.ts ***!
  191. \**************************/
  192. /***/ (function(__unused_webpack_module, __webpack_exports__, __webpack_require__) {
  193. __webpack_require__.r(__webpack_exports__);
  194. /* harmony export */ __webpack_require__.d(__webpack_exports__, {
  195. /* harmony export */ branch: function() { return /* binding */ branch; },
  196. /* harmony export */ logLevel: function() { return /* binding */ logLevel; },
  197. /* harmony export */ mode: function() { return /* binding */ mode; },
  198. /* harmony export */ scriptInfo: function() { return /* binding */ scriptInfo; }
  199. /* harmony export */ });
  200. const modeRaw = "development";
  201. const branchRaw = "develop";
  202. /** The mode in which the script was built (production or development) */
  203. const mode = (modeRaw.match(/^{{.+}}$/) ? "production" : modeRaw);
  204. /** The branch to use in various URLs that point to the GitHub repo */
  205. const branch = (branchRaw.match(/^{{.+}}$/) ? "main" : branchRaw);
  206. /**
  207. * How much info should be logged to the devtools console
  208. * 0 = Debug (show everything) or 1 = Info (show only important stuff)
  209. */
  210. const logLevel = mode === "production" ? 1 : 0;
  211. /** Info about the userscript, parsed from the userscript header (tools/post-build.js) */
  212. const scriptInfo = {
  213. name: GM.info.script.name,
  214. version: GM.info.script.version,
  215. namespace: GM.info.script.namespace,
  216. lastCommit: "c433064", // assert as generic string instead of literal
  217. };
  218. /***/ }),
  219. /***/ "./src/events.ts":
  220. /*!***********************!*\
  221. !*** ./src/events.ts ***!
  222. \***********************/
  223. /***/ (function(__unused_webpack_module, __webpack_exports__, __webpack_require__) {
  224. __webpack_require__.r(__webpack_exports__);
  225. /* harmony export */ __webpack_require__.d(__webpack_exports__, {
  226. /* harmony export */ initSiteEvents: function() { return /* binding */ initSiteEvents; },
  227. /* harmony export */ removeAllObservers: function() { return /* binding */ removeAllObservers; },
  228. /* harmony export */ siteEvents: function() { return /* binding */ siteEvents; }
  229. /* harmony export */ });
  230. /* harmony import */ var nanoevents__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! nanoevents */ "./node_modules/nanoevents/index.js");
  231. /* harmony import */ var _utils__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./utils */ "./src/utils.ts");
  232. var __awaiter = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) {
  233. function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
  234. return new (P || (P = Promise))(function (resolve, reject) {
  235. function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
  236. function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
  237. function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
  238. step((generator = generator.apply(thisArg, _arguments || [])).next());
  239. });
  240. };
  241. /** EventEmitter instance that is used to detect changes to the site */
  242. const siteEvents = (0,nanoevents__WEBPACK_IMPORTED_MODULE_1__.createNanoEvents)();
  243. let observers = [];
  244. /** Disconnects and deletes all observers. Run `initSiteEvents()` again to create new ones. */
  245. function removeAllObservers() {
  246. observers.forEach((observer, i) => {
  247. observer.disconnect();
  248. delete observers[i];
  249. });
  250. observers = [];
  251. }
  252. /** Creates MutationObservers that check if parts of the site have changed, then emit an event on the `siteEvents` instance. */
  253. function initSiteEvents() {
  254. return __awaiter(this, void 0, void 0, function* () {
  255. try {
  256. //#SECTION queue
  257. // the queue container always exists so it doesn't need the extra init function
  258. const queueObs = new MutationObserver(([{ addedNodes, removedNodes, target }]) => {
  259. if (addedNodes.length > 0 || removedNodes.length > 0) {
  260. (0,_utils__WEBPACK_IMPORTED_MODULE_0__.info)(`Detected queue change - added nodes: ${[...addedNodes.values()].length} - removed nodes: ${[...removedNodes.values()].length}`);
  261. siteEvents.emit("queueChanged", target);
  262. }
  263. });
  264. // only observe added or removed elements
  265. queueObs.observe(document.querySelector(".side-panel.modular #contents.ytmusic-player-queue"), {
  266. childList: true,
  267. });
  268. const autoplayObs = new MutationObserver(([{ addedNodes, removedNodes, target }]) => {
  269. if (addedNodes.length > 0 || removedNodes.length > 0) {
  270. (0,_utils__WEBPACK_IMPORTED_MODULE_0__.info)(`Detected autoplay queue change - added nodes: ${[...addedNodes.values()].length} - removed nodes: ${[...removedNodes.values()].length}`);
  271. siteEvents.emit("autoplayQueueChanged", target);
  272. }
  273. });
  274. autoplayObs.observe(document.querySelector(".side-panel.modular ytmusic-player-queue #automix-contents"), {
  275. childList: true,
  276. });
  277. //#SECTION home page observers
  278. initHomeObservers();
  279. (0,_utils__WEBPACK_IMPORTED_MODULE_0__.info)("Successfully initialized SiteEvents observers");
  280. observers = observers.concat([
  281. queueObs,
  282. autoplayObs,
  283. ]);
  284. }
  285. catch (err) {
  286. (0,_utils__WEBPACK_IMPORTED_MODULE_0__.error)("Couldn't initialize SiteEvents observers due to an error:\n", err);
  287. }
  288. });
  289. }
  290. /**
  291. * The home page might not exist yet if the site was accessed through any path like /watch directly.
  292. * This function will keep waiting for when the home page exists, then create the necessary MutationObservers.
  293. */
  294. function initHomeObservers() {
  295. var _a;
  296. return __awaiter(this, void 0, void 0, function* () {
  297. let interval;
  298. // hidden="" attribute is only present if the content of the page doesn't exist yet
  299. // so this pauses execution until that attribute is removed
  300. if ((_a = document.querySelector("ytmusic-browse-response#browse-page")) === null || _a === void 0 ? void 0 : _a.hasAttribute("hidden")) {
  301. yield new Promise((res) => {
  302. interval = setInterval(() => {
  303. var _a;
  304. if (!((_a = document.querySelector("ytmusic-browse-response#browse-page")) === null || _a === void 0 ? void 0 : _a.hasAttribute("hidden"))) {
  305. clearInterval(interval);
  306. res();
  307. }
  308. }, 50);
  309. });
  310. }
  311. siteEvents.emit("homePageLoaded");
  312. (0,_utils__WEBPACK_IMPORTED_MODULE_0__.info)("Initialized home page observers");
  313. //#SECTION carousel shelves
  314. const shelfContainerObs = new MutationObserver(([{ addedNodes, removedNodes }]) => {
  315. if (addedNodes.length > 0 || removedNodes.length > 0) {
  316. (0,_utils__WEBPACK_IMPORTED_MODULE_0__.info)("Detected carousel shelf container change - added nodes:", addedNodes.length, "- removed nodes:", removedNodes.length);
  317. siteEvents.emit("carouselShelvesChanged", { addedNodes, removedNodes });
  318. }
  319. });
  320. shelfContainerObs.observe(document.querySelector("#contents.ytmusic-section-list-renderer"), {
  321. childList: true,
  322. });
  323. observers.push(shelfContainerObs);
  324. });
  325. }
  326. /***/ }),
  327. /***/ "./src/features/index.ts":
  328. /*!*******************************!*\
  329. !*** ./src/features/index.ts ***!
  330. \*******************************/
  331. /***/ (function(__unused_webpack_module, __webpack_exports__, __webpack_require__) {
  332. __webpack_require__.r(__webpack_exports__);
  333. /* harmony export */ __webpack_require__.d(__webpack_exports__, {
  334. /* harmony export */ addAnchorImprovements: function() { return /* reexport safe */ _layout__WEBPACK_IMPORTED_MODULE_2__.addAnchorImprovements; },
  335. /* harmony export */ addChangelogMenu: function() { return /* reexport safe */ _menu_menu_old__WEBPACK_IMPORTED_MODULE_5__.addChangelogMenu; },
  336. /* harmony export */ addConfigMenuOption: function() { return /* reexport safe */ _layout__WEBPACK_IMPORTED_MODULE_2__.addConfigMenuOption; },
  337. /* harmony export */ addExportMenu: function() { return /* reexport safe */ _menu_menu_old__WEBPACK_IMPORTED_MODULE_5__.addExportMenu; },
  338. /* harmony export */ addImportMenu: function() { return /* reexport safe */ _menu_menu_old__WEBPACK_IMPORTED_MODULE_5__.addImportMenu; },
  339. /* harmony export */ addLyricsCacheEntry: function() { return /* reexport safe */ _lyrics__WEBPACK_IMPORTED_MODULE_3__.addLyricsCacheEntry; },
  340. /* harmony export */ addMediaCtrlLyricsBtn: function() { return /* reexport safe */ _lyrics__WEBPACK_IMPORTED_MODULE_3__.addMediaCtrlLyricsBtn; },
  341. /* harmony export */ addMenu: function() { return /* reexport safe */ _menu_menu_old__WEBPACK_IMPORTED_MODULE_5__.addMenu; },
  342. /* harmony export */ addWatermark: function() { return /* reexport safe */ _layout__WEBPACK_IMPORTED_MODULE_2__.addWatermark; },
  343. /* harmony export */ categoryNames: function() { return /* binding */ categoryNames; },
  344. /* harmony export */ closeMenu: function() { return /* reexport safe */ _menu_menu_old__WEBPACK_IMPORTED_MODULE_5__.closeMenu; },
  345. /* harmony export */ createLyricsBtn: function() { return /* reexport safe */ _lyrics__WEBPACK_IMPORTED_MODULE_3__.createLyricsBtn; },
  346. /* harmony export */ disableBeforeUnload: function() { return /* reexport safe */ _input__WEBPACK_IMPORTED_MODULE_1__.disableBeforeUnload; },
  347. /* harmony export */ enableBeforeUnload: function() { return /* reexport safe */ _input__WEBPACK_IMPORTED_MODULE_1__.enableBeforeUnload; },
  348. /* harmony export */ featInfo: function() { return /* binding */ featInfo; },
  349. /* harmony export */ geniUrlBase: function() { return /* reexport safe */ _lyrics__WEBPACK_IMPORTED_MODULE_3__.geniUrlBase; },
  350. /* harmony export */ getCurrentLyricsUrl: function() { return /* reexport safe */ _lyrics__WEBPACK_IMPORTED_MODULE_3__.getCurrentLyricsUrl; },
  351. /* harmony export */ getGeniusUrl: function() { return /* reexport safe */ _lyrics__WEBPACK_IMPORTED_MODULE_3__.getGeniusUrl; },
  352. /* harmony export */ getLyricsCacheEntry: function() { return /* reexport safe */ _lyrics__WEBPACK_IMPORTED_MODULE_3__.getLyricsCacheEntry; },
  353. /* harmony export */ initArrowKeySkip: function() { return /* reexport safe */ _input__WEBPACK_IMPORTED_MODULE_1__.initArrowKeySkip; },
  354. /* harmony export */ initAutoCloseToasts: function() { return /* reexport safe */ _layout__WEBPACK_IMPORTED_MODULE_2__.initAutoCloseToasts; },
  355. /* harmony export */ initBeforeUnloadHook: function() { return /* reexport safe */ _input__WEBPACK_IMPORTED_MODULE_1__.initBeforeUnloadHook; },
  356. /* harmony export */ initMenu: function() { return /* reexport safe */ _menu_menu__WEBPACK_IMPORTED_MODULE_4__.initMenu; },
  357. /* harmony export */ initNumKeysSkip: function() { return /* reexport safe */ _input__WEBPACK_IMPORTED_MODULE_1__.initNumKeysSkip; },
  358. /* harmony export */ initQueueButtons: function() { return /* reexport safe */ _layout__WEBPACK_IMPORTED_MODULE_2__.initQueueButtons; },
  359. /* harmony export */ initSiteSwitch: function() { return /* reexport safe */ _input__WEBPACK_IMPORTED_MODULE_1__.initSiteSwitch; },
  360. /* harmony export */ initVolumeFeatures: function() { return /* reexport safe */ _layout__WEBPACK_IMPORTED_MODULE_2__.initVolumeFeatures; },
  361. /* harmony export */ isMenuOpen: function() { return /* reexport safe */ _menu_menu_old__WEBPACK_IMPORTED_MODULE_5__.isMenuOpen; },
  362. /* harmony export */ openMenu: function() { return /* reexport safe */ _menu_menu_old__WEBPACK_IMPORTED_MODULE_5__.openMenu; },
  363. /* harmony export */ preInitLayout: function() { return /* reexport safe */ _layout__WEBPACK_IMPORTED_MODULE_2__.preInitLayout; },
  364. /* harmony export */ removeShareTrackingParam: function() { return /* reexport safe */ _layout__WEBPACK_IMPORTED_MODULE_2__.removeShareTrackingParam; },
  365. /* harmony export */ removeUpgradeTab: function() { return /* reexport safe */ _layout__WEBPACK_IMPORTED_MODULE_2__.removeUpgradeTab; },
  366. /* harmony export */ sanitizeArtists: function() { return /* reexport safe */ _lyrics__WEBPACK_IMPORTED_MODULE_3__.sanitizeArtists; },
  367. /* harmony export */ sanitizeSong: function() { return /* reexport safe */ _lyrics__WEBPACK_IMPORTED_MODULE_3__.sanitizeSong; },
  368. /* harmony export */ splitVideoTitle: function() { return /* reexport safe */ _lyrics__WEBPACK_IMPORTED_MODULE_3__.splitVideoTitle; }
  369. /* harmony export */ });
  370. /* harmony import */ var _constants__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../constants */ "./src/constants.ts");
  371. /* harmony import */ var _input__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./input */ "./src/features/input.ts");
  372. /* harmony import */ var _layout__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./layout */ "./src/features/layout.ts");
  373. /* harmony import */ var _lyrics__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./lyrics */ "./src/features/lyrics.ts");
  374. /* harmony import */ var _menu_menu__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../menu/menu */ "./src/menu/menu.ts");
  375. /* harmony import */ var _menu_menu_old__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../menu/menu_old */ "./src/menu/menu_old.ts");
  376. /** Mapping of feature category identifiers to readable strings */
  377. const categoryNames = {
  378. input: "Input",
  379. layout: "Layout",
  380. lyrics: "Lyrics",
  381. };
  382. /** Contains all possible features with their default values and other configuration */
  383. const featInfo = {
  384. //#SECTION layout
  385. removeUpgradeTab: {
  386. desc: "Remove the Upgrade / Premium tab",
  387. type: "toggle",
  388. category: "layout",
  389. default: true,
  390. },
  391. volumeSliderLabel: {
  392. desc: "Add a percentage label next to the volume slider",
  393. type: "toggle",
  394. category: "layout",
  395. default: true,
  396. },
  397. volumeSliderSize: {
  398. desc: "The width of the volume slider in pixels",
  399. type: "number",
  400. category: "layout",
  401. min: 50,
  402. max: 500,
  403. step: 5,
  404. default: 150,
  405. unit: "px",
  406. },
  407. volumeSliderStep: {
  408. desc: "Volume slider sensitivity (by how little percent the volume can be changed at a time)",
  409. type: "slider",
  410. category: "layout",
  411. min: 1,
  412. max: 25,
  413. default: 2,
  414. unit: "%",
  415. },
  416. watermarkEnabled: {
  417. desc: `Show a ${_constants__WEBPACK_IMPORTED_MODULE_0__.scriptInfo.name} watermark under the site logo that opens this config menu`,
  418. type: "toggle",
  419. category: "layout",
  420. default: true,
  421. },
  422. deleteFromQueueButton: {
  423. desc: "Add a button to each song in the queue to quickly remove it",
  424. type: "toggle",
  425. category: "layout",
  426. default: true,
  427. },
  428. closeToastsTimeout: {
  429. desc: "After how many seconds to close permanent notifications - 0 to only close them manually (default behavior)",
  430. type: "number",
  431. category: "layout",
  432. min: 0,
  433. max: 30,
  434. step: 0.5,
  435. default: 0,
  436. unit: "s",
  437. },
  438. removeShareTrackingParam: {
  439. desc: "Remove the tracking parameter (&si=...) from links in the share popup",
  440. type: "toggle",
  441. category: "layout",
  442. default: true,
  443. },
  444. //#SECTION input
  445. arrowKeySupport: {
  446. desc: "Use arrow keys to skip forwards and backwards by 10 seconds",
  447. type: "toggle",
  448. category: "input",
  449. default: true,
  450. },
  451. switchBetweenSites: {
  452. desc: "Add F9 as a hotkey to switch between the YT and YTM sites on a video / song",
  453. type: "toggle",
  454. category: "input",
  455. default: true,
  456. },
  457. switchSitesHotkey: {
  458. hidden: true,
  459. desc: "TODO(v1.1): Which hotkey needs to be pressed to switch sites?",
  460. type: "hotkey",
  461. category: "input",
  462. default: {
  463. key: "F9",
  464. shift: false,
  465. ctrl: false,
  466. meta: false,
  467. },
  468. },
  469. disableBeforeUnloadPopup: {
  470. desc: "Prevent the confirmation popup that appears when trying to leave the site while a song is playing",
  471. type: "toggle",
  472. category: "input",
  473. default: false,
  474. },
  475. anchorImprovements: {
  476. desc: "TODO:FIXME: Add link elements all over the page so things can be opened in a new tab easier",
  477. type: "toggle",
  478. category: "input",
  479. default: true,
  480. },
  481. numKeysSkipToTime: {
  482. desc: "Enable skipping to a specific time in the video by pressing a number key (0-9)",
  483. type: "toggle",
  484. category: "input",
  485. default: true,
  486. },
  487. //#SECTION lyrics
  488. geniusLyrics: {
  489. desc: "Add a button to the media controls of the currently playing song to open its lyrics on genius.com",
  490. type: "toggle",
  491. category: "lyrics",
  492. default: true,
  493. },
  494. lyricsQueueButton: {
  495. desc: "Add a button to each song in the queue to quickly open its lyrics page",
  496. type: "toggle",
  497. category: "lyrics",
  498. default: true,
  499. },
  500. };
  501. /***/ }),
  502. /***/ "./src/features/input.ts":
  503. /*!*******************************!*\
  504. !*** ./src/features/input.ts ***!
  505. \*******************************/
  506. /***/ (function(__unused_webpack_module, __webpack_exports__, __webpack_require__) {
  507. __webpack_require__.r(__webpack_exports__);
  508. /* harmony export */ __webpack_require__.d(__webpack_exports__, {
  509. /* harmony export */ disableBeforeUnload: function() { return /* binding */ disableBeforeUnload; },
  510. /* harmony export */ enableBeforeUnload: function() { return /* binding */ enableBeforeUnload; },
  511. /* harmony export */ initArrowKeySkip: function() { return /* binding */ initArrowKeySkip; },
  512. /* harmony export */ initBeforeUnloadHook: function() { return /* binding */ initBeforeUnloadHook; },
  513. /* harmony export */ initNumKeysSkip: function() { return /* binding */ initNumKeysSkip; },
  514. /* harmony export */ initSiteSwitch: function() { return /* binding */ initSiteSwitch; }
  515. /* harmony export */ });
  516. /* harmony import */ var _sv443_network_userutils__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @sv443-network/userutils */ "./node_modules/@sv443-network/userutils/dist/index.mjs");
  517. /* harmony import */ var _utils__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../utils */ "./src/utils.ts");
  518. /* harmony import */ var _menu_menu_old__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../menu/menu_old */ "./src/menu/menu_old.ts");
  519. var __awaiter = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) {
  520. function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
  521. return new (P || (P = Promise))(function (resolve, reject) {
  522. function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
  523. function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
  524. function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
  525. step((generator = generator.apply(thisArg, _arguments || [])).next());
  526. });
  527. };
  528. //#MARKER arrow key skip
  529. function initArrowKeySkip() {
  530. document.addEventListener("keydown", (evt) => {
  531. var _a, _b, _c;
  532. if (!["ArrowLeft", "ArrowRight"].includes(evt.code))
  533. return;
  534. // discard the event when a (text) input is currently active, like when editing a playlist
  535. if (["INPUT", "TEXTAREA", "SELECT"].includes((_b = (_a = document.activeElement) === null || _a === void 0 ? void 0 : _a.tagName) !== null && _b !== void 0 ? _b : "_"))
  536. return (0,_utils__WEBPACK_IMPORTED_MODULE_1__.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`);
  537. onArrowKeyPress(evt);
  538. });
  539. (0,_utils__WEBPACK_IMPORTED_MODULE_1__.log)("Added arrow key press listener");
  540. }
  541. /** Called when the user presses any key, anywhere */
  542. function onArrowKeyPress(evt) {
  543. (0,_utils__WEBPACK_IMPORTED_MODULE_1__.log)(`Captured key '${evt.code}' in proxy listener`);
  544. // ripped this stuff from the console, most of these are probably unnecessary but this was finnicky af and I am sick and tired of trial and error
  545. const defaultProps = {
  546. altKey: false,
  547. ctrlKey: false,
  548. metaKey: false,
  549. shiftKey: false,
  550. target: document.body,
  551. currentTarget: document.body,
  552. originalTarget: document.body,
  553. explicitOriginalTarget: document.body,
  554. srcElement: document.body,
  555. type: "keydown",
  556. bubbles: true,
  557. cancelBubble: false,
  558. cancelable: true,
  559. isTrusted: true,
  560. repeat: false,
  561. // needed because otherwise YTM errors out - see https://github.com/Sv443/BetterYTM/issues/18#show_issue
  562. view: (0,_sv443_network_userutils__WEBPACK_IMPORTED_MODULE_0__.getUnsafeWindow)(),
  563. };
  564. let invalidKey = false;
  565. let keyProps = {};
  566. switch (evt.code) {
  567. case "ArrowLeft":
  568. keyProps = {
  569. code: "KeyH",
  570. key: "h",
  571. keyCode: 72,
  572. which: 72,
  573. };
  574. break;
  575. case "ArrowRight":
  576. keyProps = {
  577. code: "KeyL",
  578. key: "l",
  579. keyCode: 76,
  580. which: 76,
  581. };
  582. break;
  583. default:
  584. invalidKey = true;
  585. break;
  586. }
  587. if (!invalidKey) {
  588. const proxyProps = Object.assign(Object.assign({ code: "" }, defaultProps), keyProps);
  589. document.body.dispatchEvent(new KeyboardEvent("keydown", proxyProps));
  590. (0,_utils__WEBPACK_IMPORTED_MODULE_1__.log)(`Dispatched proxy keydown event: [${evt.code}] -> [${proxyProps.code}]`);
  591. }
  592. else
  593. (0,_utils__WEBPACK_IMPORTED_MODULE_1__.warn)(`Captured key '${evt.code}' has no defined behavior`);
  594. }
  595. //#MARKER site switch
  596. /** switch sites only if current video time is greater than this value */
  597. const videoTimeThreshold = 3;
  598. /** Initializes the site switch feature */
  599. function initSiteSwitch(domain) {
  600. document.addEventListener("keydown", (e) => {
  601. if (e.key === "F9")
  602. switchSite(domain === "yt" ? "ytm" : "yt");
  603. });
  604. (0,_utils__WEBPACK_IMPORTED_MODULE_1__.log)("Initialized site switch listener");
  605. }
  606. /** Switches to the other site (between YT and YTM) */
  607. function switchSite(newDomain) {
  608. return __awaiter(this, void 0, void 0, function* () {
  609. try {
  610. if (newDomain === "ytm" && !location.href.includes("/watch"))
  611. return (0,_utils__WEBPACK_IMPORTED_MODULE_1__.warn)("Not on a video page, so the site switch is ignored");
  612. let subdomain;
  613. if (newDomain === "ytm")
  614. subdomain = "music";
  615. else if (newDomain === "yt")
  616. subdomain = "www";
  617. if (!subdomain)
  618. throw new Error(`Unrecognized domain '${newDomain}'`);
  619. disableBeforeUnload();
  620. const { pathname, search, hash } = new URL(location.href);
  621. const vt = yield (0,_utils__WEBPACK_IMPORTED_MODULE_1__.getVideoTime)();
  622. (0,_utils__WEBPACK_IMPORTED_MODULE_1__.log)(`Found video time of ${vt} seconds`);
  623. const cleanSearch = search.split("&")
  624. .filter((param) => !param.match(/^\??t=/))
  625. .join("&");
  626. const newSearch = typeof vt === "number" && vt > videoTimeThreshold ?
  627. cleanSearch.includes("?")
  628. ? `${cleanSearch.startsWith("?")
  629. ? cleanSearch
  630. : "?" + cleanSearch}&t=${vt - 1}`
  631. : `?t=${vt - 1}`
  632. : cleanSearch;
  633. const newUrl = `https://${subdomain}.youtube.com${pathname}${newSearch}${hash}`;
  634. (0,_utils__WEBPACK_IMPORTED_MODULE_1__.info)(`Switching to domain '${newDomain}' at ${newUrl}`);
  635. location.assign(newUrl);
  636. }
  637. catch (err) {
  638. (0,_utils__WEBPACK_IMPORTED_MODULE_1__.error)("Error while switching site:", err);
  639. }
  640. });
  641. }
  642. //#MARKER beforeunload popup
  643. let beforeUnloadEnabled = true;
  644. /** Disables the popup before leaving the site */
  645. function disableBeforeUnload() {
  646. beforeUnloadEnabled = false;
  647. (0,_utils__WEBPACK_IMPORTED_MODULE_1__.info)("Disabled popup before leaving the site");
  648. }
  649. /** (Re-)enables the popup before leaving the site */
  650. function enableBeforeUnload() {
  651. beforeUnloadEnabled = true;
  652. (0,_utils__WEBPACK_IMPORTED_MODULE_1__.info)("Enabled popup before leaving the site");
  653. }
  654. /**
  655. * Adds a spy function into `window.__proto__.addEventListener` to selectively discard `beforeunload`
  656. * event listeners before they can be called by the site.
  657. */
  658. function initBeforeUnloadHook() {
  659. Error.stackTraceLimit = 1000; // default is 25 on FF so this should hopefully be more than enough
  660. (function (original) {
  661. // @ts-ignore
  662. window.__proto__.addEventListener = function (...args) {
  663. const origListener = typeof args[1] === "function" ? args[1] : args[1].handleEvent;
  664. args[1] = function (...a) {
  665. if (!beforeUnloadEnabled && args[0] === "beforeunload")
  666. return (0,_utils__WEBPACK_IMPORTED_MODULE_1__.info)("Prevented beforeunload event listener from being called");
  667. else
  668. return origListener.apply(this, a);
  669. };
  670. original.apply(this, args);
  671. };
  672. // @ts-ignore
  673. })(window.__proto__.addEventListener);
  674. }
  675. //#MARKER number keys skip to time
  676. /** Adds the ability to skip to a certain time in the video by pressing a number key (0-9) */
  677. function initNumKeysSkip() {
  678. document.addEventListener("keydown", (e) => {
  679. var _a, _b, _c, _d;
  680. if (!e.key.trim().match(/^[0-9]$/))
  681. return;
  682. if (_menu_menu_old__WEBPACK_IMPORTED_MODULE_2__.isMenuOpen)
  683. return;
  684. // discard the event when a (text) input is currently active, like when editing a playlist or when the search bar is focused
  685. if (document.activeElement !== document.body
  686. && !["progress-bar"].includes((_b = (_a = document.activeElement) === null || _a === void 0 ? void 0 : _a.id) !== null && _b !== void 0 ? _b : "_")
  687. && !["BUTTON", "A"].includes((_d = (_c = document.activeElement) === null || _c === void 0 ? void 0 : _c.tagName) !== null && _d !== void 0 ? _d : "_"))
  688. return (0,_utils__WEBPACK_IMPORTED_MODULE_1__.info)("Captured valid key to skip video to but an unexpected element is focused, so the keypress is ignored");
  689. skipToTimeKey(Number(e.key));
  690. });
  691. (0,_utils__WEBPACK_IMPORTED_MODULE_1__.log)("Added number key press listener");
  692. }
  693. /** Emulates a click on the video progress bar at the position calculated from the passed time key (0-9) */
  694. function skipToTimeKey(key) {
  695. const getX = (timeKey, maxWidth) => {
  696. if (timeKey >= 10)
  697. return maxWidth;
  698. return Math.floor((maxWidth / 10) * timeKey);
  699. };
  700. /** Calculate offsets of the bounding client rect of the passed element - see https://stackoverflow.com/a/442474/11187044 */
  701. const getOffsetRect = (elem) => {
  702. let left = 0;
  703. let top = 0;
  704. const rect = elem.getBoundingClientRect();
  705. while (elem && !isNaN(elem.offsetLeft) && !isNaN(elem.offsetTop)) {
  706. left += elem.offsetLeft - elem.scrollLeft;
  707. top += elem.offsetTop - elem.scrollTop;
  708. elem = elem.offsetParent;
  709. }
  710. return {
  711. top,
  712. left,
  713. width: rect.width,
  714. height: rect.height,
  715. };
  716. };
  717. // not technically a progress element but behaves pretty much the same
  718. const progressElem = document.querySelector("tp-yt-paper-slider#progress-bar tp-yt-paper-progress#sliderBar");
  719. if (!progressElem)
  720. return;
  721. const rect = getOffsetRect(progressElem);
  722. const x = getX(key, rect.width);
  723. const y = rect.top - rect.height / 2;
  724. (0,_utils__WEBPACK_IMPORTED_MODULE_1__.log)(`Skipping to time key ${key} (x offset: ${x}px of ${rect.width}px)`);
  725. const evt = new MouseEvent("mousedown", {
  726. clientX: x,
  727. clientY: y,
  728. // @ts-ignore
  729. layerX: x,
  730. layerY: rect.height / 2,
  731. target: progressElem,
  732. bubbles: true,
  733. shiftKey: false,
  734. ctrlKey: false,
  735. altKey: false,
  736. metaKey: false,
  737. button: 0,
  738. buttons: 1,
  739. which: 1,
  740. isTrusted: true,
  741. offsetX: 0,
  742. offsetY: 0,
  743. // needed because otherwise YTM errors out - see https://github.com/Sv443/BetterYTM/issues/18#show_issue
  744. view: (0,_sv443_network_userutils__WEBPACK_IMPORTED_MODULE_0__.getUnsafeWindow)(),
  745. });
  746. progressElem.dispatchEvent(evt);
  747. }
  748. /***/ }),
  749. /***/ "./src/features/layout.ts":
  750. /*!********************************!*\
  751. !*** ./src/features/layout.ts ***!
  752. \********************************/
  753. /***/ (function(__unused_webpack_module, __webpack_exports__, __webpack_require__) {
  754. __webpack_require__.r(__webpack_exports__);
  755. /* harmony export */ __webpack_require__.d(__webpack_exports__, {
  756. /* harmony export */ addAnchorImprovements: function() { return /* binding */ addAnchorImprovements; },
  757. /* harmony export */ addConfigMenuOption: function() { return /* binding */ addConfigMenuOption; },
  758. /* harmony export */ addWatermark: function() { return /* binding */ addWatermark; },
  759. /* harmony export */ initAutoCloseToasts: function() { return /* binding */ initAutoCloseToasts; },
  760. /* harmony export */ initQueueButtons: function() { return /* binding */ initQueueButtons; },
  761. /* harmony export */ initVolumeFeatures: function() { return /* binding */ initVolumeFeatures; },
  762. /* harmony export */ preInitLayout: function() { return /* binding */ preInitLayout; },
  763. /* harmony export */ removeShareTrackingParam: function() { return /* binding */ removeShareTrackingParam; },
  764. /* harmony export */ removeUpgradeTab: function() { return /* binding */ removeUpgradeTab; }
  765. /* harmony export */ });
  766. /* harmony import */ var _sv443_network_userutils__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @sv443-network/userutils */ "./node_modules/@sv443-network/userutils/dist/index.mjs");
  767. /* harmony import */ var _constants__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../constants */ "./src/constants.ts");
  768. /* harmony import */ var _utils__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../utils */ "./src/utils.ts");
  769. /* harmony import */ var _events__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../events */ "./src/events.ts");
  770. /* harmony import */ var _menu_menu_old__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../menu/menu_old */ "./src/menu/menu_old.ts");
  771. /* harmony import */ var _lyrics__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./lyrics */ "./src/features/lyrics.ts");
  772. /* harmony import */ var _index__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ./index */ "./src/features/index.ts");
  773. /* harmony import */ var _layout_css__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ./layout.css */ "./src/features/layout.css");
  774. var __awaiter = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) {
  775. function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
  776. return new (P || (P = Promise))(function (resolve, reject) {
  777. function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
  778. function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
  779. function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
  780. step((generator = generator.apply(thisArg, _arguments || [])).next());
  781. });
  782. };
  783. let features;
  784. function preInitLayout(feats) {
  785. features = feats;
  786. }
  787. //#MARKER BYTM-Config buttons
  788. let menuOpenAmt = 0, logoExchanged = false;
  789. /** Adds a watermark beneath the logo */
  790. function addWatermark() {
  791. const watermark = document.createElement("a");
  792. watermark.role = "button";
  793. watermark.id = "bytm-watermark";
  794. watermark.className = "style-scope ytmusic-nav-bar bytm-no-select";
  795. watermark.innerText = _constants__WEBPACK_IMPORTED_MODULE_1__.scriptInfo.name;
  796. watermark.title = "Open menu";
  797. watermark.tabIndex = 1000;
  798. improveLogo();
  799. watermark.addEventListener("click", (e) => {
  800. e.stopPropagation();
  801. menuOpenAmt++;
  802. if ((!e.shiftKey || logoExchanged) && menuOpenAmt !== 5)
  803. (0,_menu_menu_old__WEBPACK_IMPORTED_MODULE_4__.openMenu)();
  804. if ((!logoExchanged && e.shiftKey) || menuOpenAmt === 5)
  805. exchangeLogo();
  806. });
  807. // when using the tab key to navigate
  808. watermark.addEventListener("keydown", (e) => {
  809. if (e.key === "Enter") {
  810. e.stopPropagation();
  811. menuOpenAmt++;
  812. if ((!e.shiftKey || logoExchanged) && menuOpenAmt !== 5)
  813. (0,_menu_menu_old__WEBPACK_IMPORTED_MODULE_4__.openMenu)();
  814. if ((!logoExchanged && e.shiftKey) || menuOpenAmt === 5)
  815. exchangeLogo();
  816. }
  817. });
  818. const logoElem = document.querySelector("#left-content");
  819. (0,_sv443_network_userutils__WEBPACK_IMPORTED_MODULE_0__.insertAfter)(logoElem, watermark);
  820. (0,_utils__WEBPACK_IMPORTED_MODULE_2__.log)("Added watermark element");
  821. }
  822. /** Turns the regular `<img>`-based logo into inline SVG to be able to animate and modify parts of it */
  823. function improveLogo() {
  824. return __awaiter(this, void 0, void 0, function* () {
  825. try {
  826. const res = yield (0,_sv443_network_userutils__WEBPACK_IMPORTED_MODULE_0__.fetchAdvanced)("https://music.youtube.com/img/on_platform_logo_dark.svg");
  827. const svg = yield res.text();
  828. (0,_sv443_network_userutils__WEBPACK_IMPORTED_MODULE_0__.onSelector)("ytmusic-logo a", {
  829. listener: (logoElem) => {
  830. var _a;
  831. logoElem.classList.add("bytm-mod-logo", "bytm-no-select");
  832. logoElem.innerHTML = svg;
  833. logoElem.querySelectorAll("ellipse").forEach((e) => {
  834. e.classList.add("bytm-mod-logo-ellipse");
  835. });
  836. (_a = logoElem.querySelector("path")) === null || _a === void 0 ? void 0 : _a.classList.add("bytm-mod-logo-path");
  837. (0,_utils__WEBPACK_IMPORTED_MODULE_2__.log)("Swapped logo to inline SVG");
  838. },
  839. });
  840. }
  841. catch (err) {
  842. (0,_utils__WEBPACK_IMPORTED_MODULE_2__.error)("Couldn't improve logo due to an error:", err);
  843. }
  844. });
  845. }
  846. /** Exchanges the default YTM logo into BetterYTM's logo with a sick ass animation */
  847. function exchangeLogo() {
  848. (0,_sv443_network_userutils__WEBPACK_IMPORTED_MODULE_0__.onSelector)(".bytm-mod-logo", {
  849. listener: (logoElem) => __awaiter(this, void 0, void 0, function* () {
  850. if (logoElem.classList.contains("bytm-logo-exchanged"))
  851. return;
  852. logoExchanged = true;
  853. logoElem.classList.add("bytm-logo-exchanged");
  854. const iconUrl = yield (0,_utils__WEBPACK_IMPORTED_MODULE_2__.getResourceUrl)("icon");
  855. const newLogo = document.createElement("img");
  856. newLogo.className = "bytm-mod-logo-img";
  857. newLogo.src = iconUrl;
  858. logoElem.insertBefore(newLogo, logoElem.querySelector("svg"));
  859. document.head.querySelectorAll("link[rel=\"icon\"]").forEach((e) => {
  860. e.href = iconUrl;
  861. });
  862. setTimeout(() => {
  863. logoElem.querySelectorAll(".bytm-mod-logo-ellipse").forEach(e => e.remove());
  864. }, 1000);
  865. }),
  866. });
  867. }
  868. /** Called whenever the menu exists to add a BYTM-Configuration button to the user menu popover */
  869. function addConfigMenuOption(container) {
  870. return __awaiter(this, void 0, void 0, function* () {
  871. const cfgOptElem = document.createElement("div");
  872. cfgOptElem.role = "button";
  873. cfgOptElem.className = "bytm-cfg-menu-option";
  874. const cfgOptItemElem = document.createElement("div");
  875. cfgOptItemElem.className = "bytm-cfg-menu-option-item";
  876. cfgOptItemElem.ariaLabel = cfgOptItemElem.title = "Click to open BetterYTM's configuration menu";
  877. cfgOptItemElem.addEventListener("click", (e) => __awaiter(this, void 0, void 0, function* () {
  878. const settingsBtnElem = document.querySelector("ytmusic-nav-bar ytmusic-settings-button tp-yt-paper-icon-button");
  879. settingsBtnElem === null || settingsBtnElem === void 0 ? void 0 : settingsBtnElem.click();
  880. menuOpenAmt++;
  881. yield (0,_sv443_network_userutils__WEBPACK_IMPORTED_MODULE_0__.pauseFor)(100);
  882. if ((!e.shiftKey || logoExchanged) && menuOpenAmt !== 5)
  883. (0,_menu_menu_old__WEBPACK_IMPORTED_MODULE_4__.openMenu)();
  884. if ((!logoExchanged && e.shiftKey) || menuOpenAmt === 5)
  885. exchangeLogo();
  886. }));
  887. const cfgOptIconElem = document.createElement("img");
  888. cfgOptIconElem.className = "bytm-cfg-menu-option-icon";
  889. cfgOptIconElem.src = yield (0,_utils__WEBPACK_IMPORTED_MODULE_2__.getResourceUrl)("icon");
  890. const cfgOptTextElem = document.createElement("div");
  891. cfgOptTextElem.className = "bytm-cfg-menu-option-text";
  892. cfgOptTextElem.innerText = "BetterYTM Configuration";
  893. cfgOptItemElem.appendChild(cfgOptIconElem);
  894. cfgOptItemElem.appendChild(cfgOptTextElem);
  895. cfgOptElem.appendChild(cfgOptItemElem);
  896. container.appendChild(cfgOptElem);
  897. (0,_utils__WEBPACK_IMPORTED_MODULE_2__.log)("Added BYTM-Configuration button to menu popover");
  898. });
  899. }
  900. //#MARKER remove upgrade tab
  901. /** Removes the "Upgrade" / YT Music Premium tab from the sidebar */
  902. function removeUpgradeTab() {
  903. (0,_sv443_network_userutils__WEBPACK_IMPORTED_MODULE_0__.onSelector)("ytmusic-app-layout tp-yt-app-drawer #contentContainer #guide-content #items ytmusic-guide-entry-renderer:nth-of-type(4)", {
  904. listener: (tabElemLarge) => {
  905. tabElemLarge.remove();
  906. (0,_utils__WEBPACK_IMPORTED_MODULE_2__.log)("Removed large upgrade tab");
  907. },
  908. });
  909. (0,_sv443_network_userutils__WEBPACK_IMPORTED_MODULE_0__.onSelector)("ytmusic-app-layout #mini-guide ytmusic-guide-renderer #sections ytmusic-guide-section-renderer[is-primary] #items ytmusic-guide-entry-renderer:nth-of-type(4)", {
  910. listener: (tabElemSmall) => {
  911. tabElemSmall.remove();
  912. (0,_utils__WEBPACK_IMPORTED_MODULE_2__.log)("Removed small upgrade tab");
  913. },
  914. });
  915. }
  916. //#MARKER volume slider
  917. function initVolumeFeatures() {
  918. // not technically an input element but behaves pretty much the same
  919. (0,_sv443_network_userutils__WEBPACK_IMPORTED_MODULE_0__.onSelector)("tp-yt-paper-slider#volume-slider", {
  920. listener: (sliderElem) => {
  921. const volSliderCont = document.createElement("div");
  922. volSliderCont.id = "bytm-vol-slider-cont";
  923. (0,_sv443_network_userutils__WEBPACK_IMPORTED_MODULE_0__.addParent)(sliderElem, volSliderCont);
  924. if (typeof features.volumeSliderSize === "number")
  925. setVolSliderSize();
  926. if (features.volumeSliderLabel)
  927. addVolumeSliderLabel(sliderElem, volSliderCont);
  928. setVolSliderStep(sliderElem);
  929. },
  930. });
  931. }
  932. /** Adds a percentage label to the volume slider and tooltip */
  933. function addVolumeSliderLabel(sliderElem, sliderCont) {
  934. const labelElem = document.createElement("div");
  935. labelElem.className = "bytm-vol-slider-label";
  936. labelElem.innerText = `${sliderElem.value}%`;
  937. // prevent video from minimizing
  938. labelElem.addEventListener("click", (e) => e.stopPropagation());
  939. const getLabelTexts = (slider) => {
  940. const labelShort = `${slider.value}%`;
  941. const sensText = features.volumeSliderStep !== _index__WEBPACK_IMPORTED_MODULE_6__.featInfo.volumeSliderStep.default ? ` (Sensitivity: ${slider.step}%)` : "";
  942. const labelFull = `Volume: ${labelShort}${sensText}`;
  943. return { labelShort, labelFull };
  944. };
  945. const { labelFull } = getLabelTexts(sliderElem);
  946. sliderCont.setAttribute("title", labelFull);
  947. sliderElem.setAttribute("title", labelFull);
  948. sliderElem.setAttribute("aria-valuetext", labelFull);
  949. const updateLabel = () => {
  950. const { labelShort, labelFull } = getLabelTexts(sliderElem);
  951. sliderCont.setAttribute("title", labelFull);
  952. sliderElem.setAttribute("title", labelFull);
  953. sliderElem.setAttribute("aria-valuetext", labelFull);
  954. const labelElem2 = document.querySelector(".bytm-vol-slider-label");
  955. if (labelElem2)
  956. labelElem2.innerText = labelShort;
  957. };
  958. sliderElem.addEventListener("change", () => updateLabel());
  959. (0,_sv443_network_userutils__WEBPACK_IMPORTED_MODULE_0__.onSelector)("#bytm-vol-slider-cont", {
  960. listener: (volumeCont) => {
  961. volumeCont.appendChild(labelElem);
  962. },
  963. });
  964. let lastSliderVal = Number(sliderElem.value);
  965. // show label if hovering over slider or slider is focused
  966. const sliderHoverObserver = new MutationObserver(() => {
  967. if (sliderElem.classList.contains("on-hover") || document.activeElement === sliderElem)
  968. labelElem.classList.add("bytm-visible");
  969. else if (labelElem.classList.contains("bytm-visible") || document.activeElement !== sliderElem)
  970. labelElem.classList.remove("bytm-visible");
  971. if (Number(sliderElem.value) !== lastSliderVal) {
  972. lastSliderVal = Number(sliderElem.value);
  973. updateLabel();
  974. }
  975. });
  976. sliderHoverObserver.observe(sliderElem, {
  977. attributes: true,
  978. });
  979. }
  980. /** Sets the volume slider to a set size */
  981. function setVolSliderSize() {
  982. const { volumeSliderSize: size } = features;
  983. if (typeof size !== "number" || isNaN(Number(size)))
  984. return;
  985. (0,_sv443_network_userutils__WEBPACK_IMPORTED_MODULE_0__.addGlobalStyle)(`\
  986. /* BetterYTM - set volume slider size */
  987. #bytm-vol-slider-cont tp-yt-paper-slider#volume-slider {
  988. width: ${size}px !important;
  989. }`);
  990. }
  991. /** Sets the `step` attribute of the volume slider */
  992. function setVolSliderStep(sliderElem) {
  993. sliderElem.setAttribute("step", String(features.volumeSliderStep));
  994. }
  995. //#MARKER queue buttons
  996. function initQueueButtons() {
  997. const addQueueBtns = (evt) => {
  998. let amt = 0;
  999. for (const queueItm of evt.childNodes) {
  1000. if (!queueItm.classList.contains("bytm-has-queue-btns")) {
  1001. addQueueButtons(queueItm);
  1002. amt++;
  1003. }
  1004. }
  1005. if (amt > 0)
  1006. (0,_utils__WEBPACK_IMPORTED_MODULE_2__.log)(`Added buttons to ${amt} new queue ${(0,_sv443_network_userutils__WEBPACK_IMPORTED_MODULE_0__.autoPlural)("item", amt)}`);
  1007. };
  1008. _events__WEBPACK_IMPORTED_MODULE_3__.siteEvents.on("queueChanged", addQueueBtns);
  1009. _events__WEBPACK_IMPORTED_MODULE_3__.siteEvents.on("autoplayQueueChanged", addQueueBtns);
  1010. const queueItems = document.querySelectorAll("#contents.ytmusic-player-queue > ytmusic-player-queue-item");
  1011. if (queueItems.length === 0)
  1012. return;
  1013. queueItems.forEach(itm => addQueueButtons(itm));
  1014. (0,_utils__WEBPACK_IMPORTED_MODULE_2__.log)(`Added buttons to ${queueItems.length} existing queue ${(0,_sv443_network_userutils__WEBPACK_IMPORTED_MODULE_0__.autoPlural)("item", queueItems)}`);
  1015. }
  1016. /**
  1017. * Adds the buttons to each item in the current song queue.
  1018. * Also observes for changes to add new buttons to new items in the queue.
  1019. * @param queueItem The element with tagname `ytmusic-player-queue-item` to add queue buttons to
  1020. */
  1021. function addQueueButtons(queueItem) {
  1022. var _a;
  1023. return __awaiter(this, void 0, void 0, function* () {
  1024. //#SECTION general queue item stuff
  1025. const queueBtnsCont = document.createElement("div");
  1026. queueBtnsCont.className = "bytm-queue-btn-container";
  1027. const lyricsIconUrl = yield (0,_utils__WEBPACK_IMPORTED_MODULE_2__.getResourceUrl)("lyrics");
  1028. const deleteIconUrl = yield (0,_utils__WEBPACK_IMPORTED_MODULE_2__.getResourceUrl)("delete");
  1029. //#SECTION lyrics btn
  1030. let lyricsBtnElem;
  1031. if (features.lyricsQueueButton) {
  1032. lyricsBtnElem = yield (0,_lyrics__WEBPACK_IMPORTED_MODULE_5__.createLyricsBtn)(undefined, false);
  1033. lyricsBtnElem.title = "Open this song's lyrics in a new tab";
  1034. lyricsBtnElem.style.display = "inline-flex";
  1035. lyricsBtnElem.style.visibility = "initial";
  1036. lyricsBtnElem.style.pointerEvents = "initial";
  1037. lyricsBtnElem.addEventListener("click", (e) => __awaiter(this, void 0, void 0, function* () {
  1038. e.stopPropagation();
  1039. const songInfo = queueItem.querySelector(".song-info");
  1040. if (!songInfo)
  1041. return;
  1042. const [songEl, artistEl] = songInfo.querySelectorAll("yt-formatted-string");
  1043. const song = songEl === null || songEl === void 0 ? void 0 : songEl.innerText;
  1044. const artist = artistEl === null || artistEl === void 0 ? void 0 : artistEl.innerText;
  1045. if (!song || !artist)
  1046. return;
  1047. let lyricsUrl;
  1048. const artistsSan = (0,_lyrics__WEBPACK_IMPORTED_MODULE_5__.sanitizeArtists)(artist);
  1049. const songSan = (0,_lyrics__WEBPACK_IMPORTED_MODULE_5__.sanitizeSong)(song);
  1050. const splitTitle = (0,_lyrics__WEBPACK_IMPORTED_MODULE_5__.splitVideoTitle)(songSan);
  1051. const cachedLyricsUrl = songSan.includes("-")
  1052. ? (0,_lyrics__WEBPACK_IMPORTED_MODULE_5__.getLyricsCacheEntry)(splitTitle.artist, splitTitle.song)
  1053. : (0,_lyrics__WEBPACK_IMPORTED_MODULE_5__.getLyricsCacheEntry)(artistsSan, songSan);
  1054. if (cachedLyricsUrl)
  1055. lyricsUrl = cachedLyricsUrl;
  1056. else if (!songInfo.hasAttribute("data-bytm-loading")) {
  1057. const imgEl = lyricsBtnElem.querySelector("img");
  1058. if (!cachedLyricsUrl) {
  1059. songInfo.setAttribute("data-bytm-loading", "");
  1060. imgEl.src = yield (0,_utils__WEBPACK_IMPORTED_MODULE_2__.getResourceUrl)("spinner");
  1061. imgEl.classList.add("bytm-spinner");
  1062. }
  1063. lyricsUrl = cachedLyricsUrl !== null && cachedLyricsUrl !== void 0 ? cachedLyricsUrl : yield (0,_lyrics__WEBPACK_IMPORTED_MODULE_5__.getGeniusUrl)(artistsSan, songSan);
  1064. const resetImgElem = () => {
  1065. imgEl.src = lyricsIconUrl;
  1066. imgEl.classList.remove("bytm-spinner");
  1067. };
  1068. if (!cachedLyricsUrl) {
  1069. songInfo.removeAttribute("data-bytm-loading");
  1070. // so the new image doesn't "blink"
  1071. setTimeout(resetImgElem, 100);
  1072. }
  1073. if (!lyricsUrl) {
  1074. resetImgElem();
  1075. if (confirm("Couldn't find a lyrics page for this song.\nDo you want to open genius.com to manually search for it?"))
  1076. (0,_sv443_network_userutils__WEBPACK_IMPORTED_MODULE_0__.openInNewTab)(`https://genius.com/search?q=${encodeURIComponent(`${artistsSan} ${songSan}`)}`);
  1077. return;
  1078. }
  1079. }
  1080. lyricsUrl && (0,_sv443_network_userutils__WEBPACK_IMPORTED_MODULE_0__.openInNewTab)(lyricsUrl);
  1081. }));
  1082. }
  1083. //#SECTION delete from queue btn
  1084. let deleteBtnElem;
  1085. if (features.deleteFromQueueButton) {
  1086. deleteBtnElem = document.createElement("a");
  1087. Object.assign(deleteBtnElem, {
  1088. title: "Remove this song from the queue",
  1089. className: "ytmusic-player-bar bytm-delete-from-queue bytm-generic-btn",
  1090. role: "button",
  1091. });
  1092. deleteBtnElem.style.visibility = "initial";
  1093. deleteBtnElem.addEventListener("click", (e) => __awaiter(this, void 0, void 0, function* () {
  1094. e.stopPropagation();
  1095. // container of the queue item popup menu - element gets reused for every queue item
  1096. let queuePopupCont = document.querySelector("ytmusic-app ytmusic-popup-container tp-yt-iron-dropdown");
  1097. try {
  1098. // three dots button to open the popup menu of a queue item
  1099. const dotsBtnElem = queueItem.querySelector("ytmusic-menu-renderer yt-button-shape button");
  1100. if (queuePopupCont)
  1101. queuePopupCont.setAttribute("data-bytm-hidden", "true");
  1102. dotsBtnElem === null || dotsBtnElem === void 0 ? void 0 : dotsBtnElem.click();
  1103. yield (0,_sv443_network_userutils__WEBPACK_IMPORTED_MODULE_0__.pauseFor)(20);
  1104. queuePopupCont = document.querySelector("ytmusic-app ytmusic-popup-container tp-yt-iron-dropdown");
  1105. queuePopupCont === null || queuePopupCont === void 0 ? void 0 : queuePopupCont.setAttribute("data-bytm-hidden", "true");
  1106. // a little bit janky and unreliable but the only way afaik
  1107. const removeFromQueueBtn = queuePopupCont === null || queuePopupCont === void 0 ? void 0 : queuePopupCont.querySelector("tp-yt-paper-listbox ytmusic-menu-service-item-renderer:nth-of-type(3)");
  1108. yield (0,_sv443_network_userutils__WEBPACK_IMPORTED_MODULE_0__.pauseFor)(10);
  1109. removeFromQueueBtn === null || removeFromQueueBtn === void 0 ? void 0 : removeFromQueueBtn.click();
  1110. }
  1111. catch (err) {
  1112. (0,_utils__WEBPACK_IMPORTED_MODULE_2__.error)("Couldn't remove song from queue due to error:", err);
  1113. }
  1114. finally {
  1115. queuePopupCont === null || queuePopupCont === void 0 ? void 0 : queuePopupCont.removeAttribute("data-bytm-hidden");
  1116. }
  1117. }));
  1118. const imgElem = document.createElement("img");
  1119. imgElem.className = "bytm-generic-btn-img";
  1120. imgElem.src = deleteIconUrl;
  1121. deleteBtnElem.appendChild(imgElem);
  1122. }
  1123. //#SECTION append elements to DOM
  1124. lyricsBtnElem && queueBtnsCont.appendChild(lyricsBtnElem);
  1125. deleteBtnElem && queueBtnsCont.appendChild(deleteBtnElem);
  1126. (_a = queueItem.querySelector(".song-info")) === null || _a === void 0 ? void 0 : _a.appendChild(queueBtnsCont);
  1127. queueItem.classList.add("bytm-has-queue-btns");
  1128. });
  1129. }
  1130. //#MARKER anchor improvements
  1131. // TODO: add to thumbnails in "songs" list on channel pages (/channel/$id)
  1132. // TODO: add to thumbnails in playlists (/playlist?list=$id)
  1133. // TODO:FIXME: only works for the first 7 items of each carousel shelf -> probably needs own mutation observer
  1134. /** Adds anchors around elements and tweaks existing ones so songs are easier to open in a new tab */
  1135. function addAnchorImprovements() {
  1136. //#SECTION carousel shelves
  1137. try {
  1138. // home page
  1139. /** Only adds anchor improvements for carousel shelves that contain the regular list-item-renderer, not the two-row-item-renderer */
  1140. const condCarouselImprovements = (el) => {
  1141. const listItemRenderer = el.querySelector("ytmusic-responsive-list-item-renderer");
  1142. if (listItemRenderer) {
  1143. const itemsElem = el.querySelector("ul#items");
  1144. if (itemsElem) {
  1145. const improvedElems = improveCarouselAnchors(itemsElem);
  1146. improvedElems > 0 && (0,_utils__WEBPACK_IMPORTED_MODULE_2__.log)(`Added anchor improvements to ${improvedElems} carousel shelf ${(0,_sv443_network_userutils__WEBPACK_IMPORTED_MODULE_0__.autoPlural)("item", improvedElems)}`);
  1147. }
  1148. }
  1149. };
  1150. // initial three shelves aren't included in the event fire
  1151. (0,_sv443_network_userutils__WEBPACK_IMPORTED_MODULE_0__.onSelector)("ytmusic-carousel-shelf-renderer", {
  1152. listener: () => {
  1153. const carouselShelves = document.body.querySelectorAll("ytmusic-carousel-shelf-renderer");
  1154. carouselShelves.forEach(condCarouselImprovements);
  1155. },
  1156. });
  1157. // every shelf that's loaded by scrolling:
  1158. _events__WEBPACK_IMPORTED_MODULE_3__.siteEvents.on("carouselShelvesChanged", ({ addedNodes }) => {
  1159. if (addedNodes && addedNodes.length > 0)
  1160. addedNodes.forEach(condCarouselImprovements);
  1161. });
  1162. // related tab in /watch
  1163. // TODO: items are lazy-loaded so this needs to be done differently
  1164. // maybe the onSelectorExists feature can be expanded to conditionally support continuous checking & querySelectorAll
  1165. const relatedTabAnchorImprovements = (tabElem) => {
  1166. const relatedCarouselShelves = tabElem === null || tabElem === void 0 ? void 0 : tabElem.querySelectorAll("ytmusic-carousel-shelf-renderer");
  1167. if (relatedCarouselShelves)
  1168. relatedCarouselShelves.forEach(condCarouselImprovements);
  1169. };
  1170. const relatedTabContentsSelector = "ytmusic-section-list-renderer[page-type=\"MUSIC_PAGE_TYPE_TRACK_RELATED\"] #contents";
  1171. (0,_sv443_network_userutils__WEBPACK_IMPORTED_MODULE_0__.onSelector)("ytmusic-tab-renderer[page-type=\"MUSIC_PAGE_TYPE_TRACK_RELATED\"]", {
  1172. listener: (relatedTabContainer) => {
  1173. const relatedTabObserver = new MutationObserver(([{ addedNodes, removedNodes }]) => {
  1174. if (addedNodes.length > 0 || removedNodes.length > 0)
  1175. relatedTabAnchorImprovements(document.querySelector(relatedTabContentsSelector));
  1176. });
  1177. relatedTabObserver.observe(relatedTabContainer, {
  1178. childList: true,
  1179. });
  1180. },
  1181. });
  1182. (0,_sv443_network_userutils__WEBPACK_IMPORTED_MODULE_0__.onSelector)(relatedTabContentsSelector, {
  1183. listener: (relatedTabContents) => {
  1184. relatedTabAnchorImprovements(relatedTabContents);
  1185. },
  1186. });
  1187. }
  1188. catch (err) {
  1189. (0,_utils__WEBPACK_IMPORTED_MODULE_2__.error)("Couldn't improve carousel shelf anchors due to an error:", err);
  1190. }
  1191. //#SECTION sidebar
  1192. try {
  1193. const addSidebarAnchors = (sidebarCont) => {
  1194. const items = sidebarCont.parentNode.querySelectorAll("ytmusic-guide-entry-renderer tp-yt-paper-item");
  1195. improveSidebarAnchors(items);
  1196. return items.length;
  1197. };
  1198. (0,_sv443_network_userutils__WEBPACK_IMPORTED_MODULE_0__.onSelector)("ytmusic-app-layout tp-yt-app-drawer #contentContainer #guide-content #items ytmusic-guide-entry-renderer", {
  1199. listener: (sidebarCont) => {
  1200. const itemsAmt = addSidebarAnchors(sidebarCont);
  1201. (0,_utils__WEBPACK_IMPORTED_MODULE_2__.log)(`Added anchors around ${itemsAmt} sidebar ${(0,_sv443_network_userutils__WEBPACK_IMPORTED_MODULE_0__.autoPlural)("item", itemsAmt)}`);
  1202. },
  1203. });
  1204. (0,_sv443_network_userutils__WEBPACK_IMPORTED_MODULE_0__.onSelector)("ytmusic-app-layout #mini-guide ytmusic-guide-renderer ytmusic-guide-section-renderer #items ytmusic-guide-entry-renderer", {
  1205. listener: (miniSidebarCont) => {
  1206. const itemsAmt = addSidebarAnchors(miniSidebarCont);
  1207. (0,_utils__WEBPACK_IMPORTED_MODULE_2__.log)(`Added anchors around ${itemsAmt} mini sidebar ${(0,_sv443_network_userutils__WEBPACK_IMPORTED_MODULE_0__.autoPlural)("item", itemsAmt)}`);
  1208. },
  1209. });
  1210. }
  1211. catch (err) {
  1212. (0,_utils__WEBPACK_IMPORTED_MODULE_2__.error)("Couldn't add anchors to sidebar items due to an error:", err);
  1213. }
  1214. }
  1215. const sidebarPaths = [
  1216. "/",
  1217. "/explore",
  1218. "/library",
  1219. ];
  1220. /**
  1221. * Adds anchors to the sidebar items so they can be opened in a new tab
  1222. * @param sidebarItem
  1223. */
  1224. function improveSidebarAnchors(sidebarItems) {
  1225. sidebarItems.forEach((item, i) => {
  1226. var _a;
  1227. const anchorElem = document.createElement("a");
  1228. anchorElem.classList.add("bytm-anchor", "bytm-no-select");
  1229. anchorElem.role = "button";
  1230. anchorElem.target = "_self";
  1231. anchorElem.href = (_a = sidebarPaths[i]) !== null && _a !== void 0 ? _a : "#";
  1232. anchorElem.title = "Middle click to open in a new tab";
  1233. anchorElem.addEventListener("click", (e) => {
  1234. e.preventDefault();
  1235. });
  1236. (0,_sv443_network_userutils__WEBPACK_IMPORTED_MODULE_0__.addParent)(item, anchorElem);
  1237. });
  1238. }
  1239. /**
  1240. * Actually adds the anchor improvements to carousel shelf items
  1241. * @param itemsElement The container with the selector `ul#items` inside of each `ytmusic-carousel`
  1242. */
  1243. function improveCarouselAnchors(itemsElement) {
  1244. if (itemsElement.classList.contains("bytm-anchors-improved"))
  1245. return 0;
  1246. let improvedElems = 0;
  1247. try {
  1248. const allListItems = itemsElement.querySelectorAll("ytmusic-responsive-list-item-renderer");
  1249. for (const listItem of allListItems) {
  1250. const thumbnailElem = listItem.querySelector(".left-items");
  1251. const titleElem = listItem.querySelector(".title-column yt-formatted-string.title a");
  1252. if (!thumbnailElem || !titleElem) {
  1253. (0,_utils__WEBPACK_IMPORTED_MODULE_2__.error)("Couldn't add carousel shelf anchor improvements because either the thumbnail or title element couldn't be found");
  1254. continue;
  1255. }
  1256. const thumbnailAnchor = document.createElement("a");
  1257. thumbnailAnchor.className = "bytm-carousel-shelf-anchor bytm-anchor";
  1258. thumbnailAnchor.href = titleElem.href;
  1259. thumbnailAnchor.target = "_self";
  1260. thumbnailAnchor.role = "button";
  1261. thumbnailAnchor.addEventListener("click", (e) => {
  1262. e.preventDefault();
  1263. });
  1264. (0,_sv443_network_userutils__WEBPACK_IMPORTED_MODULE_0__.addParent)(thumbnailElem, thumbnailAnchor);
  1265. improvedElems++;
  1266. }
  1267. }
  1268. catch (err) {
  1269. (0,_utils__WEBPACK_IMPORTED_MODULE_2__.error)("Couldn't add anchor improvements due to error:", err);
  1270. }
  1271. finally {
  1272. itemsElement.classList.add("bytm-anchors-improved");
  1273. }
  1274. return improvedElems;
  1275. }
  1276. //#MARKER auto close toasts
  1277. /** Closes toasts after a set amount of time */
  1278. function initAutoCloseToasts() {
  1279. try {
  1280. const animTimeout = 300;
  1281. const closeTimeout = Math.max(features.closeToastsTimeout * 1000 + animTimeout, animTimeout);
  1282. (0,_sv443_network_userutils__WEBPACK_IMPORTED_MODULE_0__.onSelector)("tp-yt-paper-toast#toast", {
  1283. all: true,
  1284. continuous: true,
  1285. listener: (toastElems) => __awaiter(this, void 0, void 0, function* () {
  1286. var _a;
  1287. for (const toastElem of toastElems) {
  1288. if (!toastElem.hasAttribute("allow-click-through"))
  1289. continue;
  1290. if (toastElem.classList.contains("bytm-closing"))
  1291. continue;
  1292. toastElem.classList.add("bytm-closing");
  1293. yield (0,_sv443_network_userutils__WEBPACK_IMPORTED_MODULE_0__.pauseFor)(closeTimeout);
  1294. toastElem.classList.remove("paper-toast-open");
  1295. (0,_utils__WEBPACK_IMPORTED_MODULE_2__.log)(`Automatically closed toast '${(_a = toastElem.querySelector("#text-container yt-formatted-string")) === null || _a === void 0 ? void 0 : _a.innerText}' after ${features.closeToastsTimeout * 1000}ms`);
  1296. // wait for the transition to finish
  1297. yield (0,_sv443_network_userutils__WEBPACK_IMPORTED_MODULE_0__.pauseFor)(animTimeout);
  1298. toastElem.style.display = "none";
  1299. }
  1300. }),
  1301. });
  1302. (0,_utils__WEBPACK_IMPORTED_MODULE_2__.log)("Initialized automatic toast closing");
  1303. }
  1304. catch (err) {
  1305. (0,_utils__WEBPACK_IMPORTED_MODULE_2__.error)("Error in automatic toast closing:", err);
  1306. }
  1307. }
  1308. //#MARKER remove share tracking param
  1309. /** Continuously removes the ?si tracking parameter from share URLs */
  1310. function removeShareTrackingParam() {
  1311. (0,_sv443_network_userutils__WEBPACK_IMPORTED_MODULE_0__.onSelector)("yt-copy-link-renderer input#share-url", {
  1312. continuous: true,
  1313. listener: (inputElem) => {
  1314. try {
  1315. const url = new URL(inputElem.value);
  1316. if (!url.searchParams.has("si"))
  1317. return;
  1318. url.searchParams.delete("si");
  1319. inputElem.value = String(url);
  1320. (0,_utils__WEBPACK_IMPORTED_MODULE_2__.log)(`Removed tracking parameter from share link: ${url}`);
  1321. }
  1322. catch (err) {
  1323. (0,_utils__WEBPACK_IMPORTED_MODULE_2__.warn)("Couldn't remove tracking parameter from share link due to error:", err);
  1324. }
  1325. },
  1326. });
  1327. }
  1328. /***/ }),
  1329. /***/ "./src/features/lyrics.ts":
  1330. /*!********************************!*\
  1331. !*** ./src/features/lyrics.ts ***!
  1332. \********************************/
  1333. /***/ (function(__unused_webpack_module, __webpack_exports__, __webpack_require__) {
  1334. __webpack_require__.r(__webpack_exports__);
  1335. /* harmony export */ __webpack_require__.d(__webpack_exports__, {
  1336. /* harmony export */ addLyricsCacheEntry: function() { return /* binding */ addLyricsCacheEntry; },
  1337. /* harmony export */ addMediaCtrlLyricsBtn: function() { return /* binding */ addMediaCtrlLyricsBtn; },
  1338. /* harmony export */ createLyricsBtn: function() { return /* binding */ createLyricsBtn; },
  1339. /* harmony export */ geniUrlBase: function() { return /* binding */ geniUrlBase; },
  1340. /* harmony export */ getCurrentLyricsUrl: function() { return /* binding */ getCurrentLyricsUrl; },
  1341. /* harmony export */ getGeniusUrl: function() { return /* binding */ getGeniusUrl; },
  1342. /* harmony export */ getLyricsCacheEntry: function() { return /* binding */ getLyricsCacheEntry; },
  1343. /* harmony export */ sanitizeArtists: function() { return /* binding */ sanitizeArtists; },
  1344. /* harmony export */ sanitizeSong: function() { return /* binding */ sanitizeSong; },
  1345. /* harmony export */ splitVideoTitle: function() { return /* binding */ splitVideoTitle; }
  1346. /* harmony export */ });
  1347. /* harmony import */ var _sv443_network_userutils__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @sv443-network/userutils */ "./node_modules/@sv443-network/userutils/dist/index.mjs");
  1348. /* harmony import */ var _utils__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../utils */ "./src/utils.ts");
  1349. var __awaiter = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) {
  1350. function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
  1351. return new (P || (P = Promise))(function (resolve, reject) {
  1352. function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
  1353. function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
  1354. function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
  1355. step((generator = generator.apply(thisArg, _arguments || [])).next());
  1356. });
  1357. };
  1358. var __asyncValues = (undefined && undefined.__asyncValues) || function (o) {
  1359. if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined.");
  1360. var m = o[Symbol.asyncIterator], i;
  1361. 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);
  1362. 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); }); }; }
  1363. function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); }
  1364. };
  1365. /** Base URL of geniURL */
  1366. const geniUrlBase = "https://api.sv443.net/geniurl";
  1367. /** GeniURL endpoint that gives song metadata when provided with a `?q` or `?artist` and `?song` parameter - [more info](https://api.sv443.net/geniurl) */
  1368. const geniURLSearchTopUrl = `${geniUrlBase}/search/top`;
  1369. /**
  1370. * The threshold to pass to geniURL's fuzzy filtering.
  1371. * 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.
  1372. * Set to undefined to use the default.
  1373. */
  1374. const threshold = 0.55;
  1375. /** Ratelimit budget timeframe in seconds - should reflect what's in geniURL's docs */
  1376. const geniUrlRatelimitTimeframe = 30;
  1377. const thresholdParam = threshold ? `&threshold=${(0,_sv443_network_userutils__WEBPACK_IMPORTED_MODULE_0__.clamp)(threshold, 0, 1)}` : "";
  1378. //#MARKER cache
  1379. /** Cache with key format `ARTIST - SONG` (sanitized) and lyrics URLs as values. Used to prevent extraneous requests to geniURL. */
  1380. const lyricsUrlCache = new Map();
  1381. /** How many cache entries can exist at a time - this is used to cap memory usage */
  1382. const maxLyricsCacheSize = 100;
  1383. /**
  1384. * Returns the lyrics URL from the passed un-/sanitized artist and song name, or undefined if the entry doesn't exist yet.
  1385. * **The passed parameters need to be sanitized first!**
  1386. */
  1387. function getLyricsCacheEntry(artists, song) {
  1388. return lyricsUrlCache.get(`${artists} - ${song}`);
  1389. }
  1390. /** Adds the provided entry into the lyrics URL cache */
  1391. function addLyricsCacheEntry(artists, song, lyricsUrl) {
  1392. lyricsUrlCache.set(`${sanitizeArtists(artists)} - ${sanitizeSong(song)}`, lyricsUrl);
  1393. // delete oldest entry if cache gets too big
  1394. if (lyricsUrlCache.size > maxLyricsCacheSize)
  1395. lyricsUrlCache.delete([...lyricsUrlCache.keys()].at(-1));
  1396. }
  1397. //#MARKER media control bar
  1398. let mcCurrentSongTitle = "";
  1399. /** Adds a lyrics button to the media controls bar */
  1400. function addMediaCtrlLyricsBtn() {
  1401. (0,_sv443_network_userutils__WEBPACK_IMPORTED_MODULE_0__.onSelector)(".middle-controls-buttons ytmusic-like-button-renderer#like-button-renderer", { listener: addActualMediaCtrlLyricsBtn });
  1402. }
  1403. // TODO: add error.svg if the request fails
  1404. /** Actually adds the lyrics button after the like button renderer has been verified to exist */
  1405. function addActualMediaCtrlLyricsBtn(likeContainer) {
  1406. return __awaiter(this, void 0, void 0, function* () {
  1407. const songTitleElem = document.querySelector(".content-info-wrapper > yt-formatted-string");
  1408. // run parallel without awaiting so the MutationObserver below can observe the title element in time
  1409. (() => __awaiter(this, void 0, void 0, function* () {
  1410. const gUrl = yield getCurrentLyricsUrl();
  1411. const linkElem = yield createLyricsBtn(gUrl !== null && gUrl !== void 0 ? gUrl : undefined);
  1412. linkElem.id = "betterytm-lyrics-button";
  1413. (0,_utils__WEBPACK_IMPORTED_MODULE_1__.log)("Inserted lyrics button into media controls bar");
  1414. (0,_sv443_network_userutils__WEBPACK_IMPORTED_MODULE_0__.insertAfter)(likeContainer, linkElem);
  1415. }))();
  1416. mcCurrentSongTitle = songTitleElem.title;
  1417. const spinnerIconUrl = yield (0,_utils__WEBPACK_IMPORTED_MODULE_1__.getResourceUrl)("spinner");
  1418. const lyricsIconUrl = yield (0,_utils__WEBPACK_IMPORTED_MODULE_1__.getResourceUrl)("lyrics");
  1419. const onMutation = (mutations) => { var _a, mutations_1, mutations_1_1; return __awaiter(this, void 0, void 0, function* () {
  1420. var _b, e_1, _c, _d;
  1421. try {
  1422. for (_a = true, mutations_1 = __asyncValues(mutations); mutations_1_1 = yield mutations_1.next(), _b = mutations_1_1.done, !_b; _a = true) {
  1423. _d = mutations_1_1.value;
  1424. _a = false;
  1425. const mut = _d;
  1426. const newTitle = mut.target.title;
  1427. if (newTitle !== mcCurrentSongTitle && newTitle.length > 0) {
  1428. const lyricsBtn = document.querySelector("#betterytm-lyrics-button");
  1429. if (!lyricsBtn)
  1430. return;
  1431. (0,_utils__WEBPACK_IMPORTED_MODULE_1__.info)(`Song title changed from '${mcCurrentSongTitle}' to '${newTitle}'`);
  1432. lyricsBtn.style.cursor = "wait";
  1433. lyricsBtn.style.pointerEvents = "none";
  1434. const imgElem = lyricsBtn.querySelector("img");
  1435. imgElem.src = spinnerIconUrl;
  1436. imgElem.classList.add("bytm-spinner");
  1437. mcCurrentSongTitle = newTitle;
  1438. const url = yield getCurrentLyricsUrl(); // can take a second or two
  1439. imgElem.src = lyricsIconUrl;
  1440. imgElem.classList.remove("bytm-spinner");
  1441. if (!url)
  1442. continue;
  1443. lyricsBtn.href = url;
  1444. lyricsBtn.title = "Open the current song's lyrics in a new tab";
  1445. lyricsBtn.style.cursor = "pointer";
  1446. lyricsBtn.style.visibility = "initial";
  1447. lyricsBtn.style.display = "inline-flex";
  1448. lyricsBtn.style.pointerEvents = "initial";
  1449. }
  1450. }
  1451. }
  1452. catch (e_1_1) { e_1 = { error: e_1_1 }; }
  1453. finally {
  1454. try {
  1455. if (!_a && !_b && (_c = mutations_1.return)) yield _c.call(mutations_1);
  1456. }
  1457. finally { if (e_1) throw e_1.error; }
  1458. }
  1459. }); };
  1460. // 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
  1461. const obs = new MutationObserver(onMutation);
  1462. obs.observe(songTitleElem, { attributes: true, attributeFilter: ["title"] });
  1463. });
  1464. }
  1465. //#MARKER utils
  1466. /** Removes everything in parentheses from the passed song name */
  1467. function sanitizeSong(songName) {
  1468. const parensRegex = /\(.+\)/gmi;
  1469. const squareParensRegex = /\[.+\]/gmi;
  1470. // trim right after the song name:
  1471. const sanitized = songName
  1472. .replace(parensRegex, "")
  1473. .replace(squareParensRegex, "");
  1474. return sanitized.trim();
  1475. }
  1476. /** Removes the secondary artist (if it exists) from the passed artists string */
  1477. function sanitizeArtists(artists) {
  1478. artists = artists.split(/\s*\u2022\s*/gmiu)[0]; // split at &bull; [•] character
  1479. if (artists.match(/&/))
  1480. artists = artists.split(/\s*&\s*/gm)[0];
  1481. if (artists.match(/,/))
  1482. artists = artists.split(/,\s*/gm)[0];
  1483. return artists.trim();
  1484. }
  1485. /** Returns the lyrics URL from genius for the currently selected song */
  1486. function getCurrentLyricsUrl() {
  1487. var _a;
  1488. return __awaiter(this, void 0, void 0, function* () {
  1489. try {
  1490. // In videos the video title contains both artist and song title, in "regular" YTM songs, the video title only contains the song title
  1491. const isVideo = typeof ((_a = document.querySelector("ytmusic-player")) === null || _a === void 0 ? void 0 : _a.hasAttribute("video-mode"));
  1492. const songTitleElem = document.querySelector(".content-info-wrapper > yt-formatted-string");
  1493. const songMetaElem = document.querySelector("span.subtitle > yt-formatted-string:first-child");
  1494. if (!songTitleElem || !songMetaElem || !songTitleElem.title)
  1495. return undefined;
  1496. const songNameRaw = songTitleElem.title;
  1497. const songName = sanitizeSong(songNameRaw);
  1498. const artistName = sanitizeArtists(songMetaElem.title);
  1499. /** Use when the current song is not a "real YTM song" with a static background, but rather a music video */
  1500. const getGeniusUrlVideo = () => __awaiter(this, void 0, void 0, function* () {
  1501. if (!songName.includes("-")) // for some fucking reason some music videos have YTM-like song title and artist separation, some don't
  1502. return yield getGeniusUrl(artistName, songName);
  1503. const { artist, song } = splitVideoTitle(songName);
  1504. return yield getGeniusUrl(artist, song);
  1505. });
  1506. // TODO: artist might need further splitting before comma or ampersand
  1507. const url = isVideo ? yield getGeniusUrlVideo() : yield getGeniusUrl(artistName, songName);
  1508. return url;
  1509. }
  1510. catch (err) {
  1511. (0,_utils__WEBPACK_IMPORTED_MODULE_1__.error)("Couldn't resolve lyrics URL:", err);
  1512. return undefined;
  1513. }
  1514. });
  1515. }
  1516. /** Fetches the actual lyrics URL from geniURL - **the passed parameters need to be sanitized first!** */
  1517. function getGeniusUrl(artist, song) {
  1518. var _a, _b, _c;
  1519. return __awaiter(this, void 0, void 0, function* () {
  1520. try {
  1521. const cacheEntry = getLyricsCacheEntry(artist, song);
  1522. if (cacheEntry) {
  1523. (0,_utils__WEBPACK_IMPORTED_MODULE_1__.info)(`Found lyrics URL in cache: ${cacheEntry}`);
  1524. return cacheEntry;
  1525. }
  1526. const startTs = Date.now();
  1527. const fetchUrl = `${geniURLSearchTopUrl}?artist=${encodeURIComponent(artist)}&song=${encodeURIComponent(song)}${thresholdParam}`;
  1528. (0,_utils__WEBPACK_IMPORTED_MODULE_1__.log)(`Requesting URL from geniURL at '${fetchUrl}'`);
  1529. const fetchRes = yield (0,_sv443_network_userutils__WEBPACK_IMPORTED_MODULE_0__.fetchAdvanced)(fetchUrl);
  1530. if (fetchRes.status === 429) {
  1531. alert(`You are being rate limited.\nPlease wait ${(_a = fetchRes.headers.get("retry-after")) !== null && _a !== void 0 ? _a : geniUrlRatelimitTimeframe} seconds before requesting more lyrics.`);
  1532. return undefined;
  1533. }
  1534. else if (fetchRes.status < 200 || fetchRes.status >= 300) {
  1535. (0,_utils__WEBPACK_IMPORTED_MODULE_1__.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)"}`);
  1536. return undefined;
  1537. }
  1538. const result = yield fetchRes.json();
  1539. if (typeof result === "object" && result.error) {
  1540. (0,_utils__WEBPACK_IMPORTED_MODULE_1__.error)("Couldn't fetch lyrics URL:", result.message);
  1541. return undefined;
  1542. }
  1543. const url = result.url;
  1544. (0,_utils__WEBPACK_IMPORTED_MODULE_1__.info)(`Found lyrics URL (after ${Date.now() - startTs}ms): ${url}`);
  1545. addLyricsCacheEntry(artist, song, url);
  1546. return url;
  1547. }
  1548. catch (err) {
  1549. (0,_utils__WEBPACK_IMPORTED_MODULE_1__.error)("Couldn't get lyrics URL due to error:", err);
  1550. return undefined;
  1551. }
  1552. });
  1553. }
  1554. /** Creates the base lyrics button element */
  1555. function createLyricsBtn(geniusUrl, hideIfLoading = true) {
  1556. return __awaiter(this, void 0, void 0, function* () {
  1557. const linkElem = document.createElement("a");
  1558. linkElem.className = "ytmusic-player-bar bytm-generic-btn";
  1559. linkElem.title = geniusUrl ? "Click to open this song's lyrics in a new tab" : "Loading lyrics URL...";
  1560. if (geniusUrl)
  1561. linkElem.href = geniusUrl;
  1562. linkElem.role = "button";
  1563. linkElem.target = "_blank";
  1564. linkElem.rel = "noopener noreferrer";
  1565. linkElem.style.visibility = hideIfLoading && geniusUrl ? "initial" : "hidden";
  1566. linkElem.style.display = hideIfLoading && geniusUrl ? "inline-flex" : "none";
  1567. const imgElem = document.createElement("img");
  1568. imgElem.className = "bytm-generic-btn-img";
  1569. imgElem.src = yield (0,_utils__WEBPACK_IMPORTED_MODULE_1__.getResourceUrl)("lyrics");
  1570. linkElem.appendChild(imgElem);
  1571. return linkElem;
  1572. });
  1573. }
  1574. /** Splits a video title that contains a hyphen into an artist and song */
  1575. function splitVideoTitle(title) {
  1576. const [artist, ...rest] = title.split("-").map((v, i) => i < 2 ? v.trim() : v);
  1577. return { artist, song: rest.join("-") };
  1578. }
  1579. /***/ }),
  1580. /***/ "./src/menu/menu.ts":
  1581. /*!**************************!*\
  1582. !*** ./src/menu/menu.ts ***!
  1583. \**************************/
  1584. /***/ (function(__unused_webpack_module, __webpack_exports__, __webpack_require__) {
  1585. __webpack_require__.r(__webpack_exports__);
  1586. /* harmony export */ __webpack_require__.d(__webpack_exports__, {
  1587. /* harmony export */ closeMenu: function() { return /* binding */ closeMenu; },
  1588. /* harmony export */ initMenu: function() { return /* binding */ initMenu; },
  1589. /* harmony export */ openMenu: function() { return /* binding */ openMenu; },
  1590. /* harmony export */ setActiveTab: function() { return /* binding */ setActiveTab; }
  1591. /* harmony export */ });
  1592. /* harmony import */ var _changelog_md__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../../changelog.md */ "./changelog.md");
  1593. /* harmony import */ var _menu_html__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./menu.html */ "./src/menu/menu.html");
  1594. /* harmony import */ var _menu_css__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./menu.css */ "./src/menu/menu.css");
  1595. // REQUIREMENTS:
  1596. // - modal using the <dialog> element
  1597. // - sections with headers
  1598. // - support for "custom widgets"
  1599. // - debounce or save on button press to store new configuration
  1600. // - much better scaling including no vw and vh units
  1601. // - cleanup function per feature so a page reload is not always needed
  1602. //#MARKER menu
  1603. /**
  1604. * The base selector values for the menu tabs
  1605. * Header selector format: `#${baseValue}-header`
  1606. * Content selector format: `#${baseValue}-content`
  1607. */
  1608. const tabsSelectors = {
  1609. options: "bytm-menu-tab-options",
  1610. info: "bytm-menu-tab-info",
  1611. changelog: "bytm-menu-tab-changelog",
  1612. };
  1613. /** Called from init(), before DOMContentLoaded is fired */
  1614. function initMenu() {
  1615. document.addEventListener("DOMContentLoaded", () => {
  1616. // create menu container
  1617. const menuContainer = document.createElement("div");
  1618. menuContainer.id = "bytm-menu-container";
  1619. // add menu html
  1620. menuContainer.innerHTML = _menu_html__WEBPACK_IMPORTED_MODULE_1__["default"];
  1621. document.body.appendChild(menuContainer);
  1622. initMenuContents();
  1623. });
  1624. }
  1625. function initMenuContents() {
  1626. var _a;
  1627. // hook events
  1628. for (const tab in tabsSelectors) {
  1629. const selector = tabsSelectors[tab];
  1630. (_a = document.querySelector(`#${selector}-header`)) === null || _a === void 0 ? void 0 : _a.addEventListener("click", () => {
  1631. setActiveTab(tab);
  1632. });
  1633. }
  1634. // init tab contents
  1635. initOptionsContent();
  1636. initInfoContent();
  1637. initChangelogContent();
  1638. }
  1639. /** Opens the specified tab */
  1640. function setActiveTab(tab) {
  1641. const tabs = Object.assign({}, tabsSelectors);
  1642. delete tabs[tab];
  1643. // disable all but new active tab
  1644. for (const [, val] of Object.entries(tabs)) {
  1645. document.querySelector(`#${val}-header`).dataset.active = "false";
  1646. document.querySelector(`#${val}-content`).dataset.active = "false";
  1647. }
  1648. // enable new active tab
  1649. document.querySelector(`#${tabsSelectors[tab]}-header`).dataset.active = "true";
  1650. document.querySelector(`#${tabsSelectors[tab]}-content`).dataset.active = "true";
  1651. }
  1652. /** Opens the modal menu dialog */
  1653. function openMenu() {
  1654. var _a;
  1655. (_a = document.querySelector("#bytm-menu-dialog")) === null || _a === void 0 ? void 0 : _a.showModal();
  1656. }
  1657. /** Closes the modal menu dialog */
  1658. function closeMenu() {
  1659. var _a;
  1660. (_a = document.querySelector("#bytm-menu-dialog")) === null || _a === void 0 ? void 0 : _a.close();
  1661. }
  1662. //#MARKER menu tab contents
  1663. function initOptionsContent() {
  1664. const tab = document.querySelector("#bytm-menu-tab-options-content");
  1665. void tab;
  1666. }
  1667. function initInfoContent() {
  1668. const tab = document.querySelector("#bytm-menu-tab-info-content");
  1669. void tab;
  1670. }
  1671. function initChangelogContent() {
  1672. const tab = document.querySelector("#bytm-menu-tab-changelog-content");
  1673. tab.innerHTML = _changelog_md__WEBPACK_IMPORTED_MODULE_0__["default"];
  1674. }
  1675. /***/ }),
  1676. /***/ "./src/menu/menu_old.ts":
  1677. /*!******************************!*\
  1678. !*** ./src/menu/menu_old.ts ***!
  1679. \******************************/
  1680. /***/ (function(__unused_webpack_module, __webpack_exports__, __webpack_require__) {
  1681. __webpack_require__.r(__webpack_exports__);
  1682. /* harmony export */ __webpack_require__.d(__webpack_exports__, {
  1683. /* harmony export */ addChangelogMenu: function() { return /* binding */ addChangelogMenu; },
  1684. /* harmony export */ addExportMenu: function() { return /* binding */ addExportMenu; },
  1685. /* harmony export */ addImportMenu: function() { return /* binding */ addImportMenu; },
  1686. /* harmony export */ addMenu: function() { return /* binding */ addMenu; },
  1687. /* harmony export */ closeMenu: function() { return /* binding */ closeMenu; },
  1688. /* harmony export */ isMenuOpen: function() { return /* binding */ isMenuOpen; },
  1689. /* harmony export */ openMenu: function() { return /* binding */ openMenu; }
  1690. /* harmony export */ });
  1691. /* harmony import */ var _sv443_network_userutils__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @sv443-network/userutils */ "./node_modules/@sv443-network/userutils/dist/index.mjs");
  1692. /* harmony import */ var _config__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../config */ "./src/config.ts");
  1693. /* harmony import */ var _constants__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../constants */ "./src/constants.ts");
  1694. /* harmony import */ var _features_index__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../features/index */ "./src/features/index.ts");
  1695. /* harmony import */ var _utils__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../utils */ "./src/utils.ts");
  1696. /* harmony import */ var _events__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../events */ "./src/events.ts");
  1697. /* harmony import */ var _menu_old_css__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ./menu_old.css */ "./src/menu/menu_old.css");
  1698. var __awaiter = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) {
  1699. function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
  1700. return new (P || (P = Promise))(function (resolve, reject) {
  1701. function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
  1702. function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
  1703. function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
  1704. step((generator = generator.apply(thisArg, _arguments || [])).next());
  1705. });
  1706. };
  1707. //#MARKER create menu elements
  1708. let isMenuOpen = false;
  1709. /** Threshold in pixels from the top of the options container that dictates for how long the scroll indicator is shown */
  1710. const scrollIndicatorOffsetThreshold = 30;
  1711. let scrollIndicatorEnabled = true;
  1712. /**
  1713. * Adds an element to open the BetterYTM menu
  1714. * @deprecated to be replaced with new menu - see https://github.com/Sv443/BetterYTM/issues/23
  1715. */
  1716. function addMenu() {
  1717. var _a, _b;
  1718. return __awaiter(this, void 0, void 0, function* () {
  1719. //#SECTION backdrop & menu container
  1720. const backgroundElem = document.createElement("div");
  1721. backgroundElem.id = "bytm-cfg-menu-bg";
  1722. backgroundElem.classList.add("bytm-menu-bg");
  1723. backgroundElem.title = "Click here to close the menu";
  1724. backgroundElem.style.visibility = "hidden";
  1725. backgroundElem.style.display = "none";
  1726. backgroundElem.addEventListener("click", (e) => {
  1727. var _a;
  1728. if (isMenuOpen && ((_a = e.target) === null || _a === void 0 ? void 0 : _a.id) === "bytm-cfg-menu-bg")
  1729. closeMenu(e);
  1730. });
  1731. document.body.addEventListener("keydown", (e) => {
  1732. if (isMenuOpen && e.key === "Escape")
  1733. closeMenu(e);
  1734. });
  1735. const menuContainer = document.createElement("div");
  1736. menuContainer.title = ""; // prevent bg title from propagating downwards
  1737. menuContainer.classList.add("bytm-menu");
  1738. menuContainer.id = "bytm-cfg-menu";
  1739. //#SECTION title bar
  1740. const headerElem = document.createElement("div");
  1741. headerElem.classList.add("bytm-menu-header");
  1742. const titleCont = document.createElement("div");
  1743. titleCont.id = "bytm-menu-titlecont";
  1744. titleCont.role = "heading";
  1745. titleCont.ariaLevel = "1";
  1746. const titleElem = document.createElement("h2");
  1747. titleElem.id = "bytm-menu-title";
  1748. titleElem.innerText = `${_constants__WEBPACK_IMPORTED_MODULE_2__.scriptInfo.name} - Configuration`;
  1749. const linksCont = document.createElement("div");
  1750. linksCont.id = "bytm-menu-linkscont";
  1751. const addLink = (imgSrc, href, title) => {
  1752. const anchorElem = document.createElement("a");
  1753. anchorElem.className = "bytm-menu-link bytm-no-select";
  1754. anchorElem.rel = "noopener noreferrer";
  1755. anchorElem.target = "_blank";
  1756. anchorElem.href = href;
  1757. anchorElem.title = title;
  1758. const imgElem = document.createElement("img");
  1759. imgElem.className = "bytm-menu-img";
  1760. imgElem.src = imgSrc;
  1761. imgElem.style.width = "32px";
  1762. imgElem.style.height = "32px";
  1763. anchorElem.appendChild(imgElem);
  1764. linksCont.appendChild(anchorElem);
  1765. };
  1766. addLink(yield (0,_utils__WEBPACK_IMPORTED_MODULE_4__.getResourceUrl)("github"), _constants__WEBPACK_IMPORTED_MODULE_2__.scriptInfo.namespace, `Open ${_constants__WEBPACK_IMPORTED_MODULE_2__.scriptInfo.name} on GitHub`);
  1767. // TODO:
  1768. // addLink(await getResourceUrl("greasyfork"), "https://greasyfork.org/en/users/184165-sv443", `Open ${scriptInfo.name} on GreasyFork`);
  1769. const closeElem = document.createElement("img");
  1770. closeElem.classList.add("bytm-menu-close");
  1771. closeElem.src = yield (0,_utils__WEBPACK_IMPORTED_MODULE_4__.getResourceUrl)("close");
  1772. closeElem.title = "Click to close the menu";
  1773. closeElem.addEventListener("click", closeMenu);
  1774. titleCont.appendChild(titleElem);
  1775. titleCont.appendChild(linksCont);
  1776. headerElem.appendChild(titleCont);
  1777. headerElem.appendChild(closeElem);
  1778. //#SECTION feature list
  1779. const featuresCont = document.createElement("div");
  1780. featuresCont.id = "bytm-menu-opts";
  1781. featuresCont.style.display = "flex";
  1782. featuresCont.style.flexDirection = "column";
  1783. featuresCont.style.overflowY = "auto";
  1784. /** Gets called whenever the feature config is changed */
  1785. const confChanged = (0,_sv443_network_userutils__WEBPACK_IMPORTED_MODULE_0__.debounce)((key, initialVal, newVal) => __awaiter(this, void 0, void 0, function* () {
  1786. const fmt = (val) => typeof val === "object" ? JSON.stringify(val) : String(val);
  1787. (0,_utils__WEBPACK_IMPORTED_MODULE_4__.info)(`Feature config changed at key '${key}', from value '${fmt(initialVal)}' to '${fmt(newVal)}'`);
  1788. const featConf = Object.assign({}, (0,_config__WEBPACK_IMPORTED_MODULE_1__.getFeatures)());
  1789. featConf[key] = newVal;
  1790. yield (0,_config__WEBPACK_IMPORTED_MODULE_1__.saveFeatures)(featConf);
  1791. }));
  1792. const featureCfg = (0,_config__WEBPACK_IMPORTED_MODULE_1__.getFeatures)();
  1793. const featureCfgWithCategories = Object.entries(_features_index__WEBPACK_IMPORTED_MODULE_3__.featInfo)
  1794. .reduce((acc, [key, { category }]) => {
  1795. if (!acc[category])
  1796. acc[category] = {};
  1797. acc[category][key] = featureCfg[key];
  1798. return acc;
  1799. }, {});
  1800. const fmtVal = (v) => String(v).trim();
  1801. const toggleLabelText = (toggled) => toggled ? "On" : "Off";
  1802. for (const category in featureCfgWithCategories) {
  1803. const featObj = featureCfgWithCategories[category];
  1804. const catHeaderElem = document.createElement("h3");
  1805. catHeaderElem.classList.add("bytm-ftconf-category-header");
  1806. catHeaderElem.role = "heading";
  1807. catHeaderElem.ariaLevel = "2";
  1808. catHeaderElem.innerText = `${_features_index__WEBPACK_IMPORTED_MODULE_3__.categoryNames[category]}:`;
  1809. featuresCont.appendChild(catHeaderElem);
  1810. for (const featKey in featObj) {
  1811. const ftInfo = _features_index__WEBPACK_IMPORTED_MODULE_3__.featInfo[featKey];
  1812. // @ts-ignore
  1813. if (!ftInfo || ftInfo.hidden === true)
  1814. continue;
  1815. const { desc, type, default: ftDefault } = ftInfo;
  1816. // @ts-ignore
  1817. const step = (_a = ftInfo === null || ftInfo === void 0 ? void 0 : ftInfo.step) !== null && _a !== void 0 ? _a : undefined;
  1818. const val = featureCfg[featKey];
  1819. const initialVal = (_b = val !== null && val !== void 0 ? val : ftDefault) !== null && _b !== void 0 ? _b : undefined;
  1820. const ftConfElem = document.createElement("div");
  1821. ftConfElem.classList.add("bytm-ftitem");
  1822. {
  1823. const textElem = document.createElement("span");
  1824. textElem.style.display = "inline-block";
  1825. textElem.style.fontSize = "15px";
  1826. textElem.innerText = desc;
  1827. ftConfElem.appendChild(textElem);
  1828. }
  1829. {
  1830. let inputType = "text";
  1831. switch (type) {
  1832. case "toggle":
  1833. inputType = "checkbox";
  1834. break;
  1835. case "slider":
  1836. inputType = "range";
  1837. break;
  1838. case "number":
  1839. inputType = "number";
  1840. break;
  1841. }
  1842. const inputElemId = `bytm-ftconf-${featKey}-input`;
  1843. const ctrlElem = document.createElement("span");
  1844. ctrlElem.style.display = "inline-flex";
  1845. ctrlElem.style.alignItems = "center";
  1846. ctrlElem.style.whiteSpace = "nowrap";
  1847. const inputElem = document.createElement("input");
  1848. inputElem.classList.add("bytm-ftconf-input");
  1849. inputElem.id = inputElemId;
  1850. inputElem.type = inputType;
  1851. if (type === "toggle")
  1852. inputElem.style.marginLeft = "5px";
  1853. if (typeof initialVal !== "undefined")
  1854. inputElem.value = String(initialVal);
  1855. if (type === "number" && step)
  1856. inputElem.step = step;
  1857. // @ts-ignore
  1858. if (typeof ftInfo.min !== "undefined" && ftInfo.max !== "undefined") {
  1859. // @ts-ignore
  1860. inputElem.min = ftInfo.min;
  1861. // @ts-ignore
  1862. inputElem.max = ftInfo.max;
  1863. }
  1864. if (type === "toggle" && typeof initialVal !== "undefined")
  1865. inputElem.checked = Boolean(initialVal);
  1866. // @ts-ignore
  1867. const unitTxt = typeof ftInfo.unit === "string" ? " " + ftInfo.unit : "";
  1868. let labelElem;
  1869. if (type === "slider") {
  1870. labelElem = document.createElement("label");
  1871. labelElem.classList.add("bytm-ftconf-label");
  1872. labelElem.style.marginRight = "10px";
  1873. labelElem.style.fontSize = "16px";
  1874. labelElem.htmlFor = inputElemId;
  1875. labelElem.innerText = fmtVal(initialVal) + unitTxt;
  1876. inputElem.addEventListener("input", () => {
  1877. if (labelElem)
  1878. labelElem.innerText = fmtVal(parseInt(inputElem.value)) + unitTxt;
  1879. });
  1880. }
  1881. else if (type === "toggle") {
  1882. labelElem = document.createElement("label");
  1883. labelElem.classList.add("bytm-ftconf-label");
  1884. labelElem.style.paddingLeft = "10px";
  1885. labelElem.style.paddingRight = "5px";
  1886. labelElem.style.fontSize = "16px";
  1887. labelElem.htmlFor = inputElemId;
  1888. labelElem.innerText = toggleLabelText(Boolean(initialVal)) + unitTxt;
  1889. inputElem.addEventListener("input", () => {
  1890. if (labelElem)
  1891. labelElem.innerText = toggleLabelText(inputElem.checked) + unitTxt;
  1892. });
  1893. }
  1894. inputElem.addEventListener("input", () => {
  1895. let v = Number(String(inputElem.value).trim());
  1896. if (isNaN(v))
  1897. v = Number(inputElem.value);
  1898. if (typeof initialVal !== "undefined")
  1899. confChanged(featKey, initialVal, (type !== "toggle" ? v : inputElem.checked));
  1900. });
  1901. if (labelElem) {
  1902. labelElem.id = `bytm-ftconf-${featKey}-label`;
  1903. ctrlElem.appendChild(labelElem);
  1904. }
  1905. ctrlElem.appendChild(inputElem);
  1906. ftConfElem.appendChild(ctrlElem);
  1907. }
  1908. featuresCont.appendChild(ftConfElem);
  1909. }
  1910. }
  1911. _events__WEBPACK_IMPORTED_MODULE_5__.siteEvents.on("configImported", (newConfig) => {
  1912. for (const ftKey in _features_index__WEBPACK_IMPORTED_MODULE_3__.featInfo) {
  1913. const ftElem = document.querySelector(`#bytm-ftconf-${ftKey}-input`);
  1914. const labelElem = document.querySelector(`#bytm-ftconf-${ftKey}-label`);
  1915. if (!ftElem)
  1916. continue;
  1917. const ftInfo = _features_index__WEBPACK_IMPORTED_MODULE_3__.featInfo[ftKey];
  1918. const value = newConfig[ftKey];
  1919. if (ftInfo.type === "toggle")
  1920. ftElem.checked = Boolean(value);
  1921. else
  1922. ftElem.value = String(value);
  1923. if (!labelElem)
  1924. continue;
  1925. // @ts-ignore
  1926. const unitTxt = typeof ftInfo.unit === "string" ? " " + ftInfo.unit : "";
  1927. if (ftInfo.type === "slider")
  1928. labelElem.innerText = fmtVal(Number(value)) + unitTxt;
  1929. else if (ftInfo.type === "toggle")
  1930. labelElem.innerText = toggleLabelText(Boolean(value)) + unitTxt;
  1931. }
  1932. });
  1933. //#SECTION scroll indicator
  1934. const scrollIndicator = document.createElement("img");
  1935. scrollIndicator.id = "bytm-menu-scroll-indicator";
  1936. scrollIndicator.src = yield (0,_utils__WEBPACK_IMPORTED_MODULE_4__.getResourceUrl)("arrow_down");
  1937. scrollIndicator.role = "button";
  1938. scrollIndicator.title = "Click to scroll to the bottom";
  1939. featuresCont.appendChild(scrollIndicator);
  1940. scrollIndicator.addEventListener("click", () => {
  1941. const bottomAnchor = document.querySelector("#bytm-menu-bottom-anchor");
  1942. bottomAnchor === null || bottomAnchor === void 0 ? void 0 : bottomAnchor.scrollIntoView({
  1943. behavior: "smooth",
  1944. });
  1945. });
  1946. featuresCont.addEventListener("scroll", (evt) => {
  1947. var _a, _b;
  1948. const scrollPos = (_b = (_a = evt.target) === null || _a === void 0 ? void 0 : _a.scrollTop) !== null && _b !== void 0 ? _b : 0;
  1949. const scrollIndicator = document.querySelector("#bytm-menu-scroll-indicator");
  1950. if (!scrollIndicator)
  1951. return;
  1952. if (scrollIndicatorEnabled && scrollPos > scrollIndicatorOffsetThreshold && !scrollIndicator.classList.contains("bytm-hidden")) {
  1953. scrollIndicator.classList.add("bytm-hidden");
  1954. }
  1955. else if (scrollIndicatorEnabled && scrollPos <= scrollIndicatorOffsetThreshold && scrollIndicator.classList.contains("bytm-hidden")) {
  1956. scrollIndicator.classList.remove("bytm-hidden");
  1957. }
  1958. });
  1959. const bottomAnchor = document.createElement("div");
  1960. bottomAnchor.id = "bytm-menu-bottom-anchor";
  1961. featuresCont.appendChild(bottomAnchor);
  1962. //#SECTION footer
  1963. const footerCont = document.createElement("div");
  1964. footerCont.id = "bytm-menu-footer-cont";
  1965. const footerElem = document.createElement("div");
  1966. footerElem.id = "bytm-menu-footer";
  1967. footerElem.style.fontSize = "17px";
  1968. footerElem.style.textDecoration = "underline";
  1969. footerElem.innerText = "You need to reload the page to apply changes";
  1970. const reloadElem = document.createElement("button");
  1971. reloadElem.classList.add("bytm-btn");
  1972. reloadElem.style.marginLeft = "10px";
  1973. reloadElem.innerText = "Reload now";
  1974. reloadElem.title = "Click to reload the page";
  1975. reloadElem.addEventListener("click", () => {
  1976. closeMenu();
  1977. location.reload();
  1978. });
  1979. footerElem.appendChild(reloadElem);
  1980. const resetElem = document.createElement("button");
  1981. resetElem.classList.add("bytm-btn");
  1982. resetElem.title = "Click to reset all settings to their default values";
  1983. resetElem.innerText = "Reset";
  1984. resetElem.addEventListener("click", () => __awaiter(this, void 0, void 0, function* () {
  1985. if (confirm("Do you really want to reset all settings to their default values?\nThe page will be automatically reloaded.")) {
  1986. yield (0,_config__WEBPACK_IMPORTED_MODULE_1__.setDefaultFeatures)();
  1987. closeMenu();
  1988. location.reload();
  1989. }
  1990. }));
  1991. const exportElem = document.createElement("button");
  1992. exportElem.classList.add("bytm-btn");
  1993. exportElem.title = "Click to export all settings";
  1994. exportElem.innerText = "Export config";
  1995. exportElem.addEventListener("click", () => __awaiter(this, void 0, void 0, function* () {
  1996. closeMenu();
  1997. openExportMenu();
  1998. }));
  1999. const importElem = document.createElement("button");
  2000. importElem.classList.add("bytm-btn");
  2001. importElem.title = "Click to import settings you have previously exported";
  2002. importElem.innerText = "Import config";
  2003. importElem.addEventListener("click", () => __awaiter(this, void 0, void 0, function* () {
  2004. closeMenu();
  2005. openImportMenu();
  2006. }));
  2007. const buttonsCont = document.createElement("div");
  2008. buttonsCont.id = "bytm-menu-footer-buttons-cont";
  2009. buttonsCont.appendChild(exportElem);
  2010. buttonsCont.appendChild(importElem);
  2011. buttonsCont.appendChild(resetElem);
  2012. footerCont.appendChild(footerElem);
  2013. footerCont.appendChild(buttonsCont);
  2014. //#SECTION finalize
  2015. menuContainer.appendChild(headerElem);
  2016. menuContainer.appendChild(featuresCont);
  2017. const versionCont = document.createElement("div");
  2018. versionCont.id = "bytm-menu-version-cont";
  2019. const versionElem = document.createElement("span");
  2020. versionElem.id = "bytm-menu-version";
  2021. versionElem.innerText = `v${_constants__WEBPACK_IMPORTED_MODULE_2__.scriptInfo.version}`;
  2022. versionCont.appendChild(versionElem);
  2023. menuContainer.appendChild(footerCont);
  2024. menuContainer.appendChild(versionCont);
  2025. backgroundElem.appendChild(menuContainer);
  2026. document.body.appendChild(backgroundElem);
  2027. window.addEventListener("resize", (0,_sv443_network_userutils__WEBPACK_IMPORTED_MODULE_0__.debounce)(checkToggleScrollIndicator, 150));
  2028. yield addExportMenu();
  2029. yield addImportMenu();
  2030. (0,_utils__WEBPACK_IMPORTED_MODULE_4__.log)("Added menu element");
  2031. });
  2032. }
  2033. /** Closes the menu if it is open. If a bubbling event is passed, its propagation will be prevented. */
  2034. function closeMenu(evt) {
  2035. if (!isMenuOpen)
  2036. return;
  2037. isMenuOpen = false;
  2038. (evt === null || evt === void 0 ? void 0 : evt.bubbles) && evt.stopPropagation();
  2039. document.body.classList.remove("bytm-disable-scroll");
  2040. const menuBg = document.querySelector("#bytm-cfg-menu-bg");
  2041. menuBg.style.visibility = "hidden";
  2042. menuBg.style.display = "none";
  2043. }
  2044. /** Opens the menu if it is closed */
  2045. function openMenu() {
  2046. if (isMenuOpen)
  2047. return;
  2048. isMenuOpen = true;
  2049. document.body.classList.add("bytm-disable-scroll");
  2050. const menuBg = document.querySelector("#bytm-cfg-menu-bg");
  2051. menuBg.style.visibility = "visible";
  2052. menuBg.style.display = "block";
  2053. checkToggleScrollIndicator();
  2054. }
  2055. /** Checks if the features container is scrollable and toggles the scroll indicator accordingly */
  2056. function checkToggleScrollIndicator() {
  2057. const featuresCont = document.querySelector("#bytm-menu-opts");
  2058. const scrollIndicator = document.querySelector("#bytm-menu-scroll-indicator");
  2059. // disable scroll indicator if container doesn't scroll
  2060. if (featuresCont && scrollIndicator) {
  2061. const verticalScroll = (0,_sv443_network_userutils__WEBPACK_IMPORTED_MODULE_0__.isScrollable)(featuresCont).vertical;
  2062. /** If true, the indicator's threshold is under the available scrollable space and so it should be disabled */
  2063. const underThreshold = featuresCont.scrollHeight - featuresCont.clientHeight <= scrollIndicatorOffsetThreshold;
  2064. if (!underThreshold && verticalScroll && !scrollIndicatorEnabled) {
  2065. scrollIndicatorEnabled = true;
  2066. scrollIndicator.classList.remove("bytm-hidden");
  2067. }
  2068. if ((!verticalScroll && scrollIndicatorEnabled) || underThreshold) {
  2069. scrollIndicatorEnabled = false;
  2070. scrollIndicator.classList.add("bytm-hidden");
  2071. }
  2072. }
  2073. }
  2074. //#MARKER export menu
  2075. let isExportMenuOpen = false;
  2076. let exportSelectedOnce = false;
  2077. /** Adds a menu to copy the current configuration as JSON (hidden by default) */
  2078. function addExportMenu() {
  2079. return __awaiter(this, void 0, void 0, function* () {
  2080. const menuBgElem = document.createElement("div");
  2081. menuBgElem.id = "bytm-export-menu-bg";
  2082. menuBgElem.classList.add("bytm-menu-bg");
  2083. menuBgElem.title = "Click here to close the menu";
  2084. menuBgElem.style.visibility = "hidden";
  2085. menuBgElem.style.display = "none";
  2086. menuBgElem.addEventListener("click", (e) => {
  2087. var _a;
  2088. if (isExportMenuOpen && ((_a = e.target) === null || _a === void 0 ? void 0 : _a.id) === "bytm-export-menu-bg") {
  2089. closeExportMenu(e);
  2090. openMenu();
  2091. }
  2092. });
  2093. document.body.addEventListener("keydown", (e) => {
  2094. if (isExportMenuOpen && e.key === "Escape") {
  2095. closeExportMenu(e);
  2096. openMenu();
  2097. }
  2098. });
  2099. const menuContainer = document.createElement("div");
  2100. menuContainer.title = ""; // prevent bg title from propagating downwards
  2101. menuContainer.classList.add("bytm-menu");
  2102. menuContainer.id = "bytm-cfg-menu";
  2103. //#SECTION title bar
  2104. const headerElem = document.createElement("div");
  2105. headerElem.classList.add("bytm-menu-header");
  2106. const titleCont = document.createElement("div");
  2107. titleCont.id = "bytm-menu-titlecont";
  2108. titleCont.role = "heading";
  2109. titleCont.ariaLevel = "1";
  2110. const titleElem = document.createElement("h2");
  2111. titleElem.id = "bytm-menu-title";
  2112. titleElem.innerText = `${_constants__WEBPACK_IMPORTED_MODULE_2__.scriptInfo.name} - Export Configuration`;
  2113. const closeElem = document.createElement("img");
  2114. closeElem.classList.add("bytm-menu-close");
  2115. closeElem.src = yield (0,_utils__WEBPACK_IMPORTED_MODULE_4__.getResourceUrl)("close");
  2116. closeElem.title = "Click to close the menu";
  2117. closeElem.addEventListener("click", (e) => {
  2118. closeExportMenu(e);
  2119. openMenu();
  2120. });
  2121. titleCont.appendChild(titleElem);
  2122. headerElem.appendChild(titleCont);
  2123. headerElem.appendChild(closeElem);
  2124. //#SECTION body
  2125. const menuBodyElem = document.createElement("div");
  2126. menuBodyElem.classList.add("bytm-menu-body");
  2127. const textElem = document.createElement("div");
  2128. textElem.id = "bytm-export-menu-text";
  2129. textElem.innerText = "Copy the following text to export your configuration:";
  2130. const textAreaElem = document.createElement("textarea");
  2131. textAreaElem.id = "bytm-export-menu-textarea";
  2132. textAreaElem.readOnly = true;
  2133. textAreaElem.value = JSON.stringify({ formatVersion: _config__WEBPACK_IMPORTED_MODULE_1__.formatVersion, data: (0,_config__WEBPACK_IMPORTED_MODULE_1__.getFeatures)() });
  2134. textAreaElem.addEventListener("click", () => {
  2135. if (exportSelectedOnce)
  2136. return;
  2137. exportSelectedOnce = true;
  2138. textAreaElem.select();
  2139. });
  2140. _events__WEBPACK_IMPORTED_MODULE_5__.siteEvents.on("configChanged", (data) => {
  2141. const textAreaElem = document.querySelector("#bytm-export-menu-textarea");
  2142. if (textAreaElem)
  2143. textAreaElem.value = JSON.stringify({ formatVersion: _config__WEBPACK_IMPORTED_MODULE_1__.formatVersion, data });
  2144. });
  2145. //#SECTION finalize
  2146. menuBodyElem.appendChild(textElem);
  2147. menuBodyElem.appendChild(textAreaElem);
  2148. menuContainer.appendChild(headerElem);
  2149. menuContainer.appendChild(menuBodyElem);
  2150. menuBgElem.appendChild(menuContainer);
  2151. document.body.appendChild(menuBgElem);
  2152. });
  2153. }
  2154. /** Closes the export menu if it is open. If a bubbling event is passed, its propagation will be prevented. */
  2155. function closeExportMenu(evt) {
  2156. if (!isExportMenuOpen)
  2157. return;
  2158. isExportMenuOpen = false;
  2159. (evt === null || evt === void 0 ? void 0 : evt.bubbles) && evt.stopPropagation();
  2160. document.body.classList.remove("bytm-disable-scroll");
  2161. const menuBg = document.querySelector("#bytm-export-menu-bg");
  2162. if (!menuBg)
  2163. return (0,_utils__WEBPACK_IMPORTED_MODULE_4__.warn)("Couldn't find export menu background element");
  2164. menuBg.style.visibility = "hidden";
  2165. menuBg.style.display = "none";
  2166. }
  2167. /** Opens the export menu if it is closed */
  2168. function openExportMenu() {
  2169. if (isExportMenuOpen)
  2170. return;
  2171. isExportMenuOpen = true;
  2172. document.body.classList.add("bytm-disable-scroll");
  2173. const menuBg = document.querySelector("#bytm-export-menu-bg");
  2174. if (!menuBg)
  2175. return (0,_utils__WEBPACK_IMPORTED_MODULE_4__.warn)("Couldn't find export menu background element");
  2176. menuBg.style.visibility = "visible";
  2177. menuBg.style.display = "block";
  2178. }
  2179. //#MARKER import menu
  2180. let isImportMenuOpen = false;
  2181. /** Adds a menu to import a configuration from JSON (hidden by default) */
  2182. function addImportMenu() {
  2183. return __awaiter(this, void 0, void 0, function* () {
  2184. const menuBgElem = document.createElement("div");
  2185. menuBgElem.id = "bytm-import-menu-bg";
  2186. menuBgElem.classList.add("bytm-menu-bg");
  2187. menuBgElem.title = "Click here to close the menu";
  2188. menuBgElem.style.visibility = "hidden";
  2189. menuBgElem.style.display = "none";
  2190. menuBgElem.addEventListener("click", (e) => {
  2191. var _a;
  2192. if (isImportMenuOpen && ((_a = e.target) === null || _a === void 0 ? void 0 : _a.id) === "bytm-import-menu-bg") {
  2193. closeImportMenu(e);
  2194. openMenu();
  2195. }
  2196. });
  2197. document.body.addEventListener("keydown", (e) => {
  2198. if (isImportMenuOpen && e.key === "Escape") {
  2199. closeImportMenu(e);
  2200. openMenu();
  2201. }
  2202. });
  2203. const menuContainer = document.createElement("div");
  2204. menuContainer.title = ""; // prevent bg title from propagating downwards
  2205. menuContainer.classList.add("bytm-menu");
  2206. menuContainer.id = "bytm-cfg-menu";
  2207. //#SECTION title bar
  2208. const headerElem = document.createElement("div");
  2209. headerElem.classList.add("bytm-menu-header");
  2210. const titleCont = document.createElement("div");
  2211. titleCont.id = "bytm-menu-titlecont";
  2212. titleCont.role = "heading";
  2213. titleCont.ariaLevel = "1";
  2214. const titleElem = document.createElement("h2");
  2215. titleElem.id = "bytm-menu-title";
  2216. titleElem.innerText = `${_constants__WEBPACK_IMPORTED_MODULE_2__.scriptInfo.name} - Import Configuration`;
  2217. const closeElem = document.createElement("img");
  2218. closeElem.classList.add("bytm-menu-close");
  2219. closeElem.src = yield (0,_utils__WEBPACK_IMPORTED_MODULE_4__.getResourceUrl)("close");
  2220. closeElem.title = "Click to close the menu";
  2221. closeElem.addEventListener("click", (e) => {
  2222. closeImportMenu(e);
  2223. openMenu();
  2224. });
  2225. titleCont.appendChild(titleElem);
  2226. headerElem.appendChild(titleCont);
  2227. headerElem.appendChild(closeElem);
  2228. //#SECTION body
  2229. const menuBodyElem = document.createElement("div");
  2230. menuBodyElem.classList.add("bytm-menu-body");
  2231. const textElem = document.createElement("div");
  2232. textElem.id = "bytm-import-menu-text";
  2233. textElem.innerText = "Paste the configuration you want to import into the field below, then click the import button";
  2234. const textAreaElem = document.createElement("textarea");
  2235. textAreaElem.id = "bytm-import-menu-textarea";
  2236. //#SECTION footer
  2237. const footerElem = document.createElement("div");
  2238. footerElem.classList.add("bytm-menu-footer-right");
  2239. const importBtnElem = document.createElement("button");
  2240. importBtnElem.classList.add("bytm-btn");
  2241. importBtnElem.innerText = "Import";
  2242. importBtnElem.title = "Click to import the configuration";
  2243. importBtnElem.addEventListener("click", (evt) => __awaiter(this, void 0, void 0, function* () {
  2244. (evt === null || evt === void 0 ? void 0 : evt.bubbles) && evt.stopPropagation();
  2245. const textAreaElem = document.querySelector("#bytm-import-menu-textarea");
  2246. if (!textAreaElem)
  2247. return (0,_utils__WEBPACK_IMPORTED_MODULE_4__.warn)("Couldn't find import menu textarea element");
  2248. try {
  2249. const parsed = JSON.parse(textAreaElem.value.trim());
  2250. if (typeof parsed !== "object")
  2251. return alert("The imported data is not an object");
  2252. if (typeof parsed.formatVersion !== "number")
  2253. return alert("The imported data does not contain a format version");
  2254. if (typeof parsed.data !== "object")
  2255. return alert("The imported object does not contain any data");
  2256. if (parsed.formatVersion < _config__WEBPACK_IMPORTED_MODULE_1__.formatVersion) {
  2257. let newData = JSON.parse(JSON.stringify(parsed.data));
  2258. const sortedMigrations = Object.entries(_config__WEBPACK_IMPORTED_MODULE_1__.migrations)
  2259. .sort(([a], [b]) => Number(a) - Number(b));
  2260. let curFmtVer = Number(parsed.formatVersion);
  2261. for (const [fmtVer, migrationFunc] of sortedMigrations) {
  2262. const ver = Number(fmtVer);
  2263. if (curFmtVer < _config__WEBPACK_IMPORTED_MODULE_1__.formatVersion && curFmtVer < ver) {
  2264. try {
  2265. const migRes = JSON.parse(JSON.stringify(migrationFunc(newData)));
  2266. newData = migRes instanceof Promise ? yield migRes : migRes;
  2267. curFmtVer = ver;
  2268. }
  2269. catch (err) {
  2270. console.error(`Error while running migration function for format version ${fmtVer}:`, err);
  2271. }
  2272. }
  2273. }
  2274. parsed.formatVersion = curFmtVer;
  2275. parsed.data = newData;
  2276. }
  2277. else if (parsed.formatVersion !== _config__WEBPACK_IMPORTED_MODULE_1__.formatVersion)
  2278. return alert(`The imported data is in an unsupported format version (expected ${_config__WEBPACK_IMPORTED_MODULE_1__.formatVersion} or lower, got ${parsed.formatVersion})`);
  2279. yield (0,_config__WEBPACK_IMPORTED_MODULE_1__.saveFeatures)(parsed.data);
  2280. _events__WEBPACK_IMPORTED_MODULE_5__.siteEvents.emit("configImported", parsed.data);
  2281. if (confirm("Successfully imported the configuration.\nDo you want to reload the page now to apply changes?"))
  2282. return location.reload();
  2283. closeImportMenu();
  2284. openMenu();
  2285. }
  2286. catch (err) {
  2287. (0,_utils__WEBPACK_IMPORTED_MODULE_4__.warn)("Couldn't import configuration:", err);
  2288. alert("The imported data is not a valid configuration");
  2289. }
  2290. }));
  2291. footerElem.appendChild(importBtnElem);
  2292. //#SECTION finalize
  2293. menuBodyElem.appendChild(textElem);
  2294. menuBodyElem.appendChild(textAreaElem);
  2295. menuBodyElem.appendChild(footerElem);
  2296. menuContainer.appendChild(headerElem);
  2297. menuContainer.appendChild(menuBodyElem);
  2298. menuBgElem.appendChild(menuContainer);
  2299. document.body.appendChild(menuBgElem);
  2300. });
  2301. }
  2302. /** Closes the import menu if it is open. If a bubbling event is passed, its propagation will be prevented. */
  2303. function closeImportMenu(evt) {
  2304. if (!isImportMenuOpen)
  2305. return;
  2306. isImportMenuOpen = false;
  2307. (evt === null || evt === void 0 ? void 0 : evt.bubbles) && evt.stopPropagation();
  2308. document.body.classList.remove("bytm-disable-scroll");
  2309. const menuBg = document.querySelector("#bytm-import-menu-bg");
  2310. const textAreaElem = document.querySelector("#bytm-import-menu-textarea");
  2311. if (textAreaElem)
  2312. textAreaElem.value = "";
  2313. if (!menuBg)
  2314. return (0,_utils__WEBPACK_IMPORTED_MODULE_4__.warn)("Couldn't find import menu background element");
  2315. menuBg.style.visibility = "hidden";
  2316. menuBg.style.display = "none";
  2317. }
  2318. /** Opens the import menu if it is closed */
  2319. function openImportMenu() {
  2320. if (isImportMenuOpen)
  2321. return;
  2322. isImportMenuOpen = true;
  2323. document.body.classList.add("bytm-disable-scroll");
  2324. const menuBg = document.querySelector("#bytm-import-menu-bg");
  2325. if (!menuBg)
  2326. return (0,_utils__WEBPACK_IMPORTED_MODULE_4__.warn)("Couldn't find import menu background element");
  2327. menuBg.style.visibility = "visible";
  2328. menuBg.style.display = "block";
  2329. }
  2330. //#MARKER changelog menu
  2331. /** TODO: Adds a changelog menu to the DOM (hidden by default) */
  2332. function addChangelogMenu() {
  2333. return __awaiter(this, void 0, void 0, function* () {
  2334. void 0;
  2335. });
  2336. }
  2337. /***/ }),
  2338. /***/ "./src/utils.ts":
  2339. /*!**********************!*\
  2340. !*** ./src/utils.ts ***!
  2341. \**********************/
  2342. /***/ (function(__unused_webpack_module, __webpack_exports__, __webpack_require__) {
  2343. __webpack_require__.r(__webpack_exports__);
  2344. /* harmony export */ __webpack_require__.d(__webpack_exports__, {
  2345. /* harmony export */ dbg: function() { return /* binding */ dbg; },
  2346. /* harmony export */ error: function() { return /* binding */ error; },
  2347. /* harmony export */ getDomain: function() { return /* binding */ getDomain; },
  2348. /* harmony export */ getResourceUrl: function() { return /* binding */ getResourceUrl; },
  2349. /* harmony export */ getVideoTime: function() { return /* binding */ getVideoTime; },
  2350. /* harmony export */ info: function() { return /* binding */ info; },
  2351. /* harmony export */ log: function() { return /* binding */ log; },
  2352. /* harmony export */ setLogLevel: function() { return /* binding */ setLogLevel; },
  2353. /* harmony export */ warn: function() { return /* binding */ warn; }
  2354. /* harmony export */ });
  2355. /* harmony import */ var _sv443_network_userutils__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @sv443-network/userutils */ "./node_modules/@sv443-network/userutils/dist/index.mjs");
  2356. /* harmony import */ var _constants__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./constants */ "./src/constants.ts");
  2357. //#SECTION logging
  2358. let curLogLevel = 1;
  2359. /** Sets the current log level. 0 = Debug, 1 = Info */
  2360. function setLogLevel(level) {
  2361. curLogLevel = level;
  2362. }
  2363. /** 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 */
  2364. function getLogLevel(args) {
  2365. const minLogLvl = 0, maxLogLvl = 1;
  2366. if (typeof args.at(-1) === "number")
  2367. return (0,_sv443_network_userutils__WEBPACK_IMPORTED_MODULE_0__.clamp)(args.splice(args.length - 1)[0], minLogLvl, maxLogLvl);
  2368. return 0;
  2369. }
  2370. /** Common prefix to be able to tell logged messages apart and filter them in devtools */
  2371. const consPrefix = `[${_constants__WEBPACK_IMPORTED_MODULE_1__.scriptInfo.name}]`;
  2372. const consPrefixDbg = `[${_constants__WEBPACK_IMPORTED_MODULE_1__.scriptInfo.name}/#DEBUG]`;
  2373. /**
  2374. * Logs all passed values to the console, as long as the log level is sufficient.
  2375. * @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.
  2376. */
  2377. function log(...args) {
  2378. if (curLogLevel <= getLogLevel(args))
  2379. console.log(consPrefix, ...args);
  2380. }
  2381. /**
  2382. * Logs all passed values to the console as info, as long as the log level is sufficient.
  2383. * @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.
  2384. */
  2385. function info(...args) {
  2386. if (curLogLevel <= getLogLevel(args))
  2387. console.info(consPrefix, ...args);
  2388. }
  2389. /** Logs all passed values to the console as a warning, no matter the log level. */
  2390. function warn(...args) {
  2391. console.warn(consPrefix, ...args);
  2392. }
  2393. /** Logs all passed values to the console as an error, no matter the log level. */
  2394. function error(...args) {
  2395. console.error(consPrefix, ...args);
  2396. }
  2397. /** Logs all passed values to the console with a debug-specific prefix */
  2398. function dbg(...args) {
  2399. console.log(consPrefixDbg, ...args);
  2400. }
  2401. //#SECTION video time
  2402. /**
  2403. * Returns the current video time in seconds
  2404. * Dispatches mouse movement events in case the video time can't be estimated
  2405. * @returns Returns null if the video time is unavailable
  2406. */
  2407. function getVideoTime() {
  2408. return new Promise((res) => {
  2409. const domain = getDomain();
  2410. try {
  2411. if (domain === "ytm") {
  2412. (0,_sv443_network_userutils__WEBPACK_IMPORTED_MODULE_0__.onSelector)("#progress-bar", {
  2413. listener: (pbEl) => res(!isNaN(Number(pbEl.value)) ? Number(pbEl.value) : null)
  2414. });
  2415. }
  2416. else if (domain === "yt") {
  2417. // YT doesn't update the progress bar when it's hidden (contrary to YTM which never hides it)
  2418. ytForceShowVideoTime();
  2419. const pbSelector = ".ytp-chrome-bottom div.ytp-progress-bar[role=\"slider\"]";
  2420. let videoTime = -1;
  2421. const mut = new MutationObserver(() => {
  2422. // .observe() is only called when the element exists - no need to check for null
  2423. videoTime = Number(document.querySelector(pbSelector).getAttribute("aria-valuenow"));
  2424. });
  2425. const observe = (progElem) => {
  2426. mut.observe(progElem, {
  2427. attributes: true,
  2428. attributeFilter: ["aria-valuenow"],
  2429. });
  2430. if (videoTime >= 0 && !isNaN(videoTime)) {
  2431. res(videoTime);
  2432. mut.disconnect();
  2433. }
  2434. else
  2435. setTimeout(() => {
  2436. res(videoTime >= 0 && !isNaN(videoTime) ? videoTime : null);
  2437. mut.disconnect();
  2438. }, 500);
  2439. };
  2440. (0,_sv443_network_userutils__WEBPACK_IMPORTED_MODULE_0__.onSelector)(pbSelector, { listener: observe });
  2441. }
  2442. }
  2443. catch (err) {
  2444. error("Couldn't get video time due to error:", err);
  2445. res(null);
  2446. }
  2447. });
  2448. }
  2449. /**
  2450. * Sends events that force the video controls to become visible for about 3 seconds.
  2451. * This only works once, then the page needs to be reloaded!
  2452. */
  2453. function ytForceShowVideoTime() {
  2454. const player = document.querySelector("#movie_player");
  2455. if (!player)
  2456. return false;
  2457. const defaultProps = {
  2458. // needed because otherwise YTM errors out - see https://github.com/Sv443/BetterYTM/issues/18#show_issue
  2459. view: (0,_sv443_network_userutils__WEBPACK_IMPORTED_MODULE_0__.getUnsafeWindow)(),
  2460. bubbles: true,
  2461. cancelable: false,
  2462. };
  2463. player.dispatchEvent(new MouseEvent("mouseenter", defaultProps));
  2464. const { x, y, width, height } = player.getBoundingClientRect();
  2465. const screenY = Math.round(y + height / 2);
  2466. const screenX = x + Math.min(50, Math.round(width / 3));
  2467. player.dispatchEvent(new MouseEvent("mousemove", Object.assign(Object.assign({}, defaultProps), { screenY,
  2468. screenX, movementX: 5, movementY: 0 })));
  2469. return true;
  2470. }
  2471. // /** Parses a video time string in the format `[hh:m]m:ss` to the equivalent number of seconds - returns 0 if input couldn't be parsed */
  2472. // function parseVideoTime(videoTime: string) {
  2473. // const matches = /^((\d{1,2}):)?(\d{1,2}):(\d{2})$/.exec(videoTime);
  2474. // if(!matches)
  2475. // return 0;
  2476. // const [, , hrs, min, sec] = matches as unknown as [string, string | undefined, string | undefined, string, string];
  2477. // let finalTime = 0;
  2478. // if(hrs)
  2479. // finalTime += Number(hrs) * 60 * 60;
  2480. // finalTime += Number(min) * 60 + Number(sec);
  2481. // return isNaN(finalTime) ? 0 : finalTime;
  2482. // }
  2483. /**
  2484. * Returns the current domain as a constant string representation
  2485. * @throws Throws if script runs on an unexpected website
  2486. */
  2487. function getDomain() {
  2488. if (location.hostname.match(/^music\.youtube/))
  2489. return "ytm";
  2490. else if (location.hostname.match(/youtube\./))
  2491. return "yt";
  2492. else
  2493. throw new Error("BetterYTM is running on an unexpected website. Please don't tamper with the @match directives in the userscript header.");
  2494. }
  2495. /** 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) */
  2496. function getResourceUrl(name) {
  2497. return GM.getResourceUrl(name);
  2498. }
  2499. /***/ }),
  2500. /***/ "./node_modules/@sv443-network/userutils/dist/index.mjs":
  2501. /*!**************************************************************!*\
  2502. !*** ./node_modules/@sv443-network/userutils/dist/index.mjs ***!
  2503. \**************************************************************/
  2504. /***/ (function(__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) {
  2505. __webpack_require__.r(__webpack_exports__);
  2506. /* harmony export */ __webpack_require__.d(__webpack_exports__, {
  2507. /* harmony export */ ConfigManager: function() { return /* binding */ ConfigManager; },
  2508. /* harmony export */ addGlobalStyle: function() { return /* binding */ addGlobalStyle; },
  2509. /* harmony export */ addParent: function() { return /* binding */ addParent; },
  2510. /* harmony export */ amplifyMedia: function() { return /* binding */ amplifyMedia; },
  2511. /* harmony export */ autoPlural: function() { return /* binding */ autoPlural; },
  2512. /* harmony export */ clamp: function() { return /* binding */ clamp; },
  2513. /* harmony export */ debounce: function() { return /* binding */ debounce; },
  2514. /* harmony export */ fetchAdvanced: function() { return /* binding */ fetchAdvanced; },
  2515. /* harmony export */ getSelectorMap: function() { return /* binding */ getSelectorMap; },
  2516. /* harmony export */ getUnsafeWindow: function() { return /* binding */ getUnsafeWindow; },
  2517. /* harmony export */ initOnSelector: function() { return /* binding */ initOnSelector; },
  2518. /* harmony export */ insertAfter: function() { return /* binding */ insertAfter; },
  2519. /* harmony export */ interceptEvent: function() { return /* binding */ interceptEvent; },
  2520. /* harmony export */ interceptWindowEvent: function() { return /* binding */ interceptWindowEvent; },
  2521. /* harmony export */ isScrollable: function() { return /* binding */ isScrollable; },
  2522. /* harmony export */ mapRange: function() { return /* binding */ mapRange; },
  2523. /* harmony export */ onSelector: function() { return /* binding */ onSelector; },
  2524. /* harmony export */ openInNewTab: function() { return /* binding */ openInNewTab; },
  2525. /* harmony export */ pauseFor: function() { return /* binding */ pauseFor; },
  2526. /* harmony export */ preloadImages: function() { return /* binding */ preloadImages; },
  2527. /* harmony export */ randRange: function() { return /* binding */ randRange; },
  2528. /* harmony export */ randomItem: function() { return /* binding */ randomItem; },
  2529. /* harmony export */ randomItemIndex: function() { return /* binding */ randomItemIndex; },
  2530. /* harmony export */ randomizeArray: function() { return /* binding */ randomizeArray; },
  2531. /* harmony export */ removeOnSelector: function() { return /* binding */ removeOnSelector; },
  2532. /* harmony export */ takeRandomItem: function() { return /* binding */ takeRandomItem; }
  2533. /* harmony export */ });
  2534. var __defProp = Object.defineProperty;
  2535. var __defProps = Object.defineProperties;
  2536. var __getOwnPropDescs = Object.getOwnPropertyDescriptors;
  2537. var __getOwnPropSymbols = Object.getOwnPropertySymbols;
  2538. var __hasOwnProp = Object.prototype.hasOwnProperty;
  2539. var __propIsEnum = Object.prototype.propertyIsEnumerable;
  2540. var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
  2541. var __spreadValues = (a, b) => {
  2542. for (var prop in b || (b = {}))
  2543. if (__hasOwnProp.call(b, prop))
  2544. __defNormalProp(a, prop, b[prop]);
  2545. if (__getOwnPropSymbols)
  2546. for (var prop of __getOwnPropSymbols(b)) {
  2547. if (__propIsEnum.call(b, prop))
  2548. __defNormalProp(a, prop, b[prop]);
  2549. }
  2550. return a;
  2551. };
  2552. var __spreadProps = (a, b) => __defProps(a, __getOwnPropDescs(b));
  2553. var __publicField = (obj, key, value) => {
  2554. __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
  2555. return value;
  2556. };
  2557. var __async = (__this, __arguments, generator) => {
  2558. return new Promise((resolve, reject) => {
  2559. var fulfilled = (value) => {
  2560. try {
  2561. step(generator.next(value));
  2562. } catch (e) {
  2563. reject(e);
  2564. }
  2565. };
  2566. var rejected = (value) => {
  2567. try {
  2568. step(generator.throw(value));
  2569. } catch (e) {
  2570. reject(e);
  2571. }
  2572. };
  2573. var step = (x) => x.done ? resolve(x.value) : Promise.resolve(x.value).then(fulfilled, rejected);
  2574. step((generator = generator.apply(__this, __arguments)).next());
  2575. });
  2576. };
  2577. // lib/math.ts
  2578. function clamp(value, min, max) {
  2579. return Math.max(Math.min(value, max), min);
  2580. }
  2581. function mapRange(value, range_1_min, range_1_max, range_2_min, range_2_max) {
  2582. if (Number(range_1_min) === 0 && Number(range_2_min) === 0)
  2583. return value * (range_2_max / range_1_max);
  2584. return (value - range_1_min) * ((range_2_max - range_2_min) / (range_1_max - range_1_min)) + range_2_min;
  2585. }
  2586. function randRange(...args) {
  2587. let min, max;
  2588. if (typeof args[0] === "number" && typeof args[1] === "number") {
  2589. [min, max] = args;
  2590. } else if (typeof args[0] === "number" && typeof args[1] !== "number") {
  2591. min = 0;
  2592. max = args[0];
  2593. } else
  2594. throw new TypeError(`Wrong parameter(s) provided - expected: "number" and "number|undefined", got: "${typeof args[0]}" and "${typeof args[1]}"`);
  2595. min = Number(min);
  2596. max = Number(max);
  2597. if (isNaN(min) || isNaN(max))
  2598. throw new TypeError(`Parameters "min" and "max" can't be NaN`);
  2599. if (min > max)
  2600. throw new TypeError(`Parameter "min" can't be bigger than "max"`);
  2601. return Math.floor(Math.random() * (max - min + 1)) + min;
  2602. }
  2603. // lib/array.ts
  2604. function randomItem(array) {
  2605. return randomItemIndex(array)[0];
  2606. }
  2607. function randomItemIndex(array) {
  2608. if (array.length === 0)
  2609. return [void 0, void 0];
  2610. const idx = randRange(array.length - 1);
  2611. return [array[idx], idx];
  2612. }
  2613. function takeRandomItem(arr) {
  2614. const [itm, idx] = randomItemIndex(arr);
  2615. if (idx === void 0)
  2616. return void 0;
  2617. arr.splice(idx, 1);
  2618. return itm;
  2619. }
  2620. function randomizeArray(array) {
  2621. const retArray = [...array];
  2622. if (array.length === 0)
  2623. return array;
  2624. for (let i = retArray.length - 1; i > 0; i--) {
  2625. const j = Math.floor(randRange(0, 1e4) / 1e4 * (i + 1));
  2626. [retArray[i], retArray[j]] = [retArray[j], retArray[i]];
  2627. }
  2628. return retArray;
  2629. }
  2630. // lib/config.ts
  2631. var ConfigManager = class {
  2632. /**
  2633. * Creates an instance of ConfigManager to manage a user configuration that is cached in memory and persistently saved across sessions.
  2634. * Supports migrating data from older versions of the configuration to newer ones and populating the cache with default data if no persistent data is found.
  2635. *
  2636. * ⚠️ Requires the directives `@grant GM.getValue` and `@grant GM.setValue`
  2637. * ⚠️ Make sure to call `loadData()` at least once after creating an instance, or the returned data will be the same as `options.defaultConfig`
  2638. *
  2639. * @template TData The type of the data that is saved in persistent storage (will be automatically inferred from `config.defaultConfig`) - this should also be the type of the data format associated with the current `options.formatVersion`
  2640. * @param options The options for this ConfigManager instance
  2641. */
  2642. constructor(options) {
  2643. __publicField(this, "id");
  2644. __publicField(this, "formatVersion");
  2645. __publicField(this, "defaultConfig");
  2646. __publicField(this, "cachedConfig");
  2647. __publicField(this, "migrations");
  2648. this.id = options.id;
  2649. this.formatVersion = options.formatVersion;
  2650. this.defaultConfig = options.defaultConfig;
  2651. this.cachedConfig = options.defaultConfig;
  2652. this.migrations = options.migrations;
  2653. }
  2654. /**
  2655. * Loads the data saved in persistent storage into the in-memory cache and also returns it.
  2656. * Automatically populates persistent storage with default data if it doesn't contain any data yet.
  2657. * Also runs all necessary migration functions if the data format has changed since the last time the data was saved.
  2658. */
  2659. loadData() {
  2660. return __async(this, null, function* () {
  2661. try {
  2662. const gmData = yield GM.getValue(`_uucfg-${this.id}`, this.defaultConfig);
  2663. let gmFmtVer = Number(yield GM.getValue(`_uucfgver-${this.id}`));
  2664. if (typeof gmData !== "string") {
  2665. yield this.saveDefaultData();
  2666. return this.defaultConfig;
  2667. }
  2668. if (isNaN(gmFmtVer))
  2669. yield GM.setValue(`_uucfgver-${this.id}`, gmFmtVer = this.formatVersion);
  2670. let parsed = JSON.parse(gmData);
  2671. if (gmFmtVer < this.formatVersion && this.migrations)
  2672. parsed = yield this.runMigrations(parsed, gmFmtVer);
  2673. return this.cachedConfig = typeof parsed === "object" ? parsed : void 0;
  2674. } catch (err) {
  2675. yield this.saveDefaultData();
  2676. return this.defaultConfig;
  2677. }
  2678. });
  2679. }
  2680. /** Returns a copy of the data from the in-memory cache. Use `loadData()` to get fresh data from persistent storage (usually not necessary since the cache should always exactly reflect persistent storage). */
  2681. getData() {
  2682. return this.deepCopy(this.cachedConfig);
  2683. }
  2684. /** Saves the data synchronously to the in-memory cache and asynchronously to the persistent storage */
  2685. setData(data) {
  2686. this.cachedConfig = data;
  2687. return new Promise((resolve) => __async(this, null, function* () {
  2688. yield Promise.all([
  2689. GM.setValue(`_uucfg-${this.id}`, JSON.stringify(data)),
  2690. GM.setValue(`_uucfgver-${this.id}`, this.formatVersion)
  2691. ]);
  2692. resolve();
  2693. }));
  2694. }
  2695. /** Saves the default configuration data passed in the constructor synchronously to the in-memory cache and asynchronously to persistent storage */
  2696. saveDefaultData() {
  2697. return __async(this, null, function* () {
  2698. this.cachedConfig = this.defaultConfig;
  2699. return new Promise((resolve) => __async(this, null, function* () {
  2700. yield Promise.all([
  2701. GM.setValue(`_uucfg-${this.id}`, JSON.stringify(this.defaultConfig)),
  2702. GM.setValue(`_uucfgver-${this.id}`, this.formatVersion)
  2703. ]);
  2704. resolve();
  2705. }));
  2706. });
  2707. }
  2708. /**
  2709. * Call this method to clear all persistently stored data associated with this ConfigManager instance.
  2710. * The in-memory cache will be left untouched, so you may still access the data with `getData()`.
  2711. * Calling `loadData()` or `setData()` after this method was called will recreate persistent storage with the cached or default data.
  2712. *
  2713. * ⚠️ This requires the additional directive `@grant GM.deleteValue`
  2714. */
  2715. deleteConfig() {
  2716. return __async(this, null, function* () {
  2717. yield Promise.all([
  2718. GM.deleteValue(`_uucfg-${this.id}`),
  2719. GM.deleteValue(`_uucfgver-${this.id}`)
  2720. ]);
  2721. });
  2722. }
  2723. /** Runs all necessary migration functions consecutively - may be overwritten in a subclass */
  2724. runMigrations(oldData, oldFmtVer) {
  2725. return __async(this, null, function* () {
  2726. if (!this.migrations)
  2727. return oldData;
  2728. let newData = oldData;
  2729. const sortedMigrations = Object.entries(this.migrations).sort(([a], [b]) => Number(a) - Number(b));
  2730. let lastFmtVer = oldFmtVer;
  2731. for (const [fmtVer, migrationFunc] of sortedMigrations) {
  2732. const ver = Number(fmtVer);
  2733. if (oldFmtVer < this.formatVersion && oldFmtVer < ver) {
  2734. try {
  2735. const migRes = migrationFunc(newData);
  2736. newData = migRes instanceof Promise ? yield migRes : migRes;
  2737. lastFmtVer = oldFmtVer = ver;
  2738. } catch (err) {
  2739. console.error(`Error while running migration function for format version ${fmtVer}:`, err);
  2740. }
  2741. }
  2742. }
  2743. yield Promise.all([
  2744. GM.setValue(`_uucfg-${this.id}`, JSON.stringify(newData)),
  2745. GM.setValue(`_uucfgver-${this.id}`, lastFmtVer)
  2746. ]);
  2747. return newData;
  2748. });
  2749. }
  2750. /** Copies a JSON-compatible object and loses its internal references */
  2751. deepCopy(obj) {
  2752. return JSON.parse(JSON.stringify(obj));
  2753. }
  2754. };
  2755. // lib/dom.ts
  2756. function getUnsafeWindow() {
  2757. try {
  2758. return unsafeWindow;
  2759. } catch (e) {
  2760. return window;
  2761. }
  2762. }
  2763. function insertAfter(beforeElement, afterElement) {
  2764. var _a;
  2765. (_a = beforeElement.parentNode) == null ? void 0 : _a.insertBefore(afterElement, beforeElement.nextSibling);
  2766. return afterElement;
  2767. }
  2768. function addParent(element, newParent) {
  2769. const oldParent = element.parentNode;
  2770. if (!oldParent)
  2771. throw new Error("Element doesn't have a parent node");
  2772. oldParent.replaceChild(newParent, element);
  2773. newParent.appendChild(element);
  2774. return newParent;
  2775. }
  2776. function addGlobalStyle(style) {
  2777. const styleElem = document.createElement("style");
  2778. styleElem.innerHTML = style;
  2779. document.head.appendChild(styleElem);
  2780. }
  2781. function preloadImages(srcUrls, rejects = false) {
  2782. const promises = srcUrls.map((src) => new Promise((res, rej) => {
  2783. const image = new Image();
  2784. image.src = src;
  2785. image.addEventListener("load", () => res(image));
  2786. image.addEventListener("error", (evt) => rejects && rej(evt));
  2787. }));
  2788. return Promise.allSettled(promises);
  2789. }
  2790. function openInNewTab(href) {
  2791. const openElem = document.createElement("a");
  2792. Object.assign(openElem, {
  2793. className: "userutils-open-in-new-tab",
  2794. target: "_blank",
  2795. rel: "noopener noreferrer",
  2796. href
  2797. });
  2798. openElem.style.display = "none";
  2799. document.body.appendChild(openElem);
  2800. openElem.click();
  2801. setTimeout(openElem.remove, 50);
  2802. }
  2803. function interceptEvent(eventObject, eventName, predicate) {
  2804. if (typeof Error.stackTraceLimit === "number" && Error.stackTraceLimit < 1e3) {
  2805. Error.stackTraceLimit = 1e3;
  2806. }
  2807. (function(original) {
  2808. eventObject.__proto__.addEventListener = function(...args) {
  2809. var _a, _b;
  2810. const origListener = typeof args[1] === "function" ? args[1] : (_b = (_a = args[1]) == null ? void 0 : _a.handleEvent) != null ? _b : () => void 0;
  2811. args[1] = function(...a) {
  2812. if (args[0] === eventName && predicate(Array.isArray(a) ? a[0] : a))
  2813. return;
  2814. else
  2815. return origListener.apply(this, a);
  2816. };
  2817. original.apply(this, args);
  2818. };
  2819. })(eventObject.__proto__.addEventListener);
  2820. }
  2821. function interceptWindowEvent(eventName, predicate) {
  2822. return interceptEvent(getUnsafeWindow(), eventName, predicate);
  2823. }
  2824. function amplifyMedia(mediaElement, multiplier = 1) {
  2825. const context = new (window.AudioContext || window.webkitAudioContext)();
  2826. const result = {
  2827. mediaElement,
  2828. amplify: (multiplier2) => {
  2829. result.gain.gain.value = multiplier2;
  2830. },
  2831. getAmpLevel: () => result.gain.gain.value,
  2832. context,
  2833. source: context.createMediaElementSource(mediaElement),
  2834. gain: context.createGain()
  2835. };
  2836. result.source.connect(result.gain);
  2837. result.gain.connect(context.destination);
  2838. result.amplify(multiplier);
  2839. return result;
  2840. }
  2841. function isScrollable(element) {
  2842. const { overflowX, overflowY } = getComputedStyle(element);
  2843. return {
  2844. vertical: (overflowY === "scroll" || overflowY === "auto") && element.scrollHeight > element.clientHeight,
  2845. horizontal: (overflowX === "scroll" || overflowX === "auto") && element.scrollWidth > element.clientWidth
  2846. };
  2847. }
  2848. // lib/misc.ts
  2849. function autoPlural(word, num) {
  2850. if (Array.isArray(num) || num instanceof NodeList)
  2851. num = num.length;
  2852. return `${word}${num === 1 ? "" : "s"}`;
  2853. }
  2854. function pauseFor(time) {
  2855. return new Promise((res) => {
  2856. setTimeout(() => res(), time);
  2857. });
  2858. }
  2859. function debounce(func, timeout = 300) {
  2860. let timer;
  2861. return function(...args) {
  2862. clearTimeout(timer);
  2863. timer = setTimeout(() => func.apply(this, args), timeout);
  2864. };
  2865. }
  2866. function fetchAdvanced(_0) {
  2867. return __async(this, arguments, function* (url, options = {}) {
  2868. const { timeout = 1e4 } = options;
  2869. const controller = new AbortController();
  2870. const id = setTimeout(() => controller.abort(), timeout);
  2871. const res = yield fetch(url, __spreadProps(__spreadValues({}, options), {
  2872. signal: controller.signal
  2873. }));
  2874. clearTimeout(id);
  2875. return res;
  2876. });
  2877. }
  2878. // lib/onSelector.ts
  2879. var selectorMap = /* @__PURE__ */ new Map();
  2880. function onSelector(selector, options) {
  2881. let selectorMapItems = [];
  2882. if (selectorMap.has(selector))
  2883. selectorMapItems = selectorMap.get(selector);
  2884. selectorMapItems.push(options);
  2885. selectorMap.set(selector, selectorMapItems);
  2886. checkSelectorExists(selector, selectorMapItems);
  2887. }
  2888. function removeOnSelector(selector) {
  2889. return selectorMap.delete(selector);
  2890. }
  2891. function checkSelectorExists(selector, options) {
  2892. const deleteIndices = [];
  2893. options.forEach((option, i) => {
  2894. try {
  2895. const elements = option.all ? document.querySelectorAll(selector) : document.querySelector(selector);
  2896. if (elements !== null && elements instanceof NodeList && elements.length > 0 || elements !== null) {
  2897. option.listener(elements);
  2898. if (!option.continuous)
  2899. deleteIndices.push(i);
  2900. }
  2901. } catch (err) {
  2902. console.error(`Couldn't call listener for selector '${selector}'`, err);
  2903. }
  2904. });
  2905. if (deleteIndices.length > 0) {
  2906. const newOptsArray = options.filter((_, i) => !deleteIndices.includes(i));
  2907. if (newOptsArray.length === 0)
  2908. selectorMap.delete(selector);
  2909. else {
  2910. selectorMap.set(selector, newOptsArray);
  2911. }
  2912. }
  2913. }
  2914. function initOnSelector(options = {}) {
  2915. const observer = new MutationObserver(() => {
  2916. for (const [selector, options2] of selectorMap.entries())
  2917. checkSelectorExists(selector, options2);
  2918. });
  2919. observer.observe(document.body, __spreadValues({
  2920. subtree: true,
  2921. childList: true
  2922. }, options));
  2923. }
  2924. function getSelectorMap() {
  2925. return selectorMap;
  2926. }
  2927. /***/ }),
  2928. /***/ "./node_modules/nanoevents/index.js":
  2929. /*!******************************************!*\
  2930. !*** ./node_modules/nanoevents/index.js ***!
  2931. \******************************************/
  2932. /***/ (function(__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) {
  2933. __webpack_require__.r(__webpack_exports__);
  2934. /* harmony export */ __webpack_require__.d(__webpack_exports__, {
  2935. /* harmony export */ createNanoEvents: function() { return /* binding */ createNanoEvents; }
  2936. /* harmony export */ });
  2937. let createNanoEvents = () => ({
  2938. emit(event, ...args) {
  2939. let callbacks = this.events[event] || []
  2940. for (let i = 0, length = callbacks.length; i < length; i++) {
  2941. callbacks[i](...args)
  2942. }
  2943. },
  2944. events: {},
  2945. on(event, cb) {
  2946. this.events[event]?.push(cb) || (this.events[event] = [cb])
  2947. return () => {
  2948. this.events[event] = this.events[event]?.filter(i => cb !== i)
  2949. }
  2950. }
  2951. })
  2952. /***/ })
  2953. /******/ });
  2954. /************************************************************************/
  2955. /******/ // The module cache
  2956. /******/ var __webpack_module_cache__ = {};
  2957. /******/
  2958. /******/ // The require function
  2959. /******/ function __webpack_require__(moduleId) {
  2960. /******/ // Check if module is in cache
  2961. /******/ var cachedModule = __webpack_module_cache__[moduleId];
  2962. /******/ if (cachedModule !== undefined) {
  2963. /******/ return cachedModule.exports;
  2964. /******/ }
  2965. /******/ // Create a new module (and put it into the cache)
  2966. /******/ var module = __webpack_module_cache__[moduleId] = {
  2967. /******/ // no module.id needed
  2968. /******/ // no module.loaded needed
  2969. /******/ exports: {}
  2970. /******/ };
  2971. /******/
  2972. /******/ // Execute the module function
  2973. /******/ __webpack_modules__[moduleId](module, module.exports, __webpack_require__);
  2974. /******/
  2975. /******/ // Return the exports of the module
  2976. /******/ return module.exports;
  2977. /******/ }
  2978. /******/
  2979. /************************************************************************/
  2980. /******/ /* webpack/runtime/define property getters */
  2981. /******/ !function() {
  2982. /******/ // define getter functions for harmony exports
  2983. /******/ __webpack_require__.d = function(exports, definition) {
  2984. /******/ for(var key in definition) {
  2985. /******/ if(__webpack_require__.o(definition, key) && !__webpack_require__.o(exports, key)) {
  2986. /******/ Object.defineProperty(exports, key, { enumerable: true, get: definition[key] });
  2987. /******/ }
  2988. /******/ }
  2989. /******/ };
  2990. /******/ }();
  2991. /******/
  2992. /******/ /* webpack/runtime/hasOwnProperty shorthand */
  2993. /******/ !function() {
  2994. /******/ __webpack_require__.o = function(obj, prop) { return Object.prototype.hasOwnProperty.call(obj, prop); }
  2995. /******/ }();
  2996. /******/
  2997. /******/ /* webpack/runtime/make namespace object */
  2998. /******/ !function() {
  2999. /******/ // define __esModule on exports
  3000. /******/ __webpack_require__.r = function(exports) {
  3001. /******/ if(typeof Symbol !== 'undefined' && Symbol.toStringTag) {
  3002. /******/ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
  3003. /******/ }
  3004. /******/ Object.defineProperty(exports, '__esModule', { value: true });
  3005. /******/ };
  3006. /******/ }();
  3007. /******/
  3008. /************************************************************************/
  3009. var __webpack_exports__ = {};
  3010. // This entry need to be wrapped in an IIFE because it need to be isolated against other modules in the chunk.
  3011. !function() {
  3012. /*!**********************!*\
  3013. !*** ./src/index.ts ***!
  3014. \**********************/
  3015. __webpack_require__.r(__webpack_exports__);
  3016. /* harmony import */ var _sv443_network_userutils__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @sv443-network/userutils */ "./node_modules/@sv443-network/userutils/dist/index.mjs");
  3017. /* harmony import */ var _config__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./config */ "./src/config.ts");
  3018. /* harmony import */ var _constants__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./constants */ "./src/constants.ts");
  3019. /* harmony import */ var _utils__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./utils */ "./src/utils.ts");
  3020. /* harmony import */ var _events__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./events */ "./src/events.ts");
  3021. /* harmony import */ var _features_index__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./features/index */ "./src/features/index.ts");
  3022. var __awaiter = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) {
  3023. function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
  3024. return new (P || (P = Promise))(function (resolve, reject) {
  3025. function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
  3026. function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
  3027. function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
  3028. step((generator = generator.apply(thisArg, _arguments || [])).next());
  3029. });
  3030. };
  3031. {
  3032. // console watermark with sexy gradient
  3033. 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%);";
  3034. const styleCommon = "color: #fff; font-size: 1.5em; padding-left: 6px; padding-right: 6px;";
  3035. console.log();
  3036. console.log(`%c${_constants__WEBPACK_IMPORTED_MODULE_2__.scriptInfo.name}%cv${_constants__WEBPACK_IMPORTED_MODULE_2__.scriptInfo.version}%c\n\nBuild #${_constants__WEBPACK_IMPORTED_MODULE_2__.scriptInfo.lastCommit} ─ ${_constants__WEBPACK_IMPORTED_MODULE_2__.scriptInfo.namespace}`, `font-weight: bold; ${styleCommon} ${styleGradient}`, `background-color: #333; ${styleCommon}`, "padding: initial;");
  3037. console.log([
  3038. "Powered by:",
  3039. "─ lots of ambition",
  3040. `─ my song metadata API: ${_features_index__WEBPACK_IMPORTED_MODULE_5__.geniUrlBase}`,
  3041. "─ my userscript utility library: https://github.com/Sv443-Network/UserUtils",
  3042. "─ this tiny event listener library: https://github.com/ai/nanoevents",
  3043. ].join("\n"));
  3044. console.log();
  3045. }
  3046. const domain = (0,_utils__WEBPACK_IMPORTED_MODULE_3__.getDomain)();
  3047. /** Stuff that needs to be called ASAP, before anything async happens */
  3048. function preInit() {
  3049. (0,_utils__WEBPACK_IMPORTED_MODULE_3__.setLogLevel)(_constants__WEBPACK_IMPORTED_MODULE_2__.logLevel);
  3050. if (domain === "ytm")
  3051. (0,_features_index__WEBPACK_IMPORTED_MODULE_5__.initBeforeUnloadHook)();
  3052. init();
  3053. }
  3054. function init() {
  3055. return __awaiter(this, void 0, void 0, function* () {
  3056. try {
  3057. registerMenuCommands();
  3058. }
  3059. catch (e) {
  3060. void e;
  3061. }
  3062. // init DOM-dependant stuff like features
  3063. try {
  3064. document.addEventListener("DOMContentLoaded", onDomLoad);
  3065. }
  3066. catch (err) {
  3067. (0,_utils__WEBPACK_IMPORTED_MODULE_3__.error)("General Error:", err);
  3068. }
  3069. // init config
  3070. try {
  3071. (0,_features_index__WEBPACK_IMPORTED_MODULE_5__.preInitLayout)(yield (0,_config__WEBPACK_IMPORTED_MODULE_1__.initConfig)());
  3072. if ((0,_config__WEBPACK_IMPORTED_MODULE_1__.getFeatures)().disableBeforeUnloadPopup)
  3073. (0,_features_index__WEBPACK_IMPORTED_MODULE_5__.disableBeforeUnload)();
  3074. }
  3075. catch (err) {
  3076. (0,_utils__WEBPACK_IMPORTED_MODULE_3__.error)("Error while initializing ConfigManager:", err);
  3077. }
  3078. // init menu separately from features
  3079. try {
  3080. void ["TODO(v1.1):", _features_index__WEBPACK_IMPORTED_MODULE_5__.initMenu];
  3081. // initMenu();
  3082. }
  3083. catch (err) {
  3084. (0,_utils__WEBPACK_IMPORTED_MODULE_3__.error)("Couldn't initialize menu:", err);
  3085. }
  3086. });
  3087. }
  3088. /** Called when the DOM has finished loading and can be queried and altered by the userscript */
  3089. function onDomLoad() {
  3090. return __awaiter(this, void 0, void 0, function* () {
  3091. // post-build these double quotes are replaced by backticks (because if backticks are used here, webpack converts them to double quotes)
  3092. (0,_sv443_network_userutils__WEBPACK_IMPORTED_MODULE_0__.addGlobalStyle)(`/*!*************************************************************************!*\
  3093. !*** css ./node_modules/css-loader/dist/cjs.js!./src/menu/menu_old.css ***!
  3094. \*************************************************************************/
  3095. .bytm-menu-bg {
  3096. --bytm-menu-bg: #333333;
  3097. --bytm-menu-bg-highlight: #1e1e1e;
  3098. --bytm-menu-separator-color: #797979;
  3099. --bytm-menu-border-radius: 15px;
  3100. }
  3101. #bytm-cfg-menu-bg {
  3102. --bytm-menu-height-max: 750px;
  3103. --bytm-menu-width-max: 1000px;
  3104. }
  3105. #bytm-export-menu-bg, #bytm-import-menu-bg {
  3106. --bytm-menu-height-max: 500px;
  3107. --bytm-menu-width-max: 600px;
  3108. }
  3109. .bytm-menu-bg {
  3110. display: block;
  3111. position: fixed;
  3112. width: 100%;
  3113. height: 100%;
  3114. top: 0;
  3115. left: 0;
  3116. z-index: 15;
  3117. background-color: rgba(0, 0, 0, 0.6);
  3118. }
  3119. .bytm-menu {
  3120. position: fixed;
  3121. display: flex;
  3122. flex-direction: column;
  3123. justify-content: space-between;
  3124. width: calc(min(100% - 60px, var(--bytm-menu-width-max)));
  3125. border-radius: var(--bytm-menu-border-radius);
  3126. height: auto;
  3127. max-height: calc(min(100% - 40px, var(--bytm-menu-height-max)));
  3128. left: 50%;
  3129. top: 50%;
  3130. transform: translate(-50%, -50%);
  3131. z-index: 16;
  3132. color: #fff;
  3133. background-color: var(--bytm-menu-bg);
  3134. }
  3135. .bytm-menu-body {
  3136. padding: 20px;
  3137. }
  3138. #bytm-menu-opts {
  3139. position: relative;
  3140. overflow: auto;
  3141. padding: 30px 0px;
  3142. }
  3143. .bytm-menu-header {
  3144. display: flex;
  3145. justify-content: space-between;
  3146. margin-bottom: 6px;
  3147. padding: 15px 20px 15px 20px;
  3148. background-color: var(--bytm-menu-bg);
  3149. border: 2px solid var(--bytm-menu-separator-color);
  3150. border-style: none none solid none;
  3151. border-radius: var(--bytm-menu-border-radius) var(--bytm-menu-border-radius) 0px 0px;
  3152. }
  3153. #bytm-menu-titlecont {
  3154. display: flex;
  3155. align-items: center;
  3156. }
  3157. #bytm-menu-title {
  3158. display: inline-block;
  3159. font-size: 22px;
  3160. }
  3161. #bytm-menu-linkscont {
  3162. display: flex;
  3163. align-items: center;
  3164. margin-left: 32px;
  3165. }
  3166. .bytm-menu-link {
  3167. display: inline-flex;
  3168. align-items: center;
  3169. cursor: pointer;
  3170. }
  3171. .bytm-menu-link:not(:last-of-type) {
  3172. margin-right: 10px;
  3173. }
  3174. .bytm-menu-close {
  3175. width: 32px;
  3176. height: 32px;
  3177. cursor: pointer;
  3178. }
  3179. #bytm-menu-footer-cont {
  3180. display: flex;
  3181. flex-direction: row;
  3182. justify-content: space-between;
  3183. margin-top: 6px;
  3184. padding: 20px 20px 8px 20px;
  3185. background: var(--bytm-menu-bg);
  3186. background: linear-gradient(to bottom, rgba(0, 0, 0, 0) 0%, var(--bytm-menu-bg) 30%, var(--bytm-menu-bg) 100%);
  3187. border: 2px solid var(--bytm-menu-separator-color);
  3188. border-style: solid none none none;
  3189. }
  3190. #bytm-menu-footer-buttons-cont button:not(:last-of-type) {
  3191. margin-right: 15px;
  3192. }
  3193. .bytm-menu-footer-right {
  3194. display: flex;
  3195. flex-direction: row-reverse;
  3196. align-items: center;
  3197. margin-top: 15px;
  3198. }
  3199. #bytm-menu-version-cont {
  3200. display: flex;
  3201. justify-content: space-around;
  3202. font-size: 1.15em;
  3203. padding-bottom: 8px;
  3204. border-radius: var(--bytm-menu-border-radius) var(--bytm-menu-border-radius) 0px 0px;
  3205. }
  3206. #bytm-menu-scroll-indicator {
  3207. --bytm-scroll-indicator-padding: 5px;
  3208. position: sticky;
  3209. bottom: -15px;
  3210. left: 50%;
  3211. margin-top: calc(-32px - var(--bytm-scroll-indicator-padding) * 2);
  3212. padding: var(--bytm-scroll-indicator-padding);
  3213. transform: translateX(-50%);
  3214. width: 32px;
  3215. height: 32px;
  3216. z-index: 101;
  3217. background-color: var(--bytm-menu-bg-highlight);
  3218. border-radius: 50%;
  3219. cursor: pointer;
  3220. }
  3221. .bytm-hidden {
  3222. visibility: hidden !important;
  3223. }
  3224. .bytm-ftconf-category-header {
  3225. font-size: 18px;
  3226. margin-top: 32px;
  3227. margin-bottom: 8px;
  3228. padding: 0px 20px;
  3229. }
  3230. .bytm-ftconf-category-header:first-of-type {
  3231. margin-top: 0;
  3232. }
  3233. .bytm-ftitem {
  3234. display: flex;
  3235. flex-direction: row;
  3236. justify-content: space-between;
  3237. align-items: center;
  3238. padding: 8px 20px;
  3239. }
  3240. .bytm-ftconf-label {
  3241. user-select: none;
  3242. }
  3243. .bytm-ftconf-input[type=number] {
  3244. width: 75px;
  3245. }
  3246. #bytm-export-menu-text, #bytm-import-menu-text {
  3247. font-size: 1.6em;
  3248. margin-bottom: 15px;
  3249. }
  3250. #bytm-export-menu-textarea, #bytm-import-menu-textarea {
  3251. width: 100%;
  3252. height: 150px;
  3253. resize: none;
  3254. }
  3255. /*!***************************************************************************!*\
  3256. !*** css ./node_modules/css-loader/dist/cjs.js!./src/features/layout.css ***!
  3257. \***************************************************************************/
  3258. /* #MARKER misc */
  3259. .bytm-disable-scroll {
  3260. overflow: hidden !important;
  3261. }
  3262. .bytm-generic-btn {
  3263. display: inline-flex;
  3264. align-items: center;
  3265. justify-content: center;
  3266. position: relative;
  3267. vertical-align: middle;
  3268. cursor: pointer;
  3269. margin-left: 8px;
  3270. width: 40px;
  3271. height: 40px;
  3272. border-radius: 100%;
  3273. background-color: transparent;
  3274. }
  3275. .bytm-generic-btn:hover {
  3276. background-color: var(--yt-spec-10-percent-layer, #1d1d1d);
  3277. }
  3278. .bytm-generic-btn-img {
  3279. display: inline-block;
  3280. z-index: 10;
  3281. width: 24px;
  3282. height: 24px;
  3283. padding: 5px;
  3284. }
  3285. .bytm-spinner {
  3286. animation: rotate 1.2s linear infinite;
  3287. }
  3288. @keyframes rotate {
  3289. from {
  3290. transform: rotate(0deg);
  3291. }
  3292. to {
  3293. transform: rotate(360deg);
  3294. }
  3295. }
  3296. .bytm-anchor {
  3297. all: unset;
  3298. cursor: pointer;
  3299. }
  3300. /* ytmusic-logo a[bytm-animated="true"] .bytm-mod-logo-ellipse {
  3301. transform-origin: 12px 12px;
  3302. animation: rotate 1s ease-in-out infinite;
  3303. } */
  3304. ytmusic-logo a.bytm-logo-exchanged .bytm-mod-logo-path {
  3305. transform-origin: 12px 12px;
  3306. animation: rotate 1s ease-in-out;
  3307. }
  3308. ytmusic-logo a.bytm-logo-exchanged .bytm-mod-logo-img {
  3309. width: 24px;
  3310. height: 24px;
  3311. z-index: 1000;
  3312. position: absolute;
  3313. animation: rotate-fade-in 1s ease-in-out;
  3314. }
  3315. @keyframes rotate-fade-in {
  3316. 0% {
  3317. opacity: 0;
  3318. transform: rotate(0deg);
  3319. }
  3320. 30% {
  3321. opacity: 0;
  3322. }
  3323. 90% {
  3324. opacity: 1;
  3325. }
  3326. 100% {
  3327. transform: rotate(360deg);
  3328. }
  3329. }
  3330. .bytm-no-select {
  3331. user-select: none;
  3332. -ms-user-select: none;
  3333. -moz-user-select: none;
  3334. -webkit-user-select: none;
  3335. }
  3336. /* YTM does some weird styling that breaks everything, so this reverts all of BYTM's buttons to the browser default style */
  3337. button.bytm-btn {
  3338. padding: revert;
  3339. border: revert;
  3340. outline: revert;
  3341. font: revert;
  3342. text-transform: revert;
  3343. color: revert;
  3344. background: revert;
  3345. }
  3346. /* #MARKER menu */
  3347. .bytm-cfg-menu-option {
  3348. display: block;
  3349. padding: 8px 0;
  3350. }
  3351. .bytm-cfg-menu-option-item {
  3352. display: flex;
  3353. flex-direction: row;
  3354. align-items: center;
  3355. font-size: 16px;
  3356. font-weight: 400;
  3357. line-height: 24px;
  3358. padding: var(--yt-compact-link-paper-item-padding, 0px 36px 0 16px);
  3359. min-height: var(--paper-item-min-height, 40px);
  3360. white-space: nowrap;
  3361. cursor: pointer;
  3362. }
  3363. .bytm-cfg-menu-option-item:hover {
  3364. background-color: var(--yt-spec-badge-chip-background, #3e3e3e);
  3365. }
  3366. .bytm-cfg-menu-option-icon {
  3367. width: 24px;
  3368. height: 24px;
  3369. margin-right: 16px;
  3370. display: flex;
  3371. align-items: center;
  3372. flex-direction: row;
  3373. flex: none;
  3374. }
  3375. .bytm-cfg-menu-option-text {
  3376. font-size: 1.4rem;
  3377. line-height: 2rem;
  3378. }
  3379. yt-multi-page-menu-section-renderer.ytd-multi-page-menu-renderer {
  3380. border-bottom: 1px solid var(--yt-spec-10-percent-layer, #3e3e3e);
  3381. }
  3382. /* #MARKER watermark */
  3383. #bytm-watermark {
  3384. font-size: 10px;
  3385. display: inline-block;
  3386. position: absolute;
  3387. left: 97px;
  3388. top: 46px;
  3389. z-index: 10;
  3390. color: white;
  3391. text-decoration: none;
  3392. cursor: pointer;
  3393. }
  3394. #bytm-watermark:hover {
  3395. text-decoration: underline;
  3396. }
  3397. /* #MARKER queue buttons */
  3398. .side-panel.modular ytmusic-player-queue-item .song-info.ytmusic-player-queue-item {
  3399. position: relative;
  3400. }
  3401. .side-panel.modular ytmusic-player-queue-item .bytm-queue-btn-container {
  3402. background: rgb(0, 0, 0);
  3403. background: linear-gradient(90deg, rgba(0, 0, 0, 0) 0%, rgba(0, 0, 0, 1) 15%);
  3404. display: none;
  3405. position: absolute;
  3406. right: 0;
  3407. padding-left: 25px;
  3408. height: 100%;
  3409. }
  3410. .side-panel.modular ytmusic-player-queue-item:hover .bytm-queue-btn-container {
  3411. display: inline-block;
  3412. }
  3413. .side-panel.modular ytmusic-player-queue-item[play-button-state="loading"] .bytm-queue-btn-container,
  3414. .side-panel.modular ytmusic-player-queue-item[play-button-state="playing"] .bytm-queue-btn-container,
  3415. .side-panel.modular ytmusic-player-queue-item[play-button-state="paused"] .bytm-queue-btn-container {
  3416. /* using a var() with predefined value from YTM is not viable since the nesting changes the actual value of the variable */
  3417. background: linear-gradient(90deg, rgba(0, 0, 0, 0) 0%, rgba(29, 29, 29, 1) 15%);
  3418. }
  3419. ytmusic-app ytmusic-popup-container tp-yt-iron-dropdown[data-bytm-hidden=true] {
  3420. display: none !important;
  3421. }
  3422. /* #MARKER anchor improvements */
  3423. ytmusic-responsive-list-item-renderer .left-items {
  3424. margin-right: 0 !important;
  3425. }
  3426. .bytm-carousel-shelf-anchor {
  3427. margin: 0 var(--ytmusic-responsive-list-item-thumbnail-margin-right, 16px) 0 0;
  3428. }
  3429. /* #MARKER volume slider */
  3430. #bytm-vol-slider-cont {
  3431. position: relative;
  3432. }
  3433. .bytm-vol-slider-label {
  3434. opacity: 0.000001;
  3435. position: absolute;
  3436. font-size: 15px;
  3437. top: 50%;
  3438. left: 0;
  3439. transform: translate(calc(-50% - 10px), -50%);
  3440. text-align: right;
  3441. transition: opacity 0.2s ease;
  3442. }
  3443. .bytm-vol-slider-label.bytm-visible {
  3444. opacity: 1;
  3445. }
  3446. /*!*********************************************************************!*\
  3447. !*** css ./node_modules/css-loader/dist/cjs.js!./src/menu/menu.css ***!
  3448. \*********************************************************************/
  3449. /* #bytm-menu-backdrop {
  3450. display: none;
  3451. flex-direction: column;
  3452. justify-content: center;
  3453. align-items: center;
  3454. }
  3455. #bytm-menu-backdrop[data-menu-open="true"] {
  3456. display: flex;
  3457. } */
  3458. #bytm-menu-header-container {
  3459. display: flex;
  3460. justify-content: flex-start;
  3461. align-items: center;
  3462. border-color: #ffffff;
  3463. border-style: none solid none none;
  3464. }
  3465. .bytm-menu-header-option {
  3466. display: "flex";
  3467. justify-content: center;
  3468. align-items: center;
  3469. border-color: #ffffff;
  3470. border-style: solid none solid none;
  3471. }
  3472. #bytm-menu-header-option h3 {
  3473. margin: 0;
  3474. }
  3475. .bytm-menu-tab[data-active="true"] {
  3476. display: none;
  3477. }
  3478. .bytm-menu-tab[data-active="false"] {
  3479. display: none;
  3480. }
  3481. /*# sourceMappingURL=http://localhost:8710/global.css.map*/`);
  3482. (0,_sv443_network_userutils__WEBPACK_IMPORTED_MODULE_0__.initOnSelector)();
  3483. const features = (0,_config__WEBPACK_IMPORTED_MODULE_1__.getFeatures)();
  3484. (0,_utils__WEBPACK_IMPORTED_MODULE_3__.log)(`Initializing features for domain "${domain}"...`);
  3485. try {
  3486. if (domain === "ytm") {
  3487. try {
  3488. (0,_features_index__WEBPACK_IMPORTED_MODULE_5__.addMenu)(); // TODO(v1.1): remove
  3489. (0,_features_index__WEBPACK_IMPORTED_MODULE_5__.addChangelogMenu)();
  3490. }
  3491. catch (err) {
  3492. (0,_utils__WEBPACK_IMPORTED_MODULE_3__.error)("Couldn't add menu:", err);
  3493. }
  3494. (0,_events__WEBPACK_IMPORTED_MODULE_4__.initSiteEvents)();
  3495. (0,_sv443_network_userutils__WEBPACK_IMPORTED_MODULE_0__.onSelector)("tp-yt-iron-dropdown #contentWrapper ytd-multi-page-menu-renderer #container.menu-container", { listener: _features_index__WEBPACK_IMPORTED_MODULE_5__.addConfigMenuOption });
  3496. if (features.arrowKeySupport)
  3497. (0,_features_index__WEBPACK_IMPORTED_MODULE_5__.initArrowKeySkip)();
  3498. if (features.removeUpgradeTab)
  3499. (0,_features_index__WEBPACK_IMPORTED_MODULE_5__.removeUpgradeTab)();
  3500. if (features.watermarkEnabled)
  3501. (0,_features_index__WEBPACK_IMPORTED_MODULE_5__.addWatermark)();
  3502. if (features.geniusLyrics)
  3503. (0,_features_index__WEBPACK_IMPORTED_MODULE_5__.addMediaCtrlLyricsBtn)();
  3504. if (features.deleteFromQueueButton || features.lyricsQueueButton)
  3505. (0,_features_index__WEBPACK_IMPORTED_MODULE_5__.initQueueButtons)();
  3506. if (features.anchorImprovements)
  3507. (0,_features_index__WEBPACK_IMPORTED_MODULE_5__.addAnchorImprovements)();
  3508. if (features.closeToastsTimeout > 0)
  3509. (0,_features_index__WEBPACK_IMPORTED_MODULE_5__.initAutoCloseToasts)();
  3510. if (features.removeShareTrackingParam)
  3511. (0,_features_index__WEBPACK_IMPORTED_MODULE_5__.removeShareTrackingParam)();
  3512. if (features.numKeysSkipToTime)
  3513. (0,_features_index__WEBPACK_IMPORTED_MODULE_5__.initNumKeysSkip)();
  3514. (0,_features_index__WEBPACK_IMPORTED_MODULE_5__.initVolumeFeatures)();
  3515. }
  3516. if (["ytm", "yt"].includes(domain)) {
  3517. if (features.switchBetweenSites)
  3518. (0,_features_index__WEBPACK_IMPORTED_MODULE_5__.initSiteSwitch)(domain);
  3519. }
  3520. }
  3521. catch (err) {
  3522. (0,_utils__WEBPACK_IMPORTED_MODULE_3__.error)("Feature error:", err);
  3523. }
  3524. });
  3525. }
  3526. function registerMenuCommands() {
  3527. if (_constants__WEBPACK_IMPORTED_MODULE_2__.mode === "development") {
  3528. GM.registerMenuCommand("Reset config", () => __awaiter(this, void 0, void 0, function* () {
  3529. if (confirm("Are you sure you want to reset the configuration to its default values?\nThis will automatically reload the page.")) {
  3530. yield (0,_config__WEBPACK_IMPORTED_MODULE_1__.clearConfig)();
  3531. location.reload();
  3532. }
  3533. }), "r");
  3534. GM.registerMenuCommand("List GM values", () => __awaiter(this, void 0, void 0, function* () {
  3535. alert("See console.");
  3536. const keys = yield GM.listValues();
  3537. (0,_utils__WEBPACK_IMPORTED_MODULE_3__.log)("GM values:");
  3538. if (keys.length === 0)
  3539. (0,_utils__WEBPACK_IMPORTED_MODULE_3__.log)(" No values found.");
  3540. for (const key of keys)
  3541. (0,_utils__WEBPACK_IMPORTED_MODULE_3__.log)(` ${key} -> ${yield GM.getValue(key)}`);
  3542. }), "l");
  3543. GM.registerMenuCommand("Clear all GM values", () => __awaiter(this, void 0, void 0, function* () {
  3544. if (confirm("Are you sure you want to clear all GM values?")) {
  3545. const keys = yield GM.listValues();
  3546. (0,_utils__WEBPACK_IMPORTED_MODULE_3__.log)("Clearing GM values:");
  3547. if (keys.length === 0)
  3548. (0,_utils__WEBPACK_IMPORTED_MODULE_3__.log)(" No values found.");
  3549. for (const key of keys) {
  3550. yield GM.deleteValue(key);
  3551. (0,_utils__WEBPACK_IMPORTED_MODULE_3__.log)(` Deleted ${key}`);
  3552. }
  3553. }
  3554. }), "c");
  3555. }
  3556. }
  3557. preInit();
  3558. }();
  3559. //# sourceMappingURL=http://localhost:8710/BetterYTM.user.js.map