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);