Skip to content

Privacy-first password manager with built-in email aliasing. Fully encrypted and self-hostable.

Add custom confirm dialog component for Android with native fallback for iOS (#1473)

Leendert de Borst204605edc090
diff --git a/apps/mobile-app/app/(tabs)/emails/[id].tsx b/apps/mobile-app/app/(tabs)/emails/[id].tsx
index 5c632a4a9..f33a3d75e 100644
--- a/apps/mobile-app/app/(tabs)/emails/[id].tsx
+++ b/apps/mobile-app/app/(tabs)/emails/[id].tsx
@@ -5,7 +5,7 @@ import * as FileSystem from 'expo-file-system';
import { useLocalSearchParams, useRouter, useNavigation, Stack } from 'expo-router';
import React, { useEffect, useState, useCallback } from 'react';
import { useTranslation } from 'react-i18next';
-import { StyleSheet, View, ActivityIndicator, Alert, Share, useColorScheme, Linking, Text, TextInput, Platform } from 'react-native';
+import { StyleSheet, View, ActivityIndicator, Share, useColorScheme, Linking, Text, TextInput, Platform } from 'react-native';
import { WebView } from 'react-native-webview';
import type { Item } from '@/utils/dist/core/models/vault';
@@ -15,6 +15,7 @@ import emitter from '@/utils/EventEmitter';
import { useColors } from '@/hooks/useColorScheme';
+import { ConfirmDialog } from '@/components/common/ConfirmDialog';
import { ThemedText } from '@/components/themed/ThemedText';
import { ThemedView } from '@/components/themed/ThemedView';
import { IconSymbol } from '@/components/ui/IconSymbol';
@@ -41,6 +42,7 @@ export default function EmailDetailsScreen() : React.ReactNode {
const [isHtmlView, setHtmlView] = useState(true);
const isDarkMode = useColorScheme() === 'dark';
const [associatedItem, setAssociatedItem] = useState<Item | null>(null);
+ const [showDeleteConfirm, setShowDeleteConfirm] = useState(false);
/**
* Load the email.
@@ -88,40 +90,36 @@ export default function EmailDetailsScreen() : React.ReactNode {
/**
* Handle the delete button press.
*/
- const handleDelete = useCallback(async () : Promise<void> => {
- Alert.alert(
- t('emails.deleteEmail'),
- t('emails.deleteEmailConfirm'),
- [
- {
- text: t('common.cancel'),
- style: 'cancel',
- },
- {
- text: t('common.delete'),
- style: 'destructive',
- /**
- * Handle the delete button press.
- */
- onPress: async () : Promise<void> => {
- try {
- // Delete the email from the server.
- await webApi.delete(`Email/${id}`);
-
- // Refresh the emails list in the index screen.
- emitter.emit('refreshEmails');
-
- // Go back to the emails list screen.
- router.back();
- } catch (err) {
- setError(err instanceof Error ? err.message : t('common.errors.unknownError'));
- }
- },
- },
- ]
- );
+ const handleDelete = useCallback(() : void => {
+ setShowDeleteConfirm(true);
+ }, []);
+
+ /**
+ * Confirm and execute email deletion.
+ */
+ const confirmDelete = useCallback(async () : Promise<void> => {
+ try {
+ // Delete the email from the server.
+ await webApi.delete(`Email/${id}`);
+
+ // Refresh the emails list in the index screen.
+ emitter.emit('refreshEmails');
+
+ // Go back to the emails list screen.
+ router.back();
+ } catch (err) {
+ setError(err instanceof Error ? err.message : t('common.errors.unknownError'));
+ }
+ setShowDeleteConfirm(false);
}, [id, router, webApi, t]);
+ /**
+ * Hide delete confirmation dialog.
+ */
+ const hideDeleteConfirm = useCallback((): void => {
+ setShowDeleteConfirm(false);
+ }, []);
+
/**
* Handle the download attachment button press.
*/
@@ -500,27 +498,48 @@ export default function EmailDetailsScreen() : React.ReactNode {
}
return (
- <ThemedView style={styles.container}>
- <Stack.Screen options={{ title: t('emails.emailDetails') }} />
- {metadataView}
- {emailView}
- {email.attachments && email.attachments.length > 0 && (
- <View style={styles.attachments}>
- <ThemedText style={styles.attachmentsTitle}>{t('emails.attachments')}</ThemedText>
- {email.attachments.map((attachment) => (
- <RobustPressable
- key={attachment.id}
- style={styles.attachment}
- onPress={() => handleDownloadAttachment(attachment)}
- >
- <Ionicons name="attach" size={20} color="#666" />
- <ThemedText style={styles.attachmentName}>
- {attachment.filename} ({Math.ceil(attachment.filesize / 1024)} {t('emails.sizeKB')})
- </ThemedText>
- </RobustPressable>
- ))}
- </View>
- )}
- </ThemedView>
+ <>
+ <ThemedView style={styles.container}>
+ <Stack.Screen options={{ title: t('emails.emailDetails') }} />
+ {metadataView}
+ {emailView}
+ {email.attachments && email.attachments.length > 0 && (
+ <View style={styles.attachments}>
+ <ThemedText style={styles.attachmentsTitle}>{t('emails.attachments')}</ThemedText>
+ {email.attachments.map((attachment) => (
+ <RobustPressable
+ key={attachment.id}
+ style={styles.attachment}
+ onPress={() => handleDownloadAttachment(attachment)}
+ >
+ <Ionicons name="attach" size={20} color="#666" />
+ <ThemedText style={styles.attachmentName}>
+ {attachment.filename} ({Math.ceil(attachment.filesize / 1024)} {t('emails.sizeKB')})
+ </ThemedText>
+ </RobustPressable>
+ ))}
+ </View>
+ )}
+ </ThemedView>
+
+ <ConfirmDialog
+ isVisible={showDeleteConfirm}
+ title={t('emails.deleteEmail')}
+ message={t('emails.deleteEmailConfirm')}
+ buttons={[
+ {
+ text: t('common.cancel'),
+ style: 'cancel',
+ onPress: hideDeleteConfirm,
+ },
+ {
+ text: t('common.delete'),
+ style: 'destructive',
+ onPress: confirmDelete,
+ },
+ ]}
+ onClose={hideDeleteConfirm}
+ />
+ </>
);
}
\ No newline at end of file
diff --git a/apps/mobile-app/app/(tabs)/items/add-edit.tsx b/apps/mobile-app/app/(tabs)/items/add-edit.tsx
index 87a202059..e5f22f221 100644
--- a/apps/mobile-app/app/(tabs)/items/add-edit.tsx
+++ b/apps/mobile-app/app/(tabs)/items/add-edit.tsx
@@ -1,12 +1,12 @@
import { Buffer } from 'buffer';
import MaterialIcons from '@expo/vector-icons/MaterialIcons';
-import { usePreventRemove } from '@react-navigation/native';
+import { usePreventRemove, NavigationAction } from '@react-navigation/native';
import * as Haptics from 'expo-haptics';
import { Stack, useLocalSearchParams, useNavigation, useRouter } from 'expo-router';
import { useState, useEffect, useRef, useCallback, useMemo } from 'react';
import { useTranslation } from 'react-i18next';
-import { StyleSheet, View, Alert, Keyboard, Platform, ScrollView, KeyboardAvoidingView, TouchableOpacity } from 'react-native';
+import { StyleSheet, View, Keyboard, Platform, ScrollView, KeyboardAvoidingView, TouchableOpacity } from 'react-native';
import Toast from 'react-native-toast-message';
import type { Folder } from '@/utils/db/repositories/FolderRepository';
@@ -21,6 +21,7 @@ import { extractServiceNameFromUrl } from '@/utils/UrlUtility';
import { useColors } from '@/hooks/useColorScheme';
import { useVaultMutate } from '@/hooks/useVaultMutate';
+import { ConfirmDialog } from '@/components/common/ConfirmDialog';
import { AddFieldMenu, type OptionalSection } from '@/components/form/AddFieldMenu';
import { AdvancedPasswordField } from '@/components/form/AdvancedPasswordField';
import { EmailDomainField } from '@/components/form/EmailDomainField';
@@ -88,6 +89,10 @@ export default function AddEditItemScreen(): React.ReactNode {
const [passkeyIds, setPasskeyIds] = useState<string[]>([]);
const [passkeyIdsMarkedForDeletion, setPasskeyIdsMarkedForDeletion] = useState<string[]>([]);
const [hasUnsavedChanges, setHasUnsavedChanges] = useState(false);
+ const [showDeleteConfirm, setShowDeleteConfirm] = useState(false);
+ const [showDiscardConfirm, setShowDiscardConfirm] = useState(false);
+ // Store the pending navigation action when usePreventRemove triggers
+ const [pendingNavigationAction, setPendingNavigationAction] = useState<NavigationAction | null>(null);
// Item state
const [item, setItem] = useState<Item | null>(null);
@@ -380,33 +385,12 @@ export default function AddEditItemScreen(): React.ReactNode {
/**
* Prevent accidental dismissal when there are unsaved changes.
+ * Shows custom dialog on Android, stores pending action for later execution.
*/
usePreventRemove(hasUnsavedChanges, ({ data }): void => {
- Alert.alert(
- t('items.unsavedChanges.title'),
- t('items.unsavedChanges.message'),
- [
- {
- text: t('common.cancel'),
- style: 'cancel',
- /**
- * Do nothing
- */
- onPress: (): void => {}
- },
- {
- text: t('items.unsavedChanges.discard'),
- style: 'destructive',
- /**
- * Discard unsaved changes and navigate back
- */
- onPress: (): void => {
- setHasUnsavedChanges(false);
- navigation.dispatch(data.action);
- },
- },
- ]
- );
+ // Store the pending navigation action and show the discard confirm dialog
+ setPendingNavigationAction(data.action);
+ setShowDiscardConfirm(true);
});
/**
@@ -878,80 +862,115 @@ export default function AddEditItemScreen(): React.ReactNode {
/**
* Handle the delete button press.
*/
- const handleDelete = async (): Promise<void> => {
+ const handleDelete = (): void => {
if (!id) {
return;
}
Keyboard.dismiss();
+ setShowDeleteConfirm(true);
+ };
- Alert.alert(
- t('items.deleteItem'),
- t('items.deleteConfirm'),
- [
- {
- text: t('common.cancel'),
- style: "cancel"
- },
- {
- text: t('common.delete'),
- style: "destructive",
- /**
- * Delete the item
- */
- onPress: async (): Promise<void> => {
- await executeVaultMutation(async () => {
- await dbContext.sqliteClient!.items.trash(id);
- });
+ /**
+ * Confirm and execute item deletion.
+ */
+ const confirmDelete = useCallback(async (): Promise<void> => {
+ if (!id) {
+ return;
+ }
- emitter.emit('credentialChanged', id);
+ await executeVaultMutation(async () => {
+ await dbContext.sqliteClient!.items.trash(id);
+ });
- setTimeout(() => {
- Toast.show({
- type: 'success',
- text1: t('items.toasts.itemDeleted'),
- position: 'bottom'
- });
- }, 200);
+ emitter.emit('credentialChanged', id);
- router.back();
- router.back();
- }
- }
- ]
- );
- };
+ setTimeout(() => {
+ Toast.show({
+ type: 'success',
+ text1: t('items.toasts.itemDeleted'),
+ position: 'bottom'
+ });
+ }, 200);
+
+ setShowDeleteConfirm(false);
+ router.back();
+ router.back();
+ }, [id, executeVaultMutation, dbContext.sqliteClient, t, router]);
/**
* Handle cancel button press.
*/
const handleCancel = useCallback((): void => {
if (hasUnsavedChanges) {
- Alert.alert(
- t('items.unsavedChanges.title'),
- t('items.unsavedChanges.message'),
- [
- {
- text: t('common.cancel'),
- style: 'cancel',
- },
- {
- text: t('items.unsavedChanges.discard'),
- style: 'destructive',
- /**
- * Discard unsaved changes and navigate back
- */
- onPress: (): void => {
- setHasUnsavedChanges(false);
- router.back();
- },
- },
- ]
- );
+ setShowDiscardConfirm(true);
} else {
router.back();
}
- }, [hasUnsavedChanges, router, t]);
+ }, [hasUnsavedChanges, router]);
+
+ /**
+ * Confirm discard and navigate back.
+ */
+ const confirmDiscard = useCallback((): void => {
+ setHasUnsavedChanges(false);
+ setShowDiscardConfirm(false);
+
+ // If we have a pending navigation action (from usePreventRemove), dispatch it
+ if (pendingNavigationAction) {
+ navigation.dispatch(pendingNavigationAction);
+ setPendingNavigationAction(null);
+ } else {
+ // Otherwise just go back (from cancel button press)
+ router.back();
+ }
+ }, [router, navigation, pendingNavigationAction]);
+
+ /**
+ * Hide delete confirmation dialog.
+ */
+ const hideDeleteConfirm = useCallback((): void => {
+ setShowDeleteConfirm(false);
+ }, []);
+
+ /**
+ * Hide discard confirmation dialog.
+ */
+ const hideDiscardConfirm = useCallback((): void => {
+ setShowDiscardConfirm(false);
+ }, []);
+
+ /**
+ * Buttons for delete confirmation dialog.
+ */
+ const deleteConfirmButtons = useMemo(() => [
+ {
+ text: t('common.cancel'),
+ style: 'cancel' as const,
+ onPress: hideDeleteConfirm,
+ },
+ {
+ text: t('common.delete'),
+ style: 'destructive' as const,
+ onPress: confirmDelete,
+ },
+ ], [t, hideDeleteConfirm, confirmDelete]);
+
+ /**
+ * Buttons for discard confirmation dialog.
+ */
+ const discardConfirmButtons = useMemo(() => [
+ {
+ text: t('common.cancel'),
+ style: 'cancel' as const,
+ onPress: hideDiscardConfirm,
+ },
+ {
+ text: t('items.unsavedChanges.discard'),
+ style: 'destructive' as const,
+ onPress: confirmDiscard,
+ },
+ ], [t, hideDiscardConfirm, confirmDiscard]);
/**
* Get the top padding for the container.
@@ -1575,6 +1594,22 @@ export default function AddEditItemScreen(): React.ReactNode {
</KeyboardAvoidingView>
</ThemedContainer>
<AliasVaultToast />
+
+ <ConfirmDialog
+ isVisible={showDeleteConfirm}
+ title={t('items.deleteItem')}
+ message={t('items.deleteConfirm')}
+ buttons={deleteConfirmButtons}
+ onClose={hideDeleteConfirm}
+ />
+
+ <ConfirmDialog
+ isVisible={showDiscardConfirm}
+ title={t('items.unsavedChanges.title')}
+ message={t('items.unsavedChanges.message')}
+ buttons={discardConfirmButtons}
+ onClose={hideDiscardConfirm}
+ />
</>
);
}
diff --git a/apps/mobile-app/app/(tabs)/items/folder/[id].tsx b/apps/mobile-app/app/(tabs)/items/folder/[id].tsx
index 25dc287a5..0ba434b4c 100644
--- a/apps/mobile-app/app/(tabs)/items/folder/[id].tsx
+++ b/apps/mobile-app/app/(tabs)/items/folder/[id].tsx
@@ -4,7 +4,7 @@ import * as Haptics from 'expo-haptics';
import { useRouter, useLocalSearchParams } from 'expo-router';
import { useState, useEffect, useCallback, useRef, useMemo } from 'react';
import { useTranslation } from 'react-i18next';
-import { Alert, StyleSheet, Platform, View, Text, TextInput, TouchableOpacity, RefreshControl, FlatList } from 'react-native';
+import { StyleSheet, Platform, View, Text, TextInput, TouchableOpacity, RefreshControl, FlatList } from 'react-native';
import { useSafeAreaInsets } from 'react-native-safe-area-context';
import Toast from 'react-native-toast-message';
@@ -29,6 +29,7 @@ import { RobustPressable } from '@/components/ui/RobustPressable';
import { SkeletonLoader } from '@/components/ui/SkeletonLoader';
import { useApp } from '@/context/AppContext';
import { useDb } from '@/context/DbContext';
+import { useDialog } from '@/context/DialogContext';
/**
* Folder view screen - displays items within a specific folder.
@@ -59,6 +60,7 @@ export default function FolderViewScreen(): React.ReactNode {
const authContext = useApp();
const dbContext = useDb();
+ const { showAlert } = useDialog();
const isAuthenticated = authContext.isLoggedIn;
const isDatabaseAvailable = dbContext.dbAvailable;
@@ -178,11 +180,7 @@ export default function FolderViewScreen(): React.ReactNode {
console.error('Error syncing vault:', error);
setRefreshing(false);
setIsLoadingItems(false);
- Alert.alert(
- t('common.error'),
- error,
- [{ text: t('common.ok'), style: 'default' }]
- );
+ showAlert(t('common.error'), error);
},
/**
* On upgrade required.
@@ -204,7 +202,7 @@ export default function FolderViewScreen(): React.ReactNode {
});
}
}
- }, [syncVault, loadItems, setIsLoadingItems, setRefreshing, authContext, dbContext, router, t]);
+ }, [syncVault, loadItems, setIsLoadingItems, setRefreshing, authContext, dbContext, router, showAlert, t]);
useEffect(() => {
if (!isAuthenticated || !isDatabaseAvailable) {
diff --git a/apps/mobile-app/app/(tabs)/items/index.tsx b/apps/mobile-app/app/(tabs)/items/index.tsx
index 9777078e8..1d80e31b0 100644
--- a/apps/mobile-app/app/(tabs)/items/index.tsx
+++ b/apps/mobile-app/app/(tabs)/items/index.tsx
@@ -4,7 +4,7 @@ import * as Haptics from 'expo-haptics';
import { useRouter, useLocalSearchParams } from 'expo-router';
import { useState, useEffect, useCallback, useRef, useMemo } from 'react';
import { useTranslation } from 'react-i18next';
-import { Alert, StyleSheet, Text, Platform, Animated, TextInput, TouchableOpacity, View, RefreshControl } from 'react-native';
+import { StyleSheet, Text, Platform, Animated, TextInput, TouchableOpacity, View, RefreshControl } from 'react-native';
import { useSafeAreaInsets } from 'react-native-safe-area-context';
import Toast from 'react-native-toast-message';
@@ -20,6 +20,7 @@ import { useVaultMutate } from '@/hooks/useVaultMutate';
import { useVaultSync } from '@/hooks/useVaultSync';
import Logo from '@/assets/images/logo.svg';
+import { ConfirmDialog } from '@/components/common/ConfirmDialog';
import { FolderModal } from '@/components/folders/FolderModal';
import { FolderPill, type FolderWithCount } from '@/components/folders/FolderPill';
import { ItemCard } from '@/components/items/ItemCard';
@@ -93,6 +94,16 @@ export default function ItemsScreen(): React.ReactNode {
// Recently deleted count state
const [recentlyDeletedCount, setRecentlyDeletedCount] = useState(0);
+ // Alert dialog state
+ const [alertConfig, setAlertConfig] = useState<{ title: string; message: string } | null>(null);
+
+ /**
+ * Hide the alert dialog.
+ */
+ const hideAlert = useCallback((): void => {
+ setAlertConfig(null);
+ }, []);
+
const authContext = useApp();
const dbContext = useDb();
@@ -304,11 +315,7 @@ export default function ItemsScreen(): React.ReactNode {
setRefreshing(false);
setIsLoadingItems(false);
- Alert.alert(
- t('common.error'),
- error,
- [{ text: t('common.ok'), style: 'default' }]
- );
+ setAlertConfig({ title: t('common.error'), message: error });
},
/**
* On upgrade required.
@@ -1171,6 +1178,15 @@ export default function ItemsScreen(): React.ReactNode {
onSave={handleCreateFolder}
mode="create"
/>
+
+ {/* Alert dialog */}
+ <ConfirmDialog
+ isVisible={alertConfig !== null}
+ title={alertConfig?.title ?? ''}
+ message={alertConfig?.message ?? ''}
+ buttons={[{ text: t('common.ok'), style: 'default', onPress: hideAlert }]}
+ onClose={hideAlert}
+ />
</ThemedContainer>
);
}
diff --git a/apps/mobile-app/app/(tabs)/settings/identity-generator.tsx b/apps/mobile-app/app/(tabs)/settings/identity-generator.tsx
index b3625aa9e..f43542c3a 100644
--- a/apps/mobile-app/app/(tabs)/settings/identity-generator.tsx
+++ b/apps/mobile-app/app/(tabs)/settings/identity-generator.tsx
@@ -2,7 +2,7 @@ import { Ionicons } from '@expo/vector-icons';
import { useFocusEffect } from 'expo-router';
import { useState, useCallback, useRef, useEffect } from 'react';
import { useTranslation } from 'react-i18next';
-import { StyleSheet, View, Alert, TouchableOpacity } from 'react-native';
+import { StyleSheet, View, TouchableOpacity } from 'react-native';
import { getAvailableAgeRanges, IAgeRangeOption, getAvailableLanguages, ILanguageOption } from '@/utils/dist/core/identity-generator';
@@ -13,6 +13,7 @@ import { ThemedContainer } from '@/components/themed/ThemedContainer';
import { ThemedScrollView } from '@/components/themed/ThemedScrollView';
import { ThemedText } from '@/components/themed/ThemedText';
import { useDb } from '@/context/DbContext';
+import { useDialog } from '@/context/DialogContext';
/**
* Identity Generator Settings screen.
@@ -21,6 +22,7 @@ export default function IdentityGeneratorSettingsScreen(): React.ReactNode {
const colors = useColors();
const { t } = useTranslation();
const dbContext = useDb();
+ const { showAlert } = useDialog();
const { executeVaultMutation } = useVaultMutate();
const [language, setLanguage] = useState<string>('en');
@@ -69,7 +71,7 @@ export default function IdentityGeneratorSettingsScreen(): React.ReactNode {
pendingChanges.current = {};
} catch (error) {
console.error('Error loading identity generator settings:', error);
- Alert.alert(t('common.error'), t('common.errors.unknownError'));
+ showAlert(t('common.error'), t('common.errors.unknownError'));
}
};
@@ -113,7 +115,7 @@ export default function IdentityGeneratorSettingsScreen(): React.ReactNode {
// Execute save without blocking navigation
saveChanges();
};
- }, [dbContext.sqliteClient, t, executeVaultMutation])
+ }, [dbContext.sqliteClient, showAlert, t, executeVaultMutation])
);
/**
diff --git a/apps/mobile-app/app/(tabs)/settings/import-export.tsx b/apps/mobile-app/app/(tabs)/settings/import-export.tsx
index e7cfb95d9..b26f0a8f8 100644
--- a/apps/mobile-app/app/(tabs)/settings/import-export.tsx
+++ b/apps/mobile-app/app/(tabs)/settings/import-export.tsx
@@ -2,7 +2,7 @@ import { Ionicons } from '@expo/vector-icons';
import * as FileSystem from 'expo-file-system';
import * as Sharing from 'expo-sharing';
import { useState } from 'react';
-import { StyleSheet, View, TouchableOpacity, Alert } from 'react-native';
+import { StyleSheet, View, TouchableOpacity } from 'react-native';
import type { Item } from '@/utils/dist/core/models/vault';
import { FieldKey, getFieldValue, itemToCredential } from '@/utils/dist/core/models/vault';
@@ -14,6 +14,7 @@ import { ThemedContainer } from '@/components/themed/ThemedContainer';
import { ThemedScrollView } from '@/components/themed/ThemedScrollView';
import { ThemedText } from '@/components/themed/ThemedText';
import { useDb } from '@/context/DbContext';
+import { useDialog } from '@/context/DialogContext';
/**
* CSV record for Credential objects (matching server format).
@@ -44,6 +45,7 @@ export default function ImportExportScreen(): React.ReactNode {
const colors = useColors();
const { t } = useTranslation();
const dbContext = useDb();
+ const { showAlert, showConfirm } = useDialog();
const [isExporting, setIsExporting] = useState(false);
/**
@@ -183,24 +185,14 @@ export default function ImportExportScreen(): React.ReactNode {
* Show export confirmation dialog.
*/
const showExportConfirmation = (): void => {
- const warningMessage = t('settings.exportWarning');
-
- Alert.alert(
+ showConfirm(
t('settings.exportConfirmTitle'),
- warningMessage,
- [
- { text: t('common.cancel'), style: 'cancel' },
- {
- text: t('common.confirm'),
- style: 'destructive',
- /**
- * Handle export confirmation.
- */
- onPress: (): void => {
- handleExport();
- }
- },
- ]
+ t('settings.exportWarning'),
+ t('common.confirm'),
+ () => {
+ handleExport();
+ },
+ { confirmStyle: 'destructive' }
);
};
@@ -260,10 +252,7 @@ export default function ImportExportScreen(): React.ReactNode {
}
} catch (error) {
console.error('Export error:', error);
- Alert.alert(
- t('common.error'),
- t('common.errors.unknownError')
- );
+ showAlert(t('common.error'), t('common.errors.unknownError'));
} finally {
setIsExporting(false);
}
diff --git a/apps/mobile-app/app/(tabs)/settings/index.tsx b/apps/mobile-app/app/(tabs)/settings/index.tsx
index 4de5df5a1..37e423b6c 100644
--- a/apps/mobile-app/app/(tabs)/settings/index.tsx
+++ b/apps/mobile-app/app/(tabs)/settings/index.tsx
@@ -1,7 +1,7 @@
import { Ionicons } from '@expo/vector-icons';
import { router, useFocusEffect } from 'expo-router';
import { useRef, useState, useCallback } from 'react';
-import { StyleSheet, View, ScrollView, TouchableOpacity, Animated, Platform, Alert, Linking } from 'react-native';
+import { StyleSheet, View, ScrollView, TouchableOpacity, Animated, Platform, Linking } from 'react-native';
import { useSafeAreaInsets } from 'react-native-safe-area-context';
import { useApiUrl } from '@/utils/ApiUrlUtility';
@@ -19,6 +19,7 @@ import { InlineSkeletonLoader } from '@/components/ui/InlineSkeletonLoader';
import { TitleContainer } from '@/components/ui/TitleContainer';
import { UsernameDisplay } from '@/components/ui/UsernameDisplay';
import { useApp } from '@/context/AppContext';
+import { useDialog } from '@/context/DialogContext';
/**
* Settings screen.
@@ -26,6 +27,7 @@ import { useApp } from '@/context/AppContext';
export default function SettingsScreen() : React.ReactNode {
const colors = useColors();
const { t } = useTranslation();
+ const { showAlert, showConfirm } = useDialog();
const insets = useSafeAreaInsets();
const { getAuthMethodDisplayKey, shouldShowAutofillReminder } = useApp();
const { getAutoLockTimeout, getClipboardClearTimeout } = useApp();
@@ -163,47 +165,39 @@ export default function SettingsScreen() : React.ReactNode {
const handleLanguagePress = (): void => {
const isIOS = Platform.OS === 'ios';
- Alert.alert(
+ showConfirm(
t('settings.language'),
t('settings.languageSystemMessage'),
- [
- { text: t('common.cancel'), style: 'cancel' },
- {
- text: t('settings.openSettings'),
- style: 'default',
- /**
- * Open platform-specific settings
- */
- onPress: async (): Promise<void> => {
- if (isIOS) {
- // Open iOS Settings app
- await Linking.openURL('app-settings:');
- } else {
- // Fallback to general locale settings
- try {
- await Linking.openSettings();
- return;
- } catch (error) {
- console.warn('Failed to open general locale settings:', error);
- }
-
- // Fallback to general settings
- try {
- await Linking.openSettings();
- return;
- } catch (error) {
- console.warn('Failed to open general settings:', error);
- }
+ t('settings.openSettings'),
+ async (): Promise<void> => {
+ if (isIOS) {
+ // Open iOS Settings app
+ await Linking.openURL('app-settings:');
+ } else {
+ // Fallback to general locale settings
+ try {
+ await Linking.openSettings();
+ return;
+ } catch (error) {
+ console.warn('Failed to open general locale settings:', error);
+ }
- // Final fallback - show manual instructions
- Alert.alert(
- t('common.error') ?? 'Error',
- 'Unable to open device settings. Please manually navigate to the app settings and change the language.'
- );
- }
+ // Fallback to general settings
+ try {
+ await Linking.openSettings();
+ return;
+ } catch (error) {
+ console.warn('Failed to open general settings:', error);
}
+
+ // Final fallback - show manual instructions
+ showAlert(
+ t('common.error') ?? 'Error',
+ 'Unable to open device settings. Please manually navigate to the app settings and change the language.'
+ );
}
- ]
+ },
+ { cancelText: t('common.cancel') }
);
};
diff --git a/apps/mobile-app/app/(tabs)/settings/mobile-unlock/[id].tsx b/apps/mobile-app/app/(tabs)/settings/mobile-unlock/[id].tsx
index 52299606d..cbf3c66ee 100644
--- a/apps/mobile-app/app/(tabs)/settings/mobile-unlock/[id].tsx
+++ b/apps/mobile-app/app/(tabs)/settings/mobile-unlock/[id].tsx
@@ -1,6 +1,6 @@
import { router, useLocalSearchParams } from 'expo-router';
import { useState, useEffect } from 'react';
-import { View, Alert, StyleSheet } from 'react-native';
+import { View, StyleSheet } from 'react-native';
import { useSafeAreaInsets } from 'react-native-safe-area-context';
import { VaultUnlockHelper } from '@/utils/VaultUnlockHelper';
@@ -14,6 +14,7 @@ import { ThemedContainer } from '@/components/themed/ThemedContainer';
import { ThemedScrollView } from '@/components/themed/ThemedScrollView';
import { ThemedText } from '@/components/themed/ThemedText';
import { UsernameDisplay } from '@/components/ui/UsernameDisplay';
+import { useDialog } from '@/context/DialogContext';
import { useWebApi } from '@/context/WebApiContext';
import NativeVaultManager from '@/specs/NativeVaultManager';
@@ -23,6 +24,7 @@ import NativeVaultManager from '@/specs/NativeVaultManager';
export default function MobileUnlockConfirmScreen() : React.ReactNode {
const colors = useColors();
const { t } = useTranslation();
+ const { showAlert } = useDialog();
const webApi = useWebApi();
const insets = useSafeAreaInsets();
const { id } = useLocalSearchParams();
@@ -35,19 +37,7 @@ export default function MobileUnlockConfirmScreen() : React.ReactNode {
*/
useEffect(() => {
if (!id) {
- Alert.alert(
- t('common.error'),
- t('common.errors.unknownErrorTryAgain'),
- [
- {
- text: t('common.ok'),
- /**
- * Navigate back to settings.
- */
- onPress: (): void => router.back(),
- },
- ]
- );
+ showAlert(t('common.error'), t('common.errors.unknownErrorTryAgain'), () => router.back());
return;
}
@@ -60,19 +50,7 @@ export default function MobileUnlockConfirmScreen() : React.ReactNode {
const isVersionSupported = await NativeVaultManager.isServerVersionGreaterThanOrEqualTo('0.25.0');
if (!isVersionSupported) {
- Alert.alert(
- t('common.error'),
- t('common.errors.serverVersionTooOld'),
- [
- {
- text: t('common.ok'),
- /**
- * Navigate back to settings.
- */
- onPress: (): void => router.back(),
- },
- ]
- );
+ showAlert(t('common.error'), t('common.errors.serverVersionTooOld'), () => router.back());
return;
}
@@ -92,24 +70,12 @@ export default function MobileUnlockConfirmScreen() : React.ReactNode {
errorMsg = t('settings.qrScanner.mobileLogin.requestExpired');
}
- Alert.alert(
- t('common.error'),
- errorMsg,
- [
- {
- text: t('common.ok'),
- /**
- * Navigate back to settings.
- */
- onPress: (): void => router.back(),
- },
- ]
- );
+ showAlert(t('common.error'), errorMsg, () => router.back());
}
};
validateRequest();
- }, [id, webApi, t]);
+ }, [id, webApi, showAlert, t]);
/**
* Handle mobile login QR code.
@@ -191,10 +157,7 @@ export default function MobileUnlockConfirmScreen() : React.ReactNode {
await handleMobileLogin(id as string);
} catch (error) {
console.error('Authentication or QR code processing error:', error);
- Alert.alert(
- t('common.error'),
- error instanceof Error ? error.message : t('common.errors.unknownError')
- );
+ showAlert(t('common.error'), error instanceof Error ? error.message : t('common.errors.unknownError'));
} finally {
setIsProcessing(false);
}
diff --git a/apps/mobile-app/app/(tabs)/settings/password-generator.tsx b/apps/mobile-app/app/(tabs)/settings/password-generator.tsx
index 05fda0c0d..d3cfe1364 100644
--- a/apps/mobile-app/app/(tabs)/settings/password-generator.tsx
+++ b/apps/mobile-app/app/(tabs)/settings/password-generator.tsx
@@ -3,7 +3,7 @@ import Slider from '@react-native-community/slider';
import { useFocusEffect } from 'expo-router';
import { useState, useCallback, useRef } from 'react';
import { useTranslation } from 'react-i18next';
-import { StyleSheet, View, Alert, TouchableOpacity, Switch, Platform } from 'react-native';
+import { StyleSheet, View, TouchableOpacity, Switch, Platform } from 'react-native';
import type { PasswordSettings } from '@/utils/dist/core/models/vault';
import { CreatePasswordGenerator } from '@/utils/dist/core/password-generator';
@@ -15,6 +15,7 @@ import { ThemedContainer } from '@/components/themed/ThemedContainer';
import { ThemedScrollView } from '@/components/themed/ThemedScrollView';
import { ThemedText } from '@/components/themed/ThemedText';
import { useDb } from '@/context/DbContext';
+import { useDialog } from '@/context/DialogContext';
/**
* Password Generator Settings screen.
@@ -23,6 +24,7 @@ export default function PasswordGeneratorSettingsScreen(): React.ReactNode {
const colors = useColors();
const { t } = useTranslation();
const dbContext = useDb();
+ const { showAlert } = useDialog();
const { executeVaultMutation } = useVaultMutate();
const [settings, setSettings] = useState<PasswordSettings | null>(null);
@@ -76,7 +78,7 @@ export default function PasswordGeneratorSettingsScreen(): React.ReactNode {
console.debug('Settings loaded and initialized');
} catch (error) {
console.error('Error loading password generator settings:', error);
- Alert.alert(t('common.error'), t('common.errors.unknownError'));
+ showAlert(t('common.error'), t('common.errors.unknownError'));
}
};
@@ -110,7 +112,7 @@ export default function PasswordGeneratorSettingsScreen(): React.ReactNode {
console.error('Error saving password generator settings:', error);
});
};
- }, [dbContext.sqliteClient, t, executeVaultMutation])
+ }, [dbContext.sqliteClient, showAlert, t, executeVaultMutation])
);
/**
diff --git a/apps/mobile-app/app/(tabs)/settings/qr-scanner.tsx b/apps/mobile-app/app/(tabs)/settings/qr-scanner.tsx
index 278139892..ac7985a14 100644
--- a/apps/mobile-app/app/(tabs)/settings/qr-scanner.tsx
+++ b/apps/mobile-app/app/(tabs)/settings/qr-scanner.tsx
@@ -1,6 +1,6 @@
import { Href, router, useLocalSearchParams } from 'expo-router';
import { useEffect, useCallback, useRef } from 'react';
-import { View, StyleSheet, Platform, Alert } from 'react-native';
+import { View, StyleSheet, Platform } from 'react-native';
import { useColors } from '@/hooks/useColorScheme';
import { useTranslation } from '@/hooks/useTranslation';
@@ -8,6 +8,7 @@ import { useTranslation } from '@/hooks/useTranslation';
import LoadingIndicator from '@/components/LoadingIndicator';
import { ThemedContainer } from '@/components/themed/ThemedContainer';
import { ThemedText } from '@/components/themed/ThemedText';
+import { useDialog } from '@/context/DialogContext';
import NativeVaultManager from '@/specs/NativeVaultManager';
// QR Code type prefixes
@@ -53,6 +54,7 @@ function parseQRCode(data: string): ScannedQRCode {
export default function QRScannerScreen() : React.ReactNode {
const colors = useColors();
const { t } = useTranslation();
+ const { showAlert } = useDialog();
const { url } = useLocalSearchParams<{ url?: string }>();
const hasProcessedUrl = useRef(false);
const processedUrls = useRef(new Set<string>());
@@ -109,16 +111,9 @@ export default function QRScannerScreen() : React.ReactNode {
}
} catch (error) {
console.error('QR scan error:', error);
- Alert.alert(
- t('common.error'),
- 'Failed to scan QR code',
- [{ text: t('common.ok'), /**
- * Navigate back.
- */
- onPress: (): void => router.back() }]
- );
+ showAlert(t('common.error'), 'Failed to scan QR code', () => router.back());
}
- }, [handleQRCodeScanned, t]);
+ }, [handleQRCodeScanned, showAlert, t]);
/**
* Reset hasProcessedUrl when URL changes to allow processing new URLs.
diff --git a/apps/mobile-app/app/(tabs)/settings/security/active-sessions.tsx b/apps/mobile-app/app/(tabs)/settings/security/active-sessions.tsx
index d4d32af0a..4482e883c 100644
--- a/apps/mobile-app/app/(tabs)/settings/security/active-sessions.tsx
+++ b/apps/mobile-app/app/(tabs)/settings/security/active-sessions.tsx
@@ -1,7 +1,7 @@
import * as Haptics from 'expo-haptics';
import { useState, useEffect, useCallback } from 'react';
import { useTranslation } from 'react-i18next';
-import { StyleSheet, View, TouchableOpacity, Alert, RefreshControl, Platform } from 'react-native';
+import { StyleSheet, View, TouchableOpacity, RefreshControl, Platform } from 'react-native';
import Toast from 'react-native-toast-message';
import type { RefreshToken } from '@/utils/dist/core/models/webapi';
@@ -13,6 +13,7 @@ import { ThemedContainer } from '@/components/themed/ThemedContainer';
import { ThemedScrollView } from '@/components/themed/ThemedScrollView';
import { ThemedText } from '@/components/themed/ThemedText';
import { SkeletonLoader } from '@/components/ui/SkeletonLoader';
+import { useDialog } from '@/context/DialogContext';
import { useWebApi } from '@/context/WebApiContext';
/**
* Active sessions screen.
@@ -21,6 +22,7 @@ export default function ActiveSessionsScreen() : React.ReactNode {
const colors = useColors();
const webApi = useWebApi();
const { t } = useTranslation();
+ const { showAlert, showConfirm } = useDialog();
const [refreshTokens, setRefreshTokens] = useState<RefreshToken[]>([]);
const [isLoading, setIsLoading] = useMinDurationLoading(true, 200);
@@ -90,49 +92,41 @@ export default function ActiveSessionsScreen() : React.ReactNode {
const response = await webApi.getActiveSessions();
setRefreshTokens(response);
} catch {
- Alert.alert(t('common.error'), t('settings.securitySettings.activeSessions.failedToLoad'));
+ showAlert(t('common.error'), t('settings.securitySettings.activeSessions.failedToLoad'));
} finally {
setIsLoading(false);
}
- }, [webApi, setIsLoading, setRefreshTokens, t]);
+ }, [webApi, setIsLoading, setRefreshTokens, showAlert, t]);
/**
* Handle the revoke session action.
*/
const handleRevokeSession = async (sessionId: string) : Promise<void> => {
- Alert.alert(
+ showConfirm(
t('settings.securitySettings.activeSessions.revokeSession'),
t('settings.securitySettings.activeSessions.revokeConfirmation'),
- [
- { text: t('common.cancel'), style: 'cancel' },
- {
- text: t('settings.securitySettings.activeSessions.revoke'),
- style: 'destructive',
- /**
- * Revoke the session and refresh the sessions.
- */
- onPress: async () : Promise<void> => {
- try {
- await webApi.revokeSession(sessionId);
- await loadSessions();
+ t('settings.securitySettings.activeSessions.revoke'),
+ async () : Promise<void> => {
+ try {
+ await webApi.revokeSession(sessionId);
+ await loadSessions();
- // Show success toast
- Toast.show({
- text1: t('settings.securitySettings.activeSessions.sessionRevoked'),
- type: 'success',
- position: 'bottom',
- });
- } catch {
- // Show error toast
- Toast.show({
- text1: t('settings.securitySettings.activeSessions.failedToRevoke'),
- type: 'error',
- position: 'bottom',
- });
- }
- },
- },
- ]
+ // Show success toast
+ Toast.show({
+ text1: t('settings.securitySettings.activeSessions.sessionRevoked'),
+ type: 'success',
+ position: 'bottom',
+ });
+ } catch {
+ // Show error toast
+ Toast.show({
+ text1: t('settings.securitySettings.activeSessions.failedToRevoke'),
+ type: 'error',
+ position: 'bottom',
+ });
+ }
+ },
+ { confirmStyle: 'destructive' }
);
};
diff --git a/apps/mobile-app/app/(tabs)/settings/security/change-password.tsx b/apps/mobile-app/app/(tabs)/settings/security/change-password.tsx
index e5e01a4d5..78e4eac0a 100644
--- a/apps/mobile-app/app/(tabs)/settings/security/change-password.tsx
+++ b/apps/mobile-app/app/(tabs)/settings/security/change-password.tsx
@@ -1,7 +1,7 @@
import { router } from 'expo-router';
import { useState } from 'react';
import { useTranslation } from 'react-i18next';
-import { StyleSheet, View, Alert, KeyboardAvoidingView, Platform } from 'react-native';
+import { StyleSheet, View, KeyboardAvoidingView, Platform } from 'react-native';
import { useColors } from '@/hooks/useColorScheme';
import { useVaultMutate } from '@/hooks/useVaultMutate';
@@ -14,6 +14,7 @@ import { ThemedText } from '@/components/themed/ThemedText';
import { ThemedTextInput } from '@/components/themed/ThemedTextInput';
import { UsernameDisplay } from '@/components/ui/UsernameDisplay';
import { useAuth } from '@/context/AuthContext';
+import { useDialog } from '@/context/DialogContext';
/**
* Change password screen.
@@ -24,6 +25,7 @@ export default function ChangePasswordScreen(): React.ReactNode {
const authContext = useAuth();
const { executeVaultPasswordChange, syncStatus } = useVaultMutate();
const { t } = useTranslation();
+ const { showAlert } = useDialog();
const [currentPassword, setCurrentPassword] = useState('');
const [newPassword, setNewPassword] = useState('');
@@ -65,17 +67,17 @@ export default function ChangePasswordScreen(): React.ReactNode {
*/
const handleSubmit = async (): Promise<void> => {
if (!currentPassword || !newPassword || !confirmPassword) {
- Alert.alert(t('common.error'), t('settings.securitySettings.changePassword.fillAllFields'));
+ showAlert(t('common.error'), t('settings.securitySettings.changePassword.fillAllFields'));
return;
}
if (newPassword !== confirmPassword) {
- Alert.alert(t('common.error'), t('settings.securitySettings.changePassword.passwordsDoNotMatch'));
+ showAlert(t('common.error'), t('settings.securitySettings.changePassword.passwordsDoNotMatch'));
return;
}
if (!authContext.username) {
- Alert.alert(t('common.error'), t('settings.securitySettings.changePassword.userNotAuthenticated'));
+ showAlert(t('common.error'), t('settings.securitySettings.changePassword.userNotAuthenticated'));
return;
}
@@ -85,28 +87,22 @@ export default function ChangePasswordScreen(): React.ReactNode {
const currentPasswordHashBase64 = await authContext.verifyPassword(currentPassword);
if (!currentPasswordHashBase64) {
- Alert.alert(t('common.error'), t('settings.securitySettings.changePassword.currentPasswordIncorrect'));
+ showAlert(t('common.error'), t('settings.securitySettings.changePassword.currentPasswordIncorrect'));
return;
}
await executeVaultPasswordChange(currentPasswordHashBase64, newPassword);
// Show confirm dialog and go back to the settings screen
- Alert.alert(t('common.success'), t('settings.securitySettings.changePassword.passwordChangedSuccessfully'), [
- { text: t('common.ok'),
- /**
- * Reset the password change state and go back to the settings screen
- */
- onPress: () : void => {
- setCurrentPassword('');
- setNewPassword('');
- setConfirmPassword('');
- router.back();
- } }
- ]);
+ showAlert(t('common.success'), t('settings.securitySettings.changePassword.passwordChangedSuccessfully'), () => {
+ setCurrentPassword('');
+ setNewPassword('');
+ setConfirmPassword('');
+ router.back();
+ });
} catch (error) {
console.error('Password change error:', error);
- Alert.alert(t('common.error'), t('settings.securitySettings.changePassword.failedToChange'));
+ showAlert(t('common.error'), t('settings.securitySettings.changePassword.failedToChange'));
} finally {
setIsLoading(false);
setLoadingStatus(null);
diff --git a/apps/mobile-app/app/(tabs)/settings/security/delete-account.tsx b/apps/mobile-app/app/(tabs)/settings/security/delete-account.tsx
index ebd6f7b8d..b12f96d35 100644
--- a/apps/mobile-app/app/(tabs)/settings/security/delete-account.tsx
+++ b/apps/mobile-app/app/(tabs)/settings/security/delete-account.tsx
@@ -3,7 +3,7 @@ import { Buffer } from 'buffer';
import { router } from 'expo-router';
import { useState } from 'react';
import { useTranslation } from 'react-i18next';
-import { StyleSheet, View, Alert, KeyboardAvoidingView, Platform } from 'react-native';
+import { StyleSheet, View, KeyboardAvoidingView, Platform } from 'react-native';
import type { DeleteAccountInitiateRequest, DeleteAccountInitiateResponse, DeleteAccountRequest } from '@/utils/dist/core/models/webapi';
@@ -17,6 +17,7 @@ import { ThemedText } from '@/components/themed/ThemedText';
import { ThemedTextInput } from '@/components/themed/ThemedTextInput';
import { UsernameDisplay } from '@/components/ui/UsernameDisplay';
import { useApp } from '@/context/AppContext';
+import { useDialog } from '@/context/DialogContext';
import { useWebApi } from '@/context/WebApiContext';
import NativeVaultManager from '@/specs/NativeVaultManager';
@@ -28,6 +29,7 @@ export default function DeleteAccountScreen(): React.ReactNode {
const webApi = useWebApi();
const { username, verifyPassword, logout } = useApp();
const { t } = useTranslation();
+ const { showAlert, showConfirm } = useDialog();
const [confirmUsername, setConfirmUsername] = useState('');
const [password, setPassword] = useState('');
@@ -99,7 +101,7 @@ export default function DeleteAccountScreen(): React.ReactNode {
*/
const handleUsernameSubmit = (): void => {
if (confirmUsername !== username) {
- Alert.alert(t('common.error'), t('settings.securitySettings.deleteAccount.usernameDoesNotMatch'));
+ showAlert(t('common.error'), t('settings.securitySettings.deleteAccount.usernameDoesNotMatch'));
return;
}
setStep('password');
@@ -110,24 +112,16 @@ export default function DeleteAccountScreen(): React.ReactNode {
*/
const handleDeleteAccount = async (): Promise<void> => {
if (!password) {
- Alert.alert(t('common.error'), t('settings.securitySettings.deleteAccount.enterPassword'));
+ showAlert(t('common.error'), t('settings.securitySettings.deleteAccount.enterPassword'));
return;
}
- Alert.alert(
+ showConfirm(
t('settings.securitySettings.deleteAccount.deleteAccount'),
t('settings.securitySettings.deleteAccount.confirmationMessage'),
- [
- { text: t('common.cancel'), style: 'cancel' },
- {
- text: t('settings.securitySettings.deleteAccount.deleteAccount'),
- style: 'destructive',
- /**
- * Handles the delete account press.
- */
- onPress: async (): Promise<void> => handleDeleteAccountPress(),
- },
- ]
+ t('settings.securitySettings.deleteAccount.deleteAccount'),
+ async (): Promise<void> => handleDeleteAccountPress(),
+ { confirmStyle: 'destructive' }
);
};
@@ -140,7 +134,7 @@ export default function DeleteAccountScreen(): React.ReactNode {
setLoadingStatus(t('settings.securitySettings.deleteAccount.verifyingPassword'));
const currentPasswordHashBase64 = await verifyPassword(password);
if (!currentPasswordHashBase64) {
- Alert.alert(t('common.error'), t('settings.securitySettings.deleteAccount.currentPasswordIncorrect'));
+ showAlert(t('common.error'), t('settings.securitySettings.deleteAccount.currentPasswordIncorrect'));
return;
}
@@ -200,7 +194,7 @@ export default function DeleteAccountScreen(): React.ReactNode {
router.replace('/login');
} catch (error) {
console.error('Error deleting account:', error);
- Alert.alert(t('common.error'), t('settings.securitySettings.deleteAccount.failedToDelete'));
+ showAlert(t('common.error'), t('settings.securitySettings.deleteAccount.failedToDelete'));
} finally {
setIsLoading(false);
setLoadingStatus(null);
diff --git a/apps/mobile-app/app/(tabs)/settings/vault-unlock.tsx b/apps/mobile-app/app/(tabs)/settings/vault-unlock.tsx
index 4a1a40ab3..6d215e7a4 100644
--- a/apps/mobile-app/app/(tabs)/settings/vault-unlock.tsx
+++ b/apps/mobile-app/app/(tabs)/settings/vault-unlock.tsx
@@ -1,7 +1,7 @@
import * as LocalAuthentication from 'expo-local-authentication';
import { useState, useEffect, useCallback } from 'react';
import { useTranslation } from 'react-i18next';
-import { StyleSheet, View, Alert, Platform, Linking, Switch, TouchableOpacity } from 'react-native';
+import { StyleSheet, View, Platform, Linking, Switch, TouchableOpacity } from 'react-native';
import Toast from 'react-native-toast-message';
import { useColors } from '@/hooks/useColorScheme';
@@ -10,6 +10,7 @@ import { ThemedContainer } from '@/components/themed/ThemedContainer';
import { ThemedScrollView } from '@/components/themed/ThemedScrollView';
import { ThemedText } from '@/components/themed/ThemedText';
import { AuthMethod, useAuth } from '@/context/AuthContext';
+import { useDialog } from '@/context/DialogContext';
import NativeVaultManager from '@/specs/NativeVaultManager';
/**
@@ -18,6 +19,7 @@ import NativeVaultManager from '@/specs/NativeVaultManager';
export default function VaultUnlockSettingsScreen() : React.ReactNode {
const colors = useColors();
const { t } = useTranslation();
+ const { showAlert, showDialog } = useDialog();
const [initialized, setInitialized] = useState(false);
const { setAuthMethods, getEnabledAuthMethods, getBiometricDisplayName } = useAuth();
const [hasBiometrics, setHasBiometrics] = useState(false);
@@ -95,12 +97,13 @@ export default function VaultUnlockSettingsScreen() : React.ReactNode {
const handleBiometricsToggle = useCallback(async (value: boolean) : Promise<void> => {
if (value && !hasBiometrics) {
- Alert.alert(
+ showDialog(
t('settings.vaultUnlockSettings.biometricNotAvailable', { biometric: biometricDisplayName }),
t('settings.vaultUnlockSettings.biometricDisabledMessage', { biometric: biometricDisplayName }),
[
{
text: t('settings.openSettings'),
+ style: 'default',
/**
* Handle the open settings press.
*/
@@ -152,7 +155,7 @@ export default function VaultUnlockSettingsScreen() : React.ReactNode {
visibilityTime: 1200,
});
}
- }, [hasBiometrics, pinEnabled, setAuthMethods, biometricDisplayName, t]);
+ }, [hasBiometrics, pinEnabled, setAuthMethods, biometricDisplayName, showDialog, t]);
/**
* Handle enable PIN - launches native PIN setup UI.
@@ -183,13 +186,9 @@ export default function VaultUnlockSettingsScreen() : React.ReactNode {
}
console.error('Failed to enable PIN:', error);
- Alert.alert(
- t('common.error'),
- t('common.errors.unknownErrorTryAgain'),
- [{ text: t('common.ok'), style: 'default' }]
- );
+ showAlert(t('common.error'), t('common.errors.unknownErrorTryAgain'));
}
- }, [isBiometricsEnabled, setAuthMethods, t]);
+ }, [isBiometricsEnabled, setAuthMethods, showAlert, t]);
/**
* Handle disable PIN.
@@ -206,13 +205,9 @@ export default function VaultUnlockSettingsScreen() : React.ReactNode {
});
} catch (error) {
console.error('Failed to disable PIN:', error);
- Alert.alert(
- t('common.error'),
- t('common.errors.unknownErrorTryAgain'),
- [{ text: t('common.ok'), style: 'default' }]
- );
+ showAlert(t('common.error'), t('common.errors.unknownErrorTryAgain'));
}
- }, [t]);
+ }, [showAlert, t]);
const styles = StyleSheet.create({
button: {
diff --git a/apps/mobile-app/app/_layout.tsx b/apps/mobile-app/app/_layout.tsx
index ce294b2bf..93587c92f 100644
--- a/apps/mobile-app/app/_layout.tsx
+++ b/apps/mobile-app/app/_layout.tsx
@@ -19,6 +19,7 @@ import { AppProvider } from '@/context/AppContext';
import { AuthProvider } from '@/context/AuthContext';
import { ClipboardCountdownProvider } from '@/context/ClipboardCountdownContext';
import { DbProvider } from '@/context/DbContext';
+import { DialogProvider } from '@/context/DialogContext';
import { NavigationProvider, useNavigation } from '@/context/NavigationContext';
import { WebApiProvider } from '@/context/WebApiContext';
import { initI18n } from '@/i18n';
@@ -177,9 +178,11 @@ export default function RootLayout() : React.ReactNode {
<WebApiProvider>
<AppProvider>
<ClipboardCountdownProvider>
- <GestureHandlerRootView>
- <RootLayoutNav />
- </GestureHandlerRootView>
+ <DialogProvider>
+ <GestureHandlerRootView>
+ <RootLayoutNav />
+ </GestureHandlerRootView>
+ </DialogProvider>
</ClipboardCountdownProvider>
</AppProvider>
</WebApiProvider>
diff --git a/apps/mobile-app/app/login.tsx b/apps/mobile-app/app/login.tsx
index 0fde6fbb7..ac424e841 100644
--- a/apps/mobile-app/app/login.tsx
+++ b/apps/mobile-app/app/login.tsx
@@ -5,7 +5,7 @@ import { useFocusEffect } from '@react-navigation/native';
import { LinearGradient } from 'expo-linear-gradient';
import { router } from 'expo-router';
import React, { useState, useEffect } from 'react';
-import { StyleSheet, View, Text, SafeAreaView, TextInput, ActivityIndicator, Animated, ScrollView, KeyboardAvoidingView, Platform, Dimensions, Alert } from 'react-native';
+import { StyleSheet, View, Text, SafeAreaView, TextInput, ActivityIndicator, Animated, ScrollView, KeyboardAvoidingView, Platform, Dimensions } from 'react-native';
import { useApiUrl } from '@/utils/ApiUrlUtility';
import ConversionUtility from '@/utils/ConversionUtility';
@@ -27,6 +27,7 @@ import { InAppBrowserView } from '@/components/ui/InAppBrowserView';
import { RobustPressable } from '@/components/ui/RobustPressable';
import { useApp } from '@/context/AppContext';
import { useDb } from '@/context/DbContext';
+import { useDialog } from '@/context/DialogContext';
import { useWebApi } from '@/context/WebApiContext';
import NativeVaultManager from '@/specs/NativeVaultManager';
@@ -36,6 +37,7 @@ import NativeVaultManager from '@/specs/NativeVaultManager';
export default function LoginScreen() : React.ReactNode {
const colors = useColors();
const { t } = useTranslation();
+ const { showAlert, showDialog } = useDialog();
const [fadeAnim] = useState(new Animated.Value(0));
const { loadApiUrl, getDisplayUrl } = useApiUrl();
@@ -109,7 +111,7 @@ export default function LoginScreen() : React.ReactNode {
if (isBiometricsEnabledOnDevice) {
// Show biometric prompt if biometrics are available (faceid or fingerprint enrolled) on device.
- Alert.alert(
+ showDialog(
t('auth.enableBiometric', { biometric: biometricDisplayName }),
t('auth.biometricPrompt', { biometric: biometricDisplayName }),
[
@@ -131,7 +133,7 @@ export default function LoginScreen() : React.ReactNode {
},
{
text: t('common.yes'),
- isPreferred: true,
+ style: 'default',
/**
* Handle enabling biometric authentication
*/
@@ -230,11 +232,7 @@ export default function LoginScreen() : React.ReactNode {
checkSuccess = false;
// Show modal with error message
- Alert.alert(
- t('common.error'),
- message,
- [{ text: t('common.ok'), style: 'default' }]
- );
+ showAlert(t('common.error'), message);
// Error will trigger logout through the sync process
setIsLoading(false);
},
diff --git a/apps/mobile-app/app/unlock.tsx b/apps/mobile-app/app/unlock.tsx
index da69a589c..352a65889 100644
--- a/apps/mobile-app/app/unlock.tsx
+++ b/apps/mobile-app/app/unlock.tsx
@@ -4,7 +4,7 @@ import { MaterialIcons } from '@expo/vector-icons';
import { LinearGradient } from 'expo-linear-gradient';
import { router } from 'expo-router';
import { useState, useEffect, useCallback } from 'react';
-import { StyleSheet, View, TextInput, Alert, KeyboardAvoidingView, Platform, ScrollView, Dimensions, Text, Pressable } from 'react-native';
+import { StyleSheet, View, TextInput, KeyboardAvoidingView, Platform, ScrollView, Dimensions, Text, Pressable } from 'react-native';
import EncryptionUtility from '@/utils/EncryptionUtility';
import { VaultVersionIncompatibleError } from '@/utils/types/errors/VaultVersionIncompatibleError';
@@ -14,6 +14,7 @@ import { useLogout } from '@/hooks/useLogout';
import { useTranslation } from '@/hooks/useTranslation';
import Logo from '@/assets/images/logo.svg';
+import { ConfirmDialog } from '@/components/common/ConfirmDialog';
import LoadingIndicator from '@/components/LoadingIndicator';
import { ThemedText } from '@/components/themed/ThemedText';
import { Avatar } from '@/components/ui/Avatar';
@@ -43,6 +44,9 @@ export default function UnlockScreen() : React.ReactNode {
// Error state for password unlock
const [error, setError] = useState<string | null>(null);
+ // Alert dialog state
+ const [alertConfig, setAlertConfig] = useState<{ title: string; message: string } | null>(null);
+
/**
* Check if the key derivation parameters are stored in native storage.
* If not, we can't unlock the vault so logout instead to redirect user to login screen.
@@ -82,16 +86,29 @@ export default function UnlockScreen() : React.ReactNode {
}, [isBiometricsEnabled, getKeyDerivationParams, getBiometricDisplayName]);
+ /**
+ * Handle the unlock.
+ */
+ /**
+ * Show an alert dialog.
+ */
+ const showAlert = useCallback((title: string, message: string): void => {
+ setAlertConfig({ title, message });
+ }, []);
+
+ /**
+ * Hide the alert dialog.
+ */
+ const hideAlert = useCallback((): void => {
+ setAlertConfig(null);
+ }, []);
+
/**
* Handle the unlock.
*/
const handleUnlock = async () : Promise<void> => {
if (!password) {
- Alert.alert(
- t('common.error'),
- t('auth.errors.enterPassword'),
- [{ text: t('common.ok'), style: 'default' }]
- );
+ showAlert(t('common.error'), t('auth.errors.enterPassword'));
return;
}
@@ -134,25 +151,17 @@ export default function UnlockScreen() : React.ReactNode {
*/
router.replace('/reinitialize');
} else {
- Alert.alert(
- t('common.error'),
- t('auth.errors.incorrectPassword'),
- [{ text: t('common.ok'), style: 'default' }]
- );
+ showAlert(t('common.error'), t('auth.errors.incorrectPassword'));
}
- } catch (error) {
- if (error instanceof VaultVersionIncompatibleError) {
+ } catch (err) {
+ if (err instanceof VaultVersionIncompatibleError) {
// Vault version incompatible - force logout without confirmation
await logoutForced();
return;
}
- console.error('Unlock error:', error);
- Alert.alert(
- t('common.error'),
- t('auth.errors.incorrectPassword'),
- [{ text: t('common.ok'), style: 'default' }]
- );
+ console.error('Unlock error:', err);
+ showAlert(t('common.error'), t('auth.errors.incorrectPassword'));
} finally {
setIsLoading(false);
}
@@ -414,6 +423,14 @@ export default function UnlockScreen() : React.ReactNode {
</View>
</ScrollView>
)}
+
+ <ConfirmDialog
+ isVisible={alertConfig !== null}
+ title={alertConfig?.title ?? ''}
+ message={alertConfig?.message ?? ''}
+ buttons={[{ text: t('common.ok'), style: 'default', onPress: hideAlert }]}
+ onClose={hideAlert}
+ />
</KeyboardAvoidingView>
);
}
\ No newline at end of file
diff --git a/apps/mobile-app/app/upgrade.tsx b/apps/mobile-app/app/upgrade.tsx
index 813020bc4..507d0a59b 100644
--- a/apps/mobile-app/app/upgrade.tsx
+++ b/apps/mobile-app/app/upgrade.tsx
@@ -2,7 +2,7 @@ import { LinearGradient } from 'expo-linear-gradient';
import { router } from 'expo-router';
import { useState, useEffect, useCallback } from 'react';
import { useTranslation } from 'react-i18next';
-import { StyleSheet, View, Alert, KeyboardAvoidingView, Platform, ScrollView, Dimensions, TouchableWithoutFeedback, Keyboard, Text } from 'react-native';
+import { StyleSheet, View, KeyboardAvoidingView, Platform, ScrollView, Dimensions, TouchableWithoutFeedback, Keyboard, Text } from 'react-native';
import type { VaultVersion } from '@/utils/dist/core/vault';
import { VaultSqlGenerator } from '@/utils/dist/core/vault';
@@ -20,6 +20,7 @@ import { Avatar } from '@/components/ui/Avatar';
import { RobustPressable } from '@/components/ui/RobustPressable';
import { useApp } from '@/context/AppContext';
import { useDb } from '@/context/DbContext';
+import { useDialog } from '@/context/DialogContext';
import { useWebApi } from '@/context/WebApiContext';
import NativeVaultManager from '@/specs/NativeVaultManager';
@@ -40,6 +41,7 @@ export default function UpgradeScreen() : React.ReactNode {
const { t } = useTranslation();
const { executeVaultMutation, isLoading: isVaultMutationLoading, syncStatus } = useVaultMutate();
const { syncVault } = useVaultSync();
+ const { showAlert, showConfirm } = useDialog();
// Initialize upgrade status with translation
useEffect(() => {
@@ -71,32 +73,17 @@ export default function UpgradeScreen() : React.ReactNode {
*/
const handleUpgrade = async (): Promise<void> => {
if (!sqliteClient || !currentVersion || !latestVersion) {
- Alert.alert(
- t('common.error'),
- t('upgrade.alerts.unableToGetVersionInfo'),
- [{ text: t('common.ok'), style: 'default' }]
- );
+ showAlert(t('common.error'), t('upgrade.alerts.unableToGetVersionInfo'));
return;
}
// Check if this is a self-hosted instance and show warning if needed
if (await webApi.isSelfHosted()) {
- Alert.alert(
+ showConfirm(
t('upgrade.alerts.selfHostedServer'),
t('upgrade.alerts.selfHostedWarning'),
- [
- { text: t('common.cancel'), style: 'cancel' },
- {
- text: t('upgrade.alerts.continueUpgrade'),
- style: 'default',
- /**
- * Continue upgrade.
- */
- onPress: async () : Promise<void> => {
- await performUpgrade();
- }
- }
- ]
+ t('upgrade.alerts.continueUpgrade'),
+ performUpgrade
);
} else {
await performUpgrade();
@@ -108,11 +95,7 @@ export default function UpgradeScreen() : React.ReactNode {
*/
const performUpgrade = async (): Promise<void> => {
if (!sqliteClient || !currentVersion || !latestVersion) {
- Alert.alert(
- t('common.error'),
- t('upgrade.alerts.unableToGetVersionInfo'),
- [{ text: t('common.ok'), style: 'default' }]
- );
+ showAlert(t('common.error'), t('upgrade.alerts.unableToGetVersionInfo'));
return;
}
@@ -123,11 +106,7 @@ export default function UpgradeScreen() : React.ReactNode {
await NativeVaultManager.unlockVault();
} catch (error) {
console.error('Failed to unlock vault for upgrade:', error);
- Alert.alert(
- t('common.error'),
- t('auth.errors.enterPassword'),
- [{ text: t('common.ok'), style: 'default' }]
- );
+ showAlert(t('common.error'), t('auth.errors.enterPassword'));
return;
}
}
@@ -190,20 +169,15 @@ export default function UpgradeScreen() : React.ReactNode {
*/
onError: (error: Error) => {
console.error('Upgrade failed:', error);
- Alert.alert(
- t('upgrade.alerts.upgradeFailed'),
- error.message,
- [{ text: t('common.ok'), style: 'default' }]
- );
+ showAlert(t('upgrade.alerts.upgradeFailed'), error.message);
}
});
- } catch (error) {
- console.error('Upgrade failed:', error);
- Alert.alert(
+ } catch (err) {
+ console.error('Upgrade failed:', err);
+ showAlert(
t('upgrade.alerts.upgradeFailed'),
- error instanceof Error ? error.message : t('common.errors.unknownError'),
- [{ text: t('common.ok'), style: 'default' }]
+ err instanceof Error ? err.message : t('common.errors.unknownError')
);
} finally {
setIsLoading(false);
@@ -265,12 +239,9 @@ export default function UpgradeScreen() : React.ReactNode {
* Show native dialog with version description.
*/
const showVersionDialog = (): void => {
- Alert.alert(
+ showAlert(
t('upgrade.whatsNew'),
- `${t('upgrade.whatsNewDescription')}\n\n${latestVersion?.description ?? t('upgrade.noDescriptionAvailable')}`,
- [
- { text: t('common.ok'), style: 'default' }
- ]
+ `${t('upgrade.whatsNewDescription')}\n\n${latestVersion?.description ?? t('upgrade.noDescriptionAvailable')}`
);
};
diff --git a/apps/mobile-app/components/common/ConfirmDialog.tsx b/apps/mobile-app/components/common/ConfirmDialog.tsx
new file mode 100644
index 000000000..588c67fb1
--- /dev/null
+++ b/apps/mobile-app/components/common/ConfirmDialog.tsx
@@ -0,0 +1,231 @@
+import React, { useState, useCallback, useEffect } from 'react';
+import {
+ Alert,
+ Platform,
+ StyleSheet,
+ Text,
+ TouchableOpacity,
+ View,
+ ActivityIndicator,
+} from 'react-native';
+
+import { useColors } from '@/hooks/useColorScheme';
+import { ModalWrapper } from '@/components/common/ModalWrapper';
+
+/**
+ * Button configuration for confirm dialog.
+ */
+export interface IConfirmDialogButton {
+ /** Button label text. */
+ text: string;
+ /** Button style - determines appearance. */
+ style?: 'default' | 'cancel' | 'destructive';
+ /** Callback when button is pressed. Can be async. */
+ onPress?: () => void | Promise<void>;
+}
+
+interface IConfirmDialogProps {
+ /** Whether the dialog is visible. */
+ isVisible: boolean;
+ /** Dialog title. */
+ title: string;
+ /** Dialog message/description. */
+ message: string;
+ /** Array of buttons to display. */
+ buttons: IConfirmDialogButton[];
+ /** Callback when dialog is closed (via backdrop tap or cancel). */
+ onClose: () => void;
+}
+
+/**
+ * Cross-platform confirm dialog component.
+ *
+ * On iOS: Uses native Alert.alert() for platform-consistent UX.
+ * On Android: Uses custom ModalWrapper for better styling.
+ *
+ * Usage:
+ * ```tsx
+ * <ConfirmDialog
+ * isVisible={showConfirm}
+ * title="Delete Item"
+ * message="Are you sure you want to delete this item?"
+ * buttons={[
+ * { text: 'Cancel', style: 'cancel', onPress: () => setShowConfirm(false) },
+ * { text: 'Delete', style: 'destructive', onPress: handleDelete },
+ * ]}
+ * onClose={() => setShowConfirm(false)}
+ * />
+ * ```
+ */
+export const ConfirmDialog: React.FC<IConfirmDialogProps> = ({
+ isVisible,
+ title,
+ message,
+ buttons,
+ onClose,
+}) => {
+ const colors = useColors();
+ const [loadingButtonIndex, setLoadingButtonIndex] = useState<number | null>(null);
+
+ /**
+ * Show iOS native alert when visible.
+ * We track whether we've shown the alert for this visibility state to prevent
+ * showing it multiple times.
+ */
+ const [hasShownAlert, setHasShownAlert] = useState(false);
+
+ useEffect(() => {
+ if (Platform.OS === 'ios' && isVisible && !hasShownAlert) {
+ setHasShownAlert(true);
+
+ const alertButtons = buttons.map((button) => ({
+ text: button.text,
+ style: button.style,
+ onPress: () => {
+ button.onPress?.();
+ // Always call onClose after any button press to reset visibility state
+ onClose();
+ },
+ }));
+
+ Alert.alert(title, message, alertButtons);
+ } else if (!isVisible && hasShownAlert) {
+ // Reset the flag when dialog becomes invisible
+ setHasShownAlert(false);
+ }
+ }, [isVisible, title, message, buttons, hasShownAlert, onClose]);
+
+ /**
+ * Handle button press with loading state for async actions.
+ */
+ const handleButtonPress = useCallback(async (button: IConfirmDialogButton, index: number): Promise<void> => {
+ if (!button.onPress) {
+ onClose();
+ return;
+ }
+
+ const result = button.onPress();
+
+ // If the onPress returns a Promise, show loading state
+ if (result instanceof Promise) {
+ setLoadingButtonIndex(index);
+ try {
+ await result;
+ } catch (error) {
+ console.error('ConfirmDialog button action error:', error);
+ } finally {
+ setLoadingButtonIndex(null);
+ }
+ }
+ }, [onClose]);
+
+ // On iOS, return null since we use native Alert
+ if (Platform.OS === 'ios') {
+ return null;
+ }
+
+ const isSubmitting = loadingButtonIndex !== null;
+
+ /**
+ * Get button style based on button configuration.
+ */
+ const getButtonStyle = (button: IConfirmDialogButton, index: number): object[] => {
+ const baseStyle = [styles.button];
+
+ if (button.style === 'destructive') {
+ baseStyle.push({ backgroundColor: colors.destructive });
+ } else if (button.style === 'cancel') {
+ baseStyle.push({
+ backgroundColor: colors.accentBackground,
+ borderColor: colors.accentBorder,
+ borderWidth: 1,
+ });
+ } else {
+ baseStyle.push({ backgroundColor: colors.primary });
+ }
+
+ if (isSubmitting && loadingButtonIndex === index) {
+ baseStyle.push(styles.buttonDisabled);
+ }
+
+ return baseStyle;
+ };
+
+ /**
+ * Get button text style based on button configuration.
+ */
+ const getButtonTextStyle = (button: IConfirmDialogButton): object[] => {
+ const baseStyle = [styles.buttonText];
+
+ if (button.style === 'cancel') {
+ baseStyle.push({ color: colors.text });
+ } else {
+ baseStyle.push({ color: colors.white });
+ }
+
+ return baseStyle;
+ };
+
+ const styles = StyleSheet.create({
+ message: {
+ color: colors.textMuted,
+ fontSize: 14,
+ lineHeight: 20,
+ },
+ buttonsContainer: {
+ flexDirection: 'row',
+ gap: 12,
+ marginTop: 20,
+ },
+ button: {
+ alignItems: 'center',
+ borderRadius: 8,
+ flex: 1,
+ flexDirection: 'row',
+ gap: 8,
+ justifyContent: 'center',
+ paddingVertical: 12,
+ },
+ buttonDisabled: {
+ opacity: 0.6,
+ },
+ buttonText: {
+ fontSize: 16,
+ fontWeight: '500',
+ },
+ });
+
+ return (
+ <ModalWrapper
+ isOpen={isVisible}
+ onClose={onClose}
+ isSubmitting={isSubmitting}
+ title={title}
+ showHeaderBorder={false}
+ showFooterBorder={false}
+ >
+ <Text style={styles.message}>{message}</Text>
+
+ <View style={styles.buttonsContainer}>
+ {buttons.map((button, index) => (
+ <TouchableOpacity
+ key={index}
+ style={getButtonStyle(button, index)}
+ onPress={() => handleButtonPress(button, index)}
+ disabled={isSubmitting}
+ >
+ {isSubmitting && loadingButtonIndex === index && (
+ <ActivityIndicator
+ size="small"
+ color={button.style === 'cancel' ? colors.text : colors.white}
+ />
+ )}
+ <Text style={getButtonTextStyle(button)}>{button.text}</Text>
+ </TouchableOpacity>
+ ))}
+ </View>
+ </ModalWrapper>
+ );
+};
+
+export default ConfirmDialog;
diff --git a/apps/mobile-app/components/items/ItemCard.tsx b/apps/mobile-app/components/items/ItemCard.tsx
index 2517e6def..405ba6344 100644
--- a/apps/mobile-app/components/items/ItemCard.tsx
+++ b/apps/mobile-app/components/items/ItemCard.tsx
@@ -1,21 +1,21 @@
/* eslint-disable max-len */
import MaterialIcons from '@expo/vector-icons/MaterialIcons';
import { router } from 'expo-router';
+import React from 'react';
import { useTranslation } from 'react-i18next';
-import { StyleSheet, View, Text, TouchableOpacity, Keyboard, Platform, Alert } from 'react-native';
+import { StyleSheet, View, Text, TouchableOpacity, Keyboard, Platform } from 'react-native';
import ContextMenu, { ContextMenuOnPressNativeEvent } from 'react-native-context-menu-view';
import type { NativeSyntheticEvent } from 'react-native';
import Toast from 'react-native-toast-message';
+import { ItemIcon } from '@/components/items/ItemIcon';
+import { useAuth } from '@/context/AuthContext';
+import { useDialog } from '@/context/DialogContext';
+import { useColors } from '@/hooks/useColorScheme';
import { copyToClipboardWithExpiration } from '@/utils/ClipboardUtility';
import type { Item } from '@/utils/dist/core/models/vault';
import { getFieldValue, FieldKey } from '@/utils/dist/core/models/vault';
-import { useColors } from '@/hooks/useColorScheme';
-
-import { ItemIcon } from '@/components/items/ItemIcon';
-import { useAuth } from '@/context/AuthContext';
-
type ItemCardProps = {
item: Item;
onItemDelete?: (itemId: string) => Promise<void>;
@@ -28,6 +28,7 @@ export function ItemCard({ item, onItemDelete }: ItemCardProps): React.ReactNode
const colors = useColors();
const { t } = useTranslation();
const { getClipboardClearTimeout } = useAuth();
+ const { showConfirm } = useDialog();
/**
* Get the display text for an item, showing username by default,
@@ -93,27 +94,16 @@ export function ItemCard({ item, onItemDelete }: ItemCardProps): React.ReactNode
break;
case t('items.contextMenu.delete'):
Keyboard.dismiss();
- Alert.alert(
+ showConfirm(
t('items.deleteItem'),
t('items.deleteConfirm'),
- [
- {
- text: t('common.cancel'),
- style: "cancel"
- },
- {
- text: t('common.delete'),
- style: "destructive",
- /**
- * Handles the delete item action.
- */
- onPress: async (): Promise<void> => {
- if (onItemDelete) {
- await onItemDelete(item.Id);
- }
- }
+ t('common.delete'),
+ async () => {
+ if (onItemDelete) {
+ await onItemDelete(item.Id);
}
- ]
+ },
+ { confirmStyle: 'destructive' }
);
break;
case t('items.contextMenu.copyUsername'):
@@ -278,57 +268,57 @@ export function ItemCard({ item, onItemDelete }: ItemCardProps): React.ReactNode
onPress={handleContextMenuAction}
previewBackgroundColor={colors.accentBackground}
>
- <TouchableOpacity
- style={styles.credentialCard}
- onPress={() => {
- Keyboard.dismiss();
- router.push(`/(tabs)/items/${item.Id}`);
- }}
- onLongPress={() => {
- // Ignore long press to prevent context menu long press from triggering the item card press.
- }}
- activeOpacity={0.7}
- testID="item-card"
- accessibilityLabel={item.Name}
- >
- <View style={styles.itemContent}>
- <ItemIcon item={item} style={styles.logo} />
- <View style={styles.itemInfo}>
- <View style={styles.serviceNameRow}>
- <Text style={styles.serviceName}>
- {getItemName(item)}
+ <TouchableOpacity
+ style={styles.credentialCard}
+ onPress={() => {
+ Keyboard.dismiss();
+ router.push(`/(tabs)/items/${item.Id}`);
+ }}
+ onLongPress={() => {
+ // Ignore long press to prevent context menu long press from triggering the item card press.
+ }}
+ activeOpacity={0.7}
+ testID="item-card"
+ accessibilityLabel={item.Name}
+ >
+ <View style={styles.itemContent}>
+ <ItemIcon item={item} style={styles.logo} />
+ <View style={styles.itemInfo}>
+ <View style={styles.serviceNameRow}>
+ <Text style={styles.serviceName}>
+ {getItemName(item)}
+ </Text>
+ {item.HasPasskey && (
+ <MaterialIcons
+ name="vpn-key"
+ size={14}
+ color={colors.textMuted}
+ style={styles.iconStyle}
+ />
+ )}
+ {item.HasAttachment && (
+ <MaterialIcons
+ name="attach-file"
+ size={14}
+ color={colors.textMuted}
+ style={styles.iconStyle}
+ />
+ )}
+ {item.HasTotp && (
+ <MaterialIcons
+ name="pin"
+ size={14}
+ color={colors.textMuted}
+ style={styles.iconStyle}
+ />
+ )}
+ </View>
+ <Text style={styles.itemText}>
+ {getItemDisplayText(item)}
</Text>
- {item.HasPasskey && (
- <MaterialIcons
- name="vpn-key"
- size={14}
- color={colors.textMuted}
- style={styles.iconStyle}
- />
- )}
- {item.HasAttachment && (
- <MaterialIcons
- name="attach-file"
- size={14}
- color={colors.textMuted}
- style={styles.iconStyle}
- />
- )}
- {item.HasTotp && (
- <MaterialIcons
- name="pin"
- size={14}
- color={colors.textMuted}
- style={styles.iconStyle}
- />
- )}
</View>
- <Text style={styles.itemText}>
- {getItemDisplayText(item)}
- </Text>
</View>
- </View>
- </TouchableOpacity>
+ </TouchableOpacity>
</ContextMenu>
);
}
diff --git a/apps/mobile-app/components/items/details/AttachmentSection.tsx b/apps/mobile-app/components/items/details/AttachmentSection.tsx
index 50520d4bd..bc6f7c366 100644
--- a/apps/mobile-app/components/items/details/AttachmentSection.tsx
+++ b/apps/mobile-app/components/items/details/AttachmentSection.tsx
@@ -5,7 +5,7 @@ import * as FileSystem from 'expo-file-system';
import * as Sharing from 'expo-sharing';
import React, { useState, useEffect, useCallback } from 'react';
import { useTranslation } from 'react-i18next';
-import { View, StyleSheet, TouchableOpacity, Alert } from 'react-native';
+import { View, StyleSheet, TouchableOpacity } from 'react-native';
import type { Item, Attachment } from '@/utils/dist/core/models/vault';
import emitter from '@/utils/EventEmitter';
@@ -15,6 +15,7 @@ import { useColors } from '@/hooks/useColorScheme';
import { ThemedText } from '@/components/themed/ThemedText';
import { ThemedView } from '@/components/themed/ThemedView';
import { useDb } from '@/context/DbContext';
+import { useDialog } from '@/context/DialogContext';
import { FilePreviewModal } from './FilePreviewModal';
@@ -36,6 +37,7 @@ export const AttachmentSection: React.FC<AttachmentSectionProps> = ({ item }): R
const colors = useColors();
const dbContext = useDb();
const { t } = useTranslation();
+ const { showAlert } = useDialog();
/**
* Handle attachment action - preview or download.
@@ -87,7 +89,7 @@ export const AttachmentSection: React.FC<AttachmentSectionProps> = ({ item }): R
}
} catch (error) {
console.error('Error handling attachment:', error);
- Alert.alert('Error', 'Failed to process attachment');
+ showAlert('Error', 'Failed to process attachment');
}
};
@@ -105,14 +107,11 @@ export const AttachmentSection: React.FC<AttachmentSectionProps> = ({ item }): R
UTI: getUTI(filename),
});
} else {
- Alert.alert(
- t('common.success'),
- `${t('items.fileSavedTo')}: ${filePath}`
- );
+ showAlert(t('common.success'), `${t('items.fileSavedTo')}: ${filePath}`);
}
} catch (error) {
console.error('Error downloading file:', error);
- Alert.alert(t('common.error'), t('common.errors.unknownError'));
+ showAlert(t('common.error'), t('common.errors.unknownError'));
}
};
diff --git a/apps/mobile-app/components/items/details/AttachmentUploader.tsx b/apps/mobile-app/components/items/details/AttachmentUploader.tsx
index b7aa908d6..1fe740872 100644
--- a/apps/mobile-app/components/items/details/AttachmentUploader.tsx
+++ b/apps/mobile-app/components/items/details/AttachmentUploader.tsx
@@ -3,14 +3,13 @@ import * as DocumentPicker from 'expo-document-picker';
import * as FileSystem from 'expo-file-system';
import React, { useState } from 'react';
import { useTranslation } from 'react-i18next';
-import { View, StyleSheet, TouchableOpacity, Alert } from 'react-native';
-
-import type { Attachment } from '@/utils/dist/core/models/vault';
-
-import { useColors } from '@/hooks/useColorScheme';
+import { View, StyleSheet, TouchableOpacity } from 'react-native';
+import { ConfirmDialog } from '@/components/common/ConfirmDialog';
import { ThemedText } from '@/components/themed/ThemedText';
import { ThemedView } from '@/components/themed/ThemedView';
+import { useColors } from '@/hooks/useColorScheme';
+import type { Attachment } from '@/utils/dist/core/models/vault';
type AttachmentUploaderProps = {
attachments: Attachment[];
@@ -27,6 +26,7 @@ export const AttachmentUploader: React.FC<AttachmentUploaderProps> = ({
const { t } = useTranslation();
const colors = useColors();
const [statusMessage, setStatusMessage] = useState<string>('');
+ const [attachmentToDelete, setAttachmentToDelete] = useState<Attachment | null>(null);
/**
* Handles file selection and upload.
@@ -112,44 +112,36 @@ export const AttachmentUploader: React.FC<AttachmentUploaderProps> = ({
};
/**
- * Deletes an attachment.
+ * Initiates the delete process for an attachment.
*/
- const deleteAttachment = (attachmentToDelete: Attachment): void => {
- Alert.alert(
- 'Delete Attachment',
- `Are you sure you want to delete ${attachmentToDelete.Filename}?`,
- [
- {
- text: 'Cancel',
- style: 'cancel',
- },
- {
- text: 'Delete',
- style: 'destructive',
- /**
- * Deletes the attachment.
- */
- onPress: (): void => {
- try {
- const updatedAttachments = [...attachments];
-
- // Remove the attachment from the list
- const index = updatedAttachments.findIndex(a => a.Id === attachmentToDelete.Id);
- if (index !== -1) {
- updatedAttachments.splice(index, 1);
- }
+ const initiateDeleteAttachment = (attachment: Attachment): void => {
+ setAttachmentToDelete(attachment);
+ };
- onAttachmentsChange(updatedAttachments);
- setStatusMessage('');
- } catch (error) {
- console.error('Error deleting attachment:', error);
- setStatusMessage('Error deleting attachment.');
- setTimeout(() => setStatusMessage(''), 3000);
- }
- },
- },
- ]
- );
+ /**
+ * Confirms and deletes an attachment.
+ */
+ const confirmDeleteAttachment = (): void => {
+ if (!attachmentToDelete) return;
+
+ try {
+ const updatedAttachments = [...attachments];
+
+ // Remove the attachment from the list
+ const index = updatedAttachments.findIndex(a => a.Id === attachmentToDelete.Id);
+ if (index !== -1) {
+ updatedAttachments.splice(index, 1);
+ }
+
+ onAttachmentsChange(updatedAttachments);
+ setStatusMessage('');
+ } catch (error) {
+ console.error('Error deleting attachment:', error);
+ setStatusMessage(t('items.attachments.errorDeleting'));
+ setTimeout(() => setStatusMessage(''), 3000);
+ }
+
+ setAttachmentToDelete(null);
};
const activeAttachments = attachments.filter(a => !a.IsDeleted);
@@ -226,7 +218,7 @@ export const AttachmentUploader: React.FC<AttachmentUploaderProps> = ({
</View>
<TouchableOpacity
style={styles.deleteButton}
- onPress={() => deleteAttachment(attachment)}
+ onPress={() => initiateDeleteAttachment(attachment)}
>
<ThemedText style={styles.deleteButtonText}>
{t('items.deleteAttachment')}
@@ -243,6 +235,25 @@ export const AttachmentUploader: React.FC<AttachmentUploaderProps> = ({
>
<Ionicons name="add" size={24} color={colors.background} />
</TouchableOpacity>
+
+ <ConfirmDialog
+ isVisible={attachmentToDelete !== null}
+ title={t('items.attachments.deleteTitle')}
+ message={t('items.attachments.deleteConfirm', { filename: attachmentToDelete?.Filename })}
+ buttons={[
+ {
+ text: t('common.cancel'),
+ style: 'cancel',
+ onPress: (): void => setAttachmentToDelete(null),
+ },
+ {
+ text: t('common.delete'),
+ style: 'destructive',
+ onPress: confirmDeleteAttachment,
+ },
+ ]}
+ onClose={(): void => setAttachmentToDelete(null)}
+ />
</ThemedView>
);
};
\ No newline at end of file
diff --git a/apps/mobile-app/components/items/details/FilePreviewModal.tsx b/apps/mobile-app/components/items/details/FilePreviewModal.tsx
index ecb19ef5b..2f1c85780 100644
--- a/apps/mobile-app/components/items/details/FilePreviewModal.tsx
+++ b/apps/mobile-app/components/items/details/FilePreviewModal.tsx
@@ -9,8 +9,7 @@ import {
StyleSheet,
TouchableOpacity,
ScrollView,
- Dimensions,
- Alert
+ Dimensions
} from 'react-native';
import ImageViewer from 'react-native-image-zoom-viewer';
@@ -18,6 +17,7 @@ import { useColors } from '@/hooks/useColorScheme';
import { ThemedText } from '@/components/themed/ThemedText';
import { ThemedView } from '@/components/themed/ThemedView';
+import { useDialog } from '@/context/DialogContext';
type FilePreviewModalProps = {
visible: boolean;
@@ -47,6 +47,7 @@ export const FilePreviewModal: React.FC<FilePreviewModalProps> = ({
const [fileSize, setFileSize] = useState<string>('');
const colors = useColors();
const { t } = useTranslation();
+ const { showAlert } = useDialog();
const imageExtensions = ['jpg', 'jpeg', 'png', 'gif', 'bmp', 'webp'];
const textExtensions = ['txt', 'md', 'json', 'csv', 'log', 'xml', 'js', 'ts', 'tsx', 'jsx', 'html', 'css'];
@@ -85,12 +86,12 @@ export const FilePreviewModal: React.FC<FilePreviewModalProps> = ({
setFileContent(content);
} catch (error) {
console.error('Error reading text file:', error);
- Alert.alert('Error', 'Could not read file content');
+ showAlert('Error', 'Could not read file content');
setFileContent('Error loading file content');
} finally {
setLoading(false);
}
- }, [filePath]);
+ }, [filePath, showAlert]);
useEffect(() => {
if (visible) {
@@ -114,14 +115,11 @@ export const FilePreviewModal: React.FC<FilePreviewModalProps> = ({
dialogTitle: `Save ${fileName}`,
});
} else {
- Alert.alert(
- t('common.success'),
- `${t('items.fileSavedTo')}: ${filePath}`
- );
+ showAlert(t('common.success'), `${t('items.fileSavedTo')}: ${filePath}`);
}
} catch (error) {
console.error('Error downloading file:', error);
- Alert.alert('Error', 'Failed to download file');
+ showAlert('Error', 'Failed to download file');
}
};
diff --git a/apps/mobile-app/components/items/details/TotpEditor.tsx b/apps/mobile-app/components/items/details/TotpEditor.tsx
index 42bcfcba0..daf5d9797 100644
--- a/apps/mobile-app/components/items/details/TotpEditor.tsx
+++ b/apps/mobile-app/components/items/details/TotpEditor.tsx
@@ -1,16 +1,15 @@
+import { Ionicons } from '@expo/vector-icons';
import MaterialIcons from '@expo/vector-icons/MaterialIcons';
import * as OTPAuth from 'otpauth';
import React, { useState } from 'react';
import { useTranslation } from 'react-i18next';
-import { View, StyleSheet, Alert, TextInput, Modal, TouchableOpacity, ScrollView, KeyboardAvoidingView, Platform } from 'react-native';
-
-import type { TotpCode } from '@/utils/dist/core/models/vault';
-
-import { useColors, useColorScheme } from '@/hooks/useColorScheme';
+import { View, StyleSheet, TextInput, Modal, TouchableOpacity, ScrollView, KeyboardAvoidingView, Platform } from 'react-native';
import { ThemedText } from '@/components/themed/ThemedText';
import { ThemedView } from '@/components/themed/ThemedView';
-import { Ionicons } from '@expo/vector-icons';
+import { useDialog } from '@/context/DialogContext';
+import { useColors, useColorScheme } from '@/hooks/useColorScheme';
+import type { TotpCode } from '@/utils/dist/core/models/vault';
type TotpFormData = {
name: string;
@@ -39,6 +38,7 @@ export const TotpEditor: React.FC<TotpEditorProps> = ({
const { t } = useTranslation();
const colors = useColors();
const colorScheme = useColorScheme();
+ const { showConfirm } = useDialog();
const [isAddFormVisible, setIsAddFormVisible] = useState(false);
const [formData, setFormData] = useState<TotpFormData>({ name: '', secretKey: '' });
const [formError, setFormError] = useState<string | null>(null);
@@ -150,20 +150,12 @@ export const TotpEditor: React.FC<TotpEditorProps> = ({
* Initiates the delete process for a TOTP code
*/
const initiateTotpDelete = (totpCode: TotpCode): void => {
- Alert.alert(
+ showConfirm(
t('common.deleteItemConfirmTitle'),
t('common.deleteItemConfirmDescription'),
- [
- {
- text: t('common.cancel'),
- style: 'cancel'
- },
- {
- text: t('common.delete'),
- style: 'destructive',
- onPress: () => confirmDeleteTotpCode(totpCode)
- }
- ]
+ t('common.delete'),
+ () => confirmDeleteTotpCode(totpCode),
+ { confirmStyle: 'destructive' }
);
};
diff --git a/apps/mobile-app/context/DialogContext.tsx b/apps/mobile-app/context/DialogContext.tsx
new file mode 100644
index 000000000..b7009d06c
--- /dev/null
+++ b/apps/mobile-app/context/DialogContext.tsx
@@ -0,0 +1,217 @@
+import React, { createContext, useContext, useState, useCallback, useMemo } from 'react';
+import { Alert, Platform } from 'react-native';
+
+import { ConfirmDialog, type IConfirmDialogButton } from '@/components/common/ConfirmDialog';
+
+interface DialogConfig {
+ title: string;
+ message: string;
+ buttons: IConfirmDialogButton[];
+}
+
+interface DialogContextValue {
+ /**
+ * Show a simple alert with an OK button.
+ */
+ showAlert: (title: string, message: string, onOk?: () => void) => void;
+
+ /**
+ * Show a confirm dialog with Cancel and a custom action button.
+ */
+ showConfirm: (
+ title: string,
+ message: string,
+ confirmText: string,
+ onConfirm: () => void | Promise<void>,
+ options?: {
+ cancelText?: string;
+ confirmStyle?: 'default' | 'destructive';
+ }
+ ) => void;
+
+ /**
+ * Show a custom dialog with any buttons.
+ */
+ showDialog: (title: string, message: string, buttons: IConfirmDialogButton[]) => void;
+
+ /**
+ * Hide the current dialog.
+ */
+ hideDialog: () => void;
+}
+
+const DialogContext = createContext<DialogContextValue | null>(null);
+
+/**
+ * Hook to access the dialog service.
+ *
+ * Usage:
+ * ```tsx
+ * const { showAlert, showConfirm } = useDialog();
+ *
+ * // Simple alert
+ * showAlert(t('common.error'), t('auth.errors.enterPassword'));
+ *
+ * // Confirm dialog
+ * showConfirm(
+ * t('items.deleteItem'),
+ * t('items.deleteConfirm'),
+ * t('common.delete'),
+ * async () => { await deleteItem(); },
+ * { confirmStyle: 'destructive' }
+ * );
+ * ```
+ */
+export function useDialog(): DialogContextValue {
+ const context = useContext(DialogContext);
+ if (!context) {
+ throw new Error('useDialog must be used within a DialogProvider');
+ }
+ return context;
+}
+
+interface DialogProviderProps {
+ children: React.ReactNode;
+}
+
+/**
+ * Provider component that enables the dialog service.
+ * Add this near the root of your app (e.g., in _layout.tsx).
+ */
+export function DialogProvider({ children }: DialogProviderProps): React.ReactNode {
+ const [dialogConfig, setDialogConfig] = useState<DialogConfig | null>(null);
+
+ /**
+ * Hide the dialog.
+ */
+ const hideDialog = useCallback((): void => {
+ setDialogConfig(null);
+ }, []);
+
+ /**
+ * Show a simple alert with an OK button.
+ */
+ const showAlert = useCallback((title: string, message: string, onOk?: () => void): void => {
+ // On iOS, use native Alert for simple alerts too
+ if (Platform.OS === 'ios') {
+ Alert.alert(title, message, [{
+ text: 'OK',
+ style: 'default',
+ onPress: onOk,
+ }]);
+ return;
+ }
+
+ setDialogConfig({
+ title,
+ message,
+ buttons: [{
+ text: 'OK',
+ style: 'default',
+ onPress: (): void => {
+ onOk?.();
+ setDialogConfig(null);
+ },
+ }],
+ });
+ }, []);
+
+ /**
+ * Show a confirm dialog with Cancel and action button.
+ */
+ const showConfirm = useCallback((
+ title: string,
+ message: string,
+ confirmText: string,
+ onConfirm: () => void | Promise<void>,
+ options?: {
+ cancelText?: string;
+ confirmStyle?: 'default' | 'destructive';
+ }
+ ): void => {
+ // On iOS, use native Alert
+ if (Platform.OS === 'ios') {
+ Alert.alert(title, message, [
+ { text: options?.cancelText ?? 'Cancel', style: 'cancel' },
+ {
+ text: confirmText,
+ style: options?.confirmStyle ?? 'default',
+ onPress: () => { onConfirm(); },
+ },
+ ]);
+ return;
+ }
+
+ setDialogConfig({
+ title,
+ message,
+ buttons: [
+ {
+ text: options?.cancelText ?? 'Cancel',
+ style: 'cancel',
+ onPress: (): void => setDialogConfig(null),
+ },
+ {
+ text: confirmText,
+ style: options?.confirmStyle ?? 'default',
+ onPress: async (): Promise<void> => {
+ await onConfirm();
+ setDialogConfig(null);
+ },
+ },
+ ],
+ });
+ }, []);
+
+ /**
+ * Show a custom dialog with any buttons.
+ */
+ const showDialog = useCallback((title: string, message: string, buttons: IConfirmDialogButton[]): void => {
+ // On iOS, use native Alert
+ if (Platform.OS === 'ios') {
+ const alertButtons = buttons.map(btn => ({
+ text: btn.text,
+ style: btn.style,
+ onPress: () => { btn.onPress?.(); },
+ }));
+ Alert.alert(title, message, alertButtons);
+ return;
+ }
+
+ // Wrap button onPress to auto-close dialog
+ const wrappedButtons = buttons.map(btn => ({
+ ...btn,
+ onPress: async (): Promise<void> => {
+ await btn.onPress?.();
+ setDialogConfig(null);
+ },
+ }));
+
+ setDialogConfig({ title, message, buttons: wrappedButtons });
+ }, []);
+
+ const contextValue = useMemo(() => ({
+ showAlert,
+ showConfirm,
+ showDialog,
+ hideDialog,
+ }), [showAlert, showConfirm, showDialog, hideDialog]);
+
+ return (
+ <DialogContext.Provider value={contextValue}>
+ {children}
+ {/* Only render on Android since iOS uses native Alert */}
+ {Platform.OS !== 'ios' && (
+ <ConfirmDialog
+ isVisible={dialogConfig !== null}
+ title={dialogConfig?.title ?? ''}
+ message={dialogConfig?.message ?? ''}
+ buttons={dialogConfig?.buttons ?? []}
+ onClose={hideDialog}
+ />
+ )}
+ </DialogContext.Provider>
+ );
+}
+
+export default DialogProvider;
diff --git a/apps/mobile-app/hooks/useAlertDialog.ts b/apps/mobile-app/hooks/useAlertDialog.ts
new file mode 100644
index 000000000..faa67acbb
--- /dev/null
+++ b/apps/mobile-app/hooks/useAlertDialog.ts
@@ -0,0 +1,139 @@
+import { useState, useCallback } from 'react';
+
+import type { IConfirmDialogButton } from '@/components/common/ConfirmDialog';
+
+interface AlertDialogConfig {
+ title: string;
+ message: string;
+ buttons: IConfirmDialogButton[];
+}
+
+interface UseAlertDialogReturn {
+ /** Whether the alert dialog is visible. */
+ isVisible: boolean;
+ /** Alert dialog configuration. */
+ config: AlertDialogConfig | null;
+ /**
+ * Show an alert dialog with a single OK button.
+ */
+ showAlert: (title: string, message: string, onOk?: () => void) => void;
+ /**
+ * Show a confirm dialog with Cancel and action buttons.
+ */
+ showConfirm: (
+ title: string,
+ message: string,
+ confirmText: string,
+ onConfirm: () => void | Promise<void>,
+ options?: {
+ cancelText?: string;
+ confirmStyle?: 'default' | 'destructive';
+ }
+ ) => void;
+ /**
+ * Show a custom dialog with any buttons.
+ */
+ showCustom: (title: string, message: string, buttons: IConfirmDialogButton[]) => void;
+ /**
+ * Hide the alert dialog.
+ */
+ hideAlert: () => void;
+}
+
+/**
+ * Hook for managing alert dialog state.
+ *
+ * Usage:
+ * ```tsx
+ * const { isVisible, config, showAlert, showConfirm, hideAlert } = useAlertDialog();
+ *
+ * // Show simple alert
+ * showAlert(t('common.error'), t('auth.errors.enterPassword'));
+ *
+ * // Show confirm dialog
+ * showConfirm(
+ * t('items.deleteItem'),
+ * t('items.deleteConfirm'),
+ * t('common.delete'),
+ * handleDelete,
+ * { confirmStyle: 'destructive' }
+ * );
+ *
+ * // Render the dialog
+ * <ConfirmDialog
+ * isVisible={isVisible}
+ * title={config?.title ?? ''}
+ * message={config?.message ?? ''}
+ * buttons={config?.buttons ?? []}
+ * onClose={hideAlert}
+ * />
+ * ```
+ */
+export function useAlertDialog(): UseAlertDialogReturn {
+ const [config, setConfig] = useState<AlertDialogConfig | null>(null);
+
+ const hideAlert = useCallback((): void => {
+ setConfig(null);
+ }, []);
+
+ const showAlert = useCallback((title: string, message: string, onOk?: () => void): void => {
+ setConfig({
+ title,
+ message,
+ buttons: [{
+ text: 'OK',
+ style: 'default',
+ onPress: (): void => {
+ onOk?.();
+ setConfig(null);
+ },
+ }],
+ });
+ }, []);
+
+ const showConfirm = useCallback((
+ title: string,
+ message: string,
+ confirmText: string,
+ onConfirm: () => void | Promise<void>,
+ options?: {
+ cancelText?: string;
+ confirmStyle?: 'default' | 'destructive';
+ }
+ ): void => {
+ setConfig({
+ title,
+ message,
+ buttons: [
+ {
+ text: options?.cancelText ?? 'Cancel',
+ style: 'cancel',
+ onPress: (): void => setConfig(null),
+ },
+ {
+ text: confirmText,
+ style: options?.confirmStyle ?? 'default',
+ onPress: async (): Promise<void> => {
+ await onConfirm();
+ setConfig(null);
+ },
+ },
+ ],
+ });
+ }, []);
+
+ const showCustom = useCallback((title: string, message: string, buttons: IConfirmDialogButton[]): void => {
+ setConfig({ title, message, buttons });
+ }, []);
+
+ return {
+ isVisible: config !== null,
+ config,
+ showAlert,
+ showConfirm,
+ showCustom,
+ hideAlert,
+ };
+}
+
+export default useAlertDialog;
diff --git a/apps/mobile-app/hooks/useLogout.ts b/apps/mobile-app/hooks/useLogout.ts
index ce236a43b..8b315ee76 100644
--- a/apps/mobile-app/hooks/useLogout.ts
+++ b/apps/mobile-app/hooks/useLogout.ts
@@ -1,10 +1,10 @@
import { useCallback } from 'react';
-import { Alert } from 'react-native';
import { router } from 'expo-router';
import { useTranslation } from '@/hooks/useTranslation';
import { useAuth } from '@/context/AuthContext';
import { useDb } from '@/context/DbContext';
+import { useDialog } from '@/context/DialogContext';
import { useWebApi } from '@/context/WebApiContext';
type UseLogoutReturn = {
@@ -46,6 +46,7 @@ export function useLogout(): UseLogoutReturn {
const { t } = useTranslation();
const { clearAuthUserInitiated } = useAuth();
const { isDirty } = useDb();
+ const { showConfirm } = useDialog();
const webApi = useWebApi();
/**
@@ -78,34 +79,24 @@ export function useLogout(): UseLogoutReturn {
const logoutUserInitiated = useCallback(async (): Promise<void> => {
if (isDirty) {
// Show warning about unsynced changes
- Alert.alert(
+ showConfirm(
t('logout.unsyncedChangesTitle'),
t('logout.unsyncedChangesWarning'),
- [
- { text: t('common.cancel'), style: 'cancel' },
- {
- text: t('logout.logoutAnyway'),
- style: 'destructive',
- onPress: performLogout,
- },
- ]
+ t('logout.logoutAnyway'),
+ performLogout,
+ { confirmStyle: 'destructive' }
);
} else {
// Show normal confirmation dialog
- Alert.alert(
+ showConfirm(
t('auth.logout'),
t('auth.confirmLogout'),
- [
- { text: t('common.cancel'), style: 'cancel' },
- {
- text: t('auth.logout'),
- style: 'destructive',
- onPress: performLogout,
- },
- ]
+ t('auth.logout'),
+ performLogout,
+ { confirmStyle: 'destructive' }
);
}
- }, [isDirty, t, performLogout]);
+ }, [isDirty, showConfirm, t, performLogout]);
return {
logoutUserInitiated,