BetterYTM.user.js 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835
  1. // ==UserScript==
  2. // @name BetterYTM
  3. // @name:de BetterYTM
  4. // @namespace https://github.com/Sv443/BetterYTM#readme
  5. // @version 1.0.0
  6. // @license MIT
  7. // @author Sv443
  8. // @copyright Sv443 <[email protected]> (https://github.com/Sv443)
  9. // @description Improvements for YouTube Music
  10. // @description:de Verbesserungen für YouTube Music
  11. // @match https://music.youtube.com/*
  12. // @match https://www.youtube.com/*
  13. // @icon https://www.google.com/s2/favicons?domain=music.youtube.com
  14. // @run-at document-start
  15. // @grant GM.getValue
  16. // @grant GM.setValue
  17. // @connect self
  18. // @connect youtube.com
  19. // @connect github.com
  20. // @connect githubusercontent.com
  21. // @downloadURL https://raw.githubusercontent.com/Sv443/BetterYTM/main/BetterYTM.user.js
  22. // @updateURL https://raw.githubusercontent.com/Sv443/BetterYTM/main/BetterYTM.user.js
  23. // ==/UserScript==
  24. /* Disclaimer: I am not affiliated with YouTube, Google, Alphabet, Genius or anyone else */
  25. /* C&D this, Susan 🖕 */
  26. (async () => {
  27. "use-strict";
  28. /** Set to true to enable debug mode for more output in the JS console */
  29. const dbg = true;
  30. const defaultFeatures = {
  31. /** Whether arrow keys should skip forwards and backwards by 10 seconds */
  32. arrowKeySupport: true,
  33. /** Whether to remove the "Upgrade" / YT Music Premium tab */
  34. removeUpgradeTab: true,
  35. /** Whether to add a button or key combination (TODO) to switch between the YT and YTM sites on a video */
  36. switchBetweenSites: true,
  37. /** Adds a button to the media controls bar to search for the current song's lyrics on genius.com in a new tab */
  38. geniusLyrics: true,
  39. /** Adds a lyrics button to each song in the queue ("up next" tab) */
  40. lyricsButtonsOnSongQueue: true,
  41. /** Set to true to remove the watermark under the YTM logo */
  42. removeWatermark: false,
  43. };
  44. const featureConf = await loadFeatureConf();
  45. console.log("bytm load", featureConf);
  46. const features = { ...defaultFeatures, ...featureConf };
  47. console.log("bytm save", features);
  48. await saveFeatureConf(features);
  49. //#MARKER types
  50. /** @typedef {"yt"|"ytm"} Domain Constant string representation of which domain this script is currently running on */
  51. //#MARKER init
  52. /** Specifies the hard limit for repetitive tasks */
  53. const triesLimit = 20;
  54. const info = Object.freeze({
  55. name: GM.info.script.name, // eslint-disable-line no-undef
  56. version: GM.info.script.version, // eslint-disable-line no-undef
  57. namespace: GM.info.script.namespace, // eslint-disable-line no-undef
  58. });
  59. function init()
  60. {
  61. try
  62. {
  63. console.log(`${info.name} v${info.version} - ${info.namespace}`);
  64. document.addEventListener("DOMContentLoaded", onDomLoad);
  65. }
  66. catch(err)
  67. {
  68. console.error("BetterYTM - General Error:", err);
  69. }
  70. }
  71. //#MARKER events
  72. /**
  73. * Called when the DOM has finished loading (after `DOMContentLoaded` is emitted)
  74. */
  75. async function onDomLoad()
  76. {
  77. const domain = getDomain();
  78. dbg && console.log(`BetterYTM: Initializing features for domain '${domain}'`);
  79. try
  80. {
  81. if(domain === "ytm")
  82. {
  83. if(features.arrowKeySupport)
  84. {
  85. document.addEventListener("keydown", onKeyDown);
  86. dbg && console.log(`BetterYTM: Added key press listener`);
  87. }
  88. if(features.removeUpgradeTab)
  89. removeUpgradeTab();
  90. if(!features.removeWatermark)
  91. addWatermark();
  92. if(features.geniusLyrics)
  93. await addMediaCtrlGeniusBtn();
  94. if(features.lyricsButtonsOnSongQueue)
  95. await addQueueGeniusBtns();
  96. }
  97. if(["ytm", "yt"].includes(domain))
  98. {
  99. if(features.switchBetweenSites)
  100. initSiteSwitch(domain);
  101. try
  102. {
  103. addMenu();
  104. }
  105. catch(err)
  106. {
  107. console.error("BetterYTM: Couldn't add menu:", err);
  108. }
  109. }
  110. }
  111. catch(err)
  112. {
  113. console.error(`BetterYTM: General error while executing feature:`, err);
  114. }
  115. // if(features.themeColor != "#f00" && features.themeColor != "#ff0000")
  116. // applyTheme();
  117. }
  118. //#MARKER menu
  119. /**
  120. * Adds an element to open the BetterYTM menu
  121. */
  122. function addMenu()
  123. {
  124. // const domain = getDomain();
  125. // bg & menu
  126. const backgroundElem = document.createElement("div");
  127. backgroundElem.id = "betterytm-menu-bg";
  128. backgroundElem.title = "Click here to close the menu";
  129. backgroundElem.style.visibility = "hidden";
  130. backgroundElem.style.display = "none";
  131. backgroundElem.addEventListener("click", (e) => {
  132. if(e.target.id === "betterytm-menu-bg")
  133. closeMenu();
  134. });
  135. const menuContainer = document.createElement("div");
  136. menuContainer.title = "";
  137. menuContainer.id = "betterytm-menu";
  138. // title
  139. const titleCont = document.createElement("div");
  140. titleCont.id = "betterytm-menu-titlecont";
  141. const titleElem = document.createElement("h2");
  142. titleElem.id = "betterytm-menu-title";
  143. titleElem.innerText = "BetterYTM - Menu";
  144. const linksCont = document.createElement("div");
  145. linksCont.id = "betterytm-menu-linkscont";
  146. const addLink = (imgSrc, href, title) => {
  147. const anchorElem = document.createElement("a");
  148. anchorElem.className = "betterytm-menu-link";
  149. anchorElem.rel = "noopener noreferrer";
  150. anchorElem.target = "_blank";
  151. anchorElem.href = href;
  152. anchorElem.title = title;
  153. const linkElem = document.createElement("img");
  154. linkElem.className = "betterytm-menu-img";
  155. linkElem.src = imgSrc;
  156. anchorElem.appendChild(linkElem);
  157. linksCont.appendChild(anchorElem);
  158. };
  159. addLink("TODO:github.png", info.namespace, `${info.name} on GitHub`);
  160. addLink("TODO:greasyfork.png", "https://greasyfork.org/", `${info.name} on GreasyFork`);
  161. const closeElem = document.createElement("img");
  162. closeElem.id = "betterytm-menu-close";
  163. closeElem.src = "TODO:close.png";
  164. closeElem.title = "Click to close the menu";
  165. closeElem.addEventListener("click", closeMenu);
  166. titleCont.appendChild(titleElem);
  167. titleCont.appendChild(linksCont);
  168. titleCont.appendChild(closeElem);
  169. // TODO: features
  170. const featuresCont = document.createElement("div");
  171. featuresCont.id = "betterytm-menu-opts";
  172. // finalize
  173. menuContainer.appendChild(titleCont);
  174. menuContainer.appendChild(featuresCont);
  175. backgroundElem.appendChild(menuContainer);
  176. document.body.appendChild(backgroundElem);
  177. // add style
  178. const menuStyle = `\
  179. #betterytm-menu-bg {
  180. display: block;
  181. position: fixed;
  182. width: 100vw;
  183. height: 100vh;
  184. top: 0;
  185. left: 0;
  186. z-index: 15;
  187. background-color: rgba(0, 0, 0, 0.6);
  188. }
  189. #betterytm-menu {
  190. display: inline-block;
  191. position: fixed;
  192. width: 50vw;
  193. height: 50vh;
  194. min-height: 500px;
  195. left: 25vw;
  196. top: 25vh;
  197. z-index: 16;
  198. overflow: auto;
  199. padding: 8px;
  200. color: #fff;
  201. background-color: #212121;
  202. }
  203. #betterytm-menu-titlecont {
  204. display: flex;
  205. }
  206. #betterytm-menu-title {
  207. font-size: 20px;
  208. margin-top: 5px;
  209. margin-bottom: 8px;
  210. }
  211. #betterytm-menu-linkscont {
  212. display: flex;
  213. }
  214. .betterytm-menu-link {
  215. display: inline-block;
  216. }
  217. .betterytm-menu-img {
  218. }
  219. #betterytm-menu-close {
  220. cursor: pointer;
  221. }
  222. `;
  223. dbg && console.log("BetterYTM: Added menu elem:", backgroundElem);
  224. /* #DEBUG */ //openMenu();
  225. addGlobalStyle(menuStyle, "menu");
  226. }
  227. function closeMenu()
  228. {
  229. const menuBg = document.querySelector("#betterytm-menu-bg");
  230. menuBg.style.visibility = "hidden";
  231. menuBg.style.display = "none";
  232. }
  233. // function openMenu()
  234. // {
  235. // const menuBg = document.querySelector("#betterytm-menu-bg");
  236. // menuBg.style.visibility = "visible";
  237. // menuBg.style.display = "block";
  238. // }
  239. //#MARKER features
  240. //#SECTION arrow key skip
  241. /**
  242. * Called when the user presses keys
  243. * @param {KeyboardEvent} evt
  244. */
  245. function onKeyDown(evt)
  246. {
  247. if(["ArrowLeft", "ArrowRight"].includes(evt.code))
  248. {
  249. // discard the event when a (text) input is currently active, like when editing a playlist
  250. if(["INPUT", "TEXTAREA", "SELECT"].includes(document.activeElement.tagName))
  251. return dbg && console.info(`BetterYTM: Captured valid key but the current active element is <${document.activeElement.tagName.toLowerCase()}>, so the keypress is ignored`);
  252. dbg && console.log(`BetterYTM: Captured key '${evt.code}' in proxy listener`);
  253. // 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
  254. const defaultProps = {
  255. altKey: false,
  256. bubbles: true,
  257. cancelBubble: false,
  258. cancelable: true,
  259. charCode: 0,
  260. composed: true,
  261. ctrlKey: false,
  262. currentTarget: null,
  263. defaultPrevented: evt.defaultPrevented,
  264. explicitOriginalTarget: document.body,
  265. isTrusted: true,
  266. metaKey: false,
  267. originalTarget: document.body,
  268. repeat: false,
  269. shiftKey: false,
  270. srcElement: document.body,
  271. target: document.body,
  272. type: "keydown",
  273. view: window,
  274. };
  275. let invalidKey = false;
  276. let keyProps = {};
  277. switch(evt.code)
  278. {
  279. case "ArrowLeft":
  280. keyProps = {
  281. code: "KeyH",
  282. key: "h",
  283. keyCode: 72,
  284. which: 72,
  285. };
  286. break;
  287. case "ArrowRight":
  288. keyProps = {
  289. code: "KeyL",
  290. key: "l",
  291. keyCode: 76,
  292. which: 76,
  293. };
  294. break;
  295. default:
  296. // console.warn("BetterYTM - Unknown key", evt.code);
  297. invalidKey = true;
  298. break;
  299. }
  300. if(!invalidKey)
  301. {
  302. const proxyProps = { ...defaultProps, ...keyProps };
  303. document.body.dispatchEvent(new KeyboardEvent("keydown", proxyProps));
  304. dbg && console.log(`BetterYTM: Dispatched proxy keydown event: [${evt.code}] -> [${proxyProps.code}]`);
  305. }
  306. else if(dbg)
  307. console.warn(`BetterYTM: Captured key '${evt.code}' has no defined behavior`);
  308. }
  309. }
  310. //#SECTION site switch
  311. /**
  312. * Initializes the site switch feature
  313. * @param {Domain} domain
  314. */
  315. function initSiteSwitch(domain)
  316. {
  317. // TODO:
  318. // extra features:
  319. // - keep video time
  320. document.addEventListener("keydown", (e) => {
  321. if(e.key == "F9")
  322. switchSite(domain === "yt" ? "ytm" : "yt");
  323. });
  324. dbg && console.log(`BetterYTM: Initialized site switch listener`);
  325. }
  326. /**
  327. * Switches to the other site (between YT and YTM)
  328. * @param {Domain} newDomain
  329. */
  330. function switchSite(newDomain)
  331. {
  332. try
  333. {
  334. let subdomain;
  335. if(newDomain === "ytm")
  336. subdomain = "music";
  337. else if(newDomain === "yt")
  338. subdomain = "www";
  339. if(!subdomain)
  340. throw new TypeError(`Unrecognized domain '${newDomain}'`);
  341. const { pathname, search, hash } = new URL(location.href);
  342. const vt = getVideoTime() ?? 0;
  343. dbg && console.log(`BetterYTM: Found video time of ${vt} seconds`);
  344. const newSearch = search.includes("?") ? `${search}&t=${vt}` : `?t=${vt}`;
  345. const url = `https://${subdomain}.youtube.com${pathname}${newSearch}${hash}`;
  346. console.info(`BetterYTM - switching to domain '${newDomain}' at ${url}`);
  347. location.href = url;
  348. }
  349. catch(err)
  350. {
  351. console.error(`BetterYTM: Error while switching site:`, err);
  352. }
  353. }
  354. //#SECTION remove upgrade tab
  355. let removeUpgradeTries = 0;
  356. /**
  357. * Removes the "Upgrade" / YT Music Premium tab from the title / nav bar
  358. */
  359. function removeUpgradeTab()
  360. {
  361. const tabElem = document.querySelector(`.ytmusic-nav-bar ytmusic-pivot-bar-item-renderer[tab-id="SPunlimited"]`);
  362. if(tabElem)
  363. {
  364. tabElem.remove();
  365. dbg && console.log(`BetterYTM: Removed upgrade tab after ${removeUpgradeTries} tries`);
  366. }
  367. else if(removeUpgradeTries < triesLimit)
  368. {
  369. setTimeout(removeUpgradeTab, 250); // TODO: improve this
  370. removeUpgradeTries++;
  371. }
  372. else
  373. console.error(`BetterYTM: Couldn't find upgrade tab to remove after ${removeUpgradeTries} tries`);
  374. }
  375. //#SECTION add watermark
  376. /**
  377. * Adds a watermark beneath the logo
  378. */
  379. function addWatermark()
  380. {
  381. const watermark = document.createElement("a");
  382. watermark.id = "betterytm-watermark";
  383. watermark.className = "style-scope ytmusic-nav-bar";
  384. watermark.innerText = info.name;
  385. watermark.title = `${info.name} v${info.version}`;
  386. watermark.href = info.namespace;
  387. watermark.target = "_blank";
  388. watermark.rel = "noopener noreferrer";
  389. const style = `\
  390. #betterytm-watermark {
  391. display: inline-block;
  392. position: absolute;
  393. left: 45px;
  394. top: 43px;
  395. z-index: 10;
  396. color: white;
  397. text-decoration: none;
  398. cursor: pointer;
  399. }
  400. @media(max-width: 615px) {
  401. #betterytm-watermark {
  402. display: none;
  403. }
  404. }
  405. #betterytm-watermark:hover {
  406. text-decoration: underline;
  407. }`;
  408. addGlobalStyle(style, "watermark");
  409. const logoElem = document.querySelector("#left-content");
  410. insertAfter(logoElem, watermark);
  411. dbg && console.log(`BetterYTM: Added watermark element:`, watermark);
  412. }
  413. //#SECTION genius.com lyrics button
  414. let mcCurrentSongTitle = "";
  415. let mcLyricsButtonAddTries = 0;
  416. /**
  417. * Adds a genius.com lyrics button to the media controls bar
  418. */
  419. async function addMediaCtrlGeniusBtn()
  420. {
  421. const likeContainer = document.querySelector(".middle-controls-buttons ytmusic-like-button-renderer#like-button-renderer");
  422. if(!likeContainer)
  423. {
  424. mcLyricsButtonAddTries++;
  425. if(mcLyricsButtonAddTries < triesLimit)
  426. return setTimeout(addMediaCtrlGeniusBtn, 250); // TODO: improve this
  427. return console.error(`BetterYTM: Couldn't find element to append lyrics buttons to after ${mcLyricsButtonAddTries} tries`);
  428. }
  429. const songTitleElem = document.querySelector(".content-info-wrapper > yt-formatted-string");
  430. const gUrl = await getCurrentGeniusUrl();
  431. const linkElem = document.createElement("a");
  432. linkElem.id = "betterytm-lyrics-button";
  433. linkElem.className = "ytmusic-player-bar";
  434. linkElem.title = "Search for lyrics on genius.com";
  435. linkElem.href = gUrl;
  436. linkElem.target = "_blank";
  437. linkElem.rel = "noopener noreferrer";
  438. linkElem.style.visibility = gUrl ? "initial" : "hidden";
  439. const style = `\
  440. #betterytm-lyrics-button {
  441. display: inline-flex;
  442. align-items: center;
  443. justify-content: center;
  444. position: relative;
  445. vertical-align: middle;
  446. margin-left: 8px;
  447. width: 40px;
  448. height: 40px;
  449. border-radius: 100%;
  450. background-color: transparent;
  451. }
  452. #betterytm-lyrics-button:hover {
  453. background-color: #383838;
  454. }
  455. #betterytm-lyrics-img {
  456. display: inline-block;
  457. z-index: 10;
  458. width: 24px;
  459. height: 24px;
  460. padding: 5px;
  461. }`;
  462. addGlobalStyle(style, "lyrics");
  463. const imgElem = document.createElement("img");
  464. imgElem.id = "betterytm-lyrics-img";
  465. imgElem.src = "https://raw.githubusercontent.com/Sv443/BetterYTM/main/resources/external/genius.png";
  466. linkElem.appendChild(imgElem);
  467. dbg && console.log(`BetterYTM: Inserted genius button after ${mcLyricsButtonAddTries} tries:`, linkElem);
  468. insertAfter(likeContainer, linkElem);
  469. mcCurrentSongTitle = songTitleElem.title;
  470. /** @param {MutationRecord[]} mutations */
  471. const onMutation = async (mutations) => {
  472. for await(const mut of mutations)
  473. {
  474. const newTitle = mut.target.title;
  475. if(newTitle != mcCurrentSongTitle)
  476. {
  477. const lyricsBtn = document.querySelector("#betterytm-lyrics-button");
  478. dbg && console.log(`BetterYTM: Song title changed from '${mcCurrentSongTitle}' to '${newTitle}'`);
  479. lyricsBtn.style.cursor = "wait";
  480. lyricsBtn.style.pointerEvents = "none";
  481. mcCurrentSongTitle = newTitle;
  482. lyricsBtn.href = await getCurrentGeniusUrl(); // can take a second or two
  483. lyricsBtn.style.cursor = "pointer";
  484. lyricsBtn.style.visibility = "initial";
  485. lyricsBtn.style.pointerEvents = "initial";
  486. }
  487. }
  488. };
  489. // since YT and YTM don't reload the page on video change, MutationObserver needs to be used
  490. const obs = new MutationObserver(onMutation);
  491. obs.observe(songTitleElem, { attributes: true, attributeFilter: [ "title" ] });
  492. }
  493. /**
  494. * Adds genius lyrics buttons to the song queue
  495. */
  496. async function addQueueGeniusBtns()
  497. {
  498. }
  499. /**
  500. * Returns the genius.com lyrics site URL for the current song
  501. * @returns {string|null}
  502. */
  503. async function getCurrentGeniusUrl()
  504. {
  505. try
  506. {
  507. const songTitleElem = document.querySelector(".content-info-wrapper > yt-formatted-string");
  508. const songMetaElem = document.querySelector("span.subtitle > yt-formatted-string:first-child");
  509. if(!songTitleElem || !songMetaElem || !songTitleElem.title)
  510. return null;
  511. const sanitizeSongName = (songName) => {
  512. let sanitized;
  513. if(songName.match(/\(|feat|ft/gmi))
  514. {
  515. // should hopefully trim right after the song name
  516. sanitized = songName.substring(0, songName.indexOf("("));
  517. }
  518. return (sanitized || songName).trim();
  519. };
  520. /** @param {string} songMeta */
  521. const splitArtist = (songMeta) => {
  522. songMeta = songMeta.split(/\s*\u2022\s*/gmiu)[0]; // split at &bull; (•) character
  523. if(songMeta.match(/&/))
  524. songMeta = songMeta.split(/\s*&\s*/gm)[0];
  525. if(songMeta.match(/,/))
  526. songMeta = songMeta.split(/,\s*/gm)[0];
  527. return songMeta;
  528. }
  529. const songNameRaw = songTitleElem.title;
  530. const songName = sanitizeSongName(songNameRaw);
  531. const artistName = splitArtist(songMetaElem.title);
  532. // TODO: artist might need further splitting before comma or ampersand
  533. // TODO: song title might need *less* splitting for something like "MyNewSong (wip)"
  534. const query = encodeURIComponent(`${artistName} ${songName}`);
  535. return getGeniusUrl(query);
  536. }
  537. catch(err)
  538. {
  539. console.error(`BetterYTM: Couldn't resolve genius.com URL:`, err);
  540. }
  541. }
  542. /**
  543. * @param {string} query
  544. * @returns {string|null}
  545. */
  546. async function getGeniusUrl(query)
  547. {
  548. const result = await (await fetch(`https://api.sv443.net/geniurl/search/top?q=${query}`)).json();
  549. if(result.error)
  550. {
  551. console.error("BetterYTM: Couldn't fetch genius.com URL:", result.message);
  552. return null;
  553. }
  554. return result.url;
  555. }
  556. //#MARKER other
  557. /**
  558. * Returns the current domain as a constant string representation
  559. * @throws {Error} If script runs on an unexpected website
  560. * @returns {Domain}
  561. */
  562. function getDomain()
  563. {
  564. const { hostname } = new URL(location.href);
  565. if(hostname.includes("music.youtube"))
  566. return "ytm";
  567. else if(hostname.includes("youtube"))
  568. return "yt";
  569. else
  570. throw new Error("BetterYTM is running on an unexpected website");
  571. }
  572. /**
  573. * TODO: this is entirely broken now
  574. * Returns the current video time in seconds
  575. * @returns {number|null} Returns null if the video time is unavailable
  576. */
  577. function getVideoTime()
  578. {
  579. const domain = getDomain();
  580. try
  581. {
  582. if(domain === "ytm")
  583. {
  584. const pbEl = document.querySelector("#progress-bar");
  585. return pbEl.value ?? null;
  586. }
  587. else if(domain === "yt") // YT doesn't update the progress bar when it's hidden (YTM doesn't hide it) so TODO: come up with some solution here
  588. return 0;
  589. return null;
  590. }
  591. catch(err)
  592. {
  593. console.error("BetterYTM: Couldn't get video time due to error:", err);
  594. return null;
  595. }
  596. }
  597. /**
  598. * Inserts `afterNode` as a sibling just after the provided `beforeNode`
  599. * @param {HTMLElement} beforeNode
  600. * @param {HTMLElement} afterNode
  601. * @returns {HTMLElement} Returns the `afterNode`
  602. */
  603. function insertAfter(beforeNode, afterNode)
  604. {
  605. beforeNode.parentNode.insertBefore(afterNode, beforeNode.nextSibling);
  606. return afterNode;
  607. }
  608. /**
  609. * Adds global CSS style through a &lt;style&gt; element in the document's &lt;head&gt;
  610. * @param {string} style CSS string
  611. * @param {string} ref Reference name that is included in the &lt;style&gt;'s ID
  612. */
  613. function addGlobalStyle(style, ref)
  614. {
  615. const styleElem = document.createElement("style");
  616. styleElem.id = `betterytm-${ref}-style`;
  617. if(styleElem.styleSheet)
  618. styleElem.styleSheet.cssText = style;
  619. else
  620. styleElem.appendChild(document.createTextNode(style));
  621. document.querySelector("head").appendChild(styleElem);
  622. dbg && console.log(`BetterYTM: Inserted global style with ref '${ref}':`, styleElem);
  623. }
  624. /**
  625. * Loads a feature configuration saved persistently, returns an empty object if no feature configuration was saved
  626. * @returns {Promise<Readonly<typeof defaultFeatures | {}>>}
  627. */
  628. async function loadFeatureConf()
  629. {
  630. /** @type {string} */
  631. const featureConf = await GM.getValue("bytm-featureconf"); // eslint-disable-line no-undef
  632. return Object.freeze(featureConf ? JSON.parse(featureConf) : {});
  633. }
  634. /**
  635. * Saves a feature configuration saved persistently
  636. * @param {typeof defaultFeatures} featureConf
  637. * @returns {Promise<void>}
  638. */
  639. function saveFeatureConf(featureConf)
  640. {
  641. if(!featureConf || typeof featureConf != "object")
  642. throw new TypeError("Feature config not provided or invalid");
  643. return GM.setValue("bytm-featureconf", JSON.stringify(featureConf)); // eslint-disable-line no-undef
  644. }
  645. init(); // call init() when script is loaded
  646. })();