BetterYTM.user.js 124 KB

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