BetterYTM.user.js 124 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721
  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.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 unsafeWindow
  21. // ==/UserScript==
  22. /*
  23. ▄▄▄ ▄ ▄▄▄▄▄▄ ▄
  24. █ █ ▄▄▄ █ █ ▄▄▄ ▄ ▄█ █ █ █▀▄▀█
  25. █▀▀▄ █▄█ █▀ █▀ █▄█ █▀ █ █ █ █
  26. █▄▄▀ ▀▄▄ ▀▄▄ ▀▄▄ ▀▄▄ █ █ █ █ █
  27. Made with ❤️ by Sv443
  28. I welcome every contribution on GitHub!
  29. https://github.com/Sv443/BetterYTM
  30. */
  31. /* Disclaimer: I am not affiliated with YouTube, Google, Alphabet, Genius or anyone else */
  32. /* C&D this 🖕 */
  33. /******/ var __webpack_modules__ = ({
  34. /***/ "./node_modules/@billjs/event-emitter/lib/index.js":
  35. /*!*********************************************************!*\
  36. !*** ./node_modules/@billjs/event-emitter/lib/index.js ***!
  37. \*********************************************************/
  38. /***/ (function(__unused_webpack_module, exports) {
  39. /**
  40. * A simple and lightweight EventEmitter by TypeScript for Node.js or Browsers.
  41. *
  42. * @author billjs
  43. * @see https://github.com/billjs/event-emitter
  44. * @license MIT(https://opensource.org/licenses/MIT)
  45. */
  46. Object.defineProperty(exports, "__esModule", ({ value: true }));
  47. /**
  48. * It's a class for managing events.
  49. * It can be extended to provide event functionality for other classes or object.
  50. *
  51. * @export
  52. * @class EventEmitter
  53. */
  54. var EventEmitter = /** @class */ (function () {
  55. function EventEmitter() {
  56. /**
  57. * the all event handlers are added.
  58. * it's a Map data structure(key-value), the key is event type, and the value is event handler.
  59. *
  60. * @memberof EventEmitter
  61. */
  62. this._eventHandlers = {};
  63. }
  64. /**
  65. * event type validator.
  66. *
  67. * @param {string} type event type
  68. * @returns {boolean}
  69. * @memberof EventEmitter
  70. */
  71. EventEmitter.prototype.isValidType = function (type) {
  72. return typeof type === 'string';
  73. };
  74. /**
  75. * event handler validator.
  76. *
  77. * @param {EventHandler} handler event handler
  78. * @returns {boolean}
  79. * @memberof EventEmitter
  80. */
  81. EventEmitter.prototype.isValidHandler = function (handler) {
  82. return typeof handler === 'function';
  83. };
  84. /**
  85. * listen on a new event by type and handler.
  86. * if listen on, the true is returned, otherwise the false.
  87. * The handler will not be listen if it is a duplicate.
  88. *
  89. * @param {string} type event type, it must be a unique string.
  90. * @param {EventHandler} handler event handler, when if the same handler is passed, listen it by only once.
  91. * @returns {boolean}
  92. * @memberof EventEmitter
  93. * @example
  94. * const emitter = new EventEmitter();
  95. * emitter.on('change:name', evt => {
  96. * console.log(evt);
  97. * });
  98. */
  99. EventEmitter.prototype.on = function (type, handler) {
  100. if (!type || !handler)
  101. return false;
  102. if (!this.isValidType(type))
  103. return false;
  104. if (!this.isValidHandler(handler))
  105. return false;
  106. var handlers = this._eventHandlers[type];
  107. if (!handlers)
  108. handlers = this._eventHandlers[type] = [];
  109. // when the same handler is passed, listen it by only once.
  110. if (handlers.indexOf(handler) >= 0)
  111. return false;
  112. handler._once = false;
  113. handlers.push(handler);
  114. return true;
  115. };
  116. /**
  117. * listen on an once event by type and handler.
  118. * when the event is fired, that will be listen off immediately and automatically.
  119. * The handler will not be listen if it is a duplicate.
  120. *
  121. * @param {string} type event type, it must be a unique string.
  122. * @param {EventHandler} handler event handler, when if the same handler is passed, listen it by only once.
  123. * @returns {boolean}
  124. * @memberof EventEmitter
  125. * @example
  126. * const emitter = new EventEmitter();
  127. * emitter.once('change:name', evt => {
  128. * console.log(evt);
  129. * });
  130. */
  131. EventEmitter.prototype.once = function (type, handler) {
  132. if (!type || !handler)
  133. return false;
  134. if (!this.isValidType(type))
  135. return false;
  136. if (!this.isValidHandler(handler))
  137. return false;
  138. var ret = this.on(type, handler);
  139. if (ret) {
  140. // set `_once` private property after listened,
  141. // avoid to modify event handler that has been listened.
  142. handler._once = true;
  143. }
  144. return ret;
  145. };
  146. /**
  147. * listen off an event by type and handler.
  148. * or listen off events by type, when if only type argument is passed.
  149. * or listen off all events, when if no arguments are passed.
  150. *
  151. * @param {string} [type] event type
  152. * @param {EventHandler} [handler] event handler
  153. * @returns
  154. * @memberof EventEmitter
  155. * @example
  156. * const emitter = new EventEmitter();
  157. * // listen off the specified event
  158. * emitter.off('change:name', evt => {
  159. * console.log(evt);
  160. * });
  161. * // listen off events by type
  162. * emitter.off('change:name');
  163. * // listen off all events
  164. * emitter.off();
  165. */
  166. EventEmitter.prototype.off = function (type, handler) {
  167. // listen off all events, when if no arguments are passed.
  168. // it does samething as `offAll` method.
  169. if (!type)
  170. return this.offAll();
  171. // listen off events by type, when if only type argument is passed.
  172. if (!handler) {
  173. this._eventHandlers[type] = [];
  174. return;
  175. }
  176. if (!this.isValidType(type))
  177. return;
  178. if (!this.isValidHandler(handler))
  179. return;
  180. var handlers = this._eventHandlers[type];
  181. if (!handlers || !handlers.length)
  182. return;
  183. // otherwise, listen off the specified event.
  184. for (var i = 0; i < handlers.length; i++) {
  185. var fn = handlers[i];
  186. if (fn === handler) {
  187. handlers.splice(i, 1);
  188. break;
  189. }
  190. }
  191. };
  192. /**
  193. * listen off all events, that means every event will be emptied.
  194. *
  195. * @memberof EventEmitter
  196. * @example
  197. * const emitter = new EventEmitter();
  198. * emitter.offAll();
  199. */
  200. EventEmitter.prototype.offAll = function () {
  201. this._eventHandlers = {};
  202. };
  203. /**
  204. * fire the specified event, and you can to pass a data.
  205. * When fired, every handler attached to that event will be executed.
  206. * But, if it's an once event, listen off it immediately after called handler.
  207. *
  208. * @param {string} type event type
  209. * @param {*} [data] event data
  210. * @returns
  211. * @memberof EventEmitter
  212. * @example
  213. * const emitter = new EventEmitter();
  214. * emitter.fire('change:name', 'new name');
  215. */
  216. EventEmitter.prototype.fire = function (type, data) {
  217. if (!type || !this.isValidType(type))
  218. return;
  219. var handlers = this._eventHandlers[type];
  220. if (!handlers || !handlers.length)
  221. return;
  222. var event = this.createEvent(type, data);
  223. for (var _i = 0, handlers_1 = handlers; _i < handlers_1.length; _i++) {
  224. var handler = handlers_1[_i];
  225. if (!this.isValidHandler(handler))
  226. continue;
  227. if (handler._once)
  228. event.once = true;
  229. // call event handler, and pass the event argument.
  230. handler(event);
  231. // if it's an once event, listen off it immediately after called handler.
  232. if (event.once)
  233. this.off(type, handler);
  234. }
  235. };
  236. /**
  237. * check whether the specified event has been listen on.
  238. * or check whether the events by type has been listen on, when if only `type` argument is passed.
  239. *
  240. * @param {string} type event type
  241. * @param {EventHandler} [handler] event handler, optional
  242. * @returns {boolean}
  243. * @memberof EventEmitter
  244. * @example
  245. * const emitter = new EventEmitter();
  246. * const result = emitter.has('change:name');
  247. */
  248. EventEmitter.prototype.has = function (type, handler) {
  249. if (!type || !this.isValidType(type))
  250. return false;
  251. var handlers = this._eventHandlers[type];
  252. // if there are no any events, return false.
  253. if (!handlers || !handlers.length)
  254. return false;
  255. // at lest one event, and no pass `handler` argument, then return true.
  256. if (!handler || !this.isValidHandler(handler))
  257. return true;
  258. // otherwise, need to traverse the handlers.
  259. return handlers.indexOf(handler) >= 0;
  260. };
  261. /**
  262. * get the handlers for the specified event type.
  263. *
  264. * @param {string} type event type
  265. * @returns {EventHandler[]}
  266. * @memberof EventEmitter
  267. * @example
  268. * const emitter = new EventEmitter();
  269. * const handlers = emitter.getHandlers('change:name');
  270. * console.log(handlers);
  271. */
  272. EventEmitter.prototype.getHandlers = function (type) {
  273. if (!type || !this.isValidType(type))
  274. return [];
  275. return this._eventHandlers[type] || [];
  276. };
  277. /**
  278. * create event object.
  279. *
  280. * @param {string} type event type
  281. * @param {*} [data] event data
  282. * @param {boolean} [once=false] is it an once event?
  283. * @returns {Event}
  284. * @memberof EventEmitter
  285. */
  286. EventEmitter.prototype.createEvent = function (type, data, once) {
  287. if (once === void 0) { once = false; }
  288. var event = { type: type, data: data, timestamp: Date.now(), once: once };
  289. return event;
  290. };
  291. return EventEmitter;
  292. }());
  293. exports.EventEmitter = EventEmitter;
  294. /**
  295. * EventEmitter instance for global.
  296. * @type {EventEmitter}
  297. */
  298. exports.globalEvent = new EventEmitter();
  299. /***/ }),
  300. /***/ "./changelog.md":
  301. /*!**********************!*\
  302. !*** ./changelog.md ***!
  303. \**********************/
  304. /***/ (function(__unused_webpack_module, __webpack_exports__, __webpack_require__) {
  305. __webpack_require__.r(__webpack_exports__);
  306. // Module
  307. 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<p><br><br><br><br><br><br><br><br><br></p>\n";
  308. // Exports
  309. /* harmony default export */ __webpack_exports__["default"] = (code);
  310. /***/ }),
  311. /***/ "./src/features/menu/menu.html":
  312. /*!*************************************!*\
  313. !*** ./src/features/menu/menu.html ***!
  314. \*************************************/
  315. /***/ (function(__unused_webpack_module, __webpack_exports__, __webpack_require__) {
  316. __webpack_require__.r(__webpack_exports__);
  317. // Module
  318. 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";
  319. // Exports
  320. /* harmony default export */ __webpack_exports__["default"] = (code);
  321. /***/ }),
  322. /***/ "./src/features/layout.css":
  323. /*!*********************************!*\
  324. !*** ./src/features/layout.css ***!
  325. \*********************************/
  326. /***/ (function(__unused_webpack_module, __webpack_exports__, __webpack_require__) {
  327. __webpack_require__.r(__webpack_exports__);
  328. // extracted by mini-css-extract-plugin
  329. /***/ }),
  330. /***/ "./src/features/menu/menu.css":
  331. /*!************************************!*\
  332. !*** ./src/features/menu/menu.css ***!
  333. \************************************/
  334. /***/ (function(__unused_webpack_module, __webpack_exports__, __webpack_require__) {
  335. __webpack_require__.r(__webpack_exports__);
  336. // extracted by mini-css-extract-plugin
  337. /***/ }),
  338. /***/ "./src/features/menu/menu_old.css":
  339. /*!****************************************!*\
  340. !*** ./src/features/menu/menu_old.css ***!
  341. \****************************************/
  342. /***/ (function(__unused_webpack_module, __webpack_exports__, __webpack_require__) {
  343. __webpack_require__.r(__webpack_exports__);
  344. // extracted by mini-css-extract-plugin
  345. /***/ }),
  346. /***/ "./src/config.ts":
  347. /*!***********************!*\
  348. !*** ./src/config.ts ***!
  349. \***********************/
  350. /***/ (function(__unused_webpack_module, __webpack_exports__, __webpack_require__) {
  351. __webpack_require__.r(__webpack_exports__);
  352. /* harmony export */ __webpack_require__.d(__webpack_exports__, {
  353. /* harmony export */ defaultFeatures: function() { return /* binding */ defaultFeatures; },
  354. /* harmony export */ getFeatures: function() { return /* binding */ getFeatures; },
  355. /* harmony export */ loadFeatureConf: function() { return /* binding */ loadFeatureConf; },
  356. /* harmony export */ saveFeatureConf: function() { return /* binding */ saveFeatureConf; },
  357. /* harmony export */ setDefaultFeatConf: function() { return /* binding */ setDefaultFeatConf; }
  358. /* harmony export */ });
  359. /* harmony import */ var _features_index__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./features/index */ "./src/features/index.ts");
  360. /* harmony import */ var _utils__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./utils */ "./src/utils.ts");
  361. var __awaiter = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) {
  362. function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
  363. return new (P || (P = Promise))(function (resolve, reject) {
  364. function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
  365. function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
  366. function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
  367. step((generator = generator.apply(thisArg, _arguments || [])).next());
  368. });
  369. };
  370. /** If this number is incremented, the features object needs to be migrated (TODO: migration not implemented yet) */
  371. const formatVersion = 1;
  372. const defaultFeatures = Object.keys(_features_index__WEBPACK_IMPORTED_MODULE_0__.featInfo)
  373. .reduce((acc, key) => {
  374. acc[key] = _features_index__WEBPACK_IMPORTED_MODULE_0__.featInfo[key].default;
  375. return acc;
  376. }, {});
  377. /** In-memory features object to save on a little bit of I/O */
  378. let featuresCache;
  379. /**
  380. * Returns the current FeatureConfig in memory or reads it from GM storage
  381. * Automatically applies defaults for non-existant keys
  382. * @param forceRead Set to true to force reading the config from GM storage
  383. */
  384. function getFeatures(forceRead = false) {
  385. return __awaiter(this, void 0, void 0, function* () {
  386. if (featuresCache === undefined || forceRead)
  387. yield saveFeatureConf(featuresCache = Object.assign(Object.assign({}, defaultFeatures), yield loadFeatureConf())); // look at this sexy one liner
  388. return featuresCache;
  389. });
  390. }
  391. /** Loads a feature configuration saved persistently, returns an empty object if no feature configuration was saved */
  392. function loadFeatureConf() {
  393. return __awaiter(this, void 0, void 0, function* () {
  394. const defConf = Object.assign({}, defaultFeatures);
  395. try {
  396. const featureConf = yield GM.getValue("betterytm-config");
  397. if (typeof featureConf !== "string") {
  398. yield setDefaultFeatConf();
  399. return featuresCache = defConf;
  400. }
  401. return featuresCache = Object.freeze(featureConf ? JSON.parse(featureConf) : defConf);
  402. }
  403. catch (err) {
  404. yield setDefaultFeatConf();
  405. return featuresCache = defConf;
  406. }
  407. });
  408. }
  409. /**
  410. * Saves the passed feature configuration persistently in GM storage and in the in-memory cache
  411. * @param featureConf
  412. */
  413. function saveFeatureConf(featureConf) {
  414. if (!featureConf || typeof featureConf != "object")
  415. throw new TypeError("Feature config not provided or invalid");
  416. (0,_utils__WEBPACK_IMPORTED_MODULE_1__.log)("Saving new feature config:", featureConf);
  417. featuresCache = Object.assign({}, featureConf);
  418. GM.setValue("betterytm-config-ver", formatVersion);
  419. return GM.setValue("betterytm-config", JSON.stringify(featureConf));
  420. }
  421. /** Resets the featuresCache synchronously and the persistent features storage asynchronously to their default values */
  422. function setDefaultFeatConf() {
  423. featuresCache = Object.assign({}, defaultFeatures);
  424. GM.setValue("betterytm-config-ver", formatVersion);
  425. return GM.setValue("betterytm-config", JSON.stringify(defaultFeatures));
  426. }
  427. /***/ }),
  428. /***/ "./src/constants.ts":
  429. /*!**************************!*\
  430. !*** ./src/constants.ts ***!
  431. \**************************/
  432. /***/ (function(__unused_webpack_module, __webpack_exports__, __webpack_require__) {
  433. __webpack_require__.r(__webpack_exports__);
  434. /* harmony export */ __webpack_require__.d(__webpack_exports__, {
  435. /* harmony export */ branch: function() { return /* binding */ branch; },
  436. /* harmony export */ logLevel: function() { return /* binding */ logLevel; },
  437. /* harmony export */ mode: function() { return /* binding */ mode; },
  438. /* harmony export */ scriptInfo: function() { return /* binding */ scriptInfo; }
  439. /* harmony export */ });
  440. const modeRaw = "development";
  441. const branchRaw = "develop";
  442. /** The mode in which the script was built (production or development) */
  443. const mode = modeRaw.match(/^{{.+}}$/) ? "production" : modeRaw;
  444. /** The branch to use in various URLs that point to the GitHub repo */
  445. const branch = branchRaw.match(/^{{.+}}$/) ? "main" : branchRaw;
  446. /**
  447. * How much info should be logged to the devtools console?
  448. * 0 = Debug (show everything) or 1 = Info (show only important stuff)
  449. */
  450. const logLevel = mode === "production" ? 1 : 0;
  451. /** Info about the userscript, parsed from the userscript header (tools/post-build.js) */
  452. const scriptInfo = {
  453. name: GM.info.script.name,
  454. version: GM.info.script.version,
  455. namespace: GM.info.script.namespace,
  456. lastCommit: "d76e16e", // assert as generic string instead of union
  457. };
  458. /***/ }),
  459. /***/ "./src/events.ts":
  460. /*!***********************!*\
  461. !*** ./src/events.ts ***!
  462. \***********************/
  463. /***/ (function(__unused_webpack_module, __webpack_exports__, __webpack_require__) {
  464. __webpack_require__.r(__webpack_exports__);
  465. /* harmony export */ __webpack_require__.d(__webpack_exports__, {
  466. /* harmony export */ getEvtData: function() { return /* binding */ getEvtData; },
  467. /* harmony export */ initSiteEvents: function() { return /* binding */ initSiteEvents; },
  468. /* harmony export */ removeAllObservers: function() { return /* binding */ removeAllObservers; },
  469. /* harmony export */ siteEvents: function() { return /* binding */ siteEvents; }
  470. /* harmony export */ });
  471. /* harmony import */ var _billjs_event_emitter__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @billjs/event-emitter */ "./node_modules/@billjs/event-emitter/lib/index.js");
  472. /* harmony import */ var _utils__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./utils */ "./src/utils.ts");
  473. var __awaiter = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) {
  474. function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
  475. return new (P || (P = Promise))(function (resolve, reject) {
  476. function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
  477. function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
  478. function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
  479. step((generator = generator.apply(thisArg, _arguments || [])).next());
  480. });
  481. };
  482. /** EventEmitter instance that is used to detect changes to the site */
  483. const siteEvents = new _billjs_event_emitter__WEBPACK_IMPORTED_MODULE_0__.EventEmitter();
  484. /**
  485. * Returns the data of an event from the `@billjs/event-emitter` library.
  486. * This function is used as a shorthand to extract the data and assert it with the type passed in `<T>`
  487. * @param evt Event object from the `.on()` or `.once()` method
  488. * @template T Type of the data passed by `.fire(type: string, data: T)`
  489. */
  490. function getEvtData(evt) {
  491. return evt.data;
  492. }
  493. let observers = [];
  494. /** Disconnects and deletes all observers. Run `initSiteEvents()` again to create new ones. */
  495. function removeAllObservers() {
  496. observers.forEach((observer, i) => {
  497. observer.disconnect();
  498. delete observers[i];
  499. });
  500. observers = [];
  501. }
  502. /** Creates MutationObservers that check if parts of the site have changed, then emit an event on the `siteEvents` instance. */
  503. function initSiteEvents() {
  504. return __awaiter(this, void 0, void 0, function* () {
  505. try {
  506. //#SECTION queue
  507. // the queue container always exists so it doesn't need the extra init function
  508. const queueObs = new MutationObserver(([{ addedNodes, removedNodes, target }]) => {
  509. if (addedNodes.length > 0 || removedNodes.length > 0) {
  510. (0,_utils__WEBPACK_IMPORTED_MODULE_1__.info)(`Detected queue change - added nodes: ${[...addedNodes.values()].length} - removed nodes: ${[...removedNodes.values()].length}`);
  511. siteEvents.fire("queueChanged", target);
  512. }
  513. });
  514. // only observe added or removed elements
  515. queueObs.observe(document.querySelector(".side-panel.modular #contents.ytmusic-player-queue"), {
  516. childList: true,
  517. });
  518. const autoplayObs = new MutationObserver(([{ addedNodes, removedNodes, target }]) => {
  519. if (addedNodes.length > 0 || removedNodes.length > 0) {
  520. (0,_utils__WEBPACK_IMPORTED_MODULE_1__.info)(`Detected autoplay queue change - added nodes: ${[...addedNodes.values()].length} - removed nodes: ${[...removedNodes.values()].length}`);
  521. siteEvents.fire("autoplayQueueChanged", target);
  522. }
  523. });
  524. autoplayObs.observe(document.querySelector(".side-panel.modular ytmusic-player-queue #automix-contents"), {
  525. childList: true,
  526. });
  527. //#SECTION home page observers
  528. initHomeObservers();
  529. (0,_utils__WEBPACK_IMPORTED_MODULE_1__.info)("Successfully initialized SiteEvents observers");
  530. observers = observers.concat([
  531. queueObs,
  532. autoplayObs,
  533. ]);
  534. }
  535. catch (err) {
  536. (0,_utils__WEBPACK_IMPORTED_MODULE_1__.error)("Couldn't initialize SiteEvents observers due to an error:\n", err);
  537. }
  538. });
  539. }
  540. /**
  541. * The home page might not exist yet if the site was accessed through any path like /watch directly.
  542. * This function will keep waiting for when the home page exists, then create the necessary MutationObservers.
  543. */
  544. function initHomeObservers() {
  545. var _a;
  546. return __awaiter(this, void 0, void 0, function* () {
  547. let interval;
  548. // hidden="" attribute is only present if the content of the page doesn't exist yet
  549. // so this pauses execution until that attribute is removed
  550. if ((_a = document.querySelector("ytmusic-browse-response#browse-page")) === null || _a === void 0 ? void 0 : _a.hasAttribute("hidden")) {
  551. yield new Promise((res) => {
  552. interval = setInterval(() => {
  553. var _a;
  554. if (!((_a = document.querySelector("ytmusic-browse-response#browse-page")) === null || _a === void 0 ? void 0 : _a.hasAttribute("hidden"))) {
  555. clearInterval(interval);
  556. res();
  557. }
  558. }, 50);
  559. });
  560. }
  561. siteEvents.fire("homePageLoaded");
  562. (0,_utils__WEBPACK_IMPORTED_MODULE_1__.info)("Initialized home page observers");
  563. //#SECTION carousel shelves
  564. const shelfContainerObs = new MutationObserver(([{ addedNodes, removedNodes }]) => {
  565. if (addedNodes.length > 0 || removedNodes.length > 0) {
  566. (0,_utils__WEBPACK_IMPORTED_MODULE_1__.info)("Detected carousel shelf container change - added nodes:", addedNodes.length, "- removed nodes:", removedNodes.length);
  567. siteEvents.fire("carouselShelvesChanged", { addedNodes, removedNodes });
  568. }
  569. });
  570. shelfContainerObs.observe(document.querySelector("#contents.ytmusic-section-list-renderer"), {
  571. childList: true,
  572. });
  573. observers = observers.concat([shelfContainerObs]);
  574. });
  575. }
  576. /***/ }),
  577. /***/ "./src/features/index.ts":
  578. /*!*******************************!*\
  579. !*** ./src/features/index.ts ***!
  580. \*******************************/
  581. /***/ (function(__unused_webpack_module, __webpack_exports__, __webpack_require__) {
  582. __webpack_require__.r(__webpack_exports__);
  583. /* harmony export */ __webpack_require__.d(__webpack_exports__, {
  584. /* harmony export */ addAnchorImprovements: function() { return /* reexport safe */ _layout__WEBPACK_IMPORTED_MODULE_2__.addAnchorImprovements; },
  585. /* harmony export */ addConfigMenuOption: function() { return /* reexport safe */ _layout__WEBPACK_IMPORTED_MODULE_2__.addConfigMenuOption; },
  586. /* harmony export */ addLyricsCacheEntry: function() { return /* reexport safe */ _lyrics__WEBPACK_IMPORTED_MODULE_3__.addLyricsCacheEntry; },
  587. /* harmony export */ addMediaCtrlLyricsBtn: function() { return /* reexport safe */ _lyrics__WEBPACK_IMPORTED_MODULE_3__.addMediaCtrlLyricsBtn; },
  588. /* harmony export */ addMenu: function() { return /* reexport safe */ _menu_menu_old__WEBPACK_IMPORTED_MODULE_5__.addMenu; },
  589. /* harmony export */ addWatermark: function() { return /* reexport safe */ _layout__WEBPACK_IMPORTED_MODULE_2__.addWatermark; },
  590. /* harmony export */ closeMenu: function() { return /* reexport safe */ _menu_menu_old__WEBPACK_IMPORTED_MODULE_5__.closeMenu; },
  591. /* harmony export */ createLyricsBtn: function() { return /* reexport safe */ _lyrics__WEBPACK_IMPORTED_MODULE_3__.createLyricsBtn; },
  592. /* harmony export */ disableBeforeUnload: function() { return /* reexport safe */ _input__WEBPACK_IMPORTED_MODULE_1__.disableBeforeUnload; },
  593. /* harmony export */ enableBeforeUnload: function() { return /* reexport safe */ _input__WEBPACK_IMPORTED_MODULE_1__.enableBeforeUnload; },
  594. /* harmony export */ featInfo: function() { return /* binding */ featInfo; },
  595. /* harmony export */ geniUrlBase: function() { return /* reexport safe */ _lyrics__WEBPACK_IMPORTED_MODULE_3__.geniUrlBase; },
  596. /* harmony export */ getCurrentLyricsUrl: function() { return /* reexport safe */ _lyrics__WEBPACK_IMPORTED_MODULE_3__.getCurrentLyricsUrl; },
  597. /* harmony export */ getGeniusUrl: function() { return /* reexport safe */ _lyrics__WEBPACK_IMPORTED_MODULE_3__.getGeniusUrl; },
  598. /* harmony export */ getLyricsCacheEntry: function() { return /* reexport safe */ _lyrics__WEBPACK_IMPORTED_MODULE_3__.getLyricsCacheEntry; },
  599. /* harmony export */ initArrowKeySkip: function() { return /* reexport safe */ _input__WEBPACK_IMPORTED_MODULE_1__.initArrowKeySkip; },
  600. /* harmony export */ initBeforeUnloadHook: function() { return /* reexport safe */ _input__WEBPACK_IMPORTED_MODULE_1__.initBeforeUnloadHook; },
  601. /* harmony export */ initMenu: function() { return /* reexport safe */ _menu_menu__WEBPACK_IMPORTED_MODULE_4__.initMenu; },
  602. /* harmony export */ initQueueButtons: function() { return /* reexport safe */ _layout__WEBPACK_IMPORTED_MODULE_2__.initQueueButtons; },
  603. /* harmony export */ initSiteSwitch: function() { return /* reexport safe */ _input__WEBPACK_IMPORTED_MODULE_1__.initSiteSwitch; },
  604. /* harmony export */ openMenu: function() { return /* reexport safe */ _menu_menu_old__WEBPACK_IMPORTED_MODULE_5__.openMenu; },
  605. /* harmony export */ preInitLayout: function() { return /* reexport safe */ _layout__WEBPACK_IMPORTED_MODULE_2__.preInitLayout; },
  606. /* harmony export */ removeUpgradeTab: function() { return /* reexport safe */ _layout__WEBPACK_IMPORTED_MODULE_2__.removeUpgradeTab; },
  607. /* harmony export */ sanitizeArtists: function() { return /* reexport safe */ _lyrics__WEBPACK_IMPORTED_MODULE_3__.sanitizeArtists; },
  608. /* harmony export */ sanitizeSong: function() { return /* reexport safe */ _lyrics__WEBPACK_IMPORTED_MODULE_3__.sanitizeSong; },
  609. /* harmony export */ setVolSliderSize: function() { return /* reexport safe */ _layout__WEBPACK_IMPORTED_MODULE_2__.setVolSliderSize; },
  610. /* harmony export */ setVolSliderStep: function() { return /* reexport safe */ _layout__WEBPACK_IMPORTED_MODULE_2__.setVolSliderStep; }
  611. /* harmony export */ });
  612. /* harmony import */ var _constants__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../constants */ "./src/constants.ts");
  613. /* harmony import */ var _input__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./input */ "./src/features/input.ts");
  614. /* harmony import */ var _layout__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./layout */ "./src/features/layout.ts");
  615. /* harmony import */ var _lyrics__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./lyrics */ "./src/features/lyrics.ts");
  616. /* harmony import */ var _menu_menu__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./menu/menu */ "./src/features/menu/menu.ts");
  617. /* harmony import */ var _menu_menu_old__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./menu/menu_old */ "./src/features/menu/menu_old.ts");
  618. /** Contains all possible features with their default values and other config */
  619. const featInfo = {
  620. //#SECTION input
  621. arrowKeySupport: {
  622. desc: "Arrow keys skip forwards and backwards by 10 seconds",
  623. type: "toggle",
  624. category: "input",
  625. default: true,
  626. },
  627. switchBetweenSites: {
  628. desc: "Add F9 as a hotkey to switch between the YT and YTM sites on a video / song",
  629. type: "toggle",
  630. category: "input",
  631. default: true,
  632. },
  633. switchSitesHotkey: {
  634. desc: "TODO: Which hotkey needs to be pressed to switch sites?",
  635. type: "hotkey",
  636. category: "input",
  637. default: {
  638. key: "F9",
  639. shift: false,
  640. ctrl: false,
  641. meta: false,
  642. },
  643. visible: false,
  644. },
  645. disableBeforeUnloadPopup: {
  646. desc: "Completely disable the popup that sometimes appears before leaving the site",
  647. type: "toggle",
  648. category: "input",
  649. default: false,
  650. },
  651. anchorImprovements: {
  652. desc: "Add link elements all over the page so stuff can be opened in a new tab easier",
  653. type: "toggle",
  654. category: "input",
  655. default: true,
  656. },
  657. //#SECTION layout
  658. removeUpgradeTab: {
  659. desc: "Remove the \"Upgrade\" / YT Music Premium tab",
  660. type: "toggle",
  661. category: "layout",
  662. default: true,
  663. },
  664. volumeSliderSize: {
  665. desc: "The width of the volume slider in pixels",
  666. type: "number",
  667. category: "layout",
  668. min: 10,
  669. max: 1000,
  670. step: 5,
  671. default: 160,
  672. unit: "px",
  673. },
  674. volumeSliderStep: {
  675. desc: "Volume slider sensitivity - the smaller this number, the finer the volume control",
  676. type: "slider",
  677. category: "layout",
  678. min: 1,
  679. max: 20,
  680. default: 2,
  681. },
  682. watermarkEnabled: {
  683. desc: `Show a ${_constants__WEBPACK_IMPORTED_MODULE_0__.scriptInfo.name} watermark under the YTM logo`,
  684. type: "toggle",
  685. category: "layout",
  686. default: true,
  687. },
  688. queueButtons: {
  689. desc: "Add buttons to each song in the queue to quickly open their lyrics or remove them from the queue",
  690. type: "toggle",
  691. category: "layout",
  692. default: true,
  693. },
  694. //#SECTION lyrics
  695. geniusLyrics: {
  696. desc: "Add a button to the media controls of the currently playing song to open its lyrics on genius.com",
  697. type: "toggle",
  698. category: "lyrics",
  699. default: true,
  700. },
  701. };
  702. /***/ }),
  703. /***/ "./src/features/input.ts":
  704. /*!*******************************!*\
  705. !*** ./src/features/input.ts ***!
  706. \*******************************/
  707. /***/ (function(__unused_webpack_module, __webpack_exports__, __webpack_require__) {
  708. __webpack_require__.r(__webpack_exports__);
  709. /* harmony export */ __webpack_require__.d(__webpack_exports__, {
  710. /* harmony export */ disableBeforeUnload: function() { return /* binding */ disableBeforeUnload; },
  711. /* harmony export */ enableBeforeUnload: function() { return /* binding */ enableBeforeUnload; },
  712. /* harmony export */ initArrowKeySkip: function() { return /* binding */ initArrowKeySkip; },
  713. /* harmony export */ initBeforeUnloadHook: function() { return /* binding */ initBeforeUnloadHook; },
  714. /* harmony export */ initSiteSwitch: function() { return /* binding */ initSiteSwitch; }
  715. /* harmony export */ });
  716. /* harmony import */ var _utils__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../utils */ "./src/utils.ts");
  717. /* harmony import */ var _config__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../config */ "./src/config.ts");
  718. var __awaiter = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) {
  719. function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
  720. return new (P || (P = Promise))(function (resolve, reject) {
  721. function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
  722. function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
  723. function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
  724. step((generator = generator.apply(thisArg, _arguments || [])).next());
  725. });
  726. };
  727. //#MARKER arrow key skip
  728. function initArrowKeySkip() {
  729. document.addEventListener("keydown", onKeyDown);
  730. (0,_utils__WEBPACK_IMPORTED_MODULE_0__.log)("Added key press listener");
  731. }
  732. /** Called when the user presses any key, anywhere */
  733. function onKeyDown(evt) {
  734. var _a, _b;
  735. if (["ArrowLeft", "ArrowRight"].includes(evt.code)) {
  736. // discard the event when a (text) input is currently active, like when editing a playlist
  737. if (["INPUT", "TEXTAREA", "SELECT"].includes((_b = (_a = document.activeElement) === null || _a === void 0 ? void 0 : _a.tagName) !== null && _b !== void 0 ? _b : "_"))
  738. return (0,_utils__WEBPACK_IMPORTED_MODULE_0__.info)(`Captured valid key but the current active element is <${document.activeElement.tagName.toLowerCase()}>, so the keypress is ignored`);
  739. (0,_utils__WEBPACK_IMPORTED_MODULE_0__.log)(`Captured key '${evt.code}' in proxy listener`);
  740. // 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
  741. const defaultProps = {
  742. altKey: false,
  743. ctrlKey: false,
  744. metaKey: false,
  745. shiftKey: false,
  746. target: document.body,
  747. currentTarget: document.body,
  748. originalTarget: document.body,
  749. explicitOriginalTarget: document.body,
  750. srcElement: document.body,
  751. type: "keydown",
  752. bubbles: true,
  753. cancelBubble: false,
  754. cancelable: true,
  755. isTrusted: true,
  756. repeat: false,
  757. // needed because otherwise YTM errors out - see https://github.com/Sv443/BetterYTM/issues/18#show_issue
  758. view: (0,_utils__WEBPACK_IMPORTED_MODULE_0__.getUnsafeWindow)(),
  759. };
  760. let invalidKey = false;
  761. let keyProps = {};
  762. switch (evt.code) {
  763. case "ArrowLeft":
  764. keyProps = {
  765. code: "KeyH",
  766. key: "h",
  767. keyCode: 72,
  768. which: 72,
  769. };
  770. break;
  771. case "ArrowRight":
  772. keyProps = {
  773. code: "KeyL",
  774. key: "l",
  775. keyCode: 76,
  776. which: 76,
  777. };
  778. break;
  779. default:
  780. invalidKey = true;
  781. break;
  782. }
  783. if (!invalidKey) {
  784. const proxyProps = Object.assign(Object.assign({ code: "" }, defaultProps), keyProps);
  785. document.body.dispatchEvent(new KeyboardEvent("keydown", proxyProps));
  786. (0,_utils__WEBPACK_IMPORTED_MODULE_0__.log)(`Dispatched proxy keydown event: [${evt.code}] -> [${proxyProps.code}]`);
  787. }
  788. else
  789. (0,_utils__WEBPACK_IMPORTED_MODULE_0__.warn)(`Captured key '${evt.code}' has no defined behavior`);
  790. }
  791. }
  792. //#MARKER site switch
  793. /** Initializes the site switch feature */
  794. function initSiteSwitch(domain) {
  795. document.addEventListener("keydown", (e) => {
  796. if (e.key === "F9")
  797. switchSite(domain === "yt" ? "ytm" : "yt");
  798. });
  799. (0,_utils__WEBPACK_IMPORTED_MODULE_0__.log)("Initialized site switch listener");
  800. }
  801. /** Switches to the other site (between YT and YTM) */
  802. function switchSite(newDomain) {
  803. var _a;
  804. return __awaiter(this, void 0, void 0, function* () {
  805. try {
  806. if (newDomain === "ytm" && !location.href.includes("/watch"))
  807. return (0,_utils__WEBPACK_IMPORTED_MODULE_0__.warn)("Not on a video page, so the site switch is ignored");
  808. let subdomain;
  809. if (newDomain === "ytm")
  810. subdomain = "music";
  811. else if (newDomain === "yt")
  812. subdomain = "www";
  813. if (!subdomain)
  814. throw new Error(`Unrecognized domain '${newDomain}'`);
  815. disableBeforeUnload();
  816. const { pathname, search, hash } = new URL(location.href);
  817. const vt = (_a = yield (0,_utils__WEBPACK_IMPORTED_MODULE_0__.getVideoTime)()) !== null && _a !== void 0 ? _a : 0;
  818. (0,_utils__WEBPACK_IMPORTED_MODULE_0__.log)(`Found video time of ${vt} seconds`);
  819. const cleanSearch = search.split("&")
  820. .filter((param) => !param.match(/^\??t=/))
  821. .join("&");
  822. const newSearch = cleanSearch.includes("?") ? `${cleanSearch.startsWith("?") ? cleanSearch : "?" + cleanSearch}&t=${vt}` : `?t=${vt}`;
  823. const newUrl = `https://${subdomain}.youtube.com${pathname}${newSearch}${hash}`;
  824. (0,_utils__WEBPACK_IMPORTED_MODULE_0__.info)(`Switching to domain '${newDomain}' at ${newUrl}`);
  825. location.assign(newUrl);
  826. }
  827. catch (err) {
  828. (0,_utils__WEBPACK_IMPORTED_MODULE_0__.error)("Error while switching site:", err);
  829. }
  830. });
  831. }
  832. //#MARKER beforeunload popup
  833. let beforeUnloadEnabled = true;
  834. /** Disables the popup before leaving the site */
  835. function disableBeforeUnload() {
  836. beforeUnloadEnabled = false;
  837. (0,_utils__WEBPACK_IMPORTED_MODULE_0__.info)("Disabled popup before leaving the site");
  838. }
  839. /** (Re-)enables the popup before leaving the site */
  840. function enableBeforeUnload() {
  841. beforeUnloadEnabled = true;
  842. (0,_utils__WEBPACK_IMPORTED_MODULE_0__.info)("Enabled popup before leaving the site");
  843. }
  844. /**
  845. * Adds a spy function into `window.__proto__.addEventListener` to selectively discard `beforeunload`
  846. * event listeners before they can be called by the site.
  847. */
  848. function initBeforeUnloadHook() {
  849. Error.stackTraceLimit = 1000; // default is 25 on FF so this should hopefully be more than enough
  850. (function (original) {
  851. // @ts-ignore
  852. window.__proto__.addEventListener = function (...args) {
  853. if (!beforeUnloadEnabled && args[0] === "beforeunload")
  854. return (0,_utils__WEBPACK_IMPORTED_MODULE_0__.log)("Prevented beforeunload event listener from being called");
  855. else
  856. return original.apply(this, args);
  857. };
  858. // @ts-ignore
  859. })(window.__proto__.addEventListener);
  860. (0,_config__WEBPACK_IMPORTED_MODULE_1__.getFeatures)().then(feats => {
  861. if (feats.disableBeforeUnloadPopup)
  862. disableBeforeUnload();
  863. });
  864. }
  865. /***/ }),
  866. /***/ "./src/features/layout.ts":
  867. /*!********************************!*\
  868. !*** ./src/features/layout.ts ***!
  869. \********************************/
  870. /***/ (function(__unused_webpack_module, __webpack_exports__, __webpack_require__) {
  871. __webpack_require__.r(__webpack_exports__);
  872. /* harmony export */ __webpack_require__.d(__webpack_exports__, {
  873. /* harmony export */ addAnchorImprovements: function() { return /* binding */ addAnchorImprovements; },
  874. /* harmony export */ addConfigMenuOption: function() { return /* binding */ addConfigMenuOption; },
  875. /* harmony export */ addWatermark: function() { return /* binding */ addWatermark; },
  876. /* harmony export */ initQueueButtons: function() { return /* binding */ initQueueButtons; },
  877. /* harmony export */ preInitLayout: function() { return /* binding */ preInitLayout; },
  878. /* harmony export */ removeUpgradeTab: function() { return /* binding */ removeUpgradeTab; },
  879. /* harmony export */ setVolSliderSize: function() { return /* binding */ setVolSliderSize; },
  880. /* harmony export */ setVolSliderStep: function() { return /* binding */ setVolSliderStep; }
  881. /* harmony export */ });
  882. /* harmony import */ var _constants__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../constants */ "./src/constants.ts");
  883. /* harmony import */ var _config__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../config */ "./src/config.ts");
  884. /* harmony import */ var _utils__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../utils */ "./src/utils.ts");
  885. /* harmony import */ var _events__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../events */ "./src/events.ts");
  886. /* harmony import */ var _menu_menu_old__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./menu/menu_old */ "./src/features/menu/menu_old.ts");
  887. /* harmony import */ var _lyrics__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./lyrics */ "./src/features/lyrics.ts");
  888. /* harmony import */ var _layout_css__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ./layout.css */ "./src/features/layout.css");
  889. var __awaiter = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) {
  890. function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
  891. return new (P || (P = Promise))(function (resolve, reject) {
  892. function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
  893. function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
  894. function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
  895. step((generator = generator.apply(thisArg, _arguments || [])).next());
  896. });
  897. };
  898. let features;
  899. function preInitLayout() {
  900. return __awaiter(this, void 0, void 0, function* () {
  901. features = yield (0,_config__WEBPACK_IMPORTED_MODULE_1__.getFeatures)();
  902. });
  903. }
  904. //#MARKER BYTM-Config buttons
  905. /** Adds a watermark beneath the logo */
  906. function addWatermark() {
  907. const watermark = document.createElement("a");
  908. watermark.role = "button";
  909. watermark.id = "betterytm-watermark";
  910. watermark.className = "style-scope ytmusic-nav-bar";
  911. watermark.innerText = _constants__WEBPACK_IMPORTED_MODULE_0__.scriptInfo.name;
  912. watermark.title = "Open menu";
  913. watermark.tabIndex = 1000;
  914. watermark.addEventListener("click", (e) => {
  915. e.stopPropagation();
  916. (0,_menu_menu_old__WEBPACK_IMPORTED_MODULE_4__.openMenu)();
  917. });
  918. // when using the tab key to navigate
  919. watermark.addEventListener("keydown", (e) => {
  920. if (e.key === "Enter") {
  921. e.stopPropagation();
  922. (0,_menu_menu_old__WEBPACK_IMPORTED_MODULE_4__.openMenu)();
  923. }
  924. });
  925. const logoElem = document.querySelector("#left-content");
  926. (0,_utils__WEBPACK_IMPORTED_MODULE_2__.insertAfter)(logoElem, watermark);
  927. (0,_utils__WEBPACK_IMPORTED_MODULE_2__.log)("Added watermark element:", watermark);
  928. }
  929. /** Called whenever the menu exists to add a BYTM-Configuration button */
  930. function addConfigMenuOption(container) {
  931. const cfgOptElem = document.createElement("a");
  932. cfgOptElem.role = "button";
  933. cfgOptElem.className = "bytm-cfg-menu-option bytm-anchor";
  934. cfgOptElem.ariaLabel = "Click to open BetterYTM's configuration menu";
  935. const cfgOptItemElem = document.createElement("div");
  936. cfgOptItemElem.className = "bytm-cfg-menu-option-item";
  937. cfgOptItemElem.addEventListener("click", () => {
  938. const settingsBtnElem = document.querySelector("ytmusic-nav-bar ytmusic-settings-button tp-yt-paper-icon-button");
  939. settingsBtnElem === null || settingsBtnElem === void 0 ? void 0 : settingsBtnElem.click();
  940. (0,_menu_menu_old__WEBPACK_IMPORTED_MODULE_4__.openMenu)();
  941. });
  942. const cfgOptIconElem = document.createElement("img");
  943. cfgOptIconElem.className = "bytm-cfg-menu-option-icon";
  944. cfgOptIconElem.src = (0,_utils__WEBPACK_IMPORTED_MODULE_2__.getAssetUrl)("icon/icon.png");
  945. const cfgOptTextElem = document.createElement("div");
  946. cfgOptTextElem.className = "bytm-cfg-menu-option-text";
  947. cfgOptTextElem.innerText = "BetterYTM Configuration";
  948. cfgOptItemElem.appendChild(cfgOptIconElem);
  949. cfgOptItemElem.appendChild(cfgOptTextElem);
  950. cfgOptElem.appendChild(cfgOptItemElem);
  951. container.appendChild(cfgOptElem);
  952. (0,_utils__WEBPACK_IMPORTED_MODULE_2__.log)("Added BYTM-Configuration button to menu popover");
  953. }
  954. //#MARKER remove upgrade tab
  955. /** Removes the "Upgrade" / YT Music Premium tab from the sidebar */
  956. function removeUpgradeTab() {
  957. (0,_utils__WEBPACK_IMPORTED_MODULE_2__.onSelectorExists)("ytmusic-app-layout tp-yt-app-drawer #contentContainer #guide-content #items ytmusic-guide-entry-renderer:nth-child(4)", (tabElemLarge) => {
  958. tabElemLarge.remove();
  959. (0,_utils__WEBPACK_IMPORTED_MODULE_2__.log)("Removed large upgrade tab");
  960. });
  961. (0,_utils__WEBPACK_IMPORTED_MODULE_2__.onSelectorExists)("ytmusic-app-layout #mini-guide ytmusic-guide-renderer #sections ytmusic-guide-section-renderer #items ytmusic-guide-entry-renderer:nth-child(4)", (tabElemSmall) => {
  962. tabElemSmall.remove();
  963. (0,_utils__WEBPACK_IMPORTED_MODULE_2__.log)("Removed small upgrade tab");
  964. });
  965. }
  966. //#MARKER volume slider
  967. /** Sets the volume slider to a set size */
  968. function setVolSliderSize() {
  969. const { volumeSliderSize: size } = features;
  970. if (typeof size !== "number" || isNaN(Number(size)))
  971. return;
  972. const style = `\
  973. .volume-slider.ytmusic-player-bar, .expand-volume-slider.ytmusic-player-bar {
  974. width: ${size}px !important;
  975. }`;
  976. (0,_utils__WEBPACK_IMPORTED_MODULE_2__.addGlobalStyle)(style, "vol-slider");
  977. }
  978. /** Sets the `step` attribute of the volume slider */
  979. function setVolSliderStep() {
  980. const sliderElem = document.querySelector("tp-yt-paper-slider#volume-slider");
  981. sliderElem.setAttribute("step", String(features.volumeSliderStep));
  982. }
  983. //#MARKER queue buttons
  984. function initQueueButtons() {
  985. const addQueueBtns = (evt) => {
  986. let amt = 0;
  987. for (const queueItm of (0,_events__WEBPACK_IMPORTED_MODULE_3__.getEvtData)(evt).childNodes) {
  988. if (!queueItm.classList.contains("bytm-has-queue-btns")) {
  989. addQueueButtons(queueItm);
  990. amt++;
  991. }
  992. }
  993. if (amt > 0)
  994. (0,_utils__WEBPACK_IMPORTED_MODULE_2__.log)(`Added buttons to ${amt} new queue ${(0,_utils__WEBPACK_IMPORTED_MODULE_2__.autoPlural)("item", amt)}`);
  995. };
  996. _events__WEBPACK_IMPORTED_MODULE_3__.siteEvents.on("queueChanged", addQueueBtns);
  997. _events__WEBPACK_IMPORTED_MODULE_3__.siteEvents.on("autoplayQueueChanged", addQueueBtns);
  998. const queueItems = document.querySelectorAll("#contents.ytmusic-player-queue > ytmusic-player-queue-item");
  999. if (queueItems.length === 0)
  1000. return;
  1001. queueItems.forEach(itm => addQueueButtons(itm));
  1002. (0,_utils__WEBPACK_IMPORTED_MODULE_2__.log)(`Added buttons to ${queueItems.length} existing queue items`);
  1003. }
  1004. /**
  1005. * Adds the buttons to each item in the current song queue.
  1006. * Also observes for changes to add new buttons to new items in the queue.
  1007. * TODO:FIXME: deleting an element from the queue shifts the lyrics buttons
  1008. * @param queueItem The element with tagname `ytmusic-player-queue-item` to add queue buttons to
  1009. */
  1010. function addQueueButtons(queueItem) {
  1011. return __awaiter(this, void 0, void 0, function* () {
  1012. //#SECTION general queue item stuff
  1013. const queueBtnsCont = document.createElement("div");
  1014. queueBtnsCont.className = "bytm-queue-btn-container";
  1015. const songInfo = queueItem.querySelector(".song-info");
  1016. if (!songInfo)
  1017. return false;
  1018. const [songEl, artistEl] = songInfo.querySelectorAll("yt-formatted-string");
  1019. const song = songEl.innerText;
  1020. const artist = artistEl.innerText;
  1021. if (!song || !artist)
  1022. return false;
  1023. //#SECTION lyrics btn
  1024. const lyricsBtnElem = (0,_lyrics__WEBPACK_IMPORTED_MODULE_5__.createLyricsBtn)(undefined, false);
  1025. {
  1026. lyricsBtnElem.title = "Open this song's lyrics in a new tab";
  1027. lyricsBtnElem.style.display = "inline-flex";
  1028. lyricsBtnElem.style.visibility = "initial";
  1029. lyricsBtnElem.style.pointerEvents = "initial";
  1030. lyricsBtnElem.addEventListener("click", (e) => __awaiter(this, void 0, void 0, function* () {
  1031. e.stopPropagation();
  1032. let lyricsUrl;
  1033. const artistsSan = (0,_lyrics__WEBPACK_IMPORTED_MODULE_5__.sanitizeArtists)(artist);
  1034. const songSan = (0,_lyrics__WEBPACK_IMPORTED_MODULE_5__.sanitizeSong)(song);
  1035. const cachedLyricsUrl = (0,_lyrics__WEBPACK_IMPORTED_MODULE_5__.getLyricsCacheEntry)(artistsSan, songSan);
  1036. if (cachedLyricsUrl)
  1037. lyricsUrl = cachedLyricsUrl;
  1038. else if (!songInfo.hasAttribute("data-bytm-loading")) {
  1039. const imgEl = lyricsBtnElem.querySelector("img");
  1040. if (!cachedLyricsUrl) {
  1041. songInfo.setAttribute("data-bytm-loading", "");
  1042. imgEl.src = (0,_utils__WEBPACK_IMPORTED_MODULE_2__.getAssetUrl)("spinner.svg");
  1043. imgEl.classList.add("bytm-spinner");
  1044. }
  1045. lyricsUrl = cachedLyricsUrl !== null && cachedLyricsUrl !== void 0 ? cachedLyricsUrl : yield (0,_lyrics__WEBPACK_IMPORTED_MODULE_5__.getGeniusUrl)(artistsSan, songSan);
  1046. const resetImgElem = () => {
  1047. imgEl.src = (0,_utils__WEBPACK_IMPORTED_MODULE_2__.getAssetUrl)("external/genius.png");
  1048. imgEl.classList.remove("bytm-spinner");
  1049. };
  1050. if (!cachedLyricsUrl) {
  1051. songInfo.removeAttribute("data-bytm-loading");
  1052. // so the new image doesn't "blink"
  1053. setTimeout(resetImgElem, 100);
  1054. }
  1055. if (!lyricsUrl) {
  1056. resetImgElem();
  1057. if (confirm("Couldn't find a lyrics page for this song.\nDo you want to open genius.com to manually search for it?"))
  1058. (0,_utils__WEBPACK_IMPORTED_MODULE_2__.openInNewTab)("https://genius.com/search");
  1059. return;
  1060. }
  1061. }
  1062. lyricsUrl && (0,_utils__WEBPACK_IMPORTED_MODULE_2__.openInNewTab)(lyricsUrl);
  1063. }));
  1064. }
  1065. //#SECTION delete from queue btn
  1066. const deleteBtnElem = document.createElement("a");
  1067. {
  1068. Object.assign(deleteBtnElem, {
  1069. title: "Remove this song from the queue",
  1070. className: "ytmusic-player-bar bytm-delete-from-queue bytm-generic-btn",
  1071. role: "button",
  1072. });
  1073. deleteBtnElem.style.visibility = "initial";
  1074. deleteBtnElem.addEventListener("click", (e) => __awaiter(this, void 0, void 0, function* () {
  1075. e.stopPropagation();
  1076. // container of the queue item popup menu - element gets reused for every queue item
  1077. let queuePopupCont = document.querySelector("ytmusic-app ytmusic-popup-container tp-yt-iron-dropdown");
  1078. try {
  1079. // three dots button to open the popup menu of a queue item
  1080. const dotsBtnElem = queueItem.querySelector("ytmusic-menu-renderer yt-button-shape button");
  1081. if (queuePopupCont)
  1082. queuePopupCont.setAttribute("data-bytm-hidden", "true");
  1083. dotsBtnElem.click();
  1084. yield (0,_utils__WEBPACK_IMPORTED_MODULE_2__.pauseFor)(25);
  1085. queuePopupCont = document.querySelector("ytmusic-app ytmusic-popup-container tp-yt-iron-dropdown");
  1086. if (!queuePopupCont.hasAttribute("data-bytm-hidden"))
  1087. queuePopupCont.setAttribute("data-bytm-hidden", "true");
  1088. // a little bit janky and unreliable but the only way afaik
  1089. const removeFromQueueBtn = queuePopupCont.querySelector("tp-yt-paper-listbox *[role=option]:nth-child(7)");
  1090. yield (0,_utils__WEBPACK_IMPORTED_MODULE_2__.pauseFor)(20);
  1091. removeFromQueueBtn.click();
  1092. }
  1093. catch (err) {
  1094. (0,_utils__WEBPACK_IMPORTED_MODULE_2__.error)("Couldn't remove song from queue due to error:", err);
  1095. }
  1096. finally {
  1097. queuePopupCont === null || queuePopupCont === void 0 ? void 0 : queuePopupCont.removeAttribute("data-bytm-hidden");
  1098. }
  1099. }));
  1100. const imgElem = document.createElement("img");
  1101. imgElem.className = "bytm-generic-btn-img";
  1102. imgElem.src = (0,_utils__WEBPACK_IMPORTED_MODULE_2__.getAssetUrl)("delete.svg");
  1103. deleteBtnElem.appendChild(imgElem);
  1104. }
  1105. //#SECTION append elements to DOM
  1106. queueBtnsCont.appendChild(lyricsBtnElem);
  1107. queueBtnsCont.appendChild(deleteBtnElem);
  1108. songInfo.appendChild(queueBtnsCont);
  1109. queueItem.classList.add("bytm-has-queue-btns");
  1110. return true;
  1111. });
  1112. }
  1113. //#MARKER better clickable stuff
  1114. /** Adds anchors around elements and tweaks existing ones so songs are easier to open in a new tab */
  1115. function addAnchorImprovements() {
  1116. //#SECTION carousel shelves
  1117. try {
  1118. /** Only adds anchor improvements for carousel shelves that contain the regular list-item-renderer, not the two-row-item-renderer */
  1119. const condCarouselImprovements = (el) => {
  1120. const listItemRenderer = el.querySelector("ytmusic-responsive-list-item-renderer");
  1121. if (listItemRenderer) {
  1122. const itemsElem = el.querySelector("ul#items");
  1123. if (itemsElem) {
  1124. (0,_utils__WEBPACK_IMPORTED_MODULE_2__.log)("Adding anchor improvements to carousel shelf");
  1125. improveCarouselAnchors(itemsElem);
  1126. }
  1127. }
  1128. };
  1129. // initial three shelves aren't included in the event fire
  1130. (0,_utils__WEBPACK_IMPORTED_MODULE_2__.onSelectorExists)("ytmusic-carousel-shelf-renderer", () => {
  1131. const carouselShelves = document.body.querySelectorAll("ytmusic-carousel-shelf-renderer");
  1132. carouselShelves.forEach(condCarouselImprovements);
  1133. });
  1134. // every shelf that's loaded by scrolling:
  1135. _events__WEBPACK_IMPORTED_MODULE_3__.siteEvents.on("carouselShelvesChanged", (evt) => {
  1136. const { addedNodes, removedNodes } = (0,_events__WEBPACK_IMPORTED_MODULE_3__.getEvtData)(evt);
  1137. void removedNodes;
  1138. if (addedNodes.length > 0)
  1139. addedNodes.forEach(condCarouselImprovements);
  1140. });
  1141. }
  1142. catch (err) {
  1143. (0,_utils__WEBPACK_IMPORTED_MODULE_2__.error)("Couldn't improve carousel shelf anchors due to an error:", err);
  1144. }
  1145. //#SECTION sidebar
  1146. try {
  1147. const addSidebarAnchors = (sidebarCont) => {
  1148. const items = sidebarCont.parentNode.querySelectorAll("ytmusic-guide-entry-renderer tp-yt-paper-item");
  1149. improveSidebarAnchors(items);
  1150. return items.length;
  1151. };
  1152. (0,_utils__WEBPACK_IMPORTED_MODULE_2__.onSelectorExists)("ytmusic-app-layout tp-yt-app-drawer #contentContainer #guide-content #items ytmusic-guide-entry-renderer", (sidebarCont) => {
  1153. const itemsAmt = addSidebarAnchors(sidebarCont);
  1154. (0,_utils__WEBPACK_IMPORTED_MODULE_2__.log)(`Added anchors around ${itemsAmt} sidebar items`);
  1155. });
  1156. (0,_utils__WEBPACK_IMPORTED_MODULE_2__.onSelectorExists)("ytmusic-app-layout #mini-guide ytmusic-guide-renderer ytmusic-guide-section-renderer #items ytmusic-guide-entry-renderer", (miniSidebarCont) => {
  1157. const itemsAmt = addSidebarAnchors(miniSidebarCont);
  1158. (0,_utils__WEBPACK_IMPORTED_MODULE_2__.log)(`Added anchors around ${itemsAmt} mini sidebar items`);
  1159. });
  1160. }
  1161. catch (err) {
  1162. (0,_utils__WEBPACK_IMPORTED_MODULE_2__.error)("Couldn't add anchors to sidebar items due to an error:", err);
  1163. }
  1164. }
  1165. // TODO: add to "related" tab in /watch
  1166. const sidebarPaths = [
  1167. "/",
  1168. "/explore",
  1169. "/library",
  1170. ];
  1171. /**
  1172. * Adds anchors to the sidebar items so they can be opened in a new tab
  1173. * @param sidebarItem
  1174. */
  1175. function improveSidebarAnchors(sidebarItems) {
  1176. sidebarItems.forEach((item, i) => {
  1177. var _a;
  1178. const anchorElem = document.createElement("a");
  1179. anchorElem.className = "bytm-anchor";
  1180. anchorElem.role = "button";
  1181. anchorElem.target = "_self";
  1182. anchorElem.href = (_a = sidebarPaths[i]) !== null && _a !== void 0 ? _a : "#";
  1183. anchorElem.title = "Middle click to open in a new tab";
  1184. anchorElem.addEventListener("click", (e) => {
  1185. e.preventDefault();
  1186. });
  1187. (0,_utils__WEBPACK_IMPORTED_MODULE_2__.addParent)(item, anchorElem);
  1188. });
  1189. }
  1190. /**
  1191. * Actually adds the anchor improvements to carousel shelf items
  1192. * @param itemsElement The container with the selector `ul#items` inside of each `ytmusic-carousel`
  1193. */
  1194. function improveCarouselAnchors(itemsElement) {
  1195. if (itemsElement.classList.contains("bytm-anchors-improved"))
  1196. return;
  1197. itemsElement.classList.add("bytm-anchors-improved");
  1198. for (const listItem of itemsElement.querySelectorAll("ytmusic-responsive-list-item-renderer")) {
  1199. try {
  1200. const thumbnailElem = listItem.querySelector(".left-items");
  1201. const titleElem = listItem.querySelector(".title-column yt-formatted-string.title a");
  1202. if (!thumbnailElem || !titleElem) {
  1203. (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");
  1204. continue;
  1205. }
  1206. const thumbnailAnchor = document.createElement("a");
  1207. thumbnailAnchor.className = "bytm-carousel-shelf-anchor bytm-anchor";
  1208. thumbnailAnchor.href = titleElem.href;
  1209. thumbnailAnchor.target = "_self";
  1210. thumbnailAnchor.role = "button";
  1211. thumbnailAnchor.addEventListener("click", (e) => {
  1212. e.preventDefault();
  1213. });
  1214. (0,_utils__WEBPACK_IMPORTED_MODULE_2__.addParent)(thumbnailElem, thumbnailAnchor);
  1215. }
  1216. catch (err) {
  1217. (0,_utils__WEBPACK_IMPORTED_MODULE_2__.error)("Couldn't add anchor improvements due to error:", err);
  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 */ });
  1239. /* harmony import */ var _utils__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../utils */ "./src/utils.ts");
  1240. var __awaiter = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) {
  1241. function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
  1242. return new (P || (P = Promise))(function (resolve, reject) {
  1243. function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
  1244. function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
  1245. function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
  1246. step((generator = generator.apply(thisArg, _arguments || [])).next());
  1247. });
  1248. };
  1249. var __asyncValues = (undefined && undefined.__asyncValues) || function (o) {
  1250. if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined.");
  1251. var m = o[Symbol.asyncIterator], i;
  1252. 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);
  1253. 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); }); }; }
  1254. function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); }
  1255. };
  1256. /** Base URL of geniURL */
  1257. const geniUrlBase = "https://api.sv443.net/geniurl";
  1258. /** GeniURL endpoint that gives song metadata when provided with a `?q` or `?artist` and `?song` parameter - [more info](https://api.sv443.net/geniurl) */
  1259. const geniURLSearchTopUrl = `${geniUrlBase}/search/top`;
  1260. /**
  1261. * The threshold to pass to geniURL's fuzzy filtering.
  1262. * 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.
  1263. * Set to undefined to use the default.
  1264. */
  1265. const threshold = 0.55;
  1266. /** Ratelimit budget timeframe in seconds - should reflect what's in geniURL's docs */
  1267. const geniUrlRatelimitTimeframe = 30;
  1268. const thresholdParam = threshold ? `&threshold=${(0,_utils__WEBPACK_IMPORTED_MODULE_0__.clamp)(threshold, 0, 1)}` : "";
  1269. //#MARKER cache
  1270. /** Cache with key format `ARTIST - SONG` (sanitized) and lyrics URLs as values. Used to prevent extraneous requests to geniURL. */
  1271. const lyricsUrlCache = new Map();
  1272. /** How many cache entries can exist at a time - this is used to cap memory usage */
  1273. const maxLyricsCacheSize = 100;
  1274. /**
  1275. * Returns the lyrics URL from the passed un-/sanitized artist and song name, or undefined if the entry doesn't exist yet.
  1276. * **The passed parameters need to be sanitized first!**
  1277. */
  1278. function getLyricsCacheEntry(artists, song) {
  1279. return lyricsUrlCache.get(`${artists} - ${song}`);
  1280. }
  1281. /** Adds the provided entry into the lyrics URL cache */
  1282. function addLyricsCacheEntry(artists, song, lyricsUrl) {
  1283. lyricsUrlCache.set(`${sanitizeArtists(artists)} - ${sanitizeSong(song)}`, lyricsUrl);
  1284. // delete oldest entry if cache gets too big
  1285. if (lyricsUrlCache.size > maxLyricsCacheSize)
  1286. lyricsUrlCache.delete([...lyricsUrlCache.keys()].at(-1));
  1287. }
  1288. //#MARKER media control bar
  1289. let mcCurrentSongTitle = "";
  1290. /** Adds a lyrics button to the media controls bar */
  1291. function addMediaCtrlLyricsBtn() {
  1292. (0,_utils__WEBPACK_IMPORTED_MODULE_0__.onSelectorExists)(".middle-controls-buttons ytmusic-like-button-renderer#like-button-renderer", addActualMediaCtrlLyricsBtn);
  1293. }
  1294. /** Actually adds the lyrics button after the like button renderer has been verified to exist */
  1295. function addActualMediaCtrlLyricsBtn(likeContainer) {
  1296. const songTitleElem = document.querySelector(".content-info-wrapper > yt-formatted-string");
  1297. // run parallel without awaiting so the MutationObserver below can observe the title element in time
  1298. (() => __awaiter(this, void 0, void 0, function* () {
  1299. const gUrl = yield getCurrentLyricsUrl();
  1300. const linkElem = createLyricsBtn(gUrl !== null && gUrl !== void 0 ? gUrl : undefined);
  1301. linkElem.id = "betterytm-lyrics-button";
  1302. (0,_utils__WEBPACK_IMPORTED_MODULE_0__.log)("Inserted lyrics button into media controls bar");
  1303. (0,_utils__WEBPACK_IMPORTED_MODULE_0__.insertAfter)(likeContainer, linkElem);
  1304. }))();
  1305. mcCurrentSongTitle = songTitleElem.title;
  1306. const onMutation = (mutations) => { var _a, mutations_1, mutations_1_1; return __awaiter(this, void 0, void 0, function* () {
  1307. var _b, e_1, _c, _d;
  1308. try {
  1309. for (_a = true, mutations_1 = __asyncValues(mutations); mutations_1_1 = yield mutations_1.next(), _b = mutations_1_1.done, !_b;) {
  1310. _d = mutations_1_1.value;
  1311. _a = false;
  1312. try {
  1313. const mut = _d;
  1314. const newTitle = mut.target.title;
  1315. if (newTitle !== mcCurrentSongTitle && newTitle.length > 0) {
  1316. const lyricsBtn = document.querySelector("#betterytm-lyrics-button");
  1317. if (!lyricsBtn)
  1318. return;
  1319. (0,_utils__WEBPACK_IMPORTED_MODULE_0__.log)(`Song title changed from '${mcCurrentSongTitle}' to '${newTitle}'`);
  1320. lyricsBtn.style.cursor = "wait";
  1321. lyricsBtn.style.pointerEvents = "none";
  1322. const imgElem = lyricsBtn.querySelector("img");
  1323. imgElem.src = (0,_utils__WEBPACK_IMPORTED_MODULE_0__.getAssetUrl)("spinner.svg");
  1324. imgElem.classList.add("bytm-spinner");
  1325. mcCurrentSongTitle = newTitle;
  1326. const url = yield getCurrentLyricsUrl(); // can take a second or two
  1327. imgElem.src = (0,_utils__WEBPACK_IMPORTED_MODULE_0__.getAssetUrl)("external/genius.png");
  1328. imgElem.classList.remove("bytm-spinner");
  1329. if (!url)
  1330. continue;
  1331. lyricsBtn.href = url;
  1332. lyricsBtn.title = "Open the current song's lyrics in a new tab";
  1333. lyricsBtn.style.cursor = "pointer";
  1334. lyricsBtn.style.visibility = "initial";
  1335. lyricsBtn.style.display = "inline-flex";
  1336. lyricsBtn.style.pointerEvents = "initial";
  1337. }
  1338. }
  1339. finally {
  1340. _a = true;
  1341. }
  1342. }
  1343. }
  1344. catch (e_1_1) { e_1 = { error: e_1_1 }; }
  1345. finally {
  1346. try {
  1347. if (!_a && !_b && (_c = mutations_1.return)) yield _c.call(mutations_1);
  1348. }
  1349. finally { if (e_1) throw e_1.error; }
  1350. }
  1351. }); };
  1352. // 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
  1353. const obs = new MutationObserver(onMutation);
  1354. obs.observe(songTitleElem, { attributes: true, attributeFilter: ["title"] });
  1355. }
  1356. //#MARKER utils
  1357. /** Removes everything in parentheses from the passed song name */
  1358. function sanitizeSong(songName) {
  1359. const parensRegex = /\(.+\)/gmi;
  1360. const squareParensRegex = /\[.+\]/gmi;
  1361. // trim right after the song name:
  1362. const sanitized = songName
  1363. .replace(parensRegex, "")
  1364. .replace(squareParensRegex, "");
  1365. return sanitized.trim();
  1366. }
  1367. /** Removes the secondary artist (if it exists) from the passed artists string */
  1368. function sanitizeArtists(artists) {
  1369. artists = artists.split(/\s*\u2022\s*/gmiu)[0]; // split at &bull; [•] character
  1370. if (artists.match(/&/))
  1371. artists = artists.split(/\s*&\s*/gm)[0];
  1372. if (artists.match(/,/))
  1373. artists = artists.split(/,\s*/gm)[0];
  1374. return artists.trim();
  1375. }
  1376. /** Returns the lyrics URL from genius for the currently selected song */
  1377. function getCurrentLyricsUrl() {
  1378. var _a;
  1379. return __awaiter(this, void 0, void 0, function* () {
  1380. try {
  1381. // In videos the video title contains both artist and song title, in "regular" YTM songs, the video title only contains the song title
  1382. const isVideo = typeof ((_a = document.querySelector("ytmusic-player")) === null || _a === void 0 ? void 0 : _a.getAttribute("video-mode_")) === "string";
  1383. const songTitleElem = document.querySelector(".content-info-wrapper > yt-formatted-string");
  1384. const songMetaElem = document.querySelector("span.subtitle > yt-formatted-string:first-child");
  1385. if (!songTitleElem || !songMetaElem || !songTitleElem.title)
  1386. return undefined;
  1387. const songNameRaw = songTitleElem.title;
  1388. const songName = sanitizeSong(songNameRaw);
  1389. const artistName = sanitizeArtists(songMetaElem.title);
  1390. /** Use when the current song is not a "real YTM song" with a static background, but rather a music video */
  1391. const getGeniusUrlVideo = () => __awaiter(this, void 0, void 0, function* () {
  1392. if (!songName.includes("-")) // for some fucking reason some music videos have YTM-like song title and artist separation, some don't
  1393. return yield getGeniusUrl(artistName, songName);
  1394. const [artist, ...rest] = songName.split("-").map(v => v.trim());
  1395. return yield getGeniusUrl(artist, rest.join(" "));
  1396. });
  1397. // TODO: artist might need further splitting before comma or ampersand
  1398. const url = isVideo ? yield getGeniusUrlVideo() : yield getGeniusUrl(artistName, songName);
  1399. return url;
  1400. }
  1401. catch (err) {
  1402. (0,_utils__WEBPACK_IMPORTED_MODULE_0__.error)("Couldn't resolve lyrics URL:", err);
  1403. return undefined;
  1404. }
  1405. });
  1406. }
  1407. /** Fetches the actual lyrics URL from geniURL - **the passed parameters need to be sanitized first!** */
  1408. function getGeniusUrl(artist, song) {
  1409. var _a, _b, _c;
  1410. return __awaiter(this, void 0, void 0, function* () {
  1411. try {
  1412. const cacheEntry = getLyricsCacheEntry(artist, song);
  1413. if (cacheEntry) {
  1414. (0,_utils__WEBPACK_IMPORTED_MODULE_0__.info)(`Found lyrics URL in cache: ${cacheEntry}`);
  1415. return cacheEntry;
  1416. }
  1417. const startTs = Date.now();
  1418. const fetchUrl = `${geniURLSearchTopUrl}?artist=${encodeURIComponent(artist)}&song=${encodeURIComponent(song)}${thresholdParam}`;
  1419. (0,_utils__WEBPACK_IMPORTED_MODULE_0__.log)(`Requesting URL from geniURL at '${fetchUrl}'`);
  1420. const fetchRes = yield (0,_utils__WEBPACK_IMPORTED_MODULE_0__.fetchAdvanced)(fetchUrl);
  1421. if (fetchRes.status === 429) {
  1422. 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.`);
  1423. return undefined;
  1424. }
  1425. else if (fetchRes.status < 200 || fetchRes.status >= 300) {
  1426. (0,_utils__WEBPACK_IMPORTED_MODULE_0__.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)"}`);
  1427. return undefined;
  1428. }
  1429. const result = yield fetchRes.json();
  1430. if (typeof result === "object" && result.error) {
  1431. (0,_utils__WEBPACK_IMPORTED_MODULE_0__.error)("Couldn't fetch lyrics URL:", result.message);
  1432. return undefined;
  1433. }
  1434. const url = result.url;
  1435. (0,_utils__WEBPACK_IMPORTED_MODULE_0__.info)(`Found lyrics URL (after ${Date.now() - startTs}ms): ${url}`);
  1436. addLyricsCacheEntry(artist, song, url);
  1437. return url;
  1438. }
  1439. catch (err) {
  1440. (0,_utils__WEBPACK_IMPORTED_MODULE_0__.error)("Couldn't get lyrics URL due to error:", err);
  1441. return undefined;
  1442. }
  1443. });
  1444. }
  1445. /** Creates the base lyrics button element */
  1446. function createLyricsBtn(geniusUrl, hideIfLoading = true) {
  1447. const linkElem = document.createElement("a");
  1448. linkElem.className = "ytmusic-player-bar bytm-generic-btn";
  1449. linkElem.title = geniusUrl ? "Click to open this song's lyrics in a new tab" : "Loading lyrics URL...";
  1450. if (geniusUrl)
  1451. linkElem.href = geniusUrl;
  1452. linkElem.role = "button";
  1453. linkElem.target = "_blank";
  1454. linkElem.rel = "noopener noreferrer";
  1455. linkElem.style.visibility = hideIfLoading && geniusUrl ? "initial" : "hidden";
  1456. linkElem.style.display = hideIfLoading && geniusUrl ? "inline-flex" : "none";
  1457. const imgElem = document.createElement("img");
  1458. imgElem.className = "bytm-generic-btn-img";
  1459. imgElem.src = (0,_utils__WEBPACK_IMPORTED_MODULE_0__.getAssetUrl)("external/genius.png");
  1460. linkElem.appendChild(imgElem);
  1461. return linkElem;
  1462. }
  1463. /***/ }),
  1464. /***/ "./src/features/menu/menu.ts":
  1465. /*!***********************************!*\
  1466. !*** ./src/features/menu/menu.ts ***!
  1467. \***********************************/
  1468. /***/ (function(__unused_webpack_module, __webpack_exports__, __webpack_require__) {
  1469. __webpack_require__.r(__webpack_exports__);
  1470. /* harmony export */ __webpack_require__.d(__webpack_exports__, {
  1471. /* harmony export */ closeMenu: function() { return /* binding */ closeMenu; },
  1472. /* harmony export */ initMenu: function() { return /* binding */ initMenu; },
  1473. /* harmony export */ openMenu: function() { return /* binding */ openMenu; },
  1474. /* harmony export */ setActiveTab: function() { return /* binding */ setActiveTab; }
  1475. /* harmony export */ });
  1476. /* harmony import */ var _changelog_md__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../../../changelog.md */ "./changelog.md");
  1477. /* harmony import */ var _menu_html__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./menu.html */ "./src/features/menu/menu.html");
  1478. /* harmony import */ var _menu_css__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./menu.css */ "./src/features/menu/menu.css");
  1479. // REQUIREMENTS:
  1480. // - modal using the <dialog> element
  1481. // - sections with headers
  1482. // - support for "custom widgets"
  1483. // - debounce or save on button press to store new configuration
  1484. // - much better scaling including no vw and vh units
  1485. //#MARKER menu
  1486. /**
  1487. * These are the base selector values for the menu tabs
  1488. * Header selector format: `#${baseValue}-header`
  1489. * Content selector format: `#${baseValue}-content`
  1490. */
  1491. const tabsSelectors = {
  1492. options: "bytm-menu-tab-options",
  1493. info: "bytm-menu-tab-info",
  1494. changelog: "bytm-menu-tab-changelog",
  1495. };
  1496. function initMenu() {
  1497. document.addEventListener("DOMContentLoaded", () => {
  1498. // create menu container
  1499. const menuContainer = document.createElement("div");
  1500. menuContainer.id = "bytm-menu-container";
  1501. // add menu html
  1502. menuContainer.innerHTML = _menu_html__WEBPACK_IMPORTED_MODULE_1__["default"];
  1503. document.body.appendChild(menuContainer);
  1504. initMenuContents();
  1505. });
  1506. }
  1507. function initMenuContents() {
  1508. var _a;
  1509. // hook events
  1510. for (const tab in tabsSelectors) {
  1511. const selector = tabsSelectors[tab];
  1512. (_a = document.querySelector(`#${selector}-header`)) === null || _a === void 0 ? void 0 : _a.addEventListener("click", () => {
  1513. setActiveTab(tab);
  1514. });
  1515. }
  1516. // init tab contents
  1517. initOptionsContent();
  1518. initInfoContent();
  1519. initChangelogContent();
  1520. }
  1521. /** Opens the specified tab */
  1522. function setActiveTab(tab) {
  1523. const tabs = Object.assign({}, tabsSelectors);
  1524. delete tabs[tab];
  1525. // disable all but new active tab
  1526. for (const [, val] of Object.entries(tabs)) {
  1527. document.querySelector(`#${val}-header`).dataset.active = "false";
  1528. document.querySelector(`#${val}-content`).dataset.active = "false";
  1529. }
  1530. // enable new active tab
  1531. document.querySelector(`#${tabsSelectors[tab]}-header`).dataset.active = "true";
  1532. document.querySelector(`#${tabsSelectors[tab]}-content`).dataset.active = "true";
  1533. }
  1534. /** Opens the modal menu dialog */
  1535. function openMenu() {
  1536. var _a;
  1537. (_a = document.querySelector("#bytm-menu-dialog")) === null || _a === void 0 ? void 0 : _a.showModal();
  1538. }
  1539. /** Closes the modal menu dialog */
  1540. function closeMenu() {
  1541. var _a;
  1542. (_a = document.querySelector("#bytm-menu-dialog")) === null || _a === void 0 ? void 0 : _a.close();
  1543. }
  1544. //#MARKER menu tab contents
  1545. function initOptionsContent() {
  1546. const tab = document.querySelector("#bytm-menu-tab-options-content");
  1547. void tab;
  1548. }
  1549. function initInfoContent() {
  1550. const tab = document.querySelector("#bytm-menu-tab-info-content");
  1551. void tab;
  1552. }
  1553. function initChangelogContent() {
  1554. const tab = document.querySelector("#bytm-menu-tab-changelog-content");
  1555. tab.innerHTML = _changelog_md__WEBPACK_IMPORTED_MODULE_0__["default"];
  1556. }
  1557. /***/ }),
  1558. /***/ "./src/features/menu/menu_old.ts":
  1559. /*!***************************************!*\
  1560. !*** ./src/features/menu/menu_old.ts ***!
  1561. \***************************************/
  1562. /***/ (function(__unused_webpack_module, __webpack_exports__, __webpack_require__) {
  1563. __webpack_require__.r(__webpack_exports__);
  1564. /* harmony export */ __webpack_require__.d(__webpack_exports__, {
  1565. /* harmony export */ addMenu: function() { return /* binding */ addMenu; },
  1566. /* harmony export */ closeMenu: function() { return /* binding */ closeMenu; },
  1567. /* harmony export */ openMenu: function() { return /* binding */ openMenu; }
  1568. /* harmony export */ });
  1569. /* harmony import */ var _config__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../../config */ "./src/config.ts");
  1570. /* harmony import */ var _constants__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../../constants */ "./src/constants.ts");
  1571. /* harmony import */ var _index__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../index */ "./src/features/index.ts");
  1572. /* harmony import */ var _utils__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../../utils */ "./src/utils.ts");
  1573. /* harmony import */ var _menu_old_css__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./menu_old.css */ "./src/features/menu/menu_old.css");
  1574. var __awaiter = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) {
  1575. function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
  1576. return new (P || (P = Promise))(function (resolve, reject) {
  1577. function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
  1578. function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
  1579. function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
  1580. step((generator = generator.apply(thisArg, _arguments || [])).next());
  1581. });
  1582. };
  1583. //#MARKER create menu elements
  1584. let isMenuOpen = false;
  1585. /**
  1586. * Adds an element to open the BetterYTM menu
  1587. * @deprecated TODO: replace in v1.1.0 - see https://github.com/Sv443/BetterYTM/issues/23
  1588. */
  1589. function addMenu() {
  1590. var _a, _b;
  1591. return __awaiter(this, void 0, void 0, function* () {
  1592. //#SECTION backdrop & menu container
  1593. const backgroundElem = document.createElement("div");
  1594. backgroundElem.id = "betterytm-menu-bg";
  1595. backgroundElem.title = "Click here to close the menu";
  1596. backgroundElem.style.visibility = "hidden";
  1597. backgroundElem.style.display = "none";
  1598. backgroundElem.addEventListener("click", (e) => {
  1599. var _a;
  1600. if (isMenuOpen && ((_a = e.target) === null || _a === void 0 ? void 0 : _a.id) === "betterytm-menu-bg")
  1601. closeMenu(e);
  1602. });
  1603. document.body.addEventListener("keydown", (e) => {
  1604. if (isMenuOpen && e.key === "Escape")
  1605. closeMenu(e);
  1606. });
  1607. const menuContainer = document.createElement("div");
  1608. menuContainer.title = "";
  1609. menuContainer.id = "betterytm-menu";
  1610. menuContainer.style.borderRadius = "15px";
  1611. menuContainer.style.display = "flex";
  1612. menuContainer.style.flexDirection = "column";
  1613. menuContainer.style.justifyContent = "space-between";
  1614. //#SECTION title bar
  1615. const titleCont = document.createElement("div");
  1616. titleCont.style.padding = "8px 20px 15px 8px";
  1617. titleCont.style.display = "flex";
  1618. titleCont.style.justifyContent = "space-between";
  1619. titleCont.id = "betterytm-menu-titlecont";
  1620. const titleElem = document.createElement("h2");
  1621. titleElem.id = "betterytm-menu-title";
  1622. titleElem.innerText = `${_constants__WEBPACK_IMPORTED_MODULE_1__.scriptInfo.name} - Configuration`;
  1623. const linksCont = document.createElement("div");
  1624. linksCont.id = "betterytm-menu-linkscont";
  1625. const addLink = (imgSrc, href, title) => {
  1626. const anchorElem = document.createElement("a");
  1627. anchorElem.className = "betterytm-menu-link";
  1628. anchorElem.rel = "noopener noreferrer";
  1629. anchorElem.target = "_blank";
  1630. anchorElem.href = href;
  1631. anchorElem.title = title;
  1632. anchorElem.style.marginLeft = "10px";
  1633. const imgElem = document.createElement("img");
  1634. imgElem.className = "betterytm-menu-img";
  1635. imgElem.src = imgSrc;
  1636. imgElem.style.width = "32px";
  1637. imgElem.style.height = "32px";
  1638. anchorElem.appendChild(imgElem);
  1639. linksCont.appendChild(anchorElem);
  1640. };
  1641. addLink((0,_utils__WEBPACK_IMPORTED_MODULE_3__.getAssetUrl)("external/github.png"), _constants__WEBPACK_IMPORTED_MODULE_1__.scriptInfo.namespace, `${_constants__WEBPACK_IMPORTED_MODULE_1__.scriptInfo.name} on GitHub`);
  1642. addLink((0,_utils__WEBPACK_IMPORTED_MODULE_3__.getAssetUrl)("external/greasyfork.png"), "https://greasyfork.org/xyz", `${_constants__WEBPACK_IMPORTED_MODULE_1__.scriptInfo.name} on GreasyFork`);
  1643. const closeElem = document.createElement("img");
  1644. closeElem.id = "betterytm-menu-close";
  1645. closeElem.src = (0,_utils__WEBPACK_IMPORTED_MODULE_3__.getAssetUrl)("close.png");
  1646. closeElem.title = "Click to close the menu";
  1647. closeElem.style.marginLeft = "50px";
  1648. closeElem.style.width = "32px";
  1649. closeElem.style.height = "32px";
  1650. closeElem.addEventListener("click", closeMenu);
  1651. linksCont.appendChild(closeElem);
  1652. titleCont.appendChild(titleElem);
  1653. titleCont.appendChild(linksCont);
  1654. //#SECTION feature list
  1655. const featuresCont = document.createElement("div");
  1656. featuresCont.id = "betterytm-menu-opts";
  1657. featuresCont.style.display = "flex";
  1658. featuresCont.style.flexDirection = "column";
  1659. featuresCont.style.overflowY = "auto";
  1660. /** Gets called whenever the feature config is changed */
  1661. const confChanged = (key, initialVal, newVal) => __awaiter(this, void 0, void 0, function* () {
  1662. const fmt = (val) => typeof val === "object" ? JSON.stringify(val) : String(val);
  1663. (0,_utils__WEBPACK_IMPORTED_MODULE_3__.info)(`Feature config changed, key '${key}' from value '${fmt(initialVal)}' to '${fmt(newVal)}'`);
  1664. const featConf = Object.assign({}, yield (0,_config__WEBPACK_IMPORTED_MODULE_0__.getFeatures)());
  1665. featConf[key] = newVal;
  1666. yield (0,_config__WEBPACK_IMPORTED_MODULE_0__.saveFeatureConf)(featConf);
  1667. (0,_utils__WEBPACK_IMPORTED_MODULE_3__.log)("Saved feature config changes:\n", yield GM.getValue("betterytm-config"));
  1668. });
  1669. const features = yield (0,_config__WEBPACK_IMPORTED_MODULE_0__.getFeatures)();
  1670. for (const key in features) {
  1671. const ftInfo = _index__WEBPACK_IMPORTED_MODULE_2__.featInfo[key];
  1672. // @ts-ignore
  1673. if (!ftInfo || ftInfo.visible === false)
  1674. continue;
  1675. const { desc, type, default: ftDefault } = ftInfo;
  1676. // @ts-ignore
  1677. const step = (_a = ftInfo === null || ftInfo === void 0 ? void 0 : ftInfo.step) !== null && _a !== void 0 ? _a : undefined;
  1678. const val = features[key];
  1679. const initialVal = (_b = val !== null && val !== void 0 ? val : ftDefault) !== null && _b !== void 0 ? _b : undefined;
  1680. const ftConfElem = document.createElement("div");
  1681. ftConfElem.id = `betterytm-ftconf-${key}`;
  1682. ftConfElem.style.display = "flex";
  1683. ftConfElem.style.flexDirection = "row";
  1684. ftConfElem.style.justifyContent = "space-between";
  1685. ftConfElem.style.padding = "8px 20px";
  1686. {
  1687. const textElem = document.createElement("span");
  1688. textElem.style.display = "inline-block";
  1689. textElem.style.fontSize = "15px";
  1690. textElem.innerText = desc;
  1691. ftConfElem.appendChild(textElem);
  1692. }
  1693. {
  1694. let inputType = "text";
  1695. switch (type) {
  1696. case "toggle":
  1697. inputType = "checkbox";
  1698. break;
  1699. case "slider":
  1700. inputType = "range";
  1701. break;
  1702. case "number":
  1703. inputType = "number";
  1704. break;
  1705. }
  1706. const inputElemId = `betterytm-ftconf-${key}-input`;
  1707. const ctrlElem = document.createElement("span");
  1708. ctrlElem.style.display = "inline-block";
  1709. ctrlElem.style.whiteSpace = "nowrap";
  1710. const inputElem = document.createElement("input");
  1711. inputElem.id = inputElemId;
  1712. inputElem.type = inputType;
  1713. if (type === "toggle")
  1714. inputElem.style.marginLeft = "5px";
  1715. if (typeof initialVal !== "undefined")
  1716. inputElem.value = String(initialVal);
  1717. if (type === "number" && step)
  1718. inputElem.step = step;
  1719. // @ts-ignore
  1720. if (ftInfo.min && ftInfo.max) {
  1721. // @ts-ignore
  1722. inputElem.min = ftInfo.min;
  1723. // @ts-ignore
  1724. inputElem.max = ftInfo.max;
  1725. }
  1726. if (type === "toggle" && typeof initialVal !== "undefined")
  1727. inputElem.checked = Boolean(initialVal);
  1728. // @ts-ignore
  1729. const unitTxt = typeof ftInfo.unit === "string" ? " " + ftInfo.unit : "";
  1730. const fmtVal = (v) => String(v).trim();
  1731. const toggleLabelText = (toggled) => toggled ? "On" : "Off";
  1732. let labelElem;
  1733. if (type === "slider") {
  1734. labelElem = document.createElement("label");
  1735. labelElem.classList.add("betterytm-ftconf-label");
  1736. labelElem.style.marginRight = "20px";
  1737. labelElem.style.fontSize = "16px";
  1738. labelElem.htmlFor = inputElemId;
  1739. labelElem.innerText = fmtVal(initialVal) + unitTxt;
  1740. inputElem.addEventListener("input", () => {
  1741. if (labelElem)
  1742. labelElem.innerText = fmtVal(parseInt(inputElem.value)) + unitTxt;
  1743. });
  1744. }
  1745. else if (type === "toggle") {
  1746. labelElem = document.createElement("label");
  1747. labelElem.classList.add("betterytm-ftconf-label");
  1748. labelElem.style.paddingLeft = "10px";
  1749. labelElem.style.paddingRight = "5px";
  1750. labelElem.style.fontSize = "16px";
  1751. labelElem.htmlFor = inputElemId;
  1752. labelElem.innerText = toggleLabelText(Boolean(initialVal)) + unitTxt;
  1753. inputElem.addEventListener("input", () => {
  1754. if (labelElem)
  1755. labelElem.innerText = toggleLabelText(inputElem.checked) + unitTxt;
  1756. });
  1757. }
  1758. inputElem.addEventListener("input", () => {
  1759. let v = Number(String(inputElem.value).trim());
  1760. if (isNaN(v))
  1761. v = Number(inputElem.value);
  1762. if (typeof initialVal !== "undefined")
  1763. confChanged(key, initialVal, (type !== "toggle" ? v : inputElem.checked));
  1764. });
  1765. labelElem && ctrlElem.appendChild(labelElem);
  1766. ctrlElem.appendChild(inputElem);
  1767. ftConfElem.appendChild(ctrlElem);
  1768. }
  1769. featuresCont.appendChild(ftConfElem);
  1770. }
  1771. //#SECTION footer
  1772. const footerCont = document.createElement("div");
  1773. footerCont.id = "betterytm-menu-footer-cont";
  1774. footerCont.style.display = "flex";
  1775. footerCont.style.flexDirection = "row";
  1776. footerCont.style.justifyContent = "space-between";
  1777. footerCont.style.padding = "10px 20px";
  1778. footerCont.style.marginTop = "20px";
  1779. footerCont.style.position = "sticky";
  1780. footerCont.style.bottom = "0";
  1781. footerCont.style.backgroundColor = "var(--bytm-menu-bg)";
  1782. const footerElem = document.createElement("div");
  1783. footerElem.id = "betterytm-menu-footer";
  1784. footerElem.style.fontSize = "17px";
  1785. footerElem.style.textDecoration = "underline";
  1786. footerElem.innerText = "You need to reload the page to apply changes.";
  1787. const reloadElem = document.createElement("button");
  1788. reloadElem.style.marginLeft = "20px";
  1789. reloadElem.innerText = "Reload now";
  1790. reloadElem.title = "Click to reload the page";
  1791. reloadElem.addEventListener("click", () => location.reload());
  1792. const resetElem = document.createElement("button");
  1793. resetElem.className = "bytm-cfg-reset-btn";
  1794. resetElem.title = "Click to reset all settings to their default value";
  1795. resetElem.innerText = "Reset";
  1796. resetElem.addEventListener("click", () => __awaiter(this, void 0, void 0, function* () {
  1797. if (confirm("Do you really want to reset all settings to their default value?\nThe page will automatically reload if you proceed.")) {
  1798. yield (0,_config__WEBPACK_IMPORTED_MODULE_0__.setDefaultFeatConf)();
  1799. location.reload();
  1800. }
  1801. }));
  1802. footerElem.appendChild(reloadElem);
  1803. footerCont.appendChild(footerElem);
  1804. footerCont.appendChild(resetElem);
  1805. featuresCont.appendChild(footerCont);
  1806. //#SECTION finalize
  1807. const menuBody = document.createElement("div");
  1808. menuBody.id = "betterytm-menu-body";
  1809. menuBody.appendChild(titleCont);
  1810. menuBody.appendChild(featuresCont);
  1811. const versionCont = document.createElement("div");
  1812. versionCont.style.display = "flex";
  1813. versionCont.style.justifyContent = "space-around";
  1814. versionCont.style.fontSize = "1.15em";
  1815. versionCont.style.marginTop = "10px";
  1816. versionCont.style.marginBottom = "5px";
  1817. const versionElem = document.createElement("span");
  1818. versionElem.id = "betterytm-menu-version";
  1819. versionElem.innerText = `v${_constants__WEBPACK_IMPORTED_MODULE_1__.scriptInfo.version}`;
  1820. versionCont.appendChild(versionElem);
  1821. featuresCont.appendChild(versionCont);
  1822. menuContainer.appendChild(menuBody);
  1823. menuContainer.appendChild(versionCont);
  1824. backgroundElem.appendChild(menuContainer);
  1825. document.body.appendChild(backgroundElem);
  1826. (0,_utils__WEBPACK_IMPORTED_MODULE_3__.log)("Added menu elem:", backgroundElem);
  1827. });
  1828. }
  1829. //#MARKER utilities
  1830. function closeMenu(e) {
  1831. if (!isMenuOpen)
  1832. return;
  1833. isMenuOpen = false;
  1834. (e === null || e === void 0 ? void 0 : e.bubbles) && e.stopPropagation();
  1835. document.body.classList.remove("bytm-disable-scroll");
  1836. const menuBg = document.querySelector("#betterytm-menu-bg");
  1837. menuBg.style.visibility = "hidden";
  1838. menuBg.style.display = "none";
  1839. }
  1840. // function that opens the menu, it should do the inverse of closeMenu()
  1841. function openMenu() {
  1842. if (isMenuOpen)
  1843. return;
  1844. isMenuOpen = true;
  1845. document.body.classList.add("bytm-disable-scroll");
  1846. const menuBg = document.querySelector("#betterytm-menu-bg");
  1847. menuBg.style.visibility = "visible";
  1848. menuBg.style.display = "block";
  1849. }
  1850. /***/ }),
  1851. /***/ "./src/utils.ts":
  1852. /*!**********************!*\
  1853. !*** ./src/utils.ts ***!
  1854. \**********************/
  1855. /***/ (function(__unused_webpack_module, __webpack_exports__, __webpack_require__) {
  1856. __webpack_require__.r(__webpack_exports__);
  1857. /* harmony export */ __webpack_require__.d(__webpack_exports__, {
  1858. /* harmony export */ addGlobalStyle: function() { return /* binding */ addGlobalStyle; },
  1859. /* harmony export */ addParent: function() { return /* binding */ addParent; },
  1860. /* harmony export */ autoPlural: function() { return /* binding */ autoPlural; },
  1861. /* harmony export */ clamp: function() { return /* binding */ clamp; },
  1862. /* harmony export */ dbg: function() { return /* binding */ dbg; },
  1863. /* harmony export */ error: function() { return /* binding */ error; },
  1864. /* harmony export */ fetchAdvanced: function() { return /* binding */ fetchAdvanced; },
  1865. /* harmony export */ getAssetUrl: function() { return /* binding */ getAssetUrl; },
  1866. /* harmony export */ getDomain: function() { return /* binding */ getDomain; },
  1867. /* harmony export */ getUnsafeWindow: function() { return /* binding */ getUnsafeWindow; },
  1868. /* harmony export */ getVideoTime: function() { return /* binding */ getVideoTime; },
  1869. /* harmony export */ info: function() { return /* binding */ info; },
  1870. /* harmony export */ initSelectorExistsCheck: function() { return /* binding */ initSelectorExistsCheck; },
  1871. /* harmony export */ insertAfter: function() { return /* binding */ insertAfter; },
  1872. /* harmony export */ log: function() { return /* binding */ log; },
  1873. /* harmony export */ onSelectorExists: function() { return /* binding */ onSelectorExists; },
  1874. /* harmony export */ openInNewTab: function() { return /* binding */ openInNewTab; },
  1875. /* harmony export */ pauseFor: function() { return /* binding */ pauseFor; },
  1876. /* harmony export */ precacheImages: function() { return /* binding */ precacheImages; },
  1877. /* harmony export */ setLogLevel: function() { return /* binding */ setLogLevel; },
  1878. /* harmony export */ warn: function() { return /* binding */ warn; }
  1879. /* harmony export */ });
  1880. /* harmony import */ var _constants__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./constants */ "./src/constants.ts");
  1881. var __awaiter = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) {
  1882. function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
  1883. return new (P || (P = Promise))(function (resolve, reject) {
  1884. function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
  1885. function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
  1886. function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
  1887. step((generator = generator.apply(thisArg, _arguments || [])).next());
  1888. });
  1889. };
  1890. //#SECTION logging
  1891. let curLogLevel = 1;
  1892. /** Sets the current log level. 0 = Debug, 1 = Info */
  1893. function setLogLevel(level) {
  1894. curLogLevel = level;
  1895. }
  1896. /** Extracts the log level from the last item from spread arguments - returns 1 if the last item is not a number or too low or high */
  1897. function getLogLevel(args) {
  1898. const minLogLvl = 0, maxLogLvl = 1;
  1899. if (typeof args.at(-1) === "number")
  1900. return clamp(args.splice(args.length - 1)[0], minLogLvl, maxLogLvl);
  1901. return 0;
  1902. }
  1903. /** Common prefix to be able to tell logged messages apart and filter them in devtools */
  1904. const consPrefix = `[${_constants__WEBPACK_IMPORTED_MODULE_0__.scriptInfo.name}]`;
  1905. const consPrefixDbg = `[${_constants__WEBPACK_IMPORTED_MODULE_0__.scriptInfo.name}/#DEBUG]`;
  1906. /**
  1907. * Logs string-compatible values to the console, as long as the log level is sufficient.
  1908. * @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.
  1909. */
  1910. function log(...args) {
  1911. if (curLogLevel <= getLogLevel(args))
  1912. console.log(consPrefix, ...args);
  1913. }
  1914. /**
  1915. * Logs string-compatible values to the console as info, as long as the log level is sufficient.
  1916. * @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.
  1917. */
  1918. function info(...args) {
  1919. if (curLogLevel <= getLogLevel(args))
  1920. console.info(consPrefix, ...args);
  1921. }
  1922. /**
  1923. * Logs string-compatible values to the console as a warning, as long as the log level is sufficient.
  1924. * @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.
  1925. */
  1926. function warn(...args) {
  1927. if (curLogLevel <= getLogLevel(args))
  1928. console.warn(consPrefix, ...args);
  1929. }
  1930. /** Logs string-compatible values to the console as an error, no matter the log level. */
  1931. function error(...args) {
  1932. console.error(consPrefix, ...args);
  1933. }
  1934. /** Logs string-compatible values to the console, intended for debugging only */
  1935. function dbg(...args) {
  1936. console.log(consPrefixDbg, ...args);
  1937. }
  1938. //#SECTION video time
  1939. /**
  1940. * Returns the current video time in seconds
  1941. * Dispatches mouse movement events in case the video time can't be estimated
  1942. * @returns Returns null if the video time is unavailable
  1943. */
  1944. function getVideoTime() {
  1945. return new Promise((res) => {
  1946. const domain = getDomain();
  1947. try {
  1948. if (domain === "ytm") {
  1949. const pbEl = document.querySelector("#progress-bar");
  1950. return res(!isNaN(Number(pbEl.value)) ? Number(pbEl.value) : null);
  1951. }
  1952. else if (domain === "yt") {
  1953. // YT doesn't update the progress bar when it's hidden (contrary to YTM which never hides it)
  1954. ytForceShowVideoTime();
  1955. const pbSelector = ".ytp-chrome-bottom div.ytp-progress-bar[role=\"slider\"]";
  1956. const progElem = document.querySelector(pbSelector);
  1957. let videoTime = progElem ? Number(progElem.getAttribute("aria-valuenow")) : -1;
  1958. const mut = new MutationObserver(() => {
  1959. // .observe() is only called when the element exists - no need to check for null
  1960. videoTime = Number(document.querySelector(pbSelector).getAttribute("aria-valuenow"));
  1961. });
  1962. const observe = (progElem) => {
  1963. mut.observe(progElem, {
  1964. attributes: true,
  1965. attributeFilter: ["aria-valuenow"],
  1966. });
  1967. setTimeout(() => {
  1968. res(videoTime >= 0 && !isNaN(videoTime) ? videoTime : null);
  1969. }, 500);
  1970. };
  1971. if (!progElem)
  1972. return onSelectorExists(pbSelector, observe);
  1973. else
  1974. return observe(progElem);
  1975. // Possible solution:
  1976. // - Use MutationObserver to detect when attributes of progress bar (selector `div.ytp-progress-bar[role="slider"]`) change
  1977. // - Wait until the attribute increments, then save the value of `aria-valuenow` and the current system time to memory
  1978. // - When site switch hotkey is pressed, take saved `aria-valuenow` value and add the difference between saved system time and current system time
  1979. // - If no value is present, use the script from `dev/ytForceShowVideoTime.js` to simulate mouse movement to force the element to update
  1980. // - Subtract one or two seconds to make up for rounding errors
  1981. // - profit
  1982. // if(!ytCurrentVideoTime) {
  1983. // ytForceShowVideoTime();
  1984. // const videoTime = document.querySelector("#TODO")?.getAttribute("aria-valuenow") ?? null;
  1985. // }
  1986. }
  1987. }
  1988. catch (err) {
  1989. error("Couldn't get video time due to error:", err);
  1990. res(null);
  1991. }
  1992. });
  1993. }
  1994. /**
  1995. * Sends events that force the video controls to become visible for about 3 seconds.
  1996. * This only works once, then the page needs to be reloaded!
  1997. */
  1998. function ytForceShowVideoTime() {
  1999. const player = document.querySelector("#movie_player");
  2000. if (!player)
  2001. return false;
  2002. const defaultProps = {
  2003. // needed because otherwise YTM errors out - see https://github.com/Sv443/BetterYTM/issues/18#show_issue
  2004. view: getUnsafeWindow(),
  2005. bubbles: true,
  2006. cancelable: false,
  2007. };
  2008. player.dispatchEvent(new MouseEvent("mouseenter", defaultProps));
  2009. const { x, y, width, height } = player.getBoundingClientRect();
  2010. const screenY = Math.round(y + height / 2);
  2011. const screenX = x + Math.min(50, Math.round(width / 3));
  2012. player.dispatchEvent(new MouseEvent("mousemove", Object.assign(Object.assign({}, defaultProps), { screenY,
  2013. screenX, movementX: 5, movementY: 0 })));
  2014. return true;
  2015. }
  2016. // /** 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 */
  2017. // function parseVideoTime(videoTime: string) {
  2018. // const matches = /^((\d{1,2}):)?(\d{1,2}):(\d{2})$/.exec(videoTime);
  2019. // if(!matches)
  2020. // return 0;
  2021. // const [, , hrs, min, sec] = matches as unknown as [string, string | undefined, string | undefined, string, string];
  2022. // let finalTime = 0;
  2023. // if(hrs)
  2024. // finalTime += Number(hrs) * 60 * 60;
  2025. // finalTime += Number(min) * 60 + Number(sec);
  2026. // return isNaN(finalTime) ? 0 : finalTime;
  2027. // }
  2028. //#SECTION DOM
  2029. /**
  2030. * Inserts `afterNode` as a sibling just after the provided `beforeNode`
  2031. * @returns Returns the `afterNode`
  2032. */
  2033. function insertAfter(beforeNode, afterNode) {
  2034. var _a;
  2035. (_a = beforeNode.parentNode) === null || _a === void 0 ? void 0 : _a.insertBefore(afterNode, beforeNode.nextSibling);
  2036. return afterNode;
  2037. }
  2038. /** Adds a parent container around the provided element - returns the new parent node */
  2039. function addParent(element, newParent) {
  2040. const oldParent = element.parentNode;
  2041. if (!oldParent)
  2042. throw new Error("Element doesn't have a parent node");
  2043. oldParent.replaceChild(newParent, element);
  2044. newParent.appendChild(element);
  2045. return newParent;
  2046. }
  2047. /**
  2048. * Adds global CSS style through a `<style>` element in the document's `<head>`
  2049. * @param style CSS string
  2050. * @param ref Reference name that is included in the `<style>`'s ID - prefixed with `betterytm-style-` - defaults to a random number if left undefined
  2051. */
  2052. function addGlobalStyle(style, ref) {
  2053. if (typeof ref !== "string" || ref.length === 0)
  2054. ref = String(Math.floor(Math.random() * 10000));
  2055. const styleElem = document.createElement("style");
  2056. styleElem.id = `betterytm-style-${ref}`;
  2057. styleElem.innerHTML = style;
  2058. document.head.appendChild(styleElem);
  2059. log(`Inserted global style with ref '${ref}':`, styleElem);
  2060. }
  2061. const selectorExistsMap = new Map();
  2062. /**
  2063. * Calls the `listener` as soon as the `selector` exists in the DOM.
  2064. * Listeners are deleted as soon as they are called once.
  2065. * Multiple listeners with the same selector may be registered.
  2066. */
  2067. function onSelectorExists(selector, listener) {
  2068. const el = document.querySelector(selector);
  2069. if (el)
  2070. listener(el);
  2071. else {
  2072. if (selectorExistsMap.get(selector))
  2073. selectorExistsMap.set(selector, [...selectorExistsMap.get(selector), listener]);
  2074. else
  2075. selectorExistsMap.set(selector, [listener]);
  2076. }
  2077. }
  2078. /** Initializes the MutationObserver responsible for checking selectors registered in `onSelectorExists()` */
  2079. function initSelectorExistsCheck() {
  2080. const observer = new MutationObserver(() => {
  2081. for (const [selector, listeners] of selectorExistsMap.entries()) {
  2082. const el = document.querySelector(selector);
  2083. if (el) {
  2084. listeners.forEach(listener => listener(el));
  2085. selectorExistsMap.delete(selector);
  2086. }
  2087. }
  2088. });
  2089. observer.observe(document.body, {
  2090. subtree: true,
  2091. childList: true,
  2092. });
  2093. log("Initialized \"selector exists\" MutationObserver");
  2094. }
  2095. /** Preloads an array of image URLs so they can be loaded instantly from cache later on */
  2096. function precacheImages(srcUrls, rejects = false) {
  2097. const promises = srcUrls.map(src => new Promise((res, rej) => {
  2098. const image = new Image();
  2099. image.src = src;
  2100. image.addEventListener("load", () => res(image));
  2101. image.addEventListener("error", () => rejects && rej(`Failed to preload image with URL '${src}'`));
  2102. }));
  2103. return Promise.allSettled(promises);
  2104. }
  2105. /** Calls the fetch API with special options */
  2106. function fetchAdvanced(url, options = {}) {
  2107. return __awaiter(this, void 0, void 0, function* () {
  2108. const { timeout = 10000 } = options;
  2109. const controller = new AbortController();
  2110. const id = setTimeout(() => controller.abort(), timeout);
  2111. const res = yield fetch(url, Object.assign(Object.assign({}, options), { signal: controller.signal }));
  2112. clearTimeout(id);
  2113. return res;
  2114. });
  2115. }
  2116. /**
  2117. * Creates an invisible anchor with _blank target and clicks it.
  2118. * This has to be run in relatively quick succession to a user interaction event, else the browser rejects it.
  2119. */
  2120. function openInNewTab(href) {
  2121. try {
  2122. const openElem = document.createElement("a");
  2123. Object.assign(openElem, {
  2124. className: "betterytm-open-in-new-tab",
  2125. target: "_blank",
  2126. rel: "noopener noreferrer",
  2127. href,
  2128. });
  2129. openElem.style.visibility = "hidden";
  2130. document.body.appendChild(openElem);
  2131. openElem.click();
  2132. // timeout just to be safe
  2133. setTimeout(() => openElem.remove(), 200);
  2134. }
  2135. catch (err) {
  2136. error("Couldn't open URL in a new tab due to an error:", err);
  2137. }
  2138. }
  2139. /**
  2140. * Returns `unsafeWindow` if it is available, otherwise falls back to just `window`
  2141. * unsafeWindow is sometimes needed because otherwise YTM errors out - see [this issue](https://github.com/Sv443/BetterYTM/issues/18#show_issue)
  2142. */
  2143. function getUnsafeWindow() {
  2144. try {
  2145. // throws ReferenceError if the "@grant unsafeWindow" isn't present
  2146. return unsafeWindow;
  2147. }
  2148. catch (e) {
  2149. return window;
  2150. }
  2151. }
  2152. /**
  2153. * Returns the current domain as a constant string representation
  2154. * @throws Throws if script runs on an unexpected website
  2155. */
  2156. function getDomain() {
  2157. const { hostname } = new URL(location.href);
  2158. if (hostname.includes("music.youtube"))
  2159. return "ytm";
  2160. else if (hostname.includes("youtube"))
  2161. return "yt";
  2162. else
  2163. throw new Error("BetterYTM is running on an unexpected website. Please don't tamper with the @match directives in the userscript header.");
  2164. }
  2165. /** Returns the URL of the asset hosted on GitHub at the specified relative `path` (starting at `{root}/assets/`) */
  2166. function getAssetUrl(path) {
  2167. return `https://raw.githubusercontent.com/Sv443/BetterYTM/${_constants__WEBPACK_IMPORTED_MODULE_0__.branch}/assets/${path}`;
  2168. }
  2169. /**
  2170. * Automatically appends an `s` to the passed `word`, if `num` is not equal to 1
  2171. * @param word A word in singular form, to auto-convert to plural
  2172. * @param num If this is an array, the amount of items is used
  2173. */
  2174. function autoPlural(word, num) {
  2175. if (Array.isArray(num))
  2176. num = num.length;
  2177. return `${word}${num === 1 ? "" : "s"}`;
  2178. }
  2179. /** Ensures the passed `value` always stays between `min` and `max` */
  2180. function clamp(value, min, max) {
  2181. return Math.max(Math.min(value, max), min);
  2182. }
  2183. /** Pauses async execution for the specified time in ms */
  2184. function pauseFor(time) {
  2185. return new Promise((res) => {
  2186. setTimeout(res, time);
  2187. });
  2188. }
  2189. /***/ })
  2190. /******/ });
  2191. /************************************************************************/
  2192. /******/ // The module cache
  2193. /******/ var __webpack_module_cache__ = {};
  2194. /******/
  2195. /******/ // The require function
  2196. /******/ function __webpack_require__(moduleId) {
  2197. /******/ // Check if module is in cache
  2198. /******/ var cachedModule = __webpack_module_cache__[moduleId];
  2199. /******/ if (cachedModule !== undefined) {
  2200. /******/ return cachedModule.exports;
  2201. /******/ }
  2202. /******/ // Create a new module (and put it into the cache)
  2203. /******/ var module = __webpack_module_cache__[moduleId] = {
  2204. /******/ // no module.id needed
  2205. /******/ // no module.loaded needed
  2206. /******/ exports: {}
  2207. /******/ };
  2208. /******/
  2209. /******/ // Execute the module function
  2210. /******/ __webpack_modules__[moduleId](module, module.exports, __webpack_require__);
  2211. /******/
  2212. /******/ // Return the exports of the module
  2213. /******/ return module.exports;
  2214. /******/ }
  2215. /******/
  2216. /************************************************************************/
  2217. /******/ /* webpack/runtime/define property getters */
  2218. /******/ !function() {
  2219. /******/ // define getter functions for harmony exports
  2220. /******/ __webpack_require__.d = function(exports, definition) {
  2221. /******/ for(var key in definition) {
  2222. /******/ if(__webpack_require__.o(definition, key) && !__webpack_require__.o(exports, key)) {
  2223. /******/ Object.defineProperty(exports, key, { enumerable: true, get: definition[key] });
  2224. /******/ }
  2225. /******/ }
  2226. /******/ };
  2227. /******/ }();
  2228. /******/
  2229. /******/ /* webpack/runtime/hasOwnProperty shorthand */
  2230. /******/ !function() {
  2231. /******/ __webpack_require__.o = function(obj, prop) { return Object.prototype.hasOwnProperty.call(obj, prop); }
  2232. /******/ }();
  2233. /******/
  2234. /******/ /* webpack/runtime/make namespace object */
  2235. /******/ !function() {
  2236. /******/ // define __esModule on exports
  2237. /******/ __webpack_require__.r = function(exports) {
  2238. /******/ if(typeof Symbol !== 'undefined' && Symbol.toStringTag) {
  2239. /******/ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
  2240. /******/ }
  2241. /******/ Object.defineProperty(exports, '__esModule', { value: true });
  2242. /******/ };
  2243. /******/ }();
  2244. /******/
  2245. /************************************************************************/
  2246. var __webpack_exports__ = {};
  2247. // This entry need to be wrapped in an IIFE because it need to be isolated against other modules in the chunk.
  2248. !function() {
  2249. /*!**********************!*\
  2250. !*** ./src/index.ts ***!
  2251. \**********************/
  2252. __webpack_require__.r(__webpack_exports__);
  2253. /* harmony import */ var _config__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./config */ "./src/config.ts");
  2254. /* harmony import */ var _constants__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./constants */ "./src/constants.ts");
  2255. /* harmony import */ var _utils__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./utils */ "./src/utils.ts");
  2256. /* harmony import */ var _events__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./events */ "./src/events.ts");
  2257. /* harmony import */ var _features_index__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./features/index */ "./src/features/index.ts");
  2258. var __awaiter = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) {
  2259. function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
  2260. return new (P || (P = Promise))(function (resolve, reject) {
  2261. function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
  2262. function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
  2263. function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
  2264. step((generator = generator.apply(thisArg, _arguments || [])).next());
  2265. });
  2266. };
  2267. /** URLs of images to pre-cache so they can be displayed instantly */
  2268. const precacheImgs = [
  2269. (0,_utils__WEBPACK_IMPORTED_MODULE_2__.getAssetUrl)("spinner.svg"),
  2270. (0,_utils__WEBPACK_IMPORTED_MODULE_2__.getAssetUrl)("delete.svg"),
  2271. (0,_utils__WEBPACK_IMPORTED_MODULE_2__.getAssetUrl)("external/genius.png"),
  2272. ];
  2273. {
  2274. // console watermark with sexy gradient
  2275. 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%);";
  2276. const styleCommon = "color: #fff; font-size: 1.25em; padding: 4px 6px;";
  2277. console.log();
  2278. console.log(`%c${_constants__WEBPACK_IMPORTED_MODULE_1__.scriptInfo.name}%cv${_constants__WEBPACK_IMPORTED_MODULE_1__.scriptInfo.version}%c\n\nBuild #${_constants__WEBPACK_IMPORTED_MODULE_1__.scriptInfo.lastCommit} ─ ${_constants__WEBPACK_IMPORTED_MODULE_1__.scriptInfo.namespace}`, `font-weight: bold; ${styleCommon} ${styleGradient}`, `background-color: #333; ${styleCommon}`, "padding: initial;");
  2279. console.log(`─ Powered by lots of ambition and my song metadata API: ${_features_index__WEBPACK_IMPORTED_MODULE_4__.geniUrlBase} ─`);
  2280. console.log();
  2281. }
  2282. const domain = (0,_utils__WEBPACK_IMPORTED_MODULE_2__.getDomain)();
  2283. /** Stuff that needs to be called ASAP, before anything async happens */
  2284. function preInit() {
  2285. (0,_utils__WEBPACK_IMPORTED_MODULE_2__.setLogLevel)(_constants__WEBPACK_IMPORTED_MODULE_1__.logLevel);
  2286. if (domain === "ytm")
  2287. (0,_features_index__WEBPACK_IMPORTED_MODULE_4__.initBeforeUnloadHook)();
  2288. init();
  2289. }
  2290. function init() {
  2291. return __awaiter(this, void 0, void 0, function* () {
  2292. yield (0,_features_index__WEBPACK_IMPORTED_MODULE_4__.preInitLayout)();
  2293. try {
  2294. document.addEventListener("DOMContentLoaded", onDomLoad);
  2295. if (domain === "ytm")
  2296. (0,_utils__WEBPACK_IMPORTED_MODULE_2__.precacheImages)(precacheImgs)
  2297. .then(() => (0,_utils__WEBPACK_IMPORTED_MODULE_2__.log)(`Pre-cached ${precacheImgs.length} images`))
  2298. .catch((e) => (0,_utils__WEBPACK_IMPORTED_MODULE_2__.error)(`Pre-caching error: ${e}`));
  2299. }
  2300. catch (err) {
  2301. console.error(`${_constants__WEBPACK_IMPORTED_MODULE_1__.scriptInfo.name} - General Error:`, err);
  2302. }
  2303. try {
  2304. void ["TODO(v1.1):", _features_index__WEBPACK_IMPORTED_MODULE_4__.initMenu];
  2305. // initMenu();
  2306. }
  2307. catch (err) {
  2308. (0,_utils__WEBPACK_IMPORTED_MODULE_2__.error)("Couldn't initialize menu:", err);
  2309. }
  2310. });
  2311. }
  2312. /** Called when the DOM has finished loading and can be queried and altered by the userscript */
  2313. function onDomLoad() {
  2314. return __awaiter(this, void 0, void 0, function* () {
  2315. // post-build these double quotes are replaced by backticks (if backticks are used here, webpack converts them to double quotes)
  2316. (0,_utils__WEBPACK_IMPORTED_MODULE_2__.addGlobalStyle)(`/*!**********************************************************************************!*\
  2317. !*** css ./node_modules/css-loader/dist/cjs.js!./src/features/menu/menu_old.css ***!
  2318. \**********************************************************************************/
  2319. :root {
  2320. --bytm-menu-bg: #212121;
  2321. }
  2322. #betterytm-menu-bg {
  2323. display: block;
  2324. position: fixed;
  2325. width: 100vw;
  2326. height: 100vh;
  2327. top: 0;
  2328. left: 0;
  2329. z-index: 15;
  2330. background-color: rgba(0, 0, 0, 0.6);
  2331. }
  2332. #betterytm-menu {
  2333. display: inline-block;
  2334. position: fixed;
  2335. width: 50vw;
  2336. height: auto;
  2337. left: 25vw;
  2338. top: 10vh;
  2339. z-index: 16;
  2340. padding: 10px 25px;
  2341. color: #fff;
  2342. background-color: var(--bytm-menu-bg);
  2343. }
  2344. #betterytm-menu-opts {
  2345. max-height: 70vh;
  2346. overflow: auto;
  2347. }
  2348. #betterytm-menu-titlecont {
  2349. display: flex;
  2350. }
  2351. #betterytm-menu-title {
  2352. font-size: 20px;
  2353. margin-top: 5px;
  2354. margin-bottom: 8px;
  2355. }
  2356. #betterytm-menu-linkscont {
  2357. display: flex;
  2358. }
  2359. .betterytm-menu-link {
  2360. display: inline-block;
  2361. }
  2362. #betterytm-menu-close {
  2363. cursor: pointer;
  2364. }
  2365. .betterytm-ftconf-label {
  2366. user-select: none;
  2367. }
  2368. body.bytm-disable-scroll {
  2369. overflow-y: hidden !important;
  2370. }
  2371. /*!***************************************************************************!*\
  2372. !*** css ./node_modules/css-loader/dist/cjs.js!./src/features/layout.css ***!
  2373. \***************************************************************************/
  2374. /* #MARKER misc */
  2375. .bytm-generic-btn {
  2376. display: inline-flex;
  2377. align-items: center;
  2378. justify-content: center;
  2379. position: relative;
  2380. vertical-align: middle;
  2381. cursor: pointer;
  2382. margin-left: 8px;
  2383. width: 40px;
  2384. height: 40px;
  2385. border-radius: 100%;
  2386. background-color: transparent;
  2387. }
  2388. .bytm-generic-btn:hover {
  2389. background-color: var(--yt-spec-10-percent-layer, #1d1d1d);
  2390. }
  2391. .bytm-generic-btn-img {
  2392. display: inline-block;
  2393. z-index: 10;
  2394. width: 24px;
  2395. height: 24px;
  2396. padding: 5px;
  2397. }
  2398. .bytm-spinner {
  2399. animation: rotate 1.5s linear infinite;
  2400. }
  2401. @keyframes rotate {
  2402. from {
  2403. transform: rotate(0deg);
  2404. }
  2405. to {
  2406. transform: rotate(360deg);
  2407. }
  2408. }
  2409. .bytm-anchor {
  2410. all: unset;
  2411. cursor: pointer;
  2412. }
  2413. /* #MARKER menu */
  2414. .bytm-cfg-menu-option {
  2415. display: block;
  2416. padding: 8px 0;
  2417. }
  2418. .bytm-cfg-menu-option-item {
  2419. display: flex;
  2420. flex-direction: row;
  2421. align-items: center;
  2422. font-size: 16px;
  2423. font-weight: 400;
  2424. line-height: 24px;
  2425. padding: var(--yt-compact-link-paper-item-padding, 0px 36px 0 16px);
  2426. min-height: var(--paper-item-min-height, 40px);
  2427. white-space: nowrap;
  2428. cursor: pointer;
  2429. }
  2430. .bytm-cfg-menu-option-item:hover {
  2431. background-color: var(--yt-spec-badge-chip-background, #3e3e3e);
  2432. }
  2433. .bytm-cfg-menu-option-icon {
  2434. width: 24px;
  2435. height: 24px;
  2436. margin-right: 16px;
  2437. display: flex;
  2438. align-items: center;
  2439. flex-direction: row;
  2440. flex: none;
  2441. }
  2442. .bytm-cfg-menu-option-text {
  2443. font-size: 1.4rem;
  2444. line-height: 2rem;
  2445. }
  2446. yt-multi-page-menu-section-renderer.ytd-multi-page-menu-renderer {
  2447. border-bottom: 1px solid var(--yt-spec-10-percent-layer, #3e3e3e);
  2448. }
  2449. /* #MARKER watermark */
  2450. #betterytm-watermark {
  2451. font-size: 10px;
  2452. display: inline-block;
  2453. position: absolute;
  2454. left: 97px;
  2455. top: 46px;
  2456. z-index: 10;
  2457. color: white;
  2458. text-decoration: none;
  2459. cursor: pointer;
  2460. }
  2461. #betterytm-watermark:hover {
  2462. text-decoration: underline;
  2463. }
  2464. /* #MARKER queue buttons */
  2465. .side-panel.modular ytmusic-player-queue-item .song-info.ytmusic-player-queue-item {
  2466. position: relative;
  2467. }
  2468. .side-panel.modular ytmusic-player-queue-item .bytm-queue-btn-container {
  2469. background: rgb(0, 0, 0);
  2470. background: linear-gradient(90deg, rgba(0, 0, 0, 0) 0%, rgba(0, 0, 0, 1) 15%);
  2471. display: none;
  2472. position: absolute;
  2473. right: 0;
  2474. padding-left: 25px;
  2475. }
  2476. .side-panel.modular ytmusic-player-queue-item:hover .bytm-queue-btn-container {
  2477. display: inline-block;
  2478. }
  2479. .side-panel.modular ytmusic-player-queue-item[play-button-state="loading"] .bytm-queue-btn-container,
  2480. .side-panel.modular ytmusic-player-queue-item[play-button-state="playing"] .bytm-queue-btn-container,
  2481. .side-panel.modular ytmusic-player-queue-item[play-button-state="paused"] .bytm-queue-btn-container {
  2482. /* using a var() is not viable since the nesting changes the actual value of the variable */
  2483. background: linear-gradient(90deg, rgba(0, 0, 0, 0) 0%, rgba(29, 29, 29, 1) 15%);
  2484. }
  2485. ytmusic-app ytmusic-popup-container tp-yt-iron-dropdown[data-bytm-hidden=true] {
  2486. display: none !important;
  2487. }
  2488. /* #MARKER anchor improvements */
  2489. ytmusic-responsive-list-item-renderer .left-items {
  2490. margin-right: 0 !important;
  2491. }
  2492. .bytm-carousel-shelf-anchor {
  2493. margin: 0 var(--ytmusic-responsive-list-item-thumbnail-margin-right, 16px) 0 0;
  2494. }
  2495. /*!******************************************************************************!*\
  2496. !*** css ./node_modules/css-loader/dist/cjs.js!./src/features/menu/menu.css ***!
  2497. \******************************************************************************/
  2498. /* #bytm-menu-backdrop {
  2499. display: none;
  2500. flex-direction: column;
  2501. justify-content: center;
  2502. align-items: center;
  2503. }
  2504. #bytm-menu-backdrop[data-menu-open="true"] {
  2505. display: flex;
  2506. } */
  2507. #bytm-menu-header-container {
  2508. display: flex;
  2509. justify-content: flex-start;
  2510. align-items: center;
  2511. border-color: #ffffff;
  2512. border-style: none solid none none;
  2513. }
  2514. .bytm-menu-header-option {
  2515. display: "flex";
  2516. justify-content: center;
  2517. align-items: center;
  2518. border-color: #ffffff;
  2519. border-style: solid none solid none;
  2520. }
  2521. #bytm-menu-header-option h3 {
  2522. margin: 0;
  2523. }
  2524. .bytm-menu-tab[data-active="true"] {
  2525. display: none;
  2526. }
  2527. .bytm-menu-tab[data-active="false"] {
  2528. display: none;
  2529. }
  2530. /*# sourceMappingURL=http://localhost:8710/main.css.map*/`, "global");
  2531. const features = yield (0,_config__WEBPACK_IMPORTED_MODULE_0__.loadFeatureConf)();
  2532. (0,_utils__WEBPACK_IMPORTED_MODULE_2__.initSelectorExistsCheck)();
  2533. (0,_utils__WEBPACK_IMPORTED_MODULE_2__.log)(`Initializing features for domain "${domain}"...`);
  2534. try {
  2535. if (domain === "ytm") {
  2536. try {
  2537. (0,_features_index__WEBPACK_IMPORTED_MODULE_4__.addMenu)(); // TODO(v1.1): remove
  2538. }
  2539. catch (err) {
  2540. (0,_utils__WEBPACK_IMPORTED_MODULE_2__.error)("Couldn't add menu:", err);
  2541. }
  2542. (0,_events__WEBPACK_IMPORTED_MODULE_3__.initSiteEvents)();
  2543. (0,_utils__WEBPACK_IMPORTED_MODULE_2__.onSelectorExists)("tp-yt-iron-dropdown #contentWrapper ytd-multi-page-menu-renderer #container.menu-container", _features_index__WEBPACK_IMPORTED_MODULE_4__.addConfigMenuOption);
  2544. if (features.arrowKeySupport)
  2545. (0,_features_index__WEBPACK_IMPORTED_MODULE_4__.initArrowKeySkip)();
  2546. if (features.removeUpgradeTab)
  2547. (0,_features_index__WEBPACK_IMPORTED_MODULE_4__.removeUpgradeTab)();
  2548. if (features.watermarkEnabled)
  2549. (0,_features_index__WEBPACK_IMPORTED_MODULE_4__.addWatermark)();
  2550. if (features.geniusLyrics)
  2551. (0,_features_index__WEBPACK_IMPORTED_MODULE_4__.addMediaCtrlLyricsBtn)();
  2552. if (features.queueButtons)
  2553. (0,_features_index__WEBPACK_IMPORTED_MODULE_4__.initQueueButtons)();
  2554. if (typeof features.volumeSliderSize === "number")
  2555. (0,_features_index__WEBPACK_IMPORTED_MODULE_4__.setVolSliderSize)();
  2556. if (features.anchorImprovements)
  2557. (0,_features_index__WEBPACK_IMPORTED_MODULE_4__.addAnchorImprovements)();
  2558. (0,_features_index__WEBPACK_IMPORTED_MODULE_4__.setVolSliderStep)();
  2559. }
  2560. if (["ytm", "yt"].includes(domain)) {
  2561. if (features.switchBetweenSites)
  2562. (0,_features_index__WEBPACK_IMPORTED_MODULE_4__.initSiteSwitch)(domain);
  2563. }
  2564. }
  2565. catch (err) {
  2566. (0,_utils__WEBPACK_IMPORTED_MODULE_2__.error)("General error while executing feature:", err);
  2567. }
  2568. });
  2569. }
  2570. preInit();
  2571. }();
  2572. //# sourceMappingURL=http://localhost:8710/BetterYTM.user.js.map