BetterYTM.user.js 143 KB

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