BetterYTM.user.js 107 KB

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