Add useSettings composable for managing and persisting settings

This commit is contained in:
2026-02-21 17:19:23 +01:00
parent 951905b33c
commit ffeb68ef17

View File

@@ -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<Settings>({ ...settingsDefault });
const loadSettings = async () => {
const readSettings = await getValue<Settings>('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>('settings', {
username: settings.value.username,
password: encryptedPassword,
});
};
watch(settings, () => {
void saveSettings();
}, { deep: true });
void loadSettings();
return {
settings,
loadSettings,
};
}