mirror of
https://github.com/BetterSEQTA/BetterSEQTA-Plus.git
synced 2026-06-17 17:07:07 +00:00
fix: harden extension security and plugin reliability
Address audit findings across background handlers, openers, plugins, and UI: URL allowlists, XSS reductions, popup lifecycle fixes, plugin dispose/cleanup, cloud sync hardening, global search mathjs sandbox, and settings storage fixes.
This commit is contained in:
+94
-13
@@ -11,6 +11,7 @@ import {
|
||||
requestCloudSettingsDebouncedUpload,
|
||||
runCloudSettingsPoll,
|
||||
} from "./background/cloudSettingsAutoSync";
|
||||
import { isAllowedFetchUrl } from "@/seqta/utils/allowedFetchUrl";
|
||||
|
||||
/**
|
||||
* Session-only dev-mode override of the content API base.
|
||||
@@ -45,6 +46,11 @@ function reloadSeqtaPages() {
|
||||
/** Callback for sending a response back to the message sender */
|
||||
type MessageSender = { (response?: unknown): void };
|
||||
|
||||
async function getAccessTokenFromStorage(): Promise<string | null> {
|
||||
const { bsplus_token } = await browser.storage.local.get("bsplus_token");
|
||||
return typeof bsplus_token === "string" && bsplus_token.length > 0 ? bsplus_token : null;
|
||||
}
|
||||
|
||||
/** Accept API + GitHub fallback shapes; always return `{ success, data?: { themes } }`. */
|
||||
function normalizeFetchThemesResponse(json: unknown): {
|
||||
success: boolean;
|
||||
@@ -79,7 +85,8 @@ function normalizeFetchThemesResponse(json: unknown): {
|
||||
}
|
||||
|
||||
function handleFetchThemes(request: any, sendResponse: MessageSender): boolean {
|
||||
const { token } = request;
|
||||
void (async () => {
|
||||
const token = await getAccessTokenFromStorage();
|
||||
const apiUrl = `${apiBase()}/api/themes?type=betterseqta&limit=100&nocache=${Date.now()}`;
|
||||
const githubUrl = `https://raw.githubusercontent.com/BetterSEQTA/BetterSEQTA-Themes/main/store/themes.json?nocache=${Date.now()}`;
|
||||
const headers: Record<string, string> = {};
|
||||
@@ -112,15 +119,18 @@ function handleFetchThemes(request: any, sendResponse: MessageSender): boolean {
|
||||
sendResponse({ success: false, error: fallbackErr?.message });
|
||||
});
|
||||
});
|
||||
})();
|
||||
return true;
|
||||
}
|
||||
|
||||
function handleFetchThemeDetails(request: any, sendResponse: MessageSender): boolean {
|
||||
const { themeId, token } = request;
|
||||
const { themeId } = request;
|
||||
if (!themeId || typeof themeId !== "string") {
|
||||
sendResponse({ success: false, error: "Missing themeId" });
|
||||
return false;
|
||||
}
|
||||
void (async () => {
|
||||
const token = await getAccessTokenFromStorage();
|
||||
const headers: Record<string, string> = {};
|
||||
if (token) headers["Authorization"] = `Bearer ${token}`;
|
||||
fetch(`${apiBase()}/api/themes/${themeId}`, { cache: "no-store", headers })
|
||||
@@ -130,15 +140,46 @@ function handleFetchThemeDetails(request: any, sendResponse: MessageSender): boo
|
||||
console.error("[Background] fetchThemeDetails error:", err);
|
||||
sendResponse({ success: false, error: err?.message });
|
||||
});
|
||||
})();
|
||||
return true;
|
||||
}
|
||||
|
||||
function handleFetchFromUrl(request: any, sendResponse: MessageSender): boolean {
|
||||
function isTrustedSender(sender?: browser.Runtime.MessageSender): boolean {
|
||||
if (!sender) return false;
|
||||
if (sender.id && sender.id !== browser.runtime.id) return false;
|
||||
|
||||
const urls = [sender.url, sender.tab?.url].filter(Boolean) as string[];
|
||||
for (const pageUrl of urls) {
|
||||
if (/^chrome-extension:\/\//.test(pageUrl) || /^moz-extension:\/\//.test(pageUrl)) {
|
||||
return true;
|
||||
}
|
||||
try {
|
||||
if (isSeqtaOrigin(new URL(pageUrl).origin)) return true;
|
||||
} catch {
|
||||
// try next URL
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
function handleFetchFromUrl(
|
||||
request: any,
|
||||
sendResponse: MessageSender,
|
||||
sender?: browser.Runtime.MessageSender,
|
||||
): boolean {
|
||||
if (!isTrustedSender(sender)) {
|
||||
sendResponse({ error: "Unauthorized sender" });
|
||||
return false;
|
||||
}
|
||||
const { url } = request;
|
||||
if (!url || typeof url !== "string") {
|
||||
sendResponse({ error: "Missing url" });
|
||||
return false;
|
||||
}
|
||||
if (!isAllowedFetchUrl(url)) {
|
||||
sendResponse({ error: "URL not allowed" });
|
||||
return false;
|
||||
}
|
||||
fetch(url, { cache: "no-store" })
|
||||
.then((r) => r.json())
|
||||
.then((data) => sendResponse({ data }))
|
||||
@@ -177,7 +218,15 @@ function handleCloudReserveClient(request: any, sendResponse: MessageSender): bo
|
||||
return true;
|
||||
}
|
||||
|
||||
function handleCloudLogin(request: any, sendResponse: MessageSender): boolean {
|
||||
function handleCloudLogin(
|
||||
request: any,
|
||||
sendResponse: MessageSender,
|
||||
sender?: browser.Runtime.MessageSender,
|
||||
): boolean {
|
||||
if (!isTrustedSender(sender)) {
|
||||
sendResponse({ error: "Unauthorized sender" });
|
||||
return false;
|
||||
}
|
||||
const { client_id, redirect_uri, login, password } = request;
|
||||
if (!client_id || !redirect_uri || !login || !password) {
|
||||
sendResponse({ error: "Missing client_id, redirect_uri, login, or password" });
|
||||
@@ -291,10 +340,18 @@ function handleCloudRefresh(request: any, sendResponse: MessageSender): boolean
|
||||
return true;
|
||||
}
|
||||
|
||||
function handleCloudSettingsUpload(request: any, sendResponse: MessageSender): boolean {
|
||||
function handleCloudSettingsUpload(
|
||||
request: any,
|
||||
sendResponse: MessageSender,
|
||||
sender?: browser.Runtime.MessageSender,
|
||||
): boolean {
|
||||
if (!isTrustedSender(sender)) {
|
||||
sendResponse({ success: false, error: "Unauthorized sender" });
|
||||
return false;
|
||||
}
|
||||
void (async () => {
|
||||
try {
|
||||
const token = request.token as string | undefined;
|
||||
const token = await getAccessTokenFromStorage();
|
||||
if (!token) {
|
||||
sendResponse({ success: false, error: "Not authenticated" });
|
||||
return;
|
||||
@@ -316,10 +373,18 @@ function handleCloudSettingsUpload(request: any, sendResponse: MessageSender): b
|
||||
return true;
|
||||
}
|
||||
|
||||
function handleCloudSettingsDownload(request: any, sendResponse: MessageSender): boolean {
|
||||
function handleCloudSettingsDownload(
|
||||
request: any,
|
||||
sendResponse: MessageSender,
|
||||
sender?: browser.Runtime.MessageSender,
|
||||
): boolean {
|
||||
if (!isTrustedSender(sender)) {
|
||||
sendResponse({ success: false, error: "Unauthorized sender" });
|
||||
return false;
|
||||
}
|
||||
void (async () => {
|
||||
try {
|
||||
const token = request.token as string | undefined;
|
||||
const token = await getAccessTokenFromStorage();
|
||||
if (!token) {
|
||||
sendResponse({ success: false, error: "Not authenticated" });
|
||||
return;
|
||||
@@ -343,11 +408,17 @@ function handleCloudSettingsDownload(request: any, sendResponse: MessageSender):
|
||||
}
|
||||
|
||||
function handleCloudFavorite(request: any, sendResponse: MessageSender): boolean {
|
||||
const { themeId, token, action } = request;
|
||||
if (!themeId || !token) {
|
||||
sendResponse({ success: false, error: "Theme ID and token required" });
|
||||
const { themeId, action } = request;
|
||||
if (!themeId) {
|
||||
sendResponse({ success: false, error: "Theme ID required" });
|
||||
return false;
|
||||
}
|
||||
void (async () => {
|
||||
const token = await getAccessTokenFromStorage();
|
||||
if (!token) {
|
||||
sendResponse({ success: false, error: "Not authenticated" });
|
||||
return;
|
||||
}
|
||||
const isFavorite = action === "favorite";
|
||||
fetch(`${apiBase()}/api/themes/${themeId}/favorite`, {
|
||||
method: isFavorite ? "POST" : "DELETE",
|
||||
@@ -359,6 +430,7 @@ function handleCloudFavorite(request: any, sendResponse: MessageSender): boolean
|
||||
console.error("[Background] cloudFavorite error:", err);
|
||||
sendResponse({ success: false, error: err?.message });
|
||||
});
|
||||
})();
|
||||
return true;
|
||||
}
|
||||
|
||||
@@ -376,7 +448,12 @@ function isSeqtaOrigin(origin: string): boolean {
|
||||
}
|
||||
}
|
||||
|
||||
function handleSetDevApiBase(request: any): boolean {
|
||||
function handleSetDevApiBase(
|
||||
request: any,
|
||||
_sendResponse: MessageSender,
|
||||
sender?: browser.Runtime.MessageSender,
|
||||
): boolean {
|
||||
if (!isTrustedSender(sender)) return false;
|
||||
const url = typeof request?.url === "string" ? request.url.trim() : null;
|
||||
if (url && /^https?:\/\//.test(url)) {
|
||||
DEV_API_BASE = url.replace(/\/$/, "");
|
||||
@@ -415,7 +492,11 @@ const MESSAGE_HANDLERS: Record<string, MessageHandler> = {
|
||||
});
|
||||
return true;
|
||||
},
|
||||
sendNews: (req, sendResponse) => {
|
||||
sendNews: (req, sendResponse, sender) => {
|
||||
if (!isTrustedSender(sender)) {
|
||||
sendResponse({ error: "Unauthorized sender" });
|
||||
return false;
|
||||
}
|
||||
fetchNews(req.source ?? "australia", sendResponse);
|
||||
return true;
|
||||
},
|
||||
|
||||
@@ -25,6 +25,11 @@ const REFRESH_URL = `${ACCOUNTS_BASE}/api/bsplus/refresh`;
|
||||
const UPLOAD_DEBOUNCE_MS = 2000;
|
||||
const POLL_THROTTLE_MS = 24 * 60 * 60 * 1000;
|
||||
const POLL_THROTTLE_KEY = "bsplus_lastCloudPoll";
|
||||
const FETCH_TIMEOUT_MS = 30_000;
|
||||
|
||||
function fetchWithTimeout(url: string, init?: RequestInit): Promise<Response> {
|
||||
return fetch(url, { ...init, signal: AbortSignal.timeout(FETCH_TIMEOUT_MS) });
|
||||
}
|
||||
|
||||
type CloudSummaryResponse = {
|
||||
desqta?: unknown;
|
||||
@@ -35,6 +40,7 @@ let reloadSeqtaPagesFn: (() => void) | null = null;
|
||||
let suppressAutoUploadDuringRestore = false;
|
||||
let debounceTimer: ReturnType<typeof setTimeout> | null = null;
|
||||
let pollInFlight: Promise<void> | null = null;
|
||||
let autoSyncInitialized = false;
|
||||
|
||||
function isAutoCloudSyncEnabled(all: Record<string, unknown>): boolean {
|
||||
return all.autoCloudSettingsSync !== false;
|
||||
@@ -65,7 +71,7 @@ async function tryRefreshTokens(): Promise<boolean> {
|
||||
if (!refresh_token || !client_id) return false;
|
||||
|
||||
try {
|
||||
const r = await fetch(REFRESH_URL, {
|
||||
const r = await fetchWithTimeout(REFRESH_URL, {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ refresh_token, client_id }),
|
||||
@@ -100,7 +106,7 @@ async function fetchCloudSummaryOnce(
|
||||
| { ok: false; unauthorized: boolean; error?: string }
|
||||
> {
|
||||
try {
|
||||
const r = await fetch(CLOUD_SUMMARY_URL, {
|
||||
const r = await fetchWithTimeout(CLOUD_SUMMARY_URL, {
|
||||
headers: { Authorization: `Bearer ${token}` },
|
||||
cache: "no-store",
|
||||
});
|
||||
@@ -177,7 +183,7 @@ async function putSettingsOnce(token: string): Promise<PutResult> {
|
||||
return { ok: true, skipped: true };
|
||||
}
|
||||
|
||||
const r = await fetch(CLOUD_SETTINGS_SYNC_URL, {
|
||||
const r = await fetchWithTimeout(CLOUD_SETTINGS_SYNC_URL, {
|
||||
method: "PUT",
|
||||
headers: {
|
||||
Authorization: `Bearer ${token}`,
|
||||
@@ -235,7 +241,7 @@ type GetResult =
|
||||
|
||||
async function getSettingsAndApplyOnce(token: string): Promise<GetResult> {
|
||||
try {
|
||||
const r = await fetch(CLOUD_SETTINGS_SYNC_URL, {
|
||||
const r = await fetchWithTimeout(CLOUD_SETTINGS_SYNC_URL, {
|
||||
method: "GET",
|
||||
headers: { Authorization: `Bearer ${token}` },
|
||||
cache: "no-store",
|
||||
@@ -373,8 +379,8 @@ export function runCloudSettingsPoll(): Promise<void> {
|
||||
try {
|
||||
const { [POLL_THROTTLE_KEY]: last } = await browser.storage.local.get(POLL_THROTTLE_KEY);
|
||||
if (Date.now() - (Number(last) || 0) < POLL_THROTTLE_MS) return;
|
||||
await browser.storage.local.set({ [POLL_THROTTLE_KEY]: Date.now() });
|
||||
await runCloudSettingsPollInner();
|
||||
await browser.storage.local.set({ [POLL_THROTTLE_KEY]: Date.now() });
|
||||
} catch (e) {
|
||||
console.error("[BS+ cloud sync] Poll error:", e);
|
||||
} finally {
|
||||
@@ -453,6 +459,8 @@ function onStorageChanged(
|
||||
|
||||
export function initCloudSettingsAutoSync(deps: { reloadSeqtaPages: () => void }): void {
|
||||
reloadSeqtaPagesFn = deps.reloadSeqtaPages;
|
||||
if (autoSyncInitialized) return;
|
||||
autoSyncInitialized = true;
|
||||
browser.storage.onChanged.addListener(onStorageChanged);
|
||||
}
|
||||
|
||||
|
||||
+20
-6
@@ -1,5 +1,7 @@
|
||||
import Parser from "rss-parser";
|
||||
|
||||
const MAX_RATE_LIMIT_RETRIES = 3;
|
||||
|
||||
/**
|
||||
* Fetches news articles specifically for Australia from the NewsAPI.
|
||||
*
|
||||
@@ -13,15 +15,23 @@ import Parser from "rss-parser";
|
||||
* to send the fetched news data back to the caller.
|
||||
* It's called with an object like `{ news: responseData }`.
|
||||
*/
|
||||
const fetchAustraliaNews = async (url: string, sendResponse: any) => {
|
||||
const fetchAustraliaNews = async (
|
||||
url: string,
|
||||
sendResponse: any,
|
||||
rateLimitRetryCount = 0,
|
||||
) => {
|
||||
fetch(url)
|
||||
.then((result) => result.json())
|
||||
.then((response) => {
|
||||
if (response.code == "rateLimited") {
|
||||
fetchAustraliaNews((url += "%00"), sendResponse);
|
||||
if (response.code == "rateLimited" && rateLimitRetryCount < MAX_RATE_LIMIT_RETRIES) {
|
||||
fetchAustraliaNews(`${url}%00`, sendResponse, rateLimitRetryCount + 1);
|
||||
} else {
|
||||
sendResponse({ news: response });
|
||||
}
|
||||
})
|
||||
.catch((error) => {
|
||||
console.error("[BetterSEQTA+] Failed to fetch Australia news", error);
|
||||
sendResponse({ news: { articles: [] } });
|
||||
});
|
||||
};
|
||||
|
||||
@@ -99,13 +109,14 @@ export async function fetchNews(source: string | undefined, sendResponse: any) {
|
||||
|
||||
if (normalizedSource === "australia") {
|
||||
const date = new Date();
|
||||
date.setDate(date.getDate() - 5);
|
||||
|
||||
const from =
|
||||
date.getFullYear() +
|
||||
"-" +
|
||||
(date.getMonth() + 1) +
|
||||
String(date.getMonth() + 1).padStart(2, "0") +
|
||||
"-" +
|
||||
(date.getDate() - 5);
|
||||
String(date.getDate()).padStart(2, "0");
|
||||
|
||||
const url = `https://newsapi.org/v2/everything?domains=abc.net.au&from=${from}&apiKey=17c0da766ba347c89d094449504e3080`;
|
||||
fetchAustraliaNews(url, sendResponse);
|
||||
@@ -115,7 +126,6 @@ export async function fetchNews(source: string | undefined, sendResponse: any) {
|
||||
|
||||
const parser = new Parser();
|
||||
let feeds: string[];
|
||||
console.log("fetchNews", normalizedSource);
|
||||
|
||||
if (rssFeedsByCountry[normalizedSource.toLowerCase()]) {
|
||||
feeds = rssFeedsByCountry[normalizedSource.toLowerCase()];
|
||||
@@ -129,6 +139,10 @@ export async function fetchNews(source: string | undefined, sendResponse: any) {
|
||||
const articlesPromises = feeds.map(async (feedUrl) => {
|
||||
try {
|
||||
const response = await fetch(feedUrl);
|
||||
if (!response.ok) {
|
||||
console.error(`Failed to fetch RSS feed: ${feedUrl} (${response.status})`);
|
||||
return [];
|
||||
}
|
||||
const feedString = await response.text();
|
||||
const feed = await parser.parseString(feedString);
|
||||
|
||||
|
||||
@@ -92,7 +92,7 @@
|
||||
bind:this={background}
|
||||
class="flex absolute top-0 left-0 z-50 justify-center items-center w-full h-full cursor-pointer bg-black/50"
|
||||
onclick={handleBackgroundClick}
|
||||
onkeydown={(e) => { if (e.key === "Enter") handleBackgroundClick; }}
|
||||
onkeydown={(e) => { if (e.key === "Enter") handleBackgroundClick(e as unknown as MouseEvent) }}
|
||||
>
|
||||
<div
|
||||
bind:this={content}
|
||||
|
||||
@@ -22,15 +22,13 @@
|
||||
});
|
||||
|
||||
async function upload() {
|
||||
const token = await cloudAuth.getStoredToken();
|
||||
if (!token) return;
|
||||
if (!cloudState.isLoggedIn) return;
|
||||
busy = true;
|
||||
statusError = null;
|
||||
statusMessage = null;
|
||||
try {
|
||||
const res = (await browser.runtime.sendMessage({
|
||||
type: "cloudSettingsUpload",
|
||||
token,
|
||||
})) as { success?: boolean; error?: string };
|
||||
if (res?.success) {
|
||||
statusMessage = "Settings uploaded.";
|
||||
@@ -49,15 +47,13 @@
|
||||
}
|
||||
|
||||
async function confirmDownload() {
|
||||
const token = await cloudAuth.getStoredToken();
|
||||
if (!token) return;
|
||||
if (!cloudState.isLoggedIn) return;
|
||||
busy = true;
|
||||
statusError = null;
|
||||
statusMessage = null;
|
||||
try {
|
||||
const res = (await browser.runtime.sendMessage({
|
||||
type: "cloudSettingsDownload",
|
||||
token,
|
||||
})) as { success?: boolean; error?: string; notFound?: boolean };
|
||||
if (res?.success) {
|
||||
statusMessage = "Settings restored.";
|
||||
|
||||
@@ -19,6 +19,7 @@
|
||||
|
||||
let editor = $state<HTMLDivElement | null>(null)
|
||||
let view: EditorView | null = null;
|
||||
let unsubSettings: (() => void) | undefined;
|
||||
let editorTheme = new Compartment();
|
||||
let { value, onChange, className } = $props<{value: string, onChange: (value: string) => void, className?: string}>()
|
||||
|
||||
@@ -73,7 +74,7 @@
|
||||
view = createEditorView(state, editor as HTMLElement);
|
||||
}
|
||||
|
||||
settingsState.subscribe((settings) => {
|
||||
unsubSettings = settingsState.subscribe((settings) => {
|
||||
if (view) {
|
||||
view.dispatch({
|
||||
effects: editorTheme.reconfigure(
|
||||
@@ -85,6 +86,7 @@
|
||||
});
|
||||
|
||||
onDestroy(() => {
|
||||
unsubSettings?.();
|
||||
if (view) {
|
||||
view.destroy();
|
||||
}
|
||||
|
||||
@@ -90,7 +90,7 @@
|
||||
bind:this={background}
|
||||
class="flex absolute top-0 left-0 z-50 justify-center items-center w-full h-full shadow-2xl cursor-pointer bg-black/20 border border-[#DDDDDD]/30 dark:border-[#38373D]/30"
|
||||
onclick={handleBackgroundClick}
|
||||
onkeydown={(e) => { e.key === 'Enter' && handleBackgroundClick }}
|
||||
onkeydown={(e) => { if (e.key === 'Enter') handleBackgroundClick(e as unknown as MouseEvent) }}
|
||||
>
|
||||
<div
|
||||
bind:this={content}
|
||||
|
||||
@@ -78,7 +78,7 @@
|
||||
|
||||
const startRecording = () => {
|
||||
isRecording = true;
|
||||
recordedKeys.clear();
|
||||
recordedKeys = new Set();
|
||||
inputElement?.focus();
|
||||
};
|
||||
|
||||
@@ -87,7 +87,7 @@
|
||||
if (recordedKeys.has('esc')) {
|
||||
onChange('');
|
||||
isRecording = false;
|
||||
recordedKeys.clear();
|
||||
recordedKeys = new Set();
|
||||
inputElement?.blur();
|
||||
return;
|
||||
}
|
||||
@@ -113,10 +113,16 @@
|
||||
}
|
||||
|
||||
isRecording = false;
|
||||
recordedKeys.clear();
|
||||
recordedKeys = new Set();
|
||||
inputElement?.blur();
|
||||
};
|
||||
|
||||
const addRecordedKey = (key: string) => {
|
||||
const next = new Set(recordedKeys);
|
||||
next.add(key);
|
||||
recordedKeys = next;
|
||||
};
|
||||
|
||||
const handleKeyDown = (e: KeyboardEvent) => {
|
||||
if (!isRecording) return;
|
||||
|
||||
@@ -126,14 +132,14 @@
|
||||
const key = formatKeyForHotkey(e.key);
|
||||
|
||||
// Add modifiers
|
||||
if (e.ctrlKey) recordedKeys.add('ctrl');
|
||||
if (e.metaKey) recordedKeys.add('cmd');
|
||||
if (e.altKey) recordedKeys.add('alt');
|
||||
if (e.shiftKey) recordedKeys.add('shift');
|
||||
if (e.ctrlKey) addRecordedKey('ctrl');
|
||||
if (e.metaKey) addRecordedKey('cmd');
|
||||
if (e.altKey) addRecordedKey('alt');
|
||||
if (e.shiftKey) addRecordedKey('shift');
|
||||
|
||||
// Add the main key (ignore modifier keys themselves)
|
||||
if (!['ctrl', 'cmd', 'alt', 'shift'].includes(key)) {
|
||||
recordedKeys.add(key);
|
||||
addRecordedKey(key);
|
||||
}
|
||||
|
||||
// Auto-stop recording if we have a main key
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
<script lang="ts">
|
||||
let { state, onChange, min = 0, max = 100, step = 1 } = $props<{
|
||||
let { state = $bindable(), onChange, min = 0, max = 100, step = 1 } = $props<{
|
||||
state: number,
|
||||
onChange: (value: number) => void,
|
||||
min?: number,
|
||||
|
||||
@@ -39,7 +39,7 @@
|
||||
</script>
|
||||
|
||||
<div class="flex flex-col h-full">
|
||||
<div class="top-0 z-10 text-[0.875rem] pb-0.5 mx-4 px-2 tab-width-container">
|
||||
<div class="top-0 z-10 text-[0.875rem] pb-0.5 mx-4 px-2 tab-width-container" role="tablist">
|
||||
<div bind:this={containerRef} class="flex relative">
|
||||
<MotionDiv
|
||||
class="absolute top-0 left-0 z-0 h-full bg-gradient-to-tr dark:from-[#38373D]/80 dark:to-[#38373D] from-[#DDDDDD]/80 to-[#DDDDDD] rounded-full opacity-40 tab-width"
|
||||
@@ -48,6 +48,8 @@
|
||||
/>
|
||||
{#each tabs as { title }, index}
|
||||
<button
|
||||
role="tab"
|
||||
aria-selected={activeTab === index}
|
||||
class="relative z-10 flex-1 px-4 py-2 focus-visible:outline-none"
|
||||
onclick={() => activeTab = index}
|
||||
>
|
||||
@@ -64,7 +66,10 @@
|
||||
>
|
||||
<div class="flex">
|
||||
{#each tabs as { Content, props }, index}
|
||||
<div class="absolute focus:outline-none w-full pt-2 transition-opacity duration-300 overflow-y-scroll no-scrollbar pb-2 h-full tab {activeTab === index ? 'opacity-100 active' : 'opacity-0'}"
|
||||
<div
|
||||
role="tabpanel"
|
||||
aria-hidden={activeTab !== index}
|
||||
class="absolute focus:outline-none w-full pt-2 transition-opacity duration-300 overflow-y-scroll no-scrollbar pb-2 h-full tab {activeTab === index ? 'opacity-100 active' : 'opacity-0'}"
|
||||
style="left: {index * 100}%;">
|
||||
<div style="left: {index * 100}%;" class="fixed top-0 w-full h-8 bg-gradient-to-b to-transparent pointer-events-none z-[100] from-white dark:from-zinc-800 dark:to-transparent"></div>
|
||||
<Content {...props} />
|
||||
|
||||
@@ -12,18 +12,18 @@
|
||||
|
||||
<div
|
||||
onclick={onClick}
|
||||
onkeydown={onClick}
|
||||
tabindex="-1"
|
||||
onkeydown={(e) => { if (e.key === 'Enter' || e.key === ' ') onClick() }}
|
||||
tabindex="0"
|
||||
role="button"
|
||||
class="relative w-16 h-16 cursor-pointer rounded-xl transition ring-3 dark:ring-zinc-500/50 ring-zinc-300 {isEditMode ? 'animate-shake' : ''} {isSelected ? 'dark:ring-4 ring-4' : 'ring-0'}"
|
||||
>
|
||||
{#if isEditMode}
|
||||
<div
|
||||
tabindex="-1"
|
||||
tabindex="0"
|
||||
role="button"
|
||||
class="absolute top-0 right-0 z-10 flex w-6 h-6 p-2 text-white translate-x-1/2 -translate-y-1/2 bg-red-600 rounded-full place-items-center"
|
||||
onclick={onDelete}
|
||||
onkeydown={onDelete}
|
||||
onclick={(e) => { e.stopPropagation(); onDelete() }}
|
||||
onkeydown={(e) => { if (e.key === 'Enter' || e.key === ' ') { e.stopPropagation(); onDelete() } }}
|
||||
>
|
||||
<div class="w-4 h-0.5 bg-white"></div>
|
||||
</div>
|
||||
|
||||
@@ -174,18 +174,19 @@
|
||||
if (parentElement) {
|
||||
observer = new MutationObserver(checkActiveClass);
|
||||
observer.observe(parentElement, { attributes: true, attributeFilter: ['class'] });
|
||||
}
|
||||
|
||||
return () => {
|
||||
observer.disconnect();
|
||||
observer?.disconnect();
|
||||
backgroundUpdates.removeListener(syncBackgrounds);
|
||||
};
|
||||
}
|
||||
});
|
||||
|
||||
onDestroy(() => {
|
||||
if (observer) {
|
||||
observer.disconnect();
|
||||
}
|
||||
observer?.disconnect();
|
||||
backgrounds.forEach((bg) => {
|
||||
if (bg.url) URL.revokeObjectURL(bg.url);
|
||||
});
|
||||
});
|
||||
</script>
|
||||
|
||||
|
||||
@@ -21,12 +21,15 @@
|
||||
let prevLoggedIn = $state(false);
|
||||
let showSignInModal = $state(false);
|
||||
|
||||
cloudAuth.subscribe((s) => {
|
||||
$effect(() => {
|
||||
const unsub = cloudAuth.subscribe((s) => {
|
||||
const now = s.isLoggedIn;
|
||||
if (now && !prevLoggedIn && themes) void fetchThemes();
|
||||
prevLoggedIn = now;
|
||||
cloudLoggedIn = now;
|
||||
});
|
||||
return unsub;
|
||||
});
|
||||
|
||||
const handleThemeClick = async (theme: CustomTheme, e: MouseEvent) => {
|
||||
if (isEditMode) return;
|
||||
@@ -102,8 +105,6 @@
|
||||
selectedTheme: themeManager.getSelectedThemeId() || '',
|
||||
}
|
||||
if (themes && cloudLoggedIn) {
|
||||
const token = await cloudAuth.getStoredToken();
|
||||
if (token) {
|
||||
const status: Record<string, boolean> = {};
|
||||
await Promise.all(
|
||||
themes.themes.map(async (t) => {
|
||||
@@ -111,7 +112,6 @@
|
||||
const res = (await browser.runtime.sendMessage({
|
||||
type: 'fetchThemeDetails',
|
||||
themeId: t.id,
|
||||
token,
|
||||
})) as { success?: boolean; data?: { theme?: { is_favorited?: boolean } } };
|
||||
if (res?.success && res?.data?.theme) {
|
||||
status[t.id] = !!res.data.theme.is_favorited;
|
||||
@@ -122,7 +122,6 @@
|
||||
})
|
||||
);
|
||||
favoriteStatus = status;
|
||||
}
|
||||
} else {
|
||||
favoriteStatus = {};
|
||||
}
|
||||
@@ -134,13 +133,10 @@
|
||||
showSignInModal = true;
|
||||
return;
|
||||
}
|
||||
const token = await cloudAuth.getStoredToken();
|
||||
if (!token) return;
|
||||
const isFavorite = !favoriteStatus[theme.id];
|
||||
const result = (await browser.runtime.sendMessage({
|
||||
type: 'cloudFavorite',
|
||||
themeId: theme.id,
|
||||
token,
|
||||
action: isFavorite ? 'favorite' : 'unfavorite',
|
||||
})) as { success?: boolean };
|
||||
if (result?.success) {
|
||||
|
||||
@@ -1,21 +1,25 @@
|
||||
<script lang="ts">
|
||||
import React from "react";
|
||||
import ReactDOM from "react-dom";
|
||||
import { onDestroy, onMount } from "svelte";
|
||||
import { onDestroy } from "svelte";
|
||||
|
||||
const e = React.createElement;
|
||||
let container: HTMLDivElement;
|
||||
let adapterProps = $props();
|
||||
let container = $state<HTMLDivElement | null>(null);
|
||||
|
||||
onMount(() => {
|
||||
const { el, children, class: _, ...props } = $$props;
|
||||
$effect(() => {
|
||||
if (!container) return;
|
||||
|
||||
const { el, children, class: className, ...rest } = adapterProps;
|
||||
try {
|
||||
ReactDOM.render(e(el, props, children), container);
|
||||
ReactDOM.render(e(el, rest, children), container);
|
||||
} catch (err) {
|
||||
console.warn(`react-adapter failed to mount.`, { err });
|
||||
}
|
||||
});
|
||||
|
||||
onDestroy(() => {
|
||||
if (!container) return;
|
||||
try {
|
||||
ReactDOM.unmountComponentAtNode(container);
|
||||
} catch (err) {
|
||||
@@ -24,4 +28,4 @@
|
||||
});
|
||||
</script>
|
||||
|
||||
<div bind:this={container} class={$$props.class}></div>
|
||||
<div bind:this={container} class={adapterProps.class}></div>
|
||||
|
||||
@@ -6,7 +6,7 @@
|
||||
import browser from "webextension-polyfill";
|
||||
|
||||
import { standalone as StandaloneStore } from "../utils/standalone.svelte";
|
||||
import { onMount } from "svelte";
|
||||
import { onMount, onDestroy } from "svelte";
|
||||
import { settingsState } from "@/seqta/utils/listeners/SettingsState";
|
||||
|
||||
import { closeExtensionPopup } from "@/seqta/utils/Closers/closeExtensionPopup";
|
||||
@@ -108,12 +108,14 @@
|
||||
showDisclaimerModal = true;
|
||||
};
|
||||
|
||||
onMount(() => {
|
||||
settingsPopup.addListener(() => {
|
||||
const closePopupsOnSettingsClose = () => {
|
||||
showColourPicker = false;
|
||||
showFontPicker = false;
|
||||
showCloudPanel = false;
|
||||
});
|
||||
};
|
||||
|
||||
onMount(() => {
|
||||
settingsPopup.addListener(closePopupsOnSettingsClose);
|
||||
|
||||
if (standalone) {
|
||||
StandaloneStore.setStandalone(true);
|
||||
@@ -125,6 +127,10 @@
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
onDestroy(() => {
|
||||
settingsPopup.removeListener(closePopupsOnSettingsClose);
|
||||
});
|
||||
</script>
|
||||
|
||||
<div
|
||||
|
||||
@@ -19,6 +19,7 @@
|
||||
import { closeExtensionPopup } from "@/seqta/utils/Closers/closeExtensionPopup"
|
||||
import { getSnapshotForUpload } from "@/seqta/utils/cloudSettingsSync"
|
||||
import { getStoredOverride, setApiBase } from "@/seqta/utils/DevApiBase"
|
||||
import { onMount } from "svelte"
|
||||
|
||||
let devApiBaseInput = $state<string>(getStoredOverride() ?? "")
|
||||
let devApiBaseActive = $state<string | null>(getStoredOverride())
|
||||
@@ -128,9 +129,9 @@
|
||||
await browser.storage.local.set({ [storageKey]: currentSettings });
|
||||
}
|
||||
|
||||
$effect(() => {
|
||||
loadPluginSettings();
|
||||
})
|
||||
onMount(() => {
|
||||
void loadPluginSettings();
|
||||
});
|
||||
|
||||
const { showColourPicker, showFontPicker, showDisclaimer, showCloudPanel } = $props<{
|
||||
showColourPicker: () => void;
|
||||
|
||||
@@ -23,7 +23,10 @@
|
||||
const themeManager = ThemeManager.getInstance();
|
||||
let cloudLoggedIn = $state(cloudAuth.state.isLoggedIn);
|
||||
|
||||
cloudAuth.subscribe((s) => { cloudLoggedIn = s.isLoggedIn; });
|
||||
$effect(() => {
|
||||
const unsub = cloudAuth.subscribe((s) => { cloudLoggedIn = s.isLoggedIn; });
|
||||
return unsub;
|
||||
});
|
||||
|
||||
// State variables
|
||||
let searchTerm = $state('');
|
||||
@@ -86,13 +89,11 @@
|
||||
}
|
||||
|
||||
const toggleFavorite = async (theme: Theme) => {
|
||||
const token = await cloudAuth.getStoredToken();
|
||||
if (!token) return;
|
||||
if (!cloudLoggedIn) return;
|
||||
const isFavorite = !theme.is_favorited;
|
||||
const result = (await browser.runtime.sendMessage({
|
||||
type: 'cloudFavorite',
|
||||
themeId: theme.id,
|
||||
token,
|
||||
action: isFavorite ? 'favorite' : 'unfavorite',
|
||||
})) as { success?: boolean };
|
||||
if (result?.success) {
|
||||
@@ -119,14 +120,12 @@
|
||||
error = null;
|
||||
}
|
||||
try {
|
||||
const token = await cloudAuth.getStoredToken();
|
||||
const data = await sendMessageWithTimeout<{
|
||||
success?: boolean;
|
||||
data?: { themes: unknown[] };
|
||||
error?: string;
|
||||
}>({
|
||||
type: 'fetchThemes',
|
||||
token: token ?? undefined,
|
||||
});
|
||||
if (!data?.success || !Array.isArray(data?.data?.themes)) {
|
||||
throw new Error(data?.error || 'Failed to fetch themes');
|
||||
|
||||
+14
-6
@@ -509,7 +509,13 @@ function deepFunctionCheck(obj, path = "") {
|
||||
}
|
||||
}
|
||||
|
||||
function isTrustedMessage(event) {
|
||||
return event.source === window && event.origin === window.location.origin;
|
||||
}
|
||||
|
||||
window.addEventListener("message", (event) => {
|
||||
if (!isTrustedMessage(event)) return;
|
||||
|
||||
if (event.data.type === "reactFiberRequest") {
|
||||
const { selector, action, payload, debug, messageId } = event.data;
|
||||
const fiberInstance = ReactFiber.find(selector, {
|
||||
@@ -522,12 +528,14 @@ window.addEventListener("message", (event) => {
|
||||
response = fiberInstance.getState(payload.key);
|
||||
break;
|
||||
case "setState":
|
||||
// Handle both function and object updates
|
||||
if (payload.updateFn) {
|
||||
const updateFn = new Function('return ' + payload.updateFn)();
|
||||
fiberInstance.setState(updateFn);
|
||||
} else {
|
||||
if (
|
||||
payload.updateObject &&
|
||||
typeof payload.updateObject === "object" &&
|
||||
!Array.isArray(payload.updateObject)
|
||||
) {
|
||||
fiberInstance.setState(payload.updateObject);
|
||||
} else {
|
||||
console.warn("[pageState] setState rejected: only plain objects are allowed");
|
||||
}
|
||||
response = {};
|
||||
break;
|
||||
@@ -580,7 +588,7 @@ window.addEventListener("message", (event) => {
|
||||
response,
|
||||
messageId,
|
||||
},
|
||||
"*",
|
||||
window.location.origin,
|
||||
);
|
||||
} else if (event.data.type === "triggerKeyboardEvent") {
|
||||
// Handle keyboard event triggering from content script
|
||||
|
||||
@@ -17,7 +17,7 @@ import {
|
||||
processAssessments,
|
||||
type WeightingEntry,
|
||||
} from "./utils.ts";
|
||||
import { injectRubricCopyButtons } from "./rubricCopy.ts";
|
||||
import { injectRubricCopyButtons, teardownRubricCopyButtons } from "./rubricCopy.ts";
|
||||
|
||||
interface weightingsStorage {
|
||||
weightings: Record<string, WeightingEntry>;
|
||||
@@ -41,6 +41,8 @@ class AssessmentsAveragePluginClass extends BasePlugin<typeof settings> {
|
||||
const instance = new AssessmentsAveragePluginClass();
|
||||
|
||||
let overrideListenerController: AbortController | null = null;
|
||||
let wrapperColourObserver: MutationObserver | null = null;
|
||||
let wrapperColourObserverTimeout: ReturnType<typeof setTimeout> | null = null;
|
||||
|
||||
const assessmentsAveragePlugin: Plugin<typeof settings, weightingsStorage> = {
|
||||
id: "assessments-average",
|
||||
@@ -54,7 +56,9 @@ const assessmentsAveragePlugin: Plugin<typeof settings, weightingsStorage> = {
|
||||
await initStorage(api);
|
||||
clearStuck(api);
|
||||
|
||||
api.seqta.onMount(".assessmentsWrapper", async () => {
|
||||
const { unregister: unregisterWrapperMount } = api.seqta.onMount(
|
||||
".assessmentsWrapper",
|
||||
async () => {
|
||||
await waitForElm(
|
||||
"#main > .assessmentsWrapper .assessments [class*='AssessmentItem__AssessmentItem___']",
|
||||
true,
|
||||
@@ -88,17 +92,43 @@ const assessmentsAveragePlugin: Plugin<typeof settings, weightingsStorage> = {
|
||||
void parseAssessments(api);
|
||||
const wrapper = document.querySelector(".assessmentsWrapper");
|
||||
if (wrapper) {
|
||||
const observer = new MutationObserver(() => {
|
||||
wrapperColourObserver?.disconnect();
|
||||
if (wrapperColourObserverTimeout) {
|
||||
clearTimeout(wrapperColourObserverTimeout);
|
||||
}
|
||||
wrapperColourObserver = new MutationObserver(() => {
|
||||
applySubjectColourToOverallResult();
|
||||
});
|
||||
observer.observe(wrapper, { childList: true, subtree: true });
|
||||
setTimeout(() => observer.disconnect(), 10000);
|
||||
wrapperColourObserver.observe(wrapper, { childList: true, subtree: true });
|
||||
wrapperColourObserverTimeout = setTimeout(() => {
|
||||
wrapperColourObserver?.disconnect();
|
||||
wrapperColourObserver = null;
|
||||
wrapperColourObserverTimeout = null;
|
||||
}, 10000);
|
||||
}
|
||||
});
|
||||
api.seqta.onMount("[class*='SelectedAssessment__']", () => {
|
||||
},
|
||||
);
|
||||
const { unregister: unregisterSelectedMount } = api.seqta.onMount(
|
||||
"[class*='SelectedAssessment__']",
|
||||
() => {
|
||||
injectWeightingsTab(api);
|
||||
injectRubricCopyButtons();
|
||||
});
|
||||
},
|
||||
);
|
||||
|
||||
return () => {
|
||||
overrideListenerController?.abort();
|
||||
overrideListenerController = null;
|
||||
wrapperColourObserver?.disconnect();
|
||||
wrapperColourObserver = null;
|
||||
if (wrapperColourObserverTimeout) {
|
||||
clearTimeout(wrapperColourObserverTimeout);
|
||||
wrapperColourObserverTimeout = null;
|
||||
}
|
||||
teardownRubricCopyButtons();
|
||||
unregisterWrapperMount();
|
||||
unregisterSelectedMount();
|
||||
};
|
||||
},
|
||||
};
|
||||
|
||||
|
||||
@@ -25,6 +25,91 @@ export interface WeightingEntry {
|
||||
|
||||
export type WeightingsMap = Record<string, WeightingEntry>;
|
||||
|
||||
/** Primary storage key for weightings / overrides. */
|
||||
export function assessmentIdKey(mark: { id: string | number }): string {
|
||||
return String(mark.id);
|
||||
}
|
||||
|
||||
/** Composite lookup key when the same title appears in multiple metaclasses. */
|
||||
export function assessmentTitleLookupKey(mark: {
|
||||
metaclassID?: string | number;
|
||||
title?: string;
|
||||
}): string | null {
|
||||
const title = mark.title?.trim();
|
||||
if (!title) return null;
|
||||
const metaclassID = mark.metaclassID;
|
||||
if (metaclassID != null && metaclassID !== "") {
|
||||
return `${metaclassID}:${title}`;
|
||||
}
|
||||
return title;
|
||||
}
|
||||
|
||||
function registerAssessmentLookup(api: any, mark: any) {
|
||||
const assessmentID = assessmentIdKey(mark);
|
||||
const next: Record<string, string> = {
|
||||
...api.storage.assessments,
|
||||
[assessmentID]: assessmentID,
|
||||
};
|
||||
const compositeKey = assessmentTitleLookupKey(mark);
|
||||
if (compositeKey) next[compositeKey] = assessmentID;
|
||||
api.storage.assessments = next;
|
||||
}
|
||||
|
||||
type MarkLike = {
|
||||
id: string | number;
|
||||
title?: string;
|
||||
metaclassID?: string | number;
|
||||
};
|
||||
|
||||
function collectMarksFromFiberState(state: Record<string, unknown>): MarkLike[] {
|
||||
return [
|
||||
...(Array.isArray(state.marks) ? state.marks : []),
|
||||
...(Array.isArray(state.upcoming) ? state.upcoming : []),
|
||||
...(Array.isArray(state.pending) ? state.pending : []),
|
||||
] as MarkLike[];
|
||||
}
|
||||
|
||||
async function resolveAssessmentId(
|
||||
api: any,
|
||||
title: string,
|
||||
marks?: MarkLike[],
|
||||
): Promise<string | undefined> {
|
||||
const assessments = (api.storage.assessments ?? {}) as Record<string, string>;
|
||||
let resolvedMarks = marks;
|
||||
|
||||
if (!resolvedMarks) {
|
||||
try {
|
||||
const state = await ReactFiber.find(
|
||||
"[class*='AssessmentList__items___']",
|
||||
).getState();
|
||||
resolvedMarks = collectMarksFromFiberState(state);
|
||||
} catch {
|
||||
resolvedMarks = [];
|
||||
}
|
||||
}
|
||||
|
||||
const matching = resolvedMarks.filter((mark) => mark.title?.trim() === title);
|
||||
if (matching.length === 1) {
|
||||
return assessmentIdKey(matching[0]);
|
||||
}
|
||||
|
||||
for (const mark of matching) {
|
||||
const compositeKey = assessmentTitleLookupKey(mark);
|
||||
if (compositeKey && assessments[compositeKey]) {
|
||||
return assessments[compositeKey];
|
||||
}
|
||||
}
|
||||
|
||||
if (assessments[title]) return assessments[title];
|
||||
|
||||
const suffix = `:${title}`;
|
||||
for (const [key, id] of Object.entries(assessments)) {
|
||||
if (key.endsWith(suffix)) return id;
|
||||
}
|
||||
|
||||
return undefined;
|
||||
}
|
||||
|
||||
export function computeFingerprint(mark: any): string {
|
||||
const score =
|
||||
mark?.results?.percentage ?? mark?.results?.score ?? null;
|
||||
@@ -264,6 +349,7 @@ function createWeightLabel(
|
||||
weighting: string | undefined,
|
||||
api: any,
|
||||
refreshing = false,
|
||||
assessmentID?: string,
|
||||
) {
|
||||
let statsContainer = assessmentItem.querySelector(
|
||||
`[class*='AssessmentItem__stats___'], .betterseqta-stats-container`,
|
||||
@@ -289,10 +375,8 @@ function createWeightLabel(
|
||||
? "space-between"
|
||||
: "flex-end";
|
||||
|
||||
const title = assessmentItem
|
||||
.querySelector(`[class*='AssessmentItem__title___']`)
|
||||
?.textContent?.trim();
|
||||
const assessmentID = title ? api.storage.assessments?.[title] : undefined;
|
||||
const resolvedAssessmentId =
|
||||
assessmentID ?? assessmentItem.dataset.betterseqtaAssessmentId;
|
||||
|
||||
const existingLabel = statsContainer.querySelector(
|
||||
".betterseqta-weight-label",
|
||||
@@ -302,7 +386,7 @@ function createWeightLabel(
|
||||
updateWeightLabelContent(
|
||||
existingLabel,
|
||||
weighting,
|
||||
assessmentID,
|
||||
resolvedAssessmentId,
|
||||
api,
|
||||
refreshing,
|
||||
);
|
||||
@@ -340,7 +424,7 @@ function createWeightLabel(
|
||||
updateWeightLabelContent(
|
||||
weightLabel,
|
||||
weighting,
|
||||
assessmentID,
|
||||
resolvedAssessmentId,
|
||||
api,
|
||||
refreshing,
|
||||
);
|
||||
@@ -352,14 +436,20 @@ export const isFirefox =
|
||||
!navigator.userAgent.toLowerCase().includes("seamonkey") &&
|
||||
!navigator.userAgent.toLowerCase().includes("waterfox");
|
||||
|
||||
function trustedPageOrigin(): string {
|
||||
return window.location.origin;
|
||||
}
|
||||
|
||||
async function fetchPDFAsArrayBuffer(url: string): Promise<ArrayBuffer> {
|
||||
const isBlobUrl = url.startsWith("blob:");
|
||||
const pageOrigin = trustedPageOrigin();
|
||||
|
||||
if (isBlobUrl || isFirefox) {
|
||||
return new Promise((resolve, reject) => {
|
||||
const script = document.createElement("script");
|
||||
const requestId = `pdf-fetch-${Date.now()}-${Math.random()}`;
|
||||
const escapedUrl = url.replace(/'/g, "\\'");
|
||||
const escapedOrigin = pageOrigin.replace(/'/g, "\\'");
|
||||
|
||||
script.textContent = `
|
||||
(function() {
|
||||
@@ -375,19 +465,20 @@ async function fetchPDFAsArrayBuffer(url: string): Promise<ArrayBuffer> {
|
||||
type: '${requestId}',
|
||||
success: true,
|
||||
data: Array.from(new Uint8Array(arrayBuffer))
|
||||
}, '*');
|
||||
}, '${escapedOrigin}');
|
||||
})
|
||||
.catch(error => {
|
||||
window.postMessage({
|
||||
type: '${requestId}',
|
||||
success: false,
|
||||
error: error.message || String(error)
|
||||
}, '*');
|
||||
}, '${escapedOrigin}');
|
||||
});
|
||||
})();
|
||||
`;
|
||||
|
||||
const messageHandler = (event: MessageEvent) => {
|
||||
if (event.origin !== pageOrigin || event.source !== window) return;
|
||||
if (event.data?.type === requestId) {
|
||||
window.removeEventListener("message", messageHandler);
|
||||
if (script.parentNode) {
|
||||
@@ -454,6 +545,9 @@ export async function extractPDFText(url: string): Promise<string> {
|
||||
const pdfLibInj = escJsSingleQuoted(pdfLibUrl);
|
||||
const pdfWorkerInj = escJsSingleQuoted(pdfWorkerUrl);
|
||||
|
||||
const pageOrigin = trustedPageOrigin();
|
||||
const escapedOrigin = pageOrigin.replace(/'/g, "\\'");
|
||||
|
||||
return new Promise((resolve, reject) => {
|
||||
const script = document.createElement("script");
|
||||
const requestId = `pdf-extract-${Date.now()}-${Math.random()}`;
|
||||
@@ -466,6 +560,7 @@ export async function extractPDFText(url: string): Promise<string> {
|
||||
script.textContent = `
|
||||
(function() {
|
||||
const requestId = '${requestId}';
|
||||
const pageOrigin = '${escapedOrigin}';
|
||||
const url = '${escapedUrl}';
|
||||
const pdfLibSrc = '${pdfLibInj}';
|
||||
const pdfWorkerSrc = '${pdfWorkerInj}';
|
||||
@@ -485,7 +580,7 @@ export async function extractPDFText(url: string): Promise<string> {
|
||||
type: requestId,
|
||||
success: false,
|
||||
error: 'Failed to load pdfjs library'
|
||||
}, '*');
|
||||
}, pageOrigin);
|
||||
};
|
||||
|
||||
document.head.appendChild(pdfjsScript);
|
||||
@@ -506,7 +601,7 @@ export async function extractPDFText(url: string): Promise<string> {
|
||||
type: requestId,
|
||||
success: false,
|
||||
error: 'HTTP ' + xhr.status + ': ' + xhr.statusText
|
||||
}, '*');
|
||||
}, pageOrigin);
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -542,21 +637,21 @@ export async function extractPDFText(url: string): Promise<string> {
|
||||
type: requestId,
|
||||
success: true,
|
||||
text: text
|
||||
}, '*');
|
||||
}, pageOrigin);
|
||||
})
|
||||
.catch(error => {
|
||||
window.postMessage({
|
||||
type: requestId,
|
||||
success: false,
|
||||
error: 'PDF parsing error: ' + (error.message || String(error))
|
||||
}, '*');
|
||||
}, pageOrigin);
|
||||
});
|
||||
} catch (error) {
|
||||
window.postMessage({
|
||||
type: requestId,
|
||||
success: false,
|
||||
error: 'ArrayBuffer error: ' + (error.message || String(error))
|
||||
}, '*');
|
||||
}, pageOrigin);
|
||||
}
|
||||
};
|
||||
|
||||
@@ -565,7 +660,7 @@ export async function extractPDFText(url: string): Promise<string> {
|
||||
type: requestId,
|
||||
success: false,
|
||||
error: 'Network error fetching PDF'
|
||||
}, '*');
|
||||
}, pageOrigin);
|
||||
};
|
||||
|
||||
xhr.ontimeout = function() {
|
||||
@@ -573,7 +668,7 @@ export async function extractPDFText(url: string): Promise<string> {
|
||||
type: requestId,
|
||||
success: false,
|
||||
error: 'Timeout fetching PDF'
|
||||
}, '*');
|
||||
}, pageOrigin);
|
||||
};
|
||||
|
||||
xhr.timeout = 30000;
|
||||
@@ -583,13 +678,14 @@ export async function extractPDFText(url: string): Promise<string> {
|
||||
type: requestId,
|
||||
success: false,
|
||||
error: 'Setup error: ' + (error.message || String(error))
|
||||
}, '*');
|
||||
}, pageOrigin);
|
||||
}
|
||||
}
|
||||
})();
|
||||
`;
|
||||
|
||||
const messageHandler = (event: MessageEvent) => {
|
||||
if (event.origin !== pageOrigin || event.source !== window) return;
|
||||
if (event.data?.type === requestId) {
|
||||
window.removeEventListener("message", messageHandler);
|
||||
if (script.parentNode) {
|
||||
@@ -646,9 +742,8 @@ export async function extractPDFText(url: string): Promise<string> {
|
||||
}
|
||||
|
||||
async function handleWeightings(mark: any, api: any) {
|
||||
const assessmentID = mark.id;
|
||||
const assessmentID = assessmentIdKey(mark);
|
||||
const metaclassID = mark.metaclassID;
|
||||
const title = mark.title;
|
||||
|
||||
const fingerprint = computeFingerprint(mark);
|
||||
const existing = api.storage.weightings[assessmentID] as
|
||||
@@ -687,10 +782,7 @@ async function handleWeightings(mark: any, api: any) {
|
||||
[assessmentID]: placeholder,
|
||||
};
|
||||
|
||||
api.storage.assessments = {
|
||||
...api.storage.assessments,
|
||||
[title.trim()]: assessmentID,
|
||||
};
|
||||
registerAssessmentLookup(api, mark);
|
||||
|
||||
// Surface the refreshing indicator on the affected row immediately,
|
||||
// without waiting for the PDF fetch to finish.
|
||||
@@ -813,6 +905,16 @@ export async function processAssessments(api: any, assessmentItems: Element[]) {
|
||||
let hasRefreshingWeighting = false;
|
||||
let count = 0;
|
||||
|
||||
let fiberMarks: MarkLike[] = [];
|
||||
try {
|
||||
const state = await ReactFiber.find(
|
||||
"[class*='AssessmentList__items___']",
|
||||
).getState();
|
||||
fiberMarks = collectMarksFromFiberState(state);
|
||||
} catch {
|
||||
fiberMarks = [];
|
||||
}
|
||||
|
||||
for (const assessmentItem of assessmentItems) {
|
||||
const titleEl = assessmentItem.querySelector(
|
||||
`[class*='AssessmentItem__title___']`,
|
||||
@@ -822,7 +924,11 @@ export async function processAssessments(api: any, assessmentItems: Element[]) {
|
||||
const title = titleEl.textContent?.trim();
|
||||
if (!title) continue;
|
||||
|
||||
const assessmentID = api.storage.assessments?.[title];
|
||||
const assessmentID = await resolveAssessmentId(api, title, fiberMarks);
|
||||
if (assessmentID) {
|
||||
(assessmentItem as HTMLElement).dataset.betterseqtaAssessmentId =
|
||||
assessmentID;
|
||||
}
|
||||
const entry = assessmentID
|
||||
? (api.storage.weightings?.[assessmentID] as WeightingEntry | undefined)
|
||||
: undefined;
|
||||
@@ -833,7 +939,7 @@ export async function processAssessments(api: any, assessmentItems: Element[]) {
|
||||
const weighting = override ?? autoWeighting;
|
||||
const refreshing = !override && Boolean(entry?.refreshing);
|
||||
|
||||
createWeightLabel(assessmentItem, weighting, api, refreshing);
|
||||
createWeightLabel(assessmentItem, weighting, api, refreshing, assessmentID);
|
||||
|
||||
const gradeElement = assessmentItem.querySelector(
|
||||
`[class*='Thermoscore__text___']`,
|
||||
@@ -935,12 +1041,17 @@ function resolveTabSetClasses(): Record<string, string> {
|
||||
return resolved;
|
||||
}
|
||||
|
||||
function buildWeightingsTabContent(api: any, sheet: HTMLElement) {
|
||||
const titleEl = document.querySelector(
|
||||
"[class*='AssessmentItem__AssessmentItem___'][class*='selected___'] [class*='AssessmentItem__title___']",
|
||||
async function buildWeightingsTabContent(api: any, sheet: HTMLElement) {
|
||||
const selectedItem = document.querySelector(
|
||||
"[class*='AssessmentItem__AssessmentItem___'][class*='selected___']",
|
||||
) as HTMLElement | null;
|
||||
const titleEl = selectedItem?.querySelector(
|
||||
"[class*='AssessmentItem__title___']",
|
||||
);
|
||||
const title = titleEl?.textContent?.trim();
|
||||
const assessmentID = title ? api.storage.assessments?.[title] : undefined;
|
||||
const assessmentID =
|
||||
selectedItem?.dataset.betterseqtaAssessmentId ??
|
||||
(title ? await resolveAssessmentId(api, title) : undefined);
|
||||
|
||||
const entry = assessmentID
|
||||
? (api.storage.weightings?.[assessmentID] as WeightingEntry | undefined)
|
||||
@@ -1093,7 +1204,7 @@ export function injectWeightingsTab(api: any) {
|
||||
container.appendChild(newSheet);
|
||||
|
||||
newTab.addEventListener("click", () => {
|
||||
buildWeightingsTabContent(api, newSheet);
|
||||
void buildWeightingsTabContent(api, newSheet);
|
||||
});
|
||||
|
||||
const allTabs = Array.from(tabList.querySelectorAll("li"));
|
||||
@@ -1107,13 +1218,14 @@ export function injectWeightingsTab(api: any) {
|
||||
t.className.includes("TabSet__selected___"),
|
||||
);
|
||||
if (i === currentIndex) return;
|
||||
const goingRight = i > currentIndex;
|
||||
const goingRight = currentIndex < 0 ? true : i > currentIndex;
|
||||
|
||||
allTabs.forEach((t) => {
|
||||
t.className = "";
|
||||
t.setAttribute("aria-selected", "false");
|
||||
});
|
||||
|
||||
if (currentIndex >= 0) {
|
||||
allSheets[currentIndex].className = [
|
||||
cls["TabSet__tabsheet___"],
|
||||
cls["TabSet__hidden___"],
|
||||
@@ -1121,6 +1233,7 @@ export function injectWeightingsTab(api: any) {
|
||||
? cls["TabSet__disappearToLeft___"]
|
||||
: cls["TabSet__disappearToRight___"],
|
||||
].join(" ");
|
||||
}
|
||||
|
||||
allSheets[i].className = [
|
||||
cls["TabSet__tabsheet___"],
|
||||
|
||||
@@ -29,6 +29,9 @@ async function fetchJSON(url: string, body: any) {
|
||||
headers: { "Content-Type": "application/json; charset=utf-8" },
|
||||
body: JSON.stringify(body),
|
||||
});
|
||||
if (!res.ok) {
|
||||
throw new Error(`HTTP ${res.status} for ${url}`);
|
||||
}
|
||||
return res.json();
|
||||
}
|
||||
|
||||
@@ -164,7 +167,7 @@ async function getLearnAssessmentsData(studentId: number) {
|
||||
}
|
||||
|
||||
export async function getAssessmentsData() {
|
||||
if (settingsState.mockNotices) {
|
||||
if (settingsState.hideSensitiveContent) {
|
||||
return getMockAssessmentsData();
|
||||
}
|
||||
|
||||
|
||||
@@ -38,6 +38,9 @@ async function fetchJSON(url: string, body: unknown) {
|
||||
headers: { "Content-Type": "application/json; charset=utf-8" },
|
||||
body: JSON.stringify(body),
|
||||
});
|
||||
if (!res.ok) {
|
||||
throw new Error(`HTTP ${res.status} for ${url}`);
|
||||
}
|
||||
return res.json();
|
||||
}
|
||||
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import type { Plugin } from "../../core/types";
|
||||
import { waitForElm } from "@/seqta/utils/waitForElm";
|
||||
import { getAssessmentsData } from "./api";
|
||||
import { renderErrorState, renderGrid, renderSkeletonLoader } from "./ui";
|
||||
import { renderErrorState, renderGrid, renderSkeletonLoader, teardownOverviewUi } from "./ui";
|
||||
import styles from "./styles.css?inline";
|
||||
import { delay } from "@/seqta/utils/delay";
|
||||
import { isSeqtaEngageExperience } from "@/seqta/utils/isSeqtaEngage";
|
||||
@@ -66,6 +66,8 @@ const assessmentsOverviewPlugin: Plugin<{}> = {
|
||||
gridItem.appendChild(label);
|
||||
menu.insertBefore(gridItem, menu.firstChild);
|
||||
|
||||
let loadRequestId = 0;
|
||||
|
||||
const menuObserver = new MutationObserver(() => {
|
||||
ensureOverviewMenuPosition(menu, gridItem);
|
||||
});
|
||||
@@ -81,7 +83,18 @@ const assessmentsOverviewPlugin: Plugin<{}> = {
|
||||
};
|
||||
gridItem.addEventListener("click", clickHandler);
|
||||
|
||||
const popstateHandler = () => {
|
||||
if (isOverviewRoute()) {
|
||||
void loadGridView();
|
||||
} else {
|
||||
loadRequestId += 1;
|
||||
teardownOverviewUi();
|
||||
}
|
||||
};
|
||||
window.addEventListener("popstate", popstateHandler);
|
||||
|
||||
async function loadGridView() {
|
||||
const requestId = ++loadRequestId;
|
||||
await delay(1);
|
||||
|
||||
if (isSeqtaEngageExperience()) {
|
||||
@@ -98,7 +111,7 @@ const assessmentsOverviewPlugin: Plugin<{}> = {
|
||||
}
|
||||
|
||||
const main = document.getElementById("main");
|
||||
if (!main) return;
|
||||
if (!main || requestId !== loadRequestId) return;
|
||||
|
||||
document
|
||||
.querySelectorAll('[data-key="assessments"] .item')
|
||||
@@ -110,17 +123,22 @@ const assessmentsOverviewPlugin: Plugin<{}> = {
|
||||
.querySelector('[data-key="assessments"]')
|
||||
?.classList.add("active");
|
||||
|
||||
main.innerHTML = '<div id="grid-view-container" class="bsplus-overview-host"></div>';
|
||||
main.innerHTML =
|
||||
'<div id="grid-view-container" class="bsplus-overview-host"></div>';
|
||||
const container = document.getElementById(
|
||||
"grid-view-container",
|
||||
) as HTMLElement;
|
||||
|
||||
if (requestId !== loadRequestId) return;
|
||||
|
||||
renderSkeletonLoader(container);
|
||||
|
||||
try {
|
||||
const data = await getAssessmentsData();
|
||||
if (requestId !== loadRequestId) return;
|
||||
renderGrid(container, data);
|
||||
} catch (err) {
|
||||
if (requestId !== loadRequestId) return;
|
||||
console.error("Failed to load assessments:", err);
|
||||
renderErrorState(
|
||||
container,
|
||||
@@ -130,8 +148,11 @@ const assessmentsOverviewPlugin: Plugin<{}> = {
|
||||
}
|
||||
|
||||
return () => {
|
||||
loadRequestId += 1;
|
||||
window.removeEventListener("popstate", popstateHandler);
|
||||
menuObserver.disconnect();
|
||||
gridItem.removeEventListener("click", clickHandler);
|
||||
teardownOverviewUi();
|
||||
gridItem.remove();
|
||||
};
|
||||
},
|
||||
|
||||
@@ -62,7 +62,7 @@ export function activeSubjectsFromEngageChild(child: {
|
||||
const seen = new Set<string>();
|
||||
|
||||
for (const term of child.terms ?? []) {
|
||||
if (term.active !== 1) continue;
|
||||
if (!isActiveTermFlag(term.active)) continue;
|
||||
for (const raw of term.subjects ?? []) {
|
||||
const subject = normalizeOverviewSubject(raw);
|
||||
if (!subject) continue;
|
||||
@@ -151,7 +151,14 @@ export function determineStatus(item: any): string {
|
||||
}
|
||||
|
||||
const completedKey = "betterseqta-completed-assessments";
|
||||
const completed = JSON.parse(localStorage.getItem(completedKey) || "[]");
|
||||
let completed: unknown[] = [];
|
||||
try {
|
||||
const raw = localStorage.getItem(completedKey);
|
||||
const parsed = raw ? JSON.parse(raw) : [];
|
||||
completed = Array.isArray(parsed) ? parsed : [];
|
||||
} catch {
|
||||
completed = [];
|
||||
}
|
||||
if (completed.includes(item.id)) {
|
||||
return "MARKS_RELEASED";
|
||||
}
|
||||
|
||||
@@ -74,7 +74,10 @@ function ensureGestureStart(handler: () => void): () => void {
|
||||
|
||||
async function startPlayback(volume: number): Promise<void> {
|
||||
const blob = await loadAudioBlob();
|
||||
if (!blob) return;
|
||||
if (!blob) {
|
||||
stopAndCleanupAudio();
|
||||
return;
|
||||
}
|
||||
|
||||
stopAndCleanupAudio();
|
||||
|
||||
@@ -123,7 +126,7 @@ const backgroundMusicPlugin: Plugin<typeof settings> = {
|
||||
}
|
||||
});
|
||||
|
||||
// Note: Stop button/event removed by user; no stop handling needed
|
||||
// Note: Stop button dispatches betterseqta-background-music-stop on remove
|
||||
|
||||
// Start if we have audio and autoplay is enabled
|
||||
const tryStart = async () => {
|
||||
@@ -160,16 +163,21 @@ const backgroundMusicPlugin: Plugin<typeof settings> = {
|
||||
};
|
||||
document.addEventListener("visibilitychange", visHandler);
|
||||
|
||||
// Allow uploads to trigger refresh
|
||||
// Allow uploads to trigger refresh; stop event clears playback on remove
|
||||
const uploadedHandler = () => {
|
||||
const vol = (api.settings as any).volume ?? 0.5;
|
||||
startPlayback(vol);
|
||||
};
|
||||
const stopHandler = () => {
|
||||
stopAndCleanupAudio();
|
||||
};
|
||||
window.addEventListener("betterseqta-background-music-updated", uploadedHandler);
|
||||
window.addEventListener("betterseqta-background-music-stop", stopHandler);
|
||||
|
||||
return () => {
|
||||
document.removeEventListener("visibilitychange", visHandler);
|
||||
window.removeEventListener("betterseqta-background-music-updated", uploadedHandler);
|
||||
window.removeEventListener("betterseqta-background-music-stop", stopHandler);
|
||||
if (cleanupRegistered && (window as any).__betterseqta_bg_music_cancel__) {
|
||||
(window as any).__betterseqta_bg_music_cancel__();
|
||||
(window as any).__betterseqta_bg_music_cancel__ = undefined;
|
||||
|
||||
@@ -255,9 +255,9 @@ const watchNavigator = (navigator: Element, onChange: () => void) => {
|
||||
return observer;
|
||||
};
|
||||
|
||||
const handleSlidePane = (pane: Element) => {
|
||||
const handleSlidePane = (pane: Element): (() => void) => {
|
||||
const navigator = pane.querySelector(".navigator");
|
||||
if (!navigator) return;
|
||||
if (!navigator) return () => {};
|
||||
|
||||
requestAnimationFrame(() => scrollSelectedIntoView(navigator));
|
||||
setTimeout(() => scrollSelectedIntoView(navigator), 50);
|
||||
@@ -272,17 +272,22 @@ const handleSlidePane = (pane: Element) => {
|
||||
childList: true,
|
||||
});
|
||||
|
||||
const cleanup = new MutationObserver((muts) => {
|
||||
const paneCleanup = new MutationObserver((muts) => {
|
||||
muts.forEach((m) => {
|
||||
m.removedNodes.forEach((n) => {
|
||||
if (n === pane) {
|
||||
observer.disconnect();
|
||||
cleanup.disconnect();
|
||||
paneCleanup.disconnect();
|
||||
}
|
||||
});
|
||||
});
|
||||
});
|
||||
cleanup.observe(document.body, { childList: true });
|
||||
paneCleanup.observe(document.body, { childList: true });
|
||||
|
||||
return () => {
|
||||
observer.disconnect();
|
||||
paneCleanup.disconnect();
|
||||
};
|
||||
};
|
||||
|
||||
const enhancedNavigationPlugin: Plugin<typeof settings> = {
|
||||
@@ -301,7 +306,11 @@ const enhancedNavigationPlugin: Plugin<typeof settings> = {
|
||||
window.addEventListener("resize", positionArrows);
|
||||
window.addEventListener("scroll", positionArrows, true);
|
||||
|
||||
api.seqta.onMount(".course", async (element) => {
|
||||
const navObservers: MutationObserver[] = [];
|
||||
const courseObservers: MutationObserver[] = [];
|
||||
const slidePaneCleanups: Array<() => void> = [];
|
||||
|
||||
const courseMount = api.seqta.onMount(".course", async (element) => {
|
||||
const course = element as HTMLElement;
|
||||
let navObserver: MutationObserver | null = null;
|
||||
|
||||
@@ -318,6 +327,7 @@ const enhancedNavigationPlugin: Plugin<typeof settings> = {
|
||||
}
|
||||
ensureArrows(course);
|
||||
});
|
||||
navObservers.push(navObserver);
|
||||
return true;
|
||||
};
|
||||
|
||||
@@ -325,6 +335,7 @@ const enhancedNavigationPlugin: Plugin<typeof settings> = {
|
||||
const courseObserver = new MutationObserver(() => {
|
||||
if (setup()) courseObserver.disconnect();
|
||||
});
|
||||
courseObservers.push(courseObserver);
|
||||
courseObserver.observe(course, { childList: true, subtree: true });
|
||||
}
|
||||
});
|
||||
@@ -334,13 +345,21 @@ const enhancedNavigationPlugin: Plugin<typeof settings> = {
|
||||
m.addedNodes.forEach((n) => {
|
||||
if (n.nodeType !== 1) return;
|
||||
const el = n as Element;
|
||||
if (el.classList?.contains("uiSlidePane")) handleSlidePane(el);
|
||||
if (el.classList?.contains("uiSlidePane")) {
|
||||
slidePaneCleanups.push(handleSlidePane(el));
|
||||
}
|
||||
});
|
||||
});
|
||||
});
|
||||
bodyObserver.observe(document.body, { childList: true });
|
||||
|
||||
return () => {
|
||||
window.removeEventListener("resize", positionArrows);
|
||||
window.removeEventListener("scroll", positionArrows, true);
|
||||
courseMount.unregister();
|
||||
navObservers.forEach((observer) => observer.disconnect());
|
||||
courseObservers.forEach((observer) => observer.disconnect());
|
||||
slidePaneCleanups.forEach((cleanup) => cleanup());
|
||||
bodyObserver.disconnect();
|
||||
document.getElementById(ARROW_CONTAINER_ID)?.remove();
|
||||
document.getElementById(STYLE_ID)?.remove();
|
||||
|
||||
@@ -175,6 +175,7 @@
|
||||
const term = searchTerm.trim().toLowerCase();
|
||||
const requestId = ++searchRequestId;
|
||||
|
||||
try {
|
||||
if (commandsFuse && dynamicContentFuse) {
|
||||
const results = await doSearch(
|
||||
term,
|
||||
@@ -196,8 +197,13 @@
|
||||
if (requestId !== searchRequestId) return;
|
||||
combinedResults = [];
|
||||
}
|
||||
|
||||
} finally {
|
||||
// Only clear loading for the latest in-flight search — stale async
|
||||
// passes must not leave the spinner stuck after fast typing.
|
||||
if (requestId === searchRequestId) {
|
||||
isLoading = false;
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
// Optimized debounce: shorter delay for better responsiveness
|
||||
|
||||
@@ -214,7 +214,7 @@ const staticCommands: StaticCommandItem[] = [
|
||||
code: 'KeyM',
|
||||
keyCode: 77,
|
||||
altKey: true
|
||||
}, "*");
|
||||
}, location.origin);
|
||||
},
|
||||
keywords: ["compose", "message", "dm", "direct message", "new message"],
|
||||
priority: 3,
|
||||
|
||||
@@ -37,6 +37,41 @@ export function mountSearchBar(
|
||||
const searchButton = document.createElement("div");
|
||||
searchButton.className = "search-trigger";
|
||||
|
||||
const searchIcon = document.createElementNS("http://www.w3.org/2000/svg", "svg");
|
||||
searchIcon.setAttribute("xmlns", "http://www.w3.org/2000/svg");
|
||||
searchIcon.setAttribute("width", "16");
|
||||
searchIcon.setAttribute("height", "16");
|
||||
searchIcon.setAttribute("viewBox", "0 0 24 24");
|
||||
searchIcon.setAttribute("fill", "none");
|
||||
searchIcon.setAttribute("stroke", "currentColor");
|
||||
searchIcon.setAttribute("stroke-width", "2");
|
||||
searchIcon.setAttribute("stroke-linecap", "round");
|
||||
searchIcon.setAttribute("stroke-linejoin", "round");
|
||||
|
||||
const circle = document.createElementNS("http://www.w3.org/2000/svg", "circle");
|
||||
circle.setAttribute("cx", "11");
|
||||
circle.setAttribute("cy", "11");
|
||||
circle.setAttribute("r", "8");
|
||||
searchIcon.appendChild(circle);
|
||||
|
||||
const line = document.createElementNS("http://www.w3.org/2000/svg", "line");
|
||||
line.setAttribute("x1", "21");
|
||||
line.setAttribute("y1", "21");
|
||||
line.setAttribute("x2", "16.65");
|
||||
line.setAttribute("y2", "16.65");
|
||||
searchIcon.appendChild(line);
|
||||
|
||||
const searchLabel = document.createElement("p");
|
||||
searchLabel.textContent = "Quick search...";
|
||||
|
||||
const hotkeySpan = document.createElement("span");
|
||||
hotkeySpan.className = "search-trigger-hotkey";
|
||||
hotkeySpan.style.marginLeft = "auto";
|
||||
hotkeySpan.style.display = "flex";
|
||||
hotkeySpan.style.alignItems = "center";
|
||||
hotkeySpan.style.color = "#777";
|
||||
hotkeySpan.style.fontSize = "12px";
|
||||
|
||||
const progressBarWrapper = document.createElement("div");
|
||||
progressBarWrapper.className = "search-progress-bar-wrapper";
|
||||
|
||||
@@ -234,14 +269,10 @@ export function mountSearchBar(
|
||||
appRef.clearDoneFlashTimer = clearDoneFlashTimer;
|
||||
|
||||
const updateSearchButtonDisplay = () => {
|
||||
searchButton.innerHTML = /* html */ `
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
|
||||
<circle cx="11" cy="11" r="8"></circle>
|
||||
<line x1="21" y1="21" x2="16.65" y2="16.65"></line>
|
||||
</svg>
|
||||
<p>Quick search...</p>
|
||||
<span style="margin-left: auto; display: flex; align-items: center; color: #777; font-size: 12px;">${hotkeyDisplay}</span>
|
||||
`;
|
||||
hotkeySpan.textContent = hotkeyDisplay;
|
||||
if (!searchButton.contains(searchIcon)) {
|
||||
searchButton.replaceChildren(searchIcon, searchLabel, hotkeySpan);
|
||||
}
|
||||
};
|
||||
|
||||
updateSearchButtonDisplay();
|
||||
|
||||
@@ -4,7 +4,7 @@ import { renderComponentMap } from "./renderComponents";
|
||||
import type { IndexItem, Job, JobContext } from "./types";
|
||||
import { VectorWorkerManager } from "./worker/vectorWorkerManager";
|
||||
import { loadDynamicItems } from "../utils/dynamicItems";
|
||||
import { getVectorizedItemIds } from "./utils";
|
||||
import { getVectorizedItemIds, pruneOrphanVectorEmbeddings } from "./utils";
|
||||
import { INDEX_SCHEMA_VERSION, SCHEMA_VERSION_KEY } from "./schemaVersion";
|
||||
|
||||
const META_STORE = "meta";
|
||||
@@ -220,6 +220,7 @@ export async function runIndexing(): Promise<void> {
|
||||
startHeartbeat();
|
||||
console.debug("%c[Indexer] Starting indexing...", "color: green");
|
||||
|
||||
try {
|
||||
const jobIds = Object.keys(jobs);
|
||||
let completedJobs = 0;
|
||||
const totalSteps = jobIds.length + 1;
|
||||
@@ -320,6 +321,17 @@ export async function runIndexing(): Promise<void> {
|
||||
|
||||
let allItemsInPrimaryStores = await loadAllStoredItems();
|
||||
|
||||
const liveItemIds = new Set(allItemsInPrimaryStores.map((item) => item.id));
|
||||
const prunedCount = await pruneOrphanVectorEmbeddings(liveItemIds);
|
||||
if (prunedCount > 0) {
|
||||
try {
|
||||
const { refreshVectorCache } = await import("../search/vector/vectorSearch");
|
||||
await refreshVectorCache();
|
||||
} catch (e) {
|
||||
console.warn("[Indexer] Failed to refresh vector cache after prune:", e);
|
||||
}
|
||||
}
|
||||
|
||||
if (allItemsInPrimaryStores.length > 0) {
|
||||
console.debug(
|
||||
`%c[Indexer] Checking ${allItemsInPrimaryStores.length} items for vectorization...`,
|
||||
@@ -434,8 +446,6 @@ export async function runIndexing(): Promise<void> {
|
||||
);
|
||||
}
|
||||
|
||||
stopHeartbeat();
|
||||
|
||||
allItemsInPrimaryStores = await loadAllStoredItems();
|
||||
// Create new objects to avoid XrayWrapper issues in Firefox
|
||||
const itemsWithComponents = allItemsInPrimaryStores.map(item => {
|
||||
@@ -466,6 +476,9 @@ export async function runIndexing(): Promise<void> {
|
||||
});
|
||||
loadDynamicItems(itemsWithComponents);
|
||||
window.dispatchEvent(new Event("dynamic-items-updated"));
|
||||
} finally {
|
||||
stopHeartbeat();
|
||||
}
|
||||
}
|
||||
|
||||
function mergeItems(existing: IndexItem[], incoming: IndexItem[]): IndexItem[] {
|
||||
|
||||
@@ -53,6 +53,75 @@ export async function getVectorizedItemIds(): Promise<Set<string>> {
|
||||
});
|
||||
}
|
||||
|
||||
const EMBEDDIA_DB = "embeddiaDB";
|
||||
const EMBEDDIA_STORE = "embeddiaObjectStore";
|
||||
|
||||
/**
|
||||
* Remove vector embeddings for the given item ids from embeddiaDB.
|
||||
*/
|
||||
export async function removeVectorEmbeddings(ids: string[]): Promise<void> {
|
||||
if (ids.length === 0) return;
|
||||
|
||||
return new Promise((resolve) => {
|
||||
const request = indexedDB.open(EMBEDDIA_DB);
|
||||
|
||||
request.onerror = () => resolve();
|
||||
|
||||
request.onsuccess = () => {
|
||||
const db = request.result;
|
||||
|
||||
if (!db.objectStoreNames.contains(EMBEDDIA_STORE)) {
|
||||
db.close();
|
||||
resolve();
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
const transaction = db.transaction([EMBEDDIA_STORE], "readwrite");
|
||||
const store = transaction.objectStore(EMBEDDIA_STORE);
|
||||
|
||||
for (const id of ids) {
|
||||
store.delete(id);
|
||||
}
|
||||
|
||||
transaction.oncomplete = () => {
|
||||
db.close();
|
||||
resolve();
|
||||
};
|
||||
|
||||
transaction.onerror = () => {
|
||||
db.close();
|
||||
resolve();
|
||||
};
|
||||
} catch (error) {
|
||||
console.warn("[Indexer] Failed to remove vector embeddings:", error);
|
||||
db.close();
|
||||
resolve();
|
||||
}
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Delete vector embeddings that no longer exist in the structured index.
|
||||
* Returns the number of orphaned embeddings removed.
|
||||
*/
|
||||
export async function pruneOrphanVectorEmbeddings(
|
||||
liveItemIds: Set<string>,
|
||||
): Promise<number> {
|
||||
const vectorizedIds = await getVectorizedItemIds();
|
||||
const orphanIds = [...vectorizedIds].filter((id) => !liveItemIds.has(id));
|
||||
|
||||
if (orphanIds.length > 0) {
|
||||
console.debug(
|
||||
`[Indexer] Pruning ${orphanIds.length} orphaned vector embedding(s)`,
|
||||
);
|
||||
await removeVectorEmbeddings(orphanIds);
|
||||
}
|
||||
|
||||
return orphanIds.length;
|
||||
}
|
||||
|
||||
export function htmlToPlainText(rawHtml: string): string {
|
||||
const parser = new DOMParser();
|
||||
const doc = parser.parseFromString(rawHtml, "text/html");
|
||||
|
||||
@@ -242,11 +242,12 @@ export async function hybridSearch(
|
||||
export async function hybridSearchWithExpansion(
|
||||
bm25Results: CombinedResult[],
|
||||
query: string,
|
||||
_allItems: IndexItem[],
|
||||
allItems: IndexItem[],
|
||||
options: HybridSearchOptions = {},
|
||||
): Promise<CombinedResult[]> {
|
||||
const opts = { ...DEFAULT_OPTIONS, ...options };
|
||||
const trimmedQuery = query.trim().toLowerCase();
|
||||
const liveIndexIds = new Set(allItems.map((item) => item.id));
|
||||
|
||||
// First, rerank BM25 results
|
||||
const rerankedBm25 = await hybridSearch(bm25Results, query, options);
|
||||
@@ -298,6 +299,9 @@ export async function hybridSearchWithExpansion(
|
||||
vectorResults.forEach(v => {
|
||||
if (bm25Ids.has(v.object.id)) return;
|
||||
|
||||
// Drop stale vector hits for items no longer in the live structured index.
|
||||
if (!liveIndexIds.has(v.object.id)) return;
|
||||
|
||||
// This is a semantic match that BM25 missed
|
||||
const item = v.object;
|
||||
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import * as math from 'mathjs';
|
||||
import { create, all, typeOf as mathTypeOf, format as mathFormat } from 'mathjs';
|
||||
import { unitFullNames } from './unitMap';
|
||||
|
||||
export interface CalculatorResult {
|
||||
@@ -10,66 +10,42 @@ export interface CalculatorResult {
|
||||
error?: string;
|
||||
}
|
||||
|
||||
const expandedMath = math.create(math.all);
|
||||
/** Hard cap on calculator input length to limit parse/eval cost. */
|
||||
export const CALCULATOR_MAX_INPUT_LENGTH = 128;
|
||||
|
||||
expandedMath.import({
|
||||
five: 5,
|
||||
ten: 10,
|
||||
three: 3,
|
||||
four: 4,
|
||||
eight: 8,
|
||||
sixteen: 16,
|
||||
twenty: 20,
|
||||
twentyfive: 25,
|
||||
fifty: 50,
|
||||
hundred: 100,
|
||||
plus: (a: number, b: number) => a + b,
|
||||
minus: (a: number, b: number) => a - b,
|
||||
times: (a: number, b: number) => a * b,
|
||||
divided: (a: number, b: number) => a / b,
|
||||
power: (a: number, b: number) => Math.pow(a, b),
|
||||
half: (a: number) => a / 2,
|
||||
double: (a: number) => a * 2,
|
||||
quarter: (a: number) => a / 4,
|
||||
/**
|
||||
* Functions safe to replace with stubs. Do not block type constructors
|
||||
* (`complex`, `typed`, `fraction`, `bignumber`, `sparse`) or parse pipeline
|
||||
* (`parse`, `compile`, `parser`) — mathjs needs those internally and
|
||||
* `evaluate()` depends on them.
|
||||
*/
|
||||
const BLOCKED_MATH_FUNCTIONS = [
|
||||
'import',
|
||||
'createUnit',
|
||||
'random',
|
||||
'pickRandom',
|
||||
'chain',
|
||||
'help',
|
||||
] as const;
|
||||
|
||||
// String functions
|
||||
length: (str: string) => str.length,
|
||||
concat: (...args: string[]) => args.join(''),
|
||||
uppercase: (str: string) => str.toUpperCase(),
|
||||
lowercase: (str: string) => str.toLowerCase(),
|
||||
substr: (str: string, start: number, length: number) => str.substr(start, length),
|
||||
function createSandboxedMath() {
|
||||
const sandbox = create(all);
|
||||
const blockFn = () => {
|
||||
throw new Error('Function not allowed');
|
||||
};
|
||||
const blocked: Record<string, () => never> = {};
|
||||
for (const name of BLOCKED_MATH_FUNCTIONS) {
|
||||
blocked[name] = blockFn;
|
||||
}
|
||||
sandbox.import(blocked, { override: true });
|
||||
return sandbox;
|
||||
}
|
||||
|
||||
// Random functions
|
||||
randomInt: (min: number, max: number) => Math.floor(Math.random() * (max - min + 1)) + min,
|
||||
|
||||
// Comparison and Boolean operations
|
||||
and: (a: boolean, b: boolean) => a && b,
|
||||
or: (a: boolean, b: boolean) => a || b,
|
||||
not: (a: boolean) => !a,
|
||||
|
||||
// Combinatorics
|
||||
permutations: (n: number, r: number) => expandedMath.combinations(n, r) * expandedMath.factorial(r),
|
||||
nPr: (n: number, r: number) => expandedMath.combinations(n, r) * expandedMath.factorial(r),
|
||||
nCr: (n: number, r: number) => expandedMath.combinations(n, r),
|
||||
|
||||
// Number theory
|
||||
gcd: (a: number, b: number) => expandedMath.gcd(a, b),
|
||||
lcm: (a: number, b: number) => expandedMath.lcm(a, b),
|
||||
|
||||
// Precision functions
|
||||
precision: (num: number, digits: number) => parseFloat(num.toPrecision(digits)),
|
||||
fix: (num: number, digits: number) => parseFloat(num.toFixed(digits)),
|
||||
|
||||
// Percentage operations
|
||||
percent: (value: number) => value / 100,
|
||||
|
||||
// Financial operations
|
||||
compound: (principal: number, rate: number, time: number) => principal * Math.pow(1 + rate, time),
|
||||
}, { override: true });
|
||||
const calculatorMath = createSandboxedMath();
|
||||
|
||||
function detectUnit(expression: string): string {
|
||||
try {
|
||||
const unit = expandedMath.unit(expression);
|
||||
const unit = calculatorMath.unit(expression);
|
||||
if (unit) {
|
||||
const unitStr = unit.formatUnits();
|
||||
return unitFullNames[unitStr] || unitStr;
|
||||
@@ -120,9 +96,9 @@ function tryCompleteExpression(expression: string): string | null {
|
||||
// Handle cases like "4 + 3 *" -> evaluate "4 + 3"
|
||||
if (partial && !partial.match(/[\+\-\*\/\^]\s*$/)) {
|
||||
try {
|
||||
const result = expandedMath.evaluate(partial);
|
||||
const result = calculatorMath.evaluate(partial);
|
||||
if (typeof result === 'number' && !isNaN(result)) {
|
||||
return expandedMath.format(result, { precision: 14, lowerExp: -15, upperExp: 15 });
|
||||
return calculatorMath.format(result, { precision: 14, lowerExp: -15, upperExp: 15 });
|
||||
}
|
||||
} catch (e) {
|
||||
// Continue to other attempts
|
||||
@@ -148,6 +124,17 @@ export function calculateExpression(input: string): CalculatorResult {
|
||||
};
|
||||
}
|
||||
|
||||
if (trimmed.length > CALCULATOR_MAX_INPUT_LENGTH) {
|
||||
return {
|
||||
result: null,
|
||||
isValid: false,
|
||||
isPartial: false,
|
||||
inputUnit: '',
|
||||
outputUnit: '',
|
||||
error: `Expression too long (max ${CALCULATOR_MAX_INPUT_LENGTH} characters)`,
|
||||
};
|
||||
}
|
||||
|
||||
// Check if this looks like a math expression at all
|
||||
if (!isLikelyMathExpression(trimmed)) {
|
||||
return {
|
||||
@@ -161,23 +148,23 @@ export function calculateExpression(input: string): CalculatorResult {
|
||||
|
||||
try {
|
||||
// First try to evaluate the expression as-is
|
||||
const evaluated = expandedMath.evaluate(trimmed.replace('**', '^'));
|
||||
const evaluated = calculatorMath.evaluate(trimmed.replace('**', '^'));
|
||||
|
||||
if (evaluated !== undefined) {
|
||||
let result: string;
|
||||
let inputUnit = '';
|
||||
let outputUnit = '';
|
||||
|
||||
if (math.typeOf(evaluated) === 'Unit') {
|
||||
if (mathTypeOf(evaluated) === 'Unit') {
|
||||
// Handle unit conversion results
|
||||
result = expandedMath.format(evaluated, { precision: 14, lowerExp: -15, upperExp: 15 });
|
||||
result = calculatorMath.format(evaluated, { precision: 14, lowerExp: -15, upperExp: 15 });
|
||||
inputUnit = detectUnit(trimmed);
|
||||
outputUnit = detectUnit(result);
|
||||
} else if (typeof evaluated === 'number') {
|
||||
// Handle regular numbers
|
||||
result = math.format(evaluated, { precision: 14, lowerExp: -15, upperExp: 15 });
|
||||
result = mathFormat(evaluated, { precision: 14, lowerExp: -15, upperExp: 15 });
|
||||
} else {
|
||||
result = math.format(evaluated, { precision: 14, lowerExp: -15, upperExp: 15 });
|
||||
result = mathFormat(evaluated, { precision: 14, lowerExp: -15, upperExp: 15 });
|
||||
}
|
||||
|
||||
return {
|
||||
|
||||
@@ -6,6 +6,14 @@ export interface ParsedHotkey {
|
||||
key: string;
|
||||
}
|
||||
|
||||
/** Single-key allowlist: a-z, 0-9, and F1–F12 only. */
|
||||
const ALLOWED_HOTKEY_KEY = /^([a-z0-9]|f(1[0-2]|[1-9]))$/;
|
||||
|
||||
export function isAllowedHotkeyKey(key: string): boolean {
|
||||
if (!key) return false;
|
||||
return ALLOWED_HOTKEY_KEY.test(key.toLowerCase());
|
||||
}
|
||||
|
||||
export function parseHotkey(hotkeyString: string): ParsedHotkey {
|
||||
const parts = hotkeyString.toLowerCase().split('+').map(part => part.trim()).filter(part => part.length > 0);
|
||||
|
||||
@@ -68,14 +76,14 @@ export function formatHotkeyForDisplay(hotkeyString: string): string {
|
||||
parts.push(isMac ? '⇧' : 'Shift');
|
||||
}
|
||||
|
||||
if (parsed.key) {
|
||||
if (parsed.key && isAllowedHotkeyKey(parsed.key)) {
|
||||
parts.push(parsed.key.toUpperCase());
|
||||
}
|
||||
|
||||
return parts.join(isMac ? ' ' : '+');
|
||||
} catch (error) {
|
||||
console.warn('Invalid hotkey string:', hotkeyString);
|
||||
return hotkeyString; // Fallback to original string
|
||||
return 'Ctrl+K';
|
||||
}
|
||||
}
|
||||
|
||||
@@ -84,7 +92,7 @@ export function matchesHotkey(event: KeyboardEvent, hotkeyString: string): boole
|
||||
const parsed = parseHotkey(hotkeyString);
|
||||
|
||||
// If no key is specified, don't match anything
|
||||
if (!parsed.key) {
|
||||
if (!parsed.key || !isAllowedHotkeyKey(parsed.key)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
@@ -111,7 +119,7 @@ export function matchesHotkey(event: KeyboardEvent, hotkeyString: string): boole
|
||||
export function isValidHotkey(hotkeyString: string): boolean {
|
||||
try {
|
||||
const parsed = parseHotkey(hotkeyString);
|
||||
return parsed.key.length > 0;
|
||||
return parsed.key.length > 0 && isAllowedHotkeyKey(parsed.key);
|
||||
} catch (error) {
|
||||
return false;
|
||||
}
|
||||
|
||||
@@ -268,7 +268,7 @@
|
||||
|
||||
xScale={scaleBand().padding(distribution().modeUsed === "letter" ? 0.22 : 0.28)}
|
||||
|
||||
yScale={yScale()}
|
||||
yScale={yScale}
|
||||
|
||||
x="grade"
|
||||
|
||||
|
||||
@@ -35,6 +35,15 @@
|
||||
),
|
||||
);
|
||||
|
||||
$effect(() => {
|
||||
sortedData.length;
|
||||
itemsPerPage;
|
||||
const maxPage = Math.max(0, pageCount - 1);
|
||||
if (currentPage > maxPage) {
|
||||
currentPage = maxPage;
|
||||
}
|
||||
});
|
||||
|
||||
function toggleSort(column: keyof Assessment) {
|
||||
if (sortColumn === column) {
|
||||
sortDirection = sortDirection === "asc" ? "desc" : "asc";
|
||||
|
||||
@@ -53,8 +53,9 @@
|
||||
const [minG, maxG] = gradeRange;
|
||||
return analyticsData.filter((a) => {
|
||||
if (filterSubjects.length && !filterSubjects.includes(a.subject)) return false;
|
||||
const grade = a.finalGrade ?? -1;
|
||||
if (grade < minG || grade > maxG) return false;
|
||||
if (a.finalGrade !== undefined) {
|
||||
if (a.finalGrade < minG || a.finalGrade > maxG) return false;
|
||||
}
|
||||
if (
|
||||
filterSearch &&
|
||||
!a.title.toLowerCase().includes(filterSearch.toLowerCase()) &&
|
||||
|
||||
@@ -24,6 +24,9 @@ async function fetchJSON(url: string, body: Record<string, unknown>) {
|
||||
headers: { "Content-Type": "application/json; charset=utf-8" },
|
||||
body: JSON.stringify(body),
|
||||
});
|
||||
if (!res.ok) {
|
||||
throw new Error(`HTTP ${res.status} for ${url}`);
|
||||
}
|
||||
return res.json();
|
||||
}
|
||||
|
||||
@@ -254,10 +257,19 @@ async function loadAllPast(
|
||||
const results: Record<string, unknown>[][] = [];
|
||||
for (let i = 0; i < subjects.length; i += PAST_FETCH_CONCURRENCY) {
|
||||
const batch = subjects.slice(i, i + PAST_FETCH_CONCURRENCY);
|
||||
const batchResults = await Promise.all(
|
||||
const batchResults = await Promise.allSettled(
|
||||
batch.map((s) => loadPastForSubject(studentId, s)),
|
||||
);
|
||||
results.push(...batchResults);
|
||||
for (const result of batchResults) {
|
||||
if (result.status === "fulfilled") {
|
||||
results.push(result.value);
|
||||
} else {
|
||||
console.error(
|
||||
"[BetterSEQTA+] Past assessments fetch failed:",
|
||||
result.reason,
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
return results.flat();
|
||||
}
|
||||
@@ -295,7 +307,7 @@ function mergeRawAssessments(
|
||||
}
|
||||
|
||||
export async function getStudentId(): Promise<number> {
|
||||
const info = await getUserInfo();
|
||||
const info = await getUserInfo({ validateSession: true });
|
||||
const id = Number(info?.id);
|
||||
if (!id || isNaN(id)) throw new Error("Could not resolve student ID");
|
||||
return id;
|
||||
|
||||
@@ -67,6 +67,44 @@ function generateId(): string {
|
||||
return Date.now().toString(36) + Math.random().toString(36).slice(2, 7);
|
||||
}
|
||||
|
||||
function isAllowedFolderColor(color: unknown): color is string {
|
||||
return typeof color === "string" && FOLDER_COLORS.includes(color);
|
||||
}
|
||||
|
||||
function isAllowedFolderIcon(icon: unknown): icon is string {
|
||||
return typeof icon === "string" && FOLDER_HEROICONS.includes(icon);
|
||||
}
|
||||
|
||||
function normalizeFolder(folder: Folder): Folder {
|
||||
return {
|
||||
id: typeof folder.id === "string" && folder.id ? folder.id : generateId(),
|
||||
name: typeof folder.name === "string" ? folder.name.trim().slice(0, 30) : "Folder",
|
||||
color: isAllowedFolderColor(folder.color) ? folder.color : FOLDER_COLORS[0],
|
||||
emoji: isAllowedFolderIcon(folder.emoji) ? folder.emoji : FOLDER_HEROICONS[0],
|
||||
};
|
||||
}
|
||||
|
||||
function setSvgIconContent(parent: HTMLElement, svgMarkup: string): void {
|
||||
parent.replaceChildren();
|
||||
const template = document.createElement("template");
|
||||
template.innerHTML = svgMarkup.trim();
|
||||
const node = template.content.firstElementChild;
|
||||
if (node) parent.appendChild(node);
|
||||
}
|
||||
|
||||
function appendFolderBadgeContent(badge: HTMLElement, folder: Folder): void {
|
||||
badge.replaceChildren();
|
||||
if (folder.emoji) {
|
||||
const iconWrap = document.createElement("span");
|
||||
iconWrap.style.display = "inline-flex";
|
||||
iconWrap.style.verticalAlign = "middle";
|
||||
iconWrap.style.marginRight = "2px";
|
||||
setSvgIconContent(iconWrap, folder.emoji);
|
||||
badge.appendChild(iconWrap);
|
||||
}
|
||||
badge.appendChild(document.createTextNode(folder.name));
|
||||
}
|
||||
|
||||
const messageFoldersPlugin: Plugin<typeof messageFoldersSettings, MessageFoldersStorage> = {
|
||||
id: "messageFolders",
|
||||
name: "Message Folders",
|
||||
@@ -95,7 +133,8 @@ const messageFoldersPlugin: Plugin<typeof messageFoldersSettings, MessageFolders
|
||||
let foldedSection: HTMLElement | null = null;
|
||||
const unregisters: Array<{ unregister: () => void }> = [];
|
||||
|
||||
const getFolders = (): Folder[] => api.storage.folders ?? [];
|
||||
const getFolders = (): Folder[] =>
|
||||
(api.storage.folders ?? []).map((folder) => normalizeFolder(folder));
|
||||
const getAssignments = (): Record<string, string[]> => api.storage.messageAssignments ?? {};
|
||||
|
||||
const saveFolders = (folders: Folder[]) => {
|
||||
@@ -298,7 +337,7 @@ const messageFoldersPlugin: Plugin<typeof messageFoldersSettings, MessageFolders
|
||||
|
||||
const iconSpan = document.createElement("span");
|
||||
iconSpan.className = "bsplus-folder-icon";
|
||||
iconSpan.innerHTML = folder.emoji || FOLDER_HEROICONS[0];
|
||||
setSvgIconContent(iconSpan, folder.emoji || FOLDER_HEROICONS[0]);
|
||||
item.appendChild(iconSpan);
|
||||
|
||||
const name = document.createElement("span");
|
||||
@@ -622,7 +661,7 @@ const messageFoldersPlugin: Plugin<typeof messageFoldersSettings, MessageFolders
|
||||
|
||||
const iconSpan = document.createElement("span");
|
||||
iconSpan.className = "bsplus-folder-icon";
|
||||
iconSpan.innerHTML = folder.emoji || FOLDER_HEROICONS[0];
|
||||
setSvgIconContent(iconSpan, folder.emoji || FOLDER_HEROICONS[0]);
|
||||
|
||||
const name = document.createElement("span");
|
||||
name.textContent = folder.name;
|
||||
@@ -725,7 +764,7 @@ const messageFoldersPlugin: Plugin<typeof messageFoldersSettings, MessageFolders
|
||||
dot.style.background = folder.color;
|
||||
const iconSpan = document.createElement("span");
|
||||
iconSpan.className = "bsplus-folder-icon";
|
||||
iconSpan.innerHTML = folder.emoji || FOLDER_HEROICONS[0];
|
||||
setSvgIconContent(iconSpan, folder.emoji || FOLDER_HEROICONS[0]);
|
||||
const name = document.createElement("span");
|
||||
name.textContent = folder.name;
|
||||
item.appendChild(dot);
|
||||
@@ -810,7 +849,7 @@ const messageFoldersPlugin: Plugin<typeof messageFoldersSettings, MessageFolders
|
||||
const badge = document.createElement("span");
|
||||
badge.className = "bsplus-msg-badge";
|
||||
badge.style.background = folder.color;
|
||||
badge.innerHTML = `${folder.emoji ? `<span style="display:inline-flex;vertical-align:middle;margin-right:2px">${folder.emoji}</span>` : ""}${folder.name}`;
|
||||
appendFolderBadgeContent(badge, folder);
|
||||
badge.title = `Filter by "${folder.name}"`;
|
||||
badge.addEventListener("click", (e) => {
|
||||
e.stopPropagation();
|
||||
|
||||
@@ -62,6 +62,10 @@ const notificationCollectorPlugin: Plugin<{}, NotificationCollectorStorage> = {
|
||||
},
|
||||
);
|
||||
|
||||
if (!response.ok) {
|
||||
throw new Error(`Heartbeat HTTP ${response.status}`);
|
||||
}
|
||||
|
||||
const data = await response.json();
|
||||
|
||||
// Store notification count for history
|
||||
|
||||
@@ -10,8 +10,8 @@ import { BSPLUS_PENDING_THEME_ENSURE_AFTER_CLOUD_KEY } from "@/seqta/utils/cloud
|
||||
import { settingsState } from "@/seqta/utils/listeners/SettingsState";
|
||||
import debounce from "@/seqta/utils/debounce";
|
||||
import { themeUpdates } from "@/interface/hooks/ThemeUpdates";
|
||||
import { cloudAuth } from "@/seqta/utils/CloudAuth";
|
||||
import { getApiBase } from "@/seqta/utils/DevApiBase";
|
||||
import { isAllowedFetchUrl } from "@/seqta/utils/allowedFetchUrl";
|
||||
import { updateAllColors } from "@/seqta/ui/colors/Manager";
|
||||
import {
|
||||
clearCustomThemeAdaptiveCssVariables,
|
||||
@@ -667,8 +667,12 @@ export class ThemeManager {
|
||||
if (!downloadData?.success || !downloadData?.data?.theme_json_url) {
|
||||
throw new Error("Failed to get theme download URL");
|
||||
}
|
||||
const themeJsonUrl = downloadData.data.theme_json_url;
|
||||
if (!isAllowedFetchUrl(themeJsonUrl)) {
|
||||
throw new Error("Theme download URL not allowed");
|
||||
}
|
||||
themeData = (await this.fetchFromUrl(
|
||||
downloadData.data.theme_json_url,
|
||||
themeJsonUrl,
|
||||
)) as ThemeContent;
|
||||
} catch (apiError) {
|
||||
console.warn("[ThemeManager] API failed, trying GitHub fallback:", apiError);
|
||||
@@ -796,10 +800,8 @@ export class ThemeManager {
|
||||
this.storeUpdateCheckRunning = true;
|
||||
localStorage.setItem(ThemeManager.STORE_CHECK_KEY, String(Date.now()));
|
||||
try {
|
||||
const token = await cloudAuth.getStoredToken();
|
||||
const res = (await browser.runtime.sendMessage({
|
||||
type: "fetchThemes",
|
||||
token: token ?? undefined,
|
||||
})) as {
|
||||
success?: boolean;
|
||||
data?: { themes?: Array<{ id: string; updated_at?: number }> };
|
||||
|
||||
@@ -84,6 +84,8 @@ async function handleTimetable(): Promise<void> {
|
||||
}
|
||||
|
||||
function handleTimetableZoom(): void {
|
||||
if (document.querySelector(".timetable-zoom-controls")) return;
|
||||
|
||||
console.log("Initializing timetable zoom controls");
|
||||
|
||||
// Create zoom controls
|
||||
@@ -130,6 +132,8 @@ function handleTimetableZoom(): void {
|
||||
}
|
||||
|
||||
function handleTimetableAssessmentHide(): void {
|
||||
if (document.querySelector(".timetable-hide-controls")) return;
|
||||
|
||||
const hideControls = document.createElement("div");
|
||||
hideControls.className = "timetable-hide-controls";
|
||||
|
||||
|
||||
@@ -85,7 +85,10 @@ function createSEQTAAPI(): SEQTAAPI {
|
||||
*/
|
||||
function createSettingsAPI<T extends PluginSettings>(
|
||||
plugin: Plugin<T>,
|
||||
): SettingsAPI<T> & { loaded: Promise<void> } {
|
||||
): {
|
||||
settings: SettingsAPI<T> & { loaded: Promise<void> };
|
||||
dispose: () => void;
|
||||
} {
|
||||
const storageKey = `plugin.${plugin.id}.settings`;
|
||||
const listeners = new Map<keyof T, Set<(value: any) => void>>();
|
||||
|
||||
@@ -167,6 +170,10 @@ function createSettingsAPI<T extends PluginSettings>(
|
||||
|
||||
browser.storage.onChanged.addListener(handleStorageChange);
|
||||
|
||||
const dispose = () => {
|
||||
browser.storage.onChanged.removeListener(handleStorageChange);
|
||||
};
|
||||
|
||||
const proxy = new Proxy(settingsWithMeta, {
|
||||
get(target, prop) {
|
||||
return target[prop];
|
||||
@@ -183,6 +190,17 @@ function createSettingsAPI<T extends PluginSettings>(
|
||||
dataToStore[key] = target[key];
|
||||
}
|
||||
|
||||
// Preserve enabled flag managed separately for disableToggle plugins
|
||||
if (plugin.disableToggle) {
|
||||
const allSettings = settingsState.getAll() as Record<string, unknown>;
|
||||
const existing = allSettings[storageKey] as
|
||||
| { enabled?: boolean }
|
||||
| undefined;
|
||||
if (existing?.enabled !== undefined) {
|
||||
dataToStore.enabled = existing.enabled;
|
||||
}
|
||||
}
|
||||
|
||||
browser.storage.local.set({ [storageKey]: dataToStore });
|
||||
|
||||
listeners.get(prop as keyof T)?.forEach((cb) => cb(value));
|
||||
@@ -190,18 +208,18 @@ function createSettingsAPI<T extends PluginSettings>(
|
||||
},
|
||||
}) as SettingsAPI<T> & { loaded: Promise<void> };
|
||||
|
||||
return proxy;
|
||||
return { settings: proxy, dispose };
|
||||
}
|
||||
|
||||
function createStorageAPI<T = any>(
|
||||
pluginId: string,
|
||||
): StorageAPI<T> & { [K in keyof T]: T[K] } {
|
||||
): {
|
||||
storage: StorageAPI<T> & { [K in keyof T]: T[K] };
|
||||
dispose: () => void;
|
||||
} {
|
||||
const prefix = `plugin.${pluginId}.storage.`;
|
||||
const cache: Record<string, any> = {};
|
||||
const listeners = new Map<string, Set<(value: any) => void>>();
|
||||
const storageListeners = new Set<
|
||||
(changes: { [key: string]: any }, area: string) => void
|
||||
>();
|
||||
|
||||
// Load all existing storage values for this plugin
|
||||
const loadStoragePromise = (async () => {
|
||||
@@ -243,10 +261,13 @@ function createStorageAPI<T = any>(
|
||||
}
|
||||
};
|
||||
browser.storage.onChanged.addListener(handleStorageChange);
|
||||
storageListeners.add(handleStorageChange);
|
||||
|
||||
const dispose = () => {
|
||||
browser.storage.onChanged.removeListener(handleStorageChange);
|
||||
};
|
||||
|
||||
// Create the proxy for direct property access
|
||||
return new Proxy(cache, {
|
||||
const storage = new Proxy(cache, {
|
||||
get(target, prop: string) {
|
||||
if (prop === "onChange") {
|
||||
return (key: keyof T, callback: (value: T[keyof T]) => void) => {
|
||||
@@ -288,6 +309,8 @@ function createStorageAPI<T = any>(
|
||||
return true;
|
||||
},
|
||||
}) as StorageAPI<T> & { [K in keyof T]: T[K] };
|
||||
|
||||
return { storage, dispose };
|
||||
}
|
||||
|
||||
function createEventsAPI(pluginId: string): EventsAPI {
|
||||
@@ -357,10 +380,17 @@ function createEventsAPI(pluginId: string): EventsAPI {
|
||||
export function createPluginAPI<T extends PluginSettings, S = any>(
|
||||
plugin: Plugin<T, S>,
|
||||
): PluginAPI<T, S> {
|
||||
const { settings, dispose: disposeSettings } = createSettingsAPI(plugin);
|
||||
const { storage, dispose: disposeStorage } = createStorageAPI<S>(plugin.id);
|
||||
|
||||
return {
|
||||
seqta: createSEQTAAPI(),
|
||||
settings: createSettingsAPI(plugin),
|
||||
storage: createStorageAPI<S>(plugin.id),
|
||||
settings,
|
||||
storage,
|
||||
events: createEventsAPI(plugin.id),
|
||||
dispose: () => {
|
||||
disposeSettings();
|
||||
disposeStorage();
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
@@ -35,6 +35,7 @@ export class PluginManager {
|
||||
private runningPlugins: Map<string, boolean> = new Map();
|
||||
private eventBacklog: Map<string, any[]> = new Map();
|
||||
private cleanupFunctions: Map<string, () => void> = new Map();
|
||||
private apiDisposers: Map<string, () => void> = new Map();
|
||||
private listeners: Map<string, Set<(...args: any[]) => void>> = new Map();
|
||||
private styleElements: Map<string, HTMLStyleElement> = new Map();
|
||||
|
||||
@@ -148,6 +149,7 @@ export class PluginManager {
|
||||
|
||||
try {
|
||||
const api = createPluginAPI(plugin);
|
||||
this.apiDisposers.set(pluginId, api.dispose);
|
||||
|
||||
// Check if plugin is enabled before starting
|
||||
if (plugin.disableToggle) {
|
||||
@@ -158,6 +160,7 @@ export class PluginManager {
|
||||
const enabled =
|
||||
pluginSettings?.enabled ?? plugin.defaultEnabled ?? true;
|
||||
if (!enabled) {
|
||||
this.disposePluginAPI(pluginId);
|
||||
console.info(
|
||||
`Plugin "${pluginId}" is disabled, skipping initialization`,
|
||||
);
|
||||
@@ -186,6 +189,8 @@ export class PluginManager {
|
||||
// Process any backlogged events
|
||||
await this.processBackloggedEvents(pluginId);
|
||||
} catch (error) {
|
||||
this.removePluginStyles(pluginId);
|
||||
this.disposePluginAPI(pluginId);
|
||||
console.error(
|
||||
`[BetterSEQTA+] Failed to start plugin ${pluginId}:`,
|
||||
error,
|
||||
@@ -194,6 +199,22 @@ export class PluginManager {
|
||||
}
|
||||
}
|
||||
|
||||
private removePluginStyles(pluginId: string): void {
|
||||
const styleElement = this.styleElements.get(pluginId);
|
||||
if (styleElement) {
|
||||
styleElement.remove();
|
||||
this.styleElements.delete(pluginId);
|
||||
}
|
||||
}
|
||||
|
||||
private disposePluginAPI(pluginId: string): void {
|
||||
const dispose = this.apiDisposers.get(pluginId);
|
||||
if (dispose) {
|
||||
dispose();
|
||||
this.apiDisposers.delete(pluginId);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Attempts to start all registered plugins.
|
||||
* Errors during the start of individual plugins are caught and logged,
|
||||
@@ -225,12 +246,8 @@ export class PluginManager {
|
||||
* @returns {Promise<void>} A promise that resolves when the plugin has been stopped.
|
||||
*/
|
||||
public async stopPlugin(pluginId: string): Promise<void> {
|
||||
// Remove plugin styles
|
||||
const styleElement = this.styleElements.get(pluginId);
|
||||
if (styleElement) {
|
||||
styleElement.remove();
|
||||
this.styleElements.delete(pluginId);
|
||||
}
|
||||
this.removePluginStyles(pluginId);
|
||||
this.disposePluginAPI(pluginId);
|
||||
|
||||
const cleanup = this.cleanupFunctions.get(pluginId);
|
||||
if (cleanup) {
|
||||
|
||||
@@ -141,6 +141,7 @@ export interface PluginAPI<T extends PluginSettings, S = any> {
|
||||
settings: SettingsAPI<T>;
|
||||
storage: TypedStorageAPI<S>;
|
||||
events: EventsAPI;
|
||||
dispose: () => void;
|
||||
}
|
||||
|
||||
export interface Plugin<T extends PluginSettings = PluginSettings, S = any> {
|
||||
|
||||
@@ -16,6 +16,24 @@ import { updateAllColors } from "./colors/Manager";
|
||||
import { delay } from "@/seqta/utils/delay";
|
||||
|
||||
let cachedUserInfo: any = null;
|
||||
let userInfoCacheListenersAttached = false;
|
||||
|
||||
export function invalidateCachedUserInfo(): void {
|
||||
cachedUserInfo = null;
|
||||
}
|
||||
|
||||
function attachUserInfoCacheInvalidation(): void {
|
||||
if (userInfoCacheListenersAttached || typeof window === "undefined") return;
|
||||
userInfoCacheListenersAttached = true;
|
||||
|
||||
window.addEventListener("pageshow", (event) => {
|
||||
if (event.persisted) {
|
||||
invalidateCachedUserInfo();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
attachUserInfoCacheInvalidation();
|
||||
|
||||
let LightDarkModeSnakeEggButton = 0;
|
||||
let sidebarAccessibilityObserver: MutationObserver | null = null;
|
||||
@@ -25,8 +43,10 @@ let sidebarAccessibilityListenersAttached = false;
|
||||
/** Marks menu rows that are off-screen in the drill stack (CSS blocks clicks). */
|
||||
const BSPLUS_SIDEBAR_OFFSCREEN = "bsplus-sidebar-offscreen";
|
||||
|
||||
export async function getUserInfo() {
|
||||
if (cachedUserInfo) return cachedUserInfo;
|
||||
export async function getUserInfo(options?: { validateSession?: boolean }) {
|
||||
if (cachedUserInfo && !options?.validateSession) {
|
||||
return cachedUserInfo;
|
||||
}
|
||||
|
||||
try {
|
||||
const response = await fetch(`${location.origin}/seqta/student/login`, {
|
||||
@@ -41,7 +61,26 @@ export async function getUserInfo() {
|
||||
}),
|
||||
});
|
||||
|
||||
cachedUserInfo = (await response.json()).payload;
|
||||
if (!response.ok) {
|
||||
throw new Error(`Failed to get user info: HTTP ${response.status}`);
|
||||
}
|
||||
|
||||
const payload = (await response.json()).payload;
|
||||
|
||||
if (
|
||||
cachedUserInfo &&
|
||||
options?.validateSession &&
|
||||
payload?.id != null &&
|
||||
cachedUserInfo.id != null &&
|
||||
payload.id !== cachedUserInfo.id
|
||||
) {
|
||||
console.warn(
|
||||
"[BetterSEQTA+] Session user changed; invalidating cached user info",
|
||||
);
|
||||
invalidateCachedUserInfo();
|
||||
}
|
||||
|
||||
cachedUserInfo = payload;
|
||||
return cachedUserInfo;
|
||||
} catch (error) {
|
||||
console.error("[BetterSEQTA+] Failed to get user info:", error);
|
||||
|
||||
@@ -21,6 +21,7 @@ export async function appendBackgroundToUI() {
|
||||
}
|
||||
|
||||
let lastLoadedId: string | null = null;
|
||||
let lastBlobUrl: string | null = null;
|
||||
|
||||
export async function loadBackground() {
|
||||
if (!isIndexedDBSupported()) {
|
||||
@@ -36,6 +37,10 @@ export async function loadBackground() {
|
||||
backgroundContainer.remove();
|
||||
}
|
||||
lastLoadedId = null;
|
||||
if (lastBlobUrl) {
|
||||
URL.revokeObjectURL(lastBlobUrl);
|
||||
lastBlobUrl = null;
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -73,12 +78,19 @@ export async function loadBackground() {
|
||||
|
||||
mediaContainer.innerHTML = "";
|
||||
|
||||
if (lastBlobUrl) {
|
||||
URL.revokeObjectURL(lastBlobUrl);
|
||||
lastBlobUrl = null;
|
||||
}
|
||||
|
||||
const mediaElement =
|
||||
background.type === "video"
|
||||
? document.createElement("video")
|
||||
: document.createElement("img");
|
||||
|
||||
mediaElement.src = URL.createObjectURL(background.blob);
|
||||
const blobUrl = URL.createObjectURL(background.blob);
|
||||
lastBlobUrl = blobUrl;
|
||||
mediaElement.src = blobUrl;
|
||||
mediaElement.classList.add("background");
|
||||
|
||||
if (mediaElement instanceof HTMLVideoElement) {
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
import browser from "webextension-polyfill";
|
||||
import { clearCloudPfpCache } from "@/seqta/utils/cloudPfpCache";
|
||||
import { clearLastUploadedSnapshot } from "@/seqta/utils/cloudSettingsSync";
|
||||
import { settingsState } from "@/seqta/utils/listeners/SettingsState";
|
||||
|
||||
const REDIRECT_URI = "https://accounts.betterseqta.org/auth/bsplus/callback";
|
||||
|
||||
@@ -87,11 +86,10 @@ class CloudAuthService {
|
||||
}
|
||||
|
||||
/** Pull cloud settings backup after a fresh sign-in (matches manual “Download from cloud”). */
|
||||
private triggerCloudSettingsDownloadAfterLogin(accessToken: string): void {
|
||||
private triggerCloudSettingsDownloadAfterLogin(): void {
|
||||
void browser.runtime
|
||||
.sendMessage({
|
||||
type: "cloudSettingsDownload",
|
||||
token: accessToken,
|
||||
})
|
||||
.then((res: unknown) => {
|
||||
const r = res as { success?: boolean; notFound?: boolean; error?: string } | undefined;
|
||||
@@ -112,7 +110,6 @@ class CloudAuthService {
|
||||
|
||||
/** Persist an updated user object (e.g. after cloud profile picture sync). */
|
||||
public async setUser(user: CloudUser | null): Promise<void> {
|
||||
(settingsState as any).setKey(STORAGE_KEYS.user, user);
|
||||
await browser.storage.local.set({ [STORAGE_KEYS.user]: user });
|
||||
this._state = {
|
||||
isLoggedIn: this._state.isLoggedIn,
|
||||
@@ -122,11 +119,8 @@ class CloudAuthService {
|
||||
}
|
||||
|
||||
private async getClientId(): Promise<string> {
|
||||
let clientId = (settingsState as any)[STORAGE_KEYS.clientId] as string | undefined;
|
||||
if (!clientId) {
|
||||
const stored = await browser.storage.local.get(STORAGE_KEYS.clientId);
|
||||
clientId = stored[STORAGE_KEYS.clientId] as string | undefined;
|
||||
}
|
||||
let clientId = stored[STORAGE_KEYS.clientId] as string | undefined;
|
||||
if (!clientId) {
|
||||
const reserveResult = (await browser.runtime.sendMessage({
|
||||
type: "cloudReserveClient",
|
||||
@@ -136,7 +130,7 @@ class CloudAuthService {
|
||||
throw new Error(reserveResult?.error ?? "Failed to reserve client");
|
||||
}
|
||||
clientId = reserveResult.client_id;
|
||||
(settingsState as any).setKey(STORAGE_KEYS.clientId, clientId);
|
||||
await browser.storage.local.set({ [STORAGE_KEYS.clientId]: clientId });
|
||||
}
|
||||
return clientId;
|
||||
}
|
||||
@@ -180,15 +174,17 @@ class CloudAuthService {
|
||||
error?: string;
|
||||
};
|
||||
if (result?.access_token && result?.refresh_token) {
|
||||
(settingsState as any).setKey(STORAGE_KEYS.accessToken, result.access_token);
|
||||
(settingsState as any).setKey(STORAGE_KEYS.refreshToken, result.refresh_token);
|
||||
(settingsState as any).setKey(STORAGE_KEYS.user, result.user ?? null);
|
||||
await browser.storage.local.set({
|
||||
[STORAGE_KEYS.accessToken]: result.access_token,
|
||||
[STORAGE_KEYS.refreshToken]: result.refresh_token,
|
||||
[STORAGE_KEYS.user]: result.user ?? null,
|
||||
});
|
||||
this._state = {
|
||||
isLoggedIn: true,
|
||||
user: result.user ?? null,
|
||||
};
|
||||
this.notify();
|
||||
this.triggerCloudSettingsDownloadAfterLogin(result.access_token);
|
||||
this.triggerCloudSettingsDownloadAfterLogin();
|
||||
return { success: true };
|
||||
}
|
||||
return {
|
||||
@@ -239,9 +235,11 @@ class CloudAuthService {
|
||||
};
|
||||
|
||||
if (refreshResult?.access_token && refreshResult?.refresh_token) {
|
||||
(settingsState as any).setKey(STORAGE_KEYS.accessToken, refreshResult.access_token);
|
||||
(settingsState as any).setKey(STORAGE_KEYS.refreshToken, refreshResult.refresh_token);
|
||||
(settingsState as any).setKey(STORAGE_KEYS.user, refreshResult.user ?? null);
|
||||
await browser.storage.local.set({
|
||||
[STORAGE_KEYS.accessToken]: refreshResult.access_token,
|
||||
[STORAGE_KEYS.refreshToken]: refreshResult.refresh_token,
|
||||
[STORAGE_KEYS.user]: refreshResult.user ?? null,
|
||||
});
|
||||
this._state = {
|
||||
isLoggedIn: true,
|
||||
user: refreshResult.user ?? null,
|
||||
|
||||
@@ -1,13 +1,28 @@
|
||||
import stringToHTML from "../stringToHTML";
|
||||
|
||||
function isSafeShortcutHref(url: string): boolean {
|
||||
if (typeof url !== "string" || !url.trim()) return false;
|
||||
try {
|
||||
const parsed = new URL(url, window.location.href);
|
||||
return ["http:", "https:", "mailto:"].includes(parsed.protocol);
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
export function CreateCustomShortcutDiv(element: any) {
|
||||
// Creates the stucture and element information for each seperate shortcut
|
||||
const container = document.getElementById("shortcuts");
|
||||
if (!container) return;
|
||||
|
||||
var shortcut = document.createElement("a");
|
||||
if (isSafeShortcutHref(element.url)) {
|
||||
shortcut.setAttribute("href", element.url);
|
||||
shortcut.setAttribute("target", "_blank");
|
||||
} else {
|
||||
shortcut.setAttribute("href", "#");
|
||||
shortcut.setAttribute("aria-disabled", "true");
|
||||
}
|
||||
var shortcutdiv = document.createElement("div");
|
||||
shortcutdiv.classList.add("shortcut");
|
||||
shortcutdiv.classList.add("customshortcut");
|
||||
|
||||
@@ -52,6 +52,7 @@ export function OpenAboutPage() {
|
||||
</a>
|
||||
<a class="socials" href="https://www.youtube.com/@BetterSEQTAPlus" style="background: none !important; margin: 0 5px; padding: 0; display: flex; align-items: center;">
|
||||
<svg fill="currentColor" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 50 50" width="50px" height="50px"><path d="M 44.898438 14.5 C 44.5 12.300781 42.601563 10.699219 40.398438 10.199219 C 37.101563 9.5 31 9 24.398438 9 C 17.800781 9 11.601563 9.5 8.300781 10.199219 C 6.101563 10.699219 4.199219 12.199219 3.800781 14.5 C 3.398438 17 3 20.5 3 25 C 3 29.5 3.398438 33 3.898438 35.5 C 4.300781 37.699219 6.199219 39.300781 8.398438 39.800781 C 11.898438 40.5 17.898438 41 24.5 41 C 31.101563 41 37.101563 40.5 40.601563 39.800781 C 42.800781 39.300781 44.699219 37.800781 45.101563 35.5 C 45.5 33 46 29.398438 46.101563 25 C 45.898438 20.5 45.398438 17 44.898438 14.5 Z M 19 32 L 19 18 L 31.199219 25 Z"/></svg>
|
||||
</a>
|
||||
<a class="socials" href="https://chromewebstore.google.com/detail/betterseqta+/afdgaoaclhkhemfkkkonemoapeinchel" style="background: none !important; margin: 0 5px; padding: 0; display: flex; align-items: center;">
|
||||
<svg style="width:25px; height:25px; vertical-align: middle;" viewBox="0 0 24 24">
|
||||
<path fill="currentColor" d="M12,20L15.46,14H15.45C15.79,13.4 16,12.73 16,12C16,10.8 15.46,9.73 14.62,9H19.41C19.79,9.93 20,10.94 20,12A8,8 0 0,1 12,20M4,12C4,10.54 4.39,9.18 5.07,8L8.54,14H8.55C9.24,15.19 10.5,16 12,16C12.45,16 12.88,15.91 13.29,15.77L10.89,19.91C7,19.37 4,16.04 4,12M15,12A3,3 0 0,1 12,15A3,3 0 0,1 9,12A3,3 0 0,1 12,9A3,3 0 0,1 15,12M12,4C14.96,4 17.54,5.61 18.92,8H12C10.06,8 8.45,9.38 8.08,11.21L5.7,7.08C7.16,5.21 9.44,4 12,4M12,2A10,10 0 0,0 2,12A10,10 0 0,0 12,22A10,10 0 0,0 22,12A10,10 0 0,0 12,2Z" />
|
||||
|
||||
@@ -61,11 +61,12 @@ export function showBsCloudAutoSyncAnnouncement(onDismissed?: () => void) {
|
||||
</div>
|
||||
`).firstChild as HTMLElement;
|
||||
|
||||
settingsState.bsCloudAutoSyncAnnouncementShown = true;
|
||||
|
||||
openPopup({
|
||||
header,
|
||||
content: [imageContainer, text],
|
||||
afterClose: onDismissed,
|
||||
afterClose: () => {
|
||||
settingsState.bsCloudAutoSyncAnnouncementShown = true;
|
||||
onDismissed?.();
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
@@ -5,7 +5,18 @@ import Sortable from "sortablejs";
|
||||
|
||||
export let MenuOptionsOpen = false;
|
||||
|
||||
function escapeHtmlAttr(value: string): string {
|
||||
return value
|
||||
.replace(/&/g, "&")
|
||||
.replace(/"/g, """)
|
||||
.replace(/'/g, "'")
|
||||
.replace(/</g, "<")
|
||||
.replace(/>/g, ">");
|
||||
}
|
||||
|
||||
export function OpenMenuOptions() {
|
||||
if (MenuOptionsOpen) return;
|
||||
|
||||
var container = document.getElementById("container");
|
||||
var menu = document.getElementById("menu");
|
||||
|
||||
@@ -23,9 +34,9 @@ export function OpenMenuOptions() {
|
||||
for (let i = 0; i < childnodes.length; i++) {
|
||||
const element = childnodes[i];
|
||||
if (
|
||||
!settingsState.defaultmenuorder.indexOf(
|
||||
settingsState.defaultmenuorder.indexOf(
|
||||
(element as HTMLElement).dataset.key,
|
||||
)
|
||||
) === -1
|
||||
) {
|
||||
let newdefaultmenuorder = settingsState.defaultmenuorder;
|
||||
newdefaultmenuorder.push((element as HTMLElement).dataset.key);
|
||||
@@ -53,7 +64,7 @@ export function OpenMenuOptions() {
|
||||
var savebutton = document.createElement("div");
|
||||
savebutton.classList.add("editmenuoption");
|
||||
savebutton.innerText = "Save";
|
||||
savebutton.id = "restoredefaultoption";
|
||||
savebutton.id = "savemenuoption";
|
||||
|
||||
menusettings.appendChild(defaultbutton);
|
||||
menusettings.appendChild(savebutton);
|
||||
@@ -71,15 +82,18 @@ export function OpenMenuOptions() {
|
||||
(element.firstChild as HTMLElement).classList.remove("noscroll");
|
||||
}
|
||||
|
||||
const menuKey = escapeHtmlAttr((element as HTMLElement).dataset.key ?? "");
|
||||
let MenuItemToggle = stringToHTML(
|
||||
`<div class="onoffswitch" style="margin: auto 0;"><input class="onoffswitch-checkbox notification menuitem" type="checkbox" id="${(element as HTMLElement).dataset.key}"><label for="${(element as HTMLElement).dataset.key}" class="onoffswitch-label"></label>`,
|
||||
`<div class="onoffswitch" style="margin: auto 0;"><input class="onoffswitch-checkbox notification menuitem" type="checkbox" id="${menuKey}"><label for="${menuKey}" class="onoffswitch-label"></label>`,
|
||||
).firstChild;
|
||||
(element as HTMLElement).append(MenuItemToggle!);
|
||||
|
||||
if (!element.dataset.betterseqta) {
|
||||
const a = document.createElement("section");
|
||||
a.innerHTML = element.innerHTML;
|
||||
cloneAttributes(a, element);
|
||||
while (element.firstChild) {
|
||||
a.appendChild(element.firstChild);
|
||||
}
|
||||
menu!.firstChild!.insertBefore(a, element);
|
||||
element.remove();
|
||||
}
|
||||
@@ -109,12 +123,12 @@ export function OpenMenuOptions() {
|
||||
} else {
|
||||
(buttons[i] as HTMLInputElement).checked = true;
|
||||
}
|
||||
(buttons[i] as HTMLInputElement).checked = true;
|
||||
}
|
||||
|
||||
let sortable: Sortable | undefined;
|
||||
try {
|
||||
var el = document.querySelector("#menu > ul");
|
||||
var sortable = Sortable.create(el as HTMLElement, {
|
||||
sortable = Sortable.create(el as HTMLElement, {
|
||||
draggable: ".draggable",
|
||||
dataIdAttr: "data-key",
|
||||
animation: 150,
|
||||
@@ -178,8 +192,10 @@ export function OpenMenuOptions() {
|
||||
|
||||
if (!element.dataset.betterseqta) {
|
||||
const a = document.createElement("li");
|
||||
a.innerHTML = element.innerHTML;
|
||||
cloneAttributes(a, element);
|
||||
while (element.firstChild) {
|
||||
a.appendChild(element.firstChild);
|
||||
}
|
||||
menu!.firstChild!.insertBefore(a, element);
|
||||
element.remove();
|
||||
}
|
||||
@@ -209,7 +225,7 @@ export function OpenMenuOptions() {
|
||||
"important",
|
||||
);
|
||||
}
|
||||
saveNewOrder(sortable);
|
||||
if (sortable) saveNewOrder(sortable);
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
@@ -105,6 +105,7 @@ export function OpenMinecraftServerPopup() {
|
||||
</a>
|
||||
<a class="socials" href="https://www.youtube.com/@BetterSEQTAPlus" style="background: none !important; margin: 0 5px; padding: 0; display: flex; align-items: center;">
|
||||
<svg fill="currentColor" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 50 50" width="50px" height="50px"><path d="M 44.898438 14.5 C 44.5 12.300781 42.601563 10.699219 40.398438 10.199219 C 37.101563 9.5 31 9 24.398438 9 C 17.800781 9 11.601563 9.5 8.300781 10.199219 C 6.101563 10.699219 4.199219 12.199219 3.800781 14.5 C 3.398438 17 3 20.5 3 25 C 3 29.5 3.398438 33 3.898438 35.5 C 4.300781 37.699219 6.199219 39.300781 8.398438 39.800781 C 11.898438 40.5 17.898438 41 24.5 41 C 31.101563 41 37.101563 40.5 40.601563 39.800781 C 42.800781 39.300781 44.699219 37.800781 45.101563 35.5 C 45.5 33 46 29.398438 46.101563 25 C 45.898438 20.5 45.398438 17 44.898438 14.5 Z M 19 32 L 19 18 L 31.199219 25 Z"/></svg>
|
||||
</a>
|
||||
<a class="socials" href="https://chromewebstore.google.com/detail/betterseqta+/afdgaoaclhkhemfkkkonemoapeinchel" style="background: none !important; margin: 0 5px; padding: 0; display: flex; align-items: center;">
|
||||
<svg style="width:25px; height:25px; vertical-align: middle;" viewBox="0 0 24 24">
|
||||
<path fill="currentColor" d="M12,20L15.46,14H15.45C15.79,13.4 16,12.73 16,12C16,10.8 15.46,9.73 14.62,9H19.41C19.79,9.93 20,10.94 20,12A8,8 0 0,1 12,20M4,12C4,10.54 4.39,9.18 5.07,8L8.54,14H8.55C9.24,15.19 10.5,16 12,16C12.45,16 12.88,15.91 13.29,15.77L10.89,19.91C7,19.37 4,16.04 4,12M15,12A3,3 0 0,1 12,15A3,3 0 0,1 9,12A3,3 0 0,1 12,9A3,3 0 0,1 15,12M12,4C14.96,4 17.54,5.61 18.92,8H12C10.06,8 8.45,9.38 8.08,11.21L5.7,7.08C7.16,5.21 9.44,4 12,4M12,2A10,10 0 0,0 2,12A10,10 0 0,0 12,22A10,10 0 0,0 22,12A10,10 0 0,0 12,2Z" />
|
||||
|
||||
@@ -62,12 +62,13 @@ export function showPrivacyNotification(onDismissed?: () => void) {
|
||||
|
||||
attachPopupMediaFullscreenIfPresent(text, "img.aboutImg");
|
||||
|
||||
settingsState.privacyStatementLastUpdated = "2025-12-20";
|
||||
settingsState.privacyStatementShown = true;
|
||||
|
||||
openPopup({
|
||||
header,
|
||||
content: [text],
|
||||
afterClose: onDismissed,
|
||||
afterClose: () => {
|
||||
settingsState.privacyStatementLastUpdated = "2025-12-20";
|
||||
settingsState.privacyStatementShown = true;
|
||||
onDismissed?.();
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
@@ -31,12 +31,12 @@ export function OpenPrivacyStatement() {
|
||||
<p>BetterSEQTA+ uses your browser's local storage to save your preferences and settings. This data remains on your device and is never transmitted anywhere. You can clear this data at any time through your browser's settings.</p>
|
||||
|
||||
<h3>Open Source</h3>
|
||||
<p>BetterSEQTA+ is an open-source project. You can review our code on <a href="https://github.com/BetterSEQTA/BetterSEQTA-Plus" target="_blank" style="color: inherit; text-decoration: underline;">GitHub</a> to verify our privacy practices. We believe in transparency and encourage you to inspect the code yourself.</p>
|
||||
<p>BetterSEQTA+ is an open-source project. You can review our code on <a href="https://github.com/BetterSEQTA/BetterSEQTA-Plus" target="_blank" rel="noopener noreferrer" style="color: inherit; text-decoration: underline;">GitHub</a> to verify our privacy practices. We believe in transparency and encourage you to inspect the code yourself.</p>
|
||||
|
||||
<h3>Our Commitment</h3>
|
||||
<p>We are committed to providing the best features possible while respecting your privacy. We understand that schools and students have concerns about data privacy, and we want to assure you that BetterSEQTA+ is designed with privacy as a core principle.</p>
|
||||
|
||||
<p style="margin-top: 20px; font-weight: bold;">If you have any questions or concerns about our privacy practices, please reach out to us through our <a href="https://github.com/BetterSEQTA/BetterSEQTA-Plus" target="_blank" style="color: inherit; text-decoration: underline;">GitHub repository</a>.</p>
|
||||
<p style="margin-top: 20px; font-weight: bold;">If you have any questions or concerns about our privacy practices, please reach out to us through our <a href="https://github.com/BetterSEQTA/BetterSEQTA-Plus" target="_blank" rel="noopener noreferrer" style="color: inherit; text-decoration: underline;">GitHub repository</a>.</p>
|
||||
</div>
|
||||
`).firstChild as HTMLElement;
|
||||
|
||||
|
||||
@@ -4,13 +4,13 @@ import { settingsState } from "../listeners/SettingsState";
|
||||
import { closePopup } from "./PopupManager";
|
||||
import { getApiBase } from "../DevApiBase";
|
||||
import { openThemeStoreWithHighlight } from "../openThemeStoreWithHighlight";
|
||||
import { cloudAuth } from "../CloudAuth";
|
||||
import type { Theme } from "@/interface/types/Theme";
|
||||
import {
|
||||
buildModalHeroSlides,
|
||||
normalizeStoreTheme,
|
||||
} from "@/interface/utils/themeStoreFlavours";
|
||||
import { attachPopupMediaFullscreen } from "./attachPopupMediaFullscreen";
|
||||
import { allowedPopupImageUrl } from "./allowedPopupImageUrl";
|
||||
|
||||
export interface ThemeOfTheMonthEntry {
|
||||
id: string;
|
||||
@@ -67,16 +67,14 @@ function heroUrlFromStoreTheme(theme: {
|
||||
coverImage?: string | null;
|
||||
}): string | null {
|
||||
const url = (theme.marqueeImage || theme.coverImage || "").trim();
|
||||
return url || null;
|
||||
return allowedPopupImageUrl(url);
|
||||
}
|
||||
|
||||
export async function fetchThemeStoreTheme(themeId: string): Promise<Theme | null> {
|
||||
try {
|
||||
const token = await cloudAuth.getStoredToken();
|
||||
const res = (await browser.runtime.sendMessage({
|
||||
type: "fetchThemeDetails",
|
||||
themeId,
|
||||
token: token ?? undefined,
|
||||
})) as { success?: boolean; data?: { theme?: Record<string, unknown> } };
|
||||
|
||||
if (!res?.success || !res?.data?.theme) return null;
|
||||
@@ -100,7 +98,12 @@ function buildPopupGallerySlides(
|
||||
heroUrl: string | null,
|
||||
): PopupGallerySlide[] {
|
||||
if (storeTheme) {
|
||||
return buildModalHeroSlides(storeTheme).filter((s) => s.imageUrl.trim());
|
||||
return buildModalHeroSlides(storeTheme)
|
||||
.map((s) => {
|
||||
const imageUrl = allowedPopupImageUrl(s.imageUrl);
|
||||
return imageUrl ? { imageUrl, caption: s.caption } : null;
|
||||
})
|
||||
.filter((s): s is PopupGallerySlide => s !== null);
|
||||
}
|
||||
if (heroUrl) {
|
||||
return [{ imageUrl: heroUrl, caption: entry.title }];
|
||||
@@ -642,7 +645,7 @@ export async function OpenThemeOfTheMonthPopup(
|
||||
const storeTheme = linkedThemeId ? await fetchThemeStoreTheme(linkedThemeId) : null;
|
||||
const heroUrl =
|
||||
(storeTheme ? heroUrlFromStoreTheme(storeTheme) : null) ??
|
||||
entry.cover_image?.trim() ??
|
||||
allowedPopupImageUrl(entry.cover_image) ??
|
||||
null;
|
||||
const gallerySlides = buildPopupGallerySlides(entry, storeTheme, heroUrl);
|
||||
const hasExpandableContent = gallerySlides.length > 0 || entry.description.trim().length > 0;
|
||||
|
||||
@@ -396,6 +396,7 @@ export function OpenWhatsNewPopup(onDismissed?: () => void) {
|
||||
</a>
|
||||
<a class="socials" href="https://www.youtube.com/@BetterSEQTAPlus" style="background: none !important; margin: 0 5px; padding: 0; display: flex; align-items: center;">
|
||||
<svg fill="currentColor" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 50 50" width="50px" height="50px"><path d="M 44.898438 14.5 C 44.5 12.300781 42.601563 10.699219 40.398438 10.199219 C 37.101563 9.5 31 9 24.398438 9 C 17.800781 9 11.601563 9.5 8.300781 10.199219 C 6.101563 10.699219 4.199219 12.199219 3.800781 14.5 C 3.398438 17 3 20.5 3 25 C 3 29.5 3.398438 33 3.898438 35.5 C 4.300781 37.699219 6.199219 39.300781 8.398438 39.800781 C 11.898438 40.5 17.898438 41 24.5 41 C 31.101563 41 37.101563 40.5 40.601563 39.800781 C 42.800781 39.300781 44.699219 37.800781 45.101563 35.5 C 45.5 33 46 29.398438 46.101563 25 C 45.898438 20.5 45.398438 17 44.898438 14.5 Z M 19 32 L 19 18 L 31.199219 25 Z"/></svg>
|
||||
</a>
|
||||
<a class="socials" href="https://chromewebstore.google.com/detail/betterseqta+/afdgaoaclhkhemfkkkonemoapeinchel" style="background: none !important; margin: 0 5px; padding: 0; display: flex; align-items: center;">
|
||||
<svg style="width:25px; height:25px; vertical-align: middle;" viewBox="0 0 24 24">
|
||||
<path fill="currentColor" d="M12,20L15.46,14H15.45C15.79,13.4 16,12.73 16,12C16,10.8 15.46,9.73 14.62,9H19.41C19.79,9.93 20,10.94 20,12A8,8 0 0,1 12,20M4,12C4,10.54 4.39,9.18 5.07,8L8.54,14H8.55C9.24,15.19 10.5,16 12,16C12.45,16 12.88,15.91 13.29,15.77L10.89,19.91C7,19.37 4,16.04 4,12M15,12A3,3 0 0,1 12,15A3,3 0 0,1 9,12A3,3 0 0,1 12,9A3,3 0 0,1 15,12M12,4C14.96,4 17.54,5.61 18.92,8H12C10.06,8 8.45,9.38 8.08,11.21L5.7,7.08C7.16,5.21 9.44,4 12,4M12,2A10,10 0 0,0 2,12A10,10 0 0,0 12,22A10,10 0 0,0 22,12A10,10 0 0,0 12,2Z" />
|
||||
@@ -403,7 +404,7 @@ export function OpenWhatsNewPopup(onDismissed?: () => void) {
|
||||
</a>
|
||||
</div>
|
||||
<div>
|
||||
<a href="https://ko-fi.com/sethburkart" target="_blank" style="background: none !important; margin:0;margin-left:6px;padding:0; display: flex; align-items: center;">
|
||||
<a href="https://ko-fi.com/sethburkart" target="_blank" rel="noopener noreferrer" style="background: none !important; margin:0;margin-left:6px;padding:0; display: flex; align-items: center;">
|
||||
<img height="25" style="border:0px; height:25px; margin-right: -6px;" src="${kofi}" border="0" alt="Buy Me a Coffee at ko-fi.com" />
|
||||
</a>
|
||||
</div>
|
||||
|
||||
@@ -57,6 +57,15 @@ interface OpenPopupOptions {
|
||||
containerClass?: string;
|
||||
}
|
||||
|
||||
function chainAfterClose(next?: () => void) {
|
||||
if (!next) return;
|
||||
const previous = pendingAfterClose;
|
||||
pendingAfterClose = () => {
|
||||
next();
|
||||
previous?.();
|
||||
};
|
||||
}
|
||||
|
||||
export function openPopup({
|
||||
header,
|
||||
content = [],
|
||||
@@ -65,7 +74,12 @@ export function openPopup({
|
||||
clearJustUpdated = false,
|
||||
containerClass,
|
||||
}: OpenPopupOptions = {}) {
|
||||
pendingAfterClose = afterClose;
|
||||
if (document.getElementById("whatsnewbk")) {
|
||||
chainAfterClose(afterClose);
|
||||
return;
|
||||
}
|
||||
|
||||
chainAfterClose(afterClose);
|
||||
|
||||
const background = document.createElement("div");
|
||||
background.id = "whatsnewbk";
|
||||
@@ -87,7 +101,9 @@ export function openPopup({
|
||||
container.append(closeButton);
|
||||
|
||||
background.append(container);
|
||||
document.getElementById("container")!.append(background);
|
||||
const appContainer = document.getElementById("container");
|
||||
if (!appContainer) return;
|
||||
appContainer.append(background);
|
||||
|
||||
if (settingsState.animations) {
|
||||
(motionAnimate as any)(
|
||||
|
||||
@@ -0,0 +1,16 @@
|
||||
/**
|
||||
* Minimal allowlist for remote popup/API image (and media) URLs.
|
||||
* Only https: URLs are accepted; everything else is rejected.
|
||||
*/
|
||||
export function allowedPopupImageUrl(url: string | null | undefined): string | null {
|
||||
if (!url) return null;
|
||||
const trimmed = url.trim();
|
||||
if (!trimmed) return null;
|
||||
try {
|
||||
const parsed = new URL(trimmed);
|
||||
if (parsed.protocol !== "https:") return null;
|
||||
return parsed.href;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
@@ -5,6 +5,7 @@
|
||||
*/
|
||||
|
||||
import { settingsState } from "../listeners/SettingsState";
|
||||
import { allowedPopupImageUrl } from "./allowedPopupImageUrl";
|
||||
|
||||
const FULLSCREENABLE_CLASS = "popup-media-fullscreenable";
|
||||
const OVERLAY_VISIBLE_CLASS = "bsplus-popup-media-overlay-backdrop--visible";
|
||||
@@ -56,13 +57,22 @@ function openMediaOverlayViewer(source: HTMLImageElement | HTMLVideoElement) {
|
||||
nv.loop = v.loop;
|
||||
nv.muted = v.muted;
|
||||
nv.volume = v.volume;
|
||||
let hasValidSource = false;
|
||||
for (const s of v.querySelectorAll("source")) {
|
||||
const src = allowedPopupImageUrl((s as HTMLSourceElement).src);
|
||||
if (!src) continue;
|
||||
hasValidSource = true;
|
||||
const ns = document.createElement("source");
|
||||
ns.src = (s as HTMLSourceElement).src;
|
||||
ns.src = src;
|
||||
const t = (s as HTMLSourceElement).type;
|
||||
if (t) ns.type = t;
|
||||
nv.appendChild(ns);
|
||||
}
|
||||
if (!hasValidSource) {
|
||||
const directSrc = allowedPopupImageUrl(v.currentSrc || v.src);
|
||||
if (!directSrc) return;
|
||||
nv.src = directSrc;
|
||||
}
|
||||
nv.addEventListener(
|
||||
"loadeddata",
|
||||
() => {
|
||||
@@ -79,9 +89,12 @@ function openMediaOverlayViewer(source: HTMLImageElement | HTMLVideoElement) {
|
||||
nv.load();
|
||||
media = nv;
|
||||
} else {
|
||||
const rawSrc = source.currentSrc || source.src;
|
||||
const safeSrc = allowedPopupImageUrl(rawSrc);
|
||||
if (!safeSrc) return;
|
||||
const img = document.createElement("img");
|
||||
img.classList.add("bsplus-popup-media-overlay-media");
|
||||
img.src = source.currentSrc || source.src;
|
||||
img.src = safeSrc;
|
||||
img.alt = source.alt || "";
|
||||
media = img;
|
||||
}
|
||||
|
||||
@@ -22,6 +22,16 @@ class ReactFiber {
|
||||
return new ReactFiber(selector, options);
|
||||
}
|
||||
|
||||
private getTargetOrigin(): string {
|
||||
return window.location.origin;
|
||||
}
|
||||
|
||||
private isTrustedMessage(event: MessageEvent): boolean {
|
||||
return (
|
||||
event.source === window && event.origin === this.getTargetOrigin()
|
||||
);
|
||||
}
|
||||
|
||||
private async sendMessage(action: string, payload: any = {}): Promise<any> {
|
||||
return new Promise((resolve, _) => {
|
||||
const messageId = this.messageIdCounter++;
|
||||
@@ -34,7 +44,8 @@ class ReactFiber {
|
||||
messageId,
|
||||
};
|
||||
|
||||
const listener = (response: any) => {
|
||||
const listener = (response: MessageEvent) => {
|
||||
if (!this.isTrustedMessage(response)) return;
|
||||
if (
|
||||
response.data?.type === "reactFiberResponse" &&
|
||||
response.data?.messageId === messageId
|
||||
@@ -47,7 +58,7 @@ class ReactFiber {
|
||||
}
|
||||
};
|
||||
window.addEventListener("message", listener);
|
||||
window.postMessage(message, "*");
|
||||
window.postMessage(message, this.getTargetOrigin());
|
||||
});
|
||||
}
|
||||
|
||||
@@ -57,15 +68,14 @@ class ReactFiber {
|
||||
});
|
||||
}
|
||||
|
||||
async setState(update: any | ((prevState: any) => any)): Promise<ReactFiber> {
|
||||
const updateFnString =
|
||||
typeof update === "function" ? update.toString() : null;
|
||||
const updateObject = typeof update !== "function" ? update : null;
|
||||
async setState(update: Record<string, unknown>): Promise<ReactFiber> {
|
||||
if (typeof update !== "object" || update === null || Array.isArray(update)) {
|
||||
throw new TypeError(
|
||||
"ReactFiber.setState only accepts plain JSON-serializable objects",
|
||||
);
|
||||
}
|
||||
|
||||
await this.sendMessage("setState", {
|
||||
updateFn: updateFnString,
|
||||
updateObject,
|
||||
});
|
||||
await this.sendMessage("setState", { updateObject: update });
|
||||
return this;
|
||||
}
|
||||
|
||||
|
||||
@@ -100,7 +100,7 @@ export async function SendNewsPage() {
|
||||
? article.description
|
||||
: "No description available.";
|
||||
|
||||
description.innerHTML =
|
||||
description.textContent =
|
||||
articleDescription.length > 400
|
||||
? articleDescription.substring(0, 400) + "..."
|
||||
: articleDescription;
|
||||
|
||||
@@ -0,0 +1,50 @@
|
||||
const ALLOWED_HOST_SUFFIXES = [
|
||||
"betterseqta.org",
|
||||
"accounts.betterseqta.org",
|
||||
"raw.githubusercontent.com",
|
||||
"github.com",
|
||||
] as const;
|
||||
|
||||
function isPrivateOrLocalHost(hostname: string): boolean {
|
||||
const host = hostname.toLowerCase().replace(/^\[|\]$/g, "");
|
||||
if (host === "localhost" || host.endsWith(".localhost")) return true;
|
||||
if (host === "127.0.0.1" || host.startsWith("127.")) return true;
|
||||
if (host === "::1" || host === "0.0.0.0") return true;
|
||||
|
||||
const ipv4 = host.match(/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/);
|
||||
if (ipv4) {
|
||||
const [a, b] = [Number(ipv4[1]), Number(ipv4[2])];
|
||||
if (a === 10) return true;
|
||||
if (a === 172 && b >= 16 && b <= 31) return true;
|
||||
if (a === 192 && b === 168) return true;
|
||||
if (a === 169 && b === 254) return true;
|
||||
if (a === 127 || a === 0) return true;
|
||||
}
|
||||
|
||||
if (host.includes(":")) {
|
||||
const h = host.split("%")[0];
|
||||
if (h.startsWith("fe80") || h.startsWith("fc") || h.startsWith("fd")) return true;
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
function isAllowedHost(hostname: string): boolean {
|
||||
const host = hostname.toLowerCase();
|
||||
return ALLOWED_HOST_SUFFIXES.some(
|
||||
(suffix) => host === suffix || host.endsWith(`.${suffix}`),
|
||||
);
|
||||
}
|
||||
|
||||
/** HTTPS-only fetch allowlist for background `fetchFromUrl`. */
|
||||
export function isAllowedFetchUrl(urlString: string): boolean {
|
||||
let parsed: URL;
|
||||
try {
|
||||
parsed = new URL(urlString);
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
if (parsed.protocol !== "https:") return false;
|
||||
if (isPrivateOrLocalHost(parsed.hostname)) return false;
|
||||
return isAllowedHost(parsed.hostname);
|
||||
}
|
||||
@@ -73,14 +73,23 @@ const OMIT_FROM_UPLOAD_EXACT = new Set<string>([
|
||||
...KEYS_OMITTED_FROM_CLOUD_UPLOAD,
|
||||
...SENSITIVE_DEVICE_STORAGE_KEYS_EXACT,
|
||||
...CLIENT_ONLY_CLOUD_KEYS_EXACT,
|
||||
"devMode",
|
||||
"devGhReleaseVersionOverride",
|
||||
]);
|
||||
|
||||
const UNSAFE_STORAGE_KEYS = new Set(["__proto__", "constructor", "prototype"]);
|
||||
|
||||
function isUnsafeStorageKey(key: string): boolean {
|
||||
return UNSAFE_STORAGE_KEYS.has(key);
|
||||
}
|
||||
|
||||
/** True if a storage key is part of the upload payload (and should trigger auto-upload when changed). */
|
||||
export function isKeyIncludedInCloudUploadPayload(key: string): boolean {
|
||||
return !shouldOmitKeyFromCloudPayload(key);
|
||||
}
|
||||
|
||||
function shouldOmitKeyFromCloudPayload(key: string): boolean {
|
||||
if (isUnsafeStorageKey(key)) return true;
|
||||
if (OMIT_FROM_UPLOAD_EXACT.has(key)) return true;
|
||||
for (const prefix of SENSITIVE_DEVICE_STORAGE_KEY_PREFIXES) {
|
||||
if (key.startsWith(prefix)) return true;
|
||||
@@ -115,6 +124,7 @@ function collectLocalKeysToPreserve(local: Record<string, unknown>): Record<stri
|
||||
function stripExcludedKeysFromRemoteData(remote: Record<string, unknown>): Record<string, unknown> {
|
||||
const out: Record<string, unknown> = {};
|
||||
for (const [k, v] of Object.entries(remote)) {
|
||||
if (isUnsafeStorageKey(k)) continue;
|
||||
if (shouldOmitKeyFromCloudPayload(k)) continue;
|
||||
out[k] = v;
|
||||
}
|
||||
@@ -336,5 +346,7 @@ export async function applyDownloadedEnvelope(envelope: unknown): Promise<void>
|
||||
|
||||
const migrated = migrateLegacyToPluginSettings(remoteFlat);
|
||||
const remoteSanitized = stripExcludedKeysFromRemoteData(migrated);
|
||||
await browser.storage.local.set(remoteSanitized);
|
||||
const local = (await browser.storage.local.get()) as Record<string, unknown>;
|
||||
const preserve = collectLocalKeysToPreserve(local);
|
||||
await browser.storage.local.set({ ...remoteSanitized, ...preserve });
|
||||
}
|
||||
|
||||
@@ -22,6 +22,8 @@ const handleNotificationClick = async (target: HTMLElement) => {
|
||||
(item: any) => item.notificationID === parseInt(buttonId),
|
||||
);
|
||||
|
||||
if (!matchingNotification?.message?.messageID) return;
|
||||
|
||||
await waitForElm('[class*="Viewer__Viewer___"] > div', true, 20);
|
||||
|
||||
// Select the specific direct message
|
||||
|
||||
@@ -61,19 +61,19 @@ export class MessageHandler {
|
||||
themeManager.setTheme(request.body.themeID).then(() => {
|
||||
sendResponse({ status: "success" });
|
||||
});
|
||||
break;
|
||||
return true;
|
||||
|
||||
case "DisableTheme":
|
||||
themeManager.disableTheme().then(() => {
|
||||
sendResponse({ status: "success" });
|
||||
});
|
||||
break;
|
||||
return true;
|
||||
|
||||
case "DeleteTheme":
|
||||
themeManager.deleteTheme(request.body.themeID).then(() => {
|
||||
sendResponse({ status: "success" });
|
||||
});
|
||||
break;
|
||||
return true;
|
||||
|
||||
case "ListThemes":
|
||||
themeManager.getAvailableThemes().then((themes) => {
|
||||
@@ -97,11 +97,11 @@ export class MessageHandler {
|
||||
case "CloseThemeCreator":
|
||||
try {
|
||||
CloseThemeCreator();
|
||||
sendResponse({ status: "success" });
|
||||
} catch (error) {
|
||||
console.error("Error closing theme creator:", error);
|
||||
sendResponse({ status: "error" });
|
||||
}
|
||||
sendResponse({ status: "success" });
|
||||
break;
|
||||
|
||||
case "HideSensitive":
|
||||
|
||||
@@ -2,6 +2,20 @@ import browser from "webextension-polyfill";
|
||||
import type { SettingsState } from "@/types/storage";
|
||||
import type { Subscriber, Unsubscriber } from "svelte/store";
|
||||
|
||||
/** Auth/session keys live in `chrome.storage.local` only — not on the settingsState proxy. */
|
||||
const EXCLUDED_FROM_SETTINGS_SURFACE = new Set([
|
||||
"bsplus_token",
|
||||
"bsplus_refresh_token",
|
||||
"bsplus_client_id",
|
||||
"bsplus_user",
|
||||
"cloudAccessToken",
|
||||
"cloudUsername",
|
||||
]);
|
||||
|
||||
function isExcludedSettingsKey(key: string): boolean {
|
||||
return EXCLUDED_FROM_SETTINGS_SURFACE.has(key);
|
||||
}
|
||||
|
||||
type ChangeListener = (newValue: any, oldValue: any) => void;
|
||||
type GlobalChangeListener = (newValue: any, oldValue: any, key: string) => void;
|
||||
|
||||
@@ -26,9 +40,16 @@ class StorageManager {
|
||||
if (prop in target) {
|
||||
return (target as any)[prop];
|
||||
}
|
||||
if (typeof prop === "string" && isExcludedSettingsKey(prop)) {
|
||||
return undefined;
|
||||
}
|
||||
return Reflect.get(target.data, prop);
|
||||
},
|
||||
set: (target, prop: keyof SettingsState, value) => {
|
||||
if (typeof prop === "string" && isExcludedSettingsKey(prop)) {
|
||||
void browser.storage.local.set({ [prop]: value });
|
||||
return true;
|
||||
}
|
||||
const oldValue = target.data[prop];
|
||||
|
||||
// Only save if the reference actually changed
|
||||
@@ -95,6 +116,10 @@ class StorageManager {
|
||||
key: K,
|
||||
value: SettingsState[K],
|
||||
): void {
|
||||
if (typeof key === "string" && isExcludedSettingsKey(key)) {
|
||||
void browser.storage.local.set({ [key]: value });
|
||||
return;
|
||||
}
|
||||
const oldValue = this.data[key];
|
||||
if (oldValue !== value) {
|
||||
this.data[key] = value;
|
||||
@@ -121,6 +146,7 @@ class StorageManager {
|
||||
private async loadFromStorage(): Promise<void> {
|
||||
const result = await browser.storage.local.get();
|
||||
Object.entries(result).forEach(([key, value]) => {
|
||||
if (isExcludedSettingsKey(key)) return;
|
||||
Reflect.set(this.data, key, value);
|
||||
});
|
||||
}
|
||||
@@ -137,6 +163,7 @@ class StorageManager {
|
||||
: Object.keys(this.data);
|
||||
|
||||
for (const key of keys) {
|
||||
if (isExcludedSettingsKey(key)) continue;
|
||||
const value = (this.data as Record<string, unknown>)[key];
|
||||
if (value !== undefined) {
|
||||
payload[key] = value;
|
||||
@@ -163,6 +190,7 @@ class StorageManager {
|
||||
|
||||
for (const [key, { oldValue, newValue }] of Object.entries(changes)) {
|
||||
if (JSON.stringify(oldValue) === JSON.stringify(newValue)) continue;
|
||||
if (isExcludedSettingsKey(key)) continue;
|
||||
|
||||
if (newValue !== undefined) {
|
||||
(this.data as Record<string, unknown>)[key] = newValue;
|
||||
|
||||
@@ -4,7 +4,7 @@ import DOMPurify from "dompurify";
|
||||
* Converts an HTML string into a DOM element, with sanitization and optional styling.
|
||||
*
|
||||
* This function first sanitizes the input HTML string using DOMPurify to prevent XSS attacks.
|
||||
* The sanitization process allows 'onclick' attributes and specific URI schemes.
|
||||
* The sanitization process allows only safe URI schemes in links and media.
|
||||
* Then, it parses the sanitized string into an HTML document and returns its body.
|
||||
* Optionally, it can apply predefined CSS styles to the body element.
|
||||
*
|
||||
@@ -16,9 +16,8 @@ export default function stringToHTML(str: string, styles = false) {
|
||||
const parser = new DOMParser();
|
||||
|
||||
str = DOMPurify.sanitize(str, {
|
||||
ADD_ATTR: ["onclick"],
|
||||
ALLOWED_URI_REGEXP:
|
||||
/^(?:(?:(?:f|ht)tps?|mailto|tel|callto|sms|cid|xmpp|chrome-extension):|[^a-z]|[a-z+.\-]+(?:[^a-z+.\-:]|$))/i,
|
||||
/^(?:(?:https?|mailto|tel):|\/|#|[^a-z]|[a-z+.\-]+(?:[^a-z+.\-:]|$))/i,
|
||||
});
|
||||
|
||||
const doc = parser.parseFromString(str, "text/html");
|
||||
|
||||
@@ -69,11 +69,7 @@ export interface SettingsState {
|
||||
assessmentsAverage?: boolean;
|
||||
notificationCollector?: boolean;
|
||||
|
||||
// BetterSEQTA Cloud (accounts.betterseqta.org)
|
||||
bsplus_client_id?: string;
|
||||
bsplus_token?: string;
|
||||
bsplus_refresh_token?: string;
|
||||
bsplus_user?: { id: string; email?: string; username?: string; displayName?: string; pfpUrl?: string; pfpHash?: string | null; admin_level?: number };
|
||||
// BetterSEQTA Cloud (accounts.betterseqta.org) — stored via CloudAuth, not settingsState
|
||||
/** When not `false`, automatic cloud settings sync is enabled (default-on). */
|
||||
autoCloudSettingsSync?: boolean;
|
||||
}
|
||||
|
||||
@@ -215,6 +215,7 @@ export async function checkGithubReleaseUpdate(): Promise<GhReleaseUpdateInfo> {
|
||||
}
|
||||
|
||||
export function dismissNightlyUpdate(): void {
|
||||
cachedResult = null;
|
||||
void (async () => {
|
||||
const release = await fetchJson<GhRelease>(
|
||||
`https://api.github.com/repos/${getRepoSlug()}/releases/tags/${NIGHTLY_TAG}`,
|
||||
|
||||
Reference in New Issue
Block a user