mirror of
https://github.com/BetterSEQTA/BetterSEQTA-Plus.git
synced 2026-12-06 19:56:45 +10:30
fix: address release regressions in startup, analytics and sync
This commit is contained in:
1 parent
eb2bdbec2f
commit
4d9b17df37
28 files changed
+989
-136
No files matched your search
@@ -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 = '<div class="message">Page not found</div>';
|
||||||
|
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");
|
||||||
|
},
|
||||||
|
);
|
||||||
+12
-12
@@ -178,24 +178,24 @@ async function bootErrorPage() {
|
|||||||
}
|
}
|
||||||
document.removeEventListener("readystatechange", watchTitle);
|
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 {
|
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();
|
mountErrorPageKitten();
|
||||||
document.getElementById("bsplus-404-flash-hide")?.remove();
|
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
document.getElementById("bsplus-404-flash-hide")?.remove();
|
|
||||||
document
|
document
|
||||||
.querySelectorAll(".bsplus-kitten-404-hidden")
|
.querySelectorAll(".bsplus-kitten-404-hidden")
|
||||||
.forEach((el) => el.classList.remove("bsplus-kitten-404-hidden"));
|
.forEach((el) => el.classList.remove("bsplus-kitten-404-hidden"));
|
||||||
console.error("[BetterSEQTA+] Failed to boot 404 page:", error);
|
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(
|
console.error(
|
||||||
"[BetterSEQTA+] Dev module graph is still stale after recovery. Restart `npm run dev`, then reload this page.",
|
"[BetterSEQTA+] Dev module graph is still stale after recovery. Restart `npm run dev`, then reload this page.",
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
@@ -3,6 +3,16 @@ import { buildThemeBuilderCss } from "./themeBuilderDraft";
|
|||||||
import { getFontPreset } from "@/seqta/ui/fonts/presets";
|
import { getFontPreset } from "@/seqta/ui/fonts/presets";
|
||||||
|
|
||||||
describe("buildSimpleTheme", () => {
|
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", () => {
|
it("builds CSS with font import and image variables", () => {
|
||||||
const css = buildThemeBuilderCss(
|
const css = buildThemeBuilderCss(
|
||||||
getFontPreset("inter"),
|
getFontPreset("inter"),
|
||||||
|
|||||||
@@ -30,7 +30,7 @@ export function buildThemeBuilderCss(
|
|||||||
imageVariables: string[],
|
imageVariables: string[],
|
||||||
draft: Pick<
|
draft: Pick<
|
||||||
ThemeBuilderDraft,
|
ThemeBuilderDraft,
|
||||||
"accentColor" | "gradientEnd" | "gradientAngle" | "backgroundBlurPx" | "overlayOpacity"
|
"accentColor" | "gradientEnd" | "gradientAngle" | "backgroundBlurPx" | "overlayOpacity" | "customCssExtra"
|
||||||
>,
|
>,
|
||||||
): string {
|
): string {
|
||||||
const importLine = font.googleUrl ? `@import url("${font.googleUrl}");\n` : "";
|
const importLine = font.googleUrl ? `@import url("${font.googleUrl}");\n` : "";
|
||||||
@@ -77,9 +77,8 @@ export function buildThemeBuilderCss(
|
|||||||
background-attachment: fixed !important;
|
background-attachment: fixed !important;
|
||||||
}`);
|
}`);
|
||||||
} else {
|
} else {
|
||||||
const bgLayers: string[] = [];
|
const bgLayers: string[] = [gradientLayer];
|
||||||
if (imageLayer) bgLayers.push(imageLayer);
|
if (imageLayer) bgLayers.push(imageLayer);
|
||||||
bgLayers.push(gradientLayer);
|
|
||||||
rules.push(`#container {
|
rules.push(`#container {
|
||||||
background-image: ${bgLayers.join(", ")} !important;
|
background-image: ${bgLayers.join(", ")} !important;
|
||||||
background-size: cover !important;
|
background-size: cover !important;
|
||||||
|
|||||||
@@ -21,7 +21,7 @@
|
|||||||
let saving = $state(false);
|
let saving = $state(false);
|
||||||
|
|
||||||
$effect(() => {
|
$effect(() => {
|
||||||
draft = structuredClone(settings);
|
draft = $state.snapshot(settings);
|
||||||
});
|
});
|
||||||
|
|
||||||
function updateDraft(patch: Partial<AnalyticsGradeInferenceSettings>) {
|
function updateDraft(patch: Partial<AnalyticsGradeInferenceSettings>) {
|
||||||
|
|||||||
@@ -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();
|
||||||
|
});
|
||||||
@@ -335,7 +335,11 @@ function mergeRawAssessments(
|
|||||||
const letterGrade = extractLetterGrade(raw);
|
const letterGrade = extractLetterGrade(raw);
|
||||||
|
|
||||||
const existingItem = existingMap.get(id);
|
const existingItem = existingMap.get(id);
|
||||||
if (existingItem?.finalGrade !== undefined && finalGrade === undefined) {
|
if (
|
||||||
|
existingItem?.finalGrade !== undefined &&
|
||||||
|
finalGrade === undefined &&
|
||||||
|
(!existingItem.gradeSource || existingItem.gradeSource === "seqta")
|
||||||
|
) {
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -100,4 +100,17 @@ describe("resolveGradeFromAssessmentPayload", () => {
|
|||||||
expect(resolved.finalGrade).toBe(72);
|
expect(resolved.finalGrade).toBe(72);
|
||||||
expect(resolved.source).toBe("customBand");
|
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" });
|
||||||
|
});
|
||||||
});
|
});
|
||||||
@@ -37,7 +37,7 @@ function parseGradeString(value: unknown): string | undefined {
|
|||||||
return s || undefined;
|
return s || undefined;
|
||||||
}
|
}
|
||||||
|
|
||||||
function percentFromGradeLabel(
|
function customPercentFromGradeLabel(
|
||||||
label: string | undefined,
|
label: string | undefined,
|
||||||
settings: AnalyticsGradeInferenceSettings,
|
settings: AnalyticsGradeInferenceSettings,
|
||||||
): number | undefined {
|
): number | undefined {
|
||||||
@@ -50,8 +50,6 @@ function percentFromGradeLabel(
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
const approx = approximatePercentFromLetterGrade(label);
|
|
||||||
if (approx !== undefined) return approx;
|
|
||||||
return undefined;
|
return undefined;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -78,7 +76,9 @@ export function rollupPercentFromCriteria(
|
|||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
const letter = parseGradeString(row.results?.grade);
|
const letter = parseGradeString(row.results?.grade);
|
||||||
const mapped = percentFromGradeLabel(letter, settings);
|
const mapped =
|
||||||
|
customPercentFromGradeLabel(letter, settings) ??
|
||||||
|
approximatePercentFromLetterGrade(letter);
|
||||||
if (mapped !== undefined) {
|
if (mapped !== undefined) {
|
||||||
parts.push({ percent: mapped, weight: criterionWeight(row) });
|
parts.push({ percent: mapped, weight: criterionWeight(row) });
|
||||||
}
|
}
|
||||||
@@ -155,7 +155,7 @@ export function resolveGradeFromAssessmentPayload(
|
|||||||
const letter = extractLetterFromPayload(assessment);
|
const letter = extractLetterFromPayload(assessment);
|
||||||
if (letter) {
|
if (letter) {
|
||||||
const custom = settings.useCustomGradeBands
|
const custom = settings.useCustomGradeBands
|
||||||
? percentFromGradeLabel(letter, settings)
|
? customPercentFromGradeLabel(letter, settings)
|
||||||
: undefined;
|
: undefined;
|
||||||
const finalGrade =
|
const finalGrade =
|
||||||
custom ?? approximatePercentFromLetterGrade(letter);
|
custom ?? approximatePercentFromLetterGrade(letter);
|
||||||
|
|||||||
@@ -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<string, unknown>();
|
||||||
|
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",
|
||||||
|
});
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -195,7 +195,7 @@ export class ThemeManager {
|
|||||||
|
|
||||||
/**
|
/**
|
||||||
* After cloud restore, IndexedDB/theme storage is only reachable from page context (not MV3 SW).
|
* 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
|
* 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.
|
* 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];
|
const pending = snap[BSPLUS_PENDING_THEME_ENSURE_AFTER_CLOUD_KEY];
|
||||||
if (pending === undefined) return;
|
if (pending === undefined) return;
|
||||||
|
|
||||||
await browser.storage.local.remove(BSPLUS_PENDING_THEME_ENSURE_AFTER_CLOUD_KEY);
|
const id = typeof pending === "string" ? pending.trim() : "";
|
||||||
|
if (!id) {
|
||||||
if (typeof pending !== "string") return;
|
await browser.storage.local.remove(BSPLUS_PENDING_THEME_ENSURE_AFTER_CLOUD_KEY);
|
||||||
const id = pending.trim();
|
return;
|
||||||
if (!id) return;
|
}
|
||||||
|
|
||||||
const existing = (await localforage.getItem(id)) as CustomTheme | null;
|
const existing = (await localforage.getItem(id)) as CustomTheme | null;
|
||||||
if (existing) return;
|
if (!existing) {
|
||||||
|
try {
|
||||||
await this.downloadAndInstallStoreTheme({ id, name: id });
|
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) {
|
} catch (e) {
|
||||||
console.warn("[ThemeManager] prepareThemeAfterCloudSync:", e);
|
console.warn("[ThemeManager] prepareThemeAfterCloudSync:", e);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -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<void>((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<void>((resolve) => {
|
||||||
|
release = resolve;
|
||||||
|
});
|
||||||
|
const entered = new Promise<void>((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<void>((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<void>((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");
|
||||||
|
});
|
||||||
+45
-25
@@ -57,6 +57,8 @@ export class PluginManager {
|
|||||||
private static instance: PluginManager;
|
private static instance: PluginManager;
|
||||||
private plugins: Map<string, Plugin<any, any>> = new Map();
|
private plugins: Map<string, Plugin<any, any>> = new Map();
|
||||||
private runningPlugins: Map<string, boolean> = new Map();
|
private runningPlugins: Map<string, boolean> = new Map();
|
||||||
|
private startingPlugins: Map<string, Promise<void>> = new Map();
|
||||||
|
private pendingStops: Map<string, symbol> = new Map();
|
||||||
private eventBacklog: Map<string, any[]> = new Map();
|
private eventBacklog: Map<string, any[]> = new Map();
|
||||||
private cleanupFunctions: Map<string, () => void> = new Map();
|
private cleanupFunctions: Map<string, () => void> = new Map();
|
||||||
private apiDisposers: Map<string, () => void> = new Map();
|
private apiDisposers: Map<string, () => 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.
|
* @throws {Error} If the plugin is not found, or if an error occurs during plugin initialization or execution.
|
||||||
*/
|
*/
|
||||||
public async startPlugin(pluginId: string): Promise<void> {
|
public async startPlugin(pluginId: string): Promise<void> {
|
||||||
|
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<void> {
|
||||||
const plugin = this.plugins.get(pluginId);
|
const plugin = this.plugins.get(pluginId);
|
||||||
if (!plugin) {
|
if (!plugin) {
|
||||||
throw new Error(`Plugin "${pluginId}" not found`);
|
throw new Error(`Plugin "${pluginId}" not found`);
|
||||||
@@ -175,31 +193,6 @@ export class PluginManager {
|
|||||||
const api = createPluginAPI(plugin);
|
const api = createPluginAPI(plugin);
|
||||||
this.apiDisposers.set(pluginId, api.dispose);
|
this.apiDisposers.set(pluginId, api.dispose);
|
||||||
|
|
||||||
// Check if plugin is enabled before starting
|
|
||||||
if (plugin.disableToggle) {
|
|
||||||
const all = settingsState.getAll() as unknown as Record<string, unknown>;
|
|
||||||
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
|
// Inject plugin styles if provided
|
||||||
if (plugin.styles) {
|
if (plugin.styles) {
|
||||||
const styleElement = document.createElement("style");
|
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
|
// Wait for both settings and storage to be loaded before starting the plugin
|
||||||
await Promise.all([(api.settings as any).loaded, api.storage.loaded]);
|
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);
|
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") {
|
if (typeof result === "function") {
|
||||||
this.cleanupFunctions.set(plugin.id, result);
|
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<string, unknown>;
|
||||||
|
const stored = all[`plugin.${plugin.id}.settings`] as PluginSettingsStorage | undefined;
|
||||||
|
return stored?.enabled ?? plugin.defaultEnabled ?? true;
|
||||||
|
}
|
||||||
|
|
||||||
private removePluginStyles(pluginId: string): void {
|
private removePluginStyles(pluginId: string): void {
|
||||||
const styleElement = this.styleElements.get(pluginId);
|
const styleElement = this.styleElements.get(pluginId);
|
||||||
if (styleElement) {
|
if (styleElement) {
|
||||||
@@ -294,6 +309,11 @@ export class PluginManager {
|
|||||||
* @returns {Promise<void>} A promise that resolves when the plugin has been stopped.
|
* @returns {Promise<void>} A promise that resolves when the plugin has been stopped.
|
||||||
*/
|
*/
|
||||||
public async stopPlugin(pluginId: string): Promise<void> {
|
public async stopPlugin(pluginId: string): Promise<void> {
|
||||||
|
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.removePluginStyles(pluginId);
|
||||||
this.disposePluginAPI(pluginId);
|
this.disposePluginAPI(pluginId);
|
||||||
|
|
||||||
|
|||||||
@@ -111,7 +111,7 @@ export function parseNativeMenu(menu: HTMLElement): SidebarItem[] {
|
|||||||
|
|
||||||
return [...list.children]
|
return [...list.children]
|
||||||
.filter((node): node is HTMLElement => node instanceof HTMLElement)
|
.filter((node): node is HTMLElement => node instanceof HTMLElement)
|
||||||
.map(parseEntry)
|
.map((entry) => parseEntry(entry))
|
||||||
.filter((item): item is SidebarItem => item != null);
|
.filter((item): item is SidebarItem => item != null);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -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);
|
||||||
|
});
|
||||||
@@ -127,7 +127,7 @@ export function applySidebarStyleClass(
|
|||||||
/** Apply left/right placement on `body` and drill slide direction vars. */
|
/** Apply left/right placement on `body` and drill slide direction vars. */
|
||||||
export function applySidebarPosition() {
|
export function applySidebarPosition() {
|
||||||
const position = normalizeSidebarPosition(settingsState.sidebarPosition);
|
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;
|
const root = document.documentElement;
|
||||||
root.style.setProperty("--bsplus-slide-off", position === "right" ? "320px" : "-320px");
|
root.style.setProperty("--bsplus-slide-off", position === "right" ? "320px" : "-320px");
|
||||||
root.style.setProperty("--bsplus-slide-off-compact", position === "right" ? "70px" : "-70px");
|
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`). */
|
/** Safe to call with no menu (still sets width/blur/radius on `:root`). */
|
||||||
let lastSidebarLookKey = "";
|
let lastSidebarLookKey = "";
|
||||||
|
let lastSidebarLookMenu: HTMLElement | null | undefined;
|
||||||
|
|
||||||
export function applySidebarLook(
|
export function applySidebarLook(
|
||||||
menu: HTMLElement | null | undefined = document.getElementById("menu"),
|
menu: HTMLElement | null | undefined = document.getElementById("menu"),
|
||||||
@@ -150,8 +151,9 @@ export function applySidebarLook(
|
|||||||
applySidebarPosition();
|
applySidebarPosition();
|
||||||
|
|
||||||
const lookKey = `${density}|${indicator}|${width}|${radius}|${blur}|${normalizeSidebarPosition(settingsState.sidebarPosition)}`;
|
const lookKey = `${density}|${indicator}|${width}|${radius}|${blur}|${normalizeSidebarPosition(settingsState.sidebarPosition)}`;
|
||||||
if (lookKey === lastSidebarLookKey) return;
|
if (lookKey === lastSidebarLookKey && menu === lastSidebarLookMenu) return;
|
||||||
lastSidebarLookKey = lookKey;
|
lastSidebarLookKey = lookKey;
|
||||||
|
lastSidebarLookMenu = menu;
|
||||||
|
|
||||||
const root = document.documentElement;
|
const root = document.documentElement;
|
||||||
root.style.setProperty("--bsplus-sidebar-width", `${SIDEBAR_WIDTH_PX[width]}px`);
|
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) {
|
export function clearSidebarAppearance(menu: HTMLElement | null | undefined) {
|
||||||
|
lastSidebarLookKey = "";
|
||||||
|
lastSidebarLookMenu = undefined;
|
||||||
const root = document.documentElement;
|
const root = document.documentElement;
|
||||||
root.style.removeProperty("--bsplus-sidebar-width");
|
root.style.removeProperty("--bsplus-sidebar-width");
|
||||||
root.style.removeProperty("--bsplus-sidebar-radius");
|
root.style.removeProperty("--bsplus-sidebar-radius");
|
||||||
root.style.removeProperty("--bsplus-sidebar-blur");
|
root.style.removeProperty("--bsplus-sidebar-blur");
|
||||||
root.style.removeProperty("--bsplus-slide-off");
|
root.style.removeProperty("--bsplus-slide-off");
|
||||||
root.style.removeProperty("--bsplus-slide-off-compact");
|
root.style.removeProperty("--bsplus-slide-off-compact");
|
||||||
document.body.classList.remove("bsplus-sidebar-right");
|
document.body?.classList.remove("bsplus-sidebar-right");
|
||||||
if (!menu) return;
|
if (!menu) return;
|
||||||
clearPrefixed(menu, STYLE_CLASS_PREFIX);
|
clearPrefixed(menu, STYLE_CLASS_PREFIX);
|
||||||
clearPrefixed(menu, DENSITY_CLASS_PREFIX);
|
clearPrefixed(menu, DENSITY_CLASS_PREFIX);
|
||||||
|
|||||||
@@ -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");
|
||||||
|
});
|
||||||
@@ -182,16 +182,13 @@ export function deleteOutlookCalendarEvent(
|
|||||||
}
|
}
|
||||||
|
|
||||||
function toRfc3339Start(date: string): string {
|
function toRfc3339Start(date: string): string {
|
||||||
return `${date}T00:00:00Z`;
|
return new Date(`${date}T00:00:00`).toISOString();
|
||||||
}
|
}
|
||||||
|
|
||||||
function toRfc3339EndExclusive(date: string): string {
|
function toRfc3339EndExclusive(date: string): string {
|
||||||
const d = new Date(`${date}T12:00:00Z`);
|
const d = new Date(`${date}T00:00:00`);
|
||||||
d.setUTCDate(d.getUTCDate() + 1);
|
d.setDate(d.getDate() + 1);
|
||||||
const y = d.getUTCFullYear();
|
return d.toISOString();
|
||||||
const m = String(d.getUTCMonth() + 1).padStart(2, "0");
|
|
||||||
const day = String(d.getUTCDate()).padStart(2, "0");
|
|
||||||
return `${y}-${m}-${day}T00:00:00Z`;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
function dateFromDateTime(value: string | undefined): string {
|
function dateFromDateTime(value: string | undefined): string {
|
||||||
@@ -264,7 +261,7 @@ export async function listGoogleSyncedEvents(
|
|||||||
{ method: "GET" },
|
{ method: "GET" },
|
||||||
refreshAccessToken,
|
refreshAccessToken,
|
||||||
);
|
);
|
||||||
const json = (await res.json().catch(() => ({}))) as {
|
const json = (await res.json()) as {
|
||||||
items?: GoogleListItem[];
|
items?: GoogleListItem[];
|
||||||
nextPageToken?: string;
|
nextPageToken?: string;
|
||||||
error?: { message?: string };
|
error?: { message?: string };
|
||||||
@@ -272,6 +269,15 @@ export async function listGoogleSyncedEvents(
|
|||||||
if (!res.ok) {
|
if (!res.ok) {
|
||||||
throw new Error(json?.error?.message ?? `Google Calendar list failed (${res.status})`);
|
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 ?? []) {
|
for (const item of json.items ?? []) {
|
||||||
const mapped = googleItemToRemote(item, includeUnkeyed);
|
const mapped = googleItemToRemote(item, includeUnkeyed);
|
||||||
@@ -360,7 +366,7 @@ export async function listOutlookSyncedEvents(
|
|||||||
},
|
},
|
||||||
refreshAccessToken,
|
refreshAccessToken,
|
||||||
);
|
);
|
||||||
const json = (await res.json().catch(() => ({}))) as {
|
const json = (await res.json()) as {
|
||||||
value?: OutlookListItem[];
|
value?: OutlookListItem[];
|
||||||
"@odata.nextLink"?: string;
|
"@odata.nextLink"?: string;
|
||||||
error?: { message?: string };
|
error?: { message?: string };
|
||||||
@@ -368,6 +374,9 @@ export async function listOutlookSyncedEvents(
|
|||||||
if (!res.ok) {
|
if (!res.ok) {
|
||||||
throw new Error(json?.error?.message ?? `Outlook Calendar list failed (${res.status})`);
|
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 ?? []) {
|
for (const item of json.value ?? []) {
|
||||||
const mapped = outlookItemToRemote(item, includeUnkeyed);
|
const mapped = outlookItemToRemote(item, includeUnkeyed);
|
||||||
|
|||||||
@@ -40,6 +40,7 @@ import {
|
|||||||
writeGoogleCalendarState,
|
writeGoogleCalendarState,
|
||||||
} from "@/seqta/utils/calendarSync/providerStorage";
|
} from "@/seqta/utils/calendarSync/providerStorage";
|
||||||
import {
|
import {
|
||||||
|
isDateInRange,
|
||||||
syncWindowRange,
|
syncWindowRange,
|
||||||
trailingWeekRange,
|
trailingWeekRange,
|
||||||
wideCleanupRange,
|
wideCleanupRange,
|
||||||
@@ -199,6 +200,9 @@ export async function syncLessonsToCalendar(
|
|||||||
syncWindowRange,
|
syncWindowRange,
|
||||||
trailingWeekRange,
|
trailingWeekRange,
|
||||||
});
|
});
|
||||||
|
const currentMapKeys = new Set(
|
||||||
|
events.map((event) => eventMapKey(request.origin, event.seqtaKey)),
|
||||||
|
);
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const remoteEvents = await provider.listSyncedEvents(
|
const remoteEvents = await provider.listSyncedEvents(
|
||||||
@@ -207,11 +211,21 @@ export async function syncLessonsToCalendar(
|
|||||||
refreshAccessToken,
|
refreshAccessToken,
|
||||||
);
|
);
|
||||||
mergeRemoteEventsIntoMap(eventMap, request.origin, remoteEvents, eventMapKey);
|
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) {
|
} catch (err) {
|
||||||
verboseLog(`[BetterSEQTA+] ${provider.label} remote event list failed:`, 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(
|
let staleEntries = entriesToPrune(
|
||||||
eventMap,
|
eventMap,
|
||||||
request.origin,
|
request.origin,
|
||||||
|
|||||||
@@ -1,10 +1,35 @@
|
|||||||
import {
|
import {
|
||||||
|
applyDownloadedEnvelope,
|
||||||
|
buildUploadPayload,
|
||||||
buildUploadPatch,
|
buildUploadPatch,
|
||||||
CLOUD_SETTINGS_SYNC_SCHEMA_VERSION,
|
CLOUD_SETTINGS_SYNC_SCHEMA_VERSION,
|
||||||
diffSyncableStorage,
|
diffSyncableStorage,
|
||||||
normalizeStorageForSync,
|
normalizeStorageForSync,
|
||||||
normalizeThemeIdForSync,
|
normalizeThemeIdForSync,
|
||||||
} from "./cloudSettingsSync";
|
} 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", () => {
|
describe("normalizeStorageForSync", () => {
|
||||||
it("strips omitted auth and client-only keys", () => {
|
it("strips omitted auth and client-only keys", () => {
|
||||||
|
|||||||
@@ -39,6 +39,7 @@ export const KEYS_OMITTED_FROM_CLOUD_UPLOAD = [
|
|||||||
"cloudAccessToken",
|
"cloudAccessToken",
|
||||||
"cloudUsername",
|
"cloudUsername",
|
||||||
"bsplus_google_calendar",
|
"bsplus_google_calendar",
|
||||||
|
"bsplus_outlook_calendar",
|
||||||
/** Anonymous feedback install id — device-local, never synced. */
|
/** Anonymous feedback install id — device-local, never synced. */
|
||||||
"bsplus_install_id",
|
"bsplus_install_id",
|
||||||
/** Pending feedback ids awaiting a reply notification — device-local. */
|
/** Pending feedback ids awaiting a reply notification — device-local. */
|
||||||
@@ -76,6 +77,7 @@ const AUTH_KEYS_TO_PRESERVE = [
|
|||||||
"bsplus_client_id",
|
"bsplus_client_id",
|
||||||
"bsplus_user",
|
"bsplus_user",
|
||||||
"bsplus_google_calendar",
|
"bsplus_google_calendar",
|
||||||
|
"bsplus_outlook_calendar",
|
||||||
] as const;
|
] as const;
|
||||||
|
|
||||||
const OMIT_FROM_UPLOAD_EXACT = new Set<string>([
|
const OMIT_FROM_UPLOAD_EXACT = new Set<string>([
|
||||||
|
|||||||
@@ -1,5 +1,134 @@
|
|||||||
import { describe, expect, it } from "@jest/globals";
|
import {
|
||||||
import { appointmentToLesson, parseSeqtaDateTime } from "./fetchTimetable";
|
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", () => {
|
describe("parseSeqtaDateTime", () => {
|
||||||
it("parses SEQTA event timestamps", () => {
|
it("parses SEQTA event timestamps", () => {
|
||||||
|
|||||||
@@ -96,6 +96,14 @@ async function resolveLoginPayload(): Promise<SeqtaLoginPayload | undefined> {
|
|||||||
}
|
}
|
||||||
|
|
||||||
export async function resolveStudentId(): Promise<number | undefined> {
|
export async function resolveStudentId(): Promise<number | undefined> {
|
||||||
|
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 payload = await resolveLoginPayload();
|
||||||
const id = payload?.id ?? payload?.student;
|
const id = payload?.id ?? payload?.student;
|
||||||
return typeof id === "number" && Number.isFinite(id) ? id : undefined;
|
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<SeqtaTimetableLesson[]> {
|
export async function fetchAppointments(range: SyncDateRange): Promise<SeqtaTimetableLesson[]> {
|
||||||
if (isEngageParentContext()) return [];
|
if (isEngageParentContext()) return [];
|
||||||
|
|
||||||
try {
|
const person = await resolveStudentId();
|
||||||
const person = await resolveStudentId();
|
if (person == null)
|
||||||
if (person == null) return [];
|
throw new Error("Could not resolve student for calendar sync.");
|
||||||
|
|
||||||
const personType = await resolvePersonType();
|
const personType = await resolvePersonType();
|
||||||
const data = await postSeqtaJson<{ payload?: SeqtaAppointmentPayload[] }>(
|
const data = await postSeqtaJson<{ payload?: SeqtaAppointmentPayload[] }>(
|
||||||
"/seqta/student/events/load",
|
"/seqta/student/events/load",
|
||||||
{
|
{
|
||||||
dateFrom: range.from,
|
dateFrom: range.from,
|
||||||
dateTo: range.until,
|
dateTo: range.until,
|
||||||
person,
|
person,
|
||||||
personType,
|
personType,
|
||||||
},
|
},
|
||||||
);
|
);
|
||||||
|
|
||||||
const payload = Array.isArray(data?.payload) ? data.payload : [];
|
if (!Array.isArray(data?.payload)) {
|
||||||
const lessons: SeqtaTimetableLesson[] = [];
|
throw new Error("Invalid SEQTA appointments response.");
|
||||||
for (const item of payload) {
|
|
||||||
const lesson = appointmentToLesson(item);
|
|
||||||
if (lesson) lessons.push(lesson);
|
|
||||||
}
|
|
||||||
return lessons;
|
|
||||||
} catch {
|
|
||||||
return [];
|
|
||||||
}
|
}
|
||||||
|
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(
|
export async function fetchTimetableLessons(
|
||||||
@@ -191,17 +199,11 @@ export async function fetchTimetableLessons(
|
|||||||
): Promise<SeqtaTimetableLesson[]> {
|
): Promise<SeqtaTimetableLesson[]> {
|
||||||
const { from, until } = range;
|
const { from, until } = range;
|
||||||
const coloursPromise = fetchSubjectColours();
|
const coloursPromise = fetchSubjectColours();
|
||||||
const appointmentsPromise = fetchAppointments(range);
|
|
||||||
|
|
||||||
let lessons: SeqtaTimetableLesson[] = [];
|
let lessons: SeqtaTimetableLesson[] = [];
|
||||||
|
|
||||||
if (isEngageParentContext()) {
|
if (isEngageParentContext()) {
|
||||||
const listJson = await postSeqtaJson<{ payload?: { id?: string | number }[] }>(
|
const studentId = await resolveStudentId();
|
||||||
"/seqta/parent/load/timetable",
|
|
||||||
{ list: true },
|
|
||||||
);
|
|
||||||
const firstChild = Array.isArray(listJson?.payload) ? listJson.payload[0] : undefined;
|
|
||||||
const studentId = firstChild?.id;
|
|
||||||
if (studentId == null) {
|
if (studentId == null) {
|
||||||
throw new Error("No student found on this parent account.");
|
throw new Error("No student found on this parent account.");
|
||||||
}
|
}
|
||||||
@@ -209,7 +211,10 @@ export async function fetchTimetableLessons(
|
|||||||
"/seqta/parent/load/timetable",
|
"/seqta/parent/load/timetable",
|
||||||
{ from, until, student: studentId },
|
{ 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 {
|
} else {
|
||||||
const studentId = await resolveStudentId();
|
const studentId = await resolveStudentId();
|
||||||
const body: Record<string, unknown> = { from, until };
|
const body: Record<string, unknown> = { from, until };
|
||||||
@@ -219,11 +224,14 @@ export async function fetchTimetableLessons(
|
|||||||
"/seqta/student/load/timetable?",
|
"/seqta/student/load/timetable?",
|
||||||
body,
|
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 coloured = withSubjectColours(lessons, await coloursPromise);
|
||||||
const appointments = await appointmentsPromise;
|
const appointments = await fetchAppointments(range);
|
||||||
return [...coloured, ...appointments];
|
return [...coloured, ...appointments];
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -251,37 +259,38 @@ function assessmentDueInRange(due: string, range: SyncDateRange): boolean {
|
|||||||
export async function fetchAssessmentsForCalendarSync(
|
export async function fetchAssessmentsForCalendarSync(
|
||||||
range: SyncDateRange,
|
range: SyncDateRange,
|
||||||
): Promise<CalendarSyncAssessment[]> {
|
): Promise<CalendarSyncAssessment[]> {
|
||||||
try {
|
const studentId = await resolveStudentId();
|
||||||
const studentId = await resolveStudentId();
|
if (studentId == null)
|
||||||
if (studentId == null) return [];
|
throw new Error("Could not resolve student for calendar sync.");
|
||||||
|
|
||||||
const path = isEngageParentContext()
|
const path = isEngageParentContext()
|
||||||
? "/seqta/parent/assessment/list/upcoming?"
|
? "/seqta/parent/assessment/list/upcoming?"
|
||||||
: "/seqta/student/assessment/list/upcoming?";
|
: "/seqta/student/assessment/list/upcoming?";
|
||||||
const data = await postSeqtaJson<{ payload?: unknown[] }>(path, { student: studentId });
|
const data = await postSeqtaJson<{ payload?: unknown[] }>(path, {
|
||||||
const payload = Array.isArray(data.payload) ? data.payload : [];
|
student: studentId,
|
||||||
|
});
|
||||||
const out: CalendarSyncAssessment[] = [];
|
if (!Array.isArray(data?.payload)) {
|
||||||
for (const raw of payload) {
|
throw new Error("Invalid SEQTA assessments response.");
|
||||||
if (!raw || typeof raw !== "object") continue;
|
|
||||||
const row = raw as Record<string, unknown>;
|
|
||||||
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 payload = data.payload;
|
||||||
|
|
||||||
|
const out: CalendarSyncAssessment[] = [];
|
||||||
|
for (const raw of payload) {
|
||||||
|
if (!raw || typeof raw !== "object") continue;
|
||||||
|
const row = raw as Record<string, unknown>;
|
||||||
|
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;
|
||||||
}
|
}
|
||||||
@@ -76,7 +76,9 @@ describe("syncLessonsToGoogleCalendar", () => {
|
|||||||
});
|
});
|
||||||
jest.mocked(upsertGoogleCalendarEvent).mockResolvedValue("google-existing");
|
jest.mocked(upsertGoogleCalendarEvent).mockResolvedValue("google-existing");
|
||||||
jest.mocked(deleteGoogleCalendarEvent).mockResolvedValue(undefined);
|
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 () => {
|
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 () => {
|
it("creates events that are not yet tracked", async () => {
|
||||||
|
jest.mocked(listGoogleSyncedEvents).mockResolvedValue([]);
|
||||||
jest.mocked(readGoogleCalendarState).mockResolvedValue({
|
jest.mocked(readGoogleCalendarState).mockResolvedValue({
|
||||||
refreshToken: "refresh",
|
refreshToken: "refresh",
|
||||||
calendarId: "app-calendar-id",
|
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 () => {
|
it("deletes cancelled lessons that remain inside the sync window", async () => {
|
||||||
jest.mocked(readGoogleCalendarState).mockResolvedValue({
|
jest.mocked(readGoogleCalendarState).mockResolvedValue({
|
||||||
refreshToken: "refresh",
|
refreshToken: "refresh",
|
||||||
|
|||||||
@@ -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");
|
||||||
|
});
|
||||||
@@ -1,5 +1,6 @@
|
|||||||
import { settingsState } from "./SettingsState";
|
import { settingsState } from "./SettingsState";
|
||||||
import { updateAllColors } from "@/seqta/ui/colors/Manager";
|
import { updateAllColors } from "@/seqta/ui/colors/Manager";
|
||||||
|
import { applySelectedFont } from "@/seqta/ui/fonts/Manager";
|
||||||
|
|
||||||
// Shortcuts rendering
|
// Shortcuts rendering
|
||||||
import { renderShortcuts } from "@/seqta/utils/Render/renderShortcuts";
|
import { renderShortcuts } from "@/seqta/utils/Render/renderShortcuts";
|
||||||
|
|||||||
@@ -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();
|
||||||
|
}
|
||||||
|
});
|
||||||
@@ -61,6 +61,7 @@ export function animateSettingsClose(host: HTMLElement): void {
|
|||||||
: 200;
|
: 200;
|
||||||
|
|
||||||
window.setTimeout(() => {
|
window.setTimeout(() => {
|
||||||
|
if (!host.classList.contains(HOST_CLOSING_CLASS)) return;
|
||||||
host.classList.remove(HOST_CLOSING_CLASS);
|
host.classList.remove(HOST_CLOSING_CLASS);
|
||||||
host.style.opacity = "0";
|
host.style.opacity = "0";
|
||||||
}, durationMs);
|
}, durationMs);
|
||||||
|
|||||||
Reference in new issue
Block a user