menu_old.ts 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852
  1. import { debounce, isScrollable, type Stringifiable } from "@sv443-network/userutils";
  2. import { defaultData, getFeatures, setFeatures, setDefaultFeatures } from "../config";
  3. import { buildNumber, host, mode, scriptInfo } from "../constants";
  4. import { featInfo, disableBeforeUnload } from "../features/index";
  5. import { error, getResourceUrl, info, log, resourceToHTMLString, getLocale, hasKey, initTranslations, setLocale, t, arrayWithSeparators, tp, type TrKey, onInteraction, getDomain, copyToClipboard } from "../utils";
  6. import { siteEvents } from "../siteEvents";
  7. import { getChangelogDialog, getExportDialog, getFeatHelpDialog, getImportDialog } from "../dialogs";
  8. import type { FeatureCategory, FeatureKey, FeatureConfig, HotkeyObj, FeatureInfo } from "../types";
  9. import "./menu_old.css";
  10. import { createHotkeyInput, createToggleInput } from "../components";
  11. import pkg from "../../package.json" assert { type: "json" };
  12. //#region create menu
  13. let isCfgMenuAdded = false;
  14. export let isCfgMenuOpen = false;
  15. /** Threshold in pixels from the top of the options container that dictates for how long the scroll indicator is shown */
  16. const scrollIndicatorOffsetThreshold = 30;
  17. let scrollIndicatorEnabled = true;
  18. /** Locale at the point of initializing the config menu */
  19. let initLocale: string | undefined;
  20. /** Stringified config at the point of initializing the config menu */
  21. let initConfig: FeatureConfig | undefined;
  22. /** Timeout id for the "copied" text in the hidden value copy button */
  23. let hiddenCopiedTxtTimeout: ReturnType<typeof setTimeout> | undefined;
  24. /**
  25. * Adds an element to open the BetterYTM menu
  26. * @deprecated to be replaced with new menu - see https://github.com/Sv443/BetterYTM/issues/23
  27. */
  28. async function addCfgMenu() {
  29. if(isCfgMenuAdded)
  30. return;
  31. isCfgMenuAdded = true;
  32. initLocale = getFeatures().locale;
  33. initConfig = getFeatures();
  34. const initLangReloadText = t("lang_changed_prompt_reload");
  35. //#region bg & container
  36. const backgroundElem = document.createElement("div");
  37. backgroundElem.id = "bytm-cfg-menu-bg";
  38. backgroundElem.classList.add("bytm-menu-bg", `bytm-dom-${getDomain()}`);
  39. backgroundElem.ariaLabel = backgroundElem.title = t("close_menu_tooltip");
  40. backgroundElem.style.visibility = "hidden";
  41. backgroundElem.style.display = "none";
  42. backgroundElem.addEventListener("click", (e) => {
  43. if(isCfgMenuOpen && (e.target as HTMLElement)?.id === "bytm-cfg-menu-bg")
  44. closeCfgMenu(e);
  45. });
  46. document.body.addEventListener("keydown", (e) => {
  47. if(isCfgMenuOpen && e.key === "Escape")
  48. closeCfgMenu(e);
  49. });
  50. const menuContainer = document.createElement("div");
  51. menuContainer.ariaLabel = menuContainer.title = ""; // prevent bg title from propagating downwards
  52. menuContainer.classList.add("bytm-menu", `bytm-dom-${getDomain()}`);
  53. menuContainer.id = "bytm-cfg-menu";
  54. //#region title bar
  55. const headerElem = document.createElement("div");
  56. headerElem.classList.add("bytm-menu-header");
  57. const titleCont = document.createElement("div");
  58. titleCont.classList.add("bytm-menu-titlecont");
  59. titleCont.role = "heading";
  60. titleCont.ariaLevel = "1";
  61. const titleElem = document.createElement("h2");
  62. titleElem.classList.add("bytm-menu-title");
  63. const titleTextElem = document.createElement("div");
  64. titleTextElem.textContent = t("config_menu_title", scriptInfo.name);
  65. titleElem.appendChild(titleTextElem);
  66. const linksCont = document.createElement("div");
  67. linksCont.id = "bytm-menu-linkscont";
  68. linksCont.role = "navigation";
  69. const linkTitlesShort = {
  70. github: "GitHub",
  71. greasyfork: "GreasyFork",
  72. openuserjs: "OpenUserJS",
  73. discord: "Discord",
  74. };
  75. const addLink = (imgSrc: string, href: string, title: string, titleKey: keyof typeof linkTitlesShort) => {
  76. const anchorElem = document.createElement("a");
  77. anchorElem.classList.add("bytm-menu-link", "bytm-no-select");
  78. anchorElem.rel = "noopener noreferrer";
  79. anchorElem.href = href;
  80. anchorElem.target = "_blank";
  81. anchorElem.tabIndex = 0;
  82. anchorElem.role = "button";
  83. anchorElem.ariaLabel = anchorElem.title = title;
  84. const extendedAnchorEl = document.createElement("a");
  85. extendedAnchorEl.classList.add("bytm-menu-link", "extended-link", "bytm-no-select");
  86. extendedAnchorEl.rel = "noopener noreferrer";
  87. extendedAnchorEl.href = href;
  88. extendedAnchorEl.target = "_blank";
  89. extendedAnchorEl.tabIndex = -1;
  90. extendedAnchorEl.textContent = linkTitlesShort[titleKey];
  91. extendedAnchorEl.ariaLabel = extendedAnchorEl.title = title;
  92. const imgElem = document.createElement("img");
  93. imgElem.classList.add("bytm-menu-img");
  94. imgElem.src = imgSrc;
  95. anchorElem.appendChild(imgElem);
  96. anchorElem.appendChild(extendedAnchorEl);
  97. linksCont.appendChild(anchorElem);
  98. };
  99. const links: [name: string, ...Parameters<typeof addLink>][] = [
  100. ["github", await getResourceUrl("img-github"), scriptInfo.namespace, t("open_github", scriptInfo.name), "github"],
  101. ["greasyfork", await getResourceUrl("img-greasyfork"), pkg.hosts.greasyfork, t("open_greasyfork", scriptInfo.name), "greasyfork"],
  102. ["openuserjs", await getResourceUrl("img-openuserjs"), pkg.hosts.openuserjs, t("open_openuserjs", scriptInfo.name), "openuserjs"],
  103. ];
  104. const hostLink = links.find(([name]) => name === host);
  105. const otherLinks = links.filter(([name]) => name !== host);
  106. const reorderedLinks = hostLink ? [hostLink, ...otherLinks] : links;
  107. for(const [, ...args] of reorderedLinks)
  108. addLink(...args);
  109. addLink(await getResourceUrl("img-discord"), "https://dc.sv443.net/", t("open_discord"), "discord");
  110. const closeElem = document.createElement("img");
  111. closeElem.classList.add("bytm-menu-close");
  112. closeElem.role = "button";
  113. closeElem.tabIndex = 0;
  114. closeElem.src = await getResourceUrl("img-close");
  115. closeElem.ariaLabel = closeElem.title = t("close_menu_tooltip");
  116. onInteraction(closeElem, closeCfgMenu);
  117. titleCont.appendChild(titleElem);
  118. titleCont.appendChild(linksCont);
  119. headerElem.appendChild(titleCont);
  120. headerElem.appendChild(closeElem);
  121. //#region footer
  122. const footerCont = document.createElement("div");
  123. footerCont.classList.add("bytm-menu-footer-cont");
  124. const reloadFooterCont = document.createElement("div");
  125. const reloadFooterEl = document.createElement("div");
  126. reloadFooterEl.classList.add("bytm-menu-footer", "hidden");
  127. reloadFooterEl.setAttribute("aria-hidden", "true");
  128. reloadFooterEl.textContent = t("reload_hint");
  129. reloadFooterEl.role = "alert";
  130. const reloadTxtEl = document.createElement("button");
  131. reloadTxtEl.classList.add("bytm-btn");
  132. reloadTxtEl.style.marginLeft = "10px";
  133. reloadTxtEl.textContent = t("reload_now");
  134. reloadTxtEl.ariaLabel = reloadTxtEl.title = t("reload_tooltip");
  135. reloadTxtEl.addEventListener("click", () => {
  136. closeCfgMenu();
  137. disableBeforeUnload();
  138. location.reload();
  139. });
  140. reloadFooterEl.appendChild(reloadTxtEl);
  141. reloadFooterCont.appendChild(reloadFooterEl);
  142. const resetElem = document.createElement("button");
  143. resetElem.classList.add("bytm-btn");
  144. resetElem.ariaLabel = resetElem.title = t("reset_tooltip");
  145. resetElem.textContent = t("reset");
  146. resetElem.addEventListener("click", async () => {
  147. if(confirm(t("reset_confirm"))) {
  148. await setDefaultFeatures();
  149. closeCfgMenu();
  150. disableBeforeUnload();
  151. location.reload();
  152. }
  153. });
  154. const exportElem = document.createElement("button");
  155. exportElem.classList.add("bytm-btn");
  156. exportElem.ariaLabel = exportElem.title = t("export_tooltip");
  157. exportElem.textContent = t("export");
  158. exportElem.addEventListener("click", async () => {
  159. const dlg = await getExportDialog();
  160. dlg.on("close", openCfgMenu);
  161. await dlg.mount();
  162. closeCfgMenu(undefined, false);
  163. await dlg.open();
  164. });
  165. const importElem = document.createElement("button");
  166. importElem.classList.add("bytm-btn");
  167. importElem.ariaLabel = importElem.title = t("import_tooltip");
  168. importElem.textContent = t("import");
  169. importElem.addEventListener("click", async () => {
  170. const dlg = await getImportDialog();
  171. dlg.on("close", openCfgMenu);
  172. await dlg.mount();
  173. closeCfgMenu(undefined, false);
  174. await dlg.open();
  175. });
  176. const buttonsCont = document.createElement("div");
  177. buttonsCont.id = "bytm-menu-footer-buttons-cont";
  178. buttonsCont.appendChild(exportElem);
  179. buttonsCont.appendChild(importElem);
  180. buttonsCont.appendChild(resetElem);
  181. footerCont.appendChild(reloadFooterCont);
  182. footerCont.appendChild(buttonsCont);
  183. //#region feature list
  184. const featuresCont = document.createElement("div");
  185. featuresCont.id = "bytm-menu-opts";
  186. const onCfgChange = async (key: keyof typeof defaultData, initialVal: string | number | boolean | HotkeyObj, newVal: string | number | boolean | HotkeyObj) => {
  187. const fmt = (val: unknown) => typeof val === "object" ? JSON.stringify(val) : String(val);
  188. info(`Feature config changed at key '${key}', from value '${fmt(initialVal)}' to '${fmt(newVal)}'`);
  189. const featConf = JSON.parse(JSON.stringify(getFeatures())) as FeatureConfig;
  190. featConf[key] = newVal as never;
  191. const changedKeys = initConfig ? Object.keys(featConf).filter((k) =>
  192. typeof featConf[k as FeatureKey] !== "object"
  193. && featConf[k as FeatureKey] !== initConfig![k as FeatureKey]
  194. ) : [];
  195. const requiresReload =
  196. // @ts-ignore
  197. changedKeys.some((k) => featInfo[k as keyof typeof featInfo]?.reloadRequired !== false);
  198. await setFeatures(featConf);
  199. // @ts-ignore
  200. featInfo[key]?.change?.(key, initialVal, newVal);
  201. if(requiresReload) {
  202. reloadFooterEl.classList.remove("hidden");
  203. reloadFooterEl.setAttribute("aria-hidden", "false");
  204. }
  205. else if(!requiresReload) {
  206. reloadFooterEl.classList.add("hidden");
  207. reloadFooterEl.setAttribute("aria-hidden", "true");
  208. }
  209. if(initLocale !== featConf.locale) {
  210. await initTranslations(featConf.locale);
  211. setLocale(featConf.locale);
  212. const newText = t("lang_changed_prompt_reload");
  213. const confirmText = newText !== initLangReloadText ? `${newText}\n\n────────────────────────────────\n\n${initLangReloadText}` : newText;
  214. if(confirm(confirmText)) {
  215. closeCfgMenu();
  216. disableBeforeUnload();
  217. location.reload();
  218. }
  219. }
  220. else if(getLocale() !== featConf.locale)
  221. setLocale(featConf.locale);
  222. siteEvents.emit("configOptionChanged", key, initialVal, newVal);
  223. };
  224. /** Call whenever the feature config is changed */
  225. const confChanged = debounce(onCfgChange, 200, "falling");
  226. const featureCfg = getFeatures();
  227. const featureCfgWithCategories = Object.entries(featInfo)
  228. .reduce(
  229. (acc, [key, { category }]) => {
  230. if(!acc[category])
  231. acc[category] = {} as Record<FeatureKey, unknown>;
  232. acc[category][key as FeatureKey] = featureCfg[key as FeatureKey];
  233. return acc;
  234. },
  235. {} as Record<FeatureCategory, Record<FeatureKey, unknown>>,
  236. );
  237. const fmtVal = (v: unknown, key: FeatureKey) => {
  238. try {
  239. // @ts-ignore
  240. const renderValue = typeof featInfo?.[key]?.renderValue === "function" ? featInfo[key].renderValue : undefined;
  241. const retVal = (typeof v === "object" ? JSON.stringify(v) : String(v)).trim();
  242. return renderValue ? renderValue(retVal) : retVal;
  243. }
  244. catch(_e) {
  245. // because stringify throws on circular refs
  246. return String(v).trim();
  247. }
  248. };
  249. for(const category in featureCfgWithCategories) {
  250. const featObj = featureCfgWithCategories[category as FeatureCategory];
  251. const catHeaderElem = document.createElement("h3");
  252. catHeaderElem.classList.add("bytm-ftconf-category-header");
  253. catHeaderElem.role = "heading";
  254. catHeaderElem.ariaLevel = "2";
  255. catHeaderElem.tabIndex = 0;
  256. catHeaderElem.textContent = `${t(`feature_category_${category}`)}:`;
  257. featuresCont.appendChild(catHeaderElem);
  258. for(const featKey in featObj) {
  259. const ftInfo = featInfo[featKey as FeatureKey] as FeatureInfo[keyof typeof featureCfg];
  260. if(!ftInfo || ("hidden" in ftInfo && ftInfo.hidden === true))
  261. continue;
  262. if(ftInfo.advanced && !featureCfg.advancedMode)
  263. continue;
  264. const { type, default: ftDefault } = ftInfo;
  265. const step = "step" in ftInfo ? ftInfo.step : undefined;
  266. const val = featureCfg[featKey as FeatureKey];
  267. const initialVal = val ?? ftDefault ?? undefined;
  268. const ftConfElem = document.createElement("div");
  269. ftConfElem.classList.add("bytm-ftitem");
  270. {
  271. const featLeftSideElem = document.createElement("div");
  272. featLeftSideElem.classList.add("bytm-ftitem-leftside");
  273. if(getFeatures().advancedMode) {
  274. const defVal = fmtVal(ftDefault, featKey as FeatureKey);
  275. const extraTxts = [
  276. `default: ${defVal.length === 0 ? "(undefined)" : defVal}`,
  277. ];
  278. "min" in ftInfo && extraTxts.push(`min: ${ftInfo.min}`);
  279. "max" in ftInfo && extraTxts.push(`max: ${ftInfo.max}`);
  280. "step" in ftInfo && extraTxts.push(`step: ${ftInfo.step}`);
  281. const rel = "reloadRequired" in ftInfo && ftInfo.reloadRequired !== false ? " (reload required)" : "";
  282. const adv = ftInfo.advanced ? " (advanced feature)" : "";
  283. featLeftSideElem.title = `${featKey}${rel}${adv}${extraTxts.length > 0 ? `\n${extraTxts.join(" - ")}` : ""}`;
  284. }
  285. const textElem = document.createElement("span");
  286. textElem.tabIndex = 0;
  287. textElem.textContent = t(`feature_desc_${featKey}`);
  288. let adornmentElem: undefined | HTMLElement;
  289. const adornContent = ftInfo.textAdornment?.();
  290. const adornContentAw = adornContent instanceof Promise ? await adornContent : adornContent;
  291. if((typeof adornContent === "string" || adornContent instanceof Promise) && typeof adornContentAw !== "undefined") {
  292. adornmentElem = document.createElement("span");
  293. adornmentElem.id = `bytm-ftitem-${featKey}-adornment`;
  294. adornmentElem.classList.add("bytm-ftitem-adornment");
  295. adornmentElem.innerHTML = adornContentAw;
  296. }
  297. let helpElem: undefined | HTMLDivElement;
  298. // @ts-ignore
  299. const hasHelpTextFunc = typeof featInfo[featKey as keyof typeof featInfo]?.helpText === "function";
  300. // @ts-ignore
  301. const helpTextVal: string | undefined = hasHelpTextFunc && featInfo[featKey as keyof typeof featInfo]!.helpText();
  302. if(hasKey(`feature_helptext_${featKey}`) || (helpTextVal && hasKey(helpTextVal))) {
  303. const helpElemImgHtml = await resourceToHTMLString("icon-help");
  304. if(helpElemImgHtml) {
  305. helpElem = document.createElement("div");
  306. helpElem.classList.add("bytm-ftitem-help-btn", "bytm-generic-btn");
  307. helpElem.ariaLabel = helpElem.title = t("feature_help_button_tooltip");
  308. helpElem.role = "button";
  309. helpElem.tabIndex = 0;
  310. helpElem.innerHTML = helpElemImgHtml;
  311. onInteraction(helpElem, async (e: MouseEvent | KeyboardEvent) => {
  312. e.preventDefault();
  313. e.stopPropagation();
  314. await (await getFeatHelpDialog({ featKey: featKey as FeatureKey })).open();
  315. });
  316. }
  317. else {
  318. error(`Couldn't create help button SVG element for feature '${featKey}'`);
  319. }
  320. }
  321. adornmentElem && featLeftSideElem.appendChild(adornmentElem);
  322. featLeftSideElem.appendChild(textElem);
  323. helpElem && featLeftSideElem.appendChild(helpElem);
  324. ftConfElem.appendChild(featLeftSideElem);
  325. }
  326. {
  327. let inputType: string | undefined = "text";
  328. let inputTag: string | undefined = "input";
  329. switch(type)
  330. {
  331. case "toggle":
  332. inputTag = undefined;
  333. inputType = undefined;
  334. break;
  335. case "slider":
  336. inputType = "range";
  337. break;
  338. case "number":
  339. inputType = "number";
  340. break;
  341. case "text":
  342. inputType = "text";
  343. break;
  344. case "select":
  345. inputTag = "select";
  346. inputType = undefined;
  347. break;
  348. case "hotkey":
  349. inputTag = undefined;
  350. inputType = undefined;
  351. break;
  352. case "button":
  353. inputTag = undefined;
  354. inputType = undefined;
  355. break;
  356. }
  357. const inputElemId = `bytm-ftconf-${featKey}-input`;
  358. const ctrlElem = document.createElement("span");
  359. ctrlElem.classList.add("bytm-ftconf-ctrl");
  360. let advCopyHiddenCont: HTMLElement | undefined;
  361. if((getFeatures().advancedMode || mode === "development") && ftInfo.valueHidden) {
  362. const advCopyHintElem = document.createElement("span");
  363. advCopyHintElem.classList.add("bytm-ftconf-adv-copy-hint");
  364. advCopyHintElem.textContent = t("copied");
  365. advCopyHintElem.role = "status";
  366. advCopyHintElem.style.display = "none";
  367. const advCopyHiddenBtn = document.createElement("button");
  368. advCopyHiddenBtn.classList.add("bytm-ftconf-adv-copy-btn");
  369. advCopyHiddenBtn.tabIndex = 0;
  370. advCopyHiddenBtn.textContent = t("copy_hidden_value");
  371. advCopyHiddenBtn.ariaLabel = advCopyHiddenBtn.title = t("copy_hidden_tooltip");
  372. const copyHiddenInteraction = (e: MouseEvent | KeyboardEvent) => {
  373. e.preventDefault();
  374. e.stopPropagation();
  375. copyToClipboard(getFeatures()[featKey as keyof FeatureConfig] as Stringifiable);
  376. advCopyHintElem.style.display = "inline";
  377. if(typeof hiddenCopiedTxtTimeout === "undefined") {
  378. hiddenCopiedTxtTimeout = setTimeout(() => {
  379. advCopyHintElem.style.display = "none";
  380. hiddenCopiedTxtTimeout = undefined;
  381. }, 3000);
  382. }
  383. };
  384. onInteraction(advCopyHiddenBtn, copyHiddenInteraction);
  385. advCopyHiddenCont = document.createElement("span");
  386. advCopyHiddenCont.appendChild(advCopyHintElem);
  387. advCopyHiddenCont.appendChild(advCopyHiddenBtn);
  388. }
  389. advCopyHiddenCont && ctrlElem.appendChild(advCopyHiddenCont);
  390. if(inputTag) {
  391. // standard input element:
  392. const inputElem = document.createElement(inputTag) as HTMLInputElement;
  393. inputElem.classList.add("bytm-ftconf-input");
  394. inputElem.id = inputElemId;
  395. if(inputType)
  396. inputElem.type = inputType;
  397. if("min" in ftInfo && typeof ftInfo.min !== "undefined")
  398. inputElem.min = String(ftInfo.min);
  399. if("max" in ftInfo && typeof ftInfo.max !== "undefined")
  400. inputElem.max = String(ftInfo.max);
  401. if(typeof initialVal !== "undefined")
  402. inputElem.value = String(initialVal);
  403. if(type === "text" && ftInfo.valueHidden)
  404. inputElem.value = String(initialVal).length === 0 ? "" : "•".repeat(16);
  405. if(type === "number" || type === "slider" && step)
  406. inputElem.step = String(step);
  407. if(type === "toggle" && typeof initialVal !== "undefined")
  408. inputElem.checked = Boolean(initialVal);
  409. const unitTxt = (
  410. "unit" in ftInfo && typeof ftInfo.unit === "string"
  411. ? ftInfo.unit
  412. : (
  413. "unit" in ftInfo && typeof ftInfo.unit === "function"
  414. ? ftInfo.unit(Number(inputElem.value))
  415. : ""
  416. )
  417. );
  418. let labelElem: HTMLLabelElement | undefined;
  419. let lastDisplayedVal: string | undefined;
  420. if(type === "slider") {
  421. labelElem = document.createElement("label");
  422. labelElem.classList.add("bytm-ftconf-label", "bytm-slider-label");
  423. labelElem.textContent = `${fmtVal(initialVal, featKey as FeatureKey)}${unitTxt}`;
  424. inputElem.addEventListener("input", () => {
  425. if(labelElem && lastDisplayedVal !== inputElem.value) {
  426. labelElem.textContent = `${fmtVal(inputElem.value, featKey as FeatureKey)}${unitTxt}`;
  427. lastDisplayedVal = inputElem.value;
  428. }
  429. });
  430. }
  431. else if(type === "select") {
  432. const ftOpts = typeof ftInfo.options === "function"
  433. ? ftInfo.options()
  434. : ftInfo.options;
  435. for(const { value, label } of ftOpts) {
  436. const optionElem = document.createElement("option");
  437. optionElem.value = String(value);
  438. optionElem.textContent = label;
  439. if(value === initialVal)
  440. optionElem.selected = true;
  441. inputElem.appendChild(optionElem);
  442. }
  443. }
  444. if(type === "text") {
  445. let lastValue: string | undefined = inputElem.value && inputElem.value.length > 0 ? inputElem.value : ftInfo.default;
  446. const textInputUpdate = () => {
  447. let v: string | number = String(inputElem.value).trim();
  448. if(type === "text" && ftInfo.normalize)
  449. v = inputElem.value = ftInfo.normalize(String(v));
  450. if(v === lastValue)
  451. return;
  452. lastValue = v;
  453. if(v === "")
  454. v = ftInfo.default;
  455. if(typeof initialVal !== "undefined")
  456. confChanged(featKey as keyof FeatureConfig, initialVal, v);
  457. };
  458. const unsub = siteEvents.on("cfgMenuClosed", () => {
  459. unsub();
  460. textInputUpdate();
  461. });
  462. inputElem.addEventListener("blur", () => textInputUpdate());
  463. inputElem.addEventListener("keydown", (e) => e.key === "Tab" && textInputUpdate());
  464. }
  465. else {
  466. inputElem.addEventListener("input", () => {
  467. let v: string | number = String(inputElem.value).trim();
  468. if(["number", "slider"].includes(type) || v.match(/^-?\d+$/))
  469. v = Number(v);
  470. if(typeof initialVal !== "undefined")
  471. confChanged(featKey as keyof FeatureConfig, initialVal, (type !== "toggle" ? v : inputElem.checked));
  472. });
  473. }
  474. if(labelElem) {
  475. labelElem.id = `bytm-ftconf-${featKey}-label`;
  476. labelElem.htmlFor = inputElemId;
  477. ctrlElem.appendChild(labelElem);
  478. }
  479. ctrlElem.appendChild(inputElem);
  480. }
  481. else {
  482. // custom input element:
  483. let wrapperElem: HTMLElement | undefined;
  484. switch(type) {
  485. case "hotkey":
  486. wrapperElem = createHotkeyInput({
  487. initialValue: typeof initialVal === "object" ? initialVal as HotkeyObj : undefined,
  488. onChange: (hotkey) => confChanged(featKey as keyof FeatureConfig, initialVal, hotkey),
  489. });
  490. break;
  491. case "toggle":
  492. wrapperElem = await createToggleInput({
  493. initialValue: Boolean(initialVal),
  494. onChange: (checked) => confChanged(featKey as keyof FeatureConfig, initialVal, checked),
  495. id: `ftconf-${featKey}`,
  496. labelPos: "left",
  497. });
  498. break;
  499. case "button":
  500. wrapperElem = document.createElement("button");
  501. wrapperElem.tabIndex = 0;
  502. wrapperElem.textContent = wrapperElem.ariaLabel = wrapperElem.title = hasKey(`feature_btn_${featKey}`) ? t(`feature_btn_${featKey}`) : t("trigger_btn_action");
  503. onInteraction(wrapperElem, async () => {
  504. if((wrapperElem as HTMLButtonElement).disabled)
  505. return;
  506. const startTs = Date.now();
  507. const res = ftInfo.click();
  508. (wrapperElem as HTMLButtonElement).disabled = true;
  509. wrapperElem!.classList.add("bytm-busy");
  510. wrapperElem!.textContent = wrapperElem!.ariaLabel = wrapperElem!.title = hasKey(`feature_btn_${featKey}_running`) ? t(`feature_btn_${featKey}_running`) : t("trigger_btn_action_running");
  511. if(res instanceof Promise)
  512. await res;
  513. const finalize = () => {
  514. (wrapperElem as HTMLButtonElement).disabled = false;
  515. wrapperElem!.classList.remove("bytm-busy");
  516. wrapperElem!.textContent = wrapperElem!.ariaLabel = wrapperElem!.title = hasKey(`feature_btn_${featKey}`) ? t(`feature_btn_${featKey}`) : t("trigger_btn_action");
  517. };
  518. // artificial timeout ftw
  519. if(Date.now() - startTs < 350)
  520. setTimeout(finalize, 350 - (Date.now() - startTs));
  521. else
  522. finalize();
  523. });
  524. break;
  525. }
  526. ctrlElem.appendChild(wrapperElem!);
  527. }
  528. ftConfElem.appendChild(ctrlElem);
  529. }
  530. featuresCont.appendChild(ftConfElem);
  531. }
  532. }
  533. //#region reset inputs on external change
  534. siteEvents.on("rebuildCfgMenu", (newConfig) => {
  535. for(const ftKey in featInfo) {
  536. const ftElem = document.querySelector<HTMLInputElement>(`#bytm-ftconf-${ftKey}-input`);
  537. const labelElem = document.querySelector<HTMLLabelElement>(`#bytm-ftconf-${ftKey}-label`);
  538. if(!ftElem)
  539. continue;
  540. const ftInfo = featInfo[ftKey as keyof typeof featInfo];
  541. const value = newConfig[ftKey as keyof FeatureConfig];
  542. if(ftInfo.type === "toggle")
  543. ftElem.checked = Boolean(value);
  544. else
  545. ftElem.value = String(value);
  546. if(ftInfo.type === "text" && "valueHidden" in ftInfo && ftInfo.valueHidden)
  547. ftElem.value = String(value).length === 0 ? "" : "•".repeat(16);
  548. if(!labelElem)
  549. continue;
  550. const unitTxt = (
  551. "unit" in ftInfo && typeof ftInfo.unit === "string"
  552. ? ftInfo.unit
  553. : (
  554. "unit" in ftInfo && typeof ftInfo.unit === "function"
  555. ? ftInfo.unit(Number(ftElem.value))
  556. : ""
  557. )
  558. );
  559. if(ftInfo.type === "slider")
  560. labelElem.textContent = `${fmtVal(Number(value), ftKey as FeatureKey)}${unitTxt}`;
  561. }
  562. info("Rebuilt config menu");
  563. });
  564. //#region scroll indicator
  565. const scrollIndicator = document.createElement("img");
  566. scrollIndicator.id = "bytm-menu-scroll-indicator";
  567. scrollIndicator.src = await getResourceUrl("icon-arrow_down");
  568. scrollIndicator.role = "button";
  569. scrollIndicator.ariaLabel = scrollIndicator.title = t("scroll_to_bottom");
  570. featuresCont.appendChild(scrollIndicator);
  571. scrollIndicator.addEventListener("click", () => {
  572. const bottomAnchor = document.querySelector("#bytm-menu-bottom-anchor");
  573. bottomAnchor?.scrollIntoView({
  574. behavior: "smooth",
  575. });
  576. });
  577. featuresCont.addEventListener("scroll", (evt: Event) => {
  578. const scrollPos = (evt.target as HTMLDivElement)?.scrollTop ?? 0;
  579. const scrollIndicator = document.querySelector<HTMLImageElement>("#bytm-menu-scroll-indicator");
  580. if(!scrollIndicator)
  581. return;
  582. if(scrollIndicatorEnabled && scrollPos > scrollIndicatorOffsetThreshold && !scrollIndicator.classList.contains("bytm-hidden")) {
  583. scrollIndicator.classList.add("bytm-hidden");
  584. }
  585. else if(scrollIndicatorEnabled && scrollPos <= scrollIndicatorOffsetThreshold && scrollIndicator.classList.contains("bytm-hidden")) {
  586. scrollIndicator.classList.remove("bytm-hidden");
  587. }
  588. });
  589. const bottomAnchor = document.createElement("div");
  590. bottomAnchor.id = "bytm-menu-bottom-anchor";
  591. featuresCont.appendChild(bottomAnchor);
  592. //#region finalize
  593. menuContainer.appendChild(headerElem);
  594. menuContainer.appendChild(featuresCont);
  595. const subtitleElemCont = document.createElement("div");
  596. subtitleElemCont.id = "bytm-menu-subtitle-cont";
  597. const versionEl = document.createElement("a");
  598. versionEl.id = "bytm-menu-version-anchor";
  599. versionEl.classList.add("bytm-link");
  600. versionEl.role = "button";
  601. versionEl.tabIndex = 0;
  602. versionEl.ariaLabel = versionEl.title = t("version_tooltip", scriptInfo.version, buildNumber);
  603. versionEl.textContent = `v${scriptInfo.version} (#${buildNumber})`;
  604. onInteraction(versionEl, async (e: MouseEvent | KeyboardEvent) => {
  605. e.preventDefault();
  606. e.stopPropagation();
  607. const dlg = await getChangelogDialog();
  608. dlg.on("close", openCfgMenu);
  609. await dlg.mount();
  610. closeCfgMenu(undefined, false);
  611. await dlg.open();
  612. });
  613. subtitleElemCont.appendChild(versionEl);
  614. titleElem.appendChild(subtitleElemCont);
  615. const modeItems = [] as TrKey[];
  616. mode === "development" && modeItems.push("dev_mode");
  617. getFeatures().advancedMode && modeItems.push("advanced_mode");
  618. if(modeItems.length > 0) {
  619. const modeDisplayEl = document.createElement("span");
  620. modeDisplayEl.id = "bytm-menu-mode-display";
  621. modeDisplayEl.textContent = `[${t("active_mode_display", arrayWithSeparators(modeItems.map(v => t(`${v}_short`)), ", ", " & "))}]`;
  622. modeDisplayEl.ariaLabel = modeDisplayEl.title = tp("active_mode_tooltip", modeItems, arrayWithSeparators(modeItems.map(t), ", ", " & "));
  623. subtitleElemCont.appendChild(modeDisplayEl);
  624. }
  625. menuContainer.appendChild(footerCont);
  626. backgroundElem.appendChild(menuContainer);
  627. document.body.appendChild(backgroundElem);
  628. window.addEventListener("resize", debounce(checkToggleScrollIndicator, 250, "rising"));
  629. log("Added menu element");
  630. // ensure stuff is reset if menu was opened before being added
  631. isCfgMenuOpen = false;
  632. document.body.classList.remove("bytm-disable-scroll");
  633. document.querySelector(getDomain() === "ytm" ? "ytmusic-app" : "ytd-app")?.removeAttribute("inert");
  634. backgroundElem.style.visibility = "hidden";
  635. backgroundElem.style.display = "none";
  636. siteEvents.on("recreateCfgMenu", async () => {
  637. const bgElem = document.querySelector("#bytm-cfg-menu-bg");
  638. if(!bgElem)
  639. return;
  640. closeCfgMenu();
  641. bgElem.remove();
  642. isCfgMenuAdded = false;
  643. await addCfgMenu();
  644. await openCfgMenu();
  645. });
  646. }
  647. //#region open & close
  648. /** Closes the config menu if it is open. If a bubbling event is passed, its propagation will be prevented. */
  649. export function closeCfgMenu(evt?: MouseEvent | KeyboardEvent, enableScroll = true) {
  650. if(!isCfgMenuOpen)
  651. return;
  652. isCfgMenuOpen = false;
  653. evt?.bubbles && evt.stopPropagation();
  654. if(enableScroll) {
  655. document.body.classList.remove("bytm-disable-scroll");
  656. document.querySelector(getDomain() === "ytm" ? "ytmusic-app" : "ytd-app")?.removeAttribute("inert");
  657. }
  658. const menuBg = document.querySelector<HTMLElement>("#bytm-cfg-menu-bg");
  659. siteEvents.emit("cfgMenuClosed");
  660. if(!menuBg)
  661. return;
  662. menuBg.querySelectorAll<HTMLElement>(".bytm-ftconf-adv-copy-hint")?.forEach((el) => el.style.display = "none");
  663. clearTimeout(hiddenCopiedTxtTimeout);
  664. menuBg.style.visibility = "hidden";
  665. menuBg.style.display = "none";
  666. }
  667. /** Opens the config menu if it is closed */
  668. export async function openCfgMenu() {
  669. if(!isCfgMenuAdded)
  670. await addCfgMenu();
  671. if(isCfgMenuOpen)
  672. return;
  673. isCfgMenuOpen = true;
  674. document.body.classList.add("bytm-disable-scroll");
  675. document.querySelector(getDomain() === "ytm" ? "ytmusic-app" : "ytd-app")?.setAttribute("inert", "true");
  676. const menuBg = document.querySelector<HTMLElement>("#bytm-cfg-menu-bg");
  677. if(!menuBg)
  678. return;
  679. menuBg.style.visibility = "visible";
  680. menuBg.style.display = "block";
  681. checkToggleScrollIndicator();
  682. }
  683. //#region chk scroll indicator
  684. /** Checks if the features container is scrollable and toggles the scroll indicator accordingly */
  685. function checkToggleScrollIndicator() {
  686. const featuresCont = document.querySelector<HTMLElement>("#bytm-menu-opts");
  687. const scrollIndicator = document.querySelector<HTMLElement>("#bytm-menu-scroll-indicator");
  688. // disable scroll indicator if container doesn't scroll
  689. if(featuresCont && scrollIndicator) {
  690. const verticalScroll = isScrollable(featuresCont).vertical;
  691. /** If true, the indicator's threshold is under the available scrollable space and so it should be disabled */
  692. const underThreshold = featuresCont.scrollHeight - featuresCont.clientHeight <= scrollIndicatorOffsetThreshold;
  693. if(!underThreshold && verticalScroll && !scrollIndicatorEnabled) {
  694. scrollIndicatorEnabled = true;
  695. scrollIndicator.classList.remove("bytm-hidden");
  696. }
  697. if((!verticalScroll && scrollIndicatorEnabled) || underThreshold) {
  698. scrollIndicatorEnabled = false;
  699. scrollIndicator.classList.add("bytm-hidden");
  700. }
  701. }
  702. }