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:
+146
-65
@@ -11,6 +11,7 @@ import {
|
|||||||
requestCloudSettingsDebouncedUpload,
|
requestCloudSettingsDebouncedUpload,
|
||||||
runCloudSettingsPoll,
|
runCloudSettingsPoll,
|
||||||
} from "./background/cloudSettingsAutoSync";
|
} from "./background/cloudSettingsAutoSync";
|
||||||
|
import { isAllowedFetchUrl } from "@/seqta/utils/allowedFetchUrl";
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Session-only dev-mode override of the content API base.
|
* 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 */
|
/** Callback for sending a response back to the message sender */
|
||||||
type MessageSender = { (response?: unknown): void };
|
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 } }`. */
|
/** Accept API + GitHub fallback shapes; always return `{ success, data?: { themes } }`. */
|
||||||
function normalizeFetchThemesResponse(json: unknown): {
|
function normalizeFetchThemesResponse(json: unknown): {
|
||||||
success: boolean;
|
success: boolean;
|
||||||
@@ -79,66 +85,101 @@ function normalizeFetchThemesResponse(json: unknown): {
|
|||||||
}
|
}
|
||||||
|
|
||||||
function handleFetchThemes(request: any, sendResponse: MessageSender): boolean {
|
function handleFetchThemes(request: any, sendResponse: MessageSender): boolean {
|
||||||
const { token } = request;
|
void (async () => {
|
||||||
const apiUrl = `${apiBase()}/api/themes?type=betterseqta&limit=100&nocache=${Date.now()}`;
|
const token = await getAccessTokenFromStorage();
|
||||||
const githubUrl = `https://raw.githubusercontent.com/BetterSEQTA/BetterSEQTA-Themes/main/store/themes.json?nocache=${Date.now()}`;
|
const apiUrl = `${apiBase()}/api/themes?type=betterseqta&limit=100&nocache=${Date.now()}`;
|
||||||
const headers: Record<string, string> = {};
|
const githubUrl = `https://raw.githubusercontent.com/BetterSEQTA/BetterSEQTA-Themes/main/store/themes.json?nocache=${Date.now()}`;
|
||||||
if (token) headers["Authorization"] = `Bearer ${token}`;
|
const headers: Record<string, string> = {};
|
||||||
fetch(apiUrl, { cache: "no-store", headers })
|
if (token) headers["Authorization"] = `Bearer ${token}`;
|
||||||
.then(async (r) => {
|
fetch(apiUrl, { cache: "no-store", headers })
|
||||||
const json = await r.json();
|
.then(async (r) => {
|
||||||
if (!r.ok) {
|
const json = await r.json();
|
||||||
throw new Error(
|
if (!r.ok) {
|
||||||
(json && typeof json === "object" && "error" in json && typeof (json as { error?: string }).error === "string"
|
throw new Error(
|
||||||
? (json as { error: string }).error
|
(json && typeof json === "object" && "error" in json && typeof (json as { error?: string }).error === "string"
|
||||||
: null) ?? `Themes API HTTP ${r.status}`,
|
? (json as { error: string }).error
|
||||||
);
|
: null) ?? `Themes API HTTP ${r.status}`,
|
||||||
}
|
);
|
||||||
return normalizeFetchThemesResponse(json);
|
}
|
||||||
})
|
return normalizeFetchThemesResponse(json);
|
||||||
.then(sendResponse)
|
})
|
||||||
.catch((err) => {
|
.then(sendResponse)
|
||||||
console.warn("[Background] fetchThemes API failed, trying GitHub fallback:", err?.message);
|
.catch((err) => {
|
||||||
fetch(githubUrl, { cache: "no-store" })
|
console.warn("[Background] fetchThemes API failed, trying GitHub fallback:", err?.message);
|
||||||
.then(async (r) => {
|
fetch(githubUrl, { cache: "no-store" })
|
||||||
if (!r.ok) throw new Error(`GitHub fallback HTTP ${r.status}`);
|
.then(async (r) => {
|
||||||
const data = await r.json();
|
if (!r.ok) throw new Error(`GitHub fallback HTTP ${r.status}`);
|
||||||
const themes = Array.isArray(data) ? data : (data?.themes ?? []);
|
const data = await r.json();
|
||||||
return normalizeFetchThemesResponse({ success: true, data: { themes } });
|
const themes = Array.isArray(data) ? data : (data?.themes ?? []);
|
||||||
})
|
return normalizeFetchThemesResponse({ success: true, data: { themes } });
|
||||||
.then(sendResponse)
|
})
|
||||||
.catch((fallbackErr) => {
|
.then(sendResponse)
|
||||||
console.error("[Background] fetchThemes GitHub fallback error:", fallbackErr);
|
.catch((fallbackErr) => {
|
||||||
sendResponse({ success: false, error: fallbackErr?.message });
|
console.error("[Background] fetchThemes GitHub fallback error:", fallbackErr);
|
||||||
});
|
sendResponse({ success: false, error: fallbackErr?.message });
|
||||||
});
|
});
|
||||||
|
});
|
||||||
|
})();
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
function handleFetchThemeDetails(request: any, sendResponse: MessageSender): boolean {
|
function handleFetchThemeDetails(request: any, sendResponse: MessageSender): boolean {
|
||||||
const { themeId, token } = request;
|
const { themeId } = request;
|
||||||
if (!themeId || typeof themeId !== "string") {
|
if (!themeId || typeof themeId !== "string") {
|
||||||
sendResponse({ success: false, error: "Missing themeId" });
|
sendResponse({ success: false, error: "Missing themeId" });
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
const headers: Record<string, string> = {};
|
void (async () => {
|
||||||
if (token) headers["Authorization"] = `Bearer ${token}`;
|
const token = await getAccessTokenFromStorage();
|
||||||
fetch(`${apiBase()}/api/themes/${themeId}`, { cache: "no-store", headers })
|
const headers: Record<string, string> = {};
|
||||||
.then((r) => r.json())
|
if (token) headers["Authorization"] = `Bearer ${token}`;
|
||||||
.then(sendResponse)
|
fetch(`${apiBase()}/api/themes/${themeId}`, { cache: "no-store", headers })
|
||||||
.catch((err) => {
|
.then((r) => r.json())
|
||||||
console.error("[Background] fetchThemeDetails error:", err);
|
.then(sendResponse)
|
||||||
sendResponse({ success: false, error: err?.message });
|
.catch((err) => {
|
||||||
});
|
console.error("[Background] fetchThemeDetails error:", err);
|
||||||
|
sendResponse({ success: false, error: err?.message });
|
||||||
|
});
|
||||||
|
})();
|
||||||
return true;
|
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;
|
const { url } = request;
|
||||||
if (!url || typeof url !== "string") {
|
if (!url || typeof url !== "string") {
|
||||||
sendResponse({ error: "Missing url" });
|
sendResponse({ error: "Missing url" });
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
if (!isAllowedFetchUrl(url)) {
|
||||||
|
sendResponse({ error: "URL not allowed" });
|
||||||
|
return false;
|
||||||
|
}
|
||||||
fetch(url, { cache: "no-store" })
|
fetch(url, { cache: "no-store" })
|
||||||
.then((r) => r.json())
|
.then((r) => r.json())
|
||||||
.then((data) => sendResponse({ data }))
|
.then((data) => sendResponse({ data }))
|
||||||
@@ -177,7 +218,15 @@ function handleCloudReserveClient(request: any, sendResponse: MessageSender): bo
|
|||||||
return true;
|
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;
|
const { client_id, redirect_uri, login, password } = request;
|
||||||
if (!client_id || !redirect_uri || !login || !password) {
|
if (!client_id || !redirect_uri || !login || !password) {
|
||||||
sendResponse({ error: "Missing client_id, redirect_uri, login, or password" });
|
sendResponse({ error: "Missing client_id, redirect_uri, login, or password" });
|
||||||
@@ -291,10 +340,18 @@ function handleCloudRefresh(request: any, sendResponse: MessageSender): boolean
|
|||||||
return true;
|
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 () => {
|
void (async () => {
|
||||||
try {
|
try {
|
||||||
const token = request.token as string | undefined;
|
const token = await getAccessTokenFromStorage();
|
||||||
if (!token) {
|
if (!token) {
|
||||||
sendResponse({ success: false, error: "Not authenticated" });
|
sendResponse({ success: false, error: "Not authenticated" });
|
||||||
return;
|
return;
|
||||||
@@ -316,10 +373,18 @@ function handleCloudSettingsUpload(request: any, sendResponse: MessageSender): b
|
|||||||
return true;
|
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 () => {
|
void (async () => {
|
||||||
try {
|
try {
|
||||||
const token = request.token as string | undefined;
|
const token = await getAccessTokenFromStorage();
|
||||||
if (!token) {
|
if (!token) {
|
||||||
sendResponse({ success: false, error: "Not authenticated" });
|
sendResponse({ success: false, error: "Not authenticated" });
|
||||||
return;
|
return;
|
||||||
@@ -343,22 +408,29 @@ function handleCloudSettingsDownload(request: any, sendResponse: MessageSender):
|
|||||||
}
|
}
|
||||||
|
|
||||||
function handleCloudFavorite(request: any, sendResponse: MessageSender): boolean {
|
function handleCloudFavorite(request: any, sendResponse: MessageSender): boolean {
|
||||||
const { themeId, token, action } = request;
|
const { themeId, action } = request;
|
||||||
if (!themeId || !token) {
|
if (!themeId) {
|
||||||
sendResponse({ success: false, error: "Theme ID and token required" });
|
sendResponse({ success: false, error: "Theme ID required" });
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
const isFavorite = action === "favorite";
|
void (async () => {
|
||||||
fetch(`${apiBase()}/api/themes/${themeId}/favorite`, {
|
const token = await getAccessTokenFromStorage();
|
||||||
method: isFavorite ? "POST" : "DELETE",
|
if (!token) {
|
||||||
headers: { Authorization: `Bearer ${token}` },
|
sendResponse({ success: false, error: "Not authenticated" });
|
||||||
})
|
return;
|
||||||
.then((r) => r.json())
|
}
|
||||||
.then(sendResponse)
|
const isFavorite = action === "favorite";
|
||||||
.catch((err) => {
|
fetch(`${apiBase()}/api/themes/${themeId}/favorite`, {
|
||||||
console.error("[Background] cloudFavorite error:", err);
|
method: isFavorite ? "POST" : "DELETE",
|
||||||
sendResponse({ success: false, error: err?.message });
|
headers: { Authorization: `Bearer ${token}` },
|
||||||
});
|
})
|
||||||
|
.then((r) => r.json())
|
||||||
|
.then(sendResponse)
|
||||||
|
.catch((err) => {
|
||||||
|
console.error("[Background] cloudFavorite error:", err);
|
||||||
|
sendResponse({ success: false, error: err?.message });
|
||||||
|
});
|
||||||
|
})();
|
||||||
return true;
|
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;
|
const url = typeof request?.url === "string" ? request.url.trim() : null;
|
||||||
if (url && /^https?:\/\//.test(url)) {
|
if (url && /^https?:\/\//.test(url)) {
|
||||||
DEV_API_BASE = url.replace(/\/$/, "");
|
DEV_API_BASE = url.replace(/\/$/, "");
|
||||||
@@ -415,7 +492,11 @@ const MESSAGE_HANDLERS: Record<string, MessageHandler> = {
|
|||||||
});
|
});
|
||||||
return true;
|
return true;
|
||||||
},
|
},
|
||||||
sendNews: (req, sendResponse) => {
|
sendNews: (req, sendResponse, sender) => {
|
||||||
|
if (!isTrustedSender(sender)) {
|
||||||
|
sendResponse({ error: "Unauthorized sender" });
|
||||||
|
return false;
|
||||||
|
}
|
||||||
fetchNews(req.source ?? "australia", sendResponse);
|
fetchNews(req.source ?? "australia", sendResponse);
|
||||||
return true;
|
return true;
|
||||||
},
|
},
|
||||||
|
|||||||
@@ -25,6 +25,11 @@ const REFRESH_URL = `${ACCOUNTS_BASE}/api/bsplus/refresh`;
|
|||||||
const UPLOAD_DEBOUNCE_MS = 2000;
|
const UPLOAD_DEBOUNCE_MS = 2000;
|
||||||
const POLL_THROTTLE_MS = 24 * 60 * 60 * 1000;
|
const POLL_THROTTLE_MS = 24 * 60 * 60 * 1000;
|
||||||
const POLL_THROTTLE_KEY = "bsplus_lastCloudPoll";
|
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 = {
|
type CloudSummaryResponse = {
|
||||||
desqta?: unknown;
|
desqta?: unknown;
|
||||||
@@ -35,6 +40,7 @@ let reloadSeqtaPagesFn: (() => void) | null = null;
|
|||||||
let suppressAutoUploadDuringRestore = false;
|
let suppressAutoUploadDuringRestore = false;
|
||||||
let debounceTimer: ReturnType<typeof setTimeout> | null = null;
|
let debounceTimer: ReturnType<typeof setTimeout> | null = null;
|
||||||
let pollInFlight: Promise<void> | null = null;
|
let pollInFlight: Promise<void> | null = null;
|
||||||
|
let autoSyncInitialized = false;
|
||||||
|
|
||||||
function isAutoCloudSyncEnabled(all: Record<string, unknown>): boolean {
|
function isAutoCloudSyncEnabled(all: Record<string, unknown>): boolean {
|
||||||
return all.autoCloudSettingsSync !== false;
|
return all.autoCloudSettingsSync !== false;
|
||||||
@@ -65,7 +71,7 @@ async function tryRefreshTokens(): Promise<boolean> {
|
|||||||
if (!refresh_token || !client_id) return false;
|
if (!refresh_token || !client_id) return false;
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const r = await fetch(REFRESH_URL, {
|
const r = await fetchWithTimeout(REFRESH_URL, {
|
||||||
method: "POST",
|
method: "POST",
|
||||||
headers: { "Content-Type": "application/json" },
|
headers: { "Content-Type": "application/json" },
|
||||||
body: JSON.stringify({ refresh_token, client_id }),
|
body: JSON.stringify({ refresh_token, client_id }),
|
||||||
@@ -100,7 +106,7 @@ async function fetchCloudSummaryOnce(
|
|||||||
| { ok: false; unauthorized: boolean; error?: string }
|
| { ok: false; unauthorized: boolean; error?: string }
|
||||||
> {
|
> {
|
||||||
try {
|
try {
|
||||||
const r = await fetch(CLOUD_SUMMARY_URL, {
|
const r = await fetchWithTimeout(CLOUD_SUMMARY_URL, {
|
||||||
headers: { Authorization: `Bearer ${token}` },
|
headers: { Authorization: `Bearer ${token}` },
|
||||||
cache: "no-store",
|
cache: "no-store",
|
||||||
});
|
});
|
||||||
@@ -177,7 +183,7 @@ async function putSettingsOnce(token: string): Promise<PutResult> {
|
|||||||
return { ok: true, skipped: true };
|
return { ok: true, skipped: true };
|
||||||
}
|
}
|
||||||
|
|
||||||
const r = await fetch(CLOUD_SETTINGS_SYNC_URL, {
|
const r = await fetchWithTimeout(CLOUD_SETTINGS_SYNC_URL, {
|
||||||
method: "PUT",
|
method: "PUT",
|
||||||
headers: {
|
headers: {
|
||||||
Authorization: `Bearer ${token}`,
|
Authorization: `Bearer ${token}`,
|
||||||
@@ -235,7 +241,7 @@ type GetResult =
|
|||||||
|
|
||||||
async function getSettingsAndApplyOnce(token: string): Promise<GetResult> {
|
async function getSettingsAndApplyOnce(token: string): Promise<GetResult> {
|
||||||
try {
|
try {
|
||||||
const r = await fetch(CLOUD_SETTINGS_SYNC_URL, {
|
const r = await fetchWithTimeout(CLOUD_SETTINGS_SYNC_URL, {
|
||||||
method: "GET",
|
method: "GET",
|
||||||
headers: { Authorization: `Bearer ${token}` },
|
headers: { Authorization: `Bearer ${token}` },
|
||||||
cache: "no-store",
|
cache: "no-store",
|
||||||
@@ -373,8 +379,8 @@ export function runCloudSettingsPoll(): Promise<void> {
|
|||||||
try {
|
try {
|
||||||
const { [POLL_THROTTLE_KEY]: last } = await browser.storage.local.get(POLL_THROTTLE_KEY);
|
const { [POLL_THROTTLE_KEY]: last } = await browser.storage.local.get(POLL_THROTTLE_KEY);
|
||||||
if (Date.now() - (Number(last) || 0) < POLL_THROTTLE_MS) return;
|
if (Date.now() - (Number(last) || 0) < POLL_THROTTLE_MS) return;
|
||||||
await browser.storage.local.set({ [POLL_THROTTLE_KEY]: Date.now() });
|
|
||||||
await runCloudSettingsPollInner();
|
await runCloudSettingsPollInner();
|
||||||
|
await browser.storage.local.set({ [POLL_THROTTLE_KEY]: Date.now() });
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
console.error("[BS+ cloud sync] Poll error:", e);
|
console.error("[BS+ cloud sync] Poll error:", e);
|
||||||
} finally {
|
} finally {
|
||||||
@@ -453,6 +459,8 @@ function onStorageChanged(
|
|||||||
|
|
||||||
export function initCloudSettingsAutoSync(deps: { reloadSeqtaPages: () => void }): void {
|
export function initCloudSettingsAutoSync(deps: { reloadSeqtaPages: () => void }): void {
|
||||||
reloadSeqtaPagesFn = deps.reloadSeqtaPages;
|
reloadSeqtaPagesFn = deps.reloadSeqtaPages;
|
||||||
|
if (autoSyncInitialized) return;
|
||||||
|
autoSyncInitialized = true;
|
||||||
browser.storage.onChanged.addListener(onStorageChanged);
|
browser.storage.onChanged.addListener(onStorageChanged);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
+20
-6
@@ -1,5 +1,7 @@
|
|||||||
import Parser from "rss-parser";
|
import Parser from "rss-parser";
|
||||||
|
|
||||||
|
const MAX_RATE_LIMIT_RETRIES = 3;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Fetches news articles specifically for Australia from the NewsAPI.
|
* 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.
|
* to send the fetched news data back to the caller.
|
||||||
* It's called with an object like `{ news: responseData }`.
|
* 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)
|
fetch(url)
|
||||||
.then((result) => result.json())
|
.then((result) => result.json())
|
||||||
.then((response) => {
|
.then((response) => {
|
||||||
if (response.code == "rateLimited") {
|
if (response.code == "rateLimited" && rateLimitRetryCount < MAX_RATE_LIMIT_RETRIES) {
|
||||||
fetchAustraliaNews((url += "%00"), sendResponse);
|
fetchAustraliaNews(`${url}%00`, sendResponse, rateLimitRetryCount + 1);
|
||||||
} else {
|
} else {
|
||||||
sendResponse({ news: response });
|
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") {
|
if (normalizedSource === "australia") {
|
||||||
const date = new Date();
|
const date = new Date();
|
||||||
|
date.setDate(date.getDate() - 5);
|
||||||
|
|
||||||
const from =
|
const from =
|
||||||
date.getFullYear() +
|
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`;
|
const url = `https://newsapi.org/v2/everything?domains=abc.net.au&from=${from}&apiKey=17c0da766ba347c89d094449504e3080`;
|
||||||
fetchAustraliaNews(url, sendResponse);
|
fetchAustraliaNews(url, sendResponse);
|
||||||
@@ -115,7 +126,6 @@ export async function fetchNews(source: string | undefined, sendResponse: any) {
|
|||||||
|
|
||||||
const parser = new Parser();
|
const parser = new Parser();
|
||||||
let feeds: string[];
|
let feeds: string[];
|
||||||
console.log("fetchNews", normalizedSource);
|
|
||||||
|
|
||||||
if (rssFeedsByCountry[normalizedSource.toLowerCase()]) {
|
if (rssFeedsByCountry[normalizedSource.toLowerCase()]) {
|
||||||
feeds = 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) => {
|
const articlesPromises = feeds.map(async (feedUrl) => {
|
||||||
try {
|
try {
|
||||||
const response = await fetch(feedUrl);
|
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 feedString = await response.text();
|
||||||
const feed = await parser.parseString(feedString);
|
const feed = await parser.parseString(feedString);
|
||||||
|
|
||||||
|
|||||||
@@ -92,7 +92,7 @@
|
|||||||
bind:this={background}
|
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"
|
class="flex absolute top-0 left-0 z-50 justify-center items-center w-full h-full cursor-pointer bg-black/50"
|
||||||
onclick={handleBackgroundClick}
|
onclick={handleBackgroundClick}
|
||||||
onkeydown={(e) => { if (e.key === "Enter") handleBackgroundClick; }}
|
onkeydown={(e) => { if (e.key === "Enter") handleBackgroundClick(e as unknown as MouseEvent) }}
|
||||||
>
|
>
|
||||||
<div
|
<div
|
||||||
bind:this={content}
|
bind:this={content}
|
||||||
|
|||||||
@@ -22,15 +22,13 @@
|
|||||||
});
|
});
|
||||||
|
|
||||||
async function upload() {
|
async function upload() {
|
||||||
const token = await cloudAuth.getStoredToken();
|
if (!cloudState.isLoggedIn) return;
|
||||||
if (!token) return;
|
|
||||||
busy = true;
|
busy = true;
|
||||||
statusError = null;
|
statusError = null;
|
||||||
statusMessage = null;
|
statusMessage = null;
|
||||||
try {
|
try {
|
||||||
const res = (await browser.runtime.sendMessage({
|
const res = (await browser.runtime.sendMessage({
|
||||||
type: "cloudSettingsUpload",
|
type: "cloudSettingsUpload",
|
||||||
token,
|
|
||||||
})) as { success?: boolean; error?: string };
|
})) as { success?: boolean; error?: string };
|
||||||
if (res?.success) {
|
if (res?.success) {
|
||||||
statusMessage = "Settings uploaded.";
|
statusMessage = "Settings uploaded.";
|
||||||
@@ -49,15 +47,13 @@
|
|||||||
}
|
}
|
||||||
|
|
||||||
async function confirmDownload() {
|
async function confirmDownload() {
|
||||||
const token = await cloudAuth.getStoredToken();
|
if (!cloudState.isLoggedIn) return;
|
||||||
if (!token) return;
|
|
||||||
busy = true;
|
busy = true;
|
||||||
statusError = null;
|
statusError = null;
|
||||||
statusMessage = null;
|
statusMessage = null;
|
||||||
try {
|
try {
|
||||||
const res = (await browser.runtime.sendMessage({
|
const res = (await browser.runtime.sendMessage({
|
||||||
type: "cloudSettingsDownload",
|
type: "cloudSettingsDownload",
|
||||||
token,
|
|
||||||
})) as { success?: boolean; error?: string; notFound?: boolean };
|
})) as { success?: boolean; error?: string; notFound?: boolean };
|
||||||
if (res?.success) {
|
if (res?.success) {
|
||||||
statusMessage = "Settings restored.";
|
statusMessage = "Settings restored.";
|
||||||
|
|||||||
@@ -19,6 +19,7 @@
|
|||||||
|
|
||||||
let editor = $state<HTMLDivElement | null>(null)
|
let editor = $state<HTMLDivElement | null>(null)
|
||||||
let view: EditorView | null = null;
|
let view: EditorView | null = null;
|
||||||
|
let unsubSettings: (() => void) | undefined;
|
||||||
let editorTheme = new Compartment();
|
let editorTheme = new Compartment();
|
||||||
let { value, onChange, className } = $props<{value: string, onChange: (value: string) => void, className?: string}>()
|
let { value, onChange, className } = $props<{value: string, onChange: (value: string) => void, className?: string}>()
|
||||||
|
|
||||||
@@ -73,7 +74,7 @@
|
|||||||
view = createEditorView(state, editor as HTMLElement);
|
view = createEditorView(state, editor as HTMLElement);
|
||||||
}
|
}
|
||||||
|
|
||||||
settingsState.subscribe((settings) => {
|
unsubSettings = settingsState.subscribe((settings) => {
|
||||||
if (view) {
|
if (view) {
|
||||||
view.dispatch({
|
view.dispatch({
|
||||||
effects: editorTheme.reconfigure(
|
effects: editorTheme.reconfigure(
|
||||||
@@ -85,6 +86,7 @@
|
|||||||
});
|
});
|
||||||
|
|
||||||
onDestroy(() => {
|
onDestroy(() => {
|
||||||
|
unsubSettings?.();
|
||||||
if (view) {
|
if (view) {
|
||||||
view.destroy();
|
view.destroy();
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -90,7 +90,7 @@
|
|||||||
bind:this={background}
|
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"
|
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}
|
onclick={handleBackgroundClick}
|
||||||
onkeydown={(e) => { e.key === 'Enter' && handleBackgroundClick }}
|
onkeydown={(e) => { if (e.key === 'Enter') handleBackgroundClick(e as unknown as MouseEvent) }}
|
||||||
>
|
>
|
||||||
<div
|
<div
|
||||||
bind:this={content}
|
bind:this={content}
|
||||||
|
|||||||
@@ -78,7 +78,7 @@
|
|||||||
|
|
||||||
const startRecording = () => {
|
const startRecording = () => {
|
||||||
isRecording = true;
|
isRecording = true;
|
||||||
recordedKeys.clear();
|
recordedKeys = new Set();
|
||||||
inputElement?.focus();
|
inputElement?.focus();
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -87,7 +87,7 @@
|
|||||||
if (recordedKeys.has('esc')) {
|
if (recordedKeys.has('esc')) {
|
||||||
onChange('');
|
onChange('');
|
||||||
isRecording = false;
|
isRecording = false;
|
||||||
recordedKeys.clear();
|
recordedKeys = new Set();
|
||||||
inputElement?.blur();
|
inputElement?.blur();
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
@@ -113,10 +113,16 @@
|
|||||||
}
|
}
|
||||||
|
|
||||||
isRecording = false;
|
isRecording = false;
|
||||||
recordedKeys.clear();
|
recordedKeys = new Set();
|
||||||
inputElement?.blur();
|
inputElement?.blur();
|
||||||
};
|
};
|
||||||
|
|
||||||
|
const addRecordedKey = (key: string) => {
|
||||||
|
const next = new Set(recordedKeys);
|
||||||
|
next.add(key);
|
||||||
|
recordedKeys = next;
|
||||||
|
};
|
||||||
|
|
||||||
const handleKeyDown = (e: KeyboardEvent) => {
|
const handleKeyDown = (e: KeyboardEvent) => {
|
||||||
if (!isRecording) return;
|
if (!isRecording) return;
|
||||||
|
|
||||||
@@ -126,14 +132,14 @@
|
|||||||
const key = formatKeyForHotkey(e.key);
|
const key = formatKeyForHotkey(e.key);
|
||||||
|
|
||||||
// Add modifiers
|
// Add modifiers
|
||||||
if (e.ctrlKey) recordedKeys.add('ctrl');
|
if (e.ctrlKey) addRecordedKey('ctrl');
|
||||||
if (e.metaKey) recordedKeys.add('cmd');
|
if (e.metaKey) addRecordedKey('cmd');
|
||||||
if (e.altKey) recordedKeys.add('alt');
|
if (e.altKey) addRecordedKey('alt');
|
||||||
if (e.shiftKey) recordedKeys.add('shift');
|
if (e.shiftKey) addRecordedKey('shift');
|
||||||
|
|
||||||
// Add the main key (ignore modifier keys themselves)
|
// Add the main key (ignore modifier keys themselves)
|
||||||
if (!['ctrl', 'cmd', 'alt', 'shift'].includes(key)) {
|
if (!['ctrl', 'cmd', 'alt', 'shift'].includes(key)) {
|
||||||
recordedKeys.add(key);
|
addRecordedKey(key);
|
||||||
}
|
}
|
||||||
|
|
||||||
// Auto-stop recording if we have a main key
|
// Auto-stop recording if we have a main key
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
<script lang="ts">
|
<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,
|
state: number,
|
||||||
onChange: (value: number) => void,
|
onChange: (value: number) => void,
|
||||||
min?: number,
|
min?: number,
|
||||||
|
|||||||
@@ -39,7 +39,7 @@
|
|||||||
</script>
|
</script>
|
||||||
|
|
||||||
<div class="flex flex-col h-full">
|
<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">
|
<div bind:this={containerRef} class="flex relative">
|
||||||
<MotionDiv
|
<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"
|
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}
|
{#each tabs as { title }, index}
|
||||||
<button
|
<button
|
||||||
|
role="tab"
|
||||||
|
aria-selected={activeTab === index}
|
||||||
class="relative z-10 flex-1 px-4 py-2 focus-visible:outline-none"
|
class="relative z-10 flex-1 px-4 py-2 focus-visible:outline-none"
|
||||||
onclick={() => activeTab = index}
|
onclick={() => activeTab = index}
|
||||||
>
|
>
|
||||||
@@ -64,7 +66,10 @@
|
|||||||
>
|
>
|
||||||
<div class="flex">
|
<div class="flex">
|
||||||
{#each tabs as { Content, props }, index}
|
{#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}%;">
|
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>
|
<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} />
|
<Content {...props} />
|
||||||
|
|||||||
@@ -12,18 +12,18 @@
|
|||||||
|
|
||||||
<div
|
<div
|
||||||
onclick={onClick}
|
onclick={onClick}
|
||||||
onkeydown={onClick}
|
onkeydown={(e) => { if (e.key === 'Enter' || e.key === ' ') onClick() }}
|
||||||
tabindex="-1"
|
tabindex="0"
|
||||||
role="button"
|
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'}"
|
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}
|
{#if isEditMode}
|
||||||
<div
|
<div
|
||||||
tabindex="-1"
|
tabindex="0"
|
||||||
role="button"
|
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"
|
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}
|
onclick={(e) => { e.stopPropagation(); onDelete() }}
|
||||||
onkeydown={onDelete}
|
onkeydown={(e) => { if (e.key === 'Enter' || e.key === ' ') { e.stopPropagation(); onDelete() } }}
|
||||||
>
|
>
|
||||||
<div class="w-4 h-0.5 bg-white"></div>
|
<div class="w-4 h-0.5 bg-white"></div>
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@@ -174,18 +174,19 @@
|
|||||||
if (parentElement) {
|
if (parentElement) {
|
||||||
observer = new MutationObserver(checkActiveClass);
|
observer = new MutationObserver(checkActiveClass);
|
||||||
observer.observe(parentElement, { attributes: true, attributeFilter: ['class'] });
|
observer.observe(parentElement, { attributes: true, attributeFilter: ['class'] });
|
||||||
|
|
||||||
return () => {
|
|
||||||
observer.disconnect();
|
|
||||||
backgroundUpdates.removeListener(syncBackgrounds);
|
|
||||||
};
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
return () => {
|
||||||
|
observer?.disconnect();
|
||||||
|
backgroundUpdates.removeListener(syncBackgrounds);
|
||||||
|
};
|
||||||
});
|
});
|
||||||
|
|
||||||
onDestroy(() => {
|
onDestroy(() => {
|
||||||
if (observer) {
|
observer?.disconnect();
|
||||||
observer.disconnect();
|
backgrounds.forEach((bg) => {
|
||||||
}
|
if (bg.url) URL.revokeObjectURL(bg.url);
|
||||||
|
});
|
||||||
});
|
});
|
||||||
</script>
|
</script>
|
||||||
|
|
||||||
|
|||||||
@@ -21,11 +21,14 @@
|
|||||||
let prevLoggedIn = $state(false);
|
let prevLoggedIn = $state(false);
|
||||||
let showSignInModal = $state(false);
|
let showSignInModal = $state(false);
|
||||||
|
|
||||||
cloudAuth.subscribe((s) => {
|
$effect(() => {
|
||||||
const now = s.isLoggedIn;
|
const unsub = cloudAuth.subscribe((s) => {
|
||||||
if (now && !prevLoggedIn && themes) void fetchThemes();
|
const now = s.isLoggedIn;
|
||||||
prevLoggedIn = now;
|
if (now && !prevLoggedIn && themes) void fetchThemes();
|
||||||
cloudLoggedIn = now;
|
prevLoggedIn = now;
|
||||||
|
cloudLoggedIn = now;
|
||||||
|
});
|
||||||
|
return unsub;
|
||||||
});
|
});
|
||||||
|
|
||||||
const handleThemeClick = async (theme: CustomTheme, e: MouseEvent) => {
|
const handleThemeClick = async (theme: CustomTheme, e: MouseEvent) => {
|
||||||
@@ -102,17 +105,14 @@
|
|||||||
selectedTheme: themeManager.getSelectedThemeId() || '',
|
selectedTheme: themeManager.getSelectedThemeId() || '',
|
||||||
}
|
}
|
||||||
if (themes && cloudLoggedIn) {
|
if (themes && cloudLoggedIn) {
|
||||||
const token = await cloudAuth.getStoredToken();
|
const status: Record<string, boolean> = {};
|
||||||
if (token) {
|
await Promise.all(
|
||||||
const status: Record<string, boolean> = {};
|
themes.themes.map(async (t) => {
|
||||||
await Promise.all(
|
try {
|
||||||
themes.themes.map(async (t) => {
|
const res = (await browser.runtime.sendMessage({
|
||||||
try {
|
type: 'fetchThemeDetails',
|
||||||
const res = (await browser.runtime.sendMessage({
|
themeId: t.id,
|
||||||
type: 'fetchThemeDetails',
|
})) as { success?: boolean; data?: { theme?: { is_favorited?: boolean } } };
|
||||||
themeId: t.id,
|
|
||||||
token,
|
|
||||||
})) as { success?: boolean; data?: { theme?: { is_favorited?: boolean } } };
|
|
||||||
if (res?.success && res?.data?.theme) {
|
if (res?.success && res?.data?.theme) {
|
||||||
status[t.id] = !!res.data.theme.is_favorited;
|
status[t.id] = !!res.data.theme.is_favorited;
|
||||||
}
|
}
|
||||||
@@ -122,7 +122,6 @@
|
|||||||
})
|
})
|
||||||
);
|
);
|
||||||
favoriteStatus = status;
|
favoriteStatus = status;
|
||||||
}
|
|
||||||
} else {
|
} else {
|
||||||
favoriteStatus = {};
|
favoriteStatus = {};
|
||||||
}
|
}
|
||||||
@@ -134,13 +133,10 @@
|
|||||||
showSignInModal = true;
|
showSignInModal = true;
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
const token = await cloudAuth.getStoredToken();
|
|
||||||
if (!token) return;
|
|
||||||
const isFavorite = !favoriteStatus[theme.id];
|
const isFavorite = !favoriteStatus[theme.id];
|
||||||
const result = (await browser.runtime.sendMessage({
|
const result = (await browser.runtime.sendMessage({
|
||||||
type: 'cloudFavorite',
|
type: 'cloudFavorite',
|
||||||
themeId: theme.id,
|
themeId: theme.id,
|
||||||
token,
|
|
||||||
action: isFavorite ? 'favorite' : 'unfavorite',
|
action: isFavorite ? 'favorite' : 'unfavorite',
|
||||||
})) as { success?: boolean };
|
})) as { success?: boolean };
|
||||||
if (result?.success) {
|
if (result?.success) {
|
||||||
|
|||||||
@@ -1,21 +1,25 @@
|
|||||||
<script lang="ts">
|
<script lang="ts">
|
||||||
import React from "react";
|
import React from "react";
|
||||||
import ReactDOM from "react-dom";
|
import ReactDOM from "react-dom";
|
||||||
import { onDestroy, onMount } from "svelte";
|
import { onDestroy } from "svelte";
|
||||||
|
|
||||||
const e = React.createElement;
|
const e = React.createElement;
|
||||||
let container: HTMLDivElement;
|
let adapterProps = $props();
|
||||||
|
let container = $state<HTMLDivElement | null>(null);
|
||||||
|
|
||||||
onMount(() => {
|
$effect(() => {
|
||||||
const { el, children, class: _, ...props } = $$props;
|
if (!container) return;
|
||||||
|
|
||||||
|
const { el, children, class: className, ...rest } = adapterProps;
|
||||||
try {
|
try {
|
||||||
ReactDOM.render(e(el, props, children), container);
|
ReactDOM.render(e(el, rest, children), container);
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
console.warn(`react-adapter failed to mount.`, { err });
|
console.warn(`react-adapter failed to mount.`, { err });
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
onDestroy(() => {
|
onDestroy(() => {
|
||||||
|
if (!container) return;
|
||||||
try {
|
try {
|
||||||
ReactDOM.unmountComponentAtNode(container);
|
ReactDOM.unmountComponentAtNode(container);
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
@@ -24,4 +28,4 @@
|
|||||||
});
|
});
|
||||||
</script>
|
</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 browser from "webextension-polyfill";
|
||||||
|
|
||||||
import { standalone as StandaloneStore } from "../utils/standalone.svelte";
|
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 { settingsState } from "@/seqta/utils/listeners/SettingsState";
|
||||||
|
|
||||||
import { closeExtensionPopup } from "@/seqta/utils/Closers/closeExtensionPopup";
|
import { closeExtensionPopup } from "@/seqta/utils/Closers/closeExtensionPopup";
|
||||||
@@ -108,12 +108,14 @@
|
|||||||
showDisclaimerModal = true;
|
showDisclaimerModal = true;
|
||||||
};
|
};
|
||||||
|
|
||||||
|
const closePopupsOnSettingsClose = () => {
|
||||||
|
showColourPicker = false;
|
||||||
|
showFontPicker = false;
|
||||||
|
showCloudPanel = false;
|
||||||
|
};
|
||||||
|
|
||||||
onMount(() => {
|
onMount(() => {
|
||||||
settingsPopup.addListener(() => {
|
settingsPopup.addListener(closePopupsOnSettingsClose);
|
||||||
showColourPicker = false;
|
|
||||||
showFontPicker = false;
|
|
||||||
showCloudPanel = false;
|
|
||||||
});
|
|
||||||
|
|
||||||
if (standalone) {
|
if (standalone) {
|
||||||
StandaloneStore.setStandalone(true);
|
StandaloneStore.setStandalone(true);
|
||||||
@@ -125,6 +127,10 @@
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
|
onDestroy(() => {
|
||||||
|
settingsPopup.removeListener(closePopupsOnSettingsClose);
|
||||||
|
});
|
||||||
</script>
|
</script>
|
||||||
|
|
||||||
<div
|
<div
|
||||||
|
|||||||
@@ -19,6 +19,7 @@
|
|||||||
import { closeExtensionPopup } from "@/seqta/utils/Closers/closeExtensionPopup"
|
import { closeExtensionPopup } from "@/seqta/utils/Closers/closeExtensionPopup"
|
||||||
import { getSnapshotForUpload } from "@/seqta/utils/cloudSettingsSync"
|
import { getSnapshotForUpload } from "@/seqta/utils/cloudSettingsSync"
|
||||||
import { getStoredOverride, setApiBase } from "@/seqta/utils/DevApiBase"
|
import { getStoredOverride, setApiBase } from "@/seqta/utils/DevApiBase"
|
||||||
|
import { onMount } from "svelte"
|
||||||
|
|
||||||
let devApiBaseInput = $state<string>(getStoredOverride() ?? "")
|
let devApiBaseInput = $state<string>(getStoredOverride() ?? "")
|
||||||
let devApiBaseActive = $state<string | null>(getStoredOverride())
|
let devApiBaseActive = $state<string | null>(getStoredOverride())
|
||||||
@@ -128,9 +129,9 @@
|
|||||||
await browser.storage.local.set({ [storageKey]: currentSettings });
|
await browser.storage.local.set({ [storageKey]: currentSettings });
|
||||||
}
|
}
|
||||||
|
|
||||||
$effect(() => {
|
onMount(() => {
|
||||||
loadPluginSettings();
|
void loadPluginSettings();
|
||||||
})
|
});
|
||||||
|
|
||||||
const { showColourPicker, showFontPicker, showDisclaimer, showCloudPanel } = $props<{
|
const { showColourPicker, showFontPicker, showDisclaimer, showCloudPanel } = $props<{
|
||||||
showColourPicker: () => void;
|
showColourPicker: () => void;
|
||||||
|
|||||||
@@ -23,7 +23,10 @@
|
|||||||
const themeManager = ThemeManager.getInstance();
|
const themeManager = ThemeManager.getInstance();
|
||||||
let cloudLoggedIn = $state(cloudAuth.state.isLoggedIn);
|
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
|
// State variables
|
||||||
let searchTerm = $state('');
|
let searchTerm = $state('');
|
||||||
@@ -86,13 +89,11 @@
|
|||||||
}
|
}
|
||||||
|
|
||||||
const toggleFavorite = async (theme: Theme) => {
|
const toggleFavorite = async (theme: Theme) => {
|
||||||
const token = await cloudAuth.getStoredToken();
|
if (!cloudLoggedIn) return;
|
||||||
if (!token) return;
|
|
||||||
const isFavorite = !theme.is_favorited;
|
const isFavorite = !theme.is_favorited;
|
||||||
const result = (await browser.runtime.sendMessage({
|
const result = (await browser.runtime.sendMessage({
|
||||||
type: 'cloudFavorite',
|
type: 'cloudFavorite',
|
||||||
themeId: theme.id,
|
themeId: theme.id,
|
||||||
token,
|
|
||||||
action: isFavorite ? 'favorite' : 'unfavorite',
|
action: isFavorite ? 'favorite' : 'unfavorite',
|
||||||
})) as { success?: boolean };
|
})) as { success?: boolean };
|
||||||
if (result?.success) {
|
if (result?.success) {
|
||||||
@@ -119,14 +120,12 @@
|
|||||||
error = null;
|
error = null;
|
||||||
}
|
}
|
||||||
try {
|
try {
|
||||||
const token = await cloudAuth.getStoredToken();
|
|
||||||
const data = await sendMessageWithTimeout<{
|
const data = await sendMessageWithTimeout<{
|
||||||
success?: boolean;
|
success?: boolean;
|
||||||
data?: { themes: unknown[] };
|
data?: { themes: unknown[] };
|
||||||
error?: string;
|
error?: string;
|
||||||
}>({
|
}>({
|
||||||
type: 'fetchThemes',
|
type: 'fetchThemes',
|
||||||
token: token ?? undefined,
|
|
||||||
});
|
});
|
||||||
if (!data?.success || !Array.isArray(data?.data?.themes)) {
|
if (!data?.success || !Array.isArray(data?.data?.themes)) {
|
||||||
throw new Error(data?.error || 'Failed to fetch 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) => {
|
window.addEventListener("message", (event) => {
|
||||||
|
if (!isTrustedMessage(event)) return;
|
||||||
|
|
||||||
if (event.data.type === "reactFiberRequest") {
|
if (event.data.type === "reactFiberRequest") {
|
||||||
const { selector, action, payload, debug, messageId } = event.data;
|
const { selector, action, payload, debug, messageId } = event.data;
|
||||||
const fiberInstance = ReactFiber.find(selector, {
|
const fiberInstance = ReactFiber.find(selector, {
|
||||||
@@ -522,12 +528,14 @@ window.addEventListener("message", (event) => {
|
|||||||
response = fiberInstance.getState(payload.key);
|
response = fiberInstance.getState(payload.key);
|
||||||
break;
|
break;
|
||||||
case "setState":
|
case "setState":
|
||||||
// Handle both function and object updates
|
if (
|
||||||
if (payload.updateFn) {
|
payload.updateObject &&
|
||||||
const updateFn = new Function('return ' + payload.updateFn)();
|
typeof payload.updateObject === "object" &&
|
||||||
fiberInstance.setState(updateFn);
|
!Array.isArray(payload.updateObject)
|
||||||
} else {
|
) {
|
||||||
fiberInstance.setState(payload.updateObject);
|
fiberInstance.setState(payload.updateObject);
|
||||||
|
} else {
|
||||||
|
console.warn("[pageState] setState rejected: only plain objects are allowed");
|
||||||
}
|
}
|
||||||
response = {};
|
response = {};
|
||||||
break;
|
break;
|
||||||
@@ -580,7 +588,7 @@ window.addEventListener("message", (event) => {
|
|||||||
response,
|
response,
|
||||||
messageId,
|
messageId,
|
||||||
},
|
},
|
||||||
"*",
|
window.location.origin,
|
||||||
);
|
);
|
||||||
} else if (event.data.type === "triggerKeyboardEvent") {
|
} else if (event.data.type === "triggerKeyboardEvent") {
|
||||||
// Handle keyboard event triggering from content script
|
// Handle keyboard event triggering from content script
|
||||||
|
|||||||
@@ -17,7 +17,7 @@ import {
|
|||||||
processAssessments,
|
processAssessments,
|
||||||
type WeightingEntry,
|
type WeightingEntry,
|
||||||
} from "./utils.ts";
|
} from "./utils.ts";
|
||||||
import { injectRubricCopyButtons } from "./rubricCopy.ts";
|
import { injectRubricCopyButtons, teardownRubricCopyButtons } from "./rubricCopy.ts";
|
||||||
|
|
||||||
interface weightingsStorage {
|
interface weightingsStorage {
|
||||||
weightings: Record<string, WeightingEntry>;
|
weightings: Record<string, WeightingEntry>;
|
||||||
@@ -41,6 +41,8 @@ class AssessmentsAveragePluginClass extends BasePlugin<typeof settings> {
|
|||||||
const instance = new AssessmentsAveragePluginClass();
|
const instance = new AssessmentsAveragePluginClass();
|
||||||
|
|
||||||
let overrideListenerController: AbortController | null = null;
|
let overrideListenerController: AbortController | null = null;
|
||||||
|
let wrapperColourObserver: MutationObserver | null = null;
|
||||||
|
let wrapperColourObserverTimeout: ReturnType<typeof setTimeout> | null = null;
|
||||||
|
|
||||||
const assessmentsAveragePlugin: Plugin<typeof settings, weightingsStorage> = {
|
const assessmentsAveragePlugin: Plugin<typeof settings, weightingsStorage> = {
|
||||||
id: "assessments-average",
|
id: "assessments-average",
|
||||||
@@ -54,7 +56,9 @@ const assessmentsAveragePlugin: Plugin<typeof settings, weightingsStorage> = {
|
|||||||
await initStorage(api);
|
await initStorage(api);
|
||||||
clearStuck(api);
|
clearStuck(api);
|
||||||
|
|
||||||
api.seqta.onMount(".assessmentsWrapper", async () => {
|
const { unregister: unregisterWrapperMount } = api.seqta.onMount(
|
||||||
|
".assessmentsWrapper",
|
||||||
|
async () => {
|
||||||
await waitForElm(
|
await waitForElm(
|
||||||
"#main > .assessmentsWrapper .assessments [class*='AssessmentItem__AssessmentItem___']",
|
"#main > .assessmentsWrapper .assessments [class*='AssessmentItem__AssessmentItem___']",
|
||||||
true,
|
true,
|
||||||
@@ -88,17 +92,43 @@ const assessmentsAveragePlugin: Plugin<typeof settings, weightingsStorage> = {
|
|||||||
void parseAssessments(api);
|
void parseAssessments(api);
|
||||||
const wrapper = document.querySelector(".assessmentsWrapper");
|
const wrapper = document.querySelector(".assessmentsWrapper");
|
||||||
if (wrapper) {
|
if (wrapper) {
|
||||||
const observer = new MutationObserver(() => {
|
wrapperColourObserver?.disconnect();
|
||||||
|
if (wrapperColourObserverTimeout) {
|
||||||
|
clearTimeout(wrapperColourObserverTimeout);
|
||||||
|
}
|
||||||
|
wrapperColourObserver = new MutationObserver(() => {
|
||||||
applySubjectColourToOverallResult();
|
applySubjectColourToOverallResult();
|
||||||
});
|
});
|
||||||
observer.observe(wrapper, { childList: true, subtree: true });
|
wrapperColourObserver.observe(wrapper, { childList: true, subtree: true });
|
||||||
setTimeout(() => observer.disconnect(), 10000);
|
wrapperColourObserverTimeout = setTimeout(() => {
|
||||||
|
wrapperColourObserver?.disconnect();
|
||||||
|
wrapperColourObserver = null;
|
||||||
|
wrapperColourObserverTimeout = null;
|
||||||
|
}, 10000);
|
||||||
}
|
}
|
||||||
});
|
},
|
||||||
api.seqta.onMount("[class*='SelectedAssessment__']", () => {
|
);
|
||||||
|
const { unregister: unregisterSelectedMount } = api.seqta.onMount(
|
||||||
|
"[class*='SelectedAssessment__']",
|
||||||
|
() => {
|
||||||
injectWeightingsTab(api);
|
injectWeightingsTab(api);
|
||||||
injectRubricCopyButtons();
|
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>;
|
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 {
|
export function computeFingerprint(mark: any): string {
|
||||||
const score =
|
const score =
|
||||||
mark?.results?.percentage ?? mark?.results?.score ?? null;
|
mark?.results?.percentage ?? mark?.results?.score ?? null;
|
||||||
@@ -264,6 +349,7 @@ function createWeightLabel(
|
|||||||
weighting: string | undefined,
|
weighting: string | undefined,
|
||||||
api: any,
|
api: any,
|
||||||
refreshing = false,
|
refreshing = false,
|
||||||
|
assessmentID?: string,
|
||||||
) {
|
) {
|
||||||
let statsContainer = assessmentItem.querySelector(
|
let statsContainer = assessmentItem.querySelector(
|
||||||
`[class*='AssessmentItem__stats___'], .betterseqta-stats-container`,
|
`[class*='AssessmentItem__stats___'], .betterseqta-stats-container`,
|
||||||
@@ -289,10 +375,8 @@ function createWeightLabel(
|
|||||||
? "space-between"
|
? "space-between"
|
||||||
: "flex-end";
|
: "flex-end";
|
||||||
|
|
||||||
const title = assessmentItem
|
const resolvedAssessmentId =
|
||||||
.querySelector(`[class*='AssessmentItem__title___']`)
|
assessmentID ?? assessmentItem.dataset.betterseqtaAssessmentId;
|
||||||
?.textContent?.trim();
|
|
||||||
const assessmentID = title ? api.storage.assessments?.[title] : undefined;
|
|
||||||
|
|
||||||
const existingLabel = statsContainer.querySelector(
|
const existingLabel = statsContainer.querySelector(
|
||||||
".betterseqta-weight-label",
|
".betterseqta-weight-label",
|
||||||
@@ -302,7 +386,7 @@ function createWeightLabel(
|
|||||||
updateWeightLabelContent(
|
updateWeightLabelContent(
|
||||||
existingLabel,
|
existingLabel,
|
||||||
weighting,
|
weighting,
|
||||||
assessmentID,
|
resolvedAssessmentId,
|
||||||
api,
|
api,
|
||||||
refreshing,
|
refreshing,
|
||||||
);
|
);
|
||||||
@@ -340,7 +424,7 @@ function createWeightLabel(
|
|||||||
updateWeightLabelContent(
|
updateWeightLabelContent(
|
||||||
weightLabel,
|
weightLabel,
|
||||||
weighting,
|
weighting,
|
||||||
assessmentID,
|
resolvedAssessmentId,
|
||||||
api,
|
api,
|
||||||
refreshing,
|
refreshing,
|
||||||
);
|
);
|
||||||
@@ -352,14 +436,20 @@ export const isFirefox =
|
|||||||
!navigator.userAgent.toLowerCase().includes("seamonkey") &&
|
!navigator.userAgent.toLowerCase().includes("seamonkey") &&
|
||||||
!navigator.userAgent.toLowerCase().includes("waterfox");
|
!navigator.userAgent.toLowerCase().includes("waterfox");
|
||||||
|
|
||||||
|
function trustedPageOrigin(): string {
|
||||||
|
return window.location.origin;
|
||||||
|
}
|
||||||
|
|
||||||
async function fetchPDFAsArrayBuffer(url: string): Promise<ArrayBuffer> {
|
async function fetchPDFAsArrayBuffer(url: string): Promise<ArrayBuffer> {
|
||||||
const isBlobUrl = url.startsWith("blob:");
|
const isBlobUrl = url.startsWith("blob:");
|
||||||
|
const pageOrigin = trustedPageOrigin();
|
||||||
|
|
||||||
if (isBlobUrl || isFirefox) {
|
if (isBlobUrl || isFirefox) {
|
||||||
return new Promise((resolve, reject) => {
|
return new Promise((resolve, reject) => {
|
||||||
const script = document.createElement("script");
|
const script = document.createElement("script");
|
||||||
const requestId = `pdf-fetch-${Date.now()}-${Math.random()}`;
|
const requestId = `pdf-fetch-${Date.now()}-${Math.random()}`;
|
||||||
const escapedUrl = url.replace(/'/g, "\\'");
|
const escapedUrl = url.replace(/'/g, "\\'");
|
||||||
|
const escapedOrigin = pageOrigin.replace(/'/g, "\\'");
|
||||||
|
|
||||||
script.textContent = `
|
script.textContent = `
|
||||||
(function() {
|
(function() {
|
||||||
@@ -375,19 +465,20 @@ async function fetchPDFAsArrayBuffer(url: string): Promise<ArrayBuffer> {
|
|||||||
type: '${requestId}',
|
type: '${requestId}',
|
||||||
success: true,
|
success: true,
|
||||||
data: Array.from(new Uint8Array(arrayBuffer))
|
data: Array.from(new Uint8Array(arrayBuffer))
|
||||||
}, '*');
|
}, '${escapedOrigin}');
|
||||||
})
|
})
|
||||||
.catch(error => {
|
.catch(error => {
|
||||||
window.postMessage({
|
window.postMessage({
|
||||||
type: '${requestId}',
|
type: '${requestId}',
|
||||||
success: false,
|
success: false,
|
||||||
error: error.message || String(error)
|
error: error.message || String(error)
|
||||||
}, '*');
|
}, '${escapedOrigin}');
|
||||||
});
|
});
|
||||||
})();
|
})();
|
||||||
`;
|
`;
|
||||||
|
|
||||||
const messageHandler = (event: MessageEvent) => {
|
const messageHandler = (event: MessageEvent) => {
|
||||||
|
if (event.origin !== pageOrigin || event.source !== window) return;
|
||||||
if (event.data?.type === requestId) {
|
if (event.data?.type === requestId) {
|
||||||
window.removeEventListener("message", messageHandler);
|
window.removeEventListener("message", messageHandler);
|
||||||
if (script.parentNode) {
|
if (script.parentNode) {
|
||||||
@@ -454,6 +545,9 @@ export async function extractPDFText(url: string): Promise<string> {
|
|||||||
const pdfLibInj = escJsSingleQuoted(pdfLibUrl);
|
const pdfLibInj = escJsSingleQuoted(pdfLibUrl);
|
||||||
const pdfWorkerInj = escJsSingleQuoted(pdfWorkerUrl);
|
const pdfWorkerInj = escJsSingleQuoted(pdfWorkerUrl);
|
||||||
|
|
||||||
|
const pageOrigin = trustedPageOrigin();
|
||||||
|
const escapedOrigin = pageOrigin.replace(/'/g, "\\'");
|
||||||
|
|
||||||
return new Promise((resolve, reject) => {
|
return new Promise((resolve, reject) => {
|
||||||
const script = document.createElement("script");
|
const script = document.createElement("script");
|
||||||
const requestId = `pdf-extract-${Date.now()}-${Math.random()}`;
|
const requestId = `pdf-extract-${Date.now()}-${Math.random()}`;
|
||||||
@@ -466,6 +560,7 @@ export async function extractPDFText(url: string): Promise<string> {
|
|||||||
script.textContent = `
|
script.textContent = `
|
||||||
(function() {
|
(function() {
|
||||||
const requestId = '${requestId}';
|
const requestId = '${requestId}';
|
||||||
|
const pageOrigin = '${escapedOrigin}';
|
||||||
const url = '${escapedUrl}';
|
const url = '${escapedUrl}';
|
||||||
const pdfLibSrc = '${pdfLibInj}';
|
const pdfLibSrc = '${pdfLibInj}';
|
||||||
const pdfWorkerSrc = '${pdfWorkerInj}';
|
const pdfWorkerSrc = '${pdfWorkerInj}';
|
||||||
@@ -485,7 +580,7 @@ export async function extractPDFText(url: string): Promise<string> {
|
|||||||
type: requestId,
|
type: requestId,
|
||||||
success: false,
|
success: false,
|
||||||
error: 'Failed to load pdfjs library'
|
error: 'Failed to load pdfjs library'
|
||||||
}, '*');
|
}, pageOrigin);
|
||||||
};
|
};
|
||||||
|
|
||||||
document.head.appendChild(pdfjsScript);
|
document.head.appendChild(pdfjsScript);
|
||||||
@@ -506,7 +601,7 @@ export async function extractPDFText(url: string): Promise<string> {
|
|||||||
type: requestId,
|
type: requestId,
|
||||||
success: false,
|
success: false,
|
||||||
error: 'HTTP ' + xhr.status + ': ' + xhr.statusText
|
error: 'HTTP ' + xhr.status + ': ' + xhr.statusText
|
||||||
}, '*');
|
}, pageOrigin);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -542,21 +637,21 @@ export async function extractPDFText(url: string): Promise<string> {
|
|||||||
type: requestId,
|
type: requestId,
|
||||||
success: true,
|
success: true,
|
||||||
text: text
|
text: text
|
||||||
}, '*');
|
}, pageOrigin);
|
||||||
})
|
})
|
||||||
.catch(error => {
|
.catch(error => {
|
||||||
window.postMessage({
|
window.postMessage({
|
||||||
type: requestId,
|
type: requestId,
|
||||||
success: false,
|
success: false,
|
||||||
error: 'PDF parsing error: ' + (error.message || String(error))
|
error: 'PDF parsing error: ' + (error.message || String(error))
|
||||||
}, '*');
|
}, pageOrigin);
|
||||||
});
|
});
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
window.postMessage({
|
window.postMessage({
|
||||||
type: requestId,
|
type: requestId,
|
||||||
success: false,
|
success: false,
|
||||||
error: 'ArrayBuffer error: ' + (error.message || String(error))
|
error: 'ArrayBuffer error: ' + (error.message || String(error))
|
||||||
}, '*');
|
}, pageOrigin);
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -565,7 +660,7 @@ export async function extractPDFText(url: string): Promise<string> {
|
|||||||
type: requestId,
|
type: requestId,
|
||||||
success: false,
|
success: false,
|
||||||
error: 'Network error fetching PDF'
|
error: 'Network error fetching PDF'
|
||||||
}, '*');
|
}, pageOrigin);
|
||||||
};
|
};
|
||||||
|
|
||||||
xhr.ontimeout = function() {
|
xhr.ontimeout = function() {
|
||||||
@@ -573,7 +668,7 @@ export async function extractPDFText(url: string): Promise<string> {
|
|||||||
type: requestId,
|
type: requestId,
|
||||||
success: false,
|
success: false,
|
||||||
error: 'Timeout fetching PDF'
|
error: 'Timeout fetching PDF'
|
||||||
}, '*');
|
}, pageOrigin);
|
||||||
};
|
};
|
||||||
|
|
||||||
xhr.timeout = 30000;
|
xhr.timeout = 30000;
|
||||||
@@ -583,13 +678,14 @@ export async function extractPDFText(url: string): Promise<string> {
|
|||||||
type: requestId,
|
type: requestId,
|
||||||
success: false,
|
success: false,
|
||||||
error: 'Setup error: ' + (error.message || String(error))
|
error: 'Setup error: ' + (error.message || String(error))
|
||||||
}, '*');
|
}, pageOrigin);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
})();
|
})();
|
||||||
`;
|
`;
|
||||||
|
|
||||||
const messageHandler = (event: MessageEvent) => {
|
const messageHandler = (event: MessageEvent) => {
|
||||||
|
if (event.origin !== pageOrigin || event.source !== window) return;
|
||||||
if (event.data?.type === requestId) {
|
if (event.data?.type === requestId) {
|
||||||
window.removeEventListener("message", messageHandler);
|
window.removeEventListener("message", messageHandler);
|
||||||
if (script.parentNode) {
|
if (script.parentNode) {
|
||||||
@@ -646,9 +742,8 @@ export async function extractPDFText(url: string): Promise<string> {
|
|||||||
}
|
}
|
||||||
|
|
||||||
async function handleWeightings(mark: any, api: any) {
|
async function handleWeightings(mark: any, api: any) {
|
||||||
const assessmentID = mark.id;
|
const assessmentID = assessmentIdKey(mark);
|
||||||
const metaclassID = mark.metaclassID;
|
const metaclassID = mark.metaclassID;
|
||||||
const title = mark.title;
|
|
||||||
|
|
||||||
const fingerprint = computeFingerprint(mark);
|
const fingerprint = computeFingerprint(mark);
|
||||||
const existing = api.storage.weightings[assessmentID] as
|
const existing = api.storage.weightings[assessmentID] as
|
||||||
@@ -687,10 +782,7 @@ async function handleWeightings(mark: any, api: any) {
|
|||||||
[assessmentID]: placeholder,
|
[assessmentID]: placeholder,
|
||||||
};
|
};
|
||||||
|
|
||||||
api.storage.assessments = {
|
registerAssessmentLookup(api, mark);
|
||||||
...api.storage.assessments,
|
|
||||||
[title.trim()]: assessmentID,
|
|
||||||
};
|
|
||||||
|
|
||||||
// Surface the refreshing indicator on the affected row immediately,
|
// Surface the refreshing indicator on the affected row immediately,
|
||||||
// without waiting for the PDF fetch to finish.
|
// without waiting for the PDF fetch to finish.
|
||||||
@@ -813,6 +905,16 @@ export async function processAssessments(api: any, assessmentItems: Element[]) {
|
|||||||
let hasRefreshingWeighting = false;
|
let hasRefreshingWeighting = false;
|
||||||
let count = 0;
|
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) {
|
for (const assessmentItem of assessmentItems) {
|
||||||
const titleEl = assessmentItem.querySelector(
|
const titleEl = assessmentItem.querySelector(
|
||||||
`[class*='AssessmentItem__title___']`,
|
`[class*='AssessmentItem__title___']`,
|
||||||
@@ -822,7 +924,11 @@ export async function processAssessments(api: any, assessmentItems: Element[]) {
|
|||||||
const title = titleEl.textContent?.trim();
|
const title = titleEl.textContent?.trim();
|
||||||
if (!title) continue;
|
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
|
const entry = assessmentID
|
||||||
? (api.storage.weightings?.[assessmentID] as WeightingEntry | undefined)
|
? (api.storage.weightings?.[assessmentID] as WeightingEntry | undefined)
|
||||||
: undefined;
|
: undefined;
|
||||||
@@ -833,7 +939,7 @@ export async function processAssessments(api: any, assessmentItems: Element[]) {
|
|||||||
const weighting = override ?? autoWeighting;
|
const weighting = override ?? autoWeighting;
|
||||||
const refreshing = !override && Boolean(entry?.refreshing);
|
const refreshing = !override && Boolean(entry?.refreshing);
|
||||||
|
|
||||||
createWeightLabel(assessmentItem, weighting, api, refreshing);
|
createWeightLabel(assessmentItem, weighting, api, refreshing, assessmentID);
|
||||||
|
|
||||||
const gradeElement = assessmentItem.querySelector(
|
const gradeElement = assessmentItem.querySelector(
|
||||||
`[class*='Thermoscore__text___']`,
|
`[class*='Thermoscore__text___']`,
|
||||||
@@ -935,12 +1041,17 @@ function resolveTabSetClasses(): Record<string, string> {
|
|||||||
return resolved;
|
return resolved;
|
||||||
}
|
}
|
||||||
|
|
||||||
function buildWeightingsTabContent(api: any, sheet: HTMLElement) {
|
async function buildWeightingsTabContent(api: any, sheet: HTMLElement) {
|
||||||
const titleEl = document.querySelector(
|
const selectedItem = document.querySelector(
|
||||||
"[class*='AssessmentItem__AssessmentItem___'][class*='selected___'] [class*='AssessmentItem__title___']",
|
"[class*='AssessmentItem__AssessmentItem___'][class*='selected___']",
|
||||||
|
) as HTMLElement | null;
|
||||||
|
const titleEl = selectedItem?.querySelector(
|
||||||
|
"[class*='AssessmentItem__title___']",
|
||||||
);
|
);
|
||||||
const title = titleEl?.textContent?.trim();
|
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
|
const entry = assessmentID
|
||||||
? (api.storage.weightings?.[assessmentID] as WeightingEntry | undefined)
|
? (api.storage.weightings?.[assessmentID] as WeightingEntry | undefined)
|
||||||
@@ -1093,7 +1204,7 @@ export function injectWeightingsTab(api: any) {
|
|||||||
container.appendChild(newSheet);
|
container.appendChild(newSheet);
|
||||||
|
|
||||||
newTab.addEventListener("click", () => {
|
newTab.addEventListener("click", () => {
|
||||||
buildWeightingsTabContent(api, newSheet);
|
void buildWeightingsTabContent(api, newSheet);
|
||||||
});
|
});
|
||||||
|
|
||||||
const allTabs = Array.from(tabList.querySelectorAll("li"));
|
const allTabs = Array.from(tabList.querySelectorAll("li"));
|
||||||
@@ -1107,20 +1218,22 @@ export function injectWeightingsTab(api: any) {
|
|||||||
t.className.includes("TabSet__selected___"),
|
t.className.includes("TabSet__selected___"),
|
||||||
);
|
);
|
||||||
if (i === currentIndex) return;
|
if (i === currentIndex) return;
|
||||||
const goingRight = i > currentIndex;
|
const goingRight = currentIndex < 0 ? true : i > currentIndex;
|
||||||
|
|
||||||
allTabs.forEach((t) => {
|
allTabs.forEach((t) => {
|
||||||
t.className = "";
|
t.className = "";
|
||||||
t.setAttribute("aria-selected", "false");
|
t.setAttribute("aria-selected", "false");
|
||||||
});
|
});
|
||||||
|
|
||||||
allSheets[currentIndex].className = [
|
if (currentIndex >= 0) {
|
||||||
cls["TabSet__tabsheet___"],
|
allSheets[currentIndex].className = [
|
||||||
cls["TabSet__hidden___"],
|
cls["TabSet__tabsheet___"],
|
||||||
goingRight
|
cls["TabSet__hidden___"],
|
||||||
? cls["TabSet__disappearToLeft___"]
|
goingRight
|
||||||
: cls["TabSet__disappearToRight___"],
|
? cls["TabSet__disappearToLeft___"]
|
||||||
].join(" ");
|
: cls["TabSet__disappearToRight___"],
|
||||||
|
].join(" ");
|
||||||
|
}
|
||||||
|
|
||||||
allSheets[i].className = [
|
allSheets[i].className = [
|
||||||
cls["TabSet__tabsheet___"],
|
cls["TabSet__tabsheet___"],
|
||||||
|
|||||||
@@ -29,6 +29,9 @@ async function fetchJSON(url: string, body: any) {
|
|||||||
headers: { "Content-Type": "application/json; charset=utf-8" },
|
headers: { "Content-Type": "application/json; charset=utf-8" },
|
||||||
body: JSON.stringify(body),
|
body: JSON.stringify(body),
|
||||||
});
|
});
|
||||||
|
if (!res.ok) {
|
||||||
|
throw new Error(`HTTP ${res.status} for ${url}`);
|
||||||
|
}
|
||||||
return res.json();
|
return res.json();
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -164,7 +167,7 @@ async function getLearnAssessmentsData(studentId: number) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
export async function getAssessmentsData() {
|
export async function getAssessmentsData() {
|
||||||
if (settingsState.mockNotices) {
|
if (settingsState.hideSensitiveContent) {
|
||||||
return getMockAssessmentsData();
|
return getMockAssessmentsData();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -38,6 +38,9 @@ async function fetchJSON(url: string, body: unknown) {
|
|||||||
headers: { "Content-Type": "application/json; charset=utf-8" },
|
headers: { "Content-Type": "application/json; charset=utf-8" },
|
||||||
body: JSON.stringify(body),
|
body: JSON.stringify(body),
|
||||||
});
|
});
|
||||||
|
if (!res.ok) {
|
||||||
|
throw new Error(`HTTP ${res.status} for ${url}`);
|
||||||
|
}
|
||||||
return res.json();
|
return res.json();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
import type { Plugin } from "../../core/types";
|
import type { Plugin } from "../../core/types";
|
||||||
import { waitForElm } from "@/seqta/utils/waitForElm";
|
import { waitForElm } from "@/seqta/utils/waitForElm";
|
||||||
import { getAssessmentsData } from "./api";
|
import { getAssessmentsData } from "./api";
|
||||||
import { renderErrorState, renderGrid, renderSkeletonLoader } from "./ui";
|
import { renderErrorState, renderGrid, renderSkeletonLoader, teardownOverviewUi } from "./ui";
|
||||||
import styles from "./styles.css?inline";
|
import styles from "./styles.css?inline";
|
||||||
import { delay } from "@/seqta/utils/delay";
|
import { delay } from "@/seqta/utils/delay";
|
||||||
import { isSeqtaEngageExperience } from "@/seqta/utils/isSeqtaEngage";
|
import { isSeqtaEngageExperience } from "@/seqta/utils/isSeqtaEngage";
|
||||||
@@ -66,6 +66,8 @@ const assessmentsOverviewPlugin: Plugin<{}> = {
|
|||||||
gridItem.appendChild(label);
|
gridItem.appendChild(label);
|
||||||
menu.insertBefore(gridItem, menu.firstChild);
|
menu.insertBefore(gridItem, menu.firstChild);
|
||||||
|
|
||||||
|
let loadRequestId = 0;
|
||||||
|
|
||||||
const menuObserver = new MutationObserver(() => {
|
const menuObserver = new MutationObserver(() => {
|
||||||
ensureOverviewMenuPosition(menu, gridItem);
|
ensureOverviewMenuPosition(menu, gridItem);
|
||||||
});
|
});
|
||||||
@@ -81,7 +83,18 @@ const assessmentsOverviewPlugin: Plugin<{}> = {
|
|||||||
};
|
};
|
||||||
gridItem.addEventListener("click", clickHandler);
|
gridItem.addEventListener("click", clickHandler);
|
||||||
|
|
||||||
|
const popstateHandler = () => {
|
||||||
|
if (isOverviewRoute()) {
|
||||||
|
void loadGridView();
|
||||||
|
} else {
|
||||||
|
loadRequestId += 1;
|
||||||
|
teardownOverviewUi();
|
||||||
|
}
|
||||||
|
};
|
||||||
|
window.addEventListener("popstate", popstateHandler);
|
||||||
|
|
||||||
async function loadGridView() {
|
async function loadGridView() {
|
||||||
|
const requestId = ++loadRequestId;
|
||||||
await delay(1);
|
await delay(1);
|
||||||
|
|
||||||
if (isSeqtaEngageExperience()) {
|
if (isSeqtaEngageExperience()) {
|
||||||
@@ -98,7 +111,7 @@ const assessmentsOverviewPlugin: Plugin<{}> = {
|
|||||||
}
|
}
|
||||||
|
|
||||||
const main = document.getElementById("main");
|
const main = document.getElementById("main");
|
||||||
if (!main) return;
|
if (!main || requestId !== loadRequestId) return;
|
||||||
|
|
||||||
document
|
document
|
||||||
.querySelectorAll('[data-key="assessments"] .item')
|
.querySelectorAll('[data-key="assessments"] .item')
|
||||||
@@ -110,17 +123,22 @@ const assessmentsOverviewPlugin: Plugin<{}> = {
|
|||||||
.querySelector('[data-key="assessments"]')
|
.querySelector('[data-key="assessments"]')
|
||||||
?.classList.add("active");
|
?.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(
|
const container = document.getElementById(
|
||||||
"grid-view-container",
|
"grid-view-container",
|
||||||
) as HTMLElement;
|
) as HTMLElement;
|
||||||
|
|
||||||
|
if (requestId !== loadRequestId) return;
|
||||||
|
|
||||||
renderSkeletonLoader(container);
|
renderSkeletonLoader(container);
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const data = await getAssessmentsData();
|
const data = await getAssessmentsData();
|
||||||
|
if (requestId !== loadRequestId) return;
|
||||||
renderGrid(container, data);
|
renderGrid(container, data);
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
|
if (requestId !== loadRequestId) return;
|
||||||
console.error("Failed to load assessments:", err);
|
console.error("Failed to load assessments:", err);
|
||||||
renderErrorState(
|
renderErrorState(
|
||||||
container,
|
container,
|
||||||
@@ -130,8 +148,11 @@ const assessmentsOverviewPlugin: Plugin<{}> = {
|
|||||||
}
|
}
|
||||||
|
|
||||||
return () => {
|
return () => {
|
||||||
|
loadRequestId += 1;
|
||||||
|
window.removeEventListener("popstate", popstateHandler);
|
||||||
menuObserver.disconnect();
|
menuObserver.disconnect();
|
||||||
gridItem.removeEventListener("click", clickHandler);
|
gridItem.removeEventListener("click", clickHandler);
|
||||||
|
teardownOverviewUi();
|
||||||
gridItem.remove();
|
gridItem.remove();
|
||||||
};
|
};
|
||||||
},
|
},
|
||||||
|
|||||||
@@ -62,7 +62,7 @@ export function activeSubjectsFromEngageChild(child: {
|
|||||||
const seen = new Set<string>();
|
const seen = new Set<string>();
|
||||||
|
|
||||||
for (const term of child.terms ?? []) {
|
for (const term of child.terms ?? []) {
|
||||||
if (term.active !== 1) continue;
|
if (!isActiveTermFlag(term.active)) continue;
|
||||||
for (const raw of term.subjects ?? []) {
|
for (const raw of term.subjects ?? []) {
|
||||||
const subject = normalizeOverviewSubject(raw);
|
const subject = normalizeOverviewSubject(raw);
|
||||||
if (!subject) continue;
|
if (!subject) continue;
|
||||||
@@ -151,7 +151,14 @@ export function determineStatus(item: any): string {
|
|||||||
}
|
}
|
||||||
|
|
||||||
const completedKey = "betterseqta-completed-assessments";
|
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)) {
|
if (completed.includes(item.id)) {
|
||||||
return "MARKS_RELEASED";
|
return "MARKS_RELEASED";
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -74,7 +74,10 @@ function ensureGestureStart(handler: () => void): () => void {
|
|||||||
|
|
||||||
async function startPlayback(volume: number): Promise<void> {
|
async function startPlayback(volume: number): Promise<void> {
|
||||||
const blob = await loadAudioBlob();
|
const blob = await loadAudioBlob();
|
||||||
if (!blob) return;
|
if (!blob) {
|
||||||
|
stopAndCleanupAudio();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
stopAndCleanupAudio();
|
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
|
// Start if we have audio and autoplay is enabled
|
||||||
const tryStart = async () => {
|
const tryStart = async () => {
|
||||||
@@ -160,16 +163,21 @@ const backgroundMusicPlugin: Plugin<typeof settings> = {
|
|||||||
};
|
};
|
||||||
document.addEventListener("visibilitychange", visHandler);
|
document.addEventListener("visibilitychange", visHandler);
|
||||||
|
|
||||||
// Allow uploads to trigger refresh
|
// Allow uploads to trigger refresh; stop event clears playback on remove
|
||||||
const uploadedHandler = () => {
|
const uploadedHandler = () => {
|
||||||
const vol = (api.settings as any).volume ?? 0.5;
|
const vol = (api.settings as any).volume ?? 0.5;
|
||||||
startPlayback(vol);
|
startPlayback(vol);
|
||||||
};
|
};
|
||||||
|
const stopHandler = () => {
|
||||||
|
stopAndCleanupAudio();
|
||||||
|
};
|
||||||
window.addEventListener("betterseqta-background-music-updated", uploadedHandler);
|
window.addEventListener("betterseqta-background-music-updated", uploadedHandler);
|
||||||
|
window.addEventListener("betterseqta-background-music-stop", stopHandler);
|
||||||
|
|
||||||
return () => {
|
return () => {
|
||||||
document.removeEventListener("visibilitychange", visHandler);
|
document.removeEventListener("visibilitychange", visHandler);
|
||||||
window.removeEventListener("betterseqta-background-music-updated", uploadedHandler);
|
window.removeEventListener("betterseqta-background-music-updated", uploadedHandler);
|
||||||
|
window.removeEventListener("betterseqta-background-music-stop", stopHandler);
|
||||||
if (cleanupRegistered && (window as any).__betterseqta_bg_music_cancel__) {
|
if (cleanupRegistered && (window as any).__betterseqta_bg_music_cancel__) {
|
||||||
(window as any).__betterseqta_bg_music_cancel__();
|
(window as any).__betterseqta_bg_music_cancel__();
|
||||||
(window as any).__betterseqta_bg_music_cancel__ = undefined;
|
(window as any).__betterseqta_bg_music_cancel__ = undefined;
|
||||||
|
|||||||
@@ -255,9 +255,9 @@ const watchNavigator = (navigator: Element, onChange: () => void) => {
|
|||||||
return observer;
|
return observer;
|
||||||
};
|
};
|
||||||
|
|
||||||
const handleSlidePane = (pane: Element) => {
|
const handleSlidePane = (pane: Element): (() => void) => {
|
||||||
const navigator = pane.querySelector(".navigator");
|
const navigator = pane.querySelector(".navigator");
|
||||||
if (!navigator) return;
|
if (!navigator) return () => {};
|
||||||
|
|
||||||
requestAnimationFrame(() => scrollSelectedIntoView(navigator));
|
requestAnimationFrame(() => scrollSelectedIntoView(navigator));
|
||||||
setTimeout(() => scrollSelectedIntoView(navigator), 50);
|
setTimeout(() => scrollSelectedIntoView(navigator), 50);
|
||||||
@@ -272,17 +272,22 @@ const handleSlidePane = (pane: Element) => {
|
|||||||
childList: true,
|
childList: true,
|
||||||
});
|
});
|
||||||
|
|
||||||
const cleanup = new MutationObserver((muts) => {
|
const paneCleanup = new MutationObserver((muts) => {
|
||||||
muts.forEach((m) => {
|
muts.forEach((m) => {
|
||||||
m.removedNodes.forEach((n) => {
|
m.removedNodes.forEach((n) => {
|
||||||
if (n === pane) {
|
if (n === pane) {
|
||||||
observer.disconnect();
|
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> = {
|
const enhancedNavigationPlugin: Plugin<typeof settings> = {
|
||||||
@@ -301,7 +306,11 @@ const enhancedNavigationPlugin: Plugin<typeof settings> = {
|
|||||||
window.addEventListener("resize", positionArrows);
|
window.addEventListener("resize", positionArrows);
|
||||||
window.addEventListener("scroll", positionArrows, true);
|
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;
|
const course = element as HTMLElement;
|
||||||
let navObserver: MutationObserver | null = null;
|
let navObserver: MutationObserver | null = null;
|
||||||
|
|
||||||
@@ -318,6 +327,7 @@ const enhancedNavigationPlugin: Plugin<typeof settings> = {
|
|||||||
}
|
}
|
||||||
ensureArrows(course);
|
ensureArrows(course);
|
||||||
});
|
});
|
||||||
|
navObservers.push(navObserver);
|
||||||
return true;
|
return true;
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -325,6 +335,7 @@ const enhancedNavigationPlugin: Plugin<typeof settings> = {
|
|||||||
const courseObserver = new MutationObserver(() => {
|
const courseObserver = new MutationObserver(() => {
|
||||||
if (setup()) courseObserver.disconnect();
|
if (setup()) courseObserver.disconnect();
|
||||||
});
|
});
|
||||||
|
courseObservers.push(courseObserver);
|
||||||
courseObserver.observe(course, { childList: true, subtree: true });
|
courseObserver.observe(course, { childList: true, subtree: true });
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
@@ -334,13 +345,21 @@ const enhancedNavigationPlugin: Plugin<typeof settings> = {
|
|||||||
m.addedNodes.forEach((n) => {
|
m.addedNodes.forEach((n) => {
|
||||||
if (n.nodeType !== 1) return;
|
if (n.nodeType !== 1) return;
|
||||||
const el = n as Element;
|
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 });
|
bodyObserver.observe(document.body, { childList: true });
|
||||||
|
|
||||||
return () => {
|
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();
|
bodyObserver.disconnect();
|
||||||
document.getElementById(ARROW_CONTAINER_ID)?.remove();
|
document.getElementById(ARROW_CONTAINER_ID)?.remove();
|
||||||
document.getElementById(STYLE_ID)?.remove();
|
document.getElementById(STYLE_ID)?.remove();
|
||||||
|
|||||||
@@ -175,29 +175,35 @@
|
|||||||
const term = searchTerm.trim().toLowerCase();
|
const term = searchTerm.trim().toLowerCase();
|
||||||
const requestId = ++searchRequestId;
|
const requestId = ++searchRequestId;
|
||||||
|
|
||||||
if (commandsFuse && dynamicContentFuse) {
|
try {
|
||||||
const results = await doSearch(
|
if (commandsFuse && dynamicContentFuse) {
|
||||||
term,
|
const results = await doSearch(
|
||||||
commandsFuse,
|
term,
|
||||||
commandIdToItemMap,
|
commandsFuse,
|
||||||
dynamicContentFuse,
|
commandIdToItemMap,
|
||||||
dynamicIdToItemMap,
|
dynamicContentFuse,
|
||||||
true, // sortByRecent
|
dynamicIdToItemMap,
|
||||||
);
|
true, // sortByRecent
|
||||||
|
);
|
||||||
|
|
||||||
// Drop the result if the user has typed since this search started, or
|
// Drop the result if the user has typed since this search started, or
|
||||||
// if the current term no longer matches what we searched for. This
|
// if the current term no longer matches what we searched for. This
|
||||||
// keeps the visible list anchored to the latest query.
|
// keeps the visible list anchored to the latest query.
|
||||||
if (requestId !== searchRequestId) return;
|
if (requestId !== searchRequestId) return;
|
||||||
if (searchTerm.trim().toLowerCase() !== term) return;
|
if (searchTerm.trim().toLowerCase() !== term) return;
|
||||||
|
|
||||||
combinedResults = results;
|
combinedResults = results;
|
||||||
} else {
|
} else {
|
||||||
if (requestId !== searchRequestId) return;
|
if (requestId !== searchRequestId) return;
|
||||||
combinedResults = [];
|
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;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
isLoading = false;
|
|
||||||
};
|
};
|
||||||
|
|
||||||
// Optimized debounce: shorter delay for better responsiveness
|
// Optimized debounce: shorter delay for better responsiveness
|
||||||
|
|||||||
@@ -214,7 +214,7 @@ const staticCommands: StaticCommandItem[] = [
|
|||||||
code: 'KeyM',
|
code: 'KeyM',
|
||||||
keyCode: 77,
|
keyCode: 77,
|
||||||
altKey: true
|
altKey: true
|
||||||
}, "*");
|
}, location.origin);
|
||||||
},
|
},
|
||||||
keywords: ["compose", "message", "dm", "direct message", "new message"],
|
keywords: ["compose", "message", "dm", "direct message", "new message"],
|
||||||
priority: 3,
|
priority: 3,
|
||||||
|
|||||||
@@ -37,6 +37,41 @@ export function mountSearchBar(
|
|||||||
const searchButton = document.createElement("div");
|
const searchButton = document.createElement("div");
|
||||||
searchButton.className = "search-trigger";
|
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");
|
const progressBarWrapper = document.createElement("div");
|
||||||
progressBarWrapper.className = "search-progress-bar-wrapper";
|
progressBarWrapper.className = "search-progress-bar-wrapper";
|
||||||
|
|
||||||
@@ -234,14 +269,10 @@ export function mountSearchBar(
|
|||||||
appRef.clearDoneFlashTimer = clearDoneFlashTimer;
|
appRef.clearDoneFlashTimer = clearDoneFlashTimer;
|
||||||
|
|
||||||
const updateSearchButtonDisplay = () => {
|
const updateSearchButtonDisplay = () => {
|
||||||
searchButton.innerHTML = /* html */ `
|
hotkeySpan.textContent = hotkeyDisplay;
|
||||||
<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">
|
if (!searchButton.contains(searchIcon)) {
|
||||||
<circle cx="11" cy="11" r="8"></circle>
|
searchButton.replaceChildren(searchIcon, searchLabel, hotkeySpan);
|
||||||
<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>
|
|
||||||
`;
|
|
||||||
};
|
};
|
||||||
|
|
||||||
updateSearchButtonDisplay();
|
updateSearchButtonDisplay();
|
||||||
|
|||||||
@@ -4,7 +4,7 @@ import { renderComponentMap } from "./renderComponents";
|
|||||||
import type { IndexItem, Job, JobContext } from "./types";
|
import type { IndexItem, Job, JobContext } from "./types";
|
||||||
import { VectorWorkerManager } from "./worker/vectorWorkerManager";
|
import { VectorWorkerManager } from "./worker/vectorWorkerManager";
|
||||||
import { loadDynamicItems } from "../utils/dynamicItems";
|
import { loadDynamicItems } from "../utils/dynamicItems";
|
||||||
import { getVectorizedItemIds } from "./utils";
|
import { getVectorizedItemIds, pruneOrphanVectorEmbeddings } from "./utils";
|
||||||
import { INDEX_SCHEMA_VERSION, SCHEMA_VERSION_KEY } from "./schemaVersion";
|
import { INDEX_SCHEMA_VERSION, SCHEMA_VERSION_KEY } from "./schemaVersion";
|
||||||
|
|
||||||
const META_STORE = "meta";
|
const META_STORE = "meta";
|
||||||
@@ -220,6 +220,7 @@ export async function runIndexing(): Promise<void> {
|
|||||||
startHeartbeat();
|
startHeartbeat();
|
||||||
console.debug("%c[Indexer] Starting indexing...", "color: green");
|
console.debug("%c[Indexer] Starting indexing...", "color: green");
|
||||||
|
|
||||||
|
try {
|
||||||
const jobIds = Object.keys(jobs);
|
const jobIds = Object.keys(jobs);
|
||||||
let completedJobs = 0;
|
let completedJobs = 0;
|
||||||
const totalSteps = jobIds.length + 1;
|
const totalSteps = jobIds.length + 1;
|
||||||
@@ -320,6 +321,17 @@ export async function runIndexing(): Promise<void> {
|
|||||||
|
|
||||||
let allItemsInPrimaryStores = await loadAllStoredItems();
|
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) {
|
if (allItemsInPrimaryStores.length > 0) {
|
||||||
console.debug(
|
console.debug(
|
||||||
`%c[Indexer] Checking ${allItemsInPrimaryStores.length} items for vectorization...`,
|
`%c[Indexer] Checking ${allItemsInPrimaryStores.length} items for vectorization...`,
|
||||||
@@ -434,8 +446,6 @@ export async function runIndexing(): Promise<void> {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
stopHeartbeat();
|
|
||||||
|
|
||||||
allItemsInPrimaryStores = await loadAllStoredItems();
|
allItemsInPrimaryStores = await loadAllStoredItems();
|
||||||
// Create new objects to avoid XrayWrapper issues in Firefox
|
// Create new objects to avoid XrayWrapper issues in Firefox
|
||||||
const itemsWithComponents = allItemsInPrimaryStores.map(item => {
|
const itemsWithComponents = allItemsInPrimaryStores.map(item => {
|
||||||
@@ -466,6 +476,9 @@ export async function runIndexing(): Promise<void> {
|
|||||||
});
|
});
|
||||||
loadDynamicItems(itemsWithComponents);
|
loadDynamicItems(itemsWithComponents);
|
||||||
window.dispatchEvent(new Event("dynamic-items-updated"));
|
window.dispatchEvent(new Event("dynamic-items-updated"));
|
||||||
|
} finally {
|
||||||
|
stopHeartbeat();
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
function mergeItems(existing: IndexItem[], incoming: IndexItem[]): IndexItem[] {
|
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 {
|
export function htmlToPlainText(rawHtml: string): string {
|
||||||
const parser = new DOMParser();
|
const parser = new DOMParser();
|
||||||
const doc = parser.parseFromString(rawHtml, "text/html");
|
const doc = parser.parseFromString(rawHtml, "text/html");
|
||||||
|
|||||||
@@ -242,11 +242,12 @@ export async function hybridSearch(
|
|||||||
export async function hybridSearchWithExpansion(
|
export async function hybridSearchWithExpansion(
|
||||||
bm25Results: CombinedResult[],
|
bm25Results: CombinedResult[],
|
||||||
query: string,
|
query: string,
|
||||||
_allItems: IndexItem[],
|
allItems: IndexItem[],
|
||||||
options: HybridSearchOptions = {},
|
options: HybridSearchOptions = {},
|
||||||
): Promise<CombinedResult[]> {
|
): Promise<CombinedResult[]> {
|
||||||
const opts = { ...DEFAULT_OPTIONS, ...options };
|
const opts = { ...DEFAULT_OPTIONS, ...options };
|
||||||
const trimmedQuery = query.trim().toLowerCase();
|
const trimmedQuery = query.trim().toLowerCase();
|
||||||
|
const liveIndexIds = new Set(allItems.map((item) => item.id));
|
||||||
|
|
||||||
// First, rerank BM25 results
|
// First, rerank BM25 results
|
||||||
const rerankedBm25 = await hybridSearch(bm25Results, query, options);
|
const rerankedBm25 = await hybridSearch(bm25Results, query, options);
|
||||||
@@ -298,6 +299,9 @@ export async function hybridSearchWithExpansion(
|
|||||||
vectorResults.forEach(v => {
|
vectorResults.forEach(v => {
|
||||||
if (bm25Ids.has(v.object.id)) return;
|
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
|
// This is a semantic match that BM25 missed
|
||||||
const item = v.object;
|
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';
|
import { unitFullNames } from './unitMap';
|
||||||
|
|
||||||
export interface CalculatorResult {
|
export interface CalculatorResult {
|
||||||
@@ -10,66 +10,42 @@ export interface CalculatorResult {
|
|||||||
error?: string;
|
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,
|
* Functions safe to replace with stubs. Do not block type constructors
|
||||||
ten: 10,
|
* (`complex`, `typed`, `fraction`, `bignumber`, `sparse`) or parse pipeline
|
||||||
three: 3,
|
* (`parse`, `compile`, `parser`) — mathjs needs those internally and
|
||||||
four: 4,
|
* `evaluate()` depends on them.
|
||||||
eight: 8,
|
*/
|
||||||
sixteen: 16,
|
const BLOCKED_MATH_FUNCTIONS = [
|
||||||
twenty: 20,
|
'import',
|
||||||
twentyfive: 25,
|
'createUnit',
|
||||||
fifty: 50,
|
'random',
|
||||||
hundred: 100,
|
'pickRandom',
|
||||||
plus: (a: number, b: number) => a + b,
|
'chain',
|
||||||
minus: (a: number, b: number) => a - b,
|
'help',
|
||||||
times: (a: number, b: number) => a * b,
|
] as const;
|
||||||
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,
|
|
||||||
|
|
||||||
// String functions
|
function createSandboxedMath() {
|
||||||
length: (str: string) => str.length,
|
const sandbox = create(all);
|
||||||
concat: (...args: string[]) => args.join(''),
|
const blockFn = () => {
|
||||||
uppercase: (str: string) => str.toUpperCase(),
|
throw new Error('Function not allowed');
|
||||||
lowercase: (str: string) => str.toLowerCase(),
|
};
|
||||||
substr: (str: string, start: number, length: number) => str.substr(start, length),
|
const blocked: Record<string, () => never> = {};
|
||||||
|
for (const name of BLOCKED_MATH_FUNCTIONS) {
|
||||||
|
blocked[name] = blockFn;
|
||||||
|
}
|
||||||
|
sandbox.import(blocked, { override: true });
|
||||||
|
return sandbox;
|
||||||
|
}
|
||||||
|
|
||||||
// Random functions
|
const calculatorMath = createSandboxedMath();
|
||||||
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 });
|
|
||||||
|
|
||||||
function detectUnit(expression: string): string {
|
function detectUnit(expression: string): string {
|
||||||
try {
|
try {
|
||||||
const unit = expandedMath.unit(expression);
|
const unit = calculatorMath.unit(expression);
|
||||||
if (unit) {
|
if (unit) {
|
||||||
const unitStr = unit.formatUnits();
|
const unitStr = unit.formatUnits();
|
||||||
return unitFullNames[unitStr] || unitStr;
|
return unitFullNames[unitStr] || unitStr;
|
||||||
@@ -120,9 +96,9 @@ function tryCompleteExpression(expression: string): string | null {
|
|||||||
// Handle cases like "4 + 3 *" -> evaluate "4 + 3"
|
// Handle cases like "4 + 3 *" -> evaluate "4 + 3"
|
||||||
if (partial && !partial.match(/[\+\-\*\/\^]\s*$/)) {
|
if (partial && !partial.match(/[\+\-\*\/\^]\s*$/)) {
|
||||||
try {
|
try {
|
||||||
const result = expandedMath.evaluate(partial);
|
const result = calculatorMath.evaluate(partial);
|
||||||
if (typeof result === 'number' && !isNaN(result)) {
|
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) {
|
} catch (e) {
|
||||||
// Continue to other attempts
|
// 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
|
// Check if this looks like a math expression at all
|
||||||
if (!isLikelyMathExpression(trimmed)) {
|
if (!isLikelyMathExpression(trimmed)) {
|
||||||
return {
|
return {
|
||||||
@@ -161,23 +148,23 @@ export function calculateExpression(input: string): CalculatorResult {
|
|||||||
|
|
||||||
try {
|
try {
|
||||||
// First try to evaluate the expression as-is
|
// First try to evaluate the expression as-is
|
||||||
const evaluated = expandedMath.evaluate(trimmed.replace('**', '^'));
|
const evaluated = calculatorMath.evaluate(trimmed.replace('**', '^'));
|
||||||
|
|
||||||
if (evaluated !== undefined) {
|
if (evaluated !== undefined) {
|
||||||
let result: string;
|
let result: string;
|
||||||
let inputUnit = '';
|
let inputUnit = '';
|
||||||
let outputUnit = '';
|
let outputUnit = '';
|
||||||
|
|
||||||
if (math.typeOf(evaluated) === 'Unit') {
|
if (mathTypeOf(evaluated) === 'Unit') {
|
||||||
// Handle unit conversion results
|
// 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);
|
inputUnit = detectUnit(trimmed);
|
||||||
outputUnit = detectUnit(result);
|
outputUnit = detectUnit(result);
|
||||||
} else if (typeof evaluated === 'number') {
|
} else if (typeof evaluated === 'number') {
|
||||||
// Handle regular numbers
|
// Handle regular numbers
|
||||||
result = math.format(evaluated, { precision: 14, lowerExp: -15, upperExp: 15 });
|
result = mathFormat(evaluated, { precision: 14, lowerExp: -15, upperExp: 15 });
|
||||||
} else {
|
} else {
|
||||||
result = math.format(evaluated, { precision: 14, lowerExp: -15, upperExp: 15 });
|
result = mathFormat(evaluated, { precision: 14, lowerExp: -15, upperExp: 15 });
|
||||||
}
|
}
|
||||||
|
|
||||||
return {
|
return {
|
||||||
|
|||||||
@@ -6,6 +6,14 @@ export interface ParsedHotkey {
|
|||||||
key: string;
|
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 {
|
export function parseHotkey(hotkeyString: string): ParsedHotkey {
|
||||||
const parts = hotkeyString.toLowerCase().split('+').map(part => part.trim()).filter(part => part.length > 0);
|
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');
|
parts.push(isMac ? '⇧' : 'Shift');
|
||||||
}
|
}
|
||||||
|
|
||||||
if (parsed.key) {
|
if (parsed.key && isAllowedHotkeyKey(parsed.key)) {
|
||||||
parts.push(parsed.key.toUpperCase());
|
parts.push(parsed.key.toUpperCase());
|
||||||
}
|
}
|
||||||
|
|
||||||
return parts.join(isMac ? ' ' : '+');
|
return parts.join(isMac ? ' ' : '+');
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.warn('Invalid hotkey string:', hotkeyString);
|
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);
|
const parsed = parseHotkey(hotkeyString);
|
||||||
|
|
||||||
// If no key is specified, don't match anything
|
// If no key is specified, don't match anything
|
||||||
if (!parsed.key) {
|
if (!parsed.key || !isAllowedHotkeyKey(parsed.key)) {
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -111,7 +119,7 @@ export function matchesHotkey(event: KeyboardEvent, hotkeyString: string): boole
|
|||||||
export function isValidHotkey(hotkeyString: string): boolean {
|
export function isValidHotkey(hotkeyString: string): boolean {
|
||||||
try {
|
try {
|
||||||
const parsed = parseHotkey(hotkeyString);
|
const parsed = parseHotkey(hotkeyString);
|
||||||
return parsed.key.length > 0;
|
return parsed.key.length > 0 && isAllowedHotkeyKey(parsed.key);
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -268,7 +268,7 @@
|
|||||||
|
|
||||||
xScale={scaleBand().padding(distribution().modeUsed === "letter" ? 0.22 : 0.28)}
|
xScale={scaleBand().padding(distribution().modeUsed === "letter" ? 0.22 : 0.28)}
|
||||||
|
|
||||||
yScale={yScale()}
|
yScale={yScale}
|
||||||
|
|
||||||
x="grade"
|
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) {
|
function toggleSort(column: keyof Assessment) {
|
||||||
if (sortColumn === column) {
|
if (sortColumn === column) {
|
||||||
sortDirection = sortDirection === "asc" ? "desc" : "asc";
|
sortDirection = sortDirection === "asc" ? "desc" : "asc";
|
||||||
|
|||||||
@@ -53,8 +53,9 @@
|
|||||||
const [minG, maxG] = gradeRange;
|
const [minG, maxG] = gradeRange;
|
||||||
return analyticsData.filter((a) => {
|
return analyticsData.filter((a) => {
|
||||||
if (filterSubjects.length && !filterSubjects.includes(a.subject)) return false;
|
if (filterSubjects.length && !filterSubjects.includes(a.subject)) return false;
|
||||||
const grade = a.finalGrade ?? -1;
|
if (a.finalGrade !== undefined) {
|
||||||
if (grade < minG || grade > maxG) return false;
|
if (a.finalGrade < minG || a.finalGrade > maxG) return false;
|
||||||
|
}
|
||||||
if (
|
if (
|
||||||
filterSearch &&
|
filterSearch &&
|
||||||
!a.title.toLowerCase().includes(filterSearch.toLowerCase()) &&
|
!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" },
|
headers: { "Content-Type": "application/json; charset=utf-8" },
|
||||||
body: JSON.stringify(body),
|
body: JSON.stringify(body),
|
||||||
});
|
});
|
||||||
|
if (!res.ok) {
|
||||||
|
throw new Error(`HTTP ${res.status} for ${url}`);
|
||||||
|
}
|
||||||
return res.json();
|
return res.json();
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -254,10 +257,19 @@ async function loadAllPast(
|
|||||||
const results: Record<string, unknown>[][] = [];
|
const results: Record<string, unknown>[][] = [];
|
||||||
for (let i = 0; i < subjects.length; i += PAST_FETCH_CONCURRENCY) {
|
for (let i = 0; i < subjects.length; i += PAST_FETCH_CONCURRENCY) {
|
||||||
const batch = subjects.slice(i, 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)),
|
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();
|
return results.flat();
|
||||||
}
|
}
|
||||||
@@ -295,7 +307,7 @@ function mergeRawAssessments(
|
|||||||
}
|
}
|
||||||
|
|
||||||
export async function getStudentId(): Promise<number> {
|
export async function getStudentId(): Promise<number> {
|
||||||
const info = await getUserInfo();
|
const info = await getUserInfo({ validateSession: true });
|
||||||
const id = Number(info?.id);
|
const id = Number(info?.id);
|
||||||
if (!id || isNaN(id)) throw new Error("Could not resolve student ID");
|
if (!id || isNaN(id)) throw new Error("Could not resolve student ID");
|
||||||
return id;
|
return id;
|
||||||
|
|||||||
@@ -67,6 +67,44 @@ function generateId(): string {
|
|||||||
return Date.now().toString(36) + Math.random().toString(36).slice(2, 7);
|
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> = {
|
const messageFoldersPlugin: Plugin<typeof messageFoldersSettings, MessageFoldersStorage> = {
|
||||||
id: "messageFolders",
|
id: "messageFolders",
|
||||||
name: "Message Folders",
|
name: "Message Folders",
|
||||||
@@ -95,7 +133,8 @@ const messageFoldersPlugin: Plugin<typeof messageFoldersSettings, MessageFolders
|
|||||||
let foldedSection: HTMLElement | null = null;
|
let foldedSection: HTMLElement | null = null;
|
||||||
const unregisters: Array<{ unregister: () => void }> = [];
|
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 getAssignments = (): Record<string, string[]> => api.storage.messageAssignments ?? {};
|
||||||
|
|
||||||
const saveFolders = (folders: Folder[]) => {
|
const saveFolders = (folders: Folder[]) => {
|
||||||
@@ -298,7 +337,7 @@ const messageFoldersPlugin: Plugin<typeof messageFoldersSettings, MessageFolders
|
|||||||
|
|
||||||
const iconSpan = document.createElement("span");
|
const iconSpan = document.createElement("span");
|
||||||
iconSpan.className = "bsplus-folder-icon";
|
iconSpan.className = "bsplus-folder-icon";
|
||||||
iconSpan.innerHTML = folder.emoji || FOLDER_HEROICONS[0];
|
setSvgIconContent(iconSpan, folder.emoji || FOLDER_HEROICONS[0]);
|
||||||
item.appendChild(iconSpan);
|
item.appendChild(iconSpan);
|
||||||
|
|
||||||
const name = document.createElement("span");
|
const name = document.createElement("span");
|
||||||
@@ -622,7 +661,7 @@ const messageFoldersPlugin: Plugin<typeof messageFoldersSettings, MessageFolders
|
|||||||
|
|
||||||
const iconSpan = document.createElement("span");
|
const iconSpan = document.createElement("span");
|
||||||
iconSpan.className = "bsplus-folder-icon";
|
iconSpan.className = "bsplus-folder-icon";
|
||||||
iconSpan.innerHTML = folder.emoji || FOLDER_HEROICONS[0];
|
setSvgIconContent(iconSpan, folder.emoji || FOLDER_HEROICONS[0]);
|
||||||
|
|
||||||
const name = document.createElement("span");
|
const name = document.createElement("span");
|
||||||
name.textContent = folder.name;
|
name.textContent = folder.name;
|
||||||
@@ -725,7 +764,7 @@ const messageFoldersPlugin: Plugin<typeof messageFoldersSettings, MessageFolders
|
|||||||
dot.style.background = folder.color;
|
dot.style.background = folder.color;
|
||||||
const iconSpan = document.createElement("span");
|
const iconSpan = document.createElement("span");
|
||||||
iconSpan.className = "bsplus-folder-icon";
|
iconSpan.className = "bsplus-folder-icon";
|
||||||
iconSpan.innerHTML = folder.emoji || FOLDER_HEROICONS[0];
|
setSvgIconContent(iconSpan, folder.emoji || FOLDER_HEROICONS[0]);
|
||||||
const name = document.createElement("span");
|
const name = document.createElement("span");
|
||||||
name.textContent = folder.name;
|
name.textContent = folder.name;
|
||||||
item.appendChild(dot);
|
item.appendChild(dot);
|
||||||
@@ -810,7 +849,7 @@ const messageFoldersPlugin: Plugin<typeof messageFoldersSettings, MessageFolders
|
|||||||
const badge = document.createElement("span");
|
const badge = document.createElement("span");
|
||||||
badge.className = "bsplus-msg-badge";
|
badge.className = "bsplus-msg-badge";
|
||||||
badge.style.background = folder.color;
|
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.title = `Filter by "${folder.name}"`;
|
||||||
badge.addEventListener("click", (e) => {
|
badge.addEventListener("click", (e) => {
|
||||||
e.stopPropagation();
|
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();
|
const data = await response.json();
|
||||||
|
|
||||||
// Store notification count for history
|
// 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 { settingsState } from "@/seqta/utils/listeners/SettingsState";
|
||||||
import debounce from "@/seqta/utils/debounce";
|
import debounce from "@/seqta/utils/debounce";
|
||||||
import { themeUpdates } from "@/interface/hooks/ThemeUpdates";
|
import { themeUpdates } from "@/interface/hooks/ThemeUpdates";
|
||||||
import { cloudAuth } from "@/seqta/utils/CloudAuth";
|
|
||||||
import { getApiBase } from "@/seqta/utils/DevApiBase";
|
import { getApiBase } from "@/seqta/utils/DevApiBase";
|
||||||
|
import { isAllowedFetchUrl } from "@/seqta/utils/allowedFetchUrl";
|
||||||
import { updateAllColors } from "@/seqta/ui/colors/Manager";
|
import { updateAllColors } from "@/seqta/ui/colors/Manager";
|
||||||
import {
|
import {
|
||||||
clearCustomThemeAdaptiveCssVariables,
|
clearCustomThemeAdaptiveCssVariables,
|
||||||
@@ -667,8 +667,12 @@ export class ThemeManager {
|
|||||||
if (!downloadData?.success || !downloadData?.data?.theme_json_url) {
|
if (!downloadData?.success || !downloadData?.data?.theme_json_url) {
|
||||||
throw new Error("Failed to get theme download 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(
|
themeData = (await this.fetchFromUrl(
|
||||||
downloadData.data.theme_json_url,
|
themeJsonUrl,
|
||||||
)) as ThemeContent;
|
)) as ThemeContent;
|
||||||
} catch (apiError) {
|
} catch (apiError) {
|
||||||
console.warn("[ThemeManager] API failed, trying GitHub fallback:", apiError);
|
console.warn("[ThemeManager] API failed, trying GitHub fallback:", apiError);
|
||||||
@@ -796,10 +800,8 @@ export class ThemeManager {
|
|||||||
this.storeUpdateCheckRunning = true;
|
this.storeUpdateCheckRunning = true;
|
||||||
localStorage.setItem(ThemeManager.STORE_CHECK_KEY, String(Date.now()));
|
localStorage.setItem(ThemeManager.STORE_CHECK_KEY, String(Date.now()));
|
||||||
try {
|
try {
|
||||||
const token = await cloudAuth.getStoredToken();
|
|
||||||
const res = (await browser.runtime.sendMessage({
|
const res = (await browser.runtime.sendMessage({
|
||||||
type: "fetchThemes",
|
type: "fetchThemes",
|
||||||
token: token ?? undefined,
|
|
||||||
})) as {
|
})) as {
|
||||||
success?: boolean;
|
success?: boolean;
|
||||||
data?: { themes?: Array<{ id: string; updated_at?: number }> };
|
data?: { themes?: Array<{ id: string; updated_at?: number }> };
|
||||||
|
|||||||
@@ -84,6 +84,8 @@ async function handleTimetable(): Promise<void> {
|
|||||||
}
|
}
|
||||||
|
|
||||||
function handleTimetableZoom(): void {
|
function handleTimetableZoom(): void {
|
||||||
|
if (document.querySelector(".timetable-zoom-controls")) return;
|
||||||
|
|
||||||
console.log("Initializing timetable zoom controls");
|
console.log("Initializing timetable zoom controls");
|
||||||
|
|
||||||
// Create zoom controls
|
// Create zoom controls
|
||||||
@@ -130,6 +132,8 @@ function handleTimetableZoom(): void {
|
|||||||
}
|
}
|
||||||
|
|
||||||
function handleTimetableAssessmentHide(): void {
|
function handleTimetableAssessmentHide(): void {
|
||||||
|
if (document.querySelector(".timetable-hide-controls")) return;
|
||||||
|
|
||||||
const hideControls = document.createElement("div");
|
const hideControls = document.createElement("div");
|
||||||
hideControls.className = "timetable-hide-controls";
|
hideControls.className = "timetable-hide-controls";
|
||||||
|
|
||||||
|
|||||||
@@ -85,7 +85,10 @@ function createSEQTAAPI(): SEQTAAPI {
|
|||||||
*/
|
*/
|
||||||
function createSettingsAPI<T extends PluginSettings>(
|
function createSettingsAPI<T extends PluginSettings>(
|
||||||
plugin: Plugin<T>,
|
plugin: Plugin<T>,
|
||||||
): SettingsAPI<T> & { loaded: Promise<void> } {
|
): {
|
||||||
|
settings: SettingsAPI<T> & { loaded: Promise<void> };
|
||||||
|
dispose: () => void;
|
||||||
|
} {
|
||||||
const storageKey = `plugin.${plugin.id}.settings`;
|
const storageKey = `plugin.${plugin.id}.settings`;
|
||||||
const listeners = new Map<keyof T, Set<(value: any) => void>>();
|
const listeners = new Map<keyof T, Set<(value: any) => void>>();
|
||||||
|
|
||||||
@@ -167,6 +170,10 @@ function createSettingsAPI<T extends PluginSettings>(
|
|||||||
|
|
||||||
browser.storage.onChanged.addListener(handleStorageChange);
|
browser.storage.onChanged.addListener(handleStorageChange);
|
||||||
|
|
||||||
|
const dispose = () => {
|
||||||
|
browser.storage.onChanged.removeListener(handleStorageChange);
|
||||||
|
};
|
||||||
|
|
||||||
const proxy = new Proxy(settingsWithMeta, {
|
const proxy = new Proxy(settingsWithMeta, {
|
||||||
get(target, prop) {
|
get(target, prop) {
|
||||||
return target[prop];
|
return target[prop];
|
||||||
@@ -183,6 +190,17 @@ function createSettingsAPI<T extends PluginSettings>(
|
|||||||
dataToStore[key] = target[key];
|
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 });
|
browser.storage.local.set({ [storageKey]: dataToStore });
|
||||||
|
|
||||||
listeners.get(prop as keyof T)?.forEach((cb) => cb(value));
|
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> };
|
}) as SettingsAPI<T> & { loaded: Promise<void> };
|
||||||
|
|
||||||
return proxy;
|
return { settings: proxy, dispose };
|
||||||
}
|
}
|
||||||
|
|
||||||
function createStorageAPI<T = any>(
|
function createStorageAPI<T = any>(
|
||||||
pluginId: string,
|
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 prefix = `plugin.${pluginId}.storage.`;
|
||||||
const cache: Record<string, any> = {};
|
const cache: Record<string, any> = {};
|
||||||
const listeners = new Map<string, Set<(value: any) => void>>();
|
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
|
// Load all existing storage values for this plugin
|
||||||
const loadStoragePromise = (async () => {
|
const loadStoragePromise = (async () => {
|
||||||
@@ -243,10 +261,13 @@ function createStorageAPI<T = any>(
|
|||||||
}
|
}
|
||||||
};
|
};
|
||||||
browser.storage.onChanged.addListener(handleStorageChange);
|
browser.storage.onChanged.addListener(handleStorageChange);
|
||||||
storageListeners.add(handleStorageChange);
|
|
||||||
|
const dispose = () => {
|
||||||
|
browser.storage.onChanged.removeListener(handleStorageChange);
|
||||||
|
};
|
||||||
|
|
||||||
// Create the proxy for direct property access
|
// Create the proxy for direct property access
|
||||||
return new Proxy(cache, {
|
const storage = new Proxy(cache, {
|
||||||
get(target, prop: string) {
|
get(target, prop: string) {
|
||||||
if (prop === "onChange") {
|
if (prop === "onChange") {
|
||||||
return (key: keyof T, callback: (value: T[keyof T]) => void) => {
|
return (key: keyof T, callback: (value: T[keyof T]) => void) => {
|
||||||
@@ -288,6 +309,8 @@ function createStorageAPI<T = any>(
|
|||||||
return true;
|
return true;
|
||||||
},
|
},
|
||||||
}) as StorageAPI<T> & { [K in keyof T]: T[K] };
|
}) as StorageAPI<T> & { [K in keyof T]: T[K] };
|
||||||
|
|
||||||
|
return { storage, dispose };
|
||||||
}
|
}
|
||||||
|
|
||||||
function createEventsAPI(pluginId: string): EventsAPI {
|
function createEventsAPI(pluginId: string): EventsAPI {
|
||||||
@@ -357,10 +380,17 @@ function createEventsAPI(pluginId: string): EventsAPI {
|
|||||||
export function createPluginAPI<T extends PluginSettings, S = any>(
|
export function createPluginAPI<T extends PluginSettings, S = any>(
|
||||||
plugin: Plugin<T, S>,
|
plugin: Plugin<T, S>,
|
||||||
): PluginAPI<T, S> {
|
): PluginAPI<T, S> {
|
||||||
|
const { settings, dispose: disposeSettings } = createSettingsAPI(plugin);
|
||||||
|
const { storage, dispose: disposeStorage } = createStorageAPI<S>(plugin.id);
|
||||||
|
|
||||||
return {
|
return {
|
||||||
seqta: createSEQTAAPI(),
|
seqta: createSEQTAAPI(),
|
||||||
settings: createSettingsAPI(plugin),
|
settings,
|
||||||
storage: createStorageAPI<S>(plugin.id),
|
storage,
|
||||||
events: createEventsAPI(plugin.id),
|
events: createEventsAPI(plugin.id),
|
||||||
|
dispose: () => {
|
||||||
|
disposeSettings();
|
||||||
|
disposeStorage();
|
||||||
|
},
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -35,6 +35,7 @@ export class PluginManager {
|
|||||||
private runningPlugins: Map<string, boolean> = new Map();
|
private runningPlugins: Map<string, boolean> = new Map();
|
||||||
private eventBacklog: Map<string, any[]> = new Map();
|
private eventBacklog: Map<string, any[]> = new Map();
|
||||||
private cleanupFunctions: Map<string, () => void> = 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 listeners: Map<string, Set<(...args: any[]) => void>> = new Map();
|
||||||
private styleElements: Map<string, HTMLStyleElement> = new Map();
|
private styleElements: Map<string, HTMLStyleElement> = new Map();
|
||||||
|
|
||||||
@@ -148,6 +149,7 @@ export class PluginManager {
|
|||||||
|
|
||||||
try {
|
try {
|
||||||
const api = createPluginAPI(plugin);
|
const api = createPluginAPI(plugin);
|
||||||
|
this.apiDisposers.set(pluginId, api.dispose);
|
||||||
|
|
||||||
// Check if plugin is enabled before starting
|
// Check if plugin is enabled before starting
|
||||||
if (plugin.disableToggle) {
|
if (plugin.disableToggle) {
|
||||||
@@ -158,6 +160,7 @@ export class PluginManager {
|
|||||||
const enabled =
|
const enabled =
|
||||||
pluginSettings?.enabled ?? plugin.defaultEnabled ?? true;
|
pluginSettings?.enabled ?? plugin.defaultEnabled ?? true;
|
||||||
if (!enabled) {
|
if (!enabled) {
|
||||||
|
this.disposePluginAPI(pluginId);
|
||||||
console.info(
|
console.info(
|
||||||
`Plugin "${pluginId}" is disabled, skipping initialization`,
|
`Plugin "${pluginId}" is disabled, skipping initialization`,
|
||||||
);
|
);
|
||||||
@@ -186,6 +189,8 @@ export class PluginManager {
|
|||||||
// Process any backlogged events
|
// Process any backlogged events
|
||||||
await this.processBackloggedEvents(pluginId);
|
await this.processBackloggedEvents(pluginId);
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
|
this.removePluginStyles(pluginId);
|
||||||
|
this.disposePluginAPI(pluginId);
|
||||||
console.error(
|
console.error(
|
||||||
`[BetterSEQTA+] Failed to start plugin ${pluginId}:`,
|
`[BetterSEQTA+] Failed to start plugin ${pluginId}:`,
|
||||||
error,
|
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.
|
* Attempts to start all registered plugins.
|
||||||
* Errors during the start of individual plugins are caught and logged,
|
* 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.
|
* @returns {Promise<void>} A promise that resolves when the plugin has been stopped.
|
||||||
*/
|
*/
|
||||||
public async stopPlugin(pluginId: string): Promise<void> {
|
public async stopPlugin(pluginId: string): Promise<void> {
|
||||||
// Remove plugin styles
|
this.removePluginStyles(pluginId);
|
||||||
const styleElement = this.styleElements.get(pluginId);
|
this.disposePluginAPI(pluginId);
|
||||||
if (styleElement) {
|
|
||||||
styleElement.remove();
|
|
||||||
this.styleElements.delete(pluginId);
|
|
||||||
}
|
|
||||||
|
|
||||||
const cleanup = this.cleanupFunctions.get(pluginId);
|
const cleanup = this.cleanupFunctions.get(pluginId);
|
||||||
if (cleanup) {
|
if (cleanup) {
|
||||||
|
|||||||
@@ -141,6 +141,7 @@ export interface PluginAPI<T extends PluginSettings, S = any> {
|
|||||||
settings: SettingsAPI<T>;
|
settings: SettingsAPI<T>;
|
||||||
storage: TypedStorageAPI<S>;
|
storage: TypedStorageAPI<S>;
|
||||||
events: EventsAPI;
|
events: EventsAPI;
|
||||||
|
dispose: () => void;
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface Plugin<T extends PluginSettings = PluginSettings, S = any> {
|
export interface Plugin<T extends PluginSettings = PluginSettings, S = any> {
|
||||||
|
|||||||
@@ -16,6 +16,24 @@ import { updateAllColors } from "./colors/Manager";
|
|||||||
import { delay } from "@/seqta/utils/delay";
|
import { delay } from "@/seqta/utils/delay";
|
||||||
|
|
||||||
let cachedUserInfo: any = null;
|
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 LightDarkModeSnakeEggButton = 0;
|
||||||
let sidebarAccessibilityObserver: MutationObserver | null = null;
|
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). */
|
/** Marks menu rows that are off-screen in the drill stack (CSS blocks clicks). */
|
||||||
const BSPLUS_SIDEBAR_OFFSCREEN = "bsplus-sidebar-offscreen";
|
const BSPLUS_SIDEBAR_OFFSCREEN = "bsplus-sidebar-offscreen";
|
||||||
|
|
||||||
export async function getUserInfo() {
|
export async function getUserInfo(options?: { validateSession?: boolean }) {
|
||||||
if (cachedUserInfo) return cachedUserInfo;
|
if (cachedUserInfo && !options?.validateSession) {
|
||||||
|
return cachedUserInfo;
|
||||||
|
}
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const response = await fetch(`${location.origin}/seqta/student/login`, {
|
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;
|
return cachedUserInfo;
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error("[BetterSEQTA+] Failed to get user info:", error);
|
console.error("[BetterSEQTA+] Failed to get user info:", error);
|
||||||
|
|||||||
@@ -21,6 +21,7 @@ export async function appendBackgroundToUI() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
let lastLoadedId: string | null = null;
|
let lastLoadedId: string | null = null;
|
||||||
|
let lastBlobUrl: string | null = null;
|
||||||
|
|
||||||
export async function loadBackground() {
|
export async function loadBackground() {
|
||||||
if (!isIndexedDBSupported()) {
|
if (!isIndexedDBSupported()) {
|
||||||
@@ -36,6 +37,10 @@ export async function loadBackground() {
|
|||||||
backgroundContainer.remove();
|
backgroundContainer.remove();
|
||||||
}
|
}
|
||||||
lastLoadedId = null;
|
lastLoadedId = null;
|
||||||
|
if (lastBlobUrl) {
|
||||||
|
URL.revokeObjectURL(lastBlobUrl);
|
||||||
|
lastBlobUrl = null;
|
||||||
|
}
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -73,12 +78,19 @@ export async function loadBackground() {
|
|||||||
|
|
||||||
mediaContainer.innerHTML = "";
|
mediaContainer.innerHTML = "";
|
||||||
|
|
||||||
|
if (lastBlobUrl) {
|
||||||
|
URL.revokeObjectURL(lastBlobUrl);
|
||||||
|
lastBlobUrl = null;
|
||||||
|
}
|
||||||
|
|
||||||
const mediaElement =
|
const mediaElement =
|
||||||
background.type === "video"
|
background.type === "video"
|
||||||
? document.createElement("video")
|
? document.createElement("video")
|
||||||
: document.createElement("img");
|
: document.createElement("img");
|
||||||
|
|
||||||
mediaElement.src = URL.createObjectURL(background.blob);
|
const blobUrl = URL.createObjectURL(background.blob);
|
||||||
|
lastBlobUrl = blobUrl;
|
||||||
|
mediaElement.src = blobUrl;
|
||||||
mediaElement.classList.add("background");
|
mediaElement.classList.add("background");
|
||||||
|
|
||||||
if (mediaElement instanceof HTMLVideoElement) {
|
if (mediaElement instanceof HTMLVideoElement) {
|
||||||
|
|||||||
@@ -1,7 +1,6 @@
|
|||||||
import browser from "webextension-polyfill";
|
import browser from "webextension-polyfill";
|
||||||
import { clearCloudPfpCache } from "@/seqta/utils/cloudPfpCache";
|
import { clearCloudPfpCache } from "@/seqta/utils/cloudPfpCache";
|
||||||
import { clearLastUploadedSnapshot } from "@/seqta/utils/cloudSettingsSync";
|
import { clearLastUploadedSnapshot } from "@/seqta/utils/cloudSettingsSync";
|
||||||
import { settingsState } from "@/seqta/utils/listeners/SettingsState";
|
|
||||||
|
|
||||||
const REDIRECT_URI = "https://accounts.betterseqta.org/auth/bsplus/callback";
|
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”). */
|
/** 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
|
void browser.runtime
|
||||||
.sendMessage({
|
.sendMessage({
|
||||||
type: "cloudSettingsDownload",
|
type: "cloudSettingsDownload",
|
||||||
token: accessToken,
|
|
||||||
})
|
})
|
||||||
.then((res: unknown) => {
|
.then((res: unknown) => {
|
||||||
const r = res as { success?: boolean; notFound?: boolean; error?: string } | undefined;
|
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). */
|
/** Persist an updated user object (e.g. after cloud profile picture sync). */
|
||||||
public async setUser(user: CloudUser | null): Promise<void> {
|
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 });
|
await browser.storage.local.set({ [STORAGE_KEYS.user]: user });
|
||||||
this._state = {
|
this._state = {
|
||||||
isLoggedIn: this._state.isLoggedIn,
|
isLoggedIn: this._state.isLoggedIn,
|
||||||
@@ -122,11 +119,8 @@ class CloudAuthService {
|
|||||||
}
|
}
|
||||||
|
|
||||||
private async getClientId(): Promise<string> {
|
private async getClientId(): Promise<string> {
|
||||||
let clientId = (settingsState as any)[STORAGE_KEYS.clientId] as string | undefined;
|
const stored = await browser.storage.local.get(STORAGE_KEYS.clientId);
|
||||||
if (!clientId) {
|
let clientId = stored[STORAGE_KEYS.clientId] as string | undefined;
|
||||||
const stored = await browser.storage.local.get(STORAGE_KEYS.clientId);
|
|
||||||
clientId = stored[STORAGE_KEYS.clientId] as string | undefined;
|
|
||||||
}
|
|
||||||
if (!clientId) {
|
if (!clientId) {
|
||||||
const reserveResult = (await browser.runtime.sendMessage({
|
const reserveResult = (await browser.runtime.sendMessage({
|
||||||
type: "cloudReserveClient",
|
type: "cloudReserveClient",
|
||||||
@@ -136,7 +130,7 @@ class CloudAuthService {
|
|||||||
throw new Error(reserveResult?.error ?? "Failed to reserve client");
|
throw new Error(reserveResult?.error ?? "Failed to reserve client");
|
||||||
}
|
}
|
||||||
clientId = reserveResult.client_id;
|
clientId = reserveResult.client_id;
|
||||||
(settingsState as any).setKey(STORAGE_KEYS.clientId, clientId);
|
await browser.storage.local.set({ [STORAGE_KEYS.clientId]: clientId });
|
||||||
}
|
}
|
||||||
return clientId;
|
return clientId;
|
||||||
}
|
}
|
||||||
@@ -180,15 +174,17 @@ class CloudAuthService {
|
|||||||
error?: string;
|
error?: string;
|
||||||
};
|
};
|
||||||
if (result?.access_token && result?.refresh_token) {
|
if (result?.access_token && result?.refresh_token) {
|
||||||
(settingsState as any).setKey(STORAGE_KEYS.accessToken, result.access_token);
|
await browser.storage.local.set({
|
||||||
(settingsState as any).setKey(STORAGE_KEYS.refreshToken, result.refresh_token);
|
[STORAGE_KEYS.accessToken]: result.access_token,
|
||||||
(settingsState as any).setKey(STORAGE_KEYS.user, result.user ?? null);
|
[STORAGE_KEYS.refreshToken]: result.refresh_token,
|
||||||
|
[STORAGE_KEYS.user]: result.user ?? null,
|
||||||
|
});
|
||||||
this._state = {
|
this._state = {
|
||||||
isLoggedIn: true,
|
isLoggedIn: true,
|
||||||
user: result.user ?? null,
|
user: result.user ?? null,
|
||||||
};
|
};
|
||||||
this.notify();
|
this.notify();
|
||||||
this.triggerCloudSettingsDownloadAfterLogin(result.access_token);
|
this.triggerCloudSettingsDownloadAfterLogin();
|
||||||
return { success: true };
|
return { success: true };
|
||||||
}
|
}
|
||||||
return {
|
return {
|
||||||
@@ -239,9 +235,11 @@ class CloudAuthService {
|
|||||||
};
|
};
|
||||||
|
|
||||||
if (refreshResult?.access_token && refreshResult?.refresh_token) {
|
if (refreshResult?.access_token && refreshResult?.refresh_token) {
|
||||||
(settingsState as any).setKey(STORAGE_KEYS.accessToken, refreshResult.access_token);
|
await browser.storage.local.set({
|
||||||
(settingsState as any).setKey(STORAGE_KEYS.refreshToken, refreshResult.refresh_token);
|
[STORAGE_KEYS.accessToken]: refreshResult.access_token,
|
||||||
(settingsState as any).setKey(STORAGE_KEYS.user, refreshResult.user ?? null);
|
[STORAGE_KEYS.refreshToken]: refreshResult.refresh_token,
|
||||||
|
[STORAGE_KEYS.user]: refreshResult.user ?? null,
|
||||||
|
});
|
||||||
this._state = {
|
this._state = {
|
||||||
isLoggedIn: true,
|
isLoggedIn: true,
|
||||||
user: refreshResult.user ?? null,
|
user: refreshResult.user ?? null,
|
||||||
|
|||||||
@@ -1,13 +1,28 @@
|
|||||||
import stringToHTML from "../stringToHTML";
|
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) {
|
export function CreateCustomShortcutDiv(element: any) {
|
||||||
// Creates the stucture and element information for each seperate shortcut
|
// Creates the stucture and element information for each seperate shortcut
|
||||||
const container = document.getElementById("shortcuts");
|
const container = document.getElementById("shortcuts");
|
||||||
if (!container) return;
|
if (!container) return;
|
||||||
|
|
||||||
var shortcut = document.createElement("a");
|
var shortcut = document.createElement("a");
|
||||||
shortcut.setAttribute("href", element.url);
|
if (isSafeShortcutHref(element.url)) {
|
||||||
shortcut.setAttribute("target", "_blank");
|
shortcut.setAttribute("href", element.url);
|
||||||
|
shortcut.setAttribute("target", "_blank");
|
||||||
|
} else {
|
||||||
|
shortcut.setAttribute("href", "#");
|
||||||
|
shortcut.setAttribute("aria-disabled", "true");
|
||||||
|
}
|
||||||
var shortcutdiv = document.createElement("div");
|
var shortcutdiv = document.createElement("div");
|
||||||
shortcutdiv.classList.add("shortcut");
|
shortcutdiv.classList.add("shortcut");
|
||||||
shortcutdiv.classList.add("customshortcut");
|
shortcutdiv.classList.add("customshortcut");
|
||||||
|
|||||||
@@ -52,6 +52,7 @@ export function OpenAboutPage() {
|
|||||||
</a>
|
</a>
|
||||||
<a class="socials" href="https://www.youtube.com/@BetterSEQTAPlus" style="background: none !important; margin: 0 5px; padding: 0; display: flex; align-items: center;">
|
<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>
|
<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;">
|
<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">
|
<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" />
|
<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>
|
</div>
|
||||||
`).firstChild as HTMLElement;
|
`).firstChild as HTMLElement;
|
||||||
|
|
||||||
settingsState.bsCloudAutoSyncAnnouncementShown = true;
|
|
||||||
|
|
||||||
openPopup({
|
openPopup({
|
||||||
header,
|
header,
|
||||||
content: [imageContainer, text],
|
content: [imageContainer, text],
|
||||||
afterClose: onDismissed,
|
afterClose: () => {
|
||||||
|
settingsState.bsCloudAutoSyncAnnouncementShown = true;
|
||||||
|
onDismissed?.();
|
||||||
|
},
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -5,7 +5,18 @@ import Sortable from "sortablejs";
|
|||||||
|
|
||||||
export let MenuOptionsOpen = false;
|
export let MenuOptionsOpen = false;
|
||||||
|
|
||||||
|
function escapeHtmlAttr(value: string): string {
|
||||||
|
return value
|
||||||
|
.replace(/&/g, "&")
|
||||||
|
.replace(/"/g, """)
|
||||||
|
.replace(/'/g, "'")
|
||||||
|
.replace(/</g, "<")
|
||||||
|
.replace(/>/g, ">");
|
||||||
|
}
|
||||||
|
|
||||||
export function OpenMenuOptions() {
|
export function OpenMenuOptions() {
|
||||||
|
if (MenuOptionsOpen) return;
|
||||||
|
|
||||||
var container = document.getElementById("container");
|
var container = document.getElementById("container");
|
||||||
var menu = document.getElementById("menu");
|
var menu = document.getElementById("menu");
|
||||||
|
|
||||||
@@ -23,9 +34,9 @@ export function OpenMenuOptions() {
|
|||||||
for (let i = 0; i < childnodes.length; i++) {
|
for (let i = 0; i < childnodes.length; i++) {
|
||||||
const element = childnodes[i];
|
const element = childnodes[i];
|
||||||
if (
|
if (
|
||||||
!settingsState.defaultmenuorder.indexOf(
|
settingsState.defaultmenuorder.indexOf(
|
||||||
(element as HTMLElement).dataset.key,
|
(element as HTMLElement).dataset.key,
|
||||||
)
|
) === -1
|
||||||
) {
|
) {
|
||||||
let newdefaultmenuorder = settingsState.defaultmenuorder;
|
let newdefaultmenuorder = settingsState.defaultmenuorder;
|
||||||
newdefaultmenuorder.push((element as HTMLElement).dataset.key);
|
newdefaultmenuorder.push((element as HTMLElement).dataset.key);
|
||||||
@@ -53,7 +64,7 @@ export function OpenMenuOptions() {
|
|||||||
var savebutton = document.createElement("div");
|
var savebutton = document.createElement("div");
|
||||||
savebutton.classList.add("editmenuoption");
|
savebutton.classList.add("editmenuoption");
|
||||||
savebutton.innerText = "Save";
|
savebutton.innerText = "Save";
|
||||||
savebutton.id = "restoredefaultoption";
|
savebutton.id = "savemenuoption";
|
||||||
|
|
||||||
menusettings.appendChild(defaultbutton);
|
menusettings.appendChild(defaultbutton);
|
||||||
menusettings.appendChild(savebutton);
|
menusettings.appendChild(savebutton);
|
||||||
@@ -71,15 +82,18 @@ export function OpenMenuOptions() {
|
|||||||
(element.firstChild as HTMLElement).classList.remove("noscroll");
|
(element.firstChild as HTMLElement).classList.remove("noscroll");
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const menuKey = escapeHtmlAttr((element as HTMLElement).dataset.key ?? "");
|
||||||
let MenuItemToggle = stringToHTML(
|
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;
|
).firstChild;
|
||||||
(element as HTMLElement).append(MenuItemToggle!);
|
(element as HTMLElement).append(MenuItemToggle!);
|
||||||
|
|
||||||
if (!element.dataset.betterseqta) {
|
if (!element.dataset.betterseqta) {
|
||||||
const a = document.createElement("section");
|
const a = document.createElement("section");
|
||||||
a.innerHTML = element.innerHTML;
|
|
||||||
cloneAttributes(a, element);
|
cloneAttributes(a, element);
|
||||||
|
while (element.firstChild) {
|
||||||
|
a.appendChild(element.firstChild);
|
||||||
|
}
|
||||||
menu!.firstChild!.insertBefore(a, element);
|
menu!.firstChild!.insertBefore(a, element);
|
||||||
element.remove();
|
element.remove();
|
||||||
}
|
}
|
||||||
@@ -109,12 +123,12 @@ export function OpenMenuOptions() {
|
|||||||
} else {
|
} else {
|
||||||
(buttons[i] as HTMLInputElement).checked = true;
|
(buttons[i] as HTMLInputElement).checked = true;
|
||||||
}
|
}
|
||||||
(buttons[i] as HTMLInputElement).checked = true;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
let sortable: Sortable | undefined;
|
||||||
try {
|
try {
|
||||||
var el = document.querySelector("#menu > ul");
|
var el = document.querySelector("#menu > ul");
|
||||||
var sortable = Sortable.create(el as HTMLElement, {
|
sortable = Sortable.create(el as HTMLElement, {
|
||||||
draggable: ".draggable",
|
draggable: ".draggable",
|
||||||
dataIdAttr: "data-key",
|
dataIdAttr: "data-key",
|
||||||
animation: 150,
|
animation: 150,
|
||||||
@@ -178,8 +192,10 @@ export function OpenMenuOptions() {
|
|||||||
|
|
||||||
if (!element.dataset.betterseqta) {
|
if (!element.dataset.betterseqta) {
|
||||||
const a = document.createElement("li");
|
const a = document.createElement("li");
|
||||||
a.innerHTML = element.innerHTML;
|
|
||||||
cloneAttributes(a, element);
|
cloneAttributes(a, element);
|
||||||
|
while (element.firstChild) {
|
||||||
|
a.appendChild(element.firstChild);
|
||||||
|
}
|
||||||
menu!.firstChild!.insertBefore(a, element);
|
menu!.firstChild!.insertBefore(a, element);
|
||||||
element.remove();
|
element.remove();
|
||||||
}
|
}
|
||||||
@@ -209,7 +225,7 @@ export function OpenMenuOptions() {
|
|||||||
"important",
|
"important",
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
saveNewOrder(sortable);
|
if (sortable) saveNewOrder(sortable);
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -105,6 +105,7 @@ export function OpenMinecraftServerPopup() {
|
|||||||
</a>
|
</a>
|
||||||
<a class="socials" href="https://www.youtube.com/@BetterSEQTAPlus" style="background: none !important; margin: 0 5px; padding: 0; display: flex; align-items: center;">
|
<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>
|
<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;">
|
<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">
|
<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" />
|
<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");
|
attachPopupMediaFullscreenIfPresent(text, "img.aboutImg");
|
||||||
|
|
||||||
settingsState.privacyStatementLastUpdated = "2025-12-20";
|
|
||||||
settingsState.privacyStatementShown = true;
|
|
||||||
|
|
||||||
openPopup({
|
openPopup({
|
||||||
header,
|
header,
|
||||||
content: [text],
|
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>
|
<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>
|
<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>
|
<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>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>
|
</div>
|
||||||
`).firstChild as HTMLElement;
|
`).firstChild as HTMLElement;
|
||||||
|
|
||||||
|
|||||||
@@ -4,13 +4,13 @@ import { settingsState } from "../listeners/SettingsState";
|
|||||||
import { closePopup } from "./PopupManager";
|
import { closePopup } from "./PopupManager";
|
||||||
import { getApiBase } from "../DevApiBase";
|
import { getApiBase } from "../DevApiBase";
|
||||||
import { openThemeStoreWithHighlight } from "../openThemeStoreWithHighlight";
|
import { openThemeStoreWithHighlight } from "../openThemeStoreWithHighlight";
|
||||||
import { cloudAuth } from "../CloudAuth";
|
|
||||||
import type { Theme } from "@/interface/types/Theme";
|
import type { Theme } from "@/interface/types/Theme";
|
||||||
import {
|
import {
|
||||||
buildModalHeroSlides,
|
buildModalHeroSlides,
|
||||||
normalizeStoreTheme,
|
normalizeStoreTheme,
|
||||||
} from "@/interface/utils/themeStoreFlavours";
|
} from "@/interface/utils/themeStoreFlavours";
|
||||||
import { attachPopupMediaFullscreen } from "./attachPopupMediaFullscreen";
|
import { attachPopupMediaFullscreen } from "./attachPopupMediaFullscreen";
|
||||||
|
import { allowedPopupImageUrl } from "./allowedPopupImageUrl";
|
||||||
|
|
||||||
export interface ThemeOfTheMonthEntry {
|
export interface ThemeOfTheMonthEntry {
|
||||||
id: string;
|
id: string;
|
||||||
@@ -67,17 +67,15 @@ function heroUrlFromStoreTheme(theme: {
|
|||||||
coverImage?: string | null;
|
coverImage?: string | null;
|
||||||
}): string | null {
|
}): string | null {
|
||||||
const url = (theme.marqueeImage || theme.coverImage || "").trim();
|
const url = (theme.marqueeImage || theme.coverImage || "").trim();
|
||||||
return url || null;
|
return allowedPopupImageUrl(url);
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function fetchThemeStoreTheme(themeId: string): Promise<Theme | null> {
|
export async function fetchThemeStoreTheme(themeId: string): Promise<Theme | null> {
|
||||||
try {
|
try {
|
||||||
const token = await cloudAuth.getStoredToken();
|
const res = (await browser.runtime.sendMessage({
|
||||||
const res = (await browser.runtime.sendMessage({
|
type: "fetchThemeDetails",
|
||||||
type: "fetchThemeDetails",
|
themeId,
|
||||||
themeId,
|
})) as { success?: boolean; data?: { theme?: Record<string, unknown> } };
|
||||||
token: token ?? undefined,
|
|
||||||
})) as { success?: boolean; data?: { theme?: Record<string, unknown> } };
|
|
||||||
|
|
||||||
if (!res?.success || !res?.data?.theme) return null;
|
if (!res?.success || !res?.data?.theme) return null;
|
||||||
return normalizeStoreTheme(res.data.theme);
|
return normalizeStoreTheme(res.data.theme);
|
||||||
@@ -100,7 +98,12 @@ function buildPopupGallerySlides(
|
|||||||
heroUrl: string | null,
|
heroUrl: string | null,
|
||||||
): PopupGallerySlide[] {
|
): PopupGallerySlide[] {
|
||||||
if (storeTheme) {
|
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) {
|
if (heroUrl) {
|
||||||
return [{ imageUrl: heroUrl, caption: entry.title }];
|
return [{ imageUrl: heroUrl, caption: entry.title }];
|
||||||
@@ -642,7 +645,7 @@ export async function OpenThemeOfTheMonthPopup(
|
|||||||
const storeTheme = linkedThemeId ? await fetchThemeStoreTheme(linkedThemeId) : null;
|
const storeTheme = linkedThemeId ? await fetchThemeStoreTheme(linkedThemeId) : null;
|
||||||
const heroUrl =
|
const heroUrl =
|
||||||
(storeTheme ? heroUrlFromStoreTheme(storeTheme) : null) ??
|
(storeTheme ? heroUrlFromStoreTheme(storeTheme) : null) ??
|
||||||
entry.cover_image?.trim() ??
|
allowedPopupImageUrl(entry.cover_image) ??
|
||||||
null;
|
null;
|
||||||
const gallerySlides = buildPopupGallerySlides(entry, storeTheme, heroUrl);
|
const gallerySlides = buildPopupGallerySlides(entry, storeTheme, heroUrl);
|
||||||
const hasExpandableContent = gallerySlides.length > 0 || entry.description.trim().length > 0;
|
const hasExpandableContent = gallerySlides.length > 0 || entry.description.trim().length > 0;
|
||||||
|
|||||||
@@ -396,6 +396,7 @@ export function OpenWhatsNewPopup(onDismissed?: () => void) {
|
|||||||
</a>
|
</a>
|
||||||
<a class="socials" href="https://www.youtube.com/@BetterSEQTAPlus" style="background: none !important; margin: 0 5px; padding: 0; display: flex; align-items: center;">
|
<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>
|
<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;">
|
<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">
|
<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" />
|
<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>
|
</a>
|
||||||
</div>
|
</div>
|
||||||
<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" />
|
<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>
|
</a>
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@@ -57,6 +57,15 @@ interface OpenPopupOptions {
|
|||||||
containerClass?: string;
|
containerClass?: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function chainAfterClose(next?: () => void) {
|
||||||
|
if (!next) return;
|
||||||
|
const previous = pendingAfterClose;
|
||||||
|
pendingAfterClose = () => {
|
||||||
|
next();
|
||||||
|
previous?.();
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
export function openPopup({
|
export function openPopup({
|
||||||
header,
|
header,
|
||||||
content = [],
|
content = [],
|
||||||
@@ -65,7 +74,12 @@ export function openPopup({
|
|||||||
clearJustUpdated = false,
|
clearJustUpdated = false,
|
||||||
containerClass,
|
containerClass,
|
||||||
}: OpenPopupOptions = {}) {
|
}: OpenPopupOptions = {}) {
|
||||||
pendingAfterClose = afterClose;
|
if (document.getElementById("whatsnewbk")) {
|
||||||
|
chainAfterClose(afterClose);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
chainAfterClose(afterClose);
|
||||||
|
|
||||||
const background = document.createElement("div");
|
const background = document.createElement("div");
|
||||||
background.id = "whatsnewbk";
|
background.id = "whatsnewbk";
|
||||||
@@ -87,7 +101,9 @@ export function openPopup({
|
|||||||
container.append(closeButton);
|
container.append(closeButton);
|
||||||
|
|
||||||
background.append(container);
|
background.append(container);
|
||||||
document.getElementById("container")!.append(background);
|
const appContainer = document.getElementById("container");
|
||||||
|
if (!appContainer) return;
|
||||||
|
appContainer.append(background);
|
||||||
|
|
||||||
if (settingsState.animations) {
|
if (settingsState.animations) {
|
||||||
(motionAnimate as any)(
|
(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 { settingsState } from "../listeners/SettingsState";
|
||||||
|
import { allowedPopupImageUrl } from "./allowedPopupImageUrl";
|
||||||
|
|
||||||
const FULLSCREENABLE_CLASS = "popup-media-fullscreenable";
|
const FULLSCREENABLE_CLASS = "popup-media-fullscreenable";
|
||||||
const OVERLAY_VISIBLE_CLASS = "bsplus-popup-media-overlay-backdrop--visible";
|
const OVERLAY_VISIBLE_CLASS = "bsplus-popup-media-overlay-backdrop--visible";
|
||||||
@@ -56,13 +57,22 @@ function openMediaOverlayViewer(source: HTMLImageElement | HTMLVideoElement) {
|
|||||||
nv.loop = v.loop;
|
nv.loop = v.loop;
|
||||||
nv.muted = v.muted;
|
nv.muted = v.muted;
|
||||||
nv.volume = v.volume;
|
nv.volume = v.volume;
|
||||||
|
let hasValidSource = false;
|
||||||
for (const s of v.querySelectorAll("source")) {
|
for (const s of v.querySelectorAll("source")) {
|
||||||
|
const src = allowedPopupImageUrl((s as HTMLSourceElement).src);
|
||||||
|
if (!src) continue;
|
||||||
|
hasValidSource = true;
|
||||||
const ns = document.createElement("source");
|
const ns = document.createElement("source");
|
||||||
ns.src = (s as HTMLSourceElement).src;
|
ns.src = src;
|
||||||
const t = (s as HTMLSourceElement).type;
|
const t = (s as HTMLSourceElement).type;
|
||||||
if (t) ns.type = t;
|
if (t) ns.type = t;
|
||||||
nv.appendChild(ns);
|
nv.appendChild(ns);
|
||||||
}
|
}
|
||||||
|
if (!hasValidSource) {
|
||||||
|
const directSrc = allowedPopupImageUrl(v.currentSrc || v.src);
|
||||||
|
if (!directSrc) return;
|
||||||
|
nv.src = directSrc;
|
||||||
|
}
|
||||||
nv.addEventListener(
|
nv.addEventListener(
|
||||||
"loadeddata",
|
"loadeddata",
|
||||||
() => {
|
() => {
|
||||||
@@ -79,9 +89,12 @@ function openMediaOverlayViewer(source: HTMLImageElement | HTMLVideoElement) {
|
|||||||
nv.load();
|
nv.load();
|
||||||
media = nv;
|
media = nv;
|
||||||
} else {
|
} else {
|
||||||
|
const rawSrc = source.currentSrc || source.src;
|
||||||
|
const safeSrc = allowedPopupImageUrl(rawSrc);
|
||||||
|
if (!safeSrc) return;
|
||||||
const img = document.createElement("img");
|
const img = document.createElement("img");
|
||||||
img.classList.add("bsplus-popup-media-overlay-media");
|
img.classList.add("bsplus-popup-media-overlay-media");
|
||||||
img.src = source.currentSrc || source.src;
|
img.src = safeSrc;
|
||||||
img.alt = source.alt || "";
|
img.alt = source.alt || "";
|
||||||
media = img;
|
media = img;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -22,6 +22,16 @@ class ReactFiber {
|
|||||||
return new ReactFiber(selector, options);
|
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> {
|
private async sendMessage(action: string, payload: any = {}): Promise<any> {
|
||||||
return new Promise((resolve, _) => {
|
return new Promise((resolve, _) => {
|
||||||
const messageId = this.messageIdCounter++;
|
const messageId = this.messageIdCounter++;
|
||||||
@@ -34,7 +44,8 @@ class ReactFiber {
|
|||||||
messageId,
|
messageId,
|
||||||
};
|
};
|
||||||
|
|
||||||
const listener = (response: any) => {
|
const listener = (response: MessageEvent) => {
|
||||||
|
if (!this.isTrustedMessage(response)) return;
|
||||||
if (
|
if (
|
||||||
response.data?.type === "reactFiberResponse" &&
|
response.data?.type === "reactFiberResponse" &&
|
||||||
response.data?.messageId === messageId
|
response.data?.messageId === messageId
|
||||||
@@ -47,7 +58,7 @@ class ReactFiber {
|
|||||||
}
|
}
|
||||||
};
|
};
|
||||||
window.addEventListener("message", listener);
|
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> {
|
async setState(update: Record<string, unknown>): Promise<ReactFiber> {
|
||||||
const updateFnString =
|
if (typeof update !== "object" || update === null || Array.isArray(update)) {
|
||||||
typeof update === "function" ? update.toString() : null;
|
throw new TypeError(
|
||||||
const updateObject = typeof update !== "function" ? update : null;
|
"ReactFiber.setState only accepts plain JSON-serializable objects",
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
await this.sendMessage("setState", {
|
await this.sendMessage("setState", { updateObject: update });
|
||||||
updateFn: updateFnString,
|
|
||||||
updateObject,
|
|
||||||
});
|
|
||||||
return this;
|
return this;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -100,7 +100,7 @@ export async function SendNewsPage() {
|
|||||||
? article.description
|
? article.description
|
||||||
: "No description available.";
|
: "No description available.";
|
||||||
|
|
||||||
description.innerHTML =
|
description.textContent =
|
||||||
articleDescription.length > 400
|
articleDescription.length > 400
|
||||||
? articleDescription.substring(0, 400) + "..."
|
? articleDescription.substring(0, 400) + "..."
|
||||||
: articleDescription;
|
: 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,
|
...KEYS_OMITTED_FROM_CLOUD_UPLOAD,
|
||||||
...SENSITIVE_DEVICE_STORAGE_KEYS_EXACT,
|
...SENSITIVE_DEVICE_STORAGE_KEYS_EXACT,
|
||||||
...CLIENT_ONLY_CLOUD_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). */
|
/** True if a storage key is part of the upload payload (and should trigger auto-upload when changed). */
|
||||||
export function isKeyIncludedInCloudUploadPayload(key: string): boolean {
|
export function isKeyIncludedInCloudUploadPayload(key: string): boolean {
|
||||||
return !shouldOmitKeyFromCloudPayload(key);
|
return !shouldOmitKeyFromCloudPayload(key);
|
||||||
}
|
}
|
||||||
|
|
||||||
function shouldOmitKeyFromCloudPayload(key: string): boolean {
|
function shouldOmitKeyFromCloudPayload(key: string): boolean {
|
||||||
|
if (isUnsafeStorageKey(key)) return true;
|
||||||
if (OMIT_FROM_UPLOAD_EXACT.has(key)) return true;
|
if (OMIT_FROM_UPLOAD_EXACT.has(key)) return true;
|
||||||
for (const prefix of SENSITIVE_DEVICE_STORAGE_KEY_PREFIXES) {
|
for (const prefix of SENSITIVE_DEVICE_STORAGE_KEY_PREFIXES) {
|
||||||
if (key.startsWith(prefix)) return true;
|
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> {
|
function stripExcludedKeysFromRemoteData(remote: Record<string, unknown>): Record<string, unknown> {
|
||||||
const out: Record<string, unknown> = {};
|
const out: Record<string, unknown> = {};
|
||||||
for (const [k, v] of Object.entries(remote)) {
|
for (const [k, v] of Object.entries(remote)) {
|
||||||
|
if (isUnsafeStorageKey(k)) continue;
|
||||||
if (shouldOmitKeyFromCloudPayload(k)) continue;
|
if (shouldOmitKeyFromCloudPayload(k)) continue;
|
||||||
out[k] = v;
|
out[k] = v;
|
||||||
}
|
}
|
||||||
@@ -336,5 +346,7 @@ export async function applyDownloadedEnvelope(envelope: unknown): Promise<void>
|
|||||||
|
|
||||||
const migrated = migrateLegacyToPluginSettings(remoteFlat);
|
const migrated = migrateLegacyToPluginSettings(remoteFlat);
|
||||||
const remoteSanitized = stripExcludedKeysFromRemoteData(migrated);
|
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),
|
(item: any) => item.notificationID === parseInt(buttonId),
|
||||||
);
|
);
|
||||||
|
|
||||||
|
if (!matchingNotification?.message?.messageID) return;
|
||||||
|
|
||||||
await waitForElm('[class*="Viewer__Viewer___"] > div', true, 20);
|
await waitForElm('[class*="Viewer__Viewer___"] > div', true, 20);
|
||||||
|
|
||||||
// Select the specific direct message
|
// Select the specific direct message
|
||||||
|
|||||||
@@ -61,19 +61,19 @@ export class MessageHandler {
|
|||||||
themeManager.setTheme(request.body.themeID).then(() => {
|
themeManager.setTheme(request.body.themeID).then(() => {
|
||||||
sendResponse({ status: "success" });
|
sendResponse({ status: "success" });
|
||||||
});
|
});
|
||||||
break;
|
return true;
|
||||||
|
|
||||||
case "DisableTheme":
|
case "DisableTheme":
|
||||||
themeManager.disableTheme().then(() => {
|
themeManager.disableTheme().then(() => {
|
||||||
sendResponse({ status: "success" });
|
sendResponse({ status: "success" });
|
||||||
});
|
});
|
||||||
break;
|
return true;
|
||||||
|
|
||||||
case "DeleteTheme":
|
case "DeleteTheme":
|
||||||
themeManager.deleteTheme(request.body.themeID).then(() => {
|
themeManager.deleteTheme(request.body.themeID).then(() => {
|
||||||
sendResponse({ status: "success" });
|
sendResponse({ status: "success" });
|
||||||
});
|
});
|
||||||
break;
|
return true;
|
||||||
|
|
||||||
case "ListThemes":
|
case "ListThemes":
|
||||||
themeManager.getAvailableThemes().then((themes) => {
|
themeManager.getAvailableThemes().then((themes) => {
|
||||||
@@ -97,11 +97,11 @@ export class MessageHandler {
|
|||||||
case "CloseThemeCreator":
|
case "CloseThemeCreator":
|
||||||
try {
|
try {
|
||||||
CloseThemeCreator();
|
CloseThemeCreator();
|
||||||
|
sendResponse({ status: "success" });
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error("Error closing theme creator:", error);
|
console.error("Error closing theme creator:", error);
|
||||||
sendResponse({ status: "error" });
|
sendResponse({ status: "error" });
|
||||||
}
|
}
|
||||||
sendResponse({ status: "success" });
|
|
||||||
break;
|
break;
|
||||||
|
|
||||||
case "HideSensitive":
|
case "HideSensitive":
|
||||||
|
|||||||
@@ -2,6 +2,20 @@ import browser from "webextension-polyfill";
|
|||||||
import type { SettingsState } from "@/types/storage";
|
import type { SettingsState } from "@/types/storage";
|
||||||
import type { Subscriber, Unsubscriber } from "svelte/store";
|
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 ChangeListener = (newValue: any, oldValue: any) => void;
|
||||||
type GlobalChangeListener = (newValue: any, oldValue: any, key: string) => void;
|
type GlobalChangeListener = (newValue: any, oldValue: any, key: string) => void;
|
||||||
|
|
||||||
@@ -26,9 +40,16 @@ class StorageManager {
|
|||||||
if (prop in target) {
|
if (prop in target) {
|
||||||
return (target as any)[prop];
|
return (target as any)[prop];
|
||||||
}
|
}
|
||||||
|
if (typeof prop === "string" && isExcludedSettingsKey(prop)) {
|
||||||
|
return undefined;
|
||||||
|
}
|
||||||
return Reflect.get(target.data, prop);
|
return Reflect.get(target.data, prop);
|
||||||
},
|
},
|
||||||
set: (target, prop: keyof SettingsState, value) => {
|
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];
|
const oldValue = target.data[prop];
|
||||||
|
|
||||||
// Only save if the reference actually changed
|
// Only save if the reference actually changed
|
||||||
@@ -95,6 +116,10 @@ class StorageManager {
|
|||||||
key: K,
|
key: K,
|
||||||
value: SettingsState[K],
|
value: SettingsState[K],
|
||||||
): void {
|
): void {
|
||||||
|
if (typeof key === "string" && isExcludedSettingsKey(key)) {
|
||||||
|
void browser.storage.local.set({ [key]: value });
|
||||||
|
return;
|
||||||
|
}
|
||||||
const oldValue = this.data[key];
|
const oldValue = this.data[key];
|
||||||
if (oldValue !== value) {
|
if (oldValue !== value) {
|
||||||
this.data[key] = value;
|
this.data[key] = value;
|
||||||
@@ -121,6 +146,7 @@ class StorageManager {
|
|||||||
private async loadFromStorage(): Promise<void> {
|
private async loadFromStorage(): Promise<void> {
|
||||||
const result = await browser.storage.local.get();
|
const result = await browser.storage.local.get();
|
||||||
Object.entries(result).forEach(([key, value]) => {
|
Object.entries(result).forEach(([key, value]) => {
|
||||||
|
if (isExcludedSettingsKey(key)) return;
|
||||||
Reflect.set(this.data, key, value);
|
Reflect.set(this.data, key, value);
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
@@ -137,6 +163,7 @@ class StorageManager {
|
|||||||
: Object.keys(this.data);
|
: Object.keys(this.data);
|
||||||
|
|
||||||
for (const key of keys) {
|
for (const key of keys) {
|
||||||
|
if (isExcludedSettingsKey(key)) continue;
|
||||||
const value = (this.data as Record<string, unknown>)[key];
|
const value = (this.data as Record<string, unknown>)[key];
|
||||||
if (value !== undefined) {
|
if (value !== undefined) {
|
||||||
payload[key] = value;
|
payload[key] = value;
|
||||||
@@ -163,6 +190,7 @@ class StorageManager {
|
|||||||
|
|
||||||
for (const [key, { oldValue, newValue }] of Object.entries(changes)) {
|
for (const [key, { oldValue, newValue }] of Object.entries(changes)) {
|
||||||
if (JSON.stringify(oldValue) === JSON.stringify(newValue)) continue;
|
if (JSON.stringify(oldValue) === JSON.stringify(newValue)) continue;
|
||||||
|
if (isExcludedSettingsKey(key)) continue;
|
||||||
|
|
||||||
if (newValue !== undefined) {
|
if (newValue !== undefined) {
|
||||||
(this.data as Record<string, unknown>)[key] = newValue;
|
(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.
|
* 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.
|
* 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.
|
* 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.
|
* 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();
|
const parser = new DOMParser();
|
||||||
|
|
||||||
str = DOMPurify.sanitize(str, {
|
str = DOMPurify.sanitize(str, {
|
||||||
ADD_ATTR: ["onclick"],
|
|
||||||
ALLOWED_URI_REGEXP:
|
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");
|
const doc = parser.parseFromString(str, "text/html");
|
||||||
|
|||||||
@@ -69,11 +69,7 @@ export interface SettingsState {
|
|||||||
assessmentsAverage?: boolean;
|
assessmentsAverage?: boolean;
|
||||||
notificationCollector?: boolean;
|
notificationCollector?: boolean;
|
||||||
|
|
||||||
// BetterSEQTA Cloud (accounts.betterseqta.org)
|
// BetterSEQTA Cloud (accounts.betterseqta.org) — stored via CloudAuth, not settingsState
|
||||||
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 };
|
|
||||||
/** When not `false`, automatic cloud settings sync is enabled (default-on). */
|
/** When not `false`, automatic cloud settings sync is enabled (default-on). */
|
||||||
autoCloudSettingsSync?: boolean;
|
autoCloudSettingsSync?: boolean;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -215,6 +215,7 @@ export async function checkGithubReleaseUpdate(): Promise<GhReleaseUpdateInfo> {
|
|||||||
}
|
}
|
||||||
|
|
||||||
export function dismissNightlyUpdate(): void {
|
export function dismissNightlyUpdate(): void {
|
||||||
|
cachedResult = null;
|
||||||
void (async () => {
|
void (async () => {
|
||||||
const release = await fetchJson<GhRelease>(
|
const release = await fetchJson<GhRelease>(
|
||||||
`https://api.github.com/repos/${getRepoSlug()}/releases/tags/${NIGHTLY_TAG}`,
|
`https://api.github.com/repos/${getRepoSlug()}/releases/tags/${NIGHTLY_TAG}`,
|
||||||
|
|||||||
Reference in New Issue
Block a user