mirror of
https://github.com/BetterSEQTA/BetterSEQTA-Plus.git
synced 2026-12-06 19:56:45 +10:30
fix: fix svelte type checker area
This commit is contained in:
1 parent
4d1577877a
commit
6f07b39437
56 files changed
+379
-269
No files matched your search
@@ -67,6 +67,7 @@
|
|||||||
},
|
},
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
"@crxjs/vite-plugin": "^3.0.0",
|
"@crxjs/vite-plugin": "^3.0.0",
|
||||||
|
"@jest/globals": "30.5.2",
|
||||||
"@sveltejs/vite-plugin-svelte": "^7.3.1",
|
"@sveltejs/vite-plugin-svelte": "^7.3.1",
|
||||||
"@tailwindcss/forms": "^0.5.11",
|
"@tailwindcss/forms": "^0.5.11",
|
||||||
"@tailwindcss/postcss": "^4.3.3",
|
"@tailwindcss/postcss": "^4.3.3",
|
||||||
|
|||||||
@@ -47,6 +47,18 @@ function isAutoCloudSyncEnabled(all: Record<string, unknown>): boolean {
|
|||||||
return all.autoCloudSettingsSync !== false;
|
return all.autoCloudSettingsSync !== false;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
type CloudJsonBody = {
|
||||||
|
access_token?: string;
|
||||||
|
refresh_token?: string;
|
||||||
|
user?: unknown;
|
||||||
|
error?: string;
|
||||||
|
updated_at?: string;
|
||||||
|
};
|
||||||
|
|
||||||
|
function asCloudJsonBody(data: unknown): CloudJsonBody {
|
||||||
|
return data && typeof data === "object" ? (data as CloudJsonBody) : {};
|
||||||
|
}
|
||||||
|
|
||||||
async function parseJsonResponse(r: Response): Promise<unknown> {
|
async function parseJsonResponse(r: Response): Promise<unknown> {
|
||||||
const text = await r.text();
|
const text = await r.text();
|
||||||
try {
|
try {
|
||||||
@@ -77,7 +89,7 @@ async function tryRefreshTokens(): Promise<boolean> {
|
|||||||
headers: { "Content-Type": "application/json" },
|
headers: { "Content-Type": "application/json" },
|
||||||
body: JSON.stringify({ refresh_token, client_id }),
|
body: JSON.stringify({ refresh_token, client_id }),
|
||||||
});
|
});
|
||||||
const data = await parseJsonResponse(r);
|
const data = asCloudJsonBody(await parseJsonResponse(r));
|
||||||
if (!r.ok || !data.access_token || !data.refresh_token) return false;
|
if (!r.ok || !data.access_token || !data.refresh_token) return false;
|
||||||
|
|
||||||
await browser.storage.local.set({
|
await browser.storage.local.set({
|
||||||
@@ -189,16 +201,16 @@ async function putSettingsOnce(token: string): Promise<PutResult> {
|
|||||||
},
|
},
|
||||||
body: JSON.stringify(payload),
|
body: JSON.stringify(payload),
|
||||||
});
|
});
|
||||||
const data = await parseJsonResponse(r);
|
const data = asCloudJsonBody(await parseJsonResponse(r));
|
||||||
if (r.status === 401) return { ok: false, unauthorized: true };
|
if (r.status === 401) return { ok: false, unauthorized: true };
|
||||||
if (!r.ok) {
|
if (!r.ok) {
|
||||||
return {
|
return {
|
||||||
ok: false,
|
ok: false,
|
||||||
unauthorized: false,
|
unauthorized: false,
|
||||||
error: data?.error ?? `Upload failed (${r.status})`,
|
error: data.error ?? `Upload failed (${r.status})`,
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
const updated_at = data?.updated_at as string | undefined;
|
const updated_at = data.updated_at;
|
||||||
await saveLastUploadedSnapshot(normalized);
|
await saveLastUploadedSnapshot(normalized);
|
||||||
await setKnownRemoteUpdatedAt(updated_at);
|
await setKnownRemoteUpdatedAt(updated_at);
|
||||||
return { ok: true, updated_at };
|
return { ok: true, updated_at };
|
||||||
@@ -247,7 +259,7 @@ async function getSettingsAndApplyOnce(token: string): Promise<GetResult> {
|
|||||||
headers: { Authorization: `Bearer ${token}` },
|
headers: { Authorization: `Bearer ${token}` },
|
||||||
cache: "no-store",
|
cache: "no-store",
|
||||||
});
|
});
|
||||||
const data = await parseJsonResponse(r);
|
const data = asCloudJsonBody(await parseJsonResponse(r));
|
||||||
if (r.status === 401) return { ok: false, unauthorized: true };
|
if (r.status === 401) return { ok: false, unauthorized: true };
|
||||||
if (r.status === 404) {
|
if (r.status === 404) {
|
||||||
return {
|
return {
|
||||||
@@ -261,7 +273,7 @@ async function getSettingsAndApplyOnce(token: string): Promise<GetResult> {
|
|||||||
return {
|
return {
|
||||||
ok: false,
|
ok: false,
|
||||||
unauthorized: false,
|
unauthorized: false,
|
||||||
error: data?.error ?? `Download failed (${r.status})`,
|
error: data.error ?? `Download failed (${r.status})`,
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
const themeIdToEnsure = resolveThemeIdForPostSyncDownload(data);
|
const themeIdToEnsure = resolveThemeIdForPostSyncDownload(data);
|
||||||
|
|||||||
@@ -7,7 +7,7 @@
|
|||||||
import { indentWithTab, history, defaultKeymap, historyKeymap } from '@codemirror/commands';
|
import { indentWithTab, history, defaultKeymap, historyKeymap } from '@codemirror/commands';
|
||||||
import { indentOnInput, indentUnit, bracketMatching, foldKeymap, syntaxHighlighting, defaultHighlightStyle } from '@codemirror/language';
|
import { indentOnInput, indentUnit, bracketMatching, foldKeymap, syntaxHighlighting, defaultHighlightStyle } from '@codemirror/language';
|
||||||
import { closeBrackets, autocompletion, closeBracketsKeymap, completionKeymap } from '@codemirror/autocomplete';
|
import { closeBrackets, autocompletion, closeBracketsKeymap, completionKeymap } from '@codemirror/autocomplete';
|
||||||
import { highlightSpecialChars, drawSelection, rectangularSelection, crosshairCursor, highlightActiveLine, keymap, EditorView, dropCursor } from '@codemirror/view';
|
import { highlightSpecialChars, drawSelection, rectangularSelection, crosshairCursor, highlightActiveLine, keymap, EditorView, dropCursor, type KeyBinding } from '@codemirror/view';
|
||||||
import { color } from '@uiw/codemirror-extensions-color'
|
import { color } from '@uiw/codemirror-extensions-color'
|
||||||
import { Compartment } from '@codemirror/state';
|
import { Compartment } from '@codemirror/state';
|
||||||
|
|
||||||
@@ -45,7 +45,7 @@
|
|||||||
...historyKeymap,
|
...historyKeymap,
|
||||||
...foldKeymap,
|
...foldKeymap,
|
||||||
...completionKeymap,
|
...completionKeymap,
|
||||||
]),
|
] as KeyBinding[]),
|
||||||
EditorView.updateListener.of((update) => {
|
EditorView.updateListener.of((update) => {
|
||||||
if (update.docChanged) {
|
if (update.docChanged) {
|
||||||
onChange(update.state.doc.toString())
|
onChange(update.state.doc.toString())
|
||||||
|
|||||||
@@ -6,6 +6,7 @@
|
|||||||
import Switch from "@/interface/components/Switch.svelte";
|
import Switch from "@/interface/components/Switch.svelte";
|
||||||
import { settingsState } from "@/seqta/utils/listeners/SettingsState";
|
import { settingsState } from "@/seqta/utils/listeners/SettingsState";
|
||||||
import { matchesSearch } from "@/interface/pages/settings/shared";
|
import { matchesSearch } from "@/interface/pages/settings/shared";
|
||||||
|
import type { SettingsList } from "@/interface/types/SettingsProps";
|
||||||
import {
|
import {
|
||||||
DEFAULT_SIDEBAR_BLUR,
|
DEFAULT_SIDEBAR_BLUR,
|
||||||
DEFAULT_SIDEBAR_RADIUS,
|
DEFAULT_SIDEBAR_RADIUS,
|
||||||
@@ -132,7 +133,7 @@
|
|||||||
},
|
},
|
||||||
];
|
];
|
||||||
|
|
||||||
if (!transparencyOn) return base;
|
if (!transparencyOn) return base as unknown as SettingsList[];
|
||||||
|
|
||||||
return [
|
return [
|
||||||
...base,
|
...base,
|
||||||
@@ -149,7 +150,7 @@
|
|||||||
onChange: (value: number) => (settingsState.sidebarBlur = value),
|
onChange: (value: number) => (settingsState.sidebarBlur = value),
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
];
|
] as unknown as SettingsList[];
|
||||||
});
|
});
|
||||||
|
|
||||||
const visible = $derived(
|
const visible = $derived(
|
||||||
|
|||||||
@@ -1,4 +1,5 @@
|
|||||||
import { mount, type Component } from "svelte";
|
import { mount } from "svelte";
|
||||||
|
import type { MountableSvelteComponent } from "@/types/mountableComponent";
|
||||||
import settingsStyle from "./index.css?inline";
|
import settingsStyle from "./index.css?inline";
|
||||||
import contentShadowStyle from "./contentShadow.css?inline";
|
import contentShadowStyle from "./contentShadow.css?inline";
|
||||||
|
|
||||||
@@ -11,7 +12,7 @@ const shadowStyles = {
|
|||||||
export type ShadowStyleVariant = keyof typeof shadowStyles;
|
export type ShadowStyleVariant = keyof typeof shadowStyles;
|
||||||
|
|
||||||
export default function renderSvelte(
|
export default function renderSvelte(
|
||||||
Component: Component<Record<string, unknown>>,
|
Component: MountableSvelteComponent,
|
||||||
mountPoint: ShadowRoot | HTMLElement,
|
mountPoint: ShadowRoot | HTMLElement,
|
||||||
props: Record<string, unknown> = {},
|
props: Record<string, unknown> = {},
|
||||||
shadowStyle: ShadowStyleVariant = "settings",
|
shadowStyle: ShadowStyleVariant = "settings",
|
||||||
|
|||||||
@@ -23,6 +23,7 @@
|
|||||||
pluginSettingsStore,
|
pluginSettingsStore,
|
||||||
type PluginSettingsEntry,
|
type PluginSettingsEntry,
|
||||||
} from "./pluginSettingsState.svelte";
|
} from "./pluginSettingsState.svelte";
|
||||||
|
import { toMountableComponent } from "@/types/mountableComponent";
|
||||||
|
|
||||||
let {
|
let {
|
||||||
section,
|
section,
|
||||||
@@ -187,7 +188,7 @@
|
|||||||
title="Theme of the Month"
|
title="Theme of the Month"
|
||||||
description="Show the monthly featured theme popup when a new entry is available"
|
description="Show the monthly featured theme popup when a new entry is available"
|
||||||
id={15}
|
id={15}
|
||||||
Component={Switch}
|
Component={toMountableComponent(Switch)}
|
||||||
{searchQuery}
|
{searchQuery}
|
||||||
props={{
|
props={{
|
||||||
state: !($settingsState.themeOfTheMonthDisabled ?? false),
|
state: !($settingsState.themeOfTheMonthDisabled ?? false),
|
||||||
|
|||||||
@@ -1,15 +1,22 @@
|
|||||||
import type { Component } from "svelte";
|
import type { MountableSvelteComponent } from "@/types/mountableComponent";
|
||||||
import type { SettingsSectionId } from "./shared";
|
import type { SettingsSectionId } from "./shared";
|
||||||
|
|
||||||
export const SECTION_LOADERS: Record<
|
export const SECTION_LOADERS: Record<
|
||||||
SettingsSectionId,
|
SettingsSectionId,
|
||||||
() => Promise<{ default: Component<Record<string, unknown>> }>
|
() => Promise<{ default: MountableSvelteComponent }>
|
||||||
> = {
|
> = {
|
||||||
account: () => import("./sections/account.svelte"),
|
account: () =>
|
||||||
general: () => import("./sections/generalOptions.svelte"),
|
import("./sections/account.svelte") as Promise<{ default: MountableSvelteComponent }>,
|
||||||
appearance: () => import("./sections/appearance.svelte"),
|
general: () =>
|
||||||
timetable: () => import("./sections/plugins.svelte"),
|
import("./sections/generalOptions.svelte") as Promise<{ default: MountableSvelteComponent }>,
|
||||||
assessments: () => import("./sections/plugins.svelte"),
|
appearance: () =>
|
||||||
features: () => import("./sections/plugins.svelte"),
|
import("./sections/appearance.svelte") as Promise<{ default: MountableSvelteComponent }>,
|
||||||
advanced: () => import("./sections/advanced.svelte"),
|
timetable: () =>
|
||||||
|
import("./sections/plugins.svelte") as Promise<{ default: MountableSvelteComponent }>,
|
||||||
|
assessments: () =>
|
||||||
|
import("./sections/plugins.svelte") as Promise<{ default: MountableSvelteComponent }>,
|
||||||
|
features: () =>
|
||||||
|
import("./sections/plugins.svelte") as Promise<{ default: MountableSvelteComponent }>,
|
||||||
|
advanced: () =>
|
||||||
|
import("./sections/advanced.svelte") as Promise<{ default: MountableSvelteComponent }>,
|
||||||
};
|
};
|
||||||
@@ -9,6 +9,7 @@
|
|||||||
import { settingsState } from "@/seqta/utils/listeners/SettingsState";
|
import { settingsState } from "@/seqta/utils/listeners/SettingsState";
|
||||||
import { cloudAuth } from "@/seqta/utils/CloudAuth";
|
import { cloudAuth } from "@/seqta/utils/CloudAuth";
|
||||||
import { matchesSearch, type SettingsSectionSharedProps } from "../shared";
|
import { matchesSearch, type SettingsSectionSharedProps } from "../shared";
|
||||||
|
import { toMountableComponent } from "@/types/mountableComponent";
|
||||||
|
|
||||||
let {
|
let {
|
||||||
showDisclaimer,
|
showDisclaimer,
|
||||||
@@ -53,7 +54,7 @@
|
|||||||
title="Connect Mobile App"
|
title="Connect Mobile App"
|
||||||
description="Link your SEQTA session to DesQTA — the modern desktop and mobile app for SEQTA Learn"
|
description="Link your SEQTA session to DesQTA — the modern desktop and mobile app for SEQTA Learn"
|
||||||
id={0}
|
id={0}
|
||||||
Component={ConnectMobileApp}
|
Component={toMountableComponent(ConnectMobileApp)}
|
||||||
{searchQuery}
|
{searchQuery}
|
||||||
props={{}}
|
props={{}}
|
||||||
/>
|
/>
|
||||||
@@ -91,7 +92,7 @@
|
|||||||
title={founderBadgeSetting.title}
|
title={founderBadgeSetting.title}
|
||||||
description={founderBadgeSetting.description}
|
description={founderBadgeSetting.description}
|
||||||
id={17}
|
id={17}
|
||||||
Component={Switch}
|
Component={toMountableComponent(Switch)}
|
||||||
{searchQuery}
|
{searchQuery}
|
||||||
props={{
|
props={{
|
||||||
state: $settingsState.showTitlebarFounderBadge !== false,
|
state: $settingsState.showTitlebarFounderBadge !== false,
|
||||||
|
|||||||
@@ -9,6 +9,7 @@
|
|||||||
import { settingsState } from "@/seqta/utils/listeners/SettingsState";
|
import { settingsState } from "@/seqta/utils/listeners/SettingsState";
|
||||||
import { isSeqtaEngageExperience } from "@/seqta/utils/isSeqtaEngage";
|
import { isSeqtaEngageExperience } from "@/seqta/utils/isSeqtaEngage";
|
||||||
import { matchesSearch, type SettingsSectionSharedProps } from "../shared";
|
import { matchesSearch, type SettingsSectionSharedProps } from "../shared";
|
||||||
|
import type { SettingsList } from "@/interface/types/SettingsProps";
|
||||||
|
|
||||||
let {
|
let {
|
||||||
showColourPicker,
|
showColourPicker,
|
||||||
@@ -22,22 +23,24 @@
|
|||||||
|
|
||||||
{#if matchesSearch(searchQuery, "Custom Theme Colour", "Interface Font", "Customise the overall theme colour of SEQTA Learn", "Choose the typeface used across SEQTA Learn")}
|
{#if matchesSearch(searchQuery, "Custom Theme Colour", "Interface Font", "Customise the overall theme colour of SEQTA Learn", "Choose the typeface used across SEQTA Learn")}
|
||||||
<SettingsCard class="divide-y divide-zinc-200/60 dark:divide-zinc-700/40">
|
<SettingsCard class="divide-y divide-zinc-200/60 dark:divide-zinc-700/40">
|
||||||
{#each [
|
{#each (
|
||||||
{
|
[
|
||||||
title: "Custom Theme Colour",
|
{
|
||||||
description: "Customise the overall theme colour of SEQTA Learn",
|
title: "Custom Theme Colour",
|
||||||
id: 4,
|
description: "Customise the overall theme colour of SEQTA Learn",
|
||||||
Component: PickerSwatch,
|
id: 4,
|
||||||
props: { onClick: showColourPicker },
|
Component: PickerSwatch,
|
||||||
},
|
props: { onClick: showColourPicker },
|
||||||
{
|
},
|
||||||
title: "Interface Font",
|
{
|
||||||
description: "Choose the typeface used across SEQTA Learn",
|
title: "Interface Font",
|
||||||
id: 16,
|
description: "Choose the typeface used across SEQTA Learn",
|
||||||
Component: Button,
|
id: 16,
|
||||||
props: { onClick: showFontPicker, text: "Change" },
|
Component: Button,
|
||||||
},
|
props: { onClick: showFontPicker, text: "Change" },
|
||||||
] as option (option.id)}
|
},
|
||||||
|
] as unknown as SettingsList[]
|
||||||
|
) as option (option.id)}
|
||||||
<SettingRow {...option} {searchQuery} />
|
<SettingRow {...option} {searchQuery} />
|
||||||
{/each}
|
{/each}
|
||||||
</SettingsCard>
|
</SettingsCard>
|
||||||
|
|||||||
@@ -12,6 +12,7 @@
|
|||||||
} from "@/seqta/utils/performanceMode";
|
} from "@/seqta/utils/performanceMode";
|
||||||
import browser from "@/lib/browser";
|
import browser from "@/lib/browser";
|
||||||
import { matchesSearch, type SettingsSectionSharedProps } from "../shared";
|
import { matchesSearch, type SettingsSectionSharedProps } from "../shared";
|
||||||
|
import type { SettingsList } from "@/interface/types/SettingsProps";
|
||||||
import { checkRemoteFeature } from "@/seqta/utils/remoteConfig/runtime";
|
import { checkRemoteFeature } from "@/seqta/utils/remoteConfig/runtime";
|
||||||
|
|
||||||
let { searchQuery = "" }: SettingsSectionSharedProps = $props();
|
let { searchQuery = "" }: SettingsSectionSharedProps = $props();
|
||||||
@@ -142,7 +143,7 @@
|
|||||||
},
|
},
|
||||||
]
|
]
|
||||||
: []),
|
: []),
|
||||||
]);
|
] as unknown as SettingsList[]);
|
||||||
</script>
|
</script>
|
||||||
|
|
||||||
{#if generalOptions.some((option) => matchesSearch(searchQuery, option.title, option.description))}
|
{#if generalOptions.some((option) => matchesSearch(searchQuery, option.title, option.description))}
|
||||||
|
|||||||
@@ -1,9 +1,9 @@
|
|||||||
import type { Component } from "svelte";
|
import type { MountableSvelteComponent } from "@/types/mountableComponent";
|
||||||
|
|
||||||
export interface SettingsList {
|
export interface SettingsList {
|
||||||
title: string;
|
title: string;
|
||||||
id: number;
|
id: number;
|
||||||
description: string;
|
description: string;
|
||||||
Component: Component<Record<string, unknown>>;
|
Component: MountableSvelteComponent;
|
||||||
props?: Record<string, unknown>;
|
props?: Record<string, unknown>;
|
||||||
}
|
}
|
||||||
@@ -78,8 +78,10 @@ async function resolveAssessmentId(
|
|||||||
|
|
||||||
if (!resolvedMarks) {
|
if (!resolvedMarks) {
|
||||||
try {
|
try {
|
||||||
const state = await ReactFiber.find("[class*='AssessmentList__items___']").getState();
|
const state = (await ReactFiber.find(
|
||||||
resolvedMarks = collectMarksFromFiberState(state);
|
"[class*='AssessmentList__items___']",
|
||||||
|
).getState()) as Record<string, unknown> | null;
|
||||||
|
resolvedMarks = collectMarksFromFiberState(state ?? {});
|
||||||
} catch {
|
} catch {
|
||||||
resolvedMarks = [];
|
resolvedMarks = [];
|
||||||
}
|
}
|
||||||
@@ -794,6 +796,9 @@ async function handleWeightings(mark: AssessmentMark, api: AssessmentsAverageApi
|
|||||||
} else {
|
} else {
|
||||||
const userInfo = await getUserInfo();
|
const userInfo = await getUserInfo();
|
||||||
const userID = userInfo.id;
|
const userID = userInfo.id;
|
||||||
|
if (userID == null) {
|
||||||
|
throw new Error("Could not resolve student ID from user info");
|
||||||
|
}
|
||||||
|
|
||||||
const reportFile = await requestStudentAssessmentPdf({
|
const reportFile = await requestStudentAssessmentPdf({
|
||||||
assessmentID,
|
assessmentID,
|
||||||
@@ -853,7 +858,10 @@ async function handleWeightings(mark: AssessmentMark, api: AssessmentsAverageApi
|
|||||||
}
|
}
|
||||||
|
|
||||||
export async function parseAssessments(api: AssessmentsAverageApi) {
|
export async function parseAssessments(api: AssessmentsAverageApi) {
|
||||||
const state = await ReactFiber.find("[class*='AssessmentList__items___']").getState();
|
const state = (await ReactFiber.find("[class*='AssessmentList__items___']").getState()) as Record<
|
||||||
|
string,
|
||||||
|
MarkLike[] | undefined
|
||||||
|
>;
|
||||||
|
|
||||||
const marks = [
|
const marks = [
|
||||||
...(state["marks"] ?? []),
|
...(state["marks"] ?? []),
|
||||||
@@ -878,8 +886,10 @@ export async function processAssessments(
|
|||||||
|
|
||||||
let fiberMarks: MarkLike[];
|
let fiberMarks: MarkLike[];
|
||||||
try {
|
try {
|
||||||
const state = await ReactFiber.find("[class*='AssessmentList__items___']").getState();
|
const state = (await ReactFiber.find(
|
||||||
fiberMarks = collectMarksFromFiberState(state);
|
"[class*='AssessmentList__items___']",
|
||||||
|
).getState()) as Record<string, unknown> | null;
|
||||||
|
fiberMarks = collectMarksFromFiberState(state ?? {});
|
||||||
} catch {
|
} catch {
|
||||||
fiberMarks = [];
|
fiberMarks = [];
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -179,6 +179,9 @@ export async function getAssessmentsData() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
const studentId = (await getUserInfo()).id;
|
const studentId = (await getUserInfo()).id;
|
||||||
|
if (typeof studentId !== "number") {
|
||||||
|
return [];
|
||||||
|
}
|
||||||
|
|
||||||
if (cache && Date.now() - cache.time < CACHE_MS && cache.studentId === studentId) {
|
if (cache && Date.now() - cache.time < CACHE_MS && cache.studentId === studentId) {
|
||||||
return cache.data;
|
return cache.data;
|
||||||
|
|||||||
@@ -185,18 +185,19 @@ async function loadEngageAssessmentsForStudent(
|
|||||||
else map[task.id] = task;
|
else map[task.id] = task;
|
||||||
});
|
});
|
||||||
|
|
||||||
const assessments = filterAssessmentsForActiveSubjects(Object.values(map), subjects).map(
|
const assessments: OverviewAssessment[] = filterAssessmentsForActiveSubjects(
|
||||||
(assessment) => ({
|
Object.values(map),
|
||||||
...assessment,
|
subjects,
|
||||||
studentId,
|
).map((assessment) => ({
|
||||||
studentName,
|
...assessment,
|
||||||
}),
|
studentId,
|
||||||
);
|
studentName,
|
||||||
|
}));
|
||||||
|
|
||||||
const submissions = await loadEngageSubmissions(studentId, assessments);
|
const submissions = await loadEngageSubmissions(studentId, assessments);
|
||||||
assessments.forEach((assessment) => {
|
for (const assessment of assessments) {
|
||||||
assessment.submitted = submissions[assessment.id] || false;
|
assessment.submitted = submissions[assessment.id] || false;
|
||||||
});
|
}
|
||||||
|
|
||||||
return assessments;
|
return assessments;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -5,6 +5,7 @@ import AssessmentsOverview from "./AssessmentsOverview.svelte";
|
|||||||
import SkeletonLoader from "./SkeletonLoader.svelte";
|
import SkeletonLoader from "./SkeletonLoader.svelte";
|
||||||
import ErrorState from "./ErrorState.svelte";
|
import ErrorState from "./ErrorState.svelte";
|
||||||
import { unmount } from "svelte";
|
import { unmount } from "svelte";
|
||||||
|
import { toMountableComponent } from "@/types/mountableComponent";
|
||||||
|
|
||||||
let currentApp: ReturnType<typeof renderSvelte> | null = null;
|
let currentApp: ReturnType<typeof renderSvelte> | null = null;
|
||||||
let themeObserver: MutationObserver | null = null;
|
let themeObserver: MutationObserver | null = null;
|
||||||
@@ -118,13 +119,13 @@ export function renderGrid(
|
|||||||
) {
|
) {
|
||||||
if (currentApp) unmount(currentApp);
|
if (currentApp) unmount(currentApp);
|
||||||
prepareContainer(container);
|
prepareContainer(container);
|
||||||
currentApp = renderSvelte(AssessmentsOverview, container, { data });
|
currentApp = renderSvelte(toMountableComponent(AssessmentsOverview), container, { data });
|
||||||
}
|
}
|
||||||
|
|
||||||
export function renderSkeletonLoader(container: HTMLElement) {
|
export function renderSkeletonLoader(container: HTMLElement) {
|
||||||
if (currentApp) unmount(currentApp);
|
if (currentApp) unmount(currentApp);
|
||||||
prepareContainer(container);
|
prepareContainer(container);
|
||||||
currentApp = renderSvelte(SkeletonLoader, container);
|
currentApp = renderSvelte(toMountableComponent(SkeletonLoader), container);
|
||||||
}
|
}
|
||||||
|
|
||||||
export function renderLoadingState(container: HTMLElement) {
|
export function renderLoadingState(container: HTMLElement) {
|
||||||
@@ -134,7 +135,7 @@ export function renderLoadingState(container: HTMLElement) {
|
|||||||
export function renderErrorState(container: HTMLElement, error: string) {
|
export function renderErrorState(container: HTMLElement, error: string) {
|
||||||
if (currentApp) unmount(currentApp);
|
if (currentApp) unmount(currentApp);
|
||||||
prepareContainer(container);
|
prepareContainer(container);
|
||||||
currentApp = renderSvelte(ErrorState, container, { error });
|
currentApp = renderSvelte(toMountableComponent(ErrorState), container, { error });
|
||||||
}
|
}
|
||||||
|
|
||||||
export function teardownOverviewUi() {
|
export function teardownOverviewUi() {
|
||||||
|
|||||||
@@ -186,7 +186,11 @@ export function readStoredList(key: string): unknown[] {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
export type OverviewAssessment = Record<string, unknown>;
|
export type OverviewAssessment = {
|
||||||
|
id: number;
|
||||||
|
submitted?: boolean;
|
||||||
|
[key: string]: unknown;
|
||||||
|
};
|
||||||
|
|
||||||
function readNumber(value: unknown): number | null {
|
function readNumber(value: unknown): number | null {
|
||||||
if (value === undefined || value === null) return null;
|
if (value === undefined || value === null) return null;
|
||||||
|
|||||||
@@ -7,6 +7,7 @@ import {
|
|||||||
} from "@/plugins/core/settingsHelpers";
|
} from "@/plugins/core/settingsHelpers";
|
||||||
import styles from "./styles.css?inline";
|
import styles from "./styles.css?inline";
|
||||||
import BackgroundMusicSetting from "./BackgroundMusicSetting.svelte";
|
import BackgroundMusicSetting from "./BackgroundMusicSetting.svelte";
|
||||||
|
import { toMountableComponent } from "@/types/mountableComponent";
|
||||||
import localforage from "localforage";
|
import localforage from "localforage";
|
||||||
import { isPerformanceMode } from "@/seqta/utils/performanceMode";
|
import { isPerformanceMode } from "@/seqta/utils/performanceMode";
|
||||||
import { delay } from "@/seqta/utils/delay";
|
import { delay } from "@/seqta/utils/delay";
|
||||||
@@ -15,7 +16,7 @@ const settings = defineSettings({
|
|||||||
uploader: componentSetting({
|
uploader: componentSetting({
|
||||||
title: "Background Music",
|
title: "Background Music",
|
||||||
description: "Upload a .wav or .mp3 audio file to play in the background",
|
description: "Upload a .wav or .mp3 audio file to play in the background",
|
||||||
component: BackgroundMusicSetting,
|
component: toMountableComponent(BackgroundMusicSetting),
|
||||||
}),
|
}),
|
||||||
volume: numberSetting({
|
volume: numberSetting({
|
||||||
title: "Volume",
|
title: "Volume",
|
||||||
|
|||||||
@@ -70,7 +70,7 @@ async function getCurrentLesson() {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
async function navigateToSpecificLesson(lesson: HomeTimetableLesson) {
|
async function navigateToSpecificLesson(_lesson: HomeTimetableLesson) {
|
||||||
try {
|
try {
|
||||||
await waitForElm(".course .navigator", true, 100, 100);
|
await waitForElm(".course .navigator", true, 100, 100);
|
||||||
|
|
||||||
@@ -98,7 +98,7 @@ async function navigateToSpecificLesson(lesson: HomeTimetableLesson) {
|
|||||||
const lessonPeriod = periodElement.textContent?.trim().match(/\d+/)?.[0];
|
const lessonPeriod = periodElement.textContent?.trim().match(/\d+/)?.[0];
|
||||||
|
|
||||||
// extract the number from the period
|
// extract the number from the period
|
||||||
const normalizedLessonPeriod = lesson.period?.match(/\d+/)?.[0];
|
const normalizedLessonPeriod = lessonPeriod;
|
||||||
|
|
||||||
// Check if this lesson matches today's date and the current lesson's period
|
// Check if this lesson matches today's date and the current lesson's period
|
||||||
if (lessonDate === todayDateString && lessonPeriod === normalizedLessonPeriod) {
|
if (lessonDate === todayDateString && lessonPeriod === normalizedLessonPeriod) {
|
||||||
|
|||||||
@@ -7,14 +7,14 @@ import { transparencyEnabled } from "@/seqta/utils/performanceMode";
|
|||||||
import renderSvelte from "@/interface/main";
|
import renderSvelte from "@/interface/main";
|
||||||
import type { GlobalSearchApi } from "../../lazy";
|
import type { GlobalSearchApi } from "../../lazy";
|
||||||
import browser from "@/lib/browser";
|
import browser from "@/lib/browser";
|
||||||
|
import { toMountableComponent } from "@/types/mountableComponent";
|
||||||
|
|
||||||
|
type StorageChangeMap = Record<string, chrome.storage.StorageChange>;
|
||||||
|
|
||||||
type AppRef = {
|
type AppRef = {
|
||||||
current: ReturnType<typeof renderSvelte> | null;
|
current: ReturnType<typeof renderSvelte> | null;
|
||||||
storageChangeHandler?: (
|
storageChangeHandler?: (changes: StorageChangeMap, area: string) => void;
|
||||||
changes: Record<string, browser.storage.StorageChange>,
|
progressHandler?: EventListener | null;
|
||||||
area: string,
|
|
||||||
) => void;
|
|
||||||
progressHandler?: ((event: Event) => void) | null;
|
|
||||||
clearDoneFlashTimer?: () => void;
|
clearDoneFlashTimer?: () => void;
|
||||||
clickHandler?: () => void;
|
clickHandler?: () => void;
|
||||||
ownedTrigger?: boolean;
|
ownedTrigger?: boolean;
|
||||||
@@ -214,8 +214,8 @@ export async function mountSearchBar(titleElement: Element, api: GlobalSearchApi
|
|||||||
resetIdleProgressUi();
|
resetIdleProgressUi();
|
||||||
};
|
};
|
||||||
|
|
||||||
const progressHandler = (event: CustomEvent) => {
|
const progressHandler: EventListener = (event) => {
|
||||||
const { completed, total, indexing, status } = event.detail as {
|
const { completed, total, indexing, status } = (event as CustomEvent).detail as {
|
||||||
completed?: number;
|
completed?: number;
|
||||||
total?: number;
|
total?: number;
|
||||||
indexing?: boolean;
|
indexing?: boolean;
|
||||||
@@ -235,7 +235,7 @@ export async function mountSearchBar(titleElement: Element, api: GlobalSearchApi
|
|||||||
updateProgressDisplay();
|
updateProgressDisplay();
|
||||||
};
|
};
|
||||||
|
|
||||||
window.addEventListener("indexing-progress", progressHandler as EventListener);
|
window.addEventListener("indexing-progress", progressHandler);
|
||||||
appRef.progressHandler = progressHandler;
|
appRef.progressHandler = progressHandler;
|
||||||
appRef.clearDoneFlashTimer = clearDoneFlashTimer;
|
appRef.clearDoneFlashTimer = clearDoneFlashTimer;
|
||||||
|
|
||||||
@@ -251,10 +251,7 @@ export async function mountSearchBar(titleElement: Element, api: GlobalSearchApi
|
|||||||
}
|
}
|
||||||
searchWrapper.dataset.bsplusSearchWired = "1";
|
searchWrapper.dataset.bsplusSearchWired = "1";
|
||||||
|
|
||||||
const handleStorageChange = (
|
const handleStorageChange = (changes: StorageChangeMap, area: string) => {
|
||||||
changes: Record<string, browser.storage.StorageChange>,
|
|
||||||
area: string,
|
|
||||||
) => {
|
|
||||||
if (area !== "local" || !changes["plugin.global-search.settings"]) return;
|
if (area !== "local" || !changes["plugin.global-search.settings"]) return;
|
||||||
const next = changes["plugin.global-search.settings"].newValue as
|
const next = changes["plugin.global-search.settings"].newValue as
|
||||||
| { searchHotkey?: string }
|
| { searchHotkey?: string }
|
||||||
@@ -283,7 +280,7 @@ export async function mountSearchBar(titleElement: Element, api: GlobalSearchApi
|
|||||||
try {
|
try {
|
||||||
const { default: renderSvelte } = await import("@/interface/main");
|
const { default: renderSvelte } = await import("@/interface/main");
|
||||||
appRef.current = renderSvelte(
|
appRef.current = renderSvelte(
|
||||||
SearchBar,
|
toMountableComponent(SearchBar),
|
||||||
searchRoot.attachShadow({ mode: "open" }),
|
searchRoot.attachShadow({ mode: "open" }),
|
||||||
{
|
{
|
||||||
transparencyEffects: transparencyEnabled(),
|
transparencyEffects: transparencyEnabled(),
|
||||||
@@ -349,7 +346,7 @@ export function cleanupSearchBar(appRef: AppRef) {
|
|||||||
|
|
||||||
if (appRef.storageChangeHandler) {
|
if (appRef.storageChangeHandler) {
|
||||||
browser.storage.onChanged.removeListener(appRef.storageChangeHandler);
|
browser.storage.onChanged.removeListener(appRef.storageChangeHandler);
|
||||||
appRef.storageChangeHandler = null;
|
appRef.storageChangeHandler = undefined;
|
||||||
}
|
}
|
||||||
appRef.ownedTrigger = undefined;
|
appRef.ownedTrigger = undefined;
|
||||||
}
|
}
|
||||||
@@ -81,7 +81,13 @@ function cloneAssessmentActionItem(item: IndexItem & { metadata: AssessmentMetad
|
|||||||
);
|
);
|
||||||
try {
|
try {
|
||||||
const metadata = JSON.parse(JSON.stringify(item.metadata || {})) as AssessmentMetadata;
|
const metadata = JSON.parse(JSON.stringify(item.metadata || {})) as AssessmentMetadata;
|
||||||
return { itemClone: { ...item, metadata }, metadata };
|
return {
|
||||||
|
itemClone: {
|
||||||
|
...item,
|
||||||
|
metadata: metadata as unknown as AssessmentMetadata & Record<string, unknown>,
|
||||||
|
},
|
||||||
|
metadata,
|
||||||
|
};
|
||||||
} catch (e2) {
|
} catch (e2) {
|
||||||
console.warn("[Assessment Action] Failed to clone metadata, using direct access:", e2);
|
console.warn("[Assessment Action] Failed to clone metadata, using direct access:", e2);
|
||||||
const metadata = item.metadata || ({} as AssessmentMetadata);
|
const metadata = item.metadata || ({} as AssessmentMetadata);
|
||||||
@@ -91,7 +97,7 @@ function cloneAssessmentActionItem(item: IndexItem & { metadata: AssessmentMetad
|
|||||||
}
|
}
|
||||||
|
|
||||||
function createMetadataValueReader(metadata: AssessmentMetadata) {
|
function createMetadataValueReader(metadata: AssessmentMetadata) {
|
||||||
const bag = metadata as Record<string, unknown>;
|
const bag = metadata as unknown as Record<string, unknown>;
|
||||||
return (key: string, altKey?: string): unknown => {
|
return (key: string, altKey?: string): unknown => {
|
||||||
try {
|
try {
|
||||||
const value = bag[key];
|
const value = bag[key];
|
||||||
@@ -405,11 +411,11 @@ export const actionMap: Record<string, ActionHandler<Record<string, unknown>>> =
|
|||||||
if (button) {
|
if (button) {
|
||||||
(button as HTMLElement).click();
|
(button as HTMLElement).click();
|
||||||
}
|
}
|
||||||
}) as ActionHandler<Record<string, unknown>>,
|
}) as unknown as ActionHandler<Record<string, unknown>>,
|
||||||
|
|
||||||
assessment: (async (item: IndexItem & { metadata: AssessmentMetadata }) => {
|
assessment: (async (item: IndexItem & { metadata: AssessmentMetadata }) => {
|
||||||
await runAssessmentSearchAction(item);
|
await runAssessmentSearchAction(item);
|
||||||
}) as ActionHandler<Record<string, unknown>>,
|
}) as unknown as ActionHandler<Record<string, unknown>>,
|
||||||
|
|
||||||
subjectassessment: ((item: IndexItem) => {
|
subjectassessment: ((item: IndexItem) => {
|
||||||
navigateToHashRoute(`/assessments/${item.metadata.programme}:${item.metadata.subjectId}`);
|
navigateToHashRoute(`/assessments/${item.metadata.programme}:${item.metadata.subjectId}`);
|
||||||
|
|||||||
@@ -55,8 +55,8 @@ async function ensureSchemaCurrent(): Promise<void> {
|
|||||||
export { ensureSchemaCurrent };
|
export { ensureSchemaCurrent };
|
||||||
|
|
||||||
async function loadProgress<T = unknown>(jobId: string): Promise<T | undefined> {
|
async function loadProgress<T = unknown>(jobId: string): Promise<T | undefined> {
|
||||||
const rec = await get(META_STORE, `progress:${jobId}`);
|
const rec = (await get(META_STORE, `progress:${jobId}`)) as { progress?: T } | undefined;
|
||||||
return rec?.progress as T | undefined;
|
return rec?.progress;
|
||||||
}
|
}
|
||||||
|
|
||||||
async function saveProgress<T = unknown>(jobId: string, progress: T): Promise<void> {
|
async function saveProgress<T = unknown>(jobId: string, progress: T): Promise<void> {
|
||||||
@@ -84,7 +84,7 @@ function shouldRun(job: Job, lastRun?: number): boolean {
|
|||||||
}
|
}
|
||||||
|
|
||||||
function getLastRunMeta(jobId: string): Promise<number | undefined> {
|
function getLastRunMeta(jobId: string): Promise<number | undefined> {
|
||||||
return get(META_STORE, jobId).then((rec) => rec?.lastRun);
|
return get(META_STORE, jobId).then((rec) => (rec as { lastRun?: number } | undefined)?.lastRun);
|
||||||
}
|
}
|
||||||
|
|
||||||
function indexItemStorageKey(item: IndexItem): string {
|
function indexItemStorageKey(item: IndexItem): string {
|
||||||
@@ -343,7 +343,8 @@ export async function runIndexing(): Promise<void> {
|
|||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
|
|
||||||
const getStoredItems = async (storeId?: string) => await getAll(storeId ?? jobId);
|
const getStoredItems = async (storeId?: string) =>
|
||||||
|
(await getAll(storeId ?? jobId)) as IndexItem[];
|
||||||
const setStoredItems = async (items: IndexItem[], storeId?: string) => {
|
const setStoredItems = async (items: IndexItem[], storeId?: string) => {
|
||||||
const targetStore = storeId ?? jobId;
|
const targetStore = storeId ?? jobId;
|
||||||
await diffAndStoreItems(targetStore, items);
|
await diffAndStoreItems(targetStore, items);
|
||||||
@@ -385,7 +386,7 @@ export async function runIndexing(): Promise<void> {
|
|||||||
verboseDebug(`%c[Indexer] Running job "${jobId}"...`, "color: #4ea1ff");
|
verboseDebug(`%c[Indexer] Running job "${jobId}"...`, "color: #4ea1ff");
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const newItemsRaw = await job.run(ctx);
|
const newItemsRaw = (await job.run(ctx)) as IndexItem[];
|
||||||
const stored = await getStoredItems();
|
const stored = await getStoredItems();
|
||||||
|
|
||||||
let merged = mergeItems(stored, newItemsRaw);
|
let merged = mergeItems(stored, newItemsRaw);
|
||||||
|
|||||||
@@ -80,7 +80,7 @@ const fetchPastAssessments = async (student: number, subjects: OverviewSubject[]
|
|||||||
}
|
}
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
console.warn(
|
console.warn(
|
||||||
`[Assignments job] Failed to fetch past assessments for subject ${subject.code || subject.subject || "unknown"}:`,
|
`[Assignments job] Failed to fetch past assessments for subject ${subject.code || "unknown"}:`,
|
||||||
e,
|
e,
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
@@ -200,7 +200,7 @@ export const assignmentsJob: Job = {
|
|||||||
let score = 0;
|
let score = 0;
|
||||||
|
|
||||||
if (item.metadata.dueDate) {
|
if (item.metadata.dueDate) {
|
||||||
const dueDate = new Date(item.metadata.dueDate).getTime();
|
const dueDate = new Date(String(item.metadata.dueDate)).getTime();
|
||||||
const now = Date.now();
|
const now = Date.now();
|
||||||
const daysUntilDue = (dueDate - now) / (1000 * 60 * 60 * 24);
|
const daysUntilDue = (dueDate - now) / (1000 * 60 * 60 * 24);
|
||||||
|
|
||||||
@@ -225,6 +225,10 @@ export const assignmentsJob: Job = {
|
|||||||
const existingIds = new Set(existingItems.map((i) => i.id));
|
const existingIds = new Set(existingItems.map((i) => i.id));
|
||||||
|
|
||||||
const { id: student } = await getUserInfo();
|
const { id: student } = await getUserInfo();
|
||||||
|
if (student == null) {
|
||||||
|
verboseDebug("[Assignments job] No student id; skipping run");
|
||||||
|
return [];
|
||||||
|
}
|
||||||
|
|
||||||
verboseDebug(
|
verboseDebug(
|
||||||
"[Assignments job] Starting indexing - fetching all assessments (upcoming and past)...",
|
"[Assignments job] Starting indexing - fetching all assessments (upcoming and past)...",
|
||||||
@@ -258,7 +262,7 @@ export const assignmentsJob: Job = {
|
|||||||
let metaclass = a.metaclassID || a.metaclass;
|
let metaclass = a.metaclassID || a.metaclass;
|
||||||
|
|
||||||
if ((!programme || !metaclass) && a.code) {
|
if ((!programme || !metaclass) && a.code) {
|
||||||
const subjectInfo = subjectLookup.get(a.code);
|
const subjectInfo = subjectLookup.get(String(a.code));
|
||||||
if (subjectInfo) {
|
if (subjectInfo) {
|
||||||
programme = programme || subjectInfo.programme;
|
programme = programme || subjectInfo.programme;
|
||||||
metaclass = metaclass || subjectInfo.metaclass;
|
metaclass = metaclass || subjectInfo.metaclass;
|
||||||
|
|||||||
@@ -36,12 +36,12 @@ export const forumsJob: Job = {
|
|||||||
const items: IndexItem[] = [];
|
const items: IndexItem[] = [];
|
||||||
|
|
||||||
for (const forum of list.payload.forums) {
|
for (const forum of list.payload.forums) {
|
||||||
const id = forum.id.toString();
|
const id = String(forum.id);
|
||||||
if (existingIds.has(id)) continue;
|
if (existingIds.has(id)) continue;
|
||||||
|
|
||||||
items.push({
|
items.push({
|
||||||
id,
|
id,
|
||||||
text: forum.title,
|
text: String(forum.title ?? ""),
|
||||||
category: "forums",
|
category: "forums",
|
||||||
content: `${forum.title}`,
|
content: `${forum.title}`,
|
||||||
dateAdded: Date.now(),
|
dateAdded: Date.now(),
|
||||||
|
|||||||
@@ -207,8 +207,8 @@ async function processMessagesInParallel(
|
|||||||
let shouldStop = false;
|
let shouldStop = false;
|
||||||
|
|
||||||
const messagesToProcess = messages.filter((msg) => {
|
const messagesToProcess = messages.filter((msg) => {
|
||||||
const id = msg.id.toString();
|
const id = String(msg.id);
|
||||||
const messageDate = new Date(msg.date).getTime();
|
const messageDate = new Date(String(msg.date)).getTime();
|
||||||
|
|
||||||
if (messageDate < twoYearsAgo) {
|
if (messageDate < twoYearsAgo) {
|
||||||
//! older than 2 years ago
|
//! older than 2 years ago
|
||||||
@@ -238,19 +238,20 @@ async function processMessagesInParallel(
|
|||||||
const batchStartTime = Date.now();
|
const batchStartTime = Date.now();
|
||||||
|
|
||||||
const batchPromises = batch.map(async (msg) => {
|
const batchPromises = batch.map(async (msg) => {
|
||||||
const id = msg.id.toString();
|
const id = String(msg.id);
|
||||||
|
const messageId = Number(msg.id);
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const full = await fetchMessageContent(msg.id);
|
const full = await fetchMessageContent(messageId);
|
||||||
const responseTime = Date.now() - batchStartTime;
|
const responseTime = Date.now() - batchStartTime;
|
||||||
|
|
||||||
if (full && full.status === "200") {
|
if (full && full.status === "200") {
|
||||||
const item: IndexItem = {
|
const item: IndexItem = {
|
||||||
id,
|
id,
|
||||||
text: msg.subject,
|
text: String(msg.subject ?? ""),
|
||||||
category: "messages",
|
category: "messages",
|
||||||
content: `${htmlToPlainText(full.payload.contents)}\nFrom: ${msg.sender}`,
|
content: `${htmlToPlainText(full.payload.contents)}\nFrom: ${String(msg.sender ?? "")}`,
|
||||||
dateAdded: new Date(msg.date).getTime(),
|
dateAdded: new Date(String(msg.date)).getTime(),
|
||||||
metadata: {
|
metadata: {
|
||||||
messageId: msg.id,
|
messageId: msg.id,
|
||||||
author: msg.sender,
|
author: msg.sender,
|
||||||
@@ -290,7 +291,7 @@ async function processMessagesInParallel(
|
|||||||
batchSuccesses++;
|
batchSuccesses++;
|
||||||
} else {
|
} else {
|
||||||
if (updatedProgress.retryQueue.length < 50 && result.messageId) {
|
if (updatedProgress.retryQueue.length < 50 && result.messageId) {
|
||||||
updatedProgress.retryQueue.push(result.messageId);
|
updatedProgress.retryQueue.push(Number(result.messageId));
|
||||||
}
|
}
|
||||||
batchFailures++;
|
batchFailures++;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,4 +1,5 @@
|
|||||||
import type { Component } from "svelte";
|
import type { MountableSvelteComponent } from "@/types/mountableComponent";
|
||||||
|
import { toMountableComponent } from "@/types/mountableComponent";
|
||||||
import AssessmentItem from "../components/items/AssessmentItem.svelte";
|
import AssessmentItem from "../components/items/AssessmentItem.svelte";
|
||||||
import ForumItem from "../components/items/ForumItem.svelte";
|
import ForumItem from "../components/items/ForumItem.svelte";
|
||||||
import SubjectItem from "../components/items/SubjectItem.svelte";
|
import SubjectItem from "../components/items/SubjectItem.svelte";
|
||||||
@@ -7,26 +8,22 @@ import type { IndexItem } from "./types";
|
|||||||
import { jobs } from "./jobs";
|
import { jobs } from "./jobs";
|
||||||
import { loadDynamicItems } from "../utils/dynamicItems";
|
import { loadDynamicItems } from "../utils/dynamicItems";
|
||||||
|
|
||||||
export const renderComponentMap: Record<string, Component<Record<string, unknown>>> = {
|
export const renderComponentMap: Record<string, MountableSvelteComponent> = {
|
||||||
assessment: AssessmentItem,
|
assessment: toMountableComponent(AssessmentItem),
|
||||||
message: AssessmentItem,
|
message: toMountableComponent(AssessmentItem),
|
||||||
forum: ForumItem,
|
forum: toMountableComponent(ForumItem),
|
||||||
subject: SubjectItem,
|
subject: toMountableComponent(SubjectItem),
|
||||||
// New categories share a generic, category-aware row component to keep
|
course: toMountableComponent(GenericItem),
|
||||||
// the palette consistent without bespoke layouts for every job. The
|
notice: toMountableComponent(GenericItem),
|
||||||
// component reads `item.metadata.icon` and the `category` to pick a
|
document: toMountableComponent(GenericItem),
|
||||||
// sensible default visual treatment.
|
folio: toMountableComponent(GenericItem),
|
||||||
course: GenericItem,
|
portal: toMountableComponent(GenericItem),
|
||||||
notice: GenericItem,
|
report: toMountableComponent(GenericItem),
|
||||||
document: GenericItem,
|
goal: toMountableComponent(GenericItem),
|
||||||
folio: GenericItem,
|
passive: toMountableComponent(GenericItem),
|
||||||
portal: GenericItem,
|
|
||||||
report: GenericItem,
|
|
||||||
goal: GenericItem,
|
|
||||||
passive: GenericItem,
|
|
||||||
};
|
};
|
||||||
|
|
||||||
function resolveRenderComponent(item: IndexItem): Component<Record<string, unknown>> | undefined {
|
function resolveRenderComponent(item: IndexItem): MountableSvelteComponent | undefined {
|
||||||
const jobDef =
|
const jobDef =
|
||||||
jobs[item.category] ||
|
jobs[item.category] ||
|
||||||
Object.values(jobs).find((j) => j.id === item.category) ||
|
Object.values(jobs).find((j) => j.id === item.category) ||
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
import type { Component } from "svelte";
|
import type { MountableSvelteComponent } from "@/types/mountableComponent";
|
||||||
|
|
||||||
export interface IndexItem {
|
export interface IndexItem {
|
||||||
id: string;
|
id: string;
|
||||||
@@ -9,7 +9,7 @@ export interface IndexItem {
|
|||||||
metadata: Record<string, unknown>;
|
metadata: Record<string, unknown>;
|
||||||
actionId: string;
|
actionId: string;
|
||||||
renderComponentId: string;
|
renderComponentId: string;
|
||||||
renderComponent?: Component<Record<string, unknown>>;
|
renderComponent?: MountableSvelteComponent;
|
||||||
}
|
}
|
||||||
|
|
||||||
export type Frequency =
|
export type Frequency =
|
||||||
|
|||||||
@@ -289,8 +289,8 @@ export function searchDynamicItems(
|
|||||||
for (const item of dynamicIdToItemMap.values()) {
|
for (const item of dynamicIdToItemMap.values()) {
|
||||||
const textLower = item.text.toLowerCase();
|
const textLower = item.text.toLowerCase();
|
||||||
const contentLower = (item.content || "").toLowerCase();
|
const contentLower = (item.content || "").toLowerCase();
|
||||||
const subjectNameLower = (item.metadata?.subjectName || "").toLowerCase();
|
const subjectNameLower = String(item.metadata?.subjectName ?? "").toLowerCase();
|
||||||
const subjectCodeLower = (item.metadata?.subjectCode || "").toLowerCase();
|
const subjectCodeLower = String(item.metadata?.subjectCode ?? "").toLowerCase();
|
||||||
|
|
||||||
// Check if query appears anywhere in the text, content, or metadata
|
// Check if query appears anywhere in the text, content, or metadata
|
||||||
if (
|
if (
|
||||||
|
|||||||
@@ -38,7 +38,9 @@ function mergeLiveWithArchived(
|
|||||||
async function tryInjectArchived(archive: ArchiveMap): Promise<boolean> {
|
async function tryInjectArchived(archive: ArchiveMap): Promise<boolean> {
|
||||||
if (!document.querySelector(LIST_SELECTOR)) return false;
|
if (!document.querySelector(LIST_SELECTOR)) return false;
|
||||||
|
|
||||||
const state = await ReactFiber.find(LIST_SELECTOR).getState();
|
const state = (await ReactFiber.find(LIST_SELECTOR).getState()) as {
|
||||||
|
items?: unknown[];
|
||||||
|
} | null;
|
||||||
if (!state || !Array.isArray(state.items)) return false;
|
if (!state || !Array.isArray(state.items)) return false;
|
||||||
|
|
||||||
const liveItems = state.items as Record<string, unknown>[];
|
const liveItems = state.items as Record<string, unknown>[];
|
||||||
|
|||||||
@@ -1,6 +1,7 @@
|
|||||||
import type { Plugin } from "@/plugins/core/types";
|
import type { Plugin } from "@/plugins/core/types";
|
||||||
import { booleanSetting, componentSetting, defineSettings } from "@/plugins/core/settingsHelpers";
|
import { booleanSetting, componentSetting, defineSettings } from "@/plugins/core/settingsHelpers";
|
||||||
import ProfilePictureSetting from "./ProfilePictureSetting.svelte";
|
import ProfilePictureSetting from "./ProfilePictureSetting.svelte";
|
||||||
|
import { toMountableComponent } from "@/types/mountableComponent";
|
||||||
import { waitForElm } from "@/seqta/utils/waitForElm";
|
import { waitForElm } from "@/seqta/utils/waitForElm";
|
||||||
import browser from "@/lib/browser";
|
import browser from "@/lib/browser";
|
||||||
import { cloudAuth } from "@/seqta/utils/CloudAuth";
|
import { cloudAuth } from "@/seqta/utils/CloudAuth";
|
||||||
@@ -17,7 +18,7 @@ const settings = defineSettings({
|
|||||||
picture: componentSetting({
|
picture: componentSetting({
|
||||||
title: "Profile Picture",
|
title: "Profile Picture",
|
||||||
description: "Upload or remove your custom profile image",
|
description: "Upload or remove your custom profile image",
|
||||||
component: ProfilePictureSetting,
|
component: toMountableComponent(ProfilePictureSetting),
|
||||||
}),
|
}),
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|||||||
@@ -10,6 +10,7 @@ import {
|
|||||||
applyThemeCreatorLayout,
|
applyThemeCreatorLayout,
|
||||||
clearThemeCreatorLayout,
|
clearThemeCreatorLayout,
|
||||||
} from "@/plugins/built-in/themes/themeCreatorLayout";
|
} from "@/plugins/built-in/themes/themeCreatorLayout";
|
||||||
|
import { toMountableComponent } from "@/types/mountableComponent";
|
||||||
|
|
||||||
let themeCreatorSvelteApp: Parameters<typeof unmount>[0] | null = null;
|
let themeCreatorSvelteApp: Parameters<typeof unmount>[0] | null = null;
|
||||||
let currentWidthPx = 400;
|
let currentWidthPx = 400;
|
||||||
@@ -45,7 +46,7 @@ export async function OpenThemeCreator(themeID: string = "") {
|
|||||||
}
|
}
|
||||||
|
|
||||||
const shadow = themeCreatorDiv.attachShadow({ mode: "open" });
|
const shadow = themeCreatorDiv.attachShadow({ mode: "open" });
|
||||||
themeCreatorSvelteApp = renderSvelte(ThemeCreatorPage, shadow, {
|
themeCreatorSvelteApp = renderSvelte(toMountableComponent(ThemeCreatorPage), shadow, {
|
||||||
themeID: editingId,
|
themeID: editingId,
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|||||||
@@ -1,6 +1,7 @@
|
|||||||
import { booleanSetting, componentSetting, defineSettings } from "@/plugins/core/settingsHelpers";
|
import { booleanSetting, componentSetting, defineSettings } from "@/plugins/core/settingsHelpers";
|
||||||
import TimetableClassmatesAvatarsSwitch from "./TimetableClassmatesAvatarsSwitch.svelte";
|
import TimetableClassmatesAvatarsSwitch from "./TimetableClassmatesAvatarsSwitch.svelte";
|
||||||
import TimetableClassmatesSharing from "./TimetableClassmatesSharing.svelte";
|
import TimetableClassmatesSharing from "./TimetableClassmatesSharing.svelte";
|
||||||
|
import { toMountableComponent } from "@/types/mountableComponent";
|
||||||
|
|
||||||
export const timetableClassmatesSettings = defineSettings({
|
export const timetableClassmatesSettings = defineSettings({
|
||||||
enabled: booleanSetting({
|
enabled: booleanSetting({
|
||||||
@@ -12,12 +13,12 @@ export const timetableClassmatesSettings = defineSettings({
|
|||||||
title: "Show classmate avatars",
|
title: "Show classmate avatars",
|
||||||
description:
|
description:
|
||||||
"Display avatar stacks on lessons (saved per SEQTA site and student on this device)",
|
"Display avatar stacks on lessons (saved per SEQTA site and student on this device)",
|
||||||
component: TimetableClassmatesAvatarsSwitch,
|
component: toMountableComponent(TimetableClassmatesAvatarsSwitch),
|
||||||
}),
|
}),
|
||||||
sharing: componentSetting({
|
sharing: componentSetting({
|
||||||
title: "Classmate sharing",
|
title: "Classmate sharing",
|
||||||
description:
|
description:
|
||||||
"Encrypted class enrollments sync through BetterSEQTA Cloud. Your full timetable is never stored on our servers.",
|
"Encrypted class enrollments sync through BetterSEQTA Cloud. Your full timetable is never stored on our servers.",
|
||||||
component: TimetableClassmatesSharing,
|
component: toMountableComponent(TimetableClassmatesSharing),
|
||||||
}),
|
}),
|
||||||
});
|
});
|
||||||
@@ -1,4 +1,4 @@
|
|||||||
import type { Plugin } from "../../core/types";
|
import type { PluginAPI } from "../../core/types";
|
||||||
import { waitForElm } from "@/seqta/utils/waitForElm";
|
import { waitForElm } from "@/seqta/utils/waitForElm";
|
||||||
|
|
||||||
interface TimetableEntryData {
|
interface TimetableEntryData {
|
||||||
@@ -118,8 +118,13 @@ function showEditModal(
|
|||||||
roomInput?.focus();
|
roomInput?.focus();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
interface TimetableEditStorage extends Record<string, unknown> {
|
||||||
|
timetableOverrides?: TimetableOverrides;
|
||||||
|
timetableOverridesBySubject?: TimetableOverridesBySubject;
|
||||||
|
}
|
||||||
|
|
||||||
const timetableEditPlugin = {
|
const timetableEditPlugin = {
|
||||||
run: async (api: Parameters<NonNullable<Plugin["run"]>>[0]) => {
|
run: async (api: PluginAPI<Record<string, never>, TimetableEditStorage>) => {
|
||||||
await api.storage.loaded;
|
await api.storage.loaded;
|
||||||
|
|
||||||
let observer: MutationObserver | null = null;
|
let observer: MutationObserver | null = null;
|
||||||
|
|||||||
@@ -51,7 +51,7 @@ function createSEQTAAPI(): SEQTAAPI {
|
|||||||
}
|
}
|
||||||
|
|
||||||
function createSettingsAPI<T extends PluginSettings>(
|
function createSettingsAPI<T extends PluginSettings>(
|
||||||
plugin: Plugin<T>,
|
plugin: Pick<Plugin<T>, "id" | "settings" | "disableToggle">,
|
||||||
): {
|
): {
|
||||||
settings: SettingsAPI<T> & { loaded: Promise<void> };
|
settings: SettingsAPI<T> & { loaded: Promise<void> };
|
||||||
dispose: () => void;
|
dispose: () => void;
|
||||||
@@ -59,11 +59,7 @@ function createSettingsAPI<T extends PluginSettings>(
|
|||||||
const storageKey = `plugin.${plugin.id}.settings`;
|
const storageKey = `plugin.${plugin.id}.settings`;
|
||||||
const listeners = new Map<keyof T, Set<(value: SettingValue<T[keyof T]>) => void>>();
|
const listeners = new Map<keyof T, Set<(value: SettingValue<T[keyof T]>) => void>>();
|
||||||
|
|
||||||
const settingsWithMeta: Record<string, unknown> & {
|
const backing: Record<string, unknown> = {
|
||||||
onChange: SettingsAPI<T>["onChange"];
|
|
||||||
offChange: SettingsAPI<T>["offChange"];
|
|
||||||
loaded: Promise<void>;
|
|
||||||
} = {
|
|
||||||
onChange: <K extends keyof T>(key: K, callback: (value: SettingValue<T[K]>) => void) => {
|
onChange: <K extends keyof T>(key: K, callback: (value: SettingValue<T[K]>) => void) => {
|
||||||
if (!listeners.has(key)) {
|
if (!listeners.has(key)) {
|
||||||
listeners.set(key, new Set());
|
listeners.set(key, new Set());
|
||||||
@@ -78,16 +74,15 @@ function createSettingsAPI<T extends PluginSettings>(
|
|||||||
offChange: <K extends keyof T>(key: K, callback: (value: SettingValue<T[K]>) => void) => {
|
offChange: <K extends keyof T>(key: K, callback: (value: SettingValue<T[K]>) => void) => {
|
||||||
listeners.get(key)?.delete(callback);
|
listeners.get(key)?.delete(callback);
|
||||||
},
|
},
|
||||||
loaded: Promise.resolve(), // will be replaced below
|
loaded: Promise.resolve(),
|
||||||
};
|
};
|
||||||
|
|
||||||
for (const key in plugin.settings) {
|
for (const key in plugin.settings) {
|
||||||
if (plugin.settings[key].type !== "component" && plugin.settings[key].type !== "button") {
|
if (plugin.settings[key].type !== "component" && plugin.settings[key].type !== "button") {
|
||||||
settingsWithMeta[key] = plugin.settings[key].default;
|
backing[key] = plugin.settings[key].default;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Load stored settings and override defaults
|
|
||||||
const loaded = (async () => {
|
const loaded = (async () => {
|
||||||
try {
|
try {
|
||||||
const allSettings = settingsState.getAll() as unknown as Record<string, unknown>;
|
const allSettings = settingsState.getAll() as unknown as Record<string, unknown>;
|
||||||
@@ -96,10 +91,11 @@ function createSettingsAPI<T extends PluginSettings>(
|
|||||||
>;
|
>;
|
||||||
if (storedSettings) {
|
if (storedSettings) {
|
||||||
for (const key in storedSettings) {
|
for (const key in storedSettings) {
|
||||||
if (key in settingsWithMeta) {
|
if (!(key in backing)) continue;
|
||||||
settingsWithMeta[key] = storedSettings[key];
|
const value = storedSettings[key as keyof T];
|
||||||
listeners.get(key as keyof T)?.forEach((cb) => cb(storedSettings[key]));
|
if (value === undefined) continue;
|
||||||
}
|
backing[key] = value;
|
||||||
|
listeners.get(key as keyof T)?.forEach((cb) => cb(value));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
@@ -107,7 +103,7 @@ function createSettingsAPI<T extends PluginSettings>(
|
|||||||
}
|
}
|
||||||
})();
|
})();
|
||||||
|
|
||||||
settingsWithMeta.loaded = loaded;
|
backing.loaded = loaded;
|
||||||
|
|
||||||
const handleSettingsChange = (newValue: unknown) => {
|
const handleSettingsChange = (newValue: unknown) => {
|
||||||
if (!newValue || typeof newValue !== "object") return;
|
if (!newValue || typeof newValue !== "object") return;
|
||||||
@@ -115,8 +111,10 @@ function createSettingsAPI<T extends PluginSettings>(
|
|||||||
const newSettings = newValue as Partial<Record<keyof T, SettingValue<T[keyof T]>>>;
|
const newSettings = newValue as Partial<Record<keyof T, SettingValue<T[keyof T]>>>;
|
||||||
for (const key in newSettings) {
|
for (const key in newSettings) {
|
||||||
const typedKey = key as keyof T;
|
const typedKey = key as keyof T;
|
||||||
settingsWithMeta[typedKey] = newSettings[typedKey];
|
const value = newSettings[typedKey];
|
||||||
listeners.get(typedKey)?.forEach((cb) => cb(newSettings[typedKey]));
|
if (value === undefined) continue;
|
||||||
|
backing[key] = value;
|
||||||
|
listeners.get(typedKey)?.forEach((cb) => cb(value));
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -126,22 +124,23 @@ function createSettingsAPI<T extends PluginSettings>(
|
|||||||
settingsState.unregister(storageKey as keyof SettingsState, handleSettingsChange);
|
settingsState.unregister(storageKey as keyof SettingsState, handleSettingsChange);
|
||||||
};
|
};
|
||||||
|
|
||||||
const proxy = new Proxy(settingsWithMeta, {
|
const proxy = new Proxy(backing, {
|
||||||
get(target, prop) {
|
get(target, prop) {
|
||||||
return target[prop];
|
if (typeof prop === "symbol") return undefined;
|
||||||
|
return target[prop as string];
|
||||||
},
|
},
|
||||||
set(target, prop, value) {
|
set(target, prop, value) {
|
||||||
if (["onChange", "offChange", "loaded"].includes(prop as string)) return false;
|
if (typeof prop === "symbol") return false;
|
||||||
|
const key = prop as string;
|
||||||
|
if (["onChange", "offChange", "loaded"].includes(key)) return false;
|
||||||
|
|
||||||
target[prop] = value;
|
target[key] = value;
|
||||||
|
|
||||||
// Reconstruct just the data keys for storage (excluding metadata methods)
|
|
||||||
const dataToStore: Record<string, unknown> = {};
|
const dataToStore: Record<string, unknown> = {};
|
||||||
for (const key in plugin.settings) {
|
for (const settingKey in plugin.settings) {
|
||||||
dataToStore[key] = target[key];
|
dataToStore[settingKey] = target[settingKey];
|
||||||
}
|
}
|
||||||
|
|
||||||
// Preserve enabled flag managed separately for disableToggle plugins
|
|
||||||
if (plugin.disableToggle) {
|
if (plugin.disableToggle) {
|
||||||
const allSettings = settingsState.getAll() as Record<string, unknown>;
|
const allSettings = settingsState.getAll() as Record<string, unknown>;
|
||||||
const existing = allSettings[storageKey] as { enabled?: boolean } | undefined;
|
const existing = allSettings[storageKey] as { enabled?: boolean } | undefined;
|
||||||
@@ -152,7 +151,7 @@ function createSettingsAPI<T extends PluginSettings>(
|
|||||||
|
|
||||||
browser.storage.local.set({ [storageKey]: dataToStore });
|
browser.storage.local.set({ [storageKey]: dataToStore });
|
||||||
|
|
||||||
listeners.get(prop as keyof T)?.forEach((cb) => cb(value));
|
listeners.get(key as keyof T)?.forEach((cb) => cb(value as SettingValue<T[keyof T]>));
|
||||||
return true;
|
return true;
|
||||||
},
|
},
|
||||||
}) as SettingsAPI<T> & { loaded: Promise<void> };
|
}) as SettingsAPI<T> & { loaded: Promise<void> };
|
||||||
@@ -209,17 +208,17 @@ function createStorageAPI<T extends Record<string, unknown> = Record<string, unk
|
|||||||
if (!listeners.has(key as string)) {
|
if (!listeners.has(key as string)) {
|
||||||
listeners.set(key as string, new Set());
|
listeners.set(key as string, new Set());
|
||||||
}
|
}
|
||||||
listeners.get(key as string)!.add(callback);
|
listeners.get(key as string)!.add(callback as (value: unknown) => void);
|
||||||
return {
|
return {
|
||||||
unregister: () => {
|
unregister: () => {
|
||||||
listeners.get(key as string)?.delete(callback);
|
listeners.get(key as string)?.delete(callback as (value: unknown) => void);
|
||||||
},
|
},
|
||||||
};
|
};
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
if (prop === "offChange") {
|
if (prop === "offChange") {
|
||||||
return (key: keyof T, callback: (value: T[keyof T]) => void) => {
|
return (key: keyof T, callback: (value: T[keyof T]) => void) => {
|
||||||
listeners.get(key as string)?.delete(callback);
|
listeners.get(key as string)?.delete(callback as (value: unknown) => void);
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
if (prop === "loaded") {
|
if (prop === "loaded") {
|
||||||
|
|||||||
@@ -118,7 +118,7 @@ export class PluginManager {
|
|||||||
if (this.plugins.has(plugin.id)) {
|
if (this.plugins.has(plugin.id)) {
|
||||||
throw new Error(`Plugin with id "${plugin.id}" is already registered`);
|
throw new Error(`Plugin with id "${plugin.id}" is already registered`);
|
||||||
}
|
}
|
||||||
this.plugins.set(plugin.id, plugin);
|
this.plugins.set(plugin.id, plugin as unknown as Plugin);
|
||||||
}
|
}
|
||||||
|
|
||||||
public async startPlugin(pluginId: string): Promise<void> {
|
public async startPlugin(pluginId: string): Promise<void> {
|
||||||
@@ -328,10 +328,10 @@ export class PluginManager {
|
|||||||
let result: Record<string, unknown>;
|
let result: Record<string, unknown>;
|
||||||
if (settingObj.type === "button" || settingObj.type === "component") {
|
if (settingObj.type === "button" || settingObj.type === "component") {
|
||||||
// For button or component, keep the functions
|
// For button or component, keep the functions
|
||||||
result = { ...(settingObj as Record<string, unknown>) };
|
result = { ...(settingObj as unknown as Record<string, unknown>) };
|
||||||
} else {
|
} else {
|
||||||
result = Object.fromEntries(
|
result = Object.fromEntries(
|
||||||
Object.entries(settingObj as Record<string, unknown>).filter(
|
Object.entries(settingObj as unknown as Record<string, unknown>).filter(
|
||||||
([, value]) => typeof value !== "function",
|
([, value]) => typeof value !== "function",
|
||||||
),
|
),
|
||||||
);
|
);
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
import ReactFiber from "@/seqta/utils/ReactFiber";
|
import ReactFiber from "@/seqta/utils/ReactFiber";
|
||||||
|
|
||||||
import type { Component } from "svelte";
|
import type { MountableSvelteComponent } from "@/types/mountableComponent";
|
||||||
|
|
||||||
export interface BooleanSetting {
|
export interface BooleanSetting {
|
||||||
type: "boolean";
|
type: "boolean";
|
||||||
@@ -54,7 +54,7 @@ export interface ComponentSetting {
|
|||||||
type: "component";
|
type: "component";
|
||||||
title: string;
|
title: string;
|
||||||
description?: string;
|
description?: string;
|
||||||
component: Component<Record<string, unknown>>;
|
component: MountableSvelteComponent;
|
||||||
}
|
}
|
||||||
|
|
||||||
export type PluginSetting =
|
export type PluginSetting =
|
||||||
@@ -139,7 +139,7 @@ export interface PluginAPI<T extends PluginSettings, S = unknown> {
|
|||||||
|
|
||||||
export type PluginRunResult = void | (() => void);
|
export type PluginRunResult = void | (() => void);
|
||||||
|
|
||||||
export interface Plugin<T extends PluginSettings = PluginSettings, S = unknown> {
|
export interface Plugin<T extends PluginSettings = PluginSettings, S = Record<string, unknown>> {
|
||||||
id: string;
|
id: string;
|
||||||
name: string;
|
name: string;
|
||||||
description: string;
|
description: string;
|
||||||
|
|||||||
@@ -596,7 +596,7 @@ export function tryLoad() {
|
|||||||
});
|
});
|
||||||
|
|
||||||
waitForElm(".code", true, 50).then((elm: Element) => {
|
waitForElm(".code", true, 50).then((elm: Element) => {
|
||||||
if (!elm.innerText.includes("BetterSEQTA")) LoadPageElements();
|
if (!(elm as HTMLElement).innerText.includes("BetterSEQTA")) LoadPageElements();
|
||||||
});
|
});
|
||||||
|
|
||||||
updateIframesWithDarkMode();
|
updateIframesWithDarkMode();
|
||||||
@@ -821,7 +821,9 @@ export function init() {
|
|||||||
iframe.focus();
|
iframe.focus();
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
const ckeditor = getCkeditorGlobal();
|
const ckeditor = getCkeditorGlobal() as
|
||||||
|
| { instances?: { editor1?: { focus: () => void } } }
|
||||||
|
| undefined;
|
||||||
if (ckeditor?.instances?.editor1) {
|
if (ckeditor?.instances?.editor1) {
|
||||||
try {
|
try {
|
||||||
ckeditor.instances.editor1.focus();
|
ckeditor.instances.editor1.focus();
|
||||||
|
|||||||
@@ -141,26 +141,10 @@ async function handleUserInfoAndStudentData() {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
function updateUserInfo(info: {
|
function updateUserInfo(info: Awaited<ReturnType<typeof getUserInfo>>) {
|
||||||
basic: boolean;
|
|
||||||
clientIP: string[] | null;
|
|
||||||
email: string | null;
|
|
||||||
id: number | null;
|
|
||||||
lastAccessedTime: number | null;
|
|
||||||
meta: {
|
|
||||||
code: string | null;
|
|
||||||
governmentID: string | null;
|
|
||||||
};
|
|
||||||
personUUID: string | null;
|
|
||||||
status: number | null;
|
|
||||||
synergeticCommunityUrl: string | null;
|
|
||||||
type: string | null;
|
|
||||||
userCode: string | null;
|
|
||||||
userDesc: string | null;
|
|
||||||
userName: string | null;
|
|
||||||
}) {
|
|
||||||
const titlebar = document.getElementsByClassName("titlebar")[0];
|
const titlebar = document.getElementsByClassName("titlebar")[0];
|
||||||
const metadata = [info.meta.code, info.meta.governmentID]
|
const meta = info.meta as { code?: string | null; governmentID?: string | null } | undefined;
|
||||||
|
const metadata = [meta?.code, meta?.governmentID]
|
||||||
.filter((value): value is string => Boolean(value))
|
.filter((value): value is string => Boolean(value))
|
||||||
.join(" // ");
|
.join(" // ");
|
||||||
const displayName = info.userDesc || info.userName || "";
|
const displayName = info.userDesc || info.userName || "";
|
||||||
@@ -202,10 +186,10 @@ async function updateStudentInfo(
|
|||||||
students: StudentPerson[],
|
students: StudentPerson[],
|
||||||
info: Awaited<ReturnType<typeof getUserInfo>>,
|
info: Awaited<ReturnType<typeof getUserInfo>>,
|
||||||
) {
|
) {
|
||||||
|
const userDesc = info.userDesc ?? "";
|
||||||
const index = students.findIndex(
|
const index = students.findIndex(
|
||||||
(person) =>
|
(person) =>
|
||||||
person.firstname == info.userDesc.split(" ")[0] &&
|
person.firstname == userDesc.split(" ")[0] && person.surname == userDesc.split(" ")[1],
|
||||||
person.surname == info.userDesc.split(" ")[1],
|
|
||||||
);
|
);
|
||||||
|
|
||||||
const houseelement = document.getElementsByClassName("userInfohouse")[0] as
|
const houseelement = document.getElementsByClassName("userInfohouse")[0] as
|
||||||
@@ -229,8 +213,8 @@ async function updateStudentInfo(
|
|||||||
// Invalid color format, leave text color as default
|
// Invalid color format, leave text color as default
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
} else if (student.year) {
|
} else if (student.year != null && student.year !== "") {
|
||||||
text = student.year;
|
text = String(student.year);
|
||||||
}
|
}
|
||||||
|
|
||||||
houseelement.innerText = text;
|
houseelement.innerText = text;
|
||||||
|
|||||||
@@ -32,8 +32,9 @@ export default function ColorLuminance(color: string, lum = 0) {
|
|||||||
|
|
||||||
// Adjust luminance for each unique color stop
|
// Adjust luminance for each unique color stop
|
||||||
for (const colorStop of uniqueColorSet) {
|
for (const colorStop of uniqueColorSet) {
|
||||||
const adjustedColor = adjustLuminance(colorStop, lum);
|
const stop = String(colorStop);
|
||||||
gradient = gradient.replace(new RegExp(colorStop as string, "gi"), adjustedColor);
|
const adjustedColor = adjustLuminance(stop, lum);
|
||||||
|
gradient = gradient.replace(new RegExp(stop, "gi"), adjustedColor);
|
||||||
}
|
}
|
||||||
|
|
||||||
return gradient;
|
return gradient;
|
||||||
|
|||||||
@@ -160,7 +160,11 @@ function applyColorsWith(selectedColor: string) {
|
|||||||
"--better-light": selectedColor === "#ffffff" ? "#b7b7b7" : ColorLuminance(selectedColor, 0.95),
|
"--better-light": selectedColor === "#ffffff" ? "#b7b7b7" : ColorLuminance(selectedColor, 0.95),
|
||||||
};
|
};
|
||||||
|
|
||||||
applyProperties({ ...commonProps, ...modeProps, ...dynamicProps });
|
const cssVars: Record<string, string> = { ...commonProps, ...dynamicProps };
|
||||||
|
for (const [key, value] of Object.entries(modeProps)) {
|
||||||
|
if (value != null) cssVars[key] = value;
|
||||||
|
}
|
||||||
|
applyProperties(cssVars);
|
||||||
|
|
||||||
if (settingsState.selectedTheme) {
|
if (settingsState.selectedTheme) {
|
||||||
const channels = getRepresentativeRgbChannels(selectedColor);
|
const channels = getRepresentativeRgbChannels(selectedColor);
|
||||||
|
|||||||
@@ -5,6 +5,7 @@ export function lightenAndPaleColor(inputColor: string, lightenFactor = 0.75, pa
|
|||||||
|
|
||||||
if (inputColor.includes("gradient")) {
|
if (inputColor.includes("gradient")) {
|
||||||
const baseColor = findMatchingColor(inputColor);
|
const baseColor = findMatchingColor(inputColor);
|
||||||
|
if (!baseColor) return;
|
||||||
|
|
||||||
return lightenAndPaleColor(baseColor, lightenFactor, paleFactor);
|
return lightenAndPaleColor(baseColor, lightenFactor, paleFactor);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -749,47 +749,47 @@ export function getMockNotices() {
|
|||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
type MockGradedAssessment = {
|
||||||
|
id: number;
|
||||||
|
title: string;
|
||||||
|
code: string;
|
||||||
|
due: string;
|
||||||
|
percentage?: number;
|
||||||
|
results?: { percentage?: number };
|
||||||
|
programmeID: number;
|
||||||
|
metaclassID: number;
|
||||||
|
};
|
||||||
|
|
||||||
export function getMockGradeAnalyticsData() {
|
export function getMockGradeAnalyticsData() {
|
||||||
const { assessments } = getMockAssessmentsData();
|
const { assessments } = getMockAssessmentsData();
|
||||||
return assessments
|
return (assessments as MockGradedAssessment[])
|
||||||
.filter((a: { percentage?: number; results?: { percentage?: number } }) => {
|
.filter((a) => {
|
||||||
const pct = a.percentage ?? a.results?.percentage;
|
const pct = a.percentage ?? a.results?.percentage;
|
||||||
return pct != null;
|
return pct != null;
|
||||||
})
|
})
|
||||||
.map(
|
.map((a) => {
|
||||||
(a: {
|
const finalGrade = a.percentage ?? a.results?.percentage ?? 0;
|
||||||
id: number;
|
return {
|
||||||
title: string;
|
id: a.id,
|
||||||
code: string;
|
title: a.title,
|
||||||
due: string;
|
subject: a.code,
|
||||||
percentage?: number;
|
status: "MARKS_RELEASED" as const,
|
||||||
results?: { percentage?: number };
|
due: a.due,
|
||||||
programmeID: number;
|
code: a.code,
|
||||||
metaclassID: number;
|
metaclassID: a.metaclassID,
|
||||||
}) => {
|
programmeID: a.programmeID,
|
||||||
const finalGrade = a.percentage ?? a.results?.percentage ?? 0;
|
graded: true,
|
||||||
return {
|
overdue: false,
|
||||||
id: a.id,
|
hasFeedback: false,
|
||||||
title: a.title,
|
expectationsEnabled: false,
|
||||||
subject: a.code,
|
expectationsCompleted: false,
|
||||||
status: "MARKS_RELEASED" as const,
|
reflectionsEnabled: false,
|
||||||
due: a.due,
|
reflectionsCompleted: false,
|
||||||
code: a.code,
|
availability: "",
|
||||||
metaclassID: a.metaclassID,
|
finalGrade,
|
||||||
programmeID: a.programmeID,
|
letterGrade: finalGrade >= 85 ? "A" : finalGrade >= 70 ? "B" : "C",
|
||||||
graded: true,
|
};
|
||||||
overdue: false,
|
});
|
||||||
hasFeedback: false,
|
|
||||||
expectationsEnabled: false,
|
|
||||||
expectationsCompleted: false,
|
|
||||||
reflectionsEnabled: false,
|
|
||||||
reflectionsCompleted: false,
|
|
||||||
availability: "",
|
|
||||||
finalGrade,
|
|
||||||
letterGrade: finalGrade >= 85 ? "A" : finalGrade >= 70 ? "B" : "C",
|
|
||||||
};
|
|
||||||
},
|
|
||||||
);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
export function getMockAssessmentsData() {
|
export function getMockAssessmentsData() {
|
||||||
|
|||||||
@@ -32,7 +32,7 @@ export function FilterUpcomingAssessments(subjectoptions: Record<string, boolean
|
|||||||
(element.parentNode!.parentNode! as HTMLElement).classList.add("hidden");
|
(element.parentNode!.parentNode! as HTMLElement).classList.add("hidden");
|
||||||
} else {
|
} else {
|
||||||
AddPlaceHolderToParent(
|
AddPlaceHolderToParent(
|
||||||
element.parentNode!.parentNode,
|
element.parentNode!.parentNode as HTMLElement,
|
||||||
element.parentNode!.querySelectorAll(".hidden").length,
|
element.parentNode!.querySelectorAll(".hidden").length,
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -94,8 +94,9 @@ export async function getAdaptiveColour(): Promise<string | null> {
|
|||||||
let userId: number;
|
let userId: number;
|
||||||
try {
|
try {
|
||||||
const userInfo = await getUserInfo();
|
const userInfo = await getUserInfo();
|
||||||
userId = userInfo?.id;
|
const id = userInfo?.id;
|
||||||
if (typeof userId !== "number") return null;
|
if (typeof id !== "number") return null;
|
||||||
|
userId = id;
|
||||||
} catch {
|
} catch {
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,4 +1,5 @@
|
|||||||
import stringToHTML from "../stringToHTML";
|
import stringToHTML from "../stringToHTML";
|
||||||
|
import type { CustomShortcut } from "@/types/storage";
|
||||||
|
|
||||||
function isSafeShortcutHref(url: string): boolean {
|
function isSafeShortcutHref(url: string): boolean {
|
||||||
if (typeof url !== "string" || !url.trim()) return false;
|
if (typeof url !== "string" || !url.trim()) return false;
|
||||||
@@ -10,7 +11,7 @@ function isSafeShortcutHref(url: string): boolean {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
export function CreateCustomShortcutDiv(element: HTMLElement) {
|
export function CreateCustomShortcutDiv(element: CustomShortcut) {
|
||||||
const container = document.getElementById("shortcuts");
|
const container = document.getElementById("shortcuts");
|
||||||
if (!container) return;
|
if (!container) return;
|
||||||
|
|
||||||
|
|||||||
@@ -1,9 +1,9 @@
|
|||||||
export default function debounce<T extends (...args: unknown[]) => void>(
|
export default function debounce<A extends unknown[]>(
|
||||||
fn: T,
|
fn: (...args: A) => void,
|
||||||
delay: number,
|
delay: number,
|
||||||
): (...args: Parameters<T>) => void {
|
): (...args: A) => void {
|
||||||
let timeout: ReturnType<typeof setTimeout>;
|
let timeout: ReturnType<typeof setTimeout>;
|
||||||
return function (this: ThisParameterType<T>, ...args: Parameters<T>) {
|
return function (this: unknown, ...args: A) {
|
||||||
clearTimeout(timeout);
|
clearTimeout(timeout);
|
||||||
timeout = setTimeout(() => fn.apply(this, args), delay);
|
timeout = setTimeout(() => fn.apply(this, args), delay);
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -11,15 +11,19 @@ const handleNotificationClick = async (target: HTMLElement) => {
|
|||||||
const buttonType = notificationItem.getAttribute("data-type");
|
const buttonType = notificationItem.getAttribute("data-type");
|
||||||
if (buttonType !== "message") return;
|
if (buttonType !== "message") return;
|
||||||
|
|
||||||
const notificationList = await ReactFiber.find('[class*="notifications__list___"]').getState();
|
|
||||||
const buttonId = notificationItem.getAttribute("data-id");
|
|
||||||
if (!buttonId) return;
|
|
||||||
|
|
||||||
type NotificationListItem = {
|
type NotificationListItem = {
|
||||||
notificationID?: number;
|
notificationID?: number;
|
||||||
message?: { messageID?: number };
|
message?: { messageID?: number };
|
||||||
};
|
};
|
||||||
const matchingNotification = (notificationList.items as NotificationListItem[]).find(
|
const notificationList = (await ReactFiber.find(
|
||||||
|
'[class*="notifications__list___"]',
|
||||||
|
).getState()) as {
|
||||||
|
items?: NotificationListItem[];
|
||||||
|
};
|
||||||
|
const buttonId = notificationItem.getAttribute("data-id");
|
||||||
|
if (!buttonId) return;
|
||||||
|
|
||||||
|
const matchingNotification = notificationList.items?.find(
|
||||||
(item) => item.notificationID === parseInt(buttonId, 10),
|
(item) => item.notificationID === parseInt(buttonId, 10),
|
||||||
);
|
);
|
||||||
|
|
||||||
|
|||||||
@@ -7,6 +7,7 @@ import { isMenuOptionsOpen } from "@/seqta/utils/openers/menuOptionsState";
|
|||||||
import sendThemeUpdate from "@/seqta/utils/sendThemeUpdate";
|
import sendThemeUpdate from "@/seqta/utils/sendThemeUpdate";
|
||||||
import hideSensitiveContent from "@/seqta/ui/dev/hideSensitiveContent";
|
import hideSensitiveContent from "@/seqta/ui/dev/hideSensitiveContent";
|
||||||
import type { ThemeManager } from "@/plugins/built-in/themes/theme-manager";
|
import type { ThemeManager } from "@/plugins/built-in/themes/theme-manager";
|
||||||
|
import type { LoadedCustomTheme } from "@/types/CustomThemes";
|
||||||
|
|
||||||
let themeManagerPromise: Promise<ThemeManager> | null = null;
|
let themeManagerPromise: Promise<ThemeManager> | null = null;
|
||||||
|
|
||||||
@@ -56,7 +57,7 @@ export class MessageHandler {
|
|||||||
const save = async () => {
|
const save = async () => {
|
||||||
const themeManager = await getThemeManager();
|
const themeManager = await getThemeManager();
|
||||||
await themeManager.saveTheme({
|
await themeManager.saveTheme({
|
||||||
...request.body,
|
...(request.body as LoadedCustomTheme),
|
||||||
userEdited: true,
|
userEdited: true,
|
||||||
});
|
});
|
||||||
if (request.body?.enableTheme) {
|
if (request.body?.enableTheme) {
|
||||||
@@ -68,7 +69,9 @@ export class MessageHandler {
|
|||||||
void save();
|
void save();
|
||||||
} else {
|
} else {
|
||||||
void getThemeManager().then((themeManager) => {
|
void getThemeManager().then((themeManager) => {
|
||||||
themeManager.updatePreview(request.body);
|
if (request.body) {
|
||||||
|
themeManager.updatePreview(request.body as Partial<LoadedCustomTheme>);
|
||||||
|
}
|
||||||
sendResponse({ status: "success" });
|
sendResponse({ status: "success" });
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,5 +1,7 @@
|
|||||||
/** @jest-environment jsdom */
|
/** @jest-environment jsdom */
|
||||||
|
|
||||||
|
type MockBrowser = typeof import("@/test/mocks/browser").default;
|
||||||
|
|
||||||
describe("master extension setting", () => {
|
describe("master extension setting", () => {
|
||||||
afterEach(() => {
|
afterEach(() => {
|
||||||
jest.useRealTimers();
|
jest.useRealTimers();
|
||||||
@@ -9,10 +11,10 @@ describe("master extension setting", () => {
|
|||||||
"persists %s and queued preferences before reloading SEQTA tabs",
|
"persists %s and queued preferences before reloading SEQTA tabs",
|
||||||
async (enabled) => {
|
async (enabled) => {
|
||||||
jest.useFakeTimers();
|
jest.useFakeTimers();
|
||||||
let browser: typeof import("@/lib/browser").default;
|
let browser!: MockBrowser;
|
||||||
let settings: typeof import("./SettingsState");
|
let settings!: typeof import("./SettingsState");
|
||||||
jest.isolateModules(() => {
|
jest.isolateModules(() => {
|
||||||
browser = require("@/lib/browser").default;
|
browser = require("@/lib/browser").default as MockBrowser;
|
||||||
settings = require("./SettingsState");
|
settings = require("./SettingsState");
|
||||||
});
|
});
|
||||||
await browser.storage.local.set({ onoff: !enabled });
|
await browser.storage.local.set({ onoff: !enabled });
|
||||||
@@ -24,7 +26,7 @@ describe("master extension setting", () => {
|
|||||||
(patch: Record<string, unknown>) =>
|
(patch: Record<string, unknown>) =>
|
||||||
new Promise<void>((resolve) => {
|
new Promise<void>((resolve) => {
|
||||||
finishWrite = async () => {
|
finishWrite = async () => {
|
||||||
await originalSet(patch);
|
await originalSet?.(patch);
|
||||||
resolve();
|
resolve();
|
||||||
};
|
};
|
||||||
}),
|
}),
|
||||||
|
|||||||
@@ -22,15 +22,25 @@ export class StorageChangeHandler {
|
|||||||
settingsState.register("adaptiveThemeGradient", () => void updateAllColors());
|
settingsState.register("adaptiveThemeGradient", () => void updateAllColors());
|
||||||
settingsState.register("adaptiveThemeColourTransition", () => void updateAllColors());
|
settingsState.register("adaptiveThemeColourTransition", () => void updateAllColors());
|
||||||
settingsState.register("selectedTheme", () => void updateAllColors());
|
settingsState.register("selectedTheme", () => void updateAllColors());
|
||||||
settingsState.register("DarkMode", this.handleDarkModeChange.bind(this));
|
settingsState.register("DarkMode", () => this.handleDarkModeChange());
|
||||||
settingsState.register("shortcuts", this.handleShortcutsChange.bind(this));
|
settingsState.register("shortcuts", (newValue) =>
|
||||||
settingsState.register("customshortcuts", this.handleCustomShortcutsChange.bind(this));
|
this.handleShortcutsChange(newValue as { enabled: boolean; name: string }[] | undefined),
|
||||||
settingsState.register("transparencyEffects", this.handleTransparencyEffectsChange.bind(this));
|
);
|
||||||
|
settingsState.register("customshortcuts", (newValue) =>
|
||||||
|
this.handleCustomShortcutsChange(newValue as CustomShortcut[] | undefined),
|
||||||
|
);
|
||||||
|
settingsState.register("transparencyEffects", (newValue) =>
|
||||||
|
this.handleTransparencyEffectsChange(newValue as boolean),
|
||||||
|
);
|
||||||
settingsState.register("performanceMode", () => syncPerformanceModeEffects());
|
settingsState.register("performanceMode", () => syncPerformanceModeEffects());
|
||||||
settingsState.register("performanceModePluginOverrides", () => syncPerformanceModeEffects());
|
settingsState.register("performanceModePluginOverrides", () => syncPerformanceModeEffects());
|
||||||
settingsState.register("subjectfilters", FilterUpcomingAssessments.bind(this));
|
settingsState.register("subjectfilters", (newValue) =>
|
||||||
|
FilterUpcomingAssessments(newValue as Record<string, boolean>),
|
||||||
|
);
|
||||||
registerHomeUpcomingSettingsListeners();
|
registerHomeUpcomingSettingsListeners();
|
||||||
settingsState.register("iconOnlySidebar", this.handleIconOnlySidebarChange.bind(this));
|
settingsState.register("iconOnlySidebar", (newValue) =>
|
||||||
|
this.handleIconOnlySidebarChange(newValue as boolean | undefined),
|
||||||
|
);
|
||||||
settingsState.register("selectedFont", () => applySelectedFont());
|
settingsState.register("selectedFont", () => applySelectedFont());
|
||||||
settingsState.register("menuitems", () => scheduleMenuItemVisibility());
|
settingsState.register("menuitems", () => scheduleMenuItemVisibility());
|
||||||
settingsState.register("menuorder", (order) => {
|
settingsState.register("menuorder", (order) => {
|
||||||
|
|||||||
@@ -155,7 +155,7 @@ export async function loadHomePage() {
|
|||||||
const activeSubjects = activeSubjectsFromLearnPayload(classes);
|
const activeSubjects = activeSubjectsFromLearnPayload(classes);
|
||||||
const currentAssessments = filterAssessmentsForActiveSubjects(assessments, activeSubjects).sort(
|
const currentAssessments = filterAssessmentsForActiveSubjects(assessments, activeSubjects).sort(
|
||||||
comparedate,
|
comparedate,
|
||||||
);
|
) as HomeUpcomingAssessment[];
|
||||||
|
|
||||||
const upcomingItems = document.getElementById("upcoming-items");
|
const upcomingItems = document.getElementById("upcoming-items");
|
||||||
if (upcomingItems) {
|
if (upcomingItems) {
|
||||||
@@ -208,7 +208,7 @@ async function renderHomeUpcomingAssessments() {
|
|||||||
const activeSubjects = activeSubjectsFromLearnPayload(classes);
|
const activeSubjects = activeSubjectsFromLearnPayload(classes);
|
||||||
const currentAssessments = filterAssessmentsForActiveSubjects(assessments, activeSubjects).sort(
|
const currentAssessments = filterAssessmentsForActiveSubjects(assessments, activeSubjects).sort(
|
||||||
comparedate,
|
comparedate,
|
||||||
);
|
) as HomeUpcomingAssessment[];
|
||||||
|
|
||||||
await CreateUpcomingSection(currentAssessments, activeSubjects);
|
await CreateUpcomingSection(currentAssessments, activeSubjects);
|
||||||
upcomingItems.classList.remove("loading");
|
upcomingItems.classList.remove("loading");
|
||||||
@@ -546,7 +546,8 @@ function applyHomeUpcomingLimits(
|
|||||||
const subjectOrder: string[] = [];
|
const subjectOrder: string[] = [];
|
||||||
|
|
||||||
for (const assessment of assessments) {
|
for (const assessment of assessments) {
|
||||||
const code = assessment.filterCode;
|
const code = assessment.filterCode ?? assessment.code;
|
||||||
|
if (!code) continue;
|
||||||
if (!bySubject.has(code)) {
|
if (!bySubject.has(code)) {
|
||||||
bySubject.set(code, []);
|
bySubject.set(code, []);
|
||||||
subjectOrder.push(code);
|
subjectOrder.push(code);
|
||||||
@@ -640,7 +641,12 @@ async function CreateUpcomingSection(
|
|||||||
for (const date in upcomingDates) {
|
for (const date in upcomingDates) {
|
||||||
const assessmentdue = new Date(upcomingDates[date].assessments[0].due);
|
const assessmentdue = new Date(upcomingDates[date].assessments[0].due);
|
||||||
const specialcase = CheckSpecialDay(Today, assessmentdue);
|
const specialcase = CheckSpecialDay(Today, assessmentdue);
|
||||||
const assessmentDate = createAssessmentDateDiv(date, upcomingDates[date], student, specialcase);
|
const assessmentDate = createAssessmentDateDiv(
|
||||||
|
date,
|
||||||
|
upcomingDates[date],
|
||||||
|
student ?? 0,
|
||||||
|
specialcase,
|
||||||
|
);
|
||||||
|
|
||||||
if (specialcase === "Yesterday") {
|
if (specialcase === "Yesterday") {
|
||||||
upcomingitemcontainer!.insertBefore(assessmentDate, upcomingitemcontainer!.firstChild);
|
upcomingitemcontainer!.insertBefore(assessmentDate, upcomingitemcontainer!.firstChild);
|
||||||
@@ -699,7 +705,7 @@ function createAssessmentDateDiv(
|
|||||||
item.classList.add("upcoming-assessment");
|
item.classList.add("upcoming-assessment");
|
||||||
item.setAttribute("data-subject", element.filterCode ?? element.code);
|
item.setAttribute("data-subject", element.filterCode ?? element.code);
|
||||||
item.id = `assessment${element.id}`;
|
item.id = `assessment${element.id}`;
|
||||||
item.style.cssText = element.colour;
|
item.style.cssText = element.colour ?? "";
|
||||||
|
|
||||||
const titlediv = document.createElement("div");
|
const titlediv = document.createElement("div");
|
||||||
titlediv.classList.add("upcoming-subject-title");
|
titlediv.classList.add("upcoming-subject-title");
|
||||||
|
|||||||
@@ -47,19 +47,23 @@ export function isDateInCachedWeek(date: Date, weekFrom: string, weekUntil: stri
|
|||||||
return isInWeekRange(toISODate(date), weekFrom, weekUntil);
|
return isInWeekRange(toISODate(date), weekFrom, weekUntil);
|
||||||
}
|
}
|
||||||
|
|
||||||
async function postParentTimetable(body: object): Promise<unknown> {
|
type ParentTimetableJson = {
|
||||||
|
payload?: unknown | { items?: EngageParentTimetableItem[] };
|
||||||
|
};
|
||||||
|
|
||||||
|
async function postParentTimetable(body: object): Promise<ParentTimetableJson> {
|
||||||
const res = await fetch(`${location.origin}${TIMETABLE_URL}`, {
|
const res = await fetch(`${location.origin}${TIMETABLE_URL}`, {
|
||||||
method: "POST",
|
method: "POST",
|
||||||
headers: { "Content-Type": "application/json; charset=utf-8" },
|
headers: { "Content-Type": "application/json; charset=utf-8" },
|
||||||
credentials: "include",
|
credentials: "include",
|
||||||
body: JSON.stringify(body),
|
body: JSON.stringify(body),
|
||||||
});
|
});
|
||||||
return res.json();
|
return res.json() as Promise<ParentTimetableJson>;
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function fetchEngageParentChildren(): Promise<EngageParentChild[]> {
|
export async function fetchEngageParentChildren(): Promise<EngageParentChild[]> {
|
||||||
const data = await postParentTimetable({ list: true });
|
const data = await postParentTimetable({ list: true });
|
||||||
const raw = data?.payload;
|
const raw = data.payload;
|
||||||
if (!Array.isArray(raw)) return [];
|
if (!Array.isArray(raw)) return [];
|
||||||
return raw.map((row: { name?: string; id?: string | number }) => ({
|
return raw.map((row: { name?: string; id?: string | number }) => ({
|
||||||
name: String(row?.name ?? ""),
|
name: String(row?.name ?? ""),
|
||||||
@@ -74,6 +78,10 @@ export async function fetchEngageParentTimetableWeek(
|
|||||||
): Promise<EngageParentTimetableItem[]> {
|
): Promise<EngageParentTimetableItem[]> {
|
||||||
const student = /^\d+$/.test(studentId) ? Number(studentId) : studentId;
|
const student = /^\d+$/.test(studentId) ? Number(studentId) : studentId;
|
||||||
const data = await postParentTimetable({ from, until, student });
|
const data = await postParentTimetable({ from, until, student });
|
||||||
const items = data?.payload?.items;
|
const payload = data.payload;
|
||||||
return Array.isArray(items) ? items : [];
|
const items =
|
||||||
|
payload && typeof payload === "object" && "items" in payload
|
||||||
|
? (payload as { items?: unknown }).items
|
||||||
|
: undefined;
|
||||||
|
return Array.isArray(items) ? (items as EngageParentTimetableItem[]) : [];
|
||||||
}
|
}
|
||||||
@@ -65,7 +65,7 @@ export async function closePopup() {
|
|||||||
await motionAnimate(
|
await motionAnimate(
|
||||||
[popup, background],
|
[popup, background],
|
||||||
{ opacity: [1, 0], scale: [1, 0.95] },
|
{ opacity: [1, 0], scale: [1, 0.95] },
|
||||||
{ duration: 0.25, easing: [0.22, 0.03, 0.26, 1] },
|
{ duration: 0.25, ease: [0.22, 0.03, 0.26, 1] },
|
||||||
);
|
);
|
||||||
} else {
|
} else {
|
||||||
await animatePopupClose(background);
|
await animatePopupClose(background);
|
||||||
@@ -195,7 +195,7 @@ export function openPopup({
|
|||||||
{
|
{
|
||||||
delay: stagger(0.05, { startDelay: 0.1 }),
|
delay: stagger(0.05, { startDelay: 0.1 }),
|
||||||
duration: 0.5,
|
duration: 0.5,
|
||||||
easing: [0.22, 0.03, 0.26, 1],
|
ease: [0.22, 0.03, 0.26, 1],
|
||||||
},
|
},
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -10,7 +10,7 @@ export function ChangeMenuItemPositions(menuorder: SettingsState["menuorder"]) {
|
|||||||
|
|
||||||
for (let i = 0; i < menuList.length; i++) {
|
for (let i = 0; i < menuList.length; i++) {
|
||||||
const menu = menuList[i] as HTMLElement;
|
const menu = menuList[i] as HTMLElement;
|
||||||
listorder.push(menuorder.indexOf(menu.dataset.key));
|
listorder.push(menuorder.indexOf(menu.dataset.key ?? ""));
|
||||||
}
|
}
|
||||||
|
|
||||||
const newArr: ChildNode[] = [];
|
const newArr: ChildNode[] = [];
|
||||||
|
|||||||
@@ -11,7 +11,10 @@ export function renderShortcuts() {
|
|||||||
try {
|
try {
|
||||||
addShortcuts(settingsState.shortcuts || []);
|
addShortcuts(settingsState.shortcuts || []);
|
||||||
} catch (err: unknown) {
|
} catch (err: unknown) {
|
||||||
console.error("[BetterSEQTA+] Error adding built-in shortcuts:", err?.message || err);
|
console.error(
|
||||||
|
"[BetterSEQTA+] Error adding built-in shortcuts:",
|
||||||
|
err instanceof Error ? err.message : err,
|
||||||
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
const custom = settingsState.customshortcuts || [];
|
const custom = settingsState.customshortcuts || [];
|
||||||
@@ -22,7 +25,7 @@ export function renderShortcuts() {
|
|||||||
console.error(
|
console.error(
|
||||||
"[BetterSEQTA+] Error adding custom shortcut:",
|
"[BetterSEQTA+] Error adding custom shortcut:",
|
||||||
element?.name,
|
element?.name,
|
||||||
err?.message || err,
|
err instanceof Error ? err.message : err,
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,17 @@
|
|||||||
|
import type { Component } from "svelte";
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Svelte components mounted with runtime props (settings UI, search bar, etc.).
|
||||||
|
* Use {@link toMountableComponent} at registration sites — prop shapes vary.
|
||||||
|
*/
|
||||||
|
export type MountableSvelteComponent = Component<
|
||||||
|
Record<string, unknown>,
|
||||||
|
Record<string, unknown>,
|
||||||
|
string
|
||||||
|
>;
|
||||||
|
|
||||||
|
export function toMountableComponent(
|
||||||
|
component: Component<any, any, any>,
|
||||||
|
): MountableSvelteComponent {
|
||||||
|
return component as MountableSvelteComponent;
|
||||||
|
}
|
||||||
+1
-1
@@ -27,7 +27,7 @@
|
|||||||
"paths": {
|
"paths": {
|
||||||
"@/*": ["./src/*"]
|
"@/*": ["./src/*"]
|
||||||
},
|
},
|
||||||
"types": ["vite/client", "node", "chrome"]
|
"types": ["vite/client", "node", "chrome", "jest"]
|
||||||
},
|
},
|
||||||
"include": [
|
"include": [
|
||||||
"src/**/*.ts",
|
"src/**/*.ts",
|
||||||
|
|||||||
Reference in new issue
Block a user