BetterYTM.user.js 132 KB

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