fix(assessments): show letter grades not undefined%

cannot triple confirm that this works for all schools but it works for my assessments that are letter-based
This commit is contained in:
2026-06-22 21:47:03 +09:30
parent 6f7788497a
commit 37ae32be59
12 changed files with 619 additions and 101 deletions
+11 -6
View File
@@ -64,8 +64,8 @@ body {
select { select {
border-radius: 16px !important; border-radius: 16px !important;
border: 1px solid color-mix(in srgb, var(--theme-offset-bg, var(--background-secondary)) 78%, transparent) !important; border: 1px solid var(--theme-offset-bg, var(--theme-secondary, var(--background-secondary))) !important;
background: color-mix(in srgb, var(--background-primary) 90%, transparent) !important; background: var(--theme-primary, var(--background-primary)) !important;
color: var(--text-primary) !important; color: var(--text-primary) !important;
padding: 0.5rem 1rem !important; padding: 0.5rem 1rem !important;
min-height: 2.5rem !important; min-height: 2.5rem !important;
@@ -78,14 +78,14 @@ select {
} }
select:hover { select:hover {
background: color-mix(in srgb, var(--background-primary) 94%, var(--background-secondary) 6%) !important; background: var(--theme-secondary, var(--background-secondary)) !important;
border-color: color-mix(in srgb, var(--theme-offset-bg, var(--background-secondary)) 92%, transparent) !important; border-color: var(--theme-offset-bg, var(--theme-secondary, var(--background-secondary))) !important;
} }
select:focus { select:focus {
outline: none !important; outline: none !important;
background: color-mix(in srgb, var(--background-primary) 96%, var(--background-secondary) 4%) !important; background: var(--theme-secondary, var(--background-secondary)) !important;
border-color: color-mix(in srgb, var(--text-primary) 18%, var(--theme-offset-bg, var(--background-secondary)) 82%) !important; border-color: color-mix(in srgb, var(--text-primary) 18%, var(--theme-offset-bg, var(--theme-secondary, var(--background-secondary))) 82%) !important;
box-shadow: 0 0 0 1px color-mix(in srgb, var(--text-primary) 12%, transparent) !important; box-shadow: 0 0 0 1px color-mix(in srgb, var(--text-primary) 12%, transparent) !important;
} }
@@ -116,6 +116,11 @@ select option {
color: #18181b !important; color: #18181b !important;
} }
.dark select option {
background-color: #1a1a1a !important;
color: #ffffff !important;
}
.dark select:not([multiple]):not([size]), .dark select:not([multiple]):not([size]),
.dark select[size="1"] { .dark select[size="1"] {
background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 20 20' fill='%23c9c9c9'%3E%3Cpath fill-rule='evenodd' d='M5.23 7.21a.75.75 0 0 1 1.06.02L10 11.168l3.71-3.938a.75.75 0 1 1 1.08 1.04l-4.25 4.5a.75.75 0 0 1-1.08 0l-4.25-4.5a.75.75 0 0 1 .02-1.06Z' clip-rule='evenodd'/%3E%3C/svg%3E") !important; background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 20 20' fill='%23c9c9c9'%3E%3Cpath fill-rule='evenodd' d='M5.23 7.21a.75.75 0 0 1 1.06.02L10 11.168l3.71-3.938a.75.75 0 1 1 1.08 1.04l-4.25 4.5a.75.75 0 0 1-1.08 0l-4.25-4.5a.75.75 0 0 1 .02-1.06Z' clip-rule='evenodd'/%3E%3C/svg%3E") !important;
+10 -10
View File
@@ -85,9 +85,9 @@
justify-content: space-between; justify-content: space-between;
gap: 0.75rem; gap: 0.75rem;
width: 100%; width: 100%;
border: 1px solid color-mix(in srgb, var(--theme-offset-bg, var(--background-secondary)) 72%, transparent); border: 1px solid var(--theme-offset-bg, var(--theme-secondary, #e5e7eb));
border-radius: 18px; border-radius: 18px;
background: color-mix(in srgb, var(--background-primary) 88%, transparent); background: var(--theme-primary, #ffffff);
color: var(--text-primary); color: var(--text-primary);
padding: 0.625rem 1rem; padding: 0.625rem 1rem;
font-size: 0.875rem; font-size: 0.875rem;
@@ -102,14 +102,14 @@
} }
.select-trigger:hover { .select-trigger:hover {
background: color-mix(in srgb, var(--background-primary) 94%, var(--background-secondary) 6%); background: var(--theme-secondary, #e5e7eb);
border-color: color-mix(in srgb, var(--theme-offset-bg, var(--background-secondary)) 88%, transparent); border-color: var(--theme-offset-bg, var(--theme-secondary, #d4d4d8));
} }
.select-trigger:focus-visible { .select-trigger:focus-visible {
outline: none; outline: none;
background: color-mix(in srgb, var(--background-primary) 96%, var(--background-secondary) 4%); background: var(--theme-secondary, #e5e7eb);
border-color: color-mix(in srgb, var(--text-primary) 22%, var(--theme-offset-bg, var(--background-secondary)) 78%); border-color: color-mix(in srgb, var(--text-primary) 22%, var(--theme-secondary, #e5e7eb) 78%);
box-shadow: 0 0 0 1px color-mix(in srgb, var(--text-primary) 12%, transparent); box-shadow: 0 0 0 1px color-mix(in srgb, var(--text-primary) 12%, transparent);
} }
@@ -133,9 +133,9 @@
margin: 0; margin: 0;
padding: 0.35rem; padding: 0.35rem;
list-style: none; list-style: none;
border: 1px solid color-mix(in srgb, var(--theme-offset-bg, var(--background-secondary)) 72%, transparent); border: 1px solid var(--theme-offset-bg, var(--theme-secondary, #e5e7eb));
border-radius: 14px; border-radius: 14px;
background: var(--background-primary); background: var(--theme-primary, #ffffff);
box-shadow: box-shadow:
0 10px 25px -5px rgb(0 0 0 / 0.25), 0 10px 25px -5px rgb(0 0 0 / 0.25),
0 8px 10px -6px rgb(0 0 0 / 0.2); 0 8px 10px -6px rgb(0 0 0 / 0.2);
@@ -161,10 +161,10 @@
.select-option:hover, .select-option:hover,
.select-option:focus-visible { .select-option:focus-visible {
outline: none; outline: none;
background: color-mix(in srgb, var(--background-secondary) 55%, transparent); background: var(--theme-secondary, #e5e7eb);
} }
.select-option.is-selected { .select-option.is-selected {
background: color-mix(in srgb, var(--background-secondary) 70%, transparent); background: var(--theme-secondary, #e5e7eb);
} }
</style> </style>
+2
View File
@@ -7,6 +7,8 @@ const THEME_CSS_VARS = [
"--text-color", "--text-color",
"--background-primary", "--background-primary",
"--background-secondary", "--background-secondary",
"--theme-primary",
"--theme-secondary",
"--text-primary", "--text-primary",
"--theme-offset-bg", "--theme-offset-bg",
"--better-sub", "--better-sub",
@@ -1,5 +1,11 @@
<script lang="ts"> <script lang="ts">
import { determineStatus, formatDate, getGradeValue } from "./utils"; import {
assessmentHasGradeDisplay,
determineStatus,
formatDate,
getDisplayGrade,
getThermoscorePercent,
} from "./utils";
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 { buildEngageAssessmentPagePath } from "@/seqta/utils/engageAssessmentStudent"; import { buildEngageAssessmentPagePath } from "@/seqta/utils/engageAssessmentStudent";
@@ -21,28 +27,12 @@
const HIDDEN_ASSESSMENTS_KEY = "betterseqta-hidden-assessments"; const HIDDEN_ASSESSMENTS_KEY = "betterseqta-hidden-assessments";
function percentageToLetter(percentage: number): string { function isLetterGradeMode(): boolean {
const letterMap: Record<number, string> = { const allSettings = settingsState.getAll() as unknown as Record<
100: "A+", string,
95: "A", { lettergrade?: boolean } | undefined
90: "A-", >;
85: "B+", return allSettings["plugin.assessments-average.settings"]?.lettergrade ?? false;
80: "B",
75: "B-",
70: "C+",
65: "C",
60: "C-",
55: "D+",
50: "D",
45: "D-",
40: "E+",
35: "E",
30: "E-",
0: "F",
};
const rounded = Math.ceil(percentage / 5) * 5;
return letterMap[rounded] || "F";
} }
let currentFilters: FilterOptions = { let currentFilters: FilterOptions = {
@@ -73,9 +63,7 @@
} }
function getAssessmentGrade(a: any): string { function getAssessmentGrade(a: any): string {
const val = getGradeValue(a); return getDisplayGrade(a, isLetterGradeMode());
if (val === null) return "No grade";
return percentageToLetter(val);
} }
function getGroupKey(assessment: any): string { function getGroupKey(assessment: any): string {
@@ -522,7 +510,7 @@
{#if assessment.submitted} {#if assessment.submitted}
<span class="card-label label-submitted" style="background: #10b981; color: white;">Submitted</span> <span class="card-label label-submitted" style="background: #10b981; color: white;">Submitted</span>
{/if} {/if}
{#if isCompleted && status === "MARKS_RELEASED" && !assessment.results} {#if isCompleted && status === "MARKS_RELEASED" && !assessmentHasGradeDisplay(assessment)}
<span class="card-label label-completed" style="background: #059669; color: white;">Completed</span> <span class="card-label label-completed" style="background: #059669; color: white;">Completed</span>
{/if} {/if}
</div> </div>
@@ -559,7 +547,7 @@
<h3 class="assessment-title">{assessment.title}</h3> <h3 class="assessment-title">{assessment.title}</h3>
{#if !assessment.results && !isCompleted} {#if !assessmentHasGradeDisplay(assessment) && !isCompleted}
<div class="assessment-meta"> <div class="assessment-meta">
<div class="due-date {dueDateClass}"> <div class="due-date {dueDateClass}">
<OverviewIcon name="calendar-days" size={14} /> <OverviewIcon name="calendar-days" size={14} />
@@ -568,18 +556,14 @@
</div> </div>
{/if} {/if}
{#if assessment.results} {#if assessmentHasGradeDisplay(assessment)}
{@const gradeLabel = getDisplayGrade(assessment, isLetterGradeMode())}
{@const barPercent = getThermoscorePercent(assessment) ?? 0}
<div class="card-footer"> <div class="card-footer">
<div class="Thermoscore__Thermoscore___WFpL3" style="--fill-colour: {color}"> <div class="Thermoscore__Thermoscore___WFpL3" style="--fill-colour: {color}">
<div style="width: {assessment.results.percentage}%" class="Thermoscore__fill___ojxDI"> <div style="width: {barPercent}%" class="Thermoscore__fill___ojxDI">
<div title="{assessment.results.percentage}%" class="Thermoscore__text___XSR_M"> <div title={gradeLabel} class="Thermoscore__text___XSR_M">
{(() => { {gradeLabel}
const allSettings = settingsState.getAll() as unknown as any;
const letterGradeSetting = allSettings["plugin.assessments-average.settings"]?.lettergrade;
return letterGradeSetting
? percentageToLetter(assessment.results.percentage)
: `${assessment.results.percentage}%`;
})()}
</div> </div>
</div> </div>
</div> </div>
@@ -1,3 +1,8 @@
import {
approximatePercentFromLetterGrade,
extractLetterGradeStringFromPayload,
} from "../gradeAnalytics/letterGradeScale";
export interface OverviewSubject { export interface OverviewSubject {
code: string; code: string;
programme: number; programme: number;
@@ -257,3 +262,73 @@ export function getGradeValue(assessment: any): number | null {
return null; return null;
} }
export function extractAssessmentLetterGrade(assessment: any): string | undefined {
if (assessment?.grade != null && String(assessment.grade).trim() !== "") {
return String(assessment.grade).trim();
}
return extractLetterGradeStringFromPayload(assessment);
}
export function percentageToLetterGrade(percentage: number): string {
const letterMap: Record<number, string> = {
100: "A+",
95: "A",
90: "A-",
85: "B+",
80: "B",
75: "B-",
70: "C+",
65: "C",
60: "C-",
55: "D+",
50: "D",
45: "D-",
40: "E+",
35: "E",
30: "E-",
0: "F",
};
const rounded = Math.ceil(percentage / 5) * 5;
return letterMap[rounded] || "F";
}
export function getThermoscorePercent(assessment: any): number | null {
const numeric = getGradeValue(assessment);
if (numeric !== null) return numeric;
const letter = extractAssessmentLetterGrade(assessment);
if (letter) {
const approx = approximatePercentFromLetterGrade(letter);
if (approx !== undefined) return approx;
}
return null;
}
export function getDisplayGrade(assessment: any, letterGradeMode: boolean): string {
if (letterGradeMode) {
const letter = extractAssessmentLetterGrade(assessment);
if (letter) return letter;
const val = getGradeValue(assessment);
if (val !== null) return percentageToLetterGrade(val);
return "No grade";
}
const val = getGradeValue(assessment);
if (val !== null) return `${val}%`;
const letter = extractAssessmentLetterGrade(assessment);
if (letter) return letter;
return "No grade";
}
export function assessmentHasGradeDisplay(assessment: any): boolean {
if (extractAssessmentLetterGrade(assessment)) return true;
if (getGradeValue(assessment) !== null) return true;
return false;
}
@@ -18,8 +18,8 @@
--bsplus-analytics-radius: 16px; --bsplus-analytics-radius: 16px;
--bsplus-analytics-radius-sm: 12px; --bsplus-analytics-radius-sm: 12px;
--bsplus-analytics-ease: cubic-bezier(0.4, 0, 0.2, 1); --bsplus-analytics-ease: cubic-bezier(0.4, 0, 0.2, 1);
--bsplus-analytics-surface: var(--background-primary, #ffffff); --bsplus-analytics-surface: var(--theme-primary, var(--background-primary, #ffffff));
--bsplus-analytics-surface-2: var(--background-secondary, #f8fafc); --bsplus-analytics-surface-2: var(--theme-secondary, var(--background-secondary, #f8fafc));
--bsplus-analytics-text: var(--text-primary, #1a1a1a); --bsplus-analytics-text: var(--text-primary, #1a1a1a);
--bsplus-analytics-muted: color-mix( --bsplus-analytics-muted: color-mix(
in srgb, in srgb,
@@ -388,8 +388,8 @@
right: 0; right: 0;
margin-top: 4px; margin-top: 4px;
min-width: 180px; min-width: 180px;
background: var(--background-primary, #fff); background: var(--theme-primary, var(--background-primary, #fff));
border: 1px solid var(--background-secondary, #e0e0e0); border: 1px solid var(--theme-secondary, var(--background-secondary, #e0e0e0));
border-radius: 8px; border-radius: 8px;
box-shadow: 0 8px 24px rgba(0, 0, 0, 0.15); box-shadow: 0 8px 24px rgba(0, 0, 0, 0.15);
z-index: 1000; z-index: 1000;
@@ -0,0 +1,152 @@
import { getUserInfo } from "@/seqta/ui/AddBetterSEQTAElements";
export interface ArchivedNotification {
notificationID: number;
type: string;
timestamp: string;
title: string;
subtitle: string;
messageID?: number;
assessmentID?: number;
programmeID?: number;
metaclassID?: number;
subjectCode?: string;
firstSavedAt: string;
lastSeenAt: string;
}
export type ArchiveMap = Record<string, ArchivedNotification>;
export type ArchivesByUser = Record<string, ArchiveMap>;
type RawNotification = Record<string, unknown>;
export async function resolveNotificationUserKey(): Promise<string | null> {
try {
const info = await getUserInfo();
const id = info?.id ?? info?.personUUID ?? info?.username;
if (id == null || id === "") return null;
const label =
info?.displayName ?? info?.name ?? info?.username ?? String(id);
return `${location.hostname}:${id}:${String(label).slice(0, 64)}`;
} catch {
return null;
}
}
export async function fetchAllNotifications(): Promise<RawNotification[]> {
const res = await fetch(`${location.origin}/seqta/student/heartbeat?`, {
method: "POST",
headers: { "Content-Type": "application/json; charset=utf-8" },
credentials: "include",
body: JSON.stringify({
timestamp: "1970-01-01 00:00:00.0",
hash: "#?page=/notifications",
}),
});
if (!res.ok) return [];
const json = (await res.json()) as {
notifications?: RawNotification[];
payload?: { notifications?: RawNotification[] };
};
const list = json.notifications ?? json.payload?.notifications;
return Array.isArray(list) ? list : [];
}
function readString(value: unknown): string {
if (value == null) return "";
return String(value).trim();
}
export function normalizeArchivedNotification(
raw: RawNotification,
now = new Date().toISOString(),
): ArchivedNotification | null {
const notificationID = Number(raw.notificationID);
if (!notificationID || Number.isNaN(notificationID)) return null;
const type = readString(raw.type) || "unknown";
const timestamp = readString(raw.timestamp) || now;
if (type === "message" && raw.message && typeof raw.message === "object") {
const message = raw.message as Record<string, unknown>;
return {
notificationID,
type,
timestamp,
title: readString(message.title) || "Message",
subtitle: readString(message.subtitle),
messageID: Number(message.messageID) || undefined,
firstSavedAt: now,
lastSeenAt: now,
};
}
if (
type === "coneqtassessments" &&
raw.coneqtAssessments &&
typeof raw.coneqtAssessments === "object"
) {
const assessment = raw.coneqtAssessments as Record<string, unknown>;
return {
notificationID,
type,
timestamp,
title: readString(assessment.title) || "Assessment",
subtitle: readString(assessment.subtitle) || readString(assessment.subjectCode),
assessmentID: Number(assessment.assessmentID) || undefined,
programmeID: Number(assessment.programmeID) || undefined,
metaclassID: Number(assessment.metaclassID) || undefined,
subjectCode: readString(assessment.subjectCode) || undefined,
firstSavedAt: now,
lastSeenAt: now,
};
}
return {
notificationID,
type,
timestamp,
title: readString(raw.title) || "Notification",
subtitle: readString(raw.subtitle),
firstSavedAt: now,
lastSeenAt: now,
};
}
export function mergeNotificationsIntoArchive(
existing: ArchiveMap,
notifications: RawNotification[],
): ArchiveMap {
const now = new Date().toISOString();
const merged: ArchiveMap = { ...existing };
for (const raw of notifications) {
const normalized = normalizeArchivedNotification(raw, now);
if (!normalized) continue;
const key = String(normalized.notificationID);
const prev = merged[key];
if (prev) {
merged[key] = {
...prev,
...normalized,
firstSavedAt: prev.firstSavedAt,
lastSeenAt: now,
};
} else {
merged[key] = normalized;
}
}
return merged;
}
export function listArchivedNotifications(archive: ArchiveMap): ArchivedNotification[] {
return Object.values(archive).sort(
(a, b) => new Date(b.timestamp).getTime() - new Date(a.timestamp).getTime(),
);
}
@@ -0,0 +1,165 @@
import type { PluginAPI } from "../../core/types";
import type { ArchivedNotification, ArchiveMap } from "./archive";
import { listArchivedNotifications } from "./archive";
import { delay } from "@/seqta/utils/delay";
import ReactFiber from "@/seqta/utils/ReactFiber";
import { waitForElm } from "@/seqta/utils/waitForElm";
interface ArchiveUIStorage {
archivesByUser?: Record<string, ArchiveMap>;
}
function formatArchiveDate(timestamp: string): string {
const date = new Date(timestamp);
if (Number.isNaN(date.getTime())) return timestamp;
return date.toLocaleString(undefined, {
year: "numeric",
month: "short",
day: "numeric",
hour: "2-digit",
minute: "2-digit",
});
}
async function openArchivedMessage(item: ArchivedNotification) {
if (!item.messageID) return;
location.hash = `#?page=/messages`;
await waitForElm('[class*="Viewer__Viewer___"] > div', true, 40);
ReactFiber.find('[class*="Viewer__Viewer___"] > div').setState({
selected: new Set([item.messageID]),
});
await delay(10);
const row = document.querySelector('[class*="MessageList__selected___"]');
if (row) (row as HTMLElement).click();
}
function openArchivedAssessment(item: ArchivedNotification) {
if (!item.programmeID || !item.metaclassID) return;
const base = `#?page=/assessments/${item.programmeID}:${item.metaclassID}`;
location.hash = item.assessmentID ? `${base}&item=${item.assessmentID}` : base;
}
function renderArchiveItem(item: ArchivedNotification): HTMLElement {
const row = document.createElement("button");
row.type = "button";
row.className = "bsplus-notification-archive-item";
row.dataset.notificationId = String(item.notificationID);
const title = document.createElement("span");
title.className = "bsplus-notification-archive-title";
title.textContent = item.title;
const meta = document.createElement("span");
meta.className = "bsplus-notification-archive-meta";
const parts = [formatArchiveDate(item.timestamp)];
if (item.subtitle) parts.push(item.subtitle);
if (item.subjectCode) parts.push(item.subjectCode);
meta.textContent = parts.join(" · ");
const badge = document.createElement("span");
badge.className = "bsplus-notification-archive-badge";
badge.textContent = "Saved locally";
row.append(title, meta, badge);
row.addEventListener("click", () => {
if (item.type === "message") {
void openArchivedMessage(item);
} else if (item.type === "coneqtassessments") {
openArchivedAssessment(item);
}
});
return row;
}
export function mountArchiveUI(
api: PluginAPI<Record<string, never>, ArchiveUIStorage>,
getUserKey: () => Promise<string | null>,
) {
const mountOnList = (listEl: HTMLElement) => {
if (listEl.querySelector(".bsplus-notification-archive-bar")) return;
const bar = document.createElement("div");
bar.className = "bsplus-notification-archive-bar";
const toggle = document.createElement("button");
toggle.type = "button";
toggle.className = "bsplus-notification-archive-toggle";
const panel = document.createElement("div");
panel.className = "bsplus-notification-archive-panel";
panel.hidden = true;
const refresh = async () => {
const userKey = await getUserKey();
if (!userKey) {
toggle.textContent = "Saved notifications (sign in required)";
toggle.disabled = true;
panel.replaceChildren();
return;
}
const archivesByUser = api.storage.archivesByUser ?? {};
const archive = archivesByUser[userKey] ?? {};
const items = listArchivedNotifications(archive);
const liveIds = new Set(
Array.from(listEl.querySelectorAll('[class*="notifications__item___"]'))
.map((el) => el.getAttribute("data-id"))
.filter(Boolean),
);
const removedCount = items.filter(
(item) => !liveIds.has(String(item.notificationID)),
).length;
toggle.disabled = false;
toggle.textContent =
items.length === 0
? "Saved notifications (none yet)"
: `Saved notifications (${items.length}${removedCount > 0 ? `, ${removedCount} no longer on SEQTA` : ""})`;
panel.replaceChildren();
if (items.length === 0) {
const empty = document.createElement("p");
empty.className = "bsplus-notification-archive-empty";
empty.textContent =
"Notifications you receive are saved here per account in extension storage.";
panel.append(empty);
return;
}
for (const item of items) {
panel.append(renderArchiveItem(item));
}
};
toggle.addEventListener("click", () => {
panel.hidden = !panel.hidden;
toggle.setAttribute("aria-expanded", panel.hidden ? "false" : "true");
if (!panel.hidden) void refresh();
});
bar.append(toggle, panel);
listEl.append(bar);
void refresh();
};
api.seqta.onMount('[class*="notifications__list___"]', (el) => {
mountOnList(el as HTMLElement);
});
api.storage.onChange("archivesByUser", () => {
document
.querySelectorAll('[class*="notifications__list___"]')
.forEach((el) => {
const bar = el.querySelector(".bsplus-notification-archive-bar");
if (bar) bar.remove();
mountOnList(el as HTMLElement);
});
});
}
@@ -1,19 +1,43 @@
import type { Plugin } from "../../core/types"; import type { Plugin } from "../../core/types";
import { booleanSetting } from "@/plugins/core/settingsHelpers";
import { isSeqtaEngageExperience } from "@/seqta/utils/isSeqtaEngage"; import { isSeqtaEngageExperience } from "@/seqta/utils/isSeqtaEngage";
import { verboseInfo } from "@/utils/verboseLog"; import { verboseInfo } from "@/utils/verboseLog";
import {
type ArchivesByUser,
fetchAllNotifications,
mergeNotificationsIntoArchive,
resolveNotificationUserKey,
} from "./archive";
import { mountArchiveUI } from "./archiveUI";
import styles from "./styles.css?inline";
const notificationCollectorSettings = {
saveLocally: booleanSetting({
default: true,
title: "Save notification history locally",
description:
"Keeps a per-account copy in extension storage. SEQTA removes notifications after about a year; these stay until you clear extension data.",
}),
} as const;
interface NotificationCollectorStorage { interface NotificationCollectorStorage {
lastNotificationCount: number; lastNotificationCount: number;
lastCheckedTime: string; lastCheckedTime: string;
consecutiveErrors: number; consecutiveErrors: number;
archivesByUser: ArchivesByUser;
} }
const notificationCollectorPlugin: Plugin<{}, NotificationCollectorStorage> = { const notificationCollectorPlugin: Plugin<
typeof notificationCollectorSettings,
NotificationCollectorStorage
> = {
id: "notificationCollector", id: "notificationCollector",
name: "Notification Collector", name: "Notification Collector",
description: "Collects and displays SEQTA notifications", description:
version: "1.0.0", "Tracks notifications and saves a local per-account archive that outlasts SEQTA's server retention",
settings: {}, version: "1.1.0",
settings: notificationCollectorSettings,
styles,
disableToggle: true, disableToggle: true,
run: async (api) => { run: async (api) => {
@@ -21,24 +45,51 @@ const notificationCollectorPlugin: Plugin<{}, NotificationCollectorStorage> = {
return () => {}; return () => {};
} }
await api.storage.loaded;
await api.settings.loaded;
let pollInterval: number | null = null; let pollInterval: number | null = null;
let isVisible = !document.hidden; let isVisible = !document.hidden;
let baseInterval = 30000; // 30 seconds let archiveSyncInFlight = false;
const maxInterval = 300000; // 5 minutes max const baseInterval = 30000;
const maxInterval = 300000;
// Store last notification count in storage
if (!api.storage.lastNotificationCount) { if (!api.storage.lastNotificationCount) {
api.storage.lastNotificationCount = 0; api.storage.lastNotificationCount = 0;
} }
if (!api.storage.consecutiveErrors) { if (!api.storage.consecutiveErrors) {
api.storage.consecutiveErrors = 0; api.storage.consecutiveErrors = 0;
} }
if (!api.storage.archivesByUser) {
api.storage.archivesByUser = {};
}
const syncArchive = async () => {
if (!api.settings.saveLocally || archiveSyncInFlight) return;
archiveSyncInFlight = true;
try {
const userKey = await resolveNotificationUserKey();
if (!userKey) return;
const notifications = await fetchAllNotifications();
const archivesByUser = { ...(api.storage.archivesByUser ?? {}) };
const existing = archivesByUser[userKey] ?? {};
const merged = mergeNotificationsIntoArchive(existing, notifications);
if (JSON.stringify(existing) !== JSON.stringify(merged)) {
archivesByUser[userKey] = merged;
api.storage.archivesByUser = archivesByUser;
}
} catch (error) {
console.warn("[BetterSEQTA+] Notification archive sync failed:", error);
} finally {
archiveSyncInFlight = false;
}
};
const checkNotifications = async () => { const checkNotifications = async () => {
// Skip if tab is not visible to save battery if (!isVisible) return;
if (!isVisible) {
return;
}
try { try {
const alertDiv = document.querySelector( const alertDiv = document.querySelector(
@@ -49,30 +100,17 @@ const notificationCollectorPlugin: Plugin<{}, NotificationCollectorStorage> = {
alertDiv.textContent = api.storage.lastNotificationCount.toString(); alertDiv.textContent = api.storage.lastNotificationCount.toString();
} }
const response = await fetch( const notifications = await fetchAllNotifications();
`${location.origin}/seqta/student/heartbeat?`, const notificationCount = notifications.length;
{
method: "POST",
headers: {
"Content-Type": "application/json; charset=utf-8",
},
body: JSON.stringify({
timestamp: "1970-01-01 00:00:00.0",
hash: "#?page=/home",
}),
},
);
const data = await response.json();
// Store notification count for history
const notificationCount = data.payload.notifications.length;
api.storage.lastNotificationCount = notificationCount; api.storage.lastNotificationCount = notificationCount;
api.storage.lastCheckedTime = new Date().toISOString(); api.storage.lastCheckedTime = new Date().toISOString();
// Reset error count on success
api.storage.consecutiveErrors = 0; api.storage.consecutiveErrors = 0;
if (api.settings.saveLocally) {
await syncArchive();
}
if (alertDiv) { if (alertDiv) {
alertDiv.textContent = notificationCount.toString(); alertDiv.textContent = notificationCount.toString();
} else { } else {
@@ -86,7 +124,6 @@ const notificationCollectorPlugin: Plugin<{}, NotificationCollectorStorage> = {
}; };
const getNextInterval = () => { const getNextInterval = () => {
// Exponential backoff on errors, max 5 minutes
const errorMultiplier = Math.min( const errorMultiplier = Math.min(
Math.pow(2, api.storage.consecutiveErrors || 0), Math.pow(2, api.storage.consecutiveErrors || 0),
10, 10,
@@ -95,17 +132,14 @@ const notificationCollectorPlugin: Plugin<{}, NotificationCollectorStorage> = {
}; };
const startPolling = () => { const startPolling = () => {
if (pollInterval) return; // Already polling if (pollInterval) return;
checkNotifications(); checkNotifications();
const scheduleNext = () => { const scheduleNext = () => {
const interval = getNextInterval(); const interval = getNextInterval();
pollInterval = window.setTimeout(() => { pollInterval = window.setTimeout(() => {
checkNotifications().then(() => { checkNotifications().then(() => {
if (pollInterval) { if (pollInterval) scheduleNext();
// Only continue if not stopped
scheduleNext();
}
}); });
}, interval); }, interval);
}; };
@@ -130,29 +164,43 @@ const notificationCollectorPlugin: Plugin<{}, NotificationCollectorStorage> = {
} }
}; };
// Listen for visibility changes to pause/resume polling
const handleVisibilityChange = () => { const handleVisibilityChange = () => {
isVisible = !document.hidden; isVisible = !document.hidden;
if (isVisible && !pollInterval) { if (isVisible && !pollInterval) {
// Resume polling when tab becomes visible
const alertDiv = document.querySelector( const alertDiv = document.querySelector(
"[class*='notifications__bubble___']", "[class*='notifications__bubble___']",
); );
if (alertDiv) { if (alertDiv) startPolling();
startPolling();
}
} }
}; };
document.addEventListener("visibilitychange", handleVisibilityChange); document.addEventListener("visibilitychange", handleVisibilityChange);
api.seqta.onMount("[class*='notifications__bubble___']", (_) => { const pageChangeUnregister = api.seqta.onPageChange((page) => {
if (page === "notifications" && api.settings.saveLocally) {
void syncArchive();
}
});
mountArchiveUI(api, resolveNotificationUserKey);
api.seqta.onMount("[class*='notifications__bubble___']", () => {
startPolling(); startPolling();
if (api.settings.saveLocally) {
void syncArchive();
}
});
api.seqta.onMount("[class*='notifications__list___']", () => {
if (api.settings.saveLocally) {
void syncArchive();
}
}); });
return () => { return () => {
stopPolling(); stopPolling();
document.removeEventListener("visibilitychange", handleVisibilityChange); document.removeEventListener("visibilitychange", handleVisibilityChange);
pageChangeUnregister.unregister();
}; };
}, },
}; };
@@ -0,0 +1,87 @@
.bsplus-notification-archive-bar {
margin-top: 0.5rem;
padding-top: 0.5rem;
border-top: 1px solid color-mix(in srgb, var(--text-primary) 12%, transparent);
}
.bsplus-notification-archive-toggle {
display: block;
width: 100%;
border: 1px solid color-mix(in srgb, var(--text-primary) 14%, transparent);
border-radius: 12px;
background: var(--theme-primary, var(--background-primary, #232323));
color: var(--text-primary);
padding: 0.55rem 0.75rem;
font-size: 0.8125rem;
font-weight: 600;
text-align: left;
cursor: pointer;
transition: background-color 150ms ease;
}
.bsplus-notification-archive-toggle:hover:not(:disabled) {
background: var(--theme-secondary, var(--background-secondary, #1a1a1a));
}
.bsplus-notification-archive-toggle:disabled {
opacity: 0.65;
cursor: default;
}
.bsplus-notification-archive-panel {
margin-top: 0.45rem;
max-height: 14rem;
overflow-y: auto;
display: flex;
flex-direction: column;
gap: 0.35rem;
}
.bsplus-notification-archive-panel[hidden] {
display: none !important;
}
.bsplus-notification-archive-item {
display: flex;
flex-direction: column;
gap: 0.2rem;
width: 100%;
border: none;
border-left: 3px solid var(--better-main, #3b82f6);
border-radius: 10px;
background: var(--theme-primary, var(--background-primary, #232323));
color: var(--text-primary);
padding: 0.5rem 0.65rem;
text-align: left;
cursor: pointer;
transition: background-color 150ms ease;
}
.bsplus-notification-archive-item:hover {
background: var(--theme-secondary, var(--background-secondary, #1a1a1a));
}
.bsplus-notification-archive-title {
font-size: 0.8125rem;
font-weight: 600;
line-height: 1.3;
}
.bsplus-notification-archive-meta {
font-size: 0.75rem;
opacity: 0.78;
line-height: 1.3;
}
.bsplus-notification-archive-badge {
font-size: 0.6875rem;
font-weight: 600;
opacity: 0.7;
}
.bsplus-notification-archive-empty {
font-size: 0.75rem;
opacity: 0.8;
margin: 0.25rem 0 0;
line-height: 1.4;
}
+1 -1
View File
@@ -19,7 +19,7 @@ export const SYNCABLE_PLUGIN_SETTING_DEFAULTS: Record<
themes: {}, themes: {},
"animated-background": { speed: 1 }, "animated-background": { speed: 1 },
"assessments-average": { lettergrade: false }, "assessments-average": { lettergrade: false },
notificationCollector: {}, notificationCollector: { saveLocally: true },
timetable: {}, timetable: {},
timetableEdit: {}, timetableEdit: {},
"profile-picture": { useCloudPfp: false }, "profile-picture": { useCloudPfp: false },