BetterYTM.user.js 102 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262
  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/develop/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/develop/dist/BetterYTM.user.js
  23. // @updateURL https://raw.githubusercontent.com/Sv443/BetterYTM/develop/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<p>TODO:</p>\n<ul>\n<li>Added menu to configure features</li>\n<li>New configurable features:<ul>\n<li>Make volume slider bigger</li>\n<li>Choose step of volume slider for finer control</li>\n<li>Add lyrics button to each song in a playlist</li>\n</ul>\n</li>\n<li>Changes / Fixes:<ul>\n<li>Now the lyrics button will directly link to the lyrics (using my API <a href=\"https://github.com/Sv443/geniURL\">geniURL</a>)</li>\n<li>Site switch with <kbd>F9</kbd> will now keep the video time</li>\n</ul>\n</li>\n</ul>\n<br>\n\n<h2 id=\"020\">0.2.0</h2>\n<ul>\n<li>Added Features:<ul>\n<li>Switch between YouTube and YT Music (with <kbd>F9</kbd> by default)</li>\n<li>Search for song lyrics with new button in media controls</li>\n<li>Remove &quot;Upgrade to YTM Premium&quot; tab</li>\n</ul>\n</li>\n</ul>\n<br>\n\n<h2 id=\"010\">0.1.0</h2>\n<ul>\n<li>Added support for arrow keys to skip forward or backward (currently only by fixed 10 second interval)</li>\n</ul>\n<p><br><br><br><br><br><br><br><br><br></p>\n";
  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. const branchRaw = "develop";
  445. /** The branch to use in various URLs that point to the GitHub repo */
  446. const branch = branchRaw.match(/^{{.+}}$/) ? "main" : branchRaw;
  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: "814cb33", // assert as generic string instead of union
  462. });
  463. /***/ }),
  464. /***/ "./src/events.ts":
  465. /*!***********************!*\
  466. !*** ./src/events.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 */ getEvtData: function() { return /* binding */ getEvtData; },
  472. /* harmony export */ initSiteEvents: function() { return /* binding */ initSiteEvents; },
  473. /* harmony export */ removeAllObservers: function() { return /* binding */ removeAllObservers; },
  474. /* harmony export */ siteEvents: function() { return /* binding */ siteEvents; }
  475. /* harmony export */ });
  476. /* harmony import */ var _billjs_event_emitter__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @billjs/event-emitter */ "./node_modules/@billjs/event-emitter/lib/index.js");
  477. /* harmony import */ var _utils__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./utils */ "./src/utils.ts");
  478. var __awaiter = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) {
  479. function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
  480. return new (P || (P = Promise))(function (resolve, reject) {
  481. function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
  482. function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
  483. function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
  484. step((generator = generator.apply(thisArg, _arguments || [])).next());
  485. });
  486. };
  487. /** EventEmitter instance that is used to detect changes to the site */
  488. const siteEvents = new _billjs_event_emitter__WEBPACK_IMPORTED_MODULE_0__.EventEmitter();
  489. /**
  490. * Returns the data of an event from the `@billjs/event-emitter` library.
  491. * This function is used as a shorthand to extract the data and assert it with the type passed in `<T>`
  492. * @param evt Event object from the `.on()` or `.once()` method
  493. * @template T Type of the data passed by `.fire(type: string, data: T)`
  494. */
  495. function getEvtData(evt) {
  496. return evt.data;
  497. }
  498. let observers = [];
  499. /** Disconnects and deletes all observers. Run `initSiteEvents()` again to create new ones. */
  500. function removeAllObservers() {
  501. observers.forEach((observer) => observer.disconnect());
  502. observers = [];
  503. }
  504. /** Creates MutationObservers that check if parts of the site have changed, then emit an event on the `siteEvents` instance. */
  505. function initSiteEvents() {
  506. return __awaiter(this, void 0, void 0, function* () {
  507. try {
  508. //#SECTION queue
  509. // the queue container always exists so it doesn't need the extra init function
  510. const queueObs = new MutationObserver(([{ addedNodes, removedNodes, target }]) => {
  511. if (addedNodes.length > 0 || removedNodes.length > 0) {
  512. (0,_utils__WEBPACK_IMPORTED_MODULE_1__.info)(`Detected queue change - added nodes: ${[...addedNodes.values()].length} - removed nodes: ${[...removedNodes.values()].length}`);
  513. siteEvents.fire("queueChanged", target);
  514. }
  515. });
  516. // only observe added or removed elements
  517. queueObs.observe(document.querySelector(".side-panel.modular #contents.ytmusic-player-queue"), {
  518. childList: true,
  519. });
  520. const autoplayObs = new MutationObserver(([{ addedNodes, removedNodes, target }]) => {
  521. if (addedNodes.length > 0 || removedNodes.length > 0) {
  522. (0,_utils__WEBPACK_IMPORTED_MODULE_1__.info)(`Detected autoplay queue change - added nodes: ${[...addedNodes.values()].length} - removed nodes: ${[...removedNodes.values()].length}`);
  523. siteEvents.fire("autoplayQueueChanged", target);
  524. }
  525. });
  526. // TODO: check if this works since autoplay seems to be lazy-loaded
  527. autoplayObs.observe(document.querySelector(".side-panel.modular ytmusic-player-queue #automix-contents"), {
  528. childList: true,
  529. });
  530. //#SECTION home page observers
  531. initHomeObservers();
  532. (0,_utils__WEBPACK_IMPORTED_MODULE_1__.info)("Successfully initialized SiteEvents observers");
  533. observers = observers.concat([
  534. queueObs,
  535. autoplayObs,
  536. ]);
  537. }
  538. catch (err) {
  539. (0,_utils__WEBPACK_IMPORTED_MODULE_1__.error)("Couldn't initialize SiteEvents observers due to an error:\n", err);
  540. }
  541. });
  542. }
  543. /**
  544. * The home page might not exist yet if the site was accessed through any path like /watch directly.
  545. * This function will keep waiting for when the home page exists, then create the necessary MutationObservers.
  546. */
  547. function initHomeObservers() {
  548. var _a;
  549. return __awaiter(this, void 0, void 0, function* () {
  550. let interval;
  551. // hidden="" attribute is only present if the content of the page doesn't exist yet
  552. // so this pauses execution until that attribute is removed
  553. if ((_a = document.querySelector("ytmusic-browse-response#browse-page")) === null || _a === void 0 ? void 0 : _a.hasAttribute("hidden")) {
  554. yield new Promise((res) => {
  555. interval = setInterval(() => {
  556. var _a;
  557. if (!((_a = document.querySelector("ytmusic-browse-response#browse-page")) === null || _a === void 0 ? void 0 : _a.hasAttribute("hidden"))) {
  558. clearInterval(interval);
  559. res();
  560. }
  561. }, 50);
  562. });
  563. }
  564. siteEvents.fire("homePageLoaded");
  565. (0,_utils__WEBPACK_IMPORTED_MODULE_1__.info)("Initialized home page observers");
  566. //#SECTION carousel shelves
  567. const shelfContainerObs = new MutationObserver(([{ addedNodes, removedNodes }]) => {
  568. if (addedNodes.length > 0 || removedNodes.length > 0) {
  569. (0,_utils__WEBPACK_IMPORTED_MODULE_1__.info)("Detected carousel shelf container change - added nodes:", addedNodes.length, "- removed nodes:", removedNodes.length);
  570. siteEvents.fire("carouselShelvesChanged", { addedNodes, removedNodes });
  571. }
  572. });
  573. shelfContainerObs.observe(document.querySelector("#contents.ytmusic-section-list-renderer"), {
  574. childList: true,
  575. });
  576. observers = observers.concat([shelfContainerObs]);
  577. });
  578. }
  579. /***/ }),
  580. /***/ "./src/features/index.ts":
  581. /*!*******************************!*\
  582. !*** ./src/features/index.ts ***!
  583. \*******************************/
  584. /***/ (function(__unused_webpack_module, __webpack_exports__, __webpack_require__) {
  585. __webpack_require__.r(__webpack_exports__);
  586. /* harmony export */ __webpack_require__.d(__webpack_exports__, {
  587. /* harmony export */ addAnchorImprovements: function() { return /* reexport safe */ _layout__WEBPACK_IMPORTED_MODULE_2__.addAnchorImprovements; },
  588. /* harmony export */ addLyricsCacheEntry: function() { return /* reexport safe */ _lyrics__WEBPACK_IMPORTED_MODULE_3__.addLyricsCacheEntry; },
  589. /* harmony export */ addMediaCtrlLyricsBtn: function() { return /* reexport safe */ _lyrics__WEBPACK_IMPORTED_MODULE_3__.addMediaCtrlLyricsBtn; },
  590. /* harmony export */ addMenu: function() { return /* reexport safe */ _menu_menu_old__WEBPACK_IMPORTED_MODULE_5__.addMenu; },
  591. /* harmony export */ addWatermark: function() { return /* reexport safe */ _layout__WEBPACK_IMPORTED_MODULE_2__.addWatermark; },
  592. /* harmony export */ closeMenu: function() { return /* reexport safe */ _menu_menu_old__WEBPACK_IMPORTED_MODULE_5__.closeMenu; },
  593. /* harmony export */ createLyricsBtn: function() { return /* reexport safe */ _lyrics__WEBPACK_IMPORTED_MODULE_3__.createLyricsBtn; },
  594. /* harmony export */ disableBeforeUnload: function() { return /* reexport safe */ _input__WEBPACK_IMPORTED_MODULE_1__.disableBeforeUnload; },
  595. /* harmony export */ enableBeforeUnload: function() { return /* reexport safe */ _input__WEBPACK_IMPORTED_MODULE_1__.enableBeforeUnload; },
  596. /* harmony export */ featInfo: function() { return /* binding */ featInfo; },
  597. /* harmony export */ geniUrlBase: function() { return /* reexport safe */ _lyrics__WEBPACK_IMPORTED_MODULE_3__.geniUrlBase; },
  598. /* harmony export */ getCurrentLyricsUrl: function() { return /* reexport safe */ _lyrics__WEBPACK_IMPORTED_MODULE_3__.getCurrentLyricsUrl; },
  599. /* harmony export */ getGeniusUrl: function() { return /* reexport safe */ _lyrics__WEBPACK_IMPORTED_MODULE_3__.getGeniusUrl; },
  600. /* harmony export */ getLyricsCacheEntry: function() { return /* reexport safe */ _lyrics__WEBPACK_IMPORTED_MODULE_3__.getLyricsCacheEntry; },
  601. /* harmony export */ initArrowKeySkip: function() { return /* reexport safe */ _input__WEBPACK_IMPORTED_MODULE_1__.initArrowKeySkip; },
  602. /* harmony export */ initBeforeUnloadHook: function() { return /* reexport safe */ _input__WEBPACK_IMPORTED_MODULE_1__.initBeforeUnloadHook; },
  603. /* harmony export */ initMenu: function() { return /* reexport safe */ _menu_menu__WEBPACK_IMPORTED_MODULE_4__.initMenu; },
  604. /* harmony export */ initQueueButtons: function() { return /* reexport safe */ _layout__WEBPACK_IMPORTED_MODULE_2__.initQueueButtons; },
  605. /* harmony export */ initSiteSwitch: function() { return /* reexport safe */ _input__WEBPACK_IMPORTED_MODULE_1__.initSiteSwitch; },
  606. /* harmony export */ openMenu: function() { return /* reexport safe */ _menu_menu_old__WEBPACK_IMPORTED_MODULE_5__.openMenu; },
  607. /* harmony export */ preInitLayout: function() { return /* reexport safe */ _layout__WEBPACK_IMPORTED_MODULE_2__.preInitLayout; },
  608. /* harmony export */ removeUpgradeTab: function() { return /* reexport safe */ _layout__WEBPACK_IMPORTED_MODULE_2__.removeUpgradeTab; },
  609. /* harmony export */ sanitizeArtists: function() { return /* reexport safe */ _lyrics__WEBPACK_IMPORTED_MODULE_3__.sanitizeArtists; },
  610. /* harmony export */ sanitizeSong: function() { return /* reexport safe */ _lyrics__WEBPACK_IMPORTED_MODULE_3__.sanitizeSong; },
  611. /* harmony export */ setVolSliderSize: function() { return /* reexport safe */ _layout__WEBPACK_IMPORTED_MODULE_2__.setVolSliderSize; },
  612. /* harmony export */ setVolSliderStep: function() { return /* reexport safe */ _layout__WEBPACK_IMPORTED_MODULE_2__.setVolSliderStep; }
  613. /* harmony export */ });
  614. /* harmony import */ var _constants__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../constants */ "./src/constants.ts");
  615. /* harmony import */ var _input__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./input */ "./src/features/input.ts");
  616. /* harmony import */ var _layout__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./layout */ "./src/features/layout.ts");
  617. /* harmony import */ var _lyrics__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./lyrics */ "./src/features/lyrics.ts");
  618. /* harmony import */ var _menu_menu__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./menu/menu */ "./src/features/menu/menu.ts");
  619. /* harmony import */ var _menu_menu_old__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./menu/menu_old */ "./src/features/menu/menu_old.ts");
  620. // TODO
  621. /** Contains all possible features with their default values and other config */
  622. const featInfo = {
  623. //#SECTION input
  624. arrowKeySupport: {
  625. desc: "Arrow keys skip forwards and backwards by 10 seconds",
  626. type: "toggle",
  627. category: "input",
  628. default: true,
  629. },
  630. switchBetweenSites: {
  631. desc: "Add F9 as a hotkey to switch between the YT and YTM sites on a video / song",
  632. type: "toggle",
  633. category: "input",
  634. default: true,
  635. },
  636. switchSitesHotkey: {
  637. desc: "TODO: Which hotkey needs to be pressed to switch sites?",
  638. type: "hotkey",
  639. category: "input",
  640. default: {
  641. key: "F9",
  642. shift: false,
  643. ctrl: false,
  644. meta: false,
  645. },
  646. visible: false,
  647. },
  648. disableBeforeUnloadPopup: {
  649. desc: "Completely disable the popup that sometimes appears before leaving the site",
  650. type: "toggle",
  651. category: "input",
  652. default: false,
  653. },
  654. anchorImprovements: {
  655. desc: "TODO: Make it so middle clicking a song to open it in a new tab is easier",
  656. type: "toggle",
  657. category: "input",
  658. default: true,
  659. visible: false,
  660. },
  661. //#SECTION layout
  662. removeUpgradeTab: {
  663. desc: "Remove the \"Upgrade\" / YT Music Premium tab",
  664. type: "toggle",
  665. category: "layout",
  666. default: true,
  667. },
  668. volumeSliderSize: {
  669. desc: "The width of the volume slider in pixels",
  670. type: "number",
  671. category: "layout",
  672. min: 10,
  673. max: 1000,
  674. step: 5,
  675. default: 160,
  676. unit: "px",
  677. },
  678. volumeSliderStep: {
  679. desc: "Volume slider sensitivity - the smaller this number, the finer the volume control",
  680. type: "slider",
  681. category: "layout",
  682. min: 1,
  683. max: 20,
  684. default: 2,
  685. },
  686. watermarkEnabled: {
  687. desc: `Show a ${_constants__WEBPACK_IMPORTED_MODULE_0__.scriptInfo.name} watermark under the YTM logo`,
  688. type: "toggle",
  689. category: "layout",
  690. default: true,
  691. visible: false,
  692. },
  693. queueButtons: {
  694. desc: "Add buttons while hovering over a song in a queue to quickly remove it (TODO) or open its lyrics",
  695. type: "toggle",
  696. category: "layout",
  697. default: true,
  698. },
  699. //#SECTION lyrics
  700. geniusLyrics: {
  701. desc: "Add a button to the media controls to open the current song's lyrics on genius.com in a new tab",
  702. type: "toggle",
  703. category: "lyrics",
  704. default: true,
  705. },
  706. };
  707. /***/ }),
  708. /***/ "./src/features/input.ts":
  709. /*!*******************************!*\
  710. !*** ./src/features/input.ts ***!
  711. \*******************************/
  712. /***/ (function(__unused_webpack_module, __webpack_exports__, __webpack_require__) {
  713. __webpack_require__.r(__webpack_exports__);
  714. /* harmony export */ __webpack_require__.d(__webpack_exports__, {
  715. /* harmony export */ disableBeforeUnload: function() { return /* binding */ disableBeforeUnload; },
  716. /* harmony export */ enableBeforeUnload: function() { return /* binding */ enableBeforeUnload; },
  717. /* harmony export */ initArrowKeySkip: function() { return /* binding */ initArrowKeySkip; },
  718. /* harmony export */ initBeforeUnloadHook: function() { return /* binding */ initBeforeUnloadHook; },
  719. /* harmony export */ initSiteSwitch: function() { return /* binding */ initSiteSwitch; }
  720. /* harmony export */ });
  721. /* harmony import */ var _utils__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../utils */ "./src/utils.ts");
  722. /* harmony import */ var _config__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../config */ "./src/config.ts");
  723. //#MARKER arrow key skip
  724. function initArrowKeySkip() {
  725. document.addEventListener("keydown", onKeyDown);
  726. (0,_utils__WEBPACK_IMPORTED_MODULE_0__.log)("Added key press listener");
  727. }
  728. /** Called when the user presses any key, anywhere */
  729. function onKeyDown(evt) {
  730. var _a, _b;
  731. if (["ArrowLeft", "ArrowRight"].includes(evt.code)) {
  732. // discard the event when a (text) input is currently active, like when editing a playlist
  733. if (["INPUT", "TEXTAREA", "SELECT"].includes((_b = (_a = document.activeElement) === null || _a === void 0 ? void 0 : _a.tagName) !== null && _b !== void 0 ? _b : "_"))
  734. 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`);
  735. (0,_utils__WEBPACK_IMPORTED_MODULE_0__.log)(`Captured key '${evt.code}' in proxy listener`);
  736. // 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
  737. const defaultProps = {
  738. altKey: false,
  739. ctrlKey: false,
  740. metaKey: false,
  741. shiftKey: false,
  742. target: document.body,
  743. currentTarget: document.body,
  744. originalTarget: document.body,
  745. explicitOriginalTarget: document.body,
  746. srcElement: document.body,
  747. type: "keydown",
  748. bubbles: true,
  749. cancelBubble: false,
  750. cancelable: true,
  751. isTrusted: true,
  752. repeat: false,
  753. // needed because otherwise YTM errors out - see https://github.com/Sv443/BetterYTM/issues/18#show_issue
  754. view: (0,_utils__WEBPACK_IMPORTED_MODULE_0__.getUnsafeWindow)(),
  755. };
  756. let invalidKey = false;
  757. let keyProps = {};
  758. switch (evt.code) {
  759. case "ArrowLeft":
  760. keyProps = {
  761. code: "KeyH",
  762. key: "h",
  763. keyCode: 72,
  764. which: 72,
  765. };
  766. break;
  767. case "ArrowRight":
  768. keyProps = {
  769. code: "KeyL",
  770. key: "l",
  771. keyCode: 76,
  772. which: 76,
  773. };
  774. break;
  775. default:
  776. invalidKey = true;
  777. break;
  778. }
  779. if (!invalidKey) {
  780. const proxyProps = Object.assign(Object.assign({ code: "" }, defaultProps), keyProps);
  781. document.body.dispatchEvent(new KeyboardEvent("keydown", proxyProps));
  782. (0,_utils__WEBPACK_IMPORTED_MODULE_0__.log)(`Dispatched proxy keydown event: [${evt.code}] -> [${proxyProps.code}]`);
  783. }
  784. else
  785. (0,_utils__WEBPACK_IMPORTED_MODULE_0__.warn)(`Captured key '${evt.code}' has no defined behavior`);
  786. }
  787. }
  788. //#MARKER site switch
  789. /** Initializes the site switch feature */
  790. function initSiteSwitch(domain) {
  791. // TODO:
  792. // extra features:
  793. // - keep video time
  794. // - configurable hotkey
  795. document.addEventListener("keydown", (e) => {
  796. if (e.key === "F9")
  797. switchSite(domain === "yt" ? "ytm" : "yt");
  798. });
  799. (0,_utils__WEBPACK_IMPORTED_MODULE_0__.log)("Initialized site switch listener");
  800. }
  801. /** Switches to the other site (between YT and YTM) */
  802. function switchSite(newDomain) {
  803. var _a;
  804. try {
  805. let subdomain;
  806. if (newDomain === "ytm")
  807. subdomain = "music";
  808. else if (newDomain === "yt")
  809. subdomain = "www";
  810. if (!subdomain)
  811. throw new TypeError(`Unrecognized domain '${newDomain}'`);
  812. const { pathname, search, hash } = new URL(location.href);
  813. const vt = (_a = (0,_utils__WEBPACK_IMPORTED_MODULE_0__.getVideoTime)()) !== null && _a !== void 0 ? _a : 0;
  814. (0,_utils__WEBPACK_IMPORTED_MODULE_0__.log)(`Found video time of ${vt} seconds`);
  815. const newSearch = search.includes("?") ? `${search}&t=${vt}` : `?t=${vt}`;
  816. const url = `https://${subdomain}.youtube.com${pathname}${newSearch}${hash}`;
  817. console.info(`BetterYTM - switching to domain '${newDomain}' at ${url}`);
  818. disableBeforeUnload();
  819. location.assign(url);
  820. }
  821. catch (err) {
  822. (0,_utils__WEBPACK_IMPORTED_MODULE_0__.error)("Error while switching site:", err);
  823. }
  824. }
  825. //#MARKER beforeunload popup
  826. let beforeUnloadEnabled = true;
  827. /** Disables the popup before leaving the site */
  828. function disableBeforeUnload() {
  829. beforeUnloadEnabled = false;
  830. (0,_utils__WEBPACK_IMPORTED_MODULE_0__.info)("Disabled popup before leaving the site");
  831. }
  832. /** (Re-)enables the popup before leaving the site */
  833. function enableBeforeUnload() {
  834. beforeUnloadEnabled = true;
  835. (0,_utils__WEBPACK_IMPORTED_MODULE_0__.info)("Enabled popup before leaving the site");
  836. }
  837. /**
  838. * Adds a spy function into `window.__proto__.addEventListener` to selectively discard `beforeunload`
  839. * event listeners before they can be attached by the site.
  840. */
  841. function initBeforeUnloadHook() {
  842. Error.stackTraceLimit = 1000; // default is 25 on FF so this should hopefully be more than enough
  843. (function (original) {
  844. // @ts-ignore
  845. window.__proto__.addEventListener = function (...args) {
  846. if (beforeUnloadEnabled && args[0] === "beforeunload")
  847. return (0,_utils__WEBPACK_IMPORTED_MODULE_0__.log)("Prevented beforeunload event listener from attaching");
  848. else
  849. return original.apply(this, args);
  850. };
  851. // @ts-ignore
  852. })(window.__proto__.addEventListener);
  853. (0,_config__WEBPACK_IMPORTED_MODULE_1__.getFeatures)().then(feats => {
  854. if (feats.disableBeforeUnloadPopup)
  855. disableBeforeUnload();
  856. });
  857. }
  858. /***/ }),
  859. /***/ "./src/features/layout.ts":
  860. /*!********************************!*\
  861. !*** ./src/features/layout.ts ***!
  862. \********************************/
  863. /***/ (function(__unused_webpack_module, __webpack_exports__, __webpack_require__) {
  864. __webpack_require__.r(__webpack_exports__);
  865. /* harmony export */ __webpack_require__.d(__webpack_exports__, {
  866. /* harmony export */ addAnchorImprovements: function() { return /* binding */ addAnchorImprovements; },
  867. /* harmony export */ addWatermark: function() { return /* binding */ addWatermark; },
  868. /* harmony export */ initQueueButtons: function() { return /* binding */ initQueueButtons; },
  869. /* harmony export */ preInitLayout: function() { return /* binding */ preInitLayout; },
  870. /* harmony export */ removeUpgradeTab: function() { return /* binding */ removeUpgradeTab; },
  871. /* harmony export */ setVolSliderSize: function() { return /* binding */ setVolSliderSize; },
  872. /* harmony export */ setVolSliderStep: function() { return /* binding */ setVolSliderStep; }
  873. /* harmony export */ });
  874. /* harmony import */ var _constants__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../constants */ "./src/constants.ts");
  875. /* harmony import */ var _config__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../config */ "./src/config.ts");
  876. /* harmony import */ var _utils__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../utils */ "./src/utils.ts");
  877. /* harmony import */ var _events__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../events */ "./src/events.ts");
  878. /* harmony import */ var _menu_menu_old__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./menu/menu_old */ "./src/features/menu/menu_old.ts");
  879. /* harmony import */ var _layout_css__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./layout.css */ "./src/features/layout.css");
  880. /* harmony import */ var _lyrics__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ./lyrics */ "./src/features/lyrics.ts");
  881. var __awaiter = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) {
  882. function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
  883. return new (P || (P = Promise))(function (resolve, reject) {
  884. function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
  885. function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
  886. function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
  887. step((generator = generator.apply(thisArg, _arguments || [])).next());
  888. });
  889. };
  890. let features;
  891. function preInitLayout() {
  892. return __awaiter(this, void 0, void 0, function* () {
  893. features = yield (0,_config__WEBPACK_IMPORTED_MODULE_1__.getFeatures)();
  894. });
  895. }
  896. //#MARKER watermark
  897. /** Adds a watermark beneath the logo */
  898. function addWatermark() {
  899. const watermark = document.createElement("a");
  900. watermark.role = "button";
  901. watermark.id = "betterytm-watermark";
  902. watermark.className = "style-scope ytmusic-nav-bar";
  903. watermark.innerText = _constants__WEBPACK_IMPORTED_MODULE_0__.scriptInfo.name;
  904. watermark.title = "Open menu";
  905. watermark.tabIndex = 1000;
  906. watermark.addEventListener("click", () => (0,_menu_menu_old__WEBPACK_IMPORTED_MODULE_4__.openMenu)());
  907. watermark.addEventListener("keydown", (e) => e.key === "Enter" && (0,_menu_menu_old__WEBPACK_IMPORTED_MODULE_4__.openMenu)());
  908. const logoElem = document.querySelector("#left-content");
  909. (0,_utils__WEBPACK_IMPORTED_MODULE_2__.insertAfter)(logoElem, watermark);
  910. (0,_utils__WEBPACK_IMPORTED_MODULE_2__.log)("Added watermark element:", watermark);
  911. }
  912. //#MARKER remove upgrade tab
  913. let removeUpgradeTries = 0;
  914. /** Removes the "Upgrade" / YT Music Premium tab from the title / nav bar */
  915. function removeUpgradeTab() {
  916. const tabElem = document.querySelector(".ytmusic-nav-bar ytmusic-pivot-bar-item-renderer[tab-id=\"SPunlimited\"]");
  917. if (tabElem) {
  918. tabElem.remove();
  919. (0,_utils__WEBPACK_IMPORTED_MODULE_2__.log)(`Removed upgrade tab after ${removeUpgradeTries} tries`);
  920. }
  921. else if (removeUpgradeTries < _constants__WEBPACK_IMPORTED_MODULE_0__.triesLimit) {
  922. setTimeout(removeUpgradeTab, _constants__WEBPACK_IMPORTED_MODULE_0__.triesInterval); // TODO: improve this
  923. removeUpgradeTries++;
  924. }
  925. else
  926. (0,_utils__WEBPACK_IMPORTED_MODULE_2__.error)(`Couldn't find upgrade tab to remove after ${removeUpgradeTries} tries`);
  927. }
  928. //#MARKER volume slider
  929. /** Sets the volume slider to a set size */
  930. function setVolSliderSize() {
  931. const { volumeSliderSize: size } = features;
  932. if (typeof size !== "number" || isNaN(Number(size)))
  933. return;
  934. const style = `\
  935. .volume-slider.ytmusic-player-bar, .expand-volume-slider.ytmusic-player-bar {
  936. width: ${size}px !important;
  937. }`;
  938. (0,_utils__WEBPACK_IMPORTED_MODULE_2__.addGlobalStyle)(style, "vol-slider");
  939. }
  940. /** Sets the `step` attribute of the volume slider */
  941. function setVolSliderStep() {
  942. const sliderElem = document.querySelector("tp-yt-paper-slider#volume-slider");
  943. sliderElem.setAttribute("step", String(features.volumeSliderStep));
  944. }
  945. //#MARKER queue buttons
  946. // 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
  947. function initQueueButtons() {
  948. const addQueueBtns = (evt) => {
  949. let amt = 0;
  950. for (const queueItm of (0,_events__WEBPACK_IMPORTED_MODULE_3__.getEvtData)(evt).childNodes) {
  951. if (!queueItm.classList.contains("bytm-has-queue-btns")) {
  952. addQueueButtons(queueItm);
  953. amt++;
  954. }
  955. }
  956. if (amt > 0)
  957. (0,_utils__WEBPACK_IMPORTED_MODULE_2__.log)(`Added buttons to ${amt} new queue ${(0,_utils__WEBPACK_IMPORTED_MODULE_2__.autoPlural)("item", amt)}`);
  958. };
  959. _events__WEBPACK_IMPORTED_MODULE_3__.siteEvents.on("queueChanged", addQueueBtns);
  960. _events__WEBPACK_IMPORTED_MODULE_3__.siteEvents.on("autoplayQueueChanged", addQueueBtns);
  961. const queueItems = document.querySelectorAll("#contents.ytmusic-player-queue > ytmusic-player-queue-item");
  962. if (queueItems.length === 0)
  963. return;
  964. queueItems.forEach(itm => addQueueButtons(itm));
  965. (0,_utils__WEBPACK_IMPORTED_MODULE_2__.log)(`Added buttons to ${queueItems.length} existing queue items`);
  966. }
  967. /**
  968. * Adds the buttons to each item in the current song queue.
  969. * Also observes for changes to add new buttons to new items in the queue.
  970. */
  971. function addQueueButtons(queueItem) {
  972. return __awaiter(this, void 0, void 0, function* () {
  973. const queueBtnsCont = document.createElement("div");
  974. queueBtnsCont.className = "bytm-queue-btn-container";
  975. const songInfo = queueItem.querySelector(".song-info");
  976. if (!songInfo)
  977. return false;
  978. const [songEl, artistEl] = songInfo.querySelectorAll("yt-formatted-string");
  979. const song = songEl.innerText;
  980. const artist = artistEl.innerText;
  981. if (!song || !artist)
  982. return false;
  983. // TODO: display "currently loading" icon
  984. const lyricsBtnElem = (0,_lyrics__WEBPACK_IMPORTED_MODULE_6__.createLyricsBtn)(undefined, false);
  985. lyricsBtnElem.title = "Open this song's lyrics in a new tab";
  986. lyricsBtnElem.style.cursor = "pointer";
  987. lyricsBtnElem.style.visibility = "initial";
  988. lyricsBtnElem.style.display = "inline-flex";
  989. lyricsBtnElem.style.pointerEvents = "initial";
  990. lyricsBtnElem.addEventListener("click", () => __awaiter(this, void 0, void 0, function* () {
  991. let lyricsUrl;
  992. if (songInfo.dataset.bytmLyrics && songInfo.dataset.bytmLyrics.length > 0)
  993. lyricsUrl = songInfo.dataset.bytmLyrics;
  994. else if (songInfo.dataset.bytmLoading !== "true") {
  995. songInfo.dataset.bytmLoading = "true";
  996. const imgEl = lyricsBtnElem.querySelector("img");
  997. imgEl.src = (0,_utils__WEBPACK_IMPORTED_MODULE_2__.getAssetUrl)("loading.gif");
  998. lyricsUrl = yield (0,_lyrics__WEBPACK_IMPORTED_MODULE_6__.getGeniusUrl)((0,_lyrics__WEBPACK_IMPORTED_MODULE_6__.sanitizeArtists)(artist), (0,_lyrics__WEBPACK_IMPORTED_MODULE_6__.sanitizeSong)(song));
  999. songInfo.dataset.bytmLoading = "false";
  1000. imgEl.src = (0,_utils__WEBPACK_IMPORTED_MODULE_2__.getAssetUrl)("external/genius.png");
  1001. if (!lyricsUrl) {
  1002. if (confirm("Couldn't find a lyrics page for this song.\nDo you want to open genius.com to manually search for it?"))
  1003. (0,_utils__WEBPACK_IMPORTED_MODULE_2__.openInNewTab)("https://genius.com/search");
  1004. return;
  1005. }
  1006. songInfo.dataset.bytmLyrics = lyricsUrl;
  1007. }
  1008. lyricsUrl && (0,_utils__WEBPACK_IMPORTED_MODULE_2__.openInNewTab)(lyricsUrl);
  1009. }));
  1010. queueBtnsCont.appendChild(lyricsBtnElem);
  1011. songInfo.appendChild(queueBtnsCont);
  1012. queueItem.classList.add("bytm-has-queue-btns");
  1013. return true;
  1014. });
  1015. }
  1016. //#MARKER better clickable stuff
  1017. // TODO: account for the fact initially the elements might not exist, if the site was opened directly with the /watch path
  1018. function addAnchorImprovements() {
  1019. void 0;
  1020. }
  1021. /***/ }),
  1022. /***/ "./src/features/lyrics.ts":
  1023. /*!********************************!*\
  1024. !*** ./src/features/lyrics.ts ***!
  1025. \********************************/
  1026. /***/ (function(__unused_webpack_module, __webpack_exports__, __webpack_require__) {
  1027. __webpack_require__.r(__webpack_exports__);
  1028. /* harmony export */ __webpack_require__.d(__webpack_exports__, {
  1029. /* harmony export */ addLyricsCacheEntry: function() { return /* binding */ addLyricsCacheEntry; },
  1030. /* harmony export */ addMediaCtrlLyricsBtn: function() { return /* binding */ addMediaCtrlLyricsBtn; },
  1031. /* harmony export */ createLyricsBtn: function() { return /* binding */ createLyricsBtn; },
  1032. /* harmony export */ geniUrlBase: function() { return /* binding */ geniUrlBase; },
  1033. /* harmony export */ getCurrentLyricsUrl: function() { return /* binding */ getCurrentLyricsUrl; },
  1034. /* harmony export */ getGeniusUrl: function() { return /* binding */ getGeniusUrl; },
  1035. /* harmony export */ getLyricsCacheEntry: function() { return /* binding */ getLyricsCacheEntry; },
  1036. /* harmony export */ sanitizeArtists: function() { return /* binding */ sanitizeArtists; },
  1037. /* harmony export */ sanitizeSong: function() { return /* binding */ sanitizeSong; }
  1038. /* harmony export */ });
  1039. /* harmony import */ var _constants__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../constants */ "./src/constants.ts");
  1040. /* harmony import */ var _utils__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../utils */ "./src/utils.ts");
  1041. /* harmony import */ var _lyrics_css__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./lyrics.css */ "./src/features/lyrics.css");
  1042. var __awaiter = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) {
  1043. function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
  1044. return new (P || (P = Promise))(function (resolve, reject) {
  1045. function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
  1046. function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
  1047. function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
  1048. step((generator = generator.apply(thisArg, _arguments || [])).next());
  1049. });
  1050. };
  1051. var __asyncValues = (undefined && undefined.__asyncValues) || function (o) {
  1052. if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined.");
  1053. var m = o[Symbol.asyncIterator], i;
  1054. 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);
  1055. 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); }); }; }
  1056. function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); }
  1057. };
  1058. /** Base URL of geniURL */
  1059. const geniUrlBase = "https://api.sv443.net/geniurl";
  1060. /** GeniURL endpoint that gives song metadata when provided with a `?q` or `?artist` and `?song` parameter - [more info](https://api.sv443.net/geniurl) */
  1061. const geniURLSearchTopUrl = `${geniUrlBase}/search/top`;
  1062. //#MARKER cache
  1063. /** Cache with key format `ARTIST - SONG` and lyrics URLs as values. Used to prevent extraneous requests to geniURL. */
  1064. const lyricsUrlCache = new Map();
  1065. /** How many cache entries can exist at a time - this is used to cap memory usage */
  1066. const maxLyricsCacheSize = 100;
  1067. // TODO: implement this
  1068. /** Returns the lyrics URL from the passed un-/sanitized artist and song name, or undefined if the entry doesn't exist yet */
  1069. function getLyricsCacheEntry(artists, song) {
  1070. return lyricsUrlCache.get(`${sanitizeArtists(artists)} - ${sanitizeSong(song)}`);
  1071. }
  1072. /** Adds the provided entry into the lyrics URL cache */
  1073. function addLyricsCacheEntry(artists, song, lyricsUrl) {
  1074. lyricsUrlCache.set(`${sanitizeArtists(artists)} - ${sanitizeSong(song)}`, lyricsUrl);
  1075. // delete oldest entry if cache gets too big
  1076. if (lyricsUrlCache.size > maxLyricsCacheSize)
  1077. lyricsUrlCache.delete([...lyricsUrlCache.keys()].at(-1));
  1078. }
  1079. //#MARKER media control bar
  1080. let mcCurrentSongTitle = "";
  1081. let mcLyricsButtonAddTries = 0;
  1082. /** Adds a lyrics button to the media controls bar */
  1083. function addMediaCtrlLyricsBtn() {
  1084. const likeContainer = document.querySelector(".middle-controls-buttons ytmusic-like-button-renderer#like-button-renderer");
  1085. if (!likeContainer) {
  1086. mcLyricsButtonAddTries++;
  1087. if (mcLyricsButtonAddTries < _constants__WEBPACK_IMPORTED_MODULE_0__.triesLimit) {
  1088. setTimeout(addMediaCtrlLyricsBtn, _constants__WEBPACK_IMPORTED_MODULE_0__.triesInterval); // TODO: improve this
  1089. return;
  1090. }
  1091. return (0,_utils__WEBPACK_IMPORTED_MODULE_1__.error)(`Couldn't find element to append lyrics buttons to after ${mcLyricsButtonAddTries} tries`);
  1092. }
  1093. const songTitleElem = document.querySelector(".content-info-wrapper > yt-formatted-string");
  1094. // run parallel without awaiting so the MutationObserver below can observe the title element in time
  1095. (() => __awaiter(this, void 0, void 0, function* () {
  1096. const gUrl = yield getCurrentLyricsUrl();
  1097. const linkElem = createLyricsBtn(gUrl !== null && gUrl !== void 0 ? gUrl : undefined);
  1098. linkElem.id = "betterytm-lyrics-button";
  1099. (0,_utils__WEBPACK_IMPORTED_MODULE_1__.log)(`Inserted lyrics button after ${mcLyricsButtonAddTries} tries:`, linkElem);
  1100. (0,_utils__WEBPACK_IMPORTED_MODULE_1__.insertAfter)(likeContainer, linkElem);
  1101. }))();
  1102. mcCurrentSongTitle = songTitleElem.title;
  1103. const onMutation = (mutations) => { var _a, mutations_1, mutations_1_1; return __awaiter(this, void 0, void 0, function* () {
  1104. var _b, e_1, _c, _d;
  1105. try {
  1106. for (_a = true, mutations_1 = __asyncValues(mutations); mutations_1_1 = yield mutations_1.next(), _b = mutations_1_1.done, !_b;) {
  1107. _d = mutations_1_1.value;
  1108. _a = false;
  1109. try {
  1110. const mut = _d;
  1111. const newTitle = mut.target.title;
  1112. if (newTitle !== mcCurrentSongTitle && newTitle.length > 0) {
  1113. const lyricsBtn = document.querySelector("#betterytm-lyrics-button");
  1114. if (!lyricsBtn)
  1115. return;
  1116. (0,_utils__WEBPACK_IMPORTED_MODULE_1__.log)(`Song title changed from '${mcCurrentSongTitle}' to '${newTitle}'`);
  1117. lyricsBtn.style.cursor = "wait";
  1118. lyricsBtn.style.pointerEvents = "none";
  1119. mcCurrentSongTitle = newTitle;
  1120. const url = yield getCurrentLyricsUrl(); // can take a second or two
  1121. if (!url)
  1122. continue;
  1123. lyricsBtn.href = url;
  1124. lyricsBtn.title = "Open the current song's lyrics in a new tab";
  1125. lyricsBtn.style.cursor = "pointer";
  1126. lyricsBtn.style.visibility = "initial";
  1127. lyricsBtn.style.display = "inline-flex";
  1128. lyricsBtn.style.pointerEvents = "initial";
  1129. }
  1130. }
  1131. finally {
  1132. _a = true;
  1133. }
  1134. }
  1135. }
  1136. catch (e_1_1) { e_1 = { error: e_1_1 }; }
  1137. finally {
  1138. try {
  1139. if (!_a && !_b && (_c = mutations_1.return)) yield _c.call(mutations_1);
  1140. }
  1141. finally { if (e_1) throw e_1.error; }
  1142. }
  1143. }); };
  1144. // 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
  1145. const obs = new MutationObserver(onMutation);
  1146. obs.observe(songTitleElem, { attributes: true, attributeFilter: ["title"] });
  1147. }
  1148. //#MARKER utils
  1149. /** Removes everything in parentheses from the passed song name */
  1150. function sanitizeSong(songName) {
  1151. const parensRegex = /\(.+\)/gmi;
  1152. const squareParensRegex = /\[.+\]/gmi;
  1153. // trim right after the song name:
  1154. const sanitized = songName
  1155. .replace(parensRegex, "")
  1156. .replace(squareParensRegex, "");
  1157. return sanitized.trim();
  1158. }
  1159. /** Removes the secondary artist (if it exists) from the passed artists string */
  1160. function sanitizeArtists(artists) {
  1161. artists = artists.split(/\s*\u2022\s*/gmiu)[0]; // split at &bull; [•] character
  1162. if (artists.match(/&/))
  1163. artists = artists.split(/\s*&\s*/gm)[0];
  1164. if (artists.match(/,/))
  1165. artists = artists.split(/,\s*/gm)[0];
  1166. return artists.trim();
  1167. }
  1168. /** Returns the lyrics URL from genius for the currently selected song */
  1169. function getCurrentLyricsUrl() {
  1170. var _a, _b;
  1171. return __awaiter(this, void 0, void 0, function* () {
  1172. try {
  1173. // In videos the video title contains both artist and song title, in "regular" YTM songs, the video title only contains the song title
  1174. const isVideo = typeof ((_a = document.querySelector("ytmusic-player")) === null || _a === void 0 ? void 0 : _a.getAttribute("video-mode_")) === "string";
  1175. const songTitleElem = document.querySelector(".content-info-wrapper > yt-formatted-string");
  1176. const songMetaElem = document.querySelector("span.subtitle > yt-formatted-string:first-child");
  1177. if (!songTitleElem || !songMetaElem || !songTitleElem.title)
  1178. return null;
  1179. const songNameRaw = songTitleElem.title;
  1180. const songName = sanitizeSong(songNameRaw);
  1181. const artistName = sanitizeArtists(songMetaElem.title);
  1182. /** Use when the current song is not a "real YTM song" with a static background, but rather a music video */
  1183. const getGeniusUrlVideo = () => __awaiter(this, void 0, void 0, function* () {
  1184. if (!songName.includes("-")) // for some fucking reason some music videos have YTM-like song title and artist separation, some don't
  1185. return yield getGeniusUrl(artistName, songName);
  1186. const [artist, ...rest] = songName.split("-").map(v => v.trim());
  1187. return yield getGeniusUrl(artist, rest.join(" "));
  1188. });
  1189. // TODO: artist might need further splitting before comma or ampersand
  1190. const url = isVideo ? yield getGeniusUrlVideo() : ((_b = yield getGeniusUrl(artistName, songName)) !== null && _b !== void 0 ? _b : yield getGeniusUrlVideo());
  1191. return url;
  1192. }
  1193. catch (err) {
  1194. (0,_utils__WEBPACK_IMPORTED_MODULE_1__.error)("Couldn't resolve lyrics URL:", err);
  1195. return null;
  1196. }
  1197. });
  1198. }
  1199. /** Fetches the actual lyrics URL from geniURL - **the passed parameters need to be sanitized first!** */
  1200. function getGeniusUrl(artist, song) {
  1201. return __awaiter(this, void 0, void 0, function* () {
  1202. try {
  1203. const startTs = Date.now();
  1204. const fetchUrl = `${geniURLSearchTopUrl}?artist=${encodeURIComponent(artist)}&song=${encodeURIComponent(song)}`;
  1205. (0,_utils__WEBPACK_IMPORTED_MODULE_1__.log)(`Requesting URL from geniURL at '${fetchUrl}'`);
  1206. const result = yield (yield fetch(fetchUrl)).json();
  1207. if (typeof result === "object" && result.error) {
  1208. (0,_utils__WEBPACK_IMPORTED_MODULE_1__.error)("Couldn't fetch lyrics URL:", result.message);
  1209. return undefined;
  1210. }
  1211. const url = result.url;
  1212. (0,_utils__WEBPACK_IMPORTED_MODULE_1__.info)(`Found lyrics URL (after ${Date.now() - startTs}ms): ${url}`);
  1213. addLyricsCacheEntry(artist, song, url);
  1214. return url;
  1215. }
  1216. catch (err) {
  1217. (0,_utils__WEBPACK_IMPORTED_MODULE_1__.error)("Couldn't get lyrics URL due to error:", err);
  1218. return undefined;
  1219. }
  1220. });
  1221. }
  1222. /** Creates the base lyrics button element */
  1223. function createLyricsBtn(geniusUrl, hideIfLoading = true) {
  1224. const linkElem = document.createElement("a");
  1225. linkElem.className = "ytmusic-player-bar bytm-generic-lyrics-btn";
  1226. linkElem.title = geniusUrl ? "Click to open this song's lyrics in a new tab" : "Loading...";
  1227. if (geniusUrl)
  1228. linkElem.href = geniusUrl;
  1229. linkElem.target = "_blank";
  1230. linkElem.rel = "noopener noreferrer";
  1231. linkElem.style.visibility = hideIfLoading && geniusUrl ? "initial" : "hidden";
  1232. linkElem.style.display = hideIfLoading && geniusUrl ? "inline-flex" : "none";
  1233. const imgElem = document.createElement("img");
  1234. imgElem.className = "betterytm-lyrics-img";
  1235. imgElem.src = (0,_utils__WEBPACK_IMPORTED_MODULE_1__.getAssetUrl)("external/genius.png");
  1236. linkElem.appendChild(imgElem);
  1237. return linkElem;
  1238. }
  1239. /***/ }),
  1240. /***/ "./src/features/menu/menu.ts":
  1241. /*!***********************************!*\
  1242. !*** ./src/features/menu/menu.ts ***!
  1243. \***********************************/
  1244. /***/ (function(__unused_webpack_module, __webpack_exports__, __webpack_require__) {
  1245. __webpack_require__.r(__webpack_exports__);
  1246. /* harmony export */ __webpack_require__.d(__webpack_exports__, {
  1247. /* harmony export */ closeMenu: function() { return /* binding */ closeMenu; },
  1248. /* harmony export */ initMenu: function() { return /* binding */ initMenu; },
  1249. /* harmony export */ openMenu: function() { return /* binding */ openMenu; },
  1250. /* harmony export */ setActiveTab: function() { return /* binding */ setActiveTab; }
  1251. /* harmony export */ });
  1252. /* harmony import */ var _constants__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../../constants */ "./src/constants.ts");
  1253. /* harmony import */ var _utils__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../../utils */ "./src/utils.ts");
  1254. /* harmony import */ var _changelog_md__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../../../changelog.md */ "./changelog.md");
  1255. /* harmony import */ var _menu_html__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./menu.html */ "./src/features/menu/menu.html");
  1256. /* harmony import */ var _menu_css__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./menu.css */ "./src/features/menu/menu.css");
  1257. //#MARKER menu
  1258. /**
  1259. * These are the base selector values for the menu tabs
  1260. * Header selector format: `#${baseValue}-header`
  1261. * Content selector format: `#${baseValue}-content`
  1262. */
  1263. const tabsSelectors = {
  1264. options: "bytm-menu-tab-options",
  1265. info: "bytm-menu-tab-info",
  1266. changelog: "bytm-menu-tab-changelog",
  1267. };
  1268. function initMenu() {
  1269. document.addEventListener("DOMContentLoaded", () => {
  1270. // create menu container
  1271. const menuContainer = document.createElement("div");
  1272. menuContainer.id = "bytm-menu-container";
  1273. // add menu html
  1274. menuContainer.innerHTML = _menu_html__WEBPACK_IMPORTED_MODULE_3__["default"];
  1275. document.body.appendChild(menuContainer);
  1276. initMenuContents();
  1277. });
  1278. }
  1279. let menuContTries = 0;
  1280. function initMenuContents() {
  1281. var _a;
  1282. if (!document.querySelector("#bytm-menu-dialog"))
  1283. return menuContTries++ < _constants__WEBPACK_IMPORTED_MODULE_0__.triesLimit
  1284. ? setTimeout(initMenuContents, _constants__WEBPACK_IMPORTED_MODULE_0__.triesInterval)
  1285. : (0,_utils__WEBPACK_IMPORTED_MODULE_1__.error)(`couldn't create menu element after ${_constants__WEBPACK_IMPORTED_MODULE_0__.triesLimit} tries.`);
  1286. // hook events
  1287. for (const tab in tabsSelectors) {
  1288. const selector = tabsSelectors[tab];
  1289. (_a = document.querySelector(`#${selector}-header`)) === null || _a === void 0 ? void 0 : _a.addEventListener("click", () => {
  1290. setActiveTab(tab);
  1291. });
  1292. }
  1293. // init tab contents
  1294. initOptionsContent();
  1295. initInfoContent();
  1296. initChangelogContent();
  1297. }
  1298. /** Opens the specified tab */
  1299. function setActiveTab(tab) {
  1300. const tabs = Object.assign({}, tabsSelectors);
  1301. delete tabs[tab];
  1302. // disable all but new active tab
  1303. for (const disableTab of Object.keys(tabs)) {
  1304. document.querySelector(`#${tabs[disableTab]}-header`).dataset.active = "false";
  1305. document.querySelector(`#${tabs[disableTab]}-content`).dataset.active = "false";
  1306. }
  1307. // enable new active tab
  1308. document.querySelector(`#${tabsSelectors[tab]}-header`).dataset.active = "true";
  1309. document.querySelector(`#${tabsSelectors[tab]}-content`).dataset.active = "true";
  1310. }
  1311. /** Opens the modal menu dialog */
  1312. function openMenu() {
  1313. document.querySelector("#bytm-menu-dialog").showModal();
  1314. }
  1315. /** Closes the modal menu dialog */
  1316. function closeMenu() {
  1317. document.querySelector("#bytm-menu-dialog").close();
  1318. }
  1319. //#MARKER menu tab contents
  1320. function initOptionsContent() {
  1321. const tab = document.querySelector("#bytm-menu-tab-options-content");
  1322. void tab;
  1323. }
  1324. function initInfoContent() {
  1325. const tab = document.querySelector("#bytm-menu-tab-info-content");
  1326. void tab;
  1327. }
  1328. function initChangelogContent() {
  1329. const tab = document.querySelector("#bytm-menu-tab-changelog-content");
  1330. tab.innerHTML = _changelog_md__WEBPACK_IMPORTED_MODULE_2__["default"];
  1331. }
  1332. /***/ }),
  1333. /***/ "./src/features/menu/menu_old.ts":
  1334. /*!***************************************!*\
  1335. !*** ./src/features/menu/menu_old.ts ***!
  1336. \***************************************/
  1337. /***/ (function(__unused_webpack_module, __webpack_exports__, __webpack_require__) {
  1338. __webpack_require__.r(__webpack_exports__);
  1339. /* harmony export */ __webpack_require__.d(__webpack_exports__, {
  1340. /* harmony export */ addMenu: function() { return /* binding */ addMenu; },
  1341. /* harmony export */ closeMenu: function() { return /* binding */ closeMenu; },
  1342. /* harmony export */ openMenu: function() { return /* binding */ openMenu; }
  1343. /* harmony export */ });
  1344. /* harmony import */ var _config__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../../config */ "./src/config.ts");
  1345. /* harmony import */ var _constants__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../../constants */ "./src/constants.ts");
  1346. /* harmony import */ var _index__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../index */ "./src/features/index.ts");
  1347. /* harmony import */ var _utils__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../../utils */ "./src/utils.ts");
  1348. var __awaiter = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) {
  1349. function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
  1350. return new (P || (P = Promise))(function (resolve, reject) {
  1351. function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
  1352. function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
  1353. function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
  1354. step((generator = generator.apply(thisArg, _arguments || [])).next());
  1355. });
  1356. };
  1357. //#MARKER menu
  1358. /**
  1359. * Adds an element to open the BetterYTM menu
  1360. * @deprecated TODO: replace in v1.1.0 - see https://github.com/Sv443/BetterYTM/issues/23
  1361. */
  1362. function addMenu() {
  1363. var _a, _b;
  1364. return __awaiter(this, void 0, void 0, function* () {
  1365. // bg & menu
  1366. const backgroundElem = document.createElement("div");
  1367. backgroundElem.id = "betterytm-menu-bg";
  1368. backgroundElem.title = "Click here to close the menu";
  1369. backgroundElem.style.visibility = "hidden";
  1370. backgroundElem.style.display = "none";
  1371. backgroundElem.addEventListener("click", (e) => {
  1372. if (e.target.id === "betterytm-menu-bg")
  1373. closeMenu();
  1374. });
  1375. document.body.addEventListener("keydown", ({ key }) => {
  1376. if (key === "Escape")
  1377. closeMenu();
  1378. });
  1379. const menuContainer = document.createElement("div");
  1380. menuContainer.title = "";
  1381. menuContainer.id = "betterytm-menu";
  1382. menuContainer.style.borderRadius = "15px";
  1383. menuContainer.style.display = "flex";
  1384. menuContainer.style.flexDirection = "column";
  1385. menuContainer.style.justifyContent = "space-between";
  1386. // title
  1387. const titleCont = document.createElement("div");
  1388. titleCont.style.padding = "8px 20px 15px 8px";
  1389. titleCont.style.display = "flex";
  1390. titleCont.style.justifyContent = "space-between";
  1391. titleCont.id = "betterytm-menu-titlecont";
  1392. const titleElem = document.createElement("h2");
  1393. titleElem.id = "betterytm-menu-title";
  1394. titleElem.innerText = `${_constants__WEBPACK_IMPORTED_MODULE_1__.scriptInfo.name} - Configuration`;
  1395. const linksCont = document.createElement("div");
  1396. linksCont.id = "betterytm-menu-linkscont";
  1397. const addLink = (imgSrc, href, title) => {
  1398. const anchorElem = document.createElement("a");
  1399. anchorElem.className = "betterytm-menu-link";
  1400. anchorElem.rel = "noopener noreferrer";
  1401. anchorElem.target = "_blank";
  1402. anchorElem.href = href;
  1403. anchorElem.title = title;
  1404. anchorElem.style.marginLeft = "10px";
  1405. const imgElem = document.createElement("img");
  1406. imgElem.className = "betterytm-menu-img";
  1407. imgElem.src = imgSrc;
  1408. imgElem.style.width = "32px";
  1409. imgElem.style.height = "32px";
  1410. anchorElem.appendChild(imgElem);
  1411. linksCont.appendChild(anchorElem);
  1412. };
  1413. 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`);
  1414. addLink((0,_utils__WEBPACK_IMPORTED_MODULE_3__.getAssetUrl)("external/greasyfork.png"), "https://greasyfork.org/xyz", `${_constants__WEBPACK_IMPORTED_MODULE_1__.scriptInfo.name} on GreasyFork`);
  1415. const closeElem = document.createElement("img");
  1416. closeElem.id = "betterytm-menu-close";
  1417. closeElem.src = (0,_utils__WEBPACK_IMPORTED_MODULE_3__.getAssetUrl)("close.png");
  1418. closeElem.title = "Click to close the menu";
  1419. closeElem.style.marginLeft = "50px";
  1420. closeElem.style.width = "32px";
  1421. closeElem.style.height = "32px";
  1422. closeElem.addEventListener("click", closeMenu);
  1423. linksCont.appendChild(closeElem);
  1424. titleCont.appendChild(titleElem);
  1425. titleCont.appendChild(linksCont);
  1426. // TODO: features
  1427. const featuresCont = document.createElement("div");
  1428. featuresCont.id = "betterytm-menu-opts";
  1429. featuresCont.style.display = "flex";
  1430. featuresCont.style.flexDirection = "column";
  1431. featuresCont.style.overflowY = "auto";
  1432. /** Gets called whenever the feature config is changed */
  1433. const confChanged = (key, initialVal, newVal) => __awaiter(this, void 0, void 0, function* () {
  1434. const fmt = (val) => typeof val === "object" ? JSON.stringify(val) : String(val);
  1435. (0,_utils__WEBPACK_IMPORTED_MODULE_3__.info)(`Feature config changed, key '${key}' from value '${fmt(initialVal)}' to '${fmt(newVal)}'`);
  1436. const featConf = Object.assign({}, yield (0,_config__WEBPACK_IMPORTED_MODULE_0__.getFeatures)());
  1437. featConf[key] = newVal;
  1438. yield (0,_config__WEBPACK_IMPORTED_MODULE_0__.saveFeatureConf)(featConf);
  1439. (0,_utils__WEBPACK_IMPORTED_MODULE_3__.log)("Saved feature config changes:\n", yield GM.getValue("betterytm-config"));
  1440. });
  1441. const features = yield (0,_config__WEBPACK_IMPORTED_MODULE_0__.getFeatures)();
  1442. for (const key in features) {
  1443. const ftInfo = _index__WEBPACK_IMPORTED_MODULE_2__.featInfo[key];
  1444. // @ts-ignore
  1445. if (!ftInfo || ftInfo.visible === false)
  1446. continue;
  1447. const { desc, type, default: ftDefault } = ftInfo;
  1448. // @ts-ignore
  1449. const step = (_a = ftInfo === null || ftInfo === void 0 ? void 0 : ftInfo.step) !== null && _a !== void 0 ? _a : undefined;
  1450. const val = features[key];
  1451. const initialVal = (_b = val !== null && val !== void 0 ? val : ftDefault) !== null && _b !== void 0 ? _b : undefined;
  1452. const ftConfElem = document.createElement("div");
  1453. ftConfElem.id = `betterytm-ftconf-${key}`;
  1454. ftConfElem.style.display = "flex";
  1455. ftConfElem.style.flexDirection = "row";
  1456. ftConfElem.style.justifyContent = "space-between";
  1457. ftConfElem.style.padding = "8px 20px";
  1458. {
  1459. const textElem = document.createElement("span");
  1460. textElem.style.display = "inline-block";
  1461. textElem.style.fontSize = "15px";
  1462. textElem.innerText = desc;
  1463. ftConfElem.appendChild(textElem);
  1464. }
  1465. {
  1466. let inputType = "text";
  1467. switch (type) {
  1468. case "toggle":
  1469. inputType = "checkbox";
  1470. break;
  1471. case "slider":
  1472. inputType = "range";
  1473. break;
  1474. case "number":
  1475. inputType = "number";
  1476. break;
  1477. }
  1478. const inputElemId = `betterytm-ftconf-${key}-input`;
  1479. const ctrlElem = document.createElement("span");
  1480. ctrlElem.style.display = "inline-block";
  1481. ctrlElem.style.whiteSpace = "nowrap";
  1482. const inputElem = document.createElement("input");
  1483. inputElem.id = inputElemId;
  1484. inputElem.style.marginRight = "37px";
  1485. inputElem.type = inputType;
  1486. if (type === "toggle")
  1487. inputElem.style.marginLeft = "5px";
  1488. if (typeof initialVal !== "undefined")
  1489. inputElem.value = String(initialVal);
  1490. if (type === "number" && step)
  1491. inputElem.step = step;
  1492. // @ts-ignore
  1493. if (ftInfo.min && ftInfo.max) {
  1494. // @ts-ignore
  1495. inputElem.min = ftInfo.min;
  1496. // @ts-ignore
  1497. inputElem.max = ftInfo.max;
  1498. }
  1499. if (type === "toggle" && typeof initialVal !== "undefined")
  1500. inputElem.checked = Boolean(initialVal);
  1501. // @ts-ignore
  1502. const unitTxt = typeof ftInfo.unit === "string" ? " " + ftInfo.unit : "";
  1503. const fmtVal = (v) => String(v).trim();
  1504. const toggleLabelText = (toggled) => toggled ? "On" : "Off";
  1505. let labelElem;
  1506. if (type === "slider") {
  1507. labelElem = document.createElement("label");
  1508. labelElem.classList.add("betterytm-ftconf-label");
  1509. labelElem.style.marginRight = "20px";
  1510. labelElem.style.fontSize = "16px";
  1511. labelElem.htmlFor = inputElemId;
  1512. labelElem.innerText = fmtVal(initialVal) + unitTxt;
  1513. inputElem.addEventListener("input", () => {
  1514. if (labelElem)
  1515. labelElem.innerText = fmtVal(parseInt(inputElem.value)) + unitTxt;
  1516. });
  1517. }
  1518. else if (type === "toggle") {
  1519. labelElem = document.createElement("label");
  1520. labelElem.classList.add("betterytm-ftconf-label");
  1521. labelElem.style.paddingLeft = "10px";
  1522. labelElem.style.paddingRight = "5px";
  1523. labelElem.style.fontSize = "16px";
  1524. labelElem.htmlFor = inputElemId;
  1525. labelElem.innerText = toggleLabelText(Boolean(initialVal)) + unitTxt;
  1526. inputElem.addEventListener("input", () => {
  1527. if (labelElem)
  1528. labelElem.innerText = toggleLabelText(inputElem.checked) + unitTxt;
  1529. });
  1530. }
  1531. inputElem.addEventListener("input", () => {
  1532. let v = parseInt(inputElem.value);
  1533. if (isNaN(v))
  1534. v = Number(inputElem.value);
  1535. if (typeof initialVal !== "undefined")
  1536. confChanged(key, initialVal, (type !== "toggle" ? v : inputElem.checked));
  1537. });
  1538. const resetElem = document.createElement("button");
  1539. resetElem.innerText = "Reset";
  1540. resetElem.addEventListener("click", () => {
  1541. inputElem[type !== "toggle" ? "value" : "checked"] = ftDefault;
  1542. if (labelElem) {
  1543. if (type === "toggle")
  1544. labelElem.innerText = toggleLabelText(inputElem.checked);
  1545. else
  1546. labelElem.innerText = fmtVal(parseInt(inputElem.value));
  1547. }
  1548. if (typeof initialVal !== "undefined")
  1549. confChanged(key, initialVal, ftDefault);
  1550. });
  1551. labelElem && ctrlElem.appendChild(labelElem);
  1552. ctrlElem.appendChild(inputElem);
  1553. ctrlElem.appendChild(resetElem);
  1554. ftConfElem.appendChild(ctrlElem);
  1555. }
  1556. featuresCont.appendChild(ftConfElem);
  1557. }
  1558. const footerElem = document.createElement("div");
  1559. footerElem.id = "betterytm-menu-footer";
  1560. footerElem.style.marginTop = "20px";
  1561. footerElem.style.fontSize = "17px";
  1562. footerElem.style.textDecoration = "underline";
  1563. footerElem.style.padding = "10px 20px";
  1564. footerElem.style.position = "sticky";
  1565. footerElem.style.backgroundColor = "var(--bytm-menu-bg)";
  1566. footerElem.style.bottom = "0";
  1567. footerElem.innerText = "You need to reload the page to apply changes.";
  1568. const reloadElem = document.createElement("button");
  1569. reloadElem.style.marginLeft = "20px";
  1570. reloadElem.innerText = "Reload now";
  1571. reloadElem.title = "Click to reload the page";
  1572. reloadElem.addEventListener("click", () => location.reload());
  1573. footerElem.appendChild(reloadElem);
  1574. featuresCont.appendChild(footerElem);
  1575. // finalize
  1576. const menuBody = document.createElement("div");
  1577. menuBody.id = "betterytm-menu-body";
  1578. menuBody.appendChild(titleCont);
  1579. menuBody.appendChild(featuresCont);
  1580. const versionCont = document.createElement("div");
  1581. versionCont.style.display = "flex";
  1582. versionCont.style.justifyContent = "space-around";
  1583. versionCont.style.fontSize = "1.15em";
  1584. versionCont.style.marginTop = "10px";
  1585. versionCont.style.marginBottom = "5px";
  1586. const versionElem = document.createElement("span");
  1587. versionElem.id = "betterytm-menu-version";
  1588. versionElem.innerText = `v${_constants__WEBPACK_IMPORTED_MODULE_1__.scriptInfo.version}`;
  1589. versionCont.appendChild(versionElem);
  1590. featuresCont.appendChild(versionCont);
  1591. menuContainer.appendChild(menuBody);
  1592. menuContainer.appendChild(versionCont);
  1593. backgroundElem.appendChild(menuContainer);
  1594. document.body.appendChild(backgroundElem);
  1595. // add style
  1596. const menuStyle = `\
  1597. :root {
  1598. --bytm-menu-bg: #212121;
  1599. }
  1600. #betterytm-menu-bg {
  1601. display: block;
  1602. position: fixed;
  1603. width: 100vw;
  1604. height: 100vh;
  1605. top: 0;
  1606. left: 0;
  1607. z-index: 15;
  1608. background-color: rgba(0, 0, 0, 0.6);
  1609. }
  1610. /* TODO:FIXME: needs better positioning (vw and vh === "big no no") */
  1611. #betterytm-menu {
  1612. display: inline-block;
  1613. position: fixed;
  1614. width: 50vw;
  1615. height: auto;
  1616. left: 25vw;
  1617. top: 10vh;
  1618. z-index: 16;
  1619. padding: 8px;
  1620. color: #fff;
  1621. background-color: var(--bytm-menu-bg);
  1622. }
  1623. #betterytm-menu-opts {
  1624. max-height: 70vh;
  1625. overflow: auto;
  1626. }
  1627. #betterytm-menu-titlecont {
  1628. display: flex;
  1629. }
  1630. #betterytm-menu-title {
  1631. font-size: 20px;
  1632. margin-top: 5px;
  1633. margin-bottom: 8px;
  1634. }
  1635. #betterytm-menu-linkscont {
  1636. display: flex;
  1637. }
  1638. .betterytm-menu-link {
  1639. display: inline-block;
  1640. }
  1641. /*.betterytm-menu-img {
  1642. }*/
  1643. #betterytm-menu-close {
  1644. cursor: pointer;
  1645. }
  1646. .betterytm-ftconf-label {
  1647. user-select: none;
  1648. }`;
  1649. (0,_utils__WEBPACK_IMPORTED_MODULE_3__.log)("Added menu elem:", backgroundElem);
  1650. (0,_utils__WEBPACK_IMPORTED_MODULE_3__.addGlobalStyle)(menuStyle, "menu");
  1651. });
  1652. }
  1653. function closeMenu() {
  1654. const menuBg = document.querySelector("#betterytm-menu-bg");
  1655. menuBg.style.visibility = "hidden";
  1656. menuBg.style.display = "none";
  1657. }
  1658. function openMenu() {
  1659. const menuBg = document.querySelector("#betterytm-menu-bg");
  1660. menuBg.style.visibility = "visible";
  1661. menuBg.style.display = "block";
  1662. }
  1663. /***/ }),
  1664. /***/ "./src/utils.ts":
  1665. /*!**********************!*\
  1666. !*** ./src/utils.ts ***!
  1667. \**********************/
  1668. /***/ (function(__unused_webpack_module, __webpack_exports__, __webpack_require__) {
  1669. __webpack_require__.r(__webpack_exports__);
  1670. /* harmony export */ __webpack_require__.d(__webpack_exports__, {
  1671. /* harmony export */ addGlobalStyle: function() { return /* binding */ addGlobalStyle; },
  1672. /* harmony export */ autoPlural: function() { return /* binding */ autoPlural; },
  1673. /* harmony export */ dbg: function() { return /* binding */ dbg; },
  1674. /* harmony export */ error: function() { return /* binding */ error; },
  1675. /* harmony export */ getAssetUrl: function() { return /* binding */ getAssetUrl; },
  1676. /* harmony export */ getDomain: function() { return /* binding */ getDomain; },
  1677. /* harmony export */ getUnsafeWindow: function() { return /* binding */ getUnsafeWindow; },
  1678. /* harmony export */ getVideoTime: function() { return /* binding */ getVideoTime; },
  1679. /* harmony export */ info: function() { return /* binding */ info; },
  1680. /* harmony export */ insertAfter: function() { return /* binding */ insertAfter; },
  1681. /* harmony export */ log: function() { return /* binding */ log; },
  1682. /* harmony export */ openInNewTab: function() { return /* binding */ openInNewTab; },
  1683. /* harmony export */ setLogLevel: function() { return /* binding */ setLogLevel; },
  1684. /* harmony export */ warn: function() { return /* binding */ warn; }
  1685. /* harmony export */ });
  1686. /* harmony import */ var _constants__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./constants */ "./src/constants.ts");
  1687. //#SECTION logging
  1688. let curLogLevel = 1;
  1689. /** Sets the current log level. 0 = Debug, 1 = Info */
  1690. function setLogLevel(level) {
  1691. curLogLevel = level;
  1692. }
  1693. /** Extracts the log level from the last item from spread arguments - returns 1 if the last item is not a number or too low or high */
  1694. function getLogLevel(args) {
  1695. const minLogLvl = 0, maxLogLvl = 1;
  1696. if (typeof args.at(-1) === "number")
  1697. return Math.max(Math.min(args.splice(args.length - 1)[0], minLogLvl), maxLogLvl);
  1698. return 1;
  1699. }
  1700. /** Common prefix to be able to tell logged messages apart and filter them in devtools */
  1701. const consPrefix = `[${_constants__WEBPACK_IMPORTED_MODULE_0__.scriptInfo.name}]`;
  1702. const consPrefixDbg = `[${_constants__WEBPACK_IMPORTED_MODULE_0__.scriptInfo.name}/#DEBUG]`;
  1703. /**
  1704. * Logs string-compatible values to the console, as long as the log level is sufficient.
  1705. * @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.
  1706. */
  1707. function log(...args) {
  1708. if (curLogLevel <= getLogLevel(args))
  1709. console.log(consPrefix, ...args);
  1710. }
  1711. /**
  1712. * Logs string-compatible values to the console as info, as long as the log level is sufficient.
  1713. * @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.
  1714. */
  1715. function info(...args) {
  1716. if (curLogLevel <= getLogLevel(args))
  1717. console.info(consPrefix, ...args);
  1718. }
  1719. /**
  1720. * Logs string-compatible values to the console as a warning, as long as the log level is sufficient.
  1721. * @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.
  1722. */
  1723. function warn(...args) {
  1724. if (curLogLevel <= getLogLevel(args))
  1725. console.warn(consPrefix, ...args);
  1726. }
  1727. /** Logs string-compatible values to the console as an error. */
  1728. function error(...args) {
  1729. console.error(consPrefix, ...args);
  1730. }
  1731. /** Logs string-compatible values to the console, intended for debugging only */
  1732. function dbg(...args) {
  1733. console.log(consPrefixDbg, ...args);
  1734. }
  1735. //#SECTION video time
  1736. /**
  1737. * Returns the current video time in seconds
  1738. * @param force Set to true to dispatch mouse movement events in case the video time can't be estimated
  1739. * @returns Returns null if the video time is unavailable
  1740. */
  1741. function getVideoTime(force = false) {
  1742. const domain = getDomain();
  1743. try {
  1744. if (domain === "ytm") {
  1745. const pbEl = document.querySelector("#progress-bar");
  1746. return !isNaN(Number(pbEl.value)) ? Number(pbEl.value) : null;
  1747. }
  1748. else if (domain === "yt") {
  1749. // YT doesn't update the progress bar when it's hidden (YTM doesn't hide it) so TODO: come up with some solution here
  1750. // Possible solution:
  1751. // - Use MutationObserver to detect when attributes of progress bar (selector `div.ytp-progress-bar[role="slider"]`) change
  1752. // - Wait until the attribute increments, then save the value of `aria-valuenow` and the current system time to memory
  1753. // - When site switch hotkey is pressed, take saved `aria-valuenow` value and add the difference between saved system time and current system time
  1754. // - If no value is present, use the script from `dev/ytForceShowVideoTime.js` to simulate mouse movement to force the element to update
  1755. // - Subtract one or two seconds to make up for rounding errors
  1756. // - profit
  1757. // if(!ytCurrentVideoTime) {
  1758. // ytForceShowVideoTime();
  1759. // const videoTime = document.querySelector("#TODO")?.getAttribute("aria-valuenow") ?? null;
  1760. // }
  1761. void [force, ytForceShowVideoTime];
  1762. return null;
  1763. }
  1764. return null;
  1765. }
  1766. catch (err) {
  1767. error("Couldn't get video time due to error:", err);
  1768. return null;
  1769. }
  1770. }
  1771. /** Sends events that force the video controls to become visible for about 3 seconds */
  1772. function ytForceShowVideoTime() {
  1773. const player = document.querySelector("#movie_player");
  1774. if (!player)
  1775. return false;
  1776. const defaultProps = {
  1777. // needed because otherwise YTM errors out - see https://github.com/Sv443/BetterYTM/issues/18#show_issue
  1778. view: getUnsafeWindow(),
  1779. bubbles: true,
  1780. cancelable: false,
  1781. };
  1782. player.dispatchEvent(new MouseEvent("mouseenter", defaultProps));
  1783. const { x, y, width, height } = player.getBoundingClientRect();
  1784. const screenY = Math.round(y + height / 2);
  1785. const screenX = x + Math.min(50, Math.round(width / 3));
  1786. player.dispatchEvent(new MouseEvent("mousemove", Object.assign(Object.assign({}, defaultProps), { screenY,
  1787. screenX, movementX: 5, movementY: 0 })));
  1788. setTimeout(() => {
  1789. player.dispatchEvent(new MouseEvent("mouseleave", defaultProps));
  1790. }, 4000);
  1791. return true;
  1792. }
  1793. //#SECTION DOM
  1794. /**
  1795. * Inserts `afterNode` as a sibling just after the provided `beforeNode`
  1796. * @param beforeNode
  1797. * @param afterNode
  1798. * @returns Returns the `afterNode`
  1799. */
  1800. function insertAfter(beforeNode, afterNode) {
  1801. var _a;
  1802. (_a = beforeNode.parentNode) === null || _a === void 0 ? void 0 : _a.insertBefore(afterNode, beforeNode.nextSibling);
  1803. return afterNode;
  1804. }
  1805. /**
  1806. * Adds global CSS style through a `<style>` element in the document's `<head>`
  1807. * @param style CSS string
  1808. * @param ref Reference name that is included in the `<style>`'s ID - prefixed with `betterytm-style-` - defaults to a random number if left undefined
  1809. */
  1810. function addGlobalStyle(style, ref) {
  1811. if (typeof ref !== "string" || ref.length === 0)
  1812. ref = String(Math.floor(Math.random() * 10000));
  1813. const styleElem = document.createElement("style");
  1814. styleElem.id = `betterytm-style-${ref}`;
  1815. styleElem.innerHTML = style;
  1816. document.head.appendChild(styleElem);
  1817. log(`Inserted global style with ref '${ref}':`, styleElem);
  1818. }
  1819. //#SECTION misc
  1820. /**
  1821. * Creates an invisible anchor with _blank target and clicks it.
  1822. * This has to be run in relatively quick succession to a user interaction event, else the browser rejects it.
  1823. */
  1824. function openInNewTab(href) {
  1825. const openElem = document.createElement("a");
  1826. Object.assign(openElem, {
  1827. className: "betterytm-open-in-new-tab",
  1828. target: "_blank",
  1829. rel: "noopener noreferrer",
  1830. href,
  1831. style: {
  1832. visibility: "hidden",
  1833. },
  1834. });
  1835. document.body.appendChild(openElem);
  1836. openElem.click();
  1837. // timeout just to be safe
  1838. setTimeout(() => openElem.remove(), 200);
  1839. }
  1840. /**
  1841. * Returns `unsafeWindow` if it is available, otherwise falls back to just `window`
  1842. * unsafeWindow is sometimes needed because otherwise YTM errors out - see [this issue](https://github.com/Sv443/BetterYTM/issues/18#show_issue)
  1843. */
  1844. function getUnsafeWindow() {
  1845. try {
  1846. // throws ReferenceError if the "@grant unsafeWindow" isn't present
  1847. return unsafeWindow;
  1848. }
  1849. catch (e) {
  1850. return window;
  1851. }
  1852. }
  1853. /**
  1854. * Returns the current domain as a constant string representation
  1855. * @throws Throws if script runs on an unexpected website
  1856. */
  1857. function getDomain() {
  1858. const { hostname } = new URL(location.href);
  1859. if (hostname.includes("music.youtube"))
  1860. return "ytm";
  1861. else if (hostname.includes("youtube"))
  1862. return "yt";
  1863. else
  1864. throw new Error("BetterYTM is running on an unexpected website. Please don't tamper with the @match directives in the userscript header.");
  1865. }
  1866. /** Returns the URL of the asset hosted on GitHub at the specified relative `path` (starting at `ROOT/assets/`) */
  1867. function getAssetUrl(path) {
  1868. return `https://raw.githubusercontent.com/Sv443/BetterYTM/${_constants__WEBPACK_IMPORTED_MODULE_0__.branch}/assets/${path}`;
  1869. }
  1870. /**
  1871. * Automatically appends an `s` to the passed `word`, if `num` is not equal to 1
  1872. * @param word A word in singular form, to auto-convert to plural
  1873. * @param num If this is an array, the amount of items is used
  1874. */
  1875. function autoPlural(word, num) {
  1876. if (Array.isArray(num))
  1877. num = num.length;
  1878. return `${word}${num === 1 ? "" : "s"}`;
  1879. }
  1880. /***/ })
  1881. /******/ });
  1882. /************************************************************************/
  1883. /******/ // The module cache
  1884. /******/ var __webpack_module_cache__ = {};
  1885. /******/
  1886. /******/ // The require function
  1887. /******/ function __webpack_require__(moduleId) {
  1888. /******/ // Check if module is in cache
  1889. /******/ var cachedModule = __webpack_module_cache__[moduleId];
  1890. /******/ if (cachedModule !== undefined) {
  1891. /******/ return cachedModule.exports;
  1892. /******/ }
  1893. /******/ // Create a new module (and put it into the cache)
  1894. /******/ var module = __webpack_module_cache__[moduleId] = {
  1895. /******/ // no module.id needed
  1896. /******/ // no module.loaded needed
  1897. /******/ exports: {}
  1898. /******/ };
  1899. /******/
  1900. /******/ // Execute the module function
  1901. /******/ __webpack_modules__[moduleId](module, module.exports, __webpack_require__);
  1902. /******/
  1903. /******/ // Return the exports of the module
  1904. /******/ return module.exports;
  1905. /******/ }
  1906. /******/
  1907. /************************************************************************/
  1908. /******/ /* webpack/runtime/define property getters */
  1909. /******/ !function() {
  1910. /******/ // define getter functions for harmony exports
  1911. /******/ __webpack_require__.d = function(exports, definition) {
  1912. /******/ for(var key in definition) {
  1913. /******/ if(__webpack_require__.o(definition, key) && !__webpack_require__.o(exports, key)) {
  1914. /******/ Object.defineProperty(exports, key, { enumerable: true, get: definition[key] });
  1915. /******/ }
  1916. /******/ }
  1917. /******/ };
  1918. /******/ }();
  1919. /******/
  1920. /******/ /* webpack/runtime/hasOwnProperty shorthand */
  1921. /******/ !function() {
  1922. /******/ __webpack_require__.o = function(obj, prop) { return Object.prototype.hasOwnProperty.call(obj, prop); }
  1923. /******/ }();
  1924. /******/
  1925. /******/ /* webpack/runtime/make namespace object */
  1926. /******/ !function() {
  1927. /******/ // define __esModule on exports
  1928. /******/ __webpack_require__.r = function(exports) {
  1929. /******/ if(typeof Symbol !== 'undefined' && Symbol.toStringTag) {
  1930. /******/ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
  1931. /******/ }
  1932. /******/ Object.defineProperty(exports, '__esModule', { value: true });
  1933. /******/ };
  1934. /******/ }();
  1935. /******/
  1936. /************************************************************************/
  1937. var __webpack_exports__ = {};
  1938. // This entry need to be wrapped in an IIFE because it need to be isolated against other modules in the chunk.
  1939. !function() {
  1940. /*!**********************!*\
  1941. !*** ./src/index.ts ***!
  1942. \**********************/
  1943. __webpack_require__.r(__webpack_exports__);
  1944. /* harmony import */ var _config__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./config */ "./src/config.ts");
  1945. /* harmony import */ var _constants__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./constants */ "./src/constants.ts");
  1946. /* harmony import */ var _utils__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./utils */ "./src/utils.ts");
  1947. /* harmony import */ var _events__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./events */ "./src/events.ts");
  1948. /* harmony import */ var _features_index__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./features/index */ "./src/features/index.ts");
  1949. var __awaiter = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) {
  1950. function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
  1951. return new (P || (P = Promise))(function (resolve, reject) {
  1952. function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
  1953. function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
  1954. function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
  1955. step((generator = generator.apply(thisArg, _arguments || [])).next());
  1956. });
  1957. };
  1958. // TODO: add some style
  1959. 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}`);
  1960. console.log(`Powered by lots of ambition and my song metadata API: ${_features_index__WEBPACK_IMPORTED_MODULE_4__.geniUrlBase}`);
  1961. const domain = (0,_utils__WEBPACK_IMPORTED_MODULE_2__.getDomain)();
  1962. /** Stuff that needs to be called ASAP, before anything async happens */
  1963. function preInit() {
  1964. (0,_utils__WEBPACK_IMPORTED_MODULE_2__.setLogLevel)(_constants__WEBPACK_IMPORTED_MODULE_1__.logLevel);
  1965. if (domain === "ytm")
  1966. (0,_features_index__WEBPACK_IMPORTED_MODULE_4__.initBeforeUnloadHook)();
  1967. init();
  1968. }
  1969. function init() {
  1970. return __awaiter(this, void 0, void 0, function* () {
  1971. yield (0,_features_index__WEBPACK_IMPORTED_MODULE_4__.preInitLayout)();
  1972. try {
  1973. document.addEventListener("DOMContentLoaded", onDomLoad);
  1974. }
  1975. catch (err) {
  1976. console.error(`${_constants__WEBPACK_IMPORTED_MODULE_1__.scriptInfo.name} - General Error:`, err);
  1977. }
  1978. try {
  1979. void ["TODO(v1.1):", _features_index__WEBPACK_IMPORTED_MODULE_4__.initMenu];
  1980. // initMenu();
  1981. }
  1982. catch (err) {
  1983. (0,_utils__WEBPACK_IMPORTED_MODULE_2__.error)("Couldn't initialize menu:", err);
  1984. }
  1985. });
  1986. }
  1987. /** Called when the DOM has finished loading and can be queried and altered by the userscript */
  1988. function onDomLoad() {
  1989. return __awaiter(this, void 0, void 0, function* () {
  1990. // post-build these double quotes are replaced by backticks
  1991. (0,_utils__WEBPACK_IMPORTED_MODULE_2__.addGlobalStyle)(`/*!***************************************************************************!*\
  1992. !*** css ./node_modules/css-loader/dist/cjs.js!./src/features/layout.css ***!
  1993. \***************************************************************************/
  1994. /* #MARKER watermark */
  1995. #betterytm-watermark {
  1996. font-size: 10px;
  1997. display: inline-block;
  1998. position: absolute;
  1999. left: 45px;
  2000. top: 46px;
  2001. z-index: 10;
  2002. color: white;
  2003. text-decoration: none;
  2004. cursor: pointer;
  2005. }
  2006. @media(max-width: 615px) {
  2007. #betterytm-watermark {
  2008. display: none;
  2009. }
  2010. }
  2011. #betterytm-watermark:hover {
  2012. text-decoration: underline;
  2013. }
  2014. /* #MARKER queue buttons */
  2015. /* TODO: */
  2016. .side-panel.modular ytmusic-player-queue-item .song-info.ytmusic-player-queue-item {
  2017. position: relative;
  2018. }
  2019. .side-panel.modular ytmusic-player-queue-item .song-info .bytm-queue-btn-container {
  2020. display: none;
  2021. position: absolute;
  2022. right: 0;
  2023. }
  2024. .side-panel.modular ytmusic-player-queue-item:hover .song-info .bytm-queue-btn-container {
  2025. display: inline-block;
  2026. }
  2027. /*!***************************************************************************!*\
  2028. !*** css ./node_modules/css-loader/dist/cjs.js!./src/features/lyrics.css ***!
  2029. \***************************************************************************/
  2030. .bytm-generic-lyrics-btn {
  2031. align-items: center;
  2032. justify-content: center;
  2033. position: relative;
  2034. vertical-align: middle;
  2035. margin-left: 8px;
  2036. width: 40px;
  2037. height: 40px;
  2038. border-radius: 100%;
  2039. background-color: transparent;
  2040. }
  2041. .bytm-generic-lyrics-btn:hover {
  2042. background-color: var(--yt-spec-10-percent-layer, #1d1d1d);
  2043. }
  2044. .betterytm-lyrics-img {
  2045. display: inline-block;
  2046. z-index: 10;
  2047. width: 24px;
  2048. height: 24px;
  2049. padding: 5px;
  2050. }
  2051. /*!******************************************************************************!*\
  2052. !*** css ./node_modules/css-loader/dist/cjs.js!./src/features/menu/menu.css ***!
  2053. \******************************************************************************/
  2054. /* #bytm-menu-backdrop {
  2055. display: none;
  2056. flex-direction: column;
  2057. justify-content: center;
  2058. align-items: center;
  2059. }
  2060. #bytm-menu-backdrop[data-menu-open="true"] {
  2061. display: flex;
  2062. } */
  2063. #bytm-menu-header-container {
  2064. display: flex;
  2065. justify-content: flex-start;
  2066. align-items: center;
  2067. border-color: #ffffff;
  2068. border-style: none solid none none;
  2069. }
  2070. .bytm-menu-header-option {
  2071. display: "flex";
  2072. justify-content: center;
  2073. align-items: center;
  2074. border-color: #ffffff;
  2075. border-style: solid none solid none;
  2076. }
  2077. #bytm-menu-header-option h3 {
  2078. margin: 0;
  2079. }
  2080. .bytm-menu-tab[data-active="true"] {
  2081. display: none;
  2082. }
  2083. .bytm-menu-tab[data-active="false"] {
  2084. display: none;
  2085. }
  2086. /*# sourceMappingURL=main.css.map*/`, "global");
  2087. const features = yield (0,_config__WEBPACK_IMPORTED_MODULE_0__.loadFeatureConf)();
  2088. (0,_utils__WEBPACK_IMPORTED_MODULE_2__.log)(`Initializing features for domain '${domain}'`);
  2089. try {
  2090. if (domain === "ytm") {
  2091. (0,_events__WEBPACK_IMPORTED_MODULE_3__.initSiteEvents)();
  2092. if (features.arrowKeySupport)
  2093. (0,_features_index__WEBPACK_IMPORTED_MODULE_4__.initArrowKeySkip)();
  2094. if (features.removeUpgradeTab)
  2095. (0,_features_index__WEBPACK_IMPORTED_MODULE_4__.removeUpgradeTab)();
  2096. if (features.watermarkEnabled)
  2097. (0,_features_index__WEBPACK_IMPORTED_MODULE_4__.addWatermark)();
  2098. if (features.geniusLyrics)
  2099. (0,_features_index__WEBPACK_IMPORTED_MODULE_4__.addMediaCtrlLyricsBtn)();
  2100. if (features.queueButtons)
  2101. (0,_features_index__WEBPACK_IMPORTED_MODULE_4__.initQueueButtons)();
  2102. if (typeof features.volumeSliderSize === "number")
  2103. (0,_features_index__WEBPACK_IMPORTED_MODULE_4__.setVolSliderSize)();
  2104. if (features.anchorImprovements)
  2105. (0,_features_index__WEBPACK_IMPORTED_MODULE_4__.addAnchorImprovements)();
  2106. (0,_features_index__WEBPACK_IMPORTED_MODULE_4__.setVolSliderStep)();
  2107. }
  2108. if (["ytm", "yt"].includes(domain)) {
  2109. if (features.switchBetweenSites)
  2110. (0,_features_index__WEBPACK_IMPORTED_MODULE_4__.initSiteSwitch)(domain);
  2111. try {
  2112. (0,_features_index__WEBPACK_IMPORTED_MODULE_4__.addMenu)(); // TODO: remove
  2113. }
  2114. catch (err) {
  2115. (0,_utils__WEBPACK_IMPORTED_MODULE_2__.error)("Couldn't add menu:", err);
  2116. }
  2117. }
  2118. }
  2119. catch (err) {
  2120. (0,_utils__WEBPACK_IMPORTED_MODULE_2__.error)("General error while executing feature:", err);
  2121. }
  2122. });
  2123. }
  2124. preInit();
  2125. }();
  2126. //# sourceMappingURL=BetterYTM.user.js.map