From a93c3ccda75bd553449262be4a9a02fbd9350733 Mon Sep 17 00:00:00 2001 From: Aden Linday Date: Wed, 26 Aug 2026 16:47:41 +0930 Subject: [PATCH 01/25] feat: light mode variations for the loading screen --- src/interface/pages/settings/general.svelte | 12 +++ src/plugins/monofile.ts | 4 + src/seqta/ui/Loading.ts | 61 +++++++++----- src/seqta/ui/loadingCanvas.ts | 37 ++++++--- src/seqta/ui/loadingHold.test.ts | 30 +++++++ src/seqta/ui/loadingHold.ts | 10 +++ src/seqta/ui/loadingVariants.test.ts | 24 ++++++ src/seqta/ui/loadingVariants.ts | 80 ++++++++++++++++--- src/seqta/utils/cloudSettingsSync.ts | 1 + .../utils/ensureSyncableStorageDefaults.ts | 1 + src/seqta/utils/listeners/SettingsState.ts | 1 + src/types/storage.ts | 2 + 12 files changed, 223 insertions(+), 40 deletions(-) create mode 100644 src/seqta/ui/loadingHold.test.ts create mode 100644 src/seqta/ui/loadingHold.ts create mode 100644 src/seqta/ui/loadingVariants.test.ts diff --git a/src/interface/pages/settings/general.svelte b/src/interface/pages/settings/general.svelte index a7ec2710..4cd27343 100644 --- a/src/interface/pages/settings/general.svelte +++ b/src/interface/pages/settings/general.svelte @@ -619,6 +619,18 @@ /> +
+
+

Delay loading screen

+

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

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

Sensitive Hider

