BetterYTM.user.js 176 KB

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