BetterYTM.user.js 138 KB

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