Privacy-first password manager with built-in email aliasing. Fully encrypted and self-hostable.
Add duplicate option to mobile app (#2293)
Leendert de Borst4c83fe5b83e0
diff --git a/apps/mobile-app/app/(tabs)/items/folder/[id].tsx b/apps/mobile-app/app/(tabs)/items/folder/[id].tsxindex 9efd0c41c..c15f88c5a 100644--- a/apps/mobile-app/app/(tabs)/items/folder/[id].tsx+++ b/apps/mobile-app/app/(tabs)/items/folder/[id].tsx@@ -92,6 +92,9 @@ export default function FolderViewScreen(): React.ReactNode {// Sort stateconst { sortOrder, setSortOrder, showSortMenu, setShowSortMenu, toggleSortMenu } = useItemSort();+ // Freshly duplicated item that gets scrolled into view and briefly highlighted+ const [highlightedItemId, setHighlightedItemId] = useState<string | null>(null);+// Folder modalsconst [showEditFolderModal, setShowEditFolderModal] = useState(false);const [showDeleteFolderModal, setShowDeleteFolderModal] = useState(false);@@ -370,6 +373,40 @@ export default function FolderViewScreen(): React.ReactNode {await loadItems();}, [dbContext.sqliteClient, executeVaultMutation, loadItems]);+ /**+ * Duplicate an item including all fields except passkeys and field history.+ */+ const onItemDuplicate = useCallback(async (itemId: string): Promise<void> => {+ let newItemId: string | null = null;+ await executeVaultMutation(async () => {+ newItemId = await dbContext.sqliteClient!.items.duplicate(itemId);+ });++ // Reload items to show the new duplicate+ await loadItems();++ // Scroll to and briefly highlight the new duplicate so it's clear where it landed+ setHighlightedItemId(newItemId);+ }, [dbContext.sqliteClient, executeVaultMutation, loadItems]);++ /**+ * Scroll the highlighted item (a freshly created duplicate) into view once it's+ * rendered, then clear the highlight after a short moment.+ */+ useEffect(() => {+ if (!highlightedItemId) {+ return;+ }++ const index = sortedItems.findIndex(itm => itm.Id === highlightedItemId);+ if (index >= 0) {+ flatListRef.current?.scrollToIndex({ index, viewPosition: 0.5, animated: true });+ }++ const timer = setTimeout(() => setHighlightedItemId(null), 2000);+ return (): void => clearTimeout(timer);+ }, [highlightedItemId, sortedItems]);+/*** Rename the folder.*/@@ -921,6 +958,9 @@ export default function FolderViewScreen(): React.ReactNode {windowSize={7}removeClippedSubviews={false}ListHeaderComponent={renderListHeader() as React.ReactElement}+ onScrollToIndexFailed={({ index, averageItemLength }) => {+ flatListRef.current?.scrollToOffset({ offset: index * averageItemLength, animated: true });+ }}refreshControl={<RefreshControlrefreshing={refreshing}@@ -934,7 +974,7 @@ export default function FolderViewScreen(): React.ReactNode {isLoadingItems ? (<SkeletonLoader count={1} height={60} parts={2} />) : (- <ItemCard item={itm} onItemDelete={onItemDelete} />+ <ItemCard item={itm} onItemDelete={onItemDelete} onItemDuplicate={onItemDuplicate} isHighlighted={itm.Id === highlightedItemId} />)}ListEmptyComponent={renderEmptyComponent() as React.ReactElement}diff --git a/apps/mobile-app/app/(tabs)/items/index.tsx b/apps/mobile-app/app/(tabs)/items/index.tsxindex 1c36e7f2e..377e7c634 100644--- a/apps/mobile-app/app/(tabs)/items/index.tsx+++ b/apps/mobile-app/app/(tabs)/items/index.tsx@@ -91,6 +91,9 @@ export default function ItemsScreen(): React.ReactNode {// Recently deleted count stateconst [recentlyDeletedCount, setRecentlyDeletedCount] = useState(0);+ // Freshly duplicated item that gets scrolled into view and briefly highlighted+ const [highlightedItemId, setHighlightedItemId] = useState<string | null>(null);+// Alert dialog stateconst [alertConfig, setAlertConfig] = useState<{ title: string; message: string } | null>(null);@@ -505,6 +508,41 @@ export default function ItemsScreen(): React.ReactNode {await loadItems();}, [dbContext.sqliteClient, executeVaultMutation, loadItems]);+ /**+ * Duplicate an item including all fields except passkeys and field history.+ * Non-blocking: saves locally and syncs in background via ServerSyncIndicator.+ */+ const onItemDuplicate = useCallback(async (itemId: string): Promise<void> => {+ let newItemId: string | null = null;+ await executeVaultMutation(async () => {+ newItemId = await dbContext.sqliteClient!.items.duplicate(itemId);+ });++ // Reload items to show the new duplicate+ await loadItems();++ // Scroll to and briefly highlight the new duplicate so it's clear where it landed+ setHighlightedItemId(newItemId);+ }, [dbContext.sqliteClient, executeVaultMutation, loadItems]);++ /**+ * Scroll the highlighted item (a freshly created duplicate) into view once it's+ * rendered, then clear the highlight after a short moment.+ */+ useEffect(() => {+ if (!highlightedItemId) {+ return;+ }++ const index = sortedItems.findIndex(itm => itm.Id === highlightedItemId);+ if (index >= 0) {+ flatListRef.current?.scrollToIndex({ index, viewPosition: 0.5, animated: true });+ }++ const timer = setTimeout(() => setHighlightedItemId(null), 2000);+ return (): void => clearTimeout(timer);+ }, [highlightedItemId, sortedItems]);+/*** Navigate to a folder, preserving the active type/feature filter so the folder view* shows the same subset of items reflected in the folder's badge count.@@ -950,6 +988,9 @@ export default function ItemsScreen(): React.ReactNode {windowSize={7}removeClippedSubviews={false}ListHeaderComponent={renderListHeader() as React.ReactElement}+ onScrollToIndexFailed={({ index, averageItemLength }) => {+ flatListRef.current?.scrollToOffset({ offset: index * averageItemLength, animated: true });+ }}refreshControl={<RefreshControlrefreshing={refreshing}@@ -962,7 +1003,7 @@ export default function ItemsScreen(): React.ReactNode {isLoadingItems ? (<SkeletonLoader count={1} height={60} parts={2} />) : (- <ItemCard item={itm} onItemDelete={onItemDelete} showFolderPath={!!searchQuery} />+ <ItemCard item={itm} onItemDelete={onItemDelete} onItemDuplicate={onItemDuplicate} showFolderPath={!!searchQuery} isHighlighted={itm.Id === highlightedItemId} />)}ListEmptyComponent={renderEmptyComponent() as React.ReactElement}diff --git a/apps/mobile-app/components/form/PasswordGeneratorPanel.tsx b/apps/mobile-app/components/form/PasswordGeneratorPanel.tsxindex e7bbc886a..922ecdb8a 100644--- a/apps/mobile-app/components/form/PasswordGeneratorPanel.tsx+++ b/apps/mobile-app/components/form/PasswordGeneratorPanel.tsx@@ -108,8 +108,14 @@ export function PasswordGeneratorPanel({ initialSettings, onSettingsChange, onPr}, [applyChange]);const styles = useMemo(() => StyleSheet.create({- chip: {+ card: {backgroundColor: colors.accentBackground,+ borderRadius: 10,+ marginBottom: 16,+ paddingHorizontal: 16,+ },+ chip: {+ backgroundColor: colors.background,borderColor: colors.accentBorder,borderRadius: 6,borderWidth: 1,@@ -186,6 +192,10 @@ export function PasswordGeneratorPanel({ initialSettings, onSettingsChange, onPrborderLeftWidth: 1,padding: 10,},+ rowDivider: {+ borderTopColor: colors.accentBorder,+ borderTopWidth: StyleSheet.hairlineWidth,+ },sectionLabel: {color: colors.textMuted,fontSize: 13,@@ -207,6 +217,7 @@ export function PasswordGeneratorPanel({ initialSettings, onSettingsChange, onPr},sliderSection: {marginBottom: 8,+ paddingTop: 12,},sliderValue: {color: colors.primary,@@ -216,19 +227,19 @@ export function PasswordGeneratorPanel({ initialSettings, onSettingsChange, onPr},tab: {alignItems: 'center',- borderBottomColor: 'transparent',- borderBottomWidth: 2,+ borderRadius: 7,flex: 1,- paddingVertical: 12,+ paddingVertical: 8,},tabActive: {- borderBottomColor: colors.primary,+ backgroundColor: colors.primary,},tabRow: {- borderBottomColor: colors.accentBorder,- borderBottomWidth: StyleSheet.hairlineWidth,+ backgroundColor: colors.accentBackground,+ borderRadius: 10,flexDirection: 'row',marginBottom: 16,+ padding: 4,},tabText: {color: colors.textMuted,@@ -236,7 +247,7 @@ export function PasswordGeneratorPanel({ initialSettings, onSettingsChange, onPrfontWeight: '500',},tabTextActive: {- color: colors.primary,+ color: colors.primarySurfaceText,},toggleRow: {alignItems: 'center',@@ -245,7 +256,7 @@ export function PasswordGeneratorPanel({ initialSettings, onSettingsChange, onPrpaddingVertical: 10,},valuePill: {- backgroundColor: colors.accentBackground,+ backgroundColor: colors.background,borderColor: colors.accentBorder,borderRadius: 6,borderWidth: 1,@@ -268,7 +279,7 @@ export function PasswordGeneratorPanel({ initialSettings, onSettingsChange, onPrvalue: string,onCycle: () => void): React.ReactNode => (- <View style={styles.optionRow}>+ <View style={[styles.optionRow, styles.rowDivider]}><ThemedText style={styles.sliderLabel}>{label}</ThemedText><TouchableOpacity style={styles.valuePill} onPress={onCycle} activeOpacity={0.7}><ThemedText style={styles.valuePillText}>@@ -310,7 +321,7 @@ export function PasswordGeneratorPanel({ initialSettings, onSettingsChange, onPr</View>{!isDiceware ? (- <View>+ <View style={styles.card}>{/* Length slider. */}<View style={styles.sliderSection}><View style={styles.sliderHeader}>@@ -337,7 +348,7 @@ export function PasswordGeneratorPanel({ initialSettings, onSettingsChange, onPr['UseSpecialChars', t('items.includeSpecialChars')],['UseNonAmbiguousChars', t('items.avoidAmbiguousChars')],] as [keyof PasswordSettings, string][]).map(([key, label]) => (- <View key={key} style={styles.toggleRow}>+ <View key={key} style={[styles.toggleRow, styles.rowDivider]}><ThemedText style={styles.sliderLabel}>{label}</ThemedText><TouchableOpacitystyle={[styles.chip, settings[key] ? styles.chipActive : null]}@@ -352,7 +363,7 @@ export function PasswordGeneratorPanel({ initialSettings, onSettingsChange, onPr))}</View>) : (- <View>+ <View style={styles.card}>{/* Word count slider. */}<View style={styles.sliderSection}><View style={styles.sliderHeader}>@@ -393,7 +404,7 @@ export function PasswordGeneratorPanel({ initialSettings, onSettingsChange, onPr{/* Language row. */}<TouchableOpacity- style={styles.languageRow}+ style={[styles.languageRow, styles.rowDivider]}onPress={() => setShowLanguageModal(true)}activeOpacity={0.7}>diff --git a/apps/mobile-app/components/items/ItemCard.tsx b/apps/mobile-app/components/items/ItemCard.tsxindex f01d7fa31..266b24e7d 100644--- a/apps/mobile-app/components/items/ItemCard.tsx+++ b/apps/mobile-app/components/items/ItemCard.tsx@@ -22,13 +22,15 @@ import { getFieldValue, FieldKey } from '@/utils/dist/core/models/vault';type ItemCardProps = {item: Item;onItemDelete?: (itemId: string) => Promise<void>;+ onItemDuplicate?: (itemId: string) => Promise<void>;showFolderPath?: boolean;+ isHighlighted?: boolean;};/*** Item card component for displaying vault items in a list.*/-export function ItemCard({ item, onItemDelete, showFolderPath = false }: ItemCardProps): React.ReactNode {+export function ItemCard({ item, onItemDelete, onItemDuplicate, showFolderPath = false, isHighlighted = false }: ItemCardProps): React.ReactNode {const colors = useColors();const { t } = useTranslation();const { showConfirm } = useDialog();@@ -99,6 +101,11 @@ export function ItemCard({ item, onItemDelete, showFolderPath = false }: ItemCar});});break;+ case t('items.contextMenu.duplicate'):+ if (onItemDuplicate) {+ await onItemDuplicate(item.Id);+ }+ break;case t('items.contextMenu.delete'):Keyboard.dismiss();showConfirm(@@ -204,6 +211,14 @@ export function ItemCard({ item, onItemDelete, showFolderPath = false }: ItemCardefault: 'pencil',}),},+ {+ title: t('items.contextMenu.duplicate'),+ systemIcon: Platform.select({+ ios: 'plus.square.on.square',+ android: 'baseline_content_copy',+ default: 'plus.square.on.square',+ }),+ },{title: t('items.contextMenu.delete'),systemIcon: Platform.select({@@ -268,9 +283,14 @@ export function ItemCard({ item, onItemDelete, showFolderPath = false }: ItemCarconst styles = StyleSheet.create({credentialCard: {backgroundColor: colors.accentBackground,+ borderColor: 'transparent',borderRadius: 8,+ borderWidth: 2,marginBottom: 8,- padding: 12,+ padding: 10,+ },+ credentialCardHighlighted: {+ borderColor: colors.primary,},itemContent: {alignItems: 'center',@@ -317,7 +337,7 @@ export function ItemCard({ item, onItemDelete, showFolderPath = false }: ItemCarpreviewBackgroundColor={colors.accentBackground}><TouchableOpacity- style={styles.credentialCard}+ style={[styles.credentialCard, isHighlighted && styles.credentialCardHighlighted]}onPress={() => {navigate(() => {Keyboard.dismiss();diff --git a/apps/mobile-app/i18n/locales/en.json b/apps/mobile-app/i18n/locales/en.jsonindex 3f73a14d4..c532233b8 100644--- a/apps/mobile-app/i18n/locales/en.json+++ b/apps/mobile-app/i18n/locales/en.json@@ -533,6 +533,7 @@"contextMenu": {"title": "Item Options","edit": "Edit",+ "duplicate": "Duplicate","delete": "Delete","copyUsername": "Copy Username","copyEmail": "Copy Email",diff --git a/apps/mobile-app/utils/db/repositories/ItemRepository.ts b/apps/mobile-app/utils/db/repositories/ItemRepository.tsindex 693573158..01fb93a37 100644--- a/apps/mobile-app/utils/db/repositories/ItemRepository.ts+++ b/apps/mobile-app/utils/db/repositories/ItemRepository.ts@@ -397,6 +397,132 @@ export class ItemRepository extends BaseRepository {});}+ /**+ * Duplicate an item including all fields except passkeys and field history.+ * @param itemId - The ID of the item to duplicate+ * @returns The ID of the newly created item+ */+ public async duplicate(itemId: string): Promise<string | null> {+ return this.withTransaction(async () => {+ const now = this.now();+ const newItemId = this.generateId();++ const sourceRows = await this.client.executeQuery<{ Name: string | null }>(+ `SELECT Name FROM Items WHERE Id = ? AND IsDeleted = 0`,+ [itemId]+ );+ if (sourceRows.length === 0) {+ throw new Error(`Item not found: ${itemId}`);+ }++ const existingNames = await this.client.executeQuery<{ Name: string | null }>(+ `SELECT Name FROM Items WHERE IsDeleted = 0 AND DeletedAt IS NULL`+ );+ const newName = ItemRepository.generateCopyName(+ sourceRows[0].Name,+ existingNames.map(row => row.Name)+ );++ // 1. Copy the item row itself (same logo, folder and type).+ await this.client.executeUpdate(`+ INSERT INTO Items (Id, Name, ItemType, LogoId, FolderId, CreatedAt, UpdatedAt, IsDeleted)+ SELECT ?, ?, ItemType, LogoId, FolderId, ?, ?, 0 FROM Items WHERE Id = ?`,+ [newItemId, newName, now, now, itemId]);++ // 2. Copy custom field definitions so later edits to the duplicate's+ // custom fields don't affect the original item.+ const definitionRows = await this.client.executeQuery<{ Id: string }>(+ `SELECT DISTINCT FieldDefinitionId as Id FROM FieldValues+ WHERE ItemId = ? AND IsDeleted = 0 AND FieldDefinitionId IS NOT NULL`,+ [itemId]+ );+ const definitionIdMap = new Map<string, string>();+ for (const definition of definitionRows) {+ const newDefinitionId = this.generateId();+ definitionIdMap.set(definition.Id, newDefinitionId);+ await this.client.executeUpdate(`+ INSERT INTO FieldDefinitions (Id, FieldType, Label, IsMultiValue, IsHidden, EnableHistory, Weight, ApplicableToTypes, CreatedAt, UpdatedAt, IsDeleted)+ SELECT ?, FieldType, Label, IsMultiValue, IsHidden, EnableHistory, Weight, ApplicableToTypes, ?, ?, 0 FROM FieldDefinitions WHERE Id = ?`,+ [newDefinitionId, now, now, definition.Id]);+ }++ // 3. Copy field values, remapping custom fields to the copied definitions.+ const fieldValueRows = await this.client.executeQuery<{ Id: string; FieldDefinitionId: string | null }>(+ `SELECT Id, FieldDefinitionId FROM FieldValues WHERE ItemId = ? AND IsDeleted = 0`,+ [itemId]+ );+ for (const row of fieldValueRows) {+ await this.client.executeUpdate(`+ INSERT INTO FieldValues (Id, ItemId, FieldDefinitionId, FieldKey, Value, Weight, CreatedAt, UpdatedAt, IsDeleted)+ SELECT ?, ?, ?, FieldKey, Value, Weight, ?, ?, 0 FROM FieldValues WHERE Id = ?`,+ [+ this.generateId(),+ newItemId,+ row.FieldDefinitionId ? definitionIdMap.get(row.FieldDefinitionId) ?? null : null,+ now,+ now,+ row.Id+ ]);+ }++ // 4. Copy remaining child rows with fresh IDs.+ const childCopies = [+ {+ table: 'TotpCodes',+ sql: `INSERT INTO TotpCodes (Id, ItemId, Name, SecretKey, CreatedAt, UpdatedAt, IsDeleted)+ SELECT ?, ?, Name, SecretKey, ?, ?, 0 FROM TotpCodes WHERE Id = ?`,+ },+ {+ table: 'Attachments',+ sql: `INSERT INTO Attachments (Id, ItemId, Filename, Blob, CreatedAt, UpdatedAt, IsDeleted)+ SELECT ?, ?, Filename, Blob, ?, ?, 0 FROM Attachments WHERE Id = ?`,+ },+ {+ table: 'ItemTags',+ sql: `INSERT INTO ItemTags (Id, ItemId, TagId, CreatedAt, UpdatedAt, IsDeleted)+ SELECT ?, ?, TagId, ?, ?, 0 FROM ItemTags WHERE Id = ?`,+ optional: true,+ },+ ];++ for (const copy of childCopies) {+ if (copy.optional && !(await this.tableExists(copy.table))) {+ continue;+ }++ const rows = await this.client.executeQuery<{ Id: string }>(+ `SELECT Id FROM ${copy.table} WHERE ItemId = ? AND IsDeleted = 0`,+ [itemId]+ );+ for (const row of rows) {+ await this.client.executeUpdate(copy.sql, [this.generateId(), newItemId, now, now, row.Id]);+ }+ }++ return newItemId;+ });+ }++ /**+ * Generate a unique name for a duplicated item: "Name (1)", "Name (2)", etc.+ * If the source name already ends with a "(n)" suffix, the counter is incremented+ * instead of stacking suffixes.+ */+ private static generateCopyName(sourceName: string | null, existingNames: (string | null)[]): string | null {+ if (!sourceName) {+ return sourceName;+ }++ const base = sourceName.replace(/ \(\d+\)$/, '');+ const taken = new Set(existingNames.filter((name): name is string => name !== null));++ let candidate = `${base} (1)`;+ for (let counter = 2; taken.has(candidate); counter++) {+ candidate = `${base} (${counter})`;+ }+ return candidate;+ }+/*** Update an existing item with its fields and related entities.* @param item - The item to update