BetterYTM.user.js 156 KB

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