From 5623c129043714ab628081ade75d2bc29ce3d5ef Mon Sep 17 00:00:00 2001 From: Aden Linday Date: Wed, 30 Sep 2026 19:47:57 +0930 Subject: [PATCH 01/11] fix: settings popup reopen race after async open Use DOM visibility and an open generation counter so in-flight opens cannot leave stale state after close, and dedupe opens per generation. Co-authored-by: Cursor --- .../utils/Adders/AddExtensionSettings.ts | 11 ++-- .../utils/Closers/closeExtensionPopup.ts | 13 ++--- src/seqta/utils/feedback/client.ts | 4 +- src/seqta/utils/settingsPopupAnimation.ts | 13 ++++- src/seqta/utils/setupSettingsButton.ts | 54 +++++++++++-------- 5 files changed, 57 insertions(+), 38 deletions(-) diff --git a/src/seqta/utils/Adders/AddExtensionSettings.ts b/src/seqta/utils/Adders/AddExtensionSettings.ts index 0ec606d1..a2713ed2 100644 --- a/src/seqta/utils/Adders/AddExtensionSettings.ts +++ b/src/seqta/utils/Adders/AddExtensionSettings.ts @@ -1,8 +1,5 @@ -import { - changeSettingsClicked, - closeExtensionPopup, - SettingsClicked, -} from "../Closers/closeExtensionPopup"; +import { closeExtensionPopup } from "../Closers/closeExtensionPopup"; +import { isExtensionSettingsOpen } from "../settingsPopupAnimation"; let isSettingsRendered = false; let settingsLoadPromise: Promise | null = null; @@ -10,7 +7,7 @@ let resizerAttached = false; function extensionOutsideClickHandler(extensionPopup: HTMLElement) { return (event: MouseEvent) => { - if (!SettingsClicked) return; + if (!isExtensionSettingsOpen()) return; const target = event.target; if (!(target instanceof Node)) return; @@ -20,7 +17,7 @@ function extensionOutsideClickHandler(extensionPopup: HTMLElement) { if (target instanceof HTMLElement && target.closest("#AddedSettings")) return; if (target === extensionPopup) return; - changeSettingsClicked(closeExtensionPopup()); + closeExtensionPopup(); }; } diff --git a/src/seqta/utils/Closers/closeExtensionPopup.ts b/src/seqta/utils/Closers/closeExtensionPopup.ts index d39b4294..e32cf92f 100644 --- a/src/seqta/utils/Closers/closeExtensionPopup.ts +++ b/src/seqta/utils/Closers/closeExtensionPopup.ts @@ -1,9 +1,15 @@ import { settingsPopup } from "@/seqta/utils/settingsPopup"; import { animateSettingsClose } from "@/seqta/utils/settingsPopupAnimation"; -export let SettingsClicked = false; +let settingsOpenGeneration = 0; + +export function getSettingsOpenGeneration(): number { + return settingsOpenGeneration; +} export const closeExtensionPopup = (extensionPopup?: HTMLElement) => { + settingsOpenGeneration += 1; + if (!extensionPopup) extensionPopup = document.getElementById("ExtensionPopup")!; if (extensionPopup) { @@ -11,9 +17,4 @@ export const closeExtensionPopup = (extensionPopup?: HTMLElement) => { } settingsPopup.triggerClose(); - return (SettingsClicked = false); }; - -export function changeSettingsClicked(newVal: boolean) { - SettingsClicked = newVal; -} diff --git a/src/seqta/utils/feedback/client.ts b/src/seqta/utils/feedback/client.ts index 802b8460..2f42601c 100644 --- a/src/seqta/utils/feedback/client.ts +++ b/src/seqta/utils/feedback/client.ts @@ -1,6 +1,6 @@ import browser from "webextension-polyfill"; import { getApiBase } from "@/seqta/utils/DevApiBase"; -import { SettingsClicked } from "@/seqta/utils/Closers/closeExtensionPopup"; +import { isExtensionSettingsOpen } from "@/seqta/utils/settingsPopupAnimation"; import { isSeqtaEngageExperience } from "@/seqta/utils/isSeqtaEngage"; import { settingsState } from "@/seqta/utils/listeners/SettingsState"; import { @@ -291,6 +291,6 @@ export function consumeOpenFeedbackRequest(): string | null { } export function openExtensionSettingsPopup(): void { - if (SettingsClicked) return; + if (isExtensionSettingsOpen()) return; document.getElementById("AddedSettings")?.click(); } diff --git a/src/seqta/utils/settingsPopupAnimation.ts b/src/seqta/utils/settingsPopupAnimation.ts index 4bf0e1ed..67034981 100644 --- a/src/seqta/utils/settingsPopupAnimation.ts +++ b/src/seqta/utils/settingsPopupAnimation.ts @@ -1,9 +1,20 @@ import { settingsState } from "@/seqta/utils/listeners/SettingsState"; -const HOST_OPEN_CLASS = "bsplus-settings-host--open"; +export const HOST_OPEN_CLASS = "bsplus-settings-host--open"; const HOST_CLOSING_CLASS = "bsplus-settings-host--closing"; const PANEL_OPEN_CLASS = "bsplus-settings-panel--open"; +/** True when the settings host is shown (not fully hidden). */ +export function isSettingsHostVisiblyOpen(host: HTMLElement | null | undefined): boolean { + if (!host) return false; + if (host.classList.contains("hide")) return false; + return host.classList.contains(HOST_OPEN_CLASS); +} + +export function isExtensionSettingsOpen(): boolean { + return isSettingsHostVisiblyOpen(document.getElementById("ExtensionPopup")); +} + function settingsPanel(host: HTMLElement): HTMLElement | null { return host.shadowRoot?.querySelector("[data-settings-panel]") ?? null; } diff --git a/src/seqta/utils/setupSettingsButton.ts b/src/seqta/utils/setupSettingsButton.ts index dd4db905..53ef9c3d 100644 --- a/src/seqta/utils/setupSettingsButton.ts +++ b/src/seqta/utils/setupSettingsButton.ts @@ -1,12 +1,5 @@ -import { - changeSettingsClicked, - closeExtensionPopup, - SettingsClicked, -} from "./Closers/closeExtensionPopup"; -import { - animateSettingsOpen, - prefetchSettingsShell, -} from "./settingsPopupAnimation"; +import { closeExtensionPopup, getSettingsOpenGeneration } from "./Closers/closeExtensionPopup"; +import { animateSettingsOpen, isExtensionSettingsOpen, prefetchSettingsShell } from "./settingsPopupAnimation"; import { renderSettingsIfNeeded } from "./Adders/AddExtensionSettings"; export function setupSettingsButton() { @@ -18,8 +11,9 @@ export function setupSettingsButton() { prefetchSettingsShell(); - AddedSettings.addEventListener("click", async () => { - if (SettingsClicked) { + AddedSettings.addEventListener("click", async (event) => { + event.stopPropagation(); + if (isExtensionSettingsOpen()) { closeExtensionPopup(); } else { await openSettingsPopup(); @@ -27,18 +21,34 @@ export function setupSettingsButton() { }); } +let openSettingsInFlight: { gen: number; promise: Promise } | null = null; + export async function openSettingsPopup(): Promise { - if (SettingsClicked && document.getElementById("ExtensionPopup")) return; + if (isExtensionSettingsOpen()) return; - let extensionPopup = document.getElementById("ExtensionPopup"); - if (!extensionPopup) { - const { addExtensionSettings } = await import("./Adders/AddExtensionSettings"); - addExtensionSettings(); - extensionPopup = document.getElementById("ExtensionPopup"); - } - if (!extensionPopup) return; + const gen = getSettingsOpenGeneration(); + if (openSettingsInFlight?.gen === gen) return openSettingsInFlight.promise; - await renderSettingsIfNeeded(); - animateSettingsOpen(extensionPopup); - changeSettingsClicked(true); + const promise = (async () => { + try { + let host = document.getElementById("ExtensionPopup"); + if (!host) { + const { addExtensionSettings } = await import("./Adders/AddExtensionSettings"); + addExtensionSettings(); + host = document.getElementById("ExtensionPopup"); + } + if (!host) return; + + await renderSettingsIfNeeded(); + if (gen !== getSettingsOpenGeneration()) return; + + host = document.getElementById("ExtensionPopup"); + if (host) animateSettingsOpen(host); + } finally { + if (openSettingsInFlight?.gen === gen) openSettingsInFlight = null; + } + })(); + + openSettingsInFlight = { gen, promise }; + return promise; } From eb2bdbec2f7ab5aef741b72984f8f3f15b69e976 Mon Sep 17 00:00:00 2001 From: Aden Linday Date: Wed, 30 Sep 2026 19:48:10 +0930 Subject: [PATCH 02/11] fix: remove stale SettingsClicked import after settings popup fix Co-authored-by: Cursor --- src/interface/components/themes/ThemeSelector.svelte | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/interface/components/themes/ThemeSelector.svelte b/src/interface/components/themes/ThemeSelector.svelte index 8f42a9d0..22e9c3d6 100644 --- a/src/interface/components/themes/ThemeSelector.svelte +++ b/src/interface/components/themes/ThemeSelector.svelte @@ -9,7 +9,7 @@ import ThemeBlobImage from '@/interface/components/themes/ThemeBlobImage.svelte' import ThemePlaceholderCover from '@/interface/components/themes/ThemePlaceholderCover.svelte' import { filterThemesByMode, isLocalCustomTheme, type ThemeListMode } from '@/interface/utils/themeListFilters' - import { closeExtensionPopup, SettingsClicked } from '@/seqta/utils/Closers/closeExtensionPopup' + import { closeExtensionPopup } from '@/seqta/utils/Closers/closeExtensionPopup' import { formatCustomThemeApiError } from '@/seqta/utils/customThemes/apiErrors' const themeManager = ThemeManager.getInstance(); From 4d9b17df37b84f0b044d82544918b341b559637a Mon Sep 17 00:00:00 2001 From: SethBurkart123 Date: Wed, 30 Sep 2026 22:39:46 +1000 Subject: [PATCH 03/11] fix: address release regressions in startup, analytics and sync --- src/SEQTA.boot.test.ts | 54 ++++++ src/SEQTA.ts | 24 +-- src/interface/utils/buildSimpleTheme.test.ts | 10 ++ src/interface/utils/themeBuilderDraft.ts | 5 +- .../gradeAnalytics/GradeInferencePanel.svelte | 2 +- .../built-in/gradeAnalytics/api.test.ts | 65 +++++++ src/plugins/built-in/gradeAnalytics/api.ts | 6 +- .../gradeAnalytics/gradeResolution.test.ts | 13 ++ .../gradeAnalytics/gradeResolution.ts | 10 +- .../themes/theme-manager.cloud.test.ts | 103 +++++++++++ src/plugins/built-in/themes/theme-manager.ts | 23 ++- src/plugins/core/manager.test.ts | 165 ++++++++++++++++++ src/plugins/core/manager.ts | 70 +++++--- src/seqta/ui/sidebar/parseNativeMenu.ts | 2 +- src/seqta/ui/sidebar/sidebarStyles.test.ts | 52 ++++++ src/seqta/ui/sidebar/sidebarStyles.ts | 10 +- .../utils/calendarSync/remoteEvents.test.ts | 84 +++++++++ src/seqta/utils/calendarSync/remoteEvents.ts | 27 ++- src/seqta/utils/calendarSync/syncEngine.ts | 16 +- .../utils/cloudSettingsSync.patch.test.ts | 25 +++ src/seqta/utils/cloudSettingsSync.ts | 2 + .../googleCalendar/fetchTimetable.test.ts | 133 +++++++++++++- .../utils/googleCalendar/fetchTimetable.ts | 135 +++++++------- .../utils/googleCalendar/syncEngine.test.ts | 23 ++- .../utils/listeners/StorageChanges.test.ts | 37 ++++ src/seqta/utils/listeners/StorageChanges.ts | 1 + .../utils/settingsPopupAnimation.test.ts | 27 +++ src/seqta/utils/settingsPopupAnimation.ts | 1 + 28 files changed, 989 insertions(+), 136 deletions(-) create mode 100644 src/SEQTA.boot.test.ts create mode 100644 src/plugins/built-in/gradeAnalytics/api.test.ts create mode 100644 src/plugins/built-in/themes/theme-manager.cloud.test.ts create mode 100644 src/plugins/core/manager.test.ts create mode 100644 src/seqta/ui/sidebar/sidebarStyles.test.ts create mode 100644 src/seqta/utils/calendarSync/remoteEvents.test.ts create mode 100644 src/seqta/utils/listeners/StorageChanges.test.ts create mode 100644 src/seqta/utils/settingsPopupAnimation.test.ts diff --git a/src/SEQTA.boot.test.ts b/src/SEQTA.boot.test.ts new file mode 100644 index 00000000..002e122c --- /dev/null +++ b/src/SEQTA.boot.test.ts @@ -0,0 +1,54 @@ +/** @jest-environment jsdom */ +import { execFileSync } from "node:child_process"; +import { runInNewContext } from "node:vm"; + +// Compile the actual Vite entry in Node (esbuild cannot run in jsdom's realm). +const bootScript = execFileSync( + process.execPath, + [ + "--input-type=module", + "-e", + ` + import { readFileSync } from "node:fs"; + import { transformSync } from "esbuild"; + process.stdout.write(transformSync(readFileSync("src/SEQTA.ts", "utf8"), { + loader: "ts", format: "cjs", + supported: { "dynamic-import": false }, + define: { "import.meta.env.DEV": "false", "import.meta.hot": "undefined" }, + }).code); +`, + ], + { encoding: "utf8" }, +); + +test.each([ + { onoff: false }, + { "plugin.error-page-kitten.settings": { enabled: false } }, +])( + "disabled 404 customization preserves the native error message: %j", + async (stored) => { + document.head.innerHTML = ""; + document.body.innerHTML = '
Page not found
'; + const mount = jest.fn(); + runInNewContext(bootScript, { + document, + window, + console, + require: (module: string) => { + if (module === "webextension-polyfill") { + return { storage: { local: { get: async () => stored } } }; + } + if (module.includes("errorPageKitten")) { + return { isSeqta404Page: () => true, mountErrorPageKitten: mount }; + } + return {}; + }, + }); + for (let i = 0; i < 10; i++) await Promise.resolve(); + + expect(mount).not.toHaveBeenCalled(); + expect( + window.getComputedStyle(document.querySelector(".message")!).display, + ).not.toBe("none"); + }, +); diff --git a/src/SEQTA.ts b/src/SEQTA.ts index 3450a32c..e6ab3759 100644 --- a/src/SEQTA.ts +++ b/src/SEQTA.ts @@ -178,24 +178,24 @@ async function bootErrorPage() { } document.removeEventListener("readystatechange", watchTitle); - if (!isSeqta404Page()) return; - - const stored = await storagePromise; - if ((stored.onoff ?? true) === false) return; - const kittenSettings = stored["plugin.error-page-kitten.settings"] as - | { enabled?: boolean } - | undefined; - if (kittenSettings?.enabled === false) return; - try { + if (!isSeqta404Page()) return; + + const stored = await storagePromise; + if ((stored.onoff ?? true) === false) return; + const kittenSettings = stored["plugin.error-page-kitten.settings"] as + | { enabled?: boolean } + | undefined; + if (kittenSettings?.enabled === false) return; + mountErrorPageKitten(); - document.getElementById("bsplus-404-flash-hide")?.remove(); } catch (error) { - document.getElementById("bsplus-404-flash-hide")?.remove(); document .querySelectorAll(".bsplus-kitten-404-hidden") .forEach((el) => el.classList.remove("bsplus-kitten-404-hidden")); console.error("[BetterSEQTA+] Failed to boot 404 page:", error); + } finally { + document.getElementById("bsplus-404-flash-hide")?.remove(); } } @@ -230,4 +230,4 @@ function recoverFromStaleDevModuleGraph(error: unknown) { console.error( "[BetterSEQTA+] Dev module graph is still stale after recovery. Restart `npm run dev`, then reload this page.", ); -} \ No newline at end of file +} diff --git a/src/interface/utils/buildSimpleTheme.test.ts b/src/interface/utils/buildSimpleTheme.test.ts index 63313b59..e619ffd1 100644 --- a/src/interface/utils/buildSimpleTheme.test.ts +++ b/src/interface/utils/buildSimpleTheme.test.ts @@ -3,6 +3,16 @@ import { buildThemeBuilderCss } from "./themeBuilderDraft"; import { getFontPreset } from "@/seqta/ui/fonts/presets"; describe("buildSimpleTheme", () => { + it("paints the tint above an opaque photo when blur is disabled", () => { + const css = buildThemeBuilderCss( + getFontPreset("inter"), + ["theme-bg-0"], + { accentColor: "#00f", overlayOpacity: 0.5, backgroundBlurPx: 0 }, + ); + const backgroundLayers = css.match(/background-image: (.*) !important;/)?.[1]; + expect(backgroundLayers).toMatch(/^linear-gradient\(.*\), var\(--theme-bg-0\)$/); + }); + it("builds CSS with font import and image variables", () => { const css = buildThemeBuilderCss( getFontPreset("inter"), diff --git a/src/interface/utils/themeBuilderDraft.ts b/src/interface/utils/themeBuilderDraft.ts index 9067c694..22cd4d1f 100644 --- a/src/interface/utils/themeBuilderDraft.ts +++ b/src/interface/utils/themeBuilderDraft.ts @@ -30,7 +30,7 @@ export function buildThemeBuilderCss( imageVariables: string[], draft: Pick< ThemeBuilderDraft, - "accentColor" | "gradientEnd" | "gradientAngle" | "backgroundBlurPx" | "overlayOpacity" + "accentColor" | "gradientEnd" | "gradientAngle" | "backgroundBlurPx" | "overlayOpacity" | "customCssExtra" >, ): string { const importLine = font.googleUrl ? `@import url("${font.googleUrl}");\n` : ""; @@ -77,9 +77,8 @@ export function buildThemeBuilderCss( background-attachment: fixed !important; }`); } else { - const bgLayers: string[] = []; + const bgLayers: string[] = [gradientLayer]; if (imageLayer) bgLayers.push(imageLayer); - bgLayers.push(gradientLayer); rules.push(`#container { background-image: ${bgLayers.join(", ")} !important; background-size: cover !important; diff --git a/src/plugins/built-in/gradeAnalytics/GradeInferencePanel.svelte b/src/plugins/built-in/gradeAnalytics/GradeInferencePanel.svelte index e6d06b1e..7dd1e0a7 100644 --- a/src/plugins/built-in/gradeAnalytics/GradeInferencePanel.svelte +++ b/src/plugins/built-in/gradeAnalytics/GradeInferencePanel.svelte @@ -21,7 +21,7 @@ let saving = $state(false); $effect(() => { - draft = structuredClone(settings); + draft = $state.snapshot(settings); }); function updateDraft(patch: Partial) { diff --git a/src/plugins/built-in/gradeAnalytics/api.test.ts b/src/plugins/built-in/gradeAnalytics/api.test.ts new file mode 100644 index 00000000..111f30df --- /dev/null +++ b/src/plugins/built-in/gradeAnalytics/api.test.ts @@ -0,0 +1,65 @@ +import { afterEach, beforeEach, expect, it, jest } from "@jest/globals"; + +jest.mock("@/seqta/ui/AddBetterSEQTAElements", () => ({ + getUserInfo: async () => ({ id: 12 }), +})); +jest.mock("@/seqta/utils/listeners/SettingsState", () => ({ + settingsState: { hideSensitiveContent: false }, +})); +jest.mock("@/seqta/ui/dev/hideSensitiveContent", () => ({ + getMockGradeAnalyticsData: () => [], +})); + +import { syncGradeAnalytics } from "./api"; +import { loadAnalyticsCache, saveGradeInferenceSettings } from "./storage"; +import { DEFAULT_ANALYTICS_GRADE_INFERENCE } from "./gradeInferenceSettings"; + +const origin = "https://school.seqta.com.au"; + +beforeEach(() => { + Object.defineProperty(globalThis, "location", { + configurable: true, + value: { origin }, + }); +}); +afterEach(() => jest.restoreAllMocks()); + +it("removes cached custom rubric percentages when inference is disabled", async () => { + jest.spyOn(globalThis, "fetch").mockImplementation(async (url) => + Response.json({ + payload: String(url).includes("/load/subjects") + ? [] + : [ + { + id: 1, + title: "Essay", + subject: "English", + due: "2026-07-20", + status: "MARKS_RELEASED", + results: { grade: "Highly accomplished" }, + }, + ], + }), + ); + await saveGradeInferenceSettings(origin, 12, { + ...DEFAULT_ANALYTICS_GRADE_INFERENCE, + useCustomGradeBands: true, + gradeBands: [{ id: "band", label: "Highly accomplished", percent: 90 }], + }); + expect((await syncGradeAnalytics()).assessments[0]).toMatchObject({ + finalGrade: 90, + gradeSource: "customBand", + }); + + await saveGradeInferenceSettings( + origin, + 12, + DEFAULT_ANALYTICS_GRADE_INFERENCE, + ); + const refreshed = await syncGradeAnalytics(); + expect(refreshed.assessments[0].finalGrade).toBeUndefined(); + expect(refreshed.assessments[0].gradeSource).toBeUndefined(); + expect( + (await loadAnalyticsCache(origin, 12))?.assessments[0].finalGrade, + ).toBeUndefined(); +}); diff --git a/src/plugins/built-in/gradeAnalytics/api.ts b/src/plugins/built-in/gradeAnalytics/api.ts index e76e0cf9..8856ff3b 100644 --- a/src/plugins/built-in/gradeAnalytics/api.ts +++ b/src/plugins/built-in/gradeAnalytics/api.ts @@ -335,7 +335,11 @@ function mergeRawAssessments( const letterGrade = extractLetterGrade(raw); const existingItem = existingMap.get(id); - if (existingItem?.finalGrade !== undefined && finalGrade === undefined) { + if ( + existingItem?.finalGrade !== undefined && + finalGrade === undefined && + (!existingItem.gradeSource || existingItem.gradeSource === "seqta") + ) { continue; } diff --git a/src/plugins/built-in/gradeAnalytics/gradeResolution.test.ts b/src/plugins/built-in/gradeAnalytics/gradeResolution.test.ts index c4b3f82e..42f21666 100644 --- a/src/plugins/built-in/gradeAnalytics/gradeResolution.test.ts +++ b/src/plugins/built-in/gradeAnalytics/gradeResolution.test.ts @@ -100,4 +100,17 @@ describe("resolveGradeFromAssessmentPayload", () => { expect(resolved.finalGrade).toBe(72); expect(resolved.source).toBe("customBand"); }); + + it("attributes unmatched conventional letters to the default scale", () => { + expect( + resolveGradeFromAssessmentPayload( + { status: "MARKS_RELEASED", results: { grade: "A" } }, + { + ...DEFAULT_ANALYTICS_GRADE_INFERENCE, + useCustomGradeBands: true, + gradeBands: [{ id: "1", label: "Proficient", percent: 72 }], + }, + ), + ).toMatchObject({ finalGrade: 85, source: "defaultLetter" }); + }); }); diff --git a/src/plugins/built-in/gradeAnalytics/gradeResolution.ts b/src/plugins/built-in/gradeAnalytics/gradeResolution.ts index cbd6a148..1d90b88b 100644 --- a/src/plugins/built-in/gradeAnalytics/gradeResolution.ts +++ b/src/plugins/built-in/gradeAnalytics/gradeResolution.ts @@ -37,7 +37,7 @@ function parseGradeString(value: unknown): string | undefined { return s || undefined; } -function percentFromGradeLabel( +function customPercentFromGradeLabel( label: string | undefined, settings: AnalyticsGradeInferenceSettings, ): number | undefined { @@ -50,8 +50,6 @@ function percentFromGradeLabel( } } } - const approx = approximatePercentFromLetterGrade(label); - if (approx !== undefined) return approx; return undefined; } @@ -78,7 +76,9 @@ export function rollupPercentFromCriteria( continue; } const letter = parseGradeString(row.results?.grade); - const mapped = percentFromGradeLabel(letter, settings); + const mapped = + customPercentFromGradeLabel(letter, settings) ?? + approximatePercentFromLetterGrade(letter); if (mapped !== undefined) { parts.push({ percent: mapped, weight: criterionWeight(row) }); } @@ -155,7 +155,7 @@ export function resolveGradeFromAssessmentPayload( const letter = extractLetterFromPayload(assessment); if (letter) { const custom = settings.useCustomGradeBands - ? percentFromGradeLabel(letter, settings) + ? customPercentFromGradeLabel(letter, settings) : undefined; const finalGrade = custom ?? approximatePercentFromLetterGrade(letter); diff --git a/src/plugins/built-in/themes/theme-manager.cloud.test.ts b/src/plugins/built-in/themes/theme-manager.cloud.test.ts new file mode 100644 index 00000000..7fa10f61 --- /dev/null +++ b/src/plugins/built-in/themes/theme-manager.cloud.test.ts @@ -0,0 +1,103 @@ +import browser from "webextension-polyfill"; +import localforage from "localforage"; +import { BSPLUS_PENDING_THEME_ENSURE_AFTER_CLOUD_KEY } from "@/seqta/utils/cloudSettingsSync"; +import { ThemeManager } from "./theme-manager"; + +jest.mock("localforage", () => { + const records = new Map(); + return { + getItem: jest.fn(async (key: string) => records.get(key) ?? null), + setItem: jest.fn(async (key: string, value: unknown) => + records.set(key, value), + ), + clear: jest.fn(async () => records.clear()), + }; +}); +jest.mock("@/seqta/utils/listeners/SettingsState", () => ({ + settingsState: {}, +})); +jest.mock("@/seqta/utils/performanceMode", () => ({ + fullMotionEffectsEnabled: () => false, +})); +jest.mock("@/seqta/utils/DevApiBase", () => ({ + getApiBase: () => "https://betterseqta.org", +})); +jest.mock("@/seqta/ui/colors/Manager", () => ({ updateAllColors: jest.fn() })); +jest.mock("@/seqta/ui/colors/customThemeAdaptiveBindings", () => ({})); +jest.mock("@/seqta/utils/patchThemeImagesPageContext", () => ({})); +jest.mock("@/utils/verboseLog", () => ({ + verboseDebug: jest.fn(), + verboseInfo: jest.fn(), +})); +jest.mock("./theme-runtime", () => ({ + validateThemeScript: () => true, + validateThemeDom: () => true, +})); + +describe("cloud theme restoration", () => { + beforeEach(async () => { + await localforage.clear(); + await browser.storage.local.set({ + [BSPLUS_PENDING_THEME_ENSURE_AFTER_CLOUD_KEY]: "catalog-id", + }); + jest.spyOn(console, "warn").mockImplementation(() => {}); + }); + + afterEach(() => jest.restoreAllMocks()); + + it.each(["themes", "custom-themes"])( + "installs a missing %s catalog theme", + async (catalog) => { + const jsonUrl = "https://betterseqta.org/storage/theme.json"; + (browser.runtime.sendMessage as jest.Mock).mockImplementation( + async ({ url }) => { + if ( + url === `https://betterseqta.org/api/${catalog}/catalog-id/download` + ) { + return { + data: { success: true, data: { theme_json_url: jsonUrl } }, + }; + } + if (url === jsonUrl) + return { + data: { + id: "catalog-id", + name: "Restored theme", + CustomCSS: "body { color: red; }", + }, + }; + return { error: "Not found" }; + }, + ); + + await ThemeManager.getInstance().prepareThemeAfterCloudSync(); + + expect(await localforage.getItem("catalog-id")).toMatchObject({ + name: "Restored theme", + installedFromStore: catalog === "themes", + ...(catalog === "custom-themes" + ? { installedFromCommunity: true } + : {}), + }); + expect( + await browser.storage.local.get( + BSPLUS_PENDING_THEME_ENSURE_AFTER_CLOUD_KEY, + ), + ).toEqual({}); + }, + ); + + it("keeps a failed download pending so a later page can retry", async () => { + (browser.runtime.sendMessage as jest.Mock).mockResolvedValue({ + error: "Offline", + }); + await ThemeManager.getInstance().prepareThemeAfterCloudSync(); + expect( + await browser.storage.local.get( + BSPLUS_PENDING_THEME_ENSURE_AFTER_CLOUD_KEY, + ), + ).toEqual({ + [BSPLUS_PENDING_THEME_ENSURE_AFTER_CLOUD_KEY]: "catalog-id", + }); + }); +}); diff --git a/src/plugins/built-in/themes/theme-manager.ts b/src/plugins/built-in/themes/theme-manager.ts index c4ff3b9b..1d59f5ab 100644 --- a/src/plugins/built-in/themes/theme-manager.ts +++ b/src/plugins/built-in/themes/theme-manager.ts @@ -195,7 +195,7 @@ export class ThemeManager { /** * After cloud restore, IndexedDB/theme storage is only reachable from page context (not MV3 SW). - * Background sets BSPLUS_PENDING_THEME_ENSURE_AFTER_CLOUD_KEY; we fetch the store JSON here before setTheme(). + * Background sets BSPLUS_PENDING_THEME_ENSURE_AFTER_CLOUD_KEY; we fetch catalog JSON here before setTheme(). * The resolved id matches cloud sync **`themeId` / `selectedTheme`**: it may be a standard theme uuid or a * flavour (slave) variant id — **`downloadAndInstallStoreTheme`** is the same code path as the theme store installer. */ @@ -205,16 +205,21 @@ export class ThemeManager { const pending = snap[BSPLUS_PENDING_THEME_ENSURE_AFTER_CLOUD_KEY]; if (pending === undefined) return; - await browser.storage.local.remove(BSPLUS_PENDING_THEME_ENSURE_AFTER_CLOUD_KEY); - - if (typeof pending !== "string") return; - const id = pending.trim(); - if (!id) return; + const id = typeof pending === "string" ? pending.trim() : ""; + if (!id) { + await browser.storage.local.remove(BSPLUS_PENDING_THEME_ENSURE_AFTER_CLOUD_KEY); + return; + } const existing = (await localforage.getItem(id)) as CustomTheme | null; - if (existing) return; - - await this.downloadAndInstallStoreTheme({ id, name: id }); + if (!existing) { + try { + await this.downloadAndInstallStoreTheme({ id, name: id }); + } catch { + await this.downloadAndInstallCommunityTheme({ id }); + } + } + await browser.storage.local.remove(BSPLUS_PENDING_THEME_ENSURE_AFTER_CLOUD_KEY); } catch (e) { console.warn("[ThemeManager] prepareThemeAfterCloudSync:", e); } diff --git a/src/plugins/core/manager.test.ts b/src/plugins/core/manager.test.ts new file mode 100644 index 00000000..a586f59d --- /dev/null +++ b/src/plugins/core/manager.test.ts @@ -0,0 +1,165 @@ +/** @jest-environment jsdom */ +import { PluginManager } from "./manager"; +import { settingsState } from "@/seqta/utils/listeners/SettingsState"; +import { isPluginAllowedInPerformanceMode } from "@/seqta/utils/performanceMode"; + +jest.mock("@/seqta/utils/performanceMode", () => ({ + isPluginAllowedInPerformanceMode: jest.fn(() => true), +})); + +test("startup and performance synchronization share one plugin mount and cleanup", async () => { + const manager = PluginManager.getInstance(); + let release!: () => void; + const ready = new Promise((resolve) => { + release = resolve; + }); + const cleanup = jest.fn(); + manager.registerPlugin({ + id: "grade-analytics", + name: "Analytics", + description: "", + version: "1", + settings: {}, + run: async () => { + await ready; + const row = document.createElement("li"); + row.dataset.key = "analytics"; + document.body.append(row); + return () => { + row.remove(); + cleanup(); + }; + }, + }); + + const synchronization = manager.startPlugin("grade-analytics"); + const startup = manager.startAllPlugins(); + release(); + await Promise.all([synchronization, startup]); + + expect(document.querySelectorAll('[data-key="analytics"]')).toHaveLength(1); + await manager.stopPlugin("grade-analytics"); + expect(document.querySelectorAll('[data-key="analytics"]')).toHaveLength(0); + expect(cleanup).toHaveBeenCalledTimes(1); +}); + +test.each(["plugin", "master", "performance"])( + "a redundant startup cannot cancel a pending %s disable", + async (disable) => { + const manager = PluginManager.getInstance(); + const id = `pending-${disable}`; + const storageKey = `plugin.${id}.settings`; + let release!: () => void; + let enter!: () => void; + const ready = new Promise((resolve) => { + release = resolve; + }); + const entered = new Promise((resolve) => { + enter = resolve; + }); + const row = document.createElement("li"); + const cleanup = jest.fn(() => row.remove()); + settingsState.onoff = true; + manager.registerPlugin({ + id, + name: "Pending", + description: "", + version: "1", + settings: {}, + disableToggle: true, + run: async () => { + enter(); + await ready; + document.body.append(row); + return cleanup; + }, + }); + + const startup = manager.startPlugin(id); + await entered; + if (disable === "plugin") + settingsState.setKey(storageKey, { enabled: false }); + if (disable === "master") settingsState.onoff = false; + if (disable === "performance") + jest.mocked(isPluginAllowedInPerformanceMode).mockReturnValue(false); + const stopping = manager.stopPlugin(id); + const redundantStartup = manager.startPlugin(id); + release(); + await Promise.all([startup, stopping, redundantStartup]); + + try { + expect(row.isConnected).toBe(false); + expect(manager.isPluginRunning(id)).toBe(false); + expect(cleanup).toHaveBeenCalledTimes(1); + } finally { + settingsState.onoff = true; + jest.mocked(isPluginAllowedInPerformanceMode).mockReturnValue(true); + } + }, +); + +test("disabling a plugin during startup cleans up its eventual mount", async () => { + const manager = PluginManager.getInstance(); + let release!: () => void; + const ready = new Promise((resolve) => { + release = resolve; + }); + const row = document.createElement("li"); + manager.registerPlugin({ + id: "enhanced-navigation", + name: "Navigation", + description: "", + version: "1", + settings: {}, + run: async () => { + await ready; + document.body.append(row); + return () => row.remove(); + }, + }); + + const startup = manager.startPlugin("enhanced-navigation"); + const stopping = manager.stopPlugin("enhanced-navigation"); + release(); + await Promise.all([startup, stopping]); + + expect(row.isConnected).toBe(false); + expect(manager.isPluginRunning("enhanced-navigation")).toBe(false); +}); + +test("re-enabling during a pending startup wins over an earlier stop", async () => { + const manager = PluginManager.getInstance(); + let release!: () => void; + const ready = new Promise((resolve) => { + release = resolve; + }); + const row = document.createElement("li"); + const cleanup = jest.fn(() => row.remove()); + settingsState.setKey("plugin.background-music.settings", { enabled: true }); + manager.registerPlugin({ + id: "background-music", + name: "Music", + description: "", + version: "1", + settings: {}, + disableToggle: true, + run: async () => { + await ready; + document.body.append(row); + return cleanup; + }, + }); + + const startup = manager.startPlugin("background-music"); + settingsState.setKey("plugin.background-music.settings", { enabled: false }); + const stopping = manager.stopPlugin("background-music"); + settingsState.setKey("plugin.background-music.settings", { enabled: true }); + const restarting = manager.startPlugin("background-music"); + release(); + await Promise.all([startup, stopping, restarting]); + + expect(row.isConnected).toBe(true); + expect(manager.isPluginRunning("background-music")).toBe(true); + expect(cleanup).not.toHaveBeenCalled(); + await manager.stopPlugin("background-music"); +}); diff --git a/src/plugins/core/manager.ts b/src/plugins/core/manager.ts index 741f267a..c4975610 100644 --- a/src/plugins/core/manager.ts +++ b/src/plugins/core/manager.ts @@ -57,6 +57,8 @@ export class PluginManager { private static instance: PluginManager; private plugins: Map> = new Map(); private runningPlugins: Map = new Map(); + private startingPlugins: Map> = new Map(); + private pendingStops: Map = new Map(); private eventBacklog: Map = new Map(); private cleanupFunctions: Map void> = new Map(); private apiDisposers: Map void> = new Map(); @@ -161,6 +163,22 @@ export class PluginManager { * @throws {Error} If the plugin is not found, or if an error occurs during plugin initialization or execution. */ public async startPlugin(pluginId: string): Promise { + const plugin = this.plugins.get(pluginId); + if (plugin && !this.shouldStartPlugin(plugin)) return; + this.pendingStops.delete(pluginId); + const starting = this.startingPlugins.get(pluginId); + if (starting) return starting; + + const promise = this.startPluginOnce(pluginId); + this.startingPlugins.set(pluginId, promise); + try { + await promise; + } finally { + this.startingPlugins.delete(pluginId); + } + } + + private async startPluginOnce(pluginId: string): Promise { const plugin = this.plugins.get(pluginId); if (!plugin) { throw new Error(`Plugin "${pluginId}" not found`); @@ -175,31 +193,6 @@ export class PluginManager { const api = createPluginAPI(plugin); this.apiDisposers.set(pluginId, api.dispose); - // Check if plugin is enabled before starting - if (plugin.disableToggle) { - const all = settingsState.getAll() as unknown as Record; - const pluginSettings = all[`plugin.${pluginId}.settings`] as - | PluginSettingsStorage - | undefined; - const enabled = - pluginSettings?.enabled ?? plugin.defaultEnabled ?? true; - if (!enabled) { - this.disposePluginAPI(pluginId); - verboseInfo( - `Plugin "${pluginId}" is disabled, skipping initialization`, - ); - return; - } - } - - 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"); @@ -211,7 +204,19 @@ export class PluginManager { // Wait for both settings and storage to be loaded before starting the plugin await Promise.all([(api.settings as any).loaded, api.storage.loaded]); + if (!this.shouldStartPlugin(plugin)) { + this.removePluginStyles(pluginId); + this.disposePluginAPI(pluginId); + return; + } + const result = await plugin.run(api); + if (!this.shouldStartPlugin(plugin)) { + if (typeof result === "function") result(); + this.removePluginStyles(pluginId); + this.disposePluginAPI(pluginId); + return; + } if (typeof result === "function") { this.cleanupFunctions.set(plugin.id, result); } @@ -231,6 +236,16 @@ export class PluginManager { } } + private shouldStartPlugin(plugin: Plugin): boolean { + if (settingsState.onoff === false || !isPluginAllowedInPerformanceMode(plugin.id)) { + return false; + } + if (!plugin.disableToggle) return true; + const all = settingsState.getAll() as unknown as Record; + const stored = all[`plugin.${plugin.id}.settings`] as PluginSettingsStorage | undefined; + return stored?.enabled ?? plugin.defaultEnabled ?? true; + } + private removePluginStyles(pluginId: string): void { const styleElement = this.styleElements.get(pluginId); if (styleElement) { @@ -294,6 +309,11 @@ export class PluginManager { * @returns {Promise} A promise that resolves when the plugin has been stopped. */ public async stopPlugin(pluginId: string): Promise { + const stopRequest = Symbol(); + this.pendingStops.set(pluginId, stopRequest); + await this.startingPlugins.get(pluginId)?.catch(() => {}); + if (this.pendingStops.get(pluginId) !== stopRequest) return; + this.pendingStops.delete(pluginId); this.removePluginStyles(pluginId); this.disposePluginAPI(pluginId); diff --git a/src/seqta/ui/sidebar/parseNativeMenu.ts b/src/seqta/ui/sidebar/parseNativeMenu.ts index d713bdb2..6bbae392 100644 --- a/src/seqta/ui/sidebar/parseNativeMenu.ts +++ b/src/seqta/ui/sidebar/parseNativeMenu.ts @@ -111,7 +111,7 @@ export function parseNativeMenu(menu: HTMLElement): SidebarItem[] { return [...list.children] .filter((node): node is HTMLElement => node instanceof HTMLElement) - .map(parseEntry) + .map((entry) => parseEntry(entry)) .filter((item): item is SidebarItem => item != null); } diff --git a/src/seqta/ui/sidebar/sidebarStyles.test.ts b/src/seqta/ui/sidebar/sidebarStyles.test.ts new file mode 100644 index 00000000..d386c230 --- /dev/null +++ b/src/seqta/ui/sidebar/sidebarStyles.test.ts @@ -0,0 +1,52 @@ +/** @jest-environment jsdom */ +import { settingsState } from "@/seqta/utils/listeners/SettingsState"; +import { applySidebarLook, clearSidebarAppearance } from "./sidebarStyles"; + +jest.mock("@/seqta/utils/performanceMode", () => ({ isPerformanceMode: () => false })); + +beforeEach(() => { + clearSidebarAppearance(document.getElementById("menu")); + document.body.innerHTML = ""; + settingsState.sidebarDensity = "compact"; + settingsState.sidebarActiveIndicator = "outline"; + settingsState.sidebarWidth = "wide"; + settingsState.sidebarPosition = "right"; +}); + +test("early sidebar preparation and cleanup work before body exists", () => { + const body = document.body; + body.remove(); + try { + expect(() => applySidebarLook(null)).not.toThrow(); + expect(document.documentElement.style.getPropertyValue("--bsplus-sidebar-width")).toBe("320px"); + expect(() => clearSidebarAppearance(null)).not.toThrow(); + } finally { + document.documentElement.append(body); + } +}); + +test.each([false, true])("applies unchanged settings to a newly available menu (replacement: %s)", (replacement) => { + const initialMenu = replacement ? document.createElement("div") : null; + applySidebarLook(initialMenu); + const menu = document.createElement("div"); + menu.id = "menu"; + document.body.append(menu); + + applySidebarLook(menu); + + expect(menu.classList.contains("bsplus-sidebar-density-compact")).toBe(true); + expect(menu.classList.contains("bsplus-sidebar-indicator-outline")).toBe(true); +}); + +test("restores sidebar variables and classes after disable and re-enable", () => { + const menu = document.createElement("div"); + applySidebarLook(menu); + clearSidebarAppearance(menu); + expect(document.documentElement.style.getPropertyValue("--bsplus-sidebar-width")).toBe(""); + + applySidebarLook(menu); + + expect(document.documentElement.style.getPropertyValue("--bsplus-sidebar-width")).toBe("320px"); + expect(menu.classList.contains("bsplus-sidebar-density-compact")).toBe(true); + expect(document.body.classList.contains("bsplus-sidebar-right")).toBe(true); +}); diff --git a/src/seqta/ui/sidebar/sidebarStyles.ts b/src/seqta/ui/sidebar/sidebarStyles.ts index 9e3511e0..5366e208 100644 --- a/src/seqta/ui/sidebar/sidebarStyles.ts +++ b/src/seqta/ui/sidebar/sidebarStyles.ts @@ -127,7 +127,7 @@ export function applySidebarStyleClass( /** Apply left/right placement on `body` and drill slide direction vars. */ export function applySidebarPosition() { const position = normalizeSidebarPosition(settingsState.sidebarPosition); - document.body.classList.toggle("bsplus-sidebar-right", position === "right"); + document.body?.classList.toggle("bsplus-sidebar-right", position === "right"); const root = document.documentElement; root.style.setProperty("--bsplus-slide-off", position === "right" ? "320px" : "-320px"); root.style.setProperty("--bsplus-slide-off-compact", position === "right" ? "70px" : "-70px"); @@ -135,6 +135,7 @@ export function applySidebarPosition() { /** Safe to call with no menu (still sets width/blur/radius on `:root`). */ let lastSidebarLookKey = ""; +let lastSidebarLookMenu: HTMLElement | null | undefined; export function applySidebarLook( menu: HTMLElement | null | undefined = document.getElementById("menu"), @@ -150,8 +151,9 @@ export function applySidebarLook( applySidebarPosition(); const lookKey = `${density}|${indicator}|${width}|${radius}|${blur}|${normalizeSidebarPosition(settingsState.sidebarPosition)}`; - if (lookKey === lastSidebarLookKey) return; + if (lookKey === lastSidebarLookKey && menu === lastSidebarLookMenu) return; lastSidebarLookKey = lookKey; + lastSidebarLookMenu = menu; const root = document.documentElement; root.style.setProperty("--bsplus-sidebar-width", `${SIDEBAR_WIDTH_PX[width]}px`); @@ -169,13 +171,15 @@ export function applySidebarLook( } export function clearSidebarAppearance(menu: HTMLElement | null | undefined) { + lastSidebarLookKey = ""; + lastSidebarLookMenu = undefined; const root = document.documentElement; root.style.removeProperty("--bsplus-sidebar-width"); root.style.removeProperty("--bsplus-sidebar-radius"); root.style.removeProperty("--bsplus-sidebar-blur"); root.style.removeProperty("--bsplus-slide-off"); root.style.removeProperty("--bsplus-slide-off-compact"); - document.body.classList.remove("bsplus-sidebar-right"); + document.body?.classList.remove("bsplus-sidebar-right"); if (!menu) return; clearPrefixed(menu, STYLE_CLASS_PREFIX); clearPrefixed(menu, DENSITY_CLASS_PREFIX); diff --git a/src/seqta/utils/calendarSync/remoteEvents.test.ts b/src/seqta/utils/calendarSync/remoteEvents.test.ts new file mode 100644 index 00000000..6b91ba6e --- /dev/null +++ b/src/seqta/utils/calendarSync/remoteEvents.test.ts @@ -0,0 +1,84 @@ +import { afterEach, expect, it, jest } from "@jest/globals"; +import { + listGoogleSyncedEvents, + listOutlookSyncedEvents, +} from "./remoteEvents"; + +afterEach(() => jest.restoreAllMocks()); + +it.each([ + { provider: "google", body: "invalid JSON" }, + { provider: "outlook", body: "invalid JSON" }, + { + provider: "google", + body: JSON.stringify({ error: { message: "Invalid response" } }), + }, + { provider: "outlook", body: "{}" }, +])( + "rejects malformed successful $provider listings ($body)", + async ({ provider, body }) => { + jest.spyOn(globalThis, "fetch").mockResolvedValue(new Response(body)); + const range = { from: "2026-10-04", until: "2026-10-04" }; + const listing = + provider === "google" + ? listGoogleSyncedEvents("token", "calendar", range) + : listOutlookSyncedEvents("token", range); + await expect(listing).rejects.toThrow(); + }, +); + +it.each(["google", "outlook"])( + "queries %s over complete local days across Sydney DST", + async (provider) => { + const zone = Intl.DateTimeFormat().resolvedOptions().timeZone; + const expected = + zone === "Australia/Sydney" + ? ["2026-10-03T14:00:00.000Z", "2026-10-04T13:00:00.000Z"] + : zone === "UTC" + ? ["2026-10-04T00:00:00.000Z", "2026-10-05T00:00:00.000Z"] + : null; + let requestedBounds: string[] = []; + jest.spyOn(globalThis, "fetch").mockImplementation(async (url) => { + const query = new URL(String(url)).searchParams; + requestedBounds = + provider === "google" + ? [query.get("timeMin")!, query.get("timeMax")!] + : [query.get("startDateTime")!, query.get("endDateTime")!]; + return Response.json(provider === "google" ? {} : { value: [] }); + }); + const range = { from: "2026-10-04", until: "2026-10-04" }; + if (provider === "google") + await listGoogleSyncedEvents("token", "calendar", range); + else await listOutlookSyncedEvents("token", range); + if (expected) expect(requestedBounds).toEqual(expected); + else { + const [start, end] = requestedBounds.map((value) => new Date(value)); + expect([ + start.getDate(), + start.getHours(), + end.getDate(), + end.getHours(), + ]).toEqual([4, 0, 5, 0]); + } + }, +); + +it("rejects an incomplete paginated listing rather than authorizing reconciliation", async () => { + jest + .spyOn(globalThis, "fetch") + .mockResolvedValueOnce( + Response.json({ items: [], nextPageToken: "second-page" }), + ) + .mockResolvedValueOnce( + Response.json( + { error: { message: "Page unavailable" } }, + { status: 400 }, + ), + ); + await expect( + listGoogleSyncedEvents("token", "calendar", { + from: "2026-10-04", + until: "2026-10-04", + }), + ).rejects.toThrow("Page unavailable"); +}); diff --git a/src/seqta/utils/calendarSync/remoteEvents.ts b/src/seqta/utils/calendarSync/remoteEvents.ts index 3f1156fa..5624500d 100644 --- a/src/seqta/utils/calendarSync/remoteEvents.ts +++ b/src/seqta/utils/calendarSync/remoteEvents.ts @@ -182,16 +182,13 @@ export function deleteOutlookCalendarEvent( } function toRfc3339Start(date: string): string { - return `${date}T00:00:00Z`; + return new Date(`${date}T00:00:00`).toISOString(); } function toRfc3339EndExclusive(date: string): string { - const d = new Date(`${date}T12:00:00Z`); - d.setUTCDate(d.getUTCDate() + 1); - const y = d.getUTCFullYear(); - const m = String(d.getUTCMonth() + 1).padStart(2, "0"); - const day = String(d.getUTCDate()).padStart(2, "0"); - return `${y}-${m}-${day}T00:00:00Z`; + const d = new Date(`${date}T00:00:00`); + d.setDate(d.getDate() + 1); + return d.toISOString(); } function dateFromDateTime(value: string | undefined): string { @@ -264,7 +261,7 @@ export async function listGoogleSyncedEvents( { method: "GET" }, refreshAccessToken, ); - const json = (await res.json().catch(() => ({}))) as { + const json = (await res.json()) as { items?: GoogleListItem[]; nextPageToken?: string; error?: { message?: string }; @@ -272,6 +269,15 @@ export async function listGoogleSyncedEvents( if (!res.ok) { throw new Error(json?.error?.message ?? `Google Calendar list failed (${res.status})`); } + if ( + !json || + typeof json !== "object" || + Array.isArray(json) || + json.error || + (json.items !== undefined && !Array.isArray(json.items)) + ) { + throw new Error("Invalid Google Calendar list response."); + } for (const item of json.items ?? []) { const mapped = googleItemToRemote(item, includeUnkeyed); @@ -360,7 +366,7 @@ export async function listOutlookSyncedEvents( }, refreshAccessToken, ); - const json = (await res.json().catch(() => ({}))) as { + const json = (await res.json()) as { value?: OutlookListItem[]; "@odata.nextLink"?: string; error?: { message?: string }; @@ -368,6 +374,9 @@ export async function listOutlookSyncedEvents( if (!res.ok) { throw new Error(json?.error?.message ?? `Outlook Calendar list failed (${res.status})`); } + if (!Array.isArray(json?.value) || json.error) { + throw new Error("Invalid Outlook Calendar list response."); + } for (const item of json.value ?? []) { const mapped = outlookItemToRemote(item, includeUnkeyed); diff --git a/src/seqta/utils/calendarSync/syncEngine.ts b/src/seqta/utils/calendarSync/syncEngine.ts index 1ff8f08e..723a6569 100644 --- a/src/seqta/utils/calendarSync/syncEngine.ts +++ b/src/seqta/utils/calendarSync/syncEngine.ts @@ -40,6 +40,7 @@ import { writeGoogleCalendarState, } from "@/seqta/utils/calendarSync/providerStorage"; import { + isDateInRange, syncWindowRange, trailingWeekRange, wideCleanupRange, @@ -199,6 +200,9 @@ export async function syncLessonsToCalendar( syncWindowRange, trailingWeekRange, }); + const currentMapKeys = new Set( + events.map((event) => eventMapKey(request.origin, event.seqtaKey)), + ); try { const remoteEvents = await provider.listSyncedEvents( @@ -207,11 +211,21 @@ export async function syncLessonsToCalendar( refreshAccessToken, ); mergeRemoteEventsIntoMap(eventMap, request.origin, remoteEvents, eventMapKey); + const remoteIds = new Set(remoteEvents.map((event) => event.id)); + for (const key of currentMapKeys) { + const entry = normalizeEventMapEntry(eventMap[key]); + if ( + entry?.date && + isDateInRange(entry.date, reconcileRange) && + !remoteIds.has(entry.id) + ) { + delete eventMap[key]; + } + } } catch (err) { verboseLog(`[BetterSEQTA+] ${provider.label} remote event list failed:`, err); } - const currentMapKeys = new Set(events.map((event) => eventMapKey(request.origin, event.seqtaKey))); let staleEntries = entriesToPrune( eventMap, request.origin, diff --git a/src/seqta/utils/cloudSettingsSync.patch.test.ts b/src/seqta/utils/cloudSettingsSync.patch.test.ts index 1eb03998..5c06a6a8 100644 --- a/src/seqta/utils/cloudSettingsSync.patch.test.ts +++ b/src/seqta/utils/cloudSettingsSync.patch.test.ts @@ -1,10 +1,35 @@ import { + applyDownloadedEnvelope, + buildUploadPayload, buildUploadPatch, CLOUD_SETTINGS_SYNC_SCHEMA_VERSION, diffSyncableStorage, normalizeStorageForSync, normalizeThemeIdForSync, } from "./cloudSettingsSync"; +import browser from "webextension-polyfill"; + +describe("calendar credentials stay device-local", () => { + const key = "bsplus_outlook_calendar"; + const remoteConnection = { accessToken: "remote-access", refreshToken: "remote-refresh" }; + + it("excludes Outlook credentials from full and sparse uploads", () => { + const all = { DarkMode: true, [key]: remoteConnection }; + expect(buildUploadPayload(all).data).toEqual({ DarkMode: true }); + expect(buildUploadPatch(all, { DarkMode: true })).toBeNull(); + }); + + it.each([undefined, { accessToken: "local-access", refreshToken: "local-refresh" }])( + "ignores Outlook credentials in old backups and preserves local connection %p", + async (localConnection) => { + if (localConnection) await browser.storage.local.set({ [key]: localConnection }); + await applyDownloadedEnvelope({ data: { DarkMode: false, [key]: remoteConnection } }); + const stored = await browser.storage.local.get(); + expect(stored.DarkMode).toBe(false); + expect(stored[key]).toEqual(localConnection); + }, + ); +}); describe("normalizeStorageForSync", () => { it("strips omitted auth and client-only keys", () => { diff --git a/src/seqta/utils/cloudSettingsSync.ts b/src/seqta/utils/cloudSettingsSync.ts index bf42ecb6..a26b0178 100644 --- a/src/seqta/utils/cloudSettingsSync.ts +++ b/src/seqta/utils/cloudSettingsSync.ts @@ -39,6 +39,7 @@ export const KEYS_OMITTED_FROM_CLOUD_UPLOAD = [ "cloudAccessToken", "cloudUsername", "bsplus_google_calendar", + "bsplus_outlook_calendar", /** Anonymous feedback install id — device-local, never synced. */ "bsplus_install_id", /** Pending feedback ids awaiting a reply notification — device-local. */ @@ -76,6 +77,7 @@ const AUTH_KEYS_TO_PRESERVE = [ "bsplus_client_id", "bsplus_user", "bsplus_google_calendar", + "bsplus_outlook_calendar", ] as const; const OMIT_FROM_UPLOAD_EXACT = new Set([ diff --git a/src/seqta/utils/googleCalendar/fetchTimetable.test.ts b/src/seqta/utils/googleCalendar/fetchTimetable.test.ts index ffcb87cc..bde9eb3c 100644 --- a/src/seqta/utils/googleCalendar/fetchTimetable.test.ts +++ b/src/seqta/utils/googleCalendar/fetchTimetable.test.ts @@ -1,5 +1,134 @@ -import { describe, expect, it } from "@jest/globals"; -import { appointmentToLesson, parseSeqtaDateTime } from "./fetchTimetable"; +import { + afterEach, + beforeEach, + describe, + expect, + it, + jest, +} from "@jest/globals"; +import { + appointmentToLesson, + fetchAppointments, + fetchAssessmentsForCalendarSync, + fetchTimetableLessons, + parseSeqtaDateTime, +} from "./fetchTimetable"; + +describe("calendar source fetches", () => { + const range = { from: "2026-07-20", until: "2026-07-26" }; + const sources = [ + { + name: "assessments", + path: "/assessment/list/upcoming?", + load: fetchAssessmentsForCalendarSync, + empty: { payload: [] }, + }, + { + name: "appointments", + path: "/events/load", + load: fetchAppointments, + empty: { payload: [] }, + }, + { + name: "timetable", + path: "/load/timetable?", + load: fetchTimetableLessons, + empty: { payload: { items: [] } }, + }, + ]; + + beforeEach(() => { + Object.defineProperty(globalThis, "location", { + configurable: true, + value: { + origin: "https://school.seqta.com.au", + pathname: "/", + hash: "", + href: "https://school.seqta.com.au/", + }, + }); + Object.defineProperty(globalThis, "document", { + configurable: true, + value: { body: { classList: { contains: () => false } } }, + }); + }); + + afterEach(() => jest.restoreAllMocks()); + + it("uses the same Engage child for timetable and assessment sync", async () => { + document.body.classList.contains = () => true; + const assessmentStudents: unknown[] = []; + const timetableStudents: unknown[] = []; + jest.spyOn(globalThis, "fetch").mockImplementation(async (url, init) => { + const path = String(url); + const body = JSON.parse(String(init?.body)); + if (path.endsWith("/seqta/parent/load/timetable")) { + if (body.list) + return Response.json({ payload: [{ id: "42", name: "Child" }] }); + timetableStudents.push(body.student); + return Response.json({ payload: { items: [] } }); + } + if (path.endsWith("/seqta/parent/assessment/list/upcoming?")) { + assessmentStudents.push(body.student); + return Response.json({ + payload: [ + { id: 1, title: "Essay", subject: "English", due: "2026-07-20" }, + ], + }); + } + if (path.includes("/seqta/student/")) + return new Response("Wrong account endpoint", { status: 403 }); + return Response.json({ payload: [] }); + }); + await expect(fetchTimetableLessons(range)).resolves.toEqual([]); + await expect(fetchAssessmentsForCalendarSync(range)).resolves.toMatchObject( + [{ id: 1, title: "Essay" }], + ); + expect(timetableStudents).toEqual([42]); + expect(assessmentStudents).toEqual([42]); + }); + + it.each(sources)( + "rejects failed $name fetches instead of reporting an empty source", + async ({ path, load }) => { + jest.spyOn(globalThis, "fetch").mockImplementation(async (url) => { + if (String(url).endsWith(path)) + return new Response("unavailable", { status: 503 }); + return Response.json({ + payload: String(url).endsWith("/login") ? { id: 12 } : [], + }); + }); + await expect(load(range)).rejects.toThrow("SEQTA request failed (503)"); + }, + ); + + it.each(sources)( + "rejects missing $name payloads that cannot authorize reconciliation", + async ({ path, load }) => { + jest.spyOn(globalThis, "fetch").mockImplementation(async (url) => { + if (String(url).endsWith(path)) + return Response.json({ error: "Session expired" }); + return Response.json({ + payload: String(url).endsWith("/login") ? { id: 12 } : [], + }); + }); + await expect(load(range)).rejects.toThrow(); + }, + ); + + it.each(sources)( + "accepts a successfully fetched empty $name source", + async ({ path, load, empty }) => { + jest.spyOn(globalThis, "fetch").mockImplementation(async (url) => { + if (String(url).endsWith(path)) return Response.json(empty); + return Response.json({ + payload: String(url).endsWith("/login") ? { id: 12 } : [], + }); + }); + await expect(load(range)).resolves.toEqual([]); + }, + ); +}); describe("parseSeqtaDateTime", () => { it("parses SEQTA event timestamps", () => { diff --git a/src/seqta/utils/googleCalendar/fetchTimetable.ts b/src/seqta/utils/googleCalendar/fetchTimetable.ts index 9acce95d..26cd9906 100644 --- a/src/seqta/utils/googleCalendar/fetchTimetable.ts +++ b/src/seqta/utils/googleCalendar/fetchTimetable.ts @@ -96,6 +96,14 @@ async function resolveLoginPayload(): Promise { } export async function resolveStudentId(): Promise { + if (isEngageParentContext()) { + const data = await postSeqtaJson<{ payload?: { id?: string | number }[] }>( + "/seqta/parent/load/timetable", + { list: true }, + ); + const id = Array.isArray(data?.payload) ? Number(data.payload[0]?.id) : NaN; + return Number.isFinite(id) && id > 0 ? id : undefined; + } const payload = await resolveLoginPayload(); const id = payload?.id ?? payload?.student; return typeof id === "number" && Number.isFinite(id) ? id : undefined; @@ -159,31 +167,31 @@ export function appointmentToLesson(item: SeqtaAppointmentPayload): SeqtaTimetab export async function fetchAppointments(range: SyncDateRange): Promise { if (isEngageParentContext()) return []; - try { - const person = await resolveStudentId(); - if (person == null) return []; + const person = await resolveStudentId(); + if (person == null) + throw new Error("Could not resolve student for calendar sync."); - const personType = await resolvePersonType(); - const data = await postSeqtaJson<{ payload?: SeqtaAppointmentPayload[] }>( - "/seqta/student/events/load", - { - dateFrom: range.from, - dateTo: range.until, - person, - personType, - }, - ); + const personType = await resolvePersonType(); + const data = await postSeqtaJson<{ payload?: SeqtaAppointmentPayload[] }>( + "/seqta/student/events/load", + { + dateFrom: range.from, + dateTo: range.until, + person, + personType, + }, + ); - const payload = Array.isArray(data?.payload) ? data.payload : []; - const lessons: SeqtaTimetableLesson[] = []; - for (const item of payload) { - const lesson = appointmentToLesson(item); - if (lesson) lessons.push(lesson); - } - return lessons; - } catch { - return []; + if (!Array.isArray(data?.payload)) { + throw new Error("Invalid SEQTA appointments response."); } + const payload = data.payload; + const lessons: SeqtaTimetableLesson[] = []; + for (const item of payload) { + const lesson = appointmentToLesson(item); + if (lesson) lessons.push(lesson); + } + return lessons; } export async function fetchTimetableLessons( @@ -191,17 +199,11 @@ export async function fetchTimetableLessons( ): Promise { const { from, until } = range; const coloursPromise = fetchSubjectColours(); - const appointmentsPromise = fetchAppointments(range); let lessons: SeqtaTimetableLesson[] = []; if (isEngageParentContext()) { - const listJson = await postSeqtaJson<{ payload?: { id?: string | number }[] }>( - "/seqta/parent/load/timetable", - { list: true }, - ); - const firstChild = Array.isArray(listJson?.payload) ? listJson.payload[0] : undefined; - const studentId = firstChild?.id; + const studentId = await resolveStudentId(); if (studentId == null) { throw new Error("No student found on this parent account."); } @@ -209,7 +211,10 @@ export async function fetchTimetableLessons( "/seqta/parent/load/timetable", { from, until, student: studentId }, ); - lessons = Array.isArray(data?.payload?.items) ? data.payload.items : []; + if (!Array.isArray(data?.payload?.items)) { + throw new Error("Invalid SEQTA timetable response."); + } + lessons = data.payload.items; } else { const studentId = await resolveStudentId(); const body: Record = { from, until }; @@ -219,11 +224,14 @@ export async function fetchTimetableLessons( "/seqta/student/load/timetable?", body, ); - lessons = Array.isArray(data?.payload?.items) ? data.payload.items : []; + if (!Array.isArray(data?.payload?.items)) { + throw new Error("Invalid SEQTA timetable response."); + } + lessons = data.payload.items; } const coloured = withSubjectColours(lessons, await coloursPromise); - const appointments = await appointmentsPromise; + const appointments = await fetchAppointments(range); return [...coloured, ...appointments]; } @@ -251,37 +259,38 @@ function assessmentDueInRange(due: string, range: SyncDateRange): boolean { export async function fetchAssessmentsForCalendarSync( range: SyncDateRange, ): Promise { - try { - const studentId = await resolveStudentId(); - if (studentId == null) return []; + const studentId = await resolveStudentId(); + if (studentId == null) + throw new Error("Could not resolve student for calendar sync."); - const path = isEngageParentContext() - ? "/seqta/parent/assessment/list/upcoming?" - : "/seqta/student/assessment/list/upcoming?"; - const data = await postSeqtaJson<{ payload?: unknown[] }>(path, { student: studentId }); - const payload = Array.isArray(data.payload) ? data.payload : []; - - const out: CalendarSyncAssessment[] = []; - for (const raw of payload) { - if (!raw || typeof raw !== "object") continue; - const row = raw as Record; - const id = Number(row.id); - const title = String(row.title ?? "").trim(); - const due = parseAssessmentDue(row); - if (!id || !title || !due || !assessmentDueInRange(due, range)) continue; - if (row.status === "MARKS_RELEASED" || row.status === "CANCELLED") continue; - out.push({ - id, - title, - subject: String(row.subject ?? row.code ?? "").trim(), - code: String(row.code ?? row.subject ?? "").trim(), - due, - status: row.status != null ? String(row.status) : undefined, - }); - } - return out; - } catch (err) { - console.warn("[BetterSEQTA+] Assessment calendar fetch failed:", err); - return []; + const path = isEngageParentContext() + ? "/seqta/parent/assessment/list/upcoming?" + : "/seqta/student/assessment/list/upcoming?"; + const data = await postSeqtaJson<{ payload?: unknown[] }>(path, { + student: studentId, + }); + if (!Array.isArray(data?.payload)) { + throw new Error("Invalid SEQTA assessments response."); } + const payload = data.payload; + + const out: CalendarSyncAssessment[] = []; + for (const raw of payload) { + if (!raw || typeof raw !== "object") continue; + const row = raw as Record; + const id = Number(row.id); + const title = String(row.title ?? "").trim(); + const due = parseAssessmentDue(row); + if (!id || !title || !due || !assessmentDueInRange(due, range)) continue; + if (row.status === "MARKS_RELEASED" || row.status === "CANCELLED") continue; + out.push({ + id, + title, + subject: String(row.subject ?? row.code ?? "").trim(), + code: String(row.code ?? row.subject ?? "").trim(), + due, + status: row.status != null ? String(row.status) : undefined, + }); + } + return out; } diff --git a/src/seqta/utils/googleCalendar/syncEngine.test.ts b/src/seqta/utils/googleCalendar/syncEngine.test.ts index c5206968..7c6a5d4d 100644 --- a/src/seqta/utils/googleCalendar/syncEngine.test.ts +++ b/src/seqta/utils/googleCalendar/syncEngine.test.ts @@ -76,7 +76,9 @@ describe("syncLessonsToGoogleCalendar", () => { }); jest.mocked(upsertGoogleCalendarEvent).mockResolvedValue("google-existing"); jest.mocked(deleteGoogleCalendarEvent).mockResolvedValue(undefined); - jest.mocked(listGoogleSyncedEvents).mockResolvedValue([]); + jest.mocked(listGoogleSyncedEvents).mockResolvedValue([ + { seqtaKey: `${ORIGIN}:cal:12345`, id: "google-existing", date: syncDate, fingerprint: "" }, + ]); }); it("updates existing events and removes stale tracked events on full sync", async () => { @@ -97,6 +99,7 @@ describe("syncLessonsToGoogleCalendar", () => { }); it("creates events that are not yet tracked", async () => { + jest.mocked(listGoogleSyncedEvents).mockResolvedValue([]); jest.mocked(readGoogleCalendarState).mockResolvedValue({ refreshToken: "refresh", calendarId: "app-calendar-id", @@ -152,6 +155,24 @@ describe("syncLessonsToGoogleCalendar", () => { }); }); + it.each([false, true])("repairs missing remote events only after a complete listing (list failed: %s)", async (listFailed) => { + const mapped = lessonToGoogleEvent(ORIGIN, baseLesson, Intl.DateTimeFormat().resolvedOptions().timeZone)!; + jest.mocked(readGoogleCalendarState).mockResolvedValue({ + refreshToken: "refresh", calendarId: "app-calendar-id", + eventMap: { [`${ORIGIN}::${mapped.seqtaKey}`]: { id: "deleted-remotely", date: syncDate, fingerprint: eventFingerprint(mapped) } }, + }); + if (listFailed) jest.mocked(listGoogleSyncedEvents).mockRejectedValueOnce(new Error("Second page failed")); + else jest.mocked(listGoogleSyncedEvents).mockResolvedValueOnce([]); + const result = await syncLessonsToGoogleCalendar({ origin: ORIGIN, lessons: [baseLesson], mode: "full" }, getAccessToken); + if (listFailed) { + expect(upsertGoogleCalendarEvent).not.toHaveBeenCalled(); + expect(result.skipped).toBe(1); + } else { + expect(upsertGoogleCalendarEvent).toHaveBeenCalledWith("test-token", "app-calendar-id", undefined, expect.any(Object), expect.any(Function)); + expect(result.created).toBe(1); + } + }); + it("deletes cancelled lessons that remain inside the sync window", async () => { jest.mocked(readGoogleCalendarState).mockResolvedValue({ refreshToken: "refresh", diff --git a/src/seqta/utils/listeners/StorageChanges.test.ts b/src/seqta/utils/listeners/StorageChanges.test.ts new file mode 100644 index 00000000..e34dc8af --- /dev/null +++ b/src/seqta/utils/listeners/StorageChanges.test.ts @@ -0,0 +1,37 @@ +/** @jest-environment jsdom */ +import { settingsState } from "./SettingsState"; +import { StorageChangeHandler } from "./StorageChanges"; + +jest.mock("@/seqta/ui/colors/Manager", () => ({ updateAllColors: jest.fn() })); +jest.mock("@/seqta/utils/Render/renderShortcuts", () => ({ + renderShortcuts: jest.fn(), +})); +jest.mock("@/seqta/utils/FilterUpcomingAssessments", () => ({ + FilterUpcomingAssessments: jest.fn(), +})); +jest.mock("@/seqta/utils/Loaders/LoadHomePage", () => ({ + registerHomeUpcomingSettingsListeners: jest.fn(), +})); +jest.mock("@/seqta/utils/menuItemVisibility", () => ({ + scheduleMenuItemVisibility: jest.fn(), +})); +jest.mock("@/seqta/utils/Openers/menuOrder", () => ({ + ChangeMenuItemPositions: jest.fn(), +})); +jest.mock("@/seqta/utils/performanceMode", () => ({ + syncPerformanceModeEffects: jest.fn(), +})); + +test("changing the selected font updates the page without reloading", () => { + new StorageChangeHandler(); + settingsState.selectedFont = "inter"; + + expect( + document.documentElement.style.getPropertyValue( + "--betterseqta-font-family", + ), + ).toBe("Inter"); + expect( + document.getElementById("betterseqta-font-override")?.textContent, + ).toContain("font-family: Inter"); +}); diff --git a/src/seqta/utils/listeners/StorageChanges.ts b/src/seqta/utils/listeners/StorageChanges.ts index f102bc96..680e9243 100644 --- a/src/seqta/utils/listeners/StorageChanges.ts +++ b/src/seqta/utils/listeners/StorageChanges.ts @@ -1,5 +1,6 @@ import { settingsState } from "./SettingsState"; import { updateAllColors } from "@/seqta/ui/colors/Manager"; +import { applySelectedFont } from "@/seqta/ui/fonts/Manager"; // Shortcuts rendering import { renderShortcuts } from "@/seqta/utils/Render/renderShortcuts"; diff --git a/src/seqta/utils/settingsPopupAnimation.test.ts b/src/seqta/utils/settingsPopupAnimation.test.ts new file mode 100644 index 00000000..8d588702 --- /dev/null +++ b/src/seqta/utils/settingsPopupAnimation.test.ts @@ -0,0 +1,27 @@ +/** @jest-environment jsdom */ +import { settingsState } from "./listeners/SettingsState"; +import { + animateSettingsClose, + animateSettingsOpen, + isSettingsHostVisiblyOpen, +} from "./settingsPopupAnimation"; + +test("a settings popup reopened during its close animation stays visible", () => { + jest.useFakeTimers(); + try { + settingsState.animations = true; + const host = document.createElement("div"); + document.body.append(host); + animateSettingsOpen(host); + jest.advanceTimersByTime(20); + animateSettingsClose(host); + jest.advanceTimersByTime(50); + animateSettingsOpen(host); + jest.advanceTimersByTime(250); + + expect(isSettingsHostVisiblyOpen(host)).toBe(true); + expect(host.style.opacity).not.toBe("0"); + } finally { + jest.useRealTimers(); + } +}); diff --git a/src/seqta/utils/settingsPopupAnimation.ts b/src/seqta/utils/settingsPopupAnimation.ts index 67034981..5036edbb 100644 --- a/src/seqta/utils/settingsPopupAnimation.ts +++ b/src/seqta/utils/settingsPopupAnimation.ts @@ -61,6 +61,7 @@ export function animateSettingsClose(host: HTMLElement): void { : 200; window.setTimeout(() => { + if (!host.classList.contains(HOST_CLOSING_CLASS)) return; host.classList.remove(HOST_CLOSING_CLASS); host.style.opacity = "0"; }, durationMs); From d97cc86ab3fb9feb36c535e29190e378b8ef5477 Mon Sep 17 00:00:00 2001 From: SethBurkart123 Date: Tue, 6 Oct 2026 11:58:06 +1100 Subject: [PATCH 04/11] fix: make startup notices dismiss consistently --- .../OpenCoursesAssessmentsFixPopup.test.ts | 15 +-- .../Openers/OpenCoursesAssessmentsFixPopup.ts | 5 +- .../Openers/OpenThemeOfTheMonthPopup.test.ts | 96 +++++++++++++++++++ .../utils/Openers/OpenThemeOfTheMonthPopup.ts | 38 +++++--- src/seqta/utils/Openers/StartupPopupQueue.ts | 12 +-- 5 files changed, 125 insertions(+), 41 deletions(-) create mode 100644 src/seqta/utils/Openers/OpenThemeOfTheMonthPopup.test.ts diff --git a/src/seqta/utils/Openers/OpenCoursesAssessmentsFixPopup.test.ts b/src/seqta/utils/Openers/OpenCoursesAssessmentsFixPopup.test.ts index 6826361a..492775bf 100644 --- a/src/seqta/utils/Openers/OpenCoursesAssessmentsFixPopup.test.ts +++ b/src/seqta/utils/Openers/OpenCoursesAssessmentsFixPopup.test.ts @@ -18,7 +18,7 @@ describe("shouldShowCoursesAssessmentsFixPopup", () => { ).toBe(true); }); - it("does not show when BetterSEQTA features are on unless What's New just closed", () => { + it("does not show when BetterSEQTA features are on", () => { expect( shouldShowCoursesAssessmentsFixPopup({ onoff: true, @@ -27,18 +27,6 @@ describe("shouldShowCoursesAssessmentsFixPopup", () => { ).toBe(false); }); - it("shows after What's New even when BetterSEQTA features are already on", () => { - expect( - shouldShowCoursesAssessmentsFixPopup( - { - onoff: true, - coursesAssessmentsFixPopupShown: false, - }, - { afterWhatsNew: true }, - ), - ).toBe(true); - }); - it("does not show again after the user has seen it", () => { expect( shouldShowCoursesAssessmentsFixPopup( @@ -46,7 +34,6 @@ describe("shouldShowCoursesAssessmentsFixPopup", () => { onoff: false, coursesAssessmentsFixPopupShown: true, }, - { afterWhatsNew: true }, ), ).toBe(false); }); diff --git a/src/seqta/utils/Openers/OpenCoursesAssessmentsFixPopup.ts b/src/seqta/utils/Openers/OpenCoursesAssessmentsFixPopup.ts index 52b6bb05..c14cc5a0 100644 --- a/src/seqta/utils/Openers/OpenCoursesAssessmentsFixPopup.ts +++ b/src/seqta/utils/Openers/OpenCoursesAssessmentsFixPopup.ts @@ -12,10 +12,8 @@ export type CoursesAssessmentsFixPopupState = { export function shouldShowCoursesAssessmentsFixPopup( state: CoursesAssessmentsFixPopupState = settingsState, - options?: { afterWhatsNew?: boolean }, ): boolean { if (state.coursesAssessmentsFixPopupShown) return false; - if (options?.afterWhatsNew) return true; return state.onoff === false; } @@ -238,13 +236,12 @@ function setPopupButtonsDisabled(disabled: boolean) { export function OpenCoursesAssessmentsFixPopup( onDismissed?: () => void, - options?: { afterWhatsNew?: boolean }, ) { if (document.getElementById("whatsnewbk")) { onDismissed?.(); return; } - if (!shouldShowCoursesAssessmentsFixPopup(settingsState, options)) { + if (!shouldShowCoursesAssessmentsFixPopup(settingsState)) { onDismissed?.(); return; } diff --git a/src/seqta/utils/Openers/OpenThemeOfTheMonthPopup.test.ts b/src/seqta/utils/Openers/OpenThemeOfTheMonthPopup.test.ts new file mode 100644 index 00000000..ea8e9883 --- /dev/null +++ b/src/seqta/utils/Openers/OpenThemeOfTheMonthPopup.test.ts @@ -0,0 +1,96 @@ +/** @jest-environment jsdom */ +import { OpenThemeOfTheMonthPopup } from "./OpenThemeOfTheMonthPopup"; +import { settingsState } from "../listeners/SettingsState"; + +jest.mock("../DevApiBase", () => ({ + getApiBase: () => "https://example.test", +})); +jest.mock("./PopupManager", () => ({ closePopup: jest.fn() })); +jest.mock("../listeners/SettingsState", () => ({ + settingsState: { animations: false }, +})); + +const entry = { + id: "totm-1", + month: "2026-10", + title: "October Theme", + description: "Preview", + cover_image: "https://example.test/cover.png", + theme_id: null, + theme: null, + created_at: 1, + updated_at: 1, +}; + +beforeEach(() => { + jest.useFakeTimers(); + settingsState.themeOfTheMonthDismissedMonth = undefined; + document.body.innerHTML = ""; +}); + +afterEach(() => { + document + .querySelector(".themeOfTheMonthCardSecondary") + ?.click(); + jest.runOnlyPendingTimers(); + jest.useRealTimers(); +}); + +it.each([false, true])( + "click-away dismisses and records the month once (expanded: %s)", + async (expanded) => { + const onDismissed = jest.fn(); + await OpenThemeOfTheMonthPopup(entry, onDismissed); + if (expanded) + document + .querySelector(".themeOfTheMonthCardPopout")! + .click(); + const outside = expanded + ? document.getElementById("theme-of-the-month-backdrop")! + : document.body; + outside.click(); + document.body.click(); + jest.advanceTimersByTime(30_000); + expect(document.getElementById("theme-of-the-month-card")).toBeNull(); + expect(document.getElementById("theme-of-the-month-backdrop")).toBeNull(); + expect(settingsState.themeOfTheMonthDismissedMonth).toBe(entry.month); + expect(onDismissed).toHaveBeenCalledTimes(1); + }, +); + +it("keeps the card open while interacting with it and its fullscreen preview", async () => { + await OpenThemeOfTheMonthPopup(entry); + document.querySelector(".themeOfTheMonthCardBody")!.click(); + document + .querySelector(".themeOfTheMonthCardImage")! + .click(); + const overlay = document.getElementById("bsplus-popup-media-overlay")!; + expect(overlay).not.toBeNull(); + overlay.querySelector("img")!.click(); + overlay.click(); + jest.advanceTimersByTime(180); + expect(document.getElementById("theme-of-the-month-card")).not.toBeNull(); + expect(settingsState.themeOfTheMonthDismissedMonth).toBeUndefined(); + document.body.click(); + jest.advanceTimersByTime(180); + expect(document.getElementById("theme-of-the-month-card")).toBeNull(); +}); + +it("ignores the opening click and cleans up an existing card when replaced", async () => { + const opener = document.createElement("button"); + document.body.append(opener); + const oldDismissed = jest.fn(); + opener.addEventListener( + "click", + () => void OpenThemeOfTheMonthPopup(entry, oldDismissed), + ); + opener.click(); + expect(document.getElementById("theme-of-the-month-card")).not.toBeNull(); + const newDismissed = jest.fn(); + await OpenThemeOfTheMonthPopup({ ...entry, month: "2026-11" }, newDismissed); + document.body.click(); + jest.advanceTimersByTime(30_000); + expect(settingsState.themeOfTheMonthDismissedMonth).toBe("2026-11"); + expect(newDismissed).toHaveBeenCalledTimes(1); + expect(oldDismissed).not.toHaveBeenCalled(); +}); diff --git a/src/seqta/utils/Openers/OpenThemeOfTheMonthPopup.ts b/src/seqta/utils/Openers/OpenThemeOfTheMonthPopup.ts index 221212be..7cdd3b93 100644 --- a/src/seqta/utils/Openers/OpenThemeOfTheMonthPopup.ts +++ b/src/seqta/utils/Openers/OpenThemeOfTheMonthPopup.ts @@ -227,6 +227,7 @@ const TOTM_MORPH_MS = 550; const TOTM_LAYOUT_SWAP_MS = TOTM_MORPH_MS / 2; let themeOfTheMonthAnimGen = 0; +let cleanupThemeOfTheMonthPopup: (() => void) | undefined; // --------------------------------------------------------------------------- // Dimension helpers @@ -675,6 +676,7 @@ export async function OpenThemeOfTheMonthPopup( entry: ThemeOfTheMonthEntry, onDismissed?: () => void, ): Promise { + cleanupThemeOfTheMonthPopup?.(); document.getElementById("theme-of-the-month-card")?.remove(); document.getElementById("theme-of-the-month-backdrop")?.remove(); @@ -779,13 +781,29 @@ export async function OpenThemeOfTheMonthPopup( ); }; - const dismissWithCleanup = () => { + const cleanup = () => { pauseAutoClose(); window.removeEventListener("resize", onResize); backdrop.remove(); document.removeEventListener("keydown", onDocKey, true); + document.removeEventListener("click", onOutsideClick, true); + if (cleanupThemeOfTheMonthPopup === cleanup) cleanupThemeOfTheMonthPopup = undefined; + }; + const dismissWithCleanup = () => { + cleanup(); closeThemeOfTheMonthCard(card, onDismissed); }; + const dismissForMonth = () => { + settingsState.themeOfTheMonthDismissedMonth = entry.month; + dismissWithCleanup(); + }; + const onOutsideClick = (event: MouseEvent) => { + const target = event.target; + if (target instanceof Node && card.contains(target)) return; + if (target instanceof Element && target.closest("#bsplus-popup-media-overlay")) return; + dismissForMonth(); + }; + cleanupThemeOfTheMonthPopup = cleanup; autoCloseTimeout = window.setTimeout(dismissWithCleanup, 30_000); card.addEventListener("mouseenter", pauseAutoClose, { once: true }); @@ -807,22 +825,12 @@ export async function OpenThemeOfTheMonthPopup( toggleExpanded(); }); - backdrop.addEventListener("click", () => { - if (!isExpanded || expandAnimating) return; - isExpanded = false; - void applyExpandedState(false); - }); - document.addEventListener("keydown", onDocKey, true); - card.querySelector(".themeOfTheMonthCardSecondary")?.addEventListener("click", () => { - settingsState.themeOfTheMonthDismissedMonth = entry.month; - dismissWithCleanup(); - }); + card.querySelector(".themeOfTheMonthCardSecondary")?.addEventListener("click", dismissForMonth); card.querySelector(".themeOfTheMonthCardPrimary")?.addEventListener("click", () => { - settingsState.themeOfTheMonthDismissedMonth = entry.month; - dismissWithCleanup(); + dismissForMonth(); void openThemeStoreWithHighlight(linkedThemeId!); }); @@ -852,6 +860,8 @@ export async function OpenThemeOfTheMonthPopup( card.style.left = "0"; document.body.append(backdrop, card); + // Capture has already passed for the click that opened this card. + document.addEventListener("click", onOutsideClick, true); // Set initial collapsed position instantly (no transition). applyThemeOfTheMonthCardPosition(card, false, false); @@ -886,4 +896,4 @@ export async function showThemeOfTheMonthPopupNow(): Promise { } await OpenThemeOfTheMonthPopup(entry); -} \ No newline at end of file +} diff --git a/src/seqta/utils/Openers/StartupPopupQueue.ts b/src/seqta/utils/Openers/StartupPopupQueue.ts index 30f549a0..4635e5a3 100644 --- a/src/seqta/utils/Openers/StartupPopupQueue.ts +++ b/src/seqta/utils/Openers/StartupPopupQueue.ts @@ -16,7 +16,7 @@ type QueueStep = (goNext: () => void) => void; /** * Runs startup modals in order: What's New (if the extension just updated), - * Courses/Assessments fix notice (after What's New, or if features are off), + * Courses/Assessments fix notice (only if features are off), * Theme of the Month (when the user hasn't dismissed this calendar month), * then feedback reply notifications for pending submissions. */ @@ -32,14 +32,8 @@ export async function runStartupPopupQueue() { steps.push((goNext) => OpenWhatsNewPopup(goNext)); } - if ( - shouldShowCoursesAssessmentsFixPopup(settingsState, { - afterWhatsNew, - }) - ) { - steps.push((goNext) => - OpenCoursesAssessmentsFixPopup(goNext, { afterWhatsNew }), - ); + if (shouldShowCoursesAssessmentsFixPopup(settingsState)) { + steps.push((goNext) => OpenCoursesAssessmentsFixPopup(goNext)); } // Fetch the Theme of the Month before queueing so we don't show an empty From 5928414a1eeaf7353c27e667727484ac7171c123 Mon Sep 17 00:00:00 2001 From: SethBurkart123 Date: Tue, 6 Oct 2026 11:58:06 +1100 Subject: [PATCH 05/11] fix: persist master switch before reloading tabs --- .../listeners/SettingsState.master.test.ts | 39 +++++++++++++++++++ src/seqta/utils/listeners/SettingsState.ts | 21 +++++----- src/seqta/utils/listeners/StorageChanges.ts | 7 ---- 3 files changed, 48 insertions(+), 19 deletions(-) create mode 100644 src/seqta/utils/listeners/SettingsState.master.test.ts diff --git a/src/seqta/utils/listeners/SettingsState.master.test.ts b/src/seqta/utils/listeners/SettingsState.master.test.ts new file mode 100644 index 00000000..114716a9 --- /dev/null +++ b/src/seqta/utils/listeners/SettingsState.master.test.ts @@ -0,0 +1,39 @@ +/** @jest-environment jsdom */ + +describe("master extension setting", () => { + afterEach(() => jest.useRealTimers()); + + it.each([false, true])("persists %s and queued preferences before reloading SEQTA tabs", async (enabled) => { + jest.useFakeTimers(); + let browser: any; + let settings: typeof import("./SettingsState"); + jest.isolateModules(() => { + browser = require("webextension-polyfill").default; + settings = require("./SettingsState"); + }); + await browser.storage.local.set({ onoff: !enabled }); + await settings!.initializeSettingsState(); + browser.runtime.sendMessage.mockClear(); + const originalSet = browser.storage.local.set.getMockImplementation(); + let finishWrite: () => Promise = async () => {}; + browser.storage.local.set.mockImplementationOnce((patch: Record) => new Promise((resolve) => { + finishWrite = async () => { + await originalSet(patch); + resolve(); + }; + })); + browser.runtime.sendMessage.mockImplementation(async () => { + expect(await browser.storage.local.get(null)).toMatchObject({ onoff: enabled, selectedFont: "inter" }); + }); + + settings!.settingsState.selectedFont = "inter"; + settings!.settingsState.onoff = enabled; + jest.advanceTimersByTime(300); + expect(browser.runtime.sendMessage).not.toHaveBeenCalled(); + await finishWrite(); + await Promise.resolve(); + await Promise.resolve(); + + expect(browser.runtime.sendMessage).toHaveBeenCalledWith({ type: "reloadTabs" }); + }); +}); diff --git a/src/seqta/utils/listeners/SettingsState.ts b/src/seqta/utils/listeners/SettingsState.ts index 07d61a15..965698e8 100644 --- a/src/seqta/utils/listeners/SettingsState.ts +++ b/src/seqta/utils/listeners/SettingsState.ts @@ -107,18 +107,7 @@ class StorageManager { return Reflect.get(target.data, prop); }, set: (target, prop: keyof SettingsState, value) => { - if (typeof prop === "string" && isExcludedSettingsKey(prop)) { - void browser.storage.local.set({ [prop]: value }); - return true; - } - const oldValue = target.data[prop]; - - // Only save if the reference actually changed - if (oldValue !== value) { - Reflect.set(target.data, prop, value); - void target.saveToStorage([prop as string]); - target.notifySettingChange(prop as string, value, oldValue); - } + target.setKey(prop, value); return true; }, deleteProperty: (target, prop: keyof SettingsState) => { @@ -186,6 +175,13 @@ class StorageManager { this.data[key] = value; void this.saveToStorage([key as string]); this.notifySettingChange(key as string, value, oldValue); + if (key === "onoff" && typeof value === "boolean") { + // Reload only after this switch and any queued preferences reach storage. + // This also covers Settings opened while the extension is disabled. + void this.flushPendingPatch() + .then(() => browser.runtime.sendMessage({ type: "reloadTabs" })) + .catch((error) => console.error("[BetterSEQTA+] Failed to save master setting", error)); + } } } @@ -247,6 +243,7 @@ class StorageManager { } private async flushPendingPatch(): Promise { + if (this.saveTimeout) clearTimeout(this.saveTimeout); this.saveTimeout = null; if (this.bootstrapping || this.suppressWrites) return; diff --git a/src/seqta/utils/listeners/StorageChanges.ts b/src/seqta/utils/listeners/StorageChanges.ts index 680e9243..b8a398b5 100644 --- a/src/seqta/utils/listeners/StorageChanges.ts +++ b/src/seqta/utils/listeners/StorageChanges.ts @@ -10,7 +10,6 @@ import { applyMenuItemVisibility, scheduleMenuItemVisibility } from "@/seqta/uti import { ChangeMenuItemPositions } from "@/seqta/utils/Openers/menuOrder"; import { syncPerformanceModeEffects } from "@/seqta/utils/performanceMode"; -import browser from "webextension-polyfill"; import type { CustomShortcut } from "@/types/storage"; export class StorageChangeHandler { @@ -27,7 +26,6 @@ export class StorageChangeHandler { ); settingsState.register("selectedTheme", () => void updateAllColors()); settingsState.register("DarkMode", this.handleDarkModeChange.bind(this)); - settingsState.register("onoff", this.handleOnOffChange.bind(this)); settingsState.register("shortcuts", this.handleShortcutsChange.bind(this)); settingsState.register( "customshortcuts", @@ -72,11 +70,6 @@ export class StorageChangeHandler { void updateAllColors(); } - private handleOnOffChange(newValue: boolean) { - if (newValue) return; - browser.runtime.sendMessage({ type: "reloadTabs" }); - } - private handleCustomShortcutsChange(newValue: CustomShortcut[] | undefined) { if (!Array.isArray(newValue)) return; renderShortcuts(); From bd29ab62c6c0192129bd4237548332666364e18c Mon Sep 17 00:00:00 2001 From: SethBurkart123 Date: Tue, 6 Oct 2026 11:58:07 +1100 Subject: [PATCH 06/11] feat: keep icon sidebar rail visible during folder navigation --- src/css/injected.scss | 268 ++++++++++++++++----- src/css/injected/sidebar-animation.scss | 159 ++++-------- src/css/injected/sidebar-position.scss | 72 +++++- src/css/injected/sidebar-styles.scss | 119 ++++----- src/seqta/ui/AddBetterSEQTAElements.ts | 4 + src/seqta/ui/colors/Manager.ts | 2 +- src/seqta/ui/sidebar/sidebarDrillReturn.ts | 141 +++++++---- 7 files changed, 487 insertions(+), 278 deletions(-) diff --git a/src/css/injected.scss b/src/css/injected.scss index b78f8ca9..e537442b 100644 --- a/src/css/injected.scss +++ b/src/css/injected.scss @@ -661,92 +661,241 @@ html.bsplus-custom-title-pending #title > :not(#bsplus-title-root), height: 28px !important; } -/* Icon Only Sidebar - compact mode. When submenu is open, all styles are disabled so it behaves as normal sidebar. */ -body.icon-only-sidebar:not(:has(#menu li.hasChildren:is(.active, .bsplus-active))) { +/* Icons-only keeps the root rail visible while a full submenu opens beside it. */ +body.icon-only-sidebar { + --bsplus-icon-rail-space: 70px; + #menu { width: 70px !important; - transition: width 0.4s cubic-bezier(0.4, 0, 0.2, 1); overflow: visible !important; } #menu > ul { + position: static !important; min-width: 0 !important; - overflow-x: visible !important; + overflow-x: hidden !important; + overflow-y: auto !important; } #content { - left: 70px !important; - transition: left 0.4s cubic-bezier(0.4, 0, 0.2, 1); + left: var(--bsplus-icon-rail-space) !important; + /* Reserve the panel before its reveal so it never covers page content. */ + transition: none !important; } - #menu .sub { - left: 70px !important; - transition: left 0.4s cubic-bezier(0.4, 0, 0.2, 1); - } - - #menu li > label span, - #menu section > label span { - display: none !important; - } - - #menu ul > li > svg { - display: none !important; - } - - #menu ul li, - #menu ul section { + /* Keep root hitboxes and icons in place; only nested lists drill away. */ + #menu#menu > ul > :is(li, section) { + width: 85% !important; min-width: 0 !important; - max-width: 100% !important; + max-width: 70px !important; + margin: 8px auto !important; padding: 8px !important; justify-content: center !important; box-sizing: border-box !important; - } + pointer-events: auto !important; + transform: none !important; + animation: none !important; + transition: background-color 150ms ease !important; - #menu li > label, - #menu section > label { - flex: 0 0 auto !important; - min-width: 0 !important; - justify-content: center !important; - overflow: visible !important; - } + > label { + position: relative; + font-size: 0 !important; + flex: 0 0 auto !important; + min-width: 0 !important; + justify-content: center !important; + overflow: visible !important; + transform: none !important; - #menu li > label > svg, - #menu section > label > svg { - margin: 0 auto !important; - flex-shrink: 0 !important; - } - - /* Engage: hide text nodes in labels via font-size trick, restore SVG size */ - #menu .logo-link li > label, - #menu .logo-link section > label { - font-size: 0 !important; - justify-content: center !important; - - svg { - width: 24px !important; - height: 24px !important; - font-size: initial !important; - flex-shrink: 0 !important; - margin: 0 auto !important; + span { + display: none !important; + } + > svg { + margin: 0 auto !important; + flex-shrink: 0 !important; + } + } + > svg { + display: none !important; } } - /* Engage: hide chevron arrows on hasChildren items */ - #menu .logo-link li > svg { - display: none !important; + #menu#menu > ul > .hasChildren { + position: static !important; + backdrop-filter: none !important; + contain: none !important; + } + + #menu#menu > ul > .hasChildren:is(.active, .bsplus-active) { + /* Preserve the outer hover inset; the inner edge meets the panel. */ + width: 92.5% !important; + margin-left: 7.5% !important; + margin-right: 0 !important; + border-radius: var(--bsplus-sidebar-radius, 12px) 0 0 + var(--bsplus-sidebar-radius, 12px) !important; + background: var(--background-primary) !important; + transition: none !important; + color: var(--text-primary) !important; + } + + #menu#menu > ul > .hasChildren:is(.active, .bsplus-active) > label { + /* Compensate for the extra inner fill, keeping the icon centered on the rail. */ + transform: translateX(-2.625px) !important; + } + + /* Keep the arc fixed; bleed its paint into the opaque panel to avoid a + fractional compositor gap at the rail edge when zoomed. */ + #menu#menu > ul > .hasChildren:is(.active, .bsplus-active) > label::after { + content: ""; + position: absolute; + pointer-events: none; + width: calc(var(--bsplus-sidebar-radius, 12px) + 1px); + right: calc((100% - 70px) / 2 - 1px); + top: calc(-8px - var(--bsplus-sidebar-radius, 12px)); + bottom: calc(-8px - var(--bsplus-sidebar-radius, 12px)); + background: + radial-gradient( + circle at 0 0, + transparent calc(var(--bsplus-sidebar-radius, 12px) - 0.5px), + var(--background-primary) var(--bsplus-sidebar-radius, 12px) + ) + top / 100% var(--bsplus-sidebar-radius, 12px) no-repeat, + radial-gradient( + circle at 0 100%, + transparent calc(var(--bsplus-sidebar-radius, 12px) - 0.5px), + var(--background-primary) var(--bsplus-sidebar-radius, 12px) + ) + bottom / 100% var(--bsplus-sidebar-radius, 12px) no-repeat, + linear-gradient(var(--background-primary), var(--background-primary)) + center / 100% calc(100% - 2 * var(--bsplus-sidebar-radius, 12px)) + no-repeat; + } + + #menu > ul > .hasChildren > .sub { + left: 70px !important; + right: auto !important; + top: 71px !important; + margin-top: 0 !important; + width: min( + var(--bsplus-sidebar-width, 270px), + calc(100vw - 70px) + ) !important; + background: var(--background-primary) !important; + color: var(--text-primary) !important; + border-right: 1px solid var(--border-color, rgba(128, 128, 128, 0.3)) !important; + visibility: hidden; + opacity: 1; + transform: translateX(-100%); + /* The matching clip keeps the visible edge at the rail during the slide. */ + clip-path: inset(0 0 0 100%); + transition: + transform 0.3s ease, + clip-path 0.3s ease, + visibility 0s 0.3s; + + .nav { + background: var(--background-primary) !important; + } + :is(.nav, .back, .backLabel, li, section, label, svg) { + color: var(--text-primary) !important; + } + svg:not([fill="none"]) { + fill: currentColor !important; + } + :is(li, section):hover { + background: color-mix( + in srgb, + var(--text-primary) 8%, + transparent + ) !important; + } + :is(li, section):is(.active, .bsplus-active):not(.hasChildren) { + background: color-mix( + in srgb, + var(--text-primary) 14%, + transparent + ) !important; + &::after { + background: var(--text-primary) !important; + box-shadow: 0 0 10px + color-mix(in srgb, var(--text-primary) 45%, transparent) !important; + } + } + .sub { + left: 0 !important; + right: auto !important; + width: 100% !important; + background: var(--background-primary) !important; + color: var(--text-primary) !important; + } + } + + #menu > ul > .hasChildren:is(.active, .bsplus-active) > .sub { + visibility: visible; + opacity: 1; + transform: none; + clip-path: inset(0); + transition-delay: 0s; + } + + /* Switching root folders retires the previous panel immediately. */ + #menu:has(> ul > .hasChildren:is(.active, .bsplus-active)) + > ul + > .hasChildren:not(:is(.active, .bsplus-active)) + > .sub { + visibility: hidden; + transition-delay: 0s; + } + + /* Full panel rows retain their preset shape with equal horizontal insets. */ + #menu#menu .sub :is(li.item, section.item) { + box-sizing: border-box !important; + } + #menu#menu:not(.bsplus-sidebar-style-strip) + .sub + > ul:not(.bsplus-drill-rows) + > :is(li.item, section.item) { + margin-inline: auto !important; + } + #menu#menu.bsplus-sidebar-style-strip .sub :is(li.item, section.item) { + width: 100% !important; + margin-inline: 0 !important; + } + + #menu.bsplus-icon-rail-switching > ul > .hasChildren > .sub { + transition: none !important; + } + + #menu#menu.bsplus-sidebar-style-neon .sub li.active:not(.hasChildren) { + box-shadow: + 0 0 0 1px color-mix(in srgb, var(--text-primary) 55%, transparent), + 0 0 14px color-mix(in srgb, var(--text-primary) 40%, transparent), + inset 0 0 0 1px color-mix(in srgb, var(--text-primary) 12%, transparent) !important; + } + + #menu#menu.bsplus-sidebar-indicator-outline .sub li.active:not(.hasChildren) { + background: transparent !important; + box-shadow: + inset 0 0 0 2px color-mix(in srgb, var(--text-primary) 55%, transparent), + 0 0 0 1px color-mix(in srgb, var(--text-primary) 12%, transparent) !important; } - /* Engage: hide the name/details in #userActions */ #menu #userActions .details { display: none !important; } - /* Compact BetterSEQTA mark instead of the full wordmark. */ &.student #menu > ul::before { + width: 70px !important; background-size: 36px 36px !important; background-position: center center !important; } +} +body.icon-only-sidebar:has( + #menu > ul > .hasChildren:is(.active, .bsplus-active) + ) { + --bsplus-icon-rail-space: calc( + 70px + min(var(--bsplus-sidebar-width, 270px), calc(100vw - 70px)) + ); } [class*="notifications__items___"] { @@ -1260,15 +1409,16 @@ html.transparencyEffects transform: translatex(var(--bsplus-sidebar-width, 270px)); } - body.icon-only-sidebar:not(:has(#menu li.hasChildren:is(.active, .bsplus-active))) { + body.icon-only-sidebar { #menu { -webkit-transform: translatex(-70px); transform: translatex(-70px); } - .menuShown #content { - -webkit-transform: translatex(70px); - transform: translatex(70px); - } + #content { left: 0 !important; } + } + body.icon-only-sidebar.menuShown #content { + -webkit-transform: translatex(var(--bsplus-icon-rail-space)) !important; + transform: translatex(var(--bsplus-icon-rail-space)) !important; } } diff --git a/src/css/injected/sidebar-animation.scss b/src/css/injected/sidebar-animation.scss index 9bbd4c50..5a986625 100644 --- a/src/css/injected/sidebar-animation.scss +++ b/src/css/injected/sidebar-animation.scss @@ -1,4 +1,5 @@ -#menu ul:has(li.hasChildren:is(.active, .bsplus-active)) +#menu + ul:has(li.hasChildren:is(.active, .bsplus-active)) li.hasChildren:is(.active, .bsplus-active) { box-shadow: inset 0px 0 var(--item-colour, transparent) !important; background: transparent !important; @@ -8,77 +9,61 @@ overflow-y: scroll !important; } -#menu > ul:has(li.hasChildren:is(.active, .bsplus-active)) > li::before, -#menu > ul:has(li.hasChildren:is(.active, .bsplus-active)) > li::after, -#menu > ul ul:has(li.hasChildren:is(.active, .bsplus-active)) > li::before, -#menu > ul ul:has(li.hasChildren:is(.active, .bsplus-active)) > li::after, -#menu > ul:has(li.hasChildren:is(.active, .bsplus-active)) > li > label, -#menu > ul:has(li.hasChildren:is(.active, .bsplus-active)) > li > svg, -#menu > ul ul:has(li.hasChildren:is(.active, .bsplus-active)) > li > label, -#menu > ul ul:has(li.hasChildren:is(.active, .bsplus-active)) > li > svg { - /* !important beats theme animations (e.g. Beach palm-slide forwards). */ - transform: translateX(-320px) !important; +/* Move the complete row, including hover fill, arrow and subject stripe. + A transform on the folder itself would also move its absolute `.sub` panel. + Resting margins are measured before drilling so auto margins interpolate. */ +#menu#menu ul.bsplus-drill-rows > :is(li, section) { + margin-left: var(--bsplus-row-margin-left) !important; + transition: + margin-left 0.3s ease, + background-color 0.2s ease, + box-shadow 0.2s ease !important; animation: none !important; -} -#menu ul > li > label, -#menu ul > li > svg { - transition: transform 0.3s ease; -} - -/* Frontmost drill panel: rows move with `.sub` only — no separate enter animation. */ -#menu - li.hasChildren:is(.active, .bsplus-active):not( - :has(.sub li.hasChildren:is(.active, .bsplus-active)) - ) - > .sub - > ul - > li, -#menu - li.hasChildren:is(.active, .bsplus-active):not( - :has(.sub li.hasChildren:is(.active, .bsplus-active)) - ) - > .sub - > ul - > li > label, -#menu - li.hasChildren:is(.active, .bsplus-active):not( - :has(.sub li.hasChildren:is(.active, .bsplus-active)) - ) - > .sub - > ul - > li > svg, -#menu - li.hasChildren:is(.active, .bsplus-active):not( - :has(.sub li.hasChildren:is(.active, .bsplus-active)) - ) - > .sub - > ul - > li::before, -#menu - li.hasChildren:is(.active, .bsplus-active):not( - :has(.sub li.hasChildren:is(.active, .bsplus-active)) - ) - > .sub - > ul - > li::after { - animation: none !important; - transition: none !important; - transform: none !important; + &::before, + &::after { + transform: none !important; + animation: none !important; + } +} + +#menu#menu + ul.bsplus-drill-rows:has(> .hasChildren:is(.active, .bsplus-active)) + > :is(li, section) { + margin-left: calc( + var(--bsplus-row-margin-left) + var(--bsplus-slide-off, -320px) + ) !important; +} + +/* Incoming rows travel only with their native panel. */ +#menu .sub > ul:not(.bsplus-drill-rows) > li { + &, + > label, + > svg, + &::before, + &::after { + animation: none !important; + transform: none !important; + } } #menu .sub { - transition: transform 0.3s ease, left 0.4s cubic-bezier(0.4, 0, 0.2, 1); + transition: + transform 0.3s ease, + left 0.4s cubic-bezier(0.4, 0, 0.2, 1); } -#menu .sub ul:has(> li.hasChildren:is(.active, .bsplus-active)) +#menu + .sub + ul:has(> li.hasChildren:is(.active, .bsplus-active)) > li:not(:is(.active, .bsplus-active)) { pointer-events: none !important; } -#menu > ul:has(li.hasChildren:is(.active, .bsplus-active)) +#menu + > ul:has(li.hasChildren:is(.active, .bsplus-active)) > li:is(.active, .bsplus-active) { background: transparent !important; } @@ -99,59 +84,3 @@ #menu { --bsplus-slide-off: -320px; } - -/* Reverse slide when drilling back — label/svg motion is driven inline in JS - so text stays off-screen until `.active` clears. Pseudo-elements use CSS. */ -#menu.bsplus-sidebar-returning ul.bsplus-drill-return-target > li::before, -#menu.bsplus-sidebar-returning ul.bsplus-drill-return-target > li::after { - animation: bsplus-sidebar-return 0.3s cubic-bezier(0.4, 0, 0.2, 1) both !important; - transition: none !important; -} - -@keyframes bsplus-sidebar-return { - from { - transform: translateX(var(--bsplus-slide-off, -320px)); - } - to { - transform: translateX(0); - } -} - -/* Icon-only collapsed: submenu slides over narrow icons. */ -body.icon-only-sidebar:not(:has(#menu li.hasChildren:is(.active, .bsplus-active))) - #menu - > ul:has(li.hasChildren:is(.active, .bsplus-active)) - > li::before, -body.icon-only-sidebar:not(:has(#menu li.hasChildren:is(.active, .bsplus-active))) - #menu - > ul - ul:has(li.hasChildren:is(.active, .bsplus-active)) - > li::before, -body.icon-only-sidebar:not(:has(#menu li.hasChildren:is(.active, .bsplus-active))) - #menu - > ul:has(li.hasChildren:is(.active, .bsplus-active)) - > li - > label, -body.icon-only-sidebar:not(:has(#menu li.hasChildren:is(.active, .bsplus-active))) - #menu - > ul:has(li.hasChildren:is(.active, .bsplus-active)) - > li - > svg, -body.icon-only-sidebar:not(:has(#menu li.hasChildren:is(.active, .bsplus-active))) - #menu - > ul - ul:has(li.hasChildren:is(.active, .bsplus-active)) - > li - > label, -body.icon-only-sidebar:not(:has(#menu li.hasChildren:is(.active, .bsplus-active))) - #menu - > ul - ul:has(li.hasChildren:is(.active, .bsplus-active)) - > li - > svg { - transform: translateX(-70px); -} - -body.icon-only-sidebar #menu { - --bsplus-slide-off: -70px; -} diff --git a/src/css/injected/sidebar-position.scss b/src/css/injected/sidebar-position.scss index 5b385ccd..0471d9f8 100644 --- a/src/css/injected/sidebar-position.scss +++ b/src/css/injected/sidebar-position.scss @@ -33,13 +33,14 @@ body.bsplus-sidebar-right { max-width: none !important; } - &.icon-only-sidebar:not(:has(#menu li.hasChildren:is(.active, .bsplus-active))) { + &.icon-only-sidebar { #menu { width: 70px !important; } #content { - right: 70px !important; + right: var(--bsplus-icon-rail-space) !important; + transition: none !important; } #menu .sub { @@ -71,7 +72,11 @@ body.bsplus-sidebar-right { } } - #menu li:is(.active, .hasChildren.bsplus-active) > .sub > ul > .item:not(.hasChildren)::before { + #menu + li:is(.active, .hasChildren.bsplus-active) + > .sub + > ul + > .item:not(.hasChildren)::before { left: auto !important; right: 0 !important; border-radius: 0 8px 8px 0 !important; @@ -96,16 +101,21 @@ body.bsplus-sidebar-right { } &.menuShown #content { - transform: translateX(calc(-1 * var(--bsplus-sidebar-width, 270px))) !important; + transform: translateX( + calc(-1 * var(--bsplus-sidebar-width, 270px)) + ) !important; } - &.icon-only-sidebar:not(:has(#menu li.hasChildren:is(.active, .bsplus-active))) { + &.icon-only-sidebar { #menu { transform: translateX(70px) !important; } &.menuShown #content { - transform: translateX(-70px) !important; + right: 0 !important; + transform: translateX( + calc(-1 * var(--bsplus-icon-rail-space)) + ) !important; } } @@ -127,7 +137,55 @@ body.bsplus-sidebar-right { } &.icon-only-sidebar.menuShown #container #content #title { - transform: translateX(70px) !important; + transform: translateX(var(--bsplus-icon-rail-space)) !important; } } } + +body.icon-only-sidebar.bsplus-sidebar-right { + #menu#menu > ul > .hasChildren:is(.active, .bsplus-active) { + margin-left: 0 !important; + margin-right: 7.5% !important; + border-radius: 0 var(--bsplus-sidebar-radius, 12px) + var(--bsplus-sidebar-radius, 12px) 0 !important; + > label { + transform: translateX(2.625px) !important; + } + } + #menu#menu > ul > .hasChildren:is(.active, .bsplus-active) > label::after { + right: auto; + left: calc((100% - 70px) / 2 - 1px); + background: + radial-gradient( + circle at 100% 0, + transparent calc(var(--bsplus-sidebar-radius, 12px) - 0.5px), + var(--background-primary) var(--bsplus-sidebar-radius, 12px) + ) + top / 100% var(--bsplus-sidebar-radius, 12px) no-repeat, + radial-gradient( + circle at 100% 100%, + transparent calc(var(--bsplus-sidebar-radius, 12px) - 0.5px), + var(--background-primary) var(--bsplus-sidebar-radius, 12px) + ) + bottom / 100% var(--bsplus-sidebar-radius, 12px) no-repeat, + linear-gradient(var(--background-primary), var(--background-primary)) + center / 100% calc(100% - 2 * var(--bsplus-sidebar-radius, 12px)) + no-repeat; + } + #menu > ul > .hasChildren > .sub { + left: auto !important; + right: 70px !important; + border-right: none !important; + border-left: 1px solid var(--border-color, rgba(128, 128, 128, 0.3)) !important; + transform: translateX(100%); + clip-path: inset(0 100% 0 0); + } + #menu > ul > .hasChildren:is(.active, .bsplus-active) > .sub { + transform: none; + clip-path: inset(0); + } + #menu > ul > .hasChildren > .sub .sub { + left: 0 !important; + right: auto !important; + } +} diff --git a/src/css/injected/sidebar-styles.scss b/src/css/injected/sidebar-styles.scss index 729959c6..ead1d63c 100644 --- a/src/css/injected/sidebar-styles.scss +++ b/src/css/injected/sidebar-styles.scss @@ -92,20 +92,22 @@ $sidebar-motion: 0.4s cubic-bezier(0.4, 0, 0.2, 1); &.bsplus-sidebar-style-glass { /* Never put backdrop-filter on an open folder — it becomes a clip containing-block and hides `.sub` labels on Chromium/Edge. */ - #{$item}:not(:has(> .sub)) { - margin: 0 8px 8px !important; - background: rgba(255, 255, 255, 0.1) !important; - backdrop-filter: blur(10px); - -webkit-backdrop-filter: blur(10px); - box-shadow: inset 0 0 0 1px rgba(255, 255, 255, 0.14); - } - #{$item}:has(> .sub) { - background: transparent !important; - backdrop-filter: none !important; - -webkit-backdrop-filter: none !important; - box-shadow: none !important; - overflow: visible !important; - contain: none !important; + #{$item} { + &:not(:has(> .sub)) { + margin: 0 8px 8px !important; + background: rgba(255, 255, 255, 0.1) !important; + backdrop-filter: blur(10px); + -webkit-backdrop-filter: blur(10px); + box-shadow: inset 0 0 0 1px rgba(255, 255, 255, 0.14); + } + &:has(> .sub) { + background: transparent !important; + backdrop-filter: none !important; + -webkit-backdrop-filter: none !important; + box-shadow: none !important; + overflow: visible !important; + contain: none !important; + } } #{$active} { background: rgba(255, 255, 255, 0.2) !important; @@ -145,16 +147,17 @@ $sidebar-motion: 0.4s cubic-bezier(0.4, 0, 0.2, 1); } } - &.bsplus-sidebar-style-neon #{$active} { - background: rgba(255, 255, 255, 0.1) !important; - box-shadow: - 0 0 0 1px rgba(255, 255, 255, 0.55), - 0 0 14px rgba(255, 255, 255, 0.4), - 0 0 28px rgba(255, 255, 255, 0.22) !important; - } - - &.bsplus-sidebar-style-neon #{$item} { - margin: 0 8px 8px !important; + &.bsplus-sidebar-style-neon { + #{$active} { + background: rgba(255, 255, 255, 0.1) !important; + box-shadow: + 0 0 0 1px rgba(255, 255, 255, 0.55), + 0 0 14px rgba(255, 255, 255, 0.4), + 0 0 28px rgba(255, 255, 255, 0.22) !important; + } + #{$item} { + margin: 0 8px 8px !important; + } } /* —— Density (comfortable = no class / no overrides) —— */ @@ -206,42 +209,48 @@ $sidebar-motion: 0.4s cubic-bezier(0.4, 0, 0.2, 1); } /* —— Active indicator (fill = default, no class) —— */ - &.bsplus-sidebar-indicator-bar:not(.bsplus-sidebar-style-strip) #{$active} { - position: relative !important; - background: rgba(255, 255, 255, 0.1) !important; - box-shadow: none !important; - &::after { - @include accent-bar(0.45); + &.bsplus-sidebar-indicator-bar:not(.bsplus-sidebar-style-strip) { + #{$active} { + position: relative !important; + background: rgba(255, 255, 255, 0.1) !important; + box-shadow: none !important; + &::after { + @include accent-bar(0.45); + } } } - &.bsplus-sidebar-indicator-outline #{$active} { - background: transparent !important; - box-shadow: - inset 0 0 0 2px rgba(255, 255, 255, 0.55), - 0 0 0 1px rgba(255, 255, 255, 0.12) !important; + &.bsplus-sidebar-indicator-outline { + #{$active} { + background: transparent !important; + box-shadow: + inset 0 0 0 2px rgba(255, 255, 255, 0.55), + 0 0 0 1px rgba(255, 255, 255, 0.12) !important; + } } - &.bsplus-sidebar-indicator-underline:not(.bsplus-sidebar-style-strip) #{$active} { - position: relative !important; - background: transparent !important; - box-shadow: none !important; - &::after { - content: "" !important; - position: absolute !important; - left: 14px !important; - right: 14px !important; - bottom: 6px !important; - top: auto !important; - width: auto !important; - height: 3px !important; - border-radius: 999px !important; - background: #fff !important; - box-shadow: 0 0 8px rgba(255, 255, 255, 0.4) !important; - pointer-events: none !important; - z-index: 3 !important; - opacity: 1 !important; - display: block !important; + &.bsplus-sidebar-indicator-underline:not(.bsplus-sidebar-style-strip) { + #{$active} { + position: relative !important; + background: transparent !important; + box-shadow: none !important; + &::after { + content: "" !important; + position: absolute !important; + left: 14px !important; + right: 14px !important; + bottom: 6px !important; + top: auto !important; + width: auto !important; + height: 3px !important; + border-radius: 999px !important; + background: #fff !important; + box-shadow: 0 0 8px rgba(255, 255, 255, 0.4) !important; + pointer-events: none !important; + z-index: 3 !important; + opacity: 1 !important; + display: block !important; + } } } } diff --git a/src/seqta/ui/AddBetterSEQTAElements.ts b/src/seqta/ui/AddBetterSEQTAElements.ts index a71b51a0..5892138c 100644 --- a/src/seqta/ui/AddBetterSEQTAElements.ts +++ b/src/seqta/ui/AddBetterSEQTAElements.ts @@ -750,6 +750,10 @@ function updateSidebarAccessibility() { const visibleEntries = new Set( visibleList ? getDirectSidebarEntries(visibleList) : [], ); + if (document.body?.classList.contains("icon-only-sidebar")) { + const rootList = menu.querySelector(":scope > ul") as HTMLElement | null; + if (rootList) getDirectSidebarEntries(rootList).forEach((entry) => visibleEntries.add(entry)); + } const drillFolders = getDrillFolderChain(menu, visibleList); const menuEntries = menu.querySelectorAll("li.item, section.item, li, section"); diff --git a/src/seqta/ui/colors/Manager.ts b/src/seqta/ui/colors/Manager.ts index a0ba56b9..7fa8d155 100644 --- a/src/seqta/ui/colors/Manager.ts +++ b/src/seqta/ui/colors/Manager.ts @@ -104,7 +104,7 @@ function applyBetterseqtaLogoBackground(isDark: boolean) { background-image: url("${fullUrl}") !important; } /* Icon-only sidebar: wordmark → compact mark (theme-aware). */ - body.student.icon-only-sidebar:not(:has(#menu li.hasChildren:is(.active, .bsplus-active))) #menu > ul::before { + body.student.icon-only-sidebar #menu > ul::before { background-image: url("${iconUrl}") !important; } `; diff --git a/src/seqta/ui/sidebar/sidebarDrillReturn.ts b/src/seqta/ui/sidebar/sidebarDrillReturn.ts index aa2bc573..71dcaced 100644 --- a/src/seqta/ui/sidebar/sidebarDrillReturn.ts +++ b/src/seqta/ui/sidebar/sidebarDrillReturn.ts @@ -1,7 +1,7 @@ const MENU_RETURN_CLASS = "bsplus-sidebar-returning"; const LIST_RETURN_CLASS = "bsplus-drill-return-target"; const RETURN_MS = 300; -const RETURN_EASE = "cubic-bezier(0.4, 0, 0.2, 1)"; +const ROWS_CLASS = "bsplus-drill-rows"; /** Count open folder levels (0 = root list only). */ export function getSidebarDrillDepth( @@ -19,7 +19,9 @@ export function getSidebarDrillDepth( if (!activeFolder) break; depth += 1; - list = activeFolder.querySelector(":scope > .sub > ul") as HTMLElement | null; + list = activeFolder.querySelector( + ":scope > .sub > ul", + ) as HTMLElement | null; } return depth; @@ -42,37 +44,74 @@ function getSidebarListAtDepth( ":scope > li.hasChildren.active, :scope > section.hasChildren.active", ) as HTMLElement | null; if (!activeFolder) return list; - list = activeFolder.querySelector(":scope > .sub > ul") as HTMLElement | null; + list = activeFolder.querySelector( + ":scope > .sub > ul", + ) as HTMLElement | null; depth += 1; } return list; } -function getSlideOff(menu: HTMLElement): string { - const value = getComputedStyle(menu).getPropertyValue("--bsplus-slide-off").trim(); - return value || "-320px"; -} - function getReturnSlideNodes(list: HTMLElement): HTMLElement[] { return [ - ...list.querySelectorAll( - ":scope > li > label, :scope > li > svg, :scope > section > label, :scope > section > svg", - ), + ...list.querySelectorAll(":scope > li, :scope > section"), ]; } -function clearInlineReturnStyles(nodes: Iterable) { +function prepareRowSlide(list: HTMLElement) { + // The icons-only root rail remains visible next to the open panel. + if ( + document.body?.classList.contains("icon-only-sidebar") && + list.parentElement?.id === "menu" + ) + return; + if (list.classList.contains(ROWS_CLASS)) return; + const nodes = getReturnSlideNodes(list); + // Read all auto/preset margins before changing any row's layout. + const margins = nodes.map((node) => getComputedStyle(node).marginLeft); + nodes.forEach((node, index) => { + node.style.setProperty("--bsplus-row-margin-left", margins[index]); + node.style.setProperty("margin-left", margins[index], "important"); + }); + list.classList.add(ROWS_CLASS); + // Establish a concrete start before native state changes (or an observer + // prepares a programmatically opened folder after its class changed). + void list.offsetWidth; + nodes.forEach((node) => node.style.removeProperty("margin-left")); +} + +function clearRowSlide(nodes: Iterable) { for (const node of nodes) { - node.style.removeProperty("transition"); - node.style.removeProperty("transform"); + node.style.removeProperty("margin-left"); + node.style.removeProperty("--bsplus-row-margin-left"); + node.parentElement?.classList.remove(ROWS_CLASS); } } let returnTimer: ReturnType | null = null; -let lastAnimatedNodes: HTMLElement[] = []; let lastDrillDepth = 0; let menuObserver: MutationObserver | null = null; +let lastRootFolder: Element | null = null; +let swapFrame: number | null = null; + +function rootFolder(menu: HTMLElement) { + return menu.querySelector( + ":scope > ul > .hasChildren:is(.active, .bsplus-active)", + ); +} + +function swapRootPanel(menu: HTMLElement) { + if (!document.body?.classList.contains("icon-only-sidebar")) return; + if (swapFrame !== null) cancelAnimationFrame(swapFrame); + menu.classList.add("bsplus-icon-rail-switching"); + swapFrame = requestAnimationFrame(() => { + swapFrame = requestAnimationFrame(() => { + swapFrame = null; + menu.classList.remove("bsplus-icon-rail-switching"); + }); + }); +} let backCaptureAttached = false; function clearReturnClasses(menu: HTMLElement) { @@ -97,39 +136,24 @@ export function runSidebarDrillReturn( if (returnTimer) clearTimeout(returnTimer); clearReturnClasses(menu); - clearInlineReturnStyles(lastAnimatedNodes); - lastAnimatedNodes = nodes; - - const slideOff = getSlideOff(menu); - - // Hold the off-screen transform before SEQTA clears `.active` and drops `:has()`. - for (const node of nodes) { - node.style.transition = "none"; - node.style.transform = `translateX(${slideOff})`; - } + prepareRowSlide(list); menu.classList.add(MENU_RETURN_CLASS); list.classList.add(LIST_RETURN_CLASS); lastDrillDepth = depth; - requestAnimationFrame(() => { - requestAnimationFrame(() => { - for (const node of nodes) { - node.style.transition = `transform ${RETURN_MS}ms ${RETURN_EASE}`; - node.style.transform = "translateX(0)"; - } - }); - }); - returnTimer = setTimeout(() => { returnTimer = null; clearReturnClasses(menu); - clearInlineReturnStyles(nodes); - lastAnimatedNodes = []; + clearRowSlide(nodes); }, RETURN_MS + 50); } function onDrillDepthChange(menu: HTMLElement) { + const currentRoot = rootFolder(menu); + if (lastRootFolder && currentRoot && lastRootFolder !== currentRoot) + swapRootPanel(menu); + lastRootFolder = currentRoot; if (menu.classList.contains(MENU_RETURN_CLASS)) return; const depth = getSidebarDrillDepth(menu); @@ -137,16 +161,39 @@ function onDrillDepthChange(menu: HTMLElement) { runSidebarDrillReturn(menu, depth); return; } + if (depth > lastDrillDepth) { + const outgoing = getSidebarListAtDepth(menu, lastDrillDepth); + if (outgoing) prepareRowSlide(outgoing); + } lastDrillDepth = depth; } function onMenuClickCapture(event: MouseEvent) { const menu = document.getElementById("menu"); - if (!menu || menu.classList.contains(MENU_RETURN_CLASS)) return; + if (!menu) return; const target = event.target; if (!(target instanceof Element)) return; - if (!target.closest(".sub .back")) return; + if (!target.closest(".sub .back")) { + const folder = target.closest("li.hasChildren, section.hasChildren"); + if ( + folder && + !folder.classList.contains("active") && + folder.parentElement + ) { + if ( + folder.parentElement.parentElement === menu && + rootFolder(menu) && + rootFolder(menu) !== folder + ) + swapRootPanel(menu); + if (returnTimer) clearTimeout(returnTimer); + returnTimer = null; + clearReturnClasses(menu); + prepareRowSlide(folder.parentElement); + } + return; + } const depthBefore = getSidebarDrillDepth(menu); if (depthBefore > 0) { @@ -154,13 +201,18 @@ function onMenuClickCapture(event: MouseEvent) { } } -/** Drive the reverse slide when folder `.active` is cleared. */ +/** Keep row motion together when native folder state changes. */ export function installSidebarDrillReturn( menu: HTMLElement | null = document.getElementById("menu"), ) { if (!menu || menuObserver) return; lastDrillDepth = getSidebarDrillDepth(menu); + lastRootFolder = rootFolder(menu); + for (let depth = 0; depth < lastDrillDepth; depth++) { + const list = getSidebarListAtDepth(menu, depth); + if (list) prepareRowSlide(list); + } menuObserver = new MutationObserver(() => { onDrillDepthChange(menu); @@ -183,12 +235,19 @@ export function uninstallSidebarDrillReturn() { if (returnTimer) clearTimeout(returnTimer); returnTimer = null; lastDrillDepth = 0; + lastRootFolder = null; + if (swapFrame !== null) cancelAnimationFrame(swapFrame); + swapFrame = null; const menu = document.getElementById("menu"); if (menu) { + menu.classList.remove("bsplus-icon-rail-switching"); clearReturnClasses(menu); - clearInlineReturnStyles(lastAnimatedNodes); - lastAnimatedNodes = []; + clearRowSlide( + menu.querySelectorAll( + `ul.${ROWS_CLASS} > li, ul.${ROWS_CLASS} > section`, + ), + ); if (backCaptureAttached) { menu.removeEventListener("click", onMenuClickCapture, true); backCaptureAttached = false; From 776c1e98d994e0252197ecf6a493b45e4870330d Mon Sep 17 00:00:00 2001 From: SethBurkart123 Date: Tue, 6 Oct 2026 11:58:07 +1100 Subject: [PATCH 07/11] feat: add compact expandable settings popup --- .../components/SidebarAppearance.svelte | 83 ++++++- src/interface/components/Switch.svelte | 56 ++--- .../components/TabbedContainer.svelte | 58 ++--- .../components/store/CloudHeader.svelte | 5 +- src/interface/components/store/Header.svelte | 9 + src/interface/pages/settings.svelte | 229 ++++++++++++++++-- .../settings/PluginSettingsBlocks.svelte | 12 +- .../pages/settings/SettingRow.svelte | 8 +- .../pages/settings/sections/account.svelte | 8 +- .../pages/settings/sections/advanced.svelte | 71 +++--- .../pages/settings/sections/appearance.svelte | 18 +- .../settings/sections/generalOptions.svelte | 34 ++- src/seqta/utils/defaultSettings.ts | 1 + src/seqta/utils/settingsPopupAnimation.ts | 93 ++++--- src/types/storage.ts | 2 + 15 files changed, 478 insertions(+), 209 deletions(-) diff --git a/src/interface/components/SidebarAppearance.svelte b/src/interface/components/SidebarAppearance.svelte index 7cc1d0e0..f509d57d 100644 --- a/src/interface/components/SidebarAppearance.svelte +++ b/src/interface/components/SidebarAppearance.svelte @@ -55,6 +55,7 @@ } +