BetterYTM.user.js 143 KB

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