File size: 15,979 Bytes
f68c02e | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 | 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' },
});
|