BetterYTM.user.js 107 KB

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