diff --git a/src/plugins/monofile.ts b/src/plugins/monofile.ts index 144d6505..441505c9 100644 --- a/src/plugins/monofile.ts +++ b/src/plugins/monofile.ts @@ -20,6 +20,7 @@ import { updateAllColors } from "@/seqta/ui/colors/Manager"; import { applySelectedFont } from "@/seqta/ui/fonts/Manager"; import { verboseInfo, verboseLog } from "@/utils/verboseLog"; import loading, { stopLoadingAnimation } from "@/seqta/ui/Loading"; +import { loadingScreenHoldMs } from "@/seqta/ui/loadingHold"; import { SendNewsPage } from "@/seqta/utils/SendNewsPage"; import { getEngageRoutePage } from "@/seqta/utils/engageRoute"; import { @@ -92,6 +93,9 @@ export async function finishLoad() { document.querySelector(".legacy-root")?.classList.remove("hidden"); + const holdMs = loadingScreenHoldMs(settingsState); + if (holdMs > 0) await delay(holdMs); + const loadingbk = document.getElementById("loading"); loadingbk?.classList.add("closeLoading"); stopLoadingAnimation(); diff --git a/src/seqta/ui/Loading.ts b/src/seqta/ui/Loading.ts index 1cbd9c16..7e4757f8 100644 --- a/src/seqta/ui/Loading.ts +++ b/src/seqta/ui/Loading.ts @@ -6,6 +6,7 @@ import loadingOverlay from "./loading-overlay.html?raw"; import { startLoadingCanvas } from "./loadingCanvas"; import { pickLoadingVariant, + resolveLoadingTheme, type LoadingVariant, } from "./loadingVariants"; @@ -25,26 +26,42 @@ const THEME_GUARD_KEYS = [ "selectedFont", ] as const; -const LOADING_PALETTE = { +const LOADING_PALETTE_DARK = { line: "rgba(255, 255, 255, 0.08)", lineAccent: "rgba(255, 255, 255, 0.15)", lineBlue: "rgba(96, 165, 250, 0.42)", grid: "rgba(255, 255, 255, 0.028)", text: "#f4f4f5", + version: "rgba(255, 255, 255, 0.35)", } as const; +const LOADING_PALETTE_LIGHT = { + line: "rgba(24, 24, 27, 0.1)", + lineAccent: "rgba(24, 24, 27, 0.18)", + lineBlue: "rgba(37, 99, 235, 0.5)", + grid: "rgba(24, 24, 27, 0.055)", + text: "#18181b", + version: "rgba(24, 24, 27, 0.42)", +} as const; + +function loadingPalette(darkMode: boolean) { + return darkMode ? LOADING_PALETTE_DARK : LOADING_PALETTE_LIGHT; +} + const loadingStyles = /* css */ ` :host { - --bk-line-color: ${LOADING_PALETTE.line}; - --bk-line-accent: ${LOADING_PALETTE.lineAccent}; - --bk-line-blue: ${LOADING_PALETTE.lineBlue}; - --bk-grid-color: ${LOADING_PALETTE.grid}; + --bk-line-color: ${LOADING_PALETTE_DARK.line}; + --bk-line-accent: ${LOADING_PALETTE_DARK.lineAccent}; + --bk-line-blue: ${LOADING_PALETTE_DARK.lineBlue}; + --bk-grid-color: ${LOADING_PALETTE_DARK.grid}; --bk-spin-outer: 1s; --bk-spin-inner: 3s; --bk-spin-small: 3s; --bk-stage-name: bkloading-stage-in; --bk-stage-duration: 0.85s; - color: ${LOADING_PALETTE.text}; + --bk-vignette-fill: radial-gradient(ellipse at center, transparent 32%, rgba(0, 0, 0, 0.75) 100%); + --bk-version-color: ${LOADING_PALETTE_DARK.version}; + color: ${LOADING_PALETTE_DARK.text}; opacity: 1; transition: opacity 0.85s cubic-bezier(0.4, 0, 0.2, 1); } @@ -66,7 +83,7 @@ const loadingStyles = /* css */ ` position: absolute; inset: 0; pointer-events: none; - background: radial-gradient(ellipse at center, transparent 32%, rgba(0, 0, 0, 0.75) 100%); + background: var(--bk-vignette-fill); opacity: 0.88; } @@ -153,7 +170,7 @@ const loadingStyles = /* css */ ` bottom: 10px; font-size: 0.95rem; letter-spacing: 0.02em; - color: rgba(255, 255, 255, 0.35); + color: var(--bk-version-color); pointer-events: none; } @@ -199,7 +216,8 @@ function overlayWithSpinner(): string { ); } -function applyHostShell(host: HTMLElement) { +function applyHostShell(host: HTMLElement, darkMode: boolean) { + const palette = loadingPalette(darkMode); const shell = [ ["position", "fixed"], ["inset", "0"], @@ -209,11 +227,12 @@ function applyHostShell(host: HTMLElement) { ["contain", "strict"], ["visibility", "visible"], ["pointer-events", "auto"], - ["color", LOADING_PALETTE.text], - ["--bk-line-color", LOADING_PALETTE.line], - ["--bk-line-accent", LOADING_PALETTE.lineAccent], - ["--bk-line-blue", LOADING_PALETTE.lineBlue], - ["--bk-grid-color", LOADING_PALETTE.grid], + ["color", palette.text], + ["--bk-line-color", palette.line], + ["--bk-line-accent", palette.lineAccent], + ["--bk-line-blue", palette.lineBlue], + ["--bk-grid-color", palette.grid], + ["--bk-version-color", palette.version], ] as const; for (const [prop, value] of shell) { @@ -226,18 +245,24 @@ function applyVariantTheme( shadow: ShadowRoot, variant: LoadingVariant, ) { - const { theme } = variant; + const darkMode = !!settingsState.DarkMode; + const theme = resolveLoadingTheme(variant, darkMode); host.dataset.variant = variant.id; - applyHostShell(host); + host.dataset.scheme = darkMode ? "dark" : "light"; + applyHostShell(host, darkMode); host.style.setProperty("background", theme.background, "important"); host.style.setProperty("--bk-spin-outer", theme.spinOuter, "important"); host.style.setProperty("--bk-spin-inner", theme.spinInner, "important"); - host.style.setProperty("--bk-spin-small", theme.spinSmall, "important"); host.style.setProperty("--bk-stage-name", theme.stageName, "important"); + host.style.setProperty("--bk-spin-small", theme.spinSmall, "important"); host.style.setProperty("--bk-stage-duration", theme.stageDuration, "important"); + host.style.setProperty("--bk-vignette-fill", theme.vignetteFill, "important"); const vignette = shadow.querySelector(".bkloading__vignette") as HTMLElement | null; - if (vignette) vignette.style.opacity = String(theme.vignetteOpacity); + if (vignette) { + vignette.style.opacity = String(theme.vignetteOpacity); + vignette.style.background = theme.vignetteFill; + } } function refreshActiveLoadingTheme() { diff --git a/src/seqta/ui/loadingCanvas.ts b/src/seqta/ui/loadingCanvas.ts index 6b42f39b..74238cac 100644 --- a/src/seqta/ui/loadingCanvas.ts +++ b/src/seqta/ui/loadingCanvas.ts @@ -78,8 +78,15 @@ function cycle( return { t: fadeT, fade: true, ambient: smooth((len - tick) / revealMs) }; } -function cssVar(_root: HTMLElement, _name: string, fallback: string): string { - return fallback; +function cssVar(root: HTMLElement, name: string, fallback: string): string { + const inline = root.style.getPropertyValue(name).trim(); + if (inline) return inline; + const computed = getComputedStyle(root).getPropertyValue(name).trim(); + return computed || fallback; +} + +function isLightScheme(root: HTMLElement): boolean { + return root.dataset.scheme === "light"; } function drawGrid( @@ -122,9 +129,11 @@ function drawSoftBlobs( blur: number, fadeMs: number, tide: boolean, + light: boolean, ) { const time = reduced ? 0 : elapsed * 0.001; const fadeIn = reduced ? 1 : smooth(Math.min(1, elapsed / fadeMs)); + const alphaBoost = light ? 1.18 : 1; ctx.save(); ctx.globalAlpha = fadeIn; @@ -145,8 +154,8 @@ function drawSoftBlobs( y = b.cy * h + Math.sin(t * 0.48 + b.phase) * h * 0.025; rx = b.rx * w; ry = b.ry * h * breathe; - a0 = 0.38; - a1 = 0.14; + a0 = 0.38 * alphaBoost; + a1 = 0.14 * alphaBoost; } else { const amp = b.amp ?? 0.2; const scale = 1 + Math.sin(t * 1.35) * amp; @@ -155,8 +164,8 @@ function drawSoftBlobs( y = b.cy * h + Math.sin(t * 0.41) * h * 0.01; rx = b.rx * w * scale; ry = b.ry * h * stretch; - a0 = 0.5; - a1 = 0.18; + a0 = 0.5 * alphaBoost; + a1 = 0.18 * alphaBoost; ctx.save(); ctx.translate(x, y); ctx.rotate(t * (b.rot ?? 0)); @@ -187,6 +196,7 @@ function drawDotGlobe( phaseElapsed: number, fade: boolean, ambient: number, + light: boolean, ) { const time = reduced ? 0 : elapsed * 0.001; const cx = w * 0.5; @@ -206,8 +216,8 @@ function drawDotGlobe( ctx.save(); ctx.globalAlpha = ambient; const glow = ctx.createRadialGradient(cx, cy, 0, cx, cy, radius * 1.15); - glow.addColorStop(0, "rgba(37, 99, 235, 0.1)"); - glow.addColorStop(0.55, "rgba(37, 99, 235, 0.03)"); + glow.addColorStop(0, light ? "rgba(37, 99, 235, 0.16)" : "rgba(37, 99, 235, 0.1)"); + glow.addColorStop(0.55, light ? "rgba(37, 99, 235, 0.05)" : "rgba(37, 99, 235, 0.03)"); glow.addColorStop(1, "rgba(37, 99, 235, 0)"); ctx.fillStyle = glow; ctx.fillRect(cx - radius * 1.2, cy - radius * 1.2, radius * 2.4, radius * 2.4); @@ -256,8 +266,11 @@ function drawDotGlobe( const size = (1.2 + depth * 2.2) * dot.p; const alpha = (0.12 + brightness * 0.75) * dot.p; - ctx.fillStyle = - brightness > 0.52 + ctx.fillStyle = light + ? brightness > 0.52 + ? `rgba(29, 78, 216, ${alpha})` + : `rgba(24, 24, 27, ${0.1 + brightness * 0.28 * dot.p})` + : brightness > 0.52 ? `rgba(96, 165, 250, ${alpha})` : `rgba(255, 255, 255, ${0.08 + brightness * 0.22 * dot.p})`; ctx.beginPath(); @@ -303,10 +316,11 @@ export function startLoadingCanvas( const elapsed = now - start; ctx.clearRect(0, 0, w, h); + const light = isLightScheme(root); if (visual === "globe") { const { t, fade, ambient } = cycle(elapsed, revealMs, holdMs); - drawDotGlobe(ctx, w, h, elapsed, reduced, t, fade, reduced ? 1 : ambient); + drawDotGlobe(ctx, w, h, elapsed, reduced, t, fade, reduced ? 1 : ambient, light); } else if (visual === "blobs") { const tide = variant.blobStyle === "tide"; drawSoftBlobs( @@ -319,6 +333,7 @@ export function startLoadingCanvas( tide ? 58 : 52, tide ? 1800 : 1600, tide, + light, ); } else { const { t, fade } = cycle(elapsed, revealMs, holdMs); diff --git a/src/seqta/ui/loadingHold.test.ts b/src/seqta/ui/loadingHold.test.ts new file mode 100644 index 00000000..b93cbeba --- /dev/null +++ b/src/seqta/ui/loadingHold.test.ts @@ -0,0 +1,30 @@ +import { loadingScreenHoldMs } from "./loadingHold"; + +describe("loadingScreenHoldMs", () => { + it("holds 5 seconds when developer mode and the delay option are both on", () => { + expect( + loadingScreenHoldMs({ + devMode: true, + devDelayLoadingScreen: true, + }), + ).toBe(5000); + }); + + it("does not hold when developer mode is off", () => { + expect( + loadingScreenHoldMs({ + devMode: false, + devDelayLoadingScreen: true, + }), + ).toBe(0); + }); + + it("does not hold when the delay option is off", () => { + expect( + loadingScreenHoldMs({ + devMode: true, + devDelayLoadingScreen: false, + }), + ).toBe(0); + }); +}); diff --git a/src/seqta/ui/loadingHold.ts b/src/seqta/ui/loadingHold.ts new file mode 100644 index 00000000..c3d1ea05 --- /dev/null +++ b/src/seqta/ui/loadingHold.ts @@ -0,0 +1,10 @@ +export const LOADING_SCREEN_DEBUG_DELAY_MS = 5000; + +export function loadingScreenHoldMs(settings: { + devMode?: boolean; + devDelayLoadingScreen?: boolean; +}): number { + return settings.devMode && settings.devDelayLoadingScreen + ? LOADING_SCREEN_DEBUG_DELAY_MS + : 0; +} diff --git a/src/seqta/ui/loadingVariants.test.ts b/src/seqta/ui/loadingVariants.test.ts new file mode 100644 index 00000000..f7ea8ee0 --- /dev/null +++ b/src/seqta/ui/loadingVariants.test.ts @@ -0,0 +1,24 @@ +import { + listLoadingVariants, + resolveLoadingTheme, +} from "./loadingVariants"; + +describe("loading variant light themes", () => { + it("defines a distinct light theme for every canvas variant", () => { + const variants = listLoadingVariants(); + expect(variants.length).toBeGreaterThan(0); + + for (const variant of variants) { + expect(variant.lightTheme.background).not.toBe(variant.theme.background); + expect(variant.lightTheme.background).not.toMatch(/#0[148]0[148]0[148]/); + expect(variant.lightTheme.vignetteFill).not.toBe(variant.theme.vignetteFill); + } + }); + + it("resolves dark theme when dark mode is on and light theme when it is off", () => { + const sweep = listLoadingVariants().find((variant) => variant.id === "sweep"); + expect(sweep).toBeDefined(); + expect(resolveLoadingTheme(sweep!, true)).toEqual(sweep!.theme); + expect(resolveLoadingTheme(sweep!, false)).toEqual(sweep!.lightTheme); + }); +}); diff --git a/src/seqta/ui/loadingVariants.ts b/src/seqta/ui/loadingVariants.ts index 49cc3ad8..5694c99b 100644 --- a/src/seqta/ui/loadingVariants.ts +++ b/src/seqta/ui/loadingVariants.ts @@ -11,6 +11,17 @@ export type Line = { ) => void; }; +export type LoadingTheme = { + background: string; + vignetteOpacity: number; + vignetteFill: string; + spinOuter: string; + spinInner: string; + spinSmall: string; + stageName: string; + stageDuration: string; +}; + export type LoadingVariant = { id: string; visual?: "lines" | "blobs" | "globe"; @@ -18,15 +29,8 @@ export type LoadingVariant = { holdMs: number; grid: { cols: number; rows: number }; lines: Line[]; - theme: { - background: string; - vignetteOpacity: number; - spinOuter: string; - spinInner: string; - spinSmall: string; - stageName: string; - stageDuration: string; - }; + theme: LoadingTheme; + lightTheme: LoadingTheme; }; const curve = ( @@ -60,7 +64,13 @@ const segment = (x1: number, y1: number, x2: number, y2: number): Line["stroke"] }; const BASE = "linear-gradient(180deg, #010101 0%, #040404 50%, #080808 100%)"; +const BASE_LIGHT = + "linear-gradient(180deg, #fafafa 0%, #f4f4f5 50%, #ececef 100%)"; const STAGE = "bkloading-stage-in"; +const DARK_VIGNETTE = + "radial-gradient(ellipse at center, transparent 32%, rgba(0, 0, 0, 0.75) 100%)"; +const LIGHT_VIGNETTE = + "radial-gradient(ellipse at center, transparent 32%, rgba(250, 250, 250, 0.88) 100%)"; function theme( background: string, @@ -69,10 +79,12 @@ function theme( spinInner: string, spinSmall: string, stageDuration: string, -) { + light = false, +): LoadingTheme { return { background, vignetteOpacity, + vignetteFill: light ? LIGHT_VIGNETTE : DARK_VIGNETTE, spinOuter, spinInner, spinSmall, @@ -85,7 +97,8 @@ function canvasVariant( id: string, visual: "blobs" | "globe", holdMs: number, - t: ReturnType, + t: LoadingTheme, + lightTheme: LoadingTheme, blobStyle?: "diffuse" | "tide", ): LoadingVariant { return { @@ -96,9 +109,17 @@ function canvasVariant( grid: { cols: 0, rows: 0 }, lines: [], theme: t, + lightTheme, }; } +export function resolveLoadingTheme( + variant: LoadingVariant, + darkMode: boolean, +): LoadingTheme { + return darkMode ? variant.theme : variant.lightTheme; +} + const VARIANTS: LoadingVariant[] = [ { id: "sweep", @@ -112,6 +133,15 @@ const VARIANTS: LoadingVariant[] = [ "3s", "0.85s", ), + lightTheme: theme( + `radial-gradient(ellipse 70% 45% at 50% 95%, rgba(37, 99, 235, 0.16), transparent 62%), ${BASE_LIGHT}`, + 0.72, + "1s", + "3s", + "3s", + "0.85s", + true, + ), lines: [ { delay: 0, @@ -177,6 +207,15 @@ const VARIANTS: LoadingVariant[] = [ "2.6s", "0.75s", ), + lightTheme: theme( + `radial-gradient(ellipse 40% 30% at 80% 20%, rgba(59, 130, 246, 0.12), transparent 70%), ${BASE_LIGHT}`, + 0.74, + "0.85s", + "2.6s", + "2.6s", + "0.75s", + true, + ), lines: [ { delay: 0, dur: 1200, stroke: segment(0.5, 0.06, 0.5, 0.94) }, { delay: 80, dur: 1200, stroke: segment(0.04, 0.5, 0.96, 0.5) }, @@ -202,6 +241,7 @@ const VARIANTS: LoadingVariant[] = [ "blobs", 0, theme(BASE, 0.78, "1.3s", "3.8s", "3.8s", "0.9s"), + theme(BASE_LIGHT, 0.62, "1.3s", "3.8s", "3.8s", "0.9s", true), "diffuse", ), canvasVariant( @@ -216,6 +256,15 @@ const VARIANTS: LoadingVariant[] = [ "4.2s", "1s", ), + theme( + `radial-gradient(ellipse 85% 45% at 50% 100%, rgba(37, 99, 235, 0.14), transparent 72%), ${BASE_LIGHT}`, + 0.64, + "1.5s", + "4.2s", + "4.2s", + "1s", + true, + ), "tide", ), canvasVariant( @@ -230,6 +279,15 @@ const VARIANTS: LoadingVariant[] = [ "3.5s", "0.9s", ), + theme( + `radial-gradient(ellipse 55% 50% at 50% 48%, rgba(37, 99, 235, 0.14), transparent 70%), ${BASE_LIGHT}`, + 0.7, + "1.2s", + "3.5s", + "3.5s", + "0.9s", + true, + ), ), ]; diff --git a/src/seqta/utils/cloudSettingsSync.ts b/src/seqta/utils/cloudSettingsSync.ts index 965df51d..bf42ecb6 100644 --- a/src/seqta/utils/cloudSettingsSync.ts +++ b/src/seqta/utils/cloudSettingsSync.ts @@ -84,6 +84,7 @@ const OMIT_FROM_UPLOAD_EXACT = new Set([ ...CLIENT_ONLY_CLOUD_KEYS_EXACT, "devMode", "devGhReleaseVersionOverride", + "devDelayLoadingScreen", ]); const UNSAFE_STORAGE_KEYS = new Set(["__proto__", "constructor", "prototype"]); diff --git a/src/seqta/utils/ensureSyncableStorageDefaults.ts b/src/seqta/utils/ensureSyncableStorageDefaults.ts index cfb969c8..b3d5c0da 100644 --- a/src/seqta/utils/ensureSyncableStorageDefaults.ts +++ b/src/seqta/utils/ensureSyncableStorageDefaults.ts @@ -30,6 +30,7 @@ const OPTIONAL_UNSET_MEANS_DEFAULT_KEYS = [ "justupdated", "devMode", "verboseLogging", + "devDelayLoadingScreen", "hideSensitiveContent", "mockNotices", "homeUpcomingAssessmentsPerSubjectMax", diff --git a/src/seqta/utils/listeners/SettingsState.ts b/src/seqta/utils/listeners/SettingsState.ts index 8c93083f..f3f2cb00 100644 --- a/src/seqta/utils/listeners/SettingsState.ts +++ b/src/seqta/utils/listeners/SettingsState.ts @@ -28,6 +28,7 @@ const SETTINGS_STORAGE_KEYS = [ "justupdated", "devMode", "verboseLogging", + "devDelayLoadingScreen", "devGhReleaseVersionOverride", "lastSeenNightlyPublishedAt", "originalDarkMode", diff --git a/src/types/storage.ts b/src/types/storage.ts index 4fb3b329..8edd8f05 100644 --- a/src/types/storage.ts +++ b/src/types/storage.ts @@ -57,6 +57,8 @@ export interface SettingsState { devMode?: boolean; /** Dev-only: emit verboseDebug / verboseInfo / verboseLog output. */ verboseLogging?: boolean; + /** Dev-only: keep the loading overlay visible for 5 extra seconds. */ + devDelayLoadingScreen?: boolean; /** Dev-only: pretend this is the latest GitHub release version for update badge testing. */ devGhReleaseVersionOverride?: string; /** ISO timestamp of the last acknowledged nightly release publish time. */ From e1408fe35db9ea3111d68d82a5277bdaf89bfee6 Mon Sep 17 00:00:00 2001 From: Aden Linday Date: Wed, 26 Aug 2026 16:55:14 +0930 Subject: [PATCH 02/25] fix: fix animations on analyitics page when setting disabled (#474) --- .../gradeAnalytics/AnalyticsAreaChart.svelte | 15 ++++++----- .../gradeAnalytics/AnalyticsBarChart.svelte | 3 ++- .../gradeAnalytics/GradeAnalyticsPage.svelte | 7 +++-- .../gradeAnalytics/GradeRangeSlider.svelte | 3 ++- .../built-in/gradeAnalytics/motion.test.ts | 26 +++++++++++++++++++ src/plugins/built-in/gradeAnalytics/motion.ts | 12 +++++++++ .../built-in/gradeAnalytics/styles.css | 19 ++++++++++++++ src/plugins/built-in/gradeAnalytics/ui.ts | 10 +++++-- 8 files changed, 83 insertions(+), 12 deletions(-) create mode 100644 src/plugins/built-in/gradeAnalytics/motion.test.ts create mode 100644 src/plugins/built-in/gradeAnalytics/motion.ts diff --git a/src/plugins/built-in/gradeAnalytics/AnalyticsAreaChart.svelte b/src/plugins/built-in/gradeAnalytics/AnalyticsAreaChart.svelte index 833f35af..6cee8391 100644 --- a/src/plugins/built-in/gradeAnalytics/AnalyticsAreaChart.svelte +++ b/src/plugins/built-in/gradeAnalytics/AnalyticsAreaChart.svelte @@ -14,6 +14,7 @@ } from "./timeRange"; import { computeGradeForecast, aggregateToMonthlyPoints } from "./utils/gradePrediction"; import PredictionMonthsSlider from "./PredictionMonthsSlider.svelte"; + import { settingsState } from "@/seqta/utils/listeners/SettingsState"; interface Props { data: Assessment[]; @@ -166,6 +167,8 @@ return monthly.length >= 3; }); + const animationsOn = $derived($settingsState.animations); + /** Historical + future forecast points so tooltips work across the dashed line. */ const chartData = $derived.by((): TrendPoint[] => { if (!showPrediction || !forecast?.points.length) { @@ -243,7 +246,7 @@ curve: curveMonotoneX, "fill-opacity": showSubjectTrends ? 0.12 : 0.35, line: { class: "stroke-2" }, - motion: "tween", + motion: animationsOn ? "tween" : false, }, xAxis: { ticks: timeRange === "7d" ? 7 : undefined, @@ -267,12 +270,12 @@ {#each series as s, i (s.key)} {@const meta = chartSeries.find((c) => c.key === s.key)} diff --git a/src/plugins/built-in/gradeAnalytics/AnalyticsBarChart.svelte b/src/plugins/built-in/gradeAnalytics/AnalyticsBarChart.svelte index 2bdbed52..8b728d8a 100644 --- a/src/plugins/built-in/gradeAnalytics/AnalyticsBarChart.svelte +++ b/src/plugins/built-in/gradeAnalytics/AnalyticsBarChart.svelte @@ -27,6 +27,7 @@ } from "./gradeDistribution"; import { loadDistributionMode, saveDistributionMode } from "./storage"; + import { settingsState } from "@/seqta/utils/listeners/SettingsState"; @@ -312,7 +313,7 @@ motion: { - y: { type: "tween", duration: 600, easing: cubicInOut }, + y: { type: "tween", duration: $settingsState.animations ? 600 : 0, easing: cubicInOut }, }, diff --git a/src/plugins/built-in/gradeAnalytics/GradeAnalyticsPage.svelte b/src/plugins/built-in/gradeAnalytics/GradeAnalyticsPage.svelte index 3d265080..b9cfbe7b 100644 --- a/src/plugins/built-in/gradeAnalytics/GradeAnalyticsPage.svelte +++ b/src/plugins/built-in/gradeAnalytics/GradeAnalyticsPage.svelte @@ -20,6 +20,7 @@ type TimeRange, } from "./timeRange"; import { openAnalyticsPrivacyPopup } from "./openAnalyticsPrivacyPopup"; + import { settingsState } from "@/seqta/utils/listeners/SettingsState"; let analyticsData: Assessment[] | null = $state(null); let loading = $state(true); @@ -39,6 +40,8 @@ let timestampInterval: ReturnType | null = null; let contentReady = $state(false); + const fadeDuration = $derived($settingsState.animations ? 200 : 0); + const emptyFadeDuration = $derived($settingsState.animations ? 300 : 0); const formattedTimestamp = $derived(() => { if (!lastUpdated) return ""; @@ -204,7 +207,7 @@
{#if error} - {/if} @@ -462,7 +465,7 @@
{:else} -
+
@@ -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; From a19b43ef37f3a6b8aa96d0cae24081ce2ccf1663 Mon Sep 17 00:00:00 2001 From: Aden Linday Date: Thu, 3 Sep 2026 10:43:44 +0930 Subject: [PATCH 18/25] chore: cleanup and optmise size --- .../themes/BackgroundSelector.svelte | 110 ++++---------- src/interface/hooks/BackgroundDataLoader.ts | 142 +++++------------- .../pages/settings/LazySection.svelte | 28 ---- .../pages/settings/SettingsBody.svelte | 41 ++--- src/seqta/utils/performanceMode.ts | 5 - src/seqta/utils/popupAnimation.ts | 25 +-- 6 files changed, 94 insertions(+), 257 deletions(-) delete mode 100644 src/interface/pages/settings/LazySection.svelte diff --git a/src/interface/components/themes/BackgroundSelector.svelte b/src/interface/components/themes/BackgroundSelector.svelte index ec60e6c8..85b73da5 100644 --- a/src/interface/components/themes/BackgroundSelector.svelte +++ b/src/interface/components/themes/BackgroundSelector.svelte @@ -8,9 +8,7 @@ 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 feedback = $state<{ kind: 'error' | 'warn'; text: string } | null>(null); let imageBackgrounds = $derived(backgrounds.filter(bg => bg.type === 'image')); let videoBackgrounds = $derived(backgrounds.filter(bg => bg.type === 'video')); @@ -20,39 +18,12 @@ 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) { - if (e instanceof Error) { - error = e.message; - return; - } - if (typeof e === 'string' && e) { - error = e; - return; - } - error = 'An unknown error occurred'; - } - - 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' - ); + return ['mp4', 'mov', 'webm', 'm4v', 'mkv'].includes(ext) ? 'video' : 'image'; } async function handleFileChange(file: File): Promise { if (!file) return; - - uploading = true; - error = null; - notice = null; + feedback = null; try { if (!isIndexedDBSupported()) { @@ -75,42 +46,36 @@ ]; 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.'; + const ext = file.name.split('.').pop()?.toLowerCase() ?? ''; + if (['heic', 'heif'].includes(ext) || file.type.toLowerCase().includes('hei')) { + feedback = { + kind: 'warn', + text: '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; + feedback = { + kind: 'error', + text: e instanceof Error ? e.message : 'An unknown error occurred', + }; } } - async function getTheme() { - return localStorage.getItem('selectedBackground'); - } - - async function setTheme(theme: string) { - localStorage.setItem('selectedBackground', theme); - } - async function syncBackgrounds(): Promise { try { - error = null; + feedback = null; if (!isIndexedDBSupported()) { throw new Error("Your browser doesn't support IndexedDB. Unable to load backgrounds."); } - selectedBackground = await getTheme(); + selectedBackground = localStorage.getItem('selectedBackground'); const dbData = await readAllData(); - // Release existing object URLs to prevent memory leaks backgrounds.forEach(bg => { if (bg.url) URL.revokeObjectURL(bg.url); }); - // Create fresh background objects with new object URLs backgrounds = dbData.map(bg => ({ id: bg.id, type: bg.type, @@ -118,12 +83,14 @@ url: URL.createObjectURL(bg.blob) })); - // Check if selected background still exists if (selectedBackground && !backgrounds.some(bg => bg.id === selectedBackground)) { selectNoBackground(); } } catch (e) { - setError(e); + feedback = { + kind: 'error', + text: e instanceof Error ? e.message : 'An unknown error occurred', + }; } } @@ -134,7 +101,7 @@ } selectedBackground = fileId; - setTheme(fileId); + localStorage.setItem('selectedBackground', fileId); } async function deleteBackground(fileId: string): Promise { @@ -147,13 +114,16 @@ } backgroundUpdates.triggerUpdate(); } catch (e) { - setError(e); + feedback = { + kind: 'error', + text: e instanceof Error ? e.message : 'An unknown error occurred', + }; } } selectNoBackground = () => { selectedBackground = null; - setTheme(''); + localStorage.setItem('selectedBackground', ''); } $effect(() => { @@ -161,12 +131,6 @@ selectedBackground }); - $effect(() => { - if (error) { - console.error(error); - } - }); - onMount(() => { syncBackgrounds(); backgroundUpdates.addListener(syncBackgrounds); @@ -184,21 +148,14 @@
- {#if notice} + {#if feedback}
- {notice} -
- {/if} - - {#if error} - {/if} @@ -207,11 +164,6 @@
{#if !isEditMode} - {#if uploading} -
-
-
- {/if} {/if} {#each imageBackgrounds as bg (bg.id)} {#if bg.url} diff --git a/src/interface/hooks/BackgroundDataLoader.ts b/src/interface/hooks/BackgroundDataLoader.ts index df130eee..d164b638 100644 --- a/src/interface/hooks/BackgroundDataLoader.ts +++ b/src/interface/hooks/BackgroundDataLoader.ts @@ -1,107 +1,49 @@ type BackgroundRecord = { id: string; type: string; blob: Blob }; const DB_NAME = "BackgroundDB"; -const STORE_NAME = "backgrounds"; -const DB_VERSION = 1; +const STORE = "backgrounds"; let dbPromise: Promise | null = null; -function promisifyRequest(request: IDBRequest): Promise { +function req(request: IDBRequest): Promise { return new Promise((resolve, reject) => { request.onsuccess = () => resolve(request.result); request.onerror = () => reject(request.error); }); } -function waitForTransaction(tx: IDBTransaction): Promise { +function txDone(tx: IDBTransaction): Promise { return new Promise((resolve, reject) => { tx.oncomplete = () => resolve(); tx.onerror = () => reject(tx.error); - tx.onabort = () => reject(tx.error); }); } -function openDatabaseInternal(): Promise { +export function openDatabase(): Promise { if (!dbPromise) { dbPromise = new Promise((resolve, reject) => { - const request = indexedDB.open(DB_NAME, DB_VERSION); - - request.onerror = () => { + const open = indexedDB.open(DB_NAME, 1); + open.onerror = () => { dbPromise = null; - reject(request.error); + reject(open.error); }; - - request.onupgradeneeded = () => { - const db = request.result; - if (!db.objectStoreNames.contains(STORE_NAME)) { - db.createObjectStore(STORE_NAME, { keyPath: "id" }); + open.onupgradeneeded = () => { + if (!open.result.objectStoreNames.contains(STORE)) { + open.result.createObjectStore(STORE, { keyPath: "id" }); } }; - - request.onsuccess = () => resolve(request.result); + open.onsuccess = () => resolve(open.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 { - 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; - }); + const db = await openDatabase(); + const tx = db.transaction(STORE, "readonly"); + const items = await req(tx.objectStore(STORE).getAll()); + await txDone(tx); + return items; } export async function writeData( @@ -109,15 +51,14 @@ export async function writeData( type: string, blob: Blob, ): Promise { - const record: BackgroundRecord = { id, type, blob }; + const record = { id, type, blob }; + const db = await openDatabase(); + const tx = db.transaction(STORE, "readwrite"); + const store = tx.objectStore(STORE); try { - await withStore("readwrite", async (store) => { - const request = storeUsesInlineKeys(store) - ? store.put(record) - : store.put(record, id); - await promisifyRequest(request); - }); + await req(store.keyPath ? store.put(record) : store.put(record, id)); + await txDone(tx); } catch (e) { const detail = e instanceof Error ? e.message : String(e); throw new Error(`Failed to save background: ${detail}`); @@ -125,30 +66,27 @@ export async function writeData( } export async function deleteData(id: string): Promise { - 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}`); - } + const db = await openDatabase(); + const tx = db.transaction(STORE, "readwrite"); + await req(tx.objectStore(STORE).delete(id)); + await txDone(tx); } export async function clearAllData(): Promise { - await withStore("readwrite", async (store) => { - await promisifyRequest(store.clear()); - }); + const db = await openDatabase(); + const tx = db.transaction(STORE, "readwrite"); + await req(tx.objectStore(STORE).clear()); + await txDone(tx); } export async function getDataById( id: string, ): Promise { - const item = await withStore("readonly", async (store) => - promisifyRequest(store.get(id)), - ); - if (!item?.id || !(item.blob instanceof Blob)) return undefined; - return item as BackgroundRecord; + const db = await openDatabase(); + const tx = db.transaction(STORE, "readonly"); + const item = await req(tx.objectStore(STORE).get(id)); + await txDone(tx); + return item?.blob instanceof Blob ? item : undefined; } export function closeDatabase(): void { @@ -165,11 +103,7 @@ export function isIndexedDBSupported(): boolean { export async function hasEnoughStorageSpace( requiredSpace: number, ): Promise { - if ("storage" in navigator && "estimate" in navigator.storage) { - const { quota, usage } = await navigator.storage.estimate(); - if (quota !== undefined && usage !== undefined) { - return quota - usage > requiredSpace; - } - } - return true; + if (!("storage" in navigator) || !navigator.storage.estimate) return true; + const { quota, usage } = await navigator.storage.estimate(); + return quota == null || usage == null || quota - usage > requiredSpace; } diff --git a/src/interface/pages/settings/LazySection.svelte b/src/interface/pages/settings/LazySection.svelte deleted file mode 100644 index 39c156c1..00000000 --- a/src/interface/pages/settings/LazySection.svelte +++ /dev/null @@ -1,28 +0,0 @@ - - -{#if Comp} - -{:else} -
Loading…
-{/if} diff --git a/src/interface/pages/settings/SettingsBody.svelte b/src/interface/pages/settings/SettingsBody.svelte index f634ba96..ee6da3bb 100644 --- a/src/interface/pages/settings/SettingsBody.svelte +++ b/src/interface/pages/settings/SettingsBody.svelte @@ -1,10 +1,11 @@ +
{ - if (e.target === e.currentTarget && !busy) onClose(); - }} - onkeydown={(e) => { - if (e.key === "Escape" && !busy) onClose(); - }} - role="button" - tabindex="-1" transition:fade={{ duration: $settingsState.animations ? 200 : 0 }} > - -