BetterYTM.user.js 112 KB

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