Privacy-first password manager with built-in email aliasing. Fully encrypted and self-hostable.
Fix custom field UI and save logic in mobile app (#1473)
Leendert de Borst11d102cb964b
diff --git a/apps/mobile-app/app/(tabs)/items/[id].tsx b/apps/mobile-app/app/(tabs)/items/[id].tsxindex 094a25220..8a513f639 100644--- a/apps/mobile-app/app/(tabs)/items/[id].tsx+++ b/apps/mobile-app/app/(tabs)/items/[id].tsx@@ -13,6 +13,7 @@ import { useColors } from '@/hooks/useColorScheme';import { AliasDetails } from '@/components/items/details/AliasDetails';import { AttachmentSection } from '@/components/items/details/AttachmentSection';+import { CustomFieldsSection } from '@/components/items/details/CustomFieldsSection';import { EmailPreview } from '@/components/items/details/EmailPreview';import { LoginFields } from '@/components/items/details/LoginFields';import { NotesSection } from '@/components/items/details/NotesSection';@@ -186,6 +187,7 @@ export default function ItemDetailsScreen() : React.ReactNode {<TotpSection item={item} /><LoginFields item={item} /><AliasDetails item={item} />+ <CustomFieldsSection item={item} /><NotesSection item={item} /><AttachmentSection item={item} /></ThemedScrollView>diff --git a/apps/mobile-app/app/(tabs)/items/add-edit.tsx b/apps/mobile-app/app/(tabs)/items/add-edit.tsxindex fa68f7eac..60967a8a8 100644--- a/apps/mobile-app/app/(tabs)/items/add-edit.tsx+++ b/apps/mobile-app/app/(tabs)/items/add-edit.tsx@@ -24,6 +24,7 @@ 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 { EditableFieldLabel } from '@/components/form/EditableFieldLabel';import { EmailDomainField } from '@/components/form/EmailDomainField';import { FormField } from '@/components/form/FormField';import { FormSection } from '@/components/form/FormSection';@@ -688,6 +689,16 @@ export default function AddEditItemScreen(): React.ReactNode {setHasUnsavedChanges(true);}, []);+ /**+ * Update custom field label handler.+ */+ const handleUpdateCustomFieldLabel = useCallback((tempId: string, newLabel: string) => {+ setCustomFields(prev => prev.map(f =>+ f.tempId === tempId ? { ...f, label: newLabel } : f+ ));+ setHasUnsavedChanges(true);+ }, []);+/*** Optional sections for AddFieldMenu.*/@@ -1527,13 +1538,17 @@ export default function AddEditItemScreen(): React.ReactNode {<FormSection title={t('itemTypes.customFields')}>{customFields.map(field => (<View key={field.tempId}>+ <EditableFieldLabel+ label={field.label}+ onLabelChange={(newLabel) => handleUpdateCustomFieldLabel(field.tempId, newLabel)}+ onDelete={() => handleDeleteCustomField(field.tempId)}+ />{renderFieldInput(field.tempId,- field.label,+ '', // Label is shown by EditableFieldLabelfield.fieldType,field.isHidden,- false,- () => handleDeleteCustomField(field.tempId)+ false)}</View>))}diff --git a/apps/mobile-app/components/form/EditableFieldLabel.tsx b/apps/mobile-app/components/form/EditableFieldLabel.tsxnew file mode 100644index 000000000..33a5a68f3--- /dev/null+++ b/apps/mobile-app/components/form/EditableFieldLabel.tsx@@ -0,0 +1,157 @@+import { MaterialIcons } from '@expo/vector-icons';+import React, { useState, useRef, useEffect } from 'react';+import { View, TextInput, StyleSheet, TouchableHighlight, Keyboard } from 'react-native';++import { useColors } from '@/hooks/useColorScheme';++import { ThemedText } from '@/components/themed/ThemedText';++type EditableFieldLabelProps = {+ label: string;+ onLabelChange: (newLabel: string) => void;+ onDelete?: () => void;+}++/**+ * Editable field label component with edit button.+ * Shows label text with a small edit icon. When clicked, shows an input field.+ */+export const EditableFieldLabel: React.FC<EditableFieldLabelProps> = ({+ label,+ onLabelChange,+ onDelete+}) => {+ const colors = useColors();+ const [isEditing, setIsEditing] = useState(false);+ const [editValue, setEditValue] = useState(label);+ const inputRef = useRef<TextInput>(null);++ // Focus input when entering edit mode+ useEffect(() => {+ if (isEditing && inputRef.current) {+ inputRef.current.focus();+ }+ }, [isEditing]);++ /**+ * Handle the save action.+ */+ const handleSave = (): void => {+ if (editValue.trim()) {+ onLabelChange(editValue.trim());+ setIsEditing(false);+ Keyboard.dismiss();+ }+ };++ /**+ * Handle the cancel action.+ */+ const handleCancel = (): void => {+ setEditValue(label);+ setIsEditing(false);+ Keyboard.dismiss();+ };++ const styles = StyleSheet.create({+ actionButton: {+ borderRadius: 4,+ marginLeft: 4,+ padding: 2,+ },+ cancelButton: {+ marginLeft: 4,+ },+ container: {+ alignItems: 'center',+ flexDirection: 'row',+ },+ deleteButton: {+ marginLeft: 4,+ },+ editButton: {+ marginLeft: 4,+ padding: 2,+ },+ editContainer: {+ alignItems: 'center',+ flex: 1,+ flexDirection: 'row',+ },+ editInput: {+ backgroundColor: colors.background,+ borderColor: colors.primary,+ borderRadius: 4,+ borderWidth: 1,+ color: colors.text,+ flex: 1,+ fontSize: 12,+ paddingHorizontal: 8,+ paddingVertical: 4,+ },+ label: {+ color: colors.textMuted,+ fontSize: 12,+ },+ saveButton: {+ marginLeft: 4,+ },+ });++ if (isEditing) {+ return (+ <View style={styles.container}>+ <View style={styles.editContainer}>+ <TextInput+ ref={inputRef}+ style={styles.editInput}+ value={editValue}+ onChangeText={setEditValue}+ onSubmitEditing={handleSave}+ placeholder="Field label"+ placeholderTextColor={colors.textMuted}+ autoCapitalize="none"+ autoCorrect={false}+ returnKeyType="done"+ />+ <TouchableHighlight+ style={[styles.actionButton, styles.saveButton]}+ onPress={handleSave}+ underlayColor={colors.accentBackground}+ >+ <MaterialIcons name="check" size={18} color={colors.success} />+ </TouchableHighlight>+ <TouchableHighlight+ style={[styles.actionButton, styles.cancelButton]}+ onPress={handleCancel}+ underlayColor={colors.accentBackground}+ >+ <MaterialIcons name="close" size={18} color={colors.textMuted} />+ </TouchableHighlight>+ </View>+ </View>+ );+ }++ return (+ <View style={styles.container}>+ <ThemedText style={styles.label}>{label}</ThemedText>+ <TouchableHighlight+ style={styles.editButton}+ onPress={() => setIsEditing(true)}+ underlayColor={colors.accentBackground}+ >+ <MaterialIcons name="edit" size={14} color={colors.textMuted} />+ </TouchableHighlight>+ {onDelete && (+ <TouchableHighlight+ style={[styles.actionButton, styles.deleteButton]}+ onPress={onDelete}+ underlayColor={colors.accentBackground}+ >+ <MaterialIcons name="delete" size={14} color={colors.destructive} />+ </TouchableHighlight>+ )}+ </View>+ );+};diff --git a/apps/mobile-app/components/form/FormField.tsx b/apps/mobile-app/components/form/FormField.tsxindex b217257e8..b60c22be5 100644--- a/apps/mobile-app/components/form/FormField.tsx+++ b/apps/mobile-app/components/form/FormField.tsx@@ -117,22 +117,27 @@ const FormFieldComponent = forwardRef<FormFieldRef, FormFieldProps>(({const showClearButton = Platform.OS === 'android' && value && value.length > 0 && isFocused;+ // Only show label container if there's a label or remove button+ const showLabelContainer = label || onRemove;+return (<View style={styles.inputGroup}>- <View style={styles.labelContainer}>- <ThemedText style={styles.inputLabel}>- {label} {required && <ThemedText style={styles.requiredIndicator}>*</ThemedText>}- </ThemedText>- {onRemove && (- <TouchableHighlight- style={styles.removeButton}- onPress={onRemove}- underlayColor={colors.accentBackground}- >- <MaterialIcons name="close" size={18} color={colors.textMuted} />- </TouchableHighlight>- )}- </View>+ {showLabelContainer && (+ <View style={styles.labelContainer}>+ <ThemedText style={styles.inputLabel}>+ {label} {required && <ThemedText style={styles.requiredIndicator}>*</ThemedText>}+ </ThemedText>+ {onRemove && (+ <TouchableHighlight+ style={styles.removeButton}+ onPress={onRemove}+ underlayColor={colors.accentBackground}+ >+ <MaterialIcons name="close" size={18} color={colors.textMuted} />+ </TouchableHighlight>+ )}+ </View>+ )}<View style={[styles.inputContainer, error ? styles.inputError : null]}><TextInputref={inputRef}diff --git a/apps/mobile-app/components/form/HiddenField.tsx b/apps/mobile-app/components/form/HiddenField.tsxindex 7a475474d..1532c8488 100644--- a/apps/mobile-app/components/form/HiddenField.tsx+++ b/apps/mobile-app/components/form/HiddenField.tsx@@ -81,20 +81,25 @@ export const HiddenField: React.FC<HiddenFieldProps> = ({},});+ // Only show label container if there's a label or remove button+ const showLabelContainer = label || onRemove;+return (<View style={styles.container}>- <View style={styles.labelContainer}>- <ThemedText style={styles.label}>{label}</ThemedText>- {onRemove && (- <TouchableOpacity- style={styles.removeButton}- onPress={onRemove}- activeOpacity={0.7}- >- <MaterialIcons name="close" size={18} color={colors.textMuted} />- </TouchableOpacity>- )}- </View>+ {showLabelContainer && (+ <View style={styles.labelContainer}>+ <ThemedText style={styles.label}>{label}</ThemedText>+ {onRemove && (+ <TouchableOpacity+ style={styles.removeButton}+ onPress={onRemove}+ activeOpacity={0.7}+ >+ <MaterialIcons name="close" size={18} color={colors.textMuted} />+ </TouchableOpacity>+ )}+ </View>+ )}<View style={styles.inputContainer}><TextInputstyle={styles.input}diff --git a/apps/mobile-app/components/items/details/CustomFieldsSection.tsx b/apps/mobile-app/components/items/details/CustomFieldsSection.tsxnew file mode 100644index 000000000..710be98a0--- /dev/null+++ b/apps/mobile-app/components/items/details/CustomFieldsSection.tsx@@ -0,0 +1,48 @@+import { useTranslation } from 'react-i18next';++import type { Item, ItemField } from '@/utils/dist/core/models/vault';++import FieldBlock from '@/components/items/details/FieldBlock';+import { ThemedText } from '@/components/themed/ThemedText';+import { ThemedView } from '@/components/themed/ThemedView';++type CustomFieldsSectionProps = {+ item: Item;+};++/**+ * Custom fields section component.+ * Displays all custom fields for an item.+ */+export const CustomFieldsSection: React.FC<CustomFieldsSectionProps> = ({ item }): React.ReactNode => {+ const { t } = useTranslation();++ // Get custom fields from the item+ const customFields = item.Fields.filter(+ (field: ItemField) => field.IsCustomField+ );++ if (customFields.length === 0) {+ return null;+ }++ return (+ <ThemedView style={styles.section}>+ <ThemedText type="subtitle">{t('itemTypes.customFields')}</ThemedText>+ {customFields.map((field: ItemField) => (+ <FieldBlock+ key={field.FieldKey}+ field={field}+ itemId={item.Id}+ />+ ))}+ </ThemedView>+ );+};++const styles = {+ section: {+ paddingTop: 16,+ gap: 8,+ },+};diff --git a/apps/mobile-app/utils/db/repositories/ItemRepository.ts b/apps/mobile-app/utils/db/repositories/ItemRepository.tsindex 3a0f3aefd..8d84a8251 100644--- a/apps/mobile-app/utils/db/repositories/ItemRepository.ts+++ b/apps/mobile-app/utils/db/repositories/ItemRepository.ts@@ -2,7 +2,7 @@ import type { Item, ItemField, TotpCode, Attachment, FieldHistory } from '@/utilimport { FieldKey, MAX_FIELD_HISTORY_RECORDS } from '@/utils/dist/core/models/vault';import { BaseRepository } from '../BaseRepository';-import { ItemQueries, FieldValueQueries, FieldHistoryQueries } from '../queries/ItemQueries';+import { ItemQueries, FieldValueQueries, FieldDefinitionQueries, FieldHistoryQueries } from '../queries/ItemQueries';import { FieldMapper, type FieldRow } from '../mappers/FieldMapper';import { ItemMapper, type ItemRow, type TagRow, type ItemWithDeletedAt } from '../mappers/ItemMapper';import type { LogoRepository } from './LogoRepository';@@ -319,7 +319,7 @@ export class ItemRepository extends BaseRepository {]);// 2. Insert FieldValues- await this.insertFieldValues(itemId, item.Fields, now);+ await this.insertFieldValues(itemId, item.Fields, item.ItemType, now);// 3. Insert TOTP codesfor (const totp of totpCodes) {@@ -398,7 +398,7 @@ export class ItemRepository extends BaseRepository {await this.trackFieldHistory(item.Id, item.Fields, now);// 3. Update FieldValues using preserve-and-track strategy- await this.updateFieldValues(item.Id, item.Fields, now);+ await this.updateFieldValues(item.Id, item.Fields, item.ItemType, now);// 4. Handle TOTP codesawait this.syncRelatedEntities(@@ -430,20 +430,32 @@ export class ItemRepository extends BaseRepository {* Insert field values for an item.* Also creates history records for fields with EnableHistory=true.*/- private async insertFieldValues(itemId: string, fields: ItemField[], now: string): Promise<void> {+ private async insertFieldValues(itemId: string, fields: ItemField[], itemType: string, now: string): Promise<void> {for (let i = 0; i < fields.length; i++) {const field = fields[i];const values = Array.isArray(field.Value) ? field.Value : [field.Value];const filteredValues = values.filter(v => v !== undefined && v !== null && v !== '');+ // Skip empty fields+ if (filteredValues.length === 0) {+ continue;+ }++ let fieldDefinitionId: string | null = null;++ // For custom fields, create or get FieldDefinition first+ if (field.IsCustomField) {+ fieldDefinitionId = await this.ensureFieldDefinition(field, itemType, now);+ }+for (let j = 0; j < filteredValues.length; j++) {const value = filteredValues[j];await this.client.executeUpdate(FieldValueQueries.INSERT, [this.generateId(),itemId,- field.IsCustomField ? field.FieldKey : null, // FieldDefinitionId for custom- field.IsCustomField ? null : field.FieldKey, // FieldKey for system+ fieldDefinitionId, // FieldDefinitionId for custom, null for system+ field.IsCustomField ? null : field.FieldKey, // FieldKey for system, null for customvalue,(i * 100) + j, // Weight for orderingnow,@@ -475,11 +487,89 @@ export class ItemRepository extends BaseRepository {}}+ /**+ * Ensure a field definition exists for a custom field.+ * Creates the definition if it doesn't exist.+ * @returns The field definition ID (which is the field's FieldKey/tempId)+ */+ private async ensureFieldDefinition(+ field: ItemField,+ itemType: string,+ currentDateTime: string+ ): Promise<string> {+ const existingDef = await this.client.executeQuery<{ Id: string }>(+ FieldDefinitionQueries.EXISTS,+ [field.FieldKey]+ );++ if (existingDef.length === 0) {+ await this.client.executeUpdate(FieldDefinitionQueries.INSERT, [+ field.FieldKey,+ field.FieldType,+ field.Label,+ 0, // IsMultiValue+ field.IsHidden ? 1 : 0,+ 0, // EnableHistory+ field.DisplayOrder ?? 0,+ itemType,+ currentDateTime,+ currentDateTime,+ 0+ ]);+ }++ return field.FieldKey;+ }++ /**+ * Ensure a field definition exists and is up-to-date.+ * Creates the definition if it doesn't exist, or updates it if it does.+ * @returns The field definition ID (which is the field's FieldKey/tempId)+ */+ private async ensureOrUpdateFieldDefinition(+ field: ItemField,+ itemType: string,+ currentDateTime: string+ ): Promise<string> {+ const existingDef = await this.client.executeQuery<{ Id: string }>(+ FieldDefinitionQueries.EXISTS_ACTIVE,+ [field.FieldKey]+ );++ if (existingDef.length === 0) {+ await this.client.executeUpdate(FieldDefinitionQueries.INSERT, [+ field.FieldKey,+ field.FieldType,+ field.Label,+ 0, // IsMultiValue+ field.IsHidden ? 1 : 0,+ 0, // EnableHistory+ field.DisplayOrder ?? 0,+ itemType,+ currentDateTime,+ currentDateTime,+ 0+ ]);+ } else {+ // Update existing field definition (label, type, etc. may have changed)+ await this.client.executeUpdate(FieldDefinitionQueries.UPDATE, [+ field.Label,+ field.FieldType,+ field.IsHidden ? 1 : 0,+ field.DisplayOrder ?? 0,+ currentDateTime,+ field.FieldKey+ ]);+ }++ return field.FieldKey;+ }+/*** Update field values using preserve-and-track strategy.* Preserves existing field value IDs when possible for stable merge behavior.*/- private async updateFieldValues(itemId: string, fields: ItemField[], now: string): Promise<void> {+ private async updateFieldValues(itemId: string, fields: ItemField[], itemType: string, now: string): Promise<void> {// 1. Get existing field valuesconst existingFields = await this.client.executeQuery<{Id: string;@@ -507,9 +597,21 @@ export class ItemRepository extends BaseRepository {const values = Array.isArray(field.Value) ? field.Value : [field.Value];const existingForKey = existingByKey.get(field.FieldKey) || [];- for (let j = 0; j < values.length; j++) {- const value = values[j];- if (value === undefined || value === null || value === '') continue;+ // Skip empty fields+ const filteredValues = values.filter(v => v !== undefined && v !== null && v !== '');+ if (filteredValues.length === 0) {+ continue;+ }++ let fieldDefinitionId: string | null = null;++ // For custom fields, ensure FieldDefinition exists and is up-to-date+ if (field.IsCustomField) {+ fieldDefinitionId = await this.ensureOrUpdateFieldDefinition(field, itemType, now);+ }++ for (let j = 0; j < filteredValues.length; j++) {+ const value = filteredValues[j];const existingEntry = existingForKey[j];@@ -529,8 +631,8 @@ export class ItemRepository extends BaseRepository {await this.client.executeUpdate(FieldValueQueries.INSERT, [this.generateId(),itemId,- field.IsCustomField ? field.FieldKey : null,- field.IsCustomField ? null : field.FieldKey,+ fieldDefinitionId, // FieldDefinitionId for custom, null for system+ field.IsCustomField ? null : field.FieldKey, // FieldKey for system, null for customvalue,(i * 100) + j,now,