BetterYTM.user.js 156 KB

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