Ver Fonte

ref: remove timer-based DOM operations

Sv443 há 1 ano atrás
pai
commit
3db6e17540
4 ficheiros alterados com 20 adições e 50 exclusões
  1. 0 5
      src/constants.ts
  2. 10 17
      src/features/layout.ts
  3. 6 15
      src/features/lyrics.ts
  4. 4 13
      src/features/menu/menu.ts

+ 0 - 5
src/constants.ts

@@ -14,11 +14,6 @@ export const branch = branchRaw.match(/^{{.+}}$/) ? "main" : branchRaw;
  */
 export const logLevel: LogLevel = mode === "production" ? 1 : 0;
 
-/** Specifies the hard limit for repetitive tasks */
-export const triesLimit = 50;
-/** Specifies the interval in ms for repetitive tasks */
-export const triesInterval = 200;
-
 /** Info about the userscript, parsed from the userscript header (tools/post-build.js) */
 export const scriptInfo = Object.freeze({
   name: GM.info.script.name,

+ 10 - 17
src/features/layout.ts

@@ -1,8 +1,8 @@
 import type { Event } from "@billjs/event-emitter";
 import type { FeatureConfig } from "../types";
-import { scriptInfo, triesInterval, triesLimit } from "../constants";
+import { scriptInfo } from "../constants";
 import { getFeatures } from "../config";
-import { addGlobalStyle, autoPlural, error, getAssetUrl, insertAfter, log, openInNewTab, pauseFor } from "../utils";
+import { addGlobalStyle, autoPlural, error, getAssetUrl, insertAfter, log, onSelectorExists, openInNewTab, pauseFor } from "../utils";
 import { getEvtData, siteEvents } from "../events";
 import { openMenu } from "./menu/menu_old";
 import { getGeniusUrl, createLyricsBtn, sanitizeArtists, sanitizeSong, getLyricsCacheEntry } from "./lyrics";
@@ -73,23 +73,16 @@ export function addConfigMenuOption(container: HTMLElement) {
 
 //#MARKER remove upgrade tab
 
-let removeUpgradeTries = 0;
-
 /** Removes the "Upgrade" / YT Music Premium tab from the title / nav bar */
 export function removeUpgradeTab() {
-  const tabElem = document.querySelector("ytmusic-app-layout tp-yt-app-drawer #contentContainer #guide-content #items ytmusic-guide-entry-renderer:nth-child(4)");
-  const tabElemMini = document.querySelector("ytmusic-app-layout #mini-guide ytmusic-guide-renderer #sections ytmusic-guide-section-renderer #items ytmusic-guide-entry-renderer:nth-child(4)");
-  if(tabElem || tabElemMini) {
-    tabElem && tabElem.remove();
-    tabElemMini && tabElemMini.remove();
-    log(`Removed upgrade tab after ${removeUpgradeTries} tries`);
-  }
-  else if(removeUpgradeTries < triesLimit) {
-    setTimeout(removeUpgradeTab, triesInterval); // TODO: improve this
-    removeUpgradeTries++;
-  }
-  else
-    error(`Couldn't find upgrade tab to remove after ${removeUpgradeTries} tries`);
+  onSelectorExists("ytmusic-app-layout tp-yt-app-drawer #contentContainer #guide-content #items ytmusic-guide-entry-renderer:nth-child(4)", (tabElemLarge) => {
+    tabElemLarge.remove();
+    log("Removed large upgrade tab");
+  });
+  onSelectorExists("ytmusic-app-layout #mini-guide ytmusic-guide-renderer #sections ytmusic-guide-section-renderer #items ytmusic-guide-entry-renderer:nth-child(4)", (tabElemSmall) => {
+    tabElemSmall.remove();
+    log("Removed small upgrade tab");
+  });
 }
 
 //#MARKER volume slider

+ 6 - 15
src/features/lyrics.ts

@@ -1,5 +1,4 @@
-import { triesInterval, triesLimit } from "../constants";
-import { clamp, error, getAssetUrl, info, insertAfter, log } from "../utils";
+import { clamp, error, getAssetUrl, info, insertAfter, log, onSelectorExists } from "../utils";
 
 /** Base URL of geniURL */
 export const geniUrlBase = "https://api.sv443.net/geniurl";
@@ -42,22 +41,14 @@ export function addLyricsCacheEntry(artists: string, song: string, lyricsUrl: st
 //#MARKER media control bar
 
 let mcCurrentSongTitle = "";
-let mcLyricsButtonAddTries = 0;
 
 /** Adds a lyrics button to the media controls bar */
 export function addMediaCtrlLyricsBtn(): void {
-  const likeContainer = document.querySelector(".middle-controls-buttons ytmusic-like-button-renderer#like-button-renderer") as HTMLElement;
-
-  if(!likeContainer) {
-    mcLyricsButtonAddTries++;
-    if(mcLyricsButtonAddTries < triesLimit) {
-      setTimeout(addMediaCtrlLyricsBtn, triesInterval); // TODO: improve this
-      return;
-    }
-
-    return error(`Couldn't find element to append lyrics buttons to after ${mcLyricsButtonAddTries} tries`);
-  }
+  onSelectorExists(".middle-controls-buttons ytmusic-like-button-renderer#like-button-renderer", addActualMediaCtrlLyricsBtn);
+}
 
+/** Actually adds the lyrics button after the like button renderer has been verified to exist */
+function addActualMediaCtrlLyricsBtn(likeContainer: HTMLElement) {
   const songTitleElem = document.querySelector(".content-info-wrapper > yt-formatted-string") as HTMLDivElement;
 
   // run parallel without awaiting so the MutationObserver below can observe the title element in time
@@ -67,7 +58,7 @@ export function addMediaCtrlLyricsBtn(): void {
     const linkElem = createLyricsBtn(gUrl ?? undefined);
     linkElem.id = "betterytm-lyrics-button";
 
-    log(`Inserted lyrics button after ${mcLyricsButtonAddTries} tries:`, linkElem);
+    log("Inserted lyrics button into media controls bar");
 
     insertAfter(likeContainer, linkElem);
   })();

+ 4 - 13
src/features/menu/menu.ts

@@ -1,5 +1,3 @@
-import { triesInterval, triesLimit } from "../../constants";
-import { error } from "../../utils";
 import changelogContent from "../../../changelog.md";
 import menuContent from "./menu.html";
 import "./menu.css";
@@ -31,14 +29,7 @@ export function initMenu() {
   });
 }
 
-let menuContTries = 0;
-
-function initMenuContents(): unknown {
-  if(!document.querySelector("#bytm-menu-dialog"))
-    return menuContTries++ < triesLimit
-      ? setTimeout(initMenuContents, triesInterval)
-      : error(`couldn't create menu element after ${triesLimit} tries.`);
-
+function initMenuContents() {
   // hook events
   for(const tab in tabsSelectors) {
     const selector = tabsSelectors[tab as keyof typeof tabsSelectors];
@@ -58,9 +49,9 @@ export function setActiveTab(tab: keyof typeof tabsSelectors) {
   const tabs = { ...tabsSelectors };
   delete tabs[tab];
   // disable all but new active tab
-  for(const disableTab of Object.keys(tabs)) {
-    (document.querySelector(`#${tabs[disableTab as keyof typeof tabs]}-header`) as HTMLElement).dataset.active = "false";
-    (document.querySelector(`#${tabs[disableTab as keyof typeof tabs]}-content`) as HTMLElement).dataset.active = "false";
+  for(const [, val] of Object.entries(tabs)) {
+    (document.querySelector(`#${val}-header`) as HTMLElement).dataset.active = "false";
+    (document.querySelector(`#${val}-content`) as HTMLElement).dataset.active = "false";
   }
   // enable new active tab
   (document.querySelector(`#${tabsSelectors[tab]}-header`) as HTMLElement).dataset.active = "true";