import React, { useRef, useState, useEffect, useCallback } from 'react'; import { View, Text, StyleSheet, TouchableOpacity, TextInput, Alert, ActivityIndicator, KeyboardAvoidingView, Platform, ScrollView, useWindowDimensions, BackHandler, Keyboard, } from 'react-native'; import { WebView } from 'react-native-webview'; import * as FileSystem from 'expo-file-system/legacy'; import * as Sharing from 'expo-sharing'; import { useSafeAreaInsets } from 'react-native-safe-area-context'; import { theme, getLanguage } from '../theme'; const MONACO_HTML = require('../../assets/monaco.html'); // ── Snippet bar data ───────────────────────────────────────────────────────── // Covers: JS/TS, Python, HTML, CSS, Java, Kotlin, C/C++, Rust, Go, Swift, PHP, Ruby, SQL, Shell … const SNIPPETS = [ // cursor navigation { t: '←', tip: 'cursor ←' }, { t: '→', tip: 'cursor →' }, { t: '⇥', tip: 'Indent' }, { t: '⇤', tip: 'Dedent' }, { sep: true }, // brackets { t: '(' }, { t: ')' }, { t: '{' }, { t: '}' }, { t: '[' }, { t: ']' }, { t: '<' }, { t: '>' }, { sep: true }, // punctuation { t: ';' }, { t: ':' }, { t: ',' }, { t: '.' }, { t: '!' }, { t: '?' }, { t: '@' }, { t: '#' }, { sep: true }, // assignment / compare { t: '=' }, { t: '=>' }, { t: '==' }, { t: '===' }, { t: '!=' }, { t: '!==' }, { t: '>=' }, { t: '<=' }, { sep: true }, // string / template { t: '"' }, { t: "'" }, { t: '`' }, { t: '\\' }, { sep: true }, // arithmetic / bitwise { t: '+' }, { t: '-' }, { t: '*' }, { t: '/' }, { t: '%' }, { t: '**' }, { t: '&' }, { t: '|' }, { t: '^' }, { t: '~' }, { t: '<<' }, { t: '>>' }, { sep: true }, // logical / nullish { t: '&&' }, { t: '||' }, { t: '??' }, { t: '?.' }, { sep: true }, // compound assign { t: '+=' }, { t: '-=' }, { t: '*=' }, { t: '/=' }, { t: '%=' }, { t: '**=' }, { t: '&&=' }, { t: '||=' }, { sep: true }, // comment { t: '//' }, { t: '/*' }, { t: '*/' }, { t: '' }, { t: '#!' }, { sep: true }, // misc { t: '_' }, { t: '$' }, { t: '...' }, { t: '::' }, { t: '->' }, { t: '<-' }, { t: '|>' }, { t: '::=' }, ]; export default function EditorScreen({ route, navigation }) { const { width, height } = useWindowDimensions(); const isLandscape = width > height; const insets = useSafeAreaInsets(); const { fileUri, fileName } = route.params; const webviewRef = useRef(null); const nativeInputRef = useRef(null); const saveGoBackRef = useRef(false); const syncToNativeRef = useRef(false); const [editorReady, setEditorReady] = useState(false); const [isDirty, setIsDirty] = useState(false); const [saving, setSaving] = useState(false); const [fontSize, setFontSize] = useState(15); const [wordWrap, setWordWrap] = useState(false); const [snippetOpen, setSnippetOpen] = useState(true); const [cursor, setCursor] = useState({ line: 1, col: 1, sel: 0 }); const [kbdVisible, setKbdVisible] = useState(false); const [nativeMode, setNativeMode] = useState(Platform.OS === 'android'); const [nativeContent, setNativeContent] = useState(''); const [nativeSel, setNativeSel] = useState({ start: 0, end: 0 }); useEffect(() => { const show = Keyboard.addListener('keyboardDidShow', () => setKbdVisible(true)); const hide = Keyboard.addListener('keyboardDidHide', () => setKbdVisible(false)); return () => { show.remove(); hide.remove(); }; }, []); const loadFile = useCallback(async () => { try { const content = await FileSystem.readAsStringAsync(fileUri, { encoding: FileSystem.EncodingType.UTF8 }); setNativeContent(content); sendCommand('setContent', { content, language: getLanguage(fileName) }); } catch (e) { Alert.alert('Error reading file', e.message); } }, [fileUri, fileName]); useEffect(() => { if (editorReady) loadFile(); }, [editorReady, loadFile]); useEffect(() => { const h = BackHandler.addEventListener('hardwareBackPress', () => { handleBack(); return true; }); return () => h.remove(); }, [isDirty]); function sendCommand(type, extra = {}) { if (!webviewRef.current) return; const msg = JSON.stringify({ type, ...extra }); webviewRef.current.injectJavaScript( `(function(){document.dispatchEvent(new MessageEvent('message',{data:${JSON.stringify(msg)}}));})();true;` ); } function handleBack() { if (isDirty) { Alert.alert('Unsaved changes', 'Save before leaving?', [ { text: 'Discard', style: 'destructive', onPress: () => navigation.goBack() }, { text: 'Save & Exit', onPress: () => doSave(true) }, { text: 'Cancel', style: 'cancel' }, ]); } else { navigation.goBack(); } } function doSave(thenGoBack = false) { saveGoBackRef.current = thenGoBack; setSaving(true); if (nativeMode) writeContent(nativeContent); else sendCommand('getContent'); } async function writeContent(content) { try { await FileSystem.writeAsStringAsync(fileUri, content, { encoding: FileSystem.EncodingType.UTF8 }); setIsDirty(false); sendCommand('markClean'); } catch (e) { Alert.alert('Save failed', e.message); } finally { setSaving(false); if (saveGoBackRef.current) { saveGoBackRef.current = false; navigation.goBack(); } } } function onMessage(event) { try { const msg = JSON.parse(event.nativeEvent.data); if (msg.type === 'ready') setEditorReady(true); else if (msg.type === 'contentChanged') setIsDirty(true); else if (msg.type === 'content') { if (syncToNativeRef.current) { syncToNativeRef.current = false; setNativeContent(msg.content || ''); } else { writeContent(msg.content); } } else if (msg.type === 'fontSizeChanged') setFontSize(msg.size); else if (msg.type === 'wordWrapChanged') setWordWrap(msg.enabled); else if (msg.type === 'cursor') setCursor({ line: msg.line, col: msg.col, sel: msg.sel }); } catch {} } useEffect(() => { if (!editorReady) return; if (!nativeMode) { sendCommand('setContent', { content: nativeContent, language: getLanguage(fileName) }); } }, [nativeMode, editorReady]); function updateNativeCursor(text, start, end) { const upTo = text.slice(0, start); const line = upTo.split('\n').length; const col = start - upTo.lastIndexOf('\n'); setCursor({ line, col, sel: Math.max(0, end - start) }); } function toggleEditorMode() { if (nativeMode) { setNativeMode(false); return; } syncToNativeRef.current = true; sendCommand('getContent'); setNativeMode(true); } function nativeInsertText(t) { const s = nativeSel.start; const e = nativeSel.end; const next = nativeContent.slice(0, s) + t + nativeContent.slice(e); const p = s + t.length; setNativeContent(next); setNativeSel({ start: p, end: p }); setIsDirty(true); updateNativeCursor(next, p, p); requestAnimationFrame(() => nativeInputRef.current?.focus()); } function runEditorAction(type, extra = {}) { if (!nativeMode) { sendCommand(type, extra); return; } if (type === 'focusKeyboard') { nativeInputRef.current?.focus(); return; } if (type === 'insertText') { nativeInsertText(extra.text || ''); return; } if (type === 'fontSize') { const next = Math.max(10, Math.min(32, fontSize + (extra.delta || 0))); setFontSize(next); return; } if (type === 'toggleWordWrap') return; } const langLabel = getLanguage(fileName).toUpperCase(); const compact = isLandscape; const snipH = compact ? 30 : 36; const snipFs = compact ? 11 : 13; return ( {/* ── Top bar ── */} {fileName} {langLabel} {isDirty && } {/* Status inline */} {cursor.line}:{cursor.col}{cursor.sel > 0 ? ` [${cursor.sel}]` : ''} doSave(false)} disabled={!isDirty || saving} > {saving ? : Save} {/* ── Main area: left sidebar + editor ── */} {/* LEFT SIDEBAR ── vertical toolbar */} sendCommand('undo')} /> sendCommand('redo')} /> runEditorAction('find')} /> runEditorAction('format')} /> kbdVisible ? Keyboard.dismiss() : runEditorAction('focusKeyboard')} /> runEditorAction('duplicateLine')} /> runEditorAction('toggleComment')} /> runEditorAction('lineUp')} /> runEditorAction('lineDown')} /> runEditorAction('fontSize', { delta: -1 })} /> runEditorAction('fontSize', { delta: 1 })} /> runEditorAction('toggleWordWrap')} /> Sharing.shareAsync(fileUri)} /> {/* EDITOR */} {!editorReady && ( Loading Monaco… )} {nativeMode ? ( { setNativeContent(t); setIsDirty(true); }} onSelectionChange={(e) => { const s = e.nativeEvent.selection.start; const en = e.nativeEvent.selection.end; setNativeSel({ start: s, end: en }); updateNativeCursor(nativeContent, s, en); }} autoCorrect={false} autoCapitalize="none" spellCheck={false} keyboardAppearance="dark" textAlignVertical="top" selectionColor={theme.colors.accent} placeholder="Native editor mode (stable keyboard)" placeholderTextColor={theme.colors.textMuted} /> ) : ( Alert.alert('WebView Error', e.nativeEvent.description)} /> )} {/* ── Symbols bar — sits flush above keyboard ── */} setSnippetOpen(o => !o)}> {snippetOpen ? '▾ Symbols' : '▸ Symbols'} {snippetOpen ? 'hide' : 'show'} {snippetOpen && ( {SNIPPETS.map((s, i) => s.sep ? : ( runEditorAction('insertText', { text: s.t })} > {s.t} ) )} )} ); } // ── Sub-components ──────────────────────────────────────────────────────────── function SBtn({ label, onPress, active, disabled }) { return ( {label} ); } function SSep() { return ; } const styles = StyleSheet.create({ container: { flex: 1, backgroundColor: theme.colors.bg }, // top bar topBar: { flexDirection: 'row', alignItems: 'center', gap: 8, paddingHorizontal: 10, paddingVertical: 8, backgroundColor: theme.colors.surface, borderBottomWidth: 1, borderBottomColor: theme.colors.border, }, topBarCompact: { paddingVertical: 5 }, backBtn: { padding: 4 }, backBtnText: { color: theme.colors.accent, fontSize: 26, lineHeight: 28, fontWeight: '300' }, fileInfo: { flex: 1, flexDirection: 'row', alignItems: 'center', gap: 6, overflow: 'hidden' }, fileName: { color: theme.colors.text, fontSize: 13, fontWeight: '700', flexShrink: 1 }, langBadge: { color: theme.colors.textMuted, fontSize: 10, fontWeight: '700', backgroundColor: theme.colors.surface2, paddingHorizontal: 5, paddingVertical: 2, borderRadius: 4, }, dirtyDot: { width: 7, height: 7, borderRadius: 4, backgroundColor: theme.colors.accentOrange }, statusInline: { color: '#6b7280', fontSize: 10, fontFamily: Platform.OS === 'android' ? 'monospace' : 'Courier New', }, saveBtn: { paddingHorizontal: 12, paddingVertical: 6, borderRadius: 8, borderWidth: 1, borderColor: theme.colors.border }, saveBtnActive: { backgroundColor: theme.colors.accent, borderColor: theme.colors.accent }, saveBtnText: { color: theme.colors.textMuted, fontSize: 13, fontWeight: '700' }, saveBtnTextActive: { color: theme.colors.bg }, // main layout mainArea: { flex: 1, flexDirection: 'row' }, // left sidebar leftSidebar: { width: 44, backgroundColor: theme.colors.surface, borderRightWidth: 1, borderRightColor: theme.colors.border, }, sidebarContent: { alignItems: 'center', paddingVertical: 6, gap: 3, }, sideBtn: { width: 36, height: 36, borderRadius: 8, backgroundColor: theme.colors.surface2, alignItems: 'center', justifyContent: 'center', }, sideBtnActive: { backgroundColor: theme.colors.accent }, sideBtnText: { color: theme.colors.text, fontSize: 11, fontWeight: '700' }, sideBtnTextActive: { color: theme.colors.bg }, sideBtnDim: { color: theme.colors.textMuted }, sidebarSep: { width: 24, height: 1, backgroundColor: theme.colors.border, marginVertical: 3, }, // editor editorWrap: { flex: 1, position: 'relative' }, webview: { flex: 1, backgroundColor: theme.colors.bg }, nativeInput: { flex: 1, color: theme.colors.text, backgroundColor: theme.colors.bg, paddingHorizontal: 10, paddingTop: 12, fontFamily: Platform.OS === 'android' ? 'monospace' : 'Courier New', }, editorLoading: { ...StyleSheet.absoluteFillObject, backgroundColor: theme.colors.bg, alignItems: 'center', justifyContent: 'center', zIndex: 10, gap: 12, }, editorLoadingText: { color: theme.colors.textMuted, fontSize: 14 }, // snippet bar — no extra padding, KAV pushes it up flush against keyboard snippetBar: { backgroundColor: theme.colors.surface, borderTopWidth: 1, borderTopColor: theme.colors.border, }, snippetToggleRow: { flexDirection: 'row', alignItems: 'center', justifyContent: 'space-between', paddingHorizontal: 12, paddingVertical: 4, borderBottomWidth: 1, borderBottomColor: theme.colors.border + '60', }, snippetToggleLabel: { color: theme.colors.accent, fontSize: 12, fontWeight: '700' }, snippetToggleHint: { color: theme.colors.textMuted, fontSize: 11 }, snippetScroll: { flexDirection: 'row', alignItems: 'center', paddingHorizontal: 8, gap: 3, paddingVertical: 3 }, snippetBtn: { minWidth: 34, paddingHorizontal: 7, borderRadius: 7, backgroundColor: theme.colors.surface2, alignItems: 'center', justifyContent: 'center', }, snippetBtnText: { color: theme.colors.accentGreen, fontWeight: '700', fontFamily: Platform.OS === 'android' ? 'monospace' : 'Courier New' }, snippetSep: { width: 1, height: 20, backgroundColor: theme.colors.border + '80', marginHorizontal: 3 }, });