feat: improve releiabilty of opening WS connections

This commit is contained in:
AdenMGB committed 2026-10-31 08:52:53 +10:30
1 parent 6081b1446b
commit d4174ef006
6 files changed
+149 -55

No files matched your search

@@ -4,14 +4,12 @@
import { closeExtensionPopup } from "@/seqta/utils/Closers/closeExtensionPopup";
import { runTimetableClassmatesSync } from "./syncOrchestrator";
import { loadSession, resolveClassmatesScope } from "./rosterStore";
import { pluginSettingsStore } from "@/interface/pages/settings/pluginSettingsState.svelte";
import { accountsAvailability } from "./accountsAvailability";
import {
openTimetableClassmatesOptInPopup,
openTimetableClassmatesOptOutPopup,
} from "./openTimetableClassmatesPopup";
const PLUGIN_ID = "timetable-classmates";
const SETTINGS_CLOSE_MS = 320;
let busy = $state(false);
@@ -47,10 +45,7 @@
error = "";
afterSettingsClosed(() => {
openTimetableClassmatesOptInPopup({
onAccepted: async () => {
await pluginSettingsStore.update(PLUGIN_ID, "enabled", true);
await refreshStatus();
},
onAccepted: () => refreshStatus(),
});
});
}
@@ -5,11 +5,26 @@ import type { ArchivedMembers, ClassRosterIndex } from "./rosterMerge";
import { rosterPeersForClass } from "./rosterMerge";
import type { PeopleCache } from "./rosterStore";
import { displayNameForSeqtaId } from "./peopleCache";
import { classRosterKey } from "./classKeys";
import { openClassmatesRosterPopup } from "./openTimetableClassmatesPopup";
const STACK = "bsplus-classmate-stack";
const AVATAR = "bsplus-classmate-avatar";
/** Learn home `#day-container` tiles expose these attributes on class lessons. */
export function classKeyForHomeDay(el: HTMLElement): string | null {
if (!el.hasAttribute("data-bsplus-meta-id") && !el.hasAttribute("data-bsplus-code")) {
return null;
}
const meta = parseInt(el.getAttribute("data-bsplus-meta-id") ?? "", 10);
const programme = parseInt(el.getAttribute("data-bsplus-programme-id") ?? "", 10);
return classRosterKey({
metaID: Number.isNaN(meta) ? undefined : meta,
code: el.getAttribute("data-bsplus-code")?.trim() || undefined,
programmeID: Number.isNaN(programme) ? undefined : programme,
});
}
export function isClassmatesPluginMutation(record: MutationRecord): boolean {
const inStack = (el: Element | null) => Boolean(el?.closest(`.${STACK}`));
if (record.target instanceof Element && inStack(record.target)) return true;
@@ -28,7 +43,8 @@ function avatarColumnWidth(host: HTMLElement): number {
const scope =
(host.classList.contains("entry") ? host : host.closest(".timetablepage .entry.class")) ??
host.closest(".timetablepage .quickbar .meta") ??
host.closest(".timetablepage .days tbody td");
host.closest(".timetablepage .days tbody td") ??
host.closest("#day-container .day");
if (!(scope instanceof HTMLElement)) return 0;
const w = scope.getBoundingClientRect().width;
return w > 0 ? w * 0.5 : 0;
@@ -165,7 +181,10 @@ export async function renderClassmateStackForEntry(
if (existing?.dataset.bsplusPeers === signature) return;
existing?.remove();
const classTitle = entry.querySelector(".title")?.textContent?.trim() ?? "";
const classTitle =
entry.querySelector(".title")?.textContent?.trim() ??
entry.querySelector("h2")?.textContent?.trim() ??
"";
const stack = document.createElement("div");
stack.className = STACK;
stack.dataset.bsplusPeers = signature;
@@ -5,6 +5,7 @@ import { isPluginBlockedByPerformanceMode } from "@/seqta/utils/performanceMode"
import { timetableClassmatesSettings } from "./settings";
import styles from "./styles.css?inline";
import {
classKeyForHomeDay,
classKeyFromCi,
findClassEntryByTitle,
isClassmatesPluginMutation,
@@ -24,7 +25,10 @@ import { resolveStudentId } from "./seqtaClient";
import { peerCloudIdsForPaint } from "./accountsClient";
import { fetchSchoolYearEnrollmentSnapshot } from "./timetableYearSnapshot";
import { CLASSMATES_TIMETABLE_POLL_MS } from "./constants";
import { scheduleClassmatesSyncIfNeeded } from "./syncOrchestrator";
import {
bindClassmatesOptInActivated,
scheduleClassmatesSyncIfNeeded,
} from "./syncOrchestrator";
import {
mountClassmatesToolbarChip,
unmountClassmatesToolbarChip,
@@ -51,7 +55,7 @@ const timetableClassmatesPlugin: Plugin<typeof timetableClassmatesSettings> = {
};
browser.runtime.onMessage.addListener(onSyncMessage);
let gridObserver: MutationObserver | null = null;
let domObserver: MutationObserver | null = null;
let resizeObserver: ResizeObserver | null = null;
let paintTimer: ReturnType<typeof setTimeout> | null = null;
let pollTimer: ReturnType<typeof setInterval> | null = null;
@@ -59,10 +63,35 @@ const timetableClassmatesPlugin: Plugin<typeof timetableClassmatesSettings> = {
const schedulePaint = () => {
if (paintTimer) clearTimeout(paintTimer);
paintTimer = setTimeout(() => void paintTimetable(), 120);
paintTimer = setTimeout(() => void paintStacks(), 120);
};
const paintTimetable = async () => {
const startTimetablePoll = () => {
if (pollTimer) return;
scheduleClassmatesSyncIfNeeded(true);
pollTimer = setInterval(() => scheduleClassmatesSyncIfNeeded(), CLASSMATES_TIMETABLE_POLL_MS);
};
const armSyncIfOptedIn = async () => {
if (!(await loadSession()).syncOptIn) return;
void ensureCiToClassKey(() => fetchSchoolYearEnrollmentSnapshot()).catch(() => {});
startTimetablePoll();
};
bindClassmatesOptInActivated(() => {
if (document.querySelector(".timetablepage")) void armSyncIfOptedIn();
schedulePaint();
});
const watchRepaint = (root: Element) => {
domObserver ??= new MutationObserver((mutations) => {
if (mutations.every(isClassmatesPluginMutation)) return;
schedulePaint();
});
domObserver.observe(root, { childList: true, subtree: true });
};
const paintStacks = async () => {
if (painting) return;
painting = true;
try {
@@ -72,9 +101,6 @@ const timetableClassmatesPlugin: Plugin<typeof timetableClassmatesSettings> = {
return;
}
const page = document.querySelector(".timetablepage");
if (!page) return;
const selfId = await resolveStudentId();
if (selfId == null) return;
@@ -86,10 +112,10 @@ const timetableClassmatesPlugin: Plugin<typeof timetableClassmatesSettings> = {
peerCloudIdsForPaint(),
]);
const paintHost = (host: HTMLElement, ci: number | null) =>
const paintHost = (host: HTMLElement, classKey: string | null) =>
renderClassmateStackForEntry(
host,
classKeyFromCi(ci, ciMap),
classKey,
roster,
peopleCache,
selfId,
@@ -102,29 +128,34 @@ const timetableClassmatesPlugin: Plugin<typeof timetableClassmatesSettings> = {
return Number.isNaN(ci) ? null : ci;
};
const paints = [...page.querySelectorAll(".entry.class")].map((entry) =>
paintHost(entry as HTMLElement, ciOf(entry)),
);
const quickbar = page.querySelector(".quickbar.visible[data-type='class']");
if (quickbar) {
const title = quickbar.querySelector(".title")?.textContent?.trim() ?? "";
const host =
(quickbar.querySelector(".meta") as HTMLElement | null) ?? (quickbar as HTMLElement);
paints.push(paintHost(host, ciOf(findClassEntryByTitle(page, title))));
const paints: Promise<void>[] = [];
const page = document.querySelector(".timetablepage");
if (page) {
paints.push(
...[...page.querySelectorAll(".entry.class")].map((entry) =>
paintHost(entry as HTMLElement, classKeyFromCi(ciOf(entry), ciMap)),
),
);
const quickbar = page.querySelector(".quickbar.visible[data-type='class']");
if (quickbar) {
const title = quickbar.querySelector(".title")?.textContent?.trim() ?? "";
const host =
(quickbar.querySelector(".meta") as HTMLElement | null) ?? (quickbar as HTMLElement);
paints.push(paintHost(host, ciOf(findClassEntryByTitle(page, title))));
}
}
const homeDays = document.querySelectorAll<HTMLElement>("#day-container .day[data-bsplus-meta-id]");
for (const day of homeDays) {
paints.push(paintHost(day, classKeyForHomeDay(day)));
}
await Promise.all(paints);
} finally {
painting = false;
}
};
const startTimetablePoll = () => {
if (pollTimer) return;
scheduleClassmatesSyncIfNeeded();
pollTimer = setInterval(() => scheduleClassmatesSyncIfNeeded(), CLASSMATES_TIMETABLE_POLL_MS);
};
const handleTimetablePage = async () => {
try {
await waitForElm(".timetablepage .entry.class", true, 50, 300);
@@ -133,48 +164,63 @@ const timetableClassmatesPlugin: Plugin<typeof timetableClassmatesSettings> = {
}
const page = document.querySelector(".timetablepage");
if ((await loadSession()).syncOptIn) {
void ensureCiToClassKey(() => fetchSchoolYearEnrollmentSnapshot()).catch(() => {});
startTimetablePoll();
}
await armSyncIfOptedIn();
schedulePaint();
void mountClassmatesToolbarChip();
if (page && !gridObserver) {
gridObserver = new MutationObserver((mutations) => {
if (mutations.every(isClassmatesPluginMutation)) return;
schedulePaint();
});
gridObserver.observe(page, { childList: true, subtree: true });
resizeObserver = new ResizeObserver(() => schedulePaint());
if (page) {
watchRepaint(page);
resizeObserver ??= new ResizeObserver(() => schedulePaint());
resizeObserver.observe(page);
}
};
const handleHomePage = async () => {
const container = document.getElementById("day-container");
if (!container) return;
try {
await waitForElm("#day-container .day", true, 50, 200);
} catch {
/* empty day */
}
watchRepaint(container);
schedulePaint();
};
const onUpdated = () => schedulePaint();
window.addEventListener(CLASSMATES_UPDATED_EVENT, onUpdated);
const onClassEntryClick = (e: Event) => {
if ((e.target as HTMLElement).closest?.(".timetablepage .entry.class")) schedulePaint();
const onRepaintClick = (e: Event) => {
if (
(e.target as HTMLElement).closest?.(
".timetablepage .entry.class, #day-container .day",
)
) {
schedulePaint();
}
};
document.addEventListener("click", onClassEntryClick, true);
document.addEventListener("click", onRepaintClick, true);
const { unregister: unregisterEnabled } = api.settings.onChange("enabled", schedulePaint);
const { unregister: unregisterTimetable } = api.seqta.onMount(".timetablepage", handleTimetablePage);
const { unregister: unregisterHome } = api.seqta.onMount("#home-container", handleHomePage);
const { unregister } = api.seqta.onMount(".timetablepage", handleTimetablePage);
if ((await loadSession()).syncOptIn) scheduleClassmatesSyncIfNeeded();
if ((await loadSession()).syncOptIn) {
scheduleClassmatesSyncIfNeeded();
if (document.querySelector(".timetablepage")) startTimetablePoll();
}
return () => {
unregister();
unregisterTimetable();
unregisterHome();
bindClassmatesOptInActivated(null);
browser.runtime.onMessage.removeListener(onSyncMessage);
gridObserver?.disconnect();
domObserver?.disconnect();
resizeObserver?.disconnect();
if (paintTimer) clearTimeout(paintTimer);
if (pollTimer) clearInterval(pollTimer);
window.removeEventListener(CLASSMATES_UPDATED_EVENT, onUpdated);
document.removeEventListener("click", onClassEntryClick, true);
document.removeEventListener("click", onRepaintClick, true);
unregisterEnabled();
removeClassmateStacks();
unmountClassmatesToolbarChip();
@@ -52,6 +52,26 @@
position: relative;
}
.day-container .day:has(> .bsplus-classmate-stack) {
display: grid;
grid-template-columns: minmax(0, 1fr) minmax(0, auto);
align-items: start;
column-gap: 4px;
}
.day-container .day:has(> .bsplus-classmate-stack) > :not(.bsplus-classmate-stack) {
grid-column: 1;
min-width: 0;
}
.day-container .day:has(> .bsplus-classmate-stack) > .bsplus-classmate-stack {
grid-column: 2;
grid-row: 1 / -1;
align-self: start;
justify-self: end;
margin: 2px 4px 0 0;
}
.bsplus-classmate-avatar {
width: 20px;
height: 20px;
@@ -43,12 +43,19 @@ import { buildSharePayload } from "./relayPayload";
import { runRelayRoundTrip, sendRelayRevoke, type RelaySnapshotShare } from "./relayClient";
import type { ClassRef } from "./classKeys";
import { CLASSMATES_PEER_REFRESH_MS } from "./constants";
import { pluginSettingsStore } from "@/interface/pages/settings/pluginSettingsState.svelte";
const HEARTBEAT_MIN_MS = 15 * 60 * 1000;
const PLUGIN_ID = "timetable-classmates";
export type SyncRunResult = { ok: boolean; error?: string; peers?: number };
let syncChain: Promise<void> = Promise.resolve();
let onOptInActivated: (() => void) | null = null;
export function bindClassmatesOptInActivated(fn: (() => void) | null): void {
onOptInActivated = fn;
}
export function scheduleClassmatesSyncIfNeeded(force = false): void {
syncChain = syncChain
@@ -100,6 +107,8 @@ export async function registerOptIn(): Promise<{ ok: boolean; error?: string }>
if (scope) await setScopeSyncOptIn(scope, true);
await patchSession({ syncOptIn: true, showAvatars: true });
const sync = await runTimetableClassmatesSync();
await pluginSettingsStore.update(PLUGIN_ID, "enabled", true);
onOptInActivated?.();
if (!sync.ok) {
return { ok: true, error: sync.error ?? "Opt-in saved but initial sync failed." };
}
+6 -1
View File
@@ -507,8 +507,13 @@ function makeLessonDiv(lesson: any, num: number) {
type,
} = lesson;
const homeClassAttrs =
type === "class"
? ` data-bsplus-meta-id="${metaID ?? ""}" data-bsplus-code="${code ?? ""}" data-bsplus-programme-id="${programmeID ?? ""}"`
: "";
let lessonString = `
<div class="day" id="${code + num}" style="${colour}">
<div class="day" id="${code + num}" style="${colour}"${homeClassAttrs}>
<h2>${type == "class" ? description : type == "tutorial" ? "Tutorial" : "Unknown"}</h2>
<h3>${staff || "Unknown"}</h3>
<h3>${room || (type == "tutorial" ? "Unknown" : "N/A")}</h3>