BetterYTM.user.js 129 KB

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