menu_old.ts 32 KB

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