Privacy-first password manager with built-in email aliasing. Fully encrypted and self-hostable.
Linting refactor hooks (#771)
Leendert de Borst331874885325
diff --git a/apps/mobile-app/components/themed/ThemedSafeAreaView.tsx b/apps/mobile-app/components/themed/ThemedSafeAreaView.tsxindex 751b15617..55de3919e 100644--- a/apps/mobile-app/components/themed/ThemedSafeAreaView.tsx+++ b/apps/mobile-app/components/themed/ThemedSafeAreaView.tsx@@ -1,10 +1,8 @@import { SafeAreaView, StyleProp, ViewStyle } from 'react-native';-import { useThemeColor } from '@/hooks/useThemeColor';+import { useColors } from '@/hooks/useColorScheme';type ThemedSafeAreaViewProps = {- lightColor?: string;- darkColor?: string;style?: StyleProp<ViewStyle>;children?: React.ReactNode;};@@ -13,17 +11,15 @@ type ThemedSafeAreaViewProps = {* Themed safe area view component.*/export function ThemedSafeAreaView({- lightColor,- darkColor,style,children,...otherProps}: ThemedSafeAreaViewProps): React.ReactNode {- const backgroundColor = useThemeColor({ light: lightColor, dark: darkColor }, 'background');+ const colors = useColors();return (<SafeAreaView- style={[{ backgroundColor }, style]}+ style={[{ backgroundColor: colors.background }, style]}{...otherProps}>{children}diff --git a/apps/mobile-app/components/themed/ThemedView.tsx b/apps/mobile-app/components/themed/ThemedView.tsxindex 75911fb93..2999f42b9 100644--- a/apps/mobile-app/components/themed/ThemedView.tsx+++ b/apps/mobile-app/components/themed/ThemedView.tsx@@ -1,17 +1,14 @@import { View, type ViewProps } from 'react-native';-import { useThemeColor } from '@/hooks/useThemeColor';+import { useColors } from '@/hooks/useColorScheme';-export type ThemedViewProps = ViewProps & {- lightColor?: string;- darkColor?: string;-};+export type ThemedViewProps = ViewProps;/*** Themed view component.*/-export function ThemedView({ style, lightColor, darkColor, ...otherProps }: ThemedViewProps): React.ReactNode {- const backgroundColor = useThemeColor({ light: lightColor, dark: darkColor }, 'background');+export function ThemedView({ style, ...otherProps }: ThemedViewProps): React.ReactNode {+ const colors = useColors();- return <View style={[{ backgroundColor }, style]} {...otherProps} />;+ return <View style={[{ backgroundColor: colors.background }, style]} {...otherProps} />;}diff --git a/apps/mobile-app/hooks/useColorScheme.ts b/apps/mobile-app/hooks/useColorScheme.tsindex 1adbe3f04..7452fe9bb 100644--- a/apps/mobile-app/hooks/useColorScheme.ts+++ b/apps/mobile-app/hooks/useColorScheme.ts@@ -1,7 +1,8 @@import { Appearance } from 'react-native';-import React from 'react';+import { useEffect, useState } from 'react';import _ from 'lodash';-import { Colors } from '@/constants/Colors';++import { Colors, ThemeColors } from '@/constants/Colors';export type ColorSchemeName = 'light' | 'dark';@@ -14,36 +15,39 @@ export type ColorSchemeName = 'light' | 'dark';** @returns The color scheme of the device.*/-export const useColorScheme = (delay = 150) => {- const [colorScheme, setColorScheme] = React.useState<ColorSchemeName>(+export const useColorScheme = (delay = 150): ColorSchemeName => {+ const [colorScheme, setColorScheme] = useState<ColorSchemeName>(Appearance.getColorScheme() as ColorSchemeName);- const onColorSchemeChange = React.useCallback(- _.throttle(++ useEffect(() => {+ const throttledHandler = _.throttle((preferences: { colorScheme: string | null | undefined }) => {if (preferences.colorScheme) {setColorScheme(preferences.colorScheme as ColorSchemeName);}},delay,- {- leading: false,- }- ),- []- );- React.useEffect(() => {- const subscription = Appearance.addChangeListener(onColorSchemeChange);- return () => {- onColorSchemeChange.cancel();+ { leading: false }+ );++ const subscription = Appearance.addChangeListener(throttledHandler);++ return () : void => {+ throttledHandler.cancel();subscription.remove();};- }, []);+ }, [delay]);+return colorScheme;};-// Simple hook that returns the current theme's colors-export const useColors = () => {+/**+ * Get the colors for the current theme.+ *+ * @returns The colors for the current theme.+ */+export const useColors = () : ThemeColors => {const colorScheme = useColorScheme();- return Colors[colorScheme ?? 'light'];+ return Colors[colorScheme ?? 'light'] as ThemeColors;};diff --git a/apps/mobile-app/hooks/useColorScheme.web.ts b/apps/mobile-app/hooks/useColorScheme.web.tsindex 7eb1c1b70..23d3fc9f6 100644--- a/apps/mobile-app/hooks/useColorScheme.web.ts+++ b/apps/mobile-app/hooks/useColorScheme.web.ts@@ -1,10 +1,12 @@import { useEffect, useState } from 'react';import { useColorScheme as useRNColorScheme } from 'react-native';+type ColorSchemeName = 'light' | 'dark';+/*** To support static rendering, this value needs to be re-calculated on the client side for web*/-export function useColorScheme() {+export function useColorScheme() : ColorSchemeName {const [hasHydrated, setHasHydrated] = useState(false);useEffect(() => {@@ -14,7 +16,7 @@ export function useColorScheme() {const colorScheme = useRNColorScheme();if (hasHydrated) {- return colorScheme;+ return colorScheme as ColorSchemeName;}return 'light';diff --git a/apps/mobile-app/hooks/useThemeColor.ts b/apps/mobile-app/hooks/useThemeColor.tsindex 0608e7315..a41914a57 100644--- a/apps/mobile-app/hooks/useThemeColor.ts+++ b/apps/mobile-app/hooks/useThemeColor.ts@@ -6,10 +6,17 @@import { Colors } from '@/constants/Colors';import { useColorScheme } from '@/hooks/useColorScheme';+/**+ * Get the color for the current theme.+ *+ * @param props - The props to get the color from.+ * @param colorName - The name of the color to get.+ * @returns The color for the current theme.+ */export function useThemeColor(props: { light?: string; dark?: string },colorName: keyof typeof Colors.light & keyof typeof Colors.dark-) {+) : string {const theme = useColorScheme() ?? 'light';const colorFromProps = props[theme];diff --git a/apps/mobile-app/hooks/useVaultMutate.ts b/apps/mobile-app/hooks/useVaultMutate.tsindex 906329596..5f330e284 100644--- a/apps/mobile-app/hooks/useVaultMutate.ts+++ b/apps/mobile-app/hooks/useVaultMutate.ts@@ -1,22 +1,30 @@import { useCallback, useState } from 'react';+import Toast from 'react-native-toast-message';++import { useVaultSync } from '@/hooks/useVaultSync';import { useAuth } from '@/context/AuthContext';import { useDb } from '@/context/DbContext';import { useWebApi } from '@/context/WebApiContext';-import { useVaultSync } from './useVaultSync';import NativeVaultManager from '@/specs/NativeVaultManager';-import Toast from 'react-native-toast-message';-interface VaultPostResponse {+type VaultPostResponse = {status: number;newRevisionNumber: number;}-interface VaultMutationOptions {+type VaultMutationOptions = {onSuccess?: () => void;onError?: (error: Error) => void;}-export function useVaultMutate() {+/**+ * Hook to execute a vault mutation.+ */+export function useVaultMutate() : {+ executeVaultMutation: (operation: () => Promise<void>, options?: VaultMutationOptions) => Promise<void>;+ isLoading: boolean;+ syncStatus: string;+ } {const [isLoading, setIsLoading] = useState(false);const [syncStatus, setSyncStatus] = useState('');const authContext = useAuth();@@ -24,51 +32,13 @@ export function useVaultMutate() {const webApi = useWebApi();const { syncVault } = useVaultSync();- const executeVaultMutation = useCallback(async (- operation: () => Promise<void>,- options: VaultMutationOptions = {}- ) => {- try {- setIsLoading(true);- setSyncStatus('Checking for vault updates...');-- await syncVault({- onStatus: (message) => setSyncStatus(message),- onSuccess: async (hasNewVault) => {- if (hasNewVault) {- console.log('Vault was changed, but has now been reloaded so we can continue with the operation.');- }- await executeOperation(operation, options);- },- onError: (error) => {- Toast.show({- type: 'error',- text1: 'Failed to sync vault',- text2: error,- position: 'bottom'- });- options.onError?.(new Error(error));- }- });- } catch (error) {- console.error('Error during vault mutation:', error);- Toast.show({- type: 'error',- text1: 'Operation failed',- text2: error instanceof Error ? error.message : 'Unknown error',- position: 'bottom'- });- options.onError?.(error instanceof Error ? error : new Error('Unknown error'));- } finally {- setIsLoading(false);- setSyncStatus('');- }- }, [syncVault]);-- const executeOperation = async (+ /**+ * Execute the provided operation (e.g. create/update/delete credential)+ */+ const executeOperation = useCallback(async (operation: () => Promise<void>,options: VaultMutationOptions- ) => {+ ) : Promise<void> => {setSyncStatus('Saving changes to vault...');// Execute the provided operation (e.g. create/update/delete credential)@@ -78,7 +48,6 @@ export function useVaultMutate() {const currentRevision = await NativeVaultManager.getCurrentVaultRevisionNumber();// Get the encrypted database- console.log('Getting encrypted database new version');const encryptedDb = await NativeVaultManager.getEncryptedDatabase();if (!encryptedDb) {throw new Error('Failed to get encrypted database');@@ -118,8 +87,6 @@ export function useVaultMutate() {// Upload to serverconst response = await webApi.post<typeof newVault, VaultPostResponse>('Vault', newVault);- console.log('Vault upload response:', response);-if (response.status === 0) {await NativeVaultManager.setCurrentVaultRevisionNumber(response.newRevisionNumber);options.onSuccess?.();@@ -128,7 +95,58 @@ export function useVaultMutate() {} else {throw new Error('Failed to upload vault to server');}- };+ }, [dbContext, authContext, webApi]);++ const executeVaultMutation = useCallback(async (+ operation: () => Promise<void>,+ options: VaultMutationOptions = {}+ ) => {+ try {+ setIsLoading(true);+ setSyncStatus('Checking for vault updates...');++ await syncVault({+ /**+ * Update the sync status+ */+ onStatus: (message) => setSyncStatus(message),+ /**+ * Execute the operation if the vault has been updated+ */+ onSuccess: async (hasNewVault) => {+ if (hasNewVault) {+ // Vault was changed, but has now been reloaded so we can continue with the operation.+ }++ await executeOperation(operation, options);+ },+ /**+ * Handle errors+ */+ onError: (error) => {+ Toast.show({+ type: 'error',+ text1: 'Failed to sync vault',+ text2: error,+ position: 'bottom'+ });+ options.onError?.(new Error(error));+ }+ });+ } catch (error) {+ console.error('Error during vault mutation:', error);+ Toast.show({+ type: 'error',+ text1: 'Operation failed',+ text2: error instanceof Error ? error.message : 'Unknown error',+ position: 'bottom'+ });+ options.onError?.(error instanceof Error ? error : new Error('Unknown error'));+ } finally {+ setIsLoading(false);+ setSyncStatus('');+ }+ }, [syncVault, executeOperation]);return {executeVaultMutation,diff --git a/apps/mobile-app/hooks/useVaultSync.ts b/apps/mobile-app/hooks/useVaultSync.tsindex e3ce7e7fa..36495aaf6 100644--- a/apps/mobile-app/hooks/useVaultSync.ts+++ b/apps/mobile-app/hooks/useVaultSync.ts@@ -1,11 +1,14 @@import { useCallback } from 'react';import AsyncStorage from '@react-native-async-storage/async-storage';+import { useAuth } from '@/context/AuthContext';import { useDb } from '@/context/DbContext';import { useWebApi } from '@/context/WebApiContext';import { VaultResponse } from '@/utils/types/webapi/VaultResponse';-// Utility function to ensure a minimum time has elapsed for an operation+/**+ * Utility function to ensure a minimum time has elapsed for an operation+ */const withMinimumDelay = async <T>(operation: () => Promise<T>,minDelayMs: number,@@ -26,32 +29,34 @@ const withMinimumDelay = async <T>(return result;};-interface VaultSyncOptions {+type VaultSyncOptions = {initialSync?: boolean;onSuccess?: (hasNewVault: boolean) => void;onError?: (error: string) => void;onStatus?: (message: string) => void;}-export const useVaultSync = () => {+/**+ * Hook to sync the vault with the server.+ */+export const useVaultSync = () : {+ syncVault: (options?: VaultSyncOptions) => Promise<boolean>;+} => {const authContext = useAuth();const dbContext = useDb();const webApi = useWebApi();const syncVault = useCallback(async (options: VaultSyncOptions = {}) => {const { initialSync = false, onSuccess, onError, onStatus } = options;- console.log('syncVault called with initialSync:', initialSync);try {const { isLoggedIn } = await authContext.initializeAuth();if (!isLoggedIn) {- console.log('Vault sync: Not authenticated');+ // Not authenticated, return false immediatelyreturn false;}- console.log('Checking vault updates');-// Update last check timeawait AsyncStorage.setItem('lastVaultCheck', Date.now().toString());@@ -64,7 +69,6 @@ export const useVaultSync = () => {);const statusError = webApi.validateStatusResponse(statusResponse);if (statusError !== null) {- console.log('Vault sync error:', statusError);await webApi.logout(statusError);onError?.(statusError);return false;@@ -74,8 +78,6 @@ export const useVaultSync = () => {const vaultMetadata = await dbContext.getVaultMetadata();const vaultRevisionNumber = vaultMetadata?.vaultRevisionNumber ?? 0;- console.log('Vault revision local:', vaultRevisionNumber);- console.log('Vault revision server:', statusResponse.vaultRevision);if (statusResponse.vaultRevision > vaultRevisionNumber) {onStatus?.('Syncing updated vault');const vaultResponseJson = await withMinimumDelay(@@ -86,23 +88,21 @@ export const useVaultSync = () => {const vaultError = webApi.validateVaultResponse(vaultResponseJson as VaultResponse);if (vaultError) {- console.log('Vault sync error:', vaultError);await webApi.logout(vaultError);onError?.(vaultError);return false;}- console.log('Re-initializing database with new vault');try {await dbContext.initializeDatabase(vaultResponseJson as VaultResponse, null);onSuccess?.(true);return true;- } catch (err) {+ } catch {+ // Vault could not be decrypted, throw an errorthrow new Error('Vault could not be decrypted, if problem persists please logout and login again.');}}- console.log('Vault sync finished: No updates needed');await withMinimumDelay(() => Promise.resolve(onSuccess?.(false)),300,