Privacy-first password manager with built-in email aliasing. Fully encrypted and self-hostable.
Add AddEditItemScreen.tsx with new explicit manifestId paths (#2159)
Leendert de Borst6bd307066b33
diff --git a/apps/browser-extension/src/entrypoints/popup/pages/items/ItemAddEdit.tsx b/apps/browser-extension/src/entrypoints/popup/pages/items/ItemAddEdit.tsxindex fba9f08df..5af51a2bb 100644--- a/apps/browser-extension/src/entrypoints/popup/pages/items/ItemAddEdit.tsx+++ b/apps/browser-extension/src/entrypoints/popup/pages/items/ItemAddEdit.tsx@@ -1,7 +1,7 @@import { scopedKey } from '@aliasvault/client/database/ItemRef';import { manifestForItemIn } from '@aliasvault/client/database/ItemRef';import * as RustCore from '@aliasvault/client/rust/RustCore';-import { FieldCategories, FieldTypes, LogoKinds, ItemTypes, getSystemFieldsForItemType, getOptionalFieldsForItemType, isFieldShownByDefault, getSystemField, fieldAppliesToType } from '@aliasvault/models/vault';+import { FieldCategories, FieldTypes, LogoKinds, ItemTypes, isItemType, getSystemFieldsForItemType, getOptionalFieldsForItemType, isFieldShownByDefault, getSystemField, fieldAppliesToType } from '@aliasvault/models/vault';import React, { useState, useEffect, useCallback, useMemo, useRef } from 'react';import { flushSync } from 'react-dom';import { useTranslation } from 'react-i18next';@@ -46,9 +46,6 @@ import type { Item, ItemField, ItemType, FieldType, Attachment, TotpCode, Passwoimport { browser } from '#imports';-// Valid item types from the shared model-const VALID_ITEM_TYPES: ItemType[] = [ItemTypes.Login, ItemTypes.Alias, ItemTypes.CreditCard, ItemTypes.Note];-// Default item type for new itemsconst DEFAULT_ITEM_TYPE: ItemType = ItemTypes.Login;@@ -94,7 +91,7 @@ const ItemAddEdit: React.FC = () => {const isEditMode = id !== undefined && id.length > 0 && manifestId !== undefined && manifestId.length > 0;// Get item type, title, and folder from URL parameters (for create mode)- const itemTypeParam = searchParams.get('type') as ItemType | null;+ const itemTypeParam = searchParams.get('type');const itemTitleParam = searchParams.get('itemTitle');const folderManifestIdParam = searchParams.get('folderManifestId');const folderIdParam = folderManifestIdParam ? searchParams.get('folderId') : null;@@ -350,9 +347,7 @@ const ItemAddEdit: React.FC = () => {useEffect(() => {if (!dbContext?.sqliteClient || !id || !manifestId || !isEditMode) {// Create mode - initialize with defaults- const effectiveType: ItemType = (itemTypeParam && VALID_ITEM_TYPES.includes(itemTypeParam))- ? itemTypeParam- : DEFAULT_ITEM_TYPE;+ const effectiveType: ItemType = isItemType(itemTypeParam) ? itemTypeParam : DEFAULT_ITEM_TYPE;/*** Initialize create mode with service detection from URL params or active tab.diff --git a/apps/mobile-app/app/(tabs)/items/[manifestId]/[id]/edit-page.tsx b/apps/mobile-app/app/(tabs)/items/[manifestId]/[id]/edit-page.tsxnew file mode 100644index 000000000..bd7346917--- /dev/null+++ b/apps/mobile-app/app/(tabs)/items/[manifestId]/[id]/edit-page.tsx@@ -0,0 +1,14 @@+import { useLocalSearchParams } from 'expo-router';+import { useMemo } from 'react';++import { ItemFormPage } from '@/components/items/ItemFormPage';++/**+ * Edit item screen as a page, the deep link target.+ */+export default function EditItemPageScreen(): React.ReactNode {+ const { manifestId, id } = useLocalSearchParams<{ manifestId: string; id: string }>();+ const editRef = useMemo(() => ({ Id: id, ManifestId: manifestId }), [id, manifestId]);++ return <ItemFormPage editRef={editRef} />;+}diff --git a/apps/mobile-app/app/(tabs)/items/[manifestId]/[id]/edit.tsx b/apps/mobile-app/app/(tabs)/items/[manifestId]/[id]/edit.tsxnew file mode 100644index 000000000..f1c9faa10--- /dev/null+++ b/apps/mobile-app/app/(tabs)/items/[manifestId]/[id]/edit.tsx@@ -0,0 +1,14 @@+import { useLocalSearchParams } from 'expo-router';+import { useMemo } from 'react';++import AddEditItemScreen from '@/components/items/AddEditItemScreen';++/**+ * Edit item screen, shown as a modal.+ */+export default function EditItemScreen(): React.ReactNode {+ const { manifestId, id } = useLocalSearchParams<{ manifestId: string; id: string }>();+ const editRef = useMemo(() => ({ Id: id, ManifestId: manifestId }), [id, manifestId]);++ return <AddEditItemScreen editRef={editRef} />;+}diff --git a/apps/mobile-app/app/(tabs)/items/[manifestId]/[id]/index.tsx b/apps/mobile-app/app/(tabs)/items/[manifestId]/[id]/index.tsxindex 1c193aed5..c7f3d8ce4 100644--- a/apps/mobile-app/app/(tabs)/items/[manifestId]/[id]/index.tsx+++ b/apps/mobile-app/app/(tabs)/items/[manifestId]/[id]/index.tsx@@ -116,7 +116,7 @@ export default function ItemDetailsScreen() : React.ReactNode {loadItem();// Add listener for item changes- const itemChangedSub = emitter.addListener('credentialChanged', async (change?: ItemChangedEvent) => {+ const itemChangedSub = emitter.addListener('itemChanged', async (change?: ItemChangedEvent) => {if (!change || scopedKey(change.previous.ManifestId, change.previous.Id) !== scopedKey(itemRef.ManifestId, itemRef.Id)) {return;}diff --git a/apps/mobile-app/app/(tabs)/items/_layout.tsx b/apps/mobile-app/app/(tabs)/items/_layout.tsxindex 695460289..060f3e2b3 100644--- a/apps/mobile-app/app/(tabs)/items/_layout.tsx+++ b/apps/mobile-app/app/(tabs)/items/_layout.tsx@@ -22,7 +22,7 @@ export default function ItemsLayout(): React.ReactNode {}}/><Stack.Screen- name="folder/[id]"+ name="folder/[manifestId]/[id]"options={{title: t('items.folders.folder'),headerBackTitle: t('items.title'),@@ -30,7 +30,7 @@ export default function ItemsLayout(): React.ReactNode {}}/><Stack.Screen- name="add-edit"+ name="add"options={{title: t('items.addItem'),presentation: Platform.OS === 'ios' ? 'modal' : 'card',@@ -38,7 +38,7 @@ export default function ItemsLayout(): React.ReactNode {}}/><Stack.Screen- name="add-edit-page"+ name="add-page"options={{title: t('items.addItem'),...defaultHeaderOptions,@@ -75,12 +75,27 @@ export default function ItemsLayout(): React.ReactNode {}}/><Stack.Screen- name="[id]"+ name="[manifestId]/[id]/index"options={{title: t('items.itemDetails'),...defaultHeaderOptions,}}/>+ <Stack.Screen+ name="[manifestId]/[id]/edit"+ options={{+ title: t('items.editItem'),+ presentation: Platform.OS === 'ios' ? 'modal' : 'card',+ ...defaultHeaderOptions,+ }}+ />+ <Stack.Screen+ name="[manifestId]/[id]/edit-page"+ options={{+ title: t('items.editItem'),+ ...defaultHeaderOptions,+ }}+ /><Stack.Screenname="email/[id]"options={{diff --git a/apps/mobile-app/app/(tabs)/items/add-edit-page.tsx b/apps/mobile-app/app/(tabs)/items/add-edit-page.tsxdeleted file mode 100644index af7068739..000000000--- a/apps/mobile-app/app/(tabs)/items/add-edit-page.tsx+++ /dev/null@@ -1,32 +0,0 @@-import React from 'react';-import { View, StyleSheet } from 'react-native';--import AddEditCredentialScreen from './add-edit';--/**- * AddEditPageScreen Component- *- * This screen component displays add/edit credential details as a page- * instead of a modal. This is because when deeplinking to the add/edit- * credential screen, the modal presentation gives issues when the vault- * is locked due to time-out and can freeze the screen. Using a normal- * page presentation style works around this issue.- *- * This component is only used by deep-linking, all normal app links- * use the normal add-edit.tsx modal component.- */-export default function AddEditPageScreen(): React.ReactNode {- return (- <View style={styles.container}>- <AddEditCredentialScreen />- </View>- );-}--const styles = StyleSheet.create({- container: {- flex: 1,- paddingBottom: 60,- paddingTop: 40,- },-});diff --git a/apps/mobile-app/app/(tabs)/items/add-page.tsx b/apps/mobile-app/app/(tabs)/items/add-page.tsxnew file mode 100644index 000000000..31964b0c9--- /dev/null+++ b/apps/mobile-app/app/(tabs)/items/add-page.tsx@@ -0,0 +1,8 @@+import { ItemFormPage } from '@/components/items/ItemFormPage';++/**+ * Create item screen as a page, the deep link target. See ItemFormPage for why it is not a modal.+ */+export default function AddItemPageScreen(): React.ReactNode {+ return <ItemFormPage />;+}diff --git a/apps/mobile-app/app/(tabs)/items/add.tsx b/apps/mobile-app/app/(tabs)/items/add.tsxnew file mode 100644index 000000000..2863bde2f--- /dev/null+++ b/apps/mobile-app/app/(tabs)/items/add.tsx@@ -0,0 +1,8 @@+import AddEditItemScreen from '@/components/items/AddEditItemScreen';++/**+ * Create item screen, shown as a modal.+ */+export default function AddItemScreen(): React.ReactNode {+ return <AddEditItemScreen />;+}diff --git a/apps/mobile-app/app/(tabs)/items/autofill-open-app.tsx b/apps/mobile-app/app/(tabs)/items/autofill-open-app.tsxindex 6ae421a9a..990f05ea7 100644--- a/apps/mobile-app/app/(tabs)/items/autofill-open-app.tsx+++ b/apps/mobile-app/app/(tabs)/items/autofill-open-app.tsx@@ -58,12 +58,11 @@ export default function AutofillOpenAppScreen(): React.ReactNode {}, [router, decodedAppInfo]);/**- * Navigate to the existing add-edit-page deep-link target with the- * URL pre-populated, mirroring the previous behaviour.+ * Navigate to the add item page with the URL pre-populated.*/const handleCreateNew = useCallback(() => {router.replace(- `/(tabs)/items/add-edit-page?itemUrl=${encodeURIComponent(decodedAppInfo)}`+ `/(tabs)/items/add-page?itemUrl=${encodeURIComponent(decodedAppInfo)}`);}, [router, decodedAppInfo]);diff --git a/apps/mobile-app/app/(tabs)/items/deleted.tsx b/apps/mobile-app/app/(tabs)/items/deleted.tsxindex 6f1514c4f..39d394d6e 100644--- a/apps/mobile-app/app/(tabs)/items/deleted.tsx+++ b/apps/mobile-app/app/(tabs)/items/deleted.tsx@@ -100,7 +100,7 @@ export default function RecentlyDeletedScreen(): React.ReactNode {});await loadItems();- emitter.emit('credentialChanged');+ emitter.emit('itemChanged');Toast.show({type: 'success',@@ -121,7 +121,7 @@ export default function RecentlyDeletedScreen(): React.ReactNode {});await loadItems();- emitter.emit('credentialChanged');+ emitter.emit('itemChanged');setShowConfirmDelete(false);setSelectedItem(null);@@ -146,7 +146,7 @@ export default function RecentlyDeletedScreen(): React.ReactNode {});await loadItems();- emitter.emit('credentialChanged');+ emitter.emit('itemChanged');setShowConfirmEmptyAll(false);Toast.show({diff --git a/apps/mobile-app/app/(tabs)/items/folder/[id].tsx b/apps/mobile-app/app/(tabs)/items/folder/[manifestId]/[id].tsxsimilarity index 89%rename from apps/mobile-app/app/(tabs)/items/folder/[id].tsxrename to apps/mobile-app/app/(tabs)/items/folder/[manifestId]/[id].tsxindex d3a77dd59..a136da19f 100644--- a/apps/mobile-app/app/(tabs)/items/folder/[id].tsx+++ b/apps/mobile-app/app/(tabs)/items/folder/[manifestId]/[id].tsx@@ -1,3 +1,4 @@+import { scopedKey, type ItemRef } from '@aliasvault/client/database/ItemRef';import { canHaveSubfolders, getRecursiveItemCount, isSharedFolder } from '@aliasvault/client/items/FolderUtils';import { applyTypeFilter, isItemTypeFilter, parseItemFilterType, type ItemFilterType } from '@aliasvault/client/items/ItemFilters';import { getFieldValue, FieldKey, ItemTypes } from '@aliasvault/models/vault';@@ -11,6 +12,7 @@ import Toast from 'react-native-toast-message';import type { DisplayItem } from '@/utils/DisplayItem';import emitter from '@/utils/EventEmitter';+import { folderRoute } from '@/utils/FolderRoute';import { HapticsUtility } from '@/utils/HapticsUtility';import { VaultAuthenticationError } from '@/utils/types/errors/VaultAuthenticationError';@@ -40,7 +42,7 @@ import { useDialog } from '@/context/DialogContext';import type { FolderWithCount } from '@/components/folders/FolderPill';import type { ItemSummary } from '@aliasvault/client/database/mappers/ItemMapper';-import type { Folder } from '@aliasvault/client/database/repositories/FolderRepository';+import type { Folder, FolderRef } from '@aliasvault/client/database/repositories/FolderRepository';import type { CredentialSortOrder } from '@aliasvault/client/database/repositories/SettingsRepository';import type { ItemType } from '@aliasvault/models/vault';@@ -68,7 +70,8 @@ const ITEM_TYPE_OPTIONS: ItemTypeOption[] = [* Simplified view with search scoped to this folder only.*/export default function FolderViewScreen(): React.ReactNode {- const { id: folderId, filter: filterParam } = useLocalSearchParams<{ id: string; filter?: string }>();+ const { id: folderId, manifestId, filter: filterParam } = useLocalSearchParams<{ manifestId: string; id: string; filter?: string }>();+ const folderRef = useMemo((): FolderRef => ({ Id: folderId, ManifestId: manifestId }), [folderId, manifestId]);const { syncVault } = useVaultSync();const colors = useColors();const { t } = useTranslation();@@ -87,19 +90,11 @@ export default function FolderViewScreen(): React.ReactNode {const [isLoadingItems, setIsLoadingItems] = useState(true);const [refreshing, setRefreshing] = useMinDurationLoading(false, 200);const { executeVaultMutation } = useVaultMutate();-- // Initial filter comes from the route param so navigating from a filtered list into a folder keeps the filter active.const [searchQuery, setSearchQuery] = useState('');const [filterType, setFilterType] = useState<ItemFilterType>(() => parseItemFilterType(filterParam));const [showFilterMenu, setShowFilterMenu] = useState(false);-- // 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 modals+ const [highlightedItemKey, setHighlightedItemKey] = useState<string | null>(null);const [showEditFolderModal, setShowEditFolderModal] = useState(false);const [showDeleteFolderModal, setShowDeleteFolderModal] = useState(false);const [showCreateSubfolderModal, setShowCreateSubfolderModal] = useState(false);@@ -172,45 +167,41 @@ export default function FolderViewScreen(): React.ReactNode {* Used for the delete folder modal to show accurate count.*/const totalItemCountInFolderTree = useMemo(() => {- if (!folderId || allFolders.length === 0) {+ if (allFolders.length === 0) {return 0;}- return getRecursiveItemCount(folderId, itemSummaries, allFolders);- }, [folderId, allFolders, itemSummaries]);+ return getRecursiveItemCount(folderRef, itemSummaries, allFolders);+ }, [folderRef, allFolders, itemSummaries]);/*** Direct subfolders of the current folder, with item counts that respect the active* type/feature filter so each badge matches what the user will see when opening the folder.*/const subfolders = useMemo((): FolderWithCount[] => {- if (!folderId || allFolders.length === 0) {+ if (allFolders.length === 0) {return [];}const itemsForCount = applyTypeFilter(itemSummaries, filterType);- const childFolders = allFolders.filter((f: Folder) => f.ParentFolderId === folderId);+ const childFolders = allFolders.filter((f: Folder) => f.ParentFolderId === folderRef.Id && f.ManifestId === folderRef.ManifestId);return childFolders.map((f) => ({id: f.Id,+ manifestId: f.ManifestId,name: f.Name,- itemCount: getRecursiveItemCount(f.Id, itemsForCount, allFolders),+ itemCount: getRecursiveItemCount(f, itemsForCount, allFolders),isShared: isSharedFolder(f, personalManifestId),}));- }, [folderId, allFolders, itemSummaries, filterType, personalManifestId]);+ }, [folderRef, allFolders, itemSummaries, filterType, personalManifestId]);/*** Load items in this folder, subfolders, and folder details.*/const loadItems = useCallback(async (): Promise<void> => {- if (!folderId) {- setIsLoadingItems(false);- return;- }-try {const [folderItems, summaries, folders, savedSortOrder] = await Promise.all([- dbContext.sqliteClient!.items.getByFolder(folderId),+ dbContext.sqliteClient!.items.getByFolder(folderRef),dbContext.sqliteClient!.items.getAllSummaries(),dbContext.sqliteClient!.folders.getAll(),dbContext.sqliteClient!.settings.getCredentialsSortOrder()@@ -219,13 +210,13 @@ export default function FolderViewScreen(): React.ReactNode {setItemSummaries(summaries);// Find this folder- const currentFolder = folders.find((f: Folder) => f.Id === folderId);+ const currentFolder = folders.find((f: Folder) => f.Id === folderRef.Id && f.ManifestId === folderRef.ManifestId);setFolder(currentFolder || null);setAllFolders(folders);// Calculate if we can create subfolders (check depth)- setCanCreateSubfolder(canHaveSubfolders(folderId, folders));+ setCanCreateSubfolder(canHaveSubfolders(folderRef, folders));setSortOrder(savedSortOrder);setIsLoadingItems(false);@@ -238,11 +229,11 @@ export default function FolderViewScreen(): React.ReactNode {});setIsLoadingItems(false);}- }, [dbContext.sqliteClient, folderId, setIsLoadingItems, setSortOrder, t]);+ }, [dbContext.sqliteClient, folderRef, setIsLoadingItems, setSortOrder, t]);useEffect(() => {// Add listener for item changes- const itemChangedSub = emitter.addListener('credentialChanged', async () => {+ const itemChangedSub = emitter.addListener('itemChanged', async () => {await loadItems();});@@ -369,9 +360,9 @@ export default function FolderViewScreen(): React.ReactNode {* Delete an item (move to trash).* Non-blocking: saves locally and syncs in background via ServerSyncIndicator.*/- const onItemDelete = useCallback(async (itemId: string): Promise<void> => {+ const onItemDelete = useCallback(async (item: ItemRef): Promise<void> => {await executeVaultMutation(async () => {- await dbContext.sqliteClient!.items.trash(itemId);+ await dbContext.sqliteClient!.items.trash(item);});// Reload items to reflect the deletion@@ -381,17 +372,18 @@ export default function FolderViewScreen(): React.ReactNode {/*** Duplicate an item including all fields except passkeys and field history.*/- const onItemDuplicate = useCallback(async (itemId: string): Promise<void> => {- let newItemId: string | null = null;+ const onItemDuplicate = useCallback(async (item: ItemRef): Promise<void> => {+ let duplicate: ItemRef | null = null;await executeVaultMutation(async () => {- newItemId = await dbContext.sqliteClient!.items.duplicate(itemId);+ duplicate = await dbContext.sqliteClient!.items.duplicate(item);});// Reload items to show the new duplicateawait loadItems();// Scroll to and briefly highlight the new duplicate so it's clear where it landed- setHighlightedItemId(newItemId);+ const created = duplicate as ItemRef | null;+ setHighlightedItemKey(created ? scopedKey(created.ManifestId, created.Id) : null);}, [dbContext.sqliteClient, executeVaultMutation, loadItems]);/**@@ -399,82 +391,70 @@ export default function FolderViewScreen(): React.ReactNode {* rendered, then clear the highlight after a short moment.*/useEffect(() => {- if (!highlightedItemId) {+ if (!highlightedItemKey) {return;}- const index = sortedItems.findIndex(itm => itm.Id === highlightedItemId);+ const index = sortedItems.findIndex(itm => scopedKey(itm.ManifestId, itm.Id) === highlightedItemKey);if (index >= 0) {flatListRef.current?.scrollToIndex({ index, viewPosition: 0.5, animated: true });}- const timer = setTimeout(() => setHighlightedItemId(null), 2000);+ const timer = setTimeout(() => setHighlightedItemKey(null), 2000);return (): void => clearTimeout(timer);- }, [highlightedItemId, sortedItems]);+ }, [highlightedItemKey, sortedItems]);/*** Rename the folder.*/const handleEditFolder = useCallback(async (newName: string) => {- if (!folderId) {- return;- }-await executeVaultMutation(async () => {- await dbContext.sqliteClient!.folders.update(folderId, newName);+ await dbContext.sqliteClient!.folders.update(folderRef, newName);});await loadItems();setShowEditFolderModal(false);- }, [dbContext.sqliteClient, folderId, executeVaultMutation, loadItems]);+ }, [dbContext.sqliteClient, folderRef, executeVaultMutation, loadItems]);/*** Delete the folder (keep items - move them to root).*/const handleDeleteFolderOnly = useCallback(async () => {- if (!folderId) {- return;- }-await executeVaultMutation(async () => {- await dbContext.sqliteClient!.folders.delete(folderId);+ await dbContext.sqliteClient!.folders.delete(folderRef);});// Emit event to refresh the home screen folder list- emitter.emit('credentialChanged');+ emitter.emit('itemChanged');router.back();- }, [dbContext.sqliteClient, folderId, executeVaultMutation, router]);+ }, [dbContext.sqliteClient, folderRef, executeVaultMutation, router]);/*** Delete the folder and all its contents.*/const handleDeleteFolderAndContents = useCallback(async () => {- if (!folderId) {- return;- }-await executeVaultMutation(async () => {- await dbContext.sqliteClient!.folders.deleteWithContents(folderId);+ await dbContext.sqliteClient!.folders.deleteWithContents(folderRef);});// Emit event to refresh the home screen folder list- emitter.emit('credentialChanged');+ emitter.emit('itemChanged');router.back();- }, [dbContext.sqliteClient, folderId, executeVaultMutation, router]);+ }, [dbContext.sqliteClient, folderRef, executeVaultMutation, router]);/*** Handle item type selection from the FAB menu.*/const handleAddItem = useCallback((itemType: ItemType) => {navigate(() => {- router.push(`/(tabs)/items/add-edit?folderId=${folderId}&itemType=${itemType}` as '/(tabs)/items/add-edit');+ router.push(`/(tabs)/items/add?folderId=${folderRef.Id}&folderManifestId=${encodeURIComponent(folderRef.ManifestId)}&itemType=${itemType}` as '/(tabs)/items/add');HapticsUtility.impact();});- }, [folderId, router, navigate]);+ }, [folderRef, router, navigate]);/*** Handle subfolder click.*/- const handleSubfolderClick = useCallback((subfolderId: string) => {+ const handleSubfolderClick = useCallback((subfolder: FolderRef) => {navigate(() => {- router.push(`/(tabs)/items/folder/${subfolderId}?filter=${encodeURIComponent(filterType)}` as '/(tabs)/items/folder/[id]');+ router.push(folderRoute(subfolder, filterType));});}, [router, navigate, filterType]);@@ -482,16 +462,12 @@ export default function FolderViewScreen(): React.ReactNode {* Create a new subfolder.*/const handleCreateSubfolder = useCallback(async (name: string) => {- if (!folderId) {- return;- }-await executeVaultMutation(async () => {- await dbContext.sqliteClient!.folders.create(name, folderId);+ await dbContext.sqliteClient!.folders.create(name, folderRef);});await loadItems();setShowCreateSubfolderModal(false);- }, [dbContext.sqliteClient, folderId, executeVaultMutation, loadItems]);+ }, [dbContext.sqliteClient, folderRef, executeVaultMutation, loadItems]);const paddingTop = Platform.OS === 'ios' ? 56 : 16;const paddingBottom = Platform.OS === 'ios' ? insets.bottom + 60 : 40;@@ -779,7 +755,7 @@ export default function FolderViewScreen(): React.ReactNode {<ThemedView>{/* Folder breadcrumb navigation */}<FolderBreadcrumb- folderId={folderId}+ folder={folderRef}excludeCurrentFolder={true}folders={allFolders}/>@@ -789,9 +765,9 @@ export default function FolderViewScreen(): React.ReactNode {<View style={styles.folderPillsContainer}>{subfolders.map((subfolder) => (<FolderPill- key={subfolder.id}+ key={scopedKey(subfolder.manifestId, subfolder.id)}folder={subfolder}- onPress={() => handleSubfolderClick(subfolder.id)}+ onPress={() => handleSubfolderClick({ Id: subfolder.id, ManifestId: subfolder.manifestId })}/>))}{canCreateSubfolder && (@@ -882,7 +858,7 @@ export default function FolderViewScreen(): React.ReactNode {</ThemedView></ThemedView>);- }, [folderId, allFolders, searchQuery, subfolders, canCreateSubfolder, handleSubfolderClick, showFilterMenu, filteredItems.length, getFilterTitle, toggleSortMenu, styles, colors, t]);+ }, [folderRef, allFolders, searchQuery, subfolders, canCreateSubfolder, handleSubfolderClick, showFilterMenu, filteredItems.length, getFilterTitle, toggleSortMenu, styles, colors, t]);/*** Render empty state.@@ -913,7 +889,7 @@ export default function FolderViewScreen(): React.ReactNode {<FlatListref={flatListRef}data={isLoadingItems ? Array(4).fill(null) : sortedItems}- keyExtractor={(itm, index) => itm?.Id ?? `skeleton-${index}`}+ keyExtractor={(itm, index) => itm ? scopedKey(itm.ManifestId, itm.Id) : `skeleton-${index}`}keyboardShouldPersistTaps='handled'contentContainerStyle={styles.contentContainer}scrollIndicatorInsets={{ bottom: 40 }}@@ -938,7 +914,7 @@ export default function FolderViewScreen(): React.ReactNode {isLoadingItems ? (<SkeletonLoader count={1} height={60} parts={2} />) : (- <ItemCard item={itm} onItemDelete={onItemDelete} onItemDuplicate={onItemDuplicate} isHighlighted={itm.Id === highlightedItemId} />+ <ItemCard item={itm} onItemDelete={onItemDelete} onItemDuplicate={onItemDuplicate} isHighlighted={scopedKey(itm.ManifestId, itm.Id) === highlightedItemKey} />)}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 77c4f8cb5..662dfaa01 100644--- a/apps/mobile-app/app/(tabs)/items/index.tsx+++ b/apps/mobile-app/app/(tabs)/items/index.tsx@@ -1,4 +1,5 @@-import { isSharedFolder } from '@aliasvault/client/items/FolderUtils';+import { scopedKey, type ItemRef } from '@aliasvault/client/database/ItemRef';+import { getRecursiveItemCount, isSharedFolder } from '@aliasvault/client/items/FolderUtils';import { applyTypeFilter, isItemTypeFilter, type ItemFilterType } from '@aliasvault/client/items/ItemFilters';import { getFieldValue, FieldKey, ItemTypes } from '@aliasvault/models/vault';import MaterialIcons from '@expo/vector-icons/MaterialIcons';@@ -11,6 +12,7 @@ import Toast from 'react-native-toast-message';import type { DisplayItem } from '@/utils/DisplayItem';import emitter from '@/utils/EventEmitter';+import { folderRoute } from '@/utils/FolderRoute';import { HapticsUtility } from '@/utils/HapticsUtility';import { VaultAuthenticationError } from '@/utils/types/errors/VaultAuthenticationError';@@ -40,7 +42,7 @@ import { useApp } from '@/context/AppContext';import { useDb } from '@/context/DbContext';import { LocalPreferencesService } from '@/services/LocalPreferencesService';-import type { Folder } from '@aliasvault/client/database/repositories/FolderRepository';+import type { Folder, FolderRef } from '@aliasvault/client/database/repositories/FolderRepository';import type { CredentialSortOrder } from '@aliasvault/client/database/repositories/SettingsRepository';import type { ItemType } from '@aliasvault/models/vault';@@ -98,8 +100,8 @@ 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);+ // Scoped key (manifest and id) of a freshly duplicated item that gets scrolled into view and briefly highlighted+ const [highlightedItemKey, setHighlightedItemKey] = useState<string | null>(null);// Alert dialog stateconst [alertConfig, setAlertConfig] = useState<{ title: string; message: string } | null>(null);@@ -189,33 +191,14 @@ export default function ItemsScreen(): React.ReactNode {// Apply the active type/feature filter to the items used for counting.const itemsForCount = applyTypeFilter(itemsList, filterType);- /**- * Count items per folder (including items in subfolders recursively).- * @param folderId - The folder ID to count items for- * @returns Total count of items in the folder and all subfolders- */- const getRecursiveItemCount = (folderId: string): number => {- // Get items directly in this folder- const directItems = itemsForCount.filter((item: DisplayItem) => item.FolderId === folderId);-- // Get all child folders- const childFolders = folders.filter(f => f.ParentFolderId === folderId);-- // Recursively count items in child folders- const childItemCount = childFolders.reduce((count, child) => {- return count + getRecursiveItemCount(child.Id);- }, 0);-- return directItems.length + childItemCount;- };-// Return only root-level folders (no parent) with recursive counts, sorted alphabeticallyreturn folders.filter(folder => !folder.ParentFolderId) // Only root-level folders.map(folder => ({id: folder.Id,+ manifestId: folder.ManifestId,name: folder.Name,- itemCount: getRecursiveItemCount(folder.Id),+ itemCount: getRecursiveItemCount(folder, itemsForCount, folders),isShared: isSharedFolder(folder, personalManifestId)})).sort((a, b) => a.name.localeCompare(b.name));@@ -357,7 +340,7 @@ export default function ItemsScreen(): React.ReactNode {});// Add listener for item/credential changes- const itemChangedSub = emitter.addListener('credentialChanged', async () => {+ const itemChangedSub = emitter.addListener('itemChanged', async () => {await loadItems();});@@ -511,9 +494,9 @@ export default function ItemsScreen(): React.ReactNode {* Delete an item (move to trash).* Non-blocking: saves locally and syncs in background via ServerSyncIndicator.*/- const onItemDelete = useCallback(async (itemId: string): Promise<void> => {+ const onItemDelete = useCallback(async (item: ItemRef): Promise<void> => {await executeVaultMutation(async () => {- await dbContext.sqliteClient!.items.trash(itemId);+ await dbContext.sqliteClient!.items.trash(item);});// Reload items to reflect the deletion@@ -524,17 +507,18 @@ export default function ItemsScreen(): React.ReactNode {* 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;+ const onItemDuplicate = useCallback(async (item: ItemRef): Promise<void> => {+ let duplicate: ItemRef | null = null;await executeVaultMutation(async () => {- newItemId = await dbContext.sqliteClient!.items.duplicate(itemId);+ duplicate = await dbContext.sqliteClient!.items.duplicate(item);});// Reload items to show the new duplicateawait loadItems();// Scroll to and briefly highlight the new duplicate so it's clear where it landed- setHighlightedItemId(newItemId);+ const created = duplicate as ItemRef | null;+ setHighlightedItemKey(created ? scopedKey(created.ManifestId, created.Id) : null);}, [dbContext.sqliteClient, executeVaultMutation, loadItems]);/**@@ -542,26 +526,26 @@ export default function ItemsScreen(): React.ReactNode {* rendered, then clear the highlight after a short moment.*/useEffect(() => {- if (!highlightedItemId) {+ if (!highlightedItemKey) {return;}- const index = sortedItems.findIndex(itm => itm.Id === highlightedItemId);+ const index = sortedItems.findIndex(itm => scopedKey(itm.ManifestId, itm.Id) === highlightedItemKey);if (index >= 0) {flatListRef.current?.scrollToIndex({ index, viewPosition: 0.5, animated: true });}- const timer = setTimeout(() => setHighlightedItemId(null), 2000);+ const timer = setTimeout(() => setHighlightedItemKey(null), 2000);return (): void => clearTimeout(timer);- }, [highlightedItemId, sortedItems]);+ }, [highlightedItemKey, 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.*/- const handleFolderClick = useCallback((folderId: string) => {+ const handleFolderClick = useCallback((folder: FolderRef) => {navigate(() => {- router.push(`/(tabs)/items/folder/${folderId}?filter=${encodeURIComponent(filterType)}` as '/(tabs)/items/folder/[id]');+ router.push(folderRoute(folder, filterType));});}, [router, navigate, filterType]);@@ -585,9 +569,9 @@ export default function ItemsScreen(): React.ReactNode {if (trimmedQuery) {const isUrl = /^https?:\/\//i.test(trimmedQuery);const queryParam = isUrl ? 'itemUrl' : 'itemName';- router.push(`/(tabs)/items/add-edit?itemType=${itemType}&${queryParam}=${encodeURIComponent(trimmedQuery)}`);+ router.push(`/(tabs)/items/add?itemType=${itemType}&${queryParam}=${encodeURIComponent(trimmedQuery)}`);} else {- router.push(`/(tabs)/items/add-edit?itemType=${itemType}`);+ router.push(`/(tabs)/items/add?itemType=${itemType}`);}HapticsUtility.impact();});@@ -822,9 +806,9 @@ export default function ItemsScreen(): React.ReactNode {<View style={styles.folderPillsContainer}>{foldersWithCounts.map((folder) => (<FolderPill- key={folder.id}+ key={scopedKey(folder.manifestId, folder.id)}folder={folder}- onPress={() => handleFolderClick(folder.id)}+ onPress={() => handleFolderClick({ Id: folder.id, ManifestId: folder.manifestId })}/>))}<TouchableOpacity@@ -953,7 +937,7 @@ export default function ItemsScreen(): React.ReactNode {ref={flatListRef}testID="items-list"data={isLoadingItems ? Array(4).fill(null) : sortedItems}- keyExtractor={(itm, index) => itm?.Id ?? `skeleton-${index}`}+ keyExtractor={(itm, index) => itm ? scopedKey(itm.ManifestId, itm.Id) : `skeleton-${index}`}keyboardShouldPersistTaps='handled'onScroll={Animated.event([{ nativeEvent: { contentOffset: { y: scrollY } } }],@@ -982,7 +966,7 @@ export default function ItemsScreen(): React.ReactNode {isLoadingItems ? (<SkeletonLoader count={1} height={60} parts={2} />) : (- <ItemCard item={itm} onItemDelete={onItemDelete} onItemDuplicate={onItemDuplicate} showFolderPath={!!searchQuery} isHighlighted={itm.Id === highlightedItemId} />+ <ItemCard item={itm} onItemDelete={onItemDelete} onItemDuplicate={onItemDuplicate} showFolderPath={!!searchQuery} isHighlighted={scopedKey(itm.ManifestId, itm.Id) === highlightedItemKey} />)}ListEmptyComponent={renderEmptyComponent() as React.ReactElement}diff --git a/apps/mobile-app/components/folders/FolderSelectorModal.tsx b/apps/mobile-app/components/folders/FolderSelectorModal.tsxindex cd19a4f65..92a3152b1 100644--- a/apps/mobile-app/components/folders/FolderSelectorModal.tsx+++ b/apps/mobile-app/components/folders/FolderSelectorModal.tsx@@ -9,25 +9,19 @@ import {ScrollView,} from 'react-native';-import { isSharedFolder } from '@aliasvault/client/items/FolderUtils';+import { scopedKey } from '@aliasvault/client/database/ItemRef';+import { buildFolderTree, getFolderIdPath, isSharedFolder, type FolderTreeNode } from '@aliasvault/client/items/FolderUtils';import { useColors } from '@/hooks/useColorScheme';import { ModalWrapper } from '@/components/common/ModalWrapper';import { FolderIcon } from '@/components/folders/FolderIcon';-import type { Folder } from '@aliasvault/client/database/repositories/FolderRepository';--type FolderTreeNode = Folder & {- children: FolderTreeNode[];- depth: number;- path: string[];- indentedName: string;-};+import type { Folder, FolderRef } from '@aliasvault/client/database/repositories/FolderRepository';interface IFolderSelectorModalProps {folders: Folder[];- selectedFolderId: string | null | undefined;+ selectedFolder: FolderRef | null | undefined;personalManifestId: string | null;- onFolderChange: (folderId: string | null) => void;+ onFolderChange: (folder: FolderRef | null) => void;isOpen: boolean;onClose: () => void;}@@ -40,7 +34,7 @@ interface IFolderSelectorModalProps {*/export const FolderSelectorModal: React.FC<IFolderSelectorModalProps> = ({folders,- selectedFolderId,+ selectedFolder,personalManifestId,onFolderChange,isOpen,@@ -50,97 +44,19 @@ export const FolderSelectorModal: React.FC<IFolderSelectorModalProps> = ({const colors = useColors();const [expandedFolders, setExpandedFolders] = useState<Set<string>>(new Set());- /**- * Build a hierarchical tree from flat array of folders.- */- const buildFolderTree = useCallback((folders: Folder[]): FolderTreeNode[] => {- const folderMap = new Map<string, FolderTreeNode>();-- // Initialize all folders as tree nodes- folders.forEach(folder => {- folderMap.set(folder.Id, {- ...folder,- children: [],- depth: 0,- path: [],- indentedName: folder.Name,- });- });-- // Build the tree structure- const rootFolders: FolderTreeNode[] = [];-- folders.forEach(folder => {- const node = folderMap.get(folder.Id)!;-- if (!folder.ParentFolderId) {- // Root folder- node.depth = 0;- node.path = [folder.Id];- node.indentedName = folder.Name;- rootFolders.push(node);- } else {- // Child folder- const parent = folderMap.get(folder.ParentFolderId);- if (parent) {- node.depth = parent.depth + 1;- node.path = [...parent.path, folder.Id];- node.indentedName = ' '.repeat(node.depth) + folder.Name;- parent.children.push(node);- } else {- // Parent not found - treat as root- node.depth = 0;- node.path = [folder.Id];- node.indentedName = folder.Name;- rootFolders.push(node);- }- }- });-- // Sort folders by Weight and Name- const sortFolders = (nodes: FolderTreeNode[]): void => {- nodes.sort((a, b) => {- if (a.Weight !== b.Weight) {- return (a.Weight || 0) - (b.Weight || 0);- }- return a.Name.localeCompare(b.Name);- });- nodes.forEach(node => sortFolders(node.children));- };-- sortFolders(rootFolders);- return rootFolders;- }, []);-- /**- * Get folder ID path from root to specified folder.- */- const getFolderIdPath = useCallback((folderId: string, folders: Folder[]): string[] => {- const path: string[] = [];- let currentId: string | null = folderId;- let iterations = 0;-- while (currentId && iterations < 5) {- const folder = folders.find(f => f.Id === currentId);- if (!folder) break;- path.unshift(folder.Id);- currentId = folder.ParentFolderId || null;- iterations++;- }-- return path;- }, []);+ const selectedFolderId = selectedFolder?.Id ?? null;+ const selectedManifestId = selectedFolder?.ManifestId ?? null;/*** Toggle folder expand/collapse.*/- const toggleFolder = useCallback((folderId: string): void => {+ const toggleFolder = useCallback((folderKey: string): void => {setExpandedFolders(prev => {const next = new Set(prev);- if (next.has(folderId)) {- next.delete(folderId);+ if (next.has(folderKey)) {+ next.delete(folderKey);} else {- next.add(folderId);+ next.add(folderKey);}return next;});@@ -150,24 +66,24 @@ export const FolderSelectorModal: React.FC<IFolderSelectorModalProps> = ({* Auto-expand folders when selected folder changes.*/useEffect(() => {- if (selectedFolderId && folders.length > 0) {- const fullPath = getFolderIdPath(selectedFolderId, folders);+ if (selectedFolderId && selectedManifestId && folders.length > 0) {+ const fullPath = getFolderIdPath({ Id: selectedFolderId, ManifestId: selectedManifestId }, folders);if (fullPath.length > 0) {// Expand all folders in the path including the selected folder- setExpandedFolders(new Set(fullPath));+ setExpandedFolders(new Set(fullPath.map(id => scopedKey(selectedManifestId, id))));}} else {setExpandedFolders(new Set());}- }, [selectedFolderId, folders, getFolderIdPath]);+ }, [selectedFolderId, selectedManifestId, folders]);- const folderTree = useMemo(() => buildFolderTree(folders), [folders, buildFolderTree]);+ const folderTree = useMemo(() => buildFolderTree(folders), [folders]);/*** Handle folder selection.*/- const handleSelectFolder = useCallback((folderId: string | null): void => {- onFolderChange(folderId);+ const handleSelectFolder = useCallback((folder: FolderRef | null): void => {+ onFolderChange(folder);onClose();}, [onFolderChange, onClose]);@@ -233,18 +149,19 @@ export const FolderSelectorModal: React.FC<IFolderSelectorModalProps> = ({* Recursively render folder tree node.*/const renderFolderNode = useCallback((node: FolderTreeNode, depth: number = 0): React.ReactNode => {- const isExpanded = expandedFolders.has(node.Id);+ const nodeKey = scopedKey(node.ManifestId, node.Id);+ const isExpanded = expandedFolders.has(nodeKey);const hasChildren = node.children.length > 0;- const isSelected = selectedFolderId === node.Id;+ const isSelected = selectedFolderId === node.Id && selectedManifestId === node.ManifestId;return (- <View key={node.Id}>+ <View key={nodeKey}><TouchableOpacitystyle={[styles.folderOption,isSelected && styles.folderOptionActive,]}- onPress={() => handleSelectFolder(node.Id)}+ onPress={() => handleSelectFolder({ Id: node.Id, ManifestId: node.ManifestId })}activeOpacity={0.7}>{/* Indentation */}@@ -256,7 +173,7 @@ export const FolderSelectorModal: React.FC<IFolderSelectorModalProps> = ({<TouchableOpacityonPress={(e) => {e.stopPropagation();- toggleFolder(node.Id);+ toggleFolder(nodeKey);}}style={styles.chevronButton}hitSlop={{ top: 10, bottom: 10, left: 10, right: 10 }}@@ -308,7 +225,7 @@ export const FolderSelectorModal: React.FC<IFolderSelectorModalProps> = ({)}</View>);- }, [expandedFolders, selectedFolderId, personalManifestId, handleSelectFolder, toggleFolder, colors, styles]);+ }, [expandedFolders, selectedFolderId, selectedManifestId, personalManifestId, handleSelectFolder, toggleFolder, colors, styles]);const modalContent = (<View style={styles.modalContainer}>diff --git a/apps/mobile-app/app/(tabs)/items/add-edit.tsx b/apps/mobile-app/components/items/AddEditItemScreen.tsxsimilarity index 94%rename from apps/mobile-app/app/(tabs)/items/add-edit.tsxrename to apps/mobile-app/components/items/AddEditItemScreen.tsxindex 68cda96ea..d23e8cc4e 100644--- a/apps/mobile-app/app/(tabs)/items/add-edit.tsx+++ b/apps/mobile-app/components/items/AddEditItemScreen.tsx@@ -1,8 +1,9 @@import { Buffer } from 'buffer';+import { manifestForItemIn, type ItemRef } from '@aliasvault/client/database/ItemRef';import * as RustCore from '@aliasvault/client/rust/RustCore';import { IdentityHelperUtils } from '@aliasvault/models/identity';-import { ItemTypes, getSystemFieldsForItemType, getOptionalFieldsForItemType, isFieldShownByDefault, getSystemField, fieldAppliesToType, FieldCategories, FieldTypes } from '@aliasvault/models/vault';+import { ItemTypes, isItemType, getSystemFieldsForItemType, getOptionalFieldsForItemType, isFieldShownByDefault, getSystemField, fieldAppliesToType, FieldCategories, FieldTypes } from '@aliasvault/models/vault';import MaterialIcons from '@expo/vector-icons/MaterialIcons';import * as Haptics from 'expo-haptics';import { Stack, useLocalSearchParams, useNavigation, useRouter } from 'expo-router';@@ -13,8 +14,9 @@ import { StyleSheet, View, Keyboard, Platform, ScrollView, KeyboardAvoidingView,import Toast from 'react-native-toast-message';import type { DisplayItem } from '@/utils/DisplayItem';-import emitter from '@/utils/EventEmitter';+import emitter, { type ItemChangedEvent } from '@/utils/EventEmitter';import { HapticsUtility } from '@/utils/HapticsUtility';+import { itemRoute } from '@/utils/ItemRoute';import { extractServiceNameFromUrl, sanitizeServiceUrl } from '@/utils/UrlUtility';import { useColors } from '@/hooks/useColorScheme';@@ -47,9 +49,6 @@ import type { Identity } from '@aliasvault/models/identity';import type { Attachment, Item, ItemField, TotpCode, ItemType, FieldType, PasswordSettings } from '@aliasvault/models/vault';import type { FaviconExtractModel } from '@aliasvault/models/webapi';-// Valid item types from the shared model-const VALID_ITEM_TYPES: ItemType[] = [ItemTypes.Login, ItemTypes.Alias, ItemTypes.CreditCard, ItemTypes.Note];-// Default item type for new itemsconst DEFAULT_ITEM_TYPE: ItemType = ItemTypes.Login;@@ -59,16 +58,21 @@ const DEFAULT_ITEM_TYPE: ItemType = ItemTypes.Login;const isMaskedFieldType = (fieldType: FieldType): boolean =>fieldType === FieldTypes.Password || fieldType === FieldTypes.Hidden;+type AddEditItemScreenProps = {+ /** The item to edit, absent when creating one. */+ editRef?: ItemRef;+};+/*** Add or edit an item screen.*/-export default function AddEditItemScreen(): React.ReactNode {- const { id, itemUrl, itemName, itemType: itemTypeParam, folderId: folderIdParam } = useLocalSearchParams<{- id: string;+export default function AddEditItemScreen({ editRef }: AddEditItemScreenProps): React.ReactNode {+ const { itemUrl, itemName, itemType: itemTypeParam, folderId: folderIdParam, folderManifestId: folderManifestIdParam } = useLocalSearchParams<{itemUrl?: string;itemName?: string;itemType?: string;folderId?: string;+ folderManifestId?: string;}>();const router = useRouter();const colors = useColors();@@ -85,7 +89,6 @@ export default function AddEditItemScreen(): React.ReactNode {const [isSaveDisabled, setIsSaveDisabled] = useState(false);const [attachments, setAttachments] = useState<Omit<Attachment, 'Blob'>[]>([]);const [originalAttachmentIds, setOriginalAttachmentIds] = useState<string[]>([]);- // The bytes of newly picked attachments by id, kept out of state until save.const attachmentBlobsRef = useRef(new Map<string, Uint8Array>());const [totpCodes, setTotpCodes] = useState<TotpCode[]>([]);const [originalTotpCodeIds, setOriginalTotpCodeIds] = useState<string[]>([]);@@ -95,35 +98,17 @@ export default function AddEditItemScreen(): React.ReactNode {const [hasUnsavedChanges, setHasUnsavedChanges] = useState(false);const [showDeleteConfirm, setShowDeleteConfirm] = useState(false);const [showDiscardConfirm, setShowDiscardConfirm] = useState(false);- // Store the pending navigation action when usePreventRemove triggersconst [pendingNavigationAction, setPendingNavigationAction] = useState<NavigationAction | null>(null);-- // Item stateconst [item, setItem] = useState<DisplayItem | null>(null);-- // Form state for dynamic fields - key is FieldKey, value is the field value+ const [personalManifestId, setPersonalManifestId] = useState<string | null>(null);const [fieldValues, setFieldValues] = useState<Record<string, string | string[]>>({});-- // Custom field definitions (temporary until saved)const [customFields, setCustomFields] = useState<CustomFieldDefinition[]>([]);-- // UI visibility stateconst [show2FA, setShow2FA] = useState(false);const [showAttachments, setShowAttachments] = useState(false);-- // Folder stateconst [folders, setFolders] = useState<Folder[]>([]);-- // Track manually added optional fieldsconst [manuallyAddedFields, setManuallyAddedFields] = useState<Set<string>>(new Set());-- // Track fields that had values initially (edit mode)const [initiallyVisibleFields, setInitiallyVisibleFields] = useState<Set<string>>(new Set());-- // Track if alias was already auto-generatedconst aliasGeneratedRef = useRef(false);-- // Track last generated values to avoid overwriting manual entriesconst [lastGeneratedValues, setLastGeneratedValues] = useState<{username: string | null;password: string | null;@@ -133,10 +118,7 @@ export default function AddEditItemScreen(): React.ReactNode {// 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.- */- const isEditMode = id !== undefined && id.length > 0;+ const isEditMode = editRef !== undefined;/*** Get all applicable system fields for the current item type.@@ -415,7 +397,7 @@ export default function AddEditItemScreen(): React.ReactNode {*/const loadExistingItem = useCallback(async (): Promise<void> => {try {- const existingItem = await dbContext.sqliteClient!.items.getById(id);+ const existingItem = editRef ? await dbContext.sqliteClient!.items.getById(editRef) : null;if (existingItem) {setItem(existingItem);@@ -454,7 +436,7 @@ export default function AddEditItemScreen(): React.ReactNode {setInitiallyVisibleFields(fieldsWithValues);// Load attachments for this item- const itemAttachments = await dbContext.sqliteClient!.items.getAttachmentsForItem(id);+ const itemAttachments = await dbContext.sqliteClient!.items.getAttachmentsForItem(existingItem);// A saved attachment is only ever kept or removed on save, so its bytes are not needed here.setAttachments(itemAttachments.map(({ Blob: _blob, ...attachment }) => attachment));setOriginalAttachmentIds(itemAttachments.map(a => a.Id));@@ -463,7 +445,7 @@ export default function AddEditItemScreen(): React.ReactNode {}// Load TOTP codes for this item- const itemTotpCodes = await dbContext.sqliteClient!.items.getTotpCodesForItem(id);+ const itemTotpCodes = await dbContext.sqliteClient!.items.getTotpCodesForItem(existingItem);setTotpCodes(itemTotpCodes);setOriginalTotpCodeIds(itemTotpCodes.map(tc => tc.Id));if (itemTotpCodes.length > 0) {@@ -471,7 +453,7 @@ export default function AddEditItemScreen(): React.ReactNode {}// Load passkeys for this item- const itemPasskeys = await dbContext.sqliteClient!.passkeys.getByItemId(id);+ const itemPasskeys = await dbContext.sqliteClient!.passkeys.getByItemId(existingItem);setPasskeyIds(itemPasskeys.map(pk => pk.Id));}} catch (err) {@@ -482,7 +464,7 @@ export default function AddEditItemScreen(): React.ReactNode {text2: t('common.errors.unknownErrorTryAgain')});}- }, [id, dbContext.sqliteClient, t]);+ }, [editRef, dbContext.sqliteClient, t]);/*** On mount, load an existing item if we're in edit mode, or initialize new item.@@ -498,6 +480,7 @@ export default function AddEditItemScreen(): React.ReactNode {try {const loadedFolders = await dbContext.sqliteClient!.folders.getAll();setFolders(loadedFolders);+ setPersonalManifestId(await dbContext.sqliteClient!.getPersonalManifestId());} catch (err) {console.error('Error loading folders:', err);}@@ -534,16 +517,15 @@ export default function AddEditItemScreen(): React.ReactNode {}// Determine effective type from URL param or default- const effectiveType: ItemType = (itemTypeParam && VALID_ITEM_TYPES.includes(itemTypeParam as ItemType))- ? itemTypeParam as ItemType- : DEFAULT_ITEM_TYPE;+ const effectiveType: ItemType = isItemType(itemTypeParam) ? itemTypeParam : DEFAULT_ITEM_TYPE;+ const startsInFolder = Boolean(folderIdParam && folderManifestIdParam);const newItem: Item = {Id: crypto.randomUUID(),- ManifestId: '',+ ManifestId: manifestForItemIn(startsInFolder ? { ManifestId: folderManifestIdParam! } : null, await dbContext.sqliteClient!.getPersonalManifestId()),Name: serviceName,ItemType: effectiveType,- FolderId: folderIdParam || null,+ FolderId: startsInFolder ? folderIdParam! : null,Fields: [],CreatedAt: new Date().toISOString(),UpdatedAt: new Date().toISOString()@@ -567,7 +549,7 @@ export default function AddEditItemScreen(): React.ReactNode {};initializeComponent();- }, [id, isEditMode, itemUrl, itemName, itemTypeParam, folderIdParam, loadExistingItem, router, t, dbContext.sqliteClient]);+ }, [isEditMode, itemUrl, itemName, itemTypeParam, folderIdParam, folderManifestIdParam, loadExistingItem, router, t, dbContext.sqliteClient]);/*** Auto-generate alias when alias fields are shown by default in create mode.@@ -829,7 +811,7 @@ export default function AddEditItemScreen(): React.ReactNode {// Build the item to savelet itemToSave: Item = {...item,- Id: isEditMode ? id : crypto.randomUUID(),+ Id: editRef ? editRef.Id : crypto.randomUUID(),Name: item.Name || t('items.untitled'),Fields: fields,UpdatedAt: new Date().toISOString()@@ -875,23 +857,23 @@ export default function AddEditItemScreen(): React.ReactNode {* Navigate immediately after local save; sync happens in background via ServerSyncIndicator.*/try {+ let savedRef: ItemRef | null = null;await executeVaultMutation(async () => {- if (isEditMode) {- await dbContext.sqliteClient!.items.update(itemToSave, originalAttachmentIds, attachmentsToSave, originalTotpCodeIds, totpCodes);-- // Delete passkeys if marked for deletion- if (passkeyIdsMarkedForDeletion.length > 0) {- for (const passkeyId of passkeyIdsMarkedForDeletion) {- await dbContext.sqliteClient!.passkeys.deleteById(passkeyId);- }+ if (editRef) {+ // Passkeys are deleted first, while they still sit in the manifest the item is in now.+ for (const passkeyId of passkeyIdsMarkedForDeletion) {+ await dbContext.sqliteClient!.passkeys.deleteById(passkeyId, editRef.ManifestId);}++ savedRef = await dbContext.sqliteClient!.items.update(editRef, itemToSave, originalAttachmentIds, attachmentsToSave, originalTotpCodeIds, totpCodes) ?? editRef;} else {- await dbContext.sqliteClient!.items.create(itemToSave, attachmentsToSave, totpCodes);+ savedRef = await dbContext.sqliteClient!.items.create(itemToSave, attachmentsToSave, totpCodes);}});+ const currentRef = savedRef as ItemRef | null;// Emit event to notify list and detail views to refresh- emitter.emit('credentialChanged', itemToSave.Id);+ emitter.emit('itemChanged', { previous: editRef ?? currentRef, current: currentRef ?? undefined } as ItemChangedEvent);setHasUnsavedChanges(false);setIsSaving(false);setIsSaveDisabled(false);@@ -918,7 +900,9 @@ export default function AddEditItemScreen(): React.ReactNode {text1: t('items.toasts.itemCreated'),position: 'bottom'});- router.push(`/items/${itemToSave.Id}`);+ if (currentRef) {+ router.push(itemRoute(currentRef));+ }}}, 100);}@@ -933,13 +917,13 @@ export default function AddEditItemScreen(): React.ReactNode {setIsSaving(false);setIsSaveDisabled(false);}- }, [isEditMode, id, itemUrl, router, executeVaultMutation, dbContext.sqliteClient, webApi, isSaveDisabled, item, fieldValues, applicableSystemFields, customFields, t, originalAttachmentIds, attachments, originalTotpCodeIds, totpCodes, passkeyIdsMarkedForDeletion]);+ }, [isEditMode, editRef, itemUrl, router, executeVaultMutation, dbContext.sqliteClient, webApi, isSaveDisabled, item, fieldValues, applicableSystemFields, customFields, t, originalAttachmentIds, attachments, originalTotpCodeIds, totpCodes, passkeyIdsMarkedForDeletion]);/*** Handle the delete button press.*/const handleDelete = (): void => {- if (!id) {+ if (!editRef) {return;}@@ -951,15 +935,15 @@ export default function AddEditItemScreen(): React.ReactNode {* Confirm and execute item deletion.*/const confirmDelete = useCallback(async (): Promise<void> => {- if (!id) {+ if (!editRef) {return;}await executeVaultMutation(async () => {- await dbContext.sqliteClient!.items.trash(id);+ await dbContext.sqliteClient!.items.trash(editRef);});- emitter.emit('credentialChanged', id);+ emitter.emit('itemChanged', { previous: editRef } as ItemChangedEvent);// Haptic feedback for delete action (warning type for destructive action)HapticsUtility.notification(Haptics.NotificationFeedbackType.Warning);@@ -975,7 +959,7 @@ export default function AddEditItemScreen(): React.ReactNode {setShowDeleteConfirm(false);router.back();router.back();- }, [id, executeVaultMutation, dbContext.sqliteClient, t, router]);+ }, [editRef, executeVaultMutation, dbContext.sqliteClient, t, router]);/*** Handle cancel button press.@@ -1400,9 +1384,9 @@ export default function AddEditItemScreen(): React.ReactNode {setHasUnsavedChanges(true);}}folders={folders}- selectedFolderId={item.FolderId}- onFolderChange={(folderId) => {- setItem(prev => prev ? { ...prev, FolderId: folderId } : prev);+ selectedFolder={item.FolderId ? { Id: item.FolderId, ManifestId: item.ManifestId } : null}+ onFolderChange={(folder) => {+ setItem(prev => prev ? { ...prev, FolderId: folder?.Id ?? null, ManifestId: manifestForItemIn(folder, personalManifestId) } : prev);setHasUnsavedChanges(true);}}/>diff --git a/apps/mobile-app/components/items/ItemFormPage.tsx b/apps/mobile-app/components/items/ItemFormPage.tsxnew file mode 100644index 000000000..fcd14cc9b--- /dev/null+++ b/apps/mobile-app/components/items/ItemFormPage.tsx@@ -0,0 +1,29 @@+import type { ItemRef } from '@aliasvault/client/database/ItemRef';+import React from 'react';+import { View, StyleSheet } from 'react-native';++import AddEditItemScreen from '@/components/items/AddEditItemScreen';++type ItemFormPageProps = {+ /** The item to edit, absent when creating one. */+ editRef?: ItemRef;+};++/**+ * The add/edit item form as a page.+ */+export const ItemFormPage: React.FC<ItemFormPageProps> = ({ editRef }) => {+ return (+ <View style={styles.container}>+ <AddEditItemScreen editRef={editRef} />+ </View>+ );+};++const styles = StyleSheet.create({+ container: {+ flex: 1,+ paddingBottom: 60,+ paddingTop: 40,+ },+});diff --git a/apps/mobile-app/components/items/ServiceUrlNotice.tsx b/apps/mobile-app/components/items/ServiceUrlNotice.tsxindex b543beb3a..67cd89a4e 100644--- a/apps/mobile-app/components/items/ServiceUrlNotice.tsx+++ b/apps/mobile-app/components/items/ServiceUrlNotice.tsx@@ -17,7 +17,7 @@ interface IServiceUrlNoticeProps {/*** A dismissable notice that appears when a service URL is provided via deep link.- * Clicking the notice navigates to the add-edit page with the service URL.+ * Clicking the notice navigates to the add item page with the service URL.*/export function ServiceUrlNotice({ serviceUrl, onDismiss }: IServiceUrlNoticeProps): React.ReactNode {const router = useRouter();@@ -26,11 +26,11 @@ export function ServiceUrlNotice({ serviceUrl, onDismiss }: IServiceUrlNoticeProconst serviceName = extractServiceNameFromUrl(serviceUrl);/**- * Handle press on the notice to navigate to add-edit page+ * Handle press on the notice to navigate to the add item page*/const handlePress = (): void => {router.push({- pathname: '/(tabs)/items/add-edit',+ pathname: '/(tabs)/items/add',params: { serviceUrl }});};diff --git a/apps/mobile-app/components/items/details/AttachmentSection.tsx b/apps/mobile-app/components/items/details/AttachmentSection.tsxindex c111d02d2..629f896ea 100644--- a/apps/mobile-app/components/items/details/AttachmentSection.tsx+++ b/apps/mobile-app/components/items/details/AttachmentSection.tsx@@ -1,11 +1,10 @@import { MaterialIcons } from '@expo/vector-icons';import { Directory, Paths } from 'expo-file-system';-import React, { useState, useEffect, useCallback, useRef } from 'react';+import React, { useState, useEffect, useRef } from 'react';import { useTranslation } from 'react-i18next';import { View, StyleSheet, TouchableOpacity } from 'react-native';import type { Item, Attachment } from '@aliasvault/models/vault';-import emitter, { type ItemChangedEvent } from '@/utils/EventEmitter';import { getFileForFilename } from '@/utils/FileUtility';import { useAttachmentViewer } from '@/hooks/useAttachmentViewer';@@ -62,36 +61,27 @@ export const AttachmentSection: React.FC<AttachmentSectionProps> = ({ item }): R}};- /**- * Load the attachments.- */- const loadAttachments = useCallback(async (): Promise<void> => {- if (!dbContext?.sqliteClient) {- return;- }-- try {- const attachmentList = await dbContext.sqliteClient.items.getAttachmentsForItem({ Id: item.Id, ManifestId: item.ManifestId });- blobsRef.current = new Map(attachmentList.map(attachment => [attachment.Id, attachment.Blob]));- setAttachments(attachmentList.map(({ Blob: _blob, ...attachment }) => attachment));- } catch (error) {- console.error('Error loading attachments:', error);- }- }, [item.Id, item.ManifestId, dbContext?.sqliteClient]);-- useEffect((): (() => void) => {- loadAttachments();-- const itemChangedSub = emitter.addListener('credentialChanged', async (change?: ItemChangedEvent) => {- if (change && change.previous.Id === item.Id && change.previous.ManifestId === item.ManifestId) {- await loadAttachments();+ useEffect(() => {+ /**+ * Load the attachments.+ */+ const loadAttachments = async (): Promise<void> => {+ if (!dbContext?.sqliteClient) {+ return;}- });- return () => {- itemChangedSub.remove();+ try {+ const attachmentList = await dbContext.sqliteClient.items.getAttachmentsForItem({ Id: item.Id, ManifestId: item.ManifestId });+ blobsRef.current = new Map(attachmentList.map(attachment => [attachment.Id, attachment.Blob]));+ setAttachments(attachmentList.map(({ Blob: _blob, ...attachment }) => attachment));+ } catch (error) {+ console.error('Error loading attachments:', error);+ }};- }, [item.Id, item.ManifestId, dbContext?.sqliteClient, loadAttachments]);++ // The details screen hands over a fresh item after every edit, which reloads the attachments too.+ loadAttachments();+ }, [item, dbContext?.sqliteClient]);if (attachments.length === 0) {return null;diff --git a/apps/mobile-app/utils/EventEmitter.ts b/apps/mobile-app/utils/EventEmitter.tsindex f74a41cba..4805c1278 100644--- a/apps/mobile-app/utils/EventEmitter.ts+++ b/apps/mobile-app/utils/EventEmitter.ts@@ -1,5 +1,12 @@import { EventEmitter } from 'fbemitter';+import type { ItemRef } from '@aliasvault/client/database/ItemRef';++/**+ * Payload of `itemChanged` for one item: where it was, and where it is now (absent once it is trashed).+ */+export type ItemChangedEvent = { previous: ItemRef; current?: ItemRef };+/*** Create a new event emitter instance which is used by the app* to communicate between components.diff --git a/apps/mobile-app/utils/FolderRoute.ts b/apps/mobile-app/utils/FolderRoute.tsnew file mode 100644index 000000000..395cccd69--- /dev/null+++ b/apps/mobile-app/utils/FolderRoute.ts@@ -0,0 +1,12 @@+import type { FolderRef } from '@aliasvault/client/database/repositories/FolderRepository';++/**+ * The route of a folder screen.+ * @param folder - The folder to open+ * @param filter - The active item filter to carry over, when any+ * @returns The route, typed as the folder screen's+ */+export function folderRoute(folder: FolderRef, filter?: string): '/(tabs)/items/folder/[manifestId]/[id]' {+ const filterParam = filter ? `?filter=${encodeURIComponent(filter)}` : '';+ return `/(tabs)/items/folder/${encodeURIComponent(folder.ManifestId)}/${folder.Id}${filterParam}` as '/(tabs)/items/folder/[manifestId]/[id]';+}diff --git a/apps/mobile-app/utils/ItemRoute.ts b/apps/mobile-app/utils/ItemRoute.tsnew file mode 100644index 000000000..2f898492f--- /dev/null+++ b/apps/mobile-app/utils/ItemRoute.ts@@ -0,0 +1,19 @@+import type { ItemRef } from '@aliasvault/client/database/ItemRef';++/**+ * The route of an item's detail screen. An item id alone does not name one item, so its manifest is a path segment too.+ * @param item - The item to open+ * @returns The route, typed as the item screen's+ */+export function itemRoute(item: ItemRef): '/(tabs)/items/[manifestId]/[id]' {+ return `/(tabs)/items/${encodeURIComponent(item.ManifestId)}/${item.Id}` as '/(tabs)/items/[manifestId]/[id]';+}++/**+ * The route that edits an existing item.+ * @param item - The item to edit+ * @returns The route, typed as the edit screen's+ */+export function itemEditRoute(item: ItemRef): '/(tabs)/items/[manifestId]/[id]/edit' {+ return `/(tabs)/items/${encodeURIComponent(item.ManifestId)}/${item.Id}/edit` as '/(tabs)/items/[manifestId]/[id]/edit';+}diff --git a/core/models/src/vault/ItemMethods.ts b/core/models/src/vault/ItemMethods.tsindex 62e94d42d..07091fed1 100644--- a/core/models/src/vault/ItemMethods.ts+++ b/core/models/src/vault/ItemMethods.ts@@ -1,5 +1,5 @@-import type { Item, ItemField, FieldType } from './Item';-import { FieldTypes } from './Item';+import type { Item, ItemField, ItemType, FieldType } from './Item';+import { FieldTypes, ItemTypes } from './Item';import type { Credential } from './Credential';import { FieldKey } from './FieldKey';import { FieldCategories, getSystemField } from './SystemFieldRegistry';@@ -8,6 +8,13 @@ import { FieldCategories, getSystemField } from './SystemFieldRegistry';* Helper functions for working with Item model*/+/**+ * Whether a value, such as a route param, names a known item type+ */+export function isItemType(value: string | null | undefined): value is ItemType {+ return typeof value === 'string' && (Object.values(ItemTypes) as string[]).includes(value);+}+/*** Get a single field value by FieldKey*/