mirror of
https://github.com/BetterSEQTA/BetterSEQTA-Plus.git
synced 2026-12-06 19:56:45 +10:30
chore: cleanup and optmise size
This commit is contained in:
1 parent
5dba4ba8b5
commit
a19b43ef37
6 files changed
+94
-257
No files matched your search
@@ -8,9 +8,7 @@
|
||||
|
||||
let { isEditMode, selectNoBackground = $bindable(), selectedBackground = $bindable() } = $props<{ isEditMode: boolean, selectNoBackground: () => void, selectedBackground: string | null }>();
|
||||
let backgrounds = $state<{ id: string; type: string; blob: Blob | null; url?: string }[]>([]);
|
||||
let error = $state<string | null>(null);
|
||||
let notice = $state<string | null>(null);
|
||||
let uploading = $state(false);
|
||||
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'));
|
||||
@@ -20,39 +18,12 @@
|
||||
if (mime.startsWith('video/')) return 'video';
|
||||
if (mime.startsWith('image/')) return 'image';
|
||||
const ext = file.name.split('.').pop()?.toLowerCase() ?? '';
|
||||
if (['mp4', 'mov', 'webm', 'm4v', 'mkv'].includes(ext)) return 'video';
|
||||
return 'image';
|
||||
}
|
||||
|
||||
function setError(e: unknown) {
|
||||
if (e instanceof Error) {
|
||||
error = e.message;
|
||||
return;
|
||||
}
|
||||
if (typeof e === 'string' && e) {
|
||||
error = e;
|
||||
return;
|
||||
}
|
||||
error = 'An unknown error occurred';
|
||||
}
|
||||
|
||||
function isHeicFile(file: File): boolean {
|
||||
const mime = file.type.toLowerCase();
|
||||
const ext = file.name.split('.').pop()?.toLowerCase() ?? '';
|
||||
return (
|
||||
mime.includes('heic') ||
|
||||
mime.includes('heif') ||
|
||||
ext === 'heic' ||
|
||||
ext === 'heif'
|
||||
);
|
||||
return ['mp4', 'mov', 'webm', 'm4v', 'mkv'].includes(ext) ? 'video' : 'image';
|
||||
}
|
||||
|
||||
async function handleFileChange(file: File): Promise<void> {
|
||||
if (!file) return;
|
||||
|
||||
uploading = true;
|
||||
error = null;
|
||||
notice = null;
|
||||
feedback = null;
|
||||
|
||||
try {
|
||||
if (!isIndexedDBSupported()) {
|
||||
@@ -75,42 +46,36 @@
|
||||
];
|
||||
backgroundUpdates.triggerUpdate();
|
||||
|
||||
if (isHeicFile(file)) {
|
||||
notice =
|
||||
'HEIC saved, but Chrome and Edge often cannot preview it. Export as JPEG or PNG if the thumbnail stays blank.';
|
||||
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.',
|
||||
};
|
||||
}
|
||||
} catch (e) {
|
||||
setError(e);
|
||||
} finally {
|
||||
uploading = false;
|
||||
feedback = {
|
||||
kind: 'error',
|
||||
text: e instanceof Error ? e.message : 'An unknown error occurred',
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
async function getTheme() {
|
||||
return localStorage.getItem('selectedBackground');
|
||||
}
|
||||
|
||||
async function setTheme(theme: string) {
|
||||
localStorage.setItem('selectedBackground', theme);
|
||||
}
|
||||
|
||||
async function syncBackgrounds(): Promise<void> {
|
||||
try {
|
||||
error = null;
|
||||
feedback = null;
|
||||
|
||||
if (!isIndexedDBSupported()) {
|
||||
throw new Error("Your browser doesn't support IndexedDB. Unable to load backgrounds.");
|
||||
}
|
||||
|
||||
selectedBackground = await getTheme();
|
||||
selectedBackground = localStorage.getItem('selectedBackground');
|
||||
const dbData = await readAllData();
|
||||
|
||||
// Release existing object URLs to prevent memory leaks
|
||||
backgrounds.forEach(bg => {
|
||||
if (bg.url) URL.revokeObjectURL(bg.url);
|
||||
});
|
||||
|
||||
// Create fresh background objects with new object URLs
|
||||
backgrounds = dbData.map(bg => ({
|
||||
id: bg.id,
|
||||
type: bg.type,
|
||||
@@ -118,12 +83,14 @@
|
||||
url: URL.createObjectURL(bg.blob)
|
||||
}));
|
||||
|
||||
// Check if selected background still exists
|
||||
if (selectedBackground && !backgrounds.some(bg => bg.id === selectedBackground)) {
|
||||
selectNoBackground();
|
||||
}
|
||||
} catch (e) {
|
||||
setError(e);
|
||||
feedback = {
|
||||
kind: 'error',
|
||||
text: e instanceof Error ? e.message : 'An unknown error occurred',
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
@@ -134,7 +101,7 @@
|
||||
}
|
||||
|
||||
selectedBackground = fileId;
|
||||
setTheme(fileId);
|
||||
localStorage.setItem('selectedBackground', fileId);
|
||||
}
|
||||
|
||||
async function deleteBackground(fileId: string): Promise<void> {
|
||||
@@ -147,13 +114,16 @@
|
||||
}
|
||||
backgroundUpdates.triggerUpdate();
|
||||
} catch (e) {
|
||||
setError(e);
|
||||
feedback = {
|
||||
kind: 'error',
|
||||
text: e instanceof Error ? e.message : 'An unknown error occurred',
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
selectNoBackground = () => {
|
||||
selectedBackground = null;
|
||||
setTheme('');
|
||||
localStorage.setItem('selectedBackground', '');
|
||||
}
|
||||
|
||||
$effect(() => {
|
||||
@@ -161,12 +131,6 @@
|
||||
selectedBackground
|
||||
});
|
||||
|
||||
$effect(() => {
|
||||
if (error) {
|
||||
console.error(error);
|
||||
}
|
||||
});
|
||||
|
||||
onMount(() => {
|
||||
syncBackgrounds();
|
||||
backgroundUpdates.addListener(syncBackgrounds);
|
||||
@@ -184,21 +148,14 @@
|
||||
</script>
|
||||
|
||||
<div class="relative px-1 { !( isEditMode && imageBackgrounds.length === 0 && videoBackgrounds.length === 0 ) && 'pt-2' }">
|
||||
{#if notice}
|
||||
{#if feedback}
|
||||
<div
|
||||
class="mx-1 mb-3 rounded-lg border border-amber-300/60 bg-amber-50 px-3 py-2 text-sm text-amber-900 dark:border-amber-900/50 dark:bg-amber-950/40 dark:text-amber-100"
|
||||
role="status"
|
||||
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'}
|
||||
>
|
||||
{notice}
|
||||
</div>
|
||||
{/if}
|
||||
|
||||
{#if error}
|
||||
<div
|
||||
class="mx-1 mb-3 rounded-lg border border-red-300/60 bg-red-50 px-3 py-2 text-sm text-red-800 dark:border-red-900/50 dark:bg-red-950/40 dark:text-red-200"
|
||||
role="alert"
|
||||
>
|
||||
{error}
|
||||
{feedback.text}
|
||||
</div>
|
||||
{/if}
|
||||
|
||||
@@ -207,11 +164,6 @@
|
||||
<div class="flex flex-wrap gap-4 mb-4">
|
||||
{#if !isEditMode}
|
||||
<BackgroundUploader onFileChange={handleFileChange} />
|
||||
{#if uploading}
|
||||
<div class="flex h-16 w-16 items-center justify-center rounded-xl bg-zinc-100 dark:bg-zinc-900">
|
||||
<div class="h-5 w-5 animate-spin rounded-full border-2 border-zinc-400 border-t-transparent"></div>
|
||||
</div>
|
||||
{/if}
|
||||
{/if}
|
||||
{#each imageBackgrounds as bg (bg.id)}
|
||||
{#if bg.url}
|
||||
|
||||
@@ -1,107 +1,49 @@
|
||||
type BackgroundRecord = { id: string; type: string; blob: Blob };
|
||||
|
||||
const DB_NAME = "BackgroundDB";
|
||||
const STORE_NAME = "backgrounds";
|
||||
const DB_VERSION = 1;
|
||||
const STORE = "backgrounds";
|
||||
|
||||
let dbPromise: Promise<IDBDatabase> | null = null;
|
||||
|
||||
function promisifyRequest<T>(request: IDBRequest<T>): Promise<T> {
|
||||
function req<T>(request: IDBRequest<T>): Promise<T> {
|
||||
return new Promise((resolve, reject) => {
|
||||
request.onsuccess = () => resolve(request.result);
|
||||
request.onerror = () => reject(request.error);
|
||||
});
|
||||
}
|
||||
|
||||
function waitForTransaction(tx: IDBTransaction): Promise<void> {
|
||||
function txDone(tx: IDBTransaction): Promise<void> {
|
||||
return new Promise((resolve, reject) => {
|
||||
tx.oncomplete = () => resolve();
|
||||
tx.onerror = () => reject(tx.error);
|
||||
tx.onabort = () => reject(tx.error);
|
||||
});
|
||||
}
|
||||
|
||||
function openDatabaseInternal(): Promise<IDBDatabase> {
|
||||
export function openDatabase(): Promise<IDBDatabase> {
|
||||
if (!dbPromise) {
|
||||
dbPromise = new Promise((resolve, reject) => {
|
||||
const request = indexedDB.open(DB_NAME, DB_VERSION);
|
||||
|
||||
request.onerror = () => {
|
||||
const open = indexedDB.open(DB_NAME, 1);
|
||||
open.onerror = () => {
|
||||
dbPromise = null;
|
||||
reject(request.error);
|
||||
reject(open.error);
|
||||
};
|
||||
|
||||
request.onupgradeneeded = () => {
|
||||
const db = request.result;
|
||||
if (!db.objectStoreNames.contains(STORE_NAME)) {
|
||||
db.createObjectStore(STORE_NAME, { keyPath: "id" });
|
||||
open.onupgradeneeded = () => {
|
||||
if (!open.result.objectStoreNames.contains(STORE)) {
|
||||
open.result.createObjectStore(STORE, { keyPath: "id" });
|
||||
}
|
||||
};
|
||||
|
||||
request.onsuccess = () => resolve(request.result);
|
||||
open.onsuccess = () => resolve(open.result);
|
||||
});
|
||||
}
|
||||
|
||||
return dbPromise;
|
||||
}
|
||||
|
||||
function storeUsesInlineKeys(store: IDBObjectStore): boolean {
|
||||
return store.keyPath !== null && store.keyPath !== "";
|
||||
}
|
||||
|
||||
async function withStore<T>(
|
||||
mode: IDBTransactionMode,
|
||||
run: (store: IDBObjectStore) => Promise<T>,
|
||||
): Promise<T> {
|
||||
const db = await openDatabaseInternal();
|
||||
const tx = db.transaction(STORE_NAME, mode);
|
||||
const result = await run(tx.objectStore(STORE_NAME));
|
||||
await waitForTransaction(tx);
|
||||
return result;
|
||||
}
|
||||
|
||||
export async function openDatabase(): Promise<IDBDatabase> {
|
||||
return openDatabaseInternal();
|
||||
}
|
||||
|
||||
export async function readAllData(): Promise<BackgroundRecord[]> {
|
||||
return withStore("readonly", async (store) => {
|
||||
const items: BackgroundRecord[] = [];
|
||||
|
||||
await new Promise<void>((resolve, reject) => {
|
||||
const request = store.openCursor();
|
||||
|
||||
request.onsuccess = () => {
|
||||
const cursor = request.result;
|
||||
if (!cursor) {
|
||||
resolve();
|
||||
return;
|
||||
}
|
||||
|
||||
const value = cursor.value as Partial<BackgroundRecord> | undefined;
|
||||
const id =
|
||||
typeof value?.id === "string"
|
||||
? value.id
|
||||
: cursor.key == null
|
||||
? ""
|
||||
: String(cursor.key);
|
||||
|
||||
if (id && value?.blob instanceof Blob) {
|
||||
items.push({
|
||||
id,
|
||||
type: typeof value.type === "string" ? value.type : "image",
|
||||
blob: value.blob,
|
||||
});
|
||||
}
|
||||
|
||||
cursor.continue();
|
||||
};
|
||||
|
||||
request.onerror = () => reject(request.error);
|
||||
});
|
||||
|
||||
return items;
|
||||
});
|
||||
const db = await openDatabase();
|
||||
const tx = db.transaction(STORE, "readonly");
|
||||
const items = await req(tx.objectStore(STORE).getAll());
|
||||
await txDone(tx);
|
||||
return items;
|
||||
}
|
||||
|
||||
export async function writeData(
|
||||
@@ -109,15 +51,14 @@ export async function writeData(
|
||||
type: string,
|
||||
blob: Blob,
|
||||
): Promise<void> {
|
||||
const record: BackgroundRecord = { id, type, blob };
|
||||
const record = { id, type, blob };
|
||||
const db = await openDatabase();
|
||||
const tx = db.transaction(STORE, "readwrite");
|
||||
const store = tx.objectStore(STORE);
|
||||
|
||||
try {
|
||||
await withStore("readwrite", async (store) => {
|
||||
const request = storeUsesInlineKeys(store)
|
||||
? store.put(record)
|
||||
: store.put(record, id);
|
||||
await promisifyRequest(request);
|
||||
});
|
||||
await req(store.keyPath ? store.put(record) : store.put(record, id));
|
||||
await txDone(tx);
|
||||
} catch (e) {
|
||||
const detail = e instanceof Error ? e.message : String(e);
|
||||
throw new Error(`Failed to save background: ${detail}`);
|
||||
@@ -125,30 +66,27 @@ export async function writeData(
|
||||
}
|
||||
|
||||
export async function deleteData(id: string): Promise<void> {
|
||||
try {
|
||||
await withStore("readwrite", async (store) => {
|
||||
await promisifyRequest(store.delete(id));
|
||||
});
|
||||
} catch (e) {
|
||||
const detail = e instanceof Error ? e.message : String(e);
|
||||
throw new Error(`Failed to delete background: ${detail}`);
|
||||
}
|
||||
const db = await openDatabase();
|
||||
const tx = db.transaction(STORE, "readwrite");
|
||||
await req(tx.objectStore(STORE).delete(id));
|
||||
await txDone(tx);
|
||||
}
|
||||
|
||||
export async function clearAllData(): Promise<void> {
|
||||
await withStore("readwrite", async (store) => {
|
||||
await promisifyRequest(store.clear());
|
||||
});
|
||||
const db = await openDatabase();
|
||||
const tx = db.transaction(STORE, "readwrite");
|
||||
await req(tx.objectStore(STORE).clear());
|
||||
await txDone(tx);
|
||||
}
|
||||
|
||||
export async function getDataById(
|
||||
id: string,
|
||||
): Promise<BackgroundRecord | undefined> {
|
||||
const item = await withStore("readonly", async (store) =>
|
||||
promisifyRequest(store.get(id)),
|
||||
);
|
||||
if (!item?.id || !(item.blob instanceof Blob)) return undefined;
|
||||
return item as BackgroundRecord;
|
||||
const db = await openDatabase();
|
||||
const tx = db.transaction(STORE, "readonly");
|
||||
const item = await req(tx.objectStore(STORE).get(id));
|
||||
await txDone(tx);
|
||||
return item?.blob instanceof Blob ? item : undefined;
|
||||
}
|
||||
|
||||
export function closeDatabase(): void {
|
||||
@@ -165,11 +103,7 @@ export function isIndexedDBSupported(): boolean {
|
||||
export async function hasEnoughStorageSpace(
|
||||
requiredSpace: number,
|
||||
): Promise<boolean> {
|
||||
if ("storage" in navigator && "estimate" in navigator.storage) {
|
||||
const { quota, usage } = await navigator.storage.estimate();
|
||||
if (quota !== undefined && usage !== undefined) {
|
||||
return quota - usage > requiredSpace;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
if (!("storage" in navigator) || !navigator.storage.estimate) return true;
|
||||
const { quota, usage } = await navigator.storage.estimate();
|
||||
return quota == null || usage == null || quota - usage > requiredSpace;
|
||||
}
|
||||
@@ -1,28 +0,0 @@
|
||||
<script lang="ts">
|
||||
import type { Component } from "svelte";
|
||||
import type { SettingsSectionId, SettingsSectionSharedProps } from "./shared";
|
||||
import { SECTION_LOADERS } from "./sectionLoaders";
|
||||
|
||||
let {
|
||||
section,
|
||||
...rest
|
||||
}: SettingsSectionSharedProps & { section: SettingsSectionId } = $props();
|
||||
|
||||
let Comp = $state<Component | null>(null);
|
||||
let loadToken = 0;
|
||||
|
||||
$effect(() => {
|
||||
section;
|
||||
Comp = null;
|
||||
const token = ++loadToken;
|
||||
void SECTION_LOADERS[section]().then((mod) => {
|
||||
if (token === loadToken) Comp = mod.default;
|
||||
});
|
||||
});
|
||||
</script>
|
||||
|
||||
{#if Comp}
|
||||
<Comp {section} {...rest} />
|
||||
{:else}
|
||||
<div class="px-5 py-6 text-sm text-zinc-400 animate-pulse">Loading…</div>
|
||||
{/if}
|
||||
@@ -1,10 +1,11 @@
|
||||
<script lang="ts">
|
||||
import LazySection from "./LazySection.svelte";
|
||||
import LazyPanel from "../../components/LazyPanel.svelte";
|
||||
import {
|
||||
ALL_SETTINGS_SECTIONS,
|
||||
type SettingsSectionId,
|
||||
type SettingsSectionSharedProps,
|
||||
} from "./shared";
|
||||
import { SECTION_LOADERS } from "./sectionLoaders";
|
||||
import { isPerformanceMode } from "@/seqta/utils/performanceMode";
|
||||
|
||||
let {
|
||||
@@ -12,31 +13,29 @@
|
||||
...rest
|
||||
}: SettingsSectionSharedProps & { activeSection?: string } = $props();
|
||||
|
||||
let mountedSectionCount = $state(ALL_SETTINGS_SECTIONS.length);
|
||||
let mountedSectionCount = $state(1);
|
||||
|
||||
function scheduleIdle(step: () => void) {
|
||||
const delay = isPerformanceMode() ? 64 : 32;
|
||||
const timeout = isPerformanceMode() ? 800 : 500;
|
||||
if (typeof requestIdleCallback === "function") {
|
||||
requestIdleCallback(step, { timeout });
|
||||
} else {
|
||||
setTimeout(step, delay);
|
||||
}
|
||||
}
|
||||
|
||||
$effect(() => {
|
||||
if (activeSection !== "all") {
|
||||
mountedSectionCount = 1;
|
||||
return;
|
||||
}
|
||||
|
||||
mountedSectionCount = 1;
|
||||
if (activeSection !== "all") return;
|
||||
|
||||
let idx = 1;
|
||||
const step = () => {
|
||||
if (idx >= ALL_SETTINGS_SECTIONS.length) return;
|
||||
mountedSectionCount = ++idx;
|
||||
if (typeof requestIdleCallback === "function") {
|
||||
requestIdleCallback(step, { timeout: isPerformanceMode() ? 800 : 500 });
|
||||
} else {
|
||||
setTimeout(step, isPerformanceMode() ? 64 : 32);
|
||||
}
|
||||
scheduleIdle(step);
|
||||
};
|
||||
|
||||
if (typeof requestIdleCallback === "function") {
|
||||
requestIdleCallback(step, { timeout: isPerformanceMode() ? 800 : 500 });
|
||||
} else {
|
||||
setTimeout(step, isPerformanceMode() ? 64 : 32);
|
||||
}
|
||||
scheduleIdle(step);
|
||||
});
|
||||
|
||||
const sectionsToShow = $derived.by((): SettingsSectionId[] => {
|
||||
@@ -52,6 +51,10 @@
|
||||
|
||||
<div class="flex flex-col divide-y divide-zinc-100 dark:divide-zinc-700">
|
||||
{#each sectionsToShow as section (section)}
|
||||
<LazySection {section} {...rest} />
|
||||
<LazyPanel
|
||||
loader={SECTION_LOADERS[section]}
|
||||
remountKey={section}
|
||||
props={{ section, ...rest }}
|
||||
/>
|
||||
{/each}
|
||||
</div>
|
||||
@@ -138,11 +138,6 @@ export function syncPerformanceModeEffects(): void {
|
||||
applyPerformanceModeClass();
|
||||
applyPerformanceModeTransparency();
|
||||
applyPerformanceModeSidebarLook();
|
||||
|
||||
if (isPerformanceMode()) {
|
||||
removeAnimatedBackgroundLayers();
|
||||
}
|
||||
|
||||
void syncPerformanceModePlugins();
|
||||
}
|
||||
|
||||
|
||||
@@ -29,26 +29,7 @@ export function animatePopupOpen(background: HTMLElement): void {
|
||||
}
|
||||
|
||||
export function animatePopupClose(background: HTMLElement): Promise<void> {
|
||||
if (!useCssPopupAnimation()) {
|
||||
return Promise.resolve();
|
||||
}
|
||||
|
||||
return new Promise((resolve) => {
|
||||
let settled = false;
|
||||
const finish = () => {
|
||||
if (settled) return;
|
||||
settled = true;
|
||||
background.removeEventListener("transitionend", onEnd);
|
||||
resolve();
|
||||
};
|
||||
|
||||
const onEnd = (event: TransitionEvent) => {
|
||||
if (event.target !== background || event.propertyName !== "opacity") return;
|
||||
finish();
|
||||
};
|
||||
|
||||
background.addEventListener("transitionend", onEnd);
|
||||
background.classList.remove(OPEN_CLASS);
|
||||
window.setTimeout(finish, CLOSE_FALLBACK_MS);
|
||||
});
|
||||
if (!useCssPopupAnimation()) return Promise.resolve();
|
||||
background.classList.remove(OPEN_CLASS);
|
||||
return new Promise((resolve) => window.setTimeout(resolve, CLOSE_FALLBACK_MS));
|
||||
}
|
||||
Reference in new issue
Block a user