mirror of
https://github.com/BetterSEQTA/BetterSEQTA-Plus.git
synced 2026-12-06 19:56:45 +10:30
fix: fix codefactor issues
This commit is contained in:
1 parent
1bedf58e22
commit
bca273e8d4
20 files changed
+257
-173
No files matched your search
@@ -15,6 +15,8 @@ concurrency:
|
|||||||
|
|
||||||
jobs:
|
jobs:
|
||||||
lint:
|
lint:
|
||||||
|
permissions:
|
||||||
|
contents: read
|
||||||
# The layerchart Svelte build fails on Linux, so CI runs on Windows.
|
# The layerchart Svelte build fails on Linux, so CI runs on Windows.
|
||||||
runs-on: windows-latest
|
runs-on: windows-latest
|
||||||
defaults:
|
defaults:
|
||||||
@@ -30,6 +32,8 @@ jobs:
|
|||||||
uses: ./.github/actions/run-lint
|
uses: ./.github/actions/run-lint
|
||||||
|
|
||||||
unit-tests:
|
unit-tests:
|
||||||
|
permissions:
|
||||||
|
contents: read
|
||||||
runs-on: windows-latest
|
runs-on: windows-latest
|
||||||
defaults:
|
defaults:
|
||||||
run:
|
run:
|
||||||
@@ -44,6 +48,8 @@ jobs:
|
|||||||
uses: ./.github/actions/run-unit-tests
|
uses: ./.github/actions/run-unit-tests
|
||||||
|
|
||||||
build-and-smoke:
|
build-and-smoke:
|
||||||
|
permissions:
|
||||||
|
contents: read
|
||||||
needs: [lint, unit-tests]
|
needs: [lint, unit-tests]
|
||||||
runs-on: windows-latest
|
runs-on: windows-latest
|
||||||
defaults:
|
defaults:
|
||||||
|
|||||||
+59
-27
@@ -13,10 +13,11 @@ import {
|
|||||||
} from "./background/cloudSettingsAutoSync";
|
} from "./background/cloudSettingsAutoSync";
|
||||||
import { getBsplusDeviceName } from "@/seqta/utils/bsplusDeviceName";
|
import { getBsplusDeviceName } from "@/seqta/utils/bsplusDeviceName";
|
||||||
import { isAllowedFetchUrl } from "@/seqta/utils/allowedFetchUrl";
|
import { isAllowedFetchUrl } from "@/seqta/utils/allowedFetchUrl";
|
||||||
import { initCalendarBackground } from "./background/calendarBackground";
|
|
||||||
import {
|
import {
|
||||||
|
initCalendarBackground,
|
||||||
registerGoogleCalendarMessageHandlers,
|
registerGoogleCalendarMessageHandlers,
|
||||||
registerOutlookCalendarMessageHandlers,
|
registerOutlookCalendarMessageHandlers,
|
||||||
|
type CalendarMessageHandlerMap,
|
||||||
} from "./background/calendarBackground";
|
} from "./background/calendarBackground";
|
||||||
import { createCustomThemesHandlers } from "./background/customThemesHandlers";
|
import { createCustomThemesHandlers } from "./background/customThemesHandlers";
|
||||||
import {
|
import {
|
||||||
@@ -50,7 +51,7 @@ function apiBase(): string {
|
|||||||
|
|
||||||
function reloadSeqtaPages() {
|
function reloadSeqtaPages() {
|
||||||
const result = browser.tabs.query({});
|
const result = browser.tabs.query({});
|
||||||
function open(tabs: any) {
|
function open(tabs: chrome.tabs.Tab[]) {
|
||||||
for (const tab of tabs) {
|
for (const tab of tabs) {
|
||||||
if (tab.title?.includes("SEQTA Learn") || tab.title?.includes("SEQTA Engage")) {
|
if (tab.title?.includes("SEQTA Learn") || tab.title?.includes("SEQTA Engage")) {
|
||||||
browser.tabs.reload(tab.id);
|
browser.tabs.reload(tab.id);
|
||||||
@@ -63,6 +64,14 @@ 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 };
|
||||||
|
|
||||||
|
/** Runtime message payloads from extension pages / content scripts */
|
||||||
|
type BackgroundRequest = Record<string, unknown>;
|
||||||
|
|
||||||
|
function reqString(req: BackgroundRequest, key: string): string | undefined {
|
||||||
|
const value = req[key];
|
||||||
|
return typeof value === "string" ? value : undefined;
|
||||||
|
}
|
||||||
|
|
||||||
async function getAccessTokenFromStorage(): Promise<string | null> {
|
async function getAccessTokenFromStorage(): Promise<string | null> {
|
||||||
const { bsplus_token } = await browser.storage.local.get("bsplus_token");
|
const { bsplus_token } = await browser.storage.local.get("bsplus_token");
|
||||||
return typeof bsplus_token === "string" && bsplus_token.length > 0 ? bsplus_token : null;
|
return typeof bsplus_token === "string" && bsplus_token.length > 0 ? bsplus_token : null;
|
||||||
@@ -147,7 +156,7 @@ function handleFetchThemes(_request: unknown, sendResponse: MessageSender): bool
|
|||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
function handleFetchThemeDetails(request: any, sendResponse: MessageSender): boolean {
|
function handleFetchThemeDetails(request: BackgroundRequest, sendResponse: MessageSender): boolean {
|
||||||
const { themeId } = 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" });
|
||||||
@@ -188,7 +197,7 @@ function isTrustedSender(sender?: chrome.runtime.MessageSender): boolean {
|
|||||||
}
|
}
|
||||||
|
|
||||||
function handleFetchFromUrl(
|
function handleFetchFromUrl(
|
||||||
request: any,
|
request: BackgroundRequest,
|
||||||
sendResponse: MessageSender,
|
sendResponse: MessageSender,
|
||||||
sender?: chrome.runtime.MessageSender,
|
sender?: chrome.runtime.MessageSender,
|
||||||
): boolean {
|
): boolean {
|
||||||
@@ -238,7 +247,7 @@ function handleFetchFromUrl(
|
|||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
async function parseJsonResponse(r: Response): Promise<any> {
|
async function parseJsonResponse(r: Response): Promise<unknown> {
|
||||||
const text = await r.text();
|
const text = await r.text();
|
||||||
try {
|
try {
|
||||||
return text ? JSON.parse(text) : {};
|
return text ? JSON.parse(text) : {};
|
||||||
@@ -247,7 +256,7 @@ async function parseJsonResponse(r: Response): Promise<any> {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
function handleCloudReserveClient(request: any, sendResponse: MessageSender): boolean {
|
function handleCloudReserveClient(request: BackgroundRequest, sendResponse: MessageSender): boolean {
|
||||||
const redirect_uri =
|
const redirect_uri =
|
||||||
request.redirect_uri ?? "https://accounts.betterseqta.org/auth/bsplus/callback";
|
request.redirect_uri ?? "https://accounts.betterseqta.org/auth/bsplus/callback";
|
||||||
fetch("https://accounts.betterseqta.org/api/bsplus/client/reserve", {
|
fetch("https://accounts.betterseqta.org/api/bsplus/client/reserve", {
|
||||||
@@ -257,7 +266,11 @@ function handleCloudReserveClient(request: any, sendResponse: MessageSender): bo
|
|||||||
})
|
})
|
||||||
.then(async (r) => {
|
.then(async (r) => {
|
||||||
const data = await parseJsonResponse(r);
|
const data = await parseJsonResponse(r);
|
||||||
if (!r.ok) sendResponse({ error: data?.error ?? `Reserve failed (${r.status})` });
|
const errorText =
|
||||||
|
data && typeof data === "object" && "error" in data
|
||||||
|
? String((data as { error?: unknown }).error)
|
||||||
|
: undefined;
|
||||||
|
if (!r.ok) sendResponse({ error: errorText ?? `Reserve failed (${r.status})` });
|
||||||
else sendResponse(data);
|
else sendResponse(data);
|
||||||
})
|
})
|
||||||
.catch((err) => {
|
.catch((err) => {
|
||||||
@@ -268,7 +281,7 @@ function handleCloudReserveClient(request: any, sendResponse: MessageSender): bo
|
|||||||
}
|
}
|
||||||
|
|
||||||
function handleCloudLogin(
|
function handleCloudLogin(
|
||||||
request: any,
|
request: BackgroundRequest,
|
||||||
sendResponse: MessageSender,
|
sendResponse: MessageSender,
|
||||||
sender?: chrome.runtime.MessageSender,
|
sender?: chrome.runtime.MessageSender,
|
||||||
): boolean {
|
): boolean {
|
||||||
@@ -276,7 +289,11 @@ function handleCloudLogin(
|
|||||||
sendResponse({ error: "Unauthorized sender" });
|
sendResponse({ error: "Unauthorized sender" });
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
const { client_id, redirect_uri, login, password, device_name } = request;
|
const client_id = reqString(request, "client_id");
|
||||||
|
const redirect_uri = reqString(request, "redirect_uri");
|
||||||
|
const login = reqString(request, "login");
|
||||||
|
const password = reqString(request, "password");
|
||||||
|
const device_name = reqString(request, "device_name");
|
||||||
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" });
|
||||||
return false;
|
return false;
|
||||||
@@ -296,7 +313,11 @@ function handleCloudLogin(
|
|||||||
body: JSON.stringify(loginBody),
|
body: JSON.stringify(loginBody),
|
||||||
});
|
});
|
||||||
const data = await parseJsonResponse(r);
|
const data = await parseJsonResponse(r);
|
||||||
if (!r.ok) sendResponse({ error: data?.error ?? "Login failed" });
|
const errorText =
|
||||||
|
data && typeof data === "object" && "error" in data
|
||||||
|
? String((data as { error?: unknown }).error)
|
||||||
|
: undefined;
|
||||||
|
if (!r.ok) sendResponse({ error: errorText ?? "Login failed" });
|
||||||
else sendResponse(data);
|
else sendResponse(data);
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
console.error("[Background] cloudLogin error:", err);
|
console.error("[Background] cloudLogin error:", err);
|
||||||
@@ -306,8 +327,9 @@ function handleCloudLogin(
|
|||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
function handleCloudStartLogin(request: any, sendResponse: MessageSender): boolean {
|
function handleCloudStartLogin(request: BackgroundRequest, sendResponse: MessageSender): boolean {
|
||||||
const { client_id, redirect_uri } = request;
|
const client_id = reqString(request, "client_id");
|
||||||
|
const redirect_uri = reqString(request, "redirect_uri");
|
||||||
if (!client_id || !redirect_uri) {
|
if (!client_id || !redirect_uri) {
|
||||||
sendResponse({ error: "Missing client_id or redirect_uri" });
|
sendResponse({ error: "Missing client_id or redirect_uri" });
|
||||||
return true;
|
return true;
|
||||||
@@ -373,7 +395,7 @@ function initCloudLoginCallbackListener() {
|
|||||||
|
|
||||||
initCloudLoginCallbackListener();
|
initCloudLoginCallbackListener();
|
||||||
|
|
||||||
function handleCloudRefresh(request: any, sendResponse: MessageSender): boolean {
|
function handleCloudRefresh(request: BackgroundRequest, sendResponse: MessageSender): boolean {
|
||||||
const { refresh_token, client_id } = request;
|
const { refresh_token, client_id } = request;
|
||||||
if (!refresh_token || !client_id) {
|
if (!refresh_token || !client_id) {
|
||||||
sendResponse({ error: "Missing refresh_token or client_id" });
|
sendResponse({ error: "Missing refresh_token or client_id" });
|
||||||
@@ -386,7 +408,11 @@ function handleCloudRefresh(request: any, sendResponse: MessageSender): boolean
|
|||||||
})
|
})
|
||||||
.then(async (r) => {
|
.then(async (r) => {
|
||||||
const data = await parseJsonResponse(r);
|
const data = await parseJsonResponse(r);
|
||||||
if (!r.ok) sendResponse({ error: data?.error ?? "Refresh failed" });
|
const errorText =
|
||||||
|
data && typeof data === "object" && "error" in data
|
||||||
|
? String((data as { error?: unknown }).error)
|
||||||
|
: undefined;
|
||||||
|
if (!r.ok) sendResponse({ error: errorText ?? "Refresh failed" });
|
||||||
else sendResponse(data);
|
else sendResponse(data);
|
||||||
})
|
})
|
||||||
.catch((err) => {
|
.catch((err) => {
|
||||||
@@ -463,7 +489,7 @@ function handleCloudSettingsDownload(
|
|||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
function handleCloudFavorite(request: any, sendResponse: MessageSender): boolean {
|
function handleCloudFavorite(request: BackgroundRequest, sendResponse: MessageSender): boolean {
|
||||||
const { themeId, action } = request;
|
const { themeId, action } = request;
|
||||||
if (!themeId) {
|
if (!themeId) {
|
||||||
sendResponse({ success: false, error: "Theme ID required" });
|
sendResponse({ success: false, error: "Theme ID required" });
|
||||||
@@ -493,7 +519,7 @@ function handleCloudFavorite(request: any, sendResponse: MessageSender): boolean
|
|||||||
/** Handler for a message type; receives request, sendResponse, and optional sender (for tab routing) */
|
/** Handler for a message type; receives request, sendResponse, and optional sender (for tab routing) */
|
||||||
type MessageHandler = {
|
type MessageHandler = {
|
||||||
(
|
(
|
||||||
request: any,
|
request: BackgroundRequest,
|
||||||
sendResponse: MessageSender,
|
sendResponse: MessageSender,
|
||||||
sender?: chrome.runtime.MessageSender,
|
sender?: chrome.runtime.MessageSender,
|
||||||
): boolean | void;
|
): boolean | void;
|
||||||
@@ -509,7 +535,7 @@ function isSeqtaOrigin(origin: string): boolean {
|
|||||||
}
|
}
|
||||||
|
|
||||||
function handleSetDevApiBase(
|
function handleSetDevApiBase(
|
||||||
request: any,
|
request: BackgroundRequest,
|
||||||
_sendResponse: MessageSender,
|
_sendResponse: MessageSender,
|
||||||
sender?: chrome.runtime.MessageSender,
|
sender?: chrome.runtime.MessageSender,
|
||||||
): boolean {
|
): boolean {
|
||||||
@@ -571,7 +597,8 @@ const MESSAGE_HANDLERS: Record<string, MessageHandler> = {
|
|||||||
sendResponse({ error: "Unauthorized sender" });
|
sendResponse({ error: "Unauthorized sender" });
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
void fetchNews(req.source).then((news) => sendResponse({ news }));
|
const source = typeof req.source === "string" ? req.source : undefined;
|
||||||
|
void fetchNews(source).then((news) => sendResponse({ news }));
|
||||||
return true;
|
return true;
|
||||||
},
|
},
|
||||||
fetchThemes: handleFetchThemes,
|
fetchThemes: handleFetchThemes,
|
||||||
@@ -635,13 +662,16 @@ const MESSAGE_HANDLERS: Record<string, MessageHandler> = {
|
|||||||
},
|
},
|
||||||
};
|
};
|
||||||
|
|
||||||
registerGoogleCalendarMessageHandlers(MESSAGE_HANDLERS, isTrustedSender);
|
registerGoogleCalendarMessageHandlers(MESSAGE_HANDLERS as CalendarMessageHandlerMap, isTrustedSender);
|
||||||
registerOutlookCalendarMessageHandlers(MESSAGE_HANDLERS, isTrustedSender);
|
registerOutlookCalendarMessageHandlers(
|
||||||
|
MESSAGE_HANDLERS as CalendarMessageHandlerMap,
|
||||||
|
isTrustedSender,
|
||||||
|
);
|
||||||
initCalendarBackground();
|
initCalendarBackground();
|
||||||
|
|
||||||
browser.runtime.onMessage.addListener(
|
browser.runtime.onMessage.addListener(
|
||||||
(request: any, sender: chrome.runtime.MessageSender, sendResponse: MessageSender) => {
|
(request: BackgroundRequest, sender: chrome.runtime.MessageSender, sendResponse: MessageSender) => {
|
||||||
const handler = MESSAGE_HANDLERS[request.type];
|
const handler = MESSAGE_HANDLERS[request.type as string];
|
||||||
if (handler) {
|
if (handler) {
|
||||||
const result = handler(request, sendResponse, sender);
|
const result = handler(request, sendResponse, sender);
|
||||||
return result === true;
|
return result === true;
|
||||||
@@ -681,11 +711,13 @@ browser.runtime.onInstalled.addListener(function (event) {
|
|||||||
if (event.reason === "install") {
|
if (event.reason === "install") {
|
||||||
void refreshRemoteConfig(apiBase);
|
void refreshRemoteConfig(apiBase);
|
||||||
void browser.storage.local.set({ [DEFAULT_BACKGROUND_PENDING_KEY]: true });
|
void browser.storage.local.set({ [DEFAULT_BACKGROUND_PENDING_KEY]: true });
|
||||||
void defaultsReady.catch(() => undefined).then(async () => {
|
void defaultsReady
|
||||||
const key = "plugin.animated-background.settings";
|
.catch(() => undefined)
|
||||||
const { [key]: settings } = await browser.storage.local.get(key);
|
.then(async () => {
|
||||||
await browser.storage.local.set({ [key]: { ...(settings as object), enabled: false } });
|
const key = "plugin.animated-background.settings";
|
||||||
});
|
const { [key]: settings } = await browser.storage.local.get(key);
|
||||||
|
await browser.storage.local.set({ [key]: { ...(settings as object), enabled: false } });
|
||||||
|
});
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|||||||
@@ -47,7 +47,7 @@ function isAutoCloudSyncEnabled(all: Record<string, unknown>): boolean {
|
|||||||
return all.autoCloudSettingsSync !== false;
|
return all.autoCloudSettingsSync !== false;
|
||||||
}
|
}
|
||||||
|
|
||||||
async function parseJsonResponse(r: Response): Promise<any> {
|
async function parseJsonResponse(r: Response): Promise<unknown> {
|
||||||
const text = await r.text();
|
const text = await r.text();
|
||||||
try {
|
try {
|
||||||
return text ? JSON.parse(text) : {};
|
return text ? JSON.parse(text) : {};
|
||||||
|
|||||||
@@ -35,7 +35,7 @@ function buildFormDataFromPayload(payload: UploadPayload): FormData {
|
|||||||
export function createCustomThemesHandlers(deps: {
|
export function createCustomThemesHandlers(deps: {
|
||||||
apiBase: () => string;
|
apiBase: () => string;
|
||||||
getAccessTokenFromStorage: () => Promise<string | null>;
|
getAccessTokenFromStorage: () => Promise<string | null>;
|
||||||
}): Record<string, (request: any, sendResponse: MessageSender) => boolean> {
|
}): Record<string, (request: Record<string, unknown>, sendResponse: MessageSender) => boolean> {
|
||||||
async function readCustomThemesResponse(r: Response): Promise<Record<string, unknown>> {
|
async function readCustomThemesResponse(r: Response): Promise<Record<string, unknown>> {
|
||||||
const text = await r.text();
|
const text = await r.text();
|
||||||
let body: unknown;
|
let body: unknown;
|
||||||
@@ -95,7 +95,7 @@ export function createCustomThemesHandlers(deps: {
|
|||||||
return await readCustomThemesResponse(r);
|
return await readCustomThemesResponse(r);
|
||||||
}
|
}
|
||||||
|
|
||||||
function handleFetchCustomThemes(request: any, sendResponse: MessageSender): boolean {
|
function handleFetchCustomThemes(request: Record<string, unknown>, sendResponse: MessageSender): boolean {
|
||||||
void (async () => {
|
void (async () => {
|
||||||
try {
|
try {
|
||||||
const params = new URLSearchParams();
|
const params = new URLSearchParams();
|
||||||
@@ -104,7 +104,8 @@ export function createCustomThemesHandlers(deps: {
|
|||||||
params.set("limit", String(request.limit ?? 20));
|
params.set("limit", String(request.limit ?? 20));
|
||||||
(await bsplusApiQueryParams()).forEach((value, key) => params.set(key, value));
|
(await bsplusApiQueryParams()).forEach((value, key) => params.set(key, value));
|
||||||
if (request.sort) params.set("sort", String(request.sort));
|
if (request.sort) params.set("sort", String(request.sort));
|
||||||
const search = request.search?.trim();
|
const searchRaw = request.search;
|
||||||
|
const search = typeof searchRaw === "string" ? searchRaw.trim() : "";
|
||||||
const path = search
|
const path = search
|
||||||
? `/api/custom-themes/search?${params}&q=${encodeURIComponent(search)}`
|
? `/api/custom-themes/search?${params}&q=${encodeURIComponent(search)}`
|
||||||
: `/api/custom-themes?${params}`;
|
: `/api/custom-themes?${params}`;
|
||||||
@@ -120,7 +121,7 @@ export function createCustomThemesHandlers(deps: {
|
|||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
function handleFetchMyCustomThemes(request: any, sendResponse: MessageSender): boolean {
|
function handleFetchMyCustomThemes(request: Record<string, unknown>, sendResponse: MessageSender): boolean {
|
||||||
void (async () => {
|
void (async () => {
|
||||||
try {
|
try {
|
||||||
const params = new URLSearchParams();
|
const params = new URLSearchParams();
|
||||||
@@ -141,7 +142,7 @@ export function createCustomThemesHandlers(deps: {
|
|||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
function handleFetchMyCustomThemeDetail(request: any, sendResponse: MessageSender): boolean {
|
function handleFetchMyCustomThemeDetail(request: Record<string, unknown>, sendResponse: MessageSender): boolean {
|
||||||
const { themeId } = 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" });
|
||||||
@@ -167,7 +168,7 @@ export function createCustomThemesHandlers(deps: {
|
|||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
function handleSubmitCustomTheme(request: any, sendResponse: MessageSender): boolean {
|
function handleSubmitCustomTheme(request: Record<string, unknown>, sendResponse: MessageSender): boolean {
|
||||||
const payload = request.payload as UploadPayload | undefined;
|
const payload = request.payload as UploadPayload | undefined;
|
||||||
if (!payload?.themeZip && (!payload?.looseFiles || payload.looseFiles.length === 0)) {
|
if (!payload?.themeZip && (!payload?.looseFiles || payload.looseFiles.length === 0)) {
|
||||||
sendResponse({ success: false, error: "Missing upload files" });
|
sendResponse({ success: false, error: "Missing upload files" });
|
||||||
@@ -188,12 +189,14 @@ export function createCustomThemesHandlers(deps: {
|
|||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
function handleReplaceCustomThemeFiles(request: any, sendResponse: MessageSender): boolean {
|
function handleReplaceCustomThemeFiles(request: Record<string, unknown>, sendResponse: MessageSender): boolean {
|
||||||
const { themeId, payload } = request;
|
const { themeId, payload: payloadRaw } = 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 payload =
|
||||||
|
payloadRaw && typeof payloadRaw === "object" ? (payloadRaw as UploadPayload) : undefined;
|
||||||
if (!payload?.themeZip && (!payload?.looseFiles || payload.looseFiles.length === 0)) {
|
if (!payload?.themeZip && (!payload?.looseFiles || payload.looseFiles.length === 0)) {
|
||||||
sendResponse({ success: false, error: "Missing upload files" });
|
sendResponse({ success: false, error: "Missing upload files" });
|
||||||
return false;
|
return false;
|
||||||
@@ -203,7 +206,7 @@ export function createCustomThemesHandlers(deps: {
|
|||||||
sendResponse(
|
sendResponse(
|
||||||
await customThemesMultipartPost(
|
await customThemesMultipartPost(
|
||||||
`/api/custom-themes/mine/${encodeURIComponent(themeId)}/files`,
|
`/api/custom-themes/mine/${encodeURIComponent(themeId)}/files`,
|
||||||
payload,
|
payload as UploadPayload,
|
||||||
),
|
),
|
||||||
);
|
);
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
@@ -217,7 +220,7 @@ export function createCustomThemesHandlers(deps: {
|
|||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
function handleUpdateCustomThemeMetadata(request: any, sendResponse: MessageSender): boolean {
|
function handleUpdateCustomThemeMetadata(request: Record<string, unknown>, sendResponse: MessageSender): boolean {
|
||||||
const { themeId, body } = request;
|
const { themeId, body } = request;
|
||||||
if (!themeId || typeof themeId !== "string") {
|
if (!themeId || typeof themeId !== "string") {
|
||||||
sendResponse({ success: false, error: "Missing themeId" });
|
sendResponse({ success: false, error: "Missing themeId" });
|
||||||
@@ -247,7 +250,7 @@ export function createCustomThemesHandlers(deps: {
|
|||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
function handleDeleteCustomTheme(request: any, sendResponse: MessageSender): boolean {
|
function handleDeleteCustomTheme(request: Record<string, unknown>, sendResponse: MessageSender): boolean {
|
||||||
const { themeId } = 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" });
|
||||||
@@ -287,7 +290,7 @@ export function createCustomThemesHandlers(deps: {
|
|||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
function handleFetchBsplusAdminThemes(request: any, sendResponse: MessageSender): boolean {
|
function handleFetchBsplusAdminThemes(request: Record<string, unknown>, sendResponse: MessageSender): boolean {
|
||||||
void (async () => {
|
void (async () => {
|
||||||
try {
|
try {
|
||||||
const params = new URLSearchParams();
|
const params = new URLSearchParams();
|
||||||
@@ -295,7 +298,8 @@ export function createCustomThemesHandlers(deps: {
|
|||||||
params.set("limit", String(Math.min(Number(request.limit ?? 20) || 20, 100)));
|
params.set("limit", String(Math.min(Number(request.limit ?? 20) || 20, 100)));
|
||||||
if (request.status) params.set("status", String(request.status));
|
if (request.status) params.set("status", String(request.status));
|
||||||
if (request.source) params.set("source", String(request.source));
|
if (request.source) params.set("source", String(request.source));
|
||||||
const search = request.search?.trim();
|
const searchRaw = request.search;
|
||||||
|
const search = typeof searchRaw === "string" ? searchRaw.trim() : "";
|
||||||
if (search) params.set("search", search);
|
if (search) params.set("search", search);
|
||||||
sendResponse(await customThemesJsonFetch(`/api/bsplus/admin/themes?${params}`, {}, true));
|
sendResponse(await customThemesJsonFetch(`/api/bsplus/admin/themes?${params}`, {}, true));
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
|
|||||||
@@ -79,7 +79,7 @@ export async function fetchNews(source?: string): Promise<NewsPayload> {
|
|||||||
const results = await Promise.allSettled(feedUrls.map(fetchFeed));
|
const results = await Promise.allSettled(feedUrls.map(fetchFeed));
|
||||||
const feeds = results.flatMap((result, i) => {
|
const feeds = results.flatMap((result, i) => {
|
||||||
if (result.status === "fulfilled") return [result.value];
|
if (result.status === "fulfilled") return [result.value];
|
||||||
console.error(`[BetterSEQTA+] Failed to fetch RSS feed: ${feedUrls[i]}`, result.reason);
|
console.error("[BetterSEQTA+] Failed to fetch RSS feed:", feedUrls[i], result.reason);
|
||||||
return [];
|
return [];
|
||||||
});
|
});
|
||||||
return { feeds };
|
return { feeds };
|
||||||
|
|||||||
@@ -4,9 +4,7 @@ import browser from "@/lib/browser";
|
|||||||
function crossedUpgrade(previousVersion: string, boundary: string): boolean {
|
function crossedUpgrade(previousVersion: string, boundary: string): boolean {
|
||||||
const prev = semver.coerce(previousVersion);
|
const prev = semver.coerce(previousVersion);
|
||||||
const curr = semver.coerce(browser.runtime.getManifest().version);
|
const curr = semver.coerce(browser.runtime.getManifest().version);
|
||||||
return (
|
return prev != null && curr != null && !semver.lt(curr, boundary) && semver.lt(prev, boundary);
|
||||||
prev != null && curr != null && !semver.lt(curr, boundary) && semver.lt(prev, boundary)
|
|
||||||
);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/** One-time storage patches when crossing 3.6.5 / 3.6.6 / 3.7.0 (see git history on main). */
|
/** One-time storage patches when crossing 3.6.5 / 3.6.6 / 3.7.0 (see git history on main). */
|
||||||
|
|||||||
@@ -110,9 +110,7 @@ html {
|
|||||||
transform-origin: top;
|
transform-origin: top;
|
||||||
transition: transform 0.2s;
|
transition: transform 0.2s;
|
||||||
}
|
}
|
||||||
body:has(.outside-container:not(.hide))
|
body:has(.outside-container:not(.hide)) #AddedSettings.tooltip:hover > .tooltiptext {
|
||||||
#AddedSettings.tooltip:hover
|
|
||||||
> .tooltiptext {
|
|
||||||
transform: scale(0);
|
transform: scale(0);
|
||||||
}
|
}
|
||||||
.assessmenttooltip svg {
|
.assessmenttooltip svg {
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
import { type Plugin } from "@/plugins/core/types";
|
import type { AssessmentsAverageApi } from "./pluginApi";
|
||||||
import stringToHTML from "@/seqta/utils/stringToHTML";
|
import stringToHTML from "@/seqta/utils/stringToHTML";
|
||||||
import { waitForElm } from "@/seqta/utils/waitForElm";
|
import { waitForElm } from "@/seqta/utils/waitForElm";
|
||||||
import {
|
import {
|
||||||
@@ -17,7 +17,7 @@ let wrapperColourObserver: MutationObserver | null = null;
|
|||||||
let wrapperColourObserverTimeout: ReturnType<typeof setTimeout> | null = null;
|
let wrapperColourObserverTimeout: ReturnType<typeof setTimeout> | null = null;
|
||||||
|
|
||||||
const assessmentsAveragePlugin = {
|
const assessmentsAveragePlugin = {
|
||||||
run: async (api: Parameters<NonNullable<Plugin["run"]>>[0]) => {
|
run: async (api: AssessmentsAverageApi) => {
|
||||||
await initStorage(api);
|
await initStorage(api);
|
||||||
clearStuck(api);
|
clearStuck(api);
|
||||||
|
|
||||||
@@ -97,7 +97,7 @@ const assessmentsAveragePlugin = {
|
|||||||
|
|
||||||
let renderInFlight = false;
|
let renderInFlight = false;
|
||||||
let renderQueued = false;
|
let renderQueued = false;
|
||||||
async function renderSubjectAverage(api: any) {
|
async function renderSubjectAverage(api: AssessmentsAverageApi) {
|
||||||
if (renderInFlight) {
|
if (renderInFlight) {
|
||||||
// Coalesce: remember that fresh data arrived during this render and
|
// Coalesce: remember that fresh data arrived during this render and
|
||||||
// re-run once the current pass finishes, so the UI catches up to the
|
// re-run once the current pass finishes, so the UI catches up to the
|
||||||
|
|||||||
@@ -0,0 +1,36 @@
|
|||||||
|
import type { BooleanSetting, PluginAPI } from "@/plugins/core/types";
|
||||||
|
|
||||||
|
export interface WeightingEntry {
|
||||||
|
weight: string;
|
||||||
|
fingerprint: string;
|
||||||
|
pluginVersion: number;
|
||||||
|
refreshing?: boolean;
|
||||||
|
}
|
||||||
|
|
||||||
|
export type WeightingsMap = Record<string, WeightingEntry>;
|
||||||
|
|
||||||
|
export type AssessmentsAveragePluginSettings = {
|
||||||
|
lettergrade: BooleanSetting;
|
||||||
|
};
|
||||||
|
|
||||||
|
export type AssessmentsAverageStorage = {
|
||||||
|
weightings: WeightingsMap;
|
||||||
|
assessments: Record<string, string>;
|
||||||
|
weightingOverrides: Record<string, string>;
|
||||||
|
};
|
||||||
|
|
||||||
|
export type AssessmentsAverageApi = PluginAPI<
|
||||||
|
AssessmentsAveragePluginSettings,
|
||||||
|
AssessmentsAverageStorage
|
||||||
|
>;
|
||||||
|
|
||||||
|
export type AssessmentMark = {
|
||||||
|
id: string | number;
|
||||||
|
title?: string;
|
||||||
|
metaclassID?: string | number;
|
||||||
|
status?: string;
|
||||||
|
graded?: boolean;
|
||||||
|
availability?: string;
|
||||||
|
due?: string;
|
||||||
|
results?: { percentage?: unknown; score?: unknown };
|
||||||
|
};
|
||||||
@@ -11,20 +11,18 @@ import { ensurePdfjsWorker, getPdfjsPageContextUrls } from "@/lib/pdfjsExtension
|
|||||||
import * as pdfjs from "pdfjs-dist";
|
import * as pdfjs from "pdfjs-dist";
|
||||||
import { extractWeightFromCoversheetText } from "./extractWeightFromCoversheetText";
|
import { extractWeightFromCoversheetText } from "./extractWeightFromCoversheetText";
|
||||||
import { delay } from "@/seqta/utils/delay";
|
import { delay } from "@/seqta/utils/delay";
|
||||||
|
import type {
|
||||||
|
AssessmentMark,
|
||||||
|
AssessmentsAverageApi,
|
||||||
|
WeightingEntry,
|
||||||
|
WeightingsMap,
|
||||||
|
} from "./pluginApi";
|
||||||
|
|
||||||
export { extractWeightFromCoversheetText };
|
export { extractWeightFromCoversheetText };
|
||||||
|
export type { WeightingEntry, WeightingsMap } from "./pluginApi";
|
||||||
|
|
||||||
export const WEIGHTING_SCHEMA_VERSION = 1;
|
export const WEIGHTING_SCHEMA_VERSION = 1;
|
||||||
|
|
||||||
export interface WeightingEntry {
|
|
||||||
weight: string;
|
|
||||||
fingerprint: string;
|
|
||||||
pluginVersion: number;
|
|
||||||
refreshing?: boolean;
|
|
||||||
}
|
|
||||||
|
|
||||||
export type WeightingsMap = Record<string, WeightingEntry>;
|
|
||||||
|
|
||||||
/** Primary storage key for weightings / overrides. */
|
/** Primary storage key for weightings / overrides. */
|
||||||
export function assessmentIdKey(mark: { id: string | number }): string {
|
export function assessmentIdKey(mark: { id: string | number }): string {
|
||||||
return String(mark.id);
|
return String(mark.id);
|
||||||
@@ -44,7 +42,7 @@ export function assessmentTitleLookupKey(mark: {
|
|||||||
return title;
|
return title;
|
||||||
}
|
}
|
||||||
|
|
||||||
function registerAssessmentLookup(api: any, mark: any) {
|
function registerAssessmentLookup(api: AssessmentsAverageApi, mark: AssessmentMark) {
|
||||||
const assessmentID = assessmentIdKey(mark);
|
const assessmentID = assessmentIdKey(mark);
|
||||||
const next: Record<string, string> = {
|
const next: Record<string, string> = {
|
||||||
...api.storage.assessments,
|
...api.storage.assessments,
|
||||||
@@ -71,7 +69,7 @@ function collectMarksFromFiberState(state: Record<string, unknown>): MarkLike[]
|
|||||||
}
|
}
|
||||||
|
|
||||||
async function resolveAssessmentId(
|
async function resolveAssessmentId(
|
||||||
api: any,
|
api: AssessmentsAverageApi,
|
||||||
title: string,
|
title: string,
|
||||||
marks?: MarkLike[],
|
marks?: MarkLike[],
|
||||||
): Promise<string | undefined> {
|
): Promise<string | undefined> {
|
||||||
@@ -109,7 +107,7 @@ async function resolveAssessmentId(
|
|||||||
return undefined;
|
return undefined;
|
||||||
}
|
}
|
||||||
|
|
||||||
export function computeFingerprint(mark: any): string {
|
export function computeFingerprint(mark: AssessmentMark): string {
|
||||||
const score = mark?.results?.percentage ?? mark?.results?.score ?? null;
|
const score = mark?.results?.percentage ?? mark?.results?.score ?? null;
|
||||||
return JSON.stringify([
|
return JSON.stringify([
|
||||||
mark?.status ?? "",
|
mark?.status ?? "",
|
||||||
@@ -121,7 +119,7 @@ export function computeFingerprint(mark: any): string {
|
|||||||
]);
|
]);
|
||||||
}
|
}
|
||||||
|
|
||||||
function migrateWeightings(api: any) {
|
function migrateWeightings(api: AssessmentsAverageApi) {
|
||||||
const w = api.storage.weightings ?? {};
|
const w = api.storage.weightings ?? {};
|
||||||
let dirty = false;
|
let dirty = false;
|
||||||
const out: WeightingsMap = {};
|
const out: WeightingsMap = {};
|
||||||
@@ -150,7 +148,7 @@ function migrateWeightings(api: any) {
|
|||||||
if (dirty) api.storage.weightings = out;
|
if (dirty) api.storage.weightings = out;
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function initStorage(api: any) {
|
export async function initStorage(api: AssessmentsAverageApi) {
|
||||||
await api.storage.loaded;
|
await api.storage.loaded;
|
||||||
|
|
||||||
if (!api.storage.weightings) {
|
if (!api.storage.weightings) {
|
||||||
@@ -166,7 +164,7 @@ export async function initStorage(api: any) {
|
|||||||
migrateWeightings(api);
|
migrateWeightings(api);
|
||||||
}
|
}
|
||||||
|
|
||||||
export function clearStuck(api: any) {
|
export function clearStuck(api: AssessmentsAverageApi) {
|
||||||
const map = (api.storage.weightings ?? {}) as WeightingsMap;
|
const map = (api.storage.weightings ?? {}) as WeightingsMap;
|
||||||
let dirty = false;
|
let dirty = false;
|
||||||
const out: WeightingsMap = {};
|
const out: WeightingsMap = {};
|
||||||
@@ -237,14 +235,15 @@ function formatWeightDisplay(weighting: string): string {
|
|||||||
}
|
}
|
||||||
|
|
||||||
function saveWeightingOverride(
|
function saveWeightingOverride(
|
||||||
api: any,
|
api: AssessmentsAverageApi,
|
||||||
assessmentID: string,
|
assessmentID: string,
|
||||||
raw: string,
|
raw: string,
|
||||||
): { ok: boolean; error?: string } {
|
): { ok: boolean; error?: string } {
|
||||||
const trimmed = raw.trim();
|
const trimmed = raw.trim();
|
||||||
if (trimmed === "") {
|
if (trimmed === "") {
|
||||||
const { [assessmentID]: _, ...rest } = api.storage.weightingOverrides;
|
const overrides = { ...api.storage.weightingOverrides };
|
||||||
api.storage.weightingOverrides = rest;
|
delete overrides[assessmentID];
|
||||||
|
api.storage.weightingOverrides = overrides;
|
||||||
document.dispatchEvent(new CustomEvent("betterseqta:overrideChanged"));
|
document.dispatchEvent(new CustomEvent("betterseqta:overrideChanged"));
|
||||||
return { ok: true };
|
return { ok: true };
|
||||||
}
|
}
|
||||||
@@ -262,7 +261,11 @@ function saveWeightingOverride(
|
|||||||
return { ok: true };
|
return { ok: true };
|
||||||
}
|
}
|
||||||
|
|
||||||
function attachWeightInputListeners(input: HTMLInputElement, api: any, assessmentID: string) {
|
function attachWeightInputListeners(
|
||||||
|
input: HTMLInputElement,
|
||||||
|
api: AssessmentsAverageApi,
|
||||||
|
assessmentID: string,
|
||||||
|
) {
|
||||||
const save = () => {
|
const save = () => {
|
||||||
const result = saveWeightingOverride(api, assessmentID, input.value);
|
const result = saveWeightingOverride(api, assessmentID, input.value);
|
||||||
input.style.borderColor = result.ok ? "rgba(128,128,128,0.35)" : "rgba(255,80,80,0.6)";
|
input.style.borderColor = result.ok ? "rgba(128,128,128,0.35)" : "rgba(255,80,80,0.6)";
|
||||||
@@ -278,7 +281,7 @@ function updateWeightLabelContent(
|
|||||||
weightLabel: HTMLElement,
|
weightLabel: HTMLElement,
|
||||||
weighting: string | undefined,
|
weighting: string | undefined,
|
||||||
assessmentID: string | undefined,
|
assessmentID: string | undefined,
|
||||||
api: any,
|
api: AssessmentsAverageApi,
|
||||||
refreshing = false,
|
refreshing = false,
|
||||||
) {
|
) {
|
||||||
const existingInput = weightLabel.querySelector(
|
const existingInput = weightLabel.querySelector(
|
||||||
@@ -333,7 +336,7 @@ function updateWeightLabelContent(
|
|||||||
function createWeightLabel(
|
function createWeightLabel(
|
||||||
assessmentItem: HTMLElement,
|
assessmentItem: HTMLElement,
|
||||||
weighting: string | undefined,
|
weighting: string | undefined,
|
||||||
api: any,
|
api: AssessmentsAverageApi,
|
||||||
refreshing = false,
|
refreshing = false,
|
||||||
assessmentID?: string,
|
assessmentID?: string,
|
||||||
) {
|
) {
|
||||||
@@ -496,11 +499,12 @@ async function fetchPDFAsArrayBuffer(url: string): Promise<ArrayBuffer> {
|
|||||||
}
|
}
|
||||||
|
|
||||||
return await response.arrayBuffer();
|
return await response.arrayBuffer();
|
||||||
} catch (error: any) {
|
} catch (error: unknown) {
|
||||||
|
const message = error instanceof Error ? error.message : String(error);
|
||||||
if (
|
if (
|
||||||
error?.message?.includes("blob") ||
|
message.includes("blob") ||
|
||||||
error?.message?.includes("Security") ||
|
message.includes("Security") ||
|
||||||
error?.message?.includes("CSP")
|
message.includes("CSP")
|
||||||
) {
|
) {
|
||||||
return await fetchPDFAsArrayBuffer(url);
|
return await fetchPDFAsArrayBuffer(url);
|
||||||
}
|
}
|
||||||
@@ -631,7 +635,7 @@ export async function extractPDFText(url: string): Promise<string> {
|
|||||||
for (let i = 1; i <= pdf.numPages; i++) {
|
for (let i = 1; i <= pdf.numPages; i++) {
|
||||||
const page = await pdf.getPage(i);
|
const page = await pdf.getPage(i);
|
||||||
const content = await page.getTextContent();
|
const content = await page.getTextContent();
|
||||||
text += content.items.map((item: any) => item.str).join(" ") + "\n";
|
text += content.items.map((item) => ("str" in item ? String(item.str) : "")).join(" ") + "\n";
|
||||||
}
|
}
|
||||||
|
|
||||||
return text;
|
return text;
|
||||||
@@ -706,9 +710,21 @@ async function extractPDFTextWithRetry(url: string, attempts = 3, delayMs = 1500
|
|||||||
throw lastError;
|
throw lastError;
|
||||||
}
|
}
|
||||||
|
|
||||||
async function handleWeightings(mark: any, api: any) {
|
async function handleWeightings(mark: AssessmentMark, api: AssessmentsAverageApi) {
|
||||||
const assessmentID = assessmentIdKey(mark);
|
const assessmentID = assessmentIdKey(mark);
|
||||||
const metaclassID = mark.metaclassID;
|
const metaclassID = mark.metaclassID;
|
||||||
|
if (metaclassID == null || metaclassID === "") {
|
||||||
|
api.storage.weightings = {
|
||||||
|
...api.storage.weightings,
|
||||||
|
[assessmentID]: {
|
||||||
|
weight: "N/A",
|
||||||
|
fingerprint: computeFingerprint(mark),
|
||||||
|
pluginVersion: WEIGHTING_SCHEMA_VERSION,
|
||||||
|
},
|
||||||
|
};
|
||||||
|
document.dispatchEvent(new CustomEvent("betterseqta:weightingsChanged"));
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
const fingerprint = computeFingerprint(mark);
|
const fingerprint = computeFingerprint(mark);
|
||||||
const existing = api.storage.weightings[assessmentID] as WeightingEntry | undefined;
|
const existing = api.storage.weightings[assessmentID] as WeightingEntry | undefined;
|
||||||
@@ -799,18 +815,19 @@ async function handleWeightings(mark: any, api: any) {
|
|||||||
let text: string;
|
let text: string;
|
||||||
try {
|
try {
|
||||||
text = await extractPDFTextWithRetry(pdfUrl);
|
text = await extractPDFTextWithRetry(pdfUrl);
|
||||||
} catch (error: any) {
|
} catch (error: unknown) {
|
||||||
|
const message = error instanceof Error ? error.message : String(error);
|
||||||
if (
|
if (
|
||||||
isFirefox &&
|
isFirefox &&
|
||||||
(error?.message?.includes("blob") ||
|
(message.includes("blob") ||
|
||||||
error?.message?.includes("Security") ||
|
message.includes("Security") ||
|
||||||
error?.message?.includes("CSP") ||
|
message.includes("CSP") ||
|
||||||
error?.message?.includes("empty"))
|
message.includes("empty"))
|
||||||
) {
|
) {
|
||||||
await delay(2000);
|
await delay(2000);
|
||||||
text = await extractPDFTextWithRetry(pdfUrl, 2, 2000);
|
text = await extractPDFTextWithRetry(pdfUrl, 2, 2000);
|
||||||
} else {
|
} else {
|
||||||
throw new Error(`PDF extraction failed: ${error.message}`, { cause: error });
|
throw new Error(`PDF extraction failed: ${message}`, { cause: error });
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -824,8 +841,8 @@ async function handleWeightings(mark: any, api: any) {
|
|||||||
pluginVersion: WEIGHTING_SCHEMA_VERSION,
|
pluginVersion: WEIGHTING_SCHEMA_VERSION,
|
||||||
},
|
},
|
||||||
};
|
};
|
||||||
} catch (error: any) {
|
} catch (error: unknown) {
|
||||||
console.error("[BetterSEQTA+] Weighting fetch failed for assessment %s:", assessmentID, error);
|
console.error("[BetterSEQTA+] Weighting fetch failed for assessment:", assessmentID, error);
|
||||||
api.storage.weightings = {
|
api.storage.weightings = {
|
||||||
...api.storage.weightings,
|
...api.storage.weightings,
|
||||||
[assessmentID]: {
|
[assessmentID]: {
|
||||||
@@ -839,7 +856,7 @@ async function handleWeightings(mark: any, api: any) {
|
|||||||
document.dispatchEvent(new CustomEvent("betterseqta:weightingsChanged"));
|
document.dispatchEvent(new CustomEvent("betterseqta:weightingsChanged"));
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function parseAssessments(api: any) {
|
export async function parseAssessments(api: AssessmentsAverageApi) {
|
||||||
const state = await ReactFiber.find("[class*='AssessmentList__items___']").getState();
|
const state = await ReactFiber.find("[class*='AssessmentList__items___']").getState();
|
||||||
|
|
||||||
const marks = [
|
const marks = [
|
||||||
@@ -850,10 +867,10 @@ export async function parseAssessments(api: any) {
|
|||||||
];
|
];
|
||||||
if (!marks) return;
|
if (!marks) return;
|
||||||
|
|
||||||
await Promise.all(marks.map((mark: any) => handleWeightings(mark, api)));
|
await Promise.all(marks.map((mark: AssessmentMark) => handleWeightings(mark, api)));
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function processAssessments(api: any, assessmentItems: HTMLElement[]) {
|
export async function processAssessments(api: AssessmentsAverageApi, assessmentItems: HTMLElement[]) {
|
||||||
let weightedTotal = 0;
|
let weightedTotal = 0;
|
||||||
let totalWeight = 0;
|
let totalWeight = 0;
|
||||||
let hasInaccurateWeighting = false;
|
let hasInaccurateWeighting = false;
|
||||||
@@ -992,7 +1009,7 @@ interface WeightingTabContext {
|
|||||||
statusNote: string;
|
statusNote: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
async function resolveWeightingTabContext(api: any): Promise<WeightingTabContext> {
|
async function resolveWeightingTabContext(api: AssessmentsAverageApi): Promise<WeightingTabContext> {
|
||||||
const selectedItem = document.querySelector(
|
const selectedItem = document.querySelector(
|
||||||
"[class*='AssessmentItem__AssessmentItem___'][class*='selected___']",
|
"[class*='AssessmentItem__AssessmentItem___'][class*='selected___']",
|
||||||
) as HTMLElement | null;
|
) as HTMLElement | null;
|
||||||
@@ -1077,7 +1094,11 @@ function renderWeightingTabHtml(sheet: HTMLElement, context: WeightingTabContext
|
|||||||
`;
|
`;
|
||||||
}
|
}
|
||||||
|
|
||||||
function attachWeightingInputHandlers(sheet: HTMLElement, api: any, assessmentID: string) {
|
function attachWeightingInputHandlers(
|
||||||
|
sheet: HTMLElement,
|
||||||
|
api: AssessmentsAverageApi,
|
||||||
|
assessmentID: string,
|
||||||
|
) {
|
||||||
const input = sheet.querySelector("#betterseqta-weight-override") as HTMLInputElement;
|
const input = sheet.querySelector("#betterseqta-weight-override") as HTMLInputElement;
|
||||||
const statusEl = sheet.querySelector(".betterseqta-save-status") as HTMLElement;
|
const statusEl = sheet.querySelector(".betterseqta-save-status") as HTMLElement;
|
||||||
|
|
||||||
@@ -1112,14 +1133,14 @@ function attachWeightingInputHandlers(sheet: HTMLElement, api: any, assessmentID
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
async function buildWeightingsTabContent(api: any, sheet: HTMLElement) {
|
async function buildWeightingsTabContent(api: AssessmentsAverageApi, sheet: HTMLElement) {
|
||||||
const context = await resolveWeightingTabContext(api);
|
const context = await resolveWeightingTabContext(api);
|
||||||
renderWeightingTabHtml(sheet, context);
|
renderWeightingTabHtml(sheet, context);
|
||||||
if (!context.assessmentID) return;
|
if (!context.assessmentID) return;
|
||||||
attachWeightingInputHandlers(sheet, api, context.assessmentID);
|
attachWeightingInputHandlers(sheet, api, context.assessmentID);
|
||||||
}
|
}
|
||||||
|
|
||||||
export function injectWeightingsTab(api: any) {
|
export function injectWeightingsTab(api: AssessmentsAverageApi) {
|
||||||
const tabList = document.querySelector('[class*="TabSet__tabs___"]') as HTMLElement;
|
const tabList = document.querySelector('[class*="TabSet__tabs___"]') as HTMLElement;
|
||||||
const container = document.querySelector('[class*="TabSet__tabContainer___"]') as HTMLElement;
|
const container = document.querySelector('[class*="TabSet__tabContainer___"]') as HTMLElement;
|
||||||
if (!tabList || !container) return;
|
if (!tabList || !container) return;
|
||||||
|
|||||||
@@ -116,7 +116,7 @@ async function loadSubmissions(student: number, assessments: any[]) {
|
|||||||
|
|
||||||
submissionMap[assessment.id] = res.payload && res.payload.length > 0;
|
submissionMap[assessment.id] = res.payload && res.payload.length > 0;
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.warn(`Failed to fetch submission for assessment ${assessment.id}:`, error);
|
console.warn("Failed to fetch submission for assessment:", assessment.id, error);
|
||||||
submissionMap[assessment.id] = false;
|
submissionMap[assessment.id] = false;
|
||||||
}
|
}
|
||||||
}),
|
}),
|
||||||
|
|||||||
@@ -186,7 +186,21 @@ export function readStoredList(key: string): unknown[] {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
export function determineStatus(item: any, completed: readonly unknown[]): string {
|
export type OverviewAssessment = Record<string, unknown>;
|
||||||
|
|
||||||
|
function readNumber(value: unknown): number | null {
|
||||||
|
if (value === undefined || value === null) return null;
|
||||||
|
const n = Number(value);
|
||||||
|
return Number.isNaN(n) ? null : n;
|
||||||
|
}
|
||||||
|
|
||||||
|
function readNestedRecord(
|
||||||
|
value: unknown,
|
||||||
|
): Record<string, unknown> | undefined {
|
||||||
|
return value && typeof value === "object" ? (value as Record<string, unknown>) : undefined;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function determineStatus(item: OverviewAssessment, completed: readonly unknown[]): string {
|
||||||
if (
|
if (
|
||||||
item.status === "MARKS_RELEASED" ||
|
item.status === "MARKS_RELEASED" ||
|
||||||
item.grade ||
|
item.grade ||
|
||||||
@@ -205,7 +219,7 @@ export function determineStatus(item: any, completed: readonly unknown[]): strin
|
|||||||
}
|
}
|
||||||
|
|
||||||
const now = new Date();
|
const now = new Date();
|
||||||
const due = new Date(item.due);
|
const due = new Date(String(item.due ?? ""));
|
||||||
|
|
||||||
const diffTime = due.getTime() - now.getTime();
|
const diffTime = due.getTime() - now.getTime();
|
||||||
const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24));
|
const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24));
|
||||||
@@ -221,43 +235,37 @@ export function determineStatus(item: any, completed: readonly unknown[]): strin
|
|||||||
return "UPCOMING";
|
return "UPCOMING";
|
||||||
}
|
}
|
||||||
|
|
||||||
export function getGradeValue(assessment: any): number | null {
|
export function getGradeValue(assessment: OverviewAssessment): number | null {
|
||||||
if (assessment.results?.percentage !== undefined && assessment.results.percentage !== null) {
|
const results = readNestedRecord(assessment.results);
|
||||||
return assessment.results.percentage;
|
|
||||||
|
const fromResultsPct = readNumber(results?.percentage);
|
||||||
|
if (fromResultsPct !== null) return fromResultsPct;
|
||||||
|
|
||||||
|
const fromPct = readNumber(assessment.percentage);
|
||||||
|
if (fromPct !== null) return fromPct;
|
||||||
|
|
||||||
|
const achieved = readNumber(assessment.achieved);
|
||||||
|
const outOf = readNumber(assessment.outOf);
|
||||||
|
if (achieved !== null && outOf !== null && outOf > 0) {
|
||||||
|
return (achieved / outOf) * 100;
|
||||||
}
|
}
|
||||||
|
|
||||||
if (assessment.percentage !== undefined && assessment.percentage !== null) {
|
const resAchieved = readNumber(results?.achieved);
|
||||||
return assessment.percentage;
|
const resOutOf = readNumber(results?.outOf);
|
||||||
}
|
if (resAchieved !== null && resOutOf !== null && resOutOf > 0) {
|
||||||
|
return (resAchieved / resOutOf) * 100;
|
||||||
if (
|
|
||||||
assessment.achieved !== undefined &&
|
|
||||||
assessment.outOf !== undefined &&
|
|
||||||
assessment.achieved !== null &&
|
|
||||||
assessment.outOf !== null &&
|
|
||||||
assessment.outOf > 0
|
|
||||||
) {
|
|
||||||
return (assessment.achieved / assessment.outOf) * 100;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (
|
|
||||||
assessment.results?.achieved !== undefined &&
|
|
||||||
assessment.results?.outOf !== undefined &&
|
|
||||||
assessment.results.achieved !== null &&
|
|
||||||
assessment.results.outOf !== null &&
|
|
||||||
assessment.results.outOf > 0
|
|
||||||
) {
|
|
||||||
return (assessment.results.achieved / assessment.results.outOf) * 100;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
|
|
||||||
export function extractAssessmentLetterGrade(assessment: any): string | undefined {
|
export function extractAssessmentLetterGrade(assessment: OverviewAssessment): string | undefined {
|
||||||
if (assessment?.grade != null && String(assessment.grade).trim() !== "") {
|
if (assessment?.grade != null && String(assessment.grade).trim() !== "") {
|
||||||
return String(assessment.grade).trim();
|
return String(assessment.grade).trim();
|
||||||
}
|
}
|
||||||
return extractLetterGradeStringFromPayload(assessment);
|
return extractLetterGradeStringFromPayload(assessment as Parameters<
|
||||||
|
typeof extractLetterGradeStringFromPayload
|
||||||
|
>[0]);
|
||||||
}
|
}
|
||||||
|
|
||||||
export function percentageToLetterGrade(percentage: number): string {
|
export function percentageToLetterGrade(percentage: number): string {
|
||||||
@@ -284,7 +292,7 @@ export function percentageToLetterGrade(percentage: number): string {
|
|||||||
return letterMap[rounded] || "F";
|
return letterMap[rounded] || "F";
|
||||||
}
|
}
|
||||||
|
|
||||||
export function getThermoscorePercent(assessment: any): number | null {
|
export function getThermoscorePercent(assessment: OverviewAssessment): number | null {
|
||||||
const numeric = getGradeValue(assessment);
|
const numeric = getGradeValue(assessment);
|
||||||
if (numeric !== null) return numeric;
|
if (numeric !== null) return numeric;
|
||||||
|
|
||||||
@@ -297,7 +305,7 @@ export function getThermoscorePercent(assessment: any): number | null {
|
|||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
|
|
||||||
export function getDisplayGrade(assessment: any, letterGradeMode: boolean): string {
|
export function getDisplayGrade(assessment: OverviewAssessment, letterGradeMode: boolean): string {
|
||||||
if (letterGradeMode) {
|
if (letterGradeMode) {
|
||||||
const letter = extractAssessmentLetterGrade(assessment);
|
const letter = extractAssessmentLetterGrade(assessment);
|
||||||
if (letter) return letter;
|
if (letter) return letter;
|
||||||
@@ -317,7 +325,7 @@ export function getDisplayGrade(assessment: any, letterGradeMode: boolean): stri
|
|||||||
return "No grade";
|
return "No grade";
|
||||||
}
|
}
|
||||||
|
|
||||||
export function assessmentHasGradeDisplay(assessment: any): boolean {
|
export function assessmentHasGradeDisplay(assessment: OverviewAssessment): boolean {
|
||||||
if (extractAssessmentLetterGrade(assessment)) return true;
|
if (extractAssessmentLetterGrade(assessment)) return true;
|
||||||
if (getGradeValue(assessment) !== null) return true;
|
if (getGradeValue(assessment) !== null) return true;
|
||||||
return false;
|
return false;
|
||||||
|
|||||||
@@ -208,7 +208,7 @@ export const notificationsJob: Job = {
|
|||||||
]);
|
]);
|
||||||
return inAssessments || inMessages;
|
return inAssessments || inMessages;
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.warn(`[Notifications job] Error checking if notification ${id} is indexed:`, error);
|
console.warn("[Notifications job] Error checking if notification is indexed:", id, error);
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
@@ -292,7 +292,7 @@ export const notificationsJob: Job = {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error(`[Notifications job] Failed to process notification ${id}:`, error);
|
console.error("[Notifications job] Failed to process notification:", id, error);
|
||||||
|
|
||||||
if (progress.retryQueue.length < 10) {
|
if (progress.retryQueue.length < 10) {
|
||||||
progress.retryQueue.push(notif.notificationID);
|
progress.retryQueue.push(notif.notificationID);
|
||||||
@@ -443,7 +443,7 @@ async function processNotification(
|
|||||||
|
|
||||||
return { success: false };
|
return { success: false };
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error(`[Notifications job] Error processing notification ${id}:`, error);
|
console.error("[Notifications job] Error processing notification:", id, error);
|
||||||
return { success: false };
|
return { success: false };
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -120,7 +120,7 @@ async function vectorizeItem(
|
|||||||
const embedding = await getEmbedding(textToEmbed);
|
const embedding = await getEmbedding(textToEmbed);
|
||||||
return { ...item, embedding };
|
return { ...item, embedding };
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error(`Error vectorizing item ${item.id}:`, error);
|
console.error("Error vectorizing item:", item.id, error);
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -555,7 +555,7 @@ export class ThemeManager {
|
|||||||
/**
|
/**
|
||||||
* Fetch JSON from a URL via background script (avoids CORS when running inside SEQTA page)
|
* Fetch JSON from a URL via background script (avoids CORS when running inside SEQTA page)
|
||||||
*/
|
*/
|
||||||
private async fetchFromUrl(url: string, options?: { auth?: boolean }): Promise<any> {
|
private async fetchFromUrl(url: string, options?: { auth?: boolean }): Promise<unknown> {
|
||||||
const result = (await browser.runtime.sendMessage({
|
const result = (await browser.runtime.sendMessage({
|
||||||
type: "fetchFromUrl",
|
type: "fetchFromUrl",
|
||||||
url,
|
url,
|
||||||
|
|||||||
@@ -97,7 +97,7 @@ function createSettingsAPI<T extends PluginSettings>(
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error(`[BetterSEQTA+] Error loading settings for plugin ${plugin.id}:`, error);
|
console.error("[BetterSEQTA+] Error loading settings for plugin:", plugin.id, error);
|
||||||
}
|
}
|
||||||
})();
|
})();
|
||||||
|
|
||||||
@@ -177,7 +177,7 @@ function createStorageAPI<T = any>(
|
|||||||
}
|
}
|
||||||
});
|
});
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error(`[BetterSEQTA+] Error loading storage for plugin ${pluginId}:`, error);
|
console.error("[BetterSEQTA+] Error loading storage for plugin:", pluginId, error);
|
||||||
}
|
}
|
||||||
})();
|
})();
|
||||||
|
|
||||||
|
|||||||
@@ -143,7 +143,7 @@ export class PluginManager {
|
|||||||
}
|
}
|
||||||
|
|
||||||
if (this.runningPlugins.get(pluginId)) {
|
if (this.runningPlugins.get(pluginId)) {
|
||||||
console.warn(`Plugin "${pluginId}" is already running`);
|
console.warn("Plugin is already running:", pluginId);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -184,7 +184,7 @@ export class PluginManager {
|
|||||||
} catch (error) {
|
} catch (error) {
|
||||||
this.removePluginStyles(pluginId);
|
this.removePluginStyles(pluginId);
|
||||||
this.disposePluginAPI(pluginId);
|
this.disposePluginAPI(pluginId);
|
||||||
console.error(`[BetterSEQTA+] Failed to start plugin ${pluginId}:`, error);
|
console.error("[BetterSEQTA+] Failed to start plugin:", pluginId, error);
|
||||||
throw error;
|
throw error;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -227,7 +227,7 @@ export class PluginManager {
|
|||||||
|
|
||||||
const startPromises = idsToStart.map((id) =>
|
const startPromises = idsToStart.map((id) =>
|
||||||
this.startPlugin(id).catch((error) => {
|
this.startPlugin(id).catch((error) => {
|
||||||
console.error(`Failed to start plugin "${id}":`, error);
|
console.error("Failed to start plugin:", id, error);
|
||||||
return Promise.reject(error);
|
return Promise.reject(error);
|
||||||
}),
|
}),
|
||||||
);
|
);
|
||||||
|
|||||||
+9
-22
@@ -1,7 +1,4 @@
|
|||||||
import {
|
import { initializeSettingsState, settingsState } from "@/seqta/utils/listeners/SettingsState";
|
||||||
initializeSettingsState,
|
|
||||||
settingsState,
|
|
||||||
} from "@/seqta/utils/listeners/SettingsState";
|
|
||||||
import documentLoadCSS from "@/css/documentload.scss?inline";
|
import documentLoadCSS from "@/css/documentload.scss?inline";
|
||||||
import icon48 from "@/resources/icons/icon-48.png?base64";
|
import icon48 from "@/resources/icons/icon-48.png?base64";
|
||||||
import browser from "@/lib/browser";
|
import browser from "@/lib/browser";
|
||||||
@@ -57,13 +54,10 @@ export function boot() {
|
|||||||
|
|
||||||
async function init() {
|
async function init() {
|
||||||
const hasSEQTAText =
|
const hasSEQTAText =
|
||||||
document.childNodes[1]?.textContent?.includes(
|
document.childNodes[1]?.textContent?.includes("Copyright (c) SEQTA Software") ?? false;
|
||||||
"Copyright (c) SEQTA Software",
|
|
||||||
) ?? false;
|
|
||||||
if (
|
if (
|
||||||
hasSEQTAText &&
|
hasSEQTAText &&
|
||||||
(document.title.includes("SEQTA Learn") ||
|
(document.title.includes("SEQTA Learn") || document.title.includes("SEQTA Engage")) &&
|
||||||
document.title.includes("SEQTA Engage")) &&
|
|
||||||
!IsSEQTAPage
|
!IsSEQTAPage
|
||||||
) {
|
) {
|
||||||
IsSEQTAPage = true;
|
IsSEQTAPage = true;
|
||||||
@@ -79,7 +73,6 @@ async function init() {
|
|||||||
|
|
||||||
const observer = new MutationObserver((mutations) => {
|
const observer = new MutationObserver((mutations) => {
|
||||||
for (const mutation of mutations) {
|
for (const mutation of mutations) {
|
||||||
|
|
||||||
if (
|
if (
|
||||||
mutation.type === "attributes" &&
|
mutation.type === "attributes" &&
|
||||||
mutation.target instanceof HTMLLinkElement &&
|
mutation.target instanceof HTMLLinkElement &&
|
||||||
@@ -98,8 +91,6 @@ async function init() {
|
|||||||
attributeFilter: ["href"],
|
attributeFilter: ["href"],
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
try {
|
try {
|
||||||
await initializeSettingsState();
|
await initializeSettingsState();
|
||||||
initVerboseLogging();
|
initVerboseLogging();
|
||||||
@@ -141,9 +132,7 @@ async function init() {
|
|||||||
sessionStorage.removeItem("bsplus-dev-export-recovery");
|
sessionStorage.removeItem("bsplus-dev-export-recovery");
|
||||||
}
|
}
|
||||||
|
|
||||||
verboseInfo(
|
verboseInfo("[BetterSEQTA+] Successfully initialised BetterSEQTA+, starting to load assets.");
|
||||||
"[BetterSEQTA+] Successfully initialised BetterSEQTA+, starting to load assets.",
|
|
||||||
);
|
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error(error);
|
console.error(error);
|
||||||
recoverFromStaleDevModuleGraph(error);
|
recoverFromStaleDevModuleGraph(error);
|
||||||
@@ -152,11 +141,9 @@ async function init() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
function replaceIcons() {
|
function replaceIcons() {
|
||||||
document
|
document.querySelectorAll<HTMLLinkElement>('link[rel*="icon"]').forEach((link) => {
|
||||||
.querySelectorAll<HTMLLinkElement>('link[rel*="icon"]')
|
if (link.href !== icon48) {
|
||||||
.forEach((link) => {
|
link.href = icon48;
|
||||||
if (link.href !== icon48) {
|
}
|
||||||
link.href = icon48;
|
});
|
||||||
}
|
|
||||||
});
|
|
||||||
}
|
}
|
||||||
@@ -1,25 +1,18 @@
|
|||||||
import browser from "@/lib/browser";
|
import browser from "@/lib/browser";
|
||||||
import {
|
import { isSeqta404Page, mountErrorPageKitten } from "@/plugins/built-in/errorPageKitten";
|
||||||
isSeqta404Page,
|
|
||||||
mountErrorPageKitten,
|
|
||||||
} from "@/plugins/built-in/errorPageKitten";
|
|
||||||
|
|
||||||
/** Hide the rebranded 404 before the kitten card mounts (removed after boot). */
|
/** Hide the rebranded 404 before the kitten card mounts (removed after boot). */
|
||||||
function inject404FlashHide(): void {
|
function inject404FlashHide(): void {
|
||||||
if (document.getElementById("bsplus-404-flash-hide")) return;
|
if (document.getElementById("bsplus-404-flash-hide")) return;
|
||||||
const style = document.createElement("style");
|
const style = document.createElement("style");
|
||||||
style.id = "bsplus-404-flash-hide";
|
style.id = "bsplus-404-flash-hide";
|
||||||
style.textContent =
|
style.textContent = "html,body{background:#333!important}.message{display:none!important}";
|
||||||
"html,body{background:#333!important}.message{display:none!important}";
|
|
||||||
(document.head ?? document.documentElement).appendChild(style);
|
(document.head ?? document.documentElement).appendChild(style);
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Loaded on demand by SEQTA.ts for pages that aren't the SEQTA app. */
|
/** Loaded on demand by SEQTA.ts for pages that aren't the SEQTA app. */
|
||||||
export async function bootErrorPage() {
|
export async function bootErrorPage() {
|
||||||
const storagePromise = browser.storage.local.get([
|
const storagePromise = browser.storage.local.get(["onoff", "plugin.error-page-kitten.settings"]);
|
||||||
"onoff",
|
|
||||||
"plugin.error-page-kitten.settings",
|
|
||||||
]);
|
|
||||||
|
|
||||||
const watchTitle = () => {
|
const watchTitle = () => {
|
||||||
if (isSeqta404Page()) inject404FlashHide();
|
if (isSeqta404Page()) inject404FlashHide();
|
||||||
|
|||||||
@@ -18,12 +18,13 @@ function stripPlaceholders(html: string): string {
|
|||||||
return html.replace(PLACEHOLDER_RE, "");
|
return html.replace(PLACEHOLDER_RE, "");
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function htmlToPlainText(html: string): string {
|
||||||
|
return new DOMParser().parseFromString(html, "text/html").body.textContent ?? "";
|
||||||
|
}
|
||||||
|
|
||||||
function noticePreview(contents: string): string {
|
function noticePreview(contents: string): string {
|
||||||
const text = stripPlaceholders(contents)
|
const text = htmlToPlainText(stripPlaceholders(contents)).replace(/\s+/g, " ").trim();
|
||||||
.replace(/<[^>]*>/g, "")
|
return text.substring(0, 150) + (text.length > 150 ? "..." : "");
|
||||||
.replace(/\s+/g, " ")
|
|
||||||
.trim();
|
|
||||||
return text.substring(0, 150) + (contents.length > 150 ? "..." : "");
|
|
||||||
}
|
}
|
||||||
|
|
||||||
function noticeBody(contents: string): string {
|
function noticeBody(contents: string): string {
|
||||||
|
|||||||
Reference in new issue
Block a user