Просмотр исходного кода

ref: dedicated func for creating style elem from resources

Sven 11 месяцев назад
Родитель
Сommit
c687ff0bda
7 измененных файлов с 48 добавлено и 34 удалено
  1. 9 16
      src/features/layout.ts
  2. 3 3
      src/features/lyrics.ts
  3. 2 2
      src/features/lyricsCache.ts
  4. 4 9
      src/index.ts
  5. 1 1
      src/types.ts
  6. 12 1
      src/utils/dom.ts
  7. 17 2
      src/utils/xhr.ts

+ 9 - 16
src/features/layout.ts

@@ -2,7 +2,7 @@ import { addParent, autoPlural, debounce, fetchAdvanced, insertAfter, pauseFor }
 import { getFeatures } from "../config";
 import { siteEvents } from "../siteEvents";
 import { addSelectorListener } from "../observers";
-import { error, getResourceUrl, log, warn, t, onInteraction, openInTab, getBestThumbnailUrl, getDomain, addStyle, currentMediaType, domLoaded, waitVideoElementReady, hdrEnabled, getVideoTime, insertBefore } from "../utils";
+import { error, getResourceUrl, log, warn, t, onInteraction, openInTab, getBestThumbnailUrl, getDomain, addStyle, currentMediaType, domLoaded, waitVideoElementReady, hdrEnabled, getVideoTime, insertBefore, fetchCss, addStyleFromResource } from "../utils";
 import { scriptInfo } from "../constants";
 import { openCfgMenu } from "../menu/menu_old";
 import { createCircularBtn } from "../components";
