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
+59
-27
@@ -13,10 +13,11 @@ import {
|
||||
} from "./background/cloudSettingsAutoSync";
|
||||
import { getBsplusDeviceName } from "@/seqta/utils/bsplusDeviceName";
|
||||
import { isAllowedFetchUrl } from "@/seqta/utils/allowedFetchUrl";
|
||||
import { initCalendarBackground } from "./background/calendarBackground";
|
||||
import {
|
||||
initCalendarBackground,
|
||||
registerGoogleCalendarMessageHandlers,
|
||||
registerOutlookCalendarMessageHandlers,
|
||||
type CalendarMessageHandlerMap,
|
||||
} from "./background/calendarBackground";
|
||||
import { createCustomThemesHandlers } from "./background/customThemesHandlers";
|
||||
import {
|
||||
@@ -50,7 +51,7 @@ function apiBase(): string {
|
||||
|
||||
function reloadSeqtaPages() {
|
||||
const result = browser.tabs.query({});
|
||||
function open(tabs: any) {
|
||||
function open(tabs: chrome.tabs.Tab[]) {
|
||||
for (const tab of tabs) {
|
||||
if (tab.title?.includes("SEQTA Learn") || tab.title?.includes("SEQTA Engage")) {
|
||||
browser.tabs.reload(tab.id);
|
||||
@@ -63,6 +64,14 @@ function reloadSeqtaPages() {
|
||||
/** Callback for sending a response back to the message sender */
|
||||
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> {
|
||||
const { bsplus_token } = await browser.storage.local.get("bsplus_token");
|
||||
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;
|
||||
}
|
||||
|
||||
function handleFetchThemeDetails(request: any, sendResponse: MessageSender): boolean {
|
||||
function handleFetchThemeDetails(request: BackgroundRequest, sendResponse: MessageSender): boolean {
|
||||
const { themeId } = request;
|
||||
if (!themeId || typeof themeId !== "string") {
|
||||
sendResponse({ success: false, error: "Missing themeId" });
|
||||
@@ -188,7 +197,7 @@ function isTrustedSender(sender?: chrome.runtime.MessageSender): boolean {
|
||||
}
|
||||
|
||||
function handleFetchFromUrl(
|
||||
request: any,
|
||||
request: BackgroundRequest,
|
||||
sendResponse: MessageSender,
|
||||
sender?: chrome.runtime.MessageSender,
|
||||
): boolean {
|
||||
@@ -238,7 +247,7 @@ function handleFetchFromUrl(
|
||||
return true;
|
||||
}
|
||||
|
||||
async function parseJsonResponse(r: Response): Promise<any> {
|
||||
async function parseJsonResponse(r: Response): Promise<unknown> {
|
||||
const text = await r.text();
|
||||
try {
|
||||
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 =
|
||||
request.redirect_uri ?? "https://accounts.betterseqta.org/auth/bsplus/callback";
|
||||
fetch("https://accounts.betterseqta.org/api/bsplus/client/reserve", {
|
||||
@@ -257,7 +266,11 @@ function handleCloudReserveClient(request: any, sendResponse: MessageSender): bo
|
||||
})
|
||||
.then(async (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);
|
||||
})
|
||||
.catch((err) => {
|
||||
@@ -268,7 +281,7 @@ function handleCloudReserveClient(request: any, sendResponse: MessageSender): bo
|
||||
}
|
||||
|
||||
function handleCloudLogin(
|
||||
request: any,
|
||||
request: BackgroundRequest,
|
||||
sendResponse: MessageSender,
|
||||
sender?: chrome.runtime.MessageSender,
|
||||
): boolean {
|
||||
@@ -276,7 +289,11 @@ function handleCloudLogin(
|
||||
sendResponse({ error: "Unauthorized sender" });
|
||||
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) {
|
||||
sendResponse({ error: "Missing client_id, redirect_uri, login, or password" });
|
||||
return false;
|
||||
@@ -296,7 +313,11 @@ function handleCloudLogin(
|
||||
body: JSON.stringify(loginBody),
|
||||
});
|
||||
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);
|
||||
} catch (err) {
|
||||
console.error("[Background] cloudLogin error:", err);
|
||||
@@ -306,8 +327,9 @@ function handleCloudLogin(
|
||||
return true;
|
||||
}
|
||||
|
||||
function handleCloudStartLogin(request: any, sendResponse: MessageSender): boolean {
|
||||
const { client_id, redirect_uri } = request;
|
||||
function handleCloudStartLogin(request: BackgroundRequest, sendResponse: MessageSender): boolean {
|
||||
const client_id = reqString(request, "client_id");
|
||||
const redirect_uri = reqString(request, "redirect_uri");
|
||||
if (!client_id || !redirect_uri) {
|
||||
sendResponse({ error: "Missing client_id or redirect_uri" });
|
||||
return true;
|
||||
@@ -373,7 +395,7 @@ function initCloudLoginCallbackListener() {
|
||||
|
||||
initCloudLoginCallbackListener();
|
||||
|
||||
function handleCloudRefresh(request: any, sendResponse: MessageSender): boolean {
|
||||
function handleCloudRefresh(request: BackgroundRequest, sendResponse: MessageSender): boolean {
|
||||
const { refresh_token, client_id } = request;
|
||||
if (!refresh_token || !client_id) {
|
||||
sendResponse({ error: "Missing refresh_token or client_id" });
|
||||
@@ -386,7 +408,11 @@ function handleCloudRefresh(request: any, sendResponse: MessageSender): boolean
|
||||
})
|
||||
.then(async (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);
|
||||
})
|
||||
.catch((err) => {
|
||||
@@ -463,7 +489,7 @@ function handleCloudSettingsDownload(
|
||||
return true;
|
||||
}
|
||||
|
||||
function handleCloudFavorite(request: any, sendResponse: MessageSender): boolean {
|
||||
function handleCloudFavorite(request: BackgroundRequest, sendResponse: MessageSender): boolean {
|
||||
const { themeId, action } = request;
|
||||
if (!themeId) {
|
||||
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) */
|
||||
type MessageHandler = {
|
||||
(
|
||||
request: any,
|
||||
request: BackgroundRequest,
|
||||
sendResponse: MessageSender,
|
||||
sender?: chrome.runtime.MessageSender,
|
||||
): boolean | void;
|
||||
@@ -509,7 +535,7 @@ function isSeqtaOrigin(origin: string): boolean {
|
||||
}
|
||||
|
||||
function handleSetDevApiBase(
|
||||
request: any,
|
||||
request: BackgroundRequest,
|
||||
_sendResponse: MessageSender,
|
||||
sender?: chrome.runtime.MessageSender,
|
||||
): boolean {
|
||||
@@ -571,7 +597,8 @@ const MESSAGE_HANDLERS: Record<string, MessageHandler> = {
|
||||
sendResponse({ error: "Unauthorized sender" });
|
||||
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;
|
||||
},
|
||||
fetchThemes: handleFetchThemes,
|
||||
@@ -635,13 +662,16 @@ const MESSAGE_HANDLERS: Record<string, MessageHandler> = {
|
||||
},
|
||||
};
|
||||
|
||||
registerGoogleCalendarMessageHandlers(MESSAGE_HANDLERS, isTrustedSender);
|
||||
registerOutlookCalendarMessageHandlers(MESSAGE_HANDLERS, isTrustedSender);
|
||||
registerGoogleCalendarMessageHandlers(MESSAGE_HANDLERS as CalendarMessageHandlerMap, isTrustedSender);
|
||||
registerOutlookCalendarMessageHandlers(
|
||||
MESSAGE_HANDLERS as CalendarMessageHandlerMap,
|
||||
isTrustedSender,
|
||||
);
|
||||
initCalendarBackground();
|
||||
|
||||
browser.runtime.onMessage.addListener(
|
||||
(request: any, sender: chrome.runtime.MessageSender, sendResponse: MessageSender) => {
|
||||
const handler = MESSAGE_HANDLERS[request.type];
|
||||
(request: BackgroundRequest, sender: chrome.runtime.MessageSender, sendResponse: MessageSender) => {
|
||||
const handler = MESSAGE_HANDLERS[request.type as string];
|
||||
if (handler) {
|
||||
const result = handler(request, sendResponse, sender);
|
||||
return result === true;
|
||||
@@ -681,11 +711,13 @@ browser.runtime.onInstalled.addListener(function (event) {
|
||||
if (event.reason === "install") {
|
||||
void refreshRemoteConfig(apiBase);
|
||||
void browser.storage.local.set({ [DEFAULT_BACKGROUND_PENDING_KEY]: true });
|
||||
void defaultsReady.catch(() => undefined).then(async () => {
|
||||
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 } });
|
||||
});
|
||||
void defaultsReady
|
||||
.catch(() => undefined)
|
||||
.then(async () => {
|
||||
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;
|
||||
}
|
||||
|
||||
async function parseJsonResponse(r: Response): Promise<any> {
|
||||
async function parseJsonResponse(r: Response): Promise<unknown> {
|
||||
const text = await r.text();
|
||||
try {
|
||||
return text ? JSON.parse(text) : {};
|
||||
|
||||
@@ -35,7 +35,7 @@ function buildFormDataFromPayload(payload: UploadPayload): FormData {
|
||||
export function createCustomThemesHandlers(deps: {
|
||||
apiBase: () => string;
|
||||
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>> {
|
||||
const text = await r.text();
|
||||
let body: unknown;
|
||||
@@ -95,7 +95,7 @@ export function createCustomThemesHandlers(deps: {
|
||||
return await readCustomThemesResponse(r);
|
||||
}
|
||||
|
||||
function handleFetchCustomThemes(request: any, sendResponse: MessageSender): boolean {
|
||||
function handleFetchCustomThemes(request: Record<string, unknown>, sendResponse: MessageSender): boolean {
|
||||
void (async () => {
|
||||
try {
|
||||
const params = new URLSearchParams();
|
||||
@@ -104,7 +104,8 @@ export function createCustomThemesHandlers(deps: {
|
||||
params.set("limit", String(request.limit ?? 20));
|
||||
(await bsplusApiQueryParams()).forEach((value, key) => params.set(key, value));
|
||||
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
|
||||
? `/api/custom-themes/search?${params}&q=${encodeURIComponent(search)}`
|
||||
: `/api/custom-themes?${params}`;
|
||||
@@ -120,7 +121,7 @@ export function createCustomThemesHandlers(deps: {
|
||||
return true;
|
||||
}
|
||||
|
||||
function handleFetchMyCustomThemes(request: any, sendResponse: MessageSender): boolean {
|
||||
function handleFetchMyCustomThemes(request: Record<string, unknown>, sendResponse: MessageSender): boolean {
|
||||
void (async () => {
|
||||
try {
|
||||
const params = new URLSearchParams();
|
||||
@@ -141,7 +142,7 @@ export function createCustomThemesHandlers(deps: {
|
||||
return true;
|
||||
}
|
||||
|
||||
function handleFetchMyCustomThemeDetail(request: any, sendResponse: MessageSender): boolean {
|
||||
function handleFetchMyCustomThemeDetail(request: Record<string, unknown>, sendResponse: MessageSender): boolean {
|
||||
const { themeId } = request;
|
||||
if (!themeId || typeof themeId !== "string") {
|
||||
sendResponse({ success: false, error: "Missing themeId" });
|
||||
@@ -167,7 +168,7 @@ export function createCustomThemesHandlers(deps: {
|
||||
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;
|
||||
if (!payload?.themeZip && (!payload?.looseFiles || payload.looseFiles.length === 0)) {
|
||||
sendResponse({ success: false, error: "Missing upload files" });
|
||||
@@ -188,12 +189,14 @@ export function createCustomThemesHandlers(deps: {
|
||||
return true;
|
||||
}
|
||||
|
||||
function handleReplaceCustomThemeFiles(request: any, sendResponse: MessageSender): boolean {
|
||||
const { themeId, payload } = request;
|
||||
function handleReplaceCustomThemeFiles(request: Record<string, unknown>, sendResponse: MessageSender): boolean {
|
||||
const { themeId, payload: payloadRaw } = request;
|
||||
if (!themeId || typeof themeId !== "string") {
|
||||
sendResponse({ success: false, error: "Missing themeId" });
|
||||
return false;
|
||||
}
|
||||
const payload =
|
||||
payloadRaw && typeof payloadRaw === "object" ? (payloadRaw as UploadPayload) : undefined;
|
||||
if (!payload?.themeZip && (!payload?.looseFiles || payload.looseFiles.length === 0)) {
|
||||
sendResponse({ success: false, error: "Missing upload files" });
|
||||
return false;
|
||||
@@ -203,7 +206,7 @@ export function createCustomThemesHandlers(deps: {
|
||||
sendResponse(
|
||||
await customThemesMultipartPost(
|
||||
`/api/custom-themes/mine/${encodeURIComponent(themeId)}/files`,
|
||||
payload,
|
||||
payload as UploadPayload,
|
||||
),
|
||||
);
|
||||
} catch (err) {
|
||||
@@ -217,7 +220,7 @@ export function createCustomThemesHandlers(deps: {
|
||||
return true;
|
||||
}
|
||||
|
||||
function handleUpdateCustomThemeMetadata(request: any, sendResponse: MessageSender): boolean {
|
||||
function handleUpdateCustomThemeMetadata(request: Record<string, unknown>, sendResponse: MessageSender): boolean {
|
||||
const { themeId, body } = request;
|
||||
if (!themeId || typeof themeId !== "string") {
|
||||
sendResponse({ success: false, error: "Missing themeId" });
|
||||
@@ -247,7 +250,7 @@ export function createCustomThemesHandlers(deps: {
|
||||
return true;
|
||||
}
|
||||
|
||||
function handleDeleteCustomTheme(request: any, sendResponse: MessageSender): boolean {
|
||||
function handleDeleteCustomTheme(request: Record<string, unknown>, sendResponse: MessageSender): boolean {
|
||||
const { themeId } = request;
|
||||
if (!themeId || typeof themeId !== "string") {
|
||||
sendResponse({ success: false, error: "Missing themeId" });
|
||||
@@ -287,7 +290,7 @@ export function createCustomThemesHandlers(deps: {
|
||||
return true;
|
||||
}
|
||||
|
||||
function handleFetchBsplusAdminThemes(request: any, sendResponse: MessageSender): boolean {
|
||||
function handleFetchBsplusAdminThemes(request: Record<string, unknown>, sendResponse: MessageSender): boolean {
|
||||
void (async () => {
|
||||
try {
|
||||
const params = new URLSearchParams();
|
||||
@@ -295,7 +298,8 @@ export function createCustomThemesHandlers(deps: {
|
||||
params.set("limit", String(Math.min(Number(request.limit ?? 20) || 20, 100)));
|
||||
if (request.status) params.set("status", String(request.status));
|
||||
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);
|
||||
sendResponse(await customThemesJsonFetch(`/api/bsplus/admin/themes?${params}`, {}, true));
|
||||
} catch (err) {
|
||||
|
||||
@@ -79,7 +79,7 @@ export async function fetchNews(source?: string): Promise<NewsPayload> {
|
||||
const results = await Promise.allSettled(feedUrls.map(fetchFeed));
|
||||
const feeds = results.flatMap((result, i) => {
|
||||
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 { feeds };
|
||||
|
||||
@@ -4,9 +4,7 @@ import browser from "@/lib/browser";
|
||||
function crossedUpgrade(previousVersion: string, boundary: string): boolean {
|
||||
const prev = semver.coerce(previousVersion);
|
||||
const curr = semver.coerce(browser.runtime.getManifest().version);
|
||||
return (
|
||||
prev != null && curr != null && !semver.lt(curr, boundary) && semver.lt(prev, boundary)
|
||||
);
|
||||
return 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). */
|
||||
|
||||
@@ -110,9 +110,7 @@ html {
|
||||
transform-origin: top;
|
||||
transition: transform 0.2s;
|
||||
}
|
||||
body:has(.outside-container:not(.hide))
|
||||
#AddedSettings.tooltip:hover
|
||||
> .tooltiptext {
|
||||
body:has(.outside-container:not(.hide)) #AddedSettings.tooltip:hover > .tooltiptext {
|
||||
transform: scale(0);
|
||||
}
|
||||
.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 { waitForElm } from "@/seqta/utils/waitForElm";
|
||||
import {
|
||||
@@ -17,7 +17,7 @@ let wrapperColourObserver: MutationObserver | null = null;
|
||||
let wrapperColourObserverTimeout: ReturnType<typeof setTimeout> | null = null;
|
||||
|
||||
const assessmentsAveragePlugin = {
|
||||
run: async (api: Parameters<NonNullable<Plugin["run"]>>[0]) => {
|
||||
run: async (api: AssessmentsAverageApi) => {
|
||||
await initStorage(api);
|
||||
clearStuck(api);
|
||||
|
||||
@@ -97,7 +97,7 @@ const assessmentsAveragePlugin = {
|
||||
|
||||
let renderInFlight = false;
|
||||
let renderQueued = false;
|
||||
async function renderSubjectAverage(api: any) {
|
||||
async function renderSubjectAverage(api: AssessmentsAverageApi) {
|
||||
if (renderInFlight) {
|
||||
// Coalesce: remember that fresh data arrived during this render and
|
||||
// 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 { extractWeightFromCoversheetText } from "./extractWeightFromCoversheetText";
|
||||
import { delay } from "@/seqta/utils/delay";
|
||||
import type {
|
||||
AssessmentMark,
|
||||
AssessmentsAverageApi,
|
||||
WeightingEntry,
|
||||
WeightingsMap,
|
||||
} from "./pluginApi";
|
||||
|
||||
export { extractWeightFromCoversheetText };
|
||||
export type { WeightingEntry, WeightingsMap } from "./pluginApi";
|
||||
|
||||
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. */
|
||||
export function assessmentIdKey(mark: { id: string | number }): string {
|
||||
return String(mark.id);
|
||||
@@ -44,7 +42,7 @@ export function assessmentTitleLookupKey(mark: {
|
||||
return title;
|
||||
}
|
||||
|
||||
function registerAssessmentLookup(api: any, mark: any) {
|
||||
function registerAssessmentLookup(api: AssessmentsAverageApi, mark: AssessmentMark) {
|
||||
const assessmentID = assessmentIdKey(mark);
|
||||
const next: Record<string, string> = {
|
||||
...api.storage.assessments,
|
||||
@@ -71,7 +69,7 @@ function collectMarksFromFiberState(state: Record<string, unknown>): MarkLike[]
|
||||
}
|
||||
|
||||
async function resolveAssessmentId(
|
||||
api: any,
|
||||
api: AssessmentsAverageApi,
|
||||
title: string,
|
||||
marks?: MarkLike[],
|
||||
): Promise<string | undefined> {
|
||||
@@ -109,7 +107,7 @@ async function resolveAssessmentId(
|
||||
return undefined;
|
||||
}
|
||||
|
||||
export function computeFingerprint(mark: any): string {
|
||||
export function computeFingerprint(mark: AssessmentMark): string {
|
||||
const score = mark?.results?.percentage ?? mark?.results?.score ?? null;
|
||||
return JSON.stringify([
|
||||
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 ?? {};
|
||||
let dirty = false;
|
||||
const out: WeightingsMap = {};
|
||||
@@ -150,7 +148,7 @@ function migrateWeightings(api: any) {
|
||||
if (dirty) api.storage.weightings = out;
|
||||
}
|
||||
|
||||
export async function initStorage(api: any) {
|
||||
export async function initStorage(api: AssessmentsAverageApi) {
|
||||
await api.storage.loaded;
|
||||
|
||||
if (!api.storage.weightings) {
|
||||
@@ -166,7 +164,7 @@ export async function initStorage(api: any) {
|
||||
migrateWeightings(api);
|
||||
}
|
||||
|
||||
export function clearStuck(api: any) {
|
||||
export function clearStuck(api: AssessmentsAverageApi) {
|
||||
const map = (api.storage.weightings ?? {}) as WeightingsMap;
|
||||
let dirty = false;
|
||||
const out: WeightingsMap = {};
|
||||
@@ -237,14 +235,15 @@ function formatWeightDisplay(weighting: string): string {
|
||||
}
|
||||
|
||||
function saveWeightingOverride(
|
||||
api: any,
|
||||
api: AssessmentsAverageApi,
|
||||
assessmentID: string,
|
||||
raw: string,
|
||||
): { ok: boolean; error?: string } {
|
||||
const trimmed = raw.trim();
|
||||
if (trimmed === "") {
|
||||
const { [assessmentID]: _, ...rest } = api.storage.weightingOverrides;
|
||||
api.storage.weightingOverrides = rest;
|
||||
const overrides = { ...api.storage.weightingOverrides };
|
||||
delete overrides[assessmentID];
|
||||
api.storage.weightingOverrides = overrides;
|
||||
document.dispatchEvent(new CustomEvent("betterseqta:overrideChanged"));
|
||||
return { ok: true };
|
||||
}
|
||||
@@ -262,7 +261,11 @@ function saveWeightingOverride(
|
||||
return { ok: true };
|
||||
}
|
||||
|
||||
function attachWeightInputListeners(input: HTMLInputElement, api: any, assessmentID: string) {
|
||||
function attachWeightInputListeners(
|
||||
input: HTMLInputElement,
|
||||
api: AssessmentsAverageApi,
|
||||
assessmentID: string,
|
||||
) {
|
||||
const save = () => {
|
||||
const result = saveWeightingOverride(api, assessmentID, input.value);
|
||||
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,
|
||||
weighting: string | undefined,
|
||||
assessmentID: string | undefined,
|
||||
api: any,
|
||||
api: AssessmentsAverageApi,
|
||||
refreshing = false,
|
||||
) {
|
||||
const existingInput = weightLabel.querySelector(
|
||||
@@ -333,7 +336,7 @@ function updateWeightLabelContent(
|
||||
function createWeightLabel(
|
||||
assessmentItem: HTMLElement,
|
||||
weighting: string | undefined,
|
||||
api: any,
|
||||
api: AssessmentsAverageApi,
|
||||
refreshing = false,
|
||||
assessmentID?: string,
|
||||
) {
|
||||
@@ -496,11 +499,12 @@ async function fetchPDFAsArrayBuffer(url: string): Promise<ArrayBuffer> {
|
||||
}
|
||||
|
||||
return await response.arrayBuffer();
|
||||
} catch (error: any) {
|
||||
} catch (error: unknown) {
|
||||
const message = error instanceof Error ? error.message : String(error);
|
||||
if (
|
||||
error?.message?.includes("blob") ||
|
||||
error?.message?.includes("Security") ||
|
||||
error?.message?.includes("CSP")
|
||||
message.includes("blob") ||
|
||||
message.includes("Security") ||
|
||||
message.includes("CSP")
|
||||
) {
|
||||
return await fetchPDFAsArrayBuffer(url);
|
||||
}
|
||||
@@ -631,7 +635,7 @@ export async function extractPDFText(url: string): Promise<string> {
|
||||
for (let i = 1; i <= pdf.numPages; i++) {
|
||||
const page = await pdf.getPage(i);
|
||||
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;
|
||||
@@ -706,9 +710,21 @@ async function extractPDFTextWithRetry(url: string, attempts = 3, delayMs = 1500
|
||||
throw lastError;
|
||||
}
|
||||
|
||||
async function handleWeightings(mark: any, api: any) {
|
||||
async function handleWeightings(mark: AssessmentMark, api: AssessmentsAverageApi) {
|
||||
const assessmentID = assessmentIdKey(mark);
|
||||
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 existing = api.storage.weightings[assessmentID] as WeightingEntry | undefined;
|
||||
@@ -799,18 +815,19 @@ async function handleWeightings(mark: any, api: any) {
|
||||
let text: string;
|
||||
try {
|
||||
text = await extractPDFTextWithRetry(pdfUrl);
|
||||
} catch (error: any) {
|
||||
} catch (error: unknown) {
|
||||
const message = error instanceof Error ? error.message : String(error);
|
||||
if (
|
||||
isFirefox &&
|
||||
(error?.message?.includes("blob") ||
|
||||
error?.message?.includes("Security") ||
|
||||
error?.message?.includes("CSP") ||
|
||||
error?.message?.includes("empty"))
|
||||
(message.includes("blob") ||
|
||||
message.includes("Security") ||
|
||||
message.includes("CSP") ||
|
||||
message.includes("empty"))
|
||||
) {
|
||||
await delay(2000);
|
||||
text = await extractPDFTextWithRetry(pdfUrl, 2, 2000);
|
||||
} 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,
|
||||
},
|
||||
};
|
||||
} catch (error: any) {
|
||||
console.error("[BetterSEQTA+] Weighting fetch failed for assessment %s:", assessmentID, error);
|
||||
} catch (error: unknown) {
|
||||
console.error("[BetterSEQTA+] Weighting fetch failed for assessment:", assessmentID, error);
|
||||
api.storage.weightings = {
|
||||
...api.storage.weightings,
|
||||
[assessmentID]: {
|
||||
@@ -839,7 +856,7 @@ async function handleWeightings(mark: any, api: any) {
|
||||
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 marks = [
|
||||
@@ -850,10 +867,10 @@ export async function parseAssessments(api: any) {
|
||||
];
|
||||
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 totalWeight = 0;
|
||||
let hasInaccurateWeighting = false;
|
||||
@@ -992,7 +1009,7 @@ interface WeightingTabContext {
|
||||
statusNote: string;
|
||||
}
|
||||
|
||||
async function resolveWeightingTabContext(api: any): Promise<WeightingTabContext> {
|
||||
async function resolveWeightingTabContext(api: AssessmentsAverageApi): Promise<WeightingTabContext> {
|
||||
const selectedItem = document.querySelector(
|
||||
"[class*='AssessmentItem__AssessmentItem___'][class*='selected___']",
|
||||
) 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 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);
|
||||
renderWeightingTabHtml(sheet, context);
|
||||
if (!context.assessmentID) return;
|
||||
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 container = document.querySelector('[class*="TabSet__tabContainer___"]') as HTMLElement;
|
||||
if (!tabList || !container) return;
|
||||
|
||||
@@ -116,7 +116,7 @@ async function loadSubmissions(student: number, assessments: any[]) {
|
||||
|
||||
submissionMap[assessment.id] = res.payload && res.payload.length > 0;
|
||||
} 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;
|
||||
}
|
||||
}),
|
||||
|
||||
@@ -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 (
|
||||
item.status === "MARKS_RELEASED" ||
|
||||
item.grade ||
|
||||
@@ -205,7 +219,7 @@ export function determineStatus(item: any, completed: readonly unknown[]): strin
|
||||
}
|
||||
|
||||
const now = new Date();
|
||||
const due = new Date(item.due);
|
||||
const due = new Date(String(item.due ?? ""));
|
||||
|
||||
const diffTime = due.getTime() - now.getTime();
|
||||
const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24));
|
||||
@@ -221,43 +235,37 @@ export function determineStatus(item: any, completed: readonly unknown[]): strin
|
||||
return "UPCOMING";
|
||||
}
|
||||
|
||||
export function getGradeValue(assessment: any): number | null {
|
||||
if (assessment.results?.percentage !== undefined && assessment.results.percentage !== null) {
|
||||
return assessment.results.percentage;
|
||||
export function getGradeValue(assessment: OverviewAssessment): number | null {
|
||||
const results = readNestedRecord(assessment.results);
|
||||
|
||||
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) {
|
||||
return assessment.percentage;
|
||||
}
|
||||
|
||||
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;
|
||||
const resAchieved = readNumber(results?.achieved);
|
||||
const resOutOf = readNumber(results?.outOf);
|
||||
if (resAchieved !== null && resOutOf !== null && resOutOf > 0) {
|
||||
return (resAchieved / resOutOf) * 100;
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
export function extractAssessmentLetterGrade(assessment: any): string | undefined {
|
||||
export function extractAssessmentLetterGrade(assessment: OverviewAssessment): string | undefined {
|
||||
if (assessment?.grade != null && 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 {
|
||||
@@ -284,7 +292,7 @@ export function percentageToLetterGrade(percentage: number): string {
|
||||
return letterMap[rounded] || "F";
|
||||
}
|
||||
|
||||
export function getThermoscorePercent(assessment: any): number | null {
|
||||
export function getThermoscorePercent(assessment: OverviewAssessment): number | null {
|
||||
const numeric = getGradeValue(assessment);
|
||||
if (numeric !== null) return numeric;
|
||||
|
||||
@@ -297,7 +305,7 @@ export function getThermoscorePercent(assessment: any): number | null {
|
||||
return null;
|
||||
}
|
||||
|
||||
export function getDisplayGrade(assessment: any, letterGradeMode: boolean): string {
|
||||
export function getDisplayGrade(assessment: OverviewAssessment, letterGradeMode: boolean): string {
|
||||
if (letterGradeMode) {
|
||||
const letter = extractAssessmentLetterGrade(assessment);
|
||||
if (letter) return letter;
|
||||
@@ -317,7 +325,7 @@ export function getDisplayGrade(assessment: any, letterGradeMode: boolean): stri
|
||||
return "No grade";
|
||||
}
|
||||
|
||||
export function assessmentHasGradeDisplay(assessment: any): boolean {
|
||||
export function assessmentHasGradeDisplay(assessment: OverviewAssessment): boolean {
|
||||
if (extractAssessmentLetterGrade(assessment)) return true;
|
||||
if (getGradeValue(assessment) !== null) return true;
|
||||
return false;
|
||||
|
||||
@@ -208,7 +208,7 @@ export const notificationsJob: Job = {
|
||||
]);
|
||||
return inAssessments || inMessages;
|
||||
} 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;
|
||||
}
|
||||
};
|
||||
@@ -292,7 +292,7 @@ export const notificationsJob: Job = {
|
||||
}
|
||||
}
|
||||
} 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) {
|
||||
progress.retryQueue.push(notif.notificationID);
|
||||
@@ -443,7 +443,7 @@ async function processNotification(
|
||||
|
||||
return { success: false };
|
||||
} catch (error) {
|
||||
console.error(`[Notifications job] Error processing notification ${id}:`, error);
|
||||
console.error("[Notifications job] Error processing notification:", id, error);
|
||||
return { success: false };
|
||||
}
|
||||
}
|
||||
@@ -120,7 +120,7 @@ async function vectorizeItem(
|
||||
const embedding = await getEmbedding(textToEmbed);
|
||||
return { ...item, embedding };
|
||||
} catch (error) {
|
||||
console.error(`Error vectorizing item ${item.id}:`, error);
|
||||
console.error("Error vectorizing item:", item.id, error);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -555,7 +555,7 @@ export class ThemeManager {
|
||||
/**
|
||||
* 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({
|
||||
type: "fetchFromUrl",
|
||||
url,
|
||||
|
||||
@@ -97,7 +97,7 @@ function createSettingsAPI<T extends PluginSettings>(
|
||||
}
|
||||
}
|
||||
} 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) {
|
||||
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)) {
|
||||
console.warn(`Plugin "${pluginId}" is already running`);
|
||||
console.warn("Plugin is already running:", pluginId);
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -184,7 +184,7 @@ export class PluginManager {
|
||||
} catch (error) {
|
||||
this.removePluginStyles(pluginId);
|
||||
this.disposePluginAPI(pluginId);
|
||||
console.error(`[BetterSEQTA+] Failed to start plugin ${pluginId}:`, error);
|
||||
console.error("[BetterSEQTA+] Failed to start plugin:", pluginId, error);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
@@ -227,7 +227,7 @@ export class PluginManager {
|
||||
|
||||
const startPromises = idsToStart.map((id) =>
|
||||
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);
|
||||
}),
|
||||
);
|
||||
|
||||
+9
-22
@@ -1,7 +1,4 @@
|
||||
import {
|
||||
initializeSettingsState,
|
||||
settingsState,
|
||||
} from "@/seqta/utils/listeners/SettingsState";
|
||||
import { initializeSettingsState, settingsState } from "@/seqta/utils/listeners/SettingsState";
|
||||
import documentLoadCSS from "@/css/documentload.scss?inline";
|
||||
import icon48 from "@/resources/icons/icon-48.png?base64";
|
||||
import browser from "@/lib/browser";
|
||||
@@ -57,13 +54,10 @@ export function boot() {
|
||||
|
||||
async function init() {
|
||||
const hasSEQTAText =
|
||||
document.childNodes[1]?.textContent?.includes(
|
||||
"Copyright (c) SEQTA Software",
|
||||
) ?? false;
|
||||
document.childNodes[1]?.textContent?.includes("Copyright (c) SEQTA Software") ?? false;
|
||||
if (
|
||||
hasSEQTAText &&
|
||||
(document.title.includes("SEQTA Learn") ||
|
||||
document.title.includes("SEQTA Engage")) &&
|
||||
(document.title.includes("SEQTA Learn") || document.title.includes("SEQTA Engage")) &&
|
||||
!IsSEQTAPage
|
||||
) {
|
||||
IsSEQTAPage = true;
|
||||
@@ -79,7 +73,6 @@ async function init() {
|
||||
|
||||
const observer = new MutationObserver((mutations) => {
|
||||
for (const mutation of mutations) {
|
||||
|
||||
if (
|
||||
mutation.type === "attributes" &&
|
||||
mutation.target instanceof HTMLLinkElement &&
|
||||
@@ -98,8 +91,6 @@ async function init() {
|
||||
attributeFilter: ["href"],
|
||||
});
|
||||
|
||||
|
||||
|
||||
try {
|
||||
await initializeSettingsState();
|
||||
initVerboseLogging();
|
||||
@@ -141,9 +132,7 @@ async function init() {
|
||||
sessionStorage.removeItem("bsplus-dev-export-recovery");
|
||||
}
|
||||
|
||||
verboseInfo(
|
||||
"[BetterSEQTA+] Successfully initialised BetterSEQTA+, starting to load assets.",
|
||||
);
|
||||
verboseInfo("[BetterSEQTA+] Successfully initialised BetterSEQTA+, starting to load assets.");
|
||||
} catch (error) {
|
||||
console.error(error);
|
||||
recoverFromStaleDevModuleGraph(error);
|
||||
@@ -152,11 +141,9 @@ async function init() {
|
||||
}
|
||||
|
||||
function replaceIcons() {
|
||||
document
|
||||
.querySelectorAll<HTMLLinkElement>('link[rel*="icon"]')
|
||||
.forEach((link) => {
|
||||
if (link.href !== icon48) {
|
||||
link.href = icon48;
|
||||
}
|
||||
});
|
||||
document.querySelectorAll<HTMLLinkElement>('link[rel*="icon"]').forEach((link) => {
|
||||
if (link.href !== icon48) {
|
||||
link.href = icon48;
|
||||
}
|
||||
});
|
||||
}
|
||||
@@ -1,25 +1,18 @@
|
||||
import browser from "@/lib/browser";
|
||||
import {
|
||||
isSeqta404Page,
|
||||
mountErrorPageKitten,
|
||||
} from "@/plugins/built-in/errorPageKitten";
|
||||
import { isSeqta404Page, mountErrorPageKitten } from "@/plugins/built-in/errorPageKitten";
|
||||
|
||||
/** Hide the rebranded 404 before the kitten card mounts (removed after boot). */
|
||||
function inject404FlashHide(): void {
|
||||
if (document.getElementById("bsplus-404-flash-hide")) return;
|
||||
const style = document.createElement("style");
|
||||
style.id = "bsplus-404-flash-hide";
|
||||
style.textContent =
|
||||
"html,body{background:#333!important}.message{display:none!important}";
|
||||
style.textContent = "html,body{background:#333!important}.message{display:none!important}";
|
||||
(document.head ?? document.documentElement).appendChild(style);
|
||||
}
|
||||
|
||||
/** Loaded on demand by SEQTA.ts for pages that aren't the SEQTA app. */
|
||||
export async function bootErrorPage() {
|
||||
const storagePromise = browser.storage.local.get([
|
||||
"onoff",
|
||||
"plugin.error-page-kitten.settings",
|
||||
]);
|
||||
const storagePromise = browser.storage.local.get(["onoff", "plugin.error-page-kitten.settings"]);
|
||||
|
||||
const watchTitle = () => {
|
||||
if (isSeqta404Page()) inject404FlashHide();
|
||||
|
||||
@@ -18,12 +18,13 @@ function stripPlaceholders(html: string): string {
|
||||
return html.replace(PLACEHOLDER_RE, "");
|
||||
}
|
||||
|
||||
function htmlToPlainText(html: string): string {
|
||||
return new DOMParser().parseFromString(html, "text/html").body.textContent ?? "";
|
||||
}
|
||||
|
||||
function noticePreview(contents: string): string {
|
||||
const text = stripPlaceholders(contents)
|
||||
.replace(/<[^>]*>/g, "")
|
||||
.replace(/\s+/g, " ")
|
||||
.trim();
|
||||
return text.substring(0, 150) + (contents.length > 150 ? "..." : "");
|
||||
const text = htmlToPlainText(stripPlaceholders(contents)).replace(/\s+/g, " ").trim();
|
||||
return text.substring(0, 150) + (text.length > 150 ? "..." : "");
|
||||
}
|
||||
|
||||
function noticeBody(contents: string): string {
|
||||
|
||||
Reference in new issue
Block a user