mirror of
https://github.com/BetterSEQTA/BetterSEQTA-Plus.git
synced 2026-12-06 19:56:45 +10:30
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
98a6e7f161 | ||
|
|
c52217e902 | ||
|
|
376ab65e3b | ||
|
|
a1aa5a1f55 | ||
|
|
54ae1a1417 | ||
|
|
d5cac1e5fa | ||
|
|
ee334c901b | ||
|
|
fc72d5ac5e | ||
|
|
3869a1f8d6 | ||
|
|
d4174ef006 | ||
|
|
6081b1446b | ||
|
|
6e2251159e | ||
|
|
1bd88ec81c | ||
|
|
d467339e91 | ||
|
|
db7fff63e3 | ||
|
|
c043d4dfaa | ||
|
|
0cb616ae95 | ||
|
|
009670e201 | ||
|
|
325f194638 | ||
|
|
0eeb10a057 | ||
|
|
0b6d01feaa | ||
|
|
e2a37b3ed3 | ||
|
|
3224f64875 | ||
|
|
0090368707 | ||
|
|
767c3b9e98 | ||
|
|
b55415c93b | ||
|
|
38f934c01f | ||
|
|
0f9b8efc40 | ||
|
|
9bfc0989c1 | ||
|
|
a967e2c2fb | ||
|
|
74fdd079dd | ||
|
|
29c31a2a22 | ||
|
|
0e3297636d | ||
|
|
d3fc4b0afd | ||
|
|
4d8445d7da | ||
|
|
29bdb0064d | ||
|
|
efa4f8b85c | ||
|
|
fea017bbd7 | ||
|
|
95908baa8e | ||
|
|
6868964366 | ||
|
|
344458cc6f | ||
|
|
2135349038 | ||
|
|
06be15b0ef | ||
|
|
13f974d652 |
No files matched your search
@@ -14,6 +14,8 @@ export default {
|
||||
'/node_modules/(?!(color|color-string|color-convert|color-name)/)',
|
||||
],
|
||||
moduleNameMapper: {
|
||||
'^@/(.*)\\?script(?:&(?:iife|module))?$':
|
||||
'<rootDir>/src/test/mocks/crxjsScriptPath.ts',
|
||||
'^@/(.*)$': '<rootDir>/src/$1',
|
||||
'^color$': '<rootDir>/src/test/mocks/color.ts',
|
||||
'^webextension-polyfill$': '<rootDir>/src/test/mocks/webextension-polyfill.ts',
|
||||
|
||||
+1
-1
@@ -144,7 +144,7 @@ function zipSources() {
|
||||
.join(" ");
|
||||
|
||||
// Command to zip the current directory's contents into zipFileName, applying exclude patterns
|
||||
const zipCommand = `7z a ${zipFileName} . ${excludePatterns}`;
|
||||
const zipCommand = `7zz a ${zipFileName} . ${excludePatterns}`;
|
||||
|
||||
console.log("Zipping project sources with command:", zipCommand);
|
||||
execSync(zipCommand, { stdio: "inherit" }); // Execute synchronously and show output
|
||||
|
||||
+1
-1
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "betterseqtaplus",
|
||||
"version": "3.7.3",
|
||||
"version": "3.7.6",
|
||||
"type": "module",
|
||||
"description": "Enhance SEQTA Learn's usability and aesthetics! A fork of BetterSEQTA to continue development and add heaps more features!",
|
||||
"browserslist": "> 0.5%, last 2 versions, not dead",
|
||||
|
||||
+27
-6
@@ -12,6 +12,14 @@ import { initializeHideSensitiveToggle } from "@/seqta/utils/hideSensitiveToggle
|
||||
import { installSeqtaMenuColourPatch } from "@/seqta/utils/patchSeqtaMenuUpdateColours";
|
||||
import { installThemeImagePagePatch } from "@/seqta/utils/patchThemeImagesPageContext";
|
||||
import { initVerboseLogging, verboseInfo } from "@/utils/verboseLog";
|
||||
import {
|
||||
hydrateRemoteConfigFromStorage,
|
||||
installRemoteConfigStorageListener,
|
||||
isEffectiveBsplusEnabled,
|
||||
notifyRemoteConfigPageContext,
|
||||
ensureKilledModeSettingsAccess,
|
||||
} from "@/seqta/utils/remoteConfig/runtime";
|
||||
import { runStartupPopupQueue } from "@/seqta/utils/Openers/StartupPopupQueue";
|
||||
|
||||
function registerFetchSeqtaAppLinkListener() {
|
||||
browser.runtime.onMessage.addListener((request, _sender, sendResponse) => {
|
||||
@@ -113,14 +121,27 @@ async function init() {
|
||||
await delay(5);
|
||||
}
|
||||
|
||||
await main();
|
||||
await hydrateRemoteConfigFromStorage();
|
||||
notifyRemoteConfigPageContext(location.hostname);
|
||||
installRemoteConfigStorageListener(() => {
|
||||
location.reload();
|
||||
});
|
||||
|
||||
const { init: Monofile } = await import("@/plugins/monofile");
|
||||
Monofile();
|
||||
const bsplusEnabled = isEffectiveBsplusEnabled();
|
||||
|
||||
if (settingsState.onoff) {
|
||||
const { initializePlugins } = await import("@/plugins/index");
|
||||
await initializePlugins();
|
||||
if (bsplusEnabled) {
|
||||
await main();
|
||||
|
||||
const { init: Monofile } = await import("@/plugins/monofile");
|
||||
Monofile();
|
||||
|
||||
if (settingsState.onoff) {
|
||||
const { initializePlugins } = await import("@/plugins/index");
|
||||
await initializePlugins();
|
||||
}
|
||||
} else {
|
||||
await ensureKilledModeSettingsAccess();
|
||||
void runStartupPopupQueue();
|
||||
}
|
||||
|
||||
if (settingsState.devMode) {
|
||||
|
||||
+56
-8
@@ -20,7 +20,14 @@ import {
|
||||
registerOutlookCalendarMessageHandlers,
|
||||
} from "./background/calendarBackground";
|
||||
import { createCustomThemesHandlers } from "./background/customThemesHandlers";
|
||||
import {
|
||||
createRemoteConfigHandlers,
|
||||
initRemoteConfigBackground,
|
||||
refreshRemoteConfig,
|
||||
} from "./background/remoteConfig";
|
||||
import { BSPLUS_INSTALL_REGISTERED_AT_KEY } from "@/seqta/utils/remoteConfig/storageKeys";
|
||||
import { handleSearchThemeStockPhotos } from "./background/searchThemeStockPhotos";
|
||||
import { bsplusApiQueryParams, withBsplusApiQuery } from "@/seqta/utils/bsplusClientContext";
|
||||
import { initTimetableClassmatesBackgroundSync } from "./background/timetableClassmatesSync";
|
||||
|
||||
/**
|
||||
@@ -99,7 +106,11 @@ function normalizeFetchThemesResponse(json: unknown): {
|
||||
function handleFetchThemes(request: any, sendResponse: MessageSender): boolean {
|
||||
void (async () => {
|
||||
const token = await getAccessTokenFromStorage();
|
||||
const apiUrl = `${apiBase()}/api/themes?type=betterseqta&limit=100&nocache=${Date.now()}`;
|
||||
const params = await bsplusApiQueryParams();
|
||||
params.set("type", "betterseqta");
|
||||
params.set("limit", "100");
|
||||
params.set("nocache", String(Date.now()));
|
||||
const apiUrl = `${apiBase()}/api/themes?${params}`;
|
||||
const githubUrl = `https://raw.githubusercontent.com/BetterSEQTA/BetterSEQTA-Themes/main/store/themes.json?nocache=${Date.now()}`;
|
||||
const headers: Record<string, string> = {};
|
||||
if (token) headers["Authorization"] = `Bearer ${token}`;
|
||||
@@ -145,7 +156,10 @@ function handleFetchThemeDetails(request: any, sendResponse: MessageSender): boo
|
||||
const token = await getAccessTokenFromStorage();
|
||||
const headers: Record<string, string> = {};
|
||||
if (token) headers["Authorization"] = `Bearer ${token}`;
|
||||
fetch(`${apiBase()}/api/themes/${themeId}`, { cache: "no-store", headers })
|
||||
const detailUrl = await withBsplusApiQuery(
|
||||
`${apiBase()}/api/themes/${encodeURIComponent(themeId)}`,
|
||||
);
|
||||
fetch(detailUrl, { cache: "no-store", headers })
|
||||
.then((r) => r.json())
|
||||
.then(sendResponse)
|
||||
.catch((err) => {
|
||||
@@ -192,13 +206,36 @@ function handleFetchFromUrl(
|
||||
sendResponse({ error: "URL not allowed" });
|
||||
return false;
|
||||
}
|
||||
fetch(url, { cache: "no-store" })
|
||||
.then((r) => r.json())
|
||||
.then((data) => sendResponse({ data }))
|
||||
.catch((err) => {
|
||||
void (async () => {
|
||||
try {
|
||||
const headers: Record<string, string> = { Accept: "application/json" };
|
||||
if (request.auth === true) {
|
||||
const token = await getAccessTokenFromStorage();
|
||||
if (!token) {
|
||||
sendResponse({ error: "Not authenticated" });
|
||||
return;
|
||||
}
|
||||
headers.Authorization = `Bearer ${token}`;
|
||||
}
|
||||
const r = await fetch(url, { cache: "no-store", headers });
|
||||
const text = await r.text();
|
||||
if (!r.ok) {
|
||||
sendResponse({
|
||||
error: text?.slice(0, 200) || `HTTP ${r.status}`,
|
||||
httpStatus: r.status,
|
||||
});
|
||||
return;
|
||||
}
|
||||
try {
|
||||
sendResponse({ data: text ? JSON.parse(text) : {} });
|
||||
} catch {
|
||||
sendResponse({ error: "Invalid JSON response" });
|
||||
}
|
||||
} catch (err) {
|
||||
console.error("[Background] fetchFromUrl error:", err);
|
||||
sendResponse({ error: err?.message });
|
||||
});
|
||||
sendResponse({ error: (err as Error)?.message });
|
||||
}
|
||||
})();
|
||||
return true;
|
||||
}
|
||||
|
||||
@@ -492,8 +529,11 @@ const customThemesHandlers = createCustomThemesHandlers({
|
||||
getAccessTokenFromStorage,
|
||||
});
|
||||
|
||||
const remoteConfigHandlers = createRemoteConfigHandlers(apiBase);
|
||||
|
||||
const MESSAGE_HANDLERS: Record<string, MessageHandler> = {
|
||||
...customThemesHandlers,
|
||||
...remoteConfigHandlers,
|
||||
searchThemeStockPhotos: handleSearchThemeStockPhotos,
|
||||
reloadTabs: () => reloadSeqtaPages(),
|
||||
setDevApiBase: handleSetDevApiBase,
|
||||
@@ -742,8 +782,15 @@ browser.runtime.onInstalled.addListener(function (event) {
|
||||
void migrateGlobalSearchDefaultsFor365Upgrade(event.previousVersion);
|
||||
void resetThemeOfTheMonthDisabledFor366Upgrade(event.previousVersion);
|
||||
void resetThemeOfTheMonthDismissalFor370Upgrade(event.previousVersion);
|
||||
void browser.storage.local.remove(BSPLUS_INSTALL_REGISTERED_AT_KEY).then(() => {
|
||||
void refreshRemoteConfig(apiBase);
|
||||
});
|
||||
reloadSeqtaPages();
|
||||
}
|
||||
|
||||
if (event.reason === "install") {
|
||||
void refreshRemoteConfig(apiBase);
|
||||
}
|
||||
});
|
||||
|
||||
browser.runtime.onStartup.addListener(() => {
|
||||
@@ -751,5 +798,6 @@ browser.runtime.onStartup.addListener(() => {
|
||||
});
|
||||
|
||||
initCloudSettingsAutoSync({ reloadSeqtaPages });
|
||||
initRemoteConfigBackground(apiBase);
|
||||
initTimetableClassmatesBackgroundSync();
|
||||
void ensureSyncableStorageDefaults();
|
||||
@@ -16,6 +16,7 @@ import {
|
||||
getLastUploadedSnapshot,
|
||||
setKnownRemoteUpdatedAt,
|
||||
} from "@/seqta/utils/cloudSettingsSync";
|
||||
import { isRemoteCloudSyncDisabled } from "./remoteConfig";
|
||||
|
||||
const ACCOUNTS_BASE = "https://accounts.betterseqta.org";
|
||||
export const CLOUD_SUMMARY_URL = `${ACCOUNTS_BASE}/api/user/cloud-summary`;
|
||||
@@ -216,6 +217,9 @@ async function putSettingsOnce(token: string): Promise<PutResult> {
|
||||
export async function performCloudSettingsUploadWithRetry(
|
||||
token: string,
|
||||
): Promise<{ success: boolean; error?: string; updated_at?: string; skipped?: boolean }> {
|
||||
if (await isRemoteCloudSyncDisabled()) {
|
||||
return { success: false, error: "Cloud sync disabled by remote config", skipped: true };
|
||||
}
|
||||
let t = token;
|
||||
for (let attempt = 0; attempt < 2; attempt++) {
|
||||
const res = await putSettingsOnce(t);
|
||||
@@ -332,6 +336,8 @@ async function downloadIfNeeded(token: string): Promise<void> {
|
||||
}
|
||||
|
||||
async function runCloudSettingsPollInner(): Promise<void> {
|
||||
if (await isRemoteCloudSyncDisabled()) return;
|
||||
|
||||
const all = (await browser.storage.local.get()) as Record<string, unknown>;
|
||||
if (!isAutoCloudSyncEnabled(all)) return;
|
||||
|
||||
@@ -409,6 +415,7 @@ function scheduleDebouncedUpload(): void {
|
||||
/** Call after store theme install (and similar) so cloud upload runs even if storage events are flaky. */
|
||||
export function requestCloudSettingsDebouncedUpload(): void {
|
||||
void (async () => {
|
||||
if (await isRemoteCloudSyncDisabled()) return;
|
||||
const all = (await browser.storage.local.get()) as Record<string, unknown>;
|
||||
if (!isAutoCloudSyncEnabled(all)) return;
|
||||
if (suppressAutoUploadDuringRestore) return;
|
||||
@@ -418,6 +425,7 @@ export function requestCloudSettingsDebouncedUpload(): void {
|
||||
}
|
||||
|
||||
async function runDebouncedUploadJob(): Promise<void> {
|
||||
if (await isRemoteCloudSyncDisabled()) return;
|
||||
const all = (await browser.storage.local.get()) as Record<string, unknown>;
|
||||
if (!isAutoCloudSyncEnabled(all)) return;
|
||||
const token = await getAccessToken();
|
||||
@@ -449,6 +457,7 @@ function onStorageChanged(
|
||||
if (!keys.some((k) => isKeyIncludedInCloudUploadPayload(k))) return;
|
||||
|
||||
void (async () => {
|
||||
if (await isRemoteCloudSyncDisabled()) return;
|
||||
const all = (await browser.storage.local.get()) as Record<string, unknown>;
|
||||
if (!isAutoCloudSyncEnabled(all)) return;
|
||||
if (suppressAutoUploadDuringRestore) return;
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { normalizeCustomThemeApiResponse } from "@/seqta/utils/customThemes/parseApiEnvelope";
|
||||
import { bsplusApiQueryParams } from "@/seqta/utils/bsplusClientContext";
|
||||
|
||||
type MessageSender = { (response?: unknown): void };
|
||||
|
||||
@@ -115,6 +116,7 @@ export function createCustomThemesHandlers(deps: {
|
||||
params.set("type", "betterseqta");
|
||||
params.set("page", String(request.page ?? 1));
|
||||
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 path = search
|
||||
@@ -139,6 +141,7 @@ export function createCustomThemesHandlers(deps: {
|
||||
params.set("page", String(request.page ?? 1));
|
||||
params.set("limit", String(request.limit ?? 20));
|
||||
params.set("type", "betterseqta");
|
||||
(await bsplusApiQueryParams()).forEach((value, key) => params.set(key, value));
|
||||
if (request.status) params.set("status", String(request.status));
|
||||
sendResponse(
|
||||
await customThemesJsonFetch(`/api/custom-themes/mine?${params}`, {}, true),
|
||||
@@ -286,6 +289,41 @@ export function createCustomThemesHandlers(deps: {
|
||||
return true;
|
||||
}
|
||||
|
||||
function handleFetchBsplusAdminMe(_request: unknown, sendResponse: MessageSender): boolean {
|
||||
void (async () => {
|
||||
try {
|
||||
sendResponse(await customThemesJsonFetch("/api/bsplus/admin/me", {}, true));
|
||||
} catch (err) {
|
||||
sendResponse({
|
||||
success: false,
|
||||
error: err instanceof Error ? err.message : "Fetch failed",
|
||||
});
|
||||
}
|
||||
})();
|
||||
return true;
|
||||
}
|
||||
|
||||
function handleFetchBsplusAdminThemes(request: any, sendResponse: MessageSender): boolean {
|
||||
void (async () => {
|
||||
try {
|
||||
const params = new URLSearchParams();
|
||||
params.set("page", String(request.page ?? 1));
|
||||
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();
|
||||
if (search) params.set("search", search);
|
||||
sendResponse(await customThemesJsonFetch(`/api/bsplus/admin/themes?${params}`, {}, true));
|
||||
} catch (err) {
|
||||
sendResponse({
|
||||
success: false,
|
||||
error: err instanceof Error ? err.message : "Fetch failed",
|
||||
});
|
||||
}
|
||||
})();
|
||||
return true;
|
||||
}
|
||||
|
||||
return {
|
||||
fetchCustomThemes: handleFetchCustomThemes,
|
||||
fetchMyCustomThemes: handleFetchMyCustomThemes,
|
||||
@@ -294,5 +332,7 @@ export function createCustomThemesHandlers(deps: {
|
||||
replaceCustomThemeFiles: handleReplaceCustomThemeFiles,
|
||||
updateCustomThemeMetadata: handleUpdateCustomThemeMetadata,
|
||||
deleteCustomTheme: handleDeleteCustomTheme,
|
||||
fetchBsplusAdminMe: handleFetchBsplusAdminMe,
|
||||
fetchBsplusAdminThemes: handleFetchBsplusAdminThemes,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,386 @@
|
||||
import browser from "webextension-polyfill";
|
||||
import { getBsplusDeviceName } from "@/seqta/utils/bsplusDeviceName";
|
||||
import {
|
||||
bsplusApiQueryParams,
|
||||
bsplusExtensionPayload,
|
||||
} from "@/seqta/utils/bsplusClientContext";
|
||||
import { getOrCreateInstallId } from "@/seqta/utils/feedback/installId";
|
||||
import { isAllowedFetchUrl } from "@/seqta/utils/allowedFetchUrl";
|
||||
import {
|
||||
mergeGithubConfigFiles,
|
||||
normalizeRemoteConfigSnapshot,
|
||||
} from "@/seqta/utils/remoteConfig/normalize";
|
||||
import {
|
||||
BSPLUS_INSTALL_REGISTERED_AT_KEY,
|
||||
BSPLUS_REMOTE_CONFIG_ETAG_KEY,
|
||||
BSPLUS_REMOTE_CONFIG_FETCHED_AT_KEY,
|
||||
BSPLUS_REMOTE_CONFIG_LAST_HOSTNAME_KEY,
|
||||
BSPLUS_REMOTE_CONFIG_SNAPSHOT_KEY,
|
||||
BSPLUS_REMOTE_LAST_PRIMARY_OK_KEY,
|
||||
BS_STATUS_MANIFEST_URL,
|
||||
REGISTER_INTERVAL_MS,
|
||||
REMOTE_CONFIG_ALARM,
|
||||
REMOTE_CONFIG_POLL_MINUTES,
|
||||
} from "@/seqta/utils/remoteConfig/storageKeys";
|
||||
import type { RemoteConfigSnapshot } from "@/seqta/utils/remoteConfig/types";
|
||||
|
||||
type MessageSender = { (response?: unknown): void };
|
||||
|
||||
const ACCOUNTS_BASE = "https://accounts.betterseqta.org";
|
||||
|
||||
async function linkCloudInstall(token: string, installId: string): Promise<void> {
|
||||
try {
|
||||
const extension = bsplusExtensionPayload();
|
||||
const r = await fetch(`${ACCOUNTS_BASE}/api/bsplus/installs/link`, {
|
||||
method: "POST",
|
||||
headers: {
|
||||
Accept: "application/json",
|
||||
"Content-Type": "application/json",
|
||||
Authorization: `Bearer ${token}`,
|
||||
},
|
||||
body: JSON.stringify({
|
||||
installId,
|
||||
extensionVersion: extension.version,
|
||||
extension,
|
||||
deviceName: await getBsplusDeviceName(),
|
||||
lastSeenAt: new Date().toISOString(),
|
||||
}),
|
||||
cache: "no-store",
|
||||
});
|
||||
if (!r.ok) console.warn("[BetterSEQTA+] cloud install link failed:", r.status);
|
||||
} catch (e) {
|
||||
console.warn("[BetterSEQTA+] cloud install link failed:", e);
|
||||
}
|
||||
}
|
||||
|
||||
async function parseJson(r: Response): Promise<unknown> {
|
||||
const text = await r.text();
|
||||
try {
|
||||
return text ? JSON.parse(text) : {};
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
async function readLastHostname(): Promise<string | undefined> {
|
||||
const stored = await browser.storage.local.get(BSPLUS_REMOTE_CONFIG_LAST_HOSTNAME_KEY);
|
||||
const hostname = stored[BSPLUS_REMOTE_CONFIG_LAST_HOSTNAME_KEY];
|
||||
return typeof hostname === "string" && hostname.length > 0 ? hostname : undefined;
|
||||
}
|
||||
|
||||
async function fetchGithubSnapshot(): Promise<RemoteConfigSnapshot | null> {
|
||||
try {
|
||||
const manifestRes = await fetch(BS_STATUS_MANIFEST_URL, { cache: "no-store" });
|
||||
if (!manifestRes.ok) return null;
|
||||
const manifest = (await parseJson(manifestRes)) as Record<string, unknown> | null;
|
||||
if (!manifest?.files || typeof manifest.files !== "object") return null;
|
||||
const base =
|
||||
BS_STATUS_MANIFEST_URL.replace(/manifest\.json$/, "") ||
|
||||
"https://raw.githubusercontent.com/BetterSEQTA/BS-Status/main/config/";
|
||||
const files: Record<string, unknown> = {};
|
||||
for (const [key, fileName] of Object.entries(
|
||||
manifest.files as Record<string, string>,
|
||||
)) {
|
||||
if (typeof fileName !== "string") continue;
|
||||
const url = fileName.startsWith("http") ? fileName : `${base}${fileName}`;
|
||||
if (!isAllowedFetchUrl(url)) continue;
|
||||
const fr = await fetch(url, { cache: "no-store" });
|
||||
if (!fr.ok) continue;
|
||||
files[key] = await parseJson(fr);
|
||||
}
|
||||
return mergeGithubConfigFiles(manifest, files);
|
||||
} catch (e) {
|
||||
console.warn("[BetterSEQTA+] GitHub remote config fallback failed:", e);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
async function registerInstall(
|
||||
apiBase: string,
|
||||
primaryOk: boolean,
|
||||
force = false,
|
||||
): Promise<void> {
|
||||
if (!primaryOk) return;
|
||||
const stored = await browser.storage.local.get(BSPLUS_INSTALL_REGISTERED_AT_KEY);
|
||||
const last = Number(stored[BSPLUS_INSTALL_REGISTERED_AT_KEY] ?? 0);
|
||||
if (!force && Date.now() - last < REGISTER_INTERVAL_MS) return;
|
||||
|
||||
const installId = await getOrCreateInstallId();
|
||||
const extension = bsplusExtensionPayload();
|
||||
const { bsplus_token, bsplus_user } = await browser.storage.local.get([
|
||||
"bsplus_token",
|
||||
"bsplus_user",
|
||||
]);
|
||||
const token =
|
||||
typeof bsplus_token === "string" && bsplus_token.length > 0 ? bsplus_token : undefined;
|
||||
const userId =
|
||||
bsplus_user && typeof bsplus_user === "object" && "id" in bsplus_user
|
||||
? String((bsplus_user as { id: string }).id)
|
||||
: undefined;
|
||||
|
||||
const hostname = await readLastHostname();
|
||||
|
||||
const body = {
|
||||
installId,
|
||||
extensionVersion: extension.version,
|
||||
extension,
|
||||
userId,
|
||||
lastSeenAt: new Date().toISOString(),
|
||||
...(hostname ? { hostname } : {}),
|
||||
};
|
||||
|
||||
try {
|
||||
const headers: Record<string, string> = {
|
||||
Accept: "application/json",
|
||||
"Content-Type": "application/json",
|
||||
};
|
||||
if (token) headers.Authorization = `Bearer ${token}`;
|
||||
const r = await fetch(`${apiBase}/api/bsplus/installs/register`, {
|
||||
method: "POST",
|
||||
headers,
|
||||
body: JSON.stringify(body),
|
||||
cache: "no-store",
|
||||
});
|
||||
if (r.ok) {
|
||||
await browser.storage.local.set({
|
||||
[BSPLUS_INSTALL_REGISTERED_AT_KEY]: Date.now(),
|
||||
});
|
||||
}
|
||||
} catch (e) {
|
||||
console.warn("[BetterSEQTA+] install register failed:", e);
|
||||
}
|
||||
if (token) void linkCloudInstall(token, installId);
|
||||
}
|
||||
|
||||
export async function refreshRemoteConfig(apiBase: () => string): Promise<{
|
||||
snapshot: RemoteConfigSnapshot;
|
||||
fromNetwork: boolean;
|
||||
primaryOk: boolean;
|
||||
}> {
|
||||
const base = apiBase();
|
||||
const hostname = await readLastHostname();
|
||||
const params = await bsplusApiQueryParams();
|
||||
if (hostname) params.set("hostname", hostname);
|
||||
|
||||
const stored = await browser.storage.local.get([
|
||||
BSPLUS_REMOTE_CONFIG_SNAPSHOT_KEY,
|
||||
BSPLUS_REMOTE_CONFIG_ETAG_KEY,
|
||||
]);
|
||||
const etag = stored[BSPLUS_REMOTE_CONFIG_ETAG_KEY] as string | undefined;
|
||||
const prior = stored[BSPLUS_REMOTE_CONFIG_SNAPSHOT_KEY];
|
||||
|
||||
let primaryOk = false;
|
||||
let snapshot: RemoteConfigSnapshot | null = null;
|
||||
|
||||
try {
|
||||
const headers: Record<string, string> = { Accept: "application/json" };
|
||||
if (etag) headers["If-None-Match"] = etag;
|
||||
const r = await fetch(`${base}/api/bsplus/remote-config?${params}`, {
|
||||
cache: "no-store",
|
||||
headers,
|
||||
});
|
||||
if (r.status === 304 && prior) {
|
||||
primaryOk = true;
|
||||
snapshot = normalizeRemoteConfigSnapshot(prior);
|
||||
snapshot.source = "cache";
|
||||
} else if (r.ok) {
|
||||
primaryOk = true;
|
||||
const json = await parseJson(r);
|
||||
snapshot = normalizeRemoteConfigSnapshot(json);
|
||||
snapshot.source = "api";
|
||||
const newEtag = r.headers.get("ETag") ?? snapshot.etag;
|
||||
if (newEtag) snapshot.etag = newEtag;
|
||||
await browser.storage.local.set({
|
||||
[BSPLUS_REMOTE_CONFIG_SNAPSHOT_KEY]: snapshot,
|
||||
[BSPLUS_REMOTE_CONFIG_FETCHED_AT_KEY]: Date.now(),
|
||||
[BSPLUS_REMOTE_LAST_PRIMARY_OK_KEY]: true,
|
||||
...(newEtag ? { [BSPLUS_REMOTE_CONFIG_ETAG_KEY]: newEtag } : {}),
|
||||
});
|
||||
}
|
||||
} catch (e) {
|
||||
console.warn("[BetterSEQTA+] remote-config primary fetch failed:", e);
|
||||
}
|
||||
|
||||
if (!snapshot) {
|
||||
snapshot = await fetchGithubSnapshot();
|
||||
if (snapshot) {
|
||||
await browser.storage.local.set({
|
||||
[BSPLUS_REMOTE_CONFIG_SNAPSHOT_KEY]: snapshot,
|
||||
[BSPLUS_REMOTE_CONFIG_FETCHED_AT_KEY]: Date.now(),
|
||||
[BSPLUS_REMOTE_LAST_PRIMARY_OK_KEY]: false,
|
||||
});
|
||||
} else if (prior) {
|
||||
snapshot = normalizeRemoteConfigSnapshot(prior);
|
||||
snapshot.source = "cache";
|
||||
} else {
|
||||
snapshot = normalizeRemoteConfigSnapshot(null);
|
||||
}
|
||||
}
|
||||
|
||||
if (primaryOk) {
|
||||
await browser.storage.local.set({ [BSPLUS_REMOTE_LAST_PRIMARY_OK_KEY]: true });
|
||||
}
|
||||
|
||||
void registerInstall(base, primaryOk);
|
||||
return { snapshot, fromNetwork: primaryOk, primaryOk };
|
||||
}
|
||||
|
||||
export function initRemoteConfigBackground(apiBase: () => string): void {
|
||||
void refreshRemoteConfig(apiBase);
|
||||
|
||||
browser.alarms.create(REMOTE_CONFIG_ALARM, {
|
||||
periodInMinutes: REMOTE_CONFIG_POLL_MINUTES,
|
||||
});
|
||||
|
||||
browser.alarms.onAlarm.addListener((alarm) => {
|
||||
if (alarm.name === REMOTE_CONFIG_ALARM) void refreshRemoteConfig(apiBase);
|
||||
});
|
||||
|
||||
browser.storage.onChanged.addListener((changes, area) => {
|
||||
if (area !== "local") return;
|
||||
if (changes.bsplus_token || changes.bsplus_user) {
|
||||
void (async () => {
|
||||
const lastPrimary = await browser.storage.local.get(BSPLUS_REMOTE_LAST_PRIMARY_OK_KEY);
|
||||
const primaryOk = lastPrimary[BSPLUS_REMOTE_LAST_PRIMARY_OK_KEY] === true;
|
||||
if (primaryOk) {
|
||||
await registerInstall(apiBase(), true, true);
|
||||
} else {
|
||||
const res = await refreshRemoteConfig(apiBase);
|
||||
if (res.primaryOk) await registerInstall(apiBase(), true, true);
|
||||
else {
|
||||
const { bsplus_token } = await browser.storage.local.get("bsplus_token");
|
||||
if (typeof bsplus_token === "string" && bsplus_token) {
|
||||
void linkCloudInstall(bsplus_token, await getOrCreateInstallId());
|
||||
}
|
||||
}
|
||||
}
|
||||
})();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
export function createRemoteConfigHandlers(apiBase: () => string): Record<
|
||||
string,
|
||||
(request: unknown, sendResponse: MessageSender) => boolean
|
||||
> {
|
||||
function handleRefresh(_req: unknown, sendResponse: MessageSender): boolean {
|
||||
void refreshRemoteConfig(apiBase)
|
||||
.then((res) => sendResponse(res))
|
||||
.catch((err) =>
|
||||
sendResponse({
|
||||
error: err instanceof Error ? err.message : "Refresh failed",
|
||||
}),
|
||||
);
|
||||
return true;
|
||||
}
|
||||
|
||||
function handleGetSnapshot(_req: unknown, sendResponse: MessageSender): boolean {
|
||||
void browser.storage.local
|
||||
.get(BSPLUS_REMOTE_CONFIG_SNAPSHOT_KEY)
|
||||
.then((stored) => {
|
||||
sendResponse({
|
||||
snapshot: normalizeRemoteConfigSnapshot(
|
||||
stored[BSPLUS_REMOTE_CONFIG_SNAPSHOT_KEY],
|
||||
),
|
||||
});
|
||||
});
|
||||
return true;
|
||||
}
|
||||
|
||||
function handleSetPageContext(req: { hostname?: string }, sendResponse: MessageSender): boolean {
|
||||
const hostname = typeof req.hostname === "string" ? req.hostname.trim() : "";
|
||||
if (hostname) {
|
||||
void browser.storage.local
|
||||
.set({ [BSPLUS_REMOTE_CONFIG_LAST_HOSTNAME_KEY]: hostname })
|
||||
.then(() => sendResponse({ ok: true }));
|
||||
} else {
|
||||
sendResponse({ ok: false });
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
function handleFetchRemoteThemePackage(
|
||||
req: { packageId?: string },
|
||||
sendResponse: MessageSender,
|
||||
): boolean {
|
||||
const packageId = typeof req.packageId === "string" ? req.packageId.trim() : "";
|
||||
if (!packageId) {
|
||||
sendResponse({ error: "Missing packageId" });
|
||||
return false;
|
||||
}
|
||||
void (async () => {
|
||||
try {
|
||||
const hostname = await readLastHostname();
|
||||
const params = await bsplusApiQueryParams();
|
||||
if (hostname) params.set("hostname", hostname);
|
||||
const base = apiBase();
|
||||
const url = `${base}/api/bsplus/remote-theme-packages/${encodeURIComponent(packageId)}?${params}`;
|
||||
if (!isAllowedFetchUrl(url)) {
|
||||
sendResponse({ error: "URL not allowed" });
|
||||
return;
|
||||
}
|
||||
const r = await fetch(url, { cache: "no-store", headers: { Accept: "application/json" } });
|
||||
if (!r.ok) {
|
||||
sendResponse({ error: `HTTP ${r.status}` });
|
||||
return;
|
||||
}
|
||||
const json = await parseJson(r);
|
||||
if (!json || typeof json !== "object") {
|
||||
sendResponse({ error: "Invalid package response" });
|
||||
return;
|
||||
}
|
||||
sendResponse({ package: json });
|
||||
} catch (e) {
|
||||
sendResponse({
|
||||
error: e instanceof Error ? e.message : "Fetch failed",
|
||||
});
|
||||
}
|
||||
})();
|
||||
return true;
|
||||
}
|
||||
|
||||
function handleFetchRemoteThemePackageUrl(
|
||||
req: { url?: string },
|
||||
sendResponse: MessageSender,
|
||||
): boolean {
|
||||
const url = typeof req.url === "string" ? req.url.trim() : "";
|
||||
if (!url || !isAllowedFetchUrl(url)) {
|
||||
sendResponse({ error: "URL not allowed" });
|
||||
return false;
|
||||
}
|
||||
void (async () => {
|
||||
try {
|
||||
const r = await fetch(url, { cache: "no-store" });
|
||||
if (!r.ok) {
|
||||
sendResponse({ error: `HTTP ${r.status}` });
|
||||
return;
|
||||
}
|
||||
const theme = await parseJson(r);
|
||||
if (!theme || typeof theme !== "object") {
|
||||
sendResponse({ error: "Invalid theme JSON" });
|
||||
return;
|
||||
}
|
||||
sendResponse({ theme });
|
||||
} catch (e) {
|
||||
sendResponse({
|
||||
error: e instanceof Error ? e.message : "Fetch failed",
|
||||
});
|
||||
}
|
||||
})();
|
||||
return true;
|
||||
}
|
||||
|
||||
return {
|
||||
refreshRemoteConfig: handleRefresh,
|
||||
getRemoteConfigSnapshot: handleGetSnapshot,
|
||||
setRemoteConfigPageContext: handleSetPageContext,
|
||||
fetchRemoteThemePackage: handleFetchRemoteThemePackage,
|
||||
fetchRemoteThemePackageUrl: handleFetchRemoteThemePackageUrl,
|
||||
};
|
||||
}
|
||||
|
||||
export async function isRemoteCloudSyncDisabled(): Promise<boolean> {
|
||||
const stored = await browser.storage.local.get(BSPLUS_REMOTE_CONFIG_SNAPSHOT_KEY);
|
||||
const snap = normalizeRemoteConfigSnapshot(stored[BSPLUS_REMOTE_CONFIG_SNAPSHOT_KEY]);
|
||||
return snap.global.disableCloudSync === true;
|
||||
}
|
||||
+360
-19
@@ -241,14 +241,15 @@ html:not(.dark) .legacy-root {
|
||||
.addedButton {
|
||||
position: absolute !important;
|
||||
right: 105px;
|
||||
padding: 6px !important;
|
||||
display: flex !important;
|
||||
align-items: center !important;
|
||||
justify-content: center !important;
|
||||
overflow: unset !important;
|
||||
border-radius: 10px !important;
|
||||
cursor: pointer;
|
||||
background: var(--text-primary) !important;
|
||||
color: var(--theme-primary) !important;
|
||||
height: 35px;
|
||||
justify-content: center;
|
||||
width: 35px !important;
|
||||
}
|
||||
|
||||
@@ -422,7 +423,9 @@ ul.magicDelete > li.deleting {
|
||||
background: unset;
|
||||
}
|
||||
.addedButton svg {
|
||||
margin: 6px;
|
||||
display: block;
|
||||
margin: 0;
|
||||
flex-shrink: 0;
|
||||
fill: var(--theme-primary);
|
||||
color: var(--theme-primary);
|
||||
}
|
||||
@@ -719,6 +722,14 @@ body.icon-only-sidebar {
|
||||
}
|
||||
}
|
||||
|
||||
/* Rail tiles follow the user radius even for squared presets (strip/sharp):
|
||||
the compact rail's shape language is the rounded folder arc, so a
|
||||
square active/hover tile there reads as a glitch. Pill keeps its
|
||||
full capsule (it is the "rounder" shape, not the square one). */
|
||||
#menu#menu:not(.bsplus-sidebar-style-pill) > ul > :is(li, section) {
|
||||
border-radius: var(--bsplus-sidebar-radius, 12px) !important;
|
||||
}
|
||||
|
||||
#menu#menu > ul > .hasChildren {
|
||||
position: static !important;
|
||||
backdrop-filter: none !important;
|
||||
@@ -856,11 +867,6 @@ body.icon-only-sidebar {
|
||||
> :is(li.item, section.item) {
|
||||
margin-inline: auto !important;
|
||||
}
|
||||
#menu#menu.bsplus-sidebar-style-strip .sub :is(li.item, section.item) {
|
||||
width: 100% !important;
|
||||
margin-inline: 0 !important;
|
||||
}
|
||||
|
||||
#menu.bsplus-icon-rail-switching > ul > .hasChildren > .sub {
|
||||
transition: none !important;
|
||||
}
|
||||
@@ -890,6 +896,16 @@ body.icon-only-sidebar {
|
||||
}
|
||||
}
|
||||
|
||||
#menu#menu.bsplus-sidebar-style-strip .sub :is(li.item, section.item) {
|
||||
width: 100% !important;
|
||||
box-sizing: border-box !important;
|
||||
margin-inline: 0 !important;
|
||||
}
|
||||
body:not(.icon-only-sidebar) #menu#menu.bsplus-sidebar-style-strip > ul > :is(li.item, section.item) {
|
||||
width: calc(100% + 1px) !important;
|
||||
box-sizing: border-box !important;
|
||||
}
|
||||
|
||||
body.icon-only-sidebar:has(
|
||||
#menu > ul > .hasChildren:is(.active, .bsplus-active)
|
||||
) {
|
||||
@@ -3876,8 +3892,55 @@ div.day-empty {
|
||||
box-sizing: border-box;
|
||||
}
|
||||
.userInfoHouseWrap .bsplus-founder-badge-slot {
|
||||
display: block;
|
||||
width: 100%;
|
||||
max-width: 100%;
|
||||
margin-top: 4px;
|
||||
box-sizing: border-box;
|
||||
}
|
||||
.bsplus-founder-badge-carousel {
|
||||
display: grid;
|
||||
width: 100%;
|
||||
max-width: 100%;
|
||||
box-sizing: border-box;
|
||||
}
|
||||
.bsplus-founder-badge-carousel > .bsplus-founder-badge {
|
||||
grid-area: 1 / 1;
|
||||
width: 100%;
|
||||
min-width: 0;
|
||||
opacity: 0;
|
||||
visibility: hidden;
|
||||
transform: translateY(5px);
|
||||
transition:
|
||||
opacity 0.45s ease,
|
||||
transform 0.45s ease,
|
||||
visibility 0s linear 0.45s;
|
||||
pointer-events: none;
|
||||
}
|
||||
.bsplus-founder-badge-carousel > .bsplus-founder-badge--active {
|
||||
opacity: 1;
|
||||
visibility: visible;
|
||||
transform: translateY(0);
|
||||
transition:
|
||||
opacity 0.45s ease,
|
||||
transform 0.45s ease,
|
||||
visibility 0s;
|
||||
pointer-events: auto;
|
||||
z-index: 1;
|
||||
}
|
||||
.bsplus-founder-badge-carousel--static > .bsplus-founder-badge {
|
||||
transition: none;
|
||||
transform: none;
|
||||
visibility: hidden;
|
||||
}
|
||||
.bsplus-founder-badge-carousel--static > .bsplus-founder-badge--active {
|
||||
visibility: visible;
|
||||
}
|
||||
@media (prefers-reduced-motion: reduce) {
|
||||
.bsplus-founder-badge-carousel > .bsplus-founder-badge {
|
||||
transition: none;
|
||||
transform: none;
|
||||
}
|
||||
}
|
||||
.userInfoHouseWrap .bsplus-founder-badge-slot[hidden],
|
||||
.bsplus-founder-badge-slot[hidden] {
|
||||
@@ -3887,28 +3950,35 @@ div.day-empty {
|
||||
display: block;
|
||||
width: 100%;
|
||||
border-radius: 5px;
|
||||
overflow: hidden;
|
||||
}
|
||||
.bsplus-founder-badge--titlebar .bsplus-founder-badge__glass,
|
||||
.bsplus-founder-badge--titlebar .bsplus-founder-badge__content {
|
||||
.bsplus-founder-badge--titlebar .bsplus-founder-badge__glass {
|
||||
display: flex;
|
||||
width: 100%;
|
||||
border-radius: 5px;
|
||||
box-sizing: border-box;
|
||||
box-shadow:
|
||||
inset 0 0 0 1px rgba(255, 255, 255, 0.22),
|
||||
inset 0 1px 0 rgba(255, 255, 255, 0.12);
|
||||
}
|
||||
.bsplus-founder-badge--titlebar .bsplus-founder-badge__content {
|
||||
display: flex;
|
||||
flex: 1 1 auto;
|
||||
width: 100%;
|
||||
justify-content: center;
|
||||
padding: 0 6px;
|
||||
gap: 0;
|
||||
min-height: 0;
|
||||
min-width: 0;
|
||||
height: auto;
|
||||
font-size: 15px;
|
||||
line-height: normal;
|
||||
border-radius: 5px;
|
||||
box-sizing: border-box;
|
||||
backdrop-filter: none;
|
||||
-webkit-backdrop-filter: none;
|
||||
background: rgba(255, 255, 255, 0.12);
|
||||
box-shadow:
|
||||
inset 0 0 0 1px rgba(255, 255, 255, 0.28),
|
||||
inset 0 1px 0 rgba(255, 255, 255, 0.16),
|
||||
inset 0 -1px 0 rgba(0, 0, 0, 0.12);
|
||||
background: rgba(255, 255, 255, 0.1);
|
||||
box-shadow: none;
|
||||
}
|
||||
.bsplus-founder-badge--titlebar .bsplus-founder-badge__label {
|
||||
display: block;
|
||||
@@ -3917,11 +3987,16 @@ div.day-empty {
|
||||
white-space: nowrap;
|
||||
text-align: center;
|
||||
}
|
||||
.bsplus-founder-badge--titlebar:focus-visible .bsplus-founder-badge__content {
|
||||
.bsplus-founder-badge--titlebar:hover {
|
||||
transform: none;
|
||||
}
|
||||
.bsplus-founder-badge--titlebar:focus-visible {
|
||||
outline: none;
|
||||
}
|
||||
.bsplus-founder-badge--titlebar:focus-visible .bsplus-founder-badge__glass {
|
||||
box-shadow:
|
||||
inset 0 0 0 1px rgba(255, 255, 255, 0.28),
|
||||
inset 0 1px 0 rgba(255, 255, 255, 0.16),
|
||||
inset 0 -1px 0 rgba(0, 0, 0, 0.12),
|
||||
inset 0 0 0 1px rgba(255, 255, 255, 0.22),
|
||||
inset 0 1px 0 rgba(255, 255, 255, 0.12),
|
||||
0 0 0 2px var(--theme-primary, #f97316),
|
||||
0 0 0 4px rgba(249, 115, 22, 0.35);
|
||||
}
|
||||
@@ -4079,6 +4154,24 @@ div.day-empty {
|
||||
.bsplus-founder-badge-hero__stage .bsplus-founder-badge {
|
||||
pointer-events: auto;
|
||||
}
|
||||
|
||||
.bsplus-remote-page-banner {
|
||||
width: 90%;
|
||||
margin: 0 auto 0.75rem;
|
||||
padding: 0.65rem 0.85rem;
|
||||
border-radius: 12px;
|
||||
border: 1px solid color-mix(in srgb, var(--text-primary) 14%, transparent);
|
||||
background: color-mix(in srgb, var(--text-primary) 5%, var(--background-primary));
|
||||
font-size: 0.95rem;
|
||||
line-height: 1.5;
|
||||
color: var(--text-primary);
|
||||
}
|
||||
|
||||
.bsplus-remote-page-banner__title {
|
||||
font-weight: 600;
|
||||
margin: 0 0 0.35rem;
|
||||
}
|
||||
|
||||
.whatsnewTextContainer.bsplus-founder-badge-body p {
|
||||
margin: 0 0 1rem;
|
||||
font-size: 1.2rem;
|
||||
@@ -4315,6 +4408,181 @@ div.day-empty {
|
||||
-webkit-backdrop-filter: none !important;
|
||||
}
|
||||
}
|
||||
|
||||
/* Terms of service — compact whatsnew shell (theme vars, light + dark) */
|
||||
#whatsnewbk.bsplus-tos-overlay {
|
||||
.whatsnewContainer.bsplus-tos-container {
|
||||
position: relative !important;
|
||||
width: min(34em, calc(100vw - 1.75rem)) !important;
|
||||
height: auto !important;
|
||||
max-height: min(32rem, calc(100vh - 2rem)) !important;
|
||||
margin: auto !important;
|
||||
padding: 0 0 1rem !important;
|
||||
display: flex !important;
|
||||
flex-direction: column !important;
|
||||
overflow: hidden !important;
|
||||
background: var(--background-primary) !important;
|
||||
color: var(--text-primary) !important;
|
||||
border-radius: 20px !important;
|
||||
box-shadow: 0 18px 50px rgba(0, 0, 0, 0.28) !important;
|
||||
}
|
||||
|
||||
.bsplus-tos-header {
|
||||
margin: 20px 20px 0.5rem !important;
|
||||
width: calc(100% - 40px) !important;
|
||||
height: auto !important;
|
||||
min-height: unset !important;
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
.bsplus-tos-header h1 {
|
||||
margin: 0 !important;
|
||||
font-size: 1.75rem !important;
|
||||
font-weight: 700 !important;
|
||||
line-height: 1.15 !important;
|
||||
color: var(--text-primary) !important;
|
||||
}
|
||||
|
||||
.bsplus-tos-header p {
|
||||
margin: 0.35rem 0 0 !important;
|
||||
font-size: 1rem !important;
|
||||
font-weight: 400 !important;
|
||||
line-height: 1.4 !important;
|
||||
color: var(--text-primary) !important;
|
||||
opacity: 0.88;
|
||||
}
|
||||
|
||||
.bsplus-tos-body {
|
||||
display: flex !important;
|
||||
flex-direction: column !important;
|
||||
gap: 0.75rem !important;
|
||||
width: 90% !important;
|
||||
margin: 0 auto !important;
|
||||
min-height: 0 !important;
|
||||
flex: 1 1 auto !important;
|
||||
overflow: hidden !important;
|
||||
font-size: 1.05rem !important;
|
||||
line-height: 1.6 !important;
|
||||
}
|
||||
|
||||
.bsplus-tos-intro {
|
||||
margin: 0 !important;
|
||||
flex-shrink: 0;
|
||||
text-align: center;
|
||||
font-size: 1rem !important;
|
||||
line-height: 1.5 !important;
|
||||
color: var(--text-primary) !important;
|
||||
}
|
||||
|
||||
.bsplus-tos-scroll {
|
||||
flex: 1 1 auto;
|
||||
min-height: 7rem;
|
||||
overflow-x: hidden;
|
||||
overflow-y: auto;
|
||||
padding: 0.65rem 0.75rem;
|
||||
text-align: left;
|
||||
font-size: 1.05rem !important;
|
||||
line-height: 1.6 !important;
|
||||
color: var(--text-primary) !important;
|
||||
border-radius: 12px;
|
||||
border: 1px solid color-mix(in srgb, var(--text-primary) 14%, transparent);
|
||||
background: color-mix(in srgb, var(--text-primary) 5%, var(--background-primary));
|
||||
}
|
||||
|
||||
.bsplus-tos-scroll h3,
|
||||
.bsplus-tos-scroll h4 {
|
||||
margin: 1rem 0 0.4rem;
|
||||
font-size: 1.15em !important;
|
||||
font-weight: 600 !important;
|
||||
line-height: 1.35 !important;
|
||||
color: var(--text-primary) !important;
|
||||
}
|
||||
|
||||
.bsplus-tos-scroll h3:first-child,
|
||||
.bsplus-tos-scroll h4:first-child,
|
||||
.bsplus-tos-scroll p:first-child {
|
||||
margin-top: 0;
|
||||
}
|
||||
|
||||
.bsplus-tos-scroll p {
|
||||
margin: 0 0 1ex;
|
||||
font-size: inherit !important;
|
||||
color: var(--text-primary) !important;
|
||||
}
|
||||
|
||||
.bsplus-tos-scroll ul,
|
||||
.bsplus-tos-scroll ol {
|
||||
margin: 0 0 1ex;
|
||||
padding-left: 1.25rem;
|
||||
}
|
||||
|
||||
.bsplus-tos-scroll li {
|
||||
margin: 0.15rem 0;
|
||||
}
|
||||
|
||||
.bsplus-tos-scroll a {
|
||||
color: inherit;
|
||||
text-decoration: underline;
|
||||
text-underline-offset: 2px;
|
||||
}
|
||||
|
||||
.bsplus-tos-actions {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 0.55rem;
|
||||
flex-shrink: 0;
|
||||
padding-top: 0.1rem;
|
||||
padding-bottom: 0.15rem;
|
||||
}
|
||||
|
||||
.bsplus-tos-btn {
|
||||
width: 100%;
|
||||
min-height: 2.65rem;
|
||||
padding: 0.65rem 1rem;
|
||||
border: none;
|
||||
border-radius: 12px;
|
||||
font-size: 0.95rem;
|
||||
font-weight: 600;
|
||||
font-family: inherit;
|
||||
cursor: pointer;
|
||||
transition: all 0.2s ease-in-out;
|
||||
}
|
||||
|
||||
.bsplus-tos-btn:focus {
|
||||
outline: none;
|
||||
}
|
||||
|
||||
.bsplus-tos-btn:focus-visible {
|
||||
box-shadow:
|
||||
0 0 0 2px var(--background-primary),
|
||||
0 0 0 4px color-mix(in srgb, var(--text-primary) 45%, transparent);
|
||||
}
|
||||
|
||||
.bsplus-tos-btn--primary {
|
||||
background: var(--text-primary);
|
||||
color: var(--background-primary);
|
||||
}
|
||||
|
||||
.bsplus-tos-btn--primary:hover:not(:disabled) {
|
||||
filter: brightness(1.08);
|
||||
transform: scale(1.02);
|
||||
}
|
||||
|
||||
.bsplus-tos-btn--secondary {
|
||||
background: color-mix(in srgb, var(--text-primary) 10%, var(--background-primary));
|
||||
color: var(--text-primary);
|
||||
border: 1px solid color-mix(in srgb, var(--text-primary) 16%, transparent);
|
||||
}
|
||||
|
||||
.bsplus-tos-btn--secondary:hover:not(:disabled) {
|
||||
background: color-mix(in srgb, var(--text-primary) 14%, var(--background-primary));
|
||||
transform: scale(1.02);
|
||||
}
|
||||
|
||||
.bsplus-tos-btn:active:not(:disabled) {
|
||||
transform: scale(0.98);
|
||||
}
|
||||
}
|
||||
.whatsnewImgContainer {
|
||||
width: 96%;
|
||||
display: flex;
|
||||
@@ -5666,3 +5934,76 @@ h2.home-subtitle {
|
||||
font-size: 20px;
|
||||
font-weight: 400;
|
||||
}
|
||||
|
||||
.bsplus-ld-surprise-root {
|
||||
position: fixed;
|
||||
inset: 0;
|
||||
z-index: 50;
|
||||
pointer-events: none;
|
||||
}
|
||||
|
||||
.bsplus-ld-surprise-popout {
|
||||
pointer-events: auto;
|
||||
position: fixed;
|
||||
right: 24px;
|
||||
bottom: 24px;
|
||||
width: min(640px, calc(100vw - 48px));
|
||||
aspect-ratio: 16 / 9;
|
||||
border-radius: 16px;
|
||||
overflow: hidden;
|
||||
background: #000;
|
||||
box-shadow: 0 22px 70px rgba(0, 0, 0, 0.35);
|
||||
border: 1px solid color-mix(in srgb, var(--text-primary) 12%, transparent);
|
||||
transform-origin: bottom right;
|
||||
animation: bsplusLdSurprisePopoutIn 0.28s ease-out;
|
||||
}
|
||||
|
||||
.bsplus-ld-surprise-player {
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
background: #000;
|
||||
|
||||
iframe {
|
||||
display: block;
|
||||
width: 640px;
|
||||
max-width: 100%;
|
||||
height: 360px;
|
||||
max-height: 100%;
|
||||
border: 0;
|
||||
}
|
||||
}
|
||||
|
||||
.bsplus-ld-surprise-close {
|
||||
position: absolute;
|
||||
top: 10px;
|
||||
right: 10px;
|
||||
z-index: 1;
|
||||
width: 36px;
|
||||
height: 36px;
|
||||
padding: 0;
|
||||
border: 0;
|
||||
border-radius: 999px;
|
||||
cursor: pointer;
|
||||
background: rgba(0, 0, 0, 0.55);
|
||||
color: #fff;
|
||||
}
|
||||
|
||||
.bsplus-ld-surprise-close::before {
|
||||
content: "\ed8a";
|
||||
font-family: "IconFamily";
|
||||
font-size: 20px;
|
||||
line-height: 1;
|
||||
pointer-events: none;
|
||||
}
|
||||
|
||||
@keyframes bsplusLdSurprisePopoutIn {
|
||||
from {
|
||||
opacity: 0;
|
||||
transform: scale(0.92) translateY(12px);
|
||||
}
|
||||
|
||||
to {
|
||||
opacity: 1;
|
||||
transform: scale(1) translateY(0);
|
||||
}
|
||||
}
|
||||
@@ -90,17 +90,24 @@ $sidebar-motion: 0.4s cubic-bezier(0.4, 0, 0.2, 1);
|
||||
}
|
||||
|
||||
&.bsplus-sidebar-style-glass {
|
||||
/* Never put backdrop-filter on an open folder — it becomes a clip
|
||||
containing-block and hides `.sub` labels on Chromium/Edge. */
|
||||
/* Never put backdrop-filter on a folder — it becomes a clip
|
||||
containing-block and hides `.sub` labels on Chromium/Edge. Lean rows
|
||||
blur; closed folders keep the translated glass surface without blur;
|
||||
open folders drop the fill entirely so `.sub` stays clip-safe. */
|
||||
#{$item} {
|
||||
&:not(:has(> .sub)) {
|
||||
margin: 0 8px 8px !important;
|
||||
margin: 4px 8px 4px !important;
|
||||
background: rgba(255, 255, 255, 0.1) !important;
|
||||
backdrop-filter: blur(10px);
|
||||
-webkit-backdrop-filter: blur(10px);
|
||||
box-shadow: inset 0 0 0 1px rgba(255, 255, 255, 0.14);
|
||||
}
|
||||
&:has(> .sub) {
|
||||
&:is(li, section).hasChildren:not(:is(.active, .bsplus-active)) {
|
||||
margin: 4px 8px 4px !important;
|
||||
background: rgba(255, 255, 255, 0.1) !important;
|
||||
box-shadow: inset 0 0 0 1px rgba(255, 255, 255, 0.14);
|
||||
}
|
||||
&:has(> .sub):is(.active, .bsplus-active) {
|
||||
background: transparent !important;
|
||||
backdrop-filter: none !important;
|
||||
-webkit-backdrop-filter: none !important;
|
||||
|
||||
@@ -0,0 +1,4 @@
|
||||
{
|
||||
"last_updated": "2026-10-29T00:00:00.000Z",
|
||||
"whatsnew_html": "<div class=\"whatsnewTextContainer\"><h3>1. Agreement</h3><p>By installing or using BetterSEQTA+, you agree to these Terms of Service. If you do not agree, do not use the extension.</p><h3>2. The extension</h3><p>BetterSEQTA+ is a browser extension that enhances SEQTA Learn and SEQTA Engage on your device. Features may change over time.</p><h3>3. Your school account</h3><p>You must comply with your school’s policies when using SEQTA. BetterSEQTA+ does not replace your school’s terms.</p><h3>4. Acceptable use</h3><p>Do not use the extension to harm others, bypass security, or violate applicable law.</p><h3>5. Privacy</h3><p>Our Privacy Policy explains what data we process. See <a href=\"https://betterseqta.org/privacy\" target=\"_blank\" rel=\"noopener noreferrer\">betterseqta.org/privacy</a>.</p><h3>6. Changes</h3><p>We may update these terms. Material changes may require you to accept again in the extension.</p></div>"
|
||||
}
|
||||
@@ -3,18 +3,31 @@
|
||||
onClick,
|
||||
text,
|
||||
disabled = false,
|
||||
variant = "secondary",
|
||||
icon,
|
||||
class: className = "",
|
||||
} = $props<{
|
||||
onClick: () => void;
|
||||
text: string;
|
||||
disabled?: boolean;
|
||||
variant?: "primary" | "secondary" | "ghost";
|
||||
icon?: string;
|
||||
class?: string;
|
||||
}>();
|
||||
|
||||
const variants = {
|
||||
primary: "bg-zinc-100 text-zinc-900 border-transparent enabled:hover:bg-white",
|
||||
secondary: "dark:bg-[#38373D]/50 bg-[#DDDDDD]/50 border-[#DDDDDD]/30 dark:border-[#38373D]/30 dark:text-white enabled:hover:brightness-125",
|
||||
ghost: "bg-transparent border-transparent dark:text-white enabled:hover:bg-zinc-200/60 dark:enabled:hover:bg-zinc-700/50",
|
||||
};
|
||||
</script>
|
||||
|
||||
<button
|
||||
type="button"
|
||||
onclick={onClick}
|
||||
disabled={disabled}
|
||||
class="px-5 py-1.5 text-[0.75rem] shadow-2xl border dark:bg-[#38373D]/50 bg-[#DDDDDD]/50 border-[#DDDDDD]/30 dark:border-[#38373D]/30 dark:text-white rounded-lg disabled:cursor-not-allowed disabled:opacity-50"
|
||||
class="inline-flex items-center justify-center gap-1.5 px-5 py-1.5 text-[0.75rem] shadow-2xl border rounded-lg transition enabled:active:scale-[0.96] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-zinc-400 disabled:cursor-not-allowed disabled:opacity-50 {variants[variant]} {className}"
|
||||
>
|
||||
{#if icon}<span class="font-IconFamily text-base" aria-hidden="true">{icon}</span>{/if}
|
||||
{text}
|
||||
</button>
|
||||
</button>
|
||||
@@ -5,6 +5,7 @@
|
||||
import { cloudAuth } from "@/seqta/utils/CloudAuth";
|
||||
import { settingsState } from "@/seqta/utils/listeners/SettingsState";
|
||||
import CloudPfpAvatar from "@/interface/components/CloudPfpAvatar.svelte";
|
||||
import Button from "./Button.svelte";
|
||||
|
||||
const { hidePanel } = $props<{
|
||||
hidePanel: () => void;
|
||||
@@ -139,13 +140,7 @@
|
||||
<p class="text-sm text-zinc-600 dark:text-zinc-400">
|
||||
Sign in to sync settings across devices, use your cloud profile picture, and more.
|
||||
</p>
|
||||
<button
|
||||
type="button"
|
||||
onclick={handleSignIn}
|
||||
class="w-full px-4 py-2.5 text-sm font-medium rounded-lg bg-zinc-800 dark:bg-zinc-200 text-white dark:text-zinc-900 hover:bg-zinc-700 dark:hover:bg-zinc-300 transition-colors duration-200"
|
||||
>
|
||||
Sign in with BetterSEQTA Cloud
|
||||
</button>
|
||||
<Button class="w-full" icon={""} text="Sign in with BetterSEQTA Cloud" onClick={handleSignIn} />
|
||||
{#if loginError}
|
||||
<p class="text-xs text-red-600 dark:text-red-400">{loginError}</p>
|
||||
{/if}
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
import { fade } from "svelte/transition";
|
||||
import browser from "webextension-polyfill";
|
||||
import QRCode from "qrcode";
|
||||
import Button from "./Button.svelte";
|
||||
import { portal } from "../utils/portal";
|
||||
import { settingsState } from "@/seqta/utils/listeners/SettingsState";
|
||||
|
||||
@@ -106,13 +107,7 @@
|
||||
</script>
|
||||
|
||||
<div class="flex flex-col gap-1 items-end">
|
||||
<button
|
||||
type="button"
|
||||
onclick={generateQrCode}
|
||||
disabled={isLoading}
|
||||
class="px-5 py-1.5 text-[0.75rem] text-nowrap shadow-2xl border dark:bg-[#38373D]/50 bg-[#DDDDDD]/50 border-[#DDDDDD]/30 dark:border-[#38373D]/30 dark:text-white rounded-lg disabled:opacity-50 disabled:cursor-not-allowed transition-opacity">
|
||||
{isLoading ? "Generating..." : "Generate QR"}
|
||||
</button>
|
||||
<Button onClick={generateQrCode} disabled={isLoading} text={isLoading ? "Generating..." : "Generate QR"} />
|
||||
{#if errorMessage}
|
||||
<p class="text-xs text-right text-amber-600 dark:text-amber-400">{errorMessage}</p>
|
||||
{/if}
|
||||
|
||||
@@ -0,0 +1,99 @@
|
||||
<script lang="ts">
|
||||
import {
|
||||
dismissOptionalRemoteTheme,
|
||||
getRemoteConfigSnapshot,
|
||||
isEffectiveBsplusEnabled,
|
||||
isRemoteKillActive,
|
||||
resolveEffectiveRemoteTheme,
|
||||
setLocalOverrideOnoff,
|
||||
} from "@/seqta/utils/remoteConfig/runtime";
|
||||
import { getRemoteStatusMessage } from "@/seqta/utils/remoteConfig/apply";
|
||||
import { settingsState } from "@/seqta/utils/listeners/SettingsState";
|
||||
import { requestSettingsDestination } from "@/seqta/utils/settingsNavigation";
|
||||
import browser from "webextension-polyfill";
|
||||
import { onMount } from "svelte";
|
||||
|
||||
let localOverride = $state(false);
|
||||
|
||||
const snapshot = $derived(getRemoteConfigSnapshot());
|
||||
const activeTheme = $derived(resolveEffectiveRemoteTheme(snapshot));
|
||||
const killActive = $derived(isRemoteKillActive());
|
||||
const statusMessage = $derived(getRemoteStatusMessage(snapshot));
|
||||
const allowOverride = $derived(snapshot.global.allowLocalOverride !== false);
|
||||
const showStrip = $derived(
|
||||
killActive ||
|
||||
activeTheme?.mode === "optional" ||
|
||||
!!statusMessage ||
|
||||
!!snapshot.global.maintenance?.body ||
|
||||
!!snapshot.global.maintenance?.title,
|
||||
);
|
||||
|
||||
async function turnOffOptionalTheme() {
|
||||
await dismissOptionalRemoteTheme(snapshot);
|
||||
location.reload();
|
||||
}
|
||||
|
||||
onMount(() => {
|
||||
void browser.storage.local.get("bsplus_local_override_onoff").then((stored) => {
|
||||
localOverride = stored.bsplus_local_override_onoff === true;
|
||||
});
|
||||
});
|
||||
|
||||
async function enableLocalRun() {
|
||||
await setLocalOverrideOnoff(true);
|
||||
localOverride = true;
|
||||
location.reload();
|
||||
}
|
||||
|
||||
function openGeneralSettings() {
|
||||
requestSettingsDestination({ section: "general" });
|
||||
}
|
||||
</script>
|
||||
|
||||
{#if showStrip}
|
||||
<div
|
||||
class="shrink-0 border-b border-amber-200/80 bg-amber-50 px-4 py-3 text-sm text-amber-950 dark:border-amber-900/60 dark:bg-amber-950/40 dark:text-amber-50"
|
||||
role="status"
|
||||
>
|
||||
<p class="leading-relaxed">
|
||||
{activeTheme?.mode === "optional" && activeTheme.message?.body
|
||||
? activeTheme.message.body
|
||||
: statusMessage ??
|
||||
"BetterSEQTA+ is temporarily limited. You can review settings for details."}
|
||||
</p>
|
||||
<div class="mt-2 flex flex-wrap items-center gap-2">
|
||||
{#if activeTheme?.mode === "optional" && snapshot.remoteTheme?.allowUserOptOut !== false}
|
||||
<button
|
||||
type="button"
|
||||
class="rounded-lg bg-amber-600 px-3 py-1.5 text-xs font-semibold text-white transition-all duration-200 hover:scale-105 active:scale-95 focus:outline-none focus:ring-2 focus:ring-amber-500 focus:ring-offset-2 dark:focus:ring-offset-zinc-900"
|
||||
onclick={() => void turnOffOptionalTheme()}
|
||||
>
|
||||
Turn off school theme
|
||||
</button>
|
||||
{/if}
|
||||
{#if killActive && !isEffectiveBsplusEnabled() && allowOverride}
|
||||
<button
|
||||
type="button"
|
||||
class="rounded-lg bg-amber-600 px-3 py-1.5 text-xs font-semibold text-white transition-all duration-200 hover:scale-105 active:scale-95 focus:outline-none focus:ring-2 focus:ring-amber-500 focus:ring-offset-2 dark:focus:ring-offset-zinc-900"
|
||||
onclick={enableLocalRun}
|
||||
>
|
||||
Run locally anyway
|
||||
</button>
|
||||
{:else if killActive && localOverride && isEffectiveBsplusEnabled()}
|
||||
<span class="text-xs text-amber-800 dark:text-amber-200/90">
|
||||
Running locally (override). Reload SEQTA after the operator clears the kill switch.
|
||||
</span>
|
||||
{/if}
|
||||
<button
|
||||
type="button"
|
||||
class="rounded-lg border border-amber-300/80 px-3 py-1.5 text-xs font-medium transition-colors duration-200 hover:bg-amber-100/80 focus:outline-none focus:ring-2 focus:ring-amber-500 focus:ring-offset-2 dark:border-amber-800 dark:hover:bg-amber-900/50 dark:focus:ring-offset-zinc-900"
|
||||
onclick={openGeneralSettings}
|
||||
>
|
||||
General settings
|
||||
</button>
|
||||
{#if $settingsState.onoff === false}
|
||||
<span class="text-xs opacity-80">Master toggle is off in General.</span>
|
||||
{/if}
|
||||
</div>
|
||||
</div>
|
||||
{/if}
|
||||
@@ -1,12 +1,14 @@
|
||||
<script lang="ts">
|
||||
import SettingsCard from "@/interface/pages/settings/SettingsCard.svelte";
|
||||
import SettingRow from "@/interface/pages/settings/SettingRow.svelte";
|
||||
import Select from "@/interface/components/Select.svelte";
|
||||
import Slider from "@/interface/components/Slider.svelte";
|
||||
import Switch from "@/interface/components/Switch.svelte";
|
||||
import { settingsState } from "@/seqta/utils/listeners/SettingsState";
|
||||
import { matchesSearch } from "@/interface/pages/settings/shared";
|
||||
import {
|
||||
DEFAULT_SIDEBAR_BLUR,
|
||||
DEFAULT_SIDEBAR_RADIUS,
|
||||
getSidebarStyle,
|
||||
normalizeSidebarBlur,
|
||||
normalizeSidebarDensity,
|
||||
normalizeSidebarIndicator,
|
||||
@@ -15,676 +17,152 @@
|
||||
normalizeSidebarWidth,
|
||||
normalizeSidebarPosition,
|
||||
SIDEBAR_STYLES,
|
||||
type SidebarStyleId,
|
||||
} from "@/seqta/ui/sidebar/sidebarStyles";
|
||||
|
||||
const PREVIEW_ITEMS = [
|
||||
{ label: "Home", active: true },
|
||||
{ label: "Timetable", active: false },
|
||||
{ label: "Assessments", active: false },
|
||||
{ label: "Messages", active: false },
|
||||
{ label: "Documents", active: false },
|
||||
] as const;
|
||||
let { searchQuery = "" }: { searchQuery?: string } = $props();
|
||||
|
||||
const selectedId = $derived(
|
||||
normalizeSidebarStyleId($settingsState.sidebarStyle),
|
||||
);
|
||||
const selected = $derived(getSidebarStyle(selectedId));
|
||||
const density = $derived(
|
||||
normalizeSidebarDensity($settingsState.sidebarDensity),
|
||||
);
|
||||
const indicator = $derived(
|
||||
normalizeSidebarIndicator($settingsState.sidebarActiveIndicator),
|
||||
);
|
||||
const width = $derived(normalizeSidebarWidth($settingsState.sidebarWidth));
|
||||
const position = $derived(
|
||||
normalizeSidebarPosition($settingsState.sidebarPosition),
|
||||
);
|
||||
const radius = $derived(
|
||||
normalizeSidebarRadius(
|
||||
const styleOptions = SIDEBAR_STYLES.map((s) => ({ value: s.id, label: s.label }));
|
||||
|
||||
const rows = $derived.by(() => {
|
||||
const density = normalizeSidebarDensity($settingsState.sidebarDensity);
|
||||
const indicator = normalizeSidebarIndicator($settingsState.sidebarActiveIndicator);
|
||||
const width = normalizeSidebarWidth($settingsState.sidebarWidth);
|
||||
const position = normalizeSidebarPosition($settingsState.sidebarPosition);
|
||||
const radius = normalizeSidebarRadius(
|
||||
$settingsState.sidebarCornerRadius ?? DEFAULT_SIDEBAR_RADIUS,
|
||||
),
|
||||
);
|
||||
const blur = $derived(
|
||||
normalizeSidebarBlur($settingsState.sidebarBlur ?? DEFAULT_SIDEBAR_BLUR),
|
||||
);
|
||||
const transparencyOn = $derived($settingsState.transparencyEffects === true);
|
||||
);
|
||||
const blur = normalizeSidebarBlur($settingsState.sidebarBlur ?? DEFAULT_SIDEBAR_BLUR);
|
||||
const transparencyOn = $settingsState.transparencyEffects === true;
|
||||
const styleId = normalizeSidebarStyleId($settingsState.sidebarStyle);
|
||||
|
||||
function selectStyle(id: SidebarStyleId) {
|
||||
if (selectedId !== id) settingsState.sidebarStyle = id;
|
||||
}
|
||||
</script>
|
||||
|
||||
<div class="sidebar-appearance">
|
||||
<div class="card">
|
||||
<header class="card-header split">
|
||||
<div>
|
||||
<h2 class="title">Sidebar Style</h2>
|
||||
<p class="subtitle">Choose how the navigation menu looks</p>
|
||||
</div>
|
||||
<div class="selected-meta" aria-live="polite">
|
||||
<span class="selected-label">{selected.label}</span>
|
||||
<span class="selected-desc">{selected.description}</span>
|
||||
</div>
|
||||
</header>
|
||||
|
||||
<div class="picker-body">
|
||||
<div class="preview-pane" aria-hidden="true">
|
||||
<div class={`preview style-${selectedId}`}>
|
||||
<div class="preview-chrome">
|
||||
<div class="preview-logo"></div>
|
||||
{#each PREVIEW_ITEMS as item (item.label)}
|
||||
<div class="preview-item" class:active={item.active}>
|
||||
<span class="preview-dot"></span>
|
||||
<span class="preview-label">{item.label}</span>
|
||||
</div>
|
||||
{/each}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div
|
||||
class="options"
|
||||
role="listbox"
|
||||
tabindex="0"
|
||||
aria-label="Sidebar styles"
|
||||
aria-activedescendant={`sidebar-style-${selectedId}`}
|
||||
>
|
||||
{#each SIDEBAR_STYLES as style (style.id)}
|
||||
{@const active = style.id === selectedId}
|
||||
<button
|
||||
type="button"
|
||||
id={`sidebar-style-${style.id}`}
|
||||
class={`option style-${style.id}`}
|
||||
class:active
|
||||
role="option"
|
||||
aria-selected={active}
|
||||
onclick={() => selectStyle(style.id)}
|
||||
>
|
||||
<div class={`thumb style-${style.id}`}>
|
||||
<div class="thumb-chrome">
|
||||
{#each PREVIEW_ITEMS.slice(0, 3) as item (item.label)}
|
||||
<div class="thumb-item" class:active={item.active}></div>
|
||||
{/each}
|
||||
</div>
|
||||
</div>
|
||||
<span class="option-label">{style.label}</span>
|
||||
</button>
|
||||
{/each}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="card">
|
||||
<header class="card-header">
|
||||
<h2 class="title">Sidebar Look</h2>
|
||||
<p class="subtitle">Density, size, and active-state details</p>
|
||||
</header>
|
||||
|
||||
<div class="rows">
|
||||
<div class="row">
|
||||
<div class="copy">
|
||||
<h3 class="row-title">Item Size</h3>
|
||||
<p class="row-desc">Spacing and type size for menu rows</p>
|
||||
</div>
|
||||
<div class="control">
|
||||
<Select
|
||||
value={density}
|
||||
onChange={(value) => (settingsState.sidebarDensity = value)}
|
||||
options={[
|
||||
const base = [
|
||||
{
|
||||
title: "Sidebar Style",
|
||||
description: "Choose how the navigation menu looks",
|
||||
id: 1,
|
||||
Component: Select,
|
||||
props: {
|
||||
value: styleId,
|
||||
onChange: (value: string) => (settingsState.sidebarStyle = value),
|
||||
options: styleOptions,
|
||||
},
|
||||
},
|
||||
{
|
||||
title: "Item Size",
|
||||
description: "Spacing and type size for menu rows",
|
||||
id: 2,
|
||||
Component: Select,
|
||||
props: {
|
||||
value: density,
|
||||
onChange: (value: string) => (settingsState.sidebarDensity = value),
|
||||
options: [
|
||||
{ value: "compact", label: "Compact" },
|
||||
{ value: "comfortable", label: "Comfortable" },
|
||||
{ value: "large", label: "Large" },
|
||||
]}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="row">
|
||||
<div class="copy">
|
||||
<h3 class="row-title">Corner Radius</h3>
|
||||
<p class="row-desc">Roundness of menu items ({radius}px)</p>
|
||||
</div>
|
||||
<div class="control slider">
|
||||
<Slider
|
||||
state={radius}
|
||||
min={0}
|
||||
max={24}
|
||||
step={1}
|
||||
onChange={(value) => (settingsState.sidebarCornerRadius = value)}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="row">
|
||||
<div class="copy">
|
||||
<h3 class="row-title">Active Indicator</h3>
|
||||
<p class="row-desc">How the current page is highlighted</p>
|
||||
</div>
|
||||
<div class="control">
|
||||
<Select
|
||||
value={indicator}
|
||||
onChange={(value) => (settingsState.sidebarActiveIndicator = value)}
|
||||
options={[
|
||||
],
|
||||
},
|
||||
},
|
||||
{
|
||||
title: "Corner Radius",
|
||||
description: `Roundness of menu items (${radius}px)`,
|
||||
id: 3,
|
||||
Component: Slider,
|
||||
props: {
|
||||
state: radius,
|
||||
min: 0,
|
||||
max: 24,
|
||||
step: 1,
|
||||
onChange: (value: number) => (settingsState.sidebarCornerRadius = value),
|
||||
},
|
||||
},
|
||||
{
|
||||
title: "Active Indicator",
|
||||
description: "How the current page is highlighted",
|
||||
id: 4,
|
||||
Component: Select,
|
||||
props: {
|
||||
value: indicator,
|
||||
onChange: (value: string) => (settingsState.sidebarActiveIndicator = value),
|
||||
options: [
|
||||
{ value: "fill", label: "Fill" },
|
||||
{ value: "bar", label: "Left bar" },
|
||||
{ value: "outline", label: "Outline" },
|
||||
{ value: "underline", label: "Underline" },
|
||||
]}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="row">
|
||||
<div class="copy">
|
||||
<h3 class="row-title">Sidebar Position</h3>
|
||||
<p class="row-desc">Which edge of the screen the navigation sits on</p>
|
||||
</div>
|
||||
<div class="control">
|
||||
<Select
|
||||
value={position}
|
||||
onChange={(value) => (settingsState.sidebarPosition = value)}
|
||||
options={[
|
||||
],
|
||||
},
|
||||
},
|
||||
{
|
||||
title: "Sidebar Position",
|
||||
description: "Which edge of the screen the navigation sits on",
|
||||
id: 5,
|
||||
Component: Select,
|
||||
props: {
|
||||
value: position,
|
||||
onChange: (value: string) => (settingsState.sidebarPosition = value),
|
||||
options: [
|
||||
{ value: "left", label: "Left" },
|
||||
{ value: "right", label: "Right" },
|
||||
]}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="row">
|
||||
<div class="copy">
|
||||
<h3 class="row-title">Sidebar Width</h3>
|
||||
<p class="row-desc">Overall navigation column width</p>
|
||||
</div>
|
||||
<div class="control">
|
||||
<Select
|
||||
value={width}
|
||||
onChange={(value) => (settingsState.sidebarWidth = value)}
|
||||
options={[
|
||||
],
|
||||
},
|
||||
},
|
||||
{
|
||||
title: "Sidebar Width",
|
||||
description: "Overall navigation column width",
|
||||
id: 6,
|
||||
Component: Select,
|
||||
props: {
|
||||
value: width,
|
||||
onChange: (value: string) => (settingsState.sidebarWidth = value),
|
||||
options: [
|
||||
{ value: "narrow", label: "Narrow" },
|
||||
{ value: "default", label: "Default" },
|
||||
{ value: "wide", label: "Wide" },
|
||||
]}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="row">
|
||||
<div class="copy">
|
||||
<h3 class="row-title">Transparency Effects</h3>
|
||||
<p class="row-desc">Use glass effects on supported surfaces (may impact battery life)</p>
|
||||
</div>
|
||||
<div class="control toggle">
|
||||
<Switch
|
||||
state={transparencyOn}
|
||||
onChange={(value) => (settingsState.transparencyEffects = value)}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{#if transparencyOn}
|
||||
<div class="row">
|
||||
<div class="copy">
|
||||
<h3 class="row-title">Blur Strength</h3>
|
||||
<p class="row-desc">Glass blur on the sidebar ({blur}px)</p>
|
||||
</div>
|
||||
<div class="control slider">
|
||||
<Slider
|
||||
state={blur}
|
||||
min={0}
|
||||
max={80}
|
||||
step={1}
|
||||
onChange={(value) => (settingsState.sidebarBlur = value)}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
{/if}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
</div>
|
||||
|
||||
<style>
|
||||
.sidebar-appearance {
|
||||
container: sidebar-appearance / inline-size;
|
||||
}
|
||||
|
||||
.card {
|
||||
margin: 4px 0;
|
||||
padding: 4px;
|
||||
border-radius: 0.75rem;
|
||||
border: 1px solid rgb(228 228 231 / 0.5);
|
||||
background: linear-gradient(to bottom right, white, rgb(244 244 245));
|
||||
box-shadow: 0 1px 2px rgb(0 0 0 / 0.05);
|
||||
}
|
||||
|
||||
:global(.dark) .card {
|
||||
border-color: rgb(63 63 70 / 0.4);
|
||||
background: linear-gradient(
|
||||
to bottom right,
|
||||
rgb(24 24 27 / 0.4),
|
||||
rgb(24 24 27 / 0.5)
|
||||
);
|
||||
}
|
||||
|
||||
.card-header {
|
||||
padding: 1rem 1.25rem 0.5rem;
|
||||
}
|
||||
|
||||
.card-header.split {
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
gap: 1rem;
|
||||
align-items: flex-start;
|
||||
}
|
||||
|
||||
.title {
|
||||
font-size: 1.25rem;
|
||||
font-weight: 700;
|
||||
line-height: 1.3;
|
||||
}
|
||||
|
||||
.subtitle {
|
||||
margin-top: 0.15rem;
|
||||
font-size: 1rem;
|
||||
color: rgb(82 82 91);
|
||||
}
|
||||
|
||||
:global(.dark) .subtitle {
|
||||
color: rgb(212 212 216);
|
||||
}
|
||||
|
||||
.selected-meta {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: flex-end;
|
||||
text-align: right;
|
||||
max-width: 14rem;
|
||||
gap: 0.15rem;
|
||||
}
|
||||
|
||||
.selected-label {
|
||||
font-size: 0.95rem;
|
||||
font-weight: 700;
|
||||
}
|
||||
|
||||
.selected-desc {
|
||||
font-size: 0.8rem;
|
||||
line-height: 1.35;
|
||||
color: rgb(113 113 122);
|
||||
}
|
||||
|
||||
:global(.dark) .selected-desc {
|
||||
color: rgb(161 161 170);
|
||||
}
|
||||
|
||||
.picker-body {
|
||||
display: grid;
|
||||
grid-template-columns: minmax(160px, 210px) 1fr;
|
||||
gap: 1rem;
|
||||
padding: 0.5rem 1rem 1rem;
|
||||
}
|
||||
|
||||
@media (max-width: 720px) {
|
||||
.picker-body {
|
||||
grid-template-columns: 1fr;
|
||||
}
|
||||
}
|
||||
|
||||
.preview-pane {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
}
|
||||
|
||||
.preview {
|
||||
width: 100%;
|
||||
max-width: 196px;
|
||||
height: 280px;
|
||||
border-radius: 18px;
|
||||
overflow: hidden;
|
||||
box-shadow: 0 14px 32px rgb(0 0 0 / 0.22);
|
||||
background: linear-gradient(160deg, #aa053a, #141414 70%);
|
||||
}
|
||||
|
||||
.preview-chrome {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
height: 100%;
|
||||
padding: 14px 0 10px;
|
||||
color: #fff;
|
||||
}
|
||||
|
||||
.preview-logo {
|
||||
width: 42%;
|
||||
height: 10px;
|
||||
margin: 0 16px 14px;
|
||||
border-radius: 999px;
|
||||
background: rgb(255 255 255 / 0.35);
|
||||
}
|
||||
|
||||
.preview-item {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
margin: 0 8px 6px;
|
||||
padding: 8px 10px;
|
||||
border-radius: 12px;
|
||||
}
|
||||
|
||||
.preview-item.active {
|
||||
background: rgba(0, 0, 0, 0.35);
|
||||
}
|
||||
|
||||
.preview.style-soft .preview-item {
|
||||
margin: 0 10px 8px;
|
||||
border-radius: 16px;
|
||||
box-shadow: 0 2px 8px rgba(0, 0, 0, 0.18);
|
||||
}
|
||||
|
||||
.preview.style-pill .preview-item {
|
||||
margin: 0 12px 7px;
|
||||
border-radius: 999px;
|
||||
}
|
||||
|
||||
.preview.style-glass .preview-item {
|
||||
margin: 0 10px 7px;
|
||||
background: rgba(255, 255, 255, 0.12);
|
||||
box-shadow: inset 0 0 0 1px rgba(255, 255, 255, 0.16);
|
||||
}
|
||||
|
||||
.preview.style-glass .preview-item.active {
|
||||
background: rgba(255, 255, 255, 0.22);
|
||||
}
|
||||
|
||||
.preview.style-sharp .preview-item {
|
||||
margin: 0 6px 4px;
|
||||
border-radius: 4px;
|
||||
}
|
||||
|
||||
.preview.style-strip .preview-item {
|
||||
margin: 0;
|
||||
border-radius: 0;
|
||||
background: transparent;
|
||||
}
|
||||
|
||||
.preview.style-strip .preview-item.active {
|
||||
position: relative;
|
||||
background: rgba(255, 255, 255, 0.12);
|
||||
}
|
||||
|
||||
.preview.style-strip .preview-item.active::after {
|
||||
content: "";
|
||||
position: absolute;
|
||||
left: 0;
|
||||
top: 6px;
|
||||
bottom: 6px;
|
||||
width: 3px;
|
||||
border-radius: 2px;
|
||||
background: #fff;
|
||||
box-shadow: 0 0 8px rgba(255, 255, 255, 0.55);
|
||||
}
|
||||
|
||||
.preview.style-neon .preview-item.active {
|
||||
background: rgba(255, 255, 255, 0.1);
|
||||
box-shadow:
|
||||
0 0 0 1px rgba(255, 255, 255, 0.55),
|
||||
0 0 12px rgba(255, 255, 255, 0.4),
|
||||
0 0 22px rgba(255, 255, 255, 0.22);
|
||||
}
|
||||
|
||||
.preview-dot {
|
||||
width: 10px;
|
||||
height: 10px;
|
||||
border-radius: 999px;
|
||||
background: rgb(255 255 255 / 0.75);
|
||||
flex: 0 0 auto;
|
||||
}
|
||||
|
||||
.preview-label {
|
||||
font-size: 11px;
|
||||
font-weight: 600;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.options {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(auto-fill, minmax(96px, 1fr));
|
||||
gap: 0.65rem;
|
||||
align-content: start;
|
||||
}
|
||||
|
||||
.option {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: center;
|
||||
gap: 0.4rem;
|
||||
padding: 0.45rem;
|
||||
border: 1px solid transparent;
|
||||
border-radius: 0.75rem;
|
||||
background: rgb(255 255 255 / 0.55);
|
||||
color: inherit;
|
||||
cursor: pointer;
|
||||
transition:
|
||||
transform 0.2s ease,
|
||||
border-color 0.2s ease,
|
||||
box-shadow 0.2s ease;
|
||||
}
|
||||
|
||||
:global(.dark) .option {
|
||||
background: rgb(39 39 42 / 0.55);
|
||||
}
|
||||
|
||||
.option:hover {
|
||||
transform: scale(1.02);
|
||||
}
|
||||
|
||||
.option:active {
|
||||
transform: scale(0.98);
|
||||
}
|
||||
|
||||
.option.active {
|
||||
border-color: var(--theme-primary, #f43f5e);
|
||||
box-shadow: 0 0 0 1px var(--theme-primary, #f43f5e);
|
||||
}
|
||||
|
||||
.option:focus-visible {
|
||||
outline: none;
|
||||
box-shadow: 0 0 0 2px var(--theme-primary, #f43f5e);
|
||||
}
|
||||
|
||||
.thumb {
|
||||
width: 100%;
|
||||
aspect-ratio: 3 / 4;
|
||||
border-radius: 10px;
|
||||
overflow: hidden;
|
||||
background: linear-gradient(160deg, #aa053a, #141414 70%);
|
||||
}
|
||||
|
||||
.thumb-chrome {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
justify-content: center;
|
||||
gap: 4px;
|
||||
height: 100%;
|
||||
padding: 8px 6px;
|
||||
}
|
||||
|
||||
.thumb-item {
|
||||
height: 10px;
|
||||
border-radius: 6px;
|
||||
background: rgba(255, 255, 255, 0.18);
|
||||
}
|
||||
|
||||
.thumb-item.active {
|
||||
background: rgba(0, 0, 0, 0.4);
|
||||
}
|
||||
|
||||
.thumb.style-pill .thumb-item {
|
||||
border-radius: 999px;
|
||||
}
|
||||
|
||||
.thumb.style-sharp .thumb-item {
|
||||
border-radius: 2px;
|
||||
}
|
||||
|
||||
.thumb.style-strip .thumb-item {
|
||||
border-radius: 0;
|
||||
}
|
||||
|
||||
.thumb.style-strip .thumb-item.active {
|
||||
background: rgba(255, 255, 255, 0.22);
|
||||
box-shadow: inset 3px 0 0 #fff;
|
||||
}
|
||||
|
||||
.thumb.style-glass .thumb-item {
|
||||
background: rgba(255, 255, 255, 0.22);
|
||||
}
|
||||
|
||||
.thumb.style-neon .thumb-item.active {
|
||||
background: rgba(255, 255, 255, 0.2);
|
||||
box-shadow:
|
||||
0 0 0 1px rgba(255, 255, 255, 0.5),
|
||||
0 0 8px rgba(255, 255, 255, 0.55);
|
||||
}
|
||||
|
||||
.option-label {
|
||||
font-size: 0.8rem;
|
||||
font-weight: 700;
|
||||
}
|
||||
|
||||
.rows {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
padding: 0.25rem 0.5rem 0.75rem;
|
||||
}
|
||||
|
||||
.row {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
gap: 1rem;
|
||||
padding: 0.85rem 0.75rem;
|
||||
border-top: 1px solid rgb(244 244 245);
|
||||
}
|
||||
|
||||
:global(.dark) .row {
|
||||
border-top-color: rgb(63 63 70 / 0.5);
|
||||
}
|
||||
|
||||
.row:first-child {
|
||||
border-top: none;
|
||||
}
|
||||
|
||||
.copy {
|
||||
min-width: 0;
|
||||
flex: 1 1 auto;
|
||||
padding-right: 0.5rem;
|
||||
}
|
||||
|
||||
.row-title {
|
||||
font-size: 1.125rem;
|
||||
font-weight: 700;
|
||||
line-height: 1.3;
|
||||
}
|
||||
|
||||
.row-desc {
|
||||
margin-top: 0.1rem;
|
||||
font-size: 0.95rem;
|
||||
color: rgb(82 82 91);
|
||||
}
|
||||
|
||||
:global(.dark) .row-desc {
|
||||
color: rgb(212 212 216);
|
||||
}
|
||||
|
||||
.control {
|
||||
flex: 0 0 auto;
|
||||
min-width: 9.5rem;
|
||||
max-width: 12rem;
|
||||
}
|
||||
|
||||
.control.slider {
|
||||
min-width: 10rem;
|
||||
width: 11rem;
|
||||
}
|
||||
|
||||
.control.toggle {
|
||||
display: flex;
|
||||
justify-content: flex-end;
|
||||
}
|
||||
@container sidebar-appearance (max-width: 500px) {
|
||||
.preview-pane,
|
||||
.thumb {
|
||||
display: none;
|
||||
}
|
||||
|
||||
.picker-body {
|
||||
grid-template-columns: minmax(0, 1fr);
|
||||
gap: 0;
|
||||
}
|
||||
|
||||
.options {
|
||||
grid-template-columns: repeat(2, minmax(0, 1fr));
|
||||
gap: 0.5rem;
|
||||
}
|
||||
|
||||
.option {
|
||||
min-height: 2.5rem;
|
||||
justify-content: center;
|
||||
padding: 0.5rem;
|
||||
}
|
||||
|
||||
.option.style-soft {
|
||||
border-radius: 1rem;
|
||||
box-shadow: 0 3px 8px rgb(0 0 0 / 0.2);
|
||||
}
|
||||
|
||||
.option.style-pill {
|
||||
border-radius: 999px;
|
||||
}
|
||||
|
||||
.option.style-glass {
|
||||
background: linear-gradient(135deg, rgb(148 163 184 / 0.24), rgb(148 163 184 / 0.08));
|
||||
box-shadow: inset 0 0 0 1px rgb(148 163 184 / 0.35);
|
||||
}
|
||||
|
||||
.option.style-sharp {
|
||||
border-radius: 0.25rem;
|
||||
}
|
||||
|
||||
.option.style-strip {
|
||||
border-radius: 0;
|
||||
border-left: 3px solid currentColor;
|
||||
}
|
||||
|
||||
.option.style-neon {
|
||||
box-shadow: 0 0 0 1px rgb(148 163 184 / 0.6), 0 0 12px rgb(148 163 184 / 0.4);
|
||||
}
|
||||
|
||||
.option.active {
|
||||
outline: 1px solid currentColor;
|
||||
outline-offset: 2px;
|
||||
}
|
||||
|
||||
.option-label {
|
||||
font-size: 0.775rem;
|
||||
}
|
||||
|
||||
.card-header.split {
|
||||
gap: 0.5rem;
|
||||
}
|
||||
|
||||
.card-header.split .title {
|
||||
font-size: 0.875rem;
|
||||
}
|
||||
|
||||
.card-header.split .subtitle {
|
||||
font-size: 0.65rem;
|
||||
}
|
||||
|
||||
.selected-meta {
|
||||
display: none;
|
||||
}
|
||||
}
|
||||
</style>
|
||||
],
|
||||
},
|
||||
},
|
||||
{
|
||||
title: "Transparency Effects",
|
||||
description: "Glass effects on supported surfaces (may impact battery life)",
|
||||
id: 7,
|
||||
Component: Switch,
|
||||
props: {
|
||||
state: transparencyOn,
|
||||
onChange: (value: boolean) => (settingsState.transparencyEffects = value),
|
||||
},
|
||||
},
|
||||
];
|
||||
|
||||
if (!transparencyOn) return base;
|
||||
|
||||
return [
|
||||
...base,
|
||||
{
|
||||
title: "Blur Strength",
|
||||
description: `Glass blur on the sidebar (${blur}px)`,
|
||||
id: 8,
|
||||
Component: Slider,
|
||||
props: {
|
||||
state: blur,
|
||||
min: 0,
|
||||
max: 80,
|
||||
step: 1,
|
||||
onChange: (value: number) => (settingsState.sidebarBlur = value),
|
||||
},
|
||||
},
|
||||
];
|
||||
});
|
||||
|
||||
const visible = $derived(
|
||||
rows.some((row) => matchesSearch(searchQuery, row.title, row.description)),
|
||||
);
|
||||
</script>
|
||||
|
||||
{#if visible}
|
||||
<SettingsCard class="divide-y divide-zinc-200/60 dark:divide-zinc-700/40">
|
||||
{#each rows as row (row.id)}
|
||||
{#if matchesSearch(searchQuery, row.title, row.description)}
|
||||
<SettingRow {...row} {searchQuery} />
|
||||
{/if}
|
||||
{/each}
|
||||
</SettingsCard>
|
||||
{/if}
|
||||
@@ -2,6 +2,7 @@
|
||||
import { onDestroy, onMount } from "svelte";
|
||||
import SkeletonLoader from "@/interface/components/SkeletonLoader.svelte";
|
||||
import SignInToFavoriteModal from "@/interface/components/SignInToFavoriteModal.svelte";
|
||||
import Button from "@/interface/components/Button.svelte";
|
||||
import type { CommunityThemesState } from "@/interface/hooks/communityThemesState.svelte";
|
||||
import {
|
||||
formatCustomThemeStatus,
|
||||
@@ -13,7 +14,7 @@
|
||||
import type { CustomTheme } from "@/types/CustomThemes";
|
||||
import { ThemeManager } from "@/plugins/built-in/themes/theme-manager";
|
||||
import { themeUpdates } from "@/interface/hooks/ThemeUpdates";
|
||||
import { filterThemesByMode } from "@/interface/utils/themeListFilters";
|
||||
import { isLocalCustomTheme } from "@/interface/utils/themeListFilters";
|
||||
import { formatCustomThemeApiError } from "@/seqta/utils/customThemes/apiErrors";
|
||||
|
||||
let { communityState }: { communityState: CommunityThemesState } = $props();
|
||||
@@ -30,7 +31,7 @@
|
||||
localThemesLoading = true;
|
||||
try {
|
||||
const all = await themeManager.getAvailableThemes();
|
||||
localThemes = filterThemesByMode(all, "custom");
|
||||
localThemes = all.filter(isLocalCustomTheme);
|
||||
} finally {
|
||||
localThemesLoading = false;
|
||||
}
|
||||
@@ -76,13 +77,11 @@
|
||||
<p class="mt-3 text-zinc-600 dark:text-zinc-300">
|
||||
Submit themes for review and track pending, approved, or rejected submissions.
|
||||
</p>
|
||||
<button
|
||||
type="button"
|
||||
class="mt-6 rounded-lg bg-zinc-900 px-5 py-2.5 font-medium text-white dark:bg-zinc-100 dark:text-zinc-900"
|
||||
onclick={() => (communityState.showSignInOverlay = true)}
|
||||
>
|
||||
Sign in with BetterSEQTA Cloud
|
||||
</button>
|
||||
<Button
|
||||
class="mt-6"
|
||||
text="Sign in with BetterSEQTA Cloud"
|
||||
onClick={() => (communityState.showSignInOverlay = true)}
|
||||
/>
|
||||
</div>
|
||||
{:else}
|
||||
<section class="mb-8">
|
||||
@@ -101,7 +100,7 @@
|
||||
</div>
|
||||
{:else if localThemes.length === 0}
|
||||
<p class="mt-3 text-sm text-zinc-500 dark:text-zinc-400">
|
||||
No local custom themes yet. Use Create & submit above or build one in Custom themes settings.
|
||||
No local custom themes yet. Use Create & submit above or build one in My themes.
|
||||
</p>
|
||||
{:else}
|
||||
<ul class="mt-3 space-y-3">
|
||||
|
||||
@@ -0,0 +1,81 @@
|
||||
<script lang="ts">
|
||||
import ThemeGrid from "@/interface/components/store/ThemeGrid.svelte";
|
||||
import ThemeModal from "@/interface/components/store/ThemeModal.svelte";
|
||||
import SkeletonLoader from "@/interface/components/SkeletonLoader.svelte";
|
||||
import Select from "@/interface/components/Select.svelte";
|
||||
import type { CommunityThemesState } from "@/interface/hooks/communityThemesState.svelte";
|
||||
|
||||
let { communityState, searchTerm }: { communityState: CommunityThemesState; searchTerm: string } =
|
||||
$props();
|
||||
</script>
|
||||
|
||||
<div class="mb-6 flex flex-wrap items-end gap-4">
|
||||
<div class="min-w-[10rem]">
|
||||
<span class="mb-1 block text-sm font-medium">Status</span>
|
||||
<Select
|
||||
value={communityState.reviewStatusFilter}
|
||||
onChange={(v) => (communityState.reviewStatusFilter = v as typeof communityState.reviewStatusFilter)}
|
||||
options={[
|
||||
{ value: "pending", label: "Pending" },
|
||||
{ value: "approved", label: "Approved" },
|
||||
{ value: "rejected", label: "Rejected" },
|
||||
]}
|
||||
/>
|
||||
</div>
|
||||
<div class="min-w-[10rem]">
|
||||
<span class="mb-1 block text-sm font-medium">Source</span>
|
||||
<Select
|
||||
value={communityState.reviewSourceFilter}
|
||||
onChange={(v) =>
|
||||
(communityState.reviewSourceFilter = v as typeof communityState.reviewSourceFilter)}
|
||||
options={[
|
||||
{ value: "", label: "All sources" },
|
||||
{ value: "marketplace", label: "Official store" },
|
||||
{ value: "community", label: "Community" },
|
||||
]}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{#if communityState.reviewLoading}
|
||||
<div class="grid grid-cols-1 gap-4 py-6 sm:grid-cols-2 lg:grid-cols-3">
|
||||
{#each Array(6) as _, i (i)}
|
||||
<SkeletonLoader width="100%" height="200px" />
|
||||
{/each}
|
||||
</div>
|
||||
{:else if communityState.reviewError}
|
||||
<p class="py-16 text-center text-red-600 dark:text-red-400">{communityState.reviewError}</p>
|
||||
{:else if communityState.reviewThemes.length === 0}
|
||||
<p class="py-16 text-center text-zinc-500">No themes match this filter.</p>
|
||||
{:else}
|
||||
<ThemeGrid
|
||||
themes={communityState.reviewThemes}
|
||||
{searchTerm}
|
||||
setDisplayTheme={(t) => (communityState.displayTheme = t)}
|
||||
toggleFavorite={() => {}}
|
||||
isLoggedIn={false}
|
||||
installedThemeIds={communityState.currentThemes}
|
||||
variant="community"
|
||||
/>
|
||||
{#if communityState.displayTheme}
|
||||
<ThemeModal
|
||||
currentThemes={communityState.currentThemes}
|
||||
allThemes={communityState.reviewThemes}
|
||||
theme={communityState.displayTheme}
|
||||
displayTheme={communityState.displayTheme}
|
||||
setDisplayTheme={(t) => (communityState.displayTheme = t)}
|
||||
selectedThemeId={communityState.selectedThemeId}
|
||||
installedThemeColors={communityState.installedThemeColors}
|
||||
variant="community"
|
||||
adminPreviewMode
|
||||
onInstall={(id) => void communityState.previewAdminTheme(id, communityState.displayTheme!)}
|
||||
onRemove={(id) => void communityState.removeInstalledTheme(id)}
|
||||
onApply={(id) => void communityState.applyInstalledTheme(id)}
|
||||
/>
|
||||
{#if communityState.reviewPreviewError}
|
||||
<p class="fixed bottom-6 left-1/2 z-[100000] -translate-x-1/2 rounded-lg bg-red-600 px-4 py-2 text-sm text-white" role="alert">
|
||||
{communityState.reviewPreviewError}
|
||||
</p>
|
||||
{/if}
|
||||
{/if}
|
||||
{/if}
|
||||
@@ -13,6 +13,7 @@ import {
|
||||
getThemeApplyButtonStyles,
|
||||
resolveStoreVariantAccentColor,
|
||||
} from '@/interface/utils/themeListFilters'
|
||||
import { isRemoteThemeStoreDisabled } from '@/seqta/utils/remoteConfig/runtime'
|
||||
let {
|
||||
theme,
|
||||
currentThemes,
|
||||
@@ -29,6 +30,7 @@ onRequestSignIn,
|
||||
selectedThemeId = '',
|
||||
installedThemeColors = {},
|
||||
variant = 'official',
|
||||
adminPreviewMode = false,
|
||||
} = $props<{
|
||||
theme: Theme | null
|
||||
currentThemes: string[]
|
||||
@@ -46,8 +48,11 @@ onRequestSignIn?: () => void
|
||||
selectedThemeId?: string
|
||||
installedThemeColors?: Record<string, string>
|
||||
variant?: 'official' | 'community'
|
||||
adminPreviewMode?: boolean
|
||||
}>()
|
||||
const installActionLabel = $derived(adminPreviewMode ? 'Preview & apply' : 'Install')
|
||||
const isCommunity = $derived(variant === 'community')
|
||||
const themeStoreInstallLocked = $derived(isRemoteThemeStoreDisabled() && !adminPreviewMode)
|
||||
const showFavorites = $derived(!isCommunity)
|
||||
function variantApplyStyles(variantId: string) {
|
||||
if (!theme) {
|
||||
@@ -152,6 +157,7 @@ setDisplayTheme(relatedTheme ?? null)
|
||||
}, 100)
|
||||
}
|
||||
async function runInstall(id: string) {
|
||||
if (themeStoreInstallLocked) return
|
||||
installingId = id
|
||||
try {
|
||||
await onInstall(id)
|
||||
@@ -160,6 +166,7 @@ installingId = null
|
||||
}
|
||||
}
|
||||
async function runRemove(id: string) {
|
||||
if (themeStoreInstallLocked) return
|
||||
installingId = id
|
||||
try {
|
||||
await onRemove(id)
|
||||
@@ -254,12 +261,16 @@ By {theme.author}
|
||||
</p>
|
||||
{/if}
|
||||
<div class="flex gap-4 mb-4 text-sm text-zinc-600 dark:text-zinc-400">
|
||||
{#if !adminPreviewMode}
|
||||
<span class="flex items-center gap-1.5">
|
||||
<svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="1.5" stroke="currentColor" class="w-4 h-4">
|
||||
<path stroke-linecap="round" stroke-linejoin="round" d="M3 16.5v2.25A2.25 2.25 0 005.25 21h13.5A2.25 2.25 0 0021 18.75V16.5M16.5 12L12 16.5m0 0L7.5 12m4.5 4.5V3" />
|
||||
</svg>
|
||||
{modalDisplayDownloadCount.toLocaleString()} downloads
|
||||
</span>
|
||||
{:else}
|
||||
<span class="text-amber-700 dark:text-amber-300">Admin preview — does not count as a public download</span>
|
||||
{/if}
|
||||
{#if showFavorites}
|
||||
<span class="flex items-center gap-1.5">
|
||||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill={theme.is_favorited ? 'currentColor' : 'none'} stroke="currentColor" stroke-width="1.5" class="w-4 h-4">
|
||||
@@ -526,7 +537,7 @@ class="relative flex justify-center items-center px-4 py-2 min-w-[8rem] text-bla
|
||||
<path stroke="currentColor" fill="currentColor" class="origin-center animate-spin-fast" d="M2,12A11.2,11.2,0,0,1,13,1.05C12.67,1,12.34,1,12,1a11,11,0,0,0,0,22c.34,0,.67,0,1-.05C6,23,2,17.74,2,12Z"/>
|
||||
</svg>
|
||||
{/if}
|
||||
<span class="{installingId === theme.id ? 'opacity-0' : 'opacity-100'}">Install</span>
|
||||
<span class="{installingId === theme.id ? 'opacity-0' : 'opacity-100'}">{installActionLabel}</span>
|
||||
</button>
|
||||
{/if}
|
||||
{/if}
|
||||
|
||||
@@ -182,7 +182,7 @@
|
||||
|
||||
{#if !(videoBackgrounds.length === 0 && isEditMode)}
|
||||
<h2 class="py-2 text-lg font-bold">Background Videos</h2>
|
||||
<div class="flex flex-wrap gap-4">
|
||||
<div class="flex flex-wrap gap-4 mb-4">
|
||||
{#if !isEditMode}
|
||||
<BackgroundUploader onFileChange={handleFileChange} />
|
||||
{/if}
|
||||
|
||||
@@ -8,17 +8,21 @@
|
||||
import SignInToFavoriteModal from '@/interface/components/SignInToFavoriteModal.svelte'
|
||||
import ThemeBlobImage from '@/interface/components/themes/ThemeBlobImage.svelte'
|
||||
import ThemePlaceholderCover from '@/interface/components/themes/ThemePlaceholderCover.svelte'
|
||||
import { filterThemesByMode, isLocalCustomTheme, type ThemeListMode } from '@/interface/utils/themeListFilters'
|
||||
import { isLocalCustomTheme } from '@/interface/utils/themeListFilters'
|
||||
import { closeExtensionPopup } from '@/seqta/utils/Closers/closeExtensionPopup'
|
||||
import { formatCustomThemeApiError } from '@/seqta/utils/customThemes/apiErrors'
|
||||
import { getRemoteConfigSnapshot, resolveEffectiveRemoteTheme } from '@/seqta/utils/remoteConfig/runtime'
|
||||
|
||||
const themeManager = ThemeManager.getInstance();
|
||||
const remoteDirective = $derived(resolveEffectiveRemoteTheme(getRemoteConfigSnapshot()));
|
||||
const remoteThemeForced = $derived(
|
||||
remoteDirective?.mode === 'forced' && (remoteDirective.applicationMode ?? 'replace') === 'replace',
|
||||
);
|
||||
|
||||
let themes = $state<ThemeList | null>(null);
|
||||
let { isEditMode, showNavigation = true, listMode = 'all' } = $props<{
|
||||
let { isEditMode, showNavigation = true } = $props<{
|
||||
isEditMode: boolean;
|
||||
showNavigation?: boolean;
|
||||
listMode?: ThemeListMode;
|
||||
}>();
|
||||
let favoriteStatus = $state<Record<string, boolean>>({});
|
||||
let cloudLoggedIn = $state(cloudAuth.state.isLoggedIn);
|
||||
@@ -38,7 +42,7 @@
|
||||
});
|
||||
|
||||
const handleThemeClick = async (theme: CustomTheme, e: MouseEvent) => {
|
||||
if (isEditMode) return;
|
||||
if (isEditMode || remoteThemeForced) return;
|
||||
if (theme.id === themes?.selectedTheme) {
|
||||
themeManager.setTransitionPoint(e.clientX, e.clientY);
|
||||
await themeManager.disableTheme();
|
||||
@@ -112,11 +116,6 @@
|
||||
await launchPageThemeBuilder(themeId)
|
||||
}
|
||||
|
||||
const openCommunitySubmit = async () => {
|
||||
const { openCommunityThemeSubmit } = await import('@/seqta/utils/openCommunityThemeSubmit')
|
||||
await openCommunityThemeSubmit()
|
||||
}
|
||||
|
||||
const submitCustomTheme = async (theme: CustomTheme, e: MouseEvent) => {
|
||||
e.stopPropagation();
|
||||
submitError = null;
|
||||
@@ -135,11 +134,6 @@
|
||||
}
|
||||
}
|
||||
|
||||
const customThemeActionClass =
|
||||
'flex h-12 items-center justify-center gap-2 w-full rounded-xl transition bg-zinc-100 text-xl dark:bg-zinc-900 dark:text-white hover:bg-zinc-200 dark:hover:bg-zinc-800'
|
||||
|
||||
const customThemeActionCompactClass = customThemeActionClass
|
||||
|
||||
const handleToggleFavorite = async (theme: CustomTheme, e: MouseEvent) => {
|
||||
e.stopPropagation();
|
||||
if (!cloudLoggedIn) {
|
||||
@@ -166,11 +160,7 @@
|
||||
themeUpdates.removeListener(fetchThemes);
|
||||
})
|
||||
|
||||
const visibleThemes = $derived(
|
||||
themes ? filterThemesByMode(themes.themes, listMode) : [],
|
||||
);
|
||||
|
||||
const useTwoColumnLayout = $derived(listMode === 'downloaded' || listMode === 'custom');
|
||||
const useTwoColumnLayout = $derived(!showNavigation);
|
||||
</script>
|
||||
|
||||
<div
|
||||
@@ -178,9 +168,14 @@
|
||||
role="list"
|
||||
tabindex="-1"
|
||||
>
|
||||
<div class="{useTwoColumnLayout ? 'grid grid-cols-2 gap-3' : 'flex flex-col gap-2 px-2'}">
|
||||
{#if remoteThemeForced}
|
||||
<p class="mb-3 rounded-lg border border-amber-500/40 bg-amber-500/10 px-3 py-2 text-sm text-amber-900 dark:text-amber-100">
|
||||
Your school has applied a theme. Theme selection is locked until it is removed.
|
||||
</p>
|
||||
{/if}
|
||||
<div class="{useTwoColumnLayout ? 'grid grid-cols-2 gap-3' : 'flex flex-col gap-2 px-2'} {remoteThemeForced ? 'pointer-events-none opacity-50' : ''}">
|
||||
{#if themes}
|
||||
{#each visibleThemes as theme (theme.id)}
|
||||
{#each themes.themes as theme (theme.id)}
|
||||
<button
|
||||
class="relative group w-full aspect-theme flex justify-center items-center rounded-xl transition ring dark:ring-white ring-zinc-300 {theme.id === themes.selectedTheme ? 'dark:ring-2 ring-4' : 'ring-0'}"
|
||||
onclick={(e) => handleThemeClick(theme, e)}
|
||||
@@ -236,18 +231,16 @@
|
||||
>
|
||||
<span class="text-lg font-IconFamily"></span>
|
||||
</div>
|
||||
{#if listMode === 'custom'}
|
||||
<div
|
||||
class="flex h-8 w-8 place-items-center rounded-full bg-black/50 p-2 text-white {submittingThemeId === theme.id ? 'opacity-60' : ''}"
|
||||
onclick={(event) => void submitCustomTheme(theme, event)}
|
||||
onkeydown={(event) => { if (event.key === 'Enter' || event.key === ' ') void submitCustomTheme(theme, event as unknown as MouseEvent) }}
|
||||
role="button"
|
||||
tabindex="-1"
|
||||
title="Submit to community"
|
||||
>
|
||||
<span class="text-lg font-IconFamily"></span>
|
||||
</div>
|
||||
{/if}
|
||||
<div
|
||||
class="flex h-8 w-8 place-items-center rounded-full bg-black/50 p-2 text-white {submittingThemeId === theme.id ? 'opacity-60' : ''}"
|
||||
onclick={(event) => void submitCustomTheme(theme, event)}
|
||||
onkeydown={(event) => { if (event.key === 'Enter' || event.key === ' ') void submitCustomTheme(theme, event as unknown as MouseEvent) }}
|
||||
role="button"
|
||||
tabindex="-1"
|
||||
title="Submit to community"
|
||||
>
|
||||
<span class="text-lg font-IconFamily"></span>
|
||||
</div>
|
||||
{/if}
|
||||
</div>
|
||||
{/if}
|
||||
@@ -273,142 +266,39 @@
|
||||
{/each}
|
||||
{/if}
|
||||
|
||||
{#if themes && visibleThemes.length === 0}
|
||||
{#if themes && themes.themes.length === 0}
|
||||
<div class="flex min-h-56 flex-col items-center justify-center px-4 py-10 text-center {useTwoColumnLayout ? 'col-span-2' : ''}">
|
||||
{#if listMode === 'custom'}
|
||||
<h3 class="text-xl font-semibold text-zinc-900 dark:text-white" style="text-wrap: balance">
|
||||
No custom themes yet
|
||||
</h3>
|
||||
<p class="mt-2 max-w-md text-base text-zinc-500 dark:text-zinc-400" style="text-wrap: pretty">
|
||||
Create a theme with the builder, or follow our guide to get started.
|
||||
</p>
|
||||
<div class="mt-6 grid w-full max-w-md grid-cols-1 gap-2 sm:grid-cols-2">
|
||||
<button
|
||||
type="button"
|
||||
onclick={() => void openThemeCreator()}
|
||||
class="flex h-11 items-center justify-center gap-2 rounded-lg bg-zinc-200 px-4 font-medium text-zinc-900 transition-[background-color,color,transform] duration-150 hover:bg-zinc-300 active:scale-[0.96] focus:outline-none focus:ring-2 focus:ring-zinc-400 dark:bg-zinc-700 dark:text-white dark:hover:bg-zinc-600"
|
||||
>
|
||||
<span class="font-IconFamily text-lg" aria-hidden="true"></span>
|
||||
Create a theme
|
||||
</button>
|
||||
<a
|
||||
href="https://docs.betterseqta.org/theme-creation/"
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
class="flex h-11 items-center justify-center gap-2 rounded-lg bg-zinc-200 px-4 font-medium text-zinc-900 transition-[background-color,color,transform] duration-150 hover:bg-zinc-300 active:scale-[0.96] focus:outline-none focus:ring-2 focus:ring-zinc-400 dark:bg-zinc-700 dark:text-white dark:hover:bg-zinc-600"
|
||||
>
|
||||
<span class="font-IconFamily text-lg" aria-hidden="true">{'\uecb3'}</span>
|
||||
View docs
|
||||
</a>
|
||||
</div>
|
||||
{:else if listMode === 'downloaded'}
|
||||
<h3 class="text-xl font-semibold text-zinc-900 dark:text-white" style="text-wrap: balance">
|
||||
No downloaded themes
|
||||
</h3>
|
||||
<p class="mt-2 max-w-md text-base text-zinc-500 dark:text-zinc-400" style="text-wrap: pretty">
|
||||
Browse the theme store to find and install themes.
|
||||
</p>
|
||||
<div class="mt-6 grid w-full max-w-md grid-cols-1 gap-2">
|
||||
<button
|
||||
type="button"
|
||||
onclick={() => void openStorePage()}
|
||||
class="flex h-11 items-center justify-center gap-2 rounded-lg bg-zinc-200 px-4 font-medium text-zinc-900 transition-[background-color,color,transform] duration-150 hover:bg-zinc-300 active:scale-[0.96] focus:outline-none focus:ring-2 focus:ring-zinc-400 dark:bg-zinc-700 dark:text-white dark:hover:bg-zinc-600"
|
||||
>
|
||||
<span class="font-IconFamily text-lg" aria-hidden="true"></span>
|
||||
Browse the store
|
||||
</button>
|
||||
</div>
|
||||
{:else}
|
||||
<h3 class="text-xl font-semibold text-zinc-900 dark:text-white" style="text-wrap: balance">
|
||||
No themes installed
|
||||
</h3>
|
||||
<p class="mt-2 max-w-md text-base text-zinc-500 dark:text-zinc-400" style="text-wrap: pretty">
|
||||
Install a theme from the store or create one of your own.
|
||||
</p>
|
||||
<div class="mt-6 grid w-full max-w-md grid-cols-1 gap-2 sm:grid-cols-2">
|
||||
<button
|
||||
type="button"
|
||||
onclick={() => void openStorePage()}
|
||||
class="flex h-11 items-center justify-center gap-2 rounded-lg bg-zinc-200 px-4 font-medium text-zinc-900 transition-[background-color,color,transform] duration-150 hover:bg-zinc-300 active:scale-[0.96] focus:outline-none focus:ring-2 focus:ring-zinc-400 dark:bg-zinc-700 dark:text-white dark:hover:bg-zinc-600"
|
||||
>
|
||||
<span class="font-IconFamily text-lg" aria-hidden="true"></span>
|
||||
Install a theme
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
onclick={() => void openThemeCreator()}
|
||||
class="flex h-11 items-center justify-center gap-2 rounded-lg bg-zinc-200 px-4 font-medium text-zinc-900 transition-[background-color,color,transform] duration-150 hover:bg-zinc-300 active:scale-[0.96] focus:outline-none focus:ring-2 focus:ring-zinc-400 dark:bg-zinc-700 dark:text-white dark:hover:bg-zinc-600"
|
||||
>
|
||||
<span class="font-IconFamily text-lg" aria-hidden="true"></span>
|
||||
Create a theme
|
||||
</button>
|
||||
</div>
|
||||
{/if}
|
||||
<h3 class="text-xl font-semibold text-zinc-900 dark:text-white" style="text-wrap: balance">
|
||||
No themes installed
|
||||
</h3>
|
||||
<p class="mt-2 max-w-md text-base text-zinc-500 dark:text-zinc-400" style="text-wrap: pretty">
|
||||
Install a theme from the store or create one of your own.
|
||||
</p>
|
||||
</div>
|
||||
{/if}
|
||||
|
||||
{#if themes && (listMode === 'custom' || (showNavigation && visibleThemes.length > 0) || (listMode === 'downloaded' && visibleThemes.length > 0))}
|
||||
<div id="divider" class="w-full h-[1px] my-2 bg-zinc-100 dark:bg-zinc-600 {useTwoColumnLayout ? 'col-span-2' : ''}"></div>
|
||||
{#if submitError}
|
||||
<p class="whitespace-pre-line text-sm text-red-600 dark:text-red-400 {useTwoColumnLayout ? 'col-span-2' : ''}">{submitError}</p>
|
||||
{/if}
|
||||
|
||||
{#if listMode === 'custom' && submitError}
|
||||
<p class="col-span-2 whitespace-pre-line text-sm text-red-600 dark:text-red-400">{submitError}</p>
|
||||
{/if}
|
||||
{#if themes && showNavigation}
|
||||
<div id="divider" class="w-full h-[1px] my-2 bg-zinc-100 dark:bg-zinc-600"></div>
|
||||
|
||||
{#if listMode === 'custom'}
|
||||
<div class="grid grid-cols-2 gap-2 {useTwoColumnLayout ? 'col-span-2' : ''}">
|
||||
<button
|
||||
type="button"
|
||||
onclick={() => void openThemeCreator()}
|
||||
class={customThemeActionCompactClass}
|
||||
>
|
||||
<span class="text-2xl font-IconFamily" aria-hidden="true"></span>
|
||||
<span>Create theme</span>
|
||||
</button>
|
||||
<button
|
||||
onclick={() => void openStorePage()}
|
||||
class="flex justify-center items-center w-full rounded-xl transition aspect-theme bg-zinc-100 dark:bg-zinc-900 dark:text-white"
|
||||
>
|
||||
<span class="text-xl font-IconFamily"></span>
|
||||
<span class="ml-2">Theme Store</span>
|
||||
</button>
|
||||
|
||||
<a
|
||||
href="https://docs.betterseqta.org/theme-creation/"
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
class={customThemeActionCompactClass}
|
||||
>
|
||||
<span class="text-2xl font-IconFamily" aria-hidden="true">{'\uecb3'}</span>
|
||||
<span>View docs</span>
|
||||
</a>
|
||||
|
||||
<button
|
||||
type="button"
|
||||
onclick={() => void openCommunitySubmit()}
|
||||
class="{customThemeActionClass} col-span-2"
|
||||
>
|
||||
<span class="text-2xl font-IconFamily" aria-hidden="true"></span>
|
||||
<span>Create & submit</span>
|
||||
</button>
|
||||
</div>
|
||||
{:else if listMode === 'downloaded'}
|
||||
<button
|
||||
onclick={() => void openStorePage()}
|
||||
class="flex justify-center items-center w-full rounded-xl transition aspect-theme bg-zinc-100 dark:bg-zinc-900 dark:text-white {useTwoColumnLayout ? 'col-span-2' : ''}"
|
||||
>
|
||||
<span class="text-xl font-IconFamily"></span>
|
||||
<span class="ml-2">Theme Store</span>
|
||||
</button>
|
||||
{:else}
|
||||
<button
|
||||
onclick={() => void openStorePage()}
|
||||
class="flex justify-center items-center w-full rounded-xl transition aspect-theme bg-zinc-100 dark:bg-zinc-900 dark:text-white"
|
||||
>
|
||||
<span class="text-xl font-IconFamily"></span>
|
||||
<span class="ml-2">Theme Store</span>
|
||||
</button>
|
||||
|
||||
<button
|
||||
onclick={() => void openThemeCreator()}
|
||||
class="flex justify-center items-center w-full rounded-xl transition aspect-theme bg-zinc-100 dark:bg-zinc-900 dark:text-white"
|
||||
>
|
||||
<span class="text-xl font-IconFamily"></span>
|
||||
<span class="ml-2">Create your own</span>
|
||||
</button>
|
||||
{/if}
|
||||
<button
|
||||
onclick={() => void openThemeCreator()}
|
||||
class="flex justify-center items-center w-full rounded-xl transition aspect-theme bg-zinc-100 dark:bg-zinc-900 dark:text-white"
|
||||
>
|
||||
<span class="text-xl font-IconFamily"></span>
|
||||
<span class="ml-2">Create your own</span>
|
||||
</button>
|
||||
{/if}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -1,9 +1,10 @@
|
||||
import browser from "webextension-polyfill";
|
||||
import type { Theme } from "@/interface/types/Theme";
|
||||
import { getCommunityInstalledThemeIds } from "@/interface/utils/themeListFilters";
|
||||
import { getCommunityInstalledThemeIds, getStoreInstalledThemeIds } from "@/interface/utils/themeListFilters";
|
||||
import { normalizeStoreTheme } from "@/interface/utils/themeStoreFlavours";
|
||||
import { themeUpdates } from "@/interface/hooks/ThemeUpdates";
|
||||
import { ThemeManager } from "@/plugins/built-in/themes/theme-manager";
|
||||
import { cloudAuth } from "@/seqta/utils/CloudAuth";
|
||||
import { cloudAuth, isCloudAdmin } from "@/seqta/utils/CloudAuth";
|
||||
import {
|
||||
deleteCustomTheme,
|
||||
fetchCommunityThemes,
|
||||
@@ -23,16 +24,24 @@ import {
|
||||
consumePendingCommunitySubmitThemeId,
|
||||
OPEN_COMMUNITY_SUBMIT_EVENT,
|
||||
} from "@/seqta/utils/openCommunityThemeSubmit";
|
||||
export type CommunityThemesTab = "browse" | "mine";
|
||||
export type CommunityThemesTab = "browse" | "mine" | "review";
|
||||
|
||||
export class CommunityThemesState {
|
||||
innerTab = $state<CommunityThemesTab>("browse");
|
||||
cloudLoggedIn = $state(cloudAuth.state.isLoggedIn);
|
||||
isAdmin = $state(isCloudAdmin(cloudAuth.state.user));
|
||||
|
||||
browseThemes = $state<Theme[]>([]);
|
||||
browseLoading = $state(true);
|
||||
browseError = $state<string | null>(null);
|
||||
|
||||
reviewThemes = $state<Theme[]>([]);
|
||||
reviewLoading = $state(false);
|
||||
reviewError = $state<string | null>(null);
|
||||
reviewStatusFilter = $state<"pending" | "approved" | "rejected">("pending");
|
||||
reviewSourceFilter = $state<"" | "marketplace" | "community">("");
|
||||
reviewPreviewError = $state<string | null>(null);
|
||||
|
||||
myThemes = $state<CustomThemeOwner[]>([]);
|
||||
myLoading = $state(false);
|
||||
myError = $state<string | null>(null);
|
||||
@@ -62,7 +71,10 @@ export class CommunityThemesState {
|
||||
|
||||
async refreshInstalledThemes() {
|
||||
const themes = await this.themeManager.getAvailableThemes();
|
||||
this.currentThemes = getCommunityInstalledThemeIds(themes);
|
||||
this.currentThemes = [
|
||||
...getCommunityInstalledThemeIds(themes),
|
||||
...getStoreInstalledThemeIds(themes),
|
||||
];
|
||||
this.selectedThemeId = this.themeManager.getSelectedThemeId() || "";
|
||||
this.installedThemeColors = Object.fromEntries(
|
||||
themes
|
||||
@@ -71,6 +83,90 @@ export class CommunityThemesState {
|
||||
);
|
||||
}
|
||||
|
||||
async syncAdminAccess() {
|
||||
if (!this.cloudLoggedIn) {
|
||||
this.isAdmin = false;
|
||||
return;
|
||||
}
|
||||
if (isCloudAdmin(cloudAuth.state.user)) {
|
||||
this.isAdmin = true;
|
||||
return;
|
||||
}
|
||||
try {
|
||||
const res = (await browser.runtime.sendMessage({ type: "fetchBsplusAdminMe" })) as {
|
||||
success?: boolean;
|
||||
data?: { admin_level?: number; id?: string; username?: string };
|
||||
httpStatus?: number;
|
||||
};
|
||||
if (res?.success && res.data && cloudAuth.state.user) {
|
||||
await cloudAuth.setUser({
|
||||
...cloudAuth.state.user,
|
||||
admin_level: res.data.admin_level ?? cloudAuth.state.user.admin_level,
|
||||
username: res.data.username ?? cloudAuth.state.user.username,
|
||||
});
|
||||
}
|
||||
} catch {
|
||||
// ignore — tab may need reload after extension update
|
||||
}
|
||||
this.isAdmin = isCloudAdmin(cloudAuth.state.user);
|
||||
}
|
||||
|
||||
async loadReviewThemes() {
|
||||
if (!this.isAdmin) return;
|
||||
this.reviewLoading = true;
|
||||
this.reviewError = null;
|
||||
try {
|
||||
const q = this.getSearchTerm().trim();
|
||||
const res = (await browser.runtime.sendMessage({
|
||||
type: "fetchBsplusAdminThemes",
|
||||
status: this.reviewStatusFilter,
|
||||
source: this.reviewSourceFilter || undefined,
|
||||
search: q.length > 0 ? q : undefined,
|
||||
limit: 50,
|
||||
})) as { success?: boolean; data?: { themes?: unknown[] }; error?: unknown };
|
||||
if (!res?.success || !Array.isArray(res.data?.themes)) {
|
||||
throw new Error(
|
||||
typeof res?.error === "string" ? res.error : "Could not load admin themes",
|
||||
);
|
||||
}
|
||||
this.reviewThemes = res.data.themes
|
||||
.map((row) => {
|
||||
const theme = normalizeStoreTheme(row as Record<string, unknown>);
|
||||
const source = (row as Record<string, unknown>).source;
|
||||
theme.adminSource = source === "community" ? "community" : "marketplace";
|
||||
const preview = (row as Record<string, unknown>).preview as
|
||||
| { thumbnail?: string }
|
||||
| undefined;
|
||||
if (preview?.thumbnail) theme.coverImage = preview.thumbnail;
|
||||
return theme;
|
||||
})
|
||||
.filter((t) => t.id.length > 0);
|
||||
} catch (err) {
|
||||
this.reviewError = err instanceof Error ? err.message : "Could not load admin themes";
|
||||
} finally {
|
||||
this.reviewLoading = false;
|
||||
}
|
||||
}
|
||||
|
||||
async previewAdminTheme(themeId: string, meta: Theme) {
|
||||
const source = meta.adminSource ?? "community";
|
||||
this.reviewPreviewError = null;
|
||||
try {
|
||||
const installedId = await this.themeManager.previewAdminTheme({
|
||||
id: themeId,
|
||||
source,
|
||||
updated_at: meta.updated_at,
|
||||
});
|
||||
await this.themeManager.setTheme(installedId);
|
||||
themeUpdates.triggerUpdate();
|
||||
await this.refreshInstalledThemes();
|
||||
this.selectedThemeId = installedId;
|
||||
void browser.runtime.sendMessage({ type: "cloudSettingsRequestDebouncedUpload" }).catch(() => {});
|
||||
} catch (err) {
|
||||
this.reviewPreviewError = err instanceof Error ? err.message : "Preview failed";
|
||||
}
|
||||
}
|
||||
|
||||
async loadBrowseThemes() {
|
||||
this.browseLoading = true;
|
||||
this.browseError = null;
|
||||
@@ -141,7 +237,6 @@ export class CommunityThemesState {
|
||||
const row = this.browseThemes.find((x) => x.id === themeId) ?? meta;
|
||||
const installedId = await this.themeManager.downloadCommunityTheme({
|
||||
id: themeId,
|
||||
theme_json_url: row.theme_json_url,
|
||||
updated_at: row.updated_at,
|
||||
});
|
||||
await this.themeManager.setTheme(installedId);
|
||||
@@ -219,10 +314,16 @@ export class CommunityThemesState {
|
||||
$effect(() => {
|
||||
const unsub = cloudAuth.subscribe((s) => {
|
||||
this.cloudLoggedIn = s.isLoggedIn;
|
||||
this.isAdmin = isCloudAdmin(s.user);
|
||||
});
|
||||
return unsub;
|
||||
});
|
||||
|
||||
$effect(() => {
|
||||
if (this.cloudLoggedIn) void this.syncAdminAccess();
|
||||
else this.isAdmin = false;
|
||||
});
|
||||
|
||||
$effect(() => {
|
||||
if (this.innerTab === "browse") void this.loadBrowseThemes();
|
||||
});
|
||||
@@ -240,12 +341,20 @@ export class CommunityThemesState {
|
||||
this.statusFilter;
|
||||
if (this.innerTab === "mine" && this.cloudLoggedIn) void this.loadMyThemes();
|
||||
});
|
||||
|
||||
$effect(() => {
|
||||
this.reviewStatusFilter;
|
||||
this.reviewSourceFilter;
|
||||
this.getSearchTerm();
|
||||
if (this.innerTab === "review" && this.isAdmin) void this.loadReviewThemes();
|
||||
});
|
||||
}
|
||||
|
||||
mount() {
|
||||
const onThemesUpdated = () => void this.refreshInstalledThemes();
|
||||
themeUpdates.addListener(onThemesUpdated);
|
||||
void this.refreshInstalledThemes();
|
||||
void this.syncAdminAccess();
|
||||
|
||||
const openPageBuilderForSubmit = () => {
|
||||
const themeId = consumePendingCommunitySubmitThemeId() ?? undefined;
|
||||
|
||||
@@ -1,7 +1,9 @@
|
||||
<script lang="ts">
|
||||
import { onMount } from "svelte";
|
||||
import Button from "@/interface/components/Button.svelte";
|
||||
import BrowsePanel from "@/interface/components/communityThemes/BrowsePanel.svelte";
|
||||
import MyThemesPanel from "@/interface/components/communityThemes/MyThemesPanel.svelte";
|
||||
import ReviewPanel from "@/interface/components/communityThemes/ReviewPanel.svelte";
|
||||
import OwnerThemeDetailModal from "@/interface/components/communityThemes/OwnerThemeDetailModal.svelte";
|
||||
import { createCommunityThemesState } from "@/interface/hooks/communityThemesState.svelte";
|
||||
|
||||
@@ -35,17 +37,26 @@
|
||||
>
|
||||
My themes
|
||||
</button>
|
||||
{#if communityState.isAdmin}
|
||||
<button
|
||||
type="button"
|
||||
class="rounded-lg px-4 py-2 text-sm font-medium transition-colors {communityState.innerTab === 'review'
|
||||
? 'bg-white text-zinc-900 shadow dark:bg-zinc-700 dark:text-white'
|
||||
: 'text-zinc-600 hover:text-zinc-900 dark:text-zinc-400 dark:hover:text-white'}"
|
||||
onclick={() => (communityState.innerTab = "review")}
|
||||
>
|
||||
Review queue
|
||||
</button>
|
||||
{/if}
|
||||
</div>
|
||||
<button
|
||||
type="button"
|
||||
class="rounded-lg bg-zinc-900 px-4 py-2 text-sm font-medium text-white transition hover:bg-zinc-700 dark:bg-zinc-100 dark:text-zinc-900 dark:hover:bg-white"
|
||||
onclick={() =>
|
||||
<Button
|
||||
variant="primary"
|
||||
text="Create & submit"
|
||||
onClick={() =>
|
||||
void import("@/seqta/utils/launchPageThemeBuilder").then(({ launchPageThemeBuilder }) =>
|
||||
launchPageThemeBuilder(),
|
||||
)}
|
||||
>
|
||||
Create & submit
|
||||
</button>
|
||||
/>
|
||||
</div>
|
||||
<p class="mt-2 text-sm text-zinc-500 dark:text-zinc-400">
|
||||
Community themes are user-submitted and moderated separately from the official theme store.
|
||||
@@ -55,8 +66,10 @@
|
||||
<main class="min-h-0 flex-1 overflow-y-auto bg-zinc-50/80 px-6 py-6 dark:bg-zinc-900/40 md:px-8 lg:px-10">
|
||||
{#if communityState.innerTab === "browse"}
|
||||
<BrowsePanel {communityState} {searchTerm} />
|
||||
{:else}
|
||||
{:else if communityState.innerTab === "mine"}
|
||||
<MyThemesPanel {communityState} />
|
||||
{:else if communityState.innerTab === "review"}
|
||||
<ReviewPanel {communityState} {searchTerm} />
|
||||
{/if}
|
||||
</main>
|
||||
|
||||
|
||||
@@ -21,6 +21,8 @@
|
||||
import { settingsPopup } from "@/seqta/utils/settingsPopup";
|
||||
import { armDevModeUnlock } from "@/seqta/utils/devModeUnlock";
|
||||
import { consumeOpenFeedbackRequest } from "@/seqta/utils/feedback/client";
|
||||
import RemoteConfigStatusStrip from "../components/RemoteConfigStatusStrip.svelte";
|
||||
import { isRemoteSettingsSectionVisible } from "@/seqta/utils/remoteConfig/runtime";
|
||||
import {
|
||||
consumeSettingsDestination,
|
||||
SETTINGS_NAVIGATION_EVENT,
|
||||
@@ -35,7 +37,7 @@
|
||||
} from "@/utils/githubReleaseUpdate";
|
||||
type PageId = "settings" | "themes" | "backgrounds";
|
||||
type StoreTab = "themes" | "backgrounds";
|
||||
type ThemeView = "theme-settings" | "theme-store" | "community-themes" | "create-theme";
|
||||
type ThemeView = "theme-settings" | "theme-store" | "community-themes";
|
||||
type BackgroundView = "background-settings" | "background-store";
|
||||
|
||||
const loadSettingsBody = () => import("./settings/SettingsBody.svelte");
|
||||
@@ -90,7 +92,7 @@
|
||||
{ id: "account", label: "My Account" },
|
||||
{ id: "general", label: "General" },
|
||||
{ id: "appearance", label: "Appearance" },
|
||||
];
|
||||
].filter((item) => isRemoteSettingsSectionVisible(item.id));
|
||||
|
||||
$effect(() => {
|
||||
if (!$settingsState.devMode && activeSection === "advanced") activeSection = "general";
|
||||
@@ -102,7 +104,7 @@
|
||||
{ id: "features", label: "Features" },
|
||||
...($settingsState.devMode ? [{ id: "advanced", label: "Advanced" }] : []),
|
||||
{ id: "shortcuts", label: "Shortcuts" },
|
||||
]);
|
||||
].filter((item) => isRemoteSettingsSectionVisible(item.id)));
|
||||
|
||||
const settingsNavGroups = $derived([
|
||||
{ label: "User Settings", items: userNav },
|
||||
@@ -115,8 +117,7 @@
|
||||
items: [
|
||||
{ id: "theme-store", label: "Theme store" },
|
||||
{ id: "community-themes", label: "Community themes" },
|
||||
{ id: "theme-settings", label: "Downloaded themes" },
|
||||
{ id: "create-theme", label: "Custom themes" },
|
||||
{ id: "theme-settings", label: "My themes" },
|
||||
],
|
||||
},
|
||||
];
|
||||
@@ -165,8 +166,7 @@
|
||||
const sectionTitle = $derived.by(() => {
|
||||
if (activePage === "settings" && debouncedSettingsSearch.trim()) return "Search results";
|
||||
if (activePage === "themes") {
|
||||
if (activeThemeView === "theme-settings") return "Downloaded themes";
|
||||
if (activeThemeView === "create-theme") return "Custom themes";
|
||||
if (activeThemeView === "theme-settings") return "My themes";
|
||||
if (activeThemeView === "community-themes") return "Community themes";
|
||||
if (activeThemeView === "theme-store") return "Theme store";
|
||||
return "Themes";
|
||||
@@ -175,12 +175,6 @@
|
||||
return [...userNav, ...appNav].find((item) => item.id === activeSection)?.label ?? "Settings";
|
||||
});
|
||||
|
||||
const activeThemeListMode = $derived.by(() => {
|
||||
if (activeThemeView === "create-theme") return "custom" as const;
|
||||
if (activeThemeView === "theme-settings") return "downloaded" as const;
|
||||
return "all" as const;
|
||||
});
|
||||
|
||||
const isStoreView = $derived(
|
||||
(activePage === "themes" &&
|
||||
(activeThemeView === "theme-store" || activeThemeView === "community-themes")) ||
|
||||
@@ -464,9 +458,7 @@
|
||||
? "theme-store"
|
||||
: destination.view === "community"
|
||||
? "community-themes"
|
||||
: destination.view === "custom"
|
||||
? "create-theme"
|
||||
: "theme-settings";
|
||||
: "theme-settings";
|
||||
} else if (destination.page === "backgrounds" && destination.view) {
|
||||
activeBackgroundView = destination.view === "store" ? "background-store" : "background-settings";
|
||||
}
|
||||
@@ -561,6 +553,8 @@
|
||||
onToggleSize={standalone ? undefined : toggleExpanded}
|
||||
/>
|
||||
|
||||
<RemoteConfigStatusStrip />
|
||||
|
||||
<!-- Body: left nav + content -->
|
||||
<div class="flex flex-1 min-h-0 overflow-hidden">
|
||||
<nav
|
||||
@@ -717,8 +711,8 @@
|
||||
{:else if activePage === "themes"}
|
||||
<LazyPanel
|
||||
loader={loadThemeSettings}
|
||||
remountKey={`theme-settings-${activeThemeListMode}`}
|
||||
props={{ section: "themes", listMode: activeThemeListMode }}
|
||||
remountKey="theme-settings"
|
||||
props={{ section: "themes" }}
|
||||
/>
|
||||
{:else}
|
||||
<LazyPanel
|
||||
@@ -740,6 +734,7 @@
|
||||
<div
|
||||
class="flex h-full min-h-0 flex-col gap-2 overflow-hidden bg-white dark:bg-zinc-800 dark:text-white"
|
||||
>
|
||||
<RemoteConfigStatusStrip />
|
||||
<div
|
||||
class="grid shrink-0 items-center border-b border-zinc-200/40 dark:border-zinc-700/40 {standalone ? 'grid-cols-1' : 'grid-cols-[minmax(0,1fr)_44px] gap-2 px-2'}"
|
||||
>
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
<script lang="ts">
|
||||
import SettingsCard from "./SettingsCard.svelte";
|
||||
import Switch from "@/interface/components/Switch.svelte";
|
||||
import Button from "@/interface/components/Button.svelte";
|
||||
import Slider from "@/interface/components/Slider.svelte";
|
||||
@@ -69,121 +70,116 @@
|
||||
|
||||
{#each visiblePlugins as plugin (plugin.pluginId)}
|
||||
{@const perfPaused = pluginPerfPaused(plugin.pluginId)}
|
||||
<div class="border-none">
|
||||
<div
|
||||
class="p-1 my-1 from-white to-zinc-100 bg-gradient-to-br rounded-xl border shadow-sm border-zinc-200/50 dark:border-zinc-700/40 dark:to-zinc-900/50 dark:from-zinc-900/40 {!(plugin as PluginSettingsEntry & { disableToggle?: boolean }).disableToggle && Object.keys(plugin.settings).length === 0 ? 'hidden' : ''} {perfPaused ? 'opacity-60' : ''}"
|
||||
>
|
||||
{#if perfPaused}
|
||||
<div
|
||||
class="flex justify-between items-center px-5 py-3 border-b border-amber-200/60 dark:border-amber-900/40 bg-amber-50/80 dark:bg-amber-950/20"
|
||||
>
|
||||
<p class="text-sm text-amber-800 dark:text-amber-200">
|
||||
Paused by Performance Mode — enable anyway
|
||||
</p>
|
||||
<SettingsCard class="{!(plugin as PluginSettingsEntry & { disableToggle?: boolean }).disableToggle && Object.keys(plugin.settings).length === 0 ? 'hidden' : ''} {perfPaused ? 'opacity-60' : ''}">
|
||||
{#if perfPaused}
|
||||
<div
|
||||
class="flex justify-between items-center px-5 py-3 border-b border-amber-200/60 dark:border-amber-900/40 bg-amber-50/80 dark:bg-amber-950/20"
|
||||
>
|
||||
<p class="text-sm text-amber-800 dark:text-amber-200">
|
||||
Paused by Performance Mode — enable anyway
|
||||
</p>
|
||||
<Switch
|
||||
state={$settingsState.performanceModePluginOverrides?.[plugin.pluginId] === true}
|
||||
onChange={(forceOn: boolean) =>
|
||||
setPerformanceModePluginOverride(plugin.pluginId, forceOn)}
|
||||
/>
|
||||
</div>
|
||||
{/if}
|
||||
|
||||
{#if plugin.disableToggle}
|
||||
<div class="flex justify-between items-center px-4 py-3 {perfPaused ? 'pointer-events-none' : ''}">
|
||||
<div class="pr-4">
|
||||
<h2 class="flex gap-2 items-center text-sm font-bold">
|
||||
Enable {plugin.name}
|
||||
{#if plugin.beta}
|
||||
<span
|
||||
class="px-2 py-0.5 text-xs font-medium text-orange-800 bg-orange-100 rounded-full border border-orange-300/30 dark:bg-orange-900/30 dark:text-orange-300 dark:border-orange-900/30"
|
||||
>
|
||||
Beta
|
||||
</span>
|
||||
{/if}
|
||||
</h2>
|
||||
<p class="text-xs text-zinc-600 dark:text-zinc-300">{plugin.description}</p>
|
||||
</div>
|
||||
<div>
|
||||
<Switch
|
||||
state={$settingsState.performanceModePluginOverrides?.[plugin.pluginId] === true}
|
||||
onChange={(forceOn: boolean) =>
|
||||
setPerformanceModePluginOverride(plugin.pluginId, forceOn)}
|
||||
state={(pluginSettingsStore.values[plugin.pluginId]?.enabled as boolean | undefined) ?? true}
|
||||
onChange={async (value) => {
|
||||
if (plugin.pluginId === "assessments-average" && value === true) {
|
||||
showDisclaimer(
|
||||
async () => {
|
||||
await pluginSettingsStore.update(plugin.pluginId, "enabled", true);
|
||||
},
|
||||
() => {},
|
||||
"Assessment Averages Disclaimer",
|
||||
"This feature calculates a simple average of your assessment grades. It does not take into account:\n• Assessment weightings\n• Different grading scales\n• Other factors used in official reports\n\nThe displayed average may be inaccurate compared to your actual marks found in reports.\n\nDo you want to enable this feature?",
|
||||
);
|
||||
return;
|
||||
}
|
||||
await pluginSettingsStore.update(plugin.pluginId, "enabled", value);
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
{/if}
|
||||
</div>
|
||||
{/if}
|
||||
|
||||
{#if plugin.disableToggle}
|
||||
<div class="flex justify-between items-center px-4 py-3 {perfPaused ? 'pointer-events-none' : ''}">
|
||||
<div class="pr-4">
|
||||
<h2 class="flex gap-2 items-center text-sm font-bold">
|
||||
Enable {plugin.name}
|
||||
{#if plugin.beta}
|
||||
<span
|
||||
class="px-2 py-0.5 text-xs font-medium text-orange-800 bg-orange-100 rounded-full border border-orange-300/30 dark:bg-orange-900/30 dark:text-orange-300 dark:border-orange-900/30"
|
||||
>
|
||||
Beta
|
||||
</span>
|
||||
{/if}
|
||||
</h2>
|
||||
<p class="text-xs text-zinc-600 dark:text-zinc-300">{plugin.description}</p>
|
||||
</div>
|
||||
<div>
|
||||
<Switch
|
||||
state={(pluginSettingsStore.values[plugin.pluginId]?.enabled as boolean | undefined) ?? true}
|
||||
onChange={async (value) => {
|
||||
if (plugin.pluginId === "assessments-average" && value === true) {
|
||||
showDisclaimer(
|
||||
async () => {
|
||||
await pluginSettingsStore.update(plugin.pluginId, "enabled", true);
|
||||
},
|
||||
() => {},
|
||||
"Assessment Averages Disclaimer",
|
||||
"This feature calculates a simple average of your assessment grades. It does not take into account:\n• Assessment weightings\n• Different grading scales\n• Other factors used in official reports\n\nThe displayed average may be inaccurate compared to your actual marks found in reports.\n\nDo you want to enable this feature?",
|
||||
);
|
||||
return;
|
||||
}
|
||||
await pluginSettingsStore.update(plugin.pluginId, "enabled", value);
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
{/if}
|
||||
|
||||
{#if !perfPaused && (!plugin.disableToggle || ((pluginSettingsStore.values[plugin.pluginId]?.enabled as boolean | undefined) ?? true))}
|
||||
{#each Object.entries(plugin.settings) as [key, setting] (key)}
|
||||
{#if key !== "enabled" && !(key === "useCloudPfp" && !cloudState.isLoggedIn)}
|
||||
<div class="flex justify-between items-center px-4 py-3">
|
||||
<div class="pr-4">
|
||||
<h2 class="text-sm font-bold">{setting.title || key}</h2>
|
||||
<p class="text-xs text-zinc-600 dark:text-zinc-300">{setting.description || ""}</p>
|
||||
</div>
|
||||
<div>
|
||||
{#if setting.type === "boolean"}
|
||||
<Switch
|
||||
state={(pluginSettingsStore.values[plugin.pluginId]?.[key] as boolean | undefined) ?? setting.default}
|
||||
onChange={(value) => pluginSettingsStore.update(plugin.pluginId, key, value)}
|
||||
/>
|
||||
{:else if setting.type === "number"}
|
||||
<div class="w-28 shrink-0">
|
||||
<Slider
|
||||
state={(pluginSettingsStore.values[plugin.pluginId]?.[key] as number | undefined) ?? setting.default}
|
||||
onChange={(value) => pluginSettingsStore.update(plugin.pluginId, key, value)}
|
||||
min={setting.min}
|
||||
max={setting.max}
|
||||
step={setting.step}
|
||||
/>
|
||||
</div>
|
||||
{:else if setting.type === "string"}
|
||||
<input
|
||||
type="text"
|
||||
class="px-2 py-1 text-sm rounded-md dark:bg-[#38373D]/50 bg-[#DDDDDD] dark:text-white border-none"
|
||||
value={(pluginSettingsStore.values[plugin.pluginId]?.[key] as string | undefined) ?? setting.default}
|
||||
oninput={(e) =>
|
||||
pluginSettingsStore.update(plugin.pluginId, key, e.currentTarget.value)}
|
||||
/>
|
||||
{:else if setting.type === "select"}
|
||||
<Select
|
||||
value={(pluginSettingsStore.values[plugin.pluginId]?.[key] as string | undefined) ?? setting.default}
|
||||
onChange={(value) => pluginSettingsStore.update(plugin.pluginId, key, value)}
|
||||
options={(setting.options as string[]).map((opt) => ({
|
||||
value: opt,
|
||||
label: opt.charAt(0).toUpperCase() + opt.slice(1),
|
||||
}))}
|
||||
/>
|
||||
{:else if setting.type === "button"}
|
||||
<Button onClick={() => setting.trigger?.()} text={setting.title} />
|
||||
{:else if setting.type === "hotkey"}
|
||||
<HotkeyInput
|
||||
value={(pluginSettingsStore.values[plugin.pluginId]?.[key] as string | undefined) ?? setting.default}
|
||||
onChange={(value) => pluginSettingsStore.update(plugin.pluginId, key, value)}
|
||||
/>
|
||||
{:else if setting.type === "component" && setting.component}
|
||||
{@const Component = setting.component as import("svelte").Component}
|
||||
<Component />
|
||||
{/if}
|
||||
</div>
|
||||
{#if !perfPaused && (!plugin.disableToggle || ((pluginSettingsStore.values[plugin.pluginId]?.enabled as boolean | undefined) ?? true))}
|
||||
{#each Object.entries(plugin.settings) as [key, setting] (key)}
|
||||
{#if key !== "enabled" && !(key === "useCloudPfp" && !cloudState.isLoggedIn)}
|
||||
<div class="flex justify-between items-center px-4 py-3">
|
||||
<div class="pr-4">
|
||||
<h2 class="text-sm font-bold">{setting.title || key}</h2>
|
||||
<p class="text-xs text-zinc-600 dark:text-zinc-300">{setting.description || ""}</p>
|
||||
</div>
|
||||
{/if}
|
||||
{/each}
|
||||
{/if}
|
||||
</div>
|
||||
|
||||
<div>
|
||||
{#if setting.type === "boolean"}
|
||||
<Switch
|
||||
state={(pluginSettingsStore.values[plugin.pluginId]?.[key] as boolean | undefined) ?? setting.default}
|
||||
onChange={(value) => pluginSettingsStore.update(plugin.pluginId, key, value)}
|
||||
/>
|
||||
{:else if setting.type === "number"}
|
||||
<div class="w-28 shrink-0">
|
||||
<Slider
|
||||
state={(pluginSettingsStore.values[plugin.pluginId]?.[key] as number | undefined) ?? setting.default}
|
||||
onChange={(value) => pluginSettingsStore.update(plugin.pluginId, key, value)}
|
||||
min={setting.min}
|
||||
max={setting.max}
|
||||
step={setting.step}
|
||||
/>
|
||||
</div>
|
||||
{:else if setting.type === "string"}
|
||||
<input
|
||||
type="text"
|
||||
class="px-2 py-1 text-sm rounded-md dark:bg-[#38373D]/50 bg-[#DDDDDD] dark:text-white border-none"
|
||||
value={(pluginSettingsStore.values[plugin.pluginId]?.[key] as string | undefined) ?? setting.default}
|
||||
oninput={(e) =>
|
||||
pluginSettingsStore.update(plugin.pluginId, key, e.currentTarget.value)}
|
||||
/>
|
||||
{:else if setting.type === "select"}
|
||||
<Select
|
||||
value={(pluginSettingsStore.values[plugin.pluginId]?.[key] as string | undefined) ?? setting.default}
|
||||
onChange={(value) => pluginSettingsStore.update(plugin.pluginId, key, value)}
|
||||
options={(setting.options as string[]).map((opt) => ({
|
||||
value: opt,
|
||||
label: opt.charAt(0).toUpperCase() + opt.slice(1),
|
||||
}))}
|
||||
/>
|
||||
{:else if setting.type === "button"}
|
||||
<Button onClick={() => setting.trigger?.()} text={setting.title} />
|
||||
{:else if setting.type === "hotkey"}
|
||||
<HotkeyInput
|
||||
value={(pluginSettingsStore.values[plugin.pluginId]?.[key] as string | undefined) ?? setting.default}
|
||||
onChange={(value) => pluginSettingsStore.update(plugin.pluginId, key, value)}
|
||||
/>
|
||||
{:else if setting.type === "component" && setting.component}
|
||||
{@const Component = setting.component as import("svelte").Component}
|
||||
<Component />
|
||||
{/if}
|
||||
</div>
|
||||
</div>
|
||||
{/if}
|
||||
{/each}
|
||||
{/if}
|
||||
{#if plugin.pluginId === "global-search"}
|
||||
<SettingRow
|
||||
title="Theme of the Month"
|
||||
@@ -197,5 +193,5 @@
|
||||
}}
|
||||
/>
|
||||
{/if}
|
||||
</div>
|
||||
</SettingsCard>
|
||||
{/each}
|
||||
@@ -0,0 +1,13 @@
|
||||
<script lang="ts">
|
||||
import type { Snippet } from "svelte";
|
||||
|
||||
let { class: className = "", children }: { class?: string; children: Snippet } = $props();
|
||||
</script>
|
||||
|
||||
<div class="border-none">
|
||||
<div
|
||||
class="p-1 my-1 from-white to-zinc-100 bg-gradient-to-br rounded-xl border shadow-sm border-zinc-200/50 dark:border-zinc-700/40 dark:to-zinc-900/50 dark:from-zinc-900/40 {className}"
|
||||
>
|
||||
{@render children()}
|
||||
</div>
|
||||
</div>
|
||||
@@ -1,4 +1,5 @@
|
||||
<script lang="ts">
|
||||
import SettingsCard from "../SettingsCard.svelte";
|
||||
import Switch from "@/interface/components/Switch.svelte";
|
||||
import ConnectMobileApp from "@/interface/components/ConnectMobileApp.svelte";
|
||||
import CloudSettingsSync from "@/interface/components/CloudSettingsSync.svelte";
|
||||
@@ -24,8 +25,8 @@
|
||||
});
|
||||
|
||||
const founderBadgeSetting = {
|
||||
title: "Titlebar founder badge",
|
||||
description: "Show your Cloud founder badge in the SEQTA titlebar",
|
||||
title: "Titlebar Cloud badges",
|
||||
description: "Show your Cloud badges in the SEQTA titlebar",
|
||||
} as const;
|
||||
|
||||
const showCloudCardHeader = $derived(
|
||||
@@ -46,65 +47,65 @@
|
||||
const showCloudAccountCard = $derived(showCloudCardHeader || showFounderBadgeSetting);
|
||||
</script>
|
||||
|
||||
<SettingRow
|
||||
title="Connect Mobile App"
|
||||
description="Link your SEQTA session to DesQTA — the modern desktop and mobile app for SEQTA Learn"
|
||||
id={0}
|
||||
Component={ConnectMobileApp}
|
||||
{searchQuery}
|
||||
props={{}}
|
||||
/>
|
||||
{#if matchesSearch(searchQuery, "Connect Mobile App", "Link your SEQTA session to DesQTA — the modern desktop and mobile app for SEQTA Learn")}
|
||||
<SettingsCard>
|
||||
<SettingRow
|
||||
title="Connect Mobile App"
|
||||
description="Link your SEQTA session to DesQTA — the modern desktop and mobile app for SEQTA Learn"
|
||||
id={0}
|
||||
Component={ConnectMobileApp}
|
||||
{searchQuery}
|
||||
props={{}}
|
||||
/>
|
||||
</SettingsCard>
|
||||
{/if}
|
||||
|
||||
{#if showCloudAccountCard}
|
||||
<div class="border-none">
|
||||
<div
|
||||
class="p-1 my-1 from-white to-zinc-100 bg-gradient-to-br rounded-xl border shadow-sm border-zinc-200/50 dark:border-zinc-700/40 dark:to-zinc-900/50 dark:from-zinc-900/40"
|
||||
>
|
||||
{#if showCloudCardHeader}
|
||||
<div class="flex justify-between items-center px-4 py-3">
|
||||
<div class="pr-4">
|
||||
<h2 class="text-sm font-bold">BetterSEQTA Cloud</h2>
|
||||
<p class="text-xs text-zinc-600 dark:text-zinc-300">Account & sync</p>
|
||||
</div>
|
||||
<div>
|
||||
<CloudHeader compact alwaysShowUserName onClick={showCloudPanel} />
|
||||
</div>
|
||||
<SettingsCard>
|
||||
{#if showCloudCardHeader}
|
||||
<div class="flex justify-between items-center px-4 py-3">
|
||||
<div class="pr-4">
|
||||
<h2 class="text-sm font-bold">BetterSEQTA Cloud</h2>
|
||||
<p class="text-xs text-zinc-600 dark:text-zinc-300">Account & sync</p>
|
||||
</div>
|
||||
{/if}
|
||||
{#if cloudState.isLoggedIn}
|
||||
<div class="px-3 pb-3" class:pt-3={!showCloudCardHeader}>
|
||||
{#if showCloudCardHeader}
|
||||
<CloudSettingsSync
|
||||
showDisclaimer={(onConfirm, onCancel) =>
|
||||
showDisclaimer(
|
||||
onConfirm,
|
||||
onCancel,
|
||||
"Restore from cloud?",
|
||||
"This will replace your local settings with the cloud backup. Continue?",
|
||||
)}
|
||||
/>
|
||||
{/if}
|
||||
{#if showFounderBadgeSetting}
|
||||
<SettingRow
|
||||
title={founderBadgeSetting.title}
|
||||
description={founderBadgeSetting.description}
|
||||
id={17}
|
||||
Component={Switch}
|
||||
{searchQuery}
|
||||
props={{
|
||||
state: $settingsState.showTitlebarFounderBadge !== false,
|
||||
onChange: (isOn: boolean) => (settingsState.showTitlebarFounderBadge = isOn),
|
||||
}}
|
||||
/>
|
||||
{/if}
|
||||
<div>
|
||||
<CloudHeader compact alwaysShowUserName onClick={showCloudPanel} />
|
||||
</div>
|
||||
{:else if showFounderBadgeSetting}
|
||||
<div class="px-5 pb-4 text-sm text-zinc-600 dark:text-zinc-400">
|
||||
Sign in to Cloud first.
|
||||
</div>
|
||||
{/if}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
{/if}
|
||||
{#if cloudState.isLoggedIn}
|
||||
<div class="px-3 pb-3" class:pt-3={!showCloudCardHeader}>
|
||||
{#if showCloudCardHeader}
|
||||
<CloudSettingsSync
|
||||
showDisclaimer={(onConfirm, onCancel) =>
|
||||
showDisclaimer(
|
||||
onConfirm,
|
||||
onCancel,
|
||||
"Restore from cloud?",
|
||||
"This will replace your local settings with the cloud backup. Continue?",
|
||||
)}
|
||||
/>
|
||||
{/if}
|
||||
{#if showFounderBadgeSetting}
|
||||
<SettingRow
|
||||
title={founderBadgeSetting.title}
|
||||
description={founderBadgeSetting.description}
|
||||
id={17}
|
||||
Component={Switch}
|
||||
{searchQuery}
|
||||
props={{
|
||||
state: $settingsState.showTitlebarFounderBadge !== false,
|
||||
onChange: (isOn: boolean) => (settingsState.showTitlebarFounderBadge = isOn),
|
||||
}}
|
||||
/>
|
||||
{/if}
|
||||
</div>
|
||||
{:else if showFounderBadgeSetting}
|
||||
<div class="px-5 pb-4 text-sm text-zinc-600 dark:text-zinc-400">
|
||||
Sign in to Cloud first.
|
||||
</div>
|
||||
{/if}
|
||||
</SettingsCard>
|
||||
{/if}
|
||||
|
||||
<PluginSettingsBlocks section="account" {showDisclaimer} {searchQuery} />
|
||||
@@ -2,7 +2,7 @@
|
||||
import Switch from "@/interface/components/Switch.svelte";
|
||||
import Button from "@/interface/components/Button.svelte";
|
||||
import { settingsState } from "@/seqta/utils/listeners/SettingsState";
|
||||
import { showPrivacyNotification } from "@/seqta/utils/Openers/OpenPrivacyNotification";
|
||||
import { openTermsOfServicePopup } from "@/seqta/utils/Openers/OpenTermsOfServicePopup";
|
||||
import { showThemeOfTheMonthPopupNow } from "@/seqta/utils/Openers/OpenThemeOfTheMonthPopup";
|
||||
import { closeExtensionPopup } from "@/seqta/utils/Closers/closeExtensionPopup";
|
||||
import { getSnapshotForUpload } from "@/seqta/utils/cloudSettingsSync";
|
||||
@@ -139,19 +139,20 @@
|
||||
</div>
|
||||
<div class="flex justify-between items-center px-4 py-3">
|
||||
<div class="pr-4">
|
||||
<h2 class="text-sm font-bold">Show Privacy Notification</h2>
|
||||
<h2 class="text-sm font-bold">Show Terms of Service</h2>
|
||||
<p class="text-xs text-zinc-600 dark:text-zinc-300">
|
||||
Show the privacy notification popup on next page load
|
||||
Show the terms of service acceptance popup (same as startup queue)
|
||||
</p>
|
||||
</div>
|
||||
<div>
|
||||
<Button
|
||||
onClick={async () => {
|
||||
settingsState.termsOfServiceLastAccepted = undefined;
|
||||
settingsState.privacyStatementShown = false;
|
||||
settingsState.privacyStatementLastUpdated = undefined;
|
||||
closeExtensionPopup();
|
||||
await new Promise((resolve) => setTimeout(resolve, 100));
|
||||
await showPrivacyNotification();
|
||||
await openTermsOfServicePopup(undefined, { force: true });
|
||||
}}
|
||||
text="Show Now"
|
||||
/>
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
<script lang="ts">
|
||||
import SettingsCard from "../SettingsCard.svelte";
|
||||
import Switch from "@/interface/components/Switch.svelte";
|
||||
import Button from "@/interface/components/Button.svelte";
|
||||
import PickerSwatch from "@/interface/components/PickerSwatch.svelte";
|
||||
@@ -19,87 +20,85 @@
|
||||
const isEngage = isSeqtaEngageExperience();
|
||||
</script>
|
||||
|
||||
{#each [
|
||||
{
|
||||
title: "Custom Theme Colour",
|
||||
description: "Customise the overall theme colour of SEQTA Learn",
|
||||
id: 4,
|
||||
Component: PickerSwatch,
|
||||
props: { onClick: showColourPicker },
|
||||
},
|
||||
{
|
||||
title: "Interface Font",
|
||||
description: "Choose the typeface used across SEQTA Learn",
|
||||
id: 16,
|
||||
Component: Button,
|
||||
props: { onClick: showFontPicker, text: "Change" },
|
||||
},
|
||||
] as option (option.id)}
|
||||
<SettingRow {...option} {searchQuery} />
|
||||
{/each}
|
||||
{#if matchesSearch(searchQuery, "Custom Theme Colour", "Interface Font", "Customise the overall theme colour of SEQTA Learn", "Choose the typeface used across SEQTA Learn")}
|
||||
<SettingsCard class="divide-y divide-zinc-200/60 dark:divide-zinc-700/40">
|
||||
{#each [
|
||||
{
|
||||
title: "Custom Theme Colour",
|
||||
description: "Customise the overall theme colour of SEQTA Learn",
|
||||
id: 4,
|
||||
Component: PickerSwatch,
|
||||
props: { onClick: showColourPicker },
|
||||
},
|
||||
{
|
||||
title: "Interface Font",
|
||||
description: "Choose the typeface used across SEQTA Learn",
|
||||
id: 16,
|
||||
Component: Button,
|
||||
props: { onClick: showFontPicker, text: "Change" },
|
||||
},
|
||||
] as option (option.id)}
|
||||
<SettingRow {...option} {searchQuery} />
|
||||
{/each}
|
||||
</SettingsCard>
|
||||
{/if}
|
||||
|
||||
{#if !isEngage && matchesSearch(searchQuery, "Sidebar Style", "Item Size", "Corner Radius", "Active Indicator", "Sidebar Position", "Sidebar Width", "Transparency Effects", "Blur Strength")}
|
||||
<div class="border-none">
|
||||
<SidebarAppearance />
|
||||
</div>
|
||||
<SidebarAppearance {searchQuery} />
|
||||
{/if}
|
||||
|
||||
{#if matchesSearch(searchQuery, "Adaptive Theme Colour", "Soft Gradient", "Smooth colour transition")}
|
||||
<div class="border-none">
|
||||
<div
|
||||
class="p-1 my-1 from-white to-zinc-100 bg-gradient-to-br rounded-xl border shadow-sm border-zinc-200/50 dark:border-zinc-700/40 dark:to-zinc-900/50 dark:from-zinc-900/40"
|
||||
>
|
||||
<div class="flex justify-between items-center px-4 py-3">
|
||||
<SettingsCard>
|
||||
<div class="flex justify-between items-center px-4 py-3">
|
||||
<div class="pr-4">
|
||||
<h2 class="text-sm font-bold">Adaptive Theme Colour</h2>
|
||||
<p class="text-xs text-zinc-600 dark:text-zinc-300">
|
||||
Change the theme colour based on the current class (e.g. when viewing a course or
|
||||
assessments page)
|
||||
</p>
|
||||
</div>
|
||||
<div>
|
||||
<Switch
|
||||
state={$settingsState.adaptiveThemeColour ?? false}
|
||||
onChange={(isOn: boolean) => (settingsState.adaptiveThemeColour = isOn)}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
{#if $settingsState.adaptiveThemeColour}
|
||||
<div
|
||||
class="flex justify-between items-center px-4 py-3 pl-6 border-t border-zinc-100 dark:border-zinc-700/50"
|
||||
>
|
||||
<div class="pr-4">
|
||||
<h2 class="text-sm font-bold">Adaptive Theme Colour</h2>
|
||||
<h2 class="text-sm font-bold">Soft Gradient</h2>
|
||||
<p class="text-xs text-zinc-600 dark:text-zinc-300">
|
||||
Change the theme colour based on the current class (e.g. when viewing a course or
|
||||
assessments page)
|
||||
Use a soft gradient instead of a solid colour when viewing a class
|
||||
</p>
|
||||
</div>
|
||||
<div>
|
||||
<Switch
|
||||
state={$settingsState.adaptiveThemeColour ?? false}
|
||||
onChange={(isOn: boolean) => (settingsState.adaptiveThemeColour = isOn)}
|
||||
state={$settingsState.adaptiveThemeGradient ?? false}
|
||||
onChange={(isOn: boolean) => (settingsState.adaptiveThemeGradient = isOn)}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
{#if $settingsState.adaptiveThemeColour}
|
||||
<div
|
||||
class="flex justify-between items-center px-4 py-3 pl-6 border-t border-zinc-100 dark:border-zinc-700/50"
|
||||
>
|
||||
<div class="pr-4">
|
||||
<h2 class="text-sm font-bold">Soft Gradient</h2>
|
||||
<p class="text-xs text-zinc-600 dark:text-zinc-300">
|
||||
Use a soft gradient instead of a solid colour when viewing a class
|
||||
</p>
|
||||
</div>
|
||||
<div>
|
||||
<Switch
|
||||
state={$settingsState.adaptiveThemeGradient ?? false}
|
||||
onChange={(isOn: boolean) => (settingsState.adaptiveThemeGradient = isOn)}
|
||||
/>
|
||||
</div>
|
||||
<div
|
||||
class="flex justify-between items-center px-4 py-3 pl-6 border-t border-zinc-100 dark:border-zinc-700/50"
|
||||
>
|
||||
<div class="pr-4">
|
||||
<h2 class="text-sm font-bold">Smooth colour transition</h2>
|
||||
<p class="text-xs text-zinc-600 dark:text-zinc-300">
|
||||
Ease between class/subject colours when navigating instead of switching instantly
|
||||
</p>
|
||||
</div>
|
||||
<div
|
||||
class="flex justify-between items-center px-4 py-3 pl-6 border-t border-zinc-100 dark:border-zinc-700/50"
|
||||
>
|
||||
<div class="pr-4">
|
||||
<h2 class="text-sm font-bold">Smooth colour transition</h2>
|
||||
<p class="text-xs text-zinc-600 dark:text-zinc-300">
|
||||
Ease between class/subject colours when navigating instead of switching instantly
|
||||
</p>
|
||||
</div>
|
||||
<div>
|
||||
<Switch
|
||||
state={$settingsState.adaptiveThemeColourTransition ?? true}
|
||||
onChange={(isOn: boolean) => (settingsState.adaptiveThemeColourTransition = isOn)}
|
||||
/>
|
||||
</div>
|
||||
<div>
|
||||
<Switch
|
||||
state={$settingsState.adaptiveThemeColourTransition ?? true}
|
||||
onChange={(isOn: boolean) => (settingsState.adaptiveThemeColourTransition = isOn)}
|
||||
/>
|
||||
</div>
|
||||
{/if}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
{/if}
|
||||
</SettingsCard>
|
||||
{/if}
|
||||
|
||||
<PluginSettingsBlocks section="appearance" {showDisclaimer} {searchQuery} />
|
||||
@@ -1,4 +1,5 @@
|
||||
<script lang="ts">
|
||||
import SettingsCard from "../SettingsCard.svelte";
|
||||
import Switch from "@/interface/components/Switch.svelte";
|
||||
import Button from "@/interface/components/Button.svelte";
|
||||
import Select from "@/interface/components/Select.svelte";
|
||||
@@ -11,10 +12,14 @@
|
||||
} from "@/seqta/utils/performanceMode";
|
||||
import browser from "webextension-polyfill";
|
||||
import { matchesSearch, type SettingsSectionSharedProps } from "../shared";
|
||||
import { checkRemoteFeature } from "@/seqta/utils/remoteConfig/runtime";
|
||||
|
||||
let { searchQuery = "" }: SettingsSectionSharedProps = $props();
|
||||
|
||||
const isEngage = isSeqtaEngageExperience();
|
||||
const onoffGate = $derived(checkRemoteFeature("settings.control.onoff"));
|
||||
const onoffGreyedOut = $derived(onoffGate.mode === "greyout");
|
||||
const sidebarEditHidden = $derived(checkRemoteFeature("ui.sidebar.edit").hide);
|
||||
|
||||
const generalOptions = $derived([
|
||||
{
|
||||
@@ -38,7 +43,7 @@
|
||||
onChange: (isOn: boolean) => (settingsState.performanceMode = isOn),
|
||||
},
|
||||
},
|
||||
...(!isEngage
|
||||
...(!isEngage && !sidebarEditHidden
|
||||
? [
|
||||
{
|
||||
title: "Edit Sidebar Layout",
|
||||
@@ -140,34 +145,50 @@
|
||||
]);
|
||||
</script>
|
||||
|
||||
{#each generalOptions as option (option.id)}
|
||||
<SettingRow {...option} {searchQuery} />
|
||||
{#if option.id === 0 && $settingsState.performanceMode && matchesSearch(searchQuery, "Performance Mode", "Global Search", "Assessment Averages", "enable anyway", "paused")}
|
||||
<div class="border-none -mt-px">
|
||||
<div
|
||||
class="mx-5 mb-4 rounded-xl border border-zinc-200/80 bg-zinc-50/80 px-4 py-3 dark:border-zinc-700/60 dark:bg-zinc-900/40"
|
||||
>
|
||||
<p class="mb-3 text-sm font-medium text-zinc-500 dark:text-zinc-400">
|
||||
Paused for performance — enable anyway:
|
||||
</p>
|
||||
<div class="space-y-3">
|
||||
{#each PERFORMANCE_HEAVY_PLUGINS as heavy (heavy.id)}
|
||||
<div class="flex justify-between items-center gap-4">
|
||||
<div class="min-w-0">
|
||||
<p class="text-sm font-semibold text-zinc-800 dark:text-zinc-100">{heavy.name}</p>
|
||||
<p class="text-xs text-zinc-500 dark:text-zinc-400">{heavy.description}</p>
|
||||
</div>
|
||||
<Switch
|
||||
state={$settingsState.performanceModePluginOverrides?.[heavy.id] === true}
|
||||
onChange={(forceOn: boolean) => setPerformanceModePluginOverride(heavy.id, forceOn)}
|
||||
/>
|
||||
</div>
|
||||
{/each}
|
||||
{#if generalOptions.some((option) => matchesSearch(searchQuery, option.title, option.description))}
|
||||
<SettingsCard class="divide-y divide-zinc-200/60 dark:divide-zinc-700/40">
|
||||
{#each generalOptions as option (option.id)}
|
||||
{#if option.id === 12}
|
||||
<div
|
||||
class:opacity-50={onoffGreyedOut}
|
||||
class:pointer-events-none={onoffGreyedOut}
|
||||
title={onoffGreyedOut
|
||||
? (onoffGate.message?.body ?? "Disabled by site operator")
|
||||
: undefined}
|
||||
>
|
||||
<SettingRow {...option} {searchQuery} />
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
{/if}
|
||||
{/each}
|
||||
{:else}
|
||||
<SettingRow {...option} {searchQuery} />
|
||||
{/if}
|
||||
{#if option.id === 0 && $settingsState.performanceMode && matchesSearch(searchQuery, "Performance Mode", "Global Search", "Assessment Averages", "enable anyway", "paused")}
|
||||
<div class="border-none -mt-px">
|
||||
<div
|
||||
class="mx-5 mb-4 rounded-xl border border-zinc-200/80 bg-zinc-50/80 px-4 py-3 dark:border-zinc-700/60 dark:bg-zinc-900/40"
|
||||
>
|
||||
<p class="mb-3 text-sm font-medium text-zinc-500 dark:text-zinc-400">
|
||||
Paused for performance — enable anyway:
|
||||
</p>
|
||||
<div class="space-y-3">
|
||||
{#each PERFORMANCE_HEAVY_PLUGINS as heavy (heavy.id)}
|
||||
<div class="flex justify-between items-center gap-4">
|
||||
<div class="min-w-0">
|
||||
<p class="text-sm font-semibold text-zinc-800 dark:text-zinc-100">{heavy.name}</p>
|
||||
<p class="text-xs text-zinc-500 dark:text-zinc-400">{heavy.description}</p>
|
||||
</div>
|
||||
<Switch
|
||||
state={$settingsState.performanceModePluginOverrides?.[heavy.id] === true}
|
||||
onChange={(forceOn: boolean) => setPerformanceModePluginOverride(heavy.id, forceOn)}
|
||||
/>
|
||||
</div>
|
||||
{/each}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
{/if}
|
||||
{/each}
|
||||
</SettingsCard>
|
||||
{/if}
|
||||
|
||||
{#if matchesSearch(
|
||||
searchQuery,
|
||||
@@ -176,43 +197,41 @@
|
||||
"Maximum Subjects",
|
||||
"Maximum Assessments per Subject",
|
||||
)}
|
||||
<div class="border-none">
|
||||
<SettingsCard>
|
||||
<div class="flex justify-between items-center px-4 py-3">
|
||||
<div class="pr-4">
|
||||
<h2 class="text-sm font-bold">Home Page Assessments</h2>
|
||||
<p class="text-xs text-zinc-600 dark:text-zinc-300">
|
||||
Limit upcoming assessments shown on the home page by subject
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
<div
|
||||
class="p-1 my-1 from-white to-zinc-100 bg-gradient-to-br rounded-xl border shadow-sm border-zinc-200/50 dark:border-zinc-700/40 dark:to-zinc-900/50 dark:from-zinc-900/40"
|
||||
class="flex justify-between items-center px-4 py-3 pl-6 border-t border-zinc-100 dark:border-zinc-700/50"
|
||||
>
|
||||
<div class="flex justify-between items-center px-4 py-3">
|
||||
<div class="pr-4">
|
||||
<h2 class="text-sm font-bold">Home Page Assessments</h2>
|
||||
<p class="text-xs text-zinc-600 dark:text-zinc-300">
|
||||
Limit upcoming assessments shown on the home page by subject
|
||||
</p>
|
||||
</div>
|
||||
<div class="pr-4">
|
||||
<h2 class="text-sm font-bold">Include Past Assessments</h2>
|
||||
<p class="text-xs text-zinc-600 dark:text-zinc-300">
|
||||
Show past-due assessments from the upcoming list, matching the Assessments page
|
||||
</p>
|
||||
</div>
|
||||
<div
|
||||
class="flex justify-between items-center px-4 py-3 pl-6 border-t border-zinc-100 dark:border-zinc-700/50"
|
||||
>
|
||||
<div class="pr-4">
|
||||
<h2 class="text-sm font-bold">Include Past Assessments</h2>
|
||||
<p class="text-xs text-zinc-600 dark:text-zinc-300">
|
||||
Show past-due assessments from the upcoming list, matching the Assessments page
|
||||
</p>
|
||||
</div>
|
||||
<div>
|
||||
<Switch
|
||||
state={$settingsState.homeUpcomingIncludePast ?? true}
|
||||
onChange={(isOn: boolean) => (settingsState.homeUpcomingIncludePast = isOn)}
|
||||
/>
|
||||
</div>
|
||||
<div>
|
||||
<Switch
|
||||
state={$settingsState.homeUpcomingIncludePast ?? true}
|
||||
onChange={(isOn: boolean) => (settingsState.homeUpcomingIncludePast = isOn)}
|
||||
/>
|
||||
</div>
|
||||
<div
|
||||
class="flex justify-between items-center px-4 py-3 pl-6 border-t border-zinc-100 dark:border-zinc-700/50"
|
||||
>
|
||||
<div class="pr-4">
|
||||
<h2 class="text-sm font-bold">Maximum Subjects</h2>
|
||||
<p class="text-xs text-zinc-600 dark:text-zinc-300">
|
||||
Number of subjects to include, ordered by soonest due date
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
<div
|
||||
class="flex justify-between items-center px-4 py-3 pl-6 border-t border-zinc-100 dark:border-zinc-700/50"
|
||||
>
|
||||
<div class="pr-4">
|
||||
<h2 class="text-sm font-bold">Maximum Subjects</h2>
|
||||
<p class="text-xs text-zinc-600 dark:text-zinc-300">
|
||||
Number of subjects to include, ordered by soonest due date
|
||||
</p>
|
||||
</div>
|
||||
<div class="shrink-0">
|
||||
<Select
|
||||
value={String($settingsState.homeUpcomingSubjectsMax ?? 5)}
|
||||
onChange={(value: string) => (settingsState.homeUpcomingSubjectsMax = Number(value))}
|
||||
@@ -226,15 +245,17 @@
|
||||
]}
|
||||
/>
|
||||
</div>
|
||||
<div
|
||||
class="flex justify-between items-center px-4 py-3 pl-6 border-t border-zinc-100 dark:border-zinc-700/50"
|
||||
>
|
||||
<div class="pr-4">
|
||||
<h2 class="text-sm font-bold">Maximum Assessments per Subject</h2>
|
||||
<p class="text-xs text-zinc-600 dark:text-zinc-300">
|
||||
Assessments shown for each included subject
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
<div
|
||||
class="flex justify-between items-center px-4 py-3 pl-6 border-t border-zinc-100 dark:border-zinc-700/50"
|
||||
>
|
||||
<div class="pr-4">
|
||||
<h2 class="text-sm font-bold">Maximum Assessments per Subject</h2>
|
||||
<p class="text-xs text-zinc-600 dark:text-zinc-300">
|
||||
Assessments shown for each included subject
|
||||
</p>
|
||||
</div>
|
||||
<div class="shrink-0">
|
||||
<Select
|
||||
value={String($settingsState.homeUpcomingAssessmentsPerSubjectMax ?? 0)}
|
||||
onChange={(value: string) =>
|
||||
@@ -250,5 +271,5 @@
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</SettingsCard>
|
||||
{/if}
|
||||
@@ -2,6 +2,7 @@
|
||||
import MotionDiv from '@/interface/components/MotionDiv.svelte';
|
||||
import { settingsState } from "@/seqta/utils/listeners/SettingsState.ts"
|
||||
import Switch from "@/interface/components/Switch.svelte"
|
||||
import Button from "@/interface/components/Button.svelte"
|
||||
import { onMount } from 'svelte';
|
||||
import Shortcuts from "@/seqta/content/links.json"
|
||||
|
||||
@@ -199,16 +200,11 @@
|
||||
animate={{ opacity: 1, y: 0 }}
|
||||
transition={{ duration: 0.3 }}
|
||||
>
|
||||
<button
|
||||
class="w-full px-4 py-3 mb-4 text-base dark:text-white transition rounded-xl bg-zinc-200 dark:bg-zinc-700/50"
|
||||
onclick={isFormVisible ? addNewCustomShortcut : toggleForm}
|
||||
>
|
||||
{#if isFormVisible}
|
||||
Add
|
||||
{:else}
|
||||
Add Custom Shortcut
|
||||
{/if}
|
||||
</button>
|
||||
<Button
|
||||
class="w-full mb-4"
|
||||
text={isFormVisible ? "Add" : "Add Custom Shortcut"}
|
||||
onClick={isFormVisible ? addNewCustomShortcut : toggleForm}
|
||||
/>
|
||||
</MotionDiv>
|
||||
</div>
|
||||
{/if}
|
||||
|
||||
@@ -1,12 +1,11 @@
|
||||
<script lang="ts">
|
||||
import BackgroundSelector from "@/interface/components/themes/BackgroundSelector.svelte"
|
||||
import ThemeSelector from "@/interface/components/themes/ThemeSelector.svelte"
|
||||
import Button from "@/interface/components/Button.svelte"
|
||||
import { standalone } from "@/interface/utils/standalone.svelte"
|
||||
import type { ThemeListMode } from "@/interface/utils/themeListFilters"
|
||||
|
||||
let { section = "all", listMode = "all" } = $props<{
|
||||
let { section = "all" } = $props<{
|
||||
section?: "all" | "themes" | "backgrounds";
|
||||
listMode?: ThemeListMode;
|
||||
}>();
|
||||
|
||||
// backgrounds
|
||||
@@ -22,24 +21,23 @@
|
||||
<div class="py-4">
|
||||
{#if !standalone.standalone}
|
||||
{#if showBackgrounds}
|
||||
<button
|
||||
onclick={() => selectNoBackground()}
|
||||
<Button
|
||||
onClick={() => selectNoBackground()}
|
||||
disabled={section === "backgrounds" && !clearTheme}
|
||||
class="w-full px-4 py-3 mb-4 text-base dark:text-white transition rounded-xl bg-zinc-200 dark:bg-zinc-700/50 disabled:opacity-50">
|
||||
{section === "all"
|
||||
text={section === "all"
|
||||
? clearTheme ? 'Clear Theme' : 'Select a Theme'
|
||||
: clearTheme ? 'Clear Background' : 'No Background Selected'}
|
||||
</button>
|
||||
class="w-full mb-4"
|
||||
/>
|
||||
{/if}
|
||||
<div class="w-full">
|
||||
{#if showThemes || showBackgrounds}
|
||||
<div class="mb-3 flex justify-end">
|
||||
<button
|
||||
onclick={() => editMode = !editMode}
|
||||
class="inline-flex h-8 items-center rounded-xl bg-zinc-100 px-3 text-lg dark:bg-zinc-700">
|
||||
<span class="mr-2">{editMode ? 'Done' : 'Remove'}</span>
|
||||
<span class="font-IconFamily">{editMode ? '\ue9e4' : '\uec38'}</span>
|
||||
</button>
|
||||
<Button
|
||||
onClick={() => editMode = !editMode}
|
||||
text={editMode ? 'Done' : 'Remove'}
|
||||
icon={editMode ? '\ue9e4' : '\uec38'}
|
||||
/>
|
||||
</div>
|
||||
{/if}
|
||||
|
||||
@@ -47,20 +45,19 @@
|
||||
<BackgroundSelector isEditMode={editMode} bind:selectedBackground={selectedBackground} bind:selectNoBackground={selectNoBackground} />
|
||||
{/if}
|
||||
{#if showThemes}
|
||||
{#if listMode === "custom"}
|
||||
<button
|
||||
type="button"
|
||||
class="mb-4 flex h-11 w-full items-center justify-center gap-2 rounded-xl bg-zinc-900 text-sm font-medium text-white dark:bg-zinc-100 dark:text-zinc-900"
|
||||
onclick={() =>
|
||||
{#if section === "themes"}
|
||||
<Button
|
||||
variant="primary"
|
||||
class="w-full mb-4"
|
||||
icon={""}
|
||||
text="Open theme builder"
|
||||
onClick={() =>
|
||||
void import("@/seqta/utils/launchPageThemeBuilder").then(({ launchPageThemeBuilder }) =>
|
||||
launchPageThemeBuilder(),
|
||||
)}
|
||||
>
|
||||
<span class="font-IconFamily text-lg" aria-hidden="true"></span>
|
||||
Open theme builder
|
||||
</button>
|
||||
/>
|
||||
{/if}
|
||||
<ThemeSelector isEditMode={editMode} showNavigation={section === "all"} {listMode} />
|
||||
<ThemeSelector isEditMode={editMode} showNavigation={section === "all"} />
|
||||
{/if}
|
||||
</div>
|
||||
{:else}
|
||||
|
||||
@@ -632,7 +632,7 @@
|
||||
|
||||
<Divider />
|
||||
|
||||
<div class="theme-creator-sidebar -mx-2">
|
||||
<div class="-mx-2">
|
||||
<SidebarAppearance />
|
||||
</div>
|
||||
|
||||
@@ -694,7 +694,7 @@
|
||||
{/each}
|
||||
|
||||
<div
|
||||
class="sticky bottom-0 z-10 -mx-2 mt-4 space-y-2 border-t border-zinc-200/80 bg-zinc-100 p-3 pb-4 dark:border-zinc-700/60 dark:bg-zinc-800"
|
||||
class="sticky bottom-0 z-[1500] -mx-2 mt-4 space-y-2 border-t border-zinc-200/80 bg-zinc-100 p-3 pb-4 dark:border-zinc-700/60 dark:bg-zinc-800"
|
||||
>
|
||||
<button
|
||||
type="button"
|
||||
@@ -721,13 +721,4 @@
|
||||
{/if}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<style>
|
||||
.theme-creator-sidebar :global(.preview-pane) {
|
||||
display: none;
|
||||
}
|
||||
.theme-creator-sidebar :global(.picker-body) {
|
||||
grid-template-columns: 1fr;
|
||||
}
|
||||
</style>
|
||||
</div>
|
||||
@@ -35,6 +35,8 @@ export type Theme = {
|
||||
master_id?: string;
|
||||
/** Variants nested on master rows; installs use flavour `id` */
|
||||
flavours?: ThemeFlavour[];
|
||||
/** Admin review list: required for preview install (`marketplace` | `community`). */
|
||||
adminSource?: "marketplace" | "community";
|
||||
};
|
||||
|
||||
/** One marquee slide (cover hero or modal carousel). */
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
import type { CustomTheme } from '@/types/CustomThemes';
|
||||
import type { Theme } from '@/interface/types/Theme';
|
||||
import {
|
||||
filterThemesByMode,
|
||||
getThemeApplyButtonStyles,
|
||||
getCommunityInstalledThemeIds,
|
||||
getStoreInstalledThemeIds,
|
||||
@@ -54,27 +53,6 @@ describe('resolveLocalThemeInstallId', () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe('filterThemesByMode', () => {
|
||||
const storeTheme = makeCustomTheme({
|
||||
id: 'store-1',
|
||||
name: 'Store Theme',
|
||||
installedFromStore: true,
|
||||
});
|
||||
const communityTheme = makeCustomTheme({
|
||||
id: 'community-1',
|
||||
name: 'Community Theme',
|
||||
installedFromCommunity: true,
|
||||
});
|
||||
const localTheme = makeCustomTheme({ id: 'local-1', name: 'Local Theme' });
|
||||
|
||||
it('splits store, community, and local themes by mode', () => {
|
||||
const all = [storeTheme, communityTheme, localTheme];
|
||||
expect(filterThemesByMode(all, 'all')).toEqual(all);
|
||||
expect(filterThemesByMode(all, 'downloaded')).toEqual([storeTheme, communityTheme]);
|
||||
expect(filterThemesByMode(all, 'custom')).toEqual([localTheme]);
|
||||
});
|
||||
});
|
||||
|
||||
describe('installed theme id helpers', () => {
|
||||
it('returns store-only and community-only ids', () => {
|
||||
const themes = [
|
||||
|
||||
@@ -2,8 +2,6 @@ import type { CustomTheme } from '@/types/CustomThemes';
|
||||
import type { Theme } from '@/interface/types/Theme';
|
||||
import { parseCssColor } from '@/seqta/ui/colors/parseCssColor';
|
||||
|
||||
export type ThemeListMode = 'downloaded' | 'custom' | 'all';
|
||||
|
||||
const DEFAULT_THEME_ACCENT = 'rgba(0, 123, 255, 1)';
|
||||
|
||||
/** Local themes: created in the editor or imported from a file (not store/community). */
|
||||
@@ -11,11 +9,6 @@ export function isLocalCustomTheme(theme: CustomTheme): boolean {
|
||||
return theme.installedFromStore !== true && theme.installedFromCommunity !== true;
|
||||
}
|
||||
|
||||
/** Themes installed from the official store or community API. */
|
||||
export function isDownloadedTheme(theme: CustomTheme): boolean {
|
||||
return theme.installedFromStore === true || theme.installedFromCommunity === true;
|
||||
}
|
||||
|
||||
/**
|
||||
* When importing a local copy of a theme whose id already belongs to a store/community
|
||||
* install, use a new id so both copies can coexist.
|
||||
@@ -36,12 +29,6 @@ export function resolveLocalThemeInstallId(
|
||||
return themeId;
|
||||
}
|
||||
|
||||
export function filterThemesByMode(themes: CustomTheme[], mode: ThemeListMode): CustomTheme[] {
|
||||
if (mode === 'all') return themes;
|
||||
if (mode === 'custom') return themes.filter(isLocalCustomTheme);
|
||||
return themes.filter(isDownloadedTheme);
|
||||
}
|
||||
|
||||
/** Installed theme ids from the official store only (excludes file imports / custom copies). */
|
||||
export function getStoreInstalledThemeIds(themes: CustomTheme[]): string[] {
|
||||
return themes.filter((theme) => theme.installedFromStore === true).map((theme) => theme.id);
|
||||
|
||||
@@ -15,7 +15,7 @@
|
||||
"64": "resources/icons/icon-64.png"
|
||||
}
|
||||
},
|
||||
"permissions": ["tabs", "notifications", "storage", "alarms", "cookies"],
|
||||
"permissions": ["tabs", "notifications", "storage", "alarms"],
|
||||
"host_permissions": [
|
||||
"https://newsapi.org/",
|
||||
"https://betterseqta.org/",
|
||||
@@ -48,6 +48,7 @@
|
||||
"resources/update-image.webp",
|
||||
"resources/pdfjs/pdf.worker.min.mjs",
|
||||
"resources/pdfjs/pdf.legacy.min.mjs",
|
||||
"resources/themeToggleSurprisePage.js",
|
||||
"resources/ort/*",
|
||||
"assets/*.css",
|
||||
"assets/*"
|
||||
|
||||
@@ -9,6 +9,7 @@ import { processMenuItemNode } from "@/seqta/utils/sidebarMenuIcons";
|
||||
import { ChangeMenuItemPositions } from "@/seqta/utils/Openers/menuOrder";
|
||||
import { isMenuOptionsOpen } from "@/seqta/utils/Openers/menuOptionsState";
|
||||
import { settingsState } from "@/seqta/utils/listeners/SettingsState";
|
||||
import { checkRemoteFeature } from "@/seqta/utils/remoteConfig/runtime";
|
||||
import { applyMenuItemVisibility } from "@/seqta/utils/menuItemVisibility";
|
||||
import { getNativeMenuList } from "@/seqta/ui/sidebar/parseNativeMenu";
|
||||
import { rafThrottle } from "@/seqta/utils/rafThrottle";
|
||||
@@ -29,6 +30,9 @@ export async function injectAnalyticsMenuItem(): Promise<() => void> {
|
||||
if (isSeqtaEngageExperience()) {
|
||||
return () => {};
|
||||
}
|
||||
if (checkRemoteFeature("page.analytics").hide) {
|
||||
return () => {};
|
||||
}
|
||||
|
||||
document
|
||||
.querySelectorAll(
|
||||
|
||||
@@ -35,7 +35,7 @@ const FOLDER_HEROICONS = [
|
||||
folderHeroicon('<path d="M9 18V5l12-2v13"/><circle cx="6" cy="18" r="3"/><circle cx="18" cy="16" r="3"/>'),
|
||||
];
|
||||
|
||||
const FOLDER_ICON_SVG = `<svg style="width:24px;height:24px;flex-shrink:0" viewBox="0 0 24 24"><path fill="#888" d="M10 4H4c-1.1 0-2 .9-2 2v12c0 1.1.9 2 2 2h16c1.1 0 2-.9 2-2V8c0-1.1-.9-2-2-2h-8l-2-2z"/></svg>`;
|
||||
const FOLDER_ICON_SVG = `<svg style="width:24px;height:24px;flex-shrink:0" viewBox="0 0 24 24"><path fill="currentColor" d="M10 4H4c-1.1 0-2 .9-2 2v12c0 1.1.9 2 2 2h16c1.1 0 2-.9 2-2V8c0-1.1-.9-2-2-2h-8l-2-2z"/></svg>`;
|
||||
const PLUS_SVG = `<svg style="width:14px;height:14px;flex-shrink:0" viewBox="0 0 24 24"><path fill="#888" d="M19 13h-6v6h-2v-6H5v-2h6V5h2v6h6v2z"/></svg>`;
|
||||
const CHECK_SVG_WHITE = `<svg style="width:14px;height:14px;flex-shrink:0" viewBox="0 0 24 24"><path fill="#fff" d="M9 16.17L4.83 12l-1.42 1.41L9 19 21 7l-1.41-1.41L9 16.17z"/></svg>`;
|
||||
const CLOSE_SVG = `<svg style="width:14px;height:14px;flex-shrink:0" viewBox="0 0 24 24"><path fill="#888" d="M19 6.41L17.59 5 12 10.59 6.41 5 5 6.41 10.59 12 5 17.59 6.41 19 12 13.41 17.59 19 19 17.59 13.41 12 19 6.41z"/></svg>`;
|
||||
|
||||
@@ -375,6 +375,7 @@
|
||||
/* ── "Add to folder" button in message actions bar ── */
|
||||
.bsplus-folder-btn {
|
||||
position: relative;
|
||||
margin-left: 8px;
|
||||
}
|
||||
|
||||
.bsplus-folder-btn svg {
|
||||
|
||||
@@ -9,16 +9,20 @@
|
||||
isUseCloudPfpEnabled,
|
||||
notifyProfilePictureChanged,
|
||||
pullCloudProfilePictureFromServer,
|
||||
revertCloudProfilePicture,
|
||||
syncLocalProfilePictureToCloud,
|
||||
uploadCloudProfilePicture,
|
||||
} from '@/seqta/utils/cloudPfpSync'
|
||||
|
||||
let value = $state<string | undefined>(undefined)
|
||||
let fileInput = $state<HTMLInputElement | undefined>(undefined)
|
||||
let cloudFileInput = $state<HTMLInputElement | undefined>(undefined)
|
||||
let dragging = $state(false)
|
||||
let blobUrl = $state<string | undefined>(undefined)
|
||||
let useCloudPfp = $state(false)
|
||||
let refreshingCloud = $state(false)
|
||||
let cloudRefreshError = $state<string | undefined>(undefined)
|
||||
let cloudState = $state(cloudAuth.state)
|
||||
let cloudBusy = $state(false)
|
||||
let cloudError = $state<string | undefined>(undefined)
|
||||
|
||||
const store = localforage.createInstance({
|
||||
name: 'profile-picture-store',
|
||||
@@ -39,34 +43,32 @@
|
||||
|
||||
onMount(() => {
|
||||
void load()
|
||||
const unsub = cloudAuth.subscribe((s) => { cloudState = s })
|
||||
const onStorage = (
|
||||
changes: Record<string, browser.Storage.StorageChange>,
|
||||
areaName: string,
|
||||
) => {
|
||||
if (areaName === 'local' && changes['plugin.profile-picture.settings']) {
|
||||
void load()
|
||||
}
|
||||
if (areaName === 'local' && changes['plugin.profile-picture.settings']) void load()
|
||||
}
|
||||
browser.storage.onChanged.addListener(onStorage)
|
||||
return () => browser.storage.onChanged.removeListener(onStorage)
|
||||
return () => {
|
||||
browser.storage.onChanged.removeListener(onStorage)
|
||||
unsub()
|
||||
}
|
||||
})
|
||||
|
||||
async function afterProfilePictureChange() {
|
||||
window.dispatchEvent(new Event('profile-picture-updated'))
|
||||
if (await isUseCloudPfpEnabled()) {
|
||||
await syncLocalProfilePictureToCloud()
|
||||
}
|
||||
if (await isUseCloudPfpEnabled()) await syncLocalProfilePictureToCloud()
|
||||
await notifyProfilePictureChanged()
|
||||
}
|
||||
|
||||
async function refreshCloudPfp() {
|
||||
cloudRefreshError = undefined
|
||||
refreshingCloud = true
|
||||
const result = await pullCloudProfilePictureFromServer()
|
||||
refreshingCloud = false
|
||||
if (!result.success) {
|
||||
cloudRefreshError = result.error ?? 'Could not refresh cloud photo'
|
||||
}
|
||||
async function runCloud(action: () => Promise<{ success: boolean; error?: string }>) {
|
||||
cloudError = undefined
|
||||
cloudBusy = true
|
||||
const result = await action()
|
||||
cloudBusy = false
|
||||
if (!result.success) cloudError = result.error
|
||||
}
|
||||
|
||||
function triggerSelect() {
|
||||
@@ -75,19 +77,22 @@
|
||||
|
||||
async function handleFiles(files: FileList | null) {
|
||||
const file = files?.[0]
|
||||
if (!file) return
|
||||
|
||||
if (blobUrl) {
|
||||
URL.revokeObjectURL(blobUrl)
|
||||
}
|
||||
if (!file?.type.startsWith('image/')) return
|
||||
|
||||
if (blobUrl) URL.revokeObjectURL(blobUrl)
|
||||
await store.setItem('profile-picture', file)
|
||||
const newBlobUrl = URL.createObjectURL(file)
|
||||
value = newBlobUrl
|
||||
blobUrl = newBlobUrl
|
||||
blobUrl = URL.createObjectURL(file)
|
||||
value = blobUrl
|
||||
await afterProfilePictureChange()
|
||||
}
|
||||
|
||||
async function onCloudFileChange() {
|
||||
const file = cloudFileInput?.files?.[0]
|
||||
if (cloudFileInput) cloudFileInput.value = ''
|
||||
if (!file) return
|
||||
await runCloud(() => uploadCloudProfilePicture(file))
|
||||
}
|
||||
|
||||
function onFileChange() {
|
||||
handleFiles(fileInput?.files || null)
|
||||
}
|
||||
@@ -105,27 +110,22 @@
|
||||
}
|
||||
value = undefined
|
||||
await store.removeItem('profile-picture')
|
||||
if (await isUseCloudPfpEnabled()) {
|
||||
await clearCloudProfilePicture()
|
||||
}
|
||||
if (await isUseCloudPfpEnabled()) await clearCloudProfilePicture()
|
||||
await afterProfilePictureChange()
|
||||
}
|
||||
</script>
|
||||
|
||||
<div class="flex flex-col items-end gap-1 shrink-0">
|
||||
<div class="flex items-center gap-2">
|
||||
{#if useCloudPfp}
|
||||
<CloudPfpAvatar
|
||||
user={cloudAuth.state.user}
|
||||
class="object-cover rounded-full size-10 shrink-0"
|
||||
/>
|
||||
{#if useCloudPfp && cloudState.isLoggedIn}
|
||||
<CloudPfpAvatar user={cloudState.user} class="object-cover rounded-full size-10 shrink-0" />
|
||||
<button
|
||||
type="button"
|
||||
class="flex justify-center items-center shrink-0 rounded-md size-8 bg-zinc-200 dark:bg-zinc-700 hover:bg-zinc-300 dark:hover:bg-zinc-600 disabled:opacity-50"
|
||||
disabled={refreshingCloud}
|
||||
disabled={cloudBusy}
|
||||
title="Refresh from cloud"
|
||||
aria-label="Refresh from cloud"
|
||||
onclick={() => refreshCloudPfp()}
|
||||
onclick={() => runCloud(pullCloudProfilePictureFromServer)}
|
||||
>
|
||||
<span class="text-lg font-IconFamily dark:text-white">{'\uec79'}</span>
|
||||
</button>
|
||||
@@ -171,7 +171,41 @@
|
||||
{/if}
|
||||
</div>
|
||||
</div>
|
||||
{#if cloudRefreshError}
|
||||
<p class="max-w-[12rem] text-xs text-right text-red-500">{cloudRefreshError}</p>
|
||||
|
||||
{#if cloudState.isLoggedIn}
|
||||
<div class="flex flex-wrap gap-2 justify-end items-center max-w-[14rem]">
|
||||
<button
|
||||
type="button"
|
||||
class="text-xs text-zinc-600 dark:text-zinc-300 hover:underline disabled:opacity-50"
|
||||
disabled={cloudBusy}
|
||||
onclick={() => cloudFileInput?.click()}
|
||||
>
|
||||
Cloud upload
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
class="text-xs text-zinc-600 dark:text-zinc-300 hover:underline disabled:opacity-50"
|
||||
disabled={cloudBusy || !cloudState.user?.pfpUrl}
|
||||
onclick={() => runCloud(clearCloudProfilePicture)}
|
||||
>
|
||||
Clear cloud
|
||||
</button>
|
||||
{#each cloudState.user?.pfpHistory ?? [] as entry (entry.id)}
|
||||
<button
|
||||
type="button"
|
||||
class="size-7 overflow-hidden rounded-full ring-1 ring-zinc-300 dark:ring-zinc-600 disabled:opacity-50"
|
||||
title="Restore"
|
||||
disabled={cloudBusy}
|
||||
onclick={() => runCloud(() => revertCloudProfilePicture(entry.id))}
|
||||
>
|
||||
<img src={entry.r2Key} alt="" class="object-cover size-full" />
|
||||
</button>
|
||||
{/each}
|
||||
<input type="file" accept="image/*" class="hidden" bind:this={cloudFileInput} onchange={onCloudFileChange} />
|
||||
</div>
|
||||
{/if}
|
||||
|
||||
{#if cloudError}
|
||||
<p class="max-w-[12rem] text-xs text-right text-red-500">{cloudError}</p>
|
||||
{/if}
|
||||
</div>
|
||||
@@ -29,7 +29,7 @@ const profilePicturePlugin: Plugin<typeof settings> = {
|
||||
id: "profile-picture",
|
||||
name: "Custom Profile Picture",
|
||||
description: "Use your own image in place of the profile icon",
|
||||
version: "1.2.0",
|
||||
version: "1.3.0",
|
||||
settings: settings,
|
||||
disableToggle: true,
|
||||
defaultEnabled: false,
|
||||
@@ -96,9 +96,7 @@ const profilePicturePlugin: Plugin<typeof settings> = {
|
||||
}
|
||||
|
||||
if (api.settings.useCloudPfp && cloudAuth.state.isLoggedIn) {
|
||||
const { pullCloudProfilePictureFromServer } = await import(
|
||||
"@/seqta/utils/cloudPfpSync"
|
||||
);
|
||||
const { pullCloudProfilePictureFromServer } = await import("@/seqta/utils/cloudPfpSync");
|
||||
await pullCloudProfilePictureFromServer();
|
||||
}
|
||||
|
||||
|
||||
@@ -52,7 +52,9 @@ describe("cloud theme restoration", () => {
|
||||
(browser.runtime.sendMessage as jest.Mock).mockImplementation(
|
||||
async ({ url }) => {
|
||||
if (
|
||||
url === `https://betterseqta.org/api/${catalog}/catalog-id/download`
|
||||
typeof url === "string" &&
|
||||
url.includes(`/api/${catalog}/catalog-id/download`) &&
|
||||
url.includes("extensionVersion=")
|
||||
) {
|
||||
return {
|
||||
data: { success: true, data: { theme_json_url: jsonUrl } },
|
||||
@@ -100,4 +102,29 @@ describe("cloud theme restoration", () => {
|
||||
[BSPLUS_PENDING_THEME_ENSURE_AFTER_CLOUD_KEY]: "catalog-id",
|
||||
});
|
||||
});
|
||||
|
||||
it("installs via admin preview endpoints with auth", async () => {
|
||||
const jsonUrl =
|
||||
"https://betterseqta.org/api/bsplus/admin/themes/t1/theme.json?source=community";
|
||||
(browser.runtime.sendMessage as jest.Mock).mockImplementation(async (msg) => {
|
||||
if (msg.type === "fetchFromUrl" && msg.url.includes("/preview?")) {
|
||||
return { data: { data: { theme_json_url: jsonUrl } } };
|
||||
}
|
||||
if (msg.type === "fetchFromUrl" && msg.url === jsonUrl && msg.auth === true) {
|
||||
return {
|
||||
data: { id: "t1", name: "Pending theme", CustomCSS: "body { color: green; }" },
|
||||
};
|
||||
}
|
||||
return { error: "unexpected" };
|
||||
});
|
||||
|
||||
const id = await ThemeManager.getInstance().previewAdminTheme({
|
||||
id: "t1",
|
||||
source: "community",
|
||||
});
|
||||
expect(id).toBe("t1");
|
||||
expect(await localforage.getItem("t1")).toMatchObject({
|
||||
installedFromCommunity: true,
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -12,6 +12,7 @@ import { fullMotionEffectsEnabled } from "@/seqta/utils/performanceMode";
|
||||
import debounce from "@/seqta/utils/debounce";
|
||||
import { themeUpdates } from "@/interface/hooks/ThemeUpdates";
|
||||
import { getApiBase } from "@/seqta/utils/DevApiBase";
|
||||
import { withBsplusApiQuery } from "@/seqta/utils/bsplusClientContext";
|
||||
import { isAllowedFetchUrl } from "@/seqta/utils/allowedFetchUrl";
|
||||
import { updateAllColors } from "@/seqta/ui/colors/Manager";
|
||||
import {
|
||||
@@ -592,10 +593,11 @@ export class ThemeManager {
|
||||
/**
|
||||
* Fetch JSON from a URL via background script (avoids CORS when running inside SEQTA page)
|
||||
*/
|
||||
private async fetchFromUrl(url: string): Promise<any> {
|
||||
private async fetchFromUrl(url: string, options?: { auth?: boolean }): Promise<any> {
|
||||
const result = (await browser.runtime.sendMessage({
|
||||
type: 'fetchFromUrl',
|
||||
url,
|
||||
auth: options?.auth === true,
|
||||
})) as { data?: unknown; error?: string };
|
||||
if (result?.error) throw new Error(result.error);
|
||||
return result?.data;
|
||||
@@ -637,6 +639,35 @@ export class ThemeManager {
|
||||
}
|
||||
}
|
||||
|
||||
public async previewAdminTheme(themeContent: {
|
||||
id: string;
|
||||
source: "marketplace" | "community";
|
||||
updated_at?: number;
|
||||
}): Promise<string> {
|
||||
if (!themeContent.id) throw new Error("Missing theme id");
|
||||
|
||||
const previewBody = (await this.fetchFromUrl(
|
||||
`${this.THEME_API_BASE}/bsplus/admin/themes/${themeContent.id}/preview?source=${themeContent.source}`,
|
||||
{ auth: true },
|
||||
)) as { data?: { theme_json_url?: string }; theme_json_url?: string };
|
||||
const themeJsonUrl = previewBody?.data?.theme_json_url ?? previewBody?.theme_json_url;
|
||||
if (!themeJsonUrl || !isAllowedFetchUrl(themeJsonUrl)) {
|
||||
throw new Error("Failed to get admin theme preview URL");
|
||||
}
|
||||
|
||||
const themeData = (await this.fetchFromUrl(themeJsonUrl, { auth: true })) as ThemeContent;
|
||||
const fromCommunity = themeContent.source === "community";
|
||||
await this.installTheme(
|
||||
{ ...themeData, id: themeContent.id },
|
||||
{
|
||||
fromStore: !fromCommunity,
|
||||
fromCommunity,
|
||||
serverUpdatedAtSec: themeContent.updated_at,
|
||||
},
|
||||
);
|
||||
return themeContent.id;
|
||||
}
|
||||
|
||||
private async downloadAndInstallCommunityTheme(themeContent: {
|
||||
id: string;
|
||||
theme_json_url?: string;
|
||||
@@ -649,8 +680,16 @@ export class ThemeManager {
|
||||
|
||||
let themeJsonUrl = themeContent.theme_json_url;
|
||||
if (!themeJsonUrl) {
|
||||
const { bsplus_token } = await browser.storage.local.get("bsplus_token");
|
||||
const auth =
|
||||
typeof bsplus_token === "string" && bsplus_token.length > 0
|
||||
? { auth: true as const }
|
||||
: undefined;
|
||||
const downloadData = (await this.fetchFromUrl(
|
||||
`${this.THEME_API_BASE}/custom-themes/${themeContent.id}/download`,
|
||||
await withBsplusApiQuery(
|
||||
`${this.THEME_API_BASE}/custom-themes/${encodeURIComponent(themeContent.id)}/download`,
|
||||
),
|
||||
auth,
|
||||
)) as { success?: boolean; data?: { theme_json_url: string } };
|
||||
if (!downloadData?.success || !downloadData?.data?.theme_json_url) {
|
||||
throw new Error("Failed to get community theme download URL");
|
||||
@@ -700,8 +739,16 @@ export class ThemeManager {
|
||||
let themeData: ThemeContent;
|
||||
|
||||
try {
|
||||
const { bsplus_token } = await browser.storage.local.get("bsplus_token");
|
||||
const auth =
|
||||
typeof bsplus_token === "string" && bsplus_token.length > 0
|
||||
? { auth: true as const }
|
||||
: undefined;
|
||||
const downloadData = (await this.fetchFromUrl(
|
||||
`${this.THEME_API_BASE}/themes/${themeContent.id}/download`,
|
||||
await withBsplusApiQuery(
|
||||
`${this.THEME_API_BASE}/themes/${encodeURIComponent(themeContent.id)}/download`,
|
||||
),
|
||||
auth,
|
||||
)) as { success?: boolean; data?: { theme_json_url: string } };
|
||||
if (!downloadData?.success || !downloadData?.data?.theme_json_url) {
|
||||
throw new Error("Failed to get theme download URL");
|
||||
|
||||
@@ -5,9 +5,11 @@
|
||||
import { loadSession } from "./rosterStore";
|
||||
import { openTimetableClassmatesOptInPopup } from "./openTimetableClassmatesPopup";
|
||||
import { runTimetableClassmatesSync } from "./syncOrchestrator";
|
||||
import { accountsAvailability } from "./accountsAvailability";
|
||||
|
||||
let rootEl = $state<HTMLDivElement | null>(null);
|
||||
let busy = $state(false);
|
||||
let error = $state("");
|
||||
|
||||
function syncTheme() {
|
||||
const host = rootEl?.closest(".bsplus-friends-sync-mount");
|
||||
@@ -15,16 +17,19 @@
|
||||
}
|
||||
|
||||
async function handleClick() {
|
||||
if (busy) return;
|
||||
const session = await loadSession();
|
||||
if (!session.syncOptIn) {
|
||||
openTimetableClassmatesOptInPopup({ onAccepted: () => {} });
|
||||
return;
|
||||
}
|
||||
|
||||
if (busy || !$accountsAvailability.available) return;
|
||||
error = "";
|
||||
busy = true;
|
||||
try {
|
||||
await runTimetableClassmatesSync();
|
||||
const session = await loadSession();
|
||||
if (!session.syncOptIn) {
|
||||
openTimetableClassmatesOptInPopup({ onAccepted: () => {} });
|
||||
return;
|
||||
}
|
||||
const result = await runTimetableClassmatesSync();
|
||||
if (!result.ok) error = result.error ?? "Sync failed";
|
||||
} catch (err) {
|
||||
error = err instanceof Error ? err.message : "Sync failed";
|
||||
} finally {
|
||||
busy = false;
|
||||
}
|
||||
@@ -59,14 +64,17 @@
|
||||
type="button"
|
||||
class="uiButton bsplus-cal-trigger"
|
||||
class:bsplus-cal-trigger--busy={busy}
|
||||
disabled={busy}
|
||||
disabled={busy || !$accountsAvailability.available}
|
||||
aria-busy={busy}
|
||||
aria-label="Sync with Friends"
|
||||
aria-label={error || $accountsAvailability.message || "Sync with Friends"}
|
||||
title={error || $accountsAvailability.message || "Sync with Friends"}
|
||||
onclick={() => void handleClick()}
|
||||
>
|
||||
<span class="bsplus-cal-trigger-content">
|
||||
<span class="bsplus-cal-trigger-icon iconFamily" aria-hidden="true"></span>
|
||||
<span class="bsplus-cal-trigger-text">Sync with Friends</span>
|
||||
<span class="bsplus-cal-trigger-text">
|
||||
{busy ? "Syncing…" : error ? "Sync failed" : "Sync with Friends"}
|
||||
</span>
|
||||
</span>
|
||||
</button>
|
||||
</div>
|
||||
@@ -5,6 +5,7 @@
|
||||
import { ACCOUNTS_BASE } from "./constants";
|
||||
import { markResumeOptInAfterCloudLogin } from "./optInResume";
|
||||
import { registerOptIn } from "./syncOrchestrator";
|
||||
import { accountsAvailability } from "./accountsAvailability";
|
||||
|
||||
interface Props {
|
||||
onAccepted: () => void | Promise<void>;
|
||||
@@ -48,7 +49,7 @@
|
||||
return null;
|
||||
}
|
||||
|
||||
const canSubmit = $derived(agreeShare && agreeJoin && cloudLoggedIn && !busy);
|
||||
const canSubmit = $derived(agreeShare && agreeJoin && cloudLoggedIn && !busy && $accountsAvailability.available);
|
||||
const checksDisabled = $derived(busy || !cloudLoggedIn);
|
||||
|
||||
async function signInWithCloud() {
|
||||
@@ -113,7 +114,7 @@
|
||||
<button
|
||||
type="button"
|
||||
class="bsplus-cal-btn bsplus-cal-btn--primary bsplus-tc-cloud-signin"
|
||||
disabled={busy}
|
||||
disabled={busy || !$accountsAvailability.available}
|
||||
onclick={() => void signInWithCloud()}
|
||||
>
|
||||
Sign in with Cloud
|
||||
@@ -154,6 +155,10 @@
|
||||
<p class="bsplus-tc-error">{error}</p>
|
||||
{/if}
|
||||
|
||||
{#if $accountsAvailability.message}
|
||||
<p class="bsplus-tc-error" role="status">{$accountsAvailability.message}</p>
|
||||
{/if}
|
||||
|
||||
<div class="bsplus-tc-actions">
|
||||
<button
|
||||
type="button"
|
||||
|
||||
@@ -4,13 +4,12 @@
|
||||
import { closeExtensionPopup } from "@/seqta/utils/Closers/closeExtensionPopup";
|
||||
import { runTimetableClassmatesSync } from "./syncOrchestrator";
|
||||
import { loadSession, resolveClassmatesScope } from "./rosterStore";
|
||||
import { pluginSettingsStore } from "@/interface/pages/settings/pluginSettingsState.svelte";
|
||||
import { accountsAvailability } from "./accountsAvailability";
|
||||
import {
|
||||
openTimetableClassmatesOptInPopup,
|
||||
openTimetableClassmatesOptOutPopup,
|
||||
} from "./openTimetableClassmatesPopup";
|
||||
|
||||
const PLUGIN_ID = "timetable-classmates";
|
||||
const SETTINGS_CLOSE_MS = 320;
|
||||
|
||||
let busy = $state(false);
|
||||
@@ -46,10 +45,7 @@
|
||||
error = "";
|
||||
afterSettingsClosed(() => {
|
||||
openTimetableClassmatesOptInPopup({
|
||||
onAccepted: async () => {
|
||||
await pluginSettingsStore.update(PLUGIN_ID, "enabled", true);
|
||||
await refreshStatus();
|
||||
},
|
||||
onAccepted: () => refreshStatus(),
|
||||
});
|
||||
});
|
||||
}
|
||||
@@ -78,34 +74,33 @@
|
||||
}
|
||||
</script>
|
||||
|
||||
<div class="flex flex-col items-end gap-2 shrink-0 max-w-[14rem]">
|
||||
<p class="text-xs text-right text-zinc-500 dark:text-zinc-400">{scopeLabel}</p>
|
||||
|
||||
<div class="flex flex-col items-end gap-2 shrink-0 max-w-[14rem]" title={scopeLabel}>
|
||||
{#if syncOptIn}
|
||||
<p class="text-xs font-medium text-green-600 dark:text-green-400">Opted in on this site</p>
|
||||
<div class="flex flex-wrap gap-2 justify-end">
|
||||
<Button text="Sync now" onClick={() => void syncNow()} disabled={busy} />
|
||||
<button
|
||||
type="button"
|
||||
class="px-3 py-1.5 text-[0.75rem] rounded-lg text-red-600 dark:text-red-400 hover:bg-zinc-200/80 dark:hover:bg-zinc-700/50 disabled:opacity-50 transition-colors duration-200"
|
||||
disabled={busy}
|
||||
onclick={startOptOut}
|
||||
>
|
||||
Opt out…
|
||||
</button>
|
||||
</div>
|
||||
{:else}
|
||||
<p class="text-xs text-right text-zinc-500 dark:text-zinc-400">
|
||||
{cloudAuth.state.isLoggedIn
|
||||
? "Not sharing yet"
|
||||
: "Sign in to Cloud in the opt-in guide"}
|
||||
{cloudAuth.state.isLoggedIn ? "Not sharing yet" : "Sign in to Cloud first"}
|
||||
</p>
|
||||
<Button text="Opt in…" onClick={startOptIn} disabled={busy} />
|
||||
{/if}
|
||||
|
||||
{#if status}
|
||||
<p class="text-xs text-right text-zinc-500 dark:text-zinc-400">{status}</p>
|
||||
{/if}
|
||||
|
||||
{#if syncOptIn}
|
||||
<div class="flex flex-wrap gap-2 justify-end">
|
||||
<Button text="Sync now" onClick={() => void syncNow()} disabled={busy || !$accountsAvailability.available} />
|
||||
<Button variant="ghost" class="text-red-600 dark:text-red-400" text="Opt out…" onClick={startOptOut} disabled={busy} />
|
||||
</div>
|
||||
{:else}
|
||||
<Button text="Opt in…" onClick={startOptIn} disabled={busy || !$accountsAvailability.available} />
|
||||
{/if}
|
||||
|
||||
{#if $accountsAvailability.message}
|
||||
<p class="text-xs text-right text-zinc-500 dark:text-zinc-400" role="status">
|
||||
{$accountsAvailability.message}
|
||||
</p>
|
||||
{/if}
|
||||
|
||||
{#if error}
|
||||
<p class="text-xs text-right text-red-500">{error}</p>
|
||||
{/if}
|
||||
|
||||
@@ -0,0 +1,41 @@
|
||||
import { readable } from "svelte/store";
|
||||
import { ACCOUNTS_BASE } from "./constants";
|
||||
|
||||
export const accountsAvailability = readable(
|
||||
{ available: false, message: "Checking BetterSEQTA Cloud…" },
|
||||
(set) => {
|
||||
let checking = false;
|
||||
let stopped = false;
|
||||
async function check() {
|
||||
if (checking) return;
|
||||
checking = true;
|
||||
let available = false;
|
||||
try {
|
||||
const response = await fetch(`${ACCOUNTS_BASE}/api/health`, {
|
||||
cache: "no-store",
|
||||
credentials: "omit",
|
||||
signal: AbortSignal.timeout(5_000),
|
||||
});
|
||||
const health = await response.json();
|
||||
available = response.ok && health?.ok === true && health?.service === "accounts";
|
||||
} catch {
|
||||
/* Network errors and timeouts leave the service unavailable. */
|
||||
}
|
||||
checking = false;
|
||||
if (stopped) return;
|
||||
set({
|
||||
available,
|
||||
message: available ? "" : "BetterSEQTA Cloud is unavailable. Retrying automatically.",
|
||||
});
|
||||
}
|
||||
|
||||
void check();
|
||||
const timer = window.setInterval(check, 60_000);
|
||||
window.addEventListener("online", check);
|
||||
return () => {
|
||||
stopped = true;
|
||||
window.clearInterval(timer);
|
||||
window.removeEventListener("online", check);
|
||||
};
|
||||
},
|
||||
);
|
||||
@@ -5,11 +5,26 @@ import type { ArchivedMembers, ClassRosterIndex } from "./rosterMerge";
|
||||
import { rosterPeersForClass } from "./rosterMerge";
|
||||
import type { PeopleCache } from "./rosterStore";
|
||||
import { displayNameForSeqtaId } from "./peopleCache";
|
||||
import { classRosterKey } from "./classKeys";
|
||||
import { openClassmatesRosterPopup } from "./openTimetableClassmatesPopup";
|
||||
|
||||
const STACK = "bsplus-classmate-stack";
|
||||
const AVATAR = "bsplus-classmate-avatar";
|
||||
|
||||
/** Learn home `#day-container` tiles expose these attributes on class lessons. */
|
||||
export function classKeyForHomeDay(el: HTMLElement): string | null {
|
||||
if (!el.hasAttribute("data-bsplus-meta-id") && !el.hasAttribute("data-bsplus-code")) {
|
||||
return null;
|
||||
}
|
||||
const meta = parseInt(el.getAttribute("data-bsplus-meta-id") ?? "", 10);
|
||||
const programme = parseInt(el.getAttribute("data-bsplus-programme-id") ?? "", 10);
|
||||
return classRosterKey({
|
||||
metaID: Number.isNaN(meta) ? undefined : meta,
|
||||
code: el.getAttribute("data-bsplus-code")?.trim() || undefined,
|
||||
programmeID: Number.isNaN(programme) ? undefined : programme,
|
||||
});
|
||||
}
|
||||
|
||||
export function isClassmatesPluginMutation(record: MutationRecord): boolean {
|
||||
const inStack = (el: Element | null) => Boolean(el?.closest(`.${STACK}`));
|
||||
if (record.target instanceof Element && inStack(record.target)) return true;
|
||||
@@ -28,7 +43,8 @@ function avatarColumnWidth(host: HTMLElement): number {
|
||||
const scope =
|
||||
(host.classList.contains("entry") ? host : host.closest(".timetablepage .entry.class")) ??
|
||||
host.closest(".timetablepage .quickbar .meta") ??
|
||||
host.closest(".timetablepage .days tbody td");
|
||||
host.closest(".timetablepage .days tbody td") ??
|
||||
host.closest("#day-container .day");
|
||||
if (!(scope instanceof HTMLElement)) return 0;
|
||||
const w = scope.getBoundingClientRect().width;
|
||||
return w > 0 ? w * 0.5 : 0;
|
||||
@@ -165,7 +181,10 @@ export async function renderClassmateStackForEntry(
|
||||
if (existing?.dataset.bsplusPeers === signature) return;
|
||||
existing?.remove();
|
||||
|
||||
const classTitle = entry.querySelector(".title")?.textContent?.trim() ?? "";
|
||||
const classTitle =
|
||||
entry.querySelector(".title")?.textContent?.trim() ??
|
||||
entry.querySelector("h2")?.textContent?.trim() ??
|
||||
"";
|
||||
const stack = document.createElement("div");
|
||||
stack.className = STACK;
|
||||
stack.dataset.bsplusPeers = signature;
|
||||
|
||||
@@ -5,6 +5,7 @@ import { isPluginBlockedByPerformanceMode } from "@/seqta/utils/performanceMode"
|
||||
import { timetableClassmatesSettings } from "./settings";
|
||||
import styles from "./styles.css?inline";
|
||||
import {
|
||||
classKeyForHomeDay,
|
||||
classKeyFromCi,
|
||||
findClassEntryByTitle,
|
||||
isClassmatesPluginMutation,
|
||||
@@ -24,7 +25,10 @@ import { resolveStudentId } from "./seqtaClient";
|
||||
import { peerCloudIdsForPaint } from "./accountsClient";
|
||||
import { fetchSchoolYearEnrollmentSnapshot } from "./timetableYearSnapshot";
|
||||
import { CLASSMATES_TIMETABLE_POLL_MS } from "./constants";
|
||||
import { scheduleClassmatesSyncIfNeeded } from "./syncOrchestrator";
|
||||
import {
|
||||
bindClassmatesOptInActivated,
|
||||
scheduleClassmatesSyncIfNeeded,
|
||||
} from "./syncOrchestrator";
|
||||
import {
|
||||
mountClassmatesToolbarChip,
|
||||
unmountClassmatesToolbarChip,
|
||||
@@ -51,7 +55,7 @@ const timetableClassmatesPlugin: Plugin<typeof timetableClassmatesSettings> = {
|
||||
};
|
||||
browser.runtime.onMessage.addListener(onSyncMessage);
|
||||
|
||||
let gridObserver: MutationObserver | null = null;
|
||||
let domObserver: MutationObserver | null = null;
|
||||
let resizeObserver: ResizeObserver | null = null;
|
||||
let paintTimer: ReturnType<typeof setTimeout> | null = null;
|
||||
let pollTimer: ReturnType<typeof setInterval> | null = null;
|
||||
@@ -59,10 +63,35 @@ const timetableClassmatesPlugin: Plugin<typeof timetableClassmatesSettings> = {
|
||||
|
||||
const schedulePaint = () => {
|
||||
if (paintTimer) clearTimeout(paintTimer);
|
||||
paintTimer = setTimeout(() => void paintTimetable(), 120);
|
||||
paintTimer = setTimeout(() => void paintStacks(), 120);
|
||||
};
|
||||
|
||||
const paintTimetable = async () => {
|
||||
const startTimetablePoll = () => {
|
||||
if (pollTimer) return;
|
||||
scheduleClassmatesSyncIfNeeded(true);
|
||||
pollTimer = setInterval(() => scheduleClassmatesSyncIfNeeded(), CLASSMATES_TIMETABLE_POLL_MS);
|
||||
};
|
||||
|
||||
const armSyncIfOptedIn = async () => {
|
||||
if (!(await loadSession()).syncOptIn) return;
|
||||
void ensureCiToClassKey(() => fetchSchoolYearEnrollmentSnapshot()).catch(() => {});
|
||||
startTimetablePoll();
|
||||
};
|
||||
|
||||
bindClassmatesOptInActivated(() => {
|
||||
if (document.querySelector(".timetablepage")) void armSyncIfOptedIn();
|
||||
schedulePaint();
|
||||
});
|
||||
|
||||
const watchRepaint = (root: Element) => {
|
||||
domObserver ??= new MutationObserver((mutations) => {
|
||||
if (mutations.every(isClassmatesPluginMutation)) return;
|
||||
schedulePaint();
|
||||
});
|
||||
domObserver.observe(root, { childList: true, subtree: true });
|
||||
};
|
||||
|
||||
const paintStacks = async () => {
|
||||
if (painting) return;
|
||||
painting = true;
|
||||
try {
|
||||
@@ -72,9 +101,6 @@ const timetableClassmatesPlugin: Plugin<typeof timetableClassmatesSettings> = {
|
||||
return;
|
||||
}
|
||||
|
||||
const page = document.querySelector(".timetablepage");
|
||||
if (!page) return;
|
||||
|
||||
const selfId = await resolveStudentId();
|
||||
if (selfId == null) return;
|
||||
|
||||
@@ -86,10 +112,10 @@ const timetableClassmatesPlugin: Plugin<typeof timetableClassmatesSettings> = {
|
||||
peerCloudIdsForPaint(),
|
||||
]);
|
||||
|
||||
const paintHost = (host: HTMLElement, ci: number | null) =>
|
||||
const paintHost = (host: HTMLElement, classKey: string | null) =>
|
||||
renderClassmateStackForEntry(
|
||||
host,
|
||||
classKeyFromCi(ci, ciMap),
|
||||
classKey,
|
||||
roster,
|
||||
peopleCache,
|
||||
selfId,
|
||||
@@ -102,29 +128,34 @@ const timetableClassmatesPlugin: Plugin<typeof timetableClassmatesSettings> = {
|
||||
return Number.isNaN(ci) ? null : ci;
|
||||
};
|
||||
|
||||
const paints = [...page.querySelectorAll(".entry.class")].map((entry) =>
|
||||
paintHost(entry as HTMLElement, ciOf(entry)),
|
||||
);
|
||||
|
||||
const quickbar = page.querySelector(".quickbar.visible[data-type='class']");
|
||||
if (quickbar) {
|
||||
const title = quickbar.querySelector(".title")?.textContent?.trim() ?? "";
|
||||
const host =
|
||||
(quickbar.querySelector(".meta") as HTMLElement | null) ?? (quickbar as HTMLElement);
|
||||
paints.push(paintHost(host, ciOf(findClassEntryByTitle(page, title))));
|
||||
const paints: Promise<void>[] = [];
|
||||
const page = document.querySelector(".timetablepage");
|
||||
if (page) {
|
||||
paints.push(
|
||||
...[...page.querySelectorAll(".entry.class")].map((entry) =>
|
||||
paintHost(entry as HTMLElement, classKeyFromCi(ciOf(entry), ciMap)),
|
||||
),
|
||||
);
|
||||
const quickbar = page.querySelector(".quickbar.visible[data-type='class']");
|
||||
if (quickbar) {
|
||||
const title = quickbar.querySelector(".title")?.textContent?.trim() ?? "";
|
||||
const host =
|
||||
(quickbar.querySelector(".meta") as HTMLElement | null) ?? (quickbar as HTMLElement);
|
||||
paints.push(paintHost(host, ciOf(findClassEntryByTitle(page, title))));
|
||||
}
|
||||
}
|
||||
|
||||
const homeDays = document.querySelectorAll<HTMLElement>("#day-container .day[data-bsplus-meta-id]");
|
||||
for (const day of homeDays) {
|
||||
paints.push(paintHost(day, classKeyForHomeDay(day)));
|
||||
}
|
||||
|
||||
await Promise.all(paints);
|
||||
} finally {
|
||||
painting = false;
|
||||
}
|
||||
};
|
||||
|
||||
const startTimetablePoll = () => {
|
||||
if (pollTimer) return;
|
||||
scheduleClassmatesSyncIfNeeded();
|
||||
pollTimer = setInterval(() => scheduleClassmatesSyncIfNeeded(), CLASSMATES_TIMETABLE_POLL_MS);
|
||||
};
|
||||
|
||||
const handleTimetablePage = async () => {
|
||||
try {
|
||||
await waitForElm(".timetablepage .entry.class", true, 50, 300);
|
||||
@@ -133,49 +164,63 @@ const timetableClassmatesPlugin: Plugin<typeof timetableClassmatesSettings> = {
|
||||
}
|
||||
|
||||
const page = document.querySelector(".timetablepage");
|
||||
if ((await loadSession()).syncOptIn) {
|
||||
void ensureCiToClassKey(() => fetchSchoolYearEnrollmentSnapshot()).catch(() => {});
|
||||
startTimetablePoll();
|
||||
}
|
||||
|
||||
await armSyncIfOptedIn();
|
||||
schedulePaint();
|
||||
await paintTimetable();
|
||||
void mountClassmatesToolbarChip();
|
||||
|
||||
if (page && !gridObserver) {
|
||||
gridObserver = new MutationObserver((mutations) => {
|
||||
if (mutations.every(isClassmatesPluginMutation)) return;
|
||||
schedulePaint();
|
||||
});
|
||||
gridObserver.observe(page, { childList: true, subtree: true });
|
||||
|
||||
resizeObserver = new ResizeObserver(() => schedulePaint());
|
||||
if (page) {
|
||||
watchRepaint(page);
|
||||
resizeObserver ??= new ResizeObserver(() => schedulePaint());
|
||||
resizeObserver.observe(page);
|
||||
}
|
||||
};
|
||||
|
||||
const handleHomePage = async () => {
|
||||
const container = document.getElementById("day-container");
|
||||
if (!container) return;
|
||||
try {
|
||||
await waitForElm("#day-container .day", true, 50, 200);
|
||||
} catch {
|
||||
/* empty day */
|
||||
}
|
||||
watchRepaint(container);
|
||||
schedulePaint();
|
||||
};
|
||||
|
||||
const onUpdated = () => schedulePaint();
|
||||
window.addEventListener(CLASSMATES_UPDATED_EVENT, onUpdated);
|
||||
|
||||
const onClassEntryClick = (e: Event) => {
|
||||
if ((e.target as HTMLElement).closest?.(".timetablepage .entry.class")) schedulePaint();
|
||||
const onRepaintClick = (e: Event) => {
|
||||
if (
|
||||
(e.target as HTMLElement).closest?.(
|
||||
".timetablepage .entry.class, #day-container .day",
|
||||
)
|
||||
) {
|
||||
schedulePaint();
|
||||
}
|
||||
};
|
||||
document.addEventListener("click", onClassEntryClick, true);
|
||||
document.addEventListener("click", onRepaintClick, true);
|
||||
|
||||
const { unregister: unregisterEnabled } = api.settings.onChange("enabled", schedulePaint);
|
||||
const { unregister: unregisterTimetable } = api.seqta.onMount(".timetablepage", handleTimetablePage);
|
||||
const { unregister: unregisterHome } = api.seqta.onMount("#home-container", handleHomePage);
|
||||
|
||||
const { unregister } = api.seqta.onMount(".timetablepage", handleTimetablePage);
|
||||
if ((await loadSession()).syncOptIn) scheduleClassmatesSyncIfNeeded();
|
||||
if ((await loadSession()).syncOptIn) {
|
||||
scheduleClassmatesSyncIfNeeded();
|
||||
if (document.querySelector(".timetablepage")) startTimetablePoll();
|
||||
}
|
||||
|
||||
return () => {
|
||||
unregister();
|
||||
unregisterTimetable();
|
||||
unregisterHome();
|
||||
bindClassmatesOptInActivated(null);
|
||||
browser.runtime.onMessage.removeListener(onSyncMessage);
|
||||
gridObserver?.disconnect();
|
||||
domObserver?.disconnect();
|
||||
resizeObserver?.disconnect();
|
||||
if (paintTimer) clearTimeout(paintTimer);
|
||||
if (pollTimer) clearInterval(pollTimer);
|
||||
window.removeEventListener(CLASSMATES_UPDATED_EVENT, onUpdated);
|
||||
document.removeEventListener("click", onClassEntryClick, true);
|
||||
document.removeEventListener("click", onRepaintClick, true);
|
||||
unregisterEnabled();
|
||||
removeClassmateStacks();
|
||||
unmountClassmatesToolbarChip();
|
||||
|
||||
@@ -14,7 +14,7 @@ import {
|
||||
|
||||
const STYLE_ID = "bsplus-timetable-classmates-popup-styles";
|
||||
const CLASSMATES_VIDEO_URL =
|
||||
"https://raw.githubusercontent.com/BetterSEQTA/BetterSEQTA-Plus/main/src/resources/timetable-classmates-video.webm";
|
||||
"https://raw.githubusercontent.com/BetterSEQTA/BetterSEQTA-Plus/refs/heads/main/src/resources/timetable-classmates.webm";
|
||||
|
||||
function ensurePopupStyles(): void {
|
||||
if (document.getElementById(STYLE_ID)) return;
|
||||
@@ -26,6 +26,8 @@ function ensurePopupStyles(): void {
|
||||
|
||||
type ConsentPopupOptions = {
|
||||
onDismiss?: () => void;
|
||||
/** Fires once the popup shell is ready (Svelte mounted). */
|
||||
onOpened?: () => void;
|
||||
heroVideo?: boolean;
|
||||
};
|
||||
|
||||
@@ -76,6 +78,7 @@ function openConsentPopup(
|
||||
},
|
||||
},
|
||||
});
|
||||
options?.onOpened?.();
|
||||
},
|
||||
});
|
||||
}
|
||||
@@ -83,22 +86,17 @@ function openConsentPopup(
|
||||
export function openTimetableClassmatesOptInPopup(options: {
|
||||
onAccepted: () => void | Promise<void>;
|
||||
onDismiss?: () => void;
|
||||
/** Clears post–cloud-login resume flag as soon as the modal is shown (one-shot reopen). */
|
||||
onOpened?: () => void;
|
||||
}): void {
|
||||
openConsentPopup(
|
||||
"Timetable classmates",
|
||||
"Share class lists with opted-in students at your school",
|
||||
TimetableClassmatesOptInPopup,
|
||||
{ onAccepted: options.onAccepted },
|
||||
{
|
||||
onAccepted: async () => {
|
||||
clearResumeOptInAfterCloudLogin();
|
||||
await options.onAccepted();
|
||||
},
|
||||
},
|
||||
{
|
||||
onDismiss: () => {
|
||||
clearResumeOptInAfterCloudLogin();
|
||||
options.onDismiss?.();
|
||||
},
|
||||
onDismiss: options.onDismiss,
|
||||
onOpened: options.onOpened,
|
||||
heroVideo: true,
|
||||
},
|
||||
);
|
||||
@@ -117,7 +115,10 @@ async function openResumeOptInIfNeeded(): Promise<void> {
|
||||
return;
|
||||
}
|
||||
|
||||
openTimetableClassmatesOptInPopup({ onAccepted: () => {} });
|
||||
openTimetableClassmatesOptInPopup({
|
||||
onAccepted: () => {},
|
||||
onOpened: () => clearResumeOptInAfterCloudLogin(),
|
||||
});
|
||||
}
|
||||
|
||||
/** After cloud OAuth refreshes the page, reopen opt-in if the user started sign-in from this flow. */
|
||||
|
||||
@@ -52,6 +52,26 @@
|
||||
position: relative;
|
||||
}
|
||||
|
||||
.day-container .day:has(> .bsplus-classmate-stack) {
|
||||
display: grid;
|
||||
grid-template-columns: minmax(0, 1fr) minmax(0, auto);
|
||||
align-items: start;
|
||||
column-gap: 4px;
|
||||
}
|
||||
|
||||
.day-container .day:has(> .bsplus-classmate-stack) > :not(.bsplus-classmate-stack) {
|
||||
grid-column: 1;
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.day-container .day:has(> .bsplus-classmate-stack) > .bsplus-classmate-stack {
|
||||
grid-column: 2;
|
||||
grid-row: 1 / -1;
|
||||
align-self: start;
|
||||
justify-self: end;
|
||||
margin: 2px 4px 0 0;
|
||||
}
|
||||
|
||||
.bsplus-classmate-avatar {
|
||||
width: 20px;
|
||||
height: 20px;
|
||||
|
||||
@@ -43,12 +43,19 @@ import { buildSharePayload } from "./relayPayload";
|
||||
import { runRelayRoundTrip, sendRelayRevoke, type RelaySnapshotShare } from "./relayClient";
|
||||
import type { ClassRef } from "./classKeys";
|
||||
import { CLASSMATES_PEER_REFRESH_MS } from "./constants";
|
||||
import { pluginSettingsStore } from "@/interface/pages/settings/pluginSettingsState.svelte";
|
||||
|
||||
const HEARTBEAT_MIN_MS = 15 * 60 * 1000;
|
||||
const PLUGIN_ID = "timetable-classmates";
|
||||
|
||||
export type SyncRunResult = { ok: boolean; error?: string; peers?: number };
|
||||
|
||||
let syncChain: Promise<void> = Promise.resolve();
|
||||
let onOptInActivated: (() => void) | null = null;
|
||||
|
||||
export function bindClassmatesOptInActivated(fn: (() => void) | null): void {
|
||||
onOptInActivated = fn;
|
||||
}
|
||||
|
||||
export function scheduleClassmatesSyncIfNeeded(force = false): void {
|
||||
syncChain = syncChain
|
||||
@@ -100,6 +107,8 @@ export async function registerOptIn(): Promise<{ ok: boolean; error?: string }>
|
||||
if (scope) await setScopeSyncOptIn(scope, true);
|
||||
await patchSession({ syncOptIn: true, showAvatars: true });
|
||||
const sync = await runTimetableClassmatesSync();
|
||||
await pluginSettingsStore.update(PLUGIN_ID, "enabled", true);
|
||||
onOptInActivated?.();
|
||||
if (!sync.ok) {
|
||||
return { ok: true, error: sync.error ?? "Opt-in saved but initial sync failed." };
|
||||
}
|
||||
|
||||
@@ -13,6 +13,11 @@ import { createPluginAPI } from "./createAPI";
|
||||
import browser from "webextension-polyfill";
|
||||
import { settingsState } from "@/seqta/utils/listeners/SettingsState";
|
||||
import { verboseInfo } from "@/utils/verboseLog";
|
||||
import { isRemotePluginStartAllowed } from "@/seqta/utils/remoteConfig/runtime";
|
||||
import {
|
||||
isRemoteRouteEnhancementsStripped,
|
||||
ROUTE_STRIP_KEEP_PLUGINS,
|
||||
} from "@/seqta/utils/remoteConfig/routeGate";
|
||||
import { isPluginAllowedInPerformanceMode } from "@/seqta/utils/performanceMode";
|
||||
|
||||
interface PluginSettingsStorage {
|
||||
@@ -241,6 +246,15 @@ export class PluginManager {
|
||||
if (settingsState.onoff === false || !isPluginAllowedInPerformanceMode(plugin.id)) {
|
||||
return false;
|
||||
}
|
||||
if (!isRemotePluginStartAllowed(plugin.id)) {
|
||||
return false;
|
||||
}
|
||||
if (
|
||||
isRemoteRouteEnhancementsStripped() &&
|
||||
!ROUTE_STRIP_KEEP_PLUGINS.has(plugin.id)
|
||||
) {
|
||||
return false;
|
||||
}
|
||||
if (!plugin.disableToggle) return true;
|
||||
const all = settingsState.getAll() as unknown as Record<string, unknown>;
|
||||
const stored = all[`plugin.${plugin.id}.settings`] as PluginSettingsStorage | undefined;
|
||||
@@ -336,6 +350,13 @@ export class PluginManager {
|
||||
Array.from(this.plugins.keys()).forEach((id) => this.stopPlugin(id));
|
||||
}
|
||||
|
||||
public async stopPluginsExcept(keepIds: ReadonlySet<string>): Promise<void> {
|
||||
const stops = Array.from(this.plugins.keys())
|
||||
.filter((id) => !keepIds.has(id))
|
||||
.map((id) => this.stopPlugin(id));
|
||||
await Promise.allSettled(stops);
|
||||
}
|
||||
|
||||
/**
|
||||
* Retrieves a registered plugin by its ID.
|
||||
*
|
||||
|
||||
+20
-11
@@ -209,12 +209,8 @@ function SortMessagePageItems(messagesParentElement: any) {
|
||||
|
||||
async function LoadPageElements(): Promise<void> {
|
||||
await AddBetterSEQTAElements();
|
||||
void import("@/seqta/ui/sidebar/applyNativeSidebar").then((mod) => {
|
||||
void mod.applyNativeSidebar();
|
||||
});
|
||||
void import("@/seqta/ui/titlebar/mountCustomTitleBar").then((mod) => {
|
||||
void mod.mountCustomTitleBar();
|
||||
});
|
||||
const { syncRouteEnhancementChrome } = await import("@/seqta/utils/remoteConfig/routeGate");
|
||||
await syncRouteEnhancementChrome();
|
||||
const sublink: string | undefined = getEngageRoutePage();
|
||||
|
||||
if (isSeqtaEngageExperience() && !engageHashListenerAttached) {
|
||||
@@ -748,11 +744,16 @@ export function init() {
|
||||
// Learn only: apply sidebar CSS vars early; Engage keeps its native React menu.
|
||||
if (!onLogin && !isSeqtaEngageExperience()) {
|
||||
document.documentElement.classList.add("bsplus-custom-title-pending");
|
||||
void import("@/seqta/ui/sidebar/applyNativeSidebar").then((mod) => {
|
||||
mod.prepareNativeSidebarEarly();
|
||||
});
|
||||
void import("@/seqta/ui/titlebar/mountCustomTitleBar").then((mod) => {
|
||||
mod.prepareCustomTitleBarEarly();
|
||||
void import("@/seqta/utils/remoteConfig/routeGate").then(async (gate) => {
|
||||
if (gate.isRemoteRouteEnhancementsStripped()) return;
|
||||
if (gate.remoteChromeGateAllowed("ui.sidebar.styled")) {
|
||||
const mod = await import("@/seqta/ui/sidebar/applyNativeSidebar");
|
||||
mod.prepareNativeSidebarEarly();
|
||||
}
|
||||
if (gate.remoteChromeGateAllowed("ui.titlebar.custom")) {
|
||||
const mod = await import("@/seqta/ui/titlebar/mountCustomTitleBar");
|
||||
mod.prepareCustomTitleBarEarly();
|
||||
}
|
||||
});
|
||||
} else {
|
||||
document.documentElement.classList.remove("bsplus-custom-title-pending");
|
||||
@@ -778,7 +779,15 @@ export function init() {
|
||||
});
|
||||
|
||||
let hashColorTimer: ReturnType<typeof setTimeout> | null = null;
|
||||
let routeChromeTimer: ReturnType<typeof setTimeout> | null = null;
|
||||
window.addEventListener("hashchange", () => {
|
||||
if (routeChromeTimer) clearTimeout(routeChromeTimer);
|
||||
routeChromeTimer = setTimeout(() => {
|
||||
routeChromeTimer = null;
|
||||
void import("@/seqta/utils/remoteConfig/routeGate").then((m) =>
|
||||
m.syncRouteEnhancementChrome(),
|
||||
);
|
||||
}, 120);
|
||||
if (!settingsState.adaptiveThemeColour) return;
|
||||
if (hashColorTimer) clearTimeout(hashColorTimer);
|
||||
hashColorTimer = setTimeout(() => {
|
||||
|
||||
@@ -0,0 +1,83 @@
|
||||
/* Maintainer note: page-context YouTube IFrame API for theme toggle easter egg. */
|
||||
(function () {
|
||||
if (window.__bsplusThemeSurprisePage) return;
|
||||
window.__bsplusThemeSurprisePage = true;
|
||||
|
||||
var MESSAGE_SOURCE = "betterseqta-theme-surprise";
|
||||
var ytPlayer = null;
|
||||
var apiReady = false;
|
||||
var pendingMountId = null;
|
||||
|
||||
window.onYouTubeIframeAPIReady = function () {
|
||||
apiReady = true;
|
||||
if (pendingMountId) {
|
||||
var mountId = pendingMountId;
|
||||
pendingMountId = null;
|
||||
openPlayer(mountId);
|
||||
}
|
||||
};
|
||||
|
||||
if (
|
||||
!document.querySelector('script[src="https://www.youtube.com/iframe_api"]')
|
||||
) {
|
||||
var apiScript = document.createElement("script");
|
||||
apiScript.src = "https://www.youtube.com/iframe_api";
|
||||
(document.head || document.documentElement).appendChild(apiScript);
|
||||
}
|
||||
|
||||
function openPlayer(mountId) {
|
||||
if (!apiReady) {
|
||||
pendingMountId = mountId;
|
||||
return;
|
||||
}
|
||||
|
||||
if (ytPlayer) {
|
||||
ytPlayer.playVideo();
|
||||
ytPlayer.unMute();
|
||||
return;
|
||||
}
|
||||
|
||||
ytPlayer = new YT.Player(mountId, {
|
||||
height: "360",
|
||||
width: "640",
|
||||
videoId: "dQw4w9WgXcQ",
|
||||
playerVars: {
|
||||
autoplay: 1,
|
||||
rel: 0,
|
||||
origin: window.location.origin,
|
||||
},
|
||||
events: {
|
||||
onReady: function (event) {
|
||||
event.target.unMute();
|
||||
event.target.playVideo();
|
||||
},
|
||||
onError: function (event) {
|
||||
console.warn(
|
||||
"[BetterSEQTA+] Theme toggle surprise YouTube error:",
|
||||
event.data,
|
||||
);
|
||||
},
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
window.addEventListener("message", function (event) {
|
||||
if (event.source !== window || !event.data) return;
|
||||
if (event.data.source !== MESSAGE_SOURCE) return;
|
||||
|
||||
if (event.data.type === "open" && event.data.mountId) {
|
||||
openPlayer(event.data.mountId);
|
||||
return;
|
||||
}
|
||||
|
||||
if (event.data.type === "close") {
|
||||
try {
|
||||
if (ytPlayer && ytPlayer.destroy) {
|
||||
ytPlayer.destroy();
|
||||
}
|
||||
} catch (error) {}
|
||||
ytPlayer = null;
|
||||
pendingMountId = null;
|
||||
}
|
||||
});
|
||||
})();
|
||||
Binary file not shown.
Binary file not shown.
@@ -14,10 +14,17 @@ import stringToHTML from "@/seqta/utils/stringToHTML";
|
||||
import { settingsState } from "@/seqta/utils/listeners/SettingsState";
|
||||
import { updateAllColors } from "./colors/Manager";
|
||||
import { delay } from "@/seqta/utils/delay";
|
||||
import {
|
||||
ensureThemeToggleSurprisePageScript,
|
||||
openThemeToggleSurprise,
|
||||
THEME_TOGGLE_SURPRISE_TRIGGER_AT,
|
||||
} from "@/seqta/utils/Openers/openThemeToggleSurprise";
|
||||
import { LUCIDE_MOON_ICON_SVG } from "@/lib/icons/lucideMoon";
|
||||
import { LUCIDE_SUN_ICON_SVG } from "@/lib/icons/lucideSun";
|
||||
import { ensureTitlebarFounderBadgeMounted, refreshTitlebarFounderBadge } from "@/seqta/ui/founderBadge/mountTitlebarFounderBadge";
|
||||
import { isPerformanceMode } from "@/seqta/utils/performanceMode";
|
||||
import { checkRemoteFeature } from "@/seqta/utils/remoteConfig/runtime";
|
||||
import { remoteChromeGateAllowed } from "@/seqta/utils/remoteConfig/routeGate";
|
||||
import { rafThrottle } from "@/seqta/utils/rafThrottle";
|
||||
import {
|
||||
installSidebarDrillReturn,
|
||||
@@ -47,7 +54,7 @@ function attachUserInfoCacheInvalidation(): void {
|
||||
|
||||
attachUserInfoCacheInvalidation();
|
||||
|
||||
let LightDarkModeSnakeEggButton = 0;
|
||||
let lightDarkToggleStreak = 0;
|
||||
let sidebarAccessibilityObserver: MutationObserver | null = null;
|
||||
let sidebarTabOrderAnimationFrame: number | null = null;
|
||||
let sidebarAccessibilityListenersAttached = false;
|
||||
@@ -138,8 +145,12 @@ export async function AddBetterSEQTAElements() {
|
||||
const menu = document.getElementById("menu")!;
|
||||
const menuList = menu.firstChild as HTMLElement;
|
||||
|
||||
createHomeButton(fragment, menuList);
|
||||
createNewsButton(fragment, menu);
|
||||
if (!checkRemoteFeature("page.home").hide) {
|
||||
createHomeButton(fragment, menuList);
|
||||
}
|
||||
if (!checkRemoteFeature("page.news").hide) {
|
||||
createNewsButton(fragment, menu);
|
||||
}
|
||||
|
||||
menuList.insertBefore(fragment, menuList.firstChild);
|
||||
|
||||
@@ -152,7 +163,9 @@ export async function AddBetterSEQTAElements() {
|
||||
setupEventListeners();
|
||||
await addDarkLightToggle();
|
||||
customizeMenuToggle();
|
||||
maybeSetupSidebarAccessibility();
|
||||
if (remoteChromeGateAllowed("ui.sidebar.styled")) {
|
||||
maybeSetupSidebarAccessibility();
|
||||
}
|
||||
}
|
||||
|
||||
addExtensionSettings();
|
||||
@@ -543,14 +556,17 @@ async function addDarkLightToggle(parent?: Element) {
|
||||
"LightDarkModeButton",
|
||||
)!;
|
||||
|
||||
ensureThemeToggleSurprisePageScript();
|
||||
|
||||
lightDarkModeButtonElement.addEventListener("click", async () => {
|
||||
const darklightText = document.getElementById("darklighttooliptext");
|
||||
|
||||
LightDarkModeSnakeEggButton += 1;
|
||||
lightDarkToggleStreak += 1;
|
||||
|
||||
if (LightDarkModeSnakeEggButton >= 10) {
|
||||
window.open("https://www.youtube.com/watch?v=dQw4w9WgXcQ", "_blank");
|
||||
LightDarkModeSnakeEggButton = 0;
|
||||
if (lightDarkToggleStreak >= THEME_TOGGLE_SURPRISE_TRIGGER_AT) {
|
||||
lightDarkToggleStreak = 0;
|
||||
openThemeToggleSurprise();
|
||||
return;
|
||||
}
|
||||
|
||||
if (
|
||||
|
||||
@@ -1,21 +1,82 @@
|
||||
import { cloudAuth } from "@/seqta/utils/CloudAuth";
|
||||
import { refreshCloudUserFromServer } from "@/seqta/utils/cloudPfpSync";
|
||||
import { settingsState } from "@/seqta/utils/listeners/SettingsState";
|
||||
import { fullMotionEffectsEnabled } from "@/seqta/utils/performanceMode";
|
||||
import {
|
||||
badgesForTitlebar,
|
||||
founderBadgeChipHtml,
|
||||
pickPrimaryFounderBadge,
|
||||
type FounderBadgeItem,
|
||||
type BadgeItem,
|
||||
} from "@/seqta/utils/founderBadges";
|
||||
import { openFounderBadgeModal } from "@/seqta/ui/founderBadge/openFounderBadgeModal";
|
||||
import { remoteChromeGateAllowed } from "@/seqta/utils/remoteConfig/routeGate";
|
||||
|
||||
let subscribed = false;
|
||||
let refreshPending = false;
|
||||
let profileSyncedThisSession = false;
|
||||
|
||||
function renderBadgeChip(
|
||||
slot: HTMLElement,
|
||||
badge: FounderBadgeItem,
|
||||
const BADGE_CYCLE_MS = 4500;
|
||||
const carouselTimers = new WeakMap<HTMLElement, ReturnType<typeof setInterval>>();
|
||||
|
||||
function stopBadgeCarousel(slot: HTMLElement): void {
|
||||
const timer = carouselTimers.get(slot);
|
||||
if (timer != null) {
|
||||
clearInterval(timer);
|
||||
carouselTimers.delete(slot);
|
||||
}
|
||||
}
|
||||
|
||||
function wireBadgeChip(
|
||||
chip: HTMLButtonElement,
|
||||
badge: BadgeItem,
|
||||
signupNumber?: number | null,
|
||||
): void {
|
||||
chip.setAttribute("aria-label", `${badge.label}, click for details`);
|
||||
chip.addEventListener("click", () => openFounderBadgeModal(badge, signupNumber));
|
||||
}
|
||||
|
||||
function setActiveBadgeChip(chips: HTMLButtonElement[], index: number): void {
|
||||
chips.forEach((chip, i) => {
|
||||
const active = i === index;
|
||||
chip.classList.toggle("bsplus-founder-badge--active", active);
|
||||
chip.setAttribute("aria-hidden", active ? "false" : "true");
|
||||
chip.tabIndex = active ? 0 : -1;
|
||||
});
|
||||
}
|
||||
|
||||
function startBadgeCarousel(
|
||||
slot: HTMLElement,
|
||||
chips: HTMLButtonElement[],
|
||||
badges: BadgeItem[],
|
||||
signupNumber?: number | null,
|
||||
): void {
|
||||
stopBadgeCarousel(slot);
|
||||
if (chips.length <= 1) return;
|
||||
|
||||
let index = 0;
|
||||
setActiveBadgeChip(chips, index);
|
||||
slot.setAttribute(
|
||||
"aria-label",
|
||||
`${badges[index]?.label ?? "Cloud badge"}. Cycles through ${badges.length} badges.`,
|
||||
);
|
||||
|
||||
carouselTimers.set(
|
||||
slot,
|
||||
setInterval(() => {
|
||||
index = (index + 1) % chips.length;
|
||||
setActiveBadgeChip(chips, index);
|
||||
const label = badges[index]?.label;
|
||||
if (label) slot.setAttribute("aria-label", `${label}. Badge ${index + 1} of ${badges.length}.`);
|
||||
}, BADGE_CYCLE_MS),
|
||||
);
|
||||
}
|
||||
|
||||
function renderTitlebarBadges(
|
||||
slot: HTMLElement,
|
||||
badges: BadgeItem[],
|
||||
signupNumber?: number | null,
|
||||
): void {
|
||||
stopBadgeCarousel(slot);
|
||||
|
||||
const house = slot
|
||||
.closest(".userInfoHouseWrap")
|
||||
?.querySelector<HTMLElement>(".userInfohouse");
|
||||
@@ -25,43 +86,81 @@ function renderBadgeChip(
|
||||
return;
|
||||
}
|
||||
|
||||
const rendered = badges
|
||||
.map((b) => ({ badge: b, html: founderBadgeChipHtml(b, { titlebar: true }) }))
|
||||
.filter((entry) => entry.html.length > 0);
|
||||
|
||||
if (rendered.length === 0) {
|
||||
slot.replaceChildren();
|
||||
slot.hidden = true;
|
||||
return;
|
||||
}
|
||||
|
||||
slot.hidden = false;
|
||||
slot.innerHTML = founderBadgeChipHtml(badge, { titlebar: true });
|
||||
slot.removeAttribute("aria-label");
|
||||
|
||||
const chip = slot.querySelector<HTMLButtonElement>(".bsplus-founder-badge");
|
||||
if (!chip) return;
|
||||
if (rendered.length === 1) {
|
||||
slot.innerHTML = rendered[0].html;
|
||||
const chip = slot.querySelector<HTMLButtonElement>(".bsplus-founder-badge");
|
||||
if (chip) wireBadgeChip(chip, rendered[0].badge, signupNumber);
|
||||
return;
|
||||
}
|
||||
|
||||
chip.setAttribute("aria-label", `${badge.label}, click for details`);
|
||||
chip.addEventListener("click", () => openFounderBadgeModal(badge, signupNumber));
|
||||
const motionClass = fullMotionEffectsEnabled()
|
||||
? "bsplus-founder-badge-carousel"
|
||||
: "bsplus-founder-badge-carousel bsplus-founder-badge-carousel--static";
|
||||
slot.innerHTML = `<div class="${motionClass}">${rendered.map((r) => r.html).join("")}</div>`;
|
||||
|
||||
const chips = [...slot.querySelectorAll<HTMLButtonElement>(".bsplus-founder-badge")];
|
||||
chips.forEach((chip, i) => {
|
||||
const entry = rendered[i];
|
||||
if (!entry) return;
|
||||
wireBadgeChip(chip, entry.badge, signupNumber);
|
||||
});
|
||||
|
||||
startBadgeCarousel(
|
||||
slot,
|
||||
chips,
|
||||
rendered.map((r) => r.badge),
|
||||
signupNumber,
|
||||
);
|
||||
}
|
||||
|
||||
async function syncTitlebarFounderBadge(): Promise<void> {
|
||||
const slots = document.querySelectorAll<HTMLElement>(".titlebar .bsplus-founder-badge-slot");
|
||||
for (const slot of slots) {
|
||||
stopBadgeCarousel(slot);
|
||||
slot.replaceChildren();
|
||||
slot.hidden = true;
|
||||
}
|
||||
|
||||
if (settingsState.showTitlebarFounderBadge === false || !cloudAuth.state.isLoggedIn) return;
|
||||
if (
|
||||
settingsState.showTitlebarFounderBadge === false ||
|
||||
!cloudAuth.state.isLoggedIn ||
|
||||
!remoteChromeGateAllowed("ui.titlebar.founderBadge")
|
||||
) {
|
||||
return;
|
||||
}
|
||||
|
||||
let user = cloudAuth.state.user;
|
||||
if (user && user.signup_number == null && !user.badges?.length) {
|
||||
if (!refreshPending) {
|
||||
refreshPending = true;
|
||||
try {
|
||||
await refreshCloudUserFromServer();
|
||||
user = cloudAuth.state.user;
|
||||
} finally {
|
||||
refreshPending = false;
|
||||
}
|
||||
const needsProfileSync =
|
||||
!profileSyncedThisSession || (user?.signup_number == null && !user?.badges?.length);
|
||||
if (needsProfileSync && !refreshPending) {
|
||||
refreshPending = true;
|
||||
try {
|
||||
await refreshCloudUserFromServer();
|
||||
user = cloudAuth.state.user;
|
||||
profileSyncedThisSession = true;
|
||||
} finally {
|
||||
refreshPending = false;
|
||||
}
|
||||
}
|
||||
|
||||
const badge = pickPrimaryFounderBadge(user?.badges ?? [], user?.signup_number);
|
||||
if (!badge) return;
|
||||
const badges = badgesForTitlebar(user?.badges ?? [], user?.signup_number);
|
||||
if (badges.length === 0) return;
|
||||
|
||||
for (const slot of slots) {
|
||||
renderBadgeChip(slot, badge, user?.signup_number);
|
||||
renderTitlebarBadges(slot, badges, user?.signup_number);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -72,7 +171,10 @@ export function refreshTitlebarFounderBadge(): void {
|
||||
export function ensureTitlebarFounderBadgeMounted(): void {
|
||||
if (!subscribed) {
|
||||
subscribed = true;
|
||||
cloudAuth.subscribe(() => void syncTitlebarFounderBadge());
|
||||
cloudAuth.subscribe((state) => {
|
||||
if (!state.isLoggedIn) profileSyncedThisSession = false;
|
||||
void syncTitlebarFounderBadge();
|
||||
});
|
||||
settingsState.register("showTitlebarFounderBadge", () => void syncTitlebarFounderBadge());
|
||||
}
|
||||
void syncTitlebarFounderBadge();
|
||||
|
||||
@@ -2,10 +2,10 @@ import stringToHTML from "@/seqta/utils/stringToHTML";
|
||||
import { closePopup, openPopup } from "@/seqta/utils/Openers/PopupManager";
|
||||
import { openFounderBadgeSettings } from "@/seqta/ui/founderBadge/openFounderBadgeSettings";
|
||||
import {
|
||||
badgeBlobStyle,
|
||||
badgeVisualForKey,
|
||||
founderBadgeChipHtml,
|
||||
tierBlobStyle,
|
||||
tierForBadgeKey,
|
||||
type FounderBadgeItem,
|
||||
type BadgeItem,
|
||||
} from "@/seqta/utils/founderBadges";
|
||||
|
||||
const ACCOUNTS_URL = "https://accounts.betterseqta.org";
|
||||
@@ -19,27 +19,27 @@ function esc(value: string): string {
|
||||
}
|
||||
|
||||
export function openFounderBadgeModal(
|
||||
badge: FounderBadgeItem,
|
||||
badge: BadgeItem,
|
||||
signupNumber?: number | null,
|
||||
): void {
|
||||
const tier = tierForBadgeKey(badge.key);
|
||||
if (!tier) return;
|
||||
const visual = badgeVisualForKey(badge.key, badge.label);
|
||||
if (!visual) return;
|
||||
|
||||
const header = stringToHTML(/* html */ `
|
||||
<div class="whatsnewHeader bsplus-founder-badge-header">
|
||||
<h1>${esc(badge.label)}</h1>
|
||||
<p>${esc(tier.rankLabel)}</p>
|
||||
<p>${esc(visual.rankLabel)}</p>
|
||||
</div>
|
||||
`).firstChild as HTMLElement;
|
||||
|
||||
const signupLine =
|
||||
signupNumber != null
|
||||
signupNumber != null && badge.key.startsWith("founder_")
|
||||
? `<p class="bsplus-founder-badge-signup">Cloud user #${signupNumber.toLocaleString()}</p>`
|
||||
: "";
|
||||
|
||||
const hero = stringToHTML(/* html */ `
|
||||
<div class="whatsnewImgContainer">
|
||||
<div class="bsplus-founder-badge-hero whatsnewImg" data-tier="${badge.key}" style="${tierBlobStyle(tier)}">
|
||||
<div class="bsplus-founder-badge-hero whatsnewImg" data-tier="${badge.key}" style="${badgeBlobStyle(visual)}">
|
||||
<div class="bsplus-founder-badge-hero__blobs" aria-hidden="true"></div>
|
||||
<div class="bsplus-founder-badge-hero__vignette" aria-hidden="true"></div>
|
||||
<div class="bsplus-founder-badge-hero__stage">
|
||||
@@ -51,7 +51,7 @@ export function openFounderBadgeModal(
|
||||
|
||||
const text = stringToHTML(/* html */ `
|
||||
<div class="whatsnewTextContainer bsplus-founder-badge-body" style="overflow-y: auto;">
|
||||
<p>${esc(tier.description)}</p>
|
||||
<p>${esc(visual.description)}</p>
|
||||
<p>
|
||||
Linked to your BetterSEQTA Cloud account at
|
||||
<a href="${ACCOUNTS_URL}" target="_blank" rel="noopener noreferrer">accounts.betterseqta.org</a>.
|
||||
|
||||
@@ -1,9 +1,19 @@
|
||||
export async function OpenStorePage(): Promise<void> {
|
||||
async function openThemesDestination(
|
||||
view: "store" | "community",
|
||||
): Promise<void> {
|
||||
const [{ requestSettingsDestination }, { openSettingsPopup }] =
|
||||
await Promise.all([
|
||||
import("@/seqta/utils/settingsNavigation"),
|
||||
import("@/seqta/utils/setupSettingsButton"),
|
||||
]);
|
||||
requestSettingsDestination({ page: "themes", view: "store" });
|
||||
requestSettingsDestination({ page: "themes", view });
|
||||
await openSettingsPopup();
|
||||
}
|
||||
|
||||
export async function OpenStorePage(): Promise<void> {
|
||||
await openThemesDestination("store");
|
||||
}
|
||||
|
||||
export async function OpenCommunityThemesPage(): Promise<void> {
|
||||
await openThemesDestination("community");
|
||||
}
|
||||
@@ -25,6 +25,7 @@ export type CloudUser = {
|
||||
displayName?: string;
|
||||
pfpUrl?: string;
|
||||
pfpHash?: string | null;
|
||||
pfpHistory?: { id: string; r2Key: string; createdAt: number }[];
|
||||
admin_level?: number;
|
||||
signup_number?: number | null;
|
||||
badges?: CloudBadge[];
|
||||
@@ -36,6 +37,10 @@ export type CloudAuthState = {
|
||||
user: CloudUser | null;
|
||||
};
|
||||
|
||||
export function isCloudAdmin(user: CloudUser | null | undefined): boolean {
|
||||
return (user?.admin_level ?? 0) >= 1;
|
||||
}
|
||||
|
||||
/** Callback invoked when auth state changes */
|
||||
type Listener = { (state: CloudAuthState): void };
|
||||
|
||||
|
||||
@@ -22,6 +22,10 @@ import {
|
||||
import { resolveNoticeFilterTokens } from "@/seqta/utils/notices/noticeLabelFilters";
|
||||
import { setupNoticesSection } from "@/seqta/utils/notices/noticeHomeUi";
|
||||
import { lessonsSubtitleForViewDate } from "@/seqta/utils/Loaders/timetableSubtitle";
|
||||
import {
|
||||
applyPageFeatureGateEarly,
|
||||
injectPageFeatureBanner,
|
||||
} from "@/seqta/utils/remoteConfig/runtime";
|
||||
|
||||
let lessonInterval: ReturnType<typeof setInterval> | null = null;
|
||||
let homeTeardown: (() => void) | null = null;
|
||||
@@ -36,6 +40,8 @@ function clearLessonInterval(): void {
|
||||
}
|
||||
|
||||
export async function loadHomePage() {
|
||||
if (applyPageFeatureGateEarly("home")) return;
|
||||
|
||||
homeTeardown?.();
|
||||
homeTeardown = null;
|
||||
clearLessonInterval();
|
||||
@@ -99,6 +105,8 @@ export async function loadHomePage() {
|
||||
</div>`);
|
||||
|
||||
homeContainer.appendChild(skeletonStructure.firstChild!);
|
||||
injectPageFeatureBanner("home", "#home-container");
|
||||
injectPageFeatureBanner("home", "#home-container");
|
||||
|
||||
if (settingsState.animations) {
|
||||
animate(
|
||||
@@ -499,8 +507,13 @@ function makeLessonDiv(lesson: any, num: number) {
|
||||
type,
|
||||
} = lesson;
|
||||
|
||||
const homeClassAttrs =
|
||||
type === "class"
|
||||
? ` data-bsplus-meta-id="${metaID ?? ""}" data-bsplus-code="${code ?? ""}" data-bsplus-programme-id="${programmeID ?? ""}"`
|
||||
: "";
|
||||
|
||||
let lessonString = `
|
||||
<div class="day" id="${code + num}" style="${colour}">
|
||||
<div class="day" id="${code + num}" style="${colour}"${homeClassAttrs}>
|
||||
<h2>${type == "class" ? description : type == "tutorial" ? "Tutorial" : "Unknown"}</h2>
|
||||
<h3>${staff || "Unknown"}</h3>
|
||||
<h3>${room || (type == "tutorial" ? "Unknown" : "N/A")}</h3>
|
||||
|
||||
@@ -0,0 +1,76 @@
|
||||
/**
|
||||
* @jest-environment jsdom
|
||||
*/
|
||||
jest.mock("../DevApiBase", () => ({
|
||||
getApiBase: () => "https://betterseqta.org",
|
||||
}));
|
||||
|
||||
import {
|
||||
getFallbackTermsOfService,
|
||||
markTermsOfServiceAccepted,
|
||||
shouldShowTermsOfServicePopup,
|
||||
} from "./OpenTermsOfServicePopup";
|
||||
|
||||
const SAMPLE_TERMS = {
|
||||
last_updated: "2024-06-15T12:00:00Z",
|
||||
whatsnew_html: "<div class=\"whatsnewTextContainer\"><p>Terms body</p></div>",
|
||||
};
|
||||
|
||||
describe("shouldShowTermsOfServicePopup", () => {
|
||||
it("shows when the user has never accepted", () => {
|
||||
expect(
|
||||
shouldShowTermsOfServicePopup({ termsOfServiceLastAccepted: undefined }, SAMPLE_TERMS),
|
||||
).toBe(true);
|
||||
});
|
||||
|
||||
it("shows when the remote policy was updated after acceptance", () => {
|
||||
expect(
|
||||
shouldShowTermsOfServicePopup(
|
||||
{ termsOfServiceLastAccepted: "2024-01-01T00:00:00Z" },
|
||||
SAMPLE_TERMS,
|
||||
),
|
||||
).toBe(true);
|
||||
});
|
||||
|
||||
it("does not show when the user accepted the current version", () => {
|
||||
expect(
|
||||
shouldShowTermsOfServicePopup(
|
||||
{ termsOfServiceLastAccepted: SAMPLE_TERMS.last_updated },
|
||||
SAMPLE_TERMS,
|
||||
),
|
||||
).toBe(false);
|
||||
});
|
||||
|
||||
it("treats legacy privacy acceptance as terms acceptance", () => {
|
||||
expect(
|
||||
shouldShowTermsOfServicePopup(
|
||||
{
|
||||
privacyStatementShown: true,
|
||||
privacyStatementLastUpdated: SAMPLE_TERMS.last_updated,
|
||||
},
|
||||
SAMPLE_TERMS,
|
||||
),
|
||||
).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe("markTermsOfServiceAccepted", () => {
|
||||
it("stores the accepted terms version from GET /api/terms", () => {
|
||||
const state = {
|
||||
termsOfServiceLastAccepted: undefined as string | undefined,
|
||||
};
|
||||
|
||||
markTermsOfServiceAccepted(state, SAMPLE_TERMS.last_updated);
|
||||
|
||||
expect(state.termsOfServiceLastAccepted).toBe(SAMPLE_TERMS.last_updated);
|
||||
});
|
||||
});
|
||||
|
||||
describe("getFallbackTermsOfService", () => {
|
||||
it("returns bundled fallback content when the API is unavailable", () => {
|
||||
const fallback = getFallbackTermsOfService();
|
||||
expect(fallback.last_updated).toBeTruthy();
|
||||
expect(fallback.whatsnew_html).toContain("whatsnewTextContainer");
|
||||
expect(fallback.whatsnew_html).toContain("Agreement");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,202 @@
|
||||
import stringToHTML from "../stringToHTML";
|
||||
import { settingsState } from "../listeners/SettingsState";
|
||||
import { getApiBase } from "../DevApiBase";
|
||||
import { closePopup, openPopup } from "./PopupManager";
|
||||
import fallbackTerms from "@/exampletermsresponse.json";
|
||||
import type { SettingsState } from "@/types/storage";
|
||||
|
||||
export const TERMS_OF_SERVICE_URL = "https://betterseqta.org/terms";
|
||||
export const PRIVACY_POLICY_URL = "https://betterseqta.org/privacy";
|
||||
|
||||
const TERMS_FETCH_TIMEOUT_MS = 8_000;
|
||||
|
||||
/** Shared shape for `GET /api/terms` and `GET /api/privacy`. */
|
||||
export interface LegalDocumentPayload {
|
||||
last_updated: string;
|
||||
whatsnew_html: string;
|
||||
}
|
||||
|
||||
function isLegalDocumentPayload(data: unknown): data is LegalDocumentPayload {
|
||||
return (
|
||||
!!data &&
|
||||
typeof data === "object" &&
|
||||
typeof (data as LegalDocumentPayload).last_updated === "string" &&
|
||||
typeof (data as LegalDocumentPayload).whatsnew_html === "string" &&
|
||||
!!(data as LegalDocumentPayload).whatsnew_html.trim()
|
||||
);
|
||||
}
|
||||
|
||||
export function getFallbackTermsOfService(): LegalDocumentPayload {
|
||||
return fallbackTerms as LegalDocumentPayload;
|
||||
}
|
||||
|
||||
/** Loads Terms of Service body from `GET /api/terms`. */
|
||||
export async function fetchTermsOfService(): Promise<LegalDocumentPayload> {
|
||||
try {
|
||||
const res = await fetch(`${getApiBase()}/api/terms`, {
|
||||
cache: "no-store",
|
||||
signal: AbortSignal.timeout(TERMS_FETCH_TIMEOUT_MS),
|
||||
});
|
||||
if (!res.ok) return getFallbackTermsOfService();
|
||||
const data: unknown = await res.json();
|
||||
if (!isLegalDocumentPayload(data)) return getFallbackTermsOfService();
|
||||
return data;
|
||||
} catch (err) {
|
||||
console.warn("[TermsOfService] Failed to fetch terms:", err);
|
||||
return getFallbackTermsOfService();
|
||||
}
|
||||
}
|
||||
|
||||
/** @deprecated Use {@link fetchTermsOfService}. */
|
||||
export const fetchPrivacyTerms = fetchTermsOfService;
|
||||
|
||||
function termsVersionIsNewer(
|
||||
remoteLastUpdated: string,
|
||||
acceptedLastUpdated?: string,
|
||||
): boolean {
|
||||
if (!acceptedLastUpdated) return true;
|
||||
const remote = Date.parse(remoteLastUpdated);
|
||||
const accepted = Date.parse(acceptedLastUpdated);
|
||||
if (Number.isNaN(remote) || Number.isNaN(accepted)) {
|
||||
return remoteLastUpdated !== acceptedLastUpdated;
|
||||
}
|
||||
return remote > accepted;
|
||||
}
|
||||
|
||||
function resolvedTermsAcceptance(
|
||||
state: Pick<
|
||||
SettingsState,
|
||||
| "termsOfServiceLastAccepted"
|
||||
| "privacyStatementShown"
|
||||
| "privacyStatementLastUpdated"
|
||||
>,
|
||||
): string | undefined {
|
||||
if (state.termsOfServiceLastAccepted) return state.termsOfServiceLastAccepted;
|
||||
if (state.privacyStatementShown && state.privacyStatementLastUpdated) {
|
||||
return state.privacyStatementLastUpdated;
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
|
||||
export function shouldShowTermsOfServicePopup(
|
||||
state: Pick<
|
||||
SettingsState,
|
||||
| "termsOfServiceLastAccepted"
|
||||
| "privacyStatementShown"
|
||||
| "privacyStatementLastUpdated"
|
||||
>,
|
||||
terms: LegalDocumentPayload,
|
||||
): boolean {
|
||||
return termsVersionIsNewer(terms.last_updated, resolvedTermsAcceptance(state));
|
||||
}
|
||||
|
||||
export function markTermsOfServiceAccepted(
|
||||
state: Pick<SettingsState, "termsOfServiceLastAccepted">,
|
||||
lastUpdated: string,
|
||||
): void {
|
||||
state.termsOfServiceLastAccepted = lastUpdated;
|
||||
}
|
||||
|
||||
function buildTermsScrollContent(html: string): HTMLElement {
|
||||
const parsed = stringToHTML(html);
|
||||
const root = parsed.firstElementChild as HTMLElement | null;
|
||||
const scroll = document.createElement("div");
|
||||
scroll.className = "bsplus-tos-scroll privacyStatement";
|
||||
scroll.setAttribute("tabindex", "0");
|
||||
scroll.setAttribute("aria-label", "Terms of service");
|
||||
|
||||
if (root?.classList.contains("whatsnewTextContainer")) {
|
||||
scroll.innerHTML = root.innerHTML;
|
||||
} else if (root) {
|
||||
scroll.append(root);
|
||||
} else {
|
||||
scroll.innerHTML = parsed.innerHTML;
|
||||
}
|
||||
|
||||
return scroll;
|
||||
}
|
||||
|
||||
export async function openTermsOfServicePopup(
|
||||
onDismissed?: () => void,
|
||||
options?: { terms?: LegalDocumentPayload; force?: boolean },
|
||||
) {
|
||||
if (document.getElementById("whatsnewbk")) {
|
||||
onDismissed?.();
|
||||
return;
|
||||
}
|
||||
|
||||
const terms = options?.terms ?? (await fetchTermsOfService());
|
||||
if (!options?.force && !shouldShowTermsOfServicePopup(settingsState, terms)) {
|
||||
onDismissed?.();
|
||||
return;
|
||||
}
|
||||
|
||||
const header = stringToHTML(
|
||||
/* html */
|
||||
`<div class="whatsnewHeader bsplus-tos-header">
|
||||
<h1>Terms of Service</h1>
|
||||
<p>Scroll to read the full terms, then accept or dismiss for now</p>
|
||||
</div>`,
|
||||
).firstChild as HTMLElement;
|
||||
|
||||
const scrollContent = buildTermsScrollContent(terms.whatsnew_html);
|
||||
|
||||
const body = document.createElement("div");
|
||||
body.className = "whatsnewTextContainer bsplus-tos-body";
|
||||
|
||||
const intro = stringToHTML(/* html */ `
|
||||
<p class="bsplus-tos-intro privacyStatement">
|
||||
Do you accept the terms of service?
|
||||
<a href="${TERMS_OF_SERVICE_URL}" target="_blank" rel="noopener noreferrer">Terms</a>
|
||||
·
|
||||
<a href="${PRIVACY_POLICY_URL}" target="_blank" rel="noopener noreferrer">Privacy</a>
|
||||
</p>
|
||||
`).firstChild as HTMLElement;
|
||||
|
||||
const actions = stringToHTML(/* html */ `
|
||||
<div class="bsplus-tos-actions">
|
||||
<button type="button" id="bsplus-tos-decline" class="bsplus-tos-btn bsplus-tos-btn--secondary">
|
||||
Not now
|
||||
</button>
|
||||
<button type="button" id="bsplus-tos-accept" class="bsplus-tos-btn bsplus-tos-btn--primary">
|
||||
I accept the terms of service
|
||||
</button>
|
||||
</div>
|
||||
`).firstChild as HTMLElement;
|
||||
|
||||
body.append(intro, scrollContent, actions);
|
||||
|
||||
openPopup({
|
||||
header,
|
||||
content: [body],
|
||||
containerClass: "bsplus-tos-container",
|
||||
backgroundClass: "bsplus-tos-overlay",
|
||||
hideCloseButton: true,
|
||||
closeOnBackdrop: false,
|
||||
closeOnEscape: false,
|
||||
animateSelector: ".bsplus-tos-header *, .bsplus-tos-body > *",
|
||||
afterClose: onDismissed,
|
||||
actions: [
|
||||
{
|
||||
id: "bsplus-tos-accept",
|
||||
onClick: () => {
|
||||
markTermsOfServiceAccepted(settingsState, terms.last_updated);
|
||||
void closePopup();
|
||||
},
|
||||
},
|
||||
{
|
||||
id: "bsplus-tos-decline",
|
||||
onClick: () => {
|
||||
void closePopup();
|
||||
},
|
||||
},
|
||||
],
|
||||
onReady: ({ container }) => {
|
||||
container.setAttribute("role", "dialog");
|
||||
container.setAttribute("aria-modal", "true");
|
||||
container.setAttribute("aria-labelledby", "bsplus-tos-title");
|
||||
const title = container.querySelector(".whatsnewHeader h1");
|
||||
if (title) title.id = "bsplus-tos-title";
|
||||
},
|
||||
});
|
||||
}
|
||||
@@ -3,6 +3,7 @@ import stringToHTML from "../stringToHTML";
|
||||
import { settingsState } from "../listeners/SettingsState";
|
||||
import { closePopup } from "./PopupManager";
|
||||
import { getApiBase } from "../DevApiBase";
|
||||
import { withBsplusApiQuery } from "../bsplusClientContext";
|
||||
import { openThemeStoreWithHighlight } from "../openThemeStoreWithHighlight";
|
||||
import type { Theme } from "@/interface/types/Theme";
|
||||
import {
|
||||
@@ -62,7 +63,8 @@ async function writeCachedThemeOfTheMonth(
|
||||
*/
|
||||
export async function fetchThemeOfTheMonth(): Promise<ThemeOfTheMonthEntry | null> {
|
||||
try {
|
||||
const res = await fetch(`${getApiBase()}/api/theme-of-the-month/current`, {
|
||||
const url = await withBsplusApiQuery(`${getApiBase()}/api/theme-of-the-month/current`);
|
||||
const res = await fetch(url, {
|
||||
cache: "no-store",
|
||||
signal: AbortSignal.timeout(TOTM_FETCH_TIMEOUT_MS),
|
||||
});
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
import semver from "semver";
|
||||
import browser from "webextension-polyfill";
|
||||
import { settingsState } from "../listeners/SettingsState";
|
||||
import { OpenWhatsNewPopup } from "./OpenWhatsNewPopup";
|
||||
import {
|
||||
@@ -11,24 +13,46 @@ import {
|
||||
shouldShowCoursesAssessmentsFixPopup,
|
||||
} from "./OpenCoursesAssessmentsFixPopup";
|
||||
import { syncApiBaseToBackground } from "../DevApiBase";
|
||||
import { cloudAuth } from "../CloudAuth";
|
||||
import {
|
||||
fetchTermsOfService,
|
||||
openTermsOfServicePopup,
|
||||
shouldShowTermsOfServicePopup,
|
||||
} from "./OpenTermsOfServicePopup";
|
||||
import { getCampaignSeen, getRemoteConfigSnapshot } from "@/seqta/utils/remoteConfig/runtime";
|
||||
import type { RemoteCampaign } from "@/seqta/utils/remoteConfig/types";
|
||||
import { openRemoteCampaignPopup } from "./openRemoteCampaignPopup";
|
||||
|
||||
type QueueStep = (goNext: () => void) => void;
|
||||
|
||||
/**
|
||||
* Runs startup modals in order: What's New (if the extension just updated),
|
||||
* Courses/Assessments fix notice (only if features are off),
|
||||
* Theme of the Month (when the user hasn't dismissed this calendar month),
|
||||
* then feedback reply notifications for pending submissions.
|
||||
*/
|
||||
function remoteCampaignSteps(): QueueStep[] {
|
||||
const now = Date.now();
|
||||
const version = browser.runtime.getManifest().version;
|
||||
const seen = getCampaignSeen();
|
||||
|
||||
return [...getRemoteConfigSnapshot().campaigns]
|
||||
.filter((c) => {
|
||||
if (!c.id) return false;
|
||||
if (c.activeFrom && now < Date.parse(c.activeFrom)) return false;
|
||||
if (c.activeTo && now > Date.parse(c.activeTo)) return false;
|
||||
const hit = seen[c.id];
|
||||
if (hit && (!c.requireAcknowledge || hit.ack)) return false;
|
||||
if (c.minVersion && semver.valid(version) && semver.lt(version, c.minVersion)) return false;
|
||||
if (c.maxVersion && semver.valid(version) && semver.gt(version, c.maxVersion)) return false;
|
||||
return true;
|
||||
})
|
||||
.sort((a, b) => (b.priority ?? 0) - (a.priority ?? 0))
|
||||
.map((campaign: RemoteCampaign) => (goNext: () => void) => {
|
||||
openRemoteCampaignPopup(campaign, goNext);
|
||||
});
|
||||
}
|
||||
|
||||
export async function runStartupPopupQueue() {
|
||||
// Make sure the background script knows about any dev-mode API override
|
||||
// before we start firing requests.
|
||||
syncApiBaseToBackground();
|
||||
|
||||
const steps: QueueStep[] = [];
|
||||
const afterWhatsNew = !!settingsState.justupdated;
|
||||
const steps: QueueStep[] = [...remoteCampaignSteps()];
|
||||
|
||||
if (afterWhatsNew) {
|
||||
if (settingsState.justupdated) {
|
||||
steps.push((goNext) => OpenWhatsNewPopup(goNext));
|
||||
}
|
||||
|
||||
@@ -36,8 +60,6 @@ export async function runStartupPopupQueue() {
|
||||
steps.push((goNext) => OpenCoursesAssessmentsFixPopup(goNext));
|
||||
}
|
||||
|
||||
// Fetch the Theme of the Month before queueing so we don't show an empty
|
||||
// popup if the network or server is unavailable.
|
||||
const themeOfTheMonth = await fetchThemeOfTheMonth();
|
||||
if (shouldShowThemeOfTheMonth(themeOfTheMonth)) {
|
||||
steps.push((goNext) => {
|
||||
@@ -46,9 +68,22 @@ export async function runStartupPopupQueue() {
|
||||
}
|
||||
|
||||
const feedbackReplyStep = await maybeQueueFeedbackReplyPopup();
|
||||
if (feedbackReplyStep) {
|
||||
steps.push(feedbackReplyStep);
|
||||
}
|
||||
if (feedbackReplyStep) steps.push(feedbackReplyStep);
|
||||
|
||||
steps.push((goNext) => {
|
||||
void (async () => {
|
||||
if (!(await cloudAuth.getStoredToken())) {
|
||||
goNext();
|
||||
return;
|
||||
}
|
||||
const termsDocument = await fetchTermsOfService();
|
||||
if (!shouldShowTermsOfServicePopup(settingsState, termsDocument)) {
|
||||
goNext();
|
||||
return;
|
||||
}
|
||||
await openTermsOfServicePopup(goNext, { terms: termsDocument });
|
||||
})();
|
||||
});
|
||||
|
||||
function runNext() {
|
||||
const step = steps.shift();
|
||||
|
||||
@@ -0,0 +1,88 @@
|
||||
import stringToHTML from "../stringToHTML";
|
||||
import { closePopup, openPopup } from "./PopupManager";
|
||||
import { createPopupHeroVideo } from "./attachPopupMediaFullscreen";
|
||||
import { markCampaignSeen } from "@/seqta/utils/remoteConfig/runtime";
|
||||
import type { RemoteCampaign } from "@/seqta/utils/remoteConfig/types";
|
||||
import { requestSettingsDestination } from "@/seqta/utils/settingsNavigation";
|
||||
import { openSettingsPopup } from "@/seqta/utils/setupSettingsButton";
|
||||
|
||||
export function openRemoteCampaignPopup(
|
||||
campaign: RemoteCampaign,
|
||||
onDismissed?: () => void,
|
||||
): void {
|
||||
const title = campaign.header?.title ?? "BetterSEQTA+";
|
||||
const subtitle = campaign.header?.subtitle ?? "";
|
||||
let acknowledged = false;
|
||||
|
||||
const header = stringToHTML(
|
||||
/* html */ `<div class="whatsnewHeader"><h1>${title}</h1>${subtitle ? `<p>${subtitle}</p>` : ""}</div>`,
|
||||
).firstChild as HTMLElement;
|
||||
|
||||
const buttons = campaign.buttons?.length
|
||||
? campaign.buttons
|
||||
: [{ id: "dismiss", label: "Dismiss", action: "dismiss" as const }];
|
||||
|
||||
const actionsHtml = buttons
|
||||
.map(
|
||||
(btn, i) =>
|
||||
`<button type="button" id="bsplus-campaign-${campaign.id}-${btn.id}" class="bsplus-cal-btn ${i === 0 ? "bsplus-cal-btn--primary" : "bsplus-cal-btn--ghost"}">${btn.label}</button>`,
|
||||
)
|
||||
.join("");
|
||||
|
||||
const text = stringToHTML(/* html */ `
|
||||
<div class="whatsnewTextContainer bsplus-founder-badge-body" style="overflow-y: auto;">
|
||||
<div class="bsplus-campaign-body"></div>
|
||||
<div class="bsplus-founder-badge-actions">${actionsHtml}</div>
|
||||
</div>
|
||||
`).firstChild as HTMLElement;
|
||||
|
||||
const bodySlot = text.querySelector(".bsplus-campaign-body");
|
||||
if (bodySlot && campaign.bodyHtml) bodySlot.innerHTML = campaign.bodyHtml;
|
||||
|
||||
const content: HTMLElement[] = [];
|
||||
const hero = campaign.hero;
|
||||
if (hero?.url) {
|
||||
if (hero.type === "video") {
|
||||
content.push(createPopupHeroVideo(hero.url, hero.alt ?? ""));
|
||||
} else {
|
||||
const wrap = stringToHTML(/* html */ `<div class="whatsnewImgContainer"></div>`)
|
||||
.firstChild as HTMLElement;
|
||||
const img = document.createElement("img");
|
||||
img.src = hero.url;
|
||||
img.alt = hero.alt ?? "";
|
||||
img.className = "whatsnewImg";
|
||||
img.loading = "lazy";
|
||||
wrap.append(img);
|
||||
content.push(wrap);
|
||||
}
|
||||
}
|
||||
content.push(text);
|
||||
|
||||
const actions = buttons.map((btn) => ({
|
||||
id: `bsplus-campaign-${campaign.id}-${btn.id}`,
|
||||
onClick: async () => {
|
||||
if (btn.action === "url" && btn.url) {
|
||||
window.open(btn.url, "_blank", "noopener,noreferrer");
|
||||
} else if (btn.action === "openSettingsSection" && btn.section) {
|
||||
requestSettingsDestination({ section: btn.section });
|
||||
await openSettingsPopup();
|
||||
}
|
||||
if (campaign.requireAcknowledge) acknowledged = true;
|
||||
await closePopup();
|
||||
},
|
||||
}));
|
||||
|
||||
openPopup({
|
||||
header,
|
||||
content,
|
||||
animateSelector: ".whatsnewImgContainer, .whatsnewTextContainer *",
|
||||
actions,
|
||||
afterClose: () => {
|
||||
void markCampaignSeen(
|
||||
campaign.id,
|
||||
campaign.requireAcknowledge ? acknowledged : undefined,
|
||||
);
|
||||
onDismissed?.();
|
||||
},
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,83 @@
|
||||
import browser from "webextension-polyfill";
|
||||
|
||||
/** Maintainer note: the light/dark toggle easter egg (10 clicks) plays a Rick Roll video. */
|
||||
const PAGE_SCRIPT_RESOURCE = "resources/themeToggleSurprisePage.js";
|
||||
const POPOUT_ROOT_ID = "bsplus-ld-surprise-root";
|
||||
const PLAYER_MOUNT_ID = "bsplus-ld-surprise-player";
|
||||
const PAGE_SCRIPT_ID = "bsplus-theme-surprise-page-script";
|
||||
const MESSAGE_SOURCE = "betterseqta-theme-surprise";
|
||||
|
||||
export const THEME_TOGGLE_SURPRISE_TRIGGER_AT = 10;
|
||||
|
||||
let playerRoot: HTMLElement | null = null;
|
||||
let pageScriptInjected = false;
|
||||
|
||||
function hostElement(): HTMLElement {
|
||||
return document.getElementById("container") ?? document.body;
|
||||
}
|
||||
|
||||
function postToPageContext(type: "open" | "close", mountId?: string): void {
|
||||
window.postMessage(
|
||||
{
|
||||
source: MESSAGE_SOURCE,
|
||||
type,
|
||||
mountId,
|
||||
},
|
||||
"*",
|
||||
);
|
||||
}
|
||||
|
||||
/** Loads YouTube IFrame API in the page context (mirrors the test HTML setup). */
|
||||
export function ensureThemeToggleSurprisePageScript(): void {
|
||||
if (pageScriptInjected || document.getElementById(PAGE_SCRIPT_ID)) {
|
||||
pageScriptInjected = true;
|
||||
return;
|
||||
}
|
||||
|
||||
const script = document.createElement("script");
|
||||
script.id = PAGE_SCRIPT_ID;
|
||||
script.src = browser.runtime.getURL(PAGE_SCRIPT_RESOURCE);
|
||||
(document.head || document.documentElement).appendChild(script);
|
||||
pageScriptInjected = true;
|
||||
}
|
||||
|
||||
function ensurePlayerShell(): void {
|
||||
if (playerRoot) return;
|
||||
|
||||
const root = document.createElement("div");
|
||||
root.id = POPOUT_ROOT_ID;
|
||||
root.className = "bsplus-ld-surprise-root";
|
||||
|
||||
const aside = document.createElement("aside");
|
||||
aside.className = "bsplus-ld-surprise-popout";
|
||||
aside.setAttribute("role", "dialog");
|
||||
aside.setAttribute("aria-label", "Video player");
|
||||
|
||||
const closeBtn = document.createElement("button");
|
||||
closeBtn.type = "button";
|
||||
closeBtn.className = "bsplus-ld-surprise-close";
|
||||
closeBtn.setAttribute("aria-label", "Close");
|
||||
closeBtn.addEventListener("click", closeThemeToggleSurprise);
|
||||
|
||||
const mount = document.createElement("div");
|
||||
mount.id = PLAYER_MOUNT_ID;
|
||||
mount.className = "bsplus-ld-surprise-player";
|
||||
|
||||
aside.append(closeBtn, mount);
|
||||
root.append(aside);
|
||||
hostElement().append(root);
|
||||
|
||||
playerRoot = root;
|
||||
}
|
||||
|
||||
export function closeThemeToggleSurprise(): void {
|
||||
postToPageContext("close");
|
||||
playerRoot?.remove();
|
||||
playerRoot = null;
|
||||
}
|
||||
|
||||
export function openThemeToggleSurprise(): void {
|
||||
ensureThemeToggleSurprisePageScript();
|
||||
ensurePlayerShell();
|
||||
postToPageContext("open", PLAYER_MOUNT_ID);
|
||||
}
|
||||
@@ -5,7 +5,25 @@ export type WhatsNewRelease = {
|
||||
|
||||
export const WHATS_NEW_CHANGELOG: WhatsNewRelease[] = [
|
||||
{
|
||||
"title": "3.7.3 – Performance Mode, Timetable syncing with Friends and Calendars, Sidebar Customisation, new loading animations & Bugfix Bundle",
|
||||
"title": "3.7.6 - Timetable Sharing Fixes, Better Update resilience & Community Theme Submitter Badges,",
|
||||
"items": [
|
||||
"Improved releiability of opening the connection for Timetable Sharing.",
|
||||
"Added a new submitter badge for community theme submitters.",
|
||||
"Added ability for Admin's to view unreleased community themes for QA.",
|
||||
"Added ability for BetterSEQTA+ features to be dynamically configured remotly to negate compatability issues.",
|
||||
"Added ability to set BetterSEQTA Cloud Profile Picture from Extension Settings."
|
||||
]
|
||||
},
|
||||
{
|
||||
"title": "3.7.5 - Timetable Sharing Fixes",
|
||||
"items": [
|
||||
"Fixed the Sync with Friends button disappearing when classmate avatars fail to load.",
|
||||
"Sharing and sync controls now pause during BetterSEQTA Cloud outages and recover automatically.",
|
||||
"Timetable sync failures now show an error."
|
||||
]
|
||||
},
|
||||
{
|
||||
"title": "3.7.4 - Performance Mode, Timetable syncing with Friends and Calendars, Sidebar Customisation, new loading animations & Bugfix Bundle",
|
||||
"items": [
|
||||
"Added Performance Mode in General settings dramatically improving performance with little sacrifice to looks.",
|
||||
"Added the ability to sync your timetable with your friends and calendars.",
|
||||
@@ -47,11 +65,12 @@ export const WHATS_NEW_CHANGELOG: WhatsNewRelease[] = [
|
||||
"Improved background music autoplay with a tap-to-start hint when blocked.",
|
||||
"Added verbose logging toggle under Developer settings.",
|
||||
"Restored theme settings Edit/Done label and improved custom Select keyboard accessibility.",
|
||||
"Cloud sign-in now sends a device name for account management."
|
||||
"Cloud sign-in now sends a device name for account management.",
|
||||
"Added TOS popup"
|
||||
]
|
||||
},
|
||||
{
|
||||
"title": "3.7.2 – Analytics Fixes",
|
||||
"title": "3.7.2 - Analytics Fixes",
|
||||
"items": [
|
||||
"Fixed analytics page breaking on certain configurations.",
|
||||
"Added safer DOM handling for analytics to prevent crashes.",
|
||||
@@ -61,7 +80,7 @@ export const WHATS_NEW_CHANGELOG: WhatsNewRelease[] = [
|
||||
]
|
||||
},
|
||||
{
|
||||
"title": "3.7.0 – Grade Analytics, Enhanced Navigation, fonts, Global Search & SEQTA Engage Improvements",
|
||||
"title": "3.7.0 - Grade Analytics, Enhanced Navigation, fonts, Global Search & SEQTA Engage Improvements",
|
||||
"items": [
|
||||
"Added Enhanced Navigation for courses: the navigator now auto-scrolls to the selected lesson (e.g. inside the \"Go to…\" popup) and prev/next arrows for jumping between lessons.",
|
||||
"Added Grade Analytics, new sidebar page with grade trend charts synced from SEQTA.",
|
||||
@@ -530,6 +549,6 @@ export const WHATS_NEW_CHANGELOG: WhatsNewRelease[] = [
|
||||
export function renderWhatsNewChangelogHtml(): string {
|
||||
return WHATS_NEW_CHANGELOG.map(
|
||||
(release) =>
|
||||
`<h1>${release.title}</h1>\n${release.items.map((item) => `<li>${item}</li>`).join("\n")}`,
|
||||
).join("\n\n ");
|
||||
`<section class="whatsnewRelease">\n<h1>${release.title}</h1>\n${release.items.map((item) => `<li>${item}</li>`).join("\n")}\n</section>`,
|
||||
).join("\n");
|
||||
}
|
||||
@@ -7,8 +7,14 @@ import LogoLightOutline from "@/resources/icons/betterseqta-light-outline.png";
|
||||
import { resolveExtensionAssetUrl } from "@/lib/extensionAssetUrl";
|
||||
import { animate, stagger } from "motion";
|
||||
import { verboseInfo } from "@/utils/verboseLog";
|
||||
import {
|
||||
applyPageFeatureGateEarly,
|
||||
injectPageFeatureBanner,
|
||||
} from "@/seqta/utils/remoteConfig/runtime";
|
||||
|
||||
export async function SendNewsPage() {
|
||||
if (applyPageFeatureGateEarly("news")) return;
|
||||
|
||||
verboseInfo("[BetterSEQTA+] Started Loading News Page");
|
||||
document.title = "News ― SEQTA Learn";
|
||||
await delay(10);
|
||||
@@ -47,6 +53,7 @@ export async function SendNewsPage() {
|
||||
</div>`);
|
||||
|
||||
main.append(html.firstChild!);
|
||||
injectPageFeatureBanner("news", "#news-container");
|
||||
|
||||
void import("@/seqta/ui/titlebar/mountCustomTitleBar").then((mod) => {
|
||||
mod.setCustomTitleBarText("News");
|
||||
@@ -121,7 +128,6 @@ export async function SendNewsPage() {
|
||||
fragment.append(newsarticle);
|
||||
});
|
||||
|
||||
// Single DOM update to append all articles
|
||||
newscontainer?.append(fragment);
|
||||
|
||||
if (!settingsState.animations) return;
|
||||
|
||||
@@ -0,0 +1,46 @@
|
||||
import browser from "webextension-polyfill";
|
||||
import { getOrCreateInstallId } from "@/seqta/utils/feedback/installId";
|
||||
|
||||
function manifestVersion(): string {
|
||||
try {
|
||||
return browser.runtime.getManifest().version;
|
||||
} catch {
|
||||
return "0";
|
||||
}
|
||||
}
|
||||
|
||||
function updateChannel(): string {
|
||||
if (typeof __UPDATE_CHANNEL__ !== "undefined") {
|
||||
if (__UPDATE_CHANNEL__ === "nightly") return "nightly";
|
||||
if (__UPDATE_CHANNEL__ === "stable") return "stable";
|
||||
}
|
||||
return "unknown";
|
||||
}
|
||||
|
||||
export function bsplusExtensionPayload(): {
|
||||
version: string;
|
||||
channel: string;
|
||||
browser: "chrome";
|
||||
} {
|
||||
return { version: manifestVersion(), channel: updateChannel(), browser: "chrome" };
|
||||
}
|
||||
|
||||
/** Shared query params for betterseqta.org theme + remote-config requests. */
|
||||
export async function bsplusApiQueryParams(): Promise<URLSearchParams> {
|
||||
const params = new URLSearchParams({
|
||||
extensionVersion: manifestVersion(),
|
||||
channel: updateChannel(),
|
||||
installId: await getOrCreateInstallId(),
|
||||
});
|
||||
const { bsplus_user } = await browser.storage.local.get("bsplus_user");
|
||||
if (bsplus_user && typeof bsplus_user === "object" && "id" in bsplus_user) {
|
||||
const id = (bsplus_user as { id: unknown }).id;
|
||||
if (typeof id === "string" && id) params.set("userId", id);
|
||||
}
|
||||
return params;
|
||||
}
|
||||
|
||||
export async function withBsplusApiQuery(url: string): Promise<string> {
|
||||
const qs = (await bsplusApiQueryParams()).toString();
|
||||
return qs ? (url.includes("?") ? `${url}&${qs}` : `${url}?${qs}`) : url;
|
||||
}
|
||||
+179
-156
@@ -1,45 +1,138 @@
|
||||
import browser from "webextension-polyfill";
|
||||
import localforage from "localforage";
|
||||
import { cloudAuth, type CloudUser } from "@/seqta/utils/CloudAuth";
|
||||
import {
|
||||
clearCloudPfpCache,
|
||||
pfpUrlWithHash,
|
||||
} from "@/seqta/utils/cloudPfpCache";
|
||||
import { clearCloudPfpCache, pfpUrlWithHash } from "@/seqta/utils/cloudPfpCache";
|
||||
|
||||
const ACCOUNTS_BASE = "https://accounts.betterseqta.org";
|
||||
const BSPLUS_PFP = `${ACCOUNTS_BASE}/api/bsplus/pfp`;
|
||||
const PLUGIN_SETTINGS_KEY = "plugin.profile-picture.settings";
|
||||
const UPLOAD_MAX_EDGE = 512;
|
||||
const MAX_SOURCE_BYTES_WEBP = 20 * 1024 * 1024;
|
||||
const MAX_SOURCE_BYTES_LEGACY = 10 * 1024 * 1024;
|
||||
|
||||
function webpExportSupported(): boolean {
|
||||
try {
|
||||
const canvas = document.createElement("canvas");
|
||||
canvas.width = 1;
|
||||
canvas.height = 1;
|
||||
return canvas.toDataURL("image/webp").startsWith("data:image/webp");
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
function maxSourceBytes(): number {
|
||||
return webpExportSupported() ? MAX_SOURCE_BYTES_WEBP : MAX_SOURCE_BYTES_LEGACY;
|
||||
}
|
||||
|
||||
const profileStore = localforage.createInstance({
|
||||
name: "profile-picture-store",
|
||||
storeName: "profilePicture",
|
||||
});
|
||||
|
||||
/** Downscale before upload to reduce ingress (server still normalizes). */
|
||||
async function downscaleForUpload(blob: Blob, maxEdge = 512): Promise<Blob> {
|
||||
if (!blob.type.startsWith("image/")) return blob;
|
||||
type PfpPayload = {
|
||||
pfpUrl: string | null;
|
||||
pfpHash: string | null;
|
||||
pfpHistory: CloudUser["pfpHistory"];
|
||||
};
|
||||
|
||||
const bitmap = await createImageBitmap(blob);
|
||||
const maxSide = Math.max(bitmap.width, bitmap.height);
|
||||
if (maxSide <= maxEdge) {
|
||||
bitmap.close();
|
||||
return blob;
|
||||
async function parseJson(res: Response): Promise<Record<string, unknown>> {
|
||||
const text = await res.text();
|
||||
try {
|
||||
return text ? (JSON.parse(text) as Record<string, unknown>) : {};
|
||||
} catch {
|
||||
return {};
|
||||
}
|
||||
}
|
||||
|
||||
function parsePfpPayload(data: Record<string, unknown>): PfpPayload {
|
||||
const rawUrl = data.pfpUrl as string | null | undefined;
|
||||
const history = Array.isArray(data.pfpHistory) ? data.pfpHistory : [];
|
||||
const pfpHistory = history.flatMap((item) => {
|
||||
if (!item || typeof item !== "object") return [];
|
||||
const o = item as Record<string, unknown>;
|
||||
if (
|
||||
typeof o.id === "string" &&
|
||||
typeof o.r2Key === "string" &&
|
||||
typeof o.createdAt === "number"
|
||||
) {
|
||||
return [{ id: o.id, r2Key: o.r2Key, createdAt: o.createdAt }];
|
||||
}
|
||||
return [];
|
||||
});
|
||||
return {
|
||||
pfpUrl: rawUrl == null || rawUrl === "" ? null : rawUrl,
|
||||
pfpHash: (data.pfpHash as string | null | undefined) ?? null,
|
||||
pfpHistory,
|
||||
};
|
||||
}
|
||||
|
||||
function mergePfpIntoUser(user: CloudUser, pfp: PfpPayload): CloudUser {
|
||||
return {
|
||||
...user,
|
||||
pfpUrl: pfp.pfpUrl ? pfpUrlWithHash(pfp.pfpUrl, pfp.pfpHash) : undefined,
|
||||
pfpHash: pfp.pfpHash,
|
||||
pfpHistory: pfp.pfpHistory,
|
||||
};
|
||||
}
|
||||
|
||||
async function applyPfpPayload(data: Record<string, unknown>): Promise<void> {
|
||||
const user = cloudAuth.state.user;
|
||||
if (!user) return;
|
||||
await cloudAuth.setUser(mergePfpIntoUser(user, parsePfpPayload(data)));
|
||||
if (user.id) await clearCloudPfpCache(user.id);
|
||||
}
|
||||
|
||||
async function bsplusPfpRequest(
|
||||
path: string,
|
||||
init?: RequestInit,
|
||||
): Promise<{ ok: boolean; data: Record<string, unknown>; error?: string }> {
|
||||
const token = await cloudAuth.getStoredToken();
|
||||
if (!token) return { ok: false, data: {}, error: "Not signed in to BetterSEQTA Cloud" };
|
||||
|
||||
const res = await fetch(`${BSPLUS_PFP}${path}`, {
|
||||
...init,
|
||||
headers: {
|
||||
Authorization: `Bearer ${token}`,
|
||||
...(init?.headers ?? {}),
|
||||
},
|
||||
});
|
||||
const data = await parseJson(res);
|
||||
if (!res.ok) {
|
||||
return {
|
||||
ok: false,
|
||||
data,
|
||||
error: (data.error as string) ?? `Request failed (${res.status})`,
|
||||
};
|
||||
}
|
||||
return { ok: true, data };
|
||||
}
|
||||
|
||||
async function prepareUploadFile(source: Blob): Promise<File> {
|
||||
if (!source.type.startsWith("image/")) throw new Error("Invalid file type");
|
||||
const limit = maxSourceBytes();
|
||||
if (source.size > limit) {
|
||||
const mb = Math.round(limit / (1024 * 1024));
|
||||
throw new Error(`File too large (max ${mb}MB)`);
|
||||
}
|
||||
|
||||
const scale = maxEdge / maxSide;
|
||||
const w = Math.max(1, Math.round(bitmap.width * scale));
|
||||
const h = Math.max(1, Math.round(bitmap.height * scale));
|
||||
const bitmap = await createImageBitmap(source);
|
||||
try {
|
||||
const size = Math.min(bitmap.width, bitmap.height);
|
||||
const sx = Math.round((bitmap.width - size) / 2);
|
||||
const sy = Math.round((bitmap.height - size) / 2);
|
||||
const canvas = new OffscreenCanvas(UPLOAD_MAX_EDGE, UPLOAD_MAX_EDGE);
|
||||
const ctx = canvas.getContext("2d");
|
||||
if (!ctx) throw new Error("Could not prepare image");
|
||||
ctx.drawImage(bitmap, sx, sy, size, size, 0, 0, UPLOAD_MAX_EDGE, UPLOAD_MAX_EDGE);
|
||||
|
||||
const canvas = new OffscreenCanvas(w, h);
|
||||
const ctx = canvas.getContext("2d");
|
||||
if (!ctx) {
|
||||
const webp = webpExportSupported();
|
||||
const mime = webp ? "image/webp" : "image/jpeg";
|
||||
const blob = await canvas.convertToBlob({ type: mime, quality: webp ? 0.88 : 0.85 });
|
||||
return new File([blob], webp ? "profile.webp" : "profile.jpg", { type: mime });
|
||||
} finally {
|
||||
bitmap.close();
|
||||
return blob;
|
||||
}
|
||||
ctx.drawImage(bitmap, 0, 0, w, h);
|
||||
bitmap.close();
|
||||
|
||||
const out = await canvas.convertToBlob({ type: "image/jpeg", quality: 0.85 });
|
||||
return out;
|
||||
}
|
||||
|
||||
export async function isUseCloudPfpEnabled(): Promise<boolean> {
|
||||
@@ -48,15 +141,6 @@ export async function isUseCloudPfpEnabled(): Promise<boolean> {
|
||||
return !!settings?.useCloudPfp;
|
||||
}
|
||||
|
||||
async function parseJsonResponse(r: Response): Promise<Record<string, unknown>> {
|
||||
const text = await r.text();
|
||||
try {
|
||||
return text ? (JSON.parse(text) as Record<string, unknown>) : {};
|
||||
} catch {
|
||||
return {};
|
||||
}
|
||||
}
|
||||
|
||||
function mergeMeIntoUser(current: CloudUser, data: Record<string, unknown>): CloudUser {
|
||||
const raw = (data.user as Record<string, unknown> | undefined) ?? data;
|
||||
const pfpUrlRaw = raw.pfpUrl as string | null | undefined;
|
||||
@@ -80,34 +164,30 @@ function mergeMeIntoUser(current: CloudUser, data: Record<string, unknown>): Clo
|
||||
};
|
||||
}
|
||||
|
||||
/** Fetch `/api/auth/me` and update stored user (pfpUrl / pfpHash). */
|
||||
export async function refreshCloudUserFromServer(): Promise<{
|
||||
success: boolean;
|
||||
error?: string;
|
||||
}> {
|
||||
export async function refreshCloudUserFromServer(): Promise<{ success: boolean; error?: string }> {
|
||||
if (!cloudAuth.state.isLoggedIn) {
|
||||
return { success: false, error: "Not signed in to BetterSEQTA Cloud" };
|
||||
}
|
||||
|
||||
const token = await cloudAuth.getStoredToken();
|
||||
if (!token) return { success: false, error: "Not signed in to BetterSEQTA Cloud" };
|
||||
|
||||
const current = cloudAuth.state.user;
|
||||
if (!current?.id) return { success: false, error: "No cloud user on this device" };
|
||||
if (!token || !current?.id) {
|
||||
return { success: false, error: "Not signed in to BetterSEQTA Cloud" };
|
||||
}
|
||||
|
||||
try {
|
||||
const res = await fetch(`${ACCOUNTS_BASE}/api/auth/me`, {
|
||||
headers: { Authorization: `Bearer ${token}` },
|
||||
});
|
||||
const data = await parseJsonResponse(res);
|
||||
const data = await parseJson(res);
|
||||
if (!res.ok) {
|
||||
return {
|
||||
success: false,
|
||||
error: (data.error as string) ?? `Could not refresh account (${res.status})`,
|
||||
};
|
||||
return { success: false, error: (data.error as string) ?? `Could not refresh account (${res.status})` };
|
||||
}
|
||||
|
||||
await cloudAuth.setUser(mergeMeIntoUser(current, data));
|
||||
let merged = mergeMeIntoUser(current, data);
|
||||
const pfp = await bsplusPfpRequest("");
|
||||
if (pfp.ok) merged = mergePfpIntoUser(merged, parsePfpPayload(pfp.data));
|
||||
await cloudAuth.setUser(merged);
|
||||
await clearCloudPfpCache(current.id);
|
||||
return { success: true };
|
||||
} catch (err) {
|
||||
return {
|
||||
@@ -117,138 +197,81 @@ export async function refreshCloudUserFromServer(): Promise<{
|
||||
}
|
||||
}
|
||||
|
||||
/** Pull cloud avatar metadata from the server and refresh the in-page profile image. */
|
||||
export async function pullCloudProfilePictureFromServer(): Promise<{
|
||||
success: boolean;
|
||||
error?: string;
|
||||
}> {
|
||||
const refreshed = await refreshCloudUserFromServer();
|
||||
if (!refreshed.success) return refreshed;
|
||||
export async function pullCloudProfilePictureFromServer(): Promise<{ success: boolean; error?: string }> {
|
||||
const current = cloudAuth.state.user;
|
||||
if (!cloudAuth.state.isLoggedIn || !current?.id) {
|
||||
return { success: false, error: "Not signed in to BetterSEQTA Cloud" };
|
||||
}
|
||||
|
||||
const userId = cloudAuth.state.user?.id;
|
||||
if (userId) await clearCloudPfpCache(userId);
|
||||
const pfp = await bsplusPfpRequest("");
|
||||
if (!pfp.ok) return { success: false, error: pfp.error ?? "Could not refresh cloud photo" };
|
||||
|
||||
await applyPfpPayload(pfp.data);
|
||||
await notifyProfilePictureChanged();
|
||||
return { success: true };
|
||||
}
|
||||
|
||||
/** When cloud PFP is enabled: upload local image if present, otherwise pull from server. */
|
||||
export async function onUseCloudPfpToggled(enabled: boolean): Promise<void> {
|
||||
if (!enabled) {
|
||||
await notifyProfilePictureChanged();
|
||||
return;
|
||||
}
|
||||
|
||||
const blob = await profileStore.getItem<Blob>("profile-picture");
|
||||
if (blob instanceof Blob) {
|
||||
await syncLocalProfilePictureToCloud();
|
||||
} else {
|
||||
await pullCloudProfilePictureFromServer();
|
||||
}
|
||||
if (blob instanceof Blob) await syncLocalProfilePictureToCloud();
|
||||
else await pullCloudProfilePictureFromServer();
|
||||
}
|
||||
|
||||
export async function syncLocalProfilePictureToCloud(): Promise<{
|
||||
success: boolean;
|
||||
error?: string;
|
||||
}> {
|
||||
if (!(await isUseCloudPfpEnabled()) || !cloudAuth.state.isLoggedIn) {
|
||||
return { success: true };
|
||||
export async function uploadCloudProfilePicture(source: Blob): Promise<{ success: boolean; error?: string }> {
|
||||
if (!cloudAuth.state.isLoggedIn) {
|
||||
return { success: false, error: "Not signed in to BetterSEQTA Cloud" };
|
||||
}
|
||||
|
||||
const token = await cloudAuth.getStoredToken();
|
||||
if (!token) return { success: false, error: "Not logged in" };
|
||||
|
||||
const user = cloudAuth.state.user;
|
||||
const userId = user?.id;
|
||||
|
||||
const blob = await profileStore.getItem<Blob>("profile-picture");
|
||||
|
||||
try {
|
||||
if (!blob || !(blob instanceof Blob)) {
|
||||
// No local upload — keep the server avatar; do not clear cloud.
|
||||
return { success: true };
|
||||
}
|
||||
|
||||
if (!blob.type.startsWith("image/")) {
|
||||
return { success: false, error: "Invalid file type" };
|
||||
}
|
||||
if (blob.size > 5 * 1024 * 1024) {
|
||||
return { success: false, error: "File too large (max 5MB)" };
|
||||
}
|
||||
|
||||
const uploadBlob = await downscaleForUpload(blob);
|
||||
const formData = new FormData();
|
||||
formData.append("file", uploadBlob, "profile-picture.jpg");
|
||||
|
||||
const res = await fetch(`${ACCOUNTS_BASE}/api/user/pfp`, {
|
||||
method: "POST",
|
||||
headers: { Authorization: `Bearer ${token}` },
|
||||
body: formData,
|
||||
});
|
||||
const data = await parseJsonResponse(res);
|
||||
if (!res.ok) {
|
||||
return { success: false, error: (data.error as string) ?? `Upload failed (${res.status})` };
|
||||
}
|
||||
|
||||
const pfpUrl = data.pfpUrl as string | undefined;
|
||||
const pfpHash = (data.pfpHash as string | null | undefined) ?? null;
|
||||
if (user && pfpUrl) {
|
||||
await cloudAuth.setUser({
|
||||
...user,
|
||||
pfpUrl: pfpUrlWithHash(pfpUrl, pfpHash),
|
||||
pfpHash,
|
||||
});
|
||||
}
|
||||
if (userId) await clearCloudPfpCache(userId);
|
||||
const file = await prepareUploadFile(source);
|
||||
const form = new FormData();
|
||||
form.append("file", file, file.name);
|
||||
form.append("clientProcessed", "true");
|
||||
form.append("preCropped", "true");
|
||||
const res = await bsplusPfpRequest("", { method: "POST", body: form });
|
||||
if (!res.ok) return { success: false, error: res.error ?? "Upload failed" };
|
||||
await applyPfpPayload(res.data);
|
||||
await notifyProfilePictureChanged();
|
||||
return { success: true };
|
||||
} catch (err) {
|
||||
return {
|
||||
success: false,
|
||||
error: err instanceof Error ? err.message : "Cloud profile picture sync failed",
|
||||
};
|
||||
return { success: false, error: err instanceof Error ? err.message : "Upload failed" };
|
||||
}
|
||||
}
|
||||
|
||||
/** Upload local image to cloud, or clear cloud only when explicitly removing local image. */
|
||||
export async function clearCloudProfilePicture(): Promise<{
|
||||
success: boolean;
|
||||
error?: string;
|
||||
}> {
|
||||
export async function syncLocalProfilePictureToCloud(): Promise<{ success: boolean; error?: string }> {
|
||||
if (!(await isUseCloudPfpEnabled()) || !cloudAuth.state.isLoggedIn) return { success: true };
|
||||
const blob = await profileStore.getItem<Blob>("profile-picture");
|
||||
if (!(blob instanceof Blob)) return { success: true };
|
||||
return uploadCloudProfilePicture(blob);
|
||||
}
|
||||
|
||||
export async function clearCloudProfilePicture(): Promise<{ success: boolean; error?: string }> {
|
||||
if (!cloudAuth.state.isLoggedIn) return { success: true };
|
||||
const res = await bsplusPfpRequest("/clear", { method: "POST" });
|
||||
if (!res.ok) return { success: false, error: res.error ?? "Clear failed" };
|
||||
await applyPfpPayload(res.data);
|
||||
await notifyProfilePictureChanged();
|
||||
return { success: true };
|
||||
}
|
||||
|
||||
const token = await cloudAuth.getStoredToken();
|
||||
if (!token) return { success: false, error: "Not logged in" };
|
||||
|
||||
const user = cloudAuth.state.user;
|
||||
const userId = user?.id;
|
||||
|
||||
try {
|
||||
const res = await fetch(`${ACCOUNTS_BASE}/api/user/pfp/clear`, {
|
||||
method: "POST",
|
||||
headers: {
|
||||
Authorization: `Bearer ${token}`,
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
body: JSON.stringify({}),
|
||||
});
|
||||
const data = await parseJsonResponse(res);
|
||||
if (!res.ok) {
|
||||
return { success: false, error: (data.error as string) ?? `Clear failed (${res.status})` };
|
||||
}
|
||||
if (user) {
|
||||
await cloudAuth.setUser({ ...user, pfpUrl: undefined, pfpHash: null });
|
||||
}
|
||||
if (userId) await clearCloudPfpCache(userId);
|
||||
return { success: true };
|
||||
} catch (err) {
|
||||
return {
|
||||
success: false,
|
||||
error: err instanceof Error ? err.message : "Cloud profile picture clear failed",
|
||||
};
|
||||
export async function revertCloudProfilePicture(historyId: string): Promise<{ success: boolean; error?: string }> {
|
||||
if (!cloudAuth.state.isLoggedIn) {
|
||||
return { success: false, error: "Not signed in to BetterSEQTA Cloud" };
|
||||
}
|
||||
const res = await bsplusPfpRequest("/revert", {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ historyId }),
|
||||
});
|
||||
if (!res.ok) return { success: false, error: res.error ?? "Revert failed" };
|
||||
await applyPfpPayload(res.data);
|
||||
await notifyProfilePictureChanged();
|
||||
return { success: true };
|
||||
}
|
||||
|
||||
/** Notify SEQTA content scripts to refresh the in-page profile image. */
|
||||
export async function notifyProfilePictureChanged(): Promise<void> {
|
||||
const revision = Date.now();
|
||||
await browser.storage.local.set({ profile_picture_revision: revision });
|
||||
await browser.storage.local.set({ profile_picture_revision: Date.now() });
|
||||
}
|
||||
@@ -1,6 +1,20 @@
|
||||
import browser from "webextension-polyfill";
|
||||
import isEqual from "@/seqta/utils/isEqual";
|
||||
import { BSPLUS_CALENDAR_SYNC_IN_PROGRESS_KEY } from "@/seqta/utils/calendarSync/settings";
|
||||
import {
|
||||
BSPLUS_CAMPAIGN_SEEN_KEY,
|
||||
BSPLUS_FEATURES_HIDDEN_UNTIL_VERSION_KEY,
|
||||
BSPLUS_INSTALL_REGISTERED_AT_KEY,
|
||||
BSPLUS_LOCAL_OVERRIDE_ONOFF_KEY,
|
||||
BSPLUS_REMOTE_CONFIG_ETAG_KEY,
|
||||
BSPLUS_REMOTE_CONFIG_FETCHED_AT_KEY,
|
||||
BSPLUS_REMOTE_CONFIG_LAST_HOSTNAME_KEY,
|
||||
BSPLUS_REMOTE_CONFIG_SNAPSHOT_KEY,
|
||||
BSPLUS_REMOTE_LAST_PRIMARY_OK_KEY,
|
||||
BSPLUS_REMOTE_THEME_BEFORE_V1_KEY,
|
||||
BSPLUS_REMOTE_THEME_STATE_V1_KEY,
|
||||
BSPLUS_REMOTE_THEME_USER_OFF_KEY,
|
||||
} from "@/seqta/utils/remoteConfig/storageKeys";
|
||||
|
||||
/** Matches the contract in docs/CLOUD_SETTINGS_SYNC_SERVER.md */
|
||||
export const CLOUD_SETTINGS_SYNC_SCHEMA_VERSION = 1;
|
||||
@@ -44,6 +58,18 @@ export const KEYS_OMITTED_FROM_CLOUD_UPLOAD = [
|
||||
"bsplus_install_id",
|
||||
/** Pending feedback ids awaiting a reply notification — device-local. */
|
||||
"bsplus_pending_feedback_ids",
|
||||
BSPLUS_REMOTE_CONFIG_SNAPSHOT_KEY,
|
||||
BSPLUS_REMOTE_CONFIG_ETAG_KEY,
|
||||
BSPLUS_CAMPAIGN_SEEN_KEY,
|
||||
BSPLUS_LOCAL_OVERRIDE_ONOFF_KEY,
|
||||
BSPLUS_FEATURES_HIDDEN_UNTIL_VERSION_KEY,
|
||||
BSPLUS_INSTALL_REGISTERED_AT_KEY,
|
||||
BSPLUS_REMOTE_CONFIG_FETCHED_AT_KEY,
|
||||
BSPLUS_REMOTE_CONFIG_LAST_HOSTNAME_KEY,
|
||||
BSPLUS_REMOTE_LAST_PRIMARY_OK_KEY,
|
||||
BSPLUS_REMOTE_THEME_BEFORE_V1_KEY,
|
||||
BSPLUS_REMOTE_THEME_STATE_V1_KEY,
|
||||
BSPLUS_REMOTE_THEME_USER_OFF_KEY,
|
||||
BSPLUS_CALENDAR_SYNC_IN_PROGRESS_KEY,
|
||||
] as const;
|
||||
|
||||
@@ -68,6 +94,9 @@ const CLIENT_ONLY_CLOUD_KEYS_EXACT = [
|
||||
"bsplus_lastCloudPoll",
|
||||
BSPLUS_PENDING_THEME_ENSURE_AFTER_CLOUD_KEY,
|
||||
BSPLUS_CALENDAR_SYNC_IN_PROGRESS_KEY,
|
||||
"bsplus_remote_theme_before_v1",
|
||||
"bsplus_remote_theme_state_v1",
|
||||
"bsplus_remote_theme_user_off",
|
||||
] as const;
|
||||
|
||||
/** After restoring from cloud, keep local session so the user stays signed in. */
|
||||
@@ -338,6 +367,19 @@ export function migrateLegacyToPluginSettings(data: Record<string, unknown>): Re
|
||||
return result;
|
||||
}
|
||||
|
||||
/**
|
||||
* Apply a flat settings record (e.g. remote theme restore snapshot).
|
||||
*/
|
||||
export async function applyLocalSettingsRecord(flat: Record<string, unknown>): Promise<void> {
|
||||
await applyDownloadedEnvelope(flat);
|
||||
}
|
||||
|
||||
/** Snapshot of keys eligible for cloud upload — used for remote theme restore capture. */
|
||||
export async function captureSyncableSettingsSnapshot(): Promise<Record<string, unknown>> {
|
||||
const all = (await browser.storage.local.get()) as Record<string, unknown>;
|
||||
return normalizeStorageForSync(all);
|
||||
}
|
||||
|
||||
/**
|
||||
* Apply the downloaded cloud snapshot by setting each key individually,
|
||||
* preserving auth keys and device-only sensitive caches.
|
||||
|
||||
@@ -24,6 +24,7 @@ const OPTIONAL_UNSET_MEANS_DEFAULT_KEYS = [
|
||||
"selectedFont",
|
||||
"privacyStatementShown",
|
||||
"privacyStatementLastUpdated",
|
||||
"termsOfServiceLastAccepted",
|
||||
"bsCloudAutoSyncAnnouncementShown",
|
||||
"coursesAssessmentsFixPopupShown",
|
||||
"themeOfTheMonthDismissedMonth",
|
||||
|
||||
@@ -16,6 +16,7 @@ import {
|
||||
type FeedbackProduct,
|
||||
} from "./constants";
|
||||
import { getOrCreateInstallId } from "./installId";
|
||||
import { isRemoteFeedbackSubmitDisabled } from "@/seqta/utils/remoteConfig/runtime";
|
||||
|
||||
export class FeedbackApiError extends Error {
|
||||
constructor(
|
||||
@@ -144,6 +145,14 @@ export async function submitFeedback(form: FeedbackFormInput): Promise<{ id: str
|
||||
const err = validateFeedbackForm(form);
|
||||
if (err) throw new FeedbackApiError(err, 422);
|
||||
|
||||
if (isRemoteFeedbackSubmitDisabled()) {
|
||||
throw new FeedbackApiError(
|
||||
"Feedback submissions are temporarily disabled.",
|
||||
503,
|
||||
"REMOTE_DISABLED",
|
||||
);
|
||||
}
|
||||
|
||||
const installId = await getOrCreateInstallId();
|
||||
const host = getInstanceHostname();
|
||||
const product: FeedbackProduct = isSeqtaEngageExperience() ? "engage" : "learn";
|
||||
|
||||
@@ -0,0 +1,23 @@
|
||||
import { badgesForTitlebar } from "./founderBadges";
|
||||
|
||||
describe("badgesForTitlebar", () => {
|
||||
it("shows one founder plus achievements from API lists", () => {
|
||||
expect(
|
||||
badgesForTitlebar(
|
||||
[
|
||||
{ key: "founder_1000", label: "Thousand Club" },
|
||||
{ key: "theme_submitter", label: "Theme Submitter" },
|
||||
],
|
||||
842,
|
||||
).map((b) => b.key),
|
||||
).toEqual(["founder_1000", "theme_submitter"]);
|
||||
});
|
||||
|
||||
it("derives founder from signup_number when the API omits the founder row", () => {
|
||||
expect(
|
||||
badgesForTitlebar([{ key: "theme_submitter", label: "Theme Submitter" }], 42).map(
|
||||
(b) => b.key,
|
||||
),
|
||||
).toEqual(["founder_50", "theme_submitter"]);
|
||||
});
|
||||
});
|
||||
@@ -1,4 +1,4 @@
|
||||
/** Founder badge tiers — keep in sync with betterseqta-accounts/utils/badges.ts */
|
||||
/** Keep in sync with betterseqta-accounts `utils/badges.ts` / `utils/badgeVisuals.ts`. */
|
||||
|
||||
export const BADGE_TIERS = [
|
||||
{
|
||||
@@ -83,38 +83,57 @@ export const BADGE_TIERS = [
|
||||
},
|
||||
] as const;
|
||||
|
||||
export const ACHIEVEMENT_BADGES = [
|
||||
{
|
||||
key: "theme_submitter",
|
||||
label: "Theme Submitter",
|
||||
rankLabel: "Community",
|
||||
description:
|
||||
"Submitted a custom theme that was accepted into the BetterSEQTA theme gallery.",
|
||||
base: "#5b21b6",
|
||||
blobs: ["rgba(139,92,246,0.52)", "rgba(124,58,237,0.46)", "rgba(196,181,253,0.4)"],
|
||||
icon: "swatch",
|
||||
},
|
||||
] as const;
|
||||
|
||||
export type BadgeKey = (typeof BADGE_TIERS)[number]["key"];
|
||||
|
||||
export type FounderBadgeItem = {
|
||||
export type BadgeItem = {
|
||||
key: string;
|
||||
label: string;
|
||||
awarded_at?: number;
|
||||
};
|
||||
|
||||
type BadgeVisual = (typeof BADGE_TIERS)[number] | (typeof ACHIEVEMENT_BADGES)[number];
|
||||
|
||||
const TIER_BY_KEY = new Map(BADGE_TIERS.map((t) => [t.key, t]));
|
||||
const VISUAL_BY_KEY = new Map<string, BadgeVisual>([
|
||||
...BADGE_TIERS.map((t) => [t.key, t] as const),
|
||||
...ACHIEVEMENT_BADGES.map((b) => [b.key, b] as const),
|
||||
]);
|
||||
|
||||
export function tierForBadgeKey(key: string) {
|
||||
return TIER_BY_KEY.get(key as BadgeKey);
|
||||
}
|
||||
const UNKNOWN_ACHIEVEMENT_VISUAL = {
|
||||
rankLabel: "Achievement",
|
||||
description: "Earned on your BetterSEQTA Cloud account.",
|
||||
base: "#334155",
|
||||
blobs: ["rgba(100,116,139,0.5)", "rgba(71,85,105,0.44)", "rgba(148,163,184,0.38)"],
|
||||
icon: "sparkles",
|
||||
} as const;
|
||||
|
||||
export function primaryFounderBadgeKey(signupNumber: number): BadgeKey | null {
|
||||
const tier = BADGE_TIERS.find((t) => signupNumber <= t.threshold);
|
||||
return tier?.key ?? null;
|
||||
}
|
||||
|
||||
export function pickPrimaryFounderBadge(
|
||||
badges: FounderBadgeItem[],
|
||||
function primaryFounderBadge(
|
||||
badges: BadgeItem[],
|
||||
signupNumber?: number | null,
|
||||
): FounderBadgeItem | null {
|
||||
): BadgeItem | null {
|
||||
const fromApi = badges.find((b) => b.key.startsWith("founder_"));
|
||||
if (fromApi) return fromApi;
|
||||
|
||||
if (signupNumber != null) {
|
||||
const key = primaryFounderBadgeKey(signupNumber);
|
||||
if (!key) return null;
|
||||
return badges.find((b) => b.key === key) ?? { key, label: TIER_BY_KEY.get(key)?.label ?? key };
|
||||
const tier = BADGE_TIERS.find((t) => signupNumber <= t.threshold);
|
||||
if (!tier) return null;
|
||||
return badges.find((b) => b.key === tier.key) ?? { key: tier.key, label: tier.label };
|
||||
}
|
||||
|
||||
if (badges.length === 0) return null;
|
||||
|
||||
let best: FounderBadgeItem | null = null;
|
||||
let best: BadgeItem | null = null;
|
||||
let bestThreshold = Infinity;
|
||||
for (const badge of badges) {
|
||||
const tier = TIER_BY_KEY.get(badge.key as BadgeKey);
|
||||
@@ -126,6 +145,23 @@ export function pickPrimaryFounderBadge(
|
||||
return best;
|
||||
}
|
||||
|
||||
/** Founder pill (at most one) then achievement pills — matches Accounts display rules. */
|
||||
export function badgesForTitlebar(
|
||||
badges: BadgeItem[],
|
||||
signupNumber?: number | null,
|
||||
): BadgeItem[] {
|
||||
const founder = primaryFounderBadge(badges, signupNumber);
|
||||
const achievements = badges.filter((b) => !b.key.startsWith("founder_"));
|
||||
return founder ? [founder, ...achievements] : achievements;
|
||||
}
|
||||
|
||||
export function badgeVisualForKey(key: string, labelFallback = key): BadgeVisual | null {
|
||||
const known = VISUAL_BY_KEY.get(key);
|
||||
if (known) return known;
|
||||
if (key.startsWith("founder_")) return null;
|
||||
return { key, label: labelFallback, ...UNKNOWN_ACHIEVEMENT_VISUAL };
|
||||
}
|
||||
|
||||
const ICON_PATHS: Record<string, string> = {
|
||||
sparkles:
|
||||
"M9.813 15.904L9 18.75l-.813-2.846a4.5 4.5 0 00-3.09-3.09L2.25 12l2.846-.813a4.5 4.5 0 003.09-3.09L9 5.25l.813 2.846a4.5 4.5 0 003.09 3.09L15.75 12l-2.846.813a4.5 4.5 0 00-3.09 3.09zM18.259 8.715L18 9.75l-.259-1.035a3.375 3.375 0 00-2.455-2.456L14.25 6l1.036-.259a3.375 3.375 0 002.455-2.456L18 2.25l.259 1.035a3.375 3.375 0 002.456 2.456L21.75 6l-1.035.259a3.375 3.375 0 00-2.456 2.456zM16.894 20.567L16.5 21.75l-.394-1.183a2.25 2.25 0 00-1.423-1.423L13.5 18.75l1.183-.394a2.25 2.25 0 001.423-1.423l.394-1.183.394 1.183a2.25 2.25 0 001.423 1.423l1.183.394-1.183.394a2.25 2.25 0 00-1.423 1.423z",
|
||||
@@ -133,33 +169,37 @@ const ICON_PATHS: Record<string, string> = {
|
||||
trophy:
|
||||
"M16.5 18.75h-9m9 0a3 3 0 013 3h-15a3 3 0 013-3m9 0v-3.375c0-.621-.503-1.125-1.125-1.125h-.871M7.5 18.75v-3.375c0-.621.504-1.125 1.125-1.125h.872m5.007 0H9.497m5.007 0a7.454 7.454 0 01-.982-3.172M9.497 14.25a7.454 7.454 0 00.981-3.172M5.25 4.236c-.982.143-1.954.317-2.916.52A6.003 6.003 0 007.73 9.728M5.25 4.236V4.5c0 2.108.966 3.99 2.48 5.228M5.25 4.236V2.721C7.456 2.41 9.71 2.25 12 2.25c2.291 0 4.545.16 6.75.47v1.516M7.73 9.728a6.726 6.726 0 002.748 1.35m8.272-6.842V4.5c0 2.108-.966 3.99-2.48 5.228m2.48-5.492a46.32 46.32 0 012.916.52 6.003 6.003 0 01-5.395 4.972m0 0a6.726 6.726 0 01-2.749 1.35m0 0a6.726 6.726 0 01-3.128 0m3.128 0a6.726 6.726 0 01-3.128 0",
|
||||
fire: "M15.362 5.214A8.252 8.252 0 0112 21 8.25 8.25 0 016.038 7.048 8.287 8.287 0 009 9.6a8.983 8.983 0 013.361-6.867 8.21 8.21 0 003 2.48zM12 18a3.75 3.75 0 00.495-7.467 5.99 5.99 0 00-1.925 3.546 5.974 5.974 0 01-2.133-1A3.75 3.75 0 0012 18z",
|
||||
swatch:
|
||||
"M4.098 19.902a3.75 3.75 0 005.304 0l6.401-6.402M6.75 21A3.75 3.75 0 013 17.25V4.125C3 3.504 3.504 3 4.125 3h5.25c.621 0 1.125.504 1.125 1.125v4.072M6.75 21a3.75 3.75 0 003.75-3.75V8.197M6.75 21h13.125c.621 0 1.125-.504 1.125-1.125v-5.25c0-.621-.504-1.125-1.125-1.125h-4.072M10.5 8.197l2.88-2.88c.438-.439 1.15-.439 1.59 0l3.712 3.713c.44.44.44 1.152 0 1.59l-2.879 2.88M6.75 17.25h.008v.008H6.75v-.008z",
|
||||
};
|
||||
|
||||
export function badgeIconSvg(icon: string, size = 15): string {
|
||||
function badgeIconSvg(icon: string, size = 15): string {
|
||||
const path = ICON_PATHS[icon] ?? ICON_PATHS.sparkles;
|
||||
return `<svg class="bsplus-founder-badge__icon" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="currentColor" width="${size}" height="${size}" aria-hidden="true"><path d="${path}"/></svg>`;
|
||||
}
|
||||
|
||||
export function tierBlobStyle(tier: (typeof BADGE_TIERS)[number]): string {
|
||||
function badgeBlobStyle(visual: Pick<BadgeVisual, "base" | "blobs">): string {
|
||||
return [
|
||||
`--badge-base:${tier.base}`,
|
||||
`--badge-blob-a:${tier.blobs[0]}`,
|
||||
`--badge-blob-b:${tier.blobs[1]}`,
|
||||
`--badge-blob-c:${tier.blobs[2]}`,
|
||||
`--badge-base:${visual.base}`,
|
||||
`--badge-blob-a:${visual.blobs[0]}`,
|
||||
`--badge-blob-b:${visual.blobs[1]}`,
|
||||
`--badge-blob-c:${visual.blobs[2]}`,
|
||||
].join(";");
|
||||
}
|
||||
|
||||
export function founderBadgeChipHtml(
|
||||
badge: FounderBadgeItem,
|
||||
badge: BadgeItem,
|
||||
options?: { hero?: boolean; titlebar?: boolean },
|
||||
): string {
|
||||
const tier = tierForBadgeKey(badge.key);
|
||||
if (!tier) return "";
|
||||
const visual = badgeVisualForKey(badge.key, badge.label);
|
||||
if (!visual) return "";
|
||||
|
||||
const hero = options?.hero ?? false;
|
||||
const titlebar = options?.titlebar ?? false;
|
||||
const mods = `${hero ? " bsplus-founder-badge--hero" : ""}${titlebar ? " bsplus-founder-badge--titlebar" : ""}`;
|
||||
const icon = titlebar ? "" : badgeIconSvg(tier.icon, hero ? 20 : 15);
|
||||
const icon = titlebar ? "" : badgeIconSvg(visual.icon, hero ? 20 : 15);
|
||||
|
||||
return `<button type="button" class="bsplus-founder-badge${mods}" data-tier="${badge.key}" style="${tierBlobStyle(tier)}"><span class="bsplus-founder-badge__glass"><span class="bsplus-founder-badge__blobs" aria-hidden="true"></span><span class="bsplus-founder-badge__content">${icon}<span class="bsplus-founder-badge__label">${badge.label}</span></span></span></button>`;
|
||||
return `<button type="button" class="bsplus-founder-badge${mods}" data-tier="${badge.key}" style="${badgeBlobStyle(visual)}"><span class="bsplus-founder-badge__glass"><span class="bsplus-founder-badge__blobs" aria-hidden="true"></span><span class="bsplus-founder-badge__content">${icon}<span class="bsplus-founder-badge__label">${badge.label || visual.label}</span></span></span></button>`;
|
||||
}
|
||||
|
||||
export { badgeBlobStyle };
|
||||
@@ -35,6 +35,7 @@ const SETTINGS_STORAGE_KEYS = [
|
||||
"mockNotices",
|
||||
"hideSensitiveContent",
|
||||
"privacyStatementLastUpdated",
|
||||
"termsOfServiceLastAccepted",
|
||||
"themeOfTheMonthDismissedMonth",
|
||||
"themeOfTheMonthLastSeenId",
|
||||
...PLUGIN_SETTINGS_KEYS,
|
||||
@@ -52,6 +53,12 @@ const EXCLUDED_FROM_SETTINGS_SURFACE = new Set([
|
||||
"cloudUsername",
|
||||
"bsplus_install_id",
|
||||
"bsplus_pending_feedback_ids",
|
||||
"bsplus_remote_config_snapshot",
|
||||
"bsplus_remote_config_etag",
|
||||
"bsplus_campaign_seen",
|
||||
"bsplus_local_override_onoff",
|
||||
"bsplus_features_hidden_until_version",
|
||||
"bsplus_install_registered_at",
|
||||
]);
|
||||
|
||||
function isExcludedSettingsKey(key: string): boolean {
|
||||
|
||||
@@ -14,8 +14,11 @@ export type ThemePageSyncInput = {
|
||||
images?: Array<{ variableName: string; blob: Blob }>;
|
||||
customCss?: string;
|
||||
previewCss?: string;
|
||||
overlayCss?: string;
|
||||
overlayImages?: Array<{ variableName: string; blob: Blob }>;
|
||||
clear?: boolean;
|
||||
clearPreview?: boolean;
|
||||
clearOverlay?: boolean;
|
||||
};
|
||||
|
||||
export function installThemeImagePagePatch(): void {
|
||||
@@ -59,7 +62,22 @@ function preserveCustomSidebarActive(css: string): string {
|
||||
return css.replace(/\.active(?![\w-])/g, ":is(.active, .bsplus-active)");
|
||||
}
|
||||
|
||||
async function encodeImages(images?: Array<{ variableName: string; blob: Blob }>) {
|
||||
if (images === undefined) return undefined;
|
||||
return Promise.all(
|
||||
images.map(async (image) => ({
|
||||
variableName: image.variableName,
|
||||
data: await blobToBase64Data(image.blob),
|
||||
mime: image.blob.type || "image/png",
|
||||
})),
|
||||
);
|
||||
}
|
||||
|
||||
export async function syncThemeToPage(input: ThemePageSyncInput): Promise<void> {
|
||||
if (input.clearOverlay) {
|
||||
sendPayload({ clearOverlay: true });
|
||||
return;
|
||||
}
|
||||
if (input.clear) {
|
||||
sendPayload({ clear: true });
|
||||
return;
|
||||
@@ -73,16 +91,15 @@ export async function syncThemeToPage(input: ThemePageSyncInput): Promise<void>
|
||||
if (input.previewCss !== undefined) {
|
||||
payload.previewCss = preserveCustomSidebarActive(input.previewCss);
|
||||
}
|
||||
if (input.images !== undefined) {
|
||||
payload.images = await Promise.all(
|
||||
input.images.map(async (image) => ({
|
||||
variableName: image.variableName,
|
||||
data: await blobToBase64Data(image.blob),
|
||||
mime: image.blob.type || "image/png",
|
||||
})),
|
||||
);
|
||||
if (input.overlayCss !== undefined) {
|
||||
payload.overlayCss = preserveCustomSidebarActive(input.overlayCss);
|
||||
}
|
||||
|
||||
const images = await encodeImages(input.images);
|
||||
if (images !== undefined) payload.images = images;
|
||||
const overlayImages = await encodeImages(input.overlayImages);
|
||||
if (overlayImages !== undefined) payload.overlayImages = overlayImages;
|
||||
|
||||
if (Object.keys(payload).length === 0) return;
|
||||
sendPayload(payload);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,146 @@
|
||||
import {
|
||||
computeEffectiveEnabled,
|
||||
isRemoteFeatureAllowed,
|
||||
resolveFeatureMode,
|
||||
} from "./apply";
|
||||
import { DEFAULT_REMOTE_CONFIG } from "./normalize";
|
||||
import type { RemoteConfigSnapshot } from "./types";
|
||||
|
||||
function snapshot(partial: Partial<RemoteConfigSnapshot>): RemoteConfigSnapshot {
|
||||
return {
|
||||
...DEFAULT_REMOTE_CONFIG,
|
||||
...partial,
|
||||
global: { ...DEFAULT_REMOTE_CONFIG.global, ...partial.global },
|
||||
features: { ...DEFAULT_REMOTE_CONFIG.features, ...partial.features },
|
||||
};
|
||||
}
|
||||
|
||||
describe("computeEffectiveEnabled", () => {
|
||||
it("respects user master toggle", () => {
|
||||
expect(computeEffectiveEnabled(false, snapshot({}), false)).toBe(false);
|
||||
});
|
||||
|
||||
it("allows when remote mode is on", () => {
|
||||
expect(computeEffectiveEnabled(true, snapshot({ global: { mode: "on" } }), false)).toBe(
|
||||
true,
|
||||
);
|
||||
});
|
||||
|
||||
it("blocks when remote kill without local override", () => {
|
||||
expect(
|
||||
computeEffectiveEnabled(
|
||||
true,
|
||||
snapshot({ global: { mode: "off", allowLocalOverride: true } }),
|
||||
false,
|
||||
),
|
||||
).toBe(false);
|
||||
});
|
||||
|
||||
it("allows local override when permitted", () => {
|
||||
expect(
|
||||
computeEffectiveEnabled(
|
||||
true,
|
||||
snapshot({ global: { mode: "off", allowLocalOverride: true } }),
|
||||
true,
|
||||
),
|
||||
).toBe(true);
|
||||
});
|
||||
|
||||
it("ignores local override when server forbids it", () => {
|
||||
expect(
|
||||
computeEffectiveEnabled(
|
||||
true,
|
||||
snapshot({ global: { mode: "off", allowLocalOverride: false } }),
|
||||
true,
|
||||
),
|
||||
).toBe(false);
|
||||
});
|
||||
|
||||
it("blocks hostname on denylist unless local override", () => {
|
||||
const snap = snapshot({
|
||||
global: {
|
||||
mode: "on",
|
||||
hostnamePolicy: { mode: "denylist", suffixes: ["blocked.edu.au"] },
|
||||
},
|
||||
});
|
||||
expect(computeEffectiveEnabled(true, snap, false, "learn.blocked.edu.au")).toBe(false);
|
||||
expect(computeEffectiveEnabled(true, snap, true, "learn.blocked.edu.au")).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
describe("resolveFeatureMode", () => {
|
||||
it("treats temp_hide as hide only for matching config version", () => {
|
||||
const snap = snapshot({
|
||||
configVersion: "42",
|
||||
features: { "page.news": { mode: "temp_hide" } },
|
||||
});
|
||||
expect(resolveFeatureMode("page.news", snap, { "page.news": "41" })).toBe("allow");
|
||||
expect(resolveFeatureMode("page.news", snap, { "page.news": "42" })).toBe("hide");
|
||||
});
|
||||
|
||||
it("maps banner to allowed but not hide", () => {
|
||||
const snap = snapshot({
|
||||
features: { "plugin.grade-analytics": { mode: "banner" } },
|
||||
});
|
||||
expect(isRemoteFeatureAllowed("plugin.grade-analytics", snap)).toBe(true);
|
||||
expect(resolveFeatureMode("plugin.grade-analytics", snap)).toBe("banner");
|
||||
});
|
||||
});
|
||||
|
||||
describe("SEQTA boot decision", () => {
|
||||
it("would skip monofile when effective enablement is false", () => {
|
||||
const shouldBootFull = computeEffectiveEnabled(
|
||||
true,
|
||||
snapshot({ global: { mode: "off", allowLocalOverride: true } }),
|
||||
false,
|
||||
);
|
||||
expect(shouldBootFull).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe("hydrateRemoteConfigFromStorage", () => {
|
||||
it("requests cached snapshot before background refresh when storage is empty", async () => {
|
||||
jest.resetModules();
|
||||
jest.doMock("webextension-polyfill", () => ({
|
||||
storage: {
|
||||
local: {
|
||||
get: jest.fn(async () => ({})),
|
||||
set: jest.fn(async () => {}),
|
||||
},
|
||||
onChanged: { addListener: jest.fn() },
|
||||
},
|
||||
runtime: {
|
||||
getManifest: () => ({ version: "3.7.6" }),
|
||||
sendMessage: jest.fn(async (msg: { type?: string }) =>
|
||||
msg.type === "getRemoteConfigSnapshot"
|
||||
? { snapshot: { configVersion: "1", global: { mode: "on" }, features: {}, campaigns: [] } }
|
||||
: {},
|
||||
),
|
||||
},
|
||||
}));
|
||||
jest.doMock("@/seqta/utils/listeners/SettingsState", () => ({
|
||||
settingsState: { onoff: true },
|
||||
}));
|
||||
jest.doMock("./routeGate", () => ({
|
||||
syncRouteEnhancementChrome: jest.fn(async () => {}),
|
||||
}));
|
||||
jest.doMock("./remoteTheme", () => ({
|
||||
scheduleReconcileRemoteTheme: jest.fn(),
|
||||
dismissOptionalRemoteTheme: jest.fn(),
|
||||
resolveEffectiveRemoteTheme: jest.fn(),
|
||||
}));
|
||||
const { hydrateRemoteConfigFromStorage, notifyRemoteConfigPageContext } = await import("./runtime");
|
||||
await hydrateRemoteConfigFromStorage();
|
||||
notifyRemoteConfigPageContext("learn.example.edu.au");
|
||||
const browser = jest.requireMock("webextension-polyfill");
|
||||
const types = browser.runtime.sendMessage.mock.calls.map(
|
||||
(c: [{ type?: string }]) => c[0]?.type,
|
||||
);
|
||||
expect(types).toContain("getRemoteConfigSnapshot");
|
||||
expect(types).toContain("setRemoteConfigPageContext");
|
||||
expect(types).toContain("refreshRemoteConfig");
|
||||
expect(types.indexOf("getRemoteConfigSnapshot")).toBeLessThan(
|
||||
types.indexOf("refreshRemoteConfig"),
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,112 @@
|
||||
import type { FeatureMode, RemoteConfigSnapshot, RemoteFeatureGate } from "./types";
|
||||
import { DEFAULT_REMOTE_CONFIG } from "./normalize";
|
||||
import semver from "semver";
|
||||
import browser from "webextension-polyfill";
|
||||
|
||||
function normalizeHostname(hostname: string): string {
|
||||
return hostname.trim().toLowerCase().replace(/\.$/, "");
|
||||
}
|
||||
|
||||
export function isHostnameAllowedByPolicy(
|
||||
snapshot: RemoteConfigSnapshot,
|
||||
hostname: string,
|
||||
): boolean {
|
||||
const policy = snapshot.global.hostnamePolicy;
|
||||
if (!policy?.suffixes?.length) return true;
|
||||
const host = normalizeHostname(hostname);
|
||||
const suffixes = policy.suffixes.map((s) => normalizeHostname(s));
|
||||
const matches = suffixes.some(
|
||||
(suffix) => host === suffix || host.endsWith(`.${suffix}`),
|
||||
);
|
||||
if (policy.mode === "denylist") return !matches;
|
||||
if (policy.mode === "allowlist") return matches;
|
||||
return true;
|
||||
}
|
||||
|
||||
export function isExtensionVersionBelowMinimum(snapshot: RemoteConfigSnapshot): boolean {
|
||||
const min = snapshot.global.minExtensionVersion;
|
||||
if (!min || !semver.valid(min)) return false;
|
||||
const current = browser.runtime.getManifest().version;
|
||||
if (!semver.valid(current)) return false;
|
||||
return semver.lt(current, min);
|
||||
}
|
||||
|
||||
export function getMinVersionStatusMessage(snapshot: RemoteConfigSnapshot): string | null {
|
||||
if (!isExtensionVersionBelowMinimum(snapshot)) return null;
|
||||
const min = snapshot.global.minExtensionVersion;
|
||||
const url = snapshot.global.forceUpdateUrl;
|
||||
const base = `BetterSEQTA+ ${min ?? "a newer version"} or later is required for full features.`;
|
||||
return url ? `${base} Update: ${url}` : base;
|
||||
}
|
||||
|
||||
export function computeEffectiveEnabled(
|
||||
userOnoff: boolean,
|
||||
snapshot: RemoteConfigSnapshot,
|
||||
localOverride: boolean,
|
||||
hostname = typeof location !== "undefined" ? location.hostname : "",
|
||||
): boolean {
|
||||
if (!userOnoff) return false;
|
||||
if (!isHostnameAllowedByPolicy(snapshot, hostname)) {
|
||||
if (snapshot.global.allowLocalOverride === false) return false;
|
||||
return localOverride;
|
||||
}
|
||||
if (snapshot.global.mode !== "off") return true;
|
||||
if (snapshot.global.allowLocalOverride === false) return false;
|
||||
return localOverride;
|
||||
}
|
||||
|
||||
export function getRemoteStatusMessage(snapshot: RemoteConfigSnapshot): string | null {
|
||||
const minMsg = getMinVersionStatusMessage(snapshot);
|
||||
if (minMsg) return minMsg;
|
||||
if (snapshot.global.mode === "off" && snapshot.global.statusMessage) {
|
||||
return snapshot.global.statusMessage;
|
||||
}
|
||||
const maint = snapshot.global.maintenance;
|
||||
if (maint?.body) return maint.body;
|
||||
if (maint?.title) return maint.title;
|
||||
if (!isHostnameAllowedByPolicy(snapshot, typeof location !== "undefined" ? location.hostname : "")) {
|
||||
return "BetterSEQTA+ is not enabled for this SEQTA site.";
|
||||
}
|
||||
return snapshot.global.mode === "off"
|
||||
? "BetterSEQTA+ is temporarily disabled by the site operator."
|
||||
: null;
|
||||
}
|
||||
|
||||
export function resolveFeatureMode(
|
||||
key: string,
|
||||
snapshot: RemoteConfigSnapshot = DEFAULT_REMOTE_CONFIG,
|
||||
hiddenUntilVersion: Record<string, string> = {},
|
||||
): FeatureMode {
|
||||
const gate: RemoteFeatureGate | undefined = snapshot.features[key];
|
||||
if (!gate?.mode || gate.mode === "allow") return "allow";
|
||||
if (gate.mode === "temp_hide") {
|
||||
const pinned = hiddenUntilVersion[key];
|
||||
if (pinned && pinned === snapshot.configVersion) return "hide";
|
||||
return "allow";
|
||||
}
|
||||
return gate.mode;
|
||||
}
|
||||
|
||||
export function isRemoteFeatureAllowed(
|
||||
key: string,
|
||||
snapshot: RemoteConfigSnapshot,
|
||||
hiddenUntilVersion: Record<string, string> = {},
|
||||
): boolean {
|
||||
const mode = resolveFeatureMode(key, snapshot, hiddenUntilVersion);
|
||||
return mode === "allow" || mode === "banner";
|
||||
}
|
||||
|
||||
export function shouldHideFeature(
|
||||
key: string,
|
||||
snapshot: RemoteConfigSnapshot,
|
||||
hiddenUntilVersion: Record<string, string> = {},
|
||||
): boolean {
|
||||
return resolveFeatureMode(key, snapshot, hiddenUntilVersion) === "hide";
|
||||
}
|
||||
|
||||
export function getFeatureMessage(
|
||||
key: string,
|
||||
snapshot: RemoteConfigSnapshot,
|
||||
): RemoteFeatureGate["message"] | undefined {
|
||||
return snapshot.features[key]?.message;
|
||||
}
|
||||
@@ -0,0 +1,71 @@
|
||||
import {
|
||||
DEFAULT_REMOTE_CONFIG,
|
||||
mergeGithubConfigFiles,
|
||||
normalizeRemoteConfigSnapshot,
|
||||
} from "./normalize";
|
||||
|
||||
describe("normalizeRemoteConfigSnapshot", () => {
|
||||
it("returns defaults for empty input", () => {
|
||||
expect(normalizeRemoteConfigSnapshot(null)).toEqual(DEFAULT_REMOTE_CONFIG);
|
||||
});
|
||||
|
||||
it("unwraps API envelope data", () => {
|
||||
const snap = normalizeRemoteConfigSnapshot({
|
||||
success: true,
|
||||
data: {
|
||||
configVersion: "9",
|
||||
global: { mode: "off", statusMessage: "Maintenance" },
|
||||
},
|
||||
});
|
||||
expect(snap.configVersion).toBe("9");
|
||||
expect(snap.global.mode).toBe("off");
|
||||
expect(snap.global.statusMessage).toBe("Maintenance");
|
||||
});
|
||||
|
||||
it("normalizes remoteTheme directive", () => {
|
||||
const snap = normalizeRemoteConfigSnapshot({
|
||||
configVersion: "10",
|
||||
remoteTheme: {
|
||||
packageId: "pkg",
|
||||
packageVersion: "1",
|
||||
mode: "optional",
|
||||
},
|
||||
});
|
||||
expect(snap.remoteTheme?.packageId).toBe("pkg");
|
||||
expect(snap.remoteTheme?.mode).toBe("optional");
|
||||
});
|
||||
|
||||
it("drops invalid remoteTheme", () => {
|
||||
const snap = normalizeRemoteConfigSnapshot({
|
||||
remoteTheme: { mode: "forced" },
|
||||
});
|
||||
expect(snap.remoteTheme).toBeNull();
|
||||
});
|
||||
|
||||
it("normalizes applicationMode overlay", () => {
|
||||
const snap = normalizeRemoteConfigSnapshot({
|
||||
remoteTheme: {
|
||||
packageId: "p",
|
||||
packageVersion: "1",
|
||||
mode: "optional",
|
||||
applicationMode: "overlay",
|
||||
},
|
||||
});
|
||||
expect(snap.remoteTheme?.applicationMode).toBe("overlay");
|
||||
});
|
||||
});
|
||||
|
||||
describe("mergeGithubConfigFiles", () => {
|
||||
it("merges manifest file map into snapshot", () => {
|
||||
const snap = mergeGithubConfigFiles(
|
||||
{ version: "1", updatedAt: "2026-01-01" },
|
||||
{
|
||||
global: { mode: "on" },
|
||||
features: { "page.news": { mode: "hide" } },
|
||||
campaigns: [],
|
||||
},
|
||||
);
|
||||
expect(snap.source).toBe("github");
|
||||
expect(snap.features["page.news"]?.mode).toBe("hide");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,161 @@
|
||||
import type {
|
||||
RemoteConfigSnapshot,
|
||||
RemoteFeatureGate,
|
||||
RemoteGlobalConfig,
|
||||
RemoteThemeDirective,
|
||||
} from "./types";
|
||||
|
||||
export const DEFAULT_REMOTE_CONFIG: RemoteConfigSnapshot = {
|
||||
configVersion: "0",
|
||||
source: "default",
|
||||
global: { mode: "on", allowLocalOverride: true },
|
||||
features: {},
|
||||
campaigns: [],
|
||||
remoteTheme: null,
|
||||
};
|
||||
|
||||
function normalizeGlobal(raw: unknown): RemoteGlobalConfig {
|
||||
if (!raw || typeof raw !== "object") return DEFAULT_REMOTE_CONFIG.global;
|
||||
const g = raw as Record<string, unknown>;
|
||||
return {
|
||||
mode: g.mode === "off" ? "off" : "on",
|
||||
allowLocalOverride: g.allowLocalOverride !== false,
|
||||
statusMessage: typeof g.statusMessage === "string" ? g.statusMessage : null,
|
||||
maintenance:
|
||||
g.maintenance && typeof g.maintenance === "object"
|
||||
? (g.maintenance as RemoteGlobalConfig["maintenance"])
|
||||
: null,
|
||||
minExtensionVersion:
|
||||
typeof g.minExtensionVersion === "string" ? g.minExtensionVersion : null,
|
||||
forceUpdateUrl: typeof g.forceUpdateUrl === "string" ? g.forceUpdateUrl : null,
|
||||
disableCloudSync: g.disableCloudSync === true,
|
||||
disableThemeStore: g.disableThemeStore === true,
|
||||
disableFeedbackSubmit: g.disableFeedbackSubmit === true,
|
||||
hostnamePolicy:
|
||||
g.hostnamePolicy && typeof g.hostnamePolicy === "object"
|
||||
? {
|
||||
mode:
|
||||
(g.hostnamePolicy as { mode?: string }).mode === "allowlist" ||
|
||||
(g.hostnamePolicy as { mode?: string }).mode === "denylist"
|
||||
? ((g.hostnamePolicy as { mode: "allowlist" | "denylist" }).mode)
|
||||
: undefined,
|
||||
suffixes: Array.isArray((g.hostnamePolicy as { suffixes?: unknown }).suffixes)
|
||||
? ((g.hostnamePolicy as { suffixes: string[] }).suffixes.filter(
|
||||
(s) => typeof s === "string",
|
||||
))
|
||||
: undefined,
|
||||
}
|
||||
: null,
|
||||
};
|
||||
}
|
||||
|
||||
function normalizeFeatures(raw: unknown): Record<string, RemoteFeatureGate> {
|
||||
if (!raw || typeof raw !== "object") return {};
|
||||
const out: Record<string, RemoteFeatureGate> = {};
|
||||
for (const [key, value] of Object.entries(raw as Record<string, unknown>)) {
|
||||
if (!value || typeof value !== "object") continue;
|
||||
const v = value as Record<string, unknown>;
|
||||
const mode = v.mode;
|
||||
if (
|
||||
mode !== "allow" &&
|
||||
mode !== "hide" &&
|
||||
mode !== "banner" &&
|
||||
mode !== "block" &&
|
||||
mode !== "greyout" &&
|
||||
mode !== "temp_hide"
|
||||
) {
|
||||
continue;
|
||||
}
|
||||
const msg = v.message;
|
||||
out[key] = {
|
||||
mode,
|
||||
message:
|
||||
msg && typeof msg === "object" && typeof (msg as { body?: string }).body === "string"
|
||||
? {
|
||||
title: typeof (msg as { title?: string }).title === "string"
|
||||
? (msg as { title: string }).title
|
||||
: undefined,
|
||||
body: (msg as { body: string }).body,
|
||||
severity:
|
||||
(msg as { severity?: string }).severity === "warning" ||
|
||||
(msg as { severity?: string }).severity === "error" ||
|
||||
(msg as { severity?: string }).severity === "info"
|
||||
? ((msg as { severity: "info" | "warning" | "error" }).severity)
|
||||
: undefined,
|
||||
}
|
||||
: undefined,
|
||||
};
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
function normalizeRemoteTheme(raw: unknown): RemoteThemeDirective | null {
|
||||
if (!raw || typeof raw !== "object") return null;
|
||||
const r = raw as Record<string, unknown>;
|
||||
const mode = r.mode;
|
||||
if (mode !== "off" && mode !== "optional" && mode !== "forced") return null;
|
||||
const packageId = typeof r.packageId === "string" ? r.packageId.trim() : "";
|
||||
const packageVersion =
|
||||
typeof r.packageVersion === "string" ? r.packageVersion.trim() : "";
|
||||
if (!packageId || !packageVersion) return null;
|
||||
if (mode === "off") return null;
|
||||
const msg = r.message;
|
||||
return {
|
||||
packageId,
|
||||
packageVersion,
|
||||
mode,
|
||||
applicationMode: r.applicationMode === "overlay" ? "overlay" : "replace",
|
||||
activeFrom: typeof r.activeFrom === "string" ? r.activeFrom : undefined,
|
||||
activeTo: typeof r.activeTo === "string" ? r.activeTo : undefined,
|
||||
allowUserOptOut: r.allowUserOptOut !== false,
|
||||
message:
|
||||
msg && typeof msg === "object"
|
||||
? {
|
||||
title: typeof (msg as { title?: string }).title === "string"
|
||||
? (msg as { title: string }).title
|
||||
: undefined,
|
||||
body: typeof (msg as { body?: string }).body === "string"
|
||||
? (msg as { body: string }).body
|
||||
: undefined,
|
||||
}
|
||||
: undefined,
|
||||
};
|
||||
}
|
||||
|
||||
export function normalizeRemoteConfigSnapshot(raw: unknown): RemoteConfigSnapshot {
|
||||
if (!raw || typeof raw !== "object") return { ...DEFAULT_REMOTE_CONFIG };
|
||||
const r = raw as Record<string, unknown>;
|
||||
const data =
|
||||
r.data && typeof r.data === "object" ? (r.data as Record<string, unknown>) : r;
|
||||
return {
|
||||
configVersion:
|
||||
typeof data.configVersion === "string" ? data.configVersion : "0",
|
||||
etag: typeof data.etag === "string" ? data.etag : undefined,
|
||||
source:
|
||||
data.source === "api" ||
|
||||
data.source === "github" ||
|
||||
data.source === "cache" ||
|
||||
data.source === "default"
|
||||
? data.source
|
||||
: "cache",
|
||||
global: normalizeGlobal(data.global),
|
||||
features: normalizeFeatures(data.features),
|
||||
campaigns: Array.isArray(data.campaigns) ? (data.campaigns as RemoteConfigSnapshot["campaigns"]) : [],
|
||||
remoteTheme: normalizeRemoteTheme(data.remoteTheme),
|
||||
};
|
||||
}
|
||||
|
||||
/** Merge GitHub manifest + partial files into one snapshot. */
|
||||
export function mergeGithubConfigFiles(
|
||||
manifest: Record<string, unknown>,
|
||||
files: Record<string, unknown>,
|
||||
): RemoteConfigSnapshot {
|
||||
return normalizeRemoteConfigSnapshot({
|
||||
configVersion: manifest.configVersion ?? manifest.updatedAt ?? "0",
|
||||
source: "github",
|
||||
global: files.global ?? {},
|
||||
features: files.features ?? {},
|
||||
campaigns: files.campaigns ?? [],
|
||||
remoteTheme: files.remoteTheme ?? null,
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,269 @@
|
||||
import browser from "webextension-polyfill";
|
||||
import localforage from "localforage";
|
||||
import type { CustomTheme } from "@/types/CustomThemes";
|
||||
import {
|
||||
applyLocalSettingsRecord,
|
||||
captureSyncableSettingsSnapshot,
|
||||
} from "@/seqta/utils/cloudSettingsSync";
|
||||
import { settingsState, initializeSettingsState } from "@/seqta/utils/listeners/SettingsState";
|
||||
import { syncThemeToPage } from "@/seqta/utils/patchThemeImagesPageContext";
|
||||
import type { RemoteConfigSnapshot, RemoteThemeDirective } from "./types";
|
||||
import {
|
||||
BSPLUS_REMOTE_THEME_BEFORE_V1_KEY,
|
||||
BSPLUS_REMOTE_THEME_STATE_V1_KEY,
|
||||
BSPLUS_REMOTE_THEME_USER_OFF_KEY,
|
||||
} from "./storageKeys";
|
||||
|
||||
type BeforeSnapshot = {
|
||||
capturedAt: string;
|
||||
directiveKey: string;
|
||||
storage: Record<string, unknown>;
|
||||
selectedTheme: string;
|
||||
};
|
||||
|
||||
type ActiveThemeState = {
|
||||
directiveKey: string;
|
||||
layerIds: string[];
|
||||
mode: "optional" | "forced";
|
||||
applicationMode: "replace" | "overlay";
|
||||
};
|
||||
|
||||
type RemotePackage = {
|
||||
theme?: Record<string, unknown>;
|
||||
overlayLayers?: Record<string, unknown>[];
|
||||
downloadUrl?: string;
|
||||
};
|
||||
|
||||
let reconcileChain: Promise<void> = Promise.resolve();
|
||||
|
||||
function directiveKey(snapshot: RemoteConfigSnapshot, d: RemoteThemeDirective): string {
|
||||
return `${snapshot.configVersion}|${d.packageId}|${d.packageVersion}|${d.mode}|${d.applicationMode ?? "replace"}`;
|
||||
}
|
||||
|
||||
function isWithinWindow(d: RemoteThemeDirective, now = Date.now()): boolean {
|
||||
if (d.activeFrom && !Number.isNaN(Date.parse(d.activeFrom)) && now < Date.parse(d.activeFrom)) {
|
||||
return false;
|
||||
}
|
||||
if (d.activeTo && !Number.isNaN(Date.parse(d.activeTo)) && now > Date.parse(d.activeTo)) {
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
export function resolveEffectiveRemoteTheme(
|
||||
snapshot: RemoteConfigSnapshot,
|
||||
): RemoteThemeDirective | null {
|
||||
const d = snapshot.remoteTheme;
|
||||
if (!d || d.mode === "off" || !isWithinWindow(d)) return null;
|
||||
return d;
|
||||
}
|
||||
|
||||
async function readJson<T>(key: string): Promise<T | null> {
|
||||
const stored = await browser.storage.local.get(key);
|
||||
const raw = stored[key];
|
||||
return raw && typeof raw === "object" ? (raw as T) : null;
|
||||
}
|
||||
|
||||
async function loadBeforeSnapshot(): Promise<BeforeSnapshot | null> {
|
||||
const b = await readJson<BeforeSnapshot>(BSPLUS_REMOTE_THEME_BEFORE_V1_KEY);
|
||||
if (!b?.directiveKey || !b.storage) return null;
|
||||
return b;
|
||||
}
|
||||
|
||||
async function loadActiveState(): Promise<ActiveThemeState | null> {
|
||||
return readJson<ActiveThemeState>(BSPLUS_REMOTE_THEME_STATE_V1_KEY);
|
||||
}
|
||||
|
||||
async function loadUserOffKey(): Promise<string | null> {
|
||||
const raw = await readJson<{ directiveKey?: string }>(BSPLUS_REMOTE_THEME_USER_OFF_KEY);
|
||||
return typeof raw?.directiveKey === "string" ? raw.directiveKey : null;
|
||||
}
|
||||
|
||||
async function clearRemoteThemeLocalState(): Promise<void> {
|
||||
await browser.storage.local.remove([
|
||||
BSPLUS_REMOTE_THEME_BEFORE_V1_KEY,
|
||||
BSPLUS_REMOTE_THEME_STATE_V1_KEY,
|
||||
BSPLUS_REMOTE_THEME_USER_OFF_KEY,
|
||||
]);
|
||||
}
|
||||
|
||||
async function clearRemoteThemeOverlay(state?: ActiveThemeState | null): Promise<void> {
|
||||
const active = state ?? (await loadActiveState());
|
||||
await syncThemeToPage({ clearOverlay: true });
|
||||
if (!active?.layerIds?.length) return;
|
||||
const { ThemeManager } = await import("@/plugins/built-in/themes/theme-manager");
|
||||
const tm = ThemeManager.getInstance();
|
||||
for (const id of active.layerIds) {
|
||||
await tm.deleteTheme(id).catch(() => {});
|
||||
}
|
||||
}
|
||||
|
||||
export async function dismissOptionalRemoteTheme(snapshot: RemoteConfigSnapshot): Promise<void> {
|
||||
const d = resolveEffectiveRemoteTheme(snapshot);
|
||||
if (!d || d.mode !== "optional") return;
|
||||
await browser.storage.local.set({
|
||||
[BSPLUS_REMOTE_THEME_USER_OFF_KEY]: { directiveKey: directiveKey(snapshot, d) },
|
||||
});
|
||||
await restoreRemoteThemeSnapshot();
|
||||
}
|
||||
|
||||
async function restoreRemoteThemeSnapshot(): Promise<void> {
|
||||
const state = await loadActiveState();
|
||||
if (state?.applicationMode === "overlay") {
|
||||
await clearRemoteThemeOverlay(state);
|
||||
await clearRemoteThemeLocalState();
|
||||
return;
|
||||
}
|
||||
const before = await loadBeforeSnapshot();
|
||||
if (before) {
|
||||
await applyLocalSettingsRecord(before.storage);
|
||||
await initializeSettingsState();
|
||||
const { ThemeManager } = await import("@/plugins/built-in/themes/theme-manager");
|
||||
const tm = ThemeManager.getInstance();
|
||||
if (before.selectedTheme) await tm.setTheme(before.selectedTheme, false);
|
||||
else await tm.disableTheme();
|
||||
}
|
||||
await clearRemoteThemeLocalState();
|
||||
}
|
||||
|
||||
async function fetchPackage(packageId: string): Promise<RemotePackage | null> {
|
||||
try {
|
||||
const res = (await browser.runtime.sendMessage({
|
||||
type: "fetchRemoteThemePackage",
|
||||
packageId,
|
||||
})) as { package?: RemotePackage; error?: string };
|
||||
return res?.package && !res.error ? res.package : null;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
async function fetchDownload(url: string): Promise<Record<string, unknown> | null> {
|
||||
try {
|
||||
const res = (await browser.runtime.sendMessage({
|
||||
type: "fetchRemoteThemePackageUrl",
|
||||
url,
|
||||
})) as { theme?: Record<string, unknown> };
|
||||
return res?.theme && typeof res.theme === "object" ? res.theme : null;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
async function resolveLayers(pkg: RemotePackage): Promise<Record<string, unknown>[]> {
|
||||
if (Array.isArray(pkg.overlayLayers) && pkg.overlayLayers.length) {
|
||||
return pkg.overlayLayers.filter((l) => l && typeof l === "object") as Record<string, unknown>[];
|
||||
}
|
||||
if (pkg.theme && typeof pkg.theme === "object") return [pkg.theme];
|
||||
if (!pkg.downloadUrl) return [];
|
||||
const dl = await fetchDownload(pkg.downloadUrl);
|
||||
if (!dl) return [];
|
||||
if (Array.isArray((dl as { overlayLayers?: unknown }).overlayLayers)) {
|
||||
return (dl as { overlayLayers: Record<string, unknown>[] }).overlayLayers;
|
||||
}
|
||||
return [dl];
|
||||
}
|
||||
|
||||
async function saveActiveState(state: ActiveThemeState): Promise<void> {
|
||||
await browser.storage.local.set({ [BSPLUS_REMOTE_THEME_STATE_V1_KEY]: state });
|
||||
await browser.storage.local.remove(BSPLUS_REMOTE_THEME_USER_OFF_KEY);
|
||||
}
|
||||
|
||||
async function applyRemoteTheme(
|
||||
snapshot: RemoteConfigSnapshot,
|
||||
directive: RemoteThemeDirective,
|
||||
): Promise<void> {
|
||||
const key = directiveKey(snapshot, directive);
|
||||
const prior = await loadActiveState();
|
||||
if (prior?.directiveKey === key) return;
|
||||
|
||||
const overlay = (directive.applicationMode ?? "replace") === "overlay";
|
||||
if (prior?.applicationMode === "overlay") await clearRemoteThemeOverlay(prior);
|
||||
|
||||
const pkg = await fetchPackage(directive.packageId);
|
||||
if (!pkg) return;
|
||||
|
||||
const layers = await resolveLayers(pkg);
|
||||
const { ThemeManager } = await import("@/plugins/built-in/themes/theme-manager");
|
||||
const tm = ThemeManager.getInstance();
|
||||
|
||||
if (overlay) {
|
||||
if (!layers.length) return;
|
||||
for (const layer of layers) {
|
||||
if (typeof layer.id !== "string" || !layer.name) continue;
|
||||
await tm.installTheme(layer as Parameters<typeof tm.installTheme>[0], { fromStore: false });
|
||||
}
|
||||
if (settingsState.selectedTheme) await tm.setTheme(settingsState.selectedTheme, false);
|
||||
|
||||
const css: string[] = [];
|
||||
const images = new Map<string, { variableName: string; blob: Blob }>();
|
||||
const layerIds: string[] = [];
|
||||
for (const layer of layers) {
|
||||
if (typeof layer.id === "string") layerIds.push(layer.id);
|
||||
if (typeof layer.CustomCSS === "string") css.push(layer.CustomCSS);
|
||||
const stored = typeof layer.id === "string"
|
||||
? ((await localforage.getItem(layer.id)) as CustomTheme | null)
|
||||
: null;
|
||||
for (const img of stored?.CustomImages ?? []) {
|
||||
if (img.variableName && img.blob) images.set(img.variableName, img);
|
||||
}
|
||||
}
|
||||
await syncThemeToPage({
|
||||
overlayCss: css.join("\n"),
|
||||
overlayImages: [...images.values()],
|
||||
});
|
||||
await saveActiveState({
|
||||
directiveKey: key,
|
||||
layerIds,
|
||||
mode: directive.mode,
|
||||
applicationMode: "overlay",
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
const theme = layers[0];
|
||||
if (!theme || typeof theme.id !== "string") return;
|
||||
|
||||
await captureBeforeSnapshot(key);
|
||||
await tm.installTheme(theme as Parameters<typeof tm.installTheme>[0], {
|
||||
fromStore: false,
|
||||
forceTheme: directive.mode === "forced",
|
||||
});
|
||||
await tm.setTheme(String(theme.id), false);
|
||||
await saveActiveState({
|
||||
directiveKey: key,
|
||||
layerIds: [String(theme.id)],
|
||||
mode: directive.mode,
|
||||
applicationMode: "replace",
|
||||
});
|
||||
}
|
||||
|
||||
async function captureBeforeSnapshot(directiveKey: string): Promise<void> {
|
||||
const existing = await loadBeforeSnapshot();
|
||||
if (existing?.directiveKey === directiveKey) return;
|
||||
await browser.storage.local.set({
|
||||
[BSPLUS_REMOTE_THEME_BEFORE_V1_KEY]: {
|
||||
capturedAt: new Date().toISOString(),
|
||||
directiveKey,
|
||||
storage: await captureSyncableSettingsSnapshot(),
|
||||
selectedTheme: settingsState.selectedTheme ?? "",
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
async function reconcileRemoteThemeInner(snapshot: RemoteConfigSnapshot): Promise<void> {
|
||||
const d = resolveEffectiveRemoteTheme(snapshot);
|
||||
if (!d) {
|
||||
if (await loadActiveState()) await restoreRemoteThemeSnapshot();
|
||||
return;
|
||||
}
|
||||
const key = directiveKey(snapshot, d);
|
||||
if (d.mode === "optional" && (await loadUserOffKey()) === key) return;
|
||||
await applyRemoteTheme(snapshot, d);
|
||||
}
|
||||
|
||||
export function scheduleReconcileRemoteTheme(snapshot: RemoteConfigSnapshot): void {
|
||||
reconcileChain = reconcileChain
|
||||
.then(() => reconcileRemoteThemeInner(snapshot))
|
||||
.catch((e) => console.warn("[BetterSEQTA+] remote theme reconcile failed:", e));
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
import { checkRemoteFeature } from "./runtime";
|
||||
|
||||
export const ROUTE_STRIP_KEEP_PLUGINS = new Set(["themes", "animated-background"]);
|
||||
|
||||
export function parseSeqtaPageKeyFromHash(hash = location.hash): string | null {
|
||||
const match =
|
||||
hash.match(/[#?]page=\/([^/?&#]+)/i) ?? hash.match(/page=\/([^/?&#]+)/i);
|
||||
if (!match?.[1]) return null;
|
||||
return match[1].trim().toLowerCase();
|
||||
}
|
||||
|
||||
export function isRemoteRouteEnhancementsStripped(pageKey?: string | null): boolean {
|
||||
const key = pageKey ?? parseSeqtaPageKeyFromHash();
|
||||
if (!key) return false;
|
||||
return checkRemoteFeature(`page.${key}`).mode === "block";
|
||||
}
|
||||
|
||||
export function remoteChromeGateAllowed(
|
||||
key: "ui.sidebar.styled" | "ui.titlebar.custom" | "ui.titlebar.founderBadge",
|
||||
): boolean {
|
||||
const mode = checkRemoteFeature(key).mode;
|
||||
return mode !== "hide" && mode !== "block";
|
||||
}
|
||||
|
||||
export async function syncRouteEnhancementChrome(): Promise<void> {
|
||||
if (isRemoteRouteEnhancementsStripped()) {
|
||||
const { clearNativeSidebar } = await import("@/seqta/ui/sidebar/applyNativeSidebar");
|
||||
clearNativeSidebar();
|
||||
const { unmountCustomTitleBar } = await import("@/seqta/ui/titlebar/mountCustomTitleBar");
|
||||
unmountCustomTitleBar();
|
||||
const { pluginManager } = await import("@/plugins/index");
|
||||
await pluginManager.stopPluginsExcept(ROUTE_STRIP_KEEP_PLUGINS);
|
||||
return;
|
||||
}
|
||||
|
||||
if (remoteChromeGateAllowed("ui.sidebar.styled")) {
|
||||
const { applyNativeSidebar } = await import("@/seqta/ui/sidebar/applyNativeSidebar");
|
||||
await applyNativeSidebar();
|
||||
}
|
||||
if (remoteChromeGateAllowed("ui.titlebar.custom")) {
|
||||
const { mountCustomTitleBar } = await import("@/seqta/ui/titlebar/mountCustomTitleBar");
|
||||
void mountCustomTitleBar();
|
||||
}
|
||||
const { pluginManager } = await import("@/plugins/index");
|
||||
await pluginManager.startAllPlugins();
|
||||
}
|
||||
@@ -0,0 +1,297 @@
|
||||
import browser from "webextension-polyfill";
|
||||
import stringToHTML from "@/seqta/utils/stringToHTML";
|
||||
import { addExtensionSettings } from "@/seqta/utils/Adders/AddExtensionSettings";
|
||||
import { setupSettingsButton } from "@/seqta/utils/setupSettingsButton";
|
||||
import { waitForElm } from "@/seqta/utils/waitForElm";
|
||||
import { isSeqtaEngageExperience } from "@/seqta/utils/isSeqtaEngage";
|
||||
import { isPerformanceMode } from "@/seqta/utils/performanceMode";
|
||||
import { settingsState } from "@/seqta/utils/listeners/SettingsState";
|
||||
import {
|
||||
BSPLUS_CAMPAIGN_SEEN_KEY,
|
||||
BSPLUS_FEATURES_HIDDEN_UNTIL_VERSION_KEY,
|
||||
BSPLUS_LOCAL_OVERRIDE_ONOFF_KEY,
|
||||
BSPLUS_REMOTE_CONFIG_LAST_HOSTNAME_KEY,
|
||||
BSPLUS_REMOTE_CONFIG_SNAPSHOT_KEY,
|
||||
} from "./storageKeys";
|
||||
import { normalizeRemoteConfigSnapshot } from "./normalize";
|
||||
import type { CampaignSeenRecord, RemoteConfigSnapshot } from "./types";
|
||||
import {
|
||||
computeEffectiveEnabled,
|
||||
getFeatureMessage,
|
||||
isExtensionVersionBelowMinimum,
|
||||
isRemoteFeatureAllowed,
|
||||
resolveFeatureMode,
|
||||
shouldHideFeature,
|
||||
} from "./apply";
|
||||
import { scheduleReconcileRemoteTheme } from "./remoteTheme";
|
||||
|
||||
export {
|
||||
dismissOptionalRemoteTheme,
|
||||
resolveEffectiveRemoteTheme,
|
||||
} from "./remoteTheme";
|
||||
|
||||
let snapshot: RemoteConfigSnapshot = normalizeRemoteConfigSnapshot(null);
|
||||
let localOverride = false;
|
||||
let hiddenUntilVersion: Record<string, string> = {};
|
||||
let campaignSeen: CampaignSeenRecord = {};
|
||||
|
||||
const SNAPSHOT_FETCH_TIMEOUT_MS = 200;
|
||||
|
||||
function kickRemoteSideEffects(): void {
|
||||
scheduleReconcileRemoteTheme(snapshot);
|
||||
void import("./routeGate").then((m) => m.syncRouteEnhancementChrome());
|
||||
}
|
||||
|
||||
export function getRemoteConfigSnapshot(): RemoteConfigSnapshot {
|
||||
return snapshot;
|
||||
}
|
||||
|
||||
export function getHiddenUntilVersion(): Record<string, string> {
|
||||
return hiddenUntilVersion;
|
||||
}
|
||||
|
||||
export function getCampaignSeen(): CampaignSeenRecord {
|
||||
return campaignSeen;
|
||||
}
|
||||
|
||||
export function isEffectiveBsplusEnabled(userOnoff = settingsState.onoff !== false): boolean {
|
||||
return computeEffectiveEnabled(userOnoff, snapshot, localOverride, location.hostname);
|
||||
}
|
||||
|
||||
export function isRemoteKillActive(): boolean {
|
||||
return snapshot.global.mode === "off";
|
||||
}
|
||||
|
||||
export function isRemoteThemeStoreDisabled(): boolean {
|
||||
return snapshot.global.disableThemeStore === true;
|
||||
}
|
||||
|
||||
export function isRemoteFeedbackSubmitDisabled(): boolean {
|
||||
return snapshot.global.disableFeedbackSubmit === true;
|
||||
}
|
||||
|
||||
export async function setLocalOverrideOnoff(enabled: boolean): Promise<void> {
|
||||
localOverride = enabled;
|
||||
await browser.storage.local.set({ [BSPLUS_LOCAL_OVERRIDE_ONOFF_KEY]: enabled });
|
||||
}
|
||||
|
||||
function applyRemoteRuntime(
|
||||
next: RemoteConfigSnapshot,
|
||||
override: boolean,
|
||||
hidden: Record<string, string>,
|
||||
seen: CampaignSeenRecord,
|
||||
): void {
|
||||
snapshot = next;
|
||||
localOverride = override;
|
||||
hiddenUntilVersion = hidden;
|
||||
campaignSeen = seen;
|
||||
pinTempHideVersions(next);
|
||||
}
|
||||
|
||||
function pinTempHideVersions(next: RemoteConfigSnapshot): void {
|
||||
let changed = false;
|
||||
for (const [key, gate] of Object.entries(next.features)) {
|
||||
if (gate.mode === "temp_hide" && hiddenUntilVersion[key] !== next.configVersion) {
|
||||
hiddenUntilVersion = { ...hiddenUntilVersion, [key]: next.configVersion };
|
||||
changed = true;
|
||||
}
|
||||
}
|
||||
if (changed) {
|
||||
void browser.storage.local.set({
|
||||
[BSPLUS_FEATURES_HIDDEN_UNTIL_VERSION_KEY]: hiddenUntilVersion,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
export async function hydrateRemoteConfigFromStorage(): Promise<RemoteConfigSnapshot> {
|
||||
const stored = await browser.storage.local.get([
|
||||
BSPLUS_REMOTE_CONFIG_SNAPSHOT_KEY,
|
||||
BSPLUS_LOCAL_OVERRIDE_ONOFF_KEY,
|
||||
BSPLUS_FEATURES_HIDDEN_UNTIL_VERSION_KEY,
|
||||
BSPLUS_CAMPAIGN_SEEN_KEY,
|
||||
]);
|
||||
|
||||
let raw = stored[BSPLUS_REMOTE_CONFIG_SNAPSHOT_KEY];
|
||||
if (!raw) {
|
||||
try {
|
||||
const res = (await Promise.race([
|
||||
browser.runtime.sendMessage({ type: "getRemoteConfigSnapshot" }),
|
||||
new Promise<null>((resolve) => setTimeout(() => resolve(null), SNAPSHOT_FETCH_TIMEOUT_MS)),
|
||||
])) as { snapshot?: unknown } | null;
|
||||
if (res?.snapshot) raw = res.snapshot;
|
||||
} catch {
|
||||
// SW unavailable
|
||||
}
|
||||
}
|
||||
|
||||
applyRemoteRuntime(
|
||||
normalizeRemoteConfigSnapshot(raw),
|
||||
stored[BSPLUS_LOCAL_OVERRIDE_ONOFF_KEY] === true,
|
||||
(stored[BSPLUS_FEATURES_HIDDEN_UNTIL_VERSION_KEY] as Record<string, string>) ?? {},
|
||||
(stored[BSPLUS_CAMPAIGN_SEEN_KEY] as CampaignSeenRecord) ?? {},
|
||||
);
|
||||
kickRemoteSideEffects();
|
||||
return snapshot;
|
||||
}
|
||||
|
||||
export function syncRemoteConfigFromBackend(): void {
|
||||
void browser.runtime.sendMessage({ type: "refreshRemoteConfig" }).catch(() => {});
|
||||
}
|
||||
|
||||
export function notifyRemoteConfigPageContext(hostname: string): void {
|
||||
void browser.storage.local.set({ [BSPLUS_REMOTE_CONFIG_LAST_HOSTNAME_KEY]: hostname });
|
||||
void browser.runtime
|
||||
.sendMessage({ type: "setRemoteConfigPageContext", hostname })
|
||||
.catch(() => {});
|
||||
syncRemoteConfigFromBackend();
|
||||
}
|
||||
|
||||
export async function markCampaignSeen(campaignId: string, ack?: boolean): Promise<void> {
|
||||
campaignSeen = {
|
||||
...campaignSeen,
|
||||
[campaignId]: {
|
||||
seenAt: new Date().toISOString(),
|
||||
...(ack === true ? { ack: true } : ack === false ? { ack: false } : {}),
|
||||
},
|
||||
};
|
||||
await browser.storage.local.set({ [BSPLUS_CAMPAIGN_SEEN_KEY]: campaignSeen });
|
||||
}
|
||||
|
||||
const REMOTE_STORAGE_WATCH_KEYS = new Set([
|
||||
BSPLUS_REMOTE_CONFIG_SNAPSHOT_KEY,
|
||||
BSPLUS_LOCAL_OVERRIDE_ONOFF_KEY,
|
||||
BSPLUS_FEATURES_HIDDEN_UNTIL_VERSION_KEY,
|
||||
]);
|
||||
|
||||
export function installRemoteConfigStorageListener(onEffectiveChange: () => void): void {
|
||||
let priorEnabled = isEffectiveBsplusEnabled();
|
||||
browser.storage.onChanged.addListener((changes, area) => {
|
||||
if (area !== "local") return;
|
||||
if (!Object.keys(changes).some((k) => REMOTE_STORAGE_WATCH_KEYS.has(k))) return;
|
||||
void hydrateRemoteConfigFromStorage().then(() => {
|
||||
kickRemoteSideEffects();
|
||||
const next = isEffectiveBsplusEnabled();
|
||||
if (next !== priorEnabled) {
|
||||
priorEnabled = next;
|
||||
onEffectiveChange();
|
||||
}
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
export function checkRemoteFeature(key: string) {
|
||||
const hidden = hiddenUntilVersion;
|
||||
return {
|
||||
mode: resolveFeatureMode(key, snapshot, hidden),
|
||||
allowed: isRemoteFeatureAllowed(key, snapshot, hidden),
|
||||
hide: shouldHideFeature(key, snapshot, hidden),
|
||||
message: getFeatureMessage(key, snapshot),
|
||||
};
|
||||
}
|
||||
|
||||
export function isRemoteSettingsSectionVisible(sectionId: string): boolean {
|
||||
const key =
|
||||
sectionId === "account" ? "settings.nav.cloud" : `settings.section.${sectionId}`;
|
||||
return !checkRemoteFeature(key).hide;
|
||||
}
|
||||
|
||||
export function isRemotePluginStartAllowed(pluginId: string): boolean {
|
||||
const remote = checkRemoteFeature(`plugin.${pluginId}`);
|
||||
if (remote.hide || remote.mode === "greyout" || remote.mode === "block") return false;
|
||||
if (isExtensionVersionBelowMinimum(snapshot)) return false;
|
||||
return remote.allowed;
|
||||
}
|
||||
|
||||
/** Returns true when navigation should stop (hide or block). */
|
||||
export function applyPageFeatureGateEarly(page: string): boolean {
|
||||
const gate = checkRemoteFeature(`page.${page}`);
|
||||
if (gate.hide) return true;
|
||||
if (gate.mode !== "block") return false;
|
||||
|
||||
const main = document.getElementById("main");
|
||||
if (main) {
|
||||
const title = gate.message?.title ?? "Page unavailable";
|
||||
const body = gate.message?.body ?? "This BetterSEQTA+ page is temporarily unavailable.";
|
||||
main.innerHTML = "";
|
||||
main.append(
|
||||
stringToHTML(
|
||||
/* html */ `<div class="home-root"><div class="home-container"><h1 class="bsplus-rounded">${title}</h1><p>${body}</p></div></div>`,
|
||||
).firstChild!,
|
||||
);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
export function injectPageFeatureBanner(page: string, containerSelector: string): void {
|
||||
const gate = checkRemoteFeature(`page.${page}`);
|
||||
if (gate.mode !== "banner" || !gate.message?.body) return;
|
||||
const container = document.querySelector(containerSelector);
|
||||
if (!container || container.querySelector(`[data-bsplus-page-banner="${page}"]`)) return;
|
||||
|
||||
const severity = gate.message.severity ?? "info";
|
||||
container.insertBefore(
|
||||
stringToHTML(/* html */ `
|
||||
<div data-bsplus-page-banner="${page}" class="bsplus-remote-page-banner bsplus-remote-page-banner--${severity} mb-4 rounded-lg border px-4 py-3 text-sm">
|
||||
${gate.message.title ? `<p class="font-semibold mb-1">${gate.message.title}</p>` : ""}
|
||||
<p>${gate.message.body}</p>
|
||||
</div>
|
||||
`).firstChild!,
|
||||
container.firstChild,
|
||||
);
|
||||
}
|
||||
|
||||
/** Remote kill path: settings popup + toolbar cog without monofile. */
|
||||
export async function ensureKilledModeSettingsAccess(): Promise<void> {
|
||||
addExtensionSettings();
|
||||
if (document.getElementById("AddedSettings")) {
|
||||
setupSettingsButton();
|
||||
return;
|
||||
}
|
||||
|
||||
const fallback =
|
||||
document.getElementById("content") ??
|
||||
document.getElementById("container") ??
|
||||
document.body;
|
||||
|
||||
const mountParent = async (): Promise<Element> => {
|
||||
if (isSeqtaEngageExperience()) {
|
||||
try {
|
||||
const el = await waitForElm(
|
||||
"#content > div.connectedNotificationsWrapper > div",
|
||||
true,
|
||||
100,
|
||||
40,
|
||||
);
|
||||
return el.parentElement ?? el;
|
||||
} catch {
|
||||
return fallback;
|
||||
}
|
||||
}
|
||||
try {
|
||||
return await waitForElm(
|
||||
"#content > div.connectedNotificationsWrapper",
|
||||
true,
|
||||
isPerformanceMode() ? 120 : 80,
|
||||
50,
|
||||
);
|
||||
} catch {
|
||||
return fallback;
|
||||
}
|
||||
};
|
||||
|
||||
mountParent().then((parent) => {
|
||||
if (document.getElementById("AddedSettings")) return;
|
||||
parent.append(
|
||||
stringToHTML(/* html */ `
|
||||
<button class="addedButton tooltip" id="AddedSettings" type="button" aria-label="BetterSEQTA+ settings">
|
||||
<svg width="24" height="24" viewBox="0 0 24 24" aria-hidden="true">
|
||||
<path d="M23.182,6.923c-.29,0-3.662,2.122-4.142,2.4l-2.8-1.555V4.511l4.257-2.456a.518.518,0,0,0,.233-.408.479.479,0,0,0-.233-.407,6.511,6.511,0,1,0-3.327,12.107,6.582,6.582,0,0,0,6.148-4.374,5.228,5.228,0,0,0,.333-1.542A.461.461,0,0,0,23.182,6.923Z"></path>
|
||||
<path d="M9.73,10.418,7.376,12.883c-.01.01-.021.016-.03.025L1.158,19.1a2.682,2.682,0,1,0,3.793,3.793l4.583-4.582,0,0,4.1-4.005-.037-.037A9.094,9.094,0,0,1,9.73,10.418ZM3.053,21.888A.894.894,0,1,1,3.946,21,.893.893,0,0,1,3.053,21.888Z"></path>
|
||||
</svg>
|
||||
<div class="tooltiptext topmenutooltip">BetterSEQTA+ Settings</div>
|
||||
</button>
|
||||
`).firstChild!,
|
||||
);
|
||||
setupSettingsButton();
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
export const BSPLUS_REMOTE_CONFIG_SNAPSHOT_KEY = "bsplus_remote_config_snapshot";
|
||||
export const BSPLUS_REMOTE_CONFIG_ETAG_KEY = "bsplus_remote_config_etag";
|
||||
export const BSPLUS_CAMPAIGN_SEEN_KEY = "bsplus_campaign_seen";
|
||||
export const BSPLUS_LOCAL_OVERRIDE_ONOFF_KEY = "bsplus_local_override_onoff";
|
||||
export const BSPLUS_FEATURES_HIDDEN_UNTIL_VERSION_KEY =
|
||||
"bsplus_features_hidden_until_version";
|
||||
export const BSPLUS_INSTALL_REGISTERED_AT_KEY = "bsplus_install_registered_at";
|
||||
export const BSPLUS_REMOTE_CONFIG_FETCHED_AT_KEY = "bsplus_remote_config_fetched_at";
|
||||
export const BSPLUS_REMOTE_CONFIG_LAST_HOSTNAME_KEY = "bsplus_remote_config_last_hostname";
|
||||
export const BSPLUS_REMOTE_LAST_PRIMARY_OK_KEY = "bsplus_remote_last_primary_ok";
|
||||
|
||||
export const BSPLUS_REMOTE_THEME_BEFORE_V1_KEY = "bsplus_remote_theme_before_v1";
|
||||
export const BSPLUS_REMOTE_THEME_STATE_V1_KEY = "bsplus_remote_theme_state_v1";
|
||||
export const BSPLUS_REMOTE_THEME_USER_OFF_KEY = "bsplus_remote_theme_user_off";
|
||||
|
||||
export const REMOTE_CONFIG_ALARM = "bsplus_remote_config_poll";
|
||||
export const REMOTE_CONFIG_POLL_MINUTES = 20;
|
||||
export const REGISTER_INTERVAL_MS = 24 * 60 * 60 * 1000;
|
||||
|
||||
export const BS_STATUS_MANIFEST_URL =
|
||||
"https://raw.githubusercontent.com/BetterSEQTA/BS-Status/main/config/manifest.json";
|
||||
@@ -0,0 +1,79 @@
|
||||
export type FeatureMode =
|
||||
| "allow"
|
||||
| "hide"
|
||||
| "banner"
|
||||
| "block"
|
||||
| "greyout"
|
||||
| "temp_hide";
|
||||
|
||||
export type RemoteFeatureGate = {
|
||||
mode?: FeatureMode;
|
||||
message?: { title?: string; body?: string; severity?: "info" | "warning" | "error" };
|
||||
};
|
||||
|
||||
export type RemoteGlobalConfig = {
|
||||
mode?: "on" | "off";
|
||||
allowLocalOverride?: boolean;
|
||||
statusMessage?: string | null;
|
||||
maintenance?: { title?: string; body?: string } | null;
|
||||
minExtensionVersion?: string | null;
|
||||
forceUpdateUrl?: string | null;
|
||||
disableCloudSync?: boolean;
|
||||
disableThemeStore?: boolean;
|
||||
disableFeedbackSubmit?: boolean;
|
||||
hostnamePolicy?: {
|
||||
mode?: "allowlist" | "denylist";
|
||||
suffixes?: string[];
|
||||
} | null;
|
||||
};
|
||||
|
||||
export type RemoteCampaignButton = {
|
||||
id: string;
|
||||
label: string;
|
||||
action: "dismiss" | "url" | "openSettingsSection";
|
||||
url?: string;
|
||||
section?: string;
|
||||
};
|
||||
|
||||
export type RemoteCampaign = {
|
||||
id: string;
|
||||
priority?: number;
|
||||
activeFrom?: string;
|
||||
activeTo?: string;
|
||||
header?: { title?: string; subtitle?: string };
|
||||
hero?: { type?: "image" | "video"; url?: string; alt?: string };
|
||||
bodyHtml?: string;
|
||||
buttons?: RemoteCampaignButton[];
|
||||
requireAcknowledge?: boolean;
|
||||
minVersion?: string;
|
||||
maxVersion?: string;
|
||||
};
|
||||
|
||||
export type RemoteThemeMode = "off" | "optional" | "forced";
|
||||
export type RemoteThemeApplicationMode = "replace" | "overlay";
|
||||
|
||||
export type RemoteThemeDirective = {
|
||||
packageId: string;
|
||||
packageVersion: string;
|
||||
mode: RemoteThemeMode;
|
||||
applicationMode?: RemoteThemeApplicationMode;
|
||||
activeFrom?: string;
|
||||
activeTo?: string;
|
||||
message?: { title?: string; body?: string };
|
||||
allowUserOptOut?: boolean;
|
||||
};
|
||||
|
||||
export type RemoteConfigSnapshot = {
|
||||
configVersion: string;
|
||||
etag?: string;
|
||||
source?: "api" | "github" | "default" | "cache";
|
||||
global: RemoteGlobalConfig;
|
||||
features: Record<string, RemoteFeatureGate>;
|
||||
campaigns: RemoteCampaign[];
|
||||
remoteTheme?: RemoteThemeDirective | null;
|
||||
};
|
||||
|
||||
export type CampaignSeenRecord = Record<
|
||||
string,
|
||||
{ seenAt: string; ack?: boolean }
|
||||
>;
|
||||
@@ -13,7 +13,10 @@
|
||||
var IMAGES_STYLE_ID = "bsplus-theme-images";
|
||||
var THEME_STYLE_ID = "custom-theme";
|
||||
var PREVIEW_STYLE_ID = "custom-theme-preview";
|
||||
var OVERLAY_STYLE_ID = "bsplus-remote-theme-overlay";
|
||||
var OVERLAY_IMAGES_STYLE_ID = "bsplus-remote-theme-overlay-images";
|
||||
var urlCache = {};
|
||||
var overlayUrlCache = {};
|
||||
var headObserver = null;
|
||||
|
||||
function log(event, detail) {
|
||||
@@ -29,14 +32,16 @@
|
||||
return new Blob([ab], { type: mime || "image/png" });
|
||||
}
|
||||
|
||||
function releaseCachedUrls() {
|
||||
for (var key in urlCache) {
|
||||
if (!Object.prototype.hasOwnProperty.call(urlCache, key)) continue;
|
||||
function releaseCache(cache) {
|
||||
for (var key in cache) {
|
||||
if (!Object.prototype.hasOwnProperty.call(cache, key)) continue;
|
||||
try {
|
||||
URL.revokeObjectURL(urlCache[key]);
|
||||
URL.revokeObjectURL(cache[key]);
|
||||
} catch (e) {}
|
||||
}
|
||||
urlCache = {};
|
||||
for (key in cache) {
|
||||
if (Object.prototype.hasOwnProperty.call(cache, key)) delete cache[key];
|
||||
}
|
||||
}
|
||||
|
||||
function styleEl(id) {
|
||||
@@ -49,11 +54,23 @@
|
||||
return el;
|
||||
}
|
||||
|
||||
function keepOverlayStylesLast() {
|
||||
var overlayImages = document.getElementById(OVERLAY_IMAGES_STYLE_ID);
|
||||
var overlayCss = document.getElementById(OVERLAY_STYLE_ID);
|
||||
if (overlayImages && document.head.contains(overlayImages)) {
|
||||
document.head.appendChild(overlayImages);
|
||||
}
|
||||
if (overlayCss && document.head.contains(overlayCss)) {
|
||||
document.head.appendChild(overlayCss);
|
||||
}
|
||||
}
|
||||
|
||||
function keepThemeStyleLast() {
|
||||
var themeStyle = document.getElementById(THEME_STYLE_ID);
|
||||
if (themeStyle && document.head.contains(themeStyle) && document.head.lastElementChild !== themeStyle) {
|
||||
document.head.appendChild(themeStyle);
|
||||
}
|
||||
keepOverlayStylesLast();
|
||||
}
|
||||
|
||||
function watchHead() {
|
||||
@@ -74,38 +91,45 @@
|
||||
}
|
||||
}
|
||||
|
||||
function clearAll() {
|
||||
releaseCachedUrls();
|
||||
setStyleText(IMAGES_STYLE_ID, "");
|
||||
document.getElementById(THEME_STYLE_ID)?.remove();
|
||||
document.getElementById(PREVIEW_STYLE_ID)?.remove();
|
||||
headObserver?.disconnect();
|
||||
headObserver = null;
|
||||
log("cleared");
|
||||
}
|
||||
|
||||
function applyThemeImages(images) {
|
||||
releaseCachedUrls();
|
||||
function applyRootImages(images, styleId, cache, afterApply) {
|
||||
releaseCache(cache);
|
||||
if (!images?.length) {
|
||||
setStyleText(IMAGES_STYLE_ID, "");
|
||||
document.getElementById(styleId)?.remove();
|
||||
return;
|
||||
}
|
||||
|
||||
var lines = [":root {"];
|
||||
for (var i = 0; i < images.length; i++) {
|
||||
var img = images[i];
|
||||
if (!img?.variableName || !img.data) continue;
|
||||
try {
|
||||
var url = URL.createObjectURL(base64ToBlob(img.data, img.mime));
|
||||
urlCache[img.variableName] = url;
|
||||
cache[img.variableName] = url;
|
||||
lines.push(' --' + img.variableName + ': url("' + url + '");');
|
||||
} catch (e) {
|
||||
console.warn(LOG, "skip image", img.variableName, e);
|
||||
}
|
||||
}
|
||||
lines.push("}");
|
||||
styleEl(IMAGES_STYLE_ID).textContent = lines.join("\n");
|
||||
log("images applied", { count: images.length });
|
||||
styleEl(styleId).textContent = lines.join("\n");
|
||||
if (afterApply) afterApply();
|
||||
log("images applied", { styleId: styleId, count: images.length });
|
||||
}
|
||||
|
||||
function clearOverlayOnly() {
|
||||
releaseCache(overlayUrlCache);
|
||||
document.getElementById(OVERLAY_STYLE_ID)?.remove();
|
||||
document.getElementById(OVERLAY_IMAGES_STYLE_ID)?.remove();
|
||||
log("overlay cleared");
|
||||
}
|
||||
|
||||
function clearAll() {
|
||||
releaseCache(urlCache);
|
||||
setStyleText(IMAGES_STYLE_ID, "");
|
||||
document.getElementById(THEME_STYLE_ID)?.remove();
|
||||
document.getElementById(PREVIEW_STYLE_ID)?.remove();
|
||||
headObserver?.disconnect();
|
||||
headObserver = null;
|
||||
log("cleared");
|
||||
}
|
||||
|
||||
function processPayload() {
|
||||
@@ -121,25 +145,32 @@
|
||||
clearAll();
|
||||
return;
|
||||
}
|
||||
if (payload.clearOverlay) {
|
||||
clearOverlayOnly();
|
||||
return;
|
||||
}
|
||||
|
||||
if (payload.images !== undefined) applyThemeImages(payload.images);
|
||||
|
||||
if (payload.images !== undefined) {
|
||||
applyRootImages(payload.images, IMAGES_STYLE_ID, urlCache);
|
||||
}
|
||||
if (payload.customCss !== undefined) {
|
||||
setStyleText(THEME_STYLE_ID, payload.customCss || "", true);
|
||||
log("custom css applied");
|
||||
}
|
||||
|
||||
if (payload.overlayImages !== undefined) {
|
||||
applyRootImages(payload.overlayImages, OVERLAY_IMAGES_STYLE_ID, overlayUrlCache, keepOverlayStylesLast);
|
||||
}
|
||||
if (payload.overlayCss !== undefined) {
|
||||
setStyleText(OVERLAY_STYLE_ID, payload.overlayCss || "", false);
|
||||
keepOverlayStylesLast();
|
||||
log("overlay css applied");
|
||||
}
|
||||
if (payload.previewCss !== undefined) {
|
||||
setStyleText(PREVIEW_STYLE_ID, payload.previewCss || "");
|
||||
var previewStyle = document.getElementById(PREVIEW_STYLE_ID);
|
||||
if (previewStyle) {
|
||||
document.head.appendChild(previewStyle);
|
||||
}
|
||||
}
|
||||
|
||||
if (payload.clearPreview) {
|
||||
setStyleText(PREVIEW_STYLE_ID, "");
|
||||
if (previewStyle) document.head.appendChild(previewStyle);
|
||||
}
|
||||
if (payload.clearPreview) setStyleText(PREVIEW_STYLE_ID, "");
|
||||
} catch (e) {
|
||||
console.warn(LOG, "invalid payload", e);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,2 @@
|
||||
/** Stub for CRXJS `?script` / `?script&iife` imports (default export is an extension-relative path). */
|
||||
export default "assets/mock-page-script.js";
|
||||
@@ -36,6 +36,8 @@ export interface SettingsState {
|
||||
justupdated?: boolean;
|
||||
privacyStatementShown?: boolean;
|
||||
privacyStatementLastUpdated?: string;
|
||||
/** ISO timestamp from `GET /api/terms` `last_updated` when the user accepted ToS. */
|
||||
termsOfServiceLastAccepted?: string;
|
||||
/** One-time announcement: BS Cloud automatic settings sync (last in startup popup queue). */
|
||||
bsCloudAutoSyncAnnouncementShown?: boolean;
|
||||
/** One-time notice when BetterSEQTA features are off after the Courses/Assessments fix. */
|
||||
@@ -106,7 +108,7 @@ export interface SettingsState {
|
||||
// BetterSEQTA Cloud (accounts.betterseqta.org) — stored via CloudAuth, not settingsState
|
||||
/** When not `false`, automatic cloud settings sync is enabled (default-on). */
|
||||
autoCloudSettingsSync?: boolean;
|
||||
/** When not `false`, show the Cloud founder badge in the SEQTA titlebar (default-on). */
|
||||
/** When not `false`, show Cloud badges in the SEQTA titlebar (default-on). */
|
||||
showTitlebarFounderBadge?: boolean;
|
||||
}
|
||||
|
||||
|
||||
Reference in new issue
Block a user