BetterYTM.user.js 141 KB

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