BetterYTM.user.js 142 KB

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