Privacy-first password manager with built-in email aliasing. Fully encrypted and self-hostable.
Add field history modal UI, tweak modal UI in dark mode (#1404)
Leendert de Borst8096b7d7e9ae
diff --git a/apps/mobile-app/components/folders/DeleteFolderModal.tsx b/apps/mobile-app/components/folders/DeleteFolderModal.tsxindex 5e5b01c4c..344088a2f 100644--- a/apps/mobile-app/components/folders/DeleteFolderModal.tsx+++ b/apps/mobile-app/components/folders/DeleteFolderModal.tsx@@ -10,7 +10,7 @@ import {ActivityIndicator,} from 'react-native';-import { useColors } from '@/hooks/useColorScheme';+import { useColors, useColorScheme } from '@/hooks/useColorScheme';interface IDeleteFolderModalProps {isOpen: boolean;@@ -32,6 +32,7 @@ export const DeleteFolderModal: React.FC<IDeleteFolderModalProps> = ({}) => {const { t } = useTranslation();const colors = useColors();+ const colorScheme = useColorScheme();const [isSubmitting, setIsSubmitting] = useState(false);/**@@ -76,7 +77,7 @@ export const DeleteFolderModal: React.FC<IDeleteFolderModalProps> = ({const styles = StyleSheet.create({backdrop: {alignItems: 'center',- backgroundColor: 'rgba(0, 0, 0, 0.5)',+ backgroundColor: colorScheme === 'dark' ? 'rgba(255, 255, 255, 0.15)' : 'rgba(0, 0, 0, 0.5)',flex: 1,justifyContent: 'center',},diff --git a/apps/mobile-app/components/folders/FolderModal.tsx b/apps/mobile-app/components/folders/FolderModal.tsxindex 717c1d2fc..64ad096f0 100644--- a/apps/mobile-app/components/folders/FolderModal.tsx+++ b/apps/mobile-app/components/folders/FolderModal.tsx@@ -14,7 +14,7 @@ import {ActivityIndicator,} from 'react-native';-import { useColors } from '@/hooks/useColorScheme';+import { useColors, useColorScheme } from '@/hooks/useColorScheme';interface IFolderModalProps {isOpen: boolean;@@ -36,6 +36,7 @@ export const FolderModal: React.FC<IFolderModalProps> = ({}) => {const { t } = useTranslation();const colors = useColors();+ const colorScheme = useColorScheme();const [folderName, setFolderName] = useState(initialName);const [isSubmitting, setIsSubmitting] = useState(false);const [error, setError] = useState<string | null>(null);@@ -83,7 +84,7 @@ export const FolderModal: React.FC<IFolderModalProps> = ({const styles = StyleSheet.create({backdrop: {alignItems: 'center',- backgroundColor: 'rgba(0, 0, 0, 0.5)',+ backgroundColor: colorScheme === 'dark' ? 'rgba(255, 255, 255, 0.15)' : 'rgba(0, 0, 0, 0.5)',flex: 1,justifyContent: 'center',},diff --git a/apps/mobile-app/components/folders/FolderSelector.tsx b/apps/mobile-app/components/folders/FolderSelector.tsxindex 392437f8b..5af9ef024 100644--- a/apps/mobile-app/components/folders/FolderSelector.tsx+++ b/apps/mobile-app/components/folders/FolderSelector.tsx@@ -10,7 +10,7 @@ import {ScrollView,} from 'react-native';-import { useColors } from '@/hooks/useColorScheme';+import { useColors, useColorScheme } from '@/hooks/useColorScheme';type Folder = {Id: string;@@ -36,6 +36,7 @@ export const FolderSelector: React.FC<IFolderSelectorProps> = ({}) => {const { t } = useTranslation();const colors = useColors();+ const colorScheme = useColorScheme();const [showModal, setShowModal] = useState(false);const selectedFolder = folders.find(f => f.Id === selectedFolderId);@@ -51,7 +52,7 @@ export const FolderSelector: React.FC<IFolderSelectorProps> = ({const styles = StyleSheet.create({backdrop: {alignItems: 'center',- backgroundColor: 'rgba(0, 0, 0, 0.5)',+ backgroundColor: colorScheme === 'dark' ? 'rgba(255, 255, 255, 0.15)' : 'rgba(0, 0, 0, 0.5)',flex: 1,justifyContent: 'center',},diff --git a/apps/mobile-app/components/form/FormInputCopyToClipboard.tsx b/apps/mobile-app/components/form/FormInputCopyToClipboard.tsxindex cfa6af934..9851c3a7d 100644--- a/apps/mobile-app/components/form/FormInputCopyToClipboard.tsx+++ b/apps/mobile-app/components/form/FormInputCopyToClipboard.tsx@@ -15,6 +15,8 @@ type FormInputCopyToClipboardProps = {label: string;value: string | undefined;type?: 'text' | 'password';+ /** Optional element to render next to the label (e.g., history button) */+ labelSuffix?: React.ReactNode;}/**@@ -24,6 +26,7 @@ const FormInputCopyToClipboard: React.FC<FormInputCopyToClipboardProps> = ({label,value,type = 'text',+ labelSuffix,}) : React.ReactNode => {const [isPasswordVisible, setIsPasswordVisible] = useState(false);const colors = useColors();@@ -172,6 +175,10 @@ const FormInputCopyToClipboard: React.FC<FormInputCopyToClipboardProps> = ({fontSize: 12,marginBottom: 4,},+ labelRow: {+ alignItems: 'center',+ flexDirection: 'row',+ },value: {color: colors.text,fontSize: 16,@@ -202,9 +209,14 @@ const FormInputCopyToClipboard: React.FC<FormInputCopyToClipboardProps> = ({)}<View style={styles.inputContent}><View style={styles.valueContainer}>- <Text style={styles.label}>- {label}- </Text>+ {label && (+ <View style={styles.labelRow}>+ <Text style={styles.label}>+ {label}+ </Text>+ {labelSuffix}+ </View>+ )}<Text style={styles.value} numberOfLines={1} ellipsizeMode="tail">{displayValue}</Text>diff --git a/apps/mobile-app/components/items/ConfirmDeleteModal.tsx b/apps/mobile-app/components/items/ConfirmDeleteModal.tsxindex 2a666ee80..60fc42809 100644--- a/apps/mobile-app/components/items/ConfirmDeleteModal.tsx+++ b/apps/mobile-app/components/items/ConfirmDeleteModal.tsx@@ -9,7 +9,7 @@ import {ActivityIndicator,} from 'react-native';-import { useColors } from '@/hooks/useColorScheme';+import { useColors, useColorScheme } from '@/hooks/useColorScheme';interface IConfirmDeleteModalProps {isOpen: boolean;@@ -33,6 +33,7 @@ export const ConfirmDeleteModal: React.FC<IConfirmDeleteModalProps> = ({}) => {const { t } = useTranslation();const colors = useColors();+ const colorScheme = useColorScheme();const [isSubmitting, setIsSubmitting] = useState(false);/**@@ -61,7 +62,8 @@ export const ConfirmDeleteModal: React.FC<IConfirmDeleteModalProps> = ({const styles = StyleSheet.create({backdrop: {alignItems: 'center',- backgroundColor: 'rgba(0, 0, 0, 0.5)',+ // Lighter backdrop in dark mode for better contrast against black background+ backgroundColor: colorScheme === 'dark' ? 'rgba(255, 255, 255, 0.15)' : 'rgba(0, 0, 0, 0.5)',flex: 1,justifyContent: 'center',},diff --git a/apps/mobile-app/components/items/FieldHistoryModal.tsx b/apps/mobile-app/components/items/FieldHistoryModal.tsxnew file mode 100644index 000000000..3511bb357--- /dev/null+++ b/apps/mobile-app/components/items/FieldHistoryModal.tsx@@ -0,0 +1,335 @@+import { MaterialIcons } from '@expo/vector-icons';+import React, { useState, useEffect } from 'react';+import { useTranslation } from 'react-i18next';+import {+ Modal,+ StyleSheet,+ Text,+ View,+ ActivityIndicator,+ ScrollView,+ TouchableOpacity,+} from 'react-native';+import Toast from 'react-native-toast-message';++import type { FieldHistory, FieldType } from '@/utils/dist/core/models/vault';+import { FieldTypes } from '@/utils/dist/core/models/vault';++import { useColors, useColorScheme } from '@/hooks/useColorScheme';+import { useDb } from '@/context/DbContext';+import { copyToClipboardWithExpiration } from '@/utils/ClipboardUtility';+import { useAuth } from '@/context/AuthContext';++type FieldHistoryModalProps = {+ isOpen: boolean;+ onClose: () => void;+ itemId: string;+ fieldKey: string;+ fieldLabel: string;+ fieldType: FieldType;+ isHidden: boolean;+}++/**+ * Modal component for displaying field value history.+ * Shows historical values with dates.+ * For hidden/password fields, values are masked by default.+ * For other fields, values are visible by default.+ */+const FieldHistoryModal: React.FC<FieldHistoryModalProps> = ({+ isOpen,+ onClose,+ itemId,+ fieldKey,+ fieldLabel,+ fieldType,+ isHidden+}) => {+ const { t } = useTranslation();+ const colors = useColors();+ const colorScheme = useColorScheme();+ const dbContext = useDb();+ const { getClipboardClearTimeout } = useAuth();+ const [history, setHistory] = useState<FieldHistory[]>([]);+ const [loading, setLoading] = useState(true);+ const [visibleValues, setVisibleValues] = useState<Set<string>>(new Set());++ // For non-hidden fields, show values by default+ const shouldMaskByDefault = isHidden || fieldType === FieldTypes.Password || fieldType === FieldTypes.Hidden;++ useEffect(() => {+ if (!isOpen || !dbContext?.sqliteClient) {+ return;+ }++ const loadHistory = async (): Promise<void> => {+ if (!dbContext.sqliteClient) return;++ try {+ setLoading(true);+ const historyRecords = await dbContext.sqliteClient.items.getFieldHistory(itemId, fieldKey);+ setHistory(historyRecords);+ } catch (error) {+ console.error('Error loading field history:', error);+ } finally {+ setLoading(false);+ }+ };++ void loadHistory();+ }, [isOpen, dbContext?.sqliteClient, itemId, fieldKey]);++ /**+ * Format a date string to a human readable format.+ */+ const formatDate = (dateString: string): string => {+ try {+ const date = new Date(dateString);+ return date.toLocaleString(undefined, {+ year: 'numeric',+ month: 'short',+ day: 'numeric',+ hour: '2-digit',+ minute: '2-digit'+ });+ } catch {+ return dateString;+ }+ };++ /**+ * Parse a value snapshot into an array of values.+ */+ const parseValueSnapshot = (snapshot: string): string[] => {+ try {+ return JSON.parse(snapshot) as string[];+ } catch {+ return [snapshot];+ }+ };++ const styles = StyleSheet.create({+ backdrop: {+ alignItems: 'center',+ // Lighter backdrop in dark mode for better contrast against black background+ backgroundColor: colorScheme === 'dark' ? 'rgba(255, 255, 255, 0.15)' : 'rgba(0, 0, 0, 0.5)',+ flex: 1,+ justifyContent: 'center',+ },+ container: {+ backgroundColor: colors.background,+ borderRadius: 12,+ marginHorizontal: 16,+ maxHeight: '80%',+ width: '95%',+ },+ header: {+ borderBottomColor: colors.accentBorder,+ borderBottomWidth: 1,+ padding: 20,+ },+ title: {+ color: colors.text,+ fontSize: 18,+ fontWeight: '600',+ },+ body: {+ maxHeight: 400,+ padding: 20,+ },+ loadingContainer: {+ alignItems: 'center',+ justifyContent: 'center',+ paddingVertical: 40,+ },+ emptyContainer: {+ alignItems: 'center',+ paddingVertical: 40,+ },+ emptyText: {+ color: colors.textMuted,+ fontSize: 14,+ },+ historyItem: {+ backgroundColor: colors.accentBackground,+ borderColor: colors.accentBorder,+ borderRadius: 8,+ borderWidth: 1,+ marginBottom: 12,+ overflow: 'hidden',+ },+ historyHeader: {+ borderBottomColor: colors.accentBorder,+ borderBottomWidth: 1,+ paddingHorizontal: 12,+ paddingVertical: 8,+ },+ historyDate: {+ color: colors.textMuted,+ fontSize: 12,+ fontWeight: '500',+ },+ historyValue: {+ alignItems: 'center',+ flexDirection: 'row',+ justifyContent: 'space-between',+ padding: 12,+ },+ valueText: {+ color: colors.text,+ flex: 1,+ fontSize: 14,+ },+ actions: {+ alignItems: 'center',+ flexDirection: 'row',+ gap: 8,+ },+ iconButton: {+ padding: 4,+ },+ footer: {+ borderTopColor: colors.accentBorder,+ borderTopWidth: 1,+ padding: 16,+ },+ closeButton: {+ alignItems: 'center',+ backgroundColor: colors.accentBackground,+ borderColor: colors.accentBorder,+ borderRadius: 8,+ borderWidth: 1,+ paddingVertical: 12,+ },+ closeButtonText: {+ color: colors.text,+ fontSize: 16,+ fontWeight: '500',+ },+ });++ return (+ <Modal+ visible={isOpen}+ transparent+ animationType="fade"+ onRequestClose={onClose}+ >+ <View style={styles.backdrop}>+ <View style={styles.container}>+ <View style={styles.header}>+ <Text style={styles.title}>{fieldLabel} {t('items.history')}</Text>+ </View>++ <ScrollView style={styles.body}>+ {loading ? (+ <View style={styles.loadingContainer}>+ <ActivityIndicator size="large" color={colors.primary} />+ </View>+ ) : history.length === 0 ? (+ <View style={styles.emptyContainer}>+ <Text style={styles.emptyText}>+ {t('items.noHistoryAvailable')}+ </Text>+ </View>+ ) : (+ <View>+ {history.map((record) => {+ const values = parseValueSnapshot(record.ValueSnapshot);++ return (+ <View key={record.Id} style={styles.historyItem}>+ <View style={styles.historyHeader}>+ <Text style={styles.historyDate}>+ {formatDate(record.ChangedAt)}+ </Text>+ </View>++ {values.map((value, idx) => {+ const valueId = `${record.Id}-${idx}`;+ const isVisible = visibleValues.has(valueId);+ const displayValue = shouldMaskByDefault && !isVisible+ ? '•'.repeat(value.length)+ : value;++ const handleCopy = async (): Promise<void> => {+ try {+ const timeoutSeconds = await getClipboardClearTimeout();+ await copyToClipboardWithExpiration(value, timeoutSeconds);+ Toast.show({+ type: 'success',+ text1: t('common.copied'),+ position: 'bottom',+ visibilityTime: 2000,+ });+ } catch (error) {+ console.error('Failed to copy:', error);+ }+ };++ const toggleVisibility = (): void => {+ setVisibleValues(prev => {+ const newSet = new Set(prev);+ if (newSet.has(valueId)) {+ newSet.delete(valueId);+ } else {+ newSet.add(valueId);+ }+ return newSet;+ });+ };++ return (+ <View key={idx} style={styles.historyValue}>+ <Text style={styles.valueText} numberOfLines={1} ellipsizeMode="tail">+ {displayValue}+ </Text>+ <View style={styles.actions}>+ {shouldMaskByDefault && (+ <TouchableOpacity+ onPress={toggleVisibility}+ style={styles.iconButton}+ >+ <MaterialIcons+ name={isVisible ? 'visibility-off' : 'visibility'}+ size={20}+ color={colors.primary}+ />+ </TouchableOpacity>+ )}+ <TouchableOpacity+ onPress={handleCopy}+ style={styles.iconButton}+ >+ <MaterialIcons+ name="content-copy"+ size={18}+ color={colors.textMuted}+ />+ </TouchableOpacity>+ </View>+ </View>+ );+ })}+ </View>+ );+ })}+ </View>+ )}+ </ScrollView>++ <View style={styles.footer}>+ <TouchableOpacity+ style={styles.closeButton}+ onPress={onClose}+ >+ <Text style={styles.closeButtonText}>{t('common.close')}</Text>+ </TouchableOpacity>+ </View>+ </View>+ </View>+ </Modal>+ );+};++export default FieldHistoryModal;diff --git a/apps/mobile-app/components/items/details/FieldBlock.tsx b/apps/mobile-app/components/items/details/FieldBlock.tsxnew file mode 100644index 000000000..cf76f7c53--- /dev/null+++ b/apps/mobile-app/components/items/details/FieldBlock.tsx@@ -0,0 +1,296 @@+import MaterialIcons from '@expo/vector-icons/MaterialIcons';+import React, { useState, useEffect } from 'react';+import { useTranslation } from 'react-i18next';+import { View, Text, StyleSheet, TouchableOpacity, Linking } from 'react-native';++import type { ItemField } from '@/utils/dist/core/models/vault';+import { FieldTypes } from '@/utils/dist/core/models/vault';++import { useColors } from '@/hooks/useColorScheme';+import { useDb } from '@/context/DbContext';++import FormInputCopyToClipboard from '@/components/form/FormInputCopyToClipboard';+import FieldHistoryModal from '@/components/items/FieldHistoryModal';++type FieldBlockProps = {+ field: ItemField;+ itemId?: string;+ /** Whether to hide the label (useful when label is already shown as section header) */+ hideLabel?: boolean;+}++/**+ * Convert URLs in text to clickable links.+ */+const extractUrls = (text: string): { url: string; start: number; end: number }[] => {+ const urlPattern = /(https?:\/\/(?:www\.|(?!www))[a-zA-Z0-9][a-zA-Z0-9-]+[a-zA-Z0-9]\.[^\s]{2,}|www\.[a-zA-Z0-9][a-zA-Z0-9-]+[a-zA-Z0-9]\.[^\s]{2,}|https?:\/\/(?:www\.|(?!www))[a-zA-Z0-9]+\.[^\s]{2,}|www\.[a-zA-Z0-9]+\.[^\s]{2,})/g;+ const matches: { url: string; start: number; end: number }[] = [];+ let match;++ while ((match = urlPattern.exec(text)) !== null) {+ matches.push({+ url: match[0],+ start: match.index,+ end: match.index + match[0].length+ });+ }++ return matches;+};++/**+ * Dynamic field block component that renders based on field type.+ * Supports all field types with automatic history tracking when enabled.+ */+const FieldBlock: React.FC<FieldBlockProps> = ({ field, itemId, hideLabel = false }) => {+ const { t } = useTranslation();+ const colors = useColors();+ const dbContext = useDb();+ const [showHistoryModal, setShowHistoryModal] = useState(false);+ const [historyCount, setHistoryCount] = useState<number>(0);++ /* Get translated label for this field. System fields use fieldLabels.* translations, custom fields use their stored label */+ const label = field.IsCustomField+ ? (field.Label || field.FieldKey)+ : t(`fieldLabels.${field.FieldKey}`, { defaultValue: field.FieldKey });++ // Check if this field has history enabled+ const hasHistoryEnabled = field.EnableHistory === true;++ // Check if there's actual history available+ useEffect(() => {+ if (hasHistoryEnabled && itemId && dbContext?.sqliteClient) {+ const checkHistory = async (): Promise<void> => {+ if (!dbContext.sqliteClient) return;++ try {+ const history = await dbContext.sqliteClient.items.getFieldHistory(itemId, field.FieldKey);+ setHistoryCount(history.length);+ } catch (error) {+ console.error('[FieldBlock] Error checking history:', error);+ }+ };++ void checkHistory();+ }+ }, [hasHistoryEnabled, itemId, field.FieldKey, dbContext?.sqliteClient]);++ // Skip rendering if no value+ if (!field.Value || (typeof field.Value === 'string' && field.Value.trim() === '')) {+ return null;+ }++ const values = Array.isArray(field.Value) ? field.Value : [field.Value];++ const styles = StyleSheet.create({+ container: {+ // Used for TextArea wrapper+ },+ historyButton: {+ marginLeft: 4,+ padding: 4,+ },+ textAreaContainer: {+ backgroundColor: colors.accentBackground,+ borderRadius: 8,+ marginBottom: 8,+ padding: 12,+ },+ textAreaLabel: {+ color: colors.textMuted,+ fontSize: 12,+ marginBottom: 8,+ },+ textAreaLabelRow: {+ alignItems: 'center',+ flexDirection: 'row',+ marginBottom: 8,+ },+ textAreaText: {+ color: colors.text,+ fontSize: 14,+ lineHeight: 20,+ },+ linkText: {+ color: colors.primary,+ textDecorationLine: 'underline',+ },+ multiValueContainer: {+ gap: 8,+ },+ });++ /**+ * Render TextArea field type with URL detection.+ */+ const renderTextArea = (value: string): React.ReactNode => {+ const urls = extractUrls(value);++ if (urls.length === 0) {+ // No URLs, render plain text+ return (+ <View>+ {!hideLabel && (+ <View style={styles.textAreaLabelRow}>+ <Text style={styles.textAreaLabel}>{label}</Text>+ {HistoryButton}+ </View>+ )}+ <View style={styles.textAreaContainer}>+ <Text style={styles.textAreaText}>{value}</Text>+ </View>+ </View>+ );+ }++ // Build text segments with clickable URLs+ const segments: React.ReactNode[] = [];+ let lastEnd = 0;++ urls.forEach((urlMatch, idx) => {+ // Add text before URL+ if (urlMatch.start > lastEnd) {+ segments.push(+ <Text key={`text-${idx}`} style={styles.textAreaText}>+ {value.substring(lastEnd, urlMatch.start)}+ </Text>+ );+ }++ // Add clickable URL+ const href = urlMatch.url.startsWith('http') ? urlMatch.url : `http://${urlMatch.url}`;+ segments.push(+ <Text+ key={`url-${idx}`}+ style={[styles.textAreaText, styles.linkText]}+ onPress={() => Linking.openURL(href)}+ >+ {urlMatch.url}+ </Text>+ );++ lastEnd = urlMatch.end;+ });++ // Add remaining text after last URL+ if (lastEnd < value.length) {+ segments.push(+ <Text key="text-end" style={styles.textAreaText}>+ {value.substring(lastEnd)}+ </Text>+ );+ }++ return (+ <View>+ {!hideLabel && (+ <View style={styles.textAreaLabelRow}>+ <Text style={styles.textAreaLabel}>{label}</Text>+ {HistoryButton}+ </View>+ )}+ <View style={styles.textAreaContainer}>+ <Text>{segments}</Text>+ </View>+ </View>+ );+ };++ /**+ * Render history button if history is available.+ */+ const HistoryButton = historyCount > 0 && itemId ? (+ <TouchableOpacity+ style={styles.historyButton}+ onPress={() => setShowHistoryModal(true)}+ accessibilityLabel={t('items.viewHistory')}+ >+ <MaterialIcons+ name="history"+ size={18}+ color={colors.textMuted}+ />+ </TouchableOpacity>+ ) : null;++ /**+ * Render history modal.+ */+ const HistoryModal = showHistoryModal && itemId ? (+ <FieldHistoryModal+ isOpen={showHistoryModal}+ onClose={() => setShowHistoryModal(false)}+ itemId={itemId}+ fieldKey={field.FieldKey}+ fieldLabel={label}+ fieldType={field.FieldType}+ isHidden={field.IsHidden}+ />+ ) : null;++ // Handle multi-value fields (like multiple URLs)+ if (values.length > 1) {+ return (+ <View style={styles.multiValueContainer}>+ {values.map((value, idx) => (+ <FormInputCopyToClipboard+ key={`${field.FieldKey}-${idx}`}+ label={hideLabel ? '' : (idx === 0 ? label : `${label} ${idx + 1}`)}+ value={value}+ type={field.FieldType === FieldTypes.Password || field.IsHidden ? 'password' : 'text'}+ labelSuffix={idx === 0 ? HistoryButton : undefined}+ />+ ))}+ {HistoryModal}+ </View>+ );+ }++ const value = values[0];++ // Render based on field type+ switch (field.FieldType) {+ case FieldTypes.Password:+ case FieldTypes.Hidden:+ return (+ <>+ <FormInputCopyToClipboard+ label={hideLabel ? '' : label}+ value={value}+ type="password"+ labelSuffix={HistoryButton}+ />+ {HistoryModal}+ </>+ );++ case FieldTypes.TextArea:+ return (+ <View style={styles.container}>+ {renderTextArea(value)}+ {HistoryModal}+ </View>+ );++ case FieldTypes.Email:+ case FieldTypes.URL:+ case FieldTypes.Phone:+ case FieldTypes.Date:+ case FieldTypes.Number:+ case FieldTypes.Text:+ default:+ return (+ <>+ <FormInputCopyToClipboard+ label={hideLabel ? '' : label}+ value={value}+ type="text"+ labelSuffix={HistoryButton}+ />+ {HistoryModal}+ </>+ );+ }+};++export default FieldBlock;diff --git a/apps/mobile-app/components/items/details/LoginFields.tsx b/apps/mobile-app/components/items/details/LoginFields.tsxindex bf7aeb618..c7a01d67a 100644--- a/apps/mobile-app/components/items/details/LoginFields.tsx+++ b/apps/mobile-app/components/items/details/LoginFields.tsx@@ -2,12 +2,12 @@ import MaterialIcons from '@expo/vector-icons/MaterialIcons';import { useTranslation } from 'react-i18next';import { StyleSheet, View } from 'react-native';-import type { Item } from '@/utils/dist/core/models/vault';-import { getFieldValue, FieldKey } from '@/utils/dist/core/models/vault';+import type { Item, ItemField } from '@/utils/dist/core/models/vault';+import { FieldKey } from '@/utils/dist/core/models/vault';import { useColors } from '@/hooks/useColorScheme';-import FormInputCopyToClipboard from '@/components/form/FormInputCopyToClipboard';+import FieldBlock from '@/components/items/details/FieldBlock';import { ThemedText } from '@/components/themed/ThemedText';import { ThemedView } from '@/components/themed/ThemedView';@@ -17,16 +17,22 @@ type LoginFieldsProps = {/*** Login fields component.+ * Now uses FieldBlock for automatic field type handling and history support.*/export const LoginFields: React.FC<LoginFieldsProps> = ({ item }) : React.ReactNode => {const { t } = useTranslation();const colors = useColors();- const email = getFieldValue(item, FieldKey.LoginEmail)?.trim();- const username = getFieldValue(item, FieldKey.LoginUsername)?.trim();- const password = getFieldValue(item, FieldKey.LoginPassword)?.trim();++ // Get login-related fields from the item+ const loginFields = item.Fields.filter(+ (field: ItemField) =>+ field.FieldKey === FieldKey.LoginEmail ||+ field.FieldKey === FieldKey.LoginUsername ||+ field.FieldKey === FieldKey.LoginPassword+ );// eslint-disable-next-line @typescript-eslint/prefer-nullish-coalescing- const hasLoginCredentials = email || username || password || item.HasPasskey;+ const hasLoginCredentials = loginFields.length > 0 || item.HasPasskey;if (!hasLoginCredentials) {return null;@@ -74,21 +80,32 @@ export const LoginFields: React.FC<LoginFieldsProps> = ({ item }) : React.ReactN},});+ // Sort login fields: email first, then username, then password+ const sortedLoginFields = [...loginFields].sort((a, b) => {+ const order: Record<string, number> = {+ [FieldKey.LoginEmail]: 0,+ [FieldKey.LoginUsername]: 1,+ [FieldKey.LoginPassword]: 2+ };+ const aOrder = order[a.FieldKey] ?? 99;+ const bOrder = order[b.FieldKey] ?? 99;+ return aOrder - bOrder;+ });+return (<ThemedView style={styles.section}><ThemedText type="subtitle">{t('credentials.loginCredentials')}</ThemedText>- {email && (- <FormInputCopyToClipboard- label={t('credentials.email')}- value={email}- />- )}- {username && (- <FormInputCopyToClipboard- label={t('credentials.username')}- value={username}++ {/* Render login fields using FieldBlock */}+ {sortedLoginFields.map((field: ItemField) => (+ <FieldBlock+ key={field.FieldKey}+ field={field}+ itemId={item.Id}/>- )}+ ))}++ {/* Passkey display */}{item.HasPasskey && (<View style={passkeyStyles.container}><View style={passkeyStyles.contentRow}>@@ -109,13 +126,6 @@ export const LoginFields: React.FC<LoginFieldsProps> = ({ item }) : React.ReactN</View></View>)}- {password && (- <FormInputCopyToClipboard- label={t('credentials.password')}- value={password}- type="password"- />- )}</ThemedView>);};diff --git a/apps/mobile-app/components/items/details/TotpEditor.tsx b/apps/mobile-app/components/items/details/TotpEditor.tsxindex 4dce73900..589096fef 100644--- a/apps/mobile-app/components/items/details/TotpEditor.tsx+++ b/apps/mobile-app/components/items/details/TotpEditor.tsx@@ -6,7 +6,7 @@ import { View, StyleSheet, Alert, TextInput, Modal, TouchableOpacity, ScrollViewimport type { TotpCode } from '@/utils/dist/core/models/vault';-import { useColors } from '@/hooks/useColorScheme';+import { useColors, useColorScheme } from '@/hooks/useColorScheme';import { ThemedText } from '@/components/themed/ThemedText';import { ThemedView } from '@/components/themed/ThemedView';@@ -33,6 +33,7 @@ export const TotpEditor: React.FC<TotpEditorProps> = ({}) => {const { t } = useTranslation();const colors = useColors();+ const colorScheme = useColorScheme();const [isAddFormVisible, setIsAddFormVisible] = useState(false);const [formData, setFormData] = useState<TotpFormData>({ name: '', secretKey: '' });const [formError, setFormError] = useState<string | null>(null);@@ -275,7 +276,7 @@ export const TotpEditor: React.FC<TotpEditorProps> = ({flex: 1,},modalContainer: {- backgroundColor: 'rgba(0, 0, 0, 0.5)',+ backgroundColor: colorScheme === 'dark' ? 'rgba(255, 255, 255, 0.15)' : 'rgba(0, 0, 0, 0.5)',flex: 1,justifyContent: 'flex-end',},diff --git a/apps/mobile-app/i18n/locales/en.json b/apps/mobile-app/i18n/locales/en.jsonindex cd341d1ab..65edf0b42 100644--- a/apps/mobile-app/i18n/locales/en.json+++ b/apps/mobile-app/i18n/locales/en.json@@ -599,6 +599,9 @@"copyEmail": "Copy Email","copyPassword": "Copy Password"},+ "viewHistory": "View history",+ "history": "History",+ "noHistoryAvailable": "No history available","deleteConfirm": "Are you sure you want to delete this item? This action cannot be undone.","folders": {"folder": "Folder",diff --git a/apps/mobile-app/utils/db/queries/ItemQueries.ts b/apps/mobile-app/utils/db/queries/ItemQueries.tsindex abd7b8d0b..f3a81363f 100644--- a/apps/mobile-app/utils/db/queries/ItemQueries.ts+++ b/apps/mobile-app/utils/db/queries/ItemQueries.ts@@ -294,3 +294,62 @@ export class FieldDefinitionQueries {UpdatedAt = ?WHERE Id = ?`;}++/**+ * SQL query constants for FieldHistory operations.+ */+export class FieldHistoryQueries {+ /**+ * Insert a history record.+ */+ public static readonly INSERT = `+ INSERT INTO FieldHistories (Id, ItemId, FieldDefinitionId, FieldKey, ValueSnapshot, ChangedAt, CreatedAt, UpdatedAt, IsDeleted)+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`;++ /**+ * Get history records for a field.+ */+ public static readonly GET_FOR_FIELD = `+ SELECT+ Id,+ ItemId,+ FieldKey,+ ValueSnapshot,+ ChangedAt,+ CreatedAt,+ UpdatedAt+ FROM FieldHistories+ WHERE ItemId = ? AND FieldKey = ? AND IsDeleted = 0+ ORDER BY ChangedAt DESC+ LIMIT ?`;++ /**+ * Get field values for history comparison (before update).+ */+ public static readonly GET_FOR_HISTORY = `+ SELECT FieldKey, Value+ FROM FieldValues+ WHERE ItemId = ? AND IsDeleted = 0`;++ /**+ * Get all history records for pruning.+ */+ public static readonly GET_FOR_PRUNING = `+ SELECT Id, ChangedAt+ FROM FieldHistories+ WHERE ItemId = ? AND FieldKey = ? AND IsDeleted = 0+ ORDER BY ChangedAt DESC`;++ /**+ * Soft delete old history records.+ * @param count - Number of records to delete+ * @returns Query with placeholders+ */+ public static softDeleteOld(count: number): string {+ const placeholders = Array(count).fill('?').join(',');+ return `+ UPDATE FieldHistories+ SET IsDeleted = 1, UpdatedAt = ?+ WHERE Id IN (${placeholders})`;+ }+}diff --git a/apps/mobile-app/utils/db/repositories/ItemRepository.ts b/apps/mobile-app/utils/db/repositories/ItemRepository.tsindex 9817bc3e5..70eb8509d 100644--- a/apps/mobile-app/utils/db/repositories/ItemRepository.ts+++ b/apps/mobile-app/utils/db/repositories/ItemRepository.ts@@ -1,8 +1,8 @@-import type { Item, ItemField, TotpCode, Attachment } from '@/utils/dist/core/models/vault';-import { FieldKey } from '@/utils/dist/core/models/vault';+import type { Item, ItemField, TotpCode, Attachment, FieldHistory } from '@/utils/dist/core/models/vault';+import { FieldKey, MAX_FIELD_HISTORY_RECORDS } from '@/utils/dist/core/models/vault';import { BaseRepository } from '../BaseRepository';-import { ItemQueries, FieldValueQueries } from '../queries/ItemQueries';+import { ItemQueries, FieldValueQueries, FieldHistoryQueries } from '../queries/ItemQueries';import { FieldMapper, type FieldRow } from '../mappers/FieldMapper';import { ItemMapper, type ItemRow, type TagRow, type ItemWithDeletedAt } from '../mappers/ItemMapper';@@ -183,6 +183,34 @@ export class ItemRepository extends BaseRepository {return results.length > 0 ? results[0].count : 0;}+ /**+ * Get field history for a specific field.+ * @param itemId - The ID of the item+ * @param fieldKey - The field key to get history for+ * @returns Array of field history records+ */+ public async getFieldHistory(itemId: string, fieldKey: string): Promise<FieldHistory[]> {+ const results = await this.client.executeQuery<{+ Id: string;+ ItemId: string;+ FieldKey: string;+ ValueSnapshot: string;+ ChangedAt: string;+ CreatedAt: string;+ UpdatedAt: string;+ }>(FieldHistoryQueries.GET_FOR_FIELD, [itemId, fieldKey, MAX_FIELD_HISTORY_RECORDS]);++ return results.map(row => ({+ Id: row.Id,+ ItemId: row.ItemId,+ FieldKey: row.FieldKey,+ ValueSnapshot: row.ValueSnapshot,+ ChangedAt: row.ChangedAt,+ CreatedAt: row.CreatedAt,+ UpdatedAt: row.UpdatedAt+ }));+ }+/*** Move an item to trash (set DeletedAt timestamp).* @param itemId - The ID of the item to trash@@ -334,10 +362,13 @@ export class ItemRepository extends BaseRepository {}}- // 2. Update FieldValues using preserve-and-track strategy+ // 2. Track history for fields that have EnableHistory=true before updating+ await this.trackFieldHistory(item.Id, item.Fields, now);++ // 3. Update FieldValues using preserve-and-track strategyawait this.updateFieldValues(item.Id, item.Fields, now);- // 3. Handle TOTP codes+ // 4. Handle TOTP codesawait this.syncRelatedEntities('TotpCodes','ItemId',@@ -348,7 +379,7 @@ export class ItemRepository extends BaseRepository {`INSERT INTO TotpCodes (Id, Name, SecretKey, ItemId, CreatedAt, UpdatedAt, IsDeleted) VALUES (?, ?, ?, ?, ?, ?, ?)`);- // 4. Handle Attachments+ // 5. Handle Attachmentsawait this.syncRelatedEntities('Attachments','ItemId',@@ -495,4 +526,96 @@ export class ItemRepository extends BaseRepository {}}}++ /**+ * Track field history for fields with EnableHistory=true.+ * Compares old values with new values and creates history records.+ */+ private async trackFieldHistory(+ itemId: string,+ newFields: ItemField[],+ currentDateTime: string+ ): Promise<void> {+ // Check if FieldHistories table exists+ if (!(await this.tableExists('FieldHistories'))) {+ return;+ }++ const existingFields = await this.client.executeQuery<{ FieldKey: string; Value: string }>(+ FieldHistoryQueries.GET_FOR_HISTORY,+ [itemId]+ );++ // Create a map of existing values by FieldKey+ const existingValuesMap: { [key: string]: string[] } = {};+ for (const field of existingFields) {+ if (!existingValuesMap[field.FieldKey]) {+ existingValuesMap[field.FieldKey] = [];+ }+ existingValuesMap[field.FieldKey].push(field.Value);+ }++ for (const newField of newFields) {+ /**+ * Check if history tracking is enabled for this field.+ * EnableHistory comes from SystemFieldRegistry for system fields,+ * or from the FieldDefinitions table for custom fields.+ */+ if (!newField.EnableHistory) {+ continue;+ }++ const oldValues = existingValuesMap[newField.FieldKey] || [];+ const newValues = Array.isArray(newField.Value) ? newField.Value : [newField.Value];++ const valuesChanged = oldValues.length !== newValues.length ||+ !oldValues.every((val, idx) => val === newValues[idx]);++ if (valuesChanged && oldValues.length > 0) {+ const historyId = this.generateId();+ const valueSnapshot = JSON.stringify(oldValues);++ await this.client.executeUpdate(FieldHistoryQueries.INSERT, [+ historyId,+ itemId,+ null,+ newField.FieldKey,+ valueSnapshot,+ currentDateTime,+ currentDateTime,+ currentDateTime,+ 0+ ]);++ await this.pruneFieldHistory(itemId, newField.FieldKey, currentDateTime);+ }+ }+ }++ /**+ * Prune old field history records.+ * Keeps only the most recent MAX_FIELD_HISTORY_RECORDS records.+ */+ private async pruneFieldHistory(+ itemId: string,+ fieldKey: string,+ currentDateTime: string+ ): Promise<void> {+ const matchingHistory = await this.client.executeQuery<{ Id: string; ChangedAt: string }>(+ FieldHistoryQueries.GET_FOR_PRUNING,+ [itemId, fieldKey]+ );++ if (matchingHistory.length > MAX_FIELD_HISTORY_RECORDS) {+ const recordsToDelete = matchingHistory.slice(MAX_FIELD_HISTORY_RECORDS);+ const idsToDelete = recordsToDelete.map(r => r.Id);++ if (idsToDelete.length > 0) {+ await this.client.executeUpdate(+ FieldHistoryQueries.softDeleteOld(idsToDelete.length),+ [currentDateTime, ...idsToDelete]+ );+ }+ }+ }}