BetterYTM.user.js 147 KB

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