Skip to content

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

Update subfolder navigation performance by handing over already retrieved data (#2159)

Leendert de Borsteb164d4b2411
diff --git a/apps/mobile-app/app/(tabs)/items/folder/[id].tsx b/apps/mobile-app/app/(tabs)/items/folder/[id].tsx
index c59915175..c7bc90d9f 100644
--- a/apps/mobile-app/app/(tabs)/items/folder/[id].tsx
+++ b/apps/mobile-app/app/(tabs)/items/folder/[id].tsx
@@ -38,6 +38,7 @@ import { useDb } from '@/context/DbContext';
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 { CredentialSortOrder } from '@aliasvault/client/database/repositories/SettingsRepository';
import type { ItemType } from '@aliasvault/models/vault';
@@ -77,12 +78,11 @@ export default function FolderViewScreen(): React.ReactNode {
const flatListRef = useRef<FlatList<DisplayItem | null>>(null);
const [itemsList, setItemsList] = useState<DisplayItem[]>([]);
- const [allItemsInVault, setAllItemsInVault] = useState<DisplayItem[]>([]);
+ const [itemSummaries, setItemSummaries] = useState<ItemSummary[]>([]);
const [folder, setFolder] = useState<Folder | null>(null);
const [canCreateSubfolder, setCanCreateSubfolder] = useState(false);
const [allFolders, setAllFolders] = useState<Folder[]>([]);
- // No minimum loading delay for folder view since data is already in memory
- const [isLoadingItems, setIsLoadingItems] = useState(false);
+ const [isLoadingItems, setIsLoadingItems] = useState(true);
const [refreshing, setRefreshing] = useMinDurationLoading(false, 200);
const { executeVaultMutation } = useVaultMutate();
@@ -174,8 +174,8 @@ export default function FolderViewScreen(): React.ReactNode {
return 0;
}
- return getRecursiveItemCount(folderId, allItemsInVault, allFolders);
- }, [folderId, allFolders, allItemsInVault]);
+ return getRecursiveItemCount(folderId, itemSummaries, allFolders);
+ }, [folderId, allFolders, itemSummaries]);
/**
* Direct subfolders of the current folder, with item counts that respect the active
@@ -186,7 +186,7 @@ export default function FolderViewScreen(): React.ReactNode {
return [];
}
- const itemsForCount = applyTypeFilter(allItemsInVault, filterType);
+ const itemsForCount = applyTypeFilter(itemSummaries, filterType);
const childFolders = allFolders.filter((f: Folder) => f.ParentFolderId === folderId);
return childFolders.map((f) => ({
@@ -194,26 +194,26 @@ export default function FolderViewScreen(): React.ReactNode {
name: f.Name,
itemCount: getRecursiveItemCount(f.Id, itemsForCount, allFolders),
}));
- }, [folderId, allFolders, allItemsInVault, filterType]);
+ }, [folderId, allFolders, itemSummaries, filterType]);
/**
* Load items in this folder, subfolders, and folder details.
*/
const loadItems = useCallback(async (): Promise<void> => {
if (!folderId) {
+ setIsLoadingItems(false);
return;
}
try {
- const [items, folders, savedSortOrder] = await Promise.all([
- dbContext.sqliteClient!.items.getAll(),
+ const [folderItems, summaries, folders, savedSortOrder] = await Promise.all([
+ dbContext.sqliteClient!.items.getByFolder(folderId),
+ dbContext.sqliteClient!.items.getAllSummaries(),
dbContext.sqliteClient!.folders.getAll(),
dbContext.sqliteClient!.settings.getCredentialsSortOrder()
]);
- // Filter to only items in this folder
- const folderItems = items.filter((item: DisplayItem) => item.FolderId === folderId);
setItemsList(folderItems);
- setAllItemsInVault(items);
+ setItemSummaries(summaries);
// Find this folder
const currentFolder = folders.find((f: Folder) => f.Id === folderId);
@@ -490,21 +490,10 @@ export default function FolderViewScreen(): React.ReactNode {
setShowCreateSubfolderModal(false);
}, [dbContext.sqliteClient, folderId, executeVaultMutation, loadItems]);
- // Header styles (stable, not dependent on colors) - prefixed with _ as styles are inlined in useEffect
- const _headerStyles = StyleSheet.create({
- headerButton: {
- padding: 8,
- },
- headerRightContainer: {
- flexDirection: 'row',
- gap: 4,
- },
- });
-
const paddingTop = Platform.OS === 'ios' ? 56 : 16;
const paddingBottom = Platform.OS === 'ios' ? insets.bottom + 60 : 40;
- const styles = StyleSheet.create({
+ const styles = useMemo(() => StyleSheet.create({
container: {
paddingHorizontal: 0,
},
@@ -665,7 +654,7 @@ export default function FolderViewScreen(): React.ReactNode {
color: colors.textMuted,
fontSize: 14,
},
- });
+ }), [colors, paddingTop, paddingBottom]);
/**
* Render the filter menu as an absolute overlay.
@@ -780,15 +769,16 @@ export default function FolderViewScreen(): React.ReactNode {
};
/**
- * Render the list header with subfolders, filter, sort button, and search.
+ * The list header with subfolders, filter, sort button, and search.
*/
- const renderListHeader = (): React.ReactNode => {
+ const listHeader = useMemo((): React.ReactElement => {
return (
<ThemedView>
{/* Folder breadcrumb navigation */}
<FolderBreadcrumb
folderId={folderId}
excludeCurrentFolder={true}
+ folders={allFolders}
/>
{/* Subfolder pills (shown when not searching) */}
@@ -889,7 +879,7 @@ export default function FolderViewScreen(): React.ReactNode {
</ThemedView>
</ThemedView>
);
- };
+ }, [folderId, allFolders, searchQuery, subfolders, canCreateSubfolder, handleSubfolderClick, showFilterMenu, filteredItems.length, getFilterTitle, toggleSortMenu, styles, colors, t]);
/**
* Render empty state.
@@ -928,7 +918,7 @@ export default function FolderViewScreen(): React.ReactNode {
maxToRenderPerBatch={14}
windowSize={7}
removeClippedSubviews={false}
- ListHeaderComponent={renderListHeader() as React.ReactElement}
+ ListHeaderComponent={listHeader}
onScrollToIndexFailed={({ index, averageItemLength }) => {
flatListRef.current?.scrollToOffset({ offset: index * averageItemLength, animated: true });
}}
diff --git a/apps/mobile-app/components/folders/FolderBreadcrumb.tsx b/apps/mobile-app/components/folders/FolderBreadcrumb.tsx
index 229e3c213..c9c180fbe 100644
--- a/apps/mobile-app/components/folders/FolderBreadcrumb.tsx
+++ b/apps/mobile-app/components/folders/FolderBreadcrumb.tsx
@@ -1,6 +1,6 @@
import MaterialIcons from '@expo/vector-icons/MaterialIcons';
import { useRouter } from 'expo-router';
-import React, { useState, useEffect, useCallback } from 'react';
+import React, { useState, useEffect, useCallback, useMemo } from 'react';
import { useTranslation } from 'react-i18next';
import { View, Text, TouchableOpacity, StyleSheet } from 'react-native';
@@ -8,6 +8,8 @@ import { getFolderIdPath, getFolderPath } from '@aliasvault/client/items/FolderU
import { useColors } from '@/hooks/useColorScheme';
import { useDb } from '@/context/DbContext';
+import type { Folder } from '@aliasvault/client/database/repositories/FolderRepository';
+
type Breadcrumb = {
name: string;
id: string;
@@ -30,6 +32,10 @@ type FolderBreadcrumbProps = {
* Defaults to false.
*/
excludeCurrentFolder?: boolean;
+ /**
+ * The vault's folders, when the caller already holds them to avoid doing a separate query.
+ */
+ folders?: Folder[];
};
/**
@@ -41,45 +47,51 @@ export const FolderBreadcrumb: React.FC<FolderBreadcrumbProps> = ({
folderId,
rootLabel,
excludeCurrentFolder = false,
+ folders,
}) => {
const { t } = useTranslation();
const router = useRouter();
const dbContext = useDb();
const colors = useColors();
- const [breadcrumbs, setBreadcrumbs] = useState<Breadcrumb[]>([]);
+ const [loadedFolders, setLoadedFolders] = useState<Folder[]>([]);
/**
- * Load breadcrumb trail based on current folder.
- * Optionally excludes the current folder (to avoid duplication with page title).
+ * Load the folders this trail is built from, unless the caller already passed them in.
*/
useEffect(() => {
- const loadBreadcrumbs = async () => {
- if (!folderId || !dbContext?.sqliteClient) {
- setBreadcrumbs([]);
+ const loadFolders = async () => {
+ if (folders || !folderId || !dbContext?.sqliteClient) {
return;
}
try {
- const allFolders = await dbContext.sqliteClient.folders.getAll();
- const folderNames = getFolderPath(folderId, allFolders);
- const folderIds = getFolderIdPath(folderId, allFolders);
-
- let fullPath = folderNames.map((name, index) => ({name, id: folderIds[index]}));
-
- // If requested, exclude the current folder from breadcrumbs
- if (excludeCurrentFolder && fullPath.length > 0) {
- fullPath = fullPath.slice(0, -1); // Remove last item (current folder)
- }
-
- setBreadcrumbs(fullPath);
+ setLoadedFolders(await dbContext.sqliteClient.folders.getAll());
} catch (error) {
- console.error('[FolderBreadcrumb] Error building breadcrumbs:', error);
- setBreadcrumbs([]);
+ console.error('[FolderBreadcrumb] Error loading folders:', error);
+ setLoadedFolders([]);
}
};
- loadBreadcrumbs();
- }, [folderId, dbContext?.sqliteClient, excludeCurrentFolder]);
+ loadFolders();
+ }, [folders, folderId, dbContext?.sqliteClient]);
+
+ /**
+ * Build the breadcrumb trail for the current folder.
+ * Optionally excludes the current folder (to avoid duplication with page title).
+ */
+ const breadcrumbs = useMemo((): Breadcrumb[] => {
+ const allFolders = folders ?? loadedFolders;
+ if (!folderId || allFolders.length === 0) {
+ return [];
+ }
+
+ const folderNames = getFolderPath(folderId, allFolders);
+ const folderIds = getFolderIdPath(folderId, allFolders);
+ const fullPath = folderNames.map((name, index) => ({ name, id: folderIds[index] }));
+
+ // If requested, exclude the current folder from breadcrumbs
+ return excludeCurrentFolder ? fullPath.slice(0, -1) : fullPath;
+ }, [folders, loadedFolders, folderId, excludeCurrentFolder]);
/**
* Handle breadcrumb navigation.
diff --git a/apps/mobile-app/utils/DisplayItem.ts b/apps/mobile-app/utils/DisplayItem.ts
index a3e642608..b59e45844 100644
--- a/apps/mobile-app/utils/DisplayItem.ts
+++ b/apps/mobile-app/utils/DisplayItem.ts
@@ -23,13 +23,14 @@ export type DisplayItem<T extends Item = Item> = Omit<T, 'Logo'> & {
/**
* The item repository reads that return items.
*/
-type ItemReads = 'getAll' | 'getById' | 'getArchived' | 'getRecentlyDeleted';
+type ItemReads = 'getAll' | 'getByFolder' | 'getById' | 'getArchived' | 'getRecentlyDeleted';
/**
* The item repository as the app uses it: every item read returns display items.
*/
export type DisplayItemRepository = Omit<AsyncRepository<ItemRepository>, ItemReads> & {
getAll(): Promise<DisplayItem[]>;
+ getByFolder(folderId: string, manifestId?: string): Promise<DisplayItem[]>;
getById(itemId: string, manifestId?: string): Promise<DisplayItem | null>;
getArchived(): Promise<DisplayItem<ItemWithArchivedAt>[]>;
getRecentlyDeleted(): Promise<DisplayItem<ItemWithDeletedAt>[]>;
@@ -41,6 +42,7 @@ export type DisplayItemRepository = Omit<AsyncRepository<ItemRepository>, ItemRe
export function withDisplayItems(repository: AsyncRepository<ItemRepository>): DisplayItemRepository {
const reads: Pick<DisplayItemRepository, ItemReads> = {
getAll: async () => toDisplayItems(await repository.getAll()),
+ getByFolder: async (folderId, manifestId) => toDisplayItems(await repository.getByFolder(folderId, manifestId)),
getById: async (itemId, manifestId) => {
const item = await repository.getById(itemId, manifestId);
return item ? toDisplayItems([item])[0] : null;
diff --git a/core/client/src/database/mappers/ItemMapper.ts b/core/client/src/database/mappers/ItemMapper.ts
index 14babb82f..c50bcc820 100644
--- a/core/client/src/database/mappers/ItemMapper.ts
+++ b/core/client/src/database/mappers/ItemMapper.ts
@@ -36,6 +36,16 @@ export type ItemRow = {
ArchivedAt?: string | null;
}
+/**
+ * An active item as the folder counts need it: its key, its folder and the flags the type filters read.
+ */
+export type ItemSummary = Pick<Item, 'Id' | 'ManifestId' | 'ItemType' | 'FolderId' | 'HasPasskey' | 'HasAttachment' | 'HasTotp'>;
+
+/**
+ * Raw summary row from database query.
+ */
+export type ItemSummaryRow = Pick<ItemRow, 'Id' | 'ManifestId' | 'ItemType' | 'FolderId' | 'HasPasskey' | 'HasAttachment' | 'HasTotp'>;
+
/**
* Raw tag row from database query.
*/
@@ -107,6 +117,23 @@ export class ItemMapper {
));
}
+ /**
+ * Map raw summary rows to ItemSummary objects.
+ * @param rows - Raw summary rows from database
+ * @returns Array of ItemSummary objects
+ */
+ public static mapSummaryRows(rows: ItemSummaryRow[]): ItemSummary[] {
+ return rows.map(row => ({
+ Id: row.Id,
+ ManifestId: row.ManifestId,
+ ItemType: row.ItemType as ItemType,
+ FolderId: row.FolderId,
+ HasPasskey: row.HasPasskey === 1,
+ HasAttachment: row.HasAttachment === 1,
+ HasTotp: row.HasTotp === 1
+ }));
+ }
+
/**
* Map the joined logo columns of a row into the item's logo, or undefined when it has none.
* A row written before the Kind column existed reads as a favicon, which is what it was.
diff --git a/core/client/src/database/queries/ItemQueries.ts b/core/client/src/database/queries/ItemQueries.ts
index 30848d07d..8c995e0f9 100644
--- a/core/client/src/database/queries/ItemQueries.ts
+++ b/core/client/src/database/queries/ItemQueries.ts
@@ -43,6 +43,29 @@ export class ItemQueries {
WHERE i.IsDeleted = 0 AND i.DeletedAt IS NULL AND i.ArchivedAt IS NULL
ORDER BY i.CreatedAt DESC`;
+ /**
+ * Get the active items of one folder, matched on the folder's whole key.
+ */
+ public static readonly GET_BY_FOLDER = `
+ ${ItemQueries.BASE_SELECT}
+ WHERE i.IsDeleted = 0 AND i.DeletedAt IS NULL AND i.ArchivedAt IS NULL AND i.FolderId = ? AND i.ManifestId = ?
+ ORDER BY i.CreatedAt DESC`;
+
+ /**
+ * Get every active item that the folder counts need.
+ */
+ public static readonly GET_ALL_SUMMARIES = `
+ SELECT
+ i.Id,
+ i.ManifestId,
+ i.ItemType,
+ i.FolderId,
+ CASE WHEN EXISTS (SELECT 1 FROM Passkeys pk WHERE pk.ItemId = i.Id AND pk.ManifestId = i.ManifestId AND pk.IsDeleted = 0) THEN 1 ELSE 0 END as HasPasskey,
+ CASE WHEN EXISTS (SELECT 1 FROM Attachments att WHERE att.ItemId = i.Id AND att.ManifestId = i.ManifestId AND att.IsDeleted = 0) THEN 1 ELSE 0 END as HasAttachment,
+ CASE WHEN EXISTS (SELECT 1 FROM TotpCodes tc WHERE tc.ItemId = i.Id AND tc.ManifestId = i.ManifestId AND tc.IsDeleted = 0) THEN 1 ELSE 0 END as HasTotp
+ FROM Items i
+ WHERE i.IsDeleted = 0 AND i.DeletedAt IS NULL AND i.ArchivedAt IS NULL`;
+
/**
* Get all archived items. Trashed items are excluded: an item that is both archived and trashed
* belongs in "Recently Deleted", which is the more urgent of the two states.
diff --git a/core/client/src/database/repositories/ItemRepository.ts b/core/client/src/database/repositories/ItemRepository.ts
index b88ad9a4a..713a26ca2 100644
--- a/core/client/src/database/repositories/ItemRepository.ts
+++ b/core/client/src/database/repositories/ItemRepository.ts
@@ -2,10 +2,10 @@ import { FieldKey, LogoKinds, MAX_FIELD_HISTORY_RECORDS, normalizeTotpAlgorithm,
import { getFolderPath } from '../../items/FolderUtils';
import { selectFaviconTarget, toUrlList } from '../../rust/RustCore';
-import { BaseRepository, type IDatabaseClient } from '../BaseRepository';
+import { BaseRepository, type IDatabaseClient, type SqliteBindValue } from '../BaseRepository';
import { itemKeyBindings, scopedKey, type DraftItem, type ItemRef } from '../ItemRef';
import { FieldMapper, type FieldRow } from '../mappers/FieldMapper';
-import { ItemMapper, type ItemRow, type TagRow, type ItemWithArchivedAt, type ItemWithDeletedAt } from '../mappers/ItemMapper';
+import { ItemMapper, type ItemRow, type ItemSummary, type ItemSummaryRow, type TagRow, type ItemWithArchivedAt, type ItemWithDeletedAt } from '../mappers/ItemMapper';
import {
ItemQueries,
FieldValueQueries,
@@ -89,6 +89,39 @@ export class ItemRepository extends BaseRepository {
return yield* this.hydrateItems(itemRows);
}
+ /**
+ * Fetch the active items of one folder with their dynamic fields and tags.
+ * @param folderId - The ID of the folder to read
+ * @param manifestId - The manifest the folder belongs to, when known
+ * @returns Array of Item objects (empty array if the folder does not exist)
+ */
+ public *getByFolder(folderId: string, manifestId?: string): DbOp<Item[]> {
+ const scope = manifestId ?? (yield* this.resolveRowManifestId('Folders', folderId));
+ if (!scope) {
+ return [];
+ }
+
+ const itemRows = yield* this.selectItemRows(ItemQueries.GET_BY_FOLDER, [folderId, scope]);
+ return yield* this.hydrateItems(itemRows);
+ }
+
+ /**
+ * Fetch every active item as the folder counts need it, without logos, fields or tags.
+ * @returns Array of ItemSummary objects (empty array if Items table doesn't exist yet)
+ */
+ public *getAllSummaries(): DbOp<ItemSummary[]> {
+ try {
+ const rows = yield* this.query<ItemSummaryRow>(ItemQueries.GET_ALL_SUMMARIES);
+ return ItemMapper.mapSummaryRows(rows);
+ } catch (error) {
+ // Items table may not exist in older vault versions - return empty array
+ if (error instanceof Error && error.message.includes('no such table')) {
+ return [];
+ }
+ throw error;
+ }
+ }
+
/**
* Fetch all archived items with their dynamic fields and tags.
* @returns Array of archived Item objects with ArchivedAt (empty array if Items table doesn't exist yet)
@@ -118,11 +151,12 @@ export class ItemRepository extends BaseRepository {
/**
* Run an item SELECT, tolerating a vault whose schema predates the Items table.
* @param query - The item query to run
+ * @param params - The bound parameters
* @returns The raw item rows, or an empty array if the table does not exist yet
*/
- private *selectItemRows(query: string): DbOp<ItemRow[]> {
+ private *selectItemRows(query: string, params: SqliteBindValue[] = []): DbOp<ItemRow[]> {
try {
- return yield* this.query<ItemRow>(query);
+ return yield* this.query<ItemRow>(query, params);
} catch (error) {
// Items table may not exist in older vault versions - return empty array
if (error instanceof Error && error.message.includes('no such table')) {
diff --git a/core/client/src/items/ItemFilters.ts b/core/client/src/items/ItemFilters.ts
index 05443b01f..cfb5c3384 100644
--- a/core/client/src/items/ItemFilters.ts
+++ b/core/client/src/items/ItemFilters.ts
@@ -36,17 +36,22 @@ export function parseItemFilterType(value: string | null | undefined): ItemFilte
return 'all';
}
+/**
+ * The parts of an item a type/feature filter reads, so folder counts can run over item summaries.
+ */
+export type FilterableItem = Pick<Item, 'ItemType' | 'HasPasskey' | 'HasAttachment' | 'HasTotp'>;
+
/**
* Apply the active type/feature filter to a list of items.
* Used both for the visible item list and for computing folder badge counts so they
* stay consistent when a filter is active, folder counts only include matching items.
*/
-export function applyTypeFilter(items: Item[], filterType: ItemFilterType): Item[] {
+export function applyTypeFilter<T extends FilterableItem>(items: T[], filterType: ItemFilterType): T[] {
if (filterType === 'all') {
return items;
}
- return items.filter((item: Item) => {
+ return items.filter((item: T) => {
if (filterType === 'passkeys') {
return item.HasPasskey === true;
}