BetterYTM.user.js 107 KB

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