BetterYTM.user.js 140 KB

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