BetterYTM.user.js 116 KB

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