BetterYTM.user.js 92 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083
  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. // @match https://music.youtube.com/*
  12. // @match https://www.youtube.com/*
  13. // @icon https://raw.githubusercontent.com/Sv443/BetterYTM/main/assets/icon/icon.png
  14. // @run-at document-start
  15. // @grant GM.getValue
  16. // @grant GM.setValue
  17. // @grant unsafeWindow
  18. // @connect self
  19. // @connect youtube.com
  20. // @connect github.com
  21. // @connect githubusercontent.com
  22. // @downloadURL https://raw.githubusercontent.com/Sv443/BetterYTM/main/dist/BetterYTM.user.js
  23. // @updateURL https://raw.githubusercontent.com/Sv443/BetterYTM/main/dist/BetterYTM.user.js
  24. // ==/UserScript==
  25. /*
  26. ▄▄▄ ▄ ▄▄▄▄▄▄ ▄
  27. █ █ ▄▄▄ █ █ ▄▄▄ ▄ ▄█ █ █ █▀▄▀█
  28. █▀▀▄ █▄█ █▀ █▀ █▄█ █▀ █ █ █ █
  29. █▄▄▀ ▀▄▄ ▀▄▄ ▀▄▄ ▀▄▄ █ █ █ █ █
  30. Made with ❤️ by Sv443
  31. I welcome every contribution on GitHub!
  32. https://github.com/Sv443/BetterYTM
  33. */
  34. /* Disclaimer: I am not affiliated with YouTube, Google, Alphabet, Genius or anyone else */
  35. /* C&D this 🖕 */
  36. /******/ var __webpack_modules__ = ({
  37. /***/ "./node_modules/@billjs/event-emitter/lib/index.js":
  38. /*!*********************************************************!*\
  39. !*** ./node_modules/@billjs/event-emitter/lib/index.js ***!
  40. \*********************************************************/
  41. /***/ (function(__unused_webpack_module, exports) {
  42. /**
  43. * A simple and lightweight EventEmitter by TypeScript for Node.js or Browsers.
  44. *
  45. * @author billjs
  46. * @see https://github.com/billjs/event-emitter
  47. * @license MIT(https://opensource.org/licenses/MIT)
  48. */
  49. Object.defineProperty(exports, "__esModule", ({ value: true }));
  50. /**
  51. * It's a class for managing events.
  52. * It can be extended to provide event functionality for other classes or object.
  53. *
  54. * @export
  55. * @class EventEmitter
  56. */
  57. var EventEmitter = /** @class */ (function () {
  58. function EventEmitter() {
  59. /**
  60. * the all event handlers are added.
  61. * it's a Map data structure(key-value), the key is event type, and the value is event handler.
  62. *
  63. * @memberof EventEmitter
  64. */
  65. this._eventHandlers = {};
  66. }
  67. /**
  68. * event type validator.
  69. *
  70. * @param {string} type event type
  71. * @returns {boolean}
  72. * @memberof EventEmitter
  73. */
  74. EventEmitter.prototype.isValidType = function (type) {
  75. return typeof type === 'string';
  76. };
  77. /**
  78. * event handler validator.
  79. *
  80. * @param {EventHandler} handler event handler
  81. * @returns {boolean}
  82. * @memberof EventEmitter
  83. */
  84. EventEmitter.prototype.isValidHandler = function (handler) {
  85. return typeof handler === 'function';
  86. };
  87. /**
  88. * listen on a new event by type and handler.
  89. * if listen on, the true is returned, otherwise the false.
  90. * The handler will not be listen if it is a duplicate.
  91. *
  92. * @param {string} type event type, it must be a unique string.
  93. * @param {EventHandler} handler event handler, when if the same handler is passed, listen it by only once.
  94. * @returns {boolean}
  95. * @memberof EventEmitter
  96. * @example
  97. * const emitter = new EventEmitter();
  98. * emitter.on('change:name', evt => {
  99. * console.log(evt);
  100. * });
  101. */
  102. EventEmitter.prototype.on = function (type, handler) {
  103. if (!type || !handler)
  104. return false;
  105. if (!this.isValidType(type))
  106. return false;
  107. if (!this.isValidHandler(handler))
  108. return false;
  109. var handlers = this._eventHandlers[type];
  110. if (!handlers)
  111. handlers = this._eventHandlers[type] = [];
  112. // when the same handler is passed, listen it by only once.
  113. if (handlers.indexOf(handler) >= 0)
  114. return false;
  115. handler._once = false;
  116. handlers.push(handler);
  117. return true;
  118. };
  119. /**
  120. * listen on an once event by type and handler.
  121. * when the event is fired, that will be listen off immediately and automatically.
  122. * The handler will not be listen if it is a duplicate.
  123. *
  124. * @param {string} type event type, it must be a unique string.
  125. * @param {EventHandler} handler event handler, when if the same handler is passed, listen it by only once.
  126. * @returns {boolean}
  127. * @memberof EventEmitter
  128. * @example
  129. * const emitter = new EventEmitter();
  130. * emitter.once('change:name', evt => {
  131. * console.log(evt);
  132. * });
  133. */
  134. EventEmitter.prototype.once = function (type, handler) {
  135. if (!type || !handler)
  136. return false;
  137. if (!this.isValidType(type))
  138. return false;
  139. if (!this.isValidHandler(handler))
  140. return false;
  141. var ret = this.on(type, handler);
  142. if (ret) {
  143. // set `_once` private property after listened,
  144. // avoid to modify event handler that has been listened.
  145. handler._once = true;
  146. }
  147. return ret;
  148. };
  149. /**
  150. * listen off an event by type and handler.
  151. * or listen off events by type, when if only type argument is passed.
  152. * or listen off all events, when if no arguments are passed.
  153. *
  154. * @param {string} [type] event type
  155. * @param {EventHandler} [handler] event handler
  156. * @returns
  157. * @memberof EventEmitter
  158. * @example
  159. * const emitter = new EventEmitter();
  160. * // listen off the specified event
  161. * emitter.off('change:name', evt => {
  162. * console.log(evt);
  163. * });
  164. * // listen off events by type
  165. * emitter.off('change:name');
  166. * // listen off all events
  167. * emitter.off();
  168. */
  169. EventEmitter.prototype.off = function (type, handler) {
  170. // listen off all events, when if no arguments are passed.
  171. // it does samething as `offAll` method.
  172. if (!type)
  173. return this.offAll();
  174. // listen off events by type, when if only type argument is passed.
  175. if (!handler) {
  176. this._eventHandlers[type] = [];
  177. return;
  178. }
  179. if (!this.isValidType(type))
  180. return;
  181. if (!this.isValidHandler(handler))
  182. return;
  183. var handlers = this._eventHandlers[type];
  184. if (!handlers || !handlers.length)
  185. return;
  186. // otherwise, listen off the specified event.
  187. for (var i = 0; i < handlers.length; i++) {
  188. var fn = handlers[i];
  189. if (fn === handler) {
  190. handlers.splice(i, 1);
  191. break;
  192. }
  193. }
  194. };
  195. /**
  196. * listen off all events, that means every event will be emptied.
  197. *
  198. * @memberof EventEmitter
  199. * @example
  200. * const emitter = new EventEmitter();
  201. * emitter.offAll();
  202. */
  203. EventEmitter.prototype.offAll = function () {
  204. this._eventHandlers = {};
  205. };
  206. /**
  207. * fire the specified event, and you can to pass a data.
  208. * When fired, every handler attached to that event will be executed.
  209. * But, if it's an once event, listen off it immediately after called handler.
  210. *
  211. * @param {string} type event type
  212. * @param {*} [data] event data
  213. * @returns
  214. * @memberof EventEmitter
  215. * @example
  216. * const emitter = new EventEmitter();
  217. * emitter.fire('change:name', 'new name');
  218. */
  219. EventEmitter.prototype.fire = function (type, data) {
  220. if (!type || !this.isValidType(type))
  221. return;
  222. var handlers = this._eventHandlers[type];
  223. if (!handlers || !handlers.length)
  224. return;
  225. var event = this.createEvent(type, data);
  226. for (var _i = 0, handlers_1 = handlers; _i < handlers_1.length; _i++) {
  227. var handler = handlers_1[_i];
  228. if (!this.isValidHandler(handler))
  229. continue;
  230. if (handler._once)
  231. event.once = true;
  232. // call event handler, and pass the event argument.
  233. handler(event);
  234. // if it's an once event, listen off it immediately after called handler.
  235. if (event.once)
  236. this.off(type, handler);
  237. }
  238. };
  239. /**
  240. * check whether the specified event has been listen on.
  241. * or check whether the events by type has been listen on, when if only `type` argument is passed.
  242. *
  243. * @param {string} type event type
  244. * @param {EventHandler} [handler] event handler, optional
  245. * @returns {boolean}
  246. * @memberof EventEmitter
  247. * @example
  248. * const emitter = new EventEmitter();
  249. * const result = emitter.has('change:name');
  250. */
  251. EventEmitter.prototype.has = function (type, handler) {
  252. if (!type || !this.isValidType(type))
  253. return false;
  254. var handlers = this._eventHandlers[type];
  255. // if there are no any events, return false.
  256. if (!handlers || !handlers.length)
  257. return false;
  258. // at lest one event, and no pass `handler` argument, then return true.
  259. if (!handler || !this.isValidHandler(handler))
  260. return true;
  261. // otherwise, need to traverse the handlers.
  262. return handlers.indexOf(handler) >= 0;
  263. };
  264. /**
  265. * get the handlers for the specified event type.
  266. *
  267. * @param {string} type event type
  268. * @returns {EventHandler[]}
  269. * @memberof EventEmitter
  270. * @example
  271. * const emitter = new EventEmitter();
  272. * const handlers = emitter.getHandlers('change:name');
  273. * console.log(handlers);
  274. */
  275. EventEmitter.prototype.getHandlers = function (type) {
  276. if (!type || !this.isValidType(type))
  277. return [];
  278. return this._eventHandlers[type] || [];
  279. };
  280. /**
  281. * create event object.
  282. *
  283. * @param {string} type event type
  284. * @param {*} [data] event data
  285. * @param {boolean} [once=false] is it an once event?
  286. * @returns {Event}
  287. * @memberof EventEmitter
  288. */
  289. EventEmitter.prototype.createEvent = function (type, data, once) {
  290. if (once === void 0) { once = false; }
  291. var event = { type: type, data: data, timestamp: Date.now(), once: once };
  292. return event;
  293. };
  294. return EventEmitter;
  295. }());
  296. exports.EventEmitter = EventEmitter;
  297. /**
  298. * EventEmitter instance for global.
  299. * @type {EventEmitter}
  300. */
  301. exports.globalEvent = new EventEmitter();
  302. /***/ }),
  303. /***/ "./changelog.md":
  304. /*!**********************!*\
  305. !*** ./changelog.md ***!
  306. \**********************/
  307. /***/ (function(__unused_webpack_module, __webpack_exports__, __webpack_require__) {
  308. __webpack_require__.r(__webpack_exports__);
  309. // Module
  310. 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<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>TODO: 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>TODO: 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";
  311. // Exports
  312. /* harmony default export */ __webpack_exports__["default"] = (code);
  313. /***/ }),
  314. /***/ "./src/features/menu/menu.html":
  315. /*!*************************************!*\
  316. !*** ./src/features/menu/menu.html ***!
  317. \*************************************/
  318. /***/ (function(__unused_webpack_module, __webpack_exports__, __webpack_require__) {
  319. __webpack_require__.r(__webpack_exports__);
  320. // Module
  321. 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";
  322. // Exports
  323. /* harmony default export */ __webpack_exports__["default"] = (code);
  324. /***/ }),
  325. /***/ "./src/features/layout.css":
  326. /*!*********************************!*\
  327. !*** ./src/features/layout.css ***!
  328. \*********************************/
  329. /***/ (function(__unused_webpack_module, __webpack_exports__, __webpack_require__) {
  330. __webpack_require__.r(__webpack_exports__);
  331. // extracted by mini-css-extract-plugin
  332. /***/ }),
  333. /***/ "./src/features/lyrics.css":
  334. /*!*********************************!*\
  335. !*** ./src/features/lyrics.css ***!
  336. \*********************************/
  337. /***/ (function(__unused_webpack_module, __webpack_exports__, __webpack_require__) {
  338. __webpack_require__.r(__webpack_exports__);
  339. // extracted by mini-css-extract-plugin
  340. /***/ }),
  341. /***/ "./src/features/menu/menu.css":
  342. /*!************************************!*\
  343. !*** ./src/features/menu/menu.css ***!
  344. \************************************/
  345. /***/ (function(__unused_webpack_module, __webpack_exports__, __webpack_require__) {
  346. __webpack_require__.r(__webpack_exports__);
  347. // extracted by mini-css-extract-plugin
  348. /***/ }),
  349. /***/ "./src/config.ts":
  350. /*!***********************!*\
  351. !*** ./src/config.ts ***!
  352. \***********************/
  353. /***/ (function(__unused_webpack_module, __webpack_exports__, __webpack_require__) {
  354. __webpack_require__.r(__webpack_exports__);
  355. /* harmony export */ __webpack_require__.d(__webpack_exports__, {
  356. /* harmony export */ defaultFeatures: function() { return /* binding */ defaultFeatures; },
  357. /* harmony export */ getFeatures: function() { return /* binding */ getFeatures; },
  358. /* harmony export */ loadFeatureConf: function() { return /* binding */ loadFeatureConf; },
  359. /* harmony export */ saveFeatureConf: function() { return /* binding */ saveFeatureConf; },
  360. /* harmony export */ setDefaultFeatConf: function() { return /* binding */ setDefaultFeatConf; }
  361. /* harmony export */ });
  362. /* harmony import */ var _features_index__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./features/index */ "./src/features/index.ts");
  363. /* harmony import */ var _utils__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./utils */ "./src/utils.ts");
  364. var __awaiter = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) {
  365. function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
  366. return new (P || (P = Promise))(function (resolve, reject) {
  367. function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
  368. function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
  369. function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
  370. step((generator = generator.apply(thisArg, _arguments || [])).next());
  371. });
  372. };
  373. /** If this number is incremented, the features object needs to be migrated (TODO: migration not implemented yet) */
  374. const formatVersion = 1;
  375. const defaultFeatures = Object.keys(_features_index__WEBPACK_IMPORTED_MODULE_0__.featInfo)
  376. .reduce((acc, key) => {
  377. acc[key] = _features_index__WEBPACK_IMPORTED_MODULE_0__.featInfo[key].default;
  378. return acc;
  379. }, {});
  380. /** In-memory features object to save on a little bit of I/O */
  381. let featuresCache;
  382. /**
  383. * Returns the current FeatureConfig in memory or reads it from GM storage
  384. * Automatically applies defaults for non-existant keys
  385. * @param forceRead Set to true to force reading the config from GM storage
  386. */
  387. function getFeatures(forceRead = false) {
  388. return __awaiter(this, void 0, void 0, function* () {
  389. if (featuresCache === undefined || forceRead)
  390. yield saveFeatureConf(featuresCache = Object.assign(Object.assign({}, defaultFeatures), yield loadFeatureConf())); // look at this sexy one liner
  391. return featuresCache;
  392. });
  393. }
  394. /** Loads a feature configuration saved persistently, returns an empty object if no feature configuration was saved */
  395. function loadFeatureConf() {
  396. return __awaiter(this, void 0, void 0, function* () {
  397. const defConf = Object.assign({}, defaultFeatures);
  398. try {
  399. const featureConf = yield GM.getValue("betterytm-config");
  400. if (typeof featureConf !== "string") {
  401. yield setDefaultFeatConf();
  402. return featuresCache = defConf;
  403. }
  404. return featuresCache = Object.freeze(featureConf ? JSON.parse(featureConf) : defConf);
  405. }
  406. catch (err) {
  407. yield setDefaultFeatConf();
  408. return featuresCache = defConf;
  409. }
  410. });
  411. }
  412. /**
  413. * Saves the passed feature configuration persistently in GM storage and in the in-memory cache
  414. * @param featureConf
  415. */
  416. function saveFeatureConf(featureConf) {
  417. if (!featureConf || typeof featureConf != "object")
  418. throw new TypeError("Feature config not provided or invalid");
  419. (0,_utils__WEBPACK_IMPORTED_MODULE_1__.log)("Saving new feature config:", featureConf);
  420. featuresCache = Object.assign({}, featureConf);
  421. GM.setValue("betterytm-config-ver", formatVersion);
  422. return GM.setValue("betterytm-config", JSON.stringify(featureConf));
  423. }
  424. /** Resets the featuresCache synchronously and the persistent features storage asynchronously to its default values */
  425. function setDefaultFeatConf() {
  426. featuresCache = Object.assign({}, defaultFeatures);
  427. GM.setValue("betterytm-config-ver", formatVersion);
  428. return GM.setValue("betterytm-config", JSON.stringify(defaultFeatures));
  429. }
  430. /***/ }),
  431. /***/ "./src/constants.ts":
  432. /*!**************************!*\
  433. !*** ./src/constants.ts ***!
  434. \**************************/
  435. /***/ (function(__unused_webpack_module, __webpack_exports__, __webpack_require__) {
  436. __webpack_require__.r(__webpack_exports__);
  437. /* harmony export */ __webpack_require__.d(__webpack_exports__, {
  438. /* harmony export */ branch: function() { return /* binding */ branch; },
  439. /* harmony export */ logLevel: function() { return /* binding */ logLevel; },
  440. /* harmony export */ scriptInfo: function() { return /* binding */ scriptInfo; },
  441. /* harmony export */ triesInterval: function() { return /* binding */ triesInterval; },
  442. /* harmony export */ triesLimit: function() { return /* binding */ triesLimit; }
  443. /* harmony export */ });
  444. /** The branch to use in the @icon, @downloadURL and @updateURL directives */
  445. const branch = "develop"; // TODO: change in prod.
  446. // export const branch = "main";
  447. /**
  448. * How much info should be logged to the devtools console?
  449. * 0 = Debug (show everything) or 1 = Info (show only important stuff)
  450. */
  451. const logLevel = 0; // TODO: change in prod.
  452. /** Specifies the hard limit for repetitive tasks */
  453. const triesLimit = 50;
  454. /** Specifies the interval in ms for repetitive tasks */
  455. const triesInterval = 200;
  456. /** Info about the userscript, parsed from the userscript header (tools/post-build.js) */
  457. const scriptInfo = Object.freeze({
  458. name: GM.info.script.name,
  459. version: GM.info.script.version,
  460. namespace: GM.info.script.namespace,
  461. lastCommit: "346b74d", // assert as generic string instead of union
  462. });
  463. /***/ }),
  464. /***/ "./src/features/index.ts":
  465. /*!*******************************!*\
  466. !*** ./src/features/index.ts ***!
  467. \*******************************/
  468. /***/ (function(__unused_webpack_module, __webpack_exports__, __webpack_require__) {
  469. __webpack_require__.r(__webpack_exports__);
  470. /* harmony export */ __webpack_require__.d(__webpack_exports__, {
  471. /* harmony export */ addAnchorImprovements: function() { return /* reexport safe */ _layout__WEBPACK_IMPORTED_MODULE_2__.addAnchorImprovements; },
  472. /* harmony export */ addMediaCtrlLyricsBtn: function() { return /* reexport safe */ _lyrics__WEBPACK_IMPORTED_MODULE_3__.addMediaCtrlLyricsBtn; },
  473. /* harmony export */ addMenu: function() { return /* reexport safe */ _menu_menu_old__WEBPACK_IMPORTED_MODULE_5__.addMenu; },
  474. /* harmony export */ addWatermark: function() { return /* reexport safe */ _layout__WEBPACK_IMPORTED_MODULE_2__.addWatermark; },
  475. /* harmony export */ closeMenu: function() { return /* reexport safe */ _menu_menu_old__WEBPACK_IMPORTED_MODULE_5__.closeMenu; },
  476. /* harmony export */ disableBeforeUnload: function() { return /* reexport safe */ _input__WEBPACK_IMPORTED_MODULE_1__.disableBeforeUnload; },
  477. /* harmony export */ enableBeforeUnload: function() { return /* reexport safe */ _input__WEBPACK_IMPORTED_MODULE_1__.enableBeforeUnload; },
  478. /* harmony export */ featInfo: function() { return /* binding */ featInfo; },
  479. /* harmony export */ geniUrlBase: function() { return /* reexport safe */ _lyrics__WEBPACK_IMPORTED_MODULE_3__.geniUrlBase; },
  480. /* harmony export */ getCurrentGeniusUrl: function() { return /* reexport safe */ _lyrics__WEBPACK_IMPORTED_MODULE_3__.getCurrentGeniusUrl; },
  481. /* harmony export */ initArrowKeySkip: function() { return /* reexport safe */ _input__WEBPACK_IMPORTED_MODULE_1__.initArrowKeySkip; },
  482. /* harmony export */ initBeforeUnloadHook: function() { return /* reexport safe */ _input__WEBPACK_IMPORTED_MODULE_1__.initBeforeUnloadHook; },
  483. /* harmony export */ initMenu: function() { return /* reexport safe */ _menu_menu__WEBPACK_IMPORTED_MODULE_4__.initMenu; },
  484. /* harmony export */ initQueueButtons: function() { return /* reexport safe */ _layout__WEBPACK_IMPORTED_MODULE_2__.initQueueButtons; },
  485. /* harmony export */ initSiteSwitch: function() { return /* reexport safe */ _input__WEBPACK_IMPORTED_MODULE_1__.initSiteSwitch; },
  486. /* harmony export */ openMenu: function() { return /* reexport safe */ _menu_menu_old__WEBPACK_IMPORTED_MODULE_5__.openMenu; },
  487. /* harmony export */ preInitLayout: function() { return /* reexport safe */ _layout__WEBPACK_IMPORTED_MODULE_2__.preInitLayout; },
  488. /* harmony export */ removeUpgradeTab: function() { return /* reexport safe */ _layout__WEBPACK_IMPORTED_MODULE_2__.removeUpgradeTab; },
  489. /* harmony export */ setVolSliderSize: function() { return /* reexport safe */ _layout__WEBPACK_IMPORTED_MODULE_2__.setVolSliderSize; },
  490. /* harmony export */ setVolSliderStep: function() { return /* reexport safe */ _layout__WEBPACK_IMPORTED_MODULE_2__.setVolSliderStep; }
  491. /* harmony export */ });
  492. /* harmony import */ var _constants__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../constants */ "./src/constants.ts");
  493. /* harmony import */ var _input__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./input */ "./src/features/input.ts");
  494. /* harmony import */ var _layout__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./layout */ "./src/features/layout.ts");
  495. /* harmony import */ var _lyrics__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./lyrics */ "./src/features/lyrics.ts");
  496. /* harmony import */ var _menu_menu__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./menu/menu */ "./src/features/menu/menu.ts");
  497. /* harmony import */ var _menu_menu_old__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./menu/menu_old */ "./src/features/menu/menu_old.ts");
  498. // TODO
  499. /** Contains all possible features with their default values and other config */
  500. const featInfo = {
  501. //#SECTION input
  502. arrowKeySupport: {
  503. desc: "Arrow keys skip forwards and backwards by 10 seconds",
  504. type: "toggle",
  505. category: "input",
  506. default: true,
  507. },
  508. switchBetweenSites: {
  509. desc: "Add F9 as a hotkey to switch between the YT and YTM sites on a video / song",
  510. type: "toggle",
  511. category: "input",
  512. default: true,
  513. },
  514. switchSitesHotkey: {
  515. desc: "TODO: Which hotkey needs to be pressed to switch sites?",
  516. type: "hotkey",
  517. category: "input",
  518. default: {
  519. key: "F9",
  520. shift: false,
  521. ctrl: false,
  522. meta: false,
  523. },
  524. visible: false,
  525. },
  526. disableBeforeUnloadPopup: {
  527. desc: "Completely disable the popup that sometimes appears before leaving the site",
  528. type: "toggle",
  529. category: "input",
  530. default: false,
  531. },
  532. anchorImprovements: {
  533. desc: "TODO: Make it so middle clicking a song to open it in a new tab is easier",
  534. type: "toggle",
  535. category: "input",
  536. default: true,
  537. visible: false,
  538. },
  539. //#SECTION layout
  540. removeUpgradeTab: {
  541. desc: "Remove the \"Upgrade\" / YT Music Premium tab",
  542. type: "toggle",
  543. category: "layout",
  544. default: true,
  545. },
  546. volumeSliderSize: {
  547. desc: "The width of the volume slider in pixels",
  548. type: "number",
  549. category: "layout",
  550. min: 10,
  551. max: 1000,
  552. step: 5,
  553. default: 160,
  554. unit: "px",
  555. },
  556. volumeSliderStep: {
  557. desc: "Volume slider sensitivity - the smaller this number, the finer the volume control",
  558. type: "slider",
  559. category: "layout",
  560. min: 1,
  561. max: 20,
  562. default: 2,
  563. },
  564. watermarkEnabled: {
  565. desc: `Show a ${_constants__WEBPACK_IMPORTED_MODULE_0__.scriptInfo.name} watermark under the YTM logo`,
  566. type: "toggle",
  567. category: "layout",
  568. default: true,
  569. },
  570. queueButtons: {
  571. desc: "TODO: Add buttons while hovering over a song in a queue to quickly remove it or open its lyrics",
  572. type: "toggle",
  573. category: "layout",
  574. default: true,
  575. visible: false,
  576. },
  577. //#SECTION lyrics
  578. geniusLyrics: {
  579. desc: "Add a button to the media controls to open the current song's lyrics on genius.com in a new tab",
  580. type: "toggle",
  581. category: "lyrics",
  582. default: true,
  583. },
  584. };
  585. /***/ }),
  586. /***/ "./src/features/input.ts":
  587. /*!*******************************!*\
  588. !*** ./src/features/input.ts ***!
  589. \*******************************/
  590. /***/ (function(__unused_webpack_module, __webpack_exports__, __webpack_require__) {
  591. __webpack_require__.r(__webpack_exports__);
  592. /* harmony export */ __webpack_require__.d(__webpack_exports__, {
  593. /* harmony export */ disableBeforeUnload: function() { return /* binding */ disableBeforeUnload; },
  594. /* harmony export */ enableBeforeUnload: function() { return /* binding */ enableBeforeUnload; },
  595. /* harmony export */ initArrowKeySkip: function() { return /* binding */ initArrowKeySkip; },
  596. /* harmony export */ initBeforeUnloadHook: function() { return /* binding */ initBeforeUnloadHook; },
  597. /* harmony export */ initSiteSwitch: function() { return /* binding */ initSiteSwitch; }
  598. /* harmony export */ });
  599. /* harmony import */ var _utils__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../utils */ "./src/utils.ts");
  600. /* harmony import */ var _config__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../config */ "./src/config.ts");
  601. //#MARKER arrow key skip
  602. function initArrowKeySkip() {
  603. document.addEventListener("keydown", onKeyDown);
  604. (0,_utils__WEBPACK_IMPORTED_MODULE_0__.log)("Added key press listener");
  605. }
  606. /** Called when the user presses any key, anywhere */
  607. function onKeyDown(evt) {
  608. var _a, _b;
  609. if (["ArrowLeft", "ArrowRight"].includes(evt.code)) {
  610. // discard the event when a (text) input is currently active, like when editing a playlist
  611. if (["INPUT", "TEXTAREA", "SELECT"].includes((_b = (_a = document.activeElement) === null || _a === void 0 ? void 0 : _a.tagName) !== null && _b !== void 0 ? _b : "_"))
  612. 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`);
  613. (0,_utils__WEBPACK_IMPORTED_MODULE_0__.log)(`Captured key '${evt.code}' in proxy listener`);
  614. // 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
  615. const defaultProps = {
  616. altKey: false,
  617. ctrlKey: false,
  618. metaKey: false,
  619. shiftKey: false,
  620. target: document.body,
  621. currentTarget: document.body,
  622. originalTarget: document.body,
  623. explicitOriginalTarget: document.body,
  624. srcElement: document.body,
  625. type: "keydown",
  626. bubbles: true,
  627. cancelBubble: false,
  628. cancelable: true,
  629. isTrusted: true,
  630. repeat: false,
  631. // needed because otherwise YTM errors out - see https://github.com/Sv443/BetterYTM/issues/18#show_issue
  632. view: unsafeWindow !== null && unsafeWindow !== void 0 ? unsafeWindow : window,
  633. };
  634. let invalidKey = false;
  635. let keyProps = {};
  636. switch (evt.code) {
  637. case "ArrowLeft":
  638. keyProps = {
  639. code: "KeyH",
  640. key: "h",
  641. keyCode: 72,
  642. which: 72,
  643. };
  644. break;
  645. case "ArrowRight":
  646. keyProps = {
  647. code: "KeyL",
  648. key: "l",
  649. keyCode: 76,
  650. which: 76,
  651. };
  652. break;
  653. default:
  654. invalidKey = true;
  655. break;
  656. }
  657. if (!invalidKey) {
  658. const proxyProps = Object.assign(Object.assign({ code: "" }, defaultProps), keyProps);
  659. document.body.dispatchEvent(new KeyboardEvent("keydown", proxyProps));
  660. (0,_utils__WEBPACK_IMPORTED_MODULE_0__.log)(`Dispatched proxy keydown event: [${evt.code}] -> [${proxyProps.code}]`);
  661. }
  662. else
  663. (0,_utils__WEBPACK_IMPORTED_MODULE_0__.warn)(`Captured key '${evt.code}' has no defined behavior`);
  664. }
  665. }
  666. //#MARKER site switch
  667. /** Initializes the site switch feature */
  668. function initSiteSwitch(domain) {
  669. // TODO:
  670. // extra features:
  671. // - keep video time
  672. // - configurable hotkey
  673. document.addEventListener("keydown", (e) => {
  674. if (e.key === "F9")
  675. switchSite(domain === "yt" ? "ytm" : "yt");
  676. });
  677. (0,_utils__WEBPACK_IMPORTED_MODULE_0__.log)("Initialized site switch listener");
  678. }
  679. /** Switches to the other site (between YT and YTM) */
  680. function switchSite(newDomain) {
  681. var _a;
  682. try {
  683. let subdomain;
  684. if (newDomain === "ytm")
  685. subdomain = "music";
  686. else if (newDomain === "yt")
  687. subdomain = "www";
  688. if (!subdomain)
  689. throw new TypeError(`Unrecognized domain '${newDomain}'`);
  690. const { pathname, search, hash } = new URL(location.href);
  691. const vt = (_a = (0,_utils__WEBPACK_IMPORTED_MODULE_0__.getVideoTime)()) !== null && _a !== void 0 ? _a : 0;
  692. (0,_utils__WEBPACK_IMPORTED_MODULE_0__.log)(`Found video time of ${vt} seconds`);
  693. const newSearch = search.includes("?") ? `${search}&t=${vt}` : `?t=${vt}`;
  694. const url = `https://${subdomain}.youtube.com${pathname}${newSearch}${hash}`;
  695. console.info(`BetterYTM - switching to domain '${newDomain}' at ${url}`);
  696. disableBeforeUnload();
  697. location.assign(url);
  698. }
  699. catch (err) {
  700. (0,_utils__WEBPACK_IMPORTED_MODULE_0__.error)("Error while switching site:", err);
  701. }
  702. }
  703. //#MARKER beforeunload popup
  704. let beforeUnloadEnabled = true;
  705. /** Disables the popup before leaving the site */
  706. function disableBeforeUnload() {
  707. beforeUnloadEnabled = false;
  708. (0,_utils__WEBPACK_IMPORTED_MODULE_0__.info)("Disabled popup before leaving the site");
  709. }
  710. /** (Re-)enables the popup before leaving the site */
  711. function enableBeforeUnload() {
  712. beforeUnloadEnabled = true;
  713. (0,_utils__WEBPACK_IMPORTED_MODULE_0__.info)("Enabled popup before leaving the site");
  714. }
  715. /**
  716. * Adds a spy function into `window.__proto__.addEventListener` to selectively discard beforeunload event listeners before they can be attached by the site
  717. */
  718. function initBeforeUnloadHook() {
  719. Error.stackTraceLimit = Infinity;
  720. (function (original) {
  721. // @ts-ignore
  722. window.__proto__.addEventListener = function (...args) {
  723. if (beforeUnloadEnabled && args[0] === "beforeunload")
  724. return (0,_utils__WEBPACK_IMPORTED_MODULE_0__.log)("Prevented beforeunload event listener from attaching");
  725. else
  726. return original.apply(this, args);
  727. };
  728. // @ts-ignore
  729. })(window.__proto__.addEventListener);
  730. (0,_config__WEBPACK_IMPORTED_MODULE_1__.getFeatures)().then(feats => {
  731. if (feats.disableBeforeUnloadPopup)
  732. disableBeforeUnload();
  733. });
  734. // (function(original) {
  735. // window.__proto__.removeEventListener = function(type, listener, useCapture) {
  736. // if(evtNames.includes(type)){
  737. // console.log("------> removeEventListener " + type, listener, useCapture);
  738. // }
  739. // return original.apply(this, arguments);
  740. // };
  741. // })(window.__proto__.removeEventListener);
  742. }
  743. /***/ }),
  744. /***/ "./src/features/layout.ts":
  745. /*!********************************!*\
  746. !*** ./src/features/layout.ts ***!
  747. \********************************/
  748. /***/ (function(__unused_webpack_module, __webpack_exports__, __webpack_require__) {
  749. __webpack_require__.r(__webpack_exports__);
  750. /* harmony export */ __webpack_require__.d(__webpack_exports__, {
  751. /* harmony export */ addAnchorImprovements: function() { return /* binding */ addAnchorImprovements; },
  752. /* harmony export */ addWatermark: function() { return /* binding */ addWatermark; },
  753. /* harmony export */ initQueueButtons: function() { return /* binding */ initQueueButtons; },
  754. /* harmony export */ preInitLayout: function() { return /* binding */ preInitLayout; },
  755. /* harmony export */ removeUpgradeTab: function() { return /* binding */ removeUpgradeTab; },
  756. /* harmony export */ setVolSliderSize: function() { return /* binding */ setVolSliderSize; },
  757. /* harmony export */ setVolSliderStep: function() { return /* binding */ setVolSliderStep; }
  758. /* harmony export */ });
  759. /* harmony import */ var _constants__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../constants */ "./src/constants.ts");
  760. /* harmony import */ var _config__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../config */ "./src/config.ts");
  761. /* harmony import */ var _utils__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../utils */ "./src/utils.ts");
  762. /* harmony import */ var _menu_menu_old__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./menu/menu_old */ "./src/features/menu/menu_old.ts");
  763. /* harmony import */ var _layout_css__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./layout.css */ "./src/features/layout.css");
  764. var __awaiter = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) {
  765. function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
  766. return new (P || (P = Promise))(function (resolve, reject) {
  767. function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
  768. function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
  769. function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
  770. step((generator = generator.apply(thisArg, _arguments || [])).next());
  771. });
  772. };
  773. let features;
  774. function preInitLayout() {
  775. return __awaiter(this, void 0, void 0, function* () {
  776. features = yield (0,_config__WEBPACK_IMPORTED_MODULE_1__.getFeatures)();
  777. });
  778. }
  779. //#MARKER watermark
  780. /** Adds a watermark beneath the logo */
  781. function addWatermark() {
  782. const watermark = document.createElement("a");
  783. watermark.role = "button";
  784. watermark.id = "betterytm-watermark";
  785. watermark.className = "style-scope ytmusic-nav-bar";
  786. watermark.innerText = _constants__WEBPACK_IMPORTED_MODULE_0__.scriptInfo.name;
  787. watermark.title = "Open menu";
  788. watermark.tabIndex = 1000;
  789. watermark.addEventListener("click", () => (0,_menu_menu_old__WEBPACK_IMPORTED_MODULE_3__.openMenu)());
  790. watermark.addEventListener("keydown", (e) => e.key === "Enter" && (0,_menu_menu_old__WEBPACK_IMPORTED_MODULE_3__.openMenu)());
  791. const logoElem = document.querySelector("#left-content");
  792. (0,_utils__WEBPACK_IMPORTED_MODULE_2__.insertAfter)(logoElem, watermark);
  793. (0,_utils__WEBPACK_IMPORTED_MODULE_2__.log)("Added watermark element:", watermark);
  794. }
  795. //#MARKER remove upgrade tab
  796. let removeUpgradeTries = 0;
  797. /** Removes the "Upgrade" / YT Music Premium tab from the title / nav bar */
  798. function removeUpgradeTab() {
  799. const tabElem = document.querySelector(".ytmusic-nav-bar ytmusic-pivot-bar-item-renderer[tab-id=\"SPunlimited\"]");
  800. if (tabElem) {
  801. tabElem.remove();
  802. (0,_utils__WEBPACK_IMPORTED_MODULE_2__.log)(`Removed upgrade tab after ${removeUpgradeTries} tries`);
  803. }
  804. else if (removeUpgradeTries < _constants__WEBPACK_IMPORTED_MODULE_0__.triesLimit) {
  805. setTimeout(removeUpgradeTab, _constants__WEBPACK_IMPORTED_MODULE_0__.triesInterval); // TODO: improve this
  806. removeUpgradeTries++;
  807. }
  808. else
  809. (0,_utils__WEBPACK_IMPORTED_MODULE_2__.error)(`Couldn't find upgrade tab to remove after ${removeUpgradeTries} tries`);
  810. }
  811. //#MARKER volume slider
  812. /** Sets the volume slider to a set size */
  813. function setVolSliderSize() {
  814. const { volumeSliderSize: size } = features;
  815. if (typeof size !== "number" || isNaN(Number(size)))
  816. return;
  817. const style = `\
  818. .volume-slider.ytmusic-player-bar, .expand-volume-slider.ytmusic-player-bar {
  819. width: ${size}px !important;
  820. }`;
  821. (0,_utils__WEBPACK_IMPORTED_MODULE_2__.addGlobalStyle)(style, "vol-slider");
  822. }
  823. /** Sets the `step` attribute of the volume slider */
  824. function setVolSliderStep() {
  825. const sliderElem = document.querySelector("tp-yt-paper-slider#volume-slider");
  826. sliderElem.setAttribute("step", String(features.volumeSliderStep));
  827. }
  828. //#MARKER queue buttons
  829. // 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
  830. function initQueueButtons() {
  831. _utils__WEBPACK_IMPORTED_MODULE_2__.siteEvents.on("queueChanged", (evt) => {
  832. for (const queueItm of (0,_utils__WEBPACK_IMPORTED_MODULE_2__.getEvtData)(evt).childNodes) {
  833. if (!queueItm.classList.contains("bytm-has-queue-btns"))
  834. addQueueButtons(queueItm);
  835. }
  836. });
  837. const queueItems = document.querySelectorAll("#contents.ytmusic-player-queue > ytmusic-player-queue-item");
  838. if (queueItems.length === 0)
  839. return;
  840. queueItems.forEach(itm => addQueueButtons(itm));
  841. }
  842. function addQueueButtons(queueItem) {
  843. const queueBtnsCont = document.createElement("div");
  844. queueBtnsCont.className = "bytm-queue-btn-container";
  845. queueBtnsCont.innerText = "ayo";
  846. const songInfo = queueItem.querySelector(".song-info");
  847. if (!songInfo)
  848. return false;
  849. songInfo.appendChild(queueBtnsCont);
  850. queueItem.classList.add("bytm-has-queue-btns");
  851. return true;
  852. }
  853. //#MARKER better clickable stuff
  854. // TODO: account for the fact initially the elements might not exist, if the site was opened directly with the /watch path
  855. function addAnchorImprovements() {
  856. void 0;
  857. }
  858. /***/ }),
  859. /***/ "./src/features/lyrics.ts":
  860. /*!********************************!*\
  861. !*** ./src/features/lyrics.ts ***!
  862. \********************************/
  863. /***/ (function(__unused_webpack_module, __webpack_exports__, __webpack_require__) {
  864. __webpack_require__.r(__webpack_exports__);
  865. /* harmony export */ __webpack_require__.d(__webpack_exports__, {
  866. /* harmony export */ addMediaCtrlLyricsBtn: function() { return /* binding */ addMediaCtrlLyricsBtn; },
  867. /* harmony export */ geniUrlBase: function() { return /* binding */ geniUrlBase; },
  868. /* harmony export */ getCurrentGeniusUrl: function() { return /* binding */ getCurrentGeniusUrl; }
  869. /* harmony export */ });
  870. /* harmony import */ var _constants__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../constants */ "./src/constants.ts");
  871. /* harmony import */ var _utils__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../utils */ "./src/utils.ts");
  872. /* harmony import */ var _lyrics_css__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./lyrics.css */ "./src/features/lyrics.css");
  873. var __awaiter = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) {
  874. function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
  875. return new (P || (P = Promise))(function (resolve, reject) {
  876. function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
  877. function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
  878. function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
  879. step((generator = generator.apply(thisArg, _arguments || [])).next());
  880. });
  881. };
  882. var __asyncValues = (undefined && undefined.__asyncValues) || function (o) {
  883. if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined.");
  884. var m = o[Symbol.asyncIterator], i;
  885. 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);
  886. 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); }); }; }
  887. function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); }
  888. };
  889. /** Base URL of geniURL */
  890. const geniUrlBase = "https://api.sv443.net/geniurl";
  891. /** GeniURL endpoint that gives song metadata when provided with a `?q` or `?artist` and `?song` parameter - [more info](https://api.sv443.net/geniurl) */
  892. const geniURLSearchTopUrl = `${geniUrlBase}/search/top`;
  893. let mcCurrentSongTitle = "";
  894. let mcLyricsButtonAddTries = 0;
  895. /** Adds a lyrics button to the media controls bar */
  896. function addMediaCtrlLyricsBtn() {
  897. return __awaiter(this, void 0, void 0, function* () {
  898. const likeContainer = document.querySelector(".middle-controls-buttons ytmusic-like-button-renderer#like-button-renderer");
  899. if (!likeContainer) {
  900. mcLyricsButtonAddTries++;
  901. if (mcLyricsButtonAddTries < _constants__WEBPACK_IMPORTED_MODULE_0__.triesLimit)
  902. return setTimeout(addMediaCtrlLyricsBtn, _constants__WEBPACK_IMPORTED_MODULE_0__.triesInterval); // TODO: improve this
  903. return (0,_utils__WEBPACK_IMPORTED_MODULE_1__.error)(`Couldn't find element to append lyrics buttons to after ${mcLyricsButtonAddTries} tries`);
  904. }
  905. const songTitleElem = document.querySelector(".content-info-wrapper > yt-formatted-string");
  906. const gUrl = yield getCurrentGeniusUrl();
  907. const linkElem = document.createElement("a");
  908. linkElem.id = "betterytm-lyrics-button";
  909. linkElem.className = "ytmusic-player-bar";
  910. linkElem.title = gUrl ? "Click to open this song's lyrics in a new tab" : "Loading...";
  911. if (gUrl)
  912. linkElem.href = gUrl;
  913. linkElem.target = "_blank";
  914. linkElem.rel = "noopener noreferrer";
  915. linkElem.style.visibility = gUrl ? "initial" : "hidden";
  916. linkElem.style.display = gUrl ? "inline-flex" : "none";
  917. const imgElem = document.createElement("img");
  918. imgElem.id = "betterytm-lyrics-img";
  919. imgElem.src = "https://raw.githubusercontent.com/Sv443/BetterYTM/main/assets/external/genius.png";
  920. linkElem.appendChild(imgElem);
  921. (0,_utils__WEBPACK_IMPORTED_MODULE_1__.log)(`Inserted lyrics button after ${mcLyricsButtonAddTries} tries:`, linkElem);
  922. (0,_utils__WEBPACK_IMPORTED_MODULE_1__.insertAfter)(likeContainer, linkElem);
  923. mcCurrentSongTitle = songTitleElem.title;
  924. const onMutation = (mutations) => { var _a, mutations_1, mutations_1_1; return __awaiter(this, void 0, void 0, function* () {
  925. var _b, e_1, _c, _d;
  926. try {
  927. for (_a = true, mutations_1 = __asyncValues(mutations); mutations_1_1 = yield mutations_1.next(), _b = mutations_1_1.done, !_b;) {
  928. _d = mutations_1_1.value;
  929. _a = false;
  930. try {
  931. const mut = _d;
  932. const newTitle = mut.target.title;
  933. if (newTitle != mcCurrentSongTitle && newTitle.length > 0) {
  934. const lyricsBtn = document.querySelector("#betterytm-lyrics-button");
  935. if (!lyricsBtn)
  936. return;
  937. (0,_utils__WEBPACK_IMPORTED_MODULE_1__.log)(`Song title changed from '${mcCurrentSongTitle}' to '${newTitle}'`);
  938. lyricsBtn.style.cursor = "wait";
  939. lyricsBtn.style.pointerEvents = "none";
  940. mcCurrentSongTitle = newTitle;
  941. const url = yield getCurrentGeniusUrl(); // can take a second or two
  942. if (!url)
  943. continue;
  944. lyricsBtn.href = url;
  945. lyricsBtn.title = "Click to open this song's lyrics in a new tab";
  946. lyricsBtn.style.cursor = "pointer";
  947. lyricsBtn.style.visibility = "initial";
  948. lyricsBtn.style.display = "inline-flex";
  949. lyricsBtn.style.pointerEvents = "initial";
  950. }
  951. }
  952. finally {
  953. _a = true;
  954. }
  955. }
  956. }
  957. catch (e_1_1) { e_1 = { error: e_1_1 }; }
  958. finally {
  959. try {
  960. if (!_a && !_b && (_c = mutations_1.return)) yield _c.call(mutations_1);
  961. }
  962. finally { if (e_1) throw e_1.error; }
  963. }
  964. }); };
  965. // 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
  966. const obs = new MutationObserver(onMutation);
  967. obs.observe(songTitleElem, { attributes: true, attributeFilter: ["title"] });
  968. });
  969. }
  970. /** Returns the lyrics URL from genius for the current song */
  971. function getCurrentGeniusUrl() {
  972. var _a, _b;
  973. return __awaiter(this, void 0, void 0, function* () {
  974. try {
  975. // In videos the video title contains both artist and song title, in "regular" YTM songs, the video title only contains the song title
  976. const isVideo = typeof ((_a = document.querySelector("ytmusic-player")) === null || _a === void 0 ? void 0 : _a.getAttribute("video-mode_")) === "string";
  977. const songTitleElem = document.querySelector(".content-info-wrapper > yt-formatted-string");
  978. const songMetaElem = document.querySelector("span.subtitle > yt-formatted-string:first-child");
  979. if (!songTitleElem || !songMetaElem || !songTitleElem.title)
  980. return null;
  981. const sanitizeSongName = (songName) => {
  982. const parensRegex = /\(.+\)/gmi;
  983. const squareParensRegex = /\[.+\]/gmi;
  984. // trim right after the song name:
  985. const sanitized = songName
  986. .replace(parensRegex, "")
  987. .replace(squareParensRegex, "");
  988. return sanitized.trim();
  989. };
  990. const splitArtist = (songMeta) => {
  991. songMeta = songMeta.split(/\s*\u2022\s*/gmiu)[0]; // split at bullet (&bull; / •) character
  992. if (songMeta.match(/&/))
  993. songMeta = songMeta.split(/\s*&\s*/gm)[0];
  994. if (songMeta.match(/,/))
  995. songMeta = songMeta.split(/,\s*/gm)[0];
  996. return songMeta.trim();
  997. };
  998. const songNameRaw = songTitleElem.title;
  999. const songName = sanitizeSongName(songNameRaw);
  1000. const artistName = splitArtist(songMetaElem.title);
  1001. /** Use when the current song is not a "real YTM song" with a static background, but rather a music video */
  1002. const getGeniusUrlVideo = () => __awaiter(this, void 0, void 0, function* () {
  1003. if (!songName.includes("-")) // for some fucking reason some music videos have YTM-like song title and artist separation, some don't
  1004. return yield getGeniusUrl(artistName, songName);
  1005. const [artist, ...rest] = songName.split("-").map(v => v.trim());
  1006. return yield getGeniusUrl(artist, rest.join(" "));
  1007. });
  1008. // TODO: artist might need further splitting before comma or ampersand
  1009. const url = isVideo ? yield getGeniusUrlVideo() : ((_b = yield getGeniusUrl(artistName, songName)) !== null && _b !== void 0 ? _b : yield getGeniusUrlVideo());
  1010. return url;
  1011. }
  1012. catch (err) {
  1013. (0,_utils__WEBPACK_IMPORTED_MODULE_1__.error)("Couldn't resolve lyrics URL:", err);
  1014. return null;
  1015. }
  1016. });
  1017. }
  1018. /**
  1019. * @param artist
  1020. * @param song
  1021. */
  1022. function getGeniusUrl(artist, song) {
  1023. return __awaiter(this, void 0, void 0, function* () {
  1024. try {
  1025. const startTs = Date.now();
  1026. const fetchUrl = `${geniURLSearchTopUrl}?artist=${encodeURIComponent(artist)}&song=${encodeURIComponent(song)}`;
  1027. (0,_utils__WEBPACK_IMPORTED_MODULE_1__.log)(`Requesting URL from geniURL at '${fetchUrl}'`);
  1028. const result = yield (yield fetch(fetchUrl)).json();
  1029. if (typeof result === "object" && result.error) {
  1030. (0,_utils__WEBPACK_IMPORTED_MODULE_1__.error)("Couldn't fetch lyrics URL:", result.message);
  1031. return undefined;
  1032. }
  1033. const url = result.url;
  1034. (0,_utils__WEBPACK_IMPORTED_MODULE_1__.info)(`Found lyrics URL (after ${Date.now() - startTs}ms): ${url}`);
  1035. return url;
  1036. }
  1037. catch (err) {
  1038. (0,_utils__WEBPACK_IMPORTED_MODULE_1__.error)("Couldn't get lyrics URL due to error:", err);
  1039. return undefined;
  1040. }
  1041. });
  1042. }
  1043. /***/ }),
  1044. /***/ "./src/features/menu/menu.ts":
  1045. /*!***********************************!*\
  1046. !*** ./src/features/menu/menu.ts ***!
  1047. \***********************************/
  1048. /***/ (function(__unused_webpack_module, __webpack_exports__, __webpack_require__) {
  1049. __webpack_require__.r(__webpack_exports__);
  1050. /* harmony export */ __webpack_require__.d(__webpack_exports__, {
  1051. /* harmony export */ closeMenu: function() { return /* binding */ closeMenu; },
  1052. /* harmony export */ initMenu: function() { return /* binding */ initMenu; },
  1053. /* harmony export */ openMenu: function() { return /* binding */ openMenu; },
  1054. /* harmony export */ setActiveTab: function() { return /* binding */ setActiveTab; }
  1055. /* harmony export */ });
  1056. /* harmony import */ var _constants__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../../constants */ "./src/constants.ts");
  1057. /* harmony import */ var _utils__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../../utils */ "./src/utils.ts");
  1058. /* harmony import */ var _changelog_md__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../../../changelog.md */ "./changelog.md");
  1059. /* harmony import */ var _menu_html__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./menu.html */ "./src/features/menu/menu.html");
  1060. /* harmony import */ var _menu_css__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./menu.css */ "./src/features/menu/menu.css");
  1061. //#MARKER menu
  1062. /**
  1063. * These are the base selector values for the menu tabs
  1064. * Header selector format: `#${baseValue}-header`
  1065. * Content selector format: `#${baseValue}-content`
  1066. */
  1067. const tabsSelectors = {
  1068. options: "bytm-menu-tab-options",
  1069. info: "bytm-menu-tab-info",
  1070. changelog: "bytm-menu-tab-changelog",
  1071. };
  1072. function initMenu() {
  1073. document.addEventListener("DOMContentLoaded", () => {
  1074. // create menu container
  1075. const menuContainer = document.createElement("div");
  1076. menuContainer.id = "bytm-menu-container";
  1077. // add menu html
  1078. menuContainer.innerHTML = _menu_html__WEBPACK_IMPORTED_MODULE_3__["default"];
  1079. document.body.appendChild(menuContainer);
  1080. initMenuContents();
  1081. });
  1082. }
  1083. let menuContTries = 0;
  1084. function initMenuContents() {
  1085. var _a;
  1086. if (!document.querySelector("#bytm-menu-dialog"))
  1087. return menuContTries++ < _constants__WEBPACK_IMPORTED_MODULE_0__.triesLimit
  1088. ? setTimeout(initMenuContents, _constants__WEBPACK_IMPORTED_MODULE_0__.triesInterval)
  1089. : (0,_utils__WEBPACK_IMPORTED_MODULE_1__.error)(`couldn't create menu element after ${_constants__WEBPACK_IMPORTED_MODULE_0__.triesLimit} tries.`);
  1090. // hook events
  1091. for (const tab in tabsSelectors) {
  1092. const selector = tabsSelectors[tab];
  1093. (_a = document.querySelector(`#${selector}-header`)) === null || _a === void 0 ? void 0 : _a.addEventListener("click", () => {
  1094. setActiveTab(tab);
  1095. });
  1096. }
  1097. // init tab contents
  1098. initOptionsContent();
  1099. initInfoContent();
  1100. initChangelogContent();
  1101. }
  1102. /** Opens the specified tab */
  1103. function setActiveTab(tab) {
  1104. const tabs = Object.assign({}, tabsSelectors);
  1105. delete tabs[tab];
  1106. // disable all but new active tab
  1107. for (const disableTab of Object.keys(tabs)) {
  1108. document.querySelector(`#${tabs[disableTab]}-header`).dataset.active = "false";
  1109. document.querySelector(`#${tabs[disableTab]}-content`).dataset.active = "false";
  1110. }
  1111. // enable new active tab
  1112. document.querySelector(`#${tabsSelectors[tab]}-header`).dataset.active = "true";
  1113. document.querySelector(`#${tabsSelectors[tab]}-content`).dataset.active = "true";
  1114. }
  1115. /** Opens the modal menu dialog */
  1116. function openMenu() {
  1117. document.querySelector("#bytm-menu-dialog").showModal();
  1118. }
  1119. /** Closes the modal menu dialog */
  1120. function closeMenu() {
  1121. document.querySelector("#bytm-menu-dialog").close();
  1122. }
  1123. //#MARKER menu tab contents
  1124. function initOptionsContent() {
  1125. const tab = document.querySelector("#bytm-menu-tab-options-content");
  1126. void tab;
  1127. }
  1128. function initInfoContent() {
  1129. const tab = document.querySelector("#bytm-menu-tab-info-content");
  1130. void tab;
  1131. }
  1132. function initChangelogContent() {
  1133. const tab = document.querySelector("#bytm-menu-tab-changelog-content");
  1134. tab.innerHTML = _changelog_md__WEBPACK_IMPORTED_MODULE_2__["default"];
  1135. }
  1136. /***/ }),
  1137. /***/ "./src/features/menu/menu_old.ts":
  1138. /*!***************************************!*\
  1139. !*** ./src/features/menu/menu_old.ts ***!
  1140. \***************************************/
  1141. /***/ (function(__unused_webpack_module, __webpack_exports__, __webpack_require__) {
  1142. __webpack_require__.r(__webpack_exports__);
  1143. /* harmony export */ __webpack_require__.d(__webpack_exports__, {
  1144. /* harmony export */ addMenu: function() { return /* binding */ addMenu; },
  1145. /* harmony export */ closeMenu: function() { return /* binding */ closeMenu; },
  1146. /* harmony export */ openMenu: function() { return /* binding */ openMenu; }
  1147. /* harmony export */ });
  1148. /* harmony import */ var _config__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../../config */ "./src/config.ts");
  1149. /* harmony import */ var _constants__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../../constants */ "./src/constants.ts");
  1150. /* harmony import */ var _index__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../index */ "./src/features/index.ts");
  1151. /* harmony import */ var _utils__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../../utils */ "./src/utils.ts");
  1152. var __awaiter = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) {
  1153. function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
  1154. return new (P || (P = Promise))(function (resolve, reject) {
  1155. function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
  1156. function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
  1157. function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
  1158. step((generator = generator.apply(thisArg, _arguments || [])).next());
  1159. });
  1160. };
  1161. //#MARKER menu
  1162. /**
  1163. * Adds an element to open the BetterYTM menu
  1164. * @deprecated TODO: replace in v1.1.0 - see https://github.com/Sv443/BetterYTM/issues/23
  1165. */
  1166. function addMenu() {
  1167. var _a, _b;
  1168. return __awaiter(this, void 0, void 0, function* () {
  1169. // bg & menu
  1170. const backgroundElem = document.createElement("div");
  1171. backgroundElem.id = "betterytm-menu-bg";
  1172. backgroundElem.title = "Click here to close the menu";
  1173. backgroundElem.style.visibility = "hidden";
  1174. backgroundElem.style.display = "none";
  1175. backgroundElem.addEventListener("click", (e) => {
  1176. if (e.target.id === "betterytm-menu-bg")
  1177. closeMenu();
  1178. });
  1179. document.body.addEventListener("keydown", ({ key }) => {
  1180. if (key === "Escape")
  1181. closeMenu();
  1182. });
  1183. const menuContainer = document.createElement("div");
  1184. menuContainer.title = "";
  1185. menuContainer.id = "betterytm-menu";
  1186. menuContainer.style.borderRadius = "15px";
  1187. menuContainer.style.display = "flex";
  1188. menuContainer.style.flexDirection = "column";
  1189. menuContainer.style.justifyContent = "space-between";
  1190. // title
  1191. const titleCont = document.createElement("div");
  1192. titleCont.style.padding = "8px 20px 15px 8px";
  1193. titleCont.style.display = "flex";
  1194. titleCont.style.justifyContent = "space-between";
  1195. titleCont.id = "betterytm-menu-titlecont";
  1196. const titleElem = document.createElement("h2");
  1197. titleElem.id = "betterytm-menu-title";
  1198. titleElem.innerText = `${_constants__WEBPACK_IMPORTED_MODULE_1__.scriptInfo.name} - Configuration`;
  1199. const linksCont = document.createElement("div");
  1200. linksCont.id = "betterytm-menu-linkscont";
  1201. const addLink = (imgSrc, href, title) => {
  1202. const anchorElem = document.createElement("a");
  1203. anchorElem.className = "betterytm-menu-link";
  1204. anchorElem.rel = "noopener noreferrer";
  1205. anchorElem.target = "_blank";
  1206. anchorElem.href = href;
  1207. anchorElem.title = title;
  1208. anchorElem.style.marginLeft = "10px";
  1209. const imgElem = document.createElement("img");
  1210. imgElem.className = "betterytm-menu-img";
  1211. imgElem.src = imgSrc;
  1212. imgElem.style.width = "32px";
  1213. imgElem.style.height = "32px";
  1214. anchorElem.appendChild(imgElem);
  1215. linksCont.appendChild(anchorElem);
  1216. };
  1217. addLink(`https://raw.githubusercontent.com/Sv443/BetterYTM/${_constants__WEBPACK_IMPORTED_MODULE_1__.branch}/assets/external/github.png`, _constants__WEBPACK_IMPORTED_MODULE_1__.scriptInfo.namespace, `${_constants__WEBPACK_IMPORTED_MODULE_1__.scriptInfo.name} on GitHub`);
  1218. addLink(`https://raw.githubusercontent.com/Sv443/BetterYTM/${_constants__WEBPACK_IMPORTED_MODULE_1__.branch}/assets/external/greasyfork.png`, "https://greasyfork.org/xyz", `${_constants__WEBPACK_IMPORTED_MODULE_1__.scriptInfo.name} on GreasyFork`);
  1219. const closeElem = document.createElement("img");
  1220. closeElem.id = "betterytm-menu-close";
  1221. closeElem.src = `https://raw.githubusercontent.com/Sv443/BetterYTM/${_constants__WEBPACK_IMPORTED_MODULE_1__.branch}/assets/icon/close.png`;
  1222. closeElem.title = "Click to close the menu";
  1223. closeElem.style.marginLeft = "50px";
  1224. closeElem.style.width = "32px";
  1225. closeElem.style.height = "32px";
  1226. closeElem.addEventListener("click", closeMenu);
  1227. linksCont.appendChild(closeElem);
  1228. titleCont.appendChild(titleElem);
  1229. titleCont.appendChild(linksCont);
  1230. // TODO: features
  1231. const featuresCont = document.createElement("div");
  1232. featuresCont.id = "betterytm-menu-opts";
  1233. featuresCont.style.display = "flex";
  1234. featuresCont.style.flexDirection = "column";
  1235. featuresCont.style.overflowY = "auto";
  1236. /** Gets called whenever the feature config is changed */
  1237. const confChanged = (key, initialVal, newVal) => __awaiter(this, void 0, void 0, function* () {
  1238. const fmt = (val) => typeof val === "object" ? JSON.stringify(val) : String(val);
  1239. (0,_utils__WEBPACK_IMPORTED_MODULE_3__.info)(`Feature config changed, key '${key}' from value '${fmt(initialVal)}' to '${fmt(newVal)}'`);
  1240. const featConf = Object.assign({}, yield (0,_config__WEBPACK_IMPORTED_MODULE_0__.getFeatures)());
  1241. featConf[key] = newVal;
  1242. yield (0,_config__WEBPACK_IMPORTED_MODULE_0__.saveFeatureConf)(featConf);
  1243. (0,_utils__WEBPACK_IMPORTED_MODULE_3__.log)("Saved feature config changes:\n", yield GM.getValue("betterytm-config"));
  1244. });
  1245. const features = yield (0,_config__WEBPACK_IMPORTED_MODULE_0__.getFeatures)();
  1246. for (const key in features) {
  1247. const ftInfo = _index__WEBPACK_IMPORTED_MODULE_2__.featInfo[key];
  1248. // @ts-ignore
  1249. if (!ftInfo || ftInfo.visible === false)
  1250. continue;
  1251. const { desc, type, default: ftDefault } = ftInfo;
  1252. // @ts-ignore
  1253. const step = (_a = ftInfo === null || ftInfo === void 0 ? void 0 : ftInfo.step) !== null && _a !== void 0 ? _a : undefined;
  1254. const val = features[key];
  1255. const initialVal = (_b = val !== null && val !== void 0 ? val : ftDefault) !== null && _b !== void 0 ? _b : undefined;
  1256. const ftConfElem = document.createElement("div");
  1257. ftConfElem.id = `betterytm-ftconf-${key}`;
  1258. ftConfElem.style.display = "flex";
  1259. ftConfElem.style.flexDirection = "row";
  1260. ftConfElem.style.justifyContent = "space-between";
  1261. ftConfElem.style.padding = "8px 20px";
  1262. {
  1263. const textElem = document.createElement("span");
  1264. textElem.style.display = "inline-block";
  1265. textElem.style.fontSize = "15px";
  1266. textElem.innerText = desc;
  1267. ftConfElem.appendChild(textElem);
  1268. }
  1269. {
  1270. let inputType = "text";
  1271. switch (type) {
  1272. case "toggle":
  1273. inputType = "checkbox";
  1274. break;
  1275. case "slider":
  1276. inputType = "range";
  1277. break;
  1278. case "number":
  1279. inputType = "number";
  1280. break;
  1281. }
  1282. const inputElemId = `betterytm-ftconf-${key}-input`;
  1283. const ctrlElem = document.createElement("span");
  1284. ctrlElem.style.display = "inline-block";
  1285. ctrlElem.style.whiteSpace = "nowrap";
  1286. const inputElem = document.createElement("input");
  1287. inputElem.id = inputElemId;
  1288. inputElem.style.marginRight = "37px";
  1289. inputElem.type = inputType;
  1290. if (type === "toggle")
  1291. inputElem.style.marginLeft = "5px";
  1292. if (typeof initialVal !== "undefined")
  1293. inputElem.value = String(initialVal);
  1294. if (type === "number" && step)
  1295. inputElem.step = step;
  1296. // @ts-ignore
  1297. if (ftInfo.min && ftInfo.max) {
  1298. // @ts-ignore
  1299. inputElem.min = ftInfo.min;
  1300. // @ts-ignore
  1301. inputElem.max = ftInfo.max;
  1302. }
  1303. if (type === "toggle" && typeof initialVal !== "undefined")
  1304. inputElem.checked = Boolean(initialVal);
  1305. // @ts-ignore
  1306. const unitTxt = typeof ftInfo.unit === "string" ? " " + ftInfo.unit : "";
  1307. const fmtVal = (v) => String(v).trim();
  1308. const toggleLabelText = (toggled) => toggled ? "On" : "Off";
  1309. let labelElem;
  1310. if (type === "slider") {
  1311. labelElem = document.createElement("label");
  1312. labelElem.classList.add("betterytm-ftconf-label");
  1313. labelElem.style.marginRight = "20px";
  1314. labelElem.style.fontSize = "16px";
  1315. labelElem.htmlFor = inputElemId;
  1316. labelElem.innerText = fmtVal(initialVal) + unitTxt;
  1317. inputElem.addEventListener("input", () => {
  1318. if (labelElem)
  1319. labelElem.innerText = fmtVal(parseInt(inputElem.value)) + unitTxt;
  1320. });
  1321. }
  1322. else if (type === "toggle") {
  1323. labelElem = document.createElement("label");
  1324. labelElem.classList.add("betterytm-ftconf-label");
  1325. labelElem.style.paddingLeft = "10px";
  1326. labelElem.style.paddingRight = "5px";
  1327. labelElem.style.fontSize = "16px";
  1328. labelElem.htmlFor = inputElemId;
  1329. labelElem.innerText = toggleLabelText(Boolean(initialVal)) + unitTxt;
  1330. inputElem.addEventListener("input", () => {
  1331. if (labelElem)
  1332. labelElem.innerText = toggleLabelText(inputElem.checked) + unitTxt;
  1333. });
  1334. }
  1335. inputElem.addEventListener("input", () => {
  1336. let v = parseInt(inputElem.value);
  1337. if (isNaN(v))
  1338. v = Number(inputElem.value);
  1339. if (typeof initialVal !== "undefined")
  1340. confChanged(key, initialVal, (type !== "toggle" ? v : inputElem.checked));
  1341. });
  1342. const resetElem = document.createElement("button");
  1343. resetElem.innerText = "Reset";
  1344. resetElem.addEventListener("click", () => {
  1345. inputElem[type !== "toggle" ? "value" : "checked"] = ftDefault;
  1346. if (labelElem) {
  1347. if (type === "toggle")
  1348. labelElem.innerText = toggleLabelText(inputElem.checked);
  1349. else
  1350. labelElem.innerText = fmtVal(parseInt(inputElem.value));
  1351. }
  1352. if (typeof initialVal !== "undefined")
  1353. confChanged(key, initialVal, ftDefault);
  1354. });
  1355. labelElem && ctrlElem.appendChild(labelElem);
  1356. ctrlElem.appendChild(inputElem);
  1357. ctrlElem.appendChild(resetElem);
  1358. ftConfElem.appendChild(ctrlElem);
  1359. }
  1360. featuresCont.appendChild(ftConfElem);
  1361. }
  1362. const footerElem = document.createElement("div");
  1363. footerElem.id = "betterytm-menu-footer";
  1364. footerElem.style.marginTop = "20px";
  1365. footerElem.style.fontSize = "17px";
  1366. footerElem.style.textDecoration = "underline";
  1367. footerElem.style.padding = "10px 20px";
  1368. footerElem.style.position = "sticky";
  1369. footerElem.style.backgroundColor = "var(--bytm-menu-bg)";
  1370. footerElem.style.bottom = "0";
  1371. footerElem.innerText = "You need to reload the page to apply changes.";
  1372. const reloadElem = document.createElement("button");
  1373. reloadElem.style.marginLeft = "20px";
  1374. reloadElem.innerText = "Reload now";
  1375. reloadElem.title = "Click to reload the page";
  1376. reloadElem.addEventListener("click", () => location.reload());
  1377. footerElem.appendChild(reloadElem);
  1378. featuresCont.appendChild(footerElem);
  1379. // finalize
  1380. const menuBody = document.createElement("div");
  1381. menuBody.id = "betterytm-menu-body";
  1382. menuBody.appendChild(titleCont);
  1383. menuBody.appendChild(featuresCont);
  1384. const versionCont = document.createElement("div");
  1385. versionCont.style.display = "flex";
  1386. versionCont.style.justifyContent = "space-around";
  1387. versionCont.style.fontSize = "1.15em";
  1388. versionCont.style.marginTop = "10px";
  1389. versionCont.style.marginBottom = "5px";
  1390. const versionElem = document.createElement("span");
  1391. versionElem.id = "betterytm-menu-version";
  1392. versionElem.innerText = `v${_constants__WEBPACK_IMPORTED_MODULE_1__.scriptInfo.version}`;
  1393. versionCont.appendChild(versionElem);
  1394. featuresCont.appendChild(versionCont);
  1395. menuContainer.appendChild(menuBody);
  1396. menuContainer.appendChild(versionCont);
  1397. backgroundElem.appendChild(menuContainer);
  1398. document.body.appendChild(backgroundElem);
  1399. // add style
  1400. const menuStyle = `\
  1401. :root {
  1402. --bytm-menu-bg: #212121;
  1403. }
  1404. #betterytm-menu-bg {
  1405. display: block;
  1406. position: fixed;
  1407. width: 100vw;
  1408. height: 100vh;
  1409. top: 0;
  1410. left: 0;
  1411. z-index: 15;
  1412. background-color: rgba(0, 0, 0, 0.6);
  1413. }
  1414. /* TODO:FIXME: needs better positioning (vw and vh === "big no no") */
  1415. #betterytm-menu {
  1416. display: inline-block;
  1417. position: fixed;
  1418. width: 50vw;
  1419. height: auto;
  1420. left: 25vw;
  1421. top: 10vh;
  1422. z-index: 16;
  1423. padding: 8px;
  1424. color: #fff;
  1425. background-color: var(--bytm-menu-bg);
  1426. }
  1427. #betterytm-menu-opts {
  1428. max-height: 70vh;
  1429. overflow: auto;
  1430. }
  1431. #betterytm-menu-titlecont {
  1432. display: flex;
  1433. }
  1434. #betterytm-menu-title {
  1435. font-size: 20px;
  1436. margin-top: 5px;
  1437. margin-bottom: 8px;
  1438. }
  1439. #betterytm-menu-linkscont {
  1440. display: flex;
  1441. }
  1442. .betterytm-menu-link {
  1443. display: inline-block;
  1444. }
  1445. /*.betterytm-menu-img {
  1446. }*/
  1447. #betterytm-menu-close {
  1448. cursor: pointer;
  1449. }
  1450. .betterytm-ftconf-label {
  1451. user-select: none;
  1452. }`;
  1453. (0,_utils__WEBPACK_IMPORTED_MODULE_3__.log)("Added menu elem:", backgroundElem);
  1454. (0,_utils__WEBPACK_IMPORTED_MODULE_3__.addGlobalStyle)(menuStyle, "menu");
  1455. });
  1456. }
  1457. function closeMenu() {
  1458. const menuBg = document.querySelector("#betterytm-menu-bg");
  1459. menuBg.style.visibility = "hidden";
  1460. menuBg.style.display = "none";
  1461. }
  1462. function openMenu() {
  1463. const menuBg = document.querySelector("#betterytm-menu-bg");
  1464. menuBg.style.visibility = "visible";
  1465. menuBg.style.display = "block";
  1466. }
  1467. /***/ }),
  1468. /***/ "./src/utils.ts":
  1469. /*!**********************!*\
  1470. !*** ./src/utils.ts ***!
  1471. \**********************/
  1472. /***/ (function(__unused_webpack_module, __webpack_exports__, __webpack_require__) {
  1473. __webpack_require__.r(__webpack_exports__);
  1474. /* harmony export */ __webpack_require__.d(__webpack_exports__, {
  1475. /* harmony export */ addGlobalStyle: function() { return /* binding */ addGlobalStyle; },
  1476. /* harmony export */ error: function() { return /* binding */ error; },
  1477. /* harmony export */ getDomain: function() { return /* binding */ getDomain; },
  1478. /* harmony export */ getEvtData: function() { return /* binding */ getEvtData; },
  1479. /* harmony export */ getVideoTime: function() { return /* binding */ getVideoTime; },
  1480. /* harmony export */ info: function() { return /* binding */ info; },
  1481. /* harmony export */ initSiteEvents: function() { return /* binding */ initSiteEvents; },
  1482. /* harmony export */ insertAfter: function() { return /* binding */ insertAfter; },
  1483. /* harmony export */ log: function() { return /* binding */ log; },
  1484. /* harmony export */ removeAllObservers: function() { return /* binding */ removeAllObservers; },
  1485. /* harmony export */ setLogLevel: function() { return /* binding */ setLogLevel; },
  1486. /* harmony export */ siteEvents: function() { return /* binding */ siteEvents; },
  1487. /* harmony export */ warn: function() { return /* binding */ warn; }
  1488. /* harmony export */ });
  1489. /* harmony import */ var _billjs_event_emitter__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @billjs/event-emitter */ "./node_modules/@billjs/event-emitter/lib/index.js");
  1490. /* harmony import */ var _constants__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./constants */ "./src/constants.ts");
  1491. var __awaiter = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) {
  1492. function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
  1493. return new (P || (P = Promise))(function (resolve, reject) {
  1494. function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
  1495. function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
  1496. function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
  1497. step((generator = generator.apply(thisArg, _arguments || [])).next());
  1498. });
  1499. };
  1500. //#MARKER BYTM-specific
  1501. let curLogLevel = 1;
  1502. /** Sets the current log level. 0 = Debug, 1 = Info */
  1503. function setLogLevel(level) {
  1504. curLogLevel = level;
  1505. }
  1506. function getLogLevel(args) {
  1507. if (typeof args.at(-1) === "number")
  1508. return args.splice(args.length - 1, 1)[0];
  1509. return 0;
  1510. }
  1511. /** Common prefix to be able to tell logged messages apart */
  1512. const consPrefix = `[${_constants__WEBPACK_IMPORTED_MODULE_1__.scriptInfo.name}]`;
  1513. /**
  1514. * Logs string-compatible values to the console, as long as the log level is sufficient.
  1515. * @param args Last parameter is log level (0 = Debug, 1/undefined = Info)
  1516. */
  1517. function log(...args) {
  1518. if (curLogLevel <= getLogLevel(args))
  1519. console.log(consPrefix, ...args);
  1520. }
  1521. /**
  1522. * Logs string-compatible values to the console as info, as long as the log level is sufficient.
  1523. * @param args Last parameter is log level (0 = Debug, 1/undefined = Info)
  1524. */
  1525. function info(...args) {
  1526. if (curLogLevel <= getLogLevel(args))
  1527. console.info(consPrefix, ...args);
  1528. }
  1529. /**
  1530. * Logs string-compatible values to the console as a warning, as long as the log level is sufficient.
  1531. * @param args Last parameter is log level (0 = Debug, 1/undefined = Info)
  1532. */
  1533. function warn(...args) {
  1534. if (curLogLevel <= getLogLevel(args))
  1535. console.warn(consPrefix, ...args);
  1536. }
  1537. /** Logs string-compatible values to the console as an error. */
  1538. function error(...args) {
  1539. console.error(consPrefix, ...args);
  1540. }
  1541. /**
  1542. * Returns the current domain as a constant string representation
  1543. * @throws Throws if script runs on an unexpected website
  1544. */
  1545. function getDomain() {
  1546. const { hostname } = new URL(location.href);
  1547. if (hostname.includes("music.youtube"))
  1548. return "ytm";
  1549. else if (hostname.includes("youtube"))
  1550. return "yt";
  1551. else
  1552. throw new Error("BetterYTM is running on an unexpected website. Please don't tamper with the @match directives in the userscript header.");
  1553. }
  1554. /**
  1555. * Returns the current video time in seconds
  1556. * @param force Set to true to dispatch mouse movement events in case the video time can't be estimated
  1557. * @returns Returns null if the video time is unavailable
  1558. */
  1559. function getVideoTime(force = false) {
  1560. const domain = getDomain();
  1561. try {
  1562. if (domain === "ytm") {
  1563. const pbEl = document.querySelector("#progress-bar");
  1564. return !isNaN(Number(pbEl.value)) ? Number(pbEl.value) : null;
  1565. }
  1566. else if (domain === "yt") {
  1567. // YT doesn't update the progress bar when it's hidden (YTM doesn't hide it) so TODO: come up with some solution here
  1568. // Possible solution:
  1569. // - Use MutationObserver to detect when attributes of progress bar (selector `div.ytp-progress-bar[role="slider"]`) change
  1570. // - Wait until the attribute increments, then save the value of `aria-valuenow` and the current system time to memory
  1571. // - When site switch hotkey is pressed, take saved `aria-valuenow` value and add the difference between saved system time and current system time
  1572. // - If no value is present, use the script from `dev/ytForceShowVideoTime.js` to simulate mouse movement to force the element to update
  1573. // - Subtract one or two seconds to make up for rounding errors
  1574. // - profit
  1575. // if(!ytCurrentVideoTime) {
  1576. // ytForceShowVideoTime();
  1577. // const videoTime = document.querySelector("#TODO")?.getAttribute("aria-valuenow") ?? null;
  1578. // }
  1579. void [force, ytForceShowVideoTime];
  1580. return null;
  1581. }
  1582. return null;
  1583. }
  1584. catch (err) {
  1585. error("Couldn't get video time due to error:", err);
  1586. return null;
  1587. }
  1588. }
  1589. /** Sends events that force the video controls to become visible for about 3 seconds */
  1590. function ytForceShowVideoTime() {
  1591. const player = document.querySelector("#movie_player");
  1592. if (!player)
  1593. return false;
  1594. const defaultProps = {
  1595. // needed because otherwise YTM errors out - see https://github.com/Sv443/BetterYTM/issues/18#show_issue
  1596. view: unsafeWindow !== null && unsafeWindow !== void 0 ? unsafeWindow : window,
  1597. bubbles: true,
  1598. cancelable: false,
  1599. };
  1600. player.dispatchEvent(new MouseEvent("mouseenter", defaultProps));
  1601. const { x, y, width, height } = player.getBoundingClientRect();
  1602. const screenY = Math.round(y + height / 2);
  1603. const screenX = x + Math.min(50, Math.round(width / 3));
  1604. player.dispatchEvent(new MouseEvent("mousemove", Object.assign(Object.assign({}, defaultProps), { screenY,
  1605. screenX, movementX: 5, movementY: 0 })));
  1606. setTimeout(() => {
  1607. player.dispatchEvent(new MouseEvent("mouseleave", defaultProps));
  1608. }, 4000);
  1609. return true;
  1610. }
  1611. //#MARKER DOM
  1612. /**
  1613. * Inserts `afterNode` as a sibling just after the provided `beforeNode`
  1614. * @param beforeNode
  1615. * @param afterNode
  1616. * @returns Returns the `afterNode`
  1617. */
  1618. function insertAfter(beforeNode, afterNode) {
  1619. var _a;
  1620. (_a = beforeNode.parentNode) === null || _a === void 0 ? void 0 : _a.insertBefore(afterNode, beforeNode.nextSibling);
  1621. return afterNode;
  1622. }
  1623. /**
  1624. * Adds global CSS style through a `<style>` element in the document's `<head>`
  1625. * @param style CSS string
  1626. * @param ref Reference name that is included in the `<style>`'s ID - prefixed with `betterytm-style-` - defaults to a random number if left undefined
  1627. */
  1628. function addGlobalStyle(style, ref) {
  1629. if (typeof ref !== "string" || ref.length === 0)
  1630. ref = String(Math.floor(Math.random() * 10000));
  1631. const styleElem = document.createElement("style");
  1632. styleElem.id = `betterytm-style-${ref}`;
  1633. styleElem.innerHTML = style;
  1634. document.head.appendChild(styleElem);
  1635. log(`Inserted global style with ref '${ref}':`, styleElem);
  1636. }
  1637. const siteEvents = new _billjs_event_emitter__WEBPACK_IMPORTED_MODULE_0__.EventEmitter();
  1638. /**
  1639. * Returns the data of an event from the `@billjs/event-emitter` library.
  1640. * This function is used to assert the type passed in `<T>`
  1641. * @param evt Event object from the `.on()` or `.once()` method
  1642. * @template T Type of the data passed by `.fire(type: string, data: T)`
  1643. */
  1644. function getEvtData(evt) {
  1645. return evt.data;
  1646. }
  1647. let observers = [];
  1648. /** Creates MutationObservers that check if parts of the site have changed, then emit an event on the `siteEvents` instance. */
  1649. function initSiteEvents() {
  1650. return __awaiter(this, void 0, void 0, function* () {
  1651. try {
  1652. //#SECTION queue
  1653. // the queue container always exists so it doesn't need the extra init function
  1654. const queueObs = new MutationObserver(([{ addedNodes, removedNodes, target }]) => {
  1655. if (addedNodes.length > 0 || removedNodes.length > 0) {
  1656. info("Detected queue change - added nodes:", addedNodes.length, "- removed nodes:", removedNodes.length);
  1657. siteEvents.fire("queueChanged", target);
  1658. }
  1659. });
  1660. // only observe added or removed elements
  1661. queueObs.observe(document.querySelector(".side-panel.modular #contents.ytmusic-player-queue"), {
  1662. childList: true,
  1663. });
  1664. //#SECTION home page observers
  1665. initHomeObservers();
  1666. info("Successfully initialized SiteEvents observers");
  1667. observers = [
  1668. queueObs,
  1669. ];
  1670. }
  1671. catch (err) {
  1672. error("Couldn't initialize SiteEvents observers due to an error:\n", err);
  1673. }
  1674. });
  1675. }
  1676. /** Disconnects and deletes all observers. Run `initSiteEvents()` again to create new ones. */
  1677. function removeAllObservers() {
  1678. observers.forEach((observer) => observer.disconnect());
  1679. observers = [];
  1680. }
  1681. /**
  1682. * The home page might not exist yet if the site was accessed through any path like /watch directly.
  1683. * This function will keep waiting for when the home page exists, then create the necessary MutationObservers.
  1684. */
  1685. function initHomeObservers() {
  1686. var _a;
  1687. return __awaiter(this, void 0, void 0, function* () {
  1688. let interval;
  1689. // hidden="" attribute is only present if the content of the page doesn't exist yet
  1690. // so this resolves only once that attribute is removed
  1691. if ((_a = document.querySelector("ytmusic-browse-response#browse-page")) === null || _a === void 0 ? void 0 : _a.hasAttribute("hidden")) {
  1692. yield new Promise((res) => {
  1693. interval = setInterval(() => {
  1694. var _a;
  1695. if (!((_a = document.querySelector("ytmusic-browse-response#browse-page")) === null || _a === void 0 ? void 0 : _a.hasAttribute("hidden"))) {
  1696. info("found home page");
  1697. res();
  1698. }
  1699. }, 50);
  1700. });
  1701. }
  1702. interval && clearInterval(interval);
  1703. siteEvents.fire("homePageLoaded");
  1704. info("Initialized home page observers");
  1705. //#SECTION carousel shelves
  1706. const shelfContainerObs = new MutationObserver(([{ addedNodes, removedNodes }]) => {
  1707. if (addedNodes.length > 0 || removedNodes.length > 0) {
  1708. info("Detected carousel shelf container change - added nodes:", addedNodes.length, "- removed nodes:", removedNodes.length);
  1709. siteEvents.fire("carouselShelvesChanged", { addedNodes, removedNodes });
  1710. }
  1711. });
  1712. shelfContainerObs.observe(document.querySelector("#contents.ytmusic-section-list-renderer"), {
  1713. childList: true,
  1714. });
  1715. observers.concat([shelfContainerObs]);
  1716. });
  1717. }
  1718. /***/ })
  1719. /******/ });
  1720. /************************************************************************/
  1721. /******/ // The module cache
  1722. /******/ var __webpack_module_cache__ = {};
  1723. /******/
  1724. /******/ // The require function
  1725. /******/ function __webpack_require__(moduleId) {
  1726. /******/ // Check if module is in cache
  1727. /******/ var cachedModule = __webpack_module_cache__[moduleId];
  1728. /******/ if (cachedModule !== undefined) {
  1729. /******/ return cachedModule.exports;
  1730. /******/ }
  1731. /******/ // Create a new module (and put it into the cache)
  1732. /******/ var module = __webpack_module_cache__[moduleId] = {
  1733. /******/ // no module.id needed
  1734. /******/ // no module.loaded needed
  1735. /******/ exports: {}
  1736. /******/ };
  1737. /******/
  1738. /******/ // Execute the module function
  1739. /******/ __webpack_modules__[moduleId](module, module.exports, __webpack_require__);
  1740. /******/
  1741. /******/ // Return the exports of the module
  1742. /******/ return module.exports;
  1743. /******/ }
  1744. /******/
  1745. /************************************************************************/
  1746. /******/ /* webpack/runtime/define property getters */
  1747. /******/ !function() {
  1748. /******/ // define getter functions for harmony exports
  1749. /******/ __webpack_require__.d = function(exports, definition) {
  1750. /******/ for(var key in definition) {
  1751. /******/ if(__webpack_require__.o(definition, key) && !__webpack_require__.o(exports, key)) {
  1752. /******/ Object.defineProperty(exports, key, { enumerable: true, get: definition[key] });
  1753. /******/ }
  1754. /******/ }
  1755. /******/ };
  1756. /******/ }();
  1757. /******/
  1758. /******/ /* webpack/runtime/hasOwnProperty shorthand */
  1759. /******/ !function() {
  1760. /******/ __webpack_require__.o = function(obj, prop) { return Object.prototype.hasOwnProperty.call(obj, prop); }
  1761. /******/ }();
  1762. /******/
  1763. /******/ /* webpack/runtime/make namespace object */
  1764. /******/ !function() {
  1765. /******/ // define __esModule on exports
  1766. /******/ __webpack_require__.r = function(exports) {
  1767. /******/ if(typeof Symbol !== 'undefined' && Symbol.toStringTag) {
  1768. /******/ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
  1769. /******/ }
  1770. /******/ Object.defineProperty(exports, '__esModule', { value: true });
  1771. /******/ };
  1772. /******/ }();
  1773. /******/
  1774. /************************************************************************/
  1775. var __webpack_exports__ = {};
  1776. // This entry need to be wrapped in an IIFE because it need to be isolated against other modules in the chunk.
  1777. !function() {
  1778. /*!**********************!*\
  1779. !*** ./src/index.ts ***!
  1780. \**********************/
  1781. __webpack_require__.r(__webpack_exports__);
  1782. /* harmony import */ var _config__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./config */ "./src/config.ts");
  1783. /* harmony import */ var _constants__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./constants */ "./src/constants.ts");
  1784. /* harmony import */ var _utils__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./utils */ "./src/utils.ts");
  1785. /* harmony import */ var _features_index__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./features/index */ "./src/features/index.ts");
  1786. var __awaiter = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) {
  1787. function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
  1788. return new (P || (P = Promise))(function (resolve, reject) {
  1789. function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
  1790. function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
  1791. function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
  1792. step((generator = generator.apply(thisArg, _arguments || [])).next());
  1793. });
  1794. };
  1795. // TODO: add some style
  1796. console.log(`${_constants__WEBPACK_IMPORTED_MODULE_1__.scriptInfo.name} v${_constants__WEBPACK_IMPORTED_MODULE_1__.scriptInfo.version} (${_constants__WEBPACK_IMPORTED_MODULE_1__.scriptInfo.lastCommit}) - ${_constants__WEBPACK_IMPORTED_MODULE_1__.scriptInfo.namespace}`);
  1797. console.log(`Powered by lots of ambition and my song metadata API: ${_features_index__WEBPACK_IMPORTED_MODULE_3__.geniUrlBase}`);
  1798. const domain = (0,_utils__WEBPACK_IMPORTED_MODULE_2__.getDomain)();
  1799. /** Stuff that needs to be called ASAP, before anything async happens */
  1800. function preInit() {
  1801. (0,_utils__WEBPACK_IMPORTED_MODULE_2__.setLogLevel)(_constants__WEBPACK_IMPORTED_MODULE_1__.logLevel);
  1802. if (domain === "ytm")
  1803. (0,_features_index__WEBPACK_IMPORTED_MODULE_3__.initBeforeUnloadHook)();
  1804. init();
  1805. }
  1806. function init() {
  1807. return __awaiter(this, void 0, void 0, function* () {
  1808. yield (0,_features_index__WEBPACK_IMPORTED_MODULE_3__.preInitLayout)();
  1809. try {
  1810. document.addEventListener("DOMContentLoaded", onDomLoad);
  1811. }
  1812. catch (err) {
  1813. console.error(`${_constants__WEBPACK_IMPORTED_MODULE_1__.scriptInfo.name} - General Error:`, err);
  1814. }
  1815. try {
  1816. (0,_features_index__WEBPACK_IMPORTED_MODULE_3__.initMenu)();
  1817. }
  1818. catch (err) {
  1819. (0,_utils__WEBPACK_IMPORTED_MODULE_2__.error)("Couldn't initialize menu:", err);
  1820. }
  1821. });
  1822. }
  1823. /** Called when the DOM has finished loading and can be queried and altered by the userscript */
  1824. function onDomLoad() {
  1825. return __awaiter(this, void 0, void 0, function* () {
  1826. // post-build these double quotes are replaced by backticks
  1827. (0,_utils__WEBPACK_IMPORTED_MODULE_2__.addGlobalStyle)(`/*!***************************************************************************!*\
  1828. !*** css ./node_modules/css-loader/dist/cjs.js!./src/features/layout.css ***!
  1829. \***************************************************************************/
  1830. #betterytm-watermark {
  1831. font-size: 10px;
  1832. display: inline-block;
  1833. position: absolute;
  1834. left: 45px;
  1835. top: 46px;
  1836. z-index: 10;
  1837. color: white;
  1838. text-decoration: none;
  1839. cursor: pointer;
  1840. }
  1841. @media(max-width: 615px) {
  1842. #betterytm-watermark {
  1843. display: none;
  1844. }
  1845. }
  1846. #betterytm-watermark:hover {
  1847. text-decoration: underline;
  1848. }
  1849. .side-panel.modular ytmusic-player-queue-item .song-info.ytmusic-player-queue-item {
  1850. position: relative;
  1851. }
  1852. .side-panel.modular ytmusic-player-queue-item .song-info .bytm-queue-btn-container {
  1853. display: none;
  1854. position: absolute;
  1855. right: 0;
  1856. }
  1857. .side-panel.modular ytmusic-player-queue-item:hover .song-info .bytm-queue-btn-container {
  1858. display: inline-block;
  1859. }
  1860. /*!***************************************************************************!*\
  1861. !*** css ./node_modules/css-loader/dist/cjs.js!./src/features/lyrics.css ***!
  1862. \***************************************************************************/
  1863. #betterytm-lyrics-button {
  1864. align-items: center;
  1865. justify-content: center;
  1866. position: relative;
  1867. vertical-align: middle;
  1868. margin-left: 8px;
  1869. width: 40px;
  1870. height: 40px;
  1871. border-radius: 100%;
  1872. background-color: transparent;
  1873. }
  1874. #betterytm-lyrics-button:hover {
  1875. background-color: #383838;
  1876. }
  1877. #betterytm-lyrics-img {
  1878. display: inline-block;
  1879. z-index: 10;
  1880. width: 24px;
  1881. height: 24px;
  1882. padding: 5px;
  1883. }
  1884. /*!******************************************************************************!*\
  1885. !*** css ./node_modules/css-loader/dist/cjs.js!./src/features/menu/menu.css ***!
  1886. \******************************************************************************/
  1887. /* #bytm-menu-backdrop {
  1888. display: none;
  1889. flex-direction: column;
  1890. justify-content: center;
  1891. align-items: center;
  1892. }
  1893. #bytm-menu-backdrop[data-menu-open="true"] {
  1894. display: flex;
  1895. } */
  1896. #bytm-menu-header-container {
  1897. display: flex;
  1898. justify-content: flex-start;
  1899. align-items: center;
  1900. border-color: #ffffff;
  1901. border-style: none solid none none;
  1902. }
  1903. .bytm-menu-header-option {
  1904. display: "flex";
  1905. justify-content: center;
  1906. align-items: center;
  1907. border-color: #ffffff;
  1908. border-style: solid none solid none;
  1909. }
  1910. #bytm-menu-header-option h3 {
  1911. margin: 0;
  1912. }
  1913. .bytm-menu-tab[data-active="true"] {
  1914. display: none;
  1915. }
  1916. .bytm-menu-tab[data-active="false"] {
  1917. display: none;
  1918. }`, "global");
  1919. const features = yield (0,_config__WEBPACK_IMPORTED_MODULE_0__.loadFeatureConf)();
  1920. (0,_utils__WEBPACK_IMPORTED_MODULE_2__.log)(`Initializing features for domain '${domain}'`);
  1921. try {
  1922. if (domain === "ytm") {
  1923. (0,_utils__WEBPACK_IMPORTED_MODULE_2__.initSiteEvents)();
  1924. if (features.arrowKeySupport)
  1925. (0,_features_index__WEBPACK_IMPORTED_MODULE_3__.initArrowKeySkip)();
  1926. if (features.removeUpgradeTab)
  1927. (0,_features_index__WEBPACK_IMPORTED_MODULE_3__.removeUpgradeTab)();
  1928. if (features.watermarkEnabled)
  1929. (0,_features_index__WEBPACK_IMPORTED_MODULE_3__.addWatermark)();
  1930. if (features.geniusLyrics)
  1931. (0,_features_index__WEBPACK_IMPORTED_MODULE_3__.addMediaCtrlLyricsBtn)();
  1932. if (features.queueButtons)
  1933. (0,_features_index__WEBPACK_IMPORTED_MODULE_3__.initQueueButtons)();
  1934. if (typeof features.volumeSliderSize === "number")
  1935. (0,_features_index__WEBPACK_IMPORTED_MODULE_3__.setVolSliderSize)();
  1936. if (features.anchorImprovements)
  1937. (0,_features_index__WEBPACK_IMPORTED_MODULE_3__.addAnchorImprovements)();
  1938. (0,_features_index__WEBPACK_IMPORTED_MODULE_3__.setVolSliderStep)();
  1939. }
  1940. if (["ytm", "yt"].includes(domain)) {
  1941. if (features.switchBetweenSites)
  1942. (0,_features_index__WEBPACK_IMPORTED_MODULE_3__.initSiteSwitch)(domain);
  1943. try {
  1944. (0,_features_index__WEBPACK_IMPORTED_MODULE_3__.addMenu)(); // TODO: remove
  1945. }
  1946. catch (err) {
  1947. (0,_utils__WEBPACK_IMPORTED_MODULE_2__.error)("Couldn't add menu:", err);
  1948. }
  1949. }
  1950. }
  1951. catch (err) {
  1952. (0,_utils__WEBPACK_IMPORTED_MODULE_2__.error)("General error while executing feature:", err);
  1953. }
  1954. });
  1955. }
  1956. preInit();
  1957. }();
  1958. //# sourceMappingURL=BetterYTM.user.js.map