Skip to content

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

Tweak EmailDomainField.tsx to use email/alias simplified switcher UX (#1473)

Leendert de Borstf2c85310659c
diff --git a/apps/browser-extension/src/entrypoints/popup/components/Forms/EmailDomainField.tsx b/apps/browser-extension/src/entrypoints/popup/components/Forms/EmailDomainField.tsx
index 19ccc9fee..4b94a63b0 100644
--- a/apps/browser-extension/src/entrypoints/popup/components/Forms/EmailDomainField.tsx
+++ b/apps/browser-extension/src/entrypoints/popup/components/Forms/EmailDomainField.tsx
@@ -115,15 +115,20 @@ const EmailDomainField: React.FC<EmailDomainFieldProps> = ({
setSelectedDomain(domain);
/*
- * Only auto-switch modes in uncontrolled mode.
- * In controlled mode, the parent manages the mode state.
+ * Auto-detect mode based on domain recognition.
+ * In controlled mode, notify parent via onEmailModeChange.
+ * In uncontrolled mode, update internal state directly.
*/
- if (!isControlled) {
- // Check if it's a known domain (public, private, or hidden private)
- const isKnownDomain = publicEmailDomains.includes(domain) ||
- privateEmailDomains.includes(domain) ||
- hiddenPrivateEmailDomains.includes(domain);
- // Switch to domain chooser mode if domain is recognized
+ // Check if it's a known domain (public, private, or hidden private)
+ const isKnownDomain = publicEmailDomains.includes(domain) ||
+ privateEmailDomains.includes(domain) ||
+ hiddenPrivateEmailDomains.includes(domain);
+
+ if (isControlled && onEmailModeChange) {
+ // Controlled mode: notify parent that mode should be alias (domain chooser) if domain is known
+ onEmailModeChange(!isKnownDomain);
+ } else if (!isControlled) {
+ // Uncontrolled mode: update internal state directly
setIsCustomDomain(!isKnownDomain);
}
} else {
@@ -139,20 +144,14 @@ const EmailDomainField: React.FC<EmailDomainFieldProps> = ({
}
}
}
- // eslint-disable-next-line react-hooks/exhaustive-deps
- }, [value, privateEmailDomains, hiddenPrivateEmailDomains, showPrivateDomains, isControlled]);
+ }, [value, publicEmailDomains, privateEmailDomains, hiddenPrivateEmailDomains, showPrivateDomains, isControlled, onEmailModeChange, selectedDomain, setIsCustomDomain]);
/*
- * Re-check domain mode when private domains finish loading.
+ * Re-check domain mode when domains finish loading.
* This handles the case where value was set before domains were loaded.
- * Only applies in uncontrolled mode - in controlled mode, parent manages the state.
+ * Works in both controlled and uncontrolled modes.
*/
useEffect(() => {
- // Skip auto-correction in controlled mode
- if (isControlled) {
- return;
- }
-
if (!value || !value.includes('@')) {
return;
}
@@ -162,16 +161,60 @@ const EmailDomainField: React.FC<EmailDomainFieldProps> = ({
return;
}
- // Check if the domain is now recognized after private domains loaded
+ // Check if the domain is now recognized after domains loaded
const isKnownDomain = publicEmailDomains.includes(domain) ||
privateEmailDomains.includes(domain) ||
hiddenPrivateEmailDomains.includes(domain);
- // If domain is recognized and we're in custom mode, switch to domain chooser
- if (isKnownDomain && isCustomDomain) {
- setIsCustomDomain(false);
+ if (isControlled && onEmailModeChange) {
+ // Controlled mode: notify parent that mode should be alias (domain chooser) if domain is known
+ onEmailModeChange(!isKnownDomain);
+ } else if (!isControlled) {
+ /*
+ * Uncontrolled mode: update internal state directly.
+ * If domain is recognized and we're in custom mode, switch to domain chooser.
+ */
+ if (isKnownDomain && isCustomDomain) {
+ setIsCustomDomain(false);
+ }
}
- }, [publicEmailDomains, privateEmailDomains, hiddenPrivateEmailDomains, value, isCustomDomain, isControlled, setIsCustomDomain]);
+ }, [publicEmailDomains, privateEmailDomains, hiddenPrivateEmailDomains, value, isCustomDomain, isControlled, onEmailModeChange, setIsCustomDomain]);
+
+ /*
+ * Ensure that when in alias mode (domain chooser), the value always includes the domain.
+ * This handles the case when switching from email mode to alias mode, where the value
+ * might be just a prefix without the domain.
+ *
+ * This effect runs after the toggle function, ensuring the value is updated with the domain.
+ */
+ useEffect(() => {
+ // Only handle this in alias mode (not isCustomDomain)
+ if (isCustomDomain) {
+ return;
+ }
+
+ // If value exists but doesn't include @, we need to add the domain
+ if (value && !value.includes('@') && value.trim()) {
+ const defaultDomain = showPrivateDomains && privateEmailDomains[0]
+ ? privateEmailDomains[0]
+ : publicEmailDomains[0];
+
+ const domainToUse = selectedDomain || defaultDomain;
+
+ // Only proceed if we have a domain available
+ if (domainToUse) {
+ // Update selectedDomain if not set
+ if (!selectedDomain && defaultDomain) {
+ setSelectedDomain(defaultDomain);
+ }
+ /*
+ * Call onChange with the full email - this will update the parent's value.
+ * Once the value includes @, this effect won't trigger again.
+ */
+ onChange(`${value}@${domainToUse}`);
+ }
+ }
+ }, [value, isCustomDomain, selectedDomain, showPrivateDomains, privateEmailDomains, publicEmailDomains, onChange]);
// Handle local part changes
const handleLocalPartChange = useCallback((e: React.ChangeEvent<HTMLInputElement>) => {
@@ -195,10 +238,28 @@ const EmailDomainField: React.FC<EmailDomainFieldProps> = ({
// If the local part is empty, treat the whole field as empty
if (!newLocalPart || newLocalPart.trim() === '') {
onChange('');
- } else if (selectedDomain) {
- onChange(`${newLocalPart}@${selectedDomain}`);
+ } else {
+ /*
+ * Always ensure we have a domain - use selectedDomain if available, otherwise use default.
+ * This ensures that when user types in alias mode, we always have a domain to construct the full email.
+ */
+ const domainToUse = selectedDomain ||
+ (showPrivateDomains && privateEmailDomains[0] ? privateEmailDomains[0] : publicEmailDomains[0] || '');
+ if (domainToUse) {
+ onChange(`${newLocalPart}@${domainToUse}`);
+ // Update selectedDomain if it wasn't set
+ if (!selectedDomain) {
+ setSelectedDomain(domainToUse);
+ }
+ } else {
+ /*
+ * No domain available yet - just store the local part temporarily.
+ * This should be rare, but handle it gracefully.
+ */
+ onChange(newLocalPart);
+ }
}
- }, [isCustomDomain, selectedDomain, onChange, setIsCustomDomain]);
+ }, [isCustomDomain, selectedDomain, onChange, setIsCustomDomain, showPrivateDomains, privateEmailDomains, publicEmailDomains]);
// Select a domain from the popup
const selectDomain = useCallback((domain: string) => {
@@ -236,12 +297,22 @@ const EmailDomainField: React.FC<EmailDomainFieldProps> = ({
: publicEmailDomains[0];
setSelectedDomain(defaultDomain);
- // Only add domain if we have a local part
+ /*
+ * Use the same simple pattern as mobile app:
+ * 1. Check localPart first (most reliable, kept in sync by useEffect)
+ * 2. Fallback to value if it doesn't have @ (value is just a prefix)
+ *
+ * Note: If value has @, the useEffect will have already extracted and set localPart,
+ * so checking localPart first is the right approach.
+ */
if (localPart && localPart.trim()) {
+ // localPart is available - use it directly
onChange(`${localPart}@${defaultDomain}`);
} else if (value && !value.includes('@')) {
- // If we have a value without @, add the domain
+ // Fallback: value is just a prefix without @
onChange(`${value}@${defaultDomain}`);
+ // Also update localPart to keep in sync
+ setLocalPart(value);
}
}
}, [isCustomDomain, value, localPart, showPrivateDomains, publicEmailDomains, privateEmailDomains, onChange, setIsCustomDomain]);
@@ -268,6 +339,7 @@ const EmailDomainField: React.FC<EmailDomainFieldProps> = ({
/**
* Handle the "Generate alias email" button click.
* Calls onGenerateAlias if provided, and switches to domain chooser mode.
+ * Also ensures the value is updated with the domain when switching modes.
*/
const handleGenerateAliasClick = useCallback(() => {
if (onGenerateAlias) {
@@ -275,7 +347,30 @@ const EmailDomainField: React.FC<EmailDomainFieldProps> = ({
}
// Always switch to domain chooser mode
setIsCustomDomain(false);
- }, [onGenerateAlias, setIsCustomDomain]);
+
+ /*
+ * When switching to alias mode, ensure the value includes the domain.
+ * Use the same simple pattern as toggleCustomDomain: check localPart first, then value.
+ */
+ const defaultDomain = showPrivateDomains && privateEmailDomains[0]
+ ? privateEmailDomains[0]
+ : publicEmailDomains[0];
+
+ if (defaultDomain) {
+ setSelectedDomain(defaultDomain);
+
+ // Use the same pattern as toggleCustomDomain: check localPart first, then value
+ if (localPart && localPart.trim()) {
+ // localPart is available - use it directly
+ onChange(`${localPart}@${defaultDomain}`);
+ } else if (value && !value.includes('@')) {
+ // Fallback: value is just a prefix without @
+ onChange(`${value}@${defaultDomain}`);
+ // Also update localPart to keep in sync
+ setLocalPart(value);
+ }
+ }
+ }, [onGenerateAlias, setIsCustomDomain, showPrivateDomains, privateEmailDomains, publicEmailDomains, value, localPart, onChange]);
return (
<div className="space-y-2">
diff --git a/apps/browser-extension/src/entrypoints/popup/pages/items/ItemAddEdit.tsx b/apps/browser-extension/src/entrypoints/popup/pages/items/ItemAddEdit.tsx
index f5027e346..695dbf5bf 100644
--- a/apps/browser-extension/src/entrypoints/popup/pages/items/ItemAddEdit.tsx
+++ b/apps/browser-extension/src/entrypoints/popup/pages/items/ItemAddEdit.tsx
@@ -358,6 +358,12 @@ const ItemAddEdit: React.FC = () => {
setItem(newItem);
+ /*
+ * Initialize email field mode based on item type
+ * Login type: email mode (free text), Alias type: alias mode (domain chooser)
+ */
+ setIsLoginEmailInEmailMode(effectiveType === ItemTypes.Login);
+
// Set the detected URL in field values if we have one
if (serviceUrl) {
setFieldValues(prev => ({
@@ -824,6 +830,12 @@ const ItemAddEdit: React.FC = () => {
// Reset alias generated flag, so alias fields will be filled (again) if they are shown by the new type
aliasGeneratedRef.current = false;
+ /*
+ * Update email field mode based on new item type
+ * Login type: email mode (free text), Alias type: alias mode (domain chooser)
+ */
+ setIsLoginEmailInEmailMode(newType === ItemTypes.Login);
+
setItem({
...item,
ItemType: newType,
diff --git a/apps/mobile-app/app/(tabs)/items/add-edit.tsx b/apps/mobile-app/app/(tabs)/items/add-edit.tsx
index 016d11a1f..fa68f7eac 100644
--- a/apps/mobile-app/app/(tabs)/items/add-edit.tsx
+++ b/apps/mobile-app/app/(tabs)/items/add-edit.tsx
@@ -11,7 +11,7 @@ import Toast from 'react-native-toast-message';
import type { Folder } from '@/utils/db/repositories/FolderRepository';
import { CreateIdentityGenerator, CreateUsernameEmailGenerator, Gender, Identity, IdentityHelperUtils, convertAgeRangeToBirthdateOptions } from '@/utils/dist/core/identity-generator';
-import type { Attachment, Item, ItemField, TotpCode, ItemType, FieldType } from '@/utils/dist/core/models/vault';
+import type { Attachment, Item, ItemField, TotpCode, ItemType, FieldType, PasswordSettings } from '@/utils/dist/core/models/vault';
import { ItemTypes, getSystemFieldsForItemType, getOptionalFieldsForItemType, isFieldShownByDefault, getSystemField, fieldAppliesToType, FieldCategories, FieldTypes } from '@/utils/dist/core/models/vault';
import type { FaviconExtractModel } from '@/utils/dist/core/models/webapi';
import { CreatePasswordGenerator, PasswordGenerator } from '@/utils/dist/core/password-generator';
@@ -126,6 +126,9 @@ export default function AddEditItemScreen(): React.ReactNode {
email: string | null;
}>({ username: null, password: null, email: null });
+ // Password settings state (loaded immediately to prevent flicker)
+ const [passwordSettings, setPasswordSettings] = useState<PasswordSettings | undefined>(undefined);
+
/**
* If we received an ID, we're in edit mode.
*/
@@ -395,6 +398,7 @@ export default function AddEditItemScreen(): React.ReactNode {
/**
* Load an existing item from the database in edit mode.
+ * Note: passwordSettings should already be loaded before this is called.
*/
const loadExistingItem = useCallback(async (): Promise<void> => {
try {
@@ -483,8 +487,23 @@ export default function AddEditItemScreen(): React.ReactNode {
}
if (isEditMode) {
+ // Load password settings BEFORE loading item so it's available when components render
+ try {
+ const settings = await dbContext.sqliteClient!.getPasswordSettings();
+ setPasswordSettings(settings);
+ } catch (err) {
+ console.error('Error loading password settings:', err);
+ }
+ // Now load the item - passwordSettings is already set
loadExistingItem();
} else {
+ // Create mode - load password settings for new items too
+ try {
+ const settings = await dbContext.sqliteClient!.getPasswordSettings();
+ setPasswordSettings(settings);
+ } catch (err) {
+ console.error('Error loading password settings:', err);
+ }
// Create mode - initialize new item
let serviceName = '';
let decodedItemUrl = '';
@@ -1056,6 +1075,7 @@ export default function AddEditItemScreen(): React.ReactNode {
isNewCredential={!isEditMode}
onRemove={onRemove}
testID={testID}
+ initialSettings={passwordSettings}
/>
);
@@ -1071,7 +1091,9 @@ export default function AddEditItemScreen(): React.ReactNode {
/>
);
- case FieldTypes.Email:
+ case FieldTypes.Email: {
+ // Default to email mode (free text) for Login items, alias mode (domain chooser) for Alias items
+ const defaultEmailMode = item?.ItemType === ItemTypes.Login;
return (
<EmailDomainField
value={stringValue}
@@ -1079,8 +1101,10 @@ export default function AddEditItemScreen(): React.ReactNode {
label={label}
onRemove={onRemove}
testID={testID}
+ defaultEmailMode={defaultEmailMode}
/>
);
+ }
case FieldTypes.TextArea:
return (
@@ -1130,7 +1154,7 @@ export default function AddEditItemScreen(): React.ReactNode {
/>
);
}
- }, [fieldValues, handleFieldChange, isPasswordVisible, isEditMode, aliasFieldsShownByDefault, generateRandomUsername, t, getFieldTestId]);
+ }, [fieldValues, handleFieldChange, isPasswordVisible, isEditMode, aliasFieldsShownByDefault, generateRandomUsername, t, getFieldTestId, item?.ItemType, passwordSettings]);
const styles = StyleSheet.create({
container: {
diff --git a/apps/mobile-app/components/form/AdvancedPasswordField.tsx b/apps/mobile-app/components/form/AdvancedPasswordField.tsx
index 2c16a62f8..49e8f10e4 100644
--- a/apps/mobile-app/components/form/AdvancedPasswordField.tsx
+++ b/apps/mobile-app/components/form/AdvancedPasswordField.tsx
@@ -30,6 +30,8 @@ type AdvancedPasswordFieldProps = Omit<TextInputProps, 'value' | 'onChangeText'>
onRemove?: () => void;
/** Optional testID for the text input */
testID?: string;
+ /** Optional initial password settings to use immediately (prevents flicker) */
+ initialSettings?: PasswordSettings;
}
const AdvancedPasswordFieldComponent = forwardRef<AdvancedPasswordFieldRef, AdvancedPasswordFieldProps>(({
@@ -42,6 +44,7 @@ const AdvancedPasswordFieldComponent = forwardRef<AdvancedPasswordFieldRef, Adva
isNewCredential = false,
onRemove,
testID,
+ initialSettings,
...props
}, ref) => {
const colors = useColors();
@@ -49,12 +52,22 @@ const AdvancedPasswordFieldComponent = forwardRef<AdvancedPasswordFieldRef, Adva
const inputRef = useRef<TextInput>(null);
const [internalShowPassword, setInternalShowPassword] = useState(false);
const [showSettingsModal, setShowSettingsModal] = useState(false);
- const [currentSettings, setCurrentSettings] = useState<PasswordSettings | null>(null);
+ // Initialize settings immediately from initialSettings if provided, otherwise null
+ const [currentSettings, setCurrentSettings] = useState<PasswordSettings | null>(initialSettings || null);
const [previewPassword, setPreviewPassword] = useState<string>('');
- const [sliderValue, setSliderValue] = useState<number>(16);
+ // Initialize slider value immediately from initialSettings or value length, otherwise default to 16
+ const [sliderValue, setSliderValue] = useState<number>(() => {
+ if (initialSettings) {
+ return initialSettings.Length;
+ }
+ if (!isNewCredential && value && value.length > 0) {
+ return value.length;
+ }
+ return 16;
+ });
const lastGeneratedLength = useRef<number>(0);
const isSliding = useRef(false);
- const hasSetInitialLength = useRef(false);
+ const hasSetInitialLength = useRef(!!initialSettings || (!isNewCredential && value && value.length > 0));
const dbContext = useDb();
const showPassword = controlledShowPassword ?? internalShowPassword;
@@ -66,24 +79,31 @@ const AdvancedPasswordFieldComponent = forwardRef<AdvancedPasswordFieldRef, Adva
}
}, [controlledShowPassword, onShowPasswordChange]);
- // Load password settings from database
+ // Load password settings from database (only if initialSettings not provided)
useEffect(() => {
+ // If we already have initialSettings, skip loading from database
+ if (initialSettings) {
+ return;
+ }
const loadSettings = async () => {
try {
if (dbContext.sqliteClient) {
const settings = await dbContext.sqliteClient.getPasswordSettings();
setCurrentSettings(settings);
- setSliderValue(settings.Length);
- hasSetInitialLength.current = true;
+ // Only update slider if we haven't set it from value yet
+ if (!hasSetInitialLength.current) {
+ setSliderValue(settings.Length);
+ hasSetInitialLength.current = true;
+ }
}
} catch (error) {
console.error('Error loading password settings:', error);
}
};
loadSettings();
- }, [dbContext.sqliteClient]);
+ }, [dbContext.sqliteClient, initialSettings]);
- // Sync slider value with password length
+ // Sync slider value with password length (only if not already initialized)
useEffect(() => {
if (!hasSetInitialLength.current) {
if (!isNewCredential && value && value.length > 0) {
diff --git a/apps/mobile-app/components/form/EmailDomainField.tsx b/apps/mobile-app/components/form/EmailDomainField.tsx
index dbfbee1bd..bd0635e23 100644
--- a/apps/mobile-app/components/form/EmailDomainField.tsx
+++ b/apps/mobile-app/components/form/EmailDomainField.tsx
@@ -1,5 +1,5 @@
import MaterialIcons from '@expo/vector-icons/MaterialIcons';
-import React, { useState, useEffect, useCallback, useMemo } from 'react';
+import React, { useState, useEffect, useCallback, useMemo, useRef } from 'react';
import { useTranslation } from 'react-i18next';
import { View, Text, TextInput, TouchableOpacity, Modal, ScrollView, Pressable, StyleSheet } from 'react-native';
@@ -7,6 +7,7 @@ import { useColors } from '@/hooks/useColorScheme';
import { ThemedText } from '@/components/themed/ThemedText';
import { useDb } from '@/context/DbContext';
+import { CreateIdentityGenerator, convertAgeRangeToBirthdateOptions } from '@/utils/dist/core/identity-generator';
type EmailDomainFieldProps = {
value: string;
@@ -18,6 +19,8 @@ type EmailDomainFieldProps = {
onRemove?: () => void;
/** Optional testID for the text input */
testID?: string;
+ /** Optional: default to email mode (free text) instead of alias mode (domain chooser). Defaults to false. */
+ defaultEmailMode?: boolean;
}
// Hardcoded public email domains (same as in browser extension)
@@ -45,34 +48,103 @@ export const EmailDomainField: React.FC<EmailDomainFieldProps> = ({
required = false,
label,
onRemove,
- testID
+ testID,
+ defaultEmailMode = false
}) => {
const { t } = useTranslation();
const colors = useColors();
const dbContext = useDb();
- const [isCustomDomain, setIsCustomDomain] = useState(false);
- const [localPart, setLocalPart] = useState('');
- const [selectedDomain, setSelectedDomain] = useState('');
+
+ // Initialize mode immediately based on value (before domains load)
+ // This prevents flicker by setting the correct mode right away
+ const getInitialMode = useCallback((val: string): boolean => {
+ if (!val || !val.includes('@')) {
+ return defaultEmailMode;
+ }
+ const [, domain] = val.split('@');
+ // Check against PUBLIC_EMAIL_DOMAINS immediately (hardcoded, always available)
+ // This gives us an immediate answer for most cases
+ const isKnownPublicDomain = PUBLIC_EMAIL_DOMAINS.includes(domain);
+ // If it's a known public domain, use alias mode (not custom)
+ // Otherwise, default to email mode until private domains load
+ return !isKnownPublicDomain;
+ }, [defaultEmailMode]);
+
+ const [isCustomDomain, setIsCustomDomain] = useState(() => getInitialMode(value));
+ const [localPart, setLocalPart] = useState(() => {
+ if (value && value.includes('@')) {
+ return value.split('@')[0];
+ }
+ return value || '';
+ });
+ const [selectedDomain, setSelectedDomain] = useState(() => {
+ if (value && value.includes('@')) {
+ return value.split('@')[1];
+ }
+ return PUBLIC_EMAIL_DOMAINS[0] || '';
+ });
const [isModalVisible, setIsModalVisible] = useState(false);
+
+ // Use refs to store domains - this prevents re-renders when they load
+ const privateEmailDomainsRef = useRef<string[]>([]);
+ const hiddenPrivateEmailDomainsRef = useRef<string[]>([]);
+ const hasDomainsLoadedRef = useRef(false);
+
+ // State for domains (only used for UI display in modal, not for mode detection)
const [privateEmailDomains, setPrivateEmailDomains] = useState<string[]>([]);
const [hiddenPrivateEmailDomains, setHiddenPrivateEmailDomains] = useState<string[]>([]);
+
+ // Track value changes to avoid unnecessary re-initialization
+ const lastValueRef = useRef<string>(value);
+ const hasInitializedFromValue = useRef(false);
// Get private email domains from vault metadata
useEffect(() => {
/**
- * Load private email domains from vault metadata, excluding hidden ones from UI.
+ * Load private email domains from vault metadata.
+ * Store in refs immediately (no re-render), then update state for modal display.
+ * This prevents flicker by avoiding re-renders when domains load.
*/
const loadDomains = async (): Promise<void> => {
try {
const metadata = await dbContext.getVaultMetadata();
- setPrivateEmailDomains(metadata?.privateEmailDomains ?? []);
- setHiddenPrivateEmailDomains(metadata?.hiddenPrivateEmailDomains ?? []);
+ const privateDomains = metadata?.privateEmailDomains ?? [];
+ const hiddenDomains = metadata?.hiddenPrivateEmailDomains ?? [];
+
+ // Update refs immediately (no re-render triggered)
+ privateEmailDomainsRef.current = privateDomains;
+ hiddenPrivateEmailDomainsRef.current = hiddenDomains;
+ hasDomainsLoadedRef.current = true;
+
+ // Update state for modal display (triggers re-render, but only affects modal)
+ setPrivateEmailDomains(privateDomains);
+ setHiddenPrivateEmailDomains(hiddenDomains);
+
+ // Check if we need to update mode now that domains are loaded
+ // Only update if value has an @ and we're in custom mode
+ if (value && value.includes('@')) {
+ const domain = value.split('@')[1];
+ if (domain) {
+ const isKnownDomain = PUBLIC_EMAIL_DOMAINS.includes(domain) ||
+ privateDomains.includes(domain) ||
+ hiddenDomains.includes(domain);
+
+ // Only update mode if domain is now recognized AND we're in custom mode
+ // Use functional update to avoid stale closure and prevent unnecessary updates
+ setIsCustomDomain(prev => {
+ if (isKnownDomain && prev) {
+ return false; // Switch to alias mode
+ }
+ return prev; // No change needed - prevents re-render
+ });
+ }
+ }
} catch (err) {
console.error('Error loading email domains:', err);
}
};
loadDomains();
- }, [dbContext]);
+ }, [dbContext, value]);
// Check if private domains are available and valid
const showPrivateDomains = useMemo(() => {
@@ -80,42 +152,73 @@ export const EmailDomainField: React.FC<EmailDomainFieldProps> = ({
!(privateEmailDomains.length === 1 && (privateEmailDomains[0] === 'DISABLED.TLD' || privateEmailDomains[0] === ''));
}, [privateEmailDomains]);
- // Initialize state from value prop
+ // Initialize state from value prop - only runs when value actually changes
useEffect(() => {
+ // Skip if value hasn't changed and we've already initialized
+ if (value === lastValueRef.current && hasInitializedFromValue.current) {
+ return;
+ }
+ lastValueRef.current = value;
+
if (!value) {
- // Set default domain
- if (showPrivateDomains && privateEmailDomains[0]) {
- setSelectedDomain(privateEmailDomains[0]);
- } else if (PUBLIC_EMAIL_DOMAINS[0]) {
- setSelectedDomain(PUBLIC_EMAIL_DOMAINS[0]);
+ // Set default domain using refs (no re-render)
+ const defaultDomain = hasDomainsLoadedRef.current && privateEmailDomainsRef.current[0]
+ ? privateEmailDomainsRef.current[0]
+ : PUBLIC_EMAIL_DOMAINS[0];
+ if (defaultDomain && defaultDomain !== selectedDomain) {
+ setSelectedDomain(defaultDomain);
}
+ hasInitializedFromValue.current = true;
return;
}
if (value.includes('@')) {
const [local, domain] = value.split('@');
- setLocalPart(local);
- setSelectedDomain(domain);
-
- // Check if it's a custom domain (including hidden private domains as known domains)
+
+ // Only update if values actually changed (prevents unnecessary re-renders)
+ if (local !== localPart) {
+ setLocalPart(local);
+ }
+ if (domain !== selectedDomain) {
+ setSelectedDomain(domain);
+ }
+
+ // Check mode using refs (no re-render) - works even before domains load
const isKnownDomain = PUBLIC_EMAIL_DOMAINS.includes(domain) ||
- privateEmailDomains.includes(domain) ||
- hiddenPrivateEmailDomains.includes(domain);
- setIsCustomDomain(!isKnownDomain);
+ privateEmailDomainsRef.current.includes(domain) ||
+ hiddenPrivateEmailDomainsRef.current.includes(domain);
+
+ // Only update mode if it needs to change (prevents flicker)
+ setIsCustomDomain(prev => {
+ const newMode = !isKnownDomain;
+ return newMode !== prev ? newMode : prev;
+ });
+
+ hasInitializedFromValue.current = true;
} else {
- setLocalPart(value);
- // Don't reset isCustomDomain here - preserve the current mode
-
+ if (value !== localPart) {
+ setLocalPart(value);
+ }
// Set default domain if not already set
- if (!selectedDomain && !value.includes('@')) {
- if (showPrivateDomains && privateEmailDomains[0]) {
- setSelectedDomain(privateEmailDomains[0]);
- } else if (PUBLIC_EMAIL_DOMAINS[0]) {
- setSelectedDomain(PUBLIC_EMAIL_DOMAINS[0]);
+ if (!selectedDomain) {
+ const defaultDomain = hasDomainsLoadedRef.current && privateEmailDomainsRef.current[0]
+ ? privateEmailDomainsRef.current[0]
+ : PUBLIC_EMAIL_DOMAINS[0];
+ if (defaultDomain) {
+ setSelectedDomain(defaultDomain);
}
}
+ hasInitializedFromValue.current = true;
}
- }, [value, privateEmailDomains, hiddenPrivateEmailDomains, showPrivateDomains]);
+ }, [value, localPart, selectedDomain]);
+
+ /*
+ * Re-check domain mode when domains finish loading.
+ * This handles the case where value was set before domains were loaded.
+ * Only switches mode if domain is now recognized and we're currently in custom mode.
+ */
+ // Note: Domain mode checking is now handled in the loadDomains effect above
+ // This prevents the need for a separate effect that triggers re-renders
// Handle local part changes
const handleLocalPartChange = useCallback((newText: string) => {
@@ -156,8 +259,29 @@ export const EmailDomainField: React.FC<EmailDomainFieldProps> = ({
setIsModalVisible(false);
}, [localPart, onChange]);
+ /**
+ * Generate a random email prefix using identity generator.
+ */
+ const generateRandomEmailPrefix = useCallback(async (): Promise<string> => {
+ try {
+ const identityLanguage = await dbContext.sqliteClient!.getEffectiveIdentityLanguage();
+ const identityGenerator = CreateIdentityGenerator(identityLanguage);
+
+ const genderPreference = await dbContext.sqliteClient!.getDefaultIdentityGender();
+ const ageRange = await dbContext.sqliteClient!.getDefaultIdentityAgeRange();
+ const birthdateOptions = convertAgeRangeToBirthdateOptions(ageRange);
+
+ const identity = identityGenerator.generateRandomIdentity(genderPreference, birthdateOptions);
+ return identity.emailPrefix;
+ } catch (error) {
+ console.error('Error generating random email prefix:', error);
+ // Fallback to a simple random string if generation fails
+ return `user${Math.random().toString(36).substring(2, 9)}`;
+ }
+ }, [dbContext]);
+
// Toggle between custom domain and domain chooser
- const toggleCustomDomain = useCallback(() => {
+ const toggleCustomDomain = useCallback(async () => {
const newIsCustom = !isCustomDomain;
setIsCustomDomain(newIsCustom);
@@ -170,21 +294,18 @@ export const EmailDomainField: React.FC<EmailDomainFieldProps> = ({
setLocalPart(local);
}
} else {
- // Switching to domain chooser mode
+ // Switching to domain chooser mode - generate a random email prefix
const defaultDomain = showPrivateDomains && privateEmailDomains[0]
? privateEmailDomains[0]
: PUBLIC_EMAIL_DOMAINS[0];
setSelectedDomain(defaultDomain);
- // Only add domain if we have a local part
- if (localPart && localPart.trim()) {
- onChange(`${localPart}@${defaultDomain}`);
- } else if (value && !value.includes('@')) {
- // If we have a value without @, add the domain
- onChange(`${value}@${defaultDomain}`);
- }
+ // Generate a random email prefix instead of reusing the old one
+ const randomPrefix = await generateRandomEmailPrefix();
+ setLocalPart(randomPrefix);
+ onChange(`${randomPrefix}@${defaultDomain}`);
}
- }, [isCustomDomain, value, localPart, showPrivateDomains, privateEmailDomains, onChange]);
+ }, [isCustomDomain, value, showPrivateDomains, privateEmailDomains, onChange, generateRandomEmailPrefix]);
const styles = StyleSheet.create({
container: {
@@ -279,6 +400,28 @@ export const EmailDomainField: React.FC<EmailDomainFieldProps> = ({
justifyContent: 'space-between',
marginBottom: 4,
},
+ switcherContainer: {
+ alignItems: 'center',
+ flexDirection: 'row',
+ },
+ switcherButton: {
+ fontSize: 14,
+ fontWeight: '600',
+ },
+ switcherButtonActive: {
+ color: colors.primary,
+ fontWeight: '600',
+ },
+ switcherButtonInactive: {
+ color: colors.textMuted,
+ fontWeight: '400',
+ opacity: 0.5,
+ },
+ switcherSeparator: {
+ color: colors.textMuted,
+ fontSize: 14,
+ marginHorizontal: 6,
+ },
removeButton: {
padding: 4,
},
@@ -336,22 +479,37 @@ export const EmailDomainField: React.FC<EmailDomainFieldProps> = ({
paddingHorizontal: 12,
paddingVertical: 10,
},
- toggleButton: {
- marginTop: 8,
- },
- toggleButtonText: {
- color: colors.primary,
- fontSize: 14,
- },
});
return (
<View style={styles.container}>
<View style={styles.labelContainer}>
- <Text style={styles.label}>
- {label}
+ <View style={styles.switcherContainer}>
+ <TouchableOpacity
+ onPress={isCustomDomain ? undefined : toggleCustomDomain}
+ disabled={isCustomDomain}
+ >
+ <Text style={[
+ styles.switcherButton,
+ isCustomDomain ? styles.switcherButtonActive : styles.switcherButtonInactive
+ ]}>
+ {t('items.email')}
+ </Text>
+ </TouchableOpacity>
+ <Text style={styles.switcherSeparator}>/</Text>
+ <TouchableOpacity
+ onPress={!isCustomDomain ? undefined : toggleCustomDomain}
+ disabled={!isCustomDomain}
+ >
+ <Text style={[
+ styles.switcherButton,
+ !isCustomDomain ? styles.switcherButtonActive : styles.switcherButtonInactive
+ ]}>
+ {t('items.alias')}
+ </Text>
+ </TouchableOpacity>
{required && <Text style={styles.requiredAsterisk}> *</Text>}
- </Text>
+ </View>
{onRemove && (
<TouchableOpacity style={styles.removeButton} onPress={onRemove}>
<MaterialIcons name="close" size={18} color={colors.textMuted} />
@@ -388,14 +546,6 @@ export const EmailDomainField: React.FC<EmailDomainFieldProps> = ({
)}
</View>
- <TouchableOpacity style={styles.toggleButton} onPress={toggleCustomDomain}>
- <Text style={styles.toggleButtonText}>
- {isCustomDomain
- ? t('items.useDomainChooser')
- : t('items.enterCustomDomain')}
- </Text>
- </TouchableOpacity>
-
{error && <Text style={styles.errorText}>{error}</Text>}
{/* Domain selection modal */}