BetterYTM.user.js 97 KB

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