import React, { useState, useEffect, useCallback } from 'react'; import { View, Text, StyleSheet, FlatList, TouchableOpacity, TextInput, Alert, Modal, ActivityIndicator, BackHandler, Platform, } from 'react-native'; import * as FileSystem from 'expo-file-system/legacy'; import * as DocumentPicker from 'expo-document-picker'; import * as Sharing from 'expo-sharing'; import { useSafeAreaInsets } from 'react-native-safe-area-context'; import { theme, isEditable, getLangColor } from '../theme'; const ROOT = FileSystem.documentDirectory || 'file:///data/user/0/com.chahuadev.codeeditor/files/'; function sortEntries(entries) { return [...entries].sort((a, b) => { if (a.isDirectory !== b.isDirectory) return a.isDirectory ? -1 : 1; return a.name.localeCompare(b.name); }); } function FileIcon({ name, isDirectory, size = 16 }) { if (isDirectory) return πŸ“; const ext = name.split('.').pop().toLowerCase(); const color = getLangColor(name); const icons = { js: '󰌞', ts: '󰛦', py: '🐍', html: '', css: '🎨', json: '{}', md: 'πŸ“', sh: '>', txt: 'πŸ“„', pdf: 'πŸ“•', csv: 'πŸ“Š', xls: 'πŸ“Š', xlsx: 'πŸ“Š' }; const icon = icons[ext] || 'πŸ“„'; return {icon}; } export default function FileExplorerScreen({ navigation }) { const insets = useSafeAreaInsets(); const [currentPath, setCurrentPath] = useState(ROOT || ''); const [pathStack, setPathStack] = useState([]); const [entries, setEntries] = useState([]); const [loading, setLoading] = useState(false); const [renameModal, setRenameModal] = useState(null); const [newNameInput, setNewNameInput] = useState(''); const [newFileModal, setNewFileModal] = useState(false); const [newFileName, setNewFileName] = useState(''); const [newFolderModal, setNewFolderModal] = useState(false); const [newFolderName, setNewFolderName] = useState(''); const [searchQuery, setSearchQuery] = useState(''); const loadDir = useCallback(async (path) => { setLoading(true); try { const items = await FileSystem.readDirectoryAsync(path); const detailed = await Promise.all( items.map(async (name) => { const uri = path + name; try { const info = await FileSystem.getInfoAsync(uri); return { name, uri, isDirectory: info.isDirectory, size: info.size || 0 }; } catch { return { name, uri, isDirectory: false, size: 0 }; } }) ); setEntries(sortEntries(detailed)); } catch (e) { Alert.alert('Error', 'Could not read directory: ' + e.message); } finally { setLoading(false); } }, []); useEffect(() => { loadDir(currentPath); }, [currentPath, loadDir]); // Hardware back button useEffect(() => { const handler = BackHandler.addEventListener('hardwareBackPress', () => { if (pathStack.length > 0) { const prev = pathStack[pathStack.length - 1]; setPathStack(s => s.slice(0, -1)); setCurrentPath(prev); return true; } return false; }); return () => handler.remove(); }, [pathStack]); function openEntry(entry) { if (entry.isDirectory) { setPathStack(s => [...s, currentPath]); setCurrentPath(entry.uri + '/'); } else if (isEditable(entry.name)) { navigation.navigate('Editor', { fileUri: entry.uri, fileName: entry.name }); } else { Alert.alert('Cannot edit', `"${entry.name}" is not a text file.\n\nUse Share to open with another app.`, [ { text: 'Share', onPress: () => Sharing.shareAsync(entry.uri) }, { text: 'OK' }, ]); } } function goUp() { if (pathStack.length > 0) { const prev = pathStack[pathStack.length - 1]; setPathStack(s => s.slice(0, -1)); setCurrentPath(prev); } } async function deleteEntry(entry) { Alert.alert('Delete', `Delete "${entry.name}"?`, [ { text: 'Cancel', style: 'cancel' }, { text: 'Delete', style: 'destructive', onPress: async () => { try { await FileSystem.deleteAsync(entry.uri, { idempotent: true }); loadDir(currentPath); } catch (e) { Alert.alert('Error', e.message); } } } ]); } async function doRename() { if (!newNameInput.trim()) return; const oldUri = renameModal.uri; const newUri = currentPath + newNameInput.trim() + (renameModal.isDirectory ? '/' : ''); try { await FileSystem.moveAsync({ from: oldUri, to: newUri }); setRenameModal(null); loadDir(currentPath); } catch (e) { Alert.alert('Error', e.message); } } async function doCreateFile() { const name = newFileName.trim(); if (!name) return; const uri = currentPath + name; try { await FileSystem.writeAsStringAsync(uri, ''); setNewFileModal(false); setNewFileName(''); loadDir(currentPath); } catch (e) { Alert.alert('Error', e.message); } } async function doCreateFolder() { const name = newFolderName.trim(); if (!name) return; const uri = currentPath + name; try { await FileSystem.makeDirectoryAsync(uri, { intermediates: true }); setNewFolderModal(false); setNewFolderName(''); loadDir(currentPath); } catch (e) { Alert.alert('Error', e.message); } } async function importFile() { try { const result = await DocumentPicker.getDocumentAsync({ copyToCacheDirectory: false }); if (!result.canceled && result.assets?.length > 0) { const asset = result.assets[0]; const dest = currentPath + asset.name; await FileSystem.copyAsync({ from: asset.uri, to: dest }); loadDir(currentPath); } } catch (e) { Alert.alert('Error', e.message); } } const breadcrumb = (() => { if (!currentPath || !ROOT) return '/'; const relative = currentPath.replace(ROOT, ''); return relative ? '/ ' + relative.replace(/\/$/, '') : '/'; })(); const filtered = searchQuery ? entries.filter(e => e.name.toLowerCase().includes(searchQuery.toLowerCase())) : entries; function formatSize(bytes) { if (!bytes) return ''; if (bytes < 1024) return bytes + ' B'; if (bytes < 1024 * 1024) return (bytes / 1024).toFixed(1) + ' KB'; return (bytes / (1024 * 1024)).toFixed(1) + ' MB'; } return ( {/* Header */} Files Import setNewFolderModal(true)}> + Folder setNewFileModal(true)}> + File {/* Breadcrumb */} {pathStack.length > 0 && ( β€Ή )} {breadcrumb} {/* Search */} {/* File List */} {loading ? ( ) : filtered.length === 0 ? ( {searchQuery ? 'No matches' : 'Empty folder'} Tap "+ File" to create a new file ) : ( item.uri} contentContainerStyle={{ paddingBottom: insets.bottom + 16 }} renderItem={({ item }) => ( openEntry(item)} onLongPress={() => { Alert.alert(item.name, null, [ { text: 'Rename', onPress: () => { setNewNameInput(item.name); setRenameModal(item); } }, { text: 'Share', onPress: () => Sharing.shareAsync(item.uri) }, { text: 'Delete', style: 'destructive', onPress: () => deleteEntry(item) }, { text: 'Cancel', style: 'cancel' }, ]); }} > {item.name} {!item.isDirectory && item.size > 0 && ( {formatSize(item.size)} )} {item.isDirectory ? 'β€Ί' : isEditable(item.name) ? '✎' : 'β†—'} )} /> )} {/* Rename Modal */} Rename setRenameModal(null)}> Cancel Rename {/* New File Modal */} New File { setNewFileModal(false); setNewFileName(''); }}> Cancel Create {/* New Folder Modal */} New Folder { setNewFolderModal(false); setNewFolderName(''); }}> Cancel Create ); } const styles = StyleSheet.create({ container: { flex: 1, backgroundColor: theme.colors.bg }, header: { backgroundColor: theme.colors.surface, paddingHorizontal: 16, paddingBottom: 10, borderBottomWidth: 1, borderBottomColor: theme.colors.border }, headerTop: { flexDirection: 'row', alignItems: 'center', justifyContent: 'space-between', paddingTop: 12, paddingBottom: 6 }, title: { color: theme.colors.text, fontSize: 20, fontWeight: '800' }, headerActions: { flexDirection: 'row', gap: 8 }, actionBtn: { paddingHorizontal: 10, paddingVertical: 6, borderRadius: 8, borderWidth: 1, borderColor: theme.colors.border }, actionBtnAccent: { backgroundColor: theme.colors.accent, borderColor: theme.colors.accent }, actionBtnText: { color: theme.colors.text, fontSize: 12, fontWeight: '700' }, breadcrumbRow: { flexDirection: 'row', alignItems: 'center', gap: 8, marginBottom: 8 }, backBtn: { padding: 4 }, backBtnText: { color: theme.colors.accent, fontSize: 22, lineHeight: 24 }, breadcrumb: { color: theme.colors.textMuted, fontSize: 12, flex: 1 }, searchInput: { backgroundColor: theme.colors.surface2, color: theme.colors.text, borderRadius: 8, paddingHorizontal: 12, paddingVertical: 8, fontSize: 14 }, loadingWrap: { flex: 1, alignItems: 'center', justifyContent: 'center' }, emptyWrap: { flex: 1, alignItems: 'center', justifyContent: 'center', gap: 8 }, emptyText: { color: theme.colors.textMuted, fontSize: 16 }, emptyHint: { color: theme.colors.textMuted, fontSize: 12 }, entryRow: { flexDirection: 'row', alignItems: 'center', paddingHorizontal: 16, paddingVertical: 13, borderBottomWidth: 1, borderBottomColor: theme.colors.border + '55', gap: 12 }, fileIcon: { width: 24, textAlign: 'center' }, entryInfo: { flex: 1 }, entryName: { color: theme.colors.text, fontSize: 14, fontWeight: '600' }, entryMeta: { color: theme.colors.textMuted, fontSize: 11, marginTop: 1 }, entryArrow: { color: theme.colors.textMuted, fontSize: 16 }, modalOverlay: { flex: 1, backgroundColor: '#000000aa', alignItems: 'center', justifyContent: 'center' }, modalBox: { backgroundColor: theme.colors.surface, borderRadius: 14, padding: 20, width: 280, gap: 12, borderWidth: 1, borderColor: theme.colors.border }, modalTitle: { color: theme.colors.text, fontSize: 16, fontWeight: '800' }, modalInput: { backgroundColor: theme.colors.surface2, color: theme.colors.text, borderRadius: 8, paddingHorizontal: 12, paddingVertical: 10, fontSize: 14 }, modalRow: { flexDirection: 'row', justifyContent: 'flex-end', gap: 10 }, modalBtn: { paddingHorizontal: 14, paddingVertical: 8, borderRadius: 8, borderWidth: 1, borderColor: theme.colors.border }, modalBtnAccent: { backgroundColor: theme.colors.accent, borderColor: theme.colors.accent }, modalBtnText: { color: theme.colors.text, fontSize: 13, fontWeight: '700' }, });