display folders

This commit is contained in:
m
2026-07-29 21:58:52 +02:00
parent 3c7a1d18da
commit 470474011d
15 changed files with 961 additions and 496 deletions
+2
View File
@@ -10,6 +10,7 @@ import { AuthProvider, useAuth } from './contexts/AuthContext';
import { DeviceProvider, useDevice } from './contexts/DeviceContext';
import { SseProvider } from './contexts/SseContext';
import { SseOcrListener } from './hooks/usePollOcr';
import { SseResourceListener } from './hooks/useSSEResource';
import { registerBackgroundUpload } from './services/backgroundUpload';
import { LoginScreen } from './app/login';
import { RegisterScreen } from './app/register';
@@ -114,6 +115,7 @@ function AppContent() {
<AuthProvider>
<SseProvider>
<SseOcrListener />
<SseResourceListener />
<DeviceProvider>
<AppNavigator />
<StatusBar style="auto" />
+2 -1
View File
@@ -47,7 +47,8 @@
],
"expo-image",
"expo-sqlite",
"expo-background-task"
"expo-background-task",
"expo-status-bar"
]
}
}
+199 -16
View File
@@ -1,9 +1,14 @@
import React, { useMemo, useState, useCallback, useEffect } from 'react';
import { View, FlatList, StyleSheet, TouchableOpacity, Text, Dimensions, Alert } from 'react-native';
import { View, FlatList, StyleSheet, TouchableOpacity, Text, Dimensions, Alert, Modal, TextInput } from 'react-native';
import { useRoute, useNavigation, RouteProp } from '@react-navigation/native';
import { NativeStackNavigationProp } from '@react-navigation/native-stack';
import { MaterialIcons } from '@expo/vector-icons';
import { useDeleteFile, useFiles, useFreeLocalSpace } from '../hooks/useFiles';
import { useSafeAreaInsets } from 'react-native-safe-area-context';
import {
useDeleteFile, useFiles, useFreeLocalSpace,
useAddTags, useMoveResources, useFolders, useCreateFolder,
} from '../hooks/useFiles';
import { SelectionPanel } from '../components/SelectionPanel';
import { UnifiedFileItem } from '../types';
import { isFolder } from '../types';
import { FileThumbnail } from '../components/FileThumbnail';
@@ -21,6 +26,7 @@ const ITEM_SIZE = (SCREEN_WIDTH - 16 * 2 - (NUM_COLUMNS - 1) * 6) / NUM_COLUMNS;
type RootStackParamList = {
Folder: { folderId: string; folderName: string };
FileDetail: { fileIds: string[]; initialIndex: number };
FileEdit: { fileIds: string[] };
};
type NavigationProp = NativeStackNavigationProp<RootStackParamList>;
@@ -51,6 +57,7 @@ function FolderGridItem({ file, onPress, onLongPress, selected, onFolderPress }:
fileName={file.name}
size={ITEM_SIZE}
syncStatus={file.syncStatus}
isFolder={file.isFolder}
/>
{selected && (
<View style={styles.selectedOverlay}>
@@ -74,6 +81,17 @@ export function FolderScreen() {
const queryClient = useQueryClient();
const [selectedIds, setSelectedIds] = useState<Set<string>>(new Set());
const addTags = useAddTags();
const moveFiles = useMoveResources();
const createFolder = useCreateFolder();
const { data: foldersData } = useFolders();
const insets = useSafeAreaInsets();
const [tagModalVisible, setTagModalVisible] = useState(false);
const [tagModalMode, setTagModalMode] = useState<'tag' | 'folder'>('tag');
const [tagInput, setTagInput] = useState('');
const [moveModalVisible, setMoveModalVisible] = useState(false);
const selectionMode = selectedIds.size > 0;
useEffect(() => {
@@ -153,6 +171,50 @@ export function FolderScreen() {
Alert.alert('Supprimer', `Supprimer ${label} ?`, options);
}, [selectedIds, files, deleteFile, freeLocalSpace, queryClient]);
const handleEdit = useCallback(() => {
const ids = Array.from(selectedIds);
if (ids.length === 0) return;
navigation.navigate('FileEdit', { fileIds: ids });
setSelectedIds(new Set());
}, [selectedIds, navigation]);
const openTagModal = useCallback((mode: 'tag' | 'folder') => {
setTagModalMode(mode);
setTagInput('');
setTagModalVisible(true);
}, []);
const handleAddTag = useCallback(async () => {
const name = tagInput.trim();
if (!name) return;
const ids = Array.from(selectedIds);
for (const id of ids) {
await addTags.mutateAsync({ fileId: id, tags: [name] });
}
setTagModalVisible(false);
setSelectedIds(new Set());
}, [tagInput, selectedIds, addTags]);
const handleCreateFolderFromModal = useCallback(async () => {
const name = tagInput.trim();
if (!name) return;
const ids = Array.from(selectedIds);
try {
const newFolder = await createFolder.mutateAsync(name);
await moveFiles.mutateAsync({ resourceIds: ids, parentResourceId: newFolder.id });
setTagModalVisible(false);
setSelectedIds(new Set());
navigation.navigate('Folder', { folderId: newFolder.id, folderName: newFolder.name });
} catch {}
}, [tagInput, selectedIds, createFolder, moveFiles, navigation]);
const handleMove = useCallback(async (folderId: string | null) => {
const ids = Array.from(selectedIds);
await moveFiles.mutateAsync({ resourceIds: ids, parentResourceId: folderId });
setMoveModalVisible(false);
setSelectedIds(new Set());
}, [selectedIds, moveFiles]);
const handleItemPress = useCallback((file: UnifiedFileItem) => {
if (selectionMode) {
toggleSelection(file.id);
@@ -202,21 +264,74 @@ export function FolderScreen() {
/>
{selectionMode && (
<View style={styles.selectionBar}>
<View style={styles.selectionHeader}>
<TouchableOpacity onPress={clearSelection} style={styles.cancelBtn}>
<MaterialIcons name="close" size={22} color="#333" />
</TouchableOpacity>
<Text style={styles.selectionCount}>
{selectedIds.size} sélectionnée{selectedIds.size > 1 ? 's' : ''}
</Text>
</View>
<TouchableOpacity style={styles.deleteBtn} onPress={handleDelete}>
<MaterialIcons name="delete" size={20} color="#F44336" />
<Text style={styles.deleteText}>Supprimer</Text>
</TouchableOpacity>
</View>
<SelectionPanel
selectedCount={selectedIds.size}
onClose={clearSelection}
onDelete={handleDelete}
onEdit={handleEdit}
onTags={() => openTagModal('tag')}
onFolder={() => openTagModal('folder')}
onMove={() => setMoveModalVisible(true)}
insetsBottom={insets.bottom}
/>
)}
<Modal visible={tagModalVisible} transparent animationType="fade" onRequestClose={() => setTagModalVisible(false)}>
<TouchableOpacity style={styles.modalOverlay} activeOpacity={1} onPress={() => setTagModalVisible(false)}>
<TouchableOpacity activeOpacity={1} style={styles.modalContent} onPress={() => {}}>
<Text style={styles.modalTitle}>
{tagModalMode === 'folder' ? 'Créer un dossier' : 'Ajouter un tag'}
</Text>
<TextInput
style={styles.modalInput}
placeholder={tagModalMode === 'folder' ? 'Nom du dossier...' : 'Nom du tag...'}
placeholderTextColor="#999"
value={tagInput}
onChangeText={setTagInput}
autoFocus
returnKeyType="done"
onSubmitEditing={tagModalMode === 'folder' ? handleCreateFolderFromModal : handleAddTag}
/>
<View style={styles.modalActions}>
<TouchableOpacity style={styles.modalCancelBtn} onPress={() => setTagModalVisible(false)}>
<Text style={styles.modalCancelText}>Annuler</Text>
</TouchableOpacity>
<TouchableOpacity
style={[styles.modalConfirmBtn, !tagInput.trim() && styles.modalConfirmDisabled]}
onPress={tagModalMode === 'folder' ? handleCreateFolderFromModal : handleAddTag}
disabled={!tagInput.trim()}
>
<Text style={styles.modalConfirmText}>{tagModalMode === 'folder' ? 'Créer' : 'Ajouter'}</Text>
</TouchableOpacity>
</View>
</TouchableOpacity>
</TouchableOpacity>
</Modal>
<Modal visible={moveModalVisible} transparent animationType="fade" onRequestClose={() => setMoveModalVisible(false)}>
<TouchableOpacity style={styles.modalOverlay} activeOpacity={1} onPress={() => setMoveModalVisible(false)}>
<TouchableOpacity activeOpacity={1} style={styles.modalContent} onPress={() => {}}>
<Text style={styles.modalTitle}>Déplacer vers...</Text>
<TouchableOpacity
style={styles.folderOption}
onPress={() => handleMove(null)}
>
<MaterialIcons name="home" size={20} color="#666" />
<Text style={styles.folderOptionText}>Racine</Text>
</TouchableOpacity>
{(foldersData ?? []).map((folder) => (
<TouchableOpacity
key={folder.id}
style={styles.folderOption}
onPress={() => handleMove(folder.id)}
>
<MaterialIcons name="folder" size={20} color="#F57C00" />
<Text style={styles.folderOptionText}>{folder.name}</Text>
</TouchableOpacity>
))}
</TouchableOpacity>
</TouchableOpacity>
</Modal>
</View>
);
}
@@ -313,4 +428,72 @@ const styles = StyleSheet.create({
fontWeight: '600',
color: '#F44336',
},
modalOverlay: {
flex: 1,
backgroundColor: 'rgba(0,0,0,0.4)',
justifyContent: 'center',
alignItems: 'center',
},
modalContent: {
backgroundColor: '#fff',
borderRadius: 12,
padding: 20,
width: '80%',
},
modalTitle: {
fontSize: 18,
fontWeight: '700',
color: '#333',
marginBottom: 16,
},
modalInput: {
borderWidth: 1,
borderColor: '#ddd',
borderRadius: 8,
paddingHorizontal: 12,
paddingVertical: 10,
fontSize: 16,
color: '#333',
marginBottom: 16,
},
modalActions: {
flexDirection: 'row',
justifyContent: 'flex-end',
gap: 12,
},
modalCancelBtn: {
paddingHorizontal: 16,
paddingVertical: 8,
},
modalCancelText: {
fontSize: 15,
color: '#666',
},
modalConfirmBtn: {
paddingHorizontal: 16,
paddingVertical: 8,
backgroundColor: '#1976D2',
borderRadius: 8,
},
modalConfirmDisabled: {
backgroundColor: '#ccc',
},
modalConfirmText: {
fontSize: 15,
color: '#fff',
fontWeight: '600',
},
folderOption: {
flexDirection: 'row',
alignItems: 'center',
paddingVertical: 12,
paddingHorizontal: 8,
gap: 10,
borderBottomWidth: 1,
borderBottomColor: '#f0f0f0',
},
folderOptionText: {
fontSize: 16,
color: '#333',
},
});
+31 -72
View File
@@ -1,12 +1,13 @@
import React, { useState, useMemo, useEffect, useCallback, useRef } from 'react';
import { View, FlatList, StyleSheet, TouchableOpacity, Text, Dimensions, KeyboardAvoidingView, Platform, Keyboard, Alert, Modal, TextInput, ScrollView, RefreshControl, ActivityIndicator } from 'react-native';
import { View, FlatList, StyleSheet, TouchableOpacity, Text, Dimensions, KeyboardAvoidingView, Platform, Keyboard, Alert, Modal, TextInput, ActivityIndicator } from 'react-native';
import { useNavigation } from '@react-navigation/native';
import { useSafeAreaInsets } from 'react-native-safe-area-context';
import { NativeStackNavigationProp } from '@react-navigation/native-stack';
import { MaterialIcons } from '@expo/vector-icons';
import { Gesture, GestureDetector } from 'react-native-gesture-handler';
import Animated, { runOnJS, useSharedValue, useAnimatedStyle, withSpring } from 'react-native-reanimated';
import { useAddTags, useMoveResources, useFolders, useFiles, useFreeLocalSpace } from '../hooks/useFiles';
import { useAddTags, useMoveResources, useFolders, useFiles, useFreeLocalSpace, useCreateFolder } from '../hooks/useFiles';
import { SelectionPanel } from '../components/SelectionPanel';
import { UnifiedFileItem, isFolder } from '../types';
import { SearchBar, SearchFilters, MediaFilter } from '../components/SearchBar';
import { FileThumbnail } from '../components/FileThumbnail';
@@ -64,6 +65,7 @@ const FileGridItem = React.memo(function FileGridItem({ file, size, onPress, onL
fileName={file.name}
size={size}
syncStatus={file.syncStatus}
isFolder={file.isFolder}
/>
{selected && (
<View style={styles.selectedOverlay}>
@@ -110,6 +112,7 @@ export function HomeScreen() {
const [tagInput, setTagInput] = useState('');
const addTags = useAddTags();
const moveFiles = useMoveResources();
const createFolder = useCreateFolder();
const { data: foldersData } = useFolders();
const [moveModalVisible, setMoveModalVisible] = useState(false);
const [settingsModalVisible, setSettingsModalVisible] = useState(false);
@@ -136,11 +139,6 @@ export function HomeScreen() {
}
}, [isFetching, data?.meta?.total, data?.data?.length]);
const onRefresh = useCallback(() => {
setPage(1);
refetch();
}, [refetch]);
const totalFiles = data?.meta?.total ?? 0;
const loadedFiles = data?.data?.length ?? 0;
const hasMore = loadedFiles > 0 && loadedFiles < totalFiles;
@@ -313,7 +311,20 @@ export function HomeScreen() {
}
setTagModalVisible(false);
setSelectedIds(new Set());
}, [tagInput, selectedIds, tagModalMode, addTags]);
}, [tagInput, selectedIds, addTags]);
const handleCreateFolderFromModal = useCallback(async () => {
const name = tagInput.trim();
if (!name) return;
const ids = Array.from(selectedIds);
try {
const newFolder = await createFolder.mutateAsync(name);
await moveFiles.mutateAsync({ resourceIds: ids, parentResourceId: newFolder.id });
setTagModalVisible(false);
setSelectedIds(new Set());
navigation.navigate('Folder', { folderId: newFolder.id, folderName: newFolder.name });
} catch {}
}, [tagInput, selectedIds, createFolder, moveFiles, navigation]);
const handleMove = useCallback(async (folderId: string | null) => {
const ids = Array.from(selectedIds);
@@ -492,14 +503,6 @@ export function HomeScreen() {
contentContainerStyle={styles.list}
keyboardShouldPersistTaps="handled"
keyboardDismissMode="on-drag"
refreshControl={
<RefreshControl
refreshing={isFetching && page === 1}
onRefresh={onRefresh}
tintColor="#1976D2"
colors={['#1976D2']}
/>
}
onEndReached={loadMore}
onEndReachedThreshold={0.5}
ListFooterComponent={
@@ -543,60 +546,16 @@ export function HomeScreen() {
)}
{selectionMode ? (
<View style={[styles.selectionBar, { paddingBottom: insets.bottom + 8 }]}>
<View style={styles.selectionHeader}>
<TouchableOpacity onPress={clearSelection} style={styles.cancelBtn}>
<MaterialIcons name="close" size={22} color="#333" />
</TouchableOpacity>
<Text style={styles.selectionCount}>
{selectedIds.size} sélectionnée{selectedIds.size > 1 ? 's' : ''}
</Text>
<TouchableOpacity onPress={clearSelection} style={styles.selectAllBtn}>
<Text style={styles.selectAllText}>Tout</Text>
</TouchableOpacity>
</View>
<ScrollView
horizontal
showsHorizontalScrollIndicator={false}
contentContainerStyle={styles.selectionActions}
>
<TouchableOpacity
style={[styles.selectionChip, styles.deleteChip]}
onPress={handleDelete}
>
<MaterialIcons name="delete" size={18} color="#E53935" />
<Text style={[styles.chipText, { color: '#E53935' }]}>Supprimer</Text>
</TouchableOpacity>
<TouchableOpacity
style={[styles.selectionChip, styles.editChip]}
onPress={handleEdit}
>
<MaterialIcons name="edit" size={18} color="#1E88E5" />
<Text style={[styles.chipText, { color: '#1E88E5' }]}>Éditer</Text>
</TouchableOpacity>
<TouchableOpacity
style={[styles.selectionChip, styles.tagChip]}
onPress={() => openTagModal('tag')}
>
<MaterialIcons name="label" size={18} color="#8E24AA" />
<Text style={[styles.chipText, { color: '#8E24AA' }]}>Tags</Text>
</TouchableOpacity>
<TouchableOpacity
style={[styles.selectionChip, styles.folderChip]}
onPress={() => openTagModal('folder')}
>
<MaterialIcons name="create-new-folder" size={18} color="#F57C00" />
<Text style={[styles.chipText, { color: '#F57C00' }]}>Folder</Text>
</TouchableOpacity>
<TouchableOpacity
style={[styles.selectionChip, styles.moveChip]}
onPress={() => setMoveModalVisible(true)}
>
<MaterialIcons name="drive-file-move" size={18} color="#00897B" />
<Text style={[styles.chipText, { color: '#00897B' }]}>Déplacer</Text>
</TouchableOpacity>
</ScrollView>
</View>
<SelectionPanel
selectedCount={selectedIds.size}
onClose={clearSelection}
onDelete={handleDelete}
onEdit={handleEdit}
onTags={() => openTagModal('tag')}
onFolder={() => openTagModal('folder')}
onMove={() => setMoveModalVisible(true)}
insetsBottom={insets.bottom}
/>
) : (
<View style={styles.bottomNav}>
<TouchableOpacity style={styles.navButton} onPress={() => {}}>
@@ -636,10 +595,10 @@ export function HomeScreen() {
</TouchableOpacity>
<TouchableOpacity
style={[styles.modalConfirmBtn, !tagInput.trim() && styles.modalConfirmDisabled]}
onPress={handleAddTag}
onPress={tagModalMode === 'folder' ? handleCreateFolderFromModal : handleAddTag}
disabled={!tagInput.trim()}
>
<Text style={styles.modalConfirmText}>Ajouter</Text>
<Text style={styles.modalConfirmText}>{tagModalMode === 'folder' ? 'Créer' : 'Ajouter'}</Text>
</TouchableOpacity>
</View>
</TouchableOpacity>
+10 -1
View File
@@ -39,12 +39,21 @@ interface FileThumbnailProps {
size: number;
isLoading?: boolean;
syncStatus?: SyncStatus;
isFolder?: boolean;
}
export const FileThumbnail = React.memo(function FileThumbnail({ uri, thumbnailUrl, mimeType, fileName, size, isLoading, syncStatus }: FileThumbnailProps) {
export const FileThumbnail = React.memo(function FileThumbnail({ uri, thumbnailUrl, mimeType, fileName, size, isLoading, syncStatus, isFolder }: FileThumbnailProps) {
const info = getFileInfo(mimeType, fileName);
const ext = getExtension(fileName);
if (isFolder) {
return (
<View style={[styles.container, { width: size, height: size, backgroundColor: '#FFF3E0' }]}>
<MaterialIcons name="folder" size={size * 0.45} color="#F57C00" />
</View>
);
}
if (isLoading) {
return (
<View style={[styles.container, { width: size, height: size, backgroundColor: info.bg }]}>
+205
View File
@@ -0,0 +1,205 @@
import React, { useCallback } from 'react';
import { View, Text, StyleSheet, TouchableOpacity } from 'react-native';
import { MaterialIcons } from '@expo/vector-icons';
import { Gesture, GestureDetector } from 'react-native-gesture-handler';
import Animated, { useSharedValue, useAnimatedStyle, withSpring, runOnJS } from 'react-native-reanimated';
const PANEL_HEIGHT = 300;
const PANEL_HEADER_VISIBLE = 80;
interface SelectionPanelProps {
selectedCount: number;
onClose: () => void;
onDelete?: () => void;
onEdit?: () => void;
onTags?: () => void;
onFolder?: () => void;
onMove?: () => void;
insetsBottom: number;
}
export function SelectionPanel({
selectedCount,
onClose,
onDelete,
onEdit,
onTags,
onFolder,
onMove,
insetsBottom,
}: SelectionPanelProps) {
const panelOffset = useSharedValue(PANEL_HEIGHT - PANEL_HEADER_VISIBLE);
const panelStartY = useSharedValue(0);
const isPanelExpanded = useSharedValue(false);
const [panelExpanded, setPanelExpanded] = React.useState(false);
const togglePanelJS = useCallback(() => {
if (isPanelExpanded.value) {
panelOffset.value = withSpring(PANEL_HEIGHT - PANEL_HEADER_VISIBLE);
isPanelExpanded.value = false;
setPanelExpanded(false);
} else {
panelOffset.value = withSpring(0);
isPanelExpanded.value = true;
setPanelExpanded(true);
}
}, []);
const panGesture = Gesture.Pan()
.onStart(() => {
panelStartY.value = panelOffset.value;
})
.onUpdate((event) => {
const offset = Math.max(0, Math.min(PANEL_HEIGHT - PANEL_HEADER_VISIBLE, panelStartY.value + event.translationY));
panelOffset.value = offset;
})
.onEnd(() => {
if (panelOffset.value > (PANEL_HEIGHT - PANEL_HEADER_VISIBLE) / 2) {
panelOffset.value = withSpring(PANEL_HEIGHT - PANEL_HEADER_VISIBLE);
isPanelExpanded.value = false;
runOnJS(setPanelExpanded)(false);
} else {
panelOffset.value = withSpring(0);
isPanelExpanded.value = true;
runOnJS(setPanelExpanded)(true);
}
});
const panelAnimatedStyle = useAnimatedStyle(() => ({
transform: [{ translateY: panelOffset.value }],
}));
return (
<GestureDetector gesture={panGesture}>
<Animated.View style={[styles.panel, { paddingBottom: insetsBottom + 12 }, panelAnimatedStyle]}>
<TouchableOpacity onPress={togglePanelJS} activeOpacity={0.7}>
<View style={styles.panelHandle} />
<View style={styles.panelHeader}>
<TouchableOpacity onPress={onClose} style={styles.closeBtn} hitSlop={8}>
<MaterialIcons name="close" size={22} color="#333" />
</TouchableOpacity>
<Text style={styles.selectionCount}>
{selectedCount} sélectionnée{selectedCount > 1 ? 's' : ''}
</Text>
<TouchableOpacity onPress={onClose} style={styles.selectAllBtn}>
<Text style={styles.selectAllText}>Tout</Text>
</TouchableOpacity>
</View>
</TouchableOpacity>
<View style={styles.panelBody}>
<View style={styles.actionsGrid}>
{onDelete && (
<TouchableOpacity style={[styles.actionBtn, styles.deleteBtn]} onPress={onDelete}>
<MaterialIcons name="delete" size={22} color="#E53935" />
<Text style={[styles.actionLabel, { color: '#E53935' }]}>Supprimer</Text>
</TouchableOpacity>
)}
{onEdit && (
<TouchableOpacity style={[styles.actionBtn, styles.editBtn]} onPress={onEdit}>
<MaterialIcons name="edit" size={22} color="#1E88E5" />
<Text style={[styles.actionLabel, { color: '#1E88E5' }]}>Éditer</Text>
</TouchableOpacity>
)}
{onTags && (
<TouchableOpacity style={[styles.actionBtn, styles.tagBtn]} onPress={onTags}>
<MaterialIcons name="label" size={22} color="#8E24AA" />
<Text style={[styles.actionLabel, { color: '#8E24AA' }]}>Tags</Text>
</TouchableOpacity>
)}
{onFolder && (
<TouchableOpacity style={[styles.actionBtn, styles.folderBtn]} onPress={onFolder}>
<MaterialIcons name="create-new-folder" size={22} color="#F57C00" />
<Text style={[styles.actionLabel, { color: '#F57C00' }]}>Dossier</Text>
</TouchableOpacity>
)}
{onMove && (
<TouchableOpacity style={[styles.actionBtn, styles.moveBtn]} onPress={onMove}>
<MaterialIcons name="drive-file-move" size={22} color="#00897B" />
<Text style={[styles.actionLabel, { color: '#00897B' }]}>Déplacer</Text>
</TouchableOpacity>
)}
</View>
</View>
</Animated.View>
</GestureDetector>
);
}
const styles = StyleSheet.create({
panel: {
position: 'absolute',
bottom: 0,
left: 0,
right: 0,
backgroundColor: '#fff',
borderTopLeftRadius: 20,
borderTopRightRadius: 20,
paddingHorizontal: 20,
paddingTop: 12,
height: PANEL_HEIGHT,
shadowColor: '#000',
shadowOffset: { width: 0, height: -2 },
shadowOpacity: 0.1,
shadowRadius: 8,
elevation: 10,
},
panelHandle: {
width: 36,
height: 4,
borderRadius: 2,
backgroundColor: '#ddd',
alignSelf: 'center',
marginBottom: 12,
},
panelHeader: {
flexDirection: 'row',
alignItems: 'center',
justifyContent: 'space-between',
marginBottom: 16,
},
closeBtn: {
padding: 4,
},
selectionCount: {
fontSize: 16,
fontWeight: '700',
color: '#333',
},
selectAllBtn: {
paddingHorizontal: 8,
paddingVertical: 4,
},
selectAllText: {
fontSize: 14,
color: '#1976D2',
fontWeight: '600',
},
panelBody: {
flex: 1,
},
actionsGrid: {
flexDirection: 'row',
flexWrap: 'wrap',
gap: 10,
},
actionBtn: {
width: '47%',
flexDirection: 'row',
alignItems: 'center',
justifyContent: 'center',
gap: 10,
paddingVertical: 14,
borderRadius: 12,
backgroundColor: '#f5f5f5',
},
actionLabel: {
fontSize: 15,
fontWeight: '600',
},
deleteBtn: {},
editBtn: {},
tagBtn: {},
folderBtn: {},
moveBtn: {},
});
+26 -5
View File
@@ -3,18 +3,22 @@ import { apiClient } from '../api/client';
import { useAuth } from './AuthContext';
type OcrDoneCallback = (resourceId: string) => void;
type ResourceCreatedCallback = (resourceId: string) => void;
interface SseContextValue {
onOcrDone: (cb: OcrDoneCallback) => () => void;
onResourceCreated: (cb: ResourceCreatedCallback) => () => void;
}
const SseContext = createContext<SseContextValue>({
onOcrDone: () => () => {},
onResourceCreated: () => () => {},
});
export function SseProvider({ children }: { children: React.ReactNode }) {
const { user } = useAuth();
const listenersRef = useRef<Set<OcrDoneCallback>>(new Set());
const ocrListenersRef = useRef<Set<OcrDoneCallback>>(new Set());
const resourceListenersRef = useRef<Set<ResourceCreatedCallback>>(new Set());
const cancelRef = useRef<() => void>(() => {});
const reconnectTimeoutRef = useRef<ReturnType<typeof setTimeout> | undefined>(undefined);
@@ -28,7 +32,9 @@ export function SseProvider({ children }: { children: React.ReactNode }) {
const cancel = await apiClient.subscribeEvents(
(event, data) => {
if (event === 'ocr_done') {
listenersRef.current.forEach((cb) => cb(data));
ocrListenersRef.current.forEach((cb) => cb(data));
} else if (event === 'resource.created') {
resourceListenersRef.current.forEach((cb) => cb(data));
}
},
() => {
@@ -62,14 +68,21 @@ export function SseProvider({ children }: { children: React.ReactNode }) {
}, [connect]);
const onOcrDone = useCallback((cb: OcrDoneCallback) => {
listenersRef.current.add(cb);
ocrListenersRef.current.add(cb);
return () => {
listenersRef.current.delete(cb);
ocrListenersRef.current.delete(cb);
};
}, []);
const onResourceCreated = useCallback((cb: ResourceCreatedCallback) => {
resourceListenersRef.current.add(cb);
return () => {
resourceListenersRef.current.delete(cb);
};
}, []);
return (
<SseContext.Provider value={{ onOcrDone }}>
<SseContext.Provider value={{ onOcrDone, onResourceCreated }}>
{children}
</SseContext.Provider>
);
@@ -82,3 +95,11 @@ export function useOcrDone(onDone?: OcrDoneCallback) {
}, [onDone, ctx]);
return { onOcrDone: ctx.onOcrDone };
}
export function useResourceCreated(onCreated?: ResourceCreatedCallback) {
const ctx = useContext(SseContext);
useEffect(() => {
if (onCreated) return ctx.onResourceCreated(onCreated);
}, [onCreated, ctx]);
return { onResourceCreated: ctx.onResourceCreated };
}
+31 -5
View File
@@ -101,11 +101,19 @@ export function useFiles(parentId?: string | null, page: number = 1, limit: numb
},
placeholderData: keepPreviousData,
initialData: () => {
const cached = fileStore.getRootFiles();
if (cached.files.length === 0) return undefined;
if (!parentId) {
const cached = fileStore.getRootFiles();
if (cached.files.length === 0) return undefined;
return {
data: cached.files.map((r) => recordToUnifiedItem(r)!).filter(Boolean),
meta: { page: 0, total: cached.total },
};
}
const children = fileStore.getChildrenByParent(parentId);
if (children.length === 0) return undefined;
return {
data: cached.files.map((r) => recordToUnifiedItem(r)!).filter(Boolean),
meta: { page: 0, total: cached.total },
data: children.map((r) => recordToUnifiedItem(r)!).filter(Boolean),
meta: { page: 0, total: children.length },
};
},
staleTime: 30_000,
@@ -115,7 +123,10 @@ export function useFiles(parentId?: string | null, page: number = 1, limit: numb
export function useFile(id: string) {
return useQuery({
queryKey: ['resources', id],
queryFn: () => apiClient.get<FileItem>(`${ENDPOINTS.RESOURCES}/${id}?thumbnail=thumbnail_small`),
queryFn: async () => {
const res = await apiClient.get<{ data: FileItem }>(`${ENDPOINTS.RESOURCES}/${id}?thumbnail=thumbnail_small`);
return res.data;
},
enabled: !!id,
});
}
@@ -190,6 +201,21 @@ export function useFolders() {
});
}
export function useCreateFolder() {
const queryClient = useQueryClient();
return useMutation({
mutationFn: async (name: string) => {
const res = await apiClient.post<{ data: FileItem }>(ENDPOINTS.FOLDERS, { name });
return res.data;
},
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: ['resources'] });
queryClient.invalidateQueries({ queryKey: ['folders'] });
},
});
}
export function useFilesByParent(parentId: string) {
return useFiles(parentId);
}
+17
View File
@@ -0,0 +1,17 @@
import { useEffect } from 'react';
import { useQueryClient } from '@tanstack/react-query';
import { useResourceCreated } from '../contexts/SseContext';
export function SseResourceListener() {
const queryClient = useQueryClient();
const { onResourceCreated } = useResourceCreated();
useEffect(() => {
const unsub = onResourceCreated(() => {
queryClient.invalidateQueries({ queryKey: ['resources'] });
});
return unsub;
}, [onResourceCreated, queryClient]);
return null;
}
+7
View File
@@ -0,0 +1,7 @@
// Learn more https://docs.expo.io/guides/customizing-metro
const { getDefaultConfig } = require('expo/metro-config');
/** @type {import('expo/metro-config').MetroConfig} */
const config = getDefaultConfig(__dirname);
module.exports = config;
+411 -382
View File
File diff suppressed because it is too large Load Diff
+10 -8
View File
@@ -10,18 +10,19 @@
"@tanstack/query-async-storage-persister": "^5.101.4",
"@tanstack/react-query": "^5.101.2",
"@tanstack/react-query-persist-client": "^5.101.4",
"babel-preset-expo": "^57.0.4",
"drizzle-orm": "^0.45.2",
"expo": "~57.0.4",
"expo": "~57.0.8",
"expo-background-task": "~57.0.6",
"expo-document-picker": "~57.0.0",
"expo-file-system": "~57.0.0",
"expo-document-picker": "~57.0.1",
"expo-file-system": "~57.0.1",
"expo-image": "~57.0.1",
"expo-image-picker": "~57.0.2",
"expo-image-picker": "~57.0.6",
"expo-media-library": "~57.0.3",
"expo-print": "~57.0.0",
"expo-secure-store": "~57.0.0",
"expo-print": "~57.0.1",
"expo-secure-store": "~57.0.1",
"expo-sqlite": "~57.0.1",
"expo-status-bar": "~57.0.0",
"expo-status-bar": "~57.0.1",
"expo-task-manager": "~57.0.6",
"react": "19.2.3",
"react-native": "0.86.0",
@@ -31,11 +32,12 @@
"react-native-nitro-modules": "^0.36.1",
"react-native-reanimated": "4.5.0",
"react-native-safe-area-context": "~5.7.0",
"react-native-screens": "4.25.2",
"react-native-screens": "~4.26.0",
"react-native-vision-camera": "^5.1.0",
"react-native-worklets": "0.10.0"
},
"devDependencies": {
"@expo/metro-config": "^57.0.7",
"@types/react": "~19.2.2",
"drizzle-kit": "^0.31.10",
"typescript": "~6.0.3"
+6 -6
View File
@@ -308,12 +308,12 @@ export const fileStore = {
const d = getDb();
const countRow = d.select({ count: sql<number>`count(*)` })
.from(files)
.where(and(isNull(files.parentResourceId), eq(files.isFolder, 0)))
.where(isNull(files.parentResourceId))
.get();
const total = countRow?.count ?? 0;
const rows = d.select().from(files)
.where(and(isNull(files.parentResourceId), eq(files.isFolder, 0)))
.orderBy(desc(files.createdAt))
.where(isNull(files.parentResourceId))
.orderBy(desc(files.isFolder), desc(files.createdAt))
.all() as FileRow[];
return {
files: rows.map((r) => rowToRecord(r, getTagsForFile(r.id))),
@@ -327,13 +327,13 @@ export const fileStore = {
const countRow = d.select({ count: sql<number>`count(*)` })
.from(files)
.where(and(isNull(files.parentResourceId), eq(files.isFolder, 0)))
.where(isNull(files.parentResourceId))
.get();
const total = countRow?.count ?? 0;
const rows = d.select().from(files)
.where(and(isNull(files.parentResourceId), eq(files.isFolder, 0)))
.orderBy(desc(files.createdAt))
.where(isNull(files.parentResourceId))
.orderBy(desc(files.isFolder), desc(files.createdAt))
.limit(limit)
.offset(offset)
.all() as FileRow[];