BetterYTM.user.js 146 KB

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