From 5dba4ba8b53f023c022ca4cababf3410ed64014b Mon Sep 17 00:00:00 2001 From: Aden Linday Date: Thu, 3 Sep 2026 10:36:04 +0930 Subject: [PATCH] feat: performance mode AND fix background image bug. --- scripts/analyze-trace.mjs | 180 ++++ src/css/injected.scss | 49 +- src/css/injected/performance-mode.scss | 86 ++ src/css/injected/popup.scss | 15 +- src/interface/components/LazyPanel.svelte | 34 + src/interface/components/MotionDiv.svelte | 22 +- src/interface/components/SidebarNav.svelte | 11 +- src/interface/components/Switch.svelte | 20 +- .../components/TabbedContainer.svelte | 75 +- .../themes/BackgroundSelector.svelte | 97 ++- .../themes/BackgroundUploader.svelte | 25 +- src/interface/hooks/BackgroundDataLoader.ts | 152 +++- src/interface/index.css | 15 + src/interface/pages/settings.svelte | 175 ++-- .../pages/settings/LazySection.svelte | 28 + .../settings/PluginSettingsBlocks.svelte | 201 +++++ .../pages/settings/SettingRow.svelte | 26 + .../pages/settings/SettingsBody.svelte | 57 ++ src/interface/pages/settings/general.svelte | 813 +----------------- .../settings/pluginSettingsState.svelte.ts | 101 +++ .../pages/settings/sectionLoaders.ts | 15 + .../pages/settings/sections/account.svelte | 110 +++ .../pages/settings/sections/advanced.svelte | 248 ++++++ .../pages/settings/sections/appearance.svelte | 105 +++ .../settings/sections/generalOptions.svelte | 244 ++++++ .../pages/settings/sections/plugins.svelte | 12 + src/interface/pages/settings/shared.ts | 47 + src/interface/pages/store.svelte | 17 +- .../built-in/animatedBackground/index.ts | 6 + src/plugins/built-in/backgroundMusic/index.ts | 5 + src/plugins/built-in/globalSearch/lazy.ts | 2 + .../built-in/globalSearch/src/core/index.ts | 8 +- .../globalSearch/src/core/mountSearchBar.ts | 3 +- .../globalSearch/src/indexing/indexer.ts | 6 + .../src/indexing/passiveObserver.ts | 2 + .../gradeAnalytics/GradeAnalyticsPage.svelte | 9 +- .../gradeAnalytics/injectAnalyticsMenuItem.ts | 4 +- src/plugins/built-in/gradeAnalytics/ui.ts | 7 +- .../built-in/notificationCollector/index.ts | 4 +- src/plugins/built-in/themes/theme-manager.ts | 3 +- src/plugins/core/manager.ts | 9 + src/plugins/monofile.ts | 76 +- src/seqta/ui/AddBetterSEQTAElements.ts | 31 +- src/seqta/ui/Loading.ts | 5 +- src/seqta/ui/colors/Manager.ts | 5 +- src/seqta/ui/sidebar/mountCustomSidebar.ts | 29 +- src/seqta/ui/sidebar/parseNativeMenu.ts | 17 +- src/seqta/ui/sidebar/sidebarState.svelte.ts | 11 +- src/seqta/ui/sidebar/sidebarStyles.ts | 16 +- src/seqta/ui/titlebar/mountCustomTitleBar.ts | 27 +- .../utils/Adders/AddExtensionSettings.ts | 29 +- .../utils/Closers/closeExtensionPopup.ts | 30 +- src/seqta/utils/Openers/PopupManager.ts | 61 +- .../attachNotificationsPanelAnimation.ts | 137 +-- src/seqta/utils/defaultSettings.ts | 2 + src/seqta/utils/listeners/EventManager.ts | 39 +- src/seqta/utils/listeners/SettingsState.ts | 12 +- src/seqta/utils/listeners/StorageChanges.ts | 11 +- src/seqta/utils/menuItemVisibility.ts | 28 +- src/seqta/utils/performanceMode.test.ts | 85 ++ src/seqta/utils/performanceMode.ts | 149 ++++ src/seqta/utils/performanceModeConfig.ts | 53 ++ src/seqta/utils/popupAnimation.ts | 54 ++ src/seqta/utils/rafThrottle.ts | 16 + src/seqta/utils/settingsPopupAnimation.ts | 74 ++ src/seqta/utils/setupSettingsButton.ts | 42 +- src/seqta/utils/sidebarMenuIcons.ts | 3 +- src/types/storage.ts | 4 + 68 files changed, 2882 insertions(+), 1212 deletions(-) create mode 100644 scripts/analyze-trace.mjs create mode 100644 src/css/injected/performance-mode.scss create mode 100644 src/interface/components/LazyPanel.svelte create mode 100644 src/interface/pages/settings/LazySection.svelte create mode 100644 src/interface/pages/settings/PluginSettingsBlocks.svelte create mode 100644 src/interface/pages/settings/SettingRow.svelte create mode 100644 src/interface/pages/settings/SettingsBody.svelte create mode 100644 src/interface/pages/settings/pluginSettingsState.svelte.ts create mode 100644 src/interface/pages/settings/sectionLoaders.ts create mode 100644 src/interface/pages/settings/sections/account.svelte create mode 100644 src/interface/pages/settings/sections/advanced.svelte create mode 100644 src/interface/pages/settings/sections/appearance.svelte create mode 100644 src/interface/pages/settings/sections/generalOptions.svelte create mode 100644 src/interface/pages/settings/sections/plugins.svelte create mode 100644 src/interface/pages/settings/shared.ts create mode 100644 src/seqta/utils/performanceMode.test.ts create mode 100644 src/seqta/utils/performanceMode.ts create mode 100644 src/seqta/utils/performanceModeConfig.ts create mode 100644 src/seqta/utils/popupAnimation.ts create mode 100644 src/seqta/utils/rafThrottle.ts create mode 100644 src/seqta/utils/settingsPopupAnimation.ts diff --git a/scripts/analyze-trace.mjs b/scripts/analyze-trace.mjs new file mode 100644 index 00000000..1c3bc00e --- /dev/null +++ b/scripts/analyze-trace.mjs @@ -0,0 +1,180 @@ +/** + * Chrome trace analyzer — aggregates hotspots for BetterSEQTA+ optimization. + * Usage: node scripts/analyze-trace.mjs + */ +import fs from "node:fs"; + +const path = process.argv[2]; +if (!path) { + console.error("Usage: node scripts/analyze-trace.mjs "); + process.exit(1); +} + +const raw = fs.readFileSync(path, "utf8"); +const { traceEvents } = JSON.parse(raw); + +const DURATION_PHASES = new Set(["X", "b", "e"]); +const openStacks = new Map(); // key -> { name, cat, args, ts } + +const byName = new Map(); +const byCat = new Map(); +const byUrl = new Map(); +const byFunction = new Map(); +const layoutEvents = []; +const paintEvents = []; +const longTasks = []; +const timers = []; +const observers = []; +const hitTests = []; +const betterseqtaHits = new Map(); +const ipcMessages = new Map(); +const gcEvents = []; + +let minTs = Infinity; +let maxTs = -Infinity; + +function add(map, key, dur, count = 1) { + const e = map.get(key) ?? { dur: 0, count: 0 }; + e.dur += dur; + e.count += count; + map.set(key, e); +} + +function stackKey(ev) { + return `${ev.pid}:${ev.tid}:${ev.name}:${ev.ts}`; +} + +for (const ev of traceEvents) { + if (ev.ts != null) { + minTs = Math.min(minTs, ev.ts); + maxTs = Math.max(maxTs, ev.ts); + } + + const ph = ev.ph; + const name = ev.name ?? ""; + const cat = ev.cat ?? ""; + const args = ev.args ?? {}; + + if (ph === "b") { + openStacks.set(`${ev.pid}:${ev.tid}:${ev.id ?? name}`, ev); + continue; + } + + let dur = ev.dur ?? 0; + if (ph === "e" && ev.id != null) { + const start = openStacks.get(`${ev.pid}:${ev.tid}:${ev.id}`); + if (start) dur = ev.ts - start.ts; + } + if (dur <= 0 && ph !== "X") continue; + + add(byName, name, dur); + + const catParts = cat.split(",").filter(Boolean); + for (const c of catParts.length ? catParts : [cat || "(none)"]) { + add(byCat, c, dur); + } + + const url = + args.data?.url ?? + args.url ?? + args.fileName ?? + args.data?.scriptName ?? + args.data?.frame ?? + ""; + if (url && typeof url === "string" && dur > 0) { + add(byUrl, url.slice(0, 200), dur); + } + + const fn = + args.data?.functionName ?? + args.functionName ?? + args.data?.columnNumber != null + ? `${args.data?.functionName ?? name}@${args.data?.url ?? ""}:${args.data?.lineNumber ?? "?"}` + : ""; + if (fn && dur > 100) { + add(byFunction, String(fn).slice(0, 250), dur); + } + + if (/Layout|UpdateLayoutTree|InvalidateLayout|LocalFrameView::performLayout/i.test(name)) { + layoutEvents.push({ name, dur, ts: ev.ts, cat }); + } + if (/Paint|Raster|DrawFrame|CompositeLayers|UpdateLayer/i.test(name)) { + paintEvents.push({ name, dur, ts: ev.ts }); + } + if (name === "RunTask" && dur > 50000) { + longTasks.push({ dur, ts: ev.ts, cat, args: JSON.stringify(args).slice(0, 300) }); + } + if (/Timer|setTimeout|setInterval|FireIdleCallback|requestAnimationFrame|RequestAnimationFrame/i.test(name)) { + timers.push({ name, dur, ts: ev.ts }); + } + if (/MutationObserver|ResizeObserver|IntersectionObserver|DeliverObservations|NotifyMutation/i.test(name)) { + observers.push({ name, dur, ts: ev.ts }); + } + if (/HitTest|FindElement|ElementAt/i.test(name)) { + hitTests.push({ name, dur, ts: ev.ts }); + } + if (/V8\.GC|GC_|MajorGC|MinorGC|IncrementalMarking/i.test(name)) { + gcEvents.push({ name, dur, ts: ev.ts }); + } + if (/IPC|MessagePort|postMessage/i.test(name)) { + add(ipcMessages, name, dur); + } + + const blob = JSON.stringify(args); + if (/betterseqta|BetterSEQTA|bsplus|SEQTA\.ts|monofile|AddBetterSEQTA/i.test(blob + name + url)) { + const key = `${name} | ${(url || blob).slice(0, 120)}`; + add(betterseqtaHits, key, dur); + } +} + +function top(map, n = 40, minCount = 1) { + return [...map.entries()] + .filter(([, v]) => v.count >= minCount) + .sort((a, b) => b[1].dur - a[1].dur) + .slice(0, n) + .map(([k, v]) => ({ + key: k, + totalMs: (v.dur / 1000).toFixed(1), + count: v.count, + avgMs: (v.dur / v.count / 1000).toFixed(2), + })); +} + +const traceDurationMs = ((maxTs - minTs) / 1000).toFixed(0); + +console.log(JSON.stringify({ + summary: { + traceDurationMs, + eventCount: traceEvents.length, + layoutCount: layoutEvents.length, + layoutTotalMs: (layoutEvents.reduce((s, e) => s + e.dur, 0) / 1000).toFixed(1), + paintCount: paintEvents.length, + paintTotalMs: (paintEvents.reduce((s, e) => s + e.dur, 0) / 1000).toFixed(1), + longTaskCount: longTasks.length, + longTaskTotalMs: (longTasks.reduce((s, e) => s + e.dur, 0) / 1000).toFixed(1), + timerCount: timers.length, + timerTotalMs: (timers.reduce((s, e) => s + e.dur, 0) / 1000).toFixed(1), + observerCount: observers.length, + observerTotalMs: (observers.reduce((s, e) => s + e.dur, 0) / 1000).toFixed(1), + hitTestCount: hitTests.length, + hitTestTotalMs: (hitTests.reduce((s, e) => s + e.dur, 0) / 1000).toFixed(1), + gcCount: gcEvents.length, + gcTotalMs: (gcEvents.reduce((s, e) => s + e.dur, 0) / 1000).toFixed(1), + }, + topEventNames: top(byName, 50), + topCategories: top(byCat, 30), + topUrls: top(byUrl, 40), + topFunctions: top(byFunction, 40, 1), + topBetterseqta: top(betterseqtaHits, 50), + topLongTasks: longTasks.sort((a, b) => b.dur - a.dur).slice(0, 20).map(e => ({ + ms: (e.dur / 1000).toFixed(1), + cat: e.cat, + args: e.args, + })), + topLayout: layoutEvents.sort((a, b) => b.dur - a.dur).slice(0, 15).map(e => ({ + name: e.name, ms: (e.dur / 1000).toFixed(2), + })), + topObservers: observers.sort((a, b) => b.dur - a.dur).slice(0, 15).map(e => ({ + name: e.name, ms: (e.dur / 1000).toFixed(2), count: 1, + })), +}, null, 2)); diff --git a/src/css/injected.scss b/src/css/injected.scss index d0cafcb4..9004e6a3 100644 --- a/src/css/injected.scss +++ b/src/css/injected.scss @@ -16,6 +16,7 @@ @include meta.load-css("injected/sidebar-styles.scss"); @include meta.load-css("injected/theme.scss"); @include meta.load-css("injected/transparency.scss"); +@include meta.load-css("injected/performance-mode.scss"); :root { background: var(--better-main) !important; @@ -2071,11 +2072,21 @@ html.transparencyEffects box-shadow: 0px 10px 15px -3px rgba(0, 0, 0, 0.4); } -/* Smoothed by attachNotificationsPanelAnimation (matches #ExtensionPopup spring) */ +/* Smoothed by attachNotificationsPanelAnimation (CSS transition, no JS spring ticks) */ .bsplus-notifications-panel { transform-origin: top right; - will-change: opacity, transform; + opacity: 0; + transform: scale(0.94); + transition: + opacity 0.2s cubic-bezier(0.22, 1, 0.36, 1), + transform 0.2s cubic-bezier(0.22, 1, 0.36, 1); filter: drop-shadow(0px 0px 20px rgba(0, 0, 0, 0.35)); + backface-visibility: hidden; +} + +.bsplus-notifications-panel--open { + opacity: 1; + transform: scale(1); } #menu li.active { @@ -4289,6 +4300,40 @@ div.day-empty { z-index: 49; transform: scale(1) !important; } + +/* Lightweight popup motion (performance mode) — fade + scale, no blur springs. */ +.whatsnewBackground.bsplus-popup-css-animate { + opacity: 0; + transition: opacity var(--bs-motion-duration, 0.2s) var(--bs-motion-ease, cubic-bezier(0.22, 1, 0.36, 1)); + + .whatsnewContainer { + opacity: 0; + transform: scale(0.94); + transition: + opacity var(--bs-motion-duration, 0.2s) var(--bs-motion-ease, cubic-bezier(0.22, 1, 0.36, 1)), + transform var(--bs-motion-duration, 0.2s) var(--bs-motion-ease, cubic-bezier(0.22, 1, 0.36, 1)); + } + + &.bsplus-popup-css-animate--open { + opacity: 1; + + .whatsnewContainer { + opacity: 1; + transform: scale(1); + } + } +} + +.whatsnewBackground.bsplus-popup-backdrop--lite { + backdrop-filter: none !important; + -webkit-backdrop-filter: none !important; + background: rgba(0, 0, 0, 0.55) !important; + + .whatsnewContainer { + backdrop-filter: none !important; + -webkit-backdrop-filter: none !important; + } +} .whatsnewImgContainer { width: 96%; display: flex; diff --git a/src/css/injected/performance-mode.scss b/src/css/injected/performance-mode.scss new file mode 100644 index 00000000..56d80f38 --- /dev/null +++ b/src/css/injected/performance-mode.scss @@ -0,0 +1,86 @@ +html.performanceMode { + --bs-settings-ease: 0.2s cubic-bezier(0.22, 1, 0.36, 1); + --bs-motion-duration: 0.2s; + --bs-motion-ease: cubic-bezier(0.22, 1, 0.36, 1); + + backdrop-filter: none !important; + -webkit-backdrop-filter: none !important; + filter: none !important; + + /* Inline page loaders only — boot overlay lives in #loading shadow DOM. */ + .bkloading-inline .big-circle, + .bkloading-inline .small-circle, + .bkloading-inline .outer-circle { + animation: none !important; + } + + /* Custom title: cheaper hit-testing during mouse moves (trace showed many HitTests). */ + .bsplus-custom-title, + #title.bsplus-custom-title { + contain: layout style paint; + } + + /* Settings backdrop — skip expensive blur in performance mode. */ + #ExtensionPopup ~ *, + .outside-container.hide { + backdrop-filter: none !important; + } +} + +html.performanceModeSimpleUi { + .bsplus-analytics-charts, + .bsplus-analytics-chart-cell { + display: none !important; + } +} + +/* Boot loading spinner uses shadow DOM; custom properties inherit from the host. */ +#loading.bkloading { + --bk-stage-duration: 0.85s !important; + --bk-spin-outer: 1s !important; + --bk-spin-inner: 3s !important; + --bk-spin-small: 3s !important; +} + +html.performanceMode.transparencyEffects, +html.performanceMode .backdrop-blur-xl, +html.performanceMode .backdrop-blur-sm, +html.performanceMode [class*="backdrop-blur"] { + backdrop-filter: none !important; + -webkit-backdrop-filter: none !important; +} + +/* Sidebar drill locks: `.drilling` on the list handles pointer-events in perf mode — + skip expensive `:has()` selectors that drive hit-test cost during mouse moves. */ +html.performanceMode #menu.bsplus-custom-sidebar { + &:has(> #bsplus-sidebar-root > li.hasChildren.bsplus-active > .sub) + > #bsplus-sidebar-root + > li:not(.hasChildren.bsplus-active), + &:has(> #bsplus-sidebar-root > li.hasChildren.bsplus-active > .sub) + > #bsplus-sidebar-root + > li:not(.hasChildren.bsplus-active) + * { + pointer-events: unset !important; + } + + > #bsplus-sidebar-root:has(> li.hasChildren.bsplus-active > .sub) + > li:not(.hasChildren.bsplus-active)::before, + > #bsplus-sidebar-root:has(> li.hasChildren.bsplus-active > .sub) + > li:not(.hasChildren.bsplus-active)::after { + content: none !important; + display: none !important; + } + + > #bsplus-sidebar-root li.hasChildren.bsplus-active + > .sub:has(.hasChildren.bsplus-active) { + pointer-events: unset !important; + } + + > #bsplus-sidebar-root.drilling li.hasChildren > .sub:not(:has(.sub)) { + pointer-events: auto !important; + } + + > #bsplus-sidebar-root.drilling li.hasChildren > .sub:has(.sub) { + pointer-events: unset !important; + } +} diff --git a/src/css/injected/popup.scss b/src/css/injected/popup.scss index e012349f..a83793db 100644 --- a/src/css/injected/popup.scss +++ b/src/css/injected/popup.scss @@ -34,9 +34,16 @@ #ExtensionPopup { border-radius: 0; filter: none; - /* Avoid transform on the host — it makes shadow `position: fixed` children - size to the host instead of the viewport on Engage stacking contexts. */ transform-origin: center center; - will-change: opacity; - transition: opacity 0.05s; + opacity: 0; + transition: opacity var(--bs-motion-duration, 0.2s) cubic-bezier(0.22, 1, 0.36, 1); +} + +#ExtensionPopup.bsplus-settings-host--open { + opacity: 1; +} + +#ExtensionPopup.bsplus-settings-host--closing { + opacity: 0; + pointer-events: none; } diff --git a/src/interface/components/LazyPanel.svelte b/src/interface/components/LazyPanel.svelte new file mode 100644 index 00000000..90e2a36f --- /dev/null +++ b/src/interface/components/LazyPanel.svelte @@ -0,0 +1,34 @@ + + +{#if Comp} + +{:else} +
Loading…
+{/if} diff --git a/src/interface/components/MotionDiv.svelte b/src/interface/components/MotionDiv.svelte index 1aca4896..08d0473e 100644 --- a/src/interface/components/MotionDiv.svelte +++ b/src/interface/components/MotionDiv.svelte @@ -1,6 +1,7 @@ -
+
{#if children} {@render children()} {/if} diff --git a/src/interface/components/SidebarNav.svelte b/src/interface/components/SidebarNav.svelte index b8e8088f..2c69f247 100644 --- a/src/interface/components/SidebarNav.svelte +++ b/src/interface/components/SidebarNav.svelte @@ -1,5 +1,6 @@ @@ -54,8 +57,8 @@ {#if indicatorReady}
{/if} diff --git a/src/interface/components/Switch.svelte b/src/interface/components/Switch.svelte index 3cf2de0a..65d95b69 100644 --- a/src/interface/components/Switch.svelte +++ b/src/interface/components/Switch.svelte @@ -1,6 +1,7 @@ @@ -39,6 +44,7 @@ >
-
\ No newline at end of file +
diff --git a/src/interface/components/TabbedContainer.svelte b/src/interface/components/TabbedContainer.svelte index 9519f403..d886853c 100644 --- a/src/interface/components/TabbedContainer.svelte +++ b/src/interface/components/TabbedContainer.svelte @@ -1,39 +1,60 @@ @@ -42,7 +63,7 @@
{#each tabs as { title }, index} @@ -50,7 +71,7 @@ role="tab" aria-selected={activeTab === index} class="relative z-10 flex-1 px-4 py-2 focus-visible:outline-none" - onclick={() => activeTab = index} + onclick={() => (activeTab = index)} > {title} @@ -58,7 +79,7 @@
- {#each tabs as { Content, props }, index (index)} + {#each tabs as tab, index (index)} {#if activeTab === index} - + {#if tab.loader} + + {:else if tab.Content} + + {/if}
{/if} {/each} diff --git a/src/interface/components/themes/BackgroundSelector.svelte b/src/interface/components/themes/BackgroundSelector.svelte index 2be4c7f7..ec60e6c8 100644 --- a/src/interface/components/themes/BackgroundSelector.svelte +++ b/src/interface/components/themes/BackgroundSelector.svelte @@ -9,25 +9,51 @@ let { isEditMode, selectNoBackground = $bindable(), selectedBackground = $bindable() } = $props<{ isEditMode: boolean, selectNoBackground: () => void, selectedBackground: string | null }>(); let backgrounds = $state<{ id: string; type: string; blob: Blob | null; url?: string }[]>([]); let error = $state(null); + let notice = $state(null); + let uploading = $state(false); let imageBackgrounds = $derived(backgrounds.filter(bg => bg.type === 'image')); let videoBackgrounds = $derived(backgrounds.filter(bg => bg.type === 'video')); + function inferBackgroundType(file: File): 'image' | 'video' { + const mime = file.type.toLowerCase(); + if (mime.startsWith('video/')) return 'video'; + if (mime.startsWith('image/')) return 'image'; + const ext = file.name.split('.').pop()?.toLowerCase() ?? ''; + if (['mp4', 'mov', 'webm', 'm4v', 'mkv'].includes(ext)) return 'video'; + return 'image'; + } + function setError(e: unknown) { - error = e instanceof Error ? e.message : 'An unknown error occurred'; + if (e instanceof Error) { + error = e.message; + return; + } + if (typeof e === 'string' && e) { + error = e; + return; + } + error = 'An unknown error occurred'; } - async function getTheme() { - return localStorage.getItem('selectedBackground'); - } - - async function setTheme(theme: string) { - localStorage.setItem('selectedBackground', theme); + function isHeicFile(file: File): boolean { + const mime = file.type.toLowerCase(); + const ext = file.name.split('.').pop()?.toLowerCase() ?? ''; + return ( + mime.includes('heic') || + mime.includes('heif') || + ext === 'heic' || + ext === 'heif' + ); } async function handleFileChange(file: File): Promise { if (!file) return; + uploading = true; + error = null; + notice = null; + try { if (!isIndexedDBSupported()) { throw new Error("Your browser doesn't support IndexedDB. Unable to save backgrounds."); @@ -38,17 +64,36 @@ throw new Error("Not enough storage space to save this background."); } - const fileId = `${Date.now()}-${file.name}`; - const fileType = file.type.split('/')[0]; - const blob = new Blob([file], { type: file.type }); + const fileId = `${Date.now()}-${file.name.replace(/[^\w.-]+/g, '_')}`; + const fileType = inferBackgroundType(file); + const blob = file.slice(0, file.size, file.type || (fileType === 'video' ? 'video/mp4' : 'image/jpeg')); await writeData(fileId, fileType, blob); - backgrounds = [...backgrounds, { id: fileId, type: fileType, blob, url: URL.createObjectURL(blob) }]; + backgrounds = [ + ...backgrounds, + { id: fileId, type: fileType, blob, url: URL.createObjectURL(blob) }, + ]; + backgroundUpdates.triggerUpdate(); + + if (isHeicFile(file)) { + notice = + 'HEIC saved, but Chrome and Edge often cannot preview it. Export as JPEG or PNG if the thumbnail stays blank.'; + } } catch (e) { setError(e); + } finally { + uploading = false; } } + async function getTheme() { + return localStorage.getItem('selectedBackground'); + } + + async function setTheme(theme: string) { + localStorage.setItem('selectedBackground', theme); + } + async function syncBackgrounds(): Promise { try { error = null; @@ -100,8 +145,9 @@ if (selectedBackground === fileId) { selectNoBackground(); } + backgroundUpdates.triggerUpdate(); } catch (e) { - error = e instanceof Error ? `Failed to delete background: ${e.message}` : 'An unknown error occurred'; + setError(e); } } @@ -138,11 +184,34 @@
+ {#if notice} +
+ {notice} +
+ {/if} + + {#if error} + + {/if} + {#if !(imageBackgrounds.length === 0 && isEditMode)}

Background Images

{#if !isEditMode} - handleFileChange(e.detail)} /> + + {#if uploading} +
+
+
+ {/if} {/if} {#each imageBackgrounds as bg (bg.id)} {#if bg.url} @@ -163,7 +232,7 @@

Background Videos

{#if !isEditMode} - handleFileChange(e.detail)} /> + {/if} {#each videoBackgrounds as bg (bg.id)} {#if bg.url} diff --git a/src/interface/components/themes/BackgroundUploader.svelte b/src/interface/components/themes/BackgroundUploader.svelte index 2b34d995..6fbb765a 100644 --- a/src/interface/components/themes/BackgroundUploader.svelte +++ b/src/interface/components/themes/BackgroundUploader.svelte @@ -1,26 +1,29 @@
-
- +
+
-
\ No newline at end of file +
diff --git a/src/interface/hooks/BackgroundDataLoader.ts b/src/interface/hooks/BackgroundDataLoader.ts index 17f79338..df130eee 100644 --- a/src/interface/hooks/BackgroundDataLoader.ts +++ b/src/interface/hooks/BackgroundDataLoader.ts @@ -1,24 +1,107 @@ -import localforage from "localforage"; - type BackgroundRecord = { id: string; type: string; blob: Blob }; -const store = localforage.createInstance({ - name: "BackgroundDB", - storeName: "backgrounds", -}); +const DB_NAME = "BackgroundDB"; +const STORE_NAME = "backgrounds"; +const DB_VERSION = 1; -export async function openDatabase(): Promise { - await store.ready(); - return store; +let dbPromise: Promise | null = null; + +function promisifyRequest(request: IDBRequest): Promise { + return new Promise((resolve, reject) => { + request.onsuccess = () => resolve(request.result); + request.onerror = () => reject(request.error); + }); +} + +function waitForTransaction(tx: IDBTransaction): Promise { + return new Promise((resolve, reject) => { + tx.oncomplete = () => resolve(); + tx.onerror = () => reject(tx.error); + tx.onabort = () => reject(tx.error); + }); +} + +function openDatabaseInternal(): Promise { + if (!dbPromise) { + dbPromise = new Promise((resolve, reject) => { + const request = indexedDB.open(DB_NAME, DB_VERSION); + + request.onerror = () => { + dbPromise = null; + reject(request.error); + }; + + request.onupgradeneeded = () => { + const db = request.result; + if (!db.objectStoreNames.contains(STORE_NAME)) { + db.createObjectStore(STORE_NAME, { keyPath: "id" }); + } + }; + + request.onsuccess = () => resolve(request.result); + }); + } + + return dbPromise; +} + +function storeUsesInlineKeys(store: IDBObjectStore): boolean { + return store.keyPath !== null && store.keyPath !== ""; +} + +async function withStore( + mode: IDBTransactionMode, + run: (store: IDBObjectStore) => Promise, +): Promise { + const db = await openDatabaseInternal(); + const tx = db.transaction(STORE_NAME, mode); + const result = await run(tx.objectStore(STORE_NAME)); + await waitForTransaction(tx); + return result; +} + +export async function openDatabase(): Promise { + return openDatabaseInternal(); } export async function readAllData(): Promise { - await store.ready(); - const items: BackgroundRecord[] = []; - await store.iterate((value) => { - if (value?.id && value.blob) items.push(value); + return withStore("readonly", async (store) => { + const items: BackgroundRecord[] = []; + + await new Promise((resolve, reject) => { + const request = store.openCursor(); + + request.onsuccess = () => { + const cursor = request.result; + if (!cursor) { + resolve(); + return; + } + + const value = cursor.value as Partial | undefined; + const id = + typeof value?.id === "string" + ? value.id + : cursor.key == null + ? "" + : String(cursor.key); + + if (id && value?.blob instanceof Blob) { + items.push({ + id, + type: typeof value.type === "string" ? value.type : "image", + blob: value.blob, + }); + } + + cursor.continue(); + }; + + request.onerror = () => reject(request.error); + }); + + return items; }); - return items; } export async function writeData( @@ -26,25 +109,54 @@ export async function writeData( type: string, blob: Blob, ): Promise { - await store.setItem(id, { id, type, blob }); + const record: BackgroundRecord = { id, type, blob }; + + try { + await withStore("readwrite", async (store) => { + const request = storeUsesInlineKeys(store) + ? store.put(record) + : store.put(record, id); + await promisifyRequest(request); + }); + } catch (e) { + const detail = e instanceof Error ? e.message : String(e); + throw new Error(`Failed to save background: ${detail}`); + } } export async function deleteData(id: string): Promise { - await store.removeItem(id); + try { + await withStore("readwrite", async (store) => { + await promisifyRequest(store.delete(id)); + }); + } catch (e) { + const detail = e instanceof Error ? e.message : String(e); + throw new Error(`Failed to delete background: ${detail}`); + } } export async function clearAllData(): Promise { - await store.clear(); + await withStore("readwrite", async (store) => { + await promisifyRequest(store.clear()); + }); } export async function getDataById( id: string, ): Promise { - const item = await store.getItem(id); - return item ?? undefined; + const item = await withStore("readonly", async (store) => + promisifyRequest(store.get(id)), + ); + if (!item?.id || !(item.blob instanceof Blob)) return undefined; + return item as BackgroundRecord; } -export function closeDatabase(): void {} +export function closeDatabase(): void { + if (dbPromise) { + void dbPromise.then((db) => db.close()); + dbPromise = null; + } +} export function isIndexedDBSupported(): boolean { return "indexedDB" in window; diff --git a/src/interface/index.css b/src/interface/index.css index 5b65f9b0..da3edafb 100644 --- a/src/interface/index.css +++ b/src/interface/index.css @@ -39,6 +39,21 @@ input { scrollbar-width: none !important; } +[data-settings-panel] { + transform: scale(0.94); + opacity: 0; + transform-origin: center center; + transition: + transform var(--bs-motion-duration, 0.22s) cubic-bezier(0.22, 1, 0.36, 1), + opacity var(--bs-motion-duration, 0.22s) cubic-bezier(0.22, 1, 0.36, 1); + will-change: transform, opacity; +} + +[data-settings-panel].bsplus-settings-panel--open { + transform: scale(1); + opacity: 1; +} + .cm-editor { width: 100%; min-height: 100px; diff --git a/src/interface/pages/settings.svelte b/src/interface/pages/settings.svelte index 3a9f6523..c207bb2a 100644 --- a/src/interface/pages/settings.svelte +++ b/src/interface/pages/settings.svelte @@ -1,9 +1,6 @@ + +{#if Comp} + +{:else} +
Loading…
+{/if} diff --git a/src/interface/pages/settings/PluginSettingsBlocks.svelte b/src/interface/pages/settings/PluginSettingsBlocks.svelte new file mode 100644 index 00000000..a3d728f7 --- /dev/null +++ b/src/interface/pages/settings/PluginSettingsBlocks.svelte @@ -0,0 +1,201 @@ + + +{#if pluginSettingsStore.loading && visiblePlugins.length === 0} +
Loading plugin settings…
+{/if} + +{#each visiblePlugins as plugin (plugin.pluginId)} + {@const perfPaused = pluginPerfPaused(plugin.pluginId)} +
+
+ {#if perfPaused} +
+

+ Paused by Performance Mode — enable anyway +

+ + setPerformanceModePluginOverride(plugin.pluginId, forceOn)} + /> +
+ {/if} + + {#if plugin.disableToggle} +
+
+

+ Enable {plugin.name} + {#if plugin.beta} + + Beta + + {/if} +

+

{plugin.description}

+
+
+ { + if (plugin.pluginId === "assessments-average" && value === true) { + showDisclaimer( + async () => { + await pluginSettingsStore.update(plugin.pluginId, "enabled", true); + }, + () => {}, + "Assessment Averages Disclaimer", + "This feature calculates a simple average of your assessment grades. It does not take into account:\n• Assessment weightings\n• Different grading scales\n• Other factors used in official reports\n\nThe displayed average may be inaccurate compared to your actual marks found in reports.\n\nDo you want to enable this feature?", + ); + return; + } + await pluginSettingsStore.update(plugin.pluginId, "enabled", value); + }} + /> +
+
+ {/if} + + {#if !perfPaused && (!plugin.disableToggle || ((pluginSettingsStore.values[plugin.pluginId]?.enabled as boolean | undefined) ?? true))} + {#each Object.entries(plugin.settings) as [key, setting] (key)} + {#if key !== "enabled" && !(key === "useCloudPfp" && !cloudState.isLoggedIn)} +
+
+

{setting.title || key}

+

{setting.description || ""}

+
+
+ {#if setting.type === "boolean"} + pluginSettingsStore.update(plugin.pluginId, key, value)} + /> + {:else if setting.type === "number"} +
+ pluginSettingsStore.update(plugin.pluginId, key, value)} + min={setting.min} + max={setting.max} + step={setting.step} + /> +
+ {:else if setting.type === "string"} + + pluginSettingsStore.update(plugin.pluginId, key, e.currentTarget.value)} + /> + {:else if setting.type === "select"} + (settingsState.homeUpcomingSubjectsMax = Number(value))} - options={[ - { value: "0", label: "All" }, - { value: "3", label: "3" }, - { value: "5", label: "5" }, - { value: "7", label: "7" }, - { value: "10", label: "10" }, - { value: "15", label: "15" }, - ]} - /> -
-
-
-

Maximum Assessments per Subject

-

Assessments shown for each included subject

-
- updatePluginSetting(plugin.pluginId, key, e.currentTarget.value)} - /> - {:else if setting.type === 'select'} - -
-
-
-
-

GitHub latest version override

-

Pretend a newer GitHub release exists to test the update badge. Only applies when dev mode is on.

-
- { - settingsState.devGhReleaseVersionOverride = e.currentTarget.value; - }} - class="px-2 py-1 text-xs rounded border bg-white dark:bg-zinc-800 border-zinc-300 dark:border-zinc-700 text-zinc-900 dark:text-zinc-100" - /> -
-
- {/if} - {/if} -
+ diff --git a/src/interface/pages/settings/pluginSettingsState.svelte.ts b/src/interface/pages/settings/pluginSettingsState.svelte.ts new file mode 100644 index 00000000..a5a73415 --- /dev/null +++ b/src/interface/pages/settings/pluginSettingsState.svelte.ts @@ -0,0 +1,101 @@ +import browser from "webextension-polyfill"; +import { isSeqtaEngageExperience } from "@/seqta/utils/isSeqtaEngage"; +import type { + BooleanSetting, + ButtonSetting, + ComponentSetting, + HotkeySetting, + NumberSetting, + SelectSetting, + StringSetting, +} from "@/plugins/core/types"; + +type SettingType = + | (Omit & { type: "boolean"; id: string }) + | (Omit & { type: "string"; id: string }) + | (Omit & { type: "number"; id: string }) + | (Omit, "type"> & { + type: "select"; + id: string; + options: string[]; + }) + | (Omit & { type: "button"; id: string }) + | (Omit & { type: "hotkey"; id: string }) + | (Omit & { + type: "component"; + id: string; + component: unknown; + }); + +export type PluginSettingsEntry = { + pluginId: string; + name: string; + description: string; + beta?: boolean; + settings: Record; + disableToggle?: boolean; +}; + +let loadPromise: Promise | null = null; + +class PluginSettingsStore { + loaded = $state(false); + loading = $state(false); + plugins = $state([]); + values = $state>>({}); + + ensureLoaded(): Promise { + if (this.loaded) return Promise.resolve(); + if (loadPromise) return loadPromise; + + this.loading = true; + loadPromise = this.load().finally(() => { + this.loading = false; + this.loaded = true; + }); + return loadPromise; + } + + private async load(): Promise { + const { getAllPluginSettings } = await import("@/plugins"); + this.plugins = getAllPluginSettings().filter( + (plugin) => + !(isSeqtaEngageExperience() && plugin.pluginId === "global-search"), + ) as PluginSettingsEntry[]; + + for (const plugin of this.plugins) { + if (Object.keys(plugin.settings).length === 0) continue; + + const storageKey = `plugin.${plugin.pluginId}.settings`; + const stored = await browser.storage.local.get(storageKey); + this.values[plugin.pluginId] = (stored[storageKey] as Record) || {}; + + for (const [key, setting] of Object.entries(plugin.settings)) { + if ( + this.values[plugin.pluginId][key] === undefined && + setting.type !== "button" && + setting.type !== "component" + ) { + this.values[plugin.pluginId][key] = setting.default; + } + } + } + } + + async update(pluginId: string, key: string, value: unknown): Promise { + await this.ensureLoaded(); + + if (!this.values[pluginId]) { + this.values[pluginId] = {}; + } + this.values[pluginId][key] = value; + + const storageKey = `plugin.${pluginId}.settings`; + const stored = await browser.storage.local.get(storageKey); + const currentSettings = (stored[storageKey] || {}) as Record; + currentSettings[key] = value; + await browser.storage.local.set({ [storageKey]: currentSettings }); + } +} + +export const pluginSettingsStore = new PluginSettingsStore(); diff --git a/src/interface/pages/settings/sectionLoaders.ts b/src/interface/pages/settings/sectionLoaders.ts new file mode 100644 index 00000000..d0f3026b --- /dev/null +++ b/src/interface/pages/settings/sectionLoaders.ts @@ -0,0 +1,15 @@ +import type { Component } from "svelte"; +import type { SettingsSectionId } from "./shared"; + +export const SECTION_LOADERS: Record< + SettingsSectionId, + () => Promise<{ default: Component }> +> = { + account: () => import("./sections/account.svelte"), + general: () => import("./sections/generalOptions.svelte"), + appearance: () => import("./sections/appearance.svelte"), + timetable: () => import("./sections/plugins.svelte"), + assessments: () => import("./sections/plugins.svelte"), + features: () => import("./sections/plugins.svelte"), + advanced: () => import("./sections/advanced.svelte"), +}; diff --git a/src/interface/pages/settings/sections/account.svelte b/src/interface/pages/settings/sections/account.svelte new file mode 100644 index 00000000..377a7b13 --- /dev/null +++ b/src/interface/pages/settings/sections/account.svelte @@ -0,0 +1,110 @@ + + + + +{#if showCloudAccountCard} +
+
+ {#if showCloudCardHeader} +
+
+

BetterSEQTA Cloud

+

Account & sync

+
+
+ +
+
+ {/if} + {#if cloudState.isLoggedIn} +
+ {#if showCloudCardHeader} + + showDisclaimer( + onConfirm, + onCancel, + "Restore from cloud?", + "This will replace your local settings with the cloud backup. Continue?", + )} + /> + {/if} + {#if showFounderBadgeSetting} + (settingsState.showTitlebarFounderBadge = isOn), + }} + /> + {/if} +
+ {:else if showFounderBadgeSetting} +
+ Sign in to Cloud first. +
+ {/if} +
+
+{/if} + + diff --git a/src/interface/pages/settings/sections/advanced.svelte b/src/interface/pages/settings/sections/advanced.svelte new file mode 100644 index 00000000..afbae8a8 --- /dev/null +++ b/src/interface/pages/settings/sections/advanced.svelte @@ -0,0 +1,248 @@ + + + (settingsState.onoff = isOn), + }} +/> + +{#if $settingsState.devMode && matchesSearch( + searchQuery, + "Developer Mode", + "Verbose logging", + "Delay loading screen", + "Sensitive Hider", + "Mock Notices", + "Show Privacy Notification", + "Show Theme of the Month", + "Export cloud settings JSON", + "API Base URL", + "GitHub latest version override", +)} +
+
+
+

Developer Mode

+

+ Enables developer mode, allowing you to test new features and changes. +

+
+
+ (settingsState.devMode = isOn)} + /> +
+
+
+
+

Verbose logging

+

+ Show diagnostic console output (indexer, theme manager, timetable colour patch, etc.) +

+
+
+ (settingsState.verboseLogging = isOn)} + /> +
+
+
+
+

Delay loading screen

+

+ Keep the loading overlay visible for 5 extra seconds so you can preview canvas variants. +

+
+
+ (settingsState.devDelayLoadingScreen = isOn)} + /> +
+
+
+
+

Sensitive Hider

+

+ Replace sensitive content with mock data +

+
+
+ (settingsState.hideSensitiveContent = isOn)} + /> +
+
+
+
+

Mock Notices

+

+ Use fake notice data on homepage instead of real data +

+
+
+ (settingsState.mockNotices = isOn)} + /> +
+
+
+
+

Show Privacy Notification

+

+ Show the privacy notification popup on next page load +

+
+
+
+
+
+
+

Show Theme of the Month

+

+ Fetch and show the current month's popup now (ignores dismissed state) +

+
+
+
+
+
+
+

Export cloud settings JSON

+

+ Download the same payload as cloud sync (OAuth tokens stripped). For debugging and server + testing. +

+
+
+
+
+
+
+
+

API Base URL (session only)

+

+ Override the content API host for this browser session. Cleared on restart. Affects + themes, theme of the month, and other server-driven content. +

+ {#if devApiBaseActive} +

+ Override active: {devApiBaseActive} +

+ {/if} +
+
+
+ +
+
+
+
+

GitHub latest version override

+

+ Pretend a newer GitHub release exists to test the update badge. Only applies when dev mode + is on. +

+
+ { + settingsState.devGhReleaseVersionOverride = e.currentTarget.value; + }} + class="px-2 py-1 text-xs rounded border bg-white dark:bg-zinc-800 border-zinc-300 dark:border-zinc-700 text-zinc-900 dark:text-zinc-100" + /> +
+
+{/if} diff --git a/src/interface/pages/settings/sections/appearance.svelte b/src/interface/pages/settings/sections/appearance.svelte new file mode 100644 index 00000000..72f5b087 --- /dev/null +++ b/src/interface/pages/settings/sections/appearance.svelte @@ -0,0 +1,105 @@ + + +{#each [ + { + title: "Custom Theme Colour", + description: "Customise the overall theme colour of SEQTA Learn", + id: 4, + Component: PickerSwatch, + props: { onClick: showColourPicker }, + }, + { + title: "Interface Font", + description: "Choose the typeface used across SEQTA Learn", + id: 16, + Component: Button, + props: { onClick: showFontPicker, text: "Change" }, + }, +] as option (option.id)} + +{/each} + +{#if !isEngage && matchesSearch(searchQuery, "Sidebar Style", "Item Size", "Corner Radius", "Active Indicator", "Sidebar Width", "Transparency Effects", "Blur Strength")} +
+ +
+{/if} + +{#if matchesSearch(searchQuery, "Adaptive Theme Colour", "Soft Gradient", "Smooth colour transition")} +
+
+
+
+

Adaptive Theme Colour

+

+ Change the theme colour based on the current class (e.g. when viewing a course or + assessments page) +

+
+
+ (settingsState.adaptiveThemeColour = isOn)} + /> +
+
+ {#if $settingsState.adaptiveThemeColour} +
+
+

Soft Gradient

+

+ Use a soft gradient instead of a solid colour when viewing a class +

+
+
+ (settingsState.adaptiveThemeGradient = isOn)} + /> +
+
+
+
+

Smooth colour transition

+

+ Ease between class/subject colours when navigating instead of switching instantly +

+
+
+ (settingsState.adaptiveThemeColourTransition = isOn)} + /> +
+
+ {/if} +
+
+{/if} + + diff --git a/src/interface/pages/settings/sections/generalOptions.svelte b/src/interface/pages/settings/sections/generalOptions.svelte new file mode 100644 index 00000000..6df64ae7 --- /dev/null +++ b/src/interface/pages/settings/sections/generalOptions.svelte @@ -0,0 +1,244 @@ + + +{#each generalOptions as option (option.id)} + + {#if option.id === 0 && $settingsState.performanceMode && matchesSearch(searchQuery, "Performance Mode", "Global Search", "Assessment Averages", "enable anyway", "paused")} +
+
+

+ Paused for performance — enable anyway: +

+
+ {#each PERFORMANCE_HEAVY_PLUGINS as heavy (heavy.id)} +
+
+

{heavy.name}

+

{heavy.description}

+
+ setPerformanceModePluginOverride(heavy.id, forceOn)} + /> +
+ {/each} +
+
+
+ {/if} +{/each} + +{#if matchesSearch( + searchQuery, + "Home Page Assessments", + "Include Past Assessments", + "Maximum Subjects", + "Maximum Assessments per Subject", +)} +
+
+
+
+

Home Page Assessments

+

+ Limit upcoming assessments shown on the home page by subject +

+
+
+
+
+

Include Past Assessments

+

+ Show past-due assessments from the upcoming list, matching the Assessments page +

+
+
+ (settingsState.homeUpcomingIncludePast = isOn)} + /> +
+
+
+
+

Maximum Subjects

+

+ Number of subjects to include, ordered by soonest due date +

+
+ + (settingsState.homeUpcomingAssessmentsPerSubjectMax = Number(value))} + options={[ + { value: "0", label: "All" }, + { value: "1", label: "1" }, + { value: "2", label: "2" }, + { value: "3", label: "3" }, + { value: "5", label: "5" }, + { value: "10", label: "10" }, + ]} + /> +
+
+
+{/if} diff --git a/src/interface/pages/settings/sections/plugins.svelte b/src/interface/pages/settings/sections/plugins.svelte new file mode 100644 index 00000000..3d781215 --- /dev/null +++ b/src/interface/pages/settings/sections/plugins.svelte @@ -0,0 +1,12 @@ + + + diff --git a/src/interface/pages/settings/shared.ts b/src/interface/pages/settings/shared.ts new file mode 100644 index 00000000..bc6522f9 --- /dev/null +++ b/src/interface/pages/settings/shared.ts @@ -0,0 +1,47 @@ +export const ALL_SETTINGS_SECTIONS = [ + "account", + "general", + "appearance", + "timetable", + "assessments", + "features", + "advanced", +] as const; + +export type SettingsSectionId = (typeof ALL_SETTINGS_SECTIONS)[number]; + +export type SettingsSectionSharedProps = { + showColourPicker: () => void; + showFontPicker: () => void; + showDisclaimer: ( + onConfirm: () => void, + onCancel: () => void, + title?: string, + message?: string, + ) => void; + showCloudPanel: () => void; + searchQuery?: string; +}; + +export function matchesSearch( + searchQuery: string, + ...parts: Array +): boolean { + const q = searchQuery.trim().toLowerCase(); + return !q || parts.some((part) => part?.toLowerCase().includes(q)); +} + +export const PLUGIN_SECTION_BY_ID: Record = { + "profile-picture": "account", + "animated-background": "appearance", + "background-music": "appearance", + timetable: "timetable", + timetableEdit: "timetable", + "assessments-overview": "assessments", + "assessments-average": "assessments", + "grade-analytics": "assessments", + "global-search": "features", + "enhanced-navigation": "features", + messageFolders: "features", + notificationCollector: "features", +}; diff --git a/src/interface/pages/store.svelte b/src/interface/pages/store.svelte index 6713d253..a8e377b3 100644 --- a/src/interface/pages/store.svelte +++ b/src/interface/pages/store.svelte @@ -175,11 +175,18 @@ onMount(async () => { window.addEventListener('bsplus:highlight-theme', onHighlightThemeEvent); - await fetchThemes(); - await fetchCurrentThemes(); - - const pending = consumePendingHighlightThemeId(); - if (pending) focusThemeById(pending); + const load = async () => { + await fetchThemes(); + await fetchCurrentThemes(); + const pending = consumePendingHighlightThemeId(); + if (pending) focusThemeById(pending); + }; + + if (typeof requestIdleCallback === "function") { + requestIdleCallback(() => void load(), { timeout: 2500 }); + } else { + void load(); + } return () => { window.removeEventListener('bsplus:highlight-theme', onHighlightThemeEvent); diff --git a/src/plugins/built-in/animatedBackground/index.ts b/src/plugins/built-in/animatedBackground/index.ts index b5972447..67ee6add 100644 --- a/src/plugins/built-in/animatedBackground/index.ts +++ b/src/plugins/built-in/animatedBackground/index.ts @@ -11,6 +11,7 @@ import { syncAnimatedBackground, updateAnimationSpeed, } from "./backgroundLayers"; +import { isPerformanceMode } from "@/seqta/utils/performanceMode"; const settings = defineSettings({ speed: numberSetting({ @@ -40,6 +41,11 @@ const animatedBackgroundPlugin: Plugin = { settings: instance.settings, run: async (api) => { + if (isPerformanceMode()) { + removeAnimatedBackgroundLayers(); + return () => removeAnimatedBackgroundLayers(); + } + await syncAnimatedBackground(api); const resync = () => void syncAnimatedBackground(api); diff --git a/src/plugins/built-in/backgroundMusic/index.ts b/src/plugins/built-in/backgroundMusic/index.ts index 0a9569ee..d2fc22bc 100644 --- a/src/plugins/built-in/backgroundMusic/index.ts +++ b/src/plugins/built-in/backgroundMusic/index.ts @@ -8,6 +8,7 @@ import { import styles from "./styles.css?inline"; import BackgroundMusicSetting from "./BackgroundMusicSetting.svelte"; import localforage from "localforage"; +import { isPerformanceMode } from "@/seqta/utils/performanceMode"; const settings = defineSettings({ uploader: componentSetting({ @@ -187,6 +188,10 @@ const backgroundMusicPlugin: Plugin = { defaultEnabled: false, run: async (api) => { + if (isPerformanceMode()) { + return () => stopAudio(); + } + await api.storage.loaded; type BgSettings = { volume?: number; pauseOnHidden?: boolean }; diff --git a/src/plugins/built-in/globalSearch/lazy.ts b/src/plugins/built-in/globalSearch/lazy.ts index 8653afaf..7cda8f78 100644 --- a/src/plugins/built-in/globalSearch/lazy.ts +++ b/src/plugins/built-in/globalSearch/lazy.ts @@ -17,6 +17,7 @@ import { isValidHotkey, } from "./src/utils/hotkeyUtils"; import { titleBarState } from "@/seqta/ui/titlebar/titleBarState.svelte"; +import { isPluginAllowedInPerformanceMode } from "@/seqta/utils/performanceMode"; const settings = defineSettings({ searchHotkey: hotkeySetting({ @@ -91,6 +92,7 @@ const runGlobalSearch = globalSearchPlugin.run!; globalSearchPlugin.run = async (api) => { if (isSeqtaEngageExperience() || isSeqtaLoginPage()) return () => {}; + if (!isPluginAllowedInPerformanceMode("global-search")) return () => {}; // Eager chrome (like Analytics menu injection) — heavy chunk loads behind it. const hotkey = isValidHotkey(api.settings.searchHotkey ?? "") diff --git a/src/plugins/built-in/globalSearch/src/core/index.ts b/src/plugins/built-in/globalSearch/src/core/index.ts index b81cbdcb..69d3e40c 100644 --- a/src/plugins/built-in/globalSearch/src/core/index.ts +++ b/src/plugins/built-in/globalSearch/src/core/index.ts @@ -12,6 +12,7 @@ import { getStoredPassiveItems, installPassiveObserver, } from "../indexing/passiveObserver"; +import { globalSearchIndexingEnabled } from "@/seqta/utils/performanceMode"; function scheduleIdleIndexing(run: () => void): void { if (typeof requestIdleCallback === "function") { @@ -83,7 +84,7 @@ const globalSearchPlugin: Plugin<{}> = { (await import("../indexing/selfTests")).runGlobalSearchSelfTests(), }; - if (api.settings.passiveIndexing) { + if (globalSearchIndexingEnabled(!!api.settings.passiveIndexing)) { try { installPassiveObserver(); } catch (error) { @@ -91,7 +92,10 @@ const globalSearchPlugin: Plugin<{}> = { } } - if (api.settings.runIndexingOnLoad && !isIndexingPaused()) { + if ( + globalSearchIndexingEnabled(!!api.settings.runIndexingOnLoad) && + !isIndexingPaused() + ) { scheduleIdleIndexing(() => { if (!isIndexingPaused()) void runIndexing(); }); diff --git a/src/plugins/built-in/globalSearch/src/core/mountSearchBar.ts b/src/plugins/built-in/globalSearch/src/core/mountSearchBar.ts index 013448ef..a37cd66f 100644 --- a/src/plugins/built-in/globalSearch/src/core/mountSearchBar.ts +++ b/src/plugins/built-in/globalSearch/src/core/mountSearchBar.ts @@ -3,6 +3,7 @@ import { unmount } from "svelte"; import { warmUpVectorSearchOnInteraction } from "../search/vector/vectorSearch"; import { formatHotkeyForDisplay, isValidHotkey } from "../utils/hotkeyUtils"; import { waitForElm } from "@/seqta/utils/waitForElm"; +import { transparencyEnabled } from "@/seqta/utils/performanceMode"; import browser from "webextension-polyfill"; type AppRef = { @@ -295,7 +296,7 @@ export async function mountSearchBar( SearchBar, searchRoot.attachShadow({ mode: "open" }), { - transparencyEffects: api.settings.transparencyEffects, + transparencyEffects: transparencyEnabled(), showRecentFirst: api.settings.showRecentFirst, searchHotkey: currentHotkey, }, diff --git a/src/plugins/built-in/globalSearch/src/indexing/indexer.ts b/src/plugins/built-in/globalSearch/src/indexing/indexer.ts index 287e8783..24e27436 100644 --- a/src/plugins/built-in/globalSearch/src/indexing/indexer.ts +++ b/src/plugins/built-in/globalSearch/src/indexing/indexer.ts @@ -9,6 +9,7 @@ import { INDEX_SCHEMA_VERSION, SCHEMA_VERSION_KEY } from "./schemaVersion"; import { resetSearchIndexes } from "./resetIndexes"; import { isIndexingPaused } from "./indexingPause"; import { setIndexingActive } from "./indexingState"; +import { isPluginBlockedByPerformanceMode } from "@/seqta/utils/performanceMode"; import { verboseDebug } from '@/utils/verboseLog'; const META_STORE = "meta"; @@ -286,6 +287,11 @@ function dispatchVectorProgress( } export async function runIndexing(): Promise { + if (isPluginBlockedByPerformanceMode("global-search")) { + verboseDebug("[Indexer] Skipping indexing — performance mode blocks Global Search."); + return; + } + if (isIndexingPaused()) { verboseDebug( "[Indexer] Skipping indexing — index was reset; reload the page to rebuild.", diff --git a/src/plugins/built-in/globalSearch/src/indexing/passiveObserver.ts b/src/plugins/built-in/globalSearch/src/indexing/passiveObserver.ts index 31b12fd9..38685bca 100644 --- a/src/plugins/built-in/globalSearch/src/indexing/passiveObserver.ts +++ b/src/plugins/built-in/globalSearch/src/indexing/passiveObserver.ts @@ -13,6 +13,7 @@ import { decorateIndexItems } from "./renderComponents"; import { isIndexingPaused } from "./indexingPause"; import { isIndexingActive } from "./indexingState"; import { isAssessmentListRoute } from "./routeFilters"; +import { isPluginBlockedByPerformanceMode } from "@/seqta/utils/performanceMode"; /** * Passive network observer. @@ -481,6 +482,7 @@ async function consumeResponse( url: string, requestBody: unknown, ): Promise { + if (isPluginBlockedByPerformanceMode("global-search")) return; if (!response.ok) return; const route = normalizeSeqtaPath(url); diff --git a/src/plugins/built-in/gradeAnalytics/GradeAnalyticsPage.svelte b/src/plugins/built-in/gradeAnalytics/GradeAnalyticsPage.svelte index 8808b2ba..98c1bf8e 100644 --- a/src/plugins/built-in/gradeAnalytics/GradeAnalyticsPage.svelte +++ b/src/plugins/built-in/gradeAnalytics/GradeAnalyticsPage.svelte @@ -21,6 +21,9 @@ } from "./timeRange"; import { openAnalyticsPrivacyPopup } from "./openAnalyticsPrivacyPopup"; import { settingsState } from "@/seqta/utils/listeners/SettingsState"; + import { animationsEnabled } from "@/seqta/utils/performanceMode"; + + let { simpleMode = false } = $props<{ simpleMode?: boolean }>(); let analyticsData: Assessment[] | null = $state(null); let loading = $state(true); @@ -40,7 +43,7 @@ let timestampInterval: ReturnType | null = null; let contentReady = $state(false); - const fadeDuration = $derived($settingsState.animations ? 200 : 0); + const fadeDuration = $derived(animationsEnabled() ? 200 : 0); const formattedTimestamp = $derived(() => { if (!lastUpdated) return ""; @@ -401,6 +404,7 @@ />
+ {#if !simpleMode}
Grade range @@ -413,6 +417,7 @@ Per-subject trends
+ {/if} {@render sidebarActions()} @@ -436,6 +441,7 @@
+ {#if !simpleMode}
+ {/if}
diff --git a/src/plugins/built-in/gradeAnalytics/injectAnalyticsMenuItem.ts b/src/plugins/built-in/gradeAnalytics/injectAnalyticsMenuItem.ts index 80c62547..87d6b35f 100644 --- a/src/plugins/built-in/gradeAnalytics/injectAnalyticsMenuItem.ts +++ b/src/plugins/built-in/gradeAnalytics/injectAnalyticsMenuItem.ts @@ -11,6 +11,7 @@ import { isMenuOptionsOpen } from "@/seqta/utils/Openers/menuOptionsState"; import { settingsState } from "@/seqta/utils/listeners/SettingsState"; import { applyMenuItemVisibility } from "@/seqta/utils/menuItemVisibility"; import { getNativeMenuList } from "@/seqta/ui/sidebar/parseNativeMenu"; +import { rafThrottle } from "@/seqta/utils/rafThrottle"; const ANALYTICS_MENU_ICON = MenuitemSVGKey.analytics; export const ANALYTICS_MENU_CLASS = "betterseqta-grade-analytics-item"; @@ -88,10 +89,11 @@ export async function injectAnalyticsMenuItem(): Promise<() => void> { syncAnalyticsMenu(); + const scheduleAnalyticsSync = rafThrottle(syncAnalyticsMenu); const menuObserver = new MutationObserver(() => { const list = getNativeMenuList() ?? menuList; if (!list || isMenuOptionsOpen() || list.contains(analyticsItem)) return; - syncAnalyticsMenu(); + scheduleAnalyticsSync(); }); menuObserver.observe(menuList, { childList: true }); diff --git a/src/plugins/built-in/gradeAnalytics/ui.ts b/src/plugins/built-in/gradeAnalytics/ui.ts index a376b5be..4d8230bd 100644 --- a/src/plugins/built-in/gradeAnalytics/ui.ts +++ b/src/plugins/built-in/gradeAnalytics/ui.ts @@ -1,6 +1,7 @@ import tailwindStyles from "./tailwind.css?inline"; import pluginStyles from "./styles.css?inline"; import { settingsState } from "@/seqta/utils/listeners/SettingsState"; +import { isSimpleAnalyticsUi } from "@/seqta/utils/performanceMode"; import { mount, unmount } from "svelte"; import GradeAnalyticsPage from "./GradeAnalyticsPage.svelte"; import { buildContrastAccentPalette } from "./utils/accentColor"; @@ -121,6 +122,7 @@ function syncThemeToAnalyticsUi() { if (analyticsRoot) { syncThemeFromPage(analyticsRoot); analyticsRoot.classList.toggle("bsplus-analytics-motion", !!settingsState.animations); + analyticsRoot.classList.toggle("bsplus-analytics-simple", isSimpleAnalyticsUi()); } } @@ -204,7 +206,10 @@ export function renderAnalyticsPage(container: HTMLElement) { attributeFilter: ["class"], }); - currentApp = mount(GradeAnalyticsPage, { target: analyticsRoot }); + currentApp = mount(GradeAnalyticsPage, { + target: analyticsRoot, + props: { simpleMode: isSimpleAnalyticsUi() }, + }); } export function unmountAnalyticsPage() { diff --git a/src/plugins/built-in/notificationCollector/index.ts b/src/plugins/built-in/notificationCollector/index.ts index 033f3373..608a1f6a 100644 --- a/src/plugins/built-in/notificationCollector/index.ts +++ b/src/plugins/built-in/notificationCollector/index.ts @@ -1,4 +1,4 @@ -import type { Plugin } from "../../core/types"; +import { isPerformanceMode } from "@/seqta/utils/performanceMode"; import { booleanSetting } from "@/plugins/core/settingsHelpers"; import { isSeqtaEngageExperience } from "@/seqta/utils/isSeqtaEngage"; import { verboseInfo } from "@/utils/verboseLog"; @@ -60,7 +60,7 @@ const notificationCollectorPlugin: Plugin< let pollInterval: number | null = null; let isVisible = !document.hidden; let archiveSyncInFlight = false; - const baseInterval = 30000; + const baseInterval = isPerformanceMode() ? 60000 : 30000; const maxInterval = 300000; api.storage.lastNotificationCount ||= 0; diff --git a/src/plugins/built-in/themes/theme-manager.ts b/src/plugins/built-in/themes/theme-manager.ts index 7955cc1c..24ae6f18 100644 --- a/src/plugins/built-in/themes/theme-manager.ts +++ b/src/plugins/built-in/themes/theme-manager.ts @@ -8,6 +8,7 @@ import { } from "@/types/CustomThemes"; import { BSPLUS_PENDING_THEME_ENSURE_AFTER_CLOUD_KEY } from "@/seqta/utils/cloudSettingsSync"; import { settingsState } from "@/seqta/utils/listeners/SettingsState"; +import { fullMotionEffectsEnabled } from "@/seqta/utils/performanceMode"; import debounce from "@/seqta/utils/debounce"; import { themeUpdates } from "@/interface/hooks/ThemeUpdates"; import { getApiBase } from "@/seqta/utils/DevApiBase"; @@ -125,7 +126,7 @@ export class ThemeManager { private async applyViewTransition(callback: () => void): Promise { if ( !document.startViewTransition || - !settingsState.animations || + !fullMotionEffectsEnabled() || window.matchMedia("(prefers-reduced-motion: reduce)").matches ) { // Just run the callback without animation if transitions not supported diff --git a/src/plugins/core/manager.ts b/src/plugins/core/manager.ts index 9cc8d508..741f267a 100644 --- a/src/plugins/core/manager.ts +++ b/src/plugins/core/manager.ts @@ -13,6 +13,7 @@ import { createPluginAPI } from "./createAPI"; import browser from "webextension-polyfill"; import { settingsState } from "@/seqta/utils/listeners/SettingsState"; import { verboseInfo } from "@/utils/verboseLog"; +import { isPluginAllowedInPerformanceMode } from "@/seqta/utils/performanceMode"; interface PluginSettingsStorage { enabled?: boolean; @@ -191,6 +192,14 @@ export class PluginManager { } } + if (!isPluginAllowedInPerformanceMode(pluginId)) { + this.disposePluginAPI(pluginId); + verboseInfo( + `Plugin "${pluginId}" paused by performance mode`, + ); + return; + } + // Inject plugin styles if provided if (plugin.styles) { const styleElement = document.createElement("style"); diff --git a/src/plugins/monofile.ts b/src/plugins/monofile.ts index a4578f73..9768e59f 100644 --- a/src/plugins/monofile.ts +++ b/src/plugins/monofile.ts @@ -8,6 +8,8 @@ import { delay } from "@/seqta/utils/delay"; import stringToHTML from "@/seqta/utils/stringToHTML"; import { MessageHandler } from "@/seqta/utils/listeners/MessageListener"; import { settingsState } from "@/seqta/utils/listeners/SettingsState"; +import { animationsEnabled, fullMotionEffectsEnabled, isPerformanceMode, syncPerformanceModeEffects } from "@/seqta/utils/performanceMode"; +import { animatePopupOpen } from "@/seqta/utils/popupAnimation"; import { StorageChangeHandler } from "@/seqta/utils/listeners/StorageChanges"; import { eventManager } from "@/seqta/utils/listeners/EventManager"; import debounce from "@/seqta/utils/debounce"; @@ -253,11 +255,21 @@ async function LoadPageElements(): Promise { async function handleNotices(node: Element): Promise { if (!(node instanceof HTMLElement)) return; - if (!settingsState.animations) return; + if (!animationsEnabled()) return; + + if (!fullMotionEffectsEnabled()) { + node.style.opacity = "0"; + node.style.transform = "translateY(8px)"; + node.style.transition = "opacity 0.2s ease, transform 0.2s ease"; + requestAnimationFrame(() => { + node.style.opacity = "1"; + node.style.transform = "none"; + }); + return; + } node.style.opacity = "0"; - // get index of node in relation to parent const index = Array.from(node.parentElement!.children).indexOf(node); const { animate } = await loadMotion(); @@ -370,7 +382,7 @@ async function handleMessages(node: Element): Promise { document.title = "Direct Messages ― SEQTA Learn"; SortMessagePageItems(node); - if (!settingsState.animations) return; + if (!animationsEnabled() || !fullMotionEffectsEnabled()) return; // Hides messages on page load const style = document.createElement("style"); @@ -398,7 +410,7 @@ async function handleMessages(node: Element): Promise { async function handleDashboard(node: Element): Promise { if (!(node instanceof HTMLElement)) return; - if (!settingsState.animations) return; + if (!animationsEnabled() || !fullMotionEffectsEnabled()) return; const style = document.createElement("style"); style.classList.add("dashboardHider"); @@ -429,7 +441,7 @@ async function handleDashboard(node: Element): Promise { async function handleDocuments(node: Element): Promise { if (!(node instanceof HTMLElement)) return; - if (!settingsState.animations) return; + if (!animationsEnabled() || !fullMotionEffectsEnabled()) return; await waitForElm(".document", true, 10); try { @@ -453,7 +465,7 @@ async function handleDocuments(node: Element): Promise { async function handleReports(node: Element): Promise { if (!(node instanceof HTMLElement)) return; - if (!settingsState.animations) return; + if (!animationsEnabled() || !fullMotionEffectsEnabled()) return; await waitForElm(".report", true, 10); try { @@ -668,13 +680,17 @@ export function showConflictPopup() { document.getElementById("container")?.append(background); // CSS fade — avoid Motion on conflict overlay (not critical-path shell, but keeps Motion off this import path). - if (settingsState.animations) { - const el = background as HTMLElement; - el.style.opacity = "0"; - el.style.transition = "opacity 200ms ease-in-out"; - requestAnimationFrame(() => { - el.style.opacity = "1"; - }); + if (animationsEnabled()) { + if (fullMotionEffectsEnabled()) { + const el = background as HTMLElement; + el.style.opacity = "0"; + el.style.transition = "opacity 200ms ease-in-out"; + requestAnimationFrame(() => { + el.style.opacity = "1"; + }); + } else { + animatePopupOpen(background); + } } background.addEventListener("click", (event) => { @@ -748,11 +764,28 @@ export function init() { new StorageChangeHandler(); new MessageHandler(); - void updateAllColors(); - applySelectedFont(); + syncPerformanceModeEffects(); + const deferBootWork = (fn: () => void) => { + if (typeof requestIdleCallback === "function") { + requestIdleCallback(fn, { timeout: 3000 }); + } else { + setTimeout(fn, 100); + } + }; + deferBootWork(() => { + void updateAllColors(); + applySelectedFont(); + }); + + let hashColorTimer: ReturnType | null = null; window.addEventListener("hashchange", () => { - if (settingsState.adaptiveThemeColour) void updateAllColors(); + if (!settingsState.adaptiveThemeColour) return; + if (hashColorTimer) clearTimeout(hashColorTimer); + hashColorTimer = setTimeout(() => { + hashColorTimer = null; + void updateAllColors(); + }, isPerformanceMode() ? 200 : 80); }); if (!onLogin) { loading(); @@ -824,9 +857,14 @@ export function init() { ); } - [1000, 1200, 1500].forEach((delay) => - setTimeout(focusEditor, delay), - ); + let attempts = 0; + const tryFocus = () => { + focusEditor(); + if (attempts++ < 5) { + requestAnimationFrame(tryFocus); + } + }; + requestAnimationFrame(tryFocus); }, ); diff --git a/src/seqta/ui/AddBetterSEQTAElements.ts b/src/seqta/ui/AddBetterSEQTAElements.ts index bdc782af..71f379bb 100644 --- a/src/seqta/ui/AddBetterSEQTAElements.ts +++ b/src/seqta/ui/AddBetterSEQTAElements.ts @@ -17,6 +17,8 @@ import { delay } from "@/seqta/utils/delay"; import { LUCIDE_MOON_ICON_SVG } from "@/lib/icons/lucideMoon"; import { LUCIDE_SUN_ICON_SVG } from "@/lib/icons/lucideSun"; import { ensureTitlebarFounderBadgeMounted, refreshTitlebarFounderBadge } from "@/seqta/ui/founderBadge/mountTitlebarFounderBadge"; +import { isPerformanceMode } from "@/seqta/utils/performanceMode"; +import { rafThrottle } from "@/seqta/utils/rafThrottle"; let cachedUserInfo: any = null; let userInfoFetchPromise: Promise | null = null; @@ -145,8 +147,7 @@ export async function AddBetterSEQTAElements() { setupEventListeners(); await addDarkLightToggle(); customizeMenuToggle(); - // Kept as fallback if the custom Svelte sidebar fails to mount. - setupSidebarAccessibility(); + maybeSetupSidebarAccessibility(); } addExtensionSettings(); @@ -500,11 +501,18 @@ async function setupEngageSettingsButton() { } (content as HTMLElement).dataset.bsplusEngageSettingsWatch = "1"; - const observer = new MutationObserver(() => { - if (document.getElementById("AddedSettings")) return; - void tryMount(); - }); - observer.observe(content, { childList: true, subtree: true }); + let engageRemountTimer: ReturnType | null = null; + const debouncedTryMount = () => { + if (engageRemountTimer) clearTimeout(engageRemountTimer); + engageRemountTimer = setTimeout(() => { + engageRemountTimer = null; + if (document.getElementById("AddedSettings")) return; + void tryMount(); + }, isPerformanceMode() ? 300 : 80); + }; + + const observer = new MutationObserver(debouncedTryMount); + observer.observe(content, { childList: true, subtree: !isPerformanceMode() }); } function GetLightDarkModeString() { @@ -572,6 +580,12 @@ function customizeMenuToggle() { } } +function maybeSetupSidebarAccessibility() { + const menu = document.getElementById("menu"); + if (menu?.classList.contains("bsplus-custom-sidebar")) return; + setupSidebarAccessibility(); +} + function setupSidebarAccessibility() { updateSidebarAccessibility(); @@ -579,6 +593,7 @@ function setupSidebarAccessibility() { if (!menu) return; sidebarAccessibilityObserver?.disconnect(); + const throttledA11yUpdate = rafThrottle(scheduleSidebarAccessibilityUpdate); sidebarAccessibilityObserver = new MutationObserver((mutations) => { // Custom Svelte sidebar owns drill a11y — ignore its DOM (opening Goals/Folios // mutates a lot; re-running here used to help freeze the tab). @@ -603,7 +618,7 @@ function setupSidebarAccessibility() { return; } } - scheduleSidebarAccessibilityUpdate(); + throttledA11yUpdate(); }); sidebarAccessibilityObserver.observe(menu, { subtree: true, diff --git a/src/seqta/ui/Loading.ts b/src/seqta/ui/Loading.ts index f2ba8bb3..5d617f66 100644 --- a/src/seqta/ui/Loading.ts +++ b/src/seqta/ui/Loading.ts @@ -9,6 +9,7 @@ import { resolveLoadingTheme, type LoadingVariant, } from "./loadingVariants"; +import { isPerformanceMode } from "@/seqta/utils/performanceMode"; let stopCanvas: (() => void) | null = null; let unbindThemeGuard: (() => void) | null = null; @@ -320,7 +321,9 @@ export default function loading() { document.documentElement.append(host); applyVariantTheme(host, shadow, variant); - startCanvasForRoot(host, shadow, variant); + if (!isPerformanceMode()) { + startCanvasForRoot(host, shadow, variant); + } activeLoading = { host, shadow, variant }; unbindThemeGuard = bindLoadingThemeGuard(); diff --git a/src/seqta/ui/colors/Manager.ts b/src/seqta/ui/colors/Manager.ts index bb55220c..e24dc4c6 100644 --- a/src/seqta/ui/colors/Manager.ts +++ b/src/seqta/ui/colors/Manager.ts @@ -5,6 +5,7 @@ import { lightenAndPaleColor } from "./lightenAndPaleColor"; import ColorLuminance from "./ColorLuminance"; import { settingsState } from "@/seqta/utils/listeners/SettingsState"; import { getAdaptiveColour } from "@/seqta/utils/adaptiveThemeColour"; +import { adaptiveThemeTransitionEnabled, transparencyEnabled } from "@/seqta/utils/performanceMode"; import { getCustomThemeAdaptiveCssVariableBindings } from "@/seqta/ui/colors/customThemeAdaptiveBindings"; import { resolveExtensionAssetUrl } from "@/lib/extensionAssetUrl"; @@ -126,7 +127,7 @@ function getRepresentativeRgbChannels(s: string): { r: number; g: number; b: num } function applyColorsWith(selectedColor: string) { - if (settingsState.transparencyEffects) { + if (transparencyEnabled()) { document.documentElement.classList.add("transparencyEffects"); } @@ -253,7 +254,7 @@ export async function updateAllColors() { const shouldAnimate = settingsState.adaptiveThemeColour && - (settingsState.adaptiveThemeColourTransition ?? true) && + adaptiveThemeTransitionEnabled() && !!toHex; const applyImmediate = () => { diff --git a/src/seqta/ui/sidebar/mountCustomSidebar.ts b/src/seqta/ui/sidebar/mountCustomSidebar.ts index 9d27fa31..bfbf18cf 100644 --- a/src/seqta/ui/sidebar/mountCustomSidebar.ts +++ b/src/seqta/ui/sidebar/mountCustomSidebar.ts @@ -15,6 +15,8 @@ import { applySidebarStyleClass, clearSidebarAppearance, } from "./sidebarStyles"; +import { isPerformanceMode } from "@/seqta/utils/performanceMode"; +import { applyMenuItemVisibility } from "@/seqta/utils/menuItemVisibility"; const ROOT_ID = "bsplus-sidebar-root"; const MENU_CLASS = "bsplus-custom-sidebar"; @@ -32,6 +34,8 @@ let earlyPrepareStarted = false; let catchupTimers: ReturnType[] = []; let nativeMenuListenerAttached = false; let lastMenuFingerprint = ""; +let catchupSessionStarted = false; +let sidebarLookScheduled = false; const settingsListeners: Array<{ key: keyof SettingsState; @@ -68,10 +72,16 @@ function syncFromMenu(force = false) { * MutationObserver + scheduleSync cover ongoing changes; this only covers a short window. */ function startCatchupSync() { + if (catchupSessionStarted) { + syncFromMenu(); + return; + } + catchupSessionStarted = true; + for (const t of catchupTimers) clearTimeout(t); catchupTimers = []; // Immediate, then a few delayed passes (~1s total) instead of 50ms×60. - const delays = [0, 200, 500, 1000]; + const delays = isPerformanceMode() ? [0, 400, 1000] : [0, 200, 500, 1000]; for (const ms of delays) { catchupTimers.push( setTimeout(() => { @@ -84,16 +94,26 @@ function startCatchupSync() { } } +function scheduleSidebarLook() { + if (!menuEl || sidebarLookScheduled) return; + sidebarLookScheduled = true; + requestAnimationFrame(() => { + sidebarLookScheduled = false; + if (menuEl) applySidebarLook(menuEl); + }); +} + function onNativeMenuUpdated() { syncFromMenu(true); } function scheduleSync() { if (syncTimer) clearTimeout(syncTimer); + const delay = isPerformanceMode() ? 120 : 50; syncTimer = setTimeout(() => { syncTimer = null; syncFromMenu(); - }, 50); + }, delay); } /** @@ -325,11 +345,11 @@ export async function mountCustomSidebar(): Promise { "sidebarWidth", "sidebarBlur", ] as const) { - registerSetting(key, () => applySidebarLook(menuEl)); + registerSetting(key, () => scheduleSidebarLook()); } const resync = () => syncFromMenu(true); registerSetting("menuorder", resync); - registerSetting("menuitems", resync); + registerSetting("menuitems", () => applyMenuItemVisibility()); startCatchupSync(); clearPendingClass(); @@ -344,6 +364,7 @@ export function unmountCustomSidebar() { for (const t of catchupTimers) clearTimeout(t); catchupTimers = []; lastMenuFingerprint = ""; + catchupSessionStarted = false; clearSettingListeners(); diff --git a/src/seqta/ui/sidebar/parseNativeMenu.ts b/src/seqta/ui/sidebar/parseNativeMenu.ts index 2ce6369c..760ef828 100644 --- a/src/seqta/ui/sidebar/parseNativeMenu.ts +++ b/src/seqta/ui/sidebar/parseNativeMenu.ts @@ -12,9 +12,20 @@ export function getNativeMenuList( function readLabelText(label: HTMLElement | null): string { if (!label) return ""; - const clone = label.cloneNode(true) as HTMLElement; - clone.querySelectorAll("svg").forEach((svg) => svg.remove()); - return (clone.textContent ?? "").replace(/\s+/g, " ").trim(); + const cached = label.dataset.bsplusLabel; + if (cached) return cached; + + let text = ""; + for (const node of label.childNodes) { + if (node.nodeType === Node.TEXT_NODE) { + text += node.textContent ?? ""; + } else if (node instanceof HTMLElement && node.tagName !== "SVG") { + text += node.textContent ?? ""; + } + } + const normalized = text.replace(/\s+/g, " ").trim(); + if (normalized) label.dataset.bsplusLabel = normalized; + return normalized; } function readIconHtml(label: HTMLElement | null): string { diff --git a/src/seqta/ui/sidebar/sidebarState.svelte.ts b/src/seqta/ui/sidebar/sidebarState.svelte.ts index baeef4fd..8aaec86c 100644 --- a/src/seqta/ui/sidebar/sidebarState.svelte.ts +++ b/src/seqta/ui/sidebar/sidebarState.svelte.ts @@ -1,4 +1,5 @@ import { settingsState } from "@/seqta/utils/listeners/SettingsState"; +import { animationsEnabled } from "@/seqta/utils/performanceMode"; import { findNativeMenuEntry, getNativeMenuList, @@ -45,11 +46,7 @@ function ensureActive(el: Element | null | undefined) { function resetSidebarScroll() { const root = document.getElementById("bsplus-sidebar-root"); - if (!(root instanceof HTMLElement)) return; - root.scrollTop = 0; - requestAnimationFrame(() => { - root.scrollTop = 0; - }); + if (root instanceof HTMLElement) root.scrollTop = 0; } /** @@ -302,7 +299,7 @@ class SidebarState { this.drillStack = this.drillStack.slice(0, -1); resetSidebarScroll(); - if (settingsState.animations !== true) return; + if (!animationsEnabled()) return; this.drillReturning = true; window.setTimeout(() => { @@ -376,7 +373,7 @@ class SidebarState { // SEQTA rewrites `.active` on the route change. if (this.isDrilling) { this.enterFrameKey = null; - restoreCustomMenuActive(); + requestAnimationFrame(() => restoreCustomMenuActive()); } const native = findNativeMenuEntry(menu, item); diff --git a/src/seqta/ui/sidebar/sidebarStyles.ts b/src/seqta/ui/sidebar/sidebarStyles.ts index b4ad95fa..e70b4ea4 100644 --- a/src/seqta/ui/sidebar/sidebarStyles.ts +++ b/src/seqta/ui/sidebar/sidebarStyles.ts @@ -1,4 +1,5 @@ import { settingsState } from "@/seqta/utils/listeners/SettingsState"; +import { isPerformanceMode } from "@/seqta/utils/performanceMode"; export type SidebarStyleId = | "classic" @@ -118,10 +119,9 @@ export function applySidebarStyleClass( ); } -/** - * Apply Look CSS variables + non-default density/indicator classes. - * Safe to call with no menu (still sets width/blur/radius on `:root`). - */ +/** Safe to call with no menu (still sets width/blur/radius on `:root`). */ +let lastSidebarLookKey = ""; + export function applySidebarLook( menu: HTMLElement | null | undefined = document.getElementById("menu"), ) { @@ -129,7 +129,13 @@ export function applySidebarLook( const indicator = normalizeSidebarIndicator(settingsState.sidebarActiveIndicator); const width = normalizeSidebarWidth(settingsState.sidebarWidth); const radius = normalizeSidebarRadius(settingsState.sidebarCornerRadius); - const blur = normalizeSidebarBlur(settingsState.sidebarBlur); + const blur = isPerformanceMode() + ? 0 + : normalizeSidebarBlur(settingsState.sidebarBlur); + + const lookKey = `${density}|${indicator}|${width}|${radius}|${blur}`; + if (lookKey === lastSidebarLookKey) return; + lastSidebarLookKey = lookKey; const root = document.documentElement; root.style.setProperty("--bsplus-sidebar-width", `${SIDEBAR_WIDTH_PX[width]}px`); diff --git a/src/seqta/ui/titlebar/mountCustomTitleBar.ts b/src/seqta/ui/titlebar/mountCustomTitleBar.ts index 1efbad0b..8b06b11b 100644 --- a/src/seqta/ui/titlebar/mountCustomTitleBar.ts +++ b/src/seqta/ui/titlebar/mountCustomTitleBar.ts @@ -1,9 +1,12 @@ import { mount, unmount } from "svelte"; import { settingsState } from "@/seqta/utils/listeners/SettingsState"; import { isSeqtaEngageExperience, isSeqtaLoginPage } from "@/seqta/utils/isSeqtaEngage"; +import { isPluginAllowedInPerformanceMode } from "@/seqta/utils/performanceMode"; import { waitForSeqtaTitle } from "@/seqta/utils/waitForSeqtaShell"; import TitleBar from "./TitleBar.svelte"; import { titleBarState } from "./titleBarState.svelte"; +import { rafThrottle } from "@/seqta/utils/rafThrottle"; +import { isPerformanceMode } from "@/seqta/utils/performanceMode"; const ROOT_ID = "bsplus-title-root"; const TITLE_CLASS = "bsplus-custom-title"; @@ -30,6 +33,7 @@ function syncPageTitle() { } function needsSearchChip() { + if (!isPluginAllowedInPerformanceMode("global-search")) return false; const all = settingsState.getAll() as unknown as Record; const plugin = all["plugin.global-search.settings"] as | { enabled?: boolean } @@ -54,9 +58,10 @@ export async function waitForCustomTitleBarReady(timeoutMs = 10000) { await mountCustomTitleBar(); const start = Date.now(); + const pollMs = isPerformanceMode() ? 100 : 50; while (Date.now() - start < timeoutMs) { if (isReady()) break; - await new Promise((r) => setTimeout(r, 50)); + await new Promise((r) => setTimeout(r, pollMs)); } document.documentElement.classList.remove(PENDING_CLASS); } @@ -64,7 +69,10 @@ export async function waitForCustomTitleBarReady(timeoutMs = 10000) { function observeHost(host: HTMLElement) { hostObserver?.disconnect(); syncPageTitle(); - hostObserver = new MutationObserver(() => { + const debouncedSync = rafThrottle(() => { + syncPageTitle(); + }); + hostObserver = new MutationObserver((mutations) => { if (!document.getElementById(ROOT_ID)) { if (remountTimer) clearTimeout(remountTimer); remountTimer = setTimeout(() => { @@ -72,10 +80,21 @@ function observeHost(host: HTMLElement) { if (!settingsState.onoff || isSeqtaEngageExperience()) return; app = null; void mountCustomTitleBar(); - }, 50); + }, isPerformanceMode() ? 120 : 50); return; } - syncPageTitle(); + const titleChanged = mutations.some( + (m) => + m.type === "characterData" || + (m.type === "childList" && + [...m.addedNodes, ...m.removedNodes].some( + (n) => + n instanceof HTMLElement && + (n.matches?.('[data-testid="page-title"]') || + n.querySelector?.('[data-testid="page-title"]')), + )), + ); + if (titleChanged) debouncedSync(); }); hostObserver.observe(host, { childList: true, diff --git a/src/seqta/utils/Adders/AddExtensionSettings.ts b/src/seqta/utils/Adders/AddExtensionSettings.ts index 5436b63e..6501e2b6 100644 --- a/src/seqta/utils/Adders/AddExtensionSettings.ts +++ b/src/seqta/utils/Adders/AddExtensionSettings.ts @@ -3,23 +3,30 @@ import { closeExtensionPopup, SettingsClicked, } from "../Closers/closeExtensionPopup"; -import { SettingsResizer } from "@/seqta/ui/SettingsResizer"; let isSettingsRendered = false; let settingsLoadPromise: Promise | null = null; +let resizerAttached = false; function extensionOutsideClickHandler(extensionPopup: HTMLElement) { return (event: MouseEvent) => { if (!SettingsClicked) return; if (!(event.target as HTMLElement).closest("#AddedSettings")) { - // Clicks inside the shadow tree retarget to the host — keep open. if (event.target == extensionPopup) return; changeSettingsClicked(closeExtensionPopup()); } }; } +function ensureSettingsResizer() { + if (resizerAttached) return; + resizerAttached = true; + void import("@/seqta/ui/SettingsResizer").then(({ SettingsResizer }) => { + new SettingsResizer(); + }); +} + /** * Mount the settings host on `document.body` so `position: fixed` covers the * viewport on both SEQTA Learn and SEQTA Engage (Engage often lacks `#container` @@ -34,8 +41,6 @@ export function addExtensionSettings() { document.body.appendChild(extensionPopup); - new SettingsResizer(); - const handler = extensionOutsideClickHandler(extensionPopup); document.body.addEventListener("click", handler, false); } @@ -43,25 +48,15 @@ export function addExtensionSettings() { async function loadSettingsUi(extensionPopup: HTMLElement): Promise { if (isSettingsRendered) return; + ensureSettingsResizer(); + const [{ default: renderSvelte }, { default: Settings }] = await Promise.all([ import("@/interface/main"), import("@/interface/pages/settings.svelte"), ]); const shadow = extensionPopup.attachShadow({ mode: "open" }); - const mount = () => renderSvelte(Settings, shadow); - - if ("requestIdleCallback" in window) { - await new Promise((resolve) => { - requestIdleCallback(() => { - mount(); - resolve(); - }); - }); - } else { - mount(); - } - + renderSvelte(Settings, shadow); isSettingsRendered = true; } diff --git a/src/seqta/utils/Closers/closeExtensionPopup.ts b/src/seqta/utils/Closers/closeExtensionPopup.ts index 20d67f22..d39b4294 100644 --- a/src/seqta/utils/Closers/closeExtensionPopup.ts +++ b/src/seqta/utils/Closers/closeExtensionPopup.ts @@ -1,35 +1,13 @@ -import { settingsState } from "@/seqta/utils/listeners/SettingsState"; -import { animate } from "motion"; - import { settingsPopup } from "@/seqta/utils/settingsPopup"; +import { animateSettingsClose } from "@/seqta/utils/settingsPopupAnimation"; export let SettingsClicked = false; export const closeExtensionPopup = (extensionPopup?: HTMLElement) => { - if (!extensionPopup) - extensionPopup = document.getElementById("ExtensionPopup")!; + if (!extensionPopup) extensionPopup = document.getElementById("ExtensionPopup")!; - extensionPopup.classList.add("hide"); - if (settingsState.animations) { - const panel = extensionPopup.shadowRoot?.querySelector( - "[data-settings-panel]", - ); - animate(1, 0, { - onUpdate: (progress) => { - extensionPopup.style.opacity = Math.max(0, progress).toString(); - }, - duration: 0.18, - ease: "easeIn", - }); - if (panel) { - animate( - panel, - { scale: [1, 0], opacity: [1, 0] }, - { duration: 0.18, ease: "easeIn" }, - ); - } - } else { - extensionPopup.style.opacity = "0"; + if (extensionPopup) { + animateSettingsClose(extensionPopup); } settingsPopup.triggerClose(); diff --git a/src/seqta/utils/Openers/PopupManager.ts b/src/seqta/utils/Openers/PopupManager.ts index 5dc86c09..549433f4 100644 --- a/src/seqta/utils/Openers/PopupManager.ts +++ b/src/seqta/utils/Openers/PopupManager.ts @@ -1,4 +1,9 @@ import { settingsState } from "../listeners/SettingsState"; +import { fullMotionEffectsEnabled } from "@/seqta/utils/performanceMode"; +import { + animatePopupClose, + animatePopupOpen, +} from "@/seqta/utils/popupAnimation"; import { animate as motionAnimate, stagger } from "motion"; type AnimationTarget = string | Element | Element[] | NodeList | null; @@ -61,11 +66,15 @@ export async function closePopup() { return; } - await (motionAnimate as any)( - [popup, background], - { opacity: [1, 0], scale: [1, 0.95] }, - { duration: 0.25, easing: [0.22, 0.03, 0.26, 1] }, - ); + if (fullMotionEffectsEnabled()) { + await (motionAnimate as any)( + [popup, background], + { opacity: [1, 0], scale: [1, 0.95] }, + { duration: 0.25, easing: [0.22, 0.03, 0.26, 1] }, + ); + } else { + await animatePopupClose(background); + } background.remove(); isClosing = false; @@ -160,27 +169,31 @@ export function openPopup({ appContainer.append(background); if (settingsState.animations) { - (motionAnimate as any)( - [container, background], - { scale: [0, 1] }, - { type: "spring", stiffness: 220, damping: 18 }, - ); - - if (animateSelector) { - const targets = - typeof animateSelector === "string" - ? document.querySelectorAll(animateSelector) - : animateSelector; - + if (fullMotionEffectsEnabled()) { (motionAnimate as any)( - targets!, - { opacity: [0, 1], y: [10, 0] }, - { - delay: stagger(0.05, { startDelay: 0.1 }), - duration: 0.5, - easing: [0.22, 0.03, 0.26, 1], - }, + [container, background], + { scale: [0, 1] }, + { type: "spring", stiffness: 220, damping: 18 }, ); + + if (animateSelector) { + const targets = + typeof animateSelector === "string" + ? document.querySelectorAll(animateSelector) + : animateSelector; + + (motionAnimate as any)( + targets!, + { opacity: [0, 1], y: [10, 0] }, + { + delay: stagger(0.05, { startDelay: 0.1 }), + duration: 0.5, + easing: [0.22, 0.03, 0.26, 1], + }, + ); + } + } else { + animatePopupOpen(background); } } diff --git a/src/seqta/utils/attachNotificationsPanelAnimation.ts b/src/seqta/utils/attachNotificationsPanelAnimation.ts index 1f74c558..0f9a38e2 100644 --- a/src/seqta/utils/attachNotificationsPanelAnimation.ts +++ b/src/seqta/utils/attachNotificationsPanelAnimation.ts @@ -1,10 +1,6 @@ -import { animate } from "motion"; import { settingsState } from "@/seqta/utils/listeners/SettingsState"; import { waitForElm } from "@/seqta/utils/waitForElm"; -/** - * Finds the SEQTA notifications dropdown panel (the list container next to the bell). - */ function findNotificationPanel(): HTMLElement | null { const wrapper = document.querySelector(".connectedNotificationsWrapper"); if (!wrapper) return null; @@ -24,56 +20,82 @@ function findNotificationPanel(): HTMLElement | null { } function isPanelVisible(el: HTMLElement): boolean { - return ( - el.getClientRects().length > 0 && getComputedStyle(el).visibility !== "hidden" - ); + if (el.hidden || el.getAttribute("aria-hidden") === "true") return false; + return el.offsetWidth > 0 || el.offsetHeight > 0; } let lastVisible = false; -/** Invalidates in-flight open animations when the panel closes or reopens. */ -let motionGeneration = 0; +let observerStarted = false; +let trackedPanel: HTMLElement | null = null; +/** Ignore observer callbacks while we toggle animation classes. */ +let suppressSync = false; -function runOpenAnimation(panel: HTMLElement) { - const myGen = ++motionGeneration; +function setPanelOpen(panel: HTMLElement, open: boolean) { panel.classList.add("bsplus-notifications-panel"); + panel.style.removeProperty("opacity"); + panel.style.removeProperty("transform"); if (!settingsState.animations) { - panel.style.opacity = "1"; - panel.style.transform = "scale(1)"; + panel.classList.toggle("bsplus-notifications-panel--open", open); return; } - panel.style.opacity = "0"; - panel.style.transform = "scale(0)"; + const isOpen = panel.classList.contains("bsplus-notifications-panel--open"); + if (open === isOpen) return; - requestAnimationFrame(() => { - if (myGen !== motionGeneration) return; - animate(0, 1, { - onUpdate: (progress) => { - panel.style.opacity = String(progress); - panel.style.transform = `scale(${progress})`; - }, - type: "spring", - stiffness: 280, - damping: 20, - }); - }); + suppressSync = true; + + if (open) { + panel.classList.remove("bsplus-notifications-panel--open"); + void panel.offsetWidth; + panel.classList.add("bsplus-notifications-panel--open"); + } else { + panel.classList.remove("bsplus-notifications-panel--open"); + } + + const release = () => { + suppressSync = false; + }; + panel.addEventListener("transitionend", release, { once: true }); + window.setTimeout(release, 280); } -function clearPanelMotionStyles(panel: HTMLElement) { - motionGeneration++; - panel.style.opacity = ""; - panel.style.transform = ""; +function syncPanelState() { + if (suppressSync) return; + + const panel = findNotificationPanel(); + + if (!panel) { + if (lastVisible && trackedPanel?.isConnected) { + setPanelOpen(trackedPanel, false); + } + lastVisible = false; + trackedPanel = null; + return; + } + + if (trackedPanel && trackedPanel !== panel) { + setPanelOpen(trackedPanel, false); + } + trackedPanel = panel; + + const visible = isPanelVisible(panel); + if (visible === lastVisible) return; + + setPanelOpen(panel, visible); + lastVisible = visible; } /** - * Spring open / fade close for the native SEQTA notifications dropdown, matching ExtensionPopup. + * CSS open/close for the native SEQTA notifications dropdown. */ export function attachNotificationsPanelAnimation() { void setupNotificationsPanelAnimation(); } async function setupNotificationsPanelAnimation() { + if (observerStarted) return; + try { await waitForElm(".connectedNotificationsWrapper", true, 100, 60); } catch { @@ -83,46 +105,45 @@ async function setupNotificationsPanelAnimation() { const wrapper = document.querySelector(".connectedNotificationsWrapper"); if (!wrapper) return; - const sync = () => { - const panel = findNotificationPanel(); - // When SEQTA removes the dropdown from the DOM on close, we must reset - // lastVisible — otherwise the next open still looks "already visible" and skips animation. - if (!panel) { - if (lastVisible) { - lastVisible = false; - motionGeneration++; - } - return; - } + observerStarted = true; - const visible = isPanelVisible(panel); - if (visible === lastVisible) return; - - if (visible) { - runOpenAnimation(panel); - } else { - clearPanelMotionStyles(panel); - } - lastVisible = visible; + let syncFrame = 0; + const scheduleSync = () => { + cancelAnimationFrame(syncFrame); + syncFrame = requestAnimationFrame(() => { + syncFrame = 0; + syncPanelState(); + }); }; - const observer = new MutationObserver(() => { - sync(); + const observer = new MutationObserver((mutations) => { + if ( + suppressSync || + !mutations.some( + (m) => + m.type === "childList" || + (m.type === "attributes" && + (m.attributeName === "hidden" || m.attributeName === "aria-hidden")), + ) + ) { + return; + } + scheduleSync(); }); observer.observe(wrapper, { subtree: true, childList: true, attributes: true, - attributeFilter: ["style", "class"], + attributeFilter: ["style", "class", "hidden", "aria-hidden"], }); - document.addEventListener( + wrapper.addEventListener( "click", () => { - requestAnimationFrame(() => requestAnimationFrame(sync)); + requestAnimationFrame(() => requestAnimationFrame(scheduleSync)); }, true, ); - sync(); + scheduleSync(); } diff --git a/src/seqta/utils/defaultSettings.ts b/src/seqta/utils/defaultSettings.ts index bcd57396..09717594 100644 --- a/src/seqta/utils/defaultSettings.ts +++ b/src/seqta/utils/defaultSettings.ts @@ -48,6 +48,8 @@ export function getDefaultSettingsState(): SettingsState { originalSelectedColor: "", DarkMode: true, animations: !isLowEndDevice, + performanceMode: isLowEndDevice, + performanceModePluginOverrides: {}, assessmentsAverage: false, defaultPage: "home", homeUpcomingSubjectsMax: 5, diff --git a/src/seqta/utils/listeners/EventManager.ts b/src/seqta/utils/listeners/EventManager.ts index 7f6efa54..b91e83ef 100644 --- a/src/seqta/utils/listeners/EventManager.ts +++ b/src/seqta/utils/listeners/EventManager.ts @@ -16,14 +16,14 @@ interface EventListener { unregister: () => void; } + class EventManager { private static instance: EventManager; private listeners: Map = new Map(); private mutationObservers: Map = new Map(); private pendingElements: Set = new Set(); private firedOnceIds: Set = new Set(); - private throttleTimeout: number = 5; // 5ms throttle - private throttleTimer: number | undefined; + private rafId = 0; private chunkSize: number = 50; // Process 50 elements per chunk private constructor() {} @@ -146,26 +146,27 @@ class EventManager { } private handleMutations(mutations: MutationRecord[]): void { - mutations.forEach((mutation) => { - if (mutation.type === "childList") { - mutation.addedNodes.forEach((node) => { - if (node.nodeType === Node.ELEMENT_NODE) { - this.pendingElements.add(node as Element); - } - }); + for (const mutation of mutations) { + if (mutation.type !== "childList") continue; + for (const node of mutation.addedNodes) { + if (node.nodeType === Node.ELEMENT_NODE) { + this.pendingElements.add(node as Element); + } } - }); + } - this.throttleCheckElements(); + if (this.pendingElements.size > 0) { + this.schedulePendingCheck(); + } } - private throttleCheckElements(): void { - if (this.throttleTimer) return; + private schedulePendingCheck(): void { + if (this.rafId) return; - this.throttleTimer = window.setTimeout(() => { - this.processPendingElements(); - this.throttleTimer = undefined; - }, this.throttleTimeout); + this.rafId = requestAnimationFrame(() => { + this.rafId = 0; + void this.processPendingElements(); + }); } private async processPendingElements(): Promise { @@ -189,7 +190,11 @@ class EventManager { } private async checkElement(element: Element): Promise { + if (this.listeners.size === 0) return; + for (const [event, listeners] of this.listeners.entries()) { + if (!listeners.length) continue; + for (const { id, options, callback } of listeners) { if (options.once && this.firedOnceIds.has(id)) continue; diff --git a/src/seqta/utils/listeners/SettingsState.ts b/src/seqta/utils/listeners/SettingsState.ts index f3f2cb00..07d61a15 100644 --- a/src/seqta/utils/listeners/SettingsState.ts +++ b/src/seqta/utils/listeners/SettingsState.ts @@ -369,10 +369,16 @@ class StorageManager { }; } + private notifyFrame = 0; + private notifySubscribers(): void { - for (const subscriber of this.subscribers) { - subscriber(this.data); - } + if (this.notifyFrame) return; + this.notifyFrame = requestAnimationFrame(() => { + this.notifyFrame = 0; + for (const subscriber of this.subscribers) { + subscriber(this.data); + } + }); } } diff --git a/src/seqta/utils/listeners/StorageChanges.ts b/src/seqta/utils/listeners/StorageChanges.ts index 720601ff..680e9243 100644 --- a/src/seqta/utils/listeners/StorageChanges.ts +++ b/src/seqta/utils/listeners/StorageChanges.ts @@ -6,8 +6,9 @@ import { applySelectedFont } from "@/seqta/ui/fonts/Manager"; import { renderShortcuts } from "@/seqta/utils/Render/renderShortcuts"; import { FilterUpcomingAssessments } from "@/seqta/utils/FilterUpcomingAssessments"; import { registerHomeUpcomingSettingsListeners } from "@/seqta/utils/Loaders/LoadHomePage"; -import { applyMenuItemVisibility } from "@/seqta/utils/menuItemVisibility"; +import { applyMenuItemVisibility, scheduleMenuItemVisibility } from "@/seqta/utils/menuItemVisibility"; import { ChangeMenuItemPositions } from "@/seqta/utils/Openers/menuOrder"; +import { syncPerformanceModeEffects } from "@/seqta/utils/performanceMode"; import browser from "webextension-polyfill"; import type { CustomShortcut } from "@/types/storage"; @@ -36,6 +37,10 @@ export class StorageChangeHandler { "transparencyEffects", this.handleTransparencyEffectsChange.bind(this), ); + settingsState.register("performanceMode", () => syncPerformanceModeEffects()); + settingsState.register("performanceModePluginOverrides", () => + syncPerformanceModeEffects(), + ); settingsState.register( "subjectfilters", FilterUpcomingAssessments.bind(this), @@ -46,7 +51,7 @@ export class StorageChangeHandler { this.handleIconOnlySidebarChange.bind(this), ); settingsState.register("selectedFont", () => applySelectedFont()); - settingsState.register("menuitems", () => applyMenuItemVisibility()); + settingsState.register("menuitems", () => scheduleMenuItemVisibility()); settingsState.register("menuorder", (order) => { if (Array.isArray(order) && order.length > 0) { ChangeMenuItemPositions(order); @@ -85,7 +90,7 @@ export class StorageChangeHandler { } private handleTransparencyEffectsChange(newValue: boolean) { - if (newValue) { + if (newValue && !settingsState.performanceMode) { document.documentElement.classList.add("transparencyEffects"); } else { document.documentElement.classList.remove("transparencyEffects"); diff --git a/src/seqta/utils/menuItemVisibility.ts b/src/seqta/utils/menuItemVisibility.ts index 9a8f251f..28552362 100644 --- a/src/seqta/utils/menuItemVisibility.ts +++ b/src/seqta/utils/menuItemVisibility.ts @@ -1,20 +1,29 @@ import { settingsState } from "./listeners/SettingsState"; +import { rafThrottle } from "@/seqta/utils/rafThrottle"; const STYLE_ID = "bsplus-menuitem-visibility"; +let lastCss = ""; + +function buildMenuItemVisibilityCss(): string { + let css = ""; + for (const [menuItem, config] of Object.entries(settingsState.menuitems ?? {})) { + if (config && !config.toggle) { + // Scope to the native SEQTA list only — the custom Svelte sidebar + // filters visibility in JS and must not be forced hidden by this rule. + css += `#menu > ul:not(#bsplus-sidebar-root) li[data-key=${menuItem}],#menu > ul:not(#bsplus-sidebar-root) section[data-key=${menuItem}]{display:var(--menuHidden) !important;}`; + } + } + return css; +} /** Apply hide rules from `menuitems` (re-runnable after edit / storage sync). */ export function applyMenuItemVisibility(): void { if (document.querySelector(".editmenuoption-container")) return; try { - let css = ""; - for (const [menuItem, config] of Object.entries(settingsState.menuitems ?? {})) { - if (config && !config.toggle) { - // Scope to the native SEQTA list only — the custom Svelte sidebar - // filters visibility in JS and must not be forced hidden by this rule. - css += `#menu > ul:not(#bsplus-sidebar-root) li[data-key=${menuItem}],#menu > ul:not(#bsplus-sidebar-root) section[data-key=${menuItem}]{display:var(--menuHidden) !important;transition:1s;}`; - } - } + const css = buildMenuItemVisibilityCss(); + if (css === lastCss) return; + lastCss = css; let styleEl = document.getElementById(STYLE_ID) as HTMLStyleElement | null; if (!styleEl) { @@ -27,3 +36,6 @@ export function applyMenuItemVisibility(): void { console.error("[BetterSEQTA+] Failed to apply menu item visibility:", error); } } + +/** Coalesce rapid menuitems updates (storage + sidebar edit). */ +export const scheduleMenuItemVisibility = rafThrottle(applyMenuItemVisibility); diff --git a/src/seqta/utils/performanceMode.test.ts b/src/seqta/utils/performanceMode.test.ts new file mode 100644 index 00000000..1b61f378 --- /dev/null +++ b/src/seqta/utils/performanceMode.test.ts @@ -0,0 +1,85 @@ +import { settingsState } from "@/seqta/utils/listeners/SettingsState"; +import { + adaptiveThemeTransitionEnabled, + animationsEnabled, + fullMotionEffectsEnabled, + globalSearchIndexingEnabled, + isPerformanceMode, + isPluginAllowedInPerformanceMode, + isPluginBlockedByPerformanceMode, + isPluginForceEnabledInPerformanceMode, + setPerformanceModePluginOverride, + transparencyEnabled, +} from "./performanceMode"; + +describe("performanceMode helpers", () => { + beforeEach(() => { + settingsState.performanceMode = false; + settingsState.performanceModePluginOverrides = {}; + settingsState.animations = true; + settingsState.transparencyEffects = false; + settingsState.adaptiveThemeColourTransition = true; + }); + + it("isPerformanceMode reflects settingsState", () => { + expect(isPerformanceMode()).toBe(false); + settingsState.performanceMode = true; + expect(isPerformanceMode()).toBe(true); + }); + + it("animationsEnabled stays on in performance mode when animations setting is on", () => { + settingsState.animations = true; + settingsState.performanceMode = true; + expect(animationsEnabled()).toBe(true); + }); + + it("fullMotionEffectsEnabled is false in performance mode", () => { + settingsState.animations = true; + settingsState.performanceMode = true; + expect(fullMotionEffectsEnabled()).toBe(false); + }); + + it("animationsEnabled respects animations setting when performance mode is off", () => { + settingsState.animations = false; + expect(animationsEnabled()).toBe(false); + settingsState.animations = true; + expect(animationsEnabled()).toBe(true); + }); + + it("transparencyEnabled is false in performance mode", () => { + settingsState.transparencyEffects = true; + settingsState.performanceMode = true; + expect(transparencyEnabled()).toBe(false); + }); + + it("adaptiveThemeTransitionEnabled is false in performance mode", () => { + settingsState.adaptiveThemeColourTransition = true; + settingsState.performanceMode = true; + expect(adaptiveThemeTransitionEnabled()).toBe(false); + }); + + it("globalSearchIndexingEnabled blocks indexing when global search is paused", () => { + expect(globalSearchIndexingEnabled(true)).toBe(true); + settingsState.performanceMode = true; + expect(globalSearchIndexingEnabled(true)).toBe(false); + }); + + it("blocks heavy plugins unless force-enabled", () => { + settingsState.performanceMode = true; + expect(isPluginBlockedByPerformanceMode("global-search")).toBe(true); + expect(isPluginAllowedInPerformanceMode("global-search")).toBe(false); + + setPerformanceModePluginOverride("global-search", true); + expect(isPluginForceEnabledInPerformanceMode("global-search")).toBe(true); + expect(isPluginBlockedByPerformanceMode("global-search")).toBe(false); + expect(isPluginAllowedInPerformanceMode("global-search")).toBe(true); + + setPerformanceModePluginOverride("global-search", false); + expect(isPluginBlockedByPerformanceMode("global-search")).toBe(true); + }); + + it("does not block plugins when performance mode is off", () => { + settingsState.performanceMode = false; + expect(isPluginBlockedByPerformanceMode("assessments-average")).toBe(false); + }); +}); diff --git a/src/seqta/utils/performanceMode.ts b/src/seqta/utils/performanceMode.ts new file mode 100644 index 00000000..0b3b202e --- /dev/null +++ b/src/seqta/utils/performanceMode.ts @@ -0,0 +1,149 @@ +import { settingsState } from "@/seqta/utils/listeners/SettingsState"; +import { removeAnimatedBackgroundLayers } from "@/plugins/built-in/animatedBackground/backgroundLayers"; +import { applySidebarLook } from "@/seqta/ui/sidebar/sidebarStyles"; +import { + PERFORMANCE_HEAVY_PLUGIN_IDS, + PERFORMANCE_HEAVY_PLUGINS, +} from "@/seqta/utils/performanceModeConfig"; + +export const PERFORMANCE_MODE_CLASS = "performanceMode"; +export const SIMPLE_UI_CLASS = "performanceModeSimpleUi"; + +/** Master toggle — reduces visual effects and background work for smoother SEQTA. */ +export function isPerformanceMode(): boolean { + return settingsState.performanceMode === true; +} + +export function isSimpleAnalyticsUi(): boolean { + return ( + isPerformanceMode() && + !isPluginForceEnabledInPerformanceMode("grade-analytics") + ); +} + +export function isPluginForceEnabledInPerformanceMode(pluginId: string): boolean { + return settingsState.performanceModePluginOverrides?.[pluginId] === true; +} + +export function isPluginBlockedByPerformanceMode(pluginId: string): boolean { + if (!isPerformanceMode()) return false; + if (isPluginForceEnabledInPerformanceMode(pluginId)) return false; + return PERFORMANCE_HEAVY_PLUGIN_IDS.has(pluginId); +} + +export function isPluginAllowedInPerformanceMode(pluginId: string): boolean { + return !isPluginBlockedByPerformanceMode(pluginId); +} + +export function setPerformanceModePluginOverride( + pluginId: string, + forceEnable: boolean, +): void { + const current = { ...(settingsState.performanceModePluginOverrides ?? {}) }; + if (forceEnable) { + current[pluginId] = true; + } else { + delete current[pluginId]; + } + settingsState.performanceModePluginOverrides = current; +} + +export function animationsEnabled(): boolean { + return settingsState.animations !== false; +} + +/** Expensive full-page effects (view transitions, clip-path theme morphs). */ +export function fullMotionEffectsEnabled(): boolean { + return animationsEnabled() && !isPerformanceMode(); +} + +export function transparencyEnabled(): boolean { + return !isPerformanceMode() && settingsState.transparencyEffects === true; +} + +export function adaptiveThemeTransitionEnabled(): boolean { + return ( + !isPerformanceMode() && + (settingsState.adaptiveThemeColourTransition ?? true) + ); +} + +export function globalSearchIndexingEnabled(settingEnabled: boolean): boolean { + return isPluginAllowedInPerformanceMode("global-search") && settingEnabled; +} + +export function applyPerformanceModeClass(): void { + const on = isPerformanceMode(); + document.documentElement.classList.toggle(PERFORMANCE_MODE_CLASS, on); + document.documentElement.classList.toggle(SIMPLE_UI_CLASS, isPerformanceMode()); +} + +export function applyPerformanceModeTransparency(): void { + if (transparencyEnabled()) { + document.documentElement.classList.add("transparencyEffects"); + } else { + document.documentElement.classList.remove("transparencyEffects"); + } +} + +export function applyPerformanceModeSidebarLook(): void { + applySidebarLook(document.getElementById("menu")); +} + +async function syncPerformanceModePlugins(): Promise { + try { + const { pluginManager } = await import("@/plugins"); + const pluginIds = new Set([ + ...PERFORMANCE_HEAVY_PLUGINS.map((p) => p.id), + ...Object.keys(settingsState.performanceModePluginOverrides ?? {}), + ]); + + for (const pluginId of pluginIds) { + if (isPluginAllowedInPerformanceMode(pluginId)) { + await pluginManager.startPlugin(pluginId); + } else { + await pluginManager.stopPlugin(pluginId); + } + } + + if (isPerformanceMode()) { + removeAnimatedBackgroundLayers(); + window.dispatchEvent(new CustomEvent("betterseqta-background-music-stop")); + } else { + const browser = (await import("webextension-polyfill")).default; + const searchSettings = await browser.storage.local.get( + "plugin.global-search.settings", + ); + const gs = searchSettings["plugin.global-search.settings"] as + | { runIndexingOnLoad?: boolean } + | undefined; + if (gs?.runIndexingOnLoad && isPluginAllowedInPerformanceMode("global-search")) { + const { runIndexing } = await import( + "@/plugins/built-in/globalSearch/src/indexing/indexer" + ); + if (typeof requestIdleCallback === "function") { + requestIdleCallback(() => void runIndexing(), { timeout: 5000 }); + } else { + setTimeout(() => void runIndexing(), 2000); + } + } + } + } catch (error) { + console.warn("[BetterSEQTA+] Performance mode plugin sync failed:", error); + } +} + +/** Apply DOM + plugin side effects when performance mode changes or on boot. */ +export function syncPerformanceModeEffects(): void { + applyPerformanceModeClass(); + applyPerformanceModeTransparency(); + applyPerformanceModeSidebarLook(); + + if (isPerformanceMode()) { + removeAnimatedBackgroundLayers(); + } + + void syncPerformanceModePlugins(); +} + +export { PERFORMANCE_HEAVY_PLUGINS }; diff --git a/src/seqta/utils/performanceModeConfig.ts b/src/seqta/utils/performanceModeConfig.ts new file mode 100644 index 00000000..72d8cec1 --- /dev/null +++ b/src/seqta/utils/performanceModeConfig.ts @@ -0,0 +1,53 @@ +/** Heavy plugins paused while Performance Mode is on (unless force-enabled). */ +export type PerformanceHeavyPlugin = { + id: string; + name: string; + description: string; +}; + +export const PERFORMANCE_HEAVY_PLUGINS: readonly PerformanceHeavyPlugin[] = [ + { + id: "global-search", + name: "Global Search", + description: "Background indexing, vector search, and fetch capture", + }, + { + id: "assessments-average", + name: "Assessment Averages", + description: "Weight extraction, overrides, and live grade calculations", + }, + { + id: "grade-analytics", + name: "Grade Analytics", + description: "Chart rendering and analytics sync", + }, + { + id: "notificationCollector", + name: "Notification Collector", + description: "Background notification polling", + }, + { + id: "enhanced-navigation", + name: "Enhanced Navigation", + description: "Extra scroll and navigation observers", + }, + { + id: "animated-background", + name: "Animated Background", + description: "Continuous CSS background animation layers", + }, + { + id: "background-music", + name: "Background Music", + description: "Audio playback and gesture unlock listeners", + }, + { + id: "messageFolders", + name: "Message Folders", + description: "Message DOM tagging and folder indexing", + }, +] as const; + +export const PERFORMANCE_HEAVY_PLUGIN_IDS = new Set( + PERFORMANCE_HEAVY_PLUGINS.map((p) => p.id), +); diff --git a/src/seqta/utils/popupAnimation.ts b/src/seqta/utils/popupAnimation.ts new file mode 100644 index 00000000..0e504958 --- /dev/null +++ b/src/seqta/utils/popupAnimation.ts @@ -0,0 +1,54 @@ +import { settingsState } from "@/seqta/utils/listeners/SettingsState"; +import { fullMotionEffectsEnabled } from "@/seqta/utils/performanceMode"; + +const BACKDROP_CLASS = "bsplus-popup-css-animate"; +const OPEN_CLASS = "bsplus-popup-css-animate--open"; +const LITE_BACKDROP_CLASS = "bsplus-popup-backdrop--lite"; + +const CLOSE_FALLBACK_MS = 240; + +/** CSS fade/scale path — used when animations are on but Motion springs are off (performance mode). */ +export function useCssPopupAnimation(): boolean { + return settingsState.animations !== false && !fullMotionEffectsEnabled(); +} + +export function preparePopupCssAnimation(background: HTMLElement): void { + background.classList.add(BACKDROP_CLASS, LITE_BACKDROP_CLASS); +} + +export function animatePopupOpen(background: HTMLElement): void { + if (!useCssPopupAnimation()) return; + + preparePopupCssAnimation(background); + background.classList.remove(OPEN_CLASS); + + requestAnimationFrame(() => { + void background.offsetWidth; + background.classList.add(OPEN_CLASS); + }); +} + +export function animatePopupClose(background: HTMLElement): Promise { + if (!useCssPopupAnimation()) { + return Promise.resolve(); + } + + return new Promise((resolve) => { + let settled = false; + const finish = () => { + if (settled) return; + settled = true; + background.removeEventListener("transitionend", onEnd); + resolve(); + }; + + const onEnd = (event: TransitionEvent) => { + if (event.target !== background || event.propertyName !== "opacity") return; + finish(); + }; + + background.addEventListener("transitionend", onEnd); + background.classList.remove(OPEN_CLASS); + window.setTimeout(finish, CLOSE_FALLBACK_MS); + }); +} diff --git a/src/seqta/utils/rafThrottle.ts b/src/seqta/utils/rafThrottle.ts new file mode 100644 index 00000000..aa0ef50d --- /dev/null +++ b/src/seqta/utils/rafThrottle.ts @@ -0,0 +1,16 @@ +/** Coalesce rapid callbacks to at most once per animation frame. */ +export function rafThrottle void>(fn: T): T { + let scheduled = false; + let lastArgs: Parameters | null = null; + + return ((...args: Parameters) => { + lastArgs = args; + if (scheduled) return; + scheduled = true; + requestAnimationFrame(() => { + scheduled = false; + if (lastArgs) fn(...lastArgs); + lastArgs = null; + }); + }) as T; +} diff --git a/src/seqta/utils/settingsPopupAnimation.ts b/src/seqta/utils/settingsPopupAnimation.ts new file mode 100644 index 00000000..4bf0e1ed --- /dev/null +++ b/src/seqta/utils/settingsPopupAnimation.ts @@ -0,0 +1,74 @@ +import { settingsState } from "@/seqta/utils/listeners/SettingsState"; + +const HOST_OPEN_CLASS = "bsplus-settings-host--open"; +const HOST_CLOSING_CLASS = "bsplus-settings-host--closing"; +const PANEL_OPEN_CLASS = "bsplus-settings-panel--open"; + +function settingsPanel(host: HTMLElement): HTMLElement | null { + return host.shadowRoot?.querySelector("[data-settings-panel]") ?? null; +} + +export function animateSettingsOpen(host: HTMLElement): void { + host.style.transform = "none"; + host.classList.remove(HOST_CLOSING_CLASS, "hide"); + + const panel = settingsPanel(host); + if (!settingsState.animations) { + host.style.opacity = "1"; + host.classList.add(HOST_OPEN_CLASS); + panel?.classList.add(PANEL_OPEN_CLASS); + return; + } + + host.style.opacity = ""; + host.classList.remove(HOST_OPEN_CLASS); + panel?.classList.remove(PANEL_OPEN_CLASS); + + requestAnimationFrame(() => { + host.classList.add(HOST_OPEN_CLASS); + panel?.classList.add(PANEL_OPEN_CLASS); + }); +} + +export function animateSettingsClose(host: HTMLElement): void { + host.classList.add("hide"); + const panel = settingsPanel(host); + + if (!settingsState.animations) { + host.classList.remove(HOST_OPEN_CLASS, HOST_CLOSING_CLASS); + panel?.classList.remove(PANEL_OPEN_CLASS); + host.style.opacity = "0"; + return; + } + + host.classList.remove(HOST_OPEN_CLASS); + host.classList.add(HOST_CLOSING_CLASS); + panel?.classList.remove(PANEL_OPEN_CLASS); + + const durationMs = document.documentElement.classList.contains("performanceMode") + ? 160 + : 200; + + window.setTimeout(() => { + host.classList.remove(HOST_CLOSING_CLASS); + host.style.opacity = "0"; + }, durationMs); +} + +let prefetchStarted = false; + +/** Warm settings chunks during idle time so the first open feels instant. */ +export function prefetchSettingsShell(): void { + if (prefetchStarted) return; + prefetchStarted = true; + const run = () => { + void import("@/interface/main"); + void import("@/interface/pages/settings/SettingsBody.svelte"); + void import("@/interface/pages/settings/sections/generalOptions.svelte"); + }; + if (typeof requestIdleCallback === "function") { + requestIdleCallback(run, { timeout: 8000 }); + } else { + window.setTimeout(run, 3000); + } +} diff --git a/src/seqta/utils/setupSettingsButton.ts b/src/seqta/utils/setupSettingsButton.ts index 0cabfee0..52b5949f 100644 --- a/src/seqta/utils/setupSettingsButton.ts +++ b/src/seqta/utils/setupSettingsButton.ts @@ -3,19 +3,22 @@ import { closeExtensionPopup, SettingsClicked, } from "./Closers/closeExtensionPopup"; -import { animate } from "motion"; import { settingsState } from "./listeners/SettingsState"; +import { + animateSettingsOpen, + prefetchSettingsShell, +} from "./settingsPopupAnimation"; import { renderSettingsIfNeeded } from "./Adders/AddExtensionSettings"; -import { delay } from "./delay"; export function setupSettingsButton() { const AddedSettings = document.getElementById("AddedSettings"); if (!AddedSettings) return; - // Avoid stacking duplicate listeners if Engage remounts the toolbar. if (AddedSettings.dataset.bsplusSettingsBound === "1") return; AddedSettings.dataset.bsplusSettingsBound = "1"; + prefetchSettingsShell(); + AddedSettings.addEventListener("click", async () => { if (SettingsClicked) { closeExtensionPopup(); @@ -28,7 +31,6 @@ export function setupSettingsButton() { export async function openSettingsPopup(): Promise { if (SettingsClicked && document.getElementById("ExtensionPopup")) return; - // Re-query each time — Engage SPA navigations can recreate the host. let extensionPopup = document.getElementById("ExtensionPopup"); if (!extensionPopup) { const { addExtensionSettings } = await import("./Adders/AddExtensionSettings"); @@ -38,36 +40,6 @@ export async function openSettingsPopup(): Promise { if (!extensionPopup) return; await renderSettingsIfNeeded(); - await delay(30); - - extensionPopup.style.transform = "none"; - const panel = extensionPopup.shadowRoot?.querySelector( - "[data-settings-panel]", - ); - if (settingsState.animations) { - animate(0, 1, { - onUpdate: (progress) => { - extensionPopup.style.opacity = progress.toString(); - }, - type: "spring", - stiffness: 280, - damping: 20, - }); - if (panel) { - animate( - panel, - { scale: [0, 1], opacity: [0, 1] }, - { type: "spring", stiffness: 330, damping: 30 }, - ); - } - } else { - extensionPopup.style.opacity = "1"; - extensionPopup.style.transition = "opacity 0s linear"; - if (panel) { - panel.style.scale = "1"; - panel.style.opacity = "1"; - } - } - extensionPopup.classList.remove("hide"); + animateSettingsOpen(extensionPopup); changeSettingsClicked(true); } diff --git a/src/seqta/utils/sidebarMenuIcons.ts b/src/seqta/utils/sidebarMenuIcons.ts index 0ece53fd..bc94496d 100644 --- a/src/seqta/utils/sidebarMenuIcons.ts +++ b/src/seqta/utils/sidebarMenuIcons.ts @@ -114,9 +114,8 @@ async function observeEngageMenuIcons() { engageMenuIconObserver = new MutationObserver(() => { scheduleEngageMenuIconPass(); }); - engageMenuIconObserver.observe(menu, { + engageMenuIconObserver.observe(menuList, { childList: true, - subtree: true, }); } diff --git a/src/types/storage.ts b/src/types/storage.ts index 2b7b3fc0..50fa50ec 100644 --- a/src/types/storage.ts +++ b/src/types/storage.ts @@ -47,6 +47,10 @@ export interface SettingsState { themeOfTheMonthDisabled?: boolean; timeFormat?: string; animations: boolean; + /** Reduces animations, blur, background work, and indexing for smoother SEQTA. */ + performanceMode?: boolean; + /** Per-plugin force-enable while Performance Mode is active (`pluginId` → true). */ + performanceModePluginOverrides?: Record; defaultPage: string; /** Max subjects with upcoming assessments on the home page; 0 = no limit. */ homeUpcomingSubjectsMax?: number;