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