BetterYTM.user.js 107 KB

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