BetterYTM.user.js 175 KB

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