BetterYTM.user.js 89 KB

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