From ffeb68ef17c3298e69f35eb70f92d75c1cc04585 Mon Sep 17 00:00:00 2001 From: Paul Spenke Date: Sat, 21 Feb 2026 17:19:23 +0100 Subject: [PATCH] Add `useSettings` composable for managing and persisting settings --- src/composables/useSettings.ts | 63 ++++++++++++++++++++++++++++++++++ 1 file changed, 63 insertions(+) create mode 100644 src/composables/useSettings.ts diff --git a/src/composables/useSettings.ts b/src/composables/useSettings.ts new file mode 100644 index 0000000..9b66ae3 --- /dev/null +++ b/src/composables/useSettings.ts @@ -0,0 +1,63 @@ +import { ref, watch } from 'vue'; +import { useStore } from './useStore.ts'; +import { useCrypto } from './useCrypto.ts'; + +export type Settings = { + username: string, + password: string, +} + +const settingsDefault: Settings = { + username: '', + password: '', +}; + +export function useSettings() { + const { setValue, getValue } = useStore(); + const { encrypt, decrypt } = useCrypto(); + const settings = ref({ ...settingsDefault }); + + const loadSettings = async () => { + const readSettings = await getValue('settings'); + if (!readSettings) { + settings.value = { ...settingsDefault }; + return; + } + + let password = readSettings.password ?? ''; + if (password) { + try { + password = decrypt(password); + } catch (error) { + console.warn('Failed to decrypt stored password:', error); + } + } + + settings.value = { + username: readSettings.username ?? '', + password, + }; + }; + + const saveSettings = async () => { + const encryptedPassword = settings.value.password + ? encrypt(settings.value.password) + : ''; + + await setValue('settings', { + username: settings.value.username, + password: encryptedPassword, + }); + }; + + watch(settings, () => { + void saveSettings(); + }, { deep: true }); + + void loadSettings(); + + return { + settings, + loadSettings, + }; +}