BetterYTM.user.js 101 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225
  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<p>TODO:</p>\n<ul>\n<li>Added menu to configure features</li>\n<li>New configurable features:<ul>\n<li>Make volume slider bigger</li>\n<li>Choose step of volume slider for finer control</li>\n<li>Add lyrics button to each song in a playlist</li>\n</ul>\n</li>\n<li>Changes / Fixes:<ul>\n<li>Now the lyrics button will directly link to the lyrics (using my API <a href=\"https://github.com/Sv443/geniURL\">geniURL</a>)</li>\n<li>Site switch with <kbd>F9</kbd> will now keep the video time</li>\n</ul>\n</li>\n</ul>\n<br>\n\n<h2 id=\"020\">0.2.0</h2>\n<ul>\n<li>Added Features:<ul>\n<li>Switch between YouTube and YT Music (with <kbd>F9</kbd> by default)</li>\n<li>Search for song lyrics with new button in media controls</li>\n<li>Remove &quot;Upgrade to YTM Premium&quot; tab</li>\n</ul>\n</li>\n</ul>\n<br>\n\n<h2 id=\"010\">0.1.0</h2>\n<ul>\n<li>Added support for arrow keys to skip forward or backward (currently only by fixed 10 second interval)</li>\n</ul>\n<p><br><br><br><br><br><br><br><br><br></p>\n";
  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: "e9f4f18", // assert as generic string instead of union
  462. });
  463. /***/ }),
  464. /***/ "./src/events.ts":
  465. /*!***********************!*\
  466. !*** ./src/events.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 */ getEvtData: function() { return /* binding */ getEvtData; },
  472. /* harmony export */ initSiteEvents: function() { return /* binding */ initSiteEvents; },
  473. /* harmony export */ removeAllObservers: function() { return /* binding */ removeAllObservers; },
  474. /* harmony export */ siteEvents: function() { return /* binding */ siteEvents; }
  475. /* harmony export */ });
  476. /* harmony import */ var _billjs_event_emitter__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @billjs/event-emitter */ "./node_modules/@billjs/event-emitter/lib/index.js");
  477. /* harmony import */ var _utils__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./utils */ "./src/utils.ts");
  478. var __awaiter = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) {
  479. function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
  480. return new (P || (P = Promise))(function (resolve, reject) {
  481. function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
  482. function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
  483. function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
  484. step((generator = generator.apply(thisArg, _arguments || [])).next());
  485. });
  486. };
  487. /** EventEmitter instance that is used to detect changes to the site */
  488. const siteEvents = new _billjs_event_emitter__WEBPACK_IMPORTED_MODULE_0__.EventEmitter();
  489. /**
  490. * Returns the data of an event from the `@billjs/event-emitter` library.
  491. * This function is used as a shorthand to extract the data and assert it with the type passed in `<T>`
  492. * @param evt Event object from the `.on()` or `.once()` method
  493. * @template T Type of the data passed by `.fire(type: string, data: T)`
  494. */
  495. function getEvtData(evt) {
  496. return evt.data;
  497. }
  498. let observers = [];
  499. /** Disconnects and deletes all observers. Run `initSiteEvents()` again to create new ones. */
  500. function removeAllObservers() {
  501. observers.forEach((observer) => observer.disconnect());
  502. observers = [];
  503. }
  504. /** Creates MutationObservers that check if parts of the site have changed, then emit an event on the `siteEvents` instance. */
  505. function initSiteEvents() {
  506. return __awaiter(this, void 0, void 0, function* () {
  507. try {
  508. //#SECTION queue
  509. // the queue container always exists so it doesn't need the extra init function
  510. const queueObs = new MutationObserver(([{ addedNodes, removedNodes, target }]) => {
  511. if (addedNodes.length > 0 || removedNodes.length > 0) {
  512. (0,_utils__WEBPACK_IMPORTED_MODULE_1__.info)(`Detected queue change - added nodes: ${[...addedNodes.values()].length} - removed nodes: ${[...removedNodes.values()].length}`);
  513. siteEvents.fire("queueChanged", target);
  514. }
  515. });
  516. // only observe added or removed elements
  517. queueObs.observe(document.querySelector(".side-panel.modular #contents.ytmusic-player-queue"), {
  518. childList: true,
  519. });
  520. //#SECTION home page observers
  521. initHomeObservers();
  522. (0,_utils__WEBPACK_IMPORTED_MODULE_1__.info)("Successfully initialized SiteEvents observers");
  523. observers = [
  524. queueObs,
  525. ];
  526. }
  527. catch (err) {
  528. (0,_utils__WEBPACK_IMPORTED_MODULE_1__.error)("Couldn't initialize SiteEvents observers due to an error:\n", err);
  529. }
  530. });
  531. }
  532. /**
  533. * The home page might not exist yet if the site was accessed through any path like /watch directly.
  534. * This function will keep waiting for when the home page exists, then create the necessary MutationObservers.
  535. */
  536. function initHomeObservers() {
  537. var _a;
  538. return __awaiter(this, void 0, void 0, function* () {
  539. let interval;
  540. // hidden="" attribute is only present if the content of the page doesn't exist yet
  541. // so this pauses execution until that attribute is removed
  542. if ((_a = document.querySelector("ytmusic-browse-response#browse-page")) === null || _a === void 0 ? void 0 : _a.hasAttribute("hidden")) {
  543. yield new Promise((res) => {
  544. interval = setInterval(() => {
  545. var _a;
  546. if (!((_a = document.querySelector("ytmusic-browse-response#browse-page")) === null || _a === void 0 ? void 0 : _a.hasAttribute("hidden"))) {
  547. clearInterval(interval);
  548. res();
  549. }
  550. }, 50);
  551. });
  552. }
  553. siteEvents.fire("homePageLoaded");
  554. (0,_utils__WEBPACK_IMPORTED_MODULE_1__.info)("Initialized home page observers");
  555. //#SECTION carousel shelves
  556. const shelfContainerObs = new MutationObserver(([{ addedNodes, removedNodes }]) => {
  557. if (addedNodes.length > 0 || removedNodes.length > 0) {
  558. (0,_utils__WEBPACK_IMPORTED_MODULE_1__.info)("Detected carousel shelf container change - added nodes:", addedNodes.length, "- removed nodes:", removedNodes.length);
  559. siteEvents.fire("carouselShelvesChanged", { addedNodes, removedNodes });
  560. }
  561. });
  562. shelfContainerObs.observe(document.querySelector("#contents.ytmusic-section-list-renderer"), {
  563. childList: true,
  564. });
  565. observers = observers.concat([shelfContainerObs]);
  566. });
  567. }
  568. /***/ }),
  569. /***/ "./src/features/index.ts":
  570. /*!*******************************!*\
  571. !*** ./src/features/index.ts ***!
  572. \*******************************/
  573. /***/ (function(__unused_webpack_module, __webpack_exports__, __webpack_require__) {
  574. __webpack_require__.r(__webpack_exports__);
  575. /* harmony export */ __webpack_require__.d(__webpack_exports__, {
  576. /* harmony export */ addAnchorImprovements: function() { return /* reexport safe */ _layout__WEBPACK_IMPORTED_MODULE_2__.addAnchorImprovements; },
  577. /* harmony export */ addLyricsCacheEntry: function() { return /* reexport safe */ _lyrics__WEBPACK_IMPORTED_MODULE_3__.addLyricsCacheEntry; },
  578. /* harmony export */ addMediaCtrlLyricsBtn: function() { return /* reexport safe */ _lyrics__WEBPACK_IMPORTED_MODULE_3__.addMediaCtrlLyricsBtn; },
  579. /* harmony export */ addMenu: function() { return /* reexport safe */ _menu_menu_old__WEBPACK_IMPORTED_MODULE_5__.addMenu; },
  580. /* harmony export */ addWatermark: function() { return /* reexport safe */ _layout__WEBPACK_IMPORTED_MODULE_2__.addWatermark; },
  581. /* harmony export */ closeMenu: function() { return /* reexport safe */ _menu_menu_old__WEBPACK_IMPORTED_MODULE_5__.closeMenu; },
  582. /* harmony export */ createLyricsBtn: function() { return /* reexport safe */ _lyrics__WEBPACK_IMPORTED_MODULE_3__.createLyricsBtn; },
  583. /* harmony export */ disableBeforeUnload: function() { return /* reexport safe */ _input__WEBPACK_IMPORTED_MODULE_1__.disableBeforeUnload; },
  584. /* harmony export */ enableBeforeUnload: function() { return /* reexport safe */ _input__WEBPACK_IMPORTED_MODULE_1__.enableBeforeUnload; },
  585. /* harmony export */ featInfo: function() { return /* binding */ featInfo; },
  586. /* harmony export */ geniUrlBase: function() { return /* reexport safe */ _lyrics__WEBPACK_IMPORTED_MODULE_3__.geniUrlBase; },
  587. /* harmony export */ getCurrentLyricsUrl: function() { return /* reexport safe */ _lyrics__WEBPACK_IMPORTED_MODULE_3__.getCurrentLyricsUrl; },
  588. /* harmony export */ getGeniusUrl: function() { return /* reexport safe */ _lyrics__WEBPACK_IMPORTED_MODULE_3__.getGeniusUrl; },
  589. /* harmony export */ getLyricsCacheEntry: function() { return /* reexport safe */ _lyrics__WEBPACK_IMPORTED_MODULE_3__.getLyricsCacheEntry; },
  590. /* harmony export */ initArrowKeySkip: function() { return /* reexport safe */ _input__WEBPACK_IMPORTED_MODULE_1__.initArrowKeySkip; },
  591. /* harmony export */ initBeforeUnloadHook: function() { return /* reexport safe */ _input__WEBPACK_IMPORTED_MODULE_1__.initBeforeUnloadHook; },
  592. /* harmony export */ initMenu: function() { return /* reexport safe */ _menu_menu__WEBPACK_IMPORTED_MODULE_4__.initMenu; },
  593. /* harmony export */ initQueueButtons: function() { return /* reexport safe */ _layout__WEBPACK_IMPORTED_MODULE_2__.initQueueButtons; },
  594. /* harmony export */ initSiteSwitch: function() { return /* reexport safe */ _input__WEBPACK_IMPORTED_MODULE_1__.initSiteSwitch; },
  595. /* harmony export */ openMenu: function() { return /* reexport safe */ _menu_menu_old__WEBPACK_IMPORTED_MODULE_5__.openMenu; },
  596. /* harmony export */ preInitLayout: function() { return /* reexport safe */ _layout__WEBPACK_IMPORTED_MODULE_2__.preInitLayout; },
  597. /* harmony export */ removeUpgradeTab: function() { return /* reexport safe */ _layout__WEBPACK_IMPORTED_MODULE_2__.removeUpgradeTab; },
  598. /* harmony export */ sanitizeArtists: function() { return /* reexport safe */ _lyrics__WEBPACK_IMPORTED_MODULE_3__.sanitizeArtists; },
  599. /* harmony export */ sanitizeSong: function() { return /* reexport safe */ _lyrics__WEBPACK_IMPORTED_MODULE_3__.sanitizeSong; },
  600. /* harmony export */ setVolSliderSize: function() { return /* reexport safe */ _layout__WEBPACK_IMPORTED_MODULE_2__.setVolSliderSize; },
  601. /* harmony export */ setVolSliderStep: function() { return /* reexport safe */ _layout__WEBPACK_IMPORTED_MODULE_2__.setVolSliderStep; }
  602. /* harmony export */ });
  603. /* harmony import */ var _constants__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../constants */ "./src/constants.ts");
  604. /* harmony import */ var _input__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./input */ "./src/features/input.ts");
  605. /* harmony import */ var _layout__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./layout */ "./src/features/layout.ts");
  606. /* harmony import */ var _lyrics__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./lyrics */ "./src/features/lyrics.ts");
  607. /* harmony import */ var _menu_menu__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./menu/menu */ "./src/features/menu/menu.ts");
  608. /* harmony import */ var _menu_menu_old__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./menu/menu_old */ "./src/features/menu/menu_old.ts");
  609. // TODO
  610. /** Contains all possible features with their default values and other config */
  611. const featInfo = {
  612. //#SECTION input
  613. arrowKeySupport: {
  614. desc: "Arrow keys skip forwards and backwards by 10 seconds",
  615. type: "toggle",
  616. category: "input",
  617. default: true,
  618. },
  619. switchBetweenSites: {
  620. desc: "Add F9 as a hotkey to switch between the YT and YTM sites on a video / song",
  621. type: "toggle",
  622. category: "input",
  623. default: true,
  624. },
  625. switchSitesHotkey: {
  626. desc: "TODO: Which hotkey needs to be pressed to switch sites?",
  627. type: "hotkey",
  628. category: "input",
  629. default: {
  630. key: "F9",
  631. shift: false,
  632. ctrl: false,
  633. meta: false,
  634. },
  635. visible: false,
  636. },
  637. disableBeforeUnloadPopup: {
  638. desc: "Completely disable the popup that sometimes appears before leaving the site",
  639. type: "toggle",
  640. category: "input",
  641. default: false,
  642. },
  643. anchorImprovements: {
  644. desc: "TODO: Make it so middle clicking a song to open it in a new tab is easier",
  645. type: "toggle",
  646. category: "input",
  647. default: true,
  648. visible: false,
  649. },
  650. //#SECTION layout
  651. removeUpgradeTab: {
  652. desc: "Remove the \"Upgrade\" / YT Music Premium tab",
  653. type: "toggle",
  654. category: "layout",
  655. default: true,
  656. },
  657. volumeSliderSize: {
  658. desc: "The width of the volume slider in pixels",
  659. type: "number",
  660. category: "layout",
  661. min: 10,
  662. max: 1000,
  663. step: 5,
  664. default: 160,
  665. unit: "px",
  666. },
  667. volumeSliderStep: {
  668. desc: "Volume slider sensitivity - the smaller this number, the finer the volume control",
  669. type: "slider",
  670. category: "layout",
  671. min: 1,
  672. max: 20,
  673. default: 2,
  674. },
  675. watermarkEnabled: {
  676. desc: `Show a ${_constants__WEBPACK_IMPORTED_MODULE_0__.scriptInfo.name} watermark under the YTM logo`,
  677. type: "toggle",
  678. category: "layout",
  679. default: true,
  680. visible: false,
  681. },
  682. queueButtons: {
  683. desc: "Add buttons while hovering over a song in a queue to quickly remove it (TODO) or open its lyrics",
  684. type: "toggle",
  685. category: "layout",
  686. default: true,
  687. },
  688. //#SECTION lyrics
  689. geniusLyrics: {
  690. desc: "Add a button to the media controls to open the current song's lyrics on genius.com in a new tab",
  691. type: "toggle",
  692. category: "lyrics",
  693. default: true,
  694. },
  695. };
  696. /***/ }),
  697. /***/ "./src/features/input.ts":
  698. /*!*******************************!*\
  699. !*** ./src/features/input.ts ***!
  700. \*******************************/
  701. /***/ (function(__unused_webpack_module, __webpack_exports__, __webpack_require__) {
  702. __webpack_require__.r(__webpack_exports__);
  703. /* harmony export */ __webpack_require__.d(__webpack_exports__, {
  704. /* harmony export */ disableBeforeUnload: function() { return /* binding */ disableBeforeUnload; },
  705. /* harmony export */ enableBeforeUnload: function() { return /* binding */ enableBeforeUnload; },
  706. /* harmony export */ initArrowKeySkip: function() { return /* binding */ initArrowKeySkip; },
  707. /* harmony export */ initBeforeUnloadHook: function() { return /* binding */ initBeforeUnloadHook; },
  708. /* harmony export */ initSiteSwitch: function() { return /* binding */ initSiteSwitch; }
  709. /* harmony export */ });
  710. /* harmony import */ var _utils__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../utils */ "./src/utils.ts");
  711. /* harmony import */ var _config__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../config */ "./src/config.ts");
  712. //#MARKER arrow key skip
  713. function initArrowKeySkip() {
  714. document.addEventListener("keydown", onKeyDown);
  715. (0,_utils__WEBPACK_IMPORTED_MODULE_0__.log)("Added key press listener");
  716. }
  717. /** Called when the user presses any key, anywhere */
  718. function onKeyDown(evt) {
  719. var _a, _b;
  720. if (["ArrowLeft", "ArrowRight"].includes(evt.code)) {
  721. // discard the event when a (text) input is currently active, like when editing a playlist
  722. if (["INPUT", "TEXTAREA", "SELECT"].includes((_b = (_a = document.activeElement) === null || _a === void 0 ? void 0 : _a.tagName) !== null && _b !== void 0 ? _b : "_"))
  723. 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`);
  724. (0,_utils__WEBPACK_IMPORTED_MODULE_0__.log)(`Captured key '${evt.code}' in proxy listener`);
  725. // 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
  726. const defaultProps = {
  727. altKey: false,
  728. ctrlKey: false,
  729. metaKey: false,
  730. shiftKey: false,
  731. target: document.body,
  732. currentTarget: document.body,
  733. originalTarget: document.body,
  734. explicitOriginalTarget: document.body,
  735. srcElement: document.body,
  736. type: "keydown",
  737. bubbles: true,
  738. cancelBubble: false,
  739. cancelable: true,
  740. isTrusted: true,
  741. repeat: false,
  742. // needed because otherwise YTM errors out - see https://github.com/Sv443/BetterYTM/issues/18#show_issue
  743. view: unsafeWindow !== null && unsafeWindow !== void 0 ? unsafeWindow : window,
  744. };
  745. let invalidKey = false;
  746. let keyProps = {};
  747. switch (evt.code) {
  748. case "ArrowLeft":
  749. keyProps = {
  750. code: "KeyH",
  751. key: "h",
  752. keyCode: 72,
  753. which: 72,
  754. };
  755. break;
  756. case "ArrowRight":
  757. keyProps = {
  758. code: "KeyL",
  759. key: "l",
  760. keyCode: 76,
  761. which: 76,
  762. };
  763. break;
  764. default:
  765. invalidKey = true;
  766. break;
  767. }
  768. if (!invalidKey) {
  769. const proxyProps = Object.assign(Object.assign({ code: "" }, defaultProps), keyProps);
  770. document.body.dispatchEvent(new KeyboardEvent("keydown", proxyProps));
  771. (0,_utils__WEBPACK_IMPORTED_MODULE_0__.log)(`Dispatched proxy keydown event: [${evt.code}] -> [${proxyProps.code}]`);
  772. }
  773. else
  774. (0,_utils__WEBPACK_IMPORTED_MODULE_0__.warn)(`Captured key '${evt.code}' has no defined behavior`);
  775. }
  776. }
  777. //#MARKER site switch
  778. /** Initializes the site switch feature */
  779. function initSiteSwitch(domain) {
  780. // TODO:
  781. // extra features:
  782. // - keep video time
  783. // - configurable hotkey
  784. document.addEventListener("keydown", (e) => {
  785. if (e.key === "F9")
  786. switchSite(domain === "yt" ? "ytm" : "yt");
  787. });
  788. (0,_utils__WEBPACK_IMPORTED_MODULE_0__.log)("Initialized site switch listener");
  789. }
  790. /** Switches to the other site (between YT and YTM) */
  791. function switchSite(newDomain) {
  792. var _a;
  793. try {
  794. let subdomain;
  795. if (newDomain === "ytm")
  796. subdomain = "music";
  797. else if (newDomain === "yt")
  798. subdomain = "www";
  799. if (!subdomain)
  800. throw new TypeError(`Unrecognized domain '${newDomain}'`);
  801. const { pathname, search, hash } = new URL(location.href);
  802. const vt = (_a = (0,_utils__WEBPACK_IMPORTED_MODULE_0__.getVideoTime)()) !== null && _a !== void 0 ? _a : 0;
  803. (0,_utils__WEBPACK_IMPORTED_MODULE_0__.log)(`Found video time of ${vt} seconds`);
  804. const newSearch = search.includes("?") ? `${search}&t=${vt}` : `?t=${vt}`;
  805. const url = `https://${subdomain}.youtube.com${pathname}${newSearch}${hash}`;
  806. console.info(`BetterYTM - switching to domain '${newDomain}' at ${url}`);
  807. disableBeforeUnload();
  808. location.assign(url);
  809. }
  810. catch (err) {
  811. (0,_utils__WEBPACK_IMPORTED_MODULE_0__.error)("Error while switching site:", err);
  812. }
  813. }
  814. //#MARKER beforeunload popup
  815. let beforeUnloadEnabled = true;
  816. /** Disables the popup before leaving the site */
  817. function disableBeforeUnload() {
  818. beforeUnloadEnabled = false;
  819. (0,_utils__WEBPACK_IMPORTED_MODULE_0__.info)("Disabled popup before leaving the site");
  820. }
  821. /** (Re-)enables the popup before leaving the site */
  822. function enableBeforeUnload() {
  823. beforeUnloadEnabled = true;
  824. (0,_utils__WEBPACK_IMPORTED_MODULE_0__.info)("Enabled popup before leaving the site");
  825. }
  826. /**
  827. * Adds a spy function into `window.__proto__.addEventListener` to selectively discard `beforeunload`
  828. * event listeners before they can be attached by the site.
  829. */
  830. function initBeforeUnloadHook() {
  831. Error.stackTraceLimit = 1000; // default is 25 on FF so this should hopefully be more than enough
  832. (function (original) {
  833. // @ts-ignore
  834. window.__proto__.addEventListener = function (...args) {
  835. if (beforeUnloadEnabled && args[0] === "beforeunload")
  836. return (0,_utils__WEBPACK_IMPORTED_MODULE_0__.log)("Prevented beforeunload event listener from attaching");
  837. else
  838. return original.apply(this, args);
  839. };
  840. // @ts-ignore
  841. })(window.__proto__.addEventListener);
  842. (0,_config__WEBPACK_IMPORTED_MODULE_1__.getFeatures)().then(feats => {
  843. if (feats.disableBeforeUnloadPopup)
  844. disableBeforeUnload();
  845. });
  846. }
  847. /***/ }),
  848. /***/ "./src/features/layout.ts":
  849. /*!********************************!*\
  850. !*** ./src/features/layout.ts ***!
  851. \********************************/
  852. /***/ (function(__unused_webpack_module, __webpack_exports__, __webpack_require__) {
  853. __webpack_require__.r(__webpack_exports__);
  854. /* harmony export */ __webpack_require__.d(__webpack_exports__, {
  855. /* harmony export */ addAnchorImprovements: function() { return /* binding */ addAnchorImprovements; },
  856. /* harmony export */ addWatermark: function() { return /* binding */ addWatermark; },
  857. /* harmony export */ initQueueButtons: function() { return /* binding */ initQueueButtons; },
  858. /* harmony export */ preInitLayout: function() { return /* binding */ preInitLayout; },
  859. /* harmony export */ removeUpgradeTab: function() { return /* binding */ removeUpgradeTab; },
  860. /* harmony export */ setVolSliderSize: function() { return /* binding */ setVolSliderSize; },
  861. /* harmony export */ setVolSliderStep: function() { return /* binding */ setVolSliderStep; }
  862. /* harmony export */ });
  863. /* harmony import */ var _constants__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../constants */ "./src/constants.ts");
  864. /* harmony import */ var _config__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../config */ "./src/config.ts");
  865. /* harmony import */ var _utils__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../utils */ "./src/utils.ts");
  866. /* harmony import */ var _events__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../events */ "./src/events.ts");
  867. /* harmony import */ var _menu_menu_old__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./menu/menu_old */ "./src/features/menu/menu_old.ts");
  868. /* harmony import */ var _layout_css__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./layout.css */ "./src/features/layout.css");
  869. /* harmony import */ var _lyrics__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ./lyrics */ "./src/features/lyrics.ts");
  870. var __awaiter = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) {
  871. function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
  872. return new (P || (P = Promise))(function (resolve, reject) {
  873. function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
  874. function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
  875. function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
  876. step((generator = generator.apply(thisArg, _arguments || [])).next());
  877. });
  878. };
  879. let features;
  880. function preInitLayout() {
  881. return __awaiter(this, void 0, void 0, function* () {
  882. features = yield (0,_config__WEBPACK_IMPORTED_MODULE_1__.getFeatures)();
  883. });
  884. }
  885. //#MARKER watermark
  886. /** Adds a watermark beneath the logo */
  887. function addWatermark() {
  888. const watermark = document.createElement("a");
  889. watermark.role = "button";
  890. watermark.id = "betterytm-watermark";
  891. watermark.className = "style-scope ytmusic-nav-bar";
  892. watermark.innerText = _constants__WEBPACK_IMPORTED_MODULE_0__.scriptInfo.name;
  893. watermark.title = "Open menu";
  894. watermark.tabIndex = 1000;
  895. watermark.addEventListener("click", () => (0,_menu_menu_old__WEBPACK_IMPORTED_MODULE_4__.openMenu)());
  896. watermark.addEventListener("keydown", (e) => e.key === "Enter" && (0,_menu_menu_old__WEBPACK_IMPORTED_MODULE_4__.openMenu)());
  897. const logoElem = document.querySelector("#left-content");
  898. (0,_utils__WEBPACK_IMPORTED_MODULE_2__.insertAfter)(logoElem, watermark);
  899. (0,_utils__WEBPACK_IMPORTED_MODULE_2__.log)("Added watermark element:", watermark);
  900. }
  901. //#MARKER remove upgrade tab
  902. let removeUpgradeTries = 0;
  903. /** Removes the "Upgrade" / YT Music Premium tab from the title / nav bar */
  904. function removeUpgradeTab() {
  905. const tabElem = document.querySelector(".ytmusic-nav-bar ytmusic-pivot-bar-item-renderer[tab-id=\"SPunlimited\"]");
  906. if (tabElem) {
  907. tabElem.remove();
  908. (0,_utils__WEBPACK_IMPORTED_MODULE_2__.log)(`Removed upgrade tab after ${removeUpgradeTries} tries`);
  909. }
  910. else if (removeUpgradeTries < _constants__WEBPACK_IMPORTED_MODULE_0__.triesLimit) {
  911. setTimeout(removeUpgradeTab, _constants__WEBPACK_IMPORTED_MODULE_0__.triesInterval); // TODO: improve this
  912. removeUpgradeTries++;
  913. }
  914. else
  915. (0,_utils__WEBPACK_IMPORTED_MODULE_2__.error)(`Couldn't find upgrade tab to remove after ${removeUpgradeTries} tries`);
  916. }
  917. //#MARKER volume slider
  918. /** Sets the volume slider to a set size */
  919. function setVolSliderSize() {
  920. const { volumeSliderSize: size } = features;
  921. if (typeof size !== "number" || isNaN(Number(size)))
  922. return;
  923. const style = `\
  924. .volume-slider.ytmusic-player-bar, .expand-volume-slider.ytmusic-player-bar {
  925. width: ${size}px !important;
  926. }`;
  927. (0,_utils__WEBPACK_IMPORTED_MODULE_2__.addGlobalStyle)(style, "vol-slider");
  928. }
  929. /** Sets the `step` attribute of the volume slider */
  930. function setVolSliderStep() {
  931. const sliderElem = document.querySelector("tp-yt-paper-slider#volume-slider");
  932. sliderElem.setAttribute("step", String(features.volumeSliderStep));
  933. }
  934. //#MARKER queue buttons
  935. // 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
  936. function initQueueButtons() {
  937. _events__WEBPACK_IMPORTED_MODULE_3__.siteEvents.on("queueChanged", (evt) => {
  938. let amt = 0;
  939. for (const queueItm of (0,_events__WEBPACK_IMPORTED_MODULE_3__.getEvtData)(evt).childNodes) {
  940. if (!queueItm.classList.contains("bytm-has-queue-btns")) {
  941. addQueueButtons(queueItm);
  942. amt++;
  943. }
  944. }
  945. if (amt > 0)
  946. (0,_utils__WEBPACK_IMPORTED_MODULE_2__.log)(`Added buttons to ${amt} new queue ${(0,_utils__WEBPACK_IMPORTED_MODULE_2__.autoPlural)("item", amt)}`);
  947. });
  948. const queueItems = document.querySelectorAll("#contents.ytmusic-player-queue > ytmusic-player-queue-item");
  949. if (queueItems.length === 0)
  950. return;
  951. queueItems.forEach(itm => addQueueButtons(itm));
  952. (0,_utils__WEBPACK_IMPORTED_MODULE_2__.log)(`Added buttons to ${queueItems.length} existing queue items`);
  953. }
  954. /**
  955. * Adds the buttons to each item in the current song queue.
  956. * Also observes for changes to add new buttons to new items in the queue.
  957. */
  958. function addQueueButtons(queueItem) {
  959. return __awaiter(this, void 0, void 0, function* () {
  960. const queueBtnsCont = document.createElement("div");
  961. queueBtnsCont.className = "bytm-queue-btn-container";
  962. const songInfo = queueItem.querySelector(".song-info");
  963. if (!songInfo)
  964. return false;
  965. const [songEl, artistEl] = songInfo.querySelectorAll("yt-formatted-string");
  966. const song = songEl.innerText;
  967. const artist = artistEl.innerText;
  968. if (!song || !artist)
  969. return false;
  970. // TODO: display "currently loading" icon
  971. const lyricsBtnElem = (0,_lyrics__WEBPACK_IMPORTED_MODULE_6__.createLyricsBtn)(undefined, false);
  972. lyricsBtnElem.title = "Open this song's lyrics in a new tab";
  973. lyricsBtnElem.style.cursor = "pointer";
  974. lyricsBtnElem.style.visibility = "initial";
  975. lyricsBtnElem.style.display = "inline-flex";
  976. lyricsBtnElem.style.pointerEvents = "initial";
  977. lyricsBtnElem.addEventListener("click", () => __awaiter(this, void 0, void 0, function* () {
  978. let lyricsUrl;
  979. if (songInfo.dataset.bytmLyrics && songInfo.dataset.bytmLyrics.length > 0)
  980. lyricsUrl = songInfo.dataset.bytmLyrics;
  981. else if (songInfo.dataset.bytmLoading !== "true") {
  982. songInfo.dataset.bytmLoading = "true";
  983. const imgEl = lyricsBtnElem.querySelector("img");
  984. imgEl.src = (0,_utils__WEBPACK_IMPORTED_MODULE_2__.getAssetUrl)("loading.gif");
  985. lyricsUrl = yield (0,_lyrics__WEBPACK_IMPORTED_MODULE_6__.getGeniusUrl)((0,_lyrics__WEBPACK_IMPORTED_MODULE_6__.sanitizeArtists)(artist), (0,_lyrics__WEBPACK_IMPORTED_MODULE_6__.sanitizeSong)(song));
  986. songInfo.dataset.bytmLoading = "false";
  987. imgEl.src = (0,_utils__WEBPACK_IMPORTED_MODULE_2__.getAssetUrl)("external/genius.png");
  988. if (!lyricsUrl) {
  989. if (confirm("Couldn't find a lyrics page for this song.\nDo you want to open genius.com to manually search for it?"))
  990. (0,_utils__WEBPACK_IMPORTED_MODULE_2__.openInNewTab)("https://genius.com/search");
  991. return;
  992. }
  993. songInfo.dataset.bytmLyrics = lyricsUrl;
  994. }
  995. lyricsUrl && (0,_utils__WEBPACK_IMPORTED_MODULE_2__.openInNewTab)(lyricsUrl);
  996. }));
  997. queueBtnsCont.appendChild(lyricsBtnElem);
  998. songInfo.appendChild(queueBtnsCont);
  999. queueItem.classList.add("bytm-has-queue-btns");
  1000. return true;
  1001. });
  1002. }
  1003. //#MARKER better clickable stuff
  1004. // TODO: account for the fact initially the elements might not exist, if the site was opened directly with the /watch path
  1005. function addAnchorImprovements() {
  1006. void 0;
  1007. }
  1008. /***/ }),
  1009. /***/ "./src/features/lyrics.ts":
  1010. /*!********************************!*\
  1011. !*** ./src/features/lyrics.ts ***!
  1012. \********************************/
  1013. /***/ (function(__unused_webpack_module, __webpack_exports__, __webpack_require__) {
  1014. __webpack_require__.r(__webpack_exports__);
  1015. /* harmony export */ __webpack_require__.d(__webpack_exports__, {
  1016. /* harmony export */ addLyricsCacheEntry: function() { return /* binding */ addLyricsCacheEntry; },
  1017. /* harmony export */ addMediaCtrlLyricsBtn: function() { return /* binding */ addMediaCtrlLyricsBtn; },
  1018. /* harmony export */ createLyricsBtn: function() { return /* binding */ createLyricsBtn; },
  1019. /* harmony export */ geniUrlBase: function() { return /* binding */ geniUrlBase; },
  1020. /* harmony export */ getCurrentLyricsUrl: function() { return /* binding */ getCurrentLyricsUrl; },
  1021. /* harmony export */ getGeniusUrl: function() { return /* binding */ getGeniusUrl; },
  1022. /* harmony export */ getLyricsCacheEntry: function() { return /* binding */ getLyricsCacheEntry; },
  1023. /* harmony export */ sanitizeArtists: function() { return /* binding */ sanitizeArtists; },
  1024. /* harmony export */ sanitizeSong: function() { return /* binding */ sanitizeSong; }
  1025. /* harmony export */ });
  1026. /* harmony import */ var _constants__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../constants */ "./src/constants.ts");
  1027. /* harmony import */ var _utils__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../utils */ "./src/utils.ts");
  1028. /* harmony import */ var _lyrics_css__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./lyrics.css */ "./src/features/lyrics.css");
  1029. var __awaiter = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) {
  1030. function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
  1031. return new (P || (P = Promise))(function (resolve, reject) {
  1032. function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
  1033. function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
  1034. function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
  1035. step((generator = generator.apply(thisArg, _arguments || [])).next());
  1036. });
  1037. };
  1038. var __asyncValues = (undefined && undefined.__asyncValues) || function (o) {
  1039. if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined.");
  1040. var m = o[Symbol.asyncIterator], i;
  1041. 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);
  1042. 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); }); }; }
  1043. function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); }
  1044. };
  1045. /** Base URL of geniURL */
  1046. const geniUrlBase = "https://api.sv443.net/geniurl";
  1047. /** GeniURL endpoint that gives song metadata when provided with a `?q` or `?artist` and `?song` parameter - [more info](https://api.sv443.net/geniurl) */
  1048. const geniURLSearchTopUrl = `${geniUrlBase}/search/top`;
  1049. //#MARKER cache
  1050. /** Cache with key format `ARTIST - SONG` and lyrics URLs as values. Used to prevent extraneous requests to geniURL. */
  1051. const lyricsUrlCache = new Map();
  1052. /** How many cache entries can exist at a time - this is used to cap memory usage */
  1053. const maxLyricsCacheSize = 100;
  1054. // TODO: implement this
  1055. /** Returns the lyrics URL from the passed un-/sanitized artist and song name, or undefined if the entry doesn't exist yet */
  1056. function getLyricsCacheEntry(artists, song) {
  1057. return lyricsUrlCache.get(`${sanitizeArtists(artists)} - ${sanitizeSong(song)}`);
  1058. }
  1059. /** Adds the provided entry into the lyrics URL cache */
  1060. function addLyricsCacheEntry(artists, song, lyricsUrl) {
  1061. lyricsUrlCache.set(`${sanitizeArtists(artists)} - ${sanitizeSong(song)}`, lyricsUrl);
  1062. // delete oldest entry if cache gets too big
  1063. if (lyricsUrlCache.size > maxLyricsCacheSize)
  1064. lyricsUrlCache.delete([...lyricsUrlCache.keys()].at(-1));
  1065. }
  1066. //#MARKER media control bar
  1067. let mcCurrentSongTitle = "";
  1068. let mcLyricsButtonAddTries = 0;
  1069. /** Adds a lyrics button to the media controls bar */
  1070. function addMediaCtrlLyricsBtn() {
  1071. const likeContainer = document.querySelector(".middle-controls-buttons ytmusic-like-button-renderer#like-button-renderer");
  1072. if (!likeContainer) {
  1073. mcLyricsButtonAddTries++;
  1074. if (mcLyricsButtonAddTries < _constants__WEBPACK_IMPORTED_MODULE_0__.triesLimit) {
  1075. setTimeout(addMediaCtrlLyricsBtn, _constants__WEBPACK_IMPORTED_MODULE_0__.triesInterval); // TODO: improve this
  1076. return;
  1077. }
  1078. return (0,_utils__WEBPACK_IMPORTED_MODULE_1__.error)(`Couldn't find element to append lyrics buttons to after ${mcLyricsButtonAddTries} tries`);
  1079. }
  1080. const songTitleElem = document.querySelector(".content-info-wrapper > yt-formatted-string");
  1081. // run parallel without awaiting so the MutationObserver below can observe the title element in time
  1082. (() => __awaiter(this, void 0, void 0, function* () {
  1083. const gUrl = yield getCurrentLyricsUrl();
  1084. const linkElem = createLyricsBtn(gUrl !== null && gUrl !== void 0 ? gUrl : undefined);
  1085. linkElem.id = "betterytm-lyrics-button";
  1086. (0,_utils__WEBPACK_IMPORTED_MODULE_1__.log)(`Inserted lyrics button after ${mcLyricsButtonAddTries} tries:`, linkElem);
  1087. (0,_utils__WEBPACK_IMPORTED_MODULE_1__.insertAfter)(likeContainer, linkElem);
  1088. }))();
  1089. mcCurrentSongTitle = songTitleElem.title;
  1090. const onMutation = (mutations) => { var _a, mutations_1, mutations_1_1; return __awaiter(this, void 0, void 0, function* () {
  1091. var _b, e_1, _c, _d;
  1092. try {
  1093. for (_a = true, mutations_1 = __asyncValues(mutations); mutations_1_1 = yield mutations_1.next(), _b = mutations_1_1.done, !_b;) {
  1094. _d = mutations_1_1.value;
  1095. _a = false;
  1096. try {
  1097. const mut = _d;
  1098. const newTitle = mut.target.title;
  1099. if (newTitle !== mcCurrentSongTitle && newTitle.length > 0) {
  1100. const lyricsBtn = document.querySelector("#betterytm-lyrics-button");
  1101. if (!lyricsBtn)
  1102. return;
  1103. (0,_utils__WEBPACK_IMPORTED_MODULE_1__.log)(`Song title changed from '${mcCurrentSongTitle}' to '${newTitle}'`);
  1104. lyricsBtn.style.cursor = "wait";
  1105. lyricsBtn.style.pointerEvents = "none";
  1106. mcCurrentSongTitle = newTitle;
  1107. const url = yield getCurrentLyricsUrl(); // can take a second or two
  1108. if (!url)
  1109. continue;
  1110. lyricsBtn.href = url;
  1111. lyricsBtn.title = "Open the current song's lyrics in a new tab";
  1112. lyricsBtn.style.cursor = "pointer";
  1113. lyricsBtn.style.visibility = "initial";
  1114. lyricsBtn.style.display = "inline-flex";
  1115. lyricsBtn.style.pointerEvents = "initial";
  1116. }
  1117. }
  1118. finally {
  1119. _a = true;
  1120. }
  1121. }
  1122. }
  1123. catch (e_1_1) { e_1 = { error: e_1_1 }; }
  1124. finally {
  1125. try {
  1126. if (!_a && !_b && (_c = mutations_1.return)) yield _c.call(mutations_1);
  1127. }
  1128. finally { if (e_1) throw e_1.error; }
  1129. }
  1130. }); };
  1131. // 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
  1132. const obs = new MutationObserver(onMutation);
  1133. obs.observe(songTitleElem, { attributes: true, attributeFilter: ["title"] });
  1134. }
  1135. //#MARKER utils
  1136. /** Removes everything in parentheses from the passed song name */
  1137. function sanitizeSong(songName) {
  1138. const parensRegex = /\(.+\)/gmi;
  1139. const squareParensRegex = /\[.+\]/gmi;
  1140. // trim right after the song name:
  1141. const sanitized = songName
  1142. .replace(parensRegex, "")
  1143. .replace(squareParensRegex, "");
  1144. return sanitized.trim();
  1145. }
  1146. /** Removes the secondary artist (if it exists) from the passed artists string */
  1147. function sanitizeArtists(artists) {
  1148. artists = artists.split(/\s*\u2022\s*/gmiu)[0]; // split at &bull; [•] character
  1149. if (artists.match(/&/))
  1150. artists = artists.split(/\s*&\s*/gm)[0];
  1151. if (artists.match(/,/))
  1152. artists = artists.split(/,\s*/gm)[0];
  1153. return artists.trim();
  1154. }
  1155. /** Returns the lyrics URL from genius for the currently selected song */
  1156. function getCurrentLyricsUrl() {
  1157. var _a, _b;
  1158. return __awaiter(this, void 0, void 0, function* () {
  1159. try {
  1160. // In videos the video title contains both artist and song title, in "regular" YTM songs, the video title only contains the song title
  1161. const isVideo = typeof ((_a = document.querySelector("ytmusic-player")) === null || _a === void 0 ? void 0 : _a.getAttribute("video-mode_")) === "string";
  1162. const songTitleElem = document.querySelector(".content-info-wrapper > yt-formatted-string");
  1163. const songMetaElem = document.querySelector("span.subtitle > yt-formatted-string:first-child");
  1164. if (!songTitleElem || !songMetaElem || !songTitleElem.title)
  1165. return null;
  1166. const songNameRaw = songTitleElem.title;
  1167. const songName = sanitizeSong(songNameRaw);
  1168. const artistName = sanitizeArtists(songMetaElem.title);
  1169. /** Use when the current song is not a "real YTM song" with a static background, but rather a music video */
  1170. const getGeniusUrlVideo = () => __awaiter(this, void 0, void 0, function* () {
  1171. if (!songName.includes("-")) // for some fucking reason some music videos have YTM-like song title and artist separation, some don't
  1172. return yield getGeniusUrl(artistName, songName);
  1173. const [artist, ...rest] = songName.split("-").map(v => v.trim());
  1174. return yield getGeniusUrl(artist, rest.join(" "));
  1175. });
  1176. // TODO: artist might need further splitting before comma or ampersand
  1177. const url = isVideo ? yield getGeniusUrlVideo() : ((_b = yield getGeniusUrl(artistName, songName)) !== null && _b !== void 0 ? _b : yield getGeniusUrlVideo());
  1178. return url;
  1179. }
  1180. catch (err) {
  1181. (0,_utils__WEBPACK_IMPORTED_MODULE_1__.error)("Couldn't resolve lyrics URL:", err);
  1182. return null;
  1183. }
  1184. });
  1185. }
  1186. /** Fetches the actual lyrics URL from geniURL - **the passed parameters need to be sanitized first!** */
  1187. function getGeniusUrl(artist, song) {
  1188. return __awaiter(this, void 0, void 0, function* () {
  1189. try {
  1190. const startTs = Date.now();
  1191. const fetchUrl = `${geniURLSearchTopUrl}?artist=${encodeURIComponent(artist)}&song=${encodeURIComponent(song)}`;
  1192. (0,_utils__WEBPACK_IMPORTED_MODULE_1__.log)(`Requesting URL from geniURL at '${fetchUrl}'`);
  1193. const result = yield (yield fetch(fetchUrl)).json();
  1194. if (typeof result === "object" && result.error) {
  1195. (0,_utils__WEBPACK_IMPORTED_MODULE_1__.error)("Couldn't fetch lyrics URL:", result.message);
  1196. return undefined;
  1197. }
  1198. const url = result.url;
  1199. (0,_utils__WEBPACK_IMPORTED_MODULE_1__.info)(`Found lyrics URL (after ${Date.now() - startTs}ms): ${url}`);
  1200. addLyricsCacheEntry(artist, song, url);
  1201. return url;
  1202. }
  1203. catch (err) {
  1204. (0,_utils__WEBPACK_IMPORTED_MODULE_1__.error)("Couldn't get lyrics URL due to error:", err);
  1205. return undefined;
  1206. }
  1207. });
  1208. }
  1209. /** Creates the base lyrics button element */
  1210. function createLyricsBtn(geniusUrl, hideIfLoading = true) {
  1211. const linkElem = document.createElement("a");
  1212. linkElem.className = "ytmusic-player-bar bytm-generic-lyrics-btn";
  1213. linkElem.title = geniusUrl ? "Click to open this song's lyrics in a new tab" : "Loading...";
  1214. if (geniusUrl)
  1215. linkElem.href = geniusUrl;
  1216. linkElem.target = "_blank";
  1217. linkElem.rel = "noopener noreferrer";
  1218. linkElem.style.visibility = hideIfLoading && geniusUrl ? "initial" : "hidden";
  1219. linkElem.style.display = hideIfLoading && geniusUrl ? "inline-flex" : "none";
  1220. const imgElem = document.createElement("img");
  1221. imgElem.className = "betterytm-lyrics-img";
  1222. imgElem.src = (0,_utils__WEBPACK_IMPORTED_MODULE_1__.getAssetUrl)("external/genius.png");
  1223. linkElem.appendChild(imgElem);
  1224. return linkElem;
  1225. }
  1226. /***/ }),
  1227. /***/ "./src/features/menu/menu.ts":
  1228. /*!***********************************!*\
  1229. !*** ./src/features/menu/menu.ts ***!
  1230. \***********************************/
  1231. /***/ (function(__unused_webpack_module, __webpack_exports__, __webpack_require__) {
  1232. __webpack_require__.r(__webpack_exports__);
  1233. /* harmony export */ __webpack_require__.d(__webpack_exports__, {
  1234. /* harmony export */ closeMenu: function() { return /* binding */ closeMenu; },
  1235. /* harmony export */ initMenu: function() { return /* binding */ initMenu; },
  1236. /* harmony export */ openMenu: function() { return /* binding */ openMenu; },
  1237. /* harmony export */ setActiveTab: function() { return /* binding */ setActiveTab; }
  1238. /* harmony export */ });
  1239. /* harmony import */ var _constants__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../../constants */ "./src/constants.ts");
  1240. /* harmony import */ var _utils__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../../utils */ "./src/utils.ts");
  1241. /* harmony import */ var _changelog_md__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../../../changelog.md */ "./changelog.md");
  1242. /* harmony import */ var _menu_html__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./menu.html */ "./src/features/menu/menu.html");
  1243. /* harmony import */ var _menu_css__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./menu.css */ "./src/features/menu/menu.css");
  1244. //#MARKER menu
  1245. /**
  1246. * These are the base selector values for the menu tabs
  1247. * Header selector format: `#${baseValue}-header`
  1248. * Content selector format: `#${baseValue}-content`
  1249. */
  1250. const tabsSelectors = {
  1251. options: "bytm-menu-tab-options",
  1252. info: "bytm-menu-tab-info",
  1253. changelog: "bytm-menu-tab-changelog",
  1254. };
  1255. function initMenu() {
  1256. document.addEventListener("DOMContentLoaded", () => {
  1257. // create menu container
  1258. const menuContainer = document.createElement("div");
  1259. menuContainer.id = "bytm-menu-container";
  1260. // add menu html
  1261. menuContainer.innerHTML = _menu_html__WEBPACK_IMPORTED_MODULE_3__["default"];
  1262. document.body.appendChild(menuContainer);
  1263. initMenuContents();
  1264. });
  1265. }
  1266. let menuContTries = 0;
  1267. function initMenuContents() {
  1268. var _a;
  1269. if (!document.querySelector("#bytm-menu-dialog"))
  1270. return menuContTries++ < _constants__WEBPACK_IMPORTED_MODULE_0__.triesLimit
  1271. ? setTimeout(initMenuContents, _constants__WEBPACK_IMPORTED_MODULE_0__.triesInterval)
  1272. : (0,_utils__WEBPACK_IMPORTED_MODULE_1__.error)(`couldn't create menu element after ${_constants__WEBPACK_IMPORTED_MODULE_0__.triesLimit} tries.`);
  1273. // hook events
  1274. for (const tab in tabsSelectors) {
  1275. const selector = tabsSelectors[tab];
  1276. (_a = document.querySelector(`#${selector}-header`)) === null || _a === void 0 ? void 0 : _a.addEventListener("click", () => {
  1277. setActiveTab(tab);
  1278. });
  1279. }
  1280. // init tab contents
  1281. initOptionsContent();
  1282. initInfoContent();
  1283. initChangelogContent();
  1284. }
  1285. /** Opens the specified tab */
  1286. function setActiveTab(tab) {
  1287. const tabs = Object.assign({}, tabsSelectors);
  1288. delete tabs[tab];
  1289. // disable all but new active tab
  1290. for (const disableTab of Object.keys(tabs)) {
  1291. document.querySelector(`#${tabs[disableTab]}-header`).dataset.active = "false";
  1292. document.querySelector(`#${tabs[disableTab]}-content`).dataset.active = "false";
  1293. }
  1294. // enable new active tab
  1295. document.querySelector(`#${tabsSelectors[tab]}-header`).dataset.active = "true";
  1296. document.querySelector(`#${tabsSelectors[tab]}-content`).dataset.active = "true";
  1297. }
  1298. /** Opens the modal menu dialog */
  1299. function openMenu() {
  1300. document.querySelector("#bytm-menu-dialog").showModal();
  1301. }
  1302. /** Closes the modal menu dialog */
  1303. function closeMenu() {
  1304. document.querySelector("#bytm-menu-dialog").close();
  1305. }
  1306. //#MARKER menu tab contents
  1307. function initOptionsContent() {
  1308. const tab = document.querySelector("#bytm-menu-tab-options-content");
  1309. void tab;
  1310. }
  1311. function initInfoContent() {
  1312. const tab = document.querySelector("#bytm-menu-tab-info-content");
  1313. void tab;
  1314. }
  1315. function initChangelogContent() {
  1316. const tab = document.querySelector("#bytm-menu-tab-changelog-content");
  1317. tab.innerHTML = _changelog_md__WEBPACK_IMPORTED_MODULE_2__["default"];
  1318. }
  1319. /***/ }),
  1320. /***/ "./src/features/menu/menu_old.ts":
  1321. /*!***************************************!*\
  1322. !*** ./src/features/menu/menu_old.ts ***!
  1323. \***************************************/
  1324. /***/ (function(__unused_webpack_module, __webpack_exports__, __webpack_require__) {
  1325. __webpack_require__.r(__webpack_exports__);
  1326. /* harmony export */ __webpack_require__.d(__webpack_exports__, {
  1327. /* harmony export */ addMenu: function() { return /* binding */ addMenu; },
  1328. /* harmony export */ closeMenu: function() { return /* binding */ closeMenu; },
  1329. /* harmony export */ openMenu: function() { return /* binding */ openMenu; }
  1330. /* harmony export */ });
  1331. /* harmony import */ var _config__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../../config */ "./src/config.ts");
  1332. /* harmony import */ var _constants__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../../constants */ "./src/constants.ts");
  1333. /* harmony import */ var _index__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../index */ "./src/features/index.ts");
  1334. /* harmony import */ var _utils__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../../utils */ "./src/utils.ts");
  1335. var __awaiter = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) {
  1336. function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
  1337. return new (P || (P = Promise))(function (resolve, reject) {
  1338. function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
  1339. function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
  1340. function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
  1341. step((generator = generator.apply(thisArg, _arguments || [])).next());
  1342. });
  1343. };
  1344. //#MARKER menu
  1345. /**
  1346. * Adds an element to open the BetterYTM menu
  1347. * @deprecated TODO: replace in v1.1.0 - see https://github.com/Sv443/BetterYTM/issues/23
  1348. */
  1349. function addMenu() {
  1350. var _a, _b;
  1351. return __awaiter(this, void 0, void 0, function* () {
  1352. // bg & menu
  1353. const backgroundElem = document.createElement("div");
  1354. backgroundElem.id = "betterytm-menu-bg";
  1355. backgroundElem.title = "Click here to close the menu";
  1356. backgroundElem.style.visibility = "hidden";
  1357. backgroundElem.style.display = "none";
  1358. backgroundElem.addEventListener("click", (e) => {
  1359. if (e.target.id === "betterytm-menu-bg")
  1360. closeMenu();
  1361. });
  1362. document.body.addEventListener("keydown", ({ key }) => {
  1363. if (key === "Escape")
  1364. closeMenu();
  1365. });
  1366. const menuContainer = document.createElement("div");
  1367. menuContainer.title = "";
  1368. menuContainer.id = "betterytm-menu";
  1369. menuContainer.style.borderRadius = "15px";
  1370. menuContainer.style.display = "flex";
  1371. menuContainer.style.flexDirection = "column";
  1372. menuContainer.style.justifyContent = "space-between";
  1373. // title
  1374. const titleCont = document.createElement("div");
  1375. titleCont.style.padding = "8px 20px 15px 8px";
  1376. titleCont.style.display = "flex";
  1377. titleCont.style.justifyContent = "space-between";
  1378. titleCont.id = "betterytm-menu-titlecont";
  1379. const titleElem = document.createElement("h2");
  1380. titleElem.id = "betterytm-menu-title";
  1381. titleElem.innerText = `${_constants__WEBPACK_IMPORTED_MODULE_1__.scriptInfo.name} - Configuration`;
  1382. const linksCont = document.createElement("div");
  1383. linksCont.id = "betterytm-menu-linkscont";
  1384. const addLink = (imgSrc, href, title) => {
  1385. const anchorElem = document.createElement("a");
  1386. anchorElem.className = "betterytm-menu-link";
  1387. anchorElem.rel = "noopener noreferrer";
  1388. anchorElem.target = "_blank";
  1389. anchorElem.href = href;
  1390. anchorElem.title = title;
  1391. anchorElem.style.marginLeft = "10px";
  1392. const imgElem = document.createElement("img");
  1393. imgElem.className = "betterytm-menu-img";
  1394. imgElem.src = imgSrc;
  1395. imgElem.style.width = "32px";
  1396. imgElem.style.height = "32px";
  1397. anchorElem.appendChild(imgElem);
  1398. linksCont.appendChild(anchorElem);
  1399. };
  1400. addLink((0,_utils__WEBPACK_IMPORTED_MODULE_3__.getAssetUrl)("external/github.png"), _constants__WEBPACK_IMPORTED_MODULE_1__.scriptInfo.namespace, `${_constants__WEBPACK_IMPORTED_MODULE_1__.scriptInfo.name} on GitHub`);
  1401. addLink((0,_utils__WEBPACK_IMPORTED_MODULE_3__.getAssetUrl)("external/greasyfork.png"), "https://greasyfork.org/xyz", `${_constants__WEBPACK_IMPORTED_MODULE_1__.scriptInfo.name} on GreasyFork`);
  1402. const closeElem = document.createElement("img");
  1403. closeElem.id = "betterytm-menu-close";
  1404. closeElem.src = (0,_utils__WEBPACK_IMPORTED_MODULE_3__.getAssetUrl)("close.png");
  1405. closeElem.title = "Click to close the menu";
  1406. closeElem.style.marginLeft = "50px";
  1407. closeElem.style.width = "32px";
  1408. closeElem.style.height = "32px";
  1409. closeElem.addEventListener("click", closeMenu);
  1410. linksCont.appendChild(closeElem);
  1411. titleCont.appendChild(titleElem);
  1412. titleCont.appendChild(linksCont);
  1413. // TODO: features
  1414. const featuresCont = document.createElement("div");
  1415. featuresCont.id = "betterytm-menu-opts";
  1416. featuresCont.style.display = "flex";
  1417. featuresCont.style.flexDirection = "column";
  1418. featuresCont.style.overflowY = "auto";
  1419. /** Gets called whenever the feature config is changed */
  1420. const confChanged = (key, initialVal, newVal) => __awaiter(this, void 0, void 0, function* () {
  1421. const fmt = (val) => typeof val === "object" ? JSON.stringify(val) : String(val);
  1422. (0,_utils__WEBPACK_IMPORTED_MODULE_3__.info)(`Feature config changed, key '${key}' from value '${fmt(initialVal)}' to '${fmt(newVal)}'`);
  1423. const featConf = Object.assign({}, yield (0,_config__WEBPACK_IMPORTED_MODULE_0__.getFeatures)());
  1424. featConf[key] = newVal;
  1425. yield (0,_config__WEBPACK_IMPORTED_MODULE_0__.saveFeatureConf)(featConf);
  1426. (0,_utils__WEBPACK_IMPORTED_MODULE_3__.log)("Saved feature config changes:\n", yield GM.getValue("betterytm-config"));
  1427. });
  1428. const features = yield (0,_config__WEBPACK_IMPORTED_MODULE_0__.getFeatures)();
  1429. for (const key in features) {
  1430. const ftInfo = _index__WEBPACK_IMPORTED_MODULE_2__.featInfo[key];
  1431. // @ts-ignore
  1432. if (!ftInfo || ftInfo.visible === false)
  1433. continue;
  1434. const { desc, type, default: ftDefault } = ftInfo;
  1435. // @ts-ignore
  1436. const step = (_a = ftInfo === null || ftInfo === void 0 ? void 0 : ftInfo.step) !== null && _a !== void 0 ? _a : undefined;
  1437. const val = features[key];
  1438. const initialVal = (_b = val !== null && val !== void 0 ? val : ftDefault) !== null && _b !== void 0 ? _b : undefined;
  1439. const ftConfElem = document.createElement("div");
  1440. ftConfElem.id = `betterytm-ftconf-${key}`;
  1441. ftConfElem.style.display = "flex";
  1442. ftConfElem.style.flexDirection = "row";
  1443. ftConfElem.style.justifyContent = "space-between";
  1444. ftConfElem.style.padding = "8px 20px";
  1445. {
  1446. const textElem = document.createElement("span");
  1447. textElem.style.display = "inline-block";
  1448. textElem.style.fontSize = "15px";
  1449. textElem.innerText = desc;
  1450. ftConfElem.appendChild(textElem);
  1451. }
  1452. {
  1453. let inputType = "text";
  1454. switch (type) {
  1455. case "toggle":
  1456. inputType = "checkbox";
  1457. break;
  1458. case "slider":
  1459. inputType = "range";
  1460. break;
  1461. case "number":
  1462. inputType = "number";
  1463. break;
  1464. }
  1465. const inputElemId = `betterytm-ftconf-${key}-input`;
  1466. const ctrlElem = document.createElement("span");
  1467. ctrlElem.style.display = "inline-block";
  1468. ctrlElem.style.whiteSpace = "nowrap";
  1469. const inputElem = document.createElement("input");
  1470. inputElem.id = inputElemId;
  1471. inputElem.style.marginRight = "37px";
  1472. inputElem.type = inputType;
  1473. if (type === "toggle")
  1474. inputElem.style.marginLeft = "5px";
  1475. if (typeof initialVal !== "undefined")
  1476. inputElem.value = String(initialVal);
  1477. if (type === "number" && step)
  1478. inputElem.step = step;
  1479. // @ts-ignore
  1480. if (ftInfo.min && ftInfo.max) {
  1481. // @ts-ignore
  1482. inputElem.min = ftInfo.min;
  1483. // @ts-ignore
  1484. inputElem.max = ftInfo.max;
  1485. }
  1486. if (type === "toggle" && typeof initialVal !== "undefined")
  1487. inputElem.checked = Boolean(initialVal);
  1488. // @ts-ignore
  1489. const unitTxt = typeof ftInfo.unit === "string" ? " " + ftInfo.unit : "";
  1490. const fmtVal = (v) => String(v).trim();
  1491. const toggleLabelText = (toggled) => toggled ? "On" : "Off";
  1492. let labelElem;
  1493. if (type === "slider") {
  1494. labelElem = document.createElement("label");
  1495. labelElem.classList.add("betterytm-ftconf-label");
  1496. labelElem.style.marginRight = "20px";
  1497. labelElem.style.fontSize = "16px";
  1498. labelElem.htmlFor = inputElemId;
  1499. labelElem.innerText = fmtVal(initialVal) + unitTxt;
  1500. inputElem.addEventListener("input", () => {
  1501. if (labelElem)
  1502. labelElem.innerText = fmtVal(parseInt(inputElem.value)) + unitTxt;
  1503. });
  1504. }
  1505. else if (type === "toggle") {
  1506. labelElem = document.createElement("label");
  1507. labelElem.classList.add("betterytm-ftconf-label");
  1508. labelElem.style.paddingLeft = "10px";
  1509. labelElem.style.paddingRight = "5px";
  1510. labelElem.style.fontSize = "16px";
  1511. labelElem.htmlFor = inputElemId;
  1512. labelElem.innerText = toggleLabelText(Boolean(initialVal)) + unitTxt;
  1513. inputElem.addEventListener("input", () => {
  1514. if (labelElem)
  1515. labelElem.innerText = toggleLabelText(inputElem.checked) + unitTxt;
  1516. });
  1517. }
  1518. inputElem.addEventListener("input", () => {
  1519. let v = parseInt(inputElem.value);
  1520. if (isNaN(v))
  1521. v = Number(inputElem.value);
  1522. if (typeof initialVal !== "undefined")
  1523. confChanged(key, initialVal, (type !== "toggle" ? v : inputElem.checked));
  1524. });
  1525. const resetElem = document.createElement("button");
  1526. resetElem.innerText = "Reset";
  1527. resetElem.addEventListener("click", () => {
  1528. inputElem[type !== "toggle" ? "value" : "checked"] = ftDefault;
  1529. if (labelElem) {
  1530. if (type === "toggle")
  1531. labelElem.innerText = toggleLabelText(inputElem.checked);
  1532. else
  1533. labelElem.innerText = fmtVal(parseInt(inputElem.value));
  1534. }
  1535. if (typeof initialVal !== "undefined")
  1536. confChanged(key, initialVal, ftDefault);
  1537. });
  1538. labelElem && ctrlElem.appendChild(labelElem);
  1539. ctrlElem.appendChild(inputElem);
  1540. ctrlElem.appendChild(resetElem);
  1541. ftConfElem.appendChild(ctrlElem);
  1542. }
  1543. featuresCont.appendChild(ftConfElem);
  1544. }
  1545. const footerElem = document.createElement("div");
  1546. footerElem.id = "betterytm-menu-footer";
  1547. footerElem.style.marginTop = "20px";
  1548. footerElem.style.fontSize = "17px";
  1549. footerElem.style.textDecoration = "underline";
  1550. footerElem.style.padding = "10px 20px";
  1551. footerElem.style.position = "sticky";
  1552. footerElem.style.backgroundColor = "var(--bytm-menu-bg)";
  1553. footerElem.style.bottom = "0";
  1554. footerElem.innerText = "You need to reload the page to apply changes.";
  1555. const reloadElem = document.createElement("button");
  1556. reloadElem.style.marginLeft = "20px";
  1557. reloadElem.innerText = "Reload now";
  1558. reloadElem.title = "Click to reload the page";
  1559. reloadElem.addEventListener("click", () => location.reload());
  1560. footerElem.appendChild(reloadElem);
  1561. featuresCont.appendChild(footerElem);
  1562. // finalize
  1563. const menuBody = document.createElement("div");
  1564. menuBody.id = "betterytm-menu-body";
  1565. menuBody.appendChild(titleCont);
  1566. menuBody.appendChild(featuresCont);
  1567. const versionCont = document.createElement("div");
  1568. versionCont.style.display = "flex";
  1569. versionCont.style.justifyContent = "space-around";
  1570. versionCont.style.fontSize = "1.15em";
  1571. versionCont.style.marginTop = "10px";
  1572. versionCont.style.marginBottom = "5px";
  1573. const versionElem = document.createElement("span");
  1574. versionElem.id = "betterytm-menu-version";
  1575. versionElem.innerText = `v${_constants__WEBPACK_IMPORTED_MODULE_1__.scriptInfo.version}`;
  1576. versionCont.appendChild(versionElem);
  1577. featuresCont.appendChild(versionCont);
  1578. menuContainer.appendChild(menuBody);
  1579. menuContainer.appendChild(versionCont);
  1580. backgroundElem.appendChild(menuContainer);
  1581. document.body.appendChild(backgroundElem);
  1582. // add style
  1583. const menuStyle = `\
  1584. :root {
  1585. --bytm-menu-bg: #212121;
  1586. }
  1587. #betterytm-menu-bg {
  1588. display: block;
  1589. position: fixed;
  1590. width: 100vw;
  1591. height: 100vh;
  1592. top: 0;
  1593. left: 0;
  1594. z-index: 15;
  1595. background-color: rgba(0, 0, 0, 0.6);
  1596. }
  1597. /* TODO:FIXME: needs better positioning (vw and vh === "big no no") */
  1598. #betterytm-menu {
  1599. display: inline-block;
  1600. position: fixed;
  1601. width: 50vw;
  1602. height: auto;
  1603. left: 25vw;
  1604. top: 10vh;
  1605. z-index: 16;
  1606. padding: 8px;
  1607. color: #fff;
  1608. background-color: var(--bytm-menu-bg);
  1609. }
  1610. #betterytm-menu-opts {
  1611. max-height: 70vh;
  1612. overflow: auto;
  1613. }
  1614. #betterytm-menu-titlecont {
  1615. display: flex;
  1616. }
  1617. #betterytm-menu-title {
  1618. font-size: 20px;
  1619. margin-top: 5px;
  1620. margin-bottom: 8px;
  1621. }
  1622. #betterytm-menu-linkscont {
  1623. display: flex;
  1624. }
  1625. .betterytm-menu-link {
  1626. display: inline-block;
  1627. }
  1628. /*.betterytm-menu-img {
  1629. }*/
  1630. #betterytm-menu-close {
  1631. cursor: pointer;
  1632. }
  1633. .betterytm-ftconf-label {
  1634. user-select: none;
  1635. }`;
  1636. (0,_utils__WEBPACK_IMPORTED_MODULE_3__.log)("Added menu elem:", backgroundElem);
  1637. (0,_utils__WEBPACK_IMPORTED_MODULE_3__.addGlobalStyle)(menuStyle, "menu");
  1638. });
  1639. }
  1640. function closeMenu() {
  1641. const menuBg = document.querySelector("#betterytm-menu-bg");
  1642. menuBg.style.visibility = "hidden";
  1643. menuBg.style.display = "none";
  1644. }
  1645. function openMenu() {
  1646. const menuBg = document.querySelector("#betterytm-menu-bg");
  1647. menuBg.style.visibility = "visible";
  1648. menuBg.style.display = "block";
  1649. }
  1650. /***/ }),
  1651. /***/ "./src/utils.ts":
  1652. /*!**********************!*\
  1653. !*** ./src/utils.ts ***!
  1654. \**********************/
  1655. /***/ (function(__unused_webpack_module, __webpack_exports__, __webpack_require__) {
  1656. __webpack_require__.r(__webpack_exports__);
  1657. /* harmony export */ __webpack_require__.d(__webpack_exports__, {
  1658. /* harmony export */ addGlobalStyle: function() { return /* binding */ addGlobalStyle; },
  1659. /* harmony export */ autoPlural: function() { return /* binding */ autoPlural; },
  1660. /* harmony export */ dbg: function() { return /* binding */ dbg; },
  1661. /* harmony export */ error: function() { return /* binding */ error; },
  1662. /* harmony export */ getAssetUrl: function() { return /* binding */ getAssetUrl; },
  1663. /* harmony export */ getDomain: function() { return /* binding */ getDomain; },
  1664. /* harmony export */ getVideoTime: function() { return /* binding */ getVideoTime; },
  1665. /* harmony export */ info: function() { return /* binding */ info; },
  1666. /* harmony export */ insertAfter: function() { return /* binding */ insertAfter; },
  1667. /* harmony export */ log: function() { return /* binding */ log; },
  1668. /* harmony export */ openInNewTab: function() { return /* binding */ openInNewTab; },
  1669. /* harmony export */ setLogLevel: function() { return /* binding */ setLogLevel; },
  1670. /* harmony export */ warn: function() { return /* binding */ warn; }
  1671. /* harmony export */ });
  1672. /* harmony import */ var _constants__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./constants */ "./src/constants.ts");
  1673. //#MARKER BYTM-specific
  1674. let curLogLevel = 1;
  1675. /** Sets the current log level. 0 = Debug, 1 = Info */
  1676. function setLogLevel(level) {
  1677. curLogLevel = level;
  1678. }
  1679. function getLogLevel(args) {
  1680. const minLogLvl = 0, maxLogLvl = 1;
  1681. if (typeof args.at(-1) === "number")
  1682. return Math.max(Math.min(args.splice(args.length - 1)[0], minLogLvl), maxLogLvl);
  1683. return 0;
  1684. }
  1685. /** Common prefix to be able to tell logged messages apart and filter them in devtools */
  1686. const consPrefix = `[${_constants__WEBPACK_IMPORTED_MODULE_0__.scriptInfo.name}]`;
  1687. const consPrefixDbg = `[${_constants__WEBPACK_IMPORTED_MODULE_0__.scriptInfo.name}/#DEBUG]`;
  1688. /**
  1689. * Logs string-compatible values to the console, as long as the log level is sufficient.
  1690. * @param args Last parameter is log level (0 = Debug, 1/undefined = Info) - any number as the last parameter will be stripped out! Convert to string if they shouldn't be.
  1691. */
  1692. function log(...args) {
  1693. if (curLogLevel <= getLogLevel(args))
  1694. console.log(consPrefix, ...args);
  1695. }
  1696. /**
  1697. * Logs string-compatible values to the console as info, as long as the log level is sufficient.
  1698. * @param args Last parameter is log level (0 = Debug, 1/undefined = Info) - any number as the last parameter will be stripped out! Convert to string if they shouldn't be.
  1699. */
  1700. function info(...args) {
  1701. if (curLogLevel <= getLogLevel(args))
  1702. console.info(consPrefix, ...args);
  1703. }
  1704. /**
  1705. * Logs string-compatible values to the console as a warning, as long as the log level is sufficient.
  1706. * @param args Last parameter is log level (0 = Debug, 1/undefined = Info) - any number as the last parameter will be stripped out! Convert to string if they shouldn't be.
  1707. */
  1708. function warn(...args) {
  1709. if (curLogLevel <= getLogLevel(args))
  1710. console.warn(consPrefix, ...args);
  1711. }
  1712. /** Logs string-compatible values to the console as an error. */
  1713. function error(...args) {
  1714. console.error(consPrefix, ...args);
  1715. }
  1716. /** Logs string-compatible values to the console, intended for debugging only */
  1717. function dbg(...args) {
  1718. console.log(consPrefixDbg, ...args);
  1719. }
  1720. /**
  1721. * Returns the current domain as a constant string representation
  1722. * @throws Throws if script runs on an unexpected website
  1723. */
  1724. function getDomain() {
  1725. const { hostname } = new URL(location.href);
  1726. if (hostname.includes("music.youtube"))
  1727. return "ytm";
  1728. else if (hostname.includes("youtube"))
  1729. return "yt";
  1730. else
  1731. throw new Error("BetterYTM is running on an unexpected website. Please don't tamper with the @match directives in the userscript header.");
  1732. }
  1733. /**
  1734. * Returns the current video time in seconds
  1735. * @param force Set to true to dispatch mouse movement events in case the video time can't be estimated
  1736. * @returns Returns null if the video time is unavailable
  1737. */
  1738. function getVideoTime(force = false) {
  1739. const domain = getDomain();
  1740. try {
  1741. if (domain === "ytm") {
  1742. const pbEl = document.querySelector("#progress-bar");
  1743. return !isNaN(Number(pbEl.value)) ? Number(pbEl.value) : null;
  1744. }
  1745. else if (domain === "yt") {
  1746. // YT doesn't update the progress bar when it's hidden (YTM doesn't hide it) so TODO: come up with some solution here
  1747. // Possible solution:
  1748. // - Use MutationObserver to detect when attributes of progress bar (selector `div.ytp-progress-bar[role="slider"]`) change
  1749. // - Wait until the attribute increments, then save the value of `aria-valuenow` and the current system time to memory
  1750. // - When site switch hotkey is pressed, take saved `aria-valuenow` value and add the difference between saved system time and current system time
  1751. // - If no value is present, use the script from `dev/ytForceShowVideoTime.js` to simulate mouse movement to force the element to update
  1752. // - Subtract one or two seconds to make up for rounding errors
  1753. // - profit
  1754. // if(!ytCurrentVideoTime) {
  1755. // ytForceShowVideoTime();
  1756. // const videoTime = document.querySelector("#TODO")?.getAttribute("aria-valuenow") ?? null;
  1757. // }
  1758. void [force, ytForceShowVideoTime];
  1759. return null;
  1760. }
  1761. return null;
  1762. }
  1763. catch (err) {
  1764. error("Couldn't get video time due to error:", err);
  1765. return null;
  1766. }
  1767. }
  1768. /** Sends events that force the video controls to become visible for about 3 seconds */
  1769. function ytForceShowVideoTime() {
  1770. const player = document.querySelector("#movie_player");
  1771. if (!player)
  1772. return false;
  1773. const defaultProps = {
  1774. // needed because otherwise YTM errors out - see https://github.com/Sv443/BetterYTM/issues/18#show_issue
  1775. view: unsafeWindow !== null && unsafeWindow !== void 0 ? unsafeWindow : window,
  1776. bubbles: true,
  1777. cancelable: false,
  1778. };
  1779. player.dispatchEvent(new MouseEvent("mouseenter", defaultProps));
  1780. const { x, y, width, height } = player.getBoundingClientRect();
  1781. const screenY = Math.round(y + height / 2);
  1782. const screenX = x + Math.min(50, Math.round(width / 3));
  1783. player.dispatchEvent(new MouseEvent("mousemove", Object.assign(Object.assign({}, defaultProps), { screenY,
  1784. screenX, movementX: 5, movementY: 0 })));
  1785. setTimeout(() => {
  1786. player.dispatchEvent(new MouseEvent("mouseleave", defaultProps));
  1787. }, 4000);
  1788. return true;
  1789. }
  1790. /** Returns the URL of the asset hosted on GitHub at the specified relative `path` (starting at `ROOT/assets/`) */
  1791. function getAssetUrl(path) {
  1792. return `https://raw.githubusercontent.com/Sv443/BetterYTM/${_constants__WEBPACK_IMPORTED_MODULE_0__.branch}/assets/${path}`;
  1793. }
  1794. /**
  1795. * Creates an invisible anchor with _blank target and clicks it.
  1796. * This has to be run in relatively quick succession to a user interaction event, else the browser rejects it.
  1797. */
  1798. function openInNewTab(href) {
  1799. const openElem = document.createElement("a");
  1800. Object.assign(openElem, {
  1801. className: "betterytm-open-in-new-tab",
  1802. target: "_blank",
  1803. rel: "noopener noreferrer",
  1804. href,
  1805. style: {
  1806. visibility: "hidden",
  1807. },
  1808. });
  1809. document.body.appendChild(openElem);
  1810. openElem.click();
  1811. // timeout just to be safe
  1812. setTimeout(() => openElem.remove(), 200);
  1813. }
  1814. /**
  1815. * Automatically appends an `s` to the passed `word`, if `num` is not equal to 1
  1816. * @param word A word in singular form, to auto-convert to plural
  1817. * @param num If this is an array, the amount of items is used
  1818. */
  1819. function autoPlural(word, num) {
  1820. if (Array.isArray(num))
  1821. num = num.length;
  1822. return `${word}${num === 1 ? "" : "s"}`;
  1823. }
  1824. //#MARKER DOM
  1825. /**
  1826. * Inserts `afterNode` as a sibling just after the provided `beforeNode`
  1827. * @param beforeNode
  1828. * @param afterNode
  1829. * @returns Returns the `afterNode`
  1830. */
  1831. function insertAfter(beforeNode, afterNode) {
  1832. var _a;
  1833. (_a = beforeNode.parentNode) === null || _a === void 0 ? void 0 : _a.insertBefore(afterNode, beforeNode.nextSibling);
  1834. return afterNode;
  1835. }
  1836. /**
  1837. * Adds global CSS style through a `<style>` element in the document's `<head>`
  1838. * @param style CSS string
  1839. * @param ref Reference name that is included in the `<style>`'s ID - prefixed with `betterytm-style-` - defaults to a random number if left undefined
  1840. */
  1841. function addGlobalStyle(style, ref) {
  1842. if (typeof ref !== "string" || ref.length === 0)
  1843. ref = String(Math.floor(Math.random() * 10000));
  1844. const styleElem = document.createElement("style");
  1845. styleElem.id = `betterytm-style-${ref}`;
  1846. styleElem.innerHTML = style;
  1847. document.head.appendChild(styleElem);
  1848. log(`Inserted global style with ref '${ref}':`, styleElem);
  1849. }
  1850. /***/ })
  1851. /******/ });
  1852. /************************************************************************/
  1853. /******/ // The module cache
  1854. /******/ var __webpack_module_cache__ = {};
  1855. /******/
  1856. /******/ // The require function
  1857. /******/ function __webpack_require__(moduleId) {
  1858. /******/ // Check if module is in cache
  1859. /******/ var cachedModule = __webpack_module_cache__[moduleId];
  1860. /******/ if (cachedModule !== undefined) {
  1861. /******/ return cachedModule.exports;
  1862. /******/ }
  1863. /******/ // Create a new module (and put it into the cache)
  1864. /******/ var module = __webpack_module_cache__[moduleId] = {
  1865. /******/ // no module.id needed
  1866. /******/ // no module.loaded needed
  1867. /******/ exports: {}
  1868. /******/ };
  1869. /******/
  1870. /******/ // Execute the module function
  1871. /******/ __webpack_modules__[moduleId](module, module.exports, __webpack_require__);
  1872. /******/
  1873. /******/ // Return the exports of the module
  1874. /******/ return module.exports;
  1875. /******/ }
  1876. /******/
  1877. /************************************************************************/
  1878. /******/ /* webpack/runtime/define property getters */
  1879. /******/ !function() {
  1880. /******/ // define getter functions for harmony exports
  1881. /******/ __webpack_require__.d = function(exports, definition) {
  1882. /******/ for(var key in definition) {
  1883. /******/ if(__webpack_require__.o(definition, key) && !__webpack_require__.o(exports, key)) {
  1884. /******/ Object.defineProperty(exports, key, { enumerable: true, get: definition[key] });
  1885. /******/ }
  1886. /******/ }
  1887. /******/ };
  1888. /******/ }();
  1889. /******/
  1890. /******/ /* webpack/runtime/hasOwnProperty shorthand */
  1891. /******/ !function() {
  1892. /******/ __webpack_require__.o = function(obj, prop) { return Object.prototype.hasOwnProperty.call(obj, prop); }
  1893. /******/ }();
  1894. /******/
  1895. /******/ /* webpack/runtime/make namespace object */
  1896. /******/ !function() {
  1897. /******/ // define __esModule on exports
  1898. /******/ __webpack_require__.r = function(exports) {
  1899. /******/ if(typeof Symbol !== 'undefined' && Symbol.toStringTag) {
  1900. /******/ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
  1901. /******/ }
  1902. /******/ Object.defineProperty(exports, '__esModule', { value: true });
  1903. /******/ };
  1904. /******/ }();
  1905. /******/
  1906. /************************************************************************/
  1907. var __webpack_exports__ = {};
  1908. // This entry need to be wrapped in an IIFE because it need to be isolated against other modules in the chunk.
  1909. !function() {
  1910. /*!**********************!*\
  1911. !*** ./src/index.ts ***!
  1912. \**********************/
  1913. __webpack_require__.r(__webpack_exports__);
  1914. /* harmony import */ var _config__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./config */ "./src/config.ts");
  1915. /* harmony import */ var _constants__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./constants */ "./src/constants.ts");
  1916. /* harmony import */ var _utils__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./utils */ "./src/utils.ts");
  1917. /* harmony import */ var _events__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./events */ "./src/events.ts");
  1918. /* harmony import */ var _features_index__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./features/index */ "./src/features/index.ts");
  1919. var __awaiter = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) {
  1920. function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
  1921. return new (P || (P = Promise))(function (resolve, reject) {
  1922. function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
  1923. function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
  1924. function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
  1925. step((generator = generator.apply(thisArg, _arguments || [])).next());
  1926. });
  1927. };
  1928. // TODO: add some style
  1929. 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}`);
  1930. console.log(`Powered by lots of ambition and my song metadata API: ${_features_index__WEBPACK_IMPORTED_MODULE_4__.geniUrlBase}`);
  1931. const domain = (0,_utils__WEBPACK_IMPORTED_MODULE_2__.getDomain)();
  1932. /** Stuff that needs to be called ASAP, before anything async happens */
  1933. function preInit() {
  1934. (0,_utils__WEBPACK_IMPORTED_MODULE_2__.setLogLevel)(_constants__WEBPACK_IMPORTED_MODULE_1__.logLevel);
  1935. if (domain === "ytm")
  1936. (0,_features_index__WEBPACK_IMPORTED_MODULE_4__.initBeforeUnloadHook)();
  1937. init();
  1938. }
  1939. function init() {
  1940. return __awaiter(this, void 0, void 0, function* () {
  1941. yield (0,_features_index__WEBPACK_IMPORTED_MODULE_4__.preInitLayout)();
  1942. try {
  1943. document.addEventListener("DOMContentLoaded", onDomLoad);
  1944. }
  1945. catch (err) {
  1946. console.error(`${_constants__WEBPACK_IMPORTED_MODULE_1__.scriptInfo.name} - General Error:`, err);
  1947. }
  1948. try {
  1949. void ["TODO(v1.1):", _features_index__WEBPACK_IMPORTED_MODULE_4__.initMenu];
  1950. // initMenu();
  1951. }
  1952. catch (err) {
  1953. (0,_utils__WEBPACK_IMPORTED_MODULE_2__.error)("Couldn't initialize menu:", err);
  1954. }
  1955. });
  1956. }
  1957. /** Called when the DOM has finished loading and can be queried and altered by the userscript */
  1958. function onDomLoad() {
  1959. return __awaiter(this, void 0, void 0, function* () {
  1960. // post-build these double quotes are replaced by backticks
  1961. (0,_utils__WEBPACK_IMPORTED_MODULE_2__.addGlobalStyle)(`/*!***************************************************************************!*\
  1962. !*** css ./node_modules/css-loader/dist/cjs.js!./src/features/layout.css ***!
  1963. \***************************************************************************/
  1964. #betterytm-watermark {
  1965. font-size: 10px;
  1966. display: inline-block;
  1967. position: absolute;
  1968. left: 45px;
  1969. top: 46px;
  1970. z-index: 10;
  1971. color: white;
  1972. text-decoration: none;
  1973. cursor: pointer;
  1974. }
  1975. @media(max-width: 615px) {
  1976. #betterytm-watermark {
  1977. display: none;
  1978. }
  1979. }
  1980. #betterytm-watermark:hover {
  1981. text-decoration: underline;
  1982. }
  1983. .side-panel.modular ytmusic-player-queue-item .song-info.ytmusic-player-queue-item {
  1984. position: relative;
  1985. }
  1986. .side-panel.modular ytmusic-player-queue-item .song-info .bytm-queue-btn-container {
  1987. display: none;
  1988. position: absolute;
  1989. right: 0;
  1990. }
  1991. .side-panel.modular ytmusic-player-queue-item:hover .song-info .bytm-queue-btn-container {
  1992. display: inline-block;
  1993. }
  1994. /*!***************************************************************************!*\
  1995. !*** css ./node_modules/css-loader/dist/cjs.js!./src/features/lyrics.css ***!
  1996. \***************************************************************************/
  1997. .bytm-generic-lyrics-btn {
  1998. align-items: center;
  1999. justify-content: center;
  2000. position: relative;
  2001. vertical-align: middle;
  2002. margin-left: 8px;
  2003. width: 40px;
  2004. height: 40px;
  2005. border-radius: 100%;
  2006. background-color: transparent;
  2007. }
  2008. .bytm-generic-lyrics-btn:hover {
  2009. background-color: var(--yt-spec-10-percent-layer, #1d1d1d);
  2010. }
  2011. .betterytm-lyrics-img {
  2012. display: inline-block;
  2013. z-index: 10;
  2014. width: 24px;
  2015. height: 24px;
  2016. padding: 5px;
  2017. }
  2018. /*!******************************************************************************!*\
  2019. !*** css ./node_modules/css-loader/dist/cjs.js!./src/features/menu/menu.css ***!
  2020. \******************************************************************************/
  2021. /* #bytm-menu-backdrop {
  2022. display: none;
  2023. flex-direction: column;
  2024. justify-content: center;
  2025. align-items: center;
  2026. }
  2027. #bytm-menu-backdrop[data-menu-open="true"] {
  2028. display: flex;
  2029. } */
  2030. #bytm-menu-header-container {
  2031. display: flex;
  2032. justify-content: flex-start;
  2033. align-items: center;
  2034. border-color: #ffffff;
  2035. border-style: none solid none none;
  2036. }
  2037. .bytm-menu-header-option {
  2038. display: "flex";
  2039. justify-content: center;
  2040. align-items: center;
  2041. border-color: #ffffff;
  2042. border-style: solid none solid none;
  2043. }
  2044. #bytm-menu-header-option h3 {
  2045. margin: 0;
  2046. }
  2047. .bytm-menu-tab[data-active="true"] {
  2048. display: none;
  2049. }
  2050. .bytm-menu-tab[data-active="false"] {
  2051. display: none;
  2052. }`, "global");
  2053. const features = yield (0,_config__WEBPACK_IMPORTED_MODULE_0__.loadFeatureConf)();
  2054. (0,_utils__WEBPACK_IMPORTED_MODULE_2__.log)(`Initializing features for domain '${domain}'`);
  2055. try {
  2056. if (domain === "ytm") {
  2057. (0,_events__WEBPACK_IMPORTED_MODULE_3__.initSiteEvents)();
  2058. if (features.arrowKeySupport)
  2059. (0,_features_index__WEBPACK_IMPORTED_MODULE_4__.initArrowKeySkip)();
  2060. if (features.removeUpgradeTab)
  2061. (0,_features_index__WEBPACK_IMPORTED_MODULE_4__.removeUpgradeTab)();
  2062. if (features.watermarkEnabled)
  2063. (0,_features_index__WEBPACK_IMPORTED_MODULE_4__.addWatermark)();
  2064. if (features.geniusLyrics)
  2065. (0,_features_index__WEBPACK_IMPORTED_MODULE_4__.addMediaCtrlLyricsBtn)();
  2066. if (features.queueButtons)
  2067. (0,_features_index__WEBPACK_IMPORTED_MODULE_4__.initQueueButtons)();
  2068. if (typeof features.volumeSliderSize === "number")
  2069. (0,_features_index__WEBPACK_IMPORTED_MODULE_4__.setVolSliderSize)();
  2070. if (features.anchorImprovements)
  2071. (0,_features_index__WEBPACK_IMPORTED_MODULE_4__.addAnchorImprovements)();
  2072. (0,_features_index__WEBPACK_IMPORTED_MODULE_4__.setVolSliderStep)();
  2073. }
  2074. if (["ytm", "yt"].includes(domain)) {
  2075. if (features.switchBetweenSites)
  2076. (0,_features_index__WEBPACK_IMPORTED_MODULE_4__.initSiteSwitch)(domain);
  2077. try {
  2078. (0,_features_index__WEBPACK_IMPORTED_MODULE_4__.addMenu)(); // TODO: remove
  2079. }
  2080. catch (err) {
  2081. (0,_utils__WEBPACK_IMPORTED_MODULE_2__.error)("Couldn't add menu:", err);
  2082. }
  2083. }
  2084. }
  2085. catch (err) {
  2086. (0,_utils__WEBPACK_IMPORTED_MODULE_2__.error)("General error while executing feature:", err);
  2087. }
  2088. });
  2089. }
  2090. preInit();
  2091. }();
  2092. //# sourceMappingURL=BetterYTM.user.js.map