chahuadev-Code-Editor-apk / src /screens /FileExplorerScreen.js
chahuadev
chore: sync latest local updates
f68c02e
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 <Text style={[styles.fileIcon, { color: theme.colors.accentYellow, fontSize: size }]}>📁</Text>;
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 <Text style={[styles.fileIcon, { color, fontSize: size }]}>{icon}</Text>;
}
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 (
<View style={[styles.container, { paddingTop: insets.top }]}>
{/* Header */}
<View style={styles.header}>
<View style={styles.headerTop}>
<Text style={styles.title}>Files</Text>
<View style={styles.headerActions}>
<TouchableOpacity style={styles.actionBtn} onPress={importFile}>
<Text style={styles.actionBtnText}>Import</Text>
</TouchableOpacity>
<TouchableOpacity style={styles.actionBtn} onPress={() => setNewFolderModal(true)}>
<Text style={styles.actionBtnText}>+ Folder</Text>
</TouchableOpacity>
<TouchableOpacity style={[styles.actionBtn, styles.actionBtnAccent]} onPress={() => setNewFileModal(true)}>
<Text style={[styles.actionBtnText, { color: theme.colors.bg }]}>+ File</Text>
</TouchableOpacity>
</View>
</View>
{/* Breadcrumb */}
<View style={styles.breadcrumbRow}>
{pathStack.length > 0 && (
<TouchableOpacity onPress={goUp} style={styles.backBtn}>
<Text style={styles.backBtnText}></Text>
</TouchableOpacity>
)}
<Text style={styles.breadcrumb} numberOfLines={1}>{breadcrumb}</Text>
</View>
{/* Search */}
<TextInput
style={styles.searchInput}
placeholder="Search files…"
placeholderTextColor={theme.colors.textMuted}
value={searchQuery}
onChangeText={setSearchQuery}
/>
</View>
{/* File List */}
{loading ? (
<View style={styles.loadingWrap}>
<ActivityIndicator color={theme.colors.accent} size="large" />
</View>
) : filtered.length === 0 ? (
<View style={styles.emptyWrap}>
<Text style={styles.emptyText}>{searchQuery ? 'No matches' : 'Empty folder'}</Text>
<Text style={styles.emptyHint}>Tap "+ File" to create a new file</Text>
</View>
) : (
<FlatList
data={filtered}
keyExtractor={item => item.uri}
contentContainerStyle={{ paddingBottom: insets.bottom + 16 }}
renderItem={({ item }) => (
<TouchableOpacity
style={styles.entryRow}
onPress={() => 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' },
]);
}}
>
<FileIcon name={item.name} isDirectory={item.isDirectory} size={18} />
<View style={styles.entryInfo}>
<Text style={styles.entryName} numberOfLines={1}>{item.name}</Text>
{!item.isDirectory && item.size > 0 && (
<Text style={styles.entryMeta}>{formatSize(item.size)}</Text>
)}
</View>
<Text style={styles.entryArrow}>{item.isDirectory ? '›' : isEditable(item.name) ? '✎' : '↗'}</Text>
</TouchableOpacity>
)}
/>
)}
{/* Rename Modal */}
<Modal visible={!!renameModal} transparent animationType="fade">
<View style={styles.modalOverlay}>
<View style={styles.modalBox}>
<Text style={styles.modalTitle}>Rename</Text>
<TextInput
style={styles.modalInput}
value={newNameInput}
onChangeText={setNewNameInput}
autoFocus
selectTextOnFocus
/>
<View style={styles.modalRow}>
<TouchableOpacity style={styles.modalBtn} onPress={() => setRenameModal(null)}>
<Text style={styles.modalBtnText}>Cancel</Text>
</TouchableOpacity>
<TouchableOpacity style={[styles.modalBtn, styles.modalBtnAccent]} onPress={doRename}>
<Text style={[styles.modalBtnText, { color: theme.colors.bg }]}>Rename</Text>
</TouchableOpacity>
</View>
</View>
</View>
</Modal>
{/* New File Modal */}
<Modal visible={newFileModal} transparent animationType="fade">
<View style={styles.modalOverlay}>
<View style={styles.modalBox}>
<Text style={styles.modalTitle}>New File</Text>
<TextInput
style={styles.modalInput}
value={newFileName}
onChangeText={setNewFileName}
placeholder="filename.js"
placeholderTextColor={theme.colors.textMuted}
autoFocus
/>
<View style={styles.modalRow}>
<TouchableOpacity style={styles.modalBtn} onPress={() => { setNewFileModal(false); setNewFileName(''); }}>
<Text style={styles.modalBtnText}>Cancel</Text>
</TouchableOpacity>
<TouchableOpacity style={[styles.modalBtn, styles.modalBtnAccent]} onPress={doCreateFile}>
<Text style={[styles.modalBtnText, { color: theme.colors.bg }]}>Create</Text>
</TouchableOpacity>
</View>
</View>
</View>
</Modal>
{/* New Folder Modal */}
<Modal visible={newFolderModal} transparent animationType="fade">
<View style={styles.modalOverlay}>
<View style={styles.modalBox}>
<Text style={styles.modalTitle}>New Folder</Text>
<TextInput
style={styles.modalInput}
value={newFolderName}
onChangeText={setNewFolderName}
placeholder="folder-name"
placeholderTextColor={theme.colors.textMuted}
autoFocus
/>
<View style={styles.modalRow}>
<TouchableOpacity style={styles.modalBtn} onPress={() => { setNewFolderModal(false); setNewFolderName(''); }}>
<Text style={styles.modalBtnText}>Cancel</Text>
</TouchableOpacity>
<TouchableOpacity style={[styles.modalBtn, styles.modalBtnAccent]} onPress={doCreateFolder}>
<Text style={[styles.modalBtnText, { color: theme.colors.bg }]}>Create</Text>
</TouchableOpacity>
</View>
</View>
</View>
</Modal>
</View>
);
}
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' },
});