refactor: rename files, unify code style and tidy home page

This commit is contained in:
Jones Jankovic committed 2026-11-03 20:11:54 +10:30
1 parent 998be36575
commit 991c727267
229 files changed
+3872 -3433

No files matched your search

+2 -2
View File
@@ -9,7 +9,7 @@ Exhaustive reference for every value that **is** or **would be** included in a B
- Auto-sync (debounce, poll, triggers): `src/background/cloudSettingsAutoSync.ts`
- Core defaults: `src/seqta/utils/defaultSettings.ts`
- Full-schema initializer: `src/seqta/utils/ensureSyncableStorageDefaults.ts`
- In-memory settings + persistence: `src/seqta/utils/listeners/SettingsState.ts`
- In-memory settings + persistence: `src/seqta/utils/listeners/settingsState.ts`
- Type definitions: `src/types/storage.ts`
---
@@ -1195,7 +1195,7 @@ Implementation: `ensureSyncableStorageDefaults()` + `getSyncableStorageDefaults(
### Settings persistence and live UI
`SettingsState` (`src/seqta/utils/listeners/SettingsState.ts`):
`SettingsState` (`src/seqta/utils/listeners/settingsState.ts`):
- Assignments (`settingsState.foo = …`) and `setKey()` persist to `chrome.storage.local` and **notify registered listeners** in the same context (required for embedded SEQTA settings).
- `saveToStorage()` omits `undefined` values so optional keys are not accidentally stripped.
+24 -15
View File
@@ -111,7 +111,10 @@ function handleFetchThemes(_request: unknown, sendResponse: MessageSender): bool
})
.then(sendResponse)
.catch((err) => {
console.warn("[Background] fetchThemes API failed, trying GitHub fallback:", err?.message);
console.warn(
"[BetterSEQTA+] Background: fetchThemes API failed, trying GitHub fallback:",
err?.message,
);
fetch(githubUrl, { cache: "no-store" })
.then(async (r) => {
if (!r.ok) throw new Error(`GitHub fallback HTTP ${r.status}`);
@@ -121,7 +124,10 @@ function handleFetchThemes(_request: unknown, sendResponse: MessageSender): bool
})
.then(sendResponse)
.catch((fallbackErr) => {
console.error("[Background] fetchThemes GitHub fallback error:", fallbackErr);
console.error(
"[BetterSEQTA+] Background: fetchThemes GitHub fallback error:",
fallbackErr,
);
sendResponse({ success: false, error: fallbackErr?.message });
});
});
@@ -143,7 +149,7 @@ function handleFetchThemeDetails(request: BackgroundRequest, sendResponse: Messa
.then((r) => r.json())
.then(sendResponse)
.catch((err) => {
console.error("[Background] fetchThemeDetails error:", err);
console.error("[BetterSEQTA+] Background: fetchThemeDetails error:", err);
sendResponse({ success: false, error: err?.message });
});
})();
@@ -216,7 +222,7 @@ function handleFetchFromUrl(
sendResponse({ error: "Invalid JSON response" });
}
} catch (err) {
console.error("[Background] fetchFromUrl error:", err);
console.error("[BetterSEQTA+] Background: fetchFromUrl error:", err);
sendResponse({ error: (err as Error)?.message });
}
})();
@@ -253,7 +259,7 @@ function handleCloudReserveClient(
else sendResponse(data);
})
.catch((err) => {
console.error("[Background] cloudReserveClient error:", err);
console.error("[BetterSEQTA+] Background: cloudReserveClient error:", err);
sendResponse({ error: err?.message ?? "Network error" });
});
return true;
@@ -299,7 +305,7 @@ function handleCloudLogin(
if (!r.ok) sendResponse({ error: errorText ?? "Login failed" });
else sendResponse(data);
} catch (err) {
console.error("[Background] cloudLogin error:", err);
console.error("[BetterSEQTA+] Background: cloudLogin error:", err);
sendResponse({ error: (err as Error)?.message ?? "Network error" });
}
})();
@@ -320,7 +326,7 @@ function handleCloudStartLogin(request: BackgroundRequest, sendResponse: Message
sendResponse({ success: true });
})
.catch((err) => {
console.error("[Background] cloudStartLogin error:", err);
console.error("[BetterSEQTA+] Background: cloudStartLogin error:", err);
sendResponse({ error: err?.message ?? "Failed to open login page" });
});
return true;
@@ -356,17 +362,20 @@ function initCloudLoginCallbackListener() {
}
void performCloudSettingsDownloadWithRetry(token).catch((err) => {
console.warn("[Background] Cloud settings download after login:", err);
console.warn(
"[BetterSEQTA+] Background: Cloud settings download after login:",
err,
);
});
} catch (err) {
console.error("[Background] Failed to process login callback:", err);
console.error("[BetterSEQTA+] Background: Failed to process login callback:", err);
}
})();
void browser.tabs.remove(tabId);
}
} catch (err) {
console.error("[Background] Error parsing callback URL:", err);
console.error("[BetterSEQTA+] Background: Error parsing callback URL:", err);
}
}
});
@@ -395,7 +404,7 @@ function handleCloudRefresh(request: BackgroundRequest, sendResponse: MessageSen
else sendResponse(data);
})
.catch((err) => {
console.error("[Background] cloudRefresh error:", err);
console.error("[BetterSEQTA+] Background: cloudRefresh error:", err);
sendResponse({ error: err?.message ?? "Network error" });
});
return true;
@@ -424,7 +433,7 @@ function handleCloudSettingsUpload(
updated_at: res.updated_at,
});
} catch (err) {
console.error("[Background] cloudSettingsUpload error:", err);
console.error("[BetterSEQTA+] Background: cloudSettingsUpload error:", err);
sendResponse({
success: false,
error: err instanceof Error ? err.message : "Upload failed",
@@ -458,7 +467,7 @@ function handleCloudSettingsDownload(
updated_at: res.updated_at,
});
} catch (err) {
console.error("[Background] cloudSettingsDownload error:", err);
console.error("[BetterSEQTA+] Background: cloudSettingsDownload error:", err);
sendResponse({
success: false,
error: err instanceof Error ? err.message : "Download failed",
@@ -488,7 +497,7 @@ function handleCloudFavorite(request: BackgroundRequest, sendResponse: MessageSe
.then((r) => r.json())
.then(sendResponse)
.catch((err) => {
console.error("[Background] cloudFavorite error:", err);
console.error("[BetterSEQTA+] Background: cloudFavorite error:", err);
sendResponse({ success: false, error: err?.message });
});
})();
@@ -607,7 +616,7 @@ const MESSAGE_HANDLERS: Record<string, MessageHandler> = {
typeof reply?.appLink === "string" && reply.appLink.length > 0 ? reply.appLink : null;
sendResponse({ appLink });
} catch (err) {
console.error("[Background] getSeqtaSession error:", err);
console.error("[BetterSEQTA+] Background: getSeqtaSession error:", err);
sendResponse({ appLink: null });
}
})();
+8 -6
View File
@@ -158,7 +158,7 @@ async function fetchCloudSummaryWithAuthRetry(token: string): Promise<CloudSumma
t = next;
continue;
}
if (res.error) console.warn("[BS+ cloud sync] cloud-summary:", res.error);
if (res.error) console.warn("[BetterSEQTA+] Cloud sync: cloud-summary:", res.error);
break;
}
return null;
@@ -337,14 +337,14 @@ export async function performCloudSettingsDownloadWithRetry(
async function maybeUploadBaseline(token: string): Promise<void> {
const res = await performCloudSettingsUploadWithRetry(token);
if (!res.success) {
console.warn("[BS+ cloud sync] Baseline upload failed:", res.error);
console.warn("[BetterSEQTA+] Cloud sync: Baseline upload failed:", res.error);
}
}
async function downloadIfNeeded(token: string): Promise<void> {
const res = await performCloudSettingsDownloadWithRetry(token);
if (!res.success && !res.notFound) {
console.warn("[BS+ cloud sync] Auto-download failed:", res.error);
console.warn("[BetterSEQTA+] Cloud sync: Auto-download failed:", res.error);
}
}
@@ -368,7 +368,9 @@ async function runCloudSettingsPollInner(): Promise<void> {
typeof bsplus.schemaVersion === "number" &&
bsplus.schemaVersion > CLOUD_SETTINGS_SYNC_SCHEMA_VERSION
) {
console.warn("[BS+ cloud sync] Server schemaVersion newer than client; skip auto-download");
console.warn(
"[BetterSEQTA+] Cloud sync: Server schemaVersion newer than client; skip auto-download",
);
return;
}
@@ -399,7 +401,7 @@ export function runCloudSettingsPoll(): Promise<void> {
await runCloudSettingsPollInner();
await browser.storage.local.set({ [POLL_THROTTLE_KEY]: Date.now() });
} catch (e) {
console.error("[BS+ cloud sync] Poll error:", e);
console.error("[BetterSEQTA+] Cloud sync: Poll error:", e);
} finally {
pollInFlight = null;
}
@@ -443,7 +445,7 @@ async function runDebouncedUploadJob(): Promise<void> {
if (!token) return;
const res = await performCloudSettingsUploadWithRetry(token);
if (!res.success) {
console.warn("[BS+ cloud sync] Auto-upload failed:", res.error);
console.warn("[BetterSEQTA+] Cloud sync: Auto-upload failed:", res.error);
}
}
+8 -8
View File
@@ -45,7 +45,7 @@ export function createCustomThemesHandlers(deps: {
}
const normalized = normalizeCustomThemeApiResponse(body, r.status, text);
if (!r.ok || normalized.success === false) {
console.error("[BetterSEQTA+ CustomThemes]", r.status, r.url, normalized);
console.error("[BetterSEQTA+] CustomThemes:", r.status, r.url, normalized);
}
return normalized;
}
@@ -112,7 +112,7 @@ export function createCustomThemesHandlers(deps: {
: `/api/custom-themes?${params}`;
sendResponse(await customThemesJsonFetch(path));
} catch (err) {
console.error("[Background] fetchCustomThemes error:", err);
console.error("[BetterSEQTA+] Background: fetchCustomThemes error:", err);
sendResponse({
success: false,
error: err instanceof Error ? err.message : "Fetch failed",
@@ -135,7 +135,7 @@ export function createCustomThemesHandlers(deps: {
if (request.status) params.set("status", String(request.status));
sendResponse(await customThemesJsonFetch(`/api/custom-themes/mine?${params}`, {}, true));
} catch (err) {
console.error("[Background] fetchMyCustomThemes error:", err);
console.error("[BetterSEQTA+] Background: fetchMyCustomThemes error:", err);
sendResponse({
success: false,
error: err instanceof Error ? err.message : "Fetch failed",
@@ -164,7 +164,7 @@ export function createCustomThemesHandlers(deps: {
),
);
} catch (err) {
console.error("[Background] fetchMyCustomThemeDetail error:", err);
console.error("[BetterSEQTA+] Background: fetchMyCustomThemeDetail error:", err);
sendResponse({
success: false,
error: err instanceof Error ? err.message : "Fetch failed",
@@ -187,7 +187,7 @@ export function createCustomThemesHandlers(deps: {
try {
sendResponse(await customThemesMultipartPost("/api/custom-themes/mine", payload!));
} catch (err) {
console.error("[Background] submitCustomTheme error:", err);
console.error("[BetterSEQTA+] Background: submitCustomTheme error:", err);
sendResponse({
success: false,
error: { message: err instanceof Error ? err.message : "Upload failed" },
@@ -222,7 +222,7 @@ export function createCustomThemesHandlers(deps: {
),
);
} catch (err) {
console.error("[Background] replaceCustomThemeFiles error:", err);
console.error("[BetterSEQTA+] Background: replaceCustomThemeFiles error:", err);
sendResponse({
success: false,
error: err instanceof Error ? err.message : "Upload failed",
@@ -255,7 +255,7 @@ export function createCustomThemesHandlers(deps: {
),
);
} catch (err) {
console.error("[Background] updateCustomThemeMetadata error:", err);
console.error("[BetterSEQTA+] Background: updateCustomThemeMetadata error:", err);
sendResponse({
success: false,
error: err instanceof Error ? err.message : "Update failed",
@@ -284,7 +284,7 @@ export function createCustomThemesHandlers(deps: {
),
);
} catch (err) {
console.error("[Background] deleteCustomTheme error:", err);
console.error("[BetterSEQTA+] Background: deleteCustomTheme error:", err);
sendResponse({
success: false,
error: err instanceof Error ? err.message : "Delete failed",
+12 -95
View File
@@ -1877,12 +1877,16 @@ html.transparencyEffects [class*="BasicPanel__BasicPanel___q92_U"] > ol > li + l
border-radius: 50px;
}
.shortcut {
box-sizing: border-box;
height: 4em;
width: 15em;
max-width: 15em;
padding: 0 20px 0 12px;
gap: 10px;
background: var(--background-primary);
color: var(--text-primary);
display: flex;
align-items: center;
border-radius: 80px;
position: relative;
transition: 200ms;
@@ -1891,9 +1895,10 @@ html.transparencyEffects [class*="BasicPanel__BasicPanel___q92_U"] > ol > li + l
background: var(--auto-background);
}
.shortcut p {
margin: auto 0px auto 5px;
flex: 1;
min-width: 0;
margin: 0;
font-size: 20px;
width: 150px;
word-wrap: break-word;
line-height: 20px;
}
@@ -3006,13 +3011,13 @@ ul.uiSplitButtonList,
color: var(--text-primary);
}
.shortcuticondiv {
height: 39px;
width: 39px;
flex-shrink: 0;
height: 39px !important;
width: 39px !important;
border-radius: 50%;
padding: 0;
margin: auto 0px auto 10px;
background-repeat: no-repeat;
background-size: contain;
margin: 0;
object-fit: contain;
}
.forumView > .messages > .thread,
.forumView > .messages > .deletedPlaceholder,
@@ -3543,50 +3548,9 @@ div.day-empty {
cursor: pointer;
text-decoration: underline;
}
.upcoming-blank {
display: flex;
border-bottom: 2px solid #bebebe;
margin: 5px 50px;
height: 2em;
padding: 0px;
}
.upcoming-tick {
align-self: center;
}
.upcoming-title h2 {
width: 100%;
}
.upcoming-filters {
display: flex;
height: 26px;
width: 65%;
align-self: center;
align-items: center;
color: var(--text-color);
padding: 5px;
overflow-x: scroll;
overflow-y: hidden;
}
.upcoming-checkbox-container {
position: relative;
padding: none !important;
padding-left: 25px !important;
padding-right: 10px !important;
cursor: pointer;
font-size: 12px;
-webkit-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
user-select: none;
height: 20px;
align-items: center;
display: flex;
}
.upcoming-hiddenassessment {
color: #797979;
}
.calendarEventEditor > .tabset > .item {
border-radius: 0 !important;
}
@@ -3709,57 +3673,10 @@ div.day-empty {
.upcoming-special-day {
font-size: 20px;
}
.upcoming-blank p {
padding: 0;
margin: 0;
}
.upcoming-title {
display: flex;
align-content: space-between;
}
.upcoming-checkbox-container input {
position: absolute;
opacity: 0;
cursor: pointer;
height: 0;
width: 0;
padding: 0;
}
.upcoming-checkmark {
position: absolute;
top: 0;
left: 0;
height: 15px;
width: 15px;
border: 3px solid var(--item-colour);
border-radius: 5px;
color: var(--text-color);
}
.upcoming-checkbox-container:hover input ~ .upcoming-checkmark {
filter: brightness(0.8);
}
.upcoming-checkbox-container input:checked ~ .upcoming-checkmark {
background: var(--item-colour);
}
.upcoming-checkmark:after {
content: "";
position: absolute;
display: none;
}
.upcoming-checkbox-container input:checked ~ .upcoming-checkmark:after {
display: block;
}
.upcoming-checkbox-container .upcoming-checkmark:after {
left: 3.5px;
top: 0px;
width: 5px;
height: 10px;
border: solid white;
border-width: 0 3px 3px 0;
-webkit-transform: rotate(45deg);
-ms-transform: rotate(45deg);
transform: rotate(45deg);
}
.titlebar {
align-items: center;
transition: 200ms;
+8 -4
View File
@@ -19,16 +19,20 @@
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",
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="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] disabled:cursor-not-allowed disabled:opacity-50 {variants[variant]} {className}"
{disabled}
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] disabled:cursor-not-allowed disabled:opacity-50 {variants[
variant
]} {className}"
>
{#if Icon}<Icon size="1em" class="text-base" />{/if}
{text}
+25 -20
View File
@@ -2,12 +2,14 @@
import { onMount } from "svelte";
import { animate } from "motion";
import { delay } from "@/seqta/utils/delay.ts";
import { cloudAuth } from "@/seqta/utils/CloudAuth";
import { settingsState } from "@/seqta/utils/listeners/SettingsState";
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 }: {
const {
hidePanel,
}: {
hidePanel: () => void;
} = $props();
@@ -22,15 +24,11 @@
});
if (background && content) {
animate(
background,
{ opacity: [0, 1] },
{ duration: 0.3, ease: [0.4, 0, 0.2, 1] }
);
animate(background, { opacity: [0, 1] }, { duration: 0.3, ease: [0.4, 0, 0.2, 1] });
animate(
content,
{ scale: [0.4, 1], opacity: [0, 1] },
{ type: "spring", stiffness: 400, damping: 30 }
{ type: "spring", stiffness: 400, damping: 30 },
);
}
@@ -50,13 +48,9 @@
animate(
content,
{ scale: [1, 0.4], opacity: [1, 0] },
{ type: "spring", stiffness: 400, damping: 30 }
);
animate(
background,
{ opacity: [1, 0] },
{ ease: [0.4, 0, 0.2, 1] }
{ type: "spring", stiffness: 400, damping: 30 },
);
animate(background, { opacity: [1, 0] }, { ease: [0.4, 0, 0.2, 1] });
await delay(400);
hidePanel();
}
@@ -92,9 +86,13 @@
<!-- svelte-ignore a11y_no_static_element_interactions -->
<div
bind:this={background}
class="flex absolute top-0 left-0 z-50 justify-center items-center w-full h-full cursor-pointer bg-black/50 {$settingsState.DarkMode ? 'dark' : ''}"
class="flex absolute top-0 left-0 z-50 justify-center items-center w-full h-full cursor-pointer bg-black/50 {$settingsState.DarkMode
? 'dark'
: ''}"
onclick={handleBackgroundClick}
onkeydown={(e) => { if (e.key === "Enter") handleBackgroundClick(e as unknown as MouseEvent) }}
onkeydown={(e) => {
if (e.key === "Enter") handleBackgroundClick(e as unknown as MouseEvent);
}}
>
<div
bind:this={content}
@@ -114,16 +112,23 @@
/>
{/if}
{#if !cloudState.user?.pfpUrl}
<div class="flex items-center justify-center w-12 h-12 rounded-full bg-zinc-300 dark:bg-zinc-600 text-zinc-700 dark:text-zinc-200 font-semibold text-base">
<div
class="flex items-center justify-center w-12 h-12 rounded-full bg-zinc-300 dark:bg-zinc-600 text-zinc-700 dark:text-zinc-200 font-semibold text-base"
>
{getInitials()}
</div>
{/if}
<div class="min-w-0 flex-1">
<p class="text-sm font-medium text-zinc-900 dark:text-white truncate">
{cloudState.user?.displayName || cloudState.user?.username || cloudState.user?.email || "User"}
{cloudState.user?.displayName ||
cloudState.user?.username ||
cloudState.user?.email ||
"User"}
</p>
{#if cloudState.user?.email && cloudState.user?.email !== (cloudState.user?.displayName || cloudState.user?.username)}
<p class="text-xs text-zinc-500 dark:text-zinc-400 truncate">{cloudState.user.email}</p>
<p class="text-xs text-zinc-500 dark:text-zinc-400 truncate">
{cloudState.user.email}
</p>
{/if}
</div>
</div>
+10 -3
View File
@@ -1,8 +1,15 @@
<script lang="ts">
import { resolveCloudPfp, defaultAccountsPfpUrl, revokePfpUrl } from "@/seqta/utils/cloudPfpCache";
import type { CloudUser } from "@/seqta/utils/CloudAuth";
import {
resolveCloudPfp,
defaultAccountsPfpUrl,
revokePfpUrl,
} from "@/seqta/utils/cloudPfpCache";
import type { CloudUser } from "@/seqta/utils/cloudAuth";
const { user, class: className = "" }: {
const {
user,
class: className = "",
}: {
user: CloudUser | null | undefined;
class?: string;
} = $props();
@@ -1,11 +1,13 @@
<script lang="ts">
import browser from "@/lib/browser";
import { cloudAuth } from "@/seqta/utils/CloudAuth";
import { settingsState } from "@/seqta/utils/listeners/SettingsState";
import { cloudAuth } from "@/seqta/utils/cloudAuth";
import { settingsState } from "@/seqta/utils/listeners/settingsState";
import Button from "./Button.svelte";
import Switch from "./Switch.svelte";
let { showDisclaimer }: {
let {
showDisclaimer,
}: {
showDisclaimer: (onConfirm: () => void, onCancel: () => void) => void;
} = $props();
@@ -73,7 +75,9 @@
<div class="flex items-center justify-between gap-3">
<div>
<p class="text-[11px] font-semibold text-zinc-800 dark:text-zinc-100">Automatic sync</p>
<p class="text-[10px] text-zinc-500 dark:text-zinc-400">Syncs settings when SEQTA loads and when you make changes</p>
<p class="text-[10px] text-zinc-500 dark:text-zinc-400">
Syncs settings when SEQTA loads and when you make changes
</p>
</div>
<div class="shrink-0">
<Switch
@@ -84,11 +88,7 @@
</div>
<div class="flex flex-wrap gap-2">
<Button
text={busy ? "Please wait\u2026" : "Upload"}
onClick={upload}
disabled={busy}
/>
<Button text={busy ? "Please wait\u2026" : "Upload"} onClick={upload} disabled={busy} />
<Button
text={busy ? "Please wait\u2026" : "Download"}
onClick={promptDownload}
@@ -110,7 +110,8 @@
target="_blank"
rel="noopener noreferrer"
class="font-medium text-emerald-600 underline decoration-emerald-600/50 underline-offset-2 hover:text-emerald-700 dark:text-emerald-400 dark:hover:text-emerald-300 rounded-xs"
>Privacy policy</a>
>Privacy policy</a
>
</p>
</div>
{/if}
+84 -57
View File
@@ -1,69 +1,95 @@
<script lang="ts">
import { settingsState } from '@/seqta/utils/listeners/SettingsState'
import { onDestroy, onMount } from 'svelte'
import { settingsState } from "@/seqta/utils/listeners/settingsState";
import { onDestroy, onMount } from "svelte";
import { EditorState } from '@codemirror/state';
import { highlightSelectionMatches } from '@codemirror/search';
import { indentWithTab, history, defaultKeymap, historyKeymap } from '@codemirror/commands';
import { indentOnInput, indentUnit, bracketMatching, foldKeymap, syntaxHighlighting, defaultHighlightStyle } from '@codemirror/language';
import { closeBrackets, autocompletion, closeBracketsKeymap, completionKeymap } from '@codemirror/autocomplete';
import { highlightSpecialChars, drawSelection, rectangularSelection, crosshairCursor, highlightActiveLine, keymap, EditorView, dropCursor, type KeyBinding } from '@codemirror/view';
import { color } from '@uiw/codemirror-extensions-color'
import { Compartment } from '@codemirror/state';
import { EditorState } from "@codemirror/state";
import { highlightSelectionMatches } from "@codemirror/search";
import { indentWithTab, history, defaultKeymap, historyKeymap } from "@codemirror/commands";
import {
indentOnInput,
indentUnit,
bracketMatching,
foldKeymap,
syntaxHighlighting,
defaultHighlightStyle,
} from "@codemirror/language";
import {
closeBrackets,
autocompletion,
closeBracketsKeymap,
completionKeymap,
} from "@codemirror/autocomplete";
import {
highlightSpecialChars,
drawSelection,
rectangularSelection,
crosshairCursor,
highlightActiveLine,
keymap,
EditorView,
dropCursor,
type KeyBinding,
} from "@codemirror/view";
import { color } from "@uiw/codemirror-extensions-color";
import { Compartment } from "@codemirror/state";
import { githubLight, githubDark } from '@uiw/codemirror-theme-github';
import { githubLight, githubDark } from "@uiw/codemirror-theme-github";
import { css } from "@codemirror/lang-css";
let editor = $state<HTMLDivElement | null>(null)
let editor = $state<HTMLDivElement | null>(null);
let view: EditorView | null = null;
let unsubSettings: (() => void) | undefined;
let editorTheme = new Compartment();
let { value, onChange, className }: {value: string, onChange: (value: string) => void, className?: string} = $props()
let {
value,
onChange,
className,
}: { value: string; onChange: (value: string) => void; className?: string } = $props();
function createEditorState(initialContents: string) {
let extensions = [
highlightSpecialChars(),
history(),
drawSelection(),
indentUnit.of(" "),
EditorState.allowMultipleSelections.of(true),
indentOnInput(),
bracketMatching(),
closeBrackets(),
autocompletion(),
rectangularSelection(),
crosshairCursor(),
dropCursor(),
highlightActiveLine(),
highlightSelectionMatches(),
editorTheme.of(githubLight),
keymap.of([
indentWithTab,
...closeBracketsKeymap,
...defaultKeymap,
...historyKeymap,
...foldKeymap,
...completionKeymap,
] as KeyBinding[]),
EditorView.updateListener.of((update) => {
if (update.docChanged) {
onChange(update.state.doc.toString())
}
}),
css(),
color,
syntaxHighlighting(defaultHighlightStyle, { fallback: true }),
];
let extensions = [
highlightSpecialChars(),
history(),
drawSelection(),
indentUnit.of(" "),
EditorState.allowMultipleSelections.of(true),
indentOnInput(),
bracketMatching(),
closeBrackets(),
autocompletion(),
rectangularSelection(),
crosshairCursor(),
dropCursor(),
highlightActiveLine(),
highlightSelectionMatches(),
editorTheme.of(githubLight),
keymap.of([
indentWithTab,
...closeBracketsKeymap,
...defaultKeymap,
...historyKeymap,
...foldKeymap,
...completionKeymap,
] as KeyBinding[]),
EditorView.updateListener.of((update) => {
if (update.docChanged) {
onChange(update.state.doc.toString());
}
}),
css(),
color,
syntaxHighlighting(defaultHighlightStyle, { fallback: true }),
];
return EditorState.create({
doc: initialContents,
extensions
});
return EditorState.create({
doc: initialContents,
extensions,
});
}
function createEditorView(state: EditorState, parent: HTMLElement) {
return new EditorView({ state, parent });
return new EditorView({ state, parent });
}
onMount(() => {
@@ -75,10 +101,8 @@
unsubSettings = settingsState.subscribe((settings) => {
if (view) {
view.dispatch({
effects: editorTheme.reconfigure(
settings.DarkMode ? githubDark : githubLight
)
})
effects: editorTheme.reconfigure(settings.DarkMode ? githubDark : githubLight),
});
}
});
});
@@ -88,7 +112,10 @@
if (view) {
view.destroy();
}
})
});
</script>
<div class={`rounded-lg text-[13px] overflow-clip w-full bg-white dark:bg-zinc-900 ${className}`} bind:this={editor}></div>
<div
class={`rounded-lg text-[13px] overflow-clip w-full bg-white dark:bg-zinc-900 ${className}`}
bind:this={editor}
></div>
+32 -17
View File
@@ -1,11 +1,11 @@
<script lang="ts">
import { onMount } from 'svelte'
import { animate } from 'motion';
import { delay } from '@/seqta/utils/delay'
import { settingsState } from '@/seqta/utils/listeners/SettingsState'
import GradientPicker from './colourPicker/GradientPicker.svelte'
import { onMount } from "svelte";
import { animate } from "motion";
import { delay } from "@/seqta/utils/delay";
import { settingsState } from "@/seqta/utils/listeners/settingsState";
import GradientPicker from "./colourPicker/GradientPicker.svelte";
const PRESETS_KEY = 'colorPickerPresets';
const PRESETS_KEY = "colorPickerPresets";
const MAX_PRESETS = 18;
const DEFAULT_PRESETS = [
"linear-gradient(30deg, rgba(229,209,218,1) 0%, RGBA(235,169,202,1) 46%, rgba(214,155,162,1) 100%)",
@@ -49,12 +49,12 @@
let current = $state(initialColour());
function initialColour(): string {
return customState ?? settingsState.selectedColor ?? '';
return customState ?? settingsState.selectedColor ?? "";
}
function loadPresets(): string[] {
try {
const saved = JSON.parse(localStorage.getItem(PRESETS_KEY) ?? 'null');
const saved = JSON.parse(localStorage.getItem(PRESETS_KEY) ?? "null");
return Array.isArray(saved) ? saved : DEFAULT_PRESETS;
} catch {
return DEFAULT_PRESETS;
@@ -63,7 +63,10 @@
function rememberPreset(colour: string) {
if (!colour || presets[0] === colour) return;
const updated = [colour, ...presets.filter((preset) => preset !== colour)].slice(0, MAX_PRESETS);
const updated = [colour, ...presets.filter((preset) => preset !== colour)].slice(
0,
MAX_PRESETS,
);
localStorage.setItem(PRESETS_KEY, JSON.stringify(updated));
}
@@ -76,26 +79,34 @@
const closePicker = async () => {
if (standalone || !background || !content) return;
animate(content, { scale: [1, 0.4], opacity: [1, 0] }, { type: 'spring', stiffness: 400, damping: 30 });
animate(
content,
{ scale: [1, 0.4], opacity: [1, 0] },
{ type: "spring", stiffness: 400, damping: 30 },
);
animate(background, { opacity: [1, 0] }, { ease: [0.4, 0, 0.2, 1] });
await delay(400);
hidePicker?.();
}
};
onMount(() => {
if (!standalone && background && content) {
animate(background, { opacity: [0, 1] }, { duration: 0.3, ease: [0.4, 0, 0.2, 1] });
animate(content, { scale: [0.4, 1], opacity: [0, 1] }, { type: 'spring', stiffness: 400, damping: 30 });
animate(
content,
{ scale: [0.4, 1], opacity: [0, 1] },
{ type: "spring", stiffness: 400, damping: 30 },
);
}
const handleEscapeKey = (event: KeyboardEvent) => {
if (event.key === 'Escape') closePicker();
if (event.key === "Escape") closePicker();
};
document.addEventListener('keydown', handleEscapeKey);
document.addEventListener("keydown", handleEscapeKey);
return () => {
document.removeEventListener('keydown', handleEscapeKey);
document.removeEventListener("keydown", handleEscapeKey);
if (savePresets && !customOnChange) rememberPreset(current);
};
});
@@ -113,9 +124,13 @@
<!-- svelte-ignore a11y_no_static_element_interactions -->
<div
bind:this={background}
class="flex absolute top-0 left-0 z-50 justify-center items-center w-full h-full shadow-2xl cursor-pointer bg-black/20 border border-[#DDDDDD]/30 dark:border-[#38373D]/30 {$settingsState.DarkMode ? 'dark' : ''}"
class="flex absolute top-0 left-0 z-50 justify-center items-center w-full h-full shadow-2xl cursor-pointer bg-black/20 border border-[#DDDDDD]/30 dark:border-[#38373D]/30 {$settingsState.DarkMode
? 'dark'
: ''}"
onclick={handleBackgroundClick}
onkeydown={(event) => { if (event.key === 'Enter') handleBackgroundClick(event as unknown as MouseEvent) }}
onkeydown={(event) => {
if (event.key === "Enter") handleBackgroundClick(event as unknown as MouseEvent);
}}
>
<div
bind:this={content}
@@ -5,7 +5,7 @@
import QRCode from "qrcode";
import Button from "./Button.svelte";
import { portal } from "../utils/portal";
import { settingsState } from "@/seqta/utils/listeners/SettingsState";
import { settingsState } from "@/seqta/utils/listeners/settingsState";
let showQrModal = $state(false);
let qrDataUrl = $state<string | null>(null);
@@ -80,7 +80,7 @@
qrDataUrl = dataUrl;
showQrModal = true;
} catch (err) {
console.error("[ConnectMobileApp] Failed to generate QR:", err);
console.error("[BetterSEQTA+] ConnectMobileApp: Failed to generate QR:", err);
errorMessage = "Failed to generate QR code. Please try again.";
} finally {
isLoading = false;
@@ -108,7 +108,11 @@
</script>
<div class="flex flex-col gap-1 items-end">
<Button onClick={generateQrCode} disabled={isLoading} text={isLoading ? "Generating..." : "Generate QR"} />
<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}
@@ -117,7 +121,9 @@
{#if showQrModal && qrDataUrl}
<div
use:portal
class="fixed cursor-auto inset-0 z-10000 flex justify-center items-center bg-black/50 {isStandalone ? 'backdrop-blur-xs' : ''} {$settingsState.DarkMode ? 'dark' : ''}"
class="fixed cursor-auto inset-0 z-10000 flex justify-center items-center bg-black/50 {isStandalone
? 'backdrop-blur-xs'
: ''} {$settingsState.DarkMode ? 'dark' : ''}"
role="button"
tabindex="-1"
onclick={(e) => {
@@ -126,19 +132,22 @@
onkeydown={(e) => {
if (e.key === "Escape") closeModal();
}}
transition:fade={{ duration: 150 }}>
transition:fade={{ duration: 150 }}
>
<!-- svelte-ignore a11y_no_static_element_interactions -->
<div
class="p-6 mx-4 w-full max-w-sm bg-white rounded-2xl shadow-2xl dark:bg-zinc-800"
onclick={(e) => e.stopPropagation()}
onkeydown={(e) => e.stopPropagation()}>
onkeydown={(e) => e.stopPropagation()}
>
<div class="flex justify-between items-center mb-4">
<h2 class="text-lg font-bold text-zinc-900 dark:text-white">Scan with DesQTA</h2>
<button
type="button"
onclick={closeModal}
class="p-2 rounded-lg transition-colors text-zinc-500 hover:text-zinc-700 hover:bg-zinc-100 dark:hover:text-zinc-400 dark:hover:bg-zinc-700"
aria-label="Close">
aria-label="Close"
>
<XIcon class="w-5 h-5" />
</button>
</div>
@@ -149,13 +158,15 @@
<button
type="button"
onclick={openAppLink}
class="px-4 py-2.5 w-full text-sm font-medium text-white bg-indigo-600 rounded-lg transition-colors dark:bg-indigo-500 hover:bg-indigo-700 dark:hover:bg-indigo-600">
class="px-4 py-2.5 w-full text-sm font-medium text-white bg-indigo-600 rounded-lg transition-colors dark:bg-indigo-500 hover:bg-indigo-700 dark:hover:bg-indigo-600"
>
Sign into DesQTA Desktop
</button>
<button
type="button"
onclick={downloadQrImage}
class="px-4 py-2 w-full text-xs font-medium rounded-lg border transition-colors text-zinc-500 dark:text-zinc-400 border-zinc-200 dark:border-zinc-600 hover:bg-zinc-50 dark:hover:bg-zinc-800/50">
class="px-4 py-2 w-full text-xs font-medium rounded-lg border transition-colors text-zinc-500 dark:text-zinc-400 border-zinc-200 dark:border-zinc-600 hover:bg-zinc-50 dark:hover:bg-zinc-800/50"
>
Download QR as image
</button>
</div>
+23 -17
View File
@@ -1,9 +1,14 @@
<script lang="ts">
import { fade } from 'svelte/transition';
import { animate } from 'motion';
import { settingsState } from '@/seqta/utils/listeners/SettingsState';
import { fade } from "svelte/transition";
import { animate } from "motion";
import { settingsState } from "@/seqta/utils/listeners/settingsState";
let { onConfirm, onCancel, title, message }: {
let {
onConfirm,
onCancel,
title,
message,
}: {
onConfirm: () => void;
onCancel: () => void;
title: string;
@@ -18,39 +23,41 @@
modalElement,
{ scale: [0.9, 1], opacity: [0, 1] },
{
type: 'spring',
type: "spring",
stiffness: 300,
damping: 25
}
damping: 25,
},
);
}
});
</script>
<div
class="flex fixed inset-0 z-10000 justify-center items-center bg-black/50 {$settingsState.DarkMode ? 'dark' : ''}"
<div
class="flex fixed inset-0 z-10000 justify-center items-center bg-black/50 {$settingsState.DarkMode
? 'dark'
: ''}"
style="position: fixed; top: 0; left: 0; right: 0; bottom: 0;"
onclick={(e) => {
if (e.target === e.currentTarget) onCancel();
}}
}}
onkeydown={(e) => {
if (e.key === 'Escape') onCancel();
}}
role="button"
tabindex="-1"
if (e.key === "Escape") onCancel();
}}
role="button"
tabindex="-1"
transition:fade={{ duration: 150 }}
>
<!-- svelte-ignore a11y_no_static_element_interactions -->
<div
bind:this={modalElement}
class="p-4 mx-4 w-full max-w-md bg-white rounded-2xl shadow-2xl dark:bg-zinc-800"
class="p-4 mx-4 w-full max-w-md bg-white rounded-2xl shadow-2xl dark:bg-zinc-800"
onclick={(e) => e.stopPropagation()}
onkeydown={(e) => e.stopPropagation()}
>
<h2 class="mb-3 text-xl font-bold text-gray-900 dark:text-white">
{title}
</h2>
<div class="mb-6 text-lg text-gray-700 whitespace-pre-line dark:text-gray-300">
{message}
</div>
@@ -71,4 +78,3 @@
</div>
</div>
</div>
+15 -12
View File
@@ -22,10 +22,13 @@
validateFeedbackForm,
type FeedbackStatusItem,
} from "@/seqta/utils/feedback/client";
import { settingsState } from "@/seqta/utils/listeners/SettingsState";
import { settingsState } from "@/seqta/utils/listeners/settingsState";
import Spinner from "./Spinner.svelte";
let { onClose, initialFeedbackId = null }: {
let {
onClose,
initialFeedbackId = null,
}: {
onClose: () => void;
initialFeedbackId?: string | null;
} = $props();
@@ -56,8 +59,7 @@
? "background-color:#18181b;color:#fafafa;border-color:#52525b;color-scheme:dark"
: "background-color:#fff;color:#18181b;border-color:#e4e4e7;color-scheme:light",
);
const field =
"feedback-field w-full px-3 py-2.5 text-[18px] rounded-lg border ";
const field = "feedback-field w-full px-3 py-2.5 text-[18px] rounded-lg border ";
const btn =
"px-4 py-2 text-[18px] font-medium rounded-lg transition-all duration-200 hover:scale-105 active:scale-95 disabled:opacity-50";
const btnMuted = $derived(
@@ -412,8 +414,9 @@
{:else}
<p class="mb-4 text-zinc-500">No response yet.</p>
{/if}
{#if statusError}<p class="mb-3 text-red-600 dark:text-red-400" role="alert">{statusError}</p
>{/if}
{#if statusError}<p class="mb-3 text-red-600 dark:text-red-400" role="alert">
{statusError}
</p>{/if}
<div class="flex gap-3 justify-end">
<button
type="button"
@@ -437,8 +440,9 @@
{statusLoading ? "…" : "Refresh"}
</button>
</div>
{#if statusError}<p class="mb-3 text-red-600 dark:text-red-400" role="alert">{statusError}</p
>{/if}
{#if statusError}<p class="mb-3 text-red-600 dark:text-red-400" role="alert">
{statusError}
</p>{/if}
{#if statusLoading && !statusItems.length}
<div class="feedback-loading" aria-busy="true" aria-live="polite">
<Spinner size="md" />
@@ -461,14 +465,13 @@
<button
type="button"
onclick={() => openStatusItem(item.id)}
class="w-full p-3 text-left rounded-lg border transition-all duration-200 hover:scale-[1.01] {isDark
class="w-full p-3 text-left rounded-lg border transition-all duration-200 hover:scale-[1.01] {isDark
? 'border-zinc-700 bg-zinc-900/40'
: 'border-zinc-200 bg-white'}"
>
<p class="text-base text-zinc-500 mb-0.5">
{formatStatus(item.status)}{#if hasReply(item)} · Reply{/if} · {categoryLabel(
item.category,
)}
{formatStatus(item.status)}{#if hasReply(item)}
· Reply{/if} · {categoryLabel(item.category)}
</p>
<p class="font-medium truncate">{item.subject || "Untitled"}</p>
</button>
+13 -15
View File
@@ -1,15 +1,15 @@
<script lang="ts">
import { fade } from "svelte/transition";
import { onMount } from "svelte";
import { settingsState } from "@/seqta/utils/listeners/SettingsState";
import { settingsState } from "@/seqta/utils/listeners/settingsState";
import { FONT_PRESETS, DEFAULT_FONT_ID, getFontPreset } from "@/seqta/ui/fonts/presets";
import {
applySelectedFont,
buildFontPreviewCss,
ensureFontPickerFontsLoaded,
} from "@/seqta/ui/fonts/Manager";
} from "@/seqta/ui/fonts/fontManager";
import { portal } from "@/interface/utils/portal";
import { syncPageThemeToElement } from "@/interface/utils/syncPageTheme";
import { copyPageTheme, resolvePageAccentColor } from "@/seqta/ui/colors/pageTheme";
import fontPickerStyles from "./fontPickerModal.css?inline";
let { hidePicker }: { hidePicker: () => void } = $props();
@@ -33,15 +33,16 @@
}
function syncTheme() {
if (rootEl) syncPageThemeToElement(rootEl);
if (rootEl) {
copyPageTheme(rootEl);
rootEl.style.setProperty("--better-main", resolvePageAccentColor());
}
}
onMount(() => {
void ensureFontPickerFontsLoaded();
styleEl = document.getElementById(
"betterseqta-font-picker-styles",
) as HTMLStyleElement | null;
styleEl = document.getElementById("betterseqta-font-picker-styles") as HTMLStyleElement | null;
if (!styleEl) {
styleEl = document.createElement("style");
styleEl.id = "betterseqta-font-picker-styles";
@@ -77,7 +78,8 @@
class="bsplus-font-picker-overlay bsplus-font-picker-root"
onclick={handleBackdropClick}
onkeydown={(event) => {
if (event.key === "Enter" || event.key === " ") handleBackdropClick(event as unknown as MouseEvent);
if (event.key === "Enter" || event.key === " ")
handleBackdropClick(event as unknown as MouseEvent);
}}
role="presentation"
transition:fade={{ duration: 200 }}
@@ -112,12 +114,8 @@
</button>
</div>
<div class="bsplus-font-picker-header-text">
<h2 id="font-picker-title" class="bsplus-font-picker-title">
Choose a font
</h2>
<p class="bsplus-font-picker-desc">
Choose a typeface for SEQTA Learn.
</p>
<h2 id="font-picker-title" class="bsplus-font-picker-title">Choose a font</h2>
<p class="bsplus-font-picker-desc">Choose a typeface for SEQTA Learn.</p>
</div>
</header>
@@ -130,7 +128,7 @@
data-font-id={preset.id}
>
<div class="bsplus-font-picker-option-head">
<span
<span
class="bsplus-font-picker-option-name"
style="font-family: {preset.stack} !important;"
>
+74 -64
View File
@@ -1,9 +1,15 @@
<script lang="ts">
import { isValidHotkey, parseHotkey } from '@/plugins/built-in/globalSearch/src/utils/hotkeyUtils';
import {
isValidHotkey,
parseHotkey,
} from "@/plugins/built-in/globalSearch/src/utils/hotkeyUtils";
let { value, onChange }: {
value: string,
onChange: (newValue: string) => void
let {
value,
onChange,
}: {
value: string;
onChange: (newValue: string) => void;
} = $props();
let isRecording = $state(false);
@@ -13,43 +19,43 @@
const formatKeyForHotkey = (key: string): string => {
// Map special keys to their hotkey format
const keyMap: Record<string, string> = {
'Control': 'ctrl',
'Meta': 'cmd',
'Alt': 'alt',
'Shift': 'shift',
' ': 'space',
'ArrowUp': 'up',
'ArrowDown': 'down',
'ArrowLeft': 'left',
'ArrowRight': 'right',
'Escape': 'esc',
'Enter': 'enter',
'Tab': 'tab',
'Backspace': 'backspace',
'Delete': 'delete',
Control: "ctrl",
Meta: "cmd",
Alt: "alt",
Shift: "shift",
" ": "space",
ArrowUp: "up",
ArrowDown: "down",
ArrowLeft: "left",
ArrowRight: "right",
Escape: "esc",
Enter: "enter",
Tab: "tab",
Backspace: "backspace",
Delete: "delete",
};
return keyMap[key] || key.toLowerCase();
};
const formatKeyForDisplay = (key: string): string => {
const isMac = navigator.platform.toUpperCase().indexOf('MAC') >= 0;
const isMac = navigator.platform.toUpperCase().indexOf("MAC") >= 0;
const keyMap: Record<string, string> = {
'ctrl': isMac ? '⌃' : 'Ctrl',
'cmd': '⌘',
'meta': '⌘',
'alt': isMac ? '⌥' : 'Alt',
'shift': isMac ? '⇧' : 'Shift',
'space': 'Space',
'up': '↑',
'down': '↓',
'left': '←',
'right': '→',
'esc': 'Esc',
'enter': 'Enter',
'tab': 'Tab',
'backspace': 'Backspace',
'delete': 'Delete',
ctrl: isMac ? "⌃" : "Ctrl",
cmd: "⌘",
meta: "⌘",
alt: isMac ? "⌥" : "Alt",
shift: isMac ? "⇧" : "Shift",
space: "Space",
up: "↑",
down: "↓",
left: "←",
right: "→",
esc: "Esc",
enter: "Enter",
tab: "Tab",
backspace: "Backspace",
delete: "Delete",
};
return keyMap[key.toLowerCase()] || key.toUpperCase();
@@ -62,15 +68,15 @@
const parsed = parseHotkey(hotkeyString);
const parts: string[] = [];
// Add modifiers in a consistent order
if (parsed.ctrl) parts.push('ctrl');
if (parsed.meta) parts.push('cmd');
if (parsed.alt) parts.push('alt');
if (parsed.shift) parts.push('shift');
if (parsed.ctrl) parts.push("ctrl");
if (parsed.meta) parts.push("cmd");
if (parsed.alt) parts.push("alt");
if (parsed.shift) parts.push("shift");
if (parsed.key) parts.push(parsed.key);
return parts;
};
@@ -82,8 +88,8 @@
const stopRecording = () => {
if (recordedKeys.size > 0) {
if (recordedKeys.has('esc')) {
onChange('');
if (recordedKeys.has("esc")) {
onChange("");
isRecording = false;
recordedKeys = new Set();
inputElement?.blur();
@@ -91,10 +97,10 @@
}
const modifiers: string[] = [];
let mainKey = '';
let mainKey = "";
for (const key of recordedKeys) {
if (['ctrl', 'cmd', 'alt', 'shift'].includes(key)) {
if (["ctrl", "cmd", "alt", "shift"].includes(key)) {
modifiers.push(key);
} else {
mainKey = key;
@@ -102,13 +108,13 @@
}
if (mainKey) {
const hotkeyString = [...modifiers, mainKey].join('+');
const hotkeyString = [...modifiers, mainKey].join("+");
if (isValidHotkey(hotkeyString)) {
onChange(hotkeyString);
}
}
}
isRecording = false;
recordedKeys = new Set();
inputElement?.blur();
@@ -122,24 +128,24 @@
const handleKeyDown = (e: KeyboardEvent) => {
if (!isRecording) return;
e.preventDefault();
e.stopPropagation();
const key = formatKeyForHotkey(e.key);
if (e.ctrlKey) addRecordedKey('ctrl');
if (e.metaKey) addRecordedKey('cmd');
if (e.altKey) addRecordedKey('alt');
if (e.shiftKey) addRecordedKey('shift');
if (e.ctrlKey) addRecordedKey("ctrl");
if (e.metaKey) addRecordedKey("cmd");
if (e.altKey) addRecordedKey("alt");
if (e.shiftKey) addRecordedKey("shift");
// Add the main key (ignore modifier keys themselves)
if (!['ctrl', 'cmd', 'alt', 'shift'].includes(key)) {
if (!["ctrl", "cmd", "alt", "shift"].includes(key)) {
addRecordedKey(key);
}
// Auto-stop recording if we have a main key
if (!['ctrl', 'cmd', 'alt', 'shift'].includes(key)) {
if (!["ctrl", "cmd", "alt", "shift"].includes(key)) {
setTimeout(stopRecording, 100);
}
};
@@ -162,16 +168,18 @@
}
});
const hotkeyParts = $derived(isRecording
? Array.from(recordedKeys).map(formatKeyForDisplay)
: getHotkeyParts(value).map(formatKeyForDisplay));
const hotkeyParts = $derived(
isRecording
? Array.from(recordedKeys).map(formatKeyForDisplay)
: getHotkeyParts(value).map(formatKeyForDisplay),
);
</script>
<div class="flex gap-2 items-center">
<div class="relative">
{#if isRecording}
<!-- Recording state -->
<div
<div
class="flex items-center justify-center px-3 py-1.5 text-sm rounded-md dark:bg-[#38373D]/50 bg-[#DDDDDD]/50 border-[#DDDDDD]/30 dark:border-[#38373D]/30 dark:text-white border cursor-pointer text-nowrap"
onclick={startRecording}
onkeydown={startRecording}
@@ -182,7 +190,7 @@
</div>
{:else if hotkeyParts.length > 0}
<!-- Display current hotkey -->
<div
<div
class="flex gap-1 items-center text-sm rounded-md border-none cursor-pointer dark:text-white"
onclick={startRecording}
onkeydown={startRecording}
@@ -190,14 +198,16 @@
tabindex="0"
>
{#each hotkeyParts as part}
<div class="size-8 text-sm flex items-center justify-center rounded-md border dark:bg-[#38373D]/50 bg-[#DDDDDD]/50 border-[#DDDDDD]/30 dark:border-[#38373D]/30">
<div
class="size-8 text-sm flex items-center justify-center rounded-md border dark:bg-[#38373D]/50 bg-[#DDDDDD]/50 border-[#DDDDDD]/30 dark:border-[#38373D]/30"
>
{part}
</div>
{/each}
</div>
{:else}
<!-- Empty state -->
<div
<div
class="flex items-center justify-center px-3 py-2 text-sm rounded-md dark:bg-[#38373D]/50 bg-[#DDDDDD] dark:text-white border-none cursor-pointer text-nowrap"
onclick={startRecording}
onkeydown={startRecording}
@@ -225,4 +235,4 @@
input:focus {
outline: none;
}
</style>
</style>
+40 -33
View File
@@ -1,15 +1,22 @@
<script lang="ts">
import { onMount, onDestroy } from 'svelte';
import { animate as motionAnimate } from 'motion';
import { fullMotionEffectsEnabled } from '@/seqta/utils/performanceMode';
import { onMount, onDestroy } from "svelte";
import { animate as motionAnimate } from "motion";
import { fullMotionEffectsEnabled } from "@/seqta/utils/performanceMode";
let { initial, animate, exit, transition, children, class: className }: {
initial?: any,
animate?: any,
exit?: any,
transition?: any,
children?: any,
class?: string
let {
initial,
animate,
exit,
transition,
children,
class: className,
}: {
initial?: any;
animate?: any;
exit?: any;
transition?: any;
children?: any;
class?: string;
} = $props();
let divElement: HTMLElement;
@@ -18,12 +25,12 @@
if (!divElement || !keyframe) return;
if (keyframe.x != null) {
divElement.style.transition =
'transform var(--bs-motion-duration, 0.2s) var(--bs-motion-ease, cubic-bezier(0.22, 1, 0.36, 1))';
"transform var(--bs-motion-duration, 0.2s) var(--bs-motion-ease, cubic-bezier(0.22, 1, 0.36, 1))";
const x = keyframe.x;
divElement.style.transform =
typeof x === 'number' ? `translateX(${x}px)` : `translateX(${String(x)})`;
typeof x === "number" ? `translateX(${x}px)` : `translateX(${String(x)})`;
}
if (typeof keyframe.opacity === 'number') {
if (typeof keyframe.opacity === "number") {
divElement.style.opacity = String(keyframe.opacity);
}
};
@@ -37,34 +44,30 @@
let finalKeyframe = { ...keyframe };
if (finalKeyframe.height === 'auto') {
if (finalKeyframe.height === "auto") {
const prevHeight = divElement.style.height;
const prevVisibility = divElement.style.visibility;
divElement.style.height = 'auto';
divElement.style.visibility = 'hidden';
divElement.style.position = 'absolute';
divElement.style.height = "auto";
divElement.style.visibility = "hidden";
divElement.style.position = "absolute";
const autoHeight = divElement.offsetHeight;
divElement.style.height = prevHeight;
divElement.style.visibility = prevVisibility;
divElement.style.position = '';
divElement.style.position = "";
finalKeyframe.height = `${autoHeight}px`;
}
const defaultSpringConfig = { stiffness: 250, damping: 25 };
const animation = motionAnimate(
[divElement],
finalKeyframe,
{
type: 'spring',
stiffness: transition?.stiffness || defaultSpringConfig.stiffness,
damping: transition?.damping || defaultSpringConfig.damping
}
);
const animation = motionAnimate([divElement], finalKeyframe, {
type: "spring",
stiffness: transition?.stiffness || defaultSpringConfig.stiffness,
damping: transition?.damping || defaultSpringConfig.damping,
});
return animation;
}
return Promise.resolve();
@@ -78,7 +81,7 @@
await playAnimation(animate);
}
});
$effect(() => {
if (animate) {
playAnimation(animate);
@@ -92,7 +95,11 @@
});
</script>
<div class={className} bind:this={divElement} style={fullMotionEffectsEnabled() ? 'will-change: transform, opacity;' : undefined}>
<div
class={className}
bind:this={divElement}
style={fullMotionEffectsEnabled() ? "will-change: transform, opacity;" : undefined}
>
{#if children}
{@render children()}
{/if}
+2 -2
View File
@@ -1,5 +1,5 @@
<script lang="ts">
import { settingsState } from '@/seqta/utils/listeners/SettingsState'
import { settingsState } from "@/seqta/utils/listeners/settingsState";
let { onClick }: { onClick: () => void } = $props();
</script>
@@ -9,4 +9,4 @@
onclick={onClick}
style="background: {$settingsState.selectedColor}"
class="w-16 h-8 rounded-md shadow-2xl ring-[1px] ring-[#DDDDDD]/30 dark:ring-[#38373D]/30"
></button>
></button>
@@ -1,6 +1,9 @@
<script lang="ts">
import XIcon from "@lucide/svelte/icons/x";
let { onclick, label = "Close" }: {
let {
onclick,
label = "Close",
}: {
onclick: () => void;
label?: string;
} = $props();
+9 -7
View File
@@ -1,9 +1,13 @@
<script lang="ts">
import ChevronDownIcon from "@lucide/svelte/icons/chevron-down";
let { value, onChange, options }: {
value: string,
onChange: (newValue: string) => void,
options: Array<{ value: string, label: string }>
let {
value,
onChange,
options,
}: {
value: string;
onChange: (newValue: string) => void;
options: Array<{ value: string; label: string }>;
} = $props();
const listboxId = $props.id();
@@ -143,9 +147,7 @@
--sel-bg: var(--theme-primary, #ffffff);
--sel-surface: var(--theme-secondary, #e5e7eb);
--sel-menu-shadow:
0 10px 25px -5px rgb(0 0 0 / 0.25),
0 8px 10px -6px rgb(0 0 0 / 0.2);
--sel-menu-shadow: 0 10px 25px -5px rgb(0 0 0 / 0.25), 0 8px 10px -6px rgb(0 0 0 / 0.2);
}
.select-trigger {
@@ -4,9 +4,9 @@
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 { settingsState } from "@/seqta/utils/listeners/settingsState";
import { matchesSearch } from "@/interface/pages/settings/shared";
import type { SettingsList } from "@/interface/types/SettingsProps";
import type { SettingsList } from "@/interface/types/settingsProps";
import {
DEFAULT_SIDEBAR_BLUR,
DEFAULT_SIDEBAR_RADIUS,
+8 -2
View File
@@ -14,7 +14,11 @@
}[];
};
let { groups, selectedId, onselect }: {
let {
groups,
selectedId,
onselect,
}: {
groups: NavGroup[];
selectedId: string;
onselect: (id: string) => void;
@@ -74,7 +78,9 @@
{/if}
{#each group.items as item (item.id)}
{#if item.divided}
<div class="my-2 border-t border-zinc-200 dark:border-zinc-700 {item.nested ? 'ml-4' : ''}"></div>
<div
class="my-2 border-t border-zinc-200 dark:border-zinc-700 {item.nested ? 'ml-4' : ''}"
></div>
{/if}
<SidebarNavItem
label={item.label}
@@ -21,9 +21,7 @@
data-nav-section={trackId}
{onclick}
class="relative z-10 rounded-lg text-left transition-[color,background-color] duration-200
{nested
? 'ml-4 w-[calc(100%-1rem)] px-3 py-2 text-base'
: 'w-full px-3 py-2.5 text-lg'}
{nested ? 'ml-4 w-[calc(100%-1rem)] px-3 py-2 text-base' : 'w-full px-3 py-2.5 text-lg'}
{active || emphasized
? 'font-medium text-zinc-900 dark:text-white'
: 'text-zinc-600 hover:text-zinc-900 dark:text-zinc-300 dark:hover:text-white'}"
@@ -2,7 +2,7 @@
import { fade } from "svelte/transition";
import { animate } from "motion";
import { onMount } from "svelte";
import { cloudAuth } from "@/seqta/utils/CloudAuth";
import { cloudAuth } from "@/seqta/utils/cloudAuth";
let { onClose }: { onClose: () => void } = $props();
let modalElement: HTMLElement;
@@ -47,12 +47,11 @@
onclick={(e) => e.stopPropagation()}
onkeydown={(e) => e.stopPropagation()}
>
<h2 class="mb-3 text-xl font-bold text-zinc-900 dark:text-white">
Sign in to favorite themes
</h2>
<h2 class="mb-3 text-xl font-bold text-zinc-900 dark:text-white">Sign in to favorite themes</h2>
<p class="mb-4 text-sm text-zinc-600 dark:text-zinc-400">
Sign in to the Theme Store to save favorites across devices, or create an account to get started.
Sign in to the Theme Store to save favorites across devices, or create an account to get
started.
</p>
<button
+16 -10
View File
@@ -1,10 +1,16 @@
<script lang="ts">
let { state = $bindable(), onChange, min = 0, max = 100, step = 1 }: {
state: number,
onChange: (value: number) => void,
min?: number,
max?: number,
step?: number
let {
state = $bindable(),
onChange,
min = 0,
max = 100,
step = 1,
}: {
state: number;
onChange: (value: number) => void;
min?: number;
max?: number;
step?: number;
} = $props();
let percentage = $derived(((state - min) / (max - min)) * 100);
</script>
@@ -12,9 +18,9 @@
<div class="relative w-full min-w-0">
<input
type="range"
min={min}
max={max}
step={step}
{min}
{max}
{step}
bind:value={state}
style={`background: linear-gradient(to right, #30d259ad 0%, #30D259 ${percentage}%, #dddddd ${percentage}%)`}
oninput={(e) => onChange(Number(e.currentTarget.value))}
@@ -43,4 +49,4 @@
cursor: pointer;
border-radius: 50%;
}
</style>
</style>
+6 -13
View File
@@ -1,10 +1,10 @@
<script lang="ts">
let { size = 'md', color = 'currentColor' } = $props();
let { size = "md", color = "currentColor" } = $props();
const sizeMap = {
sm: '1rem',
md: '2rem',
lg: '3rem',
sm: "1rem",
md: "2rem",
lg: "3rem",
};
let dimensions = $derived(sizeMap[size as keyof typeof sizeMap] || size);
@@ -18,17 +18,10 @@
width={dimensions}
height={dimensions}
>
<circle
class="opacity-25"
cx="12"
cy="12"
r="10"
stroke={color}
stroke-width="4"
></circle>
<circle class="opacity-25" cx="12" cy="12" r="10" stroke={color} stroke-width="4"></circle>
<path
class="opacity-75"
fill={color}
d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"
></path>
</svg>
</svg>
+13 -6
View File
@@ -1,15 +1,18 @@
<script lang="ts">
import { onMount } from "svelte";
import { standalone } from '../utils/standalone.svelte';
import { fullMotionEffectsEnabled } from '@/seqta/utils/performanceMode';
import { standalone } from "../utils/standalone.svelte";
import { fullMotionEffectsEnabled } from "@/seqta/utils/performanceMode";
let { state: checked, onChange }: { state: boolean, onChange: (newState: boolean) => void } = $props();
let { state: checked, onChange }: { state: boolean; onChange: (newState: boolean) => void } =
$props();
let motionReady = $state(false);
onMount(() => {
// Paint the hydrated position before enabling transitions for later toggles.
let frame = requestAnimationFrame(() => {
frame = requestAnimationFrame(() => { motionReady = true; });
frame = requestAnimationFrame(() => {
motionReady = true;
});
});
return () => cancelAnimationFrame(frame);
});
@@ -18,7 +21,9 @@
</script>
<div
class="flex w-14 p-1 cursor-pointer transition-all duration-150 rounded-full bg-linear-to-tr select-none shadow-2xl ring-[1px] ring-[#DDDDDD]/30 dark:ring-[#38373D]/30 {checked ? 'to-[#30D259]/80 from-[#30D259] dark:from-[#30D259]/40 dark:to-[#30D259]' : 'dark:from-[#38373D]/50 dark:to-[#38373D] to-[#DDDDDD]/50 from-[#DDDDDD]'}"
class="flex w-14 p-1 cursor-pointer transition-all duration-150 rounded-full bg-linear-to-tr select-none shadow-2xl ring-[1px] ring-[#DDDDDD]/30 dark:ring-[#38373D]/30 {checked
? 'to-[#30D259]/80 from-[#30D259] dark:from-[#30D259]/40 dark:to-[#30D259]'
: 'dark:from-[#38373D]/50 dark:to-[#38373D] to-[#DDDDDD]/50 from-[#DDDDDD]'}"
onclick={() => onChange(!checked)}
onkeydown={(e) => e.key === "Enter" && onChange(!checked)}
role="switch"
@@ -33,6 +38,8 @@
<style>
@media (prefers-reduced-motion: reduce) {
[role="switch"] > div { transition: none !important; }
[role="switch"] > div {
transition: none !important;
}
}
</style>
@@ -11,7 +11,10 @@
props?: Record<string, unknown>;
};
let { tabs, activeTab = $bindable(0) }: {
let {
tabs,
activeTab = $bindable(0),
}: {
tabs: TabDef[];
activeTab?: number;
} = $props();
@@ -28,7 +31,10 @@
</script>
<div class="flex flex-col h-full min-h-0">
<div class="top-0 z-10 shrink-0 text-[0.875rem] pb-0.5 mx-4 px-2 tab-width-container" role="tablist">
<div
class="top-0 z-10 shrink-0 text-[0.875rem] pb-0.5 mx-4 px-2 tab-width-container"
role="tablist"
>
<div class="flex relative">
<div
class="absolute top-0 left-0 z-0 h-full bg-linear-to-tr dark:from-[#38373D]/80 dark:to-[#38373D] from-[#DDDDDD]/80 to-[#DDDDDD] rounded-full opacity-40 tab-width"
@@ -70,6 +76,8 @@
<style>
@media (prefers-reduced-motion: reduce) {
.tab-width { transition: none !important; }
.tab-width {
transition: none !important;
}
}
</style>
@@ -87,7 +87,10 @@
return $state.snapshot(model) as ColourValue;
}
function withStops(m: ColourValue, update: (stops: GradientStop[]) => GradientStop[]): ColourValue {
function withStops(
m: ColourValue,
update: (stops: GradientStop[]) => GradientStop[],
): ColourValue {
return m.kind === "solid" ? m : { ...m, stops: update(m.stops) };
}
@@ -96,7 +99,9 @@
commit(
m.kind === "solid"
? { kind: "solid", colour }
: withStops(m, (all) => all.map((stop, i) => (i === selected ? { ...stop, colour } : stop))),
: withStops(m, (all) =>
all.map((stop, i) => (i === selected ? { ...stop, colour } : stop)),
),
);
}
@@ -164,7 +169,11 @@
}
function moveStop(index: number, position: number) {
commit(withStops(snapshot(), (all) => all.map((stop, i) => (i === index ? { ...stop, position } : stop))));
commit(
withStops(snapshot(), (all) =>
all.map((stop, i) => (i === index ? { ...stop, position } : stop)),
),
);
}
function startStopDrag(event: PointerEvent, index: number) {
@@ -236,85 +245,95 @@
<div class="flex flex-col gap-3 w-72 max-w-full text-zinc-900 select-none dark:text-white">
<div>
<div class="grid relative grid-cols-3 p-0.5 rounded-lg bg-zinc-100 dark:bg-zinc-700/70" role="radiogroup" aria-label="Fill type">
<div
class="absolute left-0.5 inset-y-0.5 w-[calc((100%-0.25rem)/3)] rounded-md bg-white shadow-sm transition-transform duration-200 ease-out motion-reduce:transition-none dark:bg-zinc-600"
style="transform: translateX({modeIndex * 100}%);"
aria-hidden="true"
></div>
{#each MODES as mode (mode.kind)}
<button
type="button"
role="radio"
aria-checked={model.kind === mode.kind}
class="relative py-1 text-xs font-medium rounded-md transition-colors duration-200 {model.kind === mode.kind
? 'text-zinc-900 dark:text-white'
: 'text-zinc-500 hover:text-zinc-900 dark:text-zinc-300 dark:hover:text-white'}"
onclick={() => setMode(mode.kind)}
>
{mode.label}
</button>
{/each}
</div>
{#if model.kind !== "solid"}
<div class="flex gap-2 items-center pt-3" transition:slide={{ duration: 180 }}>
class="grid relative grid-cols-3 p-0.5 rounded-lg bg-zinc-100 dark:bg-zinc-700/70"
role="radiogroup"
aria-label="Fill type"
>
<div
class="flex-1 px-2.5 py-1.5 cursor-copy touch-none"
role="group"
aria-label="Gradient stops"
onpointerdown={addStop}
onpointermove={(event) => {
if (dragging !== null) moveStop(dragging, barPosition(event));
}}
onpointerup={() => (dragging = null)}
onpointercancel={() => (dragging = null)}
>
<div
bind:this={bar}
class="relative h-3 rounded-full ring-1 ring-inset ring-black/10 dark:ring-white/10"
style="background: linear-gradient(to right, {formatStops(stops)}), {CHECKERBOARD};"
class="absolute left-0.5 inset-y-0.5 w-[calc((100%-0.25rem)/3)] rounded-md bg-white shadow-sm transition-transform duration-200 ease-out motion-reduce:transition-none dark:bg-zinc-600"
style="transform: translateX({modeIndex * 100}%);"
aria-hidden="true"
></div>
{#each MODES as mode (mode.kind)}
<button
type="button"
role="radio"
aria-checked={model.kind === mode.kind}
class="relative py-1 text-xs font-medium rounded-md transition-colors duration-200 {model.kind ===
mode.kind
? 'text-zinc-900 dark:text-white'
: 'text-zinc-500 hover:text-zinc-900 dark:text-zinc-300 dark:hover:text-white'}"
onclick={() => setMode(mode.kind)}
>
{#each stops as stop, index (index)}
<button
type="button"
class="absolute top-1/2 handle cursor-grab active:cursor-grabbing {index === selected ? 'handle-selected' : ''}"
style="left: {stop.position}%; --swatch: {formatColour(stop.colour)};"
aria-label="Colour stop at {Math.round(stop.position)}%"
aria-pressed={index === selected}
onpointerdown={(event) => startStopDrag(event, index)}
onkeydown={(event) => stopKeys(event, index)}
></button>
{/each}
</div>
</div>
{#if model.kind === "linear"}
<label class="flex shrink-0 items-center px-2 w-14 h-7 text-xs rounded-md bg-zinc-100 dark:bg-zinc-700/70">
<input
type="number"
min="0"
max="360"
class="p-0 w-full min-w-0 text-xs text-right bg-transparent border-0 outline-none select-text picker-number"
aria-label="Gradient angle in degrees"
value={model.angle}
oninput={(event) => {
if (event.currentTarget.value !== "") setAngle(Number(event.currentTarget.value));
}}
/>
<span class="text-zinc-500 dark:text-zinc-400">°</span>
</label>
{/if}
<button
type="button"
class="grid shrink-0 place-items-center rounded-md transition size-7 text-zinc-500 hover:bg-zinc-100 hover:text-zinc-900 disabled:opacity-30 disabled:pointer-events-none dark:text-zinc-300 dark:hover:bg-zinc-700 dark:hover:text-white"
aria-label="Remove selected stop"
disabled={stops.length <= 2}
onclick={() => removeStop(selected)}
>
<TrashIcon class="size-4" />
</button>
{mode.label}
</button>
{/each}
</div>
{/if}
{#if model.kind !== "solid"}
<div class="flex gap-2 items-center pt-3" transition:slide={{ duration: 180 }}>
<div
class="flex-1 px-2.5 py-1.5 cursor-copy touch-none"
role="group"
aria-label="Gradient stops"
onpointerdown={addStop}
onpointermove={(event) => {
if (dragging !== null) moveStop(dragging, barPosition(event));
}}
onpointerup={() => (dragging = null)}
onpointercancel={() => (dragging = null)}
>
<div
bind:this={bar}
class="relative h-3 rounded-full ring-1 ring-inset ring-black/10 dark:ring-white/10"
style="background: linear-gradient(to right, {formatStops(stops)}), {CHECKERBOARD};"
>
{#each stops as stop, index (index)}
<button
type="button"
class="absolute top-1/2 handle cursor-grab active:cursor-grabbing {index ===
selected
? 'handle-selected'
: ''}"
style="left: {stop.position}%; --swatch: {formatColour(stop.colour)};"
aria-label="Colour stop at {Math.round(stop.position)}%"
aria-pressed={index === selected}
onpointerdown={(event) => startStopDrag(event, index)}
onkeydown={(event) => stopKeys(event, index)}
></button>
{/each}
</div>
</div>
{#if model.kind === "linear"}
<label
class="flex shrink-0 items-center px-2 w-14 h-7 text-xs rounded-md bg-zinc-100 dark:bg-zinc-700/70"
>
<input
type="number"
min="0"
max="360"
class="p-0 w-full min-w-0 text-xs text-right bg-transparent border-0 outline-none select-text picker-number"
aria-label="Gradient angle in degrees"
value={model.angle}
oninput={(event) => {
if (event.currentTarget.value !== "") setAngle(Number(event.currentTarget.value));
}}
/>
<span class="text-zinc-500 dark:text-zinc-400">°</span>
</label>
{/if}
<button
type="button"
class="grid shrink-0 place-items-center rounded-md transition size-7 text-zinc-500 hover:bg-zinc-100 hover:text-zinc-900 disabled:opacity-30 disabled:pointer-events-none dark:text-zinc-300 dark:hover:bg-zinc-700 dark:hover:text-white"
aria-label="Remove selected stop"
disabled={stops.length <= 2}
onclick={() => removeStop(selected)}
>
<TrashIcon class="size-4" />
</button>
</div>
{/if}
</div>
<div
@@ -368,7 +387,9 @@
min="0"
max="100"
class="picker-track"
style="background: linear-gradient(to right, transparent, {hex}), {CHECKERBOARD}; --swatch: {formatColour(active)};"
style="background: linear-gradient(to right, transparent, {hex}), {CHECKERBOARD}; --swatch: {formatColour(
active,
)};"
aria-label="Opacity"
value={Math.round(hsva.a * 100)}
oninput={(event) => updateHsva({ a: Number(event.currentTarget.value) / 100 })}
@@ -382,7 +403,9 @@
</div>
<div class="flex gap-2">
<label class="flex flex-1 gap-1.5 items-center px-2.5 min-w-0 h-8 text-xs rounded-md bg-zinc-100 dark:bg-zinc-700/70">
<label
class="flex flex-1 gap-1.5 items-center px-2.5 min-w-0 h-8 text-xs rounded-md bg-zinc-100 dark:bg-zinc-700/70"
>
<span class="text-zinc-500 dark:text-zinc-400">#</span>
<input
class="flex-1 p-0 min-w-0 font-mono text-xs uppercase bg-transparent border-0 outline-none select-text"
@@ -401,7 +424,9 @@
}}
/>
</label>
<label class="flex shrink-0 items-center px-2.5 w-16 h-8 text-xs rounded-md bg-zinc-100 dark:bg-zinc-700/70">
<label
class="flex shrink-0 items-center px-2.5 w-16 h-8 text-xs rounded-md bg-zinc-100 dark:bg-zinc-700/70"
>
<input
type="number"
min="0"
@@ -410,7 +435,8 @@
aria-label="Opacity percent"
value={Math.round(active.a * 100)}
oninput={(event) => {
if (event.currentTarget.value !== "") updateHsva({ a: clamp(Number(event.currentTarget.value), 0, 100) / 100 });
if (event.currentTarget.value !== "")
updateHsva({ a: clamp(Number(event.currentTarget.value), 0, 100) / 100 });
}}
/>
<span class="text-zinc-500 dark:text-zinc-400">%</span>
@@ -438,21 +464,30 @@
height: 1.125rem;
border-radius: 9999px;
border: 2px solid white;
background: linear-gradient(var(--swatch), var(--swatch)),
background:
linear-gradient(var(--swatch), var(--swatch)),
repeating-conic-gradient(#d4d4d8 0% 25%, #ffffff 0% 50%) 50% / 6px 6px;
box-shadow: 0 0 0 1px rgb(0 0 0 / 0.15), 0 1px 3px rgb(0 0 0 / 0.3);
box-shadow:
0 0 0 1px rgb(0 0 0 / 0.15),
0 1px 3px rgb(0 0 0 / 0.3);
transform: translate(-50%, -50%);
transition: transform 120ms ease, box-shadow 120ms ease;
transition:
transform 120ms ease,
box-shadow 120ms ease;
}
.handle-selected {
z-index: 1;
transform: translate(-50%, -50%) scale(1.2);
box-shadow: 0 0 0 2px rgb(24 24 27 / 0.85), 0 2px 6px rgb(0 0 0 / 0.35);
box-shadow:
0 0 0 2px rgb(24 24 27 / 0.85),
0 2px 6px rgb(0 0 0 / 0.35);
}
:global(.dark) .handle-selected {
box-shadow: 0 0 0 2px rgb(255 255 255 / 0.9), 0 2px 6px rgb(0 0 0 / 0.5);
box-shadow:
0 0 0 2px rgb(255 255 255 / 0.9),
0 2px 6px rgb(0 0 0 / 0.5);
}
.picker-number {
@@ -482,7 +517,9 @@
border: 2px solid white;
border-radius: 9999px;
background: var(--swatch);
box-shadow: 0 0 0 1px rgb(0 0 0 / 0.15), 0 1px 3px rgb(0 0 0 / 0.3);
box-shadow:
0 0 0 1px rgb(0 0 0 / 0.15),
0 1px 3px rgb(0 0 0 / 0.3);
}
.picker-track::-moz-range-thumb {
@@ -492,6 +529,8 @@
border: 2px solid white;
border-radius: 9999px;
background: var(--swatch);
box-shadow: 0 0 0 1px rgb(0 0 0 / 0.15), 0 1px 3px rgb(0 0 0 / 0.3);
box-shadow:
0 0 0 1px rgb(0 0 0 / 0.15),
0 1px 3px rgb(0 0 0 / 0.3);
}
</style>
@@ -6,7 +6,6 @@
let { communityState, searchTerm }: { communityState: CommunityThemesState; searchTerm: string } =
$props();
</script>
{#if communityState.browseLoading}
@@ -48,7 +47,8 @@
installedThemeColors={communityState.installedThemeColors}
variant="community"
onInstall={async (themeId) => {
if (communityState.displayTheme) await communityState.installCommunityTheme(themeId, communityState.displayTheme);
if (communityState.displayTheme)
await communityState.installCommunityTheme(themeId, communityState.displayTheme);
}}
onRemove={(id) => void communityState.removeInstalledTheme(id)}
onApply={(id) => void communityState.applyInstalledTheme(id)}
@@ -11,9 +11,9 @@
} from "@/seqta/utils/customThemes/client";
import ThemePlaceholderCover from "@/interface/components/themes/ThemePlaceholderCover.svelte";
import ThemeBlobImage from "@/interface/components/themes/ThemeBlobImage.svelte";
import type { CustomTheme } from "@/types/CustomThemes";
import type { CustomTheme } from "@/types/customThemes";
import { ThemeManager } from "@/plugins/built-in/themes/theme-manager";
import { themeUpdates } from "@/interface/hooks/ThemeUpdates";
import { themeUpdates } from "@/interface/hooks/themeUpdates";
import { isLocalCustomTheme } from "@/interface/utils/themeListFilters";
import { formatCustomThemeApiError } from "@/seqta/utils/customThemes/apiErrors";
@@ -90,7 +90,9 @@
Submit a custom theme you created or imported without opening the theme builder.
</p>
{#if localSubmitError}
<p class="mt-2 whitespace-pre-line text-sm text-red-600 dark:text-red-400">{localSubmitError}</p>
<p class="mt-2 whitespace-pre-line text-sm text-red-600 dark:text-red-400">
{localSubmitError}
</p>
{/if}
{#if localThemesLoading}
<div class="mt-3 grid grid-cols-1 gap-3">
@@ -121,9 +123,13 @@
/>
{/if}
<div class="min-w-0 flex-1">
<span class="font-semibold text-zinc-900 dark:text-white">{theme.name || "Untitled theme"}</span>
<span class="font-semibold text-zinc-900 dark:text-white"
>{theme.name || "Untitled theme"}</span
>
{#if theme.description}
<p class="mt-1 truncate text-sm text-zinc-500 dark:text-zinc-400">{theme.description}</p>
<p class="mt-1 truncate text-sm text-zinc-500 dark:text-zinc-400">
{theme.description}
</p>
{/if}
</div>
<div class="flex shrink-0 flex-wrap gap-2">
@@ -154,7 +160,8 @@
{#each statusFilters as status (status)}
<button
type="button"
class="rounded-full px-3 py-1 text-sm font-medium transition {communityState.statusFilter === status
class="rounded-full px-3 py-1 text-sm font-medium transition {communityState.statusFilter ===
status
? 'bg-zinc-900 text-white dark:bg-zinc-100 dark:text-zinc-900'
: 'bg-zinc-200 text-zinc-700 hover:bg-zinc-300 dark:bg-zinc-800 dark:text-zinc-300'}"
onclick={() => (communityState.statusFilter = status)}
@@ -196,7 +203,11 @@
onclick={() => void communityState.openDetail(theme)}
>
{#if theme.coverImage}
<img src={theme.coverImage} alt="" class="h-14 w-20 shrink-0 rounded-lg object-cover" />
<img
src={theme.coverImage}
alt=""
class="h-14 w-20 shrink-0 rounded-lg object-cover"
/>
{:else}
<ThemePlaceholderCover class="h-14 w-20 shrink-0 rounded-lg object-cover" />
{/if}
@@ -204,7 +215,9 @@
<div class="flex flex-wrap items-center gap-2">
<span class="font-semibold text-zinc-900 dark:text-white">{theme.name}</span>
<span
class="rounded-full px-2 py-0.5 text-xs font-semibold {statusBadgeClass(theme.status)}"
class="rounded-full px-2 py-0.5 text-xs font-semibold {statusBadgeClass(
theme.status,
)}"
>
{formatCustomThemeStatus(theme.status)}
</span>
@@ -26,7 +26,9 @@
<div>
<h2 class="text-2xl font-bold">{theme.name}</h2>
<span
class="mt-1 inline-flex rounded-full px-2 py-0.5 text-xs font-semibold {statusBadgeClass(theme.status)}"
class="mt-1 inline-flex rounded-full px-2 py-0.5 text-xs font-semibold {statusBadgeClass(
theme.status,
)}"
>
{formatCustomThemeStatus(theme.status)}
</span>
@@ -123,7 +125,8 @@
accept=".zip,application/zip"
class="block w-full text-sm"
onchange={(e) => {
communityState.replaceZipFile = (e.currentTarget as HTMLInputElement).files?.[0] ?? null;
communityState.replaceZipFile =
(e.currentTarget as HTMLInputElement).files?.[0] ?? null;
}}
/>
<button
@@ -14,7 +14,8 @@
<span class="mb-1 block text-sm font-medium">Status</span>
<Select
value={communityState.reviewStatusFilter}
onChange={(v) => (communityState.reviewStatusFilter = v as typeof communityState.reviewStatusFilter)}
onChange={(v) =>
(communityState.reviewStatusFilter = v as typeof communityState.reviewStatusFilter)}
options={[
{ value: "pending", label: "Pending" },
{ value: "approved", label: "Approved" },
@@ -73,7 +74,10 @@
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">
<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}
+180 -141
View File
@@ -1,16 +1,36 @@
<script lang="ts">
import DownloadIcon from "@lucide/svelte/icons/download";
import TrashIcon from "@lucide/svelte/icons/trash";
import { hasEnoughStorageSpace, isIndexedDBSupported, writeData, openDatabase, readAllData, deleteData } from '@/interface/hooks/BackgroundDataLoader';
import Spinner from '../Spinner.svelte';
import { settingsState } from '@/seqta/utils/listeners/SettingsState'
import { backgroundUpdates } from '@/interface/hooks/BackgroundUpdates'
import { ThemeManager } from '@/plugins/built-in/themes/theme-manager'
import {
hasEnoughStorageSpace,
isIndexedDBSupported,
writeData,
openDatabase,
readAllData,
deleteData,
} from "@/interface/hooks/backgroundDataLoader";
import Spinner from "../Spinner.svelte";
import { settingsState } from "@/seqta/utils/listeners/settingsState";
import { backgroundUpdates } from "@/interface/hooks/backgroundUpdates";
import { ThemeManager } from "@/plugins/built-in/themes/theme-manager";
const themeManager = ThemeManager.getInstance();
type Background = { id: string; category: string; type: string; lowResUrl: string; highResUrl: string; name: string; description: string; featured?: boolean };
let { searchTerm, selectedCategory, onCategoriesChange }: {
type Background = {
id: string;
category: string;
type: string;
lowResUrl: string;
highResUrl: string;
name: string;
description: string;
featured?: boolean;
};
let {
searchTerm,
selectedCategory,
onCategoriesChange,
}: {
searchTerm: string;
selectedCategory: string;
onCategoriesChange: (categories: string[]) => void;
@@ -22,14 +42,16 @@
let isLoading = $state<boolean>(true);
let savedBackgrounds = $state<string[]>([]);
let installingBackgrounds = $state<Set<string>>(new Set());
let debugInfo = $state<string>('');
let activeTab = $state<'all' | 'installed' | 'photos' | 'videos'>('all');
let sortBy = $state<'newest' | 'popular' | 'name'>('newest');
let debugInfo = $state<string>("");
let activeTab = $state<"all" | "installed" | "photos" | "videos">("all");
let sortBy = $state<"newest" | "popular" | "name">("newest");
const loadStore = async () => {
try {
debugInfo = 'Fetching backgrounds...';
const response = await fetch('https://raw.githubusercontent.com/BetterSEQTA/BetterSEQTA-Themes/main/store/backgrounds.json');
debugInfo = "Fetching backgrounds...";
const response = await fetch(
"https://raw.githubusercontent.com/BetterSEQTA/BetterSEQTA-Themes/main/store/backgrounds.json",
);
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
@@ -39,8 +61,8 @@
debugInfo = `Loaded ${backgrounds.length} backgrounds`;
await loadSavedBackgrounds();
} catch (e) {
error = 'Failed to load background store';
debugInfo = `Error: ${e instanceof Error ? e.message : 'Unknown error'}`;
error = "Failed to load background store";
debugInfo = `Error: ${e instanceof Error ? e.message : "Unknown error"}`;
} finally {
isLoading = false;
}
@@ -53,49 +75,51 @@
}
await openDatabase();
const data = await readAllData();
savedBackgrounds = data.map(item => item.id);
savedBackgrounds = data.map((item) => item.id);
} catch (e) {
error = e instanceof Error ? e.message : 'Unknown error occurred';
error = e instanceof Error ? e.message : "Unknown error occurred";
}
}
loadStore();
let filteredBackgrounds = $derived((() => {
let filtered = backgrounds;
if (searchTerm.trim()) {
const q = searchTerm.trim().toLowerCase();
filtered = backgrounds.filter((bg) =>
`${bg.name} ${bg.description}`.toLowerCase().includes(q),
);
}
let filteredBackgrounds = $derived(
(() => {
let filtered = backgrounds;
filtered = filtered.filter((bg: Background) => {
return selectedCategory === 'All'
? true
: selectedCategory === 'Featured'
? bg.featured
: bg.category === selectedCategory;
});
filtered.sort((a: Background, b: Background) => {
switch (sortBy) {
case 'name':
return a.name.localeCompare(b.name);
case 'newest':
return -1;
case 'popular':
return -1;
default:
return 0;
if (searchTerm.trim()) {
const q = searchTerm.trim().toLowerCase();
filtered = backgrounds.filter((bg) =>
`${bg.name} ${bg.description}`.toLowerCase().includes(q),
);
}
});
return filtered;
})());
filtered = filtered.filter((bg: Background) => {
return selectedCategory === "All"
? true
: selectedCategory === "Featured"
? bg.featured
: bg.category === selectedCategory;
});
let categories = $derived([...new Set(backgrounds.map(bg => bg.category))]);
filtered.sort((a: Background, b: Background) => {
switch (sortBy) {
case "name":
return a.name.localeCompare(b.name);
case "newest":
return -1;
case "popular":
return -1;
default:
return 0;
}
});
return filtered;
})(),
);
let categories = $derived([...new Set(backgrounds.map((bg) => bg.category))]);
async function saveBackgroundFromUrl(url: string, id: string, fileType: string): Promise<void> {
try {
if (!isIndexedDBSupported()) {
@@ -113,7 +137,7 @@
await writeData(id, fileType, blob);
savedBackgrounds = [...savedBackgrounds, id];
} catch (e) {
error = e instanceof Error ? e.message : 'Unknown error occurred';
error = e instanceof Error ? e.message : "Unknown error occurred";
}
}
@@ -121,13 +145,14 @@
installingBackgrounds = new Set(installingBackgrounds).add(fileId);
try {
await deleteData(fileId);
savedBackgrounds = savedBackgrounds.filter(id => id !== fileId);
savedBackgrounds = savedBackgrounds.filter((id) => id !== fileId);
if (selectedBackground === fileId) {
selectNoBackground();
}
} catch (e) {
error = e instanceof Error ? `Failed to delete background: ${e.message}` : 'Unknown error occurred';
error =
e instanceof Error ? `Failed to delete background: ${e.message}` : "Unknown error occurred";
} finally {
installingBackgrounds = new Set(installingBackgrounds);
installingBackgrounds.delete(fileId);
@@ -152,111 +177,125 @@
await installBackground(background);
}
}
function selectNoBackground() {
selectedBackground = null;
themeManager.setTheme('');
themeManager.setTheme("");
}
</script>
<div class="h-full overflow-auto">
<!-- Header -->
<div class="sticky top-0 z-10 p-4 border-b bg-[#F1F1F3] dark:bg-zinc-900 dark:border-zinc-700">
<div class="flex justify-between items-center mb-4">
<h1 class="text-2xl font-bold">Explore Backgrounds {searchTerm ? `- "${searchTerm}"` : ''}</h1>
<div class="flex gap-4 items-center">
<select
bind:value={sortBy}
class="p-2 rounded-lg border border-zinc-200 dark:border-zinc-700 dark:bg-zinc-800"
>
<option value="newest">Newest</option>
<option value="name">Name</option>
</select>
</div>
<!-- Header -->
<div class="sticky top-0 z-10 p-4 border-b bg-[#F1F1F3] dark:bg-zinc-900 dark:border-zinc-700">
<div class="flex justify-between items-center mb-4">
<h1 class="text-2xl font-bold">
Explore Backgrounds {searchTerm ? `- "${searchTerm}"` : ""}
</h1>
<div class="flex gap-4 items-center">
<select
bind:value={sortBy}
class="p-2 rounded-lg border border-zinc-200 dark:border-zinc-700 dark:bg-zinc-800"
>
<option value="newest">Newest</option>
<option value="name">Name</option>
</select>
</div>
</div>
<!-- Tabs -->
<div class="flex gap-2">
{#each ['All', 'Installed', 'Photos', 'Videos'] as tab}
<button
class={`px-4 py-2 text-sm font-medium transition-colors rounded-full
${activeTab === tab.toLowerCase() ? 'bg-zinc-100 dark:bg-zinc-800 hover:bg-zinc-200 dark:hover:bg-zinc-700' :
'bg-zinc-100 dark:bg-transparent dark:outline-solid dark:outline-zinc-700 hover:bg-zinc-200 dark:hover:bg-zinc-700/20'}`}
onclick={() => activeTab = tab.toLowerCase() as typeof activeTab}
>
{tab}
</button>
<!-- Tabs -->
<div class="flex gap-2">
{#each ["All", "Installed", "Photos", "Videos"] as tab}
<button
class={`px-4 py-2 text-sm font-medium transition-colors rounded-full
${
activeTab === tab.toLowerCase()
? "bg-zinc-100 dark:bg-zinc-800 hover:bg-zinc-200 dark:hover:bg-zinc-700"
: "bg-zinc-100 dark:bg-transparent dark:outline-solid dark:outline-zinc-700 hover:bg-zinc-200 dark:hover:bg-zinc-700/20"
}`}
onclick={() => (activeTab = tab.toLowerCase() as typeof activeTab)}
>
{tab}
</button>
{/each}
</div>
</div>
<!-- Background Grid -->
<div class="p-4">
{#if isLoading}
<div class="grid grid-cols-1 gap-6 sm:grid-cols-2 lg:grid-cols-3">
{#each Array(9) as _}
<div class="overflow-hidden relative rounded-lg animate-pulse">
<!-- Image placeholder -->
<div class="w-full h-48 bg-zinc-200 dark:bg-zinc-800"></div>
<!-- Gradient overlay -->
<div
class="absolute right-0 bottom-0 left-0 h-16 to-transparent bg-linear-to-t from-zinc-300 dark:from-zinc-700"
>
<!-- Title placeholder -->
<div class="absolute right-2 bottom-2 left-2">
<div class="w-2/3 h-4 rounded-full bg-zinc-200 dark:bg-zinc-800"></div>
<div class="mt-2 w-1/2 h-3 rounded-full bg-zinc-200 dark:bg-zinc-800"></div>
</div>
</div>
</div>
{/each}
</div>
</div>
<!-- Background Grid -->
<div class="p-4">
{#if isLoading}
<div class="grid grid-cols-1 gap-6 sm:grid-cols-2 lg:grid-cols-3">
{#each Array(9) as _}
<div class="overflow-hidden relative rounded-lg animate-pulse">
<!-- Image placeholder -->
<div class="w-full h-48 bg-zinc-200 dark:bg-zinc-800"></div>
<!-- Gradient overlay -->
<div class="absolute right-0 bottom-0 left-0 h-16 to-transparent bg-linear-to-t from-zinc-300 dark:from-zinc-700">
<!-- Title placeholder -->
<div class="absolute right-2 bottom-2 left-2">
<div class="w-2/3 h-4 rounded-full bg-zinc-200 dark:bg-zinc-800"></div>
<div class="mt-2 w-1/2 h-3 rounded-full bg-zinc-200 dark:bg-zinc-800"></div>
</div>
</div>
</div>
{/each}
</div>
{:else if error}
<div class="p-4 text-red-500 bg-red-100 rounded-lg">
Error: {error}
</div>
{:else}
<div class="grid grid-cols-1 gap-6 sm:grid-cols-2 lg:grid-cols-3">
{#each filteredBackgrounds.filter((bg: Background) => {
if (activeTab === 'installed') return savedBackgrounds.includes(bg.id);
if (activeTab === 'photos') return bg.type === 'image';
if (activeTab === 'videos') return bg.type !== 'image';
return true;
}) as background (background.id)}
{:else if error}
<div class="p-4 text-red-500 bg-red-100 rounded-lg">
Error: {error}
</div>
{:else}
<div class="grid grid-cols-1 gap-6 sm:grid-cols-2 lg:grid-cols-3">
{#each filteredBackgrounds.filter((bg: Background) => {
if (activeTab === "installed") return savedBackgrounds.includes(bg.id);
if (activeTab === "photos") return bg.type === "image";
if (activeTab === "videos") return bg.type !== "image";
return true;
}) as background (background.id)}
<div
class="overflow-hidden relative rounded-lg shadow-lg cursor-pointer group"
onclick={() => toggleBackgroundInstallation(background)}
onkeydown={(event) => {
if (event.key === "Enter" || event.key === " ") {
toggleBackgroundInstallation(background);
}
}}
role="button"
tabindex="0"
>
{#if background.type === "image"}
<img
src={background.lowResUrl}
alt={background.name}
class="object-cover w-full h-48 transition-all duration-300 group-hover:scale-105"
/>
{:else}
<video src={background.lowResUrl} class="object-cover w-full h-48" muted loop autoplay
></video>
{/if}
<div
class="overflow-hidden relative rounded-lg shadow-lg cursor-pointer group"
onclick={() => toggleBackgroundInstallation(background)}
onkeydown={(event) => {
if (event.key === 'Enter' || event.key === ' ') {
toggleBackgroundInstallation(background);
}
}}
role="button"
tabindex="0"
class={`flex absolute inset-0 justify-center items-center opacity-0 transition-opacity duration-300 bg-black/50 group-hover:opacity-100 ${installingBackgrounds.has(background.id) ? "opacity-100" : ""}`}
>
{#if background.type === 'image'}
<img src={background.lowResUrl} alt={background.name} class="object-cover w-full h-48 transition-all duration-300 group-hover:scale-105" />
{#if installingBackgrounds.has(background.id)}
<Spinner />
{:else if savedBackgrounds.includes(background.id)}
<span class="flex items-center text-white">
<TrashIcon size="1em" class="mr-2 text-2xl" />
<span class="text-sm font-semibold">Remove</span>
</span>
{:else}
<video src={background.lowResUrl} class="object-cover w-full h-48" muted loop autoplay></video>
<span class="flex items-center text-white">
<DownloadIcon size="1em" class="mr-2 text-2xl" />
<span class="text-sm font-semibold">Install</span>
</span>
{/if}
<div class={`flex absolute inset-0 justify-center items-center opacity-0 transition-opacity duration-300 bg-black/50 group-hover:opacity-100 ${installingBackgrounds.has(background.id) ? 'opacity-100' : ''}`}>
{#if installingBackgrounds.has(background.id)}
<Spinner />
{:else if savedBackgrounds.includes(background.id)}
<span class="flex items-center text-white">
<TrashIcon size="1em" class="mr-2 text-2xl" />
<span class="text-sm font-semibold">Remove</span>
</span>
{:else}
<span class="flex items-center text-white">
<DownloadIcon size="1em" class="mr-2 text-2xl" />
<span class="text-sm font-semibold">Install</span>
</span>
{/if}
</div>
</div>
{/each}
</div>
{/if}
</div>
</div>
{/each}
</div>
{/if}
</div>
</div>
{#if settingsState.devMode}
@@ -264,7 +303,7 @@
<h3 class="mb-2 font-bold">Debug Info:</h3>
<p>{debugInfo}</p>
<p>Total backgrounds: {backgrounds.length}</p>
<p>Categories: {categories.join(', ') || '<empty>'}</p>
<p>Categories: {categories.join(", ") || "<empty>"}</p>
<p>Active Tab: {activeTab}</p>
<p>Selected Category: {selectedCategory}</p>
</div>
@@ -1,11 +1,15 @@
<script lang="ts">
import CircleUserRoundIcon from "@lucide/svelte/icons/circle-user-round";
import { onMount } from "svelte";
import { cloudAuth } from "@/seqta/utils/CloudAuth";
import { cloudAuth } from "@/seqta/utils/cloudAuth";
import CloudPfpAvatar from "@/interface/components/CloudPfpAvatar.svelte";
import { settingsState } from "@/seqta/utils/listeners/SettingsState";
import { settingsState } from "@/seqta/utils/listeners/settingsState";
let { alwaysShowUserName = false, onClick = undefined, compact = false }: {
let {
alwaysShowUserName = false,
onClick = undefined,
compact = false,
}: {
alwaysShowUserName?: boolean;
onClick?: () => void;
compact?: boolean;
@@ -73,7 +77,9 @@
<button
type="button"
onclick={handleButtonClick}
class="flex items-center gap-2 bg-zinc-100/80 font-medium text-zinc-700 transition-colors duration-150 hover:bg-zinc-200 hover:text-zinc-950 dark:bg-zinc-900/50 dark:text-zinc-200 dark:hover:bg-zinc-700 dark:hover:text-white {compact ? 'h-8 rounded-lg px-3 text-[0.75rem]' : 'h-12 rounded-full px-4 text-sm'}"
class="flex items-center gap-2 bg-zinc-100/80 font-medium text-zinc-700 transition-colors duration-150 hover:bg-zinc-200 hover:text-zinc-950 dark:bg-zinc-900/50 dark:text-zinc-200 dark:hover:bg-zinc-700 dark:hover:text-white {compact
? 'h-8 rounded-lg px-3 text-[0.75rem]'
: 'h-12 rounded-full px-4 text-sm'}"
>
{#if cloudState.isLoggedIn}
{#if cloudState.user?.pfpUrl}
@@ -83,7 +89,9 @@
/>
{/if}
{#if !cloudState.user?.pfpUrl}
<div class="flex items-center justify-center w-5 h-5 rounded-full bg-zinc-300 dark:bg-zinc-600 text-zinc-700 dark:text-zinc-200 font-semibold text-[0.6rem]">
<div
class="flex items-center justify-center w-5 h-5 rounded-full bg-zinc-300 dark:bg-zinc-600 text-zinc-700 dark:text-zinc-200 font-semibold text-[0.6rem]"
>
{getInitials()}
</div>
{/if}
@@ -92,7 +100,10 @@
? "inline max-w-40 truncate"
: "hidden max-w-24 truncate sm:inline"}
>
{cloudState.user?.displayName || cloudState.user?.username || cloudState.user?.email || "User"}
{cloudState.user?.displayName ||
cloudState.user?.username ||
cloudState.user?.email ||
"User"}
</span>
{:else}
<CircleUserRoundIcon size="1em" class="text-sm" />
@@ -123,16 +134,23 @@
/>
{/if}
{#if !cloudState.user?.pfpUrl}
<div class="flex items-center justify-center w-12 h-12 rounded-full bg-zinc-300 dark:bg-zinc-600 text-zinc-700 dark:text-zinc-200 font-semibold text-base">
<div
class="flex items-center justify-center w-12 h-12 rounded-full bg-zinc-300 dark:bg-zinc-600 text-zinc-700 dark:text-zinc-200 font-semibold text-base"
>
{getInitials()}
</div>
{/if}
<div class="min-w-0 flex-1">
<p class="text-base font-medium text-zinc-900 dark:text-white truncate">
{cloudState.user?.displayName || cloudState.user?.username || cloudState.user?.email || "User"}
{cloudState.user?.displayName ||
cloudState.user?.username ||
cloudState.user?.email ||
"User"}
</p>
{#if cloudState.user?.email && cloudState.user?.email !== (cloudState.user?.displayName || cloudState.user?.username)}
<p class="text-base text-zinc-500 dark:text-zinc-400 truncate">{cloudState.user.email}</p>
<p class="text-base text-zinc-500 dark:text-zinc-400 truncate">
{cloudState.user.email}
</p>
{/if}
</div>
</div>
@@ -2,14 +2,17 @@
import ChevronLeftIcon from "@lucide/svelte/icons/chevron-left";
import ChevronRightIcon from "@lucide/svelte/icons/chevron-right";
import StarIcon from "@lucide/svelte/icons/star";
import { fade } from 'svelte/transition';
import type { ThemeCoverSlide } from '@/interface/types/Theme';
import emblaCarouselSvelte from 'embla-carousel-svelte';
import Autoplay from 'embla-carousel-autoplay';
import { fade } from "svelte/transition";
import type { ThemeCoverSlide } from "@/interface/types/theme";
import emblaCarouselSvelte from "embla-carousel-svelte";
import Autoplay from "embla-carousel-autoplay";
let { slides, setDisplayTheme }: {
let {
slides,
setDisplayTheme,
}: {
slides: ThemeCoverSlide[];
setDisplayTheme: (theme: import('@/interface/types/Theme').Theme) => void;
setDisplayTheme: (theme: import("@/interface/types/theme").Theme) => void;
} = $props();
let emblaApi = $state();
@@ -37,24 +40,31 @@
</script>
{#if slides.length > 0}
<div class="relative w-full overflow-clip rounded-xl ring-1 ring-black/10 transition-opacity dark:ring-white/10" transition:fade>
<div
class="relative w-full overflow-clip rounded-xl ring-1 ring-black/10 transition-opacity dark:ring-white/10"
transition:fade
>
<div
class="w-full overflow-hidden"
use:emblaCarouselSvelte={{ options, plugins }}
onemblaInit={onInit}
>
<div class="flex">
{#each slides as slide (slide.imageUrl + slide.title + (slide.subtitle ?? ''))}
{#each slides as slide (slide.imageUrl + slide.title + (slide.subtitle ?? ""))}
<div
class="cover-slide relative isolate min-w-0 flex-[0_0_100%] cursor-pointer overflow-hidden"
role="button"
tabindex="0"
onkeydown={(e) => {
if (e.key === 'Enter') setDisplayTheme(slide.openTheme);
if (e.key === "Enter") setDisplayTheme(slide.openTheme);
}}
onclick={() => setDisplayTheme(slide.openTheme)}
>
<img src={slide.imageUrl} alt="" class="absolute inset-0 z-0 h-full w-full object-cover" />
<img
src={slide.imageUrl}
alt=""
class="absolute inset-0 z-0 h-full w-full object-cover"
/>
{#if slide.badgeFeatured === true}
<div class="absolute top-4 left-4 z-2 pointer-events-none">
<span
@@ -72,7 +82,9 @@
<p class="text-lg font-medium text-white/95 mt-1 line-clamp-2">{slide.subtitle}</p>
{/if}
{#if slide.openTheme.author && !slide.subtitle}
<p class="text-sm text-white/90 mt-1 mb-1 line-clamp-1">By {slide.openTheme.author}</p>
<p class="text-sm text-white/90 mt-1 mb-1 line-clamp-1">
By {slide.openTheme.author}
</p>
{/if}
{#if slide.openTheme.description && !slide.subtitle}
<p class="text-lg text-white line-clamp-3">{slide.openTheme.description}</p>
@@ -122,7 +134,7 @@
rgb(0 0 0 / 8%) 72%,
transparent 88%
);
content: '';
content: "";
pointer-events: none;
}
</style>
+11 -4
View File
@@ -7,7 +7,7 @@
import MotionDiv from "../MotionDiv.svelte";
import PlainCloseButton from "../PlainCloseButton.svelte";
import CloudHeader from "./CloudHeader.svelte";
import { settingsState } from "@/seqta/utils/listeners/SettingsState";
import { settingsState } from "@/seqta/utils/listeners/settingsState";
type SettingsPage = "settings" | "themes" | "backgrounds";
@@ -95,7 +95,9 @@
>
<label class="relative block w-40 md:w-48 xl:w-56">
<span class="sr-only">Search {activePage}</span>
<SearchIcon class="pointer-events-none absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-zinc-400" />
<SearchIcon
class="pointer-events-none absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-zinc-400"
/>
<input
type="search"
placeholder={activePage === "themes" ? "Search themes" : "Search backgrounds"}
@@ -112,9 +114,14 @@
{/if}
{#if onToggleSize}
<button type="button" onclick={onToggleSize}
<button
type="button"
onclick={onToggleSize}
class="flex h-10 w-10 shrink-0 items-center justify-center text-zinc-500 transition-[color,transform] duration-150 hover:text-zinc-950 active:scale-[0.96] dark:text-zinc-400 dark:hover:text-white"
aria-label="Collapse settings" title="Collapse settings" aria-expanded="true">
aria-label="Collapse settings"
title="Collapse settings"
aria-expanded="true"
>
<Minimize2Icon size="1em" class="text-2xl" />
</button>
{/if}
+61 -36
View File
@@ -3,15 +3,24 @@
import DownloadIcon from "@lucide/svelte/icons/download";
import HeartIcon from "@lucide/svelte/icons/heart";
import StarIcon from "@lucide/svelte/icons/star";
import type { Theme } from '@/interface/types/Theme'
import type { Theme } from "@/interface/types/theme";
import {
masterGridDisplayDownloadCount,
gridCardPreviewImageUrls,
} from '@/interface/utils/themeStoreFlavours'
import { isStoreThemeInstalled } from '@/interface/utils/themeListFilters'
import emblaCarouselSvelte from 'embla-carousel-svelte';
import Autoplay from 'embla-carousel-autoplay';
let { theme, onClick, toggleFavorite, isLoggedIn, onRequestSignIn, allStoreThemeRows, installedThemeIds = [], variant = 'official' }: {
} from "@/interface/utils/themeStoreFlavours";
import { isStoreThemeInstalled } from "@/interface/utils/themeListFilters";
import emblaCarouselSvelte from "embla-carousel-svelte";
import Autoplay from "embla-carousel-autoplay";
let {
theme,
onClick,
toggleFavorite,
isLoggedIn,
onRequestSignIn,
allStoreThemeRows,
installedThemeIds = [],
variant = "official",
}: {
theme: Theme;
onClick: () => void;
toggleFavorite: (theme: Theme) => void;
@@ -20,7 +29,7 @@
/** Raw API themes (includes hidden slaves) for aggregated master download totals */
allStoreThemeRows?: Theme[];
installedThemeIds?: string[];
variant?: 'official' | 'community';
variant?: "official" | "community";
} = $props();
const displayDownloadCount = $derived(
@@ -33,13 +42,15 @@
/** Mirrors CoverSwiper (featured bar): horizontal slides + autoplay */
function prefersReducedMotion(): boolean {
return typeof window !== 'undefined' && window.matchMedia('(prefers-reduced-motion: reduce)').matches;
return (
typeof window !== "undefined" && window.matchMedia("(prefers-reduced-motion: reduce)").matches
);
}
/** Read once synchronously where `window` exists so reduced-motion doesn’t briefly mount carousel */
let allowSlideAutoplay = $state(!prefersReducedMotion());
const gridEmblaKey = $derived(gridRotatorUrls.join('|'));
const gridEmblaKey = $derived(gridRotatorUrls.join("|"));
const gridEmblaOptions = $derived({ loop: gridRotatorUrls.length > 1 });
@@ -55,11 +66,11 @@
});
const isInstalled = $derived(isStoreThemeInstalled(theme, installedThemeIds));
const isCommunity = $derived(variant === 'community');
const isCommunity = $derived(variant === "community");
const showFavorites = $derived(!isCommunity);
function handleCardClick(e: MouseEvent) {
if ((e.target as HTMLElement).closest('[data-theme-favorite]')) return;
if ((e.target as HTMLElement).closest("[data-theme-favorite]")) return;
onClick();
}
@@ -105,7 +116,15 @@
</div>
{/if}
{#if isInstalled}
<div class="absolute top-2 z-20 pointer-events-none {theme.featured === true ? (isCommunity ? 'left-44' : 'left-22') : isCommunity ? 'left-23' : 'left-2'}">
<div
class="absolute top-2 z-20 pointer-events-none {theme.featured === true
? isCommunity
? 'left-44'
: 'left-22'
: isCommunity
? 'left-23'
: 'left-2'}"
>
<span
class="inline-flex items-center gap-1 px-2 py-0.5 rounded-full text-xs font-semibold bg-emerald-100 text-emerald-900 dark:bg-emerald-950 dark:text-emerald-100 shadow-xs"
aria-label="Installed"
@@ -116,24 +135,27 @@
</div>
{/if}
{#if showFavorites}
<button
type="button"
data-theme-favorite
class="pointer-events-none absolute right-2 top-2 z-20 flex h-10 w-10 scale-[0.25] items-center justify-center rounded-full bg-black/50 text-white opacity-0 blur-xs transition-[opacity,transform,filter,background-color] duration-200 ease-[cubic-bezier(0.2,0,0,1)] hover:bg-black/70 active:scale-[0.96] group-hover:pointer-events-auto group-hover:scale-100 group-hover:opacity-100 group-hover:blur-0 focus-visible:pointer-events-auto focus-visible:scale-100 focus-visible:opacity-100 focus-visible:blur-0"
onclick={handleFavoriteClick}
aria-label={isLoggedIn
? theme.is_favorited
? 'Remove from favourites'
: 'Add to favourites'
: 'Sign in to favourite themes'}
title={isLoggedIn
? theme.is_favorited
? 'Remove from favourites'
: 'Add to favourites'
: 'Sign in to favourite themes'}
>
<HeartIcon class="h-5 w-5 {theme.is_favorited ? 'text-red-500' : ''}" fill={theme.is_favorited ? 'currentColor' : 'none'} />
</button>
<button
type="button"
data-theme-favorite
class="pointer-events-none absolute right-2 top-2 z-20 flex h-10 w-10 scale-[0.25] items-center justify-center rounded-full bg-black/50 text-white opacity-0 blur-xs transition-[opacity,transform,filter,background-color] duration-200 ease-[cubic-bezier(0.2,0,0,1)] hover:bg-black/70 active:scale-[0.96] group-hover:pointer-events-auto group-hover:scale-100 group-hover:opacity-100 group-hover:blur-0 focus-visible:pointer-events-auto focus-visible:scale-100 focus-visible:opacity-100 focus-visible:blur-0"
onclick={handleFavoriteClick}
aria-label={isLoggedIn
? theme.is_favorited
? "Remove from favourites"
: "Add to favourites"
: "Sign in to favourite themes"}
title={isLoggedIn
? theme.is_favorited
? "Remove from favourites"
: "Add to favourites"
: "Sign in to favourite themes"}
>
<HeartIcon
class="h-5 w-5 {theme.is_favorited ? 'text-red-500' : ''}"
fill={theme.is_favorited ? "currentColor" : "none"}
/>
</button>
{/if}
<div class="absolute bottom-1 left-3 right-3 z-10 mb-1 flex flex-col gap-0.5">
<span class="text-xl font-bold text-white drop-shadow-md">{theme.name}</span>
@@ -146,15 +168,18 @@
{displayDownloadCount.toLocaleString()}
</span>
{#if showFavorites}
<span class="flex items-center gap-1">
<HeartIcon class="w-3.5 h-3.5" fill={theme.is_favorited ? 'currentColor' : 'none'} />
{(theme.favorite_count ?? 0).toLocaleString()}
</span>
<span class="flex items-center gap-1">
<HeartIcon class="w-3.5 h-3.5" fill={theme.is_favorited ? "currentColor" : "none"} />
{(theme.favorite_count ?? 0).toLocaleString()}
</span>
{/if}
</div>
</div>
{#if gridRotatorUrls.length === 0}
<div class="relative w-full h-48 overflow-hidden rounded-md bg-zinc-200 dark:bg-zinc-700" aria-hidden="true"></div>
<div
class="relative w-full h-48 overflow-hidden rounded-md bg-zinc-200 dark:bg-zinc-700"
aria-hidden="true"
></div>
{:else if !allowSlideAutoplay || gridRotatorUrls.length === 1}
<div class="relative w-full h-48 overflow-hidden rounded-md">
<img
@@ -205,7 +230,7 @@
rgb(0 0 0 / 16%) 72%,
transparent 88%
);
content: '';
content: "";
pointer-events: none;
}
</style>
+17 -13
View File
@@ -1,6 +1,6 @@
<script lang="ts">
import type { Theme } from '@/interface/types/Theme'
import ThemeCard from './ThemeCard.svelte';
import type { Theme } from "@/interface/types/theme";
import ThemeCard from "./ThemeCard.svelte";
let {
themes,
@@ -11,7 +11,7 @@
onRequestSignIn,
allStoreThemeRows,
installedThemeIds = [],
variant = 'official',
variant = "official",
}: {
themes: Theme[];
searchTerm: string;
@@ -22,17 +22,19 @@
/** Raw API list (includes `slave` rows) for master download aggregation */
allStoreThemeRows?: Theme[];
installedThemeIds?: string[];
variant?: 'official' | 'community';
variant?: "official" | "community";
} = $props();
let filteredThemes = $derived(themes.filter((theme: Theme) => {
const q = searchTerm.toLowerCase();
const name = (theme.name ?? '').toLowerCase();
const description = (theme.description ?? '').toLowerCase();
return name.includes(q) || description.includes(q);
}));
const isCommunity = $derived(variant === 'community');
let filteredThemes = $derived(
themes.filter((theme: Theme) => {
const q = searchTerm.toLowerCase();
const name = (theme.name ?? "").toLowerCase();
const description = (theme.description ?? "").toLowerCase();
return name.includes(q) || description.includes(q);
}),
);
const isCommunity = $derived(variant === "community");
</script>
<div class="relative">
@@ -64,7 +66,9 @@
</div>
{:else}
<div class="absolute top-0 flex h-96 w-full flex-col items-center justify-center text-center">
<h1 class="mt-4 text-3xl font-bold tracking-tight text-zinc-900 dark:text-zinc-100 sm:text-5xl">
<h1
class="mt-4 text-3xl font-bold tracking-tight text-zinc-900 dark:text-zinc-100 sm:text-5xl"
>
That doesn't exist! 😭😭😭
</h1>
<p class="mt-6 text-lg leading-7 text-zinc-600 dark:text-zinc-300">
File diff suppressed because it is too large. Load diff
@@ -1,3 +1,3 @@
<script lang="ts"></script>
<div class='w-full h-0.5 my-4 bg-zinc-200 dark:bg-zinc-700'></div>
<div class="w-full h-0.5 my-4 bg-zinc-200 dark:bg-zinc-700"></div>
@@ -6,33 +6,56 @@
url?: string | undefined;
}
let { bg, isSelected, isEditMode, onClick, onDelete }: { bg: Background, isSelected: boolean, isEditMode: boolean, onClick: () => void, onDelete: () => void } = $props();
let {
bg,
isSelected,
isEditMode,
onClick,
onDelete,
}: {
bg: Background;
isSelected: boolean;
isEditMode: boolean;
onClick: () => void;
onDelete: () => void;
} = $props();
</script>
<div
onclick={onClick}
onkeydown={(e) => { if (e.key === 'Enter' || e.key === ' ') onClick() }}
onkeydown={(e) => {
if (e.key === "Enter" || e.key === " ") onClick();
}}
tabindex="0"
role="button"
class="relative w-16 h-16 cursor-pointer rounded-xl transition ring-3 dark:ring-zinc-500/50 ring-zinc-300 {isEditMode ? 'animate-shake' : ''} {isSelected ? 'dark:ring-4 ring-4' : 'ring-0'}"
class="relative w-16 h-16 cursor-pointer rounded-xl transition ring-3 dark:ring-zinc-500/50 ring-zinc-300 {isEditMode
? 'animate-shake'
: ''} {isSelected ? 'dark:ring-4 ring-4' : 'ring-0'}"
>
{#if isEditMode}
<div
tabindex="0"
role="button"
class="absolute top-0 right-0 z-10 flex w-6 h-6 p-2 text-white translate-x-1/2 -translate-y-1/2 bg-red-600 rounded-full place-items-center"
onclick={(e) => { e.stopPropagation(); onDelete() }}
onkeydown={(e) => { if (e.key === 'Enter' || e.key === ' ') { e.stopPropagation(); onDelete() } }}
onclick={(e) => {
e.stopPropagation();
onDelete();
}}
onkeydown={(e) => {
if (e.key === "Enter" || e.key === " ") {
e.stopPropagation();
onDelete();
}
}}
>
<div class="w-4 h-0.5 bg-white"></div>
</div>
{/if}
{#if bg.url}
{#if bg.type === 'image'}
{#if bg.type === "image"}
<img class="object-cover w-full h-full rounded-xl" src={bg.url} alt="swatch" />
{:else if bg.type === 'video'}
{:else if bg.type === "video"}
<video muted loop autoplay src={bg.url} class="object-cover w-full h-full rounded-xl"></video>
{/if}
{/if}
</div>
</div>
@@ -1,24 +1,38 @@
<script lang="ts">
import { hasEnoughStorageSpace, isIndexedDBSupported, writeData, readAllData, deleteData } from '@/interface/hooks/BackgroundDataLoader'
import BackgroundUploader from './BackgroundUploader.svelte';
import BackgroundItem from './BackgroundItem.svelte'
import { onMount, onDestroy } from 'svelte'
import { loadBackground } from '@/seqta/ui/ImageBackgrounds'
import { backgroundUpdates } from '@/interface/hooks/BackgroundUpdates'
import {
hasEnoughStorageSpace,
isIndexedDBSupported,
writeData,
readAllData,
deleteData,
} from "@/interface/hooks/backgroundDataLoader";
import BackgroundUploader from "./BackgroundUploader.svelte";
import BackgroundItem from "./BackgroundItem.svelte";
import { onMount, onDestroy } from "svelte";
import { loadBackground } from "@/seqta/ui/imageBackgrounds";
import { backgroundUpdates } from "@/interface/hooks/backgroundUpdates";
let { isEditMode, selectNoBackground = $bindable(), selectedBackground = $bindable() }: { isEditMode: boolean, selectNoBackground: () => void, selectedBackground: string | null } = $props();
let {
isEditMode,
selectNoBackground = $bindable(),
selectedBackground = $bindable(),
}: {
isEditMode: boolean;
selectNoBackground: () => void;
selectedBackground: string | null;
} = $props();
let backgrounds = $state<{ id: string; type: string; blob: Blob | null; url?: string }[]>([]);
let feedback = $state<{ kind: 'error' | 'warn'; text: string } | null>(null);
let feedback = $state<{ kind: "error" | "warn"; text: string } | null>(null);
let imageBackgrounds = $derived(backgrounds.filter(bg => bg.type === 'image'));
let videoBackgrounds = $derived(backgrounds.filter(bg => bg.type === 'video'));
let imageBackgrounds = $derived(backgrounds.filter((bg) => bg.type === "image"));
let videoBackgrounds = $derived(backgrounds.filter((bg) => bg.type === "video"));
function inferBackgroundType(file: File): 'image' | 'video' {
function inferBackgroundType(file: File): "image" | "video" {
const mime = file.type.toLowerCase();
if (mime.startsWith('video/')) return 'video';
if (mime.startsWith('image/')) return 'image';
const ext = file.name.split('.').pop()?.toLowerCase() ?? '';
return ['mp4', 'mov', 'webm', 'm4v', 'mkv'].includes(ext) ? 'video' : 'image';
if (mime.startsWith("video/")) return "video";
if (mime.startsWith("image/")) return "image";
const ext = file.name.split(".").pop()?.toLowerCase() ?? "";
return ["mp4", "mov", "webm", "m4v", "mkv"].includes(ext) ? "video" : "image";
}
async function handleFileChange(file: File): Promise<void> {
@@ -35,9 +49,13 @@
throw new Error("Not enough storage space to save this background.");
}
const fileId = `${Date.now()}-${file.name.replace(/[^\w.-]+/g, '_')}`;
const fileId = `${Date.now()}-${file.name.replace(/[^\w.-]+/g, "_")}`;
const fileType = inferBackgroundType(file);
const blob = file.slice(0, file.size, file.type || (fileType === 'video' ? 'video/mp4' : 'image/jpeg'));
const blob = file.slice(
0,
file.size,
file.type || (fileType === "video" ? "video/mp4" : "image/jpeg"),
);
await writeData(fileId, fileType, blob);
backgrounds = [
@@ -46,17 +64,17 @@
];
backgroundUpdates.triggerUpdate();
const ext = file.name.split('.').pop()?.toLowerCase() ?? '';
if (['heic', 'heif'].includes(ext) || file.type.toLowerCase().includes('hei')) {
const ext = file.name.split(".").pop()?.toLowerCase() ?? "";
if (["heic", "heif"].includes(ext) || file.type.toLowerCase().includes("hei")) {
feedback = {
kind: 'warn',
text: 'HEIC saved, but Chrome and Edge often cannot preview it. Export as JPEG or PNG if the thumbnail stays blank.',
kind: "warn",
text: "HEIC saved, but Chrome and Edge often cannot preview it. Export as JPEG or PNG if the thumbnail stays blank.",
};
}
} catch (e) {
feedback = {
kind: 'error',
text: e instanceof Error ? e.message : 'An unknown error occurred',
kind: "error",
text: e instanceof Error ? e.message : "An unknown error occurred",
};
}
}
@@ -69,27 +87,27 @@
throw new Error("Your browser doesn't support IndexedDB. Unable to load backgrounds.");
}
selectedBackground = localStorage.getItem('selectedBackground');
selectedBackground = localStorage.getItem("selectedBackground");
const dbData = await readAllData();
backgrounds.forEach(bg => {
backgrounds.forEach((bg) => {
if (bg.url) URL.revokeObjectURL(bg.url);
});
backgrounds = dbData.map(bg => ({
backgrounds = dbData.map((bg) => ({
id: bg.id,
type: bg.type,
blob: bg.blob,
url: URL.createObjectURL(bg.blob)
url: URL.createObjectURL(bg.blob),
}));
if (selectedBackground && !backgrounds.some(bg => bg.id === selectedBackground)) {
if (selectedBackground && !backgrounds.some((bg) => bg.id === selectedBackground)) {
selectNoBackground();
}
} catch (e) {
feedback = {
kind: 'error',
text: e instanceof Error ? e.message : 'An unknown error occurred',
kind: "error",
text: e instanceof Error ? e.message : "An unknown error occurred",
};
}
}
@@ -101,13 +119,13 @@
}
selectedBackground = fileId;
localStorage.setItem('selectedBackground', fileId);
localStorage.setItem("selectedBackground", fileId);
}
async function deleteBackground(fileId: string): Promise<void> {
try {
await deleteData(fileId);
backgrounds = backgrounds.filter(bg => bg.id !== fileId);
backgrounds = backgrounds.filter((bg) => bg.id !== fileId);
if (selectedBackground === fileId) {
selectNoBackground();
@@ -115,16 +133,16 @@
backgroundUpdates.triggerUpdate();
} catch (e) {
feedback = {
kind: 'error',
text: e instanceof Error ? e.message : 'An unknown error occurred',
kind: "error",
text: e instanceof Error ? e.message : "An unknown error occurred",
};
}
}
selectNoBackground = () => {
selectedBackground = null;
localStorage.setItem('selectedBackground', '');
}
localStorage.setItem("selectedBackground", "");
};
$effect(() => {
loadBackground();
@@ -147,13 +165,19 @@
});
</script>
<div class="relative px-1 { !( isEditMode && imageBackgrounds.length === 0 && videoBackgrounds.length === 0 ) && 'pt-2' }">
<div
class="relative px-1 {!(
isEditMode &&
imageBackgrounds.length === 0 &&
videoBackgrounds.length === 0
) && 'pt-2'}"
>
{#if feedback}
<div
class="mx-1 mb-3 rounded-lg border px-3 py-2 text-sm {feedback.kind === 'warn'
? 'border-amber-300/60 bg-amber-50 text-amber-900 dark:border-amber-900/50 dark:bg-amber-950/40 dark:text-amber-100'
: 'border-red-300/60 bg-red-50 text-red-800 dark:border-red-900/50 dark:bg-red-950/40 dark:text-red-200'}"
role={feedback.kind === 'warn' ? 'status' : 'alert'}
role={feedback.kind === "warn" ? "status" : "alert"}
>
{feedback.text}
</div>
@@ -168,11 +192,12 @@
{#each imageBackgrounds as bg (bg.id)}
{#if bg.url}
<BackgroundItem
bg={bg}
{bg}
isSelected={selectedBackground === bg.id}
isEditMode={isEditMode}
{isEditMode}
onClick={() => selectBackground(bg.id)}
onDelete={() => deleteBackground(bg.id)}/>
onDelete={() => deleteBackground(bg.id)}
/>
{:else}
<div class="w-16 h-16 rounded-xl bg-zinc-100 dark:bg-zinc-900 animate-pulse"></div>
{/if}
@@ -189,9 +214,9 @@
{#each videoBackgrounds as bg (bg.id)}
{#if bg.url}
<BackgroundItem
bg={bg}
{bg}
isSelected={selectedBackground === bg.id}
isEditMode={isEditMode}
{isEditMode}
onClick={() => selectBackground(bg.id)}
onDelete={() => deleteBackground(bg.id)}
/>
@@ -17,7 +17,7 @@
<div
class="flex items-center justify-center w-full h-full text-3xl font-bold text-gray-400 transition hover:text-gray-500 pointer-events-none"
>
<PlusIcon size="1em" />
<PlusIcon size="1em" />
</div>
<input
type="file"
@@ -1,32 +1,36 @@
<script lang="ts">
import { blobToDataUrl } from '@/seqta/utils/base64'
import { blobToDataUrl } from "@/seqta/utils/base64";
let { source, alt = '', class: className = '' }: {
source: string | Blob | null | undefined
alt?: string
class?: string
} = $props()
let {
source,
alt = "",
class: className = "",
}: {
source: string | Blob | null | undefined;
alt?: string;
class?: string;
} = $props();
let src = $state('')
let src = $state("");
$effect(() => {
const value = source
const value = source;
if (!value) {
src = ''
return
src = "";
return;
}
if (typeof value === 'string') {
src = value
return
if (typeof value === "string") {
src = value;
return;
}
let cancelled = false
let cancelled = false;
void blobToDataUrl(value).then((url) => {
if (!cancelled) src = url
})
if (!cancelled) src = url;
});
return () => {
cancelled = true
}
})
cancelled = true;
};
});
</script>
{#if src}
@@ -12,4 +12,4 @@
const src = $derived(defaultThemeCoverDataUrl(accentHint));
</script>
<img src={src} alt="" class={className} draggable="false" />
<img {src} alt="" class={className} draggable="false" />
@@ -5,22 +5,25 @@
import PlusIcon from "@lucide/svelte/icons/plus";
import ShoppingCartIcon from "@lucide/svelte/icons/shopping-cart";
import UploadIcon from "@lucide/svelte/icons/upload";
import type { CustomTheme, ThemeList } from '@/types/CustomThemes'
import { onDestroy, onMount } from 'svelte'
import browser from '@/lib/browser'
import { themeUpdates } from '@/interface/hooks/ThemeUpdates'
import { ThemeManager } from '@/plugins/built-in/themes/theme-manager'
import { cloudAuth } from '@/seqta/utils/CloudAuth'
import SignInToFavoriteModal from '@/interface/components/SignInToFavoriteModal.svelte'
import ThemeBlobImage from '@/interface/components/themes/ThemeBlobImage.svelte'
import ThemePlaceholderCover from '@/interface/components/themes/ThemePlaceholderCover.svelte'
import { isLocalCustomTheme } from '@/interface/utils/themeListFilters'
import { formatCustomThemeApiError } from '@/seqta/utils/customThemes/apiErrors'
import type { CustomTheme, ThemeList } from "@/types/customThemes";
import { onDestroy, onMount } from "svelte";
import browser from "@/lib/browser";
import { themeUpdates } from "@/interface/hooks/themeUpdates";
import { ThemeManager } from "@/plugins/built-in/themes/theme-manager";
import { cloudAuth } from "@/seqta/utils/cloudAuth";
import SignInToFavoriteModal from "@/interface/components/SignInToFavoriteModal.svelte";
import ThemeBlobImage from "@/interface/components/themes/ThemeBlobImage.svelte";
import ThemePlaceholderCover from "@/interface/components/themes/ThemePlaceholderCover.svelte";
import { isLocalCustomTheme } from "@/interface/utils/themeListFilters";
import { formatCustomThemeApiError } from "@/seqta/utils/customThemes/apiErrors";
const themeManager = ThemeManager.getInstance();
let themes = $state<ThemeList | null>(null);
let { isEditMode, showNavigation = true }: {
let {
isEditMode,
showNavigation = true,
}: {
isEditMode: boolean;
showNavigation?: boolean;
} = $props();
@@ -46,75 +49,75 @@
if (theme.id === themes?.selectedTheme) {
themeManager.setTransitionPoint(e.clientX, e.clientY);
await themeManager.disableTheme();
themes.selectedTheme = '';
themes.selectedTheme = "";
} else {
themeManager.setTransitionPoint(e.clientX, e.clientY);
await themeManager.setTheme(theme.id);
if (!themes) return;
themes.selectedTheme = theme.id;
}
}
};
const handleThemeDelete = async (themeId: string) => {
try {
await themeManager.deleteTheme(themeId);
if (!themes) return;
themes.themes = themes.themes.filter(theme => theme.id !== themeId);
themes.themes = themes.themes.filter((theme) => theme.id !== themeId);
if (themeId === themes.selectedTheme) {
themes.selectedTheme = '';
themes.selectedTheme = "";
await themeManager.disableTheme();
}
} catch (error) {
console.error('Error deleting theme:', error);
console.error("Error deleting theme:", error);
}
}
};
const handleShareTheme = async (theme: CustomTheme) => {
try {
await themeManager.shareTheme(theme.id);
} catch (error) {
console.error('Error sharing theme:', error);
console.error("Error sharing theme:", error);
}
}
};
const fetchThemes = async () => {
themes = {
themes: await themeManager.getAvailableThemes(),
selectedTheme: themeManager.getSelectedThemeId() || '',
}
selectedTheme: themeManager.getSelectedThemeId() || "",
};
if (themes && cloudLoggedIn) {
const status: Record<string, boolean> = {};
await Promise.all(
themes.themes.map(async (t) => {
try {
const res = (await browser.runtime.sendMessage({
type: 'fetchThemeDetails',
type: "fetchThemeDetails",
themeId: t.id,
})) as { success?: boolean; data?: { theme?: { is_favorited?: boolean } } };
if (res?.success && res?.data?.theme) {
status[t.id] = !!res.data.theme.is_favorited;
}
} catch {
// Theme may not exist on store (e.g. locally created)
if (res?.success && res?.data?.theme) {
status[t.id] = !!res.data.theme.is_favorited;
}
})
);
favoriteStatus = status;
} catch {
// Theme may not exist on store (e.g. locally created)
}
}),
);
favoriteStatus = status;
} else {
favoriteStatus = {};
}
}
};
const openStorePage = async () => {
const { OpenStorePage } = await import('@/seqta/ui/renderStore')
await OpenStorePage()
}
const { OpenStorePage } = await import("@/seqta/ui/renderStore");
await OpenStorePage();
};
const openThemeCreator = async (themeId?: string) => {
const { launchPageThemeBuilder } = await import('@/seqta/utils/launchPageThemeBuilder')
await launchPageThemeBuilder(themeId)
}
const { launchPageThemeBuilder } = await import("@/seqta/utils/launchPageThemeBuilder");
await launchPageThemeBuilder(themeId);
};
const submitCustomTheme = async (theme: CustomTheme, e: MouseEvent) => {
e.stopPropagation();
@@ -125,14 +128,14 @@
}
submittingThemeId = theme.id;
try {
const { submitThemeById } = await import('@/seqta/utils/customThemes/submitLocalTheme');
const { submitThemeById } = await import("@/seqta/utils/customThemes/submitLocalTheme");
await submitThemeById(theme.id, theme.description?.trim() || undefined);
} catch (err) {
submitError = formatCustomThemeApiError(err);
} finally {
submittingThemeId = null;
}
}
};
const handleToggleFavorite = async (theme: CustomTheme, e: MouseEvent) => {
e.stopPropagation();
@@ -142,23 +145,23 @@
}
const isFavorite = !favoriteStatus[theme.id];
const result = (await browser.runtime.sendMessage({
type: 'cloudFavorite',
type: "cloudFavorite",
themeId: theme.id,
action: isFavorite ? 'favorite' : 'unfavorite',
action: isFavorite ? "favorite" : "unfavorite",
})) as { success?: boolean };
if (result?.success) {
favoriteStatus = { ...favoriteStatus, [theme.id]: isFavorite };
}
}
};
onMount(async () => {
await fetchThemes();
themeUpdates.addListener(fetchThemes);
})
});
onDestroy(() => {
themeUpdates.removeListener(fetchThemes);
})
});
const useTwoColumnLayout = $derived(!showNavigation);
</script>
@@ -168,18 +171,26 @@
role="list"
tabindex="-1"
>
<div class="{useTwoColumnLayout ? 'grid grid-cols-2 gap-3' : 'flex flex-col gap-2 px-2'}">
<div class={useTwoColumnLayout ? "grid grid-cols-2 gap-3" : "flex flex-col gap-2 px-2"}>
{#if themes}
{#each themes.themes as theme (theme.id)}
<button
class="relative group w-full aspect-theme flex justify-center items-center rounded-xl transition ring-3 dark:ring-white ring-zinc-300 {theme.id === themes.selectedTheme ? 'dark:ring-2 ring-4' : 'ring-0'}"
class="relative group w-full aspect-theme flex justify-center items-center rounded-xl transition ring-3 dark:ring-white ring-zinc-300 {theme.id ===
themes.selectedTheme
? 'dark:ring-2 ring-4'
: 'ring-0'}"
onclick={(e) => handleThemeClick(theme, e)}
>
{#if isEditMode}
<div
class="flex absolute top-2 right-2 z-20 place-items-center p-2 w-6 h-6 text-white bg-red-600 rounded-full opacity-100"
onclick={(event) => { event.stopPropagation(); handleThemeDelete(theme.id) }}
onkeydown={(event) => { if (event.key === 'Enter' || event.key === ' ') handleThemeDelete(theme.id) }}
onclick={(event) => {
event.stopPropagation();
handleThemeDelete(theme.id);
}}
onkeydown={(event) => {
if (event.key === "Enter" || event.key === " ") handleThemeDelete(theme.id);
}}
role="button"
tabindex="-1"
>
@@ -188,24 +199,45 @@
{/if}
{#if !isEditMode}
<div class="absolute inset-y-0 right-3 z-20 flex items-center gap-2 opacity-0 transition-opacity group-hover:opacity-100">
<div
class="absolute inset-y-0 right-3 z-20 flex items-center gap-2 opacity-0 transition-opacity group-hover:opacity-100"
>
{#if !isLocalCustomTheme(theme)}
<div
class="flex h-8 w-8 place-items-center rounded-full bg-black/50 p-2 text-center {(favoriteStatus[theme.id] ?? false) ? 'text-red-400' : 'text-white/80'}"
class="flex h-8 w-8 place-items-center rounded-full bg-black/50 p-2 text-center {(favoriteStatus[
theme.id
] ?? false)
? 'text-red-400'
: 'text-white/80'}"
onclick={(event) => handleToggleFavorite(theme, event)}
onkeydown={(event) => { if (event.key === 'Enter' || event.key === ' ') handleToggleFavorite(theme, event as any) }}
onkeydown={(event) => {
if (event.key === "Enter" || event.key === " ")
handleToggleFavorite(theme, event as any);
}}
role="button"
tabindex="-1"
title={cloudLoggedIn ? ((favoriteStatus[theme.id] ?? false) ? 'Remove from favorites' : 'Add to favorites') : 'Sign in to favorite themes'}
title={cloudLoggedIn
? (favoriteStatus[theme.id] ?? false)
? "Remove from favorites"
: "Add to favorites"
: "Sign in to favorite themes"}
>
<HeartIcon class="h-5 w-5" fill={(favoriteStatus[theme.id] ?? false) ? 'currentColor' : 'none'} />
<HeartIcon
class="h-5 w-5"
fill={(favoriteStatus[theme.id] ?? false) ? "currentColor" : "none"}
/>
</div>
{/if}
<div
class="flex h-8 w-8 place-items-center rounded-full bg-black/50 p-2 text-white/80"
onclick={(event) => { event.stopPropagation(); handleShareTheme(theme) }}
onkeydown={(event) => { if (event.key === 'Enter' || event.key === ' ') handleShareTheme(theme) }}
onclick={(event) => {
event.stopPropagation();
handleShareTheme(theme);
}}
onkeydown={(event) => {
if (event.key === "Enter" || event.key === " ") handleShareTheme(theme);
}}
role="button"
tabindex="-1"
title="Export theme"
@@ -216,8 +248,13 @@
{#if isLocalCustomTheme(theme)}
<div
class="flex h-8 w-8 place-items-center rounded-full bg-black/50 p-2 text-white"
onclick={(event) => { event.stopPropagation(); void openThemeCreator(theme.id) }}
onkeydown={(event) => { if (event.key === 'Enter' || event.key === ' ') void openThemeCreator(theme.id) }}
onclick={(event) => {
event.stopPropagation();
void openThemeCreator(theme.id);
}}
onkeydown={(event) => {
if (event.key === "Enter" || event.key === " ") void openThemeCreator(theme.id);
}}
role="button"
tabindex="-1"
title="Edit theme"
@@ -225,9 +262,15 @@
<PencilIcon size="1em" class="text-lg" />
</div>
<div
class="flex h-8 w-8 place-items-center rounded-full bg-black/50 p-2 text-white {submittingThemeId === theme.id ? 'opacity-60' : ''}"
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) }}
onkeydown={(event) => {
if (event.key === "Enter" || event.key === " ")
void submitCustomTheme(theme, event as unknown as MouseEvent);
}}
role="button"
tabindex="-1"
title="Submit to community"
@@ -238,7 +281,11 @@
</div>
{/if}
<div class="relative top-0 z-10 flex justify-center w-full h-full overflow-hidden transition dark:text-white rounded-xl group place-items-center bg-zinc-100 dark:bg-zinc-900 { isEditMode ? 'animate-shake brightness-90' : ''}">
<div
class="relative top-0 z-10 flex justify-center w-full h-full overflow-hidden transition dark:text-white rounded-xl group place-items-center bg-zinc-100 dark:bg-zinc-900 {isEditMode
? 'animate-shake brightness-90'
: ''}"
>
{#if theme.coverImage}
<ThemeBlobImage
source={theme.coverImage}
@@ -260,18 +307,31 @@
{/if}
{#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' : ''}">
<div
class="flex min-h-56 flex-col items-center justify-center px-4 py-10 text-center {useTwoColumnLayout
? 'col-span-2'
: ''}"
>
<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">
<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 submitError}
<p class="whitespace-pre-line text-sm text-red-600 dark:text-red-400 {useTwoColumnLayout ? 'col-span-2' : ''}">{submitError}</p>
<p
class="whitespace-pre-line text-sm text-red-600 dark:text-red-400 {useTwoColumnLayout
? 'col-span-2'
: ''}"
>
{submitError}
</p>
{/if}
{#if themes && showNavigation}
@@ -1,13 +1,13 @@
import browser from "@/lib/browser";
import type { Theme } from "@/interface/types/Theme";
import type { Theme } from "@/interface/types/theme";
import {
getCommunityInstalledThemeIds,
getStoreInstalledThemeIds,
} from "@/interface/utils/themeListFilters";
import { normalizeStoreTheme } from "@/interface/utils/themeStoreFlavours";
import { themeUpdates } from "@/interface/hooks/ThemeUpdates";
import { themeUpdates } from "@/interface/hooks/themeUpdates";
import { ThemeManager } from "@/plugins/built-in/themes/theme-manager";
import { cloudAuth, isCloudAdmin } from "@/seqta/utils/CloudAuth";
import { cloudAuth, isCloudAdmin } from "@/seqta/utils/cloudAuth";
import {
deleteCustomTheme,
fetchCommunityThemes,
File renamed without changes.
+1 -1
View File
@@ -1,6 +1,6 @@
import Settings from "./pages/settings.svelte";
import renderSvelte from "./main";
import { initializeSettingsState } from "@/seqta/utils/listeners/SettingsState";
import { initializeSettingsState } from "@/seqta/utils/listeners/settingsState";
import { loadRemoteStatus } from "@/seqta/utils/remoteStatus";
import { initVerboseLogging, verboseInfo } from "@/utils/verboseLog";
+9 -4
View File
@@ -21,7 +21,8 @@
<div class="inline-flex rounded-xl bg-zinc-200/80 p-1 dark:bg-zinc-800/80">
<button
type="button"
class="rounded-lg px-4 py-2 text-sm font-medium transition-colors {communityState.innerTab === 'browse'
class="rounded-lg px-4 py-2 text-sm font-medium transition-colors {communityState.innerTab ===
'browse'
? 'bg-white text-zinc-900 shadow-sm 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 = "browse")}
@@ -30,7 +31,8 @@
</button>
<button
type="button"
class="rounded-lg px-4 py-2 text-sm font-medium transition-colors {communityState.innerTab === 'mine'
class="rounded-lg px-4 py-2 text-sm font-medium transition-colors {communityState.innerTab ===
'mine'
? 'bg-white text-zinc-900 shadow-sm 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 = "mine")}
@@ -40,7 +42,8 @@
{#if communityState.isAdmin}
<button
type="button"
class="rounded-lg px-4 py-2 text-sm font-medium transition-colors {communityState.innerTab === 'review'
class="rounded-lg px-4 py-2 text-sm font-medium transition-colors {communityState.innerTab ===
'review'
? 'bg-white text-zinc-900 shadow-sm 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")}
@@ -63,7 +66,9 @@
</p>
</div>
<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">
<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 if communityState.innerTab === "mine"}
+98 -78
View File
@@ -14,12 +14,12 @@
import { standalone as StandaloneStore } from "../utils/standalone.svelte";
import { onMount, onDestroy, tick } from "svelte";
import { animate } from "motion";
import { settingsState } from "@/seqta/utils/listeners/SettingsState";
import { settingsState } from "@/seqta/utils/listeners/settingsState";
import { isPerformanceMode } from "@/seqta/utils/performanceMode";
import { closeExtensionPopup } from "@/seqta/utils/closers/closeExtensionPopup";
import { OpenAboutPage } from "@/seqta/utils/openers/OpenAboutPage";
import { OpenWhatsNewPopup } from "@/seqta/utils/openers/OpenWhatsNewPopup";
import { OpenAboutPage } from "@/seqta/utils/openers/openAboutPage";
import { OpenWhatsNewPopup } from "@/seqta/utils/openers/openWhatsNewPopup";
import type { Component } from "svelte";
import SidebarNav from "../components/SidebarNav.svelte";
@@ -107,13 +107,15 @@
if (!$settingsState.devMode && activeSection === "advanced") activeSection = "general";
});
const appNav = $derived<NavItem[]>([
{ id: "timetable", label: "Timetable" },
{ id: "assessments", label: "Assessments" },
{ id: "features", label: "Features" },
...($settingsState.devMode ? [{ id: "advanced", label: "Advanced" }] : []),
{ id: "shortcuts", label: "Shortcuts" },
].filter((item) => isSectionVisible(item.id)));
const appNav = $derived<NavItem[]>(
[
{ id: "timetable", label: "Timetable" },
{ id: "assessments", label: "Assessments" },
{ id: "features", label: "Features" },
...($settingsState.devMode ? [{ id: "advanced", label: "Advanced" }] : []),
{ id: "shortcuts", label: "Shortcuts" },
].filter((item) => isSectionVisible(item.id)),
);
const settingsNavGroups = $derived([
{ label: "User Settings", items: userNav },
@@ -195,8 +197,7 @@
);
const openGhRelease = () => {
const url =
ghReleaseUpdate?.url ?? "https://github.com/BetterSEQTA/BetterSEQTA-Plus/releases";
const url = ghReleaseUpdate?.url ?? "https://github.com/BetterSEQTA/BetterSEQTA-Plus/releases";
if (ghReleaseUpdate?.available) {
dismissNightlyUpdate();
}
@@ -315,7 +316,9 @@
const from = panel ? getComputedStyle(panel) : null;
const start = bounds.map((key) => parseFloat(from?.[key] ?? "0"));
resizeAnimation?.stop();
const motionEnabled = $settingsState.animations !== false && !$settingsState.performanceMode &&
const motionEnabled =
$settingsState.animations !== false &&
!$settingsState.performanceMode &&
!window.matchMedia("(prefers-reduced-motion: reduce)").matches;
const root = panel?.getRootNode() as ShadowRoot | Document | undefined;
const restoreFocus = !!content?.contains(root?.activeElement ?? null);
@@ -343,9 +346,12 @@
await tick();
if (!panel || !content || generation !== resizeGeneration) return;
for (const key of bounds) panel.style.removeProperty(key);
if (restoreFocus) content.querySelector<HTMLButtonElement>(
`[aria-label="${nextExpanded ? "Collapse" : "Expand"} settings"]`,
)?.focus({ preventScroll: true });
if (restoreFocus)
content
.querySelector<HTMLButtonElement>(
`[aria-label="${nextExpanded ? "Collapse" : "Expand"} settings"]`,
)
?.focus({ preventScroll: true });
if (!motionEnabled) return;
const targetStyle = getComputedStyle(panel);
const target = bounds.map((key) => parseFloat(targetStyle[key]));
@@ -353,9 +359,13 @@
// move, so compact text and images never stretch across the expanded panel.
content.style.width = `${panel.clientWidth}px`;
content.style.height = `${panel.clientHeight}px`;
bounds.forEach((key, index) => { panel.style[key] = `${start[index]}px`; });
bounds.forEach((key, index) => {
panel.style[key] = `${start[index]}px`;
});
resizeAnimation = animate(0, 1, {
type: "spring", stiffness: 420, damping: 36,
type: "spring",
stiffness: 420,
damping: 36,
onUpdate: (progress) => {
if (generation !== resizeGeneration) return;
const opacity = Math.max(0, Math.min(1, progress));
@@ -402,9 +412,7 @@
};
const syncCompactTab = () => {
compactActiveTab = activePage === "settings"
? activeSection === "shortcuts" ? 1 : 0
: 2;
compactActiveTab = activePage === "settings" ? (activeSection === "shortcuts" ? 1 : 0) : 2;
lastExpandedTab = compactActiveTab;
};
@@ -469,7 +477,8 @@
? "community-themes"
: "theme-settings";
} else if (destination.page === "backgrounds" && destination.view) {
activeBackgroundView = destination.view === "store" ? "background-store" : "background-settings";
activeBackgroundView =
destination.view === "store" ? "background-store" : "background-settings";
}
};
@@ -575,7 +584,9 @@
{#if activePage === "settings"}
<label class="relative mb-4 block shrink-0">
<span class="sr-only">Search settings</span>
<SearchIcon class="pointer-events-none absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-zinc-400" />
<SearchIcon
class="pointer-events-none absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-zinc-400"
/>
<input
type="search"
placeholder="Search settings"
@@ -585,13 +596,11 @@
</label>
{/if}
<SidebarNav
groups={navGroups}
selectedId={selectedNavId}
onselect={selectNavItem}
/>
<SidebarNav groups={navGroups} selectedId={selectedNavId} onselect={selectNavItem} />
<div class="mt-4 flex shrink-0 flex-col gap-1 border-t border-zinc-200/60 pt-4 dark:border-zinc-700/50">
<div
class="mt-4 flex shrink-0 flex-col gap-1 border-t border-zinc-200/60 pt-4 dark:border-zinc-700/50"
>
{#if ghReleaseUpdateEnabled}
<div class="px-3 pb-2">
{#if ghReleaseUpdate?.available}
@@ -709,7 +718,6 @@
</div>
</div>
{/if}
</div>
</div>
</div>
@@ -721,13 +729,17 @@
>
<RemoteStatusStrip />
<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'}"
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'}"
>
<!-- svelte-ignore a11y_no_noninteractive_element_interactions -->
<!-- svelte-ignore a11y_click_events_have_key_events -->
<img
src={resolveExtensionAssetUrl(darkLogo)}
class="min-w-0 dark:hidden {standalone ? 'mx-auto w-4/5' : 'h-auto w-full max-w-[296px] justify-self-center object-contain'}"
class="min-w-0 dark:hidden {standalone
? 'mx-auto w-4/5'
: 'h-auto w-full max-w-[296px] justify-self-center object-contain'}"
alt="BetterSEQTA+"
onclick={handleDevModeToggle}
/>
@@ -735,14 +747,21 @@
<!-- svelte-ignore a11y_click_events_have_key_events -->
<img
src={resolveExtensionAssetUrl(lightLogo)}
class="hidden min-w-0 dark:block {standalone ? 'mx-auto w-4/5' : 'h-auto w-full max-w-[296px] justify-self-center object-contain'}"
class="hidden min-w-0 dark:block {standalone
? 'mx-auto w-4/5'
: 'h-auto w-full max-w-[296px] justify-self-center object-contain'}"
alt="BetterSEQTA+"
onclick={handleDevModeToggle}
/>
{#if !standalone}
<button type="button" onclick={toggleExpanded}
<button
type="button"
onclick={toggleExpanded}
class="mt-2 flex h-11 w-11 shrink-0 self-start items-center justify-center text-zinc-500 transition-[color,transform] duration-150 hover:text-zinc-950 active:scale-[0.96] dark:text-zinc-400 dark:hover:text-white"
aria-label="Expand settings" title="Expand settings" aria-expanded="false">
aria-label="Expand settings"
title="Expand settings"
aria-expanded="false"
>
<Maximize2Icon size="1em" class="text-2xl" />
</button>
{/if}
@@ -785,19 +804,20 @@
</div>
{:else}
<div
class="absolute inset-0 z-50 {$settingsState.DarkMode
? 'dark'
: ''}"
class="absolute inset-0 z-50 {$settingsState.DarkMode ? 'dark' : ''}"
role="dialog"
aria-modal="true"
aria-label="BetterSEQTA+ settings"
>
<button
type="button"
class="settings-backdrop absolute inset-0 {expanded ? 'bg-black/60' : 'bg-transparent'} {expanded && !$settingsState.performanceMode
class="settings-backdrop absolute inset-0 {expanded
? 'bg-black/60'
: 'bg-transparent'} {expanded && !$settingsState.performanceMode
? 'backdrop-blur-xs'
: 'backdrop-blur-none'}"
class:settings-backdrop--motion={$settingsState.animations !== false && !$settingsState.performanceMode}
class:settings-backdrop--motion={$settingsState.animations !== false &&
!$settingsState.performanceMode}
aria-label="Close settings"
onclick={handleClose}
></button>
@@ -819,44 +839,6 @@
</div>
{/if}
<style>
.settings-content {
position: absolute;
top: 0;
right: 0;
width: 100%;
height: 100%;
}
.settings-panel {
width: min(384px, calc(100vw - 20px));
height: min(600px, calc(100vh - 95px));
top: min(80px, 10vh);
right: 10px;
border-radius: 1rem;
transform-origin: 70% 0;
}
.settings-panel--expanded {
border-radius: 0.75rem;
transform-origin: center;
width: min(1180px, 96vw);
height: min(860px, 92vh);
top: calc((100% - min(860px, 92vh)) / 2);
right: calc((100% - min(1180px, 96vw)) / 2);
}
.settings-backdrop--motion {
transition: background-color 200ms ease;
}
@media (prefers-reduced-motion: reduce) {
.settings-backdrop--motion {
transition: none;
}
}
</style>
{#if showColourPicker && ColourPickerComponent}
<ColourPickerComponent
hidePicker={() => {
@@ -907,3 +889,41 @@
}}
/>
{/if}
<style>
.settings-content {
position: absolute;
top: 0;
right: 0;
width: 100%;
height: 100%;
}
.settings-panel {
width: min(384px, calc(100vw - 20px));
height: min(600px, calc(100vh - 95px));
top: min(80px, 10vh);
right: 10px;
border-radius: 1rem;
transform-origin: 70% 0;
}
.settings-panel--expanded {
border-radius: 0.75rem;
transform-origin: center;
width: min(1180px, 96vw);
height: min(860px, 92vh);
top: calc((100% - min(860px, 92vh)) / 2);
right: calc((100% - min(1180px, 96vw)) / 2);
}
.settings-backdrop--motion {
transition: background-color 200ms ease;
}
@media (prefers-reduced-motion: reduce) {
.settings-backdrop--motion {
transition: none;
}
}
</style>
@@ -5,11 +5,9 @@
import Slider from "@/interface/components/Slider.svelte";
import Select from "@/interface/components/Select.svelte";
import HotkeyInput from "@/interface/components/HotkeyInput.svelte";
import { settingsState } from "@/seqta/utils/listeners/SettingsState";
import { cloudAuth } from "@/seqta/utils/CloudAuth";
import {
setPerformanceModePluginOverride,
} from "@/seqta/utils/performanceMode";
import { settingsState } from "@/seqta/utils/listeners/settingsState";
import { cloudAuth } from "@/seqta/utils/cloudAuth";
import { setPerformanceModePluginOverride } from "@/seqta/utils/performanceMode";
import { PERFORMANCE_HEAVY_PLUGIN_IDS } from "@/seqta/utils/performanceModeConfig";
import { onMount } from "svelte";
import {
@@ -18,10 +16,7 @@
type SettingsSectionId,
type SettingsSectionSharedProps,
} from "./shared";
import {
pluginSettingsStore,
type PluginSettingsEntry,
} from "./pluginSettingsState.svelte";
import { pluginSettingsStore, type PluginSettingsEntry } from "./pluginSettingsState.svelte";
let {
section,
@@ -54,8 +49,7 @@
const visiblePlugins = $derived(
pluginSettingsStore.plugins.filter(
(plugin) =>
(PLUGIN_SECTION_BY_ID[plugin.pluginId] ?? "features") === section &&
pluginHit(plugin),
(PLUGIN_SECTION_BY_ID[plugin.pluginId] ?? "features") === section && pluginHit(plugin),
),
);
@@ -71,7 +65,12 @@
{#each visiblePlugins as plugin (plugin.pluginId)}
{@const perfPaused = pluginPerfPaused(plugin.pluginId)}
<SettingsCard class="divide-y divide-zinc-200/60 dark:divide-zinc-700/40 {!plugin.disableToggle && Object.keys(plugin.settings).length === 0 ? 'hidden' : ''} {perfPaused ? 'opacity-60' : ''}">
<SettingsCard
class="divide-y divide-zinc-200/60 dark:divide-zinc-700/40 {!plugin.disableToggle &&
Object.keys(plugin.settings).length === 0
? 'hidden'
: ''} {perfPaused ? 'opacity-60' : ''}"
>
{#if perfPaused}
<div
class="flex justify-between items-center px-4 py-3 rounded-lg bg-amber-50/80 dark:bg-amber-950/20"
@@ -88,7 +87,11 @@
{/if}
{#if plugin.disableToggle}
<div class="flex justify-between items-center px-4 py-3 {perfPaused ? 'pointer-events-none' : ''}">
<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}
@@ -104,7 +107,8 @@
</div>
<div>
<Switch
state={(pluginSettingsStore.values[plugin.pluginId]?.enabled as boolean | undefined) ?? true}
state={(pluginSettingsStore.values[plugin.pluginId]?.enabled as boolean | undefined) ??
true}
onChange={async (value) => {
if (plugin.pluginId === "assessments-average" && value === true) {
showDisclaimer(
@@ -135,13 +139,15 @@
<div>
{#if setting.type === "boolean"}
<Switch
state={(pluginSettingsStore.values[plugin.pluginId]?.[key] as boolean | undefined) ?? setting.default}
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}
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}
@@ -152,13 +158,15 @@
<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}
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}
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,
@@ -169,7 +177,8 @@
<Button onClick={() => setting.trigger?.()} text={setting.title} />
{:else if setting.type === "hotkey"}
<HotkeyInput
value={(pluginSettingsStore.values[plugin.pluginId]?.[key] as string | undefined) ?? setting.default}
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}
@@ -1,5 +1,5 @@
<script lang="ts">
import type { SettingsList } from "@/interface/types/SettingsProps";
import type { SettingsList } from "@/interface/types/settingsProps";
import { matchesSearch } from "./shared";
let {
@@ -6,16 +6,12 @@
import CloudHeader from "@/interface/components/store/CloudHeader.svelte";
import SettingRow from "../SettingRow.svelte";
import PluginSettingsBlocks from "../PluginSettingsBlocks.svelte";
import { settingsState } from "@/seqta/utils/listeners/SettingsState";
import { cloudAuth } from "@/seqta/utils/CloudAuth";
import { settingsState } from "@/seqta/utils/listeners/settingsState";
import { cloudAuth } from "@/seqta/utils/cloudAuth";
import { matchesSearch, type SettingsSectionSharedProps } from "../shared";
import { toMountableComponent } from "@/types/mountableComponent";
let {
showDisclaimer,
showCloudPanel,
searchQuery = "",
}: SettingsSectionSharedProps = $props();
let { showDisclaimer, showCloudPanel, searchQuery = "" }: SettingsSectionSharedProps = $props();
let cloudState = $state(cloudAuth.state);
$effect(() => {
@@ -102,9 +98,7 @@
{/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>
<div class="px-5 pb-4 text-sm text-zinc-600 dark:text-zinc-400">Sign in to Cloud first.</div>
{/if}
</SettingsCard>
{/if}
@@ -2,9 +2,9 @@
import { delay } from "@/seqta/utils/delay";
import Switch from "@/interface/components/Switch.svelte";
import Button from "@/interface/components/Button.svelte";
import { settingsState } from "@/seqta/utils/listeners/SettingsState";
import { openTermsOfServicePopup } from "@/seqta/utils/openers/OpenTermsOfServicePopup";
import { showThemeOfTheMonthPopupNow } from "@/seqta/utils/openers/OpenThemeOfTheMonthPopup";
import { settingsState } from "@/seqta/utils/listeners/settingsState";
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";
@@ -26,19 +26,7 @@
}
</script>
{#if $settingsState.devMode && matchesSearch(
searchQuery,
"Developer Mode",
"Verbose logging",
"Delay loading screen",
"Sensitive Hider",
"Mock Notices",
"Show Privacy Notification",
"Show Theme of the Month",
"Export cloud settings JSON",
"API Base URL",
"GitHub latest version override",
)}
{#if $settingsState.devMode && matchesSearch(searchQuery, "Developer Mode", "Verbose logging", "Delay loading screen", "Sensitive Hider", "Mock Notices", "Show Privacy Notification", "Show Theme of the Month", "Export cloud settings JSON", "API Base URL", "GitHub latest version override")}
<div
class="flex-col p-1 my-1 bg-linear-to-br from-white rounded-xl border shadow-xs to-zinc-100 border-zinc-200/50 dark:border-zinc-700/40 dark:to-zinc-900/50 dark:from-zinc-900/40"
>
@@ -6,10 +6,10 @@
import SidebarAppearance from "@/interface/components/SidebarAppearance.svelte";
import SettingRow from "../SettingRow.svelte";
import PluginSettingsBlocks from "../PluginSettingsBlocks.svelte";
import { settingsState } from "@/seqta/utils/listeners/SettingsState";
import { settingsState } from "@/seqta/utils/listeners/settingsState";
import { isSeqtaEngageExperience } from "@/seqta/utils/isSeqtaEngage";
import { matchesSearch, type SettingsSectionSharedProps } from "../shared";
import type { SettingsList } from "@/interface/types/SettingsProps";
import type { SettingsList } from "@/interface/types/settingsProps";
let {
showColourPicker,
@@ -23,34 +23,7 @@
{#if matchesSearch(searchQuery, "Custom Theme Colour", "Interface Font", "Theme of the Month", "Customise the overall theme colour of SEQTA Learn", "Choose the typeface used across SEQTA Learn", "Show the monthly featured theme popup when a new entry is available")}
<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" },
},
{
title: "Theme of the Month",
description: "Show the monthly featured theme popup when a new entry is available",
id: 15,
Component: Switch,
props: {
state: !($settingsState.themeOfTheMonthDisabled ?? false),
onChange: (isOn: boolean) => (settingsState.themeOfTheMonthDisabled = !isOn),
},
},
] as unknown as SettingsList[]
) as option (option.id)}
{#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" } }, { title: "Theme of the Month", description: "Show the monthly featured theme popup when a new entry is available", id: 15, Component: Switch, props: { state: !($settingsState.themeOfTheMonthDisabled ?? false), onChange: (isOn: boolean) => (settingsState.themeOfTheMonthDisabled = !isOn) } }] as unknown as SettingsList[] as option (option.id)}
<SettingRow {...option} {searchQuery} />
{/each}
</SettingsCard>
@@ -4,7 +4,7 @@
import Button from "@/interface/components/Button.svelte";
import Select from "@/interface/components/Select.svelte";
import SettingRow from "../SettingRow.svelte";
import { settingsState } from "@/seqta/utils/listeners/SettingsState";
import { settingsState } from "@/seqta/utils/listeners/settingsState";
import { isSeqtaEngageExperience } from "@/seqta/utils/isSeqtaEngage";
import {
PERFORMANCE_HEAVY_PLUGINS,
@@ -12,7 +12,7 @@
} from "@/seqta/utils/performanceMode";
import browser from "@/lib/browser";
import { matchesSearch, type SettingsSectionSharedProps } from "../shared";
import type { SettingsList } from "@/interface/types/SettingsProps";
import type { SettingsList } from "@/interface/types/settingsProps";
import { isFeatureDisabled } from "@/seqta/utils/remoteStatus";
let { searchQuery = "" }: SettingsSectionSharedProps = $props();
@@ -160,12 +160,15 @@
{#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-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)}
onChange={(forceOn: boolean) =>
setPerformanceModePluginOverride(heavy.id, forceOn)}
/>
</div>
{/each}
@@ -177,13 +180,7 @@
</SettingsCard>
{/if}
{#if matchesSearch(
searchQuery,
"Home Page Assessments",
"Include Past Assessments",
"Maximum Subjects",
"Maximum Assessments per Subject",
)}
{#if matchesSearch(searchQuery, "Home Page Assessments", "Include Past Assessments", "Maximum Subjects", "Maximum Assessments per Subject")}
<SettingsCard>
<div class="flex justify-between items-center px-4 py-3">
<div class="pr-4">
+98 -86
View File
@@ -1,12 +1,12 @@
<script lang="ts">
import XIcon from "@lucide/svelte/icons/x";
import UploadIcon from "@lucide/svelte/icons/upload";
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"
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";
let { searchQuery = "" }: { searchQuery?: string } = $props();
const q = $derived(searchQuery.trim().toLowerCase());
@@ -31,19 +31,14 @@
const switchChange = (shortcut: any) => {
const current = settingsState.shortcuts ?? [];
const idx = current.findIndex(s => s.name === shortcut);
const idx = current.findIndex((s) => s.name === shortcut);
if (idx !== -1) {
const updated = current.map(s =>
s.name === shortcut ? { ...s, enabled: !s.enabled } : s
);
const updated = current.map((s) => (s.name === shortcut ? { ...s, enabled: !s.enabled } : s));
settingsState.setKey("shortcuts", updated);
} else {
settingsState.setKey("shortcuts", [
...current,
{ name: shortcut, enabled: true },
]);
settingsState.setKey("shortcuts", [...current, { name: shortcut, enabled: true }]);
}
}
};
let isFormVisible = $state(false);
let newTitle = $state("");
@@ -78,9 +73,12 @@
};
const isValidTitle = (title: string) => title.trim() !== "";
const isValidURL = (url: string) => {
const pattern = new RegExp("^(https?:\\/\\/)?[\\w.-]+(?:\\.[\\w\\-]+)*(?::\\d+)?(/[\\w\\-./]*)*$", "i");
const pattern = new RegExp(
"^(https?:\\/\\/)?[\\w.-]+(?:\\.[\\w\\-]+)*(?::\\d+)?(/[\\w\\-./]*)*$",
"i",
);
return pattern.test(url);
};
@@ -113,37 +111,37 @@
<div class="flex flex-col pt-4 divide-y divide-zinc-100 dark:divide-zinc-700">
{#if isLoaded}
{#if !q}
<div>
<MotionDiv
initial={{ opacity: 0, height: 0 }}
animate={isFormVisible ? { opacity: 1, height: 'auto' } : { opacity: 0, height: 0 }}
exit={{ opacity: 0, height: 0 }}
transition={{
type: 'spring',
config: { stiffness: 400, damping: 25 }
}}
>
{#if isFormVisible}
<div class="flex flex-col items-center">
<MotionDiv
initial={{ opacity: 0, y: -10 }}
animate={{ opacity: 1, y: 0 }}
transition={{ delay: 0, duration: 0.2 }}
class="w-full"
>
<input
class="p-2 w-full rounded-lg border-0 transition placeholder-zinc-300 bg-zinc-100 dark:bg-zinc-700 focus:bg-zinc-200/50 dark:focus:bg-zinc-600"
type="text"
placeholder="Shortcut Name"
bind:value={newTitle}
/>
</MotionDiv>
<MotionDiv
initial={{ opacity: 0, y: -10 }}
animate={{ opacity: 1, y: 0 }}
transition={{ delay: 0.05, duration: 0.2 }}
class="flex gap-2 w-full"
>
<div>
<MotionDiv
initial={{ opacity: 0, height: 0 }}
animate={isFormVisible ? { opacity: 1, height: "auto" } : { opacity: 0, height: 0 }}
exit={{ opacity: 0, height: 0 }}
transition={{
type: "spring",
config: { stiffness: 400, damping: 25 },
}}
>
{#if isFormVisible}
<div class="flex flex-col items-center">
<MotionDiv
initial={{ opacity: 0, y: -10 }}
animate={{ opacity: 1, y: 0 }}
transition={{ delay: 0, duration: 0.2 }}
class="w-full"
>
<input
class="p-2 w-full rounded-lg border-0 transition placeholder-zinc-300 bg-zinc-100 dark:bg-zinc-700 focus:bg-zinc-200/50 dark:focus:bg-zinc-600"
type="text"
placeholder="Shortcut Name"
bind:value={newTitle}
/>
</MotionDiv>
<MotionDiv
initial={{ opacity: 0, y: -10 }}
animate={{ opacity: 1, y: 0 }}
transition={{ delay: 0.05, duration: 0.2 }}
class="flex gap-2 w-full"
>
<input
class="p-2 my-2 w-full rounded-lg border-0 transition placeholder-zinc-300 bg-zinc-100 dark:bg-zinc-700 focus:bg-zinc-200/50 dark:focus:bg-zinc-600"
type="text"
@@ -166,7 +164,11 @@
{#if newIcon}
<div class="flex overflow-hidden items-center">
<div class="shrink-0 mr-2 w-6 h-6">
<img src={`data:image/svg+xml;base64,${btoa(newIcon)}`} alt="Selected Icon" class="object-contain w-full h-full" />
<img
src={`data:image/svg+xml;base64,${btoa(newIcon)}`}
alt="Selected Icon"
class="object-contain w-full h-full"
/>
</div>
<span class="truncate">Selected Icon</span>
</div>
@@ -175,9 +177,12 @@
aria-label="Clear icon"
role="button"
tabindex="0"
onclick={(event) => { event.stopPropagation(); clearIcon(); }}
onclick={(event) => {
event.stopPropagation();
clearIcon();
}}
onkeydown={(event) => {
if (event.key === 'Enter' || event.key === ' ') {
if (event.key === "Enter" || event.key === " ") {
event.preventDefault();
clearIcon();
}
@@ -186,55 +191,62 @@
<XIcon class="w-4 h-4" />
</span>
{:else}
<UploadIcon size="1em" />
<span class="ml-2">SVG icon <span class="text-xs italic text-zinc-400 dark:text-zinc-500">(Optional)</span></span>
<UploadIcon size="1em" />
<span class="ml-2"
>SVG icon <span class="text-xs italic text-zinc-400 dark:text-zinc-500"
>(Optional)</span
></span
>
{/if}
</button>
</MotionDiv>
</div>
{/if}
</MotionDiv>
</MotionDiv>
</div>
{/if}
</MotionDiv>
<MotionDiv
initial={{ opacity: 0, y: 20 }}
animate={{ opacity: 1, y: 0 }}
transition={{ duration: 0.3 }}
>
<Button
class="w-full mb-4"
text={isFormVisible ? "Add" : "Add Custom Shortcut"}
onClick={isFormVisible ? addNewCustomShortcut : toggleForm}
/>
</MotionDiv>
</div>
<MotionDiv
initial={{ opacity: 0, y: 20 }}
animate={{ opacity: 1, y: 0 }}
transition={{ duration: 0.3 }}
>
<Button
class="w-full mb-4"
text={isFormVisible ? "Add" : "Add Custom Shortcut"}
onClick={isFormVisible ? addNewCustomShortcut : toggleForm}
/>
</MotionDiv>
</div>
{/if}
<!-- Custom Shortcuts Section -->
{#each ($settingsState.customshortcuts ?? []) as shortcut, index}
{#each $settingsState.customshortcuts ?? [] as shortcut, index}
{#if !q || shortcut.name.toLowerCase().includes(q)}
<div class="flex justify-between items-center px-4 py-3">
{shortcut.name}
<button aria-label="Delete Shortcut" onclick={() => deleteCustomShortcut(index)}>
<XIcon class="w-6 h-6" />
</button>
</div>
<div class="flex justify-between items-center px-4 py-3">
{shortcut.name}
<button aria-label="Delete Shortcut" onclick={() => deleteCustomShortcut(index)}>
<XIcon class="w-6 h-6" />
</button>
</div>
{/if}
{/each}
{#each Object.entries(Shortcuts) as shortcut}
{#if !q || shortcut[1].DisplayName?.toLowerCase().includes(q) || shortcut[0].toLowerCase().includes(q)}
<div class="flex justify-between items-center px-4 py-3">
<div class="pr-4">
<!-- Use DisplayName if it exists, otherwise use the key (shortcut[0]) as a fallback -->
<h2 class="text-lg font-medium">{shortcut[1].DisplayName || shortcut[0]}</h2>
{#if !q || shortcut[1].DisplayName?.toLowerCase().includes(q) || shortcut[0]
.toLowerCase()
.includes(q)}
<div class="flex justify-between items-center px-4 py-3">
<div class="pr-4">
<!-- Use DisplayName if it exists, otherwise use the key (shortcut[0]) as a fallback -->
<h2 class="text-lg font-medium">{shortcut[1].DisplayName || shortcut[0]}</h2>
</div>
<Switch
state={$settingsState.shortcuts.find((s) => s.name === shortcut[0])?.enabled ?? false}
onChange={() => switchChange(shortcut[0])}
/>
</div>
<Switch state={$settingsState.shortcuts.find(s => s.name === shortcut[0])?.enabled ?? false} onChange={() => switchChange(shortcut[0])} />
</div>
{/if}
{/each}
{:else}
<div class="p-4 text-center">
Loading shortcuts...
</div>
<div class="p-4 text-center">Loading shortcuts...</div>
{/if}
</div>
+23 -17
View File
@@ -1,18 +1,20 @@
<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 CheckIcon from "@lucide/svelte/icons/check"
import PencilIcon from "@lucide/svelte/icons/pencil"
import { standalone } from "@/interface/utils/standalone.svelte"
import BackgroundSelector from "@/interface/components/themes/BackgroundSelector.svelte";
import ThemeSelector from "@/interface/components/themes/ThemeSelector.svelte";
import Button from "@/interface/components/Button.svelte";
import CheckIcon from "@lucide/svelte/icons/check";
import PencilIcon from "@lucide/svelte/icons/pencil";
import { standalone } from "@/interface/utils/standalone.svelte";
let { section = "all" }: {
let {
section = "all",
}: {
section?: "all" | "themes" | "backgrounds";
} = $props();
let selectedBackground = $state<string | null>(null);
let selectNoBackground = $state<() => void>(() => { });
let selectNoBackground = $state<() => void>(() => {});
let clearTheme = $derived(selectedBackground !== null);
let editMode = $state<boolean>(false);
let showBackgrounds = $derived(section !== "themes");
@@ -26,8 +28,12 @@
onClick={() => selectNoBackground()}
disabled={section === "backgrounds" && !clearTheme}
text={section === "all"
? clearTheme ? 'Clear Theme' : 'Select a Theme'
: clearTheme ? 'Clear Background' : 'No Background Selected'}
? clearTheme
? "Clear Theme"
: "Select a Theme"
: clearTheme
? "Clear Background"
: "No Background Selected"}
class="w-full mb-4"
/>
{/if}
@@ -35,15 +41,15 @@
{#if showThemes || showBackgrounds}
<div class="mb-3 flex justify-end">
<Button
onClick={() => editMode = !editMode}
text={editMode ? 'Done' : 'Remove'}
onClick={() => (editMode = !editMode)}
text={editMode ? "Done" : "Remove"}
icon={editMode ? CheckIcon : PencilIcon}
/>
</div>
{/if}
{#if showBackgrounds}
<BackgroundSelector isEditMode={editMode} bind:selectedBackground={selectedBackground} bind:selectNoBackground={selectNoBackground} />
<BackgroundSelector isEditMode={editMode} bind:selectedBackground bind:selectNoBackground />
{/if}
{#if showThemes}
{#if section === "themes"}
@@ -52,8 +58,8 @@
class="w-full mb-4"
text="Open theme builder"
onClick={() =>
void import("@/seqta/utils/launchPageThemeBuilder").then(({ launchPageThemeBuilder }) =>
launchPageThemeBuilder(),
void import("@/seqta/utils/launchPageThemeBuilder").then(
({ launchPageThemeBuilder }) => launchPageThemeBuilder(),
)}
/>
{/if}
+85 -59
View File
@@ -1,25 +1,29 @@
<script lang="ts">
import { onMount } from 'svelte';
import CoverSwiper from '../components/store/CoverSwiper.svelte';
import ThemeGrid from '../components/store/ThemeGrid.svelte';
import SkeletonLoader from '../components/SkeletonLoader.svelte';
import type { Theme } from '../types/Theme'
import { visibleStoreThemes, buildCoverSlidesForThemes, normalizeStoreTheme } from '@/interface/utils/themeStoreFlavours'
import browser from '@/lib/browser'
import ThemeModal from '../components/store/ThemeModal.svelte'
import { themeUpdates } from '../hooks/ThemeUpdates'
import { ThemeManager } from '@/plugins/built-in/themes/theme-manager'
import { onMount } from "svelte";
import { loadBackground } from '@/seqta/ui/ImageBackgrounds'
import Backgrounds from '../components/store/Backgrounds.svelte'
import { cloudAuth } from '@/seqta/utils/CloudAuth'
import SignInToFavoriteModal from '../components/SignInToFavoriteModal.svelte'
import { getStoreInstalledThemeIds } from '@/interface/utils/themeListFilters'
import { consumePendingHighlightThemeId } from '@/seqta/utils/openThemeStoreWithHighlight'
import CoverSwiper from "../components/store/CoverSwiper.svelte";
import ThemeGrid from "../components/store/ThemeGrid.svelte";
import SkeletonLoader from "../components/SkeletonLoader.svelte";
import type { Theme } from "../types/theme";
import {
visibleStoreThemes,
buildCoverSlidesForThemes,
normalizeStoreTheme,
} from "@/interface/utils/themeStoreFlavours";
import browser from "@/lib/browser";
import ThemeModal from "../components/store/ThemeModal.svelte";
import { themeUpdates } from "../hooks/themeUpdates";
import { ThemeManager } from "@/plugins/built-in/themes/theme-manager";
import { loadBackground } from "@/seqta/ui/imageBackgrounds";
import Backgrounds from "../components/store/Backgrounds.svelte";
import { cloudAuth } from "@/seqta/utils/cloudAuth";
import SignInToFavoriteModal from "../components/SignInToFavoriteModal.svelte";
import { getStoreInstalledThemeIds } from "@/interface/utils/themeListFilters";
import { consumePendingHighlightThemeId } from "@/seqta/utils/openThemeStoreWithHighlight";
const themeManager = ThemeManager.getInstance();
type StoreTab = 'themes' | 'backgrounds';
type StoreTab = "themes" | "backgrounds";
let {
activeTab,
searchTerm,
@@ -38,7 +42,9 @@
let cloudLoggedIn = $state(cloudAuth.state.isLoggedIn);
$effect(() => {
const unsub = cloudAuth.subscribe((s) => { cloudLoggedIn = s.isLoggedIn; });
const unsub = cloudAuth.subscribe((s) => {
cloudLoggedIn = s.isLoggedIn;
});
return unsub;
});
@@ -52,9 +58,9 @@
let loading = $state(true);
let displayTheme = $state<Theme | null>(null);
let currentThemes = $state<string[]>([]);
let selectedThemeId = $state('');
let selectedThemeId = $state("");
let installedThemeColors = $state<Record<string, string>>({});
let error = $state<string | null>(null);
let fetchAttempt = $state(0);
let selectedBackground = $state<string | null>(null);
@@ -67,7 +73,15 @@
return Promise.race([
browser.runtime.sendMessage(message) as Promise<T>,
new Promise<T>((_, reject) => {
setTimeout(() => reject(new Error('Theme store request timed out — reload the SEQTA page after updating the extension.')), FETCH_MESSAGE_TIMEOUT_MS);
setTimeout(
() =>
reject(
new Error(
"Theme store request timed out — reload the SEQTA page after updating the extension.",
),
),
FETCH_MESSAGE_TIMEOUT_MS,
);
}),
]);
}
@@ -75,7 +89,7 @@
const fetchCurrentThemes = async () => {
const themes = await themeManager.getAvailableThemes();
currentThemes = getStoreInstalledThemeIds(themes);
selectedThemeId = themeManager.getSelectedThemeId() || '';
selectedThemeId = themeManager.getSelectedThemeId() || "";
installedThemeColors = Object.fromEntries(
themes
.filter((theme) => theme != null && theme.installedFromStore === true)
@@ -86,7 +100,7 @@
const setDisplayTheme = (theme: Theme | null) => {
displayTheme = theme;
};
/** Featured themes first; within each group, newest by `created_at` (API: Unix seconds). */
function compareStoreThemes(a: Theme, b: Theme): number {
const fa = a.featured === true ? 1 : 0;
@@ -102,16 +116,20 @@
if (!cloudLoggedIn) return;
const isFavorite = !theme.is_favorited;
const result = (await browser.runtime.sendMessage({
type: 'cloudFavorite',
type: "cloudFavorite",
themeId: theme.id,
action: isFavorite ? 'favorite' : 'unfavorite',
action: isFavorite ? "favorite" : "unfavorite",
})) as { success?: boolean };
if (result?.success) {
const delta = isFavorite ? 1 : -1;
themes = themes.map((t) =>
t.id === theme.id
? { ...t, is_favorited: isFavorite, favorite_count: Math.max(0, (t.favorite_count ?? 0) + delta) }
: t
? {
...t,
is_favorited: isFavorite,
favorite_count: Math.max(0, (t.favorite_count ?? 0) + delta),
}
: t,
);
if (displayTheme?.id === theme.id) {
displayTheme = {
@@ -135,10 +153,10 @@
data?: { themes: unknown[] };
error?: string;
}>({
type: 'fetchThemes',
type: "fetchThemes",
});
if (!data?.success || !Array.isArray(data?.data?.themes)) {
throw new Error(data?.error || 'Failed to fetch themes');
throw new Error(data?.error || "Failed to fetch themes");
}
themes = data.data.themes
.map((row) => normalizeStoreTheme(row as Record<string, unknown>))
@@ -147,13 +165,13 @@
error = null;
loading = false;
} catch (err) {
console.error('Failed to fetch themes', err);
console.error("Failed to fetch themes", err);
fetchAttempt += 1;
if (fetchAttempt >= MAX_FETCH_ATTEMPTS) {
error =
err instanceof Error
? err.message
: 'Could not load themes. Reload the SEQTA page, then open the store again.';
: "Could not load themes. Reload the SEQTA page, then open the store again.";
loading = false;
return;
}
@@ -162,24 +180,25 @@
};
function focusThemeById(themeId: string) {
const match = themes.find((t) => t.id === themeId)
?? themes.find((t) => t.flavours?.some((f) => f.id === themeId));
const match =
themes.find((t) => t.id === themeId) ??
themes.find((t) => t.flavours?.some((f) => f.id === themeId));
if (match) {
setActiveTab('themes');
setSearchTerm('');
setActiveTab("themes");
setSearchTerm("");
displayTheme = match;
}
}
function onHighlightThemeEvent(e: Event) {
const detail = (e as CustomEvent).detail;
if (detail?.themeId && typeof detail.themeId === 'string') {
if (detail?.themeId && typeof detail.themeId === "string") {
focusThemeById(detail.themeId);
}
}
onMount(() => {
window.addEventListener('bsplus:highlight-theme', onHighlightThemeEvent);
window.addEventListener("bsplus:highlight-theme", onHighlightThemeEvent);
themeUpdates.addListener(fetchCurrentThemes);
const load = async () => {
@@ -196,7 +215,7 @@
}
return () => {
window.removeEventListener('bsplus:highlight-theme', onHighlightThemeEvent);
window.removeEventListener("bsplus:highlight-theme", onHighlightThemeEvent);
themeUpdates.removeListener(fetchCurrentThemes);
};
});
@@ -205,8 +224,8 @@
let filteredThemes = $derived(
listThemes.filter((theme) => {
const q = searchTerm.toLowerCase();
const name = (theme.name ?? '').toLowerCase();
const description = (theme.description ?? '').toLowerCase();
const name = (theme.name ?? "").toLowerCase();
const description = (theme.description ?? "").toLowerCase();
return name.includes(q) || description.includes(q);
}),
);
@@ -225,7 +244,9 @@
await themeManager.setTheme(themeId);
themeUpdates.triggerUpdate();
await fetchCurrentThemes();
void browser.runtime.sendMessage({ type: 'cloudSettingsRequestDebouncedUpload' }).catch(() => {});
void browser.runtime
.sendMessage({ type: "cloudSettingsRequestDebouncedUpload" })
.catch(() => {});
}
async function removeThemeFromStore(themeId: string) {
@@ -238,7 +259,9 @@
await themeManager.setTheme(themeId);
selectedThemeId = themeId;
themeUpdates.triggerUpdate();
void browser.runtime.sendMessage({ type: 'cloudSettingsRequestDebouncedUpload' }).catch(() => {});
void browser.runtime
.sendMessage({ type: "cloudSettingsRequestDebouncedUpload" })
.catch(() => {});
}
$effect(() => {
@@ -265,10 +288,10 @@
</script>
<div class="relative flex h-full min-h-0 flex-col overflow-hidden text-zinc-900 dark:text-white">
<main class="min-h-0 flex-1 overflow-y-auto bg-zinc-50/80 dark:bg-zinc-900/40">
<div class={activeTab === 'backgrounds' ? 'h-full' : 'px-6 py-6 md:px-8 lg:px-10'}>
<!-- Loading State -->
{#if loading}
<main class="min-h-0 flex-1 overflow-y-auto bg-zinc-50/80 dark:bg-zinc-900/40">
<div class={activeTab === "backgrounds" ? "h-full" : "px-6 py-6 md:px-8 lg:px-10"}>
<!-- Loading State -->
{#if loading}
<div class="grid grid-cols-1 gap-4 py-12 mx-auto sm:grid-cols-2 lg:grid-cols-3">
{#each Array(6) as _, i (i)}
<SkeletonLoader width="100%" height="200px" />
@@ -276,10 +299,13 @@
</div>
{:else if error}
<div class="flex flex-col items-center justify-center py-24 text-center max-w-lg mx-auto">
<h2 class="text-2xl font-bold text-zinc-900 dark:text-zinc-100">Couldn&apos;t load themes</h2>
<h2 class="text-2xl font-bold text-zinc-900 dark:text-zinc-100">
Couldn&apos;t load themes
</h2>
<p class="mt-3 text-zinc-600 dark:text-zinc-300">{error}</p>
<p class="mt-2 text-sm text-zinc-500 dark:text-zinc-400">
After an extension update, reload your SEQTA tab so the new version can talk to the browser.
After an extension update, reload your SEQTA tab so the new version can talk to the
browser.
</p>
<button
type="button"
@@ -295,11 +321,11 @@
</div>
{:else}
<!-- Themes Tab Content -->
{#if activeTab === 'themes'}
{#if searchTerm === ''}
{#if activeTab === "themes"}
{#if searchTerm === ""}
<CoverSwiper slides={coverSlides} {setDisplayTheme} />
{/if}
<!-- ThemeGrid to display filtered themes -->
<ThemeGrid
themes={filteredThemes}
@@ -311,10 +337,10 @@
onRequestSignIn={() => (showSignInOverlay = true)}
installedThemeIds={currentThemes}
/>
{#if displayTheme}
<ThemeModal
currentThemes={currentThemes}
{currentThemes}
allThemes={listThemes}
allStoreThemeRows={themes}
theme={displayTheme}
@@ -329,7 +355,7 @@
if (displayTheme) await installThemeFromStore(themeId, displayTheme);
}}
onRemove={async (themeId: string) => {
console.debug('deleting theme', themeId);
console.debug("deleting theme", themeId);
await removeThemeFromStore(themeId);
}}
onApply={async (themeId: string) => {
@@ -337,16 +363,16 @@
}}
/>
{/if}
{:else if activeTab === 'backgrounds'}
{:else if activeTab === "backgrounds"}
<Backgrounds
{searchTerm}
selectedCategory={selectedBackgroundCategory}
onCategoriesChange={setBackgroundCategories}
/>
{/if}
{/if}
</div>
</main>
{/if}
</div>
</main>
{#if showSignInOverlay}
<SignInToFavoriteModal onClose={() => (showSignInOverlay = false)} />
+210 -165
View File
@@ -5,61 +5,58 @@
import CircleQuestionMarkIcon from "@lucide/svelte/icons/circle-question-mark";
import PlusIcon from "@lucide/svelte/icons/plus";
import XIcon from "@lucide/svelte/icons/x";
import { onMount } from 'svelte';
import { slide } from 'svelte/transition';
import { fade } from 'svelte/transition';
import { onMount } from "svelte";
import { slide } from "svelte/transition";
import { fade } from "svelte/transition";
import {
type LoadedCustomTheme,
shouldForceThemeAppearance,
} from '@/types/CustomThemes'
import { type LoadedCustomTheme, shouldForceThemeAppearance } from "@/types/customThemes";
import { settingsState } from '@/seqta/utils/listeners/SettingsState'
import { settingsState } from "@/seqta/utils/listeners/settingsState";
import Divider from '@/interface/components/themeCreator/divider.svelte'
import Switch from '@/interface/components/Switch.svelte'
import Button from '@/interface/components/Button.svelte'
import Slider from '@/interface/components/Slider.svelte'
import ColourPicker from '../components/ColourPicker.svelte'
import CodeEditor from '../components/CodeEditor.svelte'
import Divider from "@/interface/components/themeCreator/divider.svelte";
import Switch from "@/interface/components/Switch.svelte";
import Button from "@/interface/components/Button.svelte";
import Slider from "@/interface/components/Slider.svelte";
import ColourPicker from "../components/ColourPicker.svelte";
import CodeEditor from "../components/CodeEditor.svelte";
import {
handleImageUpload,
handleRemoveImage,
handleImageVariableChange,
} from '../utils/themeImageHandlers';
import { ThemeManager } from '@/plugins/built-in/themes/theme-manager'
import { themeUpdates } from '../hooks/ThemeUpdates'
import { CloseThemeCreator } from '@/plugins/built-in/themes/ThemeCreator'
import { submitLocalThemeToCommunity } from '@/seqta/utils/customThemes/submitLocalTheme'
import { formatCustomThemeApiError } from '@/seqta/utils/customThemes/apiErrors'
import { cloudAuth } from '@/seqta/utils/CloudAuth'
import MoonIcon from '@lucide/svelte/icons/moon'
import SunIcon from '@lucide/svelte/icons/sun'
import SidebarAppearance from '@/interface/components/SidebarAppearance.svelte'
import { FONT_PRESETS, DEFAULT_FONT_ID } from '@/seqta/ui/fonts/presets'
import { applySelectedFont, ensureFontPickerFontsLoaded } from '@/seqta/ui/fonts/Manager'
} from "../utils/themeImageHandlers";
import { ThemeManager } from "@/plugins/built-in/themes/theme-manager";
import { themeUpdates } from "../hooks/themeUpdates";
import { CloseThemeCreator } from "@/plugins/built-in/themes/themeCreator";
import { submitLocalThemeToCommunity } from "@/seqta/utils/customThemes/submitLocalTheme";
import { formatCustomThemeApiError } from "@/seqta/utils/customThemes/apiErrors";
import { cloudAuth } from "@/seqta/utils/cloudAuth";
import MoonIcon from "@lucide/svelte/icons/moon";
import SunIcon from "@lucide/svelte/icons/sun";
import SidebarAppearance from "@/interface/components/SidebarAppearance.svelte";
import { FONT_PRESETS, DEFAULT_FONT_ID } from "@/seqta/ui/fonts/presets";
import { applySelectedFont, ensureFontPickerFontsLoaded } from "@/seqta/ui/fonts/fontManager";
import {
applySidebarSettings,
defaultThemeCreatorMeta,
mergeThemeWithCreatorMeta,
snapshotSidebarSettings,
} from '@/interface/utils/themeCreatorMeta'
import { ensureThemeCoverImage } from '@/interface/utils/themePlaceholderCover'
import ThemeBlobImage from '@/interface/components/themes/ThemeBlobImage.svelte'
import type { ThemeCreatorMeta } from '@/types/CustomThemes'
} from "@/interface/utils/themeCreatorMeta";
import { ensureThemeCoverImage } from "@/interface/utils/themePlaceholderCover";
import ThemeBlobImage from "@/interface/components/themes/ThemeBlobImage.svelte";
import type { ThemeCreatorMeta } from "@/types/customThemes";
const { themeID }: { themeID: string } = $props()
const { themeID }: { themeID: string } = $props();
const themeManager = ThemeManager.getInstance();
let theme = $state<LoadedCustomTheme>({
id: crypto.randomUUID(),
name: '',
description: '',
defaultColour: 'blue',
name: "",
description: "",
defaultColour: "blue",
CanChangeColour: true,
allowBackgrounds: true,
CustomCSS: '',
CustomCSS: "",
CustomImages: [],
coverImage: null,
isEditable: true,
@@ -67,8 +64,8 @@
forceTheme: undefined,
forceDark: undefined,
adaptiveCssVariables: [],
})
let closedAccordions = $state<string[]>([])
});
let closedAccordions = $state<string[]>([]);
let themeLoaded = $state(false);
let codeEditorFullscreen = $state(false);
let communityBusy = $state(false);
@@ -94,27 +91,27 @@
composeVisuals = true;
}
function imageUsage(imageId: string): 'decorative' | 'page-background' | 'cover' {
if (creatorMeta.pageBackgroundImageId === imageId) return 'page-background';
function imageUsage(imageId: string): "decorative" | "page-background" | "cover" {
if (creatorMeta.pageBackgroundImageId === imageId) return "page-background";
const image = theme.CustomImages.find((item) => item.id === imageId);
if (image && theme.coverImage === image.blob) return 'cover';
return 'decorative';
if (image && theme.coverImage === image.blob) return "cover";
return "decorative";
}
function setImageUsage(imageId: string, usage: 'decorative' | 'page-background' | 'cover') {
function setImageUsage(imageId: string, usage: "decorative" | "page-background" | "cover") {
const image = theme.CustomImages.find((item) => item.id === imageId);
if (!image) return;
let nextMeta = { ...creatorMeta };
let coverImage = theme.coverImage;
if (usage === 'page-background') {
if (usage === "page-background") {
nextMeta = { ...nextMeta, pageBackgroundImageId: imageId };
} else if (nextMeta.pageBackgroundImageId === imageId) {
nextMeta = { ...nextMeta, pageBackgroundImageId: null };
}
if (usage === 'cover') {
if (usage === "cover") {
coverImage = image.blob;
} else if (coverImage === image.blob) {
coverImage = null;
@@ -143,12 +140,12 @@
function toggleAccordion(title: string, e: MouseEvent | KeyboardEvent) {
// if the target is the fullscreen button return
if (e.target instanceof Element && e.target.closest('.fullscreen-toggle')) {
if (e.target instanceof Element && e.target.closest(".fullscreen-toggle")) {
return;
}
if (closedAccordions.includes(title)) {
closedAccordions = closedAccordions.filter(t => t !== title);
closedAccordions = closedAccordions.filter((t) => t !== title);
} else {
closedAccordions = [...closedAccordions, title];
}
@@ -197,9 +194,7 @@
theme = {
...tempTheme,
adaptiveCssVariables: tempTheme.adaptiveCssVariables ?? [],
forceTheme:
tempTheme.forceTheme ??
(tempTheme.forceDark !== undefined ? true : undefined),
forceTheme: tempTheme.forceTheme ?? (tempTheme.forceDark !== undefined ? true : undefined),
};
}
@@ -283,13 +278,30 @@
void themeManager.updatePreviewDebounced(snapshot);
});
type SettingType = 'switch' | 'button' | 'slider' | 'select' | 'codeEditor' | 'imageUpload' | 'conditional' | 'lightDarkToggle';
type SettingType =
| "switch"
| "button"
| "slider"
| "select"
| "codeEditor"
| "imageUpload"
| "conditional"
| "lightDarkToggle";
type SwitchProps = { state: boolean; onChange: (value: boolean) => void };
type ButtonProps = { onClick: () => void; text: string };
type SliderProps = { state: number; onChange: (value: number) => void; min?: number; max?: number };
type SliderProps = {
state: number;
onChange: (value: number) => void;
min?: number;
max?: number;
};
type SelectProps = { options: Array<{ value: string; label: string }>; value: string; onChange: (value: string) => void };
type SelectProps = {
options: Array<{ value: string; label: string }>;
value: string;
onChange: (value: string) => void;
};
type CodeEditorProps = { value: string; onChange: (value: string) => void };
type LightDarkToggleProps = { state: boolean; onChange: (value: boolean) => void };
@@ -298,73 +310,107 @@
children: SettingItem;
};
type ComponentProps = SwitchProps | ButtonProps | SliderProps | SelectProps | CodeEditorProps | LightDarkToggleProps | ConditionalProps;
type ComponentProps =
| SwitchProps
| ButtonProps
| SliderProps
| SelectProps
| CodeEditorProps
| LightDarkToggleProps
| ConditionalProps;
type SettingItem = {
type: SettingType;
title: string;
description: string;
direction?: 'horizontal' | 'vertical';
direction?: "horizontal" | "vertical";
props: ComponentProps;
};
</script>
{#snippet settingItem(item: SettingItem)}
{#if item.type === 'conditional'}
{#if (item.props as ConditionalProps).condition }
{#if item.type === "conditional"}
{#if (item.props as ConditionalProps).condition}
<div transition:slide={{ duration: 300 }}>
{@render settingItem((item.props as ConditionalProps).children)}
</div>
{/if}
{:else}
<div class="flex justify-between {item.direction === 'vertical' ? 'flex-col items-start' : 'items-center'} py-3">
<div
class="flex justify-between {item.direction === 'vertical'
? 'flex-col items-start'
: 'items-center'} py-3"
>
<!-- svelte-ignore a11y_no_static_element_interactions -->
<div
onclick={(e) => { item.direction === 'vertical' && toggleAccordion(item.title, e) }}
onkeydown={(e) => { e.key === 'Enter' && item.direction === 'vertical' && toggleAccordion(item.title, e) }}
class="flex justify-between pr-4 {item.direction === 'vertical' ? 'cursor-pointer w-full select-none' : ''}">
onclick={(e) => {
item.direction === "vertical" && toggleAccordion(item.title, e);
}}
onkeydown={(e) => {
e.key === "Enter" && item.direction === "vertical" && toggleAccordion(item.title, e);
}}
class="flex justify-between pr-4 {item.direction === 'vertical'
? 'cursor-pointer w-full select-none'
: ''}"
>
<div>
<h2 class="text-sm font-bold">{item.title}</h2>
<p class="text-xs">{item.description}</p>
</div>
{#if item.direction === 'vertical'}
<div class="flex justify-center items-center h-full text-xl font-light text-zinc-500 dark:text-zinc-300">
{#if item.type === 'codeEditor'}
{#if item.direction === "vertical"}
<div
class="flex justify-center items-center h-full text-xl font-light text-zinc-500 dark:text-zinc-300"
>
{#if item.type === "codeEditor"}
<!-- Fullscreen toggle button -->
<button onclick={toggleCodeEditorFullscreen} class="px-2 mr-2 text-lg fullscreen-toggle" aria-label="Expand editor">
<Maximize2Icon size="1em" />
<button
onclick={toggleCodeEditorFullscreen}
class="px-2 mr-2 text-lg fullscreen-toggle"
aria-label="Expand editor"
>
<Maximize2Icon size="1em" />
</button>
{/if}
<ChevronDownIcon size="1em" class="transition-transform duration-300 {closedAccordions.includes(item.title) ? 'rotate-180' : ''}" />
<ChevronDownIcon
size="1em"
class="transition-transform duration-300 {closedAccordions.includes(item.title)
? 'rotate-180'
: ''}"
/>
</div>
{/if}
</div>
{#if !closedAccordions.includes(item.title)}
<div class="{item.direction === 'vertical' ? 'w-full mt-2' : ''}" transition:slide={{ duration: 300 }}>
{#if item.type === 'switch'}
<Switch {...(item.props as SwitchProps)} />
{:else if item.type === 'button'}
<Button {...(item.props as ButtonProps)} />
{:else if item.type === 'slider'}
<Slider {...(item.props as SliderProps)} />
{:else if item.type === 'codeEditor'}
<div
class={item.direction === "vertical" ? "w-full mt-2" : ""}
transition:slide={{ duration: 300 }}
>
{#if item.type === "switch"}
<Switch {...item.props as SwitchProps} />
{:else if item.type === "button"}
<Button {...item.props as ButtonProps} />
{:else if item.type === "slider"}
<Slider {...item.props as SliderProps} />
{:else if item.type === "codeEditor"}
{#if !codeEditorFullscreen}
{#key themeLoaded}
<!-- Only render inline if not fullscreen -->
<CodeEditor className="h-[400px]" {...(item.props as CodeEditorProps)} />
<CodeEditor className="h-[400px]" {...item.props as CodeEditorProps} />
{/key}
{/if}
{:else if item.type === 'imageUpload'}
{:else if item.type === "imageUpload"}
{#each theme.CustomImages as image (image.id)}
<div class="mb-4 space-y-2 rounded-lg bg-white px-2 py-2 shadow-lg dark:bg-zinc-700">
<div class="flex h-16 items-center gap-2">
<div class="h-full">
<ThemeBlobImage source={image.blob} alt={image.variableName} class="object-contain h-full rounded-sm" />
<ThemeBlobImage
source={image.blob}
alt={image.variableName}
class="object-contain h-full rounded-sm"
/>
</div>
<input
type="text"
@@ -373,7 +419,11 @@
placeholder="CSS variable name"
class="grow flex-3 rounded-lg border-0 bg-zinc-200 p-2 transition dark:bg-zinc-600/50 dark:placeholder-zinc-300 focus:bg-zinc-300/50 dark:focus:bg-zinc-600"
/>
<button onclick={() => onRemoveImage(image.id)} class="p-2 transition dark:text-white" type="button">
<button
onclick={() => onRemoveImage(image.id)}
class="p-2 transition dark:text-white"
type="button"
>
<XIcon size="1em" class="text-xl" />
</button>
</div>
@@ -383,7 +433,10 @@
class="mt-1 w-full rounded-lg border-0 bg-zinc-200 px-2 py-1.5 text-sm dark:bg-zinc-600"
value={imageUsage(image.id)}
onchange={(e) =>
setImageUsage(image.id, e.currentTarget.value as 'decorative' | 'page-background' | 'cover')}
setImageUsage(
image.id,
e.currentTarget.value as "decorative" | "page-background" | "cover",
)}
>
<option value="decorative">Decorative (CSS variable only)</option>
<option value="page-background">SEQTA page background</option>
@@ -392,16 +445,26 @@
</label>
</div>
{/each}
<div class="flex overflow-hidden relative gap-1 justify-center place-items-center w-full h-8 rounded-lg transition bg-zinc-200 dark:bg-zinc-700">
<PlusIcon size="1em" />
<span class='dark:text-white'>Add image</span>
<input type="file" accept='image/*' onchange={onImageUpload} class="absolute inset-0 w-full h-full opacity-0 cursor-pointer" />
<div
class="flex overflow-hidden relative gap-1 justify-center place-items-center w-full h-8 rounded-lg transition bg-zinc-200 dark:bg-zinc-700"
>
<PlusIcon size="1em" />
<span class="dark:text-white">Add image</span>
<input
type="file"
accept="image/*"
onchange={onImageUpload}
class="absolute inset-0 w-full h-full opacity-0 cursor-pointer"
/>
</div>
{:else if item.type === 'lightDarkToggle'}
{:else if item.type === "lightDarkToggle"}
<button
class="overflow-hidden relative flex justify-center items-center px-4 py-1 text-xl font-medium rounded-lg transition bg-zinc-200 dark:bg-zinc-700 hover:bg-zinc-300 dark:hover:bg-zinc-600"
onclick={() => (item.props as LightDarkToggleProps).onChange(!(item.props as LightDarkToggleProps).state)}
onclick={() =>
(item.props as LightDarkToggleProps).onChange(
!(item.props as LightDarkToggleProps).state,
)}
>
{#key (item.props as LightDarkToggleProps).state}
<span
@@ -431,7 +494,11 @@
<div class="sticky top-0 px-2 h-screen">
<div class="flex justify-between items-center my-4">
<h2 class="text-xl font-bold">Custom CSS</h2>
<button onclick={toggleCodeEditorFullscreen} class="pr-14 text-xl" aria-label="Collapse editor"><Minimize2Icon size="1em" /></button>
<button
onclick={toggleCodeEditorFullscreen}
class="pr-14 text-xl"
aria-label="Collapse editor"><Minimize2Icon size="1em" /></button
>
</div>
<CodeEditor
className="editorHeight"
@@ -441,8 +508,9 @@
</div>
</div>
{/if}
<div class="relative flex min-h-full w-full flex-col bg-zinc-100 p-2 text-zinc-900 dark:bg-zinc-800 dark:text-white">
<div
class="relative flex min-h-full w-full flex-col bg-zinc-100 p-2 text-zinc-900 dark:bg-zinc-800 dark:text-white"
>
<div class="mb-2 flex items-start justify-between gap-2">
<h1 class="text-xl font-semibold">Theme Creator</h1>
<button
@@ -454,39 +522,48 @@
<XIcon size="1em" />
</button>
</div>
<a href='https://docs.betterseqta.org/theme-creation/' target='_blank' rel='noopener noreferrer' class='text-sm font-light text-zinc-500 dark:text-zinc-400'>
<a
href="https://docs.betterseqta.org/theme-creation/"
target="_blank"
rel="noopener noreferrer"
class="text-sm font-light text-zinc-500 dark:text-zinc-400"
>
<CircleQuestionMarkIcon size="1em" class="pr-0.5" />
<span class='underline'>
Need help? Check out the docs!
</span>
<span class="underline"> Need help? Check out the docs! </span>
</a>
<Divider />
<div>
<div class='pb-2 text-sm'>Theme Name</div>
<div class="pb-2 text-sm">Theme Name</div>
<input
id='themeName'
type='text'
placeholder='What is your theme called?'
id="themeName"
type="text"
placeholder="What is your theme called?"
bind:value={theme.name}
class='p-2 mb-4 w-full rounded-lg border-0 transition dark:placeholder-zinc-300 bg-zinc-200 dark:bg-zinc-700 focus:bg-zinc-300/50 dark:focus:bg-zinc-600' />
class="p-2 mb-4 w-full rounded-lg border-0 transition dark:placeholder-zinc-300 bg-zinc-200 dark:bg-zinc-700 focus:bg-zinc-300/50 dark:focus:bg-zinc-600"
/>
</div>
<div>
<div class='pb-2 text-sm'>Description <span class='italic font-light opacity-80'>(optional)</span></div>
<div class="pb-2 text-sm">
Description <span class="italic font-light opacity-80">(optional)</span>
</div>
<textarea
id='themeDescription'
id="themeDescription"
placeholder="Don't worry, this one's optional!"
bind:value={theme.description}
class='p-2 w-full rounded-lg border-0 transition dark:placeholder-zinc-300 bg-zinc-200 dark:bg-zinc-700 focus:bg-zinc-300/50 dark:focus:bg-zinc-600'></textarea>
class="p-2 w-full rounded-lg border-0 transition dark:placeholder-zinc-300 bg-zinc-200 dark:bg-zinc-700 focus:bg-zinc-300/50 dark:focus:bg-zinc-600"
></textarea>
</div>
<Divider />
<div class="py-3">
<h2 class="text-sm font-bold">Accent colour</h2>
<p class="text-xs text-zinc-600 dark:text-zinc-400">Default accent and gradient start colour.</p>
<p class="text-xs text-zinc-600 dark:text-zinc-400">
Default accent and gradient start colour.
</p>
<div class="mt-2">
<ColourPicker
savePresets={false}
@@ -521,7 +598,8 @@
<div>
<h2 class="text-sm font-bold">Images &amp; page background</h2>
<p class="text-xs text-zinc-600 dark:text-zinc-400">
Upload images, then choose how each one is used. Set one as the live SEQTA page background to preview it on the main page.
Upload images, then choose how each one is used. Set one as the live SEQTA page background
to preview it on the main page.
</p>
</div>
@@ -536,7 +614,11 @@
placeholder="CSS variable"
class="min-w-0 flex-1 rounded-lg border-0 bg-zinc-100 p-2 text-sm dark:bg-zinc-600 dark:text-white"
/>
<button type="button" class="p-2 dark:text-white" onclick={() => onRemoveImage(image.id)}>
<button
type="button"
class="p-2 dark:text-white"
onclick={() => onRemoveImage(image.id)}
>
<XIcon size="1em" class="text-xl" />
</button>
</div>
@@ -544,7 +626,10 @@
class="w-full rounded-lg border-0 bg-zinc-100 px-2 py-1.5 text-sm dark:bg-zinc-600"
value={imageUsage(image.id)}
onchange={(e) =>
setImageUsage(image.id, e.currentTarget.value as 'decorative' | 'page-background' | 'cover')}
setImageUsage(
image.id,
e.currentTarget.value as "decorative" | "page-background" | "cover",
)}
>
<option value="decorative">Decorative only (CSS variable)</option>
<option value="page-background">SEQTA page background</option>
@@ -553,8 +638,10 @@
</div>
{/each}
<label class="flex h-10 cursor-pointer items-center justify-center gap-2 rounded-lg bg-zinc-200 dark:bg-zinc-700">
<PlusIcon size="1em" />
<label
class="flex h-10 cursor-pointer items-center justify-center gap-2 rounded-lg bg-zinc-200 dark:bg-zinc-700"
>
<PlusIcon size="1em" />
<span class="text-sm dark:text-white">Add image</span>
<input type="file" accept="image/*" class="hidden" onchange={onImageUpload} />
</label>
@@ -607,11 +694,14 @@
<div class="py-3">
<h2 class="text-sm font-bold">Adaptive CSS variables</h2>
<p class="text-xs text-zinc-600 dark:text-zinc-400">
One per line, each must start with <code class="text-xs">--</code>. These receive the same colour as the adaptive accent when &quot;Adaptive theme colour&quot; is enabled in general settings. Use them in Custom CSS, e.g. <code class="text-xs">border-color: var(--my-accent);</code>
One per line, each must start with <code class="text-xs">--</code>. These receive the same
colour as the adaptive accent when &quot;Adaptive theme colour&quot; is enabled in general
settings. Use them in Custom CSS, e.g.
<code class="text-xs">border-color: var(--my-accent);</code>
</p>
<textarea
placeholder="--my-accent&#10;--class-banner"
value={theme.adaptiveCssVariables?.join('\n') ?? ''}
value={theme.adaptiveCssVariables?.join("\n") ?? ""}
oninput={(e) => {
const lines = e.currentTarget.value
.split(/\r?\n/)
@@ -631,58 +721,13 @@
<Divider />
{#each [
{
type: 'switch',
title: 'Hide Theme Name',
description: 'Useful when your cover image contains text',
props: {
state: theme.hideThemeName,
onChange: (value: boolean) => theme = { ...theme, hideThemeName: value }
}
},
{
type: 'switch',
title: 'Force Theme',
description: 'Force users to use either dark or light mode',
props: {
state: shouldForceThemeAppearance(theme),
onChange: (value: boolean) => {
if (value) {
theme = { ...theme, forceTheme: true, forceDark: false };
} else {
theme = { ...theme, forceTheme: false, forceDark: undefined };
}
}
}
},
{
type: 'conditional',
props: {
condition: shouldForceThemeAppearance(theme),
children: {
type: 'lightDarkToggle',
title: 'Mode',
description: 'Choose whether to force light or dark mode',
props: {
state: theme.forceDark === true,
onChange: (value: boolean) =>
(theme = { ...theme, forceDark: value, forceTheme: true })
}
}
}
},
{
type: 'codeEditor',
title: 'Custom CSS',
description: 'Extra CSS appended after generated theme rules',
direction: 'vertical',
props: {
value: creatorMeta.userCustomCss,
onChange: (value: string) => patchCreatorMeta({ userCustomCss: value })
}
}
] as SettingItem[] as setting}
{#each [{ type: "switch", title: "Hide Theme Name", description: "Useful when your cover image contains text", props: { state: theme.hideThemeName, onChange: (value: boolean) => (theme = { ...theme, hideThemeName: value }) } }, { type: "switch", title: "Force Theme", description: "Force users to use either dark or light mode", props: { state: shouldForceThemeAppearance(theme), onChange: (value: boolean) => {
if (value) {
theme = { ...theme, forceTheme: true, forceDark: false };
} else {
theme = { ...theme, forceTheme: false, forceDark: undefined };
}
} } }, { type: "conditional", props: { condition: shouldForceThemeAppearance(theme), children: { type: "lightDarkToggle", title: "Mode", description: "Choose whether to force light or dark mode", props: { state: theme.forceDark === true, onChange: (value: boolean) => (theme = { ...theme, forceDark: value, forceTheme: true }) } } } }, { type: "codeEditor", title: "Custom CSS", description: "Extra CSS appended after generated theme rules", direction: "vertical", props: { value: creatorMeta.userCustomCss, onChange: (value: string) => patchCreatorMeta( { userCustomCss: value } ) } }] as SettingItem[] as setting}
{@render settingItem(setting)}
{/each}
@@ -714,4 +759,4 @@
{/if}
</div>
</div>
</div>
</div>
File renamed without changes.
File renamed without changes.
-67
View File
@@ -1,67 +0,0 @@
import { settingsState } from "@/seqta/utils/listeners/SettingsState";
const THEME_CSS_VARS = [
"--better-main",
"--better-pale",
"--better-light",
"--text-color",
"--background-primary",
"--background-secondary",
"--theme-primary",
"--theme-secondary",
"--text-primary",
"--theme-offset-bg",
"--better-sub",
] as const;
const ACCENT_CSS_VARS = [
"--better-main",
"--accent-color-value",
"--accentColor",
"--colour-betterseqta-blue",
] as const;
function extractSolidColor(value: string): string | null {
const trimmed = value.trim();
if (!trimmed || trimmed === "initial") return null;
if (trimmed.startsWith("#") || trimmed.startsWith("rgb") || trimmed.startsWith("hsl")) {
return trimmed;
}
if (trimmed.includes("gradient")) {
const match = trimmed.match(/#[0-9A-Fa-f]{6}|#[0-9A-Fa-f]{3}|rgba?\([^)]+\)/i);
return match?.[0] ?? null;
}
return null;
}
function resolvePageAccentColor(): string {
const computed = getComputedStyle(document.documentElement);
for (const name of ACCENT_CSS_VARS) {
const solid = extractSolidColor(computed.getPropertyValue(name));
if (solid) return solid;
}
const fromSettings = settingsState.selectedColor?.trim();
if (fromSettings) {
const solid = extractSolidColor(fromSettings);
if (solid) return solid;
}
return "#007bff";
}
/** Copy SEQTA page theme tokens onto a portaled UI root (matches analytics sync). */
export function syncPageThemeToElement(target: HTMLElement): void {
const computed = getComputedStyle(document.documentElement);
for (const name of THEME_CSS_VARS) {
const value = computed.getPropertyValue(name).trim();
if (value) {
target.style.setProperty(name, value);
}
}
const accent = resolvePageAccentColor();
target.style.setProperty("--bsplus-analytics-accent", accent);
target.style.setProperty("--better-main", accent);
target.classList.toggle("dark", document.documentElement.classList.contains("dark"));
}
+1 -1
View File
@@ -1,5 +1,5 @@
import { DEFAULT_FONT_ID, getFontPreset, type FontPreset } from "@/seqta/ui/fonts/presets";
import type { LoadedCustomTheme } from "@/types/CustomThemes";
import type { LoadedCustomTheme } from "@/types/customThemes";
export type ThemeBuilderDraft = {
name: string;
+3 -3
View File
@@ -1,8 +1,8 @@
import { buildThemeBuilderCss } from "@/interface/utils/themeBuilderDraft";
import { applySelectedFont } from "@/seqta/ui/fonts/Manager";
import { applySelectedFont } from "@/seqta/ui/fonts/fontManager";
import { DEFAULT_FONT_ID, getFontPreset } from "@/seqta/ui/fonts/presets";
import { settingsState } from "@/seqta/utils/listeners/SettingsState";
import type { LoadedCustomTheme, ThemeCreatorMeta } from "@/types/CustomThemes";
import { settingsState } from "@/seqta/utils/listeners/settingsState";
import type { LoadedCustomTheme, ThemeCreatorMeta } from "@/types/customThemes";
export type ThemeCreatorSidebarMeta = {
sidebarStyle?: string;
+1 -1
View File
@@ -1,4 +1,4 @@
import type { LoadedCustomTheme } from "@/types/CustomThemes";
import type { LoadedCustomTheme } from "@/types/customThemes";
export function handleImageUpload(event: Event, theme: LoadedCustomTheme): LoadedCustomTheme {
const input = event.target as HTMLInputElement;
+2 -2
View File
@@ -1,5 +1,5 @@
import type { CustomTheme } from "@/types/CustomThemes";
import type { Theme } from "@/interface/types/Theme";
import type { CustomTheme } from "@/types/customThemes";
import type { Theme } from "@/interface/types/theme";
import {
getThemeApplyButtonStyles,
getCommunityInstalledThemeIds,
+2 -2
View File
@@ -1,5 +1,5 @@
import type { CustomTheme } from "@/types/CustomThemes";
import type { Theme } from "@/interface/types/Theme";
import type { CustomTheme } from "@/types/customThemes";
import type { Theme } from "@/interface/types/theme";
import { parseCssColor } from "@/seqta/ui/colors/parseCssColor";
const DEFAULT_THEME_ACCENT = "rgba(0, 123, 255, 1)";
+1 -1
View File
@@ -1,4 +1,4 @@
import type { LoadedCustomTheme } from "@/types/CustomThemes";
import type { LoadedCustomTheme } from "@/types/customThemes";
/** SVG cover used when a theme has no store/community cover image. */
export function createDefaultThemeCoverSvg(accentHint = "#52525b"): string {
+1 -1
View File
@@ -1,4 +1,4 @@
import type { Theme, ThemeCoverSlide, ThemeFlavour } from "@/interface/types/Theme";
import type { Theme, ThemeCoverSlide, ThemeFlavour } from "@/interface/types/theme";
export function isHiddenStoreTheme(theme: Theme): boolean {
return theme.theme_role === "slave";
@@ -7,7 +7,7 @@
getThermoscorePercent,
readStoredList,
} from "./utils";
import { settingsState } from "@/seqta/utils/listeners/SettingsState";
import { settingsState } from "@/seqta/utils/listeners/settingsState";
import { isSeqtaEngageExperience } from "@/seqta/utils/isSeqtaEngage";
import { buildEngageAssessmentPagePath } from "@/seqta/utils/engageAssessmentStudent";
import CalendarDaysIcon from "@lucide/svelte/icons/calendar-days";
@@ -41,11 +41,36 @@
const COMPLETED_ASSESSMENTS_KEY = "betterseqta-completed-assessments";
const STATUS_COLUMNS: Column[] = [
{ key: "UPCOMING", title: "Upcoming", className: "column-upcoming", icon: STATUS_COLUMN_ICONS.UPCOMING },
{ key: "DUE_SOON", title: "Due Soon", className: "column-due-soon", icon: STATUS_COLUMN_ICONS.DUE_SOON },
{ key: "OVERDUE", title: "Overdue", className: "column-overdue", icon: STATUS_COLUMN_ICONS.OVERDUE },
{ key: "SUBMITTED", title: "Submitted", className: "column-submitted", icon: STATUS_COLUMN_ICONS.SUBMITTED },
{ key: "MARKS_RELEASED", title: "Marked", className: "column-marked", icon: STATUS_COLUMN_ICONS.MARKS_RELEASED },
{
key: "UPCOMING",
title: "Upcoming",
className: "column-upcoming",
icon: STATUS_COLUMN_ICONS.UPCOMING,
},
{
key: "DUE_SOON",
title: "Due Soon",
className: "column-due-soon",
icon: STATUS_COLUMN_ICONS.DUE_SOON,
},
{
key: "OVERDUE",
title: "Overdue",
className: "column-overdue",
icon: STATUS_COLUMN_ICONS.OVERDUE,
},
{
key: "SUBMITTED",
title: "Submitted",
className: "column-submitted",
icon: STATUS_COLUMN_ICONS.SUBMITTED,
},
{
key: "MARKS_RELEASED",
title: "Marked",
className: "column-marked",
icon: STATUS_COLUMN_ICONS.MARKS_RELEASED,
},
];
const isEngage = isSeqtaEngageExperience();
@@ -147,7 +172,11 @@
if (hiddenIds.includes(String(a.id))) return false;
if (subjectFilters[a.code] === false) return false;
if (currentFilters.subject !== "all" && a.code !== currentFilters.subject) return false;
if (isEngage && currentFilters.student !== "all" && String(a.studentId) !== currentFilters.student) {
if (
isEngage &&
currentFilters.student !== "all" &&
String(a.studentId) !== currentFilters.student
) {
return false;
}
return true;
@@ -231,7 +260,15 @@
if (overdueCount === 0 && dueSoonCount === 0) {
setTimeout(() => {
const end = Date.now() + 100;
const side = { particleCount: 17, spread: 65, startVelocity: 40, scalar: 2, gravity: 2, decay: 0.97, ticks: 300 };
const side = {
particleCount: 17,
spread: 65,
startVelocity: 40,
scalar: 2,
gravity: 2,
decay: 0.97,
ticks: 300,
};
const frame = () => {
fireConfetti({ ...side, angle: 60, drift: 0.8, origin: { x: 0, y: 1 } });
fireConfetti({ ...side, angle: 120, drift: -0.8, origin: { x: 1, y: 1 } });
@@ -297,7 +334,11 @@
<option value={subject.code}>{subject.code} - {subject.title}</option>
{/each}
</select>
<select class="filter-select" bind:value={currentFilters.sortBy} title="Group by - columns change based on this">
<select
class="filter-select"
bind:value={currentFilters.sortBy}
title="Group by - columns change based on this"
>
<option value="due">Group: Status</option>
<option value="year">Group: Year</option>
<option value="subject">Group: Subject</option>
@@ -328,7 +369,10 @@
{#each hiddenSubjects as subject}
<span class="visibility-chip">
{subject.code}
<button class="visibility-unhide" onclick={() => setSubjectVisible(subject.code, true)}>Show</button>
<button
class="visibility-unhide"
onclick={() => setSubjectVisible(subject.code, true)}>Show</button
>
</span>
{/each}
</div>
@@ -341,7 +385,9 @@
{#each hiddenAssessmentsWithInfo as assessment}
<span class="visibility-chip">
{assessment.title}
<button class="visibility-unhide" onclick={() => unhideAssessment(assessment.id)}>Show</button>
<button class="visibility-unhide" onclick={() => unhideAssessment(assessment.id)}
>Show</button
>
</span>
{/each}
</div>
@@ -364,12 +410,12 @@
<div class="kanban-column {column.className}">
<div class="column-header">
<div class="column-title">
<span class="column-title-main">
<column.icon size={18} class="bsplus-overview-icon" />
{column.title}
</span>
<span class="column-count">{board.statusGroups[column.key].length}</span>
</div>
<span class="column-title-main">
<column.icon size={18} class="bsplus-overview-icon" />
{column.title}
</span>
<span class="column-count">{board.statusGroups[column.key].length}</span>
</div>
</div>
<div class="column-cards" id="{column.key.toLowerCase()}-cards">
{#each board.statusGroups[column.key] as assessment}
@@ -377,7 +423,7 @@
{@const dueDateClass = getDueDateClass(assessment)}
{@const isCompleted = completedIds.includes(assessment.id)}
{@const color = data.colors[assessment.code] || "#6366f1"}
<div
<div
class="assessment-card"
data-subject={assessment.code}
data-status={status}
@@ -385,7 +431,7 @@
onclick={(e) => handleCardClick(assessment, e)}
role="button"
tabindex="0"
onkeydown={(e) => e.key === 'Enter' && handleCardClick(assessment, e)}
onkeydown={(e) => e.key === "Enter" && handleCardClick(assessment, e)}
>
<div class="card-labels">
{#if isEngage && assessment.studentName}
@@ -393,37 +439,58 @@
{/if}
<span class="card-label label-subject">{assessment.code}</span>
{#if assessment.submitted}
<span class="card-label label-submitted" style="background: #10b981; color: white;">Submitted</span>
<span
class="card-label label-submitted"
style="background: #10b981; color: white;">Submitted</span
>
{/if}
{#if isCompleted && status === "MARKS_RELEASED" && !assessmentHasGradeDisplay(assessment)}
<span class="card-label label-completed" style="background: #059669; color: white;">Completed</span>
<span
class="card-label label-completed"
style="background: #059669; color: white;">Completed</span
>
{/if}
</div>
{#if status !== "MARKS_RELEASED" || isCompleted}
<div class="card-menu">
<button
class="menu-button"
<button
class="menu-button"
data-assessment-id={assessment.id}
onclick={(e) => toggleMenu(assessment.id, e)}
aria-label="Open menu"
>
<EllipsisVerticalIcon size={16} class="bsplus-overview-icon" />
</button>
<div class="menu-dropdown" style="display: {openMenuId === assessment.id ? 'block' : 'none'};">
<div
class="menu-dropdown"
style="display: {openMenuId === assessment.id ? 'block' : 'none'};"
>
{#if status !== "MARKS_RELEASED"}
<button class="menu-item mark-completed" onclick={() => markAssessmentCompleted(assessment)}>
<button
class="menu-item mark-completed"
onclick={() => markAssessmentCompleted(assessment)}
>
Mark as Completed
</button>
{:else if isCompleted}
<button class="menu-item mark-not-completed" onclick={() => unmarkAssessmentCompleted(assessment)}>
<button
class="menu-item mark-not-completed"
onclick={() => unmarkAssessmentCompleted(assessment)}
>
Mark as Not Complete
</button>
{/if}
<button class="menu-item menu-item-hide" onclick={() => hideAssessment(assessment)}>
<button
class="menu-item menu-item-hide"
onclick={() => hideAssessment(assessment)}
>
Hide assessment
</button>
<button class="menu-item menu-item-hide" onclick={() => hideSubject(assessment.code)}>
<button
class="menu-item menu-item-hide"
onclick={() => hideSubject(assessment.code)}
>
Hide subject ({assessment.code})
</button>
</div>
@@ -436,7 +503,10 @@
<div class="assessment-meta">
<div class="due-date {dueDateClass}">
<CalendarDaysIcon size={14} class="bsplus-overview-icon" />
{formatDate(assessment.due || assessment.date || assessment.dueDate || "", assessment.submitted)}
{formatDate(
assessment.due || assessment.date || assessment.dueDate || "",
assessment.submitted,
)}
</div>
</div>
{/if}
@@ -445,7 +515,10 @@
{@const gradeLabel = getDisplayGrade(assessment, isLetterGradeMode())}
{@const barPercent = getThermoscorePercent(assessment) ?? 0}
<div class="card-footer">
<div class="Thermoscore__Thermoscore___WFpL3" style="--fill-colour: {color}">
<div
class="Thermoscore__Thermoscore___WFpL3"
style="--fill-colour: {color}"
>
<div style="width: {barPercent}%" class="Thermoscore__fill___ojxDI">
<div title={gradeLabel} class="Thermoscore__text___XSR_M">
{gradeLabel}
@@ -8,10 +8,34 @@
icon: OverviewIcon;
skeletonCount: number;
}[] = [
{ key: "UPCOMING", title: "Upcoming", className: "column-upcoming", icon: STATUS_COLUMN_ICONS.UPCOMING, skeletonCount: 3 },
{ key: "DUE_SOON", title: "Due Soon", className: "column-due-soon", icon: STATUS_COLUMN_ICONS.DUE_SOON, skeletonCount: 2 },
{ key: "OVERDUE", title: "Overdue", className: "column-overdue", icon: STATUS_COLUMN_ICONS.OVERDUE, skeletonCount: 1 },
{ key: "MARKS_RELEASED", title: "Marked", className: "column-marked", icon: STATUS_COLUMN_ICONS.MARKS_RELEASED, skeletonCount: 4 },
{
key: "UPCOMING",
title: "Upcoming",
className: "column-upcoming",
icon: STATUS_COLUMN_ICONS.UPCOMING,
skeletonCount: 3,
},
{
key: "DUE_SOON",
title: "Due Soon",
className: "column-due-soon",
icon: STATUS_COLUMN_ICONS.DUE_SOON,
skeletonCount: 2,
},
{
key: "OVERDUE",
title: "Overdue",
className: "column-overdue",
icon: STATUS_COLUMN_ICONS.OVERDUE,
skeletonCount: 1,
},
{
key: "MARKS_RELEASED",
title: "Marked",
className: "column-marked",
icon: STATUS_COLUMN_ICONS.MARKS_RELEASED,
skeletonCount: 4,
},
];
</script>
@@ -12,7 +12,7 @@ interface PrefItem {
}
import { getUserInfo } from "@/seqta/utils/userInfo";
import { settingsState } from "@/seqta/utils/listeners/SettingsState";
import { settingsState } from "@/seqta/utils/listeners/settingsState";
import { getMockAssessmentsData } from "@/seqta/ui/dev/hideSensitiveContent";
import { isSeqtaEngageExperience } from "@/seqta/utils/isSeqtaEngage";
import { getEngageAssessmentsData } from "./engageApi";
@@ -45,6 +45,12 @@
}
}
.bsplus-overview-static,
.bsplus-overview-static * {
animation: none !important;
transition: none !important;
}
.bsplus-overview-delay-1 {
animation-delay: 80ms;
}
+7 -57
View File
@@ -1,11 +1,12 @@
import renderSvelte from "@/interface/main";
import { getAssessmentsData } from "./api";
import { settingsState } from "@/seqta/utils/listeners/SettingsState";
import { settingsState } from "@/seqta/utils/listeners/settingsState";
import AssessmentsOverview from "./AssessmentsOverview.svelte";
import SkeletonLoader from "./SkeletonLoader.svelte";
import ErrorState from "./ErrorState.svelte";
import { unmount } from "svelte";
import { toMountableComponent } from "@/types/mountableComponent";
import { copyPageTheme, resolvePageAccentColor } from "@/seqta/ui/colors/pageTheme";
let currentApp: ReturnType<typeof renderSvelte> | null = null;
let themeObserver: MutationObserver | null = null;
@@ -14,69 +15,17 @@ type ThemeSettingKey =
| "DarkMode"
| "adaptiveThemeColour"
| "adaptiveThemeGradient"
| "selectedTheme";
| "selectedTheme"
| "animations";
let themeListeners: Array<{ key: ThemeSettingKey; listener: () => void }> = [];
const THEME_CSS_VARS = [
"--better-main",
"--better-pale",
"--better-light",
"--text-color",
"--background-primary",
"--background-secondary",
"--text-primary",
"--theme-offset-bg",
"--better-sub",
] as const;
const ACCENT_CSS_VARS = [
"--better-main",
"--accent-color-value",
"--accentColor",
"--colour-betterseqta-blue",
] as const;
function extractSolidColor(value: string): string | null {
const trimmed = value.trim();
if (!trimmed || trimmed === "initial") return null;
if (trimmed.startsWith("#") || trimmed.startsWith("rgb") || trimmed.startsWith("hsl")) {
return trimmed;
}
if (trimmed.includes("gradient")) {
const match = trimmed.match(/#[0-9A-Fa-f]{6}|#[0-9A-Fa-f]{3}|rgba?\([^)]+\)/i);
return match?.[0] ?? null;
}
return null;
}
function resolvePageAccentColor(): string {
const computed = getComputedStyle(document.documentElement);
for (const name of ACCENT_CSS_VARS) {
const solid = extractSolidColor(computed.getPropertyValue(name));
if (solid) return solid;
}
const fromSettings = settingsState.selectedColor?.trim();
if (fromSettings) {
const solid = extractSolidColor(fromSettings);
if (solid) return solid;
}
return "#007bff";
}
function syncOverviewTheme(target: HTMLElement) {
const computed = getComputedStyle(document.documentElement);
for (const name of THEME_CSS_VARS) {
const value =
document.documentElement.style.getPropertyValue(name).trim() ||
computed.getPropertyValue(name).trim();
if (value) target.style.setProperty(name, value);
}
copyPageTheme(target);
const accent = resolvePageAccentColor();
target.style.setProperty("--bsplus-overview-accent", accent);
target.style.setProperty("--better-main", accent);
target.classList.toggle("dark", document.documentElement.classList.contains("dark"));
target.classList.toggle("bsplus-overview-static", !settingsState.animations);
}
function watchOverviewTheme(root: HTMLElement) {
@@ -92,6 +41,7 @@ function watchOverviewTheme(root: HTMLElement) {
"adaptiveThemeColour",
"adaptiveThemeGradient",
"selectedTheme",
"animations",
] satisfies ThemeSettingKey[]) {
settingsState.register(key, listener);
themeListeners.push({ key, listener });
@@ -129,24 +129,6 @@ export function filterAssessmentsForActiveSubjects<T extends Record<string, unkn
);
}
/** Active subjects that have at least one assessment in the given list. */
export function subjectsWithUpcomingAssessments(
assessments: Record<string, unknown>[],
activeSubjects: OverviewSubject[],
): OverviewSubject[] {
const result: OverviewSubject[] = [];
const seen = new Set<string>();
for (const assessment of assessments) {
const subject = activeSubjectForAssessment(assessment, activeSubjects);
if (!subject || seen.has(subject.code)) continue;
seen.add(subject.code);
result.push(subject);
}
return result;
}
export function formatDate(dateStr: string, submitted?: boolean): string {
const d = new Date(dateStr);
const now = new Date();
@@ -1,90 +1,102 @@
<script lang="ts">
import UploadIcon from "@lucide/svelte/icons/upload";
import localforage from 'localforage'
import { onMount } from 'svelte'
import localforage from "localforage";
import { onMount } from "svelte";
let fileInput = $state<HTMLInputElement | undefined>(undefined)
let dragging = $state(false)
let filename = $state<string | undefined>(undefined)
let durationText = $state<string | undefined>(undefined)
let fileInput = $state<HTMLInputElement | undefined>(undefined);
let dragging = $state(false);
let filename = $state<string | undefined>(undefined);
let durationText = $state<string | undefined>(undefined);
const store = localforage.createInstance({
name: 'background-music-store',
storeName: 'music',
})
name: "background-music-store",
storeName: "music",
});
async function loadExisting() {
const name = await store.getItem<string>('audio-name')
filename = name ?? undefined
const name = await store.getItem<string>("audio-name");
filename = name ?? undefined;
}
onMount(() => { loadExisting() })
onMount(() => {
loadExisting();
});
function triggerSelect() { fileInput?.click() }
function triggerSelect() {
fileInput?.click();
}
async function handleFiles(files: FileList | null) {
const file = files?.[0]
if (!file) return
const isSupported = file.type === 'audio/wav' || file.type === 'audio/mpeg' ||
file.name.toLowerCase().endsWith('.wav') || file.name.toLowerCase().endsWith('.mp3')
const file = files?.[0];
if (!file) return;
const isSupported =
file.type === "audio/wav" ||
file.type === "audio/mpeg" ||
file.name.toLowerCase().endsWith(".wav") ||
file.name.toLowerCase().endsWith(".mp3");
if (!isSupported) {
alert('Please select a .wav or .mp3 audio file')
return
alert("Please select a .wav or .mp3 audio file");
return;
}
await store.setItem('audio-blob', file)
await store.setItem('audio-name', file.name)
filename = file.name
await store.setItem("audio-blob", file);
await store.setItem("audio-name", file.name);
filename = file.name;
try {
const url = URL.createObjectURL(file)
const audio = new Audio(url)
const url = URL.createObjectURL(file);
const audio = new Audio(url);
await new Promise<void>((resolve, reject) => {
audio.onloadedmetadata = () => resolve()
audio.onerror = () => reject()
})
audio.onloadedmetadata = () => resolve();
audio.onerror = () => reject();
});
if (!isNaN(audio.duration) && audio.duration !== Infinity) {
const minutes = Math.floor(audio.duration / 60)
const seconds = Math.round(audio.duration % 60)
durationText = `${minutes}:${seconds.toString().padStart(2, '0')}`
const minutes = Math.floor(audio.duration / 60);
const seconds = Math.round(audio.duration % 60);
durationText = `${minutes}:${seconds.toString().padStart(2, "0")}`;
} else {
durationText = undefined
durationText = undefined;
}
URL.revokeObjectURL(url)
URL.revokeObjectURL(url);
} catch {
durationText = undefined
durationText = undefined;
}
window.dispatchEvent(new Event('betterseqta-background-music-updated'))
window.dispatchEvent(new Event("betterseqta-background-music-updated"));
}
function onFileChange() { handleFiles(fileInput?.files || null) }
function onFileChange() {
handleFiles(fileInput?.files || null);
}
function onDrop(event: DragEvent) {
event.preventDefault()
dragging = false
handleFiles(event.dataTransfer?.files || null)
event.preventDefault();
dragging = false;
handleFiles(event.dataTransfer?.files || null);
}
async function removeAudio() {
await store.removeItem('audio-blob')
await store.removeItem('audio-name')
filename = undefined
durationText = undefined
window.dispatchEvent(new Event('betterseqta-background-music-stop'))
await store.removeItem("audio-blob");
await store.removeItem("audio-name");
filename = undefined;
durationText = undefined;
window.dispatchEvent(new Event("betterseqta-background-music-stop"));
}
</script>
<div
class="relative cursor-pointer select-none"
onclick={() => triggerSelect()}
ondragover={(e) => { e.stopPropagation(); dragging = true }}
ondragleave={() => dragging = false}
ondragover={(e) => {
e.stopPropagation();
dragging = true;
}}
ondragleave={() => (dragging = false)}
ondrop={onDrop}
onkeydown={(e) => {
if (e.key === 'Enter' || e.key === ' ') {
e.preventDefault()
triggerSelect()
if (e.key === "Enter" || e.key === " ") {
e.preventDefault();
triggerSelect();
}
}}
role="button"
@@ -99,21 +111,30 @@
</div>
<button
class="flex justify-center items-center m-1 text-lg dark:text-white size-7"
onclick={(e) => { e.stopPropagation(); removeAudio() }}
aria-label="Remove audio"
>&#215;</button>
onclick={(e) => {
e.stopPropagation();
removeAudio();
}}
aria-label="Remove audio">&#215;</button
>
</div>
{:else}
<div class="flex gap-2 items-center px-3 py-1 text-xs rounded-lg border border-dashed transition border-zinc-300 dark:border-zinc-600 text-zinc-500 dark:text-zinc-400 hover:text-zinc-700 dark:hover:text-zinc-300 text-nowrap">
<div
class="flex gap-2 items-center px-3 py-1 text-xs rounded-lg border border-dashed transition border-zinc-300 dark:border-zinc-600 text-zinc-500 dark:text-zinc-400 hover:text-zinc-700 dark:hover:text-zinc-300 text-nowrap"
>
<UploadIcon size="1em" class="text-lg" />
<span>Upload audio</span>
</div>
{/if}
</div>
<input type="file" accept="audio/wav,audio/mpeg" class="hidden" bind:this={fileInput} onchange={onFileChange} />
<input
type="file"
accept="audio/wav,audio/mpeg"
class="hidden"
bind:this={fileInput}
onchange={onFileChange}
/>
{#if dragging}
<div class="absolute inset-0 rounded-lg bg-zinc-200/40 dark:bg-zinc-700/40"></div>
{/if}
</div>
@@ -1,10 +1,10 @@
<script lang="ts">
import ArrowRightIcon from "@lucide/svelte/icons/arrow-right";
import { onDestroy } from 'svelte';
import { calculateExpression } from '../utils/calculator';
import { onDestroy } from "svelte";
import { calculateExpression } from "../utils/calculator";
let {
searchTerm = '',
searchTerm = "",
isSelected = false,
onresult,
}: {
@@ -15,10 +15,10 @@
let result = $state<string | null>(null);
let isCalculating = $state(false);
let inputUnit = $state<string>('');
let outputUnit = $state<string>('');
let inputUnit = $state<string>("");
let outputUnit = $state<string>("");
let isPartial = $state(false);
let calcGen = 0;
const processInput = async (input: string) => {
@@ -37,16 +37,16 @@
onresult(calcResult.result);
} else {
result = null;
inputUnit = '';
outputUnit = '';
inputUnit = "";
outputUnit = "";
isPartial = false;
onresult(null);
}
} catch {
if (gen !== calcGen) return;
result = null;
inputUnit = '';
outputUnit = '';
inputUnit = "";
outputUnit = "";
isPartial = false;
onresult(null);
} finally {
@@ -57,47 +57,65 @@
$effect(() => {
void processInput(searchTerm);
});
onDestroy(() => {
onresult(null);
});
</script>
{#if result !== null}
<div class="">
<p class="text-[0.85rem] p-1 pb-0.5 pt-0 font-semibold text-zinc-500 dark:text-zinc-400">Calculator</p>
<div class="flex items-center justify-between gap-8 rounded-lg border border-transparent {isSelected ? 'bg-zinc-900/5 dark:bg-white/10 border-zinc-900/5 dark:border-zinc-100/5' : ''}">
<div class="flex flex-col flex-1 items-center py-4 pl-4 min-w-0">
<div class="overflow-hidden py-2 w-full font-semibold text-center whitespace-nowrap text-zinc-900 dark:text-white text-ellipsis"
style="--char-count: {searchTerm?.length || 10}; font-size: min(2.5rem, max(1rem, calc(35vw / var(--char-count, 10))))">
{searchTerm}
</div>
<div class="px-3 py-1 mt-1 text-sm rounded-md text-zinc-900 dark:text-zinc-300 bg-zinc-100 dark:bg-zinc-100/10">
{inputUnit || 'Question'}
</div>
</div>
<div class="flex flex-col shrink-0 justify-center items-center w-12">
<div class="h-8 w-px bg-zinc-900/5 dark:bg-zinc-100/5"></div>
<div class="text-2xl text-zinc-900 dark:text-zinc-100">
<ArrowRightIcon size="1em" />
</div>
<div class="h-8 w-px bg-zinc-900/5 dark:bg-zinc-100/5"></div>
</div>
{#if !isCalculating}
<div class="flex flex-col flex-1 items-center py-4 pr-4 min-w-0">
<div class="overflow-hidden py-2 w-full font-semibold text-center whitespace-nowrap text-zinc-900 dark:text-white text-ellipsis"
style="--char-count: {result?.length || 10}; font-size: min(2.5rem, max(1rem, calc(30vw / var(--char-count, 10))))">
{result}
<div class="">
<p class="text-[0.85rem] p-1 pb-0.5 pt-0 font-semibold text-zinc-500 dark:text-zinc-400">
Calculator
</p>
<div
class="flex items-center justify-between gap-8 rounded-lg border border-transparent {isSelected
? 'bg-zinc-900/5 dark:bg-white/10 border-zinc-900/5 dark:border-zinc-100/5'
: ''}"
>
<div class="flex flex-col flex-1 items-center py-4 pl-4 min-w-0">
<div
class="overflow-hidden py-2 w-full font-semibold text-center whitespace-nowrap text-zinc-900 dark:text-white text-ellipsis"
style="--char-count: {searchTerm?.length ||
10}; font-size: min(2.5rem, max(1rem, calc(35vw / var(--char-count, 10))))"
>
{searchTerm}
</div>
<div class="px-3 py-1 mt-1 text-sm rounded-md text-zinc-900 dark:text-zinc-300 bg-zinc-100 dark:bg-zinc-100/10">
{outputUnit || (isPartial ? 'Partial' : 'Result')}
<div
class="px-3 py-1 mt-1 text-sm rounded-md text-zinc-900 dark:text-zinc-300 bg-zinc-100 dark:bg-zinc-100/10"
>
{inputUnit || "Question"}
</div>
</div>
{:else}
<div class="w-6 h-6 rounded-full border-2 animate-spin border-zinc-300 dark:border-zinc-700 border-t-zinc-600 dark:border-t-zinc-300"></div>
{/if}
<div class="flex flex-col shrink-0 justify-center items-center w-12">
<div class="h-8 w-px bg-zinc-900/5 dark:bg-zinc-100/5"></div>
<div class="text-2xl text-zinc-900 dark:text-zinc-100">
<ArrowRightIcon size="1em" />
</div>
<div class="h-8 w-px bg-zinc-900/5 dark:bg-zinc-100/5"></div>
</div>
{#if !isCalculating}
<div class="flex flex-col flex-1 items-center py-4 pr-4 min-w-0">
<div
class="overflow-hidden py-2 w-full font-semibold text-center whitespace-nowrap text-zinc-900 dark:text-white text-ellipsis"
style="--char-count: {result?.length ||
10}; font-size: min(2.5rem, max(1rem, calc(30vw / var(--char-count, 10))))"
>
{result}
</div>
<div
class="px-3 py-1 mt-1 text-sm rounded-md text-zinc-900 dark:text-zinc-300 bg-zinc-100 dark:bg-zinc-100/10"
>
{outputUnit || (isPartial ? "Partial" : "Result")}
</div>
</div>
{:else}
<div
class="w-6 h-6 rounded-full border-2 animate-spin border-zinc-300 dark:border-zinc-700 border-t-zinc-600 dark:border-t-zinc-300"
></div>
{/if}
</div>
</div>
</div>
{/if}
{/if}
@@ -2,42 +2,47 @@
import FolderOpenIcon from "@lucide/svelte/icons/folder-open";
import SearchIcon from "./SearchIcon.svelte";
import { iconForCategory } from "../core/searchIcons";
import { onMount, tick } from 'svelte';
import { settingsState } from '@/seqta/utils/listeners/SettingsState'
import { fade, scale } from 'svelte/transition';
import { circOut, quintOut } from 'svelte/easing';
import { type StaticCommandItem } from '../core/commands';
import type { CombinedResult } from '../core/types';
import { createSearchIndexes, applyDynamicIndexDelta, performSearch as doSearch, type DynamicItemsUpdatedDetail } from '../search/searchUtils';
import Fuse from 'fuse.js';
import Calculator from './Calculator.svelte';
import { actionMap } from '../indexing/actions';
import type { IndexItem } from '../indexing/types';
import debounce from '@/seqta/utils/debounce';
import { renderComponentMap } from '../indexing/renderComponents';
import HighlightedText from '../utils/HighlightedText.svelte';
import { matchesHotkey } from '../utils/hotkeyUtils';
import { warmUpVectorSearchOnInteraction } from '../search/vector/vectorSearch';
import browser from '@/lib/browser';
import { onMount, tick } from "svelte";
import { settingsState } from "@/seqta/utils/listeners/settingsState";
import { fade, scale } from "svelte/transition";
import { circOut, quintOut } from "svelte/easing";
import { type StaticCommandItem } from "../core/commands";
import type { CombinedResult } from "../core/types";
import {
createSearchIndexes,
applyDynamicIndexDelta,
performSearch as doSearch,
type DynamicItemsUpdatedDetail,
} from "../search/searchUtils";
import Fuse from "fuse.js";
import Calculator from "./Calculator.svelte";
import { actionMap } from "../indexing/actions";
import type { IndexItem } from "../indexing/types";
import debounce from "@/seqta/utils/debounce";
import { renderComponentMap } from "../indexing/renderComponents";
import HighlightedText from "../utils/HighlightedText.svelte";
import { matchesHotkey } from "../utils/hotkeyUtils";
import { warmUpVectorSearchOnInteraction } from "../search/vector/vectorSearch";
import browser from "@/lib/browser";
const {
transparencyEffects,
searchHotkey: initialSearchHotkey
}: {
transparencyEffects: boolean,
searchHotkey: string
const {
transparencyEffects,
searchHotkey: initialSearchHotkey,
}: {
transparencyEffects: boolean;
searchHotkey: string;
} = $props();
let currentSearchHotkey = $derived(initialSearchHotkey);
let commandsFuse = $state<Fuse<StaticCommandItem>>();
let dynamicContentFuse = $state<Fuse<IndexItem>>();
const dynamicIdToItemMap = $state(new Map<string, IndexItem>());
const commandIdToItemMap = $state(new Map<string, StaticCommandItem>());
let commandPalleteOpen = $state(false);
let searchTerm = $state('');
let searchTerm = $state("");
let selectedIndex = $state(0);
let combinedResults = $state<CombinedResult[]>([]);
let searchbar = $state<HTMLInputElement>();
@@ -53,13 +58,13 @@
// the `world w` pass and clobbers the more relevant matches.
let searchRequestId = 0;
let keydownHandler: ((e: KeyboardEvent) => void) | null = null;
$effect(() => {
const loadSettings = async () => {
const settings = await browser.storage.local.get('plugin.global-search.settings');
const pluginSettings = settings['plugin.global-search.settings'] as { searchHotkey?: string } | undefined;
const settings = await browser.storage.local.get("plugin.global-search.settings");
const pluginSettings = settings["plugin.global-search.settings"] as
{ searchHotkey?: string } | undefined;
if (pluginSettings?.searchHotkey) {
currentSearchHotkey = pluginSettings.searchHotkey;
}
@@ -68,8 +73,9 @@
loadSettings();
const handleStorageChange = (changes: any, area: string) => {
if (area === 'local' && changes['plugin.global-search.settings']) {
const newSettings = changes['plugin.global-search.settings'].newValue as { searchHotkey?: string } | undefined;
if (area === "local" && changes["plugin.global-search.settings"]) {
const newSettings = changes["plugin.global-search.settings"].newValue as
{ searchHotkey?: string } | undefined;
if (newSettings?.searchHotkey) {
currentSearchHotkey = newSettings.searchHotkey;
}
@@ -77,7 +83,7 @@
};
browser.storage.onChanged.addListener(handleStorageChange);
return () => {
browser.storage.onChanged.removeListener(handleStorageChange);
};
@@ -86,9 +92,9 @@
// Update keydown handler when hotkey changes
$effect(() => {
if (keydownHandler) {
window.removeEventListener('keydown', keydownHandler);
window.removeEventListener("keydown", keydownHandler);
}
keydownHandler = (e: KeyboardEvent) => {
if (matchesHotkey(e, currentSearchHotkey)) {
e.preventDefault();
@@ -96,16 +102,16 @@
commandPalleteOpen = true;
tick().then(() => searchbar?.focus());
}
if (e.key === 'Escape') {
if (e.key === "Escape") {
commandPalleteOpen = false;
}
};
window.addEventListener('keydown', keydownHandler);
window.addEventListener("keydown", keydownHandler);
return () => {
if (keydownHandler) {
window.removeEventListener('keydown', keydownHandler);
window.removeEventListener("keydown", keydownHandler);
keydownHandler = null;
}
};
@@ -115,21 +121,13 @@
const applyItemsUpdate = (event: Event) => {
const detail = (event as CustomEvent<DynamicItemsUpdatedDetail>).detail;
if (
detail?.vectorUpdate &&
!detail.changedItems?.length &&
!detail.removedIds?.length
) {
if (detail?.vectorUpdate && !detail.changedItems?.length && !detail.removedIds?.length) {
performSearch();
return;
}
if (detail?.incremental && !detail.fullRebuild) {
const updatedFuse = applyDynamicIndexDelta(
dynamicContentFuse,
dynamicIdToItemMap,
detail,
);
const updatedFuse = applyDynamicIndexDelta(dynamicContentFuse, dynamicIdToItemMap, detail);
if (updatedFuse) {
dynamicContentFuse = updatedFuse;
performSearch();
@@ -155,10 +153,10 @@
});
};
window.addEventListener('dynamic-items-updated', itemsUpdatedHandler);
window.addEventListener("dynamic-items-updated", itemsUpdatedHandler);
setupSearchIndexes();
// @ts-ignore - Intentionally adding to window
window.setCommandPalleteOpen = (open: boolean) => {
if (open) warmUpVectorSearchOnInteraction();
@@ -167,21 +165,26 @@
return () => {
if (itemsUpdateRaf) cancelAnimationFrame(itemsUpdateRaf);
window.removeEventListener('dynamic-items-updated', itemsUpdatedHandler);
window.removeEventListener("dynamic-items-updated", itemsUpdatedHandler);
};
});
function setupSearchIndexes() {
const { commandsFuse: cfuse, dynamicContentFuse: dfuse, commands, dynamicItems } = createSearchIndexes();
const {
commandsFuse: cfuse,
dynamicContentFuse: dfuse,
commands,
dynamicItems,
} = createSearchIndexes();
commandsFuse = cfuse;
dynamicContentFuse = dfuse;
dynamicIdToItemMap.clear();
commandIdToItemMap.clear();
dynamicItems.forEach(item => dynamicIdToItemMap.set(item.id, item));
commands.forEach(item => commandIdToItemMap.set(item.id, item));
dynamicItems.forEach((item) => dynamicIdToItemMap.set(item.id, item));
commands.forEach((item) => commandIdToItemMap.set(item.id, item));
}
const performSearch = async () => {
@@ -190,7 +193,7 @@
tick().then(() => {
const selectedElement = resultsList?.querySelector(`li:nth-child(1)`);
selectedElement?.scrollIntoView({ block: 'nearest' });
selectedElement?.scrollIntoView({ block: "nearest" });
});
const term = searchTerm.trim().toLowerCase();
@@ -232,7 +235,7 @@
$effect(() => {
if (commandPalleteOpen) {
if (searchTerm === '') {
if (searchTerm === "") {
// Immediate search for empty query (shows recent items)
performSearch();
} else if (searchTerm.length <= 2) {
@@ -242,9 +245,9 @@
// Debounced search for longer queries
debouncedPerformSearch();
}
tick().then(() => searchbar?.focus());
tick().then(() => searchbar?.focus());
} else {
searchTerm = '';
searchTerm = "";
selectedIndex = 0;
combinedResults = [];
}
@@ -262,7 +265,7 @@
selectedIndex++;
tick().then(() => {
const selectedElement = resultsList?.querySelector(`li:nth-child(${selectedIndex + 1})`);
selectedElement?.scrollIntoView({ block: 'nearest' });
selectedElement?.scrollIntoView({ block: "nearest" });
});
}
};
@@ -272,15 +275,15 @@
selectedIndex--;
tick().then(() => {
const selectedElement = resultsList?.querySelector(`li:nth-child(${selectedIndex + 1})`);
selectedElement?.scrollIntoView({ block: 'nearest' });
selectedElement?.scrollIntoView({ block: "nearest" });
});
}
};
function executeItemAction(item: StaticCommandItem | IndexItem) {
if ('action' in item && typeof item.action === 'function') {
if ("action" in item && typeof item.action === "function") {
(item as StaticCommandItem).action();
} else if ('actionId' in item && item.actionId && actionMap[item.actionId]) {
} else if ("actionId" in item && item.actionId && actionMap[item.actionId]) {
actionMap[item.actionId](item as IndexItem);
}
commandPalleteOpen = false;
@@ -300,49 +303,55 @@
};
const handleKeyNav = (e: KeyboardEvent) => {
if (e.key === 'ArrowDown') {
if (e.key === "ArrowDown") {
e.preventDefault();
selectNext();
} else if (e.key === 'ArrowUp') {
} else if (e.key === "ArrowUp") {
e.preventDefault();
selectPrev();
} else if (e.key === 'Enter') {
} else if (e.key === "Enter") {
e.preventDefault();
executeSelected();
} else if (e.key === 'Escape') {
} else if (e.key === "Escape") {
commandPalleteOpen = false;
}
};
</script>
{#if commandPalleteOpen}
<div role="dialog" aria-modal="true" class={settingsState.DarkMode ? 'dark' : ''}>
<div
class="fixed inset-0 z-50000 bg-zinc-900/40 dark:bg-black/60"
<div role="dialog" aria-modal="true" class={settingsState.DarkMode ? "dark" : ""}>
<div
class="fixed inset-0 z-50000 bg-zinc-900/40 dark:bg-black/60"
transition:fade={{ duration: 150, easing: quintOut }}
></div>
<div class="fixed inset-0 z-50000 flex justify-center place-items-start p-8 sm:p-6 md:p-8 select-none scale-120 origin-top"
onclick={() => commandPalleteOpen = false}
onkeydown={(e: KeyboardEvent) => e.key === 'Escape' && (commandPalleteOpen = false)}
role="button"
tabindex="0">
<div
class="fixed inset-0 z-50000 flex justify-center place-items-start p-8 sm:p-6 md:p-8 select-none scale-120 origin-top"
onclick={() => (commandPalleteOpen = false)}
onkeydown={(e: KeyboardEvent) => e.key === "Escape" && (commandPalleteOpen = false)}
role="button"
tabindex="0"
>
<div
class="w-full max-w-2xl overflow-clip rounded-xl ring-1 shadow-2xl ring-black/5 dark:ring-white/10 { transparencyEffects ? 'bg-white/80 dark:bg-zinc-900/80 backdrop-blur-xl' : 'bg-white dark:bg-zinc-900' }"
class="w-full max-w-2xl overflow-clip rounded-xl ring-1 shadow-2xl ring-black/5 dark:ring-white/10 {transparencyEffects
? 'bg-white/80 dark:bg-zinc-900/80 backdrop-blur-xl'
: 'bg-white dark:bg-zinc-900'}"
transition:scale={{ duration: 100, start: 0.95, opacity: 0, easing: circOut }}
onclick={(e: MouseEvent) => {
e.stopPropagation();
}}
onkeydown={(e: KeyboardEvent) => {
if (e.key === 'Escape') {
if (e.key === "Escape") {
commandPalleteOpen = false;
}
}}
role="button"
tabindex="0">
tabindex="0"
>
<div class="relative p-2 border-b border-zinc-900/5 dark:border-zinc-100/5">
<div class="absolute top-1/2 translate-y-[calc(-50%-3px)] scale-105 left-5 w-6 h-6 text-[1.3rem] text-zinc-900/40 dark:text-zinc-400/40 pointer-events-none">
<div
class="absolute top-1/2 translate-y-[calc(-50%-3px)] scale-105 left-5 w-6 h-6 text-[1.3rem] text-zinc-900/40 dark:text-zinc-400/40 pointer-events-none"
>
<SearchIcon name="search" />
</div>
<input
@@ -354,42 +363,55 @@
/>
</div>
<ul
<ul
bind:this={resultsList}
class="overflow-y-auto max-h-96 text-base scroll-py-2 p-2 gap-0.5 flex flex-col"
>
<Calculator
searchTerm={searchTerm}
isSelected={selectedIndex === 0}
<Calculator
{searchTerm}
isSelected={selectedIndex === 0}
onresult={(result) => (calculatorResult = result)}
/>
{#if combinedResults.length > 0}
{#each combinedResults as result, i (result.id)}
{#each combinedResults as result, i (result.id)}
{@const isSelected = selectedIndex === (calculatorResult ? i + 1 : i)}
{@const item = result.item}
{@const item = result.item}
<li>
{#if result.type === 'command'}
{#if result.type === "command"}
{@const staticItem = item as StaticCommandItem}
<button
class="w-full flex items-center px-2 py-1.5 rounded-lg select-none cursor-pointer group transition-colors duration-100 ring-0 dark:ring-zinc-600/50
{isSelected ? 'bg-zinc-900/5 dark:bg-white/10 text-zinc-900 dark:text-white dark:ring-[1px] dark:shadow-sm' : 'hover:bg-zinc-500/5 dark:hover:bg-white/5 text-zinc-800 dark:text-zinc-200'}"
{isSelected
? 'bg-zinc-900/5 dark:bg-white/10 text-zinc-900 dark:text-white dark:ring-[1px] dark:shadow-sm'
: 'hover:bg-zinc-500/5 dark:hover:bg-white/5 text-zinc-800 dark:text-zinc-200'}"
onclick={() => executeItemAction(staticItem)}
>
<div class="flex-none scale-90 w-8 h-8 text-xl flex items-center justify-center bg-linear-to-br {staticItem.category === 'navigation' ? 'from-[#FA5D5D] to-[#DC2F30]' : 'from-[#4FBBFE] to-[#2090F3]'} rounded-md text-white"><SearchIcon name={staticItem.icon} /></div>
<div
class="flex-none scale-90 w-8 h-8 text-xl flex items-center justify-center bg-linear-to-br {staticItem.category ===
'navigation'
? 'from-[#FA5D5D] to-[#DC2F30]'
: 'from-[#4FBBFE] to-[#2090F3]'} rounded-md text-white"
>
<SearchIcon name={staticItem.icon} />
</div>
<span class="ml-4 text-lg truncate">
<HighlightedText text={staticItem.text} term={searchTerm} matches={result.matches} />
<HighlightedText
text={staticItem.text}
term={searchTerm}
matches={result.matches}
/>
</span>
</button>
{:else if result.type === 'dynamic'}
{:else if result.type === "dynamic"}
{@const dynamicItem = item as IndexItem}
{@const RenderComponent = renderComponentMap[dynamicItem.renderComponentId]}
{#if RenderComponent}
<RenderComponent
item={dynamicItem}
isSelected={isSelected}
searchTerm={searchTerm}
matches={result.matches}
<RenderComponent
item={dynamicItem}
{isSelected}
{searchTerm}
matches={result.matches}
onclick={() => executeItemAction(dynamicItem)}
onkeydown={() => executeItemAction(dynamicItem)}
role="button"
@@ -397,22 +419,40 @@
/>
{:else}
<button
class="w-full flex flex-col px-2 py-1.5 rounded-lg select-none cursor-pointer group
{isSelected ? 'bg-zinc-900/5 dark:bg-white/10 text-zinc-900 dark:text-white dark:ring-[1px]' : 'hover:bg-zinc-500/5 dark:hover:bg-white/5 text-zinc-800 dark:text-zinc-200'}"
class="w-full flex flex-col px-2 py-1.5 rounded-lg select-none cursor-pointer group
{isSelected
? 'bg-zinc-900/5 dark:bg-white/10 text-zinc-900 dark:text-white dark:ring-[1px]'
: 'hover:bg-zinc-500/5 dark:hover:bg-white/5 text-zinc-800 dark:text-zinc-200'}"
onclick={() => executeItemAction(dynamicItem)}
>
<div class="flex items-center w-full">
<div class="flex-none w-8 h-8 text-xl flex items-center justify-center {isSelected ? 'text-zinc-900 dark:text-white' : 'text-zinc-600 dark:text-zinc-400'}"><SearchIcon name={iconForCategory(dynamicItem.category)} /></div>
<div
class="flex-none w-8 h-8 text-xl flex items-center justify-center {isSelected
? 'text-zinc-900 dark:text-white'
: 'text-zinc-600 dark:text-zinc-400'}"
>
<SearchIcon name={iconForCategory(dynamicItem.category)} />
</div>
<span class="ml-4 text-lg truncate">
<HighlightedText text={dynamicItem.text} term={searchTerm} matches={result.matches} />
<HighlightedText
text={dynamicItem.text}
term={searchTerm}
matches={result.matches}
/>
</span>
<span class="flex-none ml-auto text-xs text-zinc-500 dark:text-zinc-400">
{dynamicItem.category}
{dynamicItem.category}
</span>
</div>
{#if dynamicItem.content}
<div class="mt-1 ml-12 text-sm text-zinc-600 dark:text-zinc-400 line-clamp-2 text-start">
<HighlightedText text={dynamicItem.content} term={searchTerm} matches={result.matches} />
<div
class="mt-1 ml-12 text-sm text-zinc-600 dark:text-zinc-400 line-clamp-2 text-start"
>
<HighlightedText
text={dynamicItem.content}
term={searchTerm}
matches={result.matches}
/>
</div>
{/if}
</button>
@@ -423,7 +463,9 @@
{:else if !calculatorResult}
<div class="px-8 py-16 text-center text-zinc-900 dark:text-zinc-200 sm:px-16">
{#if isLoading}
<div class="mx-auto w-8 h-8 rounded-full border-2 animate-spin border-zinc-300 dark:border-zinc-700 border-t-zinc-600 dark:border-t-zinc-300"></div>
<div
class="mx-auto w-8 h-8 rounded-full border-2 animate-spin border-zinc-300 dark:border-zinc-700 border-t-zinc-600 dark:border-t-zinc-300"
></div>
<p class="mt-4 text-lg dark:text-zinc-300">Searching...</p>
{:else}
<FolderOpenIcon class="mx-auto w-8 h-8" />
@@ -434,13 +476,15 @@
</ul>
<div class="px-3 py-2 w-full border-t border-zinc-900/5 dark:border-zinc-100/5 bg-white/5">
{#if combinedResults.length > 0 || calculatorResult}
<div class="flex justify-between items-center h-7 text-sm text-zinc-500 dark:text-zinc-400">
<div
class="flex justify-between items-center h-7 text-sm text-zinc-500 dark:text-zinc-400"
>
<div class="flex gap-4 items-center">
{@render Shortcut({ text: 'Navigate', keybind: ['↑', '↓']})}
{@render Shortcut({ text: "Navigate", keybind: ["↑", "↓"] })}
{#if calculatorResult && selectedIndex === 0}
{@render Shortcut({ text: 'Copy result', keybind: ['↵']})}
{@render Shortcut({ text: "Copy result", keybind: ["↵"] })}
{:else}
{@render Shortcut({ text: 'Select', keybind: ['↵']})}
{@render Shortcut({ text: "Select", keybind: ["↵"] })}
{/if}
</div>
</div>
@@ -451,13 +495,16 @@
</div>
{/if}
{#snippet Shortcut({ text, keybind }: { text: string, keybind: string[] }) }
{#snippet Shortcut({ text, keybind }: { text: string; keybind: string[] })}
<div class="flex gap-2 items-center">
<div class="flex gap-1 items-center">
{#each keybind as key}
<kbd class="size-6 text-[0.9rem] flex justify-center items-center rounded-sm bg-zinc-100 dark:bg-zinc-100/10">{key}</kbd>
<kbd
class="size-6 text-[0.9rem] flex justify-center items-center rounded-sm bg-zinc-100 dark:bg-zinc-100/10"
>{key}</kbd
>
{/each}
</div>
<span>{text}</span>
</div>
{/snippet}
{/snippet}
@@ -1,10 +1,16 @@
<script lang="ts">
import SearchIcon from "../SearchIcon.svelte";
import HighlightedText from '../../utils/HighlightedText.svelte';
import type { DynamicContentItem } from '../../utils/dynamicItems';
import type { FuseResultMatch } from '../../core/types';
import HighlightedText from "../../utils/HighlightedText.svelte";
import type { DynamicContentItem } from "../../utils/dynamicItems";
import type { FuseResultMatch } from "../../core/types";
const { item, isSelected, searchTerm, matches, onclick }: {
const {
item,
isSelected,
searchTerm,
matches,
onclick,
}: {
item: DynamicContentItem;
isSelected: boolean;
searchTerm: string;
@@ -15,13 +21,19 @@
<button
class="w-full flex flex-col px-2 py-1.5 rounded-lg select-none cursor-pointer group transition-colors duration-100 ring-0 dark:ring-zinc-600/50
{isSelected ? 'bg-zinc-900/5 dark:bg-white/10 text-zinc-900 dark:text-white dark:ring-[1px] dark:shadow-sm' : 'hover:bg-zinc-500/5 dark:hover:bg-white/5 text-zinc-800 dark:text-zinc-200'}"
onclick={onclick}
>
{isSelected
? 'bg-zinc-900/5 dark:bg-white/10 text-zinc-900 dark:text-white dark:ring-[1px] dark:shadow-sm'
: 'hover:bg-zinc-500/5 dark:hover:bg-white/5 text-zinc-800 dark:text-zinc-200'}"
{onclick}
>
<div class="flex items-center w-full">
<div class="flex-none scale-90 w-8 h-8 text-xl flex items-center justify-center bg-linear-to-br from-[#59F675] to-[#1BC636] rounded-md text-white"><SearchIcon name="message-square-more" /></div>
<div
class="flex-none scale-90 w-8 h-8 text-xl flex items-center justify-center bg-linear-to-br from-[#59F675] to-[#1BC636] rounded-md text-white"
>
<SearchIcon name="message-square-more" />
</div>
<span class="ml-4 text-lg truncate">
<HighlightedText text={item.text} term={searchTerm} matches={matches} />
<HighlightedText text={item.text} term={searchTerm} {matches} />
</span>
<span class="flex-none ml-auto text-xs text-zinc-500 dark:text-zinc-400">
{item.category}
@@ -29,7 +41,7 @@
</div>
{#if item.content}
<div class="mt-1 ml-12 text-sm text-zinc-600 dark:text-zinc-400 line-clamp-2 text-start">
<HighlightedText text={item.content} term={searchTerm} matches={matches} />
<HighlightedText text={item.content} term={searchTerm} {matches} />
</div>
{/if}
</button>
</button>
@@ -1,10 +1,16 @@
<script lang="ts">
import SearchIcon from "../SearchIcon.svelte";
import HighlightedText from '../../utils/HighlightedText.svelte';
import type { DynamicContentItem } from '../../utils/dynamicItems';
import type { FuseResultMatch } from '../../core/types';
import HighlightedText from "../../utils/HighlightedText.svelte";
import type { DynamicContentItem } from "../../utils/dynamicItems";
import type { FuseResultMatch } from "../../core/types";
const { item, isSelected, searchTerm, matches, onclick }: {
const {
item,
isSelected,
searchTerm,
matches,
onclick,
}: {
item: DynamicContentItem;
isSelected: boolean;
searchTerm: string;
@@ -15,16 +21,22 @@
<button
class="w-full flex flex-col px-2 py-1.5 rounded-lg select-none cursor-pointer group transition-colors duration-100 ring-0 dark:ring-zinc-600/50
{isSelected ? 'bg-zinc-900/5 dark:bg-white/10 text-zinc-900 dark:text-white dark:ring-[1px] dark:shadow-sm' : 'hover:bg-zinc-500/5 dark:hover:bg-white/5 text-zinc-800 dark:text-zinc-200'}"
onclick={onclick}
>
{isSelected
? 'bg-zinc-900/5 dark:bg-white/10 text-zinc-900 dark:text-white dark:ring-[1px] dark:shadow-sm'
: 'hover:bg-zinc-500/5 dark:hover:bg-white/5 text-zinc-800 dark:text-zinc-200'}"
{onclick}
>
<div class="flex items-center w-full">
<div class="flex-none scale-90 w-8 h-8 text-xl flex items-center justify-center text-white bg-linear-to-br from-[#59aaf6] to-[#1b62c6] rounded-md"><SearchIcon name="messages-square" /></div>
<div
class="flex-none scale-90 w-8 h-8 text-xl flex items-center justify-center text-white bg-linear-to-br from-[#59aaf6] to-[#1b62c6] rounded-md"
>
<SearchIcon name="messages-square" />
</div>
<span class="ml-4 text-lg truncate {item.metadata?.closed ? 'line-through opacity-80' : ''}">
<HighlightedText text={item.text} term={searchTerm} matches={matches} />
<HighlightedText text={item.text} term={searchTerm} {matches} />
</span>
<span class="flex-none ml-auto text-xs text-zinc-500 dark:text-zinc-400">
{item.category}
{item.category}
</span>
</div>
</button>
</button>
@@ -1,11 +1,17 @@
<script lang="ts">
import SearchIcon from "../SearchIcon.svelte";
import { iconForCategory } from "../../core/searchIcons";
import HighlightedText from '../../utils/HighlightedText.svelte';
import type { DynamicContentItem } from '../../utils/dynamicItems';
import type { FuseResultMatch } from '../../core/types';
import HighlightedText from "../../utils/HighlightedText.svelte";
import type { DynamicContentItem } from "../../utils/dynamicItems";
import type { FuseResultMatch } from "../../core/types";
const { item, isSelected, searchTerm, matches, onclick }: {
const {
item,
isSelected,
searchTerm,
matches,
onclick,
}: {
item: DynamicContentItem;
isSelected: boolean;
searchTerm: string;
@@ -14,48 +20,51 @@
} = $props();
const categoryLabel = (category: string): string => {
if (!category) return '';
if (!category) return "";
return category.charAt(0).toUpperCase() + category.slice(1);
};
const gradientForCategory = (category: string): string => {
switch (category) {
case 'courses':
return 'from-[#7c5fe0] to-[#4d2bb8]';
case 'notices':
return 'from-[#f6c453] to-[#d39007]';
case 'documents':
return 'from-[#4FBBFE] to-[#2090F3]';
case 'folio':
return 'from-[#22c55e] to-[#0f9b3a]';
case 'portals':
return 'from-[#22d3ee] to-[#0e7490]';
case 'reports':
return 'from-[#f97316] to-[#c2410c]';
case 'goals':
return 'from-[#10b981] to-[#047857]';
case 'passive':
return 'from-[#6b7280] to-[#374151]';
case "courses":
return "from-[#7c5fe0] to-[#4d2bb8]";
case "notices":
return "from-[#f6c453] to-[#d39007]";
case "documents":
return "from-[#4FBBFE] to-[#2090F3]";
case "folio":
return "from-[#22c55e] to-[#0f9b3a]";
case "portals":
return "from-[#22d3ee] to-[#0e7490]";
case "reports":
return "from-[#f97316] to-[#c2410c]";
case "goals":
return "from-[#10b981] to-[#047857]";
case "passive":
return "from-[#6b7280] to-[#374151]";
default:
return 'from-[#4FBBFE] to-[#2090F3]';
return "from-[#4FBBFE] to-[#2090F3]";
}
};
</script>
<button
class="w-full flex flex-col px-2 py-1.5 rounded-lg select-none cursor-pointer group transition-colors duration-100 ring-0 dark:ring-zinc-600/50
{isSelected ? 'bg-zinc-900/5 dark:bg-white/10 text-zinc-900 dark:text-white dark:ring-[1px] dark:shadow-sm' : 'hover:bg-zinc-500/5 dark:hover:bg-white/5 text-zinc-800 dark:text-zinc-200'}"
onclick={onclick}
{isSelected
? 'bg-zinc-900/5 dark:bg-white/10 text-zinc-900 dark:text-white dark:ring-[1px] dark:shadow-sm'
: 'hover:bg-zinc-500/5 dark:hover:bg-white/5 text-zinc-800 dark:text-zinc-200'}"
{onclick}
>
<div class="flex items-center w-full">
<div
class="flex-none scale-90 w-8 h-8 text-xl flex items-center justify-center text-white rounded-md bg-linear-to-br {gradientForCategory(item.category)}"
class="flex-none scale-90 w-8 h-8 text-xl flex items-center justify-center text-white rounded-md bg-linear-to-br {gradientForCategory(
item.category,
)}"
>
<SearchIcon name={iconForCategory(item.category)} />
</div>
<span class="ml-4 text-lg truncate">
<HighlightedText text={item.text} term={searchTerm} matches={matches} />
<HighlightedText text={item.text} term={searchTerm} {matches} />
</span>
<span class="flex-none ml-auto text-xs text-zinc-500 dark:text-zinc-400">
{item.metadata?.subjectCode || categoryLabel(item.category)}
@@ -63,7 +72,7 @@
</div>
{#if item.content}
<div class="mt-1 ml-12 text-sm text-zinc-600 dark:text-zinc-400 line-clamp-2 text-start">
<HighlightedText text={item.content} term={searchTerm} matches={matches} />
<HighlightedText text={item.content} term={searchTerm} {matches} />
</div>
{/if}
</button>
@@ -1,8 +1,8 @@
<script lang="ts">
import SearchIcon from "../SearchIcon.svelte";
import HighlightedText from '../../utils/HighlightedText.svelte';
import type { IndexItem } from '../../indexing/types';
import type { FuseResultMatch } from '../../core/types';
import HighlightedText from "../../utils/HighlightedText.svelte";
import type { IndexItem } from "../../indexing/types";
import type { FuseResultMatch } from "../../core/types";
let {
item,
@@ -21,23 +21,36 @@
<button
class="w-full flex flex-col px-2 py-1.5 rounded-lg select-none cursor-pointer group transition-colors duration-100 ring-0 dark:ring-zinc-600/50
{isSelected ? 'bg-zinc-900/5 dark:bg-white/10 text-zinc-900 dark:text-white dark:ring-[1px] dark:shadow-sm' : 'hover:bg-zinc-500/5 dark:hover:bg-white/5 text-zinc-800 dark:text-zinc-200'}"
onclick={onclick}
{isSelected
? 'bg-zinc-900/5 dark:bg-white/10 text-zinc-900 dark:text-white dark:ring-[1px] dark:shadow-sm'
: 'hover:bg-zinc-500/5 dark:hover:bg-white/5 text-zinc-800 dark:text-zinc-200'}"
{onclick}
>
<div class="flex items-center w-full">
<div class="flex-none scale-90 w-8 h-8 text-xl flex items-center justify-center text-white {item.metadata?.type === 'assessments' ? 'bg-linear-to-br from-[#fa915d] to-[#dc6c2f] rounded-md' : 'bg-linear-to-br from-[#4FBBFE] to-[#2090F3] rounded-md'} {item.metadata.isActive ? 'opacity-100' : 'opacity-80'}">
<div
class="flex-none scale-90 w-8 h-8 text-xl flex items-center justify-center text-white {item
.metadata?.type === 'assessments'
? 'bg-linear-to-br from-[#fa915d] to-[#dc6c2f] rounded-md'
: 'bg-linear-to-br from-[#4FBBFE] to-[#2090F3] rounded-md'} {item.metadata.isActive
? 'opacity-100'
: 'opacity-80'}"
>
<SearchIcon name={item.metadata?.type === "assessments" ? "clipboard-list" : "book-open"} />
</div>
<span class="ml-4 text-lg truncate {item.metadata.isActive ? 'opacity-100' : 'opacity-70'}">
<HighlightedText text={item.text} term={searchTerm} matches={matches} />
<HighlightedText text={item.text} term={searchTerm} {matches} />
</span>
<span class="flex-none ml-auto text-xs text-zinc-500 dark:text-zinc-400 {item.metadata.isActive ? 'opacity-100' : 'opacity-70'}">
<span
class="flex-none ml-auto text-xs text-zinc-500 dark:text-zinc-400 {item.metadata.isActive
? 'opacity-100'
: 'opacity-70'}"
>
{item.metadata?.subjectCode}
</span>
</div>
{#if item.content}
<div class="mt-1 ml-12 text-sm text-zinc-600 dark:text-zinc-400 line-clamp-2 text-start">
<HighlightedText text={item.content} term={searchTerm} matches={matches} />
<HighlightedText text={item.content} term={searchTerm} {matches} />
</div>
{/if}
</button>
</button>
@@ -1,7 +1,7 @@
import type { SearchIconName } from "./searchIcons";
import type { HomeTimetableLesson } from "@/seqta/utils/loaders/homePageTypes";
import { settingsState } from "@/seqta/utils/listeners/SettingsState";
import { loadHomePage } from "@/seqta/utils/loaders/LoadHomePage";
import { settingsState } from "@/seqta/utils/listeners/settingsState";
import { loadHomePage } from "@/seqta/utils/loaders/loadHomePage";
import { waitForElm } from "@/seqta/utils/waitForElm";
export interface BaseCommandItem {
@@ -29,7 +29,7 @@ const globalSearchPlugin: Pick<Plugin<GlobalSearchSettings>, "run"> = {
const wasUpdated = await checkAndHandleUpdate();
if (wasUpdated) {
verboseLog(
"[Global Search] Extension updated — search index reset; the next indexing pass will repopulate.",
"[BetterSEQTA+] Global Search: Extension updated — search index reset; the next indexing pass will repopulate.",
);
}
} catch (error: unknown) {
@@ -40,18 +40,18 @@ const globalSearchPlugin: Pick<Plugin<GlobalSearchSettings>, "run"> = {
msg.includes("NS_ERROR_CORRUPTED_CONTENT")
) {
verboseDebug(
"[Global Search] Version check skipped due to asset loading restrictions:",
"[BetterSEQTA+] Global Search: Version check skipped due to asset loading restrictions:",
msg,
);
} else {
console.warn("[Global Search] Failed to check for updates:", error);
console.warn("[BetterSEQTA+] Global Search: Failed to check for updates:", error);
}
}
try {
await ensureSchemaCurrent();
} catch (error) {
console.warn("[Global Search] Schema check failed:", error);
console.warn("[BetterSEQTA+] Global Search: Schema check failed:", error);
}
try {
@@ -77,7 +77,7 @@ const globalSearchPlugin: Pick<Plugin<GlobalSearchSettings>, "run"> = {
try {
installPassiveObserver();
} catch (error) {
console.warn("[Global Search] Passive observer install failed:", error);
console.warn("[BetterSEQTA+] Global Search: Passive observer install failed:", error);
}
}
@@ -113,7 +113,7 @@ export async function mountSearchBar(titleElement: Element, api: GlobalSearchApi
!progressBar ||
!progressText
) {
console.error("[Global Search] Search trigger markup incomplete");
console.error("[BetterSEQTA+] Global Search: Search trigger markup incomplete");
return;
}
@@ -76,7 +76,7 @@ function cloneAssessmentActionItem(item: IndexItem & { metadata: AssessmentMetad
return { itemClone, metadata: itemClone.metadata || {} };
} catch (e) {
console.warn(
"[Assessment Action] Failed to clone item, trying to clone metadata separately:",
"[BetterSEQTA+] Assessment Action: Failed to clone item, trying to clone metadata separately:",
e,
);
try {
@@ -89,7 +89,10 @@ function cloneAssessmentActionItem(item: IndexItem & { metadata: AssessmentMetad
metadata,
};
} catch (e2) {
console.warn("[Assessment Action] Failed to clone metadata, using direct access:", e2);
console.warn(
"[BetterSEQTA+] Assessment Action: Failed to clone metadata, using direct access:",
e2,
);
const metadata = item.metadata || ({} as AssessmentMetadata);
return { itemClone: item, metadata };
}
@@ -124,7 +127,7 @@ function createMetadataValueReader(metadata: AssessmentMetadata) {
}
return undefined;
} catch (e) {
console.warn(`[Assessment Action] Failed to access metadata.${key}:`, e);
console.warn(`[BetterSEQTA+] Assessment Action: Failed to access metadata.${key}:`, e);
return undefined;
}
};
@@ -161,7 +164,10 @@ async function runAssessmentSearchAction(item: IndexItem & { metadata: Assessmen
) {
const extractedId = itemClone.id.replace("assignment-", "");
assessmentId = Number(extractedId) || extractedId;
verboseLog("[Assessment Action] Extracted assessmentId from item ID:", assessmentId);
verboseLog(
"[BetterSEQTA+] Assessment Action: Extracted assessmentId from item ID:",
assessmentId,
);
}
programmeId = coerceNumericMetadataId(programmeId);
@@ -174,12 +180,12 @@ async function runAssessmentSearchAction(item: IndexItem & { metadata: Assessmen
if (hasProgrammeId && hasMetaclassId && hasAssessmentId) {
const url = `#?page=/assessments/${programmeId}:${metaclassId}&item=${assessmentId}`;
verboseLog("[Assessment Action] ✅ Navigating to:", url);
verboseLog("[BetterSEQTA+] Assessment Action: ✅ Navigating to:", url);
window.location.hash = url;
return;
}
console.error("[Assessment Action] ❌ Missing required metadata:", {
console.error("[BetterSEQTA+] Assessment Action: ❌ Missing required metadata:", {
programmeId,
metaclassId,
assessmentId,
@@ -194,7 +200,9 @@ async function runAssessmentSearchAction(item: IndexItem & { metadata: Assessmen
if (hasAssessmentId) {
window.location.hash = `#?page=/assessments/upcoming&item=${assessmentId}`;
} else {
console.warn("[Assessment Action] No valid assessment ID, redirecting to upcoming");
console.warn(
"[BetterSEQTA+] Assessment Action: No valid assessment ID, redirecting to upcoming",
);
window.location.hash = `#?page=/assessments/upcoming`;
}
}
@@ -264,7 +264,7 @@ export async function seqtaFetchJson<T = unknown>(
if (json.status && json.status !== "200") {
console.warn(
`[Global Search API] Non-200 SEQTA status "${json.status}" for ${route} — returning payload anyway`,
`[BetterSEQTA+] Global Search API: Non-200 SEQTA status "${json.status}" for ${route} — returning payload anyway`,
);
}
@@ -302,7 +302,10 @@ export async function seqtaFetchPayload<T = unknown>(
const res = await seqtaFetchJson<T>(path, body, options);
return res.payload ?? null;
} catch (e) {
console.warn(`[Global Search API] Request to ${normalizeSeqtaPath(path)} failed:`, e);
console.warn(
`[BetterSEQTA+] Global Search API: Request to ${normalizeSeqtaPath(path)} failed:`,
e,
);
return null;
}
}
@@ -86,7 +86,7 @@ function deleteDatabaseWithRetries(name: string, maxAttempts = 6): Promise<void>
try {
req = indexedDB.deleteDatabase(name);
} catch (error) {
console.warn(`[DB] Could not start delete of ${name}:`, error);
console.warn(`[BetterSEQTA+] DB: Could not start delete of ${name}:`, error);
resolve();
return;
}
@@ -94,7 +94,7 @@ function deleteDatabaseWithRetries(name: string, maxAttempts = 6): Promise<void>
req.onsuccess = () => resolve();
req.onerror = () => {
console.warn(`[DB] Error deleting ${name}:`, req.error);
console.warn(`[BetterSEQTA+] DB: Error deleting ${name}:`, req.error);
if (attempt + 1 < maxAttempts) {
setTimeout(() => attemptDelete(attempt + 1), 150 * (attempt + 1));
return;
@@ -104,7 +104,7 @@ function deleteDatabaseWithRetries(name: string, maxAttempts = 6): Promise<void>
req.onblocked = () => {
console.warn(
`[DB] Delete of ${name} blocked (attempt ${attempt + 1}/${maxAttempts}); waiting for connections to close`,
`[BetterSEQTA+] DB: Delete of ${name} blocked (attempt ${attempt + 1}/${maxAttempts}); waiting for connections to close`,
);
if (attempt + 1 < maxAttempts) {
setTimeout(() => attemptDelete(attempt + 1), 200 * (attempt + 1));
@@ -137,12 +137,17 @@ async function openDBInternal(): Promise<IDBDatabase> {
const domError = error as DOMException | undefined;
if (domError?.name === "VersionError") {
console.warn("[DB] localStorage version out of sync with IndexedDB; opening current version");
console.warn(
"[BetterSEQTA+] DB: localStorage version out of sync with IndexedDB; opening current version",
);
invalidateConnection();
try {
return await openDatabase();
} catch (fallbackError) {
console.warn("[DB] Fallback open failed, recreating database:", fallbackError);
console.warn(
"[BetterSEQTA+] DB: Fallback open failed, recreating database:",
fallbackError,
);
}
} else {
console.error("Error opening database:", error);
@@ -253,7 +258,7 @@ async function upgradeDB(newStore: string): Promise<void> {
cachedDb = null;
dbPromise = null;
} catch (error) {
console.warn("[DB] Could not probe database version before upgrade:", error);
console.warn("[BetterSEQTA+] DB: Could not probe database version before upgrade:", error);
}
try {
@@ -278,7 +283,7 @@ export async function ensureStoresExist(stores: string[]): Promise<void> {
try {
db = await openDB();
} catch (error) {
console.warn("[DB] ensureStoresExist: could not open database:", error);
console.warn("[BetterSEQTA+] DB: ensureStoresExist: could not open database:", error);
return;
}
@@ -294,7 +299,7 @@ export async function ensureStoresExist(stores: string[]): Promise<void> {
try {
await openDatabaseWithStores(baseVersion + 1, missing);
} catch (error) {
console.error("[DB] ensureStoresExist failed:", error);
console.error("[BetterSEQTA+] DB: ensureStoresExist failed:", error);
throw error;
}
});
@@ -34,13 +34,13 @@ async function ensureSchemaCurrent(): Promise<void> {
if (stored === INDEX_SCHEMA_VERSION) return;
console.warn(
`[Indexer] Schema version changed (${stored} -> ${INDEX_SCHEMA_VERSION}); resetting structured + vector indexes.`,
`[BetterSEQTA+] Indexer: Schema version changed (${stored} -> ${INDEX_SCHEMA_VERSION}); resetting structured + vector indexes.`,
);
try {
await resetSearchIndexes();
} catch (e) {
console.warn("[Indexer] Failed to reset search indexes:", e);
console.warn("[BetterSEQTA+] Indexer: Failed to reset search indexes:", e);
}
try {
@@ -108,7 +108,7 @@ async function diffAndStoreItems(targetStore: string, items: IndexItem[]): Promi
const validItems = items.filter((i) => i && i.id);
if (validItems.length !== items.length) {
console.warn(
`[Indexer] Filtered out ${items.length - validItems.length} invalid items before storing in '${targetStore}'.`,
`[BetterSEQTA+] Indexer: Filtered out ${items.length - validItems.length} invalid items before storing in '${targetStore}'.`,
);
}
@@ -153,7 +153,7 @@ async function tryClaimLock(lockId: string): Promise<boolean> {
async function acquireLock(): Promise<boolean> {
if (isIndexingActive) {
verboseDebug("[Indexer] Already indexing in this tab");
verboseDebug("[BetterSEQTA+] Indexer: Already indexing in this tab");
return false;
}
@@ -174,7 +174,7 @@ async function acquireLock(): Promise<boolean> {
if (await tryClaimLock(lockId)) return true;
}
} catch (e) {
console.warn("[Indexer] Error parsing lock:", e);
console.warn("[BetterSEQTA+] Indexer: Error parsing lock:", e);
}
}
@@ -242,7 +242,7 @@ export async function loadAllStoredItems(): Promise<IndexItem[]> {
console.error(`Error loading items for job store ${jobId}:`, error);
}
}
verboseDebug(`[Indexer] Loaded ${all.length} items from all primary stores.`);
verboseDebug(`[BetterSEQTA+] Indexer: Loaded ${all.length} items from all primary stores.`);
return all;
}
@@ -293,12 +293,16 @@ function dispatchVectorProgress(
export async function runIndexing(): Promise<void> {
if (isPluginBlockedByPerformanceMode("global-search")) {
verboseDebug("[Indexer] Skipping indexing — performance mode blocks Global Search.");
verboseDebug(
"[BetterSEQTA+] Indexer: Skipping indexing — performance mode blocks Global Search.",
);
return;
}
if (isIndexingPaused()) {
verboseDebug("[Indexer] Skipping indexing — index was reset; reload the page to rebuild.");
verboseDebug(
"[BetterSEQTA+] Indexer: Skipping indexing — index was reset; reload the page to rebuild.",
);
return;
}
@@ -327,7 +331,9 @@ export async function runIndexing(): Promise<void> {
for (const jobId of jobIds) {
if (isIndexingPaused()) {
verboseDebug("[Indexer] Indexing stopped — index was reset; reload the page to rebuild.");
verboseDebug(
"[BetterSEQTA+] Indexer: Indexing stopped — index was reset; reload the page to rebuild.",
);
dispatchProgress(completedJobs, totalSteps, false, "Indexing paused — reload to rebuild");
return;
}
@@ -417,7 +423,7 @@ export async function runIndexing(): Promise<void> {
const { refreshVectorCache } = await import("../search/vector/vectorSearch");
await refreshVectorCache();
} catch (e) {
console.warn("[Indexer] Failed to refresh vector cache after prune:", e);
console.warn("[BetterSEQTA+] Indexer: Failed to refresh vector cache after prune:", e);
}
}
@@ -25,7 +25,7 @@ const fetchUpcomingAssessments = async (student: number) => {
});
return Array.isArray(res.payload) ? res.payload : [];
} catch (e) {
console.error("[Assignments job] Failed to fetch upcoming assessments:", e);
console.error("[BetterSEQTA+] Assignments job: Failed to fetch upcoming assessments:", e);
return [];
}
};
@@ -40,7 +40,7 @@ const fetchSubjects = async () => {
?.flatMap((s) => (Array.isArray(s.subjects) ? (s.subjects as OverviewSubject[]) : [])) ?? []
);
} catch (e) {
console.error("[Assignments job] Failed to fetch subjects:", e);
console.error("[BetterSEQTA+] Assignments job: Failed to fetch subjects:", e);
return [];
}
};
@@ -80,7 +80,7 @@ const fetchPastAssessments = async (student: number, subjects: OverviewSubject[]
}
} catch (e) {
console.warn(
`[Assignments job] Failed to fetch past assessments for subject ${subject.code || "unknown"}:`,
`[BetterSEQTA+] Assignments job: Failed to fetch past assessments for subject ${subject.code || "unknown"}:`,
e,
);
}
@@ -114,16 +114,19 @@ function buildAssignmentIndexItem(
const metaclassId = assessment.metaclassID || assessment.metaclass;
if (!programmeId || !metaclassId || !assessment.id) {
console.warn(`[Assignments job] Skipping assignment ${assessment.id} - missing required IDs:`, {
programmeId,
metaclassId,
assessmentId: assessment.id,
programmeID: assessment.programmeID,
metaclassID: assessment.metaclassID,
programme: assessment.programme,
metaclass: assessment.metaclass,
assessment,
});
console.warn(
`[BetterSEQTA+] Assignments job: Skipping assignment ${assessment.id} - missing required IDs:`,
{
programmeId,
metaclassId,
assessmentId: assessment.id,
programmeID: assessment.programmeID,
metaclassID: assessment.metaclassID,
programme: assessment.programme,
metaclass: assessment.metaclass,
assessment,
},
);
return null;
}
@@ -132,7 +135,7 @@ function buildAssignmentIndexItem(
if (finalProgrammeId === undefined || finalMetaclassId === undefined) {
console.error(
`[Assignments job] ❌ Skipping assignment ${assessment.id} - invalid IDs after conversion:`,
`[BetterSEQTA+] Assignments job: ❌ Skipping assignment ${assessment.id} - invalid IDs after conversion:`,
{
programmeId: finalProgrammeId,
metaclassId: finalMetaclassId,
@@ -173,7 +176,7 @@ function buildAssignmentIndexItem(
renderComponentId: "assessment",
};
verboseDebug(`[Assignments job] ✅ Created item for assignment ${assessment.id}:`, {
verboseDebug(`[BetterSEQTA+] Assignments job: ✅ Created item for assignment ${assessment.id}:`, {
id: item.id,
programmeId: item.metadata.programmeId,
programmeID: item.metadata.programmeID,
@@ -226,12 +229,12 @@ export const assignmentsJob: Job = {
const { id: student } = await getUserInfo();
if (student == null) {
verboseDebug("[Assignments job] No student id; skipping run");
verboseDebug("[BetterSEQTA+] Assignments job: No student id; skipping run");
return [];
}
verboseDebug(
"[Assignments job] Starting indexing - fetching all assessments (upcoming and past)...",
"[BetterSEQTA+] Assignments job: Starting indexing - fetching all assessments (upcoming and past)...",
);
const [upcoming, subjects] = await Promise.all([
@@ -240,12 +243,12 @@ export const assignmentsJob: Job = {
]);
verboseDebug(
`[Assignments job] Fetched ${upcoming.length} upcoming assessments and ${subjects.length} subjects`,
`[BetterSEQTA+] Assignments job: Fetched ${upcoming.length} upcoming assessments and ${subjects.length} subjects`,
);
const past = await fetchPastAssessments(student, subjects);
verboseDebug(`[Assignments job] Fetched ${past.length} past assessments`);
verboseDebug(`[BetterSEQTA+] Assignments job: Fetched ${past.length} past assessments`);
const subjectLookup = new Map<string, { programme: number; metaclass: number }>();
subjects.forEach((s: OverviewSubject) => {
@@ -317,7 +320,7 @@ export const assignmentsJob: Job = {
const pastCount = assessmentArray.filter((a) => !a.isUpcoming).length;
const upcomingCount = assessmentArray.filter((a) => a.isUpcoming).length;
verboseDebug(
`[Assignments job] Processing ${assessmentArray.length} total assessments (${upcomingCount} upcoming, ${pastCount} past)`,
`[BetterSEQTA+] Assignments job: Processing ${assessmentArray.length} total assessments (${upcomingCount} upcoming, ${pastCount} past)`,
);
const batchSize = 15;
@@ -344,7 +347,7 @@ export const assignmentsJob: Job = {
const newItemsCount = items.filter((item) => !existingIds.has(item.id)).length;
const updatedItemsCount = items.length - newItemsCount;
verboseDebug(
`[Assignments job] Indexed ${items.length} assignment items (${newItemsCount} new, ${updatedItemsCount} updated)`,
`[BetterSEQTA+] Assignments job: Indexed ${items.length} assignment items (${newItemsCount} new, ${updatedItemsCount} updated)`,
);
return items;
},
@@ -101,7 +101,7 @@ export const coursesJob: Job = {
run: async (ctx) => {
const subjects = await fetchActiveSubjects();
if (subjects.length === 0) {
verboseDebug("[Courses job] No active subjects discovered.");
verboseDebug("[BetterSEQTA+] Courses job: No active subjects discovered.");
return [];
}
@@ -178,7 +178,7 @@ export const coursesJob: Job = {
});
verboseDebug(
`[Courses job] Indexed ${items.length} courses across ${subjects.length} subjects.`,
`[BetterSEQTA+] Courses job: Indexed ${items.length} courses across ${subjects.length} subjects.`,
);
return items;
},
@@ -127,7 +127,7 @@ export const documentsJob: Job = {
}
}
verboseDebug(`[Documents job] Indexed ${items.length} document entries.`);
verboseDebug(`[BetterSEQTA+] Documents job: Indexed ${items.length} document entries.`);
return items;
},
@@ -121,13 +121,13 @@ export const folioJob: Job = {
renderComponentId: "folio",
});
} catch (e) {
console.warn(`[Folio job] Failed to load folio ${entry.id}:`, e);
console.warn(`[BetterSEQTA+] Folio job: Failed to load folio ${entry.id}:`, e);
}
await delay(PER_ITEM_DELAY_MS);
}
verboseDebug(`[Folio job] Indexed ${items.length} folio entries.`);
verboseDebug(`[BetterSEQTA+] Folio job: Indexed ${items.length} folio entries.`);
return items;
},
@@ -27,7 +27,7 @@ export const forumsJob: Job = {
try {
list = await fetchForums();
} catch (e) {
console.error("[Forums job] list fetch failed:", e);
console.error("[BetterSEQTA+] Forums job: list fetch failed:", e);
return [];
}
@@ -43,7 +43,7 @@ export const goalsJob: Job = {
{ mode: "years" },
);
if (!Array.isArray(years) || years.length === 0) {
verboseDebug("[Goals job] No goal years available; skipping.");
verboseDebug("[BetterSEQTA+] Goals job: No goal years available; skipping.");
return [];
}
@@ -96,12 +96,12 @@ export const goalsJob: Job = {
});
}
} catch (e) {
console.warn(`[Goals job] Failed to fetch goals for year ${year}:`, e);
console.warn(`[BetterSEQTA+] Goals job: Failed to fetch goals for year ${year}:`, e);
}
await delay(PER_YEAR_DELAY_MS);
}
verboseDebug(`[Goals job] Indexed ${items.length} goal entries.`);
verboseDebug(`[BetterSEQTA+] Goals job: Indexed ${items.length} goal entries.`);
return items;
},
Loaded 100 of 229 files, more files were not shown because too many files have changed in this diff. Show more