@@ -198,7 +198,7 @@ export async function removeUpgradeTab() {
 /** Adds anchors around elements and tweaks existing ones so songs are easier to open in a new tab */
 export async function addAnchorImprovements() {
   try {
-    const css = await (await fetchAdvanced(await getResourceUrl("css-anchor_improvements"))).text();
+    const css = await fetchCss("css-anchor_improvements");
     if(css)
       addStyle(css, "anchor-improvements");
   }
@@ -373,14 +373,8 @@ export async function initRemShareTrackParam() {
 
 /** Applies global CSS to fix various spacings */
 export async function fixSpacing() {
-  try {
-    const css = await (await fetchAdvanced(await getResourceUrl("css-fix_spacing"))).text();
-    if(css)
-      addStyle(css, "fix-spacing");
-  }
-  catch(err) {
-    error("Couldn't fix spacing due to an error:", err);
-  }
+  if(!await addStyleFromResource("css-fix_spacing"))
+    error("Couldn't fix spacing");
 }
 
 //#region above queue btns
@@ -447,8 +441,8 @@ export async function addAboveQueueBtns() {
       ];
 
       if(contBtns.some(b => Boolean(b.condition))) {
-        const css = await (await fetchAdvanced(await getResourceUrl("css-above_queue_btns"))).text();
-        css && addStyle(css, "above-queue-btns");
+        if(!await addStyleFromResource("css-above_queue_btns"))
+          error("Couldn't add CSS for above queue buttons");
 
         const wrapperElem = document.createElement("div");
         wrapperElem.id = "bytm-above-queue-btn-wrapper";
@@ -715,9 +709,8 @@ export async function initHideCursorOnIdle() {
 export async function fixHdrIssues() {
   if(!hdrEnabled())
     return log("HDR is not enabled, skipping HDR fixes");
-  const css = await (await fetchAdvanced(await getResourceUrl("css-fix_hdr"))).text();
-  if(css) {
-    addStyle(css, "fix-hdr");
+  if(!await addStyleFromResource("css-fix_hdr"))
+    error("Couldn't fix HDR issues");
+  else
     log("Fixed HDR issues");
-  }
 }

+ 3 - 3
src/features/lyrics.ts

@@ -1,6 +1,6 @@
 import { autoPlural, fetchAdvanced, insertAfter } from "@sv443-network/userutils";
 import Fuse from "fuse.js";
-import { constructUrlString, error, getResourceUrl, info, log, warn, t, tp, currentMediaType } from "../utils";
+import { error, getResourceUrl, info, log, warn, t, tp, currentMediaType, constructUrl } from "../utils";
 import { emitInterface } from "../interface";
 import { mode, scriptInfo } from "../constants";
 import { getFeature } from "../config";
@@ -221,7 +221,7 @@ export async function fetchLyricsUrls(artist: string, song: string): Promise<Omi
     }
 
     const startTs = Date.now();
-    const fetchUrl = constructUrlString(`${getFeature("geniUrlBase")}/search`, {
+    const fetchUrl = constructUrl(`${getFeature("geniUrlBase")}/search`, {
       disableFuzzy: null,
       utm_source: scriptInfo.name,
       utm_content: `v${scriptInfo.version}${mode === "development" ? "-dev" : ""}`,
@@ -229,7 +229,7 @@ export async function fetchLyricsUrls(artist: string, song: string): Promise<Omi
       song,
     });
 
-    log(`Requesting URLs from geniURL at '${fetchUrl}'`);
+    log("Requesting lyrics from geniURL:", fetchUrl);
 
     const token = getFeature("geniUrlToken");
     const fetchRes = await fetchAdvanced(fetchUrl, {

+ 2 - 2
src/features/lyricsCache.ts

@@ -123,8 +123,8 @@ export function addLyricsCacheEntryBest(artist: string, song: string, url: strin
  * Adds the provided entry into the lyrics URL cache, synchronously to RAM and asynchronously to GM storage  
  * Also adds a penalty to the viewed timestamp and added timestamp to decrease entry's lifespan in cache  
  *   
- * ⚠️ {@linkcode artist} and {@linkcode song} need to be sanitized first!
- * @param penaltyFr Fraction to remove from the timestamp values - has to be between 0 and 1 - default is 0 (no penalty) - (0.25 = only penalized by a quarter of the predefined max penalty)
+ * ⚠️ `artist` and `song` need to be sanitized first!
+ * @param penaltyFr Fraction of the max bounds {@linkcode maxViewedPenalty} and {@linkcode maxAddedPenalty} to remove from the timestamp values - has to be between 0 and 1 - default is 0 (no penalty) - (0.25 = only penalized by a quarter of the max penalty)
  */
 export function addLyricsCacheEntryPenalized(artist: string, song: string, url: string, penaltyFr = 0) {
   // refresh entry if it exists and don't overwrite / duplicate it

+ 4 - 9
src/index.ts

@@ -1,5 +1,5 @@
-import { compress, decompress, fetchAdvanced, type Stringifiable } from "@sv443-network/userutils";
-import { addStyle, domLoaded, getResourceUrl, reserialize, warn } from "./utils";
+import { compress, decompress, type Stringifiable } from "@sv443-network/userutils";
+import { addStyleFromResource, domLoaded, reserialize, warn } from "./utils";
 import { clearConfig, defaultData as defaultFeatData, getFeatures, initConfig, setFeatures } from "./config";
 import { buildNumber, compressionFormat, defaultLogLevel, mode, scriptInfo } from "./constants";
 import { error, getDomain, info, getSessionId, log, setLogLevel, initTranslations, setLocale } from "./utils";
@@ -337,13 +337,8 @@ async function onDomLoad() {
 
 /** Inserts the bundled CSS files imported throughout the script into a <style> element in the <head> */
 async function insertGlobalStyle() {
-  try {
-    const css = await (await fetchAdvanced(await getResourceUrl("css-bundle"))).text();
-    css && addStyle(css, "bundle");
-  }
-  catch(err) {
-    error("Couldn't add global CSS bundle due to an error:", err);
-  }
+  if(!await addStyleFromResource("css-bundle"))
+    error("Couldn't add global CSS bundle due to an error");
 }
 
 /** Registers dev commands using `GM.registerMenuCommand` */

+ 1 - 1
src/types.ts

@@ -287,7 +287,7 @@ type FeatureFuncProps = (
 
 /**
  * The feature info object that contains all properties necessary to construct the config menu and the feature config object.  
- * Values are loosely typed so try to only use this with the `satisfies` keyword.  
+ * All values are loosely typed so try to only use this with the `satisfies` keyword.  
  * Use `typeof featInfo` (from `src/features/index.ts`) instead for full type safety.
  */
 export type FeatureInfo = Record<

+ 12 - 1
src/utils/dom.ts

@@ -1,6 +1,7 @@
 import { addGlobalStyle, getUnsafeWindow, randomId } from "@sv443-network/userutils";
-import { error, getDomain } from ".";
+import { error, fetchCss, getDomain } from ".";
 import { addSelectorListener } from "src/observers";
+import type { ResourceKey } from "src/types";
 
 //#region video time, volume
 
@@ -191,3 +192,13 @@ export function insertBefore(afterElement: Element, beforeElement: Element) {
   afterElement.parentNode?.insertBefore(beforeElement, afterElement);
   return beforeElement;
 }
+
+/** Adds a global style element with the contents of the specified CSS resource */
+export async function addStyleFromResource(key: ResourceKey & `css-${string}`) {
+  const css = await fetchCss(key);
+  if(css) {
+    addStyle(css, key.slice(4));
+    return true;
+  }
+  return false;
+}

+ 17 - 2
src/utils/xhr.ts

@@ -1,4 +1,7 @@
-import type { Stringifiable } from "@sv443-network/userutils";
+import { fetchAdvanced, type Stringifiable } from "@sv443-network/userutils";
+import type { ResourceKey } from "src/types";
+import { getResourceUrl } from "./misc";
+import { error } from "./logging";
 
 /**
  * Constructs a URL from a base URL and a record of query parameters.  
@@ -16,7 +19,7 @@ export function constructUrlString(baseUrl: string, params: Record<string, Strin
 }
 
 /**
- * Constructs a URL from a base URL and a record of query parameters.  
+ * Constructs a URL object from a base URL and a record of query parameters.  
  * If a value is null, the parameter will be valueless.  
  * All values will be URI-encoded.  
  * @returns Returns a URL object instead of a string
@@ -41,3 +44,15 @@ export function sendRequest<T = any>(details: GM.Request<T>) {
     });
   });
 }
+
+/** Fetches a CSS file from the specified resource with a key starting with `css-` */
+export async function fetchCss(key: ResourceKey & `css-${string}`) {
+  try {
+    const css = await (await fetchAdvanced(await getResourceUrl(key))).text();
+    return css ?? undefined;
+  }
+  catch(err) {
+    error("Couldn't fetch CSS due to an error:", err);
+    return undefined;
+  }
+}