BetterYTM.user.js 89 KB

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