BetterYTM.user.js 179 KB

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