BetterYTM.user.js 107 KB

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