BetterYTM.user.js 110 KB

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