chahuadev
chore: sync latest local updates
f68c02e
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: '-->' }, { 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 (
<KeyboardAvoidingView
style={[styles.container, { paddingTop: insets.top }]}
behavior={Platform.OS === 'ios' ? 'padding' : undefined}
>
{/* ── Top bar ── */}
<View style={[styles.topBar, compact && styles.topBarCompact]}>
<TouchableOpacity style={styles.backBtn} onPress={handleBack}>
<Text style={[styles.backBtnText, compact && { fontSize: 22 }]}>β€Ή</Text>
</TouchableOpacity>
<View style={styles.fileInfo}>
<Text style={[styles.fileName, compact && { fontSize: 12 }]} numberOfLines={1}>{fileName}</Text>
<Text style={styles.langBadge}>{langLabel}</Text>
{isDirty && <View style={styles.dirtyDot} />}
</View>
{/* Status inline */}
<Text style={styles.statusInline}>
{cursor.line}:{cursor.col}{cursor.sel > 0 ? ` [${cursor.sel}]` : ''}
</Text>
<TouchableOpacity
style={[styles.saveBtn, isDirty && styles.saveBtnActive]}
onPress={() => doSave(false)}
disabled={!isDirty || saving}
>
{saving
? <ActivityIndicator size="small" color={theme.colors.bg} />
: <Text style={[styles.saveBtnText, isDirty && styles.saveBtnTextActive]}>Save</Text>}
</TouchableOpacity>
</View>
{/* ── Main area: left sidebar + editor ── */}
<View style={styles.mainArea}>
{/* LEFT SIDEBAR ── vertical toolbar */}
<View style={styles.leftSidebar}>
<ScrollView
showsVerticalScrollIndicator={false}
keyboardShouldPersistTaps="always"
contentContainerStyle={styles.sidebarContent}
>
<SBtn label="↩" onPress={() => sendCommand('undo')} />
<SBtn label="β†ͺ" onPress={() => sendCommand('redo')} />
<SSep />
<SBtn label={nativeMode ? 'RN' : 'WEB'} active={!nativeMode} onPress={toggleEditorMode} />
<SSep />
<SBtn label="βŒ•" onPress={() => runEditorAction('find')} />
<SBtn label="fmt" onPress={() => runEditorAction('format')} />
<SBtn label="⌨" active={kbdVisible}
onPress={() => kbdVisible ? Keyboard.dismiss() : runEditorAction('focusKeyboard')} />
<SSep />
<SBtn label="dup" onPress={() => runEditorAction('duplicateLine')} />
<SBtn label="//" onPress={() => runEditorAction('toggleComment')} />
<SBtn label="↑" onPress={() => runEditorAction('lineUp')} />
<SBtn label="↓" onPress={() => runEditorAction('lineDown')} />
<SSep />
<SBtn label="A-" onPress={() => runEditorAction('fontSize', { delta: -1 })} />
<SBtn label={`${fontSize}`} disabled />
<SBtn label="A+" onPress={() => runEditorAction('fontSize', { delta: 1 })} />
<SSep />
<SBtn label="β‡Œ" active={wordWrap} onPress={() => runEditorAction('toggleWordWrap')} />
<SSep />
<SBtn label="↑↑" onPress={() => Sharing.shareAsync(fileUri)} />
</ScrollView>
</View>
{/* EDITOR */}
<View style={styles.editorWrap}>
{!editorReady && (
<View style={styles.editorLoading}>
<ActivityIndicator size="large" color={theme.colors.accent} />
<Text style={styles.editorLoadingText}>Loading Monaco…</Text>
</View>
)}
{nativeMode ? (
<TextInput
ref={nativeInputRef}
style={[styles.nativeInput, { fontSize }]}
multiline
value={nativeContent}
onChangeText={(t) => {
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}
/>
) : (
<WebView
ref={webviewRef}
source={MONACO_HTML}
style={styles.webview}
onMessage={onMessage}
javaScriptEnabled
domStorageEnabled
originWhitelist={['*']}
mixedContentMode="always"
allowFileAccess
allowUniversalAccessFromFileURLs
scalesPageToFit={false}
textZoom={100}
overScrollMode="never"
nestedScrollEnabled={true}
keyboardDisplayRequiresUserAction={false}
hideKeyboardAccessoryView={true}
showsVerticalScrollIndicator={false}
showsHorizontalScrollIndicator={false}
onError={(e) => Alert.alert('WebView Error', e.nativeEvent.description)}
/>
)}
</View>
</View>
{/* ── Symbols bar β€” sits flush above keyboard ── */}
<View style={[styles.snippetBar, { paddingBottom: insets.bottom }]}>
<TouchableOpacity style={styles.snippetToggleRow} onPress={() => setSnippetOpen(o => !o)}>
<Text style={styles.snippetToggleLabel}>
{snippetOpen ? 'β–Ύ Symbols' : 'β–Έ Symbols'}
</Text>
<Text style={styles.snippetToggleHint}>
{snippetOpen ? 'hide' : 'show'}
</Text>
</TouchableOpacity>
{snippetOpen && (
<ScrollView
horizontal
showsHorizontalScrollIndicator={false}
keyboardShouldPersistTaps="always"
contentContainerStyle={styles.snippetScroll}
>
{SNIPPETS.map((s, i) =>
s.sep
? <View key={`sp${i}`} style={styles.snippetSep} />
: (
<TouchableOpacity
key={`${s.t}${i}`}
style={[styles.snippetBtn, { height: snipH }]}
onPress={() => runEditorAction('insertText', { text: s.t })}
>
<Text style={[styles.snippetBtnText, { fontSize: snipFs }]}>{s.t}</Text>
</TouchableOpacity>
)
)}
</ScrollView>
)}
</View>
</KeyboardAvoidingView>
);
}
// ── Sub-components ────────────────────────────────────────────────────────────
function SBtn({ label, onPress, active, disabled }) {
return (
<TouchableOpacity
style={[styles.sideBtn, active && styles.sideBtnActive]}
onPress={onPress}
disabled={disabled}
activeOpacity={0.65}
>
<Text style={[styles.sideBtnText, active && styles.sideBtnTextActive, disabled && styles.sideBtnDim]}>
{label}
</Text>
</TouchableOpacity>
);
}
function SSep() { return <View style={styles.sidebarSep} />; }
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 },
});