Skip to content

armgit / papra

Public Imported from GitHub
0

The minimalistic document archiving platform.

feat(mobile): manage document tags (#1491)

Corentin Thomasseta6ac457245b5
diff --git a/.changeset/cute-wings-cover.md b/.changeset/cute-wings-cover.md
new file mode 100644
index 00000000..1fe7b338
--- /dev/null
+++ b/.changeset/cute-wings-cover.md
@@ -0,0 +1,5 @@
+---
+'@papra/mobile': minor
+---
+
+Manage document tags from the document details or the document list.
diff --git a/apps/mobile/src/modules/documents/components/document-action-sheet.tsx b/apps/mobile/src/modules/documents/components/document-action-sheet.tsx
index c33d75c8..c2d50c68 100644
--- a/apps/mobile/src/modules/documents/components/document-action-sheet.tsx
+++ b/apps/mobile/src/modules/documents/components/document-action-sheet.tsx
@@ -3,27 +3,23 @@ import type { Document } from '@/modules/documents/documents.types';
import type { IconName } from '@/modules/ui/components/icon';
import type { ThemeColors } from '@/modules/ui/theme.constants';
import { formatBytes } from '@corentinth/chisels';
-import { useQueryClient } from '@tanstack/react-query';
+import { useIsMutating, useQueryClient } from '@tanstack/react-query';
import { router } from 'expo-router';
import * as Sharing from 'expo-sharing';
import { useState } from 'react';
-import {
- Modal,
- StyleSheet,
- Text,
- TouchableOpacity,
- TouchableWithoutFeedback,
- View,
-} from 'react-native';
+import { StyleSheet, Text, TouchableOpacity, View } from 'react-native';
import { useAppTranslations } from '@/modules/i18n/hooks/use-app-translations';
import { useFormatters } from '@/modules/i18n/hooks/use-formatters';
import { useApiClient, useAuthClient } from '@/modules/api/providers/api.provider';
+import { DocumentTagsDrawerContent } from '@/modules/documents/components/document-tags-drawer';
import { RenameDocumentDialog } from '@/modules/documents/components/rename-document-dialog';
import {
deleteDocument,
fetchDocumentFile,
renameDocument,
} from '@/modules/documents/documents.services';
+import { documentTagMutationKey } from '@/modules/tags/tags.queries';
+import { BottomDrawer } from '@/modules/ui/components/bottom-drawer';
import { Icon } from '@/modules/ui/components/icon';
import { useAlert } from '@/modules/ui/providers/alert-provider';
import { useThemeColor } from '@/modules/ui/providers/use-theme-color';
@@ -36,7 +32,7 @@ type DocumentActionSheetProps = {
onDeleted?: () => void;
};
-export type ActionsKey = 'view' | 'rename' | 'share' | 'delete';
+export type ActionsKey = 'view' | 'rename' | 'manage-tags' | 'share' | 'delete';
export function DocumentActionSheet({
visible,
@@ -54,6 +50,18 @@ export function DocumentActionSheet({
const apiClient = useApiClient();
const queryClient = useQueryClient();
const [isRenameDialogVisible, setIsRenameDialogVisible] = useState(false);
+ const [isManagingTags, setIsManagingTags] = useState(false);
+ const pendingTagUpdates = useIsMutating({
+ mutationKey: documentTagMutationKey({
+ organizationId: document?.organizationId ?? '',
+ documentId: document?.id ?? '',
+ }),
+ });
+
+ const handleClose = () => {
+ setIsManagingTags(false);
+ onClose();
+ };
if (document === undefined) {
return null;
@@ -197,6 +205,12 @@ export function DocumentActionSheet({
icon: 'edit-2',
onPress: handleRename,
},
+ {
+ key: 'manage-tags',
+ label: t.documents.manageTags,
+ icon: 'tag',
+ onPress: () => setIsManagingTags(true),
+ },
{
key: 'share',
label: t.common.share,
@@ -222,97 +236,77 @@ export function DocumentActionSheet({
onCancel={handleRenameCancel}
/>
- <Modal
+ <BottomDrawer
visible={visible && !isRenameDialogVisible}
- transparent
- animationType="slide"
- onRequestClose={onClose}
+ onClose={handleClose}
+ dismissible={pendingTagUpdates === 0}
>
- <TouchableWithoutFeedback onPress={onClose}>
- <View style={styles.overlay}>
- <TouchableWithoutFeedback>
- <View style={styles.sheet}>
- <View style={styles.handleBar} />
+ {isManagingTags ? (
+ <DocumentTagsDrawerContent
+ key={`${document.organizationId}:${document.id}`}
+ organizationId={document.organizationId}
+ documentId={document.id}
+ onClose={handleClose}
+ />
+ ) : (
+ <>
+ <View style={styles.header}>
+ <View style={styles.fileIconContainer}>
+ <Icon name="file-text" size={24} color={themeColors.primary} />
+ </View>
+ <View style={styles.headerContent}>
+ <Text style={styles.documentName} numberOfLines={2}>
+ {document.name}
+ </Text>
+ <Text style={styles.documentMeta}>
+ {displayMimeType}
+ {' · '}
+ {formatBytes({ bytes: document.originalSize })}
+ {' · '}
+ {formatDate(document.createdAt)}
+ </Text>
+ </View>
+ </View>
- <View style={styles.header}>
- <View style={styles.fileIconContainer}>
- <Icon name="file-text" size={24} color={themeColors.primary} />
- </View>
- <View style={styles.headerContent}>
- <Text style={styles.documentName} numberOfLines={2}>
- {document.name}
- </Text>
- <Text style={styles.documentMeta}>
- {displayMimeType}
- {' · '}
- {formatBytes({ bytes: document.originalSize })}
- {' · '}
- {formatDate(document.createdAt)}
- </Text>
+ <View style={styles.actions}>
+ {filteredActions.map((action) => (
+ <TouchableOpacity
+ key={action.key}
+ style={styles.actionRow}
+ onPress={action.onPress}
+ activeOpacity={0.6}
+ >
+ <View style={styles.actionIconContainer}>
+ <Icon
+ name={action.icon}
+ size={20}
+ color={
+ action.destructive === true
+ ? themeColors.destructive
+ : themeColors.foreground
+ }
+ />
</View>
- </View>
-
- <View style={styles.actions}>
- {filteredActions.map((action) => (
- <TouchableOpacity
- key={action.key}
- style={styles.actionRow}
- onPress={action.onPress}
- activeOpacity={0.6}
- >
- <View style={styles.actionIconContainer}>
- <Icon
- name={action.icon}
- size={20}
- color={
- action.destructive === true
- ? themeColors.destructive
- : themeColors.foreground
- }
- />
- </View>
- <Text
- style={[
- styles.actionText,
- action.destructive === true && { color: themeColors.destructive },
- ]}
- >
- {action.label}
- </Text>
- </TouchableOpacity>
- ))}
- </View>
- </View>
- </TouchableWithoutFeedback>
- </View>
- </TouchableWithoutFeedback>
- </Modal>
+ <Text
+ style={[
+ styles.actionText,
+ action.destructive === true && { color: themeColors.destructive },
+ ]}
+ >
+ {action.label}
+ </Text>
+ </TouchableOpacity>
+ ))}
+ </View>
+ </>
+ )}
+ </BottomDrawer>
</>
);
}
function createStyles({ themeColors }: { themeColors: ThemeColors }) {
return StyleSheet.create({
- overlay: {
- flex: 1,
- backgroundColor: 'rgba(0, 0, 0, 0.5)',
- justifyContent: 'flex-end',
- },
- sheet: {
- backgroundColor: themeColors.secondaryBackground,
- borderTopLeftRadius: 16,
- borderTopRightRadius: 16,
- paddingBottom: 34,
- },
- handleBar: {
- width: 36,
- height: 4,
- backgroundColor: themeColors.border,
- borderRadius: 2,
- alignSelf: 'center',
- marginTop: 8,
- marginBottom: 16,
- },
header: {
flexDirection: 'row',
alignItems: 'center',
diff --git a/apps/mobile/src/modules/documents/components/document-tags-drawer.tsx b/apps/mobile/src/modules/documents/components/document-tags-drawer.tsx
new file mode 100644
index 00000000..a0d3aab2
--- /dev/null
+++ b/apps/mobile/src/modules/documents/components/document-tags-drawer.tsx
@@ -0,0 +1,299 @@
+import type { ThemeColors } from '@/modules/ui/theme.constants';
+import { useIsMutating, useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
+import { useState } from 'react';
+import {
+ ActivityIndicator,
+ FlatList,
+ StyleSheet,
+ Text,
+ TextInput,
+ TouchableOpacity,
+ View,
+} from 'react-native';
+import { useApiClient } from '@/modules/api/providers/api.provider';
+import { useAppTranslations } from '@/modules/i18n/hooks/use-app-translations';
+import {
+ documentTagMutationKey,
+ documentTagMutationOptions,
+ organizationTagsQueryOptions,
+} from '@/modules/tags/tags.queries';
+import { BottomDrawer } from '@/modules/ui/components/bottom-drawer';
+import { Icon } from '@/modules/ui/components/icon';
+import { useThemeColor } from '@/modules/ui/providers/use-theme-color';
+import { documentQueryOptions } from '../documents.queries';
+
+type DocumentTagsDrawerContentProps = {
+ organizationId: string;
+ documentId: string;
+ onClose: () => void;
+};
+
+export function DocumentTagsDrawer({
+ visible,
+ organizationId,
+ documentId,
+ onClose,
+}: DocumentTagsDrawerContentProps & { visible: boolean }) {
+ const pendingUpdates = useIsMutating({
+ mutationKey: documentTagMutationKey({ organizationId, documentId }),
+ });
+
+ return (
+ <BottomDrawer visible={visible} onClose={onClose} dismissible={pendingUpdates === 0}>
+ {visible && (
+ <DocumentTagsDrawerContent
+ key={`${organizationId}:${documentId}`}
+ organizationId={organizationId}
+ documentId={documentId}
+ onClose={onClose}
+ />
+ )}
+ </BottomDrawer>
+ );
+}
+
+// Also embedded in the action drawer so switching to tag management does not
+// dismiss and present competing native modals on iOS.
+export function DocumentTagsDrawerContent({
+ organizationId,
+ documentId,
+ onClose,
+}: DocumentTagsDrawerContentProps) {
+ const t = useAppTranslations();
+ const themeColors = useThemeColor();
+ const styles = createStyles({ themeColors });
+ const apiClient = useApiClient();
+ const queryClient = useQueryClient();
+ const [search, setSearch] = useState('');
+ const documentQuery = useQuery({
+ ...documentQueryOptions({ organizationId, documentId, apiClient }),
+ staleTime: 0,
+ });
+ const tagsQuery = useQuery(organizationTagsQueryOptions({ organizationId, apiClient }));
+ const mutationOptions = documentTagMutationOptions({
+ organizationId,
+ documentId,
+ apiClient,
+ queryClient,
+ });
+ const updateTagMutation = useMutation(mutationOptions);
+ const selectedIds = new Set(documentQuery.data?.document.tags.map(({ id }) => id));
+ const tags = tagsQuery.data?.tags ?? [];
+ const searchText = search.trim().toLocaleLowerCase();
+ const filteredTags = tags
+ .filter(({ name }) => name.toLocaleLowerCase().includes(searchText))
+ .sort((a, b) => a.name.localeCompare(b.name));
+ const isLoading = documentQuery.isPending || tagsQuery.isPending;
+ const hasLoadError = documentQuery.isError || tagsQuery.isError;
+
+ return (
+ <View style={styles.content}>
+ <View style={styles.header}>
+ <Text style={styles.title} accessibilityRole="header">
+ {t.documents.manageTags}
+ </Text>
+ <TouchableOpacity
+ style={styles.closeButton}
+ onPress={onClose}
+ disabled={updateTagMutation.isPending}
+ accessibilityRole="button"
+ accessibilityLabel={t.common.close}
+ accessibilityState={{ disabled: updateTagMutation.isPending }}
+ >
+ <Icon name="x" size={22} color={themeColors.mutedForeground} />
+ </TouchableOpacity>
+ </View>
+ <View style={styles.searchContainer}>
+ <Icon name="search" size={18} color={themeColors.mutedForeground} />
+ <TextInput
+ style={styles.searchInput}
+ placeholder={t.documents.tagPicker.searchPlaceholder}
+ accessibilityLabel={t.documents.tagPicker.searchPlaceholder}
+ placeholderTextColor={themeColors.mutedForeground}
+ value={search}
+ onChangeText={setSearch}
+ autoCapitalize="none"
+ autoCorrect={false}
+ returnKeyType="search"
+ />
+ </View>
+
+ {updateTagMutation.isError && (
+ <Text style={styles.error} accessibilityRole="alert">
+ {t.documents.tagPicker.updateFailed}
+ </Text>
+ )}
+
+ {hasLoadError ? (
+ <View style={styles.statusContainer}>
+ <Text style={styles.statusText}>{t.documents.tagPicker.loadFailed}</Text>
+ <TouchableOpacity
+ style={styles.retryButton}
+ onPress={() => {
+ void documentQuery.refetch();
+ void tagsQuery.refetch();
+ }}
+ accessibilityRole="button"
+ >
+ <Text style={styles.retryText}>{t.common.retry}</Text>
+ </TouchableOpacity>
+ </View>
+ ) : isLoading ? (
+ <View style={styles.statusContainer}>
+ <ActivityIndicator
+ color={themeColors.primary}
+ accessibilityLabel={t.documents.tagPicker.loading}
+ />
+ </View>
+ ) : (
+ <FlatList
+ style={styles.list}
+ data={filteredTags}
+ keyExtractor={({ id }) => id}
+ keyboardShouldPersistTaps="handled"
+ keyboardDismissMode="on-drag"
+ extraData={{ selectedIds, isPending: updateTagMutation.isPending }}
+ renderItem={({ item }) => {
+ const selected = selectedIds.has(item.id);
+ const isUpdating =
+ updateTagMutation.isPending && updateTagMutation.variables.tag.id === item.id;
+
+ return (
+ <TouchableOpacity
+ style={[styles.tagRow, selected && styles.selectedRow]}
+ accessibilityRole="checkbox"
+ accessibilityLabel={item.name}
+ accessibilityState={{ checked: selected, disabled: updateTagMutation.isPending }}
+ disabled={updateTagMutation.isPending}
+ onPress={() => {
+ // Check the cache synchronously to guard rapid taps before React rerenders.
+ if (queryClient.isMutating({ mutationKey: mutationOptions.mutationKey }) > 0) {
+ return;
+ }
+ updateTagMutation.mutate({ tag: item, selected: !selected });
+ }}
+ >
+ <View style={[styles.tagDot, { backgroundColor: item.color }]} />
+ <Text style={styles.tagName} numberOfLines={2}>
+ {item.name}
+ </Text>
+ {isUpdating && (
+ <ActivityIndicator
+ size="small"
+ color={themeColors.primary}
+ accessibilityLabel={t.documents.tagPicker.updating}
+ />
+ )}
+ <Icon
+ name={selected ? 'check-square' : 'square'}
+ size={22}
+ color={selected ? themeColors.primary : themeColors.mutedForeground}
+ />
+ </TouchableOpacity>
+ );
+ }}
+ ListEmptyComponent={
+ <View style={styles.statusContainer}>
+ <Text style={styles.statusText}>
+ {tags.length === 0 ? t.documents.tagPicker.empty : t.documents.tagPicker.noResults}
+ </Text>
+ </View>
+ }
+ />
+ )}
+ </View>
+ );
+}
+
+function createStyles({ themeColors }: { themeColors: ThemeColors }) {
+ return StyleSheet.create({
+ content: {
+ flexShrink: 1,
+ },
+ header: {
+ flexDirection: 'row',
+ alignItems: 'center',
+ paddingHorizontal: 20,
+ marginBottom: 12,
+ gap: 12,
+ },
+ title: {
+ flex: 1,
+ fontSize: 20,
+ fontWeight: '600',
+ color: themeColors.foreground,
+ },
+ closeButton: {
+ width: 44,
+ height: 44,
+ alignItems: 'center',
+ justifyContent: 'center',
+ },
+ searchContainer: {
+ flexDirection: 'row',
+ alignItems: 'center',
+ gap: 8,
+ marginHorizontal: 20,
+ marginBottom: 12,
+ paddingHorizontal: 12,
+ borderRadius: 8,
+ borderWidth: 1,
+ borderColor: themeColors.border,
+ backgroundColor: themeColors.background,
+ },
+ searchInput: {
+ flex: 1,
+ paddingVertical: 12,
+ fontSize: 16,
+ color: themeColors.foreground,
+ },
+ list: {
+ flexGrow: 0,
+ },
+ tagRow: {
+ flexDirection: 'row',
+ alignItems: 'center',
+ gap: 12,
+ paddingHorizontal: 20,
+ paddingVertical: 14,
+ minHeight: 52,
+ },
+ selectedRow: {
+ backgroundColor: themeColors.muted,
+ },
+ tagDot: {
+ width: 10,
+ height: 10,
+ borderRadius: 5,
+ },
+ tagName: {
+ flex: 1,
+ fontSize: 16,
+ color: themeColors.foreground,
+ },
+ statusContainer: {
+ padding: 24,
+ alignItems: 'center',
+ gap: 8,
+ },
+ statusText: {
+ color: themeColors.mutedForeground,
+ fontSize: 14,
+ textAlign: 'center',
+ },
+ retryButton: {
+ padding: 12,
+ },
+ retryText: {
+ color: themeColors.primary,
+ fontWeight: '600',
+ fontSize: 16,
+ },
+ error: {
+ color: themeColors.destructive,
+ marginHorizontal: 20,
+ marginBottom: 12,
+ fontSize: 14,
+ },
+ });
+}
diff --git a/apps/mobile/src/modules/documents/documents.queries.ts b/apps/mobile/src/modules/documents/documents.queries.ts
index 426a036e..c96970ea 100644
--- a/apps/mobile/src/modules/documents/documents.queries.ts
+++ b/apps/mobile/src/modules/documents/documents.queries.ts
@@ -1,9 +1,25 @@
import type { ApiClient } from '../api/api.client';
-import { infiniteQueryOptions } from '@tanstack/react-query';
-import { fetchOrganizationDocuments } from './documents.services';
+import { infiniteQueryOptions, queryOptions } from '@tanstack/react-query';
+import { fetchDocument, fetchOrganizationDocuments } from './documents.services';
const pageSize = 20;
+export function documentQueryOptions({
+ organizationId,
+ documentId,
+ apiClient,
+}: {
+ organizationId: string;
+ documentId: string;
+ apiClient: ApiClient;
+}) {
+ return queryOptions({
+ queryKey: ['organizations', organizationId, 'documents', documentId],
+ queryFn: async () => fetchDocument({ organizationId, documentId, apiClient }),
+ enabled: organizationId != null && documentId != null,
+ });
+}
+
export function organizationDocumentsInfiniteQueryOptions({
organizationId,
apiClient,
diff --git a/apps/mobile/src/modules/documents/documents.types.ts b/apps/mobile/src/modules/documents/documents.types.ts
index e40df4f4..03400fbc 100644
--- a/apps/mobile/src/modules/documents/documents.types.ts
+++ b/apps/mobile/src/modules/documents/documents.types.ts
@@ -1,3 +1,5 @@
+import type { Tag } from '../tags/tags.types';
+
export type DocumentCustomProperty = {
key: string;
name: string;
@@ -17,9 +19,5 @@ export type Document = {
localUri: string | undefined;
notes?: string | null;
customProperties?: DocumentCustomProperty[];
- tags: {
- id: string;
- name: string;
- color: string;
- }[];
+ tags: Tag[];
};
diff --git a/apps/mobile/src/modules/documents/screens/document-details.screen.tsx b/apps/mobile/src/modules/documents/screens/document-details.screen.tsx
index 0a110cba..f25930c9 100644
--- a/apps/mobile/src/modules/documents/screens/document-details.screen.tsx
+++ b/apps/mobile/src/modules/documents/screens/document-details.screen.tsx
@@ -21,8 +21,10 @@ import { useAppTranslations } from '@/modules/i18n/hooks/use-app-translations';
import { useFormatters } from '@/modules/i18n/hooks/use-formatters';
import { useApiClient, useAuthClient } from '@/modules/api/providers/api.provider';
import { DocumentActionSheet } from '@/modules/documents/components/document-action-sheet';
+import { DocumentTagsDrawer } from '@/modules/documents/components/document-tags-drawer';
import { formatCustomPropertyValue } from '@/modules/documents/documents.models';
-import { fetchDocument, fetchDocumentFile } from '@/modules/documents/documents.services';
+import { documentQueryOptions } from '@/modules/documents/documents.queries';
+import { fetchDocumentFile } from '@/modules/documents/documents.services';
import { Tag } from '@/modules/tags/components/tag';
import { Icon } from '@/modules/ui/components/icon';
import { useAlert } from '@/modules/ui/providers/alert-provider';
@@ -84,15 +86,12 @@ export function DocumentDetailsScreen() {
const apiClient = useApiClient();
const authClient = useAuthClient();
const [isActionSheetVisible, setIsActionSheetVisible] = useState(false);
+ const [isTagsDrawerVisible, setIsTagsDrawerVisible] = useState(false);
const [pendingAction, setPendingAction] = useState<'download' | 'share' | undefined>(undefined);
const { documentId, organizationId } = params;
- const documentQuery = useQuery({
- queryKey: ['organizations', organizationId, 'documents', documentId],
- queryFn: async () => fetchDocument({ organizationId, documentId, apiClient }),
- enabled: organizationId != null && documentId != null,
- });
+ const documentQuery = useQuery(documentQueryOptions({ organizationId, documentId, apiClient }));
if (organizationId == null || documentId == null) {
showAlert({
@@ -272,16 +271,29 @@ export function DocumentDetailsScreen() {
</TouchableOpacity>
</View>
- {document.tags.length > 0 && (
- <View style={styles.section}>
- <Text style={styles.sectionTitle}>{t.documents.tags}</Text>
+ <View style={styles.section}>
+ <View style={styles.sectionHeader}>
+ <Text style={[styles.sectionTitle, styles.tagsTitle]}>{t.documents.tags}</Text>
+ <TouchableOpacity
+ style={styles.manageTagsButton}
+ onPress={() => setIsTagsDrawerVisible(true)}
+ accessibilityRole="button"
+ accessibilityLabel={t.documents.manageTags}
+ >
+ <Icon name="tag" size={16} color={themeColors.primary} />
+ <Text style={styles.manageTagsText}>{t.documents.manageTags}</Text>
+ </TouchableOpacity>
+ </View>
+ {document.tags.length > 0 ? (
<View style={styles.tagsContainer}>
{document.tags.map((tag) => (
<Tag key={tag.id} name={tag.name} color={tag.color} />
))}
</View>
- </View>
- )}
+ ) : (
+ <Text style={styles.heroMeta}>{t.documents.tagPicker.noTags}</Text>
+ )}
+ </View>
{hasNotes && (
<View style={styles.section}>
@@ -379,6 +391,13 @@ export function DocumentDetailsScreen() {
onDeleted={() => router.back()}
/>
+ <DocumentTagsDrawer
+ visible={isTagsDrawerVisible}
+ organizationId={organizationId}
+ documentId={documentId}
+ onClose={() => setIsTagsDrawerVisible(false)}
+ />
+
{renderContent()}
</SafeAreaView>
);
@@ -484,6 +503,29 @@ function createStyles({ themeColors }: { themeColors: ThemeColors }) {
letterSpacing: 0.5,
marginBottom: 8,
},
+ sectionHeader: {
+ flexDirection: 'row',
+ alignItems: 'center',
+ justifyContent: 'space-between',
+ gap: 12,
+ marginBottom: 8,
+ },
+ tagsTitle: {
+ marginBottom: 0,
+ },
+ manageTagsButton: {
+ flexShrink: 1,
+ flexDirection: 'row',
+ alignItems: 'center',
+ gap: 6,
+ paddingVertical: 12,
+ },
+ manageTagsText: {
+ flexShrink: 1,
+ color: themeColors.primary,
+ fontSize: 14,
+ fontWeight: '600',
+ },
tagsContainer: {
flexDirection: 'row',
flexWrap: 'wrap',
diff --git a/apps/mobile/src/modules/i18n/translations/de.ts b/apps/mobile/src/modules/i18n/translations/de.ts
index 4110a36a..257bca20 100644
--- a/apps/mobile/src/modules/i18n/translations/de.ts
+++ b/apps/mobile/src/modules/i18n/translations/de.ts
@@ -74,6 +74,17 @@ export const de = {
fallbackName: 'Dokument',
downloaded: 'Heruntergeladen',
tags: 'Tags',
+ manageTags: 'Tags verwalten',
+ tagPicker: {
+ searchPlaceholder: 'Tags suchen',
+ loading: 'Tags werden geladen…',
+ updating: 'Tags werden aktualisiert…',
+ loadFailed: 'Tags konnten nicht geladen werden. Bitte versuchen Sie es erneut.',
+ updateFailed: 'Tags konnten nicht aktualisiert werden. Bitte versuchen Sie es erneut.',
+ empty: 'In dieser Organisation gibt es noch keine Tags.',
+ noResults: 'Keine passenden Tags.',
+ noTags: 'Keine Tags zugewiesen.',
+ },
notes: 'Notizen',
size: 'Größe',
type: 'Typ',
diff --git a/apps/mobile/src/modules/i18n/translations/en.ts b/apps/mobile/src/modules/i18n/translations/en.ts
index 9b181791..c19116eb 100644
--- a/apps/mobile/src/modules/i18n/translations/en.ts
+++ b/apps/mobile/src/modules/i18n/translations/en.ts
@@ -73,6 +73,17 @@ export const en = {
fallbackName: 'Document',
downloaded: 'Downloaded',
tags: 'Tags',
+ manageTags: 'Manage tags',
+ tagPicker: {
+ searchPlaceholder: 'Search tags',
+ loading: 'Loading tags...',
+ updating: 'Updating tags...',
+ loadFailed: 'Failed to load tags. Please try again.',
+ updateFailed: 'Failed to update tags. Please try again.',
+ empty: 'No tags in this organization yet.',
+ noResults: 'No matching tags.',
+ noTags: 'No tags assigned.',
+ },
notes: 'Notes',
size: 'Size',
type: 'Type',
diff --git a/apps/mobile/src/modules/i18n/translations/es.ts b/apps/mobile/src/modules/i18n/translations/es.ts
index 19d6e1ae..a255b128 100644
--- a/apps/mobile/src/modules/i18n/translations/es.ts
+++ b/apps/mobile/src/modules/i18n/translations/es.ts
@@ -73,6 +73,17 @@ export const es = {
fallbackName: 'Documento',
downloaded: 'Descargado',
tags: 'Etiquetas',
+ manageTags: 'Gestionar etiquetas',
+ tagPicker: {
+ searchPlaceholder: 'Buscar etiquetas',
+ loading: 'Cargando etiquetas…',
+ updating: 'Actualizando etiquetas…',
+ loadFailed: 'No se han podido cargar las etiquetas. Inténtalo de nuevo.',
+ updateFailed: 'No se han podido actualizar las etiquetas. Inténtalo de nuevo.',
+ empty: 'Esta organización aún no tiene etiquetas.',
+ noResults: 'No hay etiquetas coincidentes.',
+ noTags: 'No hay etiquetas asignadas.',
+ },
notes: 'Notas',
size: 'Tamaño',
type: 'Tipo',
diff --git a/apps/mobile/src/modules/i18n/translations/fr.ts b/apps/mobile/src/modules/i18n/translations/fr.ts
index 263e40cb..13aea273 100644
--- a/apps/mobile/src/modules/i18n/translations/fr.ts
+++ b/apps/mobile/src/modules/i18n/translations/fr.ts
@@ -73,6 +73,17 @@ export const fr = {
fallbackName: 'Document',
downloaded: 'Téléchargé',
tags: 'Étiquettes',
+ manageTags: 'Gérer les étiquettes',
+ tagPicker: {
+ searchPlaceholder: 'Rechercher des étiquettes',
+ loading: 'Chargement des étiquettes…',
+ updating: 'Mise à jour des étiquettes…',
+ loadFailed: 'Impossible de charger les étiquettes. Veuillez réessayer.',
+ updateFailed: 'Impossible de modifier les étiquettes. Veuillez réessayer.',
+ empty: 'Cette organisation ne contient pas encore d’étiquettes.',
+ noResults: 'Aucune étiquette correspondante.',
+ noTags: 'Aucune étiquette attribuée.',
+ },
notes: 'Notes',
size: 'Taille',
type: 'Type',
diff --git a/apps/mobile/src/modules/tags/tags.queries.test.ts b/apps/mobile/src/modules/tags/tags.queries.test.ts
new file mode 100644
index 00000000..b035e905
--- /dev/null
+++ b/apps/mobile/src/modules/tags/tags.queries.test.ts
@@ -0,0 +1,263 @@
+import type { ApiClient } from '../api/api.client';
+import type { CoerceDates } from '../api/api.models';
+import type { Document } from '../documents/documents.types';
+import { MutationObserver, QueryClient, QueryObserver } from '@tanstack/react-query';
+import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest';
+import {
+ documentTagMutationKey,
+ documentTagMutationOptions,
+ organizationTagsQueryOptions,
+} from './tags.queries';
+
+const scope = { organizationId: 'organization-1', documentId: 'document-1' };
+const documentKey = ['organizations', scope.organizationId, 'documents', scope.documentId];
+const tag = { id: 'tag-1', name: 'Invoice', color: '#ff0000' };
+const otherTag = { id: 'tag-2', name: 'Paid', color: '#00ff00' };
+
+function createDocument(tags: Document['tags'] = []): CoerceDates<Document> {
+ return {
+ id: scope.documentId,
+ organizationId: scope.organizationId,
+ name: 'Invoice.pdf',
+ mimeType: 'application/pdf',
+ originalSize: 100,
+ createdAt: new Date('2026-01-01'),
+ updatedAt: new Date('2026-01-01'),
+ localUri: undefined,
+ tags,
+ };
+}
+
+describe('document tag queries and mutations', () => {
+ let queryClient: QueryClient;
+ const apiClient = vi.fn<ApiClient>();
+
+ beforeEach(() => {
+ apiClient.mockReset();
+ queryClient = new QueryClient({
+ defaultOptions: {
+ queries: { retry: false, gcTime: Infinity },
+ mutations: { retry: false, gcTime: Infinity },
+ },
+ });
+ queryClient.setQueryData(documentKey, { document: createDocument() });
+ });
+
+ afterEach(() => {
+ queryClient.clear();
+ });
+
+ function createMutation() {
+ return new MutationObserver(
+ queryClient,
+ documentTagMutationOptions({ ...scope, apiClient: apiClient as ApiClient, queryClient }),
+ );
+ }
+
+ function getDocument() {
+ return queryClient.getQueryData<{ document: CoerceDates<Document> }>(documentKey)?.document;
+ }
+
+ test('fetches available tags only from the document organization', async () => {
+ apiClient.mockResolvedValue({ tags: [tag, otherTag] });
+ const options = organizationTagsQueryOptions({
+ organizationId: scope.organizationId,
+ apiClient: apiClient as ApiClient,
+ });
+ const data = await queryClient.fetchQuery(options);
+
+ expect(data.tags).toEqual([tag, otherTag]);
+ expect(apiClient).toHaveBeenCalledExactlyOnceWith({
+ method: 'GET',
+ path: '/api/organizations/organization-1/tags',
+ });
+ expect(queryClient.getQueryData(['organizations', 'organization-2', 'tags'])).toBeUndefined();
+ });
+
+ test('selects immediately, then adds the tag through the API', async () => {
+ const request = Promise.withResolvers<unknown>();
+ apiClient.mockReturnValueOnce(request.promise);
+ const mutation = createMutation();
+ const update = mutation.mutate({ tag, selected: true });
+
+ await vi.waitFor(() => expect(getDocument()?.tags).toEqual([tag]));
+ expect(queryClient.isMutating({ mutationKey: documentTagMutationKey(scope) })).toBe(1);
+ expect(mutation.getCurrentResult().isPending).toBe(true);
+ expect(apiClient).toHaveBeenCalledExactlyOnceWith({
+ method: 'POST',
+ path: '/api/organizations/organization-1/documents/document-1/tags',
+ body: { tagId: tag.id },
+ });
+
+ request.resolve(undefined);
+ await update;
+ expect(getDocument()?.tags).toEqual([tag]);
+ expect(mutation.getCurrentResult().isSuccess).toBe(true);
+ expect(queryClient.isMutating({ mutationKey: documentTagMutationKey(scope) })).toBe(0);
+ });
+
+ test('removes only the selected tag and leaves other tags assigned', async () => {
+ queryClient.setQueryData(documentKey, { document: createDocument([tag, otherTag]) });
+ const mutation = createMutation();
+ await mutation.mutate({ tag, selected: false });
+
+ expect(getDocument()?.tags).toEqual([otherTag]);
+ expect(apiClient).toHaveBeenCalledExactlyOnceWith({
+ method: 'DELETE',
+ path: '/api/organizations/organization-1/documents/document-1/tags/tag-1',
+ });
+ // The same row can be selected again after a completed removal.
+ await mutation.mutate({ tag, selected: true });
+ expect(getDocument()?.tags).toEqual([otherTag, tag]);
+ });
+
+ test('does not duplicate an already assigned tag', async () => {
+ queryClient.setQueryData(documentKey, { document: createDocument([tag, otherTag]) });
+ await createMutation().mutate({ tag, selected: true });
+ expect(getDocument()?.tags.filter(({ id }) => id === tag.id)).toHaveLength(1);
+ });
+
+ test.each([true, false])(
+ 'rolls back failed changes and allows retry (selected: %s)',
+ async (selected) => {
+ const originalTags = selected ? [otherTag] : [tag, otherTag];
+ queryClient.setQueryData(documentKey, { document: createDocument(originalTags) });
+ apiClient.mockRejectedValueOnce(new Error('Network unavailable'));
+ const mutation = createMutation();
+
+ await expect(mutation.mutate({ tag, selected })).rejects.toThrow('Network unavailable');
+ expect(getDocument()?.tags).toEqual(originalTags);
+ expect(mutation.getCurrentResult().isError).toBe(true);
+
+ await mutation.mutate({ tag, selected });
+ expect(mutation.getCurrentResult().isSuccess).toBe(true);
+ expect(getDocument()?.tags).toEqual(selected ? [otherTag, tag] : [otherTag]);
+ },
+ );
+
+ test('refreshes document details, lists and searches without invalidating other organizations', async () => {
+ const affectedKeys = [
+ documentKey,
+ ['organizations', scope.organizationId, 'documents', 'infinite', { searchQuery: undefined }],
+ [
+ 'organizations',
+ scope.organizationId,
+ 'documents',
+ 'infinite',
+ { searchQuery: 'tag:Invoice' },
+ ],
+ ];
+ const unrelatedKeys = [
+ ['organizations', 'organization-2', 'documents', 'document-1'],
+ ['organizations', scope.organizationId, 'tags'],
+ [...documentKey, 'file'],
+ ];
+ for (const key of [...affectedKeys.slice(1), ...unrelatedKeys]) {
+ queryClient.setQueryData(key, {});
+ }
+
+ await createMutation().mutate({ tag, selected: true });
+ for (const key of affectedKeys) {
+ expect(queryClient.getQueryState(key)?.isInvalidated).toBe(true);
+ }
+ for (const key of unrelatedKeys) {
+ expect(queryClient.getQueryState(key)?.isInvalidated).toBe(false);
+ }
+ });
+
+ test('does not download the binary again when tagging from the document viewer', async () => {
+ const fileKey = [...documentKey, 'file'];
+ const downloadFile = vi.fn().mockResolvedValue({ uri: 'file:///invoice.pdf' });
+ queryClient.setQueryData(fileKey, { uri: 'file:///invoice.pdf' });
+ const observer = new QueryObserver(queryClient, {
+ queryKey: fileKey,
+ queryFn: downloadFile,
+ staleTime: Infinity,
+ });
+ const unsubscribe = observer.subscribe(() => {});
+
+ await createMutation().mutate({ tag, selected: true });
+ expect(downloadFile).not.toHaveBeenCalled();
+ expect(queryClient.getQueryState(fileKey)?.isInvalidated).toBe(false);
+ unsubscribe();
+ });
+
+ test('waits for active document refetches before allowing another update', async () => {
+ const refetch = Promise.withResolvers<{ document: CoerceDates<Document> }>();
+ const observer = new QueryObserver(queryClient, {
+ queryKey: documentKey,
+ queryFn: async () => refetch.promise,
+ staleTime: Infinity,
+ });
+ const unsubscribe = observer.subscribe(() => {});
+ const mutation = createMutation();
+ const update = mutation.mutate({ tag, selected: true });
+
+ await vi.waitFor(() => expect(observer.getCurrentResult().isFetching).toBe(true));
+ expect(mutation.getCurrentResult().isPending).toBe(true);
+ refetch.resolve({ document: createDocument([tag]) });
+ await update;
+ expect(mutation.getCurrentResult().isSuccess).toBe(true);
+ expect(getDocument()?.tags).toEqual([tag]);
+ unsubscribe();
+ });
+
+ test('cancels stale document fetches before applying the immediate selection', async () => {
+ const staleFetch = Promise.withResolvers<{ document: CoerceDates<Document> }>();
+ const request = Promise.withResolvers<unknown>();
+ const fetchDocument = vi
+ .fn()
+ .mockReturnValueOnce(staleFetch.promise)
+ .mockResolvedValue({ document: createDocument([tag]) });
+ const observer = new QueryObserver(queryClient, {
+ queryKey: documentKey,
+ queryFn: fetchDocument,
+ staleTime: Infinity,
+ });
+ const unsubscribe = observer.subscribe(() => {});
+ const refetch = observer.refetch();
+ apiClient.mockReturnValueOnce(request.promise);
+ const update = createMutation().mutate({ tag, selected: true });
+
+ await vi.waitFor(() => expect(getDocument()?.tags).toEqual([tag]));
+ staleFetch.resolve({ document: createDocument() });
+ await refetch;
+ expect(getDocument()?.tags).toEqual([tag]);
+
+ request.resolve(undefined);
+ await update;
+ expect(getDocument()?.tags).toEqual([tag]);
+ unsubscribe();
+ });
+
+ test('rolls back only tags without overwriting unrelated document changes', async () => {
+ const request = Promise.withResolvers<unknown>();
+ apiClient.mockReturnValueOnce(request.promise);
+ const update = createMutation().mutate({ tag, selected: true });
+ const failedUpdate = expect(update).rejects.toThrow('Update failed');
+
+ await vi.waitFor(() => expect(getDocument()?.tags).toEqual([tag]));
+ queryClient.setQueryData(documentKey, {
+ document: { ...getDocument(), name: 'Renamed.pdf' },
+ });
+ request.reject(new Error('Update failed'));
+ await failedUpdate;
+
+ expect(getDocument()?.tags).toEqual([]);
+ expect(getDocument()?.name).toBe('Renamed.pdf');
+ });
+
+ test('keeps a successful selection if the subsequent refetch fails', async () => {
+ const observer = new QueryObserver(queryClient, {
+ queryKey: documentKey,
+ queryFn: async () => {
+ throw new Error('Refetch failed');
+ },
+ staleTime: Infinity,
+ });
+ const unsubscribe = observer.subscribe(() => {});
+ await createMutation().mutate({ tag, selected: true });
+ expect(getDocument()?.tags).toEqual([tag]);
+ unsubscribe();
+ });
+});
diff --git a/apps/mobile/src/modules/tags/tags.queries.ts b/apps/mobile/src/modules/tags/tags.queries.ts
new file mode 100644
index 00000000..cb7b8bf4
--- /dev/null
+++ b/apps/mobile/src/modules/tags/tags.queries.ts
@@ -0,0 +1,79 @@
+import type { QueryClient } from '@tanstack/react-query';
+import type { ApiClient } from '../api/api.client';
+import type { fetchDocument } from '../documents/documents.services';
+import type { Tag } from './tags.types';
+import { mutationOptions, queryOptions } from '@tanstack/react-query';
+import { addTagToDocument, fetchTags, removeTagFromDocument } from './tags.services';
+
+type DocumentData = Awaited<ReturnType<typeof fetchDocument>>;
+type DocumentScope = { organizationId: string; documentId: string };
+
+export function documentTagMutationKey({ organizationId, documentId }: DocumentScope) {
+ return ['organizations', organizationId, 'documents', documentId, 'tags'];
+}
+
+export function organizationTagsQueryOptions({
+ organizationId,
+ apiClient,
+}: {
+ organizationId: string;
+ apiClient: ApiClient;
+}) {
+ return queryOptions({
+ queryKey: ['organizations', organizationId, 'tags'],
+ queryFn: async () => fetchTags({ organizationId, apiClient }),
+ staleTime: 0,
+ });
+}
+
+export function documentTagMutationOptions({
+ organizationId,
+ documentId,
+ apiClient,
+ queryClient,
+}: DocumentScope & { apiClient: ApiClient; queryClient: QueryClient }) {
+ const queryKey = ['organizations', organizationId, 'documents', documentId];
+
+ return mutationOptions({
+ mutationKey: documentTagMutationKey({ organizationId, documentId }),
+ mutationFn: async ({ tag, selected }: { tag: Tag; selected: boolean }) => {
+ const updateTag = selected ? addTagToDocument : removeTagFromDocument;
+ await updateTag({ organizationId, documentId, tagId: tag.id, apiClient });
+ },
+ onMutate: async ({ tag, selected }) => {
+ // Prevent a background refetch from overwriting the immediate selection.
+ await queryClient.cancelQueries({ queryKey, exact: true });
+ const previousTags = queryClient.getQueryData<DocumentData>(queryKey)?.document.tags;
+
+ queryClient.setQueryData<DocumentData>(queryKey, (data) => {
+ if (!data) {
+ return data;
+ }
+
+ const tags = data.document.tags.filter(({ id }) => id !== tag.id);
+ return {
+ ...data,
+ document: { ...data.document, tags: selected ? [...tags, tag] : tags },
+ };
+ });
+
+ return { previousTags };
+ },
+ onError: (_error, _variables, context) => {
+ const previousTags = context?.previousTags;
+ if (previousTags) {
+ queryClient.setQueryData<DocumentData>(queryKey, (data) =>
+ data ? { ...data, document: { ...data.document, tags: previousTags } } : data,
+ );
+ }
+ },
+ // Refresh details, lists and tag-filtered searches, even if the drawer unmounts.
+ onSettled: async () => {
+ await queryClient.invalidateQueries({
+ queryKey: ['organizations', organizationId, 'documents'],
+ // Tag changes do not affect the binary cached by the document viewer.
+ predicate: (query) => query.queryKey[4] !== 'file',
+ });
+ },
+ });
+}
diff --git a/apps/mobile/src/modules/tags/tags.services.ts b/apps/mobile/src/modules/tags/tags.services.ts
new file mode 100644
index 00000000..def5f29e
--- /dev/null
+++ b/apps/mobile/src/modules/tags/tags.services.ts
@@ -0,0 +1,47 @@
+import type { ApiClient } from '../api/api.client';
+import type { Tag } from './tags.types';
+
+export async function fetchTags({
+ organizationId,
+ apiClient,
+}: {
+ organizationId: string;
+ apiClient: ApiClient;
+}) {
+ return apiClient<{ tags: Tag[] }>({
+ method: 'GET',
+ path: `/api/organizations/${organizationId}/tags`,
+ });
+}
+
+type DocumentTagOptions = {
+ organizationId: string;
+ documentId: string;
+ tagId: string;
+ apiClient: ApiClient;
+};
+
+export async function addTagToDocument({
+ organizationId,
+ documentId,
+ tagId,
+ apiClient,
+}: DocumentTagOptions) {
+ await apiClient({
+ method: 'POST',
+ path: `/api/organizations/${organizationId}/documents/${documentId}/tags`,
+ body: { tagId },
+ });
+}
+
+export async function removeTagFromDocument({
+ organizationId,
+ documentId,
+ tagId,
+ apiClient,
+}: DocumentTagOptions) {
+ await apiClient({
+ method: 'DELETE',
+ path: `/api/organizations/${organizationId}/documents/${documentId}/tags/${tagId}`,
+ });
+}
diff --git a/apps/mobile/src/modules/tags/tags.types.ts b/apps/mobile/src/modules/tags/tags.types.ts
new file mode 100644
index 00000000..a105619a
--- /dev/null
+++ b/apps/mobile/src/modules/tags/tags.types.ts
@@ -0,0 +1,5 @@
+export type Tag = {
+ id: string;
+ name: string;
+ color: string;
+};
diff --git a/apps/mobile/src/modules/ui/components/bottom-drawer.tsx b/apps/mobile/src/modules/ui/components/bottom-drawer.tsx
new file mode 100644
index 00000000..0d1f77b1
--- /dev/null
+++ b/apps/mobile/src/modules/ui/components/bottom-drawer.tsx
@@ -0,0 +1,76 @@
+import type { ReactNode } from 'react';
+import type { ThemeColors } from '../theme.constants';
+import { KeyboardAvoidingView, Modal, Platform, Pressable, StyleSheet, View } from 'react-native';
+import { useSafeAreaInsets } from 'react-native-safe-area-context';
+import { useAppTranslations } from '@/modules/i18n/hooks/use-app-translations';
+import { useThemeColor } from '../providers/use-theme-color';
+
+export function BottomDrawer({
+ visible,
+ onClose,
+ dismissible = true,
+ children,
+}: {
+ visible: boolean;
+ onClose: () => void;
+ dismissible?: boolean;
+ children: ReactNode;
+}) {
+ const t = useAppTranslations();
+ const themeColors = useThemeColor();
+ const insets = useSafeAreaInsets();
+ const styles = createStyles({ themeColors });
+
+ const handleClose = () => {
+ if (dismissible) {
+ onClose();
+ }
+ };
+
+ return (
+ <Modal visible={visible} transparent animationType="slide" onRequestClose={handleClose}>
+ <KeyboardAvoidingView
+ style={styles.overlay}
+ behavior={Platform.OS === 'ios' ? 'padding' : 'height'}
+ >
+ <Pressable
+ style={StyleSheet.absoluteFill}
+ onPress={handleClose}
+ accessibilityRole="button"
+ accessibilityLabel={t.common.close}
+ accessibilityState={{ disabled: !dismissible }}
+ disabled={!dismissible}
+ />
+ <View style={[styles.sheet, { paddingBottom: Math.max(insets.bottom, 16) }]}>
+ <View style={styles.handleBar} />
+ {children}
+ </View>
+ </KeyboardAvoidingView>
+ </Modal>
+ );
+}
+
+function createStyles({ themeColors }: { themeColors: ThemeColors }) {
+ return StyleSheet.create({
+ overlay: {
+ flex: 1,
+ backgroundColor: 'rgba(0, 0, 0, 0.5)',
+ justifyContent: 'flex-end',
+ },
+ sheet: {
+ maxHeight: '85%',
+ backgroundColor: themeColors.secondaryBackground,
+ borderTopLeftRadius: 16,
+ borderTopRightRadius: 16,
+ },
+ handleBar: {
+ width: 36,
+ height: 4,
+ backgroundColor: themeColors.border,
+ borderRadius: 2,
+ alignSelf: 'center',
+ marginTop: 8,
+ marginBottom: 16,
+ },
+ });
+}