BetterYTM.user.js 149 KB

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