BetterYTM.user.js 116 KB

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