diff --git a/src/interface/components/themes/BackgroundSelector.svelte b/src/interface/components/themes/BackgroundSelector.svelte index ec60e6c8..85b73da5 100644 --- a/src/interface/components/themes/BackgroundSelector.svelte +++ b/src/interface/components/themes/BackgroundSelector.svelte @@ -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(null); - let notice = $state(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 { 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 { 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 { @@ -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 @@
- {#if notice} + {#if feedback}
- {notice} -
- {/if} - - {#if error} - {/if} @@ -207,11 +164,6 @@
{#if !isEditMode} - {#if uploading} -
-
-
- {/if} {/if} {#each imageBackgrounds as bg (bg.id)} {#if bg.url} diff --git a/src/interface/hooks/BackgroundDataLoader.ts b/src/interface/hooks/BackgroundDataLoader.ts index df130eee..d164b638 100644 --- a/src/interface/hooks/BackgroundDataLoader.ts +++ b/src/interface/hooks/BackgroundDataLoader.ts @@ -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 | null = null; -function promisifyRequest(request: IDBRequest): Promise { +function req(request: IDBRequest): Promise { return new Promise((resolve, reject) => { request.onsuccess = () => resolve(request.result); request.onerror = () => reject(request.error); }); } -function waitForTransaction(tx: IDBTransaction): Promise { +function txDone(tx: IDBTransaction): Promise { return new Promise((resolve, reject) => { tx.oncomplete = () => resolve(); tx.onerror = () => reject(tx.error); - tx.onabort = () => reject(tx.error); }); } -function openDatabaseInternal(): Promise { +export function openDatabase(): Promise { 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( - mode: IDBTransactionMode, - run: (store: IDBObjectStore) => Promise, -): Promise { - 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 { - return openDatabaseInternal(); -} - export async function readAllData(): Promise { - return withStore("readonly", async (store) => { - const items: BackgroundRecord[] = []; - - await new Promise((resolve, reject) => { - const request = store.openCursor(); - - request.onsuccess = () => { - const cursor = request.result; - if (!cursor) { - resolve(); - return; - } - - const value = cursor.value as Partial | 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 { - 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 { - 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 { - 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 { - 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 { - 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; } diff --git a/src/interface/pages/settings/LazySection.svelte b/src/interface/pages/settings/LazySection.svelte deleted file mode 100644 index 39c156c1..00000000 --- a/src/interface/pages/settings/LazySection.svelte +++ /dev/null @@ -1,28 +0,0 @@ - - -{#if Comp} - -{:else} -
Loading…
-{/if} diff --git a/src/interface/pages/settings/SettingsBody.svelte b/src/interface/pages/settings/SettingsBody.svelte index f634ba96..ee6da3bb 100644 --- a/src/interface/pages/settings/SettingsBody.svelte +++ b/src/interface/pages/settings/SettingsBody.svelte @@ -1,10 +1,11 @@