Spaces:
No application file
No application file
File size: 15,036 Bytes
f6113db | 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 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 | import React, { useState, useRef, useMemo, useCallback } from 'react';
import {
StyleSheet,
View,
Text,
TextInput,
TouchableOpacity,
TouchableWithoutFeedback,
Keyboard,
Dimensions,
Platform,
} from 'react-native';
import { MaterialIcons, Ionicons, FontAwesome } from '@expo/vector-icons';
import BottomSheet, { BottomSheetView, BottomSheetBackdrop } from '@gorhom/bottom-sheet';
// --- Configuration & Language Data ---
const PRIMARY_BLUE = '#1A73E8'; // Google's primary blue
const ACCENT_COLOR = '#4B5563'; // Gray for icons
const BG_OFF_WHITE = '#F8F9FA'; // Standard Google light background
const languageList = [
{ code: 'en', label: 'English', isOfflineReady: true },
{ code: 'ceb', label: 'Cebuano', isOfflineReady: false }, // Initially false, changes after download
{ code: 'tl', label: 'Tagalog (Filipino)', isOfflineReady: true },
{ code: 'es', label: 'Spanish', isOfflineReady: true },
{ code: 'ko', label: 'Korean', isOfflineReady: true },
];
const screenWidth = Dimensions.get('window').width;
// --- Custom Hook for Translation Logic & Native Bridging ---
const useTranslationEngine = () => {
const [sourceLang, setSourceLang] = useState(languageList[0].code);
const [targetLang, setTargetLang] = useState(languageList[1].code);
const [inputText, setInputText] = useState('');
const [outputText, setOutputText] = useState('');
const [isTranslating, setIsTranslating] = useState(false);
const [offlineStatus, setOfflineStatus] = useState(
languageList.reduce((acc, lang) => ({ ...acc, [lang.code]: lang.isOfflineReady }), {})
);
// [PLACEHOLDER] for actual translation.
// This function simulates the ML Kit native call.
// Replace this with the actual ML Kit bridge call (e.g., using @react-native-ml-kit/translate)
const performTranslation = useCallback(async (text, src, tgt) => {
if (!text || src === tgt) {
setOutputText('');
return;
}
setIsTranslating(true);
console.log(`[ML Kit Simulate] Translating '${text}' from ${src} to ${tgt}`);
// Simulation: Simulating a 500ms neural network inference time.
await new Promise((resolve) => setTimeout(resolve, 500));
// Simple simulation logic (you will replace this with your real model result)
if (text.toLowerCase() === 'dog' && src === 'en' && tgt === 'ceb') {
setOutputText('iro');
} else {
setOutputText(`${tgt.toUpperCase()}_MOCK: ${text}`);
}
setIsTranslating(false);
}, []);
// [PLACEHOLDER] for downloading offline models.
const downloadModel = useCallback(async (langCode) => {
console.log(`[ML Kit Simulate] Downloading model for: ${langCode}`);
// Simulate a download delay.
await new Promise((resolve) => setTimeout(resolve, 3000));
setOfflineStatus((prev) => ({ ...prev, [langCode]: true }));
console.log(`[ML Kit Simulate] Download complete for: ${langCode}`);
}, []);
const swapLanguages = useCallback(() => {
const oldSource = sourceLang;
setSourceLang(targetLang);
setTargetLang(oldSource);
setInputText(outputText);
// Translation will trigger in useEffect.
}, [sourceLang, targetLang, outputText]);
// Handle translation triggering.
React.useEffect(() => {
performTranslation(inputText, sourceLang, targetLang);
}, [inputText, sourceLang, targetLang, performTranslation]);
// Initial check or setup for offline models (simulate)
React.useEffect(() => {
const checkModels = async () => {
// You might check if models are already on disk here.
// We simulate Cebuano needing a download.
if (!offlineStatus[targetLang]) {
await downloadModel(targetLang);
}
};
checkModels();
}, [targetLang, offlineStatus, downloadModel]);
return {
sourceLang,
setSourceLang,
targetLang,
setTargetLang,
inputText,
setInputText,
outputText,
isTranslating,
swapLanguages,
offlineStatus,
};
};
// --- Reusable Sub-Components for the UI ---
const HeaderPill = ({ lang, isOfflineReady, onPress, side }) => (
<TouchableOpacity
style={[styles.headerPill, side === 'right' ? { marginRight: 2 } : { marginLeft: 2 }]}
onPress={onPress}
activeOpacity={0.7}
>
<View style={styles.headerPillContent}>
<Text style={[styles.headerPillText, { color: PRIMARY_BLUE }]}>
{languageList.find((l) => l.code === lang).label}
</Text>
<MaterialIcons name="arrow-drop-down" size={24} color={PRIMARY_BLUE} />
{isOfflineReady && (
<Ionicons name="checkmark-done-circle" size={16} color={PRIMARY_BLUE} style={{ marginLeft: -4 }} />
)}
</View>
</TouchableOpacity>
);
const IconButton = ({ name, type = 'Ionicons', size = 24, color = ACCENT_COLOR, onPress, style }) => {
const IconComponent = type === 'Ionicons' ? Ionicons : type === 'MaterialIcons' ? MaterialIcons : FontAwesome;
return (
<TouchableOpacity onPress={onPress} style={[styles.iconButton, style]}>
<IconComponent name={name} size={size} color={color} />
</TouchableOpacity>
);
};
// --- Main Screen Component ---
const CebuanoTranslatorScreen = () => {
const {
sourceLang,
setSourceLang,
targetLang,
setTargetLang,
inputText,
setInputText,
outputText,
isTranslating,
swapLanguages,
offlineStatus,
} = useTranslationEngine();
// Bottom Sheet state
const bottomSheetRef = useRef(null);
const [selectingMode, setSelectingMode] = useState(null); // 'source' or 'target'
const snapPoints = useMemo(() => ['50%', '80%'], []);
const openLanguageSelector = (mode) => {
setSelectingMode(mode);
bottomSheetRef.current?.expand();
};
const handleLanguageSelect = (langCode) => {
if (selectingMode === 'source') {
setSourceLang(langCode);
} else {
setTargetLang(langCode);
}
bottomSheetRef.current?.close();
};
// Speaker and mic actions [PLACEHOLDERS]
const handleSpeak = (text) => {
if (!text) return;
console.log(`[TTS Placeholder] Speaking: "${text}" in ${selectingMode === 'source' ? sourceLang : targetLang}`);
// Replace with Text-to-Speech library (like expo-speech)
};
const handleMicPress = () => {
console.log('[STT Placeholder] Listening...');
// Replace with Speech-to-Text library (like @react-native-voice/voice)
};
const renderBackdrop = useCallback(
(props) => (
<BottomSheetBackdrop {...props} disappearsOnIndex={-1} appearsOnIndex={0} opacity={0.5} />
),
[]
);
return (
<TouchableWithoutFeedback onPress={Keyboard.dismiss}>
<View style={styles.container}>
{/* --- Language Selector Header --- */}
<View style={styles.header}>
<HeaderPill
lang={sourceLang}
isOfflineReady={offlineStatus[sourceLang]}
onPress={() => openLanguageSelector('source')}
side="left"
/>
<IconButton name="swap-horizontal" type="MaterialIcons" onPress={swapLanguages} style={styles.swapIcon} />
<HeaderPill
lang={targetLang}
isOfflineReady={offlineStatus[targetLang]}
onPress={() => openLanguageSelector('target')}
side="right"
/>
</View>
{/* --- Translation Input and Output Cards --- */}
<View style={styles.cardsContainer}>
{/* Top Card (Input/Source) */}
<View style={[styles.card, styles.topCard, Platform.OS === 'android' ? styles.cardAndroidShadow : null]}>
<TextInput
style={styles.textInput}
multiline
placeholder="Enter text..."
placeholderTextColor="#999"
value={inputText}
onChangeText={setInputText}
textAlignVertical="top"
maxLength={1000}
/>
{inputText.length > 0 && (
<IconButton
name="close"
size={22}
onPress={() => setInputText('')}
style={styles.clearIcon}
/>
)}
{/* Input Bottom Actions (Volume, Mic) */}
<View style={styles.cardBottomActions}>
<IconButton name="volume-medium-outline" onPress={() => handleSpeak(inputText)} />
<IconButton name="mic" size={30} onPress={handleMicPress} />
<View style={styles.countContainer}>
<Text style={styles.countText}>{inputText.length}/1000</Text>
</View>
</View>
</View>
{/* Bottom Card (Output/Target) */}
<View style={[styles.card, styles.bottomCard, Platform.OS === 'android' ? styles.cardAndroidShadow : null]}>
{isTranslating ? (
<Text style={[styles.translatedText, { color: '#999' }]}>Translating...</Text>
) : (
<Text style={styles.translatedText} selectable>
{outputText}
</Text>
)}
{/* Output Bottom Actions (Volume, Copy) */}
<View style={styles.cardBottomActions}>
<IconButton name="volume-medium-outline" onPress={() => handleSpeak(outputText)} />
<IconButton name="content-copy" type="MaterialIcons" onPress={() => {}} />
</View>
</View>
</View>
{/* --- Bottom Sheet for Language Selection --- */}
<BottomSheet
ref={bottomSheetRef}
index={-1}
snapPoints={snapPoints}
enablePanDownToClose
backdropComponent={renderBackdrop}
backgroundStyle={styles.sheetBackground}
handleIndicatorStyle={{ backgroundColor: '#ccc' }}
>
<BottomSheetView style={styles.sheetContent}>
<Text style={styles.sheetHeader}>
{selectingMode === 'source' ? 'Translate From' : 'Translate To'}
</Text>
{languageList.map((lang) => (
<TouchableOpacity
key={lang.code}
style={styles.sheetItem}
onPress={() => handleLanguageSelect(lang.code)}
>
<Text
style={[
styles.sheetItemText,
(selectingMode === 'source' ? lang.code === sourceLang : lang.code === targetLang) && {
color: PRIMARY_BLUE,
fontFamily: Platform.OS === 'ios' ? 'System' : 'sans-serif-medium',
},
]}
>
{lang.label}
</Text>
{(selectingMode === 'source' ? lang.code === sourceLang : lang.code === targetLang) && (
<MaterialIcons name="check" size={24} color={PRIMARY_BLUE} />
)}
{offlineStatus[lang.code] && (
<Ionicons name="checkmark-done-circle" size={18} color="#ccc" style={{ marginLeft: 8 }} />
)}
</TouchableOpacity>
))
}
</BottomSheetView>
</BottomSheet>
</View>
</TouchableWithoutFeedback>
);
};
// --- Full Stylesheet matching the provided UI/ux images ---
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: BG_OFF_WHITE,
paddingTop: Platform.OS === 'ios' ? 60 : 20, // Adjust for top notches
},
header: {
flexDirection: 'row',
justifyContent: 'space-between',
alignItems: 'center',
backgroundColor: 'white',
paddingVertical: 12,
paddingHorizontal: 16,
borderBottomWidth: 1,
borderBottomColor: '#EBEBEB',
...Platform.select({
ios: {
shadowColor: 'black',
shadowOffset: { width: 0, height: 2 },
shadowOpacity: 0.05,
shadowRadius: 3,
},
android: {
elevation: 2,
},
}),
},
headerPill: {
backgroundColor: 'rgba(26, 115, 232, 0.06)', // Subtly tinted blue
borderRadius: 20,
paddingHorizontal: 16,
paddingVertical: 8,
minWidth: 120,
alignItems: 'center',
},
headerPillContent: {
flexDirection: 'row',
alignItems: 'center',
},
headerPillText: {
fontFamily: Platform.OS === 'ios' ? 'System' : 'sans-serif-medium',
fontSize: 16,
fontWeight: '500',
color: '#000',
},
swapIcon: {
marginHorizontal: 12,
backgroundColor: 'transparent',
padding: 8,
},
cardsContainer: {
flex: 1,
padding: 16,
},
card: {
backgroundColor: 'white',
borderRadius: 16,
...Platform.select({
ios: {
shadowColor: '#000',
shadowOffset: { width: 0, height: 3 },
shadowOpacity: 0.08,
shadowRadius: 5,
},
}),
},
cardAndroidShadow: {
elevation: 3,
},
topCard: {
marginBottom: 12,
flex: 3, // More space for input
padding: 16,
},
bottomCard: {
flex: 2, // Less space for output
padding: 16,
backgroundColor: BG_OFF_WHITE, // Matched the gray output box in the image
},
textInput: {
flex: 1,
fontSize: 26, // Large font matching the image
lineHeight: 32,
color: '#000',
paddingBottom: 40, // Space for bottom actions
},
translatedText: {
flex: 1,
fontSize: 26,
lineHeight: 32,
color: '#000',
},
clearIcon: {
position: 'absolute',
top: 10,
right: 10,
padding: 6,
backgroundColor: 'white',
borderRadius: 20,
},
cardBottomActions: {
position: 'absolute',
bottom: 12,
left: 12,
right: 12,
flexDirection: 'row',
justifyContent: 'space-between',
alignItems: 'center',
},
countContainer: {
backgroundColor: 'rgba(0,0,0,0.03)',
borderRadius: 12,
paddingHorizontal: 8,
paddingVertical: 4,
},
countText: {
color: '#aaa',
fontSize: 12,
},
iconButton: {
padding: 10,
borderRadius: 25,
backgroundColor: 'transparent',
},
// Bottom Sheet Styles
sheetBackground: {
borderTopLeftRadius: 30,
borderTopRightRadius: 30,
backgroundColor: 'white',
},
sheetContent: {
padding: 24,
paddingBottom: 40,
},
sheetHeader: {
fontSize: 20,
fontWeight: '700',
marginBottom: 20,
color: ACCENT_COLOR,
fontFamily: Platform.OS === 'ios' ? 'System' : 'sans-serif-medium',
},
sheetItem: {
flexDirection: 'row',
justifyContent: 'space-between',
alignItems: 'center',
paddingVertical: 16,
borderBottomWidth: 1,
borderBottomColor: '#f0f0f0',
},
sheetItemText: {
fontSize: 18,
color: '#333',
},
});
export default CebuanoTranslatorScreen; |