BetterYTM.user.js 111 KB

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