BetterYTM.user.js 155 KB

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