BetterYTM.user.js 131 KB

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