Skip to content

armgit / papra

Public Imported from GitHub
0

The minimalistic document archiving platform.

feat(mobile): add infinite document list pagination (#1488)

Corentin Thomasset9cc1cfb9c2d0
diff --git a/.changeset/shaggy-corners-deny.md b/.changeset/shaggy-corners-deny.md
new file mode 100644
index 00000000..bc960626
--- /dev/null
+++ b/.changeset/shaggy-corners-deny.md
@@ -0,0 +1,5 @@
+---
+'@papra/mobile': patch
+---
+
+Automatically load more documents as you scroll through the document list and search results, instead of showing only the first 20.
diff --git a/apps/mobile/src/modules/documents/components/documents-list.tsx b/apps/mobile/src/modules/documents/components/documents-list.tsx
index 9416fbb4..bfe0fd94 100644
--- a/apps/mobile/src/modules/documents/components/documents-list.tsx
+++ b/apps/mobile/src/modules/documents/components/documents-list.tsx
@@ -5,8 +5,16 @@ import type { ThemeColors } from '@/modules/ui/theme.constants';
import { formatBytes } from '@corentinth/chisels';
import { router } from 'expo-router';
import { useState } from 'react';
-import { FlatList, StyleSheet, Text, TouchableOpacity, View } from 'react-native';
+import {
+ ActivityIndicator,
+ FlatList,
+ StyleSheet,
+ Text,
+ TouchableOpacity,
+ View,
+} from 'react-native';
import { DocumentActionSheet } from '@/modules/documents/components/document-action-sheet';
+import { useAppTranslations } from '@/modules/i18n/hooks/use-app-translations';
import { useFormatters } from '@/modules/i18n/hooks/use-formatters';
import { Tag } from '@/modules/tags/components/tag';
import { Icon } from '@/modules/ui/components/icon';
@@ -16,6 +24,9 @@ const maxVisibleTags = 3;
type DocumentsListProps = {
documents: CoerceDates<Document>[];
+ onLoadMore?: () => void;
+ isFetchingNextPage?: boolean;
+ isFetchNextPageError?: boolean;
emptyState: {
title: string;
subtitle?: string;
@@ -26,10 +37,14 @@ type DocumentsListProps = {
export function DocumentsList({
documents,
+ onLoadMore,
+ isFetchingNextPage = false,
+ isFetchNextPageError = false,
emptyState,
refreshControl,
keyboardShouldPersistTaps,
}: DocumentsListProps) {
+ const t = useAppTranslations();
const { formatDate } = useFormatters();
const themeColors = useThemeColor();
const [onDocumentActionSheet, setOnDocumentActionSheet] = useState<
@@ -116,6 +131,29 @@ export function DocumentsList({
</View>
</TouchableOpacity>
)}
+ onEndReached={isFetchNextPageError ? undefined : onLoadMore}
+ onEndReachedThreshold={0.5}
+ ListFooterComponent={
+ isFetchingNextPage ? (
+ <View style={styles.footer}>
+ <ActivityIndicator
+ color={themeColors.primary}
+ accessibilityLabel={t.documents.loadingMore}
+ />
+ </View>
+ ) : isFetchNextPageError ? (
+ <View style={styles.footer}>
+ <Text style={styles.emptySubtext}>{t.documents.loadMoreFailed}</Text>
+ <TouchableOpacity
+ onPress={onLoadMore}
+ accessibilityRole="button"
+ style={styles.retryButton}
+ >
+ <Text style={styles.retryText}>{t.common.retry}</Text>
+ </TouchableOpacity>
+ </View>
+ ) : null
+ }
ListEmptyComponent={
<View style={styles.emptyContainer}>
<Text style={styles.emptyText}>{emptyState.title}</Text>
@@ -134,6 +172,20 @@ export function DocumentsList({
function createStyles({ themeColors }: { themeColors: ThemeColors }) {
return StyleSheet.create({
+ footer: {
+ padding: 16,
+ alignItems: 'center',
+ gap: 8,
+ },
+ retryButton: {
+ paddingHorizontal: 16,
+ paddingVertical: 12,
+ },
+ retryText: {
+ color: themeColors.primary,
+ fontSize: 16,
+ fontWeight: '600',
+ },
emptyList: {
flex: 1,
},
diff --git a/apps/mobile/src/modules/documents/documents.queries.test.ts b/apps/mobile/src/modules/documents/documents.queries.test.ts
new file mode 100644
index 00000000..7669d4f1
--- /dev/null
+++ b/apps/mobile/src/modules/documents/documents.queries.test.ts
@@ -0,0 +1,177 @@
+import type { ApiClient } from '../api/api.client';
+import { InfiniteQueryObserver, QueryClient } from '@tanstack/react-query';
+import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest';
+import { organizationDocumentsInfiniteQueryOptions } from './documents.queries';
+import { fetchOrganizationDocuments } from './documents.services';
+
+vi.mock('./documents.services', () => ({
+ fetchOrganizationDocuments: vi.fn(),
+}));
+
+const fetchDocuments = vi.mocked(fetchOrganizationDocuments);
+const apiClient: ApiClient = async () => {
+ throw new Error('Unexpected API request: document fetching should be mocked');
+};
+
+function createPage({ pageIndex = 0, count = 45, length = 20 } = {}) {
+ return {
+ documentsCount: count,
+ documents: Array.from({ length }, (_, index) => ({
+ id: `document-${pageIndex * 20 + index}`,
+ name: 'Document',
+ organizationId: 'organization-1',
+ mimeType: 'application/pdf',
+ originalSize: 100,
+ createdAt: new Date('2026-01-01'),
+ updatedAt: new Date('2026-01-01'),
+ localUri: undefined,
+ tags: [],
+ })),
+ };
+}
+
+describe('organization documents infinite query', () => {
+ let client: QueryClient;
+
+ beforeEach(() => {
+ vi.clearAllMocks();
+ client = new QueryClient({ defaultOptions: { queries: { retry: false, gcTime: Infinity } } });
+ });
+
+ afterEach(() => {
+ client.clear();
+ });
+
+ function createObserver(searchQuery?: string) {
+ return new InfiniteQueryObserver(
+ client,
+ organizationDocumentsInfiniteQueryOptions({
+ organizationId: 'organization-1',
+ apiClient,
+ searchQuery,
+ }),
+ );
+ }
+
+ test('loads successive pages and stops at the total count', async () => {
+ fetchDocuments
+ .mockResolvedValueOnce(createPage())
+ .mockResolvedValueOnce(createPage({ pageIndex: 1 }))
+ .mockResolvedValueOnce(createPage({ pageIndex: 2, length: 5 }));
+ const observer = createObserver();
+
+ await observer.refetch();
+ expect(observer.getCurrentResult().hasNextPage).toBe(true);
+ await observer.fetchNextPage();
+ const last = await observer.fetchNextPage();
+
+ expect(last.data?.pageParams).toEqual([0, 1, 2]);
+ expect(last.data?.pages.flatMap((page) => page.documents)).toHaveLength(45);
+ expect(last.hasNextPage).toBe(false);
+ await observer.fetchNextPage();
+ expect(fetchDocuments).toHaveBeenCalledTimes(3);
+ expect(fetchDocuments.mock.calls.map(([options]) => options.pageIndex)).toEqual([0, 1, 2]);
+ expect(fetchDocuments).toHaveBeenLastCalledWith({
+ organizationId: 'organization-1',
+ apiClient,
+ searchQuery: undefined,
+ pageIndex: 2,
+ pageSize: 20,
+ });
+ });
+
+ test.each([
+ { count: 0, length: 0 },
+ { count: 7, length: 7 },
+ { count: 20, length: 20 },
+ { count: 45, length: 0 },
+ ])('stops for a terminal page: %j', async ({ count, length }) => {
+ fetchDocuments.mockResolvedValueOnce(createPage({ count, length }));
+ const observer = createObserver();
+ await observer.refetch();
+ expect(observer.getCurrentResult().hasNextPage).toBe(false);
+ });
+
+ test('preserves loaded documents on failure and retries the same page', async () => {
+ fetchDocuments
+ .mockResolvedValueOnce(createPage())
+ .mockRejectedValueOnce(new Error('Network unavailable'))
+ .mockResolvedValueOnce(createPage({ pageIndex: 1 }));
+ const observer = createObserver();
+ await observer.refetch();
+ const failed = await observer.fetchNextPage();
+ expect(failed.isFetchNextPageError).toBe(true);
+ expect(failed.data?.pages).toHaveLength(1);
+ expect(failed.hasNextPage).toBe(true);
+
+ const retried = await observer.fetchNextPage();
+ expect(retried.isFetchNextPageError).toBe(false);
+ expect(retried.data?.pageParams).toEqual([0, 1]);
+ expect(fetchDocuments.mock.calls.map(([options]) => options.pageIndex)).toEqual([0, 1, 1]);
+ });
+
+ test('passes the search query to every page and isolates cached results', async () => {
+ fetchDocuments.mockResolvedValue(createPage());
+ const observer = createObserver('invoice');
+ await observer.refetch();
+ await observer.fetchNextPage();
+ expect(fetchDocuments.mock.calls.every(([options]) => options.searchQuery === 'invoice')).toBe(
+ true,
+ );
+
+ const options = organizationDocumentsInfiniteQueryOptions({
+ organizationId: 'organization-1',
+ apiClient,
+ searchQuery: 'invoice',
+ });
+ expect(client.getQueryData(options.queryKey)).toBeDefined();
+ for (const scope of [
+ { organizationId: 'organization-2', searchQuery: 'invoice' },
+ { organizationId: 'organization-1', searchQuery: 'receipt' },
+ { organizationId: 'organization-1', searchQuery: undefined },
+ ]) {
+ const nextOptions = organizationDocumentsInfiniteQueryOptions({ ...scope, apiClient });
+ expect(client.getQueryData(nextOptions.queryKey)).toBeUndefined();
+ }
+ });
+
+ test('disables fetching without an organization or with an empty search', () => {
+ for (const scope of [
+ { organizationId: null },
+ { organizationId: '' },
+ { organizationId: 'organization-1', searchQuery: '' },
+ ]) {
+ expect(organizationDocumentsInfiniteQueryOptions({ ...scope, apiClient }).enabled).toBe(
+ false,
+ );
+ }
+ });
+
+ test('coalesces repeated load-more requests without cancelling the pending page', async () => {
+ fetchDocuments
+ .mockResolvedValueOnce(createPage())
+ .mockResolvedValueOnce(createPage({ pageIndex: 1 }));
+ const observer = createObserver();
+ await observer.refetch();
+
+ await Promise.all([
+ observer.fetchNextPage({ cancelRefetch: false }),
+ observer.fetchNextPage({ cancelRefetch: false }),
+ ]);
+
+ expect(fetchDocuments).toHaveBeenCalledTimes(2);
+ expect(observer.getCurrentResult().data?.pageParams).toEqual([0, 1]);
+ });
+
+ test('refreshes loaded pages from the beginning', async () => {
+ fetchDocuments.mockResolvedValue(createPage());
+ const observer = createObserver();
+ await observer.refetch();
+ await observer.fetchNextPage();
+ fetchDocuments.mockClear();
+
+ const result = await observer.refetch();
+ expect(fetchDocuments.mock.calls.map(([options]) => options.pageIndex)).toEqual([0, 1]);
+ expect(result.data?.pageParams).toEqual([0, 1]);
+ });
+});
diff --git a/apps/mobile/src/modules/documents/documents.queries.ts b/apps/mobile/src/modules/documents/documents.queries.ts
new file mode 100644
index 00000000..426a036e
--- /dev/null
+++ b/apps/mobile/src/modules/documents/documents.queries.ts
@@ -0,0 +1,44 @@
+import type { ApiClient } from '../api/api.client';
+import { infiniteQueryOptions } from '@tanstack/react-query';
+import { fetchOrganizationDocuments } from './documents.services';
+
+const pageSize = 20;
+
+export function organizationDocumentsInfiniteQueryOptions({
+ organizationId,
+ apiClient,
+ searchQuery,
+}: {
+ organizationId: string | null;
+ apiClient: ApiClient;
+ searchQuery?: string;
+}) {
+ return infiniteQueryOptions({
+ queryKey: ['organizations', organizationId, 'documents', 'infinite', { searchQuery, pageSize }],
+ initialPageParam: 0,
+ queryFn: async ({ pageParam }) => {
+ if (!organizationId) {
+ return { documents: [], documentsCount: 0 };
+ }
+
+ return fetchOrganizationDocuments({
+ organizationId,
+ apiClient,
+ searchQuery,
+ pageIndex: pageParam,
+ pageSize,
+ });
+ },
+ getNextPageParam: (lastPage, _pages, lastPageParam) => {
+ const nextPageIndex = lastPageParam + 1;
+
+ // An empty page also ends pagination if the count changed while browsing.
+ if (lastPage.documents.length === 0 || nextPageIndex * pageSize >= lastPage.documentsCount) {
+ return undefined;
+ }
+
+ return nextPageIndex;
+ },
+ enabled: Boolean(organizationId) && (searchQuery === undefined || searchQuery !== ''),
+ });
+}
diff --git a/apps/mobile/src/modules/documents/hooks/use-documents.hook.ts b/apps/mobile/src/modules/documents/hooks/use-documents.hook.ts
new file mode 100644
index 00000000..0c392ded
--- /dev/null
+++ b/apps/mobile/src/modules/documents/hooks/use-documents.hook.ts
@@ -0,0 +1,38 @@
+import { useInfiniteQuery } from '@tanstack/react-query';
+import { useMemo } from 'react';
+import { useApiClient } from '@/modules/api/providers/api.provider';
+import { useOrganizations } from '@/modules/organizations/organizations.provider';
+import { organizationDocumentsInfiniteQueryOptions } from '../documents.queries';
+
+export function useDocuments({ searchQuery }: { searchQuery?: string } = {}) {
+ const apiClient = useApiClient();
+ const { currentOrganizationId } = useOrganizations();
+ const query = useInfiniteQuery(
+ organizationDocumentsInfiniteQueryOptions({
+ organizationId: currentOrganizationId,
+ apiClient,
+ searchQuery,
+ }),
+ );
+
+ const documents = useMemo(() => {
+ // Offset pagination can overlap when documents are added while browsing.
+ const seen = new Set<string>();
+ return (query.data?.pages.flatMap((page) => page.documents) ?? []).filter((document) => {
+ if (seen.has(document.id)) {
+ return false;
+ }
+ seen.add(document.id);
+ return true;
+ });
+ }, [query.data]);
+
+ const loadMore = () => {
+ if (query.hasNextPage && !query.isFetching) {
+ // Repeated end-of-list events must not cancel an in-flight request.
+ void query.fetchNextPage({ cancelRefetch: false });
+ }
+ };
+
+ return { ...query, documents, loadMore };
+}
diff --git a/apps/mobile/src/modules/documents/screens/documents-list.screen.tsx b/apps/mobile/src/modules/documents/screens/documents-list.screen.tsx
index 048e996b..dab41779 100644
--- a/apps/mobile/src/modules/documents/screens/documents-list.screen.tsx
+++ b/apps/mobile/src/modules/documents/screens/documents-list.screen.tsx
@@ -1,5 +1,4 @@
import type { ThemeColors } from '@/modules/ui/theme.constants';
-import { useQuery } from '@tanstack/react-query';
import { router } from 'expo-router';
import { useState } from 'react';
import {
@@ -19,7 +18,7 @@ import { OrganizationPickerDrawer } from '@/modules/organizations/components/org
import { useOrganizations } from '@/modules/organizations/organizations.provider';
import { Icon } from '@/modules/ui/components/icon';
import { useThemeColor } from '@/modules/ui/providers/use-theme-color';
-import { fetchOrganizationDocuments } from '../documents.services';
+import { useDocuments } from '../hooks/use-documents.hook';
import { syncUnsyncedDocuments } from '../documents.sync.services';
export function DocumentsListScreen() {
@@ -28,23 +27,7 @@ export function DocumentsListScreen() {
const apiClient = useApiClient();
const { currentOrganizationId, isLoading: isLoadingOrganizations } = useOrganizations();
const [isDrawerVisible, setIsDrawerVisible] = useState(false);
- const pagination = { pageIndex: 0, pageSize: 20 };
-
- const documentsQuery = useQuery({
- queryKey: ['organizations', currentOrganizationId, 'documents', pagination],
- queryFn: async () => {
- if (currentOrganizationId == null) {
- return { documents: [], documentsCount: 0 };
- }
-
- return fetchOrganizationDocuments({
- organizationId: currentOrganizationId,
- ...pagination,
- apiClient,
- });
- },
- enabled: currentOrganizationId !== null && currentOrganizationId !== '',
- });
+ const documentsQuery = useDocuments();
const styles = createStyles({ themeColors });
@@ -97,7 +80,11 @@ export function DocumentsListScreen() {
</View>
) : (
<DocumentsList
- documents={documentsQuery.data?.documents ?? []}
+ key={currentOrganizationId}
+ documents={documentsQuery.documents}
+ onLoadMore={documentsQuery.loadMore}
+ isFetchingNextPage={documentsQuery.isFetchingNextPage}
+ isFetchNextPageError={documentsQuery.isFetchNextPageError}
emptyState={{
title: t.documents.emptyTitle,
subtitle: t.documents.emptySubtitle,
diff --git a/apps/mobile/src/modules/documents/screens/documents-search.screen.tsx b/apps/mobile/src/modules/documents/screens/documents-search.screen.tsx
index 074cfaca..39605d79 100644
--- a/apps/mobile/src/modules/documents/screens/documents-search.screen.tsx
+++ b/apps/mobile/src/modules/documents/screens/documents-search.screen.tsx
@@ -1,5 +1,4 @@
import type { ThemeColors } from '@/modules/ui/theme.constants';
-import { useQuery } from '@tanstack/react-query';
import { router, useFocusEffect } from 'expo-router';
import { useCallback, useEffect, useRef, useState } from 'react';
import {
@@ -13,20 +12,17 @@ import {
} from 'react-native';
import { SafeAreaView } from 'react-native-safe-area-context';
import { useAppTranslations } from '@/modules/i18n/hooks/use-app-translations';
-import { useApiClient } from '@/modules/api/providers/api.provider';
import { DocumentsList } from '@/modules/documents/components/documents-list';
import { useOrganizations } from '@/modules/organizations/organizations.provider';
import { Icon } from '@/modules/ui/components/icon';
import { useThemeColor } from '@/modules/ui/providers/use-theme-color';
-import { fetchOrganizationDocuments } from '../documents.services';
+import { useDocuments } from '../hooks/use-documents.hook';
const SEARCH_DEBOUNCE_MS = 300;
-const pagination = { pageIndex: 0, pageSize: 20 };
export function DocumentsSearchScreen() {
const t = useAppTranslations();
const themeColors = useThemeColor();
- const apiClient = useApiClient();
const { currentOrganizationId } = useOrganizations();
const [searchQuery, setSearchQuery] = useState('');
@@ -51,30 +47,7 @@ export function DocumentsSearchScreen() {
return () => clearTimeout(timeout);
}, [searchQuery]);
- const searchResultsQuery = useQuery({
- queryKey: [
- 'organizations',
- currentOrganizationId,
- 'documents',
- 'search',
- debouncedSearchQuery,
- pagination,
- ],
- queryFn: async () => {
- if (currentOrganizationId == null) {
- return { documents: [], documentsCount: 0 };
- }
-
- return fetchOrganizationDocuments({
- organizationId: currentOrganizationId,
- searchQuery: debouncedSearchQuery,
- ...pagination,
- apiClient,
- });
- },
- enabled:
- currentOrganizationId !== null && currentOrganizationId !== '' && debouncedSearchQuery !== '',
- });
+ const searchResultsQuery = useDocuments({ searchQuery: debouncedSearchQuery });
const handleCancel = () => {
Keyboard.dismiss();
@@ -133,7 +106,11 @@ export function DocumentsSearchScreen() {
</View>
) : (
<DocumentsList
- documents={searchResultsQuery.data?.documents ?? []}
+ key={JSON.stringify([currentOrganizationId, debouncedSearchQuery])}
+ documents={searchResultsQuery.documents}
+ onLoadMore={searchResultsQuery.loadMore}
+ isFetchingNextPage={searchResultsQuery.isFetchingNextPage}
+ isFetchNextPageError={searchResultsQuery.isFetchNextPageError}
emptyState={{
title: t.documents.search.empty,
subtitle: t.documents.search.noResults({ query: debouncedSearchQuery }),
diff --git a/apps/mobile/src/modules/i18n/translations/de.ts b/apps/mobile/src/modules/i18n/translations/de.ts
index 73d2cf46..616e3b56 100644
--- a/apps/mobile/src/modules/i18n/translations/de.ts
+++ b/apps/mobile/src/modules/i18n/translations/de.ts
@@ -30,6 +30,8 @@ export const de = {
},
documents: {
title: 'Dokumente',
+ loadingMore: 'Weitere Dokumente werden geladen…',
+ loadMoreFailed: 'Weitere Dokumente konnten nicht geladen werden.',
search: {
title: 'Suche',
placeholder: 'Dokumente suchen',
diff --git a/apps/mobile/src/modules/i18n/translations/en.ts b/apps/mobile/src/modules/i18n/translations/en.ts
index 6e0236d5..a652f2f1 100644
--- a/apps/mobile/src/modules/i18n/translations/en.ts
+++ b/apps/mobile/src/modules/i18n/translations/en.ts
@@ -30,6 +30,8 @@ export const en = {
},
documents: {
title: 'Documents',
+ loadingMore: 'Loading more documents...',
+ loadMoreFailed: 'Failed to load more documents.',
search: {
title: 'Search',
placeholder: 'Search documents',
diff --git a/apps/mobile/src/modules/i18n/translations/es.ts b/apps/mobile/src/modules/i18n/translations/es.ts
index 3987a0c1..362d006a 100644
--- a/apps/mobile/src/modules/i18n/translations/es.ts
+++ b/apps/mobile/src/modules/i18n/translations/es.ts
@@ -30,6 +30,8 @@ export const es = {
},
documents: {
title: 'Documentos',
+ loadingMore: 'Cargando más documentos…',
+ loadMoreFailed: 'No se han podido cargar más documentos.',
search: {
title: 'Buscar',
placeholder: 'Buscar documentos',
diff --git a/apps/mobile/src/modules/i18n/translations/fr.ts b/apps/mobile/src/modules/i18n/translations/fr.ts
index 04ac2ea0..d23f2596 100644
--- a/apps/mobile/src/modules/i18n/translations/fr.ts
+++ b/apps/mobile/src/modules/i18n/translations/fr.ts
@@ -30,6 +30,8 @@ export const fr = {
},
documents: {
title: 'Documents',
+ loadingMore: 'Chargement de documents supplémentaires…',
+ loadMoreFailed: 'Impossible de charger plus de documents.',
search: {
title: 'Recherche',
placeholder: 'Rechercher des documents',