BetterYTM.user.js 136 KB

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