The minimalistic document archiving platform.
refactor(mobile): cleaned up the document viewer component (#839)
Corentin Thomassetc9d1d64b91f1
diff --git a/apps/mobile/src/modules/documents/screens/document-view.screen.tsx b/apps/mobile/src/modules/documents/screens/document-view.screen.tsxindex 502ca953..9665e9fc 100644--- a/apps/mobile/src/modules/documents/screens/document-view.screen.tsx+++ b/apps/mobile/src/modules/documents/screens/document-view.screen.tsx@@ -5,16 +5,8 @@ import { MaterialCommunityIcons } from '@expo/vector-icons';import { useQuery } from '@tanstack/react-query';import * as FileSystem from 'expo-file-system/legacy';import { useLocalSearchParams, useRouter } from 'expo-router';-import React, { useState } from 'react';-import {- ActivityIndicator,- Image,- ScrollView,- StyleSheet,- Text,- TouchableOpacity,- View,-} from 'react-native';+import { useState } from 'react';+import { ActivityIndicator, Image, ScrollView, StyleSheet, Text, TouchableOpacity, View } from 'react-native';import Pdf from 'react-native-pdf';import { SafeAreaView } from 'react-native-safe-area-context';import { useApiClient, useAuthClient } from '@/modules/api/providers/api.provider';@@ -36,12 +28,91 @@ const textMimeTypes = new Set(['application/javascript','application/x-yaml','application/yaml',+ 'application/xhtml+xml',]);function isTextBasedFile(mimeType: string): boolean {return mimeType.startsWith('text/') || textMimeTypes.has(mimeType);}+function DocumentViewer({ file, styles, themeColors, onError }: {+ file: DocumentFile;+ styles: ReturnType<typeof createStyles>;+ themeColors: ThemeColors;+ onError: (message: string) => void;+}) {+ const { mimeType } = file.doc;++ if (mimeType.startsWith('image/')) {+ return <Image source={{ uri: file.uri }} style={styles.documentViewer} />;+ }++ if (mimeType === 'application/pdf') {+ return (+ source={{ uri: file.uri, cache: true }}+ style={styles.documentViewer}+ onError={(error) => {+ console.error('PDF error:', error);+ onError('Failed to load PDF');+ }}+ enablePaging+ horizontal={false}+ enableAnnotationRendering+ fitPolicy={0}+ spacing={10}+ />+ );+ }++ if (file.textContent != null) {+ return (+ <ScrollView style={styles.textViewer} contentContainerStyle={styles.textViewerContent}>+ <Text style={styles.textContent} selectable>+ {file.textContent}+ </Text>+ </ScrollView>+ );+ }++ return (+ <View style={styles.centeredContainer}>+ <MaterialCommunityIcons name="file-question-outline" size={64} color={themeColors.mutedForeground} />+ <Text style={styles.centeredTitle}>Preview not available</Text>+ <Text style={styles.centeredText}>This file type cannot be previewed in the app</Text>+ </View>+ );+}++function LoadingState({ styles, themeColors }: { styles: ReturnType<typeof createStyles>; themeColors: ThemeColors }) {+ return (+ <View style={styles.centeredContainer}>+ <ActivityIndicator size="large" color={themeColors.primary} />+ <Text style={styles.centeredText}>Loading document...</Text>+ </View>+ );+}++function ErrorState({ styles, themeColors, onRetry, onGoBack }: {+ styles: ReturnType<typeof createStyles>;+ themeColors: ThemeColors;+ onRetry: () => void;+ onGoBack: () => void;+}) {+ return (+ <View style={styles.centeredContainer}>+ <MaterialCommunityIcons name="file-alert-outline" size={64} color={themeColors.mutedForeground} />+ <Text style={styles.centeredTitle}>Failed to load document</Text>+ <TouchableOpacity style={styles.actionButton} onPress={onRetry}>+ <Text style={styles.actionButtonText}>Retry</Text>+ </TouchableOpacity>+ <TouchableOpacity style={styles.actionButton} onPress={onGoBack}>+ <Text style={styles.actionButtonText}>Go Back</Text>+ </TouchableOpacity>+ </View>+ );+}+export default function DocumentViewScreen() {const router = useRouter();const params = useLocalSearchParams<{ documentId: string; organizationId: string }>();@@ -50,18 +121,21 @@ export default function DocumentViewScreen() {const { showAlert } = useAlert();const apiClient = useApiClient();const authClient = useAuthClient();- const { documentId, organizationId } = params;const [isActionSheetVisible, setIsActionSheetVisible] = useState(false);+ const { documentId, organizationId } = params;++ if (organizationId == null || documentId == null) {+ showAlert({+ title: 'Error',+ message: 'Organization ID and Document ID are required',+ });+ return null;+ }+const documentQuery = useQuery({queryKey: ['organizations', organizationId, 'documents', documentId],- queryFn: async () => {- if (organizationId == null || documentId == null) {- throw new Error('Organization ID and Document ID are required');- }- return fetchDocument({ organizationId, documentId, apiClient });- },- enabled: organizationId != null && documentId != null,+ queryFn: async () => fetchDocument({ organizationId, documentId, apiClient }),});const documentFileQuery = useQuery({@@ -99,145 +173,69 @@ export default function DocumentViewScreen() {enabled: documentQuery.isSuccess && documentQuery.data != null,});- const renderHeader = (documentName: string) => {- return (- <View style={styles.header}>- <TouchableOpacity- style={styles.headerButton}- onPress={() => router.back()}- >- <MaterialCommunityIcons- name="close"- size={24}- color={themeColors.foreground}- />- </TouchableOpacity>- <Text style={styles.headerTitle} numberOfLines={1}>- {documentName}- </Text>- <TouchableOpacity- style={styles.headerButton}- onPress={() => setIsActionSheetVisible(true)}- >- <MaterialCommunityIcons- name="dots-vertical"- size={24}- color={themeColors.foreground}- />- </TouchableOpacity>- </View>- );+ const isLoading = documentQuery.isLoading || documentFileQuery.isLoading;+ const error = documentQuery.error ?? documentFileQuery.error;+ const documentFile = documentFileQuery.data;+ const documentName = documentFile?.doc.name ?? 'Document';++ const handleShowError = (message: string) => {+ showAlert({ title: 'Error', message });};- const renderDocumentFile = (file: DocumentFile) => {- if (file.doc.mimeType.startsWith('image/')) {- return (- <Image- source={{ uri: file.uri }}- style={styles.pdfViewer}- />- );+ const renderContent = () => {+ if (isLoading) {+ return <LoadingState styles={styles} themeColors={themeColors} />;}- if (file.doc.mimeType.startsWith('application/pdf')) {++ if (error != null) {return (- source={{ uri: file.uri, cache: true }}- style={styles.pdfViewer}- onError={(error) => {- console.error('PDF error:', error);- showAlert({- title: 'Error',- message: 'Failed to load PDF',- });- }}- enablePaging={true}- horizontal={false}- enableAnnotationRendering={true}- fitPolicy={0}- spacing={10}+ <ErrorState+ styles={styles}+ themeColors={themeColors}+ onRetry={() => void documentQuery.refetch()}+ onGoBack={() => router.back()}/>);}- if (file.textContent != null) {++ if (documentFile != null) {return (- <ScrollView- style={styles.textViewer}- contentContainerStyle={styles.textViewerContent}- >- <Text style={styles.textContent} selectable>- {file.textContent}- </Text>- </ScrollView>+ <View style={styles.documentContainer}>+ <DocumentViewer+ file={documentFile}+ styles={styles}+ themeColors={themeColors}+ onError={handleShowError}+ />+ </View>);}- return (- <View style={styles.unsupportedContainer}>- <MaterialCommunityIcons- name="file-question-outline"- size={64}- color={themeColors.mutedForeground}- />- <Text style={styles.unsupportedTitle}>Preview not available</Text>- <Text style={styles.unsupportedText}>- This file type cannot be previewed in the app- </Text>- </View>- );- };- const isLoading = documentQuery.isLoading || documentFileQuery.isLoading;- const error = documentQuery.error ?? documentFileQuery.error;- const documentFile = documentFileQuery.data;- const documentName = documentFile?.doc.name ?? 'Document';+ return null;+ };return (<SafeAreaView style={styles.container}>- {renderHeader(documentName)}+ <View style={styles.header}>+ <TouchableOpacity style={styles.headerButton} onPress={() => router.back()}>+ <MaterialCommunityIcons name="close" size={24} color={themeColors.foreground} />+ </TouchableOpacity>+ <Text style={styles.headerTitle} numberOfLines={1}>+ {documentName}+ </Text>+ <TouchableOpacity style={styles.headerButton} onPress={() => setIsActionSheetVisible(true)}>+ <MaterialCommunityIcons name="dots-vertical" size={24} color={themeColors.foreground} />+ </TouchableOpacity>+ </View>+<DocumentActionSheetvisible={isActionSheetVisible}document={documentFile?.doc}onClose={() => setIsActionSheetVisible(false)}excludedActions={['view']}/>- {isLoading- ? (- <View style={styles.loadingContainer}>- <ActivityIndicator size="large" color={themeColors.primary} />- <Text style={styles.loadingText}>Loading document...</Text>- </View>- )- : error != null- ? (- <View style={styles.errorContainer}>- <MaterialCommunityIcons- name="file-pdf-box"- size={64}- color={themeColors.mutedForeground}- />- <Text style={styles.errorText}>Failed to load document</Text>- <TouchableOpacity- style={styles.errorButton}- onPress={() => {- void documentQuery.refetch();- }}- >- <Text style={styles.errorButtonText}>Retry</Text>- </TouchableOpacity>- <TouchableOpacity- style={styles.errorButton}- onPress={() => router.back()}- >- <Text style={styles.errorButtonText}>Go Back</Text>- </TouchableOpacity>- </View>- )- : documentFile != null- ? (- <View style={styles.pdfContainer}>- {renderDocumentFile(documentFile)}- </View>- )- : null}++ {renderContent()}</SafeAreaView>);}@@ -271,11 +269,11 @@ function createStyles({ themeColors }: { themeColors: ThemeColors }) {color: themeColors.foreground,marginHorizontal: 16,},- pdfContainer: {+ documentContainer: {flex: 1,backgroundColor: themeColors.background,},- pdfViewer: {+ documentViewer: {flex: 1,width: '100%',height: '100%',@@ -292,54 +290,32 @@ function createStyles({ themeColors }: { themeColors: ThemeColors }) {lineHeight: 20,color: themeColors.foreground,},- unsupportedContainer: {+ centeredContainer: {flex: 1,justifyContent: 'center',alignItems: 'center',padding: 32,},- unsupportedTitle: {+ centeredTitle: {fontSize: 18,fontWeight: '600',color: themeColors.foreground,marginTop: 16,},- unsupportedText: {+ centeredText: {fontSize: 14,color: themeColors.mutedForeground,marginTop: 8,textAlign: 'center',},- loadingContainer: {- flex: 1,- justifyContent: 'center',- alignItems: 'center',- },- loadingText: {- marginTop: 16,- fontSize: 16,- color: themeColors.mutedForeground,- },- errorContainer: {- flex: 1,- justifyContent: 'center',- alignItems: 'center',- padding: 32,- },- errorText: {- fontSize: 18,- color: themeColors.foreground,- marginTop: 16,- marginBottom: 24,- },- errorButton: {+ actionButton: {paddingHorizontal: 24,paddingVertical: 16,backgroundColor: themeColors.secondaryBackground,borderRadius: 12,marginTop: 16,},- errorButtonText: {+ actionButtonText: {fontSize: 16,fontWeight: '600',color: themeColors.primary,