translation-terrace/components/LanguageSelection.tsx
2025-03-17 06:56:05 -07:00

82 lines
2.7 KiB
TypeScript

import { CachedTranslator, LanguageServer, Translator, language_matrix, language_matrix_entry } from "@/app/i18n/api";
import { LIBRETRANSLATE_BASE_URL } from "@/constants/api";
import { useEffect, useState } from "react";
import ISpeakButton from "./ui/ISpeakButton";
import { LANG_FLAGS } from "@/app/i18n/lang";
import { Pressable, ScrollView, StyleSheet, Text, View } from "react-native";
import { SafeAreaProvider, SafeAreaView } from "react-native-safe-area-context";
import { Conversation, Speaker } from "@/app/lib/conversation";
import { NavigationProp, ParamListBase } from "@react-navigation/native";
import { Link, useNavigation } from "expo-router";
import { migrateDb } from "@/app/lib/db";
export function LanguageSelection(props: {
navigation?: NavigationProp<ParamListBase>
translator?: Translator
onLangSelected?: (lang: language_matrix_entry) => any
}) {
const [languages, setLanguages] = useState<language_matrix | undefined>();
const [languagesLoaded, setLanguagesLoaded] = useState<boolean>(false);
const [translator, setTranslator] = useState<Translator | undefined>();
const nav = useNavigation();
const languageServer = new LanguageServer(LIBRETRANSLATE_BASE_URL);
function onLangSelected(language: language_matrix_entry) {
props.onLangSelected && props.onLangSelected(language)
}
useEffect(() => {
(async () => {
await migrateDb();
try {
// Replace with your actual async data fetching logic
setTranslator(await CachedTranslator.getDefault());
const languageServer = await LanguageServer.getDefault();
const languages = await languageServer.fetchLanguages(10000);
setLanguages(languages);
setLanguagesLoaded(true);
} catch (error) {
console.error('Error fetching languages from %s: %s', languageServer.baseUrl, error);
}
})();
}, []);
return (
<View>
<Pressable onPress={() => nav.navigate('Settings')}>
<Text>Settings</Text>
</Pressable>
<ScrollView >
<SafeAreaProvider>
<SafeAreaView style={styles.table}>
{(languages && languagesLoaded) ? Object.entries(languages).filter((l) => (LANG_FLAGS as any)[l[0]] !== undefined).map(
([lang, lang_entry]) => {
return (
<ISpeakButton language={lang_entry} key={lang_entry.code} onLangSelected={onLangSelected} translator={translator} />
);
}
) : <Text>Waiting...</Text>
}
</SafeAreaView>
</SafeAreaProvider>
</ScrollView>
</View>
)
}
const DEBUG_BORDER = {
borderWidth: 3,
borderStyle: "dotted",
borderColor: "blue",
}
const styles = StyleSheet.create({
table: {
flexDirection: "row",
flexWrap: "wrap",
},
})