BetterYTM.user.js 135 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843
  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";
  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 if undefined.
  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 || forceRead)
  387. featuresCache = yield loadFeatureConf();
  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. // empty object length is 2-3, so check for >3 to be sure
  398. if (typeof featureConf !== "string" || featureConf.length <= 3) {
  399. yield setDefaultFeatConf();
  400. return featuresCache = defConf;
  401. }
  402. return featuresCache = Object.assign(Object.assign({}, defConf), (featureConf ? JSON.parse(featureConf) : {}));
  403. }
  404. catch (err) {
  405. (0,_utils__WEBPACK_IMPORTED_MODULE_1__.error)("Error loading feature configuration, resetting to default:", err);
  406. yield setDefaultFeatConf();
  407. return featuresCache = defConf;
  408. }
  409. });
  410. }
  411. /**
  412. * Saves the passed feature configuration persistently in GM storage and in the in-memory cache
  413. * @param featureConf
  414. */
  415. function saveFeatureConf(featureConf) {
  416. if (!featureConf || typeof featureConf != "object")
  417. throw new TypeError("Feature config not provided or invalid");
  418. (0,_utils__WEBPACK_IMPORTED_MODULE_1__.log)("Saving new feature config:", featureConf);
  419. featuresCache = Object.assign({}, featureConf);
  420. GM.setValue("betterytm-config-ver", formatVersion);
  421. return GM.setValue("betterytm-config", JSON.stringify(featureConf));
  422. }
  423. /** Resets the featuresCache synchronously and the persistent features storage asynchronously to their default values */
  424. function setDefaultFeatConf() {
  425. featuresCache = Object.assign({}, defaultFeatures);
  426. GM.setValue("betterytm-config-ver", formatVersion);
  427. return GM.setValue("betterytm-config", JSON.stringify(defaultFeatures));
  428. }
  429. /***/ }),
  430. /***/ "./src/constants.ts":
  431. /*!**************************!*\
  432. !*** ./src/constants.ts ***!
  433. \**************************/
  434. /***/ (function(__unused_webpack_module, __webpack_exports__, __webpack_require__) {
  435. __webpack_require__.r(__webpack_exports__);
  436. /* harmony export */ __webpack_require__.d(__webpack_exports__, {
  437. /* harmony export */ branch: function() { return /* binding */ branch; },
  438. /* harmony export */ logLevel: function() { return /* binding */ logLevel; },
  439. /* harmony export */ mode: function() { return /* binding */ mode; },
  440. /* harmony export */ scriptInfo: function() { return /* binding */ scriptInfo; }
  441. /* harmony export */ });
  442. const modeRaw = "development";
  443. const branchRaw = "develop";
  444. /** The mode in which the script was built (production or development) */
  445. const mode = modeRaw.match(/^{{.+}}$/) ? "production" : modeRaw;
  446. /** The branch to use in various URLs that point to the GitHub repo */
  447. const branch = branchRaw.match(/^{{.+}}$/) ? "main" : branchRaw;
  448. /**
  449. * How much info should be logged to the devtools console
  450. * 0 = Debug (show everything) or 1 = Info (show only important stuff)
  451. */
  452. const logLevel = mode === "production" ? 1 : 0;
  453. /** Info about the userscript, parsed from the userscript header (tools/post-build.js) */
  454. const scriptInfo = {
  455. name: GM.info.script.name,
  456. version: GM.info.script.version,
  457. namespace: GM.info.script.namespace,
  458. lastCommit: "92012cd", // assert as generic string instead of literal
  459. };
  460. /***/ }),
  461. /***/ "./src/events.ts":
  462. /*!***********************!*\
  463. !*** ./src/events.ts ***!
  464. \***********************/
  465. /***/ (function(__unused_webpack_module, __webpack_exports__, __webpack_require__) {
  466. __webpack_require__.r(__webpack_exports__);
  467. /* harmony export */ __webpack_require__.d(__webpack_exports__, {
  468. /* harmony export */ getEvtData: function() { return /* binding */ getEvtData; },
  469. /* harmony export */ initSiteEvents: function() { return /* binding */ initSiteEvents; },
  470. /* harmony export */ removeAllObservers: function() { return /* binding */ removeAllObservers; },
  471. /* harmony export */ siteEvents: function() { return /* binding */ siteEvents; }
  472. /* harmony export */ });
  473. /* harmony import */ var _billjs_event_emitter__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @billjs/event-emitter */ "./node_modules/@billjs/event-emitter/lib/index.js");
  474. /* harmony import */ var _utils__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./utils */ "./src/utils.ts");
  475. var __awaiter = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) {
  476. function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
  477. return new (P || (P = Promise))(function (resolve, reject) {
  478. function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
  479. function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
  480. function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
  481. step((generator = generator.apply(thisArg, _arguments || [])).next());
  482. });
  483. };
  484. /** EventEmitter instance that is used to detect changes to the site */
  485. const siteEvents = new _billjs_event_emitter__WEBPACK_IMPORTED_MODULE_0__.EventEmitter();
  486. /**
  487. * Returns the data of an event from the `@billjs/event-emitter` library.
  488. * This function is used as a shorthand to extract the data and assert it with the type passed in `<T>`
  489. * @param evt Event object from the `.on()` or `.once()` method
  490. * @template T Type of the data passed by `.fire(type: string, data: T)`
  491. */
  492. function getEvtData(evt) {
  493. return evt.data;
  494. }
  495. let observers = [];
  496. /** Disconnects and deletes all observers. Run `initSiteEvents()` again to create new ones. */
  497. function removeAllObservers() {
  498. observers.forEach((observer, i) => {
  499. observer.disconnect();
  500. delete observers[i];
  501. });
  502. observers = [];
  503. }
  504. /** Creates MutationObservers that check if parts of the site have changed, then emit an event on the `siteEvents` instance. */
  505. function initSiteEvents() {
  506. return __awaiter(this, void 0, void 0, function* () {
  507. try {
  508. //#SECTION queue
  509. // the queue container always exists so it doesn't need the extra init function
  510. const queueObs = new MutationObserver(([{ addedNodes, removedNodes, target }]) => {
  511. if (addedNodes.length > 0 || removedNodes.length > 0) {
  512. (0,_utils__WEBPACK_IMPORTED_MODULE_1__.info)(`Detected queue change - added nodes: ${[...addedNodes.values()].length} - removed nodes: ${[...removedNodes.values()].length}`);
  513. siteEvents.fire("queueChanged", target);
  514. }
  515. });
  516. // only observe added or removed elements
  517. queueObs.observe(document.querySelector(".side-panel.modular #contents.ytmusic-player-queue"), {
  518. childList: true,
  519. });
  520. const autoplayObs = new MutationObserver(([{ addedNodes, removedNodes, target }]) => {
  521. if (addedNodes.length > 0 || removedNodes.length > 0) {
  522. (0,_utils__WEBPACK_IMPORTED_MODULE_1__.info)(`Detected autoplay queue change - added nodes: ${[...addedNodes.values()].length} - removed nodes: ${[...removedNodes.values()].length}`);
  523. siteEvents.fire("autoplayQueueChanged", target);
  524. }
  525. });
  526. autoplayObs.observe(document.querySelector(".side-panel.modular ytmusic-player-queue #automix-contents"), {
  527. childList: true,
  528. });
  529. //#SECTION home page observers
  530. initHomeObservers();
  531. (0,_utils__WEBPACK_IMPORTED_MODULE_1__.info)("Successfully initialized SiteEvents observers");
  532. observers = observers.concat([
  533. queueObs,
  534. autoplayObs,
  535. ]);
  536. }
  537. catch (err) {
  538. (0,_utils__WEBPACK_IMPORTED_MODULE_1__.error)("Couldn't initialize SiteEvents observers due to an error:\n", err);
  539. }
  540. });
  541. }
  542. /**
  543. * The home page might not exist yet if the site was accessed through any path like /watch directly.
  544. * This function will keep waiting for when the home page exists, then create the necessary MutationObservers.
  545. */
  546. function initHomeObservers() {
  547. var _a;
  548. return __awaiter(this, void 0, void 0, function* () {
  549. let interval;
  550. // hidden="" attribute is only present if the content of the page doesn't exist yet
  551. // so this pauses execution until that attribute is removed
  552. if ((_a = document.querySelector("ytmusic-browse-response#browse-page")) === null || _a === void 0 ? void 0 : _a.hasAttribute("hidden")) {
  553. yield new Promise((res) => {
  554. interval = setInterval(() => {
  555. var _a;
  556. if (!((_a = document.querySelector("ytmusic-browse-response#browse-page")) === null || _a === void 0 ? void 0 : _a.hasAttribute("hidden"))) {
  557. clearInterval(interval);
  558. res();
  559. }
  560. }, 50);
  561. });
  562. }
  563. siteEvents.fire("homePageLoaded");
  564. (0,_utils__WEBPACK_IMPORTED_MODULE_1__.info)("Initialized home page observers");
  565. //#SECTION carousel shelves
  566. const shelfContainerObs = new MutationObserver(([{ addedNodes, removedNodes }]) => {
  567. if (addedNodes.length > 0 || removedNodes.length > 0) {
  568. (0,_utils__WEBPACK_IMPORTED_MODULE_1__.info)("Detected carousel shelf container change - added nodes:", addedNodes.length, "- removed nodes:", removedNodes.length);
  569. siteEvents.fire("carouselShelvesChanged", { addedNodes, removedNodes });
  570. }
  571. });
  572. shelfContainerObs.observe(document.querySelector("#contents.ytmusic-section-list-renderer"), {
  573. childList: true,
  574. });
  575. observers = observers.concat([shelfContainerObs]);
  576. });
  577. }
  578. /***/ }),
  579. /***/ "./src/features/index.ts":
  580. /*!*******************************!*\
  581. !*** ./src/features/index.ts ***!
  582. \*******************************/
  583. /***/ (function(__unused_webpack_module, __webpack_exports__, __webpack_require__) {
  584. __webpack_require__.r(__webpack_exports__);
  585. /* harmony export */ __webpack_require__.d(__webpack_exports__, {
  586. /* harmony export */ addAnchorImprovements: function() { return /* reexport safe */ _layout__WEBPACK_IMPORTED_MODULE_2__.addAnchorImprovements; },
  587. /* harmony export */ addConfigMenuOption: function() { return /* reexport safe */ _layout__WEBPACK_IMPORTED_MODULE_2__.addConfigMenuOption; },
  588. /* harmony export */ addLyricsCacheEntry: function() { return /* reexport safe */ _lyrics__WEBPACK_IMPORTED_MODULE_3__.addLyricsCacheEntry; },
  589. /* harmony export */ addMediaCtrlLyricsBtn: function() { return /* reexport safe */ _lyrics__WEBPACK_IMPORTED_MODULE_3__.addMediaCtrlLyricsBtn; },
  590. /* harmony export */ addMenu: function() { return /* reexport safe */ _menu_menu_old__WEBPACK_IMPORTED_MODULE_5__.addMenu; },
  591. /* harmony export */ addWatermark: function() { return /* reexport safe */ _layout__WEBPACK_IMPORTED_MODULE_2__.addWatermark; },
  592. /* harmony export */ closeMenu: function() { return /* reexport safe */ _menu_menu_old__WEBPACK_IMPORTED_MODULE_5__.closeMenu; },
  593. /* harmony export */ createLyricsBtn: function() { return /* reexport safe */ _lyrics__WEBPACK_IMPORTED_MODULE_3__.createLyricsBtn; },
  594. /* harmony export */ disableBeforeUnload: function() { return /* reexport safe */ _input__WEBPACK_IMPORTED_MODULE_1__.disableBeforeUnload; },
  595. /* harmony export */ enableBeforeUnload: function() { return /* reexport safe */ _input__WEBPACK_IMPORTED_MODULE_1__.enableBeforeUnload; },
  596. /* harmony export */ featInfo: function() { return /* binding */ featInfo; },
  597. /* harmony export */ geniUrlBase: function() { return /* reexport safe */ _lyrics__WEBPACK_IMPORTED_MODULE_3__.geniUrlBase; },
  598. /* harmony export */ getCurrentLyricsUrl: function() { return /* reexport safe */ _lyrics__WEBPACK_IMPORTED_MODULE_3__.getCurrentLyricsUrl; },
  599. /* harmony export */ getGeniusUrl: function() { return /* reexport safe */ _lyrics__WEBPACK_IMPORTED_MODULE_3__.getGeniusUrl; },
  600. /* harmony export */ getLyricsCacheEntry: function() { return /* reexport safe */ _lyrics__WEBPACK_IMPORTED_MODULE_3__.getLyricsCacheEntry; },
  601. /* harmony export */ initArrowKeySkip: function() { return /* reexport safe */ _input__WEBPACK_IMPORTED_MODULE_1__.initArrowKeySkip; },
  602. /* harmony export */ initBeforeUnloadHook: function() { return /* reexport safe */ _input__WEBPACK_IMPORTED_MODULE_1__.initBeforeUnloadHook; },
  603. /* harmony export */ initMenu: function() { return /* reexport safe */ _menu_menu__WEBPACK_IMPORTED_MODULE_4__.initMenu; },
  604. /* harmony export */ initQueueButtons: function() { return /* reexport safe */ _layout__WEBPACK_IMPORTED_MODULE_2__.initQueueButtons; },
  605. /* harmony export */ initSiteSwitch: function() { return /* reexport safe */ _input__WEBPACK_IMPORTED_MODULE_1__.initSiteSwitch; },
  606. /* harmony export */ initVolumeFeatures: function() { return /* reexport safe */ _layout__WEBPACK_IMPORTED_MODULE_2__.initVolumeFeatures; },
  607. /* harmony export */ openMenu: function() { return /* reexport safe */ _menu_menu_old__WEBPACK_IMPORTED_MODULE_5__.openMenu; },
  608. /* harmony export */ preInitLayout: function() { return /* reexport safe */ _layout__WEBPACK_IMPORTED_MODULE_2__.preInitLayout; },
  609. /* harmony export */ removeUpgradeTab: function() { return /* reexport safe */ _layout__WEBPACK_IMPORTED_MODULE_2__.removeUpgradeTab; },
  610. /* harmony export */ sanitizeArtists: function() { return /* reexport safe */ _lyrics__WEBPACK_IMPORTED_MODULE_3__.sanitizeArtists; },
  611. /* harmony export */ sanitizeSong: function() { return /* reexport safe */ _lyrics__WEBPACK_IMPORTED_MODULE_3__.sanitizeSong; }
  612. /* harmony export */ });
  613. /* harmony import */ var _constants__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../constants */ "./src/constants.ts");
  614. /* harmony import */ var _input__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./input */ "./src/features/input.ts");
  615. /* harmony import */ var _layout__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./layout */ "./src/features/layout.ts");
  616. /* harmony import */ var _lyrics__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./lyrics */ "./src/features/lyrics.ts");
  617. /* harmony import */ var _menu_menu__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./menu/menu */ "./src/features/menu/menu.ts");
  618. /* harmony import */ var _menu_menu_old__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./menu/menu_old */ "./src/features/menu/menu_old.ts");
  619. /** Contains all possible features with their default values and other config */
  620. const featInfo = {
  621. //#SECTION input
  622. arrowKeySupport: {
  623. desc: "Arrow keys skip forwards and backwards by 10 seconds",
  624. type: "toggle",
  625. category: "input",
  626. default: true,
  627. },
  628. switchBetweenSites: {
  629. desc: "Add F9 as a hotkey to switch between the YT and YTM sites on a video / song",
  630. type: "toggle",
  631. category: "input",
  632. default: true,
  633. },
  634. switchSitesHotkey: {
  635. desc: "TODO(v1.1): Which hotkey needs to be pressed to switch sites?",
  636. type: "hotkey",
  637. category: "input",
  638. default: {
  639. key: "F9",
  640. shift: false,
  641. ctrl: false,
  642. meta: false,
  643. },
  644. visible: false,
  645. },
  646. disableBeforeUnloadPopup: {
  647. desc: "Completely disable the popup that sometimes appears before leaving the site",
  648. type: "toggle",
  649. category: "input",
  650. default: false,
  651. },
  652. anchorImprovements: {
  653. desc: "Add link elements all over the page so stuff can be opened in a new tab easier",
  654. type: "toggle",
  655. category: "input",
  656. default: true,
  657. },
  658. //#SECTION layout
  659. removeUpgradeTab: {
  660. desc: "Remove the \"Upgrade\" / YT Music Premium tab",
  661. type: "toggle",
  662. category: "layout",
  663. default: true,
  664. },
  665. volumeSliderLabel: {
  666. desc: "Add a percentage label to the volume slider",
  667. type: "toggle",
  668. category: "layout",
  669. default: true,
  670. },
  671. volumeSliderSize: {
  672. desc: "Width of the volume slider in pixels",
  673. type: "number",
  674. category: "layout",
  675. min: 50,
  676. max: 500,
  677. step: 5,
  678. default: 160,
  679. unit: "px",
  680. },
  681. volumeSliderStep: {
  682. desc: "Volume slider sensitivity - the smaller this number, the finer the volume control",
  683. type: "slider",
  684. category: "layout",
  685. min: 1,
  686. max: 20,
  687. default: 2,
  688. },
  689. watermarkEnabled: {
  690. desc: `Show a ${_constants__WEBPACK_IMPORTED_MODULE_0__.scriptInfo.name} watermark under the YTM logo`,
  691. type: "toggle",
  692. category: "layout",
  693. default: true,
  694. },
  695. queueButtons: {
  696. desc: "Add buttons to each song in the queue to quickly open their lyrics or remove them from the queue",
  697. type: "toggle",
  698. category: "layout",
  699. default: true,
  700. },
  701. //#SECTION lyrics
  702. geniusLyrics: {
  703. desc: "Add a button to the media controls of the currently playing song to open its lyrics on genius.com",
  704. type: "toggle",
  705. category: "lyrics",
  706. default: true,
  707. },
  708. };
  709. /***/ }),
  710. /***/ "./src/features/input.ts":
  711. /*!*******************************!*\
  712. !*** ./src/features/input.ts ***!
  713. \*******************************/
  714. /***/ (function(__unused_webpack_module, __webpack_exports__, __webpack_require__) {
  715. __webpack_require__.r(__webpack_exports__);
  716. /* harmony export */ __webpack_require__.d(__webpack_exports__, {
  717. /* harmony export */ disableBeforeUnload: function() { return /* binding */ disableBeforeUnload; },
  718. /* harmony export */ enableBeforeUnload: function() { return /* binding */ enableBeforeUnload; },
  719. /* harmony export */ initArrowKeySkip: function() { return /* binding */ initArrowKeySkip; },
  720. /* harmony export */ initBeforeUnloadHook: function() { return /* binding */ initBeforeUnloadHook; },
  721. /* harmony export */ initSiteSwitch: function() { return /* binding */ initSiteSwitch; }
  722. /* harmony export */ });
  723. /* harmony import */ var _sv443_network_userutils__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @sv443-network/userutils */ "./node_modules/@sv443-network/userutils/dist/index.mjs");
  724. /* harmony import */ var _utils__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../utils */ "./src/utils.ts");
  725. /* harmony import */ var _config__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../config */ "./src/config.ts");
  726. var __awaiter = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) {
  727. function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
  728. return new (P || (P = Promise))(function (resolve, reject) {
  729. function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
  730. function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
  731. function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
  732. step((generator = generator.apply(thisArg, _arguments || [])).next());
  733. });
  734. };
  735. //#MARKER arrow key skip
  736. function initArrowKeySkip() {
  737. document.addEventListener("keydown", onKeyDown);
  738. (0,_utils__WEBPACK_IMPORTED_MODULE_1__.log)("Added key press listener");
  739. }
  740. /** Called when the user presses any key, anywhere */
  741. function onKeyDown(evt) {
  742. var _a, _b;
  743. if (["ArrowLeft", "ArrowRight"].includes(evt.code)) {
  744. // discard the event when a (text) input is currently active, like when editing a playlist
  745. if (["INPUT", "TEXTAREA", "SELECT"].includes((_b = (_a = document.activeElement) === null || _a === void 0 ? void 0 : _a.tagName) !== null && _b !== void 0 ? _b : "_"))
  746. return (0,_utils__WEBPACK_IMPORTED_MODULE_1__.info)(`Captured valid key but the current active element is <${document.activeElement.tagName.toLowerCase()}>, so the keypress is ignored`);
  747. (0,_utils__WEBPACK_IMPORTED_MODULE_1__.log)(`Captured key '${evt.code}' in proxy listener`);
  748. // 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
  749. const defaultProps = {
  750. altKey: false,
  751. ctrlKey: false,
  752. metaKey: false,
  753. shiftKey: false,
  754. target: document.body,
  755. currentTarget: document.body,
  756. originalTarget: document.body,
  757. explicitOriginalTarget: document.body,
  758. srcElement: document.body,
  759. type: "keydown",
  760. bubbles: true,
  761. cancelBubble: false,
  762. cancelable: true,
  763. isTrusted: true,
  764. repeat: false,
  765. // needed because otherwise YTM errors out - see https://github.com/Sv443/BetterYTM/issues/18#show_issue
  766. view: (0,_sv443_network_userutils__WEBPACK_IMPORTED_MODULE_0__.getUnsafeWindow)(),
  767. };
  768. let invalidKey = false;
  769. let keyProps = {};
  770. switch (evt.code) {
  771. case "ArrowLeft":
  772. keyProps = {
  773. code: "KeyH",
  774. key: "h",
  775. keyCode: 72,
  776. which: 72,
  777. };
  778. break;
  779. case "ArrowRight":
  780. keyProps = {
  781. code: "KeyL",
  782. key: "l",
  783. keyCode: 76,
  784. which: 76,
  785. };
  786. break;
  787. default:
  788. invalidKey = true;
  789. break;
  790. }
  791. if (!invalidKey) {
  792. const proxyProps = Object.assign(Object.assign({ code: "" }, defaultProps), keyProps);
  793. document.body.dispatchEvent(new KeyboardEvent("keydown", proxyProps));
  794. (0,_utils__WEBPACK_IMPORTED_MODULE_1__.log)(`Dispatched proxy keydown event: [${evt.code}] -> [${proxyProps.code}]`);
  795. }
  796. else
  797. (0,_utils__WEBPACK_IMPORTED_MODULE_1__.warn)(`Captured key '${evt.code}' has no defined behavior`);
  798. }
  799. }
  800. //#MARKER site switch
  801. /** Initializes the site switch feature */
  802. function initSiteSwitch(domain) {
  803. document.addEventListener("keydown", (e) => {
  804. if (e.key === "F9")
  805. switchSite(domain === "yt" ? "ytm" : "yt");
  806. });
  807. (0,_utils__WEBPACK_IMPORTED_MODULE_1__.log)("Initialized site switch listener");
  808. }
  809. /** Switches to the other site (between YT and YTM) */
  810. function switchSite(newDomain) {
  811. var _a;
  812. return __awaiter(this, void 0, void 0, function* () {
  813. try {
  814. if (newDomain === "ytm" && !location.href.includes("/watch"))
  815. return (0,_utils__WEBPACK_IMPORTED_MODULE_1__.warn)("Not on a video page, so the site switch is ignored");
  816. let subdomain;
  817. if (newDomain === "ytm")
  818. subdomain = "music";
  819. else if (newDomain === "yt")
  820. subdomain = "www";
  821. if (!subdomain)
  822. throw new Error(`Unrecognized domain '${newDomain}'`);
  823. disableBeforeUnload();
  824. const { pathname, search, hash } = new URL(location.href);
  825. const vt = (_a = yield (0,_utils__WEBPACK_IMPORTED_MODULE_1__.getVideoTime)()) !== null && _a !== void 0 ? _a : 0;
  826. (0,_utils__WEBPACK_IMPORTED_MODULE_1__.log)(`Found video time of ${vt} seconds`);
  827. const cleanSearch = search.split("&")
  828. .filter((param) => !param.match(/^\??t=/))
  829. .join("&");
  830. const newSearch = cleanSearch.includes("?") ? `${cleanSearch.startsWith("?") ? cleanSearch : "?" + cleanSearch}&t=${vt}` : `?t=${vt}`;
  831. const newUrl = `https://${subdomain}.youtube.com${pathname}${newSearch}${hash}`;
  832. (0,_utils__WEBPACK_IMPORTED_MODULE_1__.info)(`Switching to domain '${newDomain}' at ${newUrl}`);
  833. location.assign(newUrl);
  834. }
  835. catch (err) {
  836. (0,_utils__WEBPACK_IMPORTED_MODULE_1__.error)("Error while switching site:", err);
  837. }
  838. });
  839. }
  840. //#MARKER beforeunload popup
  841. let beforeUnloadEnabled = true;
  842. /** Disables the popup before leaving the site */
  843. function disableBeforeUnload() {
  844. beforeUnloadEnabled = false;
  845. (0,_utils__WEBPACK_IMPORTED_MODULE_1__.info)("Disabled popup before leaving the site");
  846. }
  847. /** (Re-)enables the popup before leaving the site */
  848. function enableBeforeUnload() {
  849. beforeUnloadEnabled = true;
  850. (0,_utils__WEBPACK_IMPORTED_MODULE_1__.info)("Enabled popup before leaving the site");
  851. }
  852. /**
  853. * Adds a spy function into `window.__proto__.addEventListener` to selectively discard `beforeunload`
  854. * event listeners before they can be called by the site.
  855. */
  856. function initBeforeUnloadHook() {
  857. Error.stackTraceLimit = 1000; // default is 25 on FF so this should hopefully be more than enough
  858. (function (original) {
  859. // @ts-ignore
  860. window.__proto__.addEventListener = function (...args) {
  861. if (!beforeUnloadEnabled && args[0] === "beforeunload")
  862. return (0,_utils__WEBPACK_IMPORTED_MODULE_1__.log)("Prevented beforeunload event listener from being called");
  863. else
  864. return original.apply(this, args);
  865. };
  866. // @ts-ignore
  867. })(window.__proto__.addEventListener);
  868. (0,_config__WEBPACK_IMPORTED_MODULE_2__.getFeatures)().then(feats => {
  869. if (feats.disableBeforeUnloadPopup)
  870. disableBeforeUnload();
  871. });
  872. }
  873. /***/ }),
  874. /***/ "./src/features/layout.ts":
  875. /*!********************************!*\
  876. !*** ./src/features/layout.ts ***!
  877. \********************************/
  878. /***/ (function(__unused_webpack_module, __webpack_exports__, __webpack_require__) {
  879. __webpack_require__.r(__webpack_exports__);
  880. /* harmony export */ __webpack_require__.d(__webpack_exports__, {
  881. /* harmony export */ addAnchorImprovements: function() { return /* binding */ addAnchorImprovements; },
  882. /* harmony export */ addConfigMenuOption: function() { return /* binding */ addConfigMenuOption; },
  883. /* harmony export */ addWatermark: function() { return /* binding */ addWatermark; },
  884. /* harmony export */ initQueueButtons: function() { return /* binding */ initQueueButtons; },
  885. /* harmony export */ initVolumeFeatures: function() { return /* binding */ initVolumeFeatures; },
  886. /* harmony export */ preInitLayout: function() { return /* binding */ preInitLayout; },
  887. /* harmony export */ removeUpgradeTab: function() { return /* binding */ removeUpgradeTab; }
  888. /* harmony export */ });
  889. /* harmony import */ var _sv443_network_userutils__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @sv443-network/userutils */ "./node_modules/@sv443-network/userutils/dist/index.mjs");
  890. /* harmony import */ var _constants__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../constants */ "./src/constants.ts");
  891. /* harmony import */ var _config__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../config */ "./src/config.ts");
  892. /* harmony import */ var _utils__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../utils */ "./src/utils.ts");
  893. /* harmony import */ var _events__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../events */ "./src/events.ts");
  894. /* harmony import */ var _menu_menu_old__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./menu/menu_old */ "./src/features/menu/menu_old.ts");
  895. /* harmony import */ var _lyrics__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ./lyrics */ "./src/features/lyrics.ts");
  896. /* harmony import */ var _layout_css__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ./layout.css */ "./src/features/layout.css");
  897. /* harmony import */ var ___WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! . */ "./src/features/index.ts");
  898. var __awaiter = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) {
  899. function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
  900. return new (P || (P = Promise))(function (resolve, reject) {
  901. function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
  902. function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
  903. function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
  904. step((generator = generator.apply(thisArg, _arguments || [])).next());
  905. });
  906. };
  907. let features;
  908. function preInitLayout() {
  909. return __awaiter(this, void 0, void 0, function* () {
  910. features = yield (0,_config__WEBPACK_IMPORTED_MODULE_2__.getFeatures)();
  911. });
  912. }
  913. //#MARKER BYTM-Config buttons
  914. let menuOpenAmt = 0, logoExchanged = false;
  915. /** Adds a watermark beneath the logo */
  916. function addWatermark() {
  917. const watermark = document.createElement("a");
  918. watermark.role = "button";
  919. watermark.id = "bytm-watermark";
  920. watermark.className = "style-scope ytmusic-nav-bar bytm-no-select";
  921. watermark.innerText = _constants__WEBPACK_IMPORTED_MODULE_1__.scriptInfo.name;
  922. watermark.title = "Open menu";
  923. watermark.tabIndex = 1000;
  924. improveLogo();
  925. watermark.addEventListener("click", (e) => {
  926. e.stopPropagation();
  927. menuOpenAmt++;
  928. if ((!e.shiftKey || logoExchanged) && menuOpenAmt !== 5)
  929. (0,_menu_menu_old__WEBPACK_IMPORTED_MODULE_5__.openMenu)();
  930. if ((!logoExchanged && e.shiftKey) || menuOpenAmt === 5)
  931. exchangeLogo();
  932. });
  933. // when using the tab key to navigate
  934. watermark.addEventListener("keydown", (e) => {
  935. if (e.key === "Enter") {
  936. e.stopPropagation();
  937. menuOpenAmt++;
  938. if ((!e.shiftKey || logoExchanged) && menuOpenAmt !== 5)
  939. (0,_menu_menu_old__WEBPACK_IMPORTED_MODULE_5__.openMenu)();
  940. if ((!logoExchanged && e.shiftKey) || menuOpenAmt === 5)
  941. exchangeLogo();
  942. }
  943. });
  944. const logoElem = document.querySelector("#left-content");
  945. (0,_sv443_network_userutils__WEBPACK_IMPORTED_MODULE_0__.insertAfter)(logoElem, watermark);
  946. (0,_utils__WEBPACK_IMPORTED_MODULE_3__.log)("Added watermark element", watermark);
  947. }
  948. /** Turns the regular `<img>`-based logo into inline SVG to be able to animate and modify parts of it */
  949. function improveLogo() {
  950. return __awaiter(this, void 0, void 0, function* () {
  951. try {
  952. const res = yield (0,_sv443_network_userutils__WEBPACK_IMPORTED_MODULE_0__.fetchAdvanced)("https://music.youtube.com/img/on_platform_logo_dark.svg");
  953. const svg = yield res.text();
  954. (0,_sv443_network_userutils__WEBPACK_IMPORTED_MODULE_0__.onSelector)("ytmusic-logo a", {
  955. listener: (logoElem) => {
  956. var _a;
  957. logoElem.classList.add("bytm-mod-logo", "bytm-no-select");
  958. logoElem.innerHTML = svg;
  959. logoElem.querySelectorAll("ellipse").forEach((e) => {
  960. e.classList.add("bytm-mod-logo-ellipse");
  961. });
  962. (_a = logoElem.querySelector("path")) === null || _a === void 0 ? void 0 : _a.classList.add("bytm-mod-logo-path");
  963. (0,_utils__WEBPACK_IMPORTED_MODULE_3__.log)("Swapped logo to inline SVG");
  964. },
  965. });
  966. }
  967. catch (err) {
  968. (0,_utils__WEBPACK_IMPORTED_MODULE_3__.error)("Couldn't improve logo due to an error:", err);
  969. }
  970. });
  971. }
  972. /** Exchanges the default YTM logo into BetterYTM's logo with a sick ass animation */
  973. function exchangeLogo() {
  974. (0,_sv443_network_userutils__WEBPACK_IMPORTED_MODULE_0__.onSelector)(".bytm-mod-logo", {
  975. listener: (logoElem) => {
  976. if (logoElem.classList.contains("bytm-logo-exchanged"))
  977. return;
  978. logoExchanged = true;
  979. logoElem.classList.add("bytm-logo-exchanged");
  980. const newLogo = document.createElement("img");
  981. newLogo.className = "bytm-mod-logo-img";
  982. newLogo.src = (0,_utils__WEBPACK_IMPORTED_MODULE_3__.getAssetUrl)("icon/icon.png");
  983. logoElem.insertBefore(newLogo, logoElem.querySelector("svg"));
  984. document.head.querySelectorAll("link[rel=\"icon\"]").forEach(e => {
  985. e.href = (0,_utils__WEBPACK_IMPORTED_MODULE_3__.getAssetUrl)("icon/icon.png");
  986. });
  987. setTimeout(() => {
  988. logoElem.querySelectorAll(".bytm-mod-logo-ellipse").forEach(e => e.remove());
  989. }, 1000);
  990. },
  991. });
  992. }
  993. /** Called whenever the menu exists to add a BYTM-Configuration button */
  994. function addConfigMenuOption(container) {
  995. const cfgOptElem = document.createElement("a");
  996. cfgOptElem.role = "button";
  997. cfgOptElem.className = "bytm-cfg-menu-option bytm-anchor";
  998. cfgOptElem.ariaLabel = "Click to open BetterYTM's configuration menu";
  999. const cfgOptItemElem = document.createElement("div");
  1000. cfgOptItemElem.className = "bytm-cfg-menu-option-item";
  1001. cfgOptItemElem.addEventListener("click", (e) => {
  1002. const settingsBtnElem = document.querySelector("ytmusic-nav-bar ytmusic-settings-button tp-yt-paper-icon-button");
  1003. settingsBtnElem === null || settingsBtnElem === void 0 ? void 0 : settingsBtnElem.click();
  1004. menuOpenAmt++;
  1005. if ((!e.shiftKey || logoExchanged) && menuOpenAmt !== 5)
  1006. (0,_menu_menu_old__WEBPACK_IMPORTED_MODULE_5__.openMenu)();
  1007. if ((!logoExchanged && e.shiftKey) || menuOpenAmt === 5)
  1008. exchangeLogo();
  1009. });
  1010. const cfgOptIconElem = document.createElement("img");
  1011. cfgOptIconElem.className = "bytm-cfg-menu-option-icon";
  1012. cfgOptIconElem.src = (0,_utils__WEBPACK_IMPORTED_MODULE_3__.getAssetUrl)("icon/icon.png");
  1013. const cfgOptTextElem = document.createElement("div");
  1014. cfgOptTextElem.className = "bytm-cfg-menu-option-text";
  1015. cfgOptTextElem.innerText = "BetterYTM Configuration";
  1016. cfgOptItemElem.appendChild(cfgOptIconElem);
  1017. cfgOptItemElem.appendChild(cfgOptTextElem);
  1018. cfgOptElem.appendChild(cfgOptItemElem);
  1019. container.appendChild(cfgOptElem);
  1020. (0,_utils__WEBPACK_IMPORTED_MODULE_3__.log)("Added BYTM-Configuration button to menu popover", cfgOptElem);
  1021. }
  1022. //#MARKER remove upgrade tab
  1023. /** Removes the "Upgrade" / YT Music Premium tab from the sidebar */
  1024. function removeUpgradeTab() {
  1025. (0,_sv443_network_userutils__WEBPACK_IMPORTED_MODULE_0__.onSelector)("ytmusic-app-layout tp-yt-app-drawer #contentContainer #guide-content #items ytmusic-guide-entry-renderer:nth-child(4)", {
  1026. listener: (tabElemLarge) => {
  1027. tabElemLarge.remove();
  1028. (0,_utils__WEBPACK_IMPORTED_MODULE_3__.log)("Removed large upgrade tab");
  1029. },
  1030. });
  1031. // TODO:FIXME: doesn't work fsr
  1032. (0,_sv443_network_userutils__WEBPACK_IMPORTED_MODULE_0__.onSelector)("ytmusic-app-layout #mini-guide ytmusic-guide-renderer #sections ytmusic-guide-section-renderer[is-primary] #items ytmusic-guide-entry-renderer:nth-child(4)", {
  1033. listener: (tabElemSmall) => {
  1034. tabElemSmall.remove();
  1035. (0,_utils__WEBPACK_IMPORTED_MODULE_3__.log)("Removed small upgrade tab");
  1036. },
  1037. });
  1038. }
  1039. //#MARKER volume slider
  1040. function initVolumeFeatures() {
  1041. (0,_sv443_network_userutils__WEBPACK_IMPORTED_MODULE_0__.onSelector)("tp-yt-paper-slider#volume-slider", {
  1042. listener: (sliderElem) => {
  1043. const volSliderCont = document.createElement("div");
  1044. volSliderCont.id = "bytm-vol-slider-cont";
  1045. (0,_sv443_network_userutils__WEBPACK_IMPORTED_MODULE_0__.addParent)(sliderElem, volSliderCont);
  1046. if (typeof features.volumeSliderSize === "number")
  1047. setVolSliderSize();
  1048. if (features.volumeSliderLabel)
  1049. addVolumeSliderLabel();
  1050. setVolSliderStep();
  1051. },
  1052. });
  1053. }
  1054. const volSliderSelector = "tp-yt-paper-slider#volume-slider";
  1055. /** Adds a percentage label to the volume slider and tooltip */
  1056. function addVolumeSliderLabel() {
  1057. (0,_sv443_network_userutils__WEBPACK_IMPORTED_MODULE_0__.onSelector)(volSliderSelector, {
  1058. listener: (sliderElem) => {
  1059. const labelElem = document.createElement("div");
  1060. labelElem.className = "bytm-vol-slider-label";
  1061. labelElem.innerText = `${sliderElem.value}%`;
  1062. sliderElem.addEventListener("change", () => {
  1063. const label = `${sliderElem.value}%`;
  1064. const sensText = features.volumeSliderStep !== ___WEBPACK_IMPORTED_MODULE_8__.featInfo.volumeSliderStep["default"] ? ` (Sensitivity: ${sliderElem.step})` : "";
  1065. const labelFull = `Volume: ${label}${sensText}`;
  1066. sliderElem.setAttribute("title", labelFull); // TODO: probably needs to be on the parent
  1067. sliderElem.setAttribute("aria-valuetext", labelFull);
  1068. const labelElem2 = document.querySelector(".bytm-vol-slider-label");
  1069. if (labelElem2)
  1070. labelElem2.innerText = label;
  1071. });
  1072. (0,_sv443_network_userutils__WEBPACK_IMPORTED_MODULE_0__.onSelector)("#bytm-vol-slider-cont", {
  1073. listener: (volumeCont) => {
  1074. volumeCont.appendChild(labelElem);
  1075. (0,_utils__WEBPACK_IMPORTED_MODULE_3__.log)("Added volume slider label", labelElem);
  1076. },
  1077. });
  1078. },
  1079. });
  1080. }
  1081. /** Sets the volume slider to a set size */
  1082. function setVolSliderSize() {
  1083. const { volumeSliderSize: size } = features;
  1084. if (typeof size !== "number" || isNaN(Number(size)))
  1085. return;
  1086. (0,_sv443_network_userutils__WEBPACK_IMPORTED_MODULE_0__.addGlobalStyle)(`\
  1087. /* BetterYTM - set volume slider size */
  1088. #bytm-vol-slider-cont tp-yt-paper-slider#volume-slider {
  1089. width: ${size}px !important;
  1090. }`);
  1091. }
  1092. /** Sets the `step` attribute of the volume slider */
  1093. function setVolSliderStep() {
  1094. (0,_sv443_network_userutils__WEBPACK_IMPORTED_MODULE_0__.onSelector)(volSliderSelector, {
  1095. listener: (sliderElem) => {
  1096. sliderElem.setAttribute("step", String(features.volumeSliderStep));
  1097. },
  1098. });
  1099. }
  1100. //#MARKER queue buttons
  1101. function initQueueButtons() {
  1102. const addQueueBtns = (evt) => {
  1103. let amt = 0;
  1104. for (const queueItm of (0,_events__WEBPACK_IMPORTED_MODULE_4__.getEvtData)(evt).childNodes) {
  1105. if (!queueItm.classList.contains("bytm-has-queue-btns")) {
  1106. addQueueButtons(queueItm);
  1107. amt++;
  1108. }
  1109. }
  1110. if (amt > 0)
  1111. (0,_utils__WEBPACK_IMPORTED_MODULE_3__.log)(`Added buttons to ${amt} new queue ${(0,_sv443_network_userutils__WEBPACK_IMPORTED_MODULE_0__.autoPlural)("item", amt)}`);
  1112. };
  1113. _events__WEBPACK_IMPORTED_MODULE_4__.siteEvents.on("queueChanged", addQueueBtns);
  1114. _events__WEBPACK_IMPORTED_MODULE_4__.siteEvents.on("autoplayQueueChanged", addQueueBtns);
  1115. const queueItems = document.querySelectorAll("#contents.ytmusic-player-queue > ytmusic-player-queue-item");
  1116. if (queueItems.length === 0)
  1117. return;
  1118. queueItems.forEach(itm => addQueueButtons(itm));
  1119. (0,_utils__WEBPACK_IMPORTED_MODULE_3__.log)(`Added buttons to ${queueItems.length} existing queue ${(0,_sv443_network_userutils__WEBPACK_IMPORTED_MODULE_0__.autoPlural)("item", queueItems)}`);
  1120. }
  1121. /**
  1122. * Adds the buttons to each item in the current song queue.
  1123. * Also observes for changes to add new buttons to new items in the queue.
  1124. * TODO:FIXME: deleting an element from the queue shifts the lyrics buttons
  1125. * @param queueItem The element with tagname `ytmusic-player-queue-item` to add queue buttons to
  1126. */
  1127. function addQueueButtons(queueItem) {
  1128. return __awaiter(this, void 0, void 0, function* () {
  1129. //#SECTION general queue item stuff
  1130. const queueBtnsCont = document.createElement("div");
  1131. queueBtnsCont.className = "bytm-queue-btn-container";
  1132. const songInfo = queueItem.querySelector(".song-info");
  1133. if (!songInfo)
  1134. return false;
  1135. const [songEl, artistEl] = songInfo.querySelectorAll("yt-formatted-string");
  1136. const song = songEl.innerText;
  1137. const artist = artistEl.innerText;
  1138. if (!song || !artist)
  1139. return false;
  1140. //#SECTION lyrics btn
  1141. const lyricsBtnElem = (0,_lyrics__WEBPACK_IMPORTED_MODULE_6__.createLyricsBtn)(undefined, false);
  1142. {
  1143. lyricsBtnElem.title = "Open this song's lyrics in a new tab";
  1144. lyricsBtnElem.style.display = "inline-flex";
  1145. lyricsBtnElem.style.visibility = "initial";
  1146. lyricsBtnElem.style.pointerEvents = "initial";
  1147. lyricsBtnElem.addEventListener("click", (e) => __awaiter(this, void 0, void 0, function* () {
  1148. e.stopPropagation();
  1149. let lyricsUrl;
  1150. const artistsSan = (0,_lyrics__WEBPACK_IMPORTED_MODULE_6__.sanitizeArtists)(artist);
  1151. const songSan = (0,_lyrics__WEBPACK_IMPORTED_MODULE_6__.sanitizeSong)(song);
  1152. const cachedLyricsUrl = (0,_lyrics__WEBPACK_IMPORTED_MODULE_6__.getLyricsCacheEntry)(artistsSan, songSan);
  1153. if (cachedLyricsUrl)
  1154. lyricsUrl = cachedLyricsUrl;
  1155. else if (!songInfo.hasAttribute("data-bytm-loading")) {
  1156. const imgEl = lyricsBtnElem.querySelector("img");
  1157. if (!cachedLyricsUrl) {
  1158. songInfo.setAttribute("data-bytm-loading", "");
  1159. imgEl.src = (0,_utils__WEBPACK_IMPORTED_MODULE_3__.getAssetUrl)("spinner.svg");
  1160. imgEl.classList.add("bytm-spinner");
  1161. }
  1162. lyricsUrl = cachedLyricsUrl !== null && cachedLyricsUrl !== void 0 ? cachedLyricsUrl : yield (0,_lyrics__WEBPACK_IMPORTED_MODULE_6__.getGeniusUrl)(artistsSan, songSan);
  1163. const resetImgElem = () => {
  1164. imgEl.src = (0,_utils__WEBPACK_IMPORTED_MODULE_3__.getAssetUrl)("lyrics.svg");
  1165. imgEl.classList.remove("bytm-spinner");
  1166. };
  1167. if (!cachedLyricsUrl) {
  1168. songInfo.removeAttribute("data-bytm-loading");
  1169. // so the new image doesn't "blink"
  1170. setTimeout(resetImgElem, 100);
  1171. }
  1172. if (!lyricsUrl) {
  1173. resetImgElem();
  1174. if (confirm("Couldn't find a lyrics page for this song.\nDo you want to open genius.com to manually search for it?"))
  1175. (0,_sv443_network_userutils__WEBPACK_IMPORTED_MODULE_0__.openInNewTab)("https://genius.com/search");
  1176. return;
  1177. }
  1178. }
  1179. lyricsUrl && (0,_sv443_network_userutils__WEBPACK_IMPORTED_MODULE_0__.openInNewTab)(lyricsUrl);
  1180. }));
  1181. }
  1182. //#SECTION delete from queue btn
  1183. const deleteBtnElem = document.createElement("a");
  1184. {
  1185. Object.assign(deleteBtnElem, {
  1186. title: "Remove this song from the queue",
  1187. className: "ytmusic-player-bar bytm-delete-from-queue bytm-generic-btn",
  1188. role: "button",
  1189. });
  1190. deleteBtnElem.style.visibility = "initial";
  1191. deleteBtnElem.addEventListener("click", (e) => __awaiter(this, void 0, void 0, function* () {
  1192. e.stopPropagation();
  1193. // container of the queue item popup menu - element gets reused for every queue item
  1194. let queuePopupCont = document.querySelector("ytmusic-app ytmusic-popup-container tp-yt-iron-dropdown");
  1195. try {
  1196. // three dots button to open the popup menu of a queue item
  1197. const dotsBtnElem = queueItem.querySelector("ytmusic-menu-renderer yt-button-shape button");
  1198. if (queuePopupCont)
  1199. queuePopupCont.setAttribute("data-bytm-hidden", "true");
  1200. dotsBtnElem.click();
  1201. yield (0,_sv443_network_userutils__WEBPACK_IMPORTED_MODULE_0__.pauseFor)(25);
  1202. queuePopupCont = document.querySelector("ytmusic-app ytmusic-popup-container tp-yt-iron-dropdown");
  1203. if (!queuePopupCont.hasAttribute("data-bytm-hidden"))
  1204. queuePopupCont.setAttribute("data-bytm-hidden", "true");
  1205. // a little bit janky and unreliable but the only way afaik
  1206. const removeFromQueueBtn = queuePopupCont.querySelector("tp-yt-paper-listbox *[role=option]:nth-child(7)");
  1207. yield (0,_sv443_network_userutils__WEBPACK_IMPORTED_MODULE_0__.pauseFor)(20);
  1208. removeFromQueueBtn.click();
  1209. }
  1210. catch (err) {
  1211. (0,_utils__WEBPACK_IMPORTED_MODULE_3__.error)("Couldn't remove song from queue due to error:", err);
  1212. }
  1213. finally {
  1214. queuePopupCont === null || queuePopupCont === void 0 ? void 0 : queuePopupCont.removeAttribute("data-bytm-hidden");
  1215. }
  1216. }));
  1217. const imgElem = document.createElement("img");
  1218. imgElem.className = "bytm-generic-btn-img";
  1219. imgElem.src = (0,_utils__WEBPACK_IMPORTED_MODULE_3__.getAssetUrl)("delete.svg");
  1220. deleteBtnElem.appendChild(imgElem);
  1221. }
  1222. //#SECTION append elements to DOM
  1223. queueBtnsCont.appendChild(lyricsBtnElem);
  1224. queueBtnsCont.appendChild(deleteBtnElem);
  1225. songInfo.appendChild(queueBtnsCont);
  1226. queueItem.classList.add("bytm-has-queue-btns");
  1227. return true;
  1228. });
  1229. }
  1230. //#MARKER better clickable stuff
  1231. // TODO: add to thumbnails in "songs" list on channel pages (/channel/$id)
  1232. // TODO: add to thumbnails in playlists (/playlist?list=$id)
  1233. /** Adds anchors around elements and tweaks existing ones so songs are easier to open in a new tab */
  1234. function addAnchorImprovements() {
  1235. //#SECTION carousel shelves
  1236. try {
  1237. // home page
  1238. /** Only adds anchor improvements for carousel shelves that contain the regular list-item-renderer, not the two-row-item-renderer */
  1239. const condCarouselImprovements = (el) => {
  1240. const listItemRenderer = el.querySelector("ytmusic-responsive-list-item-renderer");
  1241. if (listItemRenderer) {
  1242. const itemsElem = el.querySelector("ul#items");
  1243. if (itemsElem) {
  1244. const improvedElems = improveCarouselAnchors(itemsElem);
  1245. improvedElems > 0 && (0,_utils__WEBPACK_IMPORTED_MODULE_3__.log)(`Added anchor improvements to ${improvedElems} carousel shelf ${(0,_sv443_network_userutils__WEBPACK_IMPORTED_MODULE_0__.autoPlural)("item", improvedElems)}`);
  1246. }
  1247. }
  1248. };
  1249. // initial three shelves aren't included in the event fire
  1250. (0,_sv443_network_userutils__WEBPACK_IMPORTED_MODULE_0__.onSelector)("ytmusic-carousel-shelf-renderer", {
  1251. listener: () => {
  1252. const carouselShelves = document.body.querySelectorAll("ytmusic-carousel-shelf-renderer");
  1253. carouselShelves.forEach(condCarouselImprovements);
  1254. },
  1255. });
  1256. // every shelf that's loaded by scrolling:
  1257. _events__WEBPACK_IMPORTED_MODULE_4__.siteEvents.on("carouselShelvesChanged", (evt) => {
  1258. const { addedNodes, removedNodes } = (0,_events__WEBPACK_IMPORTED_MODULE_4__.getEvtData)(evt);
  1259. void removedNodes;
  1260. if (addedNodes.length > 0)
  1261. addedNodes.forEach(condCarouselImprovements);
  1262. });
  1263. // related tab in /watch
  1264. // TODO: items are lazy-loaded so this needs to be done differently
  1265. // maybe the onSelectorExists feature can be expanded to conditionally support continuous checking & querySelectorAll
  1266. const relatedTabAnchorImprovements = (tabElem) => {
  1267. const relatedCarouselShelves = tabElem === null || tabElem === void 0 ? void 0 : tabElem.querySelectorAll("ytmusic-carousel-shelf-renderer");
  1268. if (relatedCarouselShelves)
  1269. relatedCarouselShelves.forEach(condCarouselImprovements);
  1270. };
  1271. const relatedTabContentsSelector = "ytmusic-section-list-renderer[page-type=\"MUSIC_PAGE_TYPE_TRACK_RELATED\"] #contents";
  1272. (0,_sv443_network_userutils__WEBPACK_IMPORTED_MODULE_0__.onSelector)("ytmusic-tab-renderer[page-type=\"MUSIC_PAGE_TYPE_TRACK_RELATED\"]", {
  1273. listener: (relatedTabContainer) => {
  1274. const relatedTabObserver = new MutationObserver(([{ addedNodes, removedNodes }]) => {
  1275. if (addedNodes.length > 0 || removedNodes.length > 0)
  1276. relatedTabAnchorImprovements(document.querySelector(relatedTabContentsSelector));
  1277. });
  1278. relatedTabObserver.observe(relatedTabContainer, {
  1279. childList: true,
  1280. });
  1281. },
  1282. });
  1283. (0,_sv443_network_userutils__WEBPACK_IMPORTED_MODULE_0__.onSelector)(relatedTabContentsSelector, {
  1284. listener: (relatedTabContents) => {
  1285. relatedTabAnchorImprovements(relatedTabContents);
  1286. },
  1287. });
  1288. }
  1289. catch (err) {
  1290. (0,_utils__WEBPACK_IMPORTED_MODULE_3__.error)("Couldn't improve carousel shelf anchors due to an error:", err);
  1291. }
  1292. //#SECTION sidebar
  1293. try {
  1294. const addSidebarAnchors = (sidebarCont) => {
  1295. const items = sidebarCont.parentNode.querySelectorAll("ytmusic-guide-entry-renderer tp-yt-paper-item");
  1296. improveSidebarAnchors(items);
  1297. return items.length;
  1298. };
  1299. (0,_sv443_network_userutils__WEBPACK_IMPORTED_MODULE_0__.onSelector)("ytmusic-app-layout tp-yt-app-drawer #contentContainer #guide-content #items ytmusic-guide-entry-renderer", {
  1300. listener: (sidebarCont) => {
  1301. const itemsAmt = addSidebarAnchors(sidebarCont);
  1302. (0,_utils__WEBPACK_IMPORTED_MODULE_3__.log)(`Added anchors around ${itemsAmt} sidebar ${(0,_sv443_network_userutils__WEBPACK_IMPORTED_MODULE_0__.autoPlural)("item", itemsAmt)}`);
  1303. },
  1304. });
  1305. (0,_sv443_network_userutils__WEBPACK_IMPORTED_MODULE_0__.onSelector)("ytmusic-app-layout #mini-guide ytmusic-guide-renderer ytmusic-guide-section-renderer #items ytmusic-guide-entry-renderer", {
  1306. listener: (miniSidebarCont) => {
  1307. const itemsAmt = addSidebarAnchors(miniSidebarCont);
  1308. (0,_utils__WEBPACK_IMPORTED_MODULE_3__.log)(`Added anchors around ${itemsAmt} mini sidebar ${(0,_sv443_network_userutils__WEBPACK_IMPORTED_MODULE_0__.autoPlural)("item", itemsAmt)}`);
  1309. },
  1310. });
  1311. }
  1312. catch (err) {
  1313. (0,_utils__WEBPACK_IMPORTED_MODULE_3__.error)("Couldn't add anchors to sidebar items due to an error:", err);
  1314. }
  1315. }
  1316. const sidebarPaths = [
  1317. "/",
  1318. "/explore",
  1319. "/library",
  1320. ];
  1321. /**
  1322. * Adds anchors to the sidebar items so they can be opened in a new tab
  1323. * @param sidebarItem
  1324. */
  1325. function improveSidebarAnchors(sidebarItems) {
  1326. sidebarItems.forEach((item, i) => {
  1327. var _a;
  1328. const anchorElem = document.createElement("a");
  1329. anchorElem.classList.add("bytm-anchor", "bytm-no-select");
  1330. anchorElem.role = "button";
  1331. anchorElem.target = "_self";
  1332. anchorElem.href = (_a = sidebarPaths[i]) !== null && _a !== void 0 ? _a : "#";
  1333. anchorElem.title = "Middle click to open in a new tab";
  1334. anchorElem.addEventListener("click", (e) => {
  1335. e.preventDefault();
  1336. });
  1337. (0,_sv443_network_userutils__WEBPACK_IMPORTED_MODULE_0__.addParent)(item, anchorElem);
  1338. });
  1339. }
  1340. /**
  1341. * Actually adds the anchor improvements to carousel shelf items
  1342. * @param itemsElement The container with the selector `ul#items` inside of each `ytmusic-carousel`
  1343. */
  1344. function improveCarouselAnchors(itemsElement) {
  1345. if (itemsElement.classList.contains("bytm-anchors-improved"))
  1346. return 0;
  1347. let improvedElems = 0;
  1348. try {
  1349. const allListItems = itemsElement.querySelectorAll("ytmusic-responsive-list-item-renderer");
  1350. for (const listItem of allListItems) {
  1351. const thumbnailElem = listItem.querySelector(".left-items");
  1352. const titleElem = listItem.querySelector(".title-column yt-formatted-string.title a");
  1353. if (!thumbnailElem || !titleElem) {
  1354. (0,_utils__WEBPACK_IMPORTED_MODULE_3__.error)("Couldn't add carousel shelf anchor improvements because either the thumbnail or title element couldn't be found");
  1355. continue;
  1356. }
  1357. const thumbnailAnchor = document.createElement("a");
  1358. thumbnailAnchor.className = "bytm-carousel-shelf-anchor bytm-anchor";
  1359. thumbnailAnchor.href = titleElem.href;
  1360. thumbnailAnchor.target = "_self";
  1361. thumbnailAnchor.role = "button";
  1362. thumbnailAnchor.addEventListener("click", (e) => {
  1363. e.preventDefault();
  1364. });
  1365. (0,_sv443_network_userutils__WEBPACK_IMPORTED_MODULE_0__.addParent)(thumbnailElem, thumbnailAnchor);
  1366. improvedElems++;
  1367. }
  1368. }
  1369. catch (err) {
  1370. (0,_utils__WEBPACK_IMPORTED_MODULE_3__.error)("Couldn't add anchor improvements due to error:", err);
  1371. }
  1372. finally {
  1373. itemsElement.classList.add("bytm-anchors-improved");
  1374. }
  1375. return improvedElems;
  1376. }
  1377. /***/ }),
  1378. /***/ "./src/features/lyrics.ts":
  1379. /*!********************************!*\
  1380. !*** ./src/features/lyrics.ts ***!
  1381. \********************************/
  1382. /***/ (function(__unused_webpack_module, __webpack_exports__, __webpack_require__) {
  1383. __webpack_require__.r(__webpack_exports__);
  1384. /* harmony export */ __webpack_require__.d(__webpack_exports__, {
  1385. /* harmony export */ addLyricsCacheEntry: function() { return /* binding */ addLyricsCacheEntry; },
  1386. /* harmony export */ addMediaCtrlLyricsBtn: function() { return /* binding */ addMediaCtrlLyricsBtn; },
  1387. /* harmony export */ createLyricsBtn: function() { return /* binding */ createLyricsBtn; },
  1388. /* harmony export */ geniUrlBase: function() { return /* binding */ geniUrlBase; },
  1389. /* harmony export */ getCurrentLyricsUrl: function() { return /* binding */ getCurrentLyricsUrl; },
  1390. /* harmony export */ getGeniusUrl: function() { return /* binding */ getGeniusUrl; },
  1391. /* harmony export */ getLyricsCacheEntry: function() { return /* binding */ getLyricsCacheEntry; },
  1392. /* harmony export */ sanitizeArtists: function() { return /* binding */ sanitizeArtists; },
  1393. /* harmony export */ sanitizeSong: function() { return /* binding */ sanitizeSong; }
  1394. /* harmony export */ });
  1395. /* harmony import */ var _sv443_network_userutils__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @sv443-network/userutils */ "./node_modules/@sv443-network/userutils/dist/index.mjs");
  1396. /* harmony import */ var _utils__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../utils */ "./src/utils.ts");
  1397. var __awaiter = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) {
  1398. function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
  1399. return new (P || (P = Promise))(function (resolve, reject) {
  1400. function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
  1401. function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
  1402. function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
  1403. step((generator = generator.apply(thisArg, _arguments || [])).next());
  1404. });
  1405. };
  1406. var __asyncValues = (undefined && undefined.__asyncValues) || function (o) {
  1407. if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined.");
  1408. var m = o[Symbol.asyncIterator], i;
  1409. 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);
  1410. 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); }); }; }
  1411. function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); }
  1412. };
  1413. /** Base URL of geniURL */
  1414. const geniUrlBase = "https://api.sv443.net/geniurl";
  1415. /** GeniURL endpoint that gives song metadata when provided with a `?q` or `?artist` and `?song` parameter - [more info](https://api.sv443.net/geniurl) */
  1416. const geniURLSearchTopUrl = `${geniUrlBase}/search/top`;
  1417. /**
  1418. * The threshold to pass to geniURL's fuzzy filtering.
  1419. * 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.
  1420. * Set to undefined to use the default.
  1421. */
  1422. const threshold = 0.55;
  1423. /** Ratelimit budget timeframe in seconds - should reflect what's in geniURL's docs */
  1424. const geniUrlRatelimitTimeframe = 30;
  1425. const thresholdParam = threshold ? `&threshold=${(0,_sv443_network_userutils__WEBPACK_IMPORTED_MODULE_0__.clamp)(threshold, 0, 1)}` : "";
  1426. //#MARKER cache
  1427. /** Cache with key format `ARTIST - SONG` (sanitized) and lyrics URLs as values. Used to prevent extraneous requests to geniURL. */
  1428. const lyricsUrlCache = new Map();
  1429. /** How many cache entries can exist at a time - this is used to cap memory usage */
  1430. const maxLyricsCacheSize = 100;
  1431. /**
  1432. * Returns the lyrics URL from the passed un-/sanitized artist and song name, or undefined if the entry doesn't exist yet.
  1433. * **The passed parameters need to be sanitized first!**
  1434. */
  1435. function getLyricsCacheEntry(artists, song) {
  1436. return lyricsUrlCache.get(`${artists} - ${song}`);
  1437. }
  1438. /** Adds the provided entry into the lyrics URL cache */
  1439. function addLyricsCacheEntry(artists, song, lyricsUrl) {
  1440. lyricsUrlCache.set(`${sanitizeArtists(artists)} - ${sanitizeSong(song)}`, lyricsUrl);
  1441. // delete oldest entry if cache gets too big
  1442. if (lyricsUrlCache.size > maxLyricsCacheSize)
  1443. lyricsUrlCache.delete([...lyricsUrlCache.keys()].at(-1));
  1444. }
  1445. //#MARKER media control bar
  1446. let mcCurrentSongTitle = "";
  1447. /** Adds a lyrics button to the media controls bar */
  1448. function addMediaCtrlLyricsBtn() {
  1449. (0,_sv443_network_userutils__WEBPACK_IMPORTED_MODULE_0__.onSelector)(".middle-controls-buttons ytmusic-like-button-renderer#like-button-renderer", { listener: addActualMediaCtrlLyricsBtn });
  1450. }
  1451. // TODO: add error.svg if the request fails
  1452. /** Actually adds the lyrics button after the like button renderer has been verified to exist */
  1453. function addActualMediaCtrlLyricsBtn(likeContainer) {
  1454. const songTitleElem = document.querySelector(".content-info-wrapper > yt-formatted-string");
  1455. // run parallel without awaiting so the MutationObserver below can observe the title element in time
  1456. (() => __awaiter(this, void 0, void 0, function* () {
  1457. const gUrl = yield getCurrentLyricsUrl();
  1458. const linkElem = createLyricsBtn(gUrl !== null && gUrl !== void 0 ? gUrl : undefined);
  1459. linkElem.id = "betterytm-lyrics-button";
  1460. (0,_utils__WEBPACK_IMPORTED_MODULE_1__.log)("Inserted lyrics button into media controls bar");
  1461. (0,_sv443_network_userutils__WEBPACK_IMPORTED_MODULE_0__.insertAfter)(likeContainer, linkElem);
  1462. }))();
  1463. mcCurrentSongTitle = songTitleElem.title;
  1464. const onMutation = (mutations) => { var _a, mutations_1, mutations_1_1; return __awaiter(this, void 0, void 0, function* () {
  1465. var _b, e_1, _c, _d;
  1466. try {
  1467. for (_a = true, mutations_1 = __asyncValues(mutations); mutations_1_1 = yield mutations_1.next(), _b = mutations_1_1.done, !_b;) {
  1468. _d = mutations_1_1.value;
  1469. _a = false;
  1470. try {
  1471. const mut = _d;
  1472. const newTitle = mut.target.title;
  1473. if (newTitle !== mcCurrentSongTitle && newTitle.length > 0) {
  1474. const lyricsBtn = document.querySelector("#betterytm-lyrics-button");
  1475. if (!lyricsBtn)
  1476. return;
  1477. (0,_utils__WEBPACK_IMPORTED_MODULE_1__.info)(`Song title changed from '${mcCurrentSongTitle}' to '${newTitle}'`);
  1478. lyricsBtn.style.cursor = "wait";
  1479. lyricsBtn.style.pointerEvents = "none";
  1480. const imgElem = lyricsBtn.querySelector("img");
  1481. imgElem.src = (0,_utils__WEBPACK_IMPORTED_MODULE_1__.getAssetUrl)("spinner.svg");
  1482. imgElem.classList.add("bytm-spinner");
  1483. mcCurrentSongTitle = newTitle;
  1484. const url = yield getCurrentLyricsUrl(); // can take a second or two
  1485. imgElem.src = (0,_utils__WEBPACK_IMPORTED_MODULE_1__.getAssetUrl)("lyrics.svg");
  1486. imgElem.classList.remove("bytm-spinner");
  1487. if (!url)
  1488. continue;
  1489. lyricsBtn.href = url;
  1490. lyricsBtn.title = "Open the current song's lyrics in a new tab";
  1491. lyricsBtn.style.cursor = "pointer";
  1492. lyricsBtn.style.visibility = "initial";
  1493. lyricsBtn.style.display = "inline-flex";
  1494. lyricsBtn.style.pointerEvents = "initial";
  1495. }
  1496. }
  1497. finally {
  1498. _a = true;
  1499. }
  1500. }
  1501. }
  1502. catch (e_1_1) { e_1 = { error: e_1_1 }; }
  1503. finally {
  1504. try {
  1505. if (!_a && !_b && (_c = mutations_1.return)) yield _c.call(mutations_1);
  1506. }
  1507. finally { if (e_1) throw e_1.error; }
  1508. }
  1509. }); };
  1510. // 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
  1511. const obs = new MutationObserver(onMutation);
  1512. obs.observe(songTitleElem, { attributes: true, attributeFilter: ["title"] });
  1513. }
  1514. //#MARKER utils
  1515. /** Removes everything in parentheses from the passed song name */
  1516. function sanitizeSong(songName) {
  1517. const parensRegex = /\(.+\)/gmi;
  1518. const squareParensRegex = /\[.+\]/gmi;
  1519. // trim right after the song name:
  1520. const sanitized = songName
  1521. .replace(parensRegex, "")
  1522. .replace(squareParensRegex, "");
  1523. return sanitized.trim();
  1524. }
  1525. /** Removes the secondary artist (if it exists) from the passed artists string */
  1526. function sanitizeArtists(artists) {
  1527. artists = artists.split(/\s*\u2022\s*/gmiu)[0]; // split at &bull; [•] character
  1528. if (artists.match(/&/))
  1529. artists = artists.split(/\s*&\s*/gm)[0];
  1530. if (artists.match(/,/))
  1531. artists = artists.split(/,\s*/gm)[0];
  1532. return artists.trim();
  1533. }
  1534. /** Returns the lyrics URL from genius for the currently selected song */
  1535. function getCurrentLyricsUrl() {
  1536. var _a;
  1537. return __awaiter(this, void 0, void 0, function* () {
  1538. try {
  1539. // In videos the video title contains both artist and song title, in "regular" YTM songs, the video title only contains the song title
  1540. const isVideo = typeof ((_a = document.querySelector("ytmusic-player")) === null || _a === void 0 ? void 0 : _a.getAttribute("video-mode_")) === "string";
  1541. const songTitleElem = document.querySelector(".content-info-wrapper > yt-formatted-string");
  1542. const songMetaElem = document.querySelector("span.subtitle > yt-formatted-string:first-child");
  1543. if (!songTitleElem || !songMetaElem || !songTitleElem.title)
  1544. return undefined;
  1545. const songNameRaw = songTitleElem.title;
  1546. const songName = sanitizeSong(songNameRaw);
  1547. const artistName = sanitizeArtists(songMetaElem.title);
  1548. /** Use when the current song is not a "real YTM song" with a static background, but rather a music video */
  1549. const getGeniusUrlVideo = () => __awaiter(this, void 0, void 0, function* () {
  1550. if (!songName.includes("-")) // for some fucking reason some music videos have YTM-like song title and artist separation, some don't
  1551. return yield getGeniusUrl(artistName, songName);
  1552. const [artist, ...rest] = songName.split("-").map(v => v.trim());
  1553. return yield getGeniusUrl(artist, rest.join(" "));
  1554. });
  1555. // TODO: artist might need further splitting before comma or ampersand
  1556. const url = isVideo ? yield getGeniusUrlVideo() : yield getGeniusUrl(artistName, songName);
  1557. return url;
  1558. }
  1559. catch (err) {
  1560. (0,_utils__WEBPACK_IMPORTED_MODULE_1__.error)("Couldn't resolve lyrics URL:", err);
  1561. return undefined;
  1562. }
  1563. });
  1564. }
  1565. /** Fetches the actual lyrics URL from geniURL - **the passed parameters need to be sanitized first!** */
  1566. function getGeniusUrl(artist, song) {
  1567. var _a, _b, _c;
  1568. return __awaiter(this, void 0, void 0, function* () {
  1569. try {
  1570. const cacheEntry = getLyricsCacheEntry(artist, song);
  1571. if (cacheEntry) {
  1572. (0,_utils__WEBPACK_IMPORTED_MODULE_1__.info)(`Found lyrics URL in cache: ${cacheEntry}`);
  1573. return cacheEntry;
  1574. }
  1575. const startTs = Date.now();
  1576. const fetchUrl = `${geniURLSearchTopUrl}?artist=${encodeURIComponent(artist)}&song=${encodeURIComponent(song)}${thresholdParam}`;
  1577. (0,_utils__WEBPACK_IMPORTED_MODULE_1__.log)(`Requesting URL from geniURL at '${fetchUrl}'`);
  1578. const fetchRes = yield (0,_sv443_network_userutils__WEBPACK_IMPORTED_MODULE_0__.fetchAdvanced)(fetchUrl);
  1579. if (fetchRes.status === 429) {
  1580. 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.`);
  1581. return undefined;
  1582. }
  1583. else if (fetchRes.status < 200 || fetchRes.status >= 300) {
  1584. (0,_utils__WEBPACK_IMPORTED_MODULE_1__.error)(`Couldn't fetch lyrics URL from geniURL - status: ${fetchRes.status} - response: ${(_c = (_b = (yield fetchRes.json()).message) !== null && _b !== void 0 ? _b : yield fetchRes.text()) !== null && _c !== void 0 ? _c : "(none)"}`);
  1585. return undefined;
  1586. }
  1587. const result = yield fetchRes.json();
  1588. if (typeof result === "object" && result.error) {
  1589. (0,_utils__WEBPACK_IMPORTED_MODULE_1__.error)("Couldn't fetch lyrics URL:", result.message);
  1590. return undefined;
  1591. }
  1592. const url = result.url;
  1593. (0,_utils__WEBPACK_IMPORTED_MODULE_1__.info)(`Found lyrics URL (after ${Date.now() - startTs}ms): ${url}`);
  1594. addLyricsCacheEntry(artist, song, url);
  1595. return url;
  1596. }
  1597. catch (err) {
  1598. (0,_utils__WEBPACK_IMPORTED_MODULE_1__.error)("Couldn't get lyrics URL due to error:", err);
  1599. return undefined;
  1600. }
  1601. });
  1602. }
  1603. /** Creates the base lyrics button element */
  1604. function createLyricsBtn(geniusUrl, hideIfLoading = true) {
  1605. const linkElem = document.createElement("a");
  1606. linkElem.className = "ytmusic-player-bar bytm-generic-btn";
  1607. linkElem.title = geniusUrl ? "Click to open this song's lyrics in a new tab" : "Loading lyrics URL...";
  1608. if (geniusUrl)
  1609. linkElem.href = geniusUrl;
  1610. linkElem.role = "button";
  1611. linkElem.target = "_blank";
  1612. linkElem.rel = "noopener noreferrer";
  1613. linkElem.style.visibility = hideIfLoading && geniusUrl ? "initial" : "hidden";
  1614. linkElem.style.display = hideIfLoading && geniusUrl ? "inline-flex" : "none";
  1615. const imgElem = document.createElement("img");
  1616. imgElem.className = "bytm-generic-btn-img";
  1617. imgElem.src = (0,_utils__WEBPACK_IMPORTED_MODULE_1__.getAssetUrl)("lyrics.svg");
  1618. linkElem.appendChild(imgElem);
  1619. return linkElem;
  1620. }
  1621. /***/ }),
  1622. /***/ "./src/features/menu/menu.ts":
  1623. /*!***********************************!*\
  1624. !*** ./src/features/menu/menu.ts ***!
  1625. \***********************************/
  1626. /***/ (function(__unused_webpack_module, __webpack_exports__, __webpack_require__) {
  1627. __webpack_require__.r(__webpack_exports__);
  1628. /* harmony export */ __webpack_require__.d(__webpack_exports__, {
  1629. /* harmony export */ closeMenu: function() { return /* binding */ closeMenu; },
  1630. /* harmony export */ initMenu: function() { return /* binding */ initMenu; },
  1631. /* harmony export */ openMenu: function() { return /* binding */ openMenu; },
  1632. /* harmony export */ setActiveTab: function() { return /* binding */ setActiveTab; }
  1633. /* harmony export */ });
  1634. /* harmony import */ var _changelog_md__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../../../changelog.md */ "./changelog.md");
  1635. /* harmony import */ var _menu_html__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./menu.html */ "./src/features/menu/menu.html");
  1636. /* harmony import */ var _menu_css__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./menu.css */ "./src/features/menu/menu.css");
  1637. // REQUIREMENTS:
  1638. // - modal using the <dialog> element
  1639. // - sections with headers
  1640. // - support for "custom widgets"
  1641. // - debounce or save on button press to store new configuration
  1642. // - much better scaling including no vw and vh units
  1643. //#MARKER menu
  1644. /**
  1645. * These are the base selector values for the menu tabs
  1646. * Header selector format: `#${baseValue}-header`
  1647. * Content selector format: `#${baseValue}-content`
  1648. */
  1649. const tabsSelectors = {
  1650. options: "bytm-menu-tab-options",
  1651. info: "bytm-menu-tab-info",
  1652. changelog: "bytm-menu-tab-changelog",
  1653. };
  1654. /** Called from init(), before DOMContentLoaded is fired */
  1655. function initMenu() {
  1656. document.addEventListener("DOMContentLoaded", () => {
  1657. // create menu container
  1658. const menuContainer = document.createElement("div");
  1659. menuContainer.id = "bytm-menu-container";
  1660. // add menu html
  1661. menuContainer.innerHTML = _menu_html__WEBPACK_IMPORTED_MODULE_1__["default"];
  1662. document.body.appendChild(menuContainer);
  1663. initMenuContents();
  1664. });
  1665. }
  1666. function initMenuContents() {
  1667. var _a;
  1668. // hook events
  1669. for (const tab in tabsSelectors) {
  1670. const selector = tabsSelectors[tab];
  1671. (_a = document.querySelector(`#${selector}-header`)) === null || _a === void 0 ? void 0 : _a.addEventListener("click", () => {
  1672. setActiveTab(tab);
  1673. });
  1674. }
  1675. // init tab contents
  1676. initOptionsContent();
  1677. initInfoContent();
  1678. initChangelogContent();
  1679. }
  1680. /** Opens the specified tab */
  1681. function setActiveTab(tab) {
  1682. const tabs = Object.assign({}, tabsSelectors);
  1683. delete tabs[tab];
  1684. // disable all but new active tab
  1685. for (const [, val] of Object.entries(tabs)) {
  1686. document.querySelector(`#${val}-header`).dataset.active = "false";
  1687. document.querySelector(`#${val}-content`).dataset.active = "false";
  1688. }
  1689. // enable new active tab
  1690. document.querySelector(`#${tabsSelectors[tab]}-header`).dataset.active = "true";
  1691. document.querySelector(`#${tabsSelectors[tab]}-content`).dataset.active = "true";
  1692. }
  1693. /** Opens the modal menu dialog */
  1694. function openMenu() {
  1695. var _a;
  1696. (_a = document.querySelector("#bytm-menu-dialog")) === null || _a === void 0 ? void 0 : _a.showModal();
  1697. }
  1698. /** Closes the modal menu dialog */
  1699. function closeMenu() {
  1700. var _a;
  1701. (_a = document.querySelector("#bytm-menu-dialog")) === null || _a === void 0 ? void 0 : _a.close();
  1702. }
  1703. //#MARKER menu tab contents
  1704. function initOptionsContent() {
  1705. const tab = document.querySelector("#bytm-menu-tab-options-content");
  1706. void tab;
  1707. }
  1708. function initInfoContent() {
  1709. const tab = document.querySelector("#bytm-menu-tab-info-content");
  1710. void tab;
  1711. }
  1712. function initChangelogContent() {
  1713. const tab = document.querySelector("#bytm-menu-tab-changelog-content");
  1714. tab.innerHTML = _changelog_md__WEBPACK_IMPORTED_MODULE_0__["default"];
  1715. }
  1716. /***/ }),
  1717. /***/ "./src/features/menu/menu_old.ts":
  1718. /*!***************************************!*\
  1719. !*** ./src/features/menu/menu_old.ts ***!
  1720. \***************************************/
  1721. /***/ (function(__unused_webpack_module, __webpack_exports__, __webpack_require__) {
  1722. __webpack_require__.r(__webpack_exports__);
  1723. /* harmony export */ __webpack_require__.d(__webpack_exports__, {
  1724. /* harmony export */ addMenu: function() { return /* binding */ addMenu; },
  1725. /* harmony export */ closeMenu: function() { return /* binding */ closeMenu; },
  1726. /* harmony export */ openMenu: function() { return /* binding */ openMenu; }
  1727. /* harmony export */ });
  1728. /* harmony import */ var _sv443_network_userutils__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @sv443-network/userutils */ "./node_modules/@sv443-network/userutils/dist/index.mjs");
  1729. /* harmony import */ var _config__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../../config */ "./src/config.ts");
  1730. /* harmony import */ var _constants__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../../constants */ "./src/constants.ts");
  1731. /* harmony import */ var _index__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../index */ "./src/features/index.ts");
  1732. /* harmony import */ var _utils__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../../utils */ "./src/utils.ts");
  1733. /* harmony import */ var _menu_old_css__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./menu_old.css */ "./src/features/menu/menu_old.css");
  1734. var __awaiter = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) {
  1735. function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
  1736. return new (P || (P = Promise))(function (resolve, reject) {
  1737. function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
  1738. function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
  1739. function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
  1740. step((generator = generator.apply(thisArg, _arguments || [])).next());
  1741. });
  1742. };
  1743. //#MARKER create menu elements
  1744. let isMenuOpen = false;
  1745. /**
  1746. * Adds an element to open the BetterYTM menu
  1747. * @deprecated to be replaced with new menu - see https://github.com/Sv443/BetterYTM/issues/23
  1748. */
  1749. function addMenu() {
  1750. var _a, _b;
  1751. return __awaiter(this, void 0, void 0, function* () {
  1752. //#SECTION backdrop & menu container
  1753. const backgroundElem = document.createElement("div");
  1754. backgroundElem.id = "betterytm-menu-bg";
  1755. backgroundElem.title = "Click here to close the menu";
  1756. backgroundElem.style.visibility = "hidden";
  1757. backgroundElem.style.display = "none";
  1758. backgroundElem.addEventListener("click", (e) => {
  1759. var _a;
  1760. if (isMenuOpen && ((_a = e.target) === null || _a === void 0 ? void 0 : _a.id) === "betterytm-menu-bg")
  1761. closeMenu(e);
  1762. });
  1763. document.body.addEventListener("keydown", (e) => {
  1764. if (isMenuOpen && e.key === "Escape")
  1765. closeMenu(e);
  1766. });
  1767. const menuContainer = document.createElement("div");
  1768. menuContainer.title = "";
  1769. menuContainer.id = "betterytm-menu";
  1770. menuContainer.style.borderRadius = "15px";
  1771. menuContainer.style.display = "flex";
  1772. menuContainer.style.flexDirection = "column";
  1773. menuContainer.style.justifyContent = "space-between";
  1774. //#SECTION title bar
  1775. const titleCont = document.createElement("div");
  1776. titleCont.style.padding = "8px 20px 15px 20px";
  1777. titleCont.style.display = "flex";
  1778. titleCont.style.justifyContent = "space-between";
  1779. titleCont.id = "betterytm-menu-titlecont";
  1780. const titleElem = document.createElement("h2");
  1781. titleElem.id = "betterytm-menu-title";
  1782. titleElem.classList.add("bytm-no-select");
  1783. titleElem.innerText = `${_constants__WEBPACK_IMPORTED_MODULE_2__.scriptInfo.name} - Configuration`;
  1784. const linksCont = document.createElement("div");
  1785. linksCont.id = "betterytm-menu-linkscont";
  1786. const addLink = (imgSrc, href, title) => {
  1787. const anchorElem = document.createElement("a");
  1788. anchorElem.className = "betterytm-menu-link";
  1789. anchorElem.rel = "noopener noreferrer";
  1790. anchorElem.target = "_blank";
  1791. anchorElem.href = href;
  1792. anchorElem.title = title;
  1793. anchorElem.style.marginLeft = "10px";
  1794. const imgElem = document.createElement("img");
  1795. imgElem.className = "betterytm-menu-img bytm-no-select";
  1796. imgElem.src = imgSrc;
  1797. imgElem.style.width = "32px";
  1798. imgElem.style.height = "32px";
  1799. anchorElem.appendChild(imgElem);
  1800. linksCont.appendChild(anchorElem);
  1801. };
  1802. addLink((0,_utils__WEBPACK_IMPORTED_MODULE_4__.getAssetUrl)("external/github.png"), _constants__WEBPACK_IMPORTED_MODULE_2__.scriptInfo.namespace, `${_constants__WEBPACK_IMPORTED_MODULE_2__.scriptInfo.name} on GitHub`);
  1803. addLink((0,_utils__WEBPACK_IMPORTED_MODULE_4__.getAssetUrl)("external/greasyfork.png"), "https://greasyfork.org/xyz", `${_constants__WEBPACK_IMPORTED_MODULE_2__.scriptInfo.name} on GreasyFork`);
  1804. const closeElem = document.createElement("img");
  1805. closeElem.id = "betterytm-menu-close";
  1806. closeElem.src = (0,_utils__WEBPACK_IMPORTED_MODULE_4__.getAssetUrl)("close.png");
  1807. closeElem.title = "Click to close the menu";
  1808. closeElem.style.marginLeft = "50px";
  1809. closeElem.style.width = "32px";
  1810. closeElem.style.height = "32px";
  1811. closeElem.addEventListener("click", closeMenu);
  1812. linksCont.appendChild(closeElem);
  1813. titleCont.appendChild(titleElem);
  1814. titleCont.appendChild(linksCont);
  1815. //#SECTION feature list
  1816. const featuresCont = document.createElement("div");
  1817. featuresCont.id = "betterytm-menu-opts";
  1818. featuresCont.style.display = "flex";
  1819. featuresCont.style.flexDirection = "column";
  1820. featuresCont.style.overflowY = "auto";
  1821. /** Gets called whenever the feature config is changed */
  1822. const confChanged = (0,_sv443_network_userutils__WEBPACK_IMPORTED_MODULE_0__.debounce)((key, initialVal, newVal) => __awaiter(this, void 0, void 0, function* () {
  1823. const fmt = (val) => typeof val === "object" ? JSON.stringify(val) : String(val);
  1824. (0,_utils__WEBPACK_IMPORTED_MODULE_4__.info)(`Feature config changed, key '${key}' from value '${fmt(initialVal)}' to '${fmt(newVal)}'`);
  1825. const featConf = Object.assign({}, yield (0,_config__WEBPACK_IMPORTED_MODULE_1__.getFeatures)());
  1826. featConf[key] = newVal;
  1827. yield (0,_config__WEBPACK_IMPORTED_MODULE_1__.saveFeatureConf)(featConf);
  1828. (0,_utils__WEBPACK_IMPORTED_MODULE_4__.log)("Saved feature config changes:\n", yield GM.getValue("betterytm-config"));
  1829. }));
  1830. const features = yield (0,_config__WEBPACK_IMPORTED_MODULE_1__.getFeatures)();
  1831. for (const key in features) {
  1832. const ftInfo = _index__WEBPACK_IMPORTED_MODULE_3__.featInfo[key];
  1833. // @ts-ignore
  1834. if (!ftInfo || ftInfo.visible === false)
  1835. continue;
  1836. const { desc, type, default: ftDefault } = ftInfo;
  1837. // @ts-ignore
  1838. const step = (_a = ftInfo === null || ftInfo === void 0 ? void 0 : ftInfo.step) !== null && _a !== void 0 ? _a : undefined;
  1839. const val = features[key];
  1840. const initialVal = (_b = val !== null && val !== void 0 ? val : ftDefault) !== null && _b !== void 0 ? _b : undefined;
  1841. const ftConfElem = document.createElement("div");
  1842. ftConfElem.id = `betterytm-ftconf-${key}`;
  1843. ftConfElem.style.display = "flex";
  1844. ftConfElem.style.flexDirection = "row";
  1845. ftConfElem.style.justifyContent = "space-between";
  1846. ftConfElem.style.padding = "8px 20px";
  1847. {
  1848. const textElem = document.createElement("span");
  1849. textElem.style.display = "inline-block";
  1850. textElem.style.fontSize = "15px";
  1851. textElem.innerText = desc;
  1852. ftConfElem.appendChild(textElem);
  1853. }
  1854. {
  1855. let inputType = "text";
  1856. switch (type) {
  1857. case "toggle":
  1858. inputType = "checkbox";
  1859. break;
  1860. case "slider":
  1861. inputType = "range";
  1862. break;
  1863. case "number":
  1864. inputType = "number";
  1865. break;
  1866. }
  1867. const inputElemId = `betterytm-ftconf-${key}-input`;
  1868. const ctrlElem = document.createElement("span");
  1869. ctrlElem.style.display = "inline-block";
  1870. ctrlElem.style.whiteSpace = "nowrap";
  1871. const inputElem = document.createElement("input");
  1872. inputElem.id = inputElemId;
  1873. inputElem.type = inputType;
  1874. if (type === "toggle")
  1875. inputElem.style.marginLeft = "5px";
  1876. if (typeof initialVal !== "undefined")
  1877. inputElem.value = String(initialVal);
  1878. if (type === "number" && step)
  1879. inputElem.step = step;
  1880. // @ts-ignore
  1881. if (ftInfo.min && ftInfo.max) {
  1882. // @ts-ignore
  1883. inputElem.min = ftInfo.min;
  1884. // @ts-ignore
  1885. inputElem.max = ftInfo.max;
  1886. }
  1887. if (type === "toggle" && typeof initialVal !== "undefined")
  1888. inputElem.checked = Boolean(initialVal);
  1889. // @ts-ignore
  1890. const unitTxt = typeof ftInfo.unit === "string" ? " " + ftInfo.unit : "";
  1891. const fmtVal = (v) => String(v).trim();
  1892. const toggleLabelText = (toggled) => toggled ? "On" : "Off";
  1893. let labelElem;
  1894. if (type === "slider") {
  1895. labelElem = document.createElement("label");
  1896. labelElem.classList.add("betterytm-ftconf-label");
  1897. labelElem.style.marginRight = "20px";
  1898. labelElem.style.fontSize = "16px";
  1899. labelElem.htmlFor = inputElemId;
  1900. labelElem.innerText = fmtVal(initialVal) + unitTxt;
  1901. inputElem.addEventListener("input", () => {
  1902. if (labelElem)
  1903. labelElem.innerText = fmtVal(parseInt(inputElem.value)) + unitTxt;
  1904. });
  1905. }
  1906. else if (type === "toggle") {
  1907. labelElem = document.createElement("label");
  1908. labelElem.classList.add("betterytm-ftconf-label");
  1909. labelElem.style.paddingLeft = "10px";
  1910. labelElem.style.paddingRight = "5px";
  1911. labelElem.style.fontSize = "16px";
  1912. labelElem.htmlFor = inputElemId;
  1913. labelElem.innerText = toggleLabelText(Boolean(initialVal)) + unitTxt;
  1914. inputElem.addEventListener("input", () => {
  1915. if (labelElem)
  1916. labelElem.innerText = toggleLabelText(inputElem.checked) + unitTxt;
  1917. });
  1918. }
  1919. inputElem.addEventListener("input", () => {
  1920. let v = Number(String(inputElem.value).trim());
  1921. if (isNaN(v))
  1922. v = Number(inputElem.value);
  1923. if (typeof initialVal !== "undefined")
  1924. confChanged(key, initialVal, (type !== "toggle" ? v : inputElem.checked));
  1925. });
  1926. labelElem && ctrlElem.appendChild(labelElem);
  1927. ctrlElem.appendChild(inputElem);
  1928. ftConfElem.appendChild(ctrlElem);
  1929. }
  1930. featuresCont.appendChild(ftConfElem);
  1931. }
  1932. //#SECTION footer
  1933. const footerCont = document.createElement("div");
  1934. footerCont.id = "betterytm-menu-footer-cont";
  1935. footerCont.style.display = "flex";
  1936. footerCont.style.flexDirection = "row";
  1937. footerCont.style.justifyContent = "space-between";
  1938. footerCont.style.padding = "10px 20px";
  1939. footerCont.style.marginTop = "20px";
  1940. footerCont.style.position = "sticky";
  1941. footerCont.style.bottom = "0";
  1942. footerCont.style.backgroundColor = "var(--bytm-menu-bg)";
  1943. const footerElem = document.createElement("div");
  1944. footerElem.id = "betterytm-menu-footer";
  1945. footerElem.style.fontSize = "17px";
  1946. footerElem.style.textDecoration = "underline";
  1947. footerElem.innerText = "You need to reload the page to apply changes.";
  1948. const reloadElem = document.createElement("button");
  1949. reloadElem.style.marginLeft = "20px";
  1950. reloadElem.innerText = "Reload now";
  1951. reloadElem.title = "Click to reload the page";
  1952. reloadElem.addEventListener("click", () => location.reload());
  1953. const resetElem = document.createElement("button");
  1954. resetElem.className = "bytm-cfg-reset-btn";
  1955. resetElem.title = "Click to reset all settings to their default value";
  1956. resetElem.innerText = "Reset";
  1957. resetElem.addEventListener("click", () => __awaiter(this, void 0, void 0, function* () {
  1958. if (confirm("Do you really want to reset all settings to their default value?\nThe page will automatically reload if you proceed.")) {
  1959. yield (0,_config__WEBPACK_IMPORTED_MODULE_1__.setDefaultFeatConf)();
  1960. location.reload();
  1961. }
  1962. }));
  1963. footerElem.appendChild(reloadElem);
  1964. footerCont.appendChild(footerElem);
  1965. footerCont.appendChild(resetElem);
  1966. featuresCont.appendChild(footerCont);
  1967. //#SECTION finalize
  1968. const menuBody = document.createElement("div");
  1969. menuBody.id = "betterytm-menu-body";
  1970. menuBody.appendChild(titleCont);
  1971. menuBody.appendChild(featuresCont);
  1972. const versionCont = document.createElement("div");
  1973. versionCont.style.display = "flex";
  1974. versionCont.style.justifyContent = "space-around";
  1975. versionCont.style.fontSize = "1.15em";
  1976. versionCont.style.marginTop = "10px";
  1977. versionCont.style.marginBottom = "5px";
  1978. const versionElem = document.createElement("span");
  1979. versionElem.id = "betterytm-menu-version";
  1980. versionElem.innerText = `v${_constants__WEBPACK_IMPORTED_MODULE_2__.scriptInfo.version}`;
  1981. versionCont.appendChild(versionElem);
  1982. featuresCont.appendChild(versionCont);
  1983. menuContainer.appendChild(menuBody);
  1984. menuContainer.appendChild(versionCont);
  1985. backgroundElem.appendChild(menuContainer);
  1986. document.body.appendChild(backgroundElem);
  1987. (0,_utils__WEBPACK_IMPORTED_MODULE_4__.log)("Added menu element:", backgroundElem);
  1988. });
  1989. }
  1990. //#MARKER utilities
  1991. function closeMenu(e) {
  1992. if (!isMenuOpen)
  1993. return;
  1994. isMenuOpen = false;
  1995. (e === null || e === void 0 ? void 0 : e.bubbles) && e.stopPropagation();
  1996. document.body.classList.remove("bytm-disable-scroll");
  1997. const menuBg = document.querySelector("#betterytm-menu-bg");
  1998. menuBg.style.visibility = "hidden";
  1999. menuBg.style.display = "none";
  2000. }
  2001. // function that opens the menu, it should do the inverse of closeMenu()
  2002. function openMenu() {
  2003. if (isMenuOpen)
  2004. return;
  2005. isMenuOpen = true;
  2006. document.body.classList.add("bytm-disable-scroll");
  2007. const menuBg = document.querySelector("#betterytm-menu-bg");
  2008. menuBg.style.visibility = "visible";
  2009. menuBg.style.display = "block";
  2010. }
  2011. /***/ }),
  2012. /***/ "./src/utils.ts":
  2013. /*!**********************!*\
  2014. !*** ./src/utils.ts ***!
  2015. \**********************/
  2016. /***/ (function(__unused_webpack_module, __webpack_exports__, __webpack_require__) {
  2017. __webpack_require__.r(__webpack_exports__);
  2018. /* harmony export */ __webpack_require__.d(__webpack_exports__, {
  2019. /* harmony export */ dbg: function() { return /* binding */ dbg; },
  2020. /* harmony export */ error: function() { return /* binding */ error; },
  2021. /* harmony export */ getAssetUrl: function() { return /* binding */ getAssetUrl; },
  2022. /* harmony export */ getDomain: function() { return /* binding */ getDomain; },
  2023. /* harmony export */ getVideoTime: function() { return /* binding */ getVideoTime; },
  2024. /* harmony export */ info: function() { return /* binding */ info; },
  2025. /* harmony export */ log: function() { return /* binding */ log; },
  2026. /* harmony export */ setLogLevel: function() { return /* binding */ setLogLevel; },
  2027. /* harmony export */ warn: function() { return /* binding */ warn; }
  2028. /* harmony export */ });
  2029. /* harmony import */ var _sv443_network_userutils__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @sv443-network/userutils */ "./node_modules/@sv443-network/userutils/dist/index.mjs");
  2030. /* harmony import */ var _constants__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./constants */ "./src/constants.ts");
  2031. //#SECTION logging
  2032. let curLogLevel = 1;
  2033. /** Sets the current log level. 0 = Debug, 1 = Info */
  2034. function setLogLevel(level) {
  2035. curLogLevel = level;
  2036. }
  2037. /** 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 */
  2038. function getLogLevel(args) {
  2039. const minLogLvl = 0, maxLogLvl = 1;
  2040. if (typeof args.at(-1) === "number")
  2041. return (0,_sv443_network_userutils__WEBPACK_IMPORTED_MODULE_0__.clamp)(args.splice(args.length - 1)[0], minLogLvl, maxLogLvl);
  2042. return 0;
  2043. }
  2044. /** Common prefix to be able to tell logged messages apart and filter them in devtools */
  2045. const consPrefix = `[${_constants__WEBPACK_IMPORTED_MODULE_1__.scriptInfo.name}]`;
  2046. const consPrefixDbg = `[${_constants__WEBPACK_IMPORTED_MODULE_1__.scriptInfo.name}/#DEBUG]`;
  2047. /**
  2048. * Logs string-compatible values to the console, as long as the log level is sufficient.
  2049. * @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.
  2050. */
  2051. function log(...args) {
  2052. if (curLogLevel <= getLogLevel(args))
  2053. console.log(consPrefix, ...args);
  2054. }
  2055. /**
  2056. * Logs string-compatible values to the console as info, as long as the log level is sufficient.
  2057. * @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.
  2058. */
  2059. function info(...args) {
  2060. if (curLogLevel <= getLogLevel(args))
  2061. console.info(consPrefix, ...args);
  2062. }
  2063. /**
  2064. * Logs string-compatible values to the console as a warning, as long as the log level is sufficient.
  2065. * @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.
  2066. */
  2067. function warn(...args) {
  2068. if (curLogLevel <= getLogLevel(args))
  2069. console.warn(consPrefix, ...args);
  2070. }
  2071. /** Logs string-compatible values to the console as an error, no matter the log level. */
  2072. function error(...args) {
  2073. console.error(consPrefix, ...args);
  2074. }
  2075. /** Logs string-compatible values to the console, intended for debugging only */
  2076. function dbg(...args) {
  2077. console.log(consPrefixDbg, ...args);
  2078. }
  2079. //#SECTION video time
  2080. /**
  2081. * Returns the current video time in seconds
  2082. * Dispatches mouse movement events in case the video time can't be estimated
  2083. * @returns Returns null if the video time is unavailable
  2084. */
  2085. function getVideoTime() {
  2086. return new Promise((res) => {
  2087. const domain = getDomain();
  2088. try {
  2089. if (domain === "ytm") {
  2090. const pbEl = document.querySelector("#progress-bar");
  2091. return res(!isNaN(Number(pbEl.value)) ? Number(pbEl.value) : null);
  2092. }
  2093. else if (domain === "yt") {
  2094. // YT doesn't update the progress bar when it's hidden (contrary to YTM which never hides it)
  2095. ytForceShowVideoTime();
  2096. const pbSelector = ".ytp-chrome-bottom div.ytp-progress-bar[role=\"slider\"]";
  2097. const progElem = document.querySelector(pbSelector);
  2098. let videoTime = progElem ? Number(progElem.getAttribute("aria-valuenow")) : -1;
  2099. const mut = new MutationObserver(() => {
  2100. // .observe() is only called when the element exists - no need to check for null
  2101. videoTime = Number(document.querySelector(pbSelector).getAttribute("aria-valuenow"));
  2102. });
  2103. const observe = (progElem) => {
  2104. mut.observe(progElem, {
  2105. attributes: true,
  2106. attributeFilter: ["aria-valuenow"],
  2107. });
  2108. setTimeout(() => {
  2109. res(videoTime >= 0 && !isNaN(videoTime) ? videoTime : null);
  2110. }, 500);
  2111. };
  2112. if (!progElem)
  2113. return (0,_sv443_network_userutils__WEBPACK_IMPORTED_MODULE_0__.onSelector)(pbSelector, { listener: observe });
  2114. else
  2115. return observe(progElem);
  2116. }
  2117. }
  2118. catch (err) {
  2119. error("Couldn't get video time due to error:", err);
  2120. res(null);
  2121. }
  2122. });
  2123. }
  2124. /**
  2125. * Sends events that force the video controls to become visible for about 3 seconds.
  2126. * This only works once, then the page needs to be reloaded!
  2127. */
  2128. function ytForceShowVideoTime() {
  2129. const player = document.querySelector("#movie_player");
  2130. if (!player)
  2131. return false;
  2132. const defaultProps = {
  2133. // needed because otherwise YTM errors out - see https://github.com/Sv443/BetterYTM/issues/18#show_issue
  2134. view: (0,_sv443_network_userutils__WEBPACK_IMPORTED_MODULE_0__.getUnsafeWindow)(),
  2135. bubbles: true,
  2136. cancelable: false,
  2137. };
  2138. player.dispatchEvent(new MouseEvent("mouseenter", defaultProps));
  2139. const { x, y, width, height } = player.getBoundingClientRect();
  2140. const screenY = Math.round(y + height / 2);
  2141. const screenX = x + Math.min(50, Math.round(width / 3));
  2142. player.dispatchEvent(new MouseEvent("mousemove", Object.assign(Object.assign({}, defaultProps), { screenY,
  2143. screenX, movementX: 5, movementY: 0 })));
  2144. return true;
  2145. }
  2146. // /** Parses a video time string in the format `[hh:m]m:ss` to the equivalent number of seconds - returns 0 if input couldn't be parsed */
  2147. // function parseVideoTime(videoTime: string) {
  2148. // const matches = /^((\d{1,2}):)?(\d{1,2}):(\d{2})$/.exec(videoTime);
  2149. // if(!matches)
  2150. // return 0;
  2151. // const [, , hrs, min, sec] = matches as unknown as [string, string | undefined, string | undefined, string, string];
  2152. // let finalTime = 0;
  2153. // if(hrs)
  2154. // finalTime += Number(hrs) * 60 * 60;
  2155. // finalTime += Number(min) * 60 + Number(sec);
  2156. // return isNaN(finalTime) ? 0 : finalTime;
  2157. // }
  2158. // const selectorExistsMap = new Map<string, Array<(element: HTMLElement) => void>>();
  2159. // /**
  2160. // * Calls the `listener` as soon as the `selector` exists in the DOM.
  2161. // * Listeners are deleted as soon as they are called once.
  2162. // * Multiple listeners with the same selector may be registered.
  2163. // */
  2164. // export function onSelectorExists(selector: string, listener: (element: HTMLElement) => void) {
  2165. // const el = document.querySelector<HTMLElement>(selector);
  2166. // if(el)
  2167. // listener(el);
  2168. // else {
  2169. // if(selectorExistsMap.get(selector))
  2170. // selectorExistsMap.set(selector, [...selectorExistsMap.get(selector)!, listener]);
  2171. // else
  2172. // selectorExistsMap.set(selector, [listener]);
  2173. // }
  2174. // }
  2175. // /** Initializes the MutationObserver responsible for checking selectors registered in `onSelectorExists()` */
  2176. // export function initSelectorExistsCheck() {
  2177. // const observer = new MutationObserver(() => {
  2178. // for(const [selector, listeners] of selectorExistsMap.entries()) {
  2179. // const el = document.querySelector<HTMLElement>(selector);
  2180. // if(el) {
  2181. // listeners.forEach(listener => listener(el));
  2182. // selectorExistsMap.delete(selector);
  2183. // }
  2184. // }
  2185. // });
  2186. // observer.observe(document.body, {
  2187. // subtree: true,
  2188. // childList: true,
  2189. // });
  2190. // log("Initialized \"selector exists\" MutationObserver");
  2191. // }
  2192. /**
  2193. * Returns the current domain as a constant string representation
  2194. * @throws Throws if script runs on an unexpected website
  2195. */
  2196. function getDomain() {
  2197. const { hostname } = new URL(location.href);
  2198. if (hostname.includes("music.youtube"))
  2199. return "ytm";
  2200. else if (hostname.includes("youtube"))
  2201. return "yt";
  2202. else
  2203. throw new Error("BetterYTM is running on an unexpected website. Please don't tamper with the @match directives in the userscript header.");
  2204. }
  2205. /** Returns the URL of the asset hosted on GitHub at the specified relative `path` (starting at `{root}/assets/`) */
  2206. function getAssetUrl(path) {
  2207. return `https://raw.githubusercontent.com/Sv443/BetterYTM/${_constants__WEBPACK_IMPORTED_MODULE_1__.branch}/assets/${path}`;
  2208. }
  2209. /***/ }),
  2210. /***/ "./node_modules/@sv443-network/userutils/dist/index.mjs":
  2211. /*!**************************************************************!*\
  2212. !*** ./node_modules/@sv443-network/userutils/dist/index.mjs ***!
  2213. \**************************************************************/
  2214. /***/ (function(__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) {
  2215. __webpack_require__.r(__webpack_exports__);
  2216. /* harmony export */ __webpack_require__.d(__webpack_exports__, {
  2217. /* harmony export */ addGlobalStyle: function() { return /* binding */ F; },
  2218. /* harmony export */ addParent: function() { return /* binding */ R; },
  2219. /* harmony export */ amplifyMedia: function() { return /* binding */ q; },
  2220. /* harmony export */ autoPlural: function() { return /* binding */ z; },
  2221. /* harmony export */ clamp: function() { return /* binding */ S; },
  2222. /* harmony export */ debounce: function() { return /* binding */ D; },
  2223. /* harmony export */ fetchAdvanced: function() { return /* binding */ J; },
  2224. /* harmony export */ getSelectorMap: function() { return /* binding */ Z; },
  2225. /* harmony export */ getUnsafeWindow: function() { return /* binding */ O; },
  2226. /* harmony export */ initOnSelector: function() { return /* binding */ Y; },
  2227. /* harmony export */ insertAfter: function() { return /* binding */ j; },
  2228. /* harmony export */ interceptEvent: function() { return /* binding */ L; },
  2229. /* harmony export */ interceptWindowEvent: function() { return /* binding */ B; },
  2230. /* harmony export */ mapRange: function() { return /* binding */ A; },
  2231. /* harmony export */ onSelector: function() { return /* binding */ V; },
  2232. /* harmony export */ openInNewTab: function() { return /* binding */ $; },
  2233. /* harmony export */ pauseFor: function() { return /* binding */ U; },
  2234. /* harmony export */ preloadImages: function() { return /* binding */ W; },
  2235. /* harmony export */ randRange: function() { return /* binding */ d; },
  2236. /* harmony export */ randomItem: function() { return /* binding */ H; },
  2237. /* harmony export */ randomItemIndex: function() { return /* binding */ x; },
  2238. /* harmony export */ randomizeArray: function() { return /* binding */ P; },
  2239. /* harmony export */ removeOnSelector: function() { return /* binding */ X; },
  2240. /* harmony export */ takeRandomItem: function() { return /* binding */ I; }
  2241. /* harmony export */ });
  2242. var h=Object.defineProperty,y=Object.defineProperties;var g=Object.getOwnPropertyDescriptors;var p=Object.getOwnPropertySymbols;var w=Object.prototype.hasOwnProperty,v=Object.prototype.propertyIsEnumerable;var f=(t,e,n)=>e in t?h(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,c=(t,e)=>{for(var n in e||(e={}))w.call(e,n)&&f(t,n,e[n]);if(p)for(var n of p(e))v.call(e,n)&&f(t,n,e[n]);return t},b=(t,e)=>y(t,g(e));var T=(t,e,n)=>new Promise((r,o)=>{var i=s=>{try{a(n.next(s));}catch(m){o(m);}},u=s=>{try{a(n.throw(s));}catch(m){o(m);}},a=s=>s.done?r(s.value):Promise.resolve(s.value).then(i,u);a((n=n.apply(t,e)).next());});function S(t,e,n){return Math.max(Math.min(t,n),e)}function A(t,e,n,r,o){return Number(e)===0&&Number(r)===0?t*(o/n):(t-e)*((o-r)/(n-e))+r}function d(...t){let e,n;if(typeof t[0]=="number"&&typeof t[1]=="number")[e,n]=t;else if(typeof t[0]=="number"&&typeof t[1]!="number")e=0,n=t[0];else throw new TypeError(`Wrong parameter(s) provided - expected: "number" and "number|undefined", got: "${typeof t[0]}" and "${typeof t[1]}"`);if(e=Number(e),n=Number(n),isNaN(e)||isNaN(n))throw new TypeError(`Parameters "min" and "max" can't be NaN`);if(e>n)throw new TypeError(`Parameter "min" can't be bigger than "max"`);return Math.floor(Math.random()*(n-e+1))+e}function H(t){return x(t)[0]}function x(t){if(t.length===0)return [void 0,void 0];let e=d(t.length-1);return [t[e],e]}function I(t){let[e,n]=x(t);if(n!==void 0)return t.splice(n,1),e}function P(t){let e=[...t];if(t.length===0)return t;for(let n=e.length-1;n>0;n--){let r=Math.floor(d(0,1e4)/1e4*(n+1));[e[n],e[r]]=[e[r],e[n]];}return e}function O(){try{return unsafeWindow}catch(t){return window}}function j(t,e){var n;return (n=t.parentNode)==null||n.insertBefore(e,t.nextSibling),e}function R(t,e){let n=t.parentNode;if(!n)throw new Error("Element doesn't have a parent node");return n.replaceChild(e,t),e.appendChild(t),e}function F(t){let e=document.createElement("style");e.innerHTML=t,document.head.appendChild(e);}function W(t,e=!1){let n=t.map(r=>new Promise((o,i)=>{let u=new Image;u.src=r,u.addEventListener("load",()=>o(u)),u.addEventListener("error",a=>e&&i(a));}));return Promise.allSettled(n)}function $(t){let e=document.createElement("a");Object.assign(e,{className:"userutils-open-in-new-tab",target:"_blank",rel:"noopener noreferrer",href:t}),e.style.display="none",document.body.appendChild(e),e.click(),setTimeout(e.remove,50);}function L(t,e,n){typeof Error.stackTraceLimit=="number"&&Error.stackTraceLimit<1e3&&(Error.stackTraceLimit=1e3),function(r){element.__proto__.addEventListener=function(...o){if(!(o[0]===e&&n()))return r.apply(this,o)};}(t.__proto__.addEventListener);}function B(t,e){return L(O(),t,e)}function q(t,e=1){let n=new(window.AudioContext||window.webkitAudioContext),r={mediaElement:t,amplify:o=>{r.gain.gain.value=o;},getAmpLevel:()=>r.gain.gain.value,context:n,source:n.createMediaElementSource(t),gain:n.createGain()};return r.source.connect(r.gain),r.gain.connect(n.destination),r.amplify(e),r}function z(t,e){return (Array.isArray(e)||e instanceof NodeList)&&(e=e.length),`${t}${e===1?"":"s"}`}function U(t){return new Promise(e=>{setTimeout(e,t);})}function D(t,e=300){let n;return function(...r){clearTimeout(n),n=setTimeout(()=>t.apply(this,r),e);}}function J(n){return T(this,arguments,function*(t,e={}){let{timeout:r=1e4}=e,o=new AbortController,i=setTimeout(()=>o.abort(),r),u=yield fetch(t,b(c({},e),{signal:o.signal}));return clearTimeout(i),u})}var l=new Map;function V(t,e){let n=[];l.has(t)&&(n=l.get(t)),n.push(e),l.set(t,n),E(t,n);}function X(t){return l.delete(t)}function E(t,e){let n=[];if(e.forEach((r,o)=>{try{let i=r.all?document.querySelectorAll(t):document.querySelector(t);(i!==null&&i instanceof NodeList&&i.length>0||i!==null)&&(r.listener(i),r.continuous||n.push(o));}catch(i){console.error(`Couldn't call listener for selector '${t}'`,i);}}),n.length>0){let r=e.filter((o,i)=>!n.includes(i));r.length===0?l.delete(t):l.set(t,r);}}function Y(t={}){new MutationObserver(()=>{for(let[n,r]of l.entries())E(n,r);}).observe(document.body,c({subtree:!0,childList:!0},t));}function Z(){return l}
  2243. /***/ })
  2244. /******/ });
  2245. /************************************************************************/
  2246. /******/ // The module cache
  2247. /******/ var __webpack_module_cache__ = {};
  2248. /******/
  2249. /******/ // The require function
  2250. /******/ function __webpack_require__(moduleId) {
  2251. /******/ // Check if module is in cache
  2252. /******/ var cachedModule = __webpack_module_cache__[moduleId];
  2253. /******/ if (cachedModule !== undefined) {
  2254. /******/ return cachedModule.exports;
  2255. /******/ }
  2256. /******/ // Create a new module (and put it into the cache)
  2257. /******/ var module = __webpack_module_cache__[moduleId] = {
  2258. /******/ // no module.id needed
  2259. /******/ // no module.loaded needed
  2260. /******/ exports: {}
  2261. /******/ };
  2262. /******/
  2263. /******/ // Execute the module function
  2264. /******/ __webpack_modules__[moduleId](module, module.exports, __webpack_require__);
  2265. /******/
  2266. /******/ // Return the exports of the module
  2267. /******/ return module.exports;
  2268. /******/ }
  2269. /******/
  2270. /************************************************************************/
  2271. /******/ /* webpack/runtime/define property getters */
  2272. /******/ !function() {
  2273. /******/ // define getter functions for harmony exports
  2274. /******/ __webpack_require__.d = function(exports, definition) {
  2275. /******/ for(var key in definition) {
  2276. /******/ if(__webpack_require__.o(definition, key) && !__webpack_require__.o(exports, key)) {
  2277. /******/ Object.defineProperty(exports, key, { enumerable: true, get: definition[key] });
  2278. /******/ }
  2279. /******/ }
  2280. /******/ };
  2281. /******/ }();
  2282. /******/
  2283. /******/ /* webpack/runtime/hasOwnProperty shorthand */
  2284. /******/ !function() {
  2285. /******/ __webpack_require__.o = function(obj, prop) { return Object.prototype.hasOwnProperty.call(obj, prop); }
  2286. /******/ }();
  2287. /******/
  2288. /******/ /* webpack/runtime/make namespace object */
  2289. /******/ !function() {
  2290. /******/ // define __esModule on exports
  2291. /******/ __webpack_require__.r = function(exports) {
  2292. /******/ if(typeof Symbol !== 'undefined' && Symbol.toStringTag) {
  2293. /******/ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
  2294. /******/ }
  2295. /******/ Object.defineProperty(exports, '__esModule', { value: true });
  2296. /******/ };
  2297. /******/ }();
  2298. /******/
  2299. /************************************************************************/
  2300. var __webpack_exports__ = {};
  2301. // This entry need to be wrapped in an IIFE because it need to be isolated against other modules in the chunk.
  2302. !function() {
  2303. /*!**********************!*\
  2304. !*** ./src/index.ts ***!
  2305. \**********************/
  2306. __webpack_require__.r(__webpack_exports__);
  2307. /* harmony import */ var _sv443_network_userutils__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @sv443-network/userutils */ "./node_modules/@sv443-network/userutils/dist/index.mjs");
  2308. /* harmony import */ var _config__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./config */ "./src/config.ts");
  2309. /* harmony import */ var _constants__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./constants */ "./src/constants.ts");
  2310. /* harmony import */ var _utils__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./utils */ "./src/utils.ts");
  2311. /* harmony import */ var _events__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./events */ "./src/events.ts");
  2312. /* harmony import */ var _features_index__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./features/index */ "./src/features/index.ts");
  2313. var __awaiter = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) {
  2314. function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
  2315. return new (P || (P = Promise))(function (resolve, reject) {
  2316. function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
  2317. function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
  2318. function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
  2319. step((generator = generator.apply(thisArg, _arguments || [])).next());
  2320. });
  2321. };
  2322. /** URLs of images to pre-cache so they can be displayed instantly */
  2323. const preloadImgs = [
  2324. (0,_utils__WEBPACK_IMPORTED_MODULE_3__.getAssetUrl)("icon/icon.png"),
  2325. (0,_utils__WEBPACK_IMPORTED_MODULE_3__.getAssetUrl)("spinner.svg"),
  2326. (0,_utils__WEBPACK_IMPORTED_MODULE_3__.getAssetUrl)("delete.svg"),
  2327. (0,_utils__WEBPACK_IMPORTED_MODULE_3__.getAssetUrl)("lyrics.svg"),
  2328. ];
  2329. {
  2330. // console watermark with sexy gradient
  2331. 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%);";
  2332. const styleCommon = "color: #fff; font-size: 1.35em; padding-left: 6px; padding-right: 6px;";
  2333. console.log();
  2334. console.log(`%c${_constants__WEBPACK_IMPORTED_MODULE_2__.scriptInfo.name}%cv${_constants__WEBPACK_IMPORTED_MODULE_2__.scriptInfo.version}%c\n\nBuild #${_constants__WEBPACK_IMPORTED_MODULE_2__.scriptInfo.lastCommit} ─ ${_constants__WEBPACK_IMPORTED_MODULE_2__.scriptInfo.namespace}`, `font-weight: bold; ${styleCommon} ${styleGradient}`, `background-color: #333; ${styleCommon}`, "padding: initial;");
  2335. console.log([
  2336. "Powered by:",
  2337. "─ lots of ambition",
  2338. `─ my song metadata API: ${_features_index__WEBPACK_IMPORTED_MODULE_5__.geniUrlBase}`,
  2339. "─ my userscript utility library: https://github.com/Sv443-Network/UserUtils",
  2340. "─ this tiny event listener library: https://github.com/billjs/event-emitter",
  2341. ].join("\n"));
  2342. console.log();
  2343. }
  2344. const domain = (0,_utils__WEBPACK_IMPORTED_MODULE_3__.getDomain)();
  2345. /** Stuff that needs to be called ASAP, before anything async happens */
  2346. function preInit() {
  2347. (0,_utils__WEBPACK_IMPORTED_MODULE_3__.setLogLevel)(_constants__WEBPACK_IMPORTED_MODULE_2__.logLevel);
  2348. if (domain === "ytm")
  2349. (0,_features_index__WEBPACK_IMPORTED_MODULE_5__.initBeforeUnloadHook)();
  2350. init();
  2351. }
  2352. function init() {
  2353. return __awaiter(this, void 0, void 0, function* () {
  2354. if (domain === "ytm")
  2355. (0,_sv443_network_userutils__WEBPACK_IMPORTED_MODULE_0__.preloadImages)(preloadImgs, true)
  2356. .then(() => (0,_utils__WEBPACK_IMPORTED_MODULE_3__.log)(`Preloaded ${preloadImgs.length} ${(0,_sv443_network_userutils__WEBPACK_IMPORTED_MODULE_0__.autoPlural)("image", preloadImgs)}`))
  2357. .catch((e) => (0,_utils__WEBPACK_IMPORTED_MODULE_3__.error)(`Couldn't preload images: ${e}`));
  2358. yield (0,_features_index__WEBPACK_IMPORTED_MODULE_5__.preInitLayout)();
  2359. try {
  2360. document.addEventListener("DOMContentLoaded", onDomLoad);
  2361. }
  2362. catch (err) {
  2363. (0,_utils__WEBPACK_IMPORTED_MODULE_3__.error)("General Error:", err);
  2364. }
  2365. try {
  2366. void ["TODO(v1.1):", _features_index__WEBPACK_IMPORTED_MODULE_5__.initMenu];
  2367. // initMenu();
  2368. }
  2369. catch (err) {
  2370. (0,_utils__WEBPACK_IMPORTED_MODULE_3__.error)("Couldn't initialize menu:", err);
  2371. }
  2372. });
  2373. }
  2374. /** Called when the DOM has finished loading and can be queried and altered by the userscript */
  2375. function onDomLoad() {
  2376. return __awaiter(this, void 0, void 0, function* () {
  2377. // post-build these double quotes are replaced by backticks (because if backticks are used here, webpack converts them to double quotes)
  2378. (0,_sv443_network_userutils__WEBPACK_IMPORTED_MODULE_0__.addGlobalStyle)(/* BetterYTM - global style */
  2379. `/*!**********************************************************************************!*\
  2380. !*** css ./node_modules/css-loader/dist/cjs.js!./src/features/menu/menu_old.css ***!
  2381. \**********************************************************************************/
  2382. :root {
  2383. --bytm-menu-bg: #212121;
  2384. }
  2385. #betterytm-menu-bg {
  2386. display: block;
  2387. position: fixed;
  2388. width: 100vw;
  2389. height: 100vh;
  2390. top: 0;
  2391. left: 0;
  2392. z-index: 15;
  2393. background-color: rgba(0, 0, 0, 0.6);
  2394. }
  2395. #betterytm-menu {
  2396. display: inline-block;
  2397. position: fixed;
  2398. width: 50vw;
  2399. height: auto;
  2400. left: 25vw;
  2401. top: 10vh;
  2402. z-index: 16;
  2403. padding: 10px 25px;
  2404. color: #fff;
  2405. background-color: var(--bytm-menu-bg);
  2406. }
  2407. #betterytm-menu-opts {
  2408. max-height: 70vh;
  2409. overflow: auto;
  2410. }
  2411. #betterytm-menu-titlecont {
  2412. display: flex;
  2413. }
  2414. #betterytm-menu-title {
  2415. font-size: 20px;
  2416. margin-top: 5px;
  2417. margin-bottom: 8px;
  2418. }
  2419. #betterytm-menu-linkscont {
  2420. display: flex;
  2421. }
  2422. .betterytm-menu-link {
  2423. cursor: pointer;
  2424. display: inline-block;
  2425. }
  2426. #betterytm-menu-close {
  2427. cursor: pointer;
  2428. }
  2429. .betterytm-ftconf-label {
  2430. user-select: none;
  2431. }
  2432. body.bytm-disable-scroll {
  2433. overflow-y: hidden !important;
  2434. }
  2435. /*!***************************************************************************!*\
  2436. !*** css ./node_modules/css-loader/dist/cjs.js!./src/features/layout.css ***!
  2437. \***************************************************************************/
  2438. /* #MARKER misc */
  2439. .bytm-generic-btn {
  2440. display: inline-flex;
  2441. align-items: center;
  2442. justify-content: center;
  2443. position: relative;
  2444. vertical-align: middle;
  2445. cursor: pointer;
  2446. margin-left: 8px;
  2447. width: 40px;
  2448. height: 40px;
  2449. border-radius: 100%;
  2450. background-color: transparent;
  2451. }
  2452. .bytm-generic-btn:hover {
  2453. background-color: var(--yt-spec-10-percent-layer, #1d1d1d);
  2454. }
  2455. .bytm-generic-btn-img {
  2456. display: inline-block;
  2457. z-index: 10;
  2458. width: 24px;
  2459. height: 24px;
  2460. padding: 5px;
  2461. }
  2462. .bytm-spinner {
  2463. animation: rotate 1.5s linear infinite;
  2464. }
  2465. @keyframes rotate {
  2466. from {
  2467. transform: rotate(0deg);
  2468. }
  2469. to {
  2470. transform: rotate(360deg);
  2471. }
  2472. }
  2473. .bytm-anchor {
  2474. all: unset;
  2475. cursor: pointer;
  2476. }
  2477. /* ytmusic-logo a[bytm-animated="true"] .bytm-mod-logo-ellipse {
  2478. transform-origin: 12px 12px;
  2479. animation: rotate 1s ease-in-out infinite;
  2480. } */
  2481. ytmusic-logo a.bytm-logo-exchanged .bytm-mod-logo-path {
  2482. transform-origin: 12px 12px;
  2483. animation: rotate 1s ease-in-out;
  2484. }
  2485. ytmusic-logo a.bytm-logo-exchanged .bytm-mod-logo-img {
  2486. width: 24px;
  2487. height: 24px;
  2488. z-index: 1000;
  2489. position: absolute;
  2490. animation: rotate-fade-in 1s ease-in-out;
  2491. }
  2492. @keyframes rotate-fade-in {
  2493. 0% {
  2494. opacity: 0;
  2495. transform: rotate(0deg);
  2496. }
  2497. 30% {
  2498. opacity: 0;
  2499. }
  2500. 90% {
  2501. opacity: 1;
  2502. }
  2503. 100% {
  2504. transform: rotate(360deg);
  2505. }
  2506. }
  2507. .bytm-no-select {
  2508. user-select: none;
  2509. -ms-user-select: none;
  2510. -moz-user-select: none;
  2511. -webkit-user-select: none;
  2512. }
  2513. /* #MARKER menu */
  2514. .bytm-cfg-menu-option {
  2515. display: block;
  2516. padding: 8px 0;
  2517. }
  2518. .bytm-cfg-menu-option-item {
  2519. display: flex;
  2520. flex-direction: row;
  2521. align-items: center;
  2522. font-size: 16px;
  2523. font-weight: 400;
  2524. line-height: 24px;
  2525. padding: var(--yt-compact-link-paper-item-padding, 0px 36px 0 16px);
  2526. min-height: var(--paper-item-min-height, 40px);
  2527. white-space: nowrap;
  2528. cursor: pointer;
  2529. }
  2530. .bytm-cfg-menu-option-item:hover {
  2531. background-color: var(--yt-spec-badge-chip-background, #3e3e3e);
  2532. }
  2533. .bytm-cfg-menu-option-icon {
  2534. width: 24px;
  2535. height: 24px;
  2536. margin-right: 16px;
  2537. display: flex;
  2538. align-items: center;
  2539. flex-direction: row;
  2540. flex: none;
  2541. }
  2542. .bytm-cfg-menu-option-text {
  2543. font-size: 1.4rem;
  2544. line-height: 2rem;
  2545. }
  2546. yt-multi-page-menu-section-renderer.ytd-multi-page-menu-renderer {
  2547. border-bottom: 1px solid var(--yt-spec-10-percent-layer, #3e3e3e);
  2548. }
  2549. /* #MARKER watermark */
  2550. #bytm-watermark {
  2551. font-size: 10px;
  2552. display: inline-block;
  2553. position: absolute;
  2554. left: 97px;
  2555. top: 46px;
  2556. z-index: 10;
  2557. color: white;
  2558. text-decoration: none;
  2559. cursor: pointer;
  2560. }
  2561. #bytm-watermark:hover {
  2562. text-decoration: underline;
  2563. }
  2564. /* #MARKER queue buttons */
  2565. .side-panel.modular ytmusic-player-queue-item .song-info.ytmusic-player-queue-item {
  2566. position: relative;
  2567. }
  2568. .side-panel.modular ytmusic-player-queue-item .bytm-queue-btn-container {
  2569. background: rgb(0, 0, 0);
  2570. background: linear-gradient(90deg, rgba(0, 0, 0, 0) 0%, rgba(0, 0, 0, 1) 15%);
  2571. display: none;
  2572. position: absolute;
  2573. right: 0;
  2574. padding-left: 25px;
  2575. height: 100%;
  2576. }
  2577. .side-panel.modular ytmusic-player-queue-item:hover .bytm-queue-btn-container {
  2578. display: inline-block;
  2579. }
  2580. .side-panel.modular ytmusic-player-queue-item[play-button-state="loading"] .bytm-queue-btn-container,
  2581. .side-panel.modular ytmusic-player-queue-item[play-button-state="playing"] .bytm-queue-btn-container,
  2582. .side-panel.modular ytmusic-player-queue-item[play-button-state="paused"] .bytm-queue-btn-container {
  2583. /* using a var() is not viable since the nesting changes the actual value of the variable */
  2584. background: linear-gradient(90deg, rgba(0, 0, 0, 0) 0%, rgba(29, 29, 29, 1) 15%);
  2585. }
  2586. ytmusic-app ytmusic-popup-container tp-yt-iron-dropdown[data-bytm-hidden=true] {
  2587. display: none !important;
  2588. }
  2589. /* #MARKER anchor improvements */
  2590. ytmusic-responsive-list-item-renderer .left-items {
  2591. margin-right: 0 !important;
  2592. }
  2593. .bytm-carousel-shelf-anchor {
  2594. margin: 0 var(--ytmusic-responsive-list-item-thumbnail-margin-right, 16px) 0 0;
  2595. }
  2596. /*!******************************************************************************!*\
  2597. !*** css ./node_modules/css-loader/dist/cjs.js!./src/features/menu/menu.css ***!
  2598. \******************************************************************************/
  2599. /* #bytm-menu-backdrop {
  2600. display: none;
  2601. flex-direction: column;
  2602. justify-content: center;
  2603. align-items: center;
  2604. }
  2605. #bytm-menu-backdrop[data-menu-open="true"] {
  2606. display: flex;
  2607. } */
  2608. #bytm-menu-header-container {
  2609. display: flex;
  2610. justify-content: flex-start;
  2611. align-items: center;
  2612. border-color: #ffffff;
  2613. border-style: none solid none none;
  2614. }
  2615. .bytm-menu-header-option {
  2616. display: "flex";
  2617. justify-content: center;
  2618. align-items: center;
  2619. border-color: #ffffff;
  2620. border-style: solid none solid none;
  2621. }
  2622. #bytm-menu-header-option h3 {
  2623. margin: 0;
  2624. }
  2625. .bytm-menu-tab[data-active="true"] {
  2626. display: none;
  2627. }
  2628. .bytm-menu-tab[data-active="false"] {
  2629. display: none;
  2630. }
  2631. /*# sourceMappingURL=http://localhost:8710/global.css.map*/`);
  2632. (0,_sv443_network_userutils__WEBPACK_IMPORTED_MODULE_0__.initOnSelector)();
  2633. const features = yield (0,_config__WEBPACK_IMPORTED_MODULE_1__.loadFeatureConf)();
  2634. (0,_utils__WEBPACK_IMPORTED_MODULE_3__.log)(`Initializing features for domain "${domain}"...`);
  2635. try {
  2636. if (domain === "ytm") {
  2637. try {
  2638. (0,_features_index__WEBPACK_IMPORTED_MODULE_5__.addMenu)(); // TODO(v1.1): remove
  2639. }
  2640. catch (err) {
  2641. (0,_utils__WEBPACK_IMPORTED_MODULE_3__.error)("Couldn't add menu:", err);
  2642. }
  2643. (0,_events__WEBPACK_IMPORTED_MODULE_4__.initSiteEvents)();
  2644. (0,_sv443_network_userutils__WEBPACK_IMPORTED_MODULE_0__.onSelector)("tp-yt-iron-dropdown #contentWrapper ytd-multi-page-menu-renderer #container.menu-container", { listener: _features_index__WEBPACK_IMPORTED_MODULE_5__.addConfigMenuOption });
  2645. if (features.arrowKeySupport)
  2646. (0,_features_index__WEBPACK_IMPORTED_MODULE_5__.initArrowKeySkip)();
  2647. if (features.removeUpgradeTab)
  2648. (0,_features_index__WEBPACK_IMPORTED_MODULE_5__.removeUpgradeTab)();
  2649. if (features.watermarkEnabled)
  2650. (0,_features_index__WEBPACK_IMPORTED_MODULE_5__.addWatermark)();
  2651. if (features.geniusLyrics)
  2652. (0,_features_index__WEBPACK_IMPORTED_MODULE_5__.addMediaCtrlLyricsBtn)();
  2653. if (features.queueButtons)
  2654. (0,_features_index__WEBPACK_IMPORTED_MODULE_5__.initQueueButtons)();
  2655. if (features.anchorImprovements)
  2656. (0,_features_index__WEBPACK_IMPORTED_MODULE_5__.addAnchorImprovements)();
  2657. //#DEBUG
  2658. setInterval(() => {
  2659. const selMap = (0,_sv443_network_userutils__WEBPACK_IMPORTED_MODULE_0__.getSelectorMap)();
  2660. (0,_utils__WEBPACK_IMPORTED_MODULE_3__.dbg)("selector map", selMap.size, selMap);
  2661. }, 500);
  2662. // initVolumeFeatures();
  2663. }
  2664. if (["ytm", "yt"].includes(domain)) {
  2665. if (features.switchBetweenSites)
  2666. (0,_features_index__WEBPACK_IMPORTED_MODULE_5__.initSiteSwitch)(domain);
  2667. }
  2668. }
  2669. catch (err) {
  2670. (0,_utils__WEBPACK_IMPORTED_MODULE_3__.error)("General error while executing feature:", err);
  2671. }
  2672. });
  2673. }
  2674. preInit();
  2675. }();
  2676. //# sourceMappingURL=http://localhost:8710/BetterYTM.user.js.map