BetterYTM.user.js 96 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145
  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. // @match https://music.youtube.com/*
  12. // @match https://www.youtube.com/*
  13. // @icon https://raw.githubusercontent.com/Sv443/BetterYTM/main/assets/icon/icon.png
  14. // @run-at document-start
  15. // @grant GM.getValue
  16. // @grant GM.setValue
  17. // @grant unsafeWindow
  18. // @connect self
  19. // @connect youtube.com
  20. // @connect github.com
  21. // @connect githubusercontent.com
  22. // @downloadURL https://raw.githubusercontent.com/Sv443/BetterYTM/main/dist/BetterYTM.user.js
  23. // @updateURL https://raw.githubusercontent.com/Sv443/BetterYTM/main/dist/BetterYTM.user.js
  24. // ==/UserScript==
  25. /*
  26. ▄▄▄ ▄ ▄▄▄▄▄▄ ▄
  27. █ █ ▄▄▄ █ █ ▄▄▄ ▄ ▄█ █ █ █▀▄▀█
  28. █▀▀▄ █▄█ █▀ █▀ █▄█ █▀ █ █ █ █
  29. █▄▄▀ ▀▄▄ ▀▄▄ ▀▄▄ ▀▄▄ █ █ █ █ █
  30. Made with ❤️ by Sv443
  31. I welcome every contribution on GitHub!
  32. https://github.com/Sv443/BetterYTM
  33. */
  34. /* Disclaimer: I am not affiliated with YouTube, Google, Alphabet, Genius or anyone else */
  35. /* C&D this 🖕 */
  36. /******/ var __webpack_modules__ = ({
  37. /***/ "./node_modules/@billjs/event-emitter/lib/index.js":
  38. /*!*********************************************************!*\
  39. !*** ./node_modules/@billjs/event-emitter/lib/index.js ***!
  40. \*********************************************************/
  41. /***/ (function(__unused_webpack_module, exports) {
  42. /**
  43. * A simple and lightweight EventEmitter by TypeScript for Node.js or Browsers.
  44. *
  45. * @author billjs
  46. * @see https://github.com/billjs/event-emitter
  47. * @license MIT(https://opensource.org/licenses/MIT)
  48. */
  49. Object.defineProperty(exports, "__esModule", ({ value: true }));
  50. /**
  51. * It's a class for managing events.
  52. * It can be extended to provide event functionality for other classes or object.
  53. *
  54. * @export
  55. * @class EventEmitter
  56. */
  57. var EventEmitter = /** @class */ (function () {
  58. function EventEmitter() {
  59. /**
  60. * the all event handlers are added.
  61. * it's a Map data structure(key-value), the key is event type, and the value is event handler.
  62. *
  63. * @memberof EventEmitter
  64. */
  65. this._eventHandlers = {};
  66. }
  67. /**
  68. * event type validator.
  69. *
  70. * @param {string} type event type
  71. * @returns {boolean}
  72. * @memberof EventEmitter
  73. */
  74. EventEmitter.prototype.isValidType = function (type) {
  75. return typeof type === 'string';
  76. };
  77. /**
  78. * event handler validator.
  79. *
  80. * @param {EventHandler} handler event handler
  81. * @returns {boolean}
  82. * @memberof EventEmitter
  83. */
  84. EventEmitter.prototype.isValidHandler = function (handler) {
  85. return typeof handler === 'function';
  86. };
  87. /**
  88. * listen on a new event by type and handler.
  89. * if listen on, the true is returned, otherwise the false.
  90. * The handler will not be listen if it is a duplicate.
  91. *
  92. * @param {string} type event type, it must be a unique string.
  93. * @param {EventHandler} handler event handler, when if the same handler is passed, listen it by only once.
  94. * @returns {boolean}
  95. * @memberof EventEmitter
  96. * @example
  97. * const emitter = new EventEmitter();
  98. * emitter.on('change:name', evt => {
  99. * console.log(evt);
  100. * });
  101. */
  102. EventEmitter.prototype.on = function (type, handler) {
  103. if (!type || !handler)
  104. return false;
  105. if (!this.isValidType(type))
  106. return false;
  107. if (!this.isValidHandler(handler))
  108. return false;
  109. var handlers = this._eventHandlers[type];
  110. if (!handlers)
  111. handlers = this._eventHandlers[type] = [];
  112. // when the same handler is passed, listen it by only once.
  113. if (handlers.indexOf(handler) >= 0)
  114. return false;
  115. handler._once = false;
  116. handlers.push(handler);
  117. return true;
  118. };
  119. /**
  120. * listen on an once event by type and handler.
  121. * when the event is fired, that will be listen off immediately and automatically.
  122. * The handler will not be listen if it is a duplicate.
  123. *
  124. * @param {string} type event type, it must be a unique string.
  125. * @param {EventHandler} handler event handler, when if the same handler is passed, listen it by only once.
  126. * @returns {boolean}
  127. * @memberof EventEmitter
  128. * @example
  129. * const emitter = new EventEmitter();
  130. * emitter.once('change:name', evt => {
  131. * console.log(evt);
  132. * });
  133. */
  134. EventEmitter.prototype.once = function (type, handler) {
  135. if (!type || !handler)
  136. return false;
  137. if (!this.isValidType(type))
  138. return false;
  139. if (!this.isValidHandler(handler))
  140. return false;
  141. var ret = this.on(type, handler);
  142. if (ret) {
  143. // set `_once` private property after listened,
  144. // avoid to modify event handler that has been listened.
  145. handler._once = true;
  146. }
  147. return ret;
  148. };
  149. /**
  150. * listen off an event by type and handler.
  151. * or listen off events by type, when if only type argument is passed.
  152. * or listen off all events, when if no arguments are passed.
  153. *
  154. * @param {string} [type] event type
  155. * @param {EventHandler} [handler] event handler
  156. * @returns
  157. * @memberof EventEmitter
  158. * @example
  159. * const emitter = new EventEmitter();
  160. * // listen off the specified event
  161. * emitter.off('change:name', evt => {
  162. * console.log(evt);
  163. * });
  164. * // listen off events by type
  165. * emitter.off('change:name');
  166. * // listen off all events
  167. * emitter.off();
  168. */
  169. EventEmitter.prototype.off = function (type, handler) {
  170. // listen off all events, when if no arguments are passed.
  171. // it does samething as `offAll` method.
  172. if (!type)
  173. return this.offAll();
  174. // listen off events by type, when if only type argument is passed.
  175. if (!handler) {
  176. this._eventHandlers[type] = [];
  177. return;
  178. }
  179. if (!this.isValidType(type))
  180. return;
  181. if (!this.isValidHandler(handler))
  182. return;
  183. var handlers = this._eventHandlers[type];
  184. if (!handlers || !handlers.length)
  185. return;
  186. // otherwise, listen off the specified event.
  187. for (var i = 0; i < handlers.length; i++) {
  188. var fn = handlers[i];
  189. if (fn === handler) {
  190. handlers.splice(i, 1);
  191. break;
  192. }
  193. }
  194. };
  195. /**
  196. * listen off all events, that means every event will be emptied.
  197. *
  198. * @memberof EventEmitter
  199. * @example
  200. * const emitter = new EventEmitter();
  201. * emitter.offAll();
  202. */
  203. EventEmitter.prototype.offAll = function () {
  204. this._eventHandlers = {};
  205. };
  206. /**
  207. * fire the specified event, and you can to pass a data.
  208. * When fired, every handler attached to that event will be executed.
  209. * But, if it's an once event, listen off it immediately after called handler.
  210. *
  211. * @param {string} type event type
  212. * @param {*} [data] event data
  213. * @returns
  214. * @memberof EventEmitter
  215. * @example
  216. * const emitter = new EventEmitter();
  217. * emitter.fire('change:name', 'new name');
  218. */
  219. EventEmitter.prototype.fire = function (type, data) {
  220. if (!type || !this.isValidType(type))
  221. return;
  222. var handlers = this._eventHandlers[type];
  223. if (!handlers || !handlers.length)
  224. return;
  225. var event = this.createEvent(type, data);
  226. for (var _i = 0, handlers_1 = handlers; _i < handlers_1.length; _i++) {
  227. var handler = handlers_1[_i];
  228. if (!this.isValidHandler(handler))
  229. continue;
  230. if (handler._once)
  231. event.once = true;
  232. // call event handler, and pass the event argument.
  233. handler(event);
  234. // if it's an once event, listen off it immediately after called handler.
  235. if (event.once)
  236. this.off(type, handler);
  237. }
  238. };
  239. /**
  240. * check whether the specified event has been listen on.
  241. * or check whether the events by type has been listen on, when if only `type` argument is passed.
  242. *
  243. * @param {string} type event type
  244. * @param {EventHandler} [handler] event handler, optional
  245. * @returns {boolean}
  246. * @memberof EventEmitter
  247. * @example
  248. * const emitter = new EventEmitter();
  249. * const result = emitter.has('change:name');
  250. */
  251. EventEmitter.prototype.has = function (type, handler) {
  252. if (!type || !this.isValidType(type))
  253. return false;
  254. var handlers = this._eventHandlers[type];
  255. // if there are no any events, return false.
  256. if (!handlers || !handlers.length)
  257. return false;
  258. // at lest one event, and no pass `handler` argument, then return true.
  259. if (!handler || !this.isValidHandler(handler))
  260. return true;
  261. // otherwise, need to traverse the handlers.
  262. return handlers.indexOf(handler) >= 0;
  263. };
  264. /**
  265. * get the handlers for the specified event type.
  266. *
  267. * @param {string} type event type
  268. * @returns {EventHandler[]}
  269. * @memberof EventEmitter
  270. * @example
  271. * const emitter = new EventEmitter();
  272. * const handlers = emitter.getHandlers('change:name');
  273. * console.log(handlers);
  274. */
  275. EventEmitter.prototype.getHandlers = function (type) {
  276. if (!type || !this.isValidType(type))
  277. return [];
  278. return this._eventHandlers[type] || [];
  279. };
  280. /**
  281. * create event object.
  282. *
  283. * @param {string} type event type
  284. * @param {*} [data] event data
  285. * @param {boolean} [once=false] is it an once event?
  286. * @returns {Event}
  287. * @memberof EventEmitter
  288. */
  289. EventEmitter.prototype.createEvent = function (type, data, once) {
  290. if (once === void 0) { once = false; }
  291. var event = { type: type, data: data, timestamp: Date.now(), once: once };
  292. return event;
  293. };
  294. return EventEmitter;
  295. }());
  296. exports.EventEmitter = EventEmitter;
  297. /**
  298. * EventEmitter instance for global.
  299. * @type {EventEmitter}
  300. */
  301. exports.globalEvent = new EventEmitter();
  302. /***/ }),
  303. /***/ "./changelog.md":
  304. /*!**********************!*\
  305. !*** ./changelog.md ***!
  306. \**********************/
  307. /***/ (function(__unused_webpack_module, __webpack_exports__, __webpack_require__) {
  308. __webpack_require__.r(__webpack_exports__);
  309. // Module
  310. 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<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>TODO: 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>TODO: 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";
  311. // Exports
  312. /* harmony default export */ __webpack_exports__["default"] = (code);
  313. /***/ }),
  314. /***/ "./src/features/menu/menu.html":
  315. /*!*************************************!*\
  316. !*** ./src/features/menu/menu.html ***!
  317. \*************************************/
  318. /***/ (function(__unused_webpack_module, __webpack_exports__, __webpack_require__) {
  319. __webpack_require__.r(__webpack_exports__);
  320. // Module
  321. 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";
  322. // Exports
  323. /* harmony default export */ __webpack_exports__["default"] = (code);
  324. /***/ }),
  325. /***/ "./src/features/layout.css":
  326. /*!*********************************!*\
  327. !*** ./src/features/layout.css ***!
  328. \*********************************/
  329. /***/ (function(__unused_webpack_module, __webpack_exports__, __webpack_require__) {
  330. __webpack_require__.r(__webpack_exports__);
  331. // extracted by mini-css-extract-plugin
  332. /***/ }),
  333. /***/ "./src/features/lyrics.css":
  334. /*!*********************************!*\
  335. !*** ./src/features/lyrics.css ***!
  336. \*********************************/
  337. /***/ (function(__unused_webpack_module, __webpack_exports__, __webpack_require__) {
  338. __webpack_require__.r(__webpack_exports__);
  339. // extracted by mini-css-extract-plugin
  340. /***/ }),
  341. /***/ "./src/features/menu/menu.css":
  342. /*!************************************!*\
  343. !*** ./src/features/menu/menu.css ***!
  344. \************************************/
  345. /***/ (function(__unused_webpack_module, __webpack_exports__, __webpack_require__) {
  346. __webpack_require__.r(__webpack_exports__);
  347. // extracted by mini-css-extract-plugin
  348. /***/ }),
  349. /***/ "./src/config.ts":
  350. /*!***********************!*\
  351. !*** ./src/config.ts ***!
  352. \***********************/
  353. /***/ (function(__unused_webpack_module, __webpack_exports__, __webpack_require__) {
  354. __webpack_require__.r(__webpack_exports__);
  355. /* harmony export */ __webpack_require__.d(__webpack_exports__, {
  356. /* harmony export */ defaultFeatures: function() { return /* binding */ defaultFeatures; },
  357. /* harmony export */ getFeatures: function() { return /* binding */ getFeatures; },
  358. /* harmony export */ loadFeatureConf: function() { return /* binding */ loadFeatureConf; },
  359. /* harmony export */ saveFeatureConf: function() { return /* binding */ saveFeatureConf; },
  360. /* harmony export */ setDefaultFeatConf: function() { return /* binding */ setDefaultFeatConf; }
  361. /* harmony export */ });
  362. /* harmony import */ var _features_index__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./features/index */ "./src/features/index.ts");
  363. /* harmony import */ var _utils__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./utils */ "./src/utils.ts");
  364. var __awaiter = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) {
  365. function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
  366. return new (P || (P = Promise))(function (resolve, reject) {
  367. function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
  368. function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
  369. function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
  370. step((generator = generator.apply(thisArg, _arguments || [])).next());
  371. });
  372. };
  373. /** If this number is incremented, the features object needs to be migrated (TODO: migration not implemented yet) */
  374. const formatVersion = 1;
  375. const defaultFeatures = Object.keys(_features_index__WEBPACK_IMPORTED_MODULE_0__.featInfo)
  376. .reduce((acc, key) => {
  377. acc[key] = _features_index__WEBPACK_IMPORTED_MODULE_0__.featInfo[key].default;
  378. return acc;
  379. }, {});
  380. /** In-memory features object to save on a little bit of I/O */
  381. let featuresCache;
  382. /**
  383. * Returns the current FeatureConfig in memory or reads it from GM storage
  384. * Automatically applies defaults for non-existant keys
  385. * @param forceRead Set to true to force reading the config from GM storage
  386. */
  387. function getFeatures(forceRead = false) {
  388. return __awaiter(this, void 0, void 0, function* () {
  389. if (featuresCache === undefined || forceRead)
  390. yield saveFeatureConf(featuresCache = Object.assign(Object.assign({}, defaultFeatures), yield loadFeatureConf())); // look at this sexy one liner
  391. return featuresCache;
  392. });
  393. }
  394. /** Loads a feature configuration saved persistently, returns an empty object if no feature configuration was saved */
  395. function loadFeatureConf() {
  396. return __awaiter(this, void 0, void 0, function* () {
  397. const defConf = Object.assign({}, defaultFeatures);
  398. try {
  399. const featureConf = yield GM.getValue("betterytm-config");
  400. if (typeof featureConf !== "string") {
  401. yield setDefaultFeatConf();
  402. return featuresCache = defConf;
  403. }
  404. return featuresCache = Object.freeze(featureConf ? JSON.parse(featureConf) : defConf);
  405. }
  406. catch (err) {
  407. yield setDefaultFeatConf();
  408. return featuresCache = defConf;
  409. }
  410. });
  411. }
  412. /**
  413. * Saves the passed feature configuration persistently in GM storage and in the in-memory cache
  414. * @param featureConf
  415. */
  416. function saveFeatureConf(featureConf) {
  417. if (!featureConf || typeof featureConf != "object")
  418. throw new TypeError("Feature config not provided or invalid");
  419. (0,_utils__WEBPACK_IMPORTED_MODULE_1__.log)("Saving new feature config:", featureConf);
  420. featuresCache = Object.assign({}, featureConf);
  421. GM.setValue("betterytm-config-ver", formatVersion);
  422. return GM.setValue("betterytm-config", JSON.stringify(featureConf));
  423. }
  424. /** Resets the featuresCache synchronously and the persistent features storage asynchronously to its default values */
  425. function setDefaultFeatConf() {
  426. featuresCache = Object.assign({}, defaultFeatures);
  427. GM.setValue("betterytm-config-ver", formatVersion);
  428. return GM.setValue("betterytm-config", JSON.stringify(defaultFeatures));
  429. }
  430. /***/ }),
  431. /***/ "./src/constants.ts":
  432. /*!**************************!*\
  433. !*** ./src/constants.ts ***!
  434. \**************************/
  435. /***/ (function(__unused_webpack_module, __webpack_exports__, __webpack_require__) {
  436. __webpack_require__.r(__webpack_exports__);
  437. /* harmony export */ __webpack_require__.d(__webpack_exports__, {
  438. /* harmony export */ branch: function() { return /* binding */ branch; },
  439. /* harmony export */ logLevel: function() { return /* binding */ logLevel; },
  440. /* harmony export */ scriptInfo: function() { return /* binding */ scriptInfo; },
  441. /* harmony export */ triesInterval: function() { return /* binding */ triesInterval; },
  442. /* harmony export */ triesLimit: function() { return /* binding */ triesLimit; }
  443. /* harmony export */ });
  444. /** The branch to use in the @icon, @downloadURL and @updateURL directives */
  445. const branch = "develop"; // TODO: change in prod.
  446. // export const branch = "main";
  447. /**
  448. * How much info should be logged to the devtools console?
  449. * 0 = Debug (show everything) or 1 = Info (show only important stuff)
  450. */
  451. const logLevel = 0; // TODO: change in prod.
  452. /** Specifies the hard limit for repetitive tasks */
  453. const triesLimit = 50;
  454. /** Specifies the interval in ms for repetitive tasks */
  455. const triesInterval = 200;
  456. /** Info about the userscript, parsed from the userscript header (tools/post-build.js) */
  457. const scriptInfo = Object.freeze({
  458. name: GM.info.script.name,
  459. version: GM.info.script.version,
  460. namespace: GM.info.script.namespace,
  461. lastCommit: "7b3c32f", // assert as generic string instead of union
  462. });
  463. /***/ }),
  464. /***/ "./src/features/index.ts":
  465. /*!*******************************!*\
  466. !*** ./src/features/index.ts ***!
  467. \*******************************/
  468. /***/ (function(__unused_webpack_module, __webpack_exports__, __webpack_require__) {
  469. __webpack_require__.r(__webpack_exports__);
  470. /* harmony export */ __webpack_require__.d(__webpack_exports__, {
  471. /* harmony export */ addAnchorImprovements: function() { return /* reexport safe */ _layout__WEBPACK_IMPORTED_MODULE_2__.addAnchorImprovements; },
  472. /* harmony export */ addMediaCtrlLyricsBtn: function() { return /* reexport safe */ _lyrics__WEBPACK_IMPORTED_MODULE_3__.addMediaCtrlLyricsBtn; },
  473. /* harmony export */ addMenu: function() { return /* reexport safe */ _menu_menu_old__WEBPACK_IMPORTED_MODULE_5__.addMenu; },
  474. /* harmony export */ addWatermark: function() { return /* reexport safe */ _layout__WEBPACK_IMPORTED_MODULE_2__.addWatermark; },
  475. /* harmony export */ closeMenu: function() { return /* reexport safe */ _menu_menu_old__WEBPACK_IMPORTED_MODULE_5__.closeMenu; },
  476. /* harmony export */ disableBeforeUnload: function() { return /* reexport safe */ _input__WEBPACK_IMPORTED_MODULE_1__.disableBeforeUnload; },
  477. /* harmony export */ enableBeforeUnload: function() { return /* reexport safe */ _input__WEBPACK_IMPORTED_MODULE_1__.enableBeforeUnload; },
  478. /* harmony export */ featInfo: function() { return /* binding */ featInfo; },
  479. /* harmony export */ geniUrlBase: function() { return /* reexport safe */ _lyrics__WEBPACK_IMPORTED_MODULE_3__.geniUrlBase; },
  480. /* harmony export */ getCurrentLyricsUrl: function() { return /* reexport safe */ _lyrics__WEBPACK_IMPORTED_MODULE_3__.getCurrentLyricsUrl; },
  481. /* harmony export */ getGeniusUrl: function() { return /* reexport safe */ _lyrics__WEBPACK_IMPORTED_MODULE_3__.getGeniusUrl; },
  482. /* harmony export */ getLyricsBtn: function() { return /* reexport safe */ _lyrics__WEBPACK_IMPORTED_MODULE_3__.getLyricsBtn; },
  483. /* harmony export */ initArrowKeySkip: function() { return /* reexport safe */ _input__WEBPACK_IMPORTED_MODULE_1__.initArrowKeySkip; },
  484. /* harmony export */ initBeforeUnloadHook: function() { return /* reexport safe */ _input__WEBPACK_IMPORTED_MODULE_1__.initBeforeUnloadHook; },
  485. /* harmony export */ initMenu: function() { return /* reexport safe */ _menu_menu__WEBPACK_IMPORTED_MODULE_4__.initMenu; },
  486. /* harmony export */ initQueueButtons: function() { return /* reexport safe */ _layout__WEBPACK_IMPORTED_MODULE_2__.initQueueButtons; },
  487. /* harmony export */ initSiteSwitch: function() { return /* reexport safe */ _input__WEBPACK_IMPORTED_MODULE_1__.initSiteSwitch; },
  488. /* harmony export */ openMenu: function() { return /* reexport safe */ _menu_menu_old__WEBPACK_IMPORTED_MODULE_5__.openMenu; },
  489. /* harmony export */ preInitLayout: function() { return /* reexport safe */ _layout__WEBPACK_IMPORTED_MODULE_2__.preInitLayout; },
  490. /* harmony export */ removeUpgradeTab: function() { return /* reexport safe */ _layout__WEBPACK_IMPORTED_MODULE_2__.removeUpgradeTab; },
  491. /* harmony export */ sanitizeArtists: function() { return /* reexport safe */ _lyrics__WEBPACK_IMPORTED_MODULE_3__.sanitizeArtists; },
  492. /* harmony export */ sanitizeSong: function() { return /* reexport safe */ _lyrics__WEBPACK_IMPORTED_MODULE_3__.sanitizeSong; },
  493. /* harmony export */ setVolSliderSize: function() { return /* reexport safe */ _layout__WEBPACK_IMPORTED_MODULE_2__.setVolSliderSize; },
  494. /* harmony export */ setVolSliderStep: function() { return /* reexport safe */ _layout__WEBPACK_IMPORTED_MODULE_2__.setVolSliderStep; }
  495. /* harmony export */ });
  496. /* harmony import */ var _constants__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../constants */ "./src/constants.ts");
  497. /* harmony import */ var _input__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./input */ "./src/features/input.ts");
  498. /* harmony import */ var _layout__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./layout */ "./src/features/layout.ts");
  499. /* harmony import */ var _lyrics__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./lyrics */ "./src/features/lyrics.ts");
  500. /* harmony import */ var _menu_menu__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./menu/menu */ "./src/features/menu/menu.ts");
  501. /* harmony import */ var _menu_menu_old__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./menu/menu_old */ "./src/features/menu/menu_old.ts");
  502. // TODO
  503. /** Contains all possible features with their default values and other config */
  504. const featInfo = {
  505. //#SECTION input
  506. arrowKeySupport: {
  507. desc: "Arrow keys skip forwards and backwards by 10 seconds",
  508. type: "toggle",
  509. category: "input",
  510. default: true,
  511. },
  512. switchBetweenSites: {
  513. desc: "Add F9 as a hotkey to switch between the YT and YTM sites on a video / song",
  514. type: "toggle",
  515. category: "input",
  516. default: true,
  517. },
  518. switchSitesHotkey: {
  519. desc: "TODO: Which hotkey needs to be pressed to switch sites?",
  520. type: "hotkey",
  521. category: "input",
  522. default: {
  523. key: "F9",
  524. shift: false,
  525. ctrl: false,
  526. meta: false,
  527. },
  528. visible: false,
  529. },
  530. disableBeforeUnloadPopup: {
  531. desc: "Completely disable the popup that sometimes appears before leaving the site",
  532. type: "toggle",
  533. category: "input",
  534. default: false,
  535. },
  536. anchorImprovements: {
  537. desc: "TODO: Make it so middle clicking a song to open it in a new tab is easier",
  538. type: "toggle",
  539. category: "input",
  540. default: true,
  541. visible: false,
  542. },
  543. //#SECTION layout
  544. removeUpgradeTab: {
  545. desc: "Remove the \"Upgrade\" / YT Music Premium tab",
  546. type: "toggle",
  547. category: "layout",
  548. default: true,
  549. },
  550. volumeSliderSize: {
  551. desc: "The width of the volume slider in pixels",
  552. type: "number",
  553. category: "layout",
  554. min: 10,
  555. max: 1000,
  556. step: 5,
  557. default: 160,
  558. unit: "px",
  559. },
  560. volumeSliderStep: {
  561. desc: "Volume slider sensitivity - the smaller this number, the finer the volume control",
  562. type: "slider",
  563. category: "layout",
  564. min: 1,
  565. max: 20,
  566. default: 2,
  567. },
  568. watermarkEnabled: {
  569. desc: `Show a ${_constants__WEBPACK_IMPORTED_MODULE_0__.scriptInfo.name} watermark under the YTM logo`,
  570. type: "toggle",
  571. category: "layout",
  572. default: true,
  573. },
  574. queueButtons: {
  575. desc: "TODO: Add buttons while hovering over a song in a queue to quickly remove it or open its lyrics",
  576. type: "toggle",
  577. category: "layout",
  578. default: true,
  579. visible: false,
  580. },
  581. //#SECTION lyrics
  582. geniusLyrics: {
  583. desc: "Add a button to the media controls to open the current song's lyrics on genius.com in a new tab",
  584. type: "toggle",
  585. category: "lyrics",
  586. default: true,
  587. },
  588. };
  589. /***/ }),
  590. /***/ "./src/features/input.ts":
  591. /*!*******************************!*\
  592. !*** ./src/features/input.ts ***!
  593. \*******************************/
  594. /***/ (function(__unused_webpack_module, __webpack_exports__, __webpack_require__) {
  595. __webpack_require__.r(__webpack_exports__);
  596. /* harmony export */ __webpack_require__.d(__webpack_exports__, {
  597. /* harmony export */ disableBeforeUnload: function() { return /* binding */ disableBeforeUnload; },
  598. /* harmony export */ enableBeforeUnload: function() { return /* binding */ enableBeforeUnload; },
  599. /* harmony export */ initArrowKeySkip: function() { return /* binding */ initArrowKeySkip; },
  600. /* harmony export */ initBeforeUnloadHook: function() { return /* binding */ initBeforeUnloadHook; },
  601. /* harmony export */ initSiteSwitch: function() { return /* binding */ initSiteSwitch; }
  602. /* harmony export */ });
  603. /* harmony import */ var _utils__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../utils */ "./src/utils.ts");
  604. /* harmony import */ var _config__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../config */ "./src/config.ts");
  605. //#MARKER arrow key skip
  606. function initArrowKeySkip() {
  607. document.addEventListener("keydown", onKeyDown);
  608. (0,_utils__WEBPACK_IMPORTED_MODULE_0__.log)("Added key press listener");
  609. }
  610. /** Called when the user presses any key, anywhere */
  611. function onKeyDown(evt) {
  612. var _a, _b;
  613. if (["ArrowLeft", "ArrowRight"].includes(evt.code)) {
  614. // discard the event when a (text) input is currently active, like when editing a playlist
  615. if (["INPUT", "TEXTAREA", "SELECT"].includes((_b = (_a = document.activeElement) === null || _a === void 0 ? void 0 : _a.tagName) !== null && _b !== void 0 ? _b : "_"))
  616. 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`);
  617. (0,_utils__WEBPACK_IMPORTED_MODULE_0__.log)(`Captured key '${evt.code}' in proxy listener`);
  618. // 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
  619. const defaultProps = {
  620. altKey: false,
  621. ctrlKey: false,
  622. metaKey: false,
  623. shiftKey: false,
  624. target: document.body,
  625. currentTarget: document.body,
  626. originalTarget: document.body,
  627. explicitOriginalTarget: document.body,
  628. srcElement: document.body,
  629. type: "keydown",
  630. bubbles: true,
  631. cancelBubble: false,
  632. cancelable: true,
  633. isTrusted: true,
  634. repeat: false,
  635. // needed because otherwise YTM errors out - see https://github.com/Sv443/BetterYTM/issues/18#show_issue
  636. view: unsafeWindow !== null && unsafeWindow !== void 0 ? unsafeWindow : window,
  637. };
  638. let invalidKey = false;
  639. let keyProps = {};
  640. switch (evt.code) {
  641. case "ArrowLeft":
  642. keyProps = {
  643. code: "KeyH",
  644. key: "h",
  645. keyCode: 72,
  646. which: 72,
  647. };
  648. break;
  649. case "ArrowRight":
  650. keyProps = {
  651. code: "KeyL",
  652. key: "l",
  653. keyCode: 76,
  654. which: 76,
  655. };
  656. break;
  657. default:
  658. invalidKey = true;
  659. break;
  660. }
  661. if (!invalidKey) {
  662. const proxyProps = Object.assign(Object.assign({ code: "" }, defaultProps), keyProps);
  663. document.body.dispatchEvent(new KeyboardEvent("keydown", proxyProps));
  664. (0,_utils__WEBPACK_IMPORTED_MODULE_0__.log)(`Dispatched proxy keydown event: [${evt.code}] -> [${proxyProps.code}]`);
  665. }
  666. else
  667. (0,_utils__WEBPACK_IMPORTED_MODULE_0__.warn)(`Captured key '${evt.code}' has no defined behavior`);
  668. }
  669. }
  670. //#MARKER site switch
  671. /** Initializes the site switch feature */
  672. function initSiteSwitch(domain) {
  673. // TODO:
  674. // extra features:
  675. // - keep video time
  676. // - configurable hotkey
  677. document.addEventListener("keydown", (e) => {
  678. if (e.key === "F9")
  679. switchSite(domain === "yt" ? "ytm" : "yt");
  680. });
  681. (0,_utils__WEBPACK_IMPORTED_MODULE_0__.log)("Initialized site switch listener");
  682. }
  683. /** Switches to the other site (between YT and YTM) */
  684. function switchSite(newDomain) {
  685. var _a;
  686. try {
  687. let subdomain;
  688. if (newDomain === "ytm")
  689. subdomain = "music";
  690. else if (newDomain === "yt")
  691. subdomain = "www";
  692. if (!subdomain)
  693. throw new TypeError(`Unrecognized domain '${newDomain}'`);
  694. const { pathname, search, hash } = new URL(location.href);
  695. const vt = (_a = (0,_utils__WEBPACK_IMPORTED_MODULE_0__.getVideoTime)()) !== null && _a !== void 0 ? _a : 0;
  696. (0,_utils__WEBPACK_IMPORTED_MODULE_0__.log)(`Found video time of ${vt} seconds`);
  697. const newSearch = search.includes("?") ? `${search}&t=${vt}` : `?t=${vt}`;
  698. const url = `https://${subdomain}.youtube.com${pathname}${newSearch}${hash}`;
  699. console.info(`BetterYTM - switching to domain '${newDomain}' at ${url}`);
  700. disableBeforeUnload();
  701. location.assign(url);
  702. }
  703. catch (err) {
  704. (0,_utils__WEBPACK_IMPORTED_MODULE_0__.error)("Error while switching site:", err);
  705. }
  706. }
  707. //#MARKER beforeunload popup
  708. let beforeUnloadEnabled = true;
  709. /** Disables the popup before leaving the site */
  710. function disableBeforeUnload() {
  711. beforeUnloadEnabled = false;
  712. (0,_utils__WEBPACK_IMPORTED_MODULE_0__.info)("Disabled popup before leaving the site");
  713. }
  714. /** (Re-)enables the popup before leaving the site */
  715. function enableBeforeUnload() {
  716. beforeUnloadEnabled = true;
  717. (0,_utils__WEBPACK_IMPORTED_MODULE_0__.info)("Enabled popup before leaving the site");
  718. }
  719. /**
  720. * Adds a spy function into `window.__proto__.addEventListener` to selectively discard beforeunload event listeners before they can be attached by the site
  721. */
  722. function initBeforeUnloadHook() {
  723. Error.stackTraceLimit = Infinity;
  724. (function (original) {
  725. // @ts-ignore
  726. window.__proto__.addEventListener = function (...args) {
  727. if (beforeUnloadEnabled && args[0] === "beforeunload")
  728. return (0,_utils__WEBPACK_IMPORTED_MODULE_0__.log)("Prevented beforeunload event listener from attaching");
  729. else
  730. return original.apply(this, args);
  731. };
  732. // @ts-ignore
  733. })(window.__proto__.addEventListener);
  734. (0,_config__WEBPACK_IMPORTED_MODULE_1__.getFeatures)().then(feats => {
  735. if (feats.disableBeforeUnloadPopup)
  736. disableBeforeUnload();
  737. });
  738. // (function(original) {
  739. // window.__proto__.removeEventListener = function(type, listener, useCapture) {
  740. // if(evtNames.includes(type)){
  741. // console.log("------> removeEventListener " + type, listener, useCapture);
  742. // }
  743. // return original.apply(this, arguments);
  744. // };
  745. // })(window.__proto__.removeEventListener);
  746. }
  747. /***/ }),
  748. /***/ "./src/features/layout.ts":
  749. /*!********************************!*\
  750. !*** ./src/features/layout.ts ***!
  751. \********************************/
  752. /***/ (function(__unused_webpack_module, __webpack_exports__, __webpack_require__) {
  753. __webpack_require__.r(__webpack_exports__);
  754. /* harmony export */ __webpack_require__.d(__webpack_exports__, {
  755. /* harmony export */ addAnchorImprovements: function() { return /* binding */ addAnchorImprovements; },
  756. /* harmony export */ addWatermark: function() { return /* binding */ addWatermark; },
  757. /* harmony export */ initQueueButtons: function() { return /* binding */ initQueueButtons; },
  758. /* harmony export */ preInitLayout: function() { return /* binding */ preInitLayout; },
  759. /* harmony export */ removeUpgradeTab: function() { return /* binding */ removeUpgradeTab; },
  760. /* harmony export */ setVolSliderSize: function() { return /* binding */ setVolSliderSize; },
  761. /* harmony export */ setVolSliderStep: function() { return /* binding */ setVolSliderStep; }
  762. /* harmony export */ });
  763. /* harmony import */ var _constants__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../constants */ "./src/constants.ts");
  764. /* harmony import */ var _config__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../config */ "./src/config.ts");
  765. /* harmony import */ var _utils__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../utils */ "./src/utils.ts");
  766. /* harmony import */ var _menu_menu_old__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./menu/menu_old */ "./src/features/menu/menu_old.ts");
  767. /* harmony import */ var _layout_css__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./layout.css */ "./src/features/layout.css");
  768. /* harmony import */ var _lyrics__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./lyrics */ "./src/features/lyrics.ts");
  769. var __awaiter = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) {
  770. function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
  771. return new (P || (P = Promise))(function (resolve, reject) {
  772. function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
  773. function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
  774. function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
  775. step((generator = generator.apply(thisArg, _arguments || [])).next());
  776. });
  777. };
  778. let features;
  779. function preInitLayout() {
  780. return __awaiter(this, void 0, void 0, function* () {
  781. features = yield (0,_config__WEBPACK_IMPORTED_MODULE_1__.getFeatures)();
  782. });
  783. }
  784. //#MARKER watermark
  785. /** Adds a watermark beneath the logo */
  786. function addWatermark() {
  787. const watermark = document.createElement("a");
  788. watermark.role = "button";
  789. watermark.id = "betterytm-watermark";
  790. watermark.className = "style-scope ytmusic-nav-bar";
  791. watermark.innerText = _constants__WEBPACK_IMPORTED_MODULE_0__.scriptInfo.name;
  792. watermark.title = "Open menu";
  793. watermark.tabIndex = 1000;
  794. watermark.addEventListener("click", () => (0,_menu_menu_old__WEBPACK_IMPORTED_MODULE_3__.openMenu)());
  795. watermark.addEventListener("keydown", (e) => e.key === "Enter" && (0,_menu_menu_old__WEBPACK_IMPORTED_MODULE_3__.openMenu)());
  796. const logoElem = document.querySelector("#left-content");
  797. (0,_utils__WEBPACK_IMPORTED_MODULE_2__.insertAfter)(logoElem, watermark);
  798. (0,_utils__WEBPACK_IMPORTED_MODULE_2__.log)("Added watermark element:", watermark);
  799. }
  800. //#MARKER remove upgrade tab
  801. let removeUpgradeTries = 0;
  802. /** Removes the "Upgrade" / YT Music Premium tab from the title / nav bar */
  803. function removeUpgradeTab() {
  804. const tabElem = document.querySelector(".ytmusic-nav-bar ytmusic-pivot-bar-item-renderer[tab-id=\"SPunlimited\"]");
  805. if (tabElem) {
  806. tabElem.remove();
  807. (0,_utils__WEBPACK_IMPORTED_MODULE_2__.log)(`Removed upgrade tab after ${removeUpgradeTries} tries`);
  808. }
  809. else if (removeUpgradeTries < _constants__WEBPACK_IMPORTED_MODULE_0__.triesLimit) {
  810. setTimeout(removeUpgradeTab, _constants__WEBPACK_IMPORTED_MODULE_0__.triesInterval); // TODO: improve this
  811. removeUpgradeTries++;
  812. }
  813. else
  814. (0,_utils__WEBPACK_IMPORTED_MODULE_2__.error)(`Couldn't find upgrade tab to remove after ${removeUpgradeTries} tries`);
  815. }
  816. //#MARKER volume slider
  817. /** Sets the volume slider to a set size */
  818. function setVolSliderSize() {
  819. const { volumeSliderSize: size } = features;
  820. if (typeof size !== "number" || isNaN(Number(size)))
  821. return;
  822. const style = `\
  823. .volume-slider.ytmusic-player-bar, .expand-volume-slider.ytmusic-player-bar {
  824. width: ${size}px !important;
  825. }`;
  826. (0,_utils__WEBPACK_IMPORTED_MODULE_2__.addGlobalStyle)(style, "vol-slider");
  827. }
  828. /** Sets the `step` attribute of the volume slider */
  829. function setVolSliderStep() {
  830. const sliderElem = document.querySelector("tp-yt-paper-slider#volume-slider");
  831. sliderElem.setAttribute("step", String(features.volumeSliderStep));
  832. }
  833. //#MARKER queue buttons
  834. // TODO: account for the fact initially the elements might not exist, if the site was not opened directly with a video playing or via the /watch path
  835. function initQueueButtons() {
  836. _utils__WEBPACK_IMPORTED_MODULE_2__.siteEvents.on("queueChanged", (evt) => {
  837. for (const queueItm of (0,_utils__WEBPACK_IMPORTED_MODULE_2__.getEvtData)(evt).childNodes) {
  838. if (!queueItm.classList.contains("bytm-has-queue-btns"))
  839. addQueueButtons(queueItm);
  840. }
  841. });
  842. const queueItems = document.querySelectorAll("#contents.ytmusic-player-queue > ytmusic-player-queue-item");
  843. if (queueItems.length === 0)
  844. return;
  845. queueItems.forEach(itm => addQueueButtons(itm));
  846. }
  847. /** For how long the user needs to hover over the song info to fetch the lyrics */
  848. const queueBtnLyricsLoadDebounce = 250;
  849. function addQueueButtons(queueItem) {
  850. return __awaiter(this, void 0, void 0, function* () {
  851. const queueBtnsCont = document.createElement("div");
  852. queueBtnsCont.className = "bytm-queue-btn-container";
  853. const songInfo = queueItem.querySelector(".song-info");
  854. if (!songInfo)
  855. return false;
  856. const [songEl, artistEl] = songInfo.querySelectorAll("yt-formatted-string");
  857. const song = songEl.innerText;
  858. const artist = artistEl.innerText;
  859. if (!song || !artist)
  860. return false;
  861. // TODO: display "hover to load" and "currently loading" icons
  862. const lyricsBtnElem = (0,_lyrics__WEBPACK_IMPORTED_MODULE_5__.getLyricsBtn)(undefined, false);
  863. // load the URL only on hover because of geniURL rate limiting
  864. songInfo.addEventListener("mouseenter", () => __awaiter(this, void 0, void 0, function* () {
  865. const startTs = Date.now();
  866. if (songInfo.classList.contains("bytm-fetched-lyrics-url"))
  867. return;
  868. /** Loads lyrics after `queueBtnLyricsLoadDebounce` time has passed - gets aborted if the mouse leaves before that time passed */
  869. const lyricsLoadTimeout = setTimeout(() => __awaiter(this, void 0, void 0, function* () {
  870. const lyricsUrl = yield (0,_lyrics__WEBPACK_IMPORTED_MODULE_5__.getGeniusUrl)((0,_lyrics__WEBPACK_IMPORTED_MODULE_5__.sanitizeArtists)(artist), (0,_lyrics__WEBPACK_IMPORTED_MODULE_5__.sanitizeSong)(song));
  871. if (!lyricsUrl)
  872. return false;
  873. songInfo.classList.add("bytm-fetched-lyrics-url");
  874. lyricsBtnElem.href = lyricsUrl;
  875. lyricsBtnElem.title = "Open the current song's lyrics in a new tab";
  876. lyricsBtnElem.style.cursor = "pointer";
  877. lyricsBtnElem.style.visibility = "initial";
  878. lyricsBtnElem.style.display = "inline-flex";
  879. lyricsBtnElem.style.pointerEvents = "initial";
  880. }), queueBtnLyricsLoadDebounce);
  881. songInfo.addEventListener("mouseleave", () => {
  882. if (Date.now() - startTs < queueBtnLyricsLoadDebounce) {
  883. clearTimeout(lyricsLoadTimeout);
  884. console.log("CLEAR", song);
  885. }
  886. });
  887. }));
  888. queueBtnsCont.appendChild(lyricsBtnElem);
  889. songInfo.appendChild(queueBtnsCont);
  890. queueItem.classList.add("bytm-has-queue-btns");
  891. (0,_utils__WEBPACK_IMPORTED_MODULE_2__.log)(`Added queue buttons for song '${artist} - ${song}'`, queueBtnsCont);
  892. return true;
  893. });
  894. }
  895. //#MARKER better clickable stuff
  896. // TODO: account for the fact initially the elements might not exist, if the site was opened directly with the /watch path
  897. function addAnchorImprovements() {
  898. void 0;
  899. }
  900. /***/ }),
  901. /***/ "./src/features/lyrics.ts":
  902. /*!********************************!*\
  903. !*** ./src/features/lyrics.ts ***!
  904. \********************************/
  905. /***/ (function(__unused_webpack_module, __webpack_exports__, __webpack_require__) {
  906. __webpack_require__.r(__webpack_exports__);
  907. /* harmony export */ __webpack_require__.d(__webpack_exports__, {
  908. /* harmony export */ addMediaCtrlLyricsBtn: function() { return /* binding */ addMediaCtrlLyricsBtn; },
  909. /* harmony export */ geniUrlBase: function() { return /* binding */ geniUrlBase; },
  910. /* harmony export */ getCurrentLyricsUrl: function() { return /* binding */ getCurrentLyricsUrl; },
  911. /* harmony export */ getGeniusUrl: function() { return /* binding */ getGeniusUrl; },
  912. /* harmony export */ getLyricsBtn: function() { return /* binding */ getLyricsBtn; },
  913. /* harmony export */ sanitizeArtists: function() { return /* binding */ sanitizeArtists; },
  914. /* harmony export */ sanitizeSong: function() { return /* binding */ sanitizeSong; }
  915. /* harmony export */ });
  916. /* harmony import */ var _constants__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../constants */ "./src/constants.ts");
  917. /* harmony import */ var _utils__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../utils */ "./src/utils.ts");
  918. /* harmony import */ var _lyrics_css__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./lyrics.css */ "./src/features/lyrics.css");
  919. var __awaiter = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) {
  920. function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
  921. return new (P || (P = Promise))(function (resolve, reject) {
  922. function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
  923. function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
  924. function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
  925. step((generator = generator.apply(thisArg, _arguments || [])).next());
  926. });
  927. };
  928. var __asyncValues = (undefined && undefined.__asyncValues) || function (o) {
  929. if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined.");
  930. var m = o[Symbol.asyncIterator], i;
  931. 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);
  932. 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); }); }; }
  933. function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); }
  934. };
  935. /** Base URL of geniURL */
  936. const geniUrlBase = "https://api.sv443.net/geniurl";
  937. /** GeniURL endpoint that gives song metadata when provided with a `?q` or `?artist` and `?song` parameter - [more info](https://api.sv443.net/geniurl) */
  938. const geniURLSearchTopUrl = `${geniUrlBase}/search/top`;
  939. let mcCurrentSongTitle = "";
  940. let mcLyricsButtonAddTries = 0;
  941. /** Adds a lyrics button to the media controls bar */
  942. function addMediaCtrlLyricsBtn() {
  943. const likeContainer = document.querySelector(".middle-controls-buttons ytmusic-like-button-renderer#like-button-renderer");
  944. if (!likeContainer) {
  945. mcLyricsButtonAddTries++;
  946. if (mcLyricsButtonAddTries < _constants__WEBPACK_IMPORTED_MODULE_0__.triesLimit) {
  947. setTimeout(addMediaCtrlLyricsBtn, _constants__WEBPACK_IMPORTED_MODULE_0__.triesInterval); // TODO: improve this
  948. return;
  949. }
  950. return (0,_utils__WEBPACK_IMPORTED_MODULE_1__.error)(`Couldn't find element to append lyrics buttons to after ${mcLyricsButtonAddTries} tries`);
  951. }
  952. const songTitleElem = document.querySelector(".content-info-wrapper > yt-formatted-string");
  953. // run parallel without awaiting so the MutationObserver below can observe the title element in time
  954. (() => __awaiter(this, void 0, void 0, function* () {
  955. const gUrl = yield getCurrentLyricsUrl();
  956. const linkElem = getLyricsBtn(gUrl !== null && gUrl !== void 0 ? gUrl : undefined);
  957. linkElem.id = "betterytm-lyrics-button";
  958. (0,_utils__WEBPACK_IMPORTED_MODULE_1__.log)(`Inserted lyrics button after ${mcLyricsButtonAddTries} tries:`, linkElem);
  959. (0,_utils__WEBPACK_IMPORTED_MODULE_1__.insertAfter)(likeContainer, linkElem);
  960. }))();
  961. mcCurrentSongTitle = songTitleElem.title;
  962. const onMutation = (mutations) => { var _a, mutations_1, mutations_1_1; return __awaiter(this, void 0, void 0, function* () {
  963. var _b, e_1, _c, _d;
  964. try {
  965. for (_a = true, mutations_1 = __asyncValues(mutations); mutations_1_1 = yield mutations_1.next(), _b = mutations_1_1.done, !_b;) {
  966. _d = mutations_1_1.value;
  967. _a = false;
  968. try {
  969. const mut = _d;
  970. const newTitle = mut.target.title;
  971. if (newTitle !== mcCurrentSongTitle && newTitle.length > 0) {
  972. const lyricsBtn = document.querySelector("#betterytm-lyrics-button");
  973. if (!lyricsBtn)
  974. return;
  975. (0,_utils__WEBPACK_IMPORTED_MODULE_1__.log)(`Song title changed from '${mcCurrentSongTitle}' to '${newTitle}'`);
  976. lyricsBtn.style.cursor = "wait";
  977. lyricsBtn.style.pointerEvents = "none";
  978. mcCurrentSongTitle = newTitle;
  979. const url = yield getCurrentLyricsUrl(); // can take a second or two
  980. if (!url)
  981. continue;
  982. lyricsBtn.href = url;
  983. lyricsBtn.title = "Open the current song's lyrics in a new tab";
  984. lyricsBtn.style.cursor = "pointer";
  985. lyricsBtn.style.visibility = "initial";
  986. lyricsBtn.style.display = "inline-flex";
  987. lyricsBtn.style.pointerEvents = "initial";
  988. }
  989. }
  990. finally {
  991. _a = true;
  992. }
  993. }
  994. }
  995. catch (e_1_1) { e_1 = { error: e_1_1 }; }
  996. finally {
  997. try {
  998. if (!_a && !_b && (_c = mutations_1.return)) yield _c.call(mutations_1);
  999. }
  1000. finally { if (e_1) throw e_1.error; }
  1001. }
  1002. }); };
  1003. // 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
  1004. const obs = new MutationObserver(onMutation);
  1005. obs.observe(songTitleElem, { attributes: true, attributeFilter: ["title"] });
  1006. }
  1007. /** Removes everything in parentheses from the passed song name */
  1008. function sanitizeSong(songName) {
  1009. const parensRegex = /\(.+\)/gmi;
  1010. const squareParensRegex = /\[.+\]/gmi;
  1011. // trim right after the song name:
  1012. const sanitized = songName
  1013. .replace(parensRegex, "")
  1014. .replace(squareParensRegex, "");
  1015. return sanitized.trim();
  1016. }
  1017. /** Removes the secondary artist (if it exists) from the passed artists string */
  1018. function sanitizeArtists(artists) {
  1019. artists = artists.split(/\s*\u2022\s*/gmiu)[0]; // split at &bull; [•] character
  1020. if (artists.match(/&/))
  1021. artists = artists.split(/\s*&\s*/gm)[0];
  1022. if (artists.match(/,/))
  1023. artists = artists.split(/,\s*/gm)[0];
  1024. return artists.trim();
  1025. }
  1026. /** Returns the lyrics URL from genius for the currently selected song */
  1027. function getCurrentLyricsUrl() {
  1028. var _a, _b;
  1029. return __awaiter(this, void 0, void 0, function* () {
  1030. try {
  1031. // In videos the video title contains both artist and song title, in "regular" YTM songs, the video title only contains the song title
  1032. const isVideo = typeof ((_a = document.querySelector("ytmusic-player")) === null || _a === void 0 ? void 0 : _a.getAttribute("video-mode_")) === "string";
  1033. const songTitleElem = document.querySelector(".content-info-wrapper > yt-formatted-string");
  1034. const songMetaElem = document.querySelector("span.subtitle > yt-formatted-string:first-child");
  1035. if (!songTitleElem || !songMetaElem || !songTitleElem.title)
  1036. return null;
  1037. const songNameRaw = songTitleElem.title;
  1038. const songName = sanitizeSong(songNameRaw);
  1039. const artistName = sanitizeArtists(songMetaElem.title);
  1040. /** Use when the current song is not a "real YTM song" with a static background, but rather a music video */
  1041. const getGeniusUrlVideo = () => __awaiter(this, void 0, void 0, function* () {
  1042. if (!songName.includes("-")) // for some fucking reason some music videos have YTM-like song title and artist separation, some don't
  1043. return yield getGeniusUrl(artistName, songName);
  1044. const [artist, ...rest] = songName.split("-").map(v => v.trim());
  1045. return yield getGeniusUrl(artist, rest.join(" "));
  1046. });
  1047. // TODO: artist might need further splitting before comma or ampersand
  1048. const url = isVideo ? yield getGeniusUrlVideo() : ((_b = yield getGeniusUrl(artistName, songName)) !== null && _b !== void 0 ? _b : yield getGeniusUrlVideo());
  1049. return url;
  1050. }
  1051. catch (err) {
  1052. (0,_utils__WEBPACK_IMPORTED_MODULE_1__.error)("Couldn't resolve lyrics URL:", err);
  1053. return null;
  1054. }
  1055. });
  1056. }
  1057. /**
  1058. * @param artist
  1059. * @param song
  1060. */
  1061. function getGeniusUrl(artist, song) {
  1062. return __awaiter(this, void 0, void 0, function* () {
  1063. try {
  1064. const startTs = Date.now();
  1065. const fetchUrl = `${geniURLSearchTopUrl}?artist=${encodeURIComponent(artist)}&song=${encodeURIComponent(song)}`;
  1066. (0,_utils__WEBPACK_IMPORTED_MODULE_1__.log)(`Requesting URL from geniURL at '${fetchUrl}'`);
  1067. const result = yield (yield fetch(fetchUrl)).json();
  1068. if (typeof result === "object" && result.error) {
  1069. (0,_utils__WEBPACK_IMPORTED_MODULE_1__.error)("Couldn't fetch lyrics URL:", result.message);
  1070. return undefined;
  1071. }
  1072. const url = result.url;
  1073. (0,_utils__WEBPACK_IMPORTED_MODULE_1__.info)(`Found lyrics URL (after ${Date.now() - startTs}ms): ${url}`);
  1074. return url;
  1075. }
  1076. catch (err) {
  1077. (0,_utils__WEBPACK_IMPORTED_MODULE_1__.error)("Couldn't get lyrics URL due to error:", err);
  1078. return undefined;
  1079. }
  1080. });
  1081. }
  1082. function getLyricsBtn(geniusUrl, hideIfLoading = true) {
  1083. const linkElem = document.createElement("a");
  1084. linkElem.className = "ytmusic-player-bar bytm-generic-lyrics-btn";
  1085. linkElem.title = geniusUrl ? "Click to open this song's lyrics in a new tab" : "Loading...";
  1086. if (geniusUrl)
  1087. linkElem.href = geniusUrl;
  1088. linkElem.target = "_blank";
  1089. linkElem.rel = "noopener noreferrer";
  1090. linkElem.style.visibility = hideIfLoading && geniusUrl ? "initial" : "hidden";
  1091. linkElem.style.display = hideIfLoading && geniusUrl ? "inline-flex" : "none";
  1092. const imgElem = document.createElement("img");
  1093. imgElem.className = "betterytm-lyrics-img";
  1094. imgElem.src = (0,_utils__WEBPACK_IMPORTED_MODULE_1__.getAssetUrl)("external/genius.png");
  1095. linkElem.appendChild(imgElem);
  1096. return linkElem;
  1097. }
  1098. /***/ }),
  1099. /***/ "./src/features/menu/menu.ts":
  1100. /*!***********************************!*\
  1101. !*** ./src/features/menu/menu.ts ***!
  1102. \***********************************/
  1103. /***/ (function(__unused_webpack_module, __webpack_exports__, __webpack_require__) {
  1104. __webpack_require__.r(__webpack_exports__);
  1105. /* harmony export */ __webpack_require__.d(__webpack_exports__, {
  1106. /* harmony export */ closeMenu: function() { return /* binding */ closeMenu; },
  1107. /* harmony export */ initMenu: function() { return /* binding */ initMenu; },
  1108. /* harmony export */ openMenu: function() { return /* binding */ openMenu; },
  1109. /* harmony export */ setActiveTab: function() { return /* binding */ setActiveTab; }
  1110. /* harmony export */ });
  1111. /* harmony import */ var _constants__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../../constants */ "./src/constants.ts");
  1112. /* harmony import */ var _utils__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../../utils */ "./src/utils.ts");
  1113. /* harmony import */ var _changelog_md__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../../../changelog.md */ "./changelog.md");
  1114. /* harmony import */ var _menu_html__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./menu.html */ "./src/features/menu/menu.html");
  1115. /* harmony import */ var _menu_css__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./menu.css */ "./src/features/menu/menu.css");
  1116. //#MARKER menu
  1117. /**
  1118. * These are the base selector values for the menu tabs
  1119. * Header selector format: `#${baseValue}-header`
  1120. * Content selector format: `#${baseValue}-content`
  1121. */
  1122. const tabsSelectors = {
  1123. options: "bytm-menu-tab-options",
  1124. info: "bytm-menu-tab-info",
  1125. changelog: "bytm-menu-tab-changelog",
  1126. };
  1127. function initMenu() {
  1128. document.addEventListener("DOMContentLoaded", () => {
  1129. // create menu container
  1130. const menuContainer = document.createElement("div");
  1131. menuContainer.id = "bytm-menu-container";
  1132. // add menu html
  1133. menuContainer.innerHTML = _menu_html__WEBPACK_IMPORTED_MODULE_3__["default"];
  1134. document.body.appendChild(menuContainer);
  1135. initMenuContents();
  1136. });
  1137. }
  1138. let menuContTries = 0;
  1139. function initMenuContents() {
  1140. var _a;
  1141. if (!document.querySelector("#bytm-menu-dialog"))
  1142. return menuContTries++ < _constants__WEBPACK_IMPORTED_MODULE_0__.triesLimit
  1143. ? setTimeout(initMenuContents, _constants__WEBPACK_IMPORTED_MODULE_0__.triesInterval)
  1144. : (0,_utils__WEBPACK_IMPORTED_MODULE_1__.error)(`couldn't create menu element after ${_constants__WEBPACK_IMPORTED_MODULE_0__.triesLimit} tries.`);
  1145. // hook events
  1146. for (const tab in tabsSelectors) {
  1147. const selector = tabsSelectors[tab];
  1148. (_a = document.querySelector(`#${selector}-header`)) === null || _a === void 0 ? void 0 : _a.addEventListener("click", () => {
  1149. setActiveTab(tab);
  1150. });
  1151. }
  1152. // init tab contents
  1153. initOptionsContent();
  1154. initInfoContent();
  1155. initChangelogContent();
  1156. }
  1157. /** Opens the specified tab */
  1158. function setActiveTab(tab) {
  1159. const tabs = Object.assign({}, tabsSelectors);
  1160. delete tabs[tab];
  1161. // disable all but new active tab
  1162. for (const disableTab of Object.keys(tabs)) {
  1163. document.querySelector(`#${tabs[disableTab]}-header`).dataset.active = "false";
  1164. document.querySelector(`#${tabs[disableTab]}-content`).dataset.active = "false";
  1165. }
  1166. // enable new active tab
  1167. document.querySelector(`#${tabsSelectors[tab]}-header`).dataset.active = "true";
  1168. document.querySelector(`#${tabsSelectors[tab]}-content`).dataset.active = "true";
  1169. }
  1170. /** Opens the modal menu dialog */
  1171. function openMenu() {
  1172. document.querySelector("#bytm-menu-dialog").showModal();
  1173. }
  1174. /** Closes the modal menu dialog */
  1175. function closeMenu() {
  1176. document.querySelector("#bytm-menu-dialog").close();
  1177. }
  1178. //#MARKER menu tab contents
  1179. function initOptionsContent() {
  1180. const tab = document.querySelector("#bytm-menu-tab-options-content");
  1181. void tab;
  1182. }
  1183. function initInfoContent() {
  1184. const tab = document.querySelector("#bytm-menu-tab-info-content");
  1185. void tab;
  1186. }
  1187. function initChangelogContent() {
  1188. const tab = document.querySelector("#bytm-menu-tab-changelog-content");
  1189. tab.innerHTML = _changelog_md__WEBPACK_IMPORTED_MODULE_2__["default"];
  1190. }
  1191. /***/ }),
  1192. /***/ "./src/features/menu/menu_old.ts":
  1193. /*!***************************************!*\
  1194. !*** ./src/features/menu/menu_old.ts ***!
  1195. \***************************************/
  1196. /***/ (function(__unused_webpack_module, __webpack_exports__, __webpack_require__) {
  1197. __webpack_require__.r(__webpack_exports__);
  1198. /* harmony export */ __webpack_require__.d(__webpack_exports__, {
  1199. /* harmony export */ addMenu: function() { return /* binding */ addMenu; },
  1200. /* harmony export */ closeMenu: function() { return /* binding */ closeMenu; },
  1201. /* harmony export */ openMenu: function() { return /* binding */ openMenu; }
  1202. /* harmony export */ });
  1203. /* harmony import */ var _config__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../../config */ "./src/config.ts");
  1204. /* harmony import */ var _constants__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../../constants */ "./src/constants.ts");
  1205. /* harmony import */ var _index__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../index */ "./src/features/index.ts");
  1206. /* harmony import */ var _utils__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../../utils */ "./src/utils.ts");
  1207. var __awaiter = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) {
  1208. function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
  1209. return new (P || (P = Promise))(function (resolve, reject) {
  1210. function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
  1211. function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
  1212. function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
  1213. step((generator = generator.apply(thisArg, _arguments || [])).next());
  1214. });
  1215. };
  1216. //#MARKER menu
  1217. /**
  1218. * Adds an element to open the BetterYTM menu
  1219. * @deprecated TODO: replace in v1.1.0 - see https://github.com/Sv443/BetterYTM/issues/23
  1220. */
  1221. function addMenu() {
  1222. var _a, _b;
  1223. return __awaiter(this, void 0, void 0, function* () {
  1224. // bg & menu
  1225. const backgroundElem = document.createElement("div");
  1226. backgroundElem.id = "betterytm-menu-bg";
  1227. backgroundElem.title = "Click here to close the menu";
  1228. backgroundElem.style.visibility = "hidden";
  1229. backgroundElem.style.display = "none";
  1230. backgroundElem.addEventListener("click", (e) => {
  1231. if (e.target.id === "betterytm-menu-bg")
  1232. closeMenu();
  1233. });
  1234. document.body.addEventListener("keydown", ({ key }) => {
  1235. if (key === "Escape")
  1236. closeMenu();
  1237. });
  1238. const menuContainer = document.createElement("div");
  1239. menuContainer.title = "";
  1240. menuContainer.id = "betterytm-menu";
  1241. menuContainer.style.borderRadius = "15px";
  1242. menuContainer.style.display = "flex";
  1243. menuContainer.style.flexDirection = "column";
  1244. menuContainer.style.justifyContent = "space-between";
  1245. // title
  1246. const titleCont = document.createElement("div");
  1247. titleCont.style.padding = "8px 20px 15px 8px";
  1248. titleCont.style.display = "flex";
  1249. titleCont.style.justifyContent = "space-between";
  1250. titleCont.id = "betterytm-menu-titlecont";
  1251. const titleElem = document.createElement("h2");
  1252. titleElem.id = "betterytm-menu-title";
  1253. titleElem.innerText = `${_constants__WEBPACK_IMPORTED_MODULE_1__.scriptInfo.name} - Configuration`;
  1254. const linksCont = document.createElement("div");
  1255. linksCont.id = "betterytm-menu-linkscont";
  1256. const addLink = (imgSrc, href, title) => {
  1257. const anchorElem = document.createElement("a");
  1258. anchorElem.className = "betterytm-menu-link";
  1259. anchorElem.rel = "noopener noreferrer";
  1260. anchorElem.target = "_blank";
  1261. anchorElem.href = href;
  1262. anchorElem.title = title;
  1263. anchorElem.style.marginLeft = "10px";
  1264. const imgElem = document.createElement("img");
  1265. imgElem.className = "betterytm-menu-img";
  1266. imgElem.src = imgSrc;
  1267. imgElem.style.width = "32px";
  1268. imgElem.style.height = "32px";
  1269. anchorElem.appendChild(imgElem);
  1270. linksCont.appendChild(anchorElem);
  1271. };
  1272. 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`);
  1273. addLink((0,_utils__WEBPACK_IMPORTED_MODULE_3__.getAssetUrl)("external/greasyfork.png"), "https://greasyfork.org/xyz", `${_constants__WEBPACK_IMPORTED_MODULE_1__.scriptInfo.name} on GreasyFork`);
  1274. const closeElem = document.createElement("img");
  1275. closeElem.id = "betterytm-menu-close";
  1276. closeElem.src = (0,_utils__WEBPACK_IMPORTED_MODULE_3__.getAssetUrl)("icon/close.png");
  1277. closeElem.title = "Click to close the menu";
  1278. closeElem.style.marginLeft = "50px";
  1279. closeElem.style.width = "32px";
  1280. closeElem.style.height = "32px";
  1281. closeElem.addEventListener("click", closeMenu);
  1282. linksCont.appendChild(closeElem);
  1283. titleCont.appendChild(titleElem);
  1284. titleCont.appendChild(linksCont);
  1285. // TODO: features
  1286. const featuresCont = document.createElement("div");
  1287. featuresCont.id = "betterytm-menu-opts";
  1288. featuresCont.style.display = "flex";
  1289. featuresCont.style.flexDirection = "column";
  1290. featuresCont.style.overflowY = "auto";
  1291. /** Gets called whenever the feature config is changed */
  1292. const confChanged = (key, initialVal, newVal) => __awaiter(this, void 0, void 0, function* () {
  1293. const fmt = (val) => typeof val === "object" ? JSON.stringify(val) : String(val);
  1294. (0,_utils__WEBPACK_IMPORTED_MODULE_3__.info)(`Feature config changed, key '${key}' from value '${fmt(initialVal)}' to '${fmt(newVal)}'`);
  1295. const featConf = Object.assign({}, yield (0,_config__WEBPACK_IMPORTED_MODULE_0__.getFeatures)());
  1296. featConf[key] = newVal;
  1297. yield (0,_config__WEBPACK_IMPORTED_MODULE_0__.saveFeatureConf)(featConf);
  1298. (0,_utils__WEBPACK_IMPORTED_MODULE_3__.log)("Saved feature config changes:\n", yield GM.getValue("betterytm-config"));
  1299. });
  1300. const features = yield (0,_config__WEBPACK_IMPORTED_MODULE_0__.getFeatures)();
  1301. for (const key in features) {
  1302. const ftInfo = _index__WEBPACK_IMPORTED_MODULE_2__.featInfo[key];
  1303. // @ts-ignore
  1304. if (!ftInfo || ftInfo.visible === false)
  1305. continue;
  1306. const { desc, type, default: ftDefault } = ftInfo;
  1307. // @ts-ignore
  1308. const step = (_a = ftInfo === null || ftInfo === void 0 ? void 0 : ftInfo.step) !== null && _a !== void 0 ? _a : undefined;
  1309. const val = features[key];
  1310. const initialVal = (_b = val !== null && val !== void 0 ? val : ftDefault) !== null && _b !== void 0 ? _b : undefined;
  1311. const ftConfElem = document.createElement("div");
  1312. ftConfElem.id = `betterytm-ftconf-${key}`;
  1313. ftConfElem.style.display = "flex";
  1314. ftConfElem.style.flexDirection = "row";
  1315. ftConfElem.style.justifyContent = "space-between";
  1316. ftConfElem.style.padding = "8px 20px";
  1317. {
  1318. const textElem = document.createElement("span");
  1319. textElem.style.display = "inline-block";
  1320. textElem.style.fontSize = "15px";
  1321. textElem.innerText = desc;
  1322. ftConfElem.appendChild(textElem);
  1323. }
  1324. {
  1325. let inputType = "text";
  1326. switch (type) {
  1327. case "toggle":
  1328. inputType = "checkbox";
  1329. break;
  1330. case "slider":
  1331. inputType = "range";
  1332. break;
  1333. case "number":
  1334. inputType = "number";
  1335. break;
  1336. }
  1337. const inputElemId = `betterytm-ftconf-${key}-input`;
  1338. const ctrlElem = document.createElement("span");
  1339. ctrlElem.style.display = "inline-block";
  1340. ctrlElem.style.whiteSpace = "nowrap";
  1341. const inputElem = document.createElement("input");
  1342. inputElem.id = inputElemId;
  1343. inputElem.style.marginRight = "37px";
  1344. inputElem.type = inputType;
  1345. if (type === "toggle")
  1346. inputElem.style.marginLeft = "5px";
  1347. if (typeof initialVal !== "undefined")
  1348. inputElem.value = String(initialVal);
  1349. if (type === "number" && step)
  1350. inputElem.step = step;
  1351. // @ts-ignore
  1352. if (ftInfo.min && ftInfo.max) {
  1353. // @ts-ignore
  1354. inputElem.min = ftInfo.min;
  1355. // @ts-ignore
  1356. inputElem.max = ftInfo.max;
  1357. }
  1358. if (type === "toggle" && typeof initialVal !== "undefined")
  1359. inputElem.checked = Boolean(initialVal);
  1360. // @ts-ignore
  1361. const unitTxt = typeof ftInfo.unit === "string" ? " " + ftInfo.unit : "";
  1362. const fmtVal = (v) => String(v).trim();
  1363. const toggleLabelText = (toggled) => toggled ? "On" : "Off";
  1364. let labelElem;
  1365. if (type === "slider") {
  1366. labelElem = document.createElement("label");
  1367. labelElem.classList.add("betterytm-ftconf-label");
  1368. labelElem.style.marginRight = "20px";
  1369. labelElem.style.fontSize = "16px";
  1370. labelElem.htmlFor = inputElemId;
  1371. labelElem.innerText = fmtVal(initialVal) + unitTxt;
  1372. inputElem.addEventListener("input", () => {
  1373. if (labelElem)
  1374. labelElem.innerText = fmtVal(parseInt(inputElem.value)) + unitTxt;
  1375. });
  1376. }
  1377. else if (type === "toggle") {
  1378. labelElem = document.createElement("label");
  1379. labelElem.classList.add("betterytm-ftconf-label");
  1380. labelElem.style.paddingLeft = "10px";
  1381. labelElem.style.paddingRight = "5px";
  1382. labelElem.style.fontSize = "16px";
  1383. labelElem.htmlFor = inputElemId;
  1384. labelElem.innerText = toggleLabelText(Boolean(initialVal)) + unitTxt;
  1385. inputElem.addEventListener("input", () => {
  1386. if (labelElem)
  1387. labelElem.innerText = toggleLabelText(inputElem.checked) + unitTxt;
  1388. });
  1389. }
  1390. inputElem.addEventListener("input", () => {
  1391. let v = parseInt(inputElem.value);
  1392. if (isNaN(v))
  1393. v = Number(inputElem.value);
  1394. if (typeof initialVal !== "undefined")
  1395. confChanged(key, initialVal, (type !== "toggle" ? v : inputElem.checked));
  1396. });
  1397. const resetElem = document.createElement("button");
  1398. resetElem.innerText = "Reset";
  1399. resetElem.addEventListener("click", () => {
  1400. inputElem[type !== "toggle" ? "value" : "checked"] = ftDefault;
  1401. if (labelElem) {
  1402. if (type === "toggle")
  1403. labelElem.innerText = toggleLabelText(inputElem.checked);
  1404. else
  1405. labelElem.innerText = fmtVal(parseInt(inputElem.value));
  1406. }
  1407. if (typeof initialVal !== "undefined")
  1408. confChanged(key, initialVal, ftDefault);
  1409. });
  1410. labelElem && ctrlElem.appendChild(labelElem);
  1411. ctrlElem.appendChild(inputElem);
  1412. ctrlElem.appendChild(resetElem);
  1413. ftConfElem.appendChild(ctrlElem);
  1414. }
  1415. featuresCont.appendChild(ftConfElem);
  1416. }
  1417. const footerElem = document.createElement("div");
  1418. footerElem.id = "betterytm-menu-footer";
  1419. footerElem.style.marginTop = "20px";
  1420. footerElem.style.fontSize = "17px";
  1421. footerElem.style.textDecoration = "underline";
  1422. footerElem.style.padding = "10px 20px";
  1423. footerElem.style.position = "sticky";
  1424. footerElem.style.backgroundColor = "var(--bytm-menu-bg)";
  1425. footerElem.style.bottom = "0";
  1426. footerElem.innerText = "You need to reload the page to apply changes.";
  1427. const reloadElem = document.createElement("button");
  1428. reloadElem.style.marginLeft = "20px";
  1429. reloadElem.innerText = "Reload now";
  1430. reloadElem.title = "Click to reload the page";
  1431. reloadElem.addEventListener("click", () => location.reload());
  1432. footerElem.appendChild(reloadElem);
  1433. featuresCont.appendChild(footerElem);
  1434. // finalize
  1435. const menuBody = document.createElement("div");
  1436. menuBody.id = "betterytm-menu-body";
  1437. menuBody.appendChild(titleCont);
  1438. menuBody.appendChild(featuresCont);
  1439. const versionCont = document.createElement("div");
  1440. versionCont.style.display = "flex";
  1441. versionCont.style.justifyContent = "space-around";
  1442. versionCont.style.fontSize = "1.15em";
  1443. versionCont.style.marginTop = "10px";
  1444. versionCont.style.marginBottom = "5px";
  1445. const versionElem = document.createElement("span");
  1446. versionElem.id = "betterytm-menu-version";
  1447. versionElem.innerText = `v${_constants__WEBPACK_IMPORTED_MODULE_1__.scriptInfo.version}`;
  1448. versionCont.appendChild(versionElem);
  1449. featuresCont.appendChild(versionCont);
  1450. menuContainer.appendChild(menuBody);
  1451. menuContainer.appendChild(versionCont);
  1452. backgroundElem.appendChild(menuContainer);
  1453. document.body.appendChild(backgroundElem);
  1454. // add style
  1455. const menuStyle = `\
  1456. :root {
  1457. --bytm-menu-bg: #212121;
  1458. }
  1459. #betterytm-menu-bg {
  1460. display: block;
  1461. position: fixed;
  1462. width: 100vw;
  1463. height: 100vh;
  1464. top: 0;
  1465. left: 0;
  1466. z-index: 15;
  1467. background-color: rgba(0, 0, 0, 0.6);
  1468. }
  1469. /* TODO:FIXME: needs better positioning (vw and vh === "big no no") */
  1470. #betterytm-menu {
  1471. display: inline-block;
  1472. position: fixed;
  1473. width: 50vw;
  1474. height: auto;
  1475. left: 25vw;
  1476. top: 10vh;
  1477. z-index: 16;
  1478. padding: 8px;
  1479. color: #fff;
  1480. background-color: var(--bytm-menu-bg);
  1481. }
  1482. #betterytm-menu-opts {
  1483. max-height: 70vh;
  1484. overflow: auto;
  1485. }
  1486. #betterytm-menu-titlecont {
  1487. display: flex;
  1488. }
  1489. #betterytm-menu-title {
  1490. font-size: 20px;
  1491. margin-top: 5px;
  1492. margin-bottom: 8px;
  1493. }
  1494. #betterytm-menu-linkscont {
  1495. display: flex;
  1496. }
  1497. .betterytm-menu-link {
  1498. display: inline-block;
  1499. }
  1500. /*.betterytm-menu-img {
  1501. }*/
  1502. #betterytm-menu-close {
  1503. cursor: pointer;
  1504. }
  1505. .betterytm-ftconf-label {
  1506. user-select: none;
  1507. }`;
  1508. (0,_utils__WEBPACK_IMPORTED_MODULE_3__.log)("Added menu elem:", backgroundElem);
  1509. (0,_utils__WEBPACK_IMPORTED_MODULE_3__.addGlobalStyle)(menuStyle, "menu");
  1510. });
  1511. }
  1512. function closeMenu() {
  1513. const menuBg = document.querySelector("#betterytm-menu-bg");
  1514. menuBg.style.visibility = "hidden";
  1515. menuBg.style.display = "none";
  1516. }
  1517. function openMenu() {
  1518. const menuBg = document.querySelector("#betterytm-menu-bg");
  1519. menuBg.style.visibility = "visible";
  1520. menuBg.style.display = "block";
  1521. }
  1522. /***/ }),
  1523. /***/ "./src/utils.ts":
  1524. /*!**********************!*\
  1525. !*** ./src/utils.ts ***!
  1526. \**********************/
  1527. /***/ (function(__unused_webpack_module, __webpack_exports__, __webpack_require__) {
  1528. __webpack_require__.r(__webpack_exports__);
  1529. /* harmony export */ __webpack_require__.d(__webpack_exports__, {
  1530. /* harmony export */ addGlobalStyle: function() { return /* binding */ addGlobalStyle; },
  1531. /* harmony export */ error: function() { return /* binding */ error; },
  1532. /* harmony export */ getAssetUrl: function() { return /* binding */ getAssetUrl; },
  1533. /* harmony export */ getDomain: function() { return /* binding */ getDomain; },
  1534. /* harmony export */ getEvtData: function() { return /* binding */ getEvtData; },
  1535. /* harmony export */ getVideoTime: function() { return /* binding */ getVideoTime; },
  1536. /* harmony export */ info: function() { return /* binding */ info; },
  1537. /* harmony export */ initSiteEvents: function() { return /* binding */ initSiteEvents; },
  1538. /* harmony export */ insertAfter: function() { return /* binding */ insertAfter; },
  1539. /* harmony export */ log: function() { return /* binding */ log; },
  1540. /* harmony export */ removeAllObservers: function() { return /* binding */ removeAllObservers; },
  1541. /* harmony export */ setLogLevel: function() { return /* binding */ setLogLevel; },
  1542. /* harmony export */ siteEvents: function() { return /* binding */ siteEvents; },
  1543. /* harmony export */ warn: function() { return /* binding */ warn; }
  1544. /* harmony export */ });
  1545. /* harmony import */ var _billjs_event_emitter__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @billjs/event-emitter */ "./node_modules/@billjs/event-emitter/lib/index.js");
  1546. /* harmony import */ var _constants__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./constants */ "./src/constants.ts");
  1547. var __awaiter = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) {
  1548. function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
  1549. return new (P || (P = Promise))(function (resolve, reject) {
  1550. function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
  1551. function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
  1552. function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
  1553. step((generator = generator.apply(thisArg, _arguments || [])).next());
  1554. });
  1555. };
  1556. //#MARKER BYTM-specific
  1557. let curLogLevel = 1;
  1558. /** Sets the current log level. 0 = Debug, 1 = Info */
  1559. function setLogLevel(level) {
  1560. curLogLevel = level;
  1561. }
  1562. function getLogLevel(args) {
  1563. const minLogLvl = 0, maxLogLvl = 1;
  1564. if (typeof args.at(-1) === "number")
  1565. return Math.max(Math.min(args.splice(args.length - 1)[0], minLogLvl), maxLogLvl);
  1566. return 0;
  1567. }
  1568. /** Common prefix to be able to tell logged messages apart */
  1569. const consPrefix = `[${_constants__WEBPACK_IMPORTED_MODULE_1__.scriptInfo.name}]`;
  1570. /**
  1571. * Logs string-compatible values to the console, as long as the log level is sufficient.
  1572. * @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.
  1573. */
  1574. function log(...args) {
  1575. if (curLogLevel <= getLogLevel(args))
  1576. console.log(consPrefix, ...args);
  1577. }
  1578. /**
  1579. * Logs string-compatible values to the console as info, as long as the log level is sufficient.
  1580. * @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.
  1581. */
  1582. function info(...args) {
  1583. if (curLogLevel <= getLogLevel(args))
  1584. console.info(consPrefix, ...args);
  1585. }
  1586. /**
  1587. * Logs string-compatible values to the console as a warning, as long as the log level is sufficient.
  1588. * @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.
  1589. */
  1590. function warn(...args) {
  1591. if (curLogLevel <= getLogLevel(args))
  1592. console.warn(consPrefix, ...args);
  1593. }
  1594. /** Logs string-compatible values to the console as an error. */
  1595. function error(...args) {
  1596. console.error(consPrefix, ...args);
  1597. }
  1598. /**
  1599. * Returns the current domain as a constant string representation
  1600. * @throws Throws if script runs on an unexpected website
  1601. */
  1602. function getDomain() {
  1603. const { hostname } = new URL(location.href);
  1604. if (hostname.includes("music.youtube"))
  1605. return "ytm";
  1606. else if (hostname.includes("youtube"))
  1607. return "yt";
  1608. else
  1609. throw new Error("BetterYTM is running on an unexpected website. Please don't tamper with the @match directives in the userscript header.");
  1610. }
  1611. /**
  1612. * Returns the current video time in seconds
  1613. * @param force Set to true to dispatch mouse movement events in case the video time can't be estimated
  1614. * @returns Returns null if the video time is unavailable
  1615. */
  1616. function getVideoTime(force = false) {
  1617. const domain = getDomain();
  1618. try {
  1619. if (domain === "ytm") {
  1620. const pbEl = document.querySelector("#progress-bar");
  1621. return !isNaN(Number(pbEl.value)) ? Number(pbEl.value) : null;
  1622. }
  1623. else if (domain === "yt") {
  1624. // YT doesn't update the progress bar when it's hidden (YTM doesn't hide it) so TODO: come up with some solution here
  1625. // Possible solution:
  1626. // - Use MutationObserver to detect when attributes of progress bar (selector `div.ytp-progress-bar[role="slider"]`) change
  1627. // - Wait until the attribute increments, then save the value of `aria-valuenow` and the current system time to memory
  1628. // - When site switch hotkey is pressed, take saved `aria-valuenow` value and add the difference between saved system time and current system time
  1629. // - If no value is present, use the script from `dev/ytForceShowVideoTime.js` to simulate mouse movement to force the element to update
  1630. // - Subtract one or two seconds to make up for rounding errors
  1631. // - profit
  1632. // if(!ytCurrentVideoTime) {
  1633. // ytForceShowVideoTime();
  1634. // const videoTime = document.querySelector("#TODO")?.getAttribute("aria-valuenow") ?? null;
  1635. // }
  1636. void [force, ytForceShowVideoTime];
  1637. return null;
  1638. }
  1639. return null;
  1640. }
  1641. catch (err) {
  1642. error("Couldn't get video time due to error:", err);
  1643. return null;
  1644. }
  1645. }
  1646. /** Sends events that force the video controls to become visible for about 3 seconds */
  1647. function ytForceShowVideoTime() {
  1648. const player = document.querySelector("#movie_player");
  1649. if (!player)
  1650. return false;
  1651. const defaultProps = {
  1652. // needed because otherwise YTM errors out - see https://github.com/Sv443/BetterYTM/issues/18#show_issue
  1653. view: unsafeWindow !== null && unsafeWindow !== void 0 ? unsafeWindow : window,
  1654. bubbles: true,
  1655. cancelable: false,
  1656. };
  1657. player.dispatchEvent(new MouseEvent("mouseenter", defaultProps));
  1658. const { x, y, width, height } = player.getBoundingClientRect();
  1659. const screenY = Math.round(y + height / 2);
  1660. const screenX = x + Math.min(50, Math.round(width / 3));
  1661. player.dispatchEvent(new MouseEvent("mousemove", Object.assign(Object.assign({}, defaultProps), { screenY,
  1662. screenX, movementX: 5, movementY: 0 })));
  1663. setTimeout(() => {
  1664. player.dispatchEvent(new MouseEvent("mouseleave", defaultProps));
  1665. }, 4000);
  1666. return true;
  1667. }
  1668. /** Returns the URL of the asset hosted on GitHub at the specified relative `path` (starting at `ROOT/assets/`) */
  1669. function getAssetUrl(path) {
  1670. return `https://raw.githubusercontent.com/Sv443/BetterYTM/${_constants__WEBPACK_IMPORTED_MODULE_1__.branch}/assets/${path}`;
  1671. }
  1672. //#MARKER DOM
  1673. /**
  1674. * Inserts `afterNode` as a sibling just after the provided `beforeNode`
  1675. * @param beforeNode
  1676. * @param afterNode
  1677. * @returns Returns the `afterNode`
  1678. */
  1679. function insertAfter(beforeNode, afterNode) {
  1680. var _a;
  1681. (_a = beforeNode.parentNode) === null || _a === void 0 ? void 0 : _a.insertBefore(afterNode, beforeNode.nextSibling);
  1682. return afterNode;
  1683. }
  1684. /**
  1685. * Adds global CSS style through a `<style>` element in the document's `<head>`
  1686. * @param style CSS string
  1687. * @param ref Reference name that is included in the `<style>`'s ID - prefixed with `betterytm-style-` - defaults to a random number if left undefined
  1688. */
  1689. function addGlobalStyle(style, ref) {
  1690. if (typeof ref !== "string" || ref.length === 0)
  1691. ref = String(Math.floor(Math.random() * 10000));
  1692. const styleElem = document.createElement("style");
  1693. styleElem.id = `betterytm-style-${ref}`;
  1694. styleElem.innerHTML = style;
  1695. document.head.appendChild(styleElem);
  1696. log(`Inserted global style with ref '${ref}':`, styleElem);
  1697. }
  1698. const siteEvents = new _billjs_event_emitter__WEBPACK_IMPORTED_MODULE_0__.EventEmitter();
  1699. /**
  1700. * Returns the data of an event from the `@billjs/event-emitter` library.
  1701. * This function is used to assert the type passed in `<T>`
  1702. * @param evt Event object from the `.on()` or `.once()` method
  1703. * @template T Type of the data passed by `.fire(type: string, data: T)`
  1704. */
  1705. function getEvtData(evt) {
  1706. return evt.data;
  1707. }
  1708. let observers = [];
  1709. /** Disconnects and deletes all observers. Run `initSiteEvents()` again to create new ones. */
  1710. function removeAllObservers() {
  1711. observers.forEach((observer) => observer.disconnect());
  1712. observers = [];
  1713. }
  1714. /** Creates MutationObservers that check if parts of the site have changed, then emit an event on the `siteEvents` instance. */
  1715. function initSiteEvents() {
  1716. return __awaiter(this, void 0, void 0, function* () {
  1717. try {
  1718. //#SECTION queue
  1719. // the queue container always exists so it doesn't need the extra init function
  1720. const queueObs = new MutationObserver(([{ addedNodes, removedNodes, target }]) => {
  1721. if (addedNodes.length > 0 || removedNodes.length > 0) {
  1722. info("Detected queue change - added nodes:", addedNodes.length, "- removed nodes:", removedNodes.length);
  1723. siteEvents.fire("queueChanged", target);
  1724. }
  1725. });
  1726. // only observe added or removed elements
  1727. queueObs.observe(document.querySelector(".side-panel.modular #contents.ytmusic-player-queue"), {
  1728. childList: true,
  1729. });
  1730. //#SECTION home page observers
  1731. initHomeObservers();
  1732. info("Successfully initialized SiteEvents observers");
  1733. observers = [
  1734. queueObs,
  1735. ];
  1736. }
  1737. catch (err) {
  1738. error("Couldn't initialize SiteEvents observers due to an error:\n", err);
  1739. }
  1740. });
  1741. }
  1742. /**
  1743. * The home page might not exist yet if the site was accessed through any path like /watch directly.
  1744. * This function will keep waiting for when the home page exists, then create the necessary MutationObservers.
  1745. */
  1746. function initHomeObservers() {
  1747. var _a;
  1748. return __awaiter(this, void 0, void 0, function* () {
  1749. let interval;
  1750. // hidden="" attribute is only present if the content of the page doesn't exist yet
  1751. // so this resolves only once that attribute is removed
  1752. if ((_a = document.querySelector("ytmusic-browse-response#browse-page")) === null || _a === void 0 ? void 0 : _a.hasAttribute("hidden")) {
  1753. yield new Promise((res) => {
  1754. interval = setInterval(() => {
  1755. var _a;
  1756. if (!((_a = document.querySelector("ytmusic-browse-response#browse-page")) === null || _a === void 0 ? void 0 : _a.hasAttribute("hidden"))) {
  1757. info("found home page");
  1758. res();
  1759. }
  1760. }, 50);
  1761. });
  1762. }
  1763. interval && clearInterval(interval);
  1764. siteEvents.fire("homePageLoaded");
  1765. info("Initialized home page observers");
  1766. //#SECTION carousel shelves
  1767. const shelfContainerObs = new MutationObserver(([{ addedNodes, removedNodes }]) => {
  1768. if (addedNodes.length > 0 || removedNodes.length > 0) {
  1769. info("Detected carousel shelf container change - added nodes:", addedNodes.length, "- removed nodes:", removedNodes.length);
  1770. siteEvents.fire("carouselShelvesChanged", { addedNodes, removedNodes });
  1771. }
  1772. });
  1773. shelfContainerObs.observe(document.querySelector("#contents.ytmusic-section-list-renderer"), {
  1774. childList: true,
  1775. });
  1776. observers = observers.concat([shelfContainerObs]);
  1777. });
  1778. }
  1779. /***/ })
  1780. /******/ });
  1781. /************************************************************************/
  1782. /******/ // The module cache
  1783. /******/ var __webpack_module_cache__ = {};
  1784. /******/
  1785. /******/ // The require function
  1786. /******/ function __webpack_require__(moduleId) {
  1787. /******/ // Check if module is in cache
  1788. /******/ var cachedModule = __webpack_module_cache__[moduleId];
  1789. /******/ if (cachedModule !== undefined) {
  1790. /******/ return cachedModule.exports;
  1791. /******/ }
  1792. /******/ // Create a new module (and put it into the cache)
  1793. /******/ var module = __webpack_module_cache__[moduleId] = {
  1794. /******/ // no module.id needed
  1795. /******/ // no module.loaded needed
  1796. /******/ exports: {}
  1797. /******/ };
  1798. /******/
  1799. /******/ // Execute the module function
  1800. /******/ __webpack_modules__[moduleId](module, module.exports, __webpack_require__);
  1801. /******/
  1802. /******/ // Return the exports of the module
  1803. /******/ return module.exports;
  1804. /******/ }
  1805. /******/
  1806. /************************************************************************/
  1807. /******/ /* webpack/runtime/define property getters */
  1808. /******/ !function() {
  1809. /******/ // define getter functions for harmony exports
  1810. /******/ __webpack_require__.d = function(exports, definition) {
  1811. /******/ for(var key in definition) {
  1812. /******/ if(__webpack_require__.o(definition, key) && !__webpack_require__.o(exports, key)) {
  1813. /******/ Object.defineProperty(exports, key, { enumerable: true, get: definition[key] });
  1814. /******/ }
  1815. /******/ }
  1816. /******/ };
  1817. /******/ }();
  1818. /******/
  1819. /******/ /* webpack/runtime/hasOwnProperty shorthand */
  1820. /******/ !function() {
  1821. /******/ __webpack_require__.o = function(obj, prop) { return Object.prototype.hasOwnProperty.call(obj, prop); }
  1822. /******/ }();
  1823. /******/
  1824. /******/ /* webpack/runtime/make namespace object */
  1825. /******/ !function() {
  1826. /******/ // define __esModule on exports
  1827. /******/ __webpack_require__.r = function(exports) {
  1828. /******/ if(typeof Symbol !== 'undefined' && Symbol.toStringTag) {
  1829. /******/ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
  1830. /******/ }
  1831. /******/ Object.defineProperty(exports, '__esModule', { value: true });
  1832. /******/ };
  1833. /******/ }();
  1834. /******/
  1835. /************************************************************************/
  1836. var __webpack_exports__ = {};
  1837. // This entry need to be wrapped in an IIFE because it need to be isolated against other modules in the chunk.
  1838. !function() {
  1839. /*!**********************!*\
  1840. !*** ./src/index.ts ***!
  1841. \**********************/
  1842. __webpack_require__.r(__webpack_exports__);
  1843. /* harmony import */ var _config__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./config */ "./src/config.ts");
  1844. /* harmony import */ var _constants__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./constants */ "./src/constants.ts");
  1845. /* harmony import */ var _utils__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./utils */ "./src/utils.ts");
  1846. /* harmony import */ var _features_index__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./features/index */ "./src/features/index.ts");
  1847. var __awaiter = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) {
  1848. function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
  1849. return new (P || (P = Promise))(function (resolve, reject) {
  1850. function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
  1851. function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
  1852. function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
  1853. step((generator = generator.apply(thisArg, _arguments || [])).next());
  1854. });
  1855. };
  1856. // TODO: add some style
  1857. console.log(`${_constants__WEBPACK_IMPORTED_MODULE_1__.scriptInfo.name} v${_constants__WEBPACK_IMPORTED_MODULE_1__.scriptInfo.version} (${_constants__WEBPACK_IMPORTED_MODULE_1__.scriptInfo.lastCommit}) - ${_constants__WEBPACK_IMPORTED_MODULE_1__.scriptInfo.namespace}`);
  1858. console.log(`Powered by lots of ambition and my song metadata API: ${_features_index__WEBPACK_IMPORTED_MODULE_3__.geniUrlBase}`);
  1859. const domain = (0,_utils__WEBPACK_IMPORTED_MODULE_2__.getDomain)();
  1860. /** Stuff that needs to be called ASAP, before anything async happens */
  1861. function preInit() {
  1862. (0,_utils__WEBPACK_IMPORTED_MODULE_2__.setLogLevel)(_constants__WEBPACK_IMPORTED_MODULE_1__.logLevel);
  1863. if (domain === "ytm")
  1864. (0,_features_index__WEBPACK_IMPORTED_MODULE_3__.initBeforeUnloadHook)();
  1865. init();
  1866. }
  1867. function init() {
  1868. return __awaiter(this, void 0, void 0, function* () {
  1869. yield (0,_features_index__WEBPACK_IMPORTED_MODULE_3__.preInitLayout)();
  1870. try {
  1871. document.addEventListener("DOMContentLoaded", onDomLoad);
  1872. }
  1873. catch (err) {
  1874. console.error(`${_constants__WEBPACK_IMPORTED_MODULE_1__.scriptInfo.name} - General Error:`, err);
  1875. }
  1876. try {
  1877. (0,_features_index__WEBPACK_IMPORTED_MODULE_3__.initMenu)();
  1878. }
  1879. catch (err) {
  1880. (0,_utils__WEBPACK_IMPORTED_MODULE_2__.error)("Couldn't initialize menu:", err);
  1881. }
  1882. });
  1883. }
  1884. /** Called when the DOM has finished loading and can be queried and altered by the userscript */
  1885. function onDomLoad() {
  1886. return __awaiter(this, void 0, void 0, function* () {
  1887. // post-build these double quotes are replaced by backticks
  1888. (0,_utils__WEBPACK_IMPORTED_MODULE_2__.addGlobalStyle)(`/*!***************************************************************************!*\
  1889. !*** css ./node_modules/css-loader/dist/cjs.js!./src/features/layout.css ***!
  1890. \***************************************************************************/
  1891. #betterytm-watermark {
  1892. font-size: 10px;
  1893. display: inline-block;
  1894. position: absolute;
  1895. left: 45px;
  1896. top: 46px;
  1897. z-index: 10;
  1898. color: white;
  1899. text-decoration: none;
  1900. cursor: pointer;
  1901. }
  1902. @media(max-width: 615px) {
  1903. #betterytm-watermark {
  1904. display: none;
  1905. }
  1906. }
  1907. #betterytm-watermark:hover {
  1908. text-decoration: underline;
  1909. }
  1910. .side-panel.modular ytmusic-player-queue-item .song-info.ytmusic-player-queue-item {
  1911. position: relative;
  1912. }
  1913. .side-panel.modular ytmusic-player-queue-item .song-info .bytm-queue-btn-container {
  1914. display: none;
  1915. position: absolute;
  1916. right: 0;
  1917. }
  1918. .side-panel.modular ytmusic-player-queue-item:hover .song-info .bytm-queue-btn-container {
  1919. display: inline-block;
  1920. }
  1921. /*!***************************************************************************!*\
  1922. !*** css ./node_modules/css-loader/dist/cjs.js!./src/features/lyrics.css ***!
  1923. \***************************************************************************/
  1924. .bytm-generic-lyrics-btn {
  1925. align-items: center;
  1926. justify-content: center;
  1927. position: relative;
  1928. vertical-align: middle;
  1929. margin-left: 8px;
  1930. width: 40px;
  1931. height: 40px;
  1932. border-radius: 100%;
  1933. background-color: transparent;
  1934. }
  1935. .bytm-generic-lyrics-btn:hover {
  1936. background-color: #383838;
  1937. }
  1938. .betterytm-lyrics-img {
  1939. display: inline-block;
  1940. z-index: 10;
  1941. width: 24px;
  1942. height: 24px;
  1943. padding: 5px;
  1944. }
  1945. /*!******************************************************************************!*\
  1946. !*** css ./node_modules/css-loader/dist/cjs.js!./src/features/menu/menu.css ***!
  1947. \******************************************************************************/
  1948. /* #bytm-menu-backdrop {
  1949. display: none;
  1950. flex-direction: column;
  1951. justify-content: center;
  1952. align-items: center;
  1953. }
  1954. #bytm-menu-backdrop[data-menu-open="true"] {
  1955. display: flex;
  1956. } */
  1957. #bytm-menu-header-container {
  1958. display: flex;
  1959. justify-content: flex-start;
  1960. align-items: center;
  1961. border-color: #ffffff;
  1962. border-style: none solid none none;
  1963. }
  1964. .bytm-menu-header-option {
  1965. display: "flex";
  1966. justify-content: center;
  1967. align-items: center;
  1968. border-color: #ffffff;
  1969. border-style: solid none solid none;
  1970. }
  1971. #bytm-menu-header-option h3 {
  1972. margin: 0;
  1973. }
  1974. .bytm-menu-tab[data-active="true"] {
  1975. display: none;
  1976. }
  1977. .bytm-menu-tab[data-active="false"] {
  1978. display: none;
  1979. }`, "global");
  1980. const features = yield (0,_config__WEBPACK_IMPORTED_MODULE_0__.loadFeatureConf)();
  1981. (0,_utils__WEBPACK_IMPORTED_MODULE_2__.log)(`Initializing features for domain '${domain}'`);
  1982. try {
  1983. if (domain === "ytm") {
  1984. (0,_utils__WEBPACK_IMPORTED_MODULE_2__.initSiteEvents)();
  1985. if (features.arrowKeySupport)
  1986. (0,_features_index__WEBPACK_IMPORTED_MODULE_3__.initArrowKeySkip)();
  1987. if (features.removeUpgradeTab)
  1988. (0,_features_index__WEBPACK_IMPORTED_MODULE_3__.removeUpgradeTab)();
  1989. if (features.watermarkEnabled)
  1990. (0,_features_index__WEBPACK_IMPORTED_MODULE_3__.addWatermark)();
  1991. if (features.geniusLyrics)
  1992. (0,_features_index__WEBPACK_IMPORTED_MODULE_3__.addMediaCtrlLyricsBtn)();
  1993. if (features.queueButtons)
  1994. (0,_features_index__WEBPACK_IMPORTED_MODULE_3__.initQueueButtons)();
  1995. if (typeof features.volumeSliderSize === "number")
  1996. (0,_features_index__WEBPACK_IMPORTED_MODULE_3__.setVolSliderSize)();
  1997. if (features.anchorImprovements)
  1998. (0,_features_index__WEBPACK_IMPORTED_MODULE_3__.addAnchorImprovements)();
  1999. (0,_features_index__WEBPACK_IMPORTED_MODULE_3__.setVolSliderStep)();
  2000. }
  2001. if (["ytm", "yt"].includes(domain)) {
  2002. if (features.switchBetweenSites)
  2003. (0,_features_index__WEBPACK_IMPORTED_MODULE_3__.initSiteSwitch)(domain);
  2004. try {
  2005. (0,_features_index__WEBPACK_IMPORTED_MODULE_3__.addMenu)(); // TODO: remove
  2006. }
  2007. catch (err) {
  2008. (0,_utils__WEBPACK_IMPORTED_MODULE_2__.error)("Couldn't add menu:", err);
  2009. }
  2010. }
  2011. }
  2012. catch (err) {
  2013. (0,_utils__WEBPACK_IMPORTED_MODULE_2__.error)("General error while executing feature:", err);
  2014. }
  2015. });
  2016. }
  2017. preInit();
  2018. }();
  2019. //# sourceMappingURL=BetterYTM.user.js